From d17e94c84e5801d1e7d1e46f59a0bd72cb4ab374 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Fri, 27 Nov 2026 16:21:42 +0100 Subject: [PATCH 001/123] refactor(mover): the vehicle type is an enum class train_type, not dt_* bit constants --- McZapkie/MOVER.h | 59 +++++++------ McZapkie/Mover.cpp | 147 +++++++++++++++++---------------- application/driveruipanels.cpp | 2 +- tests/unit/drive.cpp | 2 +- tests/unit/golden.cpp | 25 +++++- tests/unit/test_cntrl.cpp | 6 +- vehicle/Driver.cpp | 16 ++-- vehicle/Driver.h | 4 +- vehicle/DynObj.cpp | 14 ++-- vehicle/Train.cpp | 42 +++++----- widgets/vehicleparams.cpp | 2 +- 11 files changed, 175 insertions(+), 144 deletions(-) diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index d5847cbc1..3c4f14b41 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -489,31 +489,33 @@ enum activation neutraldirection = 1 << 7, }; -// szczególne typy pojazdów (inna obsługa) dla zmiennej TrainType -// zamienione na flagi bitowe, aby szybko wybierać grupę (np. EZT+SZT) -// TODO: convert to enums, they're used as specific checks anyway -/// Vehicle type flag: default (no special handling). -static int const dt_Default = 0; -/// Vehicle type flag: EZT (electric multiple unit). -static int const dt_EZT = 1; -/// Vehicle type flag: ET41 locomotive. -static int const dt_ET41 = 2; -/// Vehicle type flag: ET42 locomotive. -static int const dt_ET42 = 4; -/// Vehicle type flag: pseudo-diesel (electric drivetrain with diesel input model). -static int const dt_PseudoDiesel = 8; -/// Vehicle type flag: ET22 locomotive (added in Megapack). -static int const dt_ET22 = 0x10; // używane od Megapacka -/// Vehicle type flag: SN61 (set from CHK only, not used in conditions). -static int const dt_SN61 = 0x20; // nie używane w warunkach, ale ustawiane z CHK -/// Vehicle type flag: EP05 locomotive. -static int const dt_EP05 = 0x40; -/// Vehicle type flag: ET40 locomotive. -static int const dt_ET40 = 0x80; -/// Vehicle type flag: ŠKODA 181 locomotive. -static int const dt_181 = 0x100; -/// Vehicle type flag: DMU (diesel multiple unit). -static int const dt_DMU = 0x200; +/// The vehicles the code handles in a way of their own, by the Type of the Param section of the .fiz +/// (TrainType). A vehicle is of one of them; a .fiz type not listed is generic. +enum class train_type +{ + /// No handling of its own. + generic, + /// Electric multiple unit (Type=EZT). + emu, + /// Diesel multiple unit (Type=DMU). + dmu, + /// ET22 locomotive (Type=ET22, since the Megapack). + et22, + /// ET40 locomotive. + et40, + /// ET41 locomotive. + et41, + /// ET42 locomotive. + et42, + /// EP05 locomotive. + ep05, + /// SN61 railcar: the type is read, but nothing handles it on its own. + sn61, + /// Pseudo-diesel (an electric drivetrain with the input model of a diesel). + pseudodiesel, + /// Škoda 181 and 182 locomotives (Type=181 or 182). + skoda181, +}; // stałe dla asynchronów /// EIM config index: dfic — frequency rise rate at start. @@ -1706,7 +1708,12 @@ class TMoverParameters int CategoryFlag = 1; /*1 - pociag, 2 - samochod, 4 - statek, 8 - samolot*/ /*--sekcja stalych typowych parametrow*/ std::string TypeName; /*nazwa serii/typu*/ - int TrainType = 0; /*typ: EZT/elektrowoz - Winger 040304 Ra: powinno być szybciej niż string*/ + train_type TrainType{train_type::generic}; // the vehicles of a handling of their own, from the Type of the .fiz + // an electric or a diesel multiple unit + bool is_multiple_unit() const + { + return TrainType == train_type::emu || TrainType == train_type::dmu; + } TEngineType EngineType = TEngineType::None; /*typ napedu*/ TPowerParameters EnginePowerSource; /*zrodlo mocy dla silnikow*/ TPowerParameters SystemPowerSource; /*zrodlo mocy dla systemow sterowania/przetwornic/sprezarek*/ diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 7ee85203a..466523d89 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -357,14 +357,14 @@ double TMoverParameters::Current(double n, double U) ResistorsFlag = RList[MainCtrlActualPos].R > 0.01; // and (!DelayCtrlFlag) ResistorsFlag = ResistorsFlag || (DynamicBrakeFlag == true && DynamicBrakeType == dbrake_automatic); - if (TrainType == dt_ET22 && DelayCtrlFlag && MainCtrlActualPos > 1) + if (TrainType == train_type::et22 && DelayCtrlFlag && MainCtrlActualPos > 1) Bn = 1.0 - 1.0 / RList[MainCtrlActualPos].Bn; else Bn = 1; // to jest wykonywane dla EU07 R = RList[MainCtrlActualPos].R * Bn + CircuitRes; - if (TrainType != dt_EZT || Imin != IminLo || false == ScndS) + if (TrainType != train_type::emu || Imin != IminLo || false == ScndS) { // yBARC - boczniki na szeregu poprawnie Mn = RList[MainCtrlActualPos].Mn; // to jest wykonywane dla EU07 @@ -414,7 +414,7 @@ double TMoverParameters::Current(double n, double U) void TMoverParameters::UpdateSeriesMotorDynamicBrakeFlag() { // i dzialanie hamulca ED w EP09 - if (DynamicBrakeType == dbrake_automatic && TrainType != dt_EZT) + if (DynamicBrakeType == dbrake_automatic && TrainType != train_type::emu) { if ((Hamulec->GetEDBCP() < 0.25 && Vadd < 1) || BrakePress > 2.1) DynamicBrakeFlag = false; @@ -422,7 +422,7 @@ void TMoverParameters::UpdateSeriesMotorDynamicBrakeFlag() DynamicBrakeFlag = true; DynamicBrakeFlag = DynamicBrakeFlag && Power110vIsAvailable; } - if (DynamicBrakeType == dbrake_automatic && TrainType == dt_EZT) + if (DynamicBrakeType == dbrake_automatic && TrainType == train_type::emu) { DynamicBrakeFlag = Power110vIsAvailable && (TUHEX_Active || Vadd > TUHEX_MinIw) && DynamicBrakeEMUStatus; } @@ -472,7 +472,7 @@ double TMoverParameters::SeriesMotorCurrent(double const n, double const U, doub MotorCurrent:=(U-Isf*Rz-Mn*fi*n+SQRT(Delta))/(2*Rz) end*/ // only the ET42's switched brake brakes on the starting resistors, otherwise the current is cut off (0) - if (DynamicBrakeType == dbrake_switch && TrainType == dt_ET42) + if (DynamicBrakeType == dbrake_switch && TrainType == train_type::et42) { // z Megapacka Rz = WindingRes + R; MotorCurrent = -motor_param(SP).fi * n / Rz; //{hamowanie silnikiem na oporach rozruchowych} @@ -812,7 +812,7 @@ bool TMoverParameters::DirectionForward() SendCtrlToNext("Direction", DirActive, CabActive); return true; } - else if (DirActive == 1 && IsMainCtrlNoPowerPos() && TrainType == dt_EZT && EngineType != TEngineType::ElectricInductionMotor) + else if (DirActive == 1 && IsMainCtrlNoPowerPos() && TrainType == train_type::emu && EngineType != TEngineType::ElectricInductionMotor) return MinCurrentSwitch(true); //"wysoki rozruch" EN57 return false; }; @@ -916,7 +916,7 @@ bool TMoverParameters::CurrentSwitch(bool const State) if (MaxCurrentSwitch(State)) { - if (TrainType != dt_EZT) + if (TrainType != train_type::emu) { MinCurrentSwitch(State); } @@ -966,7 +966,7 @@ void TMoverParameters::UpdatePantVolume(double dt) // włączona mała sprężarka PantVolume += dt // Ra 2013-12: Niebugocław mówi, że w EZT nabija 1.5 raz wolniej niż jak było 0.005 - * (TrainType == dt_EZT ? 0.003 : 0.005) / std::max(1.0, PantPress) * (0.45 - (0.1 / PantVolume / 10 - 0.1)) / 0.45; + * (TrainType == train_type::emu ? 0.003 : 0.005) / std::max(1.0, PantPress) * (0.45 - (0.1 / PantVolume / 10 - 0.1)) / 0.45; } PantPress = safe_clamp(10.0 * PantVolume - 1.0, 0.0, EnginePowerSource.CollectorParameters.MaxPress); // tu by się przydała objętość zbiornika } @@ -1019,14 +1019,14 @@ void TMoverParameters::PantPressureSwitchCheck() void TMoverParameters::PantPressureSwitchTrip() { // opuszczenie pantografów przy niskim ciśnieniu - if (TrainType != dt_EZT) + if (TrainType != train_type::emu) { // pressure switch safety measure -- open the line breaker, unless there's alternate source of traction voltage // (the genset of a dual-mode vehicle, when the selector is on it, doesn't need the pantographs) if (GetTrainsetHighVoltage() < EnginePowerSource.CollectorParameters.MinV && false == GensetSelected()) { // TODO: check whether line breaker should be open EMU-wide - MainSwitch(false, TrainType == dt_EZT ? range_t::unit : range_t::local); + MainSwitch(false, TrainType == train_type::emu ? range_t::unit : range_t::local); } } else @@ -1597,7 +1597,7 @@ void TMoverParameters::damage_coupler(int const End) collision::vehicle_kind TMoverParameters::collision_kind() const { auto const powered{EngineType != TEngineType::None && EngineType != TEngineType::Dumb}; - auto const unit{(TrainType & (dt_EZT | dt_DMU)) != 0}; + auto const unit{is_multiple_unit()}; auto const passengers{std::any_of(LoadAttributes.begin(), LoadAttributes.end(), [](auto const &Load) { return ToLower(Load.name).starts_with("passenger"); })}; // a coach heats its compartments; the crash zone is a matter of each end (crush_of()) return collision::kind_of(powered, unit || passengers || (false == powered && HeatingPower > 0.0), false); @@ -2487,14 +2487,14 @@ void TMoverParameters::compute_movement_(double const Deltatime) { if (MotorOverloadRelayHighThreshold) { // set high threshold - if (TrainType != dt_ET42 ? RList[MainCtrlPos].Bn < 2 : MainCtrlPos == 0) + if (TrainType != train_type::et42 ? RList[MainCtrlPos].Bn < 2 : MainCtrlPos == 0) { Imax = ImaxHi; } } else { // set low threshold - if (TrainType != dt_ET42 || MainCtrlPos == 0) + if (TrainType != train_type::et42 || MainCtrlPos == 0) { Imax = ImaxLo; } @@ -2660,7 +2660,7 @@ void TMoverParameters::MainsCheck(double const Deltatime) // an emergency brake application made under power opens the line breaker, where the vehicle has such an interlock if (Mains && EmergencyBrakeHoldsMainOff()) { - MainSwitch(false, TrainType == dt_EZT ? range_t::unit : range_t::local); + MainSwitch(false, TrainType == train_type::emu ? range_t::unit : range_t::local); } } @@ -3374,12 +3374,12 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) // nie ma sterowania return false; } - if (TrainType == dt_ET22 && ScndCtrlPos != 0) + if (TrainType == train_type::et22 && ScndCtrlPos != 0) { // w ET22 nie da się kręcić nastawnikiem przy włączonym boczniku return false; } - if (TrainType == dt_EZT && DirActive == 0) + if (TrainType == train_type::emu && DirActive == 0) { // w EZT nie da się załączyć pozycji bez ustawienia kierunku return false; @@ -3506,7 +3506,7 @@ bool TMoverParameters::IncMainCtrlSeriesMotor(int const CtrlSpeed) if (CtrlSpeed > 1) { // szybkie przejœcie na bezoporow¹ - if (TrainType == dt_ET40) + if (TrainType == train_type::et40) { return false; // this means ET40 won't react at all to fast acceleration command. should it issue just IncMainCtrl(1) instead? } @@ -3515,7 +3515,7 @@ bool TMoverParameters::IncMainCtrlSeriesMotor(int const CtrlSpeed) // all work is done in the loop header } OK = false; // shouldn't this be part of the loop above? - // if (TrainType=dt_ET40) then + // if (TrainType=train_type::et40) then // while Abs (Im)>IminHi do // dec(MainCtrlPos); // OK:=false ; @@ -3532,7 +3532,7 @@ bool TMoverParameters::IncMainCtrlSeriesMotor(int const CtrlSpeed) SetFlag( SoundFlag, sound::relay ); } */ - if (TrainType == dt_ET42) + if (TrainType == train_type::et42) { --MainCtrlPos; OK = false; @@ -3548,7 +3548,7 @@ bool TMoverParameters::IncMainCtrlSeriesMotor(int const CtrlSpeed) //} } - if (TrainType == dt_ET42 && true == DynamicBrakeFlag && MainCtrlPos > 20) + if (TrainType == train_type::et42 && true == DynamicBrakeFlag && MainCtrlPos > 20) { MainCtrlPos = 20; OK = false; @@ -3578,7 +3578,7 @@ bool TMoverParameters::DecMainCtrl(int CtrlSpeed) // TBD, TODO: replace with mainctrlpowerpos() check? if (MainCtrlPos > 0) { - if (TrainType != dt_ET22 || ScndCtrlPos == 0) // Ra: ET22 blokuje nastawnik przy boczniku + if (TrainType != train_type::et22 || ScndCtrlPos == 0) // Ra: ET22 blokuje nastawnik przy boczniku { if (CoupledCtrl && ScndCtrlPos > 0) { @@ -3677,10 +3677,10 @@ bool TMoverParameters::DecMainCtrlSeriesMotor(int const CtrlSpeed) { MainCtrlPos--; // if (MainCtrlPos=0) and (ScndCtrlPos=0) and - // (TrainType<>dt_ET40)and(TrainType<>dt_EP05) then + // (TrainType<>train_type::et40)and(TrainType<>train_type::ep05) then // StLinFlag:=false; - // if (MainCtrlPos=0) and (TrainType<>dt_ET40) and - // (TrainType<>dt_EP05) then + // if (MainCtrlPos=0) and (TrainType<>train_type::et40) and + // (TrainType<>train_type::ep05) then // MainCtrlActualPos:=0; //yBARC: co to tutaj robi? ;) OK = true; } @@ -3778,11 +3778,11 @@ bool TMoverParameters::IncScndCtrl(int CtrlSpeed) { bool OK = false; - if (DynamicBrakeFlag && TrainType == dt_ET42 && CabActive != 0 && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0) + if (DynamicBrakeFlag && TrainType == train_type::et42 && CabActive != 0 && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0) { OK = DynamicBrakeSwitch(false); } - else if (ScndCtrlPosNo > 0 && CabActive != 0 && !(TrainType == dt_ET42 && (Imax == ImaxHi || (DynamicBrakeFlag && MainCtrlPowerPos() > 0)))) + else if (ScndCtrlPosNo > 0 && CabActive != 0 && !(TrainType == train_type::et42 && (Imax == ImaxHi || (DynamicBrakeFlag && MainCtrlPowerPos() > 0)))) { // if (RList[MainCtrlPos].R=0) and (MainCtrlPos>0) and (ScndCtrlPos0 OK = DynamicBrakeSwitch(true); @@ -3926,7 +3926,7 @@ void TMoverParameters::ScndCtrlResistiveLockCheck() int TMoverParameters::GetVirtualScndPos() const { - if (TrainType == dt_ET42 && DynamicBrakeFlag && !ScndCtrlPos) + if (TrainType == train_type::et42 && DynamicBrakeFlag && !ScndCtrlPos) return -1; return ScndCtrlPos; } @@ -4348,7 +4348,7 @@ bool TMoverParameters::DirectionBackward(void) return false; } - if (DirActive == 1 && MainCtrlPos == 0 && TrainType == dt_EZT && EngineType != TEngineType::ElectricInductionMotor && MinCurrentSwitch(false)) + if (DirActive == 1 && MainCtrlPos == 0 && TrainType == train_type::emu && EngineType != TEngineType::ElectricInductionMotor && MinCurrentSwitch(false)) { return true; } @@ -5222,7 +5222,7 @@ bool TMoverParameters::DynamicBrakeSwitch(bool Switch) if (TestFlag(thiscoupler.CouplingFlag, coupling::control)) thiscoupler.Connected->DynamicBrakeFlag = Switch; // end; - // if (DynamicBrakeType=dbrake_passive) and (TrainType=dt_ET42) then + // if (DynamicBrakeType=dbrake_passive) and (TrainType=train_type::et42) then // begin // DynamicBrakeFlag:=false; // DynamicBrakeSwitch:=false; @@ -5391,7 +5391,7 @@ bool TMoverParameters::IncBrakePress(double &brake, double PressLimit, double dp bool IBP; // if (DynamicBrakeType<>dbrake_switch) and (DynamicBrakeType<>dbrake_none) and // ((BrakePress>2.0) or (PipePress<3.7{(LowPipePress+0.5)})) then - if (DynamicBrakeType != dbrake_switch && DynamicBrakeType != dbrake_none && BrakePress > 2.0 && TrainType != dt_EZT) // yB radzi nie sprawdzać ciśnienia w przewodzie + if (DynamicBrakeType != dbrake_switch && DynamicBrakeType != dbrake_none && BrakePress > 2.0 && TrainType != train_type::emu) // yB radzi nie sprawdzać ciśnienia w przewodzie // hunter-301211: dla EN57 silnikow nie odlaczamy { DynamicBrakeFlag = true; // uruchamianie hamulca ED albo odlaczanie silnikow @@ -5852,7 +5852,7 @@ double TMoverParameters::MainValveSupply() LockPipe = PipePress < (LockPipe ? LockPipeOff : LockPipeOn); bool lock_new = (LockPipe && !UnlockPipe && BrakeCtrlPosR > HandleUnlock) || (EmergencyCutsOffHandle && EmergencyValveFlow > 0); // new simple codition based on .fiz bool lock_old = BrakeHandle == TBrakeHandle::FV4a // old complex condition based on assumptions - && PipePress < 2.75 && (Hamulec->GetStatus() & b_rls) == 0 && BrakeSubsystem == TBrakeSubSystem::ss_LSt && TrainType != dt_EZT && !UnlockPipe; + && PipePress < 2.75 && (Hamulec->GetStatus() & b_rls) == 0 && BrakeSubsystem == TBrakeSubSystem::ss_LSt && TrainType != train_type::emu && !UnlockPipe; if (lock_old || lock_new) { @@ -5928,10 +5928,11 @@ void TMoverParameters::UpdateDistributorSettings() { LocBrakePress = LocHandle->GetCP(); + auto const et41or42 = [](train_type const Type) { return Type == train_type::et41 || Type == train_type::et42; }; for (auto const &couplerentry : Couplers) // nie podoba mi się to rozwiązanie, chyba trzeba // dodać jakiś wpis do fizyki na to - if ((TrainType & (dt_ET41 | dt_ET42)) != 0 && couplerentry.Connected != nullptr && (couplerentry.Connected->TrainType & (dt_ET41 | dt_ET42)) != 0 && (couplerentry.CouplingFlag & 36) == 36) + if (et41or42(TrainType) && couplerentry.Connected != nullptr && et41or42(couplerentry.Connected->TrainType) && (couplerentry.CouplingFlag & 36) == 36) LocBrakePress = std::max(couplerentry.Connected->LocHandle->GetCP(), LocBrakePress); // if ((DynamicBrakeFlag) && (EngineType == ElectricInductionMotor)) @@ -6048,7 +6049,7 @@ void TMoverParameters::UpdateScndPipePressure(double dt) Pipe2->Flow(Hamulec->GetHPFlow(ScndPipePress, dt)); // NOTE: condition disabled to allow the air flow from the main hose to the main tank as well - if (/* ( ( Compressor > ScndPipePress ) && ( */ VeselVolume > 0.0 /* ) ) || ( TrainType == dt_EZT ) || ( TrainType == dt_DMU ) */) + if (/* ( ( Compressor > ScndPipePress ) && ( */ VeselVolume > 0.0 /* ) ) || ( TrainType == train_type::emu ) || ( TrainType == train_type::dmu ) */) { double const dV = PF(Compressor, ScndPipePress, Spz) * dt; CompressedVolume += dV / 1000.0; @@ -6507,7 +6508,7 @@ void TMoverParameters::ComputeTotalForce(double dt) if (brakes_changed_asleep()) switch_physics(true, wake_cause::other); - auto const vehicleisactive{CabActive != 0 || Vel > 0.0001 || accelerating() || LastSwitchingTime < 5 || TrainType == dt_EZT || TrainType == dt_DMU}; + auto const vehicleisactive{CabActive != 0 || Vel > 0.0001 || accelerating() || LastSwitchingTime < 5 || is_multiple_unit()}; auto const movingvehicleahead{Neighbours[end::front].vehicle != nullptr && (Neighbours[end::front].vehicle->MoverParameters->Vel > 0.0001 || Neighbours[end::front].vehicle->MoverParameters->accelerating())}; @@ -6699,7 +6700,7 @@ double TMoverParameters::BrakeForceR(double ratio, double velocity) const ratio = ratio + (1.5 - ratio) * std::min(1.0, Vel * 0.02); if (BrakeDelayFlag & bdelay_R && BrakeMethod % 128 != bp_Cosid && BrakeMethod % 128 != bp_D1 && BrakeMethod % 128 != bp_D2 && Power < 1) ratio *= Hamulec->GetRapidRatio(velocity); - if (TrainType == dt_DMU && velocity < 30.0) + if (TrainType == train_type::dmu && velocity < 30.0) { ratio -= 0.3; } @@ -7508,7 +7509,7 @@ void TMoverParameters::VoltageRelaysCheck() // wywalanie szybkiego z powodu niewłaściwego napięcia // (a line breaker closed ahead of the pantographs holds without voltage) EventFlag |= true == Mains && ((false == NoVoltRelay && false == PantographsRequireMains) || false == OvervoltageRelay) && - MainSwitch(false, TrainType == dt_EZT ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide + MainSwitch(false, TrainType == train_type::emu ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide break; } @@ -7521,7 +7522,7 @@ void TMoverParameters::VoltageRelaysCheck() if (Mains && ((TractionSupplyVoltage() < TractionSupplyMinVoltage() && false == PantographsRequireMains) || TractionSupplyVoltage() > EnginePowerSource.CollectorParameters.MaxV + 200)) { - MainSwitch(false, TrainType == dt_EZT ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide + MainSwitch(false, TrainType == train_type::emu ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide } break; } @@ -7581,11 +7582,11 @@ void TMoverParameters::SeriesMotorTractionForce(double dt) { // enrot:=Transmision.Ratio*nrot; // yB: szereg dwoch sekcji w ET42 - if (TrainType == dt_ET42 && Imax == ImaxHi) + if (TrainType == train_type::et42 && Imax == ImaxHi) EngineVoltage = EngineVoltage / 2.0; Mm = Momentum(Current(enrot, EngineVoltage)); // oblicza tez prad p/slinik - if (TrainType == dt_ET42) + if (TrainType == train_type::et42) { if (Imax == ImaxHi) EngineVoltage = EngineVoltage * 2; @@ -7597,7 +7598,7 @@ void TMoverParameters::SeriesMotorTractionForce(double dt) SeriesMotorDynamicBrake(dt); } - if (TrainType == dt_ET22 && DelayCtrlFlag) // szarpanie przy zmianie układu w byku + if (TrainType == train_type::et22 && DelayCtrlFlag) // szarpanie przy zmianie układu w byku Mm = Mm * RList[MainCtrlActualPos].Bn / (RList[MainCtrlActualPos].Bn + 1); // zrobione w momencie, żeby nie dawac elektryki w przeliczaniu sił if (abs(Im) > Imax) @@ -7609,7 +7610,7 @@ void TMoverParameters::SeriesMotorTractionForce(double dt) if ((DynamicBrakeType == dbrake_automatic || DynamicBrakeType == dbrake_switch) && DynamicBrakeFlag) Itot = Im * 2; // 2x2 silniki w EP09 - else if (TrainType == dt_EZT && Imin == IminLo && ScndS) // yBARC - boczniki na szeregu poprawnie + else if (TrainType == train_type::emu && Imin == IminLo && ScndS) // yBARC - boczniki na szeregu poprawnie Itot = Im; else Itot = Im * RList[MainCtrlActualPos].Bn; // prad silnika * ilosc galezi @@ -8787,7 +8788,7 @@ bool TMoverParameters::MaxCurrentSwitch(bool State, range_t const Notify) bool TMoverParameters::MinCurrentSwitch(bool State) { bool MCS = false; - if ((EngineType == TEngineType::ElectricSeriesMotor && IminHi > IminLo) || (TrainType == dt_EZT && EngineType != TEngineType::ElectricInductionMotor)) + if ((EngineType == TEngineType::ElectricSeriesMotor && IminHi > IminLo) || (TrainType == train_type::emu && EngineType != TEngineType::ElectricInductionMotor)) { if (State && Imin == IminLo) @@ -8919,7 +8920,7 @@ bool TMoverParameters::AutoRelayShuntStep(bool const ARFASI2) } else if (ScndCtrlActualPos > ScndCtrlPos) { - if (LastRelayTime > CtrlDownDelay && TrainType != dt_EZT) + if (LastRelayTime > CtrlDownDelay && TrainType != train_type::emu) { --ScndCtrlActualPos; SetFlag(SoundFlag, sound::shuntfield); @@ -8938,11 +8939,11 @@ bool TMoverParameters::AutoRelayMainStep(bool const ARFASI) // running backwards, the motors don't get joined in more branches than allowed (the series connection // alone, usually); the camshaft still goes back down from there (eu07/maszyna#393: it stayed where it // was, the line contactors closed, whatever the driver did with the master controller) - auto const backwardslimit{DirActive < 0 && TrainType != dt_PseudoDiesel && RList[MainCtrlActualPos + 1].Bn > BackwardsBranchesAllowed}; + auto const backwardslimit{DirActive < 0 && TrainType != train_type::pseudodiesel && RList[MainCtrlActualPos + 1].Bn > BackwardsBranchesAllowed}; // main bez samoczynnego rozruchu if (false == backwardslimit && MainCtrlActualPos < std::size(RList) - 1 // crude guard against running out of current fixed table && (RList[MainCtrlActualPos].Relay < MainCtrlPos || (RList[MainCtrlActualPos + 1].Relay == MainCtrlPos && MainCtrlActualPos < RlistSize) || - (TrainType == dt_ET22 && DelayCtrlFlag))) + (TrainType == train_type::et22 && DelayCtrlFlag))) { OK = AutoRelayMainUp(ARFASI); } @@ -9007,7 +9008,7 @@ bool TMoverParameters::AutoRelayMainNotchUp() bool OK = false; // WriteLog("LRT = " + FloatToStr(LastRelayTime) + ", " + // FloatToStr(CtrlDelay)); - if (TrainType == dt_ET22 && MainCtrlPos > 1 && (RList[MainCtrlActualPos].Bn < RList[MainCtrlActualPos + 1].Bn || DelayCtrlFlag)) + if (TrainType == train_type::et22 && MainCtrlPos > 1 && (RList[MainCtrlActualPos].Bn < RList[MainCtrlActualPos + 1].Bn || DelayCtrlFlag)) { // et22 z walem grupowym if (!DelayCtrlFlag) // najpierw przejscie @@ -9067,7 +9068,7 @@ bool TMoverParameters::AutoRelayMainDown() } else if (LastRelayTime > CtrlDownDelay) { - if (TrainType != dt_EZT) // tutaj powinien być tryb sterowania wałem + if (TrainType != train_type::emu) // tutaj powinien być tryb sterowania wałem { --MainCtrlActualPos; OK = true; @@ -9087,7 +9088,7 @@ bool TMoverParameters::AutoRelayLineContactorsStep(bool const motorconnectorsoff { bool OK = false; // ybARC - zalaczenie stycznikow liniowych - if (false == motorconnectorsoff && MainCtrlActualPos == 0 && (TrainType == dt_EZT || HasCamshaft ? MainCtrlPowerPos() > 0 : MainCtrlPowerPos() == 1)) + if (false == motorconnectorsoff && MainCtrlActualPos == 0 && (TrainType == train_type::emu || HasCamshaft ? MainCtrlPowerPos() > 0 : MainCtrlPowerPos() == 1)) { DelayCtrlFlag = true; @@ -9121,7 +9122,7 @@ bool TMoverParameters::CamshaftRunDown() if (CoupledCtrl) { - if (TrainType == dt_EZT) + if (TrainType == train_type::emu) { OK = CamshaftRunDownEMU(); } @@ -11256,7 +11257,7 @@ void TMoverParameters::move_door(basic_door &door, double const Deltatime) if (door.step_folding) { // fold left doorstep - if (TrainType == dt_EZT || TrainType == dt_DMU) + if (is_multiple_unit()) { // multi-unit vehicles typically fold the doorstep only after closing the door if (door.position <= 0.f) @@ -12883,26 +12884,26 @@ void TMoverParameters::LoadFIZ_Param(std::string const &line) } { - std::map> types{ - {"pseudodiesel", dt_PseudoDiesel}, - {"ezt", dt_EZT}, - {"dmu", dt_DMU}, - {"sn61", dt_SN61}, - {"et22", dt_ET22}, - {"et40", dt_ET40}, - {"et41", dt_ET41}, - {"et42", dt_ET42}, - {"ep05", dt_EP05}, - {"181", dt_181}, - {"182", dt_181} // na razie tak + std::map> types{ + {"pseudodiesel", train_type::pseudodiesel}, + {"ezt", train_type::emu}, + {"dmu", train_type::dmu}, + {"sn61", train_type::sn61}, + {"et22", train_type::et22}, + {"et40", train_type::et40}, + {"et41", train_type::et41}, + {"et42", train_type::et42}, + {"ep05", train_type::ep05}, + {"181", train_type::skoda181}, + {"182", train_type::skoda181} // na razie tak }; std::string type; extract_value(type, "Type", line, "none"); auto lookup = types.find(ToLower(type)); - TrainType = lookup != types.end() ? lookup->second : dt_Default; + TrainType = lookup != types.end() ? lookup->second : train_type::generic; } - if (TrainType == dt_EZT) + if (TrainType == train_type::emu) { IminLo = 1; @@ -13727,7 +13728,7 @@ void TMoverParameters::LoadFIZ_CntrlStarts(std::string const &line) ConverterStart = lookup != starts.end() ? lookup->second : manual; } extract_value(ConverterStartDelay, "ConverterStartDelay", line, ""); - extract_value(ConverterOverloadRelayOffWhenMainIsOff, "ConverterOverloadWhenMainIsOff", line, TrainType == dt_EZT ? "yes" : "no"); + extract_value(ConverterOverloadRelayOffWhenMainIsOff, "ConverterOverloadWhenMainIsOff", line, TrainType == train_type::emu ? "yes" : "no"); // compressor { auto lookup = starts.find(extract_value("CompressorStart", line)); @@ -13739,7 +13740,7 @@ void TMoverParameters::LoadFIZ_CntrlStarts(std::string const &line) PantographCompressorStart = lookup != starts.end() ? lookup->second : manual; } // pantograph compressor valve - PantAutoValve = TrainType == dt_EZT; // legacy code behaviour, automatic valve was initially installed in all EMUs + PantAutoValve = TrainType == train_type::emu; // legacy code behaviour, automatic valve was initially installed in all EMUs extract_value(PantAutoValve, "PantAutoValve", line, ""); // pantographs valve { @@ -13804,14 +13805,14 @@ void TMoverParameters::LoadFIZ_CntrlStarts(std::string const &line) // ground relay { auto lookup = starts.find(extract_value("GroundRelayStart", line)); - auto const defaultstart{TrainType == dt_EZT ? automatic : manual}; + auto const defaultstart{TrainType == train_type::emu ? automatic : manual}; GroundRelayStart = lookup != starts.end() ? lookup->second : defaultstart; } // converter overload relay { auto lookup = starts.find(extract_value("ConverterOverloadRelayStart", line)); // the relay of a multiple unit activates when the converter is switched off - auto const defaultstart{TrainType == dt_EZT ? converter : manual}; + auto const defaultstart{TrainType == train_type::emu ? converter : manual}; ConverterOverloadRelayStart = lookup != starts.end() ? lookup->second : defaultstart; } } @@ -14060,7 +14061,7 @@ void TMoverParameters::LoadFIZ_Engine(std::string const &Input) extract_value(MotorBlowers[end::front].min_start_velocity, "MotorBlowersStartVelocity", Input, ""); MotorBlowers[end::rear] = MotorBlowers[end::front]; // pressure switch - extract_value(HasControlPressureSwitch, "PressureSwitch", Input, TrainType != dt_EZT ? "yes" : "no"); + extract_value(HasControlPressureSwitch, "PressureSwitch", Input, TrainType != train_type::emu ? "yes" : "no"); // its brake cylinder half; the brake pipe one stays extract_value(PressureSwitchBrakeCylinder, "PressureSwitchBrakeCylinder", Input, ""); } @@ -14966,7 +14967,7 @@ void TMoverParameters::CreateBrakeHandles() { LocHandle = std::make_shared(); LocHandle->Init(MaxBrakePress[0]); - if (TrainType == dt_EZT) + if (TrainType == train_type::emu) { dynamic_cast(LocHandle.get())->SetSpeed(3.5); @@ -15645,7 +15646,7 @@ bool TMoverParameters::RunPowerCommand(std::string const &Command, double CValue auto const inputend{(static_cast(CValue1) & 0x80) != 0 ? 1 : 0}; auto const inputcab{(static_cast(CValue1) & 0x40) != 0 ? 1 : 0}; auto const inputoperation{static_cast(CValue1) & ~(0x80 | 0x40)}; - auto const noswap{TrainType == dt_EZT || TrainType == dt_ET41}; + auto const noswap{TrainType == train_type::emu || TrainType == train_type::et41}; auto swap{false == noswap && TestFlag(Couplers[CValue2 == -1 ? end::rear : end::front].CouplingFlag, coupling::control)}; if (auto const reversed{inputcab != (CabActive != -1 ? 1 : 0)}; reversed) { @@ -15857,7 +15858,7 @@ double TMoverParameters::ShowCurrentP(int AmpN) const bool Grupowy; // ClearPendingExceptions; - Grupowy = DelayCtrlFlag && TrainType == dt_ET22; // przerzucanie walu grupowego w ET22; + Grupowy = DelayCtrlFlag && TrainType == train_type::et22; // przerzucanie walu grupowego w ET22; Bn = RList[MainCtrlActualPos].Bn; // ile równoległych gałęzi silników if (DynamicBrakeType == dbrake_automatic && DynamicBrakeFlag) diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index d7d9d6bca..f577573c9 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -892,7 +892,7 @@ debug_panel::update_section_vehicle( std::vector &Output ) { std::string( isdieselinshuntmode ? to_string( mover.AnPos, 2 ) + STR(" (shunt mode)") : std::to_string( mover.ScndCtrlPos ) + "(" + std::to_string( mover.ScndCtrlActualPos ) + ")" ).c_str(), // engine mover.EnginePower, - std::abs( mover.TrainType == dt_EZT ? mover.ShowCurrent( 0 ) : mover.Im ), + std::abs( mover.TrainType == train_type::emu ? mover.ShowCurrent( 0 ) : mover.Im ), // revolutions std::abs( mover.enrot ) * 60, std::abs( mover.nrot ) * mover.Transmision.Ratio * 60, diff --git a/tests/unit/drive.cpp b/tests/unit/drive.cpp index 02fc74c03..939a9a626 100644 --- a/tests/unit/drive.cpp +++ b/tests/unit/drive.cpp @@ -108,7 +108,7 @@ void prepare_diesel(driven const &Driven) { // the pantographs' own air topped up by their compressor, and the pantographs raised void raise_pantographs(driven const &Driven) { auto &pantographs{Driven.pantographs}; - if (auto const enough{(pantographs.TrainType == dt_EZT ? 2.5 : 3.5) + 0.1}; pantographs.PantPress < enough) { + if (auto const enough{(pantographs.TrainType == train_type::emu ? 2.5 : 3.5) + 0.1}; pantographs.PantPress < enough) { if (false == pantographs.PantAutoValve) { pantographs.bPantKurek3 = false; // the pantographs on their own air } diff --git a/tests/unit/golden.cpp b/tests/unit/golden.cpp index 45bd1c532..fcbf01e14 100644 --- a/tests/unit/golden.cpp +++ b/tests/unit/golden.cpp @@ -15,6 +15,29 @@ namespace test { +namespace { + +// the number the traces record for the type of a vehicle: the bit it was before the type became an enum, so the traces +// recorded before it still compare +int legacy_code(train_type const Type) { + switch (Type) { + case train_type::emu: return 0x1; + case train_type::et41: return 0x2; + case train_type::et42: return 0x4; + case train_type::pseudodiesel: return 0x8; + case train_type::et22: return 0x10; + case train_type::sn61: return 0x20; + case train_type::ep05: return 0x40; + case train_type::et40: return 0x80; + case train_type::skoda181: return 0x100; + case train_type::dmu: return 0x200; + case train_type::generic: return 0; + } + return 0; +} + +} // namespace + namespace channels { std::vector motion() { @@ -103,7 +126,7 @@ std::vector doors() { std::vector parameters() { std::vector result{ {"CategoryFlag", [](auto const &M) { return M.CategoryFlag; }}, - {"TrainType", [](auto const &M) { return M.TrainType; }}, + {"TrainType", [](auto const &M) { return legacy_code(M.TrainType); }}, {"EngineType", [](auto const &M) { return static_cast(M.EngineType); }}, {"Vmax", [](auto const &M) { return M.Vmax; }}, {"Mass", [](auto const &M) { return M.Mass; }}, diff --git a/tests/unit/test_cntrl.cpp b/tests/unit/test_cntrl.cpp index c73c45d85..bff7759ea 100644 --- a/tests/unit/test_cntrl.cpp +++ b/tests/unit/test_cntrl.cpp @@ -22,7 +22,7 @@ TEST_CASE("cntrl: the brake delays of the settings come from BDelay1 to BDelay4" TEST_CASE("cntrl: the relays of a multiple unit start on their own, of other vehicles by hand") { SUBCASE("multiple unit") { vehicle unit{definition::load("wagon").set("Param", "Type", "ezt")}; - REQUIRE(unit->TrainType == dt_EZT); + REQUIRE(unit->TrainType == train_type::emu); CHECK(unit->GroundRelayStart == start_t::automatic); CHECK(unit->ConverterOverloadRelayStart == start_t::converter); // activates when the converter is switched off } @@ -117,7 +117,7 @@ TEST_CASE("cntrl: ScndCtrlResistiveLock keeps the field shunting off at zero and SUBCASE("the master controller taken back from a shunt step drops the shunt") { controllers_at(locked, resistancefree); REQUIRE(locked->IncScndCtrl(1)); - if (locked->TrainType == dt_ET22) { + if (locked->TrainType == train_type::et22) { // the ET22's master controller doesn't turn with the shunt on: the shunt goes off first, as before CHECK_FALSE(locked->DecMainCtrl(1)); CHECK(locked->MainCtrlPos == resistancefree); @@ -152,7 +152,7 @@ TEST_CASE("cntrl: ScndCtrlResistiveLock keeps the field shunting off at zero and controllers_at(locked, lastseries); locked->DirActive = 1; REQUIRE(locked->IncScndCtrl(1)); - if (locked->TrainType == dt_ET22) { + if (locked->TrainType == train_type::et22) { CHECK_FALSE(locked->IncMainCtrl(1)); // the ET22's interlock, as before CHECK(locked->ScndCtrlPos == 1); } diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 4b8a68ed4..eb89088ac 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -2352,7 +2352,7 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, fAccThreshold = is_emu() ? -0.55 : is_dmu() ? -0.45 : -0.2; /* // HACK: emu with induction motors need to start their braking a bit sooner than the ones with series motors - if( ( mvOccupied->TrainType == dt_EZT ) + if( ( mvOccupied->TrainType == train_type::emu ) && ( mvControlling->EngineType == TEngineType::ElectricInductionMotor ) ) { fAccThreshold += 0.10; } @@ -3186,7 +3186,7 @@ double TController::BrakeAccFactor() const Factor += fBrakeReaction * (/*mvOccupied->BrakeCtrlPosR*/ BrakeCtrlPosition < 0.5 ? 1.5 : 1) * mvOccupied->Vel / ( std::max( 0.0, ActualProximityDist ) + 1 ) * ( ( AccDesired - AbsAccS ) / fAccThreshold ); } /* - if (mvOccupied->TrainType == dt_DMU && mvOccupied->Vel > 40 && VelNext<40) + if (mvOccupied->TrainType == train_type::dmu && mvOccupied->Vel > 40 && VelNext<40) Factor *= 1 + 0.25 * ( (1600 - VelNext * VelNext) / (mvOccupied->Vel * mvOccupied->Vel) ); */ return Factor; @@ -3623,8 +3623,8 @@ bool TController::IncBrake() } // NOTE: can't perform just test whether connected vehicle == nullptr, due to virtual couplers formed with nearby vehicles auto standalone { true }; - if( mvOccupied->TrainType == dt_ET41 - || mvOccupied->TrainType == dt_ET42 ) { + if( mvOccupied->TrainType == train_type::et41 + || mvOccupied->TrainType == train_type::et42 ) { // NOTE: we're doing simplified checks full of presuptions here. // they'll break if someone does strange thing like turning around the second unit if( mvOccupied->Couplers[end::rear].CouplingFlag & coupling::permanent @@ -3991,7 +3991,7 @@ bool TController::IncSpeed() if (!IsAnyMotorOverloadRelayOpen && !mvControlling->ControlPressureSwitch && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->StLinFlag) && (Ready || iDrivigFlags & movePress)) { // youBy polecił dodać 2012-09-08 v367 // na pozycji 0 przejdzie, a na pozostałych będzie czekać, aż się załączą liniowe (zgaśnie DelayCtrlFlag) - auto const usehighoverloadrelaythreshold{mvControlling->TrainType != dt_ET42 // ET42 uses these variables for different purpose. TODO: fix this + auto const usehighoverloadrelaythreshold{mvControlling->TrainType != train_type::et42 // ET42 uses these variables for different purpose. TODO: fix this && mvControlling->ImaxHi > mvControlling->ImaxLo && mvOccupied->Vel < (mvControlling->IsMotorOverloadRelayHighThresholdOn() ? 30.0 : 20.0) && iVehicles - ControlledEnginesCount > 0 // && ( std::fabs( mvControlling->Im ) > 0.85 * mvControlling->Imax ) @@ -4023,7 +4023,7 @@ bool TController::IncSpeed() mvControlling->MainCtrlPos == mvControlling->MainCtrlPosNo); // if needed enable high threshold for overload relay... - if (mvControlling->TrainType != dt_ET42) + if (mvControlling->TrainType != train_type::et42) { // ET42 uses these variables for different purpose. TODO: fix this if (usehighoverloadrelaythreshold) { @@ -6368,7 +6368,7 @@ void TController::DirectionForward(bool forward) iTableDirection = 0; } } - if( mvOccupied->TrainType == dt_SN61 ) { + if( mvOccupied->TrainType == train_type::sn61 ) { // specjalnie dla SN61 żeby nie zgasł while( mvControlling->RList[mvControlling->MainCtrlPos].Mn == 0 && mvControlling->IncMainCtrl(1) ) { @@ -6970,7 +6970,7 @@ TController::control_pantographs() { auto const useregularpantographlayout { pVehicle->Next(coupling::control) == nullptr // standalone || is_emu() // special case - || mvControlling->TrainType == dt_ET41 }; // special case + || mvControlling->TrainType == train_type::et41 }; // special case if( mvOccupied->Vel > EU07_AI_NOMOVEMENT ) { diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 0eae2caf1..a6985bcd6 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -274,10 +274,10 @@ public: return TestFlag( mvOccupied->CategoryFlag, 2 ); } inline bool is_emu() const { - return mvControlling->TrainType == dt_EZT; } + return mvControlling->TrainType == train_type::emu; } inline bool is_dmu() const { - return mvControlling->TrainType == dt_DMU; } + return mvControlling->TrainType == train_type::dmu; } inline bool has_diesel_engine() const { return mvControlling->EngineType == TEngineType::DieselElectric || mvControlling->EngineType == TEngineType::DieselEngine; diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 7eb6f19a9..cfe479a94 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -4285,7 +4285,7 @@ bool TDynamicObject::Update(double dt, double dt1) */ && MoverParameters->EngineType != TEngineType::DieselEngine && MoverParameters->EngineType != TEngineType::WheelsDriven ) { // jeśli bateria wyłączona, a nie diesel ani drezyna reczna - if( MoverParameters->MainSwitch( false, MoverParameters->TrainType == dt_EZT ? range_t::unit : range_t::local ) ) { + if( MoverParameters->MainSwitch( false, MoverParameters->TrainType == train_type::emu ? range_t::unit : range_t::local ) ) { // wyłączyć zasilanie // NOTE: we turn off entire EMU, but only the affected unit for other multi-unit consists MoverParameters->EventFlag = true; @@ -4294,8 +4294,8 @@ bool TDynamicObject::Update(double dt, double dt1) // TODO: have this dependant on .fiz-driven flag // NOTE: moved to pantspeed calculation part a little later in the function. all remarks and todo still apply /* - MoverParameters->PantFront( false, ( MoverParameters->TrainType == dt_EZT ? range::unit : range::local ) ); - MoverParameters->PantRear( false, ( MoverParameters->TrainType == dt_EZT ? range::unit : range::local ) ); + MoverParameters->PantFront( false, ( MoverParameters->TrainType == train_type::emu ? range::unit : range::local ) ); + MoverParameters->PantRear( false, ( MoverParameters->TrainType == train_type::emu ? range::unit : range::local ) ); */ } } @@ -4421,7 +4421,7 @@ bool TDynamicObject::Update(double dt, double dt1) // McZapkie-260202 end // fragment z EXE Kursa - /* if (MoverParameters->TrainType==dt_ET42) + /* if (MoverParameters->TrainType==train_type::et42) { if ((MoverParameters->DynamicBrakeType=dbrake_switch) && ((MoverParameters->BrakePress > @@ -4606,7 +4606,7 @@ bool TDynamicObject::Update(double dt, double dt1) break; } // pozostałe na razie nie obsługiwane if( MoverParameters->PantPress > ( - MoverParameters->TrainType == dt_EZT ? + MoverParameters->TrainType == train_type::emu ? 2.45 : // Ra 2013-12: Niebugocław mówi, że w EZT podnoszą się przy 2.5 3.45 ) ) { // z EXE Kursa @@ -8546,7 +8546,7 @@ TDynamicObject * TDynamicObject::FindPowered() // problematyczna może być kwestia wybranej kabiny (w silnikowym...) // jeśli silnikowy będzie zapięty odwrotnie (tzn. -1), to i tak powinno jeździć dobrze // również hamowanie wykonuje się zaworem w członie, a nie w silnikowym... - auto const coupling { MoverParameters->TrainType == dt_EZT || MoverParameters->TrainType == dt_DMU ? + auto const coupling { MoverParameters->is_multiple_unit() ? coupling::permanent : coupling::control }; @@ -9754,7 +9754,7 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { if( mover->Vel > 0.0001 ) { ++awake.speed; } if( mover->accelerating() ) { ++awake.acceleration; } if( mover->LastSwitchingTime < 5 ) { ++awake.switching; } - if( ( mover->TrainType == dt_EZT ) || ( mover->TrainType == dt_DMU ) ) { ++awake.multipleunit; } + if( mover->is_multiple_unit() ) { ++awake.multipleunit; } if( moving( mover->Neighbours[ end::front ] ) || moving( mover->Neighbours[ end::rear ] ) ) { ++awake.neighbour; } } } diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 3c4e5f6fe..27f23b601 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -1013,7 +1013,7 @@ TTrain::state_t TTrain::get_state() const static_cast(mvOccupied->BrakePress), static_cast(mvPantographUnit->PantPress), fHVoltage, - {fHCurrent[mvControlled->TrainType & dt_EZT ? 0 : 1], fHCurrent[2], fHCurrent[3]}, + {fHCurrent[mvControlled->TrainType == train_type::emu ? 0 : 1], fHCurrent[2], fHCurrent[3]}, ggLVoltage.GetValue(), mvOccupied->DistCounter, static_cast(RadioChannel()), @@ -1036,7 +1036,7 @@ TTrain::state_t TTrain::get_state() const bool TTrain::is_eztoer() const { - return mvControlled->TrainType == dt_EZT && mvOccupied->BrakeSubsystem == TBrakeSubSystem::ss_ESt && mvControlled->Power24vIsAvailable == true && mvControlled->EpFuse == true && + return mvControlled->TrainType == train_type::emu && mvOccupied->BrakeSubsystem == TBrakeSubSystem::ss_ESt && mvControlled->Power24vIsAvailable == true && mvControlled->EpFuse == true && mvControlled->DirActive != 0; // od yB } @@ -1112,7 +1112,7 @@ void TTrain::set_train_brake_speed(TDynamicObject *Vehicle, int const Speed) void TTrain::set_paired_open_motor_connectors_button(bool const State) { - if (mvControlled->TrainType == dt_ET41 || mvControlled->TrainType == dt_ET42) + if (mvControlled->TrainType == train_type::et41 || mvControlled->TrainType == train_type::et42) { // crude implementation of the button affecting entire unit for multi-unit engines // TODO: rework it into part of standard command propagation system @@ -1901,7 +1901,7 @@ void TTrain::OnCommand_independentbrakebailoff(TTrain *Train, command_data const { // TODO: check if this set of conditions can be simplified. // it'd be more flexible to have an attribute indicating whether bail off position is supported - if (Train->mvControlled->TrainType != dt_EZT && + if (Train->mvControlled->TrainType != train_type::emu && (Train->mvControlled->EngineType == TEngineType::ElectricSeriesMotor || Train->mvControlled->EngineType == TEngineType::DieselElectric || Train->mvControlled->EngineType == TEngineType::ElectricInductionMotor) && Train->mvOccupied->BrakeCtrlPosNo > 0) @@ -2631,7 +2631,7 @@ void TTrain::OnCommand_mubrakingindicatortoggle(TTrain *Train, command_data cons } return; } - if (Train->mvControlled->TrainType != dt_EZT) + if (Train->mvControlled->TrainType != train_type::emu) { // return; @@ -2875,7 +2875,7 @@ void TTrain::OnCommand_alerteracknowledge(TTrain *Train, command_data const &Com // visual feedback Train->ggSecurityResetButton.UpdateValue(1.0, Train->dsbSwitch); - if (Train->mvOccupied->TrainType == dt_EZT || Train->mvOccupied->DirActive != 0) + if (Train->mvOccupied->TrainType == train_type::emu || Train->mvOccupied->DirActive != 0) Train->mvOccupied->SecuritySystem.acknowledge_press(); } else if (Command.action == GLFW_RELEASE) @@ -2883,7 +2883,7 @@ void TTrain::OnCommand_alerteracknowledge(TTrain *Train, command_data const &Com // visual feedback Train->ggSecurityResetButton.UpdateValue(0.0); - if (Train->mvOccupied->TrainType == dt_EZT || Train->mvOccupied->DirActive != 0) + if (Train->mvOccupied->TrainType == train_type::emu || Train->mvOccupied->DirActive != 0) Train->mvOccupied->SecuritySystem.acknowledge_release(); } } @@ -5402,7 +5402,7 @@ void TTrain::OnCommand_motorconnectorsclose(TTrain *Train, command_data const &C void TTrain::OnCommand_motordisconnect(TTrain *Train, command_data const &Command) { - if (Train->mvControlled->TrainType == dt_EZT ? Train->mvControlled != Train->mvOccupied : Train->iCabn != 0) + if (Train->mvControlled->TrainType == train_type::emu ? Train->mvControlled != Train->mvOccupied : Train->iCabn != 0) { // tylko w maszynowym return; @@ -9053,7 +9053,7 @@ bool TTrain::Update(double const Deltatime) UpdateCab(); // nie blokujemy AI - if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag && (mvOccupied->TrainType == dt_ET40 || mvOccupied->TrainType == dt_EP05 || mvOccupied->HasCamshaft)) + if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag && (mvOccupied->TrainType == train_type::et40 || mvOccupied->TrainType == train_type::ep05 || mvOccupied->HasCamshaft)) { // dla ET40 i EU05 automatyczne cofanie nastawnika - i tak nie będzie to działać dobrze... // TODO: use deltatime to stabilize speed @@ -9326,7 +9326,7 @@ bool TTrain::Update(double const Deltatime) // Ra: sterowanie miernikiem: drugi amperomierz Console::ValueSet(4, fHCurrent[2]); // pierwszy amperomierz; dla EZT prąd całkowity - Console::ValueSet(5, fHCurrent[mvControlled->TrainType & dt_EZT ? 0 : 1]); + Console::ValueSet(5, fHCurrent[mvControlled->TrainType == train_type::emu ? 0 : 1]); // Ra: prędkość na pin 43 - wyjście analogowe (to nie jest PWM); skakanie zapewnia mechanika napędu Console::ValueSet(6, fTachoVelocity); } @@ -9337,15 +9337,15 @@ bool TTrain::Update(double const Deltatime) if (mvControlled->ConverterFlag == true) { fConverterTimer += static_cast(Deltatime); - if (mvControlled->CompressorFlag == true && mvControlled->CompressorPower == 1 && (mvControlled->EngineType == TEngineType::ElectricSeriesMotor || mvControlled->TrainType == dt_EZT) && + if (mvControlled->CompressorFlag == true && mvControlled->CompressorPower == 1 && (mvControlled->EngineType == TEngineType::ElectricSeriesMotor || mvControlled->TrainType == train_type::emu) && DynamicObject->Controller == Humandriver // hunter-110212: poprawka dla EZT && false == DynamicObject->Mechanik->AIControllFlag) { // hunter-091012: poprawka (zmiana warunku z CompressorPower /rozne od 0/ na /rowne 1/) if (fConverterTimer < fConverterPrzekaznik) { mvControlled->ConvOvldFlag = true; - if (mvControlled->TrainType != dt_EZT) - mvControlled->MainSwitch(false, mvControlled->TrainType == dt_EZT ? range_t::unit : range_t::local); + if (mvControlled->TrainType != train_type::emu) + mvControlled->MainSwitch(false, mvControlled->TrainType == train_type::emu ? range_t::unit : range_t::local); } else if (fConverterTimer >= fConverterPrzekaznik) { @@ -9432,7 +9432,7 @@ bool TTrain::Update(double const Deltatime) else { int x; - if (mvControlled->TrainType == dt_ET42 && mvControlled->Imax == mvControlled->ImaxHi) + if (mvControlled->TrainType == train_type::et42 && mvControlled->Imax == mvControlled->ImaxHi) x = 1; else x = 2; @@ -9611,12 +9611,12 @@ bool TTrain::Update(double const Deltatime) switch (mvControlled->TrainType) { // zależnie od typu lokomotywy - case dt_EZT: + case train_type::emu: { btLampkaHamienie.Turn(mvControlled->BrakePress >= 0.2 && mvControlled->Signalling); break; } - case dt_ET41: + case train_type::et41: { // odhamowanie drugiego członu if (mvSecond) @@ -9941,7 +9941,7 @@ bool TTrain::Update(double const Deltatime) // Ra: od byte odejmowane boolean i konwertowane potem na double? if (false == ggScndCtrl.is_push()) { - ggScndCtrl.UpdateValue(static_cast(double(mvControlled->ScndCtrlPos - (mvControlled->TrainType == dt_ET42 && mvControlled->DynamicBrakeFlag))), dsbNastawnikBocz); + ggScndCtrl.UpdateValue(static_cast(double(mvControlled->ScndCtrlPos - (mvControlled->TrainType == train_type::et42 && mvControlled->DynamicBrakeFlag))), dsbNastawnikBocz); } ggScndCtrl.Update(); } @@ -9963,7 +9963,7 @@ bool TTrain::Update(double const Deltatime) } if (ggDirKey.SubModel != nullptr) { - if (mvControlled->TrainType != dt_EZT) + if (mvControlled->TrainType != train_type::emu) { ggDirKey.UpdateValue(static_cast(double(mvControlled->DirActive)), dsbReverserKey); } @@ -11766,11 +11766,11 @@ void TTrain::clear_cab_controls() btLampkaNadmSil.Clear(4); btLampkaStyczn.Clear(5); btLampkaPoslizg.Clear(6); - btLampkaNadmPrzetw.Clear((mvControlled->TrainType & dt_EZT) != 0 ? -1 : 7); // EN57 nie ma tej lampki - btLampkaPrzetwOff.Clear((mvControlled->TrainType & dt_EZT) != 0 ? 7 : -1); // za to ma tę + btLampkaNadmPrzetw.Clear(mvControlled->TrainType == train_type::emu ? -1 : 7); // EN57 nie ma tej lampki + btLampkaPrzetwOff.Clear(mvControlled->TrainType == train_type::emu ? 7 : -1); // za to ma tę btLampkaNadmSpr.Clear(8); btLampkaNadmWent.Clear(9); - btLampkaWysRozr.Clear((mvControlled->TrainType & dt_ET22) != 0 ? -1 : 10); // ET22 nie ma tej lampki + btLampkaWysRozr.Clear(mvControlled->TrainType == train_type::et22 ? -1 : 10); // ET22 nie ma tej lampki btLampkaOgrzewanieSkladu.Clear(11); // overheat indicator lamps btLampkaOilOverheat.Clear(-1); diff --git a/widgets/vehicleparams.cpp b/widgets/vehicleparams.cpp index 14ca9923c..c2b140d8a 100644 --- a/widgets/vehicleparams.cpp +++ b/widgets/vehicleparams.cpp @@ -169,7 +169,7 @@ void ui::vehicleparams_panel::render_contents() mover.MainCtrlPos, mover.MainCtrlActualPos, std::string(isdieselinshuntmode ? to_string(mover.AnPos, 2) + STR(" (shunt mode)") : std::to_string(mover.ScndCtrlPos) + "(" + std::to_string(mover.ScndCtrlActualPos) + ")").c_str(), // engine - mover.EnginePower, std::abs(mover.TrainType == dt_EZT ? mover.ShowCurrent(0) : mover.Im), + mover.EnginePower, std::abs(mover.TrainType == train_type::emu ? mover.ShowCurrent(0) : mover.Im), // revolutions std::abs(mover.enrot) * 60, std::abs(mover.nrot) * mover.Transmision.Ratio * 60, mover.RventRot * 60, std::abs(mover.MotorBlowers[end::front].revolutions), std::abs(mover.MotorBlowers[end::rear].revolutions), mover.dizel_heat.rpmw, mover.dizel_heat.rpmw2); From 5a537e69f2dbf4727abae9d46ad68fdb10f72487 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Fri, 27 Nov 2026 17:11:46 +0100 Subject: [PATCH 002/123] refactor(physics): McZapkie/ becomes physics/, its files get English names The folder of the vehicle physics was named after the author of its first version (2001). Its name now says what it holds, and so do its files: McZapkie/MOVER.h, Mover.cpp -> physics/mover.h, mover.cpp McZapkie/hamulce.h, hamulce.cpp -> physics/brakes.h, brakes.cpp McZapkie/Oerlikon_ESt.h, .cpp -> physics/oerlikonest.h, .cpp friction, collision, couplerphysics, derailment: same names in physics/ Every include names the folder ("physics/mover.h"); the McZapkie include directory is gone from CMakeLists.txt. The comments and documents that named the old paths name the new ones. The credits to McZapkie stay. Renames only: git sees every file as renamed (98-100%). 1142/1142 tests, golden traces exact against staging 62f7a29b. --- CMakeLists.txt | 17 ++++++++--------- directoryDescription.md | 2 +- McZapkie/hamulce.cpp => physics/brakes.cpp | 4 ++-- McZapkie/hamulce.h => physics/brakes.h | 2 +- {McZapkie => physics}/collision.cpp | 4 ++-- {McZapkie => physics}/collision.h | 4 ++-- {McZapkie => physics}/couplerphysics.cpp | 2 +- {McZapkie => physics}/couplerphysics.h | 0 {McZapkie => physics}/derailment.cpp | 2 +- {McZapkie => physics}/derailment.h | 2 +- {McZapkie => physics}/friction.cpp | 2 +- {McZapkie => physics}/friction.h | 0 McZapkie/Mover.cpp => physics/mover.cpp | 4 ++-- McZapkie/MOVER.h => physics/mover.h | 8 ++++---- .../oerlikonest.cpp | 2 +- .../Oerlikon_ESt.h => physics/oerlikonest.h | 4 ++-- tests/unit/COVERAGE.md | 18 +++++++++--------- tests/unit/drive.cpp | 2 +- tests/unit/figures.h | 2 +- tests/unit/golden.cpp | 2 +- tests/unit/golden.h | 2 +- tests/unit/invariants.h | 2 +- tests/unit/scenario.cpp | 2 +- tests/unit/test_brake_cycle.cpp | 2 +- tests/unit/test_brake_handles.cpp | 2 +- tests/unit/test_brake_pipe.cpp | 4 ++-- tests/unit/test_brake_setting.cpp | 4 ++-- tests/unit/test_cab.cpp | 2 +- tests/unit/test_collisions.cpp | 6 +++--- tests/unit/test_commands.cpp | 2 +- tests/unit/test_consist.cpp | 2 +- tests/unit/test_controls.cpp | 2 +- tests/unit/test_coupler_physics.cpp | 4 ++-- tests/unit/test_crew.cpp | 2 +- tests/unit/test_derail_motion.cpp | 4 ++-- tests/unit/test_derailment.cpp | 4 ++-- tests/unit/test_derailment_vehicle.cpp | 6 +++--- tests/unit/test_diesel.cpp | 2 +- tests/unit/test_drivingaid.cpp | 2 +- tests/unit/test_dynamic_brake_diesel.cpp | 2 +- tests/unit/test_elf_controller.cpp | 2 +- tests/unit/test_est3al2_relay.cpp | 2 +- tests/unit/test_feed_pipe.cpp | 4 ++-- tests/unit/test_genset.cpp | 2 +- tests/unit/test_line_contactors_interlock.cpp | 2 +- tests/unit/test_pressure_switch.cpp | 2 +- tests/unit/test_timetable.cpp | 2 +- tests/unit/test_track_buckle_derailment.cpp | 2 +- tests/unit/test_traction.cpp | 2 +- tests/unit/vehicle.h | 2 +- utilities/Globals.cpp | 4 ++-- utilities/Globals.h | 6 +++--- utilities/translation.cpp | 2 +- vehicle/Camera.cpp | 2 +- vehicle/Driver.h | 2 +- vehicle/DynObj.cpp | 2 +- vehicle/DynObj.h | 4 ++-- vehicle/brakesetting.cpp | 4 ++-- vehicle/crew.cpp | 2 +- vehicle/derailmotion.cpp | 2 +- vehicle/derailmotion.h | 8 ++++---- vehicle/drivingaid.cpp | 4 ++-- vehicle/enginestart.cpp | 2 +- vehicle/handover.cpp | 2 +- vehicle/lightsprogrammer.h | 2 +- vehicle/mainctrlact.h | 2 +- vehicle/smoke.cpp | 2 +- vehicle/timetableservice.cpp | 2 +- world/TrackCheck.h | 4 ++-- 69 files changed, 110 insertions(+), 111 deletions(-) rename McZapkie/hamulce.cpp => physics/brakes.cpp (99%) rename McZapkie/hamulce.h => physics/brakes.h (99%) rename {McZapkie => physics}/collision.cpp (99%) rename {McZapkie => physics}/collision.h (99%) rename {McZapkie => physics}/couplerphysics.cpp (99%) rename {McZapkie => physics}/couplerphysics.h (100%) rename {McZapkie => physics}/derailment.cpp (99%) rename {McZapkie => physics}/derailment.h (99%) rename {McZapkie => physics}/friction.cpp (99%) rename {McZapkie => physics}/friction.h (100%) rename McZapkie/Mover.cpp => physics/mover.cpp (99%) rename McZapkie/MOVER.h => physics/mover.h (99%) rename McZapkie/Oerlikon_ESt.cpp => physics/oerlikonest.cpp (99%) rename McZapkie/Oerlikon_ESt.h => physics/oerlikonest.h (98%) diff --git a/CMakeLists.txt b/CMakeLists.txt index f5f18344f..b6f35af69 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -56,7 +56,7 @@ set(CMAKE_CXX_STANDARD 20) file(GLOB HEADERS "*.h" "Console/*.h" -"McZapkie/*.h" +"physics/*.h" "gl/*.h" "network/*.h" "vr/*.h" @@ -740,16 +740,16 @@ add_library(eu07_settings INTERFACE) # definition parser, the helpers they use and the rules of the test mode. built once, and tested as the game uses them set(CORE_SOURCES "audio/startsample.cpp" -"McZapkie/friction.cpp" -"McZapkie/hamulce.cpp" -"McZapkie/Mover.cpp" -"McZapkie/couplerphysics.cpp" -"McZapkie/derailment.cpp" -"McZapkie/collision.cpp" +"physics/friction.cpp" +"physics/brakes.cpp" +"physics/mover.cpp" +"physics/couplerphysics.cpp" +"physics/derailment.cpp" +"physics/collision.cpp" "vehicle/derailmotion.cpp" "world/TrackCheck.cpp" "world/SleeperPack.cpp" -"McZapkie/Oerlikon_ESt.cpp" +"physics/oerlikonest.cpp" "utilities/logfiles.cpp" "utilities/parser.cpp" "utilities/utilities.cpp" @@ -825,7 +825,6 @@ target_compile_definitions(eu07_settings INTERFACE ${DEFINITIONS}) target_include_directories(eu07_settings INTERFACE "." "Console" - "McZapkie" "gl" "${DEPS_DIR}/glad/include" "${DEPS_DIR}/dds-ktx/include" diff --git a/directoryDescription.md b/directoryDescription.md index 77d571771..51ba37f32 100644 --- a/directoryDescription.md +++ b/directoryDescription.md @@ -2,7 +2,7 @@ # File structure | Directory| Description| |--|--| -| McZapkie/ | Train Physics Engine | +| physics/ | Vehicle physics: the mover, brakes, couplers, collisions, derailment | | gl/ | OpenGL Abstraction Layer| | network/ | Multiplayer Support | launcher/ | Scenario/Vehicle Selection (built in starter)| diff --git a/McZapkie/hamulce.cpp b/physics/brakes.cpp similarity index 99% rename from McZapkie/hamulce.cpp rename to physics/brakes.cpp index 4a2029af5..65d38663f 100644 --- a/McZapkie/hamulce.cpp +++ b/physics/brakes.cpp @@ -13,9 +13,9 @@ Copyright (C) 2007-2014 Maciej Cierniak */ #include "stdafx.h" -#include "hamulce.h" +#include "physics/brakes.h" #include -#include "MOVER.h" +#include "physics/mover.h" #include "utilities/utilities.h" //---FUNKCJE OGOLNE--- diff --git a/McZapkie/hamulce.h b/physics/brakes.h similarity index 99% rename from McZapkie/hamulce.h rename to physics/brakes.h index 2b08e1f63..dd07f0630 100644 --- a/McZapkie/hamulce.h +++ b/physics/brakes.h @@ -33,7 +33,7 @@ Knorr/West EP - żeby był #pragma once -#include "friction.h" // Pascal unit +#include "physics/friction.h" // Pascal unit /// Number of positions of the local (auxiliary/manual) brake handle. static int const LocalBrakePosNo = 10; /*ilosc nastaw hamulca recznego lub pomocniczego*/ diff --git a/McZapkie/collision.cpp b/physics/collision.cpp similarity index 99% rename from McZapkie/collision.cpp rename to physics/collision.cpp index 2fb085e69..2dd3af62c 100644 --- a/McZapkie/collision.cpp +++ b/physics/collision.cpp @@ -8,13 +8,13 @@ http://mozilla.org/MPL/2.0/. */ #include "stdafx.h" -#include "collision.h" +#include "physics/collision.h" #include #include #include -#include "derailment.h" +#include "physics/derailment.h" namespace collision { diff --git a/McZapkie/collision.h b/physics/collision.h similarity index 99% rename from McZapkie/collision.h rename to physics/collision.h index 01239a3cd..62d16669e 100644 --- a/McZapkie/collision.h +++ b/physics/collision.h @@ -12,8 +12,8 @@ http://mozilla.org/MPL/2.0/. #include #include -#include "couplerphysics.h" -#include "derailment.h" +#include "physics/couplerphysics.h" +#include "physics/derailment.h" // what a collision of two vehicles does to them past their buffers (physics.collisions new in eu07.ini, see // TMoverParameters::CollisionDetect()), as plain functions of the vehicles and the hit: diff --git a/McZapkie/couplerphysics.cpp b/physics/couplerphysics.cpp similarity index 99% rename from McZapkie/couplerphysics.cpp rename to physics/couplerphysics.cpp index 31afd26fe..ca293f69c 100644 --- a/McZapkie/couplerphysics.cpp +++ b/physics/couplerphysics.cpp @@ -8,7 +8,7 @@ http://mozilla.org/MPL/2.0/. */ #include "stdafx.h" -#include "couplerphysics.h" +#include "physics/couplerphysics.h" #include #include diff --git a/McZapkie/couplerphysics.h b/physics/couplerphysics.h similarity index 100% rename from McZapkie/couplerphysics.h rename to physics/couplerphysics.h diff --git a/McZapkie/derailment.cpp b/physics/derailment.cpp similarity index 99% rename from McZapkie/derailment.cpp rename to physics/derailment.cpp index e9cfa452e..46945600f 100644 --- a/McZapkie/derailment.cpp +++ b/physics/derailment.cpp @@ -8,7 +8,7 @@ http://mozilla.org/MPL/2.0/. */ #include "stdafx.h" -#include "derailment.h" +#include "physics/derailment.h" #include #include diff --git a/McZapkie/derailment.h b/physics/derailment.h similarity index 99% rename from McZapkie/derailment.h rename to physics/derailment.h index 50a3d84cb..e25e027cc 100644 --- a/McZapkie/derailment.h +++ b/physics/derailment.h @@ -112,7 +112,7 @@ struct vehicle_state { std::array ends{}; }; -// the dtrack_* flags of the track (MOVER.h) the criteria look at +// the dtrack_* flags of the track (mover.h) the criteria look at namespace track_damage { inline constexpr int railwear{2}; inline constexpr int freerail{4}; diff --git a/McZapkie/friction.cpp b/physics/friction.cpp similarity index 99% rename from McZapkie/friction.cpp rename to physics/friction.cpp index 6ecf5a064..bb4d872d8 100644 --- a/McZapkie/friction.cpp +++ b/physics/friction.cpp @@ -13,7 +13,7 @@ Copyright (C) 2007-2013 Maciej Cierniak */ #include "stdafx.h" -#include "friction.h" +#include "physics/friction.h" double TFricMat::GetFC(double N, double Vel) { diff --git a/McZapkie/friction.h b/physics/friction.h similarity index 100% rename from McZapkie/friction.h rename to physics/friction.h diff --git a/McZapkie/Mover.cpp b/physics/mover.cpp similarity index 99% rename from McZapkie/Mover.cpp rename to physics/mover.cpp index 466523d89..384f1a684 100644 --- a/McZapkie/Mover.cpp +++ b/physics/mover.cpp @@ -8,10 +8,10 @@ http://mozilla.org/MPL/2.0/. */ #include "stdafx.h" -#include "MOVER.h" +#include "physics/mover.h" #include "vehicle/DynObj.h" -#include "Oerlikon_ESt.h" +#include "physics/oerlikonest.h" #include "utilities/Globals.h" #include "utilities/Logs.h" #include "utilities/Timer.h" diff --git a/McZapkie/MOVER.h b/physics/mover.h similarity index 99% rename from McZapkie/MOVER.h rename to physics/mover.h index 3c4f14b41..0e2211afe 100644 --- a/McZapkie/MOVER.h +++ b/physics/mover.h @@ -14,10 +14,10 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include "hamulce.h" -#include "couplerphysics.h" -#include "derailment.h" -#include "collision.h" +#include "physics/brakes.h" +#include "physics/couplerphysics.h" +#include "physics/derailment.h" +#include "physics/collision.h" #include "scripting/ladderlogic.h" #include "vehicle/derailmotion.h" #include "vehicle/odometerreading.h" diff --git a/McZapkie/Oerlikon_ESt.cpp b/physics/oerlikonest.cpp similarity index 99% rename from McZapkie/Oerlikon_ESt.cpp rename to physics/oerlikonest.cpp index 0717eff5d..70c3d4f8e 100644 --- a/McZapkie/Oerlikon_ESt.cpp +++ b/physics/oerlikonest.cpp @@ -13,7 +13,7 @@ Copyright (C) 2007-2014 Maciej Cierniak */ #include "stdafx.h" -#include "Oerlikon_ESt.h" +#include "physics/oerlikonest.h" #include "utilities/utilities.h" // wstepny nacisk sprezyn na glowny przyrzad rozrzadczy, wyrazony jako roznica cisnien ZS - PG [bar] diff --git a/McZapkie/Oerlikon_ESt.h b/physics/oerlikonest.h similarity index 98% rename from McZapkie/Oerlikon_ESt.h rename to physics/oerlikonest.h index eaae2c032..eedf80dc9 100644 --- a/McZapkie/Oerlikon_ESt.h +++ b/physics/oerlikonest.h @@ -19,8 +19,8 @@ http://mozilla.org/MPL/2.0/. #include #include -#include "hamulce.h" // Pascal unit -#include "friction.h" // Pascal unit +#include "physics/brakes.h" // Pascal unit +#include "physics/friction.h" // Pascal unit /* (C) youBy diff --git a/tests/unit/COVERAGE.md b/tests/unit/COVERAGE.md index 71870c892..b782d23e6 100644 --- a/tests/unit/COVERAGE.md +++ b/tests/unit/COVERAGE.md @@ -1,6 +1,6 @@ # Coverage of the simulation core by the unit tests -These tests characterise the physics of the vehicles (`McZapkie/Mover.cpp`, `hamulce.cpp`, `Oerlikon_ESt.cpp`, `friction.cpp`). They exist to show that refactors of those files, such as splitting `TractionForce` or `RunCommand`, leave the behaviour as it was. This page lists: +These tests characterise the physics of the vehicles (`physics/mover.cpp`, `brakes.cpp`, `oerlikonest.cpp`, `friction.cpp`). They exist to show that refactors of those files, such as splitting `TractionForce` or `RunCommand`, leave the behaviour as it was. This page lists: - what the tests reach; - what nothing in the game ever runs; @@ -14,9 +14,9 @@ Coverage was measured on Windows with MSVC's SanitizerCoverage (`/fsanitize-cove | File | Blocks run, at the start | Now | |---|---|---| -| `Mover.cpp` | 8.9% | 80.7% (3323 of 4118) | -| `hamulce.cpp` | 30% | 76.3% (649 of 851) | -| `Oerlikon_ESt.cpp` | 58% | 87.4% (118 of 135) | +| `mover.cpp` | 8.9% | 80.7% (3323 of 4118) | +| `brakes.cpp` | 30% | 76.3% (649 of 851) | +| `oerlikonest.cpp` | 58% | 87.4% (118 of 135) | | `friction.cpp` | 9% | 90.9% (10 of 11) | The aim is branch coverage with the rest explained below, not 100%. @@ -34,8 +34,8 @@ Nothing creates these objects or calls these functions anywhere in the game, whi - **`TFV4a`** (`GetPF`, `Init`): the FV4a handle of the vehicle definitions creates `TFV4aM`. - **Base implementations always overridden:** `TFricMat::GetFC` (every material, the default P10 too, has its own) and `TPrzekladnik::Update` (every relay has its own). - **Functions without callers:** - - In `hamulce.cpp`: `PF_old`, `TBrake::GetBCF`, `TDriverHandle::OvrldButton`, `TReservoir::pa` and `TBrakeCyl::pa`. - - In `Mover.cpp`: `BrakeVP`, `PipeRatio`, `RealPipeRatio`, `IncBrakeLevel`, `DecBrakeLevel`, `IncBrakePress`, `DecBrakePress`, `MainCtrlActualPowerPos` and `GetExternalCommand`. + - In `brakes.cpp`: `PF_old`, `TBrake::GetBCF`, `TDriverHandle::OvrldButton`, `TReservoir::pa` and `TBrakeCyl::pa`. + - In `mover.cpp`: `BrakeVP`, `PipeRatio`, `RealPipeRatio`, `IncBrakeLevel`, `DecBrakeLevel`, `IncBrakePress`, `DecBrakePress`, `MainCtrlActualPowerPos` and `GetExternalCommand`. - **Inverter failures** of the induction motor drives (`inverter::Failure_Drive`, `Failure_Const`, `Activate`): nothing ever sets them. The cab only shows them. The branches reading them in `TractionForce` can't be reached. ## Code only data no game vehicle has would run @@ -95,7 +95,7 @@ The per-file table further down is from the run before the tests of the parser, | File | Lines run | Functions run | |---|---|---| -| `McZapkie/couplerphysics.cpp` | 93.6% (147 of 157) | 20 of 21 | +| `physics/couplerphysics.cpp` | 93.6% (147 of 157) | 20 of 21 | | `scripting/ladderlogic.cpp` | 4.1% (9 of 217) | 2 of 11 | | `scripting/ladderlogic.h` | 0% (0 of 25) | 0 of 4 | | `scripting/luaprogram.cpp` | 74.7% (334 of 447) | 50 of 66 | @@ -163,9 +163,9 @@ The tests are written for the first two columns, and for what the game doesn't c The tests record the behaviour as it is. The following points may deserve a look by someone who knows how the real vehicles behave. -- **`Random(10) - Random(10)` (`Mover.cpp`, the noise of the control pipe pressure `CntrlPipePress`):** the order the two calls were evaluated in isn't specified. MSVC Release, MSVC Debug and GCC gave different traces, a control pipe pressure mirrored around 5 bar, which failed 32 tests on the Linux CI. Fixed: the draws are sequenced in the order of MSVC Release, which the golden traces were recorded with. +- **`Random(10) - Random(10)` (`mover.cpp`, the noise of the control pipe pressure `CntrlPipePress`):** the order the two calls were evaluated in isn't specified. MSVC Release, MSVC Debug and GCC gave different traces, a control pipe pressure mirrored around 5 bar, which failed 32 tests on the Linux CI. Fixed: the draws are sequenced in the order of MSVC Release, which the golden traces were recorded with. - **`TCommand::Location` isn't initialised** in a new vehicle. The game always sets it through `PutCommand()`, but a test calling `RunCommand()` directly got different results run to run. -- **`CompressorList` is `int[4][9]`** (`MOVER.h`), though its factors are fractions: 0.9 is read as 0. No game vehicle has the list yet. +- **`CompressorList` is `int[4][9]`** (`mover.h`), though its factors are fractions: 0.9 is read as 0. No game vehicle has the list yet. - **A train whose pipe leaks under 2.75 bar before its start-up can't be released:** - Where this happens: an FV4a handle and an LSt valve, for example 4 minutes standing with wagons, waiting for a hot engine. - The cause: the pipe gets cut off the main reservoir (`lock_old` in `UpdatePipePressure`). The AI presses its unlock button only for the lock set by `LPOn` and `LPOff` (`control_main_pipe`). diff --git a/tests/unit/drive.cpp b/tests/unit/drive.cpp index 939a9a626..6c0356ad5 100644 --- a/tests/unit/drive.cpp +++ b/tests/unit/drive.cpp @@ -4,7 +4,7 @@ #include "golden.h" #include "doctest.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" #include "vehicle/fieldshunting.h" namespace test { diff --git a/tests/unit/figures.h b/tests/unit/figures.h index e69e67ef4..576852dbb 100644 --- a/tests/unit/figures.h +++ b/tests/unit/figures.h @@ -3,7 +3,7 @@ #include #include -#include "McZapkie/MOVER.h" +#include "physics/mover.h" namespace test { diff --git a/tests/unit/golden.cpp b/tests/unit/golden.cpp index fcbf01e14..72cd31f9b 100644 --- a/tests/unit/golden.cpp +++ b/tests/unit/golden.cpp @@ -11,7 +11,7 @@ #include #include -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" namespace test { diff --git a/tests/unit/golden.h b/tests/unit/golden.h index cb82ed0da..d53acfa8d 100644 --- a/tests/unit/golden.h +++ b/tests/unit/golden.h @@ -5,7 +5,7 @@ #include #include -#include "McZapkie/MOVER.h" +#include "physics/mover.h" #include "figures.h" #include "invariants.h" diff --git a/tests/unit/invariants.h b/tests/unit/invariants.h index 491edc84b..83e10e7d9 100644 --- a/tests/unit/invariants.h +++ b/tests/unit/invariants.h @@ -5,7 +5,7 @@ #include #include -#include "McZapkie/MOVER.h" +#include "physics/mover.h" namespace test { diff --git a/tests/unit/scenario.cpp b/tests/unit/scenario.cpp index 4af8be18a..ebb5ae0c3 100644 --- a/tests/unit/scenario.cpp +++ b/tests/unit/scenario.cpp @@ -1,7 +1,7 @@ #include "stdafx.h" #include "scenario.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" namespace test { diff --git a/tests/unit/test_brake_cycle.cpp b/tests/unit/test_brake_cycle.cpp index 1dc5a84c1..9598879d8 100644 --- a/tests/unit/test_brake_cycle.cpp +++ b/tests/unit/test_brake_cycle.cpp @@ -4,7 +4,7 @@ #include "golden.h" #include "real_vehicles.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" #include #include diff --git a/tests/unit/test_brake_handles.cpp b/tests/unit/test_brake_handles.cpp index f74edfc03..f86942e4f 100644 --- a/tests/unit/test_brake_handles.cpp +++ b/tests/unit/test_brake_handles.cpp @@ -6,7 +6,7 @@ #include "drive.h" #include "consist.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" using test::definition; using test::vehicle; diff --git a/tests/unit/test_brake_pipe.cpp b/tests/unit/test_brake_pipe.cpp index 664f7262d..7f6b8257e 100644 --- a/tests/unit/test_brake_pipe.cpp +++ b/tests/unit/test_brake_pipe.cpp @@ -1,8 +1,8 @@ #include "stdafx.h" #include "doctest.h" -#include "McZapkie/MOVER.h" -#include "McZapkie/hamulce.h" +#include "physics/mover.h" +#include "physics/brakes.h" #include "consist.h" #include "vehicle.h" diff --git a/tests/unit/test_brake_setting.cpp b/tests/unit/test_brake_setting.cpp index 39b0e2117..ccf393dc4 100644 --- a/tests/unit/test_brake_setting.cpp +++ b/tests/unit/test_brake_setting.cpp @@ -1,8 +1,8 @@ #include "stdafx.h" #include "doctest.h" -#include "McZapkie/MOVER.h" -#include "McZapkie/hamulce.h" +#include "physics/mover.h" +#include "physics/brakes.h" #include "vehicle.h" #include "vehicle/brakesetting.h" #include "vehicle/Driver.h" diff --git a/tests/unit/test_cab.cpp b/tests/unit/test_cab.cpp index 063e70911..eab6e87ca 100644 --- a/tests/unit/test_cab.cpp +++ b/tests/unit/test_cab.cpp @@ -4,7 +4,7 @@ #include "scenario.h" #include "drive.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" #include "utilities/utilities.h" // characterisation of what the cab (Train.cpp) and the AI (Driver.cpp, driverhints.cpp) call on a vehicle diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index 6aee28e98..9534b36db 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -3,8 +3,8 @@ #include "consist.h" #include "drive.h" #include "vehicle.h" -#include "McZapkie/collision.h" -#include "McZapkie/MOVER.h" +#include "physics/collision.h" +#include "physics/mover.h" #include "utilities/Globals.h" #include @@ -12,7 +12,7 @@ #include #include -// collisions past the buffers with physics.collisions new (McZapkie/collision.h): the crush of the ends, the override, +// collisions past the buffers with physics.collisions new (physics/collision.h): the crush of the ends, the override, // the push off the track, and what they do in trains of real vehicles using test::consist; diff --git a/tests/unit/test_commands.cpp b/tests/unit/test_commands.cpp index 6f5730cf7..ca77f078f 100644 --- a/tests/unit/test_commands.cpp +++ b/tests/unit/test_commands.cpp @@ -8,7 +8,7 @@ #include #include -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" // characterisation of the commands vehicles pass each other along the couplers (RunCommand): what each of them // does to every real vehicle, recorded in golden traces (data/golden/commands/), how they travel through a train of diff --git a/tests/unit/test_consist.cpp b/tests/unit/test_consist.cpp index 8305be171..da831c6a8 100644 --- a/tests/unit/test_consist.cpp +++ b/tests/unit/test_consist.cpp @@ -4,7 +4,7 @@ #include "drive.h" #include "golden.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" using test::consist; using test::definition; diff --git a/tests/unit/test_controls.cpp b/tests/unit/test_controls.cpp index ba9404482..251bb18a6 100644 --- a/tests/unit/test_controls.cpp +++ b/tests/unit/test_controls.cpp @@ -3,7 +3,7 @@ #include "scenario.h" #include "drive.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" #include "utilities/Globals.h" #include "utilities/utilities.h" diff --git a/tests/unit/test_coupler_physics.cpp b/tests/unit/test_coupler_physics.cpp index 6785a2cb3..ebffa8e80 100644 --- a/tests/unit/test_coupler_physics.cpp +++ b/tests/unit/test_coupler_physics.cpp @@ -2,13 +2,13 @@ #include "doctest.h" #include "vehicle.h" #include "consist.h" -#include "McZapkie/couplerphysics.h" +#include "physics/couplerphysics.h" #include "utilities/Globals.h" #include #include -// the physical model of the couplings (McZapkie/couplerphysics.h, couplerphysics in eu07.ini): progressive buffers and +// the physical model of the couplings (physics/couplerphysics.h, couplerphysics in eu07.ini): progressive buffers and // draw gear with friction hysteresis, pressed in series, the play of the coupling, its yield and its breaking using test::definition; diff --git a/tests/unit/test_crew.cpp b/tests/unit/test_crew.cpp index d70cbfb4e..112560d61 100644 --- a/tests/unit/test_crew.cpp +++ b/tests/unit/test_crew.cpp @@ -3,7 +3,7 @@ #include "consist.h" #include "drive.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" #include "vehicle/crew.h" // a driver put in a vehicle or taken off it by a "Crew:" putvalues event (eu07/maszyna#510): reading the diff --git a/tests/unit/test_derail_motion.cpp b/tests/unit/test_derail_motion.cpp index 5423f2400..d4a44edda 100644 --- a/tests/unit/test_derail_motion.cpp +++ b/tests/unit/test_derail_motion.cpp @@ -2,8 +2,8 @@ #include "doctest.h" #include "vehicle.h" #include "vehicle/derailmotion.h" -#include "McZapkie/derailment.h" -#include "McZapkie/MOVER.h" +#include "physics/derailment.h" +#include "physics/mover.h" #include "utilities/Globals.h" #include diff --git a/tests/unit/test_derailment.cpp b/tests/unit/test_derailment.cpp index 3afca6a26..5dec1c570 100644 --- a/tests/unit/test_derailment.cpp +++ b/tests/unit/test_derailment.cpp @@ -1,11 +1,11 @@ #include "stdafx.h" #include "doctest.h" -#include "McZapkie/derailment.h" +#include "physics/derailment.h" #include #include -// the criteria of derailment (McZapkie/derailment.h): overturning by the lateral acceleration the cant doesn't +// the criteria of derailment (physics/derailment.h): overturning by the lateral acceleration the cant doesn't // balance, the flange climbing the rail by Nadal's Y/Q, either held over 2 m namespace dr = derailment; diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp index 99b6c0417..1b0d74930 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -1,13 +1,13 @@ #include "stdafx.h" #include "doctest.h" #include "vehicle.h" -#include "McZapkie/derailment.h" -#include "McZapkie/MOVER.h" +#include "physics/derailment.h" +#include "physics/mover.h" #include "utilities/Globals.h" #include -// a vehicle too fast in a curve with physics.derailment of eu07.ini: the criteria of McZapkie/derailment.h checked by +// a vehicle too fast in a curve with physics.derailment of eu07.ini: the criteria of physics/derailment.h checked by // TMoverParameters::check_derailment(), and what the vehicle comes to off the rails using test::definition; diff --git a/tests/unit/test_diesel.cpp b/tests/unit/test_diesel.cpp index c4ea147d3..a902a0195 100644 --- a/tests/unit/test_diesel.cpp +++ b/tests/unit/test_diesel.cpp @@ -3,7 +3,7 @@ #include "scenario.h" #include "drive.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" // characterisation of the diesel engines besides their drive, recorded in golden traces (data/golden/diesel/): // the heat of the engine, its oil and its water circuits, which keep a too cold or too hot engine from starting diff --git a/tests/unit/test_drivingaid.cpp b/tests/unit/test_drivingaid.cpp index b6ae1cc9d..4413384f3 100644 --- a/tests/unit/test_drivingaid.cpp +++ b/tests/unit/test_drivingaid.cpp @@ -4,7 +4,7 @@ #include "real_vehicles.h" #include "vehicle/drivingaid.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" #include #include diff --git a/tests/unit/test_dynamic_brake_diesel.cpp b/tests/unit/test_dynamic_brake_diesel.cpp index fc3f30f27..ddebba682 100644 --- a/tests/unit/test_dynamic_brake_diesel.cpp +++ b/tests/unit/test_dynamic_brake_diesel.cpp @@ -4,7 +4,7 @@ #include "drive.h" #include "real_vehicles.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" // the dynamic brake of the diesel-electric vehicles (Engine: EDBrake=, MaSzyna-EU07/maszyna#82): the traction motors // brake into resistors while the engine runs, with the force of the definition (EDBrakeFmax, the power limit diff --git a/tests/unit/test_elf_controller.cpp b/tests/unit/test_elf_controller.cpp index bb7d34b74..f480951e1 100644 --- a/tests/unit/test_elf_controller.cpp +++ b/tests/unit/test_elf_controller.cpp @@ -3,7 +3,7 @@ #include "consist.h" #include "drive.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" #include #include diff --git a/tests/unit/test_est3al2_relay.cpp b/tests/unit/test_est3al2_relay.cpp index 63296901b..be4adf244 100644 --- a/tests/unit/test_est3al2_relay.cpp +++ b/tests/unit/test_est3al2_relay.cpp @@ -2,7 +2,7 @@ #include "doctest.h" #include "vehicle.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" #include #include diff --git a/tests/unit/test_feed_pipe.cpp b/tests/unit/test_feed_pipe.cpp index 55816af43..2164d2784 100644 --- a/tests/unit/test_feed_pipe.cpp +++ b/tests/unit/test_feed_pipe.cpp @@ -1,8 +1,8 @@ #include "stdafx.h" #include "doctest.h" -#include "McZapkie/MOVER.h" -#include "McZapkie/hamulce.h" +#include "physics/mover.h" +#include "physics/brakes.h" #include "consist.h" #include "vehicle.h" diff --git a/tests/unit/test_genset.cpp b/tests/unit/test_genset.cpp index c3b4f3015..a00ea257e 100644 --- a/tests/unit/test_genset.cpp +++ b/tests/unit/test_genset.cpp @@ -4,7 +4,7 @@ #include "drive.h" #include "golden.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" // the genset of a dual-mode vehicle (eu07/maszyna#536): a second source of the traction circuit of an induction // motor vehicle next to its pantographs, which the traction selector picks. the vehicle is the game's E6ACT diff --git a/tests/unit/test_line_contactors_interlock.cpp b/tests/unit/test_line_contactors_interlock.cpp index a025d4a69..28bfee94e 100644 --- a/tests/unit/test_line_contactors_interlock.cpp +++ b/tests/unit/test_line_contactors_interlock.cpp @@ -4,7 +4,7 @@ #include "drive.h" #include "vehicle.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" // the line contactors interlocked with the fans of the traction motors (eu07/maszyna#460): on the ET42 the fans of a // section run off its own converter, and with them switched off the line contactors of that section don't close. diff --git a/tests/unit/test_pressure_switch.cpp b/tests/unit/test_pressure_switch.cpp index 65672b252..df142574d 100644 --- a/tests/unit/test_pressure_switch.cpp +++ b/tests/unit/test_pressure_switch.cpp @@ -2,7 +2,7 @@ #include "doctest.h" #include "drive.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" // the pressure switch of the EP05 (git.eu07.pl eu07/maszyna#48). the pressure switch of the simulator is two // conditions in one: it cuts the traction motors off above 2 bar in the brake cylinders and below 3.6 bar in the diff --git a/tests/unit/test_timetable.cpp b/tests/unit/test_timetable.cpp index a41aafcce..1066edd29 100644 --- a/tests/unit/test_timetable.cpp +++ b/tests/unit/test_timetable.cpp @@ -2,7 +2,7 @@ #include "doctest.h" #include "vehicle.h" -#include "McZapkie/MOVER.h" +#include "physics/mover.h" #include "utilities/utilities.h" #include "vehicle/timetableservice.h" #include "world/timetablereader.h" diff --git a/tests/unit/test_track_buckle_derailment.cpp b/tests/unit/test_track_buckle_derailment.cpp index 2f5d99592..98583743e 100644 --- a/tests/unit/test_track_buckle_derailment.cpp +++ b/tests/unit/test_track_buckle_derailment.cpp @@ -1,6 +1,6 @@ #include "stdafx.h" #include "doctest.h" -#include "McZapkie/derailment.h" +#include "physics/derailment.h" #include "world/TrackBuckle.h" #include diff --git a/tests/unit/test_traction.cpp b/tests/unit/test_traction.cpp index 6da4ca506..6a9bb544c 100644 --- a/tests/unit/test_traction.cpp +++ b/tests/unit/test_traction.cpp @@ -9,7 +9,7 @@ #include "real_vehicles.h" #include "scenario.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" using test::definition; using test::vehicle; diff --git a/tests/unit/vehicle.h b/tests/unit/vehicle.h index 05c03dbf6..601ece1c5 100644 --- a/tests/unit/vehicle.h +++ b/tests/unit/vehicle.h @@ -9,7 +9,7 @@ #include -#include "McZapkie/MOVER.h" +#include "physics/mover.h" namespace test { diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index a5ac87be6..751221ecb 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -1060,7 +1060,7 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& if (token == "physics.derailment") { - // new: the physical criteria (McZapkie/derailment.h), old: the legacy draw, off: no derailment from the speed, + // new: the physical criteria (physics/derailment.h), old: the legacy draw, off: no derailment from the speed, // monitor: the legacy draw, and the criteria to the log std::string model; ParseOne(Parser, model, 1); @@ -1076,7 +1076,7 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& if (token == "physics.collisions") { - // new: the crush of the ends past the buffers (McZapkie/collision.h), old: the legacy rule, monitor: the legacy + // new: the crush of the ends past the buffers (physics/collision.h), old: the legacy rule, monitor: the legacy // rule, and the crush to the log std::string model; ParseOne(Parser, model, 1); diff --git a/utilities/Globals.h b/utilities/Globals.h index e5887be33..a98d5e60a 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -359,14 +359,14 @@ struct global_settings { // buckles the scenery enters and its trackbuckle events; automatic, also by the temperature of the rails at the weak places enum class track_buckling_mode { off, scenery, automatic }; track_buckling_mode track_buckling = track_buckling_mode::scenery; - // the physical model of the couplings (McZapkie/couplerphysics.h): progressive buffers and draw gear with hysteresis, + // the physical model of the couplings (physics/couplerphysics.h): progressive buffers and draw gear with hysteresis, // the play of the coupling, its yield and breaking; the legacy model of TMoverParameters::CouplerForce() without it. // it covers the player's train and the trains it closes in on (vehicle_table::update_coupler_physics()), or every // train with coupler_physics_all bool coupler_physics = false; bool coupler_physics_all = false; // a vehicle too fast in a curve (physics.derailment in eu07.ini): new, it overturns or its flange climbs the rail - // by the criteria of McZapkie/derailment.h held over 2 m, and slides on with the friction of the ballast; old, the + // by the criteria of physics/derailment.h held over 2 m, and slides on with the friction of the ballast; old, the // legacy draw of the lateral acceleration against the gauge to the height of the vehicle in every step, which stops // it; off, it stays on the rails at any speed; monitor, the legacy draw decides and the log tells where the criteria // would derail a vehicle (derailment monitor:, once for a vehicle on a track), for the run of a scenery as it was. @@ -375,7 +375,7 @@ struct global_settings { enum class derailment_model { off, old, physical, monitor }; derailment_model derailment = derailment_model::monitor; // the collisions of rail vehicles past their buffers (physics.collisions in eu07.ini): new, the ends crush, a vehicle - // may ride up onto the other one or be pushed off the track (McZapkie/collision.h); old, the legacy rule of the safe + // may ride up onto the other one or be pushed off the track (physics/collision.h); old, the legacy rule of the safe // closing speed weighed by the masses; monitor, the legacy rule decides and the log tells what the crush would be // (collision monitor:, once for a hit). the road vehicles of the traffic keep the legacy rule with any enum class collision_model { old, physical, monitor }; diff --git a/utilities/translation.cpp b/utilities/translation.cpp index 58c9746ab..24c1946bc 100644 --- a/utilities/translation.cpp +++ b/utilities/translation.cpp @@ -15,7 +15,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/translation.h" #include "utilities/Logs.h" #include "utilities/Globals.h" -#include "MOVER.h" +#include "physics/mover.h" void locale::init() { diff --git a/vehicle/Camera.cpp b/vehicle/Camera.cpp index fe1a85c9a..234483ee4 100644 --- a/vehicle/Camera.cpp +++ b/vehicle/Camera.cpp @@ -17,7 +17,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "vehicle/Driver.h" #include "vehicle/DynObj.h" -#include "MOVER.h" +#include "physics/mover.h" //--------------------------------------------------------------------------- diff --git a/vehicle/Driver.h b/vehicle/Driver.h index a6985bcd6..539542725 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -13,7 +13,7 @@ http://mozilla.org/MPL/2.0/. #include #include "utilities/Classes.h" #include "utilities/utilities.h" -#include "MOVER.h" +#include "physics/mover.h" #include "audio/sound.h" #include "vehicle/DynObj.h" #include "world/mtable.h" diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index cfe479a94..c37efe824 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -3130,7 +3130,7 @@ derail_motion::formation TDynamicObject::track_bed() const { int TDynamicObject::outward_side() const { // the track as designed turns from the rear axle to the front one: the outside of its curve, or its inside where a - // buckle bends the line the other way more than the curve does (the criteria of derailment, McZapkie/derailment.h) + // buckle bends the line the other way more than the curve does (the criteria of derailment, physics/derailment.h) if( auto const design { std::sin( Axle1.vAngles.z - Axle0.vAngles.z ) }; std::abs( design ) >= 1e-4 ) { auto const outside { design > 0.0 ? -1 : 1 }; return MoverParameters->DerailAcceleration < 0.0 ? -outside : outside; diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index e5ea881e0..389e6edef 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -14,7 +14,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Classes.h" #include "interfaces/IMaterial.h" -#include "MOVER.h" +#include "physics/mover.h" #include "world/TrkFoll.h" #include "vehicle/Button.h" #include "vehicle/AirCoupler.h" @@ -774,7 +774,7 @@ private: void crop_off_track_terrain(); // the bed of the track at the axles, the level direction of the track there, and the side the derailment throws the // vehicle to (1 the left of the front, -1 the right, 0 none): out of the curve of the track as designed, into it - // where a buckle bends the line the other way more (McZapkie/derailment.h); on a straight track out of the turn of + // where a buckle bends the line the other way more (physics/derailment.h); on a straight track out of the turn of // the path as it lies, a buckle on it derail_motion::formation track_bed() const; glm::dvec3 track_front() const; diff --git a/vehicle/brakesetting.cpp b/vehicle/brakesetting.cpp index 918da3d02..fd7378f8c 100644 --- a/vehicle/brakesetting.cpp +++ b/vehicle/brakesetting.cpp @@ -10,8 +10,8 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/brakesetting.h" -#include "McZapkie/MOVER.h" -#include "McZapkie/hamulce.h" +#include "physics/mover.h" +#include "physics/brakes.h" #include "vehicle/Driver.h" #include diff --git a/vehicle/crew.cpp b/vehicle/crew.cpp index d32bcc82c..360952c35 100644 --- a/vehicle/crew.cpp +++ b/vehicle/crew.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/crew.h" -#include "McZapkie/MOVER.h" +#include "physics/mover.h" #include "vehicle/handover.h" namespace crew { diff --git a/vehicle/derailmotion.cpp b/vehicle/derailmotion.cpp index 89b9a1831..252ba7f4d 100644 --- a/vehicle/derailmotion.cpp +++ b/vehicle/derailmotion.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/derailmotion.h" -#include "McZapkie/derailment.h" +#include "physics/derailment.h" #include #include diff --git a/vehicle/derailmotion.h b/vehicle/derailmotion.h index 8513e7e13..4e7163ae8 100644 --- a/vehicle/derailmotion.h +++ b/vehicle/derailmotion.h @@ -19,7 +19,7 @@ http://mozilla.org/MPL/2.0/. #include -// a rail vehicle off the rails (physics.derailment new, see McZapkie/derailment.h for when it derails): from then on +// a rail vehicle off the rails (physics.derailment new, see physics/derailment.h for when it derails): from then on // it doesn't follow the track any more, it moves on the ground by itself until the friction stops it. // // along: the longitudinal motion stays with the physics of the vehicle (TMoverParameters), which brakes it with the @@ -39,7 +39,7 @@ http://mozilla.org/MPL/2.0/. // the height and the attitude: the ground under the supports of the vehicle (the ends of its wheelbase, the wheels // of both sides) gives its height, its pitch and its roll; it doesn't sink into the ground, it falls off a step // tipping over: about the wheels of one side, the body as a rigid one with the lean of its suspension, so it tips at -// the very lateral acceleration the wheel unloading of McZapkie/derailment.h reaches 1 at. what tips it: the +// the very lateral acceleration the wheel unloading of physics/derailment.h reaches 1 at. what tips it: the // overturning in the curve while its outer wheels still run on the rail (the curve keeps pushing it out as v^2/R, // the excess over the limit the faster it tips), the slope of the ground across it, and the friction under it // while it slides sideways. once over its tipping angle it falls on its side, at 90 degrees, and stays there @@ -67,7 +67,7 @@ inline constexpr double guided_friction{0.1}; // of the wheels, or of the body on its side, sliding across the heading inline constexpr double lateral_friction{0.5}; // the friction along the heading: upright on its wheels on the sleepers and the ballast, rising to the friction of a -// vehicle on its side (McZapkie/derailment.h) as it tips over +// vehicle on its side (physics/derailment.h) as it tips over double sliding_friction(double Tipping, bool Guided); // ---- the way the vehicle leaves the track @@ -299,7 +299,7 @@ struct vehicle_shape { double centre_of_gravity{1.5}; // its height above the rail [m] double contact_spacing{1.5}; // of the wheels of a wheelset [m] double base{10.0}; // between the bogie pivots or the outer axles, which it rests on lengthwise [m] - // the lean of the body on the suspension, as McZapkie/derailment.h takes it: flexibility and roll centre + // the lean of the body on the suspension, as physics/derailment.h takes it: flexibility and roll centre double flexibility{0.4}; double roll_centre{0.5}; // [kg] for the forces of the couplings on it; none: they don't move it diff --git a/vehicle/drivingaid.cpp b/vehicle/drivingaid.cpp index df8fc37a7..a7d4f2af2 100644 --- a/vehicle/drivingaid.cpp +++ b/vehicle/drivingaid.cpp @@ -10,8 +10,8 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/drivingaid.h" -#include "McZapkie/MOVER.h" -#include "McZapkie/hamulce.h" +#include "physics/mover.h" +#include "physics/brakes.h" #include #include diff --git a/vehicle/enginestart.cpp b/vehicle/enginestart.cpp index feb4445ce..a826bb19c 100644 --- a/vehicle/enginestart.cpp +++ b/vehicle/enginestart.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/enginestart.h" -#include "McZapkie/MOVER.h" +#include "physics/mover.h" #include "utilities/utilities.h" namespace engine_start { diff --git a/vehicle/handover.cpp b/vehicle/handover.cpp index a36ccde81..878afdf3d 100644 --- a/vehicle/handover.cpp +++ b/vehicle/handover.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/handover.h" -#include "McZapkie/MOVER.h" +#include "physics/mover.h" namespace handover { diff --git a/vehicle/lightsprogrammer.h b/vehicle/lightsprogrammer.h index 9ae8c2ab0..c603ace27 100644 --- a/vehicle/lightsprogrammer.h +++ b/vehicle/lightsprogrammer.h @@ -11,7 +11,7 @@ http://mozilla.org/MPL/2.0/. #include -#include "McZapkie/MOVER.h" +#include "physics/mover.h" // the lights the light preset selector (programmer) of the occupied cab gives one vehicle of the consist namespace lights_programmer { diff --git a/vehicle/mainctrlact.h b/vehicle/mainctrlact.h index df61aa061..eb594473e 100644 --- a/vehicle/mainctrlact.h +++ b/vehicle/mainctrlact.h @@ -9,7 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once -#include "McZapkie/MOVER.h" +#include "physics/mover.h" // the position the controller position marker of the cab (mainctrlact:) shows namespace main_ctrl_act { diff --git a/vehicle/smoke.cpp b/vehicle/smoke.cpp index f5f64bef0..88897c722 100644 --- a/vehicle/smoke.cpp +++ b/vehicle/smoke.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/smoke.h" -#include "McZapkie/MOVER.h" +#include "physics/mover.h" namespace smoke { diff --git a/vehicle/timetableservice.cpp b/vehicle/timetableservice.cpp index 913e9d2d4..cca7a5e17 100644 --- a/vehicle/timetableservice.cpp +++ b/vehicle/timetableservice.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/timetableservice.h" -#include "McZapkie/MOVER.h" +#include "physics/mover.h" namespace timetable { diff --git a/world/TrackCheck.h b/world/TrackCheck.h index e6e99fb2b..c7b40feba 100644 --- a/world/TrackCheck.h +++ b/world/TrackCheck.h @@ -9,7 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once -#include "McZapkie/derailment.h" +#include "physics/derailment.h" #include "world/TrackUneven.h" #include @@ -20,7 +20,7 @@ http://mozilla.org/MPL/2.0/. #include // the check of the geometry of the rail tracks of a scenery (physics.trackcheck yes in eu07.ini): what the criteria of -// derailment (McZapkie/derailment.h) and the plain rules of the track find suspicious, to the log once the scenery +// derailment (physics/derailment.h) and the plain rules of the track find suspicious, to the log once the scenery // loaded, so a run can tell a faulty scenery from a faulty simulation. one line for a track with all it found // ("trackcheck: : ..."), and a summary with the count of each kind. the damage flags are only counted: sceneries // set them for the jolts of a worn track (damage 31 on every track of line 107). a curve without a speed limit of its From 653aec7fbebaefc0a861a4e1aa91d80087baceec Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Fri, 27 Nov 2026 17:47:24 +0100 Subject: [PATCH 003/123] refactor(physics): physics/mover.cpp split into the files of its subsystems The 15 900 lines of mover.cpp go into physics/mover/, a file for each part of the vehicle, from 220 to 1850 lines: mover.cpp the vehicle as a body: construction, forces, movement couplers.cpp attaching, detaching, coupler forces, automatic coupling collisions.cpp collisions of the ends, crush, derailment, repair pneumatics.cpp brake controls, pipes, valves, compressor, spring brake electrics.cpp batteries, main switch, pantographs, converter, heating, lights, genset traction.cpp traction motors and forces of each drive, relays, fuses, dynamic brake controllers.cpp master and secondary controllers, automatic relay, camshaft, integrated controller, speed control diesel.cpp diesel engine, gearbox, clutch, hydraulic transmission cab.cpp cab activation, direction, horns doors.cpp doors and the load exchange securitysystem.cpp vigilance, cab signalling, radio-stop commands.cpp commands passed between the vehicles fizparser.cpp reading the .fiz: the parser and its tables fizsections.cpp reading the .fiz: the sections and their keywords setup.cpp checks, brake valves, handles and pipes after loading Every definition moved as it was, byte for byte, in its original order. The helpers of the anonymous namespaces went with the file using them; the seven used by several files (CouplerTune, square, DirPatch, DirF, TableInterpolation, compression_at, issection) are declared or defined in physics/mover/internal.h, which only these files include. `git blame -C -C` follows the lines into the new files. 1142/1142 tests, golden traces exact against staging 62f7a29b. --- CMakeLists.txt | 17 +- physics/mover.cpp | 15913 ----------------------------- physics/mover/cab.cpp | 250 + physics/mover/collisions.cpp | 875 ++ physics/mover/commands.cpp | 807 ++ physics/mover/controllers.cpp | 1529 +++ physics/mover/couplers.cpp | 578 ++ physics/mover/diesel.cpp | 1540 +++ physics/mover/doors.cpp | 592 ++ physics/mover/electrics.cpp | 1390 +++ physics/mover/fizparser.cpp | 1341 +++ physics/mover/fizsections.cpp | 1827 ++++ physics/mover/internal.h | 33 + physics/mover/mover.cpp | 1351 +++ physics/mover/pneumatics.cpp | 1621 +++ physics/mover/securitysystem.cpp | 298 + physics/mover/setup.cpp | 471 + physics/mover/traction.cpp | 1881 ++++ 18 files changed, 16400 insertions(+), 15914 deletions(-) delete mode 100644 physics/mover.cpp create mode 100644 physics/mover/cab.cpp create mode 100644 physics/mover/collisions.cpp create mode 100644 physics/mover/commands.cpp create mode 100644 physics/mover/controllers.cpp create mode 100644 physics/mover/couplers.cpp create mode 100644 physics/mover/diesel.cpp create mode 100644 physics/mover/doors.cpp create mode 100644 physics/mover/electrics.cpp create mode 100644 physics/mover/fizparser.cpp create mode 100644 physics/mover/fizsections.cpp create mode 100644 physics/mover/internal.h create mode 100644 physics/mover/mover.cpp create mode 100644 physics/mover/pneumatics.cpp create mode 100644 physics/mover/securitysystem.cpp create mode 100644 physics/mover/setup.cpp create mode 100644 physics/mover/traction.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index b6f35af69..6b723841c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -57,6 +57,7 @@ set(CMAKE_CXX_STANDARD 20) file(GLOB HEADERS "*.h" "Console/*.h" "physics/*.h" +"physics/mover/*.h" "gl/*.h" "network/*.h" "vr/*.h" @@ -742,7 +743,21 @@ set(CORE_SOURCES "audio/startsample.cpp" "physics/friction.cpp" "physics/brakes.cpp" -"physics/mover.cpp" +"physics/mover/mover.cpp" +"physics/mover/cab.cpp" +"physics/mover/collisions.cpp" +"physics/mover/commands.cpp" +"physics/mover/controllers.cpp" +"physics/mover/couplers.cpp" +"physics/mover/diesel.cpp" +"physics/mover/doors.cpp" +"physics/mover/electrics.cpp" +"physics/mover/fizparser.cpp" +"physics/mover/fizsections.cpp" +"physics/mover/pneumatics.cpp" +"physics/mover/securitysystem.cpp" +"physics/mover/setup.cpp" +"physics/mover/traction.cpp" "physics/couplerphysics.cpp" "physics/derailment.cpp" "physics/collision.cpp" diff --git a/physics/mover.cpp b/physics/mover.cpp deleted file mode 100644 index 384f1a684..000000000 --- a/physics/mover.cpp +++ /dev/null @@ -1,15913 +0,0 @@ -/* -This Source Code Form is subject to the -terms of the Mozilla Public License, v. -2.0. If a copy of the MPL was not -distributed with this file, You can -obtain one at -http://mozilla.org/MPL/2.0/. -*/ - -#include "stdafx.h" -#include "physics/mover.h" - -#include "vehicle/DynObj.h" -#include "physics/oerlikonest.h" -#include "utilities/Globals.h" -#include "utilities/Logs.h" -#include "utilities/Timer.h" -#include "utilities/parser.h" -#include "simulation/simulation.h" -#include "vehicle/fieldshunting.h" - -#include -#include -#include -#include -#include -#include -#include -#include -//--------------------------------------------------------------------------- - -// Ra: tu należy przenosić funcje z mover.pas, które nie są z niego wywoływane. -// Jeśli jakieś zmienne nie są używane w mover.pas, też można je przenosić. -// Przeniesienie wszystkiego na raz zrobiło by zbyt wielki chaos do ogarnięcia. - -const double dEpsilon = 0.01; // 1cm (zależy od typu sprzęgu...) -const double CouplerTune = 0.1; // skalowanie tlumiennosci - -int ConversionError = 0; - -std::vector const TMoverParameters::eimc_labels = {"dfic: ", "dfmax:", "p: ", "scfu: ", "cim: ", "icif: ", "Uzmax:", "Uzh: ", "DU: ", "I0: ", "fcfu: ", - "F0: ", "a1: ", "Pmax: ", "Fh: ", "Ph: ", "Vh0: ", "Vh1: ", "Imax: ", "abed: ", "eped: "}; - -std::vector const TMoverParameters::eimv_labels = { - "Fkrt:", "Fmax:", "ks: ", "df: ", "fp: ", "Us: ", "pole:", "Ic: ", "If: ", "M: ", "Fr: ", "Ipoj:", "Pm: ", "Pe: ", "eta: ", "fkr: ", "Uzsm:", "Pmax:", "Fzad:", "Imax:", "Fful:"}; - -inline double square(double val) // SQR() zle liczylo w current() ... -{ - return val * val; -} - -double ComputeCollision(double &v1, double &v2, double m1, double m2, double beta, bool vc) -{ // oblicza zmiane predkosci i przyrost pedu wskutek kolizji - assert(beta < 1.0); - - if (v1 < v2 && vc == true) - return 0; - else - { - double sum = m1 + m2; - double w1 = (m2 * v2 * 2.0 + v1 * (m1 - m2)) / sum; - double w2 = (m1 * v1 * 2.0 + v2 * (m2 - m1)) / sum; - // the collision changes the velocities directly: the bounce loses energy in the velocities relative to the - // centre of mass only, the pair keeps its momentum. scaling the velocities themselves braked the vehicles - // down with every step their couplers spent stretched or pressed in all the way (eu07/maszyna#553) - auto const centre{(m1 * v1 + m2 * v2) / sum}; - auto const restitution{std::sqrt(1.0 - beta)}; - v1 = std::lerp(centre, w1, restitution); - v2 = std::lerp(centre, w2, restitution); - return m1 * (w2 - w1) * (1 - beta); - } -} - -int DirPatch(int Coupler1, int Coupler2) -{ // poprawka dla liczenia sil przy ustawieniu przeciwnym obiektow - return Coupler1 != Coupler2 ? 1 : -1; -} - -namespace -{ - -// physics.collisions new: a rail vehicle derailed the legacy way keeps the deceleration of the legacy model, g, as the -// friction of its weight, and the forces of the vehicles coupled to it act on it as on any other: the train behind it -// pushes it on, and it holds the train back. alone it stops as the legacy model has it. the legacy model stops it -// whatever pushes it, and the train behind it stopped at once against it, in a hit no train had -bool legacy_derailed_slides(TMoverParameters const &Vehicle) -{ - return Global.collisions == global_settings::collision_model::physical && TestFlag(Vehicle.CategoryFlag, 1) && TestFlag(Vehicle.DamageFlag, dtrain_out) && - Vehicle.Derailed == derailment::outcome::none; -} - -// a derailed vehicle tears its brake hoses: the brake pipe vents and the rest of the train brakes in emergency -void tear_brake_hoses(TMoverParameters &Vehicle) -{ - if (std::any_of(std::begin(Vehicle.Couplers), std::end(Vehicle.Couplers), [](auto const &Coupler) { return (Coupler.CouplingFlag & coupling::brakehose) == coupling::brakehose; })) - { - Vehicle.AlarmChainFlag = true; - } -} - -} // namespace - -int DirF(int CouplerN) -{ - switch (CouplerN) - { - case 0: - return -1; - case 1: - return 1; - default: - return 0; - } -} - -void TSecuritySystem::set_enabled(bool e) -{ - if (vigilance_enabled || cabsignal_enabled || radiostop_enabled) - enabled = e; - if (CabDependent) - cabactive = 0; -} - -void TSecuritySystem::acknowledge_press() -{ - pressed = true; - - if (vigilance_timer > AwareDelay) - { - alert_timer = 0.0; - vigilance_timer = 0.0; - return; - } - vigilance_timer = 0.0; - - if (!separate_acknowledge && cabsignal_active && !cabsignal_lock) - { - cabsignal_active = false; - alert_timer = 0.0; - } -} - -void TSecuritySystem::acknowledge_release() -{ - pressed = false; - - if (press_timer > MaxHoldTime) - alert_timer = 0.0; - press_timer = 0.0; -} - -void TSecuritySystem::cabsignal_reset() -{ - if (cabsignal_active && !cabsignal_lock) - { - cabsignal_active = false; - alert_timer = 0.0; - } -} - -void TSecuritySystem::update(double dt, double vel, bool pwr, int cab) -{ - if (!enabled || !pwr || DebugModeFlag) - { - power = pwr; - cabsignal_active = false; - vigilance_timer = 0.0; - alert_timer = 0.0; - press_timer = 0.0; - return; - } - - bool just_powered_on = !power && pwr; - bool just_activated = CabDependent && cabactive != cab; - - /* enabling battery */ - if (cabsignal_enabled && (just_powered_on || just_activated)) - { - cabsignal_active = true; - alert_timer = SoundSignalDelay; - } - - power = pwr; - velocity = vel; - cabactive = cab; - - if (vigilance_suspended) - { - // the vigilance device is switched off: no time counts towards a new alarm, of the alerter or of the button held - // too long. an alarm already on, with the emergency braking it leads to, stays until it's acknowledged as usual - if (vigilance_timer <= AwareDelay) - vigilance_timer = 0.0; - if (press_timer <= MaxHoldTime) - press_timer = 0.0; - } - else - { - if (vigilance_enabled && velocity > AwareMinSpeed) - vigilance_timer += dt; - - if (pressed && (!is_sifa || velocity > AwareMinSpeed)) - press_timer += dt; - } - - if (vigilance_timer > AwareDelay || press_timer > MaxHoldTime || cabsignal_active) - alert_timer += dt; -} - -void TSecuritySystem::set_cabsignal() -{ - if (cabsignal_enabled && power) - cabsignal_active = true; -} - -bool TSecuritySystem::has_separate_acknowledge() const -{ - return separate_acknowledge; -} - -bool TSecuritySystem::is_blinking() const -{ - if (!power) - return false; - - return alert_timer > 0.0; -} - -bool TSecuritySystem::is_vigilance_blinking() const -{ - if (!power) - return false; - - return press_timer > MaxHoldTime || vigilance_timer > AwareDelay; -} - -bool TSecuritySystem::is_cabsignal_blinking() const -{ - if (!power) - return false; - - return cabsignal_active; -} - -bool TSecuritySystem::is_beeping() const -{ - if (!power) - return false; - - return alert_timer > SoundSignalDelay && (!separate_acknowledge || is_vigilance_blinking()); -} - -bool TSecuritySystem::is_cabsignal_beeping() const -{ - if (!power) - return false; - - return alert_timer > SoundSignalDelay && is_cabsignal_blinking(); -} - -bool TSecuritySystem::is_braking() const -{ - if (!power && enabled) - return true; - - return alert_timer > SoundSignalDelay + EmergencyBrakeDelay; -} - -bool TSecuritySystem::radiostop_available() const -{ - return radiostop_enabled; -} - -void TSecuritySystem::set_cabsignal_lock(bool v) -{ - cabsignal_lock = v; -} - -void TSecuritySystem::set_shunt_mode(bool const State) -{ - vigilance_suspended = State && AwareOffInShuntMode; -} - -bool TSecuritySystem::is_engine_blocked() const -{ - if (!is_sifa) - return false; - - return velocity < AwareMinSpeed && pressed; -} - -void TSecuritySystem::load(std::string const &line, double Vmax) -{ - std::string awaresystem = extract_value("AwareSystem", line); - if (awaresystem.find("Active") != std::string::npos) - vigilance_enabled = true; - if (awaresystem.find("CabSignal") != std::string::npos) - cabsignal_enabled = true; - if (awaresystem.find("Sifa") != std::string::npos) - is_sifa = true; - if (awaresystem.find("SeparateAcknowledge") != std::string::npos) - separate_acknowledge = true; - - extract_value(AwareDelay, "AwareDelay", line, ""); - AwareMinSpeed = 0.1 * Vmax; // domyślnie 10% Vmax - extract_value(AwareMinSpeed, "AwareMinSpeed", line, ""); - extract_value(SoundSignalDelay, "SoundSignalDelay", line, ""); - extract_value(EmergencyBrakeDelay, "EmergencyBrakeDelay", line, ""); - extract_value(MaxHoldTime, "MaxHoldTime", line, ""); - extract_value(radiostop_enabled, "RadioStop", line, ""); - extract_value(MagnetLocation, "MagnetLocation", line, ""); - extract_value(CabDependent, "CabDependent", line, ""); - extract_value(AwareOffInShuntMode, "AwareOffInShuntMode", line, ""); -} - -double TableInterpolation(std::map &Map, double Parameter) -{ - if (Map.empty()) - return 0.0; - if (Map.size() == 1) - return Map.begin()->second; - - auto lower = Map.lower_bound(Parameter); - auto upper = lower; - - if (lower != Map.begin()) - lower--; - else - upper++; - - if (upper == Map.end()) - { - lower--; - upper--; - } - double ratio = (upper->second - lower->second) / (upper->first - lower->first); - return lower->second + (Parameter - lower->first) * ratio; -} - -// ************************************************************************************************* -// Q: 20160716 -// Obliczanie natężenie prądu w silnikach -// ************************************************************************************************* -double TMoverParameters::Current(double n, double U) -{ - // wazna funkcja - liczy prad plynacy przez silniki polaczone szeregowo lub rownolegle - // w zaleznosci od polozenia nastawnikow MainCtrl i ScndCtrl oraz predkosci obrotowej n - // a takze wywala bezpiecznik nadmiarowy gdy za duzy prad lub za male napiecie - // jest takze mozliwosc uszkodzenia silnika wskutek nietypowych parametrow - - double R; - double MotorCurrent; - double Mn; // przujmuje int, ale dla poprawnosci obliczeń - double Bn; - - UpdateSeriesMotorDynamicBrakeFlag(); - - ResistorsFlag = RList[MainCtrlActualPos].R > 0.01; // and (!DelayCtrlFlag) - ResistorsFlag = ResistorsFlag || (DynamicBrakeFlag == true && DynamicBrakeType == dbrake_automatic); - - if (TrainType == train_type::et22 && DelayCtrlFlag && MainCtrlActualPos > 1) - Bn = 1.0 - 1.0 / RList[MainCtrlActualPos].Bn; - else - Bn = 1; // to jest wykonywane dla EU07 - - R = RList[MainCtrlActualPos].R * Bn + CircuitRes; - - if (TrainType != train_type::emu || Imin != IminLo || false == ScndS) - { - // yBARC - boczniki na szeregu poprawnie - Mn = RList[MainCtrlActualPos].Mn; // to jest wykonywane dla EU07 - } - else - { - Mn = RList[MainCtrlActualPos].Mn * RList[MainCtrlActualPos].Bn; - if (RList[MainCtrlActualPos].Bn > 1) - { - R = CircuitRes; - } - } - - if (DynamicBrakeFlag && !FuseFlag && DynamicBrakeType == dbrake_automatic && Power110vIsAvailable && Mains) // hamowanie EP09 //TUHEX - { - // TODO: zrobic bardziej uniwersalne nie tylko dla EP09 - MotorCurrent = -std::max(motor_param(0).fi * (Vadd / (Vadd + motor_param(0).Isat) - motor_param(0).fi0), 0.) * n * 2.0 / DynamicBrakeRes; - } - else if (RList[MainCtrlActualPos].Bn == 0 || false == StLinFlag) - { - // wylaczone - MotorCurrent = 0; - } - else - { // wlaczone... - MotorCurrent = SeriesMotorCurrent(n, U, R, Mn); - } - // writepaslog("MotorCurrent ", FloatToStr(MotorCurrent)); - - if (DynamicBrakeType == dbrake_switch && (BrakePress > 2.0 || PipePress < 3.6)) - { - Im = 0; - // Im:=0; - Itot = 0; - } - else - Im = MotorCurrent; - - EnginePower = abs(Itot) * (1 + RList[MainCtrlActualPos].Mn) * abs(U) / 1000.0; - - MotorFailuresCheck(n); - - return Im; -} - -// the automatic dynamic brake of the series motors (EP09, the units) on or off, and the distributor told of it -void TMoverParameters::UpdateSeriesMotorDynamicBrakeFlag() -{ - // i dzialanie hamulca ED w EP09 - if (DynamicBrakeType == dbrake_automatic && TrainType != train_type::emu) - { - if ((Hamulec->GetEDBCP() < 0.25 && Vadd < 1) || BrakePress > 2.1) - DynamicBrakeFlag = false; - else if (BrakePress > 0.25 && Hamulec->GetEDBCP() > 0.25) - DynamicBrakeFlag = true; - DynamicBrakeFlag = DynamicBrakeFlag && Power110vIsAvailable; - } - if (DynamicBrakeType == dbrake_automatic && TrainType == train_type::emu) - { - DynamicBrakeFlag = Power110vIsAvailable && (TUHEX_Active || Vadd > TUHEX_MinIw) && DynamicBrakeEMUStatus; - } - - // wylacznik cisnieniowy yBARC - to jest chyba niepotrzebne tutaj Q: no to usuwam... - - // BrakeSubsystem = ss_LSt; - // if (BrakeSubsystem == ss_LSt) WriteLog("LSt"); - // if (BrakeSubsystem == ss_LSt) // zrobiona funkcja virtualna - if (DynamicBrakeFlag) - { - Hamulec->SetED(abs(Im / 350)); // hamulec ED na EP09 dziala az do zatrzymania lokomotywy - //- WriteLog("A"); - } - else - { - Hamulec->SetED(0); - //- WriteLog("B"); - } -} - -// the current of the series motors connected, at the revolutions n and the voltage U, through the resistance R of -// Mn motors in series -double TMoverParameters::SeriesMotorCurrent(double const n, double const U, double const R, double const Mn) const -{ - double MotorCurrent{0.0}; - double Rz; - int SP = ScndCtrlActualPos; - - if (ScndCtrlActualPos < 255) // tak smiesznie bede wylaczal - { - if (ScndInMain && RList[MainCtrlActualPos].ScndAct != 255) - { - SP = RList[MainCtrlActualPos].ScndAct; - } - - Rz = Mn * WindingRes + R; - - if (DynamicBrakeFlag) // hamowanie - { - // if DynamicBrakeType<>dbrake_automatic then - // MotorCurrent:=-fi*n/Rz {hamowanie silnikiem na oporach rozruchowych} - /* begin - U:=0; - Isf:=Isat; - Delta:=SQR(Isf*Rz+Mn*fi*n-U)+4*U*Isf*Rz; - MotorCurrent:=(U-Isf*Rz-Mn*fi*n+SQRT(Delta))/(2*Rz) - end*/ - // only the ET42's switched brake brakes on the starting resistors, otherwise the current is cut off (0) - if (DynamicBrakeType == dbrake_switch && TrainType == train_type::et42) - { // z Megapacka - Rz = WindingRes + R; - MotorCurrent = -motor_param(SP).fi * n / Rz; //{hamowanie silnikiem na oporach rozruchowych} - } - } - else - { - MotorCurrent = SeriesMotorDrivingCurrent(n, U, Rz, Mn, SP); - } // else DBF - - } // 255 - else - MotorCurrent = 0; - return MotorCurrent; -} - -// the current of the series motors driving, at the revolutions n, the voltage U and the resistance Rz of Mn motors in -// series, by the motor parameters of the shunt field SP -double TMoverParameters::SeriesMotorDrivingCurrent(double const n, double const U, double const Rz, double const Mn, int const SP) const -{ - double MotorCurrent; - double Delta; - double Isf; - double U1; // napiecie z korekta - U1 = U + Mn * n * motor_param(SP).fi0 * motor_param(SP).fi; - // writepaslog("U1 ", FloatToStr(U1)); - // writepaslog("Isat ", FloatToStr(MotorParam[SP].Isat)); - // writepaslog("fi ", FloatToStr(MotorParam[SP].fi)); - Isf = Sign(U1) * motor_param(SP).Isat; - // writepaslog("Isf ", FloatToStr(Isf)); - Delta = square(Isf * Rz + Mn * motor_param(SP).fi * n - U1) + 4.0 * U1 * Isf * Rz; // 105 * 1.67 + Mn * 140.9 * 20.532 - U1 - // DeltaQ = Isf * Rz + Mn * MotorParam[SP].fi * n - U1 + 4 * U1 * Isf * Rz; - // writepaslog("Delta ", FloatToStr(Delta)); - // writepaslog("DeltaQ ", FloatToStr(DeltaQ)); - // writepaslog("U ", FloatToStr(U)); - if (MainCircuitPowered()) - { - if (U > 0) - MotorCurrent = (U1 - Isf * Rz - Mn * motor_param(SP).fi * n + std::sqrt(Delta)) / (2.0 * Rz); - else - MotorCurrent = (U1 - Isf * Rz - Mn * motor_param(SP).fi * n - std::sqrt(Delta)) / (2.0 * Rz); - } - else - MotorCurrent = 0; - return MotorCurrent; -} - -// the line breaker opened, and the motors damaged, by too high revolutions or current -void TMoverParameters::MotorFailuresCheck(double const n) -{ - double MotorCurrent; - // awarie - MotorCurrent = abs(Im); // zmienna pomocnicza - - if (MotorCurrent > 0) - { - if (FuzzyLogic(abs(n), nmax * 1.1, p_elengproblem) && MainSwitch(false)) - EventFlag = true; /*zbyt duze obroty - wywalanie wskutek ognia okreznego*/ - if (TestFlag(DamageFlag, dtrain_engine) && FuzzyLogic(MotorCurrent, (double)ImaxLo / 10.0, p_elengproblem) && MainSwitch(false)) - EventFlag = true; /*uszkodzony silnik (uplywy)*/ - /* or FuzzyLogic(Abs(U/Mn),2*NominalVoltage,1)) then */ /*poprawic potem*/ - if ((FuzzyLogic(abs(Im), Imax * 2, p_elengproblem) || FuzzyLogic(abs(n), nmax * 1.11, p_elengproblem)) && SetFlag(DamageFlag, dtrain_engine)) - EventFlag = true; - /*! dorobic grzanie oporow rozruchowych i silnika*/ - } -} - -// ************************************************************************************************* -// główny konstruktor -// ************************************************************************************************* -TMoverParameters::TMoverParameters(double VelInitial, std::string const &TypeNameInit, std::string const &NameInit, int Cab) : TypeName(TypeNameInit), Name(NameInit), CabOccupied(Cab) -{ - WriteLog("------------------------------------------------------"); - WriteLog("init default physic values for " + NameInit + ", [" + TypeNameInit + "]"); - - // BrakeLevelSet(-2); //Pascal ustawia na 0, przestawimy na odcięcie (CHK jest jeszcze nie wczytane!) - iLights[0] = 0; - iLights[1] = 0; // światła zgaszone - - // inicjalizacja stalych - for (auto &scheme : RList) - { - scheme = TScheme(); - } - RlistSize = 0; - for (auto &motorparam : MotorParam) - { - motorparam = TMotorParameters(); - } - - for (auto &cablights : Lights) - for (int k = 0; k < 17; ++k) - cablights[k] = 0; - - for (auto &compressorrow : CompressorList) - for (int k = 1; k < 9; ++k) - compressorrow[k] = 0; - CompressorList[0][0] = 0.0; - CompressorList[1][0] = 1.0; - CompressorList[2][0] = 1.0; - CompressorList[3][0] = 1.0; - - for (int b = -1; b <= MainBrakeMaxPos; ++b) - { - BrakePressureTable[b].PipePressureVal = 0.0; - BrakePressureTable[b].BrakePressureVal = 0.0; - BrakePressureTable[b].FlowSpeedVal = 0.0; - } - // with BrakePressureTable[-2] do {pozycja odciecia} - { - BrakePressureTable[-2].PipePressureVal = -1.0; - BrakePressureTable[-2].BrakePressureVal = -1.0; - BrakePressureTable[-2].FlowSpeedVal = 0.0; - } - for (auto &delay : BrakeDelay) - { - delay = 0.0; - } - - for (int b = 0; b < 2; ++b) // Ra: kto tu zrobił "for b:=1 to 2 do" ??? - { - Couplers[b].CouplerType = TCouplerType::NoCoupler; - Couplers[b].SpringKB = 1.0; - Couplers[b].SpringKC = 1.0; - Couplers[b].DmaxB = 0.1; - Couplers[b].FmaxB = 1000.0; - Couplers[b].DmaxC = 0.1; - Couplers[b].FmaxC = 1000.0; - } - for (auto &cylindermult : BrakeCylMult) - { - cylindermult = 0.0; - } - - for (auto &eimcvalue : eimc) - { - eimcvalue = 0.0; - } - eimc[eimc_p_eped] = 1.5; - - for (auto &couplerentry : Couplers) - { - couplerentry.AllowedFlag = 3; // domyślnie hak i hamulec, inne trzeba włączyć jawnie w FIZ - couplerentry.CouplingFlag = 0; - couplerentry.Connected = nullptr; - couplerentry.ConnectedNr = 0; // Ra: to nie ma znaczenia jak nie podłączony - couplerentry.Render = false; - couplerentry.CForce = 0.0; - couplerentry.Dist = 0.0; - couplerentry.CheckCollision = false; - } - - for (auto &brakepress : MaxBrakePress) - { - brakepress = 0.0; - } - - Vel = abs(VelInitial); - V = VelInitial / 3.6; - - for (auto &eimvvalue : eimv) - { - eimvvalue = 0.0; - } - - RunningShape.Len = 1.0; - - RunningTrack.CategoryFlag = CategoryFlag; - RunningTrack.Width = TrackW; - RunningTrack.friction = Steel2Steel_friction; - RunningTrack.QualityFlag = 20; - RunningTrack.DamageFlag = 0; - RunningTrack.Velmax = 100.0; // dla uzytku maszynisty w ai_driver} - - RunningTraction.TractionVoltage = 0.0; - RunningTraction.TractionFreq = 0.0; - RunningTraction.TractionMaxCurrent = 0.0; - RunningTraction.TractionResistivity = 1.0; -}; - -double TMoverParameters::Distance(const TLocation &Loc1, const TLocation &Loc2, const TDimension &Dim1, const TDimension &Dim2) -{ // zwraca odległość pomiędzy pojazdami (Loc1) i (Loc2) z uwzględnieneim ich długości (kule!) - return hypot(Loc2.X - Loc1.X, Loc1.Y - Loc2.Y) - 0.5 * (Dim2.L + Dim1.L); -}; - -double TMoverParameters::CouplerDist(TMoverParameters const *Left, TMoverParameters const *Right) -{ // obliczenie odległości pomiędzy sprzęgami (kula!) - return Distance(Left->Loc, Right->Loc, Left->Dim, Right->Dim); // odległość pomiędzy sprzęgami (kula!) -}; - -bool TMoverParameters::Attach(int ConnectNo, int ConnectToNr, TMoverParameters *ConnectTo, int CouplingType, bool Enforce, bool Audible) -{ // łączenie do swojego sprzęgu (ConnectNo) pojazdu (ConnectTo) stroną (ConnectToNr) - // Ra: zwykle wykonywane dwukrotnie, dla każdego pojazdu oddzielnie - // Ra: trzeba by odróżnić wymóg dociśnięcia od uszkodzenia sprzęgu przy podczepianiu AI do składu - - if (ConnectTo == nullptr || CouplingType == coupling::faux) - { - return false; - } - - auto &thiscoupler{Couplers[ConnectNo]}; - auto const otherend{ConnectToNr != 2 ? ConnectToNr : thiscoupler.ConnectedNr}; - auto &othercoupler = ConnectTo->Couplers[otherend]; - auto const distance{CouplerDist(this, ConnectTo) - (thiscoupler.adapter_length + othercoupler.adapter_length)}; - - - if (auto const couplercheck{Enforce || (distance <= dEpsilon && thiscoupler.type() != TCouplerType::NoCoupler && thiscoupler.type() == othercoupler.type())}; false == couplercheck) - { - return false; - } - - // no multiple-unit control between an electric and a diesel locomotive, whoever asks for it: the scenario, the AI - // or the player (eu07/maszyna#520) - if (auto const compatible{CompatibleCoupling(ConnectNo, *ConnectTo, otherend, CouplingType)}; compatible != CouplingType) - { - WriteLog(std::format("Vehicles \"{}\" and \"{}\" can't share their control, coupled without the control connection", Name, ConnectTo->Name)); - CouplingType = compatible; - if (CouplingType == coupling::faux) - { - return false; - } - } - - // stykaja sie zderzaki i kompatybilne typy sprzegow, chyba że łączenie na starcie - if (thiscoupler.CouplingFlag == coupling::faux) - { - // a new coupling: the play of the coupling as set up anew, without the stretch of the one before - thiscoupler.physics_state.couple(); - othercoupler.physics_state.couple(); - // jeśli wcześniej nie było połączone, ustalenie z której strony rysować sprzęg - thiscoupler.Render = true; // tego rysować - othercoupler.Render = false; // a tego nie - } - auto const couplingchange{CouplingType ^ thiscoupler.CouplingFlag}; - thiscoupler.Connected = ConnectTo; - thiscoupler.CouplingFlag = CouplingType; // ustawienie typu sprzęgu - if (ConnectToNr != 2) - { - thiscoupler.ConnectedNr = ConnectToNr; // 2=nic nie podłączone - } - othercoupler.Connected = this; - othercoupler.CouplingFlag = CouplingType; - othercoupler.ConnectedNr = ConnectNo; - - if (true == Audible && couplingchange != 0) - { - // set sound event flag - int soundflag{sound::none}; - std::vector> const soundmappings = {{coupling::coupler, sound::attachcoupler}, {coupling::brakehose, sound::attachbrakehose}, - {coupling::mainhose, sound::attachmainhose}, {coupling::control, sound::attachcontrol}, - {coupling::gangway, sound::attachgangway}, {coupling::heating, sound::attachheating}}; - for (auto const &[mappingcoupling, mappingsound] : soundmappings) - { - if ((couplingchange & mappingcoupling) != 0) - { - soundflag |= mappingsound; - } - } - SetFlag(thiscoupler.sounds, soundflag); - } - - return true; -} - -int TMoverParameters::DettachStatus(int ConnectNo) -{ // Ra: sprawdzenie, czy odległość jest dobra do rozłączania - // powinny być 3 informacje: =0 sprzęg już rozłączony, <0 da się rozłączyć. >0 nie da się rozłączyć - if (!Couplers[ConnectNo].Connected) - return 0; // nie ma nic, to rozłączanie jest OK - if ((Couplers[ConnectNo].CouplingFlag & ctrain_coupler) == 0) - return -Couplers[ConnectNo].CouplingFlag; // hak nie połączony - rozłączanie jest OK - if (TestFlag(DamageFlag, dtrain_coupling)) - return -Couplers[ConnectNo].CouplingFlag; // hak urwany - rozłączanie jest OK - // CouplerDist(ConnectNo); - if (Couplers[ConnectNo].type() != TCouplerType::Screw || Neighbours[ConnectNo].distance < 0.01) - return -Couplers[ConnectNo].CouplingFlag; // można rozłączać, jeśli dociśnięty - return Neighbours[ConnectNo].distance > 0.2 ? -Couplers[ConnectNo].CouplingFlag : Couplers[ConnectNo].CouplingFlag; -}; - -bool TMoverParameters::Dettach(int ConnectNo) -{ // rozlaczanie - - auto &thiscoupler{Couplers[ConnectNo]}; - auto &othervehicle{thiscoupler.Connected}; - auto &othercoupler{othervehicle->Couplers[thiscoupler.ConnectedNr]}; - - if (othervehicle == nullptr) - { - return true; - } // nie ma nic, to odczepiono - - auto couplingchange{thiscoupler.CouplingFlag}; // presume we'll uncouple all active flags - auto const couplingstate{DettachStatus(ConnectNo)}; // stan sprzęgu - if (couplingstate < 0) - { - // gdy scisniete zderzaki, chyba ze zerwany sprzeg (wirtualnego nie odpinamy z drugiej strony) - std::tie(othercoupler.Connected, othercoupler.ConnectedNr, othercoupler.CouplingFlag) = std::make_tuple(nullptr, -1, coupling::faux); - std::tie(thiscoupler.Connected, thiscoupler.ConnectedNr, thiscoupler.CouplingFlag) = std::make_tuple(nullptr, -1, coupling::faux); - } - else if (couplingstate > 0) - { // odłączamy węże i resztę, pozostaje sprzęg fizyczny, który wymaga dociśnięcia (z wirtualnym nic) - thiscoupler.CouplingFlag &= coupling::coupler; - othercoupler.CouplingFlag &= coupling::coupler; - } - // set sound event flag - couplingchange ^= thiscoupler.CouplingFlag; // remaining bits were removed from coupling - if (couplingchange != 0) - { - int soundflag{sound::detach}; // HACK: use detach flag to indicate removal of listed coupling - std::vector> const soundmappings = {{coupling::coupler, sound::attachcoupler}, {coupling::brakehose, sound::attachbrakehose}, - {coupling::mainhose, sound::attachmainhose}, {coupling::control, sound::attachcontrol}, - {coupling::gangway, sound::attachgangway}, {coupling::heating, sound::attachheating}}; - for (auto const &[mappingcoupling, mappingsound] : soundmappings) - { - if ((couplingchange & mappingcoupling) != 0) - { - soundflag |= mappingsound; - } - } - SetFlag(thiscoupler.sounds, soundflag); - } - - return couplingstate < 0; -}; - -bool TMoverParameters::DirectionForward() -{ - if (false == EIMDirectionChangeAllow()) - { - return false; - } - - if (MainCtrlPosNo > 0 && DirActive < 1 && (CabActive != 0 || (InactiveCabFlag & activation::neutraldirection) == 0)) - { - ++DirActive; - DirAbsolute = DirActive * CabActive; - SendCtrlToNext("Direction", DirActive, CabActive); - return true; - } - else if (DirActive == 1 && IsMainCtrlNoPowerPos() && TrainType == train_type::emu && EngineType != TEngineType::ElectricInductionMotor) - return MinCurrentSwitch(true); //"wysoki rozruch" EN57 - return false; -}; - -// Nastawianie hamulców - -void TMoverParameters::BrakeLevelSet(double b) -{ // ustawienie pozycji hamulca na wartość (b) w zakresie od -2 do BrakeCtrlPosNo - // jedyny dopuszczalny sposób przestawienia hamulca zasadniczego - if (fBrakeCtrlPos == b) - return; // nie przeliczać, jak nie ma zmiany - fBrakeCtrlPos = b; - if (fBrakeCtrlPos < Handle->GetPos(bh_MIN)) - fBrakeCtrlPos = Handle->GetPos(bh_MIN); // odcięcie - else if (fBrakeCtrlPos > Handle->GetPos(bh_MAX)) - fBrakeCtrlPos = Handle->GetPos(bh_MAX); - // TODO: verify whether BrakeCtrlPosR and fBrakeCtrlPos can be rolled into single variable - BrakeCtrlPosR = fBrakeCtrlPos; - auto x = static_cast(std::floor(fBrakeCtrlPos)); // jeśli odwołujemy się do BrakeCtrlPos w pośrednich, to musi być - // obcięte a nie zaokrągone - while (x > BrakeCtrlPos && BrakeCtrlPos < BrakeCtrlPosNo) // jeśli zwiększyło się o 1 - if (!IncBrakeLevelOld()) // T_MoverParameters:: - break; // wyjście awaryjne - while (x < BrakeCtrlPos && BrakeCtrlPos >= -1) // jeśli zmniejszyło się o 1 - if (!DecBrakeLevelOld()) // T_MoverParameters:: - break; - BrakePressureActual = BrakePressureTable[BrakeCtrlPos]; // skopiowanie pozycji - /* - //youBy: obawiam sie, ze tutaj to nie dziala :P - //Ra 2014-03: było tak zrobione, że działało - po każdej zmianie pozycji była wywoływana ta - funkcja - // if (BrakeSystem==Pneumatic?BrakeSubsystem==Oerlikon:false) //tylko Oerlikon akceptuje ułamki - if(false) - if (fBrakeCtrlPos>0.0) - {//wartości pośrednie wyliczamy tylko dla hamowania - double u=fBrakeCtrlPos-double(x); //ułamek ponad wartość całkowitą - if (u>0.0) - {//wyliczamy wartości ważone - BrakePressureActual.PipePressureVal+=-u*BrakePressureActual.PipePressureVal+u*BrakePressureTable[BrakeCtrlPos+1+2].PipePressureVal; - //BrakePressureActual.BrakePressureVal+=-u*BrakePressureActual.BrakePressureVal+u*BrakePressureTable[BrakeCtrlPos+1].BrakePressureVal; - //to chyba nie będzie tak działać, zwłaszcza w EN57 - BrakePressureActual.FlowSpeedVal+=-u*BrakePressureActual.FlowSpeedVal+u*BrakePressureTable[BrakeCtrlPos+1+2].FlowSpeedVal; - } - } - */ -}; - -bool TMoverParameters::BrakeLevelAdd(double b) -{ // dodanie wartości (b) do pozycji hamulca (w tym ujemnej) - // zwraca false, gdy po dodaniu było by poza zakresem - BrakeLevelSet(fBrakeCtrlPos + b); - return b > 0.0 ? fBrakeCtrlPos < BrakeCtrlPosNo : BrakeCtrlPos > -1.0; // true, jeśli można kontynuować -}; - -bool TMoverParameters::IncBrakeLevel() -{ // nowa wersja na użytek AI, false gdy osiągnięto pozycję BrakeCtrlPosNo - return BrakeLevelAdd(1.0); -}; - -bool TMoverParameters::DecBrakeLevel() -{ - return BrakeLevelAdd(-1.0); -}; // nowa wersja na użytek AI, false gdy osiągnięto pozycję -1 - -bool TMoverParameters::ChangeCab(int direction) -{ // zmiana kabiny i resetowanie ustawien - if (std::abs(CabOccupied + direction) < 2) - { - CabOccupied = CabOccupied + direction; - if (BrakeCtrlPosNo > 0 && (BrakeSystem == TBrakeSystem::Pneumatic || BrakeSystem == TBrakeSystem::ElectroPneumatic)) - { - BrakeLevelSet(Handle->GetPos(bh_NP)); - LimPipePress = PipePress; - ActFlowSpeed = 0; - } - else - BrakeLevelSet(Handle->GetPos(bh_NP)); - MainCtrlPos = MainCtrlNoPowerPos(); - ScndCtrlPos = 0; - return true; - } - return false; -}; - -// rozruch wysoki (true) albo niski (false) -bool TMoverParameters::CurrentSwitch(bool const State) -{ - // TBD, TODO: split off shunt mode toggle into a separate command? It doesn't make much sense to have these two together like that - // the diesels with a shunt mode have no motor overload relay threshold to switch, the switch sets their shunt mode alone. - // MaxCurrentSwitch() takes any change of the setting, so asked first it took the first move of the switch (eu07/maszyna#497) - if (true == ShuntModeAllow && (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric)) - { - // dla 2Ls150 przed ustawieniem kierunku, for SM42/SP42 at the controller's zero position - if (EngineType == TEngineType::DieselEngine ? DirActive != 0 : false == IsMainCtrlNoPowerPos()) - { - return false; - } - ShuntMode = State; - return true; - } - - if (MaxCurrentSwitch(State)) - { - if (TrainType != train_type::emu) - { - MinCurrentSwitch(State); - } - return true; - } - - return false; -}; - -bool TMoverParameters::IsMotorOverloadRelayHighThresholdOn() const -{ - - return ImaxHi > ImaxLo && Imax > ImaxLo; -} - -// KURS90 - sprężarka pantografów; Ra 2014-07: teraz jest to zbiornik rozrządu, chociaż to jeszcze nie tak -void TMoverParameters::UpdatePantVolume(double dt) -{ - // check the pantograph compressor while at it - // TODO: move the check to a separate method - // automatic start if the pressure is too low - PantCompFlag |= PantPress < 4.2 && true == (Pantographs[end::front].is_active | Pantographs[end::rear].is_active) // TODO: any_pantograph_is_active method - && (PantographCompressorStart == start_t::automatic || PantographCompressorStart == start_t::manualwithautofallback); - - auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; - PantCompFlag &= lowvoltagepower; - - if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector // tylko jeśli pantografujący - && EnginePowerSource.CollectorParameters.CollectorsNo > 0) - { - // Ra 2014-07: zasadniczo, to istnieje zbiornik rozrządu i zbiornik pantografów - na razie mamy razem - // Ra 2014-07: kurek trójdrogowy łączy spr.pom. z pantografami i wyłącznikiem ciśnieniowym WS - // Ra 2014-07: zbiornika rozrządu nie pompuje się tu, tylko pantografy; potem można zamknąć - // WS i odpalić resztę - if (PantAutoValve ? PantPress < ScndPipePress : bPantKurek3) // kurek zamyka połączenie z ZG - { // zbiornik pantografu połączony ze zbiornikiem głównym - małą sprężarką się tego nie napompuje - // Ra 2013-12: Niebugocław mówi, że w EZT nie ma potrzeby odcinać kurkiem - PantPress = ScndPipePress; - // ograniczenie ciśnienia do MaxPress (tylko w pantografach!) - PantPress = safe_clamp(ScndPipePress, 0.0, EnginePowerSource.CollectorParameters.MaxPress); - PantVolume = (PantPress + 1.0) * 0.1; // objętość, na wypadek odcięcia kurkiem - } - else - { // zbiornik główny odcięty, można pompować pantografy - if (PantCompFlag) - { - // włączona mała sprężarka - PantVolume += dt - // Ra 2013-12: Niebugocław mówi, że w EZT nabija 1.5 raz wolniej niż jak było 0.005 - * (TrainType == train_type::emu ? 0.003 : 0.005) / std::max(1.0, PantPress) * (0.45 - (0.1 / PantVolume / 10 - 0.1)) / 0.45; - } - PantPress = safe_clamp(10.0 * PantVolume - 1.0, 0.0, EnginePowerSource.CollectorParameters.MaxPress); // tu by się przydała objętość zbiornika - } - if (!PantCompFlag && PantVolume > 0.1) - PantVolume -= dt * 0.0003 * std::max(1.0, PantPress * 0.5); // nieszczelności: 0.0003=0.3l/s - - PantPressureSwitchCheck(); - } - else - { // a tu coś dla SM42 i SM31, aby pokazywać na manometrze - PantPress = CntrlPipePress; - } -}; - -// the pantographs' pressure switch: low, it opens the line breaker (or locks the converter of a unit) once; -// primed again over 4.6 bar, where the pantographs' compressor stops at 4.8 -void TMoverParameters::PantPressureSwitchCheck() -{ - if (PantPress < EnginePowerSource.CollectorParameters.MinPress) - { - // 3.5 wg http://www.transportszynowy.pl/eu06-07pneumat.php - if (true == PantPressSwitchActive) - { - PantPressureSwitchTrip(); - } - } - else if (PantPress >= 4.6) - { - // NOTE: we require active low power source to prime the pressure switch - // this is a work-around for potential isssues caused by the switch activating on otherwise idle vehicles, but should check whether it's accurate - if (true == Power24vIsAvailable || true == Power110vIsAvailable) - { - // prime the pressure switch - PantPressSwitchActive = true; - // turn off the subsystems lock - PantPressLockActive = false; - } - - if (PantPress >= 4.8) - { - // Winger - automatyczne wylaczanie malej sprezarki - // TODO: governor lock, disables usage until pressure drop below 3.8 (should really make compressor object we could reuse) - PantCompFlag = false; - } - } -} - -// the pantographs' pressure switch tripped by the low pressure: the line breaker opened, unless the voltage comes from -// elsewhere, or the converter of a unit locked; spent until primed again -void TMoverParameters::PantPressureSwitchTrip() -{ - // opuszczenie pantografów przy niskim ciśnieniu - if (TrainType != train_type::emu) - { - // pressure switch safety measure -- open the line breaker, unless there's alternate source of traction voltage - // (the genset of a dual-mode vehicle, when the selector is on it, doesn't need the pantographs) - if (GetTrainsetHighVoltage() < EnginePowerSource.CollectorParameters.MinV && false == GensetSelected()) - { - // TODO: check whether line breaker should be open EMU-wide - MainSwitch(false, TrainType == train_type::emu ? range_t::unit : range_t::local); - } - } - else - { - // specialized variant for EMU -- pwr system disables converter and heating, - // and prevents their activation until pressure switch is set again - PantPressLockActive = true; - // TODO: separate 'heating allowed' from actual heating flag, so we can disable it here without messing up heating toggle - ConverterSwitch(false, range_t::unit); - } - // mark the pressure switch as spent - PantPressSwitchActive = false; -} - -void TMoverParameters::UpdateBatteryVoltage(double dt) -{ // przeliczenie obciążenia baterii - using enum TEngineType; - if (BatteryVoltage > 0 && EngineType != DieselEngine && EngineType != WheelsDriven && NominalBatteryVoltage > 0) - { - - // HACK: allow to draw power also from adjacent converter, applicable for EMUs - // TODO: expand power cables system to include low voltage power transfers - // HACK: emulate low voltage generator powered directly by the diesel engine - auto const converteractive{Power110vIsAvailable || (EngineType == DieselElectric && true == Mains) || (EngineType == DieselEngine && true == Mains)}; - - BatteryVoltage -= BatteryDrain(dt, converteractive); - if (NominalBatteryVoltage / BatteryVoltage > 1.57 && MainSwitch(false) && EngineType != DieselEngine && EngineType != WheelsDriven) - EventFlag = true; // wywalanie szybkiego z powodu zbyt niskiego napiecia - if (BatteryVoltage > NominalBatteryVoltage) - BatteryVoltage = NominalBatteryVoltage; // wstrzymanie ładowania pow. 110V - if (BatteryVoltage < 0.01) - BatteryVoltage = 0.01; - } - else - { - // TODO: check and implement proper way to handle this for diesel engines - BatteryVoltage = NominalBatteryVoltage; - } -}; - -// the drop of the battery's voltage in dt, by what draws from it, or its rise by the converter charging it -double TMoverParameters::BatteryDrain(double dt, bool const converteractive) const -{ - if (NominalBatteryVoltage / BatteryVoltage < 1.22 && Battery) - { // 110V - return BatteryDrainCharged(dt, converteractive); - } - if (NominalBatteryVoltage / BatteryVoltage >= 1.22 && Battery) - { // 90V - return BatteryDrainLow(dt, converteractive); - } - if (!Battery) - { - return BatteryDrainSwitchedOff(dt); - } - return 0.0; -} - -// the drain of a battery at its voltage, the converter charging it -double TMoverParameters::BatteryDrainCharged(double dt, bool const converteractive) const -{ - double sn1; - double sn2; - double sn3; - double sn4; - double sn5; - if (!converteractive) - sn1 = dt * 2.0; // szybki spadek do ok 90V - else - sn1 = 0; - if (converteractive) - sn2 = -(dt * 2.0); // szybki wzrost do 110V - else - sn2 = 0; - if (Mains) - sn3 = dt * 0.05; - else - sn3 = 0; - if (iLights[0] & 63) // 64=blachy, nie ciągną prądu //rozpisać na poszczególne żarówki... - sn4 = dt * 0.003; - else - sn4 = 0; - if (iLights[1] & 63) // 64=blachy, nie ciągną prądu - sn5 = dt * 0.001; - else - sn5 = 0; - return sn1 + sn2 + sn3 + sn4 + sn5; -} - -// the drain of a battery run down to 90 V, the converter charging it -double TMoverParameters::BatteryDrainLow(double dt, bool const converteractive) const -{ - double sn1; - double sn2; - double sn3; - double sn4; - double sn5; - if (PantCompFlag) - sn1 = dt * 0.0046; - else - sn1 = 0; - if (converteractive) - sn2 = -(dt * 50); // szybki wzrost do 110V - else - sn2 = 0; - if (Mains) - sn3 = dt * 0.001; - else - sn3 = 0; - if (iLights[0] & 63) // 64=blachy, nie ciągną prądu - sn4 = dt * 0.0030; - else - sn4 = 0; - if (iLights[1] & 63) // 64=blachy, nie ciągną prądu - sn5 = dt * 0.0010; - else - sn5 = 0; - return sn1 + sn2 + sn3 + sn4 + sn5; -} - -// the drain of a battery switched off, very slow -double TMoverParameters::BatteryDrainSwitchedOff(double dt) const -{ - double sn1; - double sn2; - double sn3; - double sn4; - double sn5; - if (NominalBatteryVoltage / BatteryVoltage < 1.22) - sn1 = dt * 50; - else - sn1 = 0; - sn2 = dt * 0.000001; - sn3 = dt * 0.000001; - sn4 = dt * 0.000001; - sn5 = dt * 0.000001; // bardzo powolny spadek przy wyłączonych bateriach - return sn1 + sn2 + sn3 + sn4 + sn5; -} - -/* Ukrotnienie EN57: -1 //układ szeregowy -2 //układ równoległy -3 //bocznik 1 -4 //bocznik 2 -5 //bocznik 3 -6 //do przodu -7 //do tyłu -8 //1 przyspieszenie -9 //minus obw. 2 przyspieszenia -10 //jazda na oporach -11 //SHP -12A //podnoszenie pantografu przedniego -12B //podnoszenie pantografu tylnego -13A //opuszczanie pantografu przedniego -13B //opuszczanie wszystkich pantografów -14 //załączenie WS -15 //rozrząd (WS, PSR, wał kułakowy) -16 //odblok PN -18 //sygnalizacja przetwornicy głównej -19 //luzowanie EP -20 //hamowanie EP -21 //rezerwa** (1900+: zamykanie drzwi prawych) -22 //zał. przetwornicy głównej -23 //wył. przetwornicy głównej -24 //zał. przetw. oświetlenia -25 //wył. przetwornicy oświetlenia -26 //sygnalizacja WS -28 //sprężarka -29 //ogrzewanie -30 //rezerwa* (1900+: zamykanie drzwi lewych) -31 //otwieranie drzwi prawych -32H //zadziałanie PN siln. trakcyjnych -33 //sygnał odjazdu -34 //rezerwa (sygnalizacja poślizgu) -35 //otwieranie drzwi lewych -ZN //masa -*/ - -// ***************************************************************************** -// Q: 20160714 -// Oblicza iloraz aktualnej pozycji do maksymalnej hamulca pomocnicznego -// ***************************************************************************** -double TMoverParameters::LocalBrakeRatio(void) const -{ - double LBR; - if (BrakeHandle == TBrakeHandle::MHZ_EN57) - if (BrakeOpModeFlag >= bom_EP) - LBR = Handle->GetEP(BrakeCtrlPosR); - else - LBR = 0; - else - { - if (LocalBrakePosNo > 0) - LBR = LocalBrakePosA; - else - LBR = 0; - } - // if (TestFlag(BrakeStatus, b_antislip)) - // LBR = std::max(LBR, PipeRatio) + 0.4; - return LBR; -} - -// ***************************************************************************** -// Q: 20160714 -// Oblicza iloraz aktualnej pozycji do maksymalnej hamulca ręcznego -// ***************************************************************************** -double TMoverParameters::ManualBrakeRatio(void) const -{ - double MBR; - - if (ManualBrakePosNo > 0) - MBR = (double)ManualBrakePos / ManualBrakePosNo; - else - MBR = 0; - return MBR; -} - -// ***************************************************************************** -// Q: 20160713 -// Zwraca objętość -// ***************************************************************************** -double TMoverParameters::BrakeVP(void) const -{ - if (BrakeVVolume > 0) - return Volume / (10.0 * BrakeVVolume); - else - return 0; -} - -// ***************************************************************************** -// Q: 20160713 -// Zwraca iloraz różnicy między przewodem kontrolnym i głównym oraz DeltaPipePress -// ***************************************************************************** -double TMoverParameters::RealPipeRatio(void) const -{ - double rpp; - - if (DeltaPipePress > 0) - rpp = (CntrlPipePress - PipePress) / DeltaPipePress; - else - rpp = 0; - return rpp; -} - -// ***************************************************************************** -// Q: 20160713 -// Zwraca iloraz ciśnienia w przewodzie do DeltaPipePress -// ***************************************************************************** -double TMoverParameters::PipeRatio(void) const -{ - double pr; - - if (DeltaPipePress > 0) - if (false) // SPKS!! no to jak nie wchodzimy to po co branch? - { - if (3.0 * PipePress > HighPipePress + LowPipePress + LowPipePress) - pr = (HighPipePress - std::min(HighPipePress, PipePress)) / (DeltaPipePress * 4.0 / 3.0); - else - pr = (HighPipePress - 1.0 / 3.0 * DeltaPipePress - std::max(LowPipePress, PipePress)) / (DeltaPipePress * 2.0 / 3.0); - // if (not TestFlag(BrakeStatus, b_Ractive)) - // and(BrakeMethod and 1 = 0) and TestFlag(BrakeDelays, bdelay_R) and (Power < 1) and - // (BrakeCtrlPos < 1) then pr : = std::min(0.5, pr); - // if (Compressor > 0.5) - // then pr : = pr * 1.333; // dziwny rapid wywalamy - } - else - pr = (HighPipePress - std::max(LowPipePress, std::min(HighPipePress, PipePress))) / DeltaPipePress; - else - pr = 0; - return pr; -} - -double TMoverParameters::EngineRPMRatio() const -{ - - return std::clamp(EngineType == TEngineType::DieselElectric ? 60.0 * std::abs(enrot) / DElist[MainCtrlPosNo].RPM : - EngineType == TEngineType::DieselEngine ? std::abs(enrot) / nmax : - 1.0, // shouldn't ever get here but, eh - 0.0, 1.0); -} - -double TMoverParameters::EngineIdleRPM() const -{ - - return EngineType == TEngineType::DieselEngine ? dizel_nmin * 60 : - EngineType == TEngineType::DieselElectric ? DElist[MainCtrlNoPowerPos()].RPM : - std::numeric_limits::max(); // shouldn't ever get here but, eh -} - -double TMoverParameters::EngineMaxRPM() const -{ - - return EngineType == TEngineType::DieselEngine ? dizel_nmax * 60 : - EngineType == TEngineType::DieselElectric ? DElist[MainCtrlPosNo].RPM : - std::numeric_limits::max(); // shouldn't ever get here but, eh -} - -// ************************************************************************************************* -// prędkość zbliżania się stykających się końców pojazdów przy zderzeniu, w km/h -// ************************************************************************************************* -double TMoverParameters::CollisionVelocity(int const End, TMoverParameters const &Other, int const OtherEnd) const -{ - auto const velocitydifference{CouplerVelocityDifference(End, Other, OtherEnd)}; - // the front end closes in on the other vehicle when this one moves forward faster, the rear end when it's slower - return (End == end::front ? velocitydifference : -velocitydifference) * 3.6; // m/s -> km/h -} - -double TMoverParameters::CouplerVelocityDifference(int const End, TMoverParameters const &Other, int const OtherEnd) const -{ - // V runs along the vehicle's own axis, towards its front; the other vehicle's velocity is turned around when the - // vehicles face each other (touch with the same ends) - return V - Other.V * DirPatch(End, OtherEnd); -} - -bool TMoverParameters::AutomaticCouplingSafe(int const End, TMoverParameters const &Other, int const OtherEnd) const -{ - return false == Global.crash_damage || CollisionVelocity(End, Other, OtherEnd) <= SafeCollisionVelocity; -} - -namespace -{ - -// the kind of traction a vehicle's engine stands for, as far as its multiple-unit control goes -enum class traction_kind -{ - none, - electric, - diesel -}; - -traction_kind traction_of(TEngineType const Engine) -{ - switch (Engine) - { - case TEngineType::ElectricSeriesMotor: - case TEngineType::ElectricInductionMotor: - return traction_kind::electric; - case TEngineType::DieselEngine: - case TEngineType::DieselElectric: - return traction_kind::diesel; - default: - return traction_kind::none; - } -} - -} // namespace - -bool TMoverParameters::ControlCouplingAllowed(int const End, TMoverParameters const &Other, int const OtherEnd) const -{ - if (false == Global.control_coupling_engine_check) - { - return true; - } - // the same control system named on both couplers is the vehicle authors' word that they work together - if (auto const &controltype{Couplers[End].control_type}; false == controltype.empty() && controltype == Other.Couplers[OtherEnd].control_type) - { - return true; - } - auto const traction{traction_of(EngineType)}; - auto const othertraction{traction_of(Other.EngineType)}; - return traction == traction_kind::none || othertraction == traction_kind::none || traction == othertraction; -} - -int TMoverParameters::CompatibleCoupling(int const End, TMoverParameters const &Other, int const OtherEnd, int const CouplingType) const -{ - if ((CouplingType & coupling::control) == 0 || (CouplingType & coupling::permanent) != 0 || ControlCouplingAllowed(End, Other, OtherEnd)) - { - return CouplingType; - } - return CouplingType & ~coupling::control; -} - -int TMoverParameters::SoundingHorns(int const Signal) const -{ - auto const supplied{[this](horn_supply const Supply) { - if (Supply == horn_supply::electric) - { - return Power24vIsAvailable || Power110vIsAvailable; - } - if (VeselVolume > 0.0) - { - return Compressor >= HornMinPressure; - } - // a vehicle without a main reservoir of its own takes the air from the main pipe, a vehicle without either - // (a road vehicle, say) has no air to check - auto const mainpipe{((Couplers[end::front].AllowedFlag | Couplers[end::rear].AllowedFlag) & coupling::mainhose) != 0}; - return false == mainpipe || ScndPipePress >= HornMinPressure; - }}; - auto horns{0}; - if (supplied(HornSupply)) - { - horns |= Signal & (1 | 2); - } - if (supplied(Horn3Supply)) - { - horns |= Signal & 4; - } - return horns; -} - -// ************************************************************************************************* -// Q: 20160716 -// Wykrywanie kolizji -// ************************************************************************************************* -void TMoverParameters::CollisionDetect(int const End, double const dt) -{ - if (Neighbours[End].vehicle == nullptr) - { - return; - } // shouldn't normally happen but, eh - - auto const &thiscoupler{Couplers[End]}; - auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; - auto const otherend{Neighbours[End].vehicle_end}; - auto const &othercoupler{othervehicle->Couplers[otherend]}; - - auto const physical{coupler_physics_at(End)}; - // physics.collisions new: past the buffers the ends of rail vehicles crush (collision.h); a hit the steel takes stays - // the legacy one, and so do the collisions of the road vehicles (the traffic of a scenery), with the legacy rule - auto const rails{TestFlag(CategoryFlag, 1) && TestFlag(othervehicle->CategoryFlag, 1)}; - auto const crushing{Global.collisions == global_settings::collision_model::physical && rails}; - if (crushing && (thiscoupler.hit_handled || crush_hit(End, dt))) - { - return; - } - // physics.collisions monitor: the legacy collision follows, the log tells what the crush would be - if (Global.collisions == global_settings::collision_model::monitor && rails) - { - crush_hit(End, dt); - } - if (physical && false == coupler_stop_hit(End, *othervehicle, otherend)) - { - return; - } - // the share of the energy of the relative motion the hit takes: in the physical model the springs gone solid give - // for good, rather than spring back as the legacy model has it - auto const loss{physical ? coupler_physics::solid_hit_loss(thiscoupler.physics, othercoupler.physics) : (thiscoupler.beta + othercoupler.beta) / 2.0}; - - // the velocities along this vehicle's axis: the other vehicle's one is turned around when the vehicles face each - // other (touch with the same ends), as in CouplerForce() - auto const otherdirection{DirPatch(End, otherend)}; - auto velocity{V}; - auto othervehiclevelocity{othervehicle->V * otherdirection}; - // calculate collision force and new velocities for involved vehicles - auto const VirtualCoupling{(thiscoupler.CouplingFlag == coupling::faux)}; - auto CCF{0.0}; - - switch (End) - { - case 0: - { - CCF = ComputeCollision(velocity, othervehiclevelocity, TotalMass, othervehicle->TotalMass, loss, VirtualCoupling) / dt; - break; // yB: ej ej ej, a po - } - case 1: - { - CCF = ComputeCollision(othervehiclevelocity, velocity, othervehicle->TotalMass, TotalMass, loss, VirtualCoupling) / dt; - break; - } - default: - { - break; - } - } - - // the new model crushes the ends and derails the vehicles by the crush, see crush_hit() - if (Global.crash_damage && false == crushing) - { - // the physical model breaks the coupling and crushes the buffers by the force of the hit (coupler_stop_hit()) - if (false == physical && -thiscoupler.Dist >= thiscoupler.DmaxB && FuzzyLogic(std::abs(CCF), 5.0 * (thiscoupler.FmaxC + 1.0), p_coupldmg)) - { - // small chance to smash the coupler if it's hit with excessive force - damage_coupler(End); - } - - // HACK: limit excessive speed derailment checks to vehicles which aren't part of the same consist - auto const outsideconsist{thiscoupler.CouplingFlag == coupling::faux || true == TestFlag(othervehicle->DamageFlag, dtrain_out)}; - auto const velocitydifference{outsideconsist ? CollisionVelocity(End, *othervehicle, otherend) : 0.0}; - - if (velocitydifference > SafeCollisionVelocity) - { - // HACK: crude estimation for potential derail, will take place with velocity difference > 15 km/h adjusted for vehicle mass ratio - if (false == TestFlag(DamageFlag, dtrain_out) || false == TestFlag(othervehicle->DamageFlag, dtrain_out)) - { - WriteLog("Bad driving: " + Name + " and " + othervehicle->Name + " collided with velocity " + to_string(velocitydifference, 0) + " km/h"); - } - - if (velocitydifference > SafeCollisionVelocity * (TotalMass / othervehicle->TotalMass)) - { - Derail(COLLISION); - } - if (velocitydifference > SafeCollisionVelocity * (othervehicle->TotalMass / TotalMass)) - { - othervehicle->Derail(COLLISION); - } - } - } - - // adjust velocity and acceleration of affected vehicles. the physical model changes the velocities alone: the - // integration of the next step (ComputeMovement()) would carry a quarter of an acceleration spike over into the - // velocity once more, and the vehicles would bounce off the stop faster than they hit it - auto const accelerationspike{physical ? 0.0 : 1.0}; - // derailed the legacy way a vehicle is a wall, off the rails by the new criteria it slides on and takes the hit. with - // the crush, the vehicles coupled to the wall push it on (crush_hit()) - auto const coupled{thiscoupler.CouplingFlag != coupling::faux}; - auto const wall = [crushing, coupled](TMoverParameters const &Vehicle) { - return TestFlag(Vehicle.DamageFlag, dtrain_out) && (false == crushing || (Vehicle.Derailed == derailment::outcome::none && false == coupled)); - }; - if (false == wall(*this)) - { - auto const accelerationchange{(velocity - V) / dt}; - AccS += accelerationchange * accelerationspike; - V = velocity; - } - if (false == wall(*othervehicle)) - { - auto const othervehiclenewvelocity{othervehiclevelocity * otherdirection}; // back along the other vehicle's axis - auto const othervehicleaccelerationchange{(othervehiclenewvelocity - othervehicle->V) / dt}; - othervehicle->AccS += othervehicleaccelerationchange * accelerationspike; - othervehicle->V = othervehiclenewvelocity; - } -} - -void TMoverParameters::damage_coupler(int const End) -{ - - auto &thiscoupler{Couplers[End]}; - - if (thiscoupler.type() == TCouplerType::Articulated) - { - return; - } // HACK: don't break articulated couplings no matter what - - if (SetFlag(DamageFlag, dtrain_coupling)) - EventFlag = true; - - auto const hosetorn{(thiscoupler.CouplingFlag & coupling::brakehose) == coupling::brakehose}; - if (hosetorn) - { - // hamowanie nagle - zerwanie przewodow hamulcowych - AlarmChainFlag = true; - } - - thiscoupler.CouplingFlag = 0; - thiscoupler.broken = true; - - if (thiscoupler.Connected != nullptr) - { - // break connection with other vehicle, if there's any: on the end it's coupled with, which is the front one too - // for vehicles facing each other - auto &othercoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr]}; - othercoupler.CouplingFlag = coupling::faux; - // the coupling broke between the two, either end can be repaired - othercoupler.broken = true; - if (hosetorn && coupler_physics_at(End)) - { - // the brake pipe of the other part of the train vents through the torn hose as well - thiscoupler.Connected->AlarmChainFlag = true; - } - } - - WriteLog("Bad driving: " + Name + " broke a coupler"); -} - -// ************************************************************************************************* -// physics.collisions new: the collisions past the buffers, see collision.h -// ************************************************************************************************* -collision::vehicle_kind TMoverParameters::collision_kind() const -{ - auto const powered{EngineType != TEngineType::None && EngineType != TEngineType::Dumb}; - auto const unit{is_multiple_unit()}; - auto const passengers{std::any_of(LoadAttributes.begin(), LoadAttributes.end(), [](auto const &Load) { return ToLower(Load.name).starts_with("passenger"); })}; - // a coach heats its compartments; the crash zone is a matter of each end (crush_of()) - return collision::kind_of(powered, unit || passengers || (false == powered && HeatingPower > 0.0), false); -} - -collision::crush_curve TMoverParameters::crush_curve_at(int const End) const -{ - return collision::crush_of(Couplers[End].collision, collision_kind()); -} - -double TMoverParameters::buffer_height_at(int const End) const -{ - auto const loadshare{MaxLoad > 0.f ? LoadAmount / MaxLoad : 0.0}; - return collision::buffer_height(Couplers[End].collision, collision_kind(), loadshare); -} - -void TMoverParameters::derail_in_collision(DerailReason const Reason, std::string const &Why) -{ - if (false == SetFlag(DamageFlag, dtrain_out)) - { - return; - } - // upright, it slides on the sleepers and keeps passing the forces on - Derailed = derailment::outcome::off_rails; - DerailCause = derail_motion::cause::collision; - DerailAcceleration = 0.0; - DerailSide = 0; - CollisionDerail = Reason; - EventFlag = true; - MainSwitch(false, range_t::local); - if (Vel < 5.0) - { - // HACK: prevent permanent axle spin in static vehicle after a collision - nrot = 0.0; - SlippingWheels = false; - } - // the brake hoses tear: the brake pipe vents and the rest of the train brakes in emergency - tear_brake_hoses(*this); - derailment_monitor.reset(); - pushed_off_monitor.reset(); - ErrorLog(std::format("Bad driving: {} derailed in a collision, {}: {}", Name, Reason == COLLISION_OVERRIDE ? "overriding" : "pushed off the track", Why)); -} - -namespace -{ - -char const *end_name(int const End) -{ - return End == end::front ? "front" : "rear"; -} - -char const *kind_name(collision::vehicle_kind const Kind) -{ - switch (Kind) - { - case collision::vehicle_kind::locomotive: - return "locomotive"; - case collision::vehicle_kind::coach: - return "coach"; - case collision::vehicle_kind::crash_zone: - return "crash zone"; - case collision::vehicle_kind::wagon: - default: - return "wagon"; - } -} - -// the force pressing the end in, of the coupling or of the buffers touching [N]: forwards at the front pulls -double compression_at(TCoupling const &Coupler, int const End) -{ - return std::max(0.0, (End == end::front ? -1.0 : 1.0) * Coupler.CForce); -} - -// the steel parts of both ends in series [N/m] -double steel_stiffness(TCoupling const &First, TCoupling const &Second) -{ - auto const first{std::max(First.physics.link_stiffness, 1.0)}; - auto const second{std::max(Second.physics.link_stiffness, 1.0)}; - return first * second / (first + second); -} - -// the hit of the pair in the step, for the push off the track: the peak force and how long it acted -void record_hit(TCoupling &Coupler, double const Force, double const Duration) -{ - Coupler.hit_force = std::max(Coupler.hit_force, Force); - Coupler.hit_duration = std::max(Coupler.hit_duration, Duration); -} - -} // namespace - -bool TMoverParameters::crush_hit(int const End, double const dt) -{ - auto &thiscoupler{Couplers[End]}; - auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; - auto const otherend{Neighbours[End].vehicle_end}; - auto &othercoupler{othervehicle->Couplers[otherend]}; - - auto const physical{coupler_physics_at(End)}; - // the buffers pressed all the way, not the draw gear pulled all the way, and the pair still closing in - auto const buffers{physical ? thiscoupler.physics_state.stop < 0 : thiscoupler.Dist < 0.0}; - auto const closing{-CouplerVelocityDifference(End, *othervehicle, otherend) * DirF(End)}; - if (false == Global.crash_damage || false == buffers || closing <= 0.0) - { - // the hit is over, the next one is another one for the monitor - thiscoupler.crush_monitored = false; - othercoupler.crush_monitored = false; - return false; - } - auto const monitor{Global.collisions == global_settings::collision_model::monitor}; - // put down by the scenery inside each other: pressed past the stop of the buffers and the crush of the ends by more - // than a hit takes them in a step. the legacy collision pushes them apart; their springs, the stops at both ends - // and the neighbours found at either end there make up any closing velocity, not a hit - auto const stop{std::max(thiscoupler.DmaxB + othercoupler.DmaxB, thiscoupler.physics.buffers.travel + othercoupler.physics.buffers.travel) + thiscoupler.crush + othercoupler.crush}; - auto const overlap{-static_cast(Neighbours[End].distance)}; - if (overlap > stop + collision::inside_margin + closing * dt) - { - // nor is what their springs took in pressed past the stop and back a hit, for as long as the buffers touch - thiscoupler.contact.inside(); - othercoupler.contact.inside(); - if (false == thiscoupler.inside_reported) - { - thiscoupler.inside_reported = true; - othercoupler.inside_reported = true; - WriteLog(std::format("Bad scenery: {} and {} are inside each other, their buffers pressed {:.2f} m past their stop, no crush", Name, othervehicle->Name, overlap - stop)); - } - return false; - } - // parting at the start of the step: what closes the pair in now is the knock of a hit of either vehicle in the step, - // or of the vehicles inside each other next to it, not a hit of this pair. the legacy collision takes it; a pair - // still closing in at the start of the next step is a hit - if (thiscoupler.closing < 0.0) - { - return false; - } - // a vehicle derailed the legacy way (the end of the track, say) stays where it is, whatever hits it from outside its - // train. the vehicles coupled to it push it on, as the train behind a derailed vehicle does: a wall to them, it - // stopped the whole train at once, and the vehicles behind it crushed by the energy of the train - auto const coupled{thiscoupler.CouplingFlag != coupling::faux}; - auto const wall{false == coupled && TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none}; - auto const otherwall{false == coupled && TestFlag(othervehicle->DamageFlag, dtrain_out) && othervehicle->Derailed == derailment::outcome::none}; - if (wall && otherwall) - { - return false; - } - constexpr double immovable{1e12}; - auto const mass{wall ? immovable : TotalMass}; - auto const othermass{otherwall ? immovable : othervehicle->TotalMass}; - auto const loss{physical ? coupler_physics::solid_hit_loss(thiscoupler.physics, othercoupler.physics) : (thiscoupler.beta + othercoupler.beta) / 2.0}; - - auto const firstcurve{crush_curve_at(End)}; - auto const secondcurve{othervehicle->crush_curve_at(otherend)}; - auto const stiffness{steel_stiffness(thiscoupler, othercoupler)}; - auto const springs{compression_at(thiscoupler, End)}; - collision::hit_input input; - input.velocity = closing; - input.mass1 = mass; - input.mass2 = othermass; - input.restitution = std::sqrt(std::max(0.0, 1.0 - loss)); - input.stiffness = stiffness; - input.springs = springs; - // the monitor takes the whole hit at once, over a second, longer than the crush of any hit lasts - input.dt = monitor ? 1.0 : dt; - input.start_velocity = thiscoupler.closing; - // the crush takes only what the hit brings past what the buffers of EN 15551 of both ends take in. an automatic - // coupler (or its adapter) has no buffers at the side: its draft gear takes in what its springs of the .fiz do - auto const reduced{mass * othermass / (mass + othermass)}; - auto const central{thiscoupler.type() == TCouplerType::Automatic || othercoupler.type() == TCouplerType::Automatic || thiscoupler.has_adapter() || othercoupler.has_adapter()}; - auto const capacity{central ? 0.0 : collision::buffer_capacity(thiscoupler.collision, collision_kind()) + collision::buffer_capacity(othercoupler.collision, othervehicle->collision_kind())}; - auto const hitvelocity{std::max(closing, thiscoupler.closing)}; - input.budget = thiscoupler.contact.budget(reduced, hitvelocity, capacity); - auto const hit{collision::hit({firstcurve, thiscoupler.crush}, {secondcurve, othercoupler.crush}, input)}; - // the override, by the crush of both ends - auto const climbing_of = [&](double const Crush1, double const Crush2) { - collision::override_input climbing; - climbing.crush1 = Crush1; - climbing.crush2 = Crush2; - climbing.mass1 = TotalMass - Mred; - climbing.mass2 = othervehicle->TotalMass - othervehicle->Mred; - climbing.height1 = buffer_height_at(End); - climbing.height2 = othervehicle->buffer_height_at(otherend); - climbing.anticlimbers = collision::anticlimber_of(thiscoupler.collision, collision_kind()) && collision::anticlimber_of(othercoupler.collision, othervehicle->collision_kind()); - climbing.zone1 = firstcurve.densify; - climbing.zone2 = secondcurve.densify; - return climbing; - }; - if (monitor) - { - if (hit.crushing && false == thiscoupler.crush_monitored) - { - thiscoupler.crush_monitored = true; - othercoupler.crush_monitored = true; - ++crush_reports; - auto const crush1{thiscoupler.crush + hit.crush1}; - auto const crush2{othercoupler.crush + hit.crush2}; - auto const climbed{collision::override_of(climbing_of(crush1, crush2))}; - auto const torn{std::max(crush1, crush2) >= collision::draw_gear_crush}; - std::string const outcome{climbed.first && climbed.second ? std::string{"both would leave the rails"} - : climbed.first ? Name + " would ride up onto " + othervehicle->Name - : climbed.second ? othervehicle->Name + " would ride up onto " + Name - : std::string{"both would stay on the rails"}}; - WriteLog(std::format("collision monitor: {} and {} collided at {:.0f} km/h: the {} end of {} ({:.1f} t {}) would crush by {:.2f} m, the {} end of {} ({:.1f} t {}) by {:.2f} m, " - "at {:.0f} kN; draw gear {}; {}", - Name, othervehicle->Name, closing * 3.6, end_name(End), Name, TotalMass / 1000.0, kind_name(collision_kind()), crush1, end_name(otherend), othervehicle->Name, - othervehicle->TotalMass / 1000.0, kind_name(othervehicle->collision_kind()), crush2, hit.force / 1000.0, torn ? "torn off" : "holds", outcome)); - } - return false; - } - if (false == hit.crushing) - { - // the steel takes it, the legacy collision follows; its peak, under the force an end gives at, for the push - // off the track - auto const weaker{std::min(firstcurve.force(thiscoupler.crush), secondcurve.force(othercoupler.crush))}; - auto const peak{std::min(springs + coupler_physics::impact_force(closing, stiffness, mass, othermass), weaker)}; - auto const duration{std::min(dt, (1.0 + input.restitution) * std::sqrt(reduced / stiffness))}; - record_hit(thiscoupler, peak, duration); - record_hit(othercoupler, peak, duration); - return false; - } - // the other vehicle doesn't take it again in this step - thiscoupler.hit_handled = true; - othercoupler.hit_handled = true; - - // the hit at the force the weaker end gives at pushes the vehicles apart: the velocities alone change, along this - // vehicle's axis as in CollisionDetect() - auto const otherdirection{DirPatch(End, otherend)}; - auto const apart{End == end::front ? -1.0 : 1.0}; - if (false == wall) - { - V += apart * hit.impulse / mass; - } - if (false == otherwall) - { - othervehicle->V -= apart * hit.impulse / othermass * otherdirection; - } - record_hit(thiscoupler, hit.force, hit.duration); - record_hit(othercoupler, hit.force, hit.duration); - - // the energy the crush took, for both vehicles' count of the contact - thiscoupler.contact.crushed(hit.work); - othercoupler.contact.crushed(hit.work); - // what the log tells of the pair, for the analysis of a crush - auto const kinetic{0.5 * reduced * hitvelocity * hitvelocity}; - auto const pair = [&]() { - return std::format("{} {:.1f} t {}, {} end crushed {:.2f} m, gives at {:.0f} kN; {} {:.1f} t {}, {} end crushed {:.2f} m, gives at {:.0f} kN; force {:.0f} kN, springs {:.0f} kN, " - "closing at {:.1f} km/h at the start of the step; energy {:.0f} kJ of the motion and {:.0f} kJ in the buffers, past the {:.0f} kJ they take in, " - "{:.0f} kJ crushed in the contact", - Name, TotalMass / 1000.0, kind_name(collision_kind()), end_name(End), thiscoupler.crush, firstcurve.force(thiscoupler.crush) / 1000.0, othervehicle->Name, - othervehicle->TotalMass / 1000.0, kind_name(othervehicle->collision_kind()), end_name(otherend), othercoupler.crush, - secondcurve.force(othercoupler.crush) / 1000.0, hit.force / 1000.0, springs / 1000.0, input.start_velocity * 3.6, kinetic / 1000.0, - thiscoupler.contact.absorbed() / 1000.0, capacity / 1000.0, thiscoupler.contact.crush_work() / 1000.0); - }; - auto const crushed = [&](TMoverParameters const &Vehicle, int const VehicleEnd, double const Before, double const After) { - if (Before < collision::crush_mark && After >= collision::crush_mark) - { - ErrorLog(std::format("Bad driving: {} and {} collided at {:.0f} km/h, the {} end of {} crushed ({})", Name, othervehicle->Name, closing * 3.6, end_name(VehicleEnd), Vehicle.Name, pair())); - } - }; - auto const before{thiscoupler.crush}; - auto const otherbefore{othercoupler.crush}; - thiscoupler.crush += hit.crush1; - othercoupler.crush += hit.crush2; - crushed(*this, End, before, thiscoupler.crush); - crushed(*othervehicle, otherend, otherbefore, othercoupler.crush); - - // the crushed headstock tears off the draw gear, with the brake hose: both parts of the train brake in emergency. - // the coupler of an end not coupled is gone as well, it doesn't couple any more - if (thiscoupler.CouplingFlag != coupling::faux && std::max(thiscoupler.crush, othercoupler.crush) >= collision::draw_gear_crush) - { - auto const hose{(thiscoupler.CouplingFlag & coupling::brakehose) == coupling::brakehose}; - damage_coupler(End); - if (hose) - { - othervehicle->AlarmChainFlag = true; - } - } - else if (thiscoupler.CouplingFlag == coupling::faux) - { - if (thiscoupler.crush >= collision::draw_gear_crush && false == thiscoupler.broken) - { - damage_coupler(End); - } - if (othercoupler.crush >= collision::draw_gear_crush && false == othercoupler.broken) - { - othervehicle->damage_coupler(otherend); - } - } - - // the end crushed deep enough lets one vehicle climb onto the other one - auto const climbing{climbing_of(thiscoupler.crush, othercoupler.crush)}; - auto const climbed{collision::override_of(climbing)}; - auto const why = [&](TMoverParameters const &Climber, TMoverParameters const &Other) { - return std::format("{} rode up onto {} at {:.0f} km/h, the ends crushed by {:.2f} m, buffers at {:.0f} / {:.0f} mm, anticlimbers {} ({})", Climber.Name, Other.Name, closing * 3.6, - thiscoupler.crush + othercoupler.crush, climbing.height1 * 1000.0, climbing.height2 * 1000.0, climbing.anticlimbers ? "yes" : "no", pair()); - }; - if (climbed.first) - { - derail_in_collision(COLLISION_OVERRIDE, why(*this, *othervehicle)); - } - if (climbed.second) - { - othervehicle->derail_in_collision(COLLISION_OVERRIDE, why(*othervehicle, *this)); - } - return true; -} - -void TMoverParameters::check_pushed_off(double const dt, double const Distance) -{ - if (Global.collisions != global_settings::collision_model::physical || false == Global.crash_damage || TestFlag(DamageFlag, dtrain_out) || false == TestFlag(CategoryFlag, 1) || - DebugModeFlag) - { - pushed_off_monitor.reset(); - return; - } - collision::pushed_vehicle vehicle; - vehicle.mass = TotalMass - Mred; - vehicle.axles = NAxles > 0 ? NAxles : 4; - vehicle.length = Dim.L; - vehicle.pivots = BDist; - vehicle.axle_base = ADist > 0.0 ? ADist : BDist; - - auto climbs{false}; - auto distance{0.0}; - auto lifted{false}; - auto duration{0.0}; - auto worst{0.0}; - auto worstforce{0.0}; - auto worstend{static_cast(end::front)}; - for (int end = end::front; end <= end::rear; ++end) - { - auto const *other{Neighbours[end].vehicle}; - if (other == nullptr) - { - continue; - } - auto const &coupler{Couplers[end]}; - collision::pushed_end pushed; - pushed.other_length = other->MoverParameters->Dim.L; - pushed.crush = coupler.crush; - // the steady push of the springs over the step, or the peak of a hit for as long as it lasted: the flange climbs - // over the distance the wheels rolled meanwhile, a wheel lifted off the rail goes in a short time, rolling or not - for (auto const &[force, time] : {std::pair{compression_at(coupler, end), dt}, std::pair{coupler.hit_force, coupler.hit_duration}}) - { - pushed.force = force; - auto const wheel{collision::pushed_forces(vehicle, pushed, RunningShape.R)}; - auto const ratio{wheel.ratio()}; - if (ratio < derailment::climbing_limit) - { - continue; - } - climbs = true; - distance = std::max(distance, Distance * std::clamp(time / std::max(dt, 1e-9), 0.0, 1.0)); - if (wheel.lifted()) - { - lifted = true; - duration = std::max(duration, time); - } - if (ratio > worst) - { - worst = ratio; - worstforce = force; - worstend = end; - } - } - } - if (pushed_off_monitor.update(climbs, distance, lifted, duration)) - { - derail_in_collision(COLLISION_PUSHED_OFF, std::format("{:.0f} kN pressing its {} end in, {}, at {:.0f} km/h, curve radius {:.0f} m: Y/Q {:.2f} ({:.1f} t {}, {} axles, " - "springs {:.0f} / {:.0f} kN, hits {:.0f} / {:.0f} kN, crushed {:.2f} / {:.2f} m)", - worstforce / 1000.0, end_name(worstend), - lifted ? std::format("its wheels lifted off the rail for {:.3f} s", pushed_off_monitor.time()) - : std::format("the flange climbing over {:.2f} m", pushed_off_monitor.distance()), - Vel, std::abs(RunningShape.R), std::min(worst, 99.0), - vehicle.mass / 1000.0, kind_name(collision_kind()), vehicle.axles, compression_at(Couplers[end::front], end::front) / 1000.0, - compression_at(Couplers[end::rear], end::rear) / 1000.0, Couplers[end::front].hit_force / 1000.0, Couplers[end::rear].hit_force / 1000.0, - Couplers[end::front].crush, Couplers[end::rear].crush)); - } -} - -namespace -{ - -// the end as it was built (physics.collisions new): not crushed, and nothing of a contact or a hit kept -void restore_end(TCoupling &Coupler) -{ - Coupler.crush = 0.0; - Coupler.contact.reset(); - Coupler.hit_handled = false; - Coupler.hit_force = 0.0; - Coupler.hit_duration = 0.0; - Coupler.crush_monitored = false; - Coupler.inside_reported = false; -} - -// the coupler as good as new, its end with it (the crush that tore the draw gear off), the vehicle without the coupler -// damage (and the emergency braking of the torn brake hose) once neither of its couplers is broken -void repair(TMoverParameters &Vehicle, TCoupling &Coupler) -{ - Coupler.broken = false; - Coupler.stretch_duration = 0.f; - Coupler.physics_state.couple(); - restore_end(Coupler); - if (Vehicle.Couplers[end::front].broken || Vehicle.Couplers[end::rear].broken) - { - return; - } - ClearFlag(Vehicle.DamageFlag, dtrain_coupling); - // either vehicle of the pair may have been braking through the torn hose - Vehicle.AlarmChainFlag = false; -} - -} // namespace - -bool TMoverParameters::repair_coupler(int const End) -{ - auto &thiscoupler{Couplers[End]}; - if (false == thiscoupler.broken) - { - return false; - } - repair(*this, thiscoupler); - // the other half of the coupling, which may be the vehicle flagged with the damage - if (auto *other{thiscoupler.Connected}; other != nullptr && other->Couplers[thiscoupler.ConnectedNr].broken) - { - repair(*other, other->Couplers[thiscoupler.ConnectedNr]); - } - WriteLog(std::format("Coupler of {} repaired, at its {} end", Name, End == end::front ? "front" : "rear")); - return true; -} - -static_assert(derailment::track_damage::railwear == dtrack_railwear && derailment::track_damage::freerail == dtrack_freerail && derailment::track_damage::thinrail == dtrack_thinrail && - derailment::track_damage::railbend == dtrack_railbend); - -double TMoverParameters::centre_of_gravity() const -{ - auto const kind{EngineType == TEngineType::None ? derailment::vehicle_class::unpowered : derailment::vehicle_class::powered}; - auto const empty{CentreOfGravity > 0.0 ? CentreOfGravity : derailment::default_centre_of_gravity(Dim.H, kind)}; - auto const loadmass{TotalMass - Mass - Mred}; - auto const loadshare{MaxLoad > 0.f ? LoadAmount / MaxLoad : 1.0}; - return derailment::loaded_centre_of_gravity(empty, Mass, loadmass, loadshare, Floor, Dim.H); -} - -void TMoverParameters::check_derailment(TTrackShape const &Shape, TTrackParam const &Track, double const Distance) -{ - if (TestFlag(DamageFlag, dtrain_out) || false == TestFlag(CategoryFlag, 1) || DebugModeFlag) - { - derailment_monitor.reset(); - return; - } - derailment::vehicle_state vehicle; - vehicle.mass = TotalMass - Mred; - vehicle.axles = NAxles > 0 ? NAxles : 4; - vehicle.length = Dim.L; - vehicle.axle_base = ADist > 0.0 ? ADist : BDist; - vehicle.centre_of_gravity = centre_of_gravity(); - for (int end = end::front; end <= end::rear; ++end) - { - auto const *other{Neighbours[end].vehicle}; - if (other == nullptr) - { - continue; - } - // the force of the coupling, or of the buffers touching, along this vehicle: forwards at the front pulls - vehicle.ends[end].compression = (end == end::front ? -1.0 : 1.0) * Couplers[end].CForce; - vehicle.ends[end].other_length = other->MoverParameters->Dim.L; - } - derailment::track_state track; - track.radius = Shape.R; - track.cant = Shape.dHrail; - track.gauge = TrackW; - track.uneven_curvature = Shape.uneven_curvature; - track.uneven_cross = Shape.uneven_cross; - track.buckle_curvature = Shape.buckle_curvature; - track.damage = Track.DamageFlag; - - auto const verdict{derailment_monitor.update(vehicle, track, V, Distance)}; - if (verdict.result == derailment::outcome::none) - { - return; - } - if (Global.derailment == global_settings::derailment_model::physical) - { - derail(verdict, vehicle, track, Track.Name); - return; - } - // physics.derailment monitor: the legacy draw decides, the log tells what the criteria would do, once on a track - if (derailment_reported.has_value() && *derailment_reported == Track.Name) - { - return; - } - derailment_reported = Track.Name; - ++derailment_reports; - WriteLog("derailment monitor: " + Name + " " + derailment::report(verdict, vehicle, track, V, Track.Name != nullptr ? *Track.Name : std::string{})); -} - -void TMoverParameters::derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track, std::string const *TrackName) -{ - if (false == SetFlag(DamageFlag, dtrain_out)) - { - return; - } - Derailed = Verdict.result; - DerailCause = Verdict.result == derailment::outcome::overturned ? derail_motion::cause::overturned : derail_motion::cause::off_rails; - // out of the curve; a buckle bending the line against the curve more than the curve does throws it into the curve - DerailAcceleration = std::abs(Track.radius) > 1e-3 && derailment::line_curvature(Track) < 0.0 ? -Verdict.acceleration : Verdict.acceleration; - DerailSide = 0; - EventFlag = true; - MainSwitch(false, range_t::local); - // the brake hoses tear: the brake pipe vents and the rest of the train brakes in emergency - tear_brake_hoses(*this); - ErrorLog("Bad driving: " + Name + " " + derailment::report(Verdict, Vehicle, Track, V, TrackName != nullptr ? *TrackName : std::string{})); - if (Track.buckle_curvature != 0.0) - { - ErrorLog(std::format("Bad driving: {} derailed on buckled track, the buckle bending the line by 1/{:.0f} m {} the curve", Name, 1.0 / std::abs(Track.buckle_curvature), - Track.buckle_curvature > 0.0 ? "with" : "against")); - } -} - -void TMoverParameters::rerail() -{ - ClearFlag(DamageFlag, dtrain_out); - Derailed = derailment::outcome::none; - // and back on the track; what derailed it before has no say in how it leaves the track the next time - OffTrack.reset(); - DerailCause = derail_motion::cause::off_rails; - DerailAcceleration = 0.0; - DerailSide = 0; - derailment_monitor.reset(); - derailment_distance = 0.0; - derailment_reported.reset(); - // nor derailed in a collision - CollisionDerail = NONE; - pushed_off_monitor.reset(); - // back on the axis of the track, which the derailment shifted the vehicle off aside and down (a road vehicle keeps - // its place on the road) - if (TestFlag(CategoryFlag, 1)) - { - OffsetTrackH = 0.0; - OffsetTrackV = 0.0; - } - // a derailed vehicle which stopped sleeps (Global.physics_sleepheld) with the friction of the derailment in FStand and - // where the derailment put it, until something wakes it: the physics on, for the friction of the rails and its place on - // them. it is put back by a command (resetconsist, SetDamage) or by the road spawner, which sets it going anyway - switch_physics(true, wake_cause::command); -} - -void TMoverParameters::repair_damage() -{ - DamageFlag = 0; - EngDmgFlag = 0; - WheelFlat = 0.0; - AlarmChainFlag = false; - // the crushed ends rebuilt - for (auto &coupler : Couplers) - { - restore_end(coupler); - } - rerail(); -} - -void TMoverParameters::Derail(DerailReason const Reason) -{ - if (SetFlag(DamageFlag, dtrain_out)) - { - EventFlag = true; - MainSwitch(false, range_t::local); - - auto const velocity{V}; - AccS *= 0.65; - V *= 0.65; - // physics.collisions new: the vehicles coupled to it lose the speed with it. the cut in a step stands for the - // train coming to a stop with the vehicle; the coupled ones keeping their speed would run into it at a third of - // the speed of the train, and crush their ends and ride up onto it for a hit no train had - if (Global.collisions == global_settings::collision_model::physical && TestFlag(CategoryFlag, 1)) - { - change_train_velocity(V - velocity); - } - RunningShape.R = 0; - if (Vel < 5.0) - { - // HACK: prevent permanent axle spin in static vehicle after a collision - nrot = 0.0; - SlippingWheels = false; - } - // physics.derailment new: off the end of the track the vehicle runs on straight on its wheels, sliding on the - // ground as the vehicles the criteria derail do, and its brake hoses tear - if (Reason == END_OF_TRACK && Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1)) - { - Derailed = derailment::outcome::off_rails; - DerailCause = derail_motion::cause::end_of_track; - DerailAcceleration = 0.0; - DerailSide = 0; - tear_brake_hoses(*this); - } - - // Print a message in the log. - if (Reason == END_OF_TRACK) - ErrorLog("Bad driving: " + Name + " derailed due to end of track"); - else if (Reason == TOO_HIGH_SPEED) - ErrorLog("Bad driving: " + Name + " derailed due to too high speed"); - else if (Reason == GAUGE_MISMATCH) - ErrorLog("Bad dynamic: " + Name + " derailed due to track width"); // błąd w scenerii - else if (Reason == WRONG_TRACK_TYPE) - ErrorLog("Bad dynamic: " + Name + " derailed due to wrong track type"); // błąd w scenerii - else if (Reason == COLLISION) - WriteLog("Bad driving: " + Name + " derailed"); // This reason also generates its own message in `TMoverParameters::CollisionDetect()` - else if (Reason == TRAILED_SWITCH) - ErrorLog("Bad driving: " + Name + " derailed trailing through a switch with a movable nose set the other way"); - } -} - -bool TMoverParameters::leaves_track() const -{ - return Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1) && TestFlag(DamageFlag, dtrain_out) && Derailed != derailment::outcome::none && - false == OffTrack.active(); -} - -void TMoverParameters::pull_off(int const Side, double const Acceleration, std::string const &Why) -{ - if (Global.derailment != global_settings::derailment_model::physical || false == SetFlag(DamageFlag, dtrain_out)) - { - return; - } - // upright, its flange climbs the rail the coupling pulls it over - Derailed = derailment::outcome::off_rails; - DerailCause = derail_motion::cause::pulled_off; - DerailAcceleration = Acceleration; - DerailSide = Side; - EventFlag = true; - MainSwitch(false, range_t::local); - tear_brake_hoses(*this); - derailment_monitor.reset(); - ErrorLog(std::format("Bad driving: {} pulled off the track by the vehicle coupled to it, {}", Name, Why)); -} - -void TMoverParameters::change_train_velocity(double const Change) -{ - // the vehicles coupled to this one in a line, each with the direction of its axis to the axis of this one - std::vector> train{{this, 1}}; - for (std::size_t i = 0; i < train.size(); ++i) - { - auto const [vehicle, direction] = train[i]; - for (int end = end::front; end <= end::rear; ++end) - { - auto const &coupler{vehicle->Couplers[end]}; - auto *other{coupler.Connected}; - if (other == nullptr || coupler.CouplingFlag == coupling::faux || std::any_of(train.begin(), train.end(), [other](auto const &Entry) { return Entry.first == other; })) - { - continue; - } - auto const otherdirection{direction * DirPatch(end, coupler.ConnectedNr)}; - other->V += Change * otherdirection; - train.emplace_back(other, otherdirection); - } - } -} - -// ************************************************************************************************* -// Oblicza przemieszczenie taboru -// ************************************************************************************************* -double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShape &Shape, TTrackParam const &Track, TTractionParam const &ElectricTraction, TLocation const &NewLoc, TRotation const &NewRot) -{ - - if (!TestFlag(DamageFlag, dtrain_out)) - { // Ra: to przepisywanie tu jest bez sensu - RunningShape = Shape; - RunningTrack = Track; - RunningTraction = ElectricTraction; - - // if (!DynamicBrakeFlag) - // RunningTraction.TractionVoltage = ElectricTraction.TractionVoltage /*- - // abs(ElectricTraction.TractionResistivity * - // (Itot + HVCouplers[0][0] + HVCouplers[1][0]))*/; - // else - // RunningTraction.TractionVoltage = - // ElectricTraction.TractionVoltage /*- - // abs(ElectricTraction.TractionResistivity * Itot * - // 0)*/; // zasadniczo ED oporowe nie zmienia napięcia w sieci - } - else if (OffTrack.active()) - { - // off the track the grade is that of the ground under it, along its heading - RunningShape.dHtrack = Shape.dHtrack; - } - - if (CategoryFlag == 4) - OffsetTrackV = TotalMass / (Dim.L * Dim.W * 1000.0); - else if (TestFlag(CategoryFlag, 1) && TestFlag(RunningTrack.CategoryFlag, 1) && TestFlag(DamageFlag, dtrain_out)) - { - OffsetTrackV = -0.2; - OffsetTrackH = Sign(RunningShape.R) * 0.2; - } - - // TODO: investigate, seems supplied NewRot is always 0 although the code here suggests some actual values are expected - Loc = NewLoc; - Rot = NewRot; - - if (dL == 0) // oblicz przesuniecie} - { - auto const AccSprev{AccS}; - // przyspieszenie styczne - AccS = std::lerp(AccSprev, FTotal / TotalMass, 0.5); - // std::clamp( dt * 3.0, 0.0, 1.0 ) ); // prawo Newtona ale z wygladzaniem (średnia z poprzednim) - - // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce(), and so does one - // derailed the legacy way with physics.collisions new - if (TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this)) - AccS = -Sign(V) * g * 1; // random(0.0, 0.1) - // stuck in the ballast: the friction holds a derailed vehicle once it stopped, until the forces on it are larger - auto const stuck{(Derailed != derailment::outcome::none || legacy_derailed_slides(*this)) && V == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; - if (stuck) - AccS = 0.0; - - // przyspieszenie normalne - if (abs(Shape.R) > 0.01) - AccN = square(V) / Shape.R + g * Shape.dHrail / TrackW; // Q: zamieniam SQR() na sqr() - else - AccN = g * Shape.dHrail / TrackW; - - // velocity change - auto const Vprev{V}; - V += (3.0 * AccS - AccSprev) * dt / 2.0; // przyrost predkosci - if (stuck) - V = 0.0; - if (V * Vprev <= 0 && std::abs(FStand) > std::abs(FTrain)) - { - // tlumienie predkosci przy hamowaniu - // zahamowany - V = 0; - } - - // tangential acceleration, from velocity change - AccSVBased = std::lerp(AccSVBased, (V - Vprev) / dt, std::clamp(dt * 3.0, 0.0, 1.0)); - - // vertical acceleration - AccVert = std::abs(AccVert) < 0.01 ? 0.0 : AccVert * 0.5; - // szarpanie - /* - #ifdef EU07_USE_FUZZYLOGIC - if( FuzzyLogic( ( 10.0 + Track.DamageFlag ) * Mass * Vel / Vmax, 500000.0, p_accn ) ) { - // Ra: czemu tu masa bez ładunku? - AccV /= ( 2.0 * 0.95 + 2.0 * Random() * 0.1 ); // 95-105% of base modifier (2.0) - } - else - #endif - AccV = AccV / 2.0; - - if (AccV > 1.0) - AccN += (7.0 - Random(5)) * (100.0 + Track.DamageFlag / 2.0) * AccV / 2000.0; - */ - // wykolejanie na luku oraz z braku szyn - if (TestFlag(CategoryFlag, 1)) - { - if (TestFlag(Track.DamageFlag, dtrack_norail)) - Derail(END_OF_TRACK); - // too fast in a curve: the legacy draw in every step (physics.derailment old), or the physical criteria - // once the step's distance is known, below - if ((Global.derailment == global_settings::derailment_model::old || Global.derailment == global_settings::derailment_model::monitor) && FuzzyLogic(AccN / g * (1.0 + 0.1 * (Track.DamageFlag & dtrack_freerail)), TrackW / Dim.H, 1)) - Derail(TOO_HIGH_SPEED); - // wykolejanie na poszerzeniu toru - if (FuzzyLogic(abs(Track.Width - TrackW), TrackW / 10.0, 1)) - Derail(GAUGE_MISMATCH); - } - // wykolejanie wkutek niezgodnosci kategorii toru i pojazdu - if (!TestFlag(RunningTrack.CategoryFlag, CategoryFlag)) - Derail(WRONG_TRACK_TYPE); - - // dL:=(V+AccS*dt/2)*dt; - // przyrost dlugosci czyli przesuniecie - dL = (3.0 * V - Vprev) * dt / 2.0; // metoda Adamsa-Bashfortha} - if (Global.derailment == global_settings::derailment_model::physical || Global.derailment == global_settings::derailment_model::monitor) - { - // over the distance of this step and of the simpler ones of the frame before it - check_derailment(Shape, Track, derailment_distance + std::abs(dL)); - } - derailment_distance = 0.0; - // ale jesli jest kolizja (zas. zach. pedu) to...} - for (int b = 0; b < 2; b++) - if (Couplers[b].CheckCollision) - CollisionDetect(b, dt); // zmienia niejawnie AccS, V !!! - check_pushed_off(dt, std::abs(dL)); - - } // liczone dL, predkosc i przyspieszenie - - auto const d{(EngineType == TEngineType::WheelsDriven ? dL * CabActive : // na chwile dla testu - dL)}; - - DistCounter += fabs(dL) / 1000.0; - Odometer.run(dL); - dL = 0; - - // koniec procedury, tu nastepuja dodatkowe procedury pomocnicze - compute_movement_(dt); - - // security system - SecuritySystemCheck(dt1); - - return d; -}; - -// ************************************************************************************************* -// Oblicza przemieszczenie taboru - uproszczona wersja -// ************************************************************************************************* - -double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Shape*/, TTrackParam & /*Track*/, TLocation const &NewLoc, TRotation const &NewRot) -{ - // T_MoverParameters::FastComputeMovement(dt, Shape, Track, NewLoc, NewRot); - - Loc = NewLoc; - Rot = NewRot; - - if (dL == 0) // oblicz przesuniecie - { - auto const AccSprev{AccS}; - // przyspieszenie styczne - AccS = std::lerp(AccSprev, FTotal / TotalMass, 0.5); - // std::clamp( dt * 3.0, 0.0, 1.0 ) ); // prawo Newtona ale z wygladzaniem (średnia z poprzednim) - - if (TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this)) - AccS = -Sign(V) * g * 1; // * random(0.0, 0.1) - auto const stuck{(Derailed != derailment::outcome::none || legacy_derailed_slides(*this)) && V == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; - if (stuck) - AccS = 0.0; - - // simple mode skips calculation of normal acceleration - - // velocity change - auto const Vprev{V}; - V += (3.0 * AccS - AccSprev) * dt / 2.0; // przyrost predkosci - if (stuck) - V = 0.0; - if (V * Vprev <= 0 && std::abs(FStand) > std::abs(FTrain)) - { - // tlumienie predkosci przy hamowaniu - // zahamowany - V = 0; - } - - // simple mode skips calculation of tangential acceleration - - // simple mode skips calculation of vertical acceleration - AccVert = 0.0; - - // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce(), and so does one - // derailed the legacy way with physics.collisions new - if (true == TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this) && Vel < 1.0) - { - V = 0.0; - AccS = 0.0; - } - - dL = (3.0 * V - Vprev) * dt / 2.0; // metoda Adamsa-Bashfortha - // the criteria of derailment go by the distance, checked in the full step which ends the frame - derailment_distance += std::abs(dL); - // ale jesli jest kolizja (zas. zach. pedu) to... - for (int b = 0; b < 2; b++) - if (Couplers[b].CheckCollision) - CollisionDetect(b, dt); // zmienia niejawnie AccS, V !!! - check_pushed_off(dt, std::abs(dL)); - } // liczone dL, predkosc i przyspieszenie - - auto const d{(EngineType == TEngineType::WheelsDriven ? dL * CabActive : // na chwile dla testu - dL)}; - - DistCounter += fabs(dL) / 1000.0; - Odometer.run(dL); - dL = 0; - - // koniec procedury, tu nastepuja dodatkowe procedury pomocnicze - compute_movement_(dt); - - return d; -}; - -// updates shared between 'fast' and regular movement computation methods -void TMoverParameters::compute_movement_(double const Deltatime) -{ - - // sprawdzanie i ewentualnie wykonywanie->kasowanie poleceń - if (LoadStatus > 0) // czas doliczamy tylko jeśli trwa (roz)ładowanie - LastLoadChangeTime += Deltatime; // czas (roz)ładunku - - RunInternalCommand(); - - // relay settings - // adjust motor overload relay threshold - if (EngineType == TEngineType::ElectricSeriesMotor && ImaxHi > ImaxLo) - { - if (MotorOverloadRelayHighThreshold) - { // set high threshold - if (TrainType != train_type::et42 ? RList[MainCtrlPos].Bn < 2 : MainCtrlPos == 0) - { - Imax = ImaxHi; - } - } - else - { // set low threshold - if (TrainType != train_type::et42 || MainCtrlPos == 0) - { - Imax = ImaxLo; - } - } - } - - // Uproszczona symulacja wentylatorow rezystora hamowania - - // Prad oddawany na rezystor - - // Wlacz wentylator jesli prad rekuperacji przekroczy maksymalny dla pasywnego chlodzenia rezystora - if (double Irh = abs(eimv[eimv_Pe]) - abs(eimv[eimv_Ipoj]); Irh > Imaxrpc && eimv[eimv_Ipoj] < 0) - { - BRVtimer = 0; - BRVentilators = true; - } - else - { - BRVtimer += Deltatime; - if (BRVtimer > BRVto) - BRVentilators = false; - } - - // the master controller set directly, not through IncMainCtrl()/DecMainCtrl() (AI, consist): the locked shunt follows it as well - ScndCtrlResistiveLockCheck(); - // automatyczny rozruch - if (EngineType == TEngineType::ElectricSeriesMotor && AutoRelayCheck()) - { - SetFlag(SoundFlag, sound::relay); - } - - if ((EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric) && dizel_Update(Deltatime)) - { - SetFlag(SoundFlag, sound::relay); - } - - // TODO: gather and move current calculations to dedicated method - TotalCurrent = 0; - - // low voltage power sources - LowVoltagePowerCheck(Deltatime); - // power sources - PantographsCheck(Deltatime); - GensetCheck(Deltatime); - // main circuit - MainsCheck(Deltatime); - // traction motors - MotorBlowersCheck(Deltatime); - // uklady hamulcowe: - ConverterCheck(Deltatime); - if (VeselVolume > 0) - Compressor = CompressedVolume / VeselVolume; - else - { - Compressor = 0; - CompressorFlag = false; - } - if (VeselVolume > 0.0) - { - // sprężarka musi mieć jakąś niezerową wydajność żeby rozważać jej załączenie i pracę - CompressorCheck(Deltatime); - } - if (Power > 1.0) - { - // w rozrządczym nie (jest błąd w FIZ!) - Ra 2014-07: teraz we wszystkich - UpdatePantVolume(Deltatime); // Ra 2014-07: obsługa zbiornika rozrządu oraz pantografów - } - // heating - HeatingCheck(Deltatime); - // lighting - LightsCheck(Deltatime); - - UpdateBrakePressure(Deltatime); - UpdatePipePressure(Deltatime); - UpdateBatteryVoltage(Deltatime); - UpdateScndPipePressure(Deltatime); // druga rurka, youBy - - if ((DCEMUED_CC & 1) != 0 && (Couplers[end::front].CouplingFlag & coupling::control) != 0) - { - DynamicBrakeEMUStatus &= Couplers[end::front].Connected->DynamicBrakeEMUStatus; - } - if ((DCEMUED_CC & 2) != 0 && (Couplers[end::rear].CouplingFlag & coupling::control) != 0) - { - DynamicBrakeEMUStatus &= Couplers[end::rear].Connected->DynamicBrakeEMUStatus; - } - - if (BrakeSlippingTimer > 0.8 && ASBType != 128) - { // ASBSpeed=0.8 - // hamulec antypoślizgowy - wyłączanie - Hamulec->ASB(0); - } - BrakeSlippingTimer += Deltatime; - // automatic doors - update_doors(Deltatime); - - m_plc.update(Deltatime); - - PowerCouplersCheck(Deltatime, coupling::highvoltage); - PowerCouplersCheck(Deltatime, coupling::power110v); - PowerCouplersCheck(Deltatime, coupling::power24v); - - Power24vVoltage = std::max(PowerCircuits[0].first, GetTrainsetVoltage(coupling::power24v)); - Power24vIsAvailable = Power24vVoltage > 0; - Power110vIsAvailable = PowerCircuits[1].first > 0 || GetTrainsetVoltage(coupling::power110v) > 0; -} - -void TMoverParameters::MainsCheck(double const Deltatime) -{ - - // if( MainsInitTime == 0.0 ) { return; } - - // TBD, TODO: move voltage calculation to separate method and use also in power coupler state calculation? - auto localvoltage{0.0}; - switch (EnginePowerSource.SourceType) - { - case TPowerSource::CurrentCollector: - { - localvoltage = std::max(localvoltage, PantographVoltage); - break; - } - case TPowerSource::Accumulator: - { - localvoltage = std::max(localvoltage, Power24vVoltage); - break; - } - default: - { - break; - } - } - if (GensetSelected()) - { - // the traction selector of a dual-mode vehicle on the genset isolates the pantographs - localvoltage = Genset.voltage; - } - // a line breaker closed ahead of the pantographs gets ready on the low voltage circuits - auto const maincircuitpowersupply{std::abs(localvoltage) > 0.1 || GetTrainsetHighVoltage() > 0.1 || (PantographsRequireMains && (Power24vIsAvailable || Power110vIsAvailable))}; - - if (true == maincircuitpowersupply) - { - // all is well - if (MainsInitTimeCountdown >= 0.0) - { - // NOTE: we ensure main circuit readiness meets condition MainsInitTimeCountdown < 0 - // this allows for simpler rejection of cases where MainsInitTime == 0 - MainsInitTimeCountdown -= Deltatime; - } - else - { - // optional automatic circuit start - if (MainsStart != start_t::manual && false == (Mains || dizel_startup)) - { - MainSwitch(true); - } - } - } - else - { - // no power supply - MainsInitTimeCountdown = MainsInitTime; - } - - // an emergency brake application made under power opens the line breaker, where the vehicle has such an interlock - if (Mains && EmergencyBrakeHoldsMainOff()) - { - MainSwitch(false, TrainType == train_type::emu ? range_t::unit : range_t::local); - } -} - -void TMoverParameters::LowVoltagePowerCheck(double const /*Deltatime*/) -{ - - auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; - - if (EngineType == TEngineType::ElectricSeriesMotor) - { - GroundRelay &= lowvoltagepower; - if (GroundRelayStart != start_t::manual) - { - // NOTE: we're ignoring intricaties of battery and converter types as they're unlikely to be used - // TODO: generic check method which takes these into account - GroundRelay |= lowvoltagepower; - } - } -} - -void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling const Coupling) -{ - if (Coupling != coupling::highvoltage && Coupling != coupling::power110v && Coupling != coupling::power24v) - { - // only power couplings carry voltage - return; - } - - auto const localvoltage{LocalPowerVoltage(Coupling)}; - - auto const abslocalvoltage{std::abs(localvoltage)}; - auto const localpowersource{(abslocalvoltage > 1.0)}; - - // przekazywanie napiec - PowerCouplersVoltage(Coupling, abslocalvoltage, localpowersource); - - // przekazywanie pradow - PowerCouplersCurrent(Coupling, localpowersource); -} - -// the current the vehicle draws from the circuit of the power coupling given -double *TMoverParameters::PowerCircuitCurrent(coupling const Coupling) -{ - switch (Coupling) - { - case coupling::highvoltage: - return &TotalCurrent; - case coupling::power110v: - return &PowerCircuits[1].second; - case coupling::power24v: - return &PowerCircuits[0].second; - default: - return nullptr; - } -} - -// the voltage of the vehicle's own source for the coupling given; notes the low voltage circuits' too -double TMoverParameters::LocalPowerVoltage(coupling const Coupling) -{ - auto localvoltage{0.0}; - - // local power sources - // the results could be kept in the PowerCircuit fields - switch (Coupling) - { - - case coupling::highvoltage: - { - // heating power sources - if (Heating) - { - switch (HeatingPowerSource.SourceType) - { - case TPowerSource::Generator: - { - localvoltage = HeatingPowerSource.EngineGenerator.voltage - TotalCurrent * 0.02; - break; - } - case TPowerSource::CurrentCollector: - { - localvoltage = PantographVoltage; - break; - } - case TPowerSource::Main: - { - // HACK: main circuit can be fed through couplers, so we explicitly check pantograph supply here - // (or the genset's, where the traction selector of a dual-mode vehicle is on it) - localvoltage = MainCircuitPowered() ? TractionSourceVoltage() : 0.0; - break; - } - default: - { - break; - } - } - } - // high voltage power sources: the pantographs, or the genset of a dual-mode vehicle, by its traction selector - if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector) - { - localvoltage = std::max(localvoltage, TractionSourceVoltage()); - } - break; - } - - case coupling::power110v: - { - if (ConverterFlag) - { - localvoltage = NominalBatteryVoltage; - } - // TBD, TODO: reduce by current draw? - PowerCircuits[1].first = localvoltage; - break; - } - - case coupling::power24v: - { - if (Battery) - { - localvoltage = BatteryVoltage; - } - // TBD, TODO: reduce by current draw? - PowerCircuits[0].first = localvoltage; - break; - } - - default: - { - break; - } - } - - return localvoltage; -} - -// the voltage passed through the vehicle to the coupler at its other end, from the coupled vehicle or its own source -void TMoverParameters::PowerCouplersVoltage(coupling const Coupling, double const abslocalvoltage, bool const localpowersource) -{ - if (Couplers[end::front].power(Coupling) == nullptr) - { - // not a power coupling, there's no voltage to pass - return; - } - for (auto side = 0; side < 2; ++side) - { - - auto const &thiscoupler{Couplers[side]}; - // NOTE: in the loop we actually update the state of the coupler on the opposite end of the vehicle - auto &oppositecoupler{Couplers[side == end::front ? end::rear : end::front]}; - - bool oppositecouplingispresent; - bool localpowerexportisenabled; - - switch (Coupling) - { - - case coupling::highvoltage: - { - auto const oppositehighvoltagecoupling{(oppositecoupler.CouplingFlag & coupling::highvoltage) != 0}; - auto const oppositeheatingcoupling{(oppositecoupler.CouplingFlag & coupling::heating) != 0}; - - oppositecouplingispresent = oppositehighvoltagecoupling || oppositeheatingcoupling; - localpowerexportisenabled = oppositehighvoltagecoupling || (oppositeheatingcoupling && localpowersource && Heating); - break; - } - - case coupling::power110v: - { - oppositecouplingispresent = TestFlag(oppositecoupler.CouplingFlag, oppositecoupler.PowerCoupling) && (oppositecoupler.PowerFlag & coupling::power110v) != 0; - localpowerexportisenabled = oppositecouplingispresent; - break; - } - - case coupling::power24v: - { - oppositecouplingispresent = TestFlag(oppositecoupler.CouplingFlag, oppositecoupler.PowerCoupling) && (oppositecoupler.PowerFlag & coupling::power24v) != 0; - localpowerexportisenabled = oppositecouplingispresent; - break; - } - - default: - { - break; - } - } - - auto const *coupling = thiscoupler.power(Coupling); - auto *oppositecoupling = oppositecoupler.power(Coupling); - - // start with base voltage - oppositecoupling->voltage = abslocalvoltage; - oppositecoupling->is_live = false; - oppositecoupling->is_local = localpowersource; // indicate power source - // draw from external source - if (thiscoupler.Connected != nullptr) - { - auto const &connectedcoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr]}; - auto const *connectedcoupling = connectedcoupler.power(Coupling); - auto const connectedvoltage{(connectedcoupling->is_live ? connectedcoupling->voltage : 0.0)}; - oppositecoupling->voltage = std::max(oppositecoupling->voltage, connectedvoltage - coupling->current * 0.02); - oppositecoupling->is_live = connectedvoltage > 0.1 && oppositecouplingispresent; - } - // draw from local source - if (localpowersource) - { - oppositecoupling->voltage = std::max(oppositecoupling->voltage, abslocalvoltage - coupling->current * 0.02); - oppositecoupling->is_live |= abslocalvoltage > 0.1 && localpowerexportisenabled; - } - } -} - -// the current drawn through the couplers, shared by their voltages, or added to the vehicle's own -void TMoverParameters::PowerCouplersCurrent(coupling const Coupling, bool const localpowersource) -{ - auto const *frontcoupling{Couplers[end::front].power(Coupling)}; - auto const *rearcoupling{Couplers[end::rear].power(Coupling)}; - auto *totalcurrent{PowerCircuitCurrent(Coupling)}; - if (frontcoupling == nullptr || rearcoupling == nullptr || totalcurrent == nullptr) - { - // not a power coupling, there's no current to share - return; - } - auto const couplervoltage{static_cast(frontcoupling->voltage + rearcoupling->voltage)}; - - for (auto &thiscoupler : Couplers) - { - auto *coupling = thiscoupler.power(Coupling); - - coupling->current = 0.0; - - if (thiscoupler.Connected == nullptr) - { - continue; - } - - auto const &connectedothercoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr == end::front ? end::rear : end::front]}; - auto const *connectedothercoupling = connectedothercoupler.power(Coupling); - auto const extracurrent = Coupling == coupling::highvoltage ? std::abs(Itot) * IsVehicleEIMBrakingFactor() : 0.0; - - if (false == localpowersource) - { - // bez napiecia... - if (couplervoltage != 0.0) - { - // ...ale jest cos na sprzegach: - coupling->current = (*totalcurrent + extracurrent) * coupling->voltage / couplervoltage; // obciążenie rozkladane stosownie do napiec - if (true == coupling->is_live) - { - coupling->current += connectedothercoupling->current; - } - } - } - else - { - if (true == coupling->is_live) - { - *totalcurrent += connectedothercoupling->current; - } - } - } -} - -double TMoverParameters::ShowEngineRotation(int VehN) const -{ // Zwraca wartość prędkości obrotowej silnika wybranego pojazdu. Do 3 pojazdów (3×SN61). - int b; - switch (VehN) - { // numer obrotomierza - case 1: - return std::abs(enrot); - case 2: - for (b = 0; b <= 1; ++b) - if (TestFlag(Couplers[b].CouplingFlag, coupling::control) && Couplers[b].Connected->Power > 0.01) - return fabs(Couplers[b].Connected->enrot); - break; - case 3: // to nie uwzględnia ewentualnego odwrócenia pojazdu w środku - for (b = 0; b <= 1; ++b) - if (TestFlag(Couplers[b].CouplingFlag, coupling::control) && Couplers[b].Connected->Power > 0.01 && TestFlag(Couplers[b].Connected->Couplers[b].CouplingFlag, coupling::control) && Couplers[b].Connected->Couplers[b].Connected->Power > 0.01) - return fabs(Couplers[b].Connected->Couplers[b].Connected->enrot); - break; - default: - break; - } - return 0.0; -}; - -// sprawdzanie przetwornicy -void TMoverParameters::ConverterCheck(double const Timestep) -{ - // TODO: move other converter checks here, to have it all in one place for potential device object - if (ConverterStart != start_t::disabled && ConverterOverloadRelayOffWhenMainIsOff) - { - ConvOvldFlag |= !Mains && Power24vIsAvailable; - } - - switch (ConverterStart) - { - case start_t::disabled: - { - ConverterAllow = false; - // NOTE: if there's no converter in vehicle we can end the check here - return; - } - case start_t::automatic: - { - ConverterAllow = Mains; - break; - } - case start_t::direction: - { - ConverterAllow = DirActive != 0; - } - default: - { - break; - } - } - - if (ConverterAllow && ConverterAllowLocal && false == ConvOvldFlag && - false == PantPressLockActive - // HACK: allow carriages to operate converter without (missing) fuse prerequisite - && (Power > 1.0 ? MainCircuitPowered() : GetTrainsetHighVoltage() > 0.0)) - { - // delay timer can be optionally configured, and is set anew whenever converter goes off - if (ConverterStartDelayTimer <= 0.0) - { - ConverterFlag = true; - } - else - { - ConverterStartDelayTimer -= Timestep; - } - } - else - { - ConverterFlag = false; - ConverterStartDelayTimer = static_cast(ConverterStartDelay); - } - - if (ConverterOverloadRelayStart == start_t::converter && false == (ConverterAllow && ConverterAllowLocal) && false == TestFlag(EngDmgFlag, 4)) - { - // reset converter overload relay if the converter was switched off, unless it's damaged - ConvOvldFlag = false; - } -}; - -// heating system status check -void TMoverParameters::HeatingCheck(double const /*Timestep*/) -{ - - // update heating devices - // TBD, TODO: move this to a separate method? - if (HeatingPowerSource.SourceType == TPowerSource::Generator) - { - if (HeatingPowerSource.EngineGenerator.engine_revolutions != nullptr && HeatingPowerSource.EngineGenerator.revolutions_max > 0) - { - - auto &generator{HeatingPowerSource.EngineGenerator}; - // TBD, TODO: engine-generator transmission - generator.revolutions = *generator.engine_revolutions; - - auto const absrevolutions{std::abs(generator.revolutions)}; - generator.voltage = (false == HeatingAllow ? 0.0 : - // TODO: add support for desired voltage selector - absrevolutions < generator.revolutions_min ? - generator.voltage_min * absrevolutions / generator.revolutions_min : - // absrevolutions > generator.revolutions_max ? generator.voltage_max * absrevolutions / generator.revolutions_max : - std::lerp(generator.voltage_min, generator.voltage_max, - std::clamp((absrevolutions - generator.revolutions_min) / (generator.revolutions_max - generator.revolutions_min), 0.0, 1.0))) * - sign(generator.revolutions); - } - } - - // quick check first to avoid unnecessary calls... - if (false == HeatingAllow) - { - Heating = false; - return; - } - // ...detailed check if we're still here - auto const heatingpowerthreshold{0.1}; - // start with blank slate - auto voltage{0.0}; - // then try specified power source - switch (HeatingPowerSource.SourceType) - { - case TPowerSource::Generator: - { - voltage = HeatingPowerSource.EngineGenerator.voltage; - break; - } - case TPowerSource::CurrentCollector: - { - voltage = PantographVoltage; - break; - } - case TPowerSource::PowerCable: - { - if (HeatingPowerSource.PowerType == TPowerType::ElectricPower) - { - // TBD, TODO: limit input voltage to heating coupling type? - voltage = GetTrainsetHighVoltage(); - } - break; - } - case TPowerSource::Main: - { - voltage = MainCircuitPowered() ? TractionSupplyVoltage() : 0.0; - break; - } - default: - { - break; - } - } - - Heating = voltage > heatingpowerthreshold; - - if (Heating) - { - TotalCurrent += 1000 * HeatingPower / voltage; // heater power cost presumably specified in kilowatts - } -} - -// water pump status check -void TMoverParameters::WaterPumpCheck(double const /*Timestep*/) -{ - // NOTE: breaker override with start type is sm42 specific hack, replace with ability to define the presence of the breaker - WaterPump.is_active = true == (Power24vIsAvailable || Power110vIsAvailable) && true == WaterPump.breaker && false == WaterPump.is_disabled && - (true == WaterPump.is_active || true == WaterPump.is_enabled || WaterPump.start_type == start_t::battery); -} - -// water heater status check -void TMoverParameters::WaterHeaterCheck(double const /*Timestep*/) -{ - - WaterHeater.is_active = false == WaterHeater.is_damaged && true == (Power24vIsAvailable || Power110vIsAvailable) && true == WaterHeater.is_enabled && true == WaterHeater.breaker && - (WaterHeater.is_active || WaterHeater.config.temp_min < 0 || dizel_heat.temperatura1 < WaterHeater.config.temp_min); - - WaterHeater.is_damaged = true == WaterHeater.is_damaged || (true == WaterHeater.is_active && false == WaterPump.is_active); - - if (WaterHeater.config.temp_max > 0 && dizel_heat.temperatura1 > WaterHeater.config.temp_max) - { - WaterHeater.is_active = false; - } -} - -// fuel pump status update -void TMoverParameters::FuelPumpCheck(double const /*Timestep*/) -{ - using enum start_t; - - FuelPump.is_active = true == (Power24vIsAvailable || Power110vIsAvailable) && false == FuelPump.is_disabled && - (FuelPump.is_active || (FuelPump.start_type == manual ? FuelPump.is_enabled : - FuelPump.start_type == automatic ? dizel_startup || Mains : - FuelPump.start_type == manualwithautofallback ? FuelPump.is_enabled || dizel_startup || Mains : - false)); // shouldn't ever get this far but, eh -} - -// oil pump status update -void TMoverParameters::OilPumpCheck(double const Timestep) -{ - - OilPump.is_active = true == (Power24vIsAvailable || Power110vIsAvailable) && false == Mains && false == OilPump.is_disabled && - (OilPump.is_active || (OilPump.start_type == start_t::manual ? OilPump.is_enabled : - OilPump.start_type == start_t::automatic ? dizel_startup : - OilPump.start_type == start_t::manualwithautofallback ? OilPump.is_enabled || dizel_startup : - false)); // shouldn't ever get this far but, eh - - auto const minpressure{OilPump.pressure_minimum > 0.f ? OilPump.pressure_minimum : 0.15f}; // arbitrary fallback value - - OilPump.pressure_target = enrot > 0.1 ? std::lerp( minpressure, OilPump.pressure_maximum, static_cast( EngineRPMRatio() ) ) * OilPump.resource_amount : - true == OilPump.is_active ? std::min( minpressure + 0.1f, OilPump.pressure_maximum ) : // slight pressure margin to give time to switch off the pump and start the engine - 0.f; - - if (OilPump.pressure < OilPump.pressure_target) - { - // TODO: scale change rate from 0.01-0.05 with oil/engine temperature/idle time - OilPump.pressure = std::min(OilPump.pressure_target, static_cast(OilPump.pressure + (enrot > 5.0 ? 0.05 : 0.035) * Timestep)); - } - if (OilPump.pressure > OilPump.pressure_target) - { - OilPump.pressure = std::max(OilPump.pressure_target, static_cast(OilPump.pressure - (enrot > 5.0 ? 0.05 : 0.035) * 0.5 * Timestep)); - } - OilPump.pressure = std::clamp(OilPump.pressure, 0.f, 1.5f); -} - -void TMoverParameters::MotorBlowersCheck(double const Timestep) -{ - // activation check - for (auto &blower : MotorBlowers) - { - auto disable = blower.is_disabled; - auto const start{(Vel >= blower.min_start_velocity && std::abs(Im) > 0.5)}; - auto const stop{(Vel < 0.5 && std::abs(Im) < 0.5)}; - if (blower.min_start_velocity >= 0) - { - if (stop) - { - blower.stop_timer += static_cast(Timestep); - if (blower.stop_timer > blower.sustain_time) - { - disable = true; - } - } - else if (start) - { - blower.stop_timer = 0; - } - else - { - disable |= !blower.is_active; - } - } - blower.is_active = - // TODO: bind properly power source when ld is in place - MotorBlowerPowerIsAvailable(blower) // power source - // breaker condition disabled until it's implemented in the class data - // && ( true == blower.breaker ) - && false == disable && - (true == blower.is_active || (blower.stop_timer == 0.f // HACK: will be true for blower with exceeded start_velocity, and for one without start_velocity - && (blower.start_type == start_t::manual ? blower.is_enabled : true))); - } - // update - for (auto &fan : MotorBlowers) - { - - auto const revolutionstarget{(fan.is_active ? (fan.speed > 0.f ? fan.speed * static_cast(enrot) * 60 : fan.speed * -1) : 0.f)}; - - if (std::abs(fan.revolutions - revolutionstarget) < 0.01f) - { - fan.revolutions = revolutionstarget; - continue; - } - if (revolutionstarget > 0.f) - { - auto const speedincreasecap{std::max(50.f, fan.speed * 0.05f * -1)}; // 5% of fixed revolution speed, or 50 - fan.revolutions += static_cast(std::clamp(revolutionstarget - fan.revolutions, speedincreasecap * -2, speedincreasecap) * Timestep); - } - else - { - fan.revolutions *= static_cast(std::max(0.0, 1.0 - Timestep)); - } - } -} - -bool TMoverParameters::MotorBlowerPowerIsAvailable(cooling_fan const &Blower) const -{ - switch (Blower.start_type) - { - case start_t::battery: - return Power24vIsAvailable; - case start_t::converter: - return Power110vIsAvailable; - default: - return MainCircuitPowered(); - } -} - -void TMoverParameters::PantographsCheck(double const /*Timestep*/) -{ - using enum start_t; - - { - auto const &valve{PantsValve}; - auto const lowvoltagepower{valve.solenoid ? Power24vIsAvailable || Power110vIsAvailable : true}; - auto const autostart{valve.start_type == automatic || valve.start_type == manualwithautofallback}; - auto const manualcontrol{valve.start_type == manual || valve.start_type == manualwithautofallback}; - - PantsValve.is_active = (valve.spring ? lowvoltagepower : true) // spring actuator needs power to maintain non-default state - && (manualcontrol && lowvoltagepower ? false == valve.is_disabled : true) // needs power to change state - && (valve.is_active || (autostart ? lowvoltagepower : - !autostart ? lowvoltagepower && valve.is_enabled : - false)); // shouldn't ever get this far but, eh - } - - size_t pant_id = 0; - for (auto &pantograph : Pantographs) - { - - auto &valve{pantograph.valve}; - auto const lowvoltagepower{valve.solenoid ? Power24vIsAvailable || Power110vIsAvailable : true}; - auto const autostart{valve.start_type == automatic || valve.start_type == manualwithautofallback}; - auto const manualcontrol{valve.start_type == manual || valve.start_type == manualwithautofallback}; - - valve.is_active = (valve.spring ? lowvoltagepower : true) // spring actuator needs power to maintain non-default state - && (manualcontrol && lowvoltagepower ? false == valve.is_disabled : true) // needs power to change state, without it just pass through - && (manualcontrol && lowvoltagepower ? false == PantAllDown : true) && - (Mains || false == PantographsRequireMains) // fed through the closed line breaker, where it comes first - && (valve.is_active || (manualcontrol && lowvoltagepower && valve.is_enabled) || (autostart && lowvoltagepower)); // shouldn't ever get this far but, eh - - auto const pantographexists{EnginePowerSource.SourceType == TPowerSource::CurrentCollector && EnginePowerSource.CollectorParameters.PhysicalLayout & 1 << pant_id}; - - pantograph.is_active = valve.is_active && PantsValve.is_active && pantographexists; - - pant_id++; - } -} - -// the genset of a dual-mode vehicle: started on request with the battery on, it cranks for start_time, then runs at -// idle and up to full revolutions with the traction demand; stopped, it coasts down. regulated voltage from idle up -void TMoverParameters::GensetCheck(double const Deltatime) -{ - if (false == Genset.fitted()) - { - return; - } - auto &genset{Genset}; - auto const wasactive{genset.is_active}; - auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; - auto const requested{lowvoltagepower && false == genset.is_disabled && (genset.start_type == start_t::automatic ? GensetSelected() : genset.is_enabled)}; - if (false == requested) - { - genset.is_active = false; - genset.is_cranking = false; - genset.timer = 0.0; - } - else if (false == genset.is_active) - { - genset.is_cranking = true; - genset.timer += Deltatime; - if (genset.timer >= genset.start_time) - { - genset.is_cranking = false; - genset.is_active = true; - } - } - // revolutions: the start brings them up to idle in start_time; running they follow the traction demand, stopped - // they coast down to 0, both with the time constant spinup_time - if (genset.is_cranking) - { - genset.revolutions = std::max(genset.revolutions, genset.revolutions_idle * std::min(1.0, genset.timer / std::max(genset.start_time, 0.01))); - } - else if (genset.is_active && false == wasactive) - { - genset.revolutions = std::max(genset.revolutions, genset.revolutions_idle); - } - else - { - auto const demand{GensetSelected() && Mains ? std::clamp(eimv_pr, 0.0, 1.0) : 0.0}; - auto const target{genset.is_active ? genset.revolutions_idle + (genset.revolutions_max - genset.revolutions_idle) * demand : 0.0}; - genset.revolutions += (target - genset.revolutions) * std::min(1.0, Deltatime / genset.spinup_time); - if (genset.revolutions < 0.001) - { - genset.revolutions = 0.0; - } - } - // no excitation while cranking; running or coasting down, regulated from idle up, proportional below it - genset.voltage = genset.is_cranking ? 0.0 : genset.voltage_nominal * std::clamp(genset.revolutions / genset.revolutions_idle, 0.0, 1.0); - - if (genset.is_active != wasactive) - { - WriteLog("Genset of " + Name + (genset.is_active ? ": running" : ": stopped")); - } -} - -void TMoverParameters::LightsCheck(double const /*Timestep*/) -{ - - auto &light{CompartmentLights}; - - light.is_active = - // TODO: bind properly power source when ld is in place - (Power24vIsAvailable || Power110vIsAvailable) // power source - && false == light.is_disabled && (true == light.is_active || (light.start_type == start_t::manual ? light.is_enabled : true)); - - light.intensity = (light.is_active ? 1.0f : 0.0f) - // TODO: bind properly power source when ld is in place - * (Power110vIsAvailable ? 1.0f : - Power24vIsAvailable ? 0.5f : - 0.0f) * - light.dimming; -} - -double TMoverParameters::ShowCurrent(int AmpN) const -{ // Odczyt poboru prądu na podanym amperomierzu - switch (EngineType) - { - case TEngineType::ElectricInductionMotor: - switch (AmpN) - { // do asynchronicznych - case 1: - return WindingRes * Mm / Vadd; - case 2: - return eimv_pr * WindingRes; - default: - return ShowCurrentP(AmpN); // T_MoverParameters:: - } - break; - case TEngineType::DieselElectric: - return fabs(Im); - break; - default: - return ShowCurrentP(AmpN); // T_MoverParameters:: - } -}; - -// ************************************************************************************************* -// queuedEU -// ************************************************************************************************* - -// ************************************************************************************************* -// Q: 20160710 -// zwiększenie nastawinika -// ************************************************************************************************* - -bool TMoverParameters::IncMainCtrl(int CtrlSpeed) -{ - // basic fail conditions: - if (MainCtrlPosNo <= 0 || CabActive == 0) - { - // nie ma sterowania - return false; - } - if (TrainType == train_type::et22 && ScndCtrlPos != 0) - { - // w ET22 nie da się kręcić nastawnikiem przy włączonym boczniku - return false; - } - if (TrainType == train_type::emu && DirActive == 0) - { - // w EZT nie da się załączyć pozycji bez ustawienia kierunku - return false; - } - - bool OK = false; - if (MainCtrlPos < MainCtrlPosNo) - { - OK = IncMainCtrlByEngine(CtrlSpeed); - } - else - { // MainCtrlPos>=MainCtrlPosNo - if (true == CoupledCtrl) - { - // wspólny wał nastawnika jazdy i bocznikowania - if (ScndCtrlPos < ScndCtrlPosNo) - { // 3<3 -> false - ++ScndCtrlPos; - OK = true; - } - else - { - OK = false; - } - } - } - - if (true == OK) - { - ScndCtrlResistiveLockCheck(); // e.g. from the last series position on to the resistive parallel ones - SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); //??? - SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); - } - - // hunter-101012: poprawka - // poprzedni warunek byl niezbyt dobry, bo przez to przy trzymaniu + - // styczniki tkwily na tej samej pozycji (LastRelayTime byl caly czas 0 i rosl - // po puszczeniu plusa) - - if (OK) - { - if (DelayCtrlFlag) - { - if (LastRelayTime >= InitialCtrlDelay && MainCtrlPos == 1) - LastRelayTime = 0; - } - else if (LastRelayTime > CtrlDelay) - LastRelayTime = 0; - } - return OK; -} - -// a notch up, as the kind of the engine takes it; returns whether the controller moved -bool TMoverParameters::IncMainCtrlByEngine(int const CtrlSpeed) -{ - bool OK = false; - switch (EngineType) - { - case TEngineType::None: - case TEngineType::Dumb: - case TEngineType::DieselElectric: - case TEngineType::ElectricInductionMotor: - { - if (CtrlSpeed > 1) - { - OK = IncMainCtrl(1) && IncMainCtrl(CtrlSpeed - 1); // a fail will propagate up the recursion chain. should this be || instead? - break; - } - ++MainCtrlPos; - OK = true; - if (EIMCtrlType == 0 && ( SpeedCtrlAutoTurnOffFlag & 1 ) == 1 && MainCtrlActualPos != MainCtrlPos) - { - SpeedCtrlSwitch(false); - SpeedCtrlUnit.IsActive = false; - } - break; - } - - case TEngineType::ElectricSeriesMotor: - { - OK = IncMainCtrlSeriesMotor(CtrlSpeed); - break; - } - - case TEngineType::DieselEngine: - { - if (CtrlSpeed > 1) - { - while (MainCtrlPos < MainCtrlPosNo && IncMainCtrl(1)) - { - // all work is done in the loop header - } - } - else - { - ++MainCtrlPos; - } - CompressorAllow = MainCtrlPowerPos() > 0; - OK = true; - break; - } - - case TEngineType::WheelsDriven: - { - OK = AddPulseForce(CtrlSpeed); - break; - } - default: - break; - } // switch EngineType of - return OK; -} - -// a notch up of the series motors' controller: CtrlSpeed over 1 runs it to the first position without resistors; -// returns whether it moved as asked -bool TMoverParameters::IncMainCtrlSeriesMotor(int const CtrlSpeed) -{ - bool OK = false; - if (DirActive == 0) - { - return false; - } - - if (CtrlSpeed > 1) - { - // szybkie przejœcie na bezoporow¹ - if (TrainType == train_type::et40) - { - return false; // this means ET40 won't react at all to fast acceleration command. should it issue just IncMainCtrl(1) instead? - } - while (RList[MainCtrlPos].R > 0.0 && IncMainCtrl(1)) - { - // all work is done in the loop header - } - OK = false; // shouldn't this be part of the loop above? - // if (TrainType=train_type::et40) then - // while Abs (Im)>IminHi do - // dec(MainCtrlPos); - // OK:=false ; - } - else - { // CtrlSpeed == 1 - ++MainCtrlPos; - OK = true; - if (Imax == ImaxHi && RList[MainCtrlPos].Bn > 1) - { - /* NOTE: disabled, relay configuration was moved to compute_movement_ - if( true == MaxCurrentSwitch( false )) { - // wylaczanie wysokiego rozruchu - SetFlag( SoundFlag, sound::relay ); - } - */ - if (TrainType == train_type::et42) - { - --MainCtrlPos; - OK = false; - } - } - // - // if (TrainType == "et40") - // if (Abs(Im) > IminHi) - // { - // MainCtrlPos--; //Blokada nastawnika po przekroczeniu minimalnego pradu - // OK = false; - // } - //} - } - - if (TrainType == train_type::et42 && true == DynamicBrakeFlag && MainCtrlPos > 20) - { - MainCtrlPos = 20; - OK = false; - } - return OK; -} - -// ***************************************************************************** -// Q: 20160710 -// zmniejszenie nastawnika -// ***************************************************************************** -bool TMoverParameters::DecMainCtrl(int CtrlSpeed) -{ - bool OK = false; - // basic fail conditions: - if (MainCtrlPosNo <= 0 || CabActive == 0) - { - // nie ma sterowania - OK = false; - } - else if (CtrlSpeed == 0) - { - return false; - } - else - { - // TBD, TODO: replace with mainctrlpowerpos() check? - if (MainCtrlPos > 0) - { - if (TrainType != train_type::et22 || ScndCtrlPos == 0) // Ra: ET22 blokuje nastawnik przy boczniku - { - if (CoupledCtrl && ScndCtrlPos > 0) - { - ScndCtrlPos--; // wspolny wal - OK = true; - } - else - OK = DecMainCtrlByEngine(CtrlSpeed); - } - } - else if (EngineType == TEngineType::WheelsDriven) - OK = AddPulseForce(-CtrlSpeed); - else - OK = false; - - if (OK) - { - ScndCtrlResistiveLockCheck(); // the shunt drops when the master controller leaves a resistance-free position - /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); // hmmmm...???!!! - /*OK:=*/SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); - } - } - // if OK then LastRelayTime:=0; - // hunter-101012: poprawka - if (OK) - { - if (DelayCtrlFlag) - { - if (LastRelayTime >= InitialCtrlDelay) - LastRelayTime = 0; - } - else if (LastRelayTime > CtrlDownDelay) - LastRelayTime = 0; - } - return OK; -} - -// a notch down, as the kind of the engine takes it; returns whether the controller moved -bool TMoverParameters::DecMainCtrlByEngine(int const CtrlSpeed) -{ - bool OK = false; - switch (EngineType) - { - case TEngineType::None: - case TEngineType::Dumb: - case TEngineType::DieselElectric: - case TEngineType::ElectricInductionMotor: - { - if (CtrlSpeed == 1) - { - MainCtrlPos--; - OK = true; - if (EIMCtrlType == 0 && (SpeedCtrlAutoTurnOffFlag & 1) == 1 && MainCtrlActualPos != MainCtrlPos) - { - SpeedCtrlSwitch(false); - SpeedCtrlUnit.IsActive = false; - } - } - else if (CtrlSpeed > 1) - OK = DecMainCtrl(1) && DecMainCtrl(CtrlSpeed - 1); // CtrlSpeed-1); - break; - } - - case TEngineType::ElectricSeriesMotor: - { - OK = DecMainCtrlSeriesMotor(CtrlSpeed); - break; - } - - case TEngineType::DieselEngine: - { - if (CtrlSpeed == 1) - { - MainCtrlPos--; - OK = true; - } - else if (CtrlSpeed > 1) - { - while (MainCtrlPos > 0 || RList[MainCtrlPos].Mn > 0) - DecMainCtrl(1); - OK = true; - } - break; - } - default: - break; - } // switch EngineType - return OK; -} - -// a notch down of the series motors' controller: CtrlSpeed over 1 runs it down to the first position without resistors -bool TMoverParameters::DecMainCtrlSeriesMotor(int const CtrlSpeed) -{ - bool OK = false; - if (CtrlSpeed == 1) /*and (ScndCtrlPos=0)*/ - { - MainCtrlPos--; - // if (MainCtrlPos=0) and (ScndCtrlPos=0) and - // (TrainType<>train_type::et40)and(TrainType<>train_type::ep05) then - // StLinFlag:=false; - // if (MainCtrlPos=0) and (TrainType<>train_type::et40) and - // (TrainType<>train_type::ep05) then - // MainCtrlActualPos:=0; //yBARC: co to tutaj robi? ;) - OK = true; - } - else if (CtrlSpeed > 1) /*and (ScndCtrlPos=0)*/ - { - OK = true; - if (RList[MainCtrlPos].R == 0) // Q: tu zrobilem = ;] - DecMainCtrl(1); - while (RList[MainCtrlPos].R > 0 && DecMainCtrl(1)) - ; // takie chamskie, potem poprawie} - } - return OK; -} - -bool TMoverParameters::IsMainCtrlActualNoPowerPos() const -{ - // TODO: wrap controller pieces into a class for potential specializations, similar to brake subsystems - return MainCtrlActualPos <= MainCtrlNoPowerPos(); -} - -bool TMoverParameters::IsMainCtrlNoPowerPos() const -{ - // TODO: wrap controller pieces into a class for potential specializations, similar to brake subsystems - return MainCtrlPos <= MainCtrlNoPowerPos(); -} - -bool TMoverParameters::IsMainCtrlMaxPowerPos() const -{ - // TODO: wrap controller pieces into a class for potential specializations, similar to brake subsystems - return MainCtrlPos == MainCtrlPosNo; -} - -int TMoverParameters::MainCtrlNoPowerPos() const -{ - - switch (EIMCtrlType) - { - case 1: - { - return 3; - } - case 2: - { - return 3 + EIMCtrlEmergencyPositions(); - } - case 3: - { - return UniCtrlNoPowerPos; - } - default: - { - return 0; - } - } -} - -int TMoverParameters::MainCtrlActualPowerPos() const -{ - - return MainCtrlActualPos - MainCtrlNoPowerPos(); -} - -int TMoverParameters::MainCtrlPowerPos() const -{ - - return MainCtrlPos - MainCtrlNoPowerPos(); -} - -int TMoverParameters::EIMCtrlEmergencyPositions() const -{ - return (EIMCtrlType == 2 && EIMCtrlMainEmergency) ? 1 : 0; -} - -bool TMoverParameters::IsMainCtrlEmergencyPos() const -{ - return MainCtrlPos < EIMCtrlEmergencyPositions(); -} - -int TMoverParameters::MainCtrlPosForCoupled() const -{ - // the emergency brake itself reaches the train through the brake pipe, vented by the vehicle driven from - return std::max(0, MainCtrlPos - EIMCtrlEmergencyPositions()); -} - -int TMoverParameters::MainCtrlPosFromCoupled(int const Position) const -{ - return Position + EIMCtrlEmergencyPositions(); -} - -// ************************************************************************************************* -// Q: 20160710 -// zwiększenie bocznika -// ************************************************************************************************* -bool TMoverParameters::IncScndCtrl(int CtrlSpeed) -{ - bool OK = false; - - if (DynamicBrakeFlag && TrainType == train_type::et42 && CabActive != 0 && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0) - { - OK = DynamicBrakeSwitch(false); - } - else if (ScndCtrlPosNo > 0 && CabActive != 0 && !(TrainType == train_type::et42 && (Imax == ImaxHi || (DynamicBrakeFlag && MainCtrlPowerPos() > 0)))) - { - // if (RList[MainCtrlPos].R=0) and (MainCtrlPos>0) and (ScndCtrlPos 1) - { - ScndCtrlPos = ScndCtrlPosNo; // takie chamskie, potem poprawie - } - OK = true; - } - } - else // nie mozna zmienic - OK = false; - if (OK) - { - /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); //??? - /*OK:=*/SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); - } - } - else // nie ma sterowania - OK = false; - // if OK then LastRelayTime:=0; - // hunter-101012: poprawka - if (OK && LastRelayTime > CtrlDelay) - LastRelayTime = 0; - - if (OK && EngineType == TEngineType::ElectricInductionMotor && ScndCtrlPosNo == 1 && MainCtrlPos > 0) - { - SpeedCtrlValue = Vel; - if (EIMCtrlType == 0 && (SpeedCtrlAutoTurnOffFlag & 1) == 1) - { - MainCtrlActualPos = MainCtrlPos; - } - SpeedCtrlUnit.IsActive = true; - } - - if (OK && SpeedCtrl && ScndCtrlPos == 1 && EngineType == TEngineType::DieselEngine) - { - // NOTE: round() already adds 0.5, are the ones added here as well correct? - SpeedCtrlValue = static_cast(Round(Vel)); - SpeedCtrlUnit.IsActive = true; - } - - return OK; -} - -// ************************************************************************************************* -// Q: 20160710 -// zmniejszenie bocznika -// ************************************************************************************************* -bool TMoverParameters::DecScndCtrl(int CtrlSpeed) -{ - bool OK = false; - - if (IsMainCtrlNoPowerPos() && CabActive != 0 && TrainType == train_type::et42 && ScndCtrlPos == 0 && !DynamicBrakeFlag && CtrlSpeed == 1) - { - // Ra: AI wywołuje z CtrlSpeed=2 albo gdy ScndCtrlPos>0 - OK = DynamicBrakeSwitch(true); - } - else if (ScndCtrlPosNo > 0 && CabActive != 0) - { - if (ScndCtrlPos > 0 && !CoupledCtrl && (EngineType != TEngineType::DieselElectric || !AutoRelayFlag) && !IsScndCtrlLockedByMainCtrl()) - { - if (CtrlSpeed == 1) - { - ScndCtrlPos--; - } - else if (CtrlSpeed > 1) - { - ScndCtrlPos = 0; // takie chamskie, potem poprawie - } - OK = true; - } - else - OK = false; - if (OK) - { - /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); //??? - /*OK:=*/SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); - } - } - else - OK = false; - // if OK then LastRelayTime:=0; - // hunter-101012: poprawka - if (OK && LastRelayTime > CtrlDownDelay) - LastRelayTime = 0; - - if (OK && EngineType == TEngineType::ElectricInductionMotor && ScndCtrlPosNo == 1) - { - SpeedCtrlValue = 0; - SpeedCtrlUnit.IsActive = false; - if (SpeedCtrlUnit.ManualStateOverride) - { - eimic = 0.0; - } - } - - if (OK && SpeedCtrl && ScndCtrlPos == 0 && EngineType == TEngineType::DieselEngine) - { - SpeedCtrlValue = 0; - SpeedCtrlUnit.IsActive = false; - if (SpeedCtrlUnit.ManualStateOverride) - { - eimic = 0.0; - } - } - - return OK; -} - -bool TMoverParameters::IsScndCtrlLockedByMainCtrl() const -{ - // ET21, ET22, EP09: the field shunting engages only on the resistance-free positions of the master controller (eu07/maszyna#402) - return ScndCtrlResistiveLock && (IsMainCtrlNoPowerPos() || RList[MainCtrlPos].R >= 0.01); -} - -void TMoverParameters::ScndCtrlResistiveLockCheck() -{ - // the shunt controller, locked in both directions on zero and the resistive positions, would otherwise stay engaged there once the - // master controller is taken back (or set from elsewhere, e.g. by the AI or another vehicle of the consist) with the shunt on - if (ScndCtrlPos > 0 && !CoupledCtrl && IsScndCtrlLockedByMainCtrl()) - { - ScndCtrlPos = 0; - } -} - -int TMoverParameters::GetVirtualScndPos() const -{ - if (TrainType == train_type::et42 && DynamicBrakeFlag && !ScndCtrlPos) - return -1; - return ScndCtrlPos; -} - -bool TMoverParameters::IsScndCtrlNoPowerPos() const -{ - // TODO: refine the check on account of potential electric series vehicles with speed control - return ScndCtrlPos == 0 || true == SpeedCtrl; -} - -bool TMoverParameters::IsScndCtrlMaxPowerPos() const -{ - // TODO: refine the check on account of potential electric series vehicles with speed control - return ScndCtrlPos == ScndCtrlPosNo || true == SpeedCtrl; -} - -// ************************************************************************************************* -// Q: 20160710 -// załączenie rozrządu -// ************************************************************************************************* -bool TMoverParameters::CabActivisation(bool const Enforce) -{ - bool OK = false; - - OK = Enforce || CabActive == 0; // numer kabiny, z której jest sterowanie - if (PulleeMode) - { - // nobody drives from a vehicle prepared for hauling - OK = false; - } - if (OK) - { - CabActive = CabOccupied; // sterowanie jest z kabiny z obsadą - DirAbsolute = DirActive * CabActive; - CabMaster = true; - SecuritySystem.set_enabled(true); // activate the alerter TODO: make it part of control based cab selection - SendCtrlToNext("CabActivisation", 1, CabActive); - SendCtrlToNext("Direction", DirActive, CabActive); - if (InactiveCabFlag & activation::springbrakeoff) - { - SpringBrakeActivate(false); - } - } - return OK; -} - -bool TMoverParameters::CabActivisationAuto(bool const Enforce) -{ - bool OK = AutomaticCabActivation ? CabActivisation(Enforce) : false; - return OK; -} - -// ************************************************************************************************* -// Q: 20160710 -// wyłączenie rozrządu -// ************************************************************************************************* -bool TMoverParameters::CabDeactivisation(bool const Enforce) -{ - bool OK = false; - - OK = Enforce || IsCabMaster(); // o ile obsada jest w kabinie ze sterowaniem - if (OK) - { - if (InactiveCabFlag & activation::springbrakeon) - { - SpringBrakeActivate(true); - } - if (InactiveCabFlag & activation::pantographsup) - { - InactiveCabPantsCheck = true; - } - if (InactiveCabFlag & activation::doorpermition) - { - PermitDoors(side::right, true, range_t::consist); - PermitDoors(side::left, true, range_t::consist); - } - if (InactiveCabFlag & activation::neutraldirection) - { - DirActive = 0; - SendCtrlToNext("Direction", 0, CabActive); - } - - CabActive = 0; - DirAbsolute = DirActive * CabActive; - CabMaster = false; - DepartureSignal = false; // nie buczeć z nieaktywnej kabiny - SecuritySystem.set_enabled(false); // deactivate alerter TODO: make it part of control based cab selection - - SendCtrlToNext("CabActivisation", 0, CabOccupied); // CabActive==0! - } - return OK; -} - -bool TMoverParameters::CabDeactivisationAuto(bool const Enforce) -{ - bool OK = AutomaticCabActivation ? CabDeactivisation(Enforce) : false; - return OK; -} - -// ************************************************************************************************* -// Q: 20160710 -// Siła napędzająca drezynę po naciśnięciu wajhy -// ************************************************************************************************* -bool TMoverParameters::AddPulseForce(int Multipler) -{ - bool APF; - if (EngineType == TEngineType::WheelsDriven && EnginePowerSource.SourceType == TPowerSource::InternalSource && EnginePowerSource.PowerType == TPowerType::BioPower) - { - DirActive = CabActive; - DirAbsolute = DirActive * CabActive; - if (Vel > 0) - PulseForce = std::min(1000.0 * Power / (abs(V) + 0.1), Ftmax); - else - PulseForce = Ftmax; - if (PulseForceCount > 1000.0) - PulseForce = 0; - else - PulseForce = PulseForce * Multipler; - PulseForceCount = PulseForceCount + abs(Multipler); - APF = PulseForce > 0; - } - else - APF = false; - return APF; -} - -// ************************************************************************************************* -// yB: 20190909 -// sypanie piasku reczne -// ************************************************************************************************* -bool TMoverParameters::SandboxManual(bool const State, range_t const Notify) -{ - bool result{false}; - - if (SandDoseManual != State) - { - if (SandDoseManual == false) - { - // switch on - if (Sand > 0) - { - SandDoseManual = true; - result = true; - } - } - else - { - // switch off - SandDoseManual = false; - result = true; - } - } - - Sandbox(SandDoseManual || SandDoseAuto, Notify); - - return result; -} - -// ************************************************************************************************* -// yB: 20190909 -// sypanie piasku automatyczne -// ************************************************************************************************* -bool TMoverParameters::SandboxAuto(bool const State, range_t const Notify) -{ - bool result{false}; - if (bool NewState = State && SandDoseAutoAllow; SandDoseAuto != NewState) - { - if (SandDoseAuto == false) - { - // switch on - if (Sand > 0) - { - SandDoseAuto = true; - result = true; - } - } - else - { - // switch off - SandDoseAuto = false; - result = true; - } - } - - Sandbox(SandDoseManual || SandDoseAuto, Notify); - - return result; -} - -// ************************************************************************************************* -// Q: 20160713 -// sypanie piasku -// ************************************************************************************************* -bool TMoverParameters::Sandbox(bool const State, range_t const Notify) -{ - bool result{false}; - - if (SandDose != State) - { - if (SandDose == false) - { - // switch on - if (Sand > 0 && DirActive != 0) - { - SandDose = true; - result = true; - } - } - else - { - // switch off - SandDose = false; - result = true; - } - } - - if (Notify != range_t::local) - { - // if requested pass the command on - auto const couplingtype = Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control; - - if (State == true) - { - // switch on - SendCtrlToNext("Sandbox", 1, CabActive, couplingtype); - } - else - { - // switch off - SendCtrlToNext("Sandbox", 0, CabActive, couplingtype); - } - } - - return result; -} - -// ************************************************************************************************* -// yB: 20190909 -// włączenie / wyłączenie automatycznej piasecznicy -// ************************************************************************************************* -bool TMoverParameters::SandboxAutoAllow(bool State) -{ - // SendCtrlToNext("SandboxAutoAllow", int(State), CabActive, ctrain_controll); - - if (SandDoseAutoAllow != State) - { - SandDoseAutoAllow = State; - return true; - } - else - return false; -} - -// ***************************************************************************** -// Q: 20160710 -// zbicie czuwaka / SHP -// ***************************************************************************** -// hunter-091012: rozbicie alarmow, dodanie testu czuwaka -void TMoverParameters::SecuritySystemReset(void) // zbijanie czuwaka/SHP -{ - // reset all, used by AI - SecuritySystem.acknowledge_press(); - SecuritySystem.acknowledge_release(); - SecuritySystem.cabsignal_reset(); -} - -// ************************************************************************************************* -// Q: 20160711 -// sprawdzanie stanu CA/SHP -// ************************************************************************************************* -void TMoverParameters::SecuritySystemCheck(double dt) -{ - bool isPower = Power24vIsAvailable || Power110vIsAvailable; - // the shunt mode of the SM42 switches its vigilance device (CA) off, on the vehicles with AwareOffInShuntMode=Yes (eu07/maszyna#457) - SecuritySystem.set_shunt_mode(ShuntMode); - SecuritySystem.update(dt, Vel, isPower, CabActive); - - if (!Battery || !Radio || !RadioFuse) - { // wyłączenie baterii deaktywuje sprzęt - RadiostopSwitch(false); - } -} - -// ************************************************************************************************* -// Q: 20160710 -// włączenie / wyłączenie baterii -// ************************************************************************************************* -bool TMoverParameters::BatterySwitch(bool State, range_t const Notify) -{ - using enum range_t; - if (PulleeMode && State) - { - // the battery of a vehicle prepared for hauling stays off - return false; - } - auto const initialstate{Battery}; - - // Ra: ukrotnienie załączania baterii jest jakąś fikcją... - if (BatteryStart == start_t::manual) - { - Battery = State; - } - - // switching batteries does not require activation - if (Notify != local) - { - SendCtrlToNext("BatterySwitch", State ? 1 : 0, 1, Notify == unit ? coupling::control | coupling::permanent : coupling::control); - SendCtrlToNext("BatterySwitch", State ? 1 : 0, -1, Notify == unit ? coupling::control | coupling::permanent : coupling::control); - } - - return Battery != initialstate; -} - -// ************************************************************************************************* -// Q: 20160710 -// włączenie / wyłączenie hamulca elektro-pneumatycznego -// ************************************************************************************************* -bool TMoverParameters::EpFuseSwitch(bool State) -{ - if (EpFuse != State) - { - EpFuse = State; - return true; - } - else - return false; - // if (EpFuse == true) SendCtrlToNext("EpFuseSwitch", 1, CabActive) - // else SendCtrlToNext("EpFuseSwitch", 0, CabActive); -} - -// ************************************************************************************************* -// yB: 20190906 -// włączenie / wyłączenie hamulca sprezynowego -// ************************************************************************************************* -bool TMoverParameters::SpringBrakeActivate(bool State) -{ - if (Power24vIsAvailable || Power110vIsAvailable) - { - SendCtrlToNext("SpringBrakeActivate", int(State), CabActive, SpringBrake.MultiTractionCoupler); - - if (SpringBrake.Activate != State) - { - SpringBrake.Activate = State; - wake_for_brake(); - return true; - } - } - return false; -} - -// ************************************************************************************************* -// yB: 20190906 -// włączenie / wyłączenie odciecia hamulca sprezynowego -// ************************************************************************************************* -bool TMoverParameters::SpringBrakeShutOff(bool State) -{ - if (SpringBrake.ShuttOff != State) - { - SpringBrake.ShuttOff = State; - return true; - } - else - return false; -} - -// ************************************************************************************************* -// yB: 20190906 -// wyluzowanie hamulca sprezynowego -// ************************************************************************************************* -bool TMoverParameters::SpringBrakeRelease() -{ - if (SpringBrake.IsReady && SpringBrake.Cylinder->P() < SpringBrake.MinForcePressure) - { - SpringBrake.IsReady = false; - wake_for_brake(); - return true; - } - else - return false; -} - -// ************************************************************************************************* -// pullee mode ("jazda ciągniona", MaSzyna-EU07/maszyna#64): prepares the vehicle for being hauled dead in a -// train, or puts it back in service. while in the mode the vehicle: -// - vents the brake pipe for nothing of its own (inactive cab, vigilance, radio-stop, spring brake), only when -// the train parts (UpdatePipePressure()), -// - gets no force from its spring brake, whatever air its cylinder has (BrakeForce()), -// - has its driver's valve cut out and its local brake released, whatever the handles show; the distributor -// stays on the brake pipe, so it brakes and releases with the train, -// - keeps its battery off and takes no cab (BatterySwitch(), CabActivisation() and their commands). -// entering it also lets go of the hand brake and of the spring brake switch. -// returns whether the mode changed; a vehicle driven from can't enter it -// ************************************************************************************************* -bool TMoverParameters::PulleeModeSwitch(bool const State) -{ - if (PulleeMode == State || (State && CabActive != 0)) - { - return false; - } - PulleeMode = State; - if (PulleeMode) - { - DecManualBrakeLevel(ManualBrakePosNo); - SpringBrake.Activate = false; - SecuritySystem.set_enabled(false); - Battery = false; - } - return true; -} - -// ************************************************************************************************* -// Q: 20160710 -// kierunek do tyłu -// ************************************************************************************************* -bool TMoverParameters::DirectionBackward(void) -{ - if (false == EIMDirectionChangeAllow()) - { - return false; - } - - if (DirActive == 1 && MainCtrlPos == 0 && TrainType == train_type::emu && EngineType != TEngineType::ElectricInductionMotor && MinCurrentSwitch(false)) - { - return true; - } - if (MainCtrlPosNo > 0 && DirActive > -1 && (CabActive != 0 || (InactiveCabFlag & activation::neutraldirection) == 0)) - { - if (EngineType == TEngineType::WheelsDriven) - --CabActive; - // else - --DirActive; - DirAbsolute = DirActive * CabActive; - SendCtrlToNext("Direction", DirActive, CabActive); - return true; - } - - return false; -} - -bool TMoverParameters::EIMDirectionChangeAllow(void) const -{ - bool OK = false; - /* - // NOTE: disabled while eimic variables aren't immediately synced with master controller changes inside ai module - OK = (EngineType != TEngineType::ElectricInductionMotor || ((eimic <= 0) && (eimic_real <= 0) && (Vel < 0.1))); - */ - OK = MainCtrlPos <= MainCtrlMaxDirChangePos; - return OK; -} - -// ************************************************************************************************* -// Q: 20160710 -// załączenie przycisku przeciwpoślizgowego -// ************************************************************************************************* -bool TMoverParameters::AntiSlippingButton(void) -{ - // NOTE: disabled the sandbox part, it's already controlled by another part of the AI routine - return AntiSlippingBrake() /*|| Sandbox(true)*/; -} - -// water pump breaker state toggle -bool TMoverParameters::WaterPumpBreakerSwitch(bool State, range_t const Notify) -{ - /* - if( FuelPump.start_type == start::automatic ) { - // automatic fuel pump ignores 'manual' state commands - return false; - } - */ - bool const initialstate{WaterPump.breaker}; - - WaterPump.breaker = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("WaterPumpBreakerSwitch", WaterPump.breaker ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return WaterPump.breaker != initialstate; -} - -// water pump state toggle -bool TMoverParameters::WaterPumpSwitch(bool State, range_t const Notify) -{ - - if (WaterPump.start_type == start_t::battery) - { - // automatic fuel pump ignores 'manual' state commands - return false; - } - - bool const initialstate{WaterPump.is_enabled}; - - WaterPump.is_enabled = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("WaterPumpSwitch", WaterPump.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return WaterPump.is_enabled != initialstate; -} - -// water pump state toggle -bool TMoverParameters::WaterPumpSwitchOff(bool State, range_t const Notify) -{ - - if (WaterPump.start_type == start_t::battery) - { - // automatic fuel pump ignores 'manual' state commands - return false; - } - - bool const initialstate{WaterPump.is_disabled}; - - WaterPump.is_disabled = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("WaterPumpSwitchOff", WaterPump.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return WaterPump.is_disabled != initialstate; -} - -// water heater breaker state toggle -bool TMoverParameters::WaterHeaterBreakerSwitch(bool State, range_t const Notify) -{ - /* - if( FuelPump.start_type == start::automatic ) { - // automatic fuel pump ignores 'manual' state commands - return false; - } - */ - bool const initialstate{WaterHeater.breaker}; - - WaterHeater.breaker = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("WaterHeaterBreakerSwitch", WaterHeater.breaker ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return WaterHeater.breaker != initialstate; -} - -// water heater state toggle -bool TMoverParameters::WaterHeaterSwitch(bool State, range_t const Notify) -{ - /* - if( FuelPump.start_type == start::automatic ) { - // automatic fuel pump ignores 'manual' state commands - return false; - } - */ - bool const initialstate{WaterHeater.is_enabled}; - - WaterHeater.is_enabled = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("WaterHeaterSwitch", WaterHeater.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return WaterHeater.is_enabled != initialstate; -} - -// water circuits link state toggle -bool TMoverParameters::WaterCircuitsLinkSwitch(bool State, range_t const Notify) -{ - - if (false == dizel_heat.auxiliary_water_circuit) - { - // can't link the circuits if the vehicle only has one - return false; - } - - bool const initialstate{WaterCircuitsLink}; - - WaterCircuitsLink = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("WaterCircuitsLinkSwitch", WaterCircuitsLink ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return WaterCircuitsLink != initialstate; -} - -// fuel pump state toggle -bool TMoverParameters::FuelPumpSwitch(bool State, range_t const Notify) -{ - - if (FuelPump.start_type == start_t::automatic) - { - // automatic fuel pump ignores 'manual' state commands - return false; - } - - bool const initialstate{FuelPump.is_enabled}; - - FuelPump.is_enabled = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("FuelPumpSwitch", FuelPump.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return FuelPump.is_enabled != initialstate; -} - -bool TMoverParameters::FuelPumpSwitchOff(bool State, range_t const Notify) -{ - - if (FuelPump.start_type == start_t::automatic) - { - // automatic fuel pump ignores 'manual' state commands - return false; - } - - bool const initialstate{FuelPump.is_disabled}; - - FuelPump.is_disabled = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("FuelPumpSwitchOff", FuelPump.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return FuelPump.is_disabled != initialstate; -} - -// oil pump state toggle -bool TMoverParameters::OilPumpSwitch(bool State, range_t const Notify) -{ - - if (OilPump.start_type == start_t::automatic) - { - // automatic pump ignores 'manual' state commands - return false; - } - - bool const initialstate{OilPump.is_enabled}; - - OilPump.is_enabled = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("OilPumpSwitch", OilPump.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return OilPump.is_enabled != initialstate; -} - -bool TMoverParameters::OilPumpSwitchOff(bool State, range_t const Notify) -{ - - if (OilPump.start_type == start_t::automatic) - { - // automatic pump ignores 'manual' state commands - return false; - } - - bool const initialstate{OilPump.is_disabled}; - - OilPump.is_disabled = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("OilPumpSwitchOff", OilPump.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return OilPump.is_disabled != initialstate; -} - -bool TMoverParameters::MotorBlowersSwitch(bool State, end const Side, range_t const Notify) -{ - - auto &fan{MotorBlowers[Side]}; - - if (fan.start_type != start_t::manual && fan.start_type != start_t::manualwithautofallback) - { - // automatic device ignores 'manual' state commands - return false; - } - - bool const initialstate{fan.is_enabled}; - - fan.is_enabled = State; - - if (Notify != range_t::local) - { - SendCtrlToNext(Side == end::front ? "MotorBlowersFrontSwitch" : "MotorBlowersRearSwitch", fan.is_enabled ? 1 : 0, CabActive, - Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return fan.is_enabled != initialstate; -} - -bool TMoverParameters::MotorBlowersSwitchOff(bool State, end const Side, range_t const Notify) -{ - - auto &fan{MotorBlowers[Side]}; - - if (fan.start_type != start_t::manual && fan.start_type != start_t::manualwithautofallback) - { - // automatic device ignores 'manual' state commands - return false; - } - - bool const initialstate{fan.is_disabled}; - - fan.is_disabled = State; - - if (Notify != range_t::local) - { - SendCtrlToNext(Side == end::front ? "MotorBlowersFrontSwitchOff" : "MotorBlowersRearSwitchOff", fan.is_disabled ? 1 : 0, CabActive, - Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return fan.is_disabled != initialstate; -} - -bool TMoverParameters::CompartmentLightsSwitch(bool State, range_t const Notify) -{ - - if (CompartmentLights.start_type == start_t::automatic) - { - // automatic lights ignore 'manual' state commands - return false; - } - - bool const initialstate{CompartmentLights.is_enabled}; - - CompartmentLights.is_enabled = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("CompartmentLightsSwitch", CompartmentLights.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return CompartmentLights.is_enabled != initialstate; -} - -// water pump state toggle -bool TMoverParameters::CompartmentLightsSwitchOff(bool State, range_t const Notify) -{ - - if (CompartmentLights.start_type == start_t::automatic) - { - // automatic lights ignore 'manual' state commands - return false; - } - - bool const initialstate{CompartmentLights.is_disabled}; - - CompartmentLights.is_disabled = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("CompartmentLightsSwitchOff", CompartmentLights.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return CompartmentLights.is_disabled != initialstate; -} - -// ************************************************************************************************* -// Q: 20160713 -// włączenie / wyłączenie obwodu głownego -// ************************************************************************************************* -bool TMoverParameters::MainSwitch(bool const State, range_t const Notify) -{ - - bool const initialstate{Mains || dizel_startup}; - - MainSwitch_(State); - - if (Notify != range_t::local) - { - // pass the command to other vehicles - // TBD: pass the requested state, or the actual state? - SendCtrlToNext("MainSwitch", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return (Mains || dizel_startup) != initialstate; -} - -void TMoverParameters::MainSwitch_(bool const State) -{ - - if (Mains == State || MainCtrlPosNo == 0) - { - // nothing to do - return; - } - - bool const initialstate{Mains}; - - if (false == State || true == MainSwitchCheck()) - { - - if (true == State) - { - // switch on - if (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric) - { - // launch diesel engine startup procedure - dizel_startup = true; - } - else - { - // additional check, as vehicles without pantographs won't fail relay checks earlier - Mains = true; - } - } - else - { - Mains = false; - // potentially knock out the pumps if their switch doesn't force them on - WaterPump.is_active &= WaterPump.is_enabled; - FuelPump.is_active &= FuelPump.is_enabled; - } - - if (Mains != initialstate) - { - LastSwitchingTime = 0; - Timer::subsystem.switching.note(Timer::switching_counter::mains, this, &TypeName, &Name); - } - } -} - -bool TMoverParameters::MainSwitchCheck() const -{ - using enum TEngineType; - - // prevent the switch from working if there's no power - // TODO: consider whether it makes sense for diesel engines and such - bool powerisavailable{true}; - - switch (EngineType) - { - case DieselElectric: - case DieselEngine: - case Dumb: - { - powerisavailable = Power24vIsAvailable; - break; - } - case ElectricSeriesMotor: - case ElectricInductionMotor: - { - // TODO: check whether we can simplify this check and skip the outer EngineType switch - // closed ahead of the pantographs, the line breaker runs on the low voltage circuits - powerisavailable = PantographsRequireMains ? Power24vIsAvailable || Power110vIsAvailable : EnginePowerSourceVoltage() > 0.5 * EnginePowerSource.MaxVoltage; - break; - } - default: - { - break; - } - } - if (GensetSelected()) - { - // on the genset of a dual-mode vehicle the line breaker closes only on a running one, whatever the pantographs give - powerisavailable = Genset.is_active && Genset.voltage >= TractionSupplyMinVoltage(); - } - - return powerisavailable && (ScndCtrlPos == 0 || EngineType == ElectricInductionMotor) && MainsInitTimeCountdown <= 0.0 && - (ConvOvldFlag == false || ConverterOverloadRelayOffWhenMainIsOff) && true == GroundRelay && (true == NoVoltRelay || PantographsRequireMains) && true == OvervoltageRelay && - LastSwitchingTime > CtrlDelay && - (HasCamshaft ? IsMainCtrlActualNoPowerPos() : - LineBreakerClosesOnlyAtNoPowerPos ? IsMainCtrlNoPowerPos() : - true) && - false == TestFlag(DamageFlag, dtrain_out) && false == TestFlag(EngDmgFlag, 1) && false == EmergencyBrakeHoldsMainOff(); -} - -// ************************************************************************************************* -// Q: 20160713 -// włączenie / wyłączenie przetwornicy -// ************************************************************************************************* -bool TMoverParameters::ConverterSwitch(bool State, range_t const Notify) -{ - - auto const initialstate{ConverterAllow}; - - if (ConverterStart == start_t::manual) - { - ConverterAllow = State; - } - - if (Notify != range_t::local) - { - SendCtrlToNext("ConverterSwitch", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return ConverterAllow != initialstate; -} - -// ************************************************************************************************* -// Q: 20160713 -// włączenie / wyłączenie sprężarki -// ************************************************************************************************* -bool TMoverParameters::CompressorSwitch(bool State, range_t const Notify) -{ - - if (CompressorStart != start_t::manual) - { - // only pay attention if the compressor can be controlled manually - return false; - } - - auto const initialstate{CompressorAllow}; - - if (VeselVolume > 0.0 && CompressorSpeed > 0.0) - { - CompressorAllow = State; - } - - if (Notify != range_t::local) - { - SendCtrlToNext("CompressorSwitch", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return CompressorAllow != initialstate; -} - -bool TMoverParameters::ChangeCompressorPreset(int const State, range_t const Notify) -{ - - auto const initialstate{CompressorListPos}; - - CompressorListPos = safe_clamp(State, 0, CompressorListPosNo); - - if (Notify != range_t::local) - { - SendCtrlToNext("CompressorPreset", State, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return CompressorListPos != initialstate; -} - -bool TMoverParameters::HeatingSwitch(bool const State, range_t const Notify) -{ - - bool const initialstate{HeatingAllow}; - - HeatingSwitch_(State); - - if (Notify != range_t::local) - { - // pass the command to other vehicles - // TBD: pass the requested state, or the actual state? - SendCtrlToNext("HeatingSwitch", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return HeatingAllow != initialstate; -} - -void TMoverParameters::HeatingSwitch_(bool const State) -{ - - // TBD, TODO: activation dependencies? - HeatingAllow = State; -} - -// the traction selector of a dual-mode vehicle: moves only with the line breaker open, and only where a genset is -bool TMoverParameters::TractionModeSwitch(traction_mode const Mode, range_t const Notify) -{ - auto const initialstate{TractionMode}; - // refused with the line breaker closed, and then not passed on either, so the train stays on one source - auto const accepted{false == Mains}; - - if (Genset.fitted() && accepted) - { - TractionMode = Mode; - } - - if (Notify != range_t::local && accepted) - { - SendCtrlToNext("TractionMode", Mode == traction_mode::genset ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return TractionMode != initialstate; -} - -// the start request of the genset of a dual-mode vehicle; one which starts on its own ignores it, but passes it on to -// the cars behind, which may start theirs on request -bool TMoverParameters::GensetSwitch(bool const State, range_t const Notify) -{ - auto const initialstate{Genset.is_enabled}; - - if (Genset.start_type != start_t::automatic) - { - Genset.is_enabled = State; - } - - if (Notify != range_t::local) - { - SendCtrlToNext("GensetSwitch", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return Genset.is_enabled != initialstate; -} - -// the voltage of the vehicle's own source the traction selector picks: the catenary through the pantographs, or the -// genset of a dual-mode vehicle -double TMoverParameters::TractionSourceVoltage() const -{ - return GensetSelected() ? Genset.voltage : PantographVoltage; -} - -// the voltage the traction circuit gets: from the vehicle's own source, or through the train's high voltage line -double TMoverParameters::TractionSupplyVoltage() const -{ - return std::max(GetTrainsetHighVoltage(), TractionSourceVoltage()); -} - -// below it the undervoltage trip opens the line breaker -double TMoverParameters::TractionSupplyMinVoltage() const -{ - return GensetSelected() ? 0.5 * Genset.voltage_nominal : EnginePowerSource.CollectorParameters.MinV; -} - -// the power the traction may take [kW, at the wheels]: the genset's share at its present revolutions on the genset, -// no limit otherwise -double TMoverParameters::GensetTractionPowerLimit() const -{ - return GensetSelected() ? Genset.available_power() * Genset.traction_share : std::numeric_limits::max(); -} - -// the current the vehicle draws through its pantographs [A], if they touch the wire: the traction's (none while -// braking on the resistors) and the heating's. on the genset the genset feeds the traction circuit, so only a heating -// fed straight from the pantographs is left -double TMoverParameters::CatenaryCurrent() const -{ - if (GensetSelected()) - { - return HeatingPowerSource.SourceType == TPowerSource::CurrentCollector ? TotalCurrent : 0.0; - } - return (DynamicBrakeFlag && ResistorsFlag ? 0 : std::abs(Itot) * IsVehicleEIMBrakingFactor()) + TotalCurrent; -} - -// returns voltage of defined main engine power source -double TMoverParameters::EnginePowerSourceVoltage() const -{ - - return EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? TractionSupplyVoltage() : - EnginePowerSource.SourceType == TPowerSource::Accumulator ? Power24vVoltage : - 0.0; -} - -// whether the main circuit feeds what runs on it: the converter, a compressor, the heating, the motor and resistor -// blowers, the traction motors -bool TMoverParameters::MainCircuitPowered() const -{ - if (false == Mains) - { - return false; - } - if (false == PantographsRequireMains || EnginePowerSource.SourceType != TPowerSource::CurrentCollector) - { - // the closed line breaker says it all: the undervoltage trip opens it without traction voltage, and an engine - // which runs is its own supply - return true; - } - // closed ahead of the pantographs the line breaker holds without the voltage, which the undervoltage trip isn't - // there to vouch for - return EnginePowerSourceVoltage() >= TractionSupplyMinVoltage(); -} - -// ************************************************************************************************* -// Q: 20160711 -// zwiększenie nastawy hamulca -// ************************************************************************************************* -bool TMoverParameters::IncBrakeLevelOld(void) -{ - bool IBLO = false; - - if (BrakeCtrlPosNo > 0) - { - if (BrakeCtrlPos < BrakeCtrlPosNo) - { - ++BrakeCtrlPos; - // youBy: EP po nowemu - IBLO = true; - if (BrakePressureActual.PipePressureVal < 0 && BrakePressureTable[BrakeCtrlPos - 1].PipePressureVal > 0) - LimPipePress = PipePress; - } - else - { - IBLO = false; - } - } - - return IBLO; -} - -// ***************************************************************************** -// Q: 20160711 -// zmniejszenie nastawy hamulca -// ***************************************************************************** -bool TMoverParameters::DecBrakeLevelOld(void) -{ - bool DBLO = false; - - if (BrakeCtrlPosNo > 0) - { - if (BrakeCtrlPos > (BrakeHandle == TBrakeHandle::FV4a ? -2 : -1)) - { - --BrakeCtrlPos; - // youBy: EP po nowemu - DBLO = true; - // if ((BrakePressureTable[BrakeCtrlPos].PipePressureVal<0.0) && - // (BrakePressureTable[BrakeCtrlPos+1].PipePressureVal > 0)) - // LimPipePress=PipePress; - } - else - DBLO = false; - } - - return DBLO; -} - -// ************************************************************************************************* -// Q: 20160711 -// zwiększenie nastawy hamulca pomocnicznego -// ************************************************************************************************* -bool TMoverParameters::IncLocalBrakeLevel(float const CtrlSpeed) -{ - bool IBL; - if (LocalBrakePosA < 1.0 /*and (BrakeCtrlPos<1)*/) - { - LocalBrakePosA = std::min(1.0, LocalBrakePosA + CtrlSpeed / LocalBrakePosNo); - wake_for_brake(); - IBL = true; - } - else - IBL = false; - - return IBL; -} - -// ************************************************************************************************* -// Q: 20160711 -// zmniejszenie nastawy hamulca pomocniczego -// ************************************************************************************************* -bool TMoverParameters::DecLocalBrakeLevel(float const CtrlSpeed) -{ - bool DBL; - if (LocalBrakePosA > 0) - { - LocalBrakePosA = std::max(0.0, LocalBrakePosA - CtrlSpeed / LocalBrakePosNo); - wake_for_brake(); - DBL = true; - } - else - DBL = false; - - return DBL; -} - -// ************************************************************************************************* -// zwiększenie nastawy nastawnika hamulca elektrodynamicznego (DynamicBrakeCtrl) -// uzywane gdy SplitEDPneumaticBrake = true -// ************************************************************************************************* -bool TMoverParameters::IncDynamicBrakeLevel(float const CtrlSpeed) -{ - if (false == SplitEDPneumaticBrake) - return false; - if (DynamicBrakeCtrlPosNo < 1) - return false; - if (DynamicBrakeCtrlPos < 1.0) - { - DynamicBrakeCtrlPos = std::min(1.0, DynamicBrakeCtrlPos + (double)CtrlSpeed / (double)DynamicBrakeCtrlPosNo); - return true; - } - return false; -} - -// ************************************************************************************************* -// zmniejszenie nastawy nastawnika hamulca elektrodynamicznego (DynamicBrakeCtrl) -// ************************************************************************************************* -bool TMoverParameters::DecDynamicBrakeLevel(float const CtrlSpeed) -{ - if (false == SplitEDPneumaticBrake) - return false; - if (DynamicBrakeCtrlPosNo < 1) - return false; - if (DynamicBrakeCtrlPos > 0.0) - { - DynamicBrakeCtrlPos = std::max(0.0, DynamicBrakeCtrlPos - (double)CtrlSpeed / (double)DynamicBrakeCtrlPosNo); - return true; - } - return false; -} - -// ************************************************************************************************* -// bezposrednie ustawienie nastawnika hamulca elektrodynamicznego (DynamicBrakeCtrl) -// ************************************************************************************************* -bool TMoverParameters::DynamicBrakeLevelSet(double Position) -{ - if (false == SplitEDPneumaticBrake) - return false; - DynamicBrakeCtrlPos = std::clamp(Position, 0.0, 1.0); - return true; -} - -// ************************************************************************************************* -// odczyt nastawy nastawnika hamulca elektrodynamicznego (DynamicBrakeCtrl) -// zwraca 0 jezeli SplitEDPneumaticBrake nie jest aktywne (dla zachowania starej logiki) -// ************************************************************************************************* -double TMoverParameters::DynamicBrakeRatio(void) const -{ - if (false == SplitEDPneumaticBrake) - return 0.0; - return std::clamp(DynamicBrakeCtrlPos, 0.0, 1.0); -} - -// ************************************************************************************************* -// czy hamulec ED jest aktualnie dostepny w oknie predkosci Vh0..Vh1 -// ************************************************************************************************* -bool TMoverParameters::DynamicBrakeAvailable(void) const -{ - double const vh0{eimc[eimc_p_Vh0]}; - if (double const vh1{eimc[eimc_p_Vh1]}; vh1 <= 0.001) - { - // brak zdefiniowanej strefy - ED dziala zawsze - return true; - } - // strefa wylaczenia jest definiowana przez Vh0 (minimum); powyzej Vh0 ED dziala - return Vel >= vh0; -} - -// ************************************************************************************************* -// Q: 20160711 -// zwiększenie nastawy hamulca ręcznego -// ************************************************************************************************* -bool TMoverParameters::IncManualBrakeLevel(int CtrlSpeed) -{ - bool IMBL; - if (ManualBrakePos < ManualBrakePosNo) /*and (BrakeCtrlPos<1)*/ - { - while (ManualBrakePos < ManualBrakePosNo && CtrlSpeed > 0) - { - ManualBrakePos++; - CtrlSpeed--; - } - wake_for_brake(); - IMBL = true; - } - else - IMBL = false; - - return IMBL; -} - -// ************************************************************************************************* -// Q: 20160711 -// zmniejszenie nastawy hamulca ręcznego -// ************************************************************************************************* -bool TMoverParameters::DecManualBrakeLevel(int CtrlSpeed) -{ - bool DMBL; - if (ManualBrakePos > 0) - { - while (CtrlSpeed > 0 && ManualBrakePos > 0) - { - ManualBrakePos--; - CtrlSpeed--; - } - wake_for_brake(); - DMBL = true; - } - else - DMBL = false; - return DMBL; -} - -// ************************************************************************************************* -// Q: 20160713 -// reczne przelaczanie hamulca elektrodynamicznego -// ************************************************************************************************* -bool TMoverParameters::DynamicBrakeSwitch(bool Switch) -{ - bool DBS; - - if (DynamicBrakeType == dbrake_switch && IsMainCtrlNoPowerPos()) - { - DynamicBrakeFlag = Switch; - DBS = true; - for (auto &thiscoupler : Couplers) - // with Couplers[b] do - if (TestFlag(thiscoupler.CouplingFlag, coupling::control)) - thiscoupler.Connected->DynamicBrakeFlag = Switch; - // end; - // if (DynamicBrakeType=dbrake_passive) and (TrainType=train_type::et42) then - // begin - // DynamicBrakeFlag:=false; - // DynamicBrakeSwitch:=false; - } - else - DBS = false; - - return DBS; -} - -// ************************************************************************************************* -// Q: 20160711 -// włączenie / wyłączenie hamowania awaryjnego -// ************************************************************************************************* -bool TMoverParameters::RadiostopSwitch(bool Switch) -{ - bool EBS; - if (BrakeSystem != TBrakeSystem::Individual && BrakeCtrlPosNo > 0) - { - - if (true == Switch && false == RadioStopFlag) - { - RadioStopFlag = Switch; - EBS = true; - } - else - { - if (Switch == false && std::abs(V) < 0.1) - { - // odblokowanie hamulca bezpieczenistwa tylko po zatrzymaniu - RadioStopFlag = Switch; - EBS = true; - } - else - { - EBS = false; - } - } - } - else - { - // nie ma hamulca bezpieczenstwa gdy nie ma hamulca zesp. - EBS = false; - } - - return EBS; -} - -bool TMoverParameters::AlarmChainSwitch(bool const State) -{ - - if (AlarmChainFlag != State) - { - // simple routine for the time being - AlarmChainFlag = State; - return true; - } - return false; -} - -// ************************************************************************************************* -// Q: 20160710 -// hamowanie przeciwpoślizgowe -// ************************************************************************************************* -bool TMoverParameters::AntiSlippingBrake(void) -{ - bool ASB = false; // Ra: przeniesione z końca - if (ASBType == 1) - { - ASB = true; // SPKS!! - Hamulec->ASB(1); - BrakeSlippingTimer = 0; - } - return ASB; -} - -// ************************************************************************************************* -// Q: 20160711 -// włączenie / wyłączenie odluźniacza -// ************************************************************************************************* -bool TMoverParameters::BrakeReleaser(int state) -{ - bool OK = true; // false tylko jeśli nie uda się wysłać, GF 20161124 - if (state != 0) - { - // additional limitations imposed by pressure switch - if (false == ControlPressureSwitch || false == ReleaserEnabledOnlyAtNoPowerPos || true == IsMainCtrlNoPowerPos()) - { - Hamulec->Releaser(state); - } - } - else - { - Hamulec->Releaser(state); - } - if (CabActive != 0) // rekurencyjne wysłanie do następnego - OK = SendCtrlToNext("BrakeReleaser", state, CabActive); - return OK; -} - -// ************************************************************************************************* -// yB: 20160711 -// włączenie / wyłączenie uniwersalnego przycisku hamulcowego -// ************************************************************************************************* -bool TMoverParameters::UniversalBrakeButton(int button, int state) -{ - bool OK = true; // false tylko jeśli nie uda się wysłać, GF 20161124 - UniversalBrakeButtonActive[button] = state > 0; - int flag = 0; - if (Power24vIsAvailable || Power110vIsAvailable) - { - for (int i = 0; i < 3; i++) - { - flag = flag | (UniversalBrakeButtonActive[i] ? UniversalBrakeButtonFlag[i] : 0); - } - } - - Hamulec->SetUniversalFlag(flag); - Handle->SetUniversalFlag(flag); - LocHandle->SetUniversalFlag(flag); - UnlockPipe = (flag & TUniversalBrake::ub_UnlockPipe) > 0; - - // if the releaser can be activated by switch - if (TestFlag(UniversalBrakeButtonFlag[0] & UniversalBrakeButtonFlag[1] & UniversalBrakeButtonFlag[2], TUniversalBrake::ub_Release)) - { - BrakeReleaser(TestFlag(flag, TUniversalBrake::ub_Release) ? 1 : 0); - } - return OK; -} - -// ************************************************************************************************* -// Q: 20160711 -// włączenie / wyłączenie hamulca elektro-pneumatycznego -// ************************************************************************************************* -bool TMoverParameters::SwitchEPBrake(int state) -{ - bool OK; - - OK = false; - if (BrakeHandle == TBrakeHandle::St113 && CabOccupied != 0) - { - // the handle works the EP contactors pneumatically, their supply is cut as the Oerlikon handle's is - if (state > 0 && EPBrakeControlPowered()) - EpForce = Handle->GetEP(); // TODO: przetlumaczyc - else - EpForce = 0; - Hamulec->SetEPS(EpForce); - SendCtrlToNext("Brake", EpForce, CabActive); - } - // OK:=SetFlag(BrakeStatus,((2*State-1)*b_epused)); - // SendCtrlToNext('Brake',(state*(2*BrakeCtrlPos-1)),CabActive); - return OK; -} - -bool TMoverParameters::EPBrakeControlPowered() const -{ - return Power24vIsAvailable && DirActive != 0 && EpFuse; -} - -// ************************************************************************************************* -// Q: 20160711 -// zwiększenie ciśnienia hamowania -// ************************************************************************************************* -bool TMoverParameters::IncBrakePress(double &brake, double PressLimit, double dp) -{ - bool IBP; - // if (DynamicBrakeType<>dbrake_switch) and (DynamicBrakeType<>dbrake_none) and - // ((BrakePress>2.0) or (PipePress<3.7{(LowPipePress+0.5)})) then - if (DynamicBrakeType != dbrake_switch && DynamicBrakeType != dbrake_none && BrakePress > 2.0 && TrainType != train_type::emu) // yB radzi nie sprawdzać ciśnienia w przewodzie - // hunter-301211: dla EN57 silnikow nie odlaczamy - { - DynamicBrakeFlag = true; // uruchamianie hamulca ED albo odlaczanie silnikow - if (DynamicBrakeType == dbrake_automatic && abs(Im) > 60) // nie napelniaj wiecej, jak na EP09 - dp = 0.0; - } - if (brake + dp < PressLimit) - { - brake = brake + dp; - IBP = true; - } - else - { - IBP = false; - brake = PressLimit; - } - return IBP; -} - -// ************************************************************************************************* -// Q: 20160711 -// zmniejszenie ciśnienia hamowania -// ************************************************************************************************* -bool TMoverParameters::DecBrakePress(double &brake, double PressLimit, double dp) -{ - bool DBP; - - if (brake - dp > PressLimit) - { - brake = brake - dp; - DBP = true; - } - else - { - DBP = false; - brake = PressLimit; - } - // if ((DynamicBrakeType != dbrake_switch) && ((BrakePress < 0.1) && (PipePress > 0.45 - // /*(LowPipePress+0.06)*/ ))) - if (DynamicBrakeType != dbrake_switch && BrakePress < 0.1) // yB radzi nie sprawdzać ciśnienia w przewodzie - DynamicBrakeFlag = false; // wylaczanie hamulca ED i/albo zalaczanie silnikow - - return DBP; -} - -// ************************************************************************************************* -// Q: 20160711 -// przełączenie nastawy hamulca O/P/T -// ************************************************************************************************* -bool TMoverParameters::BrakeDelaySwitch(int BDS) -{ - bool rBDS; - if (Hamulec->SetBDF(BDS)) - { - BrakeDelayFlag = BDS; - rBDS = true; - Hamulec->SetBrakeStatus(Hamulec->GetBrakeStatus() & ~64); - // kopowanie nastawy hamulca do kolejnego czlonu - do przemyślenia - if (CabActive != 0) - SendCtrlToNext("BrakeDelay", BrakeDelayFlag, CabActive); - } - else - rBDS = false; - - return rBDS; -} - -// ************************************************************************************************* -// Q: 20160712 -// zwiększenie przełożenia hamulca -// ************************************************************************************************* -bool TMoverParameters::IncBrakeMult(void) -{ - bool IBM; - - if (LoadFlag > 0 && MBPM < 2 && LoadFlag < 3) - { - if (MaxBrakePress[2] > 0 && LoadFlag == 1) - LoadFlag = 2; - else - LoadFlag = 3; - IBM = true; - if (BrakeCylMult[2] > 0) - BrakeCylMult[0] = BrakeCylMult[2]; - } - else - IBM = false; - - return IBM; -} - -// ************************************************************************************************* -// Q: 20160712 -// zmniejszenie przełożenia hamulca -// ************************************************************************************************* -bool TMoverParameters::DecBrakeMult(void) -{ - bool DBM; - if (LoadFlag > 1 && MBPM < 2) - { - if (MaxBrakePress[2] > 0 && LoadFlag == 3) - LoadFlag = 2; - else - LoadFlag = 1; - DBM = true; - if (BrakeCylMult[1] > 0) - BrakeCylMult[0] = BrakeCylMult[1]; - } - else - DBM = false; - - return DBM; -} - -// ************************************************************************************************* -// Q: 20160712 -// zaktualizowanie ciśnienia w hamulcach -// ************************************************************************************************* -void TMoverParameters::UpdateBrakePressure(double dt) -{ - // const double LBDelay = 5.0; // stala czasowa hamulca - // double Rate, Speed, dp, sm; - - dpLocalValve = 0; - dpBrake = 0; - - Hamulec->ForceLeak(dt * AirLeakRate * 0.25); // fake air leaks from brake system reservoirs - - auto const brakepress{BrakePress}; - BrakePress = Hamulec->GetBCP(); - if (dt > 0.0) - { - // averaged over about a second: the valves move the cylinder in pulses, quicker than that within a single step - auto const rate{std::abs(BrakePress - brakepress) / dt}; - BrakePressRate += (rate - BrakePressRate) * std::min(1.0, dt / 1.0); - } - // BrakePress:=(Hamulec as TEst4).ImplsRes.pa; - Volume = Hamulec->GetBRP(); -} - -// ************************************************************************************************* -// Q: 20160712 -// Obliczanie pracy sprężarki -// ************************************************************************************************* -void TMoverParameters::CompressorCheck(double dt) -{ - - if (CompressorSpeed == 0.0) - { - CompressorAllow = false; - return; - } - - if (CabDependentCompressor) - { - if (CabActive > 0) - { - MinCompressor = MinCompressor_cabA; - MaxCompressor = MaxCompressor_cabA; - } - if (CabActive < 0) - { - MinCompressor = MinCompressor_cabB; - MaxCompressor = MaxCompressor_cabB; - } - } - - // EmergencyValve - EmergencyValveOpen = Compressor > (EmergencyValveOpen ? EmergencyValveOff : EmergencyValveOn); - if (EmergencyValveOpen) - { - auto dV = static_cast(PF(0, Compressor, EmergencyValveArea) * dt); - CompressedVolume -= dV; - } - - CompressedVolume = std::max(0.0, CompressedVolume - dt * AirLeakRate * 0.1); // nieszczelności: 0.001=1l/s - - Compressor = CompressedVolume / VeselVolume; - - // assorted operational logic - auto const MaxCompressorF{CompressorList[TCompressorList::cl_MaxFactor][CompressorListPos] * MaxCompressor}; - auto const MinCompressorF{CompressorList[TCompressorList::cl_MinFactor][CompressorListPos] * MinCompressor}; - auto const CompressorSpeedF{CompressorList[TCompressorList::cl_SpeedFactor][CompressorListPos] * CompressorSpeed}; - // checking the impact on the compressor allowance - if (auto const AllowFactor{CompressorList[TCompressorList::cl_Allow][CompressorListPos]}; AllowFactor > 0.5) - { - CompressorAllow = AllowFactor > 1.5; - } - - switch (CompressorPower) - { - case 2: - { - CompressorAllow = ConverterAllow; - break; - } - case 3: - { - // HACK: make sure compressor coupled with diesel engine is always ready for work - CompressorStart = start_t::automatic; - break; - } - default: - { - break; - } - } - - // the main circuit, also for a compressor driven by the engine, otherwise the low voltage - auto const compressorpower{CompressorPower == 0 || CompressorPower == 3 ? MainCircuitPowered() : Power110vIsAvailable}; - CompressorPowerTime = compressorpower ? CompressorPowerTime + dt : 0.0; - auto const compressorready{compressorpower && CompressorPowerTime >= CompressorStartDelay}; - // TBD: split CompressorAllow into separate enable/disable flags, inherit compressor from basic_device - auto const compressorenable{CompressorAllowLocal && (CompressorStart == start_t::automatic || CompressorAllow)}; - auto const compressordisable{false == compressorenable}; - - auto const pressureistoolow{Compressor < MinCompressorF}; - auto const pressureistoohigh{Compressor > MaxCompressorF}; - - // TBD, TODO: break the lock with no low voltage power? - auto const governorlockispresent{MaxCompressorF - MinCompressorF > 0.0001}; - CompressorGovernorLock = governorlockispresent && false == pressureistoolow // unlock if pressure drops below minimal threshold - && (pressureistoohigh || CompressorGovernorLock); // lock if pressure goes above maximum threshold - // for these multi-unit engines compressors turn off whenever any of them was affected by the governor - // NOTE: this is crude implementation, limited only to adjacent vehicles - // TODO: re-implement when a more elegant/flexible system is in place - auto const coupledgovernorlock{ - (Couplers[end::rear].Connected != nullptr && true == TestFlag(Couplers[end::rear].CouplingFlag, coupling::permanent) && Couplers[end::rear].Connected->CompressorGovernorLock) || - (Couplers[end::front].Connected != nullptr && true == TestFlag(Couplers[end::front].CouplingFlag, coupling::permanent) && Couplers[end::front].Connected->CompressorGovernorLock)}; - auto const governorlock{CompressorGovernorLock || coupledgovernorlock}; - - auto const compressorflag{CompressorFlag}; - CompressorFlag = - compressorready && false == compressordisable && (false == governorlock || CompressorPower == 3) && (CompressorFlag || (compressorenable && LastSwitchingTime > CtrlDelay)); - - if (CompressorFlag && CompressorFlag != compressorflag) - { - // jeśli została załączona to trzeba ograniczyć ponowne włączenie - LastSwitchingTime = 0; - } - if (CompressorFlag != compressorflag) - { - Timer::subsystem.switching.note(CompressorFlag ? Timer::switching_counter::compressor_on : Timer::switching_counter::compressor_off, this, &TypeName, &Name); - } - - if (false == CompressorFlag) - { - return; - } - - // working compressor adds air to the air reservoir - if (CompressorPower == 3) - { - // the compressor is coupled with the diesel engine, engine revolutions affect the output - CompressedVolume += - CompressorSpeedF * (2.0 * MaxCompressorF - Compressor) / MaxCompressorF * EngineRPMRatio() * dt * (CompressorGovernorLock ? 0.0 : 1.0); // with the lock active air is vented out - } - else - { - // the compressor is a stand-alone device, working at steady pace - CompressedVolume += CompressorSpeedF * (2.0 * MaxCompressorF - Compressor) / MaxCompressorF * dt; - } - - if (pressureistoohigh && (false == governorlockispresent || CompressorPower == 3)) - { - // vent some air out if there's no governor lock to stop the compressor from exceeding acceptable pressure level - SetFlag(SoundFlag, sound::relay | sound::loud); - auto ventedfraction{0.999}; // HACK: drop a tiny bit so the sound doesn't trigger repeatedly - if (false == governorlockispresent) - { - ventedfraction = 0.80; // arbitrary amount - } - else if (CompressorTankValve) - { - ventedfraction = MinCompressorF / MaxCompressorF; // drop to mincompressor level - } - CompressedVolume *= ventedfraction; - if (false == governorlockispresent || CompressorTankValve) - { - CompressorGovernorLock = false; - } - } - - // a compressor not driven by the engine doesn't draw power (some 5 A) from the high- or low voltage circuit yet -} - -// ************************************************************************************************* -// Q: 20160712 -// aktualizacja ciśnienia w przewodzie głównym -// ************************************************************************************************* -void TMoverParameters::UpdatePipePressure(double dt) -{ - if (PipePress > 1.0) - { - Pipe->Flow(-PipePress*AirLeakRate * dt); - Pipe->Act(); - } - - // double dV; - // TMoverParameters *c; // T_MoverParameters - double temp; - // int b; - - PipePress = Pipe->P(); - // PPP:=PipePress; - - dpMainValve = 0; - - if (BrakeCtrlPosNo > 1) - { - - UpdateLocalBrakeValve(dt); - UpdateMainValve(dt); - } - - UpdateEmergencyValve(dt); - - // 0.2*Spg - Pipe->Flow(-dpMainValve); - Pipe->Flow(-PipePress * 0.001 * dt); - // if Heating then - // Pipe.Flow(PF(PipePress, 0, d2A(7)) * dt); - // if ConverterFlag then - // Pipe.Flow(PF(PipePress, 0, d2A(12)) * dt); - dpMainValve = dpMainValve / (Dim.L * Spg * 20); - - CntrlPipePress = Hamulec->GetVRP(); // ciśnienie komory wstępnej rozdzielacza - - // if (Hamulec is typeid(TWest)) return 0; - - UpdateDistributorSettings(); - - if ((BrakeHandle == TBrakeHandle::FVel6 || BrakeHandle == TBrakeHandle::FVE408) && CabOccupied != 0) - { - UpdateEPBrake(); - } - else if (BrakeHandle == TBrakeHandle::St113 && CabOccupied != 0 && std::abs(EpForce) > 0.001 && !EPBrakeControlPowered()) - { - // the EP brake switched on with the button drops out with the control's supply - SwitchEPBrake(0); - } - - Pipe->Act(); - PipePress = Pipe->P(); - if ((Hamulec->GetBrakeStatus() & b_dmg) == b_dmg) // jesli hamulec wyłączony - temp = 0.0; // odetnij - else - temp = 1.0; // połącz - Pipe->Flow(temp * Hamulec->GetPF(temp * PipePress, dt, Vel)); - // the air the brake hoses carry to and from the neighbours comes once all vehicles have stepped, UpdatePipeCouplers() - PipeCouplersPending = true; - - if (ASBType == 128) - Hamulec->ASB(int(SlippingWheels && Vel > 1) * (1 + 2 * int(nrot_eps < -0.01))); - - dpPipe = 0; - - // yB: jednokrokowe liczenie tego wszystkiego - Pipe->Act(); - PipePress = Pipe->P(); - - dpMainValve = dpMainValve / (100.0 * dt); // normalizacja po czasie do syczenia; - - if (PipePress < -1.0) - { - PipePress = -1.0; - Pipe->CreatePress(-1.0); - Pipe->Act(); - } - - if (CompressedVolume < 0.0) - CompressedVolume = 0.0; -} - -// the flow of the local brake valve, by the handle, the TRAXX's timed one, the integrated controller or the parking -void TMoverParameters::UpdateLocalBrakeValve(double dt) -{ - // the local brake of a vehicle prepared for hauling (PulleeMode) is held released, whatever asks for it - if (EngineType != TEngineType::ElectricInductionMotor) - { - double lbpa = LocHandleTimeTraxx ? eim_localbrake : LocalBrakePosA; - if (EIMCtrlType > 0 && UniCtrlIntegratedLocalBrakeCtrl) - { - lbpa = std::max(0.0, -eimic_real); - } - if (SpeedCtrlUnit.Parking) - { - lbpa = std::max(lbpa, StopBrakeDecc); - } - dpLocalValve = LocHandle->GetPF(PulleeMode ? 0.0 : std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); - } - else - { - // in EIM stock the pneumatic local brake is normally driven only by the MED algorithm - // (LocalBrakePosAEIM). When SplitEDPneumaticBrake is active the dedicated LocalBrake - // lever should apply pneumatic pressure on the locomotive directly, bypassing MED. - // LocHandleTimeTraxx also bypasses MED, but has 3 positions (brake-hold-unbrake). - double lbpa; - if (LocHandleTimeTraxx) - { - lbpa = eim_localbrake; - } - else if (SplitEDPneumaticBrake) // When LocHandleTimeTraxx and SplitEDPneumaticBrake are both active, lbpa is taken from LocHandleTimeTraxx, which is the desired behavior. - { - lbpa = LocalBrakePosA; - } - else - { - lbpa = 0.0; - } - dpLocalValve = LocHandle->GetPF(PulleeMode ? 0.0 : std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); - } -} - -// the lock of the brake pipe and the flow of the driver's handle, from the main reservoir or into the air -void TMoverParameters::UpdateMainValve(double dt) -{ - auto const temp{MainValveSupply()}; - Handle->SetReductor(BrakeCtrlPos2); - - if (PulleeMode) - { - // the driver's valve of a vehicle prepared for hauling is cut out, whatever its handle shows - dpMainValve = 0; - } - else if ((BrakeOpModes & bom_PS) == 0 || (CabOccupied != 0 && BrakeOpModeFlag != bom_PS)) - { - - if (BrakeOpModeFlag < bom_EP || Handle->GetPos(bh_EB) - 0.5 < BrakeCtrlPosR || (BrakeHandle != TBrakeHandle::MHZ_EN57 && BrakeHandle != TBrakeHandle::MHZ_K8P)) - { - dpMainValve = Handle->GetPF(MainValveHandlePosition(), PipePress, temp, dt, EqvtPipePress); - } - else - { - dpMainValve = Handle->GetPF(0, PipePress, temp, dt, EqvtPipePress); - } - } - else if (BrakeCtrlPos == Handle->GetPos(bh_EB)) - { - dpMainValve = Handle->GetPF(BrakeCtrlPosR, PipePress, temp, dt, EqvtPipePress); - } - - if (dpMainValve < 0) // && (PipePressureVal > 0.01) //50 - { - if (Compressor > ScndPipePress) - { - CompressedVolume = CompressedVolume + dpMainValve / 1500.0; - Pipe2->Flow(dpMainValve / 3.0); - } - else - Pipe2->Flow(dpMainValve); - } -} - -// the pressure the driver's handle is fed from: the main pipe's, or the brake pipe's own with the pipe locked -double TMoverParameters::MainValveSupply() -{ - LockPipe = PipePress < (LockPipe ? LockPipeOff : LockPipeOn); - bool lock_new = (LockPipe && !UnlockPipe && BrakeCtrlPosR > HandleUnlock) || (EmergencyCutsOffHandle && EmergencyValveFlow > 0); // new simple codition based on .fiz - bool lock_old = BrakeHandle == TBrakeHandle::FV4a // old complex condition based on assumptions - && PipePress < 2.75 && (Hamulec->GetStatus() & b_rls) == 0 && BrakeSubsystem == TBrakeSubSystem::ss_LSt && TrainType != train_type::emu && !UnlockPipe; - - if (lock_old || lock_new) - { - return PipePress + 0.00001; - } - return ScndPipePress; -} - -// the position the driver's handle works at: its own, or the one the speed control's brake intervention sets -double TMoverParameters::MainValveHandlePosition() const -{ - double pos = BrakeCtrlPosR; - if (SpeedCtrlUnit.IsActive && SpeedCtrlUnit.BrakeIntervention && !SpeedCtrlUnit.Standby && BrakeCtrlPos != Handle->GetPos(bh_EB)) - { - pos = Handle->GetPos(bh_NP); - if (SpeedCtrlUnit.BrakeInterventionBraking) - pos = Handle->GetPos(bh_FB); - if (SpeedCtrlUnit.BrakeInterventionUnbraking) - pos = Handle->GetPos(bh_RP); - } - return pos; -} - -void TMoverParameters::UpdateEmergencyValve(double dt) -{ - // ulepszony hamulec bezp. - EmergencyValveFlow = 0.0; - - - // EngDmgFlag 32 (load destroyed) used to trigger this too; dropped, it has nothing to do with - // the emergency brake (a broken coupler sets AlarmChainFlag instead). the Elf's emergency brake position - // vents the pipe only from the vehicle driven from, whatever the controllers of the others show. - // a vehicle prepared for hauling (PulleeMode) vents it for nothing of its own, only for the alarm chain, - // which a train parting sets too - auto const ownemergency{RadioStopFlag || (EIMCtrlEmergency && LocalBrakePosA >= 1.0) || (IsMainCtrlEmergencyPos() && IsCabMaster()) || SecuritySystem.is_braking() || - (SpringBrakeDriveEmergencyVel >= 0 && Vel > SpringBrakeDriveEmergencyVel && SpringBrake.IsActive) || - (0 == CabActive && (InactiveCabFlag & activation::emergencybrake) != 0)}; - if (AlarmChainFlag || (ownemergency && false == PulleeMode)) - { - EmergencyValveFlow = PF(0, PipePress, 0.15) * dt; - } - dpMainValve += EmergencyValveFlow; -} - -// what the distributor valve gets of the local brake and the load, by its kind -void TMoverParameters::UpdateDistributorSettings() -{ - switch (BrakeValve) - { - - case TBrakeValve::K: - case TBrakeValve::W: - { - - if (BrakeLocHandle != TBrakeHandle::NoHandle) - { - LocBrakePress = LocHandle->GetCP(); - - //(Hamulec as TWest).SetLBP(LocBrakePress); - Hamulec->SetLBP(LocBrakePress); - } - if (MBPM < 2) - //(Hamulec as TWest).PLC(MaxBrakePress[LoadFlag]) - Hamulec->PLC(MaxBrakePress[LoadFlag]); - else - //(Hamulec as TWest).PLC(TotalMass); - Hamulec->PLC(TotalMass - Mred); - break; - } - - case TBrakeValve::LSt: - case TBrakeValve::EStED: - { - - LocBrakePress = LocHandle->GetCP(); - auto const et41or42 = [](train_type const Type) { return Type == train_type::et41 || Type == train_type::et42; }; - for (auto const &couplerentry : Couplers) - // nie podoba mi się to rozwiązanie, chyba trzeba - // dodać jakiś wpis do fizyki na to - if (et41or42(TrainType) && couplerentry.Connected != nullptr && et41or42(couplerentry.Connected->TrainType) && (couplerentry.CouplingFlag & 36) == 36) - LocBrakePress = std::max(couplerentry.Connected->LocHandle->GetCP(), LocBrakePress); - - // if ((DynamicBrakeFlag) && (EngineType == ElectricInductionMotor)) - //{ - // //if (Vel > 10) - // // LocBrakePress = 0; - // //else if (Vel > 5) - // // LocBrakePress = (10 - Vel) / 5 * LocBrakePress; - // } - - //(Hamulec as TLSt).SetLBP(LocBrakePress); - Hamulec->SetLBP(LocBrakePress); - if (BrakeValve == TBrakeValve::EStED) - { - if (MBPM < 2) - Hamulec->PLC(MaxBrakePress[LoadFlag]); - else - Hamulec->PLC(TotalMass - Mred); - } - break; - } - - case TBrakeValve::CV1_L_TR: - { - LocBrakePress = LocHandle->GetCP(); - //(Hamulec as TCV1L_TR).SetLBP(LocBrakePress); - Hamulec->SetLBP(LocBrakePress); - break; - } - - case TBrakeValve::EP2: - case TBrakeValve::EP1: - { - Hamulec->PLC(TotalMass - Mred); - break; - } - case TBrakeValve::ESt3AL2: - case TBrakeValve::NESt3: - case TBrakeValve::ESt4: - case TBrakeValve::ESt3: - { - if (MBPM < 2) - //(Hamulec as TNESt3).PLC(MaxBrakePress[LoadFlag]) - Hamulec->PLC(MaxBrakePress[LoadFlag]); - else - //(Hamulec as TNESt3).PLC(TotalMass); - Hamulec->PLC(TotalMass - Mred); - LocBrakePress = LocHandle->GetCP(); - //(Hamulec as TNESt3).SetLBP(LocBrakePress); - Hamulec->SetLBP(LocBrakePress); - break; - } - case TBrakeValve::KE: - { - LocBrakePress = LocHandle->GetCP(); - //(Hamulec as TKE).SetLBP(LocBrakePress); - Hamulec->SetLBP(LocBrakePress); - if (MBPM < 2) - //(Hamulec as TKE).PLC(MaxBrakePress[LoadFlag]) - Hamulec->PLC(MaxBrakePress[LoadFlag]); - else - //(Hamulec as TKE).PLC(TotalMass); - Hamulec->PLC(TotalMass - Mred); - break; - } - default: - { - // unsupported brake valve type, we should never land here - // ErrorLog( "Unsupported brake valve type (" + std::to_string( BrakeValve ) + ") in " + TypeName ); - // ::PostQuitMessage( 0 ); - break; - } - } // switch -} - -// the ep brake of the FVel6 and FVE408 handles, passed along the unit -void TMoverParameters::UpdateEPBrake() -{ - if (EPBrakeControlPowered()) // tu powinien byc jeszcze bezpiecznik EP i baterie - - // temp = (Handle as TFVel6).GetCP - EpForce = Handle->GetEP(); - else - EpForce = 0.0; - - DynamicBrakeEMUStatus = EpForce > 0.001 ? Power110vIsAvailable : true; - - double temp1 = EpForce; - if (DCEMUED_EP_max_Vel > 0.001 && Vel > DCEMUED_EP_max_Vel && DynamicBrakeEMUStatus) - temp1 = 0; - if (DCEMUED_EP_min_Im > 0.001 && abs(Im) > DCEMUED_EP_min_Im && DynamicBrakeEMUStatus) - temp1 = 0; - Hamulec->SetEPS(temp1); - TUHEX_StageActual = static_cast(EpForce); - TUHEX_Active = TUHEX_StageActual > 0; - // Ra 2014-11: na tym się wysypuje, ale nie wiem, w jakich warunkach - SendCtrlToNext("Brake", EpForce, CabActive); -} - -// ************************************************************************************************* -// Q: 20160713 -// Aktualizacja ciśnienia w przewodzie zasilającym -// ************************************************************************************************* -void TMoverParameters::UpdateScndPipePressure(double dt) -{ - if (ScndPipePress > 1.0) - { - Pipe2->Flow(-ScndPipePress*AirLeakRate * dt); - Pipe2->Act(); - } - - const double Spz = 0.5067; - - UpdateSpringBrake(dt); - - Pipe2->Flow(Hamulec->GetHPFlow(ScndPipePress, dt)); - // NOTE: condition disabled to allow the air flow from the main hose to the main tank as well - if (/* ( ( Compressor > ScndPipePress ) && ( */ VeselVolume > 0.0 /* ) ) || ( TrainType == train_type::emu ) || ( TrainType == train_type::dmu ) */) - { - double const dV = PF(Compressor, ScndPipePress, Spz) * dt; - CompressedVolume += dV / 1000.0; - Pipe2->Flow(-dV); - } - // the air the main reservoir hoses carry to and from the neighbours comes once all vehicles have stepped, UpdatePipeCouplers() - ScndPipeCouplersPending = true; - Pipe2->Act(); - ScndPipePress = Pipe2->P(); - - if (ScndPipePress < -1) - { - ScndPipePress = -1; - Pipe2->CreatePress(-1); - Pipe2->Act(); - } -} - -// ************************************************************************************************* -// yB: 20190906 -// Aktualizacja ciśnienia w hamulcu sprezynowym -// ************************************************************************************************* -void TMoverParameters::UpdateSpringBrake(double /*dt*/) -{ - double BP = SpringBrake.PNBrakeConnection ? BrakePress : 0; - double MSP = SpringBrake.ShuttOff ? 0 : SpringBrake.MaxSetPressure; - if (!SpringBrake.Activate) - { - double desired_press = std::min(std::max(MSP, BP), Pipe2->P()); - double dv = PF(desired_press, SpringBrake.SBP, SpringBrake.ValveOffArea); - SpringBrake.Cylinder->Flow(-dv); - Pipe2->Flow(std::max(dv, 0.0)); - } - else - { - double dv = PF(BP, SpringBrake.SBP, SpringBrake.ValveOnArea); - SpringBrake.Cylinder->Flow(-dv); - } - if (SpringBrake.SBP > SpringBrake.ResetPressure) - SpringBrake.IsReady = true; - - SpringBrake.IsActive = SpringBrake.SBP < (SpringBrake.IsActive ? SpringBrake.PressureOff : SpringBrake.PressureOn); - - SpringBrake.Release = false; - SpringBrake.Cylinder->Act(); - SpringBrake.SBP = SpringBrake.Cylinder->P(); -} - -namespace -{ -// whether the air flowing to a coupled vehicle along a pipe wakes its physics: any flow did, but a vehicle standing next to one -// whose physics is on gets a trickle of it all the time, as their pressures settle, and each wake kept it on for 5 s. with -// Global.physics_pipewake only a flow which leaves its pressure, with what has flown in while it slept, that much away from the -// pressure of the vehicle the air comes from, or which has changed it by that much since it fell asleep: a pressure followed in -// small steps would never reach the valves of a vehicle asleep otherwise -bool pipe_wakes(double const Flow, double const Pressure, TReservoir const &Pipe) -{ - if (Flow * Flow <= 0.00000000000001) - return false; - return (Global.physics_pipewake <= 0.f) - || (std::abs(Pressure - Pipe.P_pending()) > Global.physics_pipewake) - || (std::abs(Pipe.P_pending() - Pipe.P_applied()) > Global.physics_pipewake); -} - -// the pressure in the pipe of a coupled vehicle the flow to it goes by. the pressure the vehicle keeps is the one of its last step: -// with Global.physics_pipewake one asleep can take air for a long time without waking, and the flow, going by that pressure, would -// carry on past the pressure of the vehicle it comes from. so of one asleep, the pressure with what has flown in since -double neighbour_pipe_pressure(TMoverParameters const &Neighbour, double const Pressure, TReservoir const &Pipe) -{ - if ((Global.physics_pipewake <= 0.f) || Neighbour.PhysicActivation) - return Pressure; - return Pipe.P_pending(); -} -} // namespace - -// ************************************************************************************************* -// Q: 20160715 -// oblicza i zwraca przepływ powietrza pomiędzy pojazdami -// ************************************************************************************************* -double TMoverParameters::GetDVc(double dt) -{ - // T_MoverParameters *c; - TMoverParameters *c; - double dv1; - double dv2; // , dV; - - dv1 = 0; - dv2 = 0; - // sprzeg 1 - if (Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_pneumatic)) - { //*0.85 - c = Couplers[0].Connected; // skrot //0.08 //e/D * L/D = e/D^2 * L - dv1 = 0.5 * dt * PF(PipePress, neighbour_pipe_pressure(*c, c->PipePress, *c->Pipe), Spg / (1.0 + 0.015 / Spg * Dim.L)); - c->Pipe->Flow(-dv1); - if (pipe_wakes(dv1, PipePress, *c->Pipe)) - c->switch_physics(true, wake_cause::mainpipe); - } - // sprzeg 2 - if (Couplers[1].Connected != nullptr && TestFlag(Couplers[1].CouplingFlag, ctrain_pneumatic)) - { - c = Couplers[1].Connected; // skrot - dv2 = 0.5 * dt * PF(PipePress, neighbour_pipe_pressure(*c, c->PipePress, *c->Pipe), Spg / (1.0 + 0.015 / Spg * Dim.L)); - c->Pipe->Flow(-dv2); - if (pipe_wakes(dv2, PipePress, *c->Pipe)) - c->switch_physics(true, wake_cause::mainpipe); - } - // if ((Couplers[1].Connected != NULL) && (Couplers[0].Connected != NULL)) - // if ((TestFlag(Couplers[0].CouplingFlag, ctrain_pneumatic)) && - // (TestFlag(Couplers[1].CouplingFlag, ctrain_pneumatic))) - // { - // dV = 0.05 * dt * PF(Couplers[0].Connected->PipePress, Couplers[1].Connected->PipePress, - // (Spg * 0.85) / (1 + 0.03 * Dim.L)) * - // 0; // ktoś mi powie jaki jest sens tego bloku jeśli przepływ mnożony przez zero? - // Couplers[0].Connected->Pipe->Flow(+dV); - // Couplers[1].Connected->Pipe->Flow(-dV); - // } - // suma - return dv2 + dv1; -} - -// ************************************************************************************************* -// the air the main reservoir hoses carry between the vehicle's pipe and the neighbours' in dt: the neighbours' -// share is sent to them, the vehicle's own returned -// ************************************************************************************************* -double TMoverParameters::GetScndDVc(double dt) -{ - const double Spz = 0.5067; - TMoverParameters *c; - double dv1 = 0; - double dv2 = 0; - - // sprzeg 1 - if (Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic)) - { - c = Couplers[0].Connected; // skrot - dv1 = 0.5 * dt * PF(ScndPipePress, neighbour_pipe_pressure(*c, c->ScndPipePress, *c->Pipe2), Spz * 0.75); - c->Pipe2->Flow(-dv1); - if (pipe_wakes(dv1, ScndPipePress, *c->Pipe2)) - c->switch_physics(true, wake_cause::scndpipe); - } - // sprzeg 2 - if (Couplers[1].Connected != nullptr && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) - { - c = Couplers[1].Connected; // skrot - dv2 = 0.5 * dt * PF(ScndPipePress, neighbour_pipe_pressure(*c, c->ScndPipePress, *c->Pipe2), Spz * 0.75); - c->Pipe2->Flow(-dv2); - if (pipe_wakes(dv2, ScndPipePress, *c->Pipe2)) - c->switch_physics(true, wake_cause::scndpipe); - } - if (Couplers[1].Connected != nullptr && Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic) && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) - { - double const dV = 0.00025 * dt * PF(Couplers[0].Connected->ScndPipePress, Couplers[1].Connected->ScndPipePress, Spz * 0.25); - Couplers[0].Connected->Pipe2->Flow(+dV); - Couplers[1].Connected->Pipe2->Flow(-dV); - } - return dv1 + dv2; -} - -namespace -{ - -// a pipe along the train, whose air the hoses between the vehicles carry (TMoverParameters::UpdatePipeCouplers()) -struct train_pipe -{ - std::shared_ptr TMoverParameters::*reservoir; - double TMoverParameters::*pressure; - bool TMoverParameters::*pending; // the vehicle stepped the pipe, the exchange through its hoses is yet to come - int hose; // the coupling flag of the pipe's hose - double (TMoverParameters::*exchange)(double); // the air the hoses carry in a step, the neighbours' share sent to them - double (*area)(TMoverParameters const &); // the cross-section of the hose, as the exchange takes it -}; - -// the brake pipe, GetDVc() -train_pipe const brake_pipe{&TMoverParameters::Pipe, - &TMoverParameters::PipePress, - &TMoverParameters::PipeCouplersPending, - ctrain_pneumatic, - &TMoverParameters::GetDVc, - [](TMoverParameters const &Vehicle) { return Vehicle.Spg / (1.0 + 0.015 / Vehicle.Spg * Vehicle.Dim.L); }}; -// the main reservoir pipe, GetScndDVc() -train_pipe const main_reservoir_pipe{&TMoverParameters::Pipe2, - &TMoverParameters::ScndPipePress, - &TMoverParameters::ScndPipeCouplersPending, - ctrain_scndpneumatic, - &TMoverParameters::GetScndDVc, - [](TMoverParameters const &) { return 0.5067 * 0.75; }}; - -// the number of sub-steps of dt the air exchange through the hoses of the vehicle's pipe needs: in one, the air a -// hose carries stays below what evens out the pipes on its ends -int hose_substeps(TMoverParameters const &Vehicle, train_pipe const &Pipe, double const dt) -{ - auto substeps{1}; - auto const area{Pipe.area(Vehicle)}; - auto const capacity{(Vehicle.*Pipe.reservoir)->GetCap()}; - for (auto const &hose : Vehicle.Couplers) - { - if (hose.Connected == nullptr || false == TestFlag(hose.CouplingFlag, Pipe.hose)) - { - continue; - } - auto const &other{*hose.Connected}; - auto const othercapacity{(other.*Pipe.reservoir)->GetCap()}; - // the flow per bar of the difference, at small differences, where it's the largest - auto const pressure{std::max(Vehicle.*Pipe.pressure, other.*Pipe.pressure)}; - auto const conductance{std::abs(PF(pressure, pressure - 0.01, area)) / 0.01}; - auto const equalising{capacity * othercapacity / (capacity + othercapacity)}; - substeps = std::max(substeps, static_cast(std::ceil(dt * conductance / equalising))); - } - return std::min(substeps, 10); -} - -// the vehicles of the list which stepped the pipe, each with the number of the train it is in: the ones joined by the hoses -// of the pipe, directly, numbered in the order of their first vehicle in the list. a vehicle which didn't step the pipe -// (its physics sleeps) takes the air sent to it without passing it on, so it ends a train -std::vector hose_trains(std::vector const &Vehicles, train_pipe const &Pipe) -{ - auto constexpr none{std::numeric_limits::max()}; - std::vector trains(Vehicles.size(), none); - // the vehicles by their address, for finding the neighbours in the list - std::vector> byaddress; - byaddress.reserve(Vehicles.size()); - for (std::size_t index = 0; index < Vehicles.size(); ++index) - { - if (Vehicles[index]->*Pipe.pending) - { - byaddress.emplace_back(Vehicles[index], index); - } - } - std::ranges::sort(byaddress); - auto const find = [&byaddress](TMoverParameters const *Vehicle) { - auto const found{std::ranges::lower_bound(byaddress, Vehicle, std::less<>{}, &std::pair::first)}; - return (found != byaddress.end() && found->first == Vehicle) ? found->second : none; - }; - std::size_t count{0}; - std::vector stack; - for (std::size_t first = 0; first < Vehicles.size(); ++first) - { - if (false == Vehicles[first]->*Pipe.pending || trains[first] != none) - { - continue; - } - trains[first] = count; - stack.assign(1, first); - while (false == stack.empty()) - { - auto const &vehicle{*Vehicles[stack.back()]}; - stack.pop_back(); - for (auto const &hose : vehicle.Couplers) - { - if (hose.Connected == nullptr || false == TestFlag(hose.CouplingFlag, Pipe.hose)) - { - continue; - } - if (auto const other{find(hose.Connected)}; other != none && trains[other] == none) - { - trains[other] = count; - stack.push_back(other); - } - } - } - ++count; - } - return trains; -} - -// 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 &Pipe, double const dt) -{ - auto const trains{hose_trains(Vehicles, Pipe)}; - std::vector substeps; - for (std::size_t index = 0; index < Vehicles.size(); ++index) - { - if (false == Vehicles[index]->*Pipe.pending) - { - continue; - } - if (substeps.size() <= trains[index]) - { - substeps.resize(trains[index] + 1, 1); - } - substeps[trains[index]] = std::max(substeps[trains[index]], hose_substeps(*Vehicles[index], Pipe, dt)); - } - 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) - { - if (false == Vehicles[index]->*Pipe.pending || trains[index] != train) - { - continue; - } - auto *vehicle{Vehicles[index]}; - auto &pipe{*(vehicle->*Pipe.reservoir)}; - pipe.Act(); // what the neighbours have sent in the meantime - vehicle->*Pipe.pressure = pipe.P(); - pipe.Flow((vehicle->*Pipe.exchange)(substep)); - pipe.Act(); - vehicle->*Pipe.pressure = pipe.P(); - } - } - } - for (auto *vehicle : Vehicles) - { - vehicle->*Pipe.pending = false; - } -} - -} // namespace - -// ************************************************************************************************* -// the number of sub-steps of dt the air exchange through the brake hoses of the vehicle needs. taken in a single -// step of 0.01 s, the hose between two 14 m freight wagons carries twice the air which evens out their pipes, the -// pipes overshoot each other in turns and the distributors see the pressure up to 0.28 bar off what's in the pipe -// (eu07/maszyna#368) -// ************************************************************************************************* -int TMoverParameters::PipeCouplersSubsteps(double const dt) const -{ - return hose_substeps(*this, brake_pipe, dt); -} - -// ************************************************************************************************* -// the number of sub-steps of dt the air exchange through the main reservoir hoses of the vehicle needs. taken in a -// single step of 0.01 s, the hose carries about 1.5 times the air which evens out the pipes on its ends; along with -// the vehicles' own main reservoirs feeding the pipe in the same step, the pipes of the middle vehicles of a -// multiple unit or of locomotives in multiple traction kept jumping 0.8 bar to and fro between the steps -// ************************************************************************************************* -int TMoverParameters::ScndPipeCouplersSubsteps(double const dt) const -{ - return hose_substeps(*this, main_reservoir_pipe, dt); -} - -// ************************************************************************************************* -// the air exchange through the brake and the main reservoir hoses of the vehicles which stepped their pipes -// (UpdatePipePressure(), UpdateScndPipePressure()) since the last call, each pipe in its own sub-steps -// ************************************************************************************************* -void TMoverParameters::UpdatePipeCouplers(std::vector const &Vehicles, double const dt) -{ - exchange_through_hoses(Vehicles, brake_pipe, dt); - exchange_through_hoses(Vehicles, main_reservoir_pipe, dt); -} - -// ************************************************************************************************* -// Q: 20160713 -// Obliczenie stałych potrzebnych do dalszych obliczeń -// ************************************************************************************************* -void TMoverParameters::ComputeConstans(void) -{ - double BearingF; - double RollF; - double HideModifier; - double Curvature; // Ra 2014-07: odwrotność promienia - - TotalMassxg = TotalMass * g; // TotalMass*g - BearingF = (DamageFlag & dtrain_bearing) != 0 ? 2.0 : 0; - - HideModifier = 0; // int(Couplers[0].CouplingFlag>0)+int(Couplers[1].CouplingFlag>0); - - if (BearingType == 0) - RollF = 0.05; // slizgowe - else - RollF = 0.015; // toczne - RollF += BearingF / 200.0; - - // if (NPoweredAxles > 0) - // RollF = RollF * 1.5; //dodatkowe lozyska silnikow - - if (NPoweredAxles > 0) // drobna optymalka - { - RollF += 0.025; - // if (Ft * Ft < 1) - // HideModifier = HideModifier - 3; - } - Ff = TotalMassxg * (BearingF + RollF * V * V / 10.0) / 1000.0; - // dorobic liczenie temperatury lozyska! - FrictConst1 = TotalMassxg * RollF / 10000.0; - // drag calculation - { - // NOTE: draft effect of previous vehicle is simplified and doesn't have much to do with reality - auto const *previousvehicle{Couplers[V >= 0.0 ? end::front : end::rear].Connected}; - auto dragarea{Dim.W * Dim.H}; - if (previousvehicle) - { - dragarea = std::max(0.0, dragarea - 0.85 * previousvehicle->Dim.W * previousvehicle->Dim.H); - } - FrictConst1 += Cx * dragarea; - } - - if (CategoryFlag & 1) - { - Curvature = RunningShape.R == 0.0 ? // zero oznacza nieskończony promień - 0.0 : - 1.0 / std::abs(RunningShape.R); - } - else - { - // vehicles other than trains don't experience friction against the rail on curves - Curvature = 0.0; - } - // opór składu na łuku (youBy): +(500*TrackW/R)*TotalMassxg*0.001 do FrictConst2s/d - FrictConst2s = TotalMassxg * (500.0 * TrackW * Curvature + 2.5 - HideModifier + 2 * BearingF / dtrain_bearing) * 0.001; - FrictConst2d = TotalMassxg * (500.0 * TrackW * Curvature + 2.0 - HideModifier + BearingF / dtrain_bearing) * 0.001; -} - -// ************************************************************************************************* -// Q: 20160713 -// Oblicza masę ładunku -// ************************************************************************************************* -void TMoverParameters::ComputeMass() -{ - // Ra: na razie tak, ale nie wszędzie masy wirujące się wliczają - TotalMass = Mass + Mred; - - if (LoadAmount == 0) - { - return; - } - - // include weight of carried load - auto loadtypeunitweight{0.f}; - - if (ToLower(LoadQuantity) == "tonns") - { - loadtypeunitweight = 1000; - } - else - { - auto const lookup{simulation::Weights.find(LoadType.name)}; - loadtypeunitweight = lookup != simulation::Weights.end() ? lookup->second : 1000.f; // legacy default unit weight value - } - - TotalMass += LoadAmount * loadtypeunitweight; -} - -// ************************************************************************************************* -// Q: 20160713 -// Obliczanie wypadkowej siły z wszystkich działających sił -// ************************************************************************************************* -// TBD, TODO: move some of the calculations out of the method, they're relevant to more than just force calculations -void TMoverParameters::ComputeTotalForce(double dt) -{ - - Vel = std::abs(V) * 3.6; // prędkość w km/h - - // McZapkie-031103: sprawdzanie czy warto liczyc fizyke i inne updaty - // ABu 300105: cos tu mieszalem , dziala teraz troche lepiej, wiec zostawiam - { - // asleep, the brake force is the one of the step it fell asleep in: a vehicle whose brakes have changed since, released - // or applied, wakes for the 5 s of LastSwitchingTime, which take the new force into FStand, and sleeps again if it's - // still held. none of the causes of the test below, so as "other" - if (brakes_changed_asleep()) - switch_physics(true, wake_cause::other); - - auto const vehicleisactive{CabActive != 0 || Vel > 0.0001 || accelerating() || LastSwitchingTime < 5 || is_multiple_unit()}; - - auto const movingvehicleahead{Neighbours[end::front].vehicle != nullptr && - (Neighbours[end::front].vehicle->MoverParameters->Vel > 0.0001 || Neighbours[end::front].vehicle->MoverParameters->accelerating())}; - - auto const movingvehiclebehind{Neighbours[end::rear].vehicle != nullptr && - (Neighbours[end::rear].vehicle->MoverParameters->Vel > 0.0001 || Neighbours[end::rear].vehicle->MoverParameters->accelerating())}; - - auto const calculatephysics{vehicleisactive || movingvehicleahead || movingvehiclebehind}; - - switch_physics(calculatephysics, Vel > 0.0001 ? wake_cause::speed : - accelerating() ? wake_cause::acceleration : - vehicleisactive ? wake_cause::rest : - wake_cause::neighbour); - } - - if (false == PhysicActivation) - { - return; - } - - // juz zoptymalizowane: - FStand = FrictionForce(); // siła oporów ruchu - if (true == TestFlag(DamageFlag, dtrain_out)) - { - if (Derailed != derailment::outcome::none) - { - // off the rails by the physical criteria: the vehicle slides on the sleepers and the ballast, or on its side; - // off the track on the ground, as far as it tipped over (physics.derailment new) - auto const friction{OffTrack.active() ? OffTrack.friction() : derailment::sliding_friction(Derailed)}; - FStand = friction * (TotalMass - Mred) * g; - } - else if (legacy_derailed_slides(*this)) - { - // derailed the legacy way with physics.collisions new: the deceleration of g of the legacy model, as a friction - FStand = TotalMass * g; - } - else - { - // HACK: crude way to reduce speed after derailment - // TBD, TODO: more accurate approach? - FStand *= 1e20; - } - } - double old_nrot = abs(nrot); - nrot = v2n(); // przeliczenie prędkości liniowej na obrotową - - if (true == TestFlag(BrakeMethod, bp_MHS) && PipePress < 3.0 // ustawione na sztywno na 3 bar - && Vel > 45 && true == TestFlag(BrakeDelayFlag, bdelay_M)) - { - // doliczenie hamowania hamulcem szynowym - FStand += TrackBrakeForce; - } - // w charakterystykach jest wartość siły hamowania zamiast nacisku - - LastSwitchingTime += dt; - if (EngineType == TEngineType::ElectricSeriesMotor) - { - LastRelayTime += dt; - } - - if (EngineType == TEngineType::ElectricSeriesMotor) // potem ulepszyc! pantogtrafy! - { // Ra 2014-03: uwzględnienie kierunku jazdy w napięciu na silnikach, a powinien być zdefiniowany nawrotnik - EngineVoltage = Mains ? EnginePowerSourceVoltage() : 0.0; - if (CabActive == 0) - { - EngineVoltage *= DirActive; - } - else - { - EngineVoltage *= DirAbsolute; // the reverser of the active cab, relative to the couplers - } - } // bo nie dzialalo - else - { - EngineVoltage = Power > 1.0 ? TractionSupplyVoltage() : 0.0; - } - - FTrain = Power > 0 ? TractionForce(dt) : 0; - double FT_factor = 1.0; - if (EngineType == TEngineType::ElectricInductionMotor && InvertersRatio > 0.0) - { - FT_factor = 1.0 / InvertersRatio; - FTrain *= FT_factor; - } - - Fb = BrakeForce(RunningTrack); - // poslizg - auto Fwheels{FTrain - Fb * Sign(V)}; - if (Vel > 0.1 // crude trap, to prevent braked stationary vehicles from passing fb > mass * adhesive test - && std::abs(Fwheels) > TotalMassxg * Adhesive(RunningTrack.friction)) - { - SlippingWheels = true; - } - if (true == SlippingWheels && Vel < 0.1 // the same crude trap: (nearly) stopped vehicle... - && std::abs(nrot * M_PI * WheelDiameter - V) < 0.1 / 3.6) // ...with wheels turning at its speed, i.e. locked wheels at the end of a skid - { - // locked wheels never pass the rotation speed test below once the vehicle stops, and a skidding vehicle - // keeps its braking force capped by the sliding adhesion, so the rest of the consist could push it around - SlippingWheels = false; - nrot = V / M_PI / WheelDiameter; - } - double temp_nrot = nrot; - if (true == SlippingWheels) - { - - temp_nrot = ComputeRotatingWheel(Fwheels - Sign(nrot * M_PI * WheelDiameter - V) * Adhesive(RunningTrack.friction) * TotalMassxg, dt, nrot); - if (Sign(nrot * M_PI * WheelDiameter - V) * Sign(temp_nrot * M_PI * WheelDiameter - V) < 0) - { - SlippingWheels = false; - temp_nrot = V / M_PI / WheelDiameter; - } - } - if (true == SlippingWheels) - { - Fwheels = Sign(temp_nrot * M_PI * WheelDiameter - V) * TotalMassxg * Adhesive(RunningTrack.friction); - if (Fwheels * Sign(V) > 0) - { - FTrain = Fwheels + Fb * Sign(V); - } - else if (FTrain * Sign(V) > 0) - { - Fb = FTrain * Sign(V) - Fwheels * Sign(V); - } - else - { - double factor = FTrain - Fb * Sign(V) != 0 ? Fwheels / (FTrain - Fb * Sign(V)) : 1.0; - Fb *= factor; - FTrain *= factor; - } - if (std::abs(nrot) < 0.1) - { - WheelFlat = sqrt(square(WheelFlat) + abs(Fwheels) / NAxles * Vel * 0.000002); - } - - nrot = temp_nrot; - } - nrot_eps = (abs(nrot) - old_nrot) / dt; - // doliczenie sił z innych pojazdów - for (int end = end::front; end <= end::rear; ++end) - { - // a new step: the hit of the pair not taken by either vehicle yet - Couplers[end].hit_handled = false; - Couplers[end].hit_force = 0.0; - Couplers[end].hit_duration = 0.0; - Couplers[end].closing = 0.0; - if (Neighbours[end].vehicle != nullptr) - { - // the velocities before the step, the forces of all the vehicles come before their movement - Couplers[end].closing = -CouplerVelocityDifference(end, *Neighbours[end].vehicle->MoverParameters, Neighbours[end].vehicle_end) * DirF(end); - Couplers[end].CForce = CouplerForce(end, dt); - FTrain += Couplers[end].CForce; - // what the buffers of the pair take in, for the budget of the crush (physics.collisions new and monitor) - auto &coupler{Couplers[end]}; - coupler.contact.update(coupler.Dist < 0.0, coupler.CheckCollision, coupler.closing, compression_at(coupler, end), std::max(0.0, -coupler.Dist), dt); - } - else - { - Couplers[end].CForce = 0; - Couplers[end].contact.reset(); - } - } - - FStand += Fb; - // doliczenie składowej stycznej grawitacji - FTrain /= FT_factor; - FTrain += TotalMassxg * RunningShape.dHtrack; - //! niejawne przypisanie zmiennej! - FTotal = FTrain - Sign(V) * FStand; -} - -double TMoverParameters::BrakeForceR(double ratio, double velocity) const -{ - double press = 0; - ratio = Hamulec->GetBrakeRatio(ratio); - if (MBPM > 2) - { - press = MaxBrakePress[1] + (MaxBrakePress[3] - MaxBrakePress[1]) * std::min(1.0, (TotalMass - Mass) / (MBPM - Mass)); - } - else - { - if (MaxBrakePress[1] > 0.1) - { - press = MaxBrakePress[LoadFlag]; - } - else - { - press = MaxBrakePress[3]; - if (DynamicBrakeType == dbrake_automatic) - ratio = ratio + (1.5 - ratio) * std::min(1.0, Vel * 0.02); - if (BrakeDelayFlag & bdelay_R && BrakeMethod % 128 != bp_Cosid && BrakeMethod % 128 != bp_D1 && BrakeMethod % 128 != bp_D2 && Power < 1) - ratio *= Hamulec->GetRapidRatio(velocity); - if (TrainType == train_type::dmu && velocity < 30.0) - { - ratio -= 0.3; - } - } - } - return BrakeForceP(press * ratio, velocity); -} - -double TMoverParameters::BrakeForceP(double press, double velocity) const -{ - double BFP = 0; - double K = ((press * P2FTrans - BrakeCylSpring) * BrakeCylMult[0] - BrakeSlckAdj) * BrakeRigEff; - K *= static_cast(BrakeCylNo) / (NAxles * std::max(1, NBpA)); - BFP = Hamulec->GetFC(velocity, K) * K * (NAxles * std::max(1, NBpA)) * 1000; - return BFP; -} - -// ************************************************************************************************* -// Q: 20160713 -// oblicza siłę na styku koła i szyny -// ************************************************************************************************* -double TMoverParameters::BrakeForce(TTrackParam const & /*Track*/) -{ - - double K{0}; - double brakeforce{0}; - - switch (LocalBrake) - { - case TLocalBrake::ManualBrake: - { - K = MaxBrakeForce * ManualBrakeRatio(); - break; - } - case TLocalBrake::HydraulicBrake: - { - K = MaxBrakeForce * LocalBrakeRatio(); - break; - } - default: - { - break; - } - } - - if (MBrake == true) - { - K = MaxBrakeForce * ManualBrakeRatio(); - } - - // the spring brake of a vehicle prepared for hauling (PulleeMode) is released by hand: no force, whatever its cylinder has - if (SpringBrake.IsReady && false == PulleeMode) - K += std::max(0.0, SpringBrake.MinForcePressure - SpringBrake.Cylinder->P()) * SpringBrake.MaxBrakeForce; - - u = (BrakePress * P2FTrans - BrakeCylSpring) * BrakeCylMult[0] - BrakeSlckAdj; - if (u * BrakeRigEff > Ntotal) // histereza na nacisku klockow - Ntotal = u * BrakeRigEff; - else - { - u = (BrakePress * P2FTrans - BrakeCylSpring) * BrakeCylMult[0] - BrakeSlckAdj; - if (u * (2.0 - BrakeRigEff) < Ntotal) // histereza na nacisku klockow - Ntotal = u * (2.0 - BrakeRigEff); - } - - auto const NBrakeAxles{NAxles}; - - if (NBrakeAxles * NBpA > 0) - { - if (Ntotal > 0) // nie luz - K += Ntotal; // w kN - K *= static_cast(BrakeCylNo) / (NBrakeAxles * static_cast(NBpA)); // w kN na os - } - if (BrakeSystem == TBrakeSystem::Pneumatic || BrakeSystem == TBrakeSystem::ElectroPneumatic) - { - u = Hamulec->GetFC(Vel, K); - UnitBrakeForce = u * K * 1000.0; // sila na jeden klocek w N - } - else - UnitBrakeForce = K * 1000.0; - // if (LocalBrake=ManualBrake)or(MBrake=true)) and (BrakePress<0.3) then - // Fb:=UnitBrakeForce*NBpA {ham. reczny dziala na jedna os} - // else //yB: to nie do konca ma sens, ponieważ ręczny w wagonie działa na jeden cylinder - // hamulcowy/wózek, dlatego potrzebne są oddzielnie liczone osie - brakeforce = UnitBrakeForce * NBrakeAxles * std::max(1, NBpA); - - // u:=((BrakePress*P2FTrans)-BrakeCylSpring*BrakeCylMult[BCMFlag]/BrakeCylNo-0.83*BrakeSlckAdj/(BrakeCylNo))*BrakeCylNo; - // { end; } - return brakeforce; -} - -// ************************************************************************************************* -// Q: 20160713 -// Obliczanie siły tarcia -// ************************************************************************************************* -double TMoverParameters::FrictionForce() const -{ - double FF = 0; - // ABu 240205: chyba juz ekstremalnie zoptymalizowana funkcja liczaca sily tarcia - if (abs(V) > 0.01) - FF = FrictConst1 * V * V + FrictConst2d; - else - FF = FrictConst1 * V * V + FrictConst2s; - return FF; -} - -// ************************************************************************************************* -// Q: 20160713 -// Oblicza przyczepność -// ************************************************************************************************* -double TMoverParameters::Adhesive(double staticfriction) const -{ - double adhesion = 0.0; - const double adh_factor = 0.25; // współczynnik określający, jak bardzo spada tarcie przy poślizgu - const double slipfactor = 0.33; // współczynnik określający, jak szybko spada tarcie przy poślizgu - const double sandfactor = 1.25; // współczynnik określający, jak mocno pomaga piasek - /* - // ABu: male przerobki, tylko czy to da jakikolwiek skutek w FPS? - // w kazdym razie zaciemni kod na pewno :) - if (SlippingWheels == false) - { - if (SandDose) - adhesion = (std::max(staticfriction * (100.0 + Vel) / ((50.0 + Vel) * 11.0), 0.048)) * - (11.0 - 2.0 * Random(0.0, 1.0)); - else - adhesion = (staticfriction * (100.0 + Vel) / ((50.0 + Vel) * 10.0)) * - (11.0 - 2.0 * Random(0.0, 1.0)); - } - else - { - if (SandDose) - adhesion = (0.048) * (11.0 - 2.0 * Random(0.0, 1.0)); - else - adhesion = (staticfriction * 0.02) * (11.0 - 2.0 * Random(0.0, 1.0)); - } - // WriteLog(FloatToStr(adhesive)); // tutaj jest na poziomie 0.2 - 0.3 - return adhesion; - - //wersja druga - if( true == SlippingWheels ) { - - if( true == SandDose ) { adhesion = 0.48; } - else { adhesion = staticfriction * 0.2; } - } - else { - - if( true == SandDose ) { adhesion = std::max( staticfriction * ( 100.0 + Vel ) / ( 50.0 + Vel ) * 1.1, 0.48 ); } - else { adhesion = staticfriction * ( 100.0 + Vel ) / ( 50.0 + Vel ); } - } - // adhesion *= ( 0.9 + 0.2 * Random() ); - */ - // wersja3 by youBy - uwzględnia naturalne mikropoślizgi i wpływ piasecznicy, usuwa losowość z pojazdu - double Vwheels = nrot * M_PI * WheelDiameter; // predkosc liniowa koła wynikająca z obrotowej - double deltaV = V - Vwheels; // poślizg - różnica prędkości w punkcie styku koła i szyny - deltaV = std::max(0.0, std::abs(deltaV) - 0.25); // mikropoślizgi do ok. 0,25 m/s nie zrywają przyczepności - Vwheels = std::abs(Vwheels); - adhesion = staticfriction * (28 + Vwheels) / (14 + Vwheels) * ((SandDose ? sandfactor : 1) - (1 - adh_factor) * (deltaV / (deltaV + slipfactor))); - - return adhesion; -} - -// ************************************************************************************************* -// Q: 20160713 -// Obliczanie sił dzialających na sprzęgach -// ************************************************************************************************* -double TMoverParameters::CouplerForce(int const End, double dt) -{ - if (coupler_physics_at(End)) - { - return coupler_force_physical(End, dt); - } - - auto &thiscoupler{Couplers[End]}; - auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; - auto const otherend{Neighbours[End].vehicle_end}; - auto const &othercoupler{othervehicle->Couplers[otherend]}; - - auto const othervehiclemove{(othervehicle->dMoveLen * DirPatch(End, otherend))}; - auto const initialdistance{Neighbours[End].distance}; // odległość od sprzęgu sąsiada - auto const distancedelta{(End == end::front ? othervehiclemove - dMoveLen : dMoveLen - othervehiclemove)}; - - // the ends crushed for good (physics.collisions new, see collision.h) let the buffers meet that much closer - auto const crushed{thiscoupler.crush + othercoupler.crush}; - auto const rawdistance{initialdistance + 10.0 * distancedelta}; - auto const newdistance{rawdistance < 0.0 ? std::min(0.0, rawdistance + crushed) : rawdistance}; - - auto const dV{CouplerVelocityDifference(End, *othervehicle, otherend)}; - auto const absdV{std::abs(dV)}; - - // potentially generate sounds on clash or stretch - if (newdistance < 0.0 && thiscoupler.Dist > newdistance && dV < -0.1 && false == thiscoupler.has_adapter()) - { // HACK: with adapter present we presume buffers won't clash - // 090503: dzwieki pracy zderzakow - SetFlag(thiscoupler.sounds, absdV > 5.0 ? sound::bufferclash | sound::loud : sound::bufferclash); - } - else if (thiscoupler.CouplingFlag != coupling::faux && newdistance > 0.001 && thiscoupler.Dist <= 0.001 && absdV > 0.005 && Vel > 1.0) - { - // 090503: dzwieki pracy sprzegu - SetFlag(thiscoupler.sounds, absdV > 0.035 ? sound::couplerstretch | sound::loud : sound::couplerstretch); - } - - thiscoupler.CheckCollision = false; - thiscoupler.Dist = 0.0; - - double CF{0.0}; - - if (thiscoupler.CouplingFlag == coupling::faux && initialdistance > 0.05) - { // arbitrary distance - // potentially reset auto coupling lock - thiscoupler.AutomaticCouplingAllowed = true; - } - - if (thiscoupler.CouplingFlag != coupling::faux || initialdistance < 0) - { - - thiscoupler.Dist = safe_clamp(newdistance, thiscoupler.has_adapter() ? 0 : -thiscoupler.DmaxB, thiscoupler.DmaxC); - - double BetaAvg = 0; - double Fmax = 0; - - if (thiscoupler.CouplingFlag == coupling::faux) - { - - BetaAvg = thiscoupler.beta; - Fmax = (thiscoupler.FmaxC + thiscoupler.FmaxB) * CouplerTune; - } - else - { - // usrednij bo wspolny sprzeg - BetaAvg = 0.5 * (thiscoupler.beta + othercoupler.beta); - Fmax = 0.5 * (thiscoupler.FmaxC + thiscoupler.FmaxB + othercoupler.FmaxC + othercoupler.FmaxB) * CouplerTune; - } - auto const distDelta{std::abs(newdistance) - std::abs(thiscoupler.Dist)}; // McZapkie-191103: poprawka na histereze - - if (newdistance > 0) - { - - if (distDelta > 0) - { - CF = -(thiscoupler.SpringKC + othercoupler.SpringKC) * thiscoupler.Dist / 2.0 * DirF(End) - Fmax * dV * BetaAvg; - } - else - { - CF = -(thiscoupler.SpringKC + othercoupler.SpringKC) * thiscoupler.Dist / 2.0 * DirF(End) * BetaAvg - Fmax * dV * BetaAvg; - } - // liczenie sily ze sprezystosci sprzegu - if (newdistance > thiscoupler.DmaxC + othercoupler.DmaxC) - { - // zderzenie - thiscoupler.CheckCollision = true; - } - CouplerStretchCheck(End, CF, dt); - } - if (newdistance < 0) - { - - if (distDelta > 0) - { - CF = -(thiscoupler.SpringKB + othercoupler.SpringKB) * thiscoupler.Dist / 2.0 * DirF(End) - Fmax * dV * BetaAvg; - } - else - { - CF = -(thiscoupler.SpringKB + othercoupler.SpringKB) * thiscoupler.Dist / 2.0 * DirF(End) * BetaAvg - Fmax * dV * BetaAvg; - } - // liczenie sily ze sprezystosci zderzaka - auto const collisiondistance{(thiscoupler.has_adapter() || othercoupler.has_adapter() ? - std::min(thiscoupler.DmaxB, othercoupler.DmaxB) : // HACK: only take into account buffering ability of automatic coupler - thiscoupler.DmaxB + othercoupler.DmaxB)}; - if (-newdistance > collisiondistance) - { - // zderzenie - thiscoupler.CheckCollision = true; - } - if (-newdistance >= std::min(collisiondistance, dEpsilon)) - { - automatic_coupling(End, *othervehicle, otherend); - } - } - } - - if (thiscoupler.CouplingFlag != coupling::faux) - { - // uzgadnianie prawa Newtona, on the coupler of the other vehicle this one is coupled with, along that vehicle's - // axis: turned around once more when the vehicles face each other - othervehicle->Couplers[otherend].CForce = -CF * DirPatch(End, otherend); - } - - return CF; -} - -// a coupler stretched with more than its strength for over a second breaks, the more likely the longer, with crash damage on -void TMoverParameters::CouplerStretchCheck(int const End, double const CF, double dt) -{ - auto &thiscoupler{Couplers[End]}; - if (std::abs(CF) > thiscoupler.FmaxC) - { - // coupler is stretched with excessive force, may break - thiscoupler.stretch_duration += static_cast(dt); - // give coupler 1 sec of leeway to account for simulation glitches, before checking whether it breaks - // (arbitrary) chance to break grows from 10-100% over 10 sec period - if (Global.crash_damage && thiscoupler.stretch_duration > 1.f && Random() < thiscoupler.stretch_duration * 0.1f * dt) - { - damage_coupler(End); - } - } - else - { - thiscoupler.stretch_duration = 0.f; - } -} - -bool TMoverParameters::coupler_physics_at(int const End) const -{ - if (false == Global.coupler_physics) - { - return false; - } - if (Global.coupler_physics_all || CouplerPhysics) - { - return true; - } - // either vehicle of the pair covered takes the pair in, so both of them compute it the same way - auto const *other{Neighbours[End].vehicle}; - return other != nullptr && other->MoverParameters->CouplerPhysics; -} - -void TMoverParameters::automatic_coupling(int const End, TMoverParameters &Other, int const OtherEnd) -{ - auto &thiscoupler{Couplers[End]}; - auto &othercoupler{Other.Couplers[OtherEnd]}; - - if (thiscoupler.type() != TCouplerType::Automatic || thiscoupler.type() != othercoupler.type() || thiscoupler.CouplingFlag != coupling::faux || false == thiscoupler.AutomaticCouplingAllowed || - false == othercoupler.AutomaticCouplingAllowed) - { - return; - } - // a coupler torn off by the crush of its end (physics.collisions new) doesn't catch - if (Global.collisions == global_settings::collision_model::physical && (thiscoupler.broken || othercoupler.broken)) - { - return; - } - // sprzeganie wagonow z samoczynnymi sprzegami - auto couplingtype{thiscoupler.AutomaticCouplingFlag & othercoupler.AutomaticCouplingFlag}; - // potentially exclude incompatible control coupling - if (thiscoupler.control_type != othercoupler.control_type) - { - couplingtype &= ~coupling::control; - } - couplingtype = CompatibleCoupling(End, Other, OtherEnd, couplingtype); - - // too fast for the couplers to catch, the vehicles collide instead (and may derail, see CollisionDetect()) - auto const safe{AutomaticCouplingSafe(End, Other, OtherEnd)}; - auto const caught{safe && Attach(End, OtherEnd, &Other, couplingtype)}; - // HACK: we're reusing sound enum to mark whether vehicle was connected to another - AIFlag |= (caught ? sound::attachcoupler : 0); - // coupled, or locked until the vehicles part, so they don't couple as soon as the collision slows them down - thiscoupler.AutomaticCouplingAllowed = safe && false == caught; - othercoupler.AutomaticCouplingAllowed = safe && false == caught; -} - -namespace -{ - -// the gap between the ends of a coupled pair, taking up the play of the coupling, opens up enough to jerk the train -constexpr double coupler_stretch_threshold{0.001}; - -// the sounds of the buffers hitting each other, and of the coupling taking up its play -struct coupler_sound_input -{ - double gap{0.0}; // between the ends [m] - double previous_gap{0.0}; - double gap_rate{0.0}; // [m/s] - double draw_gear{0.0}; // deflection [m] - double previous_draw_gear{0.0}; - bool coupled{false}; - bool adapter{false}; - bool moving{false}; -}; - -int coupler_sounds(coupler_sound_input const &Input) -{ - if (Input.gap < 0.0 && Input.gap < Input.previous_gap && Input.gap_rate < -0.1 && false == Input.adapter) - { - // 090503: dzwieki pracy zderzakow - return std::abs(Input.gap_rate) > 5.0 ? sound::bufferclash | sound::loud : sound::bufferclash; - } - if (Input.coupled && Input.moving && Input.draw_gear > coupler_stretch_threshold && Input.previous_draw_gear <= coupler_stretch_threshold && std::abs(Input.gap_rate) > 0.005) - { - // 090503: dzwieki pracy sprzegu - return std::abs(Input.gap_rate) > 0.035 ? sound::couplerstretch | sound::loud : sound::couplerstretch; - } - return sound::none; -} - -} // namespace - -double TMoverParameters::coupler_force_physical(int const End, double const dt) -{ - auto &thiscoupler{Couplers[End]}; - auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; - auto const otherend{Neighbours[End].vehicle_end}; - auto &othercoupler{othervehicle->Couplers[otherend]}; - auto &state{thiscoupler.physics_state}; - - // the gap as it is now: the distance found at the start of the frame, and the movement of both vehicles since - auto const othervehiclemove{othervehicle->dMoveLen * DirPatch(End, otherend)}; - auto const gap{Neighbours[End].distance + (End == end::front ? othervehiclemove - dMoveLen : dMoveLen - othervehiclemove)}; - // the gap opens up when the front end falls behind the vehicle ahead of it, or the rear end runs ahead of the one behind - auto const gaprate{CouplerVelocityDifference(End, *othervehicle, otherend) * DirF(End)}; - auto const coupled{thiscoupler.CouplingFlag != coupling::faux}; - auto const adapter{thiscoupler.has_adapter() || othercoupler.has_adapter()}; - - if (false == coupled && Neighbours[End].distance > 0.05) - { // arbitrary distance - // potentially reset auto coupling lock - thiscoupler.AutomaticCouplingAllowed = true; - } - - auto const previousgap{state.gap}; - auto const previousdrawgear{state.draw_gear.deflection}; - auto const result{coupler_physics::update_pair(thiscoupler.physics, othercoupler.physics, state, {gap, gaprate, coupled, adapter, Global.crash_damage, thiscoupler.crush + othercoupler.crush})}; - - SetFlag(thiscoupler.sounds, coupler_sounds({gap, previousgap, gaprate, state.draw_gear.deflection, previousdrawgear, coupled, adapter, Vel > 1.0})); - - thiscoupler.CheckCollision = state.stop != 0; - // for the buffers drawn pressed in, see TDynamicObject: twice the deflection of the buffers of this end - thiscoupler.Dist = result.compression > 0.0 ? -2.0 * result.buffers_deflection : std::max(gap, 0.0); - // the link pulled past its yield force, which the AI drivers ease off on - thiscoupler.stretch_duration = result.overloaded ? thiscoupler.stretch_duration + static_cast(dt) : 0.f; - - if (result.broken) - { - damage_coupler(End); - } - if (false == coupled && gap < 0.0) - { - auto const collisiondistance{adapter ? std::min(thiscoupler.DmaxB, othercoupler.DmaxB) : thiscoupler.DmaxB + othercoupler.DmaxB}; - if (-gap >= std::min(collisiondistance, dEpsilon)) - { - automatic_coupling(End, *othervehicle, otherend); - } - } - - // tension pulls this vehicle towards the other one - auto const force{result.force * -DirF(End)}; - if (thiscoupler.CouplingFlag != coupling::faux) - { - // uzgadnianie prawa Newtona, as in CouplerForce() - othercoupler.CForce = -force * DirPatch(End, otherend); - } - return force; -} - -bool TMoverParameters::coupler_stop_hit(int const End, TMoverParameters &Other, int const OtherEnd) -{ - auto &thiscoupler{Couplers[End]}; - auto &othercoupler{Other.Couplers[OtherEnd]}; - auto &state{thiscoupler.physics_state}; - - // the draw gear went solid with the gap opening up, the buffers with it closing - auto const gaprate{CouplerVelocityDifference(End, Other, OtherEnd) * DirF(End)}; - auto const closing{state.stop > 0 ? gaprate : -gaprate}; - if (state.stop == 0 || closing <= 0.0) - { - // parting from the stop already, after the hit on the other vehicle's end - return false; - } - if (false == Global.crash_damage) - { - return true; - } - auto const hit{coupler_physics::impact(thiscoupler.physics, othercoupler.physics, state, closing, TotalMass, Other.TotalMass)}; - // the other vehicle keeps the state of the pair alike - othercoupler.physics_state.elongation = state.elongation; - // with physics.collisions new the crush of the ends past the buffers is crush_hit()'s - if (hit.broken || (hit.crushed && Global.collisions != global_settings::collision_model::physical)) - { - damage_coupler(End); - } - // a broken coupling lets the vehicles part - return false == hit.broken; -} - -// ************************************************************************************************* -// Q: 20160714 -// oblicza sile trakcyjna lokomotywy (dla elektrowozu tez calkowity prad) -// ************************************************************************************************* -double TMoverParameters::TractionForce(double dt) -{ - using enum TEngineType; - Ft = 0; - double dtrans{0.0}; - double dmoment{0.0}; - auto const revolutions{UpdateEngineRevolutions(dt, dtrans, dmoment)}; - - eAngle += enrot * dt; - if (eAngle > M_PI * 2.0) - eAngle = std::fmod(eAngle, M_PI * 2.0); - /* - while (eAngle > M_PI * 2.0) - // eAngle = Pirazy2 - eAngle; <- ABu: a nie czasem tak, jak nizej? - eAngle -= M_PI * 2.0; - */ - // hunter-091012: przeniesione z if DirActive<>0 (zeby po zejsciu z kierunku dalej spadala predkosc wentylatorow) - // wentylatory rozruchowe - // TBD, TODO: move this to update, it doesn't exactly have much to do with traction - UpdateVentilators(dt); - auto const PosRatio{UpdateEnginePower()}; - VoltageRelaysCheck(); - - if (EngineType == DieselElectric && DEDynamicBrake.source != diesel_electric_dynamic_brake::control::none) - { - update_dieselelectric_dynamic_brake(dt); - } - - if (DirActive != 0) - switch (EngineType) - { - case Dumb: - { - DumbTractionForce(PosRatio); - break; - } - case WheelsDriven: - { - WheelsDrivenTractionForce(dt); - break; - } - case ElectricSeriesMotor: - { - SeriesMotorTractionForce(dt); - break; - } - case DieselEngine: - { - DieselEngineTractionForce(dt, dmoment, dtrans); - break; - } - case DieselElectric: // youBy - { - DieselElectricTractionForce(revolutions); - if (DEDynamicBrake.level > 0.0) - { - // braking: no power asked for, so the drive above gave no force - apply_dieselelectric_dynamic_brake(dt); - } - break; - } - case ElectricInductionMotor: - { - InductionMotorTractionForce(dt); - break; - } - case None: - default: - { - break; - } - } // case EngineType - - if (EngineType == DieselElectric) - { - // rough approximation of extra effort to overcome friction etc - EnginePower += EngineRPMRatio() * 0.15 * DElist[MainCtrlPosNo].GenPower; - } - - return Ft; -} - -// the revolutions of the engine; returns those a diesel-electric engine aims at [1/s], 0 for the others. -// for a diesel engine, the ratio of the transmission and the engine's moment -double TMoverParameters::UpdateEngineRevolutions(double dt, double &dtrans, double &dmoment) -{ - double tmp{0.0}; - // youBy - switch (EngineType) - { - case TEngineType::DieselElectric: - { - if (true == Mains && true == FuelPump.is_active) - { - tmp = DieselElectricTargetRevolutions(); - } - else - { - tmp = 0.0; - dizel_fill = 0.0; - } - - if (enrot != tmp) - { - enrot = safe_clamp(enrot + dt / dizel_AIM * (enrot < tmp ? 1.0 : -1.0 * dizel_RevolutionsDecreaseRate), // NOTE: revolutions typically drop faster than they rise - 0.0, std::max(tmp, enrot)); - if (std::abs(tmp - enrot) < 0.001) - { - enrot = tmp; - } - } - break; - } - case TEngineType::DieselEngine: - { - if (ShuntMode) // dodatkowa przekładnia np. dla 2Ls150 - dtrans = AnPos * Transmision.Ratio * motor_param(ScndCtrlActualPos).mIsat; - else - dtrans = Transmision.Ratio * motor_param(ScndCtrlActualPos).mIsat; - - dmoment = dizel_Momentum(dizel_fill, dtrans * nrot * DirActive, dt); // oblicza tez enrot - break; - } - default: - { - enrot = Transmision.Ratio * nrot; - break; - } - } - - return tmp; -} - -// the revolutions a diesel-electric's engine aims at [1/s], by the controller and the heating; the fill shown by the smoke -double TMoverParameters::DieselElectricTargetRevolutions() -{ - double tmp; - - if (EIMCtrlType > 0) // sterowanie cyfrowe - tmp = (DElist[0].RPM + (DElist[MainCtrlPosNo].RPM - DElist[0].RPM) * std::max(0.0, eimic_real)) / 60.0; - else - tmp = DElist[ControlPressureSwitch ? MainCtrlNoPowerPos() : MainCtrlPos].RPM / 60.0; - - if (true == HeatingAllow && HeatingPower > 0 && EngineHeatingRPM > 0) - { - // bump engine revolutions up if needed, when heating is on - tmp = std::max(tmp, std::min(EngineMaxRPM(), EngineHeatingRPM) / 60.0); - } - // NOTE: fake dizel_fill calculation for the sake of smoke emitter which uses this parameter to determine smoke opacity - dizel_fill = std::clamp(0.2 + 0.35 * (tmp - enrot) + 0.5 * (std::abs(Im) / DElist[MainCtrlPosNo].Imax), 0.05, 1.0); - return tmp; -} - -// the starting resistors' blowers, and the diesels' radiator fans -void TMoverParameters::UpdateVentilators(double dt) -{ - switch (EngineType) - { - - case TEngineType::ElectricSeriesMotor: - { - if (MainCircuitPowered()) - { - UpdateResistorBlowers(dt); - } // mains - else - { - RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); - } - break; - } - - case TEngineType::DieselElectric: - { - // NOTE: for this type RventRot is the speed of motor blowers; we also update radiator fans while at it - if (true == Mains) - { - // TBD, TODO: currently ignores RVentType, fix this? - RventRot += std::clamp(enrot - RventRot, -100.0, 50.0) * dt; - dizel_heat.rpmw += static_cast(std::clamp(dizel_heat.rpmwz - dizel_heat.rpmw, -100.f, 50.f) * dt); - dizel_heat.rpmw2 += static_cast(std::clamp(dizel_heat.rpmwz2 - dizel_heat.rpmw2, -100.f, 50.f) * dt); - } - else - { - RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); - dizel_heat.rpmw *= static_cast(std::max(0.0, 1.0 - dizel_heat.rpmw * dt)); - dizel_heat.rpmw2 *= static_cast(std::max(0.0, 1.0 - dizel_heat.rpmw2 * dt)); - } - break; - } - - case TEngineType::DieselEngine: - { - // NOTE: we update only radiator fans, as vehicles with diesel engine don't have other ventilators - if (true == Mains) - { - dizel_heat.rpmw += static_cast(std::clamp(dizel_heat.rpmwz - dizel_heat.rpmw, -100.f, 50.f) * dt); - dizel_heat.rpmw2 += static_cast(std::clamp(dizel_heat.rpmwz2 - dizel_heat.rpmw2, -100.f, 50.f) * dt); - } - else - { - dizel_heat.rpmw *= static_cast(std::max(0.0, 1.0 - dizel_heat.rpmw * dt)); - dizel_heat.rpmw2 *= static_cast(std::max(0.0, 1.0 - dizel_heat.rpmw2 * dt)); - } - break; - } - - default: - { - break; - } - } -} - -// the starting resistors' blowers of the series motors with the line breaker closed, worked by hand or by the current -void TMoverParameters::UpdateResistorBlowers(double dt) -{ - switch (RVentType) - { - - case 1: - { // manual - if (true == RVentForceOn || (DirActive != 0 && RList[MainCtrlActualPos].R > RVentCutOff)) - { - RventRot += (RVentnmax - RventRot) * RVentSpeed * dt; - } - else - { - RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); - } - break; - } - - case 2: - { // automatic - auto const motorcurrent{std::min(ImaxHi, std::abs(Im))}; - if (std::abs(Itot) > RVentMinI && RList[MainCtrlActualPos].R > RVentCutOff) - { - - RventRot += (RVentnmax * std::min(1.0, motorcurrent / NPoweredAxles / RVentMinI) * motorcurrent / ImaxLo - RventRot) * RVentSpeed * dt; - } - else if (DynamicBrakeType == dbrake_automatic && true == DynamicBrakeFlag) - { - RventRot += (RVentnmax * motorcurrent / ImaxLo - RventRot) * RVentSpeed * dt; - } - else if (RVentForceOn) - { - RventRot += (RVentnmax - RventRot) * RVentSpeed * dt; - } - else - { - RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); - } - break; - } - - default: - { - break; - } - } // rventtype -} - -// the power of a dumb or diesel engine; returns the ratio of the power a dumb engine is set to -double TMoverParameters::UpdateEnginePower() -{ - double PosRatio{0.0}; - switch (EngineType) - { - case TEngineType::Dumb: - { - PosRatio = (MainCtrlPos + ScndCtrlPos) / (MainCtrlPosNo + ScndCtrlPosNo + 0.01); - EnginePower = /*1000.0 **/ Power * PosRatio; - break; - } - case TEngineType::DieselEngine: - { - dizel_Power = Mm * enrot * (2.0 * M_PI / 1000.0); - EnginePower = (dizel_Mstand + Mm) * enrot * (2.0 * M_PI / 1000.0); - if (MainCtrlPowerPos() > 1) - { - // dodatkowe opory z powodu sprezarki} - // dmoment -= dizel_Mstand * ( 0.2 * enrot / dizel_nmax ); //yB: skąd to w ogóle się bierze?! - } - break; - } - case TEngineType::DieselElectric: - { - EnginePower = 0; // the actual calculation is done in two steps later in the method - break; - } - default: - { - break; - } - } - - return PosRatio; -} - -// the line breaker opened by a voltage out of the motors' range, and the line contactors of a diesel-electric -void TMoverParameters::VoltageRelaysCheck() -{ - switch (EngineType) - { - - case TEngineType::ElectricSeriesMotor: - { - // update the state of voltage relays - auto const voltage{std::max(GetTrainsetHighVoltage(), PantographVoltage)}; - // where the line breaker holds without voltage (closed ahead of the pantographs) the undervoltage relay opens the - // line contactors instead, see MotorConnectorsCheck(). it picks up again only with the master controller back - // where a start begins, as the line breaker it stands in for wouldn't close on a running position either: at - // zero, or at the first position, which is the first resistance step, where the line contactors close on any - // start, and where the AI waits for them rather than going back to zero - auto const novoltrelaypicksup{false == PantographsRequireMains || NoVoltRelay || MainCtrlPowerPos() <= 1}; - NoVoltRelay = EnginePowerSource.SourceType != TPowerSource::CurrentCollector || (voltage >= EnginePowerSource.CollectorParameters.MinV && novoltrelaypicksup); - OvervoltageRelay = - EnginePowerSource.SourceType != TPowerSource::CurrentCollector || voltage <= EnginePowerSource.CollectorParameters.MaxV || false == EnginePowerSource.CollectorParameters.OVP; - // wywalanie szybkiego z powodu niewłaściwego napięcia - // (a line breaker closed ahead of the pantographs holds without voltage) - EventFlag |= true == Mains && ((false == NoVoltRelay && false == PantographsRequireMains) || false == OvervoltageRelay) && - MainSwitch(false, TrainType == train_type::emu ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide - break; - } - - case TEngineType::ElectricInductionMotor: - { - // TODO: check if we can use instead the code for electricseriesmotor - // nie wchodzić w funkcję bez potrzeby - // (a line breaker closed ahead of the pantographs holds without voltage) - // (the source by the traction selector of a dual-mode vehicle: the pantographs or the genset) - if (Mains && ((TractionSupplyVoltage() < TractionSupplyMinVoltage() && false == PantographsRequireMains) || - TractionSupplyVoltage() > EnginePowerSource.CollectorParameters.MaxV + 200)) - { - MainSwitch(false, TrainType == train_type::emu ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide - } - break; - } - - case TEngineType::DieselElectric: - { - // TODO: move this to the auto relay check when the electric engine code paths are unified - StLinFlag |= Mains && false == StLinFlag && MainCtrlPowerPos() == 1; - StLinFlag &= MotorConnectorsCheck(); - StLinFlag &= MainCtrlPowerPos() > 0; - - break; - } - - default: - { - break; - } - } -} - -void TMoverParameters::DumbTractionForce(double const PosRatio) -{ - if (Mains && CabActive != 0) - { - if (Vel > 0.1) - { - Ft = std::min(1000.0 * Power / std::abs(V), Ftmax) * PosRatio; - } - else - { - Ft = Ftmax * PosRatio; - } - Ft = Ft * DirAbsolute; // DirActive*CabActive; - } - else - { - Ft = 0; - } -} - -void TMoverParameters::WheelsDrivenTractionForce(double dt) -{ - if (EnginePowerSource.SourceType == TPowerSource::InternalSource && EnginePowerSource.PowerType == TPowerType::BioPower) - Ft = Sign(sin(eAngle)) * PulseForce * Transmision.Ratio; - PulseForceTimer = PulseForceTimer + dt; - if (PulseForceTimer > CtrlDelay) - { - PulseForce = 0; - if (PulseForceCount > 0) - PulseForceCount--; - } - EnginePower = Ft * (1.0 + Vel); -} - -void TMoverParameters::SeriesMotorTractionForce(double dt) -{ - // enrot:=Transmision.Ratio*nrot; - // yB: szereg dwoch sekcji w ET42 - if (TrainType == train_type::et42 && Imax == ImaxHi) - EngineVoltage = EngineVoltage / 2.0; - Mm = Momentum(Current(enrot, EngineVoltage)); // oblicza tez prad p/slinik - - if (TrainType == train_type::et42) - { - if (Imax == ImaxHi) - EngineVoltage = EngineVoltage * 2; - if (DynamicBrakeFlag && abs(Im) > 300) // przeiesione do mover.cpp - FuseOff(); - } - if (DynamicBrakeType == dbrake_automatic && DynamicBrakeFlag) - { - SeriesMotorDynamicBrake(dt); - } - - if (TrainType == train_type::et22 && DelayCtrlFlag) // szarpanie przy zmianie układu w byku - Mm = Mm * RList[MainCtrlActualPos].Bn / (RList[MainCtrlActualPos].Bn + 1); // zrobione w momencie, żeby nie dawac elektryki w przeliczaniu sił - - if (abs(Im) > Imax) - Vhyp += dt; //*(abs(Im) / Imax - 0.9) * 10; // zwieksz czas oddzialywania na PN - else - Vhyp = 0; - if (Vhyp > CtrlDelay / 2) // jesli czas oddzialywania przekroczony - FuseOff(); // wywalanie bezpiecznika z powodu przetezenia silnikow - - if ((DynamicBrakeType == dbrake_automatic || DynamicBrakeType == dbrake_switch) && DynamicBrakeFlag) - Itot = Im * 2; // 2x2 silniki w EP09 - else if (TrainType == train_type::emu && Imin == IminLo && ScndS) // yBARC - boczniki na szeregu poprawnie - Itot = Im; - else - Itot = Im * RList[MainCtrlActualPos].Bn; // prad silnika * ilosc galezi - Mw = Mm * Transmision.Ratio * Transmision.Efficiency; - Fw = Mw * 2.0 / WheelDiameter; - Ft = Fw * NPoweredAxles; // sila trakcyjna -} - -// the automatic dynamic brake of the series motors: the excitation current, by the stages of the ep brake (TUHEX) -void TMoverParameters::SeriesMotorDynamicBrake(double dt) -{ - if (TUHEX_Stages > 0) // hamowanie wielostopniowe, nadpisuje wartości domyślne - { - if (Vel > 100) - TUHEX_StageActual = std::min(TUHEX_StageActual, 1); - switch (TUHEX_StageActual) - { - case 1: - TUHEX_Sum = TUHEX_Sum1; - DynamicBrakeRes = DynamicBrakeRes1; - break; - case 2: - TUHEX_Sum = TUHEX_Sum2; - DynamicBrakeRes = DynamicBrakeRes1; - break; - case 3: - TUHEX_Sum = TUHEX_Sum3; - if (Vadd > 0.99 * TUHEX_MaxIw && DynamicBrakeRes == DynamicBrakeRes1) - TUHEX_ResChange = true; - if (TUHEX_ResChange && Vadd < 0.5 * TUHEX_MaxIw) - { - TUHEX_ResChange = false; - DynamicBrakeRes = DynamicBrakeRes2; - } - break; - default: - DynamicBrakeRes = DynamicBrakeRes1; - TUHEX_Sum = 0; - break; - } - } - if (Vadd + abs(Im) > TUHEX_Sum + TUHEX_Diff || Hamulec->GetEDBCP() < 0.25 || TUHEX_ResChange || (TUHEX_StageActual == 0 && TUHEX_Stages > 0)) - { - Vadd -= 500.0 * dt; - if (Vadd < TUHEX_MinIw) - { - Vadd = 0; - DynamicBrakeFlag = false; - } - } - else if (DynamicBrakeFlag && Vadd + abs(Im) < TUHEX_Sum - TUHEX_Diff) - { - Vadd += 70.0 * dt; - Vadd = std::min(std::max(Vadd, TUHEX_MinIw), TUHEX_MaxIw); - } - if (Vadd > 0) - Mm = MomentumF(Im, Vadd, 0); -} - -void TMoverParameters::DieselEngineTractionForce(double dt, double const dmoment, double const dtrans) -{ - Mw = dmoment * dtrans * Transmision.Efficiency; // dmoment i dtrans policzone przy okazji enginerotation - if (hydro_R && hydro_R_Placement == 0) - Mw -= dizel_MomentumRetarder(nrot * Transmision.Ratio, dt) * Transmision.Ratio * Transmision.Efficiency; - Fw = Mw * 2.0 / WheelDiameter / NPoweredAxles; - Ft = Fw * NPoweredAxles; // sila trakcyjna - Ft = Ft * DirAbsolute; // DirActive*CabActive; -} - -// tmp: the revolutions the engine aims at [1/s], see UpdateEngineRevolutions() -void TMoverParameters::DieselElectricTractionForce(double tmp) -{ - double PosRatio; - // tmpV:=V*CabActive*DirActive; - auto const tmpV{nrot * Pirazy2 * 0.5 * WheelDiameter * DirAbsolute}; //*CabActive*DirActive; - auto tempUmax = 0.0; - auto tempImax = 0.0; - // jazda manewrowa - if (EIMCtrlType > 0) // sterowanie cyfrowe - { - tmp = DieselElectricDigitalForce(tmpV, tempUmax, tempImax); - PosRatio = tmp / DElist[MainCtrlPosNo].GenPower; - } - else if (true == ShuntMode) - { - DieselElectricShuntForce(tmpV, tmp); - PosRatio = 1; - } - else // jazda ciapongowa - { - auto power = Power; - tempImax = DElist[MainCtrlPos].Imax; - tempUmax = DElist[MainCtrlPos].Umax; - if (true == Heating) - { - power -= HeatingPower; - } - power = std::max(power, 0.0); - // NOTE: very crude way to approximate power generated at current rpm instead of instant top output - // NOTE, TODO: doesn't take into account potentially increased revolutions if heating is on, fix it - auto const currentgenpower{(DElist[MainCtrlPos].RPM > 0 ? DElist[MainCtrlPos].GenPower * (60.0 * enrot / DElist[MainCtrlPos].RPM) : 0.0)}; - - tmp = std::min(power, currentgenpower); - - PosRatio = currentgenpower / DElist[MainCtrlPosNo].GenPower; - // stosunek mocy teraz do mocy max - // NOTE: Mains in this context is working diesel engine - if (true == StLinFlag) - Ft = DieselElectricForce(tmpV, power, PosRatio, tmp); - else - Ft = 0; // jak nastawnik na zero, to sila tez zero - - PosRatio = tmp / DElist[MainCtrlPosNo].GenPower; - } - - if (FuseFlag) - Ft = 0; - else - Ft = Ft * DirAbsolute; // DirActive * CabActive; //zwrot sily i jej wartosc - Fw = Ft / NPoweredAxles; // sila na obwodzie kola - Mw = Fw * WheelDiameter / 2.0; // moment na osi kola - Mm = Mw / Transmision.Ratio; // moment silnika trakcyjnego - - Im = dieselelectric_motor_current(Mm); - - if (ShuntMode) - { - DieselElectricShuntPower(tmp); - } - else - { - DieselElectricGenerator(tmp, tempUmax, tempImax); - } - - if (Imax > 1 && Im > Imax) - FuseOff(); - if (FuseFlag) - EngineVoltage = 0; - - // przekazniki bocznikowania, kazdy inny dla kazdej pozycji - if (auto const fieldshuntingcontrol{fieldshunting::diesel_electric(AutoRelayType, FieldShuntSwitch, AutoRelayFlag)}; - false == StLinFlag || ShuntMode || fieldshuntingcontrol == fieldshunting::control::off) - { - ScndCtrlPos = 0; - } - else if (AutoRelayFlag) - { - // the shunting relays set the field shunting (fieldshunting::control::automatic) - ShuntFieldRelaysCheck(tmpV, PosRatio, tmp); - } -} - -// the tractive force of a diesel-electric shunting, by the generator's table SST and the shunting controller AnPos; -// tmp, the power the generator gives -void TMoverParameters::DieselElectricShuntForce(double const tmpV, double &tmp) -{ - if (true == StLinFlag) - { - EngineVoltage = SST[MainCtrlPos].Umax * AnPos + SST[MainCtrlPos].Umin * (1.0 - AnPos); - // NOTE: very crude way to approximate power generated at current rpm instead of instant top output - // NOTE, TODO: doesn't take into account potentially increased revolutions if heating is on, fix it - tmp = EngineRPMRatio() * (SST[MainCtrlPos].Pmax * AnPos) + SST[MainCtrlPos].Pmin * (1.0 - AnPos); - Ft = tmp * 1000.0 / (abs(tmpV) + 1.6); - } - else - { - EngineVoltage = 0; - Ft = 0; - } -} - -// the tractive force of a diesel-electric set by the integrated controller, at the speed tmpV; the generator's -// voltage and current limits too. returns the power the generator gives -double TMoverParameters::DieselElectricDigitalForce(double const tmpV, double &tempUmax, double &tempImax) -{ - auto eimic_positive = std::max(0.0, eimic_real); - auto const rpmratio{EngineRPMRatio()}; - tempImax = DElist[MainCtrlPosNo].Imax * eimic_positive; - tempUmax = DElist[MainCtrlPosNo].Umax * std::min(eimic_positive, rpmratio); - auto const tempPmax = DElist[MainCtrlPosNo].GenPower * std::min(eimic_positive, rpmratio); - if (true == StLinFlag) - Ft = DieselElectricForce(tmpV, tempPmax, eimic_positive, tempPmax); - else - Ft = 0; // jak nastawnik na zero, to sila tez zero - return tempPmax; -} - -// the tractive force of a diesel-electric at the speed tmpV: on the straight part of its characteristic under the speed -// Vhyp gives at the power LinePower, at the share Ratio of it, on the hyperbola of the power HyperbolaPower over it -double TMoverParameters::DieselElectricForce(double const tmpV, double const LinePower, double const Ratio, double const HyperbolaPower) const -{ - if (tmpV < Vhyp * LinePower / DElist[MainCtrlPosNo].GenPower) - { - // czy na czesci prostej, czy na hiperboli - return (Ftmax - (Ftmax - 1000.0 * DElist[MainCtrlPosNo].GenPower / (Vhyp + Vadd)) * (tmpV / Vhyp) / PowerCorRatio) * Ratio; // posratio - bo sila jakos tam sie rozklada - } - // na hiperboli - // 1.107 - wspolczynnik sredniej nadwyzki Ft w symku nad charakterystyka - return 1000.0 * HyperbolaPower / (tmpV + Vadd) / PowerCorRatio; // tu jest zawarty stosunek mocy -} - -// in the shunting mode, the generator's power limited to tmp, the power the engine gives -void TMoverParameters::DieselElectricShuntPower(double const tmp) -{ - EnginePower = EngineVoltage * Im / 1000.0; - if (EnginePower > tmp) - { - EnginePower = tmp; - EngineVoltage = EnginePower * 1000.0 / Im; - } - if (EnginePower < tmp) - { - Ft *= EnginePower / tmp; - } -} - -// the generator's current limited to tempImax and its voltage by its characteristic, under tempUmax and the power tmp -void TMoverParameters::DieselElectricGenerator(double const tmp, double const tempUmax, double const tempImax) -{ - if (abs(Im) > tempImax) - { // nie ma nadmiarowego, tylko Imax i zwarcie na pradnicy - Ft = Ft / Im * tempImax; - Im = tempImax; - } - - if (Im > 0) - { - // jak pod obciazeniem - if (true == Flat) - { - // ograniczenie napiecia w pradnicy - plaszczak u gory - EngineVoltage = 1000.0 * tmp / std::abs(Im); - } - else - { - auto tempMCP = EIMCtrlType > 0 ? 1 + 99 * std::max(1.0, eimic_real) : MainCtrlPos; - auto tempMCPN = EIMCtrlType > 0 ? 100 : MainCtrlPosNo; - // charakterystyka pradnicy obcowzbudnej (elipsa) - twierdzenie Pitagorasa - EngineVoltage = std::sqrt(std::abs(square(tempUmax) - square(tempUmax * Im / tempImax))) * (tempMCP - 1) + (1.0 - Im / tempImax) * tempUmax * (tempMCPN - tempMCP); - EngineVoltage /= tempMCPN - 1; - EngineVoltage = safe_clamp(EngineVoltage, Im * 0.05, 1000.0 * tmp / std::abs(Im)); - } - } - - if (EngineVoltage > tempUmax || Im == 0) - { - // gdy wychodzi za duze napiecie albo przy biegu jalowym (jest cos takiego?) - EngineVoltage = tempUmax * (ConverterFlag ? 1 : 0); - } - - EnginePower = EngineVoltage * Im / 1000.0; - /* - // power curve drop - // NOTE: disabled for the time being due to side-effects - if( ( tmpV > 1 ) && ( EnginePower < tmp ) ) { - Ft = std::lerp( - Ft, EnginePower / tmp, - std::clamp( tmpV - 1.0, 0.0, 1.0 ) ); - } - */ -} - -// the shunt field relays of a diesel-electric, each kind its own conditions on the current, the speed or the -// power (tmp, the power the engine gives) -void TMoverParameters::ShuntFieldRelaysCheck(double const tmpV, double const PosRatio, double const tmp) -{ - auto const shuntfieldstate{ScndCtrlPos}; - - switch (RelayType) - { - - case 0: - { - - if (ScndCtrlPos < ScndCtrlPosNo && Im <= MPTRelay[ScndCtrlPos].Iup * PosRatio) - { - ++ScndCtrlPos; - } - if (ScndCtrlPos > 0 && Im >= MPTRelay[ScndCtrlPos].Idown * PosRatio) - { - --ScndCtrlPos; - } - break; - } - case 1: - { - - if (ScndCtrlPos < ScndCtrlPosNo && MPTRelay[ScndCtrlPos].Iup < Vel) - { - ++ScndCtrlPos; - } - if (ScndCtrlPos > 0 && MPTRelay[ScndCtrlPos].Idown > Vel) - { - --ScndCtrlPos; - } - break; - } - case 2: - { - - ShuntFieldRelaysType2(tmp); - break; - } - case 41: - { - ShuntFieldRelaysType41(tmpV); - break; - } - case 45: - { - ShuntFieldRelaysType45(); - break; - } - case 46: - { - ShuntFieldRelaysType46(); - break; - } - default: - { - break; - } - } // switch RelayType - - if (ScndCtrlPos != shuntfieldstate) - { - SetFlag(SoundFlag, sound::relay | sound::shuntfield); - } -} - -// the relays of type 2: up by the speed while the engine has power to spare (tmp, the power it gives), down by the current -void TMoverParameters::ShuntFieldRelaysType2(double const tmp) -{ - if (ScndCtrlPos < ScndCtrlPosNo && MPTRelay[ScndCtrlPos].Iup < Vel && EnginePower < tmp * 0.99) - { - ++ScndCtrlPos; - } - if (ScndCtrlPos > 0 && MPTRelay[ScndCtrlPos].Idown < Im) - { - --ScndCtrlPos; - } -} - -// the relays of type 41: up by the speed tmpV at full power, the engine slowed down, down by the current -void TMoverParameters::ShuntFieldRelaysType41(double const tmpV) -{ - if (ScndCtrlPos < ScndCtrlPosNo && MainCtrlPos == MainCtrlPosNo && tmpV * 3.6 > MPTRelay[ScndCtrlPos].Iup) - { - ++ScndCtrlPos; - enrot = enrot * 0.73; - } - if (ScndCtrlPos > 0 && Im > MPTRelay[ScndCtrlPos].Idown) - { - --ScndCtrlPos; - } -} - -// the relays of type 45, by the current and the speed: up from the 11th position, at most two under it, none under the 8th -void TMoverParameters::ShuntFieldRelaysType45() -{ - if (ScndCtrlPos < ScndCtrlPosNo && MainCtrlPos >= 11) - { - - if (Im < MPTRelay[ScndCtrlPos].Iup) - { - ++ScndCtrlPos; - } - // check for cases where the speed drops below threshold for level 2 or 3 - if (ScndCtrlPos > 1 && Vel < MPTRelay[ScndCtrlPos - 1].Idown) - { - --ScndCtrlPos; - } - } - // malenie - if (ScndCtrlPos > 0 && MainCtrlPos < 11) - { - - if (ScndCtrlPos == 1) - { - if (Im > MPTRelay[ScndCtrlPos - 1].Idown) - { - --ScndCtrlPos; - } - } - else - { - if (Vel < MPTRelay[ScndCtrlPos].Idown) - { - --ScndCtrlPos; - } - } - } - // 3rd level drops with master controller at position lower than 10... - if (MainCtrlPos < 11) - { - ScndCtrlPos = std::min(2, ScndCtrlPos); - } - // ...and below position 7 field shunt drops altogether - if (MainCtrlPos < 8) - { - ScndCtrlPos = 0; - } - /* - // crude woodward approximation; difference between rpm for consecutive positions is ~5% - // so we get full throttle until ~half way between desired and previous position, or zero on rpm reduction - auto const woodward { std::clamp( - ( DElist[ MainCtrlPos ].RPM / ( enrot * 60.0 ) - 1.0 ) * 50.0, - 0.0, 1.0 ) }; - */ -} - -// the relays of type 46, by the current and the speed: up from the 12th position, down under it below 50 km/h, at most two -// under the 11th, none under the 8th -void TMoverParameters::ShuntFieldRelaysType46() -{ - // wzrastanie - if (MainCtrlPos >= 12 && ScndCtrlPos < ScndCtrlPosNo) - { - ShuntFieldRelaysType46Up(); - } - // malenie - if (MainCtrlPos < 12 && ScndCtrlPos > 0 && Vel < 50.0) - { - ShuntFieldRelaysType46Down(); - } - if (MainCtrlPos < 11) - { - ScndCtrlPos = std::min(2, ScndCtrlPos); - } - if (MainCtrlPos < 8) - { - ScndCtrlPos = 0; - } -} - -// a relay of type 46 down: an even one by the current, an odd one by the current and the speed -void TMoverParameters::ShuntFieldRelaysType46Down() -{ - // above 50 km/h already active shunt field can be maintained until lower controller setting - if (ScndCtrlPos % 2 == 0) - { - if (MPTRelay[ScndCtrlPos].Idown < Im) - { - --ScndCtrlPos; - } - } - else - { - if (MPTRelay[ScndCtrlPos + 1].Idown < Im && MPTRelay[ScndCtrlPos].Idown > Vel) - { - --ScndCtrlPos; - } - } -} - -// a relay of type 46 up: an even one by the current, an odd one by the current and the speed -void TMoverParameters::ShuntFieldRelaysType46Up() -{ - if (ScndCtrlPos % 2 == 0) - { - if (MPTRelay[ScndCtrlPos].Iup > Im) - { - ++ScndCtrlPos; - } - } - else - { - if (MPTRelay[ScndCtrlPos - 1].Iup > Im && MPTRelay[ScndCtrlPos].Iup < Vel) - { - ++ScndCtrlPos; - } - } -} - -void TMoverParameters::InductionMotorTractionForce(double dt) -{ - if (MainCircuitPowered() && !SecuritySystem.is_engine_blocked()) - { - double PosRatio; - double tmp; - double ActiveInverters = 0.0; - for (auto const &inv : Inverters) - { - if (inv.IsActive) - ActiveInverters += 1.0; - } - InvertersRatio = ActiveInverters / (double)InvertersNo; - if (EIM_Pmax_Table.size() > 1) - { - eimc[eimc_p_Pmax] = TableInterpolation(EIM_Pmax_Table, Vel); - } - InductionMotorSpeedControl(dt); - InductionMotorBrakeBlending(ActiveInverters, PosRatio, tmp); - // NOTE: the commands to operate the sandbox are likely to conflict with other similar ai decisions - // TODO: gather these in single place so they can be resolved together - if (SlippingWheels) - { - PosRatio = 0; - tmp = 10; - SandboxAuto(true, range_t::unit); - } // przeciwposlizg - else - { - // switch sandbox off - SandboxAuto(false, range_t::unit); - } - if (ActiveInverters == 0.0) - { - PosRatio = 0; - eimv_pr = 0; - } - - eimv_pr += std::max(std::min(PosRatio - eimv_pr, 0.02), -0.02) * 12 * tmp /*2{+4*byte(PosRatio 1) - { - SpeedControlByPosition(dt); - } -} - -// the speed control set by the position of the second controller, after it's been held for its delay -void TMoverParameters::SpeedControlByPosition(double dt) -{ - if (ScndCtrlPos != NewSpeed) - { - - SpeedCtrlTimer = 0; - NewSpeed = ScndCtrlPos; - } - else - { - SpeedCtrlTimer += dt; - if (SpeedCtrlTimer > SpeedCtrlDelay) - { - auto NewSCAP = static_cast((float)ScndCtrlPos / (float)ScndCtrlPosNo * Vmax); - if (NewSCAP != SpeedCtrlValue) - { - SpeedCtrlValue = NewSCAP; - // SendCtrlToNext("SpeedCntrl", SpeedCtrlValue, CabActive); - } - } - } - SpeedCtrlUnit.IsActive = SpeedCtrlValue > 0; -} - -// the speed control of a four position second controller, by time: the speed set down or up by 10 km/h a step, held, -// or off and at the top -void TMoverParameters::SpeedControlByTime(double dt) -{ - SpeedCtrlUnit.IsActive = SpeedCtrlValue > 0; - switch (ScndCtrlPos) - { - case 0: - NewSpeed = 0; - SpeedCtrlValue = 0; - SpeedCtrlTimer = 10; - break; - case 1: - if (SpeedCtrlTimer > SpeedCtrlDelay) - { - SpeedCtrlTimer = 0; - NewSpeed -= 10; - if (NewSpeed < 0) - NewSpeed = 0; - } - else - SpeedCtrlTimer += dt; - break; - case 2: - SpeedCtrlTimer = 10; - SpeedCtrlValue = NewSpeed; - break; - case 3: - if (SpeedCtrlTimer > SpeedCtrlDelay) - { - SpeedCtrlTimer = 0; - NewSpeed += 10; - if (NewSpeed > Vmax) - NewSpeed = Vmax; - } - else - SpeedCtrlTimer += dt; - break; - case 4: - NewSpeed = Vmax; - SpeedCtrlValue = Vmax; - SpeedCtrlTimer = 10; - break; - default: - break; - } -} - -// whether the induction motors brake, and the share of the electrodynamic and the pneumatic brake; sets the -// force asked of the motors (PosRatio) and how fast the drive follows it (tmp) -void TMoverParameters::InductionMotorBrakeBlending(double const ActiveInverters, double &PosRatio, double &tmp) -{ - InductionMotorDynamicBrakeFlag(); - auto const edBCP{Hamulec->GetEDBCP() * eimc[eimc_p_abed]}; // stala napedu - if (DynamicBrakeFlag) - { - PosRatio = InductionMotorBrakeRatio(ActiveInverters, edBCP); - tmp = 5; - } - else - { - PosRatio = std::max(eimic_real, 0.); - eimv[eimv_Fzad] = PosRatio; - if (Flat && eimc[eimc_p_F0] * eimv[eimv_Fful] > 0) - PosRatio = std::min(PosRatio * eimc[eimc_p_F0] / eimv[eimv_Fful], 1.); - /* if (ScndCtrlActualPos > 0) //speed control - if (Vmax < 250) - PosRatio = std::min(PosRatio, std::max(-1, 0.5 * (ScndCtrlActualPos - Vel))); - else - PosRatio = - std::min(PosRatio, std::max(-1, 0.5 * (ScndCtrlActualPos * 2 - Vel))); */ - // PosRatio = 1.0 * (PosRatio * 0 + 1) * PosRatio; // 1 * 1 * PosRatio = PosRatio - Hamulec->SetED(0); - // (Hamulec as TLSt).SetLBP(LocBrakePress); - tmp = 4; // szybkie malenie, powolne wzrastanie - } -} - -// the electrodynamic brake of the induction motors on: with the doors open or permitted, by the train brake, the local -// brake or its own controller; off without them -void TMoverParameters::InductionMotorDynamicBrakeFlag() -{ - double const edBCP = Hamulec->GetEDBCP(); - auto const localbrakeactive{CabOccupied != 0 && LocHandle->GetCP() > 0.25}; - // gdy SplitEDPneumaticBrake jest aktywne, hamulec pomocniczy (LocalBrake) NIE wymusza - // zalaczenia hamulca elektrodynamicznego - ED jest sterowany wlasnym nastawnikiem - auto const dynbrakectrlactive{SplitEDPneumaticBrake && DynamicBrakeRatio() > 0.01 && DynamicBrakeAvailable()}; - auto const localbrakeforED{SplitEDPneumaticBrake ? false : localbrakeactive}; - if (false == Doors.instances[side::left].is_closed || false == Doors.instances[side::right].is_closed || - (Doors.permit_needed && (Doors.instances[side::left].open_permit || Doors.instances[side::right].open_permit))) - { - DynamicBrakeFlag = true; - } - else if ((edBCP < 0.25 && false == localbrakeforED && false == dynbrakectrlactive && AnPos < 0.01) || - (edBCP < 0.25 && ShuntModeAllow && false == dynbrakectrlactive && LocalBrakePosA < 0.01)) - DynamicBrakeFlag = false; - else if (BrakePress > 0.25 && edBCP > 0.25 || localbrakeforED || AnPos > 0.02 || dynbrakectrlactive) - DynamicBrakeFlag = true; -} - -// the share of the electrodynamic brake (negative), and the distributor told how much of the air to let out; none -// when the air brake cuts the electrodynamic one off, or an inverter is out -double TMoverParameters::InductionMotorBrakeRatio(double const ActiveInverters, double const edBCP) -{ - double PosRatio; - // ustalanie współczynnika blendingu do luzowania hamulca PN - if (eimv[eimv_Fmax] * Sign(V) * DirAbsolute < -1) - { - PosRatio = -Sign(V) * DirAbsolute * eimv[eimv_Fr] / (eimc[eimc_p_Fh] * std::max(edBCP, std::max(0.01, Hamulec->GetEDBCP())) / MaxBrakePress[0]); - PosRatio = std::clamp(PosRatio, 0.0, 1.0); - } - else - { - PosRatio = 0; - } - PosRatio = static_cast(Round(20.0 * PosRatio)) / 20.0; // stopniowanie PN/ED - if (PosRatio < 19.5 / 20.0) - PosRatio *= 0.9; - Hamulec->SetED(std::max(0.0, std::min(PosRatio, 1.0))); // ustalenie stopnia zmniejszenia ciśnienia - // ustalanie siły hamowania ED - if (Hamulec->GetEDBCP() > 0.25 && eimc[eimc_p_abed] < 0.001 || ActiveInverters < InvertersNo) // jeśli PN wyłącza ED - { - PosRatio = 0; - eimv[eimv_Fzad] = 0; - } - else - { - // strefa wylaczenia ED (Vh0..Vh1) - mnoznik 0..1 zaleznie od predkosci - double const vhRamp = std::max(0.0, std::min(1.0, (Vel - eimc[eimc_p_Vh0]) / (eimc[eimc_p_Vh1] - eimc[eimc_p_Vh0]))); - if (SplitEDPneumaticBrake) - { - // w trybie split LocalBrake nie zaleca ED; uzywany jest DynamicBrakeCtrl - // oraz zwykle zapotrzebowanie z hamulca zespolonego (edBCP) - double const edLeverDemand = DynamicBrakeRatio(); - PosRatio = -std::max(std::max(edLeverDemand, std::min(edBCP / MaxBrakePress[0], 1.0)), AnPos) * vhRamp; - eimv[eimv_Fzad] = -std::min(1.0, std::max(edLeverDemand, edBCP / MaxBrakePress[0])); - } - else - { - PosRatio = -std::max(std::min(edBCP * 1.0 / MaxBrakePress[0], 1.0), AnPos) * vhRamp; - eimv[eimv_Fzad] = -std::min(1.0, std::max(LocalBrakeRatio(), edBCP / MaxBrakePress[0])); - } - } - return PosRatio; -} - -// the model of the induction motors and their inverters: voltage, frequency, currents, moment and force -void TMoverParameters::InductionMotorDrive(double dt) -{ - double tmp; - if (DynamicBrakeFlag) - tmp = eimc[eimc_f_Uzh]; - else - tmp = eimc[eimc_f_Uzmax]; - - auto f_cfu{DynamicBrakeFlag ? eimc[eimc_f_cfuH] : eimc[eimc_f_cfu]}; - - eimv[eimv_Uzsmax] = std::min(EngineVoltage - eimc[eimc_f_DU], tmp); - eimv[eimv_fkr] = eimv[eimv_Uzsmax] / f_cfu; - if (eimv_pr < 0) - { - eimv[eimv_Pmax] = eimc[eimc_p_Ph]; - } - else - { - eimv[eimv_Pmax] = std::min(eimc[eimc_p_Pmax], 0.001 * EngineVoltage * (eimc[eimc_p_Imax] - eimc[eimc_f_I0]) * Pirazy2 * eimc[eimc_s_cim] / eimc[eimc_s_p] / eimc[eimc_s_cfu]); - if (GensetSelected()) - { - // on the genset of a dual-mode vehicle the traction takes no more than the genset gives - eimv[eimv_Pmax] = std::min(eimv[eimv_Pmax], GensetTractionPowerLimit()); - } - } - eimv[eimv_FMAXMAX] = 0.001 * - square(std::min(1.0, eimv[eimv_fkr] / std::max(abs(enrot) * eimc[eimc_s_p] + eimc[eimc_s_dfmax] * eimv[eimv_ks], eimc[eimc_s_dfmax])) * f_cfu / eimc[eimc_s_cfu]) * - (eimc[eimc_s_dfmax] * eimc[eimc_s_dfic] * eimc[eimc_s_cim]) * Transmision.Ratio * NPoweredAxles * 2.0 / WheelDiameter; - InductionMotorForceLimits(); - for (auto &inv : Inverters) - { - inv.Request = inv.IsActive ? eimv_pr : 0.0; - inv.Error = inv.Failure_Const || (inv.Failure_Drive && inv.Request != 0); - inv.IsActive = inv.Activate && !inv.Error; - } - eimv[eimv_ks] = eimv[eimv_Fr] / eimv[eimv_FMAXMAX]; - eimv[eimv_df] = eimv[eimv_ks] * eimc[eimc_s_dfmax]; - eimv[eimv_fp] = DirAbsolute * enrot * eimc[eimc_s_p] + eimv[eimv_df]; // do przemyslenia dzialanie pp z tmpV - // eimv[eimv_U]:=std::max(eimv[eimv_Uzsmax],std::min(eimc[eimc_f_cfu]*eimv[eimv_fp],eimv[eimv_Uzsmax])); - // eimv[eimv_pole]:=eimv[eimv_U]/(eimv[eimv_fp]*eimc[eimc_s_cfu]); - if (abs(eimv[eimv_fp]) <= eimv[eimv_fkr]) - eimv[eimv_pole] = f_cfu / eimc[eimc_s_cfu]; - else - eimv[eimv_pole] = eimv[eimv_Uzsmax] / eimc[eimc_s_cfu] / abs(eimv[eimv_fp]); - eimv[eimv_U] = eimv[eimv_pole] * eimv[eimv_fp] * eimc[eimc_s_cfu]; - eimv[eimv_Ic] = (eimv[eimv_fp] - DirAbsolute * enrot * eimc[eimc_s_p]) * eimc[eimc_s_dfic] * eimv[eimv_pole]; - eimv[eimv_If] = eimv[eimv_Ic] * eimc[eimc_s_icif]; - eimv[eimv_M] = eimv[eimv_pole] * eimv[eimv_Ic] * eimc[eimc_s_cim]; - eimv[eimv_Ipoj] = eimv[eimv_Ic] * NPoweredAxles * InvertersRatio * eimv[eimv_U] / (EngineVoltage - eimc[eimc_f_DU]) + eimc[eimc_f_I0]; - eimv[eimv_Pm] = DirActive * eimv[eimv_M] * NPoweredAxles * InvertersRatio * enrot * Pirazy2 / 1000; - eimv[eimv_Pe] = eimv[eimv_Ipoj] * EngineVoltage / 1000; - eimv[eimv_eta] = eimv[eimv_Pm] / eimv[eimv_Pe]; - - Im = eimv[eimv_If]; - if (eimv[eimv_Ipoj] >= 0) - Vadd *= 1.0 - 2.0 * dt; - else if (GensetSelected()) - Vadd = 1.0; // the genset of a dual-mode vehicle takes nothing back: all the braking energy to the resistors - else if (std::abs(EngineVoltage) < EnginePowerSource.CollectorParameters.MaxV) - Vadd *= 1.0 - dt; - else - Vadd = std::max(Vadd * (1.0 - 0.2 * dt), 0.007 * (std::abs(EngineVoltage) - (EnginePowerSource.CollectorParameters.MaxV - 100))); - Itot = eimv[eimv_Ipoj] * (0.01 + std::min(0.99, 0.99 - Vadd)); - - EnginePower = abs(eimv[eimv_Ic] * eimv[eimv_U] * NPoweredAxles) / 1000; - // power inverters - UpdateInverterFrequency(); - - Mm = eimv[eimv_M] * DirAbsolute; - Mw = Mm * Transmision.Ratio * Transmision.Efficiency; - Fw = Mw * 2.0 / WheelDiameter; - Ft = Fw * NPoweredAxles * InvertersRatio; - eimv[eimv_Fr] = DirAbsolute * Ft / 1000; -} - -// the force the motors give at full and at the setting (eimv_pr), braking within the power and the force of the -// electrodynamic brake, driving within the power and the starting force -void TMoverParameters::InductionMotorForceLimits() -{ - if (eimv_pr < 0) - { - eimv[eimv_Fful] = std::min(eimc[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(eimc[eimc_p_Fh], eimv[eimv_FMAXMAX])); - eimv[eimv_Fmax] = -Sign(V) * DirAbsolute*std::min(eimc[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-eimc[eimc_p_Fh] * eimv_pr, eimv[eimv_FMAXMAX])); - double pr = eimv_pr; - if (EIMCLogForce) - pr = -log(1 - 4 * pr) / log(5); - eimv[eimv_Fr] = -Sign(V) * DirAbsolute*std::min(eimc[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-eimc[eimc_p_Fh] * pr, eimv[eimv_FMAXMAX])); - if (InvertersRatio < 1.0) - eimv[eimv_Fful] = 0; - //*std::min(1,(Vel-eimc[eimc_p_Vh0])/(eimc[eimc_p_Vh1]-eimc[eimc_p_Vh0])) - } - else - { - eimv[eimv_Fful] = std::min(std::min(3.6 * eimv[eimv_Pmax] / std::max(Vel, 1.), eimc[eimc_p_F0] - Vel * eimc[eimc_p_a1]), eimv[eimv_FMAXMAX]); - // if(not Flat)then - eimv[eimv_Fmax] = eimv[eimv_Fful] * eimv_pr; - // else - // eimv[eimv_Fmax]:=std::min(eimc[eimc_p_F0]*eimv_pr,eimv[eimv_Fful]); - double pr = eimv_pr; - if (EIMCLogForce) - pr = log(1 + 4 * pr) / log(5); - eimv[eimv_Fr] = eimv[eimv_Fful] * pr; - } -} - -// the frequency of the inverters at the motors' slip frequency, from the list of the drive or of its brake -void TMoverParameters::UpdateInverterFrequency() -{ - auto const tmpV{std::abs(eimv[eimv_fp])}; - auto const useFFEDList = FFEDListSize > 0 && DynamicBrakeFlag; - auto const list = useFFEDList ? FFEDlist : FFlist; - - if (auto const listSize = useFFEDList ? FFEDListSize : FFListSize; listSize > 0 && std::abs(eimv[eimv_If]) > 1.0 && tmpV > 0.0001) - { - - int i = 0; - while (i < listSize - 1 && list[i + 1].v < tmpV) - { - ++i; - } - InverterFrequency = (tmpV - list[i].v) / std::max(1.0, list[i + 1].v - list[i].v) * (list[i + 1].freq - list[i].freq) + list[i].freq; - } - else - { - InverterFrequency = 0.0; - } -} - -// the induction motor drive without power, or blocked by the security system -void TMoverParameters::InductionMotorOff() -{ - for (auto &inv : Inverters) - { - inv.Freal = 0.0; - inv.IsActive = false; - } - Im = 0.0; - Mm = 0.0; - Mw = 0.0; - Fw = 0.0; - Ft = 0.0; - Itot = 0.0; - eimv_pr = 0.0; - EnginePower = 0.0; - { - for (auto &eimvvalue : eimv) - eimvvalue = 0.0; - } - Hamulec->SetED(0.0); - InverterFrequency = 0.0; //(Hamulec as TLSt).SetLBP(LocBrakePress); -} - -// the current of a diesel-electric vehicle's traction motors giving the moment [N m] of one motor -double TMoverParameters::dieselelectric_motor_current(double const Moment) const -{ - // with MotorParam[ScndCtrlPos] do - if (abs(Moment) > motor_param(ScndCtrlPos).fi) - return NPoweredAxles * abs(abs(Moment) / motor_param(ScndCtrlPos).mfi + motor_param(ScndCtrlPos).mIsat); - else - return NPoweredAxles * sqrt(abs(Moment * motor_param(ScndCtrlPos).Isat)); -} - -// the effort of a diesel-electric vehicle's dynamic brake the driver asks for, 0..1 -double TMoverParameters::dieselelectric_dynamic_brake_demand() const -{ - switch (DEDynamicBrake.source) - { - case diesel_electric_dynamic_brake::control::controller: - return std::clamp(-eimic_real, 0.0, 1.0); - case diesel_electric_dynamic_brake::control::lever: - return DynamicBrakeRatio(); - default: - return 0.0; - } -} - -// the force [N] of a diesel-electric vehicle's dynamic brake at full effort at the speed: the most the motors take -// (the current), above the speed where the resistors' power takes over, the power; under EDBrakeV1 it fades, down to -// nothing at EDBrakeV0. a brake of direct current motors, whose force grows with the speed (the voltage they generate -// into the resistors), fades from 0 to the speed of its whole force; an inverter's only at the stop -double TMoverParameters::dieselelectric_dynamic_brake_limit() const -{ - auto const &brake{DEDynamicBrake}; - auto limit{brake.max_force}; - if (brake.max_power > 0.0 && std::abs(V) > 0.0) - { - limit = std::min(limit, brake.max_power / std::abs(V)); - } - if (brake.fade_high > brake.fade_low) - { - limit *= std::clamp((Vel - brake.fade_low) / (brake.fade_high - brake.fade_low), 0.0, 1.0); - } - else if (Vel < brake.fade_low) - { - limit = 0.0; - } - return limit; -} - -// the dynamic brake of a diesel-electric vehicle, before the drive's force: the effort follows the demand, the force -// is the share of the most at the speed. the motors brake while the engine runs (it excites them, or keeps the -// control of the inverters going), with the direction set, the overload relay closed, no power asked for and the -// wheels rolling; otherwise there's no brake at once -void TMoverParameters::update_dieselelectric_dynamic_brake(double const dt) -{ - auto &brake{DEDynamicBrake}; - auto const nopower{brake.source == diesel_electric_dynamic_brake::control::controller ? eimic_real <= 0.0 : IsMainCtrlNoPowerPos()}; - if (Mains && DirActive != 0 && false == FuseFlag && false == SlippingWheels && nopower) - { - brake.level += std::clamp(dieselelectric_dynamic_brake_demand() - brake.level, -brake.rate * dt, brake.rate * dt); - } - else - { - brake.level = 0.0; - } - brake.force = brake.level * dieselelectric_dynamic_brake_limit(); - DynamicBrakeFlag = brake.force > 0.0; - if (brake.blending) - { - // the train brake of the locomotive lets off by the share of the dynamic brake's force (LSt, EStED) - Hamulec->SetED(brake.max_force > 0.0 ? brake.force / brake.max_force : 0.0); - } -} - -// the force of a diesel-electric vehicle's dynamic brake, against the motion, in place of the drive's one: the motors -// work as generators into the resistors, the ammeter shows their current, the main generator gives nothing. near the -// stop no more than what stops the vehicle within the step dt: with no fade (EDBrakeV0 = EDBrakeV1 = 0) the whole force -// would turn round each time the speed crosses zero, and in FTrain it never lets the stop of ComputeMovement() catch it -void TMoverParameters::apply_dieselelectric_dynamic_brake(double const dt) -{ - auto const force{dt > 0.0 ? std::min(DEDynamicBrake.force, TotalMass * std::abs(V) / dt) : DEDynamicBrake.force}; - Ft = V > 0.0 ? -force : V < 0.0 ? force : 0.0; - Fw = Ft / NPoweredAxles; - Mw = Fw * WheelDiameter / 2.0; - Mm = Mw / Transmision.Ratio; - Im = dieselelectric_motor_current(Mm); - EngineVoltage = 0.0; - EnginePower = 0.0; -} - -// ************************************************************************************************* -// Q: 20160713 -// Obliczenie predkości obrotowej kół??? -// ************************************************************************************************* -double TMoverParameters::ComputeRotatingWheel(double WForce, double dt, double n) const -{ - double newn = 0; - double eps = 0; - if (n == 0 && WForce * Sign(V) < 0) - newn = 0; - else - { - eps = WForce * WheelDiameter / (2.0 * AxleInertialMoment); - newn = n + eps * dt; - if (newn * n <= 0 && eps * n < 0) - newn = 0; - } - return newn; -} - -// ************************************************************************************************* -// Q: 20160713 -// Sprawdzenie bezpiecznika nadmiarowego -// ************************************************************************************************* -bool TMoverParameters::FuseFlagCheck(void) const -{ - bool FFC; - - FFC = false; - if (Power > 0.01) - FFC = FuseFlag; - else // pobor pradu jezeli niema mocy - for (auto &thiscoupler : Couplers) - if (TestFlag(thiscoupler.CouplingFlag, coupling::control) && thiscoupler.Connected->Power > 0.01) - FFC = thiscoupler.Connected->FuseFlagCheck(); - - return FFC; -} - -// ************************************************************************************************* -// Q: 20160713 -// Załączenie bezpiecznika nadmiarowego -// ************************************************************************************************* -bool TMoverParameters::FuseOn(range_t const Notify) -{ - auto const result{RelayReset(relay_t::maincircuitground | relay_t::tractionnmotoroverload, Notify)}; - - return result; -} - -// ************************************************************************************************* -// Q: 20160713 -// Wyłączenie bezpiecznika nadmiarowego -// ************************************************************************************************* -void TMoverParameters::FuseOff(void) -{ - if (!FuseFlag) - { - FuseFlag = true; - EventFlag = true; - SetFlag(SoundFlag, sound::relay | sound::loud); - } -} - -// resets relays assigned to specified customizable reset button -bool TMoverParameters::UniversalResetButton(int const Button, range_t const Notify) -{ - - if (auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; false == lowvoltagepower) - { - return false; - } - - auto const relays{UniversalResetButtonFlag[Button]}; - if (relays == 0) - { - return false; - } - - auto const result{RelayReset(relays, Notify)}; - - return result; -} - -// resets state of specified relays -bool TMoverParameters::RelayReset(int const Relays, range_t const Notify) -{ - - auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; - bool reset{false}; - - if (TestFlag(Relays, relay_t::maincircuitground) && (EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric) && - (GroundRelayStart == start_t::manual || GroundRelayStart == start_t::manualwithautofallback) && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0 && DirActive != 0 && - !TestFlag(EngDmgFlag, 1)) - { - // NOTE: true means the relay is operational - reset |= !GroundRelay && lowvoltagepower; - GroundRelay |= lowvoltagepower; - } - - if (TestFlag(Relays, relay_t::tractionnmotoroverload) && (EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric) && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0 && DirActive != 0 && - !TestFlag(EngDmgFlag, 1)) - { - // NOTE: false means the relay is operational - // TODO: cleanup, flip the FuseFlag code to match other relays - // TODO: check whether the power is required, TBD, TODO: make it configurable? - reset |= FuseFlag && lowvoltagepower; - FuseFlag &= !lowvoltagepower; - } - - if (TestFlag(Relays, relay_t::primaryconverteroverload) && ConverterOverloadRelayStart == start_t::manual - // && ( false == Mains ) - && false == ConverterAllow) - { - // NOTE: false means the relay is operational - // TODO: cleanup, flip the FuseFlag code to match other relays - // TODO: check whether the power is required, TBD, TODO: make it configurable? - reset |= ConvOvldFlag && lowvoltagepower; - ConvOvldFlag &= !lowvoltagepower; - } - - if (reset) - { - SetFlag(SoundFlag, sound::relay | sound::loud); - } - - if (Notify != range_t::local) - { - SendCtrlToNext("RelayReset", Relays, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return reset; -} - -// ************************************************************************************************* -// Q: 20160713 -// Przeliczenie prędkości liniowej na obrotową -// ************************************************************************************************* -double TMoverParameters::v2n(void) -{ - // przelicza predkosc liniowa na obrotowa - const double dmgn = 0.5; - double n; - double deltan = 0; - - n = V / (M_PI * WheelDiameter); // predkosc obrotowa wynikajaca z liniowej [obr/s] - deltan = n - nrot; //"pochodna" prędkości obrotowej - /* if (SlippingWheels) - if (std::abs(deltan) < 0.001) - SlippingWheels = false; // wygaszenie poslizgu */ //poslizg jest w innym miejscu wygaszany też - if (SlippingWheels) // nie ma zwiazku z predkoscia liniowa V - { // McZapkie-221103: uszkodzenia kol podczas poslizgu - if (deltan > dmgn && FuzzyLogic(deltan, dmgn, p_slippdmg) && SetFlag(DamageFlag, dtrain_wheelwear)) // podkucie - EventFlag = true; - if (deltan < -dmgn && FuzzyLogic(-deltan, dmgn, p_slippdmg) && SetFlag(DamageFlag, dtrain_thinwheel)) // wycieranie sie obreczy - EventFlag = true; - n = nrot; // predkosc obrotowa nie zalezy od predkosci liniowej - } - return n; -} - -// ************************************************************************************************* -// Q: 20160714 -// Oblicza moment siły wytwarzany przez silnik -// ************************************************************************************************* -double TMoverParameters::Momentum(double I) const -{ - // liczy moment sily wytwarzany przez silnik elektryczny} - int SP; - - SP = ScndCtrlActualPos; - if (ScndInMain && !(RList[MainCtrlActualPos].ScndAct == 255)) - SP = RList[MainCtrlActualPos].ScndAct; - - // Momentum:=mfi*I*(1-1.0/(Abs(I)/mIsat+1)); - return motor_param(SP).mfi * I * (abs(I) / (abs(I) + motor_param(SP).mIsat) - motor_param(SP).mfi0); -} - -// ************************************************************************************************* -// Q: 20160714 -// Oblicza moment siły do sterowania wzbudzeniem -// ************************************************************************************************* -double TMoverParameters::MomentumF(double I, double Iw, int SCP) const -{ - // umozliwia dokladne sterowanie wzbudzeniem - - return motor_param(SCP).mfi * I * std::max(abs(Iw) / (abs(Iw) + motor_param(SCP).mIsat) - motor_param(SCP).mfi0, 0.); -} - -// ************************************************************************************************* -// Q: 20160713 -// Odłączenie uszkodzonych silników -// ************************************************************************************************* -bool TMoverParameters::CutOffEngine(void) -{ - bool COE = false; // Ra: wartość domyślna, sprawdzić to trzeba - if (NPoweredAxles > 0 && CabActive == 0 && EngineType == TEngineType::ElectricSeriesMotor && SetFlag(DamageFlag, -dtrain_engine)) - { - NPoweredAxles = NPoweredAxles / 2; // bylo div czyli mod? - COE = true; - } - return COE; -} - -// ************************************************************************************************* -// Q: 20160713 -// Przełączenie wysoki / niski prąd rozruchu -// ************************************************************************************************* -bool TMoverParameters::MaxCurrentSwitch(bool State, range_t const Notify) -{ - auto const initialstate{MotorOverloadRelayHighThreshold}; - - MotorOverloadRelayHighThreshold = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("MaxCurrentSwitch", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return State != initialstate; -} - -// ************************************************************************************************* -// Q: 20160713 -// Przełączenie wysoki / niski prąd rozruchu automatycznego -// ************************************************************************************************* -bool TMoverParameters::MinCurrentSwitch(bool State) -{ - bool MCS = false; - if ((EngineType == TEngineType::ElectricSeriesMotor && IminHi > IminLo) || (TrainType == train_type::emu && EngineType != TEngineType::ElectricInductionMotor)) - { - - if (State && Imin == IminLo) - { - Imin = IminHi; - MCS = true; - if (CabActive != 0) - SendCtrlToNext("MinCurrentSwitch", 1, CabActive); - } - if (!State && Imin == IminHi) - { - Imin = IminLo; - MCS = true; - if (CabActive != 0) - SendCtrlToNext("MinCurrentSwitch", 0, CabActive); - } - } - return MCS; -} - -// ************************************************************************************************* -// Q: 20160713 -// Sprawdzenie wskaźnika jazdy na oporach -// ************************************************************************************************* -bool TMoverParameters::ResistorsFlagCheck(void) const -{ - bool RFC = false; - - if (Power > 0.01) - RFC = ResistorsFlag; - else // pobor pradu jezeli niema mocy - { - for (auto &thiscoupler : Couplers) - if (TestFlag(thiscoupler.CouplingFlag, coupling::control) && thiscoupler.Connected->Power > 0.01) - RFC = thiscoupler.Connected->ResistorsFlagCheck(); - } - return RFC; -} - -// ************************************************************************************************* -// Q: 20160713 -// Włączenie / wyłączenie automatycznego rozruchu -// ************************************************************************************************* -bool TMoverParameters::AutoRelaySwitch(bool State) -{ - bool ARS; - if (AutoRelayType == 2 && AutoRelayFlag != State) - { - AutoRelayFlag = State; - ARS = true; - SendCtrlToNext("AutoRelaySwitch", int(State), CabActive); - } - else - ARS = false; - - return ARS; -} - -// ************************************************************************************************* -// Q: 20160724 -// Sprawdzenie warunków pracy automatycznego rozruchu -// ************************************************************************************************* - -bool TMoverParameters::AutoRelayCheck(void) -{ - bool OK = false; // b:int; - - auto const motorconnectorsoff{false == MotorConnectorsCheck()}; - - // Ra 2014-06: dla SN61 nie działa prawidłowo - // yBARC - rozlaczenie stycznikow liniowych - if (motorconnectorsoff || (HasCamshaft ? IsMainCtrlActualNoPowerPos() : IsMainCtrlNoPowerPos())) - { - StLinFlag = false; - if (false == DynamicBrakeFlag) - { - Im = 0; - Itot = 0; - ResistorsFlag = false; - } - } - - // sprawdzenie wszystkich warunkow (AutoRelayFlag, AutoSwitch, Im 0 || ScndCtrlPos > 0) && (!CoupledCtrl || RList[MainCtrlActualPos].Relay == MainCtrlPos)) - { // zmieniaj scndctrlactualpos - OK = AutoRelayShuntStep(ARFASI2); - } - else - { // zmieniaj mainctrlactualpos - OK = AutoRelayMainStep(ARFASI); - } - } - else // not StLinFlag - { - OK = AutoRelayLineContactorsStep(motorconnectorsoff); - } - if (OK) - LastRelayTime = 0; - - return OK; - } -} - -// a step of the shunt field on a position without resistors, up or down to the second controller -bool TMoverParameters::AutoRelayShuntStep(bool const ARFASI2) -{ - bool OK = false; - // scnd bez samoczynnego rozruchu - if (ScndCtrlActualPos < ScndCtrlPos) - { - if (LastRelayTime > CtrlDelay && ARFASI2) - { - ++ScndCtrlActualPos; - SetFlag(SoundFlag, sound::shuntfield); - OK = true; - } - } - else if (ScndCtrlActualPos > ScndCtrlPos) - { - if (LastRelayTime > CtrlDownDelay && TrainType != train_type::emu) - { - --ScndCtrlActualPos; - SetFlag(SoundFlag, sound::shuntfield); - OK = true; - } - } - else - OK = false; - return OK; -} - -// a step of the main controller's relays, up or down to its position, or the shunt field off on the resistors -bool TMoverParameters::AutoRelayMainStep(bool const ARFASI) -{ - bool OK = false; - // running backwards, the motors don't get joined in more branches than allowed (the series connection - // alone, usually); the camshaft still goes back down from there (eu07/maszyna#393: it stayed where it - // was, the line contactors closed, whatever the driver did with the master controller) - auto const backwardslimit{DirActive < 0 && TrainType != train_type::pseudodiesel && RList[MainCtrlActualPos + 1].Bn > BackwardsBranchesAllowed}; - // main bez samoczynnego rozruchu - if (false == backwardslimit && MainCtrlActualPos < std::size(RList) - 1 // crude guard against running out of current fixed table - && (RList[MainCtrlActualPos].Relay < MainCtrlPos || (RList[MainCtrlActualPos + 1].Relay == MainCtrlPos && MainCtrlActualPos < RlistSize) || - (TrainType == train_type::et22 && DelayCtrlFlag))) - { - OK = AutoRelayMainUp(ARFASI); - } - else if (RList[MainCtrlActualPos].Relay > MainCtrlPos) - { - OK = AutoRelayMainDown(); - } - else if (RList[MainCtrlActualPos].R > 0 && ScndCtrlActualPos > 0) - { - if (LastRelayTime > CtrlDownDelay) - { - --ScndCtrlActualPos; // boczniki nie dzialaja na poz. oporowych - SetFlag(SoundFlag, sound::shuntfield); - OK = true; - } - } - else - OK = false; - return OK; -} - -// a step of the main relays up to the controller's position, at once to the parallel position without resistors -// on a fast serial circuit (303E); returns whether the relays moved, never into parallel with the overload relay high -bool TMoverParameters::AutoRelayMainUp(bool const ARFASI) -{ - bool OK = false; - // prevent switch to parallel mode if motor overload relay is set to high threshold mode - if (IsMotorOverloadRelayHighThresholdOn() && RList[MainCtrlActualPos + 1].Bn > 1) - { - return false; - } - - if (RList[MainCtrlPos].R == 0 && MainCtrlPos > 0 && MainCtrlPos != MainCtrlPosNo && FastSerialCircuit == 1) - { - // szybkie wchodzenie na bezoporowa (303E) - // MainCtrlActualPos:=MainCtrlPos; //hunter-111012: - ++MainCtrlActualPos; - if (MainCtrlPos - MainCtrlActualPos == 1) - { - // HACK: ensure we play only single sound of basic relays for entire trasition; return false - // for all but last step despite configuration change, to prevent playback of the basic relay sound - // TBD, TODO: move the basic sound event here and enable it with call parameter - OK = true; - } - if (RList[MainCtrlActualPos].R == 0) - { - SetFlag(SoundFlag, sound::parallel | sound::loud); - OK = true; - } - } - else if (LastRelayTime > CtrlDelay && ARFASI) - { - OK = AutoRelayMainNotchUp(); - } - return OK; -} - -// a notch up of the main relays after their delay, through the group switch of the ET22, and the sounds of the -// parallel positions; returns whether they moved -bool TMoverParameters::AutoRelayMainNotchUp() -{ - bool OK = false; - // WriteLog("LRT = " + FloatToStr(LastRelayTime) + ", " + - // FloatToStr(CtrlDelay)); - if (TrainType == train_type::et22 && MainCtrlPos > 1 && (RList[MainCtrlActualPos].Bn < RList[MainCtrlActualPos + 1].Bn || DelayCtrlFlag)) - { - // et22 z walem grupowym - if (!DelayCtrlFlag) // najpierw przejscie - { - ++MainCtrlActualPos; - DelayCtrlFlag = true; // tryb przejscia - OK = true; - } - else if (LastRelayTime > 4 * CtrlDelay) // przejscie - { - - DelayCtrlFlag = false; - OK = true; - } - /* - else - ; - */ - } - else // nie ET22 z wałem grupowym - { - ++MainCtrlActualPos; - OK = true; - } - //--------- - // hunter-111211: poprawki - if (MainCtrlActualPos > 0) - { - if (RList[MainCtrlActualPos].R == 0 && MainCtrlActualPos != MainCtrlPosNo) - { - // wejscie na bezoporowa - SetFlag(SoundFlag, sound::parallel | sound::loud); - } - else if (RList[MainCtrlActualPos].R > 0 && RList[MainCtrlActualPos - 1].R == 0) - { - // wejscie na drugi uklad - SetFlag(SoundFlag, sound::parallel); - } - } - return OK; -} - -// a step of the main relays down to the controller's position; returns whether they moved -bool TMoverParameters::AutoRelayMainDown() -{ - bool OK = false; - if (RList[MainCtrlPos].R == 0 && MainCtrlPos > 0 && !(MainCtrlPos == MainCtrlPosNo) && FastSerialCircuit == 1) - { - // szybkie wchodzenie na bezoporowa (303E) - // MainCtrlActualPos:=MainCtrlPos; //hunter-111012: - --MainCtrlActualPos; - OK = true; - if (RList[MainCtrlActualPos].R == 0) - { - SetFlag(SoundFlag, sound::parallel); - } - } - else if (LastRelayTime > CtrlDownDelay) - { - if (TrainType != train_type::emu) // tutaj powinien być tryb sterowania wałem - { - --MainCtrlActualPos; - OK = true; - } - // hunter-111211: poprawki - if (MainCtrlActualPos > 0 && RList[MainCtrlActualPos].R == 0) - { - // dzwieki schodzenia z bezoporowej} - SetFlag(SoundFlag, sound::parallel); - } - } - return OK; -} - -// the line contactors closed at the first position, or, open, the camshaft run back to zero -bool TMoverParameters::AutoRelayLineContactorsStep(bool const motorconnectorsoff) -{ - bool OK = false; - // ybARC - zalaczenie stycznikow liniowych - if (false == motorconnectorsoff && MainCtrlActualPos == 0 && (TrainType == train_type::emu || HasCamshaft ? MainCtrlPowerPos() > 0 : MainCtrlPowerPos() == 1)) - { - - DelayCtrlFlag = true; - if (LastRelayTime >= InitialCtrlDelay) - { - StLinFlag = true; - MainCtrlActualPos = 1; - DelayCtrlFlag = false; - SetFlag(SoundFlag, sound::relay | sound::loud); - OK = true; - } - } - else - { - DelayCtrlFlag = false; - } - - if (false == StLinFlag && (MainCtrlActualPos > 0 || ScndCtrlActualPos > 0)) - { - OK |= CamshaftRunDown(); - } - return OK; -} - -// the camshaft, the line contactors open, run back to its zero position a step at a time, or at once without one; -// returns whether it moved -bool TMoverParameters::CamshaftRunDown() -{ - bool OK = false; - - if (CoupledCtrl) - { - - if (TrainType == train_type::emu) - { - OK = CamshaftRunDownEMU(); - } - else if (LastRelayTime > CtrlDownDelay) // wal kulakowy dwukierunkowy - { - if (ScndCtrlActualPos > 0) - { - --ScndCtrlActualPos; - SetFlag(SoundFlag, sound::shuntfield); - } - else - { - --MainCtrlActualPos; - } - OK = true; - } - } - else if (HasCamshaft) - { - // wal kulakowy dwukierunkowy - if (LastRelayTime > CtrlDownDelay) - { - if (MainCtrlActualPos > 0) - { - --MainCtrlActualPos; - } - ScndCtrlActualPos = 0; - OK = true; - } - } - else - { - MainCtrlActualPos = 0; - ScndCtrlActualPos = 0; - OK = true; - } - return OK; -} - -// the one way camshaft of the EN57 run on to its end and round to zero; returns whether it moved -bool TMoverParameters::CamshaftRunDownEMU() -{ - bool OK = false; - // EN57 wal jednokierunkowy calosciowy - if (MainCtrlActualPos == 1) - { - - MainCtrlActualPos = 0; - OK = true; - } - else - { - - if (LastRelayTime > CtrlDownDelay) - { - - if (MainCtrlActualPos < RlistSize) - { - // dojdz do konca - ++MainCtrlActualPos; - } - else if (ScndCtrlActualPos < ScndCtrlPosNo) - { - // potem boki - ++ScndCtrlActualPos; - SetFlag(SoundFlag, sound::shuntfield); - } - else - { - // i sie przewroc na koniec - MainCtrlActualPos = 0; - ScndCtrlActualPos = 0; - } - OK = true; - } - } - return OK; -} - -bool TMoverParameters::MotorConnectorsCheck() -{ - - // hunter-111211: wylacznik cisnieniowy - // (on some vehicles it watches the brake pipe alone) - ControlPressureSwitch = HasControlPressureSwitch && ((PressureSwitchBrakeCylinder && BrakePress > 2.0) || PipePress < 3.6); - - if (true == ControlPressureSwitch) - { - return false; - } - - // a line breaker closed ahead of the pantographs holds without voltage; what cuts the motors off there is its - // undervoltage relay, which elsewhere opens the line breaker - auto const undervoltage{PantographsRequireMains && false == NoVoltRelay}; - - auto const connectorsoff{false == Mains || undervoltage || true == FuseFlag || true == StLinSwitchOff || DirActive == 0}; - - return false == connectorsoff && LineContactorsInterlockReleased(); -} - -bool TMoverParameters::LineContactorsInterlockReleased() const -{ - switch (LineContactorsInterlock) - { - case line_contactors_interlock::converter: - // the converter of this very vehicle, not the 110 V of the trainset: a section with its fans off doesn't start - return ConverterFlag; - case line_contactors_interlock::motor_blowers: - return std::ranges::all_of(MotorBlowers, [this](auto const &Blower) { - if (Blower.min_start_velocity < 0) - { - return Blower.is_active; - } - // a blower which starts with the speed and the motor current (MotorBlowersStartVelocity) can't run before - // the contactors close, nor after a stop longer than it keeps running for: it's enough that it's - // switched on and has power, so it starts once the vehicle moves - return MotorBlowerPowerIsAvailable(Blower) && false == Blower.is_disabled && (Blower.start_type == start_t::manual ? Blower.is_enabled : true); - }); - default: - return true; - } -} - -bool TMoverParameters::OperatePantographsValve(operation_t const State, range_t const Notify) -{ - - if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector && EnginePowerSource.CollectorParameters.CollectorsNo > 0) - { - - auto &valve{PantsValve}; - - switch (State) - { - using enum operation_t; - case none: - { - valve.is_enabled = false; - valve.is_disabled = false; - break; - } - case enable: - { - valve.is_enabled = true; - valve.is_disabled = false; - break; - } - case disable: - { - valve.is_enabled = false; - valve.is_disabled = true; - break; - } - case enable_on: - { - valve.is_enabled = true; - break; - } - case enable_off: - { - valve.is_enabled = false; - break; - } - case disable_on: - { - valve.is_disabled = true; - break; - } - case disable_off: - { - valve.is_disabled = false; - break; - } - } - } - - if (Notify != range_t::local) - { - SendCtrlToNext("PantsValve", static_cast(State), CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return true; -} - -bool TMoverParameters::OperatePantographValve(end const End, operation_t const State, range_t const Notify) -{ - - if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector && EnginePowerSource.CollectorParameters.CollectorsNo > 0) - { - - auto &valve{Pantographs[End].valve}; - - switch (State) - { - using enum operation_t; - case none: - { - valve.is_enabled = false; - valve.is_disabled = false; - break; - } - case enable: - { - valve.is_enabled = true; - valve.is_disabled = false; - break; - } - case disable: - { - valve.is_enabled = false; - valve.is_disabled = true; - break; - } - case enable_on: - { - valve.is_enabled = true; - break; - } - case enable_off: - { - valve.is_enabled = false; - break; - } - case disable_on: - { - valve.is_disabled = true; - break; - } - case disable_off: - { - valve.is_disabled = false; - break; - } - } - } - - if (Notify != range_t::local) - { - SendCtrlToNext("PantValve", - // HACK: pack the state, pantograph index and sender cab into 8-bit value - // with high bit storing front/rear pantograph, and 7th bit storing sender cab - static_cast(0x80 * (End == end::front ? 0 : 1) + 0x40 * (CabActive != -1 ? 1 : 0) + static_cast(State)), CabActive, - Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return true; -} - -bool TMoverParameters::DropAllPantographs(bool const State, range_t const Notify) -{ - - auto const initialstate{PantAllDown}; - - PantAllDown = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("PantAllDown", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return State != initialstate; -} - -namespace -{ -// the setting of the universal controller one UniCtrlValStep further from Value towards Limit, never past it -double next_uc_step(double const Value, double const Limit, double const Step) -{ - constexpr double epsilon{1e-6}; - if (Limit > Value) - { - return std::min((std::floor(Value / Step + epsilon) + 1.0) * Step, Limit); - } - return std::max((std::ceil(Value / Step - epsilon) - 1.0) * Step, Limit); -} - -// the universal controller with UniCtrlValStep: the setting the continuous ramp got to (Ramped) turned into whole steps. -// a move of the controller onto a position which changes the setting makes one step at once, the ramp then one step each -// time it covers a step's length; the steps stop at the position's set value (or its bound, past which the ramp doesn't go) -double stepped_uc_value(double const Current, double const Ramped, TUniversalCtrl const &Position, double const Step, bool const Moved, double &Progress) -{ - if (Moved) - { - Progress = 0.0; - } - double const delta{Ramped - Current}; - if (std::abs(delta) < 1e-9) - { - Progress = 0.0; - return Ramped; - } - double limit{0.0}; - if (delta > 0.0) - { - limit = Position.SetCtrlVal > Current ? Position.SetCtrlVal : Position.MaxCtrlVal; - } - else - { - limit = Position.SetCtrlVal < Current ? Position.SetCtrlVal : Position.MinCtrlVal; - } - Progress = Moved ? Step : Progress + std::abs(delta); - double value{Current}; - bool reached{std::abs(value - limit) < 1e-9}; - while (!reached && Progress >= Step - 1e-9) - { - value = next_uc_step(value, limit, Step); - Progress -= Step; - reached = std::abs(value - limit) < 1e-9; - } - if (reached) - { - Progress = 0.0; - } - // added after the move to std::clamp: bounds given the other way round are put in order, as master did it - auto const [lowest, highest] = std::minmax(Position.MinCtrlVal, Position.MaxCtrlVal); - return std::clamp(value, lowest, highest); -} -} // namespace - -void TMoverParameters::CheckEIMIC(double dt) -{ - double offset = EIMCtrlAdditionalZeros ? 1.0 : 0.0; - double multiplier = (EIMCtrlEmergency ? 1.0 : 0.0) + offset; - // gdy SplitEDPneumaticBrake jest wlaczone, sterowanie ujemne (hamowanie ED) bierzemy - // z osobnego nastawnika DynamicBrakeCtrl, a nie z hamulca pomocniczego (LocalBrake). - // Dodatkowo zapotrzebowanie ED jest ograniczone przez strefe Vh0..Vh1: powyzej Vh1 - pelny ED, - // pomiedzy Vh1 a Vh0 - liniowe zanikanie, ponizej Vh0 - zerowe (brak hamowania pneumatycznego - // jako uzupelnienia, poniewaz LocalBrake jest oddzielny i operuje wylacznie pneumatyka). - double brakeDemand = SplitEDPneumaticBrake ? DynamicBrakeRatio() : LocalBrakeRatio(); - if (SplitEDPneumaticBrake) - { - double const vh0 = eimc[eimc_p_Vh0]; - double const vh1 = eimc[eimc_p_Vh1]; - if (vh1 > vh0 + 0.001) - { - double const vhRamp = std::clamp((Vel - vh0) / (vh1 - vh0), 0.0, 1.0); - brakeDemand *= vhRamp; - } - } - switch (EIMCtrlType) - { - case 0: - EIMICFromController(brakeDemand, offset, multiplier); - break; - case 1: - EIMICFromSteps(dt); - break; - case 2: - EIMICFromFourPositions(dt); - break; - case 3: - EIMICFromUniversalController(dt, brakeDemand); - break; - } - if (LocHandleTimeTraxx) - { - EIMICTraxxLocalBrake(dt); - } - - EIMICLimit(); -} - -// the controller (EIMCtrlType 0): the position of the main controller, or the analog one, or the brake asked -void TMoverParameters::EIMICFromController(double const brakeDemand, double const offset, double const multiplier) -{ - eimic = brakeDemand > 0.01 ? -brakeDemand : eimic_analog > 0.01 ? eimic_analog : (double)MainCtrlPos / (double)MainCtrlPosNo; - if (EIMCtrlAdditionalZeros || EIMCtrlEmergency) - { - if (eimic > 0.001) - eimic = std::max(0.002, eimic * (double)MainCtrlPosNo / ((double)MainCtrlPosNo - offset) - offset / ((double)MainCtrlPosNo - offset)); - if (eimic < -0.001 && BrakeHandle != TBrakeHandle::MHZ_EN57) - eimic = std::min(-0.002, eimic * (double)LocalBrakePosNo / ((double)LocalBrakePosNo - multiplier) + offset / ((double)LocalBrakePosNo - multiplier)); - } - if (eimic > 0.001 && SpeedCtrlUnit.IsActive) - eimic = std::max(eimic, SpeedCtrlUnit.MinPower); -} - -// EIMCtrlType 1: the positions B+ to TMax move the value at a steady pace -void TMoverParameters::EIMICFromSteps(double dt) -{ - switch (MainCtrlPos) - { - case 0: // B+ - eimic -= std::clamp(1.0 + eimic, 0.0, dt * 0.14); // odejmuj do -1 - break; - case 1: // B - eimic -= std::clamp(0.0 + eimic, 0.0, dt * 0.14); // odejmuj do 0 - break; - case 2: // B- - case 3: // 0 - case 4: // T- - eimic -= std::clamp(0.0 + eimic, 0.0, dt * 0.14); // odejmuj do 0 - eimic += std::clamp(0.0 - eimic, 0.0, dt * 0.14); // dodawaj do 0 - break; - case 5: // T - eimic += std::clamp(0.0 - eimic, 0.0, dt * 0.14); // dodawaj do 0 - break; - case 6: // T+ - eimic += std::clamp(1.0 - eimic, 0.0, dt * 0.14); // dodawaj do 1 - break; - case 7: // TMax - eimic += std::clamp(1.0 - eimic, 0.0, dt * 0.14); // dodawaj do 1, max - break; - default: - break; - } - if (MainCtrlPos >= 3 && eimic < 0) - eimic = 0; - if (MainCtrlPos <= 3 && eimic > 0) - eimic = 0; -} - -// EIMCtrlType 2: the positions 0 to 4 move the value towards -1, 0 or 1, from the controller's delay on; the -// emergency brake position below them, where the controller has one, brakes in full at once -void TMoverParameters::EIMICFromFourPositions(double dt) -{ - if (IsMainCtrlEmergencyPos()) - { - // hamowanie nagle: pelne hamowanie od razu, przewod glowny oproznia UpdatePipePressure() - eimic = -1.0; - } - else if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) - { - double delta = MainCtrlActualPos == MainCtrlPos ? dt * CtrlDelay : 0.01; - // the positions below are those of the controller without the emergency brake position - switch (MainCtrlPos - EIMCtrlEmergencyPositions()) - { - case 0: - case 1: - eimic -= safe_clamp(1.0 + eimic, 0.0, delta); // odejmuj do -1 - if (eimic > 0) - eimic = 0; - break; - case 2: - eimic -= safe_clamp(0.0 + eimic, 0.0, delta); // odejmuj do 0 - break; - case 3: - eimic += safe_clamp(0.0 - eimic, 0.0, delta); // dodawaj do 0 - break; - case 4: - eimic += safe_clamp(1.0 - eimic, 0.0, delta); // dodawaj do 1 - if (eimic < 0) - eimic = 0; - break; - default: - break; - } - } - if (MainCtrlActualPos == MainCtrlPos) - LastRelayTime += dt; - else - { - LastRelayTime = 0; - MainCtrlActualPos = MainCtrlPos; - } -} - -// EIMCtrlType 3: the universal controller of UniCtrlList, with the train brake built in or not -void TMoverParameters::EIMICFromUniversalController(double dt, double const brakeDemand) -{ - if (UniCtrlIntegratedBrakePNCtrl) - { - UniversalControllerTrainBrake(); - } - - if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) - { - auto const &position{UniCtrlList[MainCtrlPos]}; - double ramped{eimic}; - ramped -= safe_clamp(-position.SetCtrlVal + ramped, 0.0, - MainCtrlActualPos == MainCtrlPos ? dt * position.SpeedDown : sign(position.SpeedDown) * 0.01); // odejmuj do X - ramped += safe_clamp(position.SetCtrlVal - ramped, 0.0, - MainCtrlActualPos == MainCtrlPos ? dt * position.SpeedUp : sign(position.SpeedUp) * 0.01); // dodawaj do X - ramped = safe_clamp(ramped, position.MinCtrlVal, position.MaxCtrlVal); - eimic = UniCtrlValStep > 0.0 ? stepped_uc_value(eimic, ramped, position, UniCtrlValStep, MainCtrlActualPos != MainCtrlPos, eimic_step_progress) : ramped; - } - if (MainCtrlActualPos == MainCtrlPos) - LastRelayTime += dt; - else - { - LastRelayTime = 0; - MainCtrlActualPos = MainCtrlPos; - } - if (Hamulec->GetEDBCP() > 0.3 && eimic < 0 && !UniCtrlIntegratedLocalBrakeCtrl) // when braking with pneumatic brake - eimic = 0; // shut off retarder - if (UniCtrlIntegratedBrakeCtrl == false && UniCtrlIntegratedLocalBrakeCtrl == false) - { - // w trybie SplitEDPneumaticBrake hamowanie ED przychodzi z osobnego nastawnika, - // LocalBrake operuje wylacznie pneumatycznym hamulcem lokomotywy - eimic = brakeDemand > 0.01 ? -brakeDemand : eimic; - } -} - -// the train brake built into the universal controller: the handle set to the controller's position, or the -// controller, at a brake handle moved alone, to the nearest position of the handle's -void TMoverParameters::UniversalControllerTrainBrake() -{ - if (UniCtrlList[MainCtrlPos].mode != BrakeCtrlPos && MainCtrlActualPos == MainCtrlPos) // there was no move of controller, but brake only - { - if (BrakeCtrlPos < UniCtrlList[MainCtrlPosNo].mode) - BrakeLevelSet(UniCtrlList[MainCtrlPosNo].mode); // bottom clamping - if (BrakeCtrlPos > UniCtrlList[0].mode) - BrakeLevelSet(UniCtrlList[0].mode); // top clamping - if (IsCabMaster()) - { - while (BrakeCtrlPos > UniCtrlList[MainCtrlPos].mode) - DecMainCtrl(1); // find nearest position - while (BrakeCtrlPos < UniCtrlList[MainCtrlPos].mode) - IncMainCtrl(1); // find nearest position - } - } - else // controller was moved - BrakeLevelSet(UniCtrlList[MainCtrlPos].mode); -} - -// the local brake of the TRAXX locomotives, by time: released, held or applied, which cuts the drive off -void TMoverParameters::EIMICTraxxLocalBrake(double dt) -{ - if (LocalBrakeRatio() < 0.4) // pozycja 0, odhamowywanie - { - eim_localbrake -= dt * 0.17; - } - - if (LocalBrakeRatio() > 0.6) // pozycja 2, zahamowywanie - { - eim_localbrake += dt * 0.17; - eim_localbrake = std::max(eim_localbrake, BrakePress / MaxBrakePress[0]); - } - else // pozycja 1, utrzymanie cisnienia - { - if (eim_localbrake < Hamulec->GetEDBCP() / MaxBrakePress[0]) - eim_localbrake = 0; - } - eim_localbrake = std::clamp(eim_localbrake, 0.0, 1.0); - if (eim_localbrake > 0.04 && eimic > 0) - eimic = 0; -} - -// the value limited by the power, the spring brake, the pipe lock, the direction and the doors' permits -void TMoverParameters::EIMICLimit() -{ - auto const eimicpowerenabled{(MainCircuitPowered() || Power == 0.0) && (!SpringBrake.IsActive || !SpringBrakeCutsOffDrive) && !LockPipe && DirAbsolute != 0}; - auto const eimicdoorenabled{(SpringBrake.IsActive && ReleaseParkingBySpringBrakeWhenDoorIsOpen)}; - double eimic_max = 0.0; - if (Doors.instances[side::left].open_permit == false && Doors.instances[side::right].open_permit == false) - { - if (eimicpowerenabled) - { - eimic_max = 1.0; - } - else - { - eimic_max = 0.001; - } - } - else - { - if (eimicdoorenabled) - { - eimic_max = 0.001; - } - } - eimic = safe_clamp(eimic, -1.0, eimicpowerenabled ? eimic_max : 0.0); -} - -bool TMoverParameters::UpdateStopBrakeRelease(double const Demand, double const Dt) -{ - if (Demand <= 0.0) - { - StopBrakeReleaseTimer = 0.0; - return false; - } - // the step the demand rises above 0 is time 0 of it, so without the delay the brake lets go at once, as it always did - auto const released{StopBrakeReleaseTimer >= StopBrakeReleaseDelay}; - StopBrakeReleaseTimer += Dt; - return released; -} - -void TMoverParameters::CheckSpeedCtrl(double dt) -{ - if (EIMCtrlType == 0) - { - SpeedCtrlUnit.DesiredPower = std::max(eimic, 0.0); - } - double accfactor = SpeedCtrlUnit.DesiredPower; - if (EIMCtrlType >= 2) - { - if (MainCtrlPos < MainCtrlPosNo - 2) - { - SpeedCtrlUnit.Standby = true; - } - if (MainCtrlPos > MainCtrlPosNo - 1) - { - SpeedCtrlUnit.Standby = false; - } - if (!SpeedCtrlUnit.BrakeIntervention && (Hamulec->GetEDBCP() > 0.4 || PipePress < HighPipePress - 0.2)) - SpeedCtrlUnit.Standby = true; - if (EIMCtrlType >= 3 && UniCtrlList[MainCtrlPos].SpeedUp <= 0) - { - accfactor = 0.0; - eimicSpeedCtrl = 0; - } - } - if (SpeedCtrlUnit.IsActive) - { // speed control - if (true) - { - if (!SpeedCtrlUnit.Standby) - { - SpeedCtrlRegulator(dt, accfactor); - } - else - { - eimicSpeedCtrl = 0; - eimicSpeedCtrlIntegral = 0; - } - SpeedCtrlUnit.Parking = Vel == 0.0 && eimic <= 0 && EngineType != TEngineType::ElectricInductionMotor; - SendCtrlToNext("SpeedCtrlUnit.Parking", SpeedCtrlUnit.Parking, CabActive); - } - else - { - if (Vmax < 250) - eimicSpeedCtrl = std::clamp(0.5 * (SpeedCtrlValue - Vel), -1.0, 1.0); - else - eimicSpeedCtrl = std::clamp(0.5 * (SpeedCtrlValue * 2 - Vel), -1.0, 1.0); - } - if ((SpeedCtrlAutoTurnOffFlag & 2) == 2 && Hamulec->GetEDBCP() > 0.25) - { - SpeedCtrlSwitch(false); - SpeedCtrlUnit.IsActive = false; - } - } - else - { - eimicSpeedCtrl = 1; - eimicSpeedCtrlIntegral = 0; - SpeedCtrlUnit.Parking = false; - SendCtrlToNext("SpeedCtrlUnit.Parking", SpeedCtrlUnit.Parking, CabActive); - } -} - -// the PI regulator of the speed control: the power asked of the drive, or its brake intervention, from the error of -// the speed; accfactor, the most power it may ask -void TMoverParameters::SpeedCtrlRegulator(double dt, double const accfactor) -{ - if (SpeedCtrlUnit.ManualStateOverride && eimic > 0.0009) - eimic = 1.0; - double error = std::max(SpeedCtrlValue + SpeedCtrlUnit.Offset, 0.0) - Vel; - double factorP = error > 0 ? SpeedCtrlUnit.FactorPpos : SpeedCtrlUnit.FactorPneg; - double eSCP = std::clamp(factorP * error, -1.2, 1.0); // P module - bool retarder_not_work = EngineType != TEngineType::DieselEngine || Vel < SpeedCtrlUnit.BrakeInterventionVel; - if (eSCP < -1.0) - { - SpeedCtrlUnit.BrakeInterventionBraking = eSCP < -1.1 && retarder_not_work && eimicSpeedCtrl < -0.99 * SpeedCtrlUnit.DesiredPower; - eSCP = -1.0; - } - SpeedCtrlUnit.BrakeInterventionUnbraking = eSCP > 0.0 || Vel == 0.0; - if (abs(eSCP) < 0.999) - { - // TODO: check how to disable integral part when braking in smart way - // double factorI = eimicSpeedCtrlIntegral >= 0 ? SpeedCtrlUnit.FactorIpos : SpeedCtrlUnit.FactorIneg; - double factorI = eimicSpeedCtrlIntegral >= 0 ? SpeedCtrlUnit.FactorIpos : SpeedCtrlUnit.FactorIneg; - eimicSpeedCtrlIntegral = safe_clamp(eimicSpeedCtrlIntegral + factorI * eSCP * dt, -1.0 + eSCP, 1.0 - eSCP); - } - else - { - eimicSpeedCtrlIntegral = 0; - } - auto const DesiredeimicSpeedCtrl{safe_clamp(eimicSpeedCtrlIntegral + eSCP, -SpeedCtrlUnit.DesiredPower, accfactor)}; - eimicSpeedCtrl = safe_clamp(DesiredeimicSpeedCtrl, eimicSpeedCtrl - SpeedCtrlUnit.PowerDownSpeed * dt, eimicSpeedCtrl + SpeedCtrlUnit.PowerUpSpeed * dt); - if (Vel < SpeedCtrlUnit.FullPowerVelocity) - { - eimicSpeedCtrl = std::min(eimicSpeedCtrl, SpeedCtrlUnit.InitialPower); - } - if (Vel < SpeedCtrlUnit.StartVelocity && MainCtrlPos < MainCtrlPosNo) - { - eimicSpeedCtrl = 0; - eimic = 0; - } -} - -bool TMoverParameters::IsSpeedCtrlSeparate() const -{ - // no secondary controller, or one of these engines', which shunts the field of the traction motors (eu07/maszyna#69) - return SpeedCtrl && (ScndCtrlPosNo == 0 || EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric); -} - -bool TMoverParameters::IsSpeedCtrlEngaged() const -{ - return IsSpeedCtrlSeparate() ? SpeedCtrlUnit.IsActive : ScndCtrlPos > 0; -} - -bool TMoverParameters::SpeedCtrlSwitch(bool const State) -{ - if (false == IsSpeedCtrlSeparate()) - { - return State ? IncScndCtrl(1) : DecScndCtrl(2); - } - // its own switch, the secondary controller left to the field shunting - if (State) - { - if (CabActive == 0 || SpeedCtrlUnit.IsActive) - { - return false; - } - SpeedCtrlValue = static_cast(Round(Vel)); - SpeedCtrlUnit.IsActive = true; - return true; - } - auto const wasactive{SpeedCtrlUnit.IsActive}; - SpeedCtrlValue = 0; - SpeedCtrlUnit.IsActive = false; - if (wasactive && SpeedCtrlUnit.ManualStateOverride) - { - eimic = 0.0; - } - return wasactive; -} - -void TMoverParameters::SpeedCtrlButton(int button) -{ - if (SpeedCtrl && IsSpeedCtrlEngaged()) - { - SpeedCtrlValue = SpeedCtrlButtons[button]; - } -} - -void TMoverParameters::SpeedCtrlInc() -{ - if (SpeedCtrl && IsSpeedCtrlEngaged()) - { - double x = floor(SpeedCtrlValue / SpeedCtrlUnit.VelocityStep) + 1.0; - SpeedCtrlValue = std::min(x * SpeedCtrlUnit.VelocityStep, SpeedCtrlUnit.MaxVelocity); - } -} - -void TMoverParameters::SpeedCtrlDec() -{ - if (SpeedCtrl && IsSpeedCtrlEngaged()) - { - double x = ceil(SpeedCtrlValue / SpeedCtrlUnit.VelocityStep) - 1.0; - SpeedCtrlValue = std::max(x * SpeedCtrlUnit.VelocityStep, SpeedCtrlUnit.MinVelocity); - } -} - -bool TMoverParameters::SpeedCtrlPowerInc() -{ - if (!(SpeedCtrl && IsSpeedCtrlEngaged())) - return false; - - if (SpeedCtrlUnit.DesiredPower == SpeedCtrlUnit.MaxPower) - return false; - - SpeedCtrlUnit.DesiredPower = std::min(SpeedCtrlUnit.DesiredPower + SpeedCtrlUnit.PowerStep, SpeedCtrlUnit.MaxPower); - return true; -} - -bool TMoverParameters::SpeedCtrlPowerDec() -{ - if (!(SpeedCtrl && IsSpeedCtrlEngaged())) - return false; - - if (SpeedCtrlUnit.DesiredPower == SpeedCtrlUnit.MinPower) - return false; - - SpeedCtrlUnit.DesiredPower = std::max(SpeedCtrlUnit.DesiredPower - SpeedCtrlUnit.PowerStep, SpeedCtrlUnit.MinPower); - return true; -} - -// ************************************************************************************************* -// Q: 20160715 -// Zmienia parametr do którego dąży sprzęgło -// ************************************************************************************************* -bool TMoverParameters::dizel_EngageSwitch(double state) -{ - if (EngineType == TEngineType::DieselEngine && state <= 1 && state >= 0 && state != dizel_engagestate) - { - dizel_engagestate = state; - return true; - } - else - return false; -} - -// ************************************************************************************************* -// Q: 20160715 -// Zmienia parametr do którego dąży sprzęgło -// ************************************************************************************************* -bool TMoverParameters::dizel_EngageChange(double dt) -{ - double engagespeed = 0; // OK:boolean; - bool DEC; - - DEC = false; - if (dizel_engage - dizel_engagestate > 0) - engagespeed = engagedownspeed; - else - engagespeed = engageupspeed; - if (dt > 0.2) - dt = 0.1; - if (abs(dizel_engage - dizel_engagestate) < 0.11) - { - if (dizel_engage != dizel_engagestate) - { - DEC = true; - dizel_engage = dizel_engagestate; - } - // else OK:=false; //już jest false - } - else - { - dizel_engage = dizel_engage + engagespeed * dt * (dizel_engagestate - dizel_engage); - // OK:=false; - } - // dizel_EngageChange:=OK; - return DEC; -} - -// ************************************************************************************************* -// Q: 20160715 -// Automatyczna zmiana biegów gdy prędkość przekroczy widełki -// ************************************************************************************************* -bool TMoverParameters::dizel_AutoGearCheck(void) -{ - auto OK{false}; - - auto const VelUp{(motor_param(ScndCtrlActualPos).mfi0 != 0.0 ? - motor_param(ScndCtrlActualPos).mfi0 + (motor_param(ScndCtrlActualPos).mfi - motor_param(ScndCtrlActualPos).mfi0) * std::max(0.0, eimic_real) : - motor_param(ScndCtrlActualPos).mfi)}; - - auto const VelDown{(motor_param(ScndCtrlActualPos).fi0 != 0.0 && eimic_real <= 0.0 ? motor_param(ScndCtrlActualPos).fi0 : motor_param(ScndCtrlActualPos).fi)}; - - if (motor_param(ScndCtrlActualPos).AutoSwitch && Mains) - { - OK = dizel_GearShiftCheck(VelUp, VelDown); - } - - if (Mains) - { - dizel_ClutchCheck(); - } - return OK; -} - -// the automatic gearbox: a gear up over VelUp, down under VelDown, changed once the clutch is out; returns whether it acted -bool TMoverParameters::dizel_GearShiftCheck(double const VelUp, double const VelDown) -{ - auto OK{false}; - if (RList[MainCtrlPos].Mn == 0 && !hydro_TC) - { - if (dizel_engagestate > 0) - dizel_EngageSwitch(0); - if (IsMainCtrlNoPowerPos() && ScndCtrlActualPos > 0) - dizel_automaticgearstatus = -1; - } - else - { - OK = dizel_GearShiftRequest(VelUp, VelDown); - } - if (dizel_engage < 0.1 && dizel_automaticgearstatus != 0) - { - if (dizel_automaticgearstatus == 1) - ScndCtrlActualPos++; - else - ScndCtrlActualPos--; - dizel_automaticgearstatus = 0; - dizel_EngageSwitch(1.0); - OK = true; - } - return OK; -} - -// a gear up asked over VelUp, down under VelDown, where the gearbox shifts by itself; returns whether one is -bool TMoverParameters::dizel_GearShiftRequest(double const VelUp, double const VelDown) -{ - auto OK{false}; - if (motor_param(ScndCtrlActualPos).AutoSwitch && dizel_automaticgearstatus == 0) // sprawdz czy zmienic biegi - { - if (Vel > VelUp) - { - // shift up - if (ScndCtrlActualPos < ScndCtrlPosNo) - { - dizel_automaticgearstatus = 1; - OK = true; - } - } - else if (Vel < VelDown) - { - // shift down - if (ScndCtrlActualPos > 0) - { - dizel_automaticgearstatus = -1; - OK = true; - } - } - } - return OK; -} - -// the pressure in the clutch's cylinder, by the controller's position or the integrated controller -void TMoverParameters::dizel_ClutchCheck() -{ - if (EIMCtrlType > 0) // sterowanie komputerowe - { - dizel_ClutchByIntegratedController(); - } - else if (dizel_automaticgearstatus == 0) // ustaw cisnienie w silowniku sprzegla} - dizel_ClutchByController(); - else - dizel_EngageSwitch(0.0); - if (!(motor_param(ScndCtrlActualPos).mIsat > 0)) - dizel_EngageSwitch(0.0); // wylacz sprzeglo na pozycjach neutralnych - if (!AutoRelayFlag) - ScndCtrlActualPos = ScndCtrlPos; -} - -// the clutch by the controller's position: half or fully in, fully over the speed of the full engagement -void TMoverParameters::dizel_ClutchByController() -{ - switch (RList[MainCtrlPos].Mn) - { - case 1: - dizel_EngageSwitch(0.5); - break; - case 2: - dizel_EngageSwitch(1.0); - break; - case 3: - if (Vel > dizel_minVelfullengage) - dizel_EngageSwitch(1.0); - else - dizel_EngageSwitch(0.5); - break; - case 4: - if (Vel > dizel_minVelfullengage) - dizel_EngageSwitch(1.0); - else - dizel_EngageSwitch(0.66); - break; - case 5: - if (Vel > dizel_minVelfullengage) - dizel_EngageSwitch(1.0); - else - dizel_EngageSwitch(0.35 * (1 + RList[MainCtrlPos].R) * RList[MainCtrlPos].R); - break; - default: - if (hydro_TC && hydro_TC_Fill > 0.01) - dizel_EngageSwitch(1.0); - else - dizel_EngageSwitch(0.0); - } -} - -// the clutch of the integrated controller: in with the converter filled or the power asked, half in for the retarder -void TMoverParameters::dizel_ClutchByIntegratedController() -{ - if (dizel_automaticgearstatus == 0) - { - if ((hydro_TC && hydro_TC_Fill > 0.01) || eimic_real > 0.005) - dizel_EngageSwitch(1.0); - else if (Vel > hydro_R_EngageVel && hydro_R && hydro_R_Fill > 0.01) - dizel_EngageSwitch(0.5); - else - dizel_EngageSwitch(0.0); - } - else - dizel_EngageSwitch(0.0); -} - -// performs diesel engine startup procedure; potentially clears startup switch; returns: true if the engine can be started, false otherwise -bool TMoverParameters::dizel_StartupCheck() -{ - - auto engineisready{true}; // make inital optimistic presumption, then watch the reality crush it - - // test the fuel pump - // TODO: add fuel pressure check - if (false == FuelPump.is_active || (EngineType == TEngineType::DieselEngine && RList[MainCtrlPos].R == 0.0)) - { - engineisready = false; - // if( FuelPump.start_type == start_t::manual ) { - // with manual pump control startup procedure is done only once per starter switch press - dizel_startup = false; - // } - } - // test the oil pump - if (false == OilPump.is_active || OilPump.pressure < OilPump.pressure_minimum) - { - engineisready = false; - if (OilPump.start_type == start_t::manual) - { - // with manual pump control startup procedure is done only once per starter switch press - dizel_startup = false; - } - } - // test the water circuits and water temperature - if (true == dizel_heat.PA) - { - engineisready = false; - // TBD, TODO: reset startup procedure depending on pump and heater control mode - dizel_startup = false; - } - - return engineisready; -} - -// ************************************************************************************************* -// Q: 20160715 -// Aktualizacja stanu silnika -// ************************************************************************************************* -bool TMoverParameters::dizel_Update(double dt) -{ - - WaterPumpCheck(dt); - WaterHeaterCheck(dt); - OilPumpCheck(dt); - FuelPumpCheck(dt); - // the engine being started fires once the starter has turned it a while; one stopped meanwhile starts over - dizel_FiringCountdown = (Mains ? std::max(0.0, dizel_FiringCountdown - dt) : 0.0); - - if (true == dizel_startup && true == dizel_StartupCheck()) - { - dizel_ignition = true; - } - - if (true == dizel_ignition && LastSwitchingTime >= InitialCtrlDelay) - { - - dizel_startup = false; - dizel_ignition = false; - // TODO: split engine and main circuit state indicator in two separate flags - LastSwitchingTime = 0; - Timer::subsystem.switching.note(Timer::switching_counter::diesel, this, &TypeName, &Name); - Mains = true; - dizel_spinup = true; - dizel_FiringCountdown = dizel_SmokeDelay; - enrot = std::max(enrot, - 0.35 * ( // TODO: dac zaleznie od temperatury i baterii - EngineType == TEngineType::DieselEngine ? dizel_nmin : DElist[0].RPM / 60.0)); - } - - dizel_spinup = dizel_spinup && Mains && enrot < 0.95 * (EngineType == TEngineType::DieselEngine ? dizel_nmin : DElist[0].RPM / 60.0); - - if (true == Mains && false == FuelPump.is_active) - { - // knock out the engine if the fuel pump isn't feeding it - // TBD, TODO: grace period before the engine is starved for fuel and knocked out - // an engine started on its own stops on its own - MainSwitch(false, MainSwitchRange()); - } - - bool DU{false}; - - if (EngineType == TEngineType::DieselEngine) - { - dizel_EngageChange(dt); - DU = dizel_AutoGearCheck(); - double const fillspeed{2}; - dizel_fill = dizel_fill + fillspeed * dt * (dizel_fillcheck(MainCtrlPos, dt) - dizel_fill); - } - - dizel_Heat(dt); - - return DU; -} - -// ************************************************************************************************* -// Q: 20160715 -// oblicza napelnienie, uzwglednia regulator obrotow -// ************************************************************************************************* -double TMoverParameters::dizel_fillcheck(int mcp, double dt) -{ - auto realfill{0.0}; - - if (true == Mains && MainCtrlPosNo > 0 && true == FuelPump.is_active) - { - - if (true == dizel_ignition && LastSwitchingTime >= 0.9 * InitialCtrlDelay) - { - // wzbogacenie przy rozruchu - // NOTE: ignition flag is reset before this code is executed - // TODO: sort this out - realfill = 1; - } - else - { - // napelnienie zalezne od MainCtrlPos - if (EIMCtrlType > 0) - { - realfill = dizel_DigitalFill(dt); - } - else - { - dizel_nreg_max = dizel_nmax; - realfill = RList[mcp].R; - } - } - if (dizel_nmax_cutoff > 0) - { - realfill = dizel_GovernorFill(mcp, realfill); - } - } - - return std::clamp(realfill, 0.0, 1.0); -} - -// the fill set by the integrated controller, and the idle and top revolutions the governor keeps to -double TMoverParameters::dizel_DigitalFill(double dt) -{ - double realfill; - realfill = std::max(0.0, std::min(eimic_real, 1 - motor_param(ScndCtrlActualPos).Isat)); - if (eimic_real > 0.005 && !hydro_TC_Lockup) - { - dizel_nreg_min = std::min(dizel_nreg_min + 2.5 * dt, dizel_nmin_hdrive + eimic_real * dizel_nmin_hdrive_factor); - } - else - { - if (Vel < hydro_R_EngageVel && hydro_R && hydro_R_Fill > 0.01) - dizel_nreg_min = std::min(dizel_nreg_min + 5.0 * dt, dizel_nmin_retarder); - else - dizel_nreg_min = dizel_nmin; - } - if (!dizel_vel2nmax_Table.empty() && !hydro_TC_Lockup) - { - dizel_nreg_max = std::min(std::min(dizel_nreg_max, enrot) + dizel_nreg_acc * dt, TableInterpolation(dizel_vel2nmax_Table, Vel)); - } - else - { - dizel_nreg_max = dizel_nmax; - } - return realfill; -} - -// the fill cut off over the revolutions the governor allows at the controller's position, or full under the idle ones -double TMoverParameters::dizel_GovernorFill(int const mcp, double realfill) const -{ - auto nreg{0.0}; - if (EIMCtrlType > 0) - nreg = eimic_real > 0.005 ? dizel_nreg_max : dizel_nmin; - else - nreg = dizel_GovernorRevolutions(mcp, realfill); - if (enrot > nreg) // nad predkoscia regulatora zeruj dawke - realfill = 0; - if (enrot < dizel_nreg_min && RList[mcp].R > 0.001) // jesli ponizej biegu jalowego i niezerowa dawka, to dawaj pelna - realfill = 1; - return realfill; -} - -// the revolutions the governor allows at the controller's position, the gearbox and the speed; the fill cut off at -// a position the governor doesn't know -double TMoverParameters::dizel_GovernorRevolutions(int const mcp, double &realfill) const -{ - auto nreg{0.0}; - switch (RList[MainCtrlPos].Mn) - { - case 0: - case 1: - nreg = dizel_nmin; - break; - case 2: - if (dizel_automaticgearstatus == 0 && true /*(!hydro_TC) || (dizel_engage>dizel_fill)*/) - nreg = dizel_nreg_max; - else - nreg = dizel_nmin; - break; - case 3: - if (dizel_automaticgearstatus == 0 && Vel > dizel_minVelfullengage) - nreg = dizel_nreg_max; - else - nreg = dizel_nmin; - break; - case 4: - if (dizel_automaticgearstatus == 0 && Vel > dizel_minVelfullengage) - nreg = dizel_nmax; - else - nreg = dizel_nmin * 0.75 + dizel_nreg_max * 0.25; - break; - case 5: - if (Vel > dizel_minVelfullengage) - nreg = dizel_nreg_max; - else - nreg = dizel_nmin + 0.8 * (dizel_nreg_max - dizel_nmin) * RList[mcp].R; - break; - default: - realfill = 0; // sluczaj - break; - } - return nreg; -} - -// ************************************************************************************************* -// Q: 20160715 -// Oblicza moment siły wytwarzany przez silnik spalinowy -// ************************************************************************************************* -double TMoverParameters::dizel_Momentum(double Fill, double n, double dt) -{ // liczy moment sily wytwarzany przez silnik spalinowy} - double Moment = 0; - double enMoment = 0; - double gearMoment = 0; - double eps = 0; - double newn = 0; - double friction = 0; - double TorqueH = 0; - double TorqueL = 0; - double TorqueC = 0; - n = n * CabActive; - if (motor_param(ScndCtrlActualPos).mIsat < 0.001 || DirActive == 0) - n = enrot; - friction = dizel_engagefriction; - hydro_TC_nIn = enrot; // wal wejsciowy przetwornika momentu - hydro_TC_nOut = dizel_n_old; // wal wyjsciowy przetwornika momentu - - if (enrot > 0) - { - if (dizel_Momentum_Table.size() > 1) - { - Moment = TableInterpolation(dizel_Momentum_Table, enrot) * Fill - dizel_Mstand; - } - else - { - Moment = (dizel_Mmax - (dizel_Mmax - dizel_Mnmax) * square((enrot - dizel_nMmax) / (dizel_nMmax - dizel_nmax))) * Fill - dizel_Mstand; - } - Mm = Moment; - dizel_FuelConsumptionActual = dizel_FuelConsumption * enrot * Fill; - dizel_FuelConsumptedTotal += dizel_FuelConsumptionActual * dt / 3600.0; - if (hydro_R && hydro_R_Placement == 2) - Moment -= dizel_MomentumRetarder(enrot, dt); - } - else - { - Moment = -dizel_Mstand; - } - if (enrot < dizel_nmin / 10.0 && eAngle < M_PI_2) - { - // wstrzymywanie przy malych obrotach - Moment -= dizel_Mstand; - } - if (true == dizel_spinup) - Moment += dizel_Mstand / (0.3 + std::max(0.0, enrot / dizel_nmin)); // rozrusznik - - dizel_Torque = Moment; - - hydro_TCFillCheck(dt); - - // obliczanie momentow poszczegolnych sprzegiel - // sprzeglo glowne (skrzynia biegow) - TorqueC = dizel_engageMaxForce * dizel_engage * dizel_engageDia * friction; - - if (hydro_TC) // jesli hydro - { - hydro_TCTorque(); - TorqueH = hydro_TC_TorqueOut; - TorqueL = hydro_TC_LockupTorque * hydro_TC_LockupRate; - } - else - { - TorqueH = 0; // brak przetwornika oznacza brak momentu - TorqueL = 1 + TorqueC * 2; // zabezpieczenie, polaczenie trwale - } - - // sprawdzanie dociskow poszczegolnych sprzegiel - if (abs(Moment) > std::min(TorqueC, TorqueL + abs(hydro_TC_TorqueIn)) || abs(dizel_n_old - enrot) > 0.1) // slizga sie z powodu roznic predkosci albo przekroczenia momentu - { - dizel_engagedeltaomega = enrot - dizel_n_old; - - if (TorqueC > TorqueL) - { - if (TorqueC > TorqueL + abs(TorqueH)) - { - hydro_TC_nOut = n; - gearMoment = TorqueL + abs(TorqueH) * sign(dizel_engagedeltaomega); - enMoment = Moment - (TorqueL + abs(hydro_TC_TorqueIn)) * sign(dizel_engagedeltaomega); - } - else - { - hydro_TC_nOut = enrot - (n - enrot) * (TorqueC - TorqueL) / TorqueH; // slizganie proporcjonalne, zeby przetwornik nadrabial - gearMoment = TorqueC * sign(dizel_engagedeltaomega); - enMoment = Moment - gearMoment; - } - } - else - { - hydro_TC_nOut = enrot; - gearMoment = TorqueC*sign(dizel_engagedeltaomega); - enMoment = Moment - gearMoment; - } - eps = enMoment / dizel_AIM; - newn = enrot + eps * dt; - if ((newn - n) * (enrot - dizel_n_old) < 0 && TorqueC > 0.1) // przejscie przez zero - slizgalo sie i przestało - newn = n; - if (newn * enrot <= 0 && eps * enrot < 0) // przejscie przez zero obrotow - newn = 0; - enrot = newn; - } - else // nie slizga sie (jeszcze) - { - dizel_engagedeltaomega = 0; - gearMoment = Moment; - double enrot_min = enrot - (std::min(TorqueC, TorqueL + abs(hydro_TC_TorqueIn)) - Moment) / dizel_AIM * dt; - double enrot_max = enrot + (std::min(TorqueC, TorqueL + abs(hydro_TC_TorqueIn)) + Moment) / dizel_AIM * dt; - enrot = safe_clamp(n, enrot_min, enrot_max); - } - if (hydro_R && hydro_R_Placement == 1) - gearMoment -= dizel_MomentumRetarder(hydro_TC_nOut, dt); - - if (enrot <= 0 && false == dizel_spinup) - { - // an engine stalling stops those started together with it, once. one already stopped, from its own switch or - // another vehicle's, or not started at all, has nothing to stop: it stays quiet, rather than stop every frame - // the engines started on their own or from the separate switches (eu07/maszyna#80) - if (true == Mains) - { - MainSwitch(false, MainSwitchRange()); - } - enrot = 0; - } - - dizel_n_old = n; // obecna predkosc katowa na potrzeby kolejnej klatki - - return gearMoment; -} - -// the torque converter filled and emptied, and its lockup clutch engaged and released, by the power and the speed -void TMoverParameters::hydro_TCFillCheck(double dt) -{ - if (hydro_TC) // jesli przetwornik momentu - { - // napelnianie przetwornika - bool IsPower = EIMCtrlType > 0 ? eimic_real > 0.005 : MainCtrlPowerPos() > 0; - if (IsPower && Mains && enrot > dizel_nmin * 0.9) - hydro_TC_Fill += hydro_TC_FillRateInc * dt; - // oproznianie przetwornika - if ((!IsPower && Vel < dizel_maxVelANS) || !Mains || enrot < dizel_nmin * 0.8) - hydro_TC_Fill -= hydro_TC_FillRateDec * dt; - // obcinanie zakresu - hydro_TC_Fill = std::clamp(hydro_TC_Fill, 0.0, 1.0); - - // blokowanie sprzegla blokującego - if (Vel > hydro_TC_LockupSpeed && Mains && enrot > 0.9 * dizel_nmin && IsPower) - { - hydro_TC_Lockup = true; - hydro_TC_LockupRate += hydro_TC_FillRateInc * dt; - } - // luzowanie sprzegla blokujacego - if (Vel < (IsPower ? hydro_TC_LockupSpeed : hydro_TC_UnlockSpeed) || !Mains || enrot < 0.8 * dizel_nmin) - { - hydro_TC_Lockup = false; - hydro_TC_LockupRate -= hydro_TC_FillRateDec * dt; - } - // obcinanie zakresu - hydro_TC_LockupRate = std::clamp(hydro_TC_LockupRate, 0.0, 1.0); - } - else - { - hydro_TC_Fill = 0.0; - hydro_TC_LockupRate = 0.0; - } -} - -// the torque converter's moments on its input and output shafts, by their revolutions and its fill -void TMoverParameters::hydro_TCTorque() -{ - double HydroTorque = 0; - HydroTorque += hydro_TC_nIn * hydro_TC_nIn * hydro_TC_TorqueInIn; - HydroTorque += (hydro_TC_nIn - hydro_TC_nOut) * hydro_TC_TorqueInOut; - HydroTorque += hydro_TC_nOut * hydro_TC_nOut * hydro_TC_TorqueOutOut; - double nOut2In = hydro_TC_nOut / std::max(0.01, hydro_TC_nIn); - if (hydro_TC_Table.size() > 1) - { - hydro_TC_TMRatio = TableInterpolation(hydro_TC_Table, nOut2In); - hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; - hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill * std::min(1.0, hydro_TC_TMRatio); - } - else - { - if (nOut2In < hydro_TC_CouplingPoint) - { - hydro_TC_TMRatio = 1 + (hydro_TC_TMMax - 1) * square(1 - nOut2In / hydro_TC_CouplingPoint); - hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill; - hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; - } - else - { - hydro_TC_TMRatio = (1 - nOut2In) / (1 - hydro_TC_CouplingPoint); - hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; - hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; - } - } -} - -double TMoverParameters::dizel_MomentumRetarder(double n, double dt) -{ - double RetarderRequest = Mains ? std::max(0.0, -eimic_real) : 0; - if (hydro_R_WithIndividual) - RetarderRequest = LocalBrakeRatio(); - if (Vel < hydro_R_MinVel) - RetarderRequest = 0; - if (hydro_R_Placement == 2 && enrot < dizel_nmin) - { - RetarderRequest = 0; - } - - hydro_R_ClutchActive = !hydro_R_Clutch || RetarderRequest > 0; - if (!hydro_R_Clutch || (hydro_R_ClutchActive && hydro_R_ClutchSpeed == 0)) - { - hydro_R_n = n * 60; - } - else if (hydro_R_ClutchActive) - { - hydro_R_n = sign(n) * std::min(std::abs(hydro_R_n + hydro_R_ClutchSpeed * dt), std::abs(n * 60)); - } - else - { - hydro_R_n = 0; - } - n = hydro_R_n / 60.f; - - if (hydro_R_Fill < RetarderRequest) // gdy zadane hamowanie - { - hydro_R_Fill = std::min(hydro_R_Fill + hydro_R_FillRateInc * dt, RetarderRequest); - } - else - { - hydro_R_Fill = std::max(hydro_R_Fill - hydro_R_FillRateDec * dt, RetarderRequest); - } - - double Moment = hydro_R_MaxTorque; - if (double pwr = Moment * std::abs(n) * M_PI * 2 * 0.001; pwr > hydro_R_MaxPower) - Moment = Moment * hydro_R_MaxPower / pwr; - double moment_in = n * n * hydro_R_TorqueInIn; - Moment = std::min(moment_in, Moment * hydro_R_Fill); - - hydro_R_Torque = Moment; - - return Moment; -} - -// sets component temperatures to specified value -void TMoverParameters::dizel_HeatSet(float const Value) -{ - - // TODO: don't include ambient temperature, pull it from environment data instead - dizel_heat.Te = Value; - dizel_heat.Ts = Value; - dizel_heat.To = Value; - dizel_heat.Tsr = Value; - dizel_heat.Twy = Value; - dizel_heat.Tsr2 = Value; - dizel_heat.Twy2 = Value; - dizel_heat.temperatura1 = Value; - dizel_heat.temperatura2 = Value; -} - -// calculates diesel engine temperature and heat transfers -// adapted from scripts written by adamst -// NOTE: originally executed twice per second -void TMoverParameters::dizel_Heat(double const dt) -{ - - auto const qs{44700.0}; - auto const Cs{11000.0}; - auto const Cw{4.189}; - auto const Co{1.885}; - auto const gwmin{400.0}; - auto const gwmax{4000.0}; - auto const gwmin2{400.0}; - auto const gwmax2{4000.0}; - - dizel_heat.Te = Global.AirTemperature; - - auto const engineon{(Mains ? 1 : 0)}; - auto const engineoff{(Mains ? 0 : 1)}; - auto const rpm{enrot * 60}; - // TODO: calculate this once and cache for further use, instead of doing it repeatedly all over the place - auto const revolutionsfactor{EngineRPMRatio()}; - auto const waterpump{WaterPump.is_active ? 1 : 0}; - - auto const gw = engineon * std::lerp(gwmin, gwmax, revolutionsfactor) + waterpump * 1000 + engineoff * 200; - auto const gw2 = engineon * std::lerp(gwmin2, gwmax2, revolutionsfactor) + waterpump * 1000 + engineoff * 200; - auto const gwO = std::lerp(gwmin, gwmax, revolutionsfactor); - - dizel_heat.water.is_cold = dizel_heat.water.config.temp_min > 0 && dizel_heat.temperatura1 < dizel_heat.water.config.temp_min - (Mains ? 5 : 0); - dizel_heat.water.is_hot = dizel_heat.water.config.temp_max > 0 && dizel_heat.temperatura1 > dizel_heat.water.config.temp_max - (dizel_heat.water.is_hot ? 8 : 0); - dizel_heat.water_aux.is_cold = dizel_heat.water_aux.config.temp_min > 0 && dizel_heat.temperatura2 < dizel_heat.water_aux.config.temp_min - (Mains ? 5 : 0); - dizel_heat.water_aux.is_hot = dizel_heat.water_aux.config.temp_max > 0 && dizel_heat.temperatura2 > dizel_heat.water_aux.config.temp_max - (dizel_heat.water_aux.is_hot ? 8 : 0); - dizel_heat.oil.is_cold = dizel_heat.oil.config.temp_min > 0 && dizel_heat.To < dizel_heat.oil.config.temp_min - (Mains ? 5 : 0); - dizel_heat.oil.is_hot = dizel_heat.oil.config.temp_max > 0 && dizel_heat.To > dizel_heat.oil.config.temp_max - (dizel_heat.oil.is_hot ? 8 : 0); - // engine overheat check - dizel_heat.engine_is_hot = dizel_heat.engine_max_temp > 0 && dizel_heat.Ts > dizel_heat.engine_max_temp - (dizel_heat.engine_is_hot ? 8 : 0); - - auto const PT = false == dizel_heat.water.is_cold && false == dizel_heat.water.is_hot && false == dizel_heat.water_aux.is_cold && false == dizel_heat.water_aux.is_hot && - false == dizel_heat.oil.is_cold && false == dizel_heat.oil.is_hot && false == dizel_heat.engine.is_hot /* && ( false == awaria_termostatow ) */ - /* || PTp */; - auto const PPT = false == PT /* && ( false == PPTp ) */; - dizel_heat.PA = /* ( ( !zamkniecie or niedomkniecie ) and !WBD ) || */ PPT /* || nurnik || ( woda < 7 ) */; - - // engine heat transfers - auto const Ge{engineon * (0.21 * dizel_heat.powerfactor * EnginePower + 12) / 3600}; - // TODO: replace fixed heating power cost with more accurate calculation - auto const obciazenie{engineon * (dizel_heat.powerfactor * EnginePower / 950 + (Heating ? HeatingPower : 0) + 70)}; - auto const Qd{qs * Ge - obciazenie}; - // silnik oddaje czesc ciepla do wody chlodzacej, a takze pewna niewielka czesc do otoczenia, modyfikowane przez okienko - auto const Qs{(Qd - dizel_heat.kfs * (dizel_heat.Ts - dizel_heat.Tsr) - dizel_heat.kfe * /* ( 0.3 + 0.7 * ( dizel_heat.okienko ? 1 : 0 ) ) * */ (dizel_heat.Ts - dizel_heat.Te))}; - auto const dTss{Qs / Cs}; - dizel_heat.Ts += static_cast(dTss * dt); - - // oil heat transfers - // olej oddaje cieplo do wody gdy krazy przez wymiennik ciepla == wlaczona pompka lub silnik - auto const dTo{(dizel_heat.auxiliary_water_circuit ? (dizel_heat.kfo * (dizel_heat.Ts - dizel_heat.To) - dizel_heat.kfo2 * (dizel_heat.To - dizel_heat.Tsr2)) / (gwO * Co) : - (dizel_heat.kfo * (dizel_heat.Ts - dizel_heat.To) - dizel_heat.kfo2 * (dizel_heat.To - dizel_heat.Tsr)) / (gwO * Co))}; - dizel_heat.To += static_cast(dTo * dt); - - // heater - /* - if( typ == "SP45" ) - Qp = (float)( podgrzewacz and ( true == WaterPump.is_active ) and ( Twy < 55 ) and ( Twy2 < 55 ) ) * 1000; - else - */ - auto const Qp = (true == WaterHeater.is_active && true == WaterPump.is_active && dizel_heat.Twy < 60 && dizel_heat.Twy2 < 60 ? 1 : 0) * 1000; - - auto const kurek07{1}; // unknown/unimplemented device TBD, TODO: identify and implement? - - if (true == dizel_heat.auxiliary_water_circuit) - { - // auxiliary water circuit setup - dizel_heat.water_aux.is_warm = true == dizel_heat.cooling || - (true == Mains && BatteryVoltage > 0.75 * NominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ - && dizel_heat.water_aux.config.temp_cooling > 0 && dizel_heat.temperatura2 > dizel_heat.water_aux.config.temp_cooling - (dizel_heat.water_aux.is_warm ? 8 : 0)); - auto const PTC2{(dizel_heat.water_aux.is_warm /*or PTC2p*/ ? 1 : 0)}; - dizel_heat.rpmwz2 = static_cast(PTC2 * (dizel_heat.fan_speed >= 0 ? rpm * dizel_heat.fan_speed : dizel_heat.fan_speed * -1)); - dizel_heat.zaluzje2 = dizel_heat.water_aux.config.shutters ? PTC2 == 1 : true; // no shutters is an equivalent to having them open - auto const zaluzje2{(dizel_heat.zaluzje2 ? 1 : 0)}; - // auxiliary water circuit heat transfer values - auto const kf2{kurek07 * (dizel_heat.kw * (0.3 + 0.7 * zaluzje2) * dizel_heat.rpmw2 + dizel_heat.kv * (0.3 + 0.7 * zaluzje2) * Vel / 3.6) + 2}; - auto const dTs2{dizel_heat.kfo2 * (dizel_heat.To - dizel_heat.Tsr2) / (gw2 * Cw)}; - // przy otwartym kurku B ma³y obieg jest dogrzewany przez du¿y - stosujemy przy korzystaniu z podgrzewacza oraz w zimie - auto const Qch2{-kf2 * (dizel_heat.Tsr2 - dizel_heat.Te) + 80 * (true == WaterCircuitsLink ? 1 : 0) * (dizel_heat.Twy - dizel_heat.Tsr2)}; - auto const dTch2{Qch2 / (gw2 * Cw)}; - // auxiliary water circuit heat transfers finalization - // NOTE: since primary circuit doesn't read data from the auxiliary one, we can pretty safely finalize auxiliary updates before touching the primary circuit - auto const Twe2{dizel_heat.Twy2 + dTch2 * dt}; - dizel_heat.Twy2 = static_cast(Twe2 + dTs2 * dt); - dizel_heat.Tsr2 = static_cast(0.5 * (dizel_heat.Twy2 + Twe2)); - dizel_heat.temperatura2 = dizel_heat.Twy2; - } - // primary water circuit setup - dizel_heat.water.is_flowing = dizel_heat.water.config.temp_flow < 0 || dizel_heat.temperatura1 > dizel_heat.water.config.temp_flow - (dizel_heat.water.is_flowing ? 5 : 0); - auto const obieg{(dizel_heat.water.is_flowing ? 1 : 0)}; - dizel_heat.water.is_warm = - true == dizel_heat.cooling || (true == Mains && BatteryVoltage > 0.75 * NominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ - && dizel_heat.water.config.temp_cooling > 0 && dizel_heat.temperatura1 > dizel_heat.water.config.temp_cooling - (dizel_heat.water.is_warm ? 8 : 0)); - auto const PTC1{(dizel_heat.water.is_warm /*or PTC1p*/ ? 1 : 0)}; - dizel_heat.rpmwz = static_cast(PTC1 * (dizel_heat.fan_speed >= 0 ? rpm * dizel_heat.fan_speed : dizel_heat.fan_speed * -1)); - dizel_heat.zaluzje1 = dizel_heat.water.config.shutters ? PTC1 == 1 : true; // no shutters is an equivalent to having them open - auto const zaluzje1{(dizel_heat.zaluzje1 ? 1 : 0)}; - // primary water circuit heat transfer values - auto const kf{obieg * kurek07 * (dizel_heat.kw * (0.3 + 0.7 * zaluzje1) * dizel_heat.rpmw + dizel_heat.kv * (0.3 + 0.7 * zaluzje1) * Vel / 3.6 + 3) + 2}; - auto const dTs{(dizel_heat.auxiliary_water_circuit ? dizel_heat.kfs * (dizel_heat.Ts - dizel_heat.Tsr) / (gw * Cw) : - (dizel_heat.kfs * (dizel_heat.Ts - dizel_heat.Tsr) + dizel_heat.kfo2 * (dizel_heat.To - dizel_heat.Tsr)) / (gw * Cw))}; - auto const Qch{-kf * (dizel_heat.Tsr - dizel_heat.Te) + Qp}; - auto const dTch{Qch / (gw * Cw)}; - // primary water circuit heat transfers finalization - auto const Twe{dizel_heat.Twy + dTch * dt}; - dizel_heat.Twy = static_cast(Twe + dTs * dt); - dizel_heat.Tsr = static_cast(0.5 * (dizel_heat.Twy + Twe)); - dizel_heat.temperatura1 = dizel_heat.Twy; - /* - fuelConsumed = fuelConsumed + ( Ge * 0.5 ); - - while( fuelConsumed >= 0.83 ) { - fuelConsumed = fuelConsumed - 0.83; - fuelQueue.DestroyProductMatching( null, 1 ); - }//if - - if( engineon ) - temp_turbo = temp_turbo + 0.3 * ( t_pozycja ); - if( t_pozycja == 0 and cisnienie > 0.04 ) - temp_turbo = temp_turbo - 1; - - if( temp_turbo > 400 ) - temp_turbo = 400; - if( temp_turbo < 0 ) - temp_turbo = 0; - - if( temp_turbo > 50 and cisnienie < 0.05 ) - timer_turbo = timer_turbo + 1; - - if( temp_turbo == 0 ) - timer_turbo = 0; - - if( timer_turbo > 360 ) { - awaria_turbo = true; - timer_turbo = 400; - } - - if( Ts < 50 ) - p_odpal = 3; - if( Ts > 49 and Ts < 76 ) - p_odpal = 4; - if( Ts > 75 ) - p_odpal = 7; - - stukanie = stukanie or awaria_oleju; - - if( awaria_oleju == true and ilosc_oleju > 0 ) { - ilosc_oleju = ilosc_oleju - ( 0.002 * rpm / 1500 ); - } - if( awaria_oleju == true and cisnienie < 0.06 ) - damage = 1; - */ -} - -bool TMoverParameters::AssignLoad(std::string const &Loadname, float const Amount) -{ - - if (Loadname == "pantstate") - { - if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector) - { - // wartość niby "pantstate" - nazwa dla formalności, ważna jest ilość - auto const pantographsetup{static_cast(Amount)}; - if (pantographsetup & 1 << 2) - { - DoubleTr = -1; - } - if (pantographsetup & 1 << 0) - { - if (DoubleTr == 1) - { - OperatePantographValve(end::front, operation_t::enable, range_t::local); - } - else - { - OperatePantographValve(end::rear, operation_t::enable, range_t::local); - } - } - if (pantographsetup & 1 << 1) - { - if (DoubleTr == 1) - { - OperatePantographValve(end::rear, operation_t::enable, range_t::local); - } - else - { - OperatePantographValve(end::front, operation_t::enable, range_t::local); - } - } - return true; - } - else - { - return false; - } - } - - if (Loadname.empty()) - { - // empty the vehicle if requested - LoadTypeChange = LoadType.name != Loadname; - LoadType = load_attributes(); - LoadAmount = 0.f; - return true; - } - // can't mix load types, at least for the time being - if (LoadAmount > 0 && LoadType.name != Loadname) - { - return false; - } - - auto const loadattributes = std::ranges::find_if(LoadAttributes, [&](auto const &attributes) { return attributes.name == Loadname; }); - if (loadattributes == std::end(LoadAttributes)) - { - // didn't find matching load configuration, this type is unsupported - return false; - } - LoadTypeChange = LoadType.name != Loadname; - LoadType = *loadattributes; - LoadAmount = safe_clamp(Amount, 0.f, MaxLoad); - ComputeMass(); - return true; -} - -// ************************************************************************************************* -// Q: 20160713 -// Test zakończenia załadunku / rozładunku -// ************************************************************************************************* -bool TMoverParameters::LoadingDone(double const LSpeed, std::string_view Loadname) -{ - - if (LSpeed == 0.0) - { - // zerowa prędkość zmiany, to koniec - LoadStatus = 4; - return true; - } - - if (Loadname.empty()) - { - return LoadStatus >= 4; - } - if (Loadname != LoadType.name) - { - return LoadStatus >= 4; - } - - // test zakończenia załadunku/rozładunku - // load exchange speed is reduced if the wagon is overloaded - auto const loadchange{static_cast(std::abs(LSpeed * LastLoadChangeTime) * (LoadAmount > MaxLoad ? 0.5 : 1.0))}; - - if (LSpeed < 0) - { - // gdy rozładunek - LoadStatus = 2; // trwa rozładunek (włączenie naliczania czasu) - if (loadchange > 0) // jeśli coś przeładowano - { - LastLoadChangeTime = 0; // naliczony czas został zużyty - LoadAmount -= loadchange; // zmniejszenie ilości ładunku - CommandIn.Value1 -= loadchange; // zmniejszenie ilości do rozładowania - if (LoadAmount <= 0 || CommandIn.Value1 <= 0) - { - // pusto lub rozładowano żądaną ilość - LoadStatus = 4; // skończony rozładunek - LoadAmount = safe_clamp(LoadAmount, 0.f, MaxLoad); // ładunek nie może być ujemny - } - if (LoadAmount == 0.f) - { - AssignLoad(""); // jak nic nie ma, to nie ma też nazwy - } - ComputeMass(); - } - } - else if (LSpeed > 0) - { - // gdy załadunek - LoadStatus = 1; // trwa załadunek (włączenie naliczania czasu) - if (loadchange > 0) // jeśli coś przeładowano - { - LastLoadChangeTime = 0; // naliczony czas został zużyty - LoadAmount += loadchange; // zwiększenie ładunku - CommandIn.Value1 -= loadchange; - if (LoadAmount >= MaxLoad * (1.0 + OverLoadFactor) || CommandIn.Value1 <= 0) - { - LoadStatus = 4; // skończony załadunek - LoadAmount = std::min(static_cast(MaxLoad * (1.0 + OverLoadFactor)), LoadAmount); - } - ComputeMass(); - } - } - - return LoadStatus >= 4; -} - -bool TMoverParameters::ChangeDoorPermitPreset(int const Change, range_t const Notify) -{ - - auto const initialstate{Doors.permit_preset}; - - if (false == Doors.permit_presets.empty()) - { - - Doors.permit_preset = safe_clamp(Doors.permit_preset + Change, 0, static_cast(Doors.permit_presets.size() - 1)); - auto const doors{Doors.permit_presets[Doors.permit_preset]}; - auto const permitleft{((doors & 1) != 0)}; - auto const permitright{((doors & 2) != 0)}; - - PermitDoors(CabActive > 0 ? side::left : side::right, permitleft, Notify); - PermitDoors(CabActive > 0 ? side::right : side::left, permitright, Notify); - } - - return Doors.permit_preset != initialstate; -} - -bool TMoverParameters::PermitDoorStep(bool const State, range_t const Notify) -{ - - auto const initialstate{Doors.step_enabled}; - - Doors.step_enabled = State; - if (Notify != range_t::local) - { - // wysłanie wyłączenia do pozostałych? - SendCtrlToNext("DoorStep", State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return Doors.step_enabled != initialstate; -} - -bool TMoverParameters::PermitDoors(side const Door, bool const State, range_t const Notify) -{ - - bool const initialstate{Doors.instances[Door].open_permit}; - - PermitDoors_(Door, State); - - if (Notify != range_t::local) - { - - SendCtrlToNext("DoorPermit", - (State ? 1 : -1) // positive: grant, negative: revoke - * (Door == (CabActive > 0 ? side::left : side::right) ? // 1=lewe, 2=prawe (swap if reversed) - 1 : - 2), - CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return Doors.instances[Door].open_permit != initialstate; -} - -void TMoverParameters::PermitDoors_(side const Door, bool const State) -{ - - if (State && State != Doors.instances[Door].open_permit) - { - SetFlag(SoundFlag, sound::doorpermit); - } - Doors.instances[Door].open_permit = State; -} - -bool TMoverParameters::ChangeDoorControlMode(bool const State, range_t const Notify) -{ - - auto const initialstate{Doors.remote_only}; - - Doors.remote_only = State; - if (Notify != range_t::local) - { - // wysłanie wyłączenia do pozostałych? - SendCtrlToNext("DoorMode", State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - if (true == State) - { - // when door are put in remote control mode they're automatically open - // TBD, TODO: make it dependant on config switch? - OperateDoors(side::left, true); - OperateDoors(side::right, true); - } - - return Doors.remote_only != initialstate; -} - -bool TMoverParameters::OperateDoors(side const Door, bool const State, range_t const Notify) -{ - - auto &door{Doors.instances[Door]}; - /* - if( ( State == true ? door.is_open : door.is_closed ) ) { - // TBD: should the command be passed to other vehicles regardless of whether it affected the primary target? - // (for the time being no, methods are often invoked blindly which would lead to commands spam) - return false; - } - */ - bool result{false}; - - if (Notify == range_t::local) - { - door.local_open = State; - door.local_close = false == State; - result = true; - } - else - { - // remote door operation signals require power to propagate - if (Power24vIsAvailable || Power110vIsAvailable) - { - door.remote_open = State; - door.remote_close = false == State; - result = true; - } - } - - if (Notify != range_t::local) - { - - SendCtrlToNext(State == true ? "DoorOpen" : "DoorClose", - Door == (CabActive > 0 ? side::left : side::right) ? // 1=lewe, 2=prawe (swap if reversed) - 1 : - 2, - CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return result; -} - -// toggle door lock -bool TMoverParameters::LockDoors(bool const State, range_t const Notify) -{ - - auto const initialstate{Doors.lock_enabled}; - - Doors.lock_enabled = State; - if (Notify != range_t::local) - { - // wysłanie wyłączenia do pozostałych? - SendCtrlToNext("DoorLock", State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return Doors.lock_enabled != initialstate; -} - -// toggles departure warning -bool TMoverParameters::signal_departure(bool const State, range_t const Notify) -{ - - if (DepartureSignal == State) - { - // TBD: should the command be passed to other vehicles regardless of whether it affected the primary target? - return false; - } - - DepartureSignal = State; - if (Notify != range_t::local) - { - // wysłanie wyłączenia do pozostałych? - SendCtrlToNext("DepartureSignal", State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return true; -} - -// state of the door closure signalling (SOD) of this vehicle: open while a door isn't fully closed, released while -// the closed doors can be opened (a permit given, or, for doors that need none, no lock engaged), locked otherwise. -// doors the crew doesn't close (autonomous) aren't signalled, the same as for the door lights of the consist -door_closure_t TMoverParameters::door_closure() const -{ - if (Doors.range == 0.f || Doors.close_control == control_t::autonomous) - { - return door_closure_t::none; - } - if (std::ranges::any_of(Doors.instances, [](basic_door const &Door) { return false == Door.is_closed; })) - { - return door_closure_t::open; - } - if (Doors.is_locked) - { - return door_closure_t::locked; - } - if (Doors.permit_needed && std::ranges::none_of(Doors.instances, [](basic_door const &Door) { return Door.open_permit; })) - { - return door_closure_t::locked; - } - return door_closure_t::released; -} - -bool TMoverParameters::door_closure_lamp_lit(door_closure_t const Consist, bool const BlinkLit) const -{ - return Doors.closure_signal ? door_closure_lamp(Consist, BlinkLit) : Doors.is_locked; -} - -bool door_closure_lamp(door_closure_t const State, bool const BlinkLit) -{ - switch (State) - { - case door_closure_t::locked: - return true; - case door_closure_t::released: - return BlinkLit; - default: - return false; - } -} - -// automatic door controller update -void TMoverParameters::update_doors(double const Deltatime) -{ - - if (Doors.range == 0.f) - { - return; - } // HACK: crude way to distinguish vehicles with actual doors - - // NBMX Obsluga drzwi, MC: zuniwersalnione - auto const localopencontrol{false == Doors.remote_only && (Doors.open_control == control_t::passenger || Doors.open_control == control_t::mixed)}; - auto const remoteopencontrol{Doors.open_control == control_t::driver || Doors.open_control == control_t::conductor || Doors.open_control == control_t::mixed}; - auto const localclosecontrol{false == Doors.remote_only && (Doors.close_control == control_t::passenger || Doors.close_control == control_t::mixed)}; - auto const remoteclosecontrol{Doors.close_control == control_t::driver || Doors.close_control == control_t::conductor || Doors.close_control == control_t::mixed}; - - Doors.is_locked = true == Doors.has_lock && true == Doors.lock_enabled && Vel >= Doors.doorLockSpeed; - - for (auto &door : Doors.instances) - { - update_door_requests(door, localopencontrol, remoteopencontrol, localclosecontrol, remoteclosecontrol); - move_door(door, Deltatime); - } - - if (false == Doors.instances[side::right].is_open && false == Doors.instances[side::left].is_open) - { - return; - } - - if (Doors.auto_duration > 0.f) - { - update_door_timers(Deltatime); - } - /* - // the door are closed if their timer goes below 0, or if the vehicle is moving faster than defined threshold - std::array const doorids { side::right, side::left }; - for( auto const doorid : doorids ) { - auto const &door { Doors.instances[ doorid ] }; - if( true == door.is_open ) { - if( ( ( Doors.auto_velocity != -1.f ) && ( Vel > Doors.auto_velocity ) ) - || ( ( door.auto_timer != -1.f ) && ( door.auto_timer <= 0.f ) ) ) { - // close the door and set the timer to expired state (closing may happen sooner if vehicle starts moving) - OperateDoors( doorid, false, range_t::local ); - } - } - } - */ -} - -// the permit, the state and the requests of a door, and whether it and its step open or close -void TMoverParameters::update_door_requests(basic_door &door, bool const localopencontrol, bool const remoteopencontrol, bool const localclosecontrol, bool const remoteclosecontrol) -{ - // revoke permit if... - door.open_permit = true == door.open_permit // ...we already have one... - && (false == Doors.permit_presets.empty() // ...there's no preset switch controlling permit state... - || (false == Doors.is_locked // ...and the door lock is engaged... - && false == door.remote_close)); // ...or the door is about to be closed - - door.is_open = door.position >= Doors.range && (false == Doors.step_enabled || door.step_position >= (Doors.step_range != 0.f ? 1.f : 0.f)); - door.is_closed = door.position <= 0.f && door.step_position <= 0.f; - door.is_door_closed = door.position <= 0.f; - - door.local_open = door.local_open && false == door.is_open && (false == Doors.permit_needed || door.open_permit); - door.remote_open = (door.remote_open || Doors.remote_only) && false == door.is_open && (false == Doors.permit_needed || door.open_permit); - door.local_close = door.local_close && false == door.is_closed && (false == remoteopencontrol || false == door.remote_open); - door.remote_close = door.remote_close && false == door.is_closed && (false == localopencontrol || false == door.local_open); - - auto const openrequest{door_open_request(door, localopencontrol, remoteopencontrol)}; - auto const closerequest{door_close_request(door, localclosecontrol, remoteclosecontrol)}; - auto const ispowered{doors_powered()}; - - door.is_opening = false == door.is_open && true == ispowered && false == closerequest && (true == door.is_opening || (true == openrequest && false == Doors.is_locked)); - door.is_closing = false == door.is_closed && true == ispowered && false == openrequest && (door.is_closing || closerequest); - door.step_unfolding = Doors.step_range != 0.f && Doors.step_enabled && false == Doors.is_locked && door.step_position < 1.f && door.is_opening; - door.step_folding = door_step_folding(door); - - if (true == door.is_opening) - { - door.auto_timer = door_open_duration(door, localopencontrol, remoteopencontrol); - } -} - -// whether the door is asked to open, by the passengers, from afar or by itself -bool TMoverParameters::door_open_request(basic_door const &door, bool const localopencontrol, bool const remoteopencontrol) const -{ - auto const autoopenrequest{Doors.open_control == control_t::autonomous && (false == Doors.permit_needed || door.open_permit)}; - return (localopencontrol && door.local_open) || (remoteopencontrol && door.remote_open) || (autoopenrequest && false == door.is_open); -} - -// whether the door is asked to close, by the passengers, from afar, or by itself: over the speed, after its time or -// with its permit taken back -bool TMoverParameters::door_close_request(basic_door const &door, bool const localclosecontrol, bool const remoteclosecontrol) const -{ - auto const autocloserequest{(Doors.auto_velocity != -1.f && Vel > Doors.auto_velocity) || (door.auto_timer != -1.f && door.auto_timer <= 0.f) || - (Doors.permit_needed && false == door.open_permit)}; - return (door.remote_close && remoteclosecontrol) || (door.local_close && localclosecontrol) || (autocloserequest && door.is_open); -} - -// whether the doors have the voltage they work on -bool TMoverParameters::doors_powered() const -{ - if (Doors.voltage == 0) - { - return true; - } - if (Doors.voltage == 24) - { - return Power24vIsAvailable || Power110vIsAvailable; - } - return Doors.voltage == 110 && Power110vIsAvailable; -} - -// whether the unfolded step folds: without the permission to stay out, or with the door closing, once it's about to -// close or closed -bool TMoverParameters::door_step_folding(basic_door const &door) const -{ - auto const unfolded{door.step_position > 0.f}; - auto const mayfold{false == Doors.step_enabled || (Doors.permit_needed ? false == door.open_permit : door.is_closing)}; - return unfolded && mayfold && (door.close_delay > Doors.close_delay || door.position <= 0.f); -} - -// how long the opening door stays open: the time of the doors, for the passengers' opening and, if it counts, the -// opening from afar; none otherwise -float TMoverParameters::door_open_duration(basic_door const &door, bool const localopencontrol, bool const remoteopencontrol) const -{ - if (localopencontrol && door.local_open) - { - return Doors.auto_duration; - } - if (remoteopencontrol && door.remote_open && Doors.auto_include_remote) - { - return Doors.auto_duration; - } - return -1.f; -} - -// a door and its step moved as they open or close -void TMoverParameters::move_door(basic_door &door, double const Deltatime) -{ - // doors - if (true == door.is_opening) - { - // open door - if (false == door.step_unfolding // no wait if no doorstep - || Doors.step_type == 2) - { // no wait for rotating doorstep - door.open_delay += static_cast(Deltatime); - if (door.open_delay > Doors.open_delay) - { - door.position = std::min(Doors.range, static_cast(door.position + Doors.open_rate * Deltatime)); - } - } - door.close_delay = 0.f; - } - if (true == door.is_closing) - { - // close door - door.close_delay += static_cast(Deltatime); - if (door.close_delay > Doors.close_delay) - { - door.position = std::max(0.f, static_cast(door.position - Doors.close_rate * Deltatime)); - } - door.open_delay = 0.f; - } - // doorsteps - if (door.step_unfolding) - { - // unfold left doorstep - door.step_position = std::min(1.f, static_cast(door.step_position + Doors.step_rate * Deltatime)); - } - if (door.step_folding) - { - // fold left doorstep - if (is_multiple_unit()) - { - // multi-unit vehicles typically fold the doorstep only after closing the door - if (door.position <= 0.f) - { - door.step_position = std::max(0.f, static_cast(door.step_position - Doors.step_rate * Deltatime)); - } - } - else - { - door.step_position = std::max(0.f, static_cast(door.step_position - Doors.step_rate * Deltatime)); - } - } -} - -// the timers of the open doors which close after a while, kept running while the load is exchanged -void TMoverParameters::update_door_timers(double const Deltatime) -{ - // update door timers if the door close after defined time - for (auto &door : Doors.instances) - { - - if (false == door.is_open) - { - continue; - } - - if (door.auto_timer > 0.f) - { - door.auto_timer -= static_cast(Deltatime); - } - // if there's load exchange in progress, reset the timer(s) for already open doors - if (door.auto_timer != -1.f && (LoadStatus & (2 | 1)) != 0) - { - door.auto_timer = Doors.auto_duration; - } - } -} - -// ************************************************************************************************* -// Q: 20160713 -// Przesuwa pojazd o podaną wartość w bok względem toru (dla samochodów) -// ************************************************************************************************* -bool TMoverParameters::ChangeOffsetH(double DeltaOffset) -{ - bool COH = false; - if (TestFlag(CategoryFlag, 2) && TestFlag(RunningTrack.CategoryFlag, 2)) - { - OffsetTrackH = OffsetTrackH + DeltaOffset; - // if (abs(OffsetTrackH) > (RunningTrack.Width / 1.95 - TrackW / 2.0)) - if (abs(OffsetTrackH) > 0.5 * (RunningTrack.Width - Dim.W) - 0.05) // Ra: może pół pojazdu od brzegu? - COH = false; // kola na granicy drogi - else - COH = true; - } - else - COH = false; - - return COH; -} - -// ************************************************************************************************* -// Q: 20160713 -// Testuje zmienną (narazie tylko 0) i na podstawie uszkodzenia zwraca informację tekstową -// ************************************************************************************************* -std::string TMoverParameters::EngineDescription(int what) const -{ - std::string outstr{"OK"}; - if (what == 0) - { - if (DamageFlag == 255) - { - outstr = "WRECKED"; - } - else - { - if (TestFlag(DamageFlag, dtrain_thinwheel)) - { - if (Power > 0.1) - outstr = "Thin wheel"; - else - outstr = "Load shifted"; - } - if (WheelFlat > 5.0 || TestFlag(DamageFlag, dtrain_wheelwear)) - { - outstr = "Wheel wear"; - } - if (TestFlag(DamageFlag, dtrain_bearing)) - { - outstr = "Bearing damaged"; - } - if (TestFlag(DamageFlag, dtrain_coupling)) - { - outstr = "Coupler broken"; - } - if (TestFlag(DamageFlag, dtrain_loaddamage)) - { - if (Power > 0.1) - outstr = "Ventilator damaged"; - else - outstr = "Load damaged"; - } - if (TestFlag(DamageFlag, dtrain_loaddestroyed)) - { - if (Power > 0.1) - outstr = "Engine damaged"; - else - outstr = "LOAD DESTROYED"; - } - if (TestFlag(DamageFlag, dtrain_axle)) - { - outstr = "Axle broken"; - } - if (TestFlag(DamageFlag, dtrain_out)) - { - outstr = "DERAILED"; - } - } - } - else - { - outstr = "Invalid qualifier"; - } - return outstr; -} - -// ************************************************************************************************* -// Q: 20160709 -// Funkcja zwracajaca napiecie dla calego skladu, przydatna dla EZT -// ************************************************************************************************* -double TMoverParameters::GetTrainsetVoltage(int const Coupling) const -{ // ABu: funkcja zwracajaca napiecie dla calego skladu, przydatna dla EZT - // TBD, TODO: call once per vehicle update, return cached results? - std::array voltages{0.0, 0.0}; - for (int end = end::front; end <= end::rear; ++end) - { - if (Couplers[end].Connected == nullptr) - { - continue; - } - auto const &thiscoupler{Couplers[end]}; - if (auto const fullcoupling{thiscoupler.CouplingFlag | (TestFlag(thiscoupler.CouplingFlag, thiscoupler.PowerCoupling) ? thiscoupler.PowerFlag : 0)}; (fullcoupling & Coupling) == 0) - { - continue; - } - auto const *connectedpowercoupling = (Coupling & (coupling::highvoltage | coupling::heating)) != 0 ? &thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr].power_high : - (Coupling & coupling::power110v) != 0 ? &thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr].power_110v : - (Coupling & coupling::power24v) != 0 ? &thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr].power_24v : - nullptr; - if (connectedpowercoupling != nullptr && connectedpowercoupling->is_live) - { - voltages[end] = connectedpowercoupling->voltage; - } - } - return std::max(voltages[end::front], voltages[end::rear]); -} - -double TMoverParameters::GetTrainsetHighVoltage() const -{ - - return std::max(GetTrainsetVoltage(coupling::highvoltage), HeatingAllow ? GetTrainsetVoltage(coupling::heating) : 0.0); -} - -// ************************************************************************************************* -// whether the vehicle accelerates, for the test which turns the physics off in vehicles standing still -// ************************************************************************************************* -bool TMoverParameters::accelerating() const -{ - if (std::abs(AccS) <= 0.0001) - return false; - // standing still and held by the brakes and the resistance, against the slope and the couplers: the test ComputeMovement() - // sets the speed to zero by. the forces are of the last ComputeTotalForce(), the ones the movement went by. a vehicle whose - // brake cylinders still fill or release isn't held yet: asleep, it would keep the brake force (and the pressure the AI waits on - // to set off) it had when it fell asleep. 0.05 bar/s is less than a distributor moves the cylinder when it applies or releases, and - // more than the leaks take - auto const held{Global.physics_sleepheld && Vel <= 0.0001 && std::abs(FStand) > std::abs(FTrain) && BrakePressRate <= 0.05}; - return false == held; -} - -void TMoverParameters::wake_for_brake() -{ - if (Global.physics_sleepheld) - { - switch_physics(true, wake_cause::command); - } -} - -// ************************************************************************************************* -// whether the brakes of a vehicle whose physics sleeps have changed since it fell asleep: the pressure in the brake cylinders -// or in the one of the spring brake by more than 0.05 bar, the hand brake by a notch, or the local brake by 1 percent. the brake system -// itself steps on while asleep in the vehicle the user is in (TDynamicObject::Update(), MechInside); the settings change by -// hand or by a command in any vehicle. 0.05 bar is less than what a distributor applying or releasing moves the cylinder by in -// a second, and much less than the pressure the cylinder's return spring takes (BrakeCylSpring, some tenths of a bar), below -// which the cylinder gives no force: a release ends with the vehicle asleep and no force left. a cylinder holding its -// pressure, or settling within that, leaves the vehicle asleep -// ************************************************************************************************* -bool TMoverParameters::brakes_changed_asleep() const -{ - if (PhysicActivation) - return false; - constexpr double pressure_change{0.05}; // [bar] - return std::abs(BrakePress - sleep_brakes.cylinder) > pressure_change || std::abs(SpringBrake.SBP - sleep_brakes.spring) > pressure_change || - ManualBrakePos != sleep_brakes.manual || std::abs(LocalBrakePosA - sleep_brakes.local) > 0.01; -} - -// ************************************************************************************************* -// Kasowanie zmiennych pracy fizyki -// ************************************************************************************************* -bool TMoverParameters::switch_physics(bool const State, wake_cause const Cause) // DO PRZETLUMACZENIA NA KONCU -{ - if (PhysicActivation == State) - { - return false; - } - - PhysicActivation = State; - if (true == State) - { - LastSwitchingTime = 0; - Timer::subsystem.switching.note(static_cast(Timer::switching_counter::wake + static_cast(Cause)), this, &TypeName, &Name); - } - else - { - // what the brake force of the last step came from, which it keeps while asleep (brakes_changed_asleep()) - sleep_brakes = {BrakePress, SpringBrake.SBP, ManualBrakePos, LocalBrakePosA}; - } - - return true; -} - -// ************************************************************************************************* -// FUNKCJE PARSERA WCZYTYWANIA PLIKU FIZYKI POJAZDU -// ************************************************************************************************* -bool startBPT; -bool startMPT; -bool startMPT0; -bool startRLIST; -bool startUCLIST; -bool startDIZELMOMENTUMLIST; -bool startDIZELV2NMAXLIST; -bool startHYDROTCLIST; -bool startPMAXLIST; -bool startDLIST; -bool startFFLIST; -bool startWWLIST; -bool startWiperList; -bool startDimmerList; -bool startFFEDLIST; -bool startLIGHTSLIST; -bool startCOMPRESSORLIST; -int LISTLINE; - -bool issection(std::string_view Name, std::string_view Input) -{ - - return Input.compare(0, Name.size(), Name) == 0; -} - -int s2NPW(std::string s) -{ // wylicza ilosc osi napednych z opisu ukladu osi - const char A = 64; - int NPW = 0; - for (char const chentry : s) - { - if (chentry >= (char)65 && chentry <= (char)90) - NPW += chentry - A; - } - return NPW; -} - -int s2NNW(std::string s) -{ // wylicza ilosc osi nienapedzanych z opisu ukladu osi - const char Zero = 48; - int NNW = 0; - for (char const ch : s) - { - if (ch >= (char)49 && ch <= (char)57) - NNW += ch - Zero; - } - return NNW; -} - -// ************************************************************************************************* -// Q: 20160717 -// ************************************************************************************************* -// parsowanie Motor Param Table -// checks a motor parameter table position read from the .fiz file against the table size -static bool is_valid_mpt_index(int const Index) -{ - if (Index >= 0 && Index <= MotorParametersArraySize) - { - return true; - } - WriteLog("Read MPT: position " + std::to_string(Index) + " out of range 0-" + std::to_string(MotorParametersArraySize) + " in line " + std::to_string(LISTLINE)); - return false; -} - -bool TMoverParameters::readMPT0(std::string const &line) -{ - - // TBD, TODO: split into separate functions similar to readMPT if more varied schemes appear? - cParser parser(line); - if (false == parser.getTokens(7, false)) - { - WriteLog("Read MPT0: arguments missing in line " + std::to_string(LISTLINE)); - return false; - } - int idx = 0; // numer pozycji - parser >> idx; - if (false == is_valid_mpt_index(idx)) - { - return false; - } - if (EngineType == TEngineType::DieselEngine) - { - parser >> MotorParam[idx].mIsat >> MotorParam[idx].fi0 >> MotorParam[idx].fi >> MotorParam[idx].mfi0 >> MotorParam[idx].mfi >> MotorParam[idx].Isat; - } - else - { - parser >> MotorParam[idx].mfi >> MotorParam[idx].mIsat >> MotorParam[idx].mfi0 >> MotorParam[idx].fi >> MotorParam[idx].Isat >> MotorParam[idx].fi0; - } - if (true == parser.getTokens(1, false)) - { - int autoswitch{0}; - parser >> autoswitch; - MotorParam[idx].AutoSwitch = autoswitch == 1; - } - else - { - MotorParam[idx].AutoSwitch = false; - } - return true; -} - -bool TMoverParameters::readMPT(std::string const &line) -{ - - ++LISTLINE; - - switch (EngineType) - { - - case TEngineType::ElectricSeriesMotor: - { - return readMPTElectricSeries(line); - } - case TEngineType::DieselElectric: - { - return readMPTDieselElectric(line); - } - case TEngineType::DieselEngine: - { - return readMPTDieselEngine(line); - } - default: - { - return false; - } - } -} - -bool TMoverParameters::readMPTElectricSeries(std::string const &line) -{ - - cParser parser(line); - if (false == parser.getTokens(5, false)) - { - WriteLog("Read MPT: arguments missing in line " + std::to_string(LISTLINE)); - return false; - } - int idx = 0; // numer pozycji - parser >> idx; - if (false == is_valid_mpt_index(idx)) - { - return false; - } - parser >> MotorParam[idx].mfi >> MotorParam[idx].mIsat >> MotorParam[idx].fi >> MotorParam[idx].Isat; - if (true == parser.getTokens(1, false)) - { - int autoswitch{0}; - parser >> autoswitch; - MotorParam[idx].AutoSwitch = autoswitch == 1; - } - else - { - MotorParam[idx].AutoSwitch = false; - } - return true; -} - -bool TMoverParameters::readMPTDieselElectric(std::string const &line) -{ - - cParser parser(line); - if (false == parser.getTokens(7, false)) - { - WriteLog("Read MPT: arguments missing in line " + std::to_string(LISTLINE)); - return false; - } - int idx = 0; // numer pozycji - parser >> idx; - if (false == is_valid_mpt_index(idx)) - { - return false; - } - parser >> MotorParam[idx].mfi >> MotorParam[idx].mIsat >> MotorParam[idx].fi >> MotorParam[idx].Isat >> MPTRelay[idx].Iup >> MPTRelay[idx].Idown; - - return true; -} - -bool TMoverParameters::readMPTDieselEngine(std::string const &line) -{ - - cParser parser(line); - if (false == parser.getTokens(4, false)) - { - WriteLog("Read MPT: arguments missing in line " + std::to_string(LISTLINE)); - return false; - } - int idx = 0; // numer pozycji - parser >> idx; - if (false == is_valid_mpt_index(idx)) - { - return false; - } - parser >> MotorParam[idx].mIsat >> MotorParam[idx].fi >> MotorParam[idx].mfi; - if (true == parser.getTokens(1, false)) - { - int autoswitch{0}; - parser >> autoswitch; - MotorParam[idx].AutoSwitch = autoswitch == 1; - } - else - { - MotorParam[idx].AutoSwitch = false; - } - return true; -} - -bool TMoverParameters::readBPT(std::string const &line) -{ - - cParser parser(line); - if (false == parser.getTokens(5, false)) - { - - WriteLog("Read BPT: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - ++LISTLINE; - std::string braketype; - int idx = 0; - parser >> idx; - parser >> BrakePressureTable[idx].PipePressureVal >> BrakePressureTable[idx].BrakePressureVal >> BrakePressureTable[idx].FlowSpeedVal >> braketype; - if (braketype == "Pneumatic") - { - BrakePressureTable[idx].BrakeType = TBrakeSystem::Pneumatic; - } - else if (braketype == "ElectroPneumatic") - { - BrakePressureTable[idx].BrakeType = TBrakeSystem::ElectroPneumatic; - } - else - { - BrakePressureTable[idx].BrakeType = TBrakeSystem::Individual; - } - - return true; -} - -bool TMoverParameters::readRList(std::string const &Input) -{ - - cParser parser(Input); - if (false == parser.getTokens(5, false)) - { - - WriteLog("Read RList: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - auto idx = LISTLINE++; - if (idx >= std::size(RList)) - { - WriteLog("Read RList: number of entries exceeded capacity of the data table"); - return false; - } - parser >> RList[idx].Relay >> RList[idx].R >> RList[idx].Bn >> RList[idx].Mn >> RList[idx].AutoSwitch; - - if (true == parser.getTokens(1, false)) - { - parser >> RList[idx].ScndAct; - } - else - { - RList[idx].ScndAct = 0; - } - - return true; -} - -bool TMoverParameters::readUCList(std::string const &line) -{ - - cParser parser(line); - parser.getTokens(10, false); - auto idx = LISTLINE++; - if (idx >= std::size(UniCtrlList)) - { - WriteLog("Read UCList: number of entries exceeded capacity of the data table"); - return false; - } - int i = 0; - parser >> i >> UniCtrlList[idx].mode >> UniCtrlList[idx].MinCtrlVal >> UniCtrlList[idx].MaxCtrlVal >> UniCtrlList[idx].SetCtrlVal >> UniCtrlList[idx].SpeedUp >> UniCtrlList[idx].SpeedDown >> - UniCtrlList[idx].ReturnPosition >> UniCtrlList[idx].NextPosFastInc >> UniCtrlList[idx].PrevPosFastDec; - - return true; -} - -bool TMoverParameters::readDList(std::string const &line) -{ - - cParser parser(line); - parser.getTokens(3, false); - auto idx = LISTLINE++; - if (idx >= std::size(RList)) - { - WriteLog("Read DList: number of entries exceeded capacity of the data table"); - return false; - } - parser >> RList[idx].Relay >> RList[idx].R >> RList[idx].Mn; - - return true; -} - -bool TMoverParameters::readDMList(std::string const &line) -{ - - cParser parser(line); - if (false == parser.getTokens(2, false)) - { - - WriteLog("Read DMList: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - ++LISTLINE; - double x = 0.0; - double y = 0.0; - parser >> x >> y; - - dizel_Momentum_Table.emplace(x / 60.0, y); - - return true; -} - -bool TMoverParameters::readV2NMAXList(std::string const &line) -{ - - cParser parser(line); - if (false == parser.getTokens(2, false)) - { - - WriteLog("Read V2nmaxList: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - ++LISTLINE; - double x = 0.0; - double y = 0.0; - parser >> x >> y; - - dizel_vel2nmax_Table.emplace(x, y / 60.0); - - return true; -} - -bool TMoverParameters::readHTCList(std::string const &line) -{ - - cParser parser(line); - if (false == parser.getTokens(2, false)) - { - - WriteLog("Read HTCList: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - ++LISTLINE; - double x = 0.0; - double y = 0.0; - parser >> x >> y; - - hydro_TC_Table.emplace(x, y); - - return true; -} - -bool TMoverParameters::readPmaxList(std::string const &line) -{ - - cParser parser(line); - if (false == parser.getTokens(2, false)) - { - - WriteLog("Read PmaxList: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - ++LISTLINE; - double x = 0.0; - double y = 0.0; - parser >> x >> y; - - EIM_Pmax_Table.emplace(x, y); - - return true; -} - -bool TMoverParameters::readFFList(std::string const &line) -{ - - cParser parser(line); - if (false == parser.getTokens(2, false)) - { - WriteLog("Read FList: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - int idx = LISTLINE++; - if (idx >= std::size(FFlist)) - { - WriteLog("Read FList: number of entries exceeded capacity of the data table"); - return false; - } - parser >> FFlist[idx].v >> FFlist[idx].freq; - - return true; -} - -bool TMoverParameters::readFFEDList(std::string const &line) -{ - - cParser parser(line); - if (false == parser.getTokens(2, false)) - { - WriteLog("Read FList: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - int idx = LISTLINE++; - if (idx >= std::size(FFEDlist)) - { - WriteLog("Read FList: number of entries exceeded capacity of the data table"); - return false; - } - parser >> FFEDlist[idx].v >> FFEDlist[idx].freq; - - return true; -} - -// parsowanie wiperList -bool TMoverParameters::readWiperList(std::string const &line) -{ - cParser parser(line); - if (false == parser.getTokens(4, false)) - { - WriteLog("Read WiperList: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - int idx = LISTLINE++; - if (idx >= std::size(WiperList)) - { - WriteLog("Read WiperList: number of entries exceeded capacity of the data table"); - return false; - } - parser >> WiperList[idx].byteSum >> WiperList[idx].WiperSpeed >> WiperList[idx].interval >> WiperList[idx].outBackDelay; - return true; -} - -bool TMoverParameters::readDimmerList(std::string const &line) -{ - cParser parser(line); - if (false == parser.getTokens(3, false)) - { - WriteLog("Read DimmerList: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - ++LISTLINE; - - dimPosition dps; - parser >> dps.isHighBeam >> dps.isDimmed >> dps.isOff; - dimPositions.push_back(dps); - return true; -} - -int TMoverParameters::clampDimmerPosition(int const Position) const -{ - if (dimPositions.empty()) - { - return 0; - } - return std::clamp(Position, 0, static_cast(dimPositions.size()) - 1); -} - -TMoverParameters::dimPosition TMoverParameters::currentDimPosition() const -{ - if (modernDimmerPosition < 0 || modernDimmerPosition >= static_cast(dimPositions.size())) - { - return {}; - } - return dimPositions[modernDimmerPosition]; -} - -bool TMoverParameters::stepDimmerPosition(int const Step) -{ - if (dimPositions.empty()) - { - return false; - } - auto const last{static_cast(dimPositions.size()) - 1}; - auto const current{clampDimmerPosition(modernDimmerPosition)}; - auto next{current + Step}; - if (next < 0 || next > last) - { - if (false == modernDimmerCanCycle) - { - next = current; - } - else - { - next = (next < 0 ? last : 0); - } - } - if (next == modernDimmerPosition) - { - return false; - } - modernDimmerPosition = next; - return true; -} - -// parsowanie WWList -bool TMoverParameters::readWWList(std::string const &line) -{ - - cParser parser(line); - if (false == parser.getTokens(4, false)) - { - WriteLog("Read WWList: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - int idx = LISTLINE++; - if (idx >= std::size(DElist)) - { - WriteLog("Read WWList: number of entries exceeded capacity of the data table"); - return false; - } - parser >> DElist[idx].RPM >> DElist[idx].GenPower >> DElist[idx].Umax >> DElist[idx].Imax; - - if (true == parser.getTokens(3, false)) - { - // optional parameters for shunt mode - parser >> SST[idx].Umin >> SST[idx].Umax >> SST[idx].Pmax; - - SST[idx].Pmin = std::sqrt(std::pow(SST[idx].Umin, 2) / 47.6); - SST[idx].Pmax = std::min(SST[idx].Pmax, std::pow(SST[idx].Umax, 2) / 47.6); - } - return true; -} - -bool TMoverParameters::readLightsList(std::string const &Input) -{ - - cParser parser(Input); - if (false == parser.getTokens(2, false)) - { - WriteLog("Read LightsList: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - int idx = LISTLINE++; - if (idx > 16) - { - WriteLog("Read LightsList: number of entries exceeded capacity of the data table"); - return false; - } - parser >> Lights[0][idx] >> Lights[1][idx]; - // optional third column: the cab interior light the preset sets (eu07/maszyna#529). anything but a whole number - // (some rows carry stray notes after the two columns) leaves the cab light to its own switch - LightsCabLight[idx] = -1; - if (true == parser.getTokens(1, false)) - { - std::string cablight; - parser >> cablight; - int flags{-1}; - auto const [end, error]{std::from_chars(cablight.data(), cablight.data() + cablight.size(), flags)}; - if (error == std::errc{} && end == cablight.data() + cablight.size() && flags >= 0) - { - LightsCabLight[idx] = flags; - } - } - - return true; -} - -std::optional TMoverParameters::LightsPresetCabLight(int const Position) const -{ - if (Position < 1 || Position > static_cast(LightsCabLight.size())) - { - return std::nullopt; - } - auto const flags{LightsCabLight[Position - 1]}; - if (flags < 0) - { - return std::nullopt; - } - return lights_preset_cablight{(flags & lights_preset_cablight::light_on) != 0, (flags & lights_preset_cablight::light_dimmed) != 0}; -} - -bool TMoverParameters::readCompressorList(std::string const &Input) -{ - - cParser parser(Input); - if (false == parser.getTokens(4, false)) - { - WriteLog("Read CompressorList: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - int idx = LISTLINE++; - if (idx > 8 - 1) - { - WriteLog("Read CompressorList: number of entries exceeded capacity of the data table"); - return false; - } - // NOTE: content of slot [x][0] is hardcoded elsewhere - parser >> CompressorList[0][idx + 1] >> CompressorList[1][idx + 1] >> CompressorList[2][idx + 1] >> CompressorList[3][idx + 1]; - - return true; -} - -// ************************************************************************************************* -// Q: 20160719 -// ************************************************************************************************* -void TMoverParameters::BrakeValveDecode(std::string const &Valve) -{ - using enum TBrakeValve; - - std::map> valvetypes{{"W", W}, - {"W_Lu_L", W_Lu_L}, - {"W_Lu_XR", W_Lu_XR}, - {"W_Lu_VI", W_Lu_VI}, - {"K", K}, - {"Kg", Kg}, - {"Kp", Kp}, - {"Kss", Kss}, - {"Kkg", Kkg}, - {"Kkp", Kkp}, - {"Kks", Kks}, - {"Hikp1", Hikp1}, - {"Hikss", Hikss}, - {"Hikg1", Hikg1}, - {"KE", KE}, - {"SW", SW}, - {"EStED", EStED}, - {"NESt3", NESt3}, - {"ESt3", ESt3}, - {"LSt", LSt}, - {"ESt4", ESt4}, - {"ESt3AL2", ESt3AL2}, - {"EP1", EP1}, - {"EP2", EP2}, - {"M483", M483}, - {"CV1_L_TR", CV1_L_TR}, - {"CV1", CV1}, - {"CV1_R", CV1_R}}; - auto lookup = valvetypes.find(Valve); - BrakeValve = lookup != valvetypes.end() ? lookup->second : Other; - - if (BrakeValve == Other && contains(Valve, "ESt")) - { - - BrakeValve = ESt3; - } -} - -// ************************************************************************************************* -// Q: 20160719 -// ************************************************************************************************* -void TMoverParameters::BrakeSubsystemDecode() -{ - using enum TBrakeSubSystem; - BrakeSubsystem = ss_None; - switch (BrakeValve) - { - using enum TBrakeValve; - case W: - case W_Lu_L: - case W_Lu_VI: - case W_Lu_XR: - BrakeSubsystem = ss_W; - break; - case ESt3: - case ESt3AL2: - case ESt4: - case EP2: - case EP1: - BrakeSubsystem = ss_ESt; - break; - case KE: - BrakeSubsystem = ss_KE; - break; - case CV1: - case CV1_L_TR: - BrakeSubsystem = ss_Dako; - break; - case LSt: - case EStED: - BrakeSubsystem = ss_LSt; - break; - default: - break; - } -} - -// ************************************************************************************************* -// Q: 20160717 -// Funkcja pelniaca role pierwotnej LoadChkFile wywolywana w dynobj.cpp w double -// TDynamicObject::Init() -// Po niej wykonywana jest CreateBrakeSys(), ktora jest odpowiednikiem CheckLocomotiveParameters() -// ************************************************************************************************* -bool TMoverParameters::LoadFIZ(std::string const &chkpath) -{ - chkPath = chkpath; // assign class path for reloading - - ConversionError = 666; - std::string file = TypeName + ".fiz"; - - WriteLog("LOAD FIZ FROM " + file); - /* - std::ifstream in(file); - if (!in.is_open()) - { - WriteLog("E8 - FIZ FILE NOT EXIST."); - return false; - } - */ - cParser fizparser(file, cParser::buffer_FILE, chkpath); - if (false == fizparser.ok()) - { - WriteLog("E8 - FIZ FILE NOT EXIST."); - return false; - } - - return LoadFIZ_Parse(fizparser); -} - -// reads the vehicle definition from text in the .fiz format, e.g. one made up by a unit test -bool TMoverParameters::LoadFIZ_Text(std::string const &Text) -{ - ConversionError = 666; - cParser fizparser(Text, cParser::buffer_TEXT); - return LoadFIZ_Parse(fizparser); -} - -bool TMoverParameters::LoadFIZ_Parse(cParser &fizparser) -{ - LISTLINE = 0; - startBPT = false; - startMPT = false; - startMPT0 = false; - startRLIST = false; - startUCLIST = false; - startDLIST = false; - startDIZELMOMENTUMLIST = false; - startDIZELV2NMAXLIST = false; - startHYDROTCLIST = false; - startPMAXLIST = false; - startFFLIST = false; - startFFEDLIST = false; - startWWLIST = false; - startWiperList = false; - startDimmerList = false; - startLIGHTSLIST = false; - startCOMPRESSORLIST = false; - - ConversionError = 0; - - // Zbieranie danych zawartych w pliku FIZ - // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - std::map> fizlines; - std::string inputline; - /* - while (std::getline(in, inputline)) - */ - while (fizparser.ok()) - { - - inputline = fizparser.getToken(false, "\n\r"); - - if (inputline.starts_with("//") || contains(inputline, '#')) - { - // skip commented lines - continue; - } - - if (!inputline.empty() && inputline.front() == ' ') - { - // guard against malformed config files with leading spaces - inputline.erase(0, inputline.find_first_not_of(' ')); - } - - // trim CR at end (mainly for linux) - if (!inputline.empty() && inputline.back() == '\r') - inputline.pop_back(); - - if (inputline.length() == 0) - { - startBPT = false; - continue; - } - - if (LoadFIZ_TableEnd(inputline) || LoadFIZ_Section(inputline, fizlines) || LoadFIZ_TableSection(inputline, fizlines)) - { - continue; - } - LoadFIZ_TableRow(inputline); - } // while line - /* - in.close(); - */ - // Operacje na zebranych parametrach - przypisywanie do wlasciwych zmiennych i ustawianie - // zaleznosci - - bool result; - if (ConversionError == 0) - result = true; - else - result = false; - - // ustawiamy domyslna pozycje dimmera - // the DefaultPos of a short or an empty DimmerList would put the dimmer outside of it - modernDimmerDefaultPosition = clampDimmerPosition(modernDimmerDefaultPosition); - modernDimmerPosition = clampDimmerPosition(modernDimmerPosition); - if (!enableModernDimmer) - { - modernDimmerPosition = modernDimmerDefaultPosition; - } - - WriteLog("CERROR: " + std::to_string(ConversionError) + ", SUCCES: " + std::to_string(result)); - return result; -} - -// the end of the table being read; returns whether the line is one -bool TMoverParameters::LoadFIZ_TableEnd(std::string const &inputline) const -{ - // checking if table parsing should be switched off goes first... - if (issection("END-MPT", inputline)) - { - startBPT = false; - startMPT = false; - startMPT0 = false; - return true; - } - if (issection("END-RL", inputline)) - { - startBPT = false; - startRLIST = false; - return true; - } - if (issection("END-UCL", inputline)) - { - startBPT = false; - startUCLIST = false; - return true; - } - if (issection("END-DL", inputline)) - { - startBPT = false; - startDLIST = false; - return true; - } - if (issection("END-DML", inputline)) - { - startBPT = false; - startDIZELMOMENTUMLIST = false; - return true; - } - if (issection("END-V2NL", inputline)) - { - startBPT = false; - startDIZELV2NMAXLIST = false; - return true; - } - if (issection("END-HTCL", inputline)) - { - startBPT = false; - startHYDROTCLIST = false; - return true; - } - if (issection("END-PML", inputline)) - { - startBPT = false; - startPMAXLIST = false; - return true; - } - if (issection("endff", inputline)) - { - startBPT = false; - startFFLIST = false; - startFFEDLIST = false; - return true; - } - if (issection("endwl", inputline)) - { - // skonczylismy czytac liste konfiguracji wycieraczek - startBPT = false; - startWiperList = false; - return true; - } - if (issection("endDimmerList", inputline)) - { - // skonczylismy czytac liste konfiguracji pstryka od przyciemnienia - startBPT = false; - startDimmerList = false; - return true; - } - if (issection("END-WWL", inputline)) - { - startBPT = false; - startWWLIST = false; - return true; - } - if (issection("endL", inputline)) - { - startBPT = false; - startLIGHTSLIST = false; - return true; - } - if (issection("endCL", inputline)) - { - startBPT = false; - startCOMPRESSORLIST = false; - return true; - } - return false; -} - -// a section of the definition giving values, kept in fizlines by its name; returns whether the line is one -bool TMoverParameters::LoadFIZ_Section(std::string const &inputline, std::map> &fizlines) -{ - // ...then all recognized sections... - if (issection("Param.", inputline)) - { - startBPT = false; - fizlines.try_emplace("Param", inputline); - LoadFIZ_Param(inputline); - return true; - } - - if (issection("Load:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Load", inputline); - LoadFIZ_Load(inputline); - return true; - } - - if (issection("Dimensions:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Dimensions", inputline); - LoadFIZ_Dimensions(inputline); - return true; - } - - if (issection("Wheels:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Wheels", inputline); - LoadFIZ_Wheels(inputline); - return true; - } - - if (issection("Brake:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Brake", inputline); - LoadFIZ_Brake(inputline); - return true; - } - - if (issection("Doors:", inputline)) - { - - startBPT = false; - fizlines.try_emplace("Doors", inputline); - LoadFIZ_Doors(inputline); - return true; - } - - if (issection("BuffCoupl.", inputline)) - { - - startBPT = false; - fizlines.try_emplace("BuffCoupl", inputline); - LoadFIZ_BuffCoupl(inputline, 0); - return true; - } - - else if (issection("BuffCoupl1.", inputline)) - { - - startBPT = false; - fizlines.try_emplace("BuffCoupl1", inputline); - LoadFIZ_BuffCoupl(inputline, 1); - return true; - } - - else if (issection("BuffCoupl2.", inputline)) - { - - startBPT = false; - fizlines.try_emplace("BuffCoupl2", inputline); - LoadFIZ_BuffCoupl(inputline, 2); - return true; - } - - if (issection("TurboPos:", inputline)) - { - - startBPT = false; - fizlines.try_emplace("TurboPos", inputline); - LoadFIZ_TurboPos(inputline); - return true; - } - - if (issection("Cntrl.", inputline)) - { - - startBPT = true; - LISTLINE = 0; - fizlines.try_emplace("Cntrl", inputline); - LoadFIZ_Cntrl(inputline); - return true; - } - - if (issection("Headlights:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Headlights", inputline); - LoadFIZ_Headlights(inputline); - return true; - } - - if (issection("Blending:", inputline)) - { - - startBPT = false; - LISTLINE = 0; - fizlines.try_emplace("Blending", inputline); - LoadFIZ_Blending(inputline); - return true; - } - - if (issection("DCEMUED:", inputline)) - { - - startBPT = false; - LISTLINE = 0; - fizlines.try_emplace("DCEMUED", inputline); - LoadFIZ_DCEMUED(inputline); - return true; - } - - if (issection("SpringBrake:", inputline)) - { - - startBPT = false; - LISTLINE = 0; - fizlines.try_emplace("SpringBrake", inputline); - LoadFIZ_SpringBrake(inputline); - return true; - } - - if (issection("Light:", inputline)) - { - - startBPT = false; - fizlines.try_emplace("Light", inputline); - LoadFIZ_Light(inputline); - return true; - } - - if (issection("Security:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Security", inputline); - SecuritySystem.load(inputline, Vmax); - extract_value(EmergencyBrakeWarningSignal, "EmergencyBrakeWarningSignal", inputline, ""); - return true; - } - - if (issection("Clima:", inputline)) - { - - startBPT = false; - fizlines.try_emplace("Clima", inputline); - LoadFIZ_Clima(inputline); - return true; - } - - if (issection("Power:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Power", inputline); - LoadFIZ_Power(inputline); - return true; - } - - if (issection("SpeedControl:", inputline)) - { - startBPT = false; - fizlines.try_emplace("SpeedControl", inputline); - LoadFIZ_SpeedControl(inputline); - return true; - } - - if (issection("Engine:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Engine", inputline); - LoadFIZ_Engine(inputline); - return true; - } - - if (issection("Switches:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Switches", inputline); - LoadFIZ_Switches(inputline); - return true; - } - - if (issection("Circuit:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Circuit", inputline); - LoadFIZ_Circuit(inputline); - return true; - } - - if (issection("AI:", inputline)) - { - startBPT = false; - fizlines.try_emplace("AI", inputline); - LoadFIZ_AI(inputline); - return true; - } - - return false; -} - -// a section of the definition opening a table, kept in fizlines by its name; returns whether the line is one -bool TMoverParameters::LoadFIZ_TableSection(std::string const &inputline, std::map> &fizlines) -{ - if (issection("MotorParamTable:", inputline)) - { - startBPT = false; - startMPT = true; - LISTLINE = 0; - fizlines.try_emplace("MotorParamTable", inputline); - LoadFIZ_MotorParamTable(inputline); - return true; - } - - if (issection("MotorParamTable0:", inputline)) - { - startBPT = false; - startMPT0 = true; - LISTLINE = 0; - return true; - } - - if (issection("RList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("RList", inputline); - startRLIST = true; - LISTLINE = 0; - LoadFIZ_RList(inputline); - return true; - } - - if (issection("UCList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("UCList", inputline); - startUCLIST = true; - LISTLINE = 0; - LoadFIZ_UCList(inputline); - return true; - } - - if (issection("DList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("DList", inputline); - startDLIST = true; - LISTLINE = 0; - LoadFIZ_DList(inputline); - return true; - } - - if (issection("DMList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("DMList", inputline); - startDIZELMOMENTUMLIST = true; - LISTLINE = 0; - return true; - } - - if (issection("HTCList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("HTCList", inputline); - startHYDROTCLIST = true; - LISTLINE = 0; - return true; - } - - if (issection("PmaxList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("PmaxList", inputline); - startPMAXLIST = true; - LISTLINE = 0; - return true; - } - - if (issection("V2NList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("V2NList", inputline); - startDIZELV2NMAXLIST = true; - LISTLINE = 0; - return true; - } - - if (issection("ffList:", inputline)) - { - startBPT = false; - startFFLIST = true; - LISTLINE = 0; - LoadFIZ_FFList(inputline); - return true; - } - - if (issection("ffBrakeList:", inputline)) - { - startBPT = false; - startFFEDLIST = true; - LISTLINE = 0; - LoadFIZ_FFEDList(inputline); - return true; - } - - if (issection("WWList:", inputline)) - { - startBPT = false; - startWWLIST = true; - LISTLINE = 0; - - return true; - } - - if (issection("WiperList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("WiperList", inputline); - startWiperList = true; - LISTLINE = 0; - LoadFIZ_WiperList(inputline); - - return true; - } - - if (issection("DimmerList:", inputline)) - { - dimPositions.clear(); // uzywamy customowej listy - startBPT = false; - startDimmerList = true; - fizlines.try_emplace("DimmerList", inputline); - LoadFIZ_DimmerList(inputline); - return true; - } - - if (issection("LightsList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("LightsList", inputline); - startLIGHTSLIST = true; - LISTLINE = 0; - LoadFIZ_LightsList(inputline); - return true; - } - - if (issection("CompressorList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("CompressorList", inputline); - startCOMPRESSORLIST = true; - LISTLINE = 0; - LoadFIZ_CompressorList(inputline); - return true; - } - return false; -} - -// a row of the table being read -void TMoverParameters::LoadFIZ_TableRow(std::string const &inputline) -{ - // ...and finally, table parsers. - // NOTE: once table parsing is enabled it lasts until switched off, when another section is recognized - if (true == startBPT) - { - readBPT(inputline); - return; - } - if (true == startMPT) - { - readMPT(inputline); - return; - } - if (true == startMPT0) - { - readMPT0(inputline); - return; - } - if (true == startRLIST) - { - readRList(inputline); - return; - } - if (true == startUCLIST) - { - readUCList(inputline); - return; - } - if (true == startDLIST) - { - readDList(inputline); - return; - } - if (true == startDIZELMOMENTUMLIST) - { - readDMList(inputline); - return; - } - if (true == startDIZELV2NMAXLIST) - { - readV2NMAXList(inputline); - return; - } - if (true == startHYDROTCLIST) - { - readHTCList(inputline); - return; - } - if (true == startPMAXLIST) - { - readPmaxList(inputline); - return; - } - if (true == startFFLIST) - { - readFFList(inputline); - return; - } - if (true == startFFEDLIST) - { - readFFEDList(inputline); - return; - } - if (true == startWWLIST) - { - readWWList(inputline); - return; - } - if (true == startWiperList) - { - readWiperList(inputline); - return; - } - if (true == startDimmerList) - { - readDimmerList(inputline); - } - if (true == startLIGHTSLIST) - { - readLightsList(inputline); - return; - } - if (true == startCOMPRESSORLIST) - { - readCompressorList(inputline); - return; - } -} - -void TMoverParameters::LoadFIZ_Param(std::string const &line) -{ - - extract_value(Mass, "M", line, "0"); - extract_value(Mred, "Mred", line, "0"); - extract_value(Vmax, "Vmax", line, "0"); - extract_value(Power, "PWR", line, "0"); - extract_value(SandCapacity, "SandCap", line, "0"); - extract_value(HeatingPower, "HeatingP", line, "0"); - extract_value(LightPower, "LightP", line, "0"); - - { - std::map> categories{{"train", 1}, {"road", 2}, {"unimog", 3}, {"ship", 4}, {"airplane,", 8}}; - std::string category; - extract_value(category, "Category", line, "none"); - auto lookup = categories.find(category); - CategoryFlag = lookup != categories.end() ? lookup->second : 0; - if (CategoryFlag == 0) - { - ErrorLog("Unknown vehicle category: \"" + category + "\"."); - } - } - - { - std::map> types{ - {"pseudodiesel", train_type::pseudodiesel}, - {"ezt", train_type::emu}, - {"dmu", train_type::dmu}, - {"sn61", train_type::sn61}, - {"et22", train_type::et22}, - {"et40", train_type::et40}, - {"et41", train_type::et41}, - {"et42", train_type::et42}, - {"ep05", train_type::ep05}, - {"181", train_type::skoda181}, - {"182", train_type::skoda181} // na razie tak - }; - std::string type; - extract_value(type, "Type", line, "none"); - auto lookup = types.find(ToLower(type)); - TrainType = lookup != types.end() ? lookup->second : train_type::generic; - } - - if (TrainType == train_type::emu) - { - - IminLo = 1; - IminHi = 2; - Imin = 1; - } -} - -void TMoverParameters::LoadFIZ_Load(std::string const &line) -{ - - auto const acceptedloads{Split(extract_value("LoadAccepted", line), ',')}; - - if (acceptedloads.empty()) - { - return; - } - - auto const minoffsets{Split(extract_value("LoadMinOffset", line), ',')}; - auto minoffset{0.f}; - auto minoffsetsiterator{std::begin(minoffsets)}; - // NOTE: last (if any) offset parameter retrieved from the list applies to the remainder of the list - // TBD, TODO: include other load parameters in this system - for (auto &load : acceptedloads) - { - if (minoffsetsiterator != std::end(minoffsets)) - { - minoffset = std::stof(*minoffsetsiterator); - ++minoffsetsiterator; - } - LoadAttributes.emplace_back(ToLower(load), minoffset); - } - - extract_value(MaxLoad, "MaxLoad", line, ""); - extract_value(LoadQuantity, "LoadQ", line, ""); - extract_value(OverLoadFactor, "OverLoadFactor", line, ""); - extract_value(LoadSpeed, "LoadSpeed", line, ""); - extract_value(UnLoadSpeed, "UnLoadSpeed", line, ""); -} - -void TMoverParameters::LoadFIZ_Headlights(std::string const &line) -{ - extract_value(refR, "LampRed", line, ""); - extract_value(refG, "LampGreen", line, ""); - extract_value(refB, "LampBlue", line, ""); - - extract_value(dimMultiplier, "DimmedMultiplier", line, ""); - extract_value(normMultiplier, "NormalMultiplier", line, ""); - extract_value(highDimMultiplier, "HighbeamDimmedMultiplier", line, ""); - extract_value(highMultiplier, "HighBeamMultiplier", line, ""); -} - -void TMoverParameters::LoadFIZ_Dimensions(std::string const &line) -{ - - extract_value(Dim.L, "L", line, ""); - extract_value(Dim.H, "H", line, ""); - extract_value(Dim.W, "W", line, ""); - // height of the centre of gravity of the empty vehicle [m], for the criteria of derailment - extract_value(CentreOfGravity, "CoGH", line, ""); - - extract_value(Cx, "Cx", line, "0.3"); - if (Dim.H <= 2.0) - { - // gdyby nie było parametru, lepsze to niż zero - Floor = static_cast(Dim.H); - } - else - { - // zgodność wsteczna - Floor = 0.0; - } - extract_value(Floor, "Floor", line, ""); -} - -void TMoverParameters::LoadFIZ_Wheels(std::string const &line) -{ - - extract_value(WheelDiameter, "D", line, ""); - WheelDiameterL = WheelDiameter; // gdyby nie było parametru, lepsze to niż zero - extract_value(WheelDiameterL, "Dl", line, ""); - WheelDiameterT = WheelDiameter; // gdyby nie było parametru, lepsze to niż zero - extract_value(WheelDiameterT, "Dt", line, ""); - - extract_value(TrackW, "Tw", line, ""); - extract_value(AxleInertialMoment, "AIM", line, ""); - - extract_value(AxleArangement, "Axle", line, ""); - NPoweredAxles = s2NPW(AxleArangement); - NAxles = NPoweredAxles + s2NNW(AxleArangement); - - BearingType = extract_value("BearingType", line) == "Roll" ? 1 : 0; - - extract_value(ADist, "Ad", line, ""); - extract_value(BDist, "Bd", line, ""); - - if (AxleInertialMoment <= 0.0) - { - /* - AxleInertialMoment = 1.0; - */ - // approximation formula by youby - auto const k = 472.0; // arbitrary constant - AxleInertialMoment = k / 4.0 * std::pow(WheelDiameter, 4.0) * NAxles; - Mred = k * std::pow(WheelDiameter, 2.0) * NAxles; - } -} - -void TMoverParameters::LoadFIZ_Brake(std::string const &line) -{ - - extract_value(BrakeValveParams, "BrakeValve", line, ""); - BrakeValveDecode(BrakeValveParams); - BrakeSubsystemDecode(); - - extract_value(NBpA, "NBpA", line, ""); - extract_value(MaxBrakeForce, "MBF", line, ""); - extract_value(BrakeValveSize, "Size", line, ""); - extract_value(TrackBrakeForce, "TBF", line, ""); - TrackBrakeForce *= 1000.0; - - extract_value(MaxBrakePress[3], "MaxBP", line, ""); - if (MaxBrakePress[3] > 0.0) - { - - extract_value(BrakeCylNo, "BCN", line, ""); - if (BrakeCylNo > 0) - { - - extract_value(MaxBrakePress[0], "MaxLBP", line, ""); - if (MaxBrakePress[0] < 0.01) - { - MaxBrakePress[0] = MaxBrakePress[3]; - } - extract_value(MaxBrakePress[1], "TareMaxBP", line, ""); - extract_value(MaxBrakePress[2], "MedMaxBP", line, ""); - extract_value(MaxBrakePress[4], "MaxASBP", line, ""); - if (MaxBrakePress[4] < 0.01) - { - MaxBrakePress[4] = 0.0; - } - - extract_value(BrakeCylRadius, "BCR", line, ""); - extract_value(BrakeCylDist, "BCD", line, ""); - extract_value(BrakeCylSpring, "BCS", line, ""); - extract_value(BrakeSlckAdj, "BSA", line, ""); - extract_value(BrakeRigEff, "BRE", line, "1"); - - extract_value(BrakeCylMult[0], "BCM", line, ""); - extract_value(BrakeCylMult[1], "BCMlo", line, ""); - extract_value(BrakeCylMult[2], "BCMHi", line, ""); - - P2FTrans = 100 * M_PI * std::pow(BrakeCylRadius, 2); // w kN/bar - - if (BrakeCylMult[1] > 0.0 || MaxBrakePress[1] > 0.0) - { - LoadFlag = 1; - } - else - { - LoadFlag = 0; - } - - BrakeVolume = M_PI * std::pow(BrakeCylRadius, 2) * BrakeCylDist * BrakeCylNo; - extract_value(BrakeVVolume, "BVV", line, ""); - - { - std::map> brakemethods{{"P10-Bg", bp_P10Bg}, {"P10-Bgu", bp_P10Bgu}, {"FR513", bp_FR513}, {"FR510", bp_FR510}, {"Cosid", bp_Cosid}, - {"P10yBg", bp_P10yBg}, {"P10yBgu", bp_P10yBgu}, {"Disk1", bp_D1}, {"Disk1+Mg", bp_D1 + bp_MHS}, {"Disk2", bp_D2}}; - auto lookup = brakemethods.find(extract_value("BM", line)); - BrakeMethod = lookup != brakemethods.end() ? lookup->second : 0; - } - - extract_value(RapidMult, "RM", line, "1"); - extract_value(RapidVel, "RV", line, "55"); - } - } - else - { - // maxbrakepress[3] == 0 or less - P2FTrans = 0; - } - - // Ra 2014-07: trochę niedokładności - // the draws are sequenced: the order of the operands of '-' is unspecified, and GCC and MSVC draw them the other way round - auto const firstdraw{Random(10)}; - CntrlPipePress = 5 + 0.001 * (Random(10) - firstdraw); - extract_value(CntrlPipePress, "HiPP", line, ""); - HighPipePress = CntrlPipePress; - LowPipePress = std::min(HighPipePress, 3.5); - extract_value(LowPipePress, "LoPP", line, ""); - DeltaPipePress = HighPipePress - LowPipePress; - - extract_value(VeselVolume, "Vv", line, ""); - /* - if( VeselVolume == 0.0 ) { VeselVolume = 0.01; } - */ - extract_value(MinCompressor, "MinCP", line, ""); - extract_value(MaxCompressor, "MaxCP", line, ""); - extract_value(MinCompressor_cabB, "MinCP_B", line, ""); - extract_value(MaxCompressor_cabB, "MaxCP_B", line, ""); - extract_value(CompressorTankValve, "CompressorTankValve", line, ""); - extract_value(CompressorSpeed, "CompressorSpeed", line, ""); - extract_value(EmergencyValveOff, "MinEVP", line, ""); - extract_value(EmergencyValveOn, "MaxEVP", line, ""); - extract_value(EmergencyValveArea, "EVArea", line, ""); - extract_value(UniversalBrakeButtonFlag[0], "UBB1", line, ""); - extract_value(UniversalBrakeButtonFlag[1], "UBB2", line, ""); - extract_value(UniversalBrakeButtonFlag[2], "UBB3", line, ""); - extract_value(LockPipeOn, "LPOn", line, "-1"); - extract_value(LockPipeOff, "LPOff", line, "-1"); - extract_value(HandleUnlock, "HandlePipeUnlockPos", line, "-3"); - extract_value(EmergencyCutsOffHandle, "EmergencyCutsOffHandle", line, ""); - { - std::map> compressorpowers{ - {"Main", 0}, - // 1: default, powered by converter, with manual state control - {"Converter", 2}, - {"Engine", 3}, // equivalent of 0, TODO: separate 'main' and 'engine' in the code - {"Coupler1", 4}, // włączana w silnikowym EZT z przodu - {"Coupler2", 5} // włączana w silnikowym EZT z tyłu - }; - auto lookup = compressorpowers.find(extract_value("CompressorPower", line)); - CompressorPower = lookup != compressorpowers.end() ? lookup->second : 1; - } - extract_value(CompressorStartDelay, "CompressorStartDelay", line, ""); - - if (true == extract_value(AirLeakRate, "AirLeakRate", line, "")) - { - // the parameter is provided in form of a multiplier, where 1.0 means the default rate of 0.01 - AirLeakRate *= 0.01; - } - - extract_value(ReleaserEnabledOnlyAtNoPowerPos, "ReleaserPowerPosLock", line, EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric ? "yes" : "no"); - - if (MinCompressor_cabB > 0.0) - { - MinCompressor_cabA = MinCompressor; - CabDependentCompressor = true; - } - else - { - MinCompressor_cabB = MinCompressor; - } - if (MaxCompressor_cabB > 0.0) - { - MaxCompressor_cabA = MaxCompressor; - CabDependentCompressor = true; - } - else - { - MaxCompressor_cabB = MaxCompressor; - } -} - -void TMoverParameters::LoadFIZ_Doors(std::string const &line) -{ - - std::map> doorcontrols{ - {"Passenger", control_t::passenger}, {"AutomaticCtrl", control_t::autonomous}, {"DriverCtrl", control_t::driver}, {"Conductor", control_t::conductor}, {"Mixed", control_t::mixed}}; - // opening method - { - auto lookup = doorcontrols.find(extract_value("OpenCtrl", line)); - Doors.open_control = lookup != doorcontrols.end() ? lookup->second : control_t::passenger; - } - // closing method - { - auto lookup = doorcontrols.find(extract_value("CloseCtrl", line)); - Doors.close_control = lookup != doorcontrols.end() ? lookup->second : control_t::passenger; - } - // automatic closing conditions - extract_value(Doors.auto_duration, "DoorStayOpen", line, ""); - extract_value(Doors.auto_velocity, "DoorAutoCloseVel", line, ""); - extract_value(Doors.auto_include_remote, "DoorAutoCloseRemote", line, ""); - // operation permit - extract_value(Doors.permit_needed, "DoorNeedPermit", line, ""); - // the door closure lamp (SOD) of the cab signals the doors of the whole consist - extract_value(Doors.closure_signal, "DoorClosureSignal", line, ""); - { - auto permitpresets = Split(extract_value("DoorPermitList", line), '|'); - for (auto const &permit : permitpresets) - { - Doors.permit_presets.emplace_back(std::stoi(permit)); - } - if (false == Doors.permit_presets.empty()) - { - // HACK: legacy position indices start from 1, so we deduct 1 to arrive at proper index into the array - extract_value(Doors.permit_preset, "DoorPermitListDefault", line, "1"); - Doors.permit_preset = std::min(static_cast(Doors.permit_presets.size()), Doors.permit_preset) - 1; - } - } - - extract_value(Doors.open_rate, "OpenSpeed", line, ""); - extract_value(Doors.open_delay, "DoorOpenDelay", line, ""); - extract_value(Doors.close_rate, "CloseSpeed", line, ""); - extract_value(Doors.close_delay, "DoorCloseDelay", line, ""); - extract_value(Doors.range, "DoorMaxShiftL", line, ""); - extract_value(Doors.range, "DoorMaxShiftR", line, ""); - extract_value(Doors.range_out, "DoorMaxShiftPlug", line, ""); - - std::map> doortypes{ - {"Shift", 1}, - {"Rotate", 2}, - {"Fold", 3}, - {"Plug", 4}, - }; - // opening method - { - auto lookup = doortypes.find(extract_value("DoorOpenMethod", line)); - Doors.type = lookup != doortypes.end() ? lookup->second : 2; // default type is plain, rotating door - } - - extract_value(Doors.has_warning, "DoorClosureWarning", line, ""); - extract_value(Doors.has_autowarning, "DoorClosureWarningAuto", line, ""); - extract_value(Doors.has_lock, "DoorBlocked", line, ""); - extract_value(Doors.doorLockSpeed, "DoorLockSpeed", line, ""); - { - auto const remotedoorcontrol{Doors.open_control == control_t::driver || Doors.open_control == control_t::conductor || Doors.open_control == control_t::mixed}; - - extract_value(Doors.voltage, "DoorVoltage", line, remotedoorcontrol ? "24" : "0"); - } - - extract_value(Doors.step_rate, "PlatformSpeed", line, ""); - extract_value(Doors.step_range, "PlatformMaxShift", line, ""); - - std::string platformopenmethod; - extract_value(platformopenmethod, "PlatformOpenMethod", line, ""); - if (platformopenmethod == "Shift") - { - Doors.step_type = 1; - } // przesuw - - extract_value(MirrorMaxShift, "MirrorMaxShift", line, ""); - extract_value(MirrorVelClose, "MirrorVelClose", line, ""); - - extract_value(DoorsOpenWithPermitAfter, "DoorOpenWithPermit", line, ""); - extract_value(DoorsPermitLightBlinking, "DoorsPermitLightBlinking", line, ""); -} - -namespace -{ - -// the value of an optional key of the line, or the default without it -double optional_value(std::string const &Line, std::string const &Key, double const Default) -{ - auto value{Default}; - extract_value(value, Key, Line, ""); - return value; -} - -// the value of an optional key of the line given in kilo-units, in units; or the default (in units) without it -double optional_kilo_value(std::string const &Line, std::string const &Key, double const Default) -{ - auto value{0.0}; - return extract_value(value, Key, Line, "") && value > 0.0 ? value * 1000.0 : Default; -} - -// the play of a coupling as made, for each kind: a screw coupling is tightened so that the buffers touch, the knuckles of -// an automatic coupler have about a centimetre between them, a chain hangs loose -double default_slack(TCouplerType const Type) -{ - switch (Type) - { - case TCouplerType::Automatic: - return 0.005; - case TCouplerType::Chain: - return 0.05; - default: - return 0.0; - } -} - -// the parameters of the physical model of the coupling (couplerphysics in eu07.ini, see couplerphysics.h), taken from -// those of the legacy model, and the optional keys of the .fiz for what the legacy model doesn't have: -// Slack [m] the play of the coupling of this end, negative for a screw coupling tightened to press the buffers in -// ProgB, ProgC [-] progression of the buffers and of the draw gear, 0 linear, up to 0.9 -// UnloadB, UnloadC [-] force of the unloading curve of the buffers and of the draw gear to that of the loading one -// FyieldC [kN] the force past which the link stretches for good; DbreakC [m] the elongation at which it breaks -// kL [kN/m] stiffness of the steel parts past the travel of the springs; FcrushB [kN] the buffers give under it -// RestitutionSolid [-] coefficient of restitution of a hit on the springs gone solid -coupler_physics::end_parameters coupler_physics_parameters(TCoupling const &Coupler, std::string const &Line) -{ - coupler_physics::end_parameters parameters; - parameters.buffers = {Coupler.SpringKB, Coupler.DmaxB, std::clamp(optional_value(Line, "ProgB", 0.5), 0.0, 0.9)}; - parameters.draw_gear = {Coupler.SpringKC, Coupler.DmaxC, std::clamp(optional_value(Line, "ProgC", 0.3), 0.0, 0.9)}; - // only a screw coupling can be tightened to press the buffers in, and not past their travel - auto const tightest{Coupler.CouplerType == TCouplerType::Screw ? -Coupler.DmaxB : 0.0}; - parameters.slack = std::max(optional_value(Line, "Slack", default_slack(Coupler.CouplerType)), tightest); - // the legacy model sprang back at beta of the force it was loaded with - auto const unloading{Coupler.beta > 0.0 && Coupler.beta < 1.0 ? Coupler.beta : 0.5}; - parameters.buffers_unloading = std::clamp(optional_value(Line, "UnloadB", unloading), 0.05, 1.0); - parameters.draw_gear_unloading = std::clamp(optional_value(Line, "UnloadC", unloading), 0.05, 1.0); - // as much as the legacy model had - parameters.damping = CouplerTune * (Coupler.FmaxC + Coupler.FmaxB) * std::max(Coupler.beta, 0.0); - - // FmaxC is the rated breaking force of the coupling - auto const ultimate{std::max(Coupler.FmaxC, 1.0)}; - auto const yield{std::min(optional_kilo_value(Line, "FyieldC", 0.8 * ultimate), ultimate)}; - auto const elongation{std::max(optional_value(Line, "DbreakC", 0.02), 0.001)}; - parameters.link = {yield, ultimate, std::max((ultimate - yield) / elongation, 1.0), Coupler.CouplerType != TCouplerType::Articulated}; - // the steel parts give a few millimetres under the rated force - parameters.link_stiffness = optional_kilo_value(Line, "kL", ultimate / 0.003); - parameters.crush_force = optional_kilo_value(Line, "FcrushB", 2.5 * std::max(Coupler.FmaxB, Coupler.FmaxC)); - parameters.solid_restitution = std::clamp(optional_value(Line, "RestitutionSolid", parameters.solid_restitution), 0.05, 0.95); - return parameters; -} - -void scale_strength(coupler_physics::link_strength &Link, double const Factor) -{ - Link.yield *= Factor; - Link.ultimate *= Factor; -} - -// the optional keys of the collisions past the buffers (physics.collisions new, see collision.h), what's not given -// comes from the kind of the vehicle: -// FcrushPeak, FcrushPlateau [kN] the force the end starts to crush at, and keeps crushing at -// CrushOnset, CrushDensify, CrushLimit [m] the crush the peak drops at, it packs down past, it can't go past -// CrushHardening [1/m] the growth of the force past CrushDensify, to the plateau for each metre -// CrashZone [yes/no] built to EN 15227: energy absorbers and anticlimbers; AntiClimber [yes/no] on its own -// BufferHeight [m] of the empty vehicle above the rail -// BufferCategory [A/B/C/L/P] the buffers of EN 15551 (P those of the coaches) in place of kB and DmaxB -collision::end_definition collision_definition(std::string const &Line) -{ - collision::end_definition definition; - auto const number = [&Line](std::string const &Key, double const Scale) -> std::optional { - auto value{0.0}; - if (extract_value(value, Key, Line, "") && value >= 0.0) - { - return value * Scale; - } - return std::nullopt; - }; - auto const flag = [&Line](std::string const &Key) -> std::optional { - auto value{false}; - if (extract_value(value, Key, Line, "")) - { - return value; - } - return std::nullopt; - }; - definition.peak = number("FcrushPeak", 1000.0); - definition.plateau = number("FcrushPlateau", 1000.0); - definition.onset = number("CrushOnset", 1.0); - definition.densify = number("CrushDensify", 1.0); - definition.hardening = number("CrushHardening", 1.0); - definition.limit = number("CrushLimit", 1.0); - definition.crash_zone = flag("CrashZone"); - definition.anticlimber = flag("AntiClimber"); - definition.buffer_height = number("BufferHeight", 1.0); - return definition; -} - -} // namespace - -void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Index) -{ - - TCoupling *thiscoupler; - if (Index == 2) - { - thiscoupler = &Couplers[1]; - } - else - { - thiscoupler = &Couplers[0]; - } - - std::map> couplertypes{ - {"Automatic", TCouplerType::Automatic}, {"Screw", TCouplerType::Screw}, {"Chain", TCouplerType::Chain}, {"Bare", TCouplerType::Bare}, {"Articulated", TCouplerType::Articulated}, - }; - auto lookup = couplertypes.find(extract_value("CType", line)); - thiscoupler->CouplerType = lookup != couplertypes.end() ? lookup->second : TCouplerType::NoCoupler; - - extract_value(thiscoupler->SpringKC, "kC", line, ""); - extract_value(thiscoupler->DmaxC, "DmaxC", line, ""); - extract_value(thiscoupler->FmaxC, "FmaxC", line, ""); - extract_value(thiscoupler->SpringKB, "kB", line, ""); - extract_value(thiscoupler->DmaxB, "DmaxB", line, ""); - extract_value(thiscoupler->FmaxB, "FmaxB", line, ""); - extract_value(thiscoupler->beta, "beta", line, ""); - extract_value(thiscoupler->AutomaticCouplingFlag, "AutomaticFlag", line, ""); - extract_value(thiscoupler->AllowedFlag, "AllowedFlag", line, ""); - if (thiscoupler->AllowedFlag < 0) - { - thiscoupler->AllowedFlag = -thiscoupler->AllowedFlag | coupling::permanent; - } - extract_value(thiscoupler->PowerCoupling, "PowerCoupling", line, ""); - extract_value(thiscoupler->PowerFlag, "PowerFlag", line, ""); - extract_value(thiscoupler->control_type, "ControlType", line, ""); - - if (thiscoupler->CouplerType != TCouplerType::NoCoupler && thiscoupler->CouplerType != TCouplerType::Bare && thiscoupler->CouplerType != TCouplerType::Articulated) - { - - thiscoupler->SpringKC *= 1000; - thiscoupler->FmaxC *= 1000; - thiscoupler->SpringKB *= 1000; - thiscoupler->FmaxB *= 1000; - } - else if (thiscoupler->CouplerType == TCouplerType::Bare) - { - - thiscoupler->SpringKC = 50.0 * Mass + Ftmax / 0.05; - thiscoupler->DmaxC = 0.05; - thiscoupler->FmaxC = 100.0 * Mass + 2 * Ftmax; - thiscoupler->SpringKB = 60.0 * Mass + Ftmax / 0.05; - thiscoupler->DmaxB = 0.05; - thiscoupler->FmaxB = 50.0 * Mass + 2.0 * Ftmax; - thiscoupler->beta = 0.3; - } - else if (thiscoupler->CouplerType == TCouplerType::Articulated) - { - /* - coupler->SpringKC = 60.0 * Mass + 1000; - coupler->DmaxC = 0.05; - coupler->FmaxC = 20000000.0 + 2.0 * Ftmax; - coupler->SpringKB = 70.0 * Mass + 1000; - coupler->DmaxB = 0.05; - coupler->FmaxB = 4000000.0 + 2.0 * Ftmax; - coupler->beta = 0.55; - */ - thiscoupler->SpringKC = 4500 * 1000; - thiscoupler->FmaxC = 850 * 1000; - thiscoupler->SpringKB = 9200 * 1000; - thiscoupler->FmaxB = 320 * 1000; - thiscoupler->beta = 0.55; - // the spring force is taken up to Dmax only, past it the vehicles collide (CollisionDetect()); so the joint - // carries the full FmaxC either way before it gives. with 0.05 m it carried 225 kN, short of what a loaded - // articulated wagon in a freight train takes, which then collided at every step (eu07/maszyna#553) - thiscoupler->DmaxC = std::max(0.05, thiscoupler->FmaxC / thiscoupler->SpringKC); - thiscoupler->DmaxB = std::max(0.05, thiscoupler->FmaxC / thiscoupler->SpringKB); - } - - // the buffers of a category of EN 15551 in place of the springs given - auto const categoryname{extract_value("BufferCategory", line)}; - auto const category{categoryname.empty() ? std::nullopt : collision::buffer_category_of(categoryname.front())}; - auto const buffered{thiscoupler->CouplerType != TCouplerType::NoCoupler && thiscoupler->CouplerType != TCouplerType::Bare && thiscoupler->CouplerType != TCouplerType::Articulated}; - if (category && buffered) - { - auto const linear{collision::buffer_curve(*category, 0.0)}; - thiscoupler->SpringKB = linear.stiffness; - thiscoupler->DmaxB = linear.travel; - } - thiscoupler->physics = coupler_physics_parameters(*thiscoupler, line); - if (category && buffered) - { - thiscoupler->physics.buffers = collision::buffer_curve(*category, thiscoupler->physics.buffers.progression); - } - thiscoupler->collision = collision_definition(line); - thiscoupler->collision.buffers = category; - - if (Index == 0) - { - // 0 indicates single entry for both couplers - Couplers[1] = Couplers[0]; - } - // each coupling as made is a little stronger than its rated force, a different one at each end - for (int end = end::front; end <= end::rear; ++end) - { - if (Index == 0 || end == (Index == 2 ? end::rear : end::front)) - { - scale_strength(Couplers[end].physics.link, coupler_physics::strength_scatter(Name, end)); - } - } -} - -void TMoverParameters::LoadFIZ_TurboPos(std::string const &Input) -{ - - extract_value(TurboTest, "TurboPos", Input, ""); -} - -void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) -{ - - LoadFIZ_CntrlBrakes(line); - LoadFIZ_CntrlControllers(line); - LoadFIZ_CntrlStarts(line); -} - -// Cntrl.: the brake system, the handles, the brake delays and the local and manual brakes -void TMoverParameters::LoadFIZ_CntrlBrakes(std::string const &line) -{ - { - using enum TBrakeSystem; - std::map> brakesystems{{"Pneumatic", Pneumatic}, {"ElectroPneumatic", ElectroPneumatic}}; - auto lookup = brakesystems.find(extract_value("BrakeSystem", line)); - BrakeSystem = lookup != brakesystems.end() ? lookup->second : Individual; - } - if (BrakeSystem != TBrakeSystem::Individual) - { - LoadFIZ_CntrlTrainBrake(line); - } // brakesystem != individual - - // localbrake - { - using enum TLocalBrake; - std::map> localbrakes{{"ManualBrake", ManualBrake}, {"PneumaticBrake", PneumaticBrake}, {"HydraulicBrake", HydraulicBrake}}; - auto lookup = localbrakes.find(extract_value("LocalBrake", line)); - LocalBrake = lookup != localbrakes.end() ? lookup->second : NoBrake; - } - // mbrake - extract_value(MBrake, "ManualBrake", line, ""); -} - -// Cntrl.: of a vehicle with a train brake, its positions, delays, modes, handles, load weighing and anti-slip brake -void TMoverParameters::LoadFIZ_CntrlTrainBrake(std::string const &line) -{ - using enum TBrakeHandle; - - extract_value(BrakeCtrlPosNo, "BCPN", line, ""); - for (int idx = 0; idx < 4; ++idx) - { - - extract_value(BrakeDelay[idx], std::format("BDelay{}", idx + 1), line, ""); - } - // brakedelays, brakedelayflag - { - std::map> brakedelays{{"GPR", bdelay_G + bdelay_P + bdelay_R}, - {"PR", bdelay_P + bdelay_R}, - {"GP", bdelay_G + bdelay_P}, - {"R", bdelay_R}, - {"P", bdelay_P}, - {"G", bdelay_G}, - {"GPR+Mg", bdelay_G + bdelay_P + bdelay_R + bdelay_M}, - {"PR+Mg", bdelay_P + bdelay_R + bdelay_M}}; - std::map> brakedelayflags{{"R", bdelay_R}, {"P", bdelay_P}, {"G", bdelay_G}}; - std::string brakedelay; - extract_value(brakedelay, "BrakeDelays", line, ""); - auto lookup = brakedelays.find(brakedelay); - BrakeDelays = lookup != brakedelays.end() ? lookup->second : 0; - lookup = brakedelayflags.find(brakedelay); - BrakeDelayFlag = lookup != brakedelayflags.end() ? lookup->second : 0; - } - // brakeopmode - { - std::map> brakeopmodes{{"PN", bom_PS + bom_PN}, {"PNEP", bom_PS + bom_PN + bom_EP}, {"PNEPMED", bom_PS + bom_PN + bom_EP + bom_MED}}; - auto lookup = brakeopmodes.find(extract_value("BrakeOpModes", line)); - BrakeOpModes = lookup != brakeopmodes.end() ? lookup->second : 0; - } - // brakehandle - { - std::map> brakehandles{ - {"FV4a", FV4a}, {"test", testH}, {"D2", D2}, {"MHZ_EN57", MHZ_EN57}, {"MHZ_K5P", MHZ_K5P}, - {"MHZ_K8P", MHZ_K8P}, {"MHZ_6P", MHZ_6P}, {"M394", M394}, {"Knorr", Knorr}, {"Westinghouse", West}, - {"FVel6", FVel6}, {"FVE408", FVE408}, {"St113", St113}}; - auto lookup = brakehandles.find(extract_value("BrakeHandle", line)); - BrakeHandle = lookup != brakehandles.end() ? lookup->second : NoHandle; - } - extract_value(Handle_AutomaticOverload, "HAO", line, ""); - extract_value(Handle_ManualOverload, "HMO", line, ""); - extract_value(Handle_GenericDoubleParameter1, "HGDP1", line, ""); - extract_value(Handle_GenericDoubleParameter2, "HGDP2", line, ""); - extract_value(Handle_OverloadMaxPressure, "OMP", line, ""); - extract_value(Handle_OverloadPressureDecrease, "OPD", line, ""); - // brakelochandle - { - std::map> locbrakehandles{{"FD1", FD1}, {"Knorr", Knorr}, {"Westinghouse", West}}; - auto lookup = locbrakehandles.find(extract_value("LocBrakeHandle", line)); - BrakeLocHandle = lookup != locbrakehandles.end() ? lookup->second : NoHandle; - } - - // mbpm - if (true == extract_value(MBPM, "MaxBPMass", line, "")) - { - // NOTE: only convert the value from tons to kilograms if the entry is present in the config file - MBPM *= 1000.0; - } - - // asbtype - LoadFIZ_CntrlAntiSlipBrake(ToLower(extract_value("ASB", line))); -} - -// Cntrl.: the kind of the anti-slip brake, by hand or automatic only for a vehicle with a brake handle -void TMoverParameters::LoadFIZ_CntrlAntiSlipBrake(std::string_view const asb) -{ - if (asb == "yes") - { - ASBType = 128; - } - else if (BrakeCtrlPosNo > 0 && asb == "manual") - { - ASBType = 1; - } - else if (BrakeCtrlPosNo > 0 && asb == "automatic") - { - ASBType = 2; - } -} - -// Cntrl.: the controllers, their delays, the cab and the switches of the driver's desk -void TMoverParameters::LoadFIZ_CntrlControllers(std::string const &line) -{ - // maksymalna predkosc dostepna na tarczce predkosciomierza - extract_value(maxTachoSpeed, "MaxTachoSpeed", line, ""); - - // horns - { - using enum horn_supply; - std::map> const hornsupplies{{"Pneumatic", air}, {"Electric", electric}}; - auto lookup = hornsupplies.find(extract_value("HornType", line)); - HornSupply = lookup != hornsupplies.end() ? lookup->second : air; - lookup = hornsupplies.find(extract_value("Horn3Type", line)); - Horn3Supply = lookup != hornsupplies.end() ? lookup->second : HornSupply; - } - - // dynamicbrake - { - std::map> dynamicbrakes{{"Passive", dbrake_passive}, {"Switch", dbrake_switch}, {"Reversal", dbrake_reversal}, {"Automatic", dbrake_automatic}}; - auto lookup = dynamicbrakes.find(extract_value("DynamicBrake", line)); - DynamicBrakeType = lookup != dynamicbrakes.end() ? lookup->second : dbrake_none; - extract_value(DynamicBrakeAmpmeters, "DBAM", line, ""); - } - - // split ED/pneumatic brake control: when true the local brake operates only on the - // pneumatic locomotive cylinder while electrodynamic braking is commanded by a - // separate "dynamicbrakectrl" lever (or the negative range of jointctrl). - extract_value(SplitEDPneumaticBrake, "SplitEDPneumaticBrake", line, ""); - // number of stepped positions for the dedicated ED brake controller (default 10) - DynamicBrakeCtrlPosNo = 10; - extract_value(DynamicBrakeCtrlPosNo, "DBPN", line, ""); - if (DynamicBrakeCtrlPosNo < 1) - { - DynamicBrakeCtrlPosNo = 10; - } - - extract_value(MainCtrlPosNo, "MCPN", line, ""); - extract_value(ScndCtrlPosNo, "SCPN", line, ""); - extract_value(ScndInMain, "SCIM", line, ""); - extract_value(MainCtrlMaxDirChangePos, "DirChangeMaxPos", line, ""); - - if (auto const autorelay{ToLower(extract_value("AutoRelay", line))}; autorelay == "optional") - { - AutoRelayType = 2; - } - else if (autorelay == "yes") - { - AutoRelayType = 1; - } - else - { - AutoRelayType = 0; - } - // a key of its own rather than a new AutoRelay value: an exe that doesn't know it reads the line as before, and the value - // stays Optional, which every check of the switch looks for - extract_value(FieldShuntSwitch, "FieldShuntSwitch", line, ""); - - extract_value(CoupledCtrl, "CoupledCtrl", line, ""); - extract_value(HasCamshaft, "Camshaft", line, ""); - extract_value(EIMCtrlType, "EIMCtrlType", line, ""); - EIMCtrlType = std::clamp(EIMCtrlType, 0, 3); - extract_value(LocHandleTimeTraxx, "LocalBrakeTraxx", line, ""); - extract_value(EIMCtrlAdditionalZeros, "EIMCtrlAddZeros", line, ""); - extract_value(EIMCtrlEmergency, "EIMCtrlEmergency", line, ""); - // Elf (EIMCtrlType 2): an emergency brake position below the controller's position 0, which shifts the other positions up by one - extract_value(EIMCtrlMainEmergency, "EIMCtrlMainEmergency", line, ""); - if (auto const elfpositions{4 + EIMCtrlEmergencyPositions()}; EIMCtrlEmergencyPositions() > 0 && MainCtrlPosNo < elfpositions) - { - // the old positions in the file: without the fix-up the controller would have no power position, and the - // reverser would stop working at neutral (DirChangeMaxPos read before, in the old positions) - MainCtrlMaxDirChangePos += EIMCtrlEmergencyPositions(); - ErrorLog(std::format("Bad fiz: EIMCtrlMainEmergency needs MCPN={} in {}, DirChangeMaxPos taken as {}", elfpositions, TypeName, MainCtrlMaxDirChangePos)); - MainCtrlPosNo = elfpositions; - } - - extract_value(ScndS, "ScndS", line, ""); // brak pozycji rownoleglej przy niskiej nastawie PSR - extract_value(ScndCtrlResistiveLock, "ScndCtrlResistiveLock", line, ""); // bocznikowanie tylko na pozycjach bezoporowych - - extract_value(InitialCtrlDelay, "IniCDelay", line, ""); - extract_value(CtrlDelay, "SCDelay", line, ""); - CtrlDownDelay = CtrlDelay; // hunter-101012: jesli nie ma SCDDelay; - extract_value(CtrlDownDelay, "SCDDelay", line, ""); - - // hunter-111012: dla siodemek 303E - FastSerialCircuit = ToLower(extract_value("FSCircuit", line)) == "yes" ? 1 : 0; - extract_value(BackwardsBranchesAllowed, "BackwardsBranchesAllowed", line, ""); - - extract_value(AutomaticCabActivation, "AutomaticCabActivation", line, ""); - extract_value(InactiveCabFlag, "InactiveCabFlag", line, ""); - - extract_value(StopBrakeDecc, "SBD", line, ""); - extract_value(StopBrakeReleaseDelay, "SBDReleaseDelay", line, ""); // the holding brake waits for the power demand this long, s - extract_value(ReleaseParkingBySpringBrake, "ReleaseParkingBySpringBrake", line, ""); - extract_value(ReleaseParkingBySpringBrakeWhenDoorIsOpen, "ReleaseParkingBySpringBrakeWhenDoorIsOpen", line, ""); - extract_value(SpringBrakeCutsOffDrive, "SpringBrakeCutsOffDrive", line, ""); - extract_value(SpringBrakeDriveEmergencyVel, "SpringBrakeDriveEmergencyVel", line, ""); - - extract_value(HideDirStatusWhenMoving, "HideDirStatusWhenMoving", line, ""); - extract_value(HideDirStatusSpeed, "HideDirStatusSpeed", line, ""); - extract_value(isDoubleClickForMeasureNeeded, "DCMB", line, ""); - extract_value(DistanceCounterDoublePressPeriod, "DCDPP", line, ""); - - extract_value(isBatteryButtonImpulse, "IBTB", line, ""); - extract_value(shouldHoldBatteryButton, "SBBBH", line, ""); - extract_value(BatteryButtonHoldTime, "BBHT", line, ""); -} - -// Cntrl.: how the devices start (MainStart, BatteryStart, ...) and their relays -void TMoverParameters::LoadFIZ_CntrlStarts(std::string const &line) -{ - using enum start_t; - std::map> starts{{"Disabled", disabled}, {"Manual", manual}, {"Automatic", automatic}, {"Mixed", manualwithautofallback}, - {"Battery", battery}, {"Converter", converter}, {"Direction", direction}}; - - // main circuit - extract_value(MainsInitTime, "MainInitTime", line, ""); - { - auto lookup = starts.find(extract_value("MainStart", line)); - MainsStart = lookup != starts.end() ? lookup->second : manual; - } - extract_value(PantographsRequireMains, "PantRequiresMain", line, ""); - // the brake pipe pressure of an emergency brake application, which opens the line breaker under power - extract_value(EmergencyBrakeMainOffPressure, "EmergencyBrakeMainOff", line, ""); - EmergencyBrakeMainOffPressure = std::max(0.0, EmergencyBrakeMainOffPressure); - // battery - { - auto lookup = starts.find(extract_value("BatteryStart", line)); - BatteryStart = lookup != starts.end() ? lookup->second : manual; - } - // converter - { - auto lookup = starts.find(extract_value("ConverterStart", line)); - ConverterStart = lookup != starts.end() ? lookup->second : manual; - } - extract_value(ConverterStartDelay, "ConverterStartDelay", line, ""); - extract_value(ConverterOverloadRelayOffWhenMainIsOff, "ConverterOverloadWhenMainIsOff", line, TrainType == train_type::emu ? "yes" : "no"); - // compressor - { - auto lookup = starts.find(extract_value("CompressorStart", line)); - CompressorStart = lookup != starts.end() ? lookup->second : manual; - } - // pantograph compressor - { - auto lookup = starts.find(extract_value("PantCompressorStart", line)); - PantographCompressorStart = lookup != starts.end() ? lookup->second : manual; - } - // pantograph compressor valve - PantAutoValve = TrainType == train_type::emu; // legacy code behaviour, automatic valve was initially installed in all EMUs - extract_value(PantAutoValve, "PantAutoValve", line, ""); - // pantographs valve - { - auto lookup = starts.find(extract_value("PantEPValveStart", line)); - PantsValve.start_type = lookup != starts.end() ? lookup->second : automatic; // legacy code behaviour, there was no pantographs valve - extract_value(PantsValve.spring, "PantEPValveSpring", line, ""); - } - // pantograph valve configuration - { - auto lookup = starts.find(extract_value("PantValveStart", line)); - auto valvestarttype = lookup != starts.end() ? lookup->second : manual; - auto valvespring{true}; - extract_value(valvespring, "PantValveSpring", line, ""); - auto valvesolenoid{true}; - extract_value(valvesolenoid, "PantValveSolenoid", line, ""); - for (auto &pantograph : Pantographs) - { - pantograph.valve.spring = valvespring; - pantograph.valve.solenoid = valvesolenoid; - pantograph.valve.start_type = valvestarttype; - } - } - // fuel pump - { - auto lookup = starts.find(extract_value("FuelStart", line)); - FuelPump.start_type = lookup != starts.end() ? lookup->second : manual; - } - // oil pump - { - auto lookup = starts.find(extract_value("OilStart", line)); - OilPump.start_type = lookup != starts.end() ? lookup->second : manual; - } - // genset of a dual-mode vehicle: Manual (the default) needs GensetSwitch, Automatic runs whenever the selector is on it - { - auto lookup = starts.find(extract_value("GensetStart", line)); - Genset.start_type = lookup != starts.end() ? lookup->second : manual; - } - // water pump - { - auto lookup = starts.find(extract_value("WaterStart", line)); - WaterPump.start_type = lookup != starts.end() ? lookup->second : manual; - } - // traction motor fans - { - auto lookup = starts.find(extract_value("MotorBlowersStart", line)); - MotorBlowers[end::rear].start_type = lookup != starts.end() ? lookup->second : manual; - MotorBlowers[end::front].start_type = MotorBlowers[end::rear].start_type; - } - // what else the line contactors need to close - { - std::map> const interlocks{{"Converter", line_contactors_interlock::converter}, - {"MotorBlowers", line_contactors_interlock::motor_blowers}}; - auto lookup = interlocks.find(extract_value("LineContactorsInterlock", line)); - LineContactorsInterlock = lookup != interlocks.end() ? lookup->second : line_contactors_interlock::none; - } - extract_value(LouvresOpenPressure, "LouvresOpenPressure", line, ""); - // compartment lights - { - auto lookup = starts.find(extract_value("CompartmentLightsStart", line)); - CompartmentLights.start_type = lookup != starts.end() ? lookup->second : automatic; // legacy behaviour - } - // ground relay - { - auto lookup = starts.find(extract_value("GroundRelayStart", line)); - auto const defaultstart{TrainType == train_type::emu ? automatic : manual}; - GroundRelayStart = lookup != starts.end() ? lookup->second : defaultstart; - } - // converter overload relay - { - auto lookup = starts.find(extract_value("ConverterOverloadRelayStart", line)); - // the relay of a multiple unit activates when the converter is switched off - auto const defaultstart{TrainType == train_type::emu ? converter : manual}; - ConverterOverloadRelayStart = lookup != starts.end() ? lookup->second : defaultstart; - } -} - -void TMoverParameters::LoadFIZ_Blending(std::string const &line) -{ - - extract_value(MED_Vmax, "MED_Vmax", line, std::to_string(Vmax)); - extract_value(MED_Vmin, "MED_Vmin", line, "0"); - extract_value(MED_Vref, "MED_Vref", line, std::to_string(Vmax)); - extract_value(MED_amax, "MED_amax", line, "9.81"); - extract_value(MED_EPVC, "MED_EPVC", line, ""); - extract_value(MED_Ncor, "MED_Ncor", line, ""); - extract_value(MED_MinBrakeReqED, "MED_MinBrakeReqED", line, ""); - extract_value(MED_FrED_factor, "MED_FrEDFactor", line, ""); - extract_value(MED_ED_Delay1, "MED_FirstDelayED", line, ""); - extract_value(MED_ED_Delay2, "MED_ScndDelayED", line, ""); -} - -void TMoverParameters::LoadFIZ_DCEMUED(std::string const &line) -{ - - extract_value(DCEMUED_CC, "CouplerCheck", line, "0"); - extract_value(DCEMUED_EP_max_Vel, "EP_max_Vel", line, "0"); - extract_value(DCEMUED_EP_min_Im, "EP_min_Im", line, "0"); - extract_value(DCEMUED_EP_delay, "EP_delay", line, "0"); -} - -void TMoverParameters::LoadFIZ_SpringBrake(std::string const &line) -{ - - double vol{1.0}; - extract_value(vol, "Volume", line, "1"); - if (!SpringBrake.Cylinder) - SpringBrake.Cylinder = std::make_shared(); - SpringBrake.Cylinder->CreateCap(vol); - extract_value(SpringBrake.MaxBrakeForce, "MBF", line, ""); - extract_value(SpringBrake.MaxSetPressure, "MaxSP", line, ""); - extract_value(SpringBrake.ResetPressure, "ResetP", line, ""); - extract_value(SpringBrake.MinForcePressure, "MinFP", line, ""); - extract_value(SpringBrake.PressureOff, "PressOff", line, ""); - extract_value(SpringBrake.PressureOn, "PressOn", line, ""); - extract_value(SpringBrake.ValveOffArea, "ValveOnArea", line, ""); - extract_value(SpringBrake.ValveOnArea, "ValveOffArea", line, ""); - extract_value(SpringBrake.ValvePNBrakeArea, "ValvePNBArea", line, ""); - SpringBrake.PNBrakeConnection = SpringBrake.ValvePNBrakeArea > 0; - extract_value(SpringBrake.MultiTractionCoupler, "MTC", line, ""); - SpringBrake.ShuttOff = false; - SpringBrake.Activate = false; - SpringBrake.IsReady = true; -} - -void TMoverParameters::LoadFIZ_Light(std::string const &line) -{ - - LightPowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("Light", line)); - LoadFIZ_PowerParamsDecode(LightPowerSource, "L", line); - - AlterLightPowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("AlterLight", line)); - LoadFIZ_PowerParamsDecode(AlterLightPowerSource, "AlterL", line); - - extract_value(NominalVoltage, "Volt", line, ""); - extract_value(BatteryVoltage, "LMaxVoltage", line, ""); - NominalBatteryVoltage = static_cast(BatteryVoltage); -} - -void TMoverParameters::LoadFIZ_Clima(std::string const &line) -{ - - HeatingPowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("Heating", line)); - LoadFIZ_PowerParamsDecode(HeatingPowerSource, "H", line); - AlterHeatPowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("AlterHeating", line)); - LoadFIZ_PowerParamsDecode(AlterHeatPowerSource, "AlterH", line); -} - -void TMoverParameters::LoadFIZ_Power(std::string const &Line) -{ - - EnginePowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("EnginePower", Line)); - LoadFIZ_PowerParamsDecode(EnginePowerSource, "", Line); - /* - if( ( EnginePowerSource.SourceType == TPowerSource::Generator ) - && ( EnginePowerSource.GeneratorEngine == TEngineType::WheelsDriven ) ) { - // perpetuum mobile? - ConversionError = 666; - } - */ - if (Power == 0.0) - { - // jeśli nie ma mocy, np. rozrządcze EZT - EnginePowerSource.SourceType = TPowerSource::NotDefined; - } - else - { - LoadFIZ_Genset(Line); - } - - SystemPowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("SystemPower", Line)); - LoadFIZ_PowerParamsDecode(SystemPowerSource, "", Line); -} - -// the genset of a dual-mode vehicle (eu07/maszyna#536), on the Power: line; all optional, no genset without GensetPower -void TMoverParameters::LoadFIZ_Genset(std::string const &Line) -{ - extract_value(Genset.power, "GensetPower", Line, ""); - if (false == Genset.fitted()) - { - return; - } - extract_value(Genset.voltage_nominal, "GensetVoltage", Line, ""); - if (Genset.voltage_nominal <= 0.0) - { - Genset.voltage_nominal = EnginePowerSource.MaxVoltage > 0.0 ? 0.65 * EnginePowerSource.MaxVoltage : 3000.0; - } - extract_value(Genset.revolutions_idle, "GensetIdleRPM", Line, "600"); - extract_value(Genset.revolutions_max, "GensetMaxRPM", Line, "1800"); - Genset.revolutions_max = std::max(Genset.revolutions_max, 1.0) / 60.0; - Genset.revolutions_idle = std::clamp(Genset.revolutions_idle / 60.0, 1.0 / 60.0, Genset.revolutions_max); - extract_value(Genset.start_time, "GensetStartTime", Line, "8"); - extract_value(Genset.spinup_time, "GensetSpinUpTime", Line, "3"); - extract_value(Genset.traction_share, "GensetPmaxRatio", Line, "1"); - Genset.start_time = std::max(Genset.start_time, 0.0); - Genset.spinup_time = std::max(Genset.spinup_time, 0.01); - Genset.traction_share = std::clamp(Genset.traction_share, 0.0, 1.0); -} - -void TMoverParameters::LoadFIZ_SpeedControl(std::string const &Line) -{ - // speed control - extract_value(SpeedCtrl, "SpeedCtrl", Line, ""); - if (!SpeedCtrl && EngineType == TEngineType::ElectricInductionMotor && ScndCtrlPosNo > 0) // backward compatibility - SpeedCtrl = true; - extract_value(SpeedCtrlDelay, "SpeedCtrlDelay", Line, ""); - SpeedCtrlTypeTime = extract_value("SpeedCtrlType", Line) == "Time" ? true : false; - extract_value(SpeedCtrlAutoTurnOffFlag, "SpeedCtrlATOF", Line, ""); - - auto speedpresets = Split(extract_value("SpeedButtons", Line), '|'); - int speed_no = 0; - for (auto const &speed : speedpresets) - { - SpeedCtrlButtons[speed_no++] = std::stod(speed); - if (speed_no > 9) - break; - } - extract_value(SpeedCtrlUnit.ManualStateOverride, "OverrideManual", Line, ""); - extract_value(SpeedCtrlUnit.BrakeIntervention, "BrakeIntervention", Line, ""); - extract_value(SpeedCtrlUnit.InitialPower, "InitPwr", Line, ""); - extract_value(SpeedCtrlUnit.FullPowerVelocity, "MaxPwrVel", Line, ""); - extract_value(SpeedCtrlUnit.StartVelocity, "StartVel", Line, ""); - extract_value(SpeedCtrlUnit.VelocityStep, "VelStep", Line, ""); - extract_value(SpeedCtrlUnit.PowerStep, "PwrStep", Line, ""); - extract_value(SpeedCtrlUnit.MinPower, "MinPwr", Line, ""); - extract_value(SpeedCtrlUnit.MaxPower, "MaxPwr", Line, ""); - extract_value(SpeedCtrlUnit.MinVelocity, "MinVel", Line, ""); - extract_value(SpeedCtrlUnit.MaxVelocity, "MaxVel", Line, ""); - extract_value(SpeedCtrlUnit.Offset, "Offset", Line, ""); - extract_value(SpeedCtrlUnit.FactorPpos, "kPpos", Line, ""); - extract_value(SpeedCtrlUnit.FactorPneg, "kPneg", Line, ""); - extract_value(SpeedCtrlUnit.FactorIpos, "kIpos", Line, ""); - extract_value(SpeedCtrlUnit.FactorIneg, "kIneg", Line, ""); - extract_value(SpeedCtrlUnit.BrakeInterventionVel, "BrakeIntMaxVel", Line, ""); - extract_value(SpeedCtrlUnit.PowerUpSpeed, "PowerUpSpeed", Line, ""); - extract_value(SpeedCtrlUnit.PowerDownSpeed, "PowerDownSpeed", Line, ""); -} - -void TMoverParameters::LoadFIZ_Engine(std::string const &Input) -{ - - EngineType = LoadFIZ_EngineDecode(extract_value("EngineType", Input)); - extract_value(JointEngineStart, "JointEngineStart", Input, ""); - - if (std::string transmission = extract_value("Trans", Input); false == transmission.empty()) - { - // transmission type. moved here because more than one engine type has this entry - auto ratios = Split(transmission, ':'); // e.g. 18:79 - - if (ratios.size() != 2) - { - ErrorLog("Wrong transmition definition: " + transmission); - } - - Transmision.NToothM = std::atoi(ratios[0].c_str()); // ToothM to pierwszy czyli 18 - Transmision.NToothW = std::atoi(ratios[1].c_str()); // ToothW to drugi parametr czyli 79 - - if (Transmision.NToothM > 0) - Transmision.Ratio = static_cast(Transmision.NToothW) / Transmision.NToothM; - else - Transmision.Ratio = 1.0; - extract_value(Transmision.Efficiency, "TransEff", Input, ""); - } - - switch (EngineType) - { - - case TEngineType::ElectricSeriesMotor: - { - - extract_value(NominalVoltage, "Volt", Input, ""); - extract_value(WindingRes, "WindingRes", Input, ""); - if (WindingRes == 0.0) - { - - WindingRes = 0.01; - } - extract_value(nmax, "nmax", Input, ""); - nmax /= 60.0; - break; - } - case TEngineType::WheelsDriven: - case TEngineType::Dumb: - { - - extract_value(Ftmax, "Ftmax", Input, ""); - break; - } - case TEngineType::DieselEngine: - { - LoadFIZ_EngineDiesel(Input); - break; - } - case TEngineType::DieselElectric: - { // youBy - LoadFIZ_EngineDieselElectric(Input); - break; - } - case TEngineType::ElectricInductionMotor: - { - LoadFIZ_EngineInductionMotor(Input); - break; - } - default: - { - // nothing here - } - } // engine type - - // NOTE: elements shared by both diesel engine variants; crude but, eh - if (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric) - { - LoadFIZ_EngineDieselShared(Input); - } - - // traction motors - extract_value(MotorBlowers[end::front].speed, "MotorBlowersSpeed", Input, ""); - extract_value(MotorBlowers[end::front].sustain_time, "MotorBlowersSustainTime", Input, ""); - extract_value(MotorBlowers[end::front].min_start_velocity, "MotorBlowersStartVelocity", Input, ""); - MotorBlowers[end::rear] = MotorBlowers[end::front]; - // pressure switch - extract_value(HasControlPressureSwitch, "PressureSwitch", Input, TrainType != train_type::emu ? "yes" : "no"); - // its brake cylinder half; the brake pipe one stays - extract_value(PressureSwitchBrakeCylinder, "PressureSwitchBrakeCylinder", Input, ""); -} - -// Engine: of a diesel engine, its revolutions, gears, hydraulic transmission and retarder -void TMoverParameters::LoadFIZ_EngineDiesel(std::string const &Input) -{ - - extract_value(dizel_nmin, "nmin", Input, ""); - dizel_nmin /= 60.0; - dizel_nreg_min = dizel_nmin * 0.98; - extract_value(dizel_nmin_hdrive, "nmin_hdrive", Input, ""); - dizel_nmin_hdrive /= 60.0; - if (dizel_nmin_hdrive == 0.0) - { - dizel_nmin_hdrive = dizel_nmin; - } - extract_value(dizel_nmin_hdrive_factor, "nmin_hdrive_factor", Input, ""); - dizel_nmin_hdrive_factor /= 60.0; - extract_value(dizel_nmin_retarder, "nmin_retarder", Input, ""); - dizel_nmin_retarder /= 60.0; - if (dizel_nmin_retarder == 0.0) - { - dizel_nmin_retarder = dizel_nmin; - } - // TODO: unify naming scheme and sort out which diesel engine params are used where and how - extract_value(nmax, "nmax", Input, ""); - nmax /= 60.0; - extract_value(dizel_nmax_cutoff, "nmax_cutoff", Input, "0.0"); - dizel_nmax_cutoff /= 60.0; - extract_value(dizel_nreg_acc, "nreg_acc", Input, ""); - dizel_nreg_acc /= 60.0; - extract_value(dizel_AIM, "AIM", Input, "1.0"); - extract_value(dizel_RevolutionsDecreaseRate, "RPMDecRate", Input, ""); - - extract_value(engageupspeed, "EUS", Input, "0.5"); - extract_value(engagedownspeed, "EDS", Input, "0.9"); - - if (true == extract_value(AnPos, "ShuntMode", Input, "")) - { - // dodatkowa przekładnia dla SM03 (2Ls150) - ShuntModeAllow = true; - ShuntMode = false; - if (AnPos < 1.0) - { - //"rozruch wysoki" ma dawać większą siłę - AnPos = 1.0 / AnPos; // im większa liczba, tym wolniej jedzie - } - } - extract_value(hydro_TC, "IsTC", Input, ""); - if (true == hydro_TC) - { - extract_value(hydro_TC_TMMax, "TC_TMMax", Input, ""); - extract_value(hydro_TC_CouplingPoint, "TC_CP", Input, ""); - extract_value(hydro_TC_LockupTorque, "TC_LT", Input, ""); - extract_value(hydro_TC_LockupRate, "TC_LR", Input, ""); - extract_value(hydro_TC_UnlockRate, "TC_ULR", Input, ""); - extract_value(hydro_TC_FillRateInc, "TC_FRI", Input, ""); - extract_value(hydro_TC_FillRateDec, "TC_FRD", Input, ""); - extract_value(hydro_TC_TorqueInIn, "TC_TII", Input, ""); - extract_value(hydro_TC_TorqueInOut, "TC_TIO", Input, ""); - extract_value(hydro_TC_TorqueOutOut, "TC_TOO", Input, ""); - extract_value(hydro_TC_LockupSpeed, "TC_LS", Input, ""); - extract_value(hydro_TC_UnlockSpeed, "TC_ULS", Input, ""); - extract_value(dizel_maxVelANS, "MaxVelANS", Input, ""); - - extract_value(hydro_R, "IsRetarder", Input, ""); - if (true == hydro_R) - { - extract_value(hydro_R_Placement, "R_Place", Input, ""); - extract_value(hydro_R_TorqueInIn, "R_TII", Input, ""); - extract_value(hydro_R_MaxTorque, "R_MT", Input, ""); - extract_value(hydro_R_MaxPower, "R_MP", Input, ""); - extract_value(hydro_R_FillRateInc, "R_FRI", Input, ""); - extract_value(hydro_R_FillRateDec, "R_FRD", Input, ""); - extract_value(hydro_R_MinVel, "R_MinVel", Input, ""); - extract_value(hydro_R_EngageVel, "R_EngageVel", Input, ""); - extract_value(hydro_R_Clutch, "R_IsClutch", Input, ""); - extract_value(hydro_R_ClutchSpeed, "R_ClutchSpeed", Input, ""); - extract_value(hydro_R_WithIndividual, "R_WithIndividual", Input, ""); - } - } -} - -// Engine: of a diesel-electric -void TMoverParameters::LoadFIZ_EngineDieselElectric(std::string const &Input) -{ - - extract_value(Ftmax, "Ftmax", Input, ""); - Flat = extract_value("Flat", Input) == "1"; - extract_value(Vhyp, "Vhyp", Input, ""); - Vhyp /= 3.6; - extract_value(Vadd, "Vadd", Input, ""); - Vadd /= 3.6; - extract_value(PowerCorRatio, "Cr", Input, ""); - extract_value(RelayType, "RelayType", Input, ""); - if (extract_value("ShuntMode", Input) == "1") - { - - ShuntModeAllow = true; - ShuntMode = false; - AnPos = 0.0; - ImaxHi = 2; - ImaxLo = 1; - } - extract_value(EngineHeatingRPM, "HeatingRPM", Input, ""); - extract_value(dizel_AIM, "AIM", Input, "1.25"); - extract_value(dizel_RevolutionsDecreaseRate, "RPMDecRate", Input, ""); - LoadFIZ_DieselElectricDynamicBrake(Input); -} - -// Engine: of an induction motor drive -void TMoverParameters::LoadFIZ_EngineInductionMotor(std::string const &Input) -{ - - RVentnmax = 1.0; - extract_value(NominalVoltage, "Volt", Input, ""); - - extract_value(eimc[eimc_s_dfic], "dfic", Input, ""); - extract_value(eimc[eimc_s_dfmax], "dfmax", Input, ""); - extract_value(eimc[eimc_s_p], "p", Input, ""); - extract_value(eimc[eimc_s_cfu], "cfu", Input, ""); - extract_value(eimc[eimc_s_cim], "cim", Input, ""); - extract_value(eimc[eimc_s_icif], "icif", Input, ""); - extract_value(eimc[eimc_f_Uzmax], "Uzmax", Input, ""); - extract_value(eimc[eimc_f_Uzh], "Uzh", Input, ""); - extract_value(eimc[eimc_f_DU], "DU", Input, ""); - extract_value(eimc[eimc_f_I0], "I0", Input, ""); - extract_value(eimc[eimc_f_cfu], "fcfu", Input, ""); - if (false == extract_value(eimc[eimc_f_cfuH], "fcfuH", Input, "")) - { - // without its own figure the dynamic brake takes the one of the traction - eimc[eimc_f_cfuH] = eimc[eimc_f_cfu]; - } - extract_value(eimc[eimc_p_F0], "F0", Input, ""); - extract_value(eimc[eimc_p_a1], "a1", Input, ""); - extract_value(eimc[eimc_p_Pmax], "Pmax", Input, ""); - extract_value(eimc[eimc_p_Fh], "Fh", Input, ""); - extract_value(eimc[eimc_p_Ph], "Ph", Input, ""); - extract_value(eimc[eimc_p_Vh0], "Vh0", Input, ""); - extract_value(eimc[eimc_p_Vh1], "Vh1", Input, ""); - extract_value(eimc[eimc_p_Imax], "Imax", Input, ""); - extract_value(eimc[eimc_p_abed], "abed", Input, ""); - extract_value(eimc[eimc_p_eped], "edep", Input, ""); - extract_value(EIMCLogForce, "eimclf", Input, ""); - extract_value(InvertersNo, "InvNo", Input, ""); - extract_value(InverterControlCouplerFlag, "InvCtrCplFlag", Input, ""); - extract_value(Imaxrpc, "Imaxrpc", Input, ""); - extract_value(BRVto, "BRVto", Input, ""); - extract_value(Flat, "Flat", Input, ""); - - if (eimc[eimc_p_Pmax] > 0 && Power > 0 && InvertersNo == 0) - { - InvertersNo = 1; - } - Inverters.resize(InvertersNo); - /*for (int i = 0; i > InvertersNo; i++) - { - inverter x; - Inverters.emplace_back(x); - }*/ -} - -// Engine: what both kinds of diesels have, their heat among it -void TMoverParameters::LoadFIZ_EngineDieselShared(std::string const &Input) -{ - // oil pump - extract_value(OilPump.pressure_minimum, "OilMinPressure", Input, ""); - extract_value(OilPump.pressure_maximum, "OilMaxPressure", Input, ""); - // the time the starter turns the engine before it fires and smokes (eu07/maszyna#523) - extract_value(dizel_SmokeDelay, "SmokeDelay", Input, "0"); - dizel_SmokeDelay = std::max(0.0, dizel_SmokeDelay); - // engine cooling factore - extract_value(dizel_heat.kw, "HeatKW", Input, ""); - extract_value(dizel_heat.kv, "HeatKV", Input, ""); - extract_value(dizel_heat.kfe, "HeatKFE", Input, ""); - extract_value(dizel_heat.kfs, "HeatKFS", Input, ""); - extract_value(dizel_heat.kfo, "HeatKFO", Input, ""); - extract_value(dizel_heat.kfo2, "HeatKFO2", Input, ""); - // engine cooling systems - extract_value(dizel_heat.water.config.temp_min, "WaterMinTemperature", Input, ""); - extract_value(dizel_heat.water.config.temp_max, "WaterMaxTemperature", Input, ""); - extract_value(dizel_heat.water.config.temp_flow, "WaterFlowTemperature", Input, ""); - extract_value(dizel_heat.water.config.temp_cooling, "WaterCoolingTemperature", Input, ""); - extract_value(dizel_heat.water.config.shutters, "WaterShutters", Input, ""); - extract_value(dizel_heat.auxiliary_water_circuit, "WaterAuxCircuit", Input, ""); - extract_value(dizel_heat.water_aux.config.temp_min, "WaterAuxMinTemperature", Input, ""); - extract_value(dizel_heat.water_aux.config.temp_max, "WaterAuxMaxTemperature", Input, ""); - extract_value(dizel_heat.water_aux.config.temp_cooling, "WaterAuxCoolingTemperature", Input, ""); - extract_value(dizel_heat.water_aux.config.shutters, "WaterAuxShutters", Input, ""); - extract_value(dizel_heat.oil.config.temp_min, "OilMinTemperature", Input, ""); - extract_value(dizel_heat.oil.config.temp_max, "OilMaxTemperature", Input, ""); - extract_value(dizel_heat.engine_max_temp, "EngineMaxTemperature", Input, ""); - extract_value(dizel_heat.fan_speed, "WaterCoolingFanSpeed", Input, ""); - // water heater - extract_value(WaterHeater.config.temp_min, "HeaterMinTemperature", Input, ""); - extract_value(WaterHeater.config.temp_max, "HeaterMaxTemperature", Input, ""); - float pf{1235.f}; - extract_value(pf, "NominalCoolingPower", Input, "1235"); - dizel_heat.powerfactor = 1235 / pf; -} - -void TMoverParameters::LoadFIZ_Switches(std::string const &Input) -{ - - extract_value(PantSwitchType, "Pantograph", Input, ""); - extract_value(ConvSwitchType, "Converter", Input, ""); - extract_value(StLinSwitchType, "MotorConnectors", Input, ""); - HeatingSwitchImpulse = ToLower(extract_value("TrainHeating", Input)) == "impulse"; - // because people can't make up their minds whether it's "impulse" or "Impulse"... - PantSwitchType = ToLower(PantSwitchType); - ConvSwitchType = ToLower(ConvSwitchType); - StLinSwitchType = ToLower(StLinSwitchType); - // universal reset buttons assignments - extract_value(UniversalResetButtonFlag[0], "RelayResetButton1", Input, ""); - extract_value(UniversalResetButtonFlag[1], "RelayResetButton2", Input, ""); - extract_value(UniversalResetButtonFlag[2], "RelayResetButton3", Input, ""); - extract_value(enableModernDimmer, "ModernDimmer", Input, ""); - // pantograph presets - { - auto &presets{PantsPreset.first}; - extract_value(presets, "PantographPresets", Input, "0|1|3|2"); - std::erase(presets, '|'); - } -} - -void TMoverParameters::LoadFIZ_MotorParamTable(std::string const &Input) -{ - - switch (EngineType) - { - - case TEngineType::DieselEngine: - { - - extract_value(dizel_minVelfullengage, "minVelfullengage", Input, ""); - extract_value(dizel_engageDia, "engageDia", Input, ""); - extract_value(dizel_engageMaxForce, "engageMaxForce", Input, ""); - extract_value(dizel_engagefriction, "engagefriction", Input, ""); - break; - } - default: - { - // nothing here - } - } -} - -void TMoverParameters::LoadFIZ_Circuit(std::string const &Input) -{ - - extract_value(CircuitRes, "CircuitRes", Input, ""); - extract_value(IminLo, "IminLo", Input, ""); - extract_value(IminHi, "IminHi", Input, ""); - extract_value(ImaxLo, "ImaxLo", Input, ""); - extract_value(ImaxHi, "ImaxHi", Input, ""); - Imin = IminLo; - Imax = ImaxLo; - extract_value(TUHEX_Sum, "TUHEX_Sum", Input, ""); - extract_value(TUHEX_Diff, "TUHEX_Diff", Input, ""); - extract_value(TUHEX_MaxIw, "TUHEX_MaxIw", Input, ""); - extract_value(TUHEX_MinIw, "TUHEX_MinIw", Input, ""); - extract_value(TUHEX_Sum1, "TUHEX_Sum1", Input, ""); - extract_value(TUHEX_Sum2, "TUHEX_Sum2", Input, ""); - extract_value(TUHEX_Sum3, "TUHEX_Sum3", Input, ""); - extract_value(TUHEX_Stages, "TUHEX_Stages", Input, "0"); -} - -void TMoverParameters::LoadFIZ_AI(std::string const &Input) -{ - - extract_value(AIHintPantstate, "Pantstate", Input, ""); - extract_value(AIHintShuntPantstate, "ShuntPantstate", Input, ""); - extract_value(AIHintPantUpIfIdle, "IdlePantUp", Input, ""); - extract_value(AIHintLocalBrakeAccFactor, "LocalBrakeAccFactor", Input, ""); -} - -void TMoverParameters::LoadFIZ_RList(std::string const &Input) -{ - - extract_value(RlistSize, "Size", Input, ""); - - if (auto const venttype{ToLower(extract_value("RVent", Input))}; venttype == "automatic") - { - - RVentType = 2; - } - else - { - - RVentType = venttype == "yes" ? 1 : 0; - } - - if (RVentType > 0) - { - - extract_value(RVentnmax, "RVentnmax", Input, ""); - RVentnmax /= 60.0; - extract_value(RVentCutOff, "RVentCutOff", Input, ""); - } - extract_value(RVentMinI, "RVentMinI", Input, ""); - extract_value(RVentSpeed, "RVentSpeed", Input, ""); - extract_value(DynamicBrakeRes, "DynBrakeRes", Input, ""); - extract_value(DynamicBrakeRes1, "DynBrakeRes1", Input, ""); - extract_value(DynamicBrakeRes2, "DynBrakeRes2", Input, ""); -} - -// the dynamic brake of a diesel-electric vehicle, from its Engine section: none without EDBrake -void TMoverParameters::LoadFIZ_DieselElectricDynamicBrake(std::string const &Input) -{ - using enum diesel_electric_dynamic_brake::control; - std::map> const sources{{"Controller", controller}, {"Lever", lever}}; - auto const lookup{sources.find(extract_value("EDBrake", Input))}; - if (lookup == sources.end()) - { - return; - } - auto &brake{DEDynamicBrake}; - brake.source = lookup->second; - auto force{0.0}; // [kN] - auto power{0.0}; // [kW] - extract_value(force, "EDBrakeFmax", Input, ""); - extract_value(power, "EDBrakePmax", Input, ""); - brake.max_force = force * 1000.0; - brake.max_power = power * 1000.0; - extract_value(brake.fade_low, "EDBrakeV0", Input, ""); - extract_value(brake.fade_high, "EDBrakeV1", Input, ""); - extract_value(brake.rate, "EDBrakeRate", Input, ""); - extract_value(brake.blending, "EDBrakeBlending", Input, ""); - if (brake.source == lever) - { - // the lever of its own, which the commands of the dynamic brake controller move - SplitEDPneumaticBrake = true; - } -} - -void TMoverParameters::LoadFIZ_UCList(std::string const &Input) -{ - - extract_value(UniCtrlListSize, "Size", Input, ""); - extract_value(UniCtrlIntegratedBrakeCtrl, "IntegratedBrake", Input, ""); - extract_value(UniCtrlIntegratedLocalBrakeCtrl, "IntegratedLocBrake", Input, ""); - extract_value(UniCtrlIntegratedBrakePNCtrl, "IntegratedBrakePN", Input, ""); - extract_value(UniCtrlValStep, "CtrlValStep", Input, ""); - UniCtrlValStep = std::max(UniCtrlValStep, 0.0); -} - -void TMoverParameters::LoadFIZ_DList(std::string const &Input) -{ - - extract_value(dizel_Mmax, "Mmax", Input, ""); - extract_value(dizel_nMmax, "nMmax", Input, ""); - extract_value(dizel_Mnmax, "Mnmax", Input, ""); - extract_value(dizel_nmax, "nmax", Input, ""); - extract_value(dizel_nominalfill, "nominalfill", Input, ""); - extract_value(dizel_Mstand, "Mstand", Input, ""); - extract_value(dizel_NominalFuelConsumptionRate, "NomFuelConsRate", Input, ""); - - if (dizel_nMmax == dizel_nmax) - { - // HACK: guard against cases where nMmax == nmax, leading to division by 0 in momentum calculation - dizel_nMmax = dizel_nmax - 1.0 / 60.0; - } - - // Calculation of fuel consumption coefficient for futher calculation - double dizel_max_power = dizel_nmax * (dizel_Mnmax - dizel_Mstand) * M_PI * 2 * 0.001; // power in kW - double dizel_max_energy = dizel_max_power; // energy per one hour in kWh is equal to power in kW times 1 h - double fuel_density = 850; // g/l - dizel_FuelConsumption = dizel_NominalFuelConsumptionRate * dizel_max_energy / fuel_density / dizel_nmax; -} - -void TMoverParameters::LoadFIZ_FFList(std::string const &Input) -{ - extract_value(FFListSize, "Size", Input, ""); -} - -void TMoverParameters::LoadFIZ_FFEDList(std::string const &Input) -{ - extract_value(FFEDListSize, "Size", Input, ""); -} - -void TMoverParameters::LoadFIZ_WiperList(std::string const &Input) -{ - extract_value(WiperListSize, "Size", Input, ""); - extract_value(WiperAngle, "Angle", Input, ""); - extract_value(WiperDefaultPos, "Default", Input, ""); -} - -void TMoverParameters::LoadFIZ_DimmerList(std::string const &Input) -{ - // extract_value(modernWpierListSize, "Size", Input, ""); - extract_value(modernDimmerCanCycle, "Cycle", Input, ""); - extract_value(modernDimmerDefaultPosition, "DefaultPos", Input, ""); -} -void TMoverParameters::LoadFIZ_LightsList(std::string const &Input) -{ - - extract_value(LightsPosNo, "Size", Input, ""); - extract_value(LightsWrap, "Wrap", Input, ""); - extract_value(LightsDefPos, "Default", Input, ""); -} - -void TMoverParameters::LoadFIZ_CompressorList(std::string const &Input) -{ - - extract_value(CompressorListPosNo, "Size", Input, ""); - extract_value(CompressorListWrap, "Wrap", Input, ""); - extract_value(CompressorListDefPos, "Default", Input, ""); -} - -void TMoverParameters::LoadFIZ_PowerParamsDecode(TPowerParameters &Powerparameters, std::string const &Prefix, std::string const &Line) -{ - - switch (Powerparameters.SourceType) - { - - case TPowerSource::NotDefined: - case TPowerSource::InternalSource: - { - - Powerparameters.PowerType = LoadFIZ_PowerDecode(extract_value(Prefix + "PowerType", Line)); - break; - } - case TPowerSource::Transducer: - { - - extract_value(Powerparameters.Transducer.InputVoltage, Prefix + "TransducerInputV", Line, ""); - break; - } - case TPowerSource::Generator: - { - // prime mover for the generator - auto &generatorparameters{Powerparameters.EngineGenerator}; - - if (auto const enginetype{LoadFIZ_EngineDecode(extract_value(Prefix + "GeneratorEngine", Line))}; enginetype == TEngineType::Main) - { - generatorparameters.engine_revolutions = &enrot; - } - else - { - // TODO: for engine types other than Main create requested engine object and link to its revolutions - generatorparameters.engine_revolutions = nullptr; - generatorparameters.revolutions = 0; - generatorparameters.voltage = 0; - } - // config - extract_value(generatorparameters.voltage_min, Prefix + "GeneratorMinVoltage", Line, "0"); - extract_value(generatorparameters.voltage_max, Prefix + "GeneratorMaxVoltage", Line, "0"); - // NOTE: for consistency the fiz file specifies revolutions per minute - extract_value(generatorparameters.revolutions_min, Prefix + "GeneratorMinRPM", Line, "0"); - extract_value(generatorparameters.revolutions_max, Prefix + "GeneratorMaxRPM", Line, "0"); - generatorparameters.revolutions_min /= 60; - generatorparameters.revolutions_max /= 60; - break; - } - case TPowerSource::Accumulator: - { - - extract_value(Powerparameters.RAccumulator.MaxCapacity, Prefix + "Cap", Line, ""); - Powerparameters.RAccumulator.RechargeSource = LoadFIZ_SourceDecode(extract_value(Prefix + "RS", Line)); - break; - } - case TPowerSource::CurrentCollector: - { - - auto &collectorparameters = Powerparameters.CollectorParameters; - - collectorparameters = TCurrentCollector{0, 0, 0, 0, 0, 0, false, 0, 0, 0, false, 0}; - - std::string PantType = ""; - extract_value(PantType, "PantType", Line, ""); - if (PantType == "AKP_4E") - collectorparameters.PantographType = TPantType::AKP_4E; - if (PantType.size() >= 3 && PantType.compare(0, 3, "DSA") == 0) - collectorparameters.PantographType = TPantType::DSAx; - if (PantType == "EC160" || PantType == "EC200") - collectorparameters.PantographType = TPantType::EC160_200; - if (PantType == "WBL85") - collectorparameters.PantographType = TPantType::WBL85; - - extract_value(collectorparameters.CollectorsNo, "CollectorsNo", Line, ""); - extract_value(collectorparameters.MinH, "MinH", Line, ""); - extract_value(collectorparameters.MaxH, "MaxH", Line, ""); - extract_value(collectorparameters.CSW, "CSW", Line, ""); // szerokość części roboczej - extract_value(collectorparameters.MaxV, "MaxVoltage", Line, ""); - extract_value(collectorparameters.OVP, "OverVoltProt", Line, ""); // przekaźnik nadnapięciowy - // napięcie rozłączające WS - collectorparameters.MinV = 0.5 * collectorparameters.MaxV; // gdyby parametr nie podany - extract_value(collectorparameters.MinV, "MinV", Line, ""); - // napięcie wymagane do załączenia WS - collectorparameters.InsetV = 0.6 * collectorparameters.MaxV; // gdyby parametr nie podany - extract_value(collectorparameters.InsetV, "InsetV", Line, ""); - // ciśnienie rozłączające WS - extract_value(collectorparameters.MinPress, "MinPress", Line, "3.5"); // domyślnie 2 bary do załączenia WS - // maksymalne ciśnienie za reduktorem - // collectorparameters.MaxPress = 5.0 + 0.001 * ( Random( 50 ) - Random( 50 ) ); - extract_value(collectorparameters.MaxPress, "MaxPress", Line, "5.0"); - extract_value(collectorparameters.FakePower, "FakePower", Line, ""); - if (extract_value(collectorparameters.PhysicalLayout, "PhysicalLayout", Line, "3")) - collectorparameters.CollectorsNo = std::min(collectorparameters.PhysicalLayout, 2); - break; - } - case TPowerSource::PowerCable: - { - - Powerparameters.RPowerCable.PowerTrans = LoadFIZ_PowerDecode(extract_value(Prefix + "PowerTrans", Line)); - if (Powerparameters.RPowerCable.PowerTrans == TPowerType::SteamPower) - { - - extract_value(Powerparameters.RPowerCable.SteamPressure, Prefix + "SteamPress", Line, ""); - } - break; - } - case TPowerSource::Heater: - { - // jeszcze nie skonczone! - break; - } - default:; // nothing here - } - - if (Powerparameters.SourceType != TPowerSource::Heater && Powerparameters.SourceType != TPowerSource::InternalSource) - { - - extract_value(Powerparameters.MaxVoltage, Prefix + "MaxVoltage", Line, ""); - extract_value(Powerparameters.MaxCurrent, Prefix + "MaxCurrent", Line, ""); - extract_value(Powerparameters.IntR, Prefix + "IntR", Line, ""); - } -} - -TPowerType TMoverParameters::LoadFIZ_PowerDecode(std::string const &Powertype) const -{ - using enum TPowerType; - - std::map> powertypes{ - {"BioPower", BioPower}, {"MechPower", MechPower}, {"ElectricPower", ElectricPower}, {"SteamPower", SteamPower}}; - auto lookup = powertypes.find(Powertype); - return lookup != powertypes.end() ? lookup->second : NoPower; -} - -TPowerSource TMoverParameters::LoadFIZ_SourceDecode(std::string const &Source) const -{ - using enum TPowerSource; - - std::map> powersources{{"Transducer", Transducer}, {"Generator", Generator}, - {"Accu", Accumulator}, // legacy compatibility leftover. TODO: check if we can get rid of it - {"Accumulator", Accumulator}, {"CurrentCollector", CurrentCollector}, - {"PowerCable", PowerCable}, {"Heater", Heater}, - {"Internal", InternalSource}, {"Main", Main}}; - auto lookup = powersources.find(Source); - return lookup != powersources.end() ? lookup->second : NotDefined; -} - -TEngineType TMoverParameters::LoadFIZ_EngineDecode(std::string const &Engine) const -{ - using enum TEngineType; - - std::map> enginetypes{{"ElectricSeriesMotor", ElectricSeriesMotor}, - {"DieselEngine", DieselEngine}, - {"SteamEngine", SteamEngine}, - {"WheelsDriven", WheelsDriven}, - {"Dumb", Dumb}, - {"DieselElectric", DieselElectric}, - {"DumbDE", DieselElectric}, - {"ElectricInductionMotor", ElectricInductionMotor}, - {"Main", Main}}; - auto lookup = enginetypes.find(Engine); - return lookup != enginetypes.end() ? lookup->second : None; -} - -// ************************************************************************************************* -// Q: 20160717 -// ************************************************************************************************* - -bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) -{ - WriteLog("check locomotive parameters..."); - bool OK = true; - - AutoRelayFlag = AutoRelayType == 1; - - if (NominalBatteryVoltage == 0.0) - { - BatteryStart = start_t::disabled; - } - - Sand = SandCapacity; - - // NOTE: for diesel-powered vehicles we automatically convert legacy "main" power source to more accurate "engine" - if (CompressorPower == 0 && (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric)) - { - CompressorPower = 3; - } - - // for these engine types secondary controller positions index MotorParam table - if ((EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric) && - ScndCtrlPosNo > MotorParametersArraySize) - { - WriteLog("SCPN=" + std::to_string(ScndCtrlPosNo) + " exceeds motor parameter table size, limited to " + std::to_string(MotorParametersArraySize)); - ScndCtrlPosNo = MotorParametersArraySize; - } - - // WriteLog("aa = " + AxleArangement + " " + std::string( Pos("o", AxleArangement)) ); - - if (contains(AxleArangement, "o") && EngineType == TEngineType::ElectricSeriesMotor) - { - // test poprawnosci ilosci osi indywidualnie napedzanych - OK = RList[1].Bn * RList[1].Mn == NPoweredAxles; - // WriteLogSS("aa ok", BoolToYN(OK)); - } - - if (BrakeSystem == TBrakeSystem::Individual && BrakeSubsystem != TBrakeSubSystem::ss_None) - OK = false; //! - - if (BrakeVVolume == 0 && MaxBrakePress[3] > 0 && BrakeSystem != TBrakeSystem::Individual) - { - BrakeVVolume = MaxBrakePress[3] / (5.0 - MaxBrakePress[3]) * (BrakeCylRadius * BrakeCylRadius * BrakeCylDist * BrakeCylNo * M_PI) * 1000; - } - if (BrakeVVolume == 0.0) - { - BrakeVVolume = 0.01; - } - // WriteLog("BVV = " + FloatToStr(BrakeVVolume)); - - CreateBrakeValve(); - - CreateBrakeHandles(); - - CreateBrakePipes(); - - if (LightsPosNo > 0) - LightsPos = LightsDefPos; - - // set default wiper switch position - wiperSwitchPos = WiperDefaultPos; - - if (CompressorListPosNo > 0) - CompressorListPos = CompressorListDefPos; - - // the genset of a dual-mode vehicle is a second source of the traction circuit of an induction motor vehicle - if (Genset.fitted() && (EngineType != TEngineType::ElectricInductionMotor || EnginePowerSource.SourceType != TPowerSource::CurrentCollector)) - { - WriteLog("GensetPower ignored: a genset works only with EngineType=ElectricInductionMotor and EnginePower=CurrentCollector"); - Genset = genset_device{}; - } - - // NOTE: legacy compatibility behaviour for vehicles without defined heating power source - if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector && HeatingPowerSource.SourceType == TPowerSource::NotDefined) - { - HeatingPowerSource.SourceType = TPowerSource::Main; - } - if (HeatingPowerSource.SourceType == TPowerSource::NotDefined && HeatingPower > 0) - { - HeatingPowerSource.SourceType = TPowerSource::PowerCable; - HeatingPowerSource.PowerType = TPowerType::ElectricPower; - } - - // checking ready flag - // to dac potem do init - if (ReadyFlag) // gotowy do drogi - { - SetReadyToDepart(); - } - else - { // zahamowany} - SetBraked(); - } - - ActFlowSpeed = 0.0; - BrakeCtrlPosR = BrakeCtrlPos; - - if (BrakeLocHandle == TBrakeHandle::Knorr) - LocalBrakePosA = 0.5; - - Pipe->CreatePress(PipePress); - Pipe2->CreatePress(ScndPipePress); - Pipe->Act(); - Pipe2->Act(); - - EqvtPipePress = PipePress; - - Handle->Init(PipePress); - - ComputeConstans(); - - if (LoadFlag > 0) - { - - if (LoadAmount < MaxLoad * 0.45) - { - IncBrakeMult(); - IncBrakeMult(); - DecBrakeMult(); // TODO: przeinesiono do mover.cpp - if (LoadAmount < MaxLoad * 0.35) - DecBrakeMult(); - } - else - { - IncBrakeMult(); // TODO: przeinesiono do mover.cpp - if (LoadAmount >= MaxLoad * 0.55) - IncBrakeMult(); - } - } - - // taki mini automat - powinno byc ladnie dobrze :) - BrakeDelayFlag = bdelay_P; - if (TestFlag(BrakeDelays, bdelay_G) && !TestFlag(BrakeDelays, bdelay_R)) - BrakeDelayFlag = bdelay_G; - if (TestFlag(BrakeDelays, bdelay_R) && !TestFlag(BrakeDelays, bdelay_G)) - BrakeDelayFlag = bdelay_R; - /* - // disabled, as test mode is used in specific situations and not really a default - if (BrakeOpModes & bom_PS) - BrakeOpModeFlag = bom_PS; - else - */ - BrakeOpModeFlag = bom_PN; - - // yB: jesli pojazdy nie maja zadeklarowanych czasow, to wsadz z przepisow +-16,(6)% - std::array const DefBrakeTable{15, 4, 25, 25, 13, 3, 12, 2}; - - for (int b = 1; b < 4; b++) - { - if (BrakeDelay[b] == 0) - BrakeDelay[b] = DefBrakeTable[b]; - BrakeDelay[b] = BrakeDelay[b] * (2.5 + Random(0.0, 0.2)) / 3.0; - } - - Hamulec->Init(PipePress, HighPipePress, LowPipePress, BrakePress, BrakeDelayFlag); - /* - ScndPipePress = Compressor; - */ - // WriteLogSS("OK=", BoolTo10(OK)); - // WriteLog(""); - - if (EIMCtrlType == 3) - { - for (auto idx = 0; idx < MainCtrlPosNo; ++idx) - { - if (UniCtrlList[idx].MaxCtrlVal > 0.0) - { - UniCtrlNoPowerPos = std::max(0, idx - 1); - break; - } - } - } - - // security system - // by default place the magnet in the vehicle centre - if (SecuritySystem.MagnetLocation == 0) - { - SecuritySystem.MagnetLocation = Dim.L / 2 - 0.5; - } - SecuritySystem.MagnetLocation = safe_clamp(SecuritySystem.MagnetLocation, 0.0, Dim.L); - - return OK; -} - -// the distributor valve of the vehicle's kind -void TMoverParameters::CreateBrakeValve() -{ - switch (BrakeValve) - { - case TBrakeValve::W: - case TBrakeValve::K: - { - WriteLog("XBT W, K"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - if (MBPM < 2) // jesli przystawka wazaca - Hamulec->SetLP(0, MaxBrakePress[3], 0); - else - Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]); - break; - } - case TBrakeValve::KE: - { - WriteLog("XBT WKE"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - Hamulec->SetRM(RapidMult); - if (MBPM < 2) // jesli przystawka wazaca - Hamulec->SetLP(0, MaxBrakePress[3], 0); - else - Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]); - break; - } - case TBrakeValve::NESt3: - case TBrakeValve::ESt3: - case TBrakeValve::ESt3AL2: - case TBrakeValve::ESt4: - { - WriteLog("XBT NESt3, ESt3, ESt3AL2, ESt4"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - static_cast(Hamulec.get())->SetSize(BrakeValveSize, BrakeValveParams); - if (MBPM < 2) // jesli przystawka wazaca - Hamulec->SetLP(0, MaxBrakePress[3], 0); - else - Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]); - break; - } - case TBrakeValve::LSt: - { - WriteLog("XBT LSt"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - Hamulec->SetRM(RapidMult); - break; - } - case TBrakeValve::EStED: - { - WriteLog("XBT EStED"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - Hamulec->SetRM(RapidMult); - if (MBPM < 2) - { - // jesli przystawka wazaca - Hamulec->SetLP(0, MaxBrakePress[3], 0); - } - else - { - Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]); - } - break; - } - case TBrakeValve::EP2: - { - WriteLog("XBT EP2"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]); - break; - } - case TBrakeValve::EP1: - { - WriteLog("XBT EP1"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]); - Hamulec->SetRM(RapidMult); - break; - } - case TBrakeValve::CV1: - { - WriteLog("XBT CV1"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - break; - } - case TBrakeValve::CV1_L_TR: - { - WriteLog("XBT CV1_L_T"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - break; - } - default: - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - } - - Hamulec->SetASBP(MaxBrakePress[4]); - Hamulec->SetRV(RapidVel); -} - -// the driver's handle and the local brake handle of the vehicle's kinds -void TMoverParameters::CreateBrakeHandles() -{ - switch (BrakeHandle) - { - using enum TBrakeHandle; - case FV4a: - Handle = std::make_shared(); - break; - case MHZ_EN57: - case MHZ_K8P: - Handle = std::make_shared(); - break; - case FVel6: - Handle = std::make_shared(); - break; - case FVE408: - Handle = std::make_shared(); - break; - case testH: - Handle = std::make_shared(); - break; - case M394: - Handle = std::make_shared(); - break; - case Knorr: - Handle = std::make_shared(); - break; - case St113: - Handle = std::make_shared(); - break; - case MHZ_K5P: - Handle = std::make_shared(); - break; - case MHZ_6P: - Handle = std::make_shared(); - break; - default: - Handle = std::make_shared(); - } - Handle->SetParams(Handle_AutomaticOverload, Handle_ManualOverload, Handle_GenericDoubleParameter1, Handle_GenericDoubleParameter2, Handle_OverloadMaxPressure, Handle_OverloadPressureDecrease); - - switch (BrakeLocHandle) - { - case TBrakeHandle::FD1: - { - LocHandle = std::make_shared(); - LocHandle->Init(MaxBrakePress[0]); - if (TrainType == train_type::emu) - { - - dynamic_cast(LocHandle.get())->SetSpeed(3.5); - } - break; - } - case TBrakeHandle::Knorr: - { - LocHandle = std::make_shared(); - LocHandle->Init(MaxBrakePress[0]); - break; - } - default: - LocHandle = std::make_shared(); - } -} - -// the brake pipe, the main pipe and the spring brake's cylinder -void TMoverParameters::CreateBrakePipes() -{ - if (true == TestFlag(BrakeDelays, bdelay_G) && (false == TestFlag(BrakeDelays, bdelay_R) || Power > 1.0)) // ustalanie srednicy przewodu glownego (lokomotywa lub napędowy - Spg = 0.792; - else - Spg = 0.507; - // WriteLog("SPG = " + FloatToStr(Spg)); - - Pipe = std::make_shared(); - Pipe2 = std::make_shared(); // zabezpieczenie, bo sie PG wywala... :( - Pipe->CreateCap((std::max(Dim.L, 14.0) + 0.5) * Spg * 1); // dlugosc x przekroj x odejscia i takie tam - Pipe2->CreateCap((std::max(Dim.L, 14.0) + 0.5) * Spg * 1); - if (!SpringBrake.Cylinder) - { - SpringBrake.Cylinder = std::make_shared(); - SpringBrake.Cylinder->CreateCap(1); - } -} - -// the pressure of the main pipe at the start: the main reservoir's, or HosePressure fed through a main hose, or none -double TMoverParameters::InitialScndPipePress(double const HosePressure) const -{ - if (VeselVolume > 0.0) - { - return CompressedVolume / VeselVolume; - } - if ((Couplers[end::front].AllowedFlag & coupling::mainhose) != 0 || (Couplers[end::rear].AllowedFlag & coupling::mainhose) != 0) - { - return HosePressure; - } - return 0.0; -} - -// the air and the controls of a vehicle ready to depart -void TMoverParameters::SetReadyToDepart() -{ - WriteLog("Ready to depart"); - CompressedVolume = VeselVolume * MinCompressor * 9.8 / 10.0; - ScndPipePress = InitialScndPipePress(5.0); - PipePress = CntrlPipePress; - BrakePress = 0.0; - LocalBrakePosA = 0.0; - if (CabActive == 0) - BrakeCtrlPos = static_cast(Handle->GetPos(bh_NP)); - else - BrakeCtrlPos = static_cast(Handle->GetPos(bh_RP)); - /* - // NOTE: disabled and left up to the driver, if there's any - MainSwitch( false ); - PantFront( true ); - PantRear( true ); - MainSwitch( true ); - */ - DirActive = 0; // Dir; //nastawnik kierunkowy - musi być ustawiane osobno! - DirAbsolute = DirActive * CabActive; // kierunek jazdy względem sprzęgów - LimPipePress = CntrlPipePress; - - Battery = BatteryStart != start_t::disabled; -} - -// the air and the brakes of a vehicle standing braked -void TMoverParameters::SetBraked() -{ - WriteLog("Braked"); - Volume = BrakeVVolume * MaxBrakePress[3]; - CompressedVolume = VeselVolume * MinCompressor * 0.55; - /* - ScndPipePress = 5.1; - */ - ScndPipePress = InitialScndPipePress(5.1); - PipePress = LowPipePress; - PipeBrakePress = MaxBrakePress[3] * 0.5; - BrakePress = MaxBrakePress[3] * 0.5; - LocalBrakePosA = 0.0; - BrakeCtrlPos = static_cast(Handle->GetPos(bh_NP)); - LimPipePress = LowPipePress; - if (LocalBrake == TLocalBrake::ManualBrake || MBrake == true) - { - IncManualBrakeLevel(ManualBrakePosNo); - } - if (SpringBrake.MaxBrakeForce > 0.0) - { - SpringBrake.Activate = true; - } -} - -// ************************************************************************************************* -// Q: 20160714 -// Wstawia komendę z parametrem, od sprzęgu i w lokalizacji do pojazdu -// ************************************************************************************************* -void TMoverParameters::PutCommand(std::string const &NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation) -{ - CommandLast = NewCommand; // zapamiętanie komendy - - CommandIn.Command = NewCommand; - CommandIn.Value1 = NewValue1; - CommandIn.Value2 = NewValue2; - CommandIn.Location = NewLocation; - // czy uruchomic tu RunInternalCommand? nie wiem -} - -// ************************************************************************************************* -// Q: 20160714 -// Pobiera komendę z parametru funkcji oraz wartość zmiennej jako return -// ************************************************************************************************* -double TMoverParameters::GetExternalCommand(std::string &Command) const -{ - Command = CommandOut; - return ValueOut; -} - -// ************************************************************************************************* -// Q: 20160714 -// Ustawienie komendy wraz z parametrami -// ************************************************************************************************* -bool TMoverParameters::SetInternalCommand(std::string const &NewCommand, double NewValue1, double NewValue2, int const Couplertype) -{ - bool SIC; - if (CommandIn.Command == NewCommand && CommandIn.Value1 == NewValue1 && CommandIn.Value2 == NewValue2 && CommandIn.Coupling == Couplertype) - SIC = false; - else - { - CommandIn.Command = NewCommand; - CommandIn.Value1 = NewValue1; - CommandIn.Value2 = NewValue2; - CommandIn.Coupling = Couplertype; - SIC = true; - LastLoadChangeTime = 0; // zerowanie czasu (roz)ładowania - } - - return SIC; -} - -// ************************************************************************************************* -// Q: 20160714 -// wysyłanie komendy w kierunku dir (1=przód, -1=tył) do kolejnego pojazdu (jednego) -// ************************************************************************************************* -bool TMoverParameters::SendCtrlToNext(std::string const &CtrlCommand, double const ctrlvalue, double const dir, int const Couplertype) -{ - bool OK; - int d; // numer sprzęgu w kierunku którego wysyłamy - - // Ra: był problem z propagacją, jeśli w składzie jest pojazd wstawiony odwrotnie - // Ra: problem jest również, jeśli AI będzie na końcu składu - OK = true; // ( dir != 0 ); // experimentally disabled - d = (1 + static_cast(Sign(dir))) / 2; // dir=-1=>d=0, dir=1=>d=1 - wysyłanie tylko w tył - // musi być wybrana niezerowa kabina - if (OK && Couplers[d].Connected != nullptr && TestFlag(Couplers[d].CouplingFlag, Couplertype)) - { - - if (Couplers[d].ConnectedNr != d) - { - // jeśli ten nastpęny jest zgodny z aktualnym - if (Couplers[d].Connected->SetInternalCommand(CtrlCommand, ctrlvalue, dir, Couplertype)) - OK = Couplers[d].Connected->RunInternalCommand() && OK; // tu jest rekurencja - } - else - { - // jeśli następny jest ustawiony przeciwnie, zmieniamy kierunek - if (Couplers[d].Connected->SetInternalCommand(CtrlCommand, ctrlvalue, -dir, Couplertype)) - OK = Couplers[d].Connected->RunInternalCommand() && OK; // tu jest rekurencja - } - } - return OK; -} - -// ************************************************************************************************* -// Q: 20160723 -// ************************************************************************************************* -// wysłanie komendy otrzymanej z kierunku CValue2 (względem sprzęgów: 1=przod,-1=tył) -// Ra: Jest tu problem z rekurencją. Trzeba by oddzielić wykonywanie komend od mechanizmu -// ich propagacji w składzie. Osobnym problemem może być propagacja tylko w jedną stronę. -// Jeśli jakiś człon jest wstawiony odwrotnie, to również odwrotnie musi wykonywać -// komendy związane z kierunkami (PantFront, PantRear, DoorLeft, DoorRight). -// Komenda musi być zdefiniowana tutaj, a jeśli się wywołuje funkcję, to ona nie może -// sama przesyłać do kolejnych pojazdów. Należy też się zastanowić, czy dla uzyskania -// jakiejś zmiany (np. IncMainCtrl) lepiej wywołać funkcję, czy od razu wysłać komendę. -bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype) -{ - // the group of the command sets OK; a command none of them knows isn't done - if (bool OK{false}; RunControllerCommand(Command, CValue1, CValue2, Couplertype, OK) || RunRelaysCommand(Command, CValue1, CValue2, Couplertype, OK) || - RunCabCommand(Command, CValue1, CValue2, Couplertype, OK) || - RunBrakeCommand(Command, CValue1, CValue2, Couplertype, OK) || - RunBrakeEquipmentCommand(Command, CValue1, CValue2, Couplertype, OK) || - RunAuxiliariesCommand(Command, CValue1, CValue2, Couplertype, OK) || - RunPumpsCommand(Command, CValue1, CValue2, Couplertype, OK) || - RunBlowersCommand(Command, CValue1, CValue2, Couplertype, OK) || - RunPowerCommand(Command, CValue1, CValue2, Couplertype, OK) || - RunDoorsCommand(Command, CValue1, CValue2, Couplertype, OK) || - RunLoadCommand(Command, CValue1, CValue2, Couplertype, OK)) - { - return OK; // dla true komenda będzie usunięta, dla false wykonana ponownie - } - return false; -} - -// RunCommand() for the controllers; returns whether the command is one of them -bool TMoverParameters::RunControllerCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) -{ - if (Command == "MainCtrl") - { - // sent as MainCtrlPosForCoupled(), passed on unchanged - if (auto const position{MainCtrlPosFromCoupled(static_cast(floor(CValue1)))}; MainCtrlPosNo >= position) - { - MainCtrlPos = position; - if (DelayCtrlFlag) - { - if (LastRelayTime >= InitialCtrlDelay && MainCtrlPos == 1) - LastRelayTime = 0; - } - else if (LastRelayTime > CtrlDelay) - LastRelayTime = 0; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "ScndCtrl") - { - if (ScndCtrlPosNo >= floor(CValue1)) - { - ScndCtrlPos = static_cast(floor(CValue1)); - if (LastRelayTime > CtrlDelay) - LastRelayTime = 0; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - /* else if command='BrakeCtrl' then - begin - if BrakeCtrlPosNo>=Trunc(CValue1) then - begin - BrakeCtrlPos:=Trunc(CValue1); - OK:=SendCtrlToNext(command,CValue1,CValue2); - end; - end */ - else if (Command == "EIMIC") // ElectricInductionMotor Integrated Control - propulsion and brakes in relative values - { - eimic_real = CValue1; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else - { - return false; - } - return true; -} - -// RunCommand() for the direction, the automatic start and the current relays; returns whether the command is one of them -bool TMoverParameters::RunRelaysCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) -{ - if (Command == "Direction") - { - DirActive = static_cast(floor(CValue1)); - DirAbsolute = DirActive * CabActive; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "AutoRelaySwitch") - { - if (CValue1 == 1 && AutoRelayType == 2) - AutoRelayFlag = true; - else - AutoRelayFlag = false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "MaxCurrentSwitch") - { - MaxCurrentSwitch(CValue1 == 1, range_t::local); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "MinCurrentSwitch") - { - OK = MinCurrentSwitch(CValue1 == 1); - } - /*test komend oddzialywujacych na tabor*/ - else - { - return false; - } - return true; -} - -// RunCommand() for the cab and the speed control; returns whether the command is one of them -bool TMoverParameters::RunCabCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) -{ - if (Command == "CabActivisation") - { - // OK:=Power>0.01; - switch (static_cast(CValue1 * CValue2)) - { // CValue2 ma zmieniany znak przy niezgodności sprzęgów - case 1: - { - CabActive = 1; - break; - } - case -1: - { - CabActive = -1; - break; - } - default: - { - CabActive = 0; // gdy CValue1==0 - break; - } - } - if (PulleeMode) - { - // a vehicle prepared for hauling takes no cab, the command only passes through it - CabActive = 0; - } - DirAbsolute = DirActive * CabActive; - CabMaster = false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "SpeedCntrl") - { - if (EngineType == TEngineType::ElectricInductionMotor || SpeedCtrl) - SpeedCtrlValue = static_cast(round(CValue1)); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "SpeedCtrlUnit.Parking") - { - SpeedCtrlUnit.Parking = static_cast(CValue1); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else - { - return false; - } - return true; -} - -// RunCommand() for the train brake, the releaser and the emergency brake; returns whether the command is one of them -bool TMoverParameters::RunBrakeCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) -{ - if (Command == "Brake") // youBy - jak sie EP hamuje, to trza sygnal wyslac... - { - if (CValue1 < 0.001) - DynamicBrakeEMUStatus = true; - double temp1 = CValue1; - if (DCEMUED_EP_max_Vel > 0.001 && Vel > DCEMUED_EP_max_Vel && DynamicBrakeEMUStatus) - temp1 = 0; - if (DCEMUED_EP_min_Im > 0.001 && abs(Im) > DCEMUED_EP_min_Im && DynamicBrakeEMUStatus) - temp1 = 0; - Hamulec->SetEPS(temp1); - TUHEX_StageActual = static_cast(CValue1); - TUHEX_Active = TUHEX_StageActual > 0; - if (CValue1 < 0.001) - DynamicBrakeEMUStatus = true; - // fBrakeCtrlPos:=BrakeCtrlPos; //to powinnno być w jednym miejscu, aktualnie w C++!!! - BrakePressureActual = BrakePressureTable[BrakeCtrlPos]; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } // youby - odluzniacz hamulcow, przyda sie - else if (Command == "BrakeReleaser") - { - OK = BrakeReleaser(static_cast(Round(CValue1))); // samo się przesyła dalej - // OK:=SendCtrlToNext(command,CValue1,CValue2); //to robiło kaskadę 2^n - } - else if (Command == "Emergency_brake") - { - if (RadiostopSwitch(floor(CValue1) == 1)) // YB: czy to jest potrzebne? - OK = true; - else - OK = false; - } - else - { - return false; - } - return true; -} - -// RunCommand() for the brake delays, the spring brake, the sand and the cab signalling; returns whether the command is one of them -bool TMoverParameters::RunBrakeEquipmentCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) -{ - if (Command == "BrakeDelay") - { - if (auto const brakesetting = static_cast(std::floor(CValue1)); true == Hamulec->SetBDF(brakesetting)) - { - BrakeDelayFlag = brakesetting; - OK = true; - } - else - { - OK = false; - } - SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "SpringBrakeActivate") - { - if (Power24vIsAvailable || Power110vIsAvailable) - { - SpringBrake.Activate = CValue1 > 0; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else - OK = true; - } - - else if (Command == "Sandbox") - { - OK = Sandbox(CValue1 == 1, range_t::local); - } - else if (Command == "CabSignal") /*SHP,Indusi*/ - { // Ra: to powinno działać tylko w członie obsadzonym - SecuritySystem.set_cabsignal(); - // else OK:=false; - OK = true; // true, gdy można usunąć komendę - } - /*naladunek/rozladunek*/ - // TODO: have these commands leverage load exchange system instead - // TODO: CValue1 defines amount to load/unload - else - { - return false; - } - return true; -} - -// RunCommand() for the heating, the converter, the battery and the compressor; returns whether the command is one of them -bool TMoverParameters::RunAuxiliariesCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) -{ - if (Command == "HeatingSwitch") - { - HeatingSwitch_(CValue1 > 0.0); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "ConverterSwitch") /*NBMX*/ - { - if (ConverterStart == start_t::manual) - { - ConverterAllow = CValue1 > 0.0; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "BatterySwitch") /*NBMX*/ - { - // the battery of a vehicle prepared for hauling (PulleeMode) stays off - if (BatteryStart == start_t::manual && (false == PulleeMode || CValue1 <= 0.0)) - { - Battery = CValue1 > 0.0; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - // else if command='EpFuseSwitch' then {NBMX} - // begin - // if (CValue1=1) then EpFuse:=true - // else if (CValue1=0) then EpFuse:=false; - // OK:=SendCtrlToNext(command,CValue1,CValue2); - // end - else if (Command == "CompressorSwitch") /*NBMX*/ - { - CompressorSwitch(CValue1 == 1, range_t::local); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "CompressorPreset") - { - CompressorListPos = safe_clamp(static_cast(CValue1), 0, CompressorListPosNo); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else - { - return false; - } - return true; -} - -// RunCommand() for the water, fuel and oil pumps and the water heater; returns whether the command is one of them -bool TMoverParameters::RunPumpsCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) -{ - if (Command == "WaterPumpBreakerSwitch") - { - /* - if( FuelPump.start_type != start::automatic ) { - // automatic fuel pump ignores 'manual' state commands - */ - WaterPump.breaker = CValue1 == 1; - /* - } - */ - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "WaterPumpSwitch") - { - - if (WaterPump.start_type != start_t::battery) - { - // automatic fuel pump ignores 'manual' state commands - WaterPump.is_enabled = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "WaterPumpSwitchOff") - { - - if (WaterPump.start_type != start_t::battery) - { - // automatic fuel pump ignores 'manual' state commands - WaterPump.is_disabled = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "WaterHeaterBreakerSwitch") - { - /* - if( FuelPump.start_type != start::automatic ) { - // automatic fuel pump ignores 'manual' state commands - */ - WaterHeater.breaker = CValue1 == 1; - /* - } - */ - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "WaterHeaterSwitch") - { - /* - if( FuelPump.start_type != start::automatic ) { - // automatic fuel pump ignores 'manual' state commands - */ - WaterHeater.is_enabled = CValue1 == 1; - /* - } - */ - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "WaterCircuitsLinkSwitch") - { - if (true == dizel_heat.auxiliary_water_circuit) - { - // can only link circuits if the vehicle has more than one of them - WaterCircuitsLink = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "FuelPumpSwitch") - { - if (FuelPump.start_type != start_t::automatic) - { - // automatic fuel pump ignores 'manual' state commands - FuelPump.is_enabled = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "FuelPumpSwitchOff") - { - if (FuelPump.start_type != start_t::automatic) - { - // automatic fuel pump ignores 'manual' state commands - FuelPump.is_disabled = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "OilPumpSwitch") - { - if (OilPump.start_type != start_t::automatic) - { - // automatic pump ignores 'manual' state commands - OilPump.is_enabled = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "OilPumpSwitchOff") - { - if (OilPump.start_type != start_t::automatic) - { - // automatic pump ignores 'manual' state commands - OilPump.is_disabled = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else - { - return false; - } - return true; -} - -// RunCommand() for the motor blowers and the compartment lights; returns whether the command is one of them -bool TMoverParameters::RunBlowersCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) -{ - if (Command == "MotorBlowersFrontSwitch") - { - if (MotorBlowers[end::front].start_type != start_t::manual && MotorBlowers[end::front].start_type != start_t::manualwithautofallback) - { - // automatic device ignores 'manual' state commands - MotorBlowers[end::front].is_enabled = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "MotorBlowersFrontSwitchOff") - { - if (MotorBlowers[end::front].start_type != start_t::manual && MotorBlowers[end::front].start_type != start_t::manualwithautofallback) - { - // automatic device ignores 'manual' state commands - MotorBlowers[end::front].is_disabled = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "MotorBlowersRearSwitch") - { - if (MotorBlowers[end::rear].start_type != start_t::manual && MotorBlowers[end::rear].start_type != start_t::manualwithautofallback) - { - // automatic device ignores 'manual' state commands - MotorBlowers[end::rear].is_enabled = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "MotorBlowersRearSwitchOff") - { - if (MotorBlowers[end::rear].start_type != start_t::manual && MotorBlowers[end::rear].start_type != start_t::manualwithautofallback) - { - // automatic device ignores 'manual' state commands - MotorBlowers[end::rear].is_disabled = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "CompartmentLightsSwitch") - { - - if (CompartmentLights.start_type != start_t::automatic) - { - // automatic lights ignore 'manual' state commands - CompartmentLights.is_enabled = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "CompartmentLightsSwitchOff") - { - - if (CompartmentLights.start_type != start_t::automatic) - { - // automatic lights ignore 'manual' state commands - CompartmentLights.is_disabled = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else - { - return false; - } - return true; -} - -// RunCommand() for the line breaker, the relays and the pantographs; returns whether the command is one of them -bool TMoverParameters::RunPowerCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) -{ - if (Command == "MainSwitch") - { - MainSwitch_(CValue1 > 0.0); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "RelayReset") - { - RelayReset(static_cast(CValue1), range_t::local); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "PantValve") // Winger 160204 - { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów - auto const inputend{(static_cast(CValue1) & 0x80) != 0 ? 1 : 0}; - auto const inputcab{(static_cast(CValue1) & 0x40) != 0 ? 1 : 0}; - auto const inputoperation{static_cast(CValue1) & ~(0x80 | 0x40)}; - auto const noswap{TrainType == train_type::emu || TrainType == train_type::et41}; - auto swap{false == noswap && TestFlag(Couplers[CValue2 == -1 ? end::rear : end::front].CouplingFlag, coupling::control)}; - if (auto const reversed{inputcab != (CabActive != -1 ? 1 : 0)}; reversed) - { - swap = !swap; - } // TODO: check whether this part has RL equivalent - OperatePantographValve(static_cast(swap ? 1 - inputend : inputend), static_cast(inputoperation), range_t::local); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "PantsValve") - { - OperatePantographsValve(static_cast(static_cast(CValue1)), range_t::local); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "PantAllDown") - { - DropAllPantographs(CValue1 == 1, range_t::local); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "TractionMode") - { - TractionModeSwitch(CValue1 > 0.5 ? traction_mode::genset : traction_mode::catenary, range_t::local); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "GensetSwitch") - { - GensetSwitch(CValue1 > 0.5, range_t::local); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else - { - return false; - } - return true; -} - -// RunCommand() for the doors and the departure signal; returns whether the command is one of them -bool TMoverParameters::RunDoorsCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) -{ - if (Command == "DoorPermit") - { - DoorPermitCommand(CValue1, CValue2); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorOpen" || Command == "DoorClose") /*NBMX*/ - { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów - DoorRemoteCommand(Command == "DoorOpen", CValue1, CValue2); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorLock") - { - Doors.lock_enabled = CValue1 == 1 ? true : false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorStep") - { - Doors.step_enabled = CValue1 == 1 ? true : false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorMode") - { - Doors.remote_only = CValue1 == 1 ? true : false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DepartureSignal") - { - DepartureSignal = CValue1 == 1 ? true : false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else - { - return false; - } - return true; -} - -// the doors' permits, on the sides the command names: CValue1 the sides, negative to take the permit back, CValue2 the -// direction the command comes from -void TMoverParameters::DoorPermitCommand(double const CValue1, double const CValue2) -{ - auto const leftside{CValue2 > 0 ? 1 : 2}; - if (auto const rightside{3 - leftside}; std::abs(static_cast(CValue1)) & rightside) - { - PermitDoors_(side::right, CValue1 > 0); - } - if (std::abs(static_cast(CValue1)) & leftside) - { - PermitDoors_(side::left, CValue1 > 0); - } -} - -// the doors opened or closed from afar on the sides the command names, unless they're only worked locally -void TMoverParameters::DoorRemoteCommand(bool const Open, double const CValue1, double const CValue2) -{ - using enum control_t; - if (auto const doorcontrol{Open ? Doors.open_control : Doors.close_control}; - (doorcontrol != conductor && doorcontrol != driver && doorcontrol != mixed) || (false == Power24vIsAvailable && false == Power110vIsAvailable)) - { - return; - } - auto const leftside{CValue2 > 0 ? 1 : 2}; - if (auto const rightside{3 - leftside}; static_cast(CValue1) & rightside) - { - Doors.instances[side::right].remote_open = Open; - Doors.instances[side::right].remote_close = false == Open; - } - if (static_cast(CValue1) & leftside) - { - Doors.instances[side::left].remote_open = Open; - Doors.instances[side::left].remote_close = false == Open; - } -} - -// RunCommand() for the load and the damage; returns whether the command is one of them -bool TMoverParameters::RunLoadCommand(std::string const &Command, double CValue1, double CValue2, int const /*Couplertype*/, bool &OK) -{ - if (issection("Load=", Command)) - { - OK = false; // będzie powtarzane aż się załaduje - if (Vel < 0.1 // tolerance margin for small vehicle movements in the consist - && MaxLoad > 0 && LoadAmount < MaxLoad * (1.0 + OverLoadFactor) && Distance(Loc, CommandIn.Location, Dim, Dim) < (CValue2 > 1.0 ? CValue2 : 10.0)) - { // ten peron/rampa - - auto const loadname{ToLower(extract_value("Load", Command))}; - if (LoadAmount == 0.f) - { - AssignLoad(loadname); - } - OK = LoadingDone(LoadSpeed, - loadname); // zmienia LoadStatus - } - else - { - // no loading can be done if conditions aren't met - LastLoadChangeTime = 0.0; - } - } - else if (issection("UnLoad=", Command)) - { - OK = false; // będzie powtarzane aż się rozładuje - if (Vel < 0.1 // tolerance margin for small vehicle movements in the consist - && LoadAmount > 0 // czy jest co rozladowac? - && Distance(Loc, CommandIn.Location, Dim, Dim) < (CValue2 > 1.0 ? CValue2 : 10.0)) - { // ten peron - /*mozna to rozladowac*/ - OK = LoadingDone(-1.f * LoadSpeed, ToLower(extract_value("UnLoad", Command))); - } - else - { - // no loading can be done if conditions aren't met - LastLoadChangeTime = 0.0; - } - } - else if (Command == "SetDamage") - { - if (CValue2 == 1) - OK = SetFlag(DamageFlag, static_cast(floor(CValue1))); - if (CValue2 == -1) - { - auto const derailed{TestFlag(DamageFlag, dtrain_out)}; - OK = SetFlag(DamageFlag, static_cast(-floor(CValue1))); - // taking the derailment off puts the vehicle back on the rails, with what the criteria of derailment held - if (derailed && false == TestFlag(DamageFlag, dtrain_out)) - rerail(); - } - } - else - { - return false; - } - return true; -} - -// ************************************************************************************************* -// Q: 20160714 -// Uruchamia funkcję RunCommand aż do skutku. Jeśli będzie pozytywny to kasuje komendę. -// ************************************************************************************************* -bool TMoverParameters::RunInternalCommand() -{ - bool OK; - - if (!CommandIn.Command.empty()) - { - OK = RunCommand(CommandIn.Command, CommandIn.Value1, CommandIn.Value2, CommandIn.Coupling); - if (OK) - { - - CommandIn.Command.clear(); // kasowanie bo rozkaz wykonany - CommandIn.Value1 = 0; - CommandIn.Value2 = 0; - CommandIn.Coupling = 0; - CommandIn.Location.X = 0; - CommandIn.Location.Y = 0; - CommandIn.Location.Z = 0; - switch_physics(true, wake_cause::command); - } - } - else - OK = false; - return OK; -} - -// ************************************************************************************************* -// Q: 20160714 -// Zwraca wartość natężenia prądu na wybranym amperomierzu. Podfunkcja do ShowCurrent. -// ************************************************************************************************* -double TMoverParameters::ShowCurrentP(int AmpN) const -{ - int Bn; - bool Grupowy; - - // ClearPendingExceptions; - Grupowy = DelayCtrlFlag && TrainType == train_type::et22; // przerzucanie walu grupowego w ET22; - Bn = RList[MainCtrlActualPos].Bn; // ile równoległych gałęzi silników - - if (DynamicBrakeType == dbrake_automatic && DynamicBrakeFlag) - Bn = DynamicBrakeAmpmeters; - if (Power > 0.01) - { - if (AmpN > 0) // podać prąd w gałęzi - { - if (Bn < AmpN || (Grupowy && AmpN == Bn - 1)) - return 0; - else // normalne podawanie pradu - return floor(abs(Im)); - } - else // podać całkowity - return floor(abs(Itot)); - } - else // pobor pradu jezeli niema mocy - { - int current = 0; - for (int b = 0; b < 2; b++) - // with Couplers[b] do - if (TestFlag(Couplers[b].CouplingFlag, coupling::control) && Couplers[b].Connected->Power > 0.01) - current = static_cast(Couplers[b].Connected->ShowCurrent(AmpN)); - return current; - } -} - -bool TMoverParameters::reload_FIZ() -{ - WriteLog("[DEV] Reloading FIZ for " + Name); - // pause simulation - Global.iPause |= 0b1000; - if (bool result = LoadFIZ(chkPath); result == true) - { - // jesli sie udalo przeladowac FIZ - Global.iPause &= 0b0111; - WriteLog("[DEV] FIZ reloaded for " + Name); - } - else - { - // failed to reload - exit simulator - ErrorLog("[DEV] Failed to reload fiz for vehicle " + Name); - } - return true; -} - -namespace simulation -{ - -weights_table Weights; - -} // namespace simulation diff --git a/physics/mover/cab.cpp b/physics/mover/cab.cpp new file mode 100644 index 000000000..3b73e1baf --- /dev/null +++ b/physics/mover/cab.cpp @@ -0,0 +1,250 @@ +/* +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 cab: activation, the direction, the horns, the pullee mode + +#include "stdafx.h" +#include "physics/mover.h" +#include "vehicle/DynObj.h" +#include "physics/oerlikonest.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/Timer.h" +#include "utilities/parser.h" +#include "simulation/simulation.h" +#include "vehicle/fieldshunting.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "physics/mover/internal.h" + + +bool TMoverParameters::DirectionForward() +{ + if (false == EIMDirectionChangeAllow()) + { + return false; + } + + if (MainCtrlPosNo > 0 && DirActive < 1 && (CabActive != 0 || (InactiveCabFlag & activation::neutraldirection) == 0)) + { + ++DirActive; + DirAbsolute = DirActive * CabActive; + SendCtrlToNext("Direction", DirActive, CabActive); + return true; + } + else if (DirActive == 1 && IsMainCtrlNoPowerPos() && TrainType == train_type::emu && EngineType != TEngineType::ElectricInductionMotor) + return MinCurrentSwitch(true); //"wysoki rozruch" EN57 + return false; +}; + +bool TMoverParameters::ChangeCab(int direction) +{ // zmiana kabiny i resetowanie ustawien + if (std::abs(CabOccupied + direction) < 2) + { + CabOccupied = CabOccupied + direction; + if (BrakeCtrlPosNo > 0 && (BrakeSystem == TBrakeSystem::Pneumatic || BrakeSystem == TBrakeSystem::ElectroPneumatic)) + { + BrakeLevelSet(Handle->GetPos(bh_NP)); + LimPipePress = PipePress; + ActFlowSpeed = 0; + } + else + BrakeLevelSet(Handle->GetPos(bh_NP)); + MainCtrlPos = MainCtrlNoPowerPos(); + ScndCtrlPos = 0; + return true; + } + return false; +}; + +int TMoverParameters::SoundingHorns(int const Signal) const +{ + auto const supplied{[this](horn_supply const Supply) { + if (Supply == horn_supply::electric) + { + return Power24vIsAvailable || Power110vIsAvailable; + } + if (VeselVolume > 0.0) + { + return Compressor >= HornMinPressure; + } + // a vehicle without a main reservoir of its own takes the air from the main pipe, a vehicle without either + // (a road vehicle, say) has no air to check + auto const mainpipe{((Couplers[end::front].AllowedFlag | Couplers[end::rear].AllowedFlag) & coupling::mainhose) != 0}; + return false == mainpipe || ScndPipePress >= HornMinPressure; + }}; + auto horns{0}; + if (supplied(HornSupply)) + { + horns |= Signal & (1 | 2); + } + if (supplied(Horn3Supply)) + { + horns |= Signal & 4; + } + return horns; +} + +// ************************************************************************************************* +// Q: 20160710 +// załączenie rozrządu +// ************************************************************************************************* +bool TMoverParameters::CabActivisation(bool const Enforce) +{ + bool OK = false; + + OK = Enforce || CabActive == 0; // numer kabiny, z której jest sterowanie + if (PulleeMode) + { + // nobody drives from a vehicle prepared for hauling + OK = false; + } + if (OK) + { + CabActive = CabOccupied; // sterowanie jest z kabiny z obsadą + DirAbsolute = DirActive * CabActive; + CabMaster = true; + SecuritySystem.set_enabled(true); // activate the alerter TODO: make it part of control based cab selection + SendCtrlToNext("CabActivisation", 1, CabActive); + SendCtrlToNext("Direction", DirActive, CabActive); + if (InactiveCabFlag & activation::springbrakeoff) + { + SpringBrakeActivate(false); + } + } + return OK; +} + +bool TMoverParameters::CabActivisationAuto(bool const Enforce) +{ + bool OK = AutomaticCabActivation ? CabActivisation(Enforce) : false; + return OK; +} + +// ************************************************************************************************* +// Q: 20160710 +// wyłączenie rozrządu +// ************************************************************************************************* +bool TMoverParameters::CabDeactivisation(bool const Enforce) +{ + bool OK = false; + + OK = Enforce || IsCabMaster(); // o ile obsada jest w kabinie ze sterowaniem + if (OK) + { + if (InactiveCabFlag & activation::springbrakeon) + { + SpringBrakeActivate(true); + } + if (InactiveCabFlag & activation::pantographsup) + { + InactiveCabPantsCheck = true; + } + if (InactiveCabFlag & activation::doorpermition) + { + PermitDoors(side::right, true, range_t::consist); + PermitDoors(side::left, true, range_t::consist); + } + if (InactiveCabFlag & activation::neutraldirection) + { + DirActive = 0; + SendCtrlToNext("Direction", 0, CabActive); + } + + CabActive = 0; + DirAbsolute = DirActive * CabActive; + CabMaster = false; + DepartureSignal = false; // nie buczeć z nieaktywnej kabiny + SecuritySystem.set_enabled(false); // deactivate alerter TODO: make it part of control based cab selection + + SendCtrlToNext("CabActivisation", 0, CabOccupied); // CabActive==0! + } + return OK; +} + +bool TMoverParameters::CabDeactivisationAuto(bool const Enforce) +{ + bool OK = AutomaticCabActivation ? CabDeactivisation(Enforce) : false; + return OK; +} + +// ************************************************************************************************* +// pullee mode ("jazda ciągniona", MaSzyna-EU07/maszyna#64): prepares the vehicle for being hauled dead in a +// train, or puts it back in service. while in the mode the vehicle: +// - vents the brake pipe for nothing of its own (inactive cab, vigilance, radio-stop, spring brake), only when +// the train parts (UpdatePipePressure()), +// - gets no force from its spring brake, whatever air its cylinder has (BrakeForce()), +// - has its driver's valve cut out and its local brake released, whatever the handles show; the distributor +// stays on the brake pipe, so it brakes and releases with the train, +// - keeps its battery off and takes no cab (BatterySwitch(), CabActivisation() and their commands). +// entering it also lets go of the hand brake and of the spring brake switch. +// returns whether the mode changed; a vehicle driven from can't enter it +// ************************************************************************************************* +bool TMoverParameters::PulleeModeSwitch(bool const State) +{ + if (PulleeMode == State || (State && CabActive != 0)) + { + return false; + } + PulleeMode = State; + if (PulleeMode) + { + DecManualBrakeLevel(ManualBrakePosNo); + SpringBrake.Activate = false; + SecuritySystem.set_enabled(false); + Battery = false; + } + return true; +} + +// ************************************************************************************************* +// Q: 20160710 +// kierunek do tyłu +// ************************************************************************************************* +bool TMoverParameters::DirectionBackward(void) +{ + if (false == EIMDirectionChangeAllow()) + { + return false; + } + + if (DirActive == 1 && MainCtrlPos == 0 && TrainType == train_type::emu && EngineType != TEngineType::ElectricInductionMotor && MinCurrentSwitch(false)) + { + return true; + } + if (MainCtrlPosNo > 0 && DirActive > -1 && (CabActive != 0 || (InactiveCabFlag & activation::neutraldirection) == 0)) + { + if (EngineType == TEngineType::WheelsDriven) + --CabActive; + // else + --DirActive; + DirAbsolute = DirActive * CabActive; + SendCtrlToNext("Direction", DirActive, CabActive); + return true; + } + + return false; +} + +bool TMoverParameters::EIMDirectionChangeAllow(void) const +{ + bool OK = false; + /* + // NOTE: disabled while eimic variables aren't immediately synced with master controller changes inside ai module + OK = (EngineType != TEngineType::ElectricInductionMotor || ((eimic <= 0) && (eimic_real <= 0) && (Vel < 0.1))); + */ + OK = MainCtrlPos <= MainCtrlMaxDirChangePos; + return OK; +} diff --git a/physics/mover/collisions.cpp b/physics/mover/collisions.cpp new file mode 100644 index 000000000..a890e1bbb --- /dev/null +++ b/physics/mover/collisions.cpp @@ -0,0 +1,875 @@ +/* +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/. +*/ + +// collisions of the ends, their crush and repair, derailment and putting back on the rails + +#include "stdafx.h" +#include "physics/mover.h" +#include "vehicle/DynObj.h" +#include "physics/oerlikonest.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/Timer.h" +#include "utilities/parser.h" +#include "simulation/simulation.h" +#include "vehicle/fieldshunting.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "physics/mover/internal.h" + + +double ComputeCollision(double &v1, double &v2, double m1, double m2, double beta, bool vc) +{ // oblicza zmiane predkosci i przyrost pedu wskutek kolizji + assert(beta < 1.0); + + if (v1 < v2 && vc == true) + return 0; + else + { + double sum = m1 + m2; + double w1 = (m2 * v2 * 2.0 + v1 * (m1 - m2)) / sum; + double w2 = (m1 * v1 * 2.0 + v2 * (m2 - m1)) / sum; + // the collision changes the velocities directly: the bounce loses energy in the velocities relative to the + // centre of mass only, the pair keeps its momentum. scaling the velocities themselves braked the vehicles + // down with every step their couplers spent stretched or pressed in all the way (eu07/maszyna#553) + auto const centre{(m1 * v1 + m2 * v2) / sum}; + auto const restitution{std::sqrt(1.0 - beta)}; + v1 = std::lerp(centre, w1, restitution); + v2 = std::lerp(centre, w2, restitution); + return m1 * (w2 - w1) * (1 - beta); + } +} +namespace +{ + +// a derailed vehicle tears its brake hoses: the brake pipe vents and the rest of the train brakes in emergency +void tear_brake_hoses(TMoverParameters &Vehicle) +{ + if (std::any_of(std::begin(Vehicle.Couplers), std::end(Vehicle.Couplers), [](auto const &Coupler) { return (Coupler.CouplingFlag & coupling::brakehose) == coupling::brakehose; })) + { + Vehicle.AlarmChainFlag = true; + } +} + +} // namespace + +// ************************************************************************************************* +// Q: 20160716 +// Wykrywanie kolizji +// ************************************************************************************************* +void TMoverParameters::CollisionDetect(int const End, double const dt) +{ + if (Neighbours[End].vehicle == nullptr) + { + return; + } // shouldn't normally happen but, eh + + auto const &thiscoupler{Couplers[End]}; + auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; + auto const otherend{Neighbours[End].vehicle_end}; + auto const &othercoupler{othervehicle->Couplers[otherend]}; + + auto const physical{coupler_physics_at(End)}; + // physics.collisions new: past the buffers the ends of rail vehicles crush (collision.h); a hit the steel takes stays + // the legacy one, and so do the collisions of the road vehicles (the traffic of a scenery), with the legacy rule + auto const rails{TestFlag(CategoryFlag, 1) && TestFlag(othervehicle->CategoryFlag, 1)}; + auto const crushing{Global.collisions == global_settings::collision_model::physical && rails}; + if (crushing && (thiscoupler.hit_handled || crush_hit(End, dt))) + { + return; + } + // physics.collisions monitor: the legacy collision follows, the log tells what the crush would be + if (Global.collisions == global_settings::collision_model::monitor && rails) + { + crush_hit(End, dt); + } + if (physical && false == coupler_stop_hit(End, *othervehicle, otherend)) + { + return; + } + // the share of the energy of the relative motion the hit takes: in the physical model the springs gone solid give + // for good, rather than spring back as the legacy model has it + auto const loss{physical ? coupler_physics::solid_hit_loss(thiscoupler.physics, othercoupler.physics) : (thiscoupler.beta + othercoupler.beta) / 2.0}; + + // the velocities along this vehicle's axis: the other vehicle's one is turned around when the vehicles face each + // other (touch with the same ends), as in CouplerForce() + auto const otherdirection{DirPatch(End, otherend)}; + auto velocity{V}; + auto othervehiclevelocity{othervehicle->V * otherdirection}; + // calculate collision force and new velocities for involved vehicles + auto const VirtualCoupling{(thiscoupler.CouplingFlag == coupling::faux)}; + auto CCF{0.0}; + + switch (End) + { + case 0: + { + CCF = ComputeCollision(velocity, othervehiclevelocity, TotalMass, othervehicle->TotalMass, loss, VirtualCoupling) / dt; + break; // yB: ej ej ej, a po + } + case 1: + { + CCF = ComputeCollision(othervehiclevelocity, velocity, othervehicle->TotalMass, TotalMass, loss, VirtualCoupling) / dt; + break; + } + default: + { + break; + } + } + + // the new model crushes the ends and derails the vehicles by the crush, see crush_hit() + if (Global.crash_damage && false == crushing) + { + // the physical model breaks the coupling and crushes the buffers by the force of the hit (coupler_stop_hit()) + if (false == physical && -thiscoupler.Dist >= thiscoupler.DmaxB && FuzzyLogic(std::abs(CCF), 5.0 * (thiscoupler.FmaxC + 1.0), p_coupldmg)) + { + // small chance to smash the coupler if it's hit with excessive force + damage_coupler(End); + } + + // HACK: limit excessive speed derailment checks to vehicles which aren't part of the same consist + auto const outsideconsist{thiscoupler.CouplingFlag == coupling::faux || true == TestFlag(othervehicle->DamageFlag, dtrain_out)}; + auto const velocitydifference{outsideconsist ? CollisionVelocity(End, *othervehicle, otherend) : 0.0}; + + if (velocitydifference > SafeCollisionVelocity) + { + // HACK: crude estimation for potential derail, will take place with velocity difference > 15 km/h adjusted for vehicle mass ratio + if (false == TestFlag(DamageFlag, dtrain_out) || false == TestFlag(othervehicle->DamageFlag, dtrain_out)) + { + WriteLog("Bad driving: " + Name + " and " + othervehicle->Name + " collided with velocity " + to_string(velocitydifference, 0) + " km/h"); + } + + if (velocitydifference > SafeCollisionVelocity * (TotalMass / othervehicle->TotalMass)) + { + Derail(COLLISION); + } + if (velocitydifference > SafeCollisionVelocity * (othervehicle->TotalMass / TotalMass)) + { + othervehicle->Derail(COLLISION); + } + } + } + + // adjust velocity and acceleration of affected vehicles. the physical model changes the velocities alone: the + // integration of the next step (ComputeMovement()) would carry a quarter of an acceleration spike over into the + // velocity once more, and the vehicles would bounce off the stop faster than they hit it + auto const accelerationspike{physical ? 0.0 : 1.0}; + // derailed the legacy way a vehicle is a wall, off the rails by the new criteria it slides on and takes the hit. with + // the crush, the vehicles coupled to the wall push it on (crush_hit()) + auto const coupled{thiscoupler.CouplingFlag != coupling::faux}; + auto const wall = [crushing, coupled](TMoverParameters const &Vehicle) { + return TestFlag(Vehicle.DamageFlag, dtrain_out) && (false == crushing || (Vehicle.Derailed == derailment::outcome::none && false == coupled)); + }; + if (false == wall(*this)) + { + auto const accelerationchange{(velocity - V) / dt}; + AccS += accelerationchange * accelerationspike; + V = velocity; + } + if (false == wall(*othervehicle)) + { + auto const othervehiclenewvelocity{othervehiclevelocity * otherdirection}; // back along the other vehicle's axis + auto const othervehicleaccelerationchange{(othervehiclenewvelocity - othervehicle->V) / dt}; + othervehicle->AccS += othervehicleaccelerationchange * accelerationspike; + othervehicle->V = othervehiclenewvelocity; + } +} + +void TMoverParameters::damage_coupler(int const End) +{ + + auto &thiscoupler{Couplers[End]}; + + if (thiscoupler.type() == TCouplerType::Articulated) + { + return; + } // HACK: don't break articulated couplings no matter what + + if (SetFlag(DamageFlag, dtrain_coupling)) + EventFlag = true; + + auto const hosetorn{(thiscoupler.CouplingFlag & coupling::brakehose) == coupling::brakehose}; + if (hosetorn) + { + // hamowanie nagle - zerwanie przewodow hamulcowych + AlarmChainFlag = true; + } + + thiscoupler.CouplingFlag = 0; + thiscoupler.broken = true; + + if (thiscoupler.Connected != nullptr) + { + // break connection with other vehicle, if there's any: on the end it's coupled with, which is the front one too + // for vehicles facing each other + auto &othercoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr]}; + othercoupler.CouplingFlag = coupling::faux; + // the coupling broke between the two, either end can be repaired + othercoupler.broken = true; + if (hosetorn && coupler_physics_at(End)) + { + // the brake pipe of the other part of the train vents through the torn hose as well + thiscoupler.Connected->AlarmChainFlag = true; + } + } + + WriteLog("Bad driving: " + Name + " broke a coupler"); +} + +// ************************************************************************************************* +// physics.collisions new: the collisions past the buffers, see collision.h +// ************************************************************************************************* +collision::vehicle_kind TMoverParameters::collision_kind() const +{ + auto const powered{EngineType != TEngineType::None && EngineType != TEngineType::Dumb}; + auto const unit{is_multiple_unit()}; + auto const passengers{std::any_of(LoadAttributes.begin(), LoadAttributes.end(), [](auto const &Load) { return ToLower(Load.name).starts_with("passenger"); })}; + // a coach heats its compartments; the crash zone is a matter of each end (crush_of()) + return collision::kind_of(powered, unit || passengers || (false == powered && HeatingPower > 0.0), false); +} + +collision::crush_curve TMoverParameters::crush_curve_at(int const End) const +{ + return collision::crush_of(Couplers[End].collision, collision_kind()); +} + +double TMoverParameters::buffer_height_at(int const End) const +{ + auto const loadshare{MaxLoad > 0.f ? LoadAmount / MaxLoad : 0.0}; + return collision::buffer_height(Couplers[End].collision, collision_kind(), loadshare); +} + +void TMoverParameters::derail_in_collision(DerailReason const Reason, std::string const &Why) +{ + if (false == SetFlag(DamageFlag, dtrain_out)) + { + return; + } + // upright, it slides on the sleepers and keeps passing the forces on + Derailed = derailment::outcome::off_rails; + DerailCause = derail_motion::cause::collision; + DerailAcceleration = 0.0; + DerailSide = 0; + CollisionDerail = Reason; + EventFlag = true; + MainSwitch(false, range_t::local); + if (Vel < 5.0) + { + // HACK: prevent permanent axle spin in static vehicle after a collision + nrot = 0.0; + SlippingWheels = false; + } + // the brake hoses tear: the brake pipe vents and the rest of the train brakes in emergency + tear_brake_hoses(*this); + derailment_monitor.reset(); + pushed_off_monitor.reset(); + ErrorLog(std::format("Bad driving: {} derailed in a collision, {}: {}", Name, Reason == COLLISION_OVERRIDE ? "overriding" : "pushed off the track", Why)); +} +namespace +{ + + +char const *end_name(int const End) +{ + return End == end::front ? "front" : "rear"; +} + +char const *kind_name(collision::vehicle_kind const Kind) +{ + switch (Kind) + { + case collision::vehicle_kind::locomotive: + return "locomotive"; + case collision::vehicle_kind::coach: + return "coach"; + case collision::vehicle_kind::crash_zone: + return "crash zone"; + case collision::vehicle_kind::wagon: + default: + return "wagon"; + } +} + +} // namespace + +// the force pressing the end in, of the coupling or of the buffers touching [N]: forwards at the front pulls +double compression_at(TCoupling const &Coupler, int const End) +{ + return std::max(0.0, (End == end::front ? -1.0 : 1.0) * Coupler.CForce); +} +namespace +{ + +// the steel parts of both ends in series [N/m] +double steel_stiffness(TCoupling const &First, TCoupling const &Second) +{ + auto const first{std::max(First.physics.link_stiffness, 1.0)}; + auto const second{std::max(Second.physics.link_stiffness, 1.0)}; + return first * second / (first + second); +} + +// the hit of the pair in the step, for the push off the track: the peak force and how long it acted +void record_hit(TCoupling &Coupler, double const Force, double const Duration) +{ + Coupler.hit_force = std::max(Coupler.hit_force, Force); + Coupler.hit_duration = std::max(Coupler.hit_duration, Duration); +} + +} // namespace + +bool TMoverParameters::crush_hit(int const End, double const dt) +{ + auto &thiscoupler{Couplers[End]}; + auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; + auto const otherend{Neighbours[End].vehicle_end}; + auto &othercoupler{othervehicle->Couplers[otherend]}; + + auto const physical{coupler_physics_at(End)}; + // the buffers pressed all the way, not the draw gear pulled all the way, and the pair still closing in + auto const buffers{physical ? thiscoupler.physics_state.stop < 0 : thiscoupler.Dist < 0.0}; + auto const closing{-CouplerVelocityDifference(End, *othervehicle, otherend) * DirF(End)}; + if (false == Global.crash_damage || false == buffers || closing <= 0.0) + { + // the hit is over, the next one is another one for the monitor + thiscoupler.crush_monitored = false; + othercoupler.crush_monitored = false; + return false; + } + auto const monitor{Global.collisions == global_settings::collision_model::monitor}; + // put down by the scenery inside each other: pressed past the stop of the buffers and the crush of the ends by more + // than a hit takes them in a step. the legacy collision pushes them apart; their springs, the stops at both ends + // and the neighbours found at either end there make up any closing velocity, not a hit + auto const stop{std::max(thiscoupler.DmaxB + othercoupler.DmaxB, thiscoupler.physics.buffers.travel + othercoupler.physics.buffers.travel) + thiscoupler.crush + othercoupler.crush}; + auto const overlap{-static_cast(Neighbours[End].distance)}; + if (overlap > stop + collision::inside_margin + closing * dt) + { + // nor is what their springs took in pressed past the stop and back a hit, for as long as the buffers touch + thiscoupler.contact.inside(); + othercoupler.contact.inside(); + if (false == thiscoupler.inside_reported) + { + thiscoupler.inside_reported = true; + othercoupler.inside_reported = true; + WriteLog(std::format("Bad scenery: {} and {} are inside each other, their buffers pressed {:.2f} m past their stop, no crush", Name, othervehicle->Name, overlap - stop)); + } + return false; + } + // parting at the start of the step: what closes the pair in now is the knock of a hit of either vehicle in the step, + // or of the vehicles inside each other next to it, not a hit of this pair. the legacy collision takes it; a pair + // still closing in at the start of the next step is a hit + if (thiscoupler.closing < 0.0) + { + return false; + } + // a vehicle derailed the legacy way (the end of the track, say) stays where it is, whatever hits it from outside its + // train. the vehicles coupled to it push it on, as the train behind a derailed vehicle does: a wall to them, it + // stopped the whole train at once, and the vehicles behind it crushed by the energy of the train + auto const coupled{thiscoupler.CouplingFlag != coupling::faux}; + auto const wall{false == coupled && TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none}; + auto const otherwall{false == coupled && TestFlag(othervehicle->DamageFlag, dtrain_out) && othervehicle->Derailed == derailment::outcome::none}; + if (wall && otherwall) + { + return false; + } + constexpr double immovable{1e12}; + auto const mass{wall ? immovable : TotalMass}; + auto const othermass{otherwall ? immovable : othervehicle->TotalMass}; + auto const loss{physical ? coupler_physics::solid_hit_loss(thiscoupler.physics, othercoupler.physics) : (thiscoupler.beta + othercoupler.beta) / 2.0}; + + auto const firstcurve{crush_curve_at(End)}; + auto const secondcurve{othervehicle->crush_curve_at(otherend)}; + auto const stiffness{steel_stiffness(thiscoupler, othercoupler)}; + auto const springs{compression_at(thiscoupler, End)}; + collision::hit_input input; + input.velocity = closing; + input.mass1 = mass; + input.mass2 = othermass; + input.restitution = std::sqrt(std::max(0.0, 1.0 - loss)); + input.stiffness = stiffness; + input.springs = springs; + // the monitor takes the whole hit at once, over a second, longer than the crush of any hit lasts + input.dt = monitor ? 1.0 : dt; + input.start_velocity = thiscoupler.closing; + // the crush takes only what the hit brings past what the buffers of EN 15551 of both ends take in. an automatic + // coupler (or its adapter) has no buffers at the side: its draft gear takes in what its springs of the .fiz do + auto const reduced{mass * othermass / (mass + othermass)}; + auto const central{thiscoupler.type() == TCouplerType::Automatic || othercoupler.type() == TCouplerType::Automatic || thiscoupler.has_adapter() || othercoupler.has_adapter()}; + auto const capacity{central ? 0.0 : collision::buffer_capacity(thiscoupler.collision, collision_kind()) + collision::buffer_capacity(othercoupler.collision, othervehicle->collision_kind())}; + auto const hitvelocity{std::max(closing, thiscoupler.closing)}; + input.budget = thiscoupler.contact.budget(reduced, hitvelocity, capacity); + auto const hit{collision::hit({firstcurve, thiscoupler.crush}, {secondcurve, othercoupler.crush}, input)}; + // the override, by the crush of both ends + auto const climbing_of = [&](double const Crush1, double const Crush2) { + collision::override_input climbing; + climbing.crush1 = Crush1; + climbing.crush2 = Crush2; + climbing.mass1 = TotalMass - Mred; + climbing.mass2 = othervehicle->TotalMass - othervehicle->Mred; + climbing.height1 = buffer_height_at(End); + climbing.height2 = othervehicle->buffer_height_at(otherend); + climbing.anticlimbers = collision::anticlimber_of(thiscoupler.collision, collision_kind()) && collision::anticlimber_of(othercoupler.collision, othervehicle->collision_kind()); + climbing.zone1 = firstcurve.densify; + climbing.zone2 = secondcurve.densify; + return climbing; + }; + if (monitor) + { + if (hit.crushing && false == thiscoupler.crush_monitored) + { + thiscoupler.crush_monitored = true; + othercoupler.crush_monitored = true; + ++crush_reports; + auto const crush1{thiscoupler.crush + hit.crush1}; + auto const crush2{othercoupler.crush + hit.crush2}; + auto const climbed{collision::override_of(climbing_of(crush1, crush2))}; + auto const torn{std::max(crush1, crush2) >= collision::draw_gear_crush}; + std::string const outcome{climbed.first && climbed.second ? std::string{"both would leave the rails"} + : climbed.first ? Name + " would ride up onto " + othervehicle->Name + : climbed.second ? othervehicle->Name + " would ride up onto " + Name + : std::string{"both would stay on the rails"}}; + WriteLog(std::format("collision monitor: {} and {} collided at {:.0f} km/h: the {} end of {} ({:.1f} t {}) would crush by {:.2f} m, the {} end of {} ({:.1f} t {}) by {:.2f} m, " + "at {:.0f} kN; draw gear {}; {}", + Name, othervehicle->Name, closing * 3.6, end_name(End), Name, TotalMass / 1000.0, kind_name(collision_kind()), crush1, end_name(otherend), othervehicle->Name, + othervehicle->TotalMass / 1000.0, kind_name(othervehicle->collision_kind()), crush2, hit.force / 1000.0, torn ? "torn off" : "holds", outcome)); + } + return false; + } + if (false == hit.crushing) + { + // the steel takes it, the legacy collision follows; its peak, under the force an end gives at, for the push + // off the track + auto const weaker{std::min(firstcurve.force(thiscoupler.crush), secondcurve.force(othercoupler.crush))}; + auto const peak{std::min(springs + coupler_physics::impact_force(closing, stiffness, mass, othermass), weaker)}; + auto const duration{std::min(dt, (1.0 + input.restitution) * std::sqrt(reduced / stiffness))}; + record_hit(thiscoupler, peak, duration); + record_hit(othercoupler, peak, duration); + return false; + } + // the other vehicle doesn't take it again in this step + thiscoupler.hit_handled = true; + othercoupler.hit_handled = true; + + // the hit at the force the weaker end gives at pushes the vehicles apart: the velocities alone change, along this + // vehicle's axis as in CollisionDetect() + auto const otherdirection{DirPatch(End, otherend)}; + auto const apart{End == end::front ? -1.0 : 1.0}; + if (false == wall) + { + V += apart * hit.impulse / mass; + } + if (false == otherwall) + { + othervehicle->V -= apart * hit.impulse / othermass * otherdirection; + } + record_hit(thiscoupler, hit.force, hit.duration); + record_hit(othercoupler, hit.force, hit.duration); + + // the energy the crush took, for both vehicles' count of the contact + thiscoupler.contact.crushed(hit.work); + othercoupler.contact.crushed(hit.work); + // what the log tells of the pair, for the analysis of a crush + auto const kinetic{0.5 * reduced * hitvelocity * hitvelocity}; + auto const pair = [&]() { + return std::format("{} {:.1f} t {}, {} end crushed {:.2f} m, gives at {:.0f} kN; {} {:.1f} t {}, {} end crushed {:.2f} m, gives at {:.0f} kN; force {:.0f} kN, springs {:.0f} kN, " + "closing at {:.1f} km/h at the start of the step; energy {:.0f} kJ of the motion and {:.0f} kJ in the buffers, past the {:.0f} kJ they take in, " + "{:.0f} kJ crushed in the contact", + Name, TotalMass / 1000.0, kind_name(collision_kind()), end_name(End), thiscoupler.crush, firstcurve.force(thiscoupler.crush) / 1000.0, othervehicle->Name, + othervehicle->TotalMass / 1000.0, kind_name(othervehicle->collision_kind()), end_name(otherend), othercoupler.crush, + secondcurve.force(othercoupler.crush) / 1000.0, hit.force / 1000.0, springs / 1000.0, input.start_velocity * 3.6, kinetic / 1000.0, + thiscoupler.contact.absorbed() / 1000.0, capacity / 1000.0, thiscoupler.contact.crush_work() / 1000.0); + }; + auto const crushed = [&](TMoverParameters const &Vehicle, int const VehicleEnd, double const Before, double const After) { + if (Before < collision::crush_mark && After >= collision::crush_mark) + { + ErrorLog(std::format("Bad driving: {} and {} collided at {:.0f} km/h, the {} end of {} crushed ({})", Name, othervehicle->Name, closing * 3.6, end_name(VehicleEnd), Vehicle.Name, pair())); + } + }; + auto const before{thiscoupler.crush}; + auto const otherbefore{othercoupler.crush}; + thiscoupler.crush += hit.crush1; + othercoupler.crush += hit.crush2; + crushed(*this, End, before, thiscoupler.crush); + crushed(*othervehicle, otherend, otherbefore, othercoupler.crush); + + // the crushed headstock tears off the draw gear, with the brake hose: both parts of the train brake in emergency. + // the coupler of an end not coupled is gone as well, it doesn't couple any more + if (thiscoupler.CouplingFlag != coupling::faux && std::max(thiscoupler.crush, othercoupler.crush) >= collision::draw_gear_crush) + { + auto const hose{(thiscoupler.CouplingFlag & coupling::brakehose) == coupling::brakehose}; + damage_coupler(End); + if (hose) + { + othervehicle->AlarmChainFlag = true; + } + } + else if (thiscoupler.CouplingFlag == coupling::faux) + { + if (thiscoupler.crush >= collision::draw_gear_crush && false == thiscoupler.broken) + { + damage_coupler(End); + } + if (othercoupler.crush >= collision::draw_gear_crush && false == othercoupler.broken) + { + othervehicle->damage_coupler(otherend); + } + } + + // the end crushed deep enough lets one vehicle climb onto the other one + auto const climbing{climbing_of(thiscoupler.crush, othercoupler.crush)}; + auto const climbed{collision::override_of(climbing)}; + auto const why = [&](TMoverParameters const &Climber, TMoverParameters const &Other) { + return std::format("{} rode up onto {} at {:.0f} km/h, the ends crushed by {:.2f} m, buffers at {:.0f} / {:.0f} mm, anticlimbers {} ({})", Climber.Name, Other.Name, closing * 3.6, + thiscoupler.crush + othercoupler.crush, climbing.height1 * 1000.0, climbing.height2 * 1000.0, climbing.anticlimbers ? "yes" : "no", pair()); + }; + if (climbed.first) + { + derail_in_collision(COLLISION_OVERRIDE, why(*this, *othervehicle)); + } + if (climbed.second) + { + othervehicle->derail_in_collision(COLLISION_OVERRIDE, why(*othervehicle, *this)); + } + return true; +} + +void TMoverParameters::check_pushed_off(double const dt, double const Distance) +{ + if (Global.collisions != global_settings::collision_model::physical || false == Global.crash_damage || TestFlag(DamageFlag, dtrain_out) || false == TestFlag(CategoryFlag, 1) || + DebugModeFlag) + { + pushed_off_monitor.reset(); + return; + } + collision::pushed_vehicle vehicle; + vehicle.mass = TotalMass - Mred; + vehicle.axles = NAxles > 0 ? NAxles : 4; + vehicle.length = Dim.L; + vehicle.pivots = BDist; + vehicle.axle_base = ADist > 0.0 ? ADist : BDist; + + auto climbs{false}; + auto distance{0.0}; + auto lifted{false}; + auto duration{0.0}; + auto worst{0.0}; + auto worstforce{0.0}; + auto worstend{static_cast(end::front)}; + for (int end = end::front; end <= end::rear; ++end) + { + auto const *other{Neighbours[end].vehicle}; + if (other == nullptr) + { + continue; + } + auto const &coupler{Couplers[end]}; + collision::pushed_end pushed; + pushed.other_length = other->MoverParameters->Dim.L; + pushed.crush = coupler.crush; + // the steady push of the springs over the step, or the peak of a hit for as long as it lasted: the flange climbs + // over the distance the wheels rolled meanwhile, a wheel lifted off the rail goes in a short time, rolling or not + for (auto const &[force, time] : {std::pair{compression_at(coupler, end), dt}, std::pair{coupler.hit_force, coupler.hit_duration}}) + { + pushed.force = force; + auto const wheel{collision::pushed_forces(vehicle, pushed, RunningShape.R)}; + auto const ratio{wheel.ratio()}; + if (ratio < derailment::climbing_limit) + { + continue; + } + climbs = true; + distance = std::max(distance, Distance * std::clamp(time / std::max(dt, 1e-9), 0.0, 1.0)); + if (wheel.lifted()) + { + lifted = true; + duration = std::max(duration, time); + } + if (ratio > worst) + { + worst = ratio; + worstforce = force; + worstend = end; + } + } + } + if (pushed_off_monitor.update(climbs, distance, lifted, duration)) + { + derail_in_collision(COLLISION_PUSHED_OFF, std::format("{:.0f} kN pressing its {} end in, {}, at {:.0f} km/h, curve radius {:.0f} m: Y/Q {:.2f} ({:.1f} t {}, {} axles, " + "springs {:.0f} / {:.0f} kN, hits {:.0f} / {:.0f} kN, crushed {:.2f} / {:.2f} m)", + worstforce / 1000.0, end_name(worstend), + lifted ? std::format("its wheels lifted off the rail for {:.3f} s", pushed_off_monitor.time()) + : std::format("the flange climbing over {:.2f} m", pushed_off_monitor.distance()), + Vel, std::abs(RunningShape.R), std::min(worst, 99.0), + vehicle.mass / 1000.0, kind_name(collision_kind()), vehicle.axles, compression_at(Couplers[end::front], end::front) / 1000.0, + compression_at(Couplers[end::rear], end::rear) / 1000.0, Couplers[end::front].hit_force / 1000.0, Couplers[end::rear].hit_force / 1000.0, + Couplers[end::front].crush, Couplers[end::rear].crush)); + } +} +namespace +{ + + +// the end as it was built (physics.collisions new): not crushed, and nothing of a contact or a hit kept +void restore_end(TCoupling &Coupler) +{ + Coupler.crush = 0.0; + Coupler.contact.reset(); + Coupler.hit_handled = false; + Coupler.hit_force = 0.0; + Coupler.hit_duration = 0.0; + Coupler.crush_monitored = false; + Coupler.inside_reported = false; +} + +// the coupler as good as new, its end with it (the crush that tore the draw gear off), the vehicle without the coupler +// damage (and the emergency braking of the torn brake hose) once neither of its couplers is broken +void repair(TMoverParameters &Vehicle, TCoupling &Coupler) +{ + Coupler.broken = false; + Coupler.stretch_duration = 0.f; + Coupler.physics_state.couple(); + restore_end(Coupler); + if (Vehicle.Couplers[end::front].broken || Vehicle.Couplers[end::rear].broken) + { + return; + } + ClearFlag(Vehicle.DamageFlag, dtrain_coupling); + // either vehicle of the pair may have been braking through the torn hose + Vehicle.AlarmChainFlag = false; +} + +} // namespace + +bool TMoverParameters::repair_coupler(int const End) +{ + auto &thiscoupler{Couplers[End]}; + if (false == thiscoupler.broken) + { + return false; + } + repair(*this, thiscoupler); + // the other half of the coupling, which may be the vehicle flagged with the damage + if (auto *other{thiscoupler.Connected}; other != nullptr && other->Couplers[thiscoupler.ConnectedNr].broken) + { + repair(*other, other->Couplers[thiscoupler.ConnectedNr]); + } + WriteLog(std::format("Coupler of {} repaired, at its {} end", Name, End == end::front ? "front" : "rear")); + return true; +} + +static_assert(derailment::track_damage::railwear == dtrack_railwear && derailment::track_damage::freerail == dtrack_freerail && derailment::track_damage::thinrail == dtrack_thinrail && + derailment::track_damage::railbend == dtrack_railbend); + +double TMoverParameters::centre_of_gravity() const +{ + auto const kind{EngineType == TEngineType::None ? derailment::vehicle_class::unpowered : derailment::vehicle_class::powered}; + auto const empty{CentreOfGravity > 0.0 ? CentreOfGravity : derailment::default_centre_of_gravity(Dim.H, kind)}; + auto const loadmass{TotalMass - Mass - Mred}; + auto const loadshare{MaxLoad > 0.f ? LoadAmount / MaxLoad : 1.0}; + return derailment::loaded_centre_of_gravity(empty, Mass, loadmass, loadshare, Floor, Dim.H); +} + +void TMoverParameters::check_derailment(TTrackShape const &Shape, TTrackParam const &Track, double const Distance) +{ + if (TestFlag(DamageFlag, dtrain_out) || false == TestFlag(CategoryFlag, 1) || DebugModeFlag) + { + derailment_monitor.reset(); + return; + } + derailment::vehicle_state vehicle; + vehicle.mass = TotalMass - Mred; + vehicle.axles = NAxles > 0 ? NAxles : 4; + vehicle.length = Dim.L; + vehicle.axle_base = ADist > 0.0 ? ADist : BDist; + vehicle.centre_of_gravity = centre_of_gravity(); + for (int end = end::front; end <= end::rear; ++end) + { + auto const *other{Neighbours[end].vehicle}; + if (other == nullptr) + { + continue; + } + // the force of the coupling, or of the buffers touching, along this vehicle: forwards at the front pulls + vehicle.ends[end].compression = (end == end::front ? -1.0 : 1.0) * Couplers[end].CForce; + vehicle.ends[end].other_length = other->MoverParameters->Dim.L; + } + derailment::track_state track; + track.radius = Shape.R; + track.cant = Shape.dHrail; + track.gauge = TrackW; + track.uneven_curvature = Shape.uneven_curvature; + track.uneven_cross = Shape.uneven_cross; + track.buckle_curvature = Shape.buckle_curvature; + track.damage = Track.DamageFlag; + + auto const verdict{derailment_monitor.update(vehicle, track, V, Distance)}; + if (verdict.result == derailment::outcome::none) + { + return; + } + if (Global.derailment == global_settings::derailment_model::physical) + { + derail(verdict, vehicle, track, Track.Name); + return; + } + // physics.derailment monitor: the legacy draw decides, the log tells what the criteria would do, once on a track + if (derailment_reported.has_value() && *derailment_reported == Track.Name) + { + return; + } + derailment_reported = Track.Name; + ++derailment_reports; + WriteLog("derailment monitor: " + Name + " " + derailment::report(verdict, vehicle, track, V, Track.Name != nullptr ? *Track.Name : std::string{})); +} + +void TMoverParameters::derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track, std::string const *TrackName) +{ + if (false == SetFlag(DamageFlag, dtrain_out)) + { + return; + } + Derailed = Verdict.result; + DerailCause = Verdict.result == derailment::outcome::overturned ? derail_motion::cause::overturned : derail_motion::cause::off_rails; + // out of the curve; a buckle bending the line against the curve more than the curve does throws it into the curve + DerailAcceleration = std::abs(Track.radius) > 1e-3 && derailment::line_curvature(Track) < 0.0 ? -Verdict.acceleration : Verdict.acceleration; + DerailSide = 0; + EventFlag = true; + MainSwitch(false, range_t::local); + // the brake hoses tear: the brake pipe vents and the rest of the train brakes in emergency + tear_brake_hoses(*this); + ErrorLog("Bad driving: " + Name + " " + derailment::report(Verdict, Vehicle, Track, V, TrackName != nullptr ? *TrackName : std::string{})); + if (Track.buckle_curvature != 0.0) + { + ErrorLog(std::format("Bad driving: {} derailed on buckled track, the buckle bending the line by 1/{:.0f} m {} the curve", Name, 1.0 / std::abs(Track.buckle_curvature), + Track.buckle_curvature > 0.0 ? "with" : "against")); + } +} + +void TMoverParameters::rerail() +{ + ClearFlag(DamageFlag, dtrain_out); + Derailed = derailment::outcome::none; + // and back on the track; what derailed it before has no say in how it leaves the track the next time + OffTrack.reset(); + DerailCause = derail_motion::cause::off_rails; + DerailAcceleration = 0.0; + DerailSide = 0; + derailment_monitor.reset(); + derailment_distance = 0.0; + derailment_reported.reset(); + // nor derailed in a collision + CollisionDerail = NONE; + pushed_off_monitor.reset(); + // back on the axis of the track, which the derailment shifted the vehicle off aside and down (a road vehicle keeps + // its place on the road) + if (TestFlag(CategoryFlag, 1)) + { + OffsetTrackH = 0.0; + OffsetTrackV = 0.0; + } + // a derailed vehicle which stopped sleeps (Global.physics_sleepheld) with the friction of the derailment in FStand and + // where the derailment put it, until something wakes it: the physics on, for the friction of the rails and its place on + // them. it is put back by a command (resetconsist, SetDamage) or by the road spawner, which sets it going anyway + switch_physics(true, wake_cause::command); +} + +void TMoverParameters::repair_damage() +{ + DamageFlag = 0; + EngDmgFlag = 0; + WheelFlat = 0.0; + AlarmChainFlag = false; + // the crushed ends rebuilt + for (auto &coupler : Couplers) + { + restore_end(coupler); + } + rerail(); +} + +void TMoverParameters::Derail(DerailReason const Reason) +{ + if (SetFlag(DamageFlag, dtrain_out)) + { + EventFlag = true; + MainSwitch(false, range_t::local); + + auto const velocity{V}; + AccS *= 0.65; + V *= 0.65; + // physics.collisions new: the vehicles coupled to it lose the speed with it. the cut in a step stands for the + // train coming to a stop with the vehicle; the coupled ones keeping their speed would run into it at a third of + // the speed of the train, and crush their ends and ride up onto it for a hit no train had + if (Global.collisions == global_settings::collision_model::physical && TestFlag(CategoryFlag, 1)) + { + change_train_velocity(V - velocity); + } + RunningShape.R = 0; + if (Vel < 5.0) + { + // HACK: prevent permanent axle spin in static vehicle after a collision + nrot = 0.0; + SlippingWheels = false; + } + // physics.derailment new: off the end of the track the vehicle runs on straight on its wheels, sliding on the + // ground as the vehicles the criteria derail do, and its brake hoses tear + if (Reason == END_OF_TRACK && Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1)) + { + Derailed = derailment::outcome::off_rails; + DerailCause = derail_motion::cause::end_of_track; + DerailAcceleration = 0.0; + DerailSide = 0; + tear_brake_hoses(*this); + } + + // Print a message in the log. + if (Reason == END_OF_TRACK) + ErrorLog("Bad driving: " + Name + " derailed due to end of track"); + else if (Reason == TOO_HIGH_SPEED) + ErrorLog("Bad driving: " + Name + " derailed due to too high speed"); + else if (Reason == GAUGE_MISMATCH) + ErrorLog("Bad dynamic: " + Name + " derailed due to track width"); // błąd w scenerii + else if (Reason == WRONG_TRACK_TYPE) + ErrorLog("Bad dynamic: " + Name + " derailed due to wrong track type"); // błąd w scenerii + else if (Reason == COLLISION) + WriteLog("Bad driving: " + Name + " derailed"); // This reason also generates its own message in `TMoverParameters::CollisionDetect()` + else if (Reason == TRAILED_SWITCH) + ErrorLog("Bad driving: " + Name + " derailed trailing through a switch with a movable nose set the other way"); + } +} + +bool TMoverParameters::leaves_track() const +{ + return Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1) && TestFlag(DamageFlag, dtrain_out) && Derailed != derailment::outcome::none && + false == OffTrack.active(); +} + +void TMoverParameters::pull_off(int const Side, double const Acceleration, std::string const &Why) +{ + if (Global.derailment != global_settings::derailment_model::physical || false == SetFlag(DamageFlag, dtrain_out)) + { + return; + } + // upright, its flange climbs the rail the coupling pulls it over + Derailed = derailment::outcome::off_rails; + DerailCause = derail_motion::cause::pulled_off; + DerailAcceleration = Acceleration; + DerailSide = Side; + EventFlag = true; + MainSwitch(false, range_t::local); + tear_brake_hoses(*this); + derailment_monitor.reset(); + ErrorLog(std::format("Bad driving: {} pulled off the track by the vehicle coupled to it, {}", Name, Why)); +} diff --git a/physics/mover/commands.cpp b/physics/mover/commands.cpp new file mode 100644 index 000000000..0a531f5bc --- /dev/null +++ b/physics/mover/commands.cpp @@ -0,0 +1,807 @@ +/* +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 commands passed between the vehicles of a train + +#include "stdafx.h" +#include "physics/mover.h" +#include "vehicle/DynObj.h" +#include "physics/oerlikonest.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/Timer.h" +#include "utilities/parser.h" +#include "simulation/simulation.h" +#include "vehicle/fieldshunting.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "physics/mover/internal.h" + + +// ************************************************************************************************* +// Q: 20160714 +// Wstawia komendę z parametrem, od sprzęgu i w lokalizacji do pojazdu +// ************************************************************************************************* +void TMoverParameters::PutCommand(std::string const &NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation) +{ + CommandLast = NewCommand; // zapamiętanie komendy + + CommandIn.Command = NewCommand; + CommandIn.Value1 = NewValue1; + CommandIn.Value2 = NewValue2; + CommandIn.Location = NewLocation; + // czy uruchomic tu RunInternalCommand? nie wiem +} + +// ************************************************************************************************* +// Q: 20160714 +// Pobiera komendę z parametru funkcji oraz wartość zmiennej jako return +// ************************************************************************************************* +double TMoverParameters::GetExternalCommand(std::string &Command) const +{ + Command = CommandOut; + return ValueOut; +} + +// ************************************************************************************************* +// Q: 20160714 +// Ustawienie komendy wraz z parametrami +// ************************************************************************************************* +bool TMoverParameters::SetInternalCommand(std::string const &NewCommand, double NewValue1, double NewValue2, int const Couplertype) +{ + bool SIC; + if (CommandIn.Command == NewCommand && CommandIn.Value1 == NewValue1 && CommandIn.Value2 == NewValue2 && CommandIn.Coupling == Couplertype) + SIC = false; + else + { + CommandIn.Command = NewCommand; + CommandIn.Value1 = NewValue1; + CommandIn.Value2 = NewValue2; + CommandIn.Coupling = Couplertype; + SIC = true; + LastLoadChangeTime = 0; // zerowanie czasu (roz)ładowania + } + + return SIC; +} + +// ************************************************************************************************* +// Q: 20160714 +// wysyłanie komendy w kierunku dir (1=przód, -1=tył) do kolejnego pojazdu (jednego) +// ************************************************************************************************* +bool TMoverParameters::SendCtrlToNext(std::string const &CtrlCommand, double const ctrlvalue, double const dir, int const Couplertype) +{ + bool OK; + int d; // numer sprzęgu w kierunku którego wysyłamy + + // Ra: był problem z propagacją, jeśli w składzie jest pojazd wstawiony odwrotnie + // Ra: problem jest również, jeśli AI będzie na końcu składu + OK = true; // ( dir != 0 ); // experimentally disabled + d = (1 + static_cast(Sign(dir))) / 2; // dir=-1=>d=0, dir=1=>d=1 - wysyłanie tylko w tył + // musi być wybrana niezerowa kabina + if (OK && Couplers[d].Connected != nullptr && TestFlag(Couplers[d].CouplingFlag, Couplertype)) + { + + if (Couplers[d].ConnectedNr != d) + { + // jeśli ten nastpęny jest zgodny z aktualnym + if (Couplers[d].Connected->SetInternalCommand(CtrlCommand, ctrlvalue, dir, Couplertype)) + OK = Couplers[d].Connected->RunInternalCommand() && OK; // tu jest rekurencja + } + else + { + // jeśli następny jest ustawiony przeciwnie, zmieniamy kierunek + if (Couplers[d].Connected->SetInternalCommand(CtrlCommand, ctrlvalue, -dir, Couplertype)) + OK = Couplers[d].Connected->RunInternalCommand() && OK; // tu jest rekurencja + } + } + return OK; +} + +// ************************************************************************************************* +// Q: 20160723 +// ************************************************************************************************* +// wysłanie komendy otrzymanej z kierunku CValue2 (względem sprzęgów: 1=przod,-1=tył) +// Ra: Jest tu problem z rekurencją. Trzeba by oddzielić wykonywanie komend od mechanizmu +// ich propagacji w składzie. Osobnym problemem może być propagacja tylko w jedną stronę. +// Jeśli jakiś człon jest wstawiony odwrotnie, to również odwrotnie musi wykonywać +// komendy związane z kierunkami (PantFront, PantRear, DoorLeft, DoorRight). +// Komenda musi być zdefiniowana tutaj, a jeśli się wywołuje funkcję, to ona nie może +// sama przesyłać do kolejnych pojazdów. Należy też się zastanowić, czy dla uzyskania +// jakiejś zmiany (np. IncMainCtrl) lepiej wywołać funkcję, czy od razu wysłać komendę. +bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype) +{ + // the group of the command sets OK; a command none of them knows isn't done + if (bool OK{false}; RunControllerCommand(Command, CValue1, CValue2, Couplertype, OK) || RunRelaysCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunCabCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunBrakeCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunBrakeEquipmentCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunAuxiliariesCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunPumpsCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunBlowersCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunPowerCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunDoorsCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunLoadCommand(Command, CValue1, CValue2, Couplertype, OK)) + { + return OK; // dla true komenda będzie usunięta, dla false wykonana ponownie + } + return false; +} + +// RunCommand() for the controllers; returns whether the command is one of them +bool TMoverParameters::RunControllerCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "MainCtrl") + { + // sent as MainCtrlPosForCoupled(), passed on unchanged + if (auto const position{MainCtrlPosFromCoupled(static_cast(floor(CValue1)))}; MainCtrlPosNo >= position) + { + MainCtrlPos = position; + if (DelayCtrlFlag) + { + if (LastRelayTime >= InitialCtrlDelay && MainCtrlPos == 1) + LastRelayTime = 0; + } + else if (LastRelayTime > CtrlDelay) + LastRelayTime = 0; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "ScndCtrl") + { + if (ScndCtrlPosNo >= floor(CValue1)) + { + ScndCtrlPos = static_cast(floor(CValue1)); + if (LastRelayTime > CtrlDelay) + LastRelayTime = 0; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + /* else if command='BrakeCtrl' then + begin + if BrakeCtrlPosNo>=Trunc(CValue1) then + begin + BrakeCtrlPos:=Trunc(CValue1); + OK:=SendCtrlToNext(command,CValue1,CValue2); + end; + end */ + else if (Command == "EIMIC") // ElectricInductionMotor Integrated Control - propulsion and brakes in relative values + { + eimic_real = CValue1; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + { + return false; + } + return true; +} + +// RunCommand() for the direction, the automatic start and the current relays; returns whether the command is one of them +bool TMoverParameters::RunRelaysCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "Direction") + { + DirActive = static_cast(floor(CValue1)); + DirAbsolute = DirActive * CabActive; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "AutoRelaySwitch") + { + if (CValue1 == 1 && AutoRelayType == 2) + AutoRelayFlag = true; + else + AutoRelayFlag = false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "MaxCurrentSwitch") + { + MaxCurrentSwitch(CValue1 == 1, range_t::local); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "MinCurrentSwitch") + { + OK = MinCurrentSwitch(CValue1 == 1); + } + /*test komend oddzialywujacych na tabor*/ + else + { + return false; + } + return true; +} + +// RunCommand() for the cab and the speed control; returns whether the command is one of them +bool TMoverParameters::RunCabCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "CabActivisation") + { + // OK:=Power>0.01; + switch (static_cast(CValue1 * CValue2)) + { // CValue2 ma zmieniany znak przy niezgodności sprzęgów + case 1: + { + CabActive = 1; + break; + } + case -1: + { + CabActive = -1; + break; + } + default: + { + CabActive = 0; // gdy CValue1==0 + break; + } + } + if (PulleeMode) + { + // a vehicle prepared for hauling takes no cab, the command only passes through it + CabActive = 0; + } + DirAbsolute = DirActive * CabActive; + CabMaster = false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "SpeedCntrl") + { + if (EngineType == TEngineType::ElectricInductionMotor || SpeedCtrl) + SpeedCtrlValue = static_cast(round(CValue1)); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "SpeedCtrlUnit.Parking") + { + SpeedCtrlUnit.Parking = static_cast(CValue1); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + { + return false; + } + return true; +} + +// RunCommand() for the train brake, the releaser and the emergency brake; returns whether the command is one of them +bool TMoverParameters::RunBrakeCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "Brake") // youBy - jak sie EP hamuje, to trza sygnal wyslac... + { + if (CValue1 < 0.001) + DynamicBrakeEMUStatus = true; + double temp1 = CValue1; + if (DCEMUED_EP_max_Vel > 0.001 && Vel > DCEMUED_EP_max_Vel && DynamicBrakeEMUStatus) + temp1 = 0; + if (DCEMUED_EP_min_Im > 0.001 && abs(Im) > DCEMUED_EP_min_Im && DynamicBrakeEMUStatus) + temp1 = 0; + Hamulec->SetEPS(temp1); + TUHEX_StageActual = static_cast(CValue1); + TUHEX_Active = TUHEX_StageActual > 0; + if (CValue1 < 0.001) + DynamicBrakeEMUStatus = true; + // fBrakeCtrlPos:=BrakeCtrlPos; //to powinnno być w jednym miejscu, aktualnie w C++!!! + BrakePressureActual = BrakePressureTable[BrakeCtrlPos]; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } // youby - odluzniacz hamulcow, przyda sie + else if (Command == "BrakeReleaser") + { + OK = BrakeReleaser(static_cast(Round(CValue1))); // samo się przesyła dalej + // OK:=SendCtrlToNext(command,CValue1,CValue2); //to robiło kaskadę 2^n + } + else if (Command == "Emergency_brake") + { + if (RadiostopSwitch(floor(CValue1) == 1)) // YB: czy to jest potrzebne? + OK = true; + else + OK = false; + } + else + { + return false; + } + return true; +} + +// RunCommand() for the brake delays, the spring brake, the sand and the cab signalling; returns whether the command is one of them +bool TMoverParameters::RunBrakeEquipmentCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "BrakeDelay") + { + if (auto const brakesetting = static_cast(std::floor(CValue1)); true == Hamulec->SetBDF(brakesetting)) + { + BrakeDelayFlag = brakesetting; + OK = true; + } + else + { + OK = false; + } + SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "SpringBrakeActivate") + { + if (Power24vIsAvailable || Power110vIsAvailable) + { + SpringBrake.Activate = CValue1 > 0; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + OK = true; + } + + else if (Command == "Sandbox") + { + OK = Sandbox(CValue1 == 1, range_t::local); + } + else if (Command == "CabSignal") /*SHP,Indusi*/ + { // Ra: to powinno działać tylko w członie obsadzonym + SecuritySystem.set_cabsignal(); + // else OK:=false; + OK = true; // true, gdy można usunąć komendę + } + /*naladunek/rozladunek*/ + // TODO: have these commands leverage load exchange system instead + // TODO: CValue1 defines amount to load/unload + else + { + return false; + } + return true; +} + +// RunCommand() for the heating, the converter, the battery and the compressor; returns whether the command is one of them +bool TMoverParameters::RunAuxiliariesCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "HeatingSwitch") + { + HeatingSwitch_(CValue1 > 0.0); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "ConverterSwitch") /*NBMX*/ + { + if (ConverterStart == start_t::manual) + { + ConverterAllow = CValue1 > 0.0; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "BatterySwitch") /*NBMX*/ + { + // the battery of a vehicle prepared for hauling (PulleeMode) stays off + if (BatteryStart == start_t::manual && (false == PulleeMode || CValue1 <= 0.0)) + { + Battery = CValue1 > 0.0; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + // else if command='EpFuseSwitch' then {NBMX} + // begin + // if (CValue1=1) then EpFuse:=true + // else if (CValue1=0) then EpFuse:=false; + // OK:=SendCtrlToNext(command,CValue1,CValue2); + // end + else if (Command == "CompressorSwitch") /*NBMX*/ + { + CompressorSwitch(CValue1 == 1, range_t::local); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "CompressorPreset") + { + CompressorListPos = safe_clamp(static_cast(CValue1), 0, CompressorListPosNo); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + { + return false; + } + return true; +} + +// RunCommand() for the water, fuel and oil pumps and the water heater; returns whether the command is one of them +bool TMoverParameters::RunPumpsCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "WaterPumpBreakerSwitch") + { + /* + if( FuelPump.start_type != start::automatic ) { + // automatic fuel pump ignores 'manual' state commands + */ + WaterPump.breaker = CValue1 == 1; + /* + } + */ + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "WaterPumpSwitch") + { + + if (WaterPump.start_type != start_t::battery) + { + // automatic fuel pump ignores 'manual' state commands + WaterPump.is_enabled = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "WaterPumpSwitchOff") + { + + if (WaterPump.start_type != start_t::battery) + { + // automatic fuel pump ignores 'manual' state commands + WaterPump.is_disabled = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "WaterHeaterBreakerSwitch") + { + /* + if( FuelPump.start_type != start::automatic ) { + // automatic fuel pump ignores 'manual' state commands + */ + WaterHeater.breaker = CValue1 == 1; + /* + } + */ + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "WaterHeaterSwitch") + { + /* + if( FuelPump.start_type != start::automatic ) { + // automatic fuel pump ignores 'manual' state commands + */ + WaterHeater.is_enabled = CValue1 == 1; + /* + } + */ + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "WaterCircuitsLinkSwitch") + { + if (true == dizel_heat.auxiliary_water_circuit) + { + // can only link circuits if the vehicle has more than one of them + WaterCircuitsLink = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "FuelPumpSwitch") + { + if (FuelPump.start_type != start_t::automatic) + { + // automatic fuel pump ignores 'manual' state commands + FuelPump.is_enabled = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "FuelPumpSwitchOff") + { + if (FuelPump.start_type != start_t::automatic) + { + // automatic fuel pump ignores 'manual' state commands + FuelPump.is_disabled = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "OilPumpSwitch") + { + if (OilPump.start_type != start_t::automatic) + { + // automatic pump ignores 'manual' state commands + OilPump.is_enabled = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "OilPumpSwitchOff") + { + if (OilPump.start_type != start_t::automatic) + { + // automatic pump ignores 'manual' state commands + OilPump.is_disabled = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + { + return false; + } + return true; +} + +// RunCommand() for the motor blowers and the compartment lights; returns whether the command is one of them +bool TMoverParameters::RunBlowersCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "MotorBlowersFrontSwitch") + { + if (MotorBlowers[end::front].start_type != start_t::manual && MotorBlowers[end::front].start_type != start_t::manualwithautofallback) + { + // automatic device ignores 'manual' state commands + MotorBlowers[end::front].is_enabled = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "MotorBlowersFrontSwitchOff") + { + if (MotorBlowers[end::front].start_type != start_t::manual && MotorBlowers[end::front].start_type != start_t::manualwithautofallback) + { + // automatic device ignores 'manual' state commands + MotorBlowers[end::front].is_disabled = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "MotorBlowersRearSwitch") + { + if (MotorBlowers[end::rear].start_type != start_t::manual && MotorBlowers[end::rear].start_type != start_t::manualwithautofallback) + { + // automatic device ignores 'manual' state commands + MotorBlowers[end::rear].is_enabled = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "MotorBlowersRearSwitchOff") + { + if (MotorBlowers[end::rear].start_type != start_t::manual && MotorBlowers[end::rear].start_type != start_t::manualwithautofallback) + { + // automatic device ignores 'manual' state commands + MotorBlowers[end::rear].is_disabled = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "CompartmentLightsSwitch") + { + + if (CompartmentLights.start_type != start_t::automatic) + { + // automatic lights ignore 'manual' state commands + CompartmentLights.is_enabled = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "CompartmentLightsSwitchOff") + { + + if (CompartmentLights.start_type != start_t::automatic) + { + // automatic lights ignore 'manual' state commands + CompartmentLights.is_disabled = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + { + return false; + } + return true; +} + +// RunCommand() for the line breaker, the relays and the pantographs; returns whether the command is one of them +bool TMoverParameters::RunPowerCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "MainSwitch") + { + MainSwitch_(CValue1 > 0.0); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "RelayReset") + { + RelayReset(static_cast(CValue1), range_t::local); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "PantValve") // Winger 160204 + { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów + auto const inputend{(static_cast(CValue1) & 0x80) != 0 ? 1 : 0}; + auto const inputcab{(static_cast(CValue1) & 0x40) != 0 ? 1 : 0}; + auto const inputoperation{static_cast(CValue1) & ~(0x80 | 0x40)}; + auto const noswap{TrainType == train_type::emu || TrainType == train_type::et41}; + auto swap{false == noswap && TestFlag(Couplers[CValue2 == -1 ? end::rear : end::front].CouplingFlag, coupling::control)}; + if (auto const reversed{inputcab != (CabActive != -1 ? 1 : 0)}; reversed) + { + swap = !swap; + } // TODO: check whether this part has RL equivalent + OperatePantographValve(static_cast(swap ? 1 - inputend : inputend), static_cast(inputoperation), range_t::local); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "PantsValve") + { + OperatePantographsValve(static_cast(static_cast(CValue1)), range_t::local); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "PantAllDown") + { + DropAllPantographs(CValue1 == 1, range_t::local); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "TractionMode") + { + TractionModeSwitch(CValue1 > 0.5 ? traction_mode::genset : traction_mode::catenary, range_t::local); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "GensetSwitch") + { + GensetSwitch(CValue1 > 0.5, range_t::local); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + { + return false; + } + return true; +} + +// RunCommand() for the doors and the departure signal; returns whether the command is one of them +bool TMoverParameters::RunDoorsCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +{ + if (Command == "DoorPermit") + { + DoorPermitCommand(CValue1, CValue2); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "DoorOpen" || Command == "DoorClose") /*NBMX*/ + { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów + DoorRemoteCommand(Command == "DoorOpen", CValue1, CValue2); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "DoorLock") + { + Doors.lock_enabled = CValue1 == 1 ? true : false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "DoorStep") + { + Doors.step_enabled = CValue1 == 1 ? true : false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "DoorMode") + { + Doors.remote_only = CValue1 == 1 ? true : false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == "DepartureSignal") + { + DepartureSignal = CValue1 == 1 ? true : false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + { + return false; + } + return true; +} + +// the doors' permits, on the sides the command names: CValue1 the sides, negative to take the permit back, CValue2 the +// direction the command comes from +void TMoverParameters::DoorPermitCommand(double const CValue1, double const CValue2) +{ + auto const leftside{CValue2 > 0 ? 1 : 2}; + if (auto const rightside{3 - leftside}; std::abs(static_cast(CValue1)) & rightside) + { + PermitDoors_(side::right, CValue1 > 0); + } + if (std::abs(static_cast(CValue1)) & leftside) + { + PermitDoors_(side::left, CValue1 > 0); + } +} + +// the doors opened or closed from afar on the sides the command names, unless they're only worked locally +void TMoverParameters::DoorRemoteCommand(bool const Open, double const CValue1, double const CValue2) +{ + using enum control_t; + if (auto const doorcontrol{Open ? Doors.open_control : Doors.close_control}; + (doorcontrol != conductor && doorcontrol != driver && doorcontrol != mixed) || (false == Power24vIsAvailable && false == Power110vIsAvailable)) + { + return; + } + auto const leftside{CValue2 > 0 ? 1 : 2}; + if (auto const rightside{3 - leftside}; static_cast(CValue1) & rightside) + { + Doors.instances[side::right].remote_open = Open; + Doors.instances[side::right].remote_close = false == Open; + } + if (static_cast(CValue1) & leftside) + { + Doors.instances[side::left].remote_open = Open; + Doors.instances[side::left].remote_close = false == Open; + } +} + +// RunCommand() for the load and the damage; returns whether the command is one of them +bool TMoverParameters::RunLoadCommand(std::string const &Command, double CValue1, double CValue2, int const /*Couplertype*/, bool &OK) +{ + if (issection("Load=", Command)) + { + OK = false; // będzie powtarzane aż się załaduje + if (Vel < 0.1 // tolerance margin for small vehicle movements in the consist + && MaxLoad > 0 && LoadAmount < MaxLoad * (1.0 + OverLoadFactor) && Distance(Loc, CommandIn.Location, Dim, Dim) < (CValue2 > 1.0 ? CValue2 : 10.0)) + { // ten peron/rampa + + auto const loadname{ToLower(extract_value("Load", Command))}; + if (LoadAmount == 0.f) + { + AssignLoad(loadname); + } + OK = LoadingDone(LoadSpeed, + loadname); // zmienia LoadStatus + } + else + { + // no loading can be done if conditions aren't met + LastLoadChangeTime = 0.0; + } + } + else if (issection("UnLoad=", Command)) + { + OK = false; // będzie powtarzane aż się rozładuje + if (Vel < 0.1 // tolerance margin for small vehicle movements in the consist + && LoadAmount > 0 // czy jest co rozladowac? + && Distance(Loc, CommandIn.Location, Dim, Dim) < (CValue2 > 1.0 ? CValue2 : 10.0)) + { // ten peron + /*mozna to rozladowac*/ + OK = LoadingDone(-1.f * LoadSpeed, ToLower(extract_value("UnLoad", Command))); + } + else + { + // no loading can be done if conditions aren't met + LastLoadChangeTime = 0.0; + } + } + else if (Command == "SetDamage") + { + if (CValue2 == 1) + OK = SetFlag(DamageFlag, static_cast(floor(CValue1))); + if (CValue2 == -1) + { + auto const derailed{TestFlag(DamageFlag, dtrain_out)}; + OK = SetFlag(DamageFlag, static_cast(-floor(CValue1))); + // taking the derailment off puts the vehicle back on the rails, with what the criteria of derailment held + if (derailed && false == TestFlag(DamageFlag, dtrain_out)) + rerail(); + } + } + else + { + return false; + } + return true; +} + +// ************************************************************************************************* +// Q: 20160714 +// Uruchamia funkcję RunCommand aż do skutku. Jeśli będzie pozytywny to kasuje komendę. +// ************************************************************************************************* +bool TMoverParameters::RunInternalCommand() +{ + bool OK; + + if (!CommandIn.Command.empty()) + { + OK = RunCommand(CommandIn.Command, CommandIn.Value1, CommandIn.Value2, CommandIn.Coupling); + if (OK) + { + + CommandIn.Command.clear(); // kasowanie bo rozkaz wykonany + CommandIn.Value1 = 0; + CommandIn.Value2 = 0; + CommandIn.Coupling = 0; + CommandIn.Location.X = 0; + CommandIn.Location.Y = 0; + CommandIn.Location.Z = 0; + switch_physics(true, wake_cause::command); + } + } + else + OK = false; + return OK; +} diff --git a/physics/mover/controllers.cpp b/physics/mover/controllers.cpp new file mode 100644 index 000000000..225e36a03 --- /dev/null +++ b/physics/mover/controllers.cpp @@ -0,0 +1,1529 @@ +/* +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 master and the secondary controllers, the automatic relay and the camshaft, the integrated controller, the speed control + +#include "stdafx.h" +#include "physics/mover.h" +#include "vehicle/DynObj.h" +#include "physics/oerlikonest.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/Timer.h" +#include "utilities/parser.h" +#include "simulation/simulation.h" +#include "vehicle/fieldshunting.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "physics/mover/internal.h" + + +// ************************************************************************************************* +// queuedEU +// ************************************************************************************************* + +// ************************************************************************************************* +// Q: 20160710 +// zwiększenie nastawinika +// ************************************************************************************************* + +bool TMoverParameters::IncMainCtrl(int CtrlSpeed) +{ + // basic fail conditions: + if (MainCtrlPosNo <= 0 || CabActive == 0) + { + // nie ma sterowania + return false; + } + if (TrainType == train_type::et22 && ScndCtrlPos != 0) + { + // w ET22 nie da się kręcić nastawnikiem przy włączonym boczniku + return false; + } + if (TrainType == train_type::emu && DirActive == 0) + { + // w EZT nie da się załączyć pozycji bez ustawienia kierunku + return false; + } + + bool OK = false; + if (MainCtrlPos < MainCtrlPosNo) + { + OK = IncMainCtrlByEngine(CtrlSpeed); + } + else + { // MainCtrlPos>=MainCtrlPosNo + if (true == CoupledCtrl) + { + // wspólny wał nastawnika jazdy i bocznikowania + if (ScndCtrlPos < ScndCtrlPosNo) + { // 3<3 -> false + ++ScndCtrlPos; + OK = true; + } + else + { + OK = false; + } + } + } + + if (true == OK) + { + ScndCtrlResistiveLockCheck(); // e.g. from the last series position on to the resistive parallel ones + SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); //??? + SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); + } + + // hunter-101012: poprawka + // poprzedni warunek byl niezbyt dobry, bo przez to przy trzymaniu + + // styczniki tkwily na tej samej pozycji (LastRelayTime byl caly czas 0 i rosl + // po puszczeniu plusa) + + if (OK) + { + if (DelayCtrlFlag) + { + if (LastRelayTime >= InitialCtrlDelay && MainCtrlPos == 1) + LastRelayTime = 0; + } + else if (LastRelayTime > CtrlDelay) + LastRelayTime = 0; + } + return OK; +} + +// a notch up, as the kind of the engine takes it; returns whether the controller moved +bool TMoverParameters::IncMainCtrlByEngine(int const CtrlSpeed) +{ + bool OK = false; + switch (EngineType) + { + case TEngineType::None: + case TEngineType::Dumb: + case TEngineType::DieselElectric: + case TEngineType::ElectricInductionMotor: + { + if (CtrlSpeed > 1) + { + OK = IncMainCtrl(1) && IncMainCtrl(CtrlSpeed - 1); // a fail will propagate up the recursion chain. should this be || instead? + break; + } + ++MainCtrlPos; + OK = true; + if (EIMCtrlType == 0 && ( SpeedCtrlAutoTurnOffFlag & 1 ) == 1 && MainCtrlActualPos != MainCtrlPos) + { + SpeedCtrlSwitch(false); + SpeedCtrlUnit.IsActive = false; + } + break; + } + + case TEngineType::ElectricSeriesMotor: + { + OK = IncMainCtrlSeriesMotor(CtrlSpeed); + break; + } + + case TEngineType::DieselEngine: + { + if (CtrlSpeed > 1) + { + while (MainCtrlPos < MainCtrlPosNo && IncMainCtrl(1)) + { + // all work is done in the loop header + } + } + else + { + ++MainCtrlPos; + } + CompressorAllow = MainCtrlPowerPos() > 0; + OK = true; + break; + } + + case TEngineType::WheelsDriven: + { + OK = AddPulseForce(CtrlSpeed); + break; + } + default: + break; + } // switch EngineType of + return OK; +} + +// a notch up of the series motors' controller: CtrlSpeed over 1 runs it to the first position without resistors; +// returns whether it moved as asked +bool TMoverParameters::IncMainCtrlSeriesMotor(int const CtrlSpeed) +{ + bool OK = false; + if (DirActive == 0) + { + return false; + } + + if (CtrlSpeed > 1) + { + // szybkie przejœcie na bezoporow¹ + if (TrainType == train_type::et40) + { + return false; // this means ET40 won't react at all to fast acceleration command. should it issue just IncMainCtrl(1) instead? + } + while (RList[MainCtrlPos].R > 0.0 && IncMainCtrl(1)) + { + // all work is done in the loop header + } + OK = false; // shouldn't this be part of the loop above? + // if (TrainType=train_type::et40) then + // while Abs (Im)>IminHi do + // dec(MainCtrlPos); + // OK:=false ; + } + else + { // CtrlSpeed == 1 + ++MainCtrlPos; + OK = true; + if (Imax == ImaxHi && RList[MainCtrlPos].Bn > 1) + { + /* NOTE: disabled, relay configuration was moved to compute_movement_ + if( true == MaxCurrentSwitch( false )) { + // wylaczanie wysokiego rozruchu + SetFlag( SoundFlag, sound::relay ); + } + */ + if (TrainType == train_type::et42) + { + --MainCtrlPos; + OK = false; + } + } + // + // if (TrainType == "et40") + // if (Abs(Im) > IminHi) + // { + // MainCtrlPos--; //Blokada nastawnika po przekroczeniu minimalnego pradu + // OK = false; + // } + //} + } + + if (TrainType == train_type::et42 && true == DynamicBrakeFlag && MainCtrlPos > 20) + { + MainCtrlPos = 20; + OK = false; + } + return OK; +} + +// ***************************************************************************** +// Q: 20160710 +// zmniejszenie nastawnika +// ***************************************************************************** +bool TMoverParameters::DecMainCtrl(int CtrlSpeed) +{ + bool OK = false; + // basic fail conditions: + if (MainCtrlPosNo <= 0 || CabActive == 0) + { + // nie ma sterowania + OK = false; + } + else if (CtrlSpeed == 0) + { + return false; + } + else + { + // TBD, TODO: replace with mainctrlpowerpos() check? + if (MainCtrlPos > 0) + { + if (TrainType != train_type::et22 || ScndCtrlPos == 0) // Ra: ET22 blokuje nastawnik przy boczniku + { + if (CoupledCtrl && ScndCtrlPos > 0) + { + ScndCtrlPos--; // wspolny wal + OK = true; + } + else + OK = DecMainCtrlByEngine(CtrlSpeed); + } + } + else if (EngineType == TEngineType::WheelsDriven) + OK = AddPulseForce(-CtrlSpeed); + else + OK = false; + + if (OK) + { + ScndCtrlResistiveLockCheck(); // the shunt drops when the master controller leaves a resistance-free position + /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); // hmmmm...???!!! + /*OK:=*/SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); + } + } + // if OK then LastRelayTime:=0; + // hunter-101012: poprawka + if (OK) + { + if (DelayCtrlFlag) + { + if (LastRelayTime >= InitialCtrlDelay) + LastRelayTime = 0; + } + else if (LastRelayTime > CtrlDownDelay) + LastRelayTime = 0; + } + return OK; +} + +// a notch down, as the kind of the engine takes it; returns whether the controller moved +bool TMoverParameters::DecMainCtrlByEngine(int const CtrlSpeed) +{ + bool OK = false; + switch (EngineType) + { + case TEngineType::None: + case TEngineType::Dumb: + case TEngineType::DieselElectric: + case TEngineType::ElectricInductionMotor: + { + if (CtrlSpeed == 1) + { + MainCtrlPos--; + OK = true; + if (EIMCtrlType == 0 && (SpeedCtrlAutoTurnOffFlag & 1) == 1 && MainCtrlActualPos != MainCtrlPos) + { + SpeedCtrlSwitch(false); + SpeedCtrlUnit.IsActive = false; + } + } + else if (CtrlSpeed > 1) + OK = DecMainCtrl(1) && DecMainCtrl(CtrlSpeed - 1); // CtrlSpeed-1); + break; + } + + case TEngineType::ElectricSeriesMotor: + { + OK = DecMainCtrlSeriesMotor(CtrlSpeed); + break; + } + + case TEngineType::DieselEngine: + { + if (CtrlSpeed == 1) + { + MainCtrlPos--; + OK = true; + } + else if (CtrlSpeed > 1) + { + while (MainCtrlPos > 0 || RList[MainCtrlPos].Mn > 0) + DecMainCtrl(1); + OK = true; + } + break; + } + default: + break; + } // switch EngineType + return OK; +} + +// a notch down of the series motors' controller: CtrlSpeed over 1 runs it down to the first position without resistors +bool TMoverParameters::DecMainCtrlSeriesMotor(int const CtrlSpeed) +{ + bool OK = false; + if (CtrlSpeed == 1) /*and (ScndCtrlPos=0)*/ + { + MainCtrlPos--; + // if (MainCtrlPos=0) and (ScndCtrlPos=0) and + // (TrainType<>train_type::et40)and(TrainType<>train_type::ep05) then + // StLinFlag:=false; + // if (MainCtrlPos=0) and (TrainType<>train_type::et40) and + // (TrainType<>train_type::ep05) then + // MainCtrlActualPos:=0; //yBARC: co to tutaj robi? ;) + OK = true; + } + else if (CtrlSpeed > 1) /*and (ScndCtrlPos=0)*/ + { + OK = true; + if (RList[MainCtrlPos].R == 0) // Q: tu zrobilem = ;] + DecMainCtrl(1); + while (RList[MainCtrlPos].R > 0 && DecMainCtrl(1)) + ; // takie chamskie, potem poprawie} + } + return OK; +} + +bool TMoverParameters::IsMainCtrlActualNoPowerPos() const +{ + // TODO: wrap controller pieces into a class for potential specializations, similar to brake subsystems + return MainCtrlActualPos <= MainCtrlNoPowerPos(); +} + +bool TMoverParameters::IsMainCtrlNoPowerPos() const +{ + // TODO: wrap controller pieces into a class for potential specializations, similar to brake subsystems + return MainCtrlPos <= MainCtrlNoPowerPos(); +} + +bool TMoverParameters::IsMainCtrlMaxPowerPos() const +{ + // TODO: wrap controller pieces into a class for potential specializations, similar to brake subsystems + return MainCtrlPos == MainCtrlPosNo; +} + +int TMoverParameters::MainCtrlNoPowerPos() const +{ + + switch (EIMCtrlType) + { + case 1: + { + return 3; + } + case 2: + { + return 3 + EIMCtrlEmergencyPositions(); + } + case 3: + { + return UniCtrlNoPowerPos; + } + default: + { + return 0; + } + } +} + +int TMoverParameters::MainCtrlActualPowerPos() const +{ + + return MainCtrlActualPos - MainCtrlNoPowerPos(); +} + +int TMoverParameters::MainCtrlPowerPos() const +{ + + return MainCtrlPos - MainCtrlNoPowerPos(); +} + +int TMoverParameters::EIMCtrlEmergencyPositions() const +{ + return (EIMCtrlType == 2 && EIMCtrlMainEmergency) ? 1 : 0; +} + +bool TMoverParameters::IsMainCtrlEmergencyPos() const +{ + return MainCtrlPos < EIMCtrlEmergencyPositions(); +} + +int TMoverParameters::MainCtrlPosForCoupled() const +{ + // the emergency brake itself reaches the train through the brake pipe, vented by the vehicle driven from + return std::max(0, MainCtrlPos - EIMCtrlEmergencyPositions()); +} + +int TMoverParameters::MainCtrlPosFromCoupled(int const Position) const +{ + return Position + EIMCtrlEmergencyPositions(); +} + +// ************************************************************************************************* +// Q: 20160710 +// zwiększenie bocznika +// ************************************************************************************************* +bool TMoverParameters::IncScndCtrl(int CtrlSpeed) +{ + bool OK = false; + + if (DynamicBrakeFlag && TrainType == train_type::et42 && CabActive != 0 && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0) + { + OK = DynamicBrakeSwitch(false); + } + else if (ScndCtrlPosNo > 0 && CabActive != 0 && !(TrainType == train_type::et42 && (Imax == ImaxHi || (DynamicBrakeFlag && MainCtrlPowerPos() > 0)))) + { + // if (RList[MainCtrlPos].R=0) and (MainCtrlPos>0) and (ScndCtrlPos 1) + { + ScndCtrlPos = ScndCtrlPosNo; // takie chamskie, potem poprawie + } + OK = true; + } + } + else // nie mozna zmienic + OK = false; + if (OK) + { + /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); //??? + /*OK:=*/SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); + } + } + else // nie ma sterowania + OK = false; + // if OK then LastRelayTime:=0; + // hunter-101012: poprawka + if (OK && LastRelayTime > CtrlDelay) + LastRelayTime = 0; + + if (OK && EngineType == TEngineType::ElectricInductionMotor && ScndCtrlPosNo == 1 && MainCtrlPos > 0) + { + SpeedCtrlValue = Vel; + if (EIMCtrlType == 0 && (SpeedCtrlAutoTurnOffFlag & 1) == 1) + { + MainCtrlActualPos = MainCtrlPos; + } + SpeedCtrlUnit.IsActive = true; + } + + if (OK && SpeedCtrl && ScndCtrlPos == 1 && EngineType == TEngineType::DieselEngine) + { + // NOTE: round() already adds 0.5, are the ones added here as well correct? + SpeedCtrlValue = static_cast(Round(Vel)); + SpeedCtrlUnit.IsActive = true; + } + + return OK; +} + +// ************************************************************************************************* +// Q: 20160710 +// zmniejszenie bocznika +// ************************************************************************************************* +bool TMoverParameters::DecScndCtrl(int CtrlSpeed) +{ + bool OK = false; + + if (IsMainCtrlNoPowerPos() && CabActive != 0 && TrainType == train_type::et42 && ScndCtrlPos == 0 && !DynamicBrakeFlag && CtrlSpeed == 1) + { + // Ra: AI wywołuje z CtrlSpeed=2 albo gdy ScndCtrlPos>0 + OK = DynamicBrakeSwitch(true); + } + else if (ScndCtrlPosNo > 0 && CabActive != 0) + { + if (ScndCtrlPos > 0 && !CoupledCtrl && (EngineType != TEngineType::DieselElectric || !AutoRelayFlag) && !IsScndCtrlLockedByMainCtrl()) + { + if (CtrlSpeed == 1) + { + ScndCtrlPos--; + } + else if (CtrlSpeed > 1) + { + ScndCtrlPos = 0; // takie chamskie, potem poprawie + } + OK = true; + } + else + OK = false; + if (OK) + { + /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); //??? + /*OK:=*/SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); + } + } + else + OK = false; + // if OK then LastRelayTime:=0; + // hunter-101012: poprawka + if (OK && LastRelayTime > CtrlDownDelay) + LastRelayTime = 0; + + if (OK && EngineType == TEngineType::ElectricInductionMotor && ScndCtrlPosNo == 1) + { + SpeedCtrlValue = 0; + SpeedCtrlUnit.IsActive = false; + if (SpeedCtrlUnit.ManualStateOverride) + { + eimic = 0.0; + } + } + + if (OK && SpeedCtrl && ScndCtrlPos == 0 && EngineType == TEngineType::DieselEngine) + { + SpeedCtrlValue = 0; + SpeedCtrlUnit.IsActive = false; + if (SpeedCtrlUnit.ManualStateOverride) + { + eimic = 0.0; + } + } + + return OK; +} + +bool TMoverParameters::IsScndCtrlLockedByMainCtrl() const +{ + // ET21, ET22, EP09: the field shunting engages only on the resistance-free positions of the master controller (eu07/maszyna#402) + return ScndCtrlResistiveLock && (IsMainCtrlNoPowerPos() || RList[MainCtrlPos].R >= 0.01); +} + +void TMoverParameters::ScndCtrlResistiveLockCheck() +{ + // the shunt controller, locked in both directions on zero and the resistive positions, would otherwise stay engaged there once the + // master controller is taken back (or set from elsewhere, e.g. by the AI or another vehicle of the consist) with the shunt on + if (ScndCtrlPos > 0 && !CoupledCtrl && IsScndCtrlLockedByMainCtrl()) + { + ScndCtrlPos = 0; + } +} + +int TMoverParameters::GetVirtualScndPos() const +{ + if (TrainType == train_type::et42 && DynamicBrakeFlag && !ScndCtrlPos) + return -1; + return ScndCtrlPos; +} + +bool TMoverParameters::IsScndCtrlNoPowerPos() const +{ + // TODO: refine the check on account of potential electric series vehicles with speed control + return ScndCtrlPos == 0 || true == SpeedCtrl; +} + +bool TMoverParameters::IsScndCtrlMaxPowerPos() const +{ + // TODO: refine the check on account of potential electric series vehicles with speed control + return ScndCtrlPos == ScndCtrlPosNo || true == SpeedCtrl; +} + +// ************************************************************************************************* +// Q: 20160713 +// Włączenie / wyłączenie automatycznego rozruchu +// ************************************************************************************************* +bool TMoverParameters::AutoRelaySwitch(bool State) +{ + bool ARS; + if (AutoRelayType == 2 && AutoRelayFlag != State) + { + AutoRelayFlag = State; + ARS = true; + SendCtrlToNext("AutoRelaySwitch", int(State), CabActive); + } + else + ARS = false; + + return ARS; +} + +// ************************************************************************************************* +// Q: 20160724 +// Sprawdzenie warunków pracy automatycznego rozruchu +// ************************************************************************************************* + +bool TMoverParameters::AutoRelayCheck(void) +{ + bool OK = false; // b:int; + + auto const motorconnectorsoff{false == MotorConnectorsCheck()}; + + // Ra 2014-06: dla SN61 nie działa prawidłowo + // yBARC - rozlaczenie stycznikow liniowych + if (motorconnectorsoff || (HasCamshaft ? IsMainCtrlActualNoPowerPos() : IsMainCtrlNoPowerPos())) + { + StLinFlag = false; + if (false == DynamicBrakeFlag) + { + Im = 0; + Itot = 0; + ResistorsFlag = false; + } + } + + // sprawdzenie wszystkich warunkow (AutoRelayFlag, AutoSwitch, Im 0 || ScndCtrlPos > 0) && (!CoupledCtrl || RList[MainCtrlActualPos].Relay == MainCtrlPos)) + { // zmieniaj scndctrlactualpos + OK = AutoRelayShuntStep(ARFASI2); + } + else + { // zmieniaj mainctrlactualpos + OK = AutoRelayMainStep(ARFASI); + } + } + else // not StLinFlag + { + OK = AutoRelayLineContactorsStep(motorconnectorsoff); + } + if (OK) + LastRelayTime = 0; + + return OK; + } +} + +// a step of the shunt field on a position without resistors, up or down to the second controller +bool TMoverParameters::AutoRelayShuntStep(bool const ARFASI2) +{ + bool OK = false; + // scnd bez samoczynnego rozruchu + if (ScndCtrlActualPos < ScndCtrlPos) + { + if (LastRelayTime > CtrlDelay && ARFASI2) + { + ++ScndCtrlActualPos; + SetFlag(SoundFlag, sound::shuntfield); + OK = true; + } + } + else if (ScndCtrlActualPos > ScndCtrlPos) + { + if (LastRelayTime > CtrlDownDelay && TrainType != train_type::emu) + { + --ScndCtrlActualPos; + SetFlag(SoundFlag, sound::shuntfield); + OK = true; + } + } + else + OK = false; + return OK; +} + +// a step of the main controller's relays, up or down to its position, or the shunt field off on the resistors +bool TMoverParameters::AutoRelayMainStep(bool const ARFASI) +{ + bool OK = false; + // running backwards, the motors don't get joined in more branches than allowed (the series connection + // alone, usually); the camshaft still goes back down from there (eu07/maszyna#393: it stayed where it + // was, the line contactors closed, whatever the driver did with the master controller) + auto const backwardslimit{DirActive < 0 && TrainType != train_type::pseudodiesel && RList[MainCtrlActualPos + 1].Bn > BackwardsBranchesAllowed}; + // main bez samoczynnego rozruchu + if (false == backwardslimit && MainCtrlActualPos < std::size(RList) - 1 // crude guard against running out of current fixed table + && (RList[MainCtrlActualPos].Relay < MainCtrlPos || (RList[MainCtrlActualPos + 1].Relay == MainCtrlPos && MainCtrlActualPos < RlistSize) || + (TrainType == train_type::et22 && DelayCtrlFlag))) + { + OK = AutoRelayMainUp(ARFASI); + } + else if (RList[MainCtrlActualPos].Relay > MainCtrlPos) + { + OK = AutoRelayMainDown(); + } + else if (RList[MainCtrlActualPos].R > 0 && ScndCtrlActualPos > 0) + { + if (LastRelayTime > CtrlDownDelay) + { + --ScndCtrlActualPos; // boczniki nie dzialaja na poz. oporowych + SetFlag(SoundFlag, sound::shuntfield); + OK = true; + } + } + else + OK = false; + return OK; +} + +// a step of the main relays up to the controller's position, at once to the parallel position without resistors +// on a fast serial circuit (303E); returns whether the relays moved, never into parallel with the overload relay high +bool TMoverParameters::AutoRelayMainUp(bool const ARFASI) +{ + bool OK = false; + // prevent switch to parallel mode if motor overload relay is set to high threshold mode + if (IsMotorOverloadRelayHighThresholdOn() && RList[MainCtrlActualPos + 1].Bn > 1) + { + return false; + } + + if (RList[MainCtrlPos].R == 0 && MainCtrlPos > 0 && MainCtrlPos != MainCtrlPosNo && FastSerialCircuit == 1) + { + // szybkie wchodzenie na bezoporowa (303E) + // MainCtrlActualPos:=MainCtrlPos; //hunter-111012: + ++MainCtrlActualPos; + if (MainCtrlPos - MainCtrlActualPos == 1) + { + // HACK: ensure we play only single sound of basic relays for entire trasition; return false + // for all but last step despite configuration change, to prevent playback of the basic relay sound + // TBD, TODO: move the basic sound event here and enable it with call parameter + OK = true; + } + if (RList[MainCtrlActualPos].R == 0) + { + SetFlag(SoundFlag, sound::parallel | sound::loud); + OK = true; + } + } + else if (LastRelayTime > CtrlDelay && ARFASI) + { + OK = AutoRelayMainNotchUp(); + } + return OK; +} + +// a notch up of the main relays after their delay, through the group switch of the ET22, and the sounds of the +// parallel positions; returns whether they moved +bool TMoverParameters::AutoRelayMainNotchUp() +{ + bool OK = false; + // WriteLog("LRT = " + FloatToStr(LastRelayTime) + ", " + + // FloatToStr(CtrlDelay)); + if (TrainType == train_type::et22 && MainCtrlPos > 1 && (RList[MainCtrlActualPos].Bn < RList[MainCtrlActualPos + 1].Bn || DelayCtrlFlag)) + { + // et22 z walem grupowym + if (!DelayCtrlFlag) // najpierw przejscie + { + ++MainCtrlActualPos; + DelayCtrlFlag = true; // tryb przejscia + OK = true; + } + else if (LastRelayTime > 4 * CtrlDelay) // przejscie + { + + DelayCtrlFlag = false; + OK = true; + } + /* + else + ; + */ + } + else // nie ET22 z wałem grupowym + { + ++MainCtrlActualPos; + OK = true; + } + //--------- + // hunter-111211: poprawki + if (MainCtrlActualPos > 0) + { + if (RList[MainCtrlActualPos].R == 0 && MainCtrlActualPos != MainCtrlPosNo) + { + // wejscie na bezoporowa + SetFlag(SoundFlag, sound::parallel | sound::loud); + } + else if (RList[MainCtrlActualPos].R > 0 && RList[MainCtrlActualPos - 1].R == 0) + { + // wejscie na drugi uklad + SetFlag(SoundFlag, sound::parallel); + } + } + return OK; +} + +// a step of the main relays down to the controller's position; returns whether they moved +bool TMoverParameters::AutoRelayMainDown() +{ + bool OK = false; + if (RList[MainCtrlPos].R == 0 && MainCtrlPos > 0 && !(MainCtrlPos == MainCtrlPosNo) && FastSerialCircuit == 1) + { + // szybkie wchodzenie na bezoporowa (303E) + // MainCtrlActualPos:=MainCtrlPos; //hunter-111012: + --MainCtrlActualPos; + OK = true; + if (RList[MainCtrlActualPos].R == 0) + { + SetFlag(SoundFlag, sound::parallel); + } + } + else if (LastRelayTime > CtrlDownDelay) + { + if (TrainType != train_type::emu) // tutaj powinien być tryb sterowania wałem + { + --MainCtrlActualPos; + OK = true; + } + // hunter-111211: poprawki + if (MainCtrlActualPos > 0 && RList[MainCtrlActualPos].R == 0) + { + // dzwieki schodzenia z bezoporowej} + SetFlag(SoundFlag, sound::parallel); + } + } + return OK; +} + +// the line contactors closed at the first position, or, open, the camshaft run back to zero +bool TMoverParameters::AutoRelayLineContactorsStep(bool const motorconnectorsoff) +{ + bool OK = false; + // ybARC - zalaczenie stycznikow liniowych + if (false == motorconnectorsoff && MainCtrlActualPos == 0 && (TrainType == train_type::emu || HasCamshaft ? MainCtrlPowerPos() > 0 : MainCtrlPowerPos() == 1)) + { + + DelayCtrlFlag = true; + if (LastRelayTime >= InitialCtrlDelay) + { + StLinFlag = true; + MainCtrlActualPos = 1; + DelayCtrlFlag = false; + SetFlag(SoundFlag, sound::relay | sound::loud); + OK = true; + } + } + else + { + DelayCtrlFlag = false; + } + + if (false == StLinFlag && (MainCtrlActualPos > 0 || ScndCtrlActualPos > 0)) + { + OK |= CamshaftRunDown(); + } + return OK; +} + +// the camshaft, the line contactors open, run back to its zero position a step at a time, or at once without one; +// returns whether it moved +bool TMoverParameters::CamshaftRunDown() +{ + bool OK = false; + + if (CoupledCtrl) + { + + if (TrainType == train_type::emu) + { + OK = CamshaftRunDownEMU(); + } + else if (LastRelayTime > CtrlDownDelay) // wal kulakowy dwukierunkowy + { + if (ScndCtrlActualPos > 0) + { + --ScndCtrlActualPos; + SetFlag(SoundFlag, sound::shuntfield); + } + else + { + --MainCtrlActualPos; + } + OK = true; + } + } + else if (HasCamshaft) + { + // wal kulakowy dwukierunkowy + if (LastRelayTime > CtrlDownDelay) + { + if (MainCtrlActualPos > 0) + { + --MainCtrlActualPos; + } + ScndCtrlActualPos = 0; + OK = true; + } + } + else + { + MainCtrlActualPos = 0; + ScndCtrlActualPos = 0; + OK = true; + } + return OK; +} + +// the one way camshaft of the EN57 run on to its end and round to zero; returns whether it moved +bool TMoverParameters::CamshaftRunDownEMU() +{ + bool OK = false; + // EN57 wal jednokierunkowy calosciowy + if (MainCtrlActualPos == 1) + { + + MainCtrlActualPos = 0; + OK = true; + } + else + { + + if (LastRelayTime > CtrlDownDelay) + { + + if (MainCtrlActualPos < RlistSize) + { + // dojdz do konca + ++MainCtrlActualPos; + } + else if (ScndCtrlActualPos < ScndCtrlPosNo) + { + // potem boki + ++ScndCtrlActualPos; + SetFlag(SoundFlag, sound::shuntfield); + } + else + { + // i sie przewroc na koniec + MainCtrlActualPos = 0; + ScndCtrlActualPos = 0; + } + OK = true; + } + } + return OK; +} + +bool TMoverParameters::MotorConnectorsCheck() +{ + + // hunter-111211: wylacznik cisnieniowy + // (on some vehicles it watches the brake pipe alone) + ControlPressureSwitch = HasControlPressureSwitch && ((PressureSwitchBrakeCylinder && BrakePress > 2.0) || PipePress < 3.6); + + if (true == ControlPressureSwitch) + { + return false; + } + + // a line breaker closed ahead of the pantographs holds without voltage; what cuts the motors off there is its + // undervoltage relay, which elsewhere opens the line breaker + auto const undervoltage{PantographsRequireMains && false == NoVoltRelay}; + + auto const connectorsoff{false == Mains || undervoltage || true == FuseFlag || true == StLinSwitchOff || DirActive == 0}; + + return false == connectorsoff && LineContactorsInterlockReleased(); +} + +bool TMoverParameters::LineContactorsInterlockReleased() const +{ + switch (LineContactorsInterlock) + { + case line_contactors_interlock::converter: + // the converter of this very vehicle, not the 110 V of the trainset: a section with its fans off doesn't start + return ConverterFlag; + case line_contactors_interlock::motor_blowers: + return std::ranges::all_of(MotorBlowers, [this](auto const &Blower) { + if (Blower.min_start_velocity < 0) + { + return Blower.is_active; + } + // a blower which starts with the speed and the motor current (MotorBlowersStartVelocity) can't run before + // the contactors close, nor after a stop longer than it keeps running for: it's enough that it's + // switched on and has power, so it starts once the vehicle moves + return MotorBlowerPowerIsAvailable(Blower) && false == Blower.is_disabled && (Blower.start_type == start_t::manual ? Blower.is_enabled : true); + }); + default: + return true; + } +} +namespace +{ + +// the setting of the universal controller one UniCtrlValStep further from Value towards Limit, never past it +double next_uc_step(double const Value, double const Limit, double const Step) +{ + constexpr double epsilon{1e-6}; + if (Limit > Value) + { + return std::min((std::floor(Value / Step + epsilon) + 1.0) * Step, Limit); + } + return std::max((std::ceil(Value / Step - epsilon) - 1.0) * Step, Limit); +} + +// the universal controller with UniCtrlValStep: the setting the continuous ramp got to (Ramped) turned into whole steps. +// a move of the controller onto a position which changes the setting makes one step at once, the ramp then one step each +// time it covers a step's length; the steps stop at the position's set value (or its bound, past which the ramp doesn't go) +double stepped_uc_value(double const Current, double const Ramped, TUniversalCtrl const &Position, double const Step, bool const Moved, double &Progress) +{ + if (Moved) + { + Progress = 0.0; + } + double const delta{Ramped - Current}; + if (std::abs(delta) < 1e-9) + { + Progress = 0.0; + return Ramped; + } + double limit{0.0}; + if (delta > 0.0) + { + limit = Position.SetCtrlVal > Current ? Position.SetCtrlVal : Position.MaxCtrlVal; + } + else + { + limit = Position.SetCtrlVal < Current ? Position.SetCtrlVal : Position.MinCtrlVal; + } + Progress = Moved ? Step : Progress + std::abs(delta); + double value{Current}; + bool reached{std::abs(value - limit) < 1e-9}; + while (!reached && Progress >= Step - 1e-9) + { + value = next_uc_step(value, limit, Step); + Progress -= Step; + reached = std::abs(value - limit) < 1e-9; + } + if (reached) + { + Progress = 0.0; + } + // added after the move to std::clamp: bounds given the other way round are put in order, as master did it + auto const [lowest, highest] = std::minmax(Position.MinCtrlVal, Position.MaxCtrlVal); + return std::clamp(value, lowest, highest); +} + +} // namespace + +void TMoverParameters::CheckEIMIC(double dt) +{ + double offset = EIMCtrlAdditionalZeros ? 1.0 : 0.0; + double multiplier = (EIMCtrlEmergency ? 1.0 : 0.0) + offset; + // gdy SplitEDPneumaticBrake jest wlaczone, sterowanie ujemne (hamowanie ED) bierzemy + // z osobnego nastawnika DynamicBrakeCtrl, a nie z hamulca pomocniczego (LocalBrake). + // Dodatkowo zapotrzebowanie ED jest ograniczone przez strefe Vh0..Vh1: powyzej Vh1 - pelny ED, + // pomiedzy Vh1 a Vh0 - liniowe zanikanie, ponizej Vh0 - zerowe (brak hamowania pneumatycznego + // jako uzupelnienia, poniewaz LocalBrake jest oddzielny i operuje wylacznie pneumatyka). + double brakeDemand = SplitEDPneumaticBrake ? DynamicBrakeRatio() : LocalBrakeRatio(); + if (SplitEDPneumaticBrake) + { + double const vh0 = eimc[eimc_p_Vh0]; + double const vh1 = eimc[eimc_p_Vh1]; + if (vh1 > vh0 + 0.001) + { + double const vhRamp = std::clamp((Vel - vh0) / (vh1 - vh0), 0.0, 1.0); + brakeDemand *= vhRamp; + } + } + switch (EIMCtrlType) + { + case 0: + EIMICFromController(brakeDemand, offset, multiplier); + break; + case 1: + EIMICFromSteps(dt); + break; + case 2: + EIMICFromFourPositions(dt); + break; + case 3: + EIMICFromUniversalController(dt, brakeDemand); + break; + } + if (LocHandleTimeTraxx) + { + EIMICTraxxLocalBrake(dt); + } + + EIMICLimit(); +} + +// the controller (EIMCtrlType 0): the position of the main controller, or the analog one, or the brake asked +void TMoverParameters::EIMICFromController(double const brakeDemand, double const offset, double const multiplier) +{ + eimic = brakeDemand > 0.01 ? -brakeDemand : eimic_analog > 0.01 ? eimic_analog : (double)MainCtrlPos / (double)MainCtrlPosNo; + if (EIMCtrlAdditionalZeros || EIMCtrlEmergency) + { + if (eimic > 0.001) + eimic = std::max(0.002, eimic * (double)MainCtrlPosNo / ((double)MainCtrlPosNo - offset) - offset / ((double)MainCtrlPosNo - offset)); + if (eimic < -0.001 && BrakeHandle != TBrakeHandle::MHZ_EN57) + eimic = std::min(-0.002, eimic * (double)LocalBrakePosNo / ((double)LocalBrakePosNo - multiplier) + offset / ((double)LocalBrakePosNo - multiplier)); + } + if (eimic > 0.001 && SpeedCtrlUnit.IsActive) + eimic = std::max(eimic, SpeedCtrlUnit.MinPower); +} + +// EIMCtrlType 1: the positions B+ to TMax move the value at a steady pace +void TMoverParameters::EIMICFromSteps(double dt) +{ + switch (MainCtrlPos) + { + case 0: // B+ + eimic -= std::clamp(1.0 + eimic, 0.0, dt * 0.14); // odejmuj do -1 + break; + case 1: // B + eimic -= std::clamp(0.0 + eimic, 0.0, dt * 0.14); // odejmuj do 0 + break; + case 2: // B- + case 3: // 0 + case 4: // T- + eimic -= std::clamp(0.0 + eimic, 0.0, dt * 0.14); // odejmuj do 0 + eimic += std::clamp(0.0 - eimic, 0.0, dt * 0.14); // dodawaj do 0 + break; + case 5: // T + eimic += std::clamp(0.0 - eimic, 0.0, dt * 0.14); // dodawaj do 0 + break; + case 6: // T+ + eimic += std::clamp(1.0 - eimic, 0.0, dt * 0.14); // dodawaj do 1 + break; + case 7: // TMax + eimic += std::clamp(1.0 - eimic, 0.0, dt * 0.14); // dodawaj do 1, max + break; + default: + break; + } + if (MainCtrlPos >= 3 && eimic < 0) + eimic = 0; + if (MainCtrlPos <= 3 && eimic > 0) + eimic = 0; +} + +// EIMCtrlType 2: the positions 0 to 4 move the value towards -1, 0 or 1, from the controller's delay on; the +// emergency brake position below them, where the controller has one, brakes in full at once +void TMoverParameters::EIMICFromFourPositions(double dt) +{ + if (IsMainCtrlEmergencyPos()) + { + // hamowanie nagle: pelne hamowanie od razu, przewod glowny oproznia UpdatePipePressure() + eimic = -1.0; + } + else if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) + { + double delta = MainCtrlActualPos == MainCtrlPos ? dt * CtrlDelay : 0.01; + // the positions below are those of the controller without the emergency brake position + switch (MainCtrlPos - EIMCtrlEmergencyPositions()) + { + case 0: + case 1: + eimic -= safe_clamp(1.0 + eimic, 0.0, delta); // odejmuj do -1 + if (eimic > 0) + eimic = 0; + break; + case 2: + eimic -= safe_clamp(0.0 + eimic, 0.0, delta); // odejmuj do 0 + break; + case 3: + eimic += safe_clamp(0.0 - eimic, 0.0, delta); // dodawaj do 0 + break; + case 4: + eimic += safe_clamp(1.0 - eimic, 0.0, delta); // dodawaj do 1 + if (eimic < 0) + eimic = 0; + break; + default: + break; + } + } + if (MainCtrlActualPos == MainCtrlPos) + LastRelayTime += dt; + else + { + LastRelayTime = 0; + MainCtrlActualPos = MainCtrlPos; + } +} + +// EIMCtrlType 3: the universal controller of UniCtrlList, with the train brake built in or not +void TMoverParameters::EIMICFromUniversalController(double dt, double const brakeDemand) +{ + if (UniCtrlIntegratedBrakePNCtrl) + { + UniversalControllerTrainBrake(); + } + + if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) + { + auto const &position{UniCtrlList[MainCtrlPos]}; + double ramped{eimic}; + ramped -= safe_clamp(-position.SetCtrlVal + ramped, 0.0, + MainCtrlActualPos == MainCtrlPos ? dt * position.SpeedDown : sign(position.SpeedDown) * 0.01); // odejmuj do X + ramped += safe_clamp(position.SetCtrlVal - ramped, 0.0, + MainCtrlActualPos == MainCtrlPos ? dt * position.SpeedUp : sign(position.SpeedUp) * 0.01); // dodawaj do X + ramped = safe_clamp(ramped, position.MinCtrlVal, position.MaxCtrlVal); + eimic = UniCtrlValStep > 0.0 ? stepped_uc_value(eimic, ramped, position, UniCtrlValStep, MainCtrlActualPos != MainCtrlPos, eimic_step_progress) : ramped; + } + if (MainCtrlActualPos == MainCtrlPos) + LastRelayTime += dt; + else + { + LastRelayTime = 0; + MainCtrlActualPos = MainCtrlPos; + } + if (Hamulec->GetEDBCP() > 0.3 && eimic < 0 && !UniCtrlIntegratedLocalBrakeCtrl) // when braking with pneumatic brake + eimic = 0; // shut off retarder + if (UniCtrlIntegratedBrakeCtrl == false && UniCtrlIntegratedLocalBrakeCtrl == false) + { + // w trybie SplitEDPneumaticBrake hamowanie ED przychodzi z osobnego nastawnika, + // LocalBrake operuje wylacznie pneumatycznym hamulcem lokomotywy + eimic = brakeDemand > 0.01 ? -brakeDemand : eimic; + } +} + +// the train brake built into the universal controller: the handle set to the controller's position, or the +// controller, at a brake handle moved alone, to the nearest position of the handle's +void TMoverParameters::UniversalControllerTrainBrake() +{ + if (UniCtrlList[MainCtrlPos].mode != BrakeCtrlPos && MainCtrlActualPos == MainCtrlPos) // there was no move of controller, but brake only + { + if (BrakeCtrlPos < UniCtrlList[MainCtrlPosNo].mode) + BrakeLevelSet(UniCtrlList[MainCtrlPosNo].mode); // bottom clamping + if (BrakeCtrlPos > UniCtrlList[0].mode) + BrakeLevelSet(UniCtrlList[0].mode); // top clamping + if (IsCabMaster()) + { + while (BrakeCtrlPos > UniCtrlList[MainCtrlPos].mode) + DecMainCtrl(1); // find nearest position + while (BrakeCtrlPos < UniCtrlList[MainCtrlPos].mode) + IncMainCtrl(1); // find nearest position + } + } + else // controller was moved + BrakeLevelSet(UniCtrlList[MainCtrlPos].mode); +} + +// the local brake of the TRAXX locomotives, by time: released, held or applied, which cuts the drive off +void TMoverParameters::EIMICTraxxLocalBrake(double dt) +{ + if (LocalBrakeRatio() < 0.4) // pozycja 0, odhamowywanie + { + eim_localbrake -= dt * 0.17; + } + + if (LocalBrakeRatio() > 0.6) // pozycja 2, zahamowywanie + { + eim_localbrake += dt * 0.17; + eim_localbrake = std::max(eim_localbrake, BrakePress / MaxBrakePress[0]); + } + else // pozycja 1, utrzymanie cisnienia + { + if (eim_localbrake < Hamulec->GetEDBCP() / MaxBrakePress[0]) + eim_localbrake = 0; + } + eim_localbrake = std::clamp(eim_localbrake, 0.0, 1.0); + if (eim_localbrake > 0.04 && eimic > 0) + eimic = 0; +} + +// the value limited by the power, the spring brake, the pipe lock, the direction and the doors' permits +void TMoverParameters::EIMICLimit() +{ + auto const eimicpowerenabled{(MainCircuitPowered() || Power == 0.0) && (!SpringBrake.IsActive || !SpringBrakeCutsOffDrive) && !LockPipe && DirAbsolute != 0}; + auto const eimicdoorenabled{(SpringBrake.IsActive && ReleaseParkingBySpringBrakeWhenDoorIsOpen)}; + double eimic_max = 0.0; + if (Doors.instances[side::left].open_permit == false && Doors.instances[side::right].open_permit == false) + { + if (eimicpowerenabled) + { + eimic_max = 1.0; + } + else + { + eimic_max = 0.001; + } + } + else + { + if (eimicdoorenabled) + { + eimic_max = 0.001; + } + } + eimic = safe_clamp(eimic, -1.0, eimicpowerenabled ? eimic_max : 0.0); +} + +void TMoverParameters::CheckSpeedCtrl(double dt) +{ + if (EIMCtrlType == 0) + { + SpeedCtrlUnit.DesiredPower = std::max(eimic, 0.0); + } + double accfactor = SpeedCtrlUnit.DesiredPower; + if (EIMCtrlType >= 2) + { + if (MainCtrlPos < MainCtrlPosNo - 2) + { + SpeedCtrlUnit.Standby = true; + } + if (MainCtrlPos > MainCtrlPosNo - 1) + { + SpeedCtrlUnit.Standby = false; + } + if (!SpeedCtrlUnit.BrakeIntervention && (Hamulec->GetEDBCP() > 0.4 || PipePress < HighPipePress - 0.2)) + SpeedCtrlUnit.Standby = true; + if (EIMCtrlType >= 3 && UniCtrlList[MainCtrlPos].SpeedUp <= 0) + { + accfactor = 0.0; + eimicSpeedCtrl = 0; + } + } + if (SpeedCtrlUnit.IsActive) + { // speed control + if (true) + { + if (!SpeedCtrlUnit.Standby) + { + SpeedCtrlRegulator(dt, accfactor); + } + else + { + eimicSpeedCtrl = 0; + eimicSpeedCtrlIntegral = 0; + } + SpeedCtrlUnit.Parking = Vel == 0.0 && eimic <= 0 && EngineType != TEngineType::ElectricInductionMotor; + SendCtrlToNext("SpeedCtrlUnit.Parking", SpeedCtrlUnit.Parking, CabActive); + } + else + { + if (Vmax < 250) + eimicSpeedCtrl = std::clamp(0.5 * (SpeedCtrlValue - Vel), -1.0, 1.0); + else + eimicSpeedCtrl = std::clamp(0.5 * (SpeedCtrlValue * 2 - Vel), -1.0, 1.0); + } + if ((SpeedCtrlAutoTurnOffFlag & 2) == 2 && Hamulec->GetEDBCP() > 0.25) + { + SpeedCtrlSwitch(false); + SpeedCtrlUnit.IsActive = false; + } + } + else + { + eimicSpeedCtrl = 1; + eimicSpeedCtrlIntegral = 0; + SpeedCtrlUnit.Parking = false; + SendCtrlToNext("SpeedCtrlUnit.Parking", SpeedCtrlUnit.Parking, CabActive); + } +} + +// the PI regulator of the speed control: the power asked of the drive, or its brake intervention, from the error of +// the speed; accfactor, the most power it may ask +void TMoverParameters::SpeedCtrlRegulator(double dt, double const accfactor) +{ + if (SpeedCtrlUnit.ManualStateOverride && eimic > 0.0009) + eimic = 1.0; + double error = std::max(SpeedCtrlValue + SpeedCtrlUnit.Offset, 0.0) - Vel; + double factorP = error > 0 ? SpeedCtrlUnit.FactorPpos : SpeedCtrlUnit.FactorPneg; + double eSCP = std::clamp(factorP * error, -1.2, 1.0); // P module + bool retarder_not_work = EngineType != TEngineType::DieselEngine || Vel < SpeedCtrlUnit.BrakeInterventionVel; + if (eSCP < -1.0) + { + SpeedCtrlUnit.BrakeInterventionBraking = eSCP < -1.1 && retarder_not_work && eimicSpeedCtrl < -0.99 * SpeedCtrlUnit.DesiredPower; + eSCP = -1.0; + } + SpeedCtrlUnit.BrakeInterventionUnbraking = eSCP > 0.0 || Vel == 0.0; + if (abs(eSCP) < 0.999) + { + // TODO: check how to disable integral part when braking in smart way + // double factorI = eimicSpeedCtrlIntegral >= 0 ? SpeedCtrlUnit.FactorIpos : SpeedCtrlUnit.FactorIneg; + double factorI = eimicSpeedCtrlIntegral >= 0 ? SpeedCtrlUnit.FactorIpos : SpeedCtrlUnit.FactorIneg; + eimicSpeedCtrlIntegral = safe_clamp(eimicSpeedCtrlIntegral + factorI * eSCP * dt, -1.0 + eSCP, 1.0 - eSCP); + } + else + { + eimicSpeedCtrlIntegral = 0; + } + auto const DesiredeimicSpeedCtrl{safe_clamp(eimicSpeedCtrlIntegral + eSCP, -SpeedCtrlUnit.DesiredPower, accfactor)}; + eimicSpeedCtrl = safe_clamp(DesiredeimicSpeedCtrl, eimicSpeedCtrl - SpeedCtrlUnit.PowerDownSpeed * dt, eimicSpeedCtrl + SpeedCtrlUnit.PowerUpSpeed * dt); + if (Vel < SpeedCtrlUnit.FullPowerVelocity) + { + eimicSpeedCtrl = std::min(eimicSpeedCtrl, SpeedCtrlUnit.InitialPower); + } + if (Vel < SpeedCtrlUnit.StartVelocity && MainCtrlPos < MainCtrlPosNo) + { + eimicSpeedCtrl = 0; + eimic = 0; + } +} + +bool TMoverParameters::IsSpeedCtrlSeparate() const +{ + // no secondary controller, or one of these engines', which shunts the field of the traction motors (eu07/maszyna#69) + return SpeedCtrl && (ScndCtrlPosNo == 0 || EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric); +} + +bool TMoverParameters::IsSpeedCtrlEngaged() const +{ + return IsSpeedCtrlSeparate() ? SpeedCtrlUnit.IsActive : ScndCtrlPos > 0; +} + +bool TMoverParameters::SpeedCtrlSwitch(bool const State) +{ + if (false == IsSpeedCtrlSeparate()) + { + return State ? IncScndCtrl(1) : DecScndCtrl(2); + } + // its own switch, the secondary controller left to the field shunting + if (State) + { + if (CabActive == 0 || SpeedCtrlUnit.IsActive) + { + return false; + } + SpeedCtrlValue = static_cast(Round(Vel)); + SpeedCtrlUnit.IsActive = true; + return true; + } + auto const wasactive{SpeedCtrlUnit.IsActive}; + SpeedCtrlValue = 0; + SpeedCtrlUnit.IsActive = false; + if (wasactive && SpeedCtrlUnit.ManualStateOverride) + { + eimic = 0.0; + } + return wasactive; +} + +void TMoverParameters::SpeedCtrlButton(int button) +{ + if (SpeedCtrl && IsSpeedCtrlEngaged()) + { + SpeedCtrlValue = SpeedCtrlButtons[button]; + } +} + +void TMoverParameters::SpeedCtrlInc() +{ + if (SpeedCtrl && IsSpeedCtrlEngaged()) + { + double x = floor(SpeedCtrlValue / SpeedCtrlUnit.VelocityStep) + 1.0; + SpeedCtrlValue = std::min(x * SpeedCtrlUnit.VelocityStep, SpeedCtrlUnit.MaxVelocity); + } +} + +void TMoverParameters::SpeedCtrlDec() +{ + if (SpeedCtrl && IsSpeedCtrlEngaged()) + { + double x = ceil(SpeedCtrlValue / SpeedCtrlUnit.VelocityStep) - 1.0; + SpeedCtrlValue = std::max(x * SpeedCtrlUnit.VelocityStep, SpeedCtrlUnit.MinVelocity); + } +} + +bool TMoverParameters::SpeedCtrlPowerInc() +{ + if (!(SpeedCtrl && IsSpeedCtrlEngaged())) + return false; + + if (SpeedCtrlUnit.DesiredPower == SpeedCtrlUnit.MaxPower) + return false; + + SpeedCtrlUnit.DesiredPower = std::min(SpeedCtrlUnit.DesiredPower + SpeedCtrlUnit.PowerStep, SpeedCtrlUnit.MaxPower); + return true; +} + +bool TMoverParameters::SpeedCtrlPowerDec() +{ + if (!(SpeedCtrl && IsSpeedCtrlEngaged())) + return false; + + if (SpeedCtrlUnit.DesiredPower == SpeedCtrlUnit.MinPower) + return false; + + SpeedCtrlUnit.DesiredPower = std::max(SpeedCtrlUnit.DesiredPower - SpeedCtrlUnit.PowerStep, SpeedCtrlUnit.MinPower); + return true; +} diff --git a/physics/mover/couplers.cpp b/physics/mover/couplers.cpp new file mode 100644 index 000000000..06bf30481 --- /dev/null +++ b/physics/mover/couplers.cpp @@ -0,0 +1,578 @@ +/* +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/. +*/ + +// attaching and detaching, the forces in the couplers and the automatic coupling + +#include "stdafx.h" +#include "physics/mover.h" +#include "vehicle/DynObj.h" +#include "physics/oerlikonest.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/Timer.h" +#include "utilities/parser.h" +#include "simulation/simulation.h" +#include "vehicle/fieldshunting.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "physics/mover/internal.h" + +// Ra: tu należy przenosić funcje z mover.pas, które nie są z niego wywoływane. +// Jeśli jakieś zmienne nie są używane w mover.pas, też można je przenosić. +// Przeniesienie wszystkiego na raz zrobiło by zbyt wielki chaos do ogarnięcia. + +const double dEpsilon = 0.01; // 1cm (zależy od typu sprzęgu...) + +double TMoverParameters::Distance(const TLocation &Loc1, const TLocation &Loc2, const TDimension &Dim1, const TDimension &Dim2) +{ // zwraca odległość pomiędzy pojazdami (Loc1) i (Loc2) z uwzględnieneim ich długości (kule!) + return hypot(Loc2.X - Loc1.X, Loc1.Y - Loc2.Y) - 0.5 * (Dim2.L + Dim1.L); +}; + +double TMoverParameters::CouplerDist(TMoverParameters const *Left, TMoverParameters const *Right) +{ // obliczenie odległości pomiędzy sprzęgami (kula!) + return Distance(Left->Loc, Right->Loc, Left->Dim, Right->Dim); // odległość pomiędzy sprzęgami (kula!) +}; + +bool TMoverParameters::Attach(int ConnectNo, int ConnectToNr, TMoverParameters *ConnectTo, int CouplingType, bool Enforce, bool Audible) +{ // łączenie do swojego sprzęgu (ConnectNo) pojazdu (ConnectTo) stroną (ConnectToNr) + // Ra: zwykle wykonywane dwukrotnie, dla każdego pojazdu oddzielnie + // Ra: trzeba by odróżnić wymóg dociśnięcia od uszkodzenia sprzęgu przy podczepianiu AI do składu + + if (ConnectTo == nullptr || CouplingType == coupling::faux) + { + return false; + } + + auto &thiscoupler{Couplers[ConnectNo]}; + auto const otherend{ConnectToNr != 2 ? ConnectToNr : thiscoupler.ConnectedNr}; + auto &othercoupler = ConnectTo->Couplers[otherend]; + auto const distance{CouplerDist(this, ConnectTo) - (thiscoupler.adapter_length + othercoupler.adapter_length)}; + + + if (auto const couplercheck{Enforce || (distance <= dEpsilon && thiscoupler.type() != TCouplerType::NoCoupler && thiscoupler.type() == othercoupler.type())}; false == couplercheck) + { + return false; + } + + // no multiple-unit control between an electric and a diesel locomotive, whoever asks for it: the scenario, the AI + // or the player (eu07/maszyna#520) + if (auto const compatible{CompatibleCoupling(ConnectNo, *ConnectTo, otherend, CouplingType)}; compatible != CouplingType) + { + WriteLog(std::format("Vehicles \"{}\" and \"{}\" can't share their control, coupled without the control connection", Name, ConnectTo->Name)); + CouplingType = compatible; + if (CouplingType == coupling::faux) + { + return false; + } + } + + // stykaja sie zderzaki i kompatybilne typy sprzegow, chyba że łączenie na starcie + if (thiscoupler.CouplingFlag == coupling::faux) + { + // a new coupling: the play of the coupling as set up anew, without the stretch of the one before + thiscoupler.physics_state.couple(); + othercoupler.physics_state.couple(); + // jeśli wcześniej nie było połączone, ustalenie z której strony rysować sprzęg + thiscoupler.Render = true; // tego rysować + othercoupler.Render = false; // a tego nie + } + auto const couplingchange{CouplingType ^ thiscoupler.CouplingFlag}; + thiscoupler.Connected = ConnectTo; + thiscoupler.CouplingFlag = CouplingType; // ustawienie typu sprzęgu + if (ConnectToNr != 2) + { + thiscoupler.ConnectedNr = ConnectToNr; // 2=nic nie podłączone + } + othercoupler.Connected = this; + othercoupler.CouplingFlag = CouplingType; + othercoupler.ConnectedNr = ConnectNo; + + if (true == Audible && couplingchange != 0) + { + // set sound event flag + int soundflag{sound::none}; + std::vector> const soundmappings = {{coupling::coupler, sound::attachcoupler}, {coupling::brakehose, sound::attachbrakehose}, + {coupling::mainhose, sound::attachmainhose}, {coupling::control, sound::attachcontrol}, + {coupling::gangway, sound::attachgangway}, {coupling::heating, sound::attachheating}}; + for (auto const &[mappingcoupling, mappingsound] : soundmappings) + { + if ((couplingchange & mappingcoupling) != 0) + { + soundflag |= mappingsound; + } + } + SetFlag(thiscoupler.sounds, soundflag); + } + + return true; +} + +int TMoverParameters::DettachStatus(int ConnectNo) +{ // Ra: sprawdzenie, czy odległość jest dobra do rozłączania + // powinny być 3 informacje: =0 sprzęg już rozłączony, <0 da się rozłączyć. >0 nie da się rozłączyć + if (!Couplers[ConnectNo].Connected) + return 0; // nie ma nic, to rozłączanie jest OK + if ((Couplers[ConnectNo].CouplingFlag & ctrain_coupler) == 0) + return -Couplers[ConnectNo].CouplingFlag; // hak nie połączony - rozłączanie jest OK + if (TestFlag(DamageFlag, dtrain_coupling)) + return -Couplers[ConnectNo].CouplingFlag; // hak urwany - rozłączanie jest OK + // CouplerDist(ConnectNo); + if (Couplers[ConnectNo].type() != TCouplerType::Screw || Neighbours[ConnectNo].distance < 0.01) + return -Couplers[ConnectNo].CouplingFlag; // można rozłączać, jeśli dociśnięty + return Neighbours[ConnectNo].distance > 0.2 ? -Couplers[ConnectNo].CouplingFlag : Couplers[ConnectNo].CouplingFlag; +}; + +bool TMoverParameters::Dettach(int ConnectNo) +{ // rozlaczanie + + auto &thiscoupler{Couplers[ConnectNo]}; + auto &othervehicle{thiscoupler.Connected}; + auto &othercoupler{othervehicle->Couplers[thiscoupler.ConnectedNr]}; + + if (othervehicle == nullptr) + { + return true; + } // nie ma nic, to odczepiono + + auto couplingchange{thiscoupler.CouplingFlag}; // presume we'll uncouple all active flags + auto const couplingstate{DettachStatus(ConnectNo)}; // stan sprzęgu + if (couplingstate < 0) + { + // gdy scisniete zderzaki, chyba ze zerwany sprzeg (wirtualnego nie odpinamy z drugiej strony) + std::tie(othercoupler.Connected, othercoupler.ConnectedNr, othercoupler.CouplingFlag) = std::make_tuple(nullptr, -1, coupling::faux); + std::tie(thiscoupler.Connected, thiscoupler.ConnectedNr, thiscoupler.CouplingFlag) = std::make_tuple(nullptr, -1, coupling::faux); + } + else if (couplingstate > 0) + { // odłączamy węże i resztę, pozostaje sprzęg fizyczny, który wymaga dociśnięcia (z wirtualnym nic) + thiscoupler.CouplingFlag &= coupling::coupler; + othercoupler.CouplingFlag &= coupling::coupler; + } + // set sound event flag + couplingchange ^= thiscoupler.CouplingFlag; // remaining bits were removed from coupling + if (couplingchange != 0) + { + int soundflag{sound::detach}; // HACK: use detach flag to indicate removal of listed coupling + std::vector> const soundmappings = {{coupling::coupler, sound::attachcoupler}, {coupling::brakehose, sound::attachbrakehose}, + {coupling::mainhose, sound::attachmainhose}, {coupling::control, sound::attachcontrol}, + {coupling::gangway, sound::attachgangway}, {coupling::heating, sound::attachheating}}; + for (auto const &[mappingcoupling, mappingsound] : soundmappings) + { + if ((couplingchange & mappingcoupling) != 0) + { + soundflag |= mappingsound; + } + } + SetFlag(thiscoupler.sounds, soundflag); + } + + return couplingstate < 0; +}; + +// ************************************************************************************************* +// prędkość zbliżania się stykających się końców pojazdów przy zderzeniu, w km/h +// ************************************************************************************************* +double TMoverParameters::CollisionVelocity(int const End, TMoverParameters const &Other, int const OtherEnd) const +{ + auto const velocitydifference{CouplerVelocityDifference(End, Other, OtherEnd)}; + // the front end closes in on the other vehicle when this one moves forward faster, the rear end when it's slower + return (End == end::front ? velocitydifference : -velocitydifference) * 3.6; // m/s -> km/h +} + +double TMoverParameters::CouplerVelocityDifference(int const End, TMoverParameters const &Other, int const OtherEnd) const +{ + // V runs along the vehicle's own axis, towards its front; the other vehicle's velocity is turned around when the + // vehicles face each other (touch with the same ends) + return V - Other.V * DirPatch(End, OtherEnd); +} + +bool TMoverParameters::AutomaticCouplingSafe(int const End, TMoverParameters const &Other, int const OtherEnd) const +{ + return false == Global.crash_damage || CollisionVelocity(End, Other, OtherEnd) <= SafeCollisionVelocity; +} +namespace +{ + + +// the kind of traction a vehicle's engine stands for, as far as its multiple-unit control goes +enum class traction_kind +{ + none, + electric, + diesel +}; + +traction_kind traction_of(TEngineType const Engine) +{ + switch (Engine) + { + case TEngineType::ElectricSeriesMotor: + case TEngineType::ElectricInductionMotor: + return traction_kind::electric; + case TEngineType::DieselEngine: + case TEngineType::DieselElectric: + return traction_kind::diesel; + default: + return traction_kind::none; + } +} + +} // namespace + +bool TMoverParameters::ControlCouplingAllowed(int const End, TMoverParameters const &Other, int const OtherEnd) const +{ + if (false == Global.control_coupling_engine_check) + { + return true; + } + // the same control system named on both couplers is the vehicle authors' word that they work together + if (auto const &controltype{Couplers[End].control_type}; false == controltype.empty() && controltype == Other.Couplers[OtherEnd].control_type) + { + return true; + } + auto const traction{traction_of(EngineType)}; + auto const othertraction{traction_of(Other.EngineType)}; + return traction == traction_kind::none || othertraction == traction_kind::none || traction == othertraction; +} + +int TMoverParameters::CompatibleCoupling(int const End, TMoverParameters const &Other, int const OtherEnd, int const CouplingType) const +{ + if ((CouplingType & coupling::control) == 0 || (CouplingType & coupling::permanent) != 0 || ControlCouplingAllowed(End, Other, OtherEnd)) + { + return CouplingType; + } + return CouplingType & ~coupling::control; +} + +// ************************************************************************************************* +// Q: 20160713 +// Obliczanie sił dzialających na sprzęgach +// ************************************************************************************************* +double TMoverParameters::CouplerForce(int const End, double dt) +{ + if (coupler_physics_at(End)) + { + return coupler_force_physical(End, dt); + } + + auto &thiscoupler{Couplers[End]}; + auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; + auto const otherend{Neighbours[End].vehicle_end}; + auto const &othercoupler{othervehicle->Couplers[otherend]}; + + auto const othervehiclemove{(othervehicle->dMoveLen * DirPatch(End, otherend))}; + auto const initialdistance{Neighbours[End].distance}; // odległość od sprzęgu sąsiada + auto const distancedelta{(End == end::front ? othervehiclemove - dMoveLen : dMoveLen - othervehiclemove)}; + + // the ends crushed for good (physics.collisions new, see collision.h) let the buffers meet that much closer + auto const crushed{thiscoupler.crush + othercoupler.crush}; + auto const rawdistance{initialdistance + 10.0 * distancedelta}; + auto const newdistance{rawdistance < 0.0 ? std::min(0.0, rawdistance + crushed) : rawdistance}; + + auto const dV{CouplerVelocityDifference(End, *othervehicle, otherend)}; + auto const absdV{std::abs(dV)}; + + // potentially generate sounds on clash or stretch + if (newdistance < 0.0 && thiscoupler.Dist > newdistance && dV < -0.1 && false == thiscoupler.has_adapter()) + { // HACK: with adapter present we presume buffers won't clash + // 090503: dzwieki pracy zderzakow + SetFlag(thiscoupler.sounds, absdV > 5.0 ? sound::bufferclash | sound::loud : sound::bufferclash); + } + else if (thiscoupler.CouplingFlag != coupling::faux && newdistance > 0.001 && thiscoupler.Dist <= 0.001 && absdV > 0.005 && Vel > 1.0) + { + // 090503: dzwieki pracy sprzegu + SetFlag(thiscoupler.sounds, absdV > 0.035 ? sound::couplerstretch | sound::loud : sound::couplerstretch); + } + + thiscoupler.CheckCollision = false; + thiscoupler.Dist = 0.0; + + double CF{0.0}; + + if (thiscoupler.CouplingFlag == coupling::faux && initialdistance > 0.05) + { // arbitrary distance + // potentially reset auto coupling lock + thiscoupler.AutomaticCouplingAllowed = true; + } + + if (thiscoupler.CouplingFlag != coupling::faux || initialdistance < 0) + { + + thiscoupler.Dist = safe_clamp(newdistance, thiscoupler.has_adapter() ? 0 : -thiscoupler.DmaxB, thiscoupler.DmaxC); + + double BetaAvg = 0; + double Fmax = 0; + + if (thiscoupler.CouplingFlag == coupling::faux) + { + + BetaAvg = thiscoupler.beta; + Fmax = (thiscoupler.FmaxC + thiscoupler.FmaxB) * CouplerTune; + } + else + { + // usrednij bo wspolny sprzeg + BetaAvg = 0.5 * (thiscoupler.beta + othercoupler.beta); + Fmax = 0.5 * (thiscoupler.FmaxC + thiscoupler.FmaxB + othercoupler.FmaxC + othercoupler.FmaxB) * CouplerTune; + } + auto const distDelta{std::abs(newdistance) - std::abs(thiscoupler.Dist)}; // McZapkie-191103: poprawka na histereze + + if (newdistance > 0) + { + + if (distDelta > 0) + { + CF = -(thiscoupler.SpringKC + othercoupler.SpringKC) * thiscoupler.Dist / 2.0 * DirF(End) - Fmax * dV * BetaAvg; + } + else + { + CF = -(thiscoupler.SpringKC + othercoupler.SpringKC) * thiscoupler.Dist / 2.0 * DirF(End) * BetaAvg - Fmax * dV * BetaAvg; + } + // liczenie sily ze sprezystosci sprzegu + if (newdistance > thiscoupler.DmaxC + othercoupler.DmaxC) + { + // zderzenie + thiscoupler.CheckCollision = true; + } + CouplerStretchCheck(End, CF, dt); + } + if (newdistance < 0) + { + + if (distDelta > 0) + { + CF = -(thiscoupler.SpringKB + othercoupler.SpringKB) * thiscoupler.Dist / 2.0 * DirF(End) - Fmax * dV * BetaAvg; + } + else + { + CF = -(thiscoupler.SpringKB + othercoupler.SpringKB) * thiscoupler.Dist / 2.0 * DirF(End) * BetaAvg - Fmax * dV * BetaAvg; + } + // liczenie sily ze sprezystosci zderzaka + auto const collisiondistance{(thiscoupler.has_adapter() || othercoupler.has_adapter() ? + std::min(thiscoupler.DmaxB, othercoupler.DmaxB) : // HACK: only take into account buffering ability of automatic coupler + thiscoupler.DmaxB + othercoupler.DmaxB)}; + if (-newdistance > collisiondistance) + { + // zderzenie + thiscoupler.CheckCollision = true; + } + if (-newdistance >= std::min(collisiondistance, dEpsilon)) + { + automatic_coupling(End, *othervehicle, otherend); + } + } + } + + if (thiscoupler.CouplingFlag != coupling::faux) + { + // uzgadnianie prawa Newtona, on the coupler of the other vehicle this one is coupled with, along that vehicle's + // axis: turned around once more when the vehicles face each other + othervehicle->Couplers[otherend].CForce = -CF * DirPatch(End, otherend); + } + + return CF; +} + +// a coupler stretched with more than its strength for over a second breaks, the more likely the longer, with crash damage on +void TMoverParameters::CouplerStretchCheck(int const End, double const CF, double dt) +{ + auto &thiscoupler{Couplers[End]}; + if (std::abs(CF) > thiscoupler.FmaxC) + { + // coupler is stretched with excessive force, may break + thiscoupler.stretch_duration += static_cast(dt); + // give coupler 1 sec of leeway to account for simulation glitches, before checking whether it breaks + // (arbitrary) chance to break grows from 10-100% over 10 sec period + if (Global.crash_damage && thiscoupler.stretch_duration > 1.f && Random() < thiscoupler.stretch_duration * 0.1f * dt) + { + damage_coupler(End); + } + } + else + { + thiscoupler.stretch_duration = 0.f; + } +} + +bool TMoverParameters::coupler_physics_at(int const End) const +{ + if (false == Global.coupler_physics) + { + return false; + } + if (Global.coupler_physics_all || CouplerPhysics) + { + return true; + } + // either vehicle of the pair covered takes the pair in, so both of them compute it the same way + auto const *other{Neighbours[End].vehicle}; + return other != nullptr && other->MoverParameters->CouplerPhysics; +} + +void TMoverParameters::automatic_coupling(int const End, TMoverParameters &Other, int const OtherEnd) +{ + auto &thiscoupler{Couplers[End]}; + auto &othercoupler{Other.Couplers[OtherEnd]}; + + if (thiscoupler.type() != TCouplerType::Automatic || thiscoupler.type() != othercoupler.type() || thiscoupler.CouplingFlag != coupling::faux || false == thiscoupler.AutomaticCouplingAllowed || + false == othercoupler.AutomaticCouplingAllowed) + { + return; + } + // a coupler torn off by the crush of its end (physics.collisions new) doesn't catch + if (Global.collisions == global_settings::collision_model::physical && (thiscoupler.broken || othercoupler.broken)) + { + return; + } + // sprzeganie wagonow z samoczynnymi sprzegami + auto couplingtype{thiscoupler.AutomaticCouplingFlag & othercoupler.AutomaticCouplingFlag}; + // potentially exclude incompatible control coupling + if (thiscoupler.control_type != othercoupler.control_type) + { + couplingtype &= ~coupling::control; + } + couplingtype = CompatibleCoupling(End, Other, OtherEnd, couplingtype); + + // too fast for the couplers to catch, the vehicles collide instead (and may derail, see CollisionDetect()) + auto const safe{AutomaticCouplingSafe(End, Other, OtherEnd)}; + auto const caught{safe && Attach(End, OtherEnd, &Other, couplingtype)}; + // HACK: we're reusing sound enum to mark whether vehicle was connected to another + AIFlag |= (caught ? sound::attachcoupler : 0); + // coupled, or locked until the vehicles part, so they don't couple as soon as the collision slows them down + thiscoupler.AutomaticCouplingAllowed = safe && false == caught; + othercoupler.AutomaticCouplingAllowed = safe && false == caught; +} +namespace +{ + + +// the gap between the ends of a coupled pair, taking up the play of the coupling, opens up enough to jerk the train +constexpr double coupler_stretch_threshold{0.001}; + +// the sounds of the buffers hitting each other, and of the coupling taking up its play +struct coupler_sound_input +{ + double gap{0.0}; // between the ends [m] + double previous_gap{0.0}; + double gap_rate{0.0}; // [m/s] + double draw_gear{0.0}; // deflection [m] + double previous_draw_gear{0.0}; + bool coupled{false}; + bool adapter{false}; + bool moving{false}; +}; + +int coupler_sounds(coupler_sound_input const &Input) +{ + if (Input.gap < 0.0 && Input.gap < Input.previous_gap && Input.gap_rate < -0.1 && false == Input.adapter) + { + // 090503: dzwieki pracy zderzakow + return std::abs(Input.gap_rate) > 5.0 ? sound::bufferclash | sound::loud : sound::bufferclash; + } + if (Input.coupled && Input.moving && Input.draw_gear > coupler_stretch_threshold && Input.previous_draw_gear <= coupler_stretch_threshold && std::abs(Input.gap_rate) > 0.005) + { + // 090503: dzwieki pracy sprzegu + return std::abs(Input.gap_rate) > 0.035 ? sound::couplerstretch | sound::loud : sound::couplerstretch; + } + return sound::none; +} + +} // namespace + +double TMoverParameters::coupler_force_physical(int const End, double const dt) +{ + auto &thiscoupler{Couplers[End]}; + auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; + auto const otherend{Neighbours[End].vehicle_end}; + auto &othercoupler{othervehicle->Couplers[otherend]}; + auto &state{thiscoupler.physics_state}; + + // the gap as it is now: the distance found at the start of the frame, and the movement of both vehicles since + auto const othervehiclemove{othervehicle->dMoveLen * DirPatch(End, otherend)}; + auto const gap{Neighbours[End].distance + (End == end::front ? othervehiclemove - dMoveLen : dMoveLen - othervehiclemove)}; + // the gap opens up when the front end falls behind the vehicle ahead of it, or the rear end runs ahead of the one behind + auto const gaprate{CouplerVelocityDifference(End, *othervehicle, otherend) * DirF(End)}; + auto const coupled{thiscoupler.CouplingFlag != coupling::faux}; + auto const adapter{thiscoupler.has_adapter() || othercoupler.has_adapter()}; + + if (false == coupled && Neighbours[End].distance > 0.05) + { // arbitrary distance + // potentially reset auto coupling lock + thiscoupler.AutomaticCouplingAllowed = true; + } + + auto const previousgap{state.gap}; + auto const previousdrawgear{state.draw_gear.deflection}; + auto const result{coupler_physics::update_pair(thiscoupler.physics, othercoupler.physics, state, {gap, gaprate, coupled, adapter, Global.crash_damage, thiscoupler.crush + othercoupler.crush})}; + + SetFlag(thiscoupler.sounds, coupler_sounds({gap, previousgap, gaprate, state.draw_gear.deflection, previousdrawgear, coupled, adapter, Vel > 1.0})); + + thiscoupler.CheckCollision = state.stop != 0; + // for the buffers drawn pressed in, see TDynamicObject: twice the deflection of the buffers of this end + thiscoupler.Dist = result.compression > 0.0 ? -2.0 * result.buffers_deflection : std::max(gap, 0.0); + // the link pulled past its yield force, which the AI drivers ease off on + thiscoupler.stretch_duration = result.overloaded ? thiscoupler.stretch_duration + static_cast(dt) : 0.f; + + if (result.broken) + { + damage_coupler(End); + } + if (false == coupled && gap < 0.0) + { + auto const collisiondistance{adapter ? std::min(thiscoupler.DmaxB, othercoupler.DmaxB) : thiscoupler.DmaxB + othercoupler.DmaxB}; + if (-gap >= std::min(collisiondistance, dEpsilon)) + { + automatic_coupling(End, *othervehicle, otherend); + } + } + + // tension pulls this vehicle towards the other one + auto const force{result.force * -DirF(End)}; + if (thiscoupler.CouplingFlag != coupling::faux) + { + // uzgadnianie prawa Newtona, as in CouplerForce() + othercoupler.CForce = -force * DirPatch(End, otherend); + } + return force; +} + +bool TMoverParameters::coupler_stop_hit(int const End, TMoverParameters &Other, int const OtherEnd) +{ + auto &thiscoupler{Couplers[End]}; + auto &othercoupler{Other.Couplers[OtherEnd]}; + auto &state{thiscoupler.physics_state}; + + // the draw gear went solid with the gap opening up, the buffers with it closing + auto const gaprate{CouplerVelocityDifference(End, Other, OtherEnd) * DirF(End)}; + auto const closing{state.stop > 0 ? gaprate : -gaprate}; + if (state.stop == 0 || closing <= 0.0) + { + // parting from the stop already, after the hit on the other vehicle's end + return false; + } + if (false == Global.crash_damage) + { + return true; + } + auto const hit{coupler_physics::impact(thiscoupler.physics, othercoupler.physics, state, closing, TotalMass, Other.TotalMass)}; + // the other vehicle keeps the state of the pair alike + othercoupler.physics_state.elongation = state.elongation; + // with physics.collisions new the crush of the ends past the buffers is crush_hit()'s + if (hit.broken || (hit.crushed && Global.collisions != global_settings::collision_model::physical)) + { + damage_coupler(End); + } + // a broken coupling lets the vehicles part + return false == hit.broken; +} diff --git a/physics/mover/diesel.cpp b/physics/mover/diesel.cpp new file mode 100644 index 000000000..49778945a --- /dev/null +++ b/physics/mover/diesel.cpp @@ -0,0 +1,1540 @@ +/* +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 diesel engine: its revolutions, the gearbox, the clutch, the hydraulic transmission, its heat and pumps + +#include "stdafx.h" +#include "physics/mover.h" +#include "vehicle/DynObj.h" +#include "physics/oerlikonest.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/Timer.h" +#include "utilities/parser.h" +#include "simulation/simulation.h" +#include "vehicle/fieldshunting.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "physics/mover/internal.h" + + +double TMoverParameters::EngineRPMRatio() const +{ + + return std::clamp(EngineType == TEngineType::DieselElectric ? 60.0 * std::abs(enrot) / DElist[MainCtrlPosNo].RPM : + EngineType == TEngineType::DieselEngine ? std::abs(enrot) / nmax : + 1.0, // shouldn't ever get here but, eh + 0.0, 1.0); +} + +double TMoverParameters::EngineIdleRPM() const +{ + + return EngineType == TEngineType::DieselEngine ? dizel_nmin * 60 : + EngineType == TEngineType::DieselElectric ? DElist[MainCtrlNoPowerPos()].RPM : + std::numeric_limits::max(); // shouldn't ever get here but, eh +} + +double TMoverParameters::EngineMaxRPM() const +{ + + return EngineType == TEngineType::DieselEngine ? dizel_nmax * 60 : + EngineType == TEngineType::DieselElectric ? DElist[MainCtrlPosNo].RPM : + std::numeric_limits::max(); // shouldn't ever get here but, eh +} + +// water pump status check +void TMoverParameters::WaterPumpCheck(double const /*Timestep*/) +{ + // NOTE: breaker override with start type is sm42 specific hack, replace with ability to define the presence of the breaker + WaterPump.is_active = true == (Power24vIsAvailable || Power110vIsAvailable) && true == WaterPump.breaker && false == WaterPump.is_disabled && + (true == WaterPump.is_active || true == WaterPump.is_enabled || WaterPump.start_type == start_t::battery); +} + +// water heater status check +void TMoverParameters::WaterHeaterCheck(double const /*Timestep*/) +{ + + WaterHeater.is_active = false == WaterHeater.is_damaged && true == (Power24vIsAvailable || Power110vIsAvailable) && true == WaterHeater.is_enabled && true == WaterHeater.breaker && + (WaterHeater.is_active || WaterHeater.config.temp_min < 0 || dizel_heat.temperatura1 < WaterHeater.config.temp_min); + + WaterHeater.is_damaged = true == WaterHeater.is_damaged || (true == WaterHeater.is_active && false == WaterPump.is_active); + + if (WaterHeater.config.temp_max > 0 && dizel_heat.temperatura1 > WaterHeater.config.temp_max) + { + WaterHeater.is_active = false; + } +} + +// fuel pump status update +void TMoverParameters::FuelPumpCheck(double const /*Timestep*/) +{ + using enum start_t; + + FuelPump.is_active = true == (Power24vIsAvailable || Power110vIsAvailable) && false == FuelPump.is_disabled && + (FuelPump.is_active || (FuelPump.start_type == manual ? FuelPump.is_enabled : + FuelPump.start_type == automatic ? dizel_startup || Mains : + FuelPump.start_type == manualwithautofallback ? FuelPump.is_enabled || dizel_startup || Mains : + false)); // shouldn't ever get this far but, eh +} + +// oil pump status update +void TMoverParameters::OilPumpCheck(double const Timestep) +{ + + OilPump.is_active = true == (Power24vIsAvailable || Power110vIsAvailable) && false == Mains && false == OilPump.is_disabled && + (OilPump.is_active || (OilPump.start_type == start_t::manual ? OilPump.is_enabled : + OilPump.start_type == start_t::automatic ? dizel_startup : + OilPump.start_type == start_t::manualwithautofallback ? OilPump.is_enabled || dizel_startup : + false)); // shouldn't ever get this far but, eh + + auto const minpressure{OilPump.pressure_minimum > 0.f ? OilPump.pressure_minimum : 0.15f}; // arbitrary fallback value + + OilPump.pressure_target = enrot > 0.1 ? std::lerp( minpressure, OilPump.pressure_maximum, static_cast( EngineRPMRatio() ) ) * OilPump.resource_amount : + true == OilPump.is_active ? std::min( minpressure + 0.1f, OilPump.pressure_maximum ) : // slight pressure margin to give time to switch off the pump and start the engine + 0.f; + + if (OilPump.pressure < OilPump.pressure_target) + { + // TODO: scale change rate from 0.01-0.05 with oil/engine temperature/idle time + OilPump.pressure = std::min(OilPump.pressure_target, static_cast(OilPump.pressure + (enrot > 5.0 ? 0.05 : 0.035) * Timestep)); + } + if (OilPump.pressure > OilPump.pressure_target) + { + OilPump.pressure = std::max(OilPump.pressure_target, static_cast(OilPump.pressure - (enrot > 5.0 ? 0.05 : 0.035) * 0.5 * Timestep)); + } + OilPump.pressure = std::clamp(OilPump.pressure, 0.f, 1.5f); +} + +// water pump breaker state toggle +bool TMoverParameters::WaterPumpBreakerSwitch(bool State, range_t const Notify) +{ + /* + if( FuelPump.start_type == start::automatic ) { + // automatic fuel pump ignores 'manual' state commands + return false; + } + */ + bool const initialstate{WaterPump.breaker}; + + WaterPump.breaker = State; + + if (Notify != range_t::local) + { + SendCtrlToNext("WaterPumpBreakerSwitch", WaterPump.breaker ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return WaterPump.breaker != initialstate; +} + +// water pump state toggle +bool TMoverParameters::WaterPumpSwitch(bool State, range_t const Notify) +{ + + if (WaterPump.start_type == start_t::battery) + { + // automatic fuel pump ignores 'manual' state commands + return false; + } + + bool const initialstate{WaterPump.is_enabled}; + + WaterPump.is_enabled = State; + + if (Notify != range_t::local) + { + SendCtrlToNext("WaterPumpSwitch", WaterPump.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return WaterPump.is_enabled != initialstate; +} + +// water pump state toggle +bool TMoverParameters::WaterPumpSwitchOff(bool State, range_t const Notify) +{ + + if (WaterPump.start_type == start_t::battery) + { + // automatic fuel pump ignores 'manual' state commands + return false; + } + + bool const initialstate{WaterPump.is_disabled}; + + WaterPump.is_disabled = State; + + if (Notify != range_t::local) + { + SendCtrlToNext("WaterPumpSwitchOff", WaterPump.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return WaterPump.is_disabled != initialstate; +} + +// water heater breaker state toggle +bool TMoverParameters::WaterHeaterBreakerSwitch(bool State, range_t const Notify) +{ + /* + if( FuelPump.start_type == start::automatic ) { + // automatic fuel pump ignores 'manual' state commands + return false; + } + */ + bool const initialstate{WaterHeater.breaker}; + + WaterHeater.breaker = State; + + if (Notify != range_t::local) + { + SendCtrlToNext("WaterHeaterBreakerSwitch", WaterHeater.breaker ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return WaterHeater.breaker != initialstate; +} + +// water heater state toggle +bool TMoverParameters::WaterHeaterSwitch(bool State, range_t const Notify) +{ + /* + if( FuelPump.start_type == start::automatic ) { + // automatic fuel pump ignores 'manual' state commands + return false; + } + */ + bool const initialstate{WaterHeater.is_enabled}; + + WaterHeater.is_enabled = State; + + if (Notify != range_t::local) + { + SendCtrlToNext("WaterHeaterSwitch", WaterHeater.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return WaterHeater.is_enabled != initialstate; +} + +// water circuits link state toggle +bool TMoverParameters::WaterCircuitsLinkSwitch(bool State, range_t const Notify) +{ + + if (false == dizel_heat.auxiliary_water_circuit) + { + // can't link the circuits if the vehicle only has one + return false; + } + + bool const initialstate{WaterCircuitsLink}; + + WaterCircuitsLink = State; + + if (Notify != range_t::local) + { + SendCtrlToNext("WaterCircuitsLinkSwitch", WaterCircuitsLink ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return WaterCircuitsLink != initialstate; +} + +// fuel pump state toggle +bool TMoverParameters::FuelPumpSwitch(bool State, range_t const Notify) +{ + + if (FuelPump.start_type == start_t::automatic) + { + // automatic fuel pump ignores 'manual' state commands + return false; + } + + bool const initialstate{FuelPump.is_enabled}; + + FuelPump.is_enabled = State; + + if (Notify != range_t::local) + { + SendCtrlToNext("FuelPumpSwitch", FuelPump.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return FuelPump.is_enabled != initialstate; +} + +bool TMoverParameters::FuelPumpSwitchOff(bool State, range_t const Notify) +{ + + if (FuelPump.start_type == start_t::automatic) + { + // automatic fuel pump ignores 'manual' state commands + return false; + } + + bool const initialstate{FuelPump.is_disabled}; + + FuelPump.is_disabled = State; + + if (Notify != range_t::local) + { + SendCtrlToNext("FuelPumpSwitchOff", FuelPump.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return FuelPump.is_disabled != initialstate; +} + +// oil pump state toggle +bool TMoverParameters::OilPumpSwitch(bool State, range_t const Notify) +{ + + if (OilPump.start_type == start_t::automatic) + { + // automatic pump ignores 'manual' state commands + return false; + } + + bool const initialstate{OilPump.is_enabled}; + + OilPump.is_enabled = State; + + if (Notify != range_t::local) + { + SendCtrlToNext("OilPumpSwitch", OilPump.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return OilPump.is_enabled != initialstate; +} + +bool TMoverParameters::OilPumpSwitchOff(bool State, range_t const Notify) +{ + + if (OilPump.start_type == start_t::automatic) + { + // automatic pump ignores 'manual' state commands + return false; + } + + bool const initialstate{OilPump.is_disabled}; + + OilPump.is_disabled = State; + + if (Notify != range_t::local) + { + SendCtrlToNext("OilPumpSwitchOff", OilPump.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return OilPump.is_disabled != initialstate; +} + +// the revolutions of the engine; returns those a diesel-electric engine aims at [1/s], 0 for the others. +// for a diesel engine, the ratio of the transmission and the engine's moment +double TMoverParameters::UpdateEngineRevolutions(double dt, double &dtrans, double &dmoment) +{ + double tmp{0.0}; + // youBy + switch (EngineType) + { + case TEngineType::DieselElectric: + { + if (true == Mains && true == FuelPump.is_active) + { + tmp = DieselElectricTargetRevolutions(); + } + else + { + tmp = 0.0; + dizel_fill = 0.0; + } + + if (enrot != tmp) + { + enrot = safe_clamp(enrot + dt / dizel_AIM * (enrot < tmp ? 1.0 : -1.0 * dizel_RevolutionsDecreaseRate), // NOTE: revolutions typically drop faster than they rise + 0.0, std::max(tmp, enrot)); + if (std::abs(tmp - enrot) < 0.001) + { + enrot = tmp; + } + } + break; + } + case TEngineType::DieselEngine: + { + if (ShuntMode) // dodatkowa przekładnia np. dla 2Ls150 + dtrans = AnPos * Transmision.Ratio * motor_param(ScndCtrlActualPos).mIsat; + else + dtrans = Transmision.Ratio * motor_param(ScndCtrlActualPos).mIsat; + + dmoment = dizel_Momentum(dizel_fill, dtrans * nrot * DirActive, dt); // oblicza tez enrot + break; + } + default: + { + enrot = Transmision.Ratio * nrot; + break; + } + } + + return tmp; +} + +// the revolutions a diesel-electric's engine aims at [1/s], by the controller and the heating; the fill shown by the smoke +double TMoverParameters::DieselElectricTargetRevolutions() +{ + double tmp; + + if (EIMCtrlType > 0) // sterowanie cyfrowe + tmp = (DElist[0].RPM + (DElist[MainCtrlPosNo].RPM - DElist[0].RPM) * std::max(0.0, eimic_real)) / 60.0; + else + tmp = DElist[ControlPressureSwitch ? MainCtrlNoPowerPos() : MainCtrlPos].RPM / 60.0; + + if (true == HeatingAllow && HeatingPower > 0 && EngineHeatingRPM > 0) + { + // bump engine revolutions up if needed, when heating is on + tmp = std::max(tmp, std::min(EngineMaxRPM(), EngineHeatingRPM) / 60.0); + } + // NOTE: fake dizel_fill calculation for the sake of smoke emitter which uses this parameter to determine smoke opacity + dizel_fill = std::clamp(0.2 + 0.35 * (tmp - enrot) + 0.5 * (std::abs(Im) / DElist[MainCtrlPosNo].Imax), 0.05, 1.0); + return tmp; +} + +void TMoverParameters::DieselEngineTractionForce(double dt, double const dmoment, double const dtrans) +{ + Mw = dmoment * dtrans * Transmision.Efficiency; // dmoment i dtrans policzone przy okazji enginerotation + if (hydro_R && hydro_R_Placement == 0) + Mw -= dizel_MomentumRetarder(nrot * Transmision.Ratio, dt) * Transmision.Ratio * Transmision.Efficiency; + Fw = Mw * 2.0 / WheelDiameter / NPoweredAxles; + Ft = Fw * NPoweredAxles; // sila trakcyjna + Ft = Ft * DirAbsolute; // DirActive*CabActive; +} + +// tmp: the revolutions the engine aims at [1/s], see UpdateEngineRevolutions() +void TMoverParameters::DieselElectricTractionForce(double tmp) +{ + double PosRatio; + // tmpV:=V*CabActive*DirActive; + auto const tmpV{nrot * Pirazy2 * 0.5 * WheelDiameter * DirAbsolute}; //*CabActive*DirActive; + auto tempUmax = 0.0; + auto tempImax = 0.0; + // jazda manewrowa + if (EIMCtrlType > 0) // sterowanie cyfrowe + { + tmp = DieselElectricDigitalForce(tmpV, tempUmax, tempImax); + PosRatio = tmp / DElist[MainCtrlPosNo].GenPower; + } + else if (true == ShuntMode) + { + DieselElectricShuntForce(tmpV, tmp); + PosRatio = 1; + } + else // jazda ciapongowa + { + auto power = Power; + tempImax = DElist[MainCtrlPos].Imax; + tempUmax = DElist[MainCtrlPos].Umax; + if (true == Heating) + { + power -= HeatingPower; + } + power = std::max(power, 0.0); + // NOTE: very crude way to approximate power generated at current rpm instead of instant top output + // NOTE, TODO: doesn't take into account potentially increased revolutions if heating is on, fix it + auto const currentgenpower{(DElist[MainCtrlPos].RPM > 0 ? DElist[MainCtrlPos].GenPower * (60.0 * enrot / DElist[MainCtrlPos].RPM) : 0.0)}; + + tmp = std::min(power, currentgenpower); + + PosRatio = currentgenpower / DElist[MainCtrlPosNo].GenPower; + // stosunek mocy teraz do mocy max + // NOTE: Mains in this context is working diesel engine + if (true == StLinFlag) + Ft = DieselElectricForce(tmpV, power, PosRatio, tmp); + else + Ft = 0; // jak nastawnik na zero, to sila tez zero + + PosRatio = tmp / DElist[MainCtrlPosNo].GenPower; + } + + if (FuseFlag) + Ft = 0; + else + Ft = Ft * DirAbsolute; // DirActive * CabActive; //zwrot sily i jej wartosc + Fw = Ft / NPoweredAxles; // sila na obwodzie kola + Mw = Fw * WheelDiameter / 2.0; // moment na osi kola + Mm = Mw / Transmision.Ratio; // moment silnika trakcyjnego + + Im = dieselelectric_motor_current(Mm); + + if (ShuntMode) + { + DieselElectricShuntPower(tmp); + } + else + { + DieselElectricGenerator(tmp, tempUmax, tempImax); + } + + if (Imax > 1 && Im > Imax) + FuseOff(); + if (FuseFlag) + EngineVoltage = 0; + + // przekazniki bocznikowania, kazdy inny dla kazdej pozycji + if (auto const fieldshuntingcontrol{fieldshunting::diesel_electric(AutoRelayType, FieldShuntSwitch, AutoRelayFlag)}; + false == StLinFlag || ShuntMode || fieldshuntingcontrol == fieldshunting::control::off) + { + ScndCtrlPos = 0; + } + else if (AutoRelayFlag) + { + // the shunting relays set the field shunting (fieldshunting::control::automatic) + ShuntFieldRelaysCheck(tmpV, PosRatio, tmp); + } +} + +// the tractive force of a diesel-electric shunting, by the generator's table SST and the shunting controller AnPos; +// tmp, the power the generator gives +void TMoverParameters::DieselElectricShuntForce(double const tmpV, double &tmp) +{ + if (true == StLinFlag) + { + EngineVoltage = SST[MainCtrlPos].Umax * AnPos + SST[MainCtrlPos].Umin * (1.0 - AnPos); + // NOTE: very crude way to approximate power generated at current rpm instead of instant top output + // NOTE, TODO: doesn't take into account potentially increased revolutions if heating is on, fix it + tmp = EngineRPMRatio() * (SST[MainCtrlPos].Pmax * AnPos) + SST[MainCtrlPos].Pmin * (1.0 - AnPos); + Ft = tmp * 1000.0 / (abs(tmpV) + 1.6); + } + else + { + EngineVoltage = 0; + Ft = 0; + } +} + +// the tractive force of a diesel-electric set by the integrated controller, at the speed tmpV; the generator's +// voltage and current limits too. returns the power the generator gives +double TMoverParameters::DieselElectricDigitalForce(double const tmpV, double &tempUmax, double &tempImax) +{ + auto eimic_positive = std::max(0.0, eimic_real); + auto const rpmratio{EngineRPMRatio()}; + tempImax = DElist[MainCtrlPosNo].Imax * eimic_positive; + tempUmax = DElist[MainCtrlPosNo].Umax * std::min(eimic_positive, rpmratio); + auto const tempPmax = DElist[MainCtrlPosNo].GenPower * std::min(eimic_positive, rpmratio); + if (true == StLinFlag) + Ft = DieselElectricForce(tmpV, tempPmax, eimic_positive, tempPmax); + else + Ft = 0; // jak nastawnik na zero, to sila tez zero + return tempPmax; +} + +// the tractive force of a diesel-electric at the speed tmpV: on the straight part of its characteristic under the speed +// Vhyp gives at the power LinePower, at the share Ratio of it, on the hyperbola of the power HyperbolaPower over it +double TMoverParameters::DieselElectricForce(double const tmpV, double const LinePower, double const Ratio, double const HyperbolaPower) const +{ + if (tmpV < Vhyp * LinePower / DElist[MainCtrlPosNo].GenPower) + { + // czy na czesci prostej, czy na hiperboli + return (Ftmax - (Ftmax - 1000.0 * DElist[MainCtrlPosNo].GenPower / (Vhyp + Vadd)) * (tmpV / Vhyp) / PowerCorRatio) * Ratio; // posratio - bo sila jakos tam sie rozklada + } + // na hiperboli + // 1.107 - wspolczynnik sredniej nadwyzki Ft w symku nad charakterystyka + return 1000.0 * HyperbolaPower / (tmpV + Vadd) / PowerCorRatio; // tu jest zawarty stosunek mocy +} + +// in the shunting mode, the generator's power limited to tmp, the power the engine gives +void TMoverParameters::DieselElectricShuntPower(double const tmp) +{ + EnginePower = EngineVoltage * Im / 1000.0; + if (EnginePower > tmp) + { + EnginePower = tmp; + EngineVoltage = EnginePower * 1000.0 / Im; + } + if (EnginePower < tmp) + { + Ft *= EnginePower / tmp; + } +} + +// the generator's current limited to tempImax and its voltage by its characteristic, under tempUmax and the power tmp +void TMoverParameters::DieselElectricGenerator(double const tmp, double const tempUmax, double const tempImax) +{ + if (abs(Im) > tempImax) + { // nie ma nadmiarowego, tylko Imax i zwarcie na pradnicy + Ft = Ft / Im * tempImax; + Im = tempImax; + } + + if (Im > 0) + { + // jak pod obciazeniem + if (true == Flat) + { + // ograniczenie napiecia w pradnicy - plaszczak u gory + EngineVoltage = 1000.0 * tmp / std::abs(Im); + } + else + { + auto tempMCP = EIMCtrlType > 0 ? 1 + 99 * std::max(1.0, eimic_real) : MainCtrlPos; + auto tempMCPN = EIMCtrlType > 0 ? 100 : MainCtrlPosNo; + // charakterystyka pradnicy obcowzbudnej (elipsa) - twierdzenie Pitagorasa + EngineVoltage = std::sqrt(std::abs(square(tempUmax) - square(tempUmax * Im / tempImax))) * (tempMCP - 1) + (1.0 - Im / tempImax) * tempUmax * (tempMCPN - tempMCP); + EngineVoltage /= tempMCPN - 1; + EngineVoltage = safe_clamp(EngineVoltage, Im * 0.05, 1000.0 * tmp / std::abs(Im)); + } + } + + if (EngineVoltage > tempUmax || Im == 0) + { + // gdy wychodzi za duze napiecie albo przy biegu jalowym (jest cos takiego?) + EngineVoltage = tempUmax * (ConverterFlag ? 1 : 0); + } + + EnginePower = EngineVoltage * Im / 1000.0; + /* + // power curve drop + // NOTE: disabled for the time being due to side-effects + if( ( tmpV > 1 ) && ( EnginePower < tmp ) ) { + Ft = std::lerp( + Ft, EnginePower / tmp, + std::clamp( tmpV - 1.0, 0.0, 1.0 ) ); + } + */ +} + +// the current of a diesel-electric vehicle's traction motors giving the moment [N m] of one motor +double TMoverParameters::dieselelectric_motor_current(double const Moment) const +{ + // with MotorParam[ScndCtrlPos] do + if (abs(Moment) > motor_param(ScndCtrlPos).fi) + return NPoweredAxles * abs(abs(Moment) / motor_param(ScndCtrlPos).mfi + motor_param(ScndCtrlPos).mIsat); + else + return NPoweredAxles * sqrt(abs(Moment * motor_param(ScndCtrlPos).Isat)); +} + +// the effort of a diesel-electric vehicle's dynamic brake the driver asks for, 0..1 +double TMoverParameters::dieselelectric_dynamic_brake_demand() const +{ + switch (DEDynamicBrake.source) + { + case diesel_electric_dynamic_brake::control::controller: + return std::clamp(-eimic_real, 0.0, 1.0); + case diesel_electric_dynamic_brake::control::lever: + return DynamicBrakeRatio(); + default: + return 0.0; + } +} + +// the force [N] of a diesel-electric vehicle's dynamic brake at full effort at the speed: the most the motors take +// (the current), above the speed where the resistors' power takes over, the power; under EDBrakeV1 it fades, down to +// nothing at EDBrakeV0. a brake of direct current motors, whose force grows with the speed (the voltage they generate +// into the resistors), fades from 0 to the speed of its whole force; an inverter's only at the stop +double TMoverParameters::dieselelectric_dynamic_brake_limit() const +{ + auto const &brake{DEDynamicBrake}; + auto limit{brake.max_force}; + if (brake.max_power > 0.0 && std::abs(V) > 0.0) + { + limit = std::min(limit, brake.max_power / std::abs(V)); + } + if (brake.fade_high > brake.fade_low) + { + limit *= std::clamp((Vel - brake.fade_low) / (brake.fade_high - brake.fade_low), 0.0, 1.0); + } + else if (Vel < brake.fade_low) + { + limit = 0.0; + } + return limit; +} + +// the dynamic brake of a diesel-electric vehicle, before the drive's force: the effort follows the demand, the force +// is the share of the most at the speed. the motors brake while the engine runs (it excites them, or keeps the +// control of the inverters going), with the direction set, the overload relay closed, no power asked for and the +// wheels rolling; otherwise there's no brake at once +void TMoverParameters::update_dieselelectric_dynamic_brake(double const dt) +{ + auto &brake{DEDynamicBrake}; + auto const nopower{brake.source == diesel_electric_dynamic_brake::control::controller ? eimic_real <= 0.0 : IsMainCtrlNoPowerPos()}; + if (Mains && DirActive != 0 && false == FuseFlag && false == SlippingWheels && nopower) + { + brake.level += std::clamp(dieselelectric_dynamic_brake_demand() - brake.level, -brake.rate * dt, brake.rate * dt); + } + else + { + brake.level = 0.0; + } + brake.force = brake.level * dieselelectric_dynamic_brake_limit(); + DynamicBrakeFlag = brake.force > 0.0; + if (brake.blending) + { + // the train brake of the locomotive lets off by the share of the dynamic brake's force (LSt, EStED) + Hamulec->SetED(brake.max_force > 0.0 ? brake.force / brake.max_force : 0.0); + } +} + +// the force of a diesel-electric vehicle's dynamic brake, against the motion, in place of the drive's one: the motors +// work as generators into the resistors, the ammeter shows their current, the main generator gives nothing. near the +// stop no more than what stops the vehicle within the step dt: with no fade (EDBrakeV0 = EDBrakeV1 = 0) the whole force +// would turn round each time the speed crosses zero, and in FTrain it never lets the stop of ComputeMovement() catch it +void TMoverParameters::apply_dieselelectric_dynamic_brake(double const dt) +{ + auto const force{dt > 0.0 ? std::min(DEDynamicBrake.force, TotalMass * std::abs(V) / dt) : DEDynamicBrake.force}; + Ft = V > 0.0 ? -force : V < 0.0 ? force : 0.0; + Fw = Ft / NPoweredAxles; + Mw = Fw * WheelDiameter / 2.0; + Mm = Mw / Transmision.Ratio; + Im = dieselelectric_motor_current(Mm); + EngineVoltage = 0.0; + EnginePower = 0.0; +} + +// ************************************************************************************************* +// Q: 20160715 +// Zmienia parametr do którego dąży sprzęgło +// ************************************************************************************************* +bool TMoverParameters::dizel_EngageSwitch(double state) +{ + if (EngineType == TEngineType::DieselEngine && state <= 1 && state >= 0 && state != dizel_engagestate) + { + dizel_engagestate = state; + return true; + } + else + return false; +} + +// ************************************************************************************************* +// Q: 20160715 +// Zmienia parametr do którego dąży sprzęgło +// ************************************************************************************************* +bool TMoverParameters::dizel_EngageChange(double dt) +{ + double engagespeed = 0; // OK:boolean; + bool DEC; + + DEC = false; + if (dizel_engage - dizel_engagestate > 0) + engagespeed = engagedownspeed; + else + engagespeed = engageupspeed; + if (dt > 0.2) + dt = 0.1; + if (abs(dizel_engage - dizel_engagestate) < 0.11) + { + if (dizel_engage != dizel_engagestate) + { + DEC = true; + dizel_engage = dizel_engagestate; + } + // else OK:=false; //już jest false + } + else + { + dizel_engage = dizel_engage + engagespeed * dt * (dizel_engagestate - dizel_engage); + // OK:=false; + } + // dizel_EngageChange:=OK; + return DEC; +} + +// ************************************************************************************************* +// Q: 20160715 +// Automatyczna zmiana biegów gdy prędkość przekroczy widełki +// ************************************************************************************************* +bool TMoverParameters::dizel_AutoGearCheck(void) +{ + auto OK{false}; + + auto const VelUp{(motor_param(ScndCtrlActualPos).mfi0 != 0.0 ? + motor_param(ScndCtrlActualPos).mfi0 + (motor_param(ScndCtrlActualPos).mfi - motor_param(ScndCtrlActualPos).mfi0) * std::max(0.0, eimic_real) : + motor_param(ScndCtrlActualPos).mfi)}; + + auto const VelDown{(motor_param(ScndCtrlActualPos).fi0 != 0.0 && eimic_real <= 0.0 ? motor_param(ScndCtrlActualPos).fi0 : motor_param(ScndCtrlActualPos).fi)}; + + if (motor_param(ScndCtrlActualPos).AutoSwitch && Mains) + { + OK = dizel_GearShiftCheck(VelUp, VelDown); + } + + if (Mains) + { + dizel_ClutchCheck(); + } + return OK; +} + +// the automatic gearbox: a gear up over VelUp, down under VelDown, changed once the clutch is out; returns whether it acted +bool TMoverParameters::dizel_GearShiftCheck(double const VelUp, double const VelDown) +{ + auto OK{false}; + if (RList[MainCtrlPos].Mn == 0 && !hydro_TC) + { + if (dizel_engagestate > 0) + dizel_EngageSwitch(0); + if (IsMainCtrlNoPowerPos() && ScndCtrlActualPos > 0) + dizel_automaticgearstatus = -1; + } + else + { + OK = dizel_GearShiftRequest(VelUp, VelDown); + } + if (dizel_engage < 0.1 && dizel_automaticgearstatus != 0) + { + if (dizel_automaticgearstatus == 1) + ScndCtrlActualPos++; + else + ScndCtrlActualPos--; + dizel_automaticgearstatus = 0; + dizel_EngageSwitch(1.0); + OK = true; + } + return OK; +} + +// a gear up asked over VelUp, down under VelDown, where the gearbox shifts by itself; returns whether one is +bool TMoverParameters::dizel_GearShiftRequest(double const VelUp, double const VelDown) +{ + auto OK{false}; + if (motor_param(ScndCtrlActualPos).AutoSwitch && dizel_automaticgearstatus == 0) // sprawdz czy zmienic biegi + { + if (Vel > VelUp) + { + // shift up + if (ScndCtrlActualPos < ScndCtrlPosNo) + { + dizel_automaticgearstatus = 1; + OK = true; + } + } + else if (Vel < VelDown) + { + // shift down + if (ScndCtrlActualPos > 0) + { + dizel_automaticgearstatus = -1; + OK = true; + } + } + } + return OK; +} + +// the pressure in the clutch's cylinder, by the controller's position or the integrated controller +void TMoverParameters::dizel_ClutchCheck() +{ + if (EIMCtrlType > 0) // sterowanie komputerowe + { + dizel_ClutchByIntegratedController(); + } + else if (dizel_automaticgearstatus == 0) // ustaw cisnienie w silowniku sprzegla} + dizel_ClutchByController(); + else + dizel_EngageSwitch(0.0); + if (!(motor_param(ScndCtrlActualPos).mIsat > 0)) + dizel_EngageSwitch(0.0); // wylacz sprzeglo na pozycjach neutralnych + if (!AutoRelayFlag) + ScndCtrlActualPos = ScndCtrlPos; +} + +// the clutch by the controller's position: half or fully in, fully over the speed of the full engagement +void TMoverParameters::dizel_ClutchByController() +{ + switch (RList[MainCtrlPos].Mn) + { + case 1: + dizel_EngageSwitch(0.5); + break; + case 2: + dizel_EngageSwitch(1.0); + break; + case 3: + if (Vel > dizel_minVelfullengage) + dizel_EngageSwitch(1.0); + else + dizel_EngageSwitch(0.5); + break; + case 4: + if (Vel > dizel_minVelfullengage) + dizel_EngageSwitch(1.0); + else + dizel_EngageSwitch(0.66); + break; + case 5: + if (Vel > dizel_minVelfullengage) + dizel_EngageSwitch(1.0); + else + dizel_EngageSwitch(0.35 * (1 + RList[MainCtrlPos].R) * RList[MainCtrlPos].R); + break; + default: + if (hydro_TC && hydro_TC_Fill > 0.01) + dizel_EngageSwitch(1.0); + else + dizel_EngageSwitch(0.0); + } +} + +// the clutch of the integrated controller: in with the converter filled or the power asked, half in for the retarder +void TMoverParameters::dizel_ClutchByIntegratedController() +{ + if (dizel_automaticgearstatus == 0) + { + if ((hydro_TC && hydro_TC_Fill > 0.01) || eimic_real > 0.005) + dizel_EngageSwitch(1.0); + else if (Vel > hydro_R_EngageVel && hydro_R && hydro_R_Fill > 0.01) + dizel_EngageSwitch(0.5); + else + dizel_EngageSwitch(0.0); + } + else + dizel_EngageSwitch(0.0); +} + +// performs diesel engine startup procedure; potentially clears startup switch; returns: true if the engine can be started, false otherwise +bool TMoverParameters::dizel_StartupCheck() +{ + + auto engineisready{true}; // make inital optimistic presumption, then watch the reality crush it + + // test the fuel pump + // TODO: add fuel pressure check + if (false == FuelPump.is_active || (EngineType == TEngineType::DieselEngine && RList[MainCtrlPos].R == 0.0)) + { + engineisready = false; + // if( FuelPump.start_type == start_t::manual ) { + // with manual pump control startup procedure is done only once per starter switch press + dizel_startup = false; + // } + } + // test the oil pump + if (false == OilPump.is_active || OilPump.pressure < OilPump.pressure_minimum) + { + engineisready = false; + if (OilPump.start_type == start_t::manual) + { + // with manual pump control startup procedure is done only once per starter switch press + dizel_startup = false; + } + } + // test the water circuits and water temperature + if (true == dizel_heat.PA) + { + engineisready = false; + // TBD, TODO: reset startup procedure depending on pump and heater control mode + dizel_startup = false; + } + + return engineisready; +} + +// ************************************************************************************************* +// Q: 20160715 +// Aktualizacja stanu silnika +// ************************************************************************************************* +bool TMoverParameters::dizel_Update(double dt) +{ + + WaterPumpCheck(dt); + WaterHeaterCheck(dt); + OilPumpCheck(dt); + FuelPumpCheck(dt); + // the engine being started fires once the starter has turned it a while; one stopped meanwhile starts over + dizel_FiringCountdown = (Mains ? std::max(0.0, dizel_FiringCountdown - dt) : 0.0); + + if (true == dizel_startup && true == dizel_StartupCheck()) + { + dizel_ignition = true; + } + + if (true == dizel_ignition && LastSwitchingTime >= InitialCtrlDelay) + { + + dizel_startup = false; + dizel_ignition = false; + // TODO: split engine and main circuit state indicator in two separate flags + LastSwitchingTime = 0; + Timer::subsystem.switching.note(Timer::switching_counter::diesel, this, &TypeName, &Name); + Mains = true; + dizel_spinup = true; + dizel_FiringCountdown = dizel_SmokeDelay; + enrot = std::max(enrot, + 0.35 * ( // TODO: dac zaleznie od temperatury i baterii + EngineType == TEngineType::DieselEngine ? dizel_nmin : DElist[0].RPM / 60.0)); + } + + dizel_spinup = dizel_spinup && Mains && enrot < 0.95 * (EngineType == TEngineType::DieselEngine ? dizel_nmin : DElist[0].RPM / 60.0); + + if (true == Mains && false == FuelPump.is_active) + { + // knock out the engine if the fuel pump isn't feeding it + // TBD, TODO: grace period before the engine is starved for fuel and knocked out + // an engine started on its own stops on its own + MainSwitch(false, MainSwitchRange()); + } + + bool DU{false}; + + if (EngineType == TEngineType::DieselEngine) + { + dizel_EngageChange(dt); + DU = dizel_AutoGearCheck(); + double const fillspeed{2}; + dizel_fill = dizel_fill + fillspeed * dt * (dizel_fillcheck(MainCtrlPos, dt) - dizel_fill); + } + + dizel_Heat(dt); + + return DU; +} + +// ************************************************************************************************* +// Q: 20160715 +// oblicza napelnienie, uzwglednia regulator obrotow +// ************************************************************************************************* +double TMoverParameters::dizel_fillcheck(int mcp, double dt) +{ + auto realfill{0.0}; + + if (true == Mains && MainCtrlPosNo > 0 && true == FuelPump.is_active) + { + + if (true == dizel_ignition && LastSwitchingTime >= 0.9 * InitialCtrlDelay) + { + // wzbogacenie przy rozruchu + // NOTE: ignition flag is reset before this code is executed + // TODO: sort this out + realfill = 1; + } + else + { + // napelnienie zalezne od MainCtrlPos + if (EIMCtrlType > 0) + { + realfill = dizel_DigitalFill(dt); + } + else + { + dizel_nreg_max = dizel_nmax; + realfill = RList[mcp].R; + } + } + if (dizel_nmax_cutoff > 0) + { + realfill = dizel_GovernorFill(mcp, realfill); + } + } + + return std::clamp(realfill, 0.0, 1.0); +} + +// the fill set by the integrated controller, and the idle and top revolutions the governor keeps to +double TMoverParameters::dizel_DigitalFill(double dt) +{ + double realfill; + realfill = std::max(0.0, std::min(eimic_real, 1 - motor_param(ScndCtrlActualPos).Isat)); + if (eimic_real > 0.005 && !hydro_TC_Lockup) + { + dizel_nreg_min = std::min(dizel_nreg_min + 2.5 * dt, dizel_nmin_hdrive + eimic_real * dizel_nmin_hdrive_factor); + } + else + { + if (Vel < hydro_R_EngageVel && hydro_R && hydro_R_Fill > 0.01) + dizel_nreg_min = std::min(dizel_nreg_min + 5.0 * dt, dizel_nmin_retarder); + else + dizel_nreg_min = dizel_nmin; + } + if (!dizel_vel2nmax_Table.empty() && !hydro_TC_Lockup) + { + dizel_nreg_max = std::min(std::min(dizel_nreg_max, enrot) + dizel_nreg_acc * dt, TableInterpolation(dizel_vel2nmax_Table, Vel)); + } + else + { + dizel_nreg_max = dizel_nmax; + } + return realfill; +} + +// the fill cut off over the revolutions the governor allows at the controller's position, or full under the idle ones +double TMoverParameters::dizel_GovernorFill(int const mcp, double realfill) const +{ + auto nreg{0.0}; + if (EIMCtrlType > 0) + nreg = eimic_real > 0.005 ? dizel_nreg_max : dizel_nmin; + else + nreg = dizel_GovernorRevolutions(mcp, realfill); + if (enrot > nreg) // nad predkoscia regulatora zeruj dawke + realfill = 0; + if (enrot < dizel_nreg_min && RList[mcp].R > 0.001) // jesli ponizej biegu jalowego i niezerowa dawka, to dawaj pelna + realfill = 1; + return realfill; +} + +// the revolutions the governor allows at the controller's position, the gearbox and the speed; the fill cut off at +// a position the governor doesn't know +double TMoverParameters::dizel_GovernorRevolutions(int const mcp, double &realfill) const +{ + auto nreg{0.0}; + switch (RList[MainCtrlPos].Mn) + { + case 0: + case 1: + nreg = dizel_nmin; + break; + case 2: + if (dizel_automaticgearstatus == 0 && true /*(!hydro_TC) || (dizel_engage>dizel_fill)*/) + nreg = dizel_nreg_max; + else + nreg = dizel_nmin; + break; + case 3: + if (dizel_automaticgearstatus == 0 && Vel > dizel_minVelfullengage) + nreg = dizel_nreg_max; + else + nreg = dizel_nmin; + break; + case 4: + if (dizel_automaticgearstatus == 0 && Vel > dizel_minVelfullengage) + nreg = dizel_nmax; + else + nreg = dizel_nmin * 0.75 + dizel_nreg_max * 0.25; + break; + case 5: + if (Vel > dizel_minVelfullengage) + nreg = dizel_nreg_max; + else + nreg = dizel_nmin + 0.8 * (dizel_nreg_max - dizel_nmin) * RList[mcp].R; + break; + default: + realfill = 0; // sluczaj + break; + } + return nreg; +} + +// ************************************************************************************************* +// Q: 20160715 +// Oblicza moment siły wytwarzany przez silnik spalinowy +// ************************************************************************************************* +double TMoverParameters::dizel_Momentum(double Fill, double n, double dt) +{ // liczy moment sily wytwarzany przez silnik spalinowy} + double Moment = 0; + double enMoment = 0; + double gearMoment = 0; + double eps = 0; + double newn = 0; + double friction = 0; + double TorqueH = 0; + double TorqueL = 0; + double TorqueC = 0; + n = n * CabActive; + if (motor_param(ScndCtrlActualPos).mIsat < 0.001 || DirActive == 0) + n = enrot; + friction = dizel_engagefriction; + hydro_TC_nIn = enrot; // wal wejsciowy przetwornika momentu + hydro_TC_nOut = dizel_n_old; // wal wyjsciowy przetwornika momentu + + if (enrot > 0) + { + if (dizel_Momentum_Table.size() > 1) + { + Moment = TableInterpolation(dizel_Momentum_Table, enrot) * Fill - dizel_Mstand; + } + else + { + Moment = (dizel_Mmax - (dizel_Mmax - dizel_Mnmax) * square((enrot - dizel_nMmax) / (dizel_nMmax - dizel_nmax))) * Fill - dizel_Mstand; + } + Mm = Moment; + dizel_FuelConsumptionActual = dizel_FuelConsumption * enrot * Fill; + dizel_FuelConsumptedTotal += dizel_FuelConsumptionActual * dt / 3600.0; + if (hydro_R && hydro_R_Placement == 2) + Moment -= dizel_MomentumRetarder(enrot, dt); + } + else + { + Moment = -dizel_Mstand; + } + if (enrot < dizel_nmin / 10.0 && eAngle < M_PI_2) + { + // wstrzymywanie przy malych obrotach + Moment -= dizel_Mstand; + } + if (true == dizel_spinup) + Moment += dizel_Mstand / (0.3 + std::max(0.0, enrot / dizel_nmin)); // rozrusznik + + dizel_Torque = Moment; + + hydro_TCFillCheck(dt); + + // obliczanie momentow poszczegolnych sprzegiel + // sprzeglo glowne (skrzynia biegow) + TorqueC = dizel_engageMaxForce * dizel_engage * dizel_engageDia * friction; + + if (hydro_TC) // jesli hydro + { + hydro_TCTorque(); + TorqueH = hydro_TC_TorqueOut; + TorqueL = hydro_TC_LockupTorque * hydro_TC_LockupRate; + } + else + { + TorqueH = 0; // brak przetwornika oznacza brak momentu + TorqueL = 1 + TorqueC * 2; // zabezpieczenie, polaczenie trwale + } + + // sprawdzanie dociskow poszczegolnych sprzegiel + if (abs(Moment) > std::min(TorqueC, TorqueL + abs(hydro_TC_TorqueIn)) || abs(dizel_n_old - enrot) > 0.1) // slizga sie z powodu roznic predkosci albo przekroczenia momentu + { + dizel_engagedeltaomega = enrot - dizel_n_old; + + if (TorqueC > TorqueL) + { + if (TorqueC > TorqueL + abs(TorqueH)) + { + hydro_TC_nOut = n; + gearMoment = TorqueL + abs(TorqueH) * sign(dizel_engagedeltaomega); + enMoment = Moment - (TorqueL + abs(hydro_TC_TorqueIn)) * sign(dizel_engagedeltaomega); + } + else + { + hydro_TC_nOut = enrot - (n - enrot) * (TorqueC - TorqueL) / TorqueH; // slizganie proporcjonalne, zeby przetwornik nadrabial + gearMoment = TorqueC * sign(dizel_engagedeltaomega); + enMoment = Moment - gearMoment; + } + } + else + { + hydro_TC_nOut = enrot; + gearMoment = TorqueC*sign(dizel_engagedeltaomega); + enMoment = Moment - gearMoment; + } + eps = enMoment / dizel_AIM; + newn = enrot + eps * dt; + if ((newn - n) * (enrot - dizel_n_old) < 0 && TorqueC > 0.1) // przejscie przez zero - slizgalo sie i przestało + newn = n; + if (newn * enrot <= 0 && eps * enrot < 0) // przejscie przez zero obrotow + newn = 0; + enrot = newn; + } + else // nie slizga sie (jeszcze) + { + dizel_engagedeltaomega = 0; + gearMoment = Moment; + double enrot_min = enrot - (std::min(TorqueC, TorqueL + abs(hydro_TC_TorqueIn)) - Moment) / dizel_AIM * dt; + double enrot_max = enrot + (std::min(TorqueC, TorqueL + abs(hydro_TC_TorqueIn)) + Moment) / dizel_AIM * dt; + enrot = safe_clamp(n, enrot_min, enrot_max); + } + if (hydro_R && hydro_R_Placement == 1) + gearMoment -= dizel_MomentumRetarder(hydro_TC_nOut, dt); + + if (enrot <= 0 && false == dizel_spinup) + { + // an engine stalling stops those started together with it, once. one already stopped, from its own switch or + // another vehicle's, or not started at all, has nothing to stop: it stays quiet, rather than stop every frame + // the engines started on their own or from the separate switches (eu07/maszyna#80) + if (true == Mains) + { + MainSwitch(false, MainSwitchRange()); + } + enrot = 0; + } + + dizel_n_old = n; // obecna predkosc katowa na potrzeby kolejnej klatki + + return gearMoment; +} + +// the torque converter filled and emptied, and its lockup clutch engaged and released, by the power and the speed +void TMoverParameters::hydro_TCFillCheck(double dt) +{ + if (hydro_TC) // jesli przetwornik momentu + { + // napelnianie przetwornika + bool IsPower = EIMCtrlType > 0 ? eimic_real > 0.005 : MainCtrlPowerPos() > 0; + if (IsPower && Mains && enrot > dizel_nmin * 0.9) + hydro_TC_Fill += hydro_TC_FillRateInc * dt; + // oproznianie przetwornika + if ((!IsPower && Vel < dizel_maxVelANS) || !Mains || enrot < dizel_nmin * 0.8) + hydro_TC_Fill -= hydro_TC_FillRateDec * dt; + // obcinanie zakresu + hydro_TC_Fill = std::clamp(hydro_TC_Fill, 0.0, 1.0); + + // blokowanie sprzegla blokującego + if (Vel > hydro_TC_LockupSpeed && Mains && enrot > 0.9 * dizel_nmin && IsPower) + { + hydro_TC_Lockup = true; + hydro_TC_LockupRate += hydro_TC_FillRateInc * dt; + } + // luzowanie sprzegla blokujacego + if (Vel < (IsPower ? hydro_TC_LockupSpeed : hydro_TC_UnlockSpeed) || !Mains || enrot < 0.8 * dizel_nmin) + { + hydro_TC_Lockup = false; + hydro_TC_LockupRate -= hydro_TC_FillRateDec * dt; + } + // obcinanie zakresu + hydro_TC_LockupRate = std::clamp(hydro_TC_LockupRate, 0.0, 1.0); + } + else + { + hydro_TC_Fill = 0.0; + hydro_TC_LockupRate = 0.0; + } +} + +// the torque converter's moments on its input and output shafts, by their revolutions and its fill +void TMoverParameters::hydro_TCTorque() +{ + double HydroTorque = 0; + HydroTorque += hydro_TC_nIn * hydro_TC_nIn * hydro_TC_TorqueInIn; + HydroTorque += (hydro_TC_nIn - hydro_TC_nOut) * hydro_TC_TorqueInOut; + HydroTorque += hydro_TC_nOut * hydro_TC_nOut * hydro_TC_TorqueOutOut; + double nOut2In = hydro_TC_nOut / std::max(0.01, hydro_TC_nIn); + if (hydro_TC_Table.size() > 1) + { + hydro_TC_TMRatio = TableInterpolation(hydro_TC_Table, nOut2In); + hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; + hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill * std::min(1.0, hydro_TC_TMRatio); + } + else + { + if (nOut2In < hydro_TC_CouplingPoint) + { + hydro_TC_TMRatio = 1 + (hydro_TC_TMMax - 1) * square(1 - nOut2In / hydro_TC_CouplingPoint); + hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill; + hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; + } + else + { + hydro_TC_TMRatio = (1 - nOut2In) / (1 - hydro_TC_CouplingPoint); + hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; + hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; + } + } +} + +double TMoverParameters::dizel_MomentumRetarder(double n, double dt) +{ + double RetarderRequest = Mains ? std::max(0.0, -eimic_real) : 0; + if (hydro_R_WithIndividual) + RetarderRequest = LocalBrakeRatio(); + if (Vel < hydro_R_MinVel) + RetarderRequest = 0; + if (hydro_R_Placement == 2 && enrot < dizel_nmin) + { + RetarderRequest = 0; + } + + hydro_R_ClutchActive = !hydro_R_Clutch || RetarderRequest > 0; + if (!hydro_R_Clutch || (hydro_R_ClutchActive && hydro_R_ClutchSpeed == 0)) + { + hydro_R_n = n * 60; + } + else if (hydro_R_ClutchActive) + { + hydro_R_n = sign(n) * std::min(std::abs(hydro_R_n + hydro_R_ClutchSpeed * dt), std::abs(n * 60)); + } + else + { + hydro_R_n = 0; + } + n = hydro_R_n / 60.f; + + if (hydro_R_Fill < RetarderRequest) // gdy zadane hamowanie + { + hydro_R_Fill = std::min(hydro_R_Fill + hydro_R_FillRateInc * dt, RetarderRequest); + } + else + { + hydro_R_Fill = std::max(hydro_R_Fill - hydro_R_FillRateDec * dt, RetarderRequest); + } + + double Moment = hydro_R_MaxTorque; + if (double pwr = Moment * std::abs(n) * M_PI * 2 * 0.001; pwr > hydro_R_MaxPower) + Moment = Moment * hydro_R_MaxPower / pwr; + double moment_in = n * n * hydro_R_TorqueInIn; + Moment = std::min(moment_in, Moment * hydro_R_Fill); + + hydro_R_Torque = Moment; + + return Moment; +} + +// sets component temperatures to specified value +void TMoverParameters::dizel_HeatSet(float const Value) +{ + + // TODO: don't include ambient temperature, pull it from environment data instead + dizel_heat.Te = Value; + dizel_heat.Ts = Value; + dizel_heat.To = Value; + dizel_heat.Tsr = Value; + dizel_heat.Twy = Value; + dizel_heat.Tsr2 = Value; + dizel_heat.Twy2 = Value; + dizel_heat.temperatura1 = Value; + dizel_heat.temperatura2 = Value; +} + +// calculates diesel engine temperature and heat transfers +// adapted from scripts written by adamst +// NOTE: originally executed twice per second +void TMoverParameters::dizel_Heat(double const dt) +{ + + auto const qs{44700.0}; + auto const Cs{11000.0}; + auto const Cw{4.189}; + auto const Co{1.885}; + auto const gwmin{400.0}; + auto const gwmax{4000.0}; + auto const gwmin2{400.0}; + auto const gwmax2{4000.0}; + + dizel_heat.Te = Global.AirTemperature; + + auto const engineon{(Mains ? 1 : 0)}; + auto const engineoff{(Mains ? 0 : 1)}; + auto const rpm{enrot * 60}; + // TODO: calculate this once and cache for further use, instead of doing it repeatedly all over the place + auto const revolutionsfactor{EngineRPMRatio()}; + auto const waterpump{WaterPump.is_active ? 1 : 0}; + + auto const gw = engineon * std::lerp(gwmin, gwmax, revolutionsfactor) + waterpump * 1000 + engineoff * 200; + auto const gw2 = engineon * std::lerp(gwmin2, gwmax2, revolutionsfactor) + waterpump * 1000 + engineoff * 200; + auto const gwO = std::lerp(gwmin, gwmax, revolutionsfactor); + + dizel_heat.water.is_cold = dizel_heat.water.config.temp_min > 0 && dizel_heat.temperatura1 < dizel_heat.water.config.temp_min - (Mains ? 5 : 0); + dizel_heat.water.is_hot = dizel_heat.water.config.temp_max > 0 && dizel_heat.temperatura1 > dizel_heat.water.config.temp_max - (dizel_heat.water.is_hot ? 8 : 0); + dizel_heat.water_aux.is_cold = dizel_heat.water_aux.config.temp_min > 0 && dizel_heat.temperatura2 < dizel_heat.water_aux.config.temp_min - (Mains ? 5 : 0); + dizel_heat.water_aux.is_hot = dizel_heat.water_aux.config.temp_max > 0 && dizel_heat.temperatura2 > dizel_heat.water_aux.config.temp_max - (dizel_heat.water_aux.is_hot ? 8 : 0); + dizel_heat.oil.is_cold = dizel_heat.oil.config.temp_min > 0 && dizel_heat.To < dizel_heat.oil.config.temp_min - (Mains ? 5 : 0); + dizel_heat.oil.is_hot = dizel_heat.oil.config.temp_max > 0 && dizel_heat.To > dizel_heat.oil.config.temp_max - (dizel_heat.oil.is_hot ? 8 : 0); + // engine overheat check + dizel_heat.engine_is_hot = dizel_heat.engine_max_temp > 0 && dizel_heat.Ts > dizel_heat.engine_max_temp - (dizel_heat.engine_is_hot ? 8 : 0); + + auto const PT = false == dizel_heat.water.is_cold && false == dizel_heat.water.is_hot && false == dizel_heat.water_aux.is_cold && false == dizel_heat.water_aux.is_hot && + false == dizel_heat.oil.is_cold && false == dizel_heat.oil.is_hot && false == dizel_heat.engine.is_hot /* && ( false == awaria_termostatow ) */ + /* || PTp */; + auto const PPT = false == PT /* && ( false == PPTp ) */; + dizel_heat.PA = /* ( ( !zamkniecie or niedomkniecie ) and !WBD ) || */ PPT /* || nurnik || ( woda < 7 ) */; + + // engine heat transfers + auto const Ge{engineon * (0.21 * dizel_heat.powerfactor * EnginePower + 12) / 3600}; + // TODO: replace fixed heating power cost with more accurate calculation + auto const obciazenie{engineon * (dizel_heat.powerfactor * EnginePower / 950 + (Heating ? HeatingPower : 0) + 70)}; + auto const Qd{qs * Ge - obciazenie}; + // silnik oddaje czesc ciepla do wody chlodzacej, a takze pewna niewielka czesc do otoczenia, modyfikowane przez okienko + auto const Qs{(Qd - dizel_heat.kfs * (dizel_heat.Ts - dizel_heat.Tsr) - dizel_heat.kfe * /* ( 0.3 + 0.7 * ( dizel_heat.okienko ? 1 : 0 ) ) * */ (dizel_heat.Ts - dizel_heat.Te))}; + auto const dTss{Qs / Cs}; + dizel_heat.Ts += static_cast(dTss * dt); + + // oil heat transfers + // olej oddaje cieplo do wody gdy krazy przez wymiennik ciepla == wlaczona pompka lub silnik + auto const dTo{(dizel_heat.auxiliary_water_circuit ? (dizel_heat.kfo * (dizel_heat.Ts - dizel_heat.To) - dizel_heat.kfo2 * (dizel_heat.To - dizel_heat.Tsr2)) / (gwO * Co) : + (dizel_heat.kfo * (dizel_heat.Ts - dizel_heat.To) - dizel_heat.kfo2 * (dizel_heat.To - dizel_heat.Tsr)) / (gwO * Co))}; + dizel_heat.To += static_cast(dTo * dt); + + // heater + /* + if( typ == "SP45" ) + Qp = (float)( podgrzewacz and ( true == WaterPump.is_active ) and ( Twy < 55 ) and ( Twy2 < 55 ) ) * 1000; + else + */ + auto const Qp = (true == WaterHeater.is_active && true == WaterPump.is_active && dizel_heat.Twy < 60 && dizel_heat.Twy2 < 60 ? 1 : 0) * 1000; + + auto const kurek07{1}; // unknown/unimplemented device TBD, TODO: identify and implement? + + if (true == dizel_heat.auxiliary_water_circuit) + { + // auxiliary water circuit setup + dizel_heat.water_aux.is_warm = true == dizel_heat.cooling || + (true == Mains && BatteryVoltage > 0.75 * NominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ + && dizel_heat.water_aux.config.temp_cooling > 0 && dizel_heat.temperatura2 > dizel_heat.water_aux.config.temp_cooling - (dizel_heat.water_aux.is_warm ? 8 : 0)); + auto const PTC2{(dizel_heat.water_aux.is_warm /*or PTC2p*/ ? 1 : 0)}; + dizel_heat.rpmwz2 = static_cast(PTC2 * (dizel_heat.fan_speed >= 0 ? rpm * dizel_heat.fan_speed : dizel_heat.fan_speed * -1)); + dizel_heat.zaluzje2 = dizel_heat.water_aux.config.shutters ? PTC2 == 1 : true; // no shutters is an equivalent to having them open + auto const zaluzje2{(dizel_heat.zaluzje2 ? 1 : 0)}; + // auxiliary water circuit heat transfer values + auto const kf2{kurek07 * (dizel_heat.kw * (0.3 + 0.7 * zaluzje2) * dizel_heat.rpmw2 + dizel_heat.kv * (0.3 + 0.7 * zaluzje2) * Vel / 3.6) + 2}; + auto const dTs2{dizel_heat.kfo2 * (dizel_heat.To - dizel_heat.Tsr2) / (gw2 * Cw)}; + // przy otwartym kurku B ma³y obieg jest dogrzewany przez du¿y - stosujemy przy korzystaniu z podgrzewacza oraz w zimie + auto const Qch2{-kf2 * (dizel_heat.Tsr2 - dizel_heat.Te) + 80 * (true == WaterCircuitsLink ? 1 : 0) * (dizel_heat.Twy - dizel_heat.Tsr2)}; + auto const dTch2{Qch2 / (gw2 * Cw)}; + // auxiliary water circuit heat transfers finalization + // NOTE: since primary circuit doesn't read data from the auxiliary one, we can pretty safely finalize auxiliary updates before touching the primary circuit + auto const Twe2{dizel_heat.Twy2 + dTch2 * dt}; + dizel_heat.Twy2 = static_cast(Twe2 + dTs2 * dt); + dizel_heat.Tsr2 = static_cast(0.5 * (dizel_heat.Twy2 + Twe2)); + dizel_heat.temperatura2 = dizel_heat.Twy2; + } + // primary water circuit setup + dizel_heat.water.is_flowing = dizel_heat.water.config.temp_flow < 0 || dizel_heat.temperatura1 > dizel_heat.water.config.temp_flow - (dizel_heat.water.is_flowing ? 5 : 0); + auto const obieg{(dizel_heat.water.is_flowing ? 1 : 0)}; + dizel_heat.water.is_warm = + true == dizel_heat.cooling || (true == Mains && BatteryVoltage > 0.75 * NominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ + && dizel_heat.water.config.temp_cooling > 0 && dizel_heat.temperatura1 > dizel_heat.water.config.temp_cooling - (dizel_heat.water.is_warm ? 8 : 0)); + auto const PTC1{(dizel_heat.water.is_warm /*or PTC1p*/ ? 1 : 0)}; + dizel_heat.rpmwz = static_cast(PTC1 * (dizel_heat.fan_speed >= 0 ? rpm * dizel_heat.fan_speed : dizel_heat.fan_speed * -1)); + dizel_heat.zaluzje1 = dizel_heat.water.config.shutters ? PTC1 == 1 : true; // no shutters is an equivalent to having them open + auto const zaluzje1{(dizel_heat.zaluzje1 ? 1 : 0)}; + // primary water circuit heat transfer values + auto const kf{obieg * kurek07 * (dizel_heat.kw * (0.3 + 0.7 * zaluzje1) * dizel_heat.rpmw + dizel_heat.kv * (0.3 + 0.7 * zaluzje1) * Vel / 3.6 + 3) + 2}; + auto const dTs{(dizel_heat.auxiliary_water_circuit ? dizel_heat.kfs * (dizel_heat.Ts - dizel_heat.Tsr) / (gw * Cw) : + (dizel_heat.kfs * (dizel_heat.Ts - dizel_heat.Tsr) + dizel_heat.kfo2 * (dizel_heat.To - dizel_heat.Tsr)) / (gw * Cw))}; + auto const Qch{-kf * (dizel_heat.Tsr - dizel_heat.Te) + Qp}; + auto const dTch{Qch / (gw * Cw)}; + // primary water circuit heat transfers finalization + auto const Twe{dizel_heat.Twy + dTch * dt}; + dizel_heat.Twy = static_cast(Twe + dTs * dt); + dizel_heat.Tsr = static_cast(0.5 * (dizel_heat.Twy + Twe)); + dizel_heat.temperatura1 = dizel_heat.Twy; + /* + fuelConsumed = fuelConsumed + ( Ge * 0.5 ); + + while( fuelConsumed >= 0.83 ) { + fuelConsumed = fuelConsumed - 0.83; + fuelQueue.DestroyProductMatching( null, 1 ); + }//if + + if( engineon ) + temp_turbo = temp_turbo + 0.3 * ( t_pozycja ); + if( t_pozycja == 0 and cisnienie > 0.04 ) + temp_turbo = temp_turbo - 1; + + if( temp_turbo > 400 ) + temp_turbo = 400; + if( temp_turbo < 0 ) + temp_turbo = 0; + + if( temp_turbo > 50 and cisnienie < 0.05 ) + timer_turbo = timer_turbo + 1; + + if( temp_turbo == 0 ) + timer_turbo = 0; + + if( timer_turbo > 360 ) { + awaria_turbo = true; + timer_turbo = 400; + } + + if( Ts < 50 ) + p_odpal = 3; + if( Ts > 49 and Ts < 76 ) + p_odpal = 4; + if( Ts > 75 ) + p_odpal = 7; + + stukanie = stukanie or awaria_oleju; + + if( awaria_oleju == true and ilosc_oleju > 0 ) { + ilosc_oleju = ilosc_oleju - ( 0.002 * rpm / 1500 ); + } + if( awaria_oleju == true and cisnienie < 0.06 ) + damage = 1; + */ +} diff --git a/physics/mover/doors.cpp b/physics/mover/doors.cpp new file mode 100644 index 000000000..04ad070dc --- /dev/null +++ b/physics/mover/doors.cpp @@ -0,0 +1,592 @@ +/* +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 doors and the exchange of the load + +#include "stdafx.h" +#include "physics/mover.h" +#include "vehicle/DynObj.h" +#include "physics/oerlikonest.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/Timer.h" +#include "utilities/parser.h" +#include "simulation/simulation.h" +#include "vehicle/fieldshunting.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "physics/mover/internal.h" + + +bool TMoverParameters::AssignLoad(std::string const &Loadname, float const Amount) +{ + + if (Loadname == "pantstate") + { + if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector) + { + // wartość niby "pantstate" - nazwa dla formalności, ważna jest ilość + auto const pantographsetup{static_cast(Amount)}; + if (pantographsetup & 1 << 2) + { + DoubleTr = -1; + } + if (pantographsetup & 1 << 0) + { + if (DoubleTr == 1) + { + OperatePantographValve(end::front, operation_t::enable, range_t::local); + } + else + { + OperatePantographValve(end::rear, operation_t::enable, range_t::local); + } + } + if (pantographsetup & 1 << 1) + { + if (DoubleTr == 1) + { + OperatePantographValve(end::rear, operation_t::enable, range_t::local); + } + else + { + OperatePantographValve(end::front, operation_t::enable, range_t::local); + } + } + return true; + } + else + { + return false; + } + } + + if (Loadname.empty()) + { + // empty the vehicle if requested + LoadTypeChange = LoadType.name != Loadname; + LoadType = load_attributes(); + LoadAmount = 0.f; + return true; + } + // can't mix load types, at least for the time being + if (LoadAmount > 0 && LoadType.name != Loadname) + { + return false; + } + + auto const loadattributes = std::ranges::find_if(LoadAttributes, [&](auto const &attributes) { return attributes.name == Loadname; }); + if (loadattributes == std::end(LoadAttributes)) + { + // didn't find matching load configuration, this type is unsupported + return false; + } + LoadTypeChange = LoadType.name != Loadname; + LoadType = *loadattributes; + LoadAmount = safe_clamp(Amount, 0.f, MaxLoad); + ComputeMass(); + return true; +} + +// ************************************************************************************************* +// Q: 20160713 +// Test zakończenia załadunku / rozładunku +// ************************************************************************************************* +bool TMoverParameters::LoadingDone(double const LSpeed, std::string_view Loadname) +{ + + if (LSpeed == 0.0) + { + // zerowa prędkość zmiany, to koniec + LoadStatus = 4; + return true; + } + + if (Loadname.empty()) + { + return LoadStatus >= 4; + } + if (Loadname != LoadType.name) + { + return LoadStatus >= 4; + } + + // test zakończenia załadunku/rozładunku + // load exchange speed is reduced if the wagon is overloaded + auto const loadchange{static_cast(std::abs(LSpeed * LastLoadChangeTime) * (LoadAmount > MaxLoad ? 0.5 : 1.0))}; + + if (LSpeed < 0) + { + // gdy rozładunek + LoadStatus = 2; // trwa rozładunek (włączenie naliczania czasu) + if (loadchange > 0) // jeśli coś przeładowano + { + LastLoadChangeTime = 0; // naliczony czas został zużyty + LoadAmount -= loadchange; // zmniejszenie ilości ładunku + CommandIn.Value1 -= loadchange; // zmniejszenie ilości do rozładowania + if (LoadAmount <= 0 || CommandIn.Value1 <= 0) + { + // pusto lub rozładowano żądaną ilość + LoadStatus = 4; // skończony rozładunek + LoadAmount = safe_clamp(LoadAmount, 0.f, MaxLoad); // ładunek nie może być ujemny + } + if (LoadAmount == 0.f) + { + AssignLoad(""); // jak nic nie ma, to nie ma też nazwy + } + ComputeMass(); + } + } + else if (LSpeed > 0) + { + // gdy załadunek + LoadStatus = 1; // trwa załadunek (włączenie naliczania czasu) + if (loadchange > 0) // jeśli coś przeładowano + { + LastLoadChangeTime = 0; // naliczony czas został zużyty + LoadAmount += loadchange; // zwiększenie ładunku + CommandIn.Value1 -= loadchange; + if (LoadAmount >= MaxLoad * (1.0 + OverLoadFactor) || CommandIn.Value1 <= 0) + { + LoadStatus = 4; // skończony załadunek + LoadAmount = std::min(static_cast(MaxLoad * (1.0 + OverLoadFactor)), LoadAmount); + } + ComputeMass(); + } + } + + return LoadStatus >= 4; +} + +bool TMoverParameters::ChangeDoorPermitPreset(int const Change, range_t const Notify) +{ + + auto const initialstate{Doors.permit_preset}; + + if (false == Doors.permit_presets.empty()) + { + + Doors.permit_preset = safe_clamp(Doors.permit_preset + Change, 0, static_cast(Doors.permit_presets.size() - 1)); + auto const doors{Doors.permit_presets[Doors.permit_preset]}; + auto const permitleft{((doors & 1) != 0)}; + auto const permitright{((doors & 2) != 0)}; + + PermitDoors(CabActive > 0 ? side::left : side::right, permitleft, Notify); + PermitDoors(CabActive > 0 ? side::right : side::left, permitright, Notify); + } + + return Doors.permit_preset != initialstate; +} + +bool TMoverParameters::PermitDoorStep(bool const State, range_t const Notify) +{ + + auto const initialstate{Doors.step_enabled}; + + Doors.step_enabled = State; + if (Notify != range_t::local) + { + // wysłanie wyłączenia do pozostałych? + SendCtrlToNext("DoorStep", State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return Doors.step_enabled != initialstate; +} + +bool TMoverParameters::PermitDoors(side const Door, bool const State, range_t const Notify) +{ + + bool const initialstate{Doors.instances[Door].open_permit}; + + PermitDoors_(Door, State); + + if (Notify != range_t::local) + { + + SendCtrlToNext("DoorPermit", + (State ? 1 : -1) // positive: grant, negative: revoke + * (Door == (CabActive > 0 ? side::left : side::right) ? // 1=lewe, 2=prawe (swap if reversed) + 1 : + 2), + CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return Doors.instances[Door].open_permit != initialstate; +} + +void TMoverParameters::PermitDoors_(side const Door, bool const State) +{ + + if (State && State != Doors.instances[Door].open_permit) + { + SetFlag(SoundFlag, sound::doorpermit); + } + Doors.instances[Door].open_permit = State; +} + +bool TMoverParameters::ChangeDoorControlMode(bool const State, range_t const Notify) +{ + + auto const initialstate{Doors.remote_only}; + + Doors.remote_only = State; + if (Notify != range_t::local) + { + // wysłanie wyłączenia do pozostałych? + SendCtrlToNext("DoorMode", State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + if (true == State) + { + // when door are put in remote control mode they're automatically open + // TBD, TODO: make it dependant on config switch? + OperateDoors(side::left, true); + OperateDoors(side::right, true); + } + + return Doors.remote_only != initialstate; +} + +bool TMoverParameters::OperateDoors(side const Door, bool const State, range_t const Notify) +{ + + auto &door{Doors.instances[Door]}; + /* + if( ( State == true ? door.is_open : door.is_closed ) ) { + // TBD: should the command be passed to other vehicles regardless of whether it affected the primary target? + // (for the time being no, methods are often invoked blindly which would lead to commands spam) + return false; + } + */ + bool result{false}; + + if (Notify == range_t::local) + { + door.local_open = State; + door.local_close = false == State; + result = true; + } + else + { + // remote door operation signals require power to propagate + if (Power24vIsAvailable || Power110vIsAvailable) + { + door.remote_open = State; + door.remote_close = false == State; + result = true; + } + } + + if (Notify != range_t::local) + { + + SendCtrlToNext(State == true ? "DoorOpen" : "DoorClose", + Door == (CabActive > 0 ? side::left : side::right) ? // 1=lewe, 2=prawe (swap if reversed) + 1 : + 2, + CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return result; +} + +// toggle door lock +bool TMoverParameters::LockDoors(bool const State, range_t const Notify) +{ + + auto const initialstate{Doors.lock_enabled}; + + Doors.lock_enabled = State; + if (Notify != range_t::local) + { + // wysłanie wyłączenia do pozostałych? + SendCtrlToNext("DoorLock", State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return Doors.lock_enabled != initialstate; +} + +// toggles departure warning +bool TMoverParameters::signal_departure(bool const State, range_t const Notify) +{ + + if (DepartureSignal == State) + { + // TBD: should the command be passed to other vehicles regardless of whether it affected the primary target? + return false; + } + + DepartureSignal = State; + if (Notify != range_t::local) + { + // wysłanie wyłączenia do pozostałych? + SendCtrlToNext("DepartureSignal", State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return true; +} + +// state of the door closure signalling (SOD) of this vehicle: open while a door isn't fully closed, released while +// the closed doors can be opened (a permit given, or, for doors that need none, no lock engaged), locked otherwise. +// doors the crew doesn't close (autonomous) aren't signalled, the same as for the door lights of the consist +door_closure_t TMoverParameters::door_closure() const +{ + if (Doors.range == 0.f || Doors.close_control == control_t::autonomous) + { + return door_closure_t::none; + } + if (std::ranges::any_of(Doors.instances, [](basic_door const &Door) { return false == Door.is_closed; })) + { + return door_closure_t::open; + } + if (Doors.is_locked) + { + return door_closure_t::locked; + } + if (Doors.permit_needed && std::ranges::none_of(Doors.instances, [](basic_door const &Door) { return Door.open_permit; })) + { + return door_closure_t::locked; + } + return door_closure_t::released; +} + +bool TMoverParameters::door_closure_lamp_lit(door_closure_t const Consist, bool const BlinkLit) const +{ + return Doors.closure_signal ? door_closure_lamp(Consist, BlinkLit) : Doors.is_locked; +} + +bool door_closure_lamp(door_closure_t const State, bool const BlinkLit) +{ + switch (State) + { + case door_closure_t::locked: + return true; + case door_closure_t::released: + return BlinkLit; + default: + return false; + } +} + +// automatic door controller update +void TMoverParameters::update_doors(double const Deltatime) +{ + + if (Doors.range == 0.f) + { + return; + } // HACK: crude way to distinguish vehicles with actual doors + + // NBMX Obsluga drzwi, MC: zuniwersalnione + auto const localopencontrol{false == Doors.remote_only && (Doors.open_control == control_t::passenger || Doors.open_control == control_t::mixed)}; + auto const remoteopencontrol{Doors.open_control == control_t::driver || Doors.open_control == control_t::conductor || Doors.open_control == control_t::mixed}; + auto const localclosecontrol{false == Doors.remote_only && (Doors.close_control == control_t::passenger || Doors.close_control == control_t::mixed)}; + auto const remoteclosecontrol{Doors.close_control == control_t::driver || Doors.close_control == control_t::conductor || Doors.close_control == control_t::mixed}; + + Doors.is_locked = true == Doors.has_lock && true == Doors.lock_enabled && Vel >= Doors.doorLockSpeed; + + for (auto &door : Doors.instances) + { + update_door_requests(door, localopencontrol, remoteopencontrol, localclosecontrol, remoteclosecontrol); + move_door(door, Deltatime); + } + + if (false == Doors.instances[side::right].is_open && false == Doors.instances[side::left].is_open) + { + return; + } + + if (Doors.auto_duration > 0.f) + { + update_door_timers(Deltatime); + } + /* + // the door are closed if their timer goes below 0, or if the vehicle is moving faster than defined threshold + std::array const doorids { side::right, side::left }; + for( auto const doorid : doorids ) { + auto const &door { Doors.instances[ doorid ] }; + if( true == door.is_open ) { + if( ( ( Doors.auto_velocity != -1.f ) && ( Vel > Doors.auto_velocity ) ) + || ( ( door.auto_timer != -1.f ) && ( door.auto_timer <= 0.f ) ) ) { + // close the door and set the timer to expired state (closing may happen sooner if vehicle starts moving) + OperateDoors( doorid, false, range_t::local ); + } + } + } + */ +} + +// the permit, the state and the requests of a door, and whether it and its step open or close +void TMoverParameters::update_door_requests(basic_door &door, bool const localopencontrol, bool const remoteopencontrol, bool const localclosecontrol, bool const remoteclosecontrol) +{ + // revoke permit if... + door.open_permit = true == door.open_permit // ...we already have one... + && (false == Doors.permit_presets.empty() // ...there's no preset switch controlling permit state... + || (false == Doors.is_locked // ...and the door lock is engaged... + && false == door.remote_close)); // ...or the door is about to be closed + + door.is_open = door.position >= Doors.range && (false == Doors.step_enabled || door.step_position >= (Doors.step_range != 0.f ? 1.f : 0.f)); + door.is_closed = door.position <= 0.f && door.step_position <= 0.f; + door.is_door_closed = door.position <= 0.f; + + door.local_open = door.local_open && false == door.is_open && (false == Doors.permit_needed || door.open_permit); + door.remote_open = (door.remote_open || Doors.remote_only) && false == door.is_open && (false == Doors.permit_needed || door.open_permit); + door.local_close = door.local_close && false == door.is_closed && (false == remoteopencontrol || false == door.remote_open); + door.remote_close = door.remote_close && false == door.is_closed && (false == localopencontrol || false == door.local_open); + + auto const openrequest{door_open_request(door, localopencontrol, remoteopencontrol)}; + auto const closerequest{door_close_request(door, localclosecontrol, remoteclosecontrol)}; + auto const ispowered{doors_powered()}; + + door.is_opening = false == door.is_open && true == ispowered && false == closerequest && (true == door.is_opening || (true == openrequest && false == Doors.is_locked)); + door.is_closing = false == door.is_closed && true == ispowered && false == openrequest && (door.is_closing || closerequest); + door.step_unfolding = Doors.step_range != 0.f && Doors.step_enabled && false == Doors.is_locked && door.step_position < 1.f && door.is_opening; + door.step_folding = door_step_folding(door); + + if (true == door.is_opening) + { + door.auto_timer = door_open_duration(door, localopencontrol, remoteopencontrol); + } +} + +// whether the door is asked to open, by the passengers, from afar or by itself +bool TMoverParameters::door_open_request(basic_door const &door, bool const localopencontrol, bool const remoteopencontrol) const +{ + auto const autoopenrequest{Doors.open_control == control_t::autonomous && (false == Doors.permit_needed || door.open_permit)}; + return (localopencontrol && door.local_open) || (remoteopencontrol && door.remote_open) || (autoopenrequest && false == door.is_open); +} + +// whether the door is asked to close, by the passengers, from afar, or by itself: over the speed, after its time or +// with its permit taken back +bool TMoverParameters::door_close_request(basic_door const &door, bool const localclosecontrol, bool const remoteclosecontrol) const +{ + auto const autocloserequest{(Doors.auto_velocity != -1.f && Vel > Doors.auto_velocity) || (door.auto_timer != -1.f && door.auto_timer <= 0.f) || + (Doors.permit_needed && false == door.open_permit)}; + return (door.remote_close && remoteclosecontrol) || (door.local_close && localclosecontrol) || (autocloserequest && door.is_open); +} + +// whether the doors have the voltage they work on +bool TMoverParameters::doors_powered() const +{ + if (Doors.voltage == 0) + { + return true; + } + if (Doors.voltage == 24) + { + return Power24vIsAvailable || Power110vIsAvailable; + } + return Doors.voltage == 110 && Power110vIsAvailable; +} + +// whether the unfolded step folds: without the permission to stay out, or with the door closing, once it's about to +// close or closed +bool TMoverParameters::door_step_folding(basic_door const &door) const +{ + auto const unfolded{door.step_position > 0.f}; + auto const mayfold{false == Doors.step_enabled || (Doors.permit_needed ? false == door.open_permit : door.is_closing)}; + return unfolded && mayfold && (door.close_delay > Doors.close_delay || door.position <= 0.f); +} + +// how long the opening door stays open: the time of the doors, for the passengers' opening and, if it counts, the +// opening from afar; none otherwise +float TMoverParameters::door_open_duration(basic_door const &door, bool const localopencontrol, bool const remoteopencontrol) const +{ + if (localopencontrol && door.local_open) + { + return Doors.auto_duration; + } + if (remoteopencontrol && door.remote_open && Doors.auto_include_remote) + { + return Doors.auto_duration; + } + return -1.f; +} + +// a door and its step moved as they open or close +void TMoverParameters::move_door(basic_door &door, double const Deltatime) +{ + // doors + if (true == door.is_opening) + { + // open door + if (false == door.step_unfolding // no wait if no doorstep + || Doors.step_type == 2) + { // no wait for rotating doorstep + door.open_delay += static_cast(Deltatime); + if (door.open_delay > Doors.open_delay) + { + door.position = std::min(Doors.range, static_cast(door.position + Doors.open_rate * Deltatime)); + } + } + door.close_delay = 0.f; + } + if (true == door.is_closing) + { + // close door + door.close_delay += static_cast(Deltatime); + if (door.close_delay > Doors.close_delay) + { + door.position = std::max(0.f, static_cast(door.position - Doors.close_rate * Deltatime)); + } + door.open_delay = 0.f; + } + // doorsteps + if (door.step_unfolding) + { + // unfold left doorstep + door.step_position = std::min(1.f, static_cast(door.step_position + Doors.step_rate * Deltatime)); + } + if (door.step_folding) + { + // fold left doorstep + if (is_multiple_unit()) + { + // multi-unit vehicles typically fold the doorstep only after closing the door + if (door.position <= 0.f) + { + door.step_position = std::max(0.f, static_cast(door.step_position - Doors.step_rate * Deltatime)); + } + } + else + { + door.step_position = std::max(0.f, static_cast(door.step_position - Doors.step_rate * Deltatime)); + } + } +} + +// the timers of the open doors which close after a while, kept running while the load is exchanged +void TMoverParameters::update_door_timers(double const Deltatime) +{ + // update door timers if the door close after defined time + for (auto &door : Doors.instances) + { + + if (false == door.is_open) + { + continue; + } + + if (door.auto_timer > 0.f) + { + door.auto_timer -= static_cast(Deltatime); + } + // if there's load exchange in progress, reset the timer(s) for already open doors + if (door.auto_timer != -1.f && (LoadStatus & (2 | 1)) != 0) + { + door.auto_timer = Doors.auto_duration; + } + } +} diff --git a/physics/mover/electrics.cpp b/physics/mover/electrics.cpp new file mode 100644 index 000000000..591c8b31f --- /dev/null +++ b/physics/mover/electrics.cpp @@ -0,0 +1,1390 @@ +/* +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 power supply: the batteries, the main switch, the pantographs, the converter, heating, lights, the genset + +#include "stdafx.h" +#include "physics/mover.h" +#include "vehicle/DynObj.h" +#include "physics/oerlikonest.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/Timer.h" +#include "utilities/parser.h" +#include "simulation/simulation.h" +#include "vehicle/fieldshunting.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "physics/mover/internal.h" + + +// KURS90 - sprężarka pantografów; Ra 2014-07: teraz jest to zbiornik rozrządu, chociaż to jeszcze nie tak +void TMoverParameters::UpdatePantVolume(double dt) +{ + // check the pantograph compressor while at it + // TODO: move the check to a separate method + // automatic start if the pressure is too low + PantCompFlag |= PantPress < 4.2 && true == (Pantographs[end::front].is_active | Pantographs[end::rear].is_active) // TODO: any_pantograph_is_active method + && (PantographCompressorStart == start_t::automatic || PantographCompressorStart == start_t::manualwithautofallback); + + auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; + PantCompFlag &= lowvoltagepower; + + if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector // tylko jeśli pantografujący + && EnginePowerSource.CollectorParameters.CollectorsNo > 0) + { + // Ra 2014-07: zasadniczo, to istnieje zbiornik rozrządu i zbiornik pantografów - na razie mamy razem + // Ra 2014-07: kurek trójdrogowy łączy spr.pom. z pantografami i wyłącznikiem ciśnieniowym WS + // Ra 2014-07: zbiornika rozrządu nie pompuje się tu, tylko pantografy; potem można zamknąć + // WS i odpalić resztę + if (PantAutoValve ? PantPress < ScndPipePress : bPantKurek3) // kurek zamyka połączenie z ZG + { // zbiornik pantografu połączony ze zbiornikiem głównym - małą sprężarką się tego nie napompuje + // Ra 2013-12: Niebugocław mówi, że w EZT nie ma potrzeby odcinać kurkiem + PantPress = ScndPipePress; + // ograniczenie ciśnienia do MaxPress (tylko w pantografach!) + PantPress = safe_clamp(ScndPipePress, 0.0, EnginePowerSource.CollectorParameters.MaxPress); + PantVolume = (PantPress + 1.0) * 0.1; // objętość, na wypadek odcięcia kurkiem + } + else + { // zbiornik główny odcięty, można pompować pantografy + if (PantCompFlag) + { + // włączona mała sprężarka + PantVolume += dt + // Ra 2013-12: Niebugocław mówi, że w EZT nabija 1.5 raz wolniej niż jak było 0.005 + * (TrainType == train_type::emu ? 0.003 : 0.005) / std::max(1.0, PantPress) * (0.45 - (0.1 / PantVolume / 10 - 0.1)) / 0.45; + } + PantPress = safe_clamp(10.0 * PantVolume - 1.0, 0.0, EnginePowerSource.CollectorParameters.MaxPress); // tu by się przydała objętość zbiornika + } + if (!PantCompFlag && PantVolume > 0.1) + PantVolume -= dt * 0.0003 * std::max(1.0, PantPress * 0.5); // nieszczelności: 0.0003=0.3l/s + + PantPressureSwitchCheck(); + } + else + { // a tu coś dla SM42 i SM31, aby pokazywać na manometrze + PantPress = CntrlPipePress; + } +}; + +// the pantographs' pressure switch: low, it opens the line breaker (or locks the converter of a unit) once; +// primed again over 4.6 bar, where the pantographs' compressor stops at 4.8 +void TMoverParameters::PantPressureSwitchCheck() +{ + if (PantPress < EnginePowerSource.CollectorParameters.MinPress) + { + // 3.5 wg http://www.transportszynowy.pl/eu06-07pneumat.php + if (true == PantPressSwitchActive) + { + PantPressureSwitchTrip(); + } + } + else if (PantPress >= 4.6) + { + // NOTE: we require active low power source to prime the pressure switch + // this is a work-around for potential isssues caused by the switch activating on otherwise idle vehicles, but should check whether it's accurate + if (true == Power24vIsAvailable || true == Power110vIsAvailable) + { + // prime the pressure switch + PantPressSwitchActive = true; + // turn off the subsystems lock + PantPressLockActive = false; + } + + if (PantPress >= 4.8) + { + // Winger - automatyczne wylaczanie malej sprezarki + // TODO: governor lock, disables usage until pressure drop below 3.8 (should really make compressor object we could reuse) + PantCompFlag = false; + } + } +} + +// the pantographs' pressure switch tripped by the low pressure: the line breaker opened, unless the voltage comes from +// elsewhere, or the converter of a unit locked; spent until primed again +void TMoverParameters::PantPressureSwitchTrip() +{ + // opuszczenie pantografów przy niskim ciśnieniu + if (TrainType != train_type::emu) + { + // pressure switch safety measure -- open the line breaker, unless there's alternate source of traction voltage + // (the genset of a dual-mode vehicle, when the selector is on it, doesn't need the pantographs) + if (GetTrainsetHighVoltage() < EnginePowerSource.CollectorParameters.MinV && false == GensetSelected()) + { + // TODO: check whether line breaker should be open EMU-wide + MainSwitch(false, TrainType == train_type::emu ? range_t::unit : range_t::local); + } + } + else + { + // specialized variant for EMU -- pwr system disables converter and heating, + // and prevents their activation until pressure switch is set again + PantPressLockActive = true; + // TODO: separate 'heating allowed' from actual heating flag, so we can disable it here without messing up heating toggle + ConverterSwitch(false, range_t::unit); + } + // mark the pressure switch as spent + PantPressSwitchActive = false; +} + +void TMoverParameters::UpdateBatteryVoltage(double dt) +{ // przeliczenie obciążenia baterii + using enum TEngineType; + if (BatteryVoltage > 0 && EngineType != DieselEngine && EngineType != WheelsDriven && NominalBatteryVoltage > 0) + { + + // HACK: allow to draw power also from adjacent converter, applicable for EMUs + // TODO: expand power cables system to include low voltage power transfers + // HACK: emulate low voltage generator powered directly by the diesel engine + auto const converteractive{Power110vIsAvailable || (EngineType == DieselElectric && true == Mains) || (EngineType == DieselEngine && true == Mains)}; + + BatteryVoltage -= BatteryDrain(dt, converteractive); + if (NominalBatteryVoltage / BatteryVoltage > 1.57 && MainSwitch(false) && EngineType != DieselEngine && EngineType != WheelsDriven) + EventFlag = true; // wywalanie szybkiego z powodu zbyt niskiego napiecia + if (BatteryVoltage > NominalBatteryVoltage) + BatteryVoltage = NominalBatteryVoltage; // wstrzymanie ładowania pow. 110V + if (BatteryVoltage < 0.01) + BatteryVoltage = 0.01; + } + else + { + // TODO: check and implement proper way to handle this for diesel engines + BatteryVoltage = NominalBatteryVoltage; + } +}; + +// the drop of the battery's voltage in dt, by what draws from it, or its rise by the converter charging it +double TMoverParameters::BatteryDrain(double dt, bool const converteractive) const +{ + if (NominalBatteryVoltage / BatteryVoltage < 1.22 && Battery) + { // 110V + return BatteryDrainCharged(dt, converteractive); + } + if (NominalBatteryVoltage / BatteryVoltage >= 1.22 && Battery) + { // 90V + return BatteryDrainLow(dt, converteractive); + } + if (!Battery) + { + return BatteryDrainSwitchedOff(dt); + } + return 0.0; +} + +// the drain of a battery at its voltage, the converter charging it +double TMoverParameters::BatteryDrainCharged(double dt, bool const converteractive) const +{ + double sn1; + double sn2; + double sn3; + double sn4; + double sn5; + if (!converteractive) + sn1 = dt * 2.0; // szybki spadek do ok 90V + else + sn1 = 0; + if (converteractive) + sn2 = -(dt * 2.0); // szybki wzrost do 110V + else + sn2 = 0; + if (Mains) + sn3 = dt * 0.05; + else + sn3 = 0; + if (iLights[0] & 63) // 64=blachy, nie ciągną prądu //rozpisać na poszczególne żarówki... + sn4 = dt * 0.003; + else + sn4 = 0; + if (iLights[1] & 63) // 64=blachy, nie ciągną prądu + sn5 = dt * 0.001; + else + sn5 = 0; + return sn1 + sn2 + sn3 + sn4 + sn5; +} + +// the drain of a battery run down to 90 V, the converter charging it +double TMoverParameters::BatteryDrainLow(double dt, bool const converteractive) const +{ + double sn1; + double sn2; + double sn3; + double sn4; + double sn5; + if (PantCompFlag) + sn1 = dt * 0.0046; + else + sn1 = 0; + if (converteractive) + sn2 = -(dt * 50); // szybki wzrost do 110V + else + sn2 = 0; + if (Mains) + sn3 = dt * 0.001; + else + sn3 = 0; + if (iLights[0] & 63) // 64=blachy, nie ciągną prądu + sn4 = dt * 0.0030; + else + sn4 = 0; + if (iLights[1] & 63) // 64=blachy, nie ciągną prądu + sn5 = dt * 0.0010; + else + sn5 = 0; + return sn1 + sn2 + sn3 + sn4 + sn5; +} + +// the drain of a battery switched off, very slow +double TMoverParameters::BatteryDrainSwitchedOff(double dt) const +{ + double sn1; + double sn2; + double sn3; + double sn4; + double sn5; + if (NominalBatteryVoltage / BatteryVoltage < 1.22) + sn1 = dt * 50; + else + sn1 = 0; + sn2 = dt * 0.000001; + sn3 = dt * 0.000001; + sn4 = dt * 0.000001; + sn5 = dt * 0.000001; // bardzo powolny spadek przy wyłączonych bateriach + return sn1 + sn2 + sn3 + sn4 + sn5; +} + +void TMoverParameters::MainsCheck(double const Deltatime) +{ + + // if( MainsInitTime == 0.0 ) { return; } + + // TBD, TODO: move voltage calculation to separate method and use also in power coupler state calculation? + auto localvoltage{0.0}; + switch (EnginePowerSource.SourceType) + { + case TPowerSource::CurrentCollector: + { + localvoltage = std::max(localvoltage, PantographVoltage); + break; + } + case TPowerSource::Accumulator: + { + localvoltage = std::max(localvoltage, Power24vVoltage); + break; + } + default: + { + break; + } + } + if (GensetSelected()) + { + // the traction selector of a dual-mode vehicle on the genset isolates the pantographs + localvoltage = Genset.voltage; + } + // a line breaker closed ahead of the pantographs gets ready on the low voltage circuits + auto const maincircuitpowersupply{std::abs(localvoltage) > 0.1 || GetTrainsetHighVoltage() > 0.1 || (PantographsRequireMains && (Power24vIsAvailable || Power110vIsAvailable))}; + + if (true == maincircuitpowersupply) + { + // all is well + if (MainsInitTimeCountdown >= 0.0) + { + // NOTE: we ensure main circuit readiness meets condition MainsInitTimeCountdown < 0 + // this allows for simpler rejection of cases where MainsInitTime == 0 + MainsInitTimeCountdown -= Deltatime; + } + else + { + // optional automatic circuit start + if (MainsStart != start_t::manual && false == (Mains || dizel_startup)) + { + MainSwitch(true); + } + } + } + else + { + // no power supply + MainsInitTimeCountdown = MainsInitTime; + } + + // an emergency brake application made under power opens the line breaker, where the vehicle has such an interlock + if (Mains && EmergencyBrakeHoldsMainOff()) + { + MainSwitch(false, TrainType == train_type::emu ? range_t::unit : range_t::local); + } +} + +void TMoverParameters::LowVoltagePowerCheck(double const /*Deltatime*/) +{ + + auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; + + if (EngineType == TEngineType::ElectricSeriesMotor) + { + GroundRelay &= lowvoltagepower; + if (GroundRelayStart != start_t::manual) + { + // NOTE: we're ignoring intricaties of battery and converter types as they're unlikely to be used + // TODO: generic check method which takes these into account + GroundRelay |= lowvoltagepower; + } + } +} + +void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling const Coupling) +{ + if (Coupling != coupling::highvoltage && Coupling != coupling::power110v && Coupling != coupling::power24v) + { + // only power couplings carry voltage + return; + } + + auto const localvoltage{LocalPowerVoltage(Coupling)}; + + auto const abslocalvoltage{std::abs(localvoltage)}; + auto const localpowersource{(abslocalvoltage > 1.0)}; + + // przekazywanie napiec + PowerCouplersVoltage(Coupling, abslocalvoltage, localpowersource); + + // przekazywanie pradow + PowerCouplersCurrent(Coupling, localpowersource); +} + +// the current the vehicle draws from the circuit of the power coupling given +double *TMoverParameters::PowerCircuitCurrent(coupling const Coupling) +{ + switch (Coupling) + { + case coupling::highvoltage: + return &TotalCurrent; + case coupling::power110v: + return &PowerCircuits[1].second; + case coupling::power24v: + return &PowerCircuits[0].second; + default: + return nullptr; + } +} + +// the voltage of the vehicle's own source for the coupling given; notes the low voltage circuits' too +double TMoverParameters::LocalPowerVoltage(coupling const Coupling) +{ + auto localvoltage{0.0}; + + // local power sources + // the results could be kept in the PowerCircuit fields + switch (Coupling) + { + + case coupling::highvoltage: + { + // heating power sources + if (Heating) + { + switch (HeatingPowerSource.SourceType) + { + case TPowerSource::Generator: + { + localvoltage = HeatingPowerSource.EngineGenerator.voltage - TotalCurrent * 0.02; + break; + } + case TPowerSource::CurrentCollector: + { + localvoltage = PantographVoltage; + break; + } + case TPowerSource::Main: + { + // HACK: main circuit can be fed through couplers, so we explicitly check pantograph supply here + // (or the genset's, where the traction selector of a dual-mode vehicle is on it) + localvoltage = MainCircuitPowered() ? TractionSourceVoltage() : 0.0; + break; + } + default: + { + break; + } + } + } + // high voltage power sources: the pantographs, or the genset of a dual-mode vehicle, by its traction selector + if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector) + { + localvoltage = std::max(localvoltage, TractionSourceVoltage()); + } + break; + } + + case coupling::power110v: + { + if (ConverterFlag) + { + localvoltage = NominalBatteryVoltage; + } + // TBD, TODO: reduce by current draw? + PowerCircuits[1].first = localvoltage; + break; + } + + case coupling::power24v: + { + if (Battery) + { + localvoltage = BatteryVoltage; + } + // TBD, TODO: reduce by current draw? + PowerCircuits[0].first = localvoltage; + break; + } + + default: + { + break; + } + } + + return localvoltage; +} + +// the voltage passed through the vehicle to the coupler at its other end, from the coupled vehicle or its own source +void TMoverParameters::PowerCouplersVoltage(coupling const Coupling, double const abslocalvoltage, bool const localpowersource) +{ + if (Couplers[end::front].power(Coupling) == nullptr) + { + // not a power coupling, there's no voltage to pass + return; + } + for (auto side = 0; side < 2; ++side) + { + + auto const &thiscoupler{Couplers[side]}; + // NOTE: in the loop we actually update the state of the coupler on the opposite end of the vehicle + auto &oppositecoupler{Couplers[side == end::front ? end::rear : end::front]}; + + bool oppositecouplingispresent; + bool localpowerexportisenabled; + + switch (Coupling) + { + + case coupling::highvoltage: + { + auto const oppositehighvoltagecoupling{(oppositecoupler.CouplingFlag & coupling::highvoltage) != 0}; + auto const oppositeheatingcoupling{(oppositecoupler.CouplingFlag & coupling::heating) != 0}; + + oppositecouplingispresent = oppositehighvoltagecoupling || oppositeheatingcoupling; + localpowerexportisenabled = oppositehighvoltagecoupling || (oppositeheatingcoupling && localpowersource && Heating); + break; + } + + case coupling::power110v: + { + oppositecouplingispresent = TestFlag(oppositecoupler.CouplingFlag, oppositecoupler.PowerCoupling) && (oppositecoupler.PowerFlag & coupling::power110v) != 0; + localpowerexportisenabled = oppositecouplingispresent; + break; + } + + case coupling::power24v: + { + oppositecouplingispresent = TestFlag(oppositecoupler.CouplingFlag, oppositecoupler.PowerCoupling) && (oppositecoupler.PowerFlag & coupling::power24v) != 0; + localpowerexportisenabled = oppositecouplingispresent; + break; + } + + default: + { + break; + } + } + + auto const *coupling = thiscoupler.power(Coupling); + auto *oppositecoupling = oppositecoupler.power(Coupling); + + // start with base voltage + oppositecoupling->voltage = abslocalvoltage; + oppositecoupling->is_live = false; + oppositecoupling->is_local = localpowersource; // indicate power source + // draw from external source + if (thiscoupler.Connected != nullptr) + { + auto const &connectedcoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr]}; + auto const *connectedcoupling = connectedcoupler.power(Coupling); + auto const connectedvoltage{(connectedcoupling->is_live ? connectedcoupling->voltage : 0.0)}; + oppositecoupling->voltage = std::max(oppositecoupling->voltage, connectedvoltage - coupling->current * 0.02); + oppositecoupling->is_live = connectedvoltage > 0.1 && oppositecouplingispresent; + } + // draw from local source + if (localpowersource) + { + oppositecoupling->voltage = std::max(oppositecoupling->voltage, abslocalvoltage - coupling->current * 0.02); + oppositecoupling->is_live |= abslocalvoltage > 0.1 && localpowerexportisenabled; + } + } +} + +// the current drawn through the couplers, shared by their voltages, or added to the vehicle's own +void TMoverParameters::PowerCouplersCurrent(coupling const Coupling, bool const localpowersource) +{ + auto const *frontcoupling{Couplers[end::front].power(Coupling)}; + auto const *rearcoupling{Couplers[end::rear].power(Coupling)}; + auto *totalcurrent{PowerCircuitCurrent(Coupling)}; + if (frontcoupling == nullptr || rearcoupling == nullptr || totalcurrent == nullptr) + { + // not a power coupling, there's no current to share + return; + } + auto const couplervoltage{static_cast(frontcoupling->voltage + rearcoupling->voltage)}; + + for (auto &thiscoupler : Couplers) + { + auto *coupling = thiscoupler.power(Coupling); + + coupling->current = 0.0; + + if (thiscoupler.Connected == nullptr) + { + continue; + } + + auto const &connectedothercoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr == end::front ? end::rear : end::front]}; + auto const *connectedothercoupling = connectedothercoupler.power(Coupling); + auto const extracurrent = Coupling == coupling::highvoltage ? std::abs(Itot) * IsVehicleEIMBrakingFactor() : 0.0; + + if (false == localpowersource) + { + // bez napiecia... + if (couplervoltage != 0.0) + { + // ...ale jest cos na sprzegach: + coupling->current = (*totalcurrent + extracurrent) * coupling->voltage / couplervoltage; // obciążenie rozkladane stosownie do napiec + if (true == coupling->is_live) + { + coupling->current += connectedothercoupling->current; + } + } + } + else + { + if (true == coupling->is_live) + { + *totalcurrent += connectedothercoupling->current; + } + } + } +} + +// sprawdzanie przetwornicy +void TMoverParameters::ConverterCheck(double const Timestep) +{ + // TODO: move other converter checks here, to have it all in one place for potential device object + if (ConverterStart != start_t::disabled && ConverterOverloadRelayOffWhenMainIsOff) + { + ConvOvldFlag |= !Mains && Power24vIsAvailable; + } + + switch (ConverterStart) + { + case start_t::disabled: + { + ConverterAllow = false; + // NOTE: if there's no converter in vehicle we can end the check here + return; + } + case start_t::automatic: + { + ConverterAllow = Mains; + break; + } + case start_t::direction: + { + ConverterAllow = DirActive != 0; + } + default: + { + break; + } + } + + if (ConverterAllow && ConverterAllowLocal && false == ConvOvldFlag && + false == PantPressLockActive + // HACK: allow carriages to operate converter without (missing) fuse prerequisite + && (Power > 1.0 ? MainCircuitPowered() : GetTrainsetHighVoltage() > 0.0)) + { + // delay timer can be optionally configured, and is set anew whenever converter goes off + if (ConverterStartDelayTimer <= 0.0) + { + ConverterFlag = true; + } + else + { + ConverterStartDelayTimer -= Timestep; + } + } + else + { + ConverterFlag = false; + ConverterStartDelayTimer = static_cast(ConverterStartDelay); + } + + if (ConverterOverloadRelayStart == start_t::converter && false == (ConverterAllow && ConverterAllowLocal) && false == TestFlag(EngDmgFlag, 4)) + { + // reset converter overload relay if the converter was switched off, unless it's damaged + ConvOvldFlag = false; + } +}; + +// heating system status check +void TMoverParameters::HeatingCheck(double const /*Timestep*/) +{ + + // update heating devices + // TBD, TODO: move this to a separate method? + if (HeatingPowerSource.SourceType == TPowerSource::Generator) + { + if (HeatingPowerSource.EngineGenerator.engine_revolutions != nullptr && HeatingPowerSource.EngineGenerator.revolutions_max > 0) + { + + auto &generator{HeatingPowerSource.EngineGenerator}; + // TBD, TODO: engine-generator transmission + generator.revolutions = *generator.engine_revolutions; + + auto const absrevolutions{std::abs(generator.revolutions)}; + generator.voltage = (false == HeatingAllow ? 0.0 : + // TODO: add support for desired voltage selector + absrevolutions < generator.revolutions_min ? + generator.voltage_min * absrevolutions / generator.revolutions_min : + // absrevolutions > generator.revolutions_max ? generator.voltage_max * absrevolutions / generator.revolutions_max : + std::lerp(generator.voltage_min, generator.voltage_max, + std::clamp((absrevolutions - generator.revolutions_min) / (generator.revolutions_max - generator.revolutions_min), 0.0, 1.0))) * + sign(generator.revolutions); + } + } + + // quick check first to avoid unnecessary calls... + if (false == HeatingAllow) + { + Heating = false; + return; + } + // ...detailed check if we're still here + auto const heatingpowerthreshold{0.1}; + // start with blank slate + auto voltage{0.0}; + // then try specified power source + switch (HeatingPowerSource.SourceType) + { + case TPowerSource::Generator: + { + voltage = HeatingPowerSource.EngineGenerator.voltage; + break; + } + case TPowerSource::CurrentCollector: + { + voltage = PantographVoltage; + break; + } + case TPowerSource::PowerCable: + { + if (HeatingPowerSource.PowerType == TPowerType::ElectricPower) + { + // TBD, TODO: limit input voltage to heating coupling type? + voltage = GetTrainsetHighVoltage(); + } + break; + } + case TPowerSource::Main: + { + voltage = MainCircuitPowered() ? TractionSupplyVoltage() : 0.0; + break; + } + default: + { + break; + } + } + + Heating = voltage > heatingpowerthreshold; + + if (Heating) + { + TotalCurrent += 1000 * HeatingPower / voltage; // heater power cost presumably specified in kilowatts + } +} + +void TMoverParameters::PantographsCheck(double const /*Timestep*/) +{ + using enum start_t; + + { + auto const &valve{PantsValve}; + auto const lowvoltagepower{valve.solenoid ? Power24vIsAvailable || Power110vIsAvailable : true}; + auto const autostart{valve.start_type == automatic || valve.start_type == manualwithautofallback}; + auto const manualcontrol{valve.start_type == manual || valve.start_type == manualwithautofallback}; + + PantsValve.is_active = (valve.spring ? lowvoltagepower : true) // spring actuator needs power to maintain non-default state + && (manualcontrol && lowvoltagepower ? false == valve.is_disabled : true) // needs power to change state + && (valve.is_active || (autostart ? lowvoltagepower : + !autostart ? lowvoltagepower && valve.is_enabled : + false)); // shouldn't ever get this far but, eh + } + + size_t pant_id = 0; + for (auto &pantograph : Pantographs) + { + + auto &valve{pantograph.valve}; + auto const lowvoltagepower{valve.solenoid ? Power24vIsAvailable || Power110vIsAvailable : true}; + auto const autostart{valve.start_type == automatic || valve.start_type == manualwithautofallback}; + auto const manualcontrol{valve.start_type == manual || valve.start_type == manualwithautofallback}; + + valve.is_active = (valve.spring ? lowvoltagepower : true) // spring actuator needs power to maintain non-default state + && (manualcontrol && lowvoltagepower ? false == valve.is_disabled : true) // needs power to change state, without it just pass through + && (manualcontrol && lowvoltagepower ? false == PantAllDown : true) && + (Mains || false == PantographsRequireMains) // fed through the closed line breaker, where it comes first + && (valve.is_active || (manualcontrol && lowvoltagepower && valve.is_enabled) || (autostart && lowvoltagepower)); // shouldn't ever get this far but, eh + + auto const pantographexists{EnginePowerSource.SourceType == TPowerSource::CurrentCollector && EnginePowerSource.CollectorParameters.PhysicalLayout & 1 << pant_id}; + + pantograph.is_active = valve.is_active && PantsValve.is_active && pantographexists; + + pant_id++; + } +} + +// the genset of a dual-mode vehicle: started on request with the battery on, it cranks for start_time, then runs at +// idle and up to full revolutions with the traction demand; stopped, it coasts down. regulated voltage from idle up +void TMoverParameters::GensetCheck(double const Deltatime) +{ + if (false == Genset.fitted()) + { + return; + } + auto &genset{Genset}; + auto const wasactive{genset.is_active}; + auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; + auto const requested{lowvoltagepower && false == genset.is_disabled && (genset.start_type == start_t::automatic ? GensetSelected() : genset.is_enabled)}; + if (false == requested) + { + genset.is_active = false; + genset.is_cranking = false; + genset.timer = 0.0; + } + else if (false == genset.is_active) + { + genset.is_cranking = true; + genset.timer += Deltatime; + if (genset.timer >= genset.start_time) + { + genset.is_cranking = false; + genset.is_active = true; + } + } + // revolutions: the start brings them up to idle in start_time; running they follow the traction demand, stopped + // they coast down to 0, both with the time constant spinup_time + if (genset.is_cranking) + { + genset.revolutions = std::max(genset.revolutions, genset.revolutions_idle * std::min(1.0, genset.timer / std::max(genset.start_time, 0.01))); + } + else if (genset.is_active && false == wasactive) + { + genset.revolutions = std::max(genset.revolutions, genset.revolutions_idle); + } + else + { + auto const demand{GensetSelected() && Mains ? std::clamp(eimv_pr, 0.0, 1.0) : 0.0}; + auto const target{genset.is_active ? genset.revolutions_idle + (genset.revolutions_max - genset.revolutions_idle) * demand : 0.0}; + genset.revolutions += (target - genset.revolutions) * std::min(1.0, Deltatime / genset.spinup_time); + if (genset.revolutions < 0.001) + { + genset.revolutions = 0.0; + } + } + // no excitation while cranking; running or coasting down, regulated from idle up, proportional below it + genset.voltage = genset.is_cranking ? 0.0 : genset.voltage_nominal * std::clamp(genset.revolutions / genset.revolutions_idle, 0.0, 1.0); + + if (genset.is_active != wasactive) + { + WriteLog("Genset of " + Name + (genset.is_active ? ": running" : ": stopped")); + } +} + +void TMoverParameters::LightsCheck(double const /*Timestep*/) +{ + + auto &light{CompartmentLights}; + + light.is_active = + // TODO: bind properly power source when ld is in place + (Power24vIsAvailable || Power110vIsAvailable) // power source + && false == light.is_disabled && (true == light.is_active || (light.start_type == start_t::manual ? light.is_enabled : true)); + + light.intensity = (light.is_active ? 1.0f : 0.0f) + // TODO: bind properly power source when ld is in place + * (Power110vIsAvailable ? 1.0f : + Power24vIsAvailable ? 0.5f : + 0.0f) * + light.dimming; +} + +// ************************************************************************************************* +// Q: 20160710 +// włączenie / wyłączenie baterii +// ************************************************************************************************* +bool TMoverParameters::BatterySwitch(bool State, range_t const Notify) +{ + using enum range_t; + if (PulleeMode && State) + { + // the battery of a vehicle prepared for hauling stays off + return false; + } + auto const initialstate{Battery}; + + // Ra: ukrotnienie załączania baterii jest jakąś fikcją... + if (BatteryStart == start_t::manual) + { + Battery = State; + } + + // switching batteries does not require activation + if (Notify != local) + { + SendCtrlToNext("BatterySwitch", State ? 1 : 0, 1, Notify == unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext("BatterySwitch", State ? 1 : 0, -1, Notify == unit ? coupling::control | coupling::permanent : coupling::control); + } + + return Battery != initialstate; +} + +bool TMoverParameters::CompartmentLightsSwitch(bool State, range_t const Notify) +{ + + if (CompartmentLights.start_type == start_t::automatic) + { + // automatic lights ignore 'manual' state commands + return false; + } + + bool const initialstate{CompartmentLights.is_enabled}; + + CompartmentLights.is_enabled = State; + + if (Notify != range_t::local) + { + SendCtrlToNext("CompartmentLightsSwitch", CompartmentLights.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return CompartmentLights.is_enabled != initialstate; +} + +// water pump state toggle +bool TMoverParameters::CompartmentLightsSwitchOff(bool State, range_t const Notify) +{ + + if (CompartmentLights.start_type == start_t::automatic) + { + // automatic lights ignore 'manual' state commands + return false; + } + + bool const initialstate{CompartmentLights.is_disabled}; + + CompartmentLights.is_disabled = State; + + if (Notify != range_t::local) + { + SendCtrlToNext("CompartmentLightsSwitchOff", CompartmentLights.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return CompartmentLights.is_disabled != initialstate; +} + +// ************************************************************************************************* +// Q: 20160713 +// włączenie / wyłączenie obwodu głownego +// ************************************************************************************************* +bool TMoverParameters::MainSwitch(bool const State, range_t const Notify) +{ + + bool const initialstate{Mains || dizel_startup}; + + MainSwitch_(State); + + if (Notify != range_t::local) + { + // pass the command to other vehicles + // TBD: pass the requested state, or the actual state? + SendCtrlToNext("MainSwitch", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return (Mains || dizel_startup) != initialstate; +} + +void TMoverParameters::MainSwitch_(bool const State) +{ + + if (Mains == State || MainCtrlPosNo == 0) + { + // nothing to do + return; + } + + bool const initialstate{Mains}; + + if (false == State || true == MainSwitchCheck()) + { + + if (true == State) + { + // switch on + if (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric) + { + // launch diesel engine startup procedure + dizel_startup = true; + } + else + { + // additional check, as vehicles without pantographs won't fail relay checks earlier + Mains = true; + } + } + else + { + Mains = false; + // potentially knock out the pumps if their switch doesn't force them on + WaterPump.is_active &= WaterPump.is_enabled; + FuelPump.is_active &= FuelPump.is_enabled; + } + + if (Mains != initialstate) + { + LastSwitchingTime = 0; + Timer::subsystem.switching.note(Timer::switching_counter::mains, this, &TypeName, &Name); + } + } +} + +bool TMoverParameters::MainSwitchCheck() const +{ + using enum TEngineType; + + // prevent the switch from working if there's no power + // TODO: consider whether it makes sense for diesel engines and such + bool powerisavailable{true}; + + switch (EngineType) + { + case DieselElectric: + case DieselEngine: + case Dumb: + { + powerisavailable = Power24vIsAvailable; + break; + } + case ElectricSeriesMotor: + case ElectricInductionMotor: + { + // TODO: check whether we can simplify this check and skip the outer EngineType switch + // closed ahead of the pantographs, the line breaker runs on the low voltage circuits + powerisavailable = PantographsRequireMains ? Power24vIsAvailable || Power110vIsAvailable : EnginePowerSourceVoltage() > 0.5 * EnginePowerSource.MaxVoltage; + break; + } + default: + { + break; + } + } + if (GensetSelected()) + { + // on the genset of a dual-mode vehicle the line breaker closes only on a running one, whatever the pantographs give + powerisavailable = Genset.is_active && Genset.voltage >= TractionSupplyMinVoltage(); + } + + return powerisavailable && (ScndCtrlPos == 0 || EngineType == ElectricInductionMotor) && MainsInitTimeCountdown <= 0.0 && + (ConvOvldFlag == false || ConverterOverloadRelayOffWhenMainIsOff) && true == GroundRelay && (true == NoVoltRelay || PantographsRequireMains) && true == OvervoltageRelay && + LastSwitchingTime > CtrlDelay && + (HasCamshaft ? IsMainCtrlActualNoPowerPos() : + LineBreakerClosesOnlyAtNoPowerPos ? IsMainCtrlNoPowerPos() : + true) && + false == TestFlag(DamageFlag, dtrain_out) && false == TestFlag(EngDmgFlag, 1) && false == EmergencyBrakeHoldsMainOff(); +} + +// ************************************************************************************************* +// Q: 20160713 +// włączenie / wyłączenie przetwornicy +// ************************************************************************************************* +bool TMoverParameters::ConverterSwitch(bool State, range_t const Notify) +{ + + auto const initialstate{ConverterAllow}; + + if (ConverterStart == start_t::manual) + { + ConverterAllow = State; + } + + if (Notify != range_t::local) + { + SendCtrlToNext("ConverterSwitch", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return ConverterAllow != initialstate; +} + +bool TMoverParameters::HeatingSwitch(bool const State, range_t const Notify) +{ + + bool const initialstate{HeatingAllow}; + + HeatingSwitch_(State); + + if (Notify != range_t::local) + { + // pass the command to other vehicles + // TBD: pass the requested state, or the actual state? + SendCtrlToNext("HeatingSwitch", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return HeatingAllow != initialstate; +} + +void TMoverParameters::HeatingSwitch_(bool const State) +{ + + // TBD, TODO: activation dependencies? + HeatingAllow = State; +} + +// the start request of the genset of a dual-mode vehicle; one which starts on its own ignores it, but passes it on to +// the cars behind, which may start theirs on request +bool TMoverParameters::GensetSwitch(bool const State, range_t const Notify) +{ + auto const initialstate{Genset.is_enabled}; + + if (Genset.start_type != start_t::automatic) + { + Genset.is_enabled = State; + } + + if (Notify != range_t::local) + { + SendCtrlToNext("GensetSwitch", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return Genset.is_enabled != initialstate; +} + +// the voltage of the vehicle's own source the traction selector picks: the catenary through the pantographs, or the +// genset of a dual-mode vehicle +double TMoverParameters::TractionSourceVoltage() const +{ + return GensetSelected() ? Genset.voltage : PantographVoltage; +} + +// the voltage the traction circuit gets: from the vehicle's own source, or through the train's high voltage line +double TMoverParameters::TractionSupplyVoltage() const +{ + return std::max(GetTrainsetHighVoltage(), TractionSourceVoltage()); +} + +// below it the undervoltage trip opens the line breaker +double TMoverParameters::TractionSupplyMinVoltage() const +{ + return GensetSelected() ? 0.5 * Genset.voltage_nominal : EnginePowerSource.CollectorParameters.MinV; +} + +// the power the traction may take [kW, at the wheels]: the genset's share at its present revolutions on the genset, +// no limit otherwise +double TMoverParameters::GensetTractionPowerLimit() const +{ + return GensetSelected() ? Genset.available_power() * Genset.traction_share : std::numeric_limits::max(); +} + +// the current the vehicle draws through its pantographs [A], if they touch the wire: the traction's (none while +// braking on the resistors) and the heating's. on the genset the genset feeds the traction circuit, so only a heating +// fed straight from the pantographs is left +double TMoverParameters::CatenaryCurrent() const +{ + if (GensetSelected()) + { + return HeatingPowerSource.SourceType == TPowerSource::CurrentCollector ? TotalCurrent : 0.0; + } + return (DynamicBrakeFlag && ResistorsFlag ? 0 : std::abs(Itot) * IsVehicleEIMBrakingFactor()) + TotalCurrent; +} + +// returns voltage of defined main engine power source +double TMoverParameters::EnginePowerSourceVoltage() const +{ + + return EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? TractionSupplyVoltage() : + EnginePowerSource.SourceType == TPowerSource::Accumulator ? Power24vVoltage : + 0.0; +} + +// whether the main circuit feeds what runs on it: the converter, a compressor, the heating, the motor and resistor +// blowers, the traction motors +bool TMoverParameters::MainCircuitPowered() const +{ + if (false == Mains) + { + return false; + } + if (false == PantographsRequireMains || EnginePowerSource.SourceType != TPowerSource::CurrentCollector) + { + // the closed line breaker says it all: the undervoltage trip opens it without traction voltage, and an engine + // which runs is its own supply + return true; + } + // closed ahead of the pantographs the line breaker holds without the voltage, which the undervoltage trip isn't + // there to vouch for + return EnginePowerSourceVoltage() >= TractionSupplyMinVoltage(); +} + +bool TMoverParameters::OperatePantographsValve(operation_t const State, range_t const Notify) +{ + + if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector && EnginePowerSource.CollectorParameters.CollectorsNo > 0) + { + + auto &valve{PantsValve}; + + switch (State) + { + using enum operation_t; + case none: + { + valve.is_enabled = false; + valve.is_disabled = false; + break; + } + case enable: + { + valve.is_enabled = true; + valve.is_disabled = false; + break; + } + case disable: + { + valve.is_enabled = false; + valve.is_disabled = true; + break; + } + case enable_on: + { + valve.is_enabled = true; + break; + } + case enable_off: + { + valve.is_enabled = false; + break; + } + case disable_on: + { + valve.is_disabled = true; + break; + } + case disable_off: + { + valve.is_disabled = false; + break; + } + } + } + + if (Notify != range_t::local) + { + SendCtrlToNext("PantsValve", static_cast(State), CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return true; +} + +bool TMoverParameters::OperatePantographValve(end const End, operation_t const State, range_t const Notify) +{ + + if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector && EnginePowerSource.CollectorParameters.CollectorsNo > 0) + { + + auto &valve{Pantographs[End].valve}; + + switch (State) + { + using enum operation_t; + case none: + { + valve.is_enabled = false; + valve.is_disabled = false; + break; + } + case enable: + { + valve.is_enabled = true; + valve.is_disabled = false; + break; + } + case disable: + { + valve.is_enabled = false; + valve.is_disabled = true; + break; + } + case enable_on: + { + valve.is_enabled = true; + break; + } + case enable_off: + { + valve.is_enabled = false; + break; + } + case disable_on: + { + valve.is_disabled = true; + break; + } + case disable_off: + { + valve.is_disabled = false; + break; + } + } + } + + if (Notify != range_t::local) + { + SendCtrlToNext("PantValve", + // HACK: pack the state, pantograph index and sender cab into 8-bit value + // with high bit storing front/rear pantograph, and 7th bit storing sender cab + static_cast(0x80 * (End == end::front ? 0 : 1) + 0x40 * (CabActive != -1 ? 1 : 0) + static_cast(State)), CabActive, + Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return true; +} + +bool TMoverParameters::DropAllPantographs(bool const State, range_t const Notify) +{ + + auto const initialstate{PantAllDown}; + + PantAllDown = State; + + if (Notify != range_t::local) + { + SendCtrlToNext("PantAllDown", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return State != initialstate; +} + +// ************************************************************************************************* +// Q: 20160709 +// Funkcja zwracajaca napiecie dla calego skladu, przydatna dla EZT +// ************************************************************************************************* +double TMoverParameters::GetTrainsetVoltage(int const Coupling) const +{ // ABu: funkcja zwracajaca napiecie dla calego skladu, przydatna dla EZT + // TBD, TODO: call once per vehicle update, return cached results? + std::array voltages{0.0, 0.0}; + for (int end = end::front; end <= end::rear; ++end) + { + if (Couplers[end].Connected == nullptr) + { + continue; + } + auto const &thiscoupler{Couplers[end]}; + if (auto const fullcoupling{thiscoupler.CouplingFlag | (TestFlag(thiscoupler.CouplingFlag, thiscoupler.PowerCoupling) ? thiscoupler.PowerFlag : 0)}; (fullcoupling & Coupling) == 0) + { + continue; + } + auto const *connectedpowercoupling = (Coupling & (coupling::highvoltage | coupling::heating)) != 0 ? &thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr].power_high : + (Coupling & coupling::power110v) != 0 ? &thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr].power_110v : + (Coupling & coupling::power24v) != 0 ? &thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr].power_24v : + nullptr; + if (connectedpowercoupling != nullptr && connectedpowercoupling->is_live) + { + voltages[end] = connectedpowercoupling->voltage; + } + } + return std::max(voltages[end::front], voltages[end::rear]); +} + +double TMoverParameters::GetTrainsetHighVoltage() const +{ + + return std::max(GetTrainsetVoltage(coupling::highvoltage), HeatingAllow ? GetTrainsetVoltage(coupling::heating) : 0.0); +} + +int TMoverParameters::clampDimmerPosition(int const Position) const +{ + if (dimPositions.empty()) + { + return 0; + } + return std::clamp(Position, 0, static_cast(dimPositions.size()) - 1); +} + +TMoverParameters::dimPosition TMoverParameters::currentDimPosition() const +{ + if (modernDimmerPosition < 0 || modernDimmerPosition >= static_cast(dimPositions.size())) + { + return {}; + } + return dimPositions[modernDimmerPosition]; +} + +bool TMoverParameters::stepDimmerPosition(int const Step) +{ + if (dimPositions.empty()) + { + return false; + } + auto const last{static_cast(dimPositions.size()) - 1}; + auto const current{clampDimmerPosition(modernDimmerPosition)}; + auto next{current + Step}; + if (next < 0 || next > last) + { + if (false == modernDimmerCanCycle) + { + next = current; + } + else + { + next = (next < 0 ? last : 0); + } + } + if (next == modernDimmerPosition) + { + return false; + } + modernDimmerPosition = next; + return true; +} + +std::optional TMoverParameters::LightsPresetCabLight(int const Position) const +{ + if (Position < 1 || Position > static_cast(LightsCabLight.size())) + { + return std::nullopt; + } + auto const flags{LightsCabLight[Position - 1]}; + if (flags < 0) + { + return std::nullopt; + } + return lights_preset_cablight{(flags & lights_preset_cablight::light_on) != 0, (flags & lights_preset_cablight::light_dimmed) != 0}; +} diff --git a/physics/mover/fizparser.cpp b/physics/mover/fizparser.cpp new file mode 100644 index 000000000..a0a293682 --- /dev/null +++ b/physics/mover/fizparser.cpp @@ -0,0 +1,1341 @@ +/* +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/. +*/ + +// reading the vehicle definition (.fiz): the parser and its tables + +#include "stdafx.h" +#include "physics/mover.h" +#include "vehicle/DynObj.h" +#include "physics/oerlikonest.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/Timer.h" +#include "utilities/parser.h" +#include "simulation/simulation.h" +#include "vehicle/fieldshunting.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "physics/mover/internal.h" + + +int ConversionError = 0; + +// ************************************************************************************************* +// FUNKCJE PARSERA WCZYTYWANIA PLIKU FIZYKI POJAZDU +// ************************************************************************************************* +bool startBPT; +bool startMPT; +bool startMPT0; +bool startRLIST; +bool startUCLIST; +bool startDIZELMOMENTUMLIST; +bool startDIZELV2NMAXLIST; +bool startHYDROTCLIST; +bool startPMAXLIST; +bool startDLIST; +bool startFFLIST; +bool startWWLIST; +bool startWiperList; +bool startDimmerList; +bool startFFEDLIST; +bool startLIGHTSLIST; +bool startCOMPRESSORLIST; +int LISTLINE; + +bool issection(std::string_view Name, std::string_view Input) +{ + + return Input.compare(0, Name.size(), Name) == 0; +} + +// ************************************************************************************************* +// Q: 20160717 +// ************************************************************************************************* +// parsowanie Motor Param Table +// checks a motor parameter table position read from the .fiz file against the table size +static bool is_valid_mpt_index(int const Index) +{ + if (Index >= 0 && Index <= MotorParametersArraySize) + { + return true; + } + WriteLog("Read MPT: position " + std::to_string(Index) + " out of range 0-" + std::to_string(MotorParametersArraySize) + " in line " + std::to_string(LISTLINE)); + return false; +} + +bool TMoverParameters::readMPT0(std::string const &line) +{ + + // TBD, TODO: split into separate functions similar to readMPT if more varied schemes appear? + cParser parser(line); + if (false == parser.getTokens(7, false)) + { + WriteLog("Read MPT0: arguments missing in line " + std::to_string(LISTLINE)); + return false; + } + int idx = 0; // numer pozycji + parser >> idx; + if (false == is_valid_mpt_index(idx)) + { + return false; + } + if (EngineType == TEngineType::DieselEngine) + { + parser >> MotorParam[idx].mIsat >> MotorParam[idx].fi0 >> MotorParam[idx].fi >> MotorParam[idx].mfi0 >> MotorParam[idx].mfi >> MotorParam[idx].Isat; + } + else + { + parser >> MotorParam[idx].mfi >> MotorParam[idx].mIsat >> MotorParam[idx].mfi0 >> MotorParam[idx].fi >> MotorParam[idx].Isat >> MotorParam[idx].fi0; + } + if (true == parser.getTokens(1, false)) + { + int autoswitch{0}; + parser >> autoswitch; + MotorParam[idx].AutoSwitch = autoswitch == 1; + } + else + { + MotorParam[idx].AutoSwitch = false; + } + return true; +} + +bool TMoverParameters::readMPT(std::string const &line) +{ + + ++LISTLINE; + + switch (EngineType) + { + + case TEngineType::ElectricSeriesMotor: + { + return readMPTElectricSeries(line); + } + case TEngineType::DieselElectric: + { + return readMPTDieselElectric(line); + } + case TEngineType::DieselEngine: + { + return readMPTDieselEngine(line); + } + default: + { + return false; + } + } +} + +bool TMoverParameters::readMPTElectricSeries(std::string const &line) +{ + + cParser parser(line); + if (false == parser.getTokens(5, false)) + { + WriteLog("Read MPT: arguments missing in line " + std::to_string(LISTLINE)); + return false; + } + int idx = 0; // numer pozycji + parser >> idx; + if (false == is_valid_mpt_index(idx)) + { + return false; + } + parser >> MotorParam[idx].mfi >> MotorParam[idx].mIsat >> MotorParam[idx].fi >> MotorParam[idx].Isat; + if (true == parser.getTokens(1, false)) + { + int autoswitch{0}; + parser >> autoswitch; + MotorParam[idx].AutoSwitch = autoswitch == 1; + } + else + { + MotorParam[idx].AutoSwitch = false; + } + return true; +} + +bool TMoverParameters::readMPTDieselElectric(std::string const &line) +{ + + cParser parser(line); + if (false == parser.getTokens(7, false)) + { + WriteLog("Read MPT: arguments missing in line " + std::to_string(LISTLINE)); + return false; + } + int idx = 0; // numer pozycji + parser >> idx; + if (false == is_valid_mpt_index(idx)) + { + return false; + } + parser >> MotorParam[idx].mfi >> MotorParam[idx].mIsat >> MotorParam[idx].fi >> MotorParam[idx].Isat >> MPTRelay[idx].Iup >> MPTRelay[idx].Idown; + + return true; +} + +bool TMoverParameters::readMPTDieselEngine(std::string const &line) +{ + + cParser parser(line); + if (false == parser.getTokens(4, false)) + { + WriteLog("Read MPT: arguments missing in line " + std::to_string(LISTLINE)); + return false; + } + int idx = 0; // numer pozycji + parser >> idx; + if (false == is_valid_mpt_index(idx)) + { + return false; + } + parser >> MotorParam[idx].mIsat >> MotorParam[idx].fi >> MotorParam[idx].mfi; + if (true == parser.getTokens(1, false)) + { + int autoswitch{0}; + parser >> autoswitch; + MotorParam[idx].AutoSwitch = autoswitch == 1; + } + else + { + MotorParam[idx].AutoSwitch = false; + } + return true; +} + +bool TMoverParameters::readBPT(std::string const &line) +{ + + cParser parser(line); + if (false == parser.getTokens(5, false)) + { + + WriteLog("Read BPT: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + ++LISTLINE; + std::string braketype; + int idx = 0; + parser >> idx; + parser >> BrakePressureTable[idx].PipePressureVal >> BrakePressureTable[idx].BrakePressureVal >> BrakePressureTable[idx].FlowSpeedVal >> braketype; + if (braketype == "Pneumatic") + { + BrakePressureTable[idx].BrakeType = TBrakeSystem::Pneumatic; + } + else if (braketype == "ElectroPneumatic") + { + BrakePressureTable[idx].BrakeType = TBrakeSystem::ElectroPneumatic; + } + else + { + BrakePressureTable[idx].BrakeType = TBrakeSystem::Individual; + } + + return true; +} + +bool TMoverParameters::readRList(std::string const &Input) +{ + + cParser parser(Input); + if (false == parser.getTokens(5, false)) + { + + WriteLog("Read RList: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + auto idx = LISTLINE++; + if (idx >= std::size(RList)) + { + WriteLog("Read RList: number of entries exceeded capacity of the data table"); + return false; + } + parser >> RList[idx].Relay >> RList[idx].R >> RList[idx].Bn >> RList[idx].Mn >> RList[idx].AutoSwitch; + + if (true == parser.getTokens(1, false)) + { + parser >> RList[idx].ScndAct; + } + else + { + RList[idx].ScndAct = 0; + } + + return true; +} + +bool TMoverParameters::readUCList(std::string const &line) +{ + + cParser parser(line); + parser.getTokens(10, false); + auto idx = LISTLINE++; + if (idx >= std::size(UniCtrlList)) + { + WriteLog("Read UCList: number of entries exceeded capacity of the data table"); + return false; + } + int i = 0; + parser >> i >> UniCtrlList[idx].mode >> UniCtrlList[idx].MinCtrlVal >> UniCtrlList[idx].MaxCtrlVal >> UniCtrlList[idx].SetCtrlVal >> UniCtrlList[idx].SpeedUp >> UniCtrlList[idx].SpeedDown >> + UniCtrlList[idx].ReturnPosition >> UniCtrlList[idx].NextPosFastInc >> UniCtrlList[idx].PrevPosFastDec; + + return true; +} + +bool TMoverParameters::readDList(std::string const &line) +{ + + cParser parser(line); + parser.getTokens(3, false); + auto idx = LISTLINE++; + if (idx >= std::size(RList)) + { + WriteLog("Read DList: number of entries exceeded capacity of the data table"); + return false; + } + parser >> RList[idx].Relay >> RList[idx].R >> RList[idx].Mn; + + return true; +} + +bool TMoverParameters::readDMList(std::string const &line) +{ + + cParser parser(line); + if (false == parser.getTokens(2, false)) + { + + WriteLog("Read DMList: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + ++LISTLINE; + double x = 0.0; + double y = 0.0; + parser >> x >> y; + + dizel_Momentum_Table.emplace(x / 60.0, y); + + return true; +} + +bool TMoverParameters::readV2NMAXList(std::string const &line) +{ + + cParser parser(line); + if (false == parser.getTokens(2, false)) + { + + WriteLog("Read V2nmaxList: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + ++LISTLINE; + double x = 0.0; + double y = 0.0; + parser >> x >> y; + + dizel_vel2nmax_Table.emplace(x, y / 60.0); + + return true; +} + +bool TMoverParameters::readHTCList(std::string const &line) +{ + + cParser parser(line); + if (false == parser.getTokens(2, false)) + { + + WriteLog("Read HTCList: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + ++LISTLINE; + double x = 0.0; + double y = 0.0; + parser >> x >> y; + + hydro_TC_Table.emplace(x, y); + + return true; +} + +bool TMoverParameters::readPmaxList(std::string const &line) +{ + + cParser parser(line); + if (false == parser.getTokens(2, false)) + { + + WriteLog("Read PmaxList: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + ++LISTLINE; + double x = 0.0; + double y = 0.0; + parser >> x >> y; + + EIM_Pmax_Table.emplace(x, y); + + return true; +} + +bool TMoverParameters::readFFList(std::string const &line) +{ + + cParser parser(line); + if (false == parser.getTokens(2, false)) + { + WriteLog("Read FList: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + int idx = LISTLINE++; + if (idx >= std::size(FFlist)) + { + WriteLog("Read FList: number of entries exceeded capacity of the data table"); + return false; + } + parser >> FFlist[idx].v >> FFlist[idx].freq; + + return true; +} + +bool TMoverParameters::readFFEDList(std::string const &line) +{ + + cParser parser(line); + if (false == parser.getTokens(2, false)) + { + WriteLog("Read FList: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + int idx = LISTLINE++; + if (idx >= std::size(FFEDlist)) + { + WriteLog("Read FList: number of entries exceeded capacity of the data table"); + return false; + } + parser >> FFEDlist[idx].v >> FFEDlist[idx].freq; + + return true; +} + +// parsowanie wiperList +bool TMoverParameters::readWiperList(std::string const &line) +{ + cParser parser(line); + if (false == parser.getTokens(4, false)) + { + WriteLog("Read WiperList: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + int idx = LISTLINE++; + if (idx >= std::size(WiperList)) + { + WriteLog("Read WiperList: number of entries exceeded capacity of the data table"); + return false; + } + parser >> WiperList[idx].byteSum >> WiperList[idx].WiperSpeed >> WiperList[idx].interval >> WiperList[idx].outBackDelay; + return true; +} + +bool TMoverParameters::readDimmerList(std::string const &line) +{ + cParser parser(line); + if (false == parser.getTokens(3, false)) + { + WriteLog("Read DimmerList: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + ++LISTLINE; + + dimPosition dps; + parser >> dps.isHighBeam >> dps.isDimmed >> dps.isOff; + dimPositions.push_back(dps); + return true; +} + +// parsowanie WWList +bool TMoverParameters::readWWList(std::string const &line) +{ + + cParser parser(line); + if (false == parser.getTokens(4, false)) + { + WriteLog("Read WWList: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + int idx = LISTLINE++; + if (idx >= std::size(DElist)) + { + WriteLog("Read WWList: number of entries exceeded capacity of the data table"); + return false; + } + parser >> DElist[idx].RPM >> DElist[idx].GenPower >> DElist[idx].Umax >> DElist[idx].Imax; + + if (true == parser.getTokens(3, false)) + { + // optional parameters for shunt mode + parser >> SST[idx].Umin >> SST[idx].Umax >> SST[idx].Pmax; + + SST[idx].Pmin = std::sqrt(std::pow(SST[idx].Umin, 2) / 47.6); + SST[idx].Pmax = std::min(SST[idx].Pmax, std::pow(SST[idx].Umax, 2) / 47.6); + } + return true; +} + +bool TMoverParameters::readLightsList(std::string const &Input) +{ + + cParser parser(Input); + if (false == parser.getTokens(2, false)) + { + WriteLog("Read LightsList: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + int idx = LISTLINE++; + if (idx > 16) + { + WriteLog("Read LightsList: number of entries exceeded capacity of the data table"); + return false; + } + parser >> Lights[0][idx] >> Lights[1][idx]; + // optional third column: the cab interior light the preset sets (eu07/maszyna#529). anything but a whole number + // (some rows carry stray notes after the two columns) leaves the cab light to its own switch + LightsCabLight[idx] = -1; + if (true == parser.getTokens(1, false)) + { + std::string cablight; + parser >> cablight; + int flags{-1}; + auto const [end, error]{std::from_chars(cablight.data(), cablight.data() + cablight.size(), flags)}; + if (error == std::errc{} && end == cablight.data() + cablight.size() && flags >= 0) + { + LightsCabLight[idx] = flags; + } + } + + return true; +} + +bool TMoverParameters::readCompressorList(std::string const &Input) +{ + + cParser parser(Input); + if (false == parser.getTokens(4, false)) + { + WriteLog("Read CompressorList: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + int idx = LISTLINE++; + if (idx > 8 - 1) + { + WriteLog("Read CompressorList: number of entries exceeded capacity of the data table"); + return false; + } + // NOTE: content of slot [x][0] is hardcoded elsewhere + parser >> CompressorList[0][idx + 1] >> CompressorList[1][idx + 1] >> CompressorList[2][idx + 1] >> CompressorList[3][idx + 1]; + + return true; +} + +// ************************************************************************************************* +// Q: 20160719 +// ************************************************************************************************* +void TMoverParameters::BrakeValveDecode(std::string const &Valve) +{ + using enum TBrakeValve; + + std::map> valvetypes{{"W", W}, + {"W_Lu_L", W_Lu_L}, + {"W_Lu_XR", W_Lu_XR}, + {"W_Lu_VI", W_Lu_VI}, + {"K", K}, + {"Kg", Kg}, + {"Kp", Kp}, + {"Kss", Kss}, + {"Kkg", Kkg}, + {"Kkp", Kkp}, + {"Kks", Kks}, + {"Hikp1", Hikp1}, + {"Hikss", Hikss}, + {"Hikg1", Hikg1}, + {"KE", KE}, + {"SW", SW}, + {"EStED", EStED}, + {"NESt3", NESt3}, + {"ESt3", ESt3}, + {"LSt", LSt}, + {"ESt4", ESt4}, + {"ESt3AL2", ESt3AL2}, + {"EP1", EP1}, + {"EP2", EP2}, + {"M483", M483}, + {"CV1_L_TR", CV1_L_TR}, + {"CV1", CV1}, + {"CV1_R", CV1_R}}; + auto lookup = valvetypes.find(Valve); + BrakeValve = lookup != valvetypes.end() ? lookup->second : Other; + + if (BrakeValve == Other && contains(Valve, "ESt")) + { + + BrakeValve = ESt3; + } +} + +// ************************************************************************************************* +// Q: 20160719 +// ************************************************************************************************* +void TMoverParameters::BrakeSubsystemDecode() +{ + using enum TBrakeSubSystem; + BrakeSubsystem = ss_None; + switch (BrakeValve) + { + using enum TBrakeValve; + case W: + case W_Lu_L: + case W_Lu_VI: + case W_Lu_XR: + BrakeSubsystem = ss_W; + break; + case ESt3: + case ESt3AL2: + case ESt4: + case EP2: + case EP1: + BrakeSubsystem = ss_ESt; + break; + case KE: + BrakeSubsystem = ss_KE; + break; + case CV1: + case CV1_L_TR: + BrakeSubsystem = ss_Dako; + break; + case LSt: + case EStED: + BrakeSubsystem = ss_LSt; + break; + default: + break; + } +} + +// ************************************************************************************************* +// Q: 20160717 +// Funkcja pelniaca role pierwotnej LoadChkFile wywolywana w dynobj.cpp w double +// TDynamicObject::Init() +// Po niej wykonywana jest CreateBrakeSys(), ktora jest odpowiednikiem CheckLocomotiveParameters() +// ************************************************************************************************* +bool TMoverParameters::LoadFIZ(std::string const &chkpath) +{ + chkPath = chkpath; // assign class path for reloading + + ConversionError = 666; + std::string file = TypeName + ".fiz"; + + WriteLog("LOAD FIZ FROM " + file); + /* + std::ifstream in(file); + if (!in.is_open()) + { + WriteLog("E8 - FIZ FILE NOT EXIST."); + return false; + } + */ + cParser fizparser(file, cParser::buffer_FILE, chkpath); + if (false == fizparser.ok()) + { + WriteLog("E8 - FIZ FILE NOT EXIST."); + return false; + } + + return LoadFIZ_Parse(fizparser); +} + +// reads the vehicle definition from text in the .fiz format, e.g. one made up by a unit test +bool TMoverParameters::LoadFIZ_Text(std::string const &Text) +{ + ConversionError = 666; + cParser fizparser(Text, cParser::buffer_TEXT); + return LoadFIZ_Parse(fizparser); +} + +bool TMoverParameters::LoadFIZ_Parse(cParser &fizparser) +{ + LISTLINE = 0; + startBPT = false; + startMPT = false; + startMPT0 = false; + startRLIST = false; + startUCLIST = false; + startDLIST = false; + startDIZELMOMENTUMLIST = false; + startDIZELV2NMAXLIST = false; + startHYDROTCLIST = false; + startPMAXLIST = false; + startFFLIST = false; + startFFEDLIST = false; + startWWLIST = false; + startWiperList = false; + startDimmerList = false; + startLIGHTSLIST = false; + startCOMPRESSORLIST = false; + + ConversionError = 0; + + // Zbieranie danych zawartych w pliku FIZ + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + std::map> fizlines; + std::string inputline; + /* + while (std::getline(in, inputline)) + */ + while (fizparser.ok()) + { + + inputline = fizparser.getToken(false, "\n\r"); + + if (inputline.starts_with("//") || contains(inputline, '#')) + { + // skip commented lines + continue; + } + + if (!inputline.empty() && inputline.front() == ' ') + { + // guard against malformed config files with leading spaces + inputline.erase(0, inputline.find_first_not_of(' ')); + } + + // trim CR at end (mainly for linux) + if (!inputline.empty() && inputline.back() == '\r') + inputline.pop_back(); + + if (inputline.length() == 0) + { + startBPT = false; + continue; + } + + if (LoadFIZ_TableEnd(inputline) || LoadFIZ_Section(inputline, fizlines) || LoadFIZ_TableSection(inputline, fizlines)) + { + continue; + } + LoadFIZ_TableRow(inputline); + } // while line + /* + in.close(); + */ + // Operacje na zebranych parametrach - przypisywanie do wlasciwych zmiennych i ustawianie + // zaleznosci + + bool result; + if (ConversionError == 0) + result = true; + else + result = false; + + // ustawiamy domyslna pozycje dimmera + // the DefaultPos of a short or an empty DimmerList would put the dimmer outside of it + modernDimmerDefaultPosition = clampDimmerPosition(modernDimmerDefaultPosition); + modernDimmerPosition = clampDimmerPosition(modernDimmerPosition); + if (!enableModernDimmer) + { + modernDimmerPosition = modernDimmerDefaultPosition; + } + + WriteLog("CERROR: " + std::to_string(ConversionError) + ", SUCCES: " + std::to_string(result)); + return result; +} + +// the end of the table being read; returns whether the line is one +bool TMoverParameters::LoadFIZ_TableEnd(std::string const &inputline) const +{ + // checking if table parsing should be switched off goes first... + if (issection("END-MPT", inputline)) + { + startBPT = false; + startMPT = false; + startMPT0 = false; + return true; + } + if (issection("END-RL", inputline)) + { + startBPT = false; + startRLIST = false; + return true; + } + if (issection("END-UCL", inputline)) + { + startBPT = false; + startUCLIST = false; + return true; + } + if (issection("END-DL", inputline)) + { + startBPT = false; + startDLIST = false; + return true; + } + if (issection("END-DML", inputline)) + { + startBPT = false; + startDIZELMOMENTUMLIST = false; + return true; + } + if (issection("END-V2NL", inputline)) + { + startBPT = false; + startDIZELV2NMAXLIST = false; + return true; + } + if (issection("END-HTCL", inputline)) + { + startBPT = false; + startHYDROTCLIST = false; + return true; + } + if (issection("END-PML", inputline)) + { + startBPT = false; + startPMAXLIST = false; + return true; + } + if (issection("endff", inputline)) + { + startBPT = false; + startFFLIST = false; + startFFEDLIST = false; + return true; + } + if (issection("endwl", inputline)) + { + // skonczylismy czytac liste konfiguracji wycieraczek + startBPT = false; + startWiperList = false; + return true; + } + if (issection("endDimmerList", inputline)) + { + // skonczylismy czytac liste konfiguracji pstryka od przyciemnienia + startBPT = false; + startDimmerList = false; + return true; + } + if (issection("END-WWL", inputline)) + { + startBPT = false; + startWWLIST = false; + return true; + } + if (issection("endL", inputline)) + { + startBPT = false; + startLIGHTSLIST = false; + return true; + } + if (issection("endCL", inputline)) + { + startBPT = false; + startCOMPRESSORLIST = false; + return true; + } + return false; +} + +// a section of the definition giving values, kept in fizlines by its name; returns whether the line is one +bool TMoverParameters::LoadFIZ_Section(std::string const &inputline, std::map> &fizlines) +{ + // ...then all recognized sections... + if (issection("Param.", inputline)) + { + startBPT = false; + fizlines.try_emplace("Param", inputline); + LoadFIZ_Param(inputline); + return true; + } + + if (issection("Load:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Load", inputline); + LoadFIZ_Load(inputline); + return true; + } + + if (issection("Dimensions:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Dimensions", inputline); + LoadFIZ_Dimensions(inputline); + return true; + } + + if (issection("Wheels:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Wheels", inputline); + LoadFIZ_Wheels(inputline); + return true; + } + + if (issection("Brake:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Brake", inputline); + LoadFIZ_Brake(inputline); + return true; + } + + if (issection("Doors:", inputline)) + { + + startBPT = false; + fizlines.try_emplace("Doors", inputline); + LoadFIZ_Doors(inputline); + return true; + } + + if (issection("BuffCoupl.", inputline)) + { + + startBPT = false; + fizlines.try_emplace("BuffCoupl", inputline); + LoadFIZ_BuffCoupl(inputline, 0); + return true; + } + + else if (issection("BuffCoupl1.", inputline)) + { + + startBPT = false; + fizlines.try_emplace("BuffCoupl1", inputline); + LoadFIZ_BuffCoupl(inputline, 1); + return true; + } + + else if (issection("BuffCoupl2.", inputline)) + { + + startBPT = false; + fizlines.try_emplace("BuffCoupl2", inputline); + LoadFIZ_BuffCoupl(inputline, 2); + return true; + } + + if (issection("TurboPos:", inputline)) + { + + startBPT = false; + fizlines.try_emplace("TurboPos", inputline); + LoadFIZ_TurboPos(inputline); + return true; + } + + if (issection("Cntrl.", inputline)) + { + + startBPT = true; + LISTLINE = 0; + fizlines.try_emplace("Cntrl", inputline); + LoadFIZ_Cntrl(inputline); + return true; + } + + if (issection("Headlights:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Headlights", inputline); + LoadFIZ_Headlights(inputline); + return true; + } + + if (issection("Blending:", inputline)) + { + + startBPT = false; + LISTLINE = 0; + fizlines.try_emplace("Blending", inputline); + LoadFIZ_Blending(inputline); + return true; + } + + if (issection("DCEMUED:", inputline)) + { + + startBPT = false; + LISTLINE = 0; + fizlines.try_emplace("DCEMUED", inputline); + LoadFIZ_DCEMUED(inputline); + return true; + } + + if (issection("SpringBrake:", inputline)) + { + + startBPT = false; + LISTLINE = 0; + fizlines.try_emplace("SpringBrake", inputline); + LoadFIZ_SpringBrake(inputline); + return true; + } + + if (issection("Light:", inputline)) + { + + startBPT = false; + fizlines.try_emplace("Light", inputline); + LoadFIZ_Light(inputline); + return true; + } + + if (issection("Security:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Security", inputline); + SecuritySystem.load(inputline, Vmax); + extract_value(EmergencyBrakeWarningSignal, "EmergencyBrakeWarningSignal", inputline, ""); + return true; + } + + if (issection("Clima:", inputline)) + { + + startBPT = false; + fizlines.try_emplace("Clima", inputline); + LoadFIZ_Clima(inputline); + return true; + } + + if (issection("Power:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Power", inputline); + LoadFIZ_Power(inputline); + return true; + } + + if (issection("SpeedControl:", inputline)) + { + startBPT = false; + fizlines.try_emplace("SpeedControl", inputline); + LoadFIZ_SpeedControl(inputline); + return true; + } + + if (issection("Engine:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Engine", inputline); + LoadFIZ_Engine(inputline); + return true; + } + + if (issection("Switches:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Switches", inputline); + LoadFIZ_Switches(inputline); + return true; + } + + if (issection("Circuit:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Circuit", inputline); + LoadFIZ_Circuit(inputline); + return true; + } + + if (issection("AI:", inputline)) + { + startBPT = false; + fizlines.try_emplace("AI", inputline); + LoadFIZ_AI(inputline); + return true; + } + + return false; +} + +// a section of the definition opening a table, kept in fizlines by its name; returns whether the line is one +bool TMoverParameters::LoadFIZ_TableSection(std::string const &inputline, std::map> &fizlines) +{ + if (issection("MotorParamTable:", inputline)) + { + startBPT = false; + startMPT = true; + LISTLINE = 0; + fizlines.try_emplace("MotorParamTable", inputline); + LoadFIZ_MotorParamTable(inputline); + return true; + } + + if (issection("MotorParamTable0:", inputline)) + { + startBPT = false; + startMPT0 = true; + LISTLINE = 0; + return true; + } + + if (issection("RList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("RList", inputline); + startRLIST = true; + LISTLINE = 0; + LoadFIZ_RList(inputline); + return true; + } + + if (issection("UCList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("UCList", inputline); + startUCLIST = true; + LISTLINE = 0; + LoadFIZ_UCList(inputline); + return true; + } + + if (issection("DList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("DList", inputline); + startDLIST = true; + LISTLINE = 0; + LoadFIZ_DList(inputline); + return true; + } + + if (issection("DMList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("DMList", inputline); + startDIZELMOMENTUMLIST = true; + LISTLINE = 0; + return true; + } + + if (issection("HTCList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("HTCList", inputline); + startHYDROTCLIST = true; + LISTLINE = 0; + return true; + } + + if (issection("PmaxList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("PmaxList", inputline); + startPMAXLIST = true; + LISTLINE = 0; + return true; + } + + if (issection("V2NList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("V2NList", inputline); + startDIZELV2NMAXLIST = true; + LISTLINE = 0; + return true; + } + + if (issection("ffList:", inputline)) + { + startBPT = false; + startFFLIST = true; + LISTLINE = 0; + LoadFIZ_FFList(inputline); + return true; + } + + if (issection("ffBrakeList:", inputline)) + { + startBPT = false; + startFFEDLIST = true; + LISTLINE = 0; + LoadFIZ_FFEDList(inputline); + return true; + } + + if (issection("WWList:", inputline)) + { + startBPT = false; + startWWLIST = true; + LISTLINE = 0; + + return true; + } + + if (issection("WiperList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("WiperList", inputline); + startWiperList = true; + LISTLINE = 0; + LoadFIZ_WiperList(inputline); + + return true; + } + + if (issection("DimmerList:", inputline)) + { + dimPositions.clear(); // uzywamy customowej listy + startBPT = false; + startDimmerList = true; + fizlines.try_emplace("DimmerList", inputline); + LoadFIZ_DimmerList(inputline); + return true; + } + + if (issection("LightsList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("LightsList", inputline); + startLIGHTSLIST = true; + LISTLINE = 0; + LoadFIZ_LightsList(inputline); + return true; + } + + if (issection("CompressorList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("CompressorList", inputline); + startCOMPRESSORLIST = true; + LISTLINE = 0; + LoadFIZ_CompressorList(inputline); + return true; + } + return false; +} + +// a row of the table being read +void TMoverParameters::LoadFIZ_TableRow(std::string const &inputline) +{ + // ...and finally, table parsers. + // NOTE: once table parsing is enabled it lasts until switched off, when another section is recognized + if (true == startBPT) + { + readBPT(inputline); + return; + } + if (true == startMPT) + { + readMPT(inputline); + return; + } + if (true == startMPT0) + { + readMPT0(inputline); + return; + } + if (true == startRLIST) + { + readRList(inputline); + return; + } + if (true == startUCLIST) + { + readUCList(inputline); + return; + } + if (true == startDLIST) + { + readDList(inputline); + return; + } + if (true == startDIZELMOMENTUMLIST) + { + readDMList(inputline); + return; + } + if (true == startDIZELV2NMAXLIST) + { + readV2NMAXList(inputline); + return; + } + if (true == startHYDROTCLIST) + { + readHTCList(inputline); + return; + } + if (true == startPMAXLIST) + { + readPmaxList(inputline); + return; + } + if (true == startFFLIST) + { + readFFList(inputline); + return; + } + if (true == startFFEDLIST) + { + readFFEDList(inputline); + return; + } + if (true == startWWLIST) + { + readWWList(inputline); + return; + } + if (true == startWiperList) + { + readWiperList(inputline); + return; + } + if (true == startDimmerList) + { + readDimmerList(inputline); + } + if (true == startLIGHTSLIST) + { + readLightsList(inputline); + return; + } + if (true == startCOMPRESSORLIST) + { + readCompressorList(inputline); + return; + } +} + +bool TMoverParameters::reload_FIZ() +{ + WriteLog("[DEV] Reloading FIZ for " + Name); + // pause simulation + Global.iPause |= 0b1000; + if (bool result = LoadFIZ(chkPath); result == true) + { + // jesli sie udalo przeladowac FIZ + Global.iPause &= 0b0111; + WriteLog("[DEV] FIZ reloaded for " + Name); + } + else + { + // failed to reload - exit simulator + ErrorLog("[DEV] Failed to reload fiz for vehicle " + Name); + } + return true; +} diff --git a/physics/mover/fizsections.cpp b/physics/mover/fizsections.cpp new file mode 100644 index 000000000..193356ab1 --- /dev/null +++ b/physics/mover/fizsections.cpp @@ -0,0 +1,1827 @@ +/* +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/. +*/ + +// reading the vehicle definition (.fiz): the sections and their keywords + +#include "stdafx.h" +#include "physics/mover.h" +#include "vehicle/DynObj.h" +#include "physics/oerlikonest.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/Timer.h" +#include "utilities/parser.h" +#include "simulation/simulation.h" +#include "vehicle/fieldshunting.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "physics/mover/internal.h" + + +int s2NPW(std::string s) +{ // wylicza ilosc osi napednych z opisu ukladu osi + const char A = 64; + int NPW = 0; + for (char const chentry : s) + { + if (chentry >= (char)65 && chentry <= (char)90) + NPW += chentry - A; + } + return NPW; +} + +int s2NNW(std::string s) +{ // wylicza ilosc osi nienapedzanych z opisu ukladu osi + const char Zero = 48; + int NNW = 0; + for (char const ch : s) + { + if (ch >= (char)49 && ch <= (char)57) + NNW += ch - Zero; + } + return NNW; +} + +void TMoverParameters::LoadFIZ_Param(std::string const &line) +{ + + extract_value(Mass, "M", line, "0"); + extract_value(Mred, "Mred", line, "0"); + extract_value(Vmax, "Vmax", line, "0"); + extract_value(Power, "PWR", line, "0"); + extract_value(SandCapacity, "SandCap", line, "0"); + extract_value(HeatingPower, "HeatingP", line, "0"); + extract_value(LightPower, "LightP", line, "0"); + + { + std::map> categories{{"train", 1}, {"road", 2}, {"unimog", 3}, {"ship", 4}, {"airplane,", 8}}; + std::string category; + extract_value(category, "Category", line, "none"); + auto lookup = categories.find(category); + CategoryFlag = lookup != categories.end() ? lookup->second : 0; + if (CategoryFlag == 0) + { + ErrorLog("Unknown vehicle category: \"" + category + "\"."); + } + } + + { + std::map> types{ + {"pseudodiesel", train_type::pseudodiesel}, + {"ezt", train_type::emu}, + {"dmu", train_type::dmu}, + {"sn61", train_type::sn61}, + {"et22", train_type::et22}, + {"et40", train_type::et40}, + {"et41", train_type::et41}, + {"et42", train_type::et42}, + {"ep05", train_type::ep05}, + {"181", train_type::skoda181}, + {"182", train_type::skoda181} // na razie tak + }; + std::string type; + extract_value(type, "Type", line, "none"); + auto lookup = types.find(ToLower(type)); + TrainType = lookup != types.end() ? lookup->second : train_type::generic; + } + + if (TrainType == train_type::emu) + { + + IminLo = 1; + IminHi = 2; + Imin = 1; + } +} + +void TMoverParameters::LoadFIZ_Load(std::string const &line) +{ + + auto const acceptedloads{Split(extract_value("LoadAccepted", line), ',')}; + + if (acceptedloads.empty()) + { + return; + } + + auto const minoffsets{Split(extract_value("LoadMinOffset", line), ',')}; + auto minoffset{0.f}; + auto minoffsetsiterator{std::begin(minoffsets)}; + // NOTE: last (if any) offset parameter retrieved from the list applies to the remainder of the list + // TBD, TODO: include other load parameters in this system + for (auto &load : acceptedloads) + { + if (minoffsetsiterator != std::end(minoffsets)) + { + minoffset = std::stof(*minoffsetsiterator); + ++minoffsetsiterator; + } + LoadAttributes.emplace_back(ToLower(load), minoffset); + } + + extract_value(MaxLoad, "MaxLoad", line, ""); + extract_value(LoadQuantity, "LoadQ", line, ""); + extract_value(OverLoadFactor, "OverLoadFactor", line, ""); + extract_value(LoadSpeed, "LoadSpeed", line, ""); + extract_value(UnLoadSpeed, "UnLoadSpeed", line, ""); +} + +void TMoverParameters::LoadFIZ_Headlights(std::string const &line) +{ + extract_value(refR, "LampRed", line, ""); + extract_value(refG, "LampGreen", line, ""); + extract_value(refB, "LampBlue", line, ""); + + extract_value(dimMultiplier, "DimmedMultiplier", line, ""); + extract_value(normMultiplier, "NormalMultiplier", line, ""); + extract_value(highDimMultiplier, "HighbeamDimmedMultiplier", line, ""); + extract_value(highMultiplier, "HighBeamMultiplier", line, ""); +} + +void TMoverParameters::LoadFIZ_Dimensions(std::string const &line) +{ + + extract_value(Dim.L, "L", line, ""); + extract_value(Dim.H, "H", line, ""); + extract_value(Dim.W, "W", line, ""); + // height of the centre of gravity of the empty vehicle [m], for the criteria of derailment + extract_value(CentreOfGravity, "CoGH", line, ""); + + extract_value(Cx, "Cx", line, "0.3"); + if (Dim.H <= 2.0) + { + // gdyby nie było parametru, lepsze to niż zero + Floor = static_cast(Dim.H); + } + else + { + // zgodność wsteczna + Floor = 0.0; + } + extract_value(Floor, "Floor", line, ""); +} + +void TMoverParameters::LoadFIZ_Wheels(std::string const &line) +{ + + extract_value(WheelDiameter, "D", line, ""); + WheelDiameterL = WheelDiameter; // gdyby nie było parametru, lepsze to niż zero + extract_value(WheelDiameterL, "Dl", line, ""); + WheelDiameterT = WheelDiameter; // gdyby nie było parametru, lepsze to niż zero + extract_value(WheelDiameterT, "Dt", line, ""); + + extract_value(TrackW, "Tw", line, ""); + extract_value(AxleInertialMoment, "AIM", line, ""); + + extract_value(AxleArangement, "Axle", line, ""); + NPoweredAxles = s2NPW(AxleArangement); + NAxles = NPoweredAxles + s2NNW(AxleArangement); + + BearingType = extract_value("BearingType", line) == "Roll" ? 1 : 0; + + extract_value(ADist, "Ad", line, ""); + extract_value(BDist, "Bd", line, ""); + + if (AxleInertialMoment <= 0.0) + { + /* + AxleInertialMoment = 1.0; + */ + // approximation formula by youby + auto const k = 472.0; // arbitrary constant + AxleInertialMoment = k / 4.0 * std::pow(WheelDiameter, 4.0) * NAxles; + Mred = k * std::pow(WheelDiameter, 2.0) * NAxles; + } +} + +void TMoverParameters::LoadFIZ_Brake(std::string const &line) +{ + + extract_value(BrakeValveParams, "BrakeValve", line, ""); + BrakeValveDecode(BrakeValveParams); + BrakeSubsystemDecode(); + + extract_value(NBpA, "NBpA", line, ""); + extract_value(MaxBrakeForce, "MBF", line, ""); + extract_value(BrakeValveSize, "Size", line, ""); + extract_value(TrackBrakeForce, "TBF", line, ""); + TrackBrakeForce *= 1000.0; + + extract_value(MaxBrakePress[3], "MaxBP", line, ""); + if (MaxBrakePress[3] > 0.0) + { + + extract_value(BrakeCylNo, "BCN", line, ""); + if (BrakeCylNo > 0) + { + + extract_value(MaxBrakePress[0], "MaxLBP", line, ""); + if (MaxBrakePress[0] < 0.01) + { + MaxBrakePress[0] = MaxBrakePress[3]; + } + extract_value(MaxBrakePress[1], "TareMaxBP", line, ""); + extract_value(MaxBrakePress[2], "MedMaxBP", line, ""); + extract_value(MaxBrakePress[4], "MaxASBP", line, ""); + if (MaxBrakePress[4] < 0.01) + { + MaxBrakePress[4] = 0.0; + } + + extract_value(BrakeCylRadius, "BCR", line, ""); + extract_value(BrakeCylDist, "BCD", line, ""); + extract_value(BrakeCylSpring, "BCS", line, ""); + extract_value(BrakeSlckAdj, "BSA", line, ""); + extract_value(BrakeRigEff, "BRE", line, "1"); + + extract_value(BrakeCylMult[0], "BCM", line, ""); + extract_value(BrakeCylMult[1], "BCMlo", line, ""); + extract_value(BrakeCylMult[2], "BCMHi", line, ""); + + P2FTrans = 100 * M_PI * std::pow(BrakeCylRadius, 2); // w kN/bar + + if (BrakeCylMult[1] > 0.0 || MaxBrakePress[1] > 0.0) + { + LoadFlag = 1; + } + else + { + LoadFlag = 0; + } + + BrakeVolume = M_PI * std::pow(BrakeCylRadius, 2) * BrakeCylDist * BrakeCylNo; + extract_value(BrakeVVolume, "BVV", line, ""); + + { + std::map> brakemethods{{"P10-Bg", bp_P10Bg}, {"P10-Bgu", bp_P10Bgu}, {"FR513", bp_FR513}, {"FR510", bp_FR510}, {"Cosid", bp_Cosid}, + {"P10yBg", bp_P10yBg}, {"P10yBgu", bp_P10yBgu}, {"Disk1", bp_D1}, {"Disk1+Mg", bp_D1 + bp_MHS}, {"Disk2", bp_D2}}; + auto lookup = brakemethods.find(extract_value("BM", line)); + BrakeMethod = lookup != brakemethods.end() ? lookup->second : 0; + } + + extract_value(RapidMult, "RM", line, "1"); + extract_value(RapidVel, "RV", line, "55"); + } + } + else + { + // maxbrakepress[3] == 0 or less + P2FTrans = 0; + } + + // Ra 2014-07: trochę niedokładności + // the draws are sequenced: the order of the operands of '-' is unspecified, and GCC and MSVC draw them the other way round + auto const firstdraw{Random(10)}; + CntrlPipePress = 5 + 0.001 * (Random(10) - firstdraw); + extract_value(CntrlPipePress, "HiPP", line, ""); + HighPipePress = CntrlPipePress; + LowPipePress = std::min(HighPipePress, 3.5); + extract_value(LowPipePress, "LoPP", line, ""); + DeltaPipePress = HighPipePress - LowPipePress; + + extract_value(VeselVolume, "Vv", line, ""); + /* + if( VeselVolume == 0.0 ) { VeselVolume = 0.01; } + */ + extract_value(MinCompressor, "MinCP", line, ""); + extract_value(MaxCompressor, "MaxCP", line, ""); + extract_value(MinCompressor_cabB, "MinCP_B", line, ""); + extract_value(MaxCompressor_cabB, "MaxCP_B", line, ""); + extract_value(CompressorTankValve, "CompressorTankValve", line, ""); + extract_value(CompressorSpeed, "CompressorSpeed", line, ""); + extract_value(EmergencyValveOff, "MinEVP", line, ""); + extract_value(EmergencyValveOn, "MaxEVP", line, ""); + extract_value(EmergencyValveArea, "EVArea", line, ""); + extract_value(UniversalBrakeButtonFlag[0], "UBB1", line, ""); + extract_value(UniversalBrakeButtonFlag[1], "UBB2", line, ""); + extract_value(UniversalBrakeButtonFlag[2], "UBB3", line, ""); + extract_value(LockPipeOn, "LPOn", line, "-1"); + extract_value(LockPipeOff, "LPOff", line, "-1"); + extract_value(HandleUnlock, "HandlePipeUnlockPos", line, "-3"); + extract_value(EmergencyCutsOffHandle, "EmergencyCutsOffHandle", line, ""); + { + std::map> compressorpowers{ + {"Main", 0}, + // 1: default, powered by converter, with manual state control + {"Converter", 2}, + {"Engine", 3}, // equivalent of 0, TODO: separate 'main' and 'engine' in the code + {"Coupler1", 4}, // włączana w silnikowym EZT z przodu + {"Coupler2", 5} // włączana w silnikowym EZT z tyłu + }; + auto lookup = compressorpowers.find(extract_value("CompressorPower", line)); + CompressorPower = lookup != compressorpowers.end() ? lookup->second : 1; + } + extract_value(CompressorStartDelay, "CompressorStartDelay", line, ""); + + if (true == extract_value(AirLeakRate, "AirLeakRate", line, "")) + { + // the parameter is provided in form of a multiplier, where 1.0 means the default rate of 0.01 + AirLeakRate *= 0.01; + } + + extract_value(ReleaserEnabledOnlyAtNoPowerPos, "ReleaserPowerPosLock", line, EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric ? "yes" : "no"); + + if (MinCompressor_cabB > 0.0) + { + MinCompressor_cabA = MinCompressor; + CabDependentCompressor = true; + } + else + { + MinCompressor_cabB = MinCompressor; + } + if (MaxCompressor_cabB > 0.0) + { + MaxCompressor_cabA = MaxCompressor; + CabDependentCompressor = true; + } + else + { + MaxCompressor_cabB = MaxCompressor; + } +} + +void TMoverParameters::LoadFIZ_Doors(std::string const &line) +{ + + std::map> doorcontrols{ + {"Passenger", control_t::passenger}, {"AutomaticCtrl", control_t::autonomous}, {"DriverCtrl", control_t::driver}, {"Conductor", control_t::conductor}, {"Mixed", control_t::mixed}}; + // opening method + { + auto lookup = doorcontrols.find(extract_value("OpenCtrl", line)); + Doors.open_control = lookup != doorcontrols.end() ? lookup->second : control_t::passenger; + } + // closing method + { + auto lookup = doorcontrols.find(extract_value("CloseCtrl", line)); + Doors.close_control = lookup != doorcontrols.end() ? lookup->second : control_t::passenger; + } + // automatic closing conditions + extract_value(Doors.auto_duration, "DoorStayOpen", line, ""); + extract_value(Doors.auto_velocity, "DoorAutoCloseVel", line, ""); + extract_value(Doors.auto_include_remote, "DoorAutoCloseRemote", line, ""); + // operation permit + extract_value(Doors.permit_needed, "DoorNeedPermit", line, ""); + // the door closure lamp (SOD) of the cab signals the doors of the whole consist + extract_value(Doors.closure_signal, "DoorClosureSignal", line, ""); + { + auto permitpresets = Split(extract_value("DoorPermitList", line), '|'); + for (auto const &permit : permitpresets) + { + Doors.permit_presets.emplace_back(std::stoi(permit)); + } + if (false == Doors.permit_presets.empty()) + { + // HACK: legacy position indices start from 1, so we deduct 1 to arrive at proper index into the array + extract_value(Doors.permit_preset, "DoorPermitListDefault", line, "1"); + Doors.permit_preset = std::min(static_cast(Doors.permit_presets.size()), Doors.permit_preset) - 1; + } + } + + extract_value(Doors.open_rate, "OpenSpeed", line, ""); + extract_value(Doors.open_delay, "DoorOpenDelay", line, ""); + extract_value(Doors.close_rate, "CloseSpeed", line, ""); + extract_value(Doors.close_delay, "DoorCloseDelay", line, ""); + extract_value(Doors.range, "DoorMaxShiftL", line, ""); + extract_value(Doors.range, "DoorMaxShiftR", line, ""); + extract_value(Doors.range_out, "DoorMaxShiftPlug", line, ""); + + std::map> doortypes{ + {"Shift", 1}, + {"Rotate", 2}, + {"Fold", 3}, + {"Plug", 4}, + }; + // opening method + { + auto lookup = doortypes.find(extract_value("DoorOpenMethod", line)); + Doors.type = lookup != doortypes.end() ? lookup->second : 2; // default type is plain, rotating door + } + + extract_value(Doors.has_warning, "DoorClosureWarning", line, ""); + extract_value(Doors.has_autowarning, "DoorClosureWarningAuto", line, ""); + extract_value(Doors.has_lock, "DoorBlocked", line, ""); + extract_value(Doors.doorLockSpeed, "DoorLockSpeed", line, ""); + { + auto const remotedoorcontrol{Doors.open_control == control_t::driver || Doors.open_control == control_t::conductor || Doors.open_control == control_t::mixed}; + + extract_value(Doors.voltage, "DoorVoltage", line, remotedoorcontrol ? "24" : "0"); + } + + extract_value(Doors.step_rate, "PlatformSpeed", line, ""); + extract_value(Doors.step_range, "PlatformMaxShift", line, ""); + + std::string platformopenmethod; + extract_value(platformopenmethod, "PlatformOpenMethod", line, ""); + if (platformopenmethod == "Shift") + { + Doors.step_type = 1; + } // przesuw + + extract_value(MirrorMaxShift, "MirrorMaxShift", line, ""); + extract_value(MirrorVelClose, "MirrorVelClose", line, ""); + + extract_value(DoorsOpenWithPermitAfter, "DoorOpenWithPermit", line, ""); + extract_value(DoorsPermitLightBlinking, "DoorsPermitLightBlinking", line, ""); +} +namespace +{ + + +// the value of an optional key of the line, or the default without it +double optional_value(std::string const &Line, std::string const &Key, double const Default) +{ + auto value{Default}; + extract_value(value, Key, Line, ""); + return value; +} + +// the value of an optional key of the line given in kilo-units, in units; or the default (in units) without it +double optional_kilo_value(std::string const &Line, std::string const &Key, double const Default) +{ + auto value{0.0}; + return extract_value(value, Key, Line, "") && value > 0.0 ? value * 1000.0 : Default; +} + +// the play of a coupling as made, for each kind: a screw coupling is tightened so that the buffers touch, the knuckles of +// an automatic coupler have about a centimetre between them, a chain hangs loose +double default_slack(TCouplerType const Type) +{ + switch (Type) + { + case TCouplerType::Automatic: + return 0.005; + case TCouplerType::Chain: + return 0.05; + default: + return 0.0; + } +} + +// the parameters of the physical model of the coupling (couplerphysics in eu07.ini, see couplerphysics.h), taken from +// those of the legacy model, and the optional keys of the .fiz for what the legacy model doesn't have: +// Slack [m] the play of the coupling of this end, negative for a screw coupling tightened to press the buffers in +// ProgB, ProgC [-] progression of the buffers and of the draw gear, 0 linear, up to 0.9 +// UnloadB, UnloadC [-] force of the unloading curve of the buffers and of the draw gear to that of the loading one +// FyieldC [kN] the force past which the link stretches for good; DbreakC [m] the elongation at which it breaks +// kL [kN/m] stiffness of the steel parts past the travel of the springs; FcrushB [kN] the buffers give under it +// RestitutionSolid [-] coefficient of restitution of a hit on the springs gone solid +coupler_physics::end_parameters coupler_physics_parameters(TCoupling const &Coupler, std::string const &Line) +{ + coupler_physics::end_parameters parameters; + parameters.buffers = {Coupler.SpringKB, Coupler.DmaxB, std::clamp(optional_value(Line, "ProgB", 0.5), 0.0, 0.9)}; + parameters.draw_gear = {Coupler.SpringKC, Coupler.DmaxC, std::clamp(optional_value(Line, "ProgC", 0.3), 0.0, 0.9)}; + // only a screw coupling can be tightened to press the buffers in, and not past their travel + auto const tightest{Coupler.CouplerType == TCouplerType::Screw ? -Coupler.DmaxB : 0.0}; + parameters.slack = std::max(optional_value(Line, "Slack", default_slack(Coupler.CouplerType)), tightest); + // the legacy model sprang back at beta of the force it was loaded with + auto const unloading{Coupler.beta > 0.0 && Coupler.beta < 1.0 ? Coupler.beta : 0.5}; + parameters.buffers_unloading = std::clamp(optional_value(Line, "UnloadB", unloading), 0.05, 1.0); + parameters.draw_gear_unloading = std::clamp(optional_value(Line, "UnloadC", unloading), 0.05, 1.0); + // as much as the legacy model had + parameters.damping = CouplerTune * (Coupler.FmaxC + Coupler.FmaxB) * std::max(Coupler.beta, 0.0); + + // FmaxC is the rated breaking force of the coupling + auto const ultimate{std::max(Coupler.FmaxC, 1.0)}; + auto const yield{std::min(optional_kilo_value(Line, "FyieldC", 0.8 * ultimate), ultimate)}; + auto const elongation{std::max(optional_value(Line, "DbreakC", 0.02), 0.001)}; + parameters.link = {yield, ultimate, std::max((ultimate - yield) / elongation, 1.0), Coupler.CouplerType != TCouplerType::Articulated}; + // the steel parts give a few millimetres under the rated force + parameters.link_stiffness = optional_kilo_value(Line, "kL", ultimate / 0.003); + parameters.crush_force = optional_kilo_value(Line, "FcrushB", 2.5 * std::max(Coupler.FmaxB, Coupler.FmaxC)); + parameters.solid_restitution = std::clamp(optional_value(Line, "RestitutionSolid", parameters.solid_restitution), 0.05, 0.95); + return parameters; +} + +void scale_strength(coupler_physics::link_strength &Link, double const Factor) +{ + Link.yield *= Factor; + Link.ultimate *= Factor; +} + +// the optional keys of the collisions past the buffers (physics.collisions new, see collision.h), what's not given +// comes from the kind of the vehicle: +// FcrushPeak, FcrushPlateau [kN] the force the end starts to crush at, and keeps crushing at +// CrushOnset, CrushDensify, CrushLimit [m] the crush the peak drops at, it packs down past, it can't go past +// CrushHardening [1/m] the growth of the force past CrushDensify, to the plateau for each metre +// CrashZone [yes/no] built to EN 15227: energy absorbers and anticlimbers; AntiClimber [yes/no] on its own +// BufferHeight [m] of the empty vehicle above the rail +// BufferCategory [A/B/C/L/P] the buffers of EN 15551 (P those of the coaches) in place of kB and DmaxB +collision::end_definition collision_definition(std::string const &Line) +{ + collision::end_definition definition; + auto const number = [&Line](std::string const &Key, double const Scale) -> std::optional { + auto value{0.0}; + if (extract_value(value, Key, Line, "") && value >= 0.0) + { + return value * Scale; + } + return std::nullopt; + }; + auto const flag = [&Line](std::string const &Key) -> std::optional { + auto value{false}; + if (extract_value(value, Key, Line, "")) + { + return value; + } + return std::nullopt; + }; + definition.peak = number("FcrushPeak", 1000.0); + definition.plateau = number("FcrushPlateau", 1000.0); + definition.onset = number("CrushOnset", 1.0); + definition.densify = number("CrushDensify", 1.0); + definition.hardening = number("CrushHardening", 1.0); + definition.limit = number("CrushLimit", 1.0); + definition.crash_zone = flag("CrashZone"); + definition.anticlimber = flag("AntiClimber"); + definition.buffer_height = number("BufferHeight", 1.0); + return definition; +} + +} // namespace + +void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Index) +{ + + TCoupling *thiscoupler; + if (Index == 2) + { + thiscoupler = &Couplers[1]; + } + else + { + thiscoupler = &Couplers[0]; + } + + std::map> couplertypes{ + {"Automatic", TCouplerType::Automatic}, {"Screw", TCouplerType::Screw}, {"Chain", TCouplerType::Chain}, {"Bare", TCouplerType::Bare}, {"Articulated", TCouplerType::Articulated}, + }; + auto lookup = couplertypes.find(extract_value("CType", line)); + thiscoupler->CouplerType = lookup != couplertypes.end() ? lookup->second : TCouplerType::NoCoupler; + + extract_value(thiscoupler->SpringKC, "kC", line, ""); + extract_value(thiscoupler->DmaxC, "DmaxC", line, ""); + extract_value(thiscoupler->FmaxC, "FmaxC", line, ""); + extract_value(thiscoupler->SpringKB, "kB", line, ""); + extract_value(thiscoupler->DmaxB, "DmaxB", line, ""); + extract_value(thiscoupler->FmaxB, "FmaxB", line, ""); + extract_value(thiscoupler->beta, "beta", line, ""); + extract_value(thiscoupler->AutomaticCouplingFlag, "AutomaticFlag", line, ""); + extract_value(thiscoupler->AllowedFlag, "AllowedFlag", line, ""); + if (thiscoupler->AllowedFlag < 0) + { + thiscoupler->AllowedFlag = -thiscoupler->AllowedFlag | coupling::permanent; + } + extract_value(thiscoupler->PowerCoupling, "PowerCoupling", line, ""); + extract_value(thiscoupler->PowerFlag, "PowerFlag", line, ""); + extract_value(thiscoupler->control_type, "ControlType", line, ""); + + if (thiscoupler->CouplerType != TCouplerType::NoCoupler && thiscoupler->CouplerType != TCouplerType::Bare && thiscoupler->CouplerType != TCouplerType::Articulated) + { + + thiscoupler->SpringKC *= 1000; + thiscoupler->FmaxC *= 1000; + thiscoupler->SpringKB *= 1000; + thiscoupler->FmaxB *= 1000; + } + else if (thiscoupler->CouplerType == TCouplerType::Bare) + { + + thiscoupler->SpringKC = 50.0 * Mass + Ftmax / 0.05; + thiscoupler->DmaxC = 0.05; + thiscoupler->FmaxC = 100.0 * Mass + 2 * Ftmax; + thiscoupler->SpringKB = 60.0 * Mass + Ftmax / 0.05; + thiscoupler->DmaxB = 0.05; + thiscoupler->FmaxB = 50.0 * Mass + 2.0 * Ftmax; + thiscoupler->beta = 0.3; + } + else if (thiscoupler->CouplerType == TCouplerType::Articulated) + { + /* + coupler->SpringKC = 60.0 * Mass + 1000; + coupler->DmaxC = 0.05; + coupler->FmaxC = 20000000.0 + 2.0 * Ftmax; + coupler->SpringKB = 70.0 * Mass + 1000; + coupler->DmaxB = 0.05; + coupler->FmaxB = 4000000.0 + 2.0 * Ftmax; + coupler->beta = 0.55; + */ + thiscoupler->SpringKC = 4500 * 1000; + thiscoupler->FmaxC = 850 * 1000; + thiscoupler->SpringKB = 9200 * 1000; + thiscoupler->FmaxB = 320 * 1000; + thiscoupler->beta = 0.55; + // the spring force is taken up to Dmax only, past it the vehicles collide (CollisionDetect()); so the joint + // carries the full FmaxC either way before it gives. with 0.05 m it carried 225 kN, short of what a loaded + // articulated wagon in a freight train takes, which then collided at every step (eu07/maszyna#553) + thiscoupler->DmaxC = std::max(0.05, thiscoupler->FmaxC / thiscoupler->SpringKC); + thiscoupler->DmaxB = std::max(0.05, thiscoupler->FmaxC / thiscoupler->SpringKB); + } + + // the buffers of a category of EN 15551 in place of the springs given + auto const categoryname{extract_value("BufferCategory", line)}; + auto const category{categoryname.empty() ? std::nullopt : collision::buffer_category_of(categoryname.front())}; + auto const buffered{thiscoupler->CouplerType != TCouplerType::NoCoupler && thiscoupler->CouplerType != TCouplerType::Bare && thiscoupler->CouplerType != TCouplerType::Articulated}; + if (category && buffered) + { + auto const linear{collision::buffer_curve(*category, 0.0)}; + thiscoupler->SpringKB = linear.stiffness; + thiscoupler->DmaxB = linear.travel; + } + thiscoupler->physics = coupler_physics_parameters(*thiscoupler, line); + if (category && buffered) + { + thiscoupler->physics.buffers = collision::buffer_curve(*category, thiscoupler->physics.buffers.progression); + } + thiscoupler->collision = collision_definition(line); + thiscoupler->collision.buffers = category; + + if (Index == 0) + { + // 0 indicates single entry for both couplers + Couplers[1] = Couplers[0]; + } + // each coupling as made is a little stronger than its rated force, a different one at each end + for (int end = end::front; end <= end::rear; ++end) + { + if (Index == 0 || end == (Index == 2 ? end::rear : end::front)) + { + scale_strength(Couplers[end].physics.link, coupler_physics::strength_scatter(Name, end)); + } + } +} + +void TMoverParameters::LoadFIZ_TurboPos(std::string const &Input) +{ + + extract_value(TurboTest, "TurboPos", Input, ""); +} + +void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) +{ + + LoadFIZ_CntrlBrakes(line); + LoadFIZ_CntrlControllers(line); + LoadFIZ_CntrlStarts(line); +} + +// Cntrl.: the brake system, the handles, the brake delays and the local and manual brakes +void TMoverParameters::LoadFIZ_CntrlBrakes(std::string const &line) +{ + { + using enum TBrakeSystem; + std::map> brakesystems{{"Pneumatic", Pneumatic}, {"ElectroPneumatic", ElectroPneumatic}}; + auto lookup = brakesystems.find(extract_value("BrakeSystem", line)); + BrakeSystem = lookup != brakesystems.end() ? lookup->second : Individual; + } + if (BrakeSystem != TBrakeSystem::Individual) + { + LoadFIZ_CntrlTrainBrake(line); + } // brakesystem != individual + + // localbrake + { + using enum TLocalBrake; + std::map> localbrakes{{"ManualBrake", ManualBrake}, {"PneumaticBrake", PneumaticBrake}, {"HydraulicBrake", HydraulicBrake}}; + auto lookup = localbrakes.find(extract_value("LocalBrake", line)); + LocalBrake = lookup != localbrakes.end() ? lookup->second : NoBrake; + } + // mbrake + extract_value(MBrake, "ManualBrake", line, ""); +} + +// Cntrl.: of a vehicle with a train brake, its positions, delays, modes, handles, load weighing and anti-slip brake +void TMoverParameters::LoadFIZ_CntrlTrainBrake(std::string const &line) +{ + using enum TBrakeHandle; + + extract_value(BrakeCtrlPosNo, "BCPN", line, ""); + for (int idx = 0; idx < 4; ++idx) + { + + extract_value(BrakeDelay[idx], std::format("BDelay{}", idx + 1), line, ""); + } + // brakedelays, brakedelayflag + { + std::map> brakedelays{{"GPR", bdelay_G + bdelay_P + bdelay_R}, + {"PR", bdelay_P + bdelay_R}, + {"GP", bdelay_G + bdelay_P}, + {"R", bdelay_R}, + {"P", bdelay_P}, + {"G", bdelay_G}, + {"GPR+Mg", bdelay_G + bdelay_P + bdelay_R + bdelay_M}, + {"PR+Mg", bdelay_P + bdelay_R + bdelay_M}}; + std::map> brakedelayflags{{"R", bdelay_R}, {"P", bdelay_P}, {"G", bdelay_G}}; + std::string brakedelay; + extract_value(brakedelay, "BrakeDelays", line, ""); + auto lookup = brakedelays.find(brakedelay); + BrakeDelays = lookup != brakedelays.end() ? lookup->second : 0; + lookup = brakedelayflags.find(brakedelay); + BrakeDelayFlag = lookup != brakedelayflags.end() ? lookup->second : 0; + } + // brakeopmode + { + std::map> brakeopmodes{{"PN", bom_PS + bom_PN}, {"PNEP", bom_PS + bom_PN + bom_EP}, {"PNEPMED", bom_PS + bom_PN + bom_EP + bom_MED}}; + auto lookup = brakeopmodes.find(extract_value("BrakeOpModes", line)); + BrakeOpModes = lookup != brakeopmodes.end() ? lookup->second : 0; + } + // brakehandle + { + std::map> brakehandles{ + {"FV4a", FV4a}, {"test", testH}, {"D2", D2}, {"MHZ_EN57", MHZ_EN57}, {"MHZ_K5P", MHZ_K5P}, + {"MHZ_K8P", MHZ_K8P}, {"MHZ_6P", MHZ_6P}, {"M394", M394}, {"Knorr", Knorr}, {"Westinghouse", West}, + {"FVel6", FVel6}, {"FVE408", FVE408}, {"St113", St113}}; + auto lookup = brakehandles.find(extract_value("BrakeHandle", line)); + BrakeHandle = lookup != brakehandles.end() ? lookup->second : NoHandle; + } + extract_value(Handle_AutomaticOverload, "HAO", line, ""); + extract_value(Handle_ManualOverload, "HMO", line, ""); + extract_value(Handle_GenericDoubleParameter1, "HGDP1", line, ""); + extract_value(Handle_GenericDoubleParameter2, "HGDP2", line, ""); + extract_value(Handle_OverloadMaxPressure, "OMP", line, ""); + extract_value(Handle_OverloadPressureDecrease, "OPD", line, ""); + // brakelochandle + { + std::map> locbrakehandles{{"FD1", FD1}, {"Knorr", Knorr}, {"Westinghouse", West}}; + auto lookup = locbrakehandles.find(extract_value("LocBrakeHandle", line)); + BrakeLocHandle = lookup != locbrakehandles.end() ? lookup->second : NoHandle; + } + + // mbpm + if (true == extract_value(MBPM, "MaxBPMass", line, "")) + { + // NOTE: only convert the value from tons to kilograms if the entry is present in the config file + MBPM *= 1000.0; + } + + // asbtype + LoadFIZ_CntrlAntiSlipBrake(ToLower(extract_value("ASB", line))); +} + +// Cntrl.: the kind of the anti-slip brake, by hand or automatic only for a vehicle with a brake handle +void TMoverParameters::LoadFIZ_CntrlAntiSlipBrake(std::string_view const asb) +{ + if (asb == "yes") + { + ASBType = 128; + } + else if (BrakeCtrlPosNo > 0 && asb == "manual") + { + ASBType = 1; + } + else if (BrakeCtrlPosNo > 0 && asb == "automatic") + { + ASBType = 2; + } +} + +// Cntrl.: the controllers, their delays, the cab and the switches of the driver's desk +void TMoverParameters::LoadFIZ_CntrlControllers(std::string const &line) +{ + // maksymalna predkosc dostepna na tarczce predkosciomierza + extract_value(maxTachoSpeed, "MaxTachoSpeed", line, ""); + + // horns + { + using enum horn_supply; + std::map> const hornsupplies{{"Pneumatic", air}, {"Electric", electric}}; + auto lookup = hornsupplies.find(extract_value("HornType", line)); + HornSupply = lookup != hornsupplies.end() ? lookup->second : air; + lookup = hornsupplies.find(extract_value("Horn3Type", line)); + Horn3Supply = lookup != hornsupplies.end() ? lookup->second : HornSupply; + } + + // dynamicbrake + { + std::map> dynamicbrakes{{"Passive", dbrake_passive}, {"Switch", dbrake_switch}, {"Reversal", dbrake_reversal}, {"Automatic", dbrake_automatic}}; + auto lookup = dynamicbrakes.find(extract_value("DynamicBrake", line)); + DynamicBrakeType = lookup != dynamicbrakes.end() ? lookup->second : dbrake_none; + extract_value(DynamicBrakeAmpmeters, "DBAM", line, ""); + } + + // split ED/pneumatic brake control: when true the local brake operates only on the + // pneumatic locomotive cylinder while electrodynamic braking is commanded by a + // separate "dynamicbrakectrl" lever (or the negative range of jointctrl). + extract_value(SplitEDPneumaticBrake, "SplitEDPneumaticBrake", line, ""); + // number of stepped positions for the dedicated ED brake controller (default 10) + DynamicBrakeCtrlPosNo = 10; + extract_value(DynamicBrakeCtrlPosNo, "DBPN", line, ""); + if (DynamicBrakeCtrlPosNo < 1) + { + DynamicBrakeCtrlPosNo = 10; + } + + extract_value(MainCtrlPosNo, "MCPN", line, ""); + extract_value(ScndCtrlPosNo, "SCPN", line, ""); + extract_value(ScndInMain, "SCIM", line, ""); + extract_value(MainCtrlMaxDirChangePos, "DirChangeMaxPos", line, ""); + + if (auto const autorelay{ToLower(extract_value("AutoRelay", line))}; autorelay == "optional") + { + AutoRelayType = 2; + } + else if (autorelay == "yes") + { + AutoRelayType = 1; + } + else + { + AutoRelayType = 0; + } + // a key of its own rather than a new AutoRelay value: an exe that doesn't know it reads the line as before, and the value + // stays Optional, which every check of the switch looks for + extract_value(FieldShuntSwitch, "FieldShuntSwitch", line, ""); + + extract_value(CoupledCtrl, "CoupledCtrl", line, ""); + extract_value(HasCamshaft, "Camshaft", line, ""); + extract_value(EIMCtrlType, "EIMCtrlType", line, ""); + EIMCtrlType = std::clamp(EIMCtrlType, 0, 3); + extract_value(LocHandleTimeTraxx, "LocalBrakeTraxx", line, ""); + extract_value(EIMCtrlAdditionalZeros, "EIMCtrlAddZeros", line, ""); + extract_value(EIMCtrlEmergency, "EIMCtrlEmergency", line, ""); + // Elf (EIMCtrlType 2): an emergency brake position below the controller's position 0, which shifts the other positions up by one + extract_value(EIMCtrlMainEmergency, "EIMCtrlMainEmergency", line, ""); + if (auto const elfpositions{4 + EIMCtrlEmergencyPositions()}; EIMCtrlEmergencyPositions() > 0 && MainCtrlPosNo < elfpositions) + { + // the old positions in the file: without the fix-up the controller would have no power position, and the + // reverser would stop working at neutral (DirChangeMaxPos read before, in the old positions) + MainCtrlMaxDirChangePos += EIMCtrlEmergencyPositions(); + ErrorLog(std::format("Bad fiz: EIMCtrlMainEmergency needs MCPN={} in {}, DirChangeMaxPos taken as {}", elfpositions, TypeName, MainCtrlMaxDirChangePos)); + MainCtrlPosNo = elfpositions; + } + + extract_value(ScndS, "ScndS", line, ""); // brak pozycji rownoleglej przy niskiej nastawie PSR + extract_value(ScndCtrlResistiveLock, "ScndCtrlResistiveLock", line, ""); // bocznikowanie tylko na pozycjach bezoporowych + + extract_value(InitialCtrlDelay, "IniCDelay", line, ""); + extract_value(CtrlDelay, "SCDelay", line, ""); + CtrlDownDelay = CtrlDelay; // hunter-101012: jesli nie ma SCDDelay; + extract_value(CtrlDownDelay, "SCDDelay", line, ""); + + // hunter-111012: dla siodemek 303E + FastSerialCircuit = ToLower(extract_value("FSCircuit", line)) == "yes" ? 1 : 0; + extract_value(BackwardsBranchesAllowed, "BackwardsBranchesAllowed", line, ""); + + extract_value(AutomaticCabActivation, "AutomaticCabActivation", line, ""); + extract_value(InactiveCabFlag, "InactiveCabFlag", line, ""); + + extract_value(StopBrakeDecc, "SBD", line, ""); + extract_value(StopBrakeReleaseDelay, "SBDReleaseDelay", line, ""); // the holding brake waits for the power demand this long, s + extract_value(ReleaseParkingBySpringBrake, "ReleaseParkingBySpringBrake", line, ""); + extract_value(ReleaseParkingBySpringBrakeWhenDoorIsOpen, "ReleaseParkingBySpringBrakeWhenDoorIsOpen", line, ""); + extract_value(SpringBrakeCutsOffDrive, "SpringBrakeCutsOffDrive", line, ""); + extract_value(SpringBrakeDriveEmergencyVel, "SpringBrakeDriveEmergencyVel", line, ""); + + extract_value(HideDirStatusWhenMoving, "HideDirStatusWhenMoving", line, ""); + extract_value(HideDirStatusSpeed, "HideDirStatusSpeed", line, ""); + extract_value(isDoubleClickForMeasureNeeded, "DCMB", line, ""); + extract_value(DistanceCounterDoublePressPeriod, "DCDPP", line, ""); + + extract_value(isBatteryButtonImpulse, "IBTB", line, ""); + extract_value(shouldHoldBatteryButton, "SBBBH", line, ""); + extract_value(BatteryButtonHoldTime, "BBHT", line, ""); +} + +// Cntrl.: how the devices start (MainStart, BatteryStart, ...) and their relays +void TMoverParameters::LoadFIZ_CntrlStarts(std::string const &line) +{ + using enum start_t; + std::map> starts{{"Disabled", disabled}, {"Manual", manual}, {"Automatic", automatic}, {"Mixed", manualwithautofallback}, + {"Battery", battery}, {"Converter", converter}, {"Direction", direction}}; + + // main circuit + extract_value(MainsInitTime, "MainInitTime", line, ""); + { + auto lookup = starts.find(extract_value("MainStart", line)); + MainsStart = lookup != starts.end() ? lookup->second : manual; + } + extract_value(PantographsRequireMains, "PantRequiresMain", line, ""); + // the brake pipe pressure of an emergency brake application, which opens the line breaker under power + extract_value(EmergencyBrakeMainOffPressure, "EmergencyBrakeMainOff", line, ""); + EmergencyBrakeMainOffPressure = std::max(0.0, EmergencyBrakeMainOffPressure); + // battery + { + auto lookup = starts.find(extract_value("BatteryStart", line)); + BatteryStart = lookup != starts.end() ? lookup->second : manual; + } + // converter + { + auto lookup = starts.find(extract_value("ConverterStart", line)); + ConverterStart = lookup != starts.end() ? lookup->second : manual; + } + extract_value(ConverterStartDelay, "ConverterStartDelay", line, ""); + extract_value(ConverterOverloadRelayOffWhenMainIsOff, "ConverterOverloadWhenMainIsOff", line, TrainType == train_type::emu ? "yes" : "no"); + // compressor + { + auto lookup = starts.find(extract_value("CompressorStart", line)); + CompressorStart = lookup != starts.end() ? lookup->second : manual; + } + // pantograph compressor + { + auto lookup = starts.find(extract_value("PantCompressorStart", line)); + PantographCompressorStart = lookup != starts.end() ? lookup->second : manual; + } + // pantograph compressor valve + PantAutoValve = TrainType == train_type::emu; // legacy code behaviour, automatic valve was initially installed in all EMUs + extract_value(PantAutoValve, "PantAutoValve", line, ""); + // pantographs valve + { + auto lookup = starts.find(extract_value("PantEPValveStart", line)); + PantsValve.start_type = lookup != starts.end() ? lookup->second : automatic; // legacy code behaviour, there was no pantographs valve + extract_value(PantsValve.spring, "PantEPValveSpring", line, ""); + } + // pantograph valve configuration + { + auto lookup = starts.find(extract_value("PantValveStart", line)); + auto valvestarttype = lookup != starts.end() ? lookup->second : manual; + auto valvespring{true}; + extract_value(valvespring, "PantValveSpring", line, ""); + auto valvesolenoid{true}; + extract_value(valvesolenoid, "PantValveSolenoid", line, ""); + for (auto &pantograph : Pantographs) + { + pantograph.valve.spring = valvespring; + pantograph.valve.solenoid = valvesolenoid; + pantograph.valve.start_type = valvestarttype; + } + } + // fuel pump + { + auto lookup = starts.find(extract_value("FuelStart", line)); + FuelPump.start_type = lookup != starts.end() ? lookup->second : manual; + } + // oil pump + { + auto lookup = starts.find(extract_value("OilStart", line)); + OilPump.start_type = lookup != starts.end() ? lookup->second : manual; + } + // genset of a dual-mode vehicle: Manual (the default) needs GensetSwitch, Automatic runs whenever the selector is on it + { + auto lookup = starts.find(extract_value("GensetStart", line)); + Genset.start_type = lookup != starts.end() ? lookup->second : manual; + } + // water pump + { + auto lookup = starts.find(extract_value("WaterStart", line)); + WaterPump.start_type = lookup != starts.end() ? lookup->second : manual; + } + // traction motor fans + { + auto lookup = starts.find(extract_value("MotorBlowersStart", line)); + MotorBlowers[end::rear].start_type = lookup != starts.end() ? lookup->second : manual; + MotorBlowers[end::front].start_type = MotorBlowers[end::rear].start_type; + } + // what else the line contactors need to close + { + std::map> const interlocks{{"Converter", line_contactors_interlock::converter}, + {"MotorBlowers", line_contactors_interlock::motor_blowers}}; + auto lookup = interlocks.find(extract_value("LineContactorsInterlock", line)); + LineContactorsInterlock = lookup != interlocks.end() ? lookup->second : line_contactors_interlock::none; + } + extract_value(LouvresOpenPressure, "LouvresOpenPressure", line, ""); + // compartment lights + { + auto lookup = starts.find(extract_value("CompartmentLightsStart", line)); + CompartmentLights.start_type = lookup != starts.end() ? lookup->second : automatic; // legacy behaviour + } + // ground relay + { + auto lookup = starts.find(extract_value("GroundRelayStart", line)); + auto const defaultstart{TrainType == train_type::emu ? automatic : manual}; + GroundRelayStart = lookup != starts.end() ? lookup->second : defaultstart; + } + // converter overload relay + { + auto lookup = starts.find(extract_value("ConverterOverloadRelayStart", line)); + // the relay of a multiple unit activates when the converter is switched off + auto const defaultstart{TrainType == train_type::emu ? converter : manual}; + ConverterOverloadRelayStart = lookup != starts.end() ? lookup->second : defaultstart; + } +} + +void TMoverParameters::LoadFIZ_Blending(std::string const &line) +{ + + extract_value(MED_Vmax, "MED_Vmax", line, std::to_string(Vmax)); + extract_value(MED_Vmin, "MED_Vmin", line, "0"); + extract_value(MED_Vref, "MED_Vref", line, std::to_string(Vmax)); + extract_value(MED_amax, "MED_amax", line, "9.81"); + extract_value(MED_EPVC, "MED_EPVC", line, ""); + extract_value(MED_Ncor, "MED_Ncor", line, ""); + extract_value(MED_MinBrakeReqED, "MED_MinBrakeReqED", line, ""); + extract_value(MED_FrED_factor, "MED_FrEDFactor", line, ""); + extract_value(MED_ED_Delay1, "MED_FirstDelayED", line, ""); + extract_value(MED_ED_Delay2, "MED_ScndDelayED", line, ""); +} + +void TMoverParameters::LoadFIZ_DCEMUED(std::string const &line) +{ + + extract_value(DCEMUED_CC, "CouplerCheck", line, "0"); + extract_value(DCEMUED_EP_max_Vel, "EP_max_Vel", line, "0"); + extract_value(DCEMUED_EP_min_Im, "EP_min_Im", line, "0"); + extract_value(DCEMUED_EP_delay, "EP_delay", line, "0"); +} + +void TMoverParameters::LoadFIZ_SpringBrake(std::string const &line) +{ + + double vol{1.0}; + extract_value(vol, "Volume", line, "1"); + if (!SpringBrake.Cylinder) + SpringBrake.Cylinder = std::make_shared(); + SpringBrake.Cylinder->CreateCap(vol); + extract_value(SpringBrake.MaxBrakeForce, "MBF", line, ""); + extract_value(SpringBrake.MaxSetPressure, "MaxSP", line, ""); + extract_value(SpringBrake.ResetPressure, "ResetP", line, ""); + extract_value(SpringBrake.MinForcePressure, "MinFP", line, ""); + extract_value(SpringBrake.PressureOff, "PressOff", line, ""); + extract_value(SpringBrake.PressureOn, "PressOn", line, ""); + extract_value(SpringBrake.ValveOffArea, "ValveOnArea", line, ""); + extract_value(SpringBrake.ValveOnArea, "ValveOffArea", line, ""); + extract_value(SpringBrake.ValvePNBrakeArea, "ValvePNBArea", line, ""); + SpringBrake.PNBrakeConnection = SpringBrake.ValvePNBrakeArea > 0; + extract_value(SpringBrake.MultiTractionCoupler, "MTC", line, ""); + SpringBrake.ShuttOff = false; + SpringBrake.Activate = false; + SpringBrake.IsReady = true; +} + +void TMoverParameters::LoadFIZ_Light(std::string const &line) +{ + + LightPowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("Light", line)); + LoadFIZ_PowerParamsDecode(LightPowerSource, "L", line); + + AlterLightPowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("AlterLight", line)); + LoadFIZ_PowerParamsDecode(AlterLightPowerSource, "AlterL", line); + + extract_value(NominalVoltage, "Volt", line, ""); + extract_value(BatteryVoltage, "LMaxVoltage", line, ""); + NominalBatteryVoltage = static_cast(BatteryVoltage); +} + +void TMoverParameters::LoadFIZ_Clima(std::string const &line) +{ + + HeatingPowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("Heating", line)); + LoadFIZ_PowerParamsDecode(HeatingPowerSource, "H", line); + AlterHeatPowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("AlterHeating", line)); + LoadFIZ_PowerParamsDecode(AlterHeatPowerSource, "AlterH", line); +} + +void TMoverParameters::LoadFIZ_Power(std::string const &Line) +{ + + EnginePowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("EnginePower", Line)); + LoadFIZ_PowerParamsDecode(EnginePowerSource, "", Line); + /* + if( ( EnginePowerSource.SourceType == TPowerSource::Generator ) + && ( EnginePowerSource.GeneratorEngine == TEngineType::WheelsDriven ) ) { + // perpetuum mobile? + ConversionError = 666; + } + */ + if (Power == 0.0) + { + // jeśli nie ma mocy, np. rozrządcze EZT + EnginePowerSource.SourceType = TPowerSource::NotDefined; + } + else + { + LoadFIZ_Genset(Line); + } + + SystemPowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("SystemPower", Line)); + LoadFIZ_PowerParamsDecode(SystemPowerSource, "", Line); +} + +// the genset of a dual-mode vehicle (eu07/maszyna#536), on the Power: line; all optional, no genset without GensetPower +void TMoverParameters::LoadFIZ_Genset(std::string const &Line) +{ + extract_value(Genset.power, "GensetPower", Line, ""); + if (false == Genset.fitted()) + { + return; + } + extract_value(Genset.voltage_nominal, "GensetVoltage", Line, ""); + if (Genset.voltage_nominal <= 0.0) + { + Genset.voltage_nominal = EnginePowerSource.MaxVoltage > 0.0 ? 0.65 * EnginePowerSource.MaxVoltage : 3000.0; + } + extract_value(Genset.revolutions_idle, "GensetIdleRPM", Line, "600"); + extract_value(Genset.revolutions_max, "GensetMaxRPM", Line, "1800"); + Genset.revolutions_max = std::max(Genset.revolutions_max, 1.0) / 60.0; + Genset.revolutions_idle = std::clamp(Genset.revolutions_idle / 60.0, 1.0 / 60.0, Genset.revolutions_max); + extract_value(Genset.start_time, "GensetStartTime", Line, "8"); + extract_value(Genset.spinup_time, "GensetSpinUpTime", Line, "3"); + extract_value(Genset.traction_share, "GensetPmaxRatio", Line, "1"); + Genset.start_time = std::max(Genset.start_time, 0.0); + Genset.spinup_time = std::max(Genset.spinup_time, 0.01); + Genset.traction_share = std::clamp(Genset.traction_share, 0.0, 1.0); +} + +void TMoverParameters::LoadFIZ_SpeedControl(std::string const &Line) +{ + // speed control + extract_value(SpeedCtrl, "SpeedCtrl", Line, ""); + if (!SpeedCtrl && EngineType == TEngineType::ElectricInductionMotor && ScndCtrlPosNo > 0) // backward compatibility + SpeedCtrl = true; + extract_value(SpeedCtrlDelay, "SpeedCtrlDelay", Line, ""); + SpeedCtrlTypeTime = extract_value("SpeedCtrlType", Line) == "Time" ? true : false; + extract_value(SpeedCtrlAutoTurnOffFlag, "SpeedCtrlATOF", Line, ""); + + auto speedpresets = Split(extract_value("SpeedButtons", Line), '|'); + int speed_no = 0; + for (auto const &speed : speedpresets) + { + SpeedCtrlButtons[speed_no++] = std::stod(speed); + if (speed_no > 9) + break; + } + extract_value(SpeedCtrlUnit.ManualStateOverride, "OverrideManual", Line, ""); + extract_value(SpeedCtrlUnit.BrakeIntervention, "BrakeIntervention", Line, ""); + extract_value(SpeedCtrlUnit.InitialPower, "InitPwr", Line, ""); + extract_value(SpeedCtrlUnit.FullPowerVelocity, "MaxPwrVel", Line, ""); + extract_value(SpeedCtrlUnit.StartVelocity, "StartVel", Line, ""); + extract_value(SpeedCtrlUnit.VelocityStep, "VelStep", Line, ""); + extract_value(SpeedCtrlUnit.PowerStep, "PwrStep", Line, ""); + extract_value(SpeedCtrlUnit.MinPower, "MinPwr", Line, ""); + extract_value(SpeedCtrlUnit.MaxPower, "MaxPwr", Line, ""); + extract_value(SpeedCtrlUnit.MinVelocity, "MinVel", Line, ""); + extract_value(SpeedCtrlUnit.MaxVelocity, "MaxVel", Line, ""); + extract_value(SpeedCtrlUnit.Offset, "Offset", Line, ""); + extract_value(SpeedCtrlUnit.FactorPpos, "kPpos", Line, ""); + extract_value(SpeedCtrlUnit.FactorPneg, "kPneg", Line, ""); + extract_value(SpeedCtrlUnit.FactorIpos, "kIpos", Line, ""); + extract_value(SpeedCtrlUnit.FactorIneg, "kIneg", Line, ""); + extract_value(SpeedCtrlUnit.BrakeInterventionVel, "BrakeIntMaxVel", Line, ""); + extract_value(SpeedCtrlUnit.PowerUpSpeed, "PowerUpSpeed", Line, ""); + extract_value(SpeedCtrlUnit.PowerDownSpeed, "PowerDownSpeed", Line, ""); +} + +void TMoverParameters::LoadFIZ_Engine(std::string const &Input) +{ + + EngineType = LoadFIZ_EngineDecode(extract_value("EngineType", Input)); + extract_value(JointEngineStart, "JointEngineStart", Input, ""); + + if (std::string transmission = extract_value("Trans", Input); false == transmission.empty()) + { + // transmission type. moved here because more than one engine type has this entry + auto ratios = Split(transmission, ':'); // e.g. 18:79 + + if (ratios.size() != 2) + { + ErrorLog("Wrong transmition definition: " + transmission); + } + + Transmision.NToothM = std::atoi(ratios[0].c_str()); // ToothM to pierwszy czyli 18 + Transmision.NToothW = std::atoi(ratios[1].c_str()); // ToothW to drugi parametr czyli 79 + + if (Transmision.NToothM > 0) + Transmision.Ratio = static_cast(Transmision.NToothW) / Transmision.NToothM; + else + Transmision.Ratio = 1.0; + extract_value(Transmision.Efficiency, "TransEff", Input, ""); + } + + switch (EngineType) + { + + case TEngineType::ElectricSeriesMotor: + { + + extract_value(NominalVoltage, "Volt", Input, ""); + extract_value(WindingRes, "WindingRes", Input, ""); + if (WindingRes == 0.0) + { + + WindingRes = 0.01; + } + extract_value(nmax, "nmax", Input, ""); + nmax /= 60.0; + break; + } + case TEngineType::WheelsDriven: + case TEngineType::Dumb: + { + + extract_value(Ftmax, "Ftmax", Input, ""); + break; + } + case TEngineType::DieselEngine: + { + LoadFIZ_EngineDiesel(Input); + break; + } + case TEngineType::DieselElectric: + { // youBy + LoadFIZ_EngineDieselElectric(Input); + break; + } + case TEngineType::ElectricInductionMotor: + { + LoadFIZ_EngineInductionMotor(Input); + break; + } + default: + { + // nothing here + } + } // engine type + + // NOTE: elements shared by both diesel engine variants; crude but, eh + if (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric) + { + LoadFIZ_EngineDieselShared(Input); + } + + // traction motors + extract_value(MotorBlowers[end::front].speed, "MotorBlowersSpeed", Input, ""); + extract_value(MotorBlowers[end::front].sustain_time, "MotorBlowersSustainTime", Input, ""); + extract_value(MotorBlowers[end::front].min_start_velocity, "MotorBlowersStartVelocity", Input, ""); + MotorBlowers[end::rear] = MotorBlowers[end::front]; + // pressure switch + extract_value(HasControlPressureSwitch, "PressureSwitch", Input, TrainType != train_type::emu ? "yes" : "no"); + // its brake cylinder half; the brake pipe one stays + extract_value(PressureSwitchBrakeCylinder, "PressureSwitchBrakeCylinder", Input, ""); +} + +// Engine: of a diesel engine, its revolutions, gears, hydraulic transmission and retarder +void TMoverParameters::LoadFIZ_EngineDiesel(std::string const &Input) +{ + + extract_value(dizel_nmin, "nmin", Input, ""); + dizel_nmin /= 60.0; + dizel_nreg_min = dizel_nmin * 0.98; + extract_value(dizel_nmin_hdrive, "nmin_hdrive", Input, ""); + dizel_nmin_hdrive /= 60.0; + if (dizel_nmin_hdrive == 0.0) + { + dizel_nmin_hdrive = dizel_nmin; + } + extract_value(dizel_nmin_hdrive_factor, "nmin_hdrive_factor", Input, ""); + dizel_nmin_hdrive_factor /= 60.0; + extract_value(dizel_nmin_retarder, "nmin_retarder", Input, ""); + dizel_nmin_retarder /= 60.0; + if (dizel_nmin_retarder == 0.0) + { + dizel_nmin_retarder = dizel_nmin; + } + // TODO: unify naming scheme and sort out which diesel engine params are used where and how + extract_value(nmax, "nmax", Input, ""); + nmax /= 60.0; + extract_value(dizel_nmax_cutoff, "nmax_cutoff", Input, "0.0"); + dizel_nmax_cutoff /= 60.0; + extract_value(dizel_nreg_acc, "nreg_acc", Input, ""); + dizel_nreg_acc /= 60.0; + extract_value(dizel_AIM, "AIM", Input, "1.0"); + extract_value(dizel_RevolutionsDecreaseRate, "RPMDecRate", Input, ""); + + extract_value(engageupspeed, "EUS", Input, "0.5"); + extract_value(engagedownspeed, "EDS", Input, "0.9"); + + if (true == extract_value(AnPos, "ShuntMode", Input, "")) + { + // dodatkowa przekładnia dla SM03 (2Ls150) + ShuntModeAllow = true; + ShuntMode = false; + if (AnPos < 1.0) + { + //"rozruch wysoki" ma dawać większą siłę + AnPos = 1.0 / AnPos; // im większa liczba, tym wolniej jedzie + } + } + extract_value(hydro_TC, "IsTC", Input, ""); + if (true == hydro_TC) + { + extract_value(hydro_TC_TMMax, "TC_TMMax", Input, ""); + extract_value(hydro_TC_CouplingPoint, "TC_CP", Input, ""); + extract_value(hydro_TC_LockupTorque, "TC_LT", Input, ""); + extract_value(hydro_TC_LockupRate, "TC_LR", Input, ""); + extract_value(hydro_TC_UnlockRate, "TC_ULR", Input, ""); + extract_value(hydro_TC_FillRateInc, "TC_FRI", Input, ""); + extract_value(hydro_TC_FillRateDec, "TC_FRD", Input, ""); + extract_value(hydro_TC_TorqueInIn, "TC_TII", Input, ""); + extract_value(hydro_TC_TorqueInOut, "TC_TIO", Input, ""); + extract_value(hydro_TC_TorqueOutOut, "TC_TOO", Input, ""); + extract_value(hydro_TC_LockupSpeed, "TC_LS", Input, ""); + extract_value(hydro_TC_UnlockSpeed, "TC_ULS", Input, ""); + extract_value(dizel_maxVelANS, "MaxVelANS", Input, ""); + + extract_value(hydro_R, "IsRetarder", Input, ""); + if (true == hydro_R) + { + extract_value(hydro_R_Placement, "R_Place", Input, ""); + extract_value(hydro_R_TorqueInIn, "R_TII", Input, ""); + extract_value(hydro_R_MaxTorque, "R_MT", Input, ""); + extract_value(hydro_R_MaxPower, "R_MP", Input, ""); + extract_value(hydro_R_FillRateInc, "R_FRI", Input, ""); + extract_value(hydro_R_FillRateDec, "R_FRD", Input, ""); + extract_value(hydro_R_MinVel, "R_MinVel", Input, ""); + extract_value(hydro_R_EngageVel, "R_EngageVel", Input, ""); + extract_value(hydro_R_Clutch, "R_IsClutch", Input, ""); + extract_value(hydro_R_ClutchSpeed, "R_ClutchSpeed", Input, ""); + extract_value(hydro_R_WithIndividual, "R_WithIndividual", Input, ""); + } + } +} + +// Engine: of a diesel-electric +void TMoverParameters::LoadFIZ_EngineDieselElectric(std::string const &Input) +{ + + extract_value(Ftmax, "Ftmax", Input, ""); + Flat = extract_value("Flat", Input) == "1"; + extract_value(Vhyp, "Vhyp", Input, ""); + Vhyp /= 3.6; + extract_value(Vadd, "Vadd", Input, ""); + Vadd /= 3.6; + extract_value(PowerCorRatio, "Cr", Input, ""); + extract_value(RelayType, "RelayType", Input, ""); + if (extract_value("ShuntMode", Input) == "1") + { + + ShuntModeAllow = true; + ShuntMode = false; + AnPos = 0.0; + ImaxHi = 2; + ImaxLo = 1; + } + extract_value(EngineHeatingRPM, "HeatingRPM", Input, ""); + extract_value(dizel_AIM, "AIM", Input, "1.25"); + extract_value(dizel_RevolutionsDecreaseRate, "RPMDecRate", Input, ""); + LoadFIZ_DieselElectricDynamicBrake(Input); +} + +// Engine: of an induction motor drive +void TMoverParameters::LoadFIZ_EngineInductionMotor(std::string const &Input) +{ + + RVentnmax = 1.0; + extract_value(NominalVoltage, "Volt", Input, ""); + + extract_value(eimc[eimc_s_dfic], "dfic", Input, ""); + extract_value(eimc[eimc_s_dfmax], "dfmax", Input, ""); + extract_value(eimc[eimc_s_p], "p", Input, ""); + extract_value(eimc[eimc_s_cfu], "cfu", Input, ""); + extract_value(eimc[eimc_s_cim], "cim", Input, ""); + extract_value(eimc[eimc_s_icif], "icif", Input, ""); + extract_value(eimc[eimc_f_Uzmax], "Uzmax", Input, ""); + extract_value(eimc[eimc_f_Uzh], "Uzh", Input, ""); + extract_value(eimc[eimc_f_DU], "DU", Input, ""); + extract_value(eimc[eimc_f_I0], "I0", Input, ""); + extract_value(eimc[eimc_f_cfu], "fcfu", Input, ""); + if (false == extract_value(eimc[eimc_f_cfuH], "fcfuH", Input, "")) + { + // without its own figure the dynamic brake takes the one of the traction + eimc[eimc_f_cfuH] = eimc[eimc_f_cfu]; + } + extract_value(eimc[eimc_p_F0], "F0", Input, ""); + extract_value(eimc[eimc_p_a1], "a1", Input, ""); + extract_value(eimc[eimc_p_Pmax], "Pmax", Input, ""); + extract_value(eimc[eimc_p_Fh], "Fh", Input, ""); + extract_value(eimc[eimc_p_Ph], "Ph", Input, ""); + extract_value(eimc[eimc_p_Vh0], "Vh0", Input, ""); + extract_value(eimc[eimc_p_Vh1], "Vh1", Input, ""); + extract_value(eimc[eimc_p_Imax], "Imax", Input, ""); + extract_value(eimc[eimc_p_abed], "abed", Input, ""); + extract_value(eimc[eimc_p_eped], "edep", Input, ""); + extract_value(EIMCLogForce, "eimclf", Input, ""); + extract_value(InvertersNo, "InvNo", Input, ""); + extract_value(InverterControlCouplerFlag, "InvCtrCplFlag", Input, ""); + extract_value(Imaxrpc, "Imaxrpc", Input, ""); + extract_value(BRVto, "BRVto", Input, ""); + extract_value(Flat, "Flat", Input, ""); + + if (eimc[eimc_p_Pmax] > 0 && Power > 0 && InvertersNo == 0) + { + InvertersNo = 1; + } + Inverters.resize(InvertersNo); + /*for (int i = 0; i > InvertersNo; i++) + { + inverter x; + Inverters.emplace_back(x); + }*/ +} + +// Engine: what both kinds of diesels have, their heat among it +void TMoverParameters::LoadFIZ_EngineDieselShared(std::string const &Input) +{ + // oil pump + extract_value(OilPump.pressure_minimum, "OilMinPressure", Input, ""); + extract_value(OilPump.pressure_maximum, "OilMaxPressure", Input, ""); + // the time the starter turns the engine before it fires and smokes (eu07/maszyna#523) + extract_value(dizel_SmokeDelay, "SmokeDelay", Input, "0"); + dizel_SmokeDelay = std::max(0.0, dizel_SmokeDelay); + // engine cooling factore + extract_value(dizel_heat.kw, "HeatKW", Input, ""); + extract_value(dizel_heat.kv, "HeatKV", Input, ""); + extract_value(dizel_heat.kfe, "HeatKFE", Input, ""); + extract_value(dizel_heat.kfs, "HeatKFS", Input, ""); + extract_value(dizel_heat.kfo, "HeatKFO", Input, ""); + extract_value(dizel_heat.kfo2, "HeatKFO2", Input, ""); + // engine cooling systems + extract_value(dizel_heat.water.config.temp_min, "WaterMinTemperature", Input, ""); + extract_value(dizel_heat.water.config.temp_max, "WaterMaxTemperature", Input, ""); + extract_value(dizel_heat.water.config.temp_flow, "WaterFlowTemperature", Input, ""); + extract_value(dizel_heat.water.config.temp_cooling, "WaterCoolingTemperature", Input, ""); + extract_value(dizel_heat.water.config.shutters, "WaterShutters", Input, ""); + extract_value(dizel_heat.auxiliary_water_circuit, "WaterAuxCircuit", Input, ""); + extract_value(dizel_heat.water_aux.config.temp_min, "WaterAuxMinTemperature", Input, ""); + extract_value(dizel_heat.water_aux.config.temp_max, "WaterAuxMaxTemperature", Input, ""); + extract_value(dizel_heat.water_aux.config.temp_cooling, "WaterAuxCoolingTemperature", Input, ""); + extract_value(dizel_heat.water_aux.config.shutters, "WaterAuxShutters", Input, ""); + extract_value(dizel_heat.oil.config.temp_min, "OilMinTemperature", Input, ""); + extract_value(dizel_heat.oil.config.temp_max, "OilMaxTemperature", Input, ""); + extract_value(dizel_heat.engine_max_temp, "EngineMaxTemperature", Input, ""); + extract_value(dizel_heat.fan_speed, "WaterCoolingFanSpeed", Input, ""); + // water heater + extract_value(WaterHeater.config.temp_min, "HeaterMinTemperature", Input, ""); + extract_value(WaterHeater.config.temp_max, "HeaterMaxTemperature", Input, ""); + float pf{1235.f}; + extract_value(pf, "NominalCoolingPower", Input, "1235"); + dizel_heat.powerfactor = 1235 / pf; +} + +void TMoverParameters::LoadFIZ_Switches(std::string const &Input) +{ + + extract_value(PantSwitchType, "Pantograph", Input, ""); + extract_value(ConvSwitchType, "Converter", Input, ""); + extract_value(StLinSwitchType, "MotorConnectors", Input, ""); + HeatingSwitchImpulse = ToLower(extract_value("TrainHeating", Input)) == "impulse"; + // because people can't make up their minds whether it's "impulse" or "Impulse"... + PantSwitchType = ToLower(PantSwitchType); + ConvSwitchType = ToLower(ConvSwitchType); + StLinSwitchType = ToLower(StLinSwitchType); + // universal reset buttons assignments + extract_value(UniversalResetButtonFlag[0], "RelayResetButton1", Input, ""); + extract_value(UniversalResetButtonFlag[1], "RelayResetButton2", Input, ""); + extract_value(UniversalResetButtonFlag[2], "RelayResetButton3", Input, ""); + extract_value(enableModernDimmer, "ModernDimmer", Input, ""); + // pantograph presets + { + auto &presets{PantsPreset.first}; + extract_value(presets, "PantographPresets", Input, "0|1|3|2"); + std::erase(presets, '|'); + } +} + +void TMoverParameters::LoadFIZ_MotorParamTable(std::string const &Input) +{ + + switch (EngineType) + { + + case TEngineType::DieselEngine: + { + + extract_value(dizel_minVelfullengage, "minVelfullengage", Input, ""); + extract_value(dizel_engageDia, "engageDia", Input, ""); + extract_value(dizel_engageMaxForce, "engageMaxForce", Input, ""); + extract_value(dizel_engagefriction, "engagefriction", Input, ""); + break; + } + default: + { + // nothing here + } + } +} + +void TMoverParameters::LoadFIZ_Circuit(std::string const &Input) +{ + + extract_value(CircuitRes, "CircuitRes", Input, ""); + extract_value(IminLo, "IminLo", Input, ""); + extract_value(IminHi, "IminHi", Input, ""); + extract_value(ImaxLo, "ImaxLo", Input, ""); + extract_value(ImaxHi, "ImaxHi", Input, ""); + Imin = IminLo; + Imax = ImaxLo; + extract_value(TUHEX_Sum, "TUHEX_Sum", Input, ""); + extract_value(TUHEX_Diff, "TUHEX_Diff", Input, ""); + extract_value(TUHEX_MaxIw, "TUHEX_MaxIw", Input, ""); + extract_value(TUHEX_MinIw, "TUHEX_MinIw", Input, ""); + extract_value(TUHEX_Sum1, "TUHEX_Sum1", Input, ""); + extract_value(TUHEX_Sum2, "TUHEX_Sum2", Input, ""); + extract_value(TUHEX_Sum3, "TUHEX_Sum3", Input, ""); + extract_value(TUHEX_Stages, "TUHEX_Stages", Input, "0"); +} + +void TMoverParameters::LoadFIZ_AI(std::string const &Input) +{ + + extract_value(AIHintPantstate, "Pantstate", Input, ""); + extract_value(AIHintShuntPantstate, "ShuntPantstate", Input, ""); + extract_value(AIHintPantUpIfIdle, "IdlePantUp", Input, ""); + extract_value(AIHintLocalBrakeAccFactor, "LocalBrakeAccFactor", Input, ""); +} + +void TMoverParameters::LoadFIZ_RList(std::string const &Input) +{ + + extract_value(RlistSize, "Size", Input, ""); + + if (auto const venttype{ToLower(extract_value("RVent", Input))}; venttype == "automatic") + { + + RVentType = 2; + } + else + { + + RVentType = venttype == "yes" ? 1 : 0; + } + + if (RVentType > 0) + { + + extract_value(RVentnmax, "RVentnmax", Input, ""); + RVentnmax /= 60.0; + extract_value(RVentCutOff, "RVentCutOff", Input, ""); + } + extract_value(RVentMinI, "RVentMinI", Input, ""); + extract_value(RVentSpeed, "RVentSpeed", Input, ""); + extract_value(DynamicBrakeRes, "DynBrakeRes", Input, ""); + extract_value(DynamicBrakeRes1, "DynBrakeRes1", Input, ""); + extract_value(DynamicBrakeRes2, "DynBrakeRes2", Input, ""); +} + +// the dynamic brake of a diesel-electric vehicle, from its Engine section: none without EDBrake +void TMoverParameters::LoadFIZ_DieselElectricDynamicBrake(std::string const &Input) +{ + using enum diesel_electric_dynamic_brake::control; + std::map> const sources{{"Controller", controller}, {"Lever", lever}}; + auto const lookup{sources.find(extract_value("EDBrake", Input))}; + if (lookup == sources.end()) + { + return; + } + auto &brake{DEDynamicBrake}; + brake.source = lookup->second; + auto force{0.0}; // [kN] + auto power{0.0}; // [kW] + extract_value(force, "EDBrakeFmax", Input, ""); + extract_value(power, "EDBrakePmax", Input, ""); + brake.max_force = force * 1000.0; + brake.max_power = power * 1000.0; + extract_value(brake.fade_low, "EDBrakeV0", Input, ""); + extract_value(brake.fade_high, "EDBrakeV1", Input, ""); + extract_value(brake.rate, "EDBrakeRate", Input, ""); + extract_value(brake.blending, "EDBrakeBlending", Input, ""); + if (brake.source == lever) + { + // the lever of its own, which the commands of the dynamic brake controller move + SplitEDPneumaticBrake = true; + } +} + +void TMoverParameters::LoadFIZ_UCList(std::string const &Input) +{ + + extract_value(UniCtrlListSize, "Size", Input, ""); + extract_value(UniCtrlIntegratedBrakeCtrl, "IntegratedBrake", Input, ""); + extract_value(UniCtrlIntegratedLocalBrakeCtrl, "IntegratedLocBrake", Input, ""); + extract_value(UniCtrlIntegratedBrakePNCtrl, "IntegratedBrakePN", Input, ""); + extract_value(UniCtrlValStep, "CtrlValStep", Input, ""); + UniCtrlValStep = std::max(UniCtrlValStep, 0.0); +} + +void TMoverParameters::LoadFIZ_DList(std::string const &Input) +{ + + extract_value(dizel_Mmax, "Mmax", Input, ""); + extract_value(dizel_nMmax, "nMmax", Input, ""); + extract_value(dizel_Mnmax, "Mnmax", Input, ""); + extract_value(dizel_nmax, "nmax", Input, ""); + extract_value(dizel_nominalfill, "nominalfill", Input, ""); + extract_value(dizel_Mstand, "Mstand", Input, ""); + extract_value(dizel_NominalFuelConsumptionRate, "NomFuelConsRate", Input, ""); + + if (dizel_nMmax == dizel_nmax) + { + // HACK: guard against cases where nMmax == nmax, leading to division by 0 in momentum calculation + dizel_nMmax = dizel_nmax - 1.0 / 60.0; + } + + // Calculation of fuel consumption coefficient for futher calculation + double dizel_max_power = dizel_nmax * (dizel_Mnmax - dizel_Mstand) * M_PI * 2 * 0.001; // power in kW + double dizel_max_energy = dizel_max_power; // energy per one hour in kWh is equal to power in kW times 1 h + double fuel_density = 850; // g/l + dizel_FuelConsumption = dizel_NominalFuelConsumptionRate * dizel_max_energy / fuel_density / dizel_nmax; +} + +void TMoverParameters::LoadFIZ_FFList(std::string const &Input) +{ + extract_value(FFListSize, "Size", Input, ""); +} + +void TMoverParameters::LoadFIZ_FFEDList(std::string const &Input) +{ + extract_value(FFEDListSize, "Size", Input, ""); +} + +void TMoverParameters::LoadFIZ_WiperList(std::string const &Input) +{ + extract_value(WiperListSize, "Size", Input, ""); + extract_value(WiperAngle, "Angle", Input, ""); + extract_value(WiperDefaultPos, "Default", Input, ""); +} + +void TMoverParameters::LoadFIZ_DimmerList(std::string const &Input) +{ + // extract_value(modernWpierListSize, "Size", Input, ""); + extract_value(modernDimmerCanCycle, "Cycle", Input, ""); + extract_value(modernDimmerDefaultPosition, "DefaultPos", Input, ""); +} +void TMoverParameters::LoadFIZ_LightsList(std::string const &Input) +{ + + extract_value(LightsPosNo, "Size", Input, ""); + extract_value(LightsWrap, "Wrap", Input, ""); + extract_value(LightsDefPos, "Default", Input, ""); +} + +void TMoverParameters::LoadFIZ_CompressorList(std::string const &Input) +{ + + extract_value(CompressorListPosNo, "Size", Input, ""); + extract_value(CompressorListWrap, "Wrap", Input, ""); + extract_value(CompressorListDefPos, "Default", Input, ""); +} + +void TMoverParameters::LoadFIZ_PowerParamsDecode(TPowerParameters &Powerparameters, std::string const &Prefix, std::string const &Line) +{ + + switch (Powerparameters.SourceType) + { + + case TPowerSource::NotDefined: + case TPowerSource::InternalSource: + { + + Powerparameters.PowerType = LoadFIZ_PowerDecode(extract_value(Prefix + "PowerType", Line)); + break; + } + case TPowerSource::Transducer: + { + + extract_value(Powerparameters.Transducer.InputVoltage, Prefix + "TransducerInputV", Line, ""); + break; + } + case TPowerSource::Generator: + { + // prime mover for the generator + auto &generatorparameters{Powerparameters.EngineGenerator}; + + if (auto const enginetype{LoadFIZ_EngineDecode(extract_value(Prefix + "GeneratorEngine", Line))}; enginetype == TEngineType::Main) + { + generatorparameters.engine_revolutions = &enrot; + } + else + { + // TODO: for engine types other than Main create requested engine object and link to its revolutions + generatorparameters.engine_revolutions = nullptr; + generatorparameters.revolutions = 0; + generatorparameters.voltage = 0; + } + // config + extract_value(generatorparameters.voltage_min, Prefix + "GeneratorMinVoltage", Line, "0"); + extract_value(generatorparameters.voltage_max, Prefix + "GeneratorMaxVoltage", Line, "0"); + // NOTE: for consistency the fiz file specifies revolutions per minute + extract_value(generatorparameters.revolutions_min, Prefix + "GeneratorMinRPM", Line, "0"); + extract_value(generatorparameters.revolutions_max, Prefix + "GeneratorMaxRPM", Line, "0"); + generatorparameters.revolutions_min /= 60; + generatorparameters.revolutions_max /= 60; + break; + } + case TPowerSource::Accumulator: + { + + extract_value(Powerparameters.RAccumulator.MaxCapacity, Prefix + "Cap", Line, ""); + Powerparameters.RAccumulator.RechargeSource = LoadFIZ_SourceDecode(extract_value(Prefix + "RS", Line)); + break; + } + case TPowerSource::CurrentCollector: + { + + auto &collectorparameters = Powerparameters.CollectorParameters; + + collectorparameters = TCurrentCollector{0, 0, 0, 0, 0, 0, false, 0, 0, 0, false, 0}; + + std::string PantType = ""; + extract_value(PantType, "PantType", Line, ""); + if (PantType == "AKP_4E") + collectorparameters.PantographType = TPantType::AKP_4E; + if (PantType.size() >= 3 && PantType.compare(0, 3, "DSA") == 0) + collectorparameters.PantographType = TPantType::DSAx; + if (PantType == "EC160" || PantType == "EC200") + collectorparameters.PantographType = TPantType::EC160_200; + if (PantType == "WBL85") + collectorparameters.PantographType = TPantType::WBL85; + + extract_value(collectorparameters.CollectorsNo, "CollectorsNo", Line, ""); + extract_value(collectorparameters.MinH, "MinH", Line, ""); + extract_value(collectorparameters.MaxH, "MaxH", Line, ""); + extract_value(collectorparameters.CSW, "CSW", Line, ""); // szerokość części roboczej + extract_value(collectorparameters.MaxV, "MaxVoltage", Line, ""); + extract_value(collectorparameters.OVP, "OverVoltProt", Line, ""); // przekaźnik nadnapięciowy + // napięcie rozłączające WS + collectorparameters.MinV = 0.5 * collectorparameters.MaxV; // gdyby parametr nie podany + extract_value(collectorparameters.MinV, "MinV", Line, ""); + // napięcie wymagane do załączenia WS + collectorparameters.InsetV = 0.6 * collectorparameters.MaxV; // gdyby parametr nie podany + extract_value(collectorparameters.InsetV, "InsetV", Line, ""); + // ciśnienie rozłączające WS + extract_value(collectorparameters.MinPress, "MinPress", Line, "3.5"); // domyślnie 2 bary do załączenia WS + // maksymalne ciśnienie za reduktorem + // collectorparameters.MaxPress = 5.0 + 0.001 * ( Random( 50 ) - Random( 50 ) ); + extract_value(collectorparameters.MaxPress, "MaxPress", Line, "5.0"); + extract_value(collectorparameters.FakePower, "FakePower", Line, ""); + if (extract_value(collectorparameters.PhysicalLayout, "PhysicalLayout", Line, "3")) + collectorparameters.CollectorsNo = std::min(collectorparameters.PhysicalLayout, 2); + break; + } + case TPowerSource::PowerCable: + { + + Powerparameters.RPowerCable.PowerTrans = LoadFIZ_PowerDecode(extract_value(Prefix + "PowerTrans", Line)); + if (Powerparameters.RPowerCable.PowerTrans == TPowerType::SteamPower) + { + + extract_value(Powerparameters.RPowerCable.SteamPressure, Prefix + "SteamPress", Line, ""); + } + break; + } + case TPowerSource::Heater: + { + // jeszcze nie skonczone! + break; + } + default:; // nothing here + } + + if (Powerparameters.SourceType != TPowerSource::Heater && Powerparameters.SourceType != TPowerSource::InternalSource) + { + + extract_value(Powerparameters.MaxVoltage, Prefix + "MaxVoltage", Line, ""); + extract_value(Powerparameters.MaxCurrent, Prefix + "MaxCurrent", Line, ""); + extract_value(Powerparameters.IntR, Prefix + "IntR", Line, ""); + } +} + +TPowerType TMoverParameters::LoadFIZ_PowerDecode(std::string const &Powertype) const +{ + using enum TPowerType; + + std::map> powertypes{ + {"BioPower", BioPower}, {"MechPower", MechPower}, {"ElectricPower", ElectricPower}, {"SteamPower", SteamPower}}; + auto lookup = powertypes.find(Powertype); + return lookup != powertypes.end() ? lookup->second : NoPower; +} + +TPowerSource TMoverParameters::LoadFIZ_SourceDecode(std::string const &Source) const +{ + using enum TPowerSource; + + std::map> powersources{{"Transducer", Transducer}, {"Generator", Generator}, + {"Accu", Accumulator}, // legacy compatibility leftover. TODO: check if we can get rid of it + {"Accumulator", Accumulator}, {"CurrentCollector", CurrentCollector}, + {"PowerCable", PowerCable}, {"Heater", Heater}, + {"Internal", InternalSource}, {"Main", Main}}; + auto lookup = powersources.find(Source); + return lookup != powersources.end() ? lookup->second : NotDefined; +} + +TEngineType TMoverParameters::LoadFIZ_EngineDecode(std::string const &Engine) const +{ + using enum TEngineType; + + std::map> enginetypes{{"ElectricSeriesMotor", ElectricSeriesMotor}, + {"DieselEngine", DieselEngine}, + {"SteamEngine", SteamEngine}, + {"WheelsDriven", WheelsDriven}, + {"Dumb", Dumb}, + {"DieselElectric", DieselElectric}, + {"DumbDE", DieselElectric}, + {"ElectricInductionMotor", ElectricInductionMotor}, + {"Main", Main}}; + auto lookup = enginetypes.find(Engine); + return lookup != enginetypes.end() ? lookup->second : None; +} diff --git a/physics/mover/internal.h b/physics/mover/internal.h new file mode 100644 index 000000000..c85dd999f --- /dev/null +++ b/physics/mover/internal.h @@ -0,0 +1,33 @@ +/* +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 helpers the files of physics/mover/ share: only they include this header + +#pragma once + +#include "physics/mover.h" + +const double CouplerTune = 0.1; // skalowanie tlumiennosci + + +inline double square(double val) // SQR() zle liczylo w current() ... +{ + return val * val; +} + +int DirPatch(int Coupler1, int Coupler2); + +int DirF(int CouplerN); + +double TableInterpolation(std::map &Map, double Parameter); + +double compression_at(TCoupling const &Coupler, int const End); + +bool issection(std::string_view Name, std::string_view Input); + diff --git a/physics/mover/mover.cpp b/physics/mover/mover.cpp new file mode 100644 index 000000000..bc9c74d65 --- /dev/null +++ b/physics/mover/mover.cpp @@ -0,0 +1,1351 @@ +/* +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 vehicle as a body: construction, the forces on it, its movement along the track, adhesion and sand + +#include "stdafx.h" +#include "physics/mover.h" +#include "vehicle/DynObj.h" +#include "physics/oerlikonest.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/Timer.h" +#include "utilities/parser.h" +#include "simulation/simulation.h" +#include "vehicle/fieldshunting.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "physics/mover/internal.h" + + +std::vector const TMoverParameters::eimc_labels = {"dfic: ", "dfmax:", "p: ", "scfu: ", "cim: ", "icif: ", "Uzmax:", "Uzh: ", "DU: ", "I0: ", "fcfu: ", + "F0: ", "a1: ", "Pmax: ", "Fh: ", "Ph: ", "Vh0: ", "Vh1: ", "Imax: ", "abed: ", "eped: "}; + +std::vector const TMoverParameters::eimv_labels = { + "Fkrt:", "Fmax:", "ks: ", "df: ", "fp: ", "Us: ", "pole:", "Ic: ", "If: ", "M: ", "Fr: ", "Ipoj:", "Pm: ", "Pe: ", "eta: ", "fkr: ", "Uzsm:", "Pmax:", "Fzad:", "Imax:", "Fful:"}; + +int DirPatch(int Coupler1, int Coupler2) +{ // poprawka dla liczenia sil przy ustawieniu przeciwnym obiektow + return Coupler1 != Coupler2 ? 1 : -1; +} +namespace +{ + + +// physics.collisions new: a rail vehicle derailed the legacy way keeps the deceleration of the legacy model, g, as the +// friction of its weight, and the forces of the vehicles coupled to it act on it as on any other: the train behind it +// pushes it on, and it holds the train back. alone it stops as the legacy model has it. the legacy model stops it +// whatever pushes it, and the train behind it stopped at once against it, in a hit no train had +bool legacy_derailed_slides(TMoverParameters const &Vehicle) +{ + return Global.collisions == global_settings::collision_model::physical && TestFlag(Vehicle.CategoryFlag, 1) && TestFlag(Vehicle.DamageFlag, dtrain_out) && + Vehicle.Derailed == derailment::outcome::none; +} + +} // namespace + +int DirF(int CouplerN) +{ + switch (CouplerN) + { + case 0: + return -1; + case 1: + return 1; + default: + return 0; + } +} + +// ************************************************************************************************* +// główny konstruktor +// ************************************************************************************************* +TMoverParameters::TMoverParameters(double VelInitial, std::string const &TypeNameInit, std::string const &NameInit, int Cab) : TypeName(TypeNameInit), Name(NameInit), CabOccupied(Cab) +{ + WriteLog("------------------------------------------------------"); + WriteLog("init default physic values for " + NameInit + ", [" + TypeNameInit + "]"); + + // BrakeLevelSet(-2); //Pascal ustawia na 0, przestawimy na odcięcie (CHK jest jeszcze nie wczytane!) + iLights[0] = 0; + iLights[1] = 0; // światła zgaszone + + // inicjalizacja stalych + for (auto &scheme : RList) + { + scheme = TScheme(); + } + RlistSize = 0; + for (auto &motorparam : MotorParam) + { + motorparam = TMotorParameters(); + } + + for (auto &cablights : Lights) + for (int k = 0; k < 17; ++k) + cablights[k] = 0; + + for (auto &compressorrow : CompressorList) + for (int k = 1; k < 9; ++k) + compressorrow[k] = 0; + CompressorList[0][0] = 0.0; + CompressorList[1][0] = 1.0; + CompressorList[2][0] = 1.0; + CompressorList[3][0] = 1.0; + + for (int b = -1; b <= MainBrakeMaxPos; ++b) + { + BrakePressureTable[b].PipePressureVal = 0.0; + BrakePressureTable[b].BrakePressureVal = 0.0; + BrakePressureTable[b].FlowSpeedVal = 0.0; + } + // with BrakePressureTable[-2] do {pozycja odciecia} + { + BrakePressureTable[-2].PipePressureVal = -1.0; + BrakePressureTable[-2].BrakePressureVal = -1.0; + BrakePressureTable[-2].FlowSpeedVal = 0.0; + } + for (auto &delay : BrakeDelay) + { + delay = 0.0; + } + + for (int b = 0; b < 2; ++b) // Ra: kto tu zrobił "for b:=1 to 2 do" ??? + { + Couplers[b].CouplerType = TCouplerType::NoCoupler; + Couplers[b].SpringKB = 1.0; + Couplers[b].SpringKC = 1.0; + Couplers[b].DmaxB = 0.1; + Couplers[b].FmaxB = 1000.0; + Couplers[b].DmaxC = 0.1; + Couplers[b].FmaxC = 1000.0; + } + for (auto &cylindermult : BrakeCylMult) + { + cylindermult = 0.0; + } + + for (auto &eimcvalue : eimc) + { + eimcvalue = 0.0; + } + eimc[eimc_p_eped] = 1.5; + + for (auto &couplerentry : Couplers) + { + couplerentry.AllowedFlag = 3; // domyślnie hak i hamulec, inne trzeba włączyć jawnie w FIZ + couplerentry.CouplingFlag = 0; + couplerentry.Connected = nullptr; + couplerentry.ConnectedNr = 0; // Ra: to nie ma znaczenia jak nie podłączony + couplerentry.Render = false; + couplerentry.CForce = 0.0; + couplerentry.Dist = 0.0; + couplerentry.CheckCollision = false; + } + + for (auto &brakepress : MaxBrakePress) + { + brakepress = 0.0; + } + + Vel = abs(VelInitial); + V = VelInitial / 3.6; + + for (auto &eimvvalue : eimv) + { + eimvvalue = 0.0; + } + + RunningShape.Len = 1.0; + + RunningTrack.CategoryFlag = CategoryFlag; + RunningTrack.Width = TrackW; + RunningTrack.friction = Steel2Steel_friction; + RunningTrack.QualityFlag = 20; + RunningTrack.DamageFlag = 0; + RunningTrack.Velmax = 100.0; // dla uzytku maszynisty w ai_driver} + + RunningTraction.TractionVoltage = 0.0; + RunningTraction.TractionFreq = 0.0; + RunningTraction.TractionMaxCurrent = 0.0; + RunningTraction.TractionResistivity = 1.0; +}; + +void TMoverParameters::change_train_velocity(double const Change) +{ + // the vehicles coupled to this one in a line, each with the direction of its axis to the axis of this one + std::vector> train{{this, 1}}; + for (std::size_t i = 0; i < train.size(); ++i) + { + auto const [vehicle, direction] = train[i]; + for (int end = end::front; end <= end::rear; ++end) + { + auto const &coupler{vehicle->Couplers[end]}; + auto *other{coupler.Connected}; + if (other == nullptr || coupler.CouplingFlag == coupling::faux || std::any_of(train.begin(), train.end(), [other](auto const &Entry) { return Entry.first == other; })) + { + continue; + } + auto const otherdirection{direction * DirPatch(end, coupler.ConnectedNr)}; + other->V += Change * otherdirection; + train.emplace_back(other, otherdirection); + } + } +} + +// ************************************************************************************************* +// Oblicza przemieszczenie taboru +// ************************************************************************************************* +double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShape &Shape, TTrackParam const &Track, TTractionParam const &ElectricTraction, TLocation const &NewLoc, TRotation const &NewRot) +{ + + if (!TestFlag(DamageFlag, dtrain_out)) + { // Ra: to przepisywanie tu jest bez sensu + RunningShape = Shape; + RunningTrack = Track; + RunningTraction = ElectricTraction; + + // if (!DynamicBrakeFlag) + // RunningTraction.TractionVoltage = ElectricTraction.TractionVoltage /*- + // abs(ElectricTraction.TractionResistivity * + // (Itot + HVCouplers[0][0] + HVCouplers[1][0]))*/; + // else + // RunningTraction.TractionVoltage = + // ElectricTraction.TractionVoltage /*- + // abs(ElectricTraction.TractionResistivity * Itot * + // 0)*/; // zasadniczo ED oporowe nie zmienia napięcia w sieci + } + else if (OffTrack.active()) + { + // off the track the grade is that of the ground under it, along its heading + RunningShape.dHtrack = Shape.dHtrack; + } + + if (CategoryFlag == 4) + OffsetTrackV = TotalMass / (Dim.L * Dim.W * 1000.0); + else if (TestFlag(CategoryFlag, 1) && TestFlag(RunningTrack.CategoryFlag, 1) && TestFlag(DamageFlag, dtrain_out)) + { + OffsetTrackV = -0.2; + OffsetTrackH = Sign(RunningShape.R) * 0.2; + } + + // TODO: investigate, seems supplied NewRot is always 0 although the code here suggests some actual values are expected + Loc = NewLoc; + Rot = NewRot; + + if (dL == 0) // oblicz przesuniecie} + { + auto const AccSprev{AccS}; + // przyspieszenie styczne + AccS = std::lerp(AccSprev, FTotal / TotalMass, 0.5); + // std::clamp( dt * 3.0, 0.0, 1.0 ) ); // prawo Newtona ale z wygladzaniem (średnia z poprzednim) + + // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce(), and so does one + // derailed the legacy way with physics.collisions new + if (TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this)) + AccS = -Sign(V) * g * 1; // random(0.0, 0.1) + // stuck in the ballast: the friction holds a derailed vehicle once it stopped, until the forces on it are larger + auto const stuck{(Derailed != derailment::outcome::none || legacy_derailed_slides(*this)) && V == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; + if (stuck) + AccS = 0.0; + + // przyspieszenie normalne + if (abs(Shape.R) > 0.01) + AccN = square(V) / Shape.R + g * Shape.dHrail / TrackW; // Q: zamieniam SQR() na sqr() + else + AccN = g * Shape.dHrail / TrackW; + + // velocity change + auto const Vprev{V}; + V += (3.0 * AccS - AccSprev) * dt / 2.0; // przyrost predkosci + if (stuck) + V = 0.0; + if (V * Vprev <= 0 && std::abs(FStand) > std::abs(FTrain)) + { + // tlumienie predkosci przy hamowaniu + // zahamowany + V = 0; + } + + // tangential acceleration, from velocity change + AccSVBased = std::lerp(AccSVBased, (V - Vprev) / dt, std::clamp(dt * 3.0, 0.0, 1.0)); + + // vertical acceleration + AccVert = std::abs(AccVert) < 0.01 ? 0.0 : AccVert * 0.5; + // szarpanie + /* + #ifdef EU07_USE_FUZZYLOGIC + if( FuzzyLogic( ( 10.0 + Track.DamageFlag ) * Mass * Vel / Vmax, 500000.0, p_accn ) ) { + // Ra: czemu tu masa bez ładunku? + AccV /= ( 2.0 * 0.95 + 2.0 * Random() * 0.1 ); // 95-105% of base modifier (2.0) + } + else + #endif + AccV = AccV / 2.0; + + if (AccV > 1.0) + AccN += (7.0 - Random(5)) * (100.0 + Track.DamageFlag / 2.0) * AccV / 2000.0; + */ + // wykolejanie na luku oraz z braku szyn + if (TestFlag(CategoryFlag, 1)) + { + if (TestFlag(Track.DamageFlag, dtrack_norail)) + Derail(END_OF_TRACK); + // too fast in a curve: the legacy draw in every step (physics.derailment old), or the physical criteria + // once the step's distance is known, below + if ((Global.derailment == global_settings::derailment_model::old || Global.derailment == global_settings::derailment_model::monitor) && FuzzyLogic(AccN / g * (1.0 + 0.1 * (Track.DamageFlag & dtrack_freerail)), TrackW / Dim.H, 1)) + Derail(TOO_HIGH_SPEED); + // wykolejanie na poszerzeniu toru + if (FuzzyLogic(abs(Track.Width - TrackW), TrackW / 10.0, 1)) + Derail(GAUGE_MISMATCH); + } + // wykolejanie wkutek niezgodnosci kategorii toru i pojazdu + if (!TestFlag(RunningTrack.CategoryFlag, CategoryFlag)) + Derail(WRONG_TRACK_TYPE); + + // dL:=(V+AccS*dt/2)*dt; + // przyrost dlugosci czyli przesuniecie + dL = (3.0 * V - Vprev) * dt / 2.0; // metoda Adamsa-Bashfortha} + if (Global.derailment == global_settings::derailment_model::physical || Global.derailment == global_settings::derailment_model::monitor) + { + // over the distance of this step and of the simpler ones of the frame before it + check_derailment(Shape, Track, derailment_distance + std::abs(dL)); + } + derailment_distance = 0.0; + // ale jesli jest kolizja (zas. zach. pedu) to...} + for (int b = 0; b < 2; b++) + if (Couplers[b].CheckCollision) + CollisionDetect(b, dt); // zmienia niejawnie AccS, V !!! + check_pushed_off(dt, std::abs(dL)); + + } // liczone dL, predkosc i przyspieszenie + + auto const d{(EngineType == TEngineType::WheelsDriven ? dL * CabActive : // na chwile dla testu + dL)}; + + DistCounter += fabs(dL) / 1000.0; + Odometer.run(dL); + dL = 0; + + // koniec procedury, tu nastepuja dodatkowe procedury pomocnicze + compute_movement_(dt); + + // security system + SecuritySystemCheck(dt1); + + return d; +}; + +// ************************************************************************************************* +// Oblicza przemieszczenie taboru - uproszczona wersja +// ************************************************************************************************* + +double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Shape*/, TTrackParam & /*Track*/, TLocation const &NewLoc, TRotation const &NewRot) +{ + // T_MoverParameters::FastComputeMovement(dt, Shape, Track, NewLoc, NewRot); + + Loc = NewLoc; + Rot = NewRot; + + if (dL == 0) // oblicz przesuniecie + { + auto const AccSprev{AccS}; + // przyspieszenie styczne + AccS = std::lerp(AccSprev, FTotal / TotalMass, 0.5); + // std::clamp( dt * 3.0, 0.0, 1.0 ) ); // prawo Newtona ale z wygladzaniem (średnia z poprzednim) + + if (TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this)) + AccS = -Sign(V) * g * 1; // * random(0.0, 0.1) + auto const stuck{(Derailed != derailment::outcome::none || legacy_derailed_slides(*this)) && V == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; + if (stuck) + AccS = 0.0; + + // simple mode skips calculation of normal acceleration + + // velocity change + auto const Vprev{V}; + V += (3.0 * AccS - AccSprev) * dt / 2.0; // przyrost predkosci + if (stuck) + V = 0.0; + if (V * Vprev <= 0 && std::abs(FStand) > std::abs(FTrain)) + { + // tlumienie predkosci przy hamowaniu + // zahamowany + V = 0; + } + + // simple mode skips calculation of tangential acceleration + + // simple mode skips calculation of vertical acceleration + AccVert = 0.0; + + // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce(), and so does one + // derailed the legacy way with physics.collisions new + if (true == TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this) && Vel < 1.0) + { + V = 0.0; + AccS = 0.0; + } + + dL = (3.0 * V - Vprev) * dt / 2.0; // metoda Adamsa-Bashfortha + // the criteria of derailment go by the distance, checked in the full step which ends the frame + derailment_distance += std::abs(dL); + // ale jesli jest kolizja (zas. zach. pedu) to... + for (int b = 0; b < 2; b++) + if (Couplers[b].CheckCollision) + CollisionDetect(b, dt); // zmienia niejawnie AccS, V !!! + check_pushed_off(dt, std::abs(dL)); + } // liczone dL, predkosc i przyspieszenie + + auto const d{(EngineType == TEngineType::WheelsDriven ? dL * CabActive : // na chwile dla testu + dL)}; + + DistCounter += fabs(dL) / 1000.0; + Odometer.run(dL); + dL = 0; + + // koniec procedury, tu nastepuja dodatkowe procedury pomocnicze + compute_movement_(dt); + + return d; +}; + +// updates shared between 'fast' and regular movement computation methods +void TMoverParameters::compute_movement_(double const Deltatime) +{ + + // sprawdzanie i ewentualnie wykonywanie->kasowanie poleceń + if (LoadStatus > 0) // czas doliczamy tylko jeśli trwa (roz)ładowanie + LastLoadChangeTime += Deltatime; // czas (roz)ładunku + + RunInternalCommand(); + + // relay settings + // adjust motor overload relay threshold + if (EngineType == TEngineType::ElectricSeriesMotor && ImaxHi > ImaxLo) + { + if (MotorOverloadRelayHighThreshold) + { // set high threshold + if (TrainType != train_type::et42 ? RList[MainCtrlPos].Bn < 2 : MainCtrlPos == 0) + { + Imax = ImaxHi; + } + } + else + { // set low threshold + if (TrainType != train_type::et42 || MainCtrlPos == 0) + { + Imax = ImaxLo; + } + } + } + + // Uproszczona symulacja wentylatorow rezystora hamowania + + // Prad oddawany na rezystor + + // Wlacz wentylator jesli prad rekuperacji przekroczy maksymalny dla pasywnego chlodzenia rezystora + if (double Irh = abs(eimv[eimv_Pe]) - abs(eimv[eimv_Ipoj]); Irh > Imaxrpc && eimv[eimv_Ipoj] < 0) + { + BRVtimer = 0; + BRVentilators = true; + } + else + { + BRVtimer += Deltatime; + if (BRVtimer > BRVto) + BRVentilators = false; + } + + // the master controller set directly, not through IncMainCtrl()/DecMainCtrl() (AI, consist): the locked shunt follows it as well + ScndCtrlResistiveLockCheck(); + // automatyczny rozruch + if (EngineType == TEngineType::ElectricSeriesMotor && AutoRelayCheck()) + { + SetFlag(SoundFlag, sound::relay); + } + + if ((EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric) && dizel_Update(Deltatime)) + { + SetFlag(SoundFlag, sound::relay); + } + + // TODO: gather and move current calculations to dedicated method + TotalCurrent = 0; + + // low voltage power sources + LowVoltagePowerCheck(Deltatime); + // power sources + PantographsCheck(Deltatime); + GensetCheck(Deltatime); + // main circuit + MainsCheck(Deltatime); + // traction motors + MotorBlowersCheck(Deltatime); + // uklady hamulcowe: + ConverterCheck(Deltatime); + if (VeselVolume > 0) + Compressor = CompressedVolume / VeselVolume; + else + { + Compressor = 0; + CompressorFlag = false; + } + if (VeselVolume > 0.0) + { + // sprężarka musi mieć jakąś niezerową wydajność żeby rozważać jej załączenie i pracę + CompressorCheck(Deltatime); + } + if (Power > 1.0) + { + // w rozrządczym nie (jest błąd w FIZ!) - Ra 2014-07: teraz we wszystkich + UpdatePantVolume(Deltatime); // Ra 2014-07: obsługa zbiornika rozrządu oraz pantografów + } + // heating + HeatingCheck(Deltatime); + // lighting + LightsCheck(Deltatime); + + UpdateBrakePressure(Deltatime); + UpdatePipePressure(Deltatime); + UpdateBatteryVoltage(Deltatime); + UpdateScndPipePressure(Deltatime); // druga rurka, youBy + + if ((DCEMUED_CC & 1) != 0 && (Couplers[end::front].CouplingFlag & coupling::control) != 0) + { + DynamicBrakeEMUStatus &= Couplers[end::front].Connected->DynamicBrakeEMUStatus; + } + if ((DCEMUED_CC & 2) != 0 && (Couplers[end::rear].CouplingFlag & coupling::control) != 0) + { + DynamicBrakeEMUStatus &= Couplers[end::rear].Connected->DynamicBrakeEMUStatus; + } + + if (BrakeSlippingTimer > 0.8 && ASBType != 128) + { // ASBSpeed=0.8 + // hamulec antypoślizgowy - wyłączanie + Hamulec->ASB(0); + } + BrakeSlippingTimer += Deltatime; + // automatic doors + update_doors(Deltatime); + + m_plc.update(Deltatime); + + PowerCouplersCheck(Deltatime, coupling::highvoltage); + PowerCouplersCheck(Deltatime, coupling::power110v); + PowerCouplersCheck(Deltatime, coupling::power24v); + + Power24vVoltage = std::max(PowerCircuits[0].first, GetTrainsetVoltage(coupling::power24v)); + Power24vIsAvailable = Power24vVoltage > 0; + Power110vIsAvailable = PowerCircuits[1].first > 0 || GetTrainsetVoltage(coupling::power110v) > 0; +} + +// ************************************************************************************************* +// Q: 20160710 +// Siła napędzająca drezynę po naciśnięciu wajhy +// ************************************************************************************************* +bool TMoverParameters::AddPulseForce(int Multipler) +{ + bool APF; + if (EngineType == TEngineType::WheelsDriven && EnginePowerSource.SourceType == TPowerSource::InternalSource && EnginePowerSource.PowerType == TPowerType::BioPower) + { + DirActive = CabActive; + DirAbsolute = DirActive * CabActive; + if (Vel > 0) + PulseForce = std::min(1000.0 * Power / (abs(V) + 0.1), Ftmax); + else + PulseForce = Ftmax; + if (PulseForceCount > 1000.0) + PulseForce = 0; + else + PulseForce = PulseForce * Multipler; + PulseForceCount = PulseForceCount + abs(Multipler); + APF = PulseForce > 0; + } + else + APF = false; + return APF; +} + +// ************************************************************************************************* +// yB: 20190909 +// sypanie piasku reczne +// ************************************************************************************************* +bool TMoverParameters::SandboxManual(bool const State, range_t const Notify) +{ + bool result{false}; + + if (SandDoseManual != State) + { + if (SandDoseManual == false) + { + // switch on + if (Sand > 0) + { + SandDoseManual = true; + result = true; + } + } + else + { + // switch off + SandDoseManual = false; + result = true; + } + } + + Sandbox(SandDoseManual || SandDoseAuto, Notify); + + return result; +} + +// ************************************************************************************************* +// yB: 20190909 +// sypanie piasku automatyczne +// ************************************************************************************************* +bool TMoverParameters::SandboxAuto(bool const State, range_t const Notify) +{ + bool result{false}; + if (bool NewState = State && SandDoseAutoAllow; SandDoseAuto != NewState) + { + if (SandDoseAuto == false) + { + // switch on + if (Sand > 0) + { + SandDoseAuto = true; + result = true; + } + } + else + { + // switch off + SandDoseAuto = false; + result = true; + } + } + + Sandbox(SandDoseManual || SandDoseAuto, Notify); + + return result; +} + +// ************************************************************************************************* +// Q: 20160713 +// sypanie piasku +// ************************************************************************************************* +bool TMoverParameters::Sandbox(bool const State, range_t const Notify) +{ + bool result{false}; + + if (SandDose != State) + { + if (SandDose == false) + { + // switch on + if (Sand > 0 && DirActive != 0) + { + SandDose = true; + result = true; + } + } + else + { + // switch off + SandDose = false; + result = true; + } + } + + if (Notify != range_t::local) + { + // if requested pass the command on + auto const couplingtype = Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control; + + if (State == true) + { + // switch on + SendCtrlToNext("Sandbox", 1, CabActive, couplingtype); + } + else + { + // switch off + SendCtrlToNext("Sandbox", 0, CabActive, couplingtype); + } + } + + return result; +} + +// ************************************************************************************************* +// yB: 20190909 +// włączenie / wyłączenie automatycznej piasecznicy +// ************************************************************************************************* +bool TMoverParameters::SandboxAutoAllow(bool State) +{ + // SendCtrlToNext("SandboxAutoAllow", int(State), CabActive, ctrain_controll); + + if (SandDoseAutoAllow != State) + { + SandDoseAutoAllow = State; + return true; + } + else + return false; +} + +// ************************************************************************************************* +// Q: 20160713 +// Obliczenie stałych potrzebnych do dalszych obliczeń +// ************************************************************************************************* +void TMoverParameters::ComputeConstans(void) +{ + double BearingF; + double RollF; + double HideModifier; + double Curvature; // Ra 2014-07: odwrotność promienia + + TotalMassxg = TotalMass * g; // TotalMass*g + BearingF = (DamageFlag & dtrain_bearing) != 0 ? 2.0 : 0; + + HideModifier = 0; // int(Couplers[0].CouplingFlag>0)+int(Couplers[1].CouplingFlag>0); + + if (BearingType == 0) + RollF = 0.05; // slizgowe + else + RollF = 0.015; // toczne + RollF += BearingF / 200.0; + + // if (NPoweredAxles > 0) + // RollF = RollF * 1.5; //dodatkowe lozyska silnikow + + if (NPoweredAxles > 0) // drobna optymalka + { + RollF += 0.025; + // if (Ft * Ft < 1) + // HideModifier = HideModifier - 3; + } + Ff = TotalMassxg * (BearingF + RollF * V * V / 10.0) / 1000.0; + // dorobic liczenie temperatury lozyska! + FrictConst1 = TotalMassxg * RollF / 10000.0; + // drag calculation + { + // NOTE: draft effect of previous vehicle is simplified and doesn't have much to do with reality + auto const *previousvehicle{Couplers[V >= 0.0 ? end::front : end::rear].Connected}; + auto dragarea{Dim.W * Dim.H}; + if (previousvehicle) + { + dragarea = std::max(0.0, dragarea - 0.85 * previousvehicle->Dim.W * previousvehicle->Dim.H); + } + FrictConst1 += Cx * dragarea; + } + + if (CategoryFlag & 1) + { + Curvature = RunningShape.R == 0.0 ? // zero oznacza nieskończony promień + 0.0 : + 1.0 / std::abs(RunningShape.R); + } + else + { + // vehicles other than trains don't experience friction against the rail on curves + Curvature = 0.0; + } + // opór składu na łuku (youBy): +(500*TrackW/R)*TotalMassxg*0.001 do FrictConst2s/d + FrictConst2s = TotalMassxg * (500.0 * TrackW * Curvature + 2.5 - HideModifier + 2 * BearingF / dtrain_bearing) * 0.001; + FrictConst2d = TotalMassxg * (500.0 * TrackW * Curvature + 2.0 - HideModifier + BearingF / dtrain_bearing) * 0.001; +} + +// ************************************************************************************************* +// Q: 20160713 +// Oblicza masę ładunku +// ************************************************************************************************* +void TMoverParameters::ComputeMass() +{ + // Ra: na razie tak, ale nie wszędzie masy wirujące się wliczają + TotalMass = Mass + Mred; + + if (LoadAmount == 0) + { + return; + } + + // include weight of carried load + auto loadtypeunitweight{0.f}; + + if (ToLower(LoadQuantity) == "tonns") + { + loadtypeunitweight = 1000; + } + else + { + auto const lookup{simulation::Weights.find(LoadType.name)}; + loadtypeunitweight = lookup != simulation::Weights.end() ? lookup->second : 1000.f; // legacy default unit weight value + } + + TotalMass += LoadAmount * loadtypeunitweight; +} + +// ************************************************************************************************* +// Q: 20160713 +// Obliczanie wypadkowej siły z wszystkich działających sił +// ************************************************************************************************* +// TBD, TODO: move some of the calculations out of the method, they're relevant to more than just force calculations +void TMoverParameters::ComputeTotalForce(double dt) +{ + + Vel = std::abs(V) * 3.6; // prędkość w km/h + + // McZapkie-031103: sprawdzanie czy warto liczyc fizyke i inne updaty + // ABu 300105: cos tu mieszalem , dziala teraz troche lepiej, wiec zostawiam + { + // asleep, the brake force is the one of the step it fell asleep in: a vehicle whose brakes have changed since, released + // or applied, wakes for the 5 s of LastSwitchingTime, which take the new force into FStand, and sleeps again if it's + // still held. none of the causes of the test below, so as "other" + if (brakes_changed_asleep()) + switch_physics(true, wake_cause::other); + + auto const vehicleisactive{CabActive != 0 || Vel > 0.0001 || accelerating() || LastSwitchingTime < 5 || is_multiple_unit()}; + + auto const movingvehicleahead{Neighbours[end::front].vehicle != nullptr && + (Neighbours[end::front].vehicle->MoverParameters->Vel > 0.0001 || Neighbours[end::front].vehicle->MoverParameters->accelerating())}; + + auto const movingvehiclebehind{Neighbours[end::rear].vehicle != nullptr && + (Neighbours[end::rear].vehicle->MoverParameters->Vel > 0.0001 || Neighbours[end::rear].vehicle->MoverParameters->accelerating())}; + + auto const calculatephysics{vehicleisactive || movingvehicleahead || movingvehiclebehind}; + + switch_physics(calculatephysics, Vel > 0.0001 ? wake_cause::speed : + accelerating() ? wake_cause::acceleration : + vehicleisactive ? wake_cause::rest : + wake_cause::neighbour); + } + + if (false == PhysicActivation) + { + return; + } + + // juz zoptymalizowane: + FStand = FrictionForce(); // siła oporów ruchu + if (true == TestFlag(DamageFlag, dtrain_out)) + { + if (Derailed != derailment::outcome::none) + { + // off the rails by the physical criteria: the vehicle slides on the sleepers and the ballast, or on its side; + // off the track on the ground, as far as it tipped over (physics.derailment new) + auto const friction{OffTrack.active() ? OffTrack.friction() : derailment::sliding_friction(Derailed)}; + FStand = friction * (TotalMass - Mred) * g; + } + else if (legacy_derailed_slides(*this)) + { + // derailed the legacy way with physics.collisions new: the deceleration of g of the legacy model, as a friction + FStand = TotalMass * g; + } + else + { + // HACK: crude way to reduce speed after derailment + // TBD, TODO: more accurate approach? + FStand *= 1e20; + } + } + double old_nrot = abs(nrot); + nrot = v2n(); // przeliczenie prędkości liniowej na obrotową + + if (true == TestFlag(BrakeMethod, bp_MHS) && PipePress < 3.0 // ustawione na sztywno na 3 bar + && Vel > 45 && true == TestFlag(BrakeDelayFlag, bdelay_M)) + { + // doliczenie hamowania hamulcem szynowym + FStand += TrackBrakeForce; + } + // w charakterystykach jest wartość siły hamowania zamiast nacisku + + LastSwitchingTime += dt; + if (EngineType == TEngineType::ElectricSeriesMotor) + { + LastRelayTime += dt; + } + + if (EngineType == TEngineType::ElectricSeriesMotor) // potem ulepszyc! pantogtrafy! + { // Ra 2014-03: uwzględnienie kierunku jazdy w napięciu na silnikach, a powinien być zdefiniowany nawrotnik + EngineVoltage = Mains ? EnginePowerSourceVoltage() : 0.0; + if (CabActive == 0) + { + EngineVoltage *= DirActive; + } + else + { + EngineVoltage *= DirAbsolute; // the reverser of the active cab, relative to the couplers + } + } // bo nie dzialalo + else + { + EngineVoltage = Power > 1.0 ? TractionSupplyVoltage() : 0.0; + } + + FTrain = Power > 0 ? TractionForce(dt) : 0; + double FT_factor = 1.0; + if (EngineType == TEngineType::ElectricInductionMotor && InvertersRatio > 0.0) + { + FT_factor = 1.0 / InvertersRatio; + FTrain *= FT_factor; + } + + Fb = BrakeForce(RunningTrack); + // poslizg + auto Fwheels{FTrain - Fb * Sign(V)}; + if (Vel > 0.1 // crude trap, to prevent braked stationary vehicles from passing fb > mass * adhesive test + && std::abs(Fwheels) > TotalMassxg * Adhesive(RunningTrack.friction)) + { + SlippingWheels = true; + } + if (true == SlippingWheels && Vel < 0.1 // the same crude trap: (nearly) stopped vehicle... + && std::abs(nrot * M_PI * WheelDiameter - V) < 0.1 / 3.6) // ...with wheels turning at its speed, i.e. locked wheels at the end of a skid + { + // locked wheels never pass the rotation speed test below once the vehicle stops, and a skidding vehicle + // keeps its braking force capped by the sliding adhesion, so the rest of the consist could push it around + SlippingWheels = false; + nrot = V / M_PI / WheelDiameter; + } + double temp_nrot = nrot; + if (true == SlippingWheels) + { + + temp_nrot = ComputeRotatingWheel(Fwheels - Sign(nrot * M_PI * WheelDiameter - V) * Adhesive(RunningTrack.friction) * TotalMassxg, dt, nrot); + if (Sign(nrot * M_PI * WheelDiameter - V) * Sign(temp_nrot * M_PI * WheelDiameter - V) < 0) + { + SlippingWheels = false; + temp_nrot = V / M_PI / WheelDiameter; + } + } + if (true == SlippingWheels) + { + Fwheels = Sign(temp_nrot * M_PI * WheelDiameter - V) * TotalMassxg * Adhesive(RunningTrack.friction); + if (Fwheels * Sign(V) > 0) + { + FTrain = Fwheels + Fb * Sign(V); + } + else if (FTrain * Sign(V) > 0) + { + Fb = FTrain * Sign(V) - Fwheels * Sign(V); + } + else + { + double factor = FTrain - Fb * Sign(V) != 0 ? Fwheels / (FTrain - Fb * Sign(V)) : 1.0; + Fb *= factor; + FTrain *= factor; + } + if (std::abs(nrot) < 0.1) + { + WheelFlat = sqrt(square(WheelFlat) + abs(Fwheels) / NAxles * Vel * 0.000002); + } + + nrot = temp_nrot; + } + nrot_eps = (abs(nrot) - old_nrot) / dt; + // doliczenie sił z innych pojazdów + for (int end = end::front; end <= end::rear; ++end) + { + // a new step: the hit of the pair not taken by either vehicle yet + Couplers[end].hit_handled = false; + Couplers[end].hit_force = 0.0; + Couplers[end].hit_duration = 0.0; + Couplers[end].closing = 0.0; + if (Neighbours[end].vehicle != nullptr) + { + // the velocities before the step, the forces of all the vehicles come before their movement + Couplers[end].closing = -CouplerVelocityDifference(end, *Neighbours[end].vehicle->MoverParameters, Neighbours[end].vehicle_end) * DirF(end); + Couplers[end].CForce = CouplerForce(end, dt); + FTrain += Couplers[end].CForce; + // what the buffers of the pair take in, for the budget of the crush (physics.collisions new and monitor) + auto &coupler{Couplers[end]}; + coupler.contact.update(coupler.Dist < 0.0, coupler.CheckCollision, coupler.closing, compression_at(coupler, end), std::max(0.0, -coupler.Dist), dt); + } + else + { + Couplers[end].CForce = 0; + Couplers[end].contact.reset(); + } + } + + FStand += Fb; + // doliczenie składowej stycznej grawitacji + FTrain /= FT_factor; + FTrain += TotalMassxg * RunningShape.dHtrack; + //! niejawne przypisanie zmiennej! + FTotal = FTrain - Sign(V) * FStand; +} + +double TMoverParameters::BrakeForceR(double ratio, double velocity) const +{ + double press = 0; + ratio = Hamulec->GetBrakeRatio(ratio); + if (MBPM > 2) + { + press = MaxBrakePress[1] + (MaxBrakePress[3] - MaxBrakePress[1]) * std::min(1.0, (TotalMass - Mass) / (MBPM - Mass)); + } + else + { + if (MaxBrakePress[1] > 0.1) + { + press = MaxBrakePress[LoadFlag]; + } + else + { + press = MaxBrakePress[3]; + if (DynamicBrakeType == dbrake_automatic) + ratio = ratio + (1.5 - ratio) * std::min(1.0, Vel * 0.02); + if (BrakeDelayFlag & bdelay_R && BrakeMethod % 128 != bp_Cosid && BrakeMethod % 128 != bp_D1 && BrakeMethod % 128 != bp_D2 && Power < 1) + ratio *= Hamulec->GetRapidRatio(velocity); + if (TrainType == train_type::dmu && velocity < 30.0) + { + ratio -= 0.3; + } + } + } + return BrakeForceP(press * ratio, velocity); +} + +double TMoverParameters::BrakeForceP(double press, double velocity) const +{ + double BFP = 0; + double K = ((press * P2FTrans - BrakeCylSpring) * BrakeCylMult[0] - BrakeSlckAdj) * BrakeRigEff; + K *= static_cast(BrakeCylNo) / (NAxles * std::max(1, NBpA)); + BFP = Hamulec->GetFC(velocity, K) * K * (NAxles * std::max(1, NBpA)) * 1000; + return BFP; +} + +// ************************************************************************************************* +// Q: 20160713 +// oblicza siłę na styku koła i szyny +// ************************************************************************************************* +double TMoverParameters::BrakeForce(TTrackParam const & /*Track*/) +{ + + double K{0}; + double brakeforce{0}; + + switch (LocalBrake) + { + case TLocalBrake::ManualBrake: + { + K = MaxBrakeForce * ManualBrakeRatio(); + break; + } + case TLocalBrake::HydraulicBrake: + { + K = MaxBrakeForce * LocalBrakeRatio(); + break; + } + default: + { + break; + } + } + + if (MBrake == true) + { + K = MaxBrakeForce * ManualBrakeRatio(); + } + + // the spring brake of a vehicle prepared for hauling (PulleeMode) is released by hand: no force, whatever its cylinder has + if (SpringBrake.IsReady && false == PulleeMode) + K += std::max(0.0, SpringBrake.MinForcePressure - SpringBrake.Cylinder->P()) * SpringBrake.MaxBrakeForce; + + u = (BrakePress * P2FTrans - BrakeCylSpring) * BrakeCylMult[0] - BrakeSlckAdj; + if (u * BrakeRigEff > Ntotal) // histereza na nacisku klockow + Ntotal = u * BrakeRigEff; + else + { + u = (BrakePress * P2FTrans - BrakeCylSpring) * BrakeCylMult[0] - BrakeSlckAdj; + if (u * (2.0 - BrakeRigEff) < Ntotal) // histereza na nacisku klockow + Ntotal = u * (2.0 - BrakeRigEff); + } + + auto const NBrakeAxles{NAxles}; + + if (NBrakeAxles * NBpA > 0) + { + if (Ntotal > 0) // nie luz + K += Ntotal; // w kN + K *= static_cast(BrakeCylNo) / (NBrakeAxles * static_cast(NBpA)); // w kN na os + } + if (BrakeSystem == TBrakeSystem::Pneumatic || BrakeSystem == TBrakeSystem::ElectroPneumatic) + { + u = Hamulec->GetFC(Vel, K); + UnitBrakeForce = u * K * 1000.0; // sila na jeden klocek w N + } + else + UnitBrakeForce = K * 1000.0; + // if (LocalBrake=ManualBrake)or(MBrake=true)) and (BrakePress<0.3) then + // Fb:=UnitBrakeForce*NBpA {ham. reczny dziala na jedna os} + // else //yB: to nie do konca ma sens, ponieważ ręczny w wagonie działa na jeden cylinder + // hamulcowy/wózek, dlatego potrzebne są oddzielnie liczone osie + brakeforce = UnitBrakeForce * NBrakeAxles * std::max(1, NBpA); + + // u:=((BrakePress*P2FTrans)-BrakeCylSpring*BrakeCylMult[BCMFlag]/BrakeCylNo-0.83*BrakeSlckAdj/(BrakeCylNo))*BrakeCylNo; + // { end; } + return brakeforce; +} + +// ************************************************************************************************* +// Q: 20160713 +// Obliczanie siły tarcia +// ************************************************************************************************* +double TMoverParameters::FrictionForce() const +{ + double FF = 0; + // ABu 240205: chyba juz ekstremalnie zoptymalizowana funkcja liczaca sily tarcia + if (abs(V) > 0.01) + FF = FrictConst1 * V * V + FrictConst2d; + else + FF = FrictConst1 * V * V + FrictConst2s; + return FF; +} + +// ************************************************************************************************* +// Q: 20160713 +// Oblicza przyczepność +// ************************************************************************************************* +double TMoverParameters::Adhesive(double staticfriction) const +{ + double adhesion = 0.0; + const double adh_factor = 0.25; // współczynnik określający, jak bardzo spada tarcie przy poślizgu + const double slipfactor = 0.33; // współczynnik określający, jak szybko spada tarcie przy poślizgu + const double sandfactor = 1.25; // współczynnik określający, jak mocno pomaga piasek + /* + // ABu: male przerobki, tylko czy to da jakikolwiek skutek w FPS? + // w kazdym razie zaciemni kod na pewno :) + if (SlippingWheels == false) + { + if (SandDose) + adhesion = (std::max(staticfriction * (100.0 + Vel) / ((50.0 + Vel) * 11.0), 0.048)) * + (11.0 - 2.0 * Random(0.0, 1.0)); + else + adhesion = (staticfriction * (100.0 + Vel) / ((50.0 + Vel) * 10.0)) * + (11.0 - 2.0 * Random(0.0, 1.0)); + } + else + { + if (SandDose) + adhesion = (0.048) * (11.0 - 2.0 * Random(0.0, 1.0)); + else + adhesion = (staticfriction * 0.02) * (11.0 - 2.0 * Random(0.0, 1.0)); + } + // WriteLog(FloatToStr(adhesive)); // tutaj jest na poziomie 0.2 - 0.3 + return adhesion; + + //wersja druga + if( true == SlippingWheels ) { + + if( true == SandDose ) { adhesion = 0.48; } + else { adhesion = staticfriction * 0.2; } + } + else { + + if( true == SandDose ) { adhesion = std::max( staticfriction * ( 100.0 + Vel ) / ( 50.0 + Vel ) * 1.1, 0.48 ); } + else { adhesion = staticfriction * ( 100.0 + Vel ) / ( 50.0 + Vel ); } + } + // adhesion *= ( 0.9 + 0.2 * Random() ); + */ + // wersja3 by youBy - uwzględnia naturalne mikropoślizgi i wpływ piasecznicy, usuwa losowość z pojazdu + double Vwheels = nrot * M_PI * WheelDiameter; // predkosc liniowa koła wynikająca z obrotowej + double deltaV = V - Vwheels; // poślizg - różnica prędkości w punkcie styku koła i szyny + deltaV = std::max(0.0, std::abs(deltaV) - 0.25); // mikropoślizgi do ok. 0,25 m/s nie zrywają przyczepności + Vwheels = std::abs(Vwheels); + adhesion = staticfriction * (28 + Vwheels) / (14 + Vwheels) * ((SandDose ? sandfactor : 1) - (1 - adh_factor) * (deltaV / (deltaV + slipfactor))); + + return adhesion; +} + +// ************************************************************************************************* +// Q: 20160713 +// Obliczenie predkości obrotowej kół??? +// ************************************************************************************************* +double TMoverParameters::ComputeRotatingWheel(double WForce, double dt, double n) const +{ + double newn = 0; + double eps = 0; + if (n == 0 && WForce * Sign(V) < 0) + newn = 0; + else + { + eps = WForce * WheelDiameter / (2.0 * AxleInertialMoment); + newn = n + eps * dt; + if (newn * n <= 0 && eps * n < 0) + newn = 0; + } + return newn; +} + +// ************************************************************************************************* +// Q: 20160713 +// Przesuwa pojazd o podaną wartość w bok względem toru (dla samochodów) +// ************************************************************************************************* +bool TMoverParameters::ChangeOffsetH(double DeltaOffset) +{ + bool COH = false; + if (TestFlag(CategoryFlag, 2) && TestFlag(RunningTrack.CategoryFlag, 2)) + { + OffsetTrackH = OffsetTrackH + DeltaOffset; + // if (abs(OffsetTrackH) > (RunningTrack.Width / 1.95 - TrackW / 2.0)) + if (abs(OffsetTrackH) > 0.5 * (RunningTrack.Width - Dim.W) - 0.05) // Ra: może pół pojazdu od brzegu? + COH = false; // kola na granicy drogi + else + COH = true; + } + else + COH = false; + + return COH; +} + +// ************************************************************************************************* +// Q: 20160713 +// Testuje zmienną (narazie tylko 0) i na podstawie uszkodzenia zwraca informację tekstową +// ************************************************************************************************* +std::string TMoverParameters::EngineDescription(int what) const +{ + std::string outstr{"OK"}; + if (what == 0) + { + if (DamageFlag == 255) + { + outstr = "WRECKED"; + } + else + { + if (TestFlag(DamageFlag, dtrain_thinwheel)) + { + if (Power > 0.1) + outstr = "Thin wheel"; + else + outstr = "Load shifted"; + } + if (WheelFlat > 5.0 || TestFlag(DamageFlag, dtrain_wheelwear)) + { + outstr = "Wheel wear"; + } + if (TestFlag(DamageFlag, dtrain_bearing)) + { + outstr = "Bearing damaged"; + } + if (TestFlag(DamageFlag, dtrain_coupling)) + { + outstr = "Coupler broken"; + } + if (TestFlag(DamageFlag, dtrain_loaddamage)) + { + if (Power > 0.1) + outstr = "Ventilator damaged"; + else + outstr = "Load damaged"; + } + if (TestFlag(DamageFlag, dtrain_loaddestroyed)) + { + if (Power > 0.1) + outstr = "Engine damaged"; + else + outstr = "LOAD DESTROYED"; + } + if (TestFlag(DamageFlag, dtrain_axle)) + { + outstr = "Axle broken"; + } + if (TestFlag(DamageFlag, dtrain_out)) + { + outstr = "DERAILED"; + } + } + } + else + { + outstr = "Invalid qualifier"; + } + return outstr; +} + +// ************************************************************************************************* +// whether the vehicle accelerates, for the test which turns the physics off in vehicles standing still +// ************************************************************************************************* +bool TMoverParameters::accelerating() const +{ + if (std::abs(AccS) <= 0.0001) + return false; + // standing still and held by the brakes and the resistance, against the slope and the couplers: the test ComputeMovement() + // sets the speed to zero by. the forces are of the last ComputeTotalForce(), the ones the movement went by. a vehicle whose + // brake cylinders still fill or release isn't held yet: asleep, it would keep the brake force (and the pressure the AI waits on + // to set off) it had when it fell asleep. 0.05 bar/s is less than a distributor moves the cylinder when it applies or releases, and + // more than the leaks take + auto const held{Global.physics_sleepheld && Vel <= 0.0001 && std::abs(FStand) > std::abs(FTrain) && BrakePressRate <= 0.05}; + return false == held; +} + +void TMoverParameters::wake_for_brake() +{ + if (Global.physics_sleepheld) + { + switch_physics(true, wake_cause::command); + } +} + +// ************************************************************************************************* +// whether the brakes of a vehicle whose physics sleeps have changed since it fell asleep: the pressure in the brake cylinders +// or in the one of the spring brake by more than 0.05 bar, the hand brake by a notch, or the local brake by 1 percent. the brake system +// itself steps on while asleep in the vehicle the user is in (TDynamicObject::Update(), MechInside); the settings change by +// hand or by a command in any vehicle. 0.05 bar is less than what a distributor applying or releasing moves the cylinder by in +// a second, and much less than the pressure the cylinder's return spring takes (BrakeCylSpring, some tenths of a bar), below +// which the cylinder gives no force: a release ends with the vehicle asleep and no force left. a cylinder holding its +// pressure, or settling within that, leaves the vehicle asleep +// ************************************************************************************************* +bool TMoverParameters::brakes_changed_asleep() const +{ + if (PhysicActivation) + return false; + constexpr double pressure_change{0.05}; // [bar] + return std::abs(BrakePress - sleep_brakes.cylinder) > pressure_change || std::abs(SpringBrake.SBP - sleep_brakes.spring) > pressure_change || + ManualBrakePos != sleep_brakes.manual || std::abs(LocalBrakePosA - sleep_brakes.local) > 0.01; +} + +// ************************************************************************************************* +// Kasowanie zmiennych pracy fizyki +// ************************************************************************************************* +bool TMoverParameters::switch_physics(bool const State, wake_cause const Cause) // DO PRZETLUMACZENIA NA KONCU +{ + if (PhysicActivation == State) + { + return false; + } + + PhysicActivation = State; + if (true == State) + { + LastSwitchingTime = 0; + Timer::subsystem.switching.note(static_cast(Timer::switching_counter::wake + static_cast(Cause)), this, &TypeName, &Name); + } + else + { + // what the brake force of the last step came from, which it keeps while asleep (brakes_changed_asleep()) + sleep_brakes = {BrakePress, SpringBrake.SBP, ManualBrakePos, LocalBrakePosA}; + } + + return true; +} + +namespace simulation +{ + +weights_table Weights; + +} // namespace simulation diff --git a/physics/mover/pneumatics.cpp b/physics/mover/pneumatics.cpp new file mode 100644 index 000000000..923fb7f0e --- /dev/null +++ b/physics/mover/pneumatics.cpp @@ -0,0 +1,1621 @@ +/* +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 brakes and the air: the brake controls, the pipes, the valves, the compressor, the spring brake + +#include "stdafx.h" +#include "physics/mover.h" +#include "vehicle/DynObj.h" +#include "physics/oerlikonest.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/Timer.h" +#include "utilities/parser.h" +#include "simulation/simulation.h" +#include "vehicle/fieldshunting.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "physics/mover/internal.h" + + +// Nastawianie hamulców + +void TMoverParameters::BrakeLevelSet(double b) +{ // ustawienie pozycji hamulca na wartość (b) w zakresie od -2 do BrakeCtrlPosNo + // jedyny dopuszczalny sposób przestawienia hamulca zasadniczego + if (fBrakeCtrlPos == b) + return; // nie przeliczać, jak nie ma zmiany + fBrakeCtrlPos = b; + if (fBrakeCtrlPos < Handle->GetPos(bh_MIN)) + fBrakeCtrlPos = Handle->GetPos(bh_MIN); // odcięcie + else if (fBrakeCtrlPos > Handle->GetPos(bh_MAX)) + fBrakeCtrlPos = Handle->GetPos(bh_MAX); + // TODO: verify whether BrakeCtrlPosR and fBrakeCtrlPos can be rolled into single variable + BrakeCtrlPosR = fBrakeCtrlPos; + auto x = static_cast(std::floor(fBrakeCtrlPos)); // jeśli odwołujemy się do BrakeCtrlPos w pośrednich, to musi być + // obcięte a nie zaokrągone + while (x > BrakeCtrlPos && BrakeCtrlPos < BrakeCtrlPosNo) // jeśli zwiększyło się o 1 + if (!IncBrakeLevelOld()) // T_MoverParameters:: + break; // wyjście awaryjne + while (x < BrakeCtrlPos && BrakeCtrlPos >= -1) // jeśli zmniejszyło się o 1 + if (!DecBrakeLevelOld()) // T_MoverParameters:: + break; + BrakePressureActual = BrakePressureTable[BrakeCtrlPos]; // skopiowanie pozycji + /* + //youBy: obawiam sie, ze tutaj to nie dziala :P + //Ra 2014-03: było tak zrobione, że działało - po każdej zmianie pozycji była wywoływana ta + funkcja + // if (BrakeSystem==Pneumatic?BrakeSubsystem==Oerlikon:false) //tylko Oerlikon akceptuje ułamki + if(false) + if (fBrakeCtrlPos>0.0) + {//wartości pośrednie wyliczamy tylko dla hamowania + double u=fBrakeCtrlPos-double(x); //ułamek ponad wartość całkowitą + if (u>0.0) + {//wyliczamy wartości ważone + BrakePressureActual.PipePressureVal+=-u*BrakePressureActual.PipePressureVal+u*BrakePressureTable[BrakeCtrlPos+1+2].PipePressureVal; + //BrakePressureActual.BrakePressureVal+=-u*BrakePressureActual.BrakePressureVal+u*BrakePressureTable[BrakeCtrlPos+1].BrakePressureVal; + //to chyba nie będzie tak działać, zwłaszcza w EN57 + BrakePressureActual.FlowSpeedVal+=-u*BrakePressureActual.FlowSpeedVal+u*BrakePressureTable[BrakeCtrlPos+1+2].FlowSpeedVal; + } + } + */ +}; + +bool TMoverParameters::BrakeLevelAdd(double b) +{ // dodanie wartości (b) do pozycji hamulca (w tym ujemnej) + // zwraca false, gdy po dodaniu było by poza zakresem + BrakeLevelSet(fBrakeCtrlPos + b); + return b > 0.0 ? fBrakeCtrlPos < BrakeCtrlPosNo : BrakeCtrlPos > -1.0; // true, jeśli można kontynuować +}; + +bool TMoverParameters::IncBrakeLevel() +{ // nowa wersja na użytek AI, false gdy osiągnięto pozycję BrakeCtrlPosNo + return BrakeLevelAdd(1.0); +}; + +bool TMoverParameters::DecBrakeLevel() +{ + return BrakeLevelAdd(-1.0); +}; // nowa wersja na użytek AI, false gdy osiągnięto pozycję -1 + +/* Ukrotnienie EN57: +1 //układ szeregowy +2 //układ równoległy +3 //bocznik 1 +4 //bocznik 2 +5 //bocznik 3 +6 //do przodu +7 //do tyłu +8 //1 przyspieszenie +9 //minus obw. 2 przyspieszenia +10 //jazda na oporach +11 //SHP +12A //podnoszenie pantografu przedniego +12B //podnoszenie pantografu tylnego +13A //opuszczanie pantografu przedniego +13B //opuszczanie wszystkich pantografów +14 //załączenie WS +15 //rozrząd (WS, PSR, wał kułakowy) +16 //odblok PN +18 //sygnalizacja przetwornicy głównej +19 //luzowanie EP +20 //hamowanie EP +21 //rezerwa** (1900+: zamykanie drzwi prawych) +22 //zał. przetwornicy głównej +23 //wył. przetwornicy głównej +24 //zał. przetw. oświetlenia +25 //wył. przetwornicy oświetlenia +26 //sygnalizacja WS +28 //sprężarka +29 //ogrzewanie +30 //rezerwa* (1900+: zamykanie drzwi lewych) +31 //otwieranie drzwi prawych +32H //zadziałanie PN siln. trakcyjnych +33 //sygnał odjazdu +34 //rezerwa (sygnalizacja poślizgu) +35 //otwieranie drzwi lewych +ZN //masa +*/ + +// ***************************************************************************** +// Q: 20160714 +// Oblicza iloraz aktualnej pozycji do maksymalnej hamulca pomocnicznego +// ***************************************************************************** +double TMoverParameters::LocalBrakeRatio(void) const +{ + double LBR; + if (BrakeHandle == TBrakeHandle::MHZ_EN57) + if (BrakeOpModeFlag >= bom_EP) + LBR = Handle->GetEP(BrakeCtrlPosR); + else + LBR = 0; + else + { + if (LocalBrakePosNo > 0) + LBR = LocalBrakePosA; + else + LBR = 0; + } + // if (TestFlag(BrakeStatus, b_antislip)) + // LBR = std::max(LBR, PipeRatio) + 0.4; + return LBR; +} + +// ***************************************************************************** +// Q: 20160714 +// Oblicza iloraz aktualnej pozycji do maksymalnej hamulca ręcznego +// ***************************************************************************** +double TMoverParameters::ManualBrakeRatio(void) const +{ + double MBR; + + if (ManualBrakePosNo > 0) + MBR = (double)ManualBrakePos / ManualBrakePosNo; + else + MBR = 0; + return MBR; +} + +// ***************************************************************************** +// Q: 20160713 +// Zwraca objętość +// ***************************************************************************** +double TMoverParameters::BrakeVP(void) const +{ + if (BrakeVVolume > 0) + return Volume / (10.0 * BrakeVVolume); + else + return 0; +} + +// ***************************************************************************** +// Q: 20160713 +// Zwraca iloraz różnicy między przewodem kontrolnym i głównym oraz DeltaPipePress +// ***************************************************************************** +double TMoverParameters::RealPipeRatio(void) const +{ + double rpp; + + if (DeltaPipePress > 0) + rpp = (CntrlPipePress - PipePress) / DeltaPipePress; + else + rpp = 0; + return rpp; +} + +// ***************************************************************************** +// Q: 20160713 +// Zwraca iloraz ciśnienia w przewodzie do DeltaPipePress +// ***************************************************************************** +double TMoverParameters::PipeRatio(void) const +{ + double pr; + + if (DeltaPipePress > 0) + if (false) // SPKS!! no to jak nie wchodzimy to po co branch? + { + if (3.0 * PipePress > HighPipePress + LowPipePress + LowPipePress) + pr = (HighPipePress - std::min(HighPipePress, PipePress)) / (DeltaPipePress * 4.0 / 3.0); + else + pr = (HighPipePress - 1.0 / 3.0 * DeltaPipePress - std::max(LowPipePress, PipePress)) / (DeltaPipePress * 2.0 / 3.0); + // if (not TestFlag(BrakeStatus, b_Ractive)) + // and(BrakeMethod and 1 = 0) and TestFlag(BrakeDelays, bdelay_R) and (Power < 1) and + // (BrakeCtrlPos < 1) then pr : = std::min(0.5, pr); + // if (Compressor > 0.5) + // then pr : = pr * 1.333; // dziwny rapid wywalamy + } + else + pr = (HighPipePress - std::max(LowPipePress, std::min(HighPipePress, PipePress))) / DeltaPipePress; + else + pr = 0; + return pr; +} + +// ************************************************************************************************* +// Q: 20160710 +// włączenie / wyłączenie hamulca elektro-pneumatycznego +// ************************************************************************************************* +bool TMoverParameters::EpFuseSwitch(bool State) +{ + if (EpFuse != State) + { + EpFuse = State; + return true; + } + else + return false; + // if (EpFuse == true) SendCtrlToNext("EpFuseSwitch", 1, CabActive) + // else SendCtrlToNext("EpFuseSwitch", 0, CabActive); +} + +// ************************************************************************************************* +// yB: 20190906 +// włączenie / wyłączenie hamulca sprezynowego +// ************************************************************************************************* +bool TMoverParameters::SpringBrakeActivate(bool State) +{ + if (Power24vIsAvailable || Power110vIsAvailable) + { + SendCtrlToNext("SpringBrakeActivate", int(State), CabActive, SpringBrake.MultiTractionCoupler); + + if (SpringBrake.Activate != State) + { + SpringBrake.Activate = State; + wake_for_brake(); + return true; + } + } + return false; +} + +// ************************************************************************************************* +// yB: 20190906 +// włączenie / wyłączenie odciecia hamulca sprezynowego +// ************************************************************************************************* +bool TMoverParameters::SpringBrakeShutOff(bool State) +{ + if (SpringBrake.ShuttOff != State) + { + SpringBrake.ShuttOff = State; + return true; + } + else + return false; +} + +// ************************************************************************************************* +// yB: 20190906 +// wyluzowanie hamulca sprezynowego +// ************************************************************************************************* +bool TMoverParameters::SpringBrakeRelease() +{ + if (SpringBrake.IsReady && SpringBrake.Cylinder->P() < SpringBrake.MinForcePressure) + { + SpringBrake.IsReady = false; + wake_for_brake(); + return true; + } + else + return false; +} + +// ************************************************************************************************* +// Q: 20160710 +// załączenie przycisku przeciwpoślizgowego +// ************************************************************************************************* +bool TMoverParameters::AntiSlippingButton(void) +{ + // NOTE: disabled the sandbox part, it's already controlled by another part of the AI routine + return AntiSlippingBrake() /*|| Sandbox(true)*/; +} + +// ************************************************************************************************* +// Q: 20160713 +// włączenie / wyłączenie sprężarki +// ************************************************************************************************* +bool TMoverParameters::CompressorSwitch(bool State, range_t const Notify) +{ + + if (CompressorStart != start_t::manual) + { + // only pay attention if the compressor can be controlled manually + return false; + } + + auto const initialstate{CompressorAllow}; + + if (VeselVolume > 0.0 && CompressorSpeed > 0.0) + { + CompressorAllow = State; + } + + if (Notify != range_t::local) + { + SendCtrlToNext("CompressorSwitch", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return CompressorAllow != initialstate; +} + +bool TMoverParameters::ChangeCompressorPreset(int const State, range_t const Notify) +{ + + auto const initialstate{CompressorListPos}; + + CompressorListPos = safe_clamp(State, 0, CompressorListPosNo); + + if (Notify != range_t::local) + { + SendCtrlToNext("CompressorPreset", State, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return CompressorListPos != initialstate; +} + +// ************************************************************************************************* +// Q: 20160711 +// zwiększenie nastawy hamulca +// ************************************************************************************************* +bool TMoverParameters::IncBrakeLevelOld(void) +{ + bool IBLO = false; + + if (BrakeCtrlPosNo > 0) + { + if (BrakeCtrlPos < BrakeCtrlPosNo) + { + ++BrakeCtrlPos; + // youBy: EP po nowemu + IBLO = true; + if (BrakePressureActual.PipePressureVal < 0 && BrakePressureTable[BrakeCtrlPos - 1].PipePressureVal > 0) + LimPipePress = PipePress; + } + else + { + IBLO = false; + } + } + + return IBLO; +} + +// ***************************************************************************** +// Q: 20160711 +// zmniejszenie nastawy hamulca +// ***************************************************************************** +bool TMoverParameters::DecBrakeLevelOld(void) +{ + bool DBLO = false; + + if (BrakeCtrlPosNo > 0) + { + if (BrakeCtrlPos > (BrakeHandle == TBrakeHandle::FV4a ? -2 : -1)) + { + --BrakeCtrlPos; + // youBy: EP po nowemu + DBLO = true; + // if ((BrakePressureTable[BrakeCtrlPos].PipePressureVal<0.0) && + // (BrakePressureTable[BrakeCtrlPos+1].PipePressureVal > 0)) + // LimPipePress=PipePress; + } + else + DBLO = false; + } + + return DBLO; +} + +// ************************************************************************************************* +// Q: 20160711 +// zwiększenie nastawy hamulca pomocnicznego +// ************************************************************************************************* +bool TMoverParameters::IncLocalBrakeLevel(float const CtrlSpeed) +{ + bool IBL; + if (LocalBrakePosA < 1.0 /*and (BrakeCtrlPos<1)*/) + { + LocalBrakePosA = std::min(1.0, LocalBrakePosA + CtrlSpeed / LocalBrakePosNo); + wake_for_brake(); + IBL = true; + } + else + IBL = false; + + return IBL; +} + +// ************************************************************************************************* +// Q: 20160711 +// zmniejszenie nastawy hamulca pomocniczego +// ************************************************************************************************* +bool TMoverParameters::DecLocalBrakeLevel(float const CtrlSpeed) +{ + bool DBL; + if (LocalBrakePosA > 0) + { + LocalBrakePosA = std::max(0.0, LocalBrakePosA - CtrlSpeed / LocalBrakePosNo); + wake_for_brake(); + DBL = true; + } + else + DBL = false; + + return DBL; +} + +// ************************************************************************************************* +// Q: 20160711 +// zwiększenie nastawy hamulca ręcznego +// ************************************************************************************************* +bool TMoverParameters::IncManualBrakeLevel(int CtrlSpeed) +{ + bool IMBL; + if (ManualBrakePos < ManualBrakePosNo) /*and (BrakeCtrlPos<1)*/ + { + while (ManualBrakePos < ManualBrakePosNo && CtrlSpeed > 0) + { + ManualBrakePos++; + CtrlSpeed--; + } + wake_for_brake(); + IMBL = true; + } + else + IMBL = false; + + return IMBL; +} + +// ************************************************************************************************* +// Q: 20160711 +// zmniejszenie nastawy hamulca ręcznego +// ************************************************************************************************* +bool TMoverParameters::DecManualBrakeLevel(int CtrlSpeed) +{ + bool DMBL; + if (ManualBrakePos > 0) + { + while (CtrlSpeed > 0 && ManualBrakePos > 0) + { + ManualBrakePos--; + CtrlSpeed--; + } + wake_for_brake(); + DMBL = true; + } + else + DMBL = false; + return DMBL; +} + +bool TMoverParameters::AlarmChainSwitch(bool const State) +{ + + if (AlarmChainFlag != State) + { + // simple routine for the time being + AlarmChainFlag = State; + return true; + } + return false; +} + +// ************************************************************************************************* +// Q: 20160710 +// hamowanie przeciwpoślizgowe +// ************************************************************************************************* +bool TMoverParameters::AntiSlippingBrake(void) +{ + bool ASB = false; // Ra: przeniesione z końca + if (ASBType == 1) + { + ASB = true; // SPKS!! + Hamulec->ASB(1); + BrakeSlippingTimer = 0; + } + return ASB; +} + +// ************************************************************************************************* +// Q: 20160711 +// włączenie / wyłączenie odluźniacza +// ************************************************************************************************* +bool TMoverParameters::BrakeReleaser(int state) +{ + bool OK = true; // false tylko jeśli nie uda się wysłać, GF 20161124 + if (state != 0) + { + // additional limitations imposed by pressure switch + if (false == ControlPressureSwitch || false == ReleaserEnabledOnlyAtNoPowerPos || true == IsMainCtrlNoPowerPos()) + { + Hamulec->Releaser(state); + } + } + else + { + Hamulec->Releaser(state); + } + if (CabActive != 0) // rekurencyjne wysłanie do następnego + OK = SendCtrlToNext("BrakeReleaser", state, CabActive); + return OK; +} + +// ************************************************************************************************* +// yB: 20160711 +// włączenie / wyłączenie uniwersalnego przycisku hamulcowego +// ************************************************************************************************* +bool TMoverParameters::UniversalBrakeButton(int button, int state) +{ + bool OK = true; // false tylko jeśli nie uda się wysłać, GF 20161124 + UniversalBrakeButtonActive[button] = state > 0; + int flag = 0; + if (Power24vIsAvailable || Power110vIsAvailable) + { + for (int i = 0; i < 3; i++) + { + flag = flag | (UniversalBrakeButtonActive[i] ? UniversalBrakeButtonFlag[i] : 0); + } + } + + Hamulec->SetUniversalFlag(flag); + Handle->SetUniversalFlag(flag); + LocHandle->SetUniversalFlag(flag); + UnlockPipe = (flag & TUniversalBrake::ub_UnlockPipe) > 0; + + // if the releaser can be activated by switch + if (TestFlag(UniversalBrakeButtonFlag[0] & UniversalBrakeButtonFlag[1] & UniversalBrakeButtonFlag[2], TUniversalBrake::ub_Release)) + { + BrakeReleaser(TestFlag(flag, TUniversalBrake::ub_Release) ? 1 : 0); + } + return OK; +} + +// ************************************************************************************************* +// Q: 20160711 +// włączenie / wyłączenie hamulca elektro-pneumatycznego +// ************************************************************************************************* +bool TMoverParameters::SwitchEPBrake(int state) +{ + bool OK; + + OK = false; + if (BrakeHandle == TBrakeHandle::St113 && CabOccupied != 0) + { + // the handle works the EP contactors pneumatically, their supply is cut as the Oerlikon handle's is + if (state > 0 && EPBrakeControlPowered()) + EpForce = Handle->GetEP(); // TODO: przetlumaczyc + else + EpForce = 0; + Hamulec->SetEPS(EpForce); + SendCtrlToNext("Brake", EpForce, CabActive); + } + // OK:=SetFlag(BrakeStatus,((2*State-1)*b_epused)); + // SendCtrlToNext('Brake',(state*(2*BrakeCtrlPos-1)),CabActive); + return OK; +} + +bool TMoverParameters::EPBrakeControlPowered() const +{ + return Power24vIsAvailable && DirActive != 0 && EpFuse; +} + +// ************************************************************************************************* +// Q: 20160711 +// zwiększenie ciśnienia hamowania +// ************************************************************************************************* +bool TMoverParameters::IncBrakePress(double &brake, double PressLimit, double dp) +{ + bool IBP; + // if (DynamicBrakeType<>dbrake_switch) and (DynamicBrakeType<>dbrake_none) and + // ((BrakePress>2.0) or (PipePress<3.7{(LowPipePress+0.5)})) then + if (DynamicBrakeType != dbrake_switch && DynamicBrakeType != dbrake_none && BrakePress > 2.0 && TrainType != train_type::emu) // yB radzi nie sprawdzać ciśnienia w przewodzie + // hunter-301211: dla EN57 silnikow nie odlaczamy + { + DynamicBrakeFlag = true; // uruchamianie hamulca ED albo odlaczanie silnikow + if (DynamicBrakeType == dbrake_automatic && abs(Im) > 60) // nie napelniaj wiecej, jak na EP09 + dp = 0.0; + } + if (brake + dp < PressLimit) + { + brake = brake + dp; + IBP = true; + } + else + { + IBP = false; + brake = PressLimit; + } + return IBP; +} + +// ************************************************************************************************* +// Q: 20160711 +// zmniejszenie ciśnienia hamowania +// ************************************************************************************************* +bool TMoverParameters::DecBrakePress(double &brake, double PressLimit, double dp) +{ + bool DBP; + + if (brake - dp > PressLimit) + { + brake = brake - dp; + DBP = true; + } + else + { + DBP = false; + brake = PressLimit; + } + // if ((DynamicBrakeType != dbrake_switch) && ((BrakePress < 0.1) && (PipePress > 0.45 + // /*(LowPipePress+0.06)*/ ))) + if (DynamicBrakeType != dbrake_switch && BrakePress < 0.1) // yB radzi nie sprawdzać ciśnienia w przewodzie + DynamicBrakeFlag = false; // wylaczanie hamulca ED i/albo zalaczanie silnikow + + return DBP; +} + +// ************************************************************************************************* +// Q: 20160711 +// przełączenie nastawy hamulca O/P/T +// ************************************************************************************************* +bool TMoverParameters::BrakeDelaySwitch(int BDS) +{ + bool rBDS; + if (Hamulec->SetBDF(BDS)) + { + BrakeDelayFlag = BDS; + rBDS = true; + Hamulec->SetBrakeStatus(Hamulec->GetBrakeStatus() & ~64); + // kopowanie nastawy hamulca do kolejnego czlonu - do przemyślenia + if (CabActive != 0) + SendCtrlToNext("BrakeDelay", BrakeDelayFlag, CabActive); + } + else + rBDS = false; + + return rBDS; +} + +// ************************************************************************************************* +// Q: 20160712 +// zwiększenie przełożenia hamulca +// ************************************************************************************************* +bool TMoverParameters::IncBrakeMult(void) +{ + bool IBM; + + if (LoadFlag > 0 && MBPM < 2 && LoadFlag < 3) + { + if (MaxBrakePress[2] > 0 && LoadFlag == 1) + LoadFlag = 2; + else + LoadFlag = 3; + IBM = true; + if (BrakeCylMult[2] > 0) + BrakeCylMult[0] = BrakeCylMult[2]; + } + else + IBM = false; + + return IBM; +} + +// ************************************************************************************************* +// Q: 20160712 +// zmniejszenie przełożenia hamulca +// ************************************************************************************************* +bool TMoverParameters::DecBrakeMult(void) +{ + bool DBM; + if (LoadFlag > 1 && MBPM < 2) + { + if (MaxBrakePress[2] > 0 && LoadFlag == 3) + LoadFlag = 2; + else + LoadFlag = 1; + DBM = true; + if (BrakeCylMult[1] > 0) + BrakeCylMult[0] = BrakeCylMult[1]; + } + else + DBM = false; + + return DBM; +} + +// ************************************************************************************************* +// Q: 20160712 +// zaktualizowanie ciśnienia w hamulcach +// ************************************************************************************************* +void TMoverParameters::UpdateBrakePressure(double dt) +{ + // const double LBDelay = 5.0; // stala czasowa hamulca + // double Rate, Speed, dp, sm; + + dpLocalValve = 0; + dpBrake = 0; + + Hamulec->ForceLeak(dt * AirLeakRate * 0.25); // fake air leaks from brake system reservoirs + + auto const brakepress{BrakePress}; + BrakePress = Hamulec->GetBCP(); + if (dt > 0.0) + { + // averaged over about a second: the valves move the cylinder in pulses, quicker than that within a single step + auto const rate{std::abs(BrakePress - brakepress) / dt}; + BrakePressRate += (rate - BrakePressRate) * std::min(1.0, dt / 1.0); + } + // BrakePress:=(Hamulec as TEst4).ImplsRes.pa; + Volume = Hamulec->GetBRP(); +} + +// ************************************************************************************************* +// Q: 20160712 +// Obliczanie pracy sprężarki +// ************************************************************************************************* +void TMoverParameters::CompressorCheck(double dt) +{ + + if (CompressorSpeed == 0.0) + { + CompressorAllow = false; + return; + } + + if (CabDependentCompressor) + { + if (CabActive > 0) + { + MinCompressor = MinCompressor_cabA; + MaxCompressor = MaxCompressor_cabA; + } + if (CabActive < 0) + { + MinCompressor = MinCompressor_cabB; + MaxCompressor = MaxCompressor_cabB; + } + } + + // EmergencyValve + EmergencyValveOpen = Compressor > (EmergencyValveOpen ? EmergencyValveOff : EmergencyValveOn); + if (EmergencyValveOpen) + { + auto dV = static_cast(PF(0, Compressor, EmergencyValveArea) * dt); + CompressedVolume -= dV; + } + + CompressedVolume = std::max(0.0, CompressedVolume - dt * AirLeakRate * 0.1); // nieszczelności: 0.001=1l/s + + Compressor = CompressedVolume / VeselVolume; + + // assorted operational logic + auto const MaxCompressorF{CompressorList[TCompressorList::cl_MaxFactor][CompressorListPos] * MaxCompressor}; + auto const MinCompressorF{CompressorList[TCompressorList::cl_MinFactor][CompressorListPos] * MinCompressor}; + auto const CompressorSpeedF{CompressorList[TCompressorList::cl_SpeedFactor][CompressorListPos] * CompressorSpeed}; + // checking the impact on the compressor allowance + if (auto const AllowFactor{CompressorList[TCompressorList::cl_Allow][CompressorListPos]}; AllowFactor > 0.5) + { + CompressorAllow = AllowFactor > 1.5; + } + + switch (CompressorPower) + { + case 2: + { + CompressorAllow = ConverterAllow; + break; + } + case 3: + { + // HACK: make sure compressor coupled with diesel engine is always ready for work + CompressorStart = start_t::automatic; + break; + } + default: + { + break; + } + } + + // the main circuit, also for a compressor driven by the engine, otherwise the low voltage + auto const compressorpower{CompressorPower == 0 || CompressorPower == 3 ? MainCircuitPowered() : Power110vIsAvailable}; + CompressorPowerTime = compressorpower ? CompressorPowerTime + dt : 0.0; + auto const compressorready{compressorpower && CompressorPowerTime >= CompressorStartDelay}; + // TBD: split CompressorAllow into separate enable/disable flags, inherit compressor from basic_device + auto const compressorenable{CompressorAllowLocal && (CompressorStart == start_t::automatic || CompressorAllow)}; + auto const compressordisable{false == compressorenable}; + + auto const pressureistoolow{Compressor < MinCompressorF}; + auto const pressureistoohigh{Compressor > MaxCompressorF}; + + // TBD, TODO: break the lock with no low voltage power? + auto const governorlockispresent{MaxCompressorF - MinCompressorF > 0.0001}; + CompressorGovernorLock = governorlockispresent && false == pressureistoolow // unlock if pressure drops below minimal threshold + && (pressureistoohigh || CompressorGovernorLock); // lock if pressure goes above maximum threshold + // for these multi-unit engines compressors turn off whenever any of them was affected by the governor + // NOTE: this is crude implementation, limited only to adjacent vehicles + // TODO: re-implement when a more elegant/flexible system is in place + auto const coupledgovernorlock{ + (Couplers[end::rear].Connected != nullptr && true == TestFlag(Couplers[end::rear].CouplingFlag, coupling::permanent) && Couplers[end::rear].Connected->CompressorGovernorLock) || + (Couplers[end::front].Connected != nullptr && true == TestFlag(Couplers[end::front].CouplingFlag, coupling::permanent) && Couplers[end::front].Connected->CompressorGovernorLock)}; + auto const governorlock{CompressorGovernorLock || coupledgovernorlock}; + + auto const compressorflag{CompressorFlag}; + CompressorFlag = + compressorready && false == compressordisable && (false == governorlock || CompressorPower == 3) && (CompressorFlag || (compressorenable && LastSwitchingTime > CtrlDelay)); + + if (CompressorFlag && CompressorFlag != compressorflag) + { + // jeśli została załączona to trzeba ograniczyć ponowne włączenie + LastSwitchingTime = 0; + } + if (CompressorFlag != compressorflag) + { + Timer::subsystem.switching.note(CompressorFlag ? Timer::switching_counter::compressor_on : Timer::switching_counter::compressor_off, this, &TypeName, &Name); + } + + if (false == CompressorFlag) + { + return; + } + + // working compressor adds air to the air reservoir + if (CompressorPower == 3) + { + // the compressor is coupled with the diesel engine, engine revolutions affect the output + CompressedVolume += + CompressorSpeedF * (2.0 * MaxCompressorF - Compressor) / MaxCompressorF * EngineRPMRatio() * dt * (CompressorGovernorLock ? 0.0 : 1.0); // with the lock active air is vented out + } + else + { + // the compressor is a stand-alone device, working at steady pace + CompressedVolume += CompressorSpeedF * (2.0 * MaxCompressorF - Compressor) / MaxCompressorF * dt; + } + + if (pressureistoohigh && (false == governorlockispresent || CompressorPower == 3)) + { + // vent some air out if there's no governor lock to stop the compressor from exceeding acceptable pressure level + SetFlag(SoundFlag, sound::relay | sound::loud); + auto ventedfraction{0.999}; // HACK: drop a tiny bit so the sound doesn't trigger repeatedly + if (false == governorlockispresent) + { + ventedfraction = 0.80; // arbitrary amount + } + else if (CompressorTankValve) + { + ventedfraction = MinCompressorF / MaxCompressorF; // drop to mincompressor level + } + CompressedVolume *= ventedfraction; + if (false == governorlockispresent || CompressorTankValve) + { + CompressorGovernorLock = false; + } + } + + // a compressor not driven by the engine doesn't draw power (some 5 A) from the high- or low voltage circuit yet +} + +// ************************************************************************************************* +// Q: 20160712 +// aktualizacja ciśnienia w przewodzie głównym +// ************************************************************************************************* +void TMoverParameters::UpdatePipePressure(double dt) +{ + if (PipePress > 1.0) + { + Pipe->Flow(-PipePress*AirLeakRate * dt); + Pipe->Act(); + } + + // double dV; + // TMoverParameters *c; // T_MoverParameters + double temp; + // int b; + + PipePress = Pipe->P(); + // PPP:=PipePress; + + dpMainValve = 0; + + if (BrakeCtrlPosNo > 1) + { + + UpdateLocalBrakeValve(dt); + UpdateMainValve(dt); + } + + UpdateEmergencyValve(dt); + + // 0.2*Spg + Pipe->Flow(-dpMainValve); + Pipe->Flow(-PipePress * 0.001 * dt); + // if Heating then + // Pipe.Flow(PF(PipePress, 0, d2A(7)) * dt); + // if ConverterFlag then + // Pipe.Flow(PF(PipePress, 0, d2A(12)) * dt); + dpMainValve = dpMainValve / (Dim.L * Spg * 20); + + CntrlPipePress = Hamulec->GetVRP(); // ciśnienie komory wstępnej rozdzielacza + + // if (Hamulec is typeid(TWest)) return 0; + + UpdateDistributorSettings(); + + if ((BrakeHandle == TBrakeHandle::FVel6 || BrakeHandle == TBrakeHandle::FVE408) && CabOccupied != 0) + { + UpdateEPBrake(); + } + else if (BrakeHandle == TBrakeHandle::St113 && CabOccupied != 0 && std::abs(EpForce) > 0.001 && !EPBrakeControlPowered()) + { + // the EP brake switched on with the button drops out with the control's supply + SwitchEPBrake(0); + } + + Pipe->Act(); + PipePress = Pipe->P(); + if ((Hamulec->GetBrakeStatus() & b_dmg) == b_dmg) // jesli hamulec wyłączony + temp = 0.0; // odetnij + else + temp = 1.0; // połącz + Pipe->Flow(temp * Hamulec->GetPF(temp * PipePress, dt, Vel)); + // the air the brake hoses carry to and from the neighbours comes once all vehicles have stepped, UpdatePipeCouplers() + PipeCouplersPending = true; + + if (ASBType == 128) + Hamulec->ASB(int(SlippingWheels && Vel > 1) * (1 + 2 * int(nrot_eps < -0.01))); + + dpPipe = 0; + + // yB: jednokrokowe liczenie tego wszystkiego + Pipe->Act(); + PipePress = Pipe->P(); + + dpMainValve = dpMainValve / (100.0 * dt); // normalizacja po czasie do syczenia; + + if (PipePress < -1.0) + { + PipePress = -1.0; + Pipe->CreatePress(-1.0); + Pipe->Act(); + } + + if (CompressedVolume < 0.0) + CompressedVolume = 0.0; +} + +// the flow of the local brake valve, by the handle, the TRAXX's timed one, the integrated controller or the parking +void TMoverParameters::UpdateLocalBrakeValve(double dt) +{ + // the local brake of a vehicle prepared for hauling (PulleeMode) is held released, whatever asks for it + if (EngineType != TEngineType::ElectricInductionMotor) + { + double lbpa = LocHandleTimeTraxx ? eim_localbrake : LocalBrakePosA; + if (EIMCtrlType > 0 && UniCtrlIntegratedLocalBrakeCtrl) + { + lbpa = std::max(0.0, -eimic_real); + } + if (SpeedCtrlUnit.Parking) + { + lbpa = std::max(lbpa, StopBrakeDecc); + } + dpLocalValve = LocHandle->GetPF(PulleeMode ? 0.0 : std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); + } + else + { + // in EIM stock the pneumatic local brake is normally driven only by the MED algorithm + // (LocalBrakePosAEIM). When SplitEDPneumaticBrake is active the dedicated LocalBrake + // lever should apply pneumatic pressure on the locomotive directly, bypassing MED. + // LocHandleTimeTraxx also bypasses MED, but has 3 positions (brake-hold-unbrake). + double lbpa; + if (LocHandleTimeTraxx) + { + lbpa = eim_localbrake; + } + else if (SplitEDPneumaticBrake) // When LocHandleTimeTraxx and SplitEDPneumaticBrake are both active, lbpa is taken from LocHandleTimeTraxx, which is the desired behavior. + { + lbpa = LocalBrakePosA; + } + else + { + lbpa = 0.0; + } + dpLocalValve = LocHandle->GetPF(PulleeMode ? 0.0 : std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); + } +} + +// the lock of the brake pipe and the flow of the driver's handle, from the main reservoir or into the air +void TMoverParameters::UpdateMainValve(double dt) +{ + auto const temp{MainValveSupply()}; + Handle->SetReductor(BrakeCtrlPos2); + + if (PulleeMode) + { + // the driver's valve of a vehicle prepared for hauling is cut out, whatever its handle shows + dpMainValve = 0; + } + else if ((BrakeOpModes & bom_PS) == 0 || (CabOccupied != 0 && BrakeOpModeFlag != bom_PS)) + { + + if (BrakeOpModeFlag < bom_EP || Handle->GetPos(bh_EB) - 0.5 < BrakeCtrlPosR || (BrakeHandle != TBrakeHandle::MHZ_EN57 && BrakeHandle != TBrakeHandle::MHZ_K8P)) + { + dpMainValve = Handle->GetPF(MainValveHandlePosition(), PipePress, temp, dt, EqvtPipePress); + } + else + { + dpMainValve = Handle->GetPF(0, PipePress, temp, dt, EqvtPipePress); + } + } + else if (BrakeCtrlPos == Handle->GetPos(bh_EB)) + { + dpMainValve = Handle->GetPF(BrakeCtrlPosR, PipePress, temp, dt, EqvtPipePress); + } + + if (dpMainValve < 0) // && (PipePressureVal > 0.01) //50 + { + if (Compressor > ScndPipePress) + { + CompressedVolume = CompressedVolume + dpMainValve / 1500.0; + Pipe2->Flow(dpMainValve / 3.0); + } + else + Pipe2->Flow(dpMainValve); + } +} + +// the pressure the driver's handle is fed from: the main pipe's, or the brake pipe's own with the pipe locked +double TMoverParameters::MainValveSupply() +{ + LockPipe = PipePress < (LockPipe ? LockPipeOff : LockPipeOn); + bool lock_new = (LockPipe && !UnlockPipe && BrakeCtrlPosR > HandleUnlock) || (EmergencyCutsOffHandle && EmergencyValveFlow > 0); // new simple codition based on .fiz + bool lock_old = BrakeHandle == TBrakeHandle::FV4a // old complex condition based on assumptions + && PipePress < 2.75 && (Hamulec->GetStatus() & b_rls) == 0 && BrakeSubsystem == TBrakeSubSystem::ss_LSt && TrainType != train_type::emu && !UnlockPipe; + + if (lock_old || lock_new) + { + return PipePress + 0.00001; + } + return ScndPipePress; +} + +// the position the driver's handle works at: its own, or the one the speed control's brake intervention sets +double TMoverParameters::MainValveHandlePosition() const +{ + double pos = BrakeCtrlPosR; + if (SpeedCtrlUnit.IsActive && SpeedCtrlUnit.BrakeIntervention && !SpeedCtrlUnit.Standby && BrakeCtrlPos != Handle->GetPos(bh_EB)) + { + pos = Handle->GetPos(bh_NP); + if (SpeedCtrlUnit.BrakeInterventionBraking) + pos = Handle->GetPos(bh_FB); + if (SpeedCtrlUnit.BrakeInterventionUnbraking) + pos = Handle->GetPos(bh_RP); + } + return pos; +} + +void TMoverParameters::UpdateEmergencyValve(double dt) +{ + // ulepszony hamulec bezp. + EmergencyValveFlow = 0.0; + + + // EngDmgFlag 32 (load destroyed) used to trigger this too; dropped, it has nothing to do with + // the emergency brake (a broken coupler sets AlarmChainFlag instead). the Elf's emergency brake position + // vents the pipe only from the vehicle driven from, whatever the controllers of the others show. + // a vehicle prepared for hauling (PulleeMode) vents it for nothing of its own, only for the alarm chain, + // which a train parting sets too + auto const ownemergency{RadioStopFlag || (EIMCtrlEmergency && LocalBrakePosA >= 1.0) || (IsMainCtrlEmergencyPos() && IsCabMaster()) || SecuritySystem.is_braking() || + (SpringBrakeDriveEmergencyVel >= 0 && Vel > SpringBrakeDriveEmergencyVel && SpringBrake.IsActive) || + (0 == CabActive && (InactiveCabFlag & activation::emergencybrake) != 0)}; + if (AlarmChainFlag || (ownemergency && false == PulleeMode)) + { + EmergencyValveFlow = PF(0, PipePress, 0.15) * dt; + } + dpMainValve += EmergencyValveFlow; +} + +// what the distributor valve gets of the local brake and the load, by its kind +void TMoverParameters::UpdateDistributorSettings() +{ + switch (BrakeValve) + { + + case TBrakeValve::K: + case TBrakeValve::W: + { + + if (BrakeLocHandle != TBrakeHandle::NoHandle) + { + LocBrakePress = LocHandle->GetCP(); + + //(Hamulec as TWest).SetLBP(LocBrakePress); + Hamulec->SetLBP(LocBrakePress); + } + if (MBPM < 2) + //(Hamulec as TWest).PLC(MaxBrakePress[LoadFlag]) + Hamulec->PLC(MaxBrakePress[LoadFlag]); + else + //(Hamulec as TWest).PLC(TotalMass); + Hamulec->PLC(TotalMass - Mred); + break; + } + + case TBrakeValve::LSt: + case TBrakeValve::EStED: + { + + LocBrakePress = LocHandle->GetCP(); + auto const et41or42 = [](train_type const Type) { return Type == train_type::et41 || Type == train_type::et42; }; + for (auto const &couplerentry : Couplers) + // nie podoba mi się to rozwiązanie, chyba trzeba + // dodać jakiś wpis do fizyki na to + if (et41or42(TrainType) && couplerentry.Connected != nullptr && et41or42(couplerentry.Connected->TrainType) && (couplerentry.CouplingFlag & 36) == 36) + LocBrakePress = std::max(couplerentry.Connected->LocHandle->GetCP(), LocBrakePress); + + // if ((DynamicBrakeFlag) && (EngineType == ElectricInductionMotor)) + //{ + // //if (Vel > 10) + // // LocBrakePress = 0; + // //else if (Vel > 5) + // // LocBrakePress = (10 - Vel) / 5 * LocBrakePress; + // } + + //(Hamulec as TLSt).SetLBP(LocBrakePress); + Hamulec->SetLBP(LocBrakePress); + if (BrakeValve == TBrakeValve::EStED) + { + if (MBPM < 2) + Hamulec->PLC(MaxBrakePress[LoadFlag]); + else + Hamulec->PLC(TotalMass - Mred); + } + break; + } + + case TBrakeValve::CV1_L_TR: + { + LocBrakePress = LocHandle->GetCP(); + //(Hamulec as TCV1L_TR).SetLBP(LocBrakePress); + Hamulec->SetLBP(LocBrakePress); + break; + } + + case TBrakeValve::EP2: + case TBrakeValve::EP1: + { + Hamulec->PLC(TotalMass - Mred); + break; + } + case TBrakeValve::ESt3AL2: + case TBrakeValve::NESt3: + case TBrakeValve::ESt4: + case TBrakeValve::ESt3: + { + if (MBPM < 2) + //(Hamulec as TNESt3).PLC(MaxBrakePress[LoadFlag]) + Hamulec->PLC(MaxBrakePress[LoadFlag]); + else + //(Hamulec as TNESt3).PLC(TotalMass); + Hamulec->PLC(TotalMass - Mred); + LocBrakePress = LocHandle->GetCP(); + //(Hamulec as TNESt3).SetLBP(LocBrakePress); + Hamulec->SetLBP(LocBrakePress); + break; + } + case TBrakeValve::KE: + { + LocBrakePress = LocHandle->GetCP(); + //(Hamulec as TKE).SetLBP(LocBrakePress); + Hamulec->SetLBP(LocBrakePress); + if (MBPM < 2) + //(Hamulec as TKE).PLC(MaxBrakePress[LoadFlag]) + Hamulec->PLC(MaxBrakePress[LoadFlag]); + else + //(Hamulec as TKE).PLC(TotalMass); + Hamulec->PLC(TotalMass - Mred); + break; + } + default: + { + // unsupported brake valve type, we should never land here + // ErrorLog( "Unsupported brake valve type (" + std::to_string( BrakeValve ) + ") in " + TypeName ); + // ::PostQuitMessage( 0 ); + break; + } + } // switch +} + +// the ep brake of the FVel6 and FVE408 handles, passed along the unit +void TMoverParameters::UpdateEPBrake() +{ + if (EPBrakeControlPowered()) // tu powinien byc jeszcze bezpiecznik EP i baterie - + // temp = (Handle as TFVel6).GetCP + EpForce = Handle->GetEP(); + else + EpForce = 0.0; + + DynamicBrakeEMUStatus = EpForce > 0.001 ? Power110vIsAvailable : true; + + double temp1 = EpForce; + if (DCEMUED_EP_max_Vel > 0.001 && Vel > DCEMUED_EP_max_Vel && DynamicBrakeEMUStatus) + temp1 = 0; + if (DCEMUED_EP_min_Im > 0.001 && abs(Im) > DCEMUED_EP_min_Im && DynamicBrakeEMUStatus) + temp1 = 0; + Hamulec->SetEPS(temp1); + TUHEX_StageActual = static_cast(EpForce); + TUHEX_Active = TUHEX_StageActual > 0; + // Ra 2014-11: na tym się wysypuje, ale nie wiem, w jakich warunkach + SendCtrlToNext("Brake", EpForce, CabActive); +} + +// ************************************************************************************************* +// Q: 20160713 +// Aktualizacja ciśnienia w przewodzie zasilającym +// ************************************************************************************************* +void TMoverParameters::UpdateScndPipePressure(double dt) +{ + if (ScndPipePress > 1.0) + { + Pipe2->Flow(-ScndPipePress*AirLeakRate * dt); + Pipe2->Act(); + } + + const double Spz = 0.5067; + + UpdateSpringBrake(dt); + + Pipe2->Flow(Hamulec->GetHPFlow(ScndPipePress, dt)); + // NOTE: condition disabled to allow the air flow from the main hose to the main tank as well + if (/* ( ( Compressor > ScndPipePress ) && ( */ VeselVolume > 0.0 /* ) ) || ( TrainType == train_type::emu ) || ( TrainType == train_type::dmu ) */) + { + double const dV = PF(Compressor, ScndPipePress, Spz) * dt; + CompressedVolume += dV / 1000.0; + Pipe2->Flow(-dV); + } + // the air the main reservoir hoses carry to and from the neighbours comes once all vehicles have stepped, UpdatePipeCouplers() + ScndPipeCouplersPending = true; + Pipe2->Act(); + ScndPipePress = Pipe2->P(); + + if (ScndPipePress < -1) + { + ScndPipePress = -1; + Pipe2->CreatePress(-1); + Pipe2->Act(); + } +} + +// ************************************************************************************************* +// yB: 20190906 +// Aktualizacja ciśnienia w hamulcu sprezynowym +// ************************************************************************************************* +void TMoverParameters::UpdateSpringBrake(double /*dt*/) +{ + double BP = SpringBrake.PNBrakeConnection ? BrakePress : 0; + double MSP = SpringBrake.ShuttOff ? 0 : SpringBrake.MaxSetPressure; + if (!SpringBrake.Activate) + { + double desired_press = std::min(std::max(MSP, BP), Pipe2->P()); + double dv = PF(desired_press, SpringBrake.SBP, SpringBrake.ValveOffArea); + SpringBrake.Cylinder->Flow(-dv); + Pipe2->Flow(std::max(dv, 0.0)); + } + else + { + double dv = PF(BP, SpringBrake.SBP, SpringBrake.ValveOnArea); + SpringBrake.Cylinder->Flow(-dv); + } + if (SpringBrake.SBP > SpringBrake.ResetPressure) + SpringBrake.IsReady = true; + + SpringBrake.IsActive = SpringBrake.SBP < (SpringBrake.IsActive ? SpringBrake.PressureOff : SpringBrake.PressureOn); + + SpringBrake.Release = false; + SpringBrake.Cylinder->Act(); + SpringBrake.SBP = SpringBrake.Cylinder->P(); +} +namespace +{ + +// whether the air flowing to a coupled vehicle along a pipe wakes its physics: any flow did, but a vehicle standing next to one +// whose physics is on gets a trickle of it all the time, as their pressures settle, and each wake kept it on for 5 s. with +// Global.physics_pipewake only a flow which leaves its pressure, with what has flown in while it slept, that much away from the +// pressure of the vehicle the air comes from, or which has changed it by that much since it fell asleep: a pressure followed in +// small steps would never reach the valves of a vehicle asleep otherwise +bool pipe_wakes(double const Flow, double const Pressure, TReservoir const &Pipe) +{ + if (Flow * Flow <= 0.00000000000001) + return false; + return (Global.physics_pipewake <= 0.f) + || (std::abs(Pressure - Pipe.P_pending()) > Global.physics_pipewake) + || (std::abs(Pipe.P_pending() - Pipe.P_applied()) > Global.physics_pipewake); +} + +// the pressure in the pipe of a coupled vehicle the flow to it goes by. the pressure the vehicle keeps is the one of its last step: +// with Global.physics_pipewake one asleep can take air for a long time without waking, and the flow, going by that pressure, would +// carry on past the pressure of the vehicle it comes from. so of one asleep, the pressure with what has flown in since +double neighbour_pipe_pressure(TMoverParameters const &Neighbour, double const Pressure, TReservoir const &Pipe) +{ + if ((Global.physics_pipewake <= 0.f) || Neighbour.PhysicActivation) + return Pressure; + return Pipe.P_pending(); +} + +} // namespace + +// ************************************************************************************************* +// Q: 20160715 +// oblicza i zwraca przepływ powietrza pomiędzy pojazdami +// ************************************************************************************************* +double TMoverParameters::GetDVc(double dt) +{ + // T_MoverParameters *c; + TMoverParameters *c; + double dv1; + double dv2; // , dV; + + dv1 = 0; + dv2 = 0; + // sprzeg 1 + if (Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_pneumatic)) + { //*0.85 + c = Couplers[0].Connected; // skrot //0.08 //e/D * L/D = e/D^2 * L + dv1 = 0.5 * dt * PF(PipePress, neighbour_pipe_pressure(*c, c->PipePress, *c->Pipe), Spg / (1.0 + 0.015 / Spg * Dim.L)); + c->Pipe->Flow(-dv1); + if (pipe_wakes(dv1, PipePress, *c->Pipe)) + c->switch_physics(true, wake_cause::mainpipe); + } + // sprzeg 2 + if (Couplers[1].Connected != nullptr && TestFlag(Couplers[1].CouplingFlag, ctrain_pneumatic)) + { + c = Couplers[1].Connected; // skrot + dv2 = 0.5 * dt * PF(PipePress, neighbour_pipe_pressure(*c, c->PipePress, *c->Pipe), Spg / (1.0 + 0.015 / Spg * Dim.L)); + c->Pipe->Flow(-dv2); + if (pipe_wakes(dv2, PipePress, *c->Pipe)) + c->switch_physics(true, wake_cause::mainpipe); + } + // if ((Couplers[1].Connected != NULL) && (Couplers[0].Connected != NULL)) + // if ((TestFlag(Couplers[0].CouplingFlag, ctrain_pneumatic)) && + // (TestFlag(Couplers[1].CouplingFlag, ctrain_pneumatic))) + // { + // dV = 0.05 * dt * PF(Couplers[0].Connected->PipePress, Couplers[1].Connected->PipePress, + // (Spg * 0.85) / (1 + 0.03 * Dim.L)) * + // 0; // ktoś mi powie jaki jest sens tego bloku jeśli przepływ mnożony przez zero? + // Couplers[0].Connected->Pipe->Flow(+dV); + // Couplers[1].Connected->Pipe->Flow(-dV); + // } + // suma + return dv2 + dv1; +} + +// ************************************************************************************************* +// the air the main reservoir hoses carry between the vehicle's pipe and the neighbours' in dt: the neighbours' +// share is sent to them, the vehicle's own returned +// ************************************************************************************************* +double TMoverParameters::GetScndDVc(double dt) +{ + const double Spz = 0.5067; + TMoverParameters *c; + double dv1 = 0; + double dv2 = 0; + + // sprzeg 1 + if (Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic)) + { + c = Couplers[0].Connected; // skrot + dv1 = 0.5 * dt * PF(ScndPipePress, neighbour_pipe_pressure(*c, c->ScndPipePress, *c->Pipe2), Spz * 0.75); + c->Pipe2->Flow(-dv1); + if (pipe_wakes(dv1, ScndPipePress, *c->Pipe2)) + c->switch_physics(true, wake_cause::scndpipe); + } + // sprzeg 2 + if (Couplers[1].Connected != nullptr && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) + { + c = Couplers[1].Connected; // skrot + dv2 = 0.5 * dt * PF(ScndPipePress, neighbour_pipe_pressure(*c, c->ScndPipePress, *c->Pipe2), Spz * 0.75); + c->Pipe2->Flow(-dv2); + if (pipe_wakes(dv2, ScndPipePress, *c->Pipe2)) + c->switch_physics(true, wake_cause::scndpipe); + } + if (Couplers[1].Connected != nullptr && Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic) && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) + { + double const dV = 0.00025 * dt * PF(Couplers[0].Connected->ScndPipePress, Couplers[1].Connected->ScndPipePress, Spz * 0.25); + Couplers[0].Connected->Pipe2->Flow(+dV); + Couplers[1].Connected->Pipe2->Flow(-dV); + } + return dv1 + dv2; +} +namespace +{ + + +// a pipe along the train, whose air the hoses between the vehicles carry (TMoverParameters::UpdatePipeCouplers()) +struct train_pipe +{ + std::shared_ptr TMoverParameters::*reservoir; + double TMoverParameters::*pressure; + bool TMoverParameters::*pending; // the vehicle stepped the pipe, the exchange through its hoses is yet to come + int hose; // the coupling flag of the pipe's hose + double (TMoverParameters::*exchange)(double); // the air the hoses carry in a step, the neighbours' share sent to them + double (*area)(TMoverParameters const &); // the cross-section of the hose, as the exchange takes it +}; + +// the brake pipe, GetDVc() +train_pipe const brake_pipe{&TMoverParameters::Pipe, + &TMoverParameters::PipePress, + &TMoverParameters::PipeCouplersPending, + ctrain_pneumatic, + &TMoverParameters::GetDVc, + [](TMoverParameters const &Vehicle) { return Vehicle.Spg / (1.0 + 0.015 / Vehicle.Spg * Vehicle.Dim.L); }}; +// the main reservoir pipe, GetScndDVc() +train_pipe const main_reservoir_pipe{&TMoverParameters::Pipe2, + &TMoverParameters::ScndPipePress, + &TMoverParameters::ScndPipeCouplersPending, + ctrain_scndpneumatic, + &TMoverParameters::GetScndDVc, + [](TMoverParameters const &) { return 0.5067 * 0.75; }}; + +// the number of sub-steps of dt the air exchange through the hoses of the vehicle's pipe needs: in one, the air a +// hose carries stays below what evens out the pipes on its ends +int hose_substeps(TMoverParameters const &Vehicle, train_pipe const &Pipe, double const dt) +{ + auto substeps{1}; + auto const area{Pipe.area(Vehicle)}; + auto const capacity{(Vehicle.*Pipe.reservoir)->GetCap()}; + for (auto const &hose : Vehicle.Couplers) + { + if (hose.Connected == nullptr || false == TestFlag(hose.CouplingFlag, Pipe.hose)) + { + continue; + } + auto const &other{*hose.Connected}; + auto const othercapacity{(other.*Pipe.reservoir)->GetCap()}; + // the flow per bar of the difference, at small differences, where it's the largest + auto const pressure{std::max(Vehicle.*Pipe.pressure, other.*Pipe.pressure)}; + auto const conductance{std::abs(PF(pressure, pressure - 0.01, area)) / 0.01}; + auto const equalising{capacity * othercapacity / (capacity + othercapacity)}; + substeps = std::max(substeps, static_cast(std::ceil(dt * conductance / equalising))); + } + return std::min(substeps, 10); +} + +// the vehicles of the list which stepped the pipe, each with the number of the train it is in: the ones joined by the hoses +// of the pipe, directly, numbered in the order of their first vehicle in the list. a vehicle which didn't step the pipe +// (its physics sleeps) takes the air sent to it without passing it on, so it ends a train +std::vector hose_trains(std::vector const &Vehicles, train_pipe const &Pipe) +{ + auto constexpr none{std::numeric_limits::max()}; + std::vector trains(Vehicles.size(), none); + // the vehicles by their address, for finding the neighbours in the list + std::vector> byaddress; + byaddress.reserve(Vehicles.size()); + for (std::size_t index = 0; index < Vehicles.size(); ++index) + { + if (Vehicles[index]->*Pipe.pending) + { + byaddress.emplace_back(Vehicles[index], index); + } + } + std::ranges::sort(byaddress); + auto const find = [&byaddress](TMoverParameters const *Vehicle) { + auto const found{std::ranges::lower_bound(byaddress, Vehicle, std::less<>{}, &std::pair::first)}; + return (found != byaddress.end() && found->first == Vehicle) ? found->second : none; + }; + std::size_t count{0}; + std::vector stack; + for (std::size_t first = 0; first < Vehicles.size(); ++first) + { + if (false == Vehicles[first]->*Pipe.pending || trains[first] != none) + { + continue; + } + trains[first] = count; + stack.assign(1, first); + while (false == stack.empty()) + { + auto const &vehicle{*Vehicles[stack.back()]}; + stack.pop_back(); + for (auto const &hose : vehicle.Couplers) + { + if (hose.Connected == nullptr || false == TestFlag(hose.CouplingFlag, Pipe.hose)) + { + continue; + } + if (auto const other{find(hose.Connected)}; other != none && trains[other] == none) + { + trains[other] = count; + stack.push_back(other); + } + } + } + ++count; + } + return trains; +} + +// 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 &Pipe, double const dt) +{ + auto const trains{hose_trains(Vehicles, Pipe)}; + std::vector substeps; + for (std::size_t index = 0; index < Vehicles.size(); ++index) + { + if (false == Vehicles[index]->*Pipe.pending) + { + continue; + } + if (substeps.size() <= trains[index]) + { + substeps.resize(trains[index] + 1, 1); + } + substeps[trains[index]] = std::max(substeps[trains[index]], hose_substeps(*Vehicles[index], Pipe, dt)); + } + 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) + { + if (false == Vehicles[index]->*Pipe.pending || trains[index] != train) + { + continue; + } + auto *vehicle{Vehicles[index]}; + auto &pipe{*(vehicle->*Pipe.reservoir)}; + pipe.Act(); // what the neighbours have sent in the meantime + vehicle->*Pipe.pressure = pipe.P(); + pipe.Flow((vehicle->*Pipe.exchange)(substep)); + pipe.Act(); + vehicle->*Pipe.pressure = pipe.P(); + } + } + } + for (auto *vehicle : Vehicles) + { + vehicle->*Pipe.pending = false; + } +} + +} // namespace + +// ************************************************************************************************* +// the number of sub-steps of dt the air exchange through the brake hoses of the vehicle needs. taken in a single +// step of 0.01 s, the hose between two 14 m freight wagons carries twice the air which evens out their pipes, the +// pipes overshoot each other in turns and the distributors see the pressure up to 0.28 bar off what's in the pipe +// (eu07/maszyna#368) +// ************************************************************************************************* +int TMoverParameters::PipeCouplersSubsteps(double const dt) const +{ + return hose_substeps(*this, brake_pipe, dt); +} + +// ************************************************************************************************* +// the number of sub-steps of dt the air exchange through the main reservoir hoses of the vehicle needs. taken in a +// single step of 0.01 s, the hose carries about 1.5 times the air which evens out the pipes on its ends; along with +// the vehicles' own main reservoirs feeding the pipe in the same step, the pipes of the middle vehicles of a +// multiple unit or of locomotives in multiple traction kept jumping 0.8 bar to and fro between the steps +// ************************************************************************************************* +int TMoverParameters::ScndPipeCouplersSubsteps(double const dt) const +{ + return hose_substeps(*this, main_reservoir_pipe, dt); +} + +// ************************************************************************************************* +// the air exchange through the brake and the main reservoir hoses of the vehicles which stepped their pipes +// (UpdatePipePressure(), UpdateScndPipePressure()) since the last call, each pipe in its own sub-steps +// ************************************************************************************************* +void TMoverParameters::UpdatePipeCouplers(std::vector const &Vehicles, double const dt) +{ + exchange_through_hoses(Vehicles, brake_pipe, dt); + exchange_through_hoses(Vehicles, main_reservoir_pipe, dt); +} + +bool TMoverParameters::UpdateStopBrakeRelease(double const Demand, double const Dt) +{ + if (Demand <= 0.0) + { + StopBrakeReleaseTimer = 0.0; + return false; + } + // the step the demand rises above 0 is time 0 of it, so without the delay the brake lets go at once, as it always did + auto const released{StopBrakeReleaseTimer >= StopBrakeReleaseDelay}; + StopBrakeReleaseTimer += Dt; + return released; +} diff --git a/physics/mover/securitysystem.cpp b/physics/mover/securitysystem.cpp new file mode 100644 index 000000000..bb3726029 --- /dev/null +++ b/physics/mover/securitysystem.cpp @@ -0,0 +1,298 @@ +/* +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 security system (vigilance, cab signalling, radio-stop) + +#include "stdafx.h" +#include "physics/mover.h" +#include "vehicle/DynObj.h" +#include "physics/oerlikonest.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/Timer.h" +#include "utilities/parser.h" +#include "simulation/simulation.h" +#include "vehicle/fieldshunting.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "physics/mover/internal.h" + + +void TSecuritySystem::set_enabled(bool e) +{ + if (vigilance_enabled || cabsignal_enabled || radiostop_enabled) + enabled = e; + if (CabDependent) + cabactive = 0; +} + +void TSecuritySystem::acknowledge_press() +{ + pressed = true; + + if (vigilance_timer > AwareDelay) + { + alert_timer = 0.0; + vigilance_timer = 0.0; + return; + } + vigilance_timer = 0.0; + + if (!separate_acknowledge && cabsignal_active && !cabsignal_lock) + { + cabsignal_active = false; + alert_timer = 0.0; + } +} + +void TSecuritySystem::acknowledge_release() +{ + pressed = false; + + if (press_timer > MaxHoldTime) + alert_timer = 0.0; + press_timer = 0.0; +} + +void TSecuritySystem::cabsignal_reset() +{ + if (cabsignal_active && !cabsignal_lock) + { + cabsignal_active = false; + alert_timer = 0.0; + } +} + +void TSecuritySystem::update(double dt, double vel, bool pwr, int cab) +{ + if (!enabled || !pwr || DebugModeFlag) + { + power = pwr; + cabsignal_active = false; + vigilance_timer = 0.0; + alert_timer = 0.0; + press_timer = 0.0; + return; + } + + bool just_powered_on = !power && pwr; + bool just_activated = CabDependent && cabactive != cab; + + /* enabling battery */ + if (cabsignal_enabled && (just_powered_on || just_activated)) + { + cabsignal_active = true; + alert_timer = SoundSignalDelay; + } + + power = pwr; + velocity = vel; + cabactive = cab; + + if (vigilance_suspended) + { + // the vigilance device is switched off: no time counts towards a new alarm, of the alerter or of the button held + // too long. an alarm already on, with the emergency braking it leads to, stays until it's acknowledged as usual + if (vigilance_timer <= AwareDelay) + vigilance_timer = 0.0; + if (press_timer <= MaxHoldTime) + press_timer = 0.0; + } + else + { + if (vigilance_enabled && velocity > AwareMinSpeed) + vigilance_timer += dt; + + if (pressed && (!is_sifa || velocity > AwareMinSpeed)) + press_timer += dt; + } + + if (vigilance_timer > AwareDelay || press_timer > MaxHoldTime || cabsignal_active) + alert_timer += dt; +} + +void TSecuritySystem::set_cabsignal() +{ + if (cabsignal_enabled && power) + cabsignal_active = true; +} + +bool TSecuritySystem::has_separate_acknowledge() const +{ + return separate_acknowledge; +} + +bool TSecuritySystem::is_blinking() const +{ + if (!power) + return false; + + return alert_timer > 0.0; +} + +bool TSecuritySystem::is_vigilance_blinking() const +{ + if (!power) + return false; + + return press_timer > MaxHoldTime || vigilance_timer > AwareDelay; +} + +bool TSecuritySystem::is_cabsignal_blinking() const +{ + if (!power) + return false; + + return cabsignal_active; +} + +bool TSecuritySystem::is_beeping() const +{ + if (!power) + return false; + + return alert_timer > SoundSignalDelay && (!separate_acknowledge || is_vigilance_blinking()); +} + +bool TSecuritySystem::is_cabsignal_beeping() const +{ + if (!power) + return false; + + return alert_timer > SoundSignalDelay && is_cabsignal_blinking(); +} + +bool TSecuritySystem::is_braking() const +{ + if (!power && enabled) + return true; + + return alert_timer > SoundSignalDelay + EmergencyBrakeDelay; +} + +bool TSecuritySystem::radiostop_available() const +{ + return radiostop_enabled; +} + +void TSecuritySystem::set_cabsignal_lock(bool v) +{ + cabsignal_lock = v; +} + +void TSecuritySystem::set_shunt_mode(bool const State) +{ + vigilance_suspended = State && AwareOffInShuntMode; +} + +bool TSecuritySystem::is_engine_blocked() const +{ + if (!is_sifa) + return false; + + return velocity < AwareMinSpeed && pressed; +} + +void TSecuritySystem::load(std::string const &line, double Vmax) +{ + std::string awaresystem = extract_value("AwareSystem", line); + if (awaresystem.find("Active") != std::string::npos) + vigilance_enabled = true; + if (awaresystem.find("CabSignal") != std::string::npos) + cabsignal_enabled = true; + if (awaresystem.find("Sifa") != std::string::npos) + is_sifa = true; + if (awaresystem.find("SeparateAcknowledge") != std::string::npos) + separate_acknowledge = true; + + extract_value(AwareDelay, "AwareDelay", line, ""); + AwareMinSpeed = 0.1 * Vmax; // domyślnie 10% Vmax + extract_value(AwareMinSpeed, "AwareMinSpeed", line, ""); + extract_value(SoundSignalDelay, "SoundSignalDelay", line, ""); + extract_value(EmergencyBrakeDelay, "EmergencyBrakeDelay", line, ""); + extract_value(MaxHoldTime, "MaxHoldTime", line, ""); + extract_value(radiostop_enabled, "RadioStop", line, ""); + extract_value(MagnetLocation, "MagnetLocation", line, ""); + extract_value(CabDependent, "CabDependent", line, ""); + extract_value(AwareOffInShuntMode, "AwareOffInShuntMode", line, ""); +} + +// ***************************************************************************** +// Q: 20160710 +// zbicie czuwaka / SHP +// ***************************************************************************** +// hunter-091012: rozbicie alarmow, dodanie testu czuwaka +void TMoverParameters::SecuritySystemReset(void) // zbijanie czuwaka/SHP +{ + // reset all, used by AI + SecuritySystem.acknowledge_press(); + SecuritySystem.acknowledge_release(); + SecuritySystem.cabsignal_reset(); +} + +// ************************************************************************************************* +// Q: 20160711 +// sprawdzanie stanu CA/SHP +// ************************************************************************************************* +void TMoverParameters::SecuritySystemCheck(double dt) +{ + bool isPower = Power24vIsAvailable || Power110vIsAvailable; + // the shunt mode of the SM42 switches its vigilance device (CA) off, on the vehicles with AwareOffInShuntMode=Yes (eu07/maszyna#457) + SecuritySystem.set_shunt_mode(ShuntMode); + SecuritySystem.update(dt, Vel, isPower, CabActive); + + if (!Battery || !Radio || !RadioFuse) + { // wyłączenie baterii deaktywuje sprzęt + RadiostopSwitch(false); + } +} + +// ************************************************************************************************* +// Q: 20160711 +// włączenie / wyłączenie hamowania awaryjnego +// ************************************************************************************************* +bool TMoverParameters::RadiostopSwitch(bool Switch) +{ + bool EBS; + if (BrakeSystem != TBrakeSystem::Individual && BrakeCtrlPosNo > 0) + { + + if (true == Switch && false == RadioStopFlag) + { + RadioStopFlag = Switch; + EBS = true; + } + else + { + if (Switch == false && std::abs(V) < 0.1) + { + // odblokowanie hamulca bezpieczenistwa tylko po zatrzymaniu + RadioStopFlag = Switch; + EBS = true; + } + else + { + EBS = false; + } + } + } + else + { + // nie ma hamulca bezpieczenstwa gdy nie ma hamulca zesp. + EBS = false; + } + + return EBS; +} diff --git a/physics/mover/setup.cpp b/physics/mover/setup.cpp new file mode 100644 index 000000000..18a3abcea --- /dev/null +++ b/physics/mover/setup.cpp @@ -0,0 +1,471 @@ +/* +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/. +*/ + +// setting the vehicle up after reading its definition: the checks, the brake valves, the handles and the pipes + +#include "stdafx.h" +#include "physics/mover.h" +#include "vehicle/DynObj.h" +#include "physics/oerlikonest.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/Timer.h" +#include "utilities/parser.h" +#include "simulation/simulation.h" +#include "vehicle/fieldshunting.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "physics/mover/internal.h" + + +// ************************************************************************************************* +// Q: 20160717 +// ************************************************************************************************* + +bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) +{ + WriteLog("check locomotive parameters..."); + bool OK = true; + + AutoRelayFlag = AutoRelayType == 1; + + if (NominalBatteryVoltage == 0.0) + { + BatteryStart = start_t::disabled; + } + + Sand = SandCapacity; + + // NOTE: for diesel-powered vehicles we automatically convert legacy "main" power source to more accurate "engine" + if (CompressorPower == 0 && (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric)) + { + CompressorPower = 3; + } + + // for these engine types secondary controller positions index MotorParam table + if ((EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric) && + ScndCtrlPosNo > MotorParametersArraySize) + { + WriteLog("SCPN=" + std::to_string(ScndCtrlPosNo) + " exceeds motor parameter table size, limited to " + std::to_string(MotorParametersArraySize)); + ScndCtrlPosNo = MotorParametersArraySize; + } + + // WriteLog("aa = " + AxleArangement + " " + std::string( Pos("o", AxleArangement)) ); + + if (contains(AxleArangement, "o") && EngineType == TEngineType::ElectricSeriesMotor) + { + // test poprawnosci ilosci osi indywidualnie napedzanych + OK = RList[1].Bn * RList[1].Mn == NPoweredAxles; + // WriteLogSS("aa ok", BoolToYN(OK)); + } + + if (BrakeSystem == TBrakeSystem::Individual && BrakeSubsystem != TBrakeSubSystem::ss_None) + OK = false; //! + + if (BrakeVVolume == 0 && MaxBrakePress[3] > 0 && BrakeSystem != TBrakeSystem::Individual) + { + BrakeVVolume = MaxBrakePress[3] / (5.0 - MaxBrakePress[3]) * (BrakeCylRadius * BrakeCylRadius * BrakeCylDist * BrakeCylNo * M_PI) * 1000; + } + if (BrakeVVolume == 0.0) + { + BrakeVVolume = 0.01; + } + // WriteLog("BVV = " + FloatToStr(BrakeVVolume)); + + CreateBrakeValve(); + + CreateBrakeHandles(); + + CreateBrakePipes(); + + if (LightsPosNo > 0) + LightsPos = LightsDefPos; + + // set default wiper switch position + wiperSwitchPos = WiperDefaultPos; + + if (CompressorListPosNo > 0) + CompressorListPos = CompressorListDefPos; + + // the genset of a dual-mode vehicle is a second source of the traction circuit of an induction motor vehicle + if (Genset.fitted() && (EngineType != TEngineType::ElectricInductionMotor || EnginePowerSource.SourceType != TPowerSource::CurrentCollector)) + { + WriteLog("GensetPower ignored: a genset works only with EngineType=ElectricInductionMotor and EnginePower=CurrentCollector"); + Genset = genset_device{}; + } + + // NOTE: legacy compatibility behaviour for vehicles without defined heating power source + if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector && HeatingPowerSource.SourceType == TPowerSource::NotDefined) + { + HeatingPowerSource.SourceType = TPowerSource::Main; + } + if (HeatingPowerSource.SourceType == TPowerSource::NotDefined && HeatingPower > 0) + { + HeatingPowerSource.SourceType = TPowerSource::PowerCable; + HeatingPowerSource.PowerType = TPowerType::ElectricPower; + } + + // checking ready flag + // to dac potem do init + if (ReadyFlag) // gotowy do drogi + { + SetReadyToDepart(); + } + else + { // zahamowany} + SetBraked(); + } + + ActFlowSpeed = 0.0; + BrakeCtrlPosR = BrakeCtrlPos; + + if (BrakeLocHandle == TBrakeHandle::Knorr) + LocalBrakePosA = 0.5; + + Pipe->CreatePress(PipePress); + Pipe2->CreatePress(ScndPipePress); + Pipe->Act(); + Pipe2->Act(); + + EqvtPipePress = PipePress; + + Handle->Init(PipePress); + + ComputeConstans(); + + if (LoadFlag > 0) + { + + if (LoadAmount < MaxLoad * 0.45) + { + IncBrakeMult(); + IncBrakeMult(); + DecBrakeMult(); // TODO: przeinesiono do mover.cpp + if (LoadAmount < MaxLoad * 0.35) + DecBrakeMult(); + } + else + { + IncBrakeMult(); // TODO: przeinesiono do mover.cpp + if (LoadAmount >= MaxLoad * 0.55) + IncBrakeMult(); + } + } + + // taki mini automat - powinno byc ladnie dobrze :) + BrakeDelayFlag = bdelay_P; + if (TestFlag(BrakeDelays, bdelay_G) && !TestFlag(BrakeDelays, bdelay_R)) + BrakeDelayFlag = bdelay_G; + if (TestFlag(BrakeDelays, bdelay_R) && !TestFlag(BrakeDelays, bdelay_G)) + BrakeDelayFlag = bdelay_R; + /* + // disabled, as test mode is used in specific situations and not really a default + if (BrakeOpModes & bom_PS) + BrakeOpModeFlag = bom_PS; + else + */ + BrakeOpModeFlag = bom_PN; + + // yB: jesli pojazdy nie maja zadeklarowanych czasow, to wsadz z przepisow +-16,(6)% + std::array const DefBrakeTable{15, 4, 25, 25, 13, 3, 12, 2}; + + for (int b = 1; b < 4; b++) + { + if (BrakeDelay[b] == 0) + BrakeDelay[b] = DefBrakeTable[b]; + BrakeDelay[b] = BrakeDelay[b] * (2.5 + Random(0.0, 0.2)) / 3.0; + } + + Hamulec->Init(PipePress, HighPipePress, LowPipePress, BrakePress, BrakeDelayFlag); + /* + ScndPipePress = Compressor; + */ + // WriteLogSS("OK=", BoolTo10(OK)); + // WriteLog(""); + + if (EIMCtrlType == 3) + { + for (auto idx = 0; idx < MainCtrlPosNo; ++idx) + { + if (UniCtrlList[idx].MaxCtrlVal > 0.0) + { + UniCtrlNoPowerPos = std::max(0, idx - 1); + break; + } + } + } + + // security system + // by default place the magnet in the vehicle centre + if (SecuritySystem.MagnetLocation == 0) + { + SecuritySystem.MagnetLocation = Dim.L / 2 - 0.5; + } + SecuritySystem.MagnetLocation = safe_clamp(SecuritySystem.MagnetLocation, 0.0, Dim.L); + + return OK; +} + +// the distributor valve of the vehicle's kind +void TMoverParameters::CreateBrakeValve() +{ + switch (BrakeValve) + { + case TBrakeValve::W: + case TBrakeValve::K: + { + WriteLog("XBT W, K"); + Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); + if (MBPM < 2) // jesli przystawka wazaca + Hamulec->SetLP(0, MaxBrakePress[3], 0); + else + Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]); + break; + } + case TBrakeValve::KE: + { + WriteLog("XBT WKE"); + Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); + Hamulec->SetRM(RapidMult); + if (MBPM < 2) // jesli przystawka wazaca + Hamulec->SetLP(0, MaxBrakePress[3], 0); + else + Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]); + break; + } + case TBrakeValve::NESt3: + case TBrakeValve::ESt3: + case TBrakeValve::ESt3AL2: + case TBrakeValve::ESt4: + { + WriteLog("XBT NESt3, ESt3, ESt3AL2, ESt4"); + Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); + static_cast(Hamulec.get())->SetSize(BrakeValveSize, BrakeValveParams); + if (MBPM < 2) // jesli przystawka wazaca + Hamulec->SetLP(0, MaxBrakePress[3], 0); + else + Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]); + break; + } + case TBrakeValve::LSt: + { + WriteLog("XBT LSt"); + Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); + Hamulec->SetRM(RapidMult); + break; + } + case TBrakeValve::EStED: + { + WriteLog("XBT EStED"); + Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); + Hamulec->SetRM(RapidMult); + if (MBPM < 2) + { + // jesli przystawka wazaca + Hamulec->SetLP(0, MaxBrakePress[3], 0); + } + else + { + Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]); + } + break; + } + case TBrakeValve::EP2: + { + WriteLog("XBT EP2"); + Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); + Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]); + break; + } + case TBrakeValve::EP1: + { + WriteLog("XBT EP1"); + Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); + Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]); + Hamulec->SetRM(RapidMult); + break; + } + case TBrakeValve::CV1: + { + WriteLog("XBT CV1"); + Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); + break; + } + case TBrakeValve::CV1_L_TR: + { + WriteLog("XBT CV1_L_T"); + Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); + break; + } + default: + Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); + } + + Hamulec->SetASBP(MaxBrakePress[4]); + Hamulec->SetRV(RapidVel); +} + +// the driver's handle and the local brake handle of the vehicle's kinds +void TMoverParameters::CreateBrakeHandles() +{ + switch (BrakeHandle) + { + using enum TBrakeHandle; + case FV4a: + Handle = std::make_shared(); + break; + case MHZ_EN57: + case MHZ_K8P: + Handle = std::make_shared(); + break; + case FVel6: + Handle = std::make_shared(); + break; + case FVE408: + Handle = std::make_shared(); + break; + case testH: + Handle = std::make_shared(); + break; + case M394: + Handle = std::make_shared(); + break; + case Knorr: + Handle = std::make_shared(); + break; + case St113: + Handle = std::make_shared(); + break; + case MHZ_K5P: + Handle = std::make_shared(); + break; + case MHZ_6P: + Handle = std::make_shared(); + break; + default: + Handle = std::make_shared(); + } + Handle->SetParams(Handle_AutomaticOverload, Handle_ManualOverload, Handle_GenericDoubleParameter1, Handle_GenericDoubleParameter2, Handle_OverloadMaxPressure, Handle_OverloadPressureDecrease); + + switch (BrakeLocHandle) + { + case TBrakeHandle::FD1: + { + LocHandle = std::make_shared(); + LocHandle->Init(MaxBrakePress[0]); + if (TrainType == train_type::emu) + { + + dynamic_cast(LocHandle.get())->SetSpeed(3.5); + } + break; + } + case TBrakeHandle::Knorr: + { + LocHandle = std::make_shared(); + LocHandle->Init(MaxBrakePress[0]); + break; + } + default: + LocHandle = std::make_shared(); + } +} + +// the brake pipe, the main pipe and the spring brake's cylinder +void TMoverParameters::CreateBrakePipes() +{ + if (true == TestFlag(BrakeDelays, bdelay_G) && (false == TestFlag(BrakeDelays, bdelay_R) || Power > 1.0)) // ustalanie srednicy przewodu glownego (lokomotywa lub napędowy + Spg = 0.792; + else + Spg = 0.507; + // WriteLog("SPG = " + FloatToStr(Spg)); + + Pipe = std::make_shared(); + Pipe2 = std::make_shared(); // zabezpieczenie, bo sie PG wywala... :( + Pipe->CreateCap((std::max(Dim.L, 14.0) + 0.5) * Spg * 1); // dlugosc x przekroj x odejscia i takie tam + Pipe2->CreateCap((std::max(Dim.L, 14.0) + 0.5) * Spg * 1); + if (!SpringBrake.Cylinder) + { + SpringBrake.Cylinder = std::make_shared(); + SpringBrake.Cylinder->CreateCap(1); + } +} + +// the pressure of the main pipe at the start: the main reservoir's, or HosePressure fed through a main hose, or none +double TMoverParameters::InitialScndPipePress(double const HosePressure) const +{ + if (VeselVolume > 0.0) + { + return CompressedVolume / VeselVolume; + } + if ((Couplers[end::front].AllowedFlag & coupling::mainhose) != 0 || (Couplers[end::rear].AllowedFlag & coupling::mainhose) != 0) + { + return HosePressure; + } + return 0.0; +} + +// the air and the controls of a vehicle ready to depart +void TMoverParameters::SetReadyToDepart() +{ + WriteLog("Ready to depart"); + CompressedVolume = VeselVolume * MinCompressor * 9.8 / 10.0; + ScndPipePress = InitialScndPipePress(5.0); + PipePress = CntrlPipePress; + BrakePress = 0.0; + LocalBrakePosA = 0.0; + if (CabActive == 0) + BrakeCtrlPos = static_cast(Handle->GetPos(bh_NP)); + else + BrakeCtrlPos = static_cast(Handle->GetPos(bh_RP)); + /* + // NOTE: disabled and left up to the driver, if there's any + MainSwitch( false ); + PantFront( true ); + PantRear( true ); + MainSwitch( true ); + */ + DirActive = 0; // Dir; //nastawnik kierunkowy - musi być ustawiane osobno! + DirAbsolute = DirActive * CabActive; // kierunek jazdy względem sprzęgów + LimPipePress = CntrlPipePress; + + Battery = BatteryStart != start_t::disabled; +} + +// the air and the brakes of a vehicle standing braked +void TMoverParameters::SetBraked() +{ + WriteLog("Braked"); + Volume = BrakeVVolume * MaxBrakePress[3]; + CompressedVolume = VeselVolume * MinCompressor * 0.55; + /* + ScndPipePress = 5.1; + */ + ScndPipePress = InitialScndPipePress(5.1); + PipePress = LowPipePress; + PipeBrakePress = MaxBrakePress[3] * 0.5; + BrakePress = MaxBrakePress[3] * 0.5; + LocalBrakePosA = 0.0; + BrakeCtrlPos = static_cast(Handle->GetPos(bh_NP)); + LimPipePress = LowPipePress; + if (LocalBrake == TLocalBrake::ManualBrake || MBrake == true) + { + IncManualBrakeLevel(ManualBrakePosNo); + } + if (SpringBrake.MaxBrakeForce > 0.0) + { + SpringBrake.Activate = true; + } +} diff --git a/physics/mover/traction.cpp b/physics/mover/traction.cpp new file mode 100644 index 000000000..ceb1d1ec3 --- /dev/null +++ b/physics/mover/traction.cpp @@ -0,0 +1,1881 @@ +/* +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 traction motors and their forces for each kind of drive, the relays, the fuses, the dynamic brake + +#include "stdafx.h" +#include "physics/mover.h" +#include "vehicle/DynObj.h" +#include "physics/oerlikonest.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/Timer.h" +#include "utilities/parser.h" +#include "simulation/simulation.h" +#include "vehicle/fieldshunting.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "physics/mover/internal.h" + + +double TableInterpolation(std::map &Map, double Parameter) +{ + if (Map.empty()) + return 0.0; + if (Map.size() == 1) + return Map.begin()->second; + + auto lower = Map.lower_bound(Parameter); + auto upper = lower; + + if (lower != Map.begin()) + lower--; + else + upper++; + + if (upper == Map.end()) + { + lower--; + upper--; + } + double ratio = (upper->second - lower->second) / (upper->first - lower->first); + return lower->second + (Parameter - lower->first) * ratio; +} + +// ************************************************************************************************* +// Q: 20160716 +// Obliczanie natężenie prądu w silnikach +// ************************************************************************************************* +double TMoverParameters::Current(double n, double U) +{ + // wazna funkcja - liczy prad plynacy przez silniki polaczone szeregowo lub rownolegle + // w zaleznosci od polozenia nastawnikow MainCtrl i ScndCtrl oraz predkosci obrotowej n + // a takze wywala bezpiecznik nadmiarowy gdy za duzy prad lub za male napiecie + // jest takze mozliwosc uszkodzenia silnika wskutek nietypowych parametrow + + double R; + double MotorCurrent; + double Mn; // przujmuje int, ale dla poprawnosci obliczeń + double Bn; + + UpdateSeriesMotorDynamicBrakeFlag(); + + ResistorsFlag = RList[MainCtrlActualPos].R > 0.01; // and (!DelayCtrlFlag) + ResistorsFlag = ResistorsFlag || (DynamicBrakeFlag == true && DynamicBrakeType == dbrake_automatic); + + if (TrainType == train_type::et22 && DelayCtrlFlag && MainCtrlActualPos > 1) + Bn = 1.0 - 1.0 / RList[MainCtrlActualPos].Bn; + else + Bn = 1; // to jest wykonywane dla EU07 + + R = RList[MainCtrlActualPos].R * Bn + CircuitRes; + + if (TrainType != train_type::emu || Imin != IminLo || false == ScndS) + { + // yBARC - boczniki na szeregu poprawnie + Mn = RList[MainCtrlActualPos].Mn; // to jest wykonywane dla EU07 + } + else + { + Mn = RList[MainCtrlActualPos].Mn * RList[MainCtrlActualPos].Bn; + if (RList[MainCtrlActualPos].Bn > 1) + { + R = CircuitRes; + } + } + + if (DynamicBrakeFlag && !FuseFlag && DynamicBrakeType == dbrake_automatic && Power110vIsAvailable && Mains) // hamowanie EP09 //TUHEX + { + // TODO: zrobic bardziej uniwersalne nie tylko dla EP09 + MotorCurrent = -std::max(motor_param(0).fi * (Vadd / (Vadd + motor_param(0).Isat) - motor_param(0).fi0), 0.) * n * 2.0 / DynamicBrakeRes; + } + else if (RList[MainCtrlActualPos].Bn == 0 || false == StLinFlag) + { + // wylaczone + MotorCurrent = 0; + } + else + { // wlaczone... + MotorCurrent = SeriesMotorCurrent(n, U, R, Mn); + } + // writepaslog("MotorCurrent ", FloatToStr(MotorCurrent)); + + if (DynamicBrakeType == dbrake_switch && (BrakePress > 2.0 || PipePress < 3.6)) + { + Im = 0; + // Im:=0; + Itot = 0; + } + else + Im = MotorCurrent; + + EnginePower = abs(Itot) * (1 + RList[MainCtrlActualPos].Mn) * abs(U) / 1000.0; + + MotorFailuresCheck(n); + + return Im; +} + +// the automatic dynamic brake of the series motors (EP09, the units) on or off, and the distributor told of it +void TMoverParameters::UpdateSeriesMotorDynamicBrakeFlag() +{ + // i dzialanie hamulca ED w EP09 + if (DynamicBrakeType == dbrake_automatic && TrainType != train_type::emu) + { + if ((Hamulec->GetEDBCP() < 0.25 && Vadd < 1) || BrakePress > 2.1) + DynamicBrakeFlag = false; + else if (BrakePress > 0.25 && Hamulec->GetEDBCP() > 0.25) + DynamicBrakeFlag = true; + DynamicBrakeFlag = DynamicBrakeFlag && Power110vIsAvailable; + } + if (DynamicBrakeType == dbrake_automatic && TrainType == train_type::emu) + { + DynamicBrakeFlag = Power110vIsAvailable && (TUHEX_Active || Vadd > TUHEX_MinIw) && DynamicBrakeEMUStatus; + } + + // wylacznik cisnieniowy yBARC - to jest chyba niepotrzebne tutaj Q: no to usuwam... + + // BrakeSubsystem = ss_LSt; + // if (BrakeSubsystem == ss_LSt) WriteLog("LSt"); + // if (BrakeSubsystem == ss_LSt) // zrobiona funkcja virtualna + if (DynamicBrakeFlag) + { + Hamulec->SetED(abs(Im / 350)); // hamulec ED na EP09 dziala az do zatrzymania lokomotywy + //- WriteLog("A"); + } + else + { + Hamulec->SetED(0); + //- WriteLog("B"); + } +} + +// the current of the series motors connected, at the revolutions n and the voltage U, through the resistance R of +// Mn motors in series +double TMoverParameters::SeriesMotorCurrent(double const n, double const U, double const R, double const Mn) const +{ + double MotorCurrent{0.0}; + double Rz; + int SP = ScndCtrlActualPos; + + if (ScndCtrlActualPos < 255) // tak smiesznie bede wylaczal + { + if (ScndInMain && RList[MainCtrlActualPos].ScndAct != 255) + { + SP = RList[MainCtrlActualPos].ScndAct; + } + + Rz = Mn * WindingRes + R; + + if (DynamicBrakeFlag) // hamowanie + { + // if DynamicBrakeType<>dbrake_automatic then + // MotorCurrent:=-fi*n/Rz {hamowanie silnikiem na oporach rozruchowych} + /* begin + U:=0; + Isf:=Isat; + Delta:=SQR(Isf*Rz+Mn*fi*n-U)+4*U*Isf*Rz; + MotorCurrent:=(U-Isf*Rz-Mn*fi*n+SQRT(Delta))/(2*Rz) + end*/ + // only the ET42's switched brake brakes on the starting resistors, otherwise the current is cut off (0) + if (DynamicBrakeType == dbrake_switch && TrainType == train_type::et42) + { // z Megapacka + Rz = WindingRes + R; + MotorCurrent = -motor_param(SP).fi * n / Rz; //{hamowanie silnikiem na oporach rozruchowych} + } + } + else + { + MotorCurrent = SeriesMotorDrivingCurrent(n, U, Rz, Mn, SP); + } // else DBF + + } // 255 + else + MotorCurrent = 0; + return MotorCurrent; +} + +// the current of the series motors driving, at the revolutions n, the voltage U and the resistance Rz of Mn motors in +// series, by the motor parameters of the shunt field SP +double TMoverParameters::SeriesMotorDrivingCurrent(double const n, double const U, double const Rz, double const Mn, int const SP) const +{ + double MotorCurrent; + double Delta; + double Isf; + double U1; // napiecie z korekta + U1 = U + Mn * n * motor_param(SP).fi0 * motor_param(SP).fi; + // writepaslog("U1 ", FloatToStr(U1)); + // writepaslog("Isat ", FloatToStr(MotorParam[SP].Isat)); + // writepaslog("fi ", FloatToStr(MotorParam[SP].fi)); + Isf = Sign(U1) * motor_param(SP).Isat; + // writepaslog("Isf ", FloatToStr(Isf)); + Delta = square(Isf * Rz + Mn * motor_param(SP).fi * n - U1) + 4.0 * U1 * Isf * Rz; // 105 * 1.67 + Mn * 140.9 * 20.532 - U1 + // DeltaQ = Isf * Rz + Mn * MotorParam[SP].fi * n - U1 + 4 * U1 * Isf * Rz; + // writepaslog("Delta ", FloatToStr(Delta)); + // writepaslog("DeltaQ ", FloatToStr(DeltaQ)); + // writepaslog("U ", FloatToStr(U)); + if (MainCircuitPowered()) + { + if (U > 0) + MotorCurrent = (U1 - Isf * Rz - Mn * motor_param(SP).fi * n + std::sqrt(Delta)) / (2.0 * Rz); + else + MotorCurrent = (U1 - Isf * Rz - Mn * motor_param(SP).fi * n - std::sqrt(Delta)) / (2.0 * Rz); + } + else + MotorCurrent = 0; + return MotorCurrent; +} + +// the line breaker opened, and the motors damaged, by too high revolutions or current +void TMoverParameters::MotorFailuresCheck(double const n) +{ + double MotorCurrent; + // awarie + MotorCurrent = abs(Im); // zmienna pomocnicza + + if (MotorCurrent > 0) + { + if (FuzzyLogic(abs(n), nmax * 1.1, p_elengproblem) && MainSwitch(false)) + EventFlag = true; /*zbyt duze obroty - wywalanie wskutek ognia okreznego*/ + if (TestFlag(DamageFlag, dtrain_engine) && FuzzyLogic(MotorCurrent, (double)ImaxLo / 10.0, p_elengproblem) && MainSwitch(false)) + EventFlag = true; /*uszkodzony silnik (uplywy)*/ + /* or FuzzyLogic(Abs(U/Mn),2*NominalVoltage,1)) then */ /*poprawic potem*/ + if ((FuzzyLogic(abs(Im), Imax * 2, p_elengproblem) || FuzzyLogic(abs(n), nmax * 1.11, p_elengproblem)) && SetFlag(DamageFlag, dtrain_engine)) + EventFlag = true; + /*! dorobic grzanie oporow rozruchowych i silnika*/ + } +} + +// rozruch wysoki (true) albo niski (false) +bool TMoverParameters::CurrentSwitch(bool const State) +{ + // TBD, TODO: split off shunt mode toggle into a separate command? It doesn't make much sense to have these two together like that + // the diesels with a shunt mode have no motor overload relay threshold to switch, the switch sets their shunt mode alone. + // MaxCurrentSwitch() takes any change of the setting, so asked first it took the first move of the switch (eu07/maszyna#497) + if (true == ShuntModeAllow && (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric)) + { + // dla 2Ls150 przed ustawieniem kierunku, for SM42/SP42 at the controller's zero position + if (EngineType == TEngineType::DieselEngine ? DirActive != 0 : false == IsMainCtrlNoPowerPos()) + { + return false; + } + ShuntMode = State; + return true; + } + + if (MaxCurrentSwitch(State)) + { + if (TrainType != train_type::emu) + { + MinCurrentSwitch(State); + } + return true; + } + + return false; +}; + +bool TMoverParameters::IsMotorOverloadRelayHighThresholdOn() const +{ + + return ImaxHi > ImaxLo && Imax > ImaxLo; +} + +double TMoverParameters::ShowEngineRotation(int VehN) const +{ // Zwraca wartość prędkości obrotowej silnika wybranego pojazdu. Do 3 pojazdów (3×SN61). + int b; + switch (VehN) + { // numer obrotomierza + case 1: + return std::abs(enrot); + case 2: + for (b = 0; b <= 1; ++b) + if (TestFlag(Couplers[b].CouplingFlag, coupling::control) && Couplers[b].Connected->Power > 0.01) + return fabs(Couplers[b].Connected->enrot); + break; + case 3: // to nie uwzględnia ewentualnego odwrócenia pojazdu w środku + for (b = 0; b <= 1; ++b) + if (TestFlag(Couplers[b].CouplingFlag, coupling::control) && Couplers[b].Connected->Power > 0.01 && TestFlag(Couplers[b].Connected->Couplers[b].CouplingFlag, coupling::control) && Couplers[b].Connected->Couplers[b].Connected->Power > 0.01) + return fabs(Couplers[b].Connected->Couplers[b].Connected->enrot); + break; + default: + break; + } + return 0.0; +}; + +void TMoverParameters::MotorBlowersCheck(double const Timestep) +{ + // activation check + for (auto &blower : MotorBlowers) + { + auto disable = blower.is_disabled; + auto const start{(Vel >= blower.min_start_velocity && std::abs(Im) > 0.5)}; + auto const stop{(Vel < 0.5 && std::abs(Im) < 0.5)}; + if (blower.min_start_velocity >= 0) + { + if (stop) + { + blower.stop_timer += static_cast(Timestep); + if (blower.stop_timer > blower.sustain_time) + { + disable = true; + } + } + else if (start) + { + blower.stop_timer = 0; + } + else + { + disable |= !blower.is_active; + } + } + blower.is_active = + // TODO: bind properly power source when ld is in place + MotorBlowerPowerIsAvailable(blower) // power source + // breaker condition disabled until it's implemented in the class data + // && ( true == blower.breaker ) + && false == disable && + (true == blower.is_active || (blower.stop_timer == 0.f // HACK: will be true for blower with exceeded start_velocity, and for one without start_velocity + && (blower.start_type == start_t::manual ? blower.is_enabled : true))); + } + // update + for (auto &fan : MotorBlowers) + { + + auto const revolutionstarget{(fan.is_active ? (fan.speed > 0.f ? fan.speed * static_cast(enrot) * 60 : fan.speed * -1) : 0.f)}; + + if (std::abs(fan.revolutions - revolutionstarget) < 0.01f) + { + fan.revolutions = revolutionstarget; + continue; + } + if (revolutionstarget > 0.f) + { + auto const speedincreasecap{std::max(50.f, fan.speed * 0.05f * -1)}; // 5% of fixed revolution speed, or 50 + fan.revolutions += static_cast(std::clamp(revolutionstarget - fan.revolutions, speedincreasecap * -2, speedincreasecap) * Timestep); + } + else + { + fan.revolutions *= static_cast(std::max(0.0, 1.0 - Timestep)); + } + } +} + +bool TMoverParameters::MotorBlowerPowerIsAvailable(cooling_fan const &Blower) const +{ + switch (Blower.start_type) + { + case start_t::battery: + return Power24vIsAvailable; + case start_t::converter: + return Power110vIsAvailable; + default: + return MainCircuitPowered(); + } +} + +double TMoverParameters::ShowCurrent(int AmpN) const +{ // Odczyt poboru prądu na podanym amperomierzu + switch (EngineType) + { + case TEngineType::ElectricInductionMotor: + switch (AmpN) + { // do asynchronicznych + case 1: + return WindingRes * Mm / Vadd; + case 2: + return eimv_pr * WindingRes; + default: + return ShowCurrentP(AmpN); // T_MoverParameters:: + } + break; + case TEngineType::DieselElectric: + return fabs(Im); + break; + default: + return ShowCurrentP(AmpN); // T_MoverParameters:: + } +}; + +bool TMoverParameters::MotorBlowersSwitch(bool State, end const Side, range_t const Notify) +{ + + auto &fan{MotorBlowers[Side]}; + + if (fan.start_type != start_t::manual && fan.start_type != start_t::manualwithautofallback) + { + // automatic device ignores 'manual' state commands + return false; + } + + bool const initialstate{fan.is_enabled}; + + fan.is_enabled = State; + + if (Notify != range_t::local) + { + SendCtrlToNext(Side == end::front ? "MotorBlowersFrontSwitch" : "MotorBlowersRearSwitch", fan.is_enabled ? 1 : 0, CabActive, + Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return fan.is_enabled != initialstate; +} + +bool TMoverParameters::MotorBlowersSwitchOff(bool State, end const Side, range_t const Notify) +{ + + auto &fan{MotorBlowers[Side]}; + + if (fan.start_type != start_t::manual && fan.start_type != start_t::manualwithautofallback) + { + // automatic device ignores 'manual' state commands + return false; + } + + bool const initialstate{fan.is_disabled}; + + fan.is_disabled = State; + + if (Notify != range_t::local) + { + SendCtrlToNext(Side == end::front ? "MotorBlowersFrontSwitchOff" : "MotorBlowersRearSwitchOff", fan.is_disabled ? 1 : 0, CabActive, + Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return fan.is_disabled != initialstate; +} + +// the traction selector of a dual-mode vehicle: moves only with the line breaker open, and only where a genset is +bool TMoverParameters::TractionModeSwitch(traction_mode const Mode, range_t const Notify) +{ + auto const initialstate{TractionMode}; + // refused with the line breaker closed, and then not passed on either, so the train stays on one source + auto const accepted{false == Mains}; + + if (Genset.fitted() && accepted) + { + TractionMode = Mode; + } + + if (Notify != range_t::local && accepted) + { + SendCtrlToNext("TractionMode", Mode == traction_mode::genset ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return TractionMode != initialstate; +} + +// ************************************************************************************************* +// zwiększenie nastawy nastawnika hamulca elektrodynamicznego (DynamicBrakeCtrl) +// uzywane gdy SplitEDPneumaticBrake = true +// ************************************************************************************************* +bool TMoverParameters::IncDynamicBrakeLevel(float const CtrlSpeed) +{ + if (false == SplitEDPneumaticBrake) + return false; + if (DynamicBrakeCtrlPosNo < 1) + return false; + if (DynamicBrakeCtrlPos < 1.0) + { + DynamicBrakeCtrlPos = std::min(1.0, DynamicBrakeCtrlPos + (double)CtrlSpeed / (double)DynamicBrakeCtrlPosNo); + return true; + } + return false; +} + +// ************************************************************************************************* +// zmniejszenie nastawy nastawnika hamulca elektrodynamicznego (DynamicBrakeCtrl) +// ************************************************************************************************* +bool TMoverParameters::DecDynamicBrakeLevel(float const CtrlSpeed) +{ + if (false == SplitEDPneumaticBrake) + return false; + if (DynamicBrakeCtrlPosNo < 1) + return false; + if (DynamicBrakeCtrlPos > 0.0) + { + DynamicBrakeCtrlPos = std::max(0.0, DynamicBrakeCtrlPos - (double)CtrlSpeed / (double)DynamicBrakeCtrlPosNo); + return true; + } + return false; +} + +// ************************************************************************************************* +// bezposrednie ustawienie nastawnika hamulca elektrodynamicznego (DynamicBrakeCtrl) +// ************************************************************************************************* +bool TMoverParameters::DynamicBrakeLevelSet(double Position) +{ + if (false == SplitEDPneumaticBrake) + return false; + DynamicBrakeCtrlPos = std::clamp(Position, 0.0, 1.0); + return true; +} + +// ************************************************************************************************* +// odczyt nastawy nastawnika hamulca elektrodynamicznego (DynamicBrakeCtrl) +// zwraca 0 jezeli SplitEDPneumaticBrake nie jest aktywne (dla zachowania starej logiki) +// ************************************************************************************************* +double TMoverParameters::DynamicBrakeRatio(void) const +{ + if (false == SplitEDPneumaticBrake) + return 0.0; + return std::clamp(DynamicBrakeCtrlPos, 0.0, 1.0); +} + +// ************************************************************************************************* +// czy hamulec ED jest aktualnie dostepny w oknie predkosci Vh0..Vh1 +// ************************************************************************************************* +bool TMoverParameters::DynamicBrakeAvailable(void) const +{ + double const vh0{eimc[eimc_p_Vh0]}; + if (double const vh1{eimc[eimc_p_Vh1]}; vh1 <= 0.001) + { + // brak zdefiniowanej strefy - ED dziala zawsze + return true; + } + // strefa wylaczenia jest definiowana przez Vh0 (minimum); powyzej Vh0 ED dziala + return Vel >= vh0; +} + +// ************************************************************************************************* +// Q: 20160713 +// reczne przelaczanie hamulca elektrodynamicznego +// ************************************************************************************************* +bool TMoverParameters::DynamicBrakeSwitch(bool Switch) +{ + bool DBS; + + if (DynamicBrakeType == dbrake_switch && IsMainCtrlNoPowerPos()) + { + DynamicBrakeFlag = Switch; + DBS = true; + for (auto &thiscoupler : Couplers) + // with Couplers[b] do + if (TestFlag(thiscoupler.CouplingFlag, coupling::control)) + thiscoupler.Connected->DynamicBrakeFlag = Switch; + // end; + // if (DynamicBrakeType=dbrake_passive) and (TrainType=train_type::et42) then + // begin + // DynamicBrakeFlag:=false; + // DynamicBrakeSwitch:=false; + } + else + DBS = false; + + return DBS; +} + +// ************************************************************************************************* +// Q: 20160714 +// oblicza sile trakcyjna lokomotywy (dla elektrowozu tez calkowity prad) +// ************************************************************************************************* +double TMoverParameters::TractionForce(double dt) +{ + using enum TEngineType; + Ft = 0; + double dtrans{0.0}; + double dmoment{0.0}; + auto const revolutions{UpdateEngineRevolutions(dt, dtrans, dmoment)}; + + eAngle += enrot * dt; + if (eAngle > M_PI * 2.0) + eAngle = std::fmod(eAngle, M_PI * 2.0); + /* + while (eAngle > M_PI * 2.0) + // eAngle = Pirazy2 - eAngle; <- ABu: a nie czasem tak, jak nizej? + eAngle -= M_PI * 2.0; + */ + // hunter-091012: przeniesione z if DirActive<>0 (zeby po zejsciu z kierunku dalej spadala predkosc wentylatorow) + // wentylatory rozruchowe + // TBD, TODO: move this to update, it doesn't exactly have much to do with traction + UpdateVentilators(dt); + auto const PosRatio{UpdateEnginePower()}; + VoltageRelaysCheck(); + + if (EngineType == DieselElectric && DEDynamicBrake.source != diesel_electric_dynamic_brake::control::none) + { + update_dieselelectric_dynamic_brake(dt); + } + + if (DirActive != 0) + switch (EngineType) + { + case Dumb: + { + DumbTractionForce(PosRatio); + break; + } + case WheelsDriven: + { + WheelsDrivenTractionForce(dt); + break; + } + case ElectricSeriesMotor: + { + SeriesMotorTractionForce(dt); + break; + } + case DieselEngine: + { + DieselEngineTractionForce(dt, dmoment, dtrans); + break; + } + case DieselElectric: // youBy + { + DieselElectricTractionForce(revolutions); + if (DEDynamicBrake.level > 0.0) + { + // braking: no power asked for, so the drive above gave no force + apply_dieselelectric_dynamic_brake(dt); + } + break; + } + case ElectricInductionMotor: + { + InductionMotorTractionForce(dt); + break; + } + case None: + default: + { + break; + } + } // case EngineType + + if (EngineType == DieselElectric) + { + // rough approximation of extra effort to overcome friction etc + EnginePower += EngineRPMRatio() * 0.15 * DElist[MainCtrlPosNo].GenPower; + } + + return Ft; +} + +// the starting resistors' blowers, and the diesels' radiator fans +void TMoverParameters::UpdateVentilators(double dt) +{ + switch (EngineType) + { + + case TEngineType::ElectricSeriesMotor: + { + if (MainCircuitPowered()) + { + UpdateResistorBlowers(dt); + } // mains + else + { + RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); + } + break; + } + + case TEngineType::DieselElectric: + { + // NOTE: for this type RventRot is the speed of motor blowers; we also update radiator fans while at it + if (true == Mains) + { + // TBD, TODO: currently ignores RVentType, fix this? + RventRot += std::clamp(enrot - RventRot, -100.0, 50.0) * dt; + dizel_heat.rpmw += static_cast(std::clamp(dizel_heat.rpmwz - dizel_heat.rpmw, -100.f, 50.f) * dt); + dizel_heat.rpmw2 += static_cast(std::clamp(dizel_heat.rpmwz2 - dizel_heat.rpmw2, -100.f, 50.f) * dt); + } + else + { + RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); + dizel_heat.rpmw *= static_cast(std::max(0.0, 1.0 - dizel_heat.rpmw * dt)); + dizel_heat.rpmw2 *= static_cast(std::max(0.0, 1.0 - dizel_heat.rpmw2 * dt)); + } + break; + } + + case TEngineType::DieselEngine: + { + // NOTE: we update only radiator fans, as vehicles with diesel engine don't have other ventilators + if (true == Mains) + { + dizel_heat.rpmw += static_cast(std::clamp(dizel_heat.rpmwz - dizel_heat.rpmw, -100.f, 50.f) * dt); + dizel_heat.rpmw2 += static_cast(std::clamp(dizel_heat.rpmwz2 - dizel_heat.rpmw2, -100.f, 50.f) * dt); + } + else + { + dizel_heat.rpmw *= static_cast(std::max(0.0, 1.0 - dizel_heat.rpmw * dt)); + dizel_heat.rpmw2 *= static_cast(std::max(0.0, 1.0 - dizel_heat.rpmw2 * dt)); + } + break; + } + + default: + { + break; + } + } +} + +// the starting resistors' blowers of the series motors with the line breaker closed, worked by hand or by the current +void TMoverParameters::UpdateResistorBlowers(double dt) +{ + switch (RVentType) + { + + case 1: + { // manual + if (true == RVentForceOn || (DirActive != 0 && RList[MainCtrlActualPos].R > RVentCutOff)) + { + RventRot += (RVentnmax - RventRot) * RVentSpeed * dt; + } + else + { + RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); + } + break; + } + + case 2: + { // automatic + auto const motorcurrent{std::min(ImaxHi, std::abs(Im))}; + if (std::abs(Itot) > RVentMinI && RList[MainCtrlActualPos].R > RVentCutOff) + { + + RventRot += (RVentnmax * std::min(1.0, motorcurrent / NPoweredAxles / RVentMinI) * motorcurrent / ImaxLo - RventRot) * RVentSpeed * dt; + } + else if (DynamicBrakeType == dbrake_automatic && true == DynamicBrakeFlag) + { + RventRot += (RVentnmax * motorcurrent / ImaxLo - RventRot) * RVentSpeed * dt; + } + else if (RVentForceOn) + { + RventRot += (RVentnmax - RventRot) * RVentSpeed * dt; + } + else + { + RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); + } + break; + } + + default: + { + break; + } + } // rventtype +} + +// the power of a dumb or diesel engine; returns the ratio of the power a dumb engine is set to +double TMoverParameters::UpdateEnginePower() +{ + double PosRatio{0.0}; + switch (EngineType) + { + case TEngineType::Dumb: + { + PosRatio = (MainCtrlPos + ScndCtrlPos) / (MainCtrlPosNo + ScndCtrlPosNo + 0.01); + EnginePower = /*1000.0 **/ Power * PosRatio; + break; + } + case TEngineType::DieselEngine: + { + dizel_Power = Mm * enrot * (2.0 * M_PI / 1000.0); + EnginePower = (dizel_Mstand + Mm) * enrot * (2.0 * M_PI / 1000.0); + if (MainCtrlPowerPos() > 1) + { + // dodatkowe opory z powodu sprezarki} + // dmoment -= dizel_Mstand * ( 0.2 * enrot / dizel_nmax ); //yB: skąd to w ogóle się bierze?! + } + break; + } + case TEngineType::DieselElectric: + { + EnginePower = 0; // the actual calculation is done in two steps later in the method + break; + } + default: + { + break; + } + } + + return PosRatio; +} + +// the line breaker opened by a voltage out of the motors' range, and the line contactors of a diesel-electric +void TMoverParameters::VoltageRelaysCheck() +{ + switch (EngineType) + { + + case TEngineType::ElectricSeriesMotor: + { + // update the state of voltage relays + auto const voltage{std::max(GetTrainsetHighVoltage(), PantographVoltage)}; + // where the line breaker holds without voltage (closed ahead of the pantographs) the undervoltage relay opens the + // line contactors instead, see MotorConnectorsCheck(). it picks up again only with the master controller back + // where a start begins, as the line breaker it stands in for wouldn't close on a running position either: at + // zero, or at the first position, which is the first resistance step, where the line contactors close on any + // start, and where the AI waits for them rather than going back to zero + auto const novoltrelaypicksup{false == PantographsRequireMains || NoVoltRelay || MainCtrlPowerPos() <= 1}; + NoVoltRelay = EnginePowerSource.SourceType != TPowerSource::CurrentCollector || (voltage >= EnginePowerSource.CollectorParameters.MinV && novoltrelaypicksup); + OvervoltageRelay = + EnginePowerSource.SourceType != TPowerSource::CurrentCollector || voltage <= EnginePowerSource.CollectorParameters.MaxV || false == EnginePowerSource.CollectorParameters.OVP; + // wywalanie szybkiego z powodu niewłaściwego napięcia + // (a line breaker closed ahead of the pantographs holds without voltage) + EventFlag |= true == Mains && ((false == NoVoltRelay && false == PantographsRequireMains) || false == OvervoltageRelay) && + MainSwitch(false, TrainType == train_type::emu ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide + break; + } + + case TEngineType::ElectricInductionMotor: + { + // TODO: check if we can use instead the code for electricseriesmotor + // nie wchodzić w funkcję bez potrzeby + // (a line breaker closed ahead of the pantographs holds without voltage) + // (the source by the traction selector of a dual-mode vehicle: the pantographs or the genset) + if (Mains && ((TractionSupplyVoltage() < TractionSupplyMinVoltage() && false == PantographsRequireMains) || + TractionSupplyVoltage() > EnginePowerSource.CollectorParameters.MaxV + 200)) + { + MainSwitch(false, TrainType == train_type::emu ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide + } + break; + } + + case TEngineType::DieselElectric: + { + // TODO: move this to the auto relay check when the electric engine code paths are unified + StLinFlag |= Mains && false == StLinFlag && MainCtrlPowerPos() == 1; + StLinFlag &= MotorConnectorsCheck(); + StLinFlag &= MainCtrlPowerPos() > 0; + + break; + } + + default: + { + break; + } + } +} + +void TMoverParameters::DumbTractionForce(double const PosRatio) +{ + if (Mains && CabActive != 0) + { + if (Vel > 0.1) + { + Ft = std::min(1000.0 * Power / std::abs(V), Ftmax) * PosRatio; + } + else + { + Ft = Ftmax * PosRatio; + } + Ft = Ft * DirAbsolute; // DirActive*CabActive; + } + else + { + Ft = 0; + } +} + +void TMoverParameters::WheelsDrivenTractionForce(double dt) +{ + if (EnginePowerSource.SourceType == TPowerSource::InternalSource && EnginePowerSource.PowerType == TPowerType::BioPower) + Ft = Sign(sin(eAngle)) * PulseForce * Transmision.Ratio; + PulseForceTimer = PulseForceTimer + dt; + if (PulseForceTimer > CtrlDelay) + { + PulseForce = 0; + if (PulseForceCount > 0) + PulseForceCount--; + } + EnginePower = Ft * (1.0 + Vel); +} + +void TMoverParameters::SeriesMotorTractionForce(double dt) +{ + // enrot:=Transmision.Ratio*nrot; + // yB: szereg dwoch sekcji w ET42 + if (TrainType == train_type::et42 && Imax == ImaxHi) + EngineVoltage = EngineVoltage / 2.0; + Mm = Momentum(Current(enrot, EngineVoltage)); // oblicza tez prad p/slinik + + if (TrainType == train_type::et42) + { + if (Imax == ImaxHi) + EngineVoltage = EngineVoltage * 2; + if (DynamicBrakeFlag && abs(Im) > 300) // przeiesione do mover.cpp + FuseOff(); + } + if (DynamicBrakeType == dbrake_automatic && DynamicBrakeFlag) + { + SeriesMotorDynamicBrake(dt); + } + + if (TrainType == train_type::et22 && DelayCtrlFlag) // szarpanie przy zmianie układu w byku + Mm = Mm * RList[MainCtrlActualPos].Bn / (RList[MainCtrlActualPos].Bn + 1); // zrobione w momencie, żeby nie dawac elektryki w przeliczaniu sił + + if (abs(Im) > Imax) + Vhyp += dt; //*(abs(Im) / Imax - 0.9) * 10; // zwieksz czas oddzialywania na PN + else + Vhyp = 0; + if (Vhyp > CtrlDelay / 2) // jesli czas oddzialywania przekroczony + FuseOff(); // wywalanie bezpiecznika z powodu przetezenia silnikow + + if ((DynamicBrakeType == dbrake_automatic || DynamicBrakeType == dbrake_switch) && DynamicBrakeFlag) + Itot = Im * 2; // 2x2 silniki w EP09 + else if (TrainType == train_type::emu && Imin == IminLo && ScndS) // yBARC - boczniki na szeregu poprawnie + Itot = Im; + else + Itot = Im * RList[MainCtrlActualPos].Bn; // prad silnika * ilosc galezi + Mw = Mm * Transmision.Ratio * Transmision.Efficiency; + Fw = Mw * 2.0 / WheelDiameter; + Ft = Fw * NPoweredAxles; // sila trakcyjna +} + +// the automatic dynamic brake of the series motors: the excitation current, by the stages of the ep brake (TUHEX) +void TMoverParameters::SeriesMotorDynamicBrake(double dt) +{ + if (TUHEX_Stages > 0) // hamowanie wielostopniowe, nadpisuje wartości domyślne + { + if (Vel > 100) + TUHEX_StageActual = std::min(TUHEX_StageActual, 1); + switch (TUHEX_StageActual) + { + case 1: + TUHEX_Sum = TUHEX_Sum1; + DynamicBrakeRes = DynamicBrakeRes1; + break; + case 2: + TUHEX_Sum = TUHEX_Sum2; + DynamicBrakeRes = DynamicBrakeRes1; + break; + case 3: + TUHEX_Sum = TUHEX_Sum3; + if (Vadd > 0.99 * TUHEX_MaxIw && DynamicBrakeRes == DynamicBrakeRes1) + TUHEX_ResChange = true; + if (TUHEX_ResChange && Vadd < 0.5 * TUHEX_MaxIw) + { + TUHEX_ResChange = false; + DynamicBrakeRes = DynamicBrakeRes2; + } + break; + default: + DynamicBrakeRes = DynamicBrakeRes1; + TUHEX_Sum = 0; + break; + } + } + if (Vadd + abs(Im) > TUHEX_Sum + TUHEX_Diff || Hamulec->GetEDBCP() < 0.25 || TUHEX_ResChange || (TUHEX_StageActual == 0 && TUHEX_Stages > 0)) + { + Vadd -= 500.0 * dt; + if (Vadd < TUHEX_MinIw) + { + Vadd = 0; + DynamicBrakeFlag = false; + } + } + else if (DynamicBrakeFlag && Vadd + abs(Im) < TUHEX_Sum - TUHEX_Diff) + { + Vadd += 70.0 * dt; + Vadd = std::min(std::max(Vadd, TUHEX_MinIw), TUHEX_MaxIw); + } + if (Vadd > 0) + Mm = MomentumF(Im, Vadd, 0); +} + +// the shunt field relays of a diesel-electric, each kind its own conditions on the current, the speed or the +// power (tmp, the power the engine gives) +void TMoverParameters::ShuntFieldRelaysCheck(double const tmpV, double const PosRatio, double const tmp) +{ + auto const shuntfieldstate{ScndCtrlPos}; + + switch (RelayType) + { + + case 0: + { + + if (ScndCtrlPos < ScndCtrlPosNo && Im <= MPTRelay[ScndCtrlPos].Iup * PosRatio) + { + ++ScndCtrlPos; + } + if (ScndCtrlPos > 0 && Im >= MPTRelay[ScndCtrlPos].Idown * PosRatio) + { + --ScndCtrlPos; + } + break; + } + case 1: + { + + if (ScndCtrlPos < ScndCtrlPosNo && MPTRelay[ScndCtrlPos].Iup < Vel) + { + ++ScndCtrlPos; + } + if (ScndCtrlPos > 0 && MPTRelay[ScndCtrlPos].Idown > Vel) + { + --ScndCtrlPos; + } + break; + } + case 2: + { + + ShuntFieldRelaysType2(tmp); + break; + } + case 41: + { + ShuntFieldRelaysType41(tmpV); + break; + } + case 45: + { + ShuntFieldRelaysType45(); + break; + } + case 46: + { + ShuntFieldRelaysType46(); + break; + } + default: + { + break; + } + } // switch RelayType + + if (ScndCtrlPos != shuntfieldstate) + { + SetFlag(SoundFlag, sound::relay | sound::shuntfield); + } +} + +// the relays of type 2: up by the speed while the engine has power to spare (tmp, the power it gives), down by the current +void TMoverParameters::ShuntFieldRelaysType2(double const tmp) +{ + if (ScndCtrlPos < ScndCtrlPosNo && MPTRelay[ScndCtrlPos].Iup < Vel && EnginePower < tmp * 0.99) + { + ++ScndCtrlPos; + } + if (ScndCtrlPos > 0 && MPTRelay[ScndCtrlPos].Idown < Im) + { + --ScndCtrlPos; + } +} + +// the relays of type 41: up by the speed tmpV at full power, the engine slowed down, down by the current +void TMoverParameters::ShuntFieldRelaysType41(double const tmpV) +{ + if (ScndCtrlPos < ScndCtrlPosNo && MainCtrlPos == MainCtrlPosNo && tmpV * 3.6 > MPTRelay[ScndCtrlPos].Iup) + { + ++ScndCtrlPos; + enrot = enrot * 0.73; + } + if (ScndCtrlPos > 0 && Im > MPTRelay[ScndCtrlPos].Idown) + { + --ScndCtrlPos; + } +} + +// the relays of type 45, by the current and the speed: up from the 11th position, at most two under it, none under the 8th +void TMoverParameters::ShuntFieldRelaysType45() +{ + if (ScndCtrlPos < ScndCtrlPosNo && MainCtrlPos >= 11) + { + + if (Im < MPTRelay[ScndCtrlPos].Iup) + { + ++ScndCtrlPos; + } + // check for cases where the speed drops below threshold for level 2 or 3 + if (ScndCtrlPos > 1 && Vel < MPTRelay[ScndCtrlPos - 1].Idown) + { + --ScndCtrlPos; + } + } + // malenie + if (ScndCtrlPos > 0 && MainCtrlPos < 11) + { + + if (ScndCtrlPos == 1) + { + if (Im > MPTRelay[ScndCtrlPos - 1].Idown) + { + --ScndCtrlPos; + } + } + else + { + if (Vel < MPTRelay[ScndCtrlPos].Idown) + { + --ScndCtrlPos; + } + } + } + // 3rd level drops with master controller at position lower than 10... + if (MainCtrlPos < 11) + { + ScndCtrlPos = std::min(2, ScndCtrlPos); + } + // ...and below position 7 field shunt drops altogether + if (MainCtrlPos < 8) + { + ScndCtrlPos = 0; + } + /* + // crude woodward approximation; difference between rpm for consecutive positions is ~5% + // so we get full throttle until ~half way between desired and previous position, or zero on rpm reduction + auto const woodward { std::clamp( + ( DElist[ MainCtrlPos ].RPM / ( enrot * 60.0 ) - 1.0 ) * 50.0, + 0.0, 1.0 ) }; + */ +} + +// the relays of type 46, by the current and the speed: up from the 12th position, down under it below 50 km/h, at most two +// under the 11th, none under the 8th +void TMoverParameters::ShuntFieldRelaysType46() +{ + // wzrastanie + if (MainCtrlPos >= 12 && ScndCtrlPos < ScndCtrlPosNo) + { + ShuntFieldRelaysType46Up(); + } + // malenie + if (MainCtrlPos < 12 && ScndCtrlPos > 0 && Vel < 50.0) + { + ShuntFieldRelaysType46Down(); + } + if (MainCtrlPos < 11) + { + ScndCtrlPos = std::min(2, ScndCtrlPos); + } + if (MainCtrlPos < 8) + { + ScndCtrlPos = 0; + } +} + +// a relay of type 46 down: an even one by the current, an odd one by the current and the speed +void TMoverParameters::ShuntFieldRelaysType46Down() +{ + // above 50 km/h already active shunt field can be maintained until lower controller setting + if (ScndCtrlPos % 2 == 0) + { + if (MPTRelay[ScndCtrlPos].Idown < Im) + { + --ScndCtrlPos; + } + } + else + { + if (MPTRelay[ScndCtrlPos + 1].Idown < Im && MPTRelay[ScndCtrlPos].Idown > Vel) + { + --ScndCtrlPos; + } + } +} + +// a relay of type 46 up: an even one by the current, an odd one by the current and the speed +void TMoverParameters::ShuntFieldRelaysType46Up() +{ + if (ScndCtrlPos % 2 == 0) + { + if (MPTRelay[ScndCtrlPos].Iup > Im) + { + ++ScndCtrlPos; + } + } + else + { + if (MPTRelay[ScndCtrlPos - 1].Iup > Im && MPTRelay[ScndCtrlPos].Iup < Vel) + { + ++ScndCtrlPos; + } + } +} + +void TMoverParameters::InductionMotorTractionForce(double dt) +{ + if (MainCircuitPowered() && !SecuritySystem.is_engine_blocked()) + { + double PosRatio; + double tmp; + double ActiveInverters = 0.0; + for (auto const &inv : Inverters) + { + if (inv.IsActive) + ActiveInverters += 1.0; + } + InvertersRatio = ActiveInverters / (double)InvertersNo; + if (EIM_Pmax_Table.size() > 1) + { + eimc[eimc_p_Pmax] = TableInterpolation(EIM_Pmax_Table, Vel); + } + InductionMotorSpeedControl(dt); + InductionMotorBrakeBlending(ActiveInverters, PosRatio, tmp); + // NOTE: the commands to operate the sandbox are likely to conflict with other similar ai decisions + // TODO: gather these in single place so they can be resolved together + if (SlippingWheels) + { + PosRatio = 0; + tmp = 10; + SandboxAuto(true, range_t::unit); + } // przeciwposlizg + else + { + // switch sandbox off + SandboxAuto(false, range_t::unit); + } + if (ActiveInverters == 0.0) + { + PosRatio = 0; + eimv_pr = 0; + } + + eimv_pr += std::max(std::min(PosRatio - eimv_pr, 0.02), -0.02) * 12 * tmp /*2{+4*byte(PosRatio 1) + { + SpeedControlByPosition(dt); + } +} + +// the speed control set by the position of the second controller, after it's been held for its delay +void TMoverParameters::SpeedControlByPosition(double dt) +{ + if (ScndCtrlPos != NewSpeed) + { + + SpeedCtrlTimer = 0; + NewSpeed = ScndCtrlPos; + } + else + { + SpeedCtrlTimer += dt; + if (SpeedCtrlTimer > SpeedCtrlDelay) + { + auto NewSCAP = static_cast((float)ScndCtrlPos / (float)ScndCtrlPosNo * Vmax); + if (NewSCAP != SpeedCtrlValue) + { + SpeedCtrlValue = NewSCAP; + // SendCtrlToNext("SpeedCntrl", SpeedCtrlValue, CabActive); + } + } + } + SpeedCtrlUnit.IsActive = SpeedCtrlValue > 0; +} + +// the speed control of a four position second controller, by time: the speed set down or up by 10 km/h a step, held, +// or off and at the top +void TMoverParameters::SpeedControlByTime(double dt) +{ + SpeedCtrlUnit.IsActive = SpeedCtrlValue > 0; + switch (ScndCtrlPos) + { + case 0: + NewSpeed = 0; + SpeedCtrlValue = 0; + SpeedCtrlTimer = 10; + break; + case 1: + if (SpeedCtrlTimer > SpeedCtrlDelay) + { + SpeedCtrlTimer = 0; + NewSpeed -= 10; + if (NewSpeed < 0) + NewSpeed = 0; + } + else + SpeedCtrlTimer += dt; + break; + case 2: + SpeedCtrlTimer = 10; + SpeedCtrlValue = NewSpeed; + break; + case 3: + if (SpeedCtrlTimer > SpeedCtrlDelay) + { + SpeedCtrlTimer = 0; + NewSpeed += 10; + if (NewSpeed > Vmax) + NewSpeed = Vmax; + } + else + SpeedCtrlTimer += dt; + break; + case 4: + NewSpeed = Vmax; + SpeedCtrlValue = Vmax; + SpeedCtrlTimer = 10; + break; + default: + break; + } +} + +// whether the induction motors brake, and the share of the electrodynamic and the pneumatic brake; sets the +// force asked of the motors (PosRatio) and how fast the drive follows it (tmp) +void TMoverParameters::InductionMotorBrakeBlending(double const ActiveInverters, double &PosRatio, double &tmp) +{ + InductionMotorDynamicBrakeFlag(); + auto const edBCP{Hamulec->GetEDBCP() * eimc[eimc_p_abed]}; // stala napedu + if (DynamicBrakeFlag) + { + PosRatio = InductionMotorBrakeRatio(ActiveInverters, edBCP); + tmp = 5; + } + else + { + PosRatio = std::max(eimic_real, 0.); + eimv[eimv_Fzad] = PosRatio; + if (Flat && eimc[eimc_p_F0] * eimv[eimv_Fful] > 0) + PosRatio = std::min(PosRatio * eimc[eimc_p_F0] / eimv[eimv_Fful], 1.); + /* if (ScndCtrlActualPos > 0) //speed control + if (Vmax < 250) + PosRatio = std::min(PosRatio, std::max(-1, 0.5 * (ScndCtrlActualPos - Vel))); + else + PosRatio = + std::min(PosRatio, std::max(-1, 0.5 * (ScndCtrlActualPos * 2 - Vel))); */ + // PosRatio = 1.0 * (PosRatio * 0 + 1) * PosRatio; // 1 * 1 * PosRatio = PosRatio + Hamulec->SetED(0); + // (Hamulec as TLSt).SetLBP(LocBrakePress); + tmp = 4; // szybkie malenie, powolne wzrastanie + } +} + +// the electrodynamic brake of the induction motors on: with the doors open or permitted, by the train brake, the local +// brake or its own controller; off without them +void TMoverParameters::InductionMotorDynamicBrakeFlag() +{ + double const edBCP = Hamulec->GetEDBCP(); + auto const localbrakeactive{CabOccupied != 0 && LocHandle->GetCP() > 0.25}; + // gdy SplitEDPneumaticBrake jest aktywne, hamulec pomocniczy (LocalBrake) NIE wymusza + // zalaczenia hamulca elektrodynamicznego - ED jest sterowany wlasnym nastawnikiem + auto const dynbrakectrlactive{SplitEDPneumaticBrake && DynamicBrakeRatio() > 0.01 && DynamicBrakeAvailable()}; + auto const localbrakeforED{SplitEDPneumaticBrake ? false : localbrakeactive}; + if (false == Doors.instances[side::left].is_closed || false == Doors.instances[side::right].is_closed || + (Doors.permit_needed && (Doors.instances[side::left].open_permit || Doors.instances[side::right].open_permit))) + { + DynamicBrakeFlag = true; + } + else if ((edBCP < 0.25 && false == localbrakeforED && false == dynbrakectrlactive && AnPos < 0.01) || + (edBCP < 0.25 && ShuntModeAllow && false == dynbrakectrlactive && LocalBrakePosA < 0.01)) + DynamicBrakeFlag = false; + else if (BrakePress > 0.25 && edBCP > 0.25 || localbrakeforED || AnPos > 0.02 || dynbrakectrlactive) + DynamicBrakeFlag = true; +} + +// the share of the electrodynamic brake (negative), and the distributor told how much of the air to let out; none +// when the air brake cuts the electrodynamic one off, or an inverter is out +double TMoverParameters::InductionMotorBrakeRatio(double const ActiveInverters, double const edBCP) +{ + double PosRatio; + // ustalanie współczynnika blendingu do luzowania hamulca PN + if (eimv[eimv_Fmax] * Sign(V) * DirAbsolute < -1) + { + PosRatio = -Sign(V) * DirAbsolute * eimv[eimv_Fr] / (eimc[eimc_p_Fh] * std::max(edBCP, std::max(0.01, Hamulec->GetEDBCP())) / MaxBrakePress[0]); + PosRatio = std::clamp(PosRatio, 0.0, 1.0); + } + else + { + PosRatio = 0; + } + PosRatio = static_cast(Round(20.0 * PosRatio)) / 20.0; // stopniowanie PN/ED + if (PosRatio < 19.5 / 20.0) + PosRatio *= 0.9; + Hamulec->SetED(std::max(0.0, std::min(PosRatio, 1.0))); // ustalenie stopnia zmniejszenia ciśnienia + // ustalanie siły hamowania ED + if (Hamulec->GetEDBCP() > 0.25 && eimc[eimc_p_abed] < 0.001 || ActiveInverters < InvertersNo) // jeśli PN wyłącza ED + { + PosRatio = 0; + eimv[eimv_Fzad] = 0; + } + else + { + // strefa wylaczenia ED (Vh0..Vh1) - mnoznik 0..1 zaleznie od predkosci + double const vhRamp = std::max(0.0, std::min(1.0, (Vel - eimc[eimc_p_Vh0]) / (eimc[eimc_p_Vh1] - eimc[eimc_p_Vh0]))); + if (SplitEDPneumaticBrake) + { + // w trybie split LocalBrake nie zaleca ED; uzywany jest DynamicBrakeCtrl + // oraz zwykle zapotrzebowanie z hamulca zespolonego (edBCP) + double const edLeverDemand = DynamicBrakeRatio(); + PosRatio = -std::max(std::max(edLeverDemand, std::min(edBCP / MaxBrakePress[0], 1.0)), AnPos) * vhRamp; + eimv[eimv_Fzad] = -std::min(1.0, std::max(edLeverDemand, edBCP / MaxBrakePress[0])); + } + else + { + PosRatio = -std::max(std::min(edBCP * 1.0 / MaxBrakePress[0], 1.0), AnPos) * vhRamp; + eimv[eimv_Fzad] = -std::min(1.0, std::max(LocalBrakeRatio(), edBCP / MaxBrakePress[0])); + } + } + return PosRatio; +} + +// the model of the induction motors and their inverters: voltage, frequency, currents, moment and force +void TMoverParameters::InductionMotorDrive(double dt) +{ + double tmp; + if (DynamicBrakeFlag) + tmp = eimc[eimc_f_Uzh]; + else + tmp = eimc[eimc_f_Uzmax]; + + auto f_cfu{DynamicBrakeFlag ? eimc[eimc_f_cfuH] : eimc[eimc_f_cfu]}; + + eimv[eimv_Uzsmax] = std::min(EngineVoltage - eimc[eimc_f_DU], tmp); + eimv[eimv_fkr] = eimv[eimv_Uzsmax] / f_cfu; + if (eimv_pr < 0) + { + eimv[eimv_Pmax] = eimc[eimc_p_Ph]; + } + else + { + eimv[eimv_Pmax] = std::min(eimc[eimc_p_Pmax], 0.001 * EngineVoltage * (eimc[eimc_p_Imax] - eimc[eimc_f_I0]) * Pirazy2 * eimc[eimc_s_cim] / eimc[eimc_s_p] / eimc[eimc_s_cfu]); + if (GensetSelected()) + { + // on the genset of a dual-mode vehicle the traction takes no more than the genset gives + eimv[eimv_Pmax] = std::min(eimv[eimv_Pmax], GensetTractionPowerLimit()); + } + } + eimv[eimv_FMAXMAX] = 0.001 * + square(std::min(1.0, eimv[eimv_fkr] / std::max(abs(enrot) * eimc[eimc_s_p] + eimc[eimc_s_dfmax] * eimv[eimv_ks], eimc[eimc_s_dfmax])) * f_cfu / eimc[eimc_s_cfu]) * + (eimc[eimc_s_dfmax] * eimc[eimc_s_dfic] * eimc[eimc_s_cim]) * Transmision.Ratio * NPoweredAxles * 2.0 / WheelDiameter; + InductionMotorForceLimits(); + for (auto &inv : Inverters) + { + inv.Request = inv.IsActive ? eimv_pr : 0.0; + inv.Error = inv.Failure_Const || (inv.Failure_Drive && inv.Request != 0); + inv.IsActive = inv.Activate && !inv.Error; + } + eimv[eimv_ks] = eimv[eimv_Fr] / eimv[eimv_FMAXMAX]; + eimv[eimv_df] = eimv[eimv_ks] * eimc[eimc_s_dfmax]; + eimv[eimv_fp] = DirAbsolute * enrot * eimc[eimc_s_p] + eimv[eimv_df]; // do przemyslenia dzialanie pp z tmpV + // eimv[eimv_U]:=std::max(eimv[eimv_Uzsmax],std::min(eimc[eimc_f_cfu]*eimv[eimv_fp],eimv[eimv_Uzsmax])); + // eimv[eimv_pole]:=eimv[eimv_U]/(eimv[eimv_fp]*eimc[eimc_s_cfu]); + if (abs(eimv[eimv_fp]) <= eimv[eimv_fkr]) + eimv[eimv_pole] = f_cfu / eimc[eimc_s_cfu]; + else + eimv[eimv_pole] = eimv[eimv_Uzsmax] / eimc[eimc_s_cfu] / abs(eimv[eimv_fp]); + eimv[eimv_U] = eimv[eimv_pole] * eimv[eimv_fp] * eimc[eimc_s_cfu]; + eimv[eimv_Ic] = (eimv[eimv_fp] - DirAbsolute * enrot * eimc[eimc_s_p]) * eimc[eimc_s_dfic] * eimv[eimv_pole]; + eimv[eimv_If] = eimv[eimv_Ic] * eimc[eimc_s_icif]; + eimv[eimv_M] = eimv[eimv_pole] * eimv[eimv_Ic] * eimc[eimc_s_cim]; + eimv[eimv_Ipoj] = eimv[eimv_Ic] * NPoweredAxles * InvertersRatio * eimv[eimv_U] / (EngineVoltage - eimc[eimc_f_DU]) + eimc[eimc_f_I0]; + eimv[eimv_Pm] = DirActive * eimv[eimv_M] * NPoweredAxles * InvertersRatio * enrot * Pirazy2 / 1000; + eimv[eimv_Pe] = eimv[eimv_Ipoj] * EngineVoltage / 1000; + eimv[eimv_eta] = eimv[eimv_Pm] / eimv[eimv_Pe]; + + Im = eimv[eimv_If]; + if (eimv[eimv_Ipoj] >= 0) + Vadd *= 1.0 - 2.0 * dt; + else if (GensetSelected()) + Vadd = 1.0; // the genset of a dual-mode vehicle takes nothing back: all the braking energy to the resistors + else if (std::abs(EngineVoltage) < EnginePowerSource.CollectorParameters.MaxV) + Vadd *= 1.0 - dt; + else + Vadd = std::max(Vadd * (1.0 - 0.2 * dt), 0.007 * (std::abs(EngineVoltage) - (EnginePowerSource.CollectorParameters.MaxV - 100))); + Itot = eimv[eimv_Ipoj] * (0.01 + std::min(0.99, 0.99 - Vadd)); + + EnginePower = abs(eimv[eimv_Ic] * eimv[eimv_U] * NPoweredAxles) / 1000; + // power inverters + UpdateInverterFrequency(); + + Mm = eimv[eimv_M] * DirAbsolute; + Mw = Mm * Transmision.Ratio * Transmision.Efficiency; + Fw = Mw * 2.0 / WheelDiameter; + Ft = Fw * NPoweredAxles * InvertersRatio; + eimv[eimv_Fr] = DirAbsolute * Ft / 1000; +} + +// the force the motors give at full and at the setting (eimv_pr), braking within the power and the force of the +// electrodynamic brake, driving within the power and the starting force +void TMoverParameters::InductionMotorForceLimits() +{ + if (eimv_pr < 0) + { + eimv[eimv_Fful] = std::min(eimc[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(eimc[eimc_p_Fh], eimv[eimv_FMAXMAX])); + eimv[eimv_Fmax] = -Sign(V) * DirAbsolute*std::min(eimc[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-eimc[eimc_p_Fh] * eimv_pr, eimv[eimv_FMAXMAX])); + double pr = eimv_pr; + if (EIMCLogForce) + pr = -log(1 - 4 * pr) / log(5); + eimv[eimv_Fr] = -Sign(V) * DirAbsolute*std::min(eimc[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-eimc[eimc_p_Fh] * pr, eimv[eimv_FMAXMAX])); + if (InvertersRatio < 1.0) + eimv[eimv_Fful] = 0; + //*std::min(1,(Vel-eimc[eimc_p_Vh0])/(eimc[eimc_p_Vh1]-eimc[eimc_p_Vh0])) + } + else + { + eimv[eimv_Fful] = std::min(std::min(3.6 * eimv[eimv_Pmax] / std::max(Vel, 1.), eimc[eimc_p_F0] - Vel * eimc[eimc_p_a1]), eimv[eimv_FMAXMAX]); + // if(not Flat)then + eimv[eimv_Fmax] = eimv[eimv_Fful] * eimv_pr; + // else + // eimv[eimv_Fmax]:=std::min(eimc[eimc_p_F0]*eimv_pr,eimv[eimv_Fful]); + double pr = eimv_pr; + if (EIMCLogForce) + pr = log(1 + 4 * pr) / log(5); + eimv[eimv_Fr] = eimv[eimv_Fful] * pr; + } +} + +// the frequency of the inverters at the motors' slip frequency, from the list of the drive or of its brake +void TMoverParameters::UpdateInverterFrequency() +{ + auto const tmpV{std::abs(eimv[eimv_fp])}; + auto const useFFEDList = FFEDListSize > 0 && DynamicBrakeFlag; + auto const list = useFFEDList ? FFEDlist : FFlist; + + if (auto const listSize = useFFEDList ? FFEDListSize : FFListSize; listSize > 0 && std::abs(eimv[eimv_If]) > 1.0 && tmpV > 0.0001) + { + + int i = 0; + while (i < listSize - 1 && list[i + 1].v < tmpV) + { + ++i; + } + InverterFrequency = (tmpV - list[i].v) / std::max(1.0, list[i + 1].v - list[i].v) * (list[i + 1].freq - list[i].freq) + list[i].freq; + } + else + { + InverterFrequency = 0.0; + } +} + +// the induction motor drive without power, or blocked by the security system +void TMoverParameters::InductionMotorOff() +{ + for (auto &inv : Inverters) + { + inv.Freal = 0.0; + inv.IsActive = false; + } + Im = 0.0; + Mm = 0.0; + Mw = 0.0; + Fw = 0.0; + Ft = 0.0; + Itot = 0.0; + eimv_pr = 0.0; + EnginePower = 0.0; + { + for (auto &eimvvalue : eimv) + eimvvalue = 0.0; + } + Hamulec->SetED(0.0); + InverterFrequency = 0.0; //(Hamulec as TLSt).SetLBP(LocBrakePress); +} + +// ************************************************************************************************* +// Q: 20160713 +// Sprawdzenie bezpiecznika nadmiarowego +// ************************************************************************************************* +bool TMoverParameters::FuseFlagCheck(void) const +{ + bool FFC; + + FFC = false; + if (Power > 0.01) + FFC = FuseFlag; + else // pobor pradu jezeli niema mocy + for (auto &thiscoupler : Couplers) + if (TestFlag(thiscoupler.CouplingFlag, coupling::control) && thiscoupler.Connected->Power > 0.01) + FFC = thiscoupler.Connected->FuseFlagCheck(); + + return FFC; +} + +// ************************************************************************************************* +// Q: 20160713 +// Załączenie bezpiecznika nadmiarowego +// ************************************************************************************************* +bool TMoverParameters::FuseOn(range_t const Notify) +{ + auto const result{RelayReset(relay_t::maincircuitground | relay_t::tractionnmotoroverload, Notify)}; + + return result; +} + +// ************************************************************************************************* +// Q: 20160713 +// Wyłączenie bezpiecznika nadmiarowego +// ************************************************************************************************* +void TMoverParameters::FuseOff(void) +{ + if (!FuseFlag) + { + FuseFlag = true; + EventFlag = true; + SetFlag(SoundFlag, sound::relay | sound::loud); + } +} + +// resets relays assigned to specified customizable reset button +bool TMoverParameters::UniversalResetButton(int const Button, range_t const Notify) +{ + + if (auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; false == lowvoltagepower) + { + return false; + } + + auto const relays{UniversalResetButtonFlag[Button]}; + if (relays == 0) + { + return false; + } + + auto const result{RelayReset(relays, Notify)}; + + return result; +} + +// resets state of specified relays +bool TMoverParameters::RelayReset(int const Relays, range_t const Notify) +{ + + auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; + bool reset{false}; + + if (TestFlag(Relays, relay_t::maincircuitground) && (EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric) && + (GroundRelayStart == start_t::manual || GroundRelayStart == start_t::manualwithautofallback) && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0 && DirActive != 0 && + !TestFlag(EngDmgFlag, 1)) + { + // NOTE: true means the relay is operational + reset |= !GroundRelay && lowvoltagepower; + GroundRelay |= lowvoltagepower; + } + + if (TestFlag(Relays, relay_t::tractionnmotoroverload) && (EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric) && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0 && DirActive != 0 && + !TestFlag(EngDmgFlag, 1)) + { + // NOTE: false means the relay is operational + // TODO: cleanup, flip the FuseFlag code to match other relays + // TODO: check whether the power is required, TBD, TODO: make it configurable? + reset |= FuseFlag && lowvoltagepower; + FuseFlag &= !lowvoltagepower; + } + + if (TestFlag(Relays, relay_t::primaryconverteroverload) && ConverterOverloadRelayStart == start_t::manual + // && ( false == Mains ) + && false == ConverterAllow) + { + // NOTE: false means the relay is operational + // TODO: cleanup, flip the FuseFlag code to match other relays + // TODO: check whether the power is required, TBD, TODO: make it configurable? + reset |= ConvOvldFlag && lowvoltagepower; + ConvOvldFlag &= !lowvoltagepower; + } + + if (reset) + { + SetFlag(SoundFlag, sound::relay | sound::loud); + } + + if (Notify != range_t::local) + { + SendCtrlToNext("RelayReset", Relays, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return reset; +} + +// ************************************************************************************************* +// Q: 20160713 +// Przeliczenie prędkości liniowej na obrotową +// ************************************************************************************************* +double TMoverParameters::v2n(void) +{ + // przelicza predkosc liniowa na obrotowa + const double dmgn = 0.5; + double n; + double deltan = 0; + + n = V / (M_PI * WheelDiameter); // predkosc obrotowa wynikajaca z liniowej [obr/s] + deltan = n - nrot; //"pochodna" prędkości obrotowej + /* if (SlippingWheels) + if (std::abs(deltan) < 0.001) + SlippingWheels = false; // wygaszenie poslizgu */ //poslizg jest w innym miejscu wygaszany też + if (SlippingWheels) // nie ma zwiazku z predkoscia liniowa V + { // McZapkie-221103: uszkodzenia kol podczas poslizgu + if (deltan > dmgn && FuzzyLogic(deltan, dmgn, p_slippdmg) && SetFlag(DamageFlag, dtrain_wheelwear)) // podkucie + EventFlag = true; + if (deltan < -dmgn && FuzzyLogic(-deltan, dmgn, p_slippdmg) && SetFlag(DamageFlag, dtrain_thinwheel)) // wycieranie sie obreczy + EventFlag = true; + n = nrot; // predkosc obrotowa nie zalezy od predkosci liniowej + } + return n; +} + +// ************************************************************************************************* +// Q: 20160714 +// Oblicza moment siły wytwarzany przez silnik +// ************************************************************************************************* +double TMoverParameters::Momentum(double I) const +{ + // liczy moment sily wytwarzany przez silnik elektryczny} + int SP; + + SP = ScndCtrlActualPos; + if (ScndInMain && !(RList[MainCtrlActualPos].ScndAct == 255)) + SP = RList[MainCtrlActualPos].ScndAct; + + // Momentum:=mfi*I*(1-1.0/(Abs(I)/mIsat+1)); + return motor_param(SP).mfi * I * (abs(I) / (abs(I) + motor_param(SP).mIsat) - motor_param(SP).mfi0); +} + +// ************************************************************************************************* +// Q: 20160714 +// Oblicza moment siły do sterowania wzbudzeniem +// ************************************************************************************************* +double TMoverParameters::MomentumF(double I, double Iw, int SCP) const +{ + // umozliwia dokladne sterowanie wzbudzeniem + + return motor_param(SCP).mfi * I * std::max(abs(Iw) / (abs(Iw) + motor_param(SCP).mIsat) - motor_param(SCP).mfi0, 0.); +} + +// ************************************************************************************************* +// Q: 20160713 +// Odłączenie uszkodzonych silników +// ************************************************************************************************* +bool TMoverParameters::CutOffEngine(void) +{ + bool COE = false; // Ra: wartość domyślna, sprawdzić to trzeba + if (NPoweredAxles > 0 && CabActive == 0 && EngineType == TEngineType::ElectricSeriesMotor && SetFlag(DamageFlag, -dtrain_engine)) + { + NPoweredAxles = NPoweredAxles / 2; // bylo div czyli mod? + COE = true; + } + return COE; +} + +// ************************************************************************************************* +// Q: 20160713 +// Przełączenie wysoki / niski prąd rozruchu +// ************************************************************************************************* +bool TMoverParameters::MaxCurrentSwitch(bool State, range_t const Notify) +{ + auto const initialstate{MotorOverloadRelayHighThreshold}; + + MotorOverloadRelayHighThreshold = State; + + if (Notify != range_t::local) + { + SendCtrlToNext("MaxCurrentSwitch", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + } + + return State != initialstate; +} + +// ************************************************************************************************* +// Q: 20160713 +// Przełączenie wysoki / niski prąd rozruchu automatycznego +// ************************************************************************************************* +bool TMoverParameters::MinCurrentSwitch(bool State) +{ + bool MCS = false; + if ((EngineType == TEngineType::ElectricSeriesMotor && IminHi > IminLo) || (TrainType == train_type::emu && EngineType != TEngineType::ElectricInductionMotor)) + { + + if (State && Imin == IminLo) + { + Imin = IminHi; + MCS = true; + if (CabActive != 0) + SendCtrlToNext("MinCurrentSwitch", 1, CabActive); + } + if (!State && Imin == IminHi) + { + Imin = IminLo; + MCS = true; + if (CabActive != 0) + SendCtrlToNext("MinCurrentSwitch", 0, CabActive); + } + } + return MCS; +} + +// ************************************************************************************************* +// Q: 20160713 +// Sprawdzenie wskaźnika jazdy na oporach +// ************************************************************************************************* +bool TMoverParameters::ResistorsFlagCheck(void) const +{ + bool RFC = false; + + if (Power > 0.01) + RFC = ResistorsFlag; + else // pobor pradu jezeli niema mocy + { + for (auto &thiscoupler : Couplers) + if (TestFlag(thiscoupler.CouplingFlag, coupling::control) && thiscoupler.Connected->Power > 0.01) + RFC = thiscoupler.Connected->ResistorsFlagCheck(); + } + return RFC; +} + +// ************************************************************************************************* +// Q: 20160714 +// Zwraca wartość natężenia prądu na wybranym amperomierzu. Podfunkcja do ShowCurrent. +// ************************************************************************************************* +double TMoverParameters::ShowCurrentP(int AmpN) const +{ + int Bn; + bool Grupowy; + + // ClearPendingExceptions; + Grupowy = DelayCtrlFlag && TrainType == train_type::et22; // przerzucanie walu grupowego w ET22; + Bn = RList[MainCtrlActualPos].Bn; // ile równoległych gałęzi silników + + if (DynamicBrakeType == dbrake_automatic && DynamicBrakeFlag) + Bn = DynamicBrakeAmpmeters; + if (Power > 0.01) + { + if (AmpN > 0) // podać prąd w gałęzi + { + if (Bn < AmpN || (Grupowy && AmpN == Bn - 1)) + return 0; + else // normalne podawanie pradu + return floor(abs(Im)); + } + else // podać całkowity + return floor(abs(Itot)); + } + else // pobor pradu jezeli niema mocy + { + int current = 0; + for (int b = 0; b < 2; b++) + // with Couplers[b] do + if (TestFlag(Couplers[b].CouplingFlag, coupling::control) && Couplers[b].Connected->Power > 0.01) + current = static_cast(Couplers[b].Connected->ShowCurrent(AmpN)); + return current; + } +} From 19f884cdbb31e704e52d6efad4fc14ca9928d8f8 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Fri, 27 Nov 2026 18:53:06 +0100 Subject: [PATCH 004/123] refactor(physics): the vehicle vocabulary in physics/vehicletypes.h; DynObj.h and Driver.h no longer include mover.h DynObj.h included physics/mover.h, so nearly every file of the simulator compiled the whole vehicle physics (TMoverParameters and the brakes) though most of them only name a vehicle end, a coupling or a light. - physics/vehicletypes.h: the enums, flags and small structures the rest of the simulator passes around (end, side, coupling, light, sound, activation, train_type, TEngineType, TBrakeSystem..., TLocation, TTrackShape, neighbour_data), moved from mover.h as they were. mover.h includes it. - DynObj.h and Driver.h include vehicletypes.h; TMoverParameters is forward declared (utilities/Classes.h). Their inline accessors that read the mover (NextConnected(), GetVelocity(), is_emu(), DirectionalVel()...) are defined in DynObj.cpp and Driver.cpp. - the files that use the mover include physics/mover.h themselves. Now 140 of the 730 objects of the build depend on mover.h and brakes.h, about 80 of them unit tests. No change in behaviour: 1142/1142 tests, golden traces exact against staging 62f7a29b. --- application/application.cpp | 1 + application/consistviews.cpp | 1 + application/driverhints.cpp | 1 + application/drivermode.cpp | 1 + application/driveruipanels.cpp | 1 + application/editormode.cpp | 1 + application/editormodeselftestscene.cpp | 1 + audio/sound.cpp | 1 + input/drivermouseinput.cpp | 1 + input/messaging.cpp | 1 + physics/mover.h | 806 +--------------------- physics/vehicletypes.h | 822 +++++++++++++++++++++++ rendering/common/locallights.cpp | 1 + rendering/common/localshadows.cpp | 1 + rendering/common/scenewalk.cpp | 1 + rendering/common/screenreflections.cpp | 1 + rendering/common/windscreenwater.cpp | 1 + rendering/lightarray.cpp | 1 + rendering/opengl46/opengl46renderer.cpp | 1 + rendering/particles.cpp | 1 + rendering/vulkan14/vulkan14frame.cpp | 1 + scene/scene.cpp | 1 + scripting/lua.cpp | 1 + simulation/blackboxrecorder.cpp | 1 + simulation/simulation.cpp | 1 + simulation/simulationstateserializer.cpp | 1 + utilities/motiontelemetry.cpp | 1 + utilities/uart.cpp | 1 + vehicle/Driver.cpp | 19 + vehicle/Driver.h | 27 +- vehicle/DynObj.cpp | 17 + vehicle/DynObj.h | 34 +- vehicle/Train.cpp | 1 + vehicle/crewchange.cpp | 1 + widgets/trainingcard.cpp | 1 + widgets/vehicleparams.cpp | 1 + world/Event.cpp | 1 + world/Road.cpp | 1 + world/RoadPoint.cpp | 1 + world/Track.cpp | 1 + world/TrackBuckle.cpp | 1 + world/TrkFoll.cpp | 1 + world/station.cpp | 1 + 43 files changed, 918 insertions(+), 844 deletions(-) create mode 100644 physics/vehicletypes.h diff --git a/application/application.cpp b/application/application.cpp index 563cba5c1..8181c014e 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -47,6 +47,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include "utilities/translation.h" +#include "physics/mover.h" #if WITH_DISCORD_RPC #include "ref/discord-rpc/include/discord_rpc.h" diff --git a/application/consistviews.cpp b/application/consistviews.cpp index 49815f6e8..ca9d979dd 100644 --- a/application/consistviews.cpp +++ b/application/consistviews.cpp @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Camera.h" #include "vehicle/Driver.h" #include "vehicle/DynObj.h" +#include "physics/mover.h" namespace { diff --git a/application/driverhints.cpp b/application/driverhints.cpp index cd1967aa2..3851b91e7 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Driver.h" #include "utilities/Globals.h" #include "utilities/utilities.h" +#include "physics/mover.h" void TController::hint( driver_hint const Value, hintpredicate const Predicate, float const Predicateparameter ) { diff --git a/application/drivermode.cpp b/application/drivermode.cpp index e76baec1c..20df43a3b 100644 --- a/application/drivermode.cpp +++ b/application/drivermode.cpp @@ -31,6 +31,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "rendering/renderer.h" #include "utilities/Logs.h" +#include "physics/mover.h" #include diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index f577573c9..fd77d352b 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -34,6 +34,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "widgets/vehicleparams.h" #include "utilities/U8.h" +#include "physics/mover.h" #define DRIVER_HINT_CONTENT #include "application/driverhints.h" diff --git a/application/editormode.cpp b/application/editormode.cpp index 2cb34401c..4d858e325 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -20,6 +20,7 @@ http://mozilla.org/MPL/2.0/. #include "application/editorgestures.h" #include "scene/scenenodegroups.h" #include "application/editoruilayer.h" +#include "physics/mover.h" #ifndef _WIN32 #include #include diff --git a/application/editormodeselftestscene.cpp b/application/editormodeselftestscene.cpp index df5d62622..f9315e9e5 100644 --- a/application/editormodeselftestscene.cpp +++ b/application/editormodeselftestscene.cpp @@ -47,6 +47,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include "application/editormodeselftest.h" +#include "physics/mover.h" editor_mode::selftest_result editor_mode::selftest_scene(std::string const &command, std::istringstream &words) { diff --git a/audio/sound.cpp b/audio/sound.cpp index 426ee3cc4..6e5b8ab28 100644 --- a/audio/sound.cpp +++ b/audio/sound.cpp @@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/DynObj.h" #include "simulation/simulation.h" #include "audio/audiorenderer_extra.h" +#include "physics/mover.h" // constructors sound_source::sound_source( sound_placement const Placement, float const Range ) : diff --git a/input/drivermouseinput.cpp b/input/drivermouseinput.cpp index 47105ac22..35d8fbffe 100644 --- a/input/drivermouseinput.cpp +++ b/input/drivermouseinput.cpp @@ -21,6 +21,7 @@ http://mozilla.org/MPL/2.0/. #include "application/uilayer.h" #include "utilities/Logs.h" #include "utilities/utilities.h" +#include "physics/mover.h" auto const EU07_CONTROLLER_MOUSESLIDERSIZE{ 0.6 }; diff --git a/input/messaging.cpp b/input/messaging.cpp index 66a39e7d5..f91da91bd 100644 --- a/input/messaging.cpp +++ b/input/messaging.cpp @@ -19,6 +19,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Driver.h" #include "world/mtable.h" #include "utilities/Logs.h" +#include "physics/mover.h" #ifdef _WIN32 extern "C" diff --git a/physics/mover.h b/physics/mover.h index 0e2211afe..f20b72414 100644 --- a/physics/mover.h +++ b/physics/mover.h @@ -21,6 +21,7 @@ http://mozilla.org/MPL/2.0/. #include "scripting/ladderlogic.h" #include "vehicle/derailmotion.h" #include "vehicle/odometerreading.h" +#include "physics/vehicletypes.h" class cParser; /* @@ -87,804 +88,6 @@ zwiekszenie nacisku przy duzych predkosciach w hamulcach Oerlikona ... */ - -/// Global counter incremented when a string-to-numeric conversion fails during config parsing. -extern int ConversionError; - -/// Static friction coefficient for steel-on-steel contact (used for adhesion at standstill). -const double Steel2Steel_friction = 0.15; // tarcie statyczne -/// Earth gravitational acceleration [m/s^2]. -const double g = 9.81; // przyspieszenie ziemskie -/// Sand consumption rate when sanding is active [kg/s]. -const double SandSpeed = 0.1; // ile kg/s} -/// 2*pi shortcut. -const double Pirazy2 = 6.2831853071794f; - -//-- var, const, procedure --------------------------------------------------- -/// Truthy alias used by CheckLocomotiveParameters() to ignore a check failure. -static bool const Go = true; -/// Falsy alias used by CheckLocomotiveParameters() to abort on a check failure. -static bool const Hold = false; /*dla CheckLocomotiveParameters*/ -/// Maximum number of resistor / scheme entries for electric motor traction. -static int const ResArraySize = 64; /*dla silnikow elektrycznych*/ -/// Maximum number of motor-parameter table entries (gear stages). -static int const MotorParametersArraySize = 10; -/// Maximum number of pantograph current collectors per vehicle. -static int const maxcc = 4; /*max. ilosc odbierakow pradu*/ -// static int const LocalBrakePosNo = 10; /*ilosc nastaw hamulca pomocniczego*/ -// static int const MainBrakeMaxPos = 10; /*max. ilosc nastaw hamulca zasadniczego*/ -/// Number of positions on the manual (parking) brake handle. -static int const ManualBrakePosNo = 20; /*ilosc nastaw hamulca recznego*/ -/// Number of positions on the lights selector switch. -static int const LightsSwitchPosNo = 16; -/// Maximum number of positions of the universal (auxiliary) controller. -static int const UniversalCtrlArraySize = 32; /*max liczba pozycji uniwersalnego nastawnika*/ - -/*uszkodzenia toru*/ -/// Track damage flag: rail wear. -static int const dtrack_railwear = 2; -/// Track damage flag: free / loose rail. -static int const dtrack_freerail = 4; -/// Track damage flag: thin (worn-out) rail. -static int const dtrack_thinrail = 8; -/// Track damage flag: bent rail. -static int const dtrack_railbend = 16; -/// Track damage flag: vegetation overgrowth. -static int const dtrack_plants = 32; -/// Track damage flag: track impassable for movement. -static int const dtrack_nomove = 64; -/// Track damage flag: rails missing entirely. -static int const dtrack_norail = 128; - -/*uszkodzenia taboru*/ -/// Vehicle damage flag: thin wheel (locomotives). -static int const dtrain_thinwheel = 1; /*dla lokomotyw*/ -/// Vehicle damage flag: shifted load (wagons). -static int const dtrain_loadshift = 1; /*dla wagonow*/ -/// Vehicle damage flag: wheel wear. -static int const dtrain_wheelwear = 2; -/// Vehicle damage flag: bearing failure. -static int const dtrain_bearing = 4; -/// Vehicle damage flag: coupling damage. -static int const dtrain_coupling = 8; -/// Vehicle damage flag: ventilator failure (electric locomotive). -static int const dtrain_ventilator = 16; /*dla lokomotywy el.*/ -/// Vehicle damage flag: load damage (wagons). -static int const dtrain_loaddamage = 16; /*dla wagonow*/ -/// Vehicle damage flag: engine failure (locomotives). -static int const dtrain_engine = 32; /*dla lokomotyw*/ -/// Vehicle damage flag: load destroyed (wagons). -static int const dtrain_loaddestroyed = 32; /*dla wagonow*/ -/// Vehicle damage flag: axle damage. -static int const dtrain_axle = 64; -/// Vehicle damage flag: derailment. -static int const dtrain_out = 128; /*wykolejenie*/ -/// Vehicle damage flag: broken pantograph. -static int const dtrain_pantograph = 256; /*polamanie pantografu*/ - -/// Reason for a derailment event. -enum DerailReason -{ - /// No derailment. - NONE = 0, - /// End of track reached. - END_OF_TRACK = 1, // Ra: powód wykolejenia: brak szyn - /// Speed too high for curve (overturn). - TOO_HIGH_SPEED = 2, // Ra: powód wykolejenia: przewrócony na łuku - /// Track gauge does not match wheelset gauge. - GAUGE_MISMATCH = 3, // Ra: powód wykolejenia: za szeroki tor - /// Track type incompatible with this vehicle. - WRONG_TRACK_TYPE = 4, // Ra: powód wykolejenia: nieodpowiednia trajektoria - /// Collision with another vehicle. - COLLISION = 5, // powód wykolejenia: zderzenie z innym pojazdem - /// Trailing through a switch with a movable nose set the other way. - TRAILED_SWITCH = 6, // powód wykolejenia: rozprucie rozjazdu z ruchomym dziobem - /// Climbed onto the vehicle it hit, its end crushed (physics.collisions new). - COLLISION_OVERRIDE = 7, // najechanie - /// Pushed off the track by the force pressing its end (physics.collisions new). - COLLISION_PUSHED_OFF = 8, // wyciśnięcie z toru -}; - -/*wagi prawdopodobienstwa dla funkcji FuzzyLogic*/ -/// Fuzzy-logic probability weight: electric engine general problem. -#define p_elengproblem (1e-02) -/// Fuzzy-logic probability weight: electric engine damage. -#define p_elengdamage (1e-01) -/// Fuzzy-logic probability weight: coupler damage. -#define p_coupldmg (2e-03) -/// Fuzzy-logic probability weight: derailment. -#define p_derail (1e-03) -/// Fuzzy-logic probability weight: acceleration-related event. -#define p_accn (1e-01) -/// Fuzzy-logic probability weight: damage caused by wheel slip. -#define p_slippdmg (1e-03) - -/*typ sprzegu*/ -/// Coupling type: virtual — vehicles share a track and are aware of each other. -static int const ctrain_virtual = 0; // gdy pojazdy na tym samym torze się widzą wzajemnie -/// Coupling type: physical coupler. -static int const ctrain_coupler = 1; // sprzeg fizyczny -/// Coupling type: pneumatic brake hose. -static int const ctrain_pneumatic = 2; // przewody hamulcowe -/// Coupling type: control cable (multiple-unit). -static int const ctrain_controll = 4; // przewody sterujące (ukrotnienie) -/// Coupling type: high-voltage power cable. -static int const ctrain_power = 8; // przewody zasilające (WN) -/// Coupling type: passenger gangway. -static int const ctrain_passenger = 16; // mostek przejściowy -/// Coupling type: secondary 8 atm pneumatic line (yellow, main air). -static int const ctrain_scndpneumatic = 32; // przewody 8 atm (żółte; zasilanie powietrzem) -/// Coupling type: high-voltage train heating cable. -static int const ctrain_heating = 64; // przewody ogrzewania WN -/// Coupling type: permanent (inter-section) — not separable during ordinary shunting; encoded as negative in config files. -static int const ctrain_depot = 128; // nie rozłączalny podczas zwykłych manewrów (międzyczłonowy), we wpisie wartość ujemna -/// Vehicle ends — front or rear (mutually exclusive). -enum end -{ - /// Front end. - front = 0, - /// Rear end. - rear = 1 -}; - -/// Vehicle sides — right or left (mutually exclusive). -enum side -{ - /// Right side. - right = 0, - /// Left side. - left = 1 -}; - -/// Bit flags representing the kind of physical/logical connections in a coupling. Combinable. -enum coupling -{ - /// No coupling (virtual / not connected). - faux = 0x0, - /// Mechanical coupler. - coupler = 0x1, - /// Pneumatic brake hose (PG). - brakehose = 0x2, - /// Control cable (multiple-unit). - control = 0x4, - /// High-voltage cable (traction supply). - highvoltage = 0x8, - /// Passenger gangway. - gangway = 0x10, - /// Main air (8 atm) line — secondary pneumatic supply. - mainhose = 0x20, - /// Train heating cable. - heating = 0x40, - /// Permanent (non-separable) coupling. - permanent = 0x80, - /// 24 V auxiliary power cable. - power24v = 0x100, - /// 110 V auxiliary power cable. - power110v = 0x200, - /// 3-phase 400 V auxiliary power cable. - power3x400v = 0x400, - // uic = 0x1000, -}; -/// Range of effect for a control command (mutually exclusive). -enum class range_t -{ - /// Affects only this vehicle. - local, - /// Affects this multiple-unit (vehicles permanently coupled into a unit). - unit, - /// Affects the entire consist. - consist -}; -/// State of the door closure signalling (SOD) of a vehicle or a consist, ordered from the least to the most -/// severe: the state of a consist is the most severe state of its vehicles. -enum class door_closure_t -{ - /// No doors worked by the crew: the vehicle doesn't take part in the signalling. - none, - /// All doors closed and locked: they can't be opened. - locked, - /// All doors closed, but released: a permit is given, or no lock holds them shut. - released, - /// A door is open, or not fully closed yet. - open -}; -/// Whether the door closure signalling lamp is lit: steadily for locked doors, in the lit phase of the -/// blinking for released ones, never with a door open or with no doors signalled. -bool door_closure_lamp(door_closure_t const State, bool const BlinkLit); -/// Possible settings for an enable/disable input pair (mutually exclusive). -enum class operation_t -{ - /// No input. - none = 0, - /// Enable input held active. - enable, - /// Disable input held active. - disable, - /// Enable button press transition (rising edge). - enable_on, - /// Enable button release transition. - enable_off, - /// Disable button press transition. - disable_on, - /// Disable button release transition. - disable_off, -}; -/// What else the line contactors of a vehicle need before they can close (LineContactorsInterlock in the Cntrl. section). -enum class line_contactors_interlock -{ - /// Nothing more, the legacy behaviour. - none, - /// The converter of the vehicle itself running, where it drives the traction motor fans (ET42). - converter, - /// The traction motor blowers of the vehicle running. - motor_blowers -}; -/// Auto-start method for ancillary devices (mutually exclusive). -enum class start_t -{ - /// Device cannot be started. - disabled, - /// Manual start only. - manual, - /// Starts automatically. - automatic, - /// Manual start with automatic fallback. - manualwithautofallback, - /// Driven by the converter state. - converter, - /// Driven by the battery state. - battery, - /// Driven by direction selector state. - direction -}; -/// Bit flags representing vehicle external lights (positions and types). Combinable. -enum light -{ - - /// Headlight, left. - headlight_left = 1 << 0, - /// Red marker, left. - redmarker_left = 1 << 1, - /// Headlight, upper centre. - headlight_upper = 1 << 2, - // TBD, TODO: redmarker_upper support? - /// Headlight, right. - headlight_right = 1 << 4, - /// Red marker, right. - redmarker_right = 1 << 5, - /// Rear-end markers (combined). - rearendsignals = 1 << 6, - /// Auxiliary light, left (e.g. ditch light). - auxiliary_left = 1 << 7, - /// Auxiliary light, right. - auxiliary_right = 1 << 8, - /// High-beam headlight, left. - highbeamlight_left = 1 << 9, - /// High-beam headlight, right. - highbeamlight_right = 1 << 10 -}; - -/// The cab interior light a position of the light preset selector sets (eu07/maszyna#529). -struct lights_preset_cablight -{ - /// Bits of the optional third column of a LightsList row. - enum flag - { - /// The cab light is on. - light_on = 1 << 0, - /// The cab light is dimmed. - light_dimmed = 1 << 1 - }; - bool light{false}; - bool dim{false}; -}; - -/// Door operation method (who controls them and how) — mutually exclusive. -enum control_t -{ - /// Local; passengers operate manually, doors open/close for the duration of loading. - passenger, // local, opened/closed for duration of loading - /// Remote; driver-operated. - driver, // remote, operated by the driver - /// Local autonomous; close when the vehicle moves and/or after a timeout. - autonomous, // local, closed when vehicle moves and/or after timeout - /// Remote; conductor-operated. - conductor, // remote, operated by the conductor - /// Primarily manual but also responds to remote control. - mixed // primary manual but answers also to remote control -}; -/*typ hamulca elektrodynamicznego*/ -/// Electrodynamic-brake type: no ED brake. -static int const dbrake_none = 0; -/// Electrodynamic-brake type: passive (always on while moving). -static int const dbrake_passive = 1; -/// Electrodynamic-brake type: switchable (driver toggles). -static int const dbrake_switch = 2; -/// Electrodynamic-brake type: reversal (engaged via reverser). -static int const dbrake_reversal = 4; -/// Electrodynamic-brake type: automatic (engages from main brake). -static int const dbrake_automatic = 8; - -/*dzwieki*/ -/// Bit flags identifying sound events emitted by a vehicle. Combinable. -enum sound -{ - /// No sound event. - none, - /// Generic "loud" event flag (e.g. impact / forced action). - loud = 1 << 0, - /// Coupler stretching to its limit. - couplerstretch = 1 << 1, - /// Buffer clash (vehicles colliding). - bufferclash = 1 << 2, - /// Contactor / relay clicking. - relay = 1 << 3, - /// Series-parallel switch operating. - parallel = 1 << 4, - /// Field-shunt contactor operating. - shuntfield = 1 << 5, - /// Generic pneumatic event. - pneumatic = 1 << 6, - /// Coupling detached. - detach = 1 << 7, - /// Mechanical coupler attached. - attachcoupler = 1 << 8, - /// Brake hose attached. - attachbrakehose = 1 << 9, - /// Main air hose attached. - attachmainhose = 1 << 10, - /// Control cable attached. - attachcontrol = 1 << 11, - /// Gangway attached. - attachgangway = 1 << 12, - /// Heating cable attached. - attachheating = 1 << 13, - /// Adapter piece attached to coupler. - attachadapter = 1 << 14, - /// Adapter piece removed from coupler. - removeadapter = 1 << 15, - /// Door-open permission signalling. - doorpermit = 1 << 16, -}; - -/// Bit flags for the customizable reset button — which protective relay it resets. Combinable. -enum relay_t -{ - /// Main circuit ground-fault relay. - maincircuitground = 1 << 0, - /// Auxiliary circuit ground-fault relay. - auxiliarycircuitground = 1 << 1, - /// Traction motor overload relay. - tractionnmotoroverload = 1 << 2, - /// Primary converter overload relay. - primaryconverteroverload = 1 << 3, - /// Secondary converter overload relay. - secondaryconverteroverload = 1 << 4, - /// Ventilator overload relay. - ventillatoroverload = 1 << 5, - /// Heating overload relay. - heatingoverload = 1 << 6, - /// Electrodynamic-brake overload relay. - electrodynamicbrakesoverload = 1 << 7, -}; - -/// Bit flags for actions triggered on cab activation / deactivation. Combinable. -enum activation -{ - /// Engage the emergency brake. - emergencybrake = 1 << 0, - /// Operate cab mirrors. - mirrors = 1 << 1, - /// Raise the pantographs. - pantographsup = 1 << 2, - /// Switch on red end-of-train markers. - redmarkers = 1 << 3, - /// Set door-open permit. - doorpermition = 1 << 4, - /// Engage the spring brake. - springbrakeon = 1 << 5, - /// Release the spring brake. - springbrakeoff = 1 << 6, - /// Place the reverser in neutral. - neutraldirection = 1 << 7, -}; - -/// The vehicles the code handles in a way of their own, by the Type of the Param section of the .fiz -/// (TrainType). A vehicle is of one of them; a .fiz type not listed is generic. -enum class train_type -{ - /// No handling of its own. - generic, - /// Electric multiple unit (Type=EZT). - emu, - /// Diesel multiple unit (Type=DMU). - dmu, - /// ET22 locomotive (Type=ET22, since the Megapack). - et22, - /// ET40 locomotive. - et40, - /// ET41 locomotive. - et41, - /// ET42 locomotive. - et42, - /// EP05 locomotive. - ep05, - /// SN61 railcar: the type is read, but nothing handles it on its own. - sn61, - /// Pseudo-diesel (an electric drivetrain with the input model of a diesel). - pseudodiesel, - /// Škoda 181 and 182 locomotives (Type=181 or 182). - skoda181, -}; - -// stałe dla asynchronów -/// EIM config index: dfic — frequency rise rate at start. -static int const eimc_s_dfic = 0; -/// EIM config index: dfmax — maximum frequency rate of change. -static int const eimc_s_dfmax = 1; -/// EIM config index: p — number of pole pairs. -static int const eimc_s_p = 2; -/// EIM config index: cfu — voltage / frequency conversion coefficient. -static int const eimc_s_cfu = 3; -/// EIM config index: cim — current / current conversion coefficient. -static int const eimc_s_cim = 4; -/// EIM config index: icif — magnetisation current ratio. -static int const eimc_s_icif = 5; -/// EIM config index: Uzmax — maximum DC link voltage. -static int const eimc_f_Uzmax = 7; -/// EIM config index: Uzh — DC link voltage at field-weakening transition. -static int const eimc_f_Uzh = 8; -/// EIM config index: DU — voltage drop at the converter. -static int const eimc_f_DU = 9; -/// EIM config index: I0 — no-load magnetising current. -static int const eimc_f_I0 = 10; -/// EIM config index: cfu — V/f gain in normal mode. -static int const eimc_f_cfu = 11; -/// EIM config index: cfuH — V/f gain in field-weakening region. -static int const eimc_f_cfuH = 12; -/// EIM config index: F0 — starting force at zero speed. -static int const eimc_p_F0 = 13; -/// EIM config index: a1 — force-frequency slope coefficient. -static int const eimc_p_a1 = 14; -/// EIM config index: Pmax — maximum power. -static int const eimc_p_Pmax = 15; -/// EIM config index: Fh — force at field-weakening point. -static int const eimc_p_Fh = 16; -/// EIM config index: Ph — power at field-weakening point. -static int const eimc_p_Ph = 17; -/// EIM config index: Vh0 — speed where field weakening begins. -static int const eimc_p_Vh0 = 18; -/// EIM config index: Vh1 — speed of full field weakening. -static int const eimc_p_Vh1 = 19; -/// EIM config index: Imax — maximum motor current. -static int const eimc_p_Imax = 20; -/// EIM config index: abed — anti-skid set point. -static int const eimc_p_abed = 21; -/// EIM config index: eped — EP brake intensity bias. -static int const eimc_p_eped = 22; - -// zmienne dla asynchronów -/// EIM variable index: FMAXMAX — absolute maximum allowable force. -static int const eimv_FMAXMAX = 0; -/// EIM variable index: Fmax — current force limit. -static int const eimv_Fmax = 1; -/// EIM variable index: ks — slip coefficient. -static int const eimv_ks = 2; -/// EIM variable index: df — frequency offset. -static int const eimv_df = 3; -/// EIM variable index: fp — base frequency. -static int const eimv_fp = 4; -/// EIM variable index: U — applied voltage. -static int const eimv_U = 5; -/// EIM variable index: pole — pole-pair indicator. -static int const eimv_pole = 6; -/// EIM variable index: Ic — control current. -static int const eimv_Ic = 7; -/// EIM variable index: If — field current. -static int const eimv_If = 8; -/// EIM variable index: M — torque. -static int const eimv_M = 9; -/// EIM variable index: Fr — actual force. -static int const eimv_Fr = 10; -/// EIM variable index: Ipoj — line current. -static int const eimv_Ipoj = 11; -/// EIM variable index: Pm — mechanical power. -static int const eimv_Pm = 12; -/// EIM variable index: Pe — electrical power. -static int const eimv_Pe = 13; -/// EIM variable index: eta — efficiency. -static int const eimv_eta = 14; -/// EIM variable index: fkr — critical frequency. -static int const eimv_fkr = 15; -/// EIM variable index: Uzsmax — maximum measured DC link voltage. -static int const eimv_Uzsmax = 16; -/// EIM variable index: Pmax — instantaneous power limit. -static int const eimv_Pmax = 17; -/// EIM variable index: Fzad — set-point force. -static int const eimv_Fzad = 18; -/// EIM variable index: Imax — maximum allowed current. -static int const eimv_Imax = 19; -/// EIM variable index: Fful — full force. -static int const eimv_Fful = 20; - -/// Brake-of-mode flag: PS (pneumatic, primary). -static int const bom_PS = 1; -/// Brake-of-mode flag: PN (pneumatic, no electrodynamic). -static int const bom_PN = 2; -/// Brake-of-mode flag: EP (electro-pneumatic). -static int const bom_EP = 4; -/// Brake-of-mode flag: MED (mixed pneumatic+ED). -static int const bom_MED = 8; - -/// Bit flags reporting vehicle problems that prevent driving. -enum TProblem // lista problemów taboru, które uniemożliwiają jazdę -{ // flagi bitowe - /// The vehicle has the brake applied or seized axles. - pr_Hamuje = 1, // pojazd ma załączony hamulec lub zatarte osie - /// The vehicle requires pantographs to be inflated/raised. - pr_Pantografy = 2, // pojazd wymaga napompowania pantografów - /// Reserved sentinel — last bit flag. - pr_Ostatni = 0x80000000 // ostatnia flaga bitowa -}; - -/// Compressor parameter list — indices into the compressor programmer table. -enum TCompressorList // lista parametrów w programatorze sprężarek -{ // pozycje kolejne - /// Compressor enable permission (0/1). - cl_Allow = 0, // zezwolenie na pracę sprężarek - /// Compressor output multiplier. - cl_SpeedFactor = 1, // mnożnik wydajności - /// Pressure-switch lower threshold multiplier. - cl_MinFactor = 2, // mnożnik progu załącznika ciśnieniowego - /// Pressure-switch upper threshold multiplier. - cl_MaxFactor = 3 // mnożnik progu wyłącznika ciśnieniowego -}; - -/// 3-D position in world coordinates [m]. -struct TLocation -{ - /// X coordinate. - double X; - /// Y coordinate (vertical). - double Y; - /// Z coordinate. - double Z; -}; - -/// Euler-angle rotation (radians) around X / Y / Z axes. -struct TRotation -{ - /// Rotation around X axis. - double Rx; - /// Rotation around Y axis. - double Ry; - /// Rotation around Z axis. - double Rz; -}; - -/// Vehicle bounding box (width × length × height [m]). -struct TDimension -{ - /// Width. - double W = 0.0; - /// Length. - double L = 0.0; - /// Height. - double H = 0.0; -}; - -/// A pending command queued for the vehicle, with its arguments and propagation rules. -struct TCommand -{ - /// Command name. - std::string Command; /*komenda*/ - /// First numeric argument. - double Value1 = 0.0; /*argumenty komendy*/ - /// Second numeric argument. - double Value2 = 0.0; - /// Coupling flag controlling how the command propagates between vehicles. - int Coupling{coupling::control}; // coupler flag used to determine command propagation - /// World-space location associated with the command. - TLocation Location; -}; - -/*tory*/ -/// Geometric shape of a track segment under the vehicle. -struct TTrackShape -{ /*ksztalt odcinka*/ - /// Curvature radius [m]; 0 means straight track. - double R = 0.0; // promien - /// Segment length [m]. - double Len = 0.0; // dlugosc - /// Track gradient (rise/run). - double dHtrack = 0.0; // nachylenie - /// Track cant / superelevation. - double dHrail = 0.0; // przechylka - /// Lateral curvature of the track unevenness under the vehicle [1/m], see world/TrackUneven.h. - double uneven_curvature = 0.0; - /// Cross level unevenness of the track [mm]. - double uneven_cross = 0.0; - /// Curvature a buckle of the track adds under the body [1/m], positive with the curve, see world/TrackBuckle.h. - double buckle_curvature = 0.0; -}; - -/// Per-segment track parameters: gauge, friction, category, load capacity, damage. -struct TTrackParam -{ /*parametry odcinka - szerokosc, tarcie statyczne, kategoria, obciazalnosc w t/os, uszkodzenia*/ - /// Track gauge / width [m]. - double Width = 0.0; - /// Static friction coefficient on this segment. - double friction = 0.0; - /// Track category bit flags. - int CategoryFlag = 0; - /// Track-quality bit flags. - int QualityFlag = 0; - /// Track-damage bit flags (dtrack_*). - int DamageFlag = 0; - /// Maximum allowed velocity on this segment (used by AI driver). - double Velmax; /*dla uzytku maszynisty w ai_driver*/ - /// Name of the track, for the log; nullptr where there is none. - std::string const *Name = nullptr; -}; - -/// Traction-supply parameters at the vehicle's current location. -struct TTractionParam -{ - /// Catenary voltage [V]. - double TractionVoltage = 0.0; /*napiecie*/ - /// Catenary frequency [Hz] (0 for DC). - double TractionFreq = 0.0; /*czestotliwosc*/ - /// Maximum current capacity [A]. - double TractionMaxCurrent = 0.0; /*obciazalnosc*/ - /// Pantograph-catenary contact resistance [Ω]. - double TractionResistivity = 0.0; /*rezystancja styku*/ -}; -/*powyzsze parametry zwiazane sa z torem po ktorym aktualnie pojazd jedzie*/ - -// what a horn needs to sound: air from the main reservoir, or the low voltage -enum class horn_supply -{ - air, - electric -}; - -/// High-level brake-system family. -enum class TBrakeSystem -{ - /// Individual (vehicle-only) brake. - Individual, - /// Pneumatic brake (Westinghouse-style). - Pneumatic, - /// Electro-pneumatic brake. - ElectroPneumatic -}; -/// Brake-system subtype identifying the manufacturer's distributor family. -enum class TBrakeSubSystem -{ - ss_None, - ss_W, - ss_K, - ss_KK, - ss_Hik, - ss_ESt, - ss_KE, - ss_LSt, - ss_MT, - ss_Dako -}; -/// Specific brake-distributor (valve) model. -enum class TBrakeValve -{ - NoValve, - W, - W_Lu_VI, - W_Lu_L, - W_Lu_XR, - K, - Kg, - Kp, - Kss, - Kkg, - Kkp, - Kks, - Hikg1, - Hikss, - Hikp1, - KE, - SW, - EStED, - NESt3, - ESt3, - LSt, - ESt4, - ESt3AL2, - EP1, - EP2, - M483, - CV1_L_TR, - CV1, - CV1_R, - Other -}; -/// Specific driver's brake-handle model (cab valve). -enum class TBrakeHandle -{ - NoHandle, - West, - FV4a, - M394, - M254, - FVE408, - FVel6, - D2, - Knorr, - FD1, - BS2, - testH, - St113, - MHZ_P, - MHZ_T, - MHZ_EN57, - MHZ_K5P, - MHZ_K8P, - MHZ_6P -}; -/// Type of the auxiliary (independent) brake. -enum class TLocalBrake -{ - NoBrake, - ManualBrake, - PneumaticBrake, - HydraulicBrake -}; -/// Brake delay parameter table (apply/release for passenger and freight). -using TBrakeDelayTable = double[4]; - -/// One row of the brake pressure / pipe pressure / flow-speed table for a brake handle position. -struct TBrakePressure -{ - /// Brake pipe pressure target [bar]. - double PipePressureVal = 0.0; - /// Brake cylinder pressure target [bar]. - double BrakePressureVal = 0.0; - /// Flow speed (orifice scaling). - double FlowSpeedVal = 0.0; - /// Brake system this entry applies to. - TBrakeSystem BrakeType = TBrakeSystem::Pneumatic; -}; - -/// Brake pressure table indexed by handle position. -using TBrakePressureTable = std::map; - -/// Engine / drive type. -enum class TEngineType -{ - None, - Dumb, - WheelsDriven, - ElectricSeriesMotor, - ElectricInductionMotor, - DieselEngine, - SteamEngine, - DieselElectric, - Main -}; -/// Form of energy supplied by the power source. -enum class TPowerType -{ - NoPower, - BioPower, - MechPower, - ElectricPower, - SteamPower -}; -/// Fuel type for combustion engines. -enum class TFuelType -{ - Undefined, - Coal, - Oil -}; /// Steam-locomotive grate parameters. struct TGrateType { @@ -1360,13 +563,6 @@ struct TCoupling } }; -class TDynamicObject; -struct neighbour_data -{ - TDynamicObject *vehicle{nullptr}; // detected obstacle - int vehicle_end{-1}; // facing end of the obstacle - float distance{10000.f}; // distance to the obstacle // NOTE: legacy value. TBD, TODO: use standard -1 instead? -}; struct speed_control { diff --git a/physics/vehicletypes.h b/physics/vehicletypes.h new file mode 100644 index 000000000..b8160ab3d --- /dev/null +++ b/physics/vehicletypes.h @@ -0,0 +1,822 @@ +/* +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 vocabulary of the vehicles: their ends, sides, couplings, lights, sounds, types of drive and brake, the +// flags and the small structures the rest of the simulator passes around without needing the physics itself + +#pragma once + +#include +#include + +/// Global counter incremented when a string-to-numeric conversion fails during config parsing. +extern int ConversionError; + +/// Static friction coefficient for steel-on-steel contact (used for adhesion at standstill). +const double Steel2Steel_friction = 0.15; // tarcie statyczne +/// Earth gravitational acceleration [m/s^2]. +const double g = 9.81; // przyspieszenie ziemskie +/// Sand consumption rate when sanding is active [kg/s]. +const double SandSpeed = 0.1; // ile kg/s} +/// 2*pi shortcut. +const double Pirazy2 = 6.2831853071794f; + +//-- var, const, procedure --------------------------------------------------- +/// Truthy alias used by CheckLocomotiveParameters() to ignore a check failure. +static bool const Go = true; +/// Falsy alias used by CheckLocomotiveParameters() to abort on a check failure. +static bool const Hold = false; /*dla CheckLocomotiveParameters*/ +/// Maximum number of resistor / scheme entries for electric motor traction. +static int const ResArraySize = 64; /*dla silnikow elektrycznych*/ +/// Maximum number of motor-parameter table entries (gear stages). +static int const MotorParametersArraySize = 10; +/// Maximum number of pantograph current collectors per vehicle. +static int const maxcc = 4; /*max. ilosc odbierakow pradu*/ +// static int const LocalBrakePosNo = 10; /*ilosc nastaw hamulca pomocniczego*/ +// static int const MainBrakeMaxPos = 10; /*max. ilosc nastaw hamulca zasadniczego*/ +/// Number of positions on the manual (parking) brake handle. +static int const ManualBrakePosNo = 20; /*ilosc nastaw hamulca recznego*/ +/// Number of positions on the lights selector switch. +static int const LightsSwitchPosNo = 16; +/// Maximum number of positions of the universal (auxiliary) controller. +static int const UniversalCtrlArraySize = 32; /*max liczba pozycji uniwersalnego nastawnika*/ + +/*uszkodzenia toru*/ +/// Track damage flag: rail wear. +static int const dtrack_railwear = 2; +/// Track damage flag: free / loose rail. +static int const dtrack_freerail = 4; +/// Track damage flag: thin (worn-out) rail. +static int const dtrack_thinrail = 8; +/// Track damage flag: bent rail. +static int const dtrack_railbend = 16; +/// Track damage flag: vegetation overgrowth. +static int const dtrack_plants = 32; +/// Track damage flag: track impassable for movement. +static int const dtrack_nomove = 64; +/// Track damage flag: rails missing entirely. +static int const dtrack_norail = 128; + +/*uszkodzenia taboru*/ +/// Vehicle damage flag: thin wheel (locomotives). +static int const dtrain_thinwheel = 1; /*dla lokomotyw*/ +/// Vehicle damage flag: shifted load (wagons). +static int const dtrain_loadshift = 1; /*dla wagonow*/ +/// Vehicle damage flag: wheel wear. +static int const dtrain_wheelwear = 2; +/// Vehicle damage flag: bearing failure. +static int const dtrain_bearing = 4; +/// Vehicle damage flag: coupling damage. +static int const dtrain_coupling = 8; +/// Vehicle damage flag: ventilator failure (electric locomotive). +static int const dtrain_ventilator = 16; /*dla lokomotywy el.*/ +/// Vehicle damage flag: load damage (wagons). +static int const dtrain_loaddamage = 16; /*dla wagonow*/ +/// Vehicle damage flag: engine failure (locomotives). +static int const dtrain_engine = 32; /*dla lokomotyw*/ +/// Vehicle damage flag: load destroyed (wagons). +static int const dtrain_loaddestroyed = 32; /*dla wagonow*/ +/// Vehicle damage flag: axle damage. +static int const dtrain_axle = 64; +/// Vehicle damage flag: derailment. +static int const dtrain_out = 128; /*wykolejenie*/ +/// Vehicle damage flag: broken pantograph. +static int const dtrain_pantograph = 256; /*polamanie pantografu*/ + +/// Reason for a derailment event. +enum DerailReason +{ + /// No derailment. + NONE = 0, + /// End of track reached. + END_OF_TRACK = 1, // Ra: powód wykolejenia: brak szyn + /// Speed too high for curve (overturn). + TOO_HIGH_SPEED = 2, // Ra: powód wykolejenia: przewrócony na łuku + /// Track gauge does not match wheelset gauge. + GAUGE_MISMATCH = 3, // Ra: powód wykolejenia: za szeroki tor + /// Track type incompatible with this vehicle. + WRONG_TRACK_TYPE = 4, // Ra: powód wykolejenia: nieodpowiednia trajektoria + /// Collision with another vehicle. + COLLISION = 5, // powód wykolejenia: zderzenie z innym pojazdem + /// Trailing through a switch with a movable nose set the other way. + TRAILED_SWITCH = 6, // powód wykolejenia: rozprucie rozjazdu z ruchomym dziobem + /// Climbed onto the vehicle it hit, its end crushed (physics.collisions new). + COLLISION_OVERRIDE = 7, // najechanie + /// Pushed off the track by the force pressing its end (physics.collisions new). + COLLISION_PUSHED_OFF = 8, // wyciśnięcie z toru +}; + +/*wagi prawdopodobienstwa dla funkcji FuzzyLogic*/ +/// Fuzzy-logic probability weight: electric engine general problem. +#define p_elengproblem (1e-02) +/// Fuzzy-logic probability weight: electric engine damage. +#define p_elengdamage (1e-01) +/// Fuzzy-logic probability weight: coupler damage. +#define p_coupldmg (2e-03) +/// Fuzzy-logic probability weight: derailment. +#define p_derail (1e-03) +/// Fuzzy-logic probability weight: acceleration-related event. +#define p_accn (1e-01) +/// Fuzzy-logic probability weight: damage caused by wheel slip. +#define p_slippdmg (1e-03) + +/*typ sprzegu*/ +/// Coupling type: virtual — vehicles share a track and are aware of each other. +static int const ctrain_virtual = 0; // gdy pojazdy na tym samym torze się widzą wzajemnie +/// Coupling type: physical coupler. +static int const ctrain_coupler = 1; // sprzeg fizyczny +/// Coupling type: pneumatic brake hose. +static int const ctrain_pneumatic = 2; // przewody hamulcowe +/// Coupling type: control cable (multiple-unit). +static int const ctrain_controll = 4; // przewody sterujące (ukrotnienie) +/// Coupling type: high-voltage power cable. +static int const ctrain_power = 8; // przewody zasilające (WN) +/// Coupling type: passenger gangway. +static int const ctrain_passenger = 16; // mostek przejściowy +/// Coupling type: secondary 8 atm pneumatic line (yellow, main air). +static int const ctrain_scndpneumatic = 32; // przewody 8 atm (żółte; zasilanie powietrzem) +/// Coupling type: high-voltage train heating cable. +static int const ctrain_heating = 64; // przewody ogrzewania WN +/// Coupling type: permanent (inter-section) — not separable during ordinary shunting; encoded as negative in config files. +static int const ctrain_depot = 128; // nie rozłączalny podczas zwykłych manewrów (międzyczłonowy), we wpisie wartość ujemna +/// Vehicle ends — front or rear (mutually exclusive). +enum end +{ + /// Front end. + front = 0, + /// Rear end. + rear = 1 +}; + +/// Vehicle sides — right or left (mutually exclusive). +enum side +{ + /// Right side. + right = 0, + /// Left side. + left = 1 +}; + +/// Bit flags representing the kind of physical/logical connections in a coupling. Combinable. +enum coupling +{ + /// No coupling (virtual / not connected). + faux = 0x0, + /// Mechanical coupler. + coupler = 0x1, + /// Pneumatic brake hose (PG). + brakehose = 0x2, + /// Control cable (multiple-unit). + control = 0x4, + /// High-voltage cable (traction supply). + highvoltage = 0x8, + /// Passenger gangway. + gangway = 0x10, + /// Main air (8 atm) line — secondary pneumatic supply. + mainhose = 0x20, + /// Train heating cable. + heating = 0x40, + /// Permanent (non-separable) coupling. + permanent = 0x80, + /// 24 V auxiliary power cable. + power24v = 0x100, + /// 110 V auxiliary power cable. + power110v = 0x200, + /// 3-phase 400 V auxiliary power cable. + power3x400v = 0x400, + // uic = 0x1000, +}; +/// Range of effect for a control command (mutually exclusive). +enum class range_t +{ + /// Affects only this vehicle. + local, + /// Affects this multiple-unit (vehicles permanently coupled into a unit). + unit, + /// Affects the entire consist. + consist +}; +/// State of the door closure signalling (SOD) of a vehicle or a consist, ordered from the least to the most +/// severe: the state of a consist is the most severe state of its vehicles. +enum class door_closure_t +{ + /// No doors worked by the crew: the vehicle doesn't take part in the signalling. + none, + /// All doors closed and locked: they can't be opened. + locked, + /// All doors closed, but released: a permit is given, or no lock holds them shut. + released, + /// A door is open, or not fully closed yet. + open +}; +/// Whether the door closure signalling lamp is lit: steadily for locked doors, in the lit phase of the +/// blinking for released ones, never with a door open or with no doors signalled. +bool door_closure_lamp(door_closure_t const State, bool const BlinkLit); +/// Possible settings for an enable/disable input pair (mutually exclusive). +enum class operation_t +{ + /// No input. + none = 0, + /// Enable input held active. + enable, + /// Disable input held active. + disable, + /// Enable button press transition (rising edge). + enable_on, + /// Enable button release transition. + enable_off, + /// Disable button press transition. + disable_on, + /// Disable button release transition. + disable_off, +}; +/// What else the line contactors of a vehicle need before they can close (LineContactorsInterlock in the Cntrl. section). +enum class line_contactors_interlock +{ + /// Nothing more, the legacy behaviour. + none, + /// The converter of the vehicle itself running, where it drives the traction motor fans (ET42). + converter, + /// The traction motor blowers of the vehicle running. + motor_blowers +}; +/// Auto-start method for ancillary devices (mutually exclusive). +enum class start_t +{ + /// Device cannot be started. + disabled, + /// Manual start only. + manual, + /// Starts automatically. + automatic, + /// Manual start with automatic fallback. + manualwithautofallback, + /// Driven by the converter state. + converter, + /// Driven by the battery state. + battery, + /// Driven by direction selector state. + direction +}; +/// Bit flags representing vehicle external lights (positions and types). Combinable. +enum light +{ + + /// Headlight, left. + headlight_left = 1 << 0, + /// Red marker, left. + redmarker_left = 1 << 1, + /// Headlight, upper centre. + headlight_upper = 1 << 2, + // TBD, TODO: redmarker_upper support? + /// Headlight, right. + headlight_right = 1 << 4, + /// Red marker, right. + redmarker_right = 1 << 5, + /// Rear-end markers (combined). + rearendsignals = 1 << 6, + /// Auxiliary light, left (e.g. ditch light). + auxiliary_left = 1 << 7, + /// Auxiliary light, right. + auxiliary_right = 1 << 8, + /// High-beam headlight, left. + highbeamlight_left = 1 << 9, + /// High-beam headlight, right. + highbeamlight_right = 1 << 10 +}; + +/// The cab interior light a position of the light preset selector sets (eu07/maszyna#529). +struct lights_preset_cablight +{ + /// Bits of the optional third column of a LightsList row. + enum flag + { + /// The cab light is on. + light_on = 1 << 0, + /// The cab light is dimmed. + light_dimmed = 1 << 1 + }; + bool light{false}; + bool dim{false}; +}; + +/// Door operation method (who controls them and how) — mutually exclusive. +enum control_t +{ + /// Local; passengers operate manually, doors open/close for the duration of loading. + passenger, // local, opened/closed for duration of loading + /// Remote; driver-operated. + driver, // remote, operated by the driver + /// Local autonomous; close when the vehicle moves and/or after a timeout. + autonomous, // local, closed when vehicle moves and/or after timeout + /// Remote; conductor-operated. + conductor, // remote, operated by the conductor + /// Primarily manual but also responds to remote control. + mixed // primary manual but answers also to remote control +}; +/*typ hamulca elektrodynamicznego*/ +/// Electrodynamic-brake type: no ED brake. +static int const dbrake_none = 0; +/// Electrodynamic-brake type: passive (always on while moving). +static int const dbrake_passive = 1; +/// Electrodynamic-brake type: switchable (driver toggles). +static int const dbrake_switch = 2; +/// Electrodynamic-brake type: reversal (engaged via reverser). +static int const dbrake_reversal = 4; +/// Electrodynamic-brake type: automatic (engages from main brake). +static int const dbrake_automatic = 8; + +/*dzwieki*/ +/// Bit flags identifying sound events emitted by a vehicle. Combinable. +enum sound +{ + /// No sound event. + none, + /// Generic "loud" event flag (e.g. impact / forced action). + loud = 1 << 0, + /// Coupler stretching to its limit. + couplerstretch = 1 << 1, + /// Buffer clash (vehicles colliding). + bufferclash = 1 << 2, + /// Contactor / relay clicking. + relay = 1 << 3, + /// Series-parallel switch operating. + parallel = 1 << 4, + /// Field-shunt contactor operating. + shuntfield = 1 << 5, + /// Generic pneumatic event. + pneumatic = 1 << 6, + /// Coupling detached. + detach = 1 << 7, + /// Mechanical coupler attached. + attachcoupler = 1 << 8, + /// Brake hose attached. + attachbrakehose = 1 << 9, + /// Main air hose attached. + attachmainhose = 1 << 10, + /// Control cable attached. + attachcontrol = 1 << 11, + /// Gangway attached. + attachgangway = 1 << 12, + /// Heating cable attached. + attachheating = 1 << 13, + /// Adapter piece attached to coupler. + attachadapter = 1 << 14, + /// Adapter piece removed from coupler. + removeadapter = 1 << 15, + /// Door-open permission signalling. + doorpermit = 1 << 16, +}; + +/// Bit flags for the customizable reset button — which protective relay it resets. Combinable. +enum relay_t +{ + /// Main circuit ground-fault relay. + maincircuitground = 1 << 0, + /// Auxiliary circuit ground-fault relay. + auxiliarycircuitground = 1 << 1, + /// Traction motor overload relay. + tractionnmotoroverload = 1 << 2, + /// Primary converter overload relay. + primaryconverteroverload = 1 << 3, + /// Secondary converter overload relay. + secondaryconverteroverload = 1 << 4, + /// Ventilator overload relay. + ventillatoroverload = 1 << 5, + /// Heating overload relay. + heatingoverload = 1 << 6, + /// Electrodynamic-brake overload relay. + electrodynamicbrakesoverload = 1 << 7, +}; + +/// Bit flags for actions triggered on cab activation / deactivation. Combinable. +enum activation +{ + /// Engage the emergency brake. + emergencybrake = 1 << 0, + /// Operate cab mirrors. + mirrors = 1 << 1, + /// Raise the pantographs. + pantographsup = 1 << 2, + /// Switch on red end-of-train markers. + redmarkers = 1 << 3, + /// Set door-open permit. + doorpermition = 1 << 4, + /// Engage the spring brake. + springbrakeon = 1 << 5, + /// Release the spring brake. + springbrakeoff = 1 << 6, + /// Place the reverser in neutral. + neutraldirection = 1 << 7, +}; + +/// The vehicles the code handles in a way of their own, by the Type of the Param section of the .fiz +/// (TrainType). A vehicle is of one of them; a .fiz type not listed is generic. +enum class train_type +{ + /// No handling of its own. + generic, + /// Electric multiple unit (Type=EZT). + emu, + /// Diesel multiple unit (Type=DMU). + dmu, + /// ET22 locomotive (Type=ET22, since the Megapack). + et22, + /// ET40 locomotive. + et40, + /// ET41 locomotive. + et41, + /// ET42 locomotive. + et42, + /// EP05 locomotive. + ep05, + /// SN61 railcar: the type is read, but nothing handles it on its own. + sn61, + /// Pseudo-diesel (an electric drivetrain with the input model of a diesel). + pseudodiesel, + /// Škoda 181 and 182 locomotives (Type=181 or 182). + skoda181, +}; + +// stałe dla asynchronów +/// EIM config index: dfic — frequency rise rate at start. +static int const eimc_s_dfic = 0; +/// EIM config index: dfmax — maximum frequency rate of change. +static int const eimc_s_dfmax = 1; +/// EIM config index: p — number of pole pairs. +static int const eimc_s_p = 2; +/// EIM config index: cfu — voltage / frequency conversion coefficient. +static int const eimc_s_cfu = 3; +/// EIM config index: cim — current / current conversion coefficient. +static int const eimc_s_cim = 4; +/// EIM config index: icif — magnetisation current ratio. +static int const eimc_s_icif = 5; +/// EIM config index: Uzmax — maximum DC link voltage. +static int const eimc_f_Uzmax = 7; +/// EIM config index: Uzh — DC link voltage at field-weakening transition. +static int const eimc_f_Uzh = 8; +/// EIM config index: DU — voltage drop at the converter. +static int const eimc_f_DU = 9; +/// EIM config index: I0 — no-load magnetising current. +static int const eimc_f_I0 = 10; +/// EIM config index: cfu — V/f gain in normal mode. +static int const eimc_f_cfu = 11; +/// EIM config index: cfuH — V/f gain in field-weakening region. +static int const eimc_f_cfuH = 12; +/// EIM config index: F0 — starting force at zero speed. +static int const eimc_p_F0 = 13; +/// EIM config index: a1 — force-frequency slope coefficient. +static int const eimc_p_a1 = 14; +/// EIM config index: Pmax — maximum power. +static int const eimc_p_Pmax = 15; +/// EIM config index: Fh — force at field-weakening point. +static int const eimc_p_Fh = 16; +/// EIM config index: Ph — power at field-weakening point. +static int const eimc_p_Ph = 17; +/// EIM config index: Vh0 — speed where field weakening begins. +static int const eimc_p_Vh0 = 18; +/// EIM config index: Vh1 — speed of full field weakening. +static int const eimc_p_Vh1 = 19; +/// EIM config index: Imax — maximum motor current. +static int const eimc_p_Imax = 20; +/// EIM config index: abed — anti-skid set point. +static int const eimc_p_abed = 21; +/// EIM config index: eped — EP brake intensity bias. +static int const eimc_p_eped = 22; + +// zmienne dla asynchronów +/// EIM variable index: FMAXMAX — absolute maximum allowable force. +static int const eimv_FMAXMAX = 0; +/// EIM variable index: Fmax — current force limit. +static int const eimv_Fmax = 1; +/// EIM variable index: ks — slip coefficient. +static int const eimv_ks = 2; +/// EIM variable index: df — frequency offset. +static int const eimv_df = 3; +/// EIM variable index: fp — base frequency. +static int const eimv_fp = 4; +/// EIM variable index: U — applied voltage. +static int const eimv_U = 5; +/// EIM variable index: pole — pole-pair indicator. +static int const eimv_pole = 6; +/// EIM variable index: Ic — control current. +static int const eimv_Ic = 7; +/// EIM variable index: If — field current. +static int const eimv_If = 8; +/// EIM variable index: M — torque. +static int const eimv_M = 9; +/// EIM variable index: Fr — actual force. +static int const eimv_Fr = 10; +/// EIM variable index: Ipoj — line current. +static int const eimv_Ipoj = 11; +/// EIM variable index: Pm — mechanical power. +static int const eimv_Pm = 12; +/// EIM variable index: Pe — electrical power. +static int const eimv_Pe = 13; +/// EIM variable index: eta — efficiency. +static int const eimv_eta = 14; +/// EIM variable index: fkr — critical frequency. +static int const eimv_fkr = 15; +/// EIM variable index: Uzsmax — maximum measured DC link voltage. +static int const eimv_Uzsmax = 16; +/// EIM variable index: Pmax — instantaneous power limit. +static int const eimv_Pmax = 17; +/// EIM variable index: Fzad — set-point force. +static int const eimv_Fzad = 18; +/// EIM variable index: Imax — maximum allowed current. +static int const eimv_Imax = 19; +/// EIM variable index: Fful — full force. +static int const eimv_Fful = 20; + +/// Brake-of-mode flag: PS (pneumatic, primary). +static int const bom_PS = 1; +/// Brake-of-mode flag: PN (pneumatic, no electrodynamic). +static int const bom_PN = 2; +/// Brake-of-mode flag: EP (electro-pneumatic). +static int const bom_EP = 4; +/// Brake-of-mode flag: MED (mixed pneumatic+ED). +static int const bom_MED = 8; + +/// Bit flags reporting vehicle problems that prevent driving. +enum TProblem // lista problemów taboru, które uniemożliwiają jazdę +{ // flagi bitowe + /// The vehicle has the brake applied or seized axles. + pr_Hamuje = 1, // pojazd ma załączony hamulec lub zatarte osie + /// The vehicle requires pantographs to be inflated/raised. + pr_Pantografy = 2, // pojazd wymaga napompowania pantografów + /// Reserved sentinel — last bit flag. + pr_Ostatni = 0x80000000 // ostatnia flaga bitowa +}; + +/// Compressor parameter list — indices into the compressor programmer table. +enum TCompressorList // lista parametrów w programatorze sprężarek +{ // pozycje kolejne + /// Compressor enable permission (0/1). + cl_Allow = 0, // zezwolenie na pracę sprężarek + /// Compressor output multiplier. + cl_SpeedFactor = 1, // mnożnik wydajności + /// Pressure-switch lower threshold multiplier. + cl_MinFactor = 2, // mnożnik progu załącznika ciśnieniowego + /// Pressure-switch upper threshold multiplier. + cl_MaxFactor = 3 // mnożnik progu wyłącznika ciśnieniowego +}; + +/// 3-D position in world coordinates [m]. +struct TLocation +{ + /// X coordinate. + double X; + /// Y coordinate (vertical). + double Y; + /// Z coordinate. + double Z; +}; + +/// Euler-angle rotation (radians) around X / Y / Z axes. +struct TRotation +{ + /// Rotation around X axis. + double Rx; + /// Rotation around Y axis. + double Ry; + /// Rotation around Z axis. + double Rz; +}; + +/// Vehicle bounding box (width × length × height [m]). +struct TDimension +{ + /// Width. + double W = 0.0; + /// Length. + double L = 0.0; + /// Height. + double H = 0.0; +}; + +/// A pending command queued for the vehicle, with its arguments and propagation rules. +struct TCommand +{ + /// Command name. + std::string Command; /*komenda*/ + /// First numeric argument. + double Value1 = 0.0; /*argumenty komendy*/ + /// Second numeric argument. + double Value2 = 0.0; + /// Coupling flag controlling how the command propagates between vehicles. + int Coupling{coupling::control}; // coupler flag used to determine command propagation + /// World-space location associated with the command. + TLocation Location; +}; + +/*tory*/ +/// Geometric shape of a track segment under the vehicle. +struct TTrackShape +{ /*ksztalt odcinka*/ + /// Curvature radius [m]; 0 means straight track. + double R = 0.0; // promien + /// Segment length [m]. + double Len = 0.0; // dlugosc + /// Track gradient (rise/run). + double dHtrack = 0.0; // nachylenie + /// Track cant / superelevation. + double dHrail = 0.0; // przechylka + /// Lateral curvature of the track unevenness under the vehicle [1/m], see world/TrackUneven.h. + double uneven_curvature = 0.0; + /// Cross level unevenness of the track [mm]. + double uneven_cross = 0.0; + /// Curvature a buckle of the track adds under the body [1/m], positive with the curve, see world/TrackBuckle.h. + double buckle_curvature = 0.0; +}; + +/// Per-segment track parameters: gauge, friction, category, load capacity, damage. +struct TTrackParam +{ /*parametry odcinka - szerokosc, tarcie statyczne, kategoria, obciazalnosc w t/os, uszkodzenia*/ + /// Track gauge / width [m]. + double Width = 0.0; + /// Static friction coefficient on this segment. + double friction = 0.0; + /// Track category bit flags. + int CategoryFlag = 0; + /// Track-quality bit flags. + int QualityFlag = 0; + /// Track-damage bit flags (dtrack_*). + int DamageFlag = 0; + /// Maximum allowed velocity on this segment (used by AI driver). + double Velmax; /*dla uzytku maszynisty w ai_driver*/ + /// Name of the track, for the log; nullptr where there is none. + std::string const *Name = nullptr; +}; + +/// Traction-supply parameters at the vehicle's current location. +struct TTractionParam +{ + /// Catenary voltage [V]. + double TractionVoltage = 0.0; /*napiecie*/ + /// Catenary frequency [Hz] (0 for DC). + double TractionFreq = 0.0; /*czestotliwosc*/ + /// Maximum current capacity [A]. + double TractionMaxCurrent = 0.0; /*obciazalnosc*/ + /// Pantograph-catenary contact resistance [Ω]. + double TractionResistivity = 0.0; /*rezystancja styku*/ +}; +/*powyzsze parametry zwiazane sa z torem po ktorym aktualnie pojazd jedzie*/ + +// what a horn needs to sound: air from the main reservoir, or the low voltage +enum class horn_supply +{ + air, + electric +}; + +/// High-level brake-system family. +enum class TBrakeSystem +{ + /// Individual (vehicle-only) brake. + Individual, + /// Pneumatic brake (Westinghouse-style). + Pneumatic, + /// Electro-pneumatic brake. + ElectroPneumatic +}; +/// Brake-system subtype identifying the manufacturer's distributor family. +enum class TBrakeSubSystem +{ + ss_None, + ss_W, + ss_K, + ss_KK, + ss_Hik, + ss_ESt, + ss_KE, + ss_LSt, + ss_MT, + ss_Dako +}; +/// Specific brake-distributor (valve) model. +enum class TBrakeValve +{ + NoValve, + W, + W_Lu_VI, + W_Lu_L, + W_Lu_XR, + K, + Kg, + Kp, + Kss, + Kkg, + Kkp, + Kks, + Hikg1, + Hikss, + Hikp1, + KE, + SW, + EStED, + NESt3, + ESt3, + LSt, + ESt4, + ESt3AL2, + EP1, + EP2, + M483, + CV1_L_TR, + CV1, + CV1_R, + Other +}; +/// Specific driver's brake-handle model (cab valve). +enum class TBrakeHandle +{ + NoHandle, + West, + FV4a, + M394, + M254, + FVE408, + FVel6, + D2, + Knorr, + FD1, + BS2, + testH, + St113, + MHZ_P, + MHZ_T, + MHZ_EN57, + MHZ_K5P, + MHZ_K8P, + MHZ_6P +}; +/// Type of the auxiliary (independent) brake. +enum class TLocalBrake +{ + NoBrake, + ManualBrake, + PneumaticBrake, + HydraulicBrake +}; +/// Brake delay parameter table (apply/release for passenger and freight). +using TBrakeDelayTable = double[4]; + +/// One row of the brake pressure / pipe pressure / flow-speed table for a brake handle position. +struct TBrakePressure +{ + /// Brake pipe pressure target [bar]. + double PipePressureVal = 0.0; + /// Brake cylinder pressure target [bar]. + double BrakePressureVal = 0.0; + /// Flow speed (orifice scaling). + double FlowSpeedVal = 0.0; + /// Brake system this entry applies to. + TBrakeSystem BrakeType = TBrakeSystem::Pneumatic; +}; + +/// Brake pressure table indexed by handle position. +using TBrakePressureTable = std::map; + +/// Engine / drive type. +enum class TEngineType +{ + None, + Dumb, + WheelsDriven, + ElectricSeriesMotor, + ElectricInductionMotor, + DieselEngine, + SteamEngine, + DieselElectric, + Main +}; +/// Form of energy supplied by the power source. +enum class TPowerType +{ + NoPower, + BioPower, + MechPower, + ElectricPower, + SteamPower +}; +/// Fuel type for combustion engines. +enum class TFuelType +{ + Undefined, + Coal, + Oil +}; + +class TDynamicObject; +struct neighbour_data +{ + TDynamicObject *vehicle{nullptr}; // detected obstacle + int vehicle_end{-1}; // facing end of the obstacle + float distance{10000.f}; // distance to the obstacle // NOTE: legacy value. TBD, TODO: use standard -1 instead? +}; diff --git a/rendering/common/locallights.cpp b/rendering/common/locallights.cpp index ff6b1465e..5f04155cf 100644 --- a/rendering/common/locallights.cpp +++ b/rendering/common/locallights.cpp @@ -29,6 +29,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Train.h" #include "simulation/simulation.h" #include "rendering/geometrybank.h" +#include "physics/mover.h" namespace { diff --git a/rendering/common/localshadows.cpp b/rendering/common/localshadows.cpp index 87fc056f8..49ce195ce 100644 --- a/rendering/common/localshadows.cpp +++ b/rendering/common/localshadows.cpp @@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/DynObj.h" #include "vehicle/Train.h" #include "rendering/common/skyocclusion.h" +#include "physics/mover.h" namespace gfx { diff --git a/rendering/common/scenewalk.cpp b/rendering/common/scenewalk.cpp index fa95b7670..1a91a1f5c 100644 --- a/rendering/common/scenewalk.cpp +++ b/rendering/common/scenewalk.cpp @@ -30,6 +30,7 @@ http://mozilla.org/MPL/2.0/. #include "model/AnimModel.h" #include "model/Model3d.h" #include "rendering/common/skyocclusion.h" +#include "physics/mover.h" #include #include #include diff --git a/rendering/common/screenreflections.cpp b/rendering/common/screenreflections.cpp index a00ad7f05..0976305b5 100644 --- a/rendering/common/screenreflections.cpp +++ b/rendering/common/screenreflections.cpp @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/DynObj.h" #include "gl/ubo.h" #include "utilities/Globals.h" +#include "physics/mover.h" namespace { diff --git a/rendering/common/windscreenwater.cpp b/rendering/common/windscreenwater.cpp index 9a52eb3fe..78d3a2edc 100644 --- a/rendering/common/windscreenwater.cpp +++ b/rendering/common/windscreenwater.cpp @@ -19,6 +19,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "vehicle/DynObj.h" #include "vehicle/Train.h" +#include "physics/mover.h" namespace gfx { diff --git a/rendering/lightarray.cpp b/rendering/lightarray.cpp index 15020894b..f34a4d183 100644 --- a/rendering/lightarray.cpp +++ b/rendering/lightarray.cpp @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "rendering/lightarray.h" #include "vehicle/DynObj.h" +#include "physics/mover.h" void light_array::insert( TDynamicObject const *Owner ) { diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index 29663ec23..1bbeb17fe 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -29,6 +29,7 @@ http://mozilla.org/MPL/2.0/. #include "rendering/opengl46/opengl46geometrybank.h" #include "rendering/screenshot.h" #include "rendering/editoroverlay.h" +#include "physics/mover.h" #include #include diff --git a/rendering/particles.cpp b/rendering/particles.cpp index 87fc7c0b5..9879cba25 100644 --- a/rendering/particles.cpp +++ b/rendering/particles.cpp @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationenvironment.h" #include "utilities/Logs.h" #include "vehicle/smoke.h" +#include "physics/mover.h" void diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index 9a033978a..12f3cf9b0 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -32,6 +32,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "utilities/utilities.h" #include "utilities/color.h" +#include "physics/mover.h" #include diff --git a/scene/scene.cpp b/scene/scene.cpp index 506b52d67..c8272519f 100644 --- a/scene/scene.cpp +++ b/scene/scene.cpp @@ -24,6 +24,7 @@ http://mozilla.org/MPL/2.0/. #include "rendering/renderer.h" #include "widgets/map_objects.h" #include "vehicle/aiwire.h" +#include "physics/mover.h" #include diff --git a/scripting/lua.cpp b/scripting/lua.cpp index 2011413b5..27224605f 100644 --- a/scripting/lua.cpp +++ b/scripting/lua.cpp @@ -7,6 +7,7 @@ #include "simulation/simulation.h" #include "scripting/luasandbox.h" #include "utilities/utilities.h" +#include "physics/mover.h" lua::lua() { diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index e4161ce61..3599bb1bb 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -26,6 +26,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/physicslog.h" #include "utilities/utilities.h" #include "world/stationnames.h" +#include "physics/mover.h" #include #include diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp index 2eb0a3c89..477203061 100644 --- a/simulation/simulation.cpp +++ b/simulation/simulation.cpp @@ -37,6 +37,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "vehicle/Driver.h" #include "world/catenary_scene.h" +#include "physics/mover.h" namespace simulation { diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index c1fad53ae..69fc726b9 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -37,6 +37,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/utilities.h" #include "editor/editorTerrainStreamer.hpp" +#include "physics/mover.h" #include diff --git a/utilities/motiontelemetry.cpp b/utilities/motiontelemetry.cpp index b0dd02dc1..ed2e9f8fe 100644 --- a/utilities/motiontelemetry.cpp +++ b/utilities/motiontelemetry.cpp @@ -6,6 +6,7 @@ #include "utilities/Timer.h" #include "vehicle/Driver.h" #include "simulation/simulation.h" +#include "physics/mover.h" #ifdef _WIN32 #include diff --git a/utilities/uart.cpp b/utilities/uart.cpp index 632c2b4c6..902c95b5f 100644 --- a/utilities/uart.cpp +++ b/utilities/uart.cpp @@ -9,6 +9,7 @@ #include "utilities/utilities.h" #include "simulation/simulationtime.h" #include "application/application.h" +#include "physics/mover.h" const char* const uart_baudrates_list[] = { "300", diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index eb89088ac..e6b6eff5d 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -14,6 +14,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/Driver.h" +#include "physics/mover.h" #include "utilities/Globals.h" #include "utilities/translation.h" @@ -9661,3 +9662,21 @@ TController::UpdateBrakingHelper() { } } } + +bool TController::is_train() const { + return TestFlag( mvOccupied->CategoryFlag, 1 ); } + +bool TController::is_car() const { + return TestFlag( mvOccupied->CategoryFlag, 2 ); } + +bool TController::is_emu() const { + return mvControlling->TrainType == train_type::emu; } + +bool TController::is_dmu() const { + return mvControlling->TrainType == train_type::dmu; } + +bool TController::has_diesel_engine() const { + return mvControlling->EngineType == TEngineType::DieselElectric || mvControlling->EngineType == TEngineType::DieselEngine; } + +double TController::DirectionalVel() const { + return mvOccupied->Vel * sign( iDirection * mvOccupied->V ); } diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 539542725..04ba00d01 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -13,7 +13,7 @@ http://mozilla.org/MPL/2.0/. #include #include "utilities/Classes.h" #include "utilities/utilities.h" -#include "physics/mover.h" +#include "physics/vehicletypes.h" #include "audio/sound.h" #include "vehicle/DynObj.h" #include "world/mtable.h" @@ -266,22 +266,11 @@ public: inline bool is_active() const { return TestFlag( iDrivigFlags, moveActive ); } - inline - bool is_train() const { - return TestFlag( mvOccupied->CategoryFlag, 1 ); } - inline - bool is_car() const { - return TestFlag( mvOccupied->CategoryFlag, 2 ); } - inline - bool is_emu() const { - return mvControlling->TrainType == train_type::emu; } - inline - bool is_dmu() const { - return mvControlling->TrainType == train_type::dmu; } - inline - bool has_diesel_engine() const { - return mvControlling->EngineType == TEngineType::DieselElectric || mvControlling->EngineType == TEngineType::DieselEngine; - } + bool is_train() const; + bool is_car() const; + bool is_emu() const; + bool is_dmu() const; + bool has_diesel_engine() const; TBrakeSystem consist_brake_system() const; // the next change of the speed limit ahead, as the driving aid tells it: the speed and the distance to it. // the speed is the present limit (VelDesired) when nothing worth telling changes within the scan range @@ -335,9 +324,7 @@ private: inline int DrivigFlags() const { return iDrivigFlags; }; - inline - double DirectionalVel() const { - return mvOccupied->Vel * sign( iDirection * mvOccupied->V ); } + double DirectionalVel() const; double brake_increase_margin() const; bool uphill_stop_hold() const; diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index c37efe824..53a1680b0 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -14,6 +14,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/DynObj.h" +#include "physics/mover.h" #include "vehicle/lightsprogrammer.h" @@ -10425,3 +10426,19 @@ vehicle_table::erase_disabled() { return true; } + +// the vehicles coupled at the ends, and the ends of theirs facing this one +TDynamicObject *TDynamicObject::NextConnected() { return MoverParameters->Neighbours[ end::rear ].vehicle; } +TDynamicObject *TDynamicObject::PrevConnected() { return MoverParameters->Neighbours[ end::front ].vehicle; } +TDynamicObject *TDynamicObject::NextConnected() const { return MoverParameters->Neighbours[ end::rear ].vehicle; } +TDynamicObject *TDynamicObject::PrevConnected() const { return MoverParameters->Neighbours[ end::front ].vehicle; } +int TDynamicObject::NextConnectedNo() const { return MoverParameters->Neighbours[ end::rear ].vehicle_end; } +int TDynamicObject::PrevConnectedNo() const { return MoverParameters->Neighbours[ end::front ].vehicle_end; } + +void TDynamicObject::SetdMoveLen( double dMoveLen ) { MoverParameters->dMoveLen = dMoveLen; } +void TDynamicObject::ResetdMoveLen() { MoverParameters->dMoveLen = 0; } +double TDynamicObject::GetdMoveLen() { return MoverParameters->dMoveLen; } + +double TDynamicObject::GetVelocity() const { return MoverParameters->Vel; } +double TDynamicObject::GetLength() const { return MoverParameters->Dim.L; } +double TDynamicObject::GetWidth() const { return MoverParameters->Dim.W; } diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index 389e6edef..b11ec9e84 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -14,7 +14,9 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Classes.h" #include "interfaces/IMaterial.h" -#include "physics/mover.h" +#include "physics/vehicletypes.h" +#include "physics/derailment.h" +#include "vehicle/derailmotion.h" #include "world/TrkFoll.h" #include "vehicle/Button.h" #include "vehicle/AirCoupler.h" @@ -228,12 +230,12 @@ public: std::string asDestination; // dokąd pojazd ma być kierowany "(stacja):(tor)" glm::dmat4 mMatrix; // macierz przekształcenia do renderowania modeli TMoverParameters *MoverParameters; // parametry fizyki ruchu oraz przeliczanie - inline TDynamicObject *NextConnected() { return MoverParameters->Neighbours[ end::rear ].vehicle; }; // pojazd podłączony od strony sprzęgu 1 (kabina -1) - inline TDynamicObject *PrevConnected() { return MoverParameters->Neighbours[ end::front ].vehicle; }; // pojazd podłączony od strony sprzęgu 0 (kabina 1) - inline TDynamicObject *NextConnected() const { return MoverParameters->Neighbours[ end::rear ].vehicle; }; // pojazd podłączony od strony sprzęgu 1 (kabina -1) - inline TDynamicObject *PrevConnected() const { return MoverParameters->Neighbours[ end::front ].vehicle; }; // pojazd podłączony od strony sprzęgu 0 (kabina 1) - inline int NextConnectedNo() const { return MoverParameters->Neighbours[ end::rear ].vehicle_end; } - inline int PrevConnectedNo() const { return MoverParameters->Neighbours[ end::front ].vehicle_end; } + TDynamicObject *NextConnected(); // pojazd podłączony od strony sprzęgu 1 (kabina -1) + TDynamicObject *PrevConnected(); // pojazd podłączony od strony sprzęgu 0 (kabina 1) + TDynamicObject *NextConnected() const; // pojazd podłączony od strony sprzęgu 1 (kabina -1) + TDynamicObject *PrevConnected() const; // pojazd podłączony od strony sprzęgu 0 (kabina 1) + int NextConnectedNo() const; + int PrevConnectedNo() const; // Dev tools void Reload(); @@ -671,12 +673,9 @@ private: TDynamicObject * PrevAny() const; TDynamicObject * Prev(int C = -1) const; TDynamicObject * Next(int C = -1) const; - void SetdMoveLen(double dMoveLen) { - MoverParameters->dMoveLen = dMoveLen; } - void ResetdMoveLen() { - MoverParameters->dMoveLen = 0; } - double GetdMoveLen() { - return MoverParameters->dMoveLen; } + void SetdMoveLen(double dMoveLen); + void ResetdMoveLen(); + double GetdMoveLen(); int GetPneumatic(bool front, bool red); void SetPneumatic(bool front, bool red); @@ -849,12 +848,9 @@ public: return glm::value_ptr(mMatrix); }; inline double * Matrix() { return glm::value_ptr(mMatrix); }; - inline double GetVelocity() const { - return MoverParameters->Vel; }; - inline double GetLength() const { - return MoverParameters->Dim.L; }; - inline double GetWidth() const { - return MoverParameters->Dim.W; }; + double GetVelocity() const; + double GetLength() const; + double GetWidth() const; double radius() const; // calculates distance between event-starting axle and front of the vehicle double tracing_offset() const; diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 27f23b601..e736bafdf 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -37,6 +37,7 @@ http://mozilla.org/MPL/2.0/. #include "Console.h" #include "application/application.h" #include "rendering/renderer.h" +#include "physics/mover.h" #include #include #include diff --git a/vehicle/crewchange.cpp b/vehicle/crewchange.cpp index e7bf4abe8..8f44556b4 100644 --- a/vehicle/crewchange.cpp +++ b/vehicle/crewchange.cpp @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/DynObj.h" #include "vehicle/Train.h" #include "vehicle/handover.h" +#include "physics/mover.h" namespace crew { diff --git a/widgets/trainingcard.cpp b/widgets/trainingcard.cpp index b261a5d4d..de46f9cd8 100644 --- a/widgets/trainingcard.cpp +++ b/widgets/trainingcard.cpp @@ -2,6 +2,7 @@ #include "widgets/trainingcard.h" #include "simulation/simulation.h" #include "utilities/utilities.h" +#include "physics/mover.h" #ifdef __linux__ #include diff --git a/widgets/vehicleparams.cpp b/widgets/vehicleparams.cpp index c2b140d8a..56f28782b 100644 --- a/widgets/vehicleparams.cpp +++ b/widgets/vehicleparams.cpp @@ -4,6 +4,7 @@ #include "application/driveruipanels.h" #include "vehicle/Driver.h" #include "vehicle/Train.h" +#include "physics/mover.h" ui::vehicleparams_panel::vehicleparams_panel(const std::string &vehicle) : ui_panel(std::string(STR("Vehicle parameters")) + ": " + vehicle, false), m_vehicle_name(vehicle) { diff --git a/world/Event.cpp b/world/Event.cpp index 814cd9918..acd53908c 100644 --- a/world/Event.cpp +++ b/world/Event.cpp @@ -34,6 +34,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "utilities/Logs.h" #include "widgets/map_objects.h" +#include "physics/mover.h" void basic_event::event_conditions::bind( basic_event::node_sequence *Nodes ) { diff --git a/world/Road.cpp b/world/Road.cpp index bbfb9d8cc..58b5fd575 100644 --- a/world/Road.cpp +++ b/world/Road.cpp @@ -20,6 +20,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/parser.h" #include "utilities/utilities.h" +#include "physics/mover.h" namespace { diff --git a/world/RoadPoint.cpp b/world/RoadPoint.cpp index 776d747e4..15ae891ad 100644 --- a/world/RoadPoint.cpp +++ b/world/RoadPoint.cpp @@ -26,6 +26,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/parser.h" #include "utilities/utilities.h" +#include "physics/mover.h" namespace { diff --git a/world/Track.cpp b/world/Track.cpp index 990ff4b0b..6e2824756 100644 --- a/world/Track.cpp +++ b/world/Track.cpp @@ -31,6 +31,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "utilities/Logs.h" #include "rendering/renderer.h" +#include "physics/mover.h" #include diff --git a/world/TrackBuckle.cpp b/world/TrackBuckle.cpp index c8c20fe08..f0328d8d1 100644 --- a/world/TrackBuckle.cpp +++ b/world/TrackBuckle.cpp @@ -15,6 +15,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Globals.h" #include "utilities/Logs.h" #include "vehicle/DynObj.h" +#include "physics/mover.h" #include diff --git a/world/TrkFoll.cpp b/world/TrkFoll.cpp index bc8027f43..6477f9763 100644 --- a/world/TrkFoll.cpp +++ b/world/TrkFoll.cpp @@ -21,6 +21,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/DynObj.h" #include "vehicle/Driver.h" #include "utilities/Logs.h" +#include "physics/mover.h" namespace { diff --git a/world/station.cpp b/world/station.cpp index 90b443e86..5e4dd9590 100644 --- a/world/station.cpp +++ b/world/station.cpp @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/utilities.h" #include "vehicle/DynObj.h" #include "world/mtable.h" +#include "physics/mover.h" namespace simulation { From b82784be92d76d526d8f91e5ab769dab38eda5fe Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Fri, 27 Nov 2026 19:46:26 +0100 Subject: [PATCH 005/123] refactor(vehicle): AnimModel.h, Sweep.h and Camera.h no longer include DynObj.h The scenery models (AnimModel.h), the sweeps (Sweep.h) and the camera (Camera.h, which Globals.h includes) pulled in the whole vehicle header, for one structure (material_data) and a pointer type. - model/materialdata.h/.cpp: material_data and TextureTest(), moved from DynObj.h/.cpp as they were - Camera.h names TDynamicObject through utilities/Classes.h - Classes.h includes interfaces/ITexture.h for null_handle, the value of the handles it defines; AnimModel.h includes utilities/Names.h for basic_table itself. Both came through DynObj.h before. - the files that use the vehicles include vehicle/DynObj.h themselves 164 of the 730 objects of the build depend on DynObj.h now, 304 before. No change in behaviour: 1142/1142 tests, golden traces exact against staging 62f7a29b. --- CMakeLists.txt | 1 + application/editormode.cpp | 1 + input/drivermouseinput.cpp | 1 + model/AnimModel.cpp | 1 + model/AnimModel.h | 3 +- model/materialdata.cpp | 94 +++++++++++++++++++++++++ model/materialdata.h | 30 ++++++++ rendering/common/scenewalkindirect.cpp | 1 + rendering/opengl46/opengl46renderer.cpp | 1 + rendering/particles.cpp | 1 + rendering/vulkan14/vulkan14scene.cpp | 1 + scene/scene.cpp | 1 + tests/unit/test_camera.cpp | 1 + utilities/Classes.h | 2 + vehicle/Camera.h | 2 +- vehicle/DynObj.cpp | 78 -------------------- vehicle/DynObj.h | 11 +-- widgets/map.cpp | 1 + widgets/trainingcard.cpp | 1 + world/Sweep.h | 2 +- 20 files changed, 143 insertions(+), 91 deletions(-) create mode 100644 model/materialdata.cpp create mode 100644 model/materialdata.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 6b723841c..0ce375b50 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -213,6 +213,7 @@ set(SOURCES "input/drivermouseinput.cpp" "utilities/translation.cpp" "model/material.cpp" +"model/materialdata.cpp" "stdafx.cpp" "input/messaging.cpp" "scene/scene.cpp" diff --git a/application/editormode.cpp b/application/editormode.cpp index 4d858e325..1f8b2d224 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -21,6 +21,7 @@ http://mozilla.org/MPL/2.0/. #include "scene/scenenodegroups.h" #include "application/editoruilayer.h" #include "physics/mover.h" +#include "vehicle/DynObj.h" #ifndef _WIN32 #include #include diff --git a/input/drivermouseinput.cpp b/input/drivermouseinput.cpp index 35d8fbffe..468a51dc4 100644 --- a/input/drivermouseinput.cpp +++ b/input/drivermouseinput.cpp @@ -22,6 +22,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/utilities.h" #include "physics/mover.h" +#include "vehicle/DynObj.h" auto const EU07_CONTROLLER_MOUSESLIDERSIZE{ 0.6 }; diff --git a/model/AnimModel.cpp b/model/AnimModel.cpp index 8553d63e5..5f538cdd8 100644 --- a/model/AnimModel.cpp +++ b/model/AnimModel.cpp @@ -24,6 +24,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "utilities/Logs.h" #include "rendering/renderer.h" +#include "vehicle/DynObj.h" std::list> TAnimModel::acAnimList; diff --git a/model/AnimModel.h b/model/AnimModel.h index a66def742..8650165ba 100644 --- a/model/AnimModel.h +++ b/model/AnimModel.h @@ -17,7 +17,8 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Classes.h" #include "utilities/Float3d.h" #include "model/Model3d.h" -#include "vehicle/DynObj.h" +#include "model/materialdata.h" +#include "utilities/Names.h" #include "scene/scenenode.h" const int iMaxNumLights = 8; diff --git a/model/materialdata.cpp b/model/materialdata.cpp new file mode 100644 index 000000000..8d026d71a --- /dev/null +++ b/model/materialdata.cpp @@ -0,0 +1,94 @@ +/* +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 "model/materialdata.h" + +#include "model/Texture.h" +#include "rendering/renderer.h" +#include "utilities/parser.h" +#include "utilities/utilities.h" +#include "utilities/Globals.h" + +// Ra 2015-01: sprawdzenie dostępności tekstury o podanej nazwie +std::string +TextureTest( std::string const &Name ) { + + auto const lookup { + FileExists( + { Global.asCurrentTexturePath + Name, Name, paths::textures + Name }, + { ".mat", ".dds", ".tga", ".ktx", ".png", ".bmp", ".jpg", ".tex" } ) }; + + return lookup.first + lookup.second; +} + +// assigns specified texture or a group of textures to replacable texture slots +void +material_data::assign( std::string const &Replacableskin ) { + + // a template puts its parameter after a folder ("tabl/(p6)"): a texture made by a script given there keeps its scheme + if( auto const scheme { Replacableskin.find( "/make:" ) }; + scheme != std::string::npos + && false == contains( Replacableskin, '|' ) ) { + assign( Replacableskin.substr( scheme + 1 ) ); + return; + } + // check for the pipe method first + if( contains( Replacableskin, '|' ) ) { + cParser nameparser( Replacableskin ); + nameparser.getTokens( 4, false, "|" ); + int skinindex = 0; + std::string texturename; nameparser >> texturename; + while( texturename != "" && skinindex < 4 ) { + replacable_skins[ skinindex + 1 ] = GfxRenderer->Fetch_Material( texturename ); + ++skinindex; + texturename = ""; nameparser >> texturename; + } + multi_textures = skinindex; + } + else { + // otherwise try the basic approach + int skinindex = 0; + do { + // test quietly for file existence so we don't generate tons of false errors in the log + // NOTE: this means actual missing files won't get reported which is hardly ideal, but still somewhat better + auto const material { TextureTest( ToLower( Replacableskin + "," + std::to_string( skinindex + 1 ) ) ) }; + if( true == material.empty() ) { break; } + + replacable_skins[ skinindex + 1 ] = GfxRenderer->Fetch_Material( material ); + ++skinindex; + } while( skinindex < 4 ); + multi_textures = skinindex; + if( multi_textures == 0 ) { + // zestaw nie zadziałał, próbujemy normanie + replacable_skins[ 1 ] = GfxRenderer->Fetch_Material( Replacableskin ); + } + } + if( replacable_skins[ 1 ] == null_handle ) { + // last ditch attempt, check for single replacable skin texture + replacable_skins[ 1 ] = GfxRenderer->Fetch_Material( Replacableskin ); + } + + // BUGS! it's not entierly designed whether opacity is property of material or submodel, + // and code does confusing things with this in various places + textures_alpha = GfxRenderer->Material(replacable_skins[1])->is_translucent() ? 0x31310031 : // tekstura -1 z kanałem alfa - nie renderować w cyklu nieprzezroczystych + 0x30300030; // wszystkie tekstury nieprzezroczyste - nie renderować w cyklu przezroczystych + if( GfxRenderer->Material( replacable_skins[ 2 ] )->is_translucent() ) { + // tekstura -2 z kanałem alfa - nie renderować w cyklu nieprzezroczystych + textures_alpha |= 0x02020002; + } + if( GfxRenderer->Material( replacable_skins[ 3 ] )->is_translucent() ) { + // tekstura -3 z kanałem alfa - nie renderować w cyklu nieprzezroczystych + textures_alpha |= 0x04040004; + } + if( GfxRenderer->Material( replacable_skins[ 4 ] )->is_translucent() ) { + // tekstura -4 z kanałem alfa - nie renderować w cyklu nieprzezroczystych + textures_alpha |= 0x08080008; + } +} diff --git a/model/materialdata.h b/model/materialdata.h new file mode 100644 index 000000000..e149e9e5e --- /dev/null +++ b/model/materialdata.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/. +*/ + +// the replaceable skins of a model: the textures a vehicle or a scenery model puts in place of the replaceable ones + +#pragma once + +#include + +#include "interfaces/IMaterial.h" +#include "utilities/Classes.h" + +struct material_data { + + int textures_alpha{ 0x30300030 }; // maska przezroczystości tekstur. default: tekstury wymienne nie mają przezroczystości + material_handle replacable_skins[ 5 ] = { null_handle, null_handle, null_handle, null_handle, null_handle }; // McZapkie:zmienialne nadwozie + int multi_textures{ 0 }; //<0 tekstury wskazane wpisem, >0 tekstury z przecinkami, =0 jedna + + // assigns specified texture or a group of textures to replacable texture slots + void assign( std::string const &Replacableskin ); +}; + +// the file of the texture or the material of the given name, looked up as the models do; empty when there is none +std::string TextureTest( std::string const &Name ); diff --git a/rendering/common/scenewalkindirect.cpp b/rendering/common/scenewalkindirect.cpp index 85f54b699..e65606827 100644 --- a/rendering/common/scenewalkindirect.cpp +++ b/rendering/common/scenewalkindirect.cpp @@ -19,6 +19,7 @@ http://mozilla.org/MPL/2.0/. #include "model/Model3d.h" #include "utilities/Globals.h" #include "utilities/utilities.h" +#include "vehicle/DynObj.h" #include diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index 1bbeb17fe..f2e611859 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -30,6 +30,7 @@ http://mozilla.org/MPL/2.0/. #include "rendering/screenshot.h" #include "rendering/editoroverlay.h" #include "physics/mover.h" +#include "vehicle/DynObj.h" #include #include diff --git a/rendering/particles.cpp b/rendering/particles.cpp index 9879cba25..67d81f3c2 100644 --- a/rendering/particles.cpp +++ b/rendering/particles.cpp @@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "vehicle/smoke.h" #include "physics/mover.h" +#include "vehicle/DynObj.h" void diff --git a/rendering/vulkan14/vulkan14scene.cpp b/rendering/vulkan14/vulkan14scene.cpp index 75d580bb2..3a25e0fb4 100644 --- a/rendering/vulkan14/vulkan14scene.cpp +++ b/rendering/vulkan14/vulkan14scene.cpp @@ -24,6 +24,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/color.h" #include "utilities/utilities.h" +#include "vehicle/DynObj.h" #include #include diff --git a/scene/scene.cpp b/scene/scene.cpp index c8272519f..bdcb3efb4 100644 --- a/scene/scene.cpp +++ b/scene/scene.cpp @@ -25,6 +25,7 @@ http://mozilla.org/MPL/2.0/. #include "widgets/map_objects.h" #include "vehicle/aiwire.h" #include "physics/mover.h" +#include "vehicle/DynObj.h" #include diff --git a/tests/unit/test_camera.cpp b/tests/unit/test_camera.cpp index 684fadb56..c0a75978d 100644 --- a/tests/unit/test_camera.cpp +++ b/tests/unit/test_camera.cpp @@ -9,6 +9,7 @@ #include "input/command.h" #include "utilities/Timer.h" #include "vehicle/Camera.h" +#include "vehicle/DynObj.h" // the view matrix of the camera (TCamera::SetMatrix): the pitch (Angle.x) and the yaw (Angle.y) give the line of sight, // the roll (Angle.z) turns the view about that line, wherever the camera looks. The roll comes from the sway of the cab diff --git a/utilities/Classes.h b/utilities/Classes.h index 89872d450..b8c470ec9 100644 --- a/utilities/Classes.h +++ b/utilities/Classes.h @@ -9,6 +9,8 @@ http://mozilla.org/MPL/2.0/. #ifndef ClassesH #define ClassesH + +#include "interfaces/ITexture.h" // null_handle, for the handles below //--------------------------------------------------------------------------- // Ra: zestaw klas do robienia wskaźników, aby uporządkować nagłówki //--------------------------------------------------------------------------- diff --git a/vehicle/Camera.h b/vehicle/Camera.h index 5e2f72810..a53aac497 100644 --- a/vehicle/Camera.h +++ b/vehicle/Camera.h @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. #pragma once #include "input/command.h" -#include "vehicle/DynObj.h" +#include "utilities/Classes.h" //--------------------------------------------------------------------------- diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 53a1680b0..5464570cb 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -78,18 +78,6 @@ GetSubmodelFromName( TModel3d * const Model, std::string const Name ) { return Model ? Model->GetFromName(Name) : nullptr; } -// Ra 2015-01: sprawdzenie dostępności tekstury o podanej nazwie -std::string -TextureTest( std::string const &Name ) { - - auto const lookup { - FileExists( - { Global.asCurrentTexturePath + Name, Name, paths::textures + Name }, - { ".mat", ".dds", ".tga", ".ktx", ".png", ".bmp", ".jpg", ".tex" } ) }; - - return lookup.first + lookup.second; -} - //--------------------------------------------------------------------------- void TAnimPant::common_pantograph_settings() { // wspólne ustawienia, liczone po przypisaniu wymiarów ramion @@ -258,72 +246,6 @@ void TAnim::Parovoz(){ */ -// assigns specified texture or a group of textures to replacable texture slots -void -material_data::assign( std::string const &Replacableskin ) { - - // a template puts its parameter after a folder ("tabl/(p6)"): a texture made by a script given there keeps its scheme - if( auto const scheme { Replacableskin.find( "/make:" ) }; - scheme != std::string::npos - && false == contains( Replacableskin, '|' ) ) { - assign( Replacableskin.substr( scheme + 1 ) ); - return; - } - // check for the pipe method first - if( contains( Replacableskin, '|' ) ) { - cParser nameparser( Replacableskin ); - nameparser.getTokens( 4, false, "|" ); - int skinindex = 0; - std::string texturename; nameparser >> texturename; - while( texturename != "" && skinindex < 4 ) { - replacable_skins[ skinindex + 1 ] = GfxRenderer->Fetch_Material( texturename ); - ++skinindex; - texturename = ""; nameparser >> texturename; - } - multi_textures = skinindex; - } - else { - // otherwise try the basic approach - int skinindex = 0; - do { - // test quietly for file existence so we don't generate tons of false errors in the log - // NOTE: this means actual missing files won't get reported which is hardly ideal, but still somewhat better - auto const material { TextureTest( ToLower( Replacableskin + "," + std::to_string( skinindex + 1 ) ) ) }; - if( true == material.empty() ) { break; } - - replacable_skins[ skinindex + 1 ] = GfxRenderer->Fetch_Material( material ); - ++skinindex; - } while( skinindex < 4 ); - multi_textures = skinindex; - if( multi_textures == 0 ) { - // zestaw nie zadziałał, próbujemy normanie - replacable_skins[ 1 ] = GfxRenderer->Fetch_Material( Replacableskin ); - } - } - if( replacable_skins[ 1 ] == null_handle ) { - // last ditch attempt, check for single replacable skin texture - replacable_skins[ 1 ] = GfxRenderer->Fetch_Material( Replacableskin ); - } - - // BUGS! it's not entierly designed whether opacity is property of material or submodel, - // and code does confusing things with this in various places - textures_alpha = GfxRenderer->Material(replacable_skins[1])->is_translucent() ? 0x31310031 : // tekstura -1 z kanałem alfa - nie renderować w cyklu nieprzezroczystych - 0x30300030; // wszystkie tekstury nieprzezroczyste - nie renderować w cyklu przezroczystych - if( GfxRenderer->Material( replacable_skins[ 2 ] )->is_translucent() ) { - // tekstura -2 z kanałem alfa - nie renderować w cyklu nieprzezroczystych - textures_alpha |= 0x02020002; - } - if( GfxRenderer->Material( replacable_skins[ 3 ] )->is_translucent() ) { - // tekstura -3 z kanałem alfa - nie renderować w cyklu nieprzezroczystych - textures_alpha |= 0x04040004; - } - if( GfxRenderer->Material( replacable_skins[ 4 ] )->is_translucent() ) { - // tekstura -4 z kanałem alfa - nie renderować w cyklu nieprzezroczystych - textures_alpha |= 0x08080008; - } -} - - namespace { // a luadestinationsign: or wasmdestinationsign: block, its script in the vehicle folder when it has no path of its own diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index b11ec9e84..1923e8889 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -14,6 +14,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Classes.h" #include "interfaces/IMaterial.h" +#include "model/materialdata.h" #include "physics/vehicletypes.h" #include "physics/derailment.h" #include "vehicle/derailmotion.h" @@ -189,16 +190,6 @@ enum class announcement_t : int { }; // parameters for the material object, as currently used by various simulator models -struct material_data { - - int textures_alpha{ 0x30300030 }; // maska przezroczystości tekstur. default: tekstury wymienne nie mają przezroczystości - material_handle replacable_skins[ 5 ] = { null_handle, null_handle, null_handle, null_handle, null_handle }; // McZapkie:zmienialne nadwozie - int multi_textures{ 0 }; //<0 tekstury wskazane wpisem, >0 tekstury z przecinkami, =0 jedna - - // assigns specified texture or a group of textures to replacable texture slots - void assign( std::string const &Replacableskin ); -}; - class TDynamicObject { // klasa pojazdu friend opengl46_renderer; diff --git a/widgets/map.cpp b/widgets/map.cpp index d750bbb60..19b509814 100644 --- a/widgets/map.cpp +++ b/widgets/map.cpp @@ -8,6 +8,7 @@ #include "vehicle/Driver.h" #include "model/AnimModel.h" #include "application/application.h" +#include "vehicle/DynObj.h" ui::map_panel::map_panel() : ui_panel(STR_C("Map"), false) { diff --git a/widgets/trainingcard.cpp b/widgets/trainingcard.cpp index de46f9cd8..31434237f 100644 --- a/widgets/trainingcard.cpp +++ b/widgets/trainingcard.cpp @@ -3,6 +3,7 @@ #include "simulation/simulation.h" #include "utilities/utilities.h" #include "physics/mover.h" +#include "vehicle/DynObj.h" #ifdef __linux__ #include diff --git a/world/Sweep.h b/world/Sweep.h index b83b7fa12..365c599ac 100644 --- a/world/Sweep.h +++ b/world/Sweep.h @@ -20,7 +20,7 @@ http://mozilla.org/MPL/2.0/. #include "scene/scenenode.h" #include "world/Road.h" #include "world/Segment.h" -#include "vehicle/DynObj.h" +#include "model/materialdata.h" namespace scene { From e5639e9d4832c761da662ad7139af0117e3e4e73 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Fri, 27 Nov 2026 20:40:13 +0100 Subject: [PATCH 006/123] refactor(physics): the commands between the vehicles are VehicleCommand, not text The vehicles of a train passed their commands to each other as strings (SendCtrlToNext("MainCtrl", ...)), and RunCommand() found out what to do by comparing the text with 54 names. A misspelt name compiled and did nothing. - physics/vehiclecommand.h/.cpp: enum class VehicleCommand, one value for each command a vehicle knows, plus none and unknown; ParseVehicleCommand() reads a text, VehicleCommandName() gives the name back - SendCtrlToNext(), SetInternalCommand(), RunCommand() and its groups take VehicleCommand; Load= and UnLoad= carry the name of the load as the argument of RunCommand() - the text is read once, where a command comes as text: PutCommand() (the events, Lua, the AI). TCommand keeps that text, as the AI reads the commands it knows itself (SetVelocity...) from it - two commands sent but known to no vehicle stay as they were, passed on and not done: EpFuseSwitch and SandboxAutoAllow - removed the unused GetExternalCommand(), CommandOut, ValueOut and CommandLast (written, never read) - the names are the ones the sceneries and scripts have always used, compared exactly; new tests check that every command reads back from its name No change in behaviour: 1144/1144 tests (2 new), golden traces exact against staging 62f7a29b. --- CMakeLists.txt | 1 + physics/mover.h | 32 ++--- physics/mover/cab.cpp | 12 +- physics/mover/commands.cpp | 173 ++++++++++++------------- physics/mover/controllers.cpp | 22 ++-- physics/mover/diesel.cpp | 20 +-- physics/mover/doors.cpp | 12 +- physics/mover/electrics.cpp | 22 ++-- physics/mover/mover.cpp | 6 +- physics/mover/pneumatics.cpp | 18 +-- physics/mover/traction.cpp | 16 +-- physics/vehiclecommand.cpp | 116 +++++++++++++++++ physics/vehiclecommand.h | 105 +++++++++++++++ physics/vehicletypes.h | 10 +- tests/unit/COVERAGE.md | 2 +- tests/unit/test_collisions.cpp | 2 +- tests/unit/test_commands.cpp | 23 ++-- tests/unit/test_derailment_vehicle.cpp | 6 +- tests/unit/test_genset.cpp | 2 +- tests/unit/test_vehicle_command.cpp | 43 ++++++ vehicle/Driver.cpp | 18 +-- vehicle/DynObj.cpp | 4 +- vehicle/crew.cpp | 6 +- 23 files changed, 468 insertions(+), 203 deletions(-) create mode 100644 physics/vehiclecommand.cpp create mode 100644 physics/vehiclecommand.h create mode 100644 tests/unit/test_vehicle_command.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 0ce375b50..7cd6161b6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -744,6 +744,7 @@ set(CORE_SOURCES "audio/startsample.cpp" "physics/friction.cpp" "physics/brakes.cpp" +"physics/vehiclecommand.cpp" "physics/mover/mover.cpp" "physics/mover/cab.cpp" "physics/mover/collisions.cpp" diff --git a/physics/mover.h b/physics/mover.h index f20b72414..b995ff6d6 100644 --- a/physics/mover.h +++ b/physics/mover.h @@ -1491,9 +1491,6 @@ class TMoverParameters TCommand CommandIn; /*komenda przekazywana przez PutCommand*/ /*i wykonywana przez RunInternalCommand*/ - std::string CommandOut; /*komenda przekazywana przez ExternalCommand*/ - std::string CommandLast; // Ra: ostatnio wykonana komenda do podglądu - double ValueOut = 0.0; /*argument komendy która ma byc przekazana na zewnatrz*/ TTrackShape RunningShape; /*geometria toru po ktorym jedzie pojazd*/ TTrackParam RunningTrack; /*parametry toru po ktorym jedzie pojazd*/ @@ -1894,24 +1891,23 @@ class TMoverParameters double EngineMaxRPM() const; /*! przesylanie komend sterujacych*/ - bool SendCtrlToNext(std::string const &CtrlCommand, double const ctrlvalue, double const dir, int const Couplertype = coupling::control); - bool SetInternalCommand(std::string const &NewCommand, double NewValue1, double NewValue2, int const Couplertype = coupling::control); - double GetExternalCommand(std::string &Command) const; - bool RunCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype = coupling::control); + bool SendCtrlToNext(VehicleCommand const CtrlCommand, double const ctrlvalue, double const dir, int const Couplertype = coupling::control); + bool SetInternalCommand(VehicleCommand const NewCommand, double NewValue1, double NewValue2, int const Couplertype = coupling::control); + bool RunCommand(VehicleCommand const Command, double CValue1, double CValue2, int const Couplertype = coupling::control, std::string_view Argument = {}); // the parts of RunCommand(), by the area of the commands - bool RunControllerCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunRelaysCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunCabCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunBrakeCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunBrakeEquipmentCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunAuxiliariesCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunPumpsCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunBlowersCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunPowerCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunDoorsCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunControllerCommand(VehicleCommand const Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunRelaysCommand(VehicleCommand const Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunCabCommand(VehicleCommand const Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunBrakeCommand(VehicleCommand const Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunBrakeEquipmentCommand(VehicleCommand const Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunAuxiliariesCommand(VehicleCommand const Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunPumpsCommand(VehicleCommand const Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunBlowersCommand(VehicleCommand const Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunPowerCommand(VehicleCommand const Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunDoorsCommand(VehicleCommand const Command, double CValue1, double CValue2, int Couplertype, bool &OK); void DoorPermitCommand(double CValue1, double CValue2); void DoorRemoteCommand(bool Open, double CValue1, double CValue2); - bool RunLoadCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunLoadCommand(VehicleCommand const Command, double CValue1, double CValue2, std::string_view Argument, bool &OK); bool RunInternalCommand(); void PutCommand(std::string const &NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation); bool CabActivisation(bool const Enforce = false); diff --git a/physics/mover/cab.cpp b/physics/mover/cab.cpp index 3b73e1baf..14df59d94 100644 --- a/physics/mover/cab.cpp +++ b/physics/mover/cab.cpp @@ -41,7 +41,7 @@ bool TMoverParameters::DirectionForward() { ++DirActive; DirAbsolute = DirActive * CabActive; - SendCtrlToNext("Direction", DirActive, CabActive); + SendCtrlToNext(VehicleCommand::direction, DirActive, CabActive); return true; } else if (DirActive == 1 && IsMainCtrlNoPowerPos() && TrainType == train_type::emu && EngineType != TEngineType::ElectricInductionMotor) @@ -117,8 +117,8 @@ bool TMoverParameters::CabActivisation(bool const Enforce) DirAbsolute = DirActive * CabActive; CabMaster = true; SecuritySystem.set_enabled(true); // activate the alerter TODO: make it part of control based cab selection - SendCtrlToNext("CabActivisation", 1, CabActive); - SendCtrlToNext("Direction", DirActive, CabActive); + SendCtrlToNext(VehicleCommand::cabActivation, 1, CabActive); + SendCtrlToNext(VehicleCommand::direction, DirActive, CabActive); if (InactiveCabFlag & activation::springbrakeoff) { SpringBrakeActivate(false); @@ -160,7 +160,7 @@ bool TMoverParameters::CabDeactivisation(bool const Enforce) if (InactiveCabFlag & activation::neutraldirection) { DirActive = 0; - SendCtrlToNext("Direction", 0, CabActive); + SendCtrlToNext(VehicleCommand::direction, 0, CabActive); } CabActive = 0; @@ -169,7 +169,7 @@ bool TMoverParameters::CabDeactivisation(bool const Enforce) DepartureSignal = false; // nie buczeć z nieaktywnej kabiny SecuritySystem.set_enabled(false); // deactivate alerter TODO: make it part of control based cab selection - SendCtrlToNext("CabActivisation", 0, CabOccupied); // CabActive==0! + SendCtrlToNext(VehicleCommand::cabActivation, 0, CabOccupied); // CabActive==0! } return OK; } @@ -231,7 +231,7 @@ bool TMoverParameters::DirectionBackward(void) // else --DirActive; DirAbsolute = DirActive * CabActive; - SendCtrlToNext("Direction", DirActive, CabActive); + SendCtrlToNext(VehicleCommand::direction, DirActive, CabActive); return true; } diff --git a/physics/mover/commands.cpp b/physics/mover/commands.cpp index 0a531f5bc..499ba62fc 100644 --- a/physics/mover/commands.cpp +++ b/physics/mover/commands.cpp @@ -36,37 +36,30 @@ http://mozilla.org/MPL/2.0/. // ************************************************************************************************* void TMoverParameters::PutCommand(std::string const &NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation) { - CommandLast = NewCommand; // zapamiętanie komendy - - CommandIn.Command = NewCommand; + auto const parsed{ParseVehicleCommand(NewCommand)}; + CommandIn.Command = parsed.command; + CommandIn.Text = NewCommand; + CommandIn.Argument = parsed.argument; CommandIn.Value1 = NewValue1; CommandIn.Value2 = NewValue2; CommandIn.Location = NewLocation; // czy uruchomic tu RunInternalCommand? nie wiem } -// ************************************************************************************************* -// Q: 20160714 -// Pobiera komendę z parametru funkcji oraz wartość zmiennej jako return -// ************************************************************************************************* -double TMoverParameters::GetExternalCommand(std::string &Command) const -{ - Command = CommandOut; - return ValueOut; -} - // ************************************************************************************************* // Q: 20160714 // Ustawienie komendy wraz z parametrami // ************************************************************************************************* -bool TMoverParameters::SetInternalCommand(std::string const &NewCommand, double NewValue1, double NewValue2, int const Couplertype) +bool TMoverParameters::SetInternalCommand(VehicleCommand const NewCommand, double NewValue1, double NewValue2, int const Couplertype) { bool SIC; - if (CommandIn.Command == NewCommand && CommandIn.Value1 == NewValue1 && CommandIn.Value2 == NewValue2 && CommandIn.Coupling == Couplertype) + if (CommandIn.Command == NewCommand && CommandIn.Argument.empty() && CommandIn.Value1 == NewValue1 && CommandIn.Value2 == NewValue2 && CommandIn.Coupling == Couplertype) SIC = false; else { CommandIn.Command = NewCommand; + CommandIn.Text = VehicleCommandName(NewCommand); + CommandIn.Argument.clear(); CommandIn.Value1 = NewValue1; CommandIn.Value2 = NewValue2; CommandIn.Coupling = Couplertype; @@ -81,7 +74,7 @@ bool TMoverParameters::SetInternalCommand(std::string const &NewCommand, double // Q: 20160714 // wysyłanie komendy w kierunku dir (1=przód, -1=tył) do kolejnego pojazdu (jednego) // ************************************************************************************************* -bool TMoverParameters::SendCtrlToNext(std::string const &CtrlCommand, double const ctrlvalue, double const dir, int const Couplertype) +bool TMoverParameters::SendCtrlToNext(VehicleCommand const CtrlCommand, double const ctrlvalue, double const dir, int const Couplertype) { bool OK; int d; // numer sprzęgu w kierunku którego wysyłamy @@ -121,7 +114,7 @@ bool TMoverParameters::SendCtrlToNext(std::string const &CtrlCommand, double con // Komenda musi być zdefiniowana tutaj, a jeśli się wywołuje funkcję, to ona nie może // sama przesyłać do kolejnych pojazdów. Należy też się zastanowić, czy dla uzyskania // jakiejś zmiany (np. IncMainCtrl) lepiej wywołać funkcję, czy od razu wysłać komendę. -bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype) +bool TMoverParameters::RunCommand(VehicleCommand const Command, double CValue1, double CValue2, int const Couplertype, std::string_view const Argument) { // the group of the command sets OK; a command none of them knows isn't done if (bool OK{false}; RunControllerCommand(Command, CValue1, CValue2, Couplertype, OK) || RunRelaysCommand(Command, CValue1, CValue2, Couplertype, OK) || @@ -133,7 +126,7 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do RunBlowersCommand(Command, CValue1, CValue2, Couplertype, OK) || RunPowerCommand(Command, CValue1, CValue2, Couplertype, OK) || RunDoorsCommand(Command, CValue1, CValue2, Couplertype, OK) || - RunLoadCommand(Command, CValue1, CValue2, Couplertype, OK)) + RunLoadCommand(Command, CValue1, CValue2, Argument, OK)) { return OK; // dla true komenda będzie usunięta, dla false wykonana ponownie } @@ -141,9 +134,9 @@ bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, do } // RunCommand() for the controllers; returns whether the command is one of them -bool TMoverParameters::RunControllerCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +bool TMoverParameters::RunControllerCommand(VehicleCommand const Command, double CValue1, double CValue2, int const Couplertype, bool &OK) { - if (Command == "MainCtrl") + if (Command == VehicleCommand::mainController) { // sent as MainCtrlPosForCoupled(), passed on unchanged if (auto const position{MainCtrlPosFromCoupled(static_cast(floor(CValue1)))}; MainCtrlPosNo >= position) @@ -159,7 +152,7 @@ bool TMoverParameters::RunControllerCommand(std::string const &Command, double C } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "ScndCtrl") + else if (Command == VehicleCommand::secondaryController) { if (ScndCtrlPosNo >= floor(CValue1)) { @@ -177,7 +170,7 @@ bool TMoverParameters::RunControllerCommand(std::string const &Command, double C OK:=SendCtrlToNext(command,CValue1,CValue2); end; end */ - else if (Command == "EIMIC") // ElectricInductionMotor Integrated Control - propulsion and brakes in relative values + else if (Command == VehicleCommand::integratedController) // ElectricInductionMotor Integrated Control - propulsion and brakes in relative values { eimic_real = CValue1; OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); @@ -190,15 +183,15 @@ bool TMoverParameters::RunControllerCommand(std::string const &Command, double C } // RunCommand() for the direction, the automatic start and the current relays; returns whether the command is one of them -bool TMoverParameters::RunRelaysCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +bool TMoverParameters::RunRelaysCommand(VehicleCommand const Command, double CValue1, double CValue2, int const Couplertype, bool &OK) { - if (Command == "Direction") + if (Command == VehicleCommand::direction) { DirActive = static_cast(floor(CValue1)); DirAbsolute = DirActive * CabActive; OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "AutoRelaySwitch") + else if (Command == VehicleCommand::autoRelaySwitch) { if (CValue1 == 1 && AutoRelayType == 2) AutoRelayFlag = true; @@ -206,12 +199,12 @@ bool TMoverParameters::RunRelaysCommand(std::string const &Command, double CValu AutoRelayFlag = false; OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "MaxCurrentSwitch") + else if (Command == VehicleCommand::maxCurrentSwitch) { MaxCurrentSwitch(CValue1 == 1, range_t::local); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "MinCurrentSwitch") + else if (Command == VehicleCommand::minCurrentSwitch) { OK = MinCurrentSwitch(CValue1 == 1); } @@ -224,9 +217,9 @@ bool TMoverParameters::RunRelaysCommand(std::string const &Command, double CValu } // RunCommand() for the cab and the speed control; returns whether the command is one of them -bool TMoverParameters::RunCabCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +bool TMoverParameters::RunCabCommand(VehicleCommand const Command, double CValue1, double CValue2, int const Couplertype, bool &OK) { - if (Command == "CabActivisation") + if (Command == VehicleCommand::cabActivation) { // OK:=Power>0.01; switch (static_cast(CValue1 * CValue2)) @@ -256,13 +249,13 @@ bool TMoverParameters::RunCabCommand(std::string const &Command, double CValue1, CabMaster = false; OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "SpeedCntrl") + else if (Command == VehicleCommand::speedControl) { if (EngineType == TEngineType::ElectricInductionMotor || SpeedCtrl) SpeedCtrlValue = static_cast(round(CValue1)); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "SpeedCtrlUnit.Parking") + else if (Command == VehicleCommand::speedControlParking) { SpeedCtrlUnit.Parking = static_cast(CValue1); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); @@ -275,9 +268,9 @@ bool TMoverParameters::RunCabCommand(std::string const &Command, double CValue1, } // RunCommand() for the train brake, the releaser and the emergency brake; returns whether the command is one of them -bool TMoverParameters::RunBrakeCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +bool TMoverParameters::RunBrakeCommand(VehicleCommand const Command, double CValue1, double CValue2, int const Couplertype, bool &OK) { - if (Command == "Brake") // youBy - jak sie EP hamuje, to trza sygnal wyslac... + if (Command == VehicleCommand::brake) // youBy - jak sie EP hamuje, to trza sygnal wyslac... { if (CValue1 < 0.001) DynamicBrakeEMUStatus = true; @@ -295,12 +288,12 @@ bool TMoverParameters::RunBrakeCommand(std::string const &Command, double CValue BrakePressureActual = BrakePressureTable[BrakeCtrlPos]; OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } // youby - odluzniacz hamulcow, przyda sie - else if (Command == "BrakeReleaser") + else if (Command == VehicleCommand::brakeReleaser) { OK = BrakeReleaser(static_cast(Round(CValue1))); // samo się przesyła dalej // OK:=SendCtrlToNext(command,CValue1,CValue2); //to robiło kaskadę 2^n } - else if (Command == "Emergency_brake") + else if (Command == VehicleCommand::emergencyBrake) { if (RadiostopSwitch(floor(CValue1) == 1)) // YB: czy to jest potrzebne? OK = true; @@ -315,9 +308,9 @@ bool TMoverParameters::RunBrakeCommand(std::string const &Command, double CValue } // RunCommand() for the brake delays, the spring brake, the sand and the cab signalling; returns whether the command is one of them -bool TMoverParameters::RunBrakeEquipmentCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +bool TMoverParameters::RunBrakeEquipmentCommand(VehicleCommand const Command, double CValue1, double CValue2, int const Couplertype, bool &OK) { - if (Command == "BrakeDelay") + if (Command == VehicleCommand::brakeDelay) { if (auto const brakesetting = static_cast(std::floor(CValue1)); true == Hamulec->SetBDF(brakesetting)) { @@ -330,7 +323,7 @@ bool TMoverParameters::RunBrakeEquipmentCommand(std::string const &Command, doub } SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "SpringBrakeActivate") + else if (Command == VehicleCommand::springBrakeActivate) { if (Power24vIsAvailable || Power110vIsAvailable) { @@ -341,11 +334,11 @@ bool TMoverParameters::RunBrakeEquipmentCommand(std::string const &Command, doub OK = true; } - else if (Command == "Sandbox") + else if (Command == VehicleCommand::sandbox) { OK = Sandbox(CValue1 == 1, range_t::local); } - else if (Command == "CabSignal") /*SHP,Indusi*/ + else if (Command == VehicleCommand::cabSignal) /*SHP,Indusi*/ { // Ra: to powinno działać tylko w członie obsadzonym SecuritySystem.set_cabsignal(); // else OK:=false; @@ -362,14 +355,14 @@ bool TMoverParameters::RunBrakeEquipmentCommand(std::string const &Command, doub } // RunCommand() for the heating, the converter, the battery and the compressor; returns whether the command is one of them -bool TMoverParameters::RunAuxiliariesCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +bool TMoverParameters::RunAuxiliariesCommand(VehicleCommand const Command, double CValue1, double CValue2, int const Couplertype, bool &OK) { - if (Command == "HeatingSwitch") + if (Command == VehicleCommand::heatingSwitch) { HeatingSwitch_(CValue1 > 0.0); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "ConverterSwitch") /*NBMX*/ + else if (Command == VehicleCommand::converterSwitch) /*NBMX*/ { if (ConverterStart == start_t::manual) { @@ -377,7 +370,7 @@ bool TMoverParameters::RunAuxiliariesCommand(std::string const &Command, double } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "BatterySwitch") /*NBMX*/ + else if (Command == VehicleCommand::batterySwitch) /*NBMX*/ { // the battery of a vehicle prepared for hauling (PulleeMode) stays off if (BatteryStart == start_t::manual && (false == PulleeMode || CValue1 <= 0.0)) @@ -392,12 +385,12 @@ bool TMoverParameters::RunAuxiliariesCommand(std::string const &Command, double // else if (CValue1=0) then EpFuse:=false; // OK:=SendCtrlToNext(command,CValue1,CValue2); // end - else if (Command == "CompressorSwitch") /*NBMX*/ + else if (Command == VehicleCommand::compressorSwitch) /*NBMX*/ { CompressorSwitch(CValue1 == 1, range_t::local); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "CompressorPreset") + else if (Command == VehicleCommand::compressorPreset) { CompressorListPos = safe_clamp(static_cast(CValue1), 0, CompressorListPosNo); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); @@ -410,9 +403,9 @@ bool TMoverParameters::RunAuxiliariesCommand(std::string const &Command, double } // RunCommand() for the water, fuel and oil pumps and the water heater; returns whether the command is one of them -bool TMoverParameters::RunPumpsCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +bool TMoverParameters::RunPumpsCommand(VehicleCommand const Command, double CValue1, double CValue2, int const Couplertype, bool &OK) { - if (Command == "WaterPumpBreakerSwitch") + if (Command == VehicleCommand::waterPumpBreakerSwitch) { /* if( FuelPump.start_type != start::automatic ) { @@ -424,7 +417,7 @@ bool TMoverParameters::RunPumpsCommand(std::string const &Command, double CValue */ OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "WaterPumpSwitch") + else if (Command == VehicleCommand::waterPumpSwitch) { if (WaterPump.start_type != start_t::battery) @@ -434,7 +427,7 @@ bool TMoverParameters::RunPumpsCommand(std::string const &Command, double CValue } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "WaterPumpSwitchOff") + else if (Command == VehicleCommand::waterPumpSwitchOff) { if (WaterPump.start_type != start_t::battery) @@ -444,7 +437,7 @@ bool TMoverParameters::RunPumpsCommand(std::string const &Command, double CValue } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "WaterHeaterBreakerSwitch") + else if (Command == VehicleCommand::waterHeaterBreakerSwitch) { /* if( FuelPump.start_type != start::automatic ) { @@ -456,7 +449,7 @@ bool TMoverParameters::RunPumpsCommand(std::string const &Command, double CValue */ OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "WaterHeaterSwitch") + else if (Command == VehicleCommand::waterHeaterSwitch) { /* if( FuelPump.start_type != start::automatic ) { @@ -468,7 +461,7 @@ bool TMoverParameters::RunPumpsCommand(std::string const &Command, double CValue */ OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "WaterCircuitsLinkSwitch") + else if (Command == VehicleCommand::waterCircuitsLinkSwitch) { if (true == dizel_heat.auxiliary_water_circuit) { @@ -477,7 +470,7 @@ bool TMoverParameters::RunPumpsCommand(std::string const &Command, double CValue } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "FuelPumpSwitch") + else if (Command == VehicleCommand::fuelPumpSwitch) { if (FuelPump.start_type != start_t::automatic) { @@ -486,7 +479,7 @@ bool TMoverParameters::RunPumpsCommand(std::string const &Command, double CValue } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "FuelPumpSwitchOff") + else if (Command == VehicleCommand::fuelPumpSwitchOff) { if (FuelPump.start_type != start_t::automatic) { @@ -495,7 +488,7 @@ bool TMoverParameters::RunPumpsCommand(std::string const &Command, double CValue } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "OilPumpSwitch") + else if (Command == VehicleCommand::oilPumpSwitch) { if (OilPump.start_type != start_t::automatic) { @@ -504,7 +497,7 @@ bool TMoverParameters::RunPumpsCommand(std::string const &Command, double CValue } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "OilPumpSwitchOff") + else if (Command == VehicleCommand::oilPumpSwitchOff) { if (OilPump.start_type != start_t::automatic) { @@ -521,9 +514,9 @@ bool TMoverParameters::RunPumpsCommand(std::string const &Command, double CValue } // RunCommand() for the motor blowers and the compartment lights; returns whether the command is one of them -bool TMoverParameters::RunBlowersCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +bool TMoverParameters::RunBlowersCommand(VehicleCommand const Command, double CValue1, double CValue2, int const Couplertype, bool &OK) { - if (Command == "MotorBlowersFrontSwitch") + if (Command == VehicleCommand::motorBlowersFrontSwitch) { if (MotorBlowers[end::front].start_type != start_t::manual && MotorBlowers[end::front].start_type != start_t::manualwithautofallback) { @@ -532,7 +525,7 @@ bool TMoverParameters::RunBlowersCommand(std::string const &Command, double CVal } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "MotorBlowersFrontSwitchOff") + else if (Command == VehicleCommand::motorBlowersFrontSwitchOff) { if (MotorBlowers[end::front].start_type != start_t::manual && MotorBlowers[end::front].start_type != start_t::manualwithautofallback) { @@ -541,7 +534,7 @@ bool TMoverParameters::RunBlowersCommand(std::string const &Command, double CVal } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "MotorBlowersRearSwitch") + else if (Command == VehicleCommand::motorBlowersRearSwitch) { if (MotorBlowers[end::rear].start_type != start_t::manual && MotorBlowers[end::rear].start_type != start_t::manualwithautofallback) { @@ -550,7 +543,7 @@ bool TMoverParameters::RunBlowersCommand(std::string const &Command, double CVal } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "MotorBlowersRearSwitchOff") + else if (Command == VehicleCommand::motorBlowersRearSwitchOff) { if (MotorBlowers[end::rear].start_type != start_t::manual && MotorBlowers[end::rear].start_type != start_t::manualwithautofallback) { @@ -559,7 +552,7 @@ bool TMoverParameters::RunBlowersCommand(std::string const &Command, double CVal } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "CompartmentLightsSwitch") + else if (Command == VehicleCommand::compartmentLightsSwitch) { if (CompartmentLights.start_type != start_t::automatic) @@ -569,7 +562,7 @@ bool TMoverParameters::RunBlowersCommand(std::string const &Command, double CVal } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "CompartmentLightsSwitchOff") + else if (Command == VehicleCommand::compartmentLightsSwitchOff) { if (CompartmentLights.start_type != start_t::automatic) @@ -587,19 +580,19 @@ bool TMoverParameters::RunBlowersCommand(std::string const &Command, double CVal } // RunCommand() for the line breaker, the relays and the pantographs; returns whether the command is one of them -bool TMoverParameters::RunPowerCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +bool TMoverParameters::RunPowerCommand(VehicleCommand const Command, double CValue1, double CValue2, int const Couplertype, bool &OK) { - if (Command == "MainSwitch") + if (Command == VehicleCommand::mainSwitch) { MainSwitch_(CValue1 > 0.0); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "RelayReset") + else if (Command == VehicleCommand::relayReset) { RelayReset(static_cast(CValue1), range_t::local); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "PantValve") // Winger 160204 + else if (Command == VehicleCommand::pantographValve) // Winger 160204 { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów auto const inputend{(static_cast(CValue1) & 0x80) != 0 ? 1 : 0}; auto const inputcab{(static_cast(CValue1) & 0x40) != 0 ? 1 : 0}; @@ -613,22 +606,22 @@ bool TMoverParameters::RunPowerCommand(std::string const &Command, double CValue OperatePantographValve(static_cast(swap ? 1 - inputend : inputend), static_cast(inputoperation), range_t::local); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "PantsValve") + else if (Command == VehicleCommand::pantographsValve) { OperatePantographsValve(static_cast(static_cast(CValue1)), range_t::local); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "PantAllDown") + else if (Command == VehicleCommand::pantographsAllDown) { DropAllPantographs(CValue1 == 1, range_t::local); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "TractionMode") + else if (Command == VehicleCommand::tractionMode) { TractionModeSwitch(CValue1 > 0.5 ? traction_mode::genset : traction_mode::catenary, range_t::local); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "GensetSwitch") + else if (Command == VehicleCommand::gensetSwitch) { GensetSwitch(CValue1 > 0.5, range_t::local); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); @@ -641,34 +634,34 @@ bool TMoverParameters::RunPowerCommand(std::string const &Command, double CValue } // RunCommand() for the doors and the departure signal; returns whether the command is one of them -bool TMoverParameters::RunDoorsCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +bool TMoverParameters::RunDoorsCommand(VehicleCommand const Command, double CValue1, double CValue2, int const Couplertype, bool &OK) { - if (Command == "DoorPermit") + if (Command == VehicleCommand::doorPermit) { DoorPermitCommand(CValue1, CValue2); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "DoorOpen" || Command == "DoorClose") /*NBMX*/ + else if (Command == VehicleCommand::doorOpen || Command == VehicleCommand::doorClose) /*NBMX*/ { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów - DoorRemoteCommand(Command == "DoorOpen", CValue1, CValue2); + DoorRemoteCommand(Command == VehicleCommand::doorOpen, CValue1, CValue2); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "DoorLock") + else if (Command == VehicleCommand::doorLock) { Doors.lock_enabled = CValue1 == 1 ? true : false; OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "DoorStep") + else if (Command == VehicleCommand::doorStep) { Doors.step_enabled = CValue1 == 1 ? true : false; OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "DoorMode") + else if (Command == VehicleCommand::doorMode) { Doors.remote_only = CValue1 == 1 ? true : false; OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } - else if (Command == "DepartureSignal") + else if (Command == VehicleCommand::departureSignal) { DepartureSignal = CValue1 == 1 ? true : false; OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); @@ -718,16 +711,16 @@ void TMoverParameters::DoorRemoteCommand(bool const Open, double const CValue1, } // RunCommand() for the load and the damage; returns whether the command is one of them -bool TMoverParameters::RunLoadCommand(std::string const &Command, double CValue1, double CValue2, int const /*Couplertype*/, bool &OK) +bool TMoverParameters::RunLoadCommand(VehicleCommand const Command, double CValue1, double CValue2, std::string_view const Argument, bool &OK) { - if (issection("Load=", Command)) + if (Command == VehicleCommand::load) { OK = false; // będzie powtarzane aż się załaduje if (Vel < 0.1 // tolerance margin for small vehicle movements in the consist && MaxLoad > 0 && LoadAmount < MaxLoad * (1.0 + OverLoadFactor) && Distance(Loc, CommandIn.Location, Dim, Dim) < (CValue2 > 1.0 ? CValue2 : 10.0)) { // ten peron/rampa - auto const loadname{ToLower(extract_value("Load", Command))}; + auto const loadname{ToLower(std::string{Argument})}; if (LoadAmount == 0.f) { AssignLoad(loadname); @@ -741,7 +734,7 @@ bool TMoverParameters::RunLoadCommand(std::string const &Command, double CValue1 LastLoadChangeTime = 0.0; } } - else if (issection("UnLoad=", Command)) + else if (Command == VehicleCommand::unload) { OK = false; // będzie powtarzane aż się rozładuje if (Vel < 0.1 // tolerance margin for small vehicle movements in the consist @@ -749,7 +742,7 @@ bool TMoverParameters::RunLoadCommand(std::string const &Command, double CValue1 && Distance(Loc, CommandIn.Location, Dim, Dim) < (CValue2 > 1.0 ? CValue2 : 10.0)) { // ten peron /*mozna to rozladowac*/ - OK = LoadingDone(-1.f * LoadSpeed, ToLower(extract_value("UnLoad", Command))); + OK = LoadingDone(-1.f * LoadSpeed, ToLower(std::string{Argument})); } else { @@ -757,7 +750,7 @@ bool TMoverParameters::RunLoadCommand(std::string const &Command, double CValue1 LastLoadChangeTime = 0.0; } } - else if (Command == "SetDamage") + else if (Command == VehicleCommand::setDamage) { if (CValue2 == 1) OK = SetFlag(DamageFlag, static_cast(floor(CValue1))); @@ -785,13 +778,15 @@ bool TMoverParameters::RunInternalCommand() { bool OK; - if (!CommandIn.Command.empty()) + if (CommandIn.Command != VehicleCommand::none) { - OK = RunCommand(CommandIn.Command, CommandIn.Value1, CommandIn.Value2, CommandIn.Coupling); + OK = RunCommand(CommandIn.Command, CommandIn.Value1, CommandIn.Value2, CommandIn.Coupling, CommandIn.Argument); if (OK) { - CommandIn.Command.clear(); // kasowanie bo rozkaz wykonany + CommandIn.Command = VehicleCommand::none; // kasowanie bo rozkaz wykonany + CommandIn.Text.clear(); + CommandIn.Argument.clear(); CommandIn.Value1 = 0; CommandIn.Value2 = 0; CommandIn.Coupling = 0; diff --git a/physics/mover/controllers.cpp b/physics/mover/controllers.cpp index 225e36a03..eba9ad73b 100644 --- a/physics/mover/controllers.cpp +++ b/physics/mover/controllers.cpp @@ -83,8 +83,8 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) if (true == OK) { ScndCtrlResistiveLockCheck(); // e.g. from the last series position on to the resistive parallel ones - SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); //??? - SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); + SendCtrlToNext(VehicleCommand::mainController, MainCtrlPosForCoupled(), CabActive); //??? + SendCtrlToNext(VehicleCommand::secondaryController, ScndCtrlPos, CabActive); } // hunter-101012: poprawka @@ -270,8 +270,8 @@ bool TMoverParameters::DecMainCtrl(int CtrlSpeed) if (OK) { ScndCtrlResistiveLockCheck(); // the shunt drops when the master controller leaves a resistance-free position - /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); // hmmmm...???!!! - /*OK:=*/SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); + /*OK:=*/SendCtrlToNext(VehicleCommand::mainController, MainCtrlPosForCoupled(), CabActive); // hmmmm...???!!! + /*OK:=*/SendCtrlToNext(VehicleCommand::secondaryController, ScndCtrlPos, CabActive); } } // if OK then LastRelayTime:=0; @@ -485,8 +485,8 @@ bool TMoverParameters::IncScndCtrl(int CtrlSpeed) OK = false; if (OK) { - /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); //??? - /*OK:=*/SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); + /*OK:=*/SendCtrlToNext(VehicleCommand::mainController, MainCtrlPosForCoupled(), CabActive); //??? + /*OK:=*/SendCtrlToNext(VehicleCommand::secondaryController, ScndCtrlPos, CabActive); } } else // nie ma sterowania @@ -547,8 +547,8 @@ bool TMoverParameters::DecScndCtrl(int CtrlSpeed) OK = false; if (OK) { - /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); //??? - /*OK:=*/SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); + /*OK:=*/SendCtrlToNext(VehicleCommand::mainController, MainCtrlPosForCoupled(), CabActive); //??? + /*OK:=*/SendCtrlToNext(VehicleCommand::secondaryController, ScndCtrlPos, CabActive); } } else @@ -627,7 +627,7 @@ bool TMoverParameters::AutoRelaySwitch(bool State) { AutoRelayFlag = State; ARS = true; - SendCtrlToNext("AutoRelaySwitch", int(State), CabActive); + SendCtrlToNext(VehicleCommand::autoRelaySwitch, int(State), CabActive); } else ARS = false; @@ -1376,7 +1376,7 @@ void TMoverParameters::CheckSpeedCtrl(double dt) eimicSpeedCtrlIntegral = 0; } SpeedCtrlUnit.Parking = Vel == 0.0 && eimic <= 0 && EngineType != TEngineType::ElectricInductionMotor; - SendCtrlToNext("SpeedCtrlUnit.Parking", SpeedCtrlUnit.Parking, CabActive); + SendCtrlToNext(VehicleCommand::speedControlParking, SpeedCtrlUnit.Parking, CabActive); } else { @@ -1396,7 +1396,7 @@ void TMoverParameters::CheckSpeedCtrl(double dt) eimicSpeedCtrl = 1; eimicSpeedCtrlIntegral = 0; SpeedCtrlUnit.Parking = false; - SendCtrlToNext("SpeedCtrlUnit.Parking", SpeedCtrlUnit.Parking, CabActive); + SendCtrlToNext(VehicleCommand::speedControlParking, SpeedCtrlUnit.Parking, CabActive); } } diff --git a/physics/mover/diesel.cpp b/physics/mover/diesel.cpp index 49778945a..5af5c26bf 100644 --- a/physics/mover/diesel.cpp +++ b/physics/mover/diesel.cpp @@ -133,7 +133,7 @@ bool TMoverParameters::WaterPumpBreakerSwitch(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext("WaterPumpBreakerSwitch", WaterPump.breaker ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::waterPumpBreakerSwitch, WaterPump.breaker ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return WaterPump.breaker != initialstate; @@ -155,7 +155,7 @@ bool TMoverParameters::WaterPumpSwitch(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext("WaterPumpSwitch", WaterPump.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::waterPumpSwitch, WaterPump.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return WaterPump.is_enabled != initialstate; @@ -177,7 +177,7 @@ bool TMoverParameters::WaterPumpSwitchOff(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext("WaterPumpSwitchOff", WaterPump.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::waterPumpSwitchOff, WaterPump.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return WaterPump.is_disabled != initialstate; @@ -198,7 +198,7 @@ bool TMoverParameters::WaterHeaterBreakerSwitch(bool State, range_t const Notify if (Notify != range_t::local) { - SendCtrlToNext("WaterHeaterBreakerSwitch", WaterHeater.breaker ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::waterHeaterBreakerSwitch, WaterHeater.breaker ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return WaterHeater.breaker != initialstate; @@ -219,7 +219,7 @@ bool TMoverParameters::WaterHeaterSwitch(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext("WaterHeaterSwitch", WaterHeater.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::waterHeaterSwitch, WaterHeater.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return WaterHeater.is_enabled != initialstate; @@ -241,7 +241,7 @@ bool TMoverParameters::WaterCircuitsLinkSwitch(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext("WaterCircuitsLinkSwitch", WaterCircuitsLink ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::waterCircuitsLinkSwitch, WaterCircuitsLink ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return WaterCircuitsLink != initialstate; @@ -263,7 +263,7 @@ bool TMoverParameters::FuelPumpSwitch(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext("FuelPumpSwitch", FuelPump.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::fuelPumpSwitch, FuelPump.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return FuelPump.is_enabled != initialstate; @@ -284,7 +284,7 @@ bool TMoverParameters::FuelPumpSwitchOff(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext("FuelPumpSwitchOff", FuelPump.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::fuelPumpSwitchOff, FuelPump.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return FuelPump.is_disabled != initialstate; @@ -306,7 +306,7 @@ bool TMoverParameters::OilPumpSwitch(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext("OilPumpSwitch", OilPump.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::oilPumpSwitch, OilPump.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return OilPump.is_enabled != initialstate; @@ -327,7 +327,7 @@ bool TMoverParameters::OilPumpSwitchOff(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext("OilPumpSwitchOff", OilPump.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::oilPumpSwitchOff, OilPump.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return OilPump.is_disabled != initialstate; diff --git a/physics/mover/doors.cpp b/physics/mover/doors.cpp index 04ad070dc..28b2e379a 100644 --- a/physics/mover/doors.cpp +++ b/physics/mover/doors.cpp @@ -199,7 +199,7 @@ bool TMoverParameters::PermitDoorStep(bool const State, range_t const Notify) if (Notify != range_t::local) { // wysłanie wyłączenia do pozostałych? - SendCtrlToNext("DoorStep", State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::doorStep, State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return Doors.step_enabled != initialstate; @@ -215,7 +215,7 @@ bool TMoverParameters::PermitDoors(side const Door, bool const State, range_t co if (Notify != range_t::local) { - SendCtrlToNext("DoorPermit", + SendCtrlToNext(VehicleCommand::doorPermit, (State ? 1 : -1) // positive: grant, negative: revoke * (Door == (CabActive > 0 ? side::left : side::right) ? // 1=lewe, 2=prawe (swap if reversed) 1 : @@ -245,7 +245,7 @@ bool TMoverParameters::ChangeDoorControlMode(bool const State, range_t const Not if (Notify != range_t::local) { // wysłanie wyłączenia do pozostałych? - SendCtrlToNext("DoorMode", State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::doorMode, State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } if (true == State) @@ -292,7 +292,7 @@ bool TMoverParameters::OperateDoors(side const Door, bool const State, range_t c if (Notify != range_t::local) { - SendCtrlToNext(State == true ? "DoorOpen" : "DoorClose", + SendCtrlToNext(State == true ? VehicleCommand::doorOpen : VehicleCommand::doorClose, Door == (CabActive > 0 ? side::left : side::right) ? // 1=lewe, 2=prawe (swap if reversed) 1 : 2, @@ -312,7 +312,7 @@ bool TMoverParameters::LockDoors(bool const State, range_t const Notify) if (Notify != range_t::local) { // wysłanie wyłączenia do pozostałych? - SendCtrlToNext("DoorLock", State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::doorLock, State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return Doors.lock_enabled != initialstate; @@ -332,7 +332,7 @@ bool TMoverParameters::signal_departure(bool const State, range_t const Notify) if (Notify != range_t::local) { // wysłanie wyłączenia do pozostałych? - SendCtrlToNext("DepartureSignal", State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::departureSignal, State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return true; diff --git a/physics/mover/electrics.cpp b/physics/mover/electrics.cpp index 591c8b31f..9127e00cb 100644 --- a/physics/mover/electrics.cpp +++ b/physics/mover/electrics.cpp @@ -862,8 +862,8 @@ bool TMoverParameters::BatterySwitch(bool State, range_t const Notify) // switching batteries does not require activation if (Notify != local) { - SendCtrlToNext("BatterySwitch", State ? 1 : 0, 1, Notify == unit ? coupling::control | coupling::permanent : coupling::control); - SendCtrlToNext("BatterySwitch", State ? 1 : 0, -1, Notify == unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::batterySwitch, State ? 1 : 0, 1, Notify == unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::batterySwitch, State ? 1 : 0, -1, Notify == unit ? coupling::control | coupling::permanent : coupling::control); } return Battery != initialstate; @@ -884,7 +884,7 @@ bool TMoverParameters::CompartmentLightsSwitch(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext("CompartmentLightsSwitch", CompartmentLights.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::compartmentLightsSwitch, CompartmentLights.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return CompartmentLights.is_enabled != initialstate; @@ -906,7 +906,7 @@ bool TMoverParameters::CompartmentLightsSwitchOff(bool State, range_t const Noti if (Notify != range_t::local) { - SendCtrlToNext("CompartmentLightsSwitchOff", CompartmentLights.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::compartmentLightsSwitchOff, CompartmentLights.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return CompartmentLights.is_disabled != initialstate; @@ -927,7 +927,7 @@ bool TMoverParameters::MainSwitch(bool const State, range_t const Notify) { // pass the command to other vehicles // TBD: pass the requested state, or the actual state? - SendCtrlToNext("MainSwitch", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::mainSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return (Mains || dizel_startup) != initialstate; @@ -1038,7 +1038,7 @@ bool TMoverParameters::ConverterSwitch(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext("ConverterSwitch", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::converterSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return ConverterAllow != initialstate; @@ -1055,7 +1055,7 @@ bool TMoverParameters::HeatingSwitch(bool const State, range_t const Notify) { // pass the command to other vehicles // TBD: pass the requested state, or the actual state? - SendCtrlToNext("HeatingSwitch", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::heatingSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return HeatingAllow != initialstate; @@ -1081,7 +1081,7 @@ bool TMoverParameters::GensetSwitch(bool const State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext("GensetSwitch", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::gensetSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return Genset.is_enabled != initialstate; @@ -1207,7 +1207,7 @@ bool TMoverParameters::OperatePantographsValve(operation_t const State, range_t if (Notify != range_t::local) { - SendCtrlToNext("PantsValve", static_cast(State), CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::pantographsValve, static_cast(State), CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return true; @@ -1267,7 +1267,7 @@ bool TMoverParameters::OperatePantographValve(end const End, operation_t const S if (Notify != range_t::local) { - SendCtrlToNext("PantValve", + SendCtrlToNext(VehicleCommand::pantographValve, // HACK: pack the state, pantograph index and sender cab into 8-bit value // with high bit storing front/rear pantograph, and 7th bit storing sender cab static_cast(0x80 * (End == end::front ? 0 : 1) + 0x40 * (CabActive != -1 ? 1 : 0) + static_cast(State)), CabActive, @@ -1286,7 +1286,7 @@ bool TMoverParameters::DropAllPantographs(bool const State, range_t const Notify if (Notify != range_t::local) { - SendCtrlToNext("PantAllDown", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::pantographsAllDown, State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return State != initialstate; diff --git a/physics/mover/mover.cpp b/physics/mover/mover.cpp index bc9c74d65..5a86a41ac 100644 --- a/physics/mover/mover.cpp +++ b/physics/mover/mover.cpp @@ -676,12 +676,12 @@ bool TMoverParameters::Sandbox(bool const State, range_t const Notify) if (State == true) { // switch on - SendCtrlToNext("Sandbox", 1, CabActive, couplingtype); + SendCtrlToNext(VehicleCommand::sandbox, 1, CabActive, couplingtype); } else { // switch off - SendCtrlToNext("Sandbox", 0, CabActive, couplingtype); + SendCtrlToNext(VehicleCommand::sandbox, 0, CabActive, couplingtype); } } @@ -694,7 +694,7 @@ bool TMoverParameters::Sandbox(bool const State, range_t const Notify) // ************************************************************************************************* bool TMoverParameters::SandboxAutoAllow(bool State) { - // SendCtrlToNext("SandboxAutoAllow", int(State), CabActive, ctrain_controll); + // SendCtrlToNext(VehicleCommand::sandboxAutoAllow, int(State), CabActive, ctrain_controll); if (SandDoseAutoAllow != State) { diff --git a/physics/mover/pneumatics.cpp b/physics/mover/pneumatics.cpp index 923fb7f0e..5ed05fbd5 100644 --- a/physics/mover/pneumatics.cpp +++ b/physics/mover/pneumatics.cpp @@ -236,8 +236,8 @@ bool TMoverParameters::EpFuseSwitch(bool State) } else return false; - // if (EpFuse == true) SendCtrlToNext("EpFuseSwitch", 1, CabActive) - // else SendCtrlToNext("EpFuseSwitch", 0, CabActive); + // if (EpFuse == true) SendCtrlToNext(VehicleCommand::epFuseSwitch, 1, CabActive) + // else SendCtrlToNext(VehicleCommand::epFuseSwitch, 0, CabActive); } // ************************************************************************************************* @@ -248,7 +248,7 @@ bool TMoverParameters::SpringBrakeActivate(bool State) { if (Power24vIsAvailable || Power110vIsAvailable) { - SendCtrlToNext("SpringBrakeActivate", int(State), CabActive, SpringBrake.MultiTractionCoupler); + SendCtrlToNext(VehicleCommand::springBrakeActivate, int(State), CabActive, SpringBrake.MultiTractionCoupler); if (SpringBrake.Activate != State) { @@ -323,7 +323,7 @@ bool TMoverParameters::CompressorSwitch(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext("CompressorSwitch", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::compressorSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return CompressorAllow != initialstate; @@ -338,7 +338,7 @@ bool TMoverParameters::ChangeCompressorPreset(int const State, range_t const Not if (Notify != range_t::local) { - SendCtrlToNext("CompressorPreset", State, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::compressorPreset, State, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return CompressorListPos != initialstate; @@ -528,7 +528,7 @@ bool TMoverParameters::BrakeReleaser(int state) Hamulec->Releaser(state); } if (CabActive != 0) // rekurencyjne wysłanie do następnego - OK = SendCtrlToNext("BrakeReleaser", state, CabActive); + OK = SendCtrlToNext(VehicleCommand::brakeReleaser, state, CabActive); return OK; } @@ -579,7 +579,7 @@ bool TMoverParameters::SwitchEPBrake(int state) else EpForce = 0; Hamulec->SetEPS(EpForce); - SendCtrlToNext("Brake", EpForce, CabActive); + SendCtrlToNext(VehicleCommand::brake, EpForce, CabActive); } // OK:=SetFlag(BrakeStatus,((2*State-1)*b_epused)); // SendCtrlToNext('Brake',(state*(2*BrakeCtrlPos-1)),CabActive); @@ -660,7 +660,7 @@ bool TMoverParameters::BrakeDelaySwitch(int BDS) Hamulec->SetBrakeStatus(Hamulec->GetBrakeStatus() & ~64); // kopowanie nastawy hamulca do kolejnego czlonu - do przemyślenia if (CabActive != 0) - SendCtrlToNext("BrakeDelay", BrakeDelayFlag, CabActive); + SendCtrlToNext(VehicleCommand::brakeDelay, BrakeDelayFlag, CabActive); } else rBDS = false; @@ -1237,7 +1237,7 @@ void TMoverParameters::UpdateEPBrake() TUHEX_StageActual = static_cast(EpForce); TUHEX_Active = TUHEX_StageActual > 0; // Ra 2014-11: na tym się wysypuje, ale nie wiem, w jakich warunkach - SendCtrlToNext("Brake", EpForce, CabActive); + SendCtrlToNext(VehicleCommand::brake, EpForce, CabActive); } // ************************************************************************************************* diff --git a/physics/mover/traction.cpp b/physics/mover/traction.cpp index ceb1d1ec3..c35dc307e 100644 --- a/physics/mover/traction.cpp +++ b/physics/mover/traction.cpp @@ -428,7 +428,7 @@ bool TMoverParameters::MotorBlowersSwitch(bool State, end const Side, range_t co if (Notify != range_t::local) { - SendCtrlToNext(Side == end::front ? "MotorBlowersFrontSwitch" : "MotorBlowersRearSwitch", fan.is_enabled ? 1 : 0, CabActive, + SendCtrlToNext(Side == end::front ? VehicleCommand::motorBlowersFrontSwitch : VehicleCommand::motorBlowersRearSwitch, fan.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } @@ -452,7 +452,7 @@ bool TMoverParameters::MotorBlowersSwitchOff(bool State, end const Side, range_t if (Notify != range_t::local) { - SendCtrlToNext(Side == end::front ? "MotorBlowersFrontSwitchOff" : "MotorBlowersRearSwitchOff", fan.is_disabled ? 1 : 0, CabActive, + SendCtrlToNext(Side == end::front ? VehicleCommand::motorBlowersFrontSwitchOff : VehicleCommand::motorBlowersRearSwitchOff, fan.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } @@ -473,7 +473,7 @@ bool TMoverParameters::TractionModeSwitch(traction_mode const Mode, range_t cons if (Notify != range_t::local && accepted) { - SendCtrlToNext("TractionMode", Mode == traction_mode::genset ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::tractionMode, Mode == traction_mode::genset ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return TractionMode != initialstate; @@ -1287,7 +1287,7 @@ void TMoverParameters::SpeedControlByPosition(double dt) if (NewSCAP != SpeedCtrlValue) { SpeedCtrlValue = NewSCAP; - // SendCtrlToNext("SpeedCntrl", SpeedCtrlValue, CabActive); + // SendCtrlToNext(VehicleCommand::speedControl, SpeedCtrlValue, CabActive); } } } @@ -1701,7 +1701,7 @@ bool TMoverParameters::RelayReset(int const Relays, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext("RelayReset", Relays, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::relayReset, Relays, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return reset; @@ -1789,7 +1789,7 @@ bool TMoverParameters::MaxCurrentSwitch(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext("MaxCurrentSwitch", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::maxCurrentSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); } return State != initialstate; @@ -1810,14 +1810,14 @@ bool TMoverParameters::MinCurrentSwitch(bool State) Imin = IminHi; MCS = true; if (CabActive != 0) - SendCtrlToNext("MinCurrentSwitch", 1, CabActive); + SendCtrlToNext(VehicleCommand::minCurrentSwitch, 1, CabActive); } if (!State && Imin == IminHi) { Imin = IminLo; MCS = true; if (CabActive != 0) - SendCtrlToNext("MinCurrentSwitch", 0, CabActive); + SendCtrlToNext(VehicleCommand::minCurrentSwitch, 0, CabActive); } } return MCS; diff --git a/physics/vehiclecommand.cpp b/physics/vehiclecommand.cpp new file mode 100644 index 000000000..9b8e6fc72 --- /dev/null +++ b/physics/vehiclecommand.cpp @@ -0,0 +1,116 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "physics/vehiclecommand.h" + +#include +#include +#include + +#include "utilities/utilities.h" + +namespace +{ + +using enum VehicleCommand; + +// the names of the commands, as the scenery files write them +constexpr std::array, 59> commandNames{{ + {mainController, "MainCtrl"}, + {secondaryController, "ScndCtrl"}, + {integratedController, "EIMIC"}, + {speedControl, "SpeedCntrl"}, + {speedControlParking, "SpeedCtrlUnit.Parking"}, + {direction, "Direction"}, + {autoRelaySwitch, "AutoRelaySwitch"}, + {maxCurrentSwitch, "MaxCurrentSwitch"}, + {minCurrentSwitch, "MinCurrentSwitch"}, + {relayReset, "RelayReset"}, + {cabActivation, "CabActivisation"}, + {cabSignal, "CabSignal"}, + {departureSignal, "DepartureSignal"}, + {tractionMode, "TractionMode"}, + {brake, "Brake"}, + {emergencyBrake, "Emergency_brake"}, + {brakeDelay, "BrakeDelay"}, + {brakeReleaser, "BrakeReleaser"}, + {springBrakeActivate, "SpringBrakeActivate"}, + {epFuseSwitch, "EpFuseSwitch"}, + {sandbox, "Sandbox"}, + {sandboxAutoAllow, "SandboxAutoAllow"}, + {compressorSwitch, "CompressorSwitch"}, + {compressorPreset, "CompressorPreset"}, + {converterSwitch, "ConverterSwitch"}, + {batterySwitch, "BatterySwitch"}, + {mainSwitch, "MainSwitch"}, + {heatingSwitch, "HeatingSwitch"}, + {gensetSwitch, "GensetSwitch"}, + {pantographValve, "PantValve"}, + {pantographsValve, "PantsValve"}, + {pantographsAllDown, "PantAllDown"}, + {compartmentLightsSwitch, "CompartmentLightsSwitch"}, + {compartmentLightsSwitchOff, "CompartmentLightsSwitchOff"}, + {waterPumpBreakerSwitch, "WaterPumpBreakerSwitch"}, + {waterPumpSwitch, "WaterPumpSwitch"}, + {waterPumpSwitchOff, "WaterPumpSwitchOff"}, + {waterHeaterBreakerSwitch, "WaterHeaterBreakerSwitch"}, + {waterHeaterSwitch, "WaterHeaterSwitch"}, + {waterCircuitsLinkSwitch, "WaterCircuitsLinkSwitch"}, + {fuelPumpSwitch, "FuelPumpSwitch"}, + {fuelPumpSwitchOff, "FuelPumpSwitchOff"}, + {oilPumpSwitch, "OilPumpSwitch"}, + {oilPumpSwitchOff, "OilPumpSwitchOff"}, + {motorBlowersFrontSwitch, "MotorBlowersFrontSwitch"}, + {motorBlowersFrontSwitchOff, "MotorBlowersFrontSwitchOff"}, + {motorBlowersRearSwitch, "MotorBlowersRearSwitch"}, + {motorBlowersRearSwitchOff, "MotorBlowersRearSwitchOff"}, + {doorOpen, "DoorOpen"}, + {doorClose, "DoorClose"}, + {doorLock, "DoorLock"}, + {doorMode, "DoorMode"}, + {doorPermit, "DoorPermit"}, + {doorStep, "DoorStep"}, + {setDamage, "SetDamage"}, + {load, "Load="}, + {unload, "UnLoad="}, + {none, ""}, + {unknown, ""}, +}}; + +} // namespace + +ParsedVehicleCommand ParseVehicleCommand(std::string const &Text) +{ + if (Text.empty()) + { + return {none, {}}; + } + // Load= and UnLoad= begin the text, the name of the load follows + if (Text.starts_with("Load=")) + { + return {load, extract_value("Load", Text)}; + } + if (Text.starts_with("UnLoad=")) + { + return {unload, extract_value("UnLoad", Text)}; + } + auto const named{std::ranges::find(commandNames, std::string_view{Text}, &std::pair::second)}; + if (named == commandNames.end() || named->first == load || named->first == unload) + { + return {unknown, {}}; + } + return {named->first, {}}; +} + +std::string_view VehicleCommandName(VehicleCommand const Command) +{ + auto const named{std::ranges::find(commandNames, Command, &std::pair::first)}; + return named != commandNames.end() ? named->second : std::string_view{}; +} diff --git a/physics/vehiclecommand.h b/physics/vehiclecommand.h new file mode 100644 index 000000000..fff9b1fc8 --- /dev/null +++ b/physics/vehiclecommand.h @@ -0,0 +1,105 @@ +/* +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 commands the vehicles of a train pass to each other through their couplings (the control wire of the multiple +// unit, the brake pipe and the others), and the ones a scenery, a script or the driver gives a vehicle. inside the +// simulation they are VehicleCommand; their names are only read where a command comes as text (events, Lua) and +// written where it is shown (the log, the AI) + +#pragma once + +#include +#include +#include + +enum class VehicleCommand +{ + none, // no command + unknown, // a command given as text which no vehicle knows: the AI may still read it + // the controllers + mainController, // MainCtrl + secondaryController, // ScndCtrl + integratedController, // EIMIC: the integrated controller of an induction motor drive, relative traction or braking + speedControl, // SpeedCntrl + speedControlParking, // SpeedCtrlUnit.Parking + // the direction, the automatic start and the current relays + direction, // Direction + autoRelaySwitch, // AutoRelaySwitch + maxCurrentSwitch, // MaxCurrentSwitch + minCurrentSwitch, // MinCurrentSwitch + relayReset, // RelayReset + // the cab + cabActivation, // CabActivisation + cabSignal, // CabSignal + departureSignal, // DepartureSignal + tractionMode, // TractionMode + // the brakes + brake, // Brake + emergencyBrake, // Emergency_brake + brakeDelay, // BrakeDelay + brakeReleaser, // BrakeReleaser + springBrakeActivate, // SpringBrakeActivate + epFuseSwitch, // EpFuseSwitch: passed on, but no vehicle acts on it + sandbox, // Sandbox + sandboxAutoAllow, // SandboxAutoAllow: passed on, but no vehicle acts on it + // the compressor and the converter + compressorSwitch, // CompressorSwitch + compressorPreset, // CompressorPreset + converterSwitch, // ConverterSwitch + // the power + batterySwitch, // BatterySwitch + mainSwitch, // MainSwitch + heatingSwitch, // HeatingSwitch + gensetSwitch, // GensetSwitch + pantographValve, // PantValve + pantographsValve, // PantsValve + pantographsAllDown, // PantAllDown + compartmentLightsSwitch, // CompartmentLightsSwitch + compartmentLightsSwitchOff, // CompartmentLightsSwitchOff + // the pumps of a diesel engine + waterPumpBreakerSwitch, // WaterPumpBreakerSwitch + waterPumpSwitch, // WaterPumpSwitch + waterPumpSwitchOff, // WaterPumpSwitchOff + waterHeaterBreakerSwitch, // WaterHeaterBreakerSwitch + waterHeaterSwitch, // WaterHeaterSwitch + waterCircuitsLinkSwitch, // WaterCircuitsLinkSwitch + fuelPumpSwitch, // FuelPumpSwitch + fuelPumpSwitchOff, // FuelPumpSwitchOff + oilPumpSwitch, // OilPumpSwitch + oilPumpSwitchOff, // OilPumpSwitchOff + // the traction motor blowers + motorBlowersFrontSwitch, // MotorBlowersFrontSwitch + motorBlowersFrontSwitchOff, // MotorBlowersFrontSwitchOff + motorBlowersRearSwitch, // MotorBlowersRearSwitch + motorBlowersRearSwitchOff, // MotorBlowersRearSwitchOff + // the doors + doorOpen, // DoorOpen + doorClose, // DoorClose + doorLock, // DoorLock + doorMode, // DoorMode + doorPermit, // DoorPermit + doorStep, // DoorStep + // the load and the damage + load, // Load= + unload, // UnLoad= + setDamage, // SetDamage +}; + +// a command read from its text, with the name of the load for Load= and UnLoad= +struct ParsedVehicleCommand +{ + VehicleCommand command{VehicleCommand::none}; + std::string argument; // the name of the load, as extract_value() gives it +}; + +// the command a text names: none for an empty text, unknown for a text no vehicle knows. the names are the ones the +// scenery files, the scripts and the AI have always used, compared exactly +ParsedVehicleCommand ParseVehicleCommand(std::string const &Text); +// the name of a command, as the scenery files write it; empty for none and unknown +std::string_view VehicleCommandName(VehicleCommand Command); diff --git a/physics/vehicletypes.h b/physics/vehicletypes.h index b8160ab3d..077e94cb0 100644 --- a/physics/vehicletypes.h +++ b/physics/vehicletypes.h @@ -15,6 +15,8 @@ http://mozilla.org/MPL/2.0/. #include #include +#include "physics/vehiclecommand.h" + /// Global counter incremented when a string-to-numeric conversion fails during config parsing. extern int ConversionError; @@ -603,8 +605,12 @@ struct TDimension /// A pending command queued for the vehicle, with its arguments and propagation rules. struct TCommand { - /// Command name. - std::string Command; /*komenda*/ + /// The command. + VehicleCommand Command{VehicleCommand::none}; + /// The command as it came, where it came as text (an event, a script): the AI reads it. + std::string Text; + /// The name of the load of Load= and UnLoad=. + std::string Argument; /// First numeric argument. double Value1 = 0.0; /*argumenty komendy*/ /// Second numeric argument. diff --git a/tests/unit/COVERAGE.md b/tests/unit/COVERAGE.md index b782d23e6..7299267c9 100644 --- a/tests/unit/COVERAGE.md +++ b/tests/unit/COVERAGE.md @@ -35,7 +35,7 @@ Nothing creates these objects or calls these functions anywhere in the game, whi - **Base implementations always overridden:** `TFricMat::GetFC` (every material, the default P10 too, has its own) and `TPrzekladnik::Update` (every relay has its own). - **Functions without callers:** - In `brakes.cpp`: `PF_old`, `TBrake::GetBCF`, `TDriverHandle::OvrldButton`, `TReservoir::pa` and `TBrakeCyl::pa`. - - In `mover.cpp`: `BrakeVP`, `PipeRatio`, `RealPipeRatio`, `IncBrakeLevel`, `DecBrakeLevel`, `IncBrakePress`, `DecBrakePress`, `MainCtrlActualPowerPos` and `GetExternalCommand`. + - In `mover.cpp`: `BrakeVP`, `PipeRatio`, `RealPipeRatio`, `IncBrakeLevel`, `DecBrakeLevel`, `IncBrakePress`, `DecBrakePress` and `MainCtrlActualPowerPos`. (`GetExternalCommand` was removed.) - **Inverter failures** of the induction motor drives (`inverter::Failure_Drive`, `Failure_Const`, `Activate`): nothing ever sets them. The cab only shows them. The branches reading them in `TractionForce` can't be reached. ## Code only data no game vehicle has would run diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index 9534b36db..bafa01a82 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -725,7 +725,7 @@ TEST_CASE("collisions: SetDamage taking the derailment off clears the collision' wagon->derail_in_collision(COLLISION_PUSHED_OFF, "test"); REQUIRE(wagon->CollisionDerail == COLLISION_PUSHED_OFF); REQUIRE(wagon->Derailed == derailment::outcome::off_rails); - wagon->RunCommand("SetDamage", dtrain_out, -1); + wagon->RunCommand(VehicleCommand::setDamage, dtrain_out, -1); CHECK(wagon->CollisionDerail == NONE); CHECK(wagon->Derailed == derailment::outcome::none); CHECK_FALSE(TestFlag(wagon->DamageFlag, dtrain_out)); diff --git a/tests/unit/test_commands.cpp b/tests/unit/test_commands.cpp index ca77f078f..a0b6569db 100644 --- a/tests/unit/test_commands.cpp +++ b/tests/unit/test_commands.cpp @@ -248,7 +248,8 @@ TEST_CASE("commands: every command run on every real vehicle") { for (std::size_t i = 0; i < commands.size(); ++i) { auto const &command{commands[i]}; trace.mark(std::format("{} {} {}", command.name, command.value1, command.value2)); - done = real->RunCommand(command.name, command.value1, command.value2, coupling::control); + auto const parsed{ParseVehicleCommand(command.name)}; + done = real->RunCommand(parsed.command, command.value1, command.value2, coupling::control, parsed.argument); trace.sample(static_cast(i + 1), real.mover()); } trace.check(); @@ -463,8 +464,8 @@ TEST_CASE("commands: travel along the train, turned round for a vehicle facing b CHECK(consist.middle->CabActive == -1); CHECK(consist.last->CabActive == 1); // the command is done in each vehicle and cleared - CHECK(consist.middle->CommandIn.Command.empty()); - CHECK(consist.last->CommandIn.Command.empty()); + CHECK(consist.middle->CommandIn.Command == VehicleCommand::none); + CHECK(consist.last->CommandIn.Command == VehicleCommand::none); SUBCASE("door permits: the right side of the sender is the left one of a vehicle facing backwards") { consist.head->PermitDoors(side::right, true, range_t::consist); @@ -484,24 +485,24 @@ TEST_CASE("commands: travel along the train, turned round for a vehicle facing b CHECK(consist.last->Pantographs[end::rear].valve.is_enabled); } SUBCASE("sent backwards, it goes no further than the sender: nothing is coupled at its front") { - consist.head->RunCommand("DoorLock", 0, -1, coupling::control); + consist.head->RunCommand(VehicleCommand::doorLock, 0, -1, coupling::control); CHECK_FALSE(consist.head->Doors.lock_enabled); CHECK(consist.middle->Doors.lock_enabled); } SUBCASE("the same command again isn't taken by the next vehicle a second time") { - CHECK(consist.middle->SetInternalCommand("DoorStep", 0, 1, coupling::control)); - CHECK_FALSE(consist.middle->SetInternalCommand("DoorStep", 0, 1, coupling::control)); + CHECK(consist.middle->SetInternalCommand(VehicleCommand::doorStep, 0, 1, coupling::control)); + CHECK_FALSE(consist.middle->SetInternalCommand(VehicleCommand::doorStep, 0, 1, coupling::control)); CHECK_FALSE(consist.head->RunInternalCommand()); // nothing to run } } TEST_CASE("commands: don't pass a coupling without the control cable") { train consist{coupling::coupler | coupling::brakehose}; - consist.head->RunCommand("DoorLock", 0, 1, coupling::control); + consist.head->RunCommand(VehicleCommand::doorLock, 0, 1, coupling::control); CHECK_FALSE(consist.head->Doors.lock_enabled); CHECK(consist.middle->Doors.lock_enabled); // a command of another coupling goes through it - consist.head->RunCommand("DoorStep", 0, 1, coupling::brakehose); + consist.head->RunCommand(VehicleCommand::doorStep, 0, 1, coupling::brakehose); CHECK_FALSE(consist.middle->Doors.step_enabled); } @@ -518,7 +519,7 @@ TEST_CASE("commands: a wagon loaded and unloaded by commands, which repeat until wagon.run(30.0); CHECK(wagon->LoadAmount == doctest::Approx(12.0).epsilon(0.1)); CHECK(wagon->LoadType.name == "coal"); - CHECK(wagon->CommandIn.Command.empty()); + CHECK(wagon->CommandIn.Command == VehicleCommand::none); trace.mark("unload"); wagon->PutCommand("UnLoad=Coal", 20, 0, wagon->Loc); @@ -531,7 +532,7 @@ TEST_CASE("commands: a wagon loaded and unloaded by commands, which repeat until wagon->PutCommand("Load=passengers", 12, 0, wagon->Loc); wagon.run(10.0); CHECK(wagon->LoadAmount == doctest::Approx(0.0)); - CHECK_FALSE(wagon->CommandIn.Command.empty()); + CHECK_FALSE(wagon->CommandIn.Command == VehicleCommand::none); } SUBCASE("away from the place of the command nothing is loaded") { wagon->PutCommand("Load=Coal", 12, 5.0, TLocation{100.0, 0.0, 0.0}); @@ -542,6 +543,6 @@ TEST_CASE("commands: a wagon loaded and unloaded by commands, which repeat until SUBCASE("unloading an empty wagon isn't done either") { wagon->PutCommand("UnLoad=Coal", 12, 0, wagon->Loc); wagon.run(10.0); - CHECK_FALSE(wagon->CommandIn.Command.empty()); + CHECK_FALSE(wagon->CommandIn.Command == VehicleCommand::none); } } diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp index 1b0d74930..4a3a8efa7 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -235,10 +235,10 @@ TEST_CASE("derailment: SetDamage taking the derailment off puts the vehicle back } REQUIRE(eu07vehicle->Derailed == dr::outcome::overturned); // another flag taken off leaves it derailed - eu07vehicle->RunCommand("SetDamage", dtrain_engine, 1); - eu07vehicle->RunCommand("SetDamage", dtrain_engine, -1); + eu07vehicle->RunCommand(VehicleCommand::setDamage, dtrain_engine, 1); + eu07vehicle->RunCommand(VehicleCommand::setDamage, dtrain_engine, -1); CHECK(eu07vehicle->Derailed == dr::outcome::overturned); - CHECK(eu07vehicle->RunCommand("SetDamage", dtrain_out, -1)); + CHECK(eu07vehicle->RunCommand(VehicleCommand::setDamage, dtrain_out, -1)); CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); CHECK(eu07vehicle->Derailed == dr::outcome::none); } diff --git a/tests/unit/test_genset.cpp b/tests/unit/test_genset.cpp index a00ea257e..cadd39d28 100644 --- a/tests/unit/test_genset.cpp +++ b/tests/unit/test_genset.cpp @@ -650,7 +650,7 @@ TEST_CASE("genset: a scenery command reaches the selector") { cab.PutCommand("TractionMode", 1, 0, cab.Loc); dragon6.step(no_wire); CHECK(cab.GensetSelected()); - CHECK(cab.CommandIn.Command.empty()); + CHECK(cab.CommandIn.Command == VehicleCommand::none); cab.PutCommand("GensetSwitch", 1, 0, cab.Loc); dragon6.step(no_wire); CHECK(cab.Genset.is_enabled); diff --git a/tests/unit/test_vehicle_command.cpp b/tests/unit/test_vehicle_command.cpp new file mode 100644 index 000000000..737d66431 --- /dev/null +++ b/tests/unit/test_vehicle_command.cpp @@ -0,0 +1,43 @@ +#include "stdafx.h" +#include "doctest.h" + +#include + +#include "physics/vehiclecommand.h" + +// the commands of the vehicles read from their text (events, scripts, the AI) and named for the log: every command +// has the name the scenery files have always used, and reads back as itself + +TEST_CASE("vehicle commands read back from their names") { + using enum VehicleCommand; + for (auto command{static_cast(mainController)}; command <= static_cast(setDamage); ++command) { + auto const value{static_cast(command)}; + auto const name{std::string{VehicleCommandName(value)}}; + CAPTURE(name); + REQUIRE_FALSE(name.empty()); + if (value == load || value == unload) { + continue; // these carry the name of the load after the = + } + CHECK(ParseVehicleCommand(name).command == value); + CHECK(ParseVehicleCommand(name).argument.empty()); + } +} + +TEST_CASE("vehicle commands: the empty text, an unknown one, the load") { + CHECK(ParseVehicleCommand("").command == VehicleCommand::none); + CHECK(ParseVehicleCommand("SetVelocity").command == VehicleCommand::unknown); // the AI's, not a vehicle's + CHECK(ParseVehicleCommand("mainctrl").command == VehicleCommand::unknown); // the names are compared exactly + CHECK(ParseVehicleCommand("MainCtrl").command == VehicleCommand::mainController); + CHECK(ParseVehicleCommand("SpeedCtrlUnit.Parking").command == VehicleCommand::speedControlParking); + + auto const load{ParseVehicleCommand("Load=Coal")}; + CHECK(load.command == VehicleCommand::load); + CHECK(load.argument == "Coal"); + auto const unload{ParseVehicleCommand("UnLoad=passengers")}; + CHECK(unload.command == VehicleCommand::unload); + CHECK(unload.argument == "passengers"); + + CHECK(VehicleCommandName(VehicleCommand::none).empty()); + CHECK(VehicleCommandName(VehicleCommand::unknown).empty()); + CHECK(VehicleCommandName(VehicleCommand::integratedController) == "EIMIC"); +} diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index e6b6eff5d..833facfda 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -2516,7 +2516,7 @@ void TController::Activation() auto *targetvehicledriver { targetvehicle->Mechanik }; // zapamiętanie tego, co ewentualnie tam siedzi, żeby w razie dwóch zamienić miejscami // move to the new vehicle targetvehicle->Mechanik = this; // na razie bilokacja - targetvehicle->MoverParameters->SetInternalCommand("", 0, 0); // usunięcie ewentualnie zalegającej komendy (Change_direction?) + targetvehicle->MoverParameters->SetInternalCommand(VehicleCommand::none, 0, 0); // usunięcie ewentualnie zalegającej komendy (Change_direction?) if( targetvehicle->DirectionGet() != pVehicle->DirectionGet() ) { // jeśli są przeciwne do siebie to będziemy jechać w drugą stronę względem zasiedzianego pojazdu iDirection = -iDirection; @@ -4559,7 +4559,7 @@ void TController::SpeedCntrl(double DesiredSpeed) DesiredSpeed = 0; } mvControlling->SpeedCtrlSwitch(DesiredSpeed > 0); - mvControlling->RunCommand("SpeedCntrl", DesiredSpeed, mvControlling->CabActive); + mvControlling->RunCommand(VehicleCommand::speedControl, DesiredSpeed, mvControlling->CabActive); } else if (mvControlling->EngineType == TEngineType::DieselEngine) { @@ -4570,13 +4570,13 @@ void TController::SpeedCntrl(double DesiredSpeed) else if (mvControlling->ScndCtrlPos < 1) { mvControlling->IncScndCtrl(1); } - mvControlling->RunCommand("SpeedCntrl", DesiredSpeed, mvControlling->CabActive); + mvControlling->RunCommand(VehicleCommand::speedControl, DesiredSpeed, mvControlling->CabActive); } else if (mvControlling->ScndCtrlPosNo == 1) { mvControlling->IncScndCtrl(1); - mvControlling->RunCommand("SpeedCntrl", DesiredSpeed, mvControlling->CabActive); + mvControlling->RunCommand(VehicleCommand::speedControl, DesiredSpeed, mvControlling->CabActive); } else if (mvControlling->ScndCtrlPosNo > 1 && !mvOccupied->SpeedCtrlTypeTime) { @@ -4998,8 +4998,10 @@ TController::announce( announcement_t const Announcement ) { void TController::RecognizeCommand() { // odczytuje i wykonuje komendę przekazaną lokomotywie TCommand *c = &mvOccupied->CommandIn; - PutCommand(c->Command, c->Value1, c->Value2, c->Location, stopComm); - c->Command = ""; // usunięcie obsłużonej komendy + PutCommand(c->Text, c->Value1, c->Value2, c->Location, stopComm); + c->Command = VehicleCommand::none; + c->Argument.clear(); + c->Text = ""; // usunięcie obsłużonej komendy } void TController::PutCommand(std::string NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation, TStopReason reason) @@ -5493,7 +5495,7 @@ std::string TController::physicslog_line() const { << mvOccupied->fBrakeCtrlPos << " " << mvOccupied->LocalBrakePosA << " " << int(mvControlling->DirActive) << " " - << ( mvOccupied->CommandIn.Command.empty() ? "none" : mvOccupied->CommandIn.Command.c_str() ) << " " + << ( mvOccupied->CommandIn.Text.empty() ? "none" : mvOccupied->CommandIn.Text.c_str() ) << " " << mvOccupied->CommandIn.Value1 << " " << mvOccupied->CommandIn.Value2 << " " << int(mvControlling->SecuritySystem.is_blinking()) << " " @@ -7381,7 +7383,7 @@ TController::control_doors() { void TController::UpdateCommand() { - if( false == mvOccupied->CommandIn.Command.empty() && false == mvOccupied->RunInternalCommand() ) { + if( mvOccupied->CommandIn.Command != VehicleCommand::none && false == mvOccupied->RunInternalCommand() ) { // rozpoznaj komende bo lokomotywa jej nie rozpoznaje RecognizeCommand(); // samo czyta komendę wstawioną do pojazdu? } diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 5464570cb..b2f6a268e 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -3853,7 +3853,7 @@ bool TDynamicObject::Update(double dt, double dt1) if (MoverParameters->SpeedCtrl) MoverParameters->CheckSpeedCtrl(dt1); MoverParameters->eimic_real = std::min(MoverParameters->eimic,MoverParameters->eimicSpeedCtrl); - MoverParameters->SendCtrlToNext("EIMIC", MoverParameters->eimic_real, MoverParameters->CabActive); + MoverParameters->SendCtrlToNext(VehicleCommand::integratedController, MoverParameters->eimic_real, MoverParameters->CabActive); } if( Mechanik->primary() && MoverParameters->EngineType == TEngineType::ElectricInductionMotor ) { @@ -3884,7 +3884,7 @@ bool TDynamicObject::Update(double dt, double dt1) // Elf: full braking at once in the lowest position, and in the emergency brake position below it if (MoverParameters->EIMCtrlType == 2 && MoverParameters->MainCtrlPos <= MoverParameters->EIMCtrlEmergencyPositions()) eimic = -1.0; - MoverParameters->SendCtrlToNext("EIMIC", std::max(0., eimic), MoverParameters->CabActive); + MoverParameters->SendCtrlToNext(VehicleCommand::integratedController, std::max(0., eimic), MoverParameters->CabActive); auto LBR = std::max(-eimic, 0.); auto eim_lb = Mechanik->AIControllFlag || !MoverParameters->LocHandleTimeTraxx ? 0 : MoverParameters->eim_localbrake; diff --git a/vehicle/crew.cpp b/vehicle/crew.cpp index 360952c35..e375a0c0f 100644 --- a/vehicle/crew.cpp +++ b/vehicle/crew.cpp @@ -31,9 +31,9 @@ void cut_power(TMoverParameters &Vehicle) { Vehicle.eimic_real = 0.0; Vehicle.SpeedCtrlValue = 0.0; Vehicle.SpeedCtrlUnit.IsActive = false; - Vehicle.SendCtrlToNext("MainCtrl", Vehicle.MainCtrlPosForCoupled(), Vehicle.CabActive); - Vehicle.SendCtrlToNext("ScndCtrl", Vehicle.ScndCtrlPos, Vehicle.CabActive); - Vehicle.SendCtrlToNext("EIMIC", 0.0, Vehicle.CabActive); + Vehicle.SendCtrlToNext(VehicleCommand::mainController, Vehicle.MainCtrlPosForCoupled(), Vehicle.CabActive); + Vehicle.SendCtrlToNext(VehicleCommand::secondaryController, Vehicle.ScndCtrlPos, Vehicle.CabActive); + Vehicle.SendCtrlToNext(VehicleCommand::integratedController, 0.0, Vehicle.CabActive); } } // namespace From cf73ee05a60c6d940cf8d6d9a1d8e0a402c34aab Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Fri, 27 Nov 2026 21:01:45 +0100 Subject: [PATCH 007/123] refactor(ai): the driving flags of the AI are the named fields of DrivingFlags, not bits of iDrivigFlags TController kept 23 conditions of the movement of the train as the bits of one int (iDrivigFlags, the TMovementStatus constants), set and tested with masks, ~(a | b), SetFlag(x, -flag) and TestFlag. Each is a condition of its own, set and cleared on its own, so each is now a bool of its own in DrivingFlags: stopCloser, stopPoint, active, press, connect, primary, late, stopHere, startHorn, startHornNow, startHornDone, oerlikons, incSpeed, trackEnd, switchFound, guardSignal, visibility, doorOpened, pushPull, signalFound, stopPointFound, guardOpenDoor, departureWarned. The three horn flags stay three: the code sets them in combinations that aren't a single state (startHornDone without startHorn, for one). The debug panel lists the flags set, as before (DrivingFlags::ActiveNames()). One fix: SetSignal (from the map) put the signal in bit 30 or 31 by its number, and any other number set the driving flag of that bit (5 made the driver primary). Only 30 (Pc6) and 31 (A1) mean a signal now, kept in signalPc6 and signalA1; nothing reads them yet, as before. No change in behaviour: 1144/1144 tests, golden traces exact against staging 62f7a29b. --- application/driveruipanels.cpp | 13 +- vehicle/Driver.cpp | 295 ++++++++++++++++++--------------- vehicle/Driver.h | 78 +++++---- 3 files changed, 203 insertions(+), 183 deletions(-) diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index fd77d352b..8d6e5829d 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -1271,17 +1271,10 @@ debug_panel::update_section_ai( std::vector &Output ) const { Output.emplace_back( textline, Global.UITextColor ); // ai driving flags - std::vector const drivingflagnames { - "StopCloser", "StopPoint", "Active", "Press", "Connect", "Primary", "Late", "StopHere", - "StartHorn", "StartHornNow", "StartHornDone", "Oerlikons", "IncSpeed", "TrackEnd", "SwitchFound", "GuardSignal", - "Visibility", "DoorOpened", "PushPull", "SignalFound", "StopPointFound", "GuardOpenDoor", "DepartureWarned" - /*"SemaphorWasElapsed", "TrainInsideStation", "SpeedLimitFound"*/ }; - textline = "Driving flags:"; - for( int idx = 0, flagbit = 1; idx < drivingflagnames.size(); ++idx, flagbit <<= 1 ) { - if( mechanik.DrivigFlags() & flagbit ) { - textline += "\n " + drivingflagnames[ idx ]; - } + for( auto const name : mechanik.DrivingFlagsState().ActiveNames() ) { + textline += "\n "; + textline += name; } Output.emplace_back( textline, Global.UITextColor ); diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 833facfda..9ad82244d 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -1013,7 +1013,10 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN IsScheduledPassengerStopVisible = false; mvOccupied->SecuritySystem.set_cabsignal_lock(false); // te flagi są ustawiane tutaj, w razie potrzeby - iDrivigFlags &= ~(moveTrackEnd | moveSwitchFound | moveSignalFound | /*moveSpeedLimitFound*/ moveStopPointFound ); + drivingFlags.trackEnd = false; + drivingFlags.switchFound = false; + drivingFlags.signalFound = false; + drivingFlags.stopPointFound = false; SignalAreaEndDist = -1.0; update_point_limits(); @@ -1029,7 +1032,7 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN v = point.fVelNext; // odczyt prędkości do zmiennej pomocniczej if( TestFlag( point.iFlags, spSwitch ) ) { // zwrotnice są usuwane z tabelki dopiero po zjechaniu z nich - iDrivigFlags |= moveSwitchFound; // rozjazd z przodu/pod ogranicza np. sens skanowania wstecz + drivingFlags.switchFound = true; // rozjazd z przodu/pod ogranicza np. sens skanowania wstecz SwitchClearDist = point.fDist + point.trTrack->Length() + fLength; } else if ( TestFlag(point.iFlags, spEvent) && TableUpdateEvent(v, go, point, d_to_next_sem, idx) ) // W4 może się deaktywować @@ -1055,7 +1058,7 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN && true == TestFlag(point.iFlags, spEnabled | spEvent | spPassengerStopPoint) && false == IsAtPassengerStop ) { // ma podjechać bliżej - czy na pewno w tym miejscu taki warunek? - a = d > passengerstopmaxdistance || (iDrivigFlags & moveStopCloser) != 0 ? fAcc : 0.0; + a = d > passengerstopmaxdistance || drivingFlags.stopCloser ? fAcc : 0.0; } else { // przyspieszenie: ujemne, gdy trzeba hamować @@ -1191,7 +1194,7 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN // jeśli mieliśmy ograniczenie z semafora i nie ma przed nami if( VelSignalLast >= 0.0 - && (iDrivigFlags & (moveSignalFound | moveSwitchFound | moveStopPointFound)) == 0 + && ( false == drivingFlags.signalFound && false == drivingFlags.switchFound && false == drivingFlags.stopPointFound ) && true == TestFlag(OrderCurrentGet(), Obey_train) ) { VelSignalLast = -1.0; } @@ -1228,7 +1231,7 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub // stop points are irrelevant when not in one of the basic modes if( ( OrderCurrentGet() & ( Shunt | Loose_shunt | Obey_train | Bank ) ) == 0 ) { return true; } // jeśli przystanek, trzeba obsłużyć wg rozkładu - iDrivigFlags |= moveStopPointFound; + drivingFlags.stopPointFound = true; // the W4 and the timetable name the station each in its own file, so the two spellings are compared by their key: // with or without the polish letters, in any case, with spaces or underscores if( false == timetable::stop_point_is_for( Point.evEvent->input_text(), asNextStop ) ) @@ -1250,7 +1253,7 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub } return true; // ignorowanie jakby nie było tej pozycji } - else if (iDrivigFlags & moveStopPoint) // jeśli pomijanie W4, to nie sprawdza czasu odjazdu + else if (drivingFlags.stopPoint) // jeśli pomijanie W4, to nie sprawdza czasu odjazdu { // tylko gdy nazwa zatrzymania się zgadza if( ( OrderCurrentGet() & ( Obey_train | Bank ) ) != 0 ) { // check whether the station specifies radio channel change @@ -1348,7 +1351,7 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub // peronu, chyba że pociąg jest dłuższy, to wtedy minimalna. // jeśli długość peronu ((sSpeedTable[i].evEvent->ValueGet(2)) nie podana, // przyjąć odległość fMinProximityDist - && ((iDrivigFlags & moveStopCloser) != 0 ? + && (drivingFlags.stopCloser ? Point.fDist + fLength + (Point.fMoved - stopminproximity * 0.5f) <= std::max(std::abs(Point.evEvent->input_value(2)), 2.0 * stopmaxproximity + fLength) : Point.fDist < Signaldistance); @@ -1370,7 +1373,7 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub // jeśli się zatrzymał przy W4, albo stał w momencie zobaczenia W4 if( !AIControllFlag ) { // w razie przełączenia na AI ma nie podciągać do W4, gdy użytkownik zatrzymał za daleko - iDrivigFlags &= ~moveStopCloser; + drivingFlags.stopCloser = false; } if (TrainParams.UpdateMTable( simulation::Time, asNextStop) ) { // to się wykona tylko raz po zatrzymaniu na W4 @@ -1380,7 +1383,8 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub if( TrainParams.StationIndex < TrainParams.StationCount ) { // jeśli są dalsze stacje, bez trąbienia przed odjazdem // also ignore any horn cue that may be potentially set below 1 km/h and before the actual full stop - iDrivigFlags &= ~( moveStartHorn | moveStartHornNow ); + drivingFlags.startHorn = false; + drivingFlags.startHornNow = false; } UpdateDelayFlag(); @@ -1401,9 +1405,9 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub if (TrainParams.DirectionChange()) { // jeśli "@" w rozkładzie, to wykonanie dalszych komend // wykonanie kolejnej komendy, nie dotyczy ostatniej stacji - if (iDrivigFlags & movePushPull) { + if (drivingFlags.pushPull) { // SN61 ma się też nie ruszać, chyba że ma wagony - iDrivigFlags |= moveStopHere; // EZT ma stać przy peronie + drivingFlags.stopHere = true; // EZT ma stać przy peronie if (OrderNextGet() != Change_direction) { OrderPush(Change_direction); // zmiana kierunku OrderPush( @@ -1415,12 +1419,13 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub else { // a dla lokomotyw... // pozwolenie na przejechanie za W4 przed czasem i nie ma stać - iDrivigFlags &= ~( moveStopPoint | moveStopHere ); + drivingFlags.stopPoint = false; + drivingFlags.stopHere = false; } // przejście do kolejnego rozkazu (zmiana kierunku, odczepianie) JumpToNextOrder(); // ma nie podjeżdżać pod W4 po przeciwnej stronie - iDrivigFlags &= ~moveStopCloser; + drivingFlags.stopCloser = false; // ten W4 nie liczy się już zupełnie (nie wyśle SetVelocity) Point.iFlags = 0; // jechać @@ -1459,13 +1464,13 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub if( static_cast( std::floor( std::abs( Point.evEvent->input_value( 1 ) ) ) ) % 2 ) { // nie podjeżdżać do semafora, jeśli droga nie jest wolna - iDrivigFlags |= moveStopHere; + drivingFlags.stopHere = true; } else { //po czasie jedź dalej - iDrivigFlags &= ~moveStopHere; + drivingFlags.stopHere = false; } - iDrivigFlags |= moveStopCloser; // do następnego W4 podjechać blisko (z dociąganiem) + drivingFlags.stopCloser = true; // do następnego W4 podjechać blisko (z dociąganiem) Point.iFlags = 0; // nie liczy się już zupełnie (nie wyśle SetVelocity) Point.fVelNext = -1; // można jechać za W4 if( Point.fDist <= 0.0 && eSignNext == Point.evEvent ) { @@ -1478,7 +1483,7 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub if( false == tsGuardSignal.empty() && true == timetable::has_conductor( m_stopflags ) ) { // jeśli mamy głos kierownika, to odegrać - iDrivigFlags |= moveGuardSignal; + drivingFlags.guardSignal = true; } return true; // nie analizować prędkości } // koniec startu z zatrzymania @@ -1486,7 +1491,7 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub cue_action(driver_hint::waitdeparturetime); if (timetable::has_conductor(m_stopflags) // no conductor, no door kept open for him && TrainParams.IsTimeToGo(simulation::Time.data().wHour, simulation::Time.data().wMinute + simulation::Time.data().wSecond*0.0167 + 0.1)) { //if is less than 6 sec to departure - iDrivigFlags |= moveGuardOpenDoor; + drivingFlags.guardOpenDoor = true; GuardOpenDoor(); } } @@ -1505,10 +1510,10 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub vehicle->DestinationClear(); } // ma nie podjeżdżać pod W4 i ma je pomijać - iDrivigFlags &= ~moveStopCloser; - if( false == TestFlag( iDrivigFlags, movePushPull ) ) { + drivingFlags.stopCloser = false; + if( false == drivingFlags.pushPull ) { // if the consist can change direction through a simple cab change it doesn't need fiddling with recognition of passenger stops - iDrivigFlags &= ~moveStopPoint; + drivingFlags.stopPoint = false; } fLastStopExpDist = -1.0f; // nie ma rozkładu, nie ma usuwania stacji Point.iFlags = 0; // W4 nie liczy się już (nie wyśle SetVelocity) @@ -1520,7 +1525,8 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub // wykonanie kolejnego rozkazu (Change_direction albo Shunt) JumpToNextOrder(); // ma się nie ruszać aż do momentu podania sygnału - iDrivigFlags |= moveStopHere | moveStartHorn; + drivingFlags.stopHere = true; + drivingFlags.startHorn = true; return true; // nie analizować prędkości } // koniec obsługi ostatniej stacji } // vel 0, at passenger stop @@ -1940,14 +1946,14 @@ TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPo if ( Point.fDist < 0.0) { // jeśli wskaźnik został minięty VelSignalLast = Velocity; //ustawienie prędkości na -1 } - else if( ( iDrivigFlags & moveSwitchFound ) == 0 ) { // jeśli rozjazdy już minięte + else if( ( false == drivingFlags.switchFound ) ) { // jeśli rozjazdy już minięte VelSignalLast = Velocity; //!!! to też koniec ograniczenia } } else { // w trybie manewrowym: skanować od niego wstecz, stanąć po wyjechaniu za sygnalizator i zmienić kierunek Velocity = 0.0; // zmiana kierunku może być podanym sygnałem, ale wypadało by zmienić światło wcześniej - if( ( iDrivigFlags & moveSwitchFound ) == 0 ) { // jeśli nie ma rozjazdu + if( ( false == drivingFlags.switchFound ) ) { // jeśli nie ma rozjazdu // check for presence of a signal facing the opposite direction // if there's one, we'll want to pass it before changing direction basic_event *foundevent = nullptr; @@ -1958,7 +1964,7 @@ TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPo auto *foundtrack = BackwardTraceRoute( scandistance, scandirection, scanvehicle, foundevent, -1, end::front, false ); } if( foundevent == nullptr ) { - iDrivigFlags |= moveTrackEnd; // to dalsza jazda trwale ograniczona (W5, koniec toru) + drivingFlags.trackEnd = true; // to dalsza jazda trwale ograniczona (W5, koniec toru) } } } @@ -1973,7 +1979,7 @@ TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPo // jazda na widoczność - skanować możliwość kolizji i nie podjeżdżać zbyt blisko // usunąć flagę po podjechaniu blisko semafora zezwalającego na jazdę // ostrożnie interpretować sygnały - semafor może zezwalać na jazdę pociągu z przodu! - iDrivigFlags |= moveVisibility; + drivingFlags.visibility = true; // store the ordered restricted speed and don't exceed it until the flag is cleared VelRestricted = Point.evEvent->input_value(2); } @@ -2003,7 +2009,7 @@ TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPo } else { //jeśli z przodu to dajemy flagę, że jest - iDrivigFlags |= moveSignalFound; + drivingFlags.signalFound = true; Signaldistance = std::min( Point.fDist, Signaldistance ); // if there's another vehicle closer to the signal, then it's likely its intended recipient // HACK: if so, make it a stop point, to prevent non-signals farther down affect us @@ -2146,7 +2152,7 @@ TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPo // jeśli event // ale inny niż ten, na którym minięto S1, chyba że się już zmieniło // sygnał zezwalający na jazdę wyłącza jazdę na widoczność (po S1 na SBL) - iDrivigFlags &= ~moveVisibility; + drivingFlags.visibility = false; // remove restricted speed VelRestricted = -1.0; } @@ -2169,7 +2175,7 @@ TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPo // TBD, TODO: revise this check for bank/loose_shunt; we might want to ignore obstacles with no owner in these modes if (Point.fDist < Obstacle.distance) { - if (true == TestFlag(iDrivigFlags, moveStopHere)) + if (true == drivingFlags.stopHere) { // jeśli ma stać, dostaje komendę od razu Command = TCommandType::cm_Command; // komenda z komórki, do wykonania po zatrzymaniu @@ -2369,7 +2375,7 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, OrdersClear(); if( true == Primary ) { - iDrivigFlags |= movePrimary; // aktywnie prowadzące pojazd + drivingFlags.primary = true; // aktywnie prowadzące pojazd } if( mvOccupied != nullptr ) { @@ -2425,7 +2431,7 @@ std::string TController::OrderCurrent() const { // pobranie aktualnego rozkazu celem wyświetlenia auto const order { OrderCurrentGet() }; // generally prioritize direction change... - if( order & Change_direction && false == TestFlag(iDrivigFlags, moveConnect) ) { + if( order & Change_direction && false == drivingFlags.connect ) { // ...but not in the middle of coupling operation return STR("Change direction"); } @@ -2785,15 +2791,15 @@ bool TController::CheckVehicles(TOrders user) fMass = 0.0; // całkowita masa do liczenia stycznej składowej grawitacji fVelMax = -1; // ustalenie prędkości dla składu bool main = true; // czy jest głównym sterującym - iDrivigFlags |= moveOerlikons; // zakładamy, że są same Oerlikony + drivingFlags.oerlikons = true; // zakładamy, że są same Oerlikony // Ra 2014-09: ustawić moveMultiControl, jeśli wszystkie są w ukrotnieniu (i skrajne mają kabinę?) while (p) { // sprawdzanie, czy jest głównym sterującym, żeby nie było konfliktu if( p->Mechanik // jeśli ma obsadę - && p->Mechanik != this && p->Mechanik->iDrivigFlags & movePrimary ) { // ale chodzi o inny pojazd, niż aktualnie sprawdzający + && p->Mechanik != this && p->Mechanik->drivingFlags.primary ) { // ale chodzi o inny pojazd, niż aktualnie sprawdzający // a tamten ma priorytet // TODO: take into account drivers' operating modes, one or more of them might be on banking duty - if (iDrivigFlags & movePrimary && mvOccupied->DirAbsolute && mvOccupied->BrakeCtrlPos >= -1) + if (drivingFlags.primary && mvOccupied->DirAbsolute && mvOccupied->BrakeCtrlPos >= -1) { // jeśli rządzi i ma kierunek p->Mechanik->primary(false); // dezaktywuje tamtego @@ -2814,17 +2820,17 @@ bool TController::CheckVehicles(TOrders user) // reset oerlikon brakes consist flag as different type was detected if( p->MoverParameters->BrakeSubsystem != TBrakeSubSystem::ss_ESt && p->MoverParameters->BrakeSubsystem != TBrakeSubSystem::ss_LSt ) { - iDrivigFlags &= ~moveOerlikons; + drivingFlags.oerlikons = false; } p = p->Neighbour(dir); // pojazd podłączony od wskazanej strony } if( main ) { - iDrivigFlags |= movePrimary; // nie znaleziono innego, można się porządzić + drivingFlags.primary = true; // nie znaleziono innego, można się porządzić } ControllingSet(); // ustalenie członu do sterowania (może być inny niż zasiedziany) - if (iDrivigFlags & movePrimary) + if (drivingFlags.primary) { // jeśli jest aktywnie prowadzącym pojazd, może zrobić własny porządek auto pantmask = 1; p = frontvehicle; @@ -2904,10 +2910,10 @@ bool TController::CheckVehicles(TOrders user) // nastawianie hamulca do jazdy pociągowej AutoRewident(); /* - if( ( true == TestFlag( iDrivigFlags, moveConnect ) ) + if( ( true == drivingFlags.connect ) && ( true == TestFlag( OrderCurrentGet(), Connect ) ) ) { iCoupler = 0; // dalsza jazda manewrowa już bez łączenia - iDrivigFlags &= ~moveConnect; // zdjęcie flagi doczepiania + drivingFlags.connect = false; // zdjęcie flagi doczepiania SetVelocity( 0, 0, stopJoin ); // wyłączyć przyspieszanie JumpToNextOrder(); // wykonanie następnej komendy } @@ -2917,11 +2923,11 @@ bool TController::CheckVehicles(TOrders user) // detect push-pull train configurations and mark them accordingly if( frontvehicle->is_connected( pVehicles[ end::rear ], coupling::control ) ) { // zmiana czoła przez zmianę kabiny - iDrivigFlags |= movePushPull; + drivingFlags.pushPull = true; } else { // zmiana czoła przez manewry - iDrivigFlags &= ~movePushPull; + drivingFlags.pushPull = false; } // HACK: ensure vehicle lights are active from the beginning, if it had pre-activated battery @@ -3165,11 +3171,11 @@ void TController::SetVelocity(double NewVel, double NewVelNext, TStopReason r) // to całe poniżej to warunki zatrąbienia przed ruszeniem if( is_train() // tylko pociągi trąbią (unimogi tylko na torach, więc trzeba raczej sprawdzać tor) && (OrderCurrentGet() & (Shunt | Loose_shunt | Obey_train | Bank | Connect | Prepare_engine)) != 0 // jeśli jedzie w dowolnym trybie - && (iDrivigFlags & moveStartHorn) != 0 // jezeli trąbienie włączone - && (iDrivigFlags & (moveStartHornDone | moveConnect)) == 0 // jeśli nie zatrąbione i nie jest to moment podłączania składu + && drivingFlags.startHorn // jezeli trąbienie włączone + && ( false == drivingFlags.startHornDone && false == drivingFlags.connect ) // jeśli nie zatrąbione i nie jest to moment podłączania składu && mvOccupied->Vel < 1.0 // jesli stoi (na razie, bo chyba powinien też, gdy hamuje przed semaforem) && ( NewVel >= 1.0 || NewVel < 0.0 ) ) { // o ile prędkość jest znacząca zatrąb po odhamowaniu - iDrivigFlags |= moveStartHornNow; + drivingFlags.startHornNow = true; } } VelSignal = NewVel; // prędkość zezwolona na aktualnym odcinku @@ -3388,7 +3394,7 @@ bool TController::PrepareEngine() eStopReason = stopNone; } // może skanować sygnały i reagować na komendy - iDrivigFlags |= moveActive; + drivingFlags.active = true; } iEngineActive = isready; @@ -3519,7 +3525,7 @@ bool TController::ReleaseEngine() { eAction = TAction::actSleep; //śpi (wygaszony) OrderNext(Wait_for_orders); //żeby nie próbował coś robić dalej - iDrivigFlags &= ~moveActive; // ma nie skanować sygnałów i nie reagować na komendy + drivingFlags.active = false; // ma nie skanować sygnałów i nie reagować na komendy TableClear(); // zapominamy ograniczenia VelSignalLast = -1.0; } @@ -3975,7 +3981,7 @@ bool TController::IncSpeed() { case TEngineType::None: // McZapkie-041003: wagon sterowniczy if (mvControlling->MainCtrlPosNo > 0) // jeśli ma czym kręcić - iDrivigFlags |= moveIncSpeed; // ustawienie flagi jazdy + drivingFlags.incSpeed = true; // ustawienie flagi jazdy return false; case TEngineType::ElectricSeriesMotor: if (mvPantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) // jeśli pantografujący @@ -3989,7 +3995,7 @@ bool TController::IncSpeed() if( mvControlling->EnginePowerSource.SourceType == TPowerSource::Accumulator ) { fVoltage = mvControlling->BatteryVoltage; } - if (!IsAnyMotorOverloadRelayOpen && !mvControlling->ControlPressureSwitch && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->StLinFlag) && (Ready || iDrivigFlags & movePress)) { + if (!IsAnyMotorOverloadRelayOpen && !mvControlling->ControlPressureSwitch && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->StLinFlag) && (Ready || drivingFlags.press)) { // youBy polecił dodać 2012-09-08 v367 // na pozycji 0 przejdzie, a na pozostałych będzie czekać, aż się załączą liniowe (zgaśnie DelayCtrlFlag) auto const usehighoverloadrelaythreshold{mvControlling->TrainType != train_type::et42 // ET42 uses these variables for different purpose. TODO: fix this @@ -4090,11 +4096,11 @@ bool TController::IncSpeed() // czekaj na 1 pozycji, zanim się nie włączą liniowe if (true == mvControlling->StLinFlag) { - iDrivigFlags |= moveIncSpeed; + drivingFlags.incSpeed = true; } else { - iDrivigFlags &= ~moveIncSpeed; + drivingFlags.incSpeed = false; } if (mvControlling->Im == 0 && mvControlling->MainCtrlPowerPos() > 1) @@ -4113,7 +4119,7 @@ bool TController::IncSpeed() // mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania break; case TEngineType::Dumb: - if (!IsAnyMotorOverloadRelayOpen && (Ready || iDrivigFlags & movePress)) + if (!IsAnyMotorOverloadRelayOpen && (Ready || drivingFlags.press)) //{(BrakePress<=0.01*MaxBrakePress)} { OK = IncSpeedEIM(); @@ -4124,7 +4130,7 @@ bool TController::IncSpeed() } break; case TEngineType::DieselElectric: - if (!IsAnyMotorOverloadRelayOpen && !mvControlling->ControlPressureSwitch && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->StLinFlag) && (Ready || iDrivigFlags & movePress)) { + if (!IsAnyMotorOverloadRelayOpen && !mvControlling->ControlPressureSwitch && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->StLinFlag) && (Ready || drivingFlags.press)) { // youBy polecił dodać 2012-09-08 v367 // na pozycji 0 przejdzie, a na pozostałych będzie czekać, aż się załączą liniowe (zgaśnie DelayCtrlFlag) //{(BrakePress<=0.01*MaxBrakePress)} @@ -4136,13 +4142,13 @@ bool TController::IncSpeed() } break; case TEngineType::ElectricInductionMotor: - if( !IsAnyMotorOverloadRelayOpen && (Ready || iDrivigFlags & movePress || mvOccupied->ShuntMode) ) { + if( !IsAnyMotorOverloadRelayOpen && (Ready || drivingFlags.press || mvOccupied->ShuntMode) ) { //{(BrakePress<=0.01*MaxBrakePress)} OK = IncSpeedEIM(); if (mvControlling->SpeedCtrl && mvControlling->Mains) { // cruise control - auto const couplinginprogress{true == TestFlag(iDrivigFlags, moveConnect) && true == TestFlag(OrderCurrentGet(), Connect)}; + auto const couplinginprogress{true == drivingFlags.connect && true == TestFlag(OrderCurrentGet(), Connect)}; auto const SpeedCntrlVel{(ActualProximityDist > std::max(50.0, fMaxProximityDist) || couplinginprogress ? VelDesired : min_speed(VelDesired, VelNext))}; if (SpeedCntrlVel >= mvControlling->SpeedCtrlUnit.MinVelocity && SpeedCntrlVel - mvControlling->SpeedCtrlUnit.MinVelocity == quantize(SpeedCntrlVel - mvControlling->SpeedCtrlUnit.MinVelocity, mvControlling->SpeedCtrlUnit.VelocityStep)) @@ -4171,7 +4177,7 @@ bool TController::IncSpeed() // mvControlling->ShuntMode=(OrderList[OrderPos]&Shunt)||(fMass>224000.0); } if (mvControlling->SpeedCtrl && mvControlling->Mains) {// cruise control - auto const couplinginprogress { true == TestFlag(iDrivigFlags, moveConnect) && true == TestFlag(OrderCurrentGet(), Connect) }; + auto const couplinginprogress { true == drivingFlags.connect && true == TestFlag(OrderCurrentGet(), Connect) }; auto const SpeedCntrlVel { ( ActualProximityDist > std::max(50.0, fMaxProximityDist) || couplinginprogress ? VelDesired : @@ -4231,7 +4237,7 @@ bool TController::DecSpeed(bool force) switch (mvOccupied->EngineType) { case TEngineType::None: // McZapkie-041003: wagon sterowniczy - iDrivigFlags &= ~moveIncSpeed; // usunięcie flagi jazdy + drivingFlags.incSpeed = false; // usunięcie flagi jazdy if (force && mvControlling->MainCtrlPosNo > 0) // przy aktywacji kabiny jest potrzeba natychmiastowego wyzerowania // McZapkie-041003: wagon sterowniczy, np. EZT mvControlling->DecMainCtrl(std::min(mvControlling->MainCtrlPowerPos(), 2)); @@ -4395,7 +4401,7 @@ void TController::SpeedSet() { if (mvControlling->MainCtrlPosNo > 0) { // jeśli ma czym kręcić // TODO: sprawdzanie innego czlonu //if (!FuseFlagCheck()) - if( ( iDrivigFlags & moveIncSpeed ) == 0 ) { + if( ( false == drivingFlags.incSpeed ) ) { // przetok rozłączać od razu (no dependency on fActionTime) while( mvControlling->MainCtrlPos && mvControlling->DecMainCtrl(1) ) { @@ -4457,7 +4463,7 @@ void TController::SpeedSet() { } case TEngineType::ElectricSeriesMotor: { /* - if (Ready || (iDrivigFlags & movePress)) { // o ile może jechać + if (Ready || (drivingFlags.press)) { // o ile może jechać // if (fAccGravity < -0.10) // i jedzie pod górę większą niż 10 promil { // procedura wjeżdżania na ekstremalne wzniesienia if( std::fabs( mvControlling->Im ) > 0.85 * mvControlling->Imax ) { // a prąd jest większy niż 85% nadmiarowego @@ -4909,12 +4915,12 @@ void TController::Doors( bool const Open, int const Side ) { // if the doors are already closed and locked then there's nothing to do if( false == doors_permit_active() && false == doors_open() ) { - iDrivigFlags &= ~moveDoorOpened; - iDrivigFlags &= ~moveDepartureWarned; + drivingFlags.doorOpened = false; + drivingFlags.departureWarned = false; return; } - if (mvOccupied->Doors.has_warning && !TestFlag(iDrivigFlags, moveDepartureWarned)) + if (mvOccupied->Doors.has_warning && !drivingFlags.departureWarned) { if (!mvOccupied->DepartureSignal) { @@ -4926,7 +4932,7 @@ void TController::Doors( bool const Open, int const Side ) { // Not warned yet, warning now - stop the warning signal and mark it as done. cue_action( driver_hint::departuresignaloff ); fActionTime = Random( -0.2, 0.0 ); // Wait just a bit more before departing - iDrivigFlags |= moveDepartureWarned; + drivingFlags.departureWarned = true; return; } @@ -4960,8 +4966,8 @@ void TController::Doors( bool const Open, int const Side ) { } } fActionTime = Random(-3.5, -1.0); // 1.0-3.5 sec wait - iDrivigFlags &= ~moveDoorOpened; // zostały zamknięte - nie wykonywać drugi raz - iDrivigFlags &= ~moveDepartureWarned; + drivingFlags.doorOpened = false; // zostały zamknięte - nie wykonywać drugi raz + drivingFlags.departureWarned = false; } } @@ -5076,7 +5082,7 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N pVehicle->MoverParameters->PermitDoors( side::left, false ); } } - iDrivigFlags &= ~moveDoorOpened; + drivingFlags.doorOpened = false; TrainParams.UpdateMTable( simulation::Time, TrainParams.NextStationName ); TrainParams.StationIndexInc(); // przejście do następnej @@ -5085,7 +5091,7 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N // the flags of the first station until the train stops there m_stopflags = TrainParams.stop_flags(); m_lastannouncement = announcement_t::idle; - iDrivigFlags |= movePrimary; // skoro dostał rozkład, to jest teraz głównym + drivingFlags.primary = true; // skoro dostał rozkład, to jest teraz głównym // NewCommand = Global.asCurrentSceneryPath + NewCommand; auto lookup = FileExists( @@ -5180,9 +5186,9 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N OrderCheck(); // jeśli jazda pociągowa teraz, to wykonać niezbędne operacje } if (NewValue1 != 0.0) // jeśli jechać - iDrivigFlags &= ~moveStopHere; // podjeżanie do semaforów zezwolone + drivingFlags.stopHere = false; // podjeżanie do semaforów zezwolone else - iDrivigFlags |= moveStopHere; // stać do momentu podania komendy jazdy + drivingFlags.stopHere = true; // stać do momentu podania komendy jazdy SetVelocity(NewValue1, NewValue2, reason); // bylo: nic nie rob bo SetVelocity zewnetrznie // jest wywolywane przez dynobj.cpp return true; @@ -5218,12 +5224,12 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N CheckVehicles(); // zabrać to do OrderCheck() } // dla prędkości ujemnej przestawić nawrotnik do tyłu? ale -1=brak ograniczenia !!!! - iDrivigFlags &= ~movePress; // bez dociskania + drivingFlags.press = false; // bez dociskania SetVelocity(NewValue1, NewValue2, reason); if (NewValue1 != 0.0) - iDrivigFlags &= ~moveStopHere; // podjeżanie do semaforów zezwolone + drivingFlags.stopHere = false; // podjeżanie do semaforów zezwolone else - iDrivigFlags |= moveStopHere; // ma stać w miejscu + drivingFlags.stopHere = true; // ma stać w miejscu if (fabs(NewValue1) > 2.0) // o ile wartość jest sensowna (-1 nie jest konkretną wartością) fShuntVelocity = fabs(NewValue1); // zapamiętanie obowiązującej prędkości dla manewrów @@ -5277,7 +5283,7 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N else if (!o) // jeśli wcześniej było czekanie OrderNext(Shunt); // to dalej jazda manewrowa if (mvOccupied->Vel >= EU07_AI_MOVEMENT) // jeśli jedzie - iDrivigFlags &= ~moveStartHorn; // to bez trąbienia po ruszeniu z zatrzymania + drivingFlags.startHorn = false; // to bez trąbienia po ruszeniu z zatrzymania // Change_direction wykona się samo i następnie przejdzie do kolejnej komendy return true; } @@ -5315,7 +5321,7 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N // 0, 0 - odczepienie lokomotywy // x,-y - podłączyć się do składu (sprzęgiem y>=1), a następnie odczepić i zabrać (x) wagonów // 1, 0 - odczepienie lokomotywy z jednym wagonem - iDrivigFlags &= ~moveStopHere; // podjeżanie do semaforów zezwolone + drivingFlags.stopHere = false; // podjeżanie do semaforów zezwolone if( false == iEngineActive ) { OrderNext( Prepare_engine ); // trzeba odpalić silnik najpierw } @@ -5360,17 +5366,17 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N // both couplers empty // NOTE: this condition implements legacy behavior (mis)used by some scenarios to keep vehicle idling without moving SetVelocity( 0, 0, stopJoin ); - iDrivigFlags |= moveStopHere; // nie podjeżdżać do semafora, jeśli droga nie jest wolna + drivingFlags.stopHere = true; // nie podjeżdżać do semafora, jeśli droga nie jest wolna } WaitingTime = 0.0; // nie ma co dalej czekać, można zatrąbić i jechać, chyba że już jedzie } } if (NewValue1 == -1.0) { - iDrivigFlags &= ~moveStopHere; // ma jechać + drivingFlags.stopHere = false; // ma jechać WaitingTime = 0.0; // nie ma co dalej czekać, można zatrąbić i jechać } if( NewValue1 < -1.5 ) { // jeśli -2/-3, czyli czekanie z ruszeniem na sygnał - iDrivigFlags |= moveStopHere; // nie podjeżdżać do semafora, jeśli droga nie jest wolna + drivingFlags.stopHere = true; // nie podjeżdżać do semafora, jeśli droga nie jest wolna } // (nie dotyczy Connect) if( NewValue1 < -2.5 ) { // jeśli -3 to potem jazda pociągowa @@ -5449,13 +5455,17 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N } if (NewCommand == "SetSignal") { - TSignals signal = (TSignals)std::lrint(NewValue1); + auto const signal{std::lrint(NewValue1)}; - for (int i = Signal_START; i <= Signal_MAX; i++) - iDrivigFlags &= ~(1 << i); + drivingFlags.signalPc6 = false; + drivingFlags.signalA1 = false; if (NewValue2 > 0.5) - iDrivigFlags |= 1 << (uint32_t)signal; + { + // another number set the bit of a driving flag of that number before + drivingFlags.signalPc6 = signal == Signal_Pc6; + drivingFlags.signalA1 = signal == Signal_A1; + } else CheckVehicles(); // restore light state } @@ -5542,7 +5552,7 @@ void TController::PhysicsLog() void TController::Update( double const Timedelta ) { // uruchamiać przynajmniej raz na sekundę - if( ( iDrivigFlags & movePrimary ) == 0 ) { return; } // pasywny nic nie robi + if( ( false == drivingFlags.primary ) ) { return; } // pasywny nic nie robi if( false == simulation::is_ready ) { return; } update_timers( Timedelta ); @@ -5749,17 +5759,17 @@ void TController::OrderCheck() } if( OrderCurrentGet() & ( Shunt | Loose_shunt | Connect ) ) { // HACK: ensure consist doors will be closed on departure - iDrivigFlags |= moveDoorOpened; + drivingFlags.doorOpened = true; } auto const currentorder { OrderCurrentGet() }; if (currentorder & Change_direction) // może być nałożona na inną i wtedy ma priorytet iDirectionOrder = -iDirection; // trzeba zmienić jawnie, bo się nie domyśli else if (currentorder == Obey_train) - iDrivigFlags |= moveStopPoint; // W4 są widziane + drivingFlags.stopPoint = true; // W4 są widziane else if (currentorder == Disconnect) iVehicleCount = iVehicleCount < 0 ? 0 : iVehicleCount; // odczepianie lokomotywy else if (currentorder == Connect) - iDrivigFlags &= ~moveStopPoint; // podczas jazdy na połączenie nie zwracać uwagi na W4 + drivingFlags.stopPoint = false; // podczas jazdy na połączenie nie zwracać uwagi na W4 else if (currentorder == Wait_for_orders) OrdersClear(); // czyszczenie rozkazów i przeskok do zerowej pozycji } @@ -5841,7 +5851,7 @@ void TController::OrdersInit(double fVel) if (fVel > 0.0 && fVel < 0.02) OrderPush(Shunt); // dla prędkości 0.01 włączamy jazdę manewrową else if (TrainParams.DirectionChange() ? // jeśli obrót na pierwszym przystanku - (iDrivigFlags & movePushPull ? // SZT również! SN61 zależnie od wagonów... + (drivingFlags.pushPull ? // SZT również! SN61 zależnie od wagonów... TrainParams.TimeTable[1].StationName == TrainParams.Relation1 : false) : false) @@ -5865,7 +5875,7 @@ void TController::OrdersInit(double fVel) } if ( contains( t->StationWare, '@' ) ) { // zmiana kierunku i dalsza jazda wg rozk?adu - if (iDrivigFlags & movePushPull) // SZT również! SN61 zależnie od wagonów... + if (drivingFlags.pushPull) // SZT również! SN61 zależnie od wagonów... { // jeśli skład zespolony, wystarczy zmienić kierunek jazdy OrderPush(Change_direction); // zmiana kierunku } @@ -5895,11 +5905,12 @@ void TController::OrdersInit(double fVel) || fVel < 0.02 ) { // jeśli ma jechać - dla 0.01 ma podjechać manewrowo po podaniu sygnału // to do następnego W4 ma podjechać blisko - iDrivigFlags = iDrivigFlags & ~moveStopHere | moveStopCloser; + drivingFlags.stopHere = false; + drivingFlags.stopCloser = true; } else { // czekać na sygnał - iDrivigFlags |= moveStopHere; + drivingFlags.stopHere = true; } JumpToFirstOrder(); if (fVel >= 1.0) // jeśli ma jechać @@ -6187,7 +6198,7 @@ TCommandType TController::BackwardScan( double const Range ) #endif // SetProximityVelocity(scandist,scanvel,&sl); // jeśli jedzie na W5 albo koniec toru, to można zmienić kierunek - return (iDrivigFlags & moveTrackEnd) ? TCommandType::cm_ChangeDirection : + return (drivingFlags.trackEnd) ? TCommandType::cm_ChangeDirection : TCommandType::cm_Unknown; // TBD: request direction change also if VelNext in current direction is 0, // while signal behind requests movement? @@ -6257,11 +6268,11 @@ void TController::UpdateDelayFlag() { if( TrainParams.CheckTrainLatency() < 0.0 ) { // odnotowano spóźnienie - iDrivigFlags |= moveLate; + drivingFlags.late = true; } else { // przyjazd o czasie - iDrivigFlags &= ~moveLate; + drivingFlags.late = false; } } @@ -6312,9 +6323,9 @@ void TController::TakeControl( bool const Aidriver, bool const Forcevehiclecheck OrderNext( Shunt ); // jazda manewrowa */ if( mvOccupied->Vel >= 1.0 ) // jeśli jedzie (dla 0.1 ma stać) - iDrivigFlags &= ~moveStopHere; // to ma nie czekać na sygnał, tylko jechać + drivingFlags.stopHere = false; // to ma nie czekać na sygnał, tylko jechać else - iDrivigFlags |= moveStopHere; // a jak stoi, to niech czeka + drivingFlags.stopHere = true; // a jak stoi, to niech czeka } } CheckVehicles(); // ustawienie świateł @@ -7125,19 +7136,19 @@ TController::control_horns( double const Timedelta ) { } if( mvOccupied->Vel > EU07_AI_MOVEMENT ) { // jesli jedzie, można odblokować trąbienie, bo się wtedy nie włączy - iDrivigFlags &= ~moveStartHornDone; // zatrąbi dopiero jak następnym razem stanie - iDrivigFlags |= moveStartHorn; // i trąbić przed następnym ruszeniem + drivingFlags.startHornDone = false; // zatrąbi dopiero jak następnym razem stanie + drivingFlags.startHorn = true; // i trąbić przed następnym ruszeniem } - if( true == TestFlag(iDrivigFlags, moveStartHornNow) + if( true == drivingFlags.startHornNow && true == Ready && true == iEngineActive && mvControlling->MainCtrlPowerPos() > 0 ) { // uruchomienie trąbienia przed ruszeniem fWarningDuration = 0.3; // czas trąbienia cue_action( driver_hint::hornon, pVehicle->iHornWarning ); // wysokość tonu (2=wysoki) - iDrivigFlags |= moveStartHornDone; // nie trąbić aż do ruszenia - iDrivigFlags &= ~moveStartHornNow; // trąbienie zostało zorganizowane + drivingFlags.startHornDone = true; // nie trąbić aż do ruszenia + drivingFlags.startHornNow = false; // trąbienie zostało zorganizowane } } @@ -7494,7 +7505,7 @@ TController::determine_proximity_ranges() { { case Connect: { // podłączanie do składu - if (iDrivigFlags & moveConnect) { + if (drivingFlags.connect) { // jeśli stanął już blisko, unikając zderzenia i można próbować podłączyć fMinProximityDist = -1.0; fMaxProximityDist = 0.0; //[m] dojechać maksymalnie @@ -7555,7 +7566,7 @@ TController::determine_proximity_ranges() { fMinProximityDist = minproximity; fMaxProximityDist = maxproximity; - if( iDrivigFlags & moveLate ) { + if( drivingFlags.late ) { // jeśli spóźniony, to gna fVelMinus = 1.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania @@ -7610,7 +7621,7 @@ TController::check_departure() { && mvOccupied->RunningTrack.Velmax != 0.0 ) { // jeśli stoi, a upłynął czas oczekiwania i tor ma niezerową prędkość if( OrderCurrentGet() & (Shunt | Loose_shunt | Obey_train | Bank) - && iDrivigFlags & moveStopHere ) { + && drivingFlags.stopHere ) { // zakaz ruszania z miejsca bez otrzymania wolnej drogi WaitingTime = -WaitingExpireTime; } @@ -7631,7 +7642,7 @@ TController::check_departure() { } } } - else if( VelSignal == 0.0 && VelNext > 0.0 && mvOccupied->Vel < 1.0 && (iCoupler > 0 || (iDrivigFlags & moveStopHere) == 0) ) { + else if( VelSignal == 0.0 && VelNext > 0.0 && mvOccupied->Vel < 1.0 && (iCoupler > 0 || ( false == drivingFlags.stopHere )) ) { // Ra: tu jest coś nie tak, bo bez tego warunku ruszało w manewrowym !!!! SetVelocity(VelNext, VelNext, stopSem); // omijanie SBL } @@ -7666,9 +7677,9 @@ TController::check_load_exchange() { m_lastexchangedirection = pVehicle->DirectionGet(); } if( false == TrainParams.IsMaintenance() - && ( false == TestFlag(iDrivigFlags, moveDoorOpened) + && ( false == drivingFlags.doorOpened || true == DoesAnyDoorNeedOpening ) ) { - iDrivigFlags |= moveDoorOpened; // nie wykonywać drugi raz + drivingFlags.doorOpened = true; // nie wykonywać drugi raz remove_hint( driver_hint::doorleftopen ); remove_hint( driver_hint::doorrightopen ); Doors( true, m_lastexchangeplatforms ); @@ -7695,11 +7706,11 @@ TController::UpdateChangeDirection() { VelSignalNext = -1; PrepareEngine(); JumpToNextOrder(); // następnie robimy, co jest do zrobienia (Shunt albo Obey_train) - if( OrderCurrentGet() & (Shunt | Loose_shunt | Connect) && false == TestFlag(iDrivigFlags, moveStopHere) ) { + if( OrderCurrentGet() & (Shunt | Loose_shunt | Connect) && false == drivingFlags.stopHere ) { // jeśli dalej mamy manewry // o ile nie ma stać w miejscu, // jechać od razu w przeciwną stronę i nie trąbić z tego tytułu: - iDrivigFlags &= ~moveStartHorn; + drivingFlags.startHorn = false; SetVelocity(fShuntVelocity, fShuntVelocity); } } @@ -7735,11 +7746,11 @@ TController::UpdateObeyTrain() { UpdateNextStop(); - if( (iDrivigFlags & moveGuardSignal) != 0 + if( drivingFlags.guardSignal && VelDesired > 0.0 ) { // komunikat od kierownika tu, bo musi być wolna droga i odczekany czas stania - iDrivigFlags &= ~moveGuardSignal; // tylko raz nadać - iDrivigFlags &= ~moveGuardOpenDoor; // nie trzeba już otwierać drzwi + drivingFlags.guardSignal = false; // tylko raz nadać + drivingFlags.guardOpenDoor = false; // nie trzeba już otwierać drzwi if( false == tsGuardSignal.empty() ) { tsGuardSignal.stop(); // w zasadzie to powinien mieć flagę, czy jest dźwiękiem radiowym, czy bezpośrednim @@ -7774,7 +7785,7 @@ TController::UpdateObeyTrain() { void TController::UpdateConnect() { // podłączanie do składu - if (iDrivigFlags & moveConnect) { + if (drivingFlags.connect) { // sprzęgi sprawdzamy w pierwszej kolejności, bo jak połączony, to koniec auto *vehicle { iCouplingVehicle.value().first }; auto const couplingend { iCouplingVehicle.value().second }; @@ -7814,7 +7825,7 @@ TController::UpdateConnect() { iCoupler = 0; // dalsza jazda manewrowa już bez łączenia iCouplingVehicle.reset(); - iDrivigFlags &= ~moveConnect; // zdjęcie flagi doczepiania + drivingFlags.connect = false; // zdjęcie flagi doczepiania JumpToNextOrder( true ); // wykonanie następnej komendy } } // moveConnect @@ -7824,14 +7835,14 @@ TController::UpdateConnect() { // write down which vehicle should be coupled with the target consist, // so we don't lose track of it if the user does something unexpected iCouplingVehicle = {pVehicles[end::front], (pVehicles[end::front]->DirectionGet() > 0 ? end::front : end::rear)}; - iDrivigFlags |= moveConnect; + drivingFlags.connect = true; } } } void TController::GuardOpenDoor() { - if ((iDrivigFlags & moveGuardOpenDoor) != 0) { + if (drivingFlags.guardOpenDoor) { auto *vehicle{ pVehicles[end::front] }; while (vehicle != nullptr && vehicle->MoverParameters->Doors.range == 0) { vehicle = vehicle->Next(); @@ -7847,7 +7858,7 @@ TController::GuardOpenDoor() { } } else { - iDrivigFlags &= ~moveGuardOpenDoor; + drivingFlags.guardOpenDoor = false; } } } @@ -7891,7 +7902,7 @@ TController::UpdateDisconnect() { cue_action( driver_hint::mastercontrollersetreverserunlock ); cue_action( driver_hint::directionother ); } - if( (iDrivigFlags & movePress) != 0 && iDirection == iDirectionOrder ) { + if( drivingFlags.press && iDirection == iDirectionOrder ) { if( iVehicleCount >= 0 ) { // zmieni się po odczepieniu WriteLog( "Uncoupling [" + mvOccupied->Name + "]: actuating and compressing buffers..." ); @@ -7950,7 +7961,7 @@ TController::UpdateDisconnect() { } // a jak nie, to dociskać dalej } // 2nd stage: apply consist brakes and change direction - if( ( iDrivigFlags & movePress ) == 0 ) { + if( ( false == drivingFlags.press ) ) { // store initial consist direction if( !iDirectionBackup ) { iDirectionBackup = iDirection; @@ -7969,7 +7980,7 @@ TController::UpdateDisconnect() { } */ iDirectionOrder = -iDirection; // zmiana kierunku jazdy na przeciwny (dociskanie) - iDrivigFlags |= movePress; // następnie będzie dociskanie + drivingFlags.press = true; // następnie będzie dociskanie } } } // odczepianie @@ -7986,10 +7997,10 @@ TController::UpdateDisconnect() { } // 5th stage: clean up and move on to next order if( iDirection == iDirectionOrder ) { - iDrivigFlags &= ~movePress; // koniec dociskania + drivingFlags.press = false; // koniec dociskania JumpToNextOrder( true ); // zmieni światła TableClear(); // skanowanie od nowa - iDrivigFlags &= ~moveStartHorn; // bez trąbienia przed ruszeniem + drivingFlags.startHorn = false; // bez trąbienia przed ruszeniem } } } @@ -8058,7 +8069,7 @@ TController::handle_orders() { default: { // special case, change_direction potentially received during partially completed coupling operation // this is unlikely to happen for the AI, but can happen for a (slower) human user - if( TestFlag( iDrivigFlags, moveConnect ) ) { + if( drivingFlags.connect ) { UpdateConnect(); } break; @@ -8073,13 +8084,13 @@ TController::set_velocity_for_uncoupling() { if( iVehicleCount < 0 ) { // 4th stage: restore initial direction - if( ( iDrivigFlags & movePress ) != 0 ) { + if( drivingFlags.press ) { SetVelocity( 0, 0, stopJoin ); } return; } // 3rd stage: compress buffers and uncouple - if( ( iDrivigFlags & movePress ) != 0 && iDirection == iDirectionOrder ) { + if( drivingFlags.press && iDirection == iDirectionOrder ) { SetVelocity( 2, 0 ); // jazda w ustawionym kierunku z prędkością 2 return; } @@ -8368,7 +8379,7 @@ TController::adjust_desired_speed_for_limits() { return; // speed limit can't get any lower } - if( (OrderCurrentGet() & (Shunt | Loose_shunt | Obey_train | Bank)) != 0 && (iDrivigFlags & moveStopHere) != 0 && mvOccupied->Vel < 0.01 && VelSignalNext == 0.0 ) { + if( (OrderCurrentGet() & (Shunt | Loose_shunt | Obey_train | Bank)) != 0 && drivingFlags.stopHere && mvOccupied->Vel < 0.01 && VelSignalNext == 0.0 ) { // w Connect nie, bo moveStopHere odnosi się do stanu po połączeniu // jeśli ma czekać na wolną drogę, stoi a wyjazdu nie ma, to ma stać VelDesired = 0.0; @@ -8947,7 +8958,7 @@ void TController::control_tractive_force() { // jeśli przyspieszenie pojazdu jest mniejsze niż żądane oraz... if( AccDesired > EU07_AI_NOACCELERATION // don't add power if not asked for actual speed-up && (AbsAccS < AccDesired /*- std::min( 0.05, 0.01 * iDriverFailCount )*/ || mvOccupied->SpeedCtrlUnit.IsActive && velocity < mvOccupied->SpeedCtrlUnit.FullPowerVelocity) && - false == TestFlag(iDrivigFlags, movePress) && + false == drivingFlags.press && // starting uphill against the releasing brake, the power that holds the train is enough: the brake coming off // speeds the train up, more power only drags the brake and slips the wheels. nor is a notch past that taken // back: the power got there in one notch from below, and the notch below doesn't hold the train @@ -8970,7 +8981,7 @@ void TController::control_tractive_force() { } // zmniejszanie predkosci // margines dla prędkości jest doliczany tylko jeśli oczekiwana prędkość jest większa od 5km/h - if( false == TestFlag( iDrivigFlags, movePress ) ) { + if( false == drivingFlags.press ) { double SpeedCtrlMargin = mvControlling->SpeedCtrlUnit.IsActive && VelDesired > 5 ? 3 : 0; // jeśli nie dociskanie if( AccDesired <= EU07_AI_NOACCELERATION ) { @@ -9231,7 +9242,7 @@ TController::uphill_brake_committed( double const Velocity ) const { void TController::control_braking_force() { // don't touch the brakes when compressing buffers during coupling/uncoupling - if( TestFlag( iDrivigFlags, movePress ) ) { return; } + if( drivingFlags.press ) { return; } auto const velocity { DirectionalVel() }; // a train slipping back uphill is braked, also when it is to go on: released now it only rolls back further. @@ -9243,7 +9254,7 @@ void TController::control_braking_force() { // jeśli przyspieszamy, to nie hamujemy if( AccDesired > 0.0 && OrderCurrentGet() != Disconnect // przy odłączaniu nie zwalniamy tu hamulca - && false == TestFlag(iDrivigFlags, movePress) + && false == drivingFlags.press && false == slippingbackuphill ) { cue_action(driver_hint::brakingforcesetzero); } @@ -9412,7 +9423,7 @@ void TController::control_releaser() { state.control_pressure = mvOccupied->Hamulec->GetCRP(); state.velocity = mvOccupied->Vel; state.uphill_start = bUphillStart; - state.pressing = TestFlag( iDrivigFlags, movePress ); + state.pressing = drivingFlags.press; // stage 3 of uncoupling (UpdateDisconnect), from the direction change until the coupler lets go state.compressing_buffers = state.pressing && ( OrderCurrentGet() & Disconnect ) != 0 && iVehicleCount >= 0 && iDirection == iDirectionOrder; @@ -9473,7 +9484,7 @@ void TController::control_main_pipe() { || mvOccupied->BrakeHandle == TBrakeHandle::M394 ) { auto const departblocked { is_departure_blocked( DepartBlockedFSDelay ) }; - if( (iDrivigFlags & moveOerlikons || true == IsCargoTrain || departblocked) && BrakeCtrlPosition == gbh_RP && AbsAccS < 0.03 && AccDesired > -0.03 && VelDesired - mvOccupied->Vel > 2.0 && fReady > 0.35 && + if( (drivingFlags.oerlikons || true == IsCargoTrain || departblocked) && BrakeCtrlPosition == gbh_RP && AbsAccS < 0.03 && AccDesired > -0.03 && VelDesired - mvOccupied->Vel > 2.0 && fReady > 0.35 && ( mvOccupied->EqvtPipePress < 4.5 || departblocked ) // don't charge with a risk of overcharging the main pipe && mvOccupied->Compressor >= 7.5 // don't charge without sufficient pressure in the tank && BrakeChargingCooldown >= 0.0 // don't charge while cooldown is active @@ -9562,7 +9573,7 @@ TController::check_route_ahead( double const Range ) { if( VelNext == 0.0 ) { break; // ale jak coś z przodu zamyka, to ma stać } - if( iDrivigFlags & moveStopCloser ) { + if( drivingFlags.stopCloser ) { VelSignal = -1.0; // ma czekać na sygnał z sygnalizatora! } break; @@ -9605,7 +9616,7 @@ void TController::check_route_behind( double const Range ) { if( VelNext != 0.0 ) { return; } // not if we can move ahead - if( TestFlag( iDrivigFlags, moveConnect ) ) { return; } // not if we're in middle of coupling operation + if( drivingFlags.connect ) { return; } // not if we're in middle of coupling operation if( ( OrderCurrentGet() & ~( Shunt | Loose_shunt | Connect ) ) == 0 ) { // jedzie w Shunt albo Connect, albo Wait_for_orders @@ -9613,7 +9624,7 @@ TController::check_route_behind( double const Range ) { auto const couplinginprogress { TestFlag(OrderCurrentGet(), Connect) && ( Obstacle.distance < std::min(2000.0, FirstSemaphorDist) - || TestFlag(iDrivigFlags, moveConnect) ) }; + || drivingFlags.connect ) }; if( couplinginprogress ) { return; } auto const commandbehind { BackwardScan( Range ) }; @@ -9624,7 +9635,7 @@ TController::check_route_behind( double const Range ) { // i dopiero wtedy zmienić kierunek jazdy, oczekując podania prędkości >0.5 if( commandbehind == TCommandType::cm_Command ) { // jeśli komenda Shunt to ją odbierz bez przemieszczania się (np. odczep wagony po dopchnięciu do końca toru) - iDrivigFlags |= moveStopHere; + drivingFlags.stopHere = true; } iDirectionOrder = -iDirection; // zmiana kierunku jazdy // zmiana kierunku bez psucia kolejnych komend @@ -9682,3 +9693,21 @@ bool TController::has_diesel_engine() const { double TController::DirectionalVel() const { return mvOccupied->Vel * sign( iDirection * mvOccupied->V ); } + +std::vector DrivingFlags::ActiveNames() const { + std::vector> const flags { + { stopCloser, "StopCloser" }, { stopPoint, "StopPoint" }, { active, "Active" }, { press, "Press" }, + { connect, "Connect" }, { primary, "Primary" }, { late, "Late" }, { stopHere, "StopHere" }, + { startHorn, "StartHorn" }, { startHornNow, "StartHornNow" }, { startHornDone, "StartHornDone" }, + { oerlikons, "Oerlikons" }, { incSpeed, "IncSpeed" }, { trackEnd, "TrackEnd" }, { switchFound, "SwitchFound" }, + { guardSignal, "GuardSignal" }, { visibility, "Visibility" }, { doorOpened, "DoorOpened" }, + { pushPull, "PushPull" }, { signalFound, "SignalFound" }, { stopPointFound, "StopPointFound" }, + { guardOpenDoor, "GuardOpenDoor" }, { departureWarned, "DepartureWarned" } }; + std::vector names; + for( auto const &[ set, name ] : flags ) { + if( set ) { + names.emplace_back( name ); + } + } + return names; +} diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 04ba00d01..8cf80ddcf 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -52,7 +52,7 @@ enum TOrders Jump_to_first_order = 1 << 9, // zapęlenie do pierwszej pozycji (po co?) }; -// TSignals is shifted into TMovementStatus +// the signals the map asks the driver to show (SetSignal) enum TSignals { Signal_START = 30, @@ -61,36 +61,37 @@ enum TSignals Signal_MAX = 31 }; -enum TMovementStatus -{ // flagi bitowe ruchu (iDrivigFlags) - moveStopCloser = 1, // podjechać blisko W4 (nie podjeżdżać na początku ani po zmianie czoła) - moveStopPoint = 2, // stawać na W4 (wyłączone podczas zmiany czoła) - moveActive = 4, // pojazd jest załączony i skanuje - movePress = 8, // dociskanie przy odłączeniu (zamiast zmiennej Prepare2press) - moveConnect = 0x10, // jest blisko innego pojazdu i można próbować podłączyć - movePrimary = 0x20, // ma priorytet w składzie (master) - moveLate = 0x40, // flaga spóźnienia, włączy bardziej - moveStopHere = 0x80, // nie podjeżdżać do semafora, jeśli droga nie jest wolna - moveStartHorn = 0x100, // podawaj sygnał po podaniu wolnej drogi - moveStartHornNow = 0x200, // podaj sygnał po odhamowaniu - moveStartHornDone = 0x400, // podano sygnał po podaniu wolnej drogi - moveOerlikons = 0x800, // skład wyłącznie z zaworami? Oerlikona - moveIncSpeed = 0x1000, // załączenie jazdy (np. dla EZT) - moveTrackEnd = 0x2000, // dalsza jazda do przodu trwale ograniczona (W5, koniec toru) - moveSwitchFound = 0x4000, // na drodze skanowania do przodu jest rozjazd - moveGuardSignal = 0x8000, // sygnał od kierownika (minął czas postoju) - moveVisibility = 0x10000, // jazda na widoczność po przejechaniu S1 na SBL - moveDoorOpened = 0x20000, // drzwi zostały otwarte - doliczyć czas na zamknięcie - movePushPull = 0x40000, // zmiana czoła przez zmianę kabiny - nie odczepiać przy zmianie kierunku - moveSignalFound = 0x80000, // na drodze skanowania został znaleziony semafor - moveStopPointFound = 0x100000, // stop point detected ahead - moveGuardOpenDoor = 0x200000, // time for opening a door before departure - moveDepartureWarned = 0x400000 // driver has already warned about the doors being closed (only for manual warning - i.e. EN57-ish) -/* - moveSemaphorWasElapsed = 0x100000, // minięty został semafor - moveTrainInsideStation = 0x200000, // pociąg między semaforem a rozjazdami lub następnym semaforem - moveSpeedLimitFound = 0x400000 // pociąg w ograniczeniu z podaną jego długością -*/ +// what the driver keeps in mind about the movement of the train: each a condition of its own, set and cleared on its own +struct DrivingFlags +{ + bool stopCloser{ false }; // podjechać blisko W4 (nie podjeżdżać na początku ani po zmianie czoła) + bool stopPoint{ true }; // stawać na W4 (wyłączone podczas zmiany czoła) + bool active{ false }; // pojazd jest załączony i skanuje + bool press{ false }; // dociskanie przy odłączeniu + bool connect{ false }; // jest blisko innego pojazdu i można próbować podłączyć + bool primary{ false }; // ma priorytet w składzie (master) + bool late{ false }; // spóźnienie, włączy bardziej + bool stopHere{ true }; // nie podjeżdżać do semafora, jeśli droga nie jest wolna + bool startHorn{ true }; // podawaj sygnał po podaniu wolnej drogi + bool startHornNow{ false }; // podaj sygnał po odhamowaniu + bool startHornDone{ false }; // podano sygnał po podaniu wolnej drogi + bool oerlikons{ false }; // skład wyłącznie z zaworami Oerlikona + bool incSpeed{ false }; // załączenie jazdy (np. dla EZT) + bool trackEnd{ false }; // dalsza jazda do przodu trwale ograniczona (W5, koniec toru) + bool switchFound{ false }; // na drodze skanowania do przodu jest rozjazd + bool guardSignal{ false }; // sygnał od kierownika (minął czas postoju) + bool visibility{ false }; // jazda na widoczność po przejechaniu S1 na SBL + bool doorOpened{ false }; // drzwi zostały otwarte - doliczyć czas na zamknięcie + bool pushPull{ false }; // zmiana czoła przez zmianę kabiny - nie odczepiać przy zmianie kierunku + bool signalFound{ false }; // na drodze skanowania został znaleziony semafor + bool stopPointFound{ false }; // stop point detected ahead + bool guardOpenDoor{ false }; // time for opening a door before departure + bool departureWarned{ false }; // driver has already warned about the doors being closed (only for manual warning - i.e. EN57-ish) + bool signalPc6{ false }; // the map asked to show the Pc6 signal (SetSignal); nothing reads it yet + bool signalA1{ false }; // the map asked to show the A1 signal (SetSignal); nothing reads it yet + + // the names of the flags set, for the debug panel + std::vector ActiveNames() const; }; enum TStopReason @@ -241,11 +242,11 @@ public: void TakeControl( bool const Aidriver, bool const Forcevehiclecheck = false ); inline bool primary( bool const Primary ) { - SetFlag( iDrivigFlags, Primary ? movePrimary : -movePrimary ); + drivingFlags.primary = Primary; return primary(); } inline bool primary() const { - return (iDrivigFlags & movePrimary) != 0; }; + return drivingFlags.primary; }; inline TMoverParameters const *Controlling() const { return mvControlling; } @@ -265,7 +266,7 @@ public: return eAction; } inline bool is_active() const { - return TestFlag( iDrivigFlags, moveActive ); } + return drivingFlags.active; } bool is_train() const; bool is_car() const; bool is_emu() const; @@ -322,8 +323,8 @@ private: float braking_distance_multiplier( float const Targetvelocity ) const; inline - int DrivigFlags() const { - return iDrivigFlags; }; + DrivingFlags const &DrivingFlagsState() const { + return drivingFlags; } double DirectionalVel() const; double brake_increase_margin() const; @@ -499,10 +500,7 @@ private: double fStopTime = 0.0; // czas postoju przed dalszą jazdą (np. na przystanku) float ExchangeTime{ 0.0 }; // time needed to finish current load exchange double fShuntVelocity = 40.0; // prędkość manewrowania, zależy m.in. od składu - int iDrivigFlags = // flagi bitowe ruchu - moveStopPoint | // podjedź do W4 możliwie blisko - moveStopHere | // nie podjeżdżaj do semafora, jeśli droga nie jest wolna - moveStartHorn; // podaj sygnał po podaniu wolnej drogi + DrivingFlags drivingFlags; // what the driver keeps in mind about the movement of the train double fDriverBraking = 0.0; // po pomnożeniu przez v^2 [km/h] daje ~drogę hamowania [m] double fDriverDist = 0.0; // dopuszczalna odległość podjechania do przeszkody double fVelMax = -1.0; // maksymalna prędkość składu (sprawdzany każdy pojazd) From c07eb76e519f4e1c07cd951427574f71c6508a98 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Fri, 27 Nov 2026 21:36:53 +0100 Subject: [PATCH 008/123] refactor(physics): the drives of the vehicles are classes, one for each kind of engine What a vehicle does in the step of its traction depended on a switch on EngineType in each place: the traction force, the ventilators, the power of the engine, the ammeters, the revolutions of the engine. Each kind of drive is now a class of its own in physics/mover/drive.h/.cpp, behind the interface TractionDrive: NoDrive no engine, or one with no model (steam, Main) DumbDrive an engine with no model (Dumb) WheelsDrivenDrive the wheels driven by hand SeriesMotorDrive series wound DC motors InductionMotorDrive asynchronous motors and inverters DieselMechanicalDrive a diesel engine and a mechanical or hydraulic gear DieselElectricDrive a diesel engine, a generator and traction motors TMoverParameters::Drive() gives the one of the vehicle's EngineType. TractionForce(), UpdateVentilators(), UpdateEnginePower(), ShowCurrent(), EngineRPMRatio(), EngineIdleRPM() and EngineMaxRPM() call it in the same order the switches went. The drives hold no state yet: the state of each drive moves into its class next. No change in behaviour: 1144/1144 tests, golden traces exact against staging 62f7a29b. --- CMakeLists.txt | 1 + physics/mover.h | 4 + physics/mover/diesel.cpp | 17 +-- physics/mover/drive.cpp | 293 +++++++++++++++++++++++++++++++++++++ physics/mover/drive.h | 56 +++++++ physics/mover/traction.cpp | 178 ++-------------------- 6 files changed, 374 insertions(+), 175 deletions(-) create mode 100644 physics/mover/drive.cpp create mode 100644 physics/mover/drive.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 7cd6161b6..04e07b4a5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -746,6 +746,7 @@ set(CORE_SOURCES "physics/brakes.cpp" "physics/vehiclecommand.cpp" "physics/mover/mover.cpp" +"physics/mover/drive.cpp" "physics/mover/cab.cpp" "physics/mover/collisions.cpp" "physics/mover/commands.cpp" diff --git a/physics/mover.h b/physics/mover.h index b995ff6d6..b254656c8 100644 --- a/physics/mover.h +++ b/physics/mover.h @@ -23,6 +23,8 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/odometerreading.h" #include "physics/vehicletypes.h" +class TractionDrive; + class cParser; /* MaSzyna EU07 locomotive simulator @@ -2246,6 +2248,8 @@ class TMoverParameters void FuseOff(void); // wylaczenie nadmiarowego bool UniversalResetButton(int const Button, range_t const Notify = range_t::consist); bool RelayReset(int const Relays, range_t const Notify = range_t::consist); // resets specified relays + // the drive of the kind of engine of the vehicle (physics/mover/drive.h) + TractionDrive const &Drive() const; double ShowCurrent(int AmpN) const; // pokazuje bezwgl. wartosc pradu na wybranym amperomierzu double ShowCurrentP(int AmpN) const; // pokazuje bezwgl. wartosc pradu w wybranym pojezdzie //Q 20160722 diff --git a/physics/mover/diesel.cpp b/physics/mover/diesel.cpp index 5af5c26bf..1548f8885 100644 --- a/physics/mover/diesel.cpp +++ b/physics/mover/diesel.cpp @@ -28,31 +28,22 @@ http://mozilla.org/MPL/2.0/. #include #include #include "physics/mover/internal.h" +#include "physics/mover/drive.h" double TMoverParameters::EngineRPMRatio() const { - - return std::clamp(EngineType == TEngineType::DieselElectric ? 60.0 * std::abs(enrot) / DElist[MainCtrlPosNo].RPM : - EngineType == TEngineType::DieselEngine ? std::abs(enrot) / nmax : - 1.0, // shouldn't ever get here but, eh - 0.0, 1.0); + return Drive().EngineRpmRatio(*this); } double TMoverParameters::EngineIdleRPM() const { - - return EngineType == TEngineType::DieselEngine ? dizel_nmin * 60 : - EngineType == TEngineType::DieselElectric ? DElist[MainCtrlNoPowerPos()].RPM : - std::numeric_limits::max(); // shouldn't ever get here but, eh + return Drive().EngineIdleRpm(*this); } double TMoverParameters::EngineMaxRPM() const { - - return EngineType == TEngineType::DieselEngine ? dizel_nmax * 60 : - EngineType == TEngineType::DieselElectric ? DElist[MainCtrlPosNo].RPM : - std::numeric_limits::max(); // shouldn't ever get here but, eh + return Drive().EngineMaxRpm(*this); } // water pump status check diff --git a/physics/mover/drive.cpp b/physics/mover/drive.cpp new file mode 100644 index 000000000..d108a8494 --- /dev/null +++ b/physics/mover/drive.cpp @@ -0,0 +1,293 @@ +/* +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 drives of the vehicles, one class for each kind of engine + +#include "stdafx.h" +#include "physics/mover/drive.h" + +#include +#include +#include + +#include "physics/mover.h" + +// the defaults: a drive with no engine model and no engine of revolutions does nothing in the steps + +double TractionDrive::UpdateEnginePower(TMoverParameters & /*vehicle*/) const +{ + return 0.0; +} + +void TractionDrive::BeforeTractionForce(TMoverParameters & /*vehicle*/, double /*dt*/) const +{ + // nothing before the force +} + +void TractionDrive::UpdateTractionForce(TMoverParameters & /*vehicle*/, DriveStep const & /*step*/) const +{ + // no force +} + +void TractionDrive::AfterTractionForce(TMoverParameters & /*vehicle*/) const +{ + // nothing after the force +} + +void TractionDrive::UpdateVentilators(TMoverParameters & /*vehicle*/, double /*dt*/) const +{ + // no ventilators +} + +double TractionDrive::ShowCurrent(TMoverParameters const &vehicle, int const ammeter) const +{ + return vehicle.ShowCurrentP(ammeter); +} + +double TractionDrive::EngineRpmRatio(TMoverParameters const & /*vehicle*/) const +{ + return 1.0; +} + +double TractionDrive::EngineIdleRpm(TMoverParameters const & /*vehicle*/) const +{ + return std::numeric_limits::max(); +} + +double TractionDrive::EngineMaxRpm(TMoverParameters const & /*vehicle*/) const +{ + return std::numeric_limits::max(); +} + +namespace +{ + +// the radiator fans of a diesel engine follow their demanded revolutions while the engine runs, and run down without it +void updateRadiatorFans(TMoverParameters &vehicle, double const dt) +{ + auto &heat{vehicle.dizel_heat}; + if (true == vehicle.Mains) + { + heat.rpmw += static_cast(std::clamp(heat.rpmwz - heat.rpmw, -100.f, 50.f) * dt); + heat.rpmw2 += static_cast(std::clamp(heat.rpmwz2 - heat.rpmw2, -100.f, 50.f) * dt); + } + else + { + heat.rpmw *= static_cast(std::max(0.0, 1.0 - heat.rpmw * dt)); + heat.rpmw2 *= static_cast(std::max(0.0, 1.0 - heat.rpmw2 * dt)); + } +} + +// a vehicle without an engine (a wagon), or of an engine with no model (steam, Main) +class NoDrive final : public TractionDrive +{ +}; + +// an engine with no model: the power follows the share of the controller positions +class DumbDrive final : public TractionDrive +{ +public: + double UpdateEnginePower(TMoverParameters &vehicle) const override + { + auto const posRatio{(vehicle.MainCtrlPos + vehicle.ScndCtrlPos) / (vehicle.MainCtrlPosNo + vehicle.ScndCtrlPosNo + 0.01)}; + vehicle.EnginePower = /*1000.0 **/ vehicle.Power * posRatio; + return posRatio; + } + void UpdateTractionForce(TMoverParameters &vehicle, DriveStep const &step) const override + { + vehicle.DumbTractionForce(step.posRatio); + } +}; + +// a draisine and the like, the wheels driven by hand +class WheelsDrivenDrive final : public TractionDrive +{ +public: + void UpdateTractionForce(TMoverParameters &vehicle, DriveStep const &step) const override + { + vehicle.WheelsDrivenTractionForce(step.dt); + } +}; + +// series wound direct current motors, started through resistors +class SeriesMotorDrive final : public TractionDrive +{ +public: + void UpdateTractionForce(TMoverParameters &vehicle, DriveStep const &step) const override + { + vehicle.SeriesMotorTractionForce(step.dt); + } + void UpdateVentilators(TMoverParameters &vehicle, double const dt) const override + { + if (vehicle.MainCircuitPowered()) + { + vehicle.UpdateResistorBlowers(dt); + } // mains + else + { + vehicle.RventRot *= std::max(0.0, 1.0 - vehicle.RVentSpeed * dt); + } + } +}; + +// asynchronous motors fed by inverters +class InductionMotorDrive final : public TractionDrive +{ +public: + void UpdateTractionForce(TMoverParameters &vehicle, DriveStep const &step) const override + { + vehicle.InductionMotorTractionForce(step.dt); + } + double ShowCurrent(TMoverParameters const &vehicle, int const ammeter) const override + { + switch (ammeter) + { // do asynchronicznych + case 1: + return vehicle.WindingRes * vehicle.Mm / vehicle.Vadd; + case 2: + return vehicle.eimv_pr * vehicle.WindingRes; + default: + return vehicle.ShowCurrentP(ammeter); + } + } +}; + +// a diesel engine driving the wheels through a mechanical or hydraulic transmission +class DieselMechanicalDrive final : public TractionDrive +{ +public: + double UpdateEnginePower(TMoverParameters &vehicle) const override + { + vehicle.dizel_Power = vehicle.Mm * vehicle.enrot * (2.0 * M_PI / 1000.0); + vehicle.EnginePower = (vehicle.dizel_Mstand + vehicle.Mm) * vehicle.enrot * (2.0 * M_PI / 1000.0); + if (vehicle.MainCtrlPowerPos() > 1) + { + // dodatkowe opory z powodu sprezarki} + // dmoment -= dizel_Mstand * ( 0.2 * enrot / dizel_nmax ); //yB: skąd to w ogóle się bierze?! + } + return 0.0; + } + void UpdateTractionForce(TMoverParameters &vehicle, DriveStep const &step) const override + { + vehicle.DieselEngineTractionForce(step.dt, step.moment, step.transmission); + } + void UpdateVentilators(TMoverParameters &vehicle, double const dt) const override + { + // NOTE: we update only radiator fans, as vehicles with diesel engine don't have other ventilators + updateRadiatorFans(vehicle, dt); + } + double EngineRpmRatio(TMoverParameters const &vehicle) const override + { + return std::clamp(std::abs(vehicle.enrot) / vehicle.nmax, 0.0, 1.0); + } + double EngineIdleRpm(TMoverParameters const &vehicle) const override + { + return vehicle.dizel_nmin * 60; + } + double EngineMaxRpm(TMoverParameters const &vehicle) const override + { + return vehicle.dizel_nmax * 60; + } +}; + +// a diesel engine driving a generator which feeds the traction motors +class DieselElectricDrive final : public TractionDrive +{ +public: + double UpdateEnginePower(TMoverParameters &vehicle) const override + { + vehicle.EnginePower = 0; // the actual calculation is done in two steps later in the method + return 0.0; + } + void BeforeTractionForce(TMoverParameters &vehicle, double const dt) const override + { + if (vehicle.DEDynamicBrake.source != TMoverParameters::diesel_electric_dynamic_brake::control::none) + { + vehicle.update_dieselelectric_dynamic_brake(dt); + } + } + void UpdateTractionForce(TMoverParameters &vehicle, DriveStep const &step) const override + { + vehicle.DieselElectricTractionForce(step.revolutions); + if (vehicle.DEDynamicBrake.level > 0.0) + { + // braking: no power asked for, so the drive above gave no force + vehicle.apply_dieselelectric_dynamic_brake(step.dt); + } + } + void AfterTractionForce(TMoverParameters &vehicle) const override + { + // rough approximation of extra effort to overcome friction etc + vehicle.EnginePower += EngineRpmRatio(vehicle) * 0.15 * vehicle.DElist[vehicle.MainCtrlPosNo].GenPower; + } + void UpdateVentilators(TMoverParameters &vehicle, double const dt) const override + { + // NOTE: for this type RventRot is the speed of motor blowers; we also update radiator fans while at it + if (true == vehicle.Mains) + { + // TBD, TODO: currently ignores RVentType, fix this? + vehicle.RventRot += std::clamp(vehicle.enrot - vehicle.RventRot, -100.0, 50.0) * dt; + } + else + { + vehicle.RventRot *= std::max(0.0, 1.0 - vehicle.RVentSpeed * dt); + } + updateRadiatorFans(vehicle, dt); + } + double ShowCurrent(TMoverParameters const &vehicle, int const /*ammeter*/) const override + { + return std::fabs(vehicle.Im); + } + double EngineRpmRatio(TMoverParameters const &vehicle) const override + { + return std::clamp(60.0 * std::abs(vehicle.enrot) / vehicle.DElist[vehicle.MainCtrlPosNo].RPM, 0.0, 1.0); + } + double EngineIdleRpm(TMoverParameters const &vehicle) const override + { + return vehicle.DElist[vehicle.MainCtrlNoPowerPos()].RPM; + } + double EngineMaxRpm(TMoverParameters const &vehicle) const override + { + return vehicle.DElist[vehicle.MainCtrlPosNo].RPM; + } +}; + +NoDrive const noDrive{}; +DumbDrive const dumbDrive{}; +WheelsDrivenDrive const wheelsDrivenDrive{}; +SeriesMotorDrive const seriesMotorDrive{}; +InductionMotorDrive const inductionMotorDrive{}; +DieselMechanicalDrive const dieselMechanicalDrive{}; +DieselElectricDrive const dieselElectricDrive{}; + +} // namespace + +TractionDrive const &DriveOf(TEngineType const type) +{ + switch (type) + { + case TEngineType::Dumb: + return dumbDrive; + case TEngineType::WheelsDriven: + return wheelsDrivenDrive; + case TEngineType::ElectricSeriesMotor: + return seriesMotorDrive; + case TEngineType::ElectricInductionMotor: + return inductionMotorDrive; + case TEngineType::DieselEngine: + return dieselMechanicalDrive; + case TEngineType::DieselElectric: + return dieselElectricDrive; + case TEngineType::None: + case TEngineType::SteamEngine: + case TEngineType::Main: + return noDrive; + } + return noDrive; +} diff --git a/physics/mover/drive.h b/physics/mover/drive.h new file mode 100644 index 000000000..0d13d94d9 --- /dev/null +++ b/physics/mover/drive.h @@ -0,0 +1,56 @@ +/* +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 drive of a vehicle, by the kind of its engine (EngineType, the Engine section of the .fiz): what each kind of +// drive does in the step of the vehicle, in place of a switch on the engine type in each of those places. the drives +// hold no state of their own yet (it is in TMoverParameters): there is one of each kind, shared by the vehicles + +#pragma once + +#include "physics/vehicletypes.h" + +class TMoverParameters; + +// what the step of the traction gives the drive +struct DriveStep +{ + double dt{0.0}; // the length of the step [s] + double posRatio{0.0}; // the share of the controller positions, of the drive of no engine model (Dumb) + double revolutions{0.0}; // the revolutions of the engine + double moment{0.0}; // the moment of the diesel engine + double transmission{0.0}; // the ratio of the transmission of the diesel engine +}; + +class TractionDrive +{ +public: + virtual ~TractionDrive() = default; + + // the power of the engine for the controller positions; returns the share of the positions (Dumb), 0 for the others + virtual double UpdateEnginePower(TMoverParameters &vehicle) const; + // before the traction force, whether the reverser is set or not + virtual void BeforeTractionForce(TMoverParameters &vehicle, double dt) const; + // the traction force of the step (Ft), the reverser set + virtual void UpdateTractionForce(TMoverParameters &vehicle, DriveStep const &step) const; + // after the traction force, whether the reverser is set or not + virtual void AfterTractionForce(TMoverParameters &vehicle) const; + // the blowers of the starting resistors and the fans of the radiators + virtual void UpdateVentilators(TMoverParameters &vehicle, double dt) const; + // the current the given ammeter of the cab shows + virtual double ShowCurrent(TMoverParameters const &vehicle, int ammeter) const; + // the revolutions of the engine against the most it gives at the present controller position, 0..1; 1 with no + // engine of revolutions + virtual double EngineRpmRatio(TMoverParameters const &vehicle) const; + // the revolutions of the engine idling and at most [rpm]; the largest double with no engine of revolutions + virtual double EngineIdleRpm(TMoverParameters const &vehicle) const; + virtual double EngineMaxRpm(TMoverParameters const &vehicle) const; +}; + +// the drive of the given kind of engine +TractionDrive const &DriveOf(TEngineType type); diff --git a/physics/mover/traction.cpp b/physics/mover/traction.cpp index c35dc307e..745b51d0e 100644 --- a/physics/mover/traction.cpp +++ b/physics/mover/traction.cpp @@ -28,6 +28,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include "physics/mover/internal.h" +#include "physics/mover/drive.h" double TableInterpolation(std::map &Map, double Parameter) @@ -390,25 +391,7 @@ bool TMoverParameters::MotorBlowerPowerIsAvailable(cooling_fan const &Blower) co double TMoverParameters::ShowCurrent(int AmpN) const { // Odczyt poboru prądu na podanym amperomierzu - switch (EngineType) - { - case TEngineType::ElectricInductionMotor: - switch (AmpN) - { // do asynchronicznych - case 1: - return WindingRes * Mm / Vadd; - case 2: - return eimv_pr * WindingRes; - default: - return ShowCurrentP(AmpN); // T_MoverParameters:: - } - break; - case TEngineType::DieselElectric: - return fabs(Im); - break; - default: - return ShowCurrentP(AmpN); // T_MoverParameters:: - } + return Drive().ShowCurrent(*this, AmpN); }; bool TMoverParameters::MotorBlowersSwitch(bool State, end const Side, range_t const Notify) @@ -585,7 +568,6 @@ bool TMoverParameters::DynamicBrakeSwitch(bool Switch) // ************************************************************************************************* double TMoverParameters::TractionForce(double dt) { - using enum TEngineType; Ft = 0; double dtrans{0.0}; double dmoment{0.0}; @@ -602,65 +584,17 @@ double TMoverParameters::TractionForce(double dt) // hunter-091012: przeniesione z if DirActive<>0 (zeby po zejsciu z kierunku dalej spadala predkosc wentylatorow) // wentylatory rozruchowe // TBD, TODO: move this to update, it doesn't exactly have much to do with traction - UpdateVentilators(dt); - auto const PosRatio{UpdateEnginePower()}; + auto const &drive{Drive()}; + drive.UpdateVentilators(*this, dt); + auto const PosRatio{drive.UpdateEnginePower(*this)}; VoltageRelaysCheck(); - if (EngineType == DieselElectric && DEDynamicBrake.source != diesel_electric_dynamic_brake::control::none) - { - update_dieselelectric_dynamic_brake(dt); - } - + drive.BeforeTractionForce(*this, dt); if (DirActive != 0) - switch (EngineType) - { - case Dumb: - { - DumbTractionForce(PosRatio); - break; - } - case WheelsDriven: - { - WheelsDrivenTractionForce(dt); - break; - } - case ElectricSeriesMotor: - { - SeriesMotorTractionForce(dt); - break; - } - case DieselEngine: - { - DieselEngineTractionForce(dt, dmoment, dtrans); - break; - } - case DieselElectric: // youBy - { - DieselElectricTractionForce(revolutions); - if (DEDynamicBrake.level > 0.0) - { - // braking: no power asked for, so the drive above gave no force - apply_dieselelectric_dynamic_brake(dt); - } - break; - } - case ElectricInductionMotor: - { - InductionMotorTractionForce(dt); - break; - } - case None: - default: - { - break; - } - } // case EngineType - - if (EngineType == DieselElectric) { - // rough approximation of extra effort to overcome friction etc - EnginePower += EngineRPMRatio() * 0.15 * DElist[MainCtrlPosNo].GenPower; + drive.UpdateTractionForce(*this, DriveStep{dt, PosRatio, revolutions, dmoment, dtrans}); } + drive.AfterTractionForce(*this); return Ft; } @@ -668,62 +602,7 @@ double TMoverParameters::TractionForce(double dt) // the starting resistors' blowers, and the diesels' radiator fans void TMoverParameters::UpdateVentilators(double dt) { - switch (EngineType) - { - - case TEngineType::ElectricSeriesMotor: - { - if (MainCircuitPowered()) - { - UpdateResistorBlowers(dt); - } // mains - else - { - RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); - } - break; - } - - case TEngineType::DieselElectric: - { - // NOTE: for this type RventRot is the speed of motor blowers; we also update radiator fans while at it - if (true == Mains) - { - // TBD, TODO: currently ignores RVentType, fix this? - RventRot += std::clamp(enrot - RventRot, -100.0, 50.0) * dt; - dizel_heat.rpmw += static_cast(std::clamp(dizel_heat.rpmwz - dizel_heat.rpmw, -100.f, 50.f) * dt); - dizel_heat.rpmw2 += static_cast(std::clamp(dizel_heat.rpmwz2 - dizel_heat.rpmw2, -100.f, 50.f) * dt); - } - else - { - RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); - dizel_heat.rpmw *= static_cast(std::max(0.0, 1.0 - dizel_heat.rpmw * dt)); - dizel_heat.rpmw2 *= static_cast(std::max(0.0, 1.0 - dizel_heat.rpmw2 * dt)); - } - break; - } - - case TEngineType::DieselEngine: - { - // NOTE: we update only radiator fans, as vehicles with diesel engine don't have other ventilators - if (true == Mains) - { - dizel_heat.rpmw += static_cast(std::clamp(dizel_heat.rpmwz - dizel_heat.rpmw, -100.f, 50.f) * dt); - dizel_heat.rpmw2 += static_cast(std::clamp(dizel_heat.rpmwz2 - dizel_heat.rpmw2, -100.f, 50.f) * dt); - } - else - { - dizel_heat.rpmw *= static_cast(std::max(0.0, 1.0 - dizel_heat.rpmw * dt)); - dizel_heat.rpmw2 *= static_cast(std::max(0.0, 1.0 - dizel_heat.rpmw2 * dt)); - } - break; - } - - default: - { - break; - } - } + Drive().UpdateVentilators(*this, dt); } // the starting resistors' blowers of the series motors with the line breaker closed, worked by hand or by the current @@ -778,38 +657,7 @@ void TMoverParameters::UpdateResistorBlowers(double dt) // the power of a dumb or diesel engine; returns the ratio of the power a dumb engine is set to double TMoverParameters::UpdateEnginePower() { - double PosRatio{0.0}; - switch (EngineType) - { - case TEngineType::Dumb: - { - PosRatio = (MainCtrlPos + ScndCtrlPos) / (MainCtrlPosNo + ScndCtrlPosNo + 0.01); - EnginePower = /*1000.0 **/ Power * PosRatio; - break; - } - case TEngineType::DieselEngine: - { - dizel_Power = Mm * enrot * (2.0 * M_PI / 1000.0); - EnginePower = (dizel_Mstand + Mm) * enrot * (2.0 * M_PI / 1000.0); - if (MainCtrlPowerPos() > 1) - { - // dodatkowe opory z powodu sprezarki} - // dmoment -= dizel_Mstand * ( 0.2 * enrot / dizel_nmax ); //yB: skąd to w ogóle się bierze?! - } - break; - } - case TEngineType::DieselElectric: - { - EnginePower = 0; // the actual calculation is done in two steps later in the method - break; - } - default: - { - break; - } - } - - return PosRatio; + return Drive().UpdateEnginePower(*this); } // the line breaker opened by a voltage out of the motors' range, and the line contactors of a diesel-electric @@ -1879,3 +1727,9 @@ double TMoverParameters::ShowCurrentP(int AmpN) const return current; } } + +// the drive of the kind of engine of the vehicle +TractionDrive const &TMoverParameters::Drive() const +{ + return DriveOf(EngineType); +} From 007fb6b340ceb4adc39aa090bf93551e5f17fc75 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Fri, 27 Nov 2026 21:36:53 +0100 Subject: [PATCH 009/123] docs(agents): the naming of new and restructured code, and where the vehicle code goes AGENTS.md says how new code and code that gets restructured is named: PascalCase for types, public member functions and free functions of the headers; camelCase for the internal functions, all variables, members, parameters and the values of enums; English, without prefixes of the type. What files, scripts and the log read stays the same whatever the C++ names. It also says where the vehicle code is (physics/, vehicle/) and the rules of its structure: vehicletypes.h for the vocabulary, forward declarations instead of mover.h in headers, enum class and named fields instead of bits, VehicleCommand for the commands, drive classes instead of switches on EngineType. --- AGENTS.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 3b52f36ee..82ba88bc4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -93,6 +93,32 @@ To keep the gate passing, write new code so that it doesn't raise the rules that The project is C++20 (`CMAKE_CXX_STANDARD 20`), so no C++23 library addition is available on any compiler. That rules out `std::ranges::to`, `views::zip`, `views::enumerate`, `ranges::contains`, `std::print` and `std::expected`. +## Naming and the vehicle code + +New code, and code that gets restructured, is named in English with these cases: + +- **PascalCase** for types (classes, structs, enums, aliases), for public member functions and for free functions declared in + headers. +- **camelCase** for everything else: private and internal functions (those of an anonymous namespace too), all variables, members + (public ones too) and parameters, and the values of enums (`VehicleCommand::mainController`). +- No prefixes of the type or the kind (`f`, `i`, `b`, `mv`, `p` and the like) and no Polish names (`zaluzje`, `temperatura1`). + +Code that isn't otherwise touched keeps its names; renaming a member goes together with the restructuring of its part. What files, +scripts and the log read stays byte for byte the same whatever the C++ names are: the keywords of the `.fiz` and the scenery, the +keys of the dictionaries of the Python screens, the texts of the log and of `STR(...)`. + +The vehicle code is in `physics/` (the physics of the vehicles: `mover.h` and `physics/mover/*.cpp` by subsystem, `brakes.*`, +couplers, collisions, derailment) and `vehicle/` (the vehicle in the scenery, the cab, the AI). Keep it that way: + +- `physics/vehicletypes.h` holds the vocabulary the rest of the simulator passes around (vehicle ends, sides, couplings, lights, + sounds, the types of drive and brake). A header that only names these includes it, not `physics/mover.h`; a header that only + points at a `TMoverParameters` or a `TDynamicObject` declares it (`utilities/Classes.h`) and includes neither. +- A state of several mutually exclusive values is an `enum class`, a set of independent conditions is named fields, not the bits of + an `int`. Numbers of the formats (`.scn`, events, the network) are read into these where they come in and written where they go out. +- The commands between the vehicles are `VehicleCommand` (`physics/vehiclecommand.h`); their text names only matter where a command + comes as text. +- What depends on the kind of drive (`EngineType`) goes into its class in `physics/mover/drive.*`, not into a new `switch`. + ## Renderers: the move to OpenGL 4.6 and Vulkan The renderers on `master` are to be replaced. `feat/gl46-migration` (PR #216, a draft with milestone 27.04, to be merged after the From 2098614f8c9538acbe4909414b04f2851711b669 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Fri, 27 Nov 2026 23:20:53 +0100 Subject: [PATCH 010/123] refactor(physics): the couplings are Coupling and CouplingSet, not the bits of an int What a coupling between two vehicles joins (the coupler, the brake hose, the control cable, the high voltage...) was an int of bits, tested as (flag & 36) == 36, (x & coupling::control) != 0, TestFlag(), SetFlag(x, -y), compared with 0 and 3, with the same values twice (coupling:: and ctrain_). - enum class Coupling (coupler, brakeHose, control, highVoltage, gangway, mainHose, heating, permanent, power24v, power110v, power3x400v), the values the scenery files and the definitions have always used; ctrain_* is gone - CouplingSet, a set of them: HasAll(), HasAny(), Empty(), Set(), Clear() (as SetFlag() and ClearFlag() worked), Without(), |, &, ^, ==, and a test of any kind in a condition - TCoupling's CouplingFlag, AllowedFlag, AutomaticCouplingFlag, PowerFlag and PowerCoupling, TCommand's couplings (was Coupling), the coupling parameters of the commands, Attach(), CompatibleCoupling(), Next(), Prev(), FirstFind(), is_connected(), the AI's iCoupler are CouplingSet - the numbers are read into a set where they come in: the .fiz (BuffCoupl, negative AllowedFlag still meaning permanent), the scenery trainsets, the AI's Connect command, InvCtrCplFlag; and written as numbers where they go out: the scenery loader, the black box, the debug panels, DettachStatus() - (CouplingFlag & 36) == 36 reads HasAll(Coupling::control | Coupling::mainHose) No change in behaviour: 1144/1144 tests, golden traces exact against staging 62f7a29b. --- application/consistviews.cpp | 2 +- application/driverhints.cpp | 4 +- application/driveruipanels.cpp | 6 +- application/editormodeselftestscene.cpp | 2 +- physics/mover.h | 72 +++++----- physics/mover/cab.cpp | 2 +- physics/mover/collisions.cpp | 22 +-- physics/mover/commands.cpp | 38 ++--- physics/mover/couplers.cpp | 70 +++++----- physics/mover/diesel.cpp | 20 +-- physics/mover/doors.cpp | 12 +- physics/mover/electrics.cpp | 104 +++++++------- physics/mover/fizsections.cpp | 22 +-- physics/mover/mover.cpp | 24 ++-- physics/mover/pneumatics.cpp | 36 ++--- physics/mover/setup.cpp | 2 +- physics/mover/traction.cpp | 22 +-- physics/vehicletypes.h | 170 ++++++++++++++++------- rendering/common/scenewalk.cpp | 6 +- simulation/blackboxrecorder.cpp | 6 +- simulation/simulationstateserializer.cpp | 10 +- simulation/simulationtest.cpp | 2 +- tests/unit/consist.cpp | 8 +- tests/unit/consist.h | 8 +- tests/unit/drive.cpp | 2 +- tests/unit/scenario.cpp | 4 +- tests/unit/scenario.h | 2 +- tests/unit/test_brakes.cpp | 2 +- tests/unit/test_cab.cpp | 2 +- tests/unit/test_collisions.cpp | 50 +++---- tests/unit/test_commands.cpp | 20 +-- tests/unit/test_controls.cpp | 2 +- tests/unit/test_coupler_physics.cpp | 26 ++-- tests/unit/test_couplers.cpp | 34 ++--- tests/unit/test_couplers_trains.cpp | 56 ++++---- tests/unit/test_derailment_vehicle.cpp | 2 +- tests/unit/test_engine_start.cpp | 2 +- tests/unit/test_genset.cpp | 10 +- tests/unit/test_pullee.cpp | 2 +- tests/unit/test_queries.cpp | 2 +- tests/unit/vehicle.cpp | 2 +- tests/unit/vehicle.h | 10 +- utilities/translation.cpp | 28 ++-- vehicle/Driver.cpp | 52 +++---- vehicle/Driver.h | 2 +- vehicle/DynObj.cpp | 166 +++++++++++----------- vehicle/DynObj.h | 26 ++-- vehicle/Train.cpp | 40 +++--- vehicle/enginestart.cpp | 2 +- 49 files changed, 651 insertions(+), 565 deletions(-) diff --git a/application/consistviews.cpp b/application/consistviews.cpp index ca9d979dd..8c7847386 100644 --- a/application/consistviews.cpp +++ b/application/consistviews.cpp @@ -144,7 +144,7 @@ TDynamicObject *consist_views::pick(std::vector const &Train, double consist_views::gap_beyond(TDynamicObject const *Vehicle, int const End) { auto const &neighbour{Vehicle->MoverParameters->Neighbours[End]}; - if (neighbour.vehicle == nullptr || Vehicle->MoverParameters->Couplers[End].CouplingFlag != 0) { + if (neighbour.vehicle == nullptr || false == Vehicle->MoverParameters->Couplers[End].CouplingFlag.Empty()) { return -1.0; } if (neighbour.distance > cameraviews::coupler_watch_range) { diff --git a/application/driverhints.cpp b/application/driverhints.cpp index 3851b91e7..14d1f2f0c 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -330,7 +330,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // the local switch of the converter too, where the line contactors wait for the vehicle's own converter // (LineContactorsInterlock): left off by the human driver, that vehicle would never take power pVehicle->for_each( - coupling::control, + Coupling::control, []( TDynamicObject * Vehicle ) { auto *vehicle { Vehicle->MoverParameters }; if( vehicle->LineContactorsHeldByLocalConverterSwitch() ) { @@ -1322,7 +1322,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } case driver_hint::headcodepc5: { if( AIControllFlag - || ( Global.AITrainman && false == pVehicles[end::rear]->is_connected(pVehicle, coupling::control) ) ) { + || ( Global.AITrainman && false == pVehicles[end::rear]->is_connected(pVehicle, Coupling::control) ) ) { pVehicles[ end::rear ]->RaLightsSet( -1, light::redmarker_left | light::redmarker_right | light::rearendsignals ); } remove_hint( driver_hint::headcodetb1 ); diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 8d6e5829d..2d7c3fc9a 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -388,8 +388,8 @@ timetable_panel::update() { //odejmij lokomotywy czynne, a przynajmniej aktualną consistmass -= owner->pVehicle->MoverParameters->TotalMass; // subtract potential other half of a two-part vehicle - if( auto const *previous { owner->pVehicle->Prev( coupling::permanent ) }; previous != nullptr ) { consistmass -= previous->MoverParameters->TotalMass; } - auto const *next { owner->pVehicle->Next( coupling::permanent ) }; + if( auto const *previous { owner->pVehicle->Prev( Coupling::permanent ) }; previous != nullptr ) { consistmass -= previous->MoverParameters->TotalMass; } + auto const *next { owner->pVehicle->Next( Coupling::permanent ) }; if( next != nullptr ) { consistmass -= next->MoverParameters->TotalMass; } } std::snprintf( @@ -1632,7 +1632,7 @@ debug_panel::update_section_coupler( std::vector &Output ) { Global.UITextColor ); if( neighbour.vehicle != nullptr ) { Output.emplace_back( - std::format( "Neighbour: {} ({} end), coupling [{}], gap {:.1f} mm", neighbour.vehicle->name(), neighbour.vehicle_end == end::front ? "front" : "rear", coupler.CouplingFlag, neighbour.distance * 1000.0 ), + std::format( "Neighbour: {} ({} end), coupling [{}], gap {:.1f} mm", neighbour.vehicle->name(), neighbour.vehicle_end == end::front ? "front" : "rear", coupler.CouplingFlag.Bits(), neighbour.distance * 1000.0 ), Global.UITextColor ); } else { diff --git a/application/editormodeselftestscene.cpp b/application/editormodeselftestscene.cpp index f9315e9e5..2868b22db 100644 --- a/application/editormodeselftestscene.cpp +++ b/application/editormodeselftestscene.cpp @@ -268,7 +268,7 @@ editor_mode::selftest_result editor_mode::selftest_scene(std::string const &comm auto const front{vehicle->VectorFront()}; auto const coupler = [&](int const End) { auto const &coupler{vehicle->MoverParameters->Couplers[End]}; - return coupler.Connected != nullptr ? coupler.Connected->Name + "/" + std::to_string(coupler.CouplingFlag) : std::string{"-"}; + return coupler.Connected != nullptr ? coupler.Connected->Name + "/" + std::to_string(coupler.CouplingFlag.Bits()) : std::string{"-"}; }; WriteLog(format("SELFTEST vehicle %s head %.2f %.2f front %.2f %.2f dir %d coupler0 %s coupler1 %s", vehicle->name().c_str(), head.x, head.z, front.x, front.z, vehicle->iDirection, coupler(0).c_str(), coupler(1).c_str())); } diff --git a/physics/mover.h b/physics/mover.h index b254656c8..364c6bb2b 100644 --- a/physics/mover.h +++ b/physics/mover.h @@ -479,13 +479,13 @@ struct TCoupling double FmaxC = 1000.0; double beta = 0.0; TCouplerType CouplerType = TCouplerType::NoCoupler; /*typ sprzegu*/ - int AutomaticCouplingFlag = coupling::coupler; - int AllowedFlag = coupling::coupler | coupling::brakehose; // Ra: maska dostępnych - int PowerFlag = coupling::power110v | coupling::power24v; - int PowerCoupling = coupling::permanent; // type of coupling required for power transfer + CouplingSet AutomaticCouplingFlag{Coupling::coupler}; + CouplingSet AllowedFlag{Coupling::coupler | Coupling::brakeHose}; // Ra: maska dostępnych + CouplingSet PowerFlag{Coupling::power110v | Coupling::power24v}; + CouplingSet PowerCoupling{Coupling::permanent}; // type of coupling required for power transfer /*zmienne*/ bool AutomaticCouplingAllowed{true}; // whether automatic coupling can be currently performed - int CouplingFlag = 0; /*0 - wirtualnie, 1 - sprzegi, 2 - pneumatycznie, 4 - sterowanie, 8 - kabel mocy*/ + CouplingSet CouplingFlag; // what the coupling joins; none: the vehicles only see each other class TMoverParameters *Connected = nullptr; /*co jest podlaczone*/ int ConnectedNr = 0; // Ra: od której strony podłączony do (Connected): 0=przód, 1=tył double CForce = 0.0; /*sila z jaka dzialal*/ @@ -502,29 +502,29 @@ struct TCoupling power_coupling power_110v; power_coupling power_24v; // the circuit of the power coupling given, nullptr for a coupling which isn't one - power_coupling *power(coupling const Coupling) + power_coupling *power(Coupling const kind) { - switch (Coupling) + switch (kind) { - case coupling::highvoltage: + case Coupling::highVoltage: return &power_high; - case coupling::power110v: + case Coupling::power110v: return &power_110v; - case coupling::power24v: + case Coupling::power24v: return &power_24v; default: return nullptr; } } - power_coupling const *power(coupling const Coupling) const + power_coupling const *power(Coupling const kind) const { - switch (Coupling) + switch (kind) { - case coupling::highvoltage: + case Coupling::highVoltage: return &power_high; - case coupling::power110v: + case Coupling::power110v: return &power_110v; - case coupling::power24v: + case Coupling::power24v: return &power_24v; default: return nullptr; @@ -1768,7 +1768,7 @@ class TMoverParameters // obsługa sprzęgów static double CouplerDist(TMoverParameters const *Left, TMoverParameters const *Right); static double Distance(const TLocation &Loc1, const TLocation &Loc2, const TDimension &Dim1, const TDimension &Dim2); - bool Attach(int ConnectNo, int ConnectToNr, TMoverParameters *ConnectTo, int CouplingType, bool Enforce = false, bool Audible = true); + bool Attach(int ConnectNo, int ConnectToNr, TMoverParameters *ConnectTo, CouplingSet CouplingType, bool Enforce = false, bool Audible = true); int DettachStatus(int ConnectNo); bool Dettach(int ConnectNo); void damage_coupler(int const End); @@ -1859,7 +1859,7 @@ class TMoverParameters double ShowEngineRotation(int VehN) const; // Q ******************************************************************************************* - double GetTrainsetVoltage(int const Coupling = coupling::heating | coupling::highvoltage) const; + double GetTrainsetVoltage(CouplingSet const couplings = Coupling::heating | Coupling::highVoltage) const; double GetTrainsetHighVoltage() const; // what turns the physics on, counted for the debug panel (Timer::switching_counter) enum class wake_cause @@ -1893,20 +1893,20 @@ class TMoverParameters double EngineMaxRPM() const; /*! przesylanie komend sterujacych*/ - bool SendCtrlToNext(VehicleCommand const CtrlCommand, double const ctrlvalue, double const dir, int const Couplertype = coupling::control); - bool SetInternalCommand(VehicleCommand const NewCommand, double NewValue1, double NewValue2, int const Couplertype = coupling::control); - bool RunCommand(VehicleCommand const Command, double CValue1, double CValue2, int const Couplertype = coupling::control, std::string_view Argument = {}); + bool SendCtrlToNext(VehicleCommand const CtrlCommand, double const ctrlvalue, double const dir, CouplingSet const Couplertype = Coupling::control); + bool SetInternalCommand(VehicleCommand const NewCommand, double NewValue1, double NewValue2, CouplingSet const Couplertype = Coupling::control); + bool RunCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype = Coupling::control, std::string_view Argument = {}); // the parts of RunCommand(), by the area of the commands - bool RunControllerCommand(VehicleCommand const Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunRelaysCommand(VehicleCommand const Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunCabCommand(VehicleCommand const Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunBrakeCommand(VehicleCommand const Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunBrakeEquipmentCommand(VehicleCommand const Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunAuxiliariesCommand(VehicleCommand const Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunPumpsCommand(VehicleCommand const Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunBlowersCommand(VehicleCommand const Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunPowerCommand(VehicleCommand const Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunDoorsCommand(VehicleCommand const Command, double CValue1, double CValue2, int Couplertype, bool &OK); + bool RunControllerCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet Couplertype, bool &OK); + bool RunRelaysCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet Couplertype, bool &OK); + bool RunCabCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet Couplertype, bool &OK); + bool RunBrakeCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet Couplertype, bool &OK); + bool RunBrakeEquipmentCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet Couplertype, bool &OK); + bool RunAuxiliariesCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet Couplertype, bool &OK); + bool RunPumpsCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet Couplertype, bool &OK); + bool RunBlowersCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet Couplertype, bool &OK); + bool RunPowerCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet Couplertype, bool &OK); + bool RunDoorsCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet Couplertype, bool &OK); void DoorPermitCommand(double CValue1, double CValue2); void DoorRemoteCommand(bool Open, double CValue1, double CValue2); bool RunLoadCommand(VehicleCommand const Command, double CValue1, double CValue2, std::string_view Argument, bool &OK); @@ -2111,7 +2111,7 @@ class TMoverParameters bool ControlCouplingAllowed(int const End, TMoverParameters const &Other, int const OtherEnd) const; // the CouplingType to join the End of this vehicle and the OtherEnd of the other one with, without the control coupling // when ControlCouplingAllowed() rules it out. a permanent coupling (of the vehicles of one unit) is kept whole - int CompatibleCoupling(int const End, TMoverParameters const &Other, int const OtherEnd, int const CouplingType) const; + CouplingSet CompatibleCoupling(int const End, TMoverParameters const &Other, int const OtherEnd, CouplingSet const CouplingType) const; // the horns of the Signal (WarningSignal bits) which have the air or the voltage they need to sound int SoundingHorns(int const Signal) const; // whether the signal lamps of the main circuit (line contactors, ground relay, motor overload relays) can light: @@ -2225,12 +2225,12 @@ class TMoverParameters /*-funkcje typowe dla lokomotywy elektrycznej*/ void LowVoltagePowerCheck(double const Deltatime); void MainsCheck(double const Deltatime); - void PowerCouplersCheck(double const Deltatime, coupling const Coupling); + void PowerCouplersCheck(double const Deltatime, Coupling const kind); // the parts of PowerCouplersCheck() - double LocalPowerVoltage(coupling Coupling); - void PowerCouplersVoltage(coupling Coupling, double abslocalvoltage, bool localpowersource); - void PowerCouplersCurrent(coupling Coupling, bool localpowersource); - double *PowerCircuitCurrent(coupling Coupling); + double LocalPowerVoltage(Coupling kind); + void PowerCouplersVoltage(Coupling kind, double abslocalvoltage, bool localpowersource); + void PowerCouplersCurrent(Coupling kind, bool localpowersource); + double *PowerCircuitCurrent(Coupling kind); void ConverterCheck(double const Timestep); // przetwornica void HeatingCheck(double const Timestep); void WaterPumpCheck(double const Timestep); diff --git a/physics/mover/cab.cpp b/physics/mover/cab.cpp index 14df59d94..760327cdb 100644 --- a/physics/mover/cab.cpp +++ b/physics/mover/cab.cpp @@ -82,7 +82,7 @@ int TMoverParameters::SoundingHorns(int const Signal) const } // a vehicle without a main reservoir of its own takes the air from the main pipe, a vehicle without either // (a road vehicle, say) has no air to check - auto const mainpipe{((Couplers[end::front].AllowedFlag | Couplers[end::rear].AllowedFlag) & coupling::mainhose) != 0}; + auto const mainpipe{(Couplers[end::front].AllowedFlag | Couplers[end::rear].AllowedFlag).HasAny(Coupling::mainHose)}; return false == mainpipe || ScndPipePress >= HornMinPressure; }}; auto horns{0}; diff --git a/physics/mover/collisions.cpp b/physics/mover/collisions.cpp index a890e1bbb..a696bba8b 100644 --- a/physics/mover/collisions.cpp +++ b/physics/mover/collisions.cpp @@ -57,7 +57,7 @@ namespace // a derailed vehicle tears its brake hoses: the brake pipe vents and the rest of the train brakes in emergency void tear_brake_hoses(TMoverParameters &Vehicle) { - if (std::any_of(std::begin(Vehicle.Couplers), std::end(Vehicle.Couplers), [](auto const &Coupler) { return (Coupler.CouplingFlag & coupling::brakehose) == coupling::brakehose; })) + if (std::any_of(std::begin(Vehicle.Couplers), std::end(Vehicle.Couplers), [](auto const &Coupler) { return Coupler.CouplingFlag.HasAll(Coupling::brakeHose); })) { Vehicle.AlarmChainFlag = true; } @@ -109,7 +109,7 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) auto velocity{V}; auto othervehiclevelocity{othervehicle->V * otherdirection}; // calculate collision force and new velocities for involved vehicles - auto const VirtualCoupling{(thiscoupler.CouplingFlag == coupling::faux)}; + auto const VirtualCoupling{(thiscoupler.CouplingFlag == Coupling::none)}; auto CCF{0.0}; switch (End) @@ -141,7 +141,7 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) } // HACK: limit excessive speed derailment checks to vehicles which aren't part of the same consist - auto const outsideconsist{thiscoupler.CouplingFlag == coupling::faux || true == TestFlag(othervehicle->DamageFlag, dtrain_out)}; + auto const outsideconsist{thiscoupler.CouplingFlag == Coupling::none || true == TestFlag(othervehicle->DamageFlag, dtrain_out)}; auto const velocitydifference{outsideconsist ? CollisionVelocity(End, *othervehicle, otherend) : 0.0}; if (velocitydifference > SafeCollisionVelocity) @@ -169,7 +169,7 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) auto const accelerationspike{physical ? 0.0 : 1.0}; // derailed the legacy way a vehicle is a wall, off the rails by the new criteria it slides on and takes the hit. with // the crush, the vehicles coupled to the wall push it on (crush_hit()) - auto const coupled{thiscoupler.CouplingFlag != coupling::faux}; + auto const coupled{thiscoupler.CouplingFlag != Coupling::none}; auto const wall = [crushing, coupled](TMoverParameters const &Vehicle) { return TestFlag(Vehicle.DamageFlag, dtrain_out) && (false == crushing || (Vehicle.Derailed == derailment::outcome::none && false == coupled)); }; @@ -201,14 +201,14 @@ void TMoverParameters::damage_coupler(int const End) if (SetFlag(DamageFlag, dtrain_coupling)) EventFlag = true; - auto const hosetorn{(thiscoupler.CouplingFlag & coupling::brakehose) == coupling::brakehose}; + auto const hosetorn{thiscoupler.CouplingFlag.HasAll(Coupling::brakeHose)}; if (hosetorn) { // hamowanie nagle - zerwanie przewodow hamulcowych AlarmChainFlag = true; } - thiscoupler.CouplingFlag = 0; + thiscoupler.CouplingFlag = {}; thiscoupler.broken = true; if (thiscoupler.Connected != nullptr) @@ -216,7 +216,7 @@ void TMoverParameters::damage_coupler(int const End) // break connection with other vehicle, if there's any: on the end it's coupled with, which is the front one too // for vehicles facing each other auto &othercoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr]}; - othercoupler.CouplingFlag = coupling::faux; + othercoupler.CouplingFlag = Coupling::none; // the coupling broke between the two, either end can be repaired othercoupler.broken = true; if (hosetorn && coupler_physics_at(End)) @@ -377,7 +377,7 @@ bool TMoverParameters::crush_hit(int const End, double const dt) // a vehicle derailed the legacy way (the end of the track, say) stays where it is, whatever hits it from outside its // train. the vehicles coupled to it push it on, as the train behind a derailed vehicle does: a wall to them, it // stopped the whole train at once, and the vehicles behind it crushed by the energy of the train - auto const coupled{thiscoupler.CouplingFlag != coupling::faux}; + auto const coupled{thiscoupler.CouplingFlag != Coupling::none}; auto const wall{false == coupled && TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none}; auto const otherwall{false == coupled && TestFlag(othervehicle->DamageFlag, dtrain_out) && othervehicle->Derailed == derailment::outcome::none}; if (wall && otherwall) @@ -506,16 +506,16 @@ bool TMoverParameters::crush_hit(int const End, double const dt) // the crushed headstock tears off the draw gear, with the brake hose: both parts of the train brake in emergency. // the coupler of an end not coupled is gone as well, it doesn't couple any more - if (thiscoupler.CouplingFlag != coupling::faux && std::max(thiscoupler.crush, othercoupler.crush) >= collision::draw_gear_crush) + if (thiscoupler.CouplingFlag != Coupling::none && std::max(thiscoupler.crush, othercoupler.crush) >= collision::draw_gear_crush) { - auto const hose{(thiscoupler.CouplingFlag & coupling::brakehose) == coupling::brakehose}; + auto const hose{thiscoupler.CouplingFlag.HasAll(Coupling::brakeHose)}; damage_coupler(End); if (hose) { othervehicle->AlarmChainFlag = true; } } - else if (thiscoupler.CouplingFlag == coupling::faux) + else if (thiscoupler.CouplingFlag == Coupling::none) { if (thiscoupler.crush >= collision::draw_gear_crush && false == thiscoupler.broken) { diff --git a/physics/mover/commands.cpp b/physics/mover/commands.cpp index 499ba62fc..2fc63a698 100644 --- a/physics/mover/commands.cpp +++ b/physics/mover/commands.cpp @@ -50,10 +50,10 @@ void TMoverParameters::PutCommand(std::string const &NewCommand, double NewValue // Q: 20160714 // Ustawienie komendy wraz z parametrami // ************************************************************************************************* -bool TMoverParameters::SetInternalCommand(VehicleCommand const NewCommand, double NewValue1, double NewValue2, int const Couplertype) +bool TMoverParameters::SetInternalCommand(VehicleCommand const NewCommand, double NewValue1, double NewValue2, CouplingSet const Couplertype) { bool SIC; - if (CommandIn.Command == NewCommand && CommandIn.Argument.empty() && CommandIn.Value1 == NewValue1 && CommandIn.Value2 == NewValue2 && CommandIn.Coupling == Couplertype) + if (CommandIn.Command == NewCommand && CommandIn.Argument.empty() && CommandIn.Value1 == NewValue1 && CommandIn.Value2 == NewValue2 && CommandIn.couplings == Couplertype) SIC = false; else { @@ -62,7 +62,7 @@ bool TMoverParameters::SetInternalCommand(VehicleCommand const NewCommand, doubl CommandIn.Argument.clear(); CommandIn.Value1 = NewValue1; CommandIn.Value2 = NewValue2; - CommandIn.Coupling = Couplertype; + CommandIn.couplings = Couplertype; SIC = true; LastLoadChangeTime = 0; // zerowanie czasu (roz)ładowania } @@ -74,7 +74,7 @@ bool TMoverParameters::SetInternalCommand(VehicleCommand const NewCommand, doubl // Q: 20160714 // wysyłanie komendy w kierunku dir (1=przód, -1=tył) do kolejnego pojazdu (jednego) // ************************************************************************************************* -bool TMoverParameters::SendCtrlToNext(VehicleCommand const CtrlCommand, double const ctrlvalue, double const dir, int const Couplertype) +bool TMoverParameters::SendCtrlToNext(VehicleCommand const CtrlCommand, double const ctrlvalue, double const dir, CouplingSet const Couplertype) { bool OK; int d; // numer sprzęgu w kierunku którego wysyłamy @@ -84,7 +84,7 @@ bool TMoverParameters::SendCtrlToNext(VehicleCommand const CtrlCommand, double c OK = true; // ( dir != 0 ); // experimentally disabled d = (1 + static_cast(Sign(dir))) / 2; // dir=-1=>d=0, dir=1=>d=1 - wysyłanie tylko w tył // musi być wybrana niezerowa kabina - if (OK && Couplers[d].Connected != nullptr && TestFlag(Couplers[d].CouplingFlag, Couplertype)) + if (OK && Couplers[d].Connected != nullptr && Couplers[d].CouplingFlag.HasAll(Couplertype)) { if (Couplers[d].ConnectedNr != d) @@ -114,7 +114,7 @@ bool TMoverParameters::SendCtrlToNext(VehicleCommand const CtrlCommand, double c // Komenda musi być zdefiniowana tutaj, a jeśli się wywołuje funkcję, to ona nie może // sama przesyłać do kolejnych pojazdów. Należy też się zastanowić, czy dla uzyskania // jakiejś zmiany (np. IncMainCtrl) lepiej wywołać funkcję, czy od razu wysłać komendę. -bool TMoverParameters::RunCommand(VehicleCommand const Command, double CValue1, double CValue2, int const Couplertype, std::string_view const Argument) +bool TMoverParameters::RunCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, std::string_view const Argument) { // the group of the command sets OK; a command none of them knows isn't done if (bool OK{false}; RunControllerCommand(Command, CValue1, CValue2, Couplertype, OK) || RunRelaysCommand(Command, CValue1, CValue2, Couplertype, OK) || @@ -134,7 +134,7 @@ bool TMoverParameters::RunCommand(VehicleCommand const Command, double CValue1, } // RunCommand() for the controllers; returns whether the command is one of them -bool TMoverParameters::RunControllerCommand(VehicleCommand const Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +bool TMoverParameters::RunControllerCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) { if (Command == VehicleCommand::mainController) { @@ -183,7 +183,7 @@ bool TMoverParameters::RunControllerCommand(VehicleCommand const Command, double } // RunCommand() for the direction, the automatic start and the current relays; returns whether the command is one of them -bool TMoverParameters::RunRelaysCommand(VehicleCommand const Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +bool TMoverParameters::RunRelaysCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) { if (Command == VehicleCommand::direction) { @@ -217,7 +217,7 @@ bool TMoverParameters::RunRelaysCommand(VehicleCommand const Command, double CVa } // RunCommand() for the cab and the speed control; returns whether the command is one of them -bool TMoverParameters::RunCabCommand(VehicleCommand const Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +bool TMoverParameters::RunCabCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) { if (Command == VehicleCommand::cabActivation) { @@ -268,7 +268,7 @@ bool TMoverParameters::RunCabCommand(VehicleCommand const Command, double CValue } // RunCommand() for the train brake, the releaser and the emergency brake; returns whether the command is one of them -bool TMoverParameters::RunBrakeCommand(VehicleCommand const Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +bool TMoverParameters::RunBrakeCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) { if (Command == VehicleCommand::brake) // youBy - jak sie EP hamuje, to trza sygnal wyslac... { @@ -308,7 +308,7 @@ bool TMoverParameters::RunBrakeCommand(VehicleCommand const Command, double CVal } // RunCommand() for the brake delays, the spring brake, the sand and the cab signalling; returns whether the command is one of them -bool TMoverParameters::RunBrakeEquipmentCommand(VehicleCommand const Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +bool TMoverParameters::RunBrakeEquipmentCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) { if (Command == VehicleCommand::brakeDelay) { @@ -355,7 +355,7 @@ bool TMoverParameters::RunBrakeEquipmentCommand(VehicleCommand const Command, do } // RunCommand() for the heating, the converter, the battery and the compressor; returns whether the command is one of them -bool TMoverParameters::RunAuxiliariesCommand(VehicleCommand const Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +bool TMoverParameters::RunAuxiliariesCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) { if (Command == VehicleCommand::heatingSwitch) { @@ -403,7 +403,7 @@ bool TMoverParameters::RunAuxiliariesCommand(VehicleCommand const Command, doubl } // RunCommand() for the water, fuel and oil pumps and the water heater; returns whether the command is one of them -bool TMoverParameters::RunPumpsCommand(VehicleCommand const Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +bool TMoverParameters::RunPumpsCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) { if (Command == VehicleCommand::waterPumpBreakerSwitch) { @@ -514,7 +514,7 @@ bool TMoverParameters::RunPumpsCommand(VehicleCommand const Command, double CVal } // RunCommand() for the motor blowers and the compartment lights; returns whether the command is one of them -bool TMoverParameters::RunBlowersCommand(VehicleCommand const Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +bool TMoverParameters::RunBlowersCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) { if (Command == VehicleCommand::motorBlowersFrontSwitch) { @@ -580,7 +580,7 @@ bool TMoverParameters::RunBlowersCommand(VehicleCommand const Command, double CV } // RunCommand() for the line breaker, the relays and the pantographs; returns whether the command is one of them -bool TMoverParameters::RunPowerCommand(VehicleCommand const Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +bool TMoverParameters::RunPowerCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) { if (Command == VehicleCommand::mainSwitch) { @@ -598,7 +598,7 @@ bool TMoverParameters::RunPowerCommand(VehicleCommand const Command, double CVal auto const inputcab{(static_cast(CValue1) & 0x40) != 0 ? 1 : 0}; auto const inputoperation{static_cast(CValue1) & ~(0x80 | 0x40)}; auto const noswap{TrainType == train_type::emu || TrainType == train_type::et41}; - auto swap{false == noswap && TestFlag(Couplers[CValue2 == -1 ? end::rear : end::front].CouplingFlag, coupling::control)}; + auto swap{false == noswap && Couplers[CValue2 == -1 ? end::rear : end::front].CouplingFlag.HasAll(Coupling::control)}; if (auto const reversed{inputcab != (CabActive != -1 ? 1 : 0)}; reversed) { swap = !swap; @@ -634,7 +634,7 @@ bool TMoverParameters::RunPowerCommand(VehicleCommand const Command, double CVal } // RunCommand() for the doors and the departure signal; returns whether the command is one of them -bool TMoverParameters::RunDoorsCommand(VehicleCommand const Command, double CValue1, double CValue2, int const Couplertype, bool &OK) +bool TMoverParameters::RunDoorsCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) { if (Command == VehicleCommand::doorPermit) { @@ -780,7 +780,7 @@ bool TMoverParameters::RunInternalCommand() if (CommandIn.Command != VehicleCommand::none) { - OK = RunCommand(CommandIn.Command, CommandIn.Value1, CommandIn.Value2, CommandIn.Coupling, CommandIn.Argument); + OK = RunCommand(CommandIn.Command, CommandIn.Value1, CommandIn.Value2, CommandIn.couplings, CommandIn.Argument); if (OK) { @@ -789,7 +789,7 @@ bool TMoverParameters::RunInternalCommand() CommandIn.Argument.clear(); CommandIn.Value1 = 0; CommandIn.Value2 = 0; - CommandIn.Coupling = 0; + CommandIn.couplings = {}; CommandIn.Location.X = 0; CommandIn.Location.Y = 0; CommandIn.Location.Z = 0; diff --git a/physics/mover/couplers.cpp b/physics/mover/couplers.cpp index 06bf30481..6acf3f233 100644 --- a/physics/mover/couplers.cpp +++ b/physics/mover/couplers.cpp @@ -45,12 +45,12 @@ double TMoverParameters::CouplerDist(TMoverParameters const *Left, TMoverParamet return Distance(Left->Loc, Right->Loc, Left->Dim, Right->Dim); // odległość pomiędzy sprzęgami (kula!) }; -bool TMoverParameters::Attach(int ConnectNo, int ConnectToNr, TMoverParameters *ConnectTo, int CouplingType, bool Enforce, bool Audible) +bool TMoverParameters::Attach(int ConnectNo, int ConnectToNr, TMoverParameters *ConnectTo, CouplingSet CouplingType, bool Enforce, bool Audible) { // łączenie do swojego sprzęgu (ConnectNo) pojazdu (ConnectTo) stroną (ConnectToNr) // Ra: zwykle wykonywane dwukrotnie, dla każdego pojazdu oddzielnie // Ra: trzeba by odróżnić wymóg dociśnięcia od uszkodzenia sprzęgu przy podczepianiu AI do składu - if (ConnectTo == nullptr || CouplingType == coupling::faux) + if (ConnectTo == nullptr || CouplingType == Coupling::none) { return false; } @@ -72,14 +72,14 @@ bool TMoverParameters::Attach(int ConnectNo, int ConnectToNr, TMoverParameters * { WriteLog(std::format("Vehicles \"{}\" and \"{}\" can't share their control, coupled without the control connection", Name, ConnectTo->Name)); CouplingType = compatible; - if (CouplingType == coupling::faux) + if (CouplingType == Coupling::none) { return false; } } // stykaja sie zderzaki i kompatybilne typy sprzegow, chyba że łączenie na starcie - if (thiscoupler.CouplingFlag == coupling::faux) + if (thiscoupler.CouplingFlag == Coupling::none) { // a new coupling: the play of the coupling as set up anew, without the stretch of the one before thiscoupler.physics_state.couple(); @@ -99,16 +99,16 @@ bool TMoverParameters::Attach(int ConnectNo, int ConnectToNr, TMoverParameters * othercoupler.CouplingFlag = CouplingType; othercoupler.ConnectedNr = ConnectNo; - if (true == Audible && couplingchange != 0) + if (true == Audible && false == couplingchange.Empty()) { // set sound event flag int soundflag{sound::none}; - std::vector> const soundmappings = {{coupling::coupler, sound::attachcoupler}, {coupling::brakehose, sound::attachbrakehose}, - {coupling::mainhose, sound::attachmainhose}, {coupling::control, sound::attachcontrol}, - {coupling::gangway, sound::attachgangway}, {coupling::heating, sound::attachheating}}; + std::vector> const soundmappings = {{Coupling::coupler, sound::attachcoupler}, {Coupling::brakeHose, sound::attachbrakehose}, + {Coupling::mainHose, sound::attachmainhose}, {Coupling::control, sound::attachcontrol}, + {Coupling::gangway, sound::attachgangway}, {Coupling::heating, sound::attachheating}}; for (auto const &[mappingcoupling, mappingsound] : soundmappings) { - if ((couplingchange & mappingcoupling) != 0) + if (couplingchange.HasAny(mappingcoupling)) { soundflag |= mappingsound; } @@ -124,14 +124,14 @@ int TMoverParameters::DettachStatus(int ConnectNo) // powinny być 3 informacje: =0 sprzęg już rozłączony, <0 da się rozłączyć. >0 nie da się rozłączyć if (!Couplers[ConnectNo].Connected) return 0; // nie ma nic, to rozłączanie jest OK - if ((Couplers[ConnectNo].CouplingFlag & ctrain_coupler) == 0) - return -Couplers[ConnectNo].CouplingFlag; // hak nie połączony - rozłączanie jest OK + if (false == Couplers[ConnectNo].CouplingFlag.HasAny(Coupling::coupler)) + return -Couplers[ConnectNo].CouplingFlag.Bits(); // hak nie połączony - rozłączanie jest OK if (TestFlag(DamageFlag, dtrain_coupling)) - return -Couplers[ConnectNo].CouplingFlag; // hak urwany - rozłączanie jest OK + return -Couplers[ConnectNo].CouplingFlag.Bits(); // hak urwany - rozłączanie jest OK // CouplerDist(ConnectNo); if (Couplers[ConnectNo].type() != TCouplerType::Screw || Neighbours[ConnectNo].distance < 0.01) - return -Couplers[ConnectNo].CouplingFlag; // można rozłączać, jeśli dociśnięty - return Neighbours[ConnectNo].distance > 0.2 ? -Couplers[ConnectNo].CouplingFlag : Couplers[ConnectNo].CouplingFlag; + return -Couplers[ConnectNo].CouplingFlag.Bits(); // można rozłączać, jeśli dociśnięty + return Neighbours[ConnectNo].distance > 0.2 ? -Couplers[ConnectNo].CouplingFlag.Bits() : Couplers[ConnectNo].CouplingFlag.Bits(); }; bool TMoverParameters::Dettach(int ConnectNo) @@ -151,25 +151,25 @@ bool TMoverParameters::Dettach(int ConnectNo) if (couplingstate < 0) { // gdy scisniete zderzaki, chyba ze zerwany sprzeg (wirtualnego nie odpinamy z drugiej strony) - std::tie(othercoupler.Connected, othercoupler.ConnectedNr, othercoupler.CouplingFlag) = std::make_tuple(nullptr, -1, coupling::faux); - std::tie(thiscoupler.Connected, thiscoupler.ConnectedNr, thiscoupler.CouplingFlag) = std::make_tuple(nullptr, -1, coupling::faux); + std::tie(othercoupler.Connected, othercoupler.ConnectedNr, othercoupler.CouplingFlag) = std::make_tuple(nullptr, -1, Coupling::none); + std::tie(thiscoupler.Connected, thiscoupler.ConnectedNr, thiscoupler.CouplingFlag) = std::make_tuple(nullptr, -1, Coupling::none); } else if (couplingstate > 0) { // odłączamy węże i resztę, pozostaje sprzęg fizyczny, który wymaga dociśnięcia (z wirtualnym nic) - thiscoupler.CouplingFlag &= coupling::coupler; - othercoupler.CouplingFlag &= coupling::coupler; + thiscoupler.CouplingFlag &= Coupling::coupler; + othercoupler.CouplingFlag &= Coupling::coupler; } // set sound event flag couplingchange ^= thiscoupler.CouplingFlag; // remaining bits were removed from coupling - if (couplingchange != 0) + if (false == couplingchange.Empty()) { int soundflag{sound::detach}; // HACK: use detach flag to indicate removal of listed coupling - std::vector> const soundmappings = {{coupling::coupler, sound::attachcoupler}, {coupling::brakehose, sound::attachbrakehose}, - {coupling::mainhose, sound::attachmainhose}, {coupling::control, sound::attachcontrol}, - {coupling::gangway, sound::attachgangway}, {coupling::heating, sound::attachheating}}; + std::vector> const soundmappings = {{Coupling::coupler, sound::attachcoupler}, {Coupling::brakeHose, sound::attachbrakehose}, + {Coupling::mainHose, sound::attachmainhose}, {Coupling::control, sound::attachcontrol}, + {Coupling::gangway, sound::attachgangway}, {Coupling::heating, sound::attachheating}}; for (auto const &[mappingcoupling, mappingsound] : soundmappings) { - if ((couplingchange & mappingcoupling) != 0) + if (couplingchange.HasAny(mappingcoupling)) { soundflag |= mappingsound; } @@ -246,13 +246,13 @@ bool TMoverParameters::ControlCouplingAllowed(int const End, TMoverParameters co return traction == traction_kind::none || othertraction == traction_kind::none || traction == othertraction; } -int TMoverParameters::CompatibleCoupling(int const End, TMoverParameters const &Other, int const OtherEnd, int const CouplingType) const +CouplingSet TMoverParameters::CompatibleCoupling(int const End, TMoverParameters const &Other, int const OtherEnd, CouplingSet const CouplingType) const { - if ((CouplingType & coupling::control) == 0 || (CouplingType & coupling::permanent) != 0 || ControlCouplingAllowed(End, Other, OtherEnd)) + if (false == CouplingType.HasAny(Coupling::control) || CouplingType.HasAny(Coupling::permanent) || ControlCouplingAllowed(End, Other, OtherEnd)) { return CouplingType; } - return CouplingType & ~coupling::control; + return CouplingType.Without(Coupling::control); } // ************************************************************************************************* @@ -289,7 +289,7 @@ double TMoverParameters::CouplerForce(int const End, double dt) // 090503: dzwieki pracy zderzakow SetFlag(thiscoupler.sounds, absdV > 5.0 ? sound::bufferclash | sound::loud : sound::bufferclash); } - else if (thiscoupler.CouplingFlag != coupling::faux && newdistance > 0.001 && thiscoupler.Dist <= 0.001 && absdV > 0.005 && Vel > 1.0) + else if (thiscoupler.CouplingFlag != Coupling::none && newdistance > 0.001 && thiscoupler.Dist <= 0.001 && absdV > 0.005 && Vel > 1.0) { // 090503: dzwieki pracy sprzegu SetFlag(thiscoupler.sounds, absdV > 0.035 ? sound::couplerstretch | sound::loud : sound::couplerstretch); @@ -300,13 +300,13 @@ double TMoverParameters::CouplerForce(int const End, double dt) double CF{0.0}; - if (thiscoupler.CouplingFlag == coupling::faux && initialdistance > 0.05) + if (thiscoupler.CouplingFlag == Coupling::none && initialdistance > 0.05) { // arbitrary distance // potentially reset auto coupling lock thiscoupler.AutomaticCouplingAllowed = true; } - if (thiscoupler.CouplingFlag != coupling::faux || initialdistance < 0) + if (thiscoupler.CouplingFlag != Coupling::none || initialdistance < 0) { thiscoupler.Dist = safe_clamp(newdistance, thiscoupler.has_adapter() ? 0 : -thiscoupler.DmaxB, thiscoupler.DmaxC); @@ -314,7 +314,7 @@ double TMoverParameters::CouplerForce(int const End, double dt) double BetaAvg = 0; double Fmax = 0; - if (thiscoupler.CouplingFlag == coupling::faux) + if (thiscoupler.CouplingFlag == Coupling::none) { BetaAvg = thiscoupler.beta; @@ -374,7 +374,7 @@ double TMoverParameters::CouplerForce(int const End, double dt) } } - if (thiscoupler.CouplingFlag != coupling::faux) + if (thiscoupler.CouplingFlag != Coupling::none) { // uzgadnianie prawa Newtona, on the coupler of the other vehicle this one is coupled with, along that vehicle's // axis: turned around once more when the vehicles face each other @@ -425,7 +425,7 @@ void TMoverParameters::automatic_coupling(int const End, TMoverParameters &Other auto &thiscoupler{Couplers[End]}; auto &othercoupler{Other.Couplers[OtherEnd]}; - if (thiscoupler.type() != TCouplerType::Automatic || thiscoupler.type() != othercoupler.type() || thiscoupler.CouplingFlag != coupling::faux || false == thiscoupler.AutomaticCouplingAllowed || + if (thiscoupler.type() != TCouplerType::Automatic || thiscoupler.type() != othercoupler.type() || thiscoupler.CouplingFlag != Coupling::none || false == thiscoupler.AutomaticCouplingAllowed || false == othercoupler.AutomaticCouplingAllowed) { return; @@ -440,7 +440,7 @@ void TMoverParameters::automatic_coupling(int const End, TMoverParameters &Other // potentially exclude incompatible control coupling if (thiscoupler.control_type != othercoupler.control_type) { - couplingtype &= ~coupling::control; + couplingtype = couplingtype.Without(Coupling::control); } couplingtype = CompatibleCoupling(End, Other, OtherEnd, couplingtype); @@ -503,7 +503,7 @@ double TMoverParameters::coupler_force_physical(int const End, double const dt) auto const gap{Neighbours[End].distance + (End == end::front ? othervehiclemove - dMoveLen : dMoveLen - othervehiclemove)}; // the gap opens up when the front end falls behind the vehicle ahead of it, or the rear end runs ahead of the one behind auto const gaprate{CouplerVelocityDifference(End, *othervehicle, otherend) * DirF(End)}; - auto const coupled{thiscoupler.CouplingFlag != coupling::faux}; + auto const coupled{thiscoupler.CouplingFlag != Coupling::none}; auto const adapter{thiscoupler.has_adapter() || othercoupler.has_adapter()}; if (false == coupled && Neighbours[End].distance > 0.05) @@ -539,7 +539,7 @@ double TMoverParameters::coupler_force_physical(int const End, double const dt) // tension pulls this vehicle towards the other one auto const force{result.force * -DirF(End)}; - if (thiscoupler.CouplingFlag != coupling::faux) + if (thiscoupler.CouplingFlag != Coupling::none) { // uzgadnianie prawa Newtona, as in CouplerForce() othercoupler.CForce = -force * DirPatch(End, otherend); diff --git a/physics/mover/diesel.cpp b/physics/mover/diesel.cpp index 1548f8885..e2e95959f 100644 --- a/physics/mover/diesel.cpp +++ b/physics/mover/diesel.cpp @@ -124,7 +124,7 @@ bool TMoverParameters::WaterPumpBreakerSwitch(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext(VehicleCommand::waterPumpBreakerSwitch, WaterPump.breaker ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::waterPumpBreakerSwitch, WaterPump.breaker ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return WaterPump.breaker != initialstate; @@ -146,7 +146,7 @@ bool TMoverParameters::WaterPumpSwitch(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext(VehicleCommand::waterPumpSwitch, WaterPump.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::waterPumpSwitch, WaterPump.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return WaterPump.is_enabled != initialstate; @@ -168,7 +168,7 @@ bool TMoverParameters::WaterPumpSwitchOff(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext(VehicleCommand::waterPumpSwitchOff, WaterPump.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::waterPumpSwitchOff, WaterPump.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return WaterPump.is_disabled != initialstate; @@ -189,7 +189,7 @@ bool TMoverParameters::WaterHeaterBreakerSwitch(bool State, range_t const Notify if (Notify != range_t::local) { - SendCtrlToNext(VehicleCommand::waterHeaterBreakerSwitch, WaterHeater.breaker ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::waterHeaterBreakerSwitch, WaterHeater.breaker ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return WaterHeater.breaker != initialstate; @@ -210,7 +210,7 @@ bool TMoverParameters::WaterHeaterSwitch(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext(VehicleCommand::waterHeaterSwitch, WaterHeater.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::waterHeaterSwitch, WaterHeater.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return WaterHeater.is_enabled != initialstate; @@ -232,7 +232,7 @@ bool TMoverParameters::WaterCircuitsLinkSwitch(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext(VehicleCommand::waterCircuitsLinkSwitch, WaterCircuitsLink ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::waterCircuitsLinkSwitch, WaterCircuitsLink ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return WaterCircuitsLink != initialstate; @@ -254,7 +254,7 @@ bool TMoverParameters::FuelPumpSwitch(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext(VehicleCommand::fuelPumpSwitch, FuelPump.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::fuelPumpSwitch, FuelPump.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return FuelPump.is_enabled != initialstate; @@ -275,7 +275,7 @@ bool TMoverParameters::FuelPumpSwitchOff(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext(VehicleCommand::fuelPumpSwitchOff, FuelPump.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::fuelPumpSwitchOff, FuelPump.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return FuelPump.is_disabled != initialstate; @@ -297,7 +297,7 @@ bool TMoverParameters::OilPumpSwitch(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext(VehicleCommand::oilPumpSwitch, OilPump.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::oilPumpSwitch, OilPump.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return OilPump.is_enabled != initialstate; @@ -318,7 +318,7 @@ bool TMoverParameters::OilPumpSwitchOff(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext(VehicleCommand::oilPumpSwitchOff, OilPump.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::oilPumpSwitchOff, OilPump.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return OilPump.is_disabled != initialstate; diff --git a/physics/mover/doors.cpp b/physics/mover/doors.cpp index 28b2e379a..923496d4d 100644 --- a/physics/mover/doors.cpp +++ b/physics/mover/doors.cpp @@ -199,7 +199,7 @@ bool TMoverParameters::PermitDoorStep(bool const State, range_t const Notify) if (Notify != range_t::local) { // wysłanie wyłączenia do pozostałych? - SendCtrlToNext(VehicleCommand::doorStep, State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::doorStep, State == true ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return Doors.step_enabled != initialstate; @@ -220,7 +220,7 @@ bool TMoverParameters::PermitDoors(side const Door, bool const State, range_t co * (Door == (CabActive > 0 ? side::left : side::right) ? // 1=lewe, 2=prawe (swap if reversed) 1 : 2), - CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return Doors.instances[Door].open_permit != initialstate; @@ -245,7 +245,7 @@ bool TMoverParameters::ChangeDoorControlMode(bool const State, range_t const Not if (Notify != range_t::local) { // wysłanie wyłączenia do pozostałych? - SendCtrlToNext(VehicleCommand::doorMode, State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::doorMode, State == true ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } if (true == State) @@ -296,7 +296,7 @@ bool TMoverParameters::OperateDoors(side const Door, bool const State, range_t c Door == (CabActive > 0 ? side::left : side::right) ? // 1=lewe, 2=prawe (swap if reversed) 1 : 2, - CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return result; @@ -312,7 +312,7 @@ bool TMoverParameters::LockDoors(bool const State, range_t const Notify) if (Notify != range_t::local) { // wysłanie wyłączenia do pozostałych? - SendCtrlToNext(VehicleCommand::doorLock, State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::doorLock, State == true ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return Doors.lock_enabled != initialstate; @@ -332,7 +332,7 @@ bool TMoverParameters::signal_departure(bool const State, range_t const Notify) if (Notify != range_t::local) { // wysłanie wyłączenia do pozostałych? - SendCtrlToNext(VehicleCommand::departureSignal, State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::departureSignal, State == true ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return true; diff --git a/physics/mover/electrics.cpp b/physics/mover/electrics.cpp index 9127e00cb..ada624e72 100644 --- a/physics/mover/electrics.cpp +++ b/physics/mover/electrics.cpp @@ -344,36 +344,36 @@ void TMoverParameters::LowVoltagePowerCheck(double const /*Deltatime*/) } } -void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling const Coupling) +void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, Coupling const kind) { - if (Coupling != coupling::highvoltage && Coupling != coupling::power110v && Coupling != coupling::power24v) + if (kind != Coupling::highVoltage && kind != Coupling::power110v && kind != Coupling::power24v) { // only power couplings carry voltage return; } - auto const localvoltage{LocalPowerVoltage(Coupling)}; + auto const localvoltage{LocalPowerVoltage(kind)}; auto const abslocalvoltage{std::abs(localvoltage)}; auto const localpowersource{(abslocalvoltage > 1.0)}; // przekazywanie napiec - PowerCouplersVoltage(Coupling, abslocalvoltage, localpowersource); + PowerCouplersVoltage(kind, abslocalvoltage, localpowersource); // przekazywanie pradow - PowerCouplersCurrent(Coupling, localpowersource); + PowerCouplersCurrent(kind, localpowersource); } // the current the vehicle draws from the circuit of the power coupling given -double *TMoverParameters::PowerCircuitCurrent(coupling const Coupling) +double *TMoverParameters::PowerCircuitCurrent(Coupling const kind) { - switch (Coupling) + switch (kind) { - case coupling::highvoltage: + case Coupling::highVoltage: return &TotalCurrent; - case coupling::power110v: + case Coupling::power110v: return &PowerCircuits[1].second; - case coupling::power24v: + case Coupling::power24v: return &PowerCircuits[0].second; default: return nullptr; @@ -381,16 +381,16 @@ double *TMoverParameters::PowerCircuitCurrent(coupling const Coupling) } // the voltage of the vehicle's own source for the coupling given; notes the low voltage circuits' too -double TMoverParameters::LocalPowerVoltage(coupling const Coupling) +double TMoverParameters::LocalPowerVoltage(Coupling const kind) { auto localvoltage{0.0}; // local power sources // the results could be kept in the PowerCircuit fields - switch (Coupling) + switch (kind) { - case coupling::highvoltage: + case Coupling::highVoltage: { // heating power sources if (Heating) @@ -428,7 +428,7 @@ double TMoverParameters::LocalPowerVoltage(coupling const Coupling) break; } - case coupling::power110v: + case Coupling::power110v: { if (ConverterFlag) { @@ -439,7 +439,7 @@ double TMoverParameters::LocalPowerVoltage(coupling const Coupling) break; } - case coupling::power24v: + case Coupling::power24v: { if (Battery) { @@ -460,9 +460,9 @@ double TMoverParameters::LocalPowerVoltage(coupling const Coupling) } // the voltage passed through the vehicle to the coupler at its other end, from the coupled vehicle or its own source -void TMoverParameters::PowerCouplersVoltage(coupling const Coupling, double const abslocalvoltage, bool const localpowersource) +void TMoverParameters::PowerCouplersVoltage(Coupling const kind, double const abslocalvoltage, bool const localpowersource) { - if (Couplers[end::front].power(Coupling) == nullptr) + if (Couplers[end::front].power(kind) == nullptr) { // not a power coupling, there's no voltage to pass return; @@ -477,29 +477,29 @@ void TMoverParameters::PowerCouplersVoltage(coupling const Coupling, double cons bool oppositecouplingispresent; bool localpowerexportisenabled; - switch (Coupling) + switch (kind) { - case coupling::highvoltage: + case Coupling::highVoltage: { - auto const oppositehighvoltagecoupling{(oppositecoupler.CouplingFlag & coupling::highvoltage) != 0}; - auto const oppositeheatingcoupling{(oppositecoupler.CouplingFlag & coupling::heating) != 0}; + auto const oppositehighvoltagecoupling{oppositecoupler.CouplingFlag.HasAny(Coupling::highVoltage)}; + auto const oppositeheatingcoupling{oppositecoupler.CouplingFlag.HasAny(Coupling::heating)}; oppositecouplingispresent = oppositehighvoltagecoupling || oppositeheatingcoupling; localpowerexportisenabled = oppositehighvoltagecoupling || (oppositeheatingcoupling && localpowersource && Heating); break; } - case coupling::power110v: + case Coupling::power110v: { - oppositecouplingispresent = TestFlag(oppositecoupler.CouplingFlag, oppositecoupler.PowerCoupling) && (oppositecoupler.PowerFlag & coupling::power110v) != 0; + oppositecouplingispresent = oppositecoupler.CouplingFlag.HasAll(oppositecoupler.PowerCoupling) && oppositecoupler.PowerFlag.HasAny(Coupling::power110v); localpowerexportisenabled = oppositecouplingispresent; break; } - case coupling::power24v: + case Coupling::power24v: { - oppositecouplingispresent = TestFlag(oppositecoupler.CouplingFlag, oppositecoupler.PowerCoupling) && (oppositecoupler.PowerFlag & coupling::power24v) != 0; + oppositecouplingispresent = oppositecoupler.CouplingFlag.HasAll(oppositecoupler.PowerCoupling) && oppositecoupler.PowerFlag.HasAny(Coupling::power24v); localpowerexportisenabled = oppositecouplingispresent; break; } @@ -510,8 +510,8 @@ void TMoverParameters::PowerCouplersVoltage(coupling const Coupling, double cons } } - auto const *coupling = thiscoupler.power(Coupling); - auto *oppositecoupling = oppositecoupler.power(Coupling); + auto const *coupling = thiscoupler.power(kind); + auto *oppositecoupling = oppositecoupler.power(kind); // start with base voltage oppositecoupling->voltage = abslocalvoltage; @@ -521,7 +521,7 @@ void TMoverParameters::PowerCouplersVoltage(coupling const Coupling, double cons if (thiscoupler.Connected != nullptr) { auto const &connectedcoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr]}; - auto const *connectedcoupling = connectedcoupler.power(Coupling); + auto const *connectedcoupling = connectedcoupler.power(kind); auto const connectedvoltage{(connectedcoupling->is_live ? connectedcoupling->voltage : 0.0)}; oppositecoupling->voltage = std::max(oppositecoupling->voltage, connectedvoltage - coupling->current * 0.02); oppositecoupling->is_live = connectedvoltage > 0.1 && oppositecouplingispresent; @@ -536,11 +536,11 @@ void TMoverParameters::PowerCouplersVoltage(coupling const Coupling, double cons } // the current drawn through the couplers, shared by their voltages, or added to the vehicle's own -void TMoverParameters::PowerCouplersCurrent(coupling const Coupling, bool const localpowersource) +void TMoverParameters::PowerCouplersCurrent(Coupling const kind, bool const localpowersource) { - auto const *frontcoupling{Couplers[end::front].power(Coupling)}; - auto const *rearcoupling{Couplers[end::rear].power(Coupling)}; - auto *totalcurrent{PowerCircuitCurrent(Coupling)}; + auto const *frontcoupling{Couplers[end::front].power(kind)}; + auto const *rearcoupling{Couplers[end::rear].power(kind)}; + auto *totalcurrent{PowerCircuitCurrent(kind)}; if (frontcoupling == nullptr || rearcoupling == nullptr || totalcurrent == nullptr) { // not a power coupling, there's no current to share @@ -550,7 +550,7 @@ void TMoverParameters::PowerCouplersCurrent(coupling const Coupling, bool const for (auto &thiscoupler : Couplers) { - auto *coupling = thiscoupler.power(Coupling); + auto *coupling = thiscoupler.power(kind); coupling->current = 0.0; @@ -560,8 +560,8 @@ void TMoverParameters::PowerCouplersCurrent(coupling const Coupling, bool const } auto const &connectedothercoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr == end::front ? end::rear : end::front]}; - auto const *connectedothercoupling = connectedothercoupler.power(Coupling); - auto const extracurrent = Coupling == coupling::highvoltage ? std::abs(Itot) * IsVehicleEIMBrakingFactor() : 0.0; + auto const *connectedothercoupling = connectedothercoupler.power(kind); + auto const extracurrent = kind == Coupling::highVoltage ? std::abs(Itot) * IsVehicleEIMBrakingFactor() : 0.0; if (false == localpowersource) { @@ -862,8 +862,8 @@ bool TMoverParameters::BatterySwitch(bool State, range_t const Notify) // switching batteries does not require activation if (Notify != local) { - SendCtrlToNext(VehicleCommand::batterySwitch, State ? 1 : 0, 1, Notify == unit ? coupling::control | coupling::permanent : coupling::control); - SendCtrlToNext(VehicleCommand::batterySwitch, State ? 1 : 0, -1, Notify == unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::batterySwitch, State ? 1 : 0, 1, Notify == unit ? Coupling::control | Coupling::permanent : Coupling::control); + SendCtrlToNext(VehicleCommand::batterySwitch, State ? 1 : 0, -1, Notify == unit ? Coupling::control | Coupling::permanent : Coupling::control); } return Battery != initialstate; @@ -884,7 +884,7 @@ bool TMoverParameters::CompartmentLightsSwitch(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext(VehicleCommand::compartmentLightsSwitch, CompartmentLights.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::compartmentLightsSwitch, CompartmentLights.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return CompartmentLights.is_enabled != initialstate; @@ -906,7 +906,7 @@ bool TMoverParameters::CompartmentLightsSwitchOff(bool State, range_t const Noti if (Notify != range_t::local) { - SendCtrlToNext(VehicleCommand::compartmentLightsSwitchOff, CompartmentLights.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::compartmentLightsSwitchOff, CompartmentLights.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return CompartmentLights.is_disabled != initialstate; @@ -927,7 +927,7 @@ bool TMoverParameters::MainSwitch(bool const State, range_t const Notify) { // pass the command to other vehicles // TBD: pass the requested state, or the actual state? - SendCtrlToNext(VehicleCommand::mainSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::mainSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return (Mains || dizel_startup) != initialstate; @@ -1038,7 +1038,7 @@ bool TMoverParameters::ConverterSwitch(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext(VehicleCommand::converterSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::converterSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return ConverterAllow != initialstate; @@ -1055,7 +1055,7 @@ bool TMoverParameters::HeatingSwitch(bool const State, range_t const Notify) { // pass the command to other vehicles // TBD: pass the requested state, or the actual state? - SendCtrlToNext(VehicleCommand::heatingSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::heatingSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return HeatingAllow != initialstate; @@ -1081,7 +1081,7 @@ bool TMoverParameters::GensetSwitch(bool const State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext(VehicleCommand::gensetSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::gensetSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return Genset.is_enabled != initialstate; @@ -1207,7 +1207,7 @@ bool TMoverParameters::OperatePantographsValve(operation_t const State, range_t if (Notify != range_t::local) { - SendCtrlToNext(VehicleCommand::pantographsValve, static_cast(State), CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::pantographsValve, static_cast(State), CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return true; @@ -1271,7 +1271,7 @@ bool TMoverParameters::OperatePantographValve(end const End, operation_t const S // HACK: pack the state, pantograph index and sender cab into 8-bit value // with high bit storing front/rear pantograph, and 7th bit storing sender cab static_cast(0x80 * (End == end::front ? 0 : 1) + 0x40 * (CabActive != -1 ? 1 : 0) + static_cast(State)), CabActive, - Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return true; @@ -1286,7 +1286,7 @@ bool TMoverParameters::DropAllPantographs(bool const State, range_t const Notify if (Notify != range_t::local) { - SendCtrlToNext(VehicleCommand::pantographsAllDown, State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::pantographsAllDown, State ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return State != initialstate; @@ -1296,7 +1296,7 @@ bool TMoverParameters::DropAllPantographs(bool const State, range_t const Notify // Q: 20160709 // Funkcja zwracajaca napiecie dla calego skladu, przydatna dla EZT // ************************************************************************************************* -double TMoverParameters::GetTrainsetVoltage(int const Coupling) const +double TMoverParameters::GetTrainsetVoltage(CouplingSet const couplings) const { // ABu: funkcja zwracajaca napiecie dla calego skladu, przydatna dla EZT // TBD, TODO: call once per vehicle update, return cached results? std::array voltages{0.0, 0.0}; @@ -1307,13 +1307,13 @@ double TMoverParameters::GetTrainsetVoltage(int const Coupling) const continue; } auto const &thiscoupler{Couplers[end]}; - if (auto const fullcoupling{thiscoupler.CouplingFlag | (TestFlag(thiscoupler.CouplingFlag, thiscoupler.PowerCoupling) ? thiscoupler.PowerFlag : 0)}; (fullcoupling & Coupling) == 0) + if (auto const fullcoupling{thiscoupler.CouplingFlag | (thiscoupler.CouplingFlag.HasAll(thiscoupler.PowerCoupling) ? thiscoupler.PowerFlag : CouplingSet{})}; false == fullcoupling.HasAny(couplings)) { continue; } - auto const *connectedpowercoupling = (Coupling & (coupling::highvoltage | coupling::heating)) != 0 ? &thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr].power_high : - (Coupling & coupling::power110v) != 0 ? &thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr].power_110v : - (Coupling & coupling::power24v) != 0 ? &thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr].power_24v : + auto const *connectedpowercoupling = couplings.HasAny(Coupling::highVoltage | Coupling::heating) ? &thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr].power_high : + couplings.HasAny(Coupling::power110v) ? &thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr].power_110v : + couplings.HasAny(Coupling::power24v) ? &thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr].power_24v : nullptr; if (connectedpowercoupling != nullptr && connectedpowercoupling->is_live) { @@ -1326,7 +1326,7 @@ double TMoverParameters::GetTrainsetVoltage(int const Coupling) const double TMoverParameters::GetTrainsetHighVoltage() const { - return std::max(GetTrainsetVoltage(coupling::highvoltage), HeatingAllow ? GetTrainsetVoltage(coupling::heating) : 0.0); + return std::max(GetTrainsetVoltage(Coupling::highVoltage), HeatingAllow ? GetTrainsetVoltage(Coupling::heating) : 0.0); } int TMoverParameters::clampDimmerPosition(int const Position) const diff --git a/physics/mover/fizsections.cpp b/physics/mover/fizsections.cpp index 193356ab1..8bf7673c6 100644 --- a/physics/mover/fizsections.cpp +++ b/physics/mover/fizsections.cpp @@ -578,14 +578,20 @@ void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Inde extract_value(thiscoupler->DmaxB, "DmaxB", line, ""); extract_value(thiscoupler->FmaxB, "FmaxB", line, ""); extract_value(thiscoupler->beta, "beta", line, ""); - extract_value(thiscoupler->AutomaticCouplingFlag, "AutomaticFlag", line, ""); - extract_value(thiscoupler->AllowedFlag, "AllowedFlag", line, ""); - if (thiscoupler->AllowedFlag < 0) - { - thiscoupler->AllowedFlag = -thiscoupler->AllowedFlag | coupling::permanent; - } - extract_value(thiscoupler->PowerCoupling, "PowerCoupling", line, ""); - extract_value(thiscoupler->PowerFlag, "PowerFlag", line, ""); + // the sets are numbers in the definition, the sums of the numbers of the kinds of coupling + auto automaticflag{thiscoupler->AutomaticCouplingFlag.Bits()}; + extract_value(automaticflag, "AutomaticFlag", line, ""); + thiscoupler->AutomaticCouplingFlag = CouplingSet::FromBits(automaticflag); + auto allowedflag{thiscoupler->AllowedFlag.Bits()}; + extract_value(allowedflag, "AllowedFlag", line, ""); + // negative: the coupling is permanent besides + thiscoupler->AllowedFlag = allowedflag < 0 ? CouplingSet::FromBits(-allowedflag) | Coupling::permanent : CouplingSet::FromBits(allowedflag); + auto powercoupling{thiscoupler->PowerCoupling.Bits()}; + extract_value(powercoupling, "PowerCoupling", line, ""); + thiscoupler->PowerCoupling = CouplingSet::FromBits(powercoupling); + auto powerflag{thiscoupler->PowerFlag.Bits()}; + extract_value(powerflag, "PowerFlag", line, ""); + thiscoupler->PowerFlag = CouplingSet::FromBits(powerflag); extract_value(thiscoupler->control_type, "ControlType", line, ""); if (thiscoupler->CouplerType != TCouplerType::NoCoupler && thiscoupler->CouplerType != TCouplerType::Bare && thiscoupler->CouplerType != TCouplerType::Articulated) diff --git a/physics/mover/mover.cpp b/physics/mover/mover.cpp index 5a86a41ac..fa6f20c1e 100644 --- a/physics/mover/mover.cpp +++ b/physics/mover/mover.cpp @@ -144,8 +144,8 @@ TMoverParameters::TMoverParameters(double VelInitial, std::string const &TypeNam for (auto &couplerentry : Couplers) { - couplerentry.AllowedFlag = 3; // domyślnie hak i hamulec, inne trzeba włączyć jawnie w FIZ - couplerentry.CouplingFlag = 0; + couplerentry.AllowedFlag = Coupling::coupler | Coupling::brakeHose; // domyślnie hak i hamulec, inne trzeba włączyć jawnie w FIZ + couplerentry.CouplingFlag = {}; couplerentry.Connected = nullptr; couplerentry.ConnectedNr = 0; // Ra: to nie ma znaczenia jak nie podłączony couplerentry.Render = false; @@ -193,7 +193,7 @@ void TMoverParameters::change_train_velocity(double const Change) { auto const &coupler{vehicle->Couplers[end]}; auto *other{coupler.Connected}; - if (other == nullptr || coupler.CouplingFlag == coupling::faux || std::any_of(train.begin(), train.end(), [other](auto const &Entry) { return Entry.first == other; })) + if (other == nullptr || coupler.CouplingFlag == Coupling::none || std::any_of(train.begin(), train.end(), [other](auto const &Entry) { return Entry.first == other; })) { continue; } @@ -522,11 +522,11 @@ void TMoverParameters::compute_movement_(double const Deltatime) UpdateBatteryVoltage(Deltatime); UpdateScndPipePressure(Deltatime); // druga rurka, youBy - if ((DCEMUED_CC & 1) != 0 && (Couplers[end::front].CouplingFlag & coupling::control) != 0) + if ((DCEMUED_CC & 1) != 0 && Couplers[end::front].CouplingFlag.HasAny(Coupling::control)) { DynamicBrakeEMUStatus &= Couplers[end::front].Connected->DynamicBrakeEMUStatus; } - if ((DCEMUED_CC & 2) != 0 && (Couplers[end::rear].CouplingFlag & coupling::control) != 0) + if ((DCEMUED_CC & 2) != 0 && Couplers[end::rear].CouplingFlag.HasAny(Coupling::control)) { DynamicBrakeEMUStatus &= Couplers[end::rear].Connected->DynamicBrakeEMUStatus; } @@ -542,13 +542,13 @@ void TMoverParameters::compute_movement_(double const Deltatime) m_plc.update(Deltatime); - PowerCouplersCheck(Deltatime, coupling::highvoltage); - PowerCouplersCheck(Deltatime, coupling::power110v); - PowerCouplersCheck(Deltatime, coupling::power24v); + PowerCouplersCheck(Deltatime, Coupling::highVoltage); + PowerCouplersCheck(Deltatime, Coupling::power110v); + PowerCouplersCheck(Deltatime, Coupling::power24v); - Power24vVoltage = std::max(PowerCircuits[0].first, GetTrainsetVoltage(coupling::power24v)); + Power24vVoltage = std::max(PowerCircuits[0].first, GetTrainsetVoltage(Coupling::power24v)); Power24vIsAvailable = Power24vVoltage > 0; - Power110vIsAvailable = PowerCircuits[1].first > 0 || GetTrainsetVoltage(coupling::power110v) > 0; + Power110vIsAvailable = PowerCircuits[1].first > 0 || GetTrainsetVoltage(Coupling::power110v) > 0; } // ************************************************************************************************* @@ -671,7 +671,7 @@ bool TMoverParameters::Sandbox(bool const State, range_t const Notify) if (Notify != range_t::local) { // if requested pass the command on - auto const couplingtype = Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control; + auto const couplingtype = Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control; if (State == true) { @@ -694,7 +694,7 @@ bool TMoverParameters::Sandbox(bool const State, range_t const Notify) // ************************************************************************************************* bool TMoverParameters::SandboxAutoAllow(bool State) { - // SendCtrlToNext(VehicleCommand::sandboxAutoAllow, int(State), CabActive, ctrain_controll); + // SendCtrlToNext(VehicleCommand::sandboxAutoAllow, int(State), CabActive, Coupling::control); if (SandDoseAutoAllow != State) { diff --git a/physics/mover/pneumatics.cpp b/physics/mover/pneumatics.cpp index 5ed05fbd5..c4519d5fb 100644 --- a/physics/mover/pneumatics.cpp +++ b/physics/mover/pneumatics.cpp @@ -248,7 +248,7 @@ bool TMoverParameters::SpringBrakeActivate(bool State) { if (Power24vIsAvailable || Power110vIsAvailable) { - SendCtrlToNext(VehicleCommand::springBrakeActivate, int(State), CabActive, SpringBrake.MultiTractionCoupler); + SendCtrlToNext(VehicleCommand::springBrakeActivate, int(State), CabActive, CouplingSet::FromBits(SpringBrake.MultiTractionCoupler)); if (SpringBrake.Activate != State) { @@ -323,7 +323,7 @@ bool TMoverParameters::CompressorSwitch(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext(VehicleCommand::compressorSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::compressorSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return CompressorAllow != initialstate; @@ -338,7 +338,7 @@ bool TMoverParameters::ChangeCompressorPreset(int const State, range_t const Not if (Notify != range_t::local) { - SendCtrlToNext(VehicleCommand::compressorPreset, State, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::compressorPreset, State, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return CompressorListPos != initialstate; @@ -828,8 +828,8 @@ void TMoverParameters::CompressorCheck(double dt) // NOTE: this is crude implementation, limited only to adjacent vehicles // TODO: re-implement when a more elegant/flexible system is in place auto const coupledgovernorlock{ - (Couplers[end::rear].Connected != nullptr && true == TestFlag(Couplers[end::rear].CouplingFlag, coupling::permanent) && Couplers[end::rear].Connected->CompressorGovernorLock) || - (Couplers[end::front].Connected != nullptr && true == TestFlag(Couplers[end::front].CouplingFlag, coupling::permanent) && Couplers[end::front].Connected->CompressorGovernorLock)}; + (Couplers[end::rear].Connected != nullptr && true == Couplers[end::rear].CouplingFlag.HasAll(Coupling::permanent) && Couplers[end::rear].Connected->CompressorGovernorLock) || + (Couplers[end::front].Connected != nullptr && true == Couplers[end::front].CouplingFlag.HasAll(Coupling::permanent) && Couplers[end::front].Connected->CompressorGovernorLock)}; auto const governorlock{CompressorGovernorLock || coupledgovernorlock}; auto const compressorflag{CompressorFlag}; @@ -1141,7 +1141,7 @@ void TMoverParameters::UpdateDistributorSettings() for (auto const &couplerentry : Couplers) // nie podoba mi się to rozwiązanie, chyba trzeba // dodać jakiś wpis do fizyki na to - if (et41or42(TrainType) && couplerentry.Connected != nullptr && et41or42(couplerentry.Connected->TrainType) && (couplerentry.CouplingFlag & 36) == 36) + if (et41or42(TrainType) && couplerentry.Connected != nullptr && et41or42(couplerentry.Connected->TrainType) && couplerentry.CouplingFlag.HasAll(Coupling::control | Coupling::mainHose)) LocBrakePress = std::max(couplerentry.Connected->LocHandle->GetCP(), LocBrakePress); // if ((DynamicBrakeFlag) && (EngineType == ElectricInductionMotor)) @@ -1349,7 +1349,7 @@ double TMoverParameters::GetDVc(double dt) dv1 = 0; dv2 = 0; // sprzeg 1 - if (Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_pneumatic)) + if (Couplers[0].Connected != nullptr && Couplers[0].CouplingFlag.HasAll(Coupling::brakeHose)) { //*0.85 c = Couplers[0].Connected; // skrot //0.08 //e/D * L/D = e/D^2 * L dv1 = 0.5 * dt * PF(PipePress, neighbour_pipe_pressure(*c, c->PipePress, *c->Pipe), Spg / (1.0 + 0.015 / Spg * Dim.L)); @@ -1358,7 +1358,7 @@ double TMoverParameters::GetDVc(double dt) c->switch_physics(true, wake_cause::mainpipe); } // sprzeg 2 - if (Couplers[1].Connected != nullptr && TestFlag(Couplers[1].CouplingFlag, ctrain_pneumatic)) + if (Couplers[1].Connected != nullptr && Couplers[1].CouplingFlag.HasAll(Coupling::brakeHose)) { c = Couplers[1].Connected; // skrot dv2 = 0.5 * dt * PF(PipePress, neighbour_pipe_pressure(*c, c->PipePress, *c->Pipe), Spg / (1.0 + 0.015 / Spg * Dim.L)); @@ -1367,8 +1367,8 @@ double TMoverParameters::GetDVc(double dt) c->switch_physics(true, wake_cause::mainpipe); } // if ((Couplers[1].Connected != NULL) && (Couplers[0].Connected != NULL)) - // if ((TestFlag(Couplers[0].CouplingFlag, ctrain_pneumatic)) && - // (TestFlag(Couplers[1].CouplingFlag, ctrain_pneumatic))) + // if ((Couplers[0].CouplingFlag.HasAll(Coupling::brakeHose)) && + // (Couplers[1].CouplingFlag.HasAll(Coupling::brakeHose))) // { // dV = 0.05 * dt * PF(Couplers[0].Connected->PipePress, Couplers[1].Connected->PipePress, // (Spg * 0.85) / (1 + 0.03 * Dim.L)) * @@ -1392,7 +1392,7 @@ double TMoverParameters::GetScndDVc(double dt) double dv2 = 0; // sprzeg 1 - if (Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic)) + if (Couplers[0].Connected != nullptr && Couplers[0].CouplingFlag.HasAll(Coupling::mainHose)) { c = Couplers[0].Connected; // skrot dv1 = 0.5 * dt * PF(ScndPipePress, neighbour_pipe_pressure(*c, c->ScndPipePress, *c->Pipe2), Spz * 0.75); @@ -1401,7 +1401,7 @@ double TMoverParameters::GetScndDVc(double dt) c->switch_physics(true, wake_cause::scndpipe); } // sprzeg 2 - if (Couplers[1].Connected != nullptr && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) + if (Couplers[1].Connected != nullptr && Couplers[1].CouplingFlag.HasAll(Coupling::mainHose)) { c = Couplers[1].Connected; // skrot dv2 = 0.5 * dt * PF(ScndPipePress, neighbour_pipe_pressure(*c, c->ScndPipePress, *c->Pipe2), Spz * 0.75); @@ -1409,7 +1409,7 @@ double TMoverParameters::GetScndDVc(double dt) if (pipe_wakes(dv2, ScndPipePress, *c->Pipe2)) c->switch_physics(true, wake_cause::scndpipe); } - if (Couplers[1].Connected != nullptr && Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic) && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) + if (Couplers[1].Connected != nullptr && Couplers[0].Connected != nullptr && Couplers[0].CouplingFlag.HasAll(Coupling::mainHose) && Couplers[1].CouplingFlag.HasAll(Coupling::mainHose)) { double const dV = 0.00025 * dt * PF(Couplers[0].Connected->ScndPipePress, Couplers[1].Connected->ScndPipePress, Spz * 0.25); Couplers[0].Connected->Pipe2->Flow(+dV); @@ -1427,7 +1427,7 @@ struct train_pipe std::shared_ptr TMoverParameters::*reservoir; double TMoverParameters::*pressure; bool TMoverParameters::*pending; // the vehicle stepped the pipe, the exchange through its hoses is yet to come - int hose; // the coupling flag of the pipe's hose + CouplingSet hose; // the coupling of the pipe's hose double (TMoverParameters::*exchange)(double); // the air the hoses carry in a step, the neighbours' share sent to them double (*area)(TMoverParameters const &); // the cross-section of the hose, as the exchange takes it }; @@ -1436,14 +1436,14 @@ struct train_pipe train_pipe const brake_pipe{&TMoverParameters::Pipe, &TMoverParameters::PipePress, &TMoverParameters::PipeCouplersPending, - ctrain_pneumatic, + Coupling::brakeHose, &TMoverParameters::GetDVc, [](TMoverParameters const &Vehicle) { return Vehicle.Spg / (1.0 + 0.015 / Vehicle.Spg * Vehicle.Dim.L); }}; // the main reservoir pipe, GetScndDVc() train_pipe const main_reservoir_pipe{&TMoverParameters::Pipe2, &TMoverParameters::ScndPipePress, &TMoverParameters::ScndPipeCouplersPending, - ctrain_scndpneumatic, + Coupling::mainHose, &TMoverParameters::GetScndDVc, [](TMoverParameters const &) { return 0.5067 * 0.75; }}; @@ -1456,7 +1456,7 @@ int hose_substeps(TMoverParameters const &Vehicle, train_pipe const &Pipe, doubl auto const capacity{(Vehicle.*Pipe.reservoir)->GetCap()}; for (auto const &hose : Vehicle.Couplers) { - if (hose.Connected == nullptr || false == TestFlag(hose.CouplingFlag, Pipe.hose)) + if (hose.Connected == nullptr || false == hose.CouplingFlag.HasAll(Pipe.hose)) { continue; } @@ -1509,7 +1509,7 @@ std::vector hose_trains(std::vector const &Vehi stack.pop_back(); for (auto const &hose : vehicle.Couplers) { - if (hose.Connected == nullptr || false == TestFlag(hose.CouplingFlag, Pipe.hose)) + if (hose.Connected == nullptr || false == hose.CouplingFlag.HasAll(Pipe.hose)) { continue; } diff --git a/physics/mover/setup.cpp b/physics/mover/setup.cpp index 18a3abcea..29db46d97 100644 --- a/physics/mover/setup.cpp +++ b/physics/mover/setup.cpp @@ -410,7 +410,7 @@ double TMoverParameters::InitialScndPipePress(double const HosePressure) const { return CompressedVolume / VeselVolume; } - if ((Couplers[end::front].AllowedFlag & coupling::mainhose) != 0 || (Couplers[end::rear].AllowedFlag & coupling::mainhose) != 0) + if (Couplers[end::front].AllowedFlag.HasAny(Coupling::mainHose) || Couplers[end::rear].AllowedFlag.HasAny(Coupling::mainHose)) { return HosePressure; } diff --git a/physics/mover/traction.cpp b/physics/mover/traction.cpp index 745b51d0e..05b52bbc3 100644 --- a/physics/mover/traction.cpp +++ b/physics/mover/traction.cpp @@ -303,12 +303,12 @@ double TMoverParameters::ShowEngineRotation(int VehN) const return std::abs(enrot); case 2: for (b = 0; b <= 1; ++b) - if (TestFlag(Couplers[b].CouplingFlag, coupling::control) && Couplers[b].Connected->Power > 0.01) + if (Couplers[b].CouplingFlag.HasAll(Coupling::control) && Couplers[b].Connected->Power > 0.01) return fabs(Couplers[b].Connected->enrot); break; case 3: // to nie uwzględnia ewentualnego odwrócenia pojazdu w środku for (b = 0; b <= 1; ++b) - if (TestFlag(Couplers[b].CouplingFlag, coupling::control) && Couplers[b].Connected->Power > 0.01 && TestFlag(Couplers[b].Connected->Couplers[b].CouplingFlag, coupling::control) && Couplers[b].Connected->Couplers[b].Connected->Power > 0.01) + if (Couplers[b].CouplingFlag.HasAll(Coupling::control) && Couplers[b].Connected->Power > 0.01 && Couplers[b].Connected->Couplers[b].CouplingFlag.HasAll(Coupling::control) && Couplers[b].Connected->Couplers[b].Connected->Power > 0.01) return fabs(Couplers[b].Connected->Couplers[b].Connected->enrot); break; default: @@ -412,7 +412,7 @@ bool TMoverParameters::MotorBlowersSwitch(bool State, end const Side, range_t co if (Notify != range_t::local) { SendCtrlToNext(Side == end::front ? VehicleCommand::motorBlowersFrontSwitch : VehicleCommand::motorBlowersRearSwitch, fan.is_enabled ? 1 : 0, CabActive, - Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return fan.is_enabled != initialstate; @@ -436,7 +436,7 @@ bool TMoverParameters::MotorBlowersSwitchOff(bool State, end const Side, range_t if (Notify != range_t::local) { SendCtrlToNext(Side == end::front ? VehicleCommand::motorBlowersFrontSwitchOff : VehicleCommand::motorBlowersRearSwitchOff, fan.is_disabled ? 1 : 0, CabActive, - Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return fan.is_disabled != initialstate; @@ -456,7 +456,7 @@ bool TMoverParameters::TractionModeSwitch(traction_mode const Mode, range_t cons if (Notify != range_t::local && accepted) { - SendCtrlToNext(VehicleCommand::tractionMode, Mode == traction_mode::genset ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::tractionMode, Mode == traction_mode::genset ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return TractionMode != initialstate; @@ -548,7 +548,7 @@ bool TMoverParameters::DynamicBrakeSwitch(bool Switch) DBS = true; for (auto &thiscoupler : Couplers) // with Couplers[b] do - if (TestFlag(thiscoupler.CouplingFlag, coupling::control)) + if (thiscoupler.CouplingFlag.HasAll(Coupling::control)) thiscoupler.Connected->DynamicBrakeFlag = Switch; // end; // if (DynamicBrakeType=dbrake_passive) and (TrainType=train_type::et42) then @@ -1454,7 +1454,7 @@ bool TMoverParameters::FuseFlagCheck(void) const FFC = FuseFlag; else // pobor pradu jezeli niema mocy for (auto &thiscoupler : Couplers) - if (TestFlag(thiscoupler.CouplingFlag, coupling::control) && thiscoupler.Connected->Power > 0.01) + if (thiscoupler.CouplingFlag.HasAll(Coupling::control) && thiscoupler.Connected->Power > 0.01) FFC = thiscoupler.Connected->FuseFlagCheck(); return FFC; @@ -1549,7 +1549,7 @@ bool TMoverParameters::RelayReset(int const Relays, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext(VehicleCommand::relayReset, Relays, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::relayReset, Relays, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return reset; @@ -1637,7 +1637,7 @@ bool TMoverParameters::MaxCurrentSwitch(bool State, range_t const Notify) if (Notify != range_t::local) { - SendCtrlToNext(VehicleCommand::maxCurrentSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + SendCtrlToNext(VehicleCommand::maxCurrentSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return State != initialstate; @@ -1684,7 +1684,7 @@ bool TMoverParameters::ResistorsFlagCheck(void) const else // pobor pradu jezeli niema mocy { for (auto &thiscoupler : Couplers) - if (TestFlag(thiscoupler.CouplingFlag, coupling::control) && thiscoupler.Connected->Power > 0.01) + if (thiscoupler.CouplingFlag.HasAll(Coupling::control) && thiscoupler.Connected->Power > 0.01) RFC = thiscoupler.Connected->ResistorsFlagCheck(); } return RFC; @@ -1722,7 +1722,7 @@ double TMoverParameters::ShowCurrentP(int AmpN) const int current = 0; for (int b = 0; b < 2; b++) // with Couplers[b] do - if (TestFlag(Couplers[b].CouplingFlag, coupling::control) && Couplers[b].Connected->Power > 0.01) + if (Couplers[b].CouplingFlag.HasAll(Coupling::control) && Couplers[b].Connected->Power > 0.01) current = static_cast(Couplers[b].Connected->ShowCurrent(AmpN)); return current; } diff --git a/physics/vehicletypes.h b/physics/vehicletypes.h index 077e94cb0..4cd26d21b 100644 --- a/physics/vehicletypes.h +++ b/physics/vehicletypes.h @@ -128,25 +128,6 @@ enum DerailReason /// Fuzzy-logic probability weight: damage caused by wheel slip. #define p_slippdmg (1e-03) -/*typ sprzegu*/ -/// Coupling type: virtual — vehicles share a track and are aware of each other. -static int const ctrain_virtual = 0; // gdy pojazdy na tym samym torze się widzą wzajemnie -/// Coupling type: physical coupler. -static int const ctrain_coupler = 1; // sprzeg fizyczny -/// Coupling type: pneumatic brake hose. -static int const ctrain_pneumatic = 2; // przewody hamulcowe -/// Coupling type: control cable (multiple-unit). -static int const ctrain_controll = 4; // przewody sterujące (ukrotnienie) -/// Coupling type: high-voltage power cable. -static int const ctrain_power = 8; // przewody zasilające (WN) -/// Coupling type: passenger gangway. -static int const ctrain_passenger = 16; // mostek przejściowy -/// Coupling type: secondary 8 atm pneumatic line (yellow, main air). -static int const ctrain_scndpneumatic = 32; // przewody 8 atm (żółte; zasilanie powietrzem) -/// Coupling type: high-voltage train heating cable. -static int const ctrain_heating = 64; // przewody ogrzewania WN -/// Coupling type: permanent (inter-section) — not separable during ordinary shunting; encoded as negative in config files. -static int const ctrain_depot = 128; // nie rozłączalny podczas zwykłych manewrów (międzyczłonowy), we wpisie wartość ujemna /// Vehicle ends — front or rear (mutually exclusive). enum end { @@ -165,35 +146,130 @@ enum side left = 1 }; -/// Bit flags representing the kind of physical/logical connections in a coupling. Combinable. -enum coupling +/// The kinds of connection a coupling between two vehicles makes. The numbers are the ones of the scenery +/// files and the vehicle definitions (AllowedFlag, the coupling of a vehicle in a train), where they add up. +enum class Coupling : unsigned { - /// No coupling (virtual / not connected). - faux = 0x0, - /// Mechanical coupler. - coupler = 0x1, - /// Pneumatic brake hose (PG). - brakehose = 0x2, - /// Control cable (multiple-unit). - control = 0x4, - /// High-voltage cable (traction supply). - highvoltage = 0x8, - /// Passenger gangway. - gangway = 0x10, - /// Main air (8 atm) line — secondary pneumatic supply. - mainhose = 0x20, - /// Train heating cable. - heating = 0x40, - /// Permanent (non-separable) coupling. - permanent = 0x80, - /// 24 V auxiliary power cable. - power24v = 0x100, - /// 110 V auxiliary power cable. - power110v = 0x200, - /// 3-phase 400 V auxiliary power cable. - power3x400v = 0x400, - // uic = 0x1000, + none = 0x0, // the vehicles only see each other (virtual) + coupler = 0x1, // the mechanical coupler + brakeHose = 0x2, // the brake pipe + control = 0x4, // the control cable of the multiple unit + highVoltage = 0x8, // the high voltage cable of the traction supply + gangway = 0x10, // the gangway for the passengers + mainHose = 0x20, // the main reservoir pipe (8 bar, yellow) + heating = 0x40, // the high voltage cable of the train heating + permanent = 0x80, // not parted by usual shunting (between the sections of a unit); negative in a definition + power24v = 0x100, // the 24 V cable + power110v = 0x200, // the 110 V cable + power3x400v = 0x400, // the 3x400 V cable }; + +/// A set of the kinds of connection of a coupling: what a coupling joins, what a vehicle allows, what a +/// command needs to pass. Read from and written to the numbers of the files only through FromBits() and Bits(). +class CouplingSet +{ +public: + constexpr CouplingSet() = default; + constexpr CouplingSet(Coupling const kind) : bits{static_cast(kind)} {} // NOSONAR: a kind is a set of one + // the set the number of a file gives (the sum of the numbers of the kinds) + static constexpr CouplingSet FromBits(int const number) + { + CouplingSet set; + set.bits = static_cast(number); + return set; + } + // every kind of coupling: a coupling of any kind has one of them + static constexpr CouplingSet All() + { + return FromBits(-1); + } + // any kind at all: as the old number was true when it wasn't zero + constexpr explicit operator bool() const + { + return bits != 0; + } + // the number of the set, for the files and the log + constexpr int Bits() const + { + return static_cast(bits); + } + constexpr bool Empty() const + { + return bits == 0; + } + // all the kinds of the other set are in this one + constexpr bool HasAll(CouplingSet const other) const + { + return (bits & other.bits) == other.bits; + } + // any of the kinds of the other set is in this one + constexpr bool HasAny(CouplingSet const other) const + { + return (bits & other.bits) != 0; + } + // adds the kinds; returns whether any of them was missing + constexpr bool Set(CouplingSet const other) + { + if (HasAll(other)) + { + return false; + } + bits |= other.bits; + return true; + } + // takes the kinds away, where all of them are there; returns whether it did + constexpr bool Clear(CouplingSet const other) + { + if (false == HasAll(other)) + { + return false; + } + bits &= ~other.bits; + return true; + } + // this set without the kinds of the other + constexpr CouplingSet Without(CouplingSet const other) const + { + return FromBits(static_cast(bits & ~other.bits)); + } + constexpr CouplingSet &operator|=(CouplingSet const other) + { + bits |= other.bits; + return *this; + } + constexpr CouplingSet &operator&=(CouplingSet const other) + { + bits &= other.bits; + return *this; + } + friend constexpr CouplingSet operator|(CouplingSet left, CouplingSet const right) + { + return left |= right; + } + friend constexpr CouplingSet operator&(CouplingSet left, CouplingSet const right) + { + return left &= right; + } + // the kinds in one of the sets and not in the other: what changed between them + constexpr CouplingSet &operator^=(CouplingSet const other) + { + bits ^= other.bits; + return *this; + } + friend constexpr CouplingSet operator^(CouplingSet left, CouplingSet const right) + { + return left ^= right; + } + friend constexpr bool operator==(CouplingSet const &left, CouplingSet const &right) = default; + +private: + unsigned bits{0}; +}; + +constexpr CouplingSet operator|(Coupling const left, Coupling const right) +{ + return CouplingSet{left} | CouplingSet{right}; +} /// Range of effect for a control command (mutually exclusive). enum class range_t { @@ -616,7 +692,7 @@ struct TCommand /// Second numeric argument. double Value2 = 0.0; /// Coupling flag controlling how the command propagates between vehicles. - int Coupling{coupling::control}; // coupler flag used to determine command propagation + CouplingSet couplings{Coupling::control}; // the couplings the command passes through /// World-space location associated with the command. TLocation Location; }; diff --git a/rendering/common/scenewalk.cpp b/rendering/common/scenewalk.cpp index 1a91a1f5c..ebceae0ff 100644 --- a/rendering/common/scenewalk.cpp +++ b/rendering/common/scenewalk.cpp @@ -186,16 +186,16 @@ bool scene_walk::Render_interior( bool const Alpha ) { glm::dvec3 const originoffset { dynamic->vPosition - m_renderpass.pass_camera.position() }; float const squaredistance{ glm::length2( glm::vec3{ originoffset } / Global.ZoomFactor ) }; dynamics.emplace_back( squaredistance, dynamic ); - dynamic = dynamic->Next( coupling::permanent ); + dynamic = dynamic->Next( Coupling::permanent ); } // draw also interiors of permanently coupled vehicles in front, if there's any - dynamic = simulation::Train->Dynamic()->Prev( coupling::permanent ); + dynamic = simulation::Train->Dynamic()->Prev( Coupling::permanent ); while( dynamic != nullptr ) { glm::dvec3 const originoffset { dynamic->vPosition - m_renderpass.pass_camera.position() }; float const squaredistance{ glm::length2( glm::vec3{ originoffset } / Global.ZoomFactor ) }; dynamics.emplace_back( squaredistance, dynamic ); - dynamic = dynamic->Prev( coupling::permanent ); + dynamic = dynamic->Prev( Coupling::permanent ); } if( Alpha ) { std::sort( diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index 3599bb1bb..e53e77dfa 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -208,7 +208,7 @@ bool coupled(TDynamicObject const *From, TDynamicObject const *To) { for (int step = 0; step < 1000 && vehicle != nullptr; ++step) { auto const *mover{vehicle->MoverParameters}; auto const &neighbour{mover->Neighbours[side]}; - if (mover->Couplers[side].CouplingFlag == 0 || neighbour.vehicle == nullptr) + if (mover->Couplers[side].CouplingFlag.Empty() || neighbour.vehicle == nullptr) break; if (neighbour.vehicle == To) return true; @@ -621,8 +621,8 @@ void blackbox_recorder::look_at_couplers() { for (int side = 0; side < 2; ++side) { auto const flags{mover->Couplers[side].CouplingFlag}; // a neighbour not coupled is only seen on the same track - auto const *other{flags != 0 ? mover->Neighbours[side].vehicle : nullptr}; - coupler_entry const now{other, other != nullptr ? mover->Neighbours[side].vehicle_end : 0, other != nullptr ? flags : 0}; + auto const *other{false == flags.Empty() ? mover->Neighbours[side].vehicle : nullptr}; + coupler_entry const now{other, other != nullptr ? mover->Neighbours[side].vehicle_end : 0, other != nullptr ? flags.Bits() : 0}; auto &last{entry.couplers[side]}; auto const changed{now.other != last.other || now.other_side != last.other_side || now.flags != last.flags}; auto const before{last}; diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index 69fc726b9..7c4644868 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -1478,7 +1478,7 @@ state_serializer::deserialize_endtrainset( cParser &Input, scene::scratch_data & 0, nullptr ); } - if( Scratchpad.trainset.couplings.back() == coupling::faux ) { + if( Scratchpad.trainset.couplings.back() == 0 ) { // no coupling // jeśli ostatni pojazd ma sprzęg 0 to założymy mu końcówki blaszane (jak AI się odpali, to sobie poprawi) // place end signals only on trains without a driver, activate markers otherwise Scratchpad.trainset.vehicles.back()->RaLightsSet( @@ -1625,12 +1625,12 @@ state_serializer::deserialize_dynamic( cParser &Input, scene::scratch_data &Scra auto coupling = couplingdatawithparams != std::string::npos ? std::atoi(couplingdata.substr(0, couplingdatawithparams).c_str()) : std::atoi(couplingdata.c_str()); if( coupling < 0 ) { // sprzęg zablokowany (pojazdy nierozłączalne przy manewrach) - coupling = -coupling | coupling::permanent; + coupling = ( CouplingSet::FromBits( -coupling ) | Coupling::permanent ).Bits(); } if( offset != -1.0 && std::abs(offset) > 0.5 ) { // maksymalna odległość między sprzęgami - do przemyślenia // likwidacja sprzęgu, jeśli odległość zbyt duża - to powinno być uwzględniane w fizyce sprzęgów... - coupling = coupling::faux; + coupling = 0; // no coupling } auto const params = couplingdatawithparams != std::string::npos ? couplingdata.substr(couplingdatawithparams + 1) : ""; // load amount and type @@ -1692,8 +1692,8 @@ state_serializer::deserialize_dynamic( cParser &Input, scene::scratch_data &Scra } // automatically establish permanent connections for couplers which specify them in their definitions if( coupling != 0 - && vehicle->MoverParameters->Couplers[(offset == -1.0 ? end::front : end::rear)].AllowedFlag & coupling::permanent ) { - coupling |= coupling::permanent; + && vehicle->MoverParameters->Couplers[(offset == -1.0 ? end::front : end::rear)].AllowedFlag & Coupling::permanent ) { + coupling = ( CouplingSet::FromBits( coupling ) | Coupling::permanent ).Bits(); } if( true == Scratchpad.trainset.is_open ) { Scratchpad.trainset.vehicles.emplace_back( vehicle ); diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp index f6e2a4a39..a247918aa 100644 --- a/simulation/simulationtest.cpp +++ b/simulation/simulationtest.cpp @@ -188,7 +188,7 @@ bool test_manager::tested_trains_at_rest() const // 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; + return vehicle != nullptr && vehicle->find_vehicle(Coupling::coupler, is_moving) != nullptr; }); } diff --git a/tests/unit/consist.cpp b/tests/unit/consist.cpp index 1f22632e6..141abe5af 100644 --- a/tests/unit/consist.cpp +++ b/tests/unit/consist.cpp @@ -8,7 +8,7 @@ namespace test { consist::consist() = default; consist::~consist() = default; -vehicle &consist::add(definition const &Definition, int Cab, int Coupling, double Velocity, double Gap) { +vehicle &consist::add(definition const &Definition, int Cab, CouplingSet const couplings, double Velocity, double Gap) { auto added{std::make_unique(Definition, Velocity, std::format("test{}", m_vehicles.size()), Cab)}; auto &mover{added->mover()}; @@ -20,9 +20,9 @@ vehicle &consist::add(definition const &Definition, int Cab, int Coupling, doubl auto &last{m_vehicles.back()->mover()}; position = m_positions.back() - 0.5 * (last.Dim.L + mover.Dim.L) - Gap; mover.Loc = TLocation{position, 0.0, 0.0}; - if (Coupling != coupling::faux) { - last.Attach(end::rear, end::front, &mover, Coupling, true, false); - mover.Attach(end::front, end::rear, &last, Coupling, true, false); + if (false == couplings.Empty()) { + last.Attach(end::rear, end::front, &mover, couplings, true, false); + mover.Attach(end::front, end::rear, &last, couplings, true, false); } } else { diff --git a/tests/unit/consist.h b/tests/unit/consist.h index 2c982e446..eb330e787 100644 --- a/tests/unit/consist.h +++ b/tests/unit/consist.h @@ -21,8 +21,8 @@ namespace test { class consist { public: // everything a coupler can join, as two vehicles of a train coupled by a crew - static constexpr int full_coupling{coupling::coupler | coupling::brakehose | coupling::mainhose | coupling::control | coupling::gangway | coupling::heating | - coupling::permanent | coupling::power110v | coupling::power24v | coupling::highvoltage}; + static constexpr CouplingSet full_coupling{Coupling::coupler | Coupling::brakeHose | Coupling::mainHose | Coupling::control | Coupling::gangway | Coupling::heating | + Coupling::permanent | Coupling::power110v | Coupling::power24v | Coupling::highVoltage}; consist(); ~consist(); @@ -31,8 +31,8 @@ public: // a vehicle at the back of the train, its front coupler joined to the rear one of the last vehicle with // the given coupling (coupling flags), Gap [m] between their buffers. Cab as for a vehicle. a vehicle - // with no coupling (coupling::faux) is free on the same track, as one about to be coupled or hit - vehicle &add(definition const &Definition, int Cab = 0, int Coupling = full_coupling, double Velocity = 0.0, double Gap = 0.0); + // with no coupling (Coupling::none) is free on the same track, as one about to be coupled or hit + vehicle &add(definition const &Definition, int Cab = 0, CouplingSet couplings = full_coupling, double Velocity = 0.0, double Gap = 0.0); vehicle &operator[](std::size_t Index) { return *m_vehicles[Index]; } std::size_t size() const { return m_vehicles.size(); } diff --git a/tests/unit/drive.cpp b/tests/unit/drive.cpp index 6c0356ad5..7663d8363 100644 --- a/tests/unit/drive.cpp +++ b/tests/unit/drive.cpp @@ -74,7 +74,7 @@ void release_brakes(TMoverParameters &Cab) { auto const *vehicle{pending.back()}; pending.pop_back(); for (auto const &thiscoupler : vehicle->Couplers) { - if (thiscoupler.Connected != nullptr && thiscoupler.CouplingFlag != coupling::faux && std::ranges::find(train, thiscoupler.Connected) == train.end()) { + if (thiscoupler.Connected != nullptr && thiscoupler.CouplingFlag != Coupling::none && std::ranges::find(train, thiscoupler.Connected) == train.end()) { thiscoupler.Connected->DecManualBrakeLevel(ManualBrakePosNo); thiscoupler.Connected->SpringBrake.Activate = false; train.push_back(thiscoupler.Connected); diff --git a/tests/unit/scenario.cpp b/tests/unit/scenario.cpp index ebb5ae0c3..9dfee124f 100644 --- a/tests/unit/scenario.cpp +++ b/tests/unit/scenario.cpp @@ -24,8 +24,8 @@ scenario::scenario(std::string Name, std::vector Channels, track const reseed_random(); } -scenario &scenario::add(std::string const &Path, int Cab, int Coupling, double Velocity, double Gap) { - m_train.add(definition::fiz(Path), Cab, Coupling, Velocity, Gap); +scenario &scenario::add(std::string const &Path, int Cab, CouplingSet const couplings, double Velocity, double Gap) { + m_train.add(definition::fiz(Path), Cab, couplings, Velocity, Gap); return *this; } diff --git a/tests/unit/scenario.h b/tests/unit/scenario.h index fff4d9619..54678af5d 100644 --- a/tests/unit/scenario.h +++ b/tests/unit/scenario.h @@ -25,7 +25,7 @@ public: scenario(std::string Name, std::vector Channels, track const &Track = {0.15, 0.0, catenary_3kv}); // adds a real vehicle at the back, see consist::add() - scenario &add(std::string const &Path, int Cab = 0, int Coupling = consist::full_coupling, double Velocity = 0.0, double Gap = 0.0); + scenario &add(std::string const &Path, int Cab = 0, CouplingSet couplings = consist::full_coupling, double Velocity = 0.0, double Gap = 0.0); consist &train() { return m_train; } TMoverParameters &vehicle(std::size_t Index) { return m_train[Index].mover(); } diff --git a/tests/unit/test_brakes.cpp b/tests/unit/test_brakes.cpp index cd2a95a3c..5c5246798 100644 --- a/tests/unit/test_brakes.cpp +++ b/tests/unit/test_brakes.cpp @@ -102,7 +102,7 @@ TEST_CASE("brakes: service braking stops a heavier wagon too") { TEST_CASE("brakes: a dead EN57 hauled with the brake hose alone charges from the brake pipe and brakes") { test::consist train; auto &locomotive{train.add(definition::fiz("sm42_v1/6d1"))}; - train.add(definition::fiz("en57_v1/5bgb"), 0, coupling::coupler | coupling::brakehose); + train.add(definition::fiz("en57_v1/5bgb"), 0, Coupling::coupler | Coupling::brakeHose); train.add(definition::fiz("en57_v1/6ba_840")); train.add(definition::fiz("en57_v1/5bgaiii_led_spot")); // a unit standing dead: no air anywhere, nothing in its main reservoir pipe diff --git a/tests/unit/test_cab.cpp b/tests/unit/test_cab.cpp index eab6e87ca..40a94d552 100644 --- a/tests/unit/test_cab.cpp +++ b/tests/unit/test_cab.cpp @@ -38,7 +38,7 @@ TEST_CASE("cab: the engine rotation of up to three vehicles in multiple, on the // no control cable, no reading consist apart; auto const &alone{apart.add(definition::fiz("sn61_v2/sn61"), 1).mover()}; - apart.add(definition::fiz("sn61_v2/sn61"), 0, coupling::coupler | coupling::brakehose); + apart.add(definition::fiz("sn61_v2/sn61"), 0, Coupling::coupler | Coupling::brakeHose); CHECK(alone.ShowEngineRotation(2) == doctest::Approx(0.0)); } diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index bafa01a82..be5910011 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -125,8 +125,8 @@ definition mixed_wagon(int const Index) { return definition::fiz(Index % 3 == 1 ? "3wl_v2/3wl" : "430w_v2/430w"); } -vehicle &add_mixed(consist &Train, int const Index, int const Coupling, double const Velocity, double const Gap) { - auto &wagon{Train.add(mixed_wagon(Index), 0, Coupling, Velocity, Gap)}; +vehicle &add_mixed(consist &Train, int const Index, CouplingSet const couplings, double const Velocity, double const Gap) { + auto &wagon{Train.add(mixed_wagon(Index), 0, couplings, Velocity, Gap)}; if (Index % 3 != 1) { wagon->AssignLoad("coal", 59.5f); wagon->ComputeMass(); @@ -162,7 +162,7 @@ crash_outcome freight_crash(double const Speed, double const Radius, double cons } train.run(30.0, track); // the train running into it, its locomotive leading, a metre short of the hit - train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, Speed, 1.0); + train.add(definition::fiz("4e_v1/4e"), 0, Coupling::none, Speed, 1.0); for (int i = 0; i < 12; ++i) { add_mixed(train, i, consist::full_coupling, Speed, 0.0); } @@ -202,7 +202,7 @@ double locomotive_into_wagon(double const Speed, double const Dt) { wagon->AssignLoad("coal", 59.5f); wagon->ComputeMass(); // behind the wagon, running forwards into its rear end - auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, Speed, 0.5)}; + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, Coupling::none, Speed, 0.5)}; train.run(3.0, {}, Dt); return wagon->Couplers[end::rear].crush + locomotive->Couplers[end::front].crush; } @@ -235,7 +235,7 @@ struct contact_outcome { contact_outcome contact(definition const &Front, definition const &Back, double const Speed, double const Gap, double const Seconds = 5.0, double const Dt = 0.01) { consist train; auto &front{train.add(Front)}; - auto &back{train.add(Back, 0, coupling::faux, Speed, Gap)}; + auto &back{train.add(Back, 0, Coupling::none, Speed, Gap)}; train.run(Seconds, {}, Dt); contact_outcome result; result.crush = front->Couplers[end::rear].crush + back->Couplers[end::front].crush; @@ -266,8 +266,8 @@ double pushed_ratio_of(TMoverParameters const &Vehicle, int const End, double co } // a loaded 430W coal wagon -vehicle &add_loaded(consist &Train, int const Coupling, double const Velocity, double const Gap) { - auto &wagon{Train.add(definition::fiz("430w_v2/430w"), 0, Coupling, Velocity, Gap)}; +vehicle &add_loaded(consist &Train, CouplingSet const couplings, double const Velocity, double const Gap) { + auto &wagon{Train.add(definition::fiz("430w_v2/430w"), 0, couplings, Velocity, Gap)}; wagon->AssignLoad("coal", 59.5f); wagon->ComputeMass(); return wagon; @@ -579,7 +579,7 @@ TEST_CASE("collisions: a locomotive at its starting effort against a braked trai train[i].hold_brake_pipe(0.0); } train.run(30.0, line); - auto &locomotive{train.add(definition::fiz("st44_v2/m62-1151"), 1, coupling::faux, 0.0, 0.0)}; + auto &locomotive{train.add(definition::fiz("st44_v2/m62-1151"), 1, Coupling::none, 0.0, 0.0)}; test::driven const driver{locomotive.mover(), locomotive.mover(), locomotive.mover(), [&train](double const Seconds, test::track const &Track) { train.run(Seconds, Track); }}; REQUIRE(test::start_up(driver, line)); test::release_brakes(locomotive.mover()); @@ -625,7 +625,7 @@ TEST_CASE("collisions: a locomotive running onto an empty wagon at 9 km/h doesn' curve.radius = 150.0; consist train; auto &empty{train.add(definition::fiz("3wl_v2/3wl"))}; - auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, 9.0, 0.5)}; + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, Coupling::none, 9.0, 0.5)}; auto pushed{0.0}; auto worst{0.0}; auto over{0}; // steps past the climbing limit @@ -661,7 +661,7 @@ TEST_CASE("collisions: a train propelling an empty wagon into a braked one in a train[i].hold_brake_pipe(0.0); } train.run(30.0, curve); - auto &empty{train.add(definition::fiz("3wl_v2/3wl"), 0, coupling::faux, 15.0, 1.0)}; + auto &empty{train.add(definition::fiz("3wl_v2/3wl"), 0, Coupling::none, 15.0, 1.0)}; train.add(definition::fiz("4e_v1/4e"), 0, consist::full_coupling, 15.0, 0.0); for (int i = 0; i < 6; ++i) { add_loaded(train, consist::full_coupling, 15.0, 0.0); @@ -681,8 +681,8 @@ TEST_CASE("collisions: a repaired vehicle has its ends rebuilt and is back on th model_setting const physical{global_settings::collision_model::physical}; flag_setting const crashdamage{Global.crash_damage, true}; consist train; - auto &wagon{add_loaded(train, coupling::faux, 0.0, 0.0)}; - auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, 30.0, 0.5)}; + auto &wagon{add_loaded(train, Coupling::none, 0.0, 0.0)}; + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, Coupling::none, 30.0, 0.5)}; train.run(3.0); REQUIRE(wagon->Couplers[end::rear].crush + locomotive->Couplers[end::front].crush > cl::override_crush); REQUIRE((derailed(wagon.mover()) || derailed(locomotive.mover()))); @@ -764,7 +764,7 @@ TEST_CASE("collisions: the legacy rule with physics.collisions old, the crush wi model_setting const setting{model}; consist train; train.add(definition::fiz(front)); - train.add(definition::fiz(back), 0, coupling::faux, speed, 20.0); + train.add(definition::fiz(back), 0, Coupling::none, speed, 20.0); train.run(10.0); CHECK(derailed(train[0].mover()) == (physical ? frontout_new : frontout_old)); CHECK(derailed(train[1].mover()) == (physical ? backout_new : backout_old)); @@ -805,7 +805,7 @@ TEST_CASE("collisions: the model of the collisions goes apart from the one of th model_setting const setting{collisions}; consist train; train.add(definition::fiz("4e_v1/4e")); - train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, 25.0, 20.0); + train.add(definition::fiz("4e_v1/4e"), 0, Coupling::none, 25.0, 20.0); train.run(10.0); Global.derailment = previous; auto const crush{train[0]->Couplers[end::rear].crush + train[1]->Couplers[end::front].crush}; @@ -844,7 +844,7 @@ TEST_CASE("collisions: the crush of a locomotive hitting a wagon doesn't depend TEST_CASE("collisions: automatic couplers hit too fast don't catch, the ends crush; torn off, they don't couple again") { model_setting const physical{global_settings::collision_model::physical}; flag_setting const crashdamage{Global.crash_damage, true}; - auto const automatic{definition::load("wagon").set("BuffCoupl", "CType", "Automatic").set("BuffCoupl", "AutomaticFlag", coupling::coupler | coupling::brakehose)}; + auto const automatic{definition::load("wagon").set("BuffCoupl", "CType", "Automatic").set("BuffCoupl", "AutomaticFlag", Coupling::coupler | Coupling::brakeHose)}; for (auto const speed : {20.0, 30.0, 45.0}) { CAPTURE(speed); vehicle moving{automatic, speed, "moving"}; @@ -882,7 +882,7 @@ TEST_CASE("collisions: road vehicles keep the legacy rule") { model_setting const setting{model}; consist road; road.add(definition::fiz("road/man/nl293")); - road.add(definition::fiz("road/man/nl293"), 0, coupling::faux, 40.0, 5.0); + road.add(definition::fiz("road/man/nl293"), 0, Coupling::none, 40.0, 5.0); road.run(5.0); CHECK(derailed(road[0].mover())); CHECK(derailed(road[1].mover())); @@ -897,7 +897,7 @@ TEST_CASE("collisions: a vehicle off the rails by the new model stays in the cha flag_setting const crashdamage{Global.crash_damage, true}; consist train; auto &wagon{train.add(definition::fiz("430w_v2/430w"))}; - auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, 10.0, 0.5)}; + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, Coupling::none, 10.0, 0.5)}; wagon->derail_in_collision(COLLISION_PUSHED_OFF, "for the test"); REQUIRE(derailed(wagon.mover())); auto const before{wagon->TotalMass * wagon->V + locomotive->TotalMass * locomotive->V}; @@ -946,7 +946,7 @@ TEST_CASE("collisions: identical units built to EN 15227 at 36 km/h") { consist train; train.add(unit(Anticlimbers, 1.040)); train.add(unit(Anticlimbers, 1.040)); - train.add(unit(Anticlimbers, 1.040 + Offset), 0, coupling::faux, Speed, 1.0); + train.add(unit(Anticlimbers, 1.040 + Offset), 0, Coupling::none, Speed, 1.0); train.add(unit(Anticlimbers, 1.040 + Offset), 0, consist::full_coupling, Speed); train.run(6.0); struct { @@ -1205,7 +1205,7 @@ TEST_CASE("collisions: two coaches (36 t and 41.6 t) at 8 km/h don't crush, nor auto &wall{train.add(light)}; wall->Derail(END_OF_TRACK); REQUIRE(derailed(wall.mover())); - auto &running{train.add(heavy, 0, coupling::faux, 5.0, gap)}; + auto &running{train.add(heavy, 0, Coupling::none, 5.0, gap)}; train.run(5.0); CHECK(wall->Couplers[end::rear].crush + running->Couplers[end::front].crush == 0.0); CHECK(running->CollisionDerail == NONE); @@ -1231,7 +1231,7 @@ TEST_CASE("collisions: a locomotive pushing a standing braked train at full powe } train.run(30.0, line); // the locomotive behind them, touching, driven forwards into them at full power - auto &locomotive{train.add(definition::fiz(path), 1, coupling::faux, 0.0, 0.0)}; + auto &locomotive{train.add(definition::fiz(path), 1, Coupling::none, 0.0, 0.0)}; test::driven const driver{locomotive.mover(), locomotive.mover(), locomotive.mover(), [&train](double const Seconds, test::track const &Track) { train.run(Seconds, Track); }}; REQUIRE(test::start_up(driver, line)); test::release_brakes(locomotive.mover()); @@ -1298,14 +1298,14 @@ TEST_CASE("collisions: the monitor goes by the energy of the hit as well") { CAPTURE(gap); consist train; train.add(definition::fiz("sm42_v1/6d1")); - train.add(definition::fiz("su45_v2/301d"), 0, coupling::faux, 5.8, gap); + train.add(definition::fiz("su45_v2/301d"), 0, Coupling::none, 5.8, gap); train.run(5.0); CHECK(train[0]->crush_reports + train[1]->crush_reports == 0); } // one past them it does consist train; train.add(definition::fiz("4e_v1/4e")); - train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, 25.0, 20.0); + train.add(definition::fiz("4e_v1/4e"), 0, Coupling::none, 25.0, 20.0); train.run(10.0); CHECK(train[0]->crush_reports + train[1]->crush_reports == 1); } @@ -1370,7 +1370,7 @@ TEST_CASE("collisions: the cut of the speed of the legacy derailment is no hit i for (auto const reason : {TOO_HIGH_SPEED, END_OF_TRACK}) { CAPTURE(reason); consist train; - auto &locomotive{train.add(definition::fiz(path), 0, coupling::faux, speed)}; + auto &locomotive{train.add(definition::fiz(path), 0, Coupling::none, speed)}; for (int i = 0; i < 3; ++i) { train.add(coach(41.0e3), 0, consist::full_coupling, speed); } @@ -1415,7 +1415,7 @@ TEST_CASE("collisions: the train behind a vehicle that ran off the end of the tr auto const speed{pushed ? 33.0 : 30.0}; consist train; if (false == pushed) { - train.add(definition::fiz("st44_v2/m62-1151"), 0, coupling::faux, speed); + train.add(definition::fiz("st44_v2/m62-1151"), 0, Coupling::none, speed); } constexpr int wagons{6}; for (int i = 0; i < wagons; ++i) { @@ -1477,7 +1477,7 @@ TEST_CASE("collisions: a pair parting at the start of the step isn't crushed (l0 consist train; auto &front{train.add(definition::fiz("430w_v2/430w"))}; // behind it with the buffers pressed to their stop, moving back away from it, or standing - auto &back{train.add(definition::fiz("430w_v2/430w"), 0, coupling::faux, parting ? -3.0 : 0.0, -0.3)}; + auto &back{train.add(definition::fiz("430w_v2/430w"), 0, Coupling::none, parting ? -3.0 : 0.0, -0.3)}; // one step, the way the consist steps it, with the vehicle behind knocked forwards onto the front one between // the forces and the movement, as a hit of another vehicle in the step does constexpr double dt{0.01}; diff --git a/tests/unit/test_commands.cpp b/tests/unit/test_commands.cpp index a0b6569db..bd06bb26b 100644 --- a/tests/unit/test_commands.cpp +++ b/tests/unit/test_commands.cpp @@ -249,7 +249,7 @@ TEST_CASE("commands: every command run on every real vehicle") { auto const &command{commands[i]}; trace.mark(std::format("{} {} {}", command.name, command.value1, command.value2)); auto const parsed{ParseVehicleCommand(command.name)}; - done = real->RunCommand(parsed.command, command.value1, command.value2, coupling::control, parsed.argument); + done = real->RunCommand(parsed.command, command.value1, command.value2, Coupling::control, parsed.argument); trace.sample(static_cast(i + 1), real.mover()); } trace.check(); @@ -448,9 +448,9 @@ struct train { vehicle middle{definition::fiz("4e_v1/4e"), 0.0, "middle"}; vehicle last{definition::fiz("4e_v1/4e"), 0.0, "last"}; - explicit train(int Coupling) { - head->Attach(end::rear, end::rear, &middle.mover(), Coupling, true, false); - middle->Attach(end::front, end::front, &last.mover(), Coupling, true, false); + explicit train(CouplingSet const couplings) { + head->Attach(end::rear, end::rear, &middle.mover(), couplings, true, false); + middle->Attach(end::front, end::front, &last.mover(), couplings, true, false); } }; @@ -485,24 +485,24 @@ TEST_CASE("commands: travel along the train, turned round for a vehicle facing b CHECK(consist.last->Pantographs[end::rear].valve.is_enabled); } SUBCASE("sent backwards, it goes no further than the sender: nothing is coupled at its front") { - consist.head->RunCommand(VehicleCommand::doorLock, 0, -1, coupling::control); + consist.head->RunCommand(VehicleCommand::doorLock, 0, -1, Coupling::control); CHECK_FALSE(consist.head->Doors.lock_enabled); CHECK(consist.middle->Doors.lock_enabled); } SUBCASE("the same command again isn't taken by the next vehicle a second time") { - CHECK(consist.middle->SetInternalCommand(VehicleCommand::doorStep, 0, 1, coupling::control)); - CHECK_FALSE(consist.middle->SetInternalCommand(VehicleCommand::doorStep, 0, 1, coupling::control)); + CHECK(consist.middle->SetInternalCommand(VehicleCommand::doorStep, 0, 1, Coupling::control)); + CHECK_FALSE(consist.middle->SetInternalCommand(VehicleCommand::doorStep, 0, 1, Coupling::control)); CHECK_FALSE(consist.head->RunInternalCommand()); // nothing to run } } TEST_CASE("commands: don't pass a coupling without the control cable") { - train consist{coupling::coupler | coupling::brakehose}; - consist.head->RunCommand(VehicleCommand::doorLock, 0, 1, coupling::control); + train consist{Coupling::coupler | Coupling::brakeHose}; + consist.head->RunCommand(VehicleCommand::doorLock, 0, 1, Coupling::control); CHECK_FALSE(consist.head->Doors.lock_enabled); CHECK(consist.middle->Doors.lock_enabled); // a command of another coupling goes through it - consist.head->RunCommand(VehicleCommand::doorStep, 0, 1, coupling::brakehose); + consist.head->RunCommand(VehicleCommand::doorStep, 0, 1, Coupling::brakeHose); CHECK_FALSE(consist.middle->Doors.step_enabled); } diff --git a/tests/unit/test_controls.cpp b/tests/unit/test_controls.cpp index 251bb18a6..47b852f2d 100644 --- a/tests/unit/test_controls.cpp +++ b/tests/unit/test_controls.cpp @@ -508,7 +508,7 @@ TEST_CASE("controls: a locomotive running into a standing wagon") { CAPTURE(speed); scenario scenario{std::format("controls/collision/{} kmh", static_cast(speed)), motion()}; // the wagon stands in front, the locomotive comes from behind it - scenario.add("bdhpumn_v3/bdhpumn").add("4e_v1/4e", 0, coupling::faux, speed, 30.0); + scenario.add("bdhpumn_v3/bdhpumn").add("4e_v1/4e", 0, Coupling::none, speed, 30.0); auto const &wagon{scenario.vehicle(0)}; scenario.wait(30.0); // slow, the locomotive pushes the wagon off, the buffers only touching, and both roll to a stop; fast, diff --git a/tests/unit/test_coupler_physics.cpp b/tests/unit/test_coupler_physics.cpp index ebffa8e80..31b46a165 100644 --- a/tests/unit/test_coupler_physics.cpp +++ b/tests/unit/test_coupler_physics.cpp @@ -268,9 +268,9 @@ TEST_CASE("coupler physics: a jerk on the solid draw gear breaks the coupling by namespace { // couples the facing ends of the two vehicles, as the scenery does -void join(vehicle &First, int FirstEnd, vehicle &Second, int SecondEnd, int Coupling = coupling::coupler) { - REQUIRE(First->Attach(FirstEnd, SecondEnd, &Second.mover(), Coupling, true, false)); - REQUIRE(Second->Attach(SecondEnd, FirstEnd, &First.mover(), Coupling, true, false)); +void join(vehicle &First, int FirstEnd, vehicle &Second, int SecondEnd, CouplingSet const couplings = Coupling::coupler) { + REQUIRE(First->Attach(FirstEnd, SecondEnd, &Second.mover(), couplings, true, false)); + REQUIRE(Second->Attach(SecondEnd, FirstEnd, &First.mover(), couplings, true, false)); } // the wagon of data/wagon.json with the given play of its screw couplings @@ -391,7 +391,7 @@ TEST_CASE("coupler physics: a jerk on a coupling with play breaks it, the brake flag_setting const everywhere{Global.coupler_physics_all, true}; auto front{loose_wagon(0.05, 20.0, "front")}; auto rear{loose_wagon(0.05, 0.1, "rear")}; - join(rear, end::front, front, end::rear, coupling::coupler | coupling::brakehose); + join(rear, end::front, front, end::rear, Coupling::coupler | Coupling::brakeHose); test::pair pair{rear, end::front, front, end::rear, 0.0}; front.hold_brake_pipe(5.0); rear.hold_brake_pipe(5.0); @@ -439,7 +439,7 @@ TEST_CASE("coupler physics: automatic couplers still catch a wagon rolling into flag_setting const physics{Global.coupler_physics, true}; flag_setting const everywhere{Global.coupler_physics_all, true}; flag_setting const crashdamage{Global.crash_damage, true}; - auto automatic{definition::load("wagon").set("BuffCoupl", "CType", "Automatic").set("BuffCoupl", "AutomaticFlag", coupling::coupler | coupling::brakehose)}; + auto automatic{definition::load("wagon").set("BuffCoupl", "CType", "Automatic").set("BuffCoupl", "AutomaticFlag", Coupling::coupler | Coupling::brakeHose)}; auto moving{vehicle{automatic, 5.0, "moving"}}; auto standing{vehicle{automatic, 0.0, "standing"}}; test::pair pair{moving, end::front, standing, end::rear, 1.0}; @@ -460,18 +460,18 @@ TEST_CASE("couplers: a broken coupling of vehicles facing each other uncouples t join(second, end::rear, third, end::front); first->damage_coupler(end::front); - CHECK(first->Couplers[end::front].CouplingFlag == coupling::faux); - CHECK(second->Couplers[end::front].CouplingFlag == coupling::faux); + CHECK(first->Couplers[end::front].CouplingFlag == Coupling::none); + CHECK(second->Couplers[end::front].CouplingFlag == Coupling::none); // the other coupling of the second vehicle stays - CHECK(second->Couplers[end::rear].CouplingFlag == coupling::coupler); + CHECK(second->Couplers[end::rear].CouplingFlag == Coupling::coupler); } TEST_CASE("couplers: a broken coupler is repaired alone, with the one of the vehicle it was coupled with") { auto first{vehicle{definition::load("wagon"), 0.0, "first"}}; auto second{vehicle{definition::load("wagon"), 0.0, "second"}}; auto third{vehicle{definition::load("wagon"), 0.0, "third"}}; - join(first, end::rear, second, end::front, coupling::coupler | coupling::brakehose); - join(second, end::rear, third, end::front, coupling::coupler | coupling::brakehose); + join(first, end::rear, second, end::front, Coupling::coupler | Coupling::brakeHose); + join(second, end::rear, third, end::front, Coupling::coupler | Coupling::brakeHose); // both couplings of the second wagon break second->damage_coupler(end::front); @@ -499,8 +499,8 @@ TEST_CASE("couplers: a broken coupler is repaired alone, with the one of the veh CHECK_FALSE(TestFlag(second->DamageFlag, dtrain_coupling)); CHECK_FALSE(second->AlarmChainFlag); // repaired, not coupled: the vehicles are coupled again as usual - CHECK(second->Couplers[end::rear].CouplingFlag == coupling::faux); - CHECK(second->Attach(end::rear, end::front, &third.mover(), coupling::coupler, true, false)); + CHECK(second->Couplers[end::rear].CouplingFlag == Coupling::none); + CHECK(second->Attach(end::rear, end::front, &third.mover(), Coupling::coupler, true, false)); } TEST_CASE("coupler physics: with couplerphysics yes, only the pairs with a vehicle covered take the physical model") { @@ -543,7 +543,7 @@ TEST_CASE("coupler physics: a hit on a braked train runs through it as a wave, w train.add(definition::load("wagon")); } // a wagon rolling at 15 km/h into the rear of the standing train, its brakes applied - train.add(definition::load("wagon"), 0, coupling::faux, 15.0, 0.3); + train.add(definition::load("wagon"), 0, Coupling::none, 15.0, 0.3); std::vector peak(wagons, 0.0); std::vector started(wagons, -1.0); diff --git a/tests/unit/test_couplers.cpp b/tests/unit/test_couplers.cpp index 19421c52b..44b3ad663 100644 --- a/tests/unit/test_couplers.cpp +++ b/tests/unit/test_couplers.cpp @@ -9,7 +9,7 @@ using test::vehicle; namespace { // the wagon from data/wagon.json with automatic couplers at both ends, which couple the given connections -definition automatic_definition(int Flag = coupling::coupler | coupling::brakehose) { +definition automatic_definition(CouplingSet const Flag = Coupling::coupler | Coupling::brakeHose) { return definition::load("wagon").set("BuffCoupl", "CType", "Automatic").set("BuffCoupl", "AutomaticFlag", Flag); } @@ -202,8 +202,8 @@ TEST_CASE("couplers: a wagon rolling slowly into a standing one couples with it" pair.run(3.0); REQUIRE(pair.coupled()); - CHECK(moving->Couplers[end::front].CouplingFlag == (coupling::coupler | coupling::brakehose)); - CHECK(standing->Couplers[end::rear].CouplingFlag == (coupling::coupler | coupling::brakehose)); + CHECK(moving->Couplers[end::front].CouplingFlag == (Coupling::coupler | Coupling::brakeHose)); + CHECK(standing->Couplers[end::rear].CouplingFlag == (Coupling::coupler | Coupling::brakeHose)); CHECK(moving->Couplers[end::front].Connected == &standing.mover()); CHECK_FALSE(derailed(moving)); CHECK_FALSE(derailed(standing)); @@ -423,7 +423,7 @@ TEST_CASE("couplers: an automatic coupler doesn't catch a coupler of another typ TEST_CASE("couplers: automatic couplers of different control systems couple without the control connection") { crash_damage_setting const crashdamage{true}; - auto const flag{coupling::coupler | coupling::brakehose | coupling::control}; + auto const flag{Coupling::coupler | Coupling::brakeHose | Coupling::control}; auto moving{vehicle{automatic_definition(flag).set("BuffCoupl", "ControlType", "first"), 5.0, "moving"}}; SUBCASE("the same control system") { @@ -438,7 +438,7 @@ TEST_CASE("couplers: automatic couplers of different control systems couple with REQUIRE(standing->Couplers[end::rear].control_type == "second"); test::pair pair{moving, end::front, standing, end::rear, 1.0}; REQUIRE(couple_during(pair, 3.0)); - CHECK(pair.coupling() == (coupling::coupler | coupling::brakehose)); + CHECK(pair.coupling() == (Coupling::coupler | Coupling::brakeHose)); } } @@ -488,8 +488,8 @@ vehicle articulated_wagon(double Velocity, std::string const &Name) { // couples the facing ends of the two vehicles for good, as the scenery does for an articulated set void join(vehicle &First, int FirstEnd, vehicle &Second, int SecondEnd) { - REQUIRE(First->Attach(FirstEnd, SecondEnd, &Second.mover(), coupling::coupler, true, false)); - REQUIRE(Second->Attach(SecondEnd, FirstEnd, &First.mover(), coupling::coupler, true, false)); + REQUIRE(First->Attach(FirstEnd, SecondEnd, &Second.mover(), Coupling::coupler, true, false)); + REQUIRE(Second->Attach(SecondEnd, FirstEnd, &First.mover(), Coupling::coupler, true, false)); } } // namespace @@ -560,12 +560,12 @@ private: bool m_previous{Global.control_coupling_engine_check}; }; -constexpr int scenario_coupling{coupling::coupler | coupling::brakehose | coupling::mainhose | coupling::control}; +constexpr CouplingSet scenario_coupling{Coupling::coupler | Coupling::brakeHose | Coupling::mainHose | Coupling::control}; // couples the rear of the first vehicle to the front of the second one the way the scenery does (forced, from the // first one only), returns the coupling the pair got -int scenario_couple(vehicle &First, vehicle &Second, int Coupling = scenario_coupling) { - REQUIRE(First->Attach(end::rear, end::front, &Second.mover(), Coupling, true, false)); +CouplingSet scenario_couple(vehicle &First, vehicle &Second, CouplingSet const couplings = scenario_coupling) { + REQUIRE(First->Attach(end::rear, end::front, &Second.mover(), couplings, true, false)); CHECK(Second->Couplers[end::front].CouplingFlag == First->Couplers[end::rear].CouplingFlag); return First->Couplers[end::rear].CouplingFlag; } @@ -582,13 +582,13 @@ TEST_CASE("couplers: an electric and a diesel locomotive don't share their contr auto diesel{vehicle{definition::fiz("sm42_v1/6d1"), 0.0, "diesel"}}; REQUIRE(diesel->EngineType == TEngineType::DieselElectric); CHECK_FALSE(electric->ControlCouplingAllowed(end::rear, diesel.mover(), end::front)); - CHECK(scenario_couple(electric, diesel) == (scenario_coupling & ~coupling::control)); + CHECK(scenario_couple(electric, diesel) == scenario_coupling.Without(Coupling::control)); } SUBCASE("a diesel-mechanical one without a control system named, either") { auto diesel{vehicle{definition::fiz("sm03_v1/sm03"), 0.0, "diesel"}}; REQUIRE(diesel->EngineType == TEngineType::DieselEngine); CHECK_FALSE(diesel->ControlCouplingAllowed(end::front, electric.mover(), end::rear)); - CHECK(scenario_couple(diesel, electric) == (scenario_coupling & ~coupling::control)); + CHECK(scenario_couple(diesel, electric) == scenario_coupling.Without(Coupling::control)); } SUBCASE("unless both name the same control system") { auto diesel{vehicle{definition::fiz("sm03_v1/sm03").set("BuffCoupl", "ControlType", "shared"), 0.0, "diesel"}}; @@ -597,7 +597,7 @@ TEST_CASE("couplers: an electric and a diesel locomotive don't share their contr } SUBCASE("unless the vehicles make one unit, coupled for good") { auto diesel{vehicle{definition::fiz("sm03_v1/sm03"), 0.0, "diesel"}}; - auto const forgood{scenario_coupling | coupling::permanent}; + auto const forgood{scenario_coupling | Coupling::permanent}; CHECK(scenario_couple(electric, diesel, forgood) == forgood); } SUBCASE("unless the check is turned off") { @@ -638,7 +638,7 @@ TEST_CASE("couplers: locomotives of the same traction and the cars keep their co TEST_CASE("couplers: automatic couplers of an electric and a diesel locomotive couple without the control connection") { crash_damage_setting const crashdamage{true}; control_coupling_check_setting const check{true}; - auto const flag{coupling::coupler | coupling::brakehose | coupling::control}; + auto const flag{Coupling::coupler | Coupling::brakeHose | Coupling::control}; auto automatic = [flag](std::string const &Path) { return definition::fiz(Path).set("BuffCoupl", "CType", "Automatic").set("BuffCoupl", "AutomaticFlag", flag); }; @@ -648,7 +648,7 @@ TEST_CASE("couplers: automatic couplers of an electric and a diesel locomotive c auto standing{vehicle{automatic("sm03_v1/sm03"), 0.0, "standing"}}; test::pair pair{moving, end::front, standing, end::rear, 1.0}; REQUIRE(couple_during(pair, 3.0)); - CHECK(pair.coupling() == (coupling::coupler | coupling::brakehose)); + CHECK(pair.coupling() == (Coupling::coupler | Coupling::brakeHose)); } SUBCASE("an electric one") { auto standing{vehicle{automatic("ep09_v2/104e"), 0.0, "standing"}}; @@ -664,8 +664,8 @@ TEST_CASE("couplers: the AI and the player get the coupling the vehicles can tak auto diesel{vehicle{definition::fiz("sm42_v1/6d1"), 0.0, "diesel"}}; auto other{vehicle{definition::fiz("ep09_v2/104e"), 0.0, "other"}}; - CHECK(electric->CompatibleCoupling(end::rear, diesel.mover(), end::front, scenario_coupling) == (scenario_coupling & ~coupling::control)); + CHECK(electric->CompatibleCoupling(end::rear, diesel.mover(), end::front, scenario_coupling) == scenario_coupling.Without(Coupling::control)); CHECK(electric->CompatibleCoupling(end::rear, other.mover(), end::front, scenario_coupling) == scenario_coupling); // nothing to take away without the control connection asked for - CHECK(electric->CompatibleCoupling(end::rear, diesel.mover(), end::front, coupling::coupler) == coupling::coupler); + CHECK(electric->CompatibleCoupling(end::rear, diesel.mover(), end::front, Coupling::coupler) == Coupling::coupler); } diff --git a/tests/unit/test_couplers_trains.cpp b/tests/unit/test_couplers_trains.cpp index cbe002bb1..cf4dc58b8 100644 --- a/tests/unit/test_couplers_trains.cpp +++ b/tests/unit/test_couplers_trains.cpp @@ -35,27 +35,27 @@ TEST_CASE("couplers: coupled by hand, touching or apart, of the same kind or not consist train; auto &locomotive{train.add(definition::fiz("4e_v1/4e")).mover()}; // the wagon's buffers touch the locomotive's, the unit's car stands a metre away - auto &wagon{train.add(definition::fiz("3wl_v2/3wl"), 0, coupling::faux).mover()}; + auto &wagon{train.add(definition::fiz("3wl_v2/3wl"), 0, Coupling::none).mover()}; train.step(); // nothing to couple to, or nothing to couple - CHECK_FALSE(locomotive.Attach(end::rear, end::front, nullptr, coupling::coupler)); - CHECK_FALSE(locomotive.Attach(end::rear, end::front, &wagon, coupling::faux)); + CHECK_FALSE(locomotive.Attach(end::rear, end::front, nullptr, Coupling::coupler)); + CHECK_FALSE(locomotive.Attach(end::rear, end::front, &wagon, Coupling::none)); // the hook first: the coupler alone, which sounds locomotive.Couplers[end::rear].sounds = 0; - REQUIRE(locomotive.Attach(end::rear, end::front, &wagon, coupling::coupler)); + REQUIRE(locomotive.Attach(end::rear, end::front, &wagon, Coupling::coupler)); CHECK(locomotive.Couplers[end::rear].Connected == &wagon); CHECK(wagon.Couplers[end::front].Connected == &locomotive); - CHECK(wagon.Couplers[end::front].CouplingFlag == coupling::coupler); + CHECK(wagon.Couplers[end::front].CouplingFlag == Coupling::coupler); CHECK(locomotive.Couplers[end::rear].sounds == sound::attachcoupler); // then the hoses: only what changes sounds locomotive.Couplers[end::rear].sounds = 0; - REQUIRE(locomotive.Attach(end::rear, end::front, &wagon, coupling::coupler | coupling::brakehose | coupling::mainhose)); + REQUIRE(locomotive.Attach(end::rear, end::front, &wagon, Coupling::coupler | Coupling::brakeHose | Coupling::mainHose)); CHECK(locomotive.Couplers[end::rear].sounds == (sound::attachbrakehose | sound::attachmainhose)); // and again, quietly, the other side naming the coupler by the one it's connected to (2) locomotive.Couplers[end::rear].sounds = 0; - REQUIRE(wagon.Attach(end::front, 2, &locomotive, coupling::coupler | coupling::brakehose, false, false)); - CHECK(locomotive.Couplers[end::rear].CouplingFlag == (coupling::coupler | coupling::brakehose)); + REQUIRE(wagon.Attach(end::front, 2, &locomotive, Coupling::coupler | Coupling::brakeHose, false, false)); + CHECK(locomotive.Couplers[end::rear].CouplingFlag == (Coupling::coupler | Coupling::brakeHose)); CHECK(locomotive.Couplers[end::rear].sounds == 0); // a screw coupler with the buffers pressed together comes apart whole @@ -74,20 +74,20 @@ TEST_CASE("couplers: a screw coupler uncoupled with the buffers apart, or with t struct state { char const *name; double gap; // between the buffers, the coupler stretched - int coupling; + CouplingSet coupling; bool damaged; bool apart; // whether it comes apart whole }; for (auto const &[name, gap, couplingtype, damaged, apart] : { - state{"stretched a little", 0.1, coupling::coupler | coupling::brakehose, false, false}, - state{"stretched far", 0.3, coupling::coupler | coupling::brakehose, false, true}, - state{"hoses alone", 0.1, coupling::brakehose, false, true}, - state{"broken", 0.1, coupling::coupler | coupling::brakehose, true, true}, + state{"stretched a little", 0.1, Coupling::coupler | Coupling::brakeHose, false, false}, + state{"stretched far", 0.3, Coupling::coupler | Coupling::brakeHose, false, true}, + state{"hoses alone", 0.1, Coupling::brakeHose, false, true}, + state{"broken", 0.1, Coupling::coupler | Coupling::brakeHose, true, true}, }) { CAPTURE(name); consist train; auto &locomotive{train.add(definition::fiz("4e_v1/4e")).mover()}; - auto &wagon{train.add(definition::fiz("3wl_v2/3wl"), 0, coupling::faux, 0.0, gap).mover()}; + auto &wagon{train.add(definition::fiz("3wl_v2/3wl"), 0, Coupling::none, 0.0, gap).mover()}; REQUIRE(locomotive.Attach(end::rear, end::front, &wagon, couplingtype, true)); if (damaged) { SetFlag(locomotive.DamageFlag, dtrain_coupling); @@ -96,16 +96,16 @@ TEST_CASE("couplers: a screw coupler uncoupled with the buffers apart, or with t CHECK((locomotive.DettachStatus(end::rear) < 0) == apart); CHECK(locomotive.Dettach(end::rear) == apart); // what's left when it doesn't come apart is the coupler, the hoses taken off - CHECK(locomotive.Couplers[end::rear].CouplingFlag == (apart ? coupling::faux : coupling::coupler)); - CHECK(wagon.Couplers[end::front].CouplingFlag == (apart ? coupling::faux : coupling::coupler)); + CHECK(locomotive.Couplers[end::rear].CouplingFlag == (apart ? Coupling::none : Coupling::coupler)); + CHECK(wagon.Couplers[end::front].CouplingFlag == (apart ? Coupling::none : Coupling::coupler)); } // couplers of different kinds don't couple, unless forced consist train; auto &locomotive{train.add(definition::fiz("4e_v1/4e")).mover()}; - auto &unit{train.add(definition::fiz("en57_v1/5bgb"), 0, coupling::faux).mover()}; + auto &unit{train.add(definition::fiz("en57_v1/5bgb"), 0, Coupling::none).mover()}; train.step(); - CHECK_FALSE(locomotive.Attach(end::rear, end::front, &unit, coupling::coupler)); - CHECK(locomotive.Attach(end::rear, end::front, &unit, coupling::coupler, true)); + CHECK_FALSE(locomotive.Attach(end::rear, end::front, &unit, Coupling::coupler)); + CHECK(locomotive.Attach(end::rear, end::front, &unit, Coupling::coupler, true)); } TEST_CASE("couplers: automatic couplers coupling on contact") { @@ -115,17 +115,17 @@ TEST_CASE("couplers: automatic couplers coupling on contact") { char const *name; char const *standing; // its rear coupler met char const *running; // its front coupler meets - int coupling; // what they couple: what both flags allow, the control cable only of one kind + CouplingSet coupling; // what they couple: what both flags allow, the control cable only of one kind }; for (auto const &[name, standing, running, couplingtype] : { - meeting{"en57 to en57", "en57_v1/5bgb", "en57_v1/5bgaiii_led_spot", 39}, - meeting{"impuls to en57", "en57_v1/5bgb", "impuls_v1/31we-a_pr", 39 & ~coupling::control}, - meeting{"en57 without the flag", "en57_v1/5bgaiii_led_spot", "en57_v1/6ba_840", coupling::coupler}, + meeting{"en57 to en57", "en57_v1/5bgb", "en57_v1/5bgaiii_led_spot", CouplingSet::FromBits(39)}, + meeting{"impuls to en57", "en57_v1/5bgb", "impuls_v1/31we-a_pr", CouplingSet::FromBits(39).Without(Coupling::control)}, + meeting{"en57 without the flag", "en57_v1/5bgaiii_led_spot", "en57_v1/6ba_840", Coupling::coupler}, }) { CAPTURE(name); scenario scenario{std::string{"couplers/automatic/"} + name, motion(), test::track{}}; scenario.add(standing, 0, consist::full_coupling); - scenario.add(running, 0, coupling::faux, 3.0, 0.2); + scenario.add(running, 0, Coupling::none, 3.0, 0.2); scenario.wait(10.0); auto &first{scenario.vehicle(0)}; auto &second{scenario.vehicle(1)}; @@ -147,8 +147,8 @@ TEST_CASE("couplers: a coupler broken, with its brake hose torn off") { locomotive.damage_coupler(end::rear); CHECK(TestFlag(locomotive.DamageFlag, dtrain_coupling)); CHECK(locomotive.AlarmChainFlag); - CHECK(locomotive.Couplers[end::rear].CouplingFlag == coupling::faux); - CHECK(wagon.Couplers[end::front].CouplingFlag == coupling::faux); + CHECK(locomotive.Couplers[end::rear].CouplingFlag == Coupling::none); + CHECK(wagon.Couplers[end::front].CouplingFlag == Coupling::none); // the front coupler of the wagon, broken on its own: no hose to tear wagon.damage_coupler(end::front); CHECK(TestFlag(wagon.DamageFlag, dtrain_coupling)); @@ -159,7 +159,7 @@ TEST_CASE("couplers: a coupler broken, with its brake hose torn off") { articulated.add(definition::fiz("impuls_v1/31we-b_pr")); unit.damage_coupler(end::rear); CHECK_FALSE(TestFlag(unit.DamageFlag, dtrain_coupling)); - CHECK(unit.Couplers[end::rear].CouplingFlag != coupling::faux); + CHECK(unit.Couplers[end::rear].CouplingFlag != Coupling::none); } TEST_CASE("couplers: collisions fast enough to derail") { @@ -184,7 +184,7 @@ TEST_CASE("couplers: collisions fast enough to derail") { CAPTURE(name); scenario scenario{std::string{"couplers/collision/"} + name, motion(), test::track{}}; scenario.add(frontpath, 0, consist::full_coupling, frontspeed); - scenario.add(back, 0, coupling::faux, backspeed, 20.0); + scenario.add(back, 0, Coupling::none, backspeed, 20.0); scenario.wait(10.0); CHECK(TestFlag(scenario.vehicle(0).DamageFlag, dtrain_out) == frontout); CHECK(TestFlag(scenario.vehicle(1).DamageFlag, dtrain_out) == backout); diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp index 4a3a8efa7..8fee07d9a 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -134,7 +134,7 @@ TEST_CASE("derailment: the model of eu07.ini") { TEST_CASE("derailment: the brake hoses tear") { model_setting const physical{global_settings::derailment_model::physical}; vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 150.0}; - eu07vehicle->Couplers[end::rear].CouplingFlag = coupling::coupler | coupling::brakehose; + eu07vehicle->Couplers[end::rear].CouplingFlag = Coupling::coupler | Coupling::brakeHose; test::track curve; curve.radius = 300.0; for (int step = 0; step < 20; ++step) { diff --git a/tests/unit/test_engine_start.cpp b/tests/unit/test_engine_start.cpp index c721e5a1a..59bb6af0e 100644 --- a/tests/unit/test_engine_start.cpp +++ b/tests/unit/test_engine_start.cpp @@ -111,7 +111,7 @@ TEST_CASE("engine start: only the vehicles with an engine and under control thro // coupled without the control cable, the other railcar isn't under the cab's control consist apart; auto &alone{apart.add(sn61(), 1).mover()}; - apart.add(sn61(), 0, coupling::coupler | coupling::brakehose); + apart.add(sn61(), 0, Coupling::coupler | Coupling::brakeHose); CHECK(engine_start::engine(alone, alone, 2) == nullptr); } diff --git a/tests/unit/test_genset.cpp b/tests/unit/test_genset.cpp index cadd39d28..33af24480 100644 --- a/tests/unit/test_genset.cpp +++ b/tests/unit/test_genset.cpp @@ -527,7 +527,7 @@ TEST_CASE("genset: one genset feeds the next car through the high voltage coupli consist train; auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 1).mover()}; auto &second{train.add(dragon().set("BuffCoupl", "AllowedFlag", 47)).mover()}; - REQUIRE((first.Couplers[end::rear].CouplingFlag & coupling::highvoltage) != 0); + REQUIRE(first.Couplers[end::rear].CouplingFlag.HasAny(Coupling::highVoltage)); wake(first); REQUIRE(first.TractionModeSwitch(traction_mode::genset)); first.GensetSwitch(true); @@ -553,11 +553,11 @@ TEST_CASE("genset: one genset feeds the next car through the high voltage coupli TEST_CASE("genset: the selector command travels along the train") { // two locomotives in multiple: the control line, no permanent coupling - auto const coupling{coupling::coupler | coupling::brakehose | coupling::mainhose | coupling::control}; + auto const coupling{Coupling::coupler | Coupling::brakeHose | Coupling::mainHose | Coupling::control}; consist train; auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 1).mover()}; auto &second{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 0, coupling).mover()}; - REQUIRE((first.Couplers[end::rear].CouplingFlag & coupling::control) != 0); + REQUIRE(first.Couplers[end::rear].CouplingFlag.HasAny(Coupling::control)); wake(first); train.run(1.0, no_wire); CHECK(first.TractionModeSwitch(traction_mode::genset, range_t::consist)); @@ -575,7 +575,7 @@ TEST_CASE("genset: the selector command travels along the train") { } TEST_CASE("genset: a selector command refused with the line breaker closed isn't passed on") { - auto const coupling{coupling::coupler | coupling::brakehose | coupling::mainhose | coupling::control}; + auto const coupling{Coupling::coupler | Coupling::brakeHose | Coupling::mainHose | Coupling::control}; consist train; auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 1).mover()}; auto &second{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 0, coupling).mover()}; @@ -595,7 +595,7 @@ TEST_CASE("genset: a selector command refused with the line breaker closed isn't } TEST_CASE("genset: a lead which starts its genset on its own passes the start switch on") { - auto const coupling{coupling::coupler | coupling::brakehose | coupling::mainhose | coupling::control}; + auto const coupling{Coupling::coupler | Coupling::brakeHose | Coupling::mainHose | Coupling::control}; consist train; auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47).set("Cntrl", "GensetStart", "Automatic"), 1).mover()}; auto &second{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 0, coupling).mover()}; diff --git a/tests/unit/test_pullee.cpp b/tests/unit/test_pullee.cpp index 7e2742f7a..41a3b69e2 100644 --- a/tests/unit/test_pullee.cpp +++ b/tests/unit/test_pullee.cpp @@ -18,7 +18,7 @@ using test::vehicle; namespace { -constexpr int hook_and_brake_hose{coupling::coupler | coupling::brakehose}; +constexpr CouplingSet hook_and_brake_hose{Coupling::coupler | Coupling::brakeHose}; // an EU07 with nobody in it, its brake pipe held by the test the way a driver's valve would hold it, and the // vehicle it hauls. Velocity as of a trainset of a scenery [km/h]: not 0, the vehicles are ready to depart, diff --git a/tests/unit/test_queries.cpp b/tests/unit/test_queries.cpp index d42232c2e..797e40534 100644 --- a/tests/unit/test_queries.cpp +++ b/tests/unit/test_queries.cpp @@ -51,7 +51,7 @@ TEST_CASE("queries: the damage of a vehicle as the driver's panel describes it") TEST_CASE("queries: the ammeters of a vehicle without power show the current of the ones it controls") { vehicle unpowered{definition::fiz("en57_v1/6ba_840")}; vehicle powered{definition::fiz("en57_v1/5bgb")}; - unpowered->Attach(end::rear, end::front, &powered.mover(), coupling::control, true, false); + unpowered->Attach(end::rear, end::front, &powered.mover(), Coupling::control, true, false); powered->Power = 600.0; powered->Itot = 321.7; unpowered->Power = 0.0; diff --git a/tests/unit/vehicle.cpp b/tests/unit/vehicle.cpp index afbac8680..7946d3d84 100644 --- a/tests/unit/vehicle.cpp +++ b/tests/unit/vehicle.cpp @@ -355,7 +355,7 @@ double pair::gap() const { return std::abs(m_vehicles[1].position - m_vehicles[0].position) - 0.5 * (first.Dim.L + second.Dim.L); } -int pair::coupling() const { +CouplingSet pair::coupling() const { return m_vehicles[0].owner->mover().Couplers[m_vehicles[0].end].CouplingFlag; } diff --git a/tests/unit/vehicle.h b/tests/unit/vehicle.h index 601ece1c5..97c4cf6a1 100644 --- a/tests/unit/vehicle.h +++ b/tests/unit/vehicle.h @@ -39,6 +39,10 @@ public: // sets the key of the section, adding either one when it's missing definition &set(std::string const &Section, std::string const &Key, nlohmann::ordered_json const &Value); + // a set of couplings, as the number the definition writes + definition &set(std::string const &Section, std::string const &Key, CouplingSet const Value) { + return set(Section, Key, Value.Bits()); + } // drops the whole section, with its rows, or one key of it definition &remove(std::string const &Section); definition &remove(std::string const &Section, std::string const &Key); @@ -148,9 +152,9 @@ public: void run(double Seconds, track const &Track = {}, double Dt = 0.01); // distance between the facing couplers [m], negative while the buffers are pressed in double gap() const; - // type of the coupling between the vehicles, coupling::faux when they aren't coupled - int coupling() const; - bool coupled() const { return coupling() != coupling::faux; } + // type of the coupling between the vehicles, Coupling::none when they aren't coupled + CouplingSet coupling() const; + bool coupled() const { return false == coupling().Empty(); } private: struct placement { diff --git a/utilities/translation.cpp b/utilities/translation.cpp index 24c1946bc..ec695b05b 100644 --- a/utilities/translation.cpp +++ b/utilities/translation.cpp @@ -419,25 +419,25 @@ std::string locale::label_cab_control(std::string const &Label) const std::string& locale::coupling_name(int c) { - static std::unordered_map coupling_names = + static std::unordered_map coupling_names = { - { coupling::faux, STRN("faux") }, - { coupling::coupler, STRN("coupler") }, - { coupling::brakehose, STRN("brake hose") }, - { coupling::control, STRN("control") }, - { coupling::highvoltage, STRN("high voltage") }, - { coupling::gangway, STRN("gangway") }, - { coupling::mainhose, STRN("main hose") }, - { coupling::heating, STRN("heating") }, - { coupling::permanent, STRN("permanent") }, - { coupling::power24v, STRN("power 24V") }, - { coupling::power110v, STRN("power 110V") }, - { coupling::power3x400v, STRN("power 3x400V") }, + { Coupling::none, STRN("faux") }, + { Coupling::coupler, STRN("coupler") }, + { Coupling::brakeHose, STRN("brake hose") }, + { Coupling::control, STRN("control") }, + { Coupling::highVoltage, STRN("high voltage") }, + { Coupling::gangway, STRN("gangway") }, + { Coupling::mainHose, STRN("main hose") }, + { Coupling::heating, STRN("heating") }, + { Coupling::permanent, STRN("permanent") }, + { Coupling::power24v, STRN("power 24V") }, + { Coupling::power110v, STRN("power 110V") }, + { Coupling::power3x400v, STRN("power 3x400V") }, }; static std::string unknown(STRN("unknown")); - auto it = coupling_names.find(static_cast(c)); + auto it = coupling_names.find(static_cast(c)); if (it != coupling_names.end()) return lookup_s(it->second); else diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 9ad82244d..a35244fc6 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -2504,7 +2504,7 @@ void TController::Activation() ZeroDirection(); mvOccupied->CabOccupied = mvOccupied->CabActive; // użytkownik moze zmienić CabOccupied wychodząc mvOccupied->CabDeactivisation(); // tak jest w Train.cpp - if (TestFlag(pVehicle->MoverParameters->Couplers[iDirectionOrder < 0 ? end::rear : end::front].CouplingFlag, coupling::control)) { + if (pVehicle->MoverParameters->Couplers[iDirectionOrder < 0 ? end::rear : end::front].CouplingFlag.HasAll(Coupling::control)) { ZeroLocalBrake(); if( initialspringbrakestate ) { mvOccupied->SpringBrakeActivate( false ); @@ -2517,7 +2517,7 @@ void TController::Activation() // TODO: clean this up, there's lot of redundancy with TMoverParameters::ChangeCab() and TTrain::MoveToVehicle() { int movedirection { ( iDirection < 0 ? end::rear : end::front ) }; - auto *targetvehicle { pVehicle->FirstFind( movedirection, coupling::control ) }; + auto *targetvehicle { pVehicle->FirstFind( movedirection, Coupling::control ) }; if( pVehicle != targetvehicle ) { auto *targetvehicledriver { targetvehicle->Mechanik }; // zapamiętanie tego, co ewentualnie tam siedzi, żeby w razie dwóch zamienić miejscami // move to the new vehicle @@ -2854,7 +2854,7 @@ bool TController::CheckVehicles(TOrders user) while (p) { if( p != pVehicle ) { - if( false == p->is_connected( pVehicle, coupling::control ) ) { + if( false == p->is_connected( pVehicle, Coupling::control ) ) { // NOTE: don't set battery in controllable vehicles, let the user/ai do it explicitly // HACK: wagony muszą mieć baterię załączoną do otwarcia drzwi... p->MoverParameters->BatterySwitch( true ); @@ -2883,8 +2883,8 @@ bool TController::CheckVehicles(TOrders user) if( user == Connect && true == main ) { // HACK: with additional vehicles in the consist ensure all linked vehicles are set to move in the same direction - if( pVehicle->Prev(coupling::control) != nullptr - || pVehicle->Next(coupling::control) != nullptr ) { + if( pVehicle->Prev(Coupling::control) != nullptr + || pVehicle->Next(Coupling::control) != nullptr ) { sync_consist_reversers(); } // potentially sync compartment lighting state for the newly connected vehicles @@ -2912,7 +2912,7 @@ bool TController::CheckVehicles(TOrders user) /* if( ( true == drivingFlags.connect ) && ( true == TestFlag( OrderCurrentGet(), Connect ) ) ) { - iCoupler = 0; // dalsza jazda manewrowa już bez łączenia + iCoupler = {}; // dalsza jazda manewrowa już bez łączenia drivingFlags.connect = false; // zdjęcie flagi doczepiania SetVelocity( 0, 0, stopJoin ); // wyłączyć przyspieszanie JumpToNextOrder(); // wykonanie następnej komendy @@ -2921,7 +2921,7 @@ bool TController::CheckVehicles(TOrders user) } // detect push-pull train configurations and mark them accordingly - if( frontvehicle->is_connected( pVehicles[ end::rear ], coupling::control ) ) { + if( frontvehicle->is_connected( pVehicles[ end::rear ], Coupling::control ) ) { // zmiana czoła przez zmianę kabiny drivingFlags.pushPull = true; } @@ -2957,7 +2957,7 @@ bool TController::CheckVehicles(TOrders user) // TODO: replace connection test with connection check between last engine and first car, specifically auto const isheatingcouplingactive { ( ControlledEnginesCount == 1 ? - frontvehicle->is_connected( pVehicles[ end::rear ], coupling::heating ) : + frontvehicle->is_connected( pVehicles[ end::rear ], Coupling::heating ) : true ) }; auto const isheatingneeded { (is_emu() || is_dmu() ? true : @@ -3023,9 +3023,9 @@ TBrakeSystem TController::consist_brake_system() const { // NOTE: we could simplify this by doing only check of the rear coupler, but this can be quite tricky in itself // TODO: add easier ways to access front/rear coupler taking into account vehicle's direction isepcapable = (vehicle->MoverParameters->Couplers[end::front].Connected == nullptr || - (vehicle->MoverParameters->Couplers[end::front].CouplingFlag & coupling::control && vehicle->MoverParameters->Couplers[end::front].Connected->Power > -1)) && + (vehicle->MoverParameters->Couplers[end::front].CouplingFlag & Coupling::control && vehicle->MoverParameters->Couplers[end::front].Connected->Power > -1)) && (vehicle->MoverParameters->Couplers[end::rear].Connected == nullptr || - (vehicle->MoverParameters->Couplers[end::rear].CouplingFlag & coupling::control && vehicle->MoverParameters->Couplers[end::rear].Connected->Power > -1)); + (vehicle->MoverParameters->Couplers[end::rear].CouplingFlag & Coupling::control && vehicle->MoverParameters->Couplers[end::rear].Connected->Power > -1)); vehicle = vehicle->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) } } @@ -3634,11 +3634,11 @@ bool TController::IncBrake() || mvOccupied->TrainType == train_type::et42 ) { // NOTE: we're doing simplified checks full of presuptions here. // they'll break if someone does strange thing like turning around the second unit - if( mvOccupied->Couplers[end::rear].CouplingFlag & coupling::permanent + if( mvOccupied->Couplers[end::rear].CouplingFlag & Coupling::permanent && mvOccupied->Couplers[end::rear].Connected->Couplers[end::rear].Connected != nullptr ) { standalone = false; } - if( mvOccupied->Couplers[end::front].CouplingFlag & coupling::permanent + if( mvOccupied->Couplers[end::front].CouplingFlag & Coupling::permanent && mvOccupied->Couplers[end::front].Connected->Couplers[end::front].Connected != nullptr ) { standalone = false; } @@ -3655,8 +3655,8 @@ bool TController::IncBrake() else { /* standalone = - ( ( mvOccupied->Couplers[ 0 ].CouplingFlag == 0 ) - && ( mvOccupied->Couplers[ 1 ].CouplingFlag == 0 ) ); + ( ( mvOccupied->Couplers[ 0 ].CouplingFlag.Empty() ) + && ( mvOccupied->Couplers[ 1 ].CouplingFlag.Empty() ) ); */ if( pVehicles[ end::front ] != pVehicles[ end::rear ] ) { // more detailed version, will use manual braking also for coupled sets of controlled vehicles @@ -3667,9 +3667,9 @@ bool TController::IncBrake() // TODO: add easier ways to access front/rear coupler taking into account vehicle's direction standalone = (vehicle->MoverParameters->Couplers[end::front].Connected == nullptr || - (vehicle->MoverParameters->Couplers[end::front].CouplingFlag & coupling::control && vehicle->MoverParameters->Couplers[end::front].Connected->Power > 1)) && + (vehicle->MoverParameters->Couplers[end::front].CouplingFlag & Coupling::control && vehicle->MoverParameters->Couplers[end::front].Connected->Power > 1)) && (vehicle->MoverParameters->Couplers[end::rear].Connected == nullptr || - (vehicle->MoverParameters->Couplers[end::rear].CouplingFlag & coupling::control && vehicle->MoverParameters->Couplers[end::rear].Connected->Power > 1)); + (vehicle->MoverParameters->Couplers[end::rear].CouplingFlag & Coupling::control && vehicle->MoverParameters->Couplers[end::rear].Connected->Power > 1)); vehicle = vehicle->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) } } @@ -5327,7 +5327,7 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N } if (NewValue2 != 0) // jeśli podany jest sprzęg { - iCoupler = std::floor( std::abs( NewValue2 ) ); // jakim sprzęgiem + iCoupler = CouplingSet::FromBits( static_cast( std::floor( std::abs( NewValue2 ) ) ) ); // jakim sprzęgiem OrderNext(Connect); // najpierw połącz pojazdy if (NewValue1 >= 0.0) // jeśli ilość wagonów inna niż wszystkie { // to po podpięciu należy się odczepić @@ -6764,7 +6764,7 @@ TController::determine_consist_state() { auto islocalconverterswitchoff { false }; pVehicle->for_each( - coupling::control, + Coupling::control, [this, &islocalconverterswitchoff]( TDynamicObject * Vehicle ) { auto const *vehicle { Vehicle->MoverParameters }; islocalconverterswitchoff |= vehicle->LineContactorsHeldByLocalConverterSwitch(); @@ -6982,7 +6982,7 @@ TController::control_pantographs() { // raise/lower pantographs as needed auto const useregularpantographlayout { - pVehicle->Next(coupling::control) == nullptr // standalone + pVehicle->Next(Coupling::control) == nullptr // standalone || is_emu() // special case || mvControlling->TrainType == train_type::et41 }; // special case @@ -7642,7 +7642,7 @@ TController::check_departure() { } } } - else if( VelSignal == 0.0 && VelNext > 0.0 && mvOccupied->Vel < 1.0 && (iCoupler > 0 || ( false == drivingFlags.stopHere )) ) { + else if( VelSignal == 0.0 && VelNext > 0.0 && mvOccupied->Vel < 1.0 && (false == iCoupler.Empty() || ( false == drivingFlags.stopHere )) ) { // Ra: tu jest coś nie tak, bo bez tego warunku ruszało w manewrowym !!!! SetVelocity(VelNext, VelNext, stopSem); // omijanie SBL } @@ -7823,7 +7823,7 @@ TController::UpdateConnect() { // jeżeli został podłączony CheckVehicles( Connect ); // sprawdzić światła nowego składu - iCoupler = 0; // dalsza jazda manewrowa już bez łączenia + iCoupler = {}; // dalsza jazda manewrowa już bez łączenia iCouplingVehicle.reset(); drivingFlags.connect = false; // zdjęcie flagi doczepiania JumpToNextOrder( true ); // wykonanie następnej komendy @@ -7873,11 +7873,11 @@ TController::unit_count( int const Threshold ) const { end::rear : end::front ) }; auto const coupling { vehicle->MoverParameters->Couplers[ decoupledend ].CouplingFlag }; - if( coupling == coupling::faux ) { + if( coupling == Coupling::none ) { break; } // jeżeli sprzęg zablokowany to liczymy człony jako jeden - if( ( coupling & coupling::permanent ) == 0 ) { + if( false == coupling.HasAny( Coupling::permanent ) ) { ++unitcount; } vehicle = vehicle->Next(); @@ -7920,7 +7920,7 @@ TController::UpdateDisconnect() { end::front : end::rear; // jeżeli sprzęg zablokowany to liczymy człony jako jeden - if( decoupledvehicle->MoverParameters->Couplers[ decoupledend ].CouplingFlag & coupling::permanent ) { + if( decoupledvehicle->MoverParameters->Couplers[ decoupledend ].CouplingFlag & Coupling::permanent ) { ++vehiclecount; } if( decoupledvehicle != pVehicle ) { @@ -7943,7 +7943,7 @@ TController::UpdateDisconnect() { decoupledvehicle->Dettach( decoupledend ); } // tylko jeśli odepnie - if( decoupledvehicle->MoverParameters->Couplers[ decoupledend ].CouplingFlag == coupling::faux ) { + if( decoupledvehicle->MoverParameters->Couplers[ decoupledend ].CouplingFlag == Coupling::none ) { WriteLog( "Uncoupling [" + mvOccupied->Name + "]: uncoupled" ); iVehicleCount = -2; // update trainset state @@ -9589,7 +9589,7 @@ TController::check_route_ahead( double const Range ) { if( ( OrderCurrentGet() & ~( Shunt | Loose_shunt | Obey_train | Bank ) ) == 0 ) { // jedzie w dowolnym trybie albo Wait_for_orders PutCommand( "ShuntVelocity", VelSignal, VelNext, nullptr ); } - else if( iCoupler ) { // jeśli jedzie w celu połączenia + else if( false == iCoupler.Empty() ) { // jeśli jedzie w celu połączenia SetVelocity( VelSignal, VelNext ); } break; diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 8cf80ddcf..7592e6eac 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -477,7 +477,7 @@ private: std::optional iDirectionBackup; // consist direction to be restored after coupling/uncoupling and similar direction-changing operations std::optional> iCouplingVehicle; // to be coupled with another consist in current coupling operation int iVehicleCount = -2; // wartość neutralna // ilość pojazdów do odłączenia albo zabrania ze składu (-1=wszystkie) - int iCoupler = 0; // maska sprzęgu, jaką należy użyć przy łączeniu (po osiągnięciu trybu Connect), 0 gdy jazda bez łączenia + CouplingSet iCoupler; // maska sprzęgu, jaką należy użyć przy łączeniu (po osiągnięciu trybu Connect), 0 gdy jazda bez łączenia int iDriverFailCount = 0; // licznik błędów AI bool Need_TryAgain = false; // true, jeśli druga pozycja w elektryku nie załapała // bool Need_BrakeRelease = true; diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index b2f6a268e..951e614fb 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -299,7 +299,7 @@ bool TDynamicObject::destination_data::deserialize_mapping( cParser &Input ) { //--------------------------------------------------------------------------- -TDynamicObject * TDynamicObject::FirstFind(int &coupler_nr, int cf) +TDynamicObject * TDynamicObject::FirstFind(int &coupler_nr, CouplingSet const cf) { // szukanie skrajnego połączonego pojazdu w pociagu // od strony sprzegu (coupler_nr) obiektu (start) TDynamicObject *temp = this; @@ -307,7 +307,7 @@ TDynamicObject * TDynamicObject::FirstFind(int &coupler_nr, int cf) { if (!temp) return nullptr; // Ra: zabezpieczenie przed ewentaulnymi błędami sprzęgów - if ((temp->MoverParameters->Couplers[coupler_nr].CouplingFlag & cf) != cf) + if (false == temp->MoverParameters->Couplers[coupler_nr].CouplingFlag.HasAll(cf)) return temp; // nic nie ma już dalej podłączone sprzęgiem cf if (coupler_nr == end::front) { // jeżeli szukamy od sprzęgu 0 @@ -350,7 +350,7 @@ float TDynamicObject::GetEPP() break; // Ra: zabezpieczenie przed ewentaulnymi błędami sprzęgów eq += temp->MoverParameters->PipePress * temp->MoverParameters->Dim.L; am += temp->MoverParameters->Dim.L; - if ((temp->MoverParameters->Couplers[coupler_nr].CouplingFlag & coupling::brakehose) != coupling::brakehose) + if ((temp->MoverParameters->Couplers[coupler_nr].CouplingFlag & Coupling::brakeHose) != Coupling::brakeHose) break; // nic nie ma już dalej podłączone if (coupler_nr == 0) { // jeżeli szukamy od sprzęgu 0 @@ -384,7 +384,7 @@ float TDynamicObject::GetEPP() break; // Ra: zabezpieczenie przed ewentaulnymi błędami sprzęgów eq += temp->MoverParameters->PipePress * temp->MoverParameters->Dim.L; am += temp->MoverParameters->Dim.L; - if ((temp->MoverParameters->Couplers[coupler_nr].CouplingFlag & coupling::brakehose) != coupling::brakehose) + if ((temp->MoverParameters->Couplers[coupler_nr].CouplingFlag & Coupling::brakeHose) != Coupling::brakeHose) break; // nic nie ma już dalej podłączone if (coupler_nr == 0) { // jeżeli szukamy od sprzęgu 0 @@ -415,7 +415,7 @@ float TDynamicObject::GetEPP() }; //--------------------------------------------------------------------------- -TDynamicObject * TDynamicObject::GetFirstDynamic(int cpl_type, int cf) +TDynamicObject * TDynamicObject::GetFirstDynamic(int cpl_type, CouplingSet const cf) { // Szukanie skrajnego połączonego pojazdu w pociagu // od strony sprzegu (cpl_type) obiektu szukajacego // Ra: wystarczy jedna funkcja do szukania w obu kierunkach @@ -930,7 +930,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) // display _xon if connected with another vehicle and not the coupling owner // display _xon if not connected, but equipped with coupling adapter // display _off if not connected, not equipped with coupling adapter or if _xon model is missing - if( TestFlag( MoverParameters->Couplers[ end::front ].CouplingFlag, coupling::coupler ) ) { + if( MoverParameters->Couplers[ end::front ].CouplingFlag.HasAll(Coupling::coupler) ) { if( MoverParameters->Couplers[ end::front ].Render ) { btCoupler1.TurnOn(); } @@ -945,7 +945,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) btnOn = true; } } - if( TestFlag( MoverParameters->Couplers[ end::rear ].CouplingFlag, coupling::coupler ) ) { + if( MoverParameters->Couplers[ end::rear ].CouplingFlag.HasAll(Coupling::coupler) ) { if( MoverParameters->Couplers[ end::rear ].Render ) { btCoupler2.TurnOn(); } @@ -972,7 +972,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) SetPneumatic(true, true); // ktore z nich nalezy SetPneumatic(false, true); // wyswietlic w tej klatce - if (TestFlag(MoverParameters->Couplers[end::front].CouplingFlag, ctrain_pneumatic)) + if (MoverParameters->Couplers[end::front].CouplingFlag.HasAll(Coupling::brakeHose)) { switch (cp1) { @@ -992,7 +992,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) btnOn = true; } - if (TestFlag(MoverParameters->Couplers[end::rear].CouplingFlag, ctrain_pneumatic)) + if (MoverParameters->Couplers[end::rear].CouplingFlag.HasAll(Coupling::brakeHose)) { switch (cp2) { @@ -1013,7 +1013,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } // przewody zasilajace, j.w. (yB) - if (TestFlag(MoverParameters->Couplers[end::front].CouplingFlag, ctrain_scndpneumatic)) + if (MoverParameters->Couplers[end::front].CouplingFlag.HasAll(Coupling::mainHose)) { switch (sp1) { @@ -1033,7 +1033,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) btnOn = true; } - if (TestFlag(MoverParameters->Couplers[end::rear].CouplingFlag, ctrain_scndpneumatic)) + if (MoverParameters->Couplers[end::rear].CouplingFlag.HasAll(Coupling::mainHose)) { switch (sp2) { @@ -1058,7 +1058,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) { // przewody powietrzne j.w., ABu: decyzja czy rysowac tylko na podstawie // 'render' - if (TestFlag(MoverParameters->Couplers[end::front].CouplingFlag, ctrain_pneumatic)) + if (MoverParameters->Couplers[end::front].CouplingFlag.HasAll(Coupling::brakeHose)) { if (MoverParameters->Couplers[end::front].Render) btCPneumatic1.TurnOn(); @@ -1067,7 +1067,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) btnOn = true; } - if (TestFlag(MoverParameters->Couplers[end::rear].CouplingFlag, ctrain_pneumatic)) + if (MoverParameters->Couplers[end::rear].CouplingFlag.HasAll(Coupling::brakeHose)) { if (MoverParameters->Couplers[end::rear].Render) btCPneumatic2.TurnOn(); @@ -1079,7 +1079,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) // przewody powietrzne j.w., ABu: decyzja czy rysowac tylko na podstawie // 'render' // //yB - zasilajace - if (TestFlag(MoverParameters->Couplers[0].CouplingFlag, ctrain_scndpneumatic)) + if (MoverParameters->Couplers[0].CouplingFlag.HasAll(Coupling::mainHose)) { if (MoverParameters->Couplers[0].Render) btPneumatic1.TurnOn(); @@ -1088,7 +1088,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) btnOn = true; } - if (TestFlag(MoverParameters->Couplers[1].CouplingFlag, ctrain_scndpneumatic)) + if (MoverParameters->Couplers[1].CouplingFlag.HasAll(Coupling::mainHose)) { if (MoverParameters->Couplers[1].Render) btPneumatic2.TurnOn(); @@ -1124,26 +1124,26 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) // Winger 160204 - podnoszenie pantografow // przewody sterowania ukrotnionego - if (TestFlag(MoverParameters->Couplers[0].CouplingFlag, coupling::control)) + if (MoverParameters->Couplers[0].CouplingFlag.HasAll(Coupling::control)) { btCCtrl1.Turn( true ); btnOn = true; } // else btCCtrl1.TurnOff(); - if (TestFlag(MoverParameters->Couplers[1].CouplingFlag, coupling::control)) + if (MoverParameters->Couplers[1].CouplingFlag.HasAll(Coupling::control)) { btCCtrl2.Turn( true ); btnOn = true; } // else btCCtrl2.TurnOff(); // McZapkie-181103: mostki przejsciowe - if (TestFlag(MoverParameters->Couplers[0].CouplingFlag, ctrain_passenger)) + if (MoverParameters->Couplers[0].CouplingFlag.HasAll(Coupling::gangway)) { btCPass1.Turn( true ); btnOn = true; } // else btCPass1.TurnOff(); - if (TestFlag(MoverParameters->Couplers[1].CouplingFlag, ctrain_passenger)) + if (MoverParameters->Couplers[1].CouplingFlag.HasAll(Coupling::gangway)) { btCPass2.Turn( true ); btnOn = true; @@ -1625,8 +1625,8 @@ TDynamicObject::ABuFindObject( int &Foundcoupler, double &Distance, TTrack const continue; } /* - if( ( ( dynamic == PrevConnected ) && ( MoverParameters->Couplers[ TMoverParameters::side::front ].CouplingFlag != coupling::faux ) ) - || ( ( dynamic == NextConnected ) && ( MoverParameters->Couplers[ TMoverParameters::side::rear ].CouplingFlag != coupling::faux ) ) ){ + if( ( ( dynamic == PrevConnected ) && ( MoverParameters->Couplers[ TMoverParameters::side::front ].CouplingFlag != Coupling::none ) ) + || ( ( dynamic == NextConnected ) && ( MoverParameters->Couplers[ TMoverParameters::side::rear ].CouplingFlag != Coupling::none ) ) ){ // stop-gap check to prevent 'detection' of attached vehicles // which seems to be a side-effect of inaccurate location calculation in 'simple' mode? // TODO: investigate actual cause @@ -1686,7 +1686,7 @@ int TDynamicObject::DettachStatus(int dir) // rzeczywistych od strony (dir): // 0=przód,1=tył // Ra: dziwne, że ta funkcja nie jest używana - if( MoverParameters->Couplers[ dir ].CouplingFlag == coupling::faux ) { + if( MoverParameters->Couplers[ dir ].CouplingFlag == Coupling::none ) { return 0; // jeśli nic nie podłączone, to jest OK } return MoverParameters->DettachStatus(dir); // czy jest w odpowiedniej odległości? @@ -1725,7 +1725,7 @@ int TDynamicObject::Dettach(int dir) */ } // sprzęg po rozłączaniu (czego się nie da odpiąć - return MoverParameters->Couplers[dir].CouplingFlag; + return MoverParameters->Couplers[dir].CouplingFlag.Bits(); } void @@ -1740,15 +1740,15 @@ TDynamicObject::couple( int const Side ) { auto *othervehicleparams{ othervehicle->MoverParameters }; auto const &othercoupler { othervehicleparams->Couplers[ neighbour.vehicle_end ] }; - if( coupler.CouplingFlag == coupling::faux ) { + if( coupler.CouplingFlag == Coupling::none ) { // najpierw hak if( ( coupler.AllowedFlag & othercoupler.AllowedFlag - & coupling::coupler ) == coupling::coupler ) { + & Coupling::coupler ) == Coupling::coupler ) { if( MoverParameters->Attach( Side, neighbour.vehicle_end, othervehicleparams, - coupling::coupler ) ) { + Coupling::coupler ) ) { // one coupling type per key press return; } @@ -1757,15 +1757,15 @@ TDynamicObject::couple( int const Side ) { } } } - if( false == TestFlag( MoverParameters->Couplers[ Side ].CouplingFlag, coupling::brakehose ) ) { + if( false == MoverParameters->Couplers[ Side ].CouplingFlag.HasAll(Coupling::brakeHose) ) { // pneumatyka if( ( coupler.AllowedFlag & othercoupler.AllowedFlag - & coupling::brakehose ) == coupling::brakehose ) { + & Coupling::brakeHose ) == Coupling::brakeHose ) { if( MoverParameters->Attach( Side, neighbour.vehicle_end, othervehicleparams, - coupler.CouplingFlag | coupling::brakehose ) ) { + coupler.CouplingFlag | Coupling::brakeHose ) ) { SetPneumatic( Side != 0, true ); othervehicle->SetPneumatic( Side != 0, true ); // one coupling type per key press @@ -1773,15 +1773,15 @@ TDynamicObject::couple( int const Side ) { } } } - if( false == TestFlag( MoverParameters->Couplers[ Side ].CouplingFlag, coupling::mainhose ) ) { + if( false == MoverParameters->Couplers[ Side ].CouplingFlag.HasAll(Coupling::mainHose) ) { // zasilajacy if( ( coupler.AllowedFlag & othercoupler.AllowedFlag - & coupling::mainhose ) == coupling::mainhose ) { + & Coupling::mainHose ) == Coupling::mainHose ) { if( MoverParameters->Attach( Side, neighbour.vehicle_end, othervehicleparams, - coupler.CouplingFlag | coupling::mainhose ) ) { + coupler.CouplingFlag | Coupling::mainHose ) ) { SetPneumatic( Side != 0, false ); othervehicle->SetPneumatic( Side != 0, false ); // one coupling type per key press @@ -1789,43 +1789,43 @@ TDynamicObject::couple( int const Side ) { } } } - if( false == TestFlag( MoverParameters->Couplers[ Side ].CouplingFlag, coupling::control ) ) { + if( false == MoverParameters->Couplers[ Side ].CouplingFlag.HasAll(Coupling::control) ) { // ukrotnionko - if( (coupler.AllowedFlag & othercoupler.AllowedFlag & coupling::control) == coupling::control + if( (coupler.AllowedFlag & othercoupler.AllowedFlag & Coupling::control) == Coupling::control && coupler.control_type == othercoupler.control_type - && ( MoverParameters->CompatibleCoupling( Side, *othervehicleparams, neighbour.vehicle_end, coupler.CouplingFlag | coupling::control ) & coupling::control ) != 0 ) { + && MoverParameters->CompatibleCoupling( Side, *othervehicleparams, neighbour.vehicle_end, coupler.CouplingFlag | Coupling::control ).HasAny( Coupling::control ) ) { if( MoverParameters->Attach( Side, neighbour.vehicle_end, othervehicleparams, - coupler.CouplingFlag | coupling::control ) ) { + coupler.CouplingFlag | Coupling::control ) ) { // one coupling type per key press return; } } } - if( false == TestFlag( MoverParameters->Couplers[ Side ].CouplingFlag, coupling::gangway ) ) { + if( false == MoverParameters->Couplers[ Side ].CouplingFlag.HasAll(Coupling::gangway) ) { // mostek if( ( coupler.AllowedFlag & othercoupler.AllowedFlag - & coupling::gangway ) == coupling::gangway ) { + & Coupling::gangway ) == Coupling::gangway ) { if( MoverParameters->Attach( Side, neighbour.vehicle_end, othervehicleparams, - coupler.CouplingFlag | coupling::gangway ) ) { + coupler.CouplingFlag | Coupling::gangway ) ) { // one coupling type per key press return; } } } - if( false == TestFlag( MoverParameters->Couplers[ Side ].CouplingFlag, coupling::heating ) ) { + if( false == MoverParameters->Couplers[ Side ].CouplingFlag.HasAll(Coupling::heating) ) { // heating if( ( coupler.AllowedFlag & othercoupler.AllowedFlag - & coupling::heating ) == coupling::heating ) { + & Coupling::heating ) == Coupling::heating ) { if( MoverParameters->Attach( Side, neighbour.vehicle_end, othervehicleparams, - coupler.CouplingFlag | coupling::heating ) ) { + coupler.CouplingFlag | Coupling::heating ) ) { // one coupling type per key press return; } @@ -1838,9 +1838,9 @@ int TDynamicObject::uncouple( int const Side ) { if( DettachStatus(Side) >= 0 - || true == TestFlag(MoverParameters->Couplers[Side].CouplingFlag, coupling::permanent) ) { + || true == MoverParameters->Couplers[Side].CouplingFlag.HasAll(Coupling::permanent) ) { // can't uncouple, return existing coupling state - return MoverParameters->Couplers[ Side ].CouplingFlag; + return MoverParameters->Couplers[ Side ].CouplingFlag.Bits(); } // jeżeli sprzęg niezablokowany, jest co odczepić i się da auto const couplingflag { Dettach( Side ) }; @@ -3278,7 +3278,7 @@ void TDynamicObject::pull_neighbours( double const Distance ) { for( int end = end::front; end <= end::rear; ++end ) { auto const &coupler { MoverParameters->Couplers[ end ] }; auto *neighbour { MoverParameters->Neighbours[ end ].vehicle }; - if( coupler.CouplingFlag == coupling::faux || neighbour == nullptr || neighbour->MoverParameters->OffTrack.active() + if( coupler.CouplingFlag == Coupling::none || neighbour == nullptr || neighbour->MoverParameters->OffTrack.active() || TestFlag( neighbour->MoverParameters->DamageFlag, dtrain_out ) ) { m_pulledoff[ end ].reset(); continue; @@ -3337,7 +3337,7 @@ void TDynamicObject::AttachNext(TDynamicObject *Object, int iType) auto const vehicleend { iDirection }; auto const othervehicleend { Object->iDirection ^ 1 }; - MoverParameters->Attach( vehicleend, othervehicleend, Object->MoverParameters, iType, true, false ); + MoverParameters->Attach( vehicleend, othervehicleend, Object->MoverParameters, CouplingSet::FromBits( iType ), true, false ); // update neighbour data for both affected vehicles update_neighbours(); Object->update_neighbours(); @@ -3779,8 +3779,8 @@ bool TDynamicObject::Update(double dt, double dt1) tp.Name = &MyTrack->name(); // couplers - if( MoverParameters->Couplers[0].CouplingFlag != coupling::faux - && MoverParameters->Couplers[1].CouplingFlag != coupling::faux ) { + if( MoverParameters->Couplers[0].CouplingFlag != Coupling::none + && MoverParameters->Couplers[1].CouplingFlag != Coupling::none ) { MoverParameters->InsideConsist = true; } else { @@ -3895,8 +3895,8 @@ bool TDynamicObject::Update(double dt, double dt1) // 2. ustal mozliwa do realizacji sile hamowania ED // - w szczegolnosci powinien brac pod uwage rozne sily hamowania - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, 4); p; - kier ? p = p->Next(4) : p = p->Prev(4)) + for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, Coupling::control); p; + kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) { ++np; masamax += @@ -4047,8 +4047,8 @@ bool TDynamicObject::Update(double dt, double dt1) ////ALGORYTM 2 - KAZDEMU PO ROWNO, ale nie wiecej niz eped * masa // 1. najpierw daj kazdemu tyle samo int i = 0; - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, 4); p; - p = kier == true ? p->Next(4) : p->Prev(4) ) + for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, Coupling::control); p; + p = kier == true ? p->Next(Coupling::control) : p->Prev(Coupling::control) ) { auto const Nmax = ((p->MoverParameters->P2FTrans * p->MoverParameters->MaxBrakePress[0] - p->MoverParameters->BrakeCylSpring) * @@ -4075,8 +4075,8 @@ bool TDynamicObject::Update(double dt, double dt1) test = false; i = 0; float przek = 0; - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, 4); p; - p = kier == true ? p->Next(4) : p->Prev(4) ) + for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, Coupling::control); p; + p = kier == true ? p->Next(Coupling::control) : p->Prev(Coupling::control) ) { if (FzEP[i] > 0.01 && FzEP[i] > p->MoverParameters->TotalMass * p->MoverParameters->eimc[eimc_p_eped] + std::min(p->MoverParameters->eimv[eimv_Fmax], 0.) * 1000 && @@ -4099,8 +4099,8 @@ bool TDynamicObject::Update(double dt, double dt1) } i = 0; przek = przek / (np - nPrzekrF); - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, 4); p; - true == kier ? p = p->Next(4) : p = p->Prev(4)) + for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, Coupling::control); p; + true == kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) { if (!PrzekrF[i]) { @@ -4110,8 +4110,8 @@ bool TDynamicObject::Update(double dt, double dt1) } } i = 0; - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, 4); p; - true == kier ? p = p->Next(4) : p = p->Prev(4)) + for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, Coupling::control); p; + true == kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) { float Nmax = ((p->MoverParameters->P2FTrans * p->MoverParameters->MaxBrakePress[0] - p->MoverParameters->BrakeCylSpring) * @@ -4163,8 +4163,8 @@ bool TDynamicObject::Update(double dt, double dt1) { MEDLogFile << MEDLogTime << "\t" << MoverParameters->Vel << "\t" << masa*0.001 << "\t" << osie << "\t" << FmaxPN*0.001 << "\t" << FmaxED*0.001 << "\t" << FfulED*0.001 << "\t" << FrED*0.001 << "\t" << Fzad*0.001 << "\t" << FzadED*0.001 << "\t" << FzadPN*0.001; - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, 4); p; - true == kier ? p = p->Next(4) : p = p->Prev(4)) + for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, Coupling::control); p; + true == kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) { MEDLogFile << "\t" << p->MoverParameters->BrakePress; } @@ -4857,15 +4857,15 @@ void TDynamicObject::pants_up() { isAnyPantUp |= item.is_active; } - d = d->Next(4); // pozostałe też + d = d->Next(Coupling::control); // pozostałe też } - d = Prev(4); + d = Prev(Coupling::control); while (d) { for (auto &item : d->MoverParameters->Pantographs) { isAnyPantUp |= item.is_active; } - d = d->Prev(4); // w drugą stronę też + d = d->Prev(Coupling::control); // w drugą stronę też } if (isAnyPantUp) { @@ -4873,13 +4873,13 @@ void TDynamicObject::pants_up() while (d) { d->MoverParameters->OperatePantographValve(end::front, operation_t::enable, range_t::local); d->MoverParameters->OperatePantographValve(end::rear, operation_t::enable, range_t::local); - d = d->Next(4); // pozostałe też + d = d->Next(Coupling::control); // pozostałe też } - d = Prev(4); + d = Prev(Coupling::control); while (d) { d->MoverParameters->OperatePantographValve(end::front, operation_t::enable, range_t::local); d->MoverParameters->OperatePantographValve(end::rear, operation_t::enable, range_t::local); - d = d->Prev(4); // w drugą stronę też + d = d->Prev(Coupling::control); // w drugą stronę też } } } @@ -8012,17 +8012,17 @@ void TDynamicObject::SetLights() { automaticmarkers > 0 ? automaticmarkers : MoverParameters->Lights[ end::rear ][ lightpos ] }; // the custom position keeps the lights lit at coupled ends as well auto const ignorecouplings { MoverParameters->LightsPos == 18 }; - auto *vehicle { GetFirstDynamic( MoverParameters->CabOccupied >= 0 ? end::front : end::rear, coupling::control ) }; + auto *vehicle { GetFirstDynamic( MoverParameters->CabOccupied >= 0 ? end::front : end::rear, Coupling::control ) }; while( vehicle != nullptr ) { // set lights on given side if there's no coupling with another vehicle, turn them off otherwise auto const iscoupled { [ vehicle, ignorecouplings ]( end const Side ) { return false == ignorecouplings - && ( vehicle->MoverParameters->Couplers[ Side ].CouplingFlag & coupling::coupler ) != 0 + && vehicle->MoverParameters->Couplers[ Side ].CouplingFlag.HasAny(Coupling::coupler) && vehicle->MoverParameters->Neighbours[ Side ].vehicle != nullptr; } }; auto const lights { lights_programmer::vehicle_lights( cablights, isfrontcaboccupied, vehicle->iDirection, { iscoupled( end::front ), iscoupled( end::rear ) } ) }; vehicle->RaLightsSet( lights.head, lights.rear ); - vehicle = isfrontcaboccupied ? vehicle->Next(coupling::control) : vehicle->Prev(coupling::control); + vehicle = isfrontcaboccupied ? vehicle->Next(Coupling::control) : vehicle->Prev(Coupling::control); } }; @@ -8252,16 +8252,16 @@ int TDynamicObject::DirectionSet(int d) TDynamicObject * TDynamicObject::PrevAny() const { return MoverParameters->Neighbours[ iDirection ^ 1 ].vehicle; } -TDynamicObject * TDynamicObject::Prev(int C) const { - return MoverParameters->Couplers[iDirection ^ 1].CouplingFlag & C ? MoverParameters->Neighbours[iDirection ^ 1].vehicle : nullptr;// gdy sprzęg wirtualny, to jakby nic nie było +TDynamicObject * TDynamicObject::Prev(CouplingSet const couplings) const { + return MoverParameters->Couplers[iDirection ^ 1].CouplingFlag.HasAny(couplings) ? MoverParameters->Neighbours[iDirection ^ 1].vehicle : nullptr;// gdy sprzęg wirtualny, to jakby nic nie było } -TDynamicObject * TDynamicObject::Next(int C) const { - return MoverParameters->Couplers[iDirection].CouplingFlag & C ? MoverParameters->Neighbours[iDirection].vehicle : nullptr;// gdy sprzęg wirtualny, to jakby nic nie było +TDynamicObject * TDynamicObject::Next(CouplingSet const couplings) const { + return MoverParameters->Couplers[iDirection].CouplingFlag.HasAny(couplings) ? MoverParameters->Neighbours[iDirection].vehicle : nullptr;// gdy sprzęg wirtualny, to jakby nic nie było } // checks whether there's unbroken connection of specified type to specified vehicle bool -TDynamicObject::is_connected( TDynamicObject const *Vehicle, coupling const Coupling ) const { +TDynamicObject::is_connected( TDynamicObject const *Vehicle, CouplingSet const couplings ) const { auto *vehicle { this }; if( vehicle == Vehicle ) { @@ -8269,7 +8269,7 @@ TDynamicObject::is_connected( TDynamicObject const *Vehicle, coupling const Coup return true; } // check ahead, it's more likely the "owner" using this method is located there - while( ( vehicle = vehicle->Prev( Coupling ) ) != nullptr ) { + while( ( vehicle = vehicle->Prev( couplings ) ) != nullptr ) { if( vehicle == Vehicle ) { return true; } @@ -8280,7 +8280,7 @@ TDynamicObject::is_connected( TDynamicObject const *Vehicle, coupling const Coup } // start anew in the other direction vehicle = this; - while( ( vehicle = vehicle->Next( Coupling ) ) != nullptr ) { + while( ( vehicle = vehicle->Next( couplings ) ) != nullptr ) { if( vehicle == Vehicle ) { return true; } @@ -8294,7 +8294,7 @@ TDynamicObject * TDynamicObject::Neighbour(int &dir) { auto *neighbour { ( - MoverParameters->Couplers[ dir ].CouplingFlag != coupling::faux ? + MoverParameters->Couplers[ dir ].CouplingFlag != Coupling::none ? MoverParameters->Neighbours[ dir ].vehicle : nullptr ) }; // nowa wartość @@ -8470,8 +8470,8 @@ TDynamicObject * TDynamicObject::FindPowered() // jeśli silnikowy będzie zapięty odwrotnie (tzn. -1), to i tak powinno jeździć dobrze // również hamowanie wykonuje się zaworem w członie, a nie w silnikowym... auto const coupling { MoverParameters->is_multiple_unit() ? - coupling::permanent : - coupling::control }; + Coupling::permanent : + Coupling::control }; auto *lookup { find_vehicle( @@ -8486,7 +8486,7 @@ TDynamicObject * TDynamicObject::FindPantographCarrier() { // try first within a single unit, broaden to all vehicles under our control if first attempt fails - std::array const couplings = { coupling::permanent, coupling::control }; + std::array const couplings = { Coupling::permanent, Coupling::control }; for( auto const coupling : couplings ) { auto *result = @@ -9538,7 +9538,7 @@ coupled_train( TDynamicObject *Vehicle ) { auto const &mover { *vehicle->MoverParameters }; auto *next { mover.Neighbours[ side ].vehicle }; if( next == nullptr - || ( mover.Couplers[ side ].CouplingFlag & coupling::coupler ) == 0 + || false == mover.Couplers[ side ].CouplingFlag.HasAny(Coupling::coupler) || std::ranges::find( train, next ) != train.end() ) { break; } @@ -9561,7 +9561,7 @@ trains_closing_in( std::vector const &Train ) { auto const &mover { *vehicle->MoverParameters }; auto const &neighbour { mover.Neighbours[ side ] }; if( neighbour.vehicle == nullptr - || ( mover.Couplers[ side ].CouplingFlag & coupling::coupler ) != 0 + || mover.Couplers[ side ].CouplingFlag.HasAny(Coupling::coupler) || neighbour.distance > coupler_physics_reach || std::ranges::find( Train, neighbour.vehicle ) != Train.end() ) { continue; @@ -9856,7 +9856,7 @@ std::string_view overlap_kind( TDynamicObject const &First, TDynamicObject const auto const offtrack { First.MoverParameters->OffTrack.active() && Second.MoverParameters->OffTrack.active() }; for( int end = end::front; end <= end::rear; ++end ) { if( First.MoverParameters->Couplers[ end ].Connected == Second.MoverParameters - && First.MoverParameters->Couplers[ end ].CouplingFlag != coupling::faux ) { + && First.MoverParameters->Couplers[ end ].CouplingFlag != Coupling::none ) { return offtrack ? "coupled, both off the track" : "coupled, one on the rails"; } if( First.MoverParameters->Neighbours[ end ].vehicle == &Second ) { diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index 1923e8889..afe730d07 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -660,10 +660,10 @@ private: bool HeadlightsAoff{false}; // wygaszone swiatelki A bool HeadlightsBoff{false}; // wygaszone swiatelki B // checks whether there's unbroken connection of specified type to specified vehicle - bool is_connected( TDynamicObject const *Vehicle, coupling const Coupling = coupling::coupler ) const; + bool is_connected( TDynamicObject const *Vehicle, CouplingSet const couplings = Coupling::coupler ) const; TDynamicObject * PrevAny() const; - TDynamicObject * Prev(int C = -1) const; - TDynamicObject * Next(int C = -1) const; + TDynamicObject * Prev(CouplingSet couplings = CouplingSet::All()) const; // the vehicle coupled with any of the couplings given + TDynamicObject * Next(CouplingSet couplings = CouplingSet::All()) const; void SetdMoveLen(double dMoveLen); void ResetdMoveLen(); double GetdMoveLen(); @@ -687,7 +687,7 @@ private: TDynamicObject * ABuScanNearestObject(glm::vec3 pos, TTrack *Track, double ScanDir, double ScanDist, int &CouplNr); - TDynamicObject * GetFirstDynamic(int cpl_type, int cf = 1); + TDynamicObject * GetFirstDynamic(int cpl_type, CouplingSet cf = Coupling::coupler); void ABuSetModelShake(glm::dvec3 mShake); // place in vehicle_table::m_items, set by its update for the groups of the physics steps on many threads @@ -886,7 +886,7 @@ public: bool has_signal_pc5_on() const; bool has_signal_on( int const Side, int const Pattern ) const; void set_cab_lights( int const Cab, float const Level ); - TDynamicObject * FirstFind(int &coupler_nr, int cf = 1); + TDynamicObject * FirstFind(int &coupler_nr, CouplingSet cf = Coupling::coupler); float GetEPP(); // wyliczanie sredniego cisnienia w PG int DirectionSet(int d); // ustawienie kierunku w składzie // odczyt kierunku w składzie; returns 1 if true, -1 otherwise @@ -905,11 +905,11 @@ public: auto find_vehicle( int const Direction, double const Range, bool const InLine = false ) const -> std::tuple; // locates potential vehicle connected with specific coupling type and satisfying supplied predicate template - auto find_vehicle( coupling const Coupling, Predicate_ const Predicate ) -> TDynamicObject *; + auto find_vehicle( CouplingSet const couplings, Predicate_ const Predicate ) -> TDynamicObject *; TDynamicObject * FindPowered(); TDynamicObject * FindPantographCarrier(); template - void for_each( coupling const Coupling, UnaryFunction_ const Function ); + void for_each( CouplingSet const couplings, UnaryFunction_ const Function ); void ParamSet(int what, int into); // zapytanie do AI, po którym segmencie skrzyżowania jechać int RouteWish(TTrack *tr); @@ -1050,18 +1050,18 @@ private: template auto -TDynamicObject::find_vehicle( coupling const Coupling, Predicate_ const Predicate ) -> TDynamicObject * { +TDynamicObject::find_vehicle( CouplingSet const couplings, Predicate_ const Predicate ) -> TDynamicObject * { if( Predicate( this ) ) { return this; } // try first to look towards the rear auto *vehicle { this }; - while( ( vehicle = vehicle->Next( Coupling ) ) != nullptr ) { + while( ( vehicle = vehicle->Next( couplings ) ) != nullptr ) { if( Predicate( vehicle ) ) { return vehicle; } } // if we didn't yet find a suitable vehicle try in the other direction vehicle = this; - while( ( vehicle = vehicle->Prev( Coupling ) ) != nullptr ) { + while( ( vehicle = vehicle->Prev( couplings ) ) != nullptr ) { if( Predicate( vehicle ) ) { return vehicle; } } // if we still don't have a match give up @@ -1070,16 +1070,16 @@ TDynamicObject::find_vehicle( coupling const Coupling, Predicate_ const Predicat template void -TDynamicObject::for_each( coupling const Coupling, UnaryFunction_ const Function ) { +TDynamicObject::for_each( CouplingSet const couplings, UnaryFunction_ const Function ) { Function( this ); // walk first towards the rear auto *vehicle { this }; - while( ( vehicle = vehicle->Next( Coupling ) ) != nullptr ) { + while( ( vehicle = vehicle->Next( couplings ) ) != nullptr ) { Function( vehicle ); } // then towards the front vehicle = this; - while( ( vehicle = vehicle->Prev( Coupling ) ) != nullptr ) { + while( ( vehicle = vehicle->Prev( couplings ) ) != nullptr ) { Function( vehicle ); } } diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index e736bafdf..076e01fde 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -913,7 +913,7 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const } bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; - TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? end::rear : end::front, 4); + TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? end::rear : end::front, Coupling::control); int in = 0; while (p && in < 8) { @@ -928,7 +928,7 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("eimp_c" + std::to_string(in) + "_inv" + std::to_string(j + 1) + "_allow", p->MoverParameters->Inverters[j].Activate); } } - p = kier ? p->Next(4) : p->Prev(4); + p = kier ? p->Next(Coupling::control) : p->Prev(Coupling::control); } for (int i = 0; i < 20; ++i) { @@ -1117,11 +1117,11 @@ void TTrain::set_paired_open_motor_connectors_button(bool const State) { // crude implementation of the button affecting entire unit for multi-unit engines // TODO: rework it into part of standard command propagation system - if (mvControlled->Couplers[end::front].Connected != nullptr && true == TestFlag(mvControlled->Couplers[end::front].CouplingFlag, coupling::permanent)) + if (mvControlled->Couplers[end::front].Connected != nullptr && true == mvControlled->Couplers[end::front].CouplingFlag.HasAll(Coupling::permanent)) { mvControlled->Couplers[end::front].Connected->StLinSwitchOff = State; } - if (mvControlled->Couplers[end::rear].Connected != nullptr && true == TestFlag(mvControlled->Couplers[end::rear].CouplingFlag, coupling::permanent)) + if (mvControlled->Couplers[end::rear].Connected != nullptr && true == mvControlled->Couplers[end::rear].CouplingFlag.HasAll(Coupling::permanent)) { mvControlled->Couplers[end::rear].Connected->StLinSwitchOff = State; } @@ -7401,7 +7401,7 @@ void TTrain::OnCommand_inverterenable(TTrain *Train, command_data const &Command { // only reacting to press, so the switch doesn't flip back and forth if key is held down bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; - int flag = Train->DynamicObject->MoverParameters->InverterControlCouplerFlag; + auto const flag{CouplingSet::FromBits(Train->DynamicObject->MoverParameters->InverterControlCouplerFlag)}; TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); while (p) { @@ -7440,7 +7440,7 @@ void TTrain::OnCommand_inverterdisable(TTrain *Train, command_data const &Comman { // only reacting to press, so the switch doesn't flip back and forth if key is held down bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; - int flag = Train->DynamicObject->MoverParameters->InverterControlCouplerFlag; + auto const flag{CouplingSet::FromBits(Train->DynamicObject->MoverParameters->InverterControlCouplerFlag)}; TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); while (p) { @@ -7479,7 +7479,7 @@ void TTrain::OnCommand_invertertoggle(TTrain *Train, command_data const &Command { // only reacting to press, so the switch doesn't flip back and forth if key is held down bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; - int flag = Train->DynamicObject->MoverParameters->InverterControlCouplerFlag; + auto const flag{CouplingSet::FromBits(Train->DynamicObject->MoverParameters->InverterControlCouplerFlag)}; TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); while (p) { @@ -8807,7 +8807,7 @@ void TTrain::OnCommand_cabchangeforward(TTrain *Train, command_data const &Comma if (auto const movedirection{1}; false == Train->CabChange(movedirection)) { auto const exitdirection{(movedirection > 0 ? end::front : end::rear)}; - if (TestFlag(Train->mvOccupied->Couplers[exitdirection].CouplingFlag, coupling::gangway)) + if (Train->mvOccupied->Couplers[exitdirection].CouplingFlag.HasAll(Coupling::gangway)) { // przejscie do nastepnego pojazdu auto *targetvehicle = exitdirection == end::front ? Train->DynamicObject->PrevConnected() : Train->DynamicObject->NextConnected(); @@ -8837,7 +8837,7 @@ void TTrain::OnCommand_cabchangebackward(TTrain *Train, command_data const &Comm { // current vehicle doesn't extend any farther in this direction, check if we there's one connected we can move to auto const exitdirection{(movedirection > 0 ? end::front : end::rear)}; - if (TestFlag(Train->mvOccupied->Couplers[exitdirection].CouplingFlag, coupling::gangway)) + if (Train->mvOccupied->Couplers[exitdirection].CouplingFlag.HasAll(Coupling::gangway)) { // przejscie do nastepnego pojazdu auto *targetvehicle = exitdirection == end::front ? Train->DynamicObject->PrevConnected() : Train->DynamicObject->NextConnected(); @@ -9153,7 +9153,7 @@ bool TTrain::Update(double const Deltatime) } bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; - TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? end::rear : end::front, 4); + TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? end::rear : end::front, Coupling::control); int in = 0; fEIMParams[0][6] = 0; iCarNo = 0; @@ -9262,9 +9262,9 @@ bool TTrain::Update(double const Deltatime) in++; iPowerNo = in; } - if ((kier ? p->Next(coupling::permanent) : p->Prev(coupling::permanent)) != (kier ? p->Next(coupling::control) : p->Prev(coupling::control))) + if ((kier ? p->Next(Coupling::permanent) : p->Prev(Coupling::permanent)) != (kier ? p->Next(Coupling::control) : p->Prev(Coupling::control))) iUnitNo++; - p = kier ? p->Next(coupling::control) : p->Prev(coupling::control); + p = kier ? p->Next(Coupling::control) : p->Prev(Coupling::control); iCarNo = i + 1; } else @@ -9363,9 +9363,9 @@ bool TTrain::Update(double const Deltatime) // youBy - prad w drugim czlonie: galaz lub calosc { TDynamicObject const *tmp{nullptr}; - if (DynamicObject->NextConnected() && TestFlag(mvControlled->Couplers[end::rear].CouplingFlag, coupling::control) && mvOccupied->CabOccupied == 1) + if (DynamicObject->NextConnected() && mvControlled->Couplers[end::rear].CouplingFlag.HasAll(Coupling::control) && mvOccupied->CabOccupied == 1) tmp = DynamicObject->NextConnected(); - if (DynamicObject->PrevConnected() && TestFlag(mvControlled->Couplers[end::front].CouplingFlag, coupling::control) && mvOccupied->CabOccupied == -1) + if (DynamicObject->PrevConnected() && mvControlled->Couplers[end::front].CouplingFlag.HasAll(Coupling::control) && mvOccupied->CabOccupied == -1) tmp = DynamicObject->PrevConnected(); if (tmp && tmp->MoverParameters->Power > 0) { @@ -9565,7 +9565,7 @@ bool TTrain::Update(double const Deltatime) btLampkaStyczn.Turn(mvControlled->LineContactorsLampLit()); // mozna prowadzic rozruch btLampkaPrzekRozn.Turn(!mvControlled->GroundRelay && mvControlled->MainCircuitLampsEnabled()); // relay is off and needs a reset btLampkaNadmSil.Turn(mvControlled->FuseFlagCheck() && mvControlled->MainCircuitLampsEnabled()); // relay is off and needs a reset - btLampkaUkrotnienie.Turn(TestFlag(mvControlled->Couplers[mvControlled->CabOccupied == 1 ? rear : front].CouplingFlag, control)); + btLampkaUkrotnienie.Turn(mvControlled->Couplers[mvControlled->CabOccupied == 1 ? rear : front].CouplingFlag.HasAll(Coupling::control)); btLampkaHamPosp.Turn(TestFlag(mvOccupied->Hamulec->GetBrakeStatus(), 1)); // lampka drugiego stopnia hamowania // TODO: youBy wyciągnąć flagę wysokiego stopnia btLampkaNadmWent.Turn(mvControlled->RventRot < 5.0 && mvControlled->ResistorsFlagCheck()); // hunter-121211: lampka zanikowo-pradowego wentylatorow @@ -9806,9 +9806,9 @@ bool TTrain::Update(double const Deltatime) { // yB - wskazniki drugiego czlonu TDynamicObject const *tmp{nullptr}; //=mvControlled->mvSecond; //Ra 2014-07: trzeba to jeszcze wyjąć z kabiny... // Ra 2014-07: no nie ma potrzeby szukać tego w każdej klatce - if (TestFlag(mvControlled->Couplers[1].CouplingFlag, coupling::control) && mvOccupied->CabOccupied > 0) + if (mvControlled->Couplers[1].CouplingFlag.HasAll(Coupling::control) && mvOccupied->CabOccupied > 0) tmp = DynamicObject->NextConnected(); - if (TestFlag(mvControlled->Couplers[0].CouplingFlag, coupling::control) && mvOccupied->CabOccupied < 0) + if (mvControlled->Couplers[0].CouplingFlag.HasAll(Coupling::control) && mvOccupied->CabOccupied < 0) tmp = DynamicObject->PrevConnected(); if (tmp) @@ -11560,13 +11560,13 @@ void TTrain::DynamicSet(TDynamicObject *d) mvSecond = nullptr; // gdyby się nic nie znalazło if (mvOccupied->Power > 1.0) // dwuczłonowe lub ukrotnienia, żeby nie szukać każdorazowo { - if (mvOccupied->Couplers[1].Connected ? mvOccupied->Couplers[1].AllowedFlag & coupling::control : false) + if (mvOccupied->Couplers[1].Connected != nullptr && mvOccupied->Couplers[1].AllowedFlag.HasAny(Coupling::control)) { // gdy jest człon od sprzęgu 1, a sprzęg łączony // warsztatowo (powiedzmy) if (mvOccupied->Couplers[1].Connected->Power > 1.0) // ten drugi ma moc mvSecond = mvOccupied->Couplers[1].Connected; // wskaźnik na drugiego } - else if (mvOccupied->Couplers[0].Connected ? mvOccupied->Couplers[0].AllowedFlag & coupling::control : false) + else if (mvOccupied->Couplers[0].Connected != nullptr && mvOccupied->Couplers[0].AllowedFlag.HasAny(Coupling::control)) { // gdy jest człon od sprzęgu 0, a sprzęg łączony // warsztatowo (powiedzmy) if (mvOccupied->Couplers[0].Connected->Power > 1.0) // ale ten drugi ma moc @@ -12355,7 +12355,7 @@ void TTrain::set_cab_controls(int const Cab) // finding each inverter - not so optimal, but action ins performed only during changing cabin bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; - int flag = DynamicObject->MoverParameters->InverterControlCouplerFlag; + auto const flag{CouplingSet::FromBits(DynamicObject->MoverParameters->InverterControlCouplerFlag)}; int itemstart = 0; for ([[maybe_unused]] auto const &item : ggInverterToggleButtons) // for each button { diff --git a/vehicle/enginestart.cpp b/vehicle/enginestart.cpp index a826bb19c..ca276b73c 100644 --- a/vehicle/enginestart.cpp +++ b/vehicle/enginestart.cpp @@ -30,7 +30,7 @@ TMoverParameters *find_along(TMoverParameters const &Start, int const Side, TMov // a train can't loop back on itself, the limit only guards against a broken chain of couplers for (auto steps = 0; steps < 1000; ++steps) { auto const &coupler{vehicle->Couplers[side]}; - if (coupler.Connected == nullptr || false == TestFlag(coupler.CouplingFlag, coupling::control)) { + if (coupler.Connected == nullptr || false == coupler.CouplingFlag.HasAll(Coupling::control)) { return nullptr; } // onwards through the other end of the next vehicle, whichever way round it stands From 6003615e3eeb669d6336a2d8fb6432781c81777b Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sat, 28 Nov 2026 00:08:13 +0100 Subject: [PATCH 011/123] build(tests): a precompiled header for the unit tests The game and the core library build with stdafx.h precompiled, the unit tests didn't: each of their ~150 files parsed windows.h, GLFW, glm and doctest anew, about 50 s each on a busy machine, half of the CPU time of the whole build. eu07_unit_tests precompiles stdafx.h and doctest.h too. main.cpp defines the implementation of doctest before including doctest.h and goes without. The vehicle physics stays out of the header: its unscoped enums (end::front...) clash with names in the tests. The test files take 28 min of CPU instead of 95 (10.7 s each on average), a full build some 4-5 minutes less on 16 cores. 1144/1144 tests, golden traces exact. --- tests/unit/CMakeLists.txt | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index 3de990dec..d66fd46eb 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -46,6 +46,17 @@ add_executable(${UNIT_TESTS_NAME} # the core library brings the game's build settings along target_link_libraries(${UNIT_TESTS_NAME} PRIVATE eu07_core) + +# a precompiled header, as the game has: the system and library headers of stdafx.h and doctest are parsed once, not +# again in each of the files. the vehicle physics stays out of it, its unscoped enums (end::front...) would clash with +# the names of the tests. main.cpp defines the implementation of doctest before it includes doctest.h, so it goes without +if(USE_PCH) + target_precompile_headers(${UNIT_TESTS_NAME} PRIVATE + "$<$:${CMAKE_SOURCE_DIR}/stdafx.h>" + "$<$:${CMAKE_SOURCE_DIR}/ref/doctest/doctest.h>") + set_source_files_properties(main.cpp PROPERTIES SKIP_PRECOMPILE_HEADERS TRUE) +endif() + # the script screen host, tested with the real runtimes (test_script_screen_host.cpp) target_sources(${UNIT_TESTS_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/scripting/scriptscreens.cpp") if (WITH_LUA) From d4bd3fc5caa2d1481a2facc08c5473f658d33cdb Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sat, 28 Nov 2026 00:28:34 +0100 Subject: [PATCH 012/123] refactor(physics): physics/mover/ becomes physics/components/ The files of the parts of a vehicle (pneumatics, electrics, traction, doors, drives...) are in physics/components/, not under the old name of the mover; the file of the vehicle as a body, its forces and its movement, is body.cpp (was mover.cpp). The includes, CMakeLists.txt and AGENTS.md name the new paths. Renames only. 1144/1144 tests, golden traces exact against staging 62f7a29b. --- AGENTS.md | 4 +-- CMakeLists.txt | 34 +++++++++---------- .../{mover/mover.cpp => components/body.cpp} | 2 +- physics/{mover => components}/cab.cpp | 2 +- physics/{mover => components}/collisions.cpp | 2 +- physics/{mover => components}/commands.cpp | 2 +- physics/{mover => components}/controllers.cpp | 2 +- physics/{mover => components}/couplers.cpp | 2 +- physics/{mover => components}/diesel.cpp | 4 +-- physics/{mover => components}/doors.cpp | 2 +- physics/{mover => components}/drive.cpp | 2 +- physics/{mover => components}/drive.h | 0 physics/{mover => components}/electrics.cpp | 2 +- physics/{mover => components}/fizparser.cpp | 2 +- physics/{mover => components}/fizsections.cpp | 2 +- physics/{mover => components}/internal.h | 2 +- physics/{mover => components}/pneumatics.cpp | 2 +- .../{mover => components}/securitysystem.cpp | 2 +- physics/{mover => components}/setup.cpp | 2 +- physics/{mover => components}/traction.cpp | 4 +-- physics/mover.h | 2 +- 21 files changed, 39 insertions(+), 39 deletions(-) rename physics/{mover/mover.cpp => components/body.cpp} (99%) rename physics/{mover => components}/cab.cpp (99%) rename physics/{mover => components}/collisions.cpp (99%) rename physics/{mover => components}/commands.cpp (99%) rename physics/{mover => components}/controllers.cpp (99%) rename physics/{mover => components}/couplers.cpp (99%) rename physics/{mover => components}/diesel.cpp (99%) rename physics/{mover => components}/doors.cpp (99%) rename physics/{mover => components}/drive.cpp (99%) rename physics/{mover => components}/drive.h (100%) rename physics/{mover => components}/electrics.cpp (99%) rename physics/{mover => components}/fizparser.cpp (99%) rename physics/{mover => components}/fizsections.cpp (99%) rename physics/{mover => components}/internal.h (88%) rename physics/{mover => components}/pneumatics.cpp (99%) rename physics/{mover => components}/securitysystem.cpp (99%) rename physics/{mover => components}/setup.cpp (99%) rename physics/{mover => components}/traction.cpp (99%) diff --git a/AGENTS.md b/AGENTS.md index 82ba88bc4..82285b488 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -107,7 +107,7 @@ Code that isn't otherwise touched keeps its names; renaming a member goes togeth scripts and the log read stays byte for byte the same whatever the C++ names are: the keywords of the `.fiz` and the scenery, the keys of the dictionaries of the Python screens, the texts of the log and of `STR(...)`. -The vehicle code is in `physics/` (the physics of the vehicles: `mover.h` and `physics/mover/*.cpp` by subsystem, `brakes.*`, +The vehicle code is in `physics/` (the physics of the vehicles: `mover.h` and `physics/components/*.cpp` by subsystem, `brakes.*`, couplers, collisions, derailment) and `vehicle/` (the vehicle in the scenery, the cab, the AI). Keep it that way: - `physics/vehicletypes.h` holds the vocabulary the rest of the simulator passes around (vehicle ends, sides, couplings, lights, @@ -117,7 +117,7 @@ couplers, collisions, derailment) and `vehicle/` (the vehicle in the scenery, th an `int`. Numbers of the formats (`.scn`, events, the network) are read into these where they come in and written where they go out. - The commands between the vehicles are `VehicleCommand` (`physics/vehiclecommand.h`); their text names only matter where a command comes as text. -- What depends on the kind of drive (`EngineType`) goes into its class in `physics/mover/drive.*`, not into a new `switch`. +- What depends on the kind of drive (`EngineType`) goes into its class in `physics/components/drive.*`, not into a new `switch`. ## Renderers: the move to OpenGL 4.6 and Vulkan diff --git a/CMakeLists.txt b/CMakeLists.txt index 04e07b4a5..eecd0f45b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -57,7 +57,7 @@ set(CMAKE_CXX_STANDARD 20) file(GLOB HEADERS "*.h" "Console/*.h" "physics/*.h" -"physics/mover/*.h" +"physics/components/*.h" "gl/*.h" "network/*.h" "vr/*.h" @@ -745,22 +745,22 @@ set(CORE_SOURCES "physics/friction.cpp" "physics/brakes.cpp" "physics/vehiclecommand.cpp" -"physics/mover/mover.cpp" -"physics/mover/drive.cpp" -"physics/mover/cab.cpp" -"physics/mover/collisions.cpp" -"physics/mover/commands.cpp" -"physics/mover/controllers.cpp" -"physics/mover/couplers.cpp" -"physics/mover/diesel.cpp" -"physics/mover/doors.cpp" -"physics/mover/electrics.cpp" -"physics/mover/fizparser.cpp" -"physics/mover/fizsections.cpp" -"physics/mover/pneumatics.cpp" -"physics/mover/securitysystem.cpp" -"physics/mover/setup.cpp" -"physics/mover/traction.cpp" +"physics/components/body.cpp" +"physics/components/drive.cpp" +"physics/components/cab.cpp" +"physics/components/collisions.cpp" +"physics/components/commands.cpp" +"physics/components/controllers.cpp" +"physics/components/couplers.cpp" +"physics/components/diesel.cpp" +"physics/components/doors.cpp" +"physics/components/electrics.cpp" +"physics/components/fizparser.cpp" +"physics/components/fizsections.cpp" +"physics/components/pneumatics.cpp" +"physics/components/securitysystem.cpp" +"physics/components/setup.cpp" +"physics/components/traction.cpp" "physics/couplerphysics.cpp" "physics/derailment.cpp" "physics/collision.cpp" diff --git a/physics/mover/mover.cpp b/physics/components/body.cpp similarity index 99% rename from physics/mover/mover.cpp rename to physics/components/body.cpp index fa6f20c1e..d34396304 100644 --- a/physics/mover/mover.cpp +++ b/physics/components/body.cpp @@ -27,7 +27,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include "physics/mover/internal.h" +#include "physics/components/internal.h" std::vector const TMoverParameters::eimc_labels = {"dfic: ", "dfmax:", "p: ", "scfu: ", "cim: ", "icif: ", "Uzmax:", "Uzh: ", "DU: ", "I0: ", "fcfu: ", diff --git a/physics/mover/cab.cpp b/physics/components/cab.cpp similarity index 99% rename from physics/mover/cab.cpp rename to physics/components/cab.cpp index 760327cdb..02bd95d0e 100644 --- a/physics/mover/cab.cpp +++ b/physics/components/cab.cpp @@ -27,7 +27,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include "physics/mover/internal.h" +#include "physics/components/internal.h" bool TMoverParameters::DirectionForward() diff --git a/physics/mover/collisions.cpp b/physics/components/collisions.cpp similarity index 99% rename from physics/mover/collisions.cpp rename to physics/components/collisions.cpp index a696bba8b..948db6fa5 100644 --- a/physics/mover/collisions.cpp +++ b/physics/components/collisions.cpp @@ -27,7 +27,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include "physics/mover/internal.h" +#include "physics/components/internal.h" double ComputeCollision(double &v1, double &v2, double m1, double m2, double beta, bool vc) diff --git a/physics/mover/commands.cpp b/physics/components/commands.cpp similarity index 99% rename from physics/mover/commands.cpp rename to physics/components/commands.cpp index 2fc63a698..74f1a37bc 100644 --- a/physics/mover/commands.cpp +++ b/physics/components/commands.cpp @@ -27,7 +27,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include "physics/mover/internal.h" +#include "physics/components/internal.h" // ************************************************************************************************* diff --git a/physics/mover/controllers.cpp b/physics/components/controllers.cpp similarity index 99% rename from physics/mover/controllers.cpp rename to physics/components/controllers.cpp index eba9ad73b..0dcfcbe75 100644 --- a/physics/mover/controllers.cpp +++ b/physics/components/controllers.cpp @@ -27,7 +27,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include "physics/mover/internal.h" +#include "physics/components/internal.h" // ************************************************************************************************* diff --git a/physics/mover/couplers.cpp b/physics/components/couplers.cpp similarity index 99% rename from physics/mover/couplers.cpp rename to physics/components/couplers.cpp index 6acf3f233..5fb3b55ef 100644 --- a/physics/mover/couplers.cpp +++ b/physics/components/couplers.cpp @@ -27,7 +27,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include "physics/mover/internal.h" +#include "physics/components/internal.h" // Ra: tu należy przenosić funcje z mover.pas, które nie są z niego wywoływane. // Jeśli jakieś zmienne nie są używane w mover.pas, też można je przenosić. diff --git a/physics/mover/diesel.cpp b/physics/components/diesel.cpp similarity index 99% rename from physics/mover/diesel.cpp rename to physics/components/diesel.cpp index e2e95959f..0be62d9a2 100644 --- a/physics/mover/diesel.cpp +++ b/physics/components/diesel.cpp @@ -27,8 +27,8 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include "physics/mover/internal.h" -#include "physics/mover/drive.h" +#include "physics/components/internal.h" +#include "physics/components/drive.h" double TMoverParameters::EngineRPMRatio() const diff --git a/physics/mover/doors.cpp b/physics/components/doors.cpp similarity index 99% rename from physics/mover/doors.cpp rename to physics/components/doors.cpp index 923496d4d..c9334a56e 100644 --- a/physics/mover/doors.cpp +++ b/physics/components/doors.cpp @@ -27,7 +27,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include "physics/mover/internal.h" +#include "physics/components/internal.h" bool TMoverParameters::AssignLoad(std::string const &Loadname, float const Amount) diff --git a/physics/mover/drive.cpp b/physics/components/drive.cpp similarity index 99% rename from physics/mover/drive.cpp rename to physics/components/drive.cpp index d108a8494..55284f396 100644 --- a/physics/mover/drive.cpp +++ b/physics/components/drive.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. // the drives of the vehicles, one class for each kind of engine #include "stdafx.h" -#include "physics/mover/drive.h" +#include "physics/components/drive.h" #include #include diff --git a/physics/mover/drive.h b/physics/components/drive.h similarity index 100% rename from physics/mover/drive.h rename to physics/components/drive.h diff --git a/physics/mover/electrics.cpp b/physics/components/electrics.cpp similarity index 99% rename from physics/mover/electrics.cpp rename to physics/components/electrics.cpp index ada624e72..536d24579 100644 --- a/physics/mover/electrics.cpp +++ b/physics/components/electrics.cpp @@ -27,7 +27,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include "physics/mover/internal.h" +#include "physics/components/internal.h" // KURS90 - sprężarka pantografów; Ra 2014-07: teraz jest to zbiornik rozrządu, chociaż to jeszcze nie tak diff --git a/physics/mover/fizparser.cpp b/physics/components/fizparser.cpp similarity index 99% rename from physics/mover/fizparser.cpp rename to physics/components/fizparser.cpp index a0a293682..32a50d653 100644 --- a/physics/mover/fizparser.cpp +++ b/physics/components/fizparser.cpp @@ -27,7 +27,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include "physics/mover/internal.h" +#include "physics/components/internal.h" int ConversionError = 0; diff --git a/physics/mover/fizsections.cpp b/physics/components/fizsections.cpp similarity index 99% rename from physics/mover/fizsections.cpp rename to physics/components/fizsections.cpp index 8bf7673c6..b567b3712 100644 --- a/physics/mover/fizsections.cpp +++ b/physics/components/fizsections.cpp @@ -27,7 +27,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include "physics/mover/internal.h" +#include "physics/components/internal.h" int s2NPW(std::string s) diff --git a/physics/mover/internal.h b/physics/components/internal.h similarity index 88% rename from physics/mover/internal.h rename to physics/components/internal.h index c85dd999f..a43782492 100644 --- a/physics/mover/internal.h +++ b/physics/components/internal.h @@ -7,7 +7,7 @@ obtain one at http://mozilla.org/MPL/2.0/. */ -// the helpers the files of physics/mover/ share: only they include this header +// the helpers the files of physics/components/ share: only they include this header #pragma once diff --git a/physics/mover/pneumatics.cpp b/physics/components/pneumatics.cpp similarity index 99% rename from physics/mover/pneumatics.cpp rename to physics/components/pneumatics.cpp index c4519d5fb..1e4e44f2b 100644 --- a/physics/mover/pneumatics.cpp +++ b/physics/components/pneumatics.cpp @@ -27,7 +27,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include "physics/mover/internal.h" +#include "physics/components/internal.h" // Nastawianie hamulców diff --git a/physics/mover/securitysystem.cpp b/physics/components/securitysystem.cpp similarity index 99% rename from physics/mover/securitysystem.cpp rename to physics/components/securitysystem.cpp index bb3726029..3b94ca658 100644 --- a/physics/mover/securitysystem.cpp +++ b/physics/components/securitysystem.cpp @@ -27,7 +27,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include "physics/mover/internal.h" +#include "physics/components/internal.h" void TSecuritySystem::set_enabled(bool e) diff --git a/physics/mover/setup.cpp b/physics/components/setup.cpp similarity index 99% rename from physics/mover/setup.cpp rename to physics/components/setup.cpp index 29db46d97..d4a8aae70 100644 --- a/physics/mover/setup.cpp +++ b/physics/components/setup.cpp @@ -27,7 +27,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include "physics/mover/internal.h" +#include "physics/components/internal.h" // ************************************************************************************************* diff --git a/physics/mover/traction.cpp b/physics/components/traction.cpp similarity index 99% rename from physics/mover/traction.cpp rename to physics/components/traction.cpp index 05b52bbc3..00b760db6 100644 --- a/physics/mover/traction.cpp +++ b/physics/components/traction.cpp @@ -27,8 +27,8 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include "physics/mover/internal.h" -#include "physics/mover/drive.h" +#include "physics/components/internal.h" +#include "physics/components/drive.h" double TableInterpolation(std::map &Map, double Parameter) diff --git a/physics/mover.h b/physics/mover.h index 364c6bb2b..b07ee559e 100644 --- a/physics/mover.h +++ b/physics/mover.h @@ -2248,7 +2248,7 @@ class TMoverParameters void FuseOff(void); // wylaczenie nadmiarowego bool UniversalResetButton(int const Button, range_t const Notify = range_t::consist); bool RelayReset(int const Relays, range_t const Notify = range_t::consist); // resets specified relays - // the drive of the kind of engine of the vehicle (physics/mover/drive.h) + // the drive of the kind of engine of the vehicle (physics/components/drive.h) TractionDrive const &Drive() const; double ShowCurrent(int AmpN) const; // pokazuje bezwgl. wartosc pradu na wybranym amperomierzu double ShowCurrentP(int AmpN) const; // pokazuje bezwgl. wartosc pradu w wybranym pojezdzie //Q 20160722 From 54d3a1040a370eaec52800f54b892795d207e4ba Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sat, 28 Nov 2026 01:22:57 +0100 Subject: [PATCH 013/123] refactor(physics): EnumSet for the sets of flags; the damage of a vehicle is VehicleDamage and DamageSet - utilities/enumset.h: EnumSet, a set of the values of an enum class whose values are bits, with the operations CouplingSet had (HasAll, HasAny, Empty, Set, Clear, Without, |, &, ^, ==, FromBits, Bits). CouplingSet is EnumSet now; an enum is a kind of the sets by IsEnumSetKind, which gives it its operator |. - the damage of a vehicle (DamageFlag) is a DamageSet of VehicleDamage instead of the int and the dtrain_* constants. A bit means one thing for a locomotive and another for a wagon; both names are there (thinWheel and loadShift, ventilator and loadDamage, engine and loadDestroyed). - the SetDamage command of the scenery adds or takes away the damage by its number as SetFlag() did (setOrClear()); "WRECKED" is still the set of the number 255; the bearing divisor of the resistance stays the number 4. - the damage of the tracks and of the catenary (dtrack_*, the traction's DamageFlag) are other flags and stay as they were. No change in behaviour: 1144/1144 tests, golden traces exact against staging 62f7a29b. --- application/driveruipanels.cpp | 2 +- physics/components/body.cpp | 38 +++--- physics/components/collisions.cpp | 32 +++--- physics/components/commands.cpp | 28 ++++- physics/components/couplers.cpp | 2 +- physics/components/electrics.cpp | 2 +- physics/components/traction.cpp | 10 +- physics/mover.h | 4 +- physics/vehicletypes.h | 153 +++++-------------------- scene/scene.cpp | 2 +- tests/unit/test_cab.cpp | 8 +- tests/unit/test_collisions.cpp | 12 +- tests/unit/test_commands.cpp | 2 +- tests/unit/test_controls.cpp | 2 +- tests/unit/test_coupler_physics.cpp | 12 +- tests/unit/test_couplers.cpp | 2 +- tests/unit/test_couplers_trains.cpp | 12 +- tests/unit/test_derail_motion.cpp | 10 +- tests/unit/test_derailment_vehicle.cpp | 24 ++-- tests/unit/test_queries.cpp | 26 ++--- utilities/enumset.h | 130 +++++++++++++++++++++ vehicle/DynObj.cpp | 6 +- world/station.cpp | 4 +- 23 files changed, 286 insertions(+), 237 deletions(-) create mode 100644 utilities/enumset.h diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 2d7c3fc9a..cb9f9e6d8 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -618,7 +618,7 @@ debug_panel::render() { } // sections ImGui::Separator(); - if (true == render_section( "Vehicle", m_vehiclelines ) && DebugModeFlag && m_input.mover && m_input.mover->DamageFlag != 0 && true == ImGui::Button( "Stop and repair consist" )) { + if (true == render_section( "Vehicle", m_vehiclelines ) && DebugModeFlag && m_input.mover && false == m_input.mover->DamageFlag.Empty() && true == ImGui::Button( "Stop and repair consist" )) { command_relay commandrelay; commandrelay.post(user_command::resetconsist, 0.0, 0.0, GLFW_PRESS, 0, glm::vec3(0.0f), &m_input.vehicle->name()); } diff --git a/physics/components/body.cpp b/physics/components/body.cpp index d34396304..90acf4544 100644 --- a/physics/components/body.cpp +++ b/physics/components/body.cpp @@ -50,7 +50,7 @@ namespace // whatever pushes it, and the train behind it stopped at once against it, in a hit no train had bool legacy_derailed_slides(TMoverParameters const &Vehicle) { - return Global.collisions == global_settings::collision_model::physical && TestFlag(Vehicle.CategoryFlag, 1) && TestFlag(Vehicle.DamageFlag, dtrain_out) && + return Global.collisions == global_settings::collision_model::physical && TestFlag(Vehicle.CategoryFlag, 1) && Vehicle.DamageFlag.HasAll(VehicleDamage::derailed) && Vehicle.Derailed == derailment::outcome::none; } @@ -210,7 +210,7 @@ void TMoverParameters::change_train_velocity(double const Change) double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShape &Shape, TTrackParam const &Track, TTractionParam const &ElectricTraction, TLocation const &NewLoc, TRotation const &NewRot) { - if (!TestFlag(DamageFlag, dtrain_out)) + if (!DamageFlag.HasAll(VehicleDamage::derailed)) { // Ra: to przepisywanie tu jest bez sensu RunningShape = Shape; RunningTrack = Track; @@ -234,7 +234,7 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap if (CategoryFlag == 4) OffsetTrackV = TotalMass / (Dim.L * Dim.W * 1000.0); - else if (TestFlag(CategoryFlag, 1) && TestFlag(RunningTrack.CategoryFlag, 1) && TestFlag(DamageFlag, dtrain_out)) + else if (TestFlag(CategoryFlag, 1) && TestFlag(RunningTrack.CategoryFlag, 1) && DamageFlag.HasAll(VehicleDamage::derailed)) { OffsetTrackV = -0.2; OffsetTrackH = Sign(RunningShape.R) * 0.2; @@ -253,7 +253,7 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce(), and so does one // derailed the legacy way with physics.collisions new - if (TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this)) + if (DamageFlag.HasAll(VehicleDamage::derailed) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this)) AccS = -Sign(V) * g * 1; // random(0.0, 0.1) // stuck in the ballast: the friction holds a derailed vehicle once it stopped, until the forces on it are larger auto const stuck{(Derailed != derailment::outcome::none || legacy_derailed_slides(*this)) && V == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; @@ -365,7 +365,7 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Sh AccS = std::lerp(AccSprev, FTotal / TotalMass, 0.5); // std::clamp( dt * 3.0, 0.0, 1.0 ) ); // prawo Newtona ale z wygladzaniem (średnia z poprzednim) - if (TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this)) + if (DamageFlag.HasAll(VehicleDamage::derailed) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this)) AccS = -Sign(V) * g * 1; // * random(0.0, 0.1) auto const stuck{(Derailed != derailment::outcome::none || legacy_derailed_slides(*this)) && V == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; if (stuck) @@ -392,7 +392,7 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Sh // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce(), and so does one // derailed the legacy way with physics.collisions new - if (true == TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this) && Vel < 1.0) + if (true == DamageFlag.HasAll(VehicleDamage::derailed) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this) && Vel < 1.0) { V = 0.0; AccS = 0.0; @@ -717,7 +717,7 @@ void TMoverParameters::ComputeConstans(void) double Curvature; // Ra 2014-07: odwrotność promienia TotalMassxg = TotalMass * g; // TotalMass*g - BearingF = (DamageFlag & dtrain_bearing) != 0 ? 2.0 : 0; + BearingF = DamageFlag.HasAny(VehicleDamage::bearing) ? 2.0 : 0; HideModifier = 0; // int(Couplers[0].CouplingFlag>0)+int(Couplers[1].CouplingFlag>0); @@ -763,8 +763,8 @@ void TMoverParameters::ComputeConstans(void) Curvature = 0.0; } // opór składu na łuku (youBy): +(500*TrackW/R)*TotalMassxg*0.001 do FrictConst2s/d - FrictConst2s = TotalMassxg * (500.0 * TrackW * Curvature + 2.5 - HideModifier + 2 * BearingF / dtrain_bearing) * 0.001; - FrictConst2d = TotalMassxg * (500.0 * TrackW * Curvature + 2.0 - HideModifier + BearingF / dtrain_bearing) * 0.001; + FrictConst2s = TotalMassxg * (500.0 * TrackW * Curvature + 2.5 - HideModifier + 2 * BearingF / 4.0) * 0.001; + FrictConst2d = TotalMassxg * (500.0 * TrackW * Curvature + 2.0 - HideModifier + BearingF / 4.0) * 0.001; } // ************************************************************************************************* @@ -839,7 +839,7 @@ void TMoverParameters::ComputeTotalForce(double dt) // juz zoptymalizowane: FStand = FrictionForce(); // siła oporów ruchu - if (true == TestFlag(DamageFlag, dtrain_out)) + if (true == DamageFlag.HasAll(VehicleDamage::derailed)) { if (Derailed != derailment::outcome::none) { @@ -1220,50 +1220,50 @@ std::string TMoverParameters::EngineDescription(int what) const std::string outstr{"OK"}; if (what == 0) { - if (DamageFlag == 255) + if (DamageFlag == DamageSet::FromBits(255)) // every damage but the pantograph { outstr = "WRECKED"; } else { - if (TestFlag(DamageFlag, dtrain_thinwheel)) + if (DamageFlag.HasAll(VehicleDamage::thinWheel)) { if (Power > 0.1) outstr = "Thin wheel"; else outstr = "Load shifted"; } - if (WheelFlat > 5.0 || TestFlag(DamageFlag, dtrain_wheelwear)) + if (WheelFlat > 5.0 || DamageFlag.HasAll(VehicleDamage::wheelWear)) { outstr = "Wheel wear"; } - if (TestFlag(DamageFlag, dtrain_bearing)) + if (DamageFlag.HasAll(VehicleDamage::bearing)) { outstr = "Bearing damaged"; } - if (TestFlag(DamageFlag, dtrain_coupling)) + if (DamageFlag.HasAll(VehicleDamage::coupling)) { outstr = "Coupler broken"; } - if (TestFlag(DamageFlag, dtrain_loaddamage)) + if (DamageFlag.HasAll(VehicleDamage::loadDamage)) { if (Power > 0.1) outstr = "Ventilator damaged"; else outstr = "Load damaged"; } - if (TestFlag(DamageFlag, dtrain_loaddestroyed)) + if (DamageFlag.HasAll(VehicleDamage::loadDestroyed)) { if (Power > 0.1) outstr = "Engine damaged"; else outstr = "LOAD DESTROYED"; } - if (TestFlag(DamageFlag, dtrain_axle)) + if (DamageFlag.HasAll(VehicleDamage::axle)) { outstr = "Axle broken"; } - if (TestFlag(DamageFlag, dtrain_out)) + if (DamageFlag.HasAll(VehicleDamage::derailed)) { outstr = "DERAILED"; } diff --git a/physics/components/collisions.cpp b/physics/components/collisions.cpp index 948db6fa5..12266fed8 100644 --- a/physics/components/collisions.cpp +++ b/physics/components/collisions.cpp @@ -141,13 +141,13 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) } // HACK: limit excessive speed derailment checks to vehicles which aren't part of the same consist - auto const outsideconsist{thiscoupler.CouplingFlag == Coupling::none || true == TestFlag(othervehicle->DamageFlag, dtrain_out)}; + auto const outsideconsist{thiscoupler.CouplingFlag == Coupling::none || true == othervehicle->DamageFlag.HasAll(VehicleDamage::derailed)}; auto const velocitydifference{outsideconsist ? CollisionVelocity(End, *othervehicle, otherend) : 0.0}; if (velocitydifference > SafeCollisionVelocity) { // HACK: crude estimation for potential derail, will take place with velocity difference > 15 km/h adjusted for vehicle mass ratio - if (false == TestFlag(DamageFlag, dtrain_out) || false == TestFlag(othervehicle->DamageFlag, dtrain_out)) + if (false == DamageFlag.HasAll(VehicleDamage::derailed) || false == othervehicle->DamageFlag.HasAll(VehicleDamage::derailed)) { WriteLog("Bad driving: " + Name + " and " + othervehicle->Name + " collided with velocity " + to_string(velocitydifference, 0) + " km/h"); } @@ -171,7 +171,7 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) // the crush, the vehicles coupled to the wall push it on (crush_hit()) auto const coupled{thiscoupler.CouplingFlag != Coupling::none}; auto const wall = [crushing, coupled](TMoverParameters const &Vehicle) { - return TestFlag(Vehicle.DamageFlag, dtrain_out) && (false == crushing || (Vehicle.Derailed == derailment::outcome::none && false == coupled)); + return Vehicle.DamageFlag.HasAll(VehicleDamage::derailed) && (false == crushing || (Vehicle.Derailed == derailment::outcome::none && false == coupled)); }; if (false == wall(*this)) { @@ -198,7 +198,7 @@ void TMoverParameters::damage_coupler(int const End) return; } // HACK: don't break articulated couplings no matter what - if (SetFlag(DamageFlag, dtrain_coupling)) + if (DamageFlag.Set(VehicleDamage::coupling)) EventFlag = true; auto const hosetorn{thiscoupler.CouplingFlag.HasAll(Coupling::brakeHose)}; @@ -254,7 +254,7 @@ double TMoverParameters::buffer_height_at(int const End) const void TMoverParameters::derail_in_collision(DerailReason const Reason, std::string const &Why) { - if (false == SetFlag(DamageFlag, dtrain_out)) + if (false == DamageFlag.Set(VehicleDamage::derailed)) { return; } @@ -378,8 +378,8 @@ bool TMoverParameters::crush_hit(int const End, double const dt) // train. the vehicles coupled to it push it on, as the train behind a derailed vehicle does: a wall to them, it // stopped the whole train at once, and the vehicles behind it crushed by the energy of the train auto const coupled{thiscoupler.CouplingFlag != Coupling::none}; - auto const wall{false == coupled && TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none}; - auto const otherwall{false == coupled && TestFlag(othervehicle->DamageFlag, dtrain_out) && othervehicle->Derailed == derailment::outcome::none}; + auto const wall{false == coupled && DamageFlag.HasAll(VehicleDamage::derailed) && Derailed == derailment::outcome::none}; + auto const otherwall{false == coupled && othervehicle->DamageFlag.HasAll(VehicleDamage::derailed) && othervehicle->Derailed == derailment::outcome::none}; if (wall && otherwall) { return false; @@ -547,7 +547,7 @@ bool TMoverParameters::crush_hit(int const End, double const dt) void TMoverParameters::check_pushed_off(double const dt, double const Distance) { - if (Global.collisions != global_settings::collision_model::physical || false == Global.crash_damage || TestFlag(DamageFlag, dtrain_out) || false == TestFlag(CategoryFlag, 1) || + if (Global.collisions != global_settings::collision_model::physical || false == Global.crash_damage || DamageFlag.HasAll(VehicleDamage::derailed) || false == TestFlag(CategoryFlag, 1) || DebugModeFlag) { pushed_off_monitor.reset(); @@ -645,7 +645,7 @@ void repair(TMoverParameters &Vehicle, TCoupling &Coupler) { return; } - ClearFlag(Vehicle.DamageFlag, dtrain_coupling); + Vehicle.DamageFlag.Clear(VehicleDamage::coupling); // either vehicle of the pair may have been braking through the torn hose Vehicle.AlarmChainFlag = false; } @@ -683,7 +683,7 @@ double TMoverParameters::centre_of_gravity() const void TMoverParameters::check_derailment(TTrackShape const &Shape, TTrackParam const &Track, double const Distance) { - if (TestFlag(DamageFlag, dtrain_out) || false == TestFlag(CategoryFlag, 1) || DebugModeFlag) + if (DamageFlag.HasAll(VehicleDamage::derailed) || false == TestFlag(CategoryFlag, 1) || DebugModeFlag) { derailment_monitor.reset(); return; @@ -736,7 +736,7 @@ void TMoverParameters::check_derailment(TTrackShape const &Shape, TTrackParam co void TMoverParameters::derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track, std::string const *TrackName) { - if (false == SetFlag(DamageFlag, dtrain_out)) + if (false == DamageFlag.Set(VehicleDamage::derailed)) { return; } @@ -759,7 +759,7 @@ void TMoverParameters::derail(derailment::verdict const &Verdict, derailment::ve void TMoverParameters::rerail() { - ClearFlag(DamageFlag, dtrain_out); + DamageFlag.Clear(VehicleDamage::derailed); Derailed = derailment::outcome::none; // and back on the track; what derailed it before has no say in how it leaves the track the next time OffTrack.reset(); @@ -787,7 +787,7 @@ void TMoverParameters::rerail() void TMoverParameters::repair_damage() { - DamageFlag = 0; + DamageFlag = {}; EngDmgFlag = 0; WheelFlat = 0.0; AlarmChainFlag = false; @@ -801,7 +801,7 @@ void TMoverParameters::repair_damage() void TMoverParameters::Derail(DerailReason const Reason) { - if (SetFlag(DamageFlag, dtrain_out)) + if (DamageFlag.Set(VehicleDamage::derailed)) { EventFlag = true; MainSwitch(false, range_t::local); @@ -852,13 +852,13 @@ void TMoverParameters::Derail(DerailReason const Reason) bool TMoverParameters::leaves_track() const { - return Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1) && TestFlag(DamageFlag, dtrain_out) && Derailed != derailment::outcome::none && + return Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1) && DamageFlag.HasAll(VehicleDamage::derailed) && Derailed != derailment::outcome::none && false == OffTrack.active(); } void TMoverParameters::pull_off(int const Side, double const Acceleration, std::string const &Why) { - if (Global.derailment != global_settings::derailment_model::physical || false == SetFlag(DamageFlag, dtrain_out)) + if (Global.derailment != global_settings::derailment_model::physical || false == DamageFlag.Set(VehicleDamage::derailed)) { return; } diff --git a/physics/components/commands.cpp b/physics/components/commands.cpp index 74f1a37bc..57d33dc8e 100644 --- a/physics/components/commands.cpp +++ b/physics/components/commands.cpp @@ -710,6 +710,26 @@ void TMoverParameters::DoorRemoteCommand(bool const Open, double const CValue1, } } +namespace +{ + +// the number of SetDamage on the set of the damage, as SetFlag() did on the number: a positive one adds its values, a +// negative one takes them away where all of them are there; returns whether it changed the set +bool setOrClear(DamageSet &damage, int const number) +{ + if (number > 0) + { + return damage.Set(DamageSet::FromBits(number)); + } + if (number < 0) + { + return damage.Clear(DamageSet::FromBits(-number)); + } + return false; +} + +} // namespace + // RunCommand() for the load and the damage; returns whether the command is one of them bool TMoverParameters::RunLoadCommand(VehicleCommand const Command, double CValue1, double CValue2, std::string_view const Argument, bool &OK) { @@ -753,13 +773,13 @@ bool TMoverParameters::RunLoadCommand(VehicleCommand const Command, double CValu else if (Command == VehicleCommand::setDamage) { if (CValue2 == 1) - OK = SetFlag(DamageFlag, static_cast(floor(CValue1))); + OK = setOrClear(DamageFlag, static_cast(floor(CValue1))); if (CValue2 == -1) { - auto const derailed{TestFlag(DamageFlag, dtrain_out)}; - OK = SetFlag(DamageFlag, static_cast(-floor(CValue1))); + auto const derailed{DamageFlag.HasAll(VehicleDamage::derailed)}; + OK = setOrClear(DamageFlag, static_cast(-floor(CValue1))); // taking the derailment off puts the vehicle back on the rails, with what the criteria of derailment held - if (derailed && false == TestFlag(DamageFlag, dtrain_out)) + if (derailed && false == DamageFlag.HasAll(VehicleDamage::derailed)) rerail(); } } diff --git a/physics/components/couplers.cpp b/physics/components/couplers.cpp index 5fb3b55ef..b6f750e86 100644 --- a/physics/components/couplers.cpp +++ b/physics/components/couplers.cpp @@ -126,7 +126,7 @@ int TMoverParameters::DettachStatus(int ConnectNo) return 0; // nie ma nic, to rozłączanie jest OK if (false == Couplers[ConnectNo].CouplingFlag.HasAny(Coupling::coupler)) return -Couplers[ConnectNo].CouplingFlag.Bits(); // hak nie połączony - rozłączanie jest OK - if (TestFlag(DamageFlag, dtrain_coupling)) + if (DamageFlag.HasAll(VehicleDamage::coupling)) return -Couplers[ConnectNo].CouplingFlag.Bits(); // hak urwany - rozłączanie jest OK // CouplerDist(ConnectNo); if (Couplers[ConnectNo].type() != TCouplerType::Screw || Neighbours[ConnectNo].distance < 0.01) diff --git a/physics/components/electrics.cpp b/physics/components/electrics.cpp index 536d24579..a14840bc3 100644 --- a/physics/components/electrics.cpp +++ b/physics/components/electrics.cpp @@ -1019,7 +1019,7 @@ bool TMoverParameters::MainSwitchCheck() const (HasCamshaft ? IsMainCtrlActualNoPowerPos() : LineBreakerClosesOnlyAtNoPowerPos ? IsMainCtrlNoPowerPos() : true) && - false == TestFlag(DamageFlag, dtrain_out) && false == TestFlag(EngDmgFlag, 1) && false == EmergencyBrakeHoldsMainOff(); + false == DamageFlag.HasAll(VehicleDamage::derailed) && false == TestFlag(EngDmgFlag, 1) && false == EmergencyBrakeHoldsMainOff(); } // ************************************************************************************************* diff --git a/physics/components/traction.cpp b/physics/components/traction.cpp index 00b760db6..ff3051c70 100644 --- a/physics/components/traction.cpp +++ b/physics/components/traction.cpp @@ -250,10 +250,10 @@ void TMoverParameters::MotorFailuresCheck(double const n) { if (FuzzyLogic(abs(n), nmax * 1.1, p_elengproblem) && MainSwitch(false)) EventFlag = true; /*zbyt duze obroty - wywalanie wskutek ognia okreznego*/ - if (TestFlag(DamageFlag, dtrain_engine) && FuzzyLogic(MotorCurrent, (double)ImaxLo / 10.0, p_elengproblem) && MainSwitch(false)) + if (DamageFlag.HasAll(VehicleDamage::engine) && FuzzyLogic(MotorCurrent, (double)ImaxLo / 10.0, p_elengproblem) && MainSwitch(false)) EventFlag = true; /*uszkodzony silnik (uplywy)*/ /* or FuzzyLogic(Abs(U/Mn),2*NominalVoltage,1)) then */ /*poprawic potem*/ - if ((FuzzyLogic(abs(Im), Imax * 2, p_elengproblem) || FuzzyLogic(abs(n), nmax * 1.11, p_elengproblem)) && SetFlag(DamageFlag, dtrain_engine)) + if ((FuzzyLogic(abs(Im), Imax * 2, p_elengproblem) || FuzzyLogic(abs(n), nmax * 1.11, p_elengproblem)) && DamageFlag.Set(VehicleDamage::engine)) EventFlag = true; /*! dorobic grzanie oporow rozruchowych i silnika*/ } @@ -1573,9 +1573,9 @@ double TMoverParameters::v2n(void) SlippingWheels = false; // wygaszenie poslizgu */ //poslizg jest w innym miejscu wygaszany też if (SlippingWheels) // nie ma zwiazku z predkoscia liniowa V { // McZapkie-221103: uszkodzenia kol podczas poslizgu - if (deltan > dmgn && FuzzyLogic(deltan, dmgn, p_slippdmg) && SetFlag(DamageFlag, dtrain_wheelwear)) // podkucie + if (deltan > dmgn && FuzzyLogic(deltan, dmgn, p_slippdmg) && DamageFlag.Set(VehicleDamage::wheelWear)) // podkucie EventFlag = true; - if (deltan < -dmgn && FuzzyLogic(-deltan, dmgn, p_slippdmg) && SetFlag(DamageFlag, dtrain_thinwheel)) // wycieranie sie obreczy + if (deltan < -dmgn && FuzzyLogic(-deltan, dmgn, p_slippdmg) && DamageFlag.Set(VehicleDamage::thinWheel)) // wycieranie sie obreczy EventFlag = true; n = nrot; // predkosc obrotowa nie zalezy od predkosci liniowej } @@ -1617,7 +1617,7 @@ double TMoverParameters::MomentumF(double I, double Iw, int SCP) const bool TMoverParameters::CutOffEngine(void) { bool COE = false; // Ra: wartość domyślna, sprawdzić to trzeba - if (NPoweredAxles > 0 && CabActive == 0 && EngineType == TEngineType::ElectricSeriesMotor && SetFlag(DamageFlag, -dtrain_engine)) + if (NPoweredAxles > 0 && CabActive == 0 && EngineType == TEngineType::ElectricSeriesMotor && DamageFlag.Clear(VehicleDamage::engine)) { NPoweredAxles = NPoweredAxles / 2; // bylo div czyli mod? COE = true; diff --git a/physics/mover.h b/physics/mover.h index b07ee559e..25db352e1 100644 --- a/physics/mover.h +++ b/physics/mover.h @@ -1485,7 +1485,7 @@ class TMoverParameters double LimPipePress = 0.0; /*stabilizator cisnienia*/ double ActFlowSpeed = 0.0; /*szybkosc stabilizatora*/ - int DamageFlag = 0; // kombinacja bitowa stalych dtrain_* } + DamageSet DamageFlag; // the damage of the vehicle int EngDmgFlag = 0; // kombinacja bitowa stalych usterek} // EndSignalsFlag: byte; {ABu 060205: zmiany - koncowki: 1/16 - swiatla prz/tyl, 2/31 - blachy prz/tyl} @@ -1787,7 +1787,7 @@ class TMoverParameters void derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track, std::string const *TrackName = nullptr); // height of the centre of gravity above the rail with the load [m] double centre_of_gravity() const; - // the vehicle is back on the rails (resetconsist, SetDamage taking dtrain_out off): not derailed any more, and the + // the vehicle is back on the rails (resetconsist, SetDamage taking VehicleDamage::derailed off): not derailed any more, and the // criteria of derailment start from scratch, so a later derailment goes the way its model has it void rerail(); // what resetconsist does to a vehicle: no damage of any kind, the alarm chain released, back on the rails diff --git a/physics/vehicletypes.h b/physics/vehicletypes.h index 4cd26d21b..d61ad32b1 100644 --- a/physics/vehicletypes.h +++ b/physics/vehicletypes.h @@ -15,6 +15,8 @@ http://mozilla.org/MPL/2.0/. #include #include +#include "utilities/enumset.h" + #include "physics/vehiclecommand.h" /// Global counter incremented when a string-to-numeric conversion fails during config parsing. @@ -65,31 +67,27 @@ static int const dtrack_nomove = 64; /// Track damage flag: rails missing entirely. static int const dtrack_norail = 128; -/*uszkodzenia taboru*/ -/// Vehicle damage flag: thin wheel (locomotives). -static int const dtrain_thinwheel = 1; /*dla lokomotyw*/ -/// Vehicle damage flag: shifted load (wagons). -static int const dtrain_loadshift = 1; /*dla wagonow*/ -/// Vehicle damage flag: wheel wear. -static int const dtrain_wheelwear = 2; -/// Vehicle damage flag: bearing failure. -static int const dtrain_bearing = 4; -/// Vehicle damage flag: coupling damage. -static int const dtrain_coupling = 8; -/// Vehicle damage flag: ventilator failure (electric locomotive). -static int const dtrain_ventilator = 16; /*dla lokomotywy el.*/ -/// Vehicle damage flag: load damage (wagons). -static int const dtrain_loaddamage = 16; /*dla wagonow*/ -/// Vehicle damage flag: engine failure (locomotives). -static int const dtrain_engine = 32; /*dla lokomotyw*/ -/// Vehicle damage flag: load destroyed (wagons). -static int const dtrain_loaddestroyed = 32; /*dla wagonow*/ -/// Vehicle damage flag: axle damage. -static int const dtrain_axle = 64; -/// Vehicle damage flag: derailment. -static int const dtrain_out = 128; /*wykolejenie*/ -/// Vehicle damage flag: broken pantograph. -static int const dtrain_pantograph = 256; /*polamanie pantografu*/ +/// The damage of a vehicle, DamageFlag. A bit means one thing for a locomotive and another for a wagon, +/// where two values share it. The numbers are the ones of the SetDamage command of the scenery. +enum class VehicleDamage : unsigned +{ + thinWheel = 0x1, // a locomotive: a wheel worn thin + loadShift = 0x1, // a wagon: the load shifted + wheelWear = 0x2, // the wheels worn + bearing = 0x4, // a bearing failed + coupling = 0x8, // the coupling broken + ventilator = 0x10, // an electric locomotive: a ventilator failed + loadDamage = 0x10, // a wagon: the load damaged + engine = 0x20, // a locomotive: the engine failed + loadDestroyed = 0x20, // a wagon: the load destroyed + axle = 0x40, // an axle broken + derailed = 0x80, // off the rails + pantograph = 0x100, // a pantograph broken +}; +template <> struct IsEnumSetKind : std::true_type +{ +}; +using DamageSet = EnumSet; /// Reason for a derailment event. enum DerailReason @@ -165,111 +163,12 @@ enum class Coupling : unsigned }; /// A set of the kinds of connection of a coupling: what a coupling joins, what a vehicle allows, what a -/// command needs to pass. Read from and written to the numbers of the files only through FromBits() and Bits(). -class CouplingSet +/// command needs to pass. +template <> struct IsEnumSetKind : std::true_type { -public: - constexpr CouplingSet() = default; - constexpr CouplingSet(Coupling const kind) : bits{static_cast(kind)} {} // NOSONAR: a kind is a set of one - // the set the number of a file gives (the sum of the numbers of the kinds) - static constexpr CouplingSet FromBits(int const number) - { - CouplingSet set; - set.bits = static_cast(number); - return set; - } - // every kind of coupling: a coupling of any kind has one of them - static constexpr CouplingSet All() - { - return FromBits(-1); - } - // any kind at all: as the old number was true when it wasn't zero - constexpr explicit operator bool() const - { - return bits != 0; - } - // the number of the set, for the files and the log - constexpr int Bits() const - { - return static_cast(bits); - } - constexpr bool Empty() const - { - return bits == 0; - } - // all the kinds of the other set are in this one - constexpr bool HasAll(CouplingSet const other) const - { - return (bits & other.bits) == other.bits; - } - // any of the kinds of the other set is in this one - constexpr bool HasAny(CouplingSet const other) const - { - return (bits & other.bits) != 0; - } - // adds the kinds; returns whether any of them was missing - constexpr bool Set(CouplingSet const other) - { - if (HasAll(other)) - { - return false; - } - bits |= other.bits; - return true; - } - // takes the kinds away, where all of them are there; returns whether it did - constexpr bool Clear(CouplingSet const other) - { - if (false == HasAll(other)) - { - return false; - } - bits &= ~other.bits; - return true; - } - // this set without the kinds of the other - constexpr CouplingSet Without(CouplingSet const other) const - { - return FromBits(static_cast(bits & ~other.bits)); - } - constexpr CouplingSet &operator|=(CouplingSet const other) - { - bits |= other.bits; - return *this; - } - constexpr CouplingSet &operator&=(CouplingSet const other) - { - bits &= other.bits; - return *this; - } - friend constexpr CouplingSet operator|(CouplingSet left, CouplingSet const right) - { - return left |= right; - } - friend constexpr CouplingSet operator&(CouplingSet left, CouplingSet const right) - { - return left &= right; - } - // the kinds in one of the sets and not in the other: what changed between them - constexpr CouplingSet &operator^=(CouplingSet const other) - { - bits ^= other.bits; - return *this; - } - friend constexpr CouplingSet operator^(CouplingSet left, CouplingSet const right) - { - return left ^= right; - } - friend constexpr bool operator==(CouplingSet const &left, CouplingSet const &right) = default; - -private: - unsigned bits{0}; }; +using CouplingSet = EnumSet; -constexpr CouplingSet operator|(Coupling const left, Coupling const right) -{ - return CouplingSet{left} | CouplingSet{right}; -} /// Range of effect for a control command (mutually exclusive). enum class range_t { diff --git a/scene/scene.cpp b/scene/scene.cpp index bdcb3efb4..3f67b4d31 100644 --- a/scene/scene.cpp +++ b/scene/scene.cpp @@ -131,7 +131,7 @@ basic_cell::update_traction( TDynamicObject *Vehicle, int const Pantographindex // i do tego jeszcze wejdzie pod ślizg if( fHorizontal <= 0.0 ) { // 0.635 dla AKP-1 AKP-4E - SetFlag( Vehicle->MoverParameters->DamageFlag, dtrain_pantograph ); + Vehicle->MoverParameters->DamageFlag.Set(VehicleDamage::pantograph); pantograph->PantWys = -1.0; // ujemna liczba oznacza połamanie pantograph->hvPowerWire = nullptr; // bo inaczej się zasila w nieskończoność z połamanego if( Vehicle->MoverParameters->EnginePowerSource.CollectorParameters.CollectorsNo > 0 ) { diff --git a/tests/unit/test_cab.cpp b/tests/unit/test_cab.cpp index 40a94d552..c0896e6e3 100644 --- a/tests/unit/test_cab.cpp +++ b/tests/unit/test_cab.cpp @@ -164,17 +164,17 @@ TEST_CASE("cab: damaged motors cut off in a car without a driver") { vehicle driven{definition::fiz("ew58_v1/ew58-sa"), 0.0, "test", 1}; driven->BatterySwitch(true); REQUIRE(driven->CabActivisation()); - driven->DamageFlag |= dtrain_engine; + driven->DamageFlag |= VehicleDamage::engine; CHECK_FALSE(driven->CutOffEngine()); vehicle car{definition::fiz("ew58_v1/ew58-sa")}; auto const axles{car->NPoweredAxles}; CHECK_FALSE(car->CutOffEngine()); - car->DamageFlag |= dtrain_engine; + car->DamageFlag |= VehicleDamage::engine; CHECK(car->CutOffEngine()); CHECK(car->NPoweredAxles == axles / 2); - CHECK_FALSE(TestFlag(car->DamageFlag, dtrain_engine)); + CHECK_FALSE(car->DamageFlag.HasAll(VehicleDamage::engine)); vehicle wagon{definition::fiz("3wl_v2/3wl")}; - wagon->DamageFlag |= dtrain_engine; + wagon->DamageFlag |= VehicleDamage::engine; CHECK_FALSE(wagon->CutOffEngine()); } diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index be5910011..efc144e69 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -112,7 +112,7 @@ cl::crush_curve const locomotive_curve{cl::default_crush(cl::vehicle_kind::locom // ---- trains of real vehicles bool derailed(TMoverParameters const &Vehicle) { - return TestFlag(Vehicle.DamageFlag, dtrain_out); + return Vehicle.DamageFlag.HasAll(VehicleDamage::derailed); } double crush_of(TMoverParameters const &Vehicle) { @@ -689,7 +689,7 @@ TEST_CASE("collisions: a repaired vehicle has its ends rebuilt and is back on th for (auto *vehicle : {&wagon, &locomotive}) { auto &mover{vehicle->mover()}; mover.repair_damage(); - CHECK(mover.DamageFlag == 0); + CHECK(mover.DamageFlag.Empty()); CHECK(mover.Derailed == derailment::outcome::none); CHECK(mover.CollisionDerail == NONE); CHECK(mover.pushed_off_monitor.distance() == 0.0); @@ -712,12 +712,12 @@ TEST_CASE("collisions: the repair of a coupler torn off by the crush rebuilds it coupler.crush = 0.3; coupler.broken = true; coupler.hit_force = 2.0e6; - SetFlag(wagon->DamageFlag, dtrain_coupling); + wagon->DamageFlag.Set(VehicleDamage::coupling); REQUIRE(wagon->repair_coupler(end::rear)); CHECK(coupler.crush == 0.0); CHECK(coupler.hit_force == 0.0); CHECK_FALSE(coupler.broken); - CHECK_FALSE(TestFlag(wagon->DamageFlag, dtrain_coupling)); + CHECK_FALSE(wagon->DamageFlag.HasAll(VehicleDamage::coupling)); } TEST_CASE("collisions: SetDamage taking the derailment off clears the collision's") { @@ -725,10 +725,10 @@ TEST_CASE("collisions: SetDamage taking the derailment off clears the collision' wagon->derail_in_collision(COLLISION_PUSHED_OFF, "test"); REQUIRE(wagon->CollisionDerail == COLLISION_PUSHED_OFF); REQUIRE(wagon->Derailed == derailment::outcome::off_rails); - wagon->RunCommand(VehicleCommand::setDamage, dtrain_out, -1); + wagon->RunCommand(VehicleCommand::setDamage, DamageSet{VehicleDamage::derailed}.Bits(), -1); CHECK(wagon->CollisionDerail == NONE); CHECK(wagon->Derailed == derailment::outcome::none); - CHECK_FALSE(TestFlag(wagon->DamageFlag, dtrain_out)); + CHECK_FALSE(wagon->DamageFlag.HasAll(VehicleDamage::derailed)); } // ---- the model of eu07.ini diff --git a/tests/unit/test_commands.cpp b/tests/unit/test_commands.cpp index bd06bb26b..ac9d72fee 100644 --- a/tests/unit/test_commands.cpp +++ b/tests/unit/test_commands.cpp @@ -64,7 +64,7 @@ std::vector state() { {"PantsValve", [](auto const &M) { return flag(M.PantsValve.is_enabled) + 2 * flag(M.PantsValve.is_disabled); }}, {"MaxCurrentHigh", [](auto const &M) { return flag(M.MotorOverloadRelayHighThreshold); }}, {"Imin", [](auto const &M) { return M.Imin; }}, - {"DamageFlag", [](auto const &M) { return M.DamageFlag; }}, + {"DamageFlag", [](auto const &M) { return M.DamageFlag.Bits(); }}, {"RadioStop", [](auto const &M) { return flag(M.RadioStopFlag); }}, {"BrakeDelayFlag", [](auto const &M) { return M.BrakeDelayFlag; }}, {"SandDose", [](auto const &M) { return flag(M.SandDose); }}, diff --git a/tests/unit/test_controls.cpp b/tests/unit/test_controls.cpp index 47b852f2d..133794ccd 100644 --- a/tests/unit/test_controls.cpp +++ b/tests/unit/test_controls.cpp @@ -514,7 +514,7 @@ TEST_CASE("controls: a locomotive running into a standing wagon") { // slow, the locomotive pushes the wagon off, the buffers only touching, and both roll to a stop; fast, // the wagon derails where it stands auto const derailed{speed > 30.0}; - CHECK(TestFlag(wagon.DamageFlag, dtrain_out) == derailed); + CHECK(wagon.DamageFlag.HasAll(VehicleDamage::derailed) == derailed); CHECK((std::abs(wagon.DistCounter) > 0.0001) != derailed); CHECK(stopped(scenario)); scenario.check(); diff --git a/tests/unit/test_coupler_physics.cpp b/tests/unit/test_coupler_physics.cpp index 31b46a165..bbb935365 100644 --- a/tests/unit/test_coupler_physics.cpp +++ b/tests/unit/test_coupler_physics.cpp @@ -279,7 +279,7 @@ vehicle loose_wagon(double Slack, double Velocity, std::string const &Name) { } bool coupler_damaged(vehicle &Vehicle) { - return TestFlag(Vehicle->DamageFlag, dtrain_coupling); + return Vehicle->DamageFlag.HasAll(VehicleDamage::coupling); } } // namespace @@ -448,7 +448,7 @@ TEST_CASE("coupler physics: automatic couplers still catch a wagon rolling into REQUIRE(pair.coupled()); pair.run(2.0); CHECK(moving.speed() == doctest::Approx(standing.speed()).epsilon(0.1)); - CHECK_FALSE(TestFlag(moving->DamageFlag, dtrain_out)); + CHECK_FALSE(moving->DamageFlag.HasAll(VehicleDamage::derailed)); } TEST_CASE("couplers: a broken coupling of vehicles facing each other uncouples the ends coupled") { @@ -479,7 +479,7 @@ TEST_CASE("couplers: a broken coupler is repaired alone, with the one of the veh REQUIRE(second->Couplers[end::front].broken); REQUIRE(first->Couplers[end::rear].broken); REQUIRE(third->Couplers[end::front].broken); - REQUIRE(TestFlag(second->DamageFlag, dtrain_coupling)); + REQUIRE(second->DamageFlag.HasAll(VehicleDamage::coupling)); // nothing to repair at the far end of the first wagon CHECK_FALSE(first->repair_coupler(end::front)); @@ -491,12 +491,12 @@ TEST_CASE("couplers: a broken coupler is repaired alone, with the one of the veh CHECK(second->Couplers[end::rear].broken); CHECK(third->Couplers[end::front].broken); // the second wagon keeps its damage, and its emergency braking, while a coupler of it is broken - CHECK(TestFlag(second->DamageFlag, dtrain_coupling)); + CHECK(second->DamageFlag.HasAll(VehicleDamage::coupling)); CHECK(second->AlarmChainFlag); CHECK(third->repair_coupler(end::front)); CHECK_FALSE(second->Couplers[end::rear].broken); - CHECK_FALSE(TestFlag(second->DamageFlag, dtrain_coupling)); + CHECK_FALSE(second->DamageFlag.HasAll(VehicleDamage::coupling)); CHECK_FALSE(second->AlarmChainFlag); // repaired, not coupled: the vehicles are coupled again as usual CHECK(second->Couplers[end::rear].CouplingFlag == Coupling::none); @@ -560,7 +560,7 @@ TEST_CASE("coupler physics: a hit on a braked train runs through it as a wave, w CAPTURE(i); CAPTURE(peak[i]); REQUIRE(started[i] >= 0.0); - CHECK_FALSE(TestFlag(train[i]->DamageFlag, dtrain_out)); + CHECK_FALSE(train[i]->DamageFlag.HasAll(VehicleDamage::derailed)); } // the wagon hit first takes less than the hit, the one at the far end the least CHECK(peak[wagons - 1] < 12.0); diff --git a/tests/unit/test_couplers.cpp b/tests/unit/test_couplers.cpp index 44b3ad663..825102f9a 100644 --- a/tests/unit/test_couplers.cpp +++ b/tests/unit/test_couplers.cpp @@ -24,7 +24,7 @@ vehicle heavy_automatic_wagon(double Velocity, std::string const &Name) { } bool derailed(vehicle &Vehicle) { - return TestFlag(Vehicle->DamageFlag, dtrain_out); + return Vehicle->DamageFlag.HasAll(VehicleDamage::derailed); } // runs the pair for Seconds, returns whether the vehicles were coupled at any point diff --git a/tests/unit/test_couplers_trains.cpp b/tests/unit/test_couplers_trains.cpp index cf4dc58b8..ccd0ffae4 100644 --- a/tests/unit/test_couplers_trains.cpp +++ b/tests/unit/test_couplers_trains.cpp @@ -90,7 +90,7 @@ TEST_CASE("couplers: a screw coupler uncoupled with the buffers apart, or with t auto &wagon{train.add(definition::fiz("3wl_v2/3wl"), 0, Coupling::none, 0.0, gap).mover()}; REQUIRE(locomotive.Attach(end::rear, end::front, &wagon, couplingtype, true)); if (damaged) { - SetFlag(locomotive.DamageFlag, dtrain_coupling); + locomotive.DamageFlag.Set(VehicleDamage::coupling); } train.step(); CHECK((locomotive.DettachStatus(end::rear) < 0) == apart); @@ -145,20 +145,20 @@ TEST_CASE("couplers: a coupler broken, with its brake hose torn off") { auto &wagon{train.add(definition::fiz("3wl_v2/3wl")).mover()}; REQUIRE(locomotive.Couplers[end::rear].Connected == &wagon); locomotive.damage_coupler(end::rear); - CHECK(TestFlag(locomotive.DamageFlag, dtrain_coupling)); + CHECK(locomotive.DamageFlag.HasAll(VehicleDamage::coupling)); CHECK(locomotive.AlarmChainFlag); CHECK(locomotive.Couplers[end::rear].CouplingFlag == Coupling::none); CHECK(wagon.Couplers[end::front].CouplingFlag == Coupling::none); // the front coupler of the wagon, broken on its own: no hose to tear wagon.damage_coupler(end::front); - CHECK(TestFlag(wagon.DamageFlag, dtrain_coupling)); + CHECK(wagon.DamageFlag.HasAll(VehicleDamage::coupling)); CHECK_FALSE(wagon.AlarmChainFlag); // articulated couplers don't break consist articulated; auto &unit{articulated.add(definition::fiz("impuls_v1/31we-a_pr")).mover()}; articulated.add(definition::fiz("impuls_v1/31we-b_pr")); unit.damage_coupler(end::rear); - CHECK_FALSE(TestFlag(unit.DamageFlag, dtrain_coupling)); + CHECK_FALSE(unit.DamageFlag.HasAll(VehicleDamage::coupling)); CHECK(unit.Couplers[end::rear].CouplingFlag != Coupling::none); } @@ -186,8 +186,8 @@ TEST_CASE("couplers: collisions fast enough to derail") { scenario.add(frontpath, 0, consist::full_coupling, frontspeed); scenario.add(back, 0, Coupling::none, backspeed, 20.0); scenario.wait(10.0); - CHECK(TestFlag(scenario.vehicle(0).DamageFlag, dtrain_out) == frontout); - CHECK(TestFlag(scenario.vehicle(1).DamageFlag, dtrain_out) == backout); + CHECK(scenario.vehicle(0).DamageFlag.HasAll(VehicleDamage::derailed) == frontout); + CHECK(scenario.vehicle(1).DamageFlag.HasAll(VehicleDamage::derailed) == backout); scenario.check(); } } diff --git a/tests/unit/test_derail_motion.cpp b/tests/unit/test_derail_motion.cpp index d4a44edda..2256ea455 100644 --- a/tests/unit/test_derail_motion.cpp +++ b/tests/unit/test_derail_motion.cpp @@ -441,7 +441,7 @@ TEST_CASE("derail motion: the vehicle leaves the track with physics.derailment n vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 40.0}; eu07vehicle.damage_track(dtrack_norail); eu07vehicle.step(); - REQUIRE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + REQUIRE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); CHECK(eu07vehicle->Derailed == dr::outcome::off_rails); CHECK(eu07vehicle->DerailCause == dm::cause::end_of_track); CHECK(eu07vehicle->leaves_track()); @@ -450,7 +450,7 @@ TEST_CASE("derail motion: the vehicle leaves the track with physics.derailment n model_setting const physical{global_settings::derailment_model::physical}; vehicle pulled{definition::fiz("4e_v1/4e"), 40.0}; pulled->pull_off(-1, 5.0, "test"); - CHECK(TestFlag(pulled->DamageFlag, dtrain_out)); + CHECK(pulled->DamageFlag.HasAll(VehicleDamage::derailed)); CHECK(pulled->Derailed == dr::outcome::off_rails); CHECK(pulled->DerailCause == dm::cause::pulled_off); CHECK(pulled->DerailSide == -1); @@ -473,7 +473,7 @@ TEST_CASE("derail motion: with physics.derailment monitor and old the vehicle st for (int step = 0; step < 600; ++step) { fast.step(curve); } - REQUIRE(TestFlag(fast->DamageFlag, dtrain_out)); + REQUIRE(fast->DamageFlag.HasAll(VehicleDamage::derailed)); CHECK(fast->Derailed == dr::outcome::none); CHECK_FALSE(fast->leaves_track()); CHECK_FALSE(fast->OffTrack.active()); @@ -482,13 +482,13 @@ TEST_CASE("derail motion: with physics.derailment monitor and old the vehicle st vehicle ending{definition::fiz("4e_v1/4e"), 40.0}; ending.damage_track(dtrack_norail); ending.step(); - REQUIRE(TestFlag(ending->DamageFlag, dtrain_out)); + REQUIRE(ending->DamageFlag.HasAll(VehicleDamage::derailed)); CHECK(ending->Derailed == dr::outcome::none); CHECK_FALSE(ending->leaves_track()); // nor is a vehicle pulled off it vehicle pulled{definition::fiz("4e_v1/4e"), 40.0}; pulled->pull_off(1, 5.0, "test"); - CHECK_FALSE(TestFlag(pulled->DamageFlag, dtrain_out)); + CHECK_FALSE(pulled->DamageFlag.HasAll(VehicleDamage::derailed)); } } diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp index 8fee07d9a..1c96b4f52 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -47,7 +47,7 @@ TEST_CASE("derailment: a vehicle too fast in a curve") { for (int step = 0; step < 300; ++step) { eu07vehicle.step(curve); } - CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + CHECK_FALSE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); CHECK(eu07vehicle->Derailed == dr::outcome::none); } SUBCASE("over it, it falls over and slides to a stop on its side") { @@ -57,7 +57,7 @@ TEST_CASE("derailment: a vehicle too fast in a curve") { for (int step = 0; step < 10; ++step) { eu07vehicle.step(curve); } - REQUIRE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + REQUIRE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); CHECK(eu07vehicle->Derailed == dr::outcome::overturned); CHECK_FALSE(eu07vehicle->Mains); // not stopped dead as the legacy model has it: it slows down at half of g on the 80 of its 96 t @@ -116,7 +116,7 @@ TEST_CASE("derailment: the model of eu07.ini") { for (int step = 0; step < 300; ++step) { eu07vehicle.step(curve); } - CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + CHECK_FALSE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); } SUBCASE("old: the legacy draw stops the vehicle dead") { model_setting const old{global_settings::derailment_model::old}; @@ -125,7 +125,7 @@ TEST_CASE("derailment: the model of eu07.ini") { eu07vehicle.step(curve); } // far over its threshold the draw comes out at once - CHECK(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + CHECK(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); CHECK(eu07vehicle->Derailed == dr::outcome::none); CHECK(eu07vehicle->V == doctest::Approx(0.0).epsilon(0.01)); } @@ -180,7 +180,7 @@ TEST_CASE("derailment: a repaired vehicle is back on the rails") { REQUIRE(repaired->Derailed == dr::outcome::overturned); REQUIRE(repaired->V == 0.0); repaired->repair_damage(); - CHECK(repaired->DamageFlag == 0); + CHECK(repaired->DamageFlag.Empty()); CHECK(repaired->Derailed == dr::outcome::none); CHECK(repaired->derailment_distance == 0.0); CHECK(repaired->OffsetTrackH == 0.0); @@ -235,11 +235,11 @@ TEST_CASE("derailment: SetDamage taking the derailment off puts the vehicle back } REQUIRE(eu07vehicle->Derailed == dr::outcome::overturned); // another flag taken off leaves it derailed - eu07vehicle->RunCommand(VehicleCommand::setDamage, dtrain_engine, 1); - eu07vehicle->RunCommand(VehicleCommand::setDamage, dtrain_engine, -1); + eu07vehicle->RunCommand(VehicleCommand::setDamage, DamageSet{VehicleDamage::engine}.Bits(), 1); + eu07vehicle->RunCommand(VehicleCommand::setDamage, DamageSet{VehicleDamage::engine}.Bits(), -1); CHECK(eu07vehicle->Derailed == dr::outcome::overturned); - CHECK(eu07vehicle->RunCommand(VehicleCommand::setDamage, dtrain_out, -1)); - CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + CHECK(eu07vehicle->RunCommand(VehicleCommand::setDamage, DamageSet{VehicleDamage::derailed}.Bits(), -1)); + CHECK_FALSE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); CHECK(eu07vehicle->Derailed == dr::outcome::none); } @@ -274,7 +274,7 @@ TEST_CASE("derailment: monitor, the legacy draw decides and the log tells what t for (int step = 0; step < 100; ++step) { eu07vehicle.step(curve); } - CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + CHECK_FALSE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); CHECK(eu07vehicle->Derailed == dr::outcome::none); // once on a track, however long it stays over the criteria CHECK(eu07vehicle->derailment_reports == 1); @@ -287,7 +287,7 @@ TEST_CASE("derailment: monitor, the legacy draw decides and the log tells what t eu07vehicle.step(next); } CHECK(eu07vehicle->derailment_reports == 2); - CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + CHECK_FALSE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); SUBCASE("under the criteria nothing is told") { vehicle slower{definition::fiz("4e_v1/4e"), critical - 5.0}; @@ -301,7 +301,7 @@ TEST_CASE("derailment: monitor, the legacy draw decides and the log tells what t for (int step = 0; step < 600; ++step) { faster.step(curve); } - CHECK(TestFlag(faster->DamageFlag, dtrain_out)); + CHECK(faster->DamageFlag.HasAll(VehicleDamage::derailed)); CHECK(faster->Derailed == dr::outcome::none); CHECK(faster->V == doctest::Approx(0.0).epsilon(0.01)); } diff --git a/tests/unit/test_queries.cpp b/tests/unit/test_queries.cpp index 797e40534..677b993eb 100644 --- a/tests/unit/test_queries.cpp +++ b/tests/unit/test_queries.cpp @@ -16,23 +16,23 @@ TEST_CASE("queries: the damage of a vehicle as the driver's panel describes it") REQUIRE(wagon->Power < 0.1); struct damage { - int flag; + DamageSet flag; char const *locomotive; char const *wagon; }; for (auto const &[flag, locomotivetext, wagontext] : { - damage{0, "OK", "OK"}, - damage{dtrain_thinwheel, "Thin wheel", "Load shifted"}, - damage{dtrain_wheelwear, "Wheel wear", "Wheel wear"}, - damage{dtrain_bearing, "Bearing damaged", "Bearing damaged"}, - damage{dtrain_coupling, "Coupler broken", "Coupler broken"}, - damage{dtrain_loaddamage, "Ventilator damaged", "Load damaged"}, - damage{dtrain_loaddestroyed, "Engine damaged", "LOAD DESTROYED"}, - damage{dtrain_axle, "Axle broken", "Axle broken"}, - damage{dtrain_out, "DERAILED", "DERAILED"}, + damage{{}, "OK", "OK"}, + damage{VehicleDamage::thinWheel, "Thin wheel", "Load shifted"}, + damage{VehicleDamage::wheelWear, "Wheel wear", "Wheel wear"}, + damage{VehicleDamage::bearing, "Bearing damaged", "Bearing damaged"}, + damage{VehicleDamage::coupling, "Coupler broken", "Coupler broken"}, + damage{VehicleDamage::loadDamage, "Ventilator damaged", "Load damaged"}, + damage{VehicleDamage::loadDestroyed, "Engine damaged", "LOAD DESTROYED"}, + damage{VehicleDamage::axle, "Axle broken", "Axle broken"}, + damage{VehicleDamage::derailed, "DERAILED", "DERAILED"}, // the last flag of the list wins - damage{dtrain_bearing | dtrain_axle, "Axle broken", "Axle broken"}, - damage{255, "WRECKED", "WRECKED"}, + damage{VehicleDamage::bearing | VehicleDamage::axle, "Axle broken", "Axle broken"}, + damage{DamageSet::FromBits(255), "WRECKED", "WRECKED"}, }) { CAPTURE(flag); locomotive->DamageFlag = flag; @@ -41,7 +41,7 @@ TEST_CASE("queries: the damage of a vehicle as the driver's panel describes it") CHECK(wagon->EngineDescription(0) == wagontext); } // flat wheels count as worn ones - wagon->DamageFlag = 0; + wagon->DamageFlag = {}; wagon->WheelFlat = 6.0; CHECK(wagon->EngineDescription(0) == "Wheel wear"); // nothing else is described diff --git a/utilities/enumset.h b/utilities/enumset.h new file mode 100644 index 000000000..ae5dea20e --- /dev/null +++ b/utilities/enumset.h @@ -0,0 +1,130 @@ +/* +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/. +*/ + +// a set of the values of an enum class whose values are bits: what a coupling joins, the damage of a vehicle. the +// numbers of the files (their sums of the bits) come in only through FromBits() and go out through Bits() + +#pragma once + +#include + +// an enum is a kind of the sets by a specialisation of this, which also gives its operator | +template struct IsEnumSetKind : std::false_type +{ +}; + +template class EnumSet +{ + static_assert(std::is_enum_v, "a set of the values of an enum"); + +public: + constexpr EnumSet() = default; + constexpr EnumSet(Enum const value) : bits{static_cast(value)} {} // NOSONAR: a value is a set of one + // the set the number of a file gives (the sum of the numbers of the values) + static constexpr EnumSet FromBits(int const number) + { + EnumSet set; + set.bits = static_cast(number); + return set; + } + // every value: a set of any of them has one of these + static constexpr EnumSet All() + { + return FromBits(-1); + } + // the number of the set, for the files and the log + constexpr int Bits() const + { + return static_cast(bits); + } + constexpr bool Empty() const + { + return bits == 0; + } + // any value at all: as the old number was true when it wasn't zero + constexpr explicit operator bool() const + { + return bits != 0; + } + // all the values of the other set are in this one + constexpr bool HasAll(EnumSet const other) const + { + return (bits & other.bits) == other.bits; + } + // any of the values of the other set is in this one + constexpr bool HasAny(EnumSet const other) const + { + return (bits & other.bits) != 0; + } + // adds the values; returns whether any of them was missing (as SetFlag()) + constexpr bool Set(EnumSet const other) + { + if (HasAll(other)) + { + return false; + } + bits |= other.bits; + return true; + } + // takes the values away, where all of them are there; returns whether it did (as ClearFlag()) + constexpr bool Clear(EnumSet const other) + { + if (false == HasAll(other)) + { + return false; + } + bits &= ~other.bits; + return true; + } + // this set without the values of the other + constexpr EnumSet Without(EnumSet const other) const + { + return FromBits(static_cast(bits & ~other.bits)); + } + constexpr EnumSet &operator|=(EnumSet const other) + { + bits |= other.bits; + return *this; + } + constexpr EnumSet &operator&=(EnumSet const other) + { + bits &= other.bits; + return *this; + } + // the values in one of the sets and not in the other: what changed between them + constexpr EnumSet &operator^=(EnumSet const other) + { + bits ^= other.bits; + return *this; + } + friend constexpr EnumSet operator|(EnumSet left, EnumSet const right) + { + return left |= right; + } + friend constexpr EnumSet operator&(EnumSet left, EnumSet const right) + { + return left &= right; + } + friend constexpr EnumSet operator^(EnumSet left, EnumSet const right) + { + return left ^= right; + } + friend constexpr bool operator==(EnumSet const &left, EnumSet const &right) = default; + +private: + unsigned bits{0}; +}; + +// two values make a set of them, for the enums which are kinds of the sets +template + requires IsEnumSetKind::value +constexpr EnumSet operator|(Enum const left, Enum const right) +{ + return EnumSet{left} | EnumSet{right}; +} diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 951e614fb..a89fe5146 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -3279,7 +3279,7 @@ void TDynamicObject::pull_neighbours( double const Distance ) { auto const &coupler { MoverParameters->Couplers[ end ] }; auto *neighbour { MoverParameters->Neighbours[ end ].vehicle }; if( coupler.CouplingFlag == Coupling::none || neighbour == nullptr || neighbour->MoverParameters->OffTrack.active() - || TestFlag( neighbour->MoverParameters->DamageFlag, dtrain_out ) ) { + || neighbour->MoverParameters->DamageFlag.HasAll(VehicleDamage::derailed) ) { m_pulledoff[ end ].reset(); continue; } @@ -5807,7 +5807,7 @@ void TDynamicObject::RenderSounds() { // special events if( MoverParameters->EventFlag ) { // McZapkie: w razie wykolejenia - if( true == TestFlag( MoverParameters->DamageFlag, dtrain_out ) ) { + if( true == MoverParameters->DamageFlag.HasAll(VehicleDamage::derailed) ) { rsDerailment.play( sound_flags::exclusive ); } @@ -9950,7 +9950,7 @@ vehicle_table::update_off_track_contacts( double const Deltatime ) { // one on the rails: along them into its speed, across them on its wheels, as a coupling pulls them off auto &othermover { *other->MoverParameters }; othermover.V += glm::dot( impulse, otherbody.guide ) / std::max( othermover.TotalMass, 1.0 ); - if( TestFlag( othermover.DamageFlag, dtrain_out ) ) { + if( othermover.DamageFlag.HasAll(VehicleDamage::derailed) ) { continue; } glm::dvec3 const otherleft { otherbody.guide.z, 0.0, -otherbody.guide.x }; diff --git a/world/station.cpp b/world/station.cpp index 5e4dd9590..8ac77db30 100644 --- a/world/station.cpp +++ b/world/station.cpp @@ -58,7 +58,7 @@ basic_station::update_load( TDynamicObject *First, Mtable::TTrainParameters &Sch // NOTE: for the time being we're doing simple, random load change calculation // TODO: exchange driven by station parameters and time of the day auto unloadcount = static_cast( - TestFlag( parameters.DamageFlag, dtrain_out ) ? parameters.LoadAmount : + parameters.DamageFlag.HasAll(VehicleDamage::derailed) ? parameters.LoadAmount : laststop ? parameters.LoadAmount : firststop ? 0 : maintenancestop ? 0 : @@ -66,7 +66,7 @@ basic_station::update_load( TDynamicObject *First, Mtable::TTrainParameters &Sch parameters.LoadAmount, static_cast(Random( parameters.MaxLoad * 0.15f * stationsizemodifier )) ) ); auto loadcount = static_cast( - TestFlag( parameters.DamageFlag, dtrain_out ) ? 0 : + parameters.DamageFlag.HasAll(VehicleDamage::derailed) ? 0 : laststop ? 0 : maintenancestop ? 0 : Random( parameters.MaxLoad * 0.15f * stationsizemodifier ) ); From b35a6129bc42744eb6ba9592fb09a604cd17fecd Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sat, 28 Nov 2026 13:43:45 +0100 Subject: [PATCH 014/123] refactor(ai): the orders of the AI are DriverOrder and DriverOrders, not the bits of TOrders The orders of the AI driver (TOrders) were unscoped bits, summed (an order carries Change_direction on top of Shunt), masked, and compared as numbers (order < Obey_train, order >= Shunt). - vehicle/driverorders.h: enum class DriverOrder (waitForOrders, prepareEngine, releaseEngine, changeDirection, connect, disconnect, shunt, looseShunt, obeyTrain, bank, jumpToFirstOrder) and DriverOrders, an EnumSet of them. A small header, so brakesetting.h names the orders without Driver.h. - the comparisons of the numbers are the sets they meant: the orders from shunt up are movingOrders, those from obeyTrain up trainOrders; SingleOrder() gives the order to a switch, where a sum of several matches no case, as it did - the texts of the scenery commands (Shunt, Obey_train...) and of the translations are unchanged; only the C++ names changed No change in behaviour: 1144/1144 tests, golden traces exact against staging 62f7a29b. --- application/driverhints.cpp | 4 +- simulation/blackboxrecorder.cpp | 4 +- tests/unit/test_brake_setting.cpp | 50 ++-- vehicle/Driver.cpp | 402 +++++++++++++++--------------- vehicle/Driver.h | 54 ++-- vehicle/DynObj.cpp | 2 +- vehicle/Train.cpp | 8 +- vehicle/brakesetting.cpp | 8 +- vehicle/brakesetting.h | 6 +- vehicle/driverorders.h | 49 ++++ 10 files changed, 311 insertions(+), 276 deletions(-) create mode 100644 vehicle/driverorders.h diff --git a/application/driverhints.cpp b/application/driverhints.cpp index 14d1f2f0c..890628964 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -605,7 +605,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return std::abs(mvControlling->Ft) > 30.0 || (OrderCurrentGet() & Disconnect) == 0; } ); + return std::abs(mvControlling->Ft) > 30.0 || false == OrderCurrentGet().HasAny(DriverOrder::disconnect); } ); break; } @@ -836,7 +836,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return IsConsistBraked /*|| ( ( OrderCurrentGet() & Disconnect ) == 0 ) */; } ); + return IsConsistBraked /*|| ( false == OrderCurrentGet().HasAny(DriverOrder::disconnect) ) */; } ); break; } case driver_hint::brakingforcedecrease: { diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index e53e77dfa..5d21c47d0 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -436,8 +436,8 @@ void blackbox_recorder::write_cab() { sample.lateral_acceleration = static_cast(occupied->AccN); if (owner != nullptr && owner->is_train()) { auto const order{owner->order_current()}; - sample.movement = (order & Obey_train) != 0 ? blackbox::movements::train : - (order & (Shunt | Loose_shunt | Connect)) != 0 ? blackbox::movements::shunting : blackbox::movements::other; + sample.movement = order.HasAny(DriverOrder::obeyTrain) ? blackbox::movements::train : + order.HasAny(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect) ? blackbox::movements::shunting : blackbox::movements::other; sample.light_hint_head = static_cast(owner->light_hint(end::front)); sample.light_hint_tail = static_cast(owner->light_hint(end::rear)); } diff --git a/tests/unit/test_brake_setting.cpp b/tests/unit/test_brake_setting.cpp index ccf393dc4..ce9d09075 100644 --- a/tests/unit/test_brake_setting.cpp +++ b/tests/unit/test_brake_setting.cpp @@ -456,45 +456,45 @@ TEST_CASE("brake setting: a train creeping to a stop counts as standing, one on } TEST_CASE("brake setting: a bank engine's run counts as a train, shunting doesn't") { - CHECK(brake_setting::runs_as_train(Obey_train)); - CHECK(brake_setting::runs_as_train(Bank)); - CHECK(brake_setting::runs_as_train(Obey_train | Connect)); - CHECK(false == brake_setting::runs_as_train(Shunt)); - CHECK(false == brake_setting::runs_as_train(Loose_shunt)); - CHECK(false == brake_setting::runs_as_train(Connect)); - CHECK(false == brake_setting::runs_as_train(Wait_for_orders)); + CHECK(brake_setting::runs_as_train(DriverOrder::obeyTrain)); + CHECK(brake_setting::runs_as_train(DriverOrder::bank)); + CHECK(brake_setting::runs_as_train(DriverOrder::obeyTrain | DriverOrder::connect)); + CHECK(false == brake_setting::runs_as_train(DriverOrder::shunt)); + CHECK(false == brake_setting::runs_as_train(DriverOrder::looseShunt)); + CHECK(false == brake_setting::runs_as_train(DriverOrder::connect)); + CHECK(false == brake_setting::runs_as_train(DriverOrder::waitForOrders)); // a heavy consist on G banked: the wagon without G has its brake cut out, as in a train test::vehicle car{passenger_car_definition()}; charge_and_apply(car); - CHECK(inspect_heavy_train(car, brake_setting::runs_as_train(Bank)) == brake_setting::cut_out); + CHECK(inspect_heavy_train(car, brake_setting::runs_as_train(DriverOrder::bank)) == brake_setting::cut_out); CHECK(brake_setting::is_cut_out(car.mover())); // shunted: it's back on P - CHECK(inspect_heavy_train(car, brake_setting::runs_as_train(Shunt)) == P); + CHECK(inspect_heavy_train(car, brake_setting::runs_as_train(DriverOrder::shunt)) == P); CHECK(false == brake_setting::is_cut_out(car.mover())); } TEST_CASE("brake setting: the AI looks at its train under the orders it drives it under, Connect included") { - CHECK(brake_setting::inspects_train(Shunt, false)); - CHECK(brake_setting::inspects_train(Loose_shunt, false)); - CHECK(brake_setting::inspects_train(Obey_train, false)); - CHECK(brake_setting::inspects_train(Bank, false)); + CHECK(brake_setting::inspects_train(DriverOrder::shunt, false)); + CHECK(brake_setting::inspects_train(DriverOrder::looseShunt, false)); + CHECK(brake_setting::inspects_train(DriverOrder::obeyTrain, false)); + CHECK(brake_setting::inspects_train(DriverOrder::bank, false)); // the run up to the wagons: a locomotive standing cold has its hand brake to release first - CHECK(brake_setting::inspects_train(Connect, false)); - CHECK(brake_setting::inspects_train(Connect | Change_direction, false)); + CHECK(brake_setting::inspects_train(DriverOrder::connect, false)); + CHECK(brake_setting::inspects_train(DriverOrder::connect | DriverOrder::changeDirection, false)); // but not at the coupling: the wagons just coupled wait for the next order, which may leave some of them - CHECK(false == brake_setting::inspects_train(Connect, true)); - CHECK(false == brake_setting::inspects_train(Connect | Change_direction, true)); + CHECK(false == brake_setting::inspects_train(DriverOrder::connect, true)); + CHECK(false == brake_setting::inspects_train(DriverOrder::connect | DriverOrder::changeDirection, true)); // a train run with a coupling on it is still a train run - CHECK(brake_setting::inspects_train(Obey_train | Connect, true)); - CHECK(brake_setting::inspects_train(Shunt, true)); + CHECK(brake_setting::inspects_train(DriverOrder::obeyTrain | DriverOrder::connect, true)); + CHECK(brake_setting::inspects_train(DriverOrder::shunt, true)); // standing, starting or stopping the engine, turning round, uncoupling: nothing to look at - CHECK(false == brake_setting::inspects_train(Wait_for_orders, false)); - CHECK(false == brake_setting::inspects_train(Prepare_engine, false)); - CHECK(false == brake_setting::inspects_train(Release_engine, false)); - CHECK(false == brake_setting::inspects_train(Change_direction, false)); - CHECK(false == brake_setting::inspects_train(Disconnect, false)); - CHECK(false == brake_setting::inspects_train(Jump_to_first_order, false)); + CHECK(false == brake_setting::inspects_train(DriverOrder::waitForOrders, false)); + CHECK(false == brake_setting::inspects_train(DriverOrder::prepareEngine, false)); + CHECK(false == brake_setting::inspects_train(DriverOrder::releaseEngine, false)); + CHECK(false == brake_setting::inspects_train(DriverOrder::changeDirection, false)); + CHECK(false == brake_setting::inspects_train(DriverOrder::disconnect, false)); + CHECK(false == brake_setting::inspects_train(DriverOrder::jumpToFirstOrder, false)); } TEST_CASE("brake setting: R+Mg brakes as hard as R at speed, the rapid stage of an LSt kept") { diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index a35244fc6..045de5ab0 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -206,7 +206,7 @@ TSpeedPos::TSpeedPos(TTrack *track, double dist, int flag) Set(track, dist, flag); }; -TSpeedPos::TSpeedPos(basic_event *event, double dist, double length, TOrders order) +TSpeedPos::TSpeedPos(basic_event *event, double dist, double length, DriverOrders order) { Set(event, dist, length, order); }; @@ -405,23 +405,23 @@ std::string TSpeedPos::TableText() const return "Empty"; } -bool TSpeedPos::IsProperSemaphor(TOrders order) +bool TSpeedPos::IsProperSemaphor(DriverOrders order) { // sprawdzenie czy semafor jest zgodny z trybem jazdy - if (order < Obey_train) // Wait_for_orders, Prepare_engine, Change_direction, Connect, Disconnect, Shunt + if (false == order.HasAny(trainOrders)) // Wait_for_orders, Prepare_engine, Change_direction, Connect, Disconnect, Shunt { if (iFlags & (spSemaphor | spShuntSemaphor)) return true; else if (iFlags & spOutsideStation) return true; } - else if (order & Obey_train && iFlags & spSemaphor) + else if (order & DriverOrder::obeyTrain && iFlags & spSemaphor) { return true; } return false; // true gdy zatrzymanie, wtedy nie ma po co skanować dalej } -bool TSpeedPos::Set(basic_event *event, double dist, double length, TOrders order, bool const Standing) +bool TSpeedPos::Set(basic_event *event, double dist, double length, DriverOrders order, bool const Standing) { // zapamiętanie zdarzenia fDist = dist; // an event already behind the head when found (under a train set across a signal) wasn't passed by it. a moving @@ -442,14 +442,14 @@ bool TSpeedPos::Set(basic_event *event, double dist, double length, TOrders orde // zależnie od trybu sprawdzenie czy jest tutaj gdzieś semafor lub tarcza manewrowa // jeśli wskazuje stop wtedy wystawiamy true jako koniec sprawdzania // WriteLog("EventSet: Vel=" + AnsiString(fVelNext) + " iFlags=" + AnsiString(iFlags) + " order="+AnsiString(order)); - if (order < Obey_train) // Wait_for_orders, Prepare_engine, Change_direction, Connect, Disconnect, Shunt + if (false == order.HasAny(trainOrders)) // Wait_for_orders, Prepare_engine, Change_direction, Connect, Disconnect, Shunt { if (iFlags & (spSemaphor | spShuntSemaphor) && fVelNext == 0.0) return true; else if (iFlags & spOutsideStation) return true; } - else if (order & Obey_train && iFlags & spSemaphor && fVelNext == 0.0) + else if (order & DriverOrder::obeyTrain && iFlags & spSemaphor && fVelNext == 0.0) { return true; } @@ -599,12 +599,12 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) && sSpeedTable[SemNextStopIndex].fVelNext == 0.0 ) { // znaleziono semafor lub tarczę lub tor z prędkością zero, trzeba sprawdzić czy to nadał semafor // jeśli jest następny semafor to sprawdzamy czy to on nadał zero - if( OrderCurrentGet() & Obey_train + if( OrderCurrentGet() & DriverOrder::obeyTrain && sSpeedTable[SemNextStopIndex].iFlags & spSemaphor ) { return; } else { - if( OrderCurrentGet() < Obey_train + if( false == OrderCurrentGet().HasAny(trainOrders) && sSpeedTable[SemNextStopIndex].iFlags & (spSemaphor | spShuntSemaphor | spOutsideStation) ) { return; } @@ -950,7 +950,7 @@ void TController::CheckSignalPassed( TSpeedPos const &Point, bool const Passedbe pVehicles[ end::front ], *Point.evEvent, speedatsignal, Point.evEvent->input_value( 2 ), mvOccupied->Vel, -Point.fDist, - passing_flags_of( Point, speedatsignal, ( OrderCurrentGet() & ( Shunt | Loose_shunt ) ) == 0 ) ); + passing_flags_of( Point, speedatsignal, false == OrderCurrentGet().HasAny( DriverOrder::shunt | DriverOrder::looseShunt ) ) ); } } @@ -1195,7 +1195,7 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN // jeśli mieliśmy ograniczenie z semafora i nie ma przed nami if( VelSignalLast >= 0.0 && ( false == drivingFlags.signalFound && false == drivingFlags.switchFound && false == drivingFlags.stopPointFound ) - && true == TestFlag(OrderCurrentGet(), Obey_train) ) { + && true == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { VelSignalLast = -1.0; } // if there's unbroken speed limit through our scan table take a note of it @@ -1229,7 +1229,7 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN bool TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, double const Signaldistance ) { // stop points are irrelevant when not in one of the basic modes - if( ( OrderCurrentGet() & ( Shunt | Loose_shunt | Obey_train | Bank ) ) == 0 ) { return true; } + if( false == OrderCurrentGet().HasAny( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank ) ) { return true; } // jeśli przystanek, trzeba obsłużyć wg rozkładu drivingFlags.stopPointFound = true; // the W4 and the timetable name the station each in its own file, so the two spellings are compared by their key: @@ -1255,7 +1255,7 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub } else if (drivingFlags.stopPoint) // jeśli pomijanie W4, to nie sprawdza czasu odjazdu { // tylko gdy nazwa zatrzymania się zgadza - if( ( OrderCurrentGet() & ( Obey_train | Bank ) ) != 0 ) { + if( OrderCurrentGet().HasAny( DriverOrder::obeyTrain | DriverOrder::bank ) ) { // check whether the station specifies radio channel change // NOTE: we don't do it in shunt mode, as shunting operations tend to use dedicated radio channel // NOTE: there's a risk radio channel change was specified by a station which we skipped during timetable rewind @@ -1408,12 +1408,12 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub if (drivingFlags.pushPull) { // SN61 ma się też nie ruszać, chyba że ma wagony drivingFlags.stopHere = true; // EZT ma stać przy peronie - if (OrderNextGet() != Change_direction) { - OrderPush(Change_direction); // zmiana kierunku + if (OrderNextGet() != DriverOrder::changeDirection) { + OrderPush(DriverOrder::changeDirection); // zmiana kierunku OrderPush( TrainParams.StationIndex < TrainParams.StationCount ? - Obey_train : - Shunt); // to dalej wg rozkładu + DriverOrder::obeyTrain : + DriverOrder::shunt); // to dalej wg rozkładu } } else { @@ -1435,8 +1435,8 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub } } - if (OrderCurrentGet() & ( Shunt | Loose_shunt )) { - OrderNext(Obey_train); // uruchomić jazdę pociągową + if (OrderCurrentGet() & ( DriverOrder::shunt | DriverOrder::looseShunt )) { + OrderNext(DriverOrder::obeyTrain); // uruchomić jazdę pociągową CheckVehicles(); // zmienić światła } @@ -1624,7 +1624,7 @@ TController::TableUpdateSignalAreaEnd( TSpeedPos &Point ) { // the switches lie in front of the marker, so the whole train has left them once its rear end is past it if( Point.fDist >= -fLength ) { if( SignalAreaEndDist < 0.0 - && TestFlag( OrderCurrentGet(), Obey_train ) ) { + && OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { // the table is sorted by distance, so the first marker is the nearest one SignalAreaEndDist = Point.fDist + fLength; } @@ -1632,7 +1632,7 @@ TController::TableUpdateSignalAreaEnd( TSpeedPos &Point ) { } // in shunting the marker stays, a train order given before the next signal still finds it - if( false == TestFlag( OrderCurrentGet(), Obey_train ) ) { return; } + if( false == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { return; } // a passed signal at stop (0) keeps holding the train, only a reduced speed ends here if( VelSignalLast > 0.0 ) { @@ -1940,7 +1940,7 @@ TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPo } if (Point.iFlags & spOutsideStation) { // jeśli W5, to reakcja zależna od trybu jazdy - if (OrderCurrentGet() & Obey_train) + if (OrderCurrentGet() & DriverOrder::obeyTrain) { // w trybie pociągowym: można przyspieszyć do wskazanej prędkości (po zjechaniu z rozjazdów) Velocity = -1.0; // ignorować? if ( Point.fDist < 0.0) { // jeśli wskaźnik został minięty @@ -2094,7 +2094,7 @@ TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPo if ( Point.iFlags & spShuntSemaphor) // jeśli Tm - w zasadzie to sprawdzić komendę! { // jeśli podana prędkość manewrowa if( Velocity == 0.0 - && true == TestFlag(OrderCurrentGet(), Obey_train) ) { + && true == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { // jeśli tryb pociągowy a tarcze ma ShuntVelocity 0 0 Velocity = -1; // ignorować, chyba że prędkość stanie się niezerowa if( true == TestFlag( Point.iFlags, spElapsed ) ) { @@ -2399,28 +2399,28 @@ TController::~TController() }; // zamiana kodu rozkazu na opis -std::string TController::Order2Str(TOrders Order) const { +std::string TController::Order2Str(DriverOrders Order) const { - if( (Order & Change_direction) != 0 - && Order != Change_direction ) { + if( Order.HasAny(DriverOrder::changeDirection) + && Order != DriverOrder::changeDirection ) { // może być nałożona na inną i wtedy ma priorytet return - Order2Str( Change_direction ) + Order2Str( DriverOrder::changeDirection ) + " + " - + Order2Str( static_cast( Order & ~Change_direction ) ); + + Order2Str( Order.Without(DriverOrder::changeDirection) ); } - switch( Order ) { - case Wait_for_orders: return "Wait_for_orders"; - case Prepare_engine: return "Prepare_engine"; - case Release_engine: return "Release_engine"; - case Change_direction: return "Change_direction"; - case Connect: return "Connect"; - case Disconnect: return "Disconnect"; - case Shunt: return "Shunt"; - case Loose_shunt: return "Loose_shunt"; - case Obey_train: return "Obey_train"; - case Bank: return "Bank"; - case Jump_to_first_order: return "Jump_to_first_order"; + switch( SingleOrder( Order ) ) { + case DriverOrder::waitForOrders: return "Wait_for_orders"; + case DriverOrder::prepareEngine: return "Prepare_engine"; + case DriverOrder::releaseEngine: return "Release_engine"; + case DriverOrder::changeDirection: return "Change_direction"; + case DriverOrder::connect: return "Connect"; + case DriverOrder::disconnect: return "Disconnect"; + case DriverOrder::shunt: return "Shunt"; + case DriverOrder::looseShunt: return "Loose_shunt"; + case DriverOrder::obeyTrain: return "Obey_train"; + case DriverOrder::bank: return "Bank"; + case DriverOrder::jumpToFirstOrder: return "Jump_to_first_order"; default: return "Undefined"; } } @@ -2431,18 +2431,18 @@ std::string TController::OrderCurrent() const { // pobranie aktualnego rozkazu celem wyświetlenia auto const order { OrderCurrentGet() }; // generally prioritize direction change... - if( order & Change_direction && false == drivingFlags.connect ) { + if( order & DriverOrder::changeDirection && false == drivingFlags.connect ) { // ...but not in the middle of coupling operation return STR("Change direction"); } - switch( static_cast( order & ~Change_direction ) ) { - case Wait_for_orders: { return STR("Wait for orders"); } - case Prepare_engine: { return STR("Start the engine"); } - case Release_engine: { return STR("Shut down the engine"); } - case Change_direction: { return STR("Change direction"); } - case Connect: { return STR("Couple to consist ahead"); } - case Disconnect: { + switch( SingleOrder( order.Without(DriverOrder::changeDirection) ) ) { + case DriverOrder::waitForOrders: { return STR("Wait for orders"); } + case DriverOrder::prepareEngine: { return STR("Start the engine"); } + case DriverOrder::releaseEngine: { return STR("Shut down the engine"); } + case DriverOrder::changeDirection: { return STR("Change direction"); } + case DriverOrder::connect: { return STR("Couple to consist ahead"); } + case DriverOrder::disconnect: { if( iVehicleCount < 0 ) { // done with uncoupling, order should update shortly return STR("Wait for orders"); @@ -2467,10 +2467,10 @@ std::string TController::OrderCurrent() const countstring.c_str() ); return orderbuffer.data(); } - case Shunt: { return STR("Shunt according to signals"); } - case Loose_shunt: { return STR("Loose shunt according to signals"); } - case Obey_train: { return STR("Drive according to signals and timetable"); } - case Bank: { return STR("Bank consist ahead"); } + case DriverOrder::shunt: { return STR("Shunt according to signals"); } + case DriverOrder::looseShunt: { return STR("Loose shunt according to signals"); } + case DriverOrder::obeyTrain: { return STR("Drive according to signals and timetable"); } + case DriverOrder::bank: { return STR("Bank consist ahead"); } default: { return{}; } } }; @@ -2480,7 +2480,7 @@ void TController::OrdersClear() OrderPos = 0; OrderTop = 1; // szczyt stosu rozkazów for (int b = 0; b < maxorders; b++) - OrderList[b] = Wait_for_orders; + OrderList[b] = DriverOrder::waitForOrders; #if LOGORDERS OrdersDump("OrdersClear", false); #endif @@ -2552,7 +2552,7 @@ void TController::Activation() } if( mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->ShuntModeAllow ) { // dla 2Ls150 - przed ustawieniem kierunku - można zmienić tryb pracy - mvControlling->CurrentSwitch((OrderCurrentGet() & (Shunt | Loose_shunt)) != 0 || fMass > 224000.0); // do tego na wzniesieniu może nie dać rady na liniowym + mvControlling->CurrentSwitch(OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt) || fMass > 224000.0); // do tego na wzniesieniu może nie dać rady na liniowym } // Ra: to przełączanie poniżej jest tu bez sensu mvOccupied->CabOccupied = iDirection; // aktywacja kabiny w prowadzonym pojeżdzie (silnikowy może być odwrotnie?) @@ -2628,7 +2628,7 @@ void TController::AutoRewident() fBrake_a1[i+1] = 0; } - if( OrderCurrentGet() & ( Shunt | Loose_shunt ) ) { + if( OrderCurrentGet() & ( DriverOrder::shunt | DriverOrder::looseShunt ) ) { // for uniform behaviour and compatibility with older scenarios set default acceleration table values for shunting fAccThreshold = is_emu() ? -0.55 : is_dmu() ? -0.45 : -0.2; // HACK: emu with induction motors need to start their braking a bit sooner than the ones with series motors @@ -2645,7 +2645,7 @@ void TController::AutoRewident() mvOccupied->EpFuseSwitch(BrakeSystem == TBrakeSystem::ElectroPneumatic); } - if( OrderCurrentGet() & ( Obey_train | Bank ) ) { + if( OrderCurrentGet() & ( DriverOrder::obeyTrain | DriverOrder::bank ) ) { // 4. Przeliczanie siły hamowania double const velstep = mvOccupied->Vmax * 0.5 / BrakeAccTableSize; auto *d = pVehicles[0]; // pojazd na czele składu @@ -2774,7 +2774,7 @@ int TController::CheckDirection() { return d; } -bool TController::CheckVehicles(TOrders user) +bool TController::CheckVehicles(DriverOrders user) { // sprawdzenie stanu posiadanych pojazdów w składzie i zapalenie świateł TDynamicObject *p; // roboczy wskaźnik na pojazd iVehicles = 0; // ilość pojazdów w składzie @@ -2881,7 +2881,7 @@ bool TController::CheckVehicles(TOrders user) p = p->Next(); // pojazd podłączony od tyłu (licząc od czoła) } - if( user == Connect && true == main ) { + if( user == DriverOrder::connect && true == main ) { // HACK: with additional vehicles in the consist ensure all linked vehicles are set to move in the same direction if( pVehicle->Prev(Coupling::control) != nullptr || pVehicle->Next(Coupling::control) != nullptr ) { @@ -2895,7 +2895,7 @@ bool TController::CheckVehicles(TOrders user) } // kasowanie pamieci hamowania kontrolnego - if (OrderCurrentGet() & (Shunt | Loose_shunt | Disconnect | Connect | Change_direction)) { + if (OrderCurrentGet() & (DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::disconnect | DriverOrder::connect | DriverOrder::changeDirection)) { DynamicBrakeTest = 0; DBT_VelocityBrake = DBT_VelocityRelease @@ -2906,12 +2906,12 @@ bool TController::CheckVehicles(TOrders user) = 0; } - if( brake_setting::inspects_train( OrderCurrentGet(), user == Connect ) ) { + if( brake_setting::inspects_train( OrderCurrentGet(), user == DriverOrder::connect ) ) { // nastawianie hamulca do jazdy pociągowej AutoRewident(); /* if( ( true == drivingFlags.connect ) - && ( true == TestFlag( OrderCurrentGet(), Connect ) ) ) { + && ( true == OrderCurrentGet().HasAll(DriverOrder::connect) ) ) { iCoupler = {}; // dalsza jazda manewrowa już bez łączenia drivingFlags.connect = false; // zdjęcie flagi doczepiania SetVelocity( 0, 0, stopJoin ); // wyłączyć przyspieszanie @@ -2938,7 +2938,7 @@ bool TController::CheckVehicles(TOrders user) // potentially adjust light state control_lights(); // custom ai action for disconnect mode: switch off lights on disconnected vehicle(s) - if( is_train() && true == TestFlag(OrderCurrentGet(), Disconnect) && AIControllFlag ) { + if( is_train() && true == OrderCurrentGet().HasAll(DriverOrder::disconnect) && AIControllFlag ) { // światła manewrowe (Tb1) tylko z przodu, aby nie pozostawić odczepionego ze światłem if (mvOccupied->DirActive >= 0) { // jak ma kierunek do przodu @@ -2961,7 +2961,7 @@ bool TController::CheckVehicles(TOrders user) true ) }; auto const isheatingneeded { (is_emu() || is_dmu() ? true : - (OrderCurrentGet() & (Obey_train | Bank)) == 0 ? false : + false == OrderCurrentGet().HasAny(DriverOrder::obeyTrain | DriverOrder::bank) ? false : false == isheatingcouplingactive ? false : ispassengertrain ? hasheaters : false) }; @@ -2974,8 +2974,8 @@ bool TController::CheckVehicles(TOrders user) } } - if( user == Connect - || user == Disconnect ) { + if( user == DriverOrder::connect + || user == DriverOrder::disconnect ) { // HACK: force route table update on consist change, new consist length means distances to points of interest are now wrong iTableDirection = 0; } @@ -3006,7 +3006,7 @@ void TController::DirectionChange() { auto const initialstate { iDirection }; iDirection = CheckDirection(); if( iDirection != initialstate ) { - CheckVehicles( Change_direction ); + CheckVehicles( DriverOrder::changeDirection ); } } @@ -3043,8 +3043,8 @@ std::pair TController::next_speed_limit() const { } // nie przekraczać rozkladowej auto const schedulespeedlimit { ( - ( OrderCurrentGet() & ( Obey_train | Bank ) ) != 0 && TrainParams.TTVmax > 0.0 ? static_cast( TrainParams.TTVmax ) : - ( OrderCurrentGet() & ( Obey_train | Bank ) ) == 0 ? static_cast( fShuntVelocity ) : + OrderCurrentGet().HasAny( DriverOrder::obeyTrain | DriverOrder::bank ) && TrainParams.TTVmax > 0.0 ? static_cast( TrainParams.TTVmax ) : + false == OrderCurrentGet().HasAny( DriverOrder::obeyTrain | DriverOrder::bank ) ? static_cast( fShuntVelocity ) : -1 ) }; // first take note of any speed change which should occur after passing potential current speed limit if( VelLimitLastDist.second > 0 ) { @@ -3170,7 +3170,7 @@ void TController::SetVelocity(double NewVel, double NewVelNext, TStopReason r) eStopReason = stopNone; // podana prędkość, to nie ma powodów do stania // to całe poniżej to warunki zatrąbienia przed ruszeniem if( is_train() // tylko pociągi trąbią (unimogi tylko na torach, więc trzeba raczej sprawdzać tor) - && (OrderCurrentGet() & (Shunt | Loose_shunt | Obey_train | Bank | Connect | Prepare_engine)) != 0 // jeśli jedzie w dowolnym trybie + && OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank | DriverOrder::connect | DriverOrder::prepareEngine) // jeśli jedzie w dowolnym trybie && drivingFlags.startHorn // jezeli trąbienie włączone && ( false == drivingFlags.startHornDone && false == drivingFlags.connect ) // jeśli nie zatrąbione i nie jest to moment podłączania składu && mvOccupied->Vel < 1.0 // jesli stoi (na razie, bo chyba powinien też, gdy hamuje przed semaforem) @@ -3201,7 +3201,7 @@ double TController::BrakeAccFactor() const void TController::SetDriverPsyche() { - if (Psyche == Aggressive && OrderCurrentGet() == Obey_train) { + if (Psyche == Aggressive && OrderCurrentGet() == DriverOrder::obeyTrain) { ReactionTime = HardReactionTime; // w zaleznosci od charakteru maszynisty if (is_car()) { WaitingExpireTime = 1; // tyle ma czekać samochód, zanim się ruszy @@ -3524,7 +3524,7 @@ bool TController::ReleaseEngine() { eStopReason = stopSleep; // stoimy z powodu wyłączenia eAction = TAction::actSleep; //śpi (wygaszony) - OrderNext(Wait_for_orders); //żeby nie próbował coś robić dalej + OrderNext(DriverOrder::waitForOrders); //żeby nie próbował coś robić dalej drivingFlags.active = false; // ma nie skanować sygnałów i nie reagować na komendy TableClear(); // zapominamy ograniczenia VelSignalLast = -1.0; @@ -3647,7 +3647,7 @@ bool TController::IncBrake() // enforce use of train brake for DMUs standalone = false; } - else if( (OrderCurrentGet() & Loose_shunt) != 0 + else if( OrderCurrentGet().HasAny(DriverOrder::looseShunt) && mvOccupied->Vel - VelDesired < fVelPlus + fVelMinus ) { // try to reduce train brake use in loose shunting mode standalone = true; @@ -4148,7 +4148,7 @@ bool TController::IncSpeed() if (mvControlling->SpeedCtrl && mvControlling->Mains) { // cruise control - auto const couplinginprogress{true == drivingFlags.connect && true == TestFlag(OrderCurrentGet(), Connect)}; + auto const couplinginprogress{true == drivingFlags.connect && true == OrderCurrentGet().HasAll(DriverOrder::connect)}; auto const SpeedCntrlVel{(ActualProximityDist > std::max(50.0, fMaxProximityDist) || couplinginprogress ? VelDesired : min_speed(VelDesired, VelNext))}; if (SpeedCntrlVel >= mvControlling->SpeedCtrlUnit.MinVelocity && SpeedCntrlVel - mvControlling->SpeedCtrlUnit.MinVelocity == quantize(SpeedCntrlVel - mvControlling->SpeedCtrlUnit.MinVelocity, mvControlling->SpeedCtrlUnit.VelocityStep)) @@ -4177,7 +4177,7 @@ bool TController::IncSpeed() // mvControlling->ShuntMode=(OrderList[OrderPos]&Shunt)||(fMass>224000.0); } if (mvControlling->SpeedCtrl && mvControlling->Mains) {// cruise control - auto const couplinginprogress { true == drivingFlags.connect && true == TestFlag(OrderCurrentGet(), Connect) }; + auto const couplinginprogress { true == drivingFlags.connect && true == OrderCurrentGet().HasAll(DriverOrder::connect) }; auto const SpeedCntrlVel { ( ActualProximityDist > std::max(50.0, fMaxProximityDist) || couplinginprogress ? VelDesired : @@ -5176,13 +5176,13 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N { if (NewLocation) vCommandLocation = *NewLocation; - if (NewValue1 != 0.0 && OrderCurrentGet() != Obey_train) + if (NewValue1 != 0.0 && OrderCurrentGet() != DriverOrder::obeyTrain) { // o ile jazda if( false == iEngineActive ) { // trzeba odpalić silnik najpierw, światła ustawi - OrderNext( Prepare_engine ); + OrderNext( DriverOrder::prepareEngine ); } - OrderNext(Obey_train); // to uruchomić jazdę pociągową (od razu albo po odpaleniu silnika + OrderNext(DriverOrder::obeyTrain); // to uruchomić jazdę pociągową (od razu albo po odpaleniu silnika OrderCheck(); // jeśli jazda pociągowa teraz, to wykonać niezbędne operacje } if (NewValue1 != 0.0) // jeśli jechać @@ -5215,8 +5215,8 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N vCommandLocation = *NewLocation; // if (OrderList[OrderPos]=Obey_train) and (NewValue1<>0)) if (false == iEngineActive) - OrderNext(Prepare_engine); // trzeba odpalić silnik najpierw - OrderNext(Shunt); // zamieniamy w aktualnej pozycji, albo dodajey za odpaleniem silnika + OrderNext(DriverOrder::prepareEngine); // trzeba odpalić silnik najpierw + OrderNext(DriverOrder::shunt); // zamieniamy w aktualnej pozycji, albo dodajey za odpaleniem silnika if (NewValue1 != 0.0) { // if (iVehicleCount>=0) WriteLog("Skasowano ilosć wagonów w ShuntVelocity!"); @@ -5241,7 +5241,7 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N if (NewValue1 > 0.0 ? NewValue1 > fStopTime : false) fStopTime = NewValue1; // Ra: włączenie czekania bez zmiany komendy else - OrderCurrentSet( Wait_for_orders ); // czekanie na komendę (albo dać OrderPos=0) + OrderCurrentSet( DriverOrder::waitForOrders ); // czekanie na komendę (albo dać OrderPos=0) return true; } @@ -5250,18 +5250,18 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N { // włączenie albo wyłączenie silnika (w szerokim sensie) OrdersClear(); // czyszczenie tabelki rozkazów, aby nic dalej nie robił if (NewValue1 == 0.0) - OrderNext(Release_engine); // wyłączyć silnik (przygotować pojazd do jazdy) + OrderNext(DriverOrder::releaseEngine); // wyłączyć silnik (przygotować pojazd do jazdy) else if (NewValue1 > 0.0) - OrderNext(Prepare_engine); // odpalić silnik (wyłączyć wszystko, co się da) + OrderNext(DriverOrder::prepareEngine); // odpalić silnik (wyłączyć wszystko, co się da) // po załączeniu przejdzie do kolejnej komendy, po wyłączeniu na Wait_for_orders return true; } if (NewCommand == "Change_direction") { - TOrders o = OrderCurrentGet(); // co robił przed zmianą kierunku + DriverOrders o = OrderCurrentGet(); // co robił przed zmianą kierunku if (false == iEngineActive) - OrderNext(Prepare_engine); // trzeba odpalić silnik najpierw + OrderNext(DriverOrder::prepareEngine); // trzeba odpalić silnik najpierw if (NewValue1 == 0.0) iDirectionOrder = -iDirection; // zmiana na przeciwny niż obecny else if (NewLocation) // jeśli podane współrzędne eventu/komórki ustawiającej rozkład @@ -5277,11 +5277,11 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N if ( iDirectionOrder != iDirection) - OrderNext(Change_direction); // zadanie komendy do wykonania - if (o >= Shunt) // jeśli jazda manewrowa albo pociągowa + OrderNext(DriverOrder::changeDirection); // zadanie komendy do wykonania + if (o.HasAny(movingOrders)) // jeśli jazda manewrowa albo pociągowa OrderNext(o); // to samo robić po zmianie else if (!o) // jeśli wcześniej było czekanie - OrderNext(Shunt); // to dalej jazda manewrowa + OrderNext(DriverOrder::shunt); // to dalej jazda manewrowa if (mvOccupied->Vel >= EU07_AI_MOVEMENT) // jeśli jedzie drivingFlags.startHorn = false; // to bez trąbienia po ruszeniu z zatrzymania // Change_direction wykona się samo i następnie przejdzie do kolejnej komendy @@ -5290,9 +5290,9 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N if (NewCommand == "Obey_train") { if( false == iEngineActive ) { - OrderNext( Prepare_engine ); // trzeba odpalić silnik najpierw + OrderNext( DriverOrder::prepareEngine ); // trzeba odpalić silnik najpierw } - OrderNext( Obey_train ); + OrderNext( DriverOrder::obeyTrain ); // if (NewValue1>0) TrainNumber=floor(NewValue1); //i co potem ??? OrderCheck(); // jeśli jazda pociągowa teraz, to wykonać niezbędne operacje @@ -5301,9 +5301,9 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N if (NewCommand == "Bank") { if( false == iEngineActive ) { - OrderNext( Prepare_engine ); // trzeba odpalić silnik najpierw + OrderNext( DriverOrder::prepareEngine ); // trzeba odpalić silnik najpierw } - OrderNext( Bank ); + OrderNext( DriverOrder::bank ); // if (NewValue1>0) TrainNumber=floor(NewValue1); //i co potem ??? OrderCheck(); // jeśli jazda pociągowa teraz, to wykonać niezbędne operacje @@ -5323,29 +5323,29 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N // 1, 0 - odczepienie lokomotywy z jednym wagonem drivingFlags.stopHere = false; // podjeżanie do semaforów zezwolone if( false == iEngineActive ) { - OrderNext( Prepare_engine ); // trzeba odpalić silnik najpierw + OrderNext( DriverOrder::prepareEngine ); // trzeba odpalić silnik najpierw } if (NewValue2 != 0) // jeśli podany jest sprzęg { iCoupler = CouplingSet::FromBits( static_cast( std::floor( std::abs( NewValue2 ) ) ) ); // jakim sprzęgiem - OrderNext(Connect); // najpierw połącz pojazdy + OrderNext(DriverOrder::connect); // najpierw połącz pojazdy if (NewValue1 >= 0.0) // jeśli ilość wagonów inna niż wszystkie { // to po podpięciu należy się odczepić iDirectionOrder = -iDirection; // zmiana na ciągnięcie - OrderPush(Change_direction); // najpierw zmień kierunek, bo odczepiamy z tyłu - OrderPush(Disconnect); // a odczep już po zmianie kierunku + OrderPush(DriverOrder::changeDirection); // najpierw zmień kierunek, bo odczepiamy z tyłu + OrderPush(DriverOrder::disconnect); // a odczep już po zmianie kierunku if( NewValue2 > 0.0 && NewCommand == "Loose_shunt" ) { // after decoupling continue pushing in the original direction // NOTE: for backward compatibility this option isn't supported for basic shunting mode iDirectionOrder = iDirection; // back to pushing - OrderPush( Change_direction ); + OrderPush( DriverOrder::changeDirection ); } } else if (NewValue2 < 0.0) // jeśli wszystkie, a sprzęg ujemny, to tylko zmiana kierunku po podczepieniu { // np. Shunt -1 -3 iDirectionOrder = -iDirection; // jak się podczepi, to jazda w przeciwną stronę - OrderNext(Change_direction); + OrderNext(DriverOrder::changeDirection); } WaitingTime = 0.0; // nie ma co dalej czekać, można zatrąbić i jechać, chyba że już jedzie } @@ -5356,11 +5356,11 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N if( mvOccupied->Couplers[mvOccupied->DirAbsolute > 0 ? end::rear : end::front].Connected == nullptr // z tyłu nic && mvOccupied->Couplers[mvOccupied->DirAbsolute > 0 ? end::front : end::rear].Connected != nullptr ) { // a z przodu skład iDirectionOrder = -iDirection; // zmiana na ciągnięcie - OrderNext( Change_direction ); // najpierw zmień kierunek (zastąpi Disconnect) - OrderPush( Disconnect ); // a odczep już po zmianie kierunku + OrderNext( DriverOrder::changeDirection ); // najpierw zmień kierunek (zastąpi Disconnect) + OrderPush( DriverOrder::disconnect ); // a odczep już po zmianie kierunku } else if( mvOccupied->Couplers[ mvOccupied->DirAbsolute > 0 ? end::rear : end::front ].Connected != nullptr ) { // z tyłu coś - OrderNext( Disconnect ); // jak ciągnie, to tylko odczep (NewValue1) wagonów + OrderNext( DriverOrder::disconnect ); // jak ciągnie, to tylko odczep (NewValue1) wagonów } else { // both couplers empty @@ -5380,10 +5380,10 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N } // (nie dotyczy Connect) if( NewValue1 < -2.5 ) { // jeśli -3 to potem jazda pociągowa - OrderNext( NewCommand == "Shunt" ? Obey_train : Bank ); + OrderNext( NewCommand == "Shunt" ? DriverOrder::obeyTrain : DriverOrder::bank ); } else { // otherwise continue shunting - OrderNext( NewCommand == "Shunt" ? Shunt : Loose_shunt ); + OrderNext( NewCommand == "Shunt" ? DriverOrder::shunt : DriverOrder::looseShunt ); } CheckVehicles(); // sprawdzić światła iVehicleCount = std::floor( NewValue1 ); @@ -5447,7 +5447,7 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N // set consist lights pattern hints m_lighthints[ end::front ] = static_cast( NewValue1 ); m_lighthints[ end::rear ] = static_cast( NewValue2 ); - if( true == TestFlag( OrderCurrentGet(), Obey_train ) ) { + if( true == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { // light hints only apply in the obey_train mode CheckVehicles(); } @@ -5715,13 +5715,13 @@ TController::PrepareDirection() { void TController::JumpToNextOrder( bool const Ignoremergedchangedirection ) { // wykonanie kolejnej komendy z tablicy rozkazów - if (auto const currentorder { OrderCurrentGet() }; currentorder != Wait_for_orders) + if (auto const currentorder { OrderCurrentGet() }; currentorder != DriverOrder::waitForOrders) { - if( (currentorder & Change_direction) != 0 // jeśli zmiana kierunku - && currentorder != Change_direction && false == Ignoremergedchangedirection ) { // ale nałożona na coś + if( currentorder.HasAny(DriverOrder::changeDirection) // jeśli zmiana kierunku + && currentorder != DriverOrder::changeDirection && false == Ignoremergedchangedirection ) { // ale nałożona na coś // usunięcie zmiany kierunku z innej komendy - OrderCurrentSet( TOrders(currentorder & ~Change_direction) ); + OrderCurrentSet( currentorder.Without(DriverOrder::changeDirection) ); OrderCheck(); return; } @@ -5750,47 +5750,47 @@ void TController::JumpToFirstOrder() void TController::OrderCheck() { // reakcja na zmianę rozkazu - if( OrderCurrentGet() != Obey_train ) { + if( OrderCurrentGet() != DriverOrder::obeyTrain ) { // reset light hints m_lighthints[ end::front ] = m_lighthints[ end::rear ] = -1; } - if( OrderCurrentGet() & ( Shunt | Loose_shunt | Connect | Obey_train | Bank ) ) { + if( OrderCurrentGet() & ( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect | DriverOrder::obeyTrain | DriverOrder::bank ) ) { CheckVehicles(); // sprawdzić światła } - if( OrderCurrentGet() & ( Shunt | Loose_shunt | Connect ) ) { + if( OrderCurrentGet() & ( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect ) ) { // HACK: ensure consist doors will be closed on departure drivingFlags.doorOpened = true; } auto const currentorder { OrderCurrentGet() }; - if (currentorder & Change_direction) // może być nałożona na inną i wtedy ma priorytet + if (currentorder & DriverOrder::changeDirection) // może być nałożona na inną i wtedy ma priorytet iDirectionOrder = -iDirection; // trzeba zmienić jawnie, bo się nie domyśli - else if (currentorder == Obey_train) + else if (currentorder == DriverOrder::obeyTrain) drivingFlags.stopPoint = true; // W4 są widziane - else if (currentorder == Disconnect) + else if (currentorder == DriverOrder::disconnect) iVehicleCount = iVehicleCount < 0 ? 0 : iVehicleCount; // odczepianie lokomotywy - else if (currentorder == Connect) + else if (currentorder == DriverOrder::connect) drivingFlags.stopPoint = false; // podczas jazdy na połączenie nie zwracać uwagi na W4 - else if (currentorder == Wait_for_orders) + else if (currentorder == DriverOrder::waitForOrders) OrdersClear(); // czyszczenie rozkazów i przeskok do zerowej pozycji } -void TController::OrderNext(TOrders NewOrder) +void TController::OrderNext(DriverOrders NewOrder) { // ustawienie rozkazu do wykonania jako następny if (OrderCurrentGet() == NewOrder) return; // jeśli robi to, co trzeba, to koniec if (!OrderPos) OrderPos = 1; // na pozycji zerowej pozostaje czekanie OrderTop = OrderPos; // ale może jest czymś zajęty na razie - if (NewOrder >= Shunt) // jeśli ma jechać + if (NewOrder.HasAny(movingOrders)) // jeśli ma jechać { // ale może być zajęty chwilowymi operacjami while (OrderTop >= 0 && OrderTop < maxorders - 1 - && OrderList[OrderTop] != Wait_for_orders && OrderList[OrderTop] < Shunt) // jeśli coś robi + && OrderList[OrderTop] != DriverOrder::waitForOrders && false == OrderList[OrderTop].HasAny(movingOrders)) // jeśli coś robi ++OrderTop; // pomijamy wszystkie tymczasowe prace } else { // jeśli ma ustawioną jazdę, to wyłączamy na rzecz operacji while (OrderTop >= 0 && OrderTop < maxorders - 1 - && OrderList[OrderTop] != Wait_for_orders && OrderList[OrderTop] < Shunt && OrderList[OrderTop] != NewOrder) // jeśli coś robi + && OrderList[OrderTop] != DriverOrder::waitForOrders && false == OrderList[OrderTop].HasAny(movingOrders) && OrderList[OrderTop] != NewOrder) // jeśli coś robi ++OrderTop; // pomijamy wszystkie tymczasowe prace } if (OrderTop < 0 || OrderTop >= maxorders) @@ -5804,9 +5804,9 @@ void TController::OrderNext(TOrders NewOrder) #endif } -void TController::OrderPush(TOrders NewOrder) +void TController::OrderPush(DriverOrders NewOrder) { // zapisanie na stosie kolejnego rozkazu do wykonania - if (OrderPos == OrderTop && OrderCurrentGet() < Shunt) // jeśli miałby być zapis na aktalnej pozycji + if (OrderPos == OrderTop && false == OrderCurrentGet().HasAny(movingOrders)) // jeśli miałby być zapis na aktalnej pozycji // ale nie jedzie ++OrderTop; // niektóre operacje muszą zostać najpierw dokończone => zapis na kolejnej @@ -5829,7 +5829,7 @@ void TController::OrdersDump( std::string const Neworder, bool const Verbose ) for (int b = 0; b < maxorders; ++b) { WriteLog( ( OrderPos == b ? ">" : " " ) + (std::to_string(b) + ": " + Order2Str(OrderList[b]))); - if (b && OrderList[b] == Wait_for_orders) // z wyjątkiem pierwszej pozycji + if (b && OrderList[b] == DriverOrder::waitForOrders) // z wyjątkiem pierwszej pozycji // jeśli końcowa komenda break; // dalej nie trzeba @@ -5840,25 +5840,25 @@ void TController::OrdersInit(double fVel) { // wypełnianie tabelki rozkazów na podstawie rozkładu // ustawienie kolejności komend, niezależnie kto prowadzi OrdersClear(); // usunięcie poprzedniej tabeli - OrderPush(Prepare_engine); // najpierw odpalenie silnika + OrderPush(DriverOrder::prepareEngine); // najpierw odpalenie silnika if (TrainParams.StationCount == 0) { // brak rozkładu to jazda manewrowa // if (fVel > 0.05) // typowo 0.1 oznacza gotowość do jazdy, 0.01 tylko załączenie silnika - OrderPush(Shunt); // jeśli nie ma rozkładu, to manewruje + OrderPush(DriverOrder::shunt); // jeśli nie ma rozkładu, to manewruje } else { // jeśli z rozkładem, to jedzie na szlak if (fVel > 0.0 && fVel < 0.02) - OrderPush(Shunt); // dla prędkości 0.01 włączamy jazdę manewrową + OrderPush(DriverOrder::shunt); // dla prędkości 0.01 włączamy jazdę manewrową else if (TrainParams.DirectionChange() ? // jeśli obrót na pierwszym przystanku (drivingFlags.pushPull ? // SZT również! SN61 zależnie od wagonów... TrainParams.TimeTable[1].StationName == TrainParams.Relation1 : false) : false) - OrderPush(Shunt); // a teraz start będzie w manewrowym, a tryb pociągowy włączy W4 + OrderPush(DriverOrder::shunt); // a teraz start będzie w manewrowym, a tryb pociągowy włączy W4 else // jeśli start z pierwszej stacji i jednocześnie jest na niej zmiana kierunku, to EZT ma mieć Shunt - OrderPush(Obey_train); // dla starych scenerii start w trybie pociagowym + OrderPush(DriverOrder::obeyTrain); // dla starych scenerii start w trybie pociagowym if (DebugModeFlag) // normalnie nie ma po co tego wypisywać WriteLog("/* Timetable: " + TrainParams.ShowRelation()); TMTableLine *t; @@ -5877,22 +5877,22 @@ void TController::OrdersInit(double fVel) { // zmiana kierunku i dalsza jazda wg rozk?adu if (drivingFlags.pushPull) // SZT również! SN61 zależnie od wagonów... { // jeśli skład zespolony, wystarczy zmienić kierunek jazdy - OrderPush(Change_direction); // zmiana kierunku + OrderPush(DriverOrder::changeDirection); // zmiana kierunku } else { // dla zwykłego składu wagonowego odczepiamy lokomotywę - OrderPush(Disconnect); // odczepienie lokomotywy - OrderPush(Shunt); // a dalej manewry + OrderPush(DriverOrder::disconnect); // odczepienie lokomotywy + OrderPush(DriverOrder::shunt); // a dalej manewry } if (i < TrainParams.StationCount) // jak nie ostatnia stacja - OrderPush(Obey_train); // to dalej wg rozkładu + OrderPush(DriverOrder::obeyTrain); // to dalej wg rozkładu } } if( DebugModeFlag ) { // normalnie nie ma po co tego wypisywać WriteLog( "*/" ); } - OrderPush(Shunt); // po wykonaniu rozkładu przełączy się na manewry + OrderPush(DriverOrder::shunt); // po wykonaniu rozkładu przełączy się na manewry } // McZapkie-100302 - to ma byc wyzwalane ze scenerii if( fVel == 0.0 ) { @@ -6087,7 +6087,7 @@ TCommandType TController::BackwardScan( double const Range ) // dzięki temu będzie można stawać za wskazanym sygnalizatorem, a zwłaszcza jeśli będzie jazda na kozioł // ograniczenia prędkości nie są wtedy istotne, również koniec toru jest do niczego nie przydatny // zwraca true, jeśli należy odwrócić kierunek jazdy pojazdu - if( OrderCurrentGet() & ~(Shunt | Loose_shunt | Connect) ) { + if( OrderCurrentGet().Without(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect) ) { // skanowanie sygnałów tylko gdy jedzie w trybie manewrowym albo czeka na rozkazy return TCommandType::cm_Unknown; } @@ -6152,8 +6152,8 @@ TCommandType TController::BackwardScan( double const Range ) auto move{false}; // czy AI w trybie manewerowym ma dociągnąć pod S1 if (e->input_command() == TCommandType::cm_SetVelocity) { - if (scanvel == 0.0 ? OrderCurrentGet() & (Shunt | Loose_shunt | Connect) : - OrderCurrentGet() & Connect) + if (scanvel == 0.0 ? OrderCurrentGet() & (DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect) : + OrderCurrentGet() & DriverOrder::connect) { // przy podczepianiu ignorować wyjazd? move = true; // AI w trybie manewerowym ma dociągnąć pod S1 } @@ -6165,7 +6165,7 @@ TCommandType TController::BackwardScan( double const Range ) // ruszać stop trzeba powtarzać, bo inaczej zatrąbi i pojedzie sam #if LOGBACKSCAN if (scandist > fMinProximityDist && - mvOccupied->Vel > EU07_AI_NOMOVEMENT && (OrderCurrentGet() & (Shunt | Loose_shunt)) == 0) + mvOccupied->Vel > EU07_AI_NOMOVEMENT && false == OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt)) { WriteLog(edir); } @@ -6179,7 +6179,7 @@ TCommandType TController::BackwardScan( double const Range ) } } // reakcja AI w trybie manewrowym dodatkowo na sygnały manewrowe - if ((OrderCurrentGet() ? OrderCurrentGet() & (Shunt | Loose_shunt | Connect) : true) && (move || e->input_command() == TCommandType::cm_ShuntVelocity)) // w Wait_for_orders też widzi tarcze + if ((false == OrderCurrentGet().Empty() ? OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect) : true) && (move || e->input_command() == TCommandType::cm_ShuntVelocity)) // w Wait_for_orders też widzi tarcze { // jeśli powyżej było SetVelocity 0 0, to dociągamy pod S1 /* @@ -6310,7 +6310,7 @@ void TController::TakeControl( bool const Aidriver, bool const Forcevehiclecheck } else { // jeśli nic nie robi - OrderNext( Prepare_engine ); + OrderNext( DriverOrder::prepareEngine ); if( pVehicle->MoverParameters->iLights[ ( mvOccupied->CabActive < 0 ? end::rear : end::front ) ] @@ -6318,9 +6318,9 @@ void TController::TakeControl( bool const Aidriver, bool const Forcevehiclecheck { // od wersji 357 oczekujemy podania komend dla AI przez scenerię /* if( pVehicle->MoverParameters->iLights[ mvOccupied->CabActive < 0 ? end::rear : end::front ] & light::headlight_upper ) // górne światło zapalone - OrderNext( Obey_train ); // jazda pociągowa + OrderNext( DriverOrder::obeyTrain ); // jazda pociągowa else - OrderNext( Shunt ); // jazda manewrowa + OrderNext( DriverOrder::shunt ); // jazda manewrowa */ if( mvOccupied->Vel >= 1.0 ) // jeśli jedzie (dla 0.1 ma stać) drivingFlags.stopHere = false; // to ma nie czekać na sygnał, tylko jechać @@ -6333,7 +6333,7 @@ void TController::TakeControl( bool const Aidriver, bool const Forcevehiclecheck } else { // a teraz użytkownik - if (eAction == TAction::actSleep || OrderCurrentGet() == Wait_for_orders) // gasimy swiatla jesli przejmujemy odstawione + if (eAction == TAction::actSleep || OrderCurrentGet() == DriverOrder::waitForOrders) // gasimy swiatla jesli przejmujemy odstawione pVehicle->RaLightsSet(0, 0); auto const aiwasdriving { AIControllFlag == AIdriver }; if( aiwasdriving ) { @@ -6591,7 +6591,7 @@ TController::update_timers( double dt ) { fActionTime += dt; // czas używany przy regulacji prędkości i zamykaniu drzwi LastReactionTime += dt; if( mvOccupied->Vel < 0.05 - && (OrderCurrentGet() & (Shunt | Loose_shunt | Obey_train | Bank)) != 0 ) { + && OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank) ) { IdleTime += dt; } else { @@ -6976,7 +6976,7 @@ TController::control_pantographs() { // the pantograph setup the .fiz suggests for shunting (AI: ShuntPantstate=, eu07/maszyna#461), 0 when there's none // or the vehicle isn't shunting auto const shuntpantographsetup { - ( OrderCurrentGet() & ( Shunt | Loose_shunt ) ) != 0 ? + OrderCurrentGet().HasAny( DriverOrder::shunt | DriverOrder::looseShunt ) ? mvOccupied->AIHintShuntPantstate : 0 }; @@ -7318,7 +7318,7 @@ TController::control_lights() { if( is_train() ) { // jeśli jazda pociągowa - if( true == TestFlag( OrderCurrentGet(), Obey_train ) ) { + if( true == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { // head lights if( m_lighthints[ end::front ] == -1 ) { cue_action( driver_hint::headcodepc1 ); @@ -7343,7 +7343,7 @@ TController::control_lights() { } } // for shunting mode - else if( OrderCurrentGet() & ( Shunt | Loose_shunt | Connect ) ) { + else if( OrderCurrentGet() & ( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect ) ) { cue_action( driver_hint::headcodetb1 ); } } @@ -7501,9 +7501,9 @@ TController::scan_obstacles( double const Range ) { void TController::determine_proximity_ranges() { // ustalenie dystansów w pozostałych przypadkach - switch (OrderCurrentGet()) + switch (SingleOrder(OrderCurrentGet())) { - case Connect: { + case DriverOrder::connect: { // podłączanie do składu if (drivingFlags.connect) { // jeśli stanął już blisko, unikając zderzenia i można próbować podłączyć @@ -7521,7 +7521,7 @@ TController::determine_proximity_ranges() { } break; } - case Disconnect: { + case DriverOrder::disconnect: { // 20.07.03 - manewrowanie wagonami fMinProximityDist = 1.0; fMaxProximityDist = 10.0; //[m] @@ -7529,7 +7529,7 @@ TController::determine_proximity_ranges() { fVelMinus = 0.5; // margines prędkości powodujący załączenie napędu break; } - case Shunt: { + case DriverOrder::shunt: { // na jaką odleglość i z jaką predkością ma podjechać // TODO: test if we can use the distances calculation from obey_train fMinProximityDist = std::min( 5 + iVehicles, 25 ); @@ -7551,14 +7551,14 @@ TController::determine_proximity_ranges() { fVelMinus = std::min( 0.1 * fShuntVelocity, 3.0 ); break; } - case Loose_shunt: { + case DriverOrder::looseShunt: { fMinProximityDist = -1.0; fMaxProximityDist = 0.0; //[m] dojechać maksymalnie fVelPlus = 2.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania fVelMinus = 0.5; // margines prędkości powodujący załączenie napędu break; } - case Obey_train: { + case DriverOrder::obeyTrain: { // na jaka odleglosc i z jaka predkoscia ma podjechac do przeszkody // jeśli pociąg if( is_train() ) { @@ -7597,7 +7597,7 @@ TController::determine_proximity_ranges() { } break; } - case Bank: { + case DriverOrder::bank: { // TODO: implement break; } @@ -7613,14 +7613,14 @@ TController::determine_proximity_ranges() { void TController::check_departure() { - if(( OrderCurrentGet() & ( Shunt | Loose_shunt | Obey_train | Bank | Connect ) ) == 0 ) { return; } + if(false == OrderCurrentGet().HasAny( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank | DriverOrder::connect ) ) { return; } // odjechać sam może tylko jeśli jest w trybie jazdy // automatyczne ruszanie po odstaniu albo spod SBL if( VelSignal == 0.0 && WaitingTime > 0.0 && mvOccupied->RunningTrack.Velmax != 0.0 ) { // jeśli stoi, a upłynął czas oczekiwania i tor ma niezerową prędkość - if( OrderCurrentGet() & (Shunt | Loose_shunt | Obey_train | Bank) + if( OrderCurrentGet() & (DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank) && drivingFlags.stopHere ) { // zakaz ruszania z miejsca bez otrzymania wolnej drogi WaitingTime = -WaitingExpireTime; @@ -7689,7 +7689,7 @@ TController::check_load_exchange() { void TController::UpdateChangeDirection() { // TODO: rework into driver mode independent routine - if( false == TestFlag( OrderCurrentGet(), Change_direction ) ) { return; } + if( false == OrderCurrentGet().HasAll(DriverOrder::changeDirection) ) { return; } if( true == AIControllFlag && mvOccupied->Vel < EU07_AI_NOMOVEMENT ) { // sprobuj zmienic kierunek (może być zmieszane z jeszcze jakąś komendą) @@ -7706,7 +7706,7 @@ TController::UpdateChangeDirection() { VelSignalNext = -1; PrepareEngine(); JumpToNextOrder(); // następnie robimy, co jest do zrobienia (Shunt albo Obey_train) - if( OrderCurrentGet() & (Shunt | Loose_shunt | Connect) && false == drivingFlags.stopHere ) { + if( OrderCurrentGet() & (DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect) && false == drivingFlags.stopHere ) { // jeśli dalej mamy manewry // o ile nie ma stać w miejscu, // jechać od razu w przeciwną stronę i nie trąbić z tego tytułu: @@ -7821,7 +7821,7 @@ TController::UpdateConnect() { // NOTE: no else as the preceeding block can potentially establish expected connection if( vehicleparameters->Couplers[ couplingend ].CouplingFlag == expectedcoupling ) { // jeżeli został podłączony - CheckVehicles( Connect ); // sprawdzić światła nowego składu + CheckVehicles( DriverOrder::connect ); // sprawdzić światła nowego składu iCoupler = {}; // dalsza jazda manewrowa już bez łączenia iCouplingVehicle.reset(); @@ -7947,7 +7947,7 @@ TController::UpdateDisconnect() { WriteLog( "Uncoupling [" + mvOccupied->Name + "]: uncoupled" ); iVehicleCount = -2; // update trainset state - CheckVehicles( Disconnect ); + CheckVehicles( DriverOrder::disconnect ); // potentially remove coupler adapter /* if( decoupledvehicle->MoverParameters->Couplers[ decoupledend ].has_adapter() ) { @@ -8008,19 +8008,19 @@ TController::UpdateDisconnect() { void TController::handle_engine() { // HACK: activate route scanning if an idling vehicle is activated by a human user - if( OrderCurrentGet() == Wait_for_orders + if( OrderCurrentGet() == DriverOrder::waitForOrders && false == iEngineActive // && ( false == AIControllFlag ) && true == mvOccupied->Power24vIsAvailable ) { - OrderNext( Prepare_engine ); + OrderNext( DriverOrder::prepareEngine ); } // basic engine preparation - if( OrderCurrentGet() == Prepare_engine && PrepareEngine() ) { + if( OrderCurrentGet() == DriverOrder::prepareEngine && PrepareEngine() ) { // gotowy do drogi? JumpToNextOrder(); } // engine state can potentially deteriorate in one of usual driving modes - if( OrderCurrentGet() & (Change_direction | Connect | Disconnect | Shunt | Loose_shunt | Obey_train | Bank) + if( OrderCurrentGet() & (DriverOrder::changeDirection | DriverOrder::connect | DriverOrder::disconnect | DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank) && false == iEngineActive ) { // jeśli coś ma robić to niech odpala do skutku PrepareEngine(); @@ -8030,31 +8030,31 @@ TController::handle_engine() { void TController::handle_orders() { - switch (OrderCurrentGet()) + switch (SingleOrder(OrderCurrentGet())) { - case Release_engine: { + case DriverOrder::releaseEngine: { if( ReleaseEngine() ) { // zdana maszyna? JumpToNextOrder(); } break; } - case Obey_train: { + case DriverOrder::obeyTrain: { UpdateObeyTrain(); break; } - case Loose_shunt: { + case DriverOrder::looseShunt: { UpdateLooseShunt(); break; } - case Connect: { + case DriverOrder::connect: { UpdateConnect(); break; } - case Disconnect: { + case DriverOrder::disconnect: { UpdateDisconnect(); break; } - case Jump_to_first_order: { + case DriverOrder::jumpToFirstOrder: { if( OrderPos > 1 ) { OrderPos = 1; // w zerowym zawsze jest czekanie } @@ -8106,7 +8106,7 @@ void TController::hold_train_coming_to_stand_uphill() { if( ( false == is_train() ) - || ( ( OrderCurrentGet() & Obey_train ) == 0 ) + || ( false == OrderCurrentGet().HasAny(DriverOrder::obeyTrain) ) || ( VelNext != 0.0 ) || ( ActualProximityDist > fMaxProximityDist ) || ( fAccGravity >= EU07_AI_UPHILLGRAVITY ) ) { @@ -8136,7 +8136,7 @@ TController::hold_train_coming_to_stand_uphill() { void TController::pick_optimal_speed( double const Range ) { -// if( ( OrderCurrentGet() & ( Shunt | Loose_shunt | Obey_train | Bank | Connect | Disconnect | Change_direction ) ) == 0 ) { return; } +// if( false == OrderCurrentGet().HasAny( Shunt | Loose_shunt | Obey_train | Bank | Connect | Disconnect | Change_direction ) ) { return; } // set initial velocity and acceleration values SetDriverPsyche(); // ustawia AccPreferred (potrzebne tu?) @@ -8144,7 +8144,7 @@ TController::pick_optimal_speed( double const Range ) { AccDesired = AccPreferred; // AccPreferred wynika z osobowości mechanika // nie przekraczać rozkladowej - if( (OrderCurrentGet() & Obey_train) != 0 + if( OrderCurrentGet().HasAny(DriverOrder::obeyTrain) && TrainParams.TTVmax > 0.0 ) { VelDesired = min_speed( @@ -8159,7 +8159,7 @@ TController::pick_optimal_speed( double const Range ) { // basic velocity and acceleration adjustments // jeśli manewry, to ograniczamy prędkość - if( ( OrderCurrentGet() & ( Obey_train | Bank ) ) == 0 ) { // spokojne manewry + if( false == OrderCurrentGet().HasAny( DriverOrder::obeyTrain | DriverOrder::bank ) ) { // spokojne manewry SetVelocity( fShuntVelocity, fShuntVelocity ); VelDesired = min_speed( @@ -8167,7 +8167,7 @@ TController::pick_optimal_speed( double const Range ) { fShuntVelocity ); } // uncoupling mode changes velocity/acceleration between stages - if( ( OrderCurrentGet() & Disconnect ) != 0 ) { + if( OrderCurrentGet().HasAny(DriverOrder::disconnect) ) { set_velocity_for_uncoupling(); } @@ -8189,11 +8189,11 @@ TController::pick_optimal_speed( double const Range ) { check_departure(); // if ordered to turn off the vehicle, try to stop - if( true == TestFlag( OrderCurrentGet(), Release_engine ) ) { + if( true == OrderCurrentGet().HasAll(DriverOrder::releaseEngine) ) { SetVelocity( 0, 0, stopSleep ); } // if ordered to change direction, try to stop - if( true == TestFlag( OrderCurrentGet(), Change_direction ) ) { + if( true == OrderCurrentGet().HasAll(DriverOrder::changeDirection) ) { SetVelocity( 0, 0, stopDir ); } @@ -8287,7 +8287,7 @@ TController::adjust_desired_speed_for_obstacles() { VelDesired, Obstacle.distance > 100 ? k + 20.0 : std::min(8.0, k + 4.0) ) ); - if( ( OrderCurrentGet() & ( Connect | Loose_shunt ) ) != 0 ) { + if( OrderCurrentGet().HasAny( DriverOrder::connect | DriverOrder::looseShunt ) ) { // jeśli spinanie, to jechać dalej AccPreferred = std::min( 0.35, AccPreferred ); // nie hamuj VelNext = std::floor( std::min( 8.0, k + 2.0 ) ); // i pakuj się na tamtego @@ -8300,7 +8300,7 @@ TController::adjust_desired_speed_for_obstacles() { } if( mvOccupied->CategoryFlag & 1 - && OrderCurrentGet() & Obey_train ) { + && OrderCurrentGet() & DriverOrder::obeyTrain ) { // trains which move normally should try to stop at safe margin ActualProximityDist -= fDriverDist; } @@ -8328,7 +8328,7 @@ TController::adjust_desired_speed_for_obstacles() { 2.0; // we're already standing still, so take it easy } else { - if( OrderCurrentGet() & Connect ) { + if( OrderCurrentGet() & DriverOrder::connect ) { // if there's something nearby in the connect mode don't speed up too much VelDesired = min_speed( @@ -8379,14 +8379,14 @@ TController::adjust_desired_speed_for_limits() { return; // speed limit can't get any lower } - if( (OrderCurrentGet() & (Shunt | Loose_shunt | Obey_train | Bank)) != 0 && drivingFlags.stopHere && mvOccupied->Vel < 0.01 && VelSignalNext == 0.0 ) { + if( OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank) && drivingFlags.stopHere && mvOccupied->Vel < 0.01 && VelSignalNext == 0.0 ) { // w Connect nie, bo moveStopHere odnosi się do stanu po połączeniu // jeśli ma czekać na wolną drogę, stoi a wyjazdu nie ma, to ma stać VelDesired = 0.0; return; // speed limit can't get any lower } - if( OrderCurrentGet() == Wait_for_orders ) { + if( OrderCurrentGet() == DriverOrder::waitForOrders ) { // wait means sit and wait VelDesired = 0.0; return; // speed limit can't get any lower @@ -8436,7 +8436,7 @@ TController::adjust_desired_speed_for_braking_curve( double const Vel ) { mvOccupied->CategoryFlag == 2 ? // cars can stop on a dime, for bigger vehicles we enforce some minimal braking distance brakingdistance : std::max( - (OrderCurrentGet() & Connect) == 0 ? 100.0 : 25.0, + false == OrderCurrentGet().HasAny(DriverOrder::connect) ? 100.0 : 25.0, brakingdistance ) ) }; brakingdistance + std::max(slowdowndistance, fMaxProximityDist) < ActualProximityDist - fMaxProximityDist ) { // don't slow down prematurely; as long as we have room to come to a full stop at a safe distance, we're good @@ -8444,7 +8444,7 @@ TController::adjust_desired_speed_for_braking_curve( double const Vel ) { } // ensure some minimal coasting speed, otherwise a vehicle entering this zone at very low speed will be crawling forever auto const brakingpointoffset = ( - ( VelNext == 0.0 ) && is_train() && ( OrderCurrentGet() & Obey_train ) ? + ( VelNext == 0.0 ) && is_train() && ( OrderCurrentGet() & DriverOrder::obeyTrain ) ? stopping_margin() : // the same stopping point as the final approach VelNext * braking_distance_multiplier( static_cast( VelNext ) ) ); // both plans of a pneumatic brake are made from the brake table of the consist; with none (in shunting it isn't @@ -8477,7 +8477,7 @@ TController::adjust_desired_speed_for_braking_curve( double const Vel ) { AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION ); } else if( ( fAccGravity < -0.025 ) - && ( ( OrderCurrentGet() & Obey_train ) != 0 ) + && ( OrderCurrentGet().HasAny(DriverOrder::obeyTrain) ) && ( false == uphill_brake_committed( Vel ) ) && ( ActualProximityDist - uphill_stopping_distance( Vel, fAccGravity ) > brakingpointoffset ) ) { // uphill the gradient alone slows the train down more than it is asked to; @@ -8497,7 +8497,7 @@ TController::adjust_desired_speed_for_final_approach( double const Vel ) { return; } // trains - if( ( OrderCurrentGet() & ( Shunt | Connect ) ) + if( ( OrderCurrentGet() & ( DriverOrder::shunt | DriverOrder::connect ) ) && ( Obstacle.distance < 50 ) ) { // crude detection of edge case, if approaching another vehicle coast slowly until min distance // this should allow to bunch up trainsets more on sidings @@ -8505,7 +8505,7 @@ TController::adjust_desired_speed_for_final_approach( double const Vel ) { return; } // hamowanie tak, aby stanąć - if( ( OrderCurrentGet() & Obey_train ) == 0 ) { + if( false == OrderCurrentGet().HasAny(DriverOrder::obeyTrain) ) { VelDesired = VelNext; AccDesired = ( VelNext * VelNext - Vel * Vel ) / ( 25.92 * ( ActualProximityDist + 0.1 - 0.5*fMinProximityDist ) ); AccDesired = std::min( AccDesired, fAccThreshold ); @@ -8778,7 +8778,7 @@ TController::adjust_desired_speed_for_braking_test() { && ( false == timetable::makes_brake_test( TrainParams.run_flags() ) ) ) { return; } // the timetable says there's none (eu07/maszyna#95) if( false == is_train() ) { return; } // not applicable if( mvOccupied->BrakeHandle == TBrakeHandle::FVel6 ) { return; } // leads to bugs in DecBrake, disable for now - if( false == TestFlag( OrderCurrentGet(), Obey_train ) ) { return; } // not applicable + if( false == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { return; } // not applicable if( false == AIControllFlag ) { return; } // TBD: add notification about braking test and enable it for human driver as well? auto const vel { DirectionalVel() }; @@ -8973,7 +8973,7 @@ void TController::control_tractive_force() { true : velocity + 1.0 < VelNext // uphill, a train told to hold its speed on the way to a stop needs the power to do it - || VelNext == 0.0 && (OrderCurrentGet() & Obey_train) != 0 && AccDesired >= 0.0 && fAccGravity < -0.025 && ActualProximityDist > fMinProximityDist) ) { + || VelNext == 0.0 && OrderCurrentGet().HasAny(DriverOrder::obeyTrain) && AccDesired >= 0.0 && fAccGravity < -0.025 && ActualProximityDist > fMinProximityDist) ) { // ...jeśli prędkość w kierunku czoła jest mniejsza od dozwolonej o margines... // within proximity margin don't exceed next scheduled speed, outside of the margin accelerate as you like // ...to można przyspieszyć @@ -9217,7 +9217,7 @@ bool TController::uphill_stop_hold() const { return ( - ( BrakeSystem == TBrakeSystem::Pneumatic ) && is_train() && ( ( OrderCurrentGet() & Obey_train ) != 0 ) + ( BrakeSystem == TBrakeSystem::Pneumatic ) && is_train() && ( OrderCurrentGet().HasAny(DriverOrder::obeyTrain) ) && ( VelNext == 0.0 ) && ( ActualProximityDist <= fMaxProximityDist ) && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) @@ -9253,7 +9253,7 @@ void TController::control_braking_force() { && ( false == bUphillStart ) }; // jeśli przyspieszamy, to nie hamujemy - if( AccDesired > 0.0 && OrderCurrentGet() != Disconnect // przy odłączaniu nie zwalniamy tu hamulca + if( AccDesired > 0.0 && OrderCurrentGet() != DriverOrder::disconnect // przy odłączaniu nie zwalniamy tu hamulca && false == drivingFlags.press && false == slippingbackuphill ) { cue_action(driver_hint::brakingforcesetzero); @@ -9293,7 +9293,7 @@ void TController::control_braking_force() { // hamować bardziej, gdy aktualne opóźnienie hamowania mniejsze niż (AccDesired) cue_action( driver_hint::brakingforceincrease ); } - else if( OrderCurrentGet() != Disconnect ) { // przy odłączaniu nie zwalniamy tu hamulca + else if( OrderCurrentGet() != DriverOrder::disconnect ) { // przy odłączaniu nie zwalniamy tu hamulca if( AbsAccS < accdesiredresultant - 0.05 ) { // jeśli opóźnienie większe od wymaganego (z histerezą) luzowanie, gdy za dużo // TBD: check if the condition isn't redundant with the DecBrake() code @@ -9336,7 +9336,7 @@ void TController::control_braking_force() { } if ( (accdesiredresultant < fAccGravity - 0.05 || AccDesired >= EU07_AI_NOACCELERATION) // no braking asked for, yet the train is slowing down more than that - && accdesiredresultant - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 && OrderCurrentGet() != Disconnect && VelDesired > 0.0 + && accdesiredresultant - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 && OrderCurrentGet() != DriverOrder::disconnect && VelDesired > 0.0 // a human driver standing with the train not charged yet keeps the locomotive brake on, told so by the // waitbrakecharge hint; the ai is held back in DecBrake() && ( AIControllFlag @@ -9375,12 +9375,12 @@ void TController::control_braking_force() { && ( VelDesired == 0.0 || AccDesired <= EU07_AI_NOACCELERATION ) ) { - if( (OrderCurrentGet() & (Disconnect | Connect | Change_direction)) == 0 // przy (p)odłączaniu nie zwalniamy tu hamulca + if( false == OrderCurrentGet().HasAny(DriverOrder::disconnect | DriverOrder::connect | DriverOrder::changeDirection) // przy (p)odłączaniu nie zwalniamy tu hamulca && std::abs(fAccGravity) < 0.01 ) { // only do this on flats, on slopes keep applied the train brake apply_independent_brake_only(); } // if told to change direction don't confuse human driver with request to leave applied brake in the cab they're about to leave - if( ( OrderCurrentGet() & Change_direction ) != 0 ) { + if( OrderCurrentGet().HasAny(DriverOrder::changeDirection) ) { cue_action( driver_hint::independentbrakerelease ); } } @@ -9426,7 +9426,7 @@ void TController::control_releaser() { state.pressing = drivingFlags.press; // stage 3 of uncoupling (UpdateDisconnect), from the direction change until the coupler lets go state.compressing_buffers = - state.pressing && ( OrderCurrentGet() & Disconnect ) != 0 && iVehicleCount >= 0 && iDirection == iDirectionOrder; + state.pressing && OrderCurrentGet().HasAny(DriverOrder::disconnect) && iVehicleCount >= 0 && iDirection == iDirectionOrder; // a train prepared standing charges its brakes before its first start. a pipe left below the lock of the driver's // brake valve (a train placed cold, as after an emergency application) is unlocked as the train stands, not only // once it is to go: else it charges only after the order to go, and starts on what the reservoirs got by then. @@ -9579,14 +9579,14 @@ TController::check_route_ahead( double const Range ) { break; } case TCommandType::cm_SetVelocity: { // od wersji 357 semafor nie budzi wyłączonej lokomotywy - if( (OrderCurrentGet() & ~(Shunt | Loose_shunt | Obey_train | Bank)) == 0 && std::fabs(VelSignal) >= 1.0 ) { // jedzie w dowolnym trybie albo Wait_for_orders + if( OrderCurrentGet().Without(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank).Empty() && std::fabs(VelSignal) >= 1.0 ) { // jedzie w dowolnym trybie albo Wait_for_orders // 0.1 nie wysyła się do samochodow, bo potem nie ruszą PutCommand("SetVelocity", VelSignal, VelNext, nullptr); // komenda robi dodatkowe operacje } break; } case TCommandType::cm_ShuntVelocity: { // od wersji 357 Tm nie budzi wyłączonej lokomotywy - if( ( OrderCurrentGet() & ~( Shunt | Loose_shunt | Obey_train | Bank ) ) == 0 ) { // jedzie w dowolnym trybie albo Wait_for_orders + if( OrderCurrentGet().Without( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank ).Empty() ) { // jedzie w dowolnym trybie albo Wait_for_orders PutCommand( "ShuntVelocity", VelSignal, VelNext, nullptr ); } else if( false == iCoupler.Empty() ) { // jeśli jedzie w celu połączenia @@ -9595,7 +9595,7 @@ TController::check_route_ahead( double const Range ) { break; } case TCommandType::cm_Command: { // komenda z komórki - if( (OrderCurrentGet() & ~(Shunt | Loose_shunt | Obey_train | Bank)) == 0 && mvOccupied->Vel < 0.1 ) { + if( OrderCurrentGet().Without(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank).Empty() && mvOccupied->Vel < 0.1 ) { // jedzie w dowolnym trybie albo Wait_for_orders // dopiero jak stanie /* @@ -9618,11 +9618,11 @@ TController::check_route_behind( double const Range ) { if( VelNext != 0.0 ) { return; } // not if we can move ahead if( drivingFlags.connect ) { return; } // not if we're in middle of coupling operation - if( ( OrderCurrentGet() & ~( Shunt | Loose_shunt | Connect ) ) == 0 ) { + if( OrderCurrentGet().Without( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect ).Empty() ) { // jedzie w Shunt albo Connect, albo Wait_for_orders // w trybie Connect skanować do tyłu tylko jeśli przed kolejnym sygnałem nie ma taboru do podłączenia auto const couplinginprogress { - TestFlag(OrderCurrentGet(), Connect) + OrderCurrentGet().HasAll(DriverOrder::connect) && ( Obstacle.distance < std::min(2000.0, FirstSemaphorDist) || drivingFlags.connect ) }; if( couplinginprogress ) { return; } @@ -9639,7 +9639,7 @@ TController::check_route_behind( double const Range ) { } iDirectionOrder = -iDirection; // zmiana kierunku jazdy // zmiana kierunku bez psucia kolejnych komend - OrderCurrentSet( TOrders( OrderCurrentGet() | Change_direction ) ); + OrderCurrentSet( (OrderCurrentGet() | DriverOrder::changeDirection) ); } } } diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 7592e6eac..773c608e2 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -14,6 +14,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Classes.h" #include "utilities/utilities.h" #include "physics/vehicletypes.h" +#include "vehicle/driverorders.h" #include "audio/sound.h" #include "vehicle/DynObj.h" #include "world/mtable.h" @@ -34,23 +35,6 @@ auto const EU07_AI_UPHILLRELEASETIME = 60.0; // [s] the longest an uphill start auto const EU07_AI_SPEEDLIMITEXTENDSBEYONDSCANRANGE = 10000.0; auto const EU07_AI_SANDEDSTARTVELOCITY = 15.0; // [km/h] a start that slipped keeps the sand on up to this speed -enum TOrders -{ // rozkazy dla AI - Wait_for_orders = 0, // czekanie na dostarczenie następnych rozkazów - // operacje tymczasowe - Prepare_engine = 1 << 0, // włączenie silnika - Release_engine = 1 << 1, // wyłączenie silnika - Change_direction = 1 << 2, // zmiana kierunku (bez skanowania sygnalizacji) - Connect = 1 << 3, // podłączanie wagonów (z częściowym skanowaniem sygnalizacji) - Disconnect = 1 << 4, // odłączanie wagonów (bez skanowania sygnalizacji) - // jazda - Shunt = 1 << 5, // tryb manewrowy - Loose_shunt = 1 << 6, // coupling-free shunting mode - Obey_train = 1 << 7, // tryb pociągowy - Bank = 1 << 8, // assist mode - // others - Jump_to_first_order = 1 << 9, // zapęlenie do pierwszej pozycji (po co?) -}; // the signals the map asks the driver to show (SetSignal) enum TSignals @@ -181,7 +165,7 @@ class TSpeedPos public: TSpeedPos(TTrack *track, double dist, int flag); - TSpeedPos(basic_event *event, double dist, double length, TOrders order); + TSpeedPos(basic_event *event, double dist, double length, DriverOrders order); TSpeedPos() = default; void Clear(); bool Update(); @@ -191,11 +175,11 @@ class TSpeedPos UpdateDistance( double dist ) { fDist -= dist; } // Standing: the train stands, so an event found behind its head wasn't passed by it - bool Set(basic_event *e, double d, double length, TOrders order = Wait_for_orders, bool Standing = false); + bool Set(basic_event *e, double d, double length, DriverOrders order = DriverOrder::waitForOrders, bool Standing = false); void Set(TTrack *t, double d, int f); std::string TableText() const; std::string GetName() const; - bool IsProperSemaphor(TOrders order = Wait_for_orders); + bool IsProperSemaphor(DriverOrders order = DriverOrder::waitForOrders); }; //---------------------------------------------------------------------------- @@ -281,7 +265,7 @@ public: // the light pattern the timetable or the scenery asks for at an end of the train, -1 the usual one int light_hint( int const End ) const { return m_lighthints[ End ]; } // the order the driver goes by now: a train run, shunting and the like - TOrders order_current() const { return OrderCurrentGet(); } + DriverOrders order_current() const { return OrderCurrentGet(); } private: // tells the black box of the train at the station of its timetable it makes for, at the stop point given void record_station( TSpeedPos const &Point, std::uint8_t Kind ) const; @@ -396,7 +380,7 @@ private: // how far short of a stop the AI aims: in train running the middle of the 8-15 m window before a signal, // otherwise (a W4 stop point, shunting, coupling) half the minimum proximity distance, as before double stopping_margin() const { - return ( ( OrderCurrentGet() & Obey_train ) != 0 ) && !IsAtPassengerStop ? + return ( OrderCurrentGet().HasAny(DriverOrder::obeyTrain) ) && !IsAtPassengerStop ? fMinProximityDist + 3.5 : 0.5 * fMinProximityDist; } void apply_independent_brake_only(); @@ -551,20 +535,20 @@ private: void RecognizeCommand(); // odczytuje komende przekazana lokomotywie void JumpToNextOrder( bool const Skipmergedchangedirection = false ); void JumpToFirstOrder(); - void OrderPush( TOrders NewOrder ); - void OrderNext( TOrders NewOrder ); - inline TOrders OrderCurrentGet() const; - inline void OrderCurrentSet( TOrders const Order ); - inline TOrders OrderNextGet() const; + void OrderPush( DriverOrders NewOrder ); + void OrderNext( DriverOrders NewOrder ); + inline DriverOrders OrderCurrentGet() const; + inline void OrderCurrentSet( DriverOrders const Order ); + inline DriverOrders OrderNextGet() const; void OrderCheck(); void OrdersInit( double fVel ); void OrdersClear(); void OrdersDump( std::string const Neworder, bool const Verbose = true ); - std::string Order2Str( TOrders Order ) const; + std::string Order2Str( DriverOrders Order ) const; // members std::string m_assignment; glm::dvec3 vCommandLocation; // polozenie wskaznika, sygnalizatora lub innego obiektu do ktorego odnosi sie komenda // NOTE: not used - TOrders OrderList[ maxorders ]; // lista rozkazów + DriverOrders OrderList[ maxorders ]; // lista rozkazów int OrderPos = 0, OrderTop = 0; // rozkaz aktualny oraz wolne miejsce do wstawiania nowych @@ -692,7 +676,7 @@ private: // consist // methods public: - bool CheckVehicles( TOrders user = Wait_for_orders ); + bool CheckVehicles( DriverOrders user = DriverOrder::waitForOrders ); private: bool PrepareEngine(); // tells in the log, once, of standing with the pantographs up and no voltage (eu07/maszyna#421) @@ -778,23 +762,23 @@ private: }; -inline TOrders TController::OrderCurrentGet() const { +inline DriverOrders TController::OrderCurrentGet() const { if( OrderPos < 0 || OrderPos >= maxorders ) { - return Wait_for_orders; + return DriverOrder::waitForOrders; } return OrderList[ OrderPos ]; } -inline void TController::OrderCurrentSet( TOrders const Order ) { +inline void TController::OrderCurrentSet( DriverOrders const Order ) { if( OrderPos < 0 || OrderPos >= maxorders ) { return; } OrderList[ OrderPos ] = Order; } -inline TOrders TController::OrderNextGet() const { +inline DriverOrders TController::OrderNextGet() const { if( OrderPos < 0 || OrderPos >= maxorders ) { - return Wait_for_orders; + return DriverOrder::waitForOrders; } // the order list wraps around, same as in JumpToNextOrder() return OrderList[ ( OrderPos + 1 ) % maxorders ]; diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index a89fe5146..7456749ff 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -3789,7 +3789,7 @@ bool TDynamicObject::Update(double dt, double dt1) if( TestFlag( MoverParameters->AIFlag, sound::attachcoupler ) ) { auto *driver{ ctOwner ? ctOwner : Mechanik }; if( driver != nullptr ) { - driver->CheckVehicles( Connect ); + driver->CheckVehicles( DriverOrder::connect ); } ClearFlag( MoverParameters->AIFlag, sound::attachcoupler ); } diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 076e01fde..fd55f58a9 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -8167,7 +8167,7 @@ void TTrain::OnCommand_nearestcarcouplingincrease(TTrain *Train, command_data co if (Train->DynamicObject->Mechanik) { // aktualizacja flag kierunku w składzie - Train->DynamicObject->Mechanik->CheckVehicles(Connect); + Train->DynamicObject->Mechanik->CheckVehicles(DriverOrder::connect); } } } @@ -8191,7 +8191,7 @@ void TTrain::OnCommand_nearestcarcouplingdisconnect(TTrain *Train, command_data if (Train->DynamicObject->Mechanik) { // aktualizacja flag kierunku w składzie - Train->DynamicObject->Mechanik->CheckVehicles(Disconnect); + Train->DynamicObject->Mechanik->CheckVehicles(DriverOrder::disconnect); } } } @@ -8255,7 +8255,7 @@ void TTrain::OnCommand_occupiedcarcouplingdisconnect(TTrain *Train, command_data if (Train->DynamicObject->Mechanik) { // aktualizacja flag kierunku w składzie - Train->DynamicObject->Mechanik->CheckVehicles(Disconnect); + Train->DynamicObject->Mechanik->CheckVehicles(DriverOrder::disconnect); } } } @@ -8287,7 +8287,7 @@ void TTrain::OnCommand_occupiedcarcouplingdisconnectback(TTrain *Train, command_ if (Train->DynamicObject->Mechanik) { // aktualizacja flag kierunku w składzie - Train->DynamicObject->Mechanik->CheckVehicles(Disconnect); + Train->DynamicObject->Mechanik->CheckVehicles(DriverOrder::disconnect); } } } diff --git a/vehicle/brakesetting.cpp b/vehicle/brakesetting.cpp index fd7378f8c..3b06835f9 100644 --- a/vehicle/brakesetting.cpp +++ b/vehicle/brakesetting.cpp @@ -173,12 +173,12 @@ std::vector choose(std::vector const &Consist, bool const Train) { return settings; } -bool runs_as_train(int const Orders) { - return (Orders & (Obey_train | Bank)) != 0; +bool runs_as_train(DriverOrders const Orders) { + return Orders.HasAny(DriverOrder::obeyTrain | DriverOrder::bank); } -bool inspects_train(int const Orders, bool const Coupled) { - return (Orders & (Shunt | Loose_shunt | Obey_train | Bank)) != 0 || ((Orders & Connect) != 0 && false == Coupled); +bool inspects_train(DriverOrders const Orders, bool const Coupled) { + return Orders.HasAny(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank) || (Orders.HasAny(DriverOrder::connect) && false == Coupled); } bool at_standstill(double const Velocity) { diff --git a/vehicle/brakesetting.h b/vehicle/brakesetting.h index e3e5b4974..9bb46d9da 100644 --- a/vehicle/brakesetting.h +++ b/vehicle/brakesetting.h @@ -11,6 +11,8 @@ http://mozilla.org/MPL/2.0/. #include +#include "vehicle/driverorders.h" + class TMoverParameters; // the brake setting (G/P/R/Mg) the virtual wagon inspector (TController::AutoRewident) chooses for every @@ -63,7 +65,7 @@ std::vector choose(std::vector const &Consist, bool Train); // the AI runs the consist as a train, rather than shunting it: Obey_train, or Bank, which it drives as a // train run too (with the braking of a train). Orders is the order of the AI (TOrders) -bool runs_as_train(int Orders); +bool runs_as_train(DriverOrders Orders); // the AI has the inspector look at its train (TController::AutoRewident(): the brake settings, and the hand and // spring brakes of the train released) under the orders it drives the train under: shunting, loose shunting, the @@ -72,7 +74,7 @@ bool runs_as_train(int Orders); // (CheckVehicles(Connect)); Connect doesn't count for it, so the wagons just coupled keep their hand brakes until // the order after the coupling looks at the new train, as before: those of them to be left standing again // (Shunt x,-y) stay braked. Orders is the order of the AI (TOrders) -bool inspects_train(int Orders, bool Coupled); +bool inspects_train(DriverOrders Orders, bool Coupled); // the train stands for the inspector: slower than the AI takes for a deliberate movement (EU07_AI_MOVEMENT). // the AI looks at the train while it still creeps to a stop (at a W4, or switching from shunting to the train diff --git a/vehicle/driverorders.h b/vehicle/driverorders.h new file mode 100644 index 000000000..4dffb2229 --- /dev/null +++ b/vehicle/driverorders.h @@ -0,0 +1,49 @@ +/* +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 orders of the AI driver: a temporary operation (preparing the engine, changing the direction, coupling) and the +// way it drives (shunting, a train run), which an order can carry together (changeDirection on top of shunt) + +#pragma once + +#include "utilities/enumset.h" + +enum class DriverOrder : unsigned +{ + waitForOrders = 0, // czekanie na dostarczenie następnych rozkazów + // operacje tymczasowe + prepareEngine = 1 << 0, // włączenie silnika + releaseEngine = 1 << 1, // wyłączenie silnika + changeDirection = 1 << 2, // zmiana kierunku (bez skanowania sygnalizacji) + connect = 1 << 3, // podłączanie wagonów (z częściowym skanowaniem sygnalizacji) + disconnect = 1 << 4, // odłączanie wagonów (bez skanowania sygnalizacji) + // jazda + shunt = 1 << 5, // tryb manewrowy + looseShunt = 1 << 6, // coupling-free shunting mode + obeyTrain = 1 << 7, // tryb pociągowy + bank = 1 << 8, // assist mode + // others + jumpToFirstOrder = 1 << 9, // zapętlenie do pierwszej pozycji +}; +template <> struct IsEnumSetKind : std::true_type +{ +}; +using DriverOrders = EnumSet; + +// the orders the old numbers of which were from shunt up (32): they move the train, by a way of driving or the jump +inline constexpr DriverOrders movingOrders{DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank | + DriverOrder::jumpToFirstOrder}; +// the orders the old numbers of which were from obeyTrain up (128): the train runs, not shunting +inline constexpr DriverOrders trainOrders{DriverOrder::obeyTrain | DriverOrder::bank | DriverOrder::jumpToFirstOrder}; + +// the order as a single value, for a switch: a sum of several of them matches none of the cases +constexpr DriverOrder SingleOrder(DriverOrders const orders) +{ + return static_cast(orders.Bits()); +} From 10d9a4e3ac743259753b3b7bf92f09b5ea54c5dd Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sat, 28 Nov 2026 14:02:33 +0100 Subject: [PATCH 015/123] refactor(ai): the flags of the speed table are SpeedPointFlags, the route of a crossing a field of its own TSpeedPos::iFlags held what a position of the speed table of the AI is (a track, a switch, a signal, a stop...) as the low bits of an int, and the segment of a crossing the route takes in its top 4 bits, read back as iFlags >> 28, by the sign of iFlags and by an unsigned comparison with 0x10000000. - enum class SpeedPointFlag (enabled, track, reverse, switchTrack, switchState, elapsed, trackEnd, curve, event, shuntSignal, passengerStop, stopOnAutomaticBlock, commandSent, outsideStation, signal, roadSpeed, sectionSpeed, proximitySpeed, pointSpeed, roadSpeedHeld, signalAreaEnd) and SpeedPointFlags, an EnumSet of them, in TSpeedPos::flags - TSpeedPos::crossRoute, -8..7, the route through a crossing; ResetFlags() clears both, as iFlags = 0 did - LegacyFlagsValue() puts the two together as the number they were, for the two places which read it whole: the sign the scan of the route turns by, and the hex of the speed table in the log, which stays the same - the turn of a road vehicle at a crossing is judged as before, by the top bits without their sign: -1 (straight on) counts as turning, as it did. That looks wrong, but this change keeps it No change in behaviour: 1144/1144 tests, golden traces exact against staging 62f7a29b. --- vehicle/Driver.cpp | 271 +++++++++++++++++++++++---------------------- vehicle/Driver.h | 68 +++++++----- 2 files changed, 181 insertions(+), 158 deletions(-) diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 045de5ab0..a80db0498 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -201,7 +201,19 @@ std::string StopReasonTable[] = { //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- -TSpeedPos::TSpeedPos(TTrack *track, double dist, int flag) +namespace +{ + +// the low 4 bits of a number as a number -8..7, as the route of a crossing was read from the top of the flags +int signedNibble(unsigned const value) +{ + auto const nibble{static_cast(value & 0xf)}; + return nibble >= 8 ? nibble - 16 : nibble; +} + +} // namespace + +TSpeedPos::TSpeedPos(TTrack *track, double dist, SpeedPointFlags flag) { Set(track, dist, flag); }; @@ -213,7 +225,7 @@ TSpeedPos::TSpeedPos(basic_event *event, double dist, double length, DriverOrder void TSpeedPos::Clear() { - iFlags = 0; // brak flag to brak reakcji + ResetFlags(); // brak flag to brak reakcji fVelNext = -1.0; // prędkość bez ograniczeń fSectionVelocityDist = 0.0; //brak długości fPointDist = 0.0; @@ -229,14 +241,14 @@ void TSpeedPos::CommandCheck() double value1 = evEvent->input_value(1); double value2 = evEvent->input_value(2); // the point of a PointVelocity limit is taken anew from the current command - iFlags &= ~spPointVelocity; + flags = flags.Without(SpeedPointFlag::pointSpeed); fPointDist = 0.0; switch (command) { case TCommandType::cm_ShuntVelocity: // prędkość manewrową zapisać, najwyżej AI zignoruje przy analizie tabelki fVelNext = value1; // powinno być value2, bo druga określa "za"? - iFlags |= spShuntSemaphor; + flags |= SpeedPointFlag::shuntSignal; break; case TCommandType::cm_SetVelocity: // w semaforze typu "m" jest ShuntVelocity dla Ms2 i SetVelocity dla S1 @@ -245,36 +257,36 @@ void TSpeedPos::CommandCheck() // SetVelocity -1 100 -> można jechać, przy następnym ograniczenie (SBL) // SetVelocity 40 -1 -> PutValues: jechać 40 aż do minięcia (koniec ograniczenia( fVelNext = value1; - iFlags &= ~(spShuntSemaphor | spPassengerStopPoint | spStopOnSBL); - iFlags |= spSemaphor;// nie manewrowa, nie przystanek, nie zatrzymać na SBL, ale semafor + flags = flags.Without((SpeedPointFlag::shuntSignal | SpeedPointFlag::passengerStop | SpeedPointFlag::stopOnAutomaticBlock)); + flags |= SpeedPointFlag::signal;// nie manewrowa, nie przystanek, nie zatrzymać na SBL, ale semafor if (value1 == 0.0 && value2 != 0.0) // jeśli pierwsza zerowa // a druga nie { // S1 na SBL, można przejechać po zatrzymaniu (tu nie mamy prędkości ani odległości) fVelNext = value2; // normalnie będzie zezwolenie na jazdę, aby się usunął z tabelki - iFlags |= spStopOnSBL; // flaga, że ma zatrzymać; na pewno nie zezwoli na manewry + flags |= SpeedPointFlag::stopOnAutomaticBlock; // flaga, że ma zatrzymać; na pewno nie zezwoli na manewry } break; case TCommandType::cm_SectionVelocity: // odcinek z ograniczeniem prędkości fVelNext = value1; fSectionVelocityDist = value2; - iFlags |= spSectionVel; + flags |= SpeedPointFlag::sectionSpeed; break; case TCommandType::cm_RoadVelocity: // prędkość drogowa (od tej pory będzie jako domyślna najwyższa) fVelNext = value1; - iFlags |= spRoadVel; + flags |= SpeedPointFlag::roadSpeed; break; case TCommandType::cm_PassengerStopPoint: // nie ma dostępu do rozkładu // przystanek, najwyżej AI zignoruje przy analizie tabelki fVelNext = 0.0; - iFlags |= spPassengerStopPoint; // niestety nie da się w tym miejscu współpracować z rozkładem + flags |= SpeedPointFlag::passengerStop; // niestety nie da się w tym miejscu współpracować z rozkładem /* // NOTE: not used for now as it might be unnecessary // special case, potentially override any set speed limits if requested // NOTE: we test it here because for the time being it's only used for passenger stops - if( TestFlag( iFlags, spDontApplySpeedLimit ) ) { + if( flags.HasAll(spDontApplySpeedLimit) ) { fVelNext = -1; } */ @@ -282,7 +294,7 @@ void TSpeedPos::CommandCheck() case TCommandType::cm_SetProximityVelocity: // musi zostać gdyż inaczej nie działają manewry fVelNext = -1; - iFlags |= spProximityVelocity; + flags |= SpeedPointFlag::proximitySpeed; // fSectionVelocityDist = value2; break; case TCommandType::cm_PointVelocity: @@ -291,15 +303,15 @@ void TSpeedPos::CommandCheck() // what it says then holds for the point (the warning disc of a level crossing, Osp1/Osp2) fVelNext = value1; fPointDist = std::max( value2, 0.0 ); - iFlags &= ~(spShuntSemaphor | spPassengerStopPoint | spStopOnSBL | spSemaphor); // not a signal, even if the cell was one before - iFlags |= spPointVelocity; + flags = flags.Without((SpeedPointFlag::shuntSignal | SpeedPointFlag::passengerStop | SpeedPointFlag::stopOnAutomaticBlock | SpeedPointFlag::signal)); // not a signal, even if the cell was one before + flags |= SpeedPointFlag::pointSpeed; break; case TCommandType::cm_OutsideStation: // w trybie manewrowym: skanować od niej wstecz i stanąć po wyjechaniu za sygnalizator i // zmienić kierunek // w trybie pociągowym: można przyspieszyć do wskazanej prędkości (po zjechaniu z rozjazdów) fVelNext = -1; - iFlags |= spOutsideStation; // W5 + flags |= SpeedPointFlag::outsideStation; // W5 break; case TCommandType::cm_EmergencyBrake: fVelNext = -1; @@ -310,7 +322,7 @@ void TSpeedPos::CommandCheck() case TCommandType::cm_SignalAreaEnd: // imposes no speed of its own, it only ends the reduced speed of the signal passed last fVelNext = -1; - iFlags |= spSignalAreaEnd; + flags |= SpeedPointFlag::signalAreaEnd; break; default: // inna komenda w evencie skanowanym powoduje zatrzymanie i wysłanie tej komendy @@ -320,12 +332,12 @@ void TSpeedPos::CommandCheck() /* fVelNext = ( evEvent->is_command() ? 0.0 : // ask for a stop if we have a command for the vehicle - ( iFlags & ( spSemaphor | spShuntSemaphor )) != 0 ? fVelNext : // don't change semafor velocity + flags.HasAny(( spSemaphor | spShuntSemaphor )) ? fVelNext : // don't change semafor velocity -1.0 ); // otherwise don't be a bother */ // TODO: check whether clearing spShuntSemaphor flag doesn't cause problems // potentially it can invalidate shunt semaphor used to transmit timetable or similar command - iFlags &= ~(spShuntSemaphor | spPassengerStopPoint | spStopOnSBL); + flags = flags.Without((SpeedPointFlag::shuntSignal | SpeedPointFlag::passengerStop | SpeedPointFlag::stopOnAutomaticBlock)); } }; @@ -333,10 +345,10 @@ bool TSpeedPos::Update() { if( fDist < 0.0 ) { // trzeba zazanaczyć, że minięty - iFlags |= spElapsed; + flags |= SpeedPointFlag::elapsed; } bSeenAhead = signal_passing::seen_ahead_on_update( fDist, bSeenAhead ); - if (iFlags & spTrack) { + if (flags & SpeedPointFlag::track) { // road/track if (trTrack) { // może być NULL, jeśli koniec toru (???) @@ -344,12 +356,12 @@ bool TSpeedPos::Update() if( trTrack->iCategoryFlag & 1 ) { // railways - if( iFlags & spSwitch && (trTrack->GetSwitchState() & 1) != 0 != ((iFlags & spSwitchStatus) != 0) ) { + if( flags & SpeedPointFlag::switchTrack && (trTrack->GetSwitchState() & 1) != 0 != (flags.HasAny(SpeedPointFlag::switchState)) ) { // jeśli odcinek zmienny // czy stan się zmienił? // Ra: zakładam, że są tylko 2 możliwe stany - iFlags ^= spSwitchStatus; - if ((iFlags & spElapsed) == 0) + flags ^= SpeedPointFlag::switchState; + if (false == flags.HasAny(SpeedPointFlag::elapsed)) { // jeszcze trzeba skanowanie wykonać od tego toru // problem jest chyba, jeśli zwrotnica się przełoży zaraz po zjechaniu z niej @@ -360,7 +372,7 @@ bool TSpeedPos::Update() } else { // roads and others - if( iFlags & 0xF0000000 && (iFlags & 0xF0000000) > 0x10000000 ) { + if( crossRoute != 0 && crossRoute != 1 ) { // as the top 4 bits read without the sign: -1 counts as turning // jeśli skrzyżowanie, ograniczyć prędkość przy skręcaniu // ±1 to jazda na wprost, ±2 nieby też, ale z przecięciem głównej drogi - chyba że jest równorzędne... // TODO: uzależnić prędkość od promienia; @@ -370,7 +382,7 @@ bool TSpeedPos::Update() } } } - else if (iFlags & spEvent && ((iFlags & spElapsed) == 0 || fVelNext == 0.0)) { + else if (flags & SpeedPointFlag::event && (false == flags.HasAny(SpeedPointFlag::elapsed) || fVelNext == 0.0)) { // jeśli event // ignore already passed signals, but keep an eye on overrun stops // (a PointVelocity cell is latched when the head passes it, except at 0, which has to be released by the cell) @@ -383,9 +395,9 @@ bool TSpeedPos::Update() std::string TSpeedPos::GetName() const { - if( iFlags & spTrack ) // jeśli tor + if( flags & SpeedPointFlag::track ) // jeśli tor return trTrack->name(); - else if( iFlags & spEvent ) // jeśli event + else if( flags & SpeedPointFlag::event ) // jeśli event return evEvent->m_name + " [" + std::to_string( static_cast( evEvent->input_value( 1 ) ) ) @@ -397,9 +409,9 @@ std::string TSpeedPos::GetName() const std::string TSpeedPos::TableText() const { // pozycja tabelki pr?dko?ci - if (iFlags & spEnabled) + if (flags & SpeedPointFlag::enabled) { // o ile pozycja istotna - return to_hex_str(iFlags, 8) + " " + to_string(fDist, 1, 6) + + return to_hex_str(LegacyFlagsValue(), 8) + " " + to_string(fDist, 1, 6) + " " + (fVelNext == -1.0 ? " -" : to_string(static_cast(fVelNext), 0, 3)) + " " + GetName(); } return "Empty"; @@ -409,12 +421,12 @@ bool TSpeedPos::IsProperSemaphor(DriverOrders order) { // sprawdzenie czy semafor jest zgodny z trybem jazdy if (false == order.HasAny(trainOrders)) // Wait_for_orders, Prepare_engine, Change_direction, Connect, Disconnect, Shunt { - if (iFlags & (spSemaphor | spShuntSemaphor)) + if (flags & (SpeedPointFlag::signal | SpeedPointFlag::shuntSignal)) return true; - else if (iFlags & spOutsideStation) + else if (flags & SpeedPointFlag::outsideStation) return true; } - else if (order & DriverOrder::obeyTrain && iFlags & spSemaphor) + else if (order & DriverOrder::obeyTrain && flags & SpeedPointFlag::signal) { return true; } @@ -429,7 +441,8 @@ bool TSpeedPos::Set(basic_event *event, double dist, double length, DriverOrders // little behind the head still counts as seen ahead. a standing train passes nothing: an event found behind its // head counts only once an update finds it ahead bSeenAhead = signal_passing::seen_ahead_when_found( dist, Standing ); - iFlags = spEvent; + flags = SpeedPointFlag::event; + crossRoute = 0; evEvent = event; vPos = event->input_location(); // współrzędne eventu albo komórki pamięci (zrzutować na tor?) // ignore events located behind the consist, but with exception of stop points which may be needed to update freshly received timetable @@ -437,43 +450,44 @@ bool TSpeedPos::Set(basic_event *event, double dist, double length, DriverOrders && event->input_command() != TCommandType::cm_PassengerStopPoint ) { return false; } - iFlags |= spEnabled; + flags |= SpeedPointFlag::enabled; CommandCheck(); // sprawdzenie typu komendy w evencie i określenie prędkości // zależnie od trybu sprawdzenie czy jest tutaj gdzieś semafor lub tarcza manewrowa // jeśli wskazuje stop wtedy wystawiamy true jako koniec sprawdzania - // WriteLog("EventSet: Vel=" + AnsiString(fVelNext) + " iFlags=" + AnsiString(iFlags) + " order="+AnsiString(order)); + // WriteLog("EventSet: Vel=" + AnsiString(fVelNext) + " flags=" + AnsiString(flags) + " order="+AnsiString(order)); if (false == order.HasAny(trainOrders)) // Wait_for_orders, Prepare_engine, Change_direction, Connect, Disconnect, Shunt { - if (iFlags & (spSemaphor | spShuntSemaphor) && fVelNext == 0.0) + if (flags & (SpeedPointFlag::signal | SpeedPointFlag::shuntSignal) && fVelNext == 0.0) return true; - else if (iFlags & spOutsideStation) + else if (flags & SpeedPointFlag::outsideStation) return true; } - else if (order & DriverOrder::obeyTrain && iFlags & spSemaphor && fVelNext == 0.0) + else if (order & DriverOrder::obeyTrain && flags & SpeedPointFlag::signal && fVelNext == 0.0) { return true; } return false; // true gdy zatrzymanie, wtedy nie ma po co skanować dalej }; -void TSpeedPos::Set(TTrack *track, double dist, int flag) +void TSpeedPos::Set(TTrack *track, double dist, SpeedPointFlags flag) { // zapamiętanie zmiany prędkości w torze fDist = dist; // odległość do początku toru trTrack = track; // TODO: (t) może być NULL i nie odczytamy końca poprzedniego :/ if (trTrack) { - iFlags = flag | (trTrack->eType == tt_Normal ? spTrack : spTrack | spSwitch ); // zapamiętanie kierunku wraz z typem - if (iFlags & spSwitch && trTrack->GetSwitchState() & 1) - iFlags |= spSwitchStatus; + crossRoute = 0; + flags = flag | (trTrack->eType == tt_Normal ? SpeedPointFlag::track : SpeedPointFlag::track | SpeedPointFlag::switchTrack ); // zapamiętanie kierunku wraz z typem + if (flags & SpeedPointFlag::switchTrack && trTrack->GetSwitchState() & 1) + flags |= SpeedPointFlag::switchState; fVelNext = trTrack->VelocityGet(); if (trTrack->iDamageFlag & 128) fVelNext = 0.0; // jeśli uszkodzony, to też stój - if (iFlags & spEnd) + if (flags & SpeedPointFlag::trackEnd) fVelNext = trTrack->iCategoryFlag & 1 ? 0.0 : 20.0; // jeśli koniec, to pociąg stój, a samochód zwolnij vPos = - iFlags & spReverse ? + flags & SpeedPointFlag::reverse ? trTrack->CurrentSegment()->FastGetPoint_1() : trTrack->CurrentSegment()->FastGetPoint_0(); } @@ -520,7 +534,7 @@ bool TController::TableNotFound(basic_event const *Event, double const Distance sSpeedTable.begin(), sSpeedTable.end(), [Event]( TSpeedPos const &speedpoint ){ - return true == TestFlag(speedpoint.iFlags, spEnabled | spEvent) && speedpoint.evEvent == Event; } ); + return true == speedpoint.flags.HasAll(SpeedPointFlag::enabled | SpeedPointFlag::event) && speedpoint.evEvent == Event; } ); if (Global.iWriteLogEnabled & 8 && lookup != sSpeedTable.end() ) { @@ -600,12 +614,12 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) // znaleziono semafor lub tarczę lub tor z prędkością zero, trzeba sprawdzić czy to nadał semafor // jeśli jest następny semafor to sprawdzamy czy to on nadał zero if( OrderCurrentGet() & DriverOrder::obeyTrain - && sSpeedTable[SemNextStopIndex].iFlags & spSemaphor ) { + && sSpeedTable[SemNextStopIndex].flags & SpeedPointFlag::signal ) { return; } else { if( false == OrderCurrentGet().HasAny(trainOrders) - && sSpeedTable[SemNextStopIndex].iFlags & (spSemaphor | spShuntSemaphor | spOutsideStation) ) { + && sSpeedTable[SemNextStopIndex].flags & (SpeedPointFlag::signal | SpeedPointFlag::shuntSignal | SpeedPointFlag::outsideStation) ) { return; } } @@ -615,7 +629,7 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) pTrack = lastspeedpoint.trTrack; assert( pTrack != nullptr ); // flaga ustawiona, gdy Point2 toru jest blizej - fLastDir = (lastspeedpoint.iFlags & spReverse) != 0 ? -1.0 : 1.0; + fLastDir = lastspeedpoint.flags.HasAny(SpeedPointFlag::reverse) ? -1.0 : 1.0; fCurrentDistance = lastspeedpoint.fDist; // aktualna odleglosc do jego Point1 fTrackLength = pTrack->Length(); } @@ -692,7 +706,7 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) TableAddNew(); sSpeedTable[ iLast ].Set( pTrack, fCurrentDistance, - fLastDir < 0 ? spEnabled | spReverse : spEnabled ); // dodanie odcinka do tabelki z flagą kierunku wejścia + fLastDir < 0 ? SpeedPointFlag::enabled | SpeedPointFlag::reverse : SpeedPointFlag::enabled ); // dodanie odcinka do tabelki z flagą kierunku wejścia if (pTrack->eType == tt_Cross) { // na skrzyżowaniach trzeba wybrać segment, po którym pojedzie pojazd // dopiero tutaj jest ustalany kierunek segmentu na skrzyżowaniu @@ -710,19 +724,16 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) } */ auto const routewanted { pTrack->RouteDraw() }; - sSpeedTable[iLast].iFlags |= - (pTrack->CrossSegment(fLastDir < 0 ? tLast->iPrevDirection : tLast->iNextDirection, + sSpeedTable[iLast].crossRoute = signedNibble( ( static_cast( sSpeedTable[iLast].crossRoute ) | static_cast( pTrack->CrossSegment(fLastDir < 0 ? tLast->iPrevDirection : tLast->iNextDirection, /* iRouteWanted ) */ - routewanted) & - 0xf) - << 28; // ostatnie 4 bity pola flag - sSpeedTable[iLast].iFlags &= ~spReverse; // usunięcie flagi kierunku, bo może być błędna - if (sSpeedTable[iLast].iFlags < 0) { - sSpeedTable[iLast].iFlags |= spReverse; // ustawienie flagi kierunku na podstawie wybranego segmentu + routewanted) ) ) & 0xf ); // ostatnie 4 bity pola flag + sSpeedTable[iLast].flags = sSpeedTable[iLast].flags.Without(SpeedPointFlag::reverse); // usunięcie flagi kierunku, bo może być błędna + if (sSpeedTable[iLast].crossRoute < 0) { + sSpeedTable[iLast].flags |= SpeedPointFlag::reverse; // ustawienie flagi kierunku na podstawie wybranego segmentu } - if (int(fLastDir) * sSpeedTable[iLast].iFlags < 0) { + if (int(fLastDir) * sSpeedTable[iLast].LegacyFlagsValue() < 0) { fLastDir = -fLastDir; } /* @@ -738,7 +749,7 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) TableAddNew()) // koniec łuku też jest istotny { // albo dla liczenia odległości przy pomocy cięciw - te usuwać po przejechaniu // dodanie odcinka do tabelki - sSpeedTable[iLast].Set(pTrack, fCurrentDistance, fLastDir < 0 ? spEnabled | spCurve | spReverse : spEnabled | spCurve); + sSpeedTable[iLast].Set(pTrack, fCurrentDistance, fLastDir < 0 ? SpeedPointFlag::enabled | SpeedPointFlag::curve | SpeedPointFlag::reverse : SpeedPointFlag::enabled | SpeedPointFlag::curve); } } @@ -746,7 +757,7 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) tLast = pTrack; // odhaczenie, że sprawdzony fLastVel = pTrack->VelocityGet(); // prędkość na poprzednio sprawdzonym odcinku pTrack = pTrack->Connected( - pTrack->eType == tt_Cross ? sSpeedTable[iLast].iFlags >> 28 : static_cast(fLastDir), + pTrack->eType == tt_Cross ? sSpeedTable[iLast].crossRoute : static_cast(fLastDir), fLastDir); // może być NULL if (pTrack != nullptr ) @@ -756,7 +767,7 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) if (iLast != -1 && sSpeedTable[iLast].trTrack == tLast) { // if the track is already in the table we only need to mark it as relevant - sSpeedTable[iLast].iFlags |= spEnabled; + sSpeedTable[iLast].flags |= SpeedPointFlag::enabled; } else { @@ -764,7 +775,7 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) TableAddNew(); sSpeedTable[iLast].Set(tLast, fCurrentDistance - fTrackLength, // by now the current distance points to beginning of next track - (fLastDir > 0 ? pTrack->iPrevDirection : pTrack->iNextDirection) ? spEnabled : spEnabled | spReverse); + (fLastDir > 0 ? pTrack->iPrevDirection : pTrack->iNextDirection) ? SpeedPointFlag::enabled : SpeedPointFlag::enabled | SpeedPointFlag::reverse); } } // zwiększenie skanowanej odległości tylko jeśli istnieje dalszy tor @@ -773,21 +784,21 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) else { // definitywny koniec skanowania, chyba że dalej puszczamy samochód po gruncie... if( iLast == -1 - || ( false == TestFlag(sSpeedTable[iLast].iFlags, spEnabled | spEnd) + || ( false == sSpeedTable[iLast].flags.HasAll(SpeedPointFlag::enabled | SpeedPointFlag::trackEnd) && sSpeedTable[iLast].trTrack != tLast ) ) { // only if we haven't already marked end of the track and if the new track doesn't duplicate last one if( TableAddNew() ) { // zapisanie ostatniego sprawdzonego toru sSpeedTable[iLast].Set( tLast, fCurrentDistance - fTrackLength, // by now the current distance points to beginning of next track, - fLastDir < 0 ? spEnabled | spEnd | spReverse : spEnabled | spEnd); + fLastDir < 0 ? SpeedPointFlag::enabled | SpeedPointFlag::trackEnd | SpeedPointFlag::reverse : SpeedPointFlag::enabled | SpeedPointFlag::trackEnd); } } else if( sSpeedTable[iLast].trTrack == tLast && false == TestFlag(sSpeedTable[iLast].trTrack->iCategoryFlag, 0x100) ) { // otherwise just mark the last added track as the final one // TODO: investigate exactly how we can wind up not marking the last existing track as actual end // don't mark portals, as these aren't exactly track ends, but teleport devices - sSpeedTable[iLast].iFlags |= spEnabled | spEnd; + sSpeedTable[iLast].flags |= SpeedPointFlag::enabled | SpeedPointFlag::trackEnd; } // to ostatnia pozycja, bo NULL nic nie da, a może się podpiąć obrotnica, czy jakieś transportery return; @@ -797,7 +808,7 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) // zapisanie ostatniego sprawdzonego toru sSpeedTable[ iLast ].Set( pTrack, fCurrentDistance, - fLastDir < 0 ? spNone | spReverse : spNone ); + fLastDir < 0 ? SpeedPointFlag::none | SpeedPointFlag::reverse : SpeedPointFlag::none ); } }; @@ -818,9 +829,9 @@ void TController::TableCheck(double fDistance) MoveDistanceReset(); // kasowanie odległości po aktualizacji tabelki for( int i = 0; i < iLast; ++i ) { // aktualizacja rekordów z wyjątkiem ostatniego - if (sSpeedTable[i].iFlags & spEnabled) // jeśli pozycja istotna + if (sSpeedTable[i].flags & SpeedPointFlag::enabled) // jeśli pozycja istotna { - auto const passedbefore { TestFlag( sSpeedTable[ i ].iFlags, spElapsed ) }; + auto const passedbefore { sSpeedTable[ i ].flags.HasAll(SpeedPointFlag::elapsed) }; if (sSpeedTable[i].Update()) { if( Global.iWriteLogEnabled & 8 ) { @@ -849,30 +860,30 @@ void TController::TableCheck(double fDistance) } // a switch is a track, the update of a signal never ends the loop above CheckSignalPassed( sSpeedTable[ i ], passedbefore ); - if (sSpeedTable[i].iFlags & spTrack) // jeśli odcinek + if (sSpeedTable[i].flags & SpeedPointFlag::track) // jeśli odcinek { if( sSpeedTable[ i ].fDist + sSpeedTable[ i ].trTrack->Length() < -fLength ) // a skład wyjechał całą długością poza { // degradacja pozycji - sSpeedTable[i].iFlags &= ~spEnabled; // nie liczy się + sSpeedTable[i].flags = sSpeedTable[i].flags.Without(SpeedPointFlag::enabled); // nie liczy się } - else if( (sSpeedTable[i].iFlags & 0xF0000028) == spElapsed && sSpeedTable[i].fVelNext < 0 ) { + else if( sSpeedTable[i].crossRoute == 0 && ( sSpeedTable[i].flags & ( SpeedPointFlag::elapsed | SpeedPointFlag::switchTrack ) ) == SpeedPointFlag::elapsed && sSpeedTable[i].fVelNext < 0 ) { // jest z tyłu (najechany) i nie jest zwrotnicą ani skrzyżowaniem // a nie ma ograniczenia prędkości - sSpeedTable[i].iFlags = 0; // to nie ma go po co trzymać (odtykacz usunie ze środka) + sSpeedTable[i].ResetFlags(); // to nie ma go po co trzymać (odtykacz usunie ze środka) } } - else if (sSpeedTable[i].iFlags & spEvent && (sSpeedTable[i].iFlags & spPointVelocity) == 0 && sSpeedTable[i].fDist < (typeid(*sSpeedTable[i].evEvent) == typeid(putvalues_event) ? -fLength : 0) && mvOccupied->CategoryFlag == 2 && + else if (sSpeedTable[i].flags & SpeedPointFlag::event && false == sSpeedTable[i].flags.HasAny(SpeedPointFlag::pointSpeed) && sSpeedTable[i].fDist < (typeid(*sSpeedTable[i].evEvent) == typeid(putvalues_event) ? -fLength : 0) && mvOccupied->CategoryFlag == 2 && sSpeedTable[i].fDist < -0.75) // jeśli event { // jeśli jest z tyłu // pociąg staje zawsze, a samochód tylko jeśli nie przejedzie całą długością (może być zaskoczony zmianą) // WriteLog("TableCheck: Event is behind. Delete from table: " + sSpeedTable[i].evEvent->asName); - sSpeedTable[i].iFlags &= ~spEnabled; // degradacja pozycji dla samochodu; + sSpeedTable[i].flags = sSpeedTable[i].flags.Without(SpeedPointFlag::enabled); // degradacja pozycji dla samochodu; // semafory usuwane tylko przy sprawdzaniu, bo wysyłają komendy } } } - auto const lastpassedbefore { TestFlag( sSpeedTable[ iLast ].iFlags, spElapsed ) }; + auto const lastpassedbefore { sSpeedTable[ iLast ].flags.HasAll(SpeedPointFlag::elapsed) }; sSpeedTable[iLast].Update(); // aktualizacja ostatniego // a signal at stop often is the last, the scan doesn't go past it CheckSignalPassed( sSpeedTable[ iLast ], lastpassedbefore ); @@ -891,16 +902,16 @@ namespace { // the position is a signal showing stop (SetVelocity 0 0). SetVelocity 0 x on automatic block isn't: it may be passed after a stop bool is_signal_at_stop( TSpeedPos const &Point ) { - return TestFlag( Point.iFlags, spEvent ) - && TestFlag( Point.iFlags, spSemaphor ) - && false == TestFlag( Point.iFlags, spStopOnSBL ) + return Point.flags.HasAll(SpeedPointFlag::event) + && Point.flags.HasAll(SpeedPointFlag::signal) + && false == Point.flags.HasAll(SpeedPointFlag::stopOnAutomaticBlock) && std::abs( Point.fVelNext ) <= 0.0 && Point.evEvent != nullptr; } void clear_signal_area_end( TSpeedPos &Point ) { - if( TestFlag( Point.iFlags, spSignalAreaEnd ) ) { + if( Point.flags.HasAll(SpeedPointFlag::signalAreaEnd) ) { Point.Clear(); } } @@ -909,8 +920,8 @@ void clear_signal_area_end( TSpeedPos &Point ) // set speed limits by the track, and the flags they get don't make them signals bool is_signal( TSpeedPos const &Point ) { - return TestFlag( Point.iFlags, spEvent ) - && ( TestFlag( Point.iFlags, spSemaphor ) || TestFlag( Point.iFlags, spShuntSemaphor ) ) + return Point.flags.HasAll(SpeedPointFlag::event) + && ( Point.flags.HasAll(SpeedPointFlag::signal) || Point.flags.HasAll(SpeedPointFlag::shuntSignal) ) && Point.evEvent != nullptr && typeid( *Point.evEvent ) == typeid( getvalues_event ); } @@ -918,13 +929,13 @@ bool is_signal( TSpeedPos const &Point ) std::uint8_t passing_flags_of( TSpeedPos const &Point, double const Speedatsignal, bool const Trainmovement ) { std::uint8_t flags { 0 }; - auto const shunting { TestFlag( Point.iFlags, spShuntSemaphor ) }; + auto const shunting { Point.flags.HasAll(SpeedPointFlag::shuntSignal) }; if( shunting ) { flags |= blackbox::passing_flags::shunt; } // the speeds of the aspects are whole km/h, -1 for no limit; a shunting signal binds only the shunting if( std::abs( Speedatsignal ) < 0.5 && ( false == shunting || false == Trainmovement ) ) { - flags |= ( TestFlag( Point.iFlags, spStopOnSBL ) ? blackbox::passing_flags::automatic_block : blackbox::passing_flags::at_stop ); + flags |= ( Point.flags.HasAll(SpeedPointFlag::stopOnAutomaticBlock) ? blackbox::passing_flags::automatic_block : blackbox::passing_flags::at_stop ); } return flags; } @@ -934,7 +945,7 @@ std::uint8_t passing_flags_of( TSpeedPos const &Point, double const Speedatsigna void TController::CheckSignalPassed( TSpeedPos const &Point, bool const Passedbefore ) const { // not bSeenAhead: found already behind the head, the train stood across it or past it, it didn't pass it - if( false == signal_passing::passed_now( Passedbefore, TestFlag( Point.iFlags, spElapsed ), Point.bSeenAhead ) + if( false == signal_passing::passed_now( Passedbefore, Point.flags.HasAll(SpeedPointFlag::elapsed), Point.bSeenAhead ) || ( mvOccupied->CategoryFlag & 1 ) == 0 ) { // railway only return; } @@ -945,7 +956,7 @@ void TController::CheckSignalPassed( TSpeedPos const &Point, bool const Passedbe // the aspect the train had of it: the table keeps it once the signal is behind, while the memory cell // may already show stop for the train itself, past the signal on the track it guards. the stop of an // automatic block signal is kept as the speed allowed after it, with a flag of its own - auto const speedatsignal { TestFlag( Point.iFlags, spStopOnSBL ) ? 0.0 : Point.fVelNext }; + auto const speedatsignal { Point.flags.HasAll(SpeedPointFlag::stopOnAutomaticBlock) ? 0.0 : Point.fVelNext }; simulation::Blackbox.signal_passed( pVehicles[ end::front ], *Point.evEvent, speedatsignal, Point.evEvent->input_value( 2 ), @@ -1022,40 +1033,40 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN for( std::size_t idx = 0; idx < sSpeedTable.size(); ++idx ) { // o ile dana pozycja tabelki jest istotna - if( ( sSpeedTable[ idx ].iFlags & spEnabled ) == 0 ) { continue; } + if( false == sSpeedTable[ idx ].flags.HasAny(SpeedPointFlag::enabled) ) { continue; } auto &point { sSpeedTable[ idx ] }; - if( TestFlag( point.iFlags, spPassengerStopPoint ) ) { + if( point.flags.HasAll(SpeedPointFlag::passengerStop) ) { if( TableUpdateStopPoint( go, point, d_to_next_sem ) ) { continue; }; } v = point.fVelNext; // odczyt prędkości do zmiennej pomocniczej - if( TestFlag( point.iFlags, spSwitch ) ) { + if( point.flags.HasAll(SpeedPointFlag::switchTrack) ) { // zwrotnice są usuwane z tabelki dopiero po zjechaniu z nich drivingFlags.switchFound = true; // rozjazd z przodu/pod ogranicza np. sens skanowania wstecz SwitchClearDist = point.fDist + point.trTrack->Length() + fLength; } - else if ( TestFlag(point.iFlags, spEvent) && TableUpdateEvent(v, go, point, d_to_next_sem, idx) ) // W4 może się deaktywować + else if ( point.flags.HasAll(SpeedPointFlag::event) && TableUpdateEvent(v, go, point, d_to_next_sem, idx) ) // W4 może się deaktywować { // jeżeli event, może być potrzeba wysłania komendy, aby ruszył continue; } - auto const railwaytrackend { true == TestFlag(point.iFlags, spEnd) && is_train() }; + auto const railwaytrackend { true == point.flags.HasAll(SpeedPointFlag::trackEnd) && is_train() }; if( v >= 0.0 // pozycje z prędkością -1 można spokojnie pomijać || railwaytrackend ) { // a PointVelocity limit lies fPointDist beyond its entry and stays ahead of us until the head passes it - auto const ispointlimit { TestFlag( point.iFlags, spPointVelocity ) }; + auto const ispointlimit { point.flags.HasAll(SpeedPointFlag::pointSpeed) }; d = point.fDist + point.fPointDist; if( v >= 0.0 ) { // points located in front of us can potentially affect our acceleration and target speed if( d > 0.0 - && ( false == TestFlag(point.iFlags, spElapsed) || ispointlimit ) ) { + && ( false == point.flags.HasAll(SpeedPointFlag::elapsed) || ispointlimit ) ) { // sygnał lub ograniczenie z przodu (+32=przejechane) // 2014-02: jeśli stoi, a ma do przejechania kawałek, to niech jedzie if( mvOccupied->Vel < 0.01 - && true == TestFlag(point.iFlags, spEnabled | spEvent | spPassengerStopPoint) + && true == point.flags.HasAll(SpeedPointFlag::enabled | SpeedPointFlag::event | SpeedPointFlag::passengerStop) && false == IsAtPassengerStop ) { // ma podjechać bliżej - czy na pewno w tym miejscu taki warunek? a = d > passengerstopmaxdistance || drivingFlags.stopCloser ? fAcc : 0.0; @@ -1083,7 +1094,7 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN } } // points located behind can affect our current speed, but little else - else if ( point.iFlags & spTrack) // jeśli tor + else if ( point.flags & SpeedPointFlag::track) // jeśli tor { // tor ogranicza prędkość, dopóki cały skład nie przejedzie, if( v >= 1.0 && d + point.trTrack->Length() < -fLength && false == railwaytrackend ) { // EU06 się zawieszało po dojechaniu na koniec toru postojowego // zapętlenie, jeśli już wyjechał za ten odcinek @@ -1096,7 +1107,7 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN if( v < VelLimitLastDist.first ) { VelLimitLastDist.second = d + point.trTrack->Length() + fLength; } - else if( VelLimitLastDist.second > 0 && (point.iFlags & (spSwitch | spPassengerStopPoint)) == 0 ) { // the speed limit can potentially start afterwards, so don't mark it as broken too soon + else if( VelLimitLastDist.second > 0 && false == point.flags.HasAny((SpeedPointFlag::switchTrack | SpeedPointFlag::passengerStop)) ) { // the speed limit can potentially start afterwards, so don't mark it as broken too soon speedlimitiscontinuous = false; } if( false == railwaytrackend ) { @@ -1136,7 +1147,7 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN fAcc = a; // zalecane przyspieszenie (nie musi być uwzględniane przez AI) fNext = v; // istotna jest prędkość na końcu tego odcinka fDist = d; // dlugość odcinka - bStopTargetIsPassengerStop = ( v == 0.0 ) && ( ( point.iFlags & spPassengerStopPoint ) != 0 ); + bStopTargetIsPassengerStop = ( v == 0.0 ) && ( point.flags.HasAny(SpeedPointFlag::passengerStop) ); } /* else if ((fAcc > 0) && (v >= 0) && (v > fNext)) { @@ -1151,7 +1162,7 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN fAcc = a; fNext = v; fDist = d; - bStopTargetIsPassengerStop = ( v == 0.0 ) && ( ( point.iFlags & spPassengerStopPoint ) != 0 ); + bStopTargetIsPassengerStop = ( v == 0.0 ) && ( point.flags.HasAny(SpeedPointFlag::passengerStop) ); } // potentially update our current speed limit // a point limit binds only the head at its point, it neither extends nor breaks a limit over a stretch of the line @@ -1160,11 +1171,11 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN && ( d < 0 // the point counts as part of last speed limit either if it's behind us || VelLimitLastDist.second > 0 ) ) { // or if we already have the last limit ongoing VelLimitLastDist.second = d + fLength; - if( ( point.iFlags & spTrack ) != 0 ) { + if( point.flags.HasAny(SpeedPointFlag::track) ) { VelLimitLastDist.second += point.trTrack->Length(); } } - else if( ( point.iFlags & ( spSwitch | spPassengerStopPoint | spPointVelocity ) ) == 0 ) { + else if( false == point.flags.HasAny(( SpeedPointFlag::switchTrack | SpeedPointFlag::passengerStop | SpeedPointFlag::pointSpeed )) ) { // if we found a point which isn't part of the current speed limit mark the limit as broken // NOTE: we exclude switches from this rule, as speed limits generally extend through these speedlimitiscontinuous = false; @@ -1172,14 +1183,14 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN } // if (v>=0.0) // finding a point which doesn't impose speed limit means any potential active speed limit can't extend through entire scan table // NOTE: we test actual speed value for the given point, as events may receive (v = -1) as a way to disable them in irrelevant modes - if( point.fVelNext < 0 && (point.iFlags & (spSwitch | spPassengerStopPoint | spPointVelocity)) == 0 ) { + if( point.fVelNext < 0 && false == point.flags.HasAny((SpeedPointFlag::switchTrack | SpeedPointFlag::passengerStop | SpeedPointFlag::pointSpeed)) ) { // NOTE: we exclude switches from this rule, as speed limits generally extend through these // and point limits, which say nothing of the line they lie on speedlimitiscontinuous = false; } if (fNext >= 0.0) { // jeśli ograniczenie - if( (point.iFlags & (spEnabled | spEvent)) == (spEnabled | spEvent) && (point.iFlags & spPointVelocity) == 0 && eSignNext == nullptr ) { // tylko sygnał przypisujemy (a point limit isn't one) + if( (point.flags & (SpeedPointFlag::enabled | SpeedPointFlag::event)) == (SpeedPointFlag::enabled | SpeedPointFlag::event) && false == point.flags.HasAny(SpeedPointFlag::pointSpeed) && eSignNext == nullptr ) { // tylko sygnał przypisujemy (a point limit isn't one) // jeśli jeszcze nic nie zapisane tam eSignNext = point.evEvent; // dla informacji } @@ -1249,7 +1260,7 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub } else if( Point.fDist < -fLength ) { // jeśli został przejechany - Point.iFlags = 0; // to można usunąć (nie mogą być usuwane w skanowaniu) + Point.ResetFlags(); // to można usunąć (nie mogą być usuwane w skanowaniu) } return true; // ignorowanie jakby nie było tej pozycji } @@ -1289,7 +1300,7 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub UpdateDelayFlag(); TrainParams.StationIndexInc(); // przejście do następnej asNextStop = TrainParams.NextStop(); // pobranie kolejnego miejsca zatrzymania - Point.iFlags = 0; // nie liczy się już + Point.ResetFlags(); // nie liczy się już return true; // table entry recognized and handled } } // koniec obsługi przelotu na W4 @@ -1330,14 +1341,14 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub Point.fMoved = L; } else { - Point.iFlags = 0; + Point.ResetFlags(); } } // for human-driven vehicles discard the stop point if they leave it far enough behind if( false == AIControllFlag && Point.fDist < -1 * std::max(fLength + 100, 250.0) - Point.fMoved ) { record_station( Point, blackbox::station_kinds::missed ); - Point.iFlags = 0; // nie liczy się już zupełnie (nie wyśle SetVelocity) + Point.ResetFlags(); // nie liczy się już zupełnie (nie wyśle SetVelocity) Point.fVelNext = -1; // można jechać za W4 if( Point.fDist <= 0.0 && eSignNext == Point.evEvent ) { // sanity check, if we're held by this stop point, let us go @@ -1427,7 +1438,7 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub // ma nie podjeżdżać pod W4 po przeciwnej stronie drivingFlags.stopCloser = false; // ten W4 nie liczy się już zupełnie (nie wyśle SetVelocity) - Point.iFlags = 0; + Point.ResetFlags(); // jechać Point.fVelNext = -1; // nie analizować prędkości @@ -1471,7 +1482,7 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub drivingFlags.stopHere = false; } drivingFlags.stopCloser = true; // do następnego W4 podjechać blisko (z dociąganiem) - Point.iFlags = 0; // nie liczy się już zupełnie (nie wyśle SetVelocity) + Point.ResetFlags(); // nie liczy się już zupełnie (nie wyśle SetVelocity) Point.fVelNext = -1; // można jechać za W4 if( Point.fDist <= 0.0 && eSignNext == Point.evEvent ) { // sanity check, if we're held by this stop point, let us go @@ -1516,7 +1527,7 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub drivingFlags.stopPoint = false; } fLastStopExpDist = -1.0f; // nie ma rozkładu, nie ma usuwania stacji - Point.iFlags = 0; // W4 nie liczy się już (nie wyśle SetVelocity) + Point.ResetFlags(); // W4 nie liczy się już (nie wyśle SetVelocity) Point.fVelNext = -1; // można jechać za W4 if( Point.fDist <= 0.0 && eSignNext == Point.evEvent ) { // sanity check, if we're held by this stop point, let us go @@ -1538,7 +1549,7 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub } // koniec warunku pomijania W4 podczas zmiany czoła else { // skoro pomijanie, to jechać i ignorować W4 - Point.iFlags = 0; // W4 nie liczy się już (nie zatrzymuje jazdy) + Point.ResetFlags(); // W4 nie liczy się już (nie zatrzymuje jazdy) Point.fVelNext = -1; return true; // nie analizować prędkości } @@ -1551,7 +1562,7 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub bool TController::is_road_velocity_held( TSpeedPos const &Point ) const { - return TestFlag( Point.iFlags, spRoadVel ) + return Point.flags.HasAll(SpeedPointFlag::roadSpeed) && mvOccupied->CategoryFlag != 2 && Point.fDist >= -fLength; } @@ -1561,7 +1572,7 @@ void TController::TableDropPassedEvent( TSpeedPos &Point ) const { if( is_road_velocity_held( Point ) ) { - Point.iFlags |= spRoadVelHeld; + Point.flags |= SpeedPointFlag::roadSpeedHeld; return; } Point.Clear(); @@ -1574,7 +1585,7 @@ TController::held_road_velocity_beyond( TSpeedPos const &Point ) const { auto lowest { -1.0 }; for( auto const &held : sSpeedTable ) { - if( ( held.iFlags & ( spEnabled | spRoadVel ) ) != ( spEnabled | spRoadVel ) + if( ( held.flags & ( SpeedPointFlag::enabled | SpeedPointFlag::roadSpeed ) ) != ( SpeedPointFlag::enabled | SpeedPointFlag::roadSpeed ) || held.fDist >= 0.0 || held.fDist <= Point.fDist ) { continue; @@ -1606,7 +1617,7 @@ TController::TableUpdateRoadVelocity( TSpeedPos &Point ) { else if( Point.fVelNext == min_speed( Point.fVelNext, VelRoad ) ) { VelRoad = Point.fVelNext; } - if( false == TestFlag( Point.iFlags, spRoadVelHeld ) ) { + if( false == Point.flags.HasAll(SpeedPointFlag::roadSpeedHeld) ) { return false; } if( isrearpast ) { @@ -1763,7 +1774,7 @@ void TController::update_point_limits() { sSpeedTable.begin(), sSpeedTable.end(), [&]( TSpeedPos const &Point ) { return Point.evEvent == Limit.source - && TestFlag( Point.iFlags, spEnabled | spEvent | spPointVelocity ) + && Point.flags.HasAll(SpeedPointFlag::enabled | SpeedPointFlag::event | SpeedPointFlag::pointSpeed) && Point.fDist > 0.0; } ); } ); } @@ -1819,13 +1830,13 @@ glm::dvec3 TController::travel_direction() const { bool TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPos &Point, double &Signaldistance, int const Pointindex ) { - if( TestFlag( Point.iFlags, spSignalAreaEnd ) ) { + if( Point.flags.HasAll(SpeedPointFlag::signalAreaEnd) ) { // not a signal: it neither sends a command nor counts as the end of a speed limit in the scan TableUpdateSignalAreaEnd( Point ); return true; } - if( TestFlag( Point.iFlags, spPointVelocity ) ) { + if( Point.flags.HasAll(SpeedPointFlag::pointSpeed) ) { // PointVelocity: no signal, no command, only the limit at its point // done once the head passes the point if( Point.fDist + Point.fPointDist < 0.0 ) { @@ -1938,7 +1949,7 @@ TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPo } } } - if (Point.iFlags & spOutsideStation) + if (Point.flags & SpeedPointFlag::outsideStation) { // jeśli W5, to reakcja zależna od trybu jazdy if (OrderCurrentGet() & DriverOrder::obeyTrain) { // w trybie pociągowym: można przyspieszyć do wskazanej prędkości (po zjechaniu z rozjazdów) @@ -1969,7 +1980,7 @@ TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPo } } } - else if ( Point.iFlags & spStopOnSBL) { + else if ( Point.flags & SpeedPointFlag::stopOnAutomaticBlock) { // jeśli S1 na SBL if( mvOccupied->Vel < 2.0 && Point.fDist < fMaxProximityDist && Obstacle.distance > 1000 ) { // stanąć nie musi, ale zwolnić przynajmniej @@ -2029,13 +2040,13 @@ TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPo } } } - else if ( Point.iFlags & spRoadVel) + else if ( Point.flags & SpeedPointFlag::roadSpeed) { // to W27/W27a if( TableUpdateRoadVelocity( Point ) ) { return true; } } - else if ( Point.iFlags & spSectionVel && Point.fDist < 0) + else if ( Point.flags & SpeedPointFlag::sectionSpeed && Point.fDist < 0) { // to W9 // teraz trzeba sprawdzić inne warunki if (Point.fSectionVelocityDist == 0.0) @@ -2091,13 +2102,13 @@ TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPo //sprawdzenie eventów pasywnych przed nami { // zawalidrogi nie ma (albo pojazd jest samochodem), sprawdzić sygnał - if ( Point.iFlags & spShuntSemaphor) // jeśli Tm - w zasadzie to sprawdzić komendę! + if ( Point.flags & SpeedPointFlag::shuntSignal) // jeśli Tm - w zasadzie to sprawdzić komendę! { // jeśli podana prędkość manewrowa if( Velocity == 0.0 && true == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { // jeśli tryb pociągowy a tarcze ma ShuntVelocity 0 0 Velocity = -1; // ignorować, chyba że prędkość stanie się niezerowa - if( true == TestFlag( Point.iFlags, spElapsed ) ) { + if( true == Point.flags.HasAll(SpeedPointFlag::elapsed) ) { // a jak przejechana to można usunąć, bo podstawowy automat usuwa tylko niezerowe Point.Clear(); } @@ -2123,7 +2134,7 @@ TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPo } } } - else if( ( Point.iFlags & spSectionVel ) == 0 ) { + else if( false == Point.flags.HasAny(SpeedPointFlag::sectionSpeed) ) { //jeśli jakiś event pasywny ale nie ograniczenie if( Command != TCommandType::cm_Unknown ) { @@ -2147,7 +2158,7 @@ TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPo // jeśli przejechany VelSignal = Velocity == 0.0 ? 0.0 : -1.0; // ustawienie, gdy przejechany jest lepsze niż wcale, ale to jeszcze nie to - if (Point.iFlags & spEvent && (Point.evEvent != eSignSkip || Point.fVelNext != VelRestricted)) + if (Point.flags & SpeedPointFlag::event && (Point.evEvent != eSignSkip || Point.fVelNext != VelRestricted)) { // jeśli event // ale inny niż ten, na którym minięto S1, chyba że się już zmieniło @@ -2233,8 +2244,8 @@ void TController::TablePurger() // simplest approach should be good enough for start -- just copy whatever is still relevant, then swap auto const isexpendable = []( TSpeedPos const &Speedpoint ) { return - 0 == ( Speedpoint.iFlags & spEnabled ) - || ( ( Speedpoint.iFlags & ( spElapsed | spTrack | spCurve | spSwitch ) ) == ( spElapsed | spTrack | spCurve ) + false == Speedpoint.flags.HasAny( SpeedPointFlag::enabled ) + || ( ( Speedpoint.flags & ( SpeedPointFlag::elapsed | SpeedPointFlag::track | SpeedPointFlag::curve | SpeedPointFlag::switchTrack ) ) == ( SpeedPointFlag::elapsed | SpeedPointFlag::track | SpeedPointFlag::curve ) && Speedpoint.fVelNext < 0.0 ); }; // do a trial run first, to see if we need to bother at all std::size_t trimcount{ 0 }; @@ -6531,10 +6542,10 @@ int TController::CrossRoute(TTrack *tr) { // trzeba przejrzeć tabelę skanowania w poszukiwaniu (tr) // i jak się znajdzie, to zwrócić zapamiętany numer segmentu i kierunek przejazdu // (-6..-1,1..6) - if( true == TestFlag(sSpeedTable[i].iFlags, spEnabled | spTrack) + if( true == sSpeedTable[i].flags.HasAll(SpeedPointFlag::enabled | SpeedPointFlag::track) && sSpeedTable[i].trTrack == tr ) { // jeśli pozycja odpowiadająca skrzyżowaniu (tr) - return sSpeedTable[i].iFlags >> 28; // najstarsze 4 bity jako liczba -8..7 + return sSpeedTable[i].crossRoute; // -8..7 } } return 0; // nic nie znaleziono? @@ -6550,9 +6561,9 @@ void TController::RouteSwitch(int d) // jeśli samochód for( std::size_t i = 0; i < sSpeedTable.size(); ++i ) { // szukanie pierwszego skrzyżowania i resetowanie kierunku na nim - if( true == TestFlag( sSpeedTable[ i ].iFlags, spEnabled | spTrack ) ) { + if( true == sSpeedTable[ i ].flags.HasAll(spEnabled | spTrack) ) { // jeśli pozycja istotna (1) oraz odcinek (2) - if( false == TestFlag( sSpeedTable[ i ].iFlags, spElapsed ) ) { + if( false == sSpeedTable[ i ].flags.HasAll(spElapsed) ) { // odcinek nie może być miniętym if( sSpeedTable[ i ].trTrack->eType == tt_Cross ) // jeśli skrzyżowanie { diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 773c608e2..7ce8c1cf1 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -117,32 +117,36 @@ enum class TAction : int actTrial // próba hamulca (na postoju) }; -enum TSpeedPosFlag -{ // wartości dla iFlag w TSpeedPos - spNone = 0x0, - spEnabled = 0x1, // pozycja brana pod uwagę - spTrack = 0x2, // to jest tor - spReverse = 0x4, // odwrotnie - spSwitch = 0x8, // to zwrotnica - spSwitchStatus = 0x10, // stan zwrotnicy - spElapsed = 0x20, // pozycja minięta przez pojazd - spEnd = 0x40, // koniec - spCurve = 0x80, // łuk - spEvent = 0x100, // event - spShuntSemaphor = 0x200, // tarcza manewrowa - spPassengerStopPoint = 0x400, // przystanek osobowy (wskaźnik W4) - spStopOnSBL = 0x800, // zatrzymanie na SBL - spCommandSent = 0x1000, // komenda wysłana - spOutsideStation = 0x2000, // wskaźnik końca manewrów - spSemaphor = 0x4000, // semafor pociągowy - spRoadVel = 0x8000, // zadanie prędkości drogowej - spSectionVel = 0x20000, // odcinek z ograniczeniem - spProximityVelocity = 0x40000, // odcinek z ograniczeniem i podaną jego długościa - spPointVelocity = 0x80000, // ograniczenie dla czoła w punkcie fPointDist za wpisem (PointVelocity) - spRoadVelHeld = 0x100000, // a road speed sign passed by the head, handled, kept until the rear is past it - spSignalAreaEnd = 0x200000 // end of the interlocking area of the signal passed last -// spDontApplySpeedLimit = 0x10000 // this point won't apply its speed limit. potentially set by the scanning vehicle +// what a position of the speed table of the AI is and what became of it +enum class SpeedPointFlag : unsigned +{ + none = 0x0, + enabled = 0x1, // pozycja brana pod uwagę + track = 0x2, // to jest tor + reverse = 0x4, // odwrotnie + switchTrack = 0x8, // to zwrotnica + switchState = 0x10, // stan zwrotnicy + elapsed = 0x20, // pozycja minięta przez pojazd + trackEnd = 0x40, // koniec + curve = 0x80, // łuk + event = 0x100, // event + shuntSignal = 0x200, // tarcza manewrowa + passengerStop = 0x400, // przystanek osobowy (wskaźnik W4) + stopOnAutomaticBlock = 0x800, // zatrzymanie na SBL + commandSent = 0x1000, // komenda wysłana + outsideStation = 0x2000, // wskaźnik końca manewrów + signal = 0x4000, // semafor pociągowy + roadSpeed = 0x8000, // zadanie prędkości drogowej + sectionSpeed = 0x20000, // odcinek z ograniczeniem + proximitySpeed = 0x40000, // odcinek z ograniczeniem i podaną jego długością + pointSpeed = 0x80000, // ograniczenie dla czoła w punkcie fPointDist za wpisem (PointVelocity) + roadSpeedHeld = 0x100000, // a road speed sign passed by the head, handled, kept until the rear is past it + signalAreaEnd = 0x200000, // end of the interlocking area of the signal passed last }; +template <> struct IsEnumSetKind : std::true_type +{ +}; +using SpeedPointFlags = EnumSet; class TSpeedPos { // pozycja tabeli prędkości dla AI @@ -151,7 +155,8 @@ class TSpeedPos double fVelNext{ -1.0 }; // prędkość obowiązująca od tego miejsca double fSectionVelocityDist{ 0.0 }; // długość ograniczenia prędkości double fPointDist{ 0.0 }; // PointVelocity: o ile dalej od wpisu leży punkt, w którym czoło ma mieć fVelNext - int iFlags{ spNone }; // flagi typu wpisu do tabelki + SpeedPointFlags flags; // flagi typu wpisu do tabelki + int crossRoute{ 0 }; // the segment of a crossing the route takes, -8..7, the sign the direction (in the top 4 bits of the flags before) bool bMoved{ false }; // czy przesunięty (dotyczy punktu zatrzymania w peronie) double fMoved{ 0.0 }; // ile przesunięty (dotyczy punktu zatrzymania w peronie) bool bSeenAhead{ false }; // the head of the train had it ahead once: only such a point can be passed by the train @@ -162,9 +167,16 @@ class TSpeedPos basic_event *evEvent{ nullptr }; // połączenie z eventem albo komórką pamięci }; void CommandCheck(); + // the flags and the route as the one number they were before: the scan of the route reads its sign, the table its hex + int LegacyFlagsValue() const { + return static_cast( ( static_cast( crossRoute ) << 28 ) | static_cast( flags.Bits() ) ); } + // no flags and no route: the position doesn't count any more + void ResetFlags() { + flags = {}; + crossRoute = 0; } public: - TSpeedPos(TTrack *track, double dist, int flag); + TSpeedPos(TTrack *track, double dist, SpeedPointFlags flag); TSpeedPos(basic_event *event, double dist, double length, DriverOrders order); TSpeedPos() = default; void Clear(); @@ -176,7 +188,7 @@ class TSpeedPos fDist -= dist; } // Standing: the train stands, so an event found behind its head wasn't passed by it bool Set(basic_event *e, double d, double length, DriverOrders order = DriverOrder::waitForOrders, bool Standing = false); - void Set(TTrack *t, double d, int f); + void Set(TTrack *t, double d, SpeedPointFlags f); std::string TableText() const; std::string GetName() const; bool IsProperSemaphor(DriverOrders order = DriverOrder::waitForOrders); From 601d4a3bb996550394c384682f8960fd75236526 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sat, 28 Nov 2026 14:21:41 +0100 Subject: [PATCH 016/123] refactor(ai): vehicle/Driver.cpp split into the files of its parts in vehicle/ai/ The 9 700 lines of the AI driver go into vehicle/ai/, a file for each part of what it does, from 76 to 1340 lines: driver.cpp construction, the update, taking over, what it tells speedpos.cpp a position of the speed table routescan.cpp scanning the route ahead, the signals passed speedtable.cpp what the positions ask of the driver: stops, limits, signals orders.cpp the orders and the commands of the scenery consist.cpp the consist: its vehicles, direction, brakes, the cab engine.cpp preparing and shutting down the vehicle controls.cpp the controllers and the brake handles doors.cpp the doors, the stops and the departure obstacles.cpp the obstacles and the signals behind and ahead situation.cpp what the driver keeps an eye on speed.cpp the speed it aims for force.cpp the traction and the brakes it applies physicslog.cpp the log of the physics Every definition moved as it was, in its original order. The constants and the helpers used by several files (EasyReactionTime, PrepareTime, brake_response_horizon, uphill_stopping_distance) and the LOG* switches are in vehicle/ai/internal.h. The default argument of IsOccupiedByAnotherConsist() moved from its definition to its declaration, where the other files see it. `git blame -C -C` follows the lines into the new files. 1144/1144 tests, golden traces exact against staging 62f7a29b. --- CMakeLists.txt | 18 +- vehicle/Driver.cpp | 9724 ------------------------------------- vehicle/Driver.h | 2 +- vehicle/ai/consist.cpp | 966 ++++ vehicle/ai/controls.cpp | 1390 ++++++ vehicle/ai/doors.cpp | 294 ++ vehicle/ai/driver.cpp | 599 +++ vehicle/ai/engine.cpp | 449 ++ vehicle/ai/force.cpp | 783 +++ vehicle/ai/internal.h | 115 + vehicle/ai/obstacles.cpp | 496 ++ vehicle/ai/orders.cpp | 1246 +++++ vehicle/ai/physicslog.cpp | 125 + vehicle/ai/routescan.cpp | 625 +++ vehicle/ai/situation.cpp | 730 +++ vehicle/ai/speed.cpp | 907 ++++ vehicle/ai/speedpos.cpp | 329 ++ vehicle/ai/speedtable.cpp | 1362 ++++++ 18 files changed, 10433 insertions(+), 9727 deletions(-) delete mode 100644 vehicle/Driver.cpp create mode 100644 vehicle/ai/consist.cpp create mode 100644 vehicle/ai/controls.cpp create mode 100644 vehicle/ai/doors.cpp create mode 100644 vehicle/ai/driver.cpp create mode 100644 vehicle/ai/engine.cpp create mode 100644 vehicle/ai/force.cpp create mode 100644 vehicle/ai/internal.h create mode 100644 vehicle/ai/obstacles.cpp create mode 100644 vehicle/ai/orders.cpp create mode 100644 vehicle/ai/physicslog.cpp create mode 100644 vehicle/ai/routescan.cpp create mode 100644 vehicle/ai/situation.cpp create mode 100644 vehicle/ai/speed.cpp create mode 100644 vehicle/ai/speedpos.cpp create mode 100644 vehicle/ai/speedtable.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index eecd0f45b..bed372327 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -80,7 +80,8 @@ file(GLOB HEADERS "*.h" "model/*.h" "utilities/*.h" "world/*.h" -"vehicle/*.h") +"vehicle/*.h" +"vehicle/ai/*.h") set(GLOBAL_ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}") set(GLOBAL_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/global_include") @@ -170,7 +171,20 @@ set(SOURCES "model/AnimModel.cpp" "vehicle/Button.cpp" "vehicle/Camera.cpp" -"vehicle/Driver.cpp" +"vehicle/ai/consist.cpp" +"vehicle/ai/controls.cpp" +"vehicle/ai/doors.cpp" +"vehicle/ai/driver.cpp" +"vehicle/ai/engine.cpp" +"vehicle/ai/force.cpp" +"vehicle/ai/obstacles.cpp" +"vehicle/ai/orders.cpp" +"vehicle/ai/physicslog.cpp" +"vehicle/ai/routescan.cpp" +"vehicle/ai/situation.cpp" +"vehicle/ai/speed.cpp" +"vehicle/ai/speedpos.cpp" +"vehicle/ai/speedtable.cpp" "vehicle/crewchange.cpp" "application/driverhints.cpp" "vehicle/DynObj.cpp" diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp deleted file mode 100644 index a80db0498..000000000 --- a/vehicle/Driver.cpp +++ /dev/null @@ -1,9724 +0,0 @@ -/* -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/. -*/ -/* - MaSzyna EU07 locomotive simulator - Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others - -*/ - -#include "stdafx.h" -#include "vehicle/Driver.h" -#include "physics/mover.h" - -#include "utilities/Globals.h" -#include "utilities/translation.h" -#include "utilities/Logs.h" -#include "utilities/physicslog.h" -#include "vehicle/Train.h" -#include "vehicle/brakereleaser.h" -#include "vehicle/brakesetting.h" -#include "vehicle/brakingcurve.h" -#include "vehicle/fieldshunting.h" -#include "vehicle/handover.h" -#include "vehicle/signalpassing.h" -#include "vehicle/timetableservice.h" -#include "world/mtable.h" -#include "world/stationnames.h" -#include "vehicle/DynObj.h" -#include "world/Event.h" -#include "world/MemCell.h" -#include "world/RoadOrder.h" -#include "simulation/simulation.h" -#include "simulation/blackboxrecorder.h" -#include "simulation/simulationtime.h" -#include "simulation/simulationtest.h" -#include "world/Track.h" -#include "world/station.h" -#include "input/keyboardinput.h" - -#include -#include -#include - -#define LOGVELOCITY 0 -#define LOGORDERS 1 -#define LOGSTOPS 1 -#define LOGBACKSCAN 0 -#define LOGPRESS 0 - -// finds point of specified track nearest to specified event. returns: distance to that point from the specified end of the track -// TODO: move this to file with all generic routines, too easy to forget it's here and it may come useful -double -ProjectEventOnTrack( basic_event const *Event, TTrack const *Track, double const Direction ) { - - auto const segment = Track->CurrentSegment(); - auto const nearestpoint = segment->find_nearest_point( Event->input_location() ); - return Direction > 0 ? nearestpoint * segment->GetLength() : // measure from point1 - (1.0 - nearestpoint) * segment->GetLength(); // measure from point2 -}; - -double GetDistanceToEvent(TTrack const *track, basic_event const *event, double scan_dir, double start_dist, int iter = 0, bool back = false) -{ - if( track == nullptr ) { return start_dist; } - - auto const segment = track->CurrentSegment(); - auto const pos_event = event->input_location(); - double len1, len2; - double sd = scan_dir; - double seg_len = scan_dir > 0 ? 0.0 : 1.0; - double const dzielnik = 1.0 / segment->GetLength();// rozdzielczosc mniej wiecej 1m - int krok = 0; // krok obliczeniowy do sprawdzania czy odwracamy - len2 = glm::length2(pos_event - segment->FastGetPoint(seg_len)); - do - { - len1 = len2; - seg_len += scan_dir > 0 ? dzielnik : -dzielnik; - len2 = glm::length2(pos_event - segment->FastGetPoint(seg_len)); - ++krok; - } while (len1 > len2 && seg_len >= dzielnik && seg_len <= 1.0 - dzielnik); - //trzeba sprawdzić czy seg_len nie osiągnął skrajnych wartości, bo wtedy - // trzeba sprawdzić tor obok - if (1 == krok) - sd = -sd; // jeśli tylko jeden krok tzn, że event przy poprzednim sprawdzaym torze - if ((1 == krok || seg_len <= dzielnik || seg_len > 1.0 - dzielnik) && iter < 3) - { // przejście na inny tor - track = track->Connected(int(sd), sd); - start_dist += 1 == krok ? 0 : back ? -segment->GetLength() : segment->GetLength(); - if( track != nullptr - && track->eType == tt_Cross ) { - // NOTE: tracing through crossroads currently poses risk of tracing through wrong segment - // as it's possible to be performerd before setting a route through the crossroads - // as a stop-gap measure we don't trace through crossroads which should be reasonable in most cases - // TODO: establish route before the scan, or a way for the function to know which route to pick - return start_dist; - } - else { - return GetDistanceToEvent( track, event, sd, start_dist, ++iter, 1 == krok ? true : false ); - } - } - else - { // obliczenie mojego toru - seg_len -= scan_dir > 0 ? dzielnik : -dzielnik; //trzeba wrócić do pozycji len1 - seg_len = scan_dir < 0 ? 1 - seg_len : seg_len; - seg_len = back ? 1 - seg_len : seg_len; // odwracamy jeśli idzie do tyłu - start_dist -= back ? segment->GetLength() : 0; - return start_dist + segment->GetLength() * seg_len; - } -}; - -/* - -Moduł obsługujący sterowanie pojazdami (składami pociągów, samochodami). -Ma działać zarówno jako AI oraz przy prowadzeniu przez człowieka. W tym -drugim przypadku jedynie informuje za pomocą napisów o tym, co by zrobił -w tym pierwszym. Obejmuje zarówno maszynistę jak i kierownika pociągu -(dawanie sygnału do odjazdu). - -Przeniesiona tutaj została zawartość ai_driver.pas przerobiona na C++. -Również niektóre funkcje dotyczące składów z DynObj.cpp. - -Teoria jest wtedy kiedy wszystko wiemy, ale nic nie działa. -Praktyka jest wtedy, kiedy wszystko działa, ale nikt nie wie dlaczego. -Tutaj łączymy teorię z praktyką - tu nic nie działa i nikt nie wie dlaczego… - -*/ - -// zrobione: -// 0. pobieranie komend z dwoma parametrami -// 1. przyspieszanie do zadanej predkosci, ew. hamowanie jesli przekroczona -// 2. hamowanie na zadanym odcinku do zadanej predkosci (ze stabilizacja przyspieszenia) -// 3. wychodzenie z sytuacji awaryjnych: bezpiecznik nadmiarowy, poslizg -// 4. przygotowanie pojazdu do drogi, zmiana kierunku ruchu -// 5. dwa sposoby jazdy - manewrowy i pociagowy -// 6. dwa zestawy psychiki: spokojny i agresywny -// 7. przejscie na zestaw spokojny jesli wystepuje duzo poslizgow lub wybic nadmiarowego. -// 8. lagodne ruszanie (przedluzony czas reakcji na 2 pierwszych nastawnikach) -// 9. unikanie jazdy na oporach rozruchowych -// 10. logowanie fizyki //Ra: nie przeniesione do C++ -// 11. kasowanie czuwaka/SHP -// 12. procedury wspomagajace "patrzenie" na odlegle semafory -// 13. ulepszone procedury sterowania -// 14. zglaszanie problemow z dlugim staniem na sygnale S1 -// 15. sterowanie EN57 -// 16. zmiana kierunku //Ra: z przesiadką po ukrotnieniu -// 17. otwieranie/zamykanie drzwi -// 18. Ra: odczepianie z zahamowaniem i podczepianie -// 19. dla Humandriver: tasma szybkosciomierza - zapis do pliku! -// 20. wybór pozycji zaworu maszynisty w oparciu o zadane opoznienie hamowania - - -// do zrobienia: -// 1. kierownik pociagu -// 2. madrzejsze unikanie grzania oporow rozruchowych i silnika -// 3. unikanie szarpniec, zerwania pociagu itp -// 4. obsluga innych awarii -// 5. raportowanie problemow, usterek nie do rozwiazania -// 7. samouczacy sie algorytm hamowania - -// stałe -const double EasyReactionTime = 0.5; //[s] przebłyski świadomości dla zwykłej jazdy -const double HardReactionTime = 0.2; -const double EasyAcceleration = 0.85; //[m/ss] -const double HardAcceleration = 9.81; -const double PassengetTrainAcceleration = 0.40; -const double HeavyPassengetTrainAcceleration = 0.20; -const double CargoTrainAcceleration = 0.25; -const double HeavyCargoTrainAcceleration = 0.10; -const double PrepareTime = 2.0; //[s] przebłyski świadomości przy odpalaniu -const double FSOverchargePipePress = 5.2; -const double FSOverchargeTime = 2.0; -const double FSOverchargeCRP = 0.05; -const double FSMaxTime = 10.0; -const double DepartBlockedFSDelay = 10.0; -bool WriteLogFlag = false; -bool WriteTrainLogFlag = false; -double const deltalog = 0.05; // przyrost czasu - -std::string StopReasonTable[] = { - // przyczyny zatrzymania ruchu AI - "", // stopNone, //nie ma powodu - powinien jechać - "Off", // stopSleep, //nie został odpalony, to nie pojedzie - "Semaphore", // stopSem, //semafor zamknięty - "Time", // stopTime, //czekanie na godzinę odjazdu - "End of track", // stopEnd, //brak dalszej części toru - "Change direction", // stopDir, //trzeba stanąć, by zmienić kierunek jazdy - "Joining", // stopJoin, //zatrzymanie przy (p)odczepianiu - "Block", // stopBlock, //przeszkoda na drodze ruchu - "A command", // stopComm, //otrzymano taką komendę (niewiadomego pochodzenia) - "Out of station", // stopOut, //komenda wyjazdu poza stację (raczej nie powinna zatrzymywać!) - "Radiostop", // stopRadio, //komunikat przekazany radiem (Radiostop) - "External", // stopExt, //przesłany z zewnątrz - "Error", // stopError //z powodu błędu w obliczeniu drogi hamowania -}; - -//--------------------------------------------------------------------------- -//--------------------------------------------------------------------------- -//--------------------------------------------------------------------------- - -namespace -{ - -// the low 4 bits of a number as a number -8..7, as the route of a crossing was read from the top of the flags -int signedNibble(unsigned const value) -{ - auto const nibble{static_cast(value & 0xf)}; - return nibble >= 8 ? nibble - 16 : nibble; -} - -} // namespace - -TSpeedPos::TSpeedPos(TTrack *track, double dist, SpeedPointFlags flag) -{ - Set(track, dist, flag); -}; - -TSpeedPos::TSpeedPos(basic_event *event, double dist, double length, DriverOrders order) -{ - Set(event, dist, length, order); -}; - -void TSpeedPos::Clear() -{ - ResetFlags(); // brak flag to brak reakcji - fVelNext = -1.0; // prędkość bez ograniczeń - fSectionVelocityDist = 0.0; //brak długości - fPointDist = 0.0; - fDist = 0.0; - bSeenAhead = false; - vPos = glm::dvec3(0, 0, 0); - trTrack = nullptr; // brak wskaźnika -}; - -void TSpeedPos::CommandCheck() -{ // sprawdzenie typu komendy w evencie i określenie prędkości - TCommandType command = evEvent->input_command(); - double value1 = evEvent->input_value(1); - double value2 = evEvent->input_value(2); - // the point of a PointVelocity limit is taken anew from the current command - flags = flags.Without(SpeedPointFlag::pointSpeed); - fPointDist = 0.0; - switch (command) - { - case TCommandType::cm_ShuntVelocity: - // prędkość manewrową zapisać, najwyżej AI zignoruje przy analizie tabelki - fVelNext = value1; // powinno być value2, bo druga określa "za"? - flags |= SpeedPointFlag::shuntSignal; - break; - case TCommandType::cm_SetVelocity: - // w semaforze typu "m" jest ShuntVelocity dla Ms2 i SetVelocity dla S1 - // SetVelocity * 0 -> można jechać, ale stanąć przed - // SetVelocity 0 20 -> stanąć przed, potem można jechać 20 (SBL) - // SetVelocity -1 100 -> można jechać, przy następnym ograniczenie (SBL) - // SetVelocity 40 -1 -> PutValues: jechać 40 aż do minięcia (koniec ograniczenia( - fVelNext = value1; - flags = flags.Without((SpeedPointFlag::shuntSignal | SpeedPointFlag::passengerStop | SpeedPointFlag::stopOnAutomaticBlock)); - flags |= SpeedPointFlag::signal;// nie manewrowa, nie przystanek, nie zatrzymać na SBL, ale semafor - if (value1 == 0.0 && value2 != 0.0) // jeśli pierwsza zerowa - // a druga nie - { // S1 na SBL, można przejechać po zatrzymaniu (tu nie mamy prędkości ani odległości) - fVelNext = value2; // normalnie będzie zezwolenie na jazdę, aby się usunął z tabelki - flags |= SpeedPointFlag::stopOnAutomaticBlock; // flaga, że ma zatrzymać; na pewno nie zezwoli na manewry - } - break; - case TCommandType::cm_SectionVelocity: - // odcinek z ograniczeniem prędkości - fVelNext = value1; - fSectionVelocityDist = value2; - flags |= SpeedPointFlag::sectionSpeed; - break; - case TCommandType::cm_RoadVelocity: - // prędkość drogowa (od tej pory będzie jako domyślna najwyższa) - fVelNext = value1; - flags |= SpeedPointFlag::roadSpeed; - break; - case TCommandType::cm_PassengerStopPoint: - // nie ma dostępu do rozkładu - // przystanek, najwyżej AI zignoruje przy analizie tabelki - fVelNext = 0.0; - flags |= SpeedPointFlag::passengerStop; // niestety nie da się w tym miejscu współpracować z rozkładem -/* - // NOTE: not used for now as it might be unnecessary - // special case, potentially override any set speed limits if requested - // NOTE: we test it here because for the time being it's only used for passenger stops - if( flags.HasAll(spDontApplySpeedLimit) ) { - fVelNext = -1; - } -*/ - break; - case TCommandType::cm_SetProximityVelocity: - // musi zostać gdyż inaczej nie działają manewry - fVelNext = -1; - flags |= SpeedPointFlag::proximitySpeed; - // fSectionVelocityDist = value2; - break; - case TCommandType::cm_PointVelocity: - // PointVelocity v d: the head has to be at v (-1: no limit) at the point d metres beyond the cell, - // the limit ends when the head passes that point. the cell is read until the head passes the cell, - // what it says then holds for the point (the warning disc of a level crossing, Osp1/Osp2) - fVelNext = value1; - fPointDist = std::max( value2, 0.0 ); - flags = flags.Without((SpeedPointFlag::shuntSignal | SpeedPointFlag::passengerStop | SpeedPointFlag::stopOnAutomaticBlock | SpeedPointFlag::signal)); // not a signal, even if the cell was one before - flags |= SpeedPointFlag::pointSpeed; - break; - case TCommandType::cm_OutsideStation: - // w trybie manewrowym: skanować od niej wstecz i stanąć po wyjechaniu za sygnalizator i - // zmienić kierunek - // w trybie pociągowym: można przyspieszyć do wskazanej prędkości (po zjechaniu z rozjazdów) - fVelNext = -1; - flags |= SpeedPointFlag::outsideStation; // W5 - break; - case TCommandType::cm_EmergencyBrake: - fVelNext = -1; - break; - case TCommandType::cm_SecuritySystemMagnet: - fVelNext = -1; - break; - case TCommandType::cm_SignalAreaEnd: - // imposes no speed of its own, it only ends the reduced speed of the signal passed last - fVelNext = -1; - flags |= SpeedPointFlag::signalAreaEnd; - break; - default: - // inna komenda w evencie skanowanym powoduje zatrzymanie i wysłanie tej komendy - // nie manewrowa, nie przystanek, nie zatrzymać na SBL - // jak nieznana komenda w komórce sygnałowej, to zatrzymujemy - fVelNext = 0.0; -/* - fVelNext = ( - evEvent->is_command() ? 0.0 : // ask for a stop if we have a command for the vehicle - flags.HasAny(( spSemaphor | spShuntSemaphor )) ? fVelNext : // don't change semafor velocity - -1.0 ); // otherwise don't be a bother -*/ - // TODO: check whether clearing spShuntSemaphor flag doesn't cause problems - // potentially it can invalidate shunt semaphor used to transmit timetable or similar command - flags = flags.Without((SpeedPointFlag::shuntSignal | SpeedPointFlag::passengerStop | SpeedPointFlag::stopOnAutomaticBlock)); - } -}; - -bool TSpeedPos::Update() -{ - if( fDist < 0.0 ) { - // trzeba zazanaczyć, że minięty - flags |= SpeedPointFlag::elapsed; - } - bSeenAhead = signal_passing::seen_ahead_on_update( fDist, bSeenAhead ); - if (flags & SpeedPointFlag::track) { - // road/track - if (trTrack) { - // może być NULL, jeśli koniec toru (???) - fVelNext = trTrack->VelocityGet(); // aktualizacja prędkości (może być zmieniana eventem) - - if( trTrack->iCategoryFlag & 1 ) { - // railways - if( flags & SpeedPointFlag::switchTrack && (trTrack->GetSwitchState() & 1) != 0 != (flags.HasAny(SpeedPointFlag::switchState)) ) { - // jeśli odcinek zmienny - // czy stan się zmienił? - // Ra: zakładam, że są tylko 2 możliwe stany - flags ^= SpeedPointFlag::switchState; - if (false == flags.HasAny(SpeedPointFlag::elapsed)) - { - // jeszcze trzeba skanowanie wykonać od tego toru - // problem jest chyba, jeśli zwrotnica się przełoży zaraz po zjechaniu z niej - // na Mydelniczce potrafi skanować na wprost mimo pojechania na bok - return true; - } - } - } - else { - // roads and others - if( crossRoute != 0 && crossRoute != 1 ) { // as the top 4 bits read without the sign: -1 counts as turning - // jeśli skrzyżowanie, ograniczyć prędkość przy skręcaniu - // ±1 to jazda na wprost, ±2 nieby też, ale z przecięciem głównej drogi - chyba że jest równorzędne... - // TODO: uzależnić prędkość od promienia; - // albo niech będzie ograniczona w skrzyżowaniu (velocity z ujemną wartością) - fVelNext = 30.0; - } - } - } - } - else if (flags & SpeedPointFlag::event && (false == flags.HasAny(SpeedPointFlag::elapsed) || fVelNext == 0.0)) { - // jeśli event - // ignore already passed signals, but keep an eye on overrun stops - // (a PointVelocity cell is latched when the head passes it, except at 0, which has to be released by the cell) - // odczyt komórki pamięci najlepiej by było zrobić jako notyfikację, - // czyli zmiana komórki wywoła jakąś podaną funkcję - CommandCheck(); // sprawdzenie typu komendy w evencie i określenie prędkości - } - return false; -}; - -std::string TSpeedPos::GetName() const -{ - if( flags & SpeedPointFlag::track ) // jeśli tor - return trTrack->name(); - else if( flags & SpeedPointFlag::event ) // jeśli event - return - evEvent->m_name - + " [" + std::to_string( static_cast( evEvent->input_value( 1 ) ) ) - + ", " + std::to_string( static_cast( evEvent->input_value( 2 ) ) ) - + "]"; - else - return ""; -} - -std::string TSpeedPos::TableText() const -{ // pozycja tabelki pr?dko?ci - if (flags & SpeedPointFlag::enabled) - { // o ile pozycja istotna - return to_hex_str(LegacyFlagsValue(), 8) + " " + to_string(fDist, 1, 6) + - " " + (fVelNext == -1.0 ? " -" : to_string(static_cast(fVelNext), 0, 3)) + " " + GetName(); - } - return "Empty"; -} - -bool TSpeedPos::IsProperSemaphor(DriverOrders order) -{ // sprawdzenie czy semafor jest zgodny z trybem jazdy - if (false == order.HasAny(trainOrders)) // Wait_for_orders, Prepare_engine, Change_direction, Connect, Disconnect, Shunt - { - if (flags & (SpeedPointFlag::signal | SpeedPointFlag::shuntSignal)) - return true; - else if (flags & SpeedPointFlag::outsideStation) - return true; - } - else if (order & DriverOrder::obeyTrain && flags & SpeedPointFlag::signal) - { - return true; - } - return false; // true gdy zatrzymanie, wtedy nie ma po co skanować dalej -} - -bool TSpeedPos::Set(basic_event *event, double dist, double length, DriverOrders order, bool const Standing) -{ // zapamiętanie zdarzenia - fDist = dist; - // an event already behind the head when found (under a train set across a signal) wasn't passed by it. a moving - // train may be just passing it, and the distance is found in steps of a metre, so for a moving train an event a - // little behind the head still counts as seen ahead. a standing train passes nothing: an event found behind its - // head counts only once an update finds it ahead - bSeenAhead = signal_passing::seen_ahead_when_found( dist, Standing ); - flags = SpeedPointFlag::event; - crossRoute = 0; - evEvent = event; - vPos = event->input_location(); // współrzędne eventu albo komórki pamięci (zrzutować na tor?) - // ignore events located behind the consist, but with exception of stop points which may be needed to update freshly received timetable - if( dist + length < 0 - && event->input_command() != TCommandType::cm_PassengerStopPoint ) { - return false; - } - flags |= SpeedPointFlag::enabled; - CommandCheck(); // sprawdzenie typu komendy w evencie i określenie prędkości - // zależnie od trybu sprawdzenie czy jest tutaj gdzieś semafor lub tarcza manewrowa - // jeśli wskazuje stop wtedy wystawiamy true jako koniec sprawdzania - // WriteLog("EventSet: Vel=" + AnsiString(fVelNext) + " flags=" + AnsiString(flags) + " order="+AnsiString(order)); - if (false == order.HasAny(trainOrders)) // Wait_for_orders, Prepare_engine, Change_direction, Connect, Disconnect, Shunt - { - if (flags & (SpeedPointFlag::signal | SpeedPointFlag::shuntSignal) && fVelNext == 0.0) - return true; - else if (flags & SpeedPointFlag::outsideStation) - return true; - } - else if (order & DriverOrder::obeyTrain && flags & SpeedPointFlag::signal && fVelNext == 0.0) - { - return true; - } - return false; // true gdy zatrzymanie, wtedy nie ma po co skanować dalej -}; - -void TSpeedPos::Set(TTrack *track, double dist, SpeedPointFlags flag) -{ // zapamiętanie zmiany prędkości w torze - fDist = dist; // odległość do początku toru - trTrack = track; // TODO: (t) może być NULL i nie odczytamy końca poprzedniego :/ - if (trTrack) - { - crossRoute = 0; - flags = flag | (trTrack->eType == tt_Normal ? SpeedPointFlag::track : SpeedPointFlag::track | SpeedPointFlag::switchTrack ); // zapamiętanie kierunku wraz z typem - if (flags & SpeedPointFlag::switchTrack && trTrack->GetSwitchState() & 1) - flags |= SpeedPointFlag::switchState; - fVelNext = trTrack->VelocityGet(); - if (trTrack->iDamageFlag & 128) - fVelNext = 0.0; // jeśli uszkodzony, to też stój - if (flags & SpeedPointFlag::trackEnd) - fVelNext = trTrack->iCategoryFlag & 1 ? - 0.0 : - 20.0; // jeśli koniec, to pociąg stój, a samochód zwolnij - vPos = - flags & SpeedPointFlag::reverse ? - trTrack->CurrentSegment()->FastGetPoint_1() : - trTrack->CurrentSegment()->FastGetPoint_0(); - } -}; - -//--------------------------------------------------------------------------- - -void TController::TableClear() -{ // wyczyszczenie tablicy - sSpeedTable.clear(); - iLast = -1; - iTableDirection = 0; // nieznany - tLast = nullptr; - fLastVel = -1.0; - SemNextIndex = npos; - SemNextStopIndex = npos; - eSignSkip = nullptr; // nic nie pomijamy -}; - -std::vector TController::CheckTrackEvent( TTrack *Track, double const fDirection ) const -{ // sprawdzanie eventów na podanym torze do podstawowego skanowania - std::vector events; - auto const &eventsequence { ( fDirection > 0 ? Track->m_events2 : Track->m_events1 ) }; - for( auto const &event : eventsequence ) { - if( event.second != nullptr - && event.second->m_passive ) { - events.emplace_back( event.second ); - } - } - return events; -} - -bool TController::TableAddNew() -{ // zwiększenie użytej tabelki o jeden rekord - sSpeedTable.emplace_back(); // add a new slot - iLast = sSpeedTable.size() - 1; - return true; // false gdy się nałoży -}; - -bool TController::TableNotFound(basic_event const *Event, double const Distance ) const -{ // sprawdzenie, czy nie został już dodany do tabelki (np. podwójne W4 robi problemy) - auto lookup = - std::find_if( - sSpeedTable.begin(), - sSpeedTable.end(), - [Event]( TSpeedPos const &speedpoint ){ - return true == speedpoint.flags.HasAll(SpeedPointFlag::enabled | SpeedPointFlag::event) && speedpoint.evEvent == Event; } ); - - if (Global.iWriteLogEnabled & 8 - && lookup != sSpeedTable.end() ) { - WriteLog( "Speed table for " + OwnerName() + " already contains event " + lookup->evEvent->m_name ); - } - - // ignore duplicates which seem to be reasonably apart from each other, on account of looping tracks - // NOTE: since supplied distance is only rough approximation of distance to the event, we're using large safety margin - return lookup == sSpeedTable.end() || Distance - lookup->fDist > 100.0; -}; - -void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) -{ // skanowanie trajektorii na odległość (fDistance) od (pVehicle) w kierunku przodu składu i - // uzupełnianie tabelki - // WriteLog("Starting TableTraceRoute"); - - TTrack *pTrack{ nullptr }; // zaczynamy od ostatniego analizowanego toru - double fTrackLength{ 0.0 }; // długość aktualnego toru (krótsza dla pierwszego) - double fCurrentDistance{ 0.0 }; // aktualna przeskanowana długość - double fLastDir{ 0.0 }; - - if (iTableDirection != iDirection ) { - // jeśli zmiana kierunku, zaczynamy od toru ze wskazanym pojazdem - TableClear(); -/* - // aktualna prędkość // changed to -1 to recognize speed limit, if any - fLastVel = -1.0; - sSpeedTable.clear(); - iLast = -1; - tLast = nullptr; //żaden nie sprawdzony - SemNextIndex = npos; - SemNextStopIndex = npos; -*/ - if( VelSignalLast == 0.0 ) { - // don't allow potential red light overrun keep us from reversing - VelSignalLast = -1.0; - } - iTableDirection = iDirection; // ustalenie w jakim kierunku jest wypełniana tabelka względem pojazdu - pTrack = pVehicle->GetTrack(); // odcinek, na którym stoi - fTrackLength = pVehicle->RaTranslationGet(); // pozycja na tym torze (odległość od Point1) - fLastDir = pVehicle->DirectionGet() * pVehicle->RaDirectionGet(); // ustalenie kierunku skanowania na torze - if( fLastDir < 0.0 ) { - // jeśli w kierunku Point2 toru - fTrackLength = pTrack->Length() - fTrackLength; // przeskanowana zostanie odległość do Point2 - } - // account for the fact tracing begins from active axle, not the actual front of the vehicle - // NOTE: position of the couplers is modified by track offset, but the axles ain't, so we need to account for this as well - fTrackLength -= glm::length( - pVehicle->AxlePositionGet() - - pVehicle->RearPosition() - + pVehicle->VectorLeft() * pVehicle->MoverParameters->OffsetTrackH ); - // aktualna odległość ma być ujemna gdyż jesteśmy na końcu składu - fCurrentDistance = -fLength - fTrackLength; - fTrackLength = pTrack->Length(); //skasowanie zmian w zmiennej żeby poprawnie liczyło w dalszych krokach - MoveDistanceReset(); // AI startuje 1s po zaczęciu jazdy i mógł już coś przejechać - } - else { - if( iTableDirection == 0 ) { return; } - // NOTE: belt and braces; TablePurger() used to leave these pointing past the end of the table. - // nothing is known to do that any more, so say so when it happens - auto const dropstaleindex = [this, fDistance]( std::size_t &Index, std::string_view const Name ) { - if( Index == npos - || Index < sSpeedTable.size() ) { - return; - } - ErrorLog( std::format( - "Speed table for {}: {} {} points past the end of the table ({} records), last track {} at {:.1f} m, scan range {:.1f} m; reset", - OwnerName(), Name, Index, sSpeedTable.size(), - ( iLast >= 0 && sSpeedTable[ iLast ].trTrack != nullptr ? sSpeedTable[ iLast ].trTrack->name() : "none" ), - ( iLast >= 0 ? sSpeedTable[ iLast ].fDist : 0.0 ), fDistance ) ); - Index = npos; }; - dropstaleindex( SemNextIndex, "SemNextIndex" ); - dropstaleindex( SemNextStopIndex, "SemNextStopIndex" ); - // kontynuacja skanowania od ostatnio sprawdzonego toru (w ostatniej pozycji zawsze jest tor) - if( SemNextStopIndex != npos - && sSpeedTable[SemNextStopIndex].fVelNext == 0.0 ) { - // znaleziono semafor lub tarczę lub tor z prędkością zero, trzeba sprawdzić czy to nadał semafor - // jeśli jest następny semafor to sprawdzamy czy to on nadał zero - if( OrderCurrentGet() & DriverOrder::obeyTrain - && sSpeedTable[SemNextStopIndex].flags & SpeedPointFlag::signal ) { - return; - } - else { - if( false == OrderCurrentGet().HasAny(trainOrders) - && sSpeedTable[SemNextStopIndex].flags & (SpeedPointFlag::signal | SpeedPointFlag::shuntSignal | SpeedPointFlag::outsideStation) ) { - return; - } - } - } - - auto const &lastspeedpoint = sSpeedTable[ iLast ]; - pTrack = lastspeedpoint.trTrack; - assert( pTrack != nullptr ); - // flaga ustawiona, gdy Point2 toru jest blizej - fLastDir = lastspeedpoint.flags.HasAny(SpeedPointFlag::reverse) ? -1.0 : 1.0; - fCurrentDistance = lastspeedpoint.fDist; // aktualna odleglosc do jego Point1 - fTrackLength = pTrack->Length(); - } - - if( iTableDirection == 0 ) { - // don't bother - return; - } - - while (fCurrentDistance < fDistance) - { - if (pTrack != tLast) // ostatni zapisany w tabelce nie był jeszcze sprawdzony - { // jeśli tor nie był jeszcze sprawdzany - if( Global.iWriteLogEnabled & 8 ) { - WriteLog( "Speed table for " + OwnerName() + " tracing through track " + pTrack->name() ); - } - - auto const events { CheckTrackEvent( pTrack, fLastDir ) }; - for( auto *pEvent : events ) { - if( pEvent != nullptr && TableNotFound(pEvent, fCurrentDistance) ) // jeśli jest semafor na tym torze - { // trzeba sprawdzić tabelkę, bo dodawanie drugi raz tego samego przystanku nie jest korzystne - // jeśli nie ma - TableAddNew(); // zawsze jest true - - if (Global.iWriteLogEnabled & 8) - { - WriteLog("Speed table for " + OwnerName() + " found new event, " + pEvent->m_name); - } - auto &newspeedpoint = sSpeedTable[iLast]; - /* - if( newspeedpoint.Set( - pEvent, - fCurrentDistance + ProjectEventOnTrack( pEvent, pTrack, fLastDir ), - OrderCurrentGet() ) ) { - */ - // an order of a road junction or a level crossing lies on the lane it's on. it's measured along that lane: the search - // for the events beside the track goes in steps of about a metre, and misplaces the ones on lanes shorter than a few metres - auto const eventdistance{ - typeid( *pEvent ) == typeid( road_order ) ? - fCurrentDistance + ProjectEventOnTrack( pEvent, pTrack, fLastDir ) : - GetDistanceToEvent( pTrack, pEvent, fLastDir, fCurrentDistance ) }; - if (newspeedpoint.Set(pEvent, eventdistance, fLength, OrderCurrentGet(), mvOccupied->Vel < EU07_AI_NOMOVEMENT)) - { - - fDistance = newspeedpoint.fDist; // jeśli sygnał stop, to nie ma potrzeby dalej skanować - SemNextStopIndex = iLast; - if (SemNextIndex == npos) - { - SemNextIndex = iLast; - } - if (Global.iWriteLogEnabled & 8) - { - WriteLog("(stop signal from " + (SemNextStopIndex != npos ? sSpeedTable[SemNextStopIndex].GetName() : "unknown semaphor") + ")"); - } - } - else - { - if (true == newspeedpoint.IsProperSemaphor(OrderCurrentGet()) && SemNextIndex == npos) - { - SemNextIndex = iLast; // sprawdzamy czy pierwszy na drodze - } - if (Global.iWriteLogEnabled & 8) - { - WriteLog("(forward signal for " + (SemNextIndex != npos ? sSpeedTable[SemNextIndex].GetName() : "unknown semaphor") + ")"); - } - } - } - } // event dodajemy najpierw, żeby móc sprawdzić, czy tor został dodany po odczytaniu prędkości następnego - - if( pTrack->VelocityGet() == 0.0 // zatrzymanie - || pTrack->iAction // jeśli tor ma własności istotne dla skanowania - || pTrack->VelocityGet() != fLastVel ) // następuje zmiana prędkości - { // odcinek dodajemy do tabelki, gdy jest istotny dla ruchu - TableAddNew(); - sSpeedTable[ iLast ].Set( - pTrack, fCurrentDistance, - fLastDir < 0 ? SpeedPointFlag::enabled | SpeedPointFlag::reverse : SpeedPointFlag::enabled ); // dodanie odcinka do tabelki z flagą kierunku wejścia - if (pTrack->eType == tt_Cross) { - // na skrzyżowaniach trzeba wybrać segment, po którym pojedzie pojazd - // dopiero tutaj jest ustalany kierunek segmentu na skrzyżowaniu -/* - // NOTE: manual selection disabled due to multiplayer - int routewanted; - if( false == AIControllFlag ) { - routewanted = ( - input::keys[ GLFW_KEY_LEFT ] != GLFW_RELEASE ? 1 : - input::keys[ GLFW_KEY_RIGHT ] != GLFW_RELEASE ? 2 : - 3 ); - } - else { - routewanted = 1 + std::floor( Random( static_cast( pTrack->RouteCount() ) - 0.001 ) ); - } -*/ - auto const routewanted { pTrack->RouteDraw() }; - sSpeedTable[iLast].crossRoute = signedNibble( ( static_cast( sSpeedTable[iLast].crossRoute ) | static_cast( pTrack->CrossSegment(fLastDir < 0 ? tLast->iPrevDirection : tLast->iNextDirection, - /* - iRouteWanted ) - */ - routewanted) ) ) & 0xf ); // ostatnie 4 bity pola flag - sSpeedTable[iLast].flags = sSpeedTable[iLast].flags.Without(SpeedPointFlag::reverse); // usunięcie flagi kierunku, bo może być błędna - if (sSpeedTable[iLast].crossRoute < 0) { - sSpeedTable[iLast].flags |= SpeedPointFlag::reverse; // ustawienie flagi kierunku na podstawie wybranego segmentu - } - if (int(fLastDir) * sSpeedTable[iLast].LegacyFlagsValue() < 0) { - fLastDir = -fLastDir; - } -/* - if (AIControllFlag) { - // dla AI na razie losujemy kierunek na kolejnym skrzyżowaniu - iRouteWanted = 1 + Random(3); - } -*/ - } - } - else if ( (pTrack->fRadius != 0.0 // odległość na łuku lepiej aproksymować cięciwami - || tLast != nullptr && tLast->fRadius != 0.0) && - TableAddNew()) // koniec łuku też jest istotny - { // albo dla liczenia odległości przy pomocy cięciw - te usuwać po przejechaniu - // dodanie odcinka do tabelki - sSpeedTable[iLast].Set(pTrack, fCurrentDistance, fLastDir < 0 ? SpeedPointFlag::enabled | SpeedPointFlag::curve | SpeedPointFlag::reverse : SpeedPointFlag::enabled | SpeedPointFlag::curve); - } - } - - fCurrentDistance += fTrackLength; // doliczenie kolejnego odcinka do przeskanowanej długości - tLast = pTrack; // odhaczenie, że sprawdzony - fLastVel = pTrack->VelocityGet(); // prędkość na poprzednio sprawdzonym odcinku - pTrack = pTrack->Connected( - pTrack->eType == tt_Cross ? sSpeedTable[iLast].crossRoute : static_cast(fLastDir), - fLastDir); // może być NULL - - if (pTrack != nullptr ) - { // jeśli kolejny istnieje - if( tLast != nullptr && tLast->VelocityGet() > 0 && (tLast->VelocityGet() < pTrack->VelocityGet() || pTrack->VelocityGet() < 0) ) { - - if (iLast != -1 && sSpeedTable[iLast].trTrack == tLast) - { - // if the track is already in the table we only need to mark it as relevant - sSpeedTable[iLast].flags |= SpeedPointFlag::enabled; - } - else - { - // otherwise add it - TableAddNew(); - sSpeedTable[iLast].Set(tLast, - fCurrentDistance - fTrackLength, // by now the current distance points to beginning of next track - (fLastDir > 0 ? pTrack->iPrevDirection : pTrack->iNextDirection) ? SpeedPointFlag::enabled : SpeedPointFlag::enabled | SpeedPointFlag::reverse); - } - } - // zwiększenie skanowanej odległości tylko jeśli istnieje dalszy tor - fTrackLength = pTrack->Length(); - } - else - { // definitywny koniec skanowania, chyba że dalej puszczamy samochód po gruncie... - if( iLast == -1 - || ( false == sSpeedTable[iLast].flags.HasAll(SpeedPointFlag::enabled | SpeedPointFlag::trackEnd) - && sSpeedTable[iLast].trTrack != tLast ) ) { - // only if we haven't already marked end of the track and if the new track doesn't duplicate last one - if( TableAddNew() ) { - // zapisanie ostatniego sprawdzonego toru - sSpeedTable[iLast].Set( - tLast, fCurrentDistance - fTrackLength, // by now the current distance points to beginning of next track, - fLastDir < 0 ? SpeedPointFlag::enabled | SpeedPointFlag::trackEnd | SpeedPointFlag::reverse : SpeedPointFlag::enabled | SpeedPointFlag::trackEnd); - } - } - else if( sSpeedTable[iLast].trTrack == tLast && false == TestFlag(sSpeedTable[iLast].trTrack->iCategoryFlag, 0x100) ) { - // otherwise just mark the last added track as the final one - // TODO: investigate exactly how we can wind up not marking the last existing track as actual end - // don't mark portals, as these aren't exactly track ends, but teleport devices - sSpeedTable[iLast].flags |= SpeedPointFlag::enabled | SpeedPointFlag::trackEnd; - } - // to ostatnia pozycja, bo NULL nic nie da, a może się podpiąć obrotnica, czy jakieś transportery - return; - } - } - if( TableAddNew() ) { - // zapisanie ostatniego sprawdzonego toru - sSpeedTable[ iLast ].Set( - pTrack, fCurrentDistance, - fLastDir < 0 ? SpeedPointFlag::none | SpeedPointFlag::reverse : SpeedPointFlag::none ); - } -}; - -void TController::TableCheck(double fDistance) -{ // przeliczenie odległości w tabelce, ewentualnie doskanowanie (bez analizy prędkości itp.) - if( iTableDirection != iDirection ) { - // jak zmiana kierunku, to skanujemy od końca składu - TableTraceRoute( fDistance, pVehicles[ end::rear ] ); - TableSort(); - } - else if (iTableDirection) - { // trzeba sprawdzić, czy coś się zmieniło - auto const distance = MoveDistanceGet(); - for (auto &sp : sSpeedTable) { - // aktualizacja odległości dla wszystkich pozycji tabeli - sp.UpdateDistance(distance); - } - MoveDistanceReset(); // kasowanie odległości po aktualizacji tabelki - for( int i = 0; i < iLast; ++i ) - { // aktualizacja rekordów z wyjątkiem ostatniego - if (sSpeedTable[i].flags & SpeedPointFlag::enabled) // jeśli pozycja istotna - { - auto const passedbefore { sSpeedTable[ i ].flags.HasAll(SpeedPointFlag::elapsed) }; - if (sSpeedTable[i].Update()) - { - if( Global.iWriteLogEnabled & 8 ) { - WriteLog( "Speed table for " + OwnerName() + " detected switch change at " + sSpeedTable[ i ].trTrack->name() + " (generating fresh trace)" ); - } - // usuwamy wszystko za tym torem - while (sSpeedTable.back().trTrack != sSpeedTable[i].trTrack) - { // usuwamy wszystko dopóki nie trafimy na tą zwrotnicę - sSpeedTable.pop_back(); - --iLast; - } - // a semaphor recorded beyond the switch went away with the discarded entries - if( SemNextIndex != npos - && SemNextIndex >= sSpeedTable.size() ) { - SemNextIndex = npos; - } - if( SemNextStopIndex != npos - && SemNextStopIndex >= sSpeedTable.size() ) { - SemNextStopIndex = npos; - } - tLast = sSpeedTable[ i ].trTrack; - TableTraceRoute( fDistance, pVehicles[ end::rear ] ); - TableSort(); - // nie kontynuujemy pętli, trzeba doskanować ciąg dalszy - break; - } - // a switch is a track, the update of a signal never ends the loop above - CheckSignalPassed( sSpeedTable[ i ], passedbefore ); - if (sSpeedTable[i].flags & SpeedPointFlag::track) // jeśli odcinek - { - if( sSpeedTable[ i ].fDist + sSpeedTable[ i ].trTrack->Length() < -fLength ) // a skład wyjechał całą długością poza - { // degradacja pozycji - sSpeedTable[i].flags = sSpeedTable[i].flags.Without(SpeedPointFlag::enabled); // nie liczy się - } - else if( sSpeedTable[i].crossRoute == 0 && ( sSpeedTable[i].flags & ( SpeedPointFlag::elapsed | SpeedPointFlag::switchTrack ) ) == SpeedPointFlag::elapsed && sSpeedTable[i].fVelNext < 0 ) { - // jest z tyłu (najechany) i nie jest zwrotnicą ani skrzyżowaniem - // a nie ma ograniczenia prędkości - sSpeedTable[i].ResetFlags(); // to nie ma go po co trzymać (odtykacz usunie ze środka) - } - } - else if (sSpeedTable[i].flags & SpeedPointFlag::event && false == sSpeedTable[i].flags.HasAny(SpeedPointFlag::pointSpeed) && sSpeedTable[i].fDist < (typeid(*sSpeedTable[i].evEvent) == typeid(putvalues_event) ? -fLength : 0) && mvOccupied->CategoryFlag == 2 && - sSpeedTable[i].fDist < -0.75) // jeśli event - { - // jeśli jest z tyłu - // pociąg staje zawsze, a samochód tylko jeśli nie przejedzie całą długością (może być zaskoczony zmianą) - // WriteLog("TableCheck: Event is behind. Delete from table: " + sSpeedTable[i].evEvent->asName); - sSpeedTable[i].flags = sSpeedTable[i].flags.Without(SpeedPointFlag::enabled); // degradacja pozycji dla samochodu; - // semafory usuwane tylko przy sprawdzaniu, bo wysyłają komendy - } - } - } - auto const lastpassedbefore { sSpeedTable[ iLast ].flags.HasAll(SpeedPointFlag::elapsed) }; - sSpeedTable[iLast].Update(); // aktualizacja ostatniego - // a signal at stop often is the last, the scan doesn't go past it - CheckSignalPassed( sSpeedTable[ iLast ], lastpassedbefore ); - // WriteLog("TableCheck: Upate last track. Dist=" + AnsiString(sSpeedTable[iLast].fDist)); - if( sSpeedTable[ iLast ].fDist < fDistance ) { - TableTraceRoute( fDistance, pVehicles[ end::rear ] ); // doskanowanie dalszego odcinka - TableSort(); - } - // garbage collection - TablePurger(); - } -}; - -namespace { - -// the position is a signal showing stop (SetVelocity 0 0). SetVelocity 0 x on automatic block isn't: it may be passed after a stop -bool is_signal_at_stop( TSpeedPos const &Point ) -{ - return Point.flags.HasAll(SpeedPointFlag::event) - && Point.flags.HasAll(SpeedPointFlag::signal) - && false == Point.flags.HasAll(SpeedPointFlag::stopOnAutomaticBlock) - && std::abs( Point.fVelNext ) <= 0.0 - && Point.evEvent != nullptr; -} - -void clear_signal_area_end( TSpeedPos &Point ) -{ - if( Point.flags.HasAll(SpeedPointFlag::signalAreaEnd) ) { - Point.Clear(); - } -} - -// the position is a signal, a main or a shunting one: the aspect comes from its memory cell. putvalues events -// set speed limits by the track, and the flags they get don't make them signals -bool is_signal( TSpeedPos const &Point ) -{ - return Point.flags.HasAll(SpeedPointFlag::event) - && ( Point.flags.HasAll(SpeedPointFlag::signal) || Point.flags.HasAll(SpeedPointFlag::shuntSignal) ) - && Point.evEvent != nullptr - && typeid( *Point.evEvent ) == typeid( getvalues_event ); -} - -std::uint8_t passing_flags_of( TSpeedPos const &Point, double const Speedatsignal, bool const Trainmovement ) -{ - std::uint8_t flags { 0 }; - auto const shunting { Point.flags.HasAll(SpeedPointFlag::shuntSignal) }; - if( shunting ) { - flags |= blackbox::passing_flags::shunt; - } - // the speeds of the aspects are whole km/h, -1 for no limit; a shunting signal binds only the shunting - if( std::abs( Speedatsignal ) < 0.5 && ( false == shunting || false == Trainmovement ) ) { - flags |= ( Point.flags.HasAll(SpeedPointFlag::stopOnAutomaticBlock) ? blackbox::passing_flags::automatic_block : blackbox::passing_flags::at_stop ); - } - return flags; -} - -} // namespace - -void TController::CheckSignalPassed( TSpeedPos const &Point, bool const Passedbefore ) const -{ - // not bSeenAhead: found already behind the head, the train stood across it or past it, it didn't pass it - if( false == signal_passing::passed_now( Passedbefore, Point.flags.HasAll(SpeedPointFlag::elapsed), Point.bSeenAhead ) - || ( mvOccupied->CategoryFlag & 1 ) == 0 ) { // railway only - return; - } - if( is_signal_at_stop( Point ) ) { - simulation::test().signal_passed_at_danger( OwnerName(), Point.evEvent->m_name ); - } - if( is_signal( Point ) ) { - // the aspect the train had of it: the table keeps it once the signal is behind, while the memory cell - // may already show stop for the train itself, past the signal on the track it guards. the stop of an - // automatic block signal is kept as the speed allowed after it, with a flag of its own - auto const speedatsignal { Point.flags.HasAll(SpeedPointFlag::stopOnAutomaticBlock) ? 0.0 : Point.fVelNext }; - simulation::Blackbox.signal_passed( - pVehicles[ end::front ], *Point.evEvent, - speedatsignal, Point.evEvent->input_value( 2 ), - mvOccupied->Vel, -Point.fDist, - passing_flags_of( Point, speedatsignal, false == OrderCurrentGet().HasAny( DriverOrder::shunt | DriverOrder::looseShunt ) ) ); - } -} - -auto const passengerstopmaxdistance { 400.0 }; // maximum allowed distance between passenger stop point and consist head - -// the margins of the final approach of a train [m], closer than the first of which it stops at once and within the -// second of which it makes its final approach: at a passenger stop, or at a signal and anything else it stops at -std::pair -TController::train_proximity_margins( bool const Passengerstop ) const { - - auto minproximity { 0.0 }; - auto maxproximity { 0.0 }; - if( Passengerstop ) { - // a stop point keeps the margins its W4 parameters (head or middle of the consist, - // platform length) were set up against - minproximity = std::clamp( 5 + iVehicles, 10, 15 ) + ( IsCargoTrain ? 10.0 : 0.0 ); - maxproximity = std::clamp( 10 + iVehicles, 15, 40 ); - } - else { - // a train stops 8-15 m short of the signal whatever its length; closer than the lower - // edge it stops at once, the braking aims at the middle of the window, 3.5 m further out - minproximity = 8.0; - // the final approach begins far enough out to slow from the coasting speed down to the window, - // and at the same distance whether the train is moving or standing, so it does not flip - // between creeping closer and holding still when it comes to a stand short of the window - maxproximity = 50.0; - } - if( IsCargoTrain ) { - // start the final approach earlier for cargo trains, their brakes react more slowly - maxproximity += 10.0; - } - if( ( Global.FrictionWeatherFactor < 1.f ) - && ( iVehicles > 1 ) ) { - // take into account weather conditions - minproximity += 5.0; - maxproximity += 5.0; - } - if( mvOccupied->Vel < 0.1 ) { - // jak stanie za daleko, to niech nie dociąga paru metrów - maxproximity = std::max( maxproximity, 50.0 ); - } - return { minproximity, maxproximity }; -} - -TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fNext, double &fAcc) -{ // ustalenie parametrów, zwraca typ komendy, jeśli sygnał podaje prędkość do jazdy - // fVelDes - prędkość zadana - // fDist - dystans w jakim należy rozważyć ruch - // fNext - prędkość na końcu tego dystansu - // fAcc - zalecane przyspieszenie w chwili obecnej - kryterium wyboru dystansu - auto a { 0.0 }; // przyspieszenie - auto v { 0.0 }; // prędkość - auto d { 0.0 }; // droga - auto d_to_next_sem { 10000.0 }; //ustaiwamy na pewno dalej niż widzi AI - auto go { TCommandType::cm_Unknown }; - auto speedlimitiscontinuous { true }; // stays true if potential active speed limit is unbroken to the last (relevant) point in scan table - eSignNext = nullptr; - IsAtPassengerStop = false; - bStopTargetIsPassengerStop = false; - IsScheduledPassengerStopVisible = false; - mvOccupied->SecuritySystem.set_cabsignal_lock(false); - // te flagi są ustawiane tutaj, w razie potrzeby - drivingFlags.trackEnd = false; - drivingFlags.switchFound = false; - drivingFlags.signalFound = false; - drivingFlags.stopPointFound = false; - SignalAreaEndDist = -1.0; - update_point_limits(); - - for( std::size_t idx = 0; idx < sSpeedTable.size(); ++idx ) { - // o ile dana pozycja tabelki jest istotna - if( false == sSpeedTable[ idx ].flags.HasAny(SpeedPointFlag::enabled) ) { continue; } - - auto &point { sSpeedTable[ idx ] }; - - if( point.flags.HasAll(SpeedPointFlag::passengerStop) ) { - if( TableUpdateStopPoint( go, point, d_to_next_sem ) ) { continue; }; - } - v = point.fVelNext; // odczyt prędkości do zmiennej pomocniczej - if( point.flags.HasAll(SpeedPointFlag::switchTrack) ) { - // zwrotnice są usuwane z tabelki dopiero po zjechaniu z nich - drivingFlags.switchFound = true; // rozjazd z przodu/pod ogranicza np. sens skanowania wstecz - SwitchClearDist = point.fDist + point.trTrack->Length() + fLength; - } - else if ( point.flags.HasAll(SpeedPointFlag::event) && TableUpdateEvent(v, go, point, d_to_next_sem, idx) ) // W4 może się deaktywować - { // jeżeli event, może być potrzeba wysłania komendy, aby ruszył - continue; - } - - auto const railwaytrackend { true == point.flags.HasAll(SpeedPointFlag::trackEnd) && is_train() }; - if( v >= 0.0 // pozycje z prędkością -1 można spokojnie pomijać - || railwaytrackend ) { - - // a PointVelocity limit lies fPointDist beyond its entry and stays ahead of us until the head passes it - auto const ispointlimit { point.flags.HasAll(SpeedPointFlag::pointSpeed) }; - d = point.fDist + point.fPointDist; - - if( v >= 0.0 ) { - // points located in front of us can potentially affect our acceleration and target speed - if( d > 0.0 - && ( false == point.flags.HasAll(SpeedPointFlag::elapsed) || ispointlimit ) ) { - // sygnał lub ograniczenie z przodu (+32=przejechane) - // 2014-02: jeśli stoi, a ma do przejechania kawałek, to niech jedzie - if( mvOccupied->Vel < 0.01 - && true == point.flags.HasAll(SpeedPointFlag::enabled | SpeedPointFlag::event | SpeedPointFlag::passengerStop) - && false == IsAtPassengerStop ) { - // ma podjechać bliżej - czy na pewno w tym miejscu taki warunek? - a = d > passengerstopmaxdistance || drivingFlags.stopCloser ? fAcc : 0.0; - } - else { - // przyspieszenie: ujemne, gdy trzeba hamować - if( v >= 0.0 ) { - a = ( v * v - mvOccupied->Vel * mvOccupied->Vel ) / ( 25.92 * d ); - if( mvOccupied->Vel < v - || v == 0.0 ) { - // if we're going slower than the target velocity and there's enough room for safe stop, speed up - auto const brakingdistance { 1.2 * fBrakeDist * braking_distance_multiplier( v ) }; - if( brakingdistance > 0.0 ) { - // maintain desired acc while we have enough room to brake safely, when close enough start paying attention - // try to make a smooth transition instead of sharp change - a = std::lerp( a, AccPreferred, std::clamp( ( d - brakingdistance ) / brakingdistance, 0.0, 1.0 ) ); - } - } - if( d < ( ispointlimit && v > 0.0 ? point_limit_approach() : fMinProximityDist ) - && v < fVelDes ) { - // jak jest już blisko, ograniczenie aktualnej prędkości - fVelDes = v; - } - } - } - } - // points located behind can affect our current speed, but little else - else if ( point.flags & SpeedPointFlag::track) // jeśli tor - { // tor ogranicza prędkość, dopóki cały skład nie przejedzie, - if( v >= 1.0 && d + point.trTrack->Length() < -fLength && false == railwaytrackend ) { // EU06 się zawieszało po dojechaniu na koniec toru postojowego - // zapętlenie, jeśli już wyjechał za ten odcinek - continue; - } - if( v < fVelDes ) { - // ograniczenie aktualnej prędkości aż do wyjechania za ograniczenie - fVelDes = v; - } - if( v < VelLimitLastDist.first ) { - VelLimitLastDist.second = d + point.trTrack->Length() + fLength; - } - else if( VelLimitLastDist.second > 0 && false == point.flags.HasAny((SpeedPointFlag::switchTrack | SpeedPointFlag::passengerStop)) ) { // the speed limit can potentially start afterwards, so don't mark it as broken too soon - speedlimitiscontinuous = false; - } - if( false == railwaytrackend ) { - continue; // i tyle wystarczy - } - } - else { - // event trzyma tylko jeśli VelNext=0, nawet po przejechaniu (nie powinno dotyczyć samochodów?) - a = v > 0.0 ? - fAcc : - mvOccupied->Vel < 0.01 ? - 0.0 : // already standing still so no need to bother with brakes - -2.0; // ruszanie albo hamowanie - } - } - // track can potentially end, which creates another virtual point of interest with speed limit of 0 at the end of it - // TBD, TODO: when tracing the route create a dedicated table entry for it, to simplify the code? - if( railwaytrackend ) { - // if the railway track ends here set the velnext accordingly as well - // TODO: test this with turntables and such - auto const stopatendacceleration = -1.0 * mvOccupied->Vel * mvOccupied->Vel / ( 25.92 * ( d + point.trTrack->Length() ) ); - if( stopatendacceleration < a ) { - a = stopatendacceleration; - v = 0.0; - d += point.trTrack->Length(); - if( d < fMinProximityDist ) { - // jak jest już blisko, ograniczenie aktualnej prędkości - fVelDes = v; - } - } - } - - if( a <= fAcc - && ( v < fNext || fNext < 0 ) ) { // filter out consecutive, farther out blocks with the same speed limit; they'd make us accelerate slower due to their lower a value - // mniejsze przyspieszenie to mniejsza możliwość rozpędzenia się albo konieczność hamowania - // jeśli droga wolna, to może być a>1.0 i się tu nie załapuje - fAcc = a; // zalecane przyspieszenie (nie musi być uwzględniane przez AI) - fNext = v; // istotna jest prędkość na końcu tego odcinka - fDist = d; // dlugość odcinka - bStopTargetIsPassengerStop = ( v == 0.0 ) && ( point.flags.HasAny(SpeedPointFlag::passengerStop) ); - } -/* - else if ((fAcc > 0) && (v >= 0) && (v > fNext)) { - // jeśli nie ma wskazań do hamowania, można podać drogę i prędkość na jej końcu - fNext = v; // istotna jest prędkość na końcu tego odcinka - fDist = d; // dlugość odcinka (kolejne pozycje mogą wydłużać drogę, jeśli prędkość jest stała) - } -*/ - // we'll pick first scanned target speed as our goal - // farther scan table points can override it through previous clause, if they require lower acceleration or speed reduction - else if( a > 0 && a <= fAcc && v >= 0 && fNext < 0 ) { - fAcc = a; - fNext = v; - fDist = d; - bStopTargetIsPassengerStop = ( v == 0.0 ) && ( point.flags.HasAny(SpeedPointFlag::passengerStop) ); - } - // potentially update our current speed limit - // a point limit binds only the head at its point, it neither extends nor breaks a limit over a stretch of the line - if( false == ispointlimit - && v < VelLimitLastDist.first - && ( d < 0 // the point counts as part of last speed limit either if it's behind us - || VelLimitLastDist.second > 0 ) ) { // or if we already have the last limit ongoing - VelLimitLastDist.second = d + fLength; - if( point.flags.HasAny(SpeedPointFlag::track) ) { - VelLimitLastDist.second += point.trTrack->Length(); - } - } - else if( false == point.flags.HasAny(( SpeedPointFlag::switchTrack | SpeedPointFlag::passengerStop | SpeedPointFlag::pointSpeed )) ) { - // if we found a point which isn't part of the current speed limit mark the limit as broken - // NOTE: we exclude switches from this rule, as speed limits generally extend through these - speedlimitiscontinuous = false; - } - } // if (v>=0.0) - // finding a point which doesn't impose speed limit means any potential active speed limit can't extend through entire scan table - // NOTE: we test actual speed value for the given point, as events may receive (v = -1) as a way to disable them in irrelevant modes - if( point.fVelNext < 0 && false == point.flags.HasAny((SpeedPointFlag::switchTrack | SpeedPointFlag::passengerStop | SpeedPointFlag::pointSpeed)) ) { - // NOTE: we exclude switches from this rule, as speed limits generally extend through these - // and point limits, which say nothing of the line they lie on - speedlimitiscontinuous = false; - } - if (fNext >= 0.0) - { // jeśli ograniczenie - if( (point.flags & (SpeedPointFlag::enabled | SpeedPointFlag::event)) == (SpeedPointFlag::enabled | SpeedPointFlag::event) && false == point.flags.HasAny(SpeedPointFlag::pointSpeed) && eSignNext == nullptr ) { // tylko sygnał przypisujemy (a point limit isn't one) - // jeśli jeszcze nic nie zapisane tam - eSignNext = point.evEvent; // dla informacji - } - if( fNext == 0.0 ) { - break; // nie ma sensu analizować tabelki dalej - } - } - } - - // the point limits latched before, which aren't in the table any more - apply_point_limits( fVelDes, fDist, fNext, fAcc ); - - // jeśli mieliśmy ograniczenie z semafora i nie ma przed nami - if( VelSignalLast >= 0.0 - && ( false == drivingFlags.signalFound && false == drivingFlags.switchFound && false == drivingFlags.stopPointFound ) - && true == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { - VelSignalLast = -1.0; - } - // if there's unbroken speed limit through our scan table take a note of it - if( VelLimitLastDist.second > 0 - && speedlimitiscontinuous ) { - VelLimitLastDist.second = EU07_AI_SPEEDLIMITEXTENDSBEYONDSCANRANGE; - } - // take into account the effect switches have on duration of signal-imposed speed limit, in calculation of speed limit end point - // a reduced speed ends where the interlocking area does, if that is marked, and not past the switches farther on - if( auto const signallimitend { VelSignalLast > 0.0 && SignalAreaEndDist >= 0.0 ? SignalAreaEndDist : SwitchClearDist }; - VelSignalLast >= 0.0 && signallimitend >= 0.0 ) { - VelLimitLastDist.second = std::max( VelLimitLastDist.second, signallimitend ); - } - - //analiza spisanych z tabelki ograniczeń i nadpisanie aktualnego - // if stopped at a valid passenger stop, hold there - if( true == IsAtPassengerStop && mvOccupied->Vel < 0.01 ) { - fVelDes = 0.0; - } - else { - fVelDes = min_speed( fVelDes, VelSignalLast ); - fVelDes = min_speed( fVelDes, VelLimitLast ); - fVelDes = min_speed( fVelDes, VelRoad ); - fVelDes = min_speed( fVelDes, VelRestricted ); - } - // nastepnego semafora albo zwrotnicy to uznajemy, że mijamy W5 - FirstSemaphorDist = d_to_next_sem; // przepisanie znalezionej wartosci do zmiennej - return go; -}; - -bool -TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, double const Signaldistance ) { - // stop points are irrelevant when not in one of the basic modes - if( false == OrderCurrentGet().HasAny( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank ) ) { return true; } - // jeśli przystanek, trzeba obsłużyć wg rozkładu - drivingFlags.stopPointFound = true; - // the W4 and the timetable name the station each in its own file, so the two spellings are compared by their key: - // with or without the polish letters, in any case, with spaces or underscores - if( false == timetable::stop_point_is_for( Point.evEvent->input_text(), asNextStop ) ) - { // jeśli nazwa nie jest zgodna - if( false == IsScheduledPassengerStopVisible // check if our next scheduled stop didn't show up earlier in the scan - && Point.fDist < 1.15 * fBrakeDist + 300 - && Point.fDist > 0 ) // tylko jeśli W4 jest blisko, przy dwóch może zaczać szaleć - { - // porównuje do następnej stacji, więc trzeba przewinąć do poprzedniej - // nastepnie ustawić następną na aktualną tak żeby prawidłowo ją obsłużył w następnym kroku - if( true == TrainParams.RewindTimeTable( Point.evEvent->input_text() ) ) { - asNextStop = TrainParams.NextStop(); - TrainParams.StationStart = TrainParams.StationIndex; - } - } - else if( Point.fDist < -fLength ) { - // jeśli został przejechany - Point.ResetFlags(); // to można usunąć (nie mogą być usuwane w skanowaniu) - } - return true; // ignorowanie jakby nie było tej pozycji - } - else if (drivingFlags.stopPoint) // jeśli pomijanie W4, to nie sprawdza czasu odjazdu - { // tylko gdy nazwa zatrzymania się zgadza - if( OrderCurrentGet().HasAny( DriverOrder::obeyTrain | DriverOrder::bank ) ) { - // check whether the station specifies radio channel change - // NOTE: we don't do it in shunt mode, as shunting operations tend to use dedicated radio channel - // NOTE: there's a risk radio channel change was specified by a station which we skipped during timetable rewind - // we ignore this for the time being as it's not a high priority error - auto const radiochannel { TrainParams.radio_channel() }; - if( radiochannel > 0 ) { - if( iGuardRadio != 0 ) { - iGuardRadio = radiochannel; - } - if( iRadioChannel != radiochannel ) { - cue_action( driver_hint::radiochannel, radiochannel ); - } - } - } - IsScheduledPassengerStopVisible = true; // block potential timetable rewind if the next stop shows up later in the scan - if (false == TrainParams.IsStop()) - { // jeśli nie ma tu postoju - Point.fVelNext = -1; // maksymalna prędkość w tym miejscu - // przy 160km/h jedzie 44m/s, to da dokładność rzędu 5 sekund - if (Point.fDist < passengerstopmaxdistance * 0.5 ) { - // zaliczamy posterunek w pewnej odległości przed (choć W4 nie zasłania już semafora) -#if LOGSTOPS - WriteLog(std::format( - "{} as {}: at {}:{} passed {}", - pVehicle->asName, TrainParams.TrainName, simulation::Time.data().wHour, simulation::Time.data().wMinute, asNextStop)); // informacja -#endif - // przy jakim dystansie (stanie licznika) ma przesunąć na następny postój - fLastStopExpDist = mvOccupied->DistCounter + 0.250 + 0.001 * fLength; - TrainParams.UpdateMTable( simulation::Time, asNextStop ); - record_station( Point, blackbox::station_kinds::passed ); - UpdateDelayFlag(); - TrainParams.StationIndexInc(); // przejście do następnej - asNextStop = TrainParams.NextStop(); // pobranie kolejnego miejsca zatrzymania - Point.ResetFlags(); // nie liczy się już - return true; // table entry recognized and handled - } - } // koniec obsługi przelotu na W4 - else { - // zatrzymanie na W4 - // the margins of a passenger stop, whether the train is already making for it or not: the present ones - // depend on this very flag, and a check against them would turn it on and off every other scan - auto const [ stopminproximity, stopmaxproximity ] { - is_train() ? - train_proximity_margins( true ) : - std::pair{ fMinProximityDist, fMaxProximityDist } }; - if ( false == Point.bMoved ) { - // potentially shift the stop point in accordance with its defined parameters - /* - // https://rainsted.com/pl/Wersja/18.2.133#Okr.C4.99gi_dla_W4_i_W32 - Pierwszy parametr ujemny - preferowane zatrzymanie czoła składu (np. przed przejściem). - Pierwszy parametr dodatni - preferowane zatrzymanie środka składu (np. przy wiacie, przejściu podziemnym). - Drugi parametr ujemny - wskazanie zatrzymania dla krótszych składów (W32). - Drugi paramer dodatni - długość peronu (W4). - */ - auto L = 0.0; - auto Par1 = Point.evEvent->input_value(1); - auto Par2 = Point.evEvent->input_value(2); - if (Par2 >= 0 || fLength < -Par2) { //użyj tego W4 - if (Par1 < 0) { - L = -Par1; - } - else { - //środek - L = Par1 - stopminproximity - fLength * 0.5; - } - // the train comes to a stand anywhere up to the margin of a passenger stop short of this point, not - // that of the signals it may be making for when it first sees the W4, so the tail is to keep that far - // inside the platform - L = std::max(0.0, std::min(L, std::abs(Par2) - stopminproximity - fLength)); - Point.UpdateDistance(L); - Point.bMoved = true; - Point.fMoved = L; - } - else { - Point.ResetFlags(); - } - } - // for human-driven vehicles discard the stop point if they leave it far enough behind - if( false == AIControllFlag - && Point.fDist < -1 * std::max(fLength + 100, 250.0) - Point.fMoved ) { - record_station( Point, blackbox::station_kinds::missed ); - Point.ResetFlags(); // nie liczy się już zupełnie (nie wyśle SetVelocity) - Point.fVelNext = -1; // można jechać za W4 - if( Point.fDist <= 0.0 && eSignNext == Point.evEvent ) { - // sanity check, if we're held by this stop point, let us go - VelSignalLast = -1; - } - return true; - } - - IsAtPassengerStop = Point.fDist <= passengerstopmaxdistance - // Ra 2F1I: odległość plus długość pociągu musi być mniejsza od długości - // peronu, chyba że pociąg jest dłuższy, to wtedy minimalna. - // jeśli długość peronu ((sSpeedTable[i].evEvent->ValueGet(2)) nie podana, - // przyjąć odległość fMinProximityDist - && (drivingFlags.stopCloser ? - Point.fDist + fLength + (Point.fMoved - stopminproximity * 0.5f) <= std::max(std::abs(Point.evEvent->input_value(2)), - 2.0 * stopmaxproximity + fLength) : - Point.fDist < Signaldistance); - - if( !eSignNext ) { - //jeśli nie widzi następnego sygnału ustawia dotychczasową - eSignNext = Point.evEvent; - } - if( mvOccupied->Vel > EU07_AI_MOVEMENT ) { - // jeśli jedzie (nie trzeba czekać, aż się drgania wytłumią - drzwi zamykane od 1.0) to będzie zatrzymanie - Point.fVelNext = 0; - // potentially announce pending stop - if( m_lastannouncement != announcement_t::approaching - && Point.fDist < 750 - && Point.fDist > 250 ) { - announce( announcement_t::approaching ); - } - } else if( true == IsAtPassengerStop ) { - // jeśli się zatrzymał przy W4, albo stał w momencie zobaczenia W4 - if( !AIControllFlag ) { - // w razie przełączenia na AI ma nie podciągać do W4, gdy użytkownik zatrzymał za daleko - drivingFlags.stopCloser = false; - } - if (TrainParams.UpdateMTable( simulation::Time, asNextStop) ) { - // to się wykona tylko raz po zatrzymaniu na W4 - record_station( Point, blackbox::station_kinds::stopped ); - // the service flags of this stop hold for its doors and departure - m_stopflags = TrainParams.stop_flags(); - if( TrainParams.StationIndex < TrainParams.StationCount ) { - // jeśli są dalsze stacje, bez trąbienia przed odjazdem - // also ignore any horn cue that may be potentially set below 1 km/h and before the actual full stop - drivingFlags.startHorn = false; - drivingFlags.startHornNow = false; - } - UpdateDelayFlag(); - - // perform loading/unloading - // HACK: manual check if we didn't already do load exchange at this stop - // TODO: remove the check once the station system is in place - if( m_lastexchangestop != asNextStop ) { - m_lastexchangestop = asNextStop; - m_lastexchangedirection = pVehicle->DirectionGet(); - m_lastexchangeplatforms = static_cast( std::floor( std::abs( Point.evEvent->input_value( 2 ) ) ) ) % 10; - auto const exchangetime { simulation::Station.update_load( pVehicles[ end::front ], TrainParams, m_lastexchangeplatforms ) }; - WaitingSet( exchangetime ); - // announce the stop name while at it - announce( announcement_t::current ); - m_makenextstopannouncement = true; - } - - if (TrainParams.DirectionChange()) { - // jeśli "@" w rozkładzie, to wykonanie dalszych komend - // wykonanie kolejnej komendy, nie dotyczy ostatniej stacji - if (drivingFlags.pushPull) { - // SN61 ma się też nie ruszać, chyba że ma wagony - drivingFlags.stopHere = true; // EZT ma stać przy peronie - if (OrderNextGet() != DriverOrder::changeDirection) { - OrderPush(DriverOrder::changeDirection); // zmiana kierunku - OrderPush( - TrainParams.StationIndex < TrainParams.StationCount ? - DriverOrder::obeyTrain : - DriverOrder::shunt); // to dalej wg rozkładu - } - } - else { - // a dla lokomotyw... - // pozwolenie na przejechanie za W4 przed czasem i nie ma stać - drivingFlags.stopPoint = false; - drivingFlags.stopHere = false; - } - // przejście do kolejnego rozkazu (zmiana kierunku, odczepianie) - JumpToNextOrder(); - // ma nie podjeżdżać pod W4 po przeciwnej stronie - drivingFlags.stopCloser = false; - // ten W4 nie liczy się już zupełnie (nie wyśle SetVelocity) - Point.ResetFlags(); - // jechać - Point.fVelNext = -1; - // nie analizować prędkości - return true; - } - } - - if (OrderCurrentGet() & ( DriverOrder::shunt | DriverOrder::looseShunt )) { - OrderNext(DriverOrder::obeyTrain); // uruchomić jazdę pociągową - CheckVehicles(); // zmienić światła - } - - if (TrainParams.StationIndex < TrainParams.StationCount) { - // jeśli są dalsze stacje, czekamy do godziny odjazdu - if ( true == IsCargoTrain - || true == TrainParams.IsMaintenance() - || TrainParams.IsTimeToGo(simulation::Time.data().wHour, simulation::Time.data().wMinute + simulation::Time.data().wSecond * 0.0167) ) { - // z dalszą akcją czekamy do godziny odjazdu - // cargo trains and passenger trains at maintenance stop don't need to wait - IsAtPassengerStop = false; - record_station( Point, blackbox::station_kinds::ready ); - // przy jakim dystansie (stanie licznika) ma przesunąć na następny postój - fLastStopExpDist = mvOccupied->DistCounter + 0.050 + 0.001 * fLength; - TrainParams.StationIndexInc(); // przejście do następnej - asNextStop = TrainParams.NextStop(); // pobranie kolejnego miejsca zatrzymania -#if LOGSTOPS - WriteLog(std::format( - "{} as {}: at {}:{} next {}", - pVehicle->asName, TrainParams.TrainName, simulation::Time.data().wHour, simulation::Time.data().wMinute, asNextStop)); // informacja -#endif - // update consist weight, brake settings and ai braking tables - // NOTE: this calculation is expected to run after completing loading/unloading - CheckVehicles(); // nastawianie hamulca do jazdy pociągowej - - if( static_cast( std::floor( std::abs( Point.evEvent->input_value( 1 ) ) ) ) % 2 ) { - // nie podjeżdżać do semafora, jeśli droga nie jest wolna - drivingFlags.stopHere = true; - } - else { - //po czasie jedź dalej - drivingFlags.stopHere = false; - } - drivingFlags.stopCloser = true; // do następnego W4 podjechać blisko (z dociąganiem) - Point.ResetFlags(); // nie liczy się już zupełnie (nie wyśle SetVelocity) - Point.fVelNext = -1; // można jechać za W4 - if( Point.fDist <= 0.0 && eSignNext == Point.evEvent ) { - // sanity check, if we're held by this stop point, let us go - VelSignalLast = -1; - } - if( Command == TCommandType::cm_Unknown ) { // jeśli nie było komendy wcześniej - Command = TCommandType::cm_Ready; // gotów do odjazdu z W4 (semafor może zatrzymać) - } - if( false == tsGuardSignal.empty() - && true == timetable::has_conductor( m_stopflags ) ) { - // jeśli mamy głos kierownika, to odegrać - drivingFlags.guardSignal = true; - } - return true; // nie analizować prędkości - } // koniec startu z zatrzymania - else { - cue_action(driver_hint::waitdeparturetime); - if (timetable::has_conductor(m_stopflags) // no conductor, no door kept open for him - && TrainParams.IsTimeToGo(simulation::Time.data().wHour, simulation::Time.data().wMinute + simulation::Time.data().wSecond*0.0167 + 0.1)) { //if is less than 6 sec to departure - drivingFlags.guardOpenDoor = true; - GuardOpenDoor(); - } - } - } // koniec obsługi początkowych stacji - else { - // jeśli dojechaliśmy do końca rozkładu -#if LOGSTOPS - WriteLog(std::format( - "{} as {}: at {}:{} end of route.", - pVehicle->asName, TrainParams.TrainName, simulation::Time.data().wHour, simulation::Time.data().wMinute)); // informacja -#endif - asNextStop = TrainParams.NextStop(); // informacja o końcu trasy - TrainParams.NewName("none"); // czyszczenie nieaktualnego rozkładu - // koniec kursu, gasimy wyświetlacze relacji (tablice blaszane zostają) - for( auto *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { - vehicle->DestinationClear(); - } - // ma nie podjeżdżać pod W4 i ma je pomijać - drivingFlags.stopCloser = false; - if( false == drivingFlags.pushPull ) { - // if the consist can change direction through a simple cab change it doesn't need fiddling with recognition of passenger stops - drivingFlags.stopPoint = false; - } - fLastStopExpDist = -1.0f; // nie ma rozkładu, nie ma usuwania stacji - Point.ResetFlags(); // W4 nie liczy się już (nie wyśle SetVelocity) - Point.fVelNext = -1; // można jechać za W4 - if( Point.fDist <= 0.0 && eSignNext == Point.evEvent ) { - // sanity check, if we're held by this stop point, let us go - VelSignalLast = -1; - } - // wykonanie kolejnego rozkazu (Change_direction albo Shunt) - JumpToNextOrder(); - // ma się nie ruszać aż do momentu podania sygnału - drivingFlags.stopHere = true; - drivingFlags.startHorn = true; - return true; // nie analizować prędkości - } // koniec obsługi ostatniej stacji - } // vel 0, at passenger stop - else { - // HACK: momentarily deactivate W4 to trick the controller into moving closer - Point.fVelNext = -1; - } // vel 0, outside of passenger stop - } // koniec obsługi zatrzymania na W4 - } // koniec warunku pomijania W4 podczas zmiany czoła - else - { // skoro pomijanie, to jechać i ignorować W4 - Point.ResetFlags(); // W4 nie liczy się już (nie zatrzymuje jazdy) - Point.fVelNext = -1; - return true; // nie analizować prędkości - } - - return false; // -} - -// a road speed sign (W27/W27a) passed by the head stays in the table until the rear is past it too. not for cars: their -// passed events leave the table at the latest when the rear passes them (TableCheck), before the table update sees that -bool -TController::is_road_velocity_held( TSpeedPos const &Point ) const { - - return Point.flags.HasAll(SpeedPointFlag::roadSpeed) - && mvOccupied->CategoryFlag != 2 - && Point.fDist >= -fLength; -} - -// a passed event is handled once and then dropped from the table, except a road speed sign held for the rear -void -TController::TableDropPassedEvent( TSpeedPos &Point ) const { - - if( is_road_velocity_held( Point ) ) { - Point.flags |= SpeedPointFlag::roadSpeedHeld; - return; - } - Point.Clear(); -} - -// the lowest road speed of the signs past the given one that the head has passed: held until the rear is past them too, -// or passed in this very tick and not marked as held yet; -1 if there's none -double -TController::held_road_velocity_beyond( TSpeedPos const &Point ) const { - - auto lowest { -1.0 }; - for( auto const &held : sSpeedTable ) { - if( ( held.flags & ( SpeedPointFlag::enabled | SpeedPointFlag::roadSpeed ) ) != ( SpeedPointFlag::enabled | SpeedPointFlag::roadSpeed ) - || held.fDist >= 0.0 - || held.fDist <= Point.fDist ) { - continue; - } - lowest = min_speed( lowest, held.fVelNext ); - } - return lowest; -} - -// a road speed (W27/W27a) lower than the one in force holds once the head passes the sign, a higher one only once the -// whole train is past it (a car takes it from the head). the first pass after the head handles the sign as before, the -// entry is then only held for the rear: returns true for it, so the rest of the table update leaves it out -bool -TController::TableUpdateRoadVelocity( TSpeedPos &Point ) { - - if( Point.fDist >= 0.0 ) { return false; } - - if( mvOccupied->CategoryFlag == 2 ) { - VelRoad = Point.fVelNext; - return false; - } - - auto const isrearpast { Point.fDist < -fLength }; - if( isrearpast ) { - // the rear past it, but not past a sign after it the head has passed too: none of those may be exceeded, so a - // lower one (W27a 60 within a train's length after a 120) stays in force - VelRoad = min_speed( Point.fVelNext, held_road_velocity_beyond( Point ) ); - } - else if( Point.fVelNext == min_speed( Point.fVelNext, VelRoad ) ) { - VelRoad = Point.fVelNext; - } - if( false == Point.flags.HasAll(SpeedPointFlag::roadSpeedHeld) ) { - return false; - } - if( isrearpast ) { - Point.Clear(); - } - return true; -} - -// a reduced speed shown by a signal holds to the end of the interlocking area the signal guards (Ie-1), and that end is -// marked on the main track with a SignalAreaEnd event. on a track without the marker the speed holds as it did before: -// until the next signal, or until no signal, switch or stop point is left in the scan -void -TController::TableUpdateSignalAreaEnd( TSpeedPos &Point ) { - - // the switches lie in front of the marker, so the whole train has left them once its rear end is past it - if( Point.fDist >= -fLength ) { - if( SignalAreaEndDist < 0.0 - && OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { - // the table is sorted by distance, so the first marker is the nearest one - SignalAreaEndDist = Point.fDist + fLength; - } - return; - } - - // in shunting the marker stays, a train order given before the next signal still finds it - if( false == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { return; } - - // a passed signal at stop (0) keeps holding the train, only a reduced speed ends here - if( VelSignalLast > 0.0 ) { - if( Global.iWriteLogEnabled & 8 ) { - WriteLog( "Speed table update for " + OwnerName() + ", left the interlocking area at " + Point.evEvent->m_name ); - } - VelSignalLast = -1.0; - } - Point.Clear(); -} - -bool TController::point_limit_latched( basic_event const *Cell ) const { - - return std::any_of( - m_pointlimits.begin(), m_pointlimits.end(), - [&]( point_limit const &Limit ) { return Limit.source == Cell; } ); -} - -double TController::point_limit_end( glm::dvec3 const &Heading ) const { - - auto const origin { pVehicle->GetPosition() }; - auto result { 0.0 }; - auto first { true }; - for( auto const *vehicle : { pVehicles[ end::front ], pVehicles[ end::rear ] } ) { - if( vehicle == nullptr ) { continue; } - for( auto const side : { end::front, end::rear } ) { - auto const along { glm::dot( vehicle->CouplerPosition( side ) - origin, Heading ) }; - result = ( first ? along : std::max( result, along ) ); - first = false; - } - } - return result; -} - -void TController::latch_point_limit( TSpeedPos const &Point ) { - - if( point_limit_latched( Point.evEvent ) ) { return; } - m_pointlimits.push_back( - point_limit { Point.evEvent, Point.fVelNext, Point.fDist + Point.fPointDist, Point.fPointDist, travel_direction() } ); - if( Global.iWriteLogEnabled & 8 ) { - WriteLog( "Speed table update for " + OwnerName() + ", latched point limit of " + Point.evEvent->m_name - + ": " + to_string( Point.fVelNext, 0 ) + " in " + to_string( m_pointlimits.back().distance, 0 ) + " m" ); - } -} - -void TController::update_point_limits() { - - if( pVehicle == nullptr ) { return; } - auto const position { pVehicle->GetPosition() }; - if( m_pointlimitsvehicle == pVehicle ) { - auto const movement { position - m_pointlimitsposition }; - auto const length { glm::length( movement ) }; - if( length >= 200.0 ) { - // a longer jump between two updates isn't driving: the consist was moved elsewhere - m_pointlimits.clear(); - } - else if( length > 0.0 ) { - auto const step { movement / length }; - for( auto &limit : m_pointlimits ) { - if( glm::length( limit.heading ) < 0.5 ) { - // the way wasn't known when the limit was latched, the head was passing the cell - limit.heading = step; - } - auto const along { glm::dot( step, limit.heading ) }; - limit.distance += ( along >= 0.0 ? -length : length ); - // the way towards the point follows the line, step by step; a step far off it - // (a jolt of a standing vehicle) doesn't turn it - if( std::abs( along ) > 0.5 ) { - limit.heading = ( along >= 0.0 ? step : -step ); - } - } - } - } - // a change of the vehicle (another cab) starts the measure from its place - auto const vehiclechanged { m_pointlimitsvehicle != pVehicle }; - auto const previousposition { m_pointlimitsposition }; - m_pointlimitsvehicle = pVehicle; - m_pointlimitsposition = position; - // the consist, as its end vehicles and its length - auto const *front { pVehicles[ end::front ] }; - auto const *rear { pVehicles[ end::rear ] }; - auto const consistchanged { - false == ( ( front == m_pointlimitsends[ 0 ] && rear == m_pointlimitsends[ 1 ] ) - || ( front == m_pointlimitsends[ 1 ] && rear == m_pointlimitsends[ 0 ] ) ) - || std::abs( fLength - m_pointlimitslength ) > 0.5 }; - m_pointlimitsends[ 0 ] = front; - m_pointlimitsends[ 1 ] = rear; - m_pointlimitslength = fLength; - // vehicles coupled or uncoupled at the end towards the point move the head towards it or away. only a change of - // the consist counts, as the end measured from the vehicle shifts on curves. another vehicle measured from (a cab - // change, which may come with a coupling in the same order) moves the end measured before to its place - for( auto &limit : m_pointlimits ) { - if( glm::length( limit.heading ) < 0.5 ) { continue; } - auto const consistend { point_limit_end( limit.heading ) }; - if( limit.endknown && consistchanged ) { - auto const previousend { - vehiclechanged ? - limit.end + glm::dot( previousposition - position, limit.heading ) : - limit.end }; - limit.distance -= consistend - previousend; - } - limit.end = consistend; - limit.endknown = true; - } - - auto const travel { travel_direction() }; - std::erase_if( - m_pointlimits, - [&]( point_limit const &Limit ) { - // passed by the head - if( Limit.distance < 0.0 ) { - if( Global.iWriteLogEnabled & 8 ) { - WriteLog( "Speed table update for " + OwnerName() + ", passed point limit of " + Limit.source->m_name ); - } - return true; - } - // the head backed up behind the cell: the speed table reads it again if it is ahead - if( Limit.distance > Limit.celldistance + 1.0 ) { - if( Global.iWriteLogEnabled & 8 ) { - WriteLog( "Speed table update for " + OwnerName() + ", left behind point limit of " + Limit.source->m_name ); - } - return true; - } - // the cell ahead of the head again, going towards the point after backing up past the cell: it is read anew - // (not while backing up: the cell may as well be scanned from the other side) - return glm::dot( travel, Limit.heading ) > 0.0 - && std::any_of( - sSpeedTable.begin(), sSpeedTable.end(), - [&]( TSpeedPos const &Point ) { - return Point.evEvent == Limit.source - && Point.flags.HasAll(SpeedPointFlag::enabled | SpeedPointFlag::event | SpeedPointFlag::pointSpeed) - && Point.fDist > 0.0; } ); } ); -} - -void TController::apply_point_limits( double &Velocity, double &Distance, double &Next, double &Acceleration ) { - - auto const travel { travel_direction() }; - for( auto const &limit : m_pointlimits ) { - // latched with no limit, or passed (dropped at the next update) - if( limit.velocity < 0.0 || limit.distance <= 0.0 ) { continue; } - // going away from the point, or the way isn't known - if( glm::dot( travel, limit.heading ) <= 0.0 ) { continue; } - // the same as for a point of the speed table ahead - auto const v { limit.velocity }; - auto const d { limit.distance }; - auto a { ( v * v - mvOccupied->Vel * mvOccupied->Vel ) / ( 25.92 * d ) }; - if( mvOccupied->Vel < v ) { - auto const brakingdistance { 1.2 * fBrakeDist * braking_distance_multiplier( v ) }; - if( brakingdistance > 0.0 ) { - a = std::lerp( a, AccPreferred, std::clamp( ( d - brakingdistance ) / brakingdistance, 0.0, 1.0 ) ); - } - } - if( d < point_limit_approach() && v < Velocity ) { - Velocity = v; - } - if( a <= Acceleration - && ( v < Next || Next < 0 ) ) { - Acceleration = a; - Next = v; - Distance = d; - bStopTargetIsPassengerStop = false; - } - } -} - -double TController::point_limit_approach() const { - // a point limit holds at its point and not a metre beyond, so the braking curve alone leaves a slow consist - // coasting above it (the deceleration asked for is below what makes the driver brake). within the final - // approach, and five seconds of the present speed before it, the speed is held down to it already - return fMaxProximityDist + mvOccupied->Vel / 3.6 * 5.0; -} - -glm::dvec3 TController::travel_direction() const { - - if( pVehicle == nullptr || iDirection == 0 ) { return glm::dvec3 { 0.0 }; } - // the direction is given against the couplers of the vehicle the driver is in, which is the vehicle measured; - // along its own length it follows the track, where the chord of a long consist on a curve doesn't - auto const along { pVehicle->CouplerPosition( end::front ) - pVehicle->CouplerPosition( end::rear ) }; - auto const length { glm::length( along ) }; - if( length < 0.001 ) { return glm::dvec3 { 0.0 }; } - return ( iDirection > 0 ? along : -along ) / length; -} - -bool -TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPos &Point, double &Signaldistance, int const Pointindex ) { - - if( Point.flags.HasAll(SpeedPointFlag::signalAreaEnd) ) { - // not a signal: it neither sends a command nor counts as the end of a speed limit in the scan - TableUpdateSignalAreaEnd( Point ); - return true; - } - - if( Point.flags.HasAll(SpeedPointFlag::pointSpeed) ) { - // PointVelocity: no signal, no command, only the limit at its point - // done once the head passes the point - if( Point.fDist + Point.fPointDist < 0.0 ) { - if( Global.iWriteLogEnabled & 8 ) { - WriteLog( "Speed table update for " + OwnerName() + ", passed point limit of " + Point.GetName() ); - } - Point.Clear(); - return true; - } - if( Point.fDist < 0.0 ) { - if( point_limit_latched( Point.evEvent ) ) { - // a table built anew found under the consist a cell whose state holds already - Point.Clear(); - return true; - } - if( Point.fVelNext != 0.0 ) { - // the head passed the cell: what it says now holds at the point, whatever happens to the table. - // a stop at 0 stays in the table, where the cell can still release it - latch_point_limit( Point ); - Point.Clear(); - return true; - } - } - return false; - } - - // sprawdzanie eventów pasywnych miniętych - if( Point.fDist < 0.0 ) { - if( SemNextIndex == Pointindex ) { - if( Global.iWriteLogEnabled & 8 ) { - WriteLog( "Speed table update for " + OwnerName() + ", passed semaphor " + sSpeedTable[ SemNextIndex ].GetName() ); - } - SemNextIndex = npos; // jeśli minęliśmy semafor od ograniczenia to go kasujemy ze zmiennej sprawdzającej dla skanowania w przód - } - if( SemNextStopIndex == Pointindex ) { - if( Global.iWriteLogEnabled & 8 ) { - WriteLog( "Speed table update for " + OwnerName() + ", passed semaphor " + sSpeedTable[ SemNextStopIndex ].GetName() ); - } - SemNextStopIndex = npos; // jeśli minęliśmy semafor od ograniczenia to go kasujemy ze zmiennej sprawdzającej dla skanowania w przód - } - switch( Point.evEvent->input_command() ) { - // TBD, TODO: expand emergency_brake handling to a more generic security system signal - case TCommandType::cm_EmergencyBrake: { - pVehicle->RadioStop(); - Point.Clear(); // signal received, deactivate - return true; - } - case TCommandType::cm_SecuritySystemMagnet: { - // NOTE: magnet induction calculation presumes the driver is located in the front vehicle - // TBD, TODO: take into account actual position of controlled/occupied vehicle in the consist, whichever comes first - auto const magnetlocation { pVehicles[ end::front ]->MoverParameters->SecuritySystem.MagnetLocation }; - auto const magnetrange { 1.0 }; - auto const ismagnetpassed { Point.fDist < -( magnetlocation + magnetrange ) }; - if( Point.fDist < -magnetlocation && (mvOccupied->Vel > EU07_AI_NOMOVEMENT || false == ismagnetpassed) ) { - // NOTE: normally we'd activate the magnet once the leading vehicle passes it - // but on a fresh scan after direction change it would be detected as long as it's under consist, and meet the (simple) activation condition - // thus we're doing a more precise check in such situation (we presume direction change takes place only if the vehicle is standing still) - mvOccupied->SecuritySystem.set_cabsignal_lock(!AIControllFlag); // don't make life difficult for the ai, but a human driver is a fair game - PutCommand(Point.evEvent->input_text(), Point.evEvent->input_value(1), Point.evEvent->input_value(2), nullptr); - } - if( ismagnetpassed ) { - Point.Clear(); - mvOccupied->SecuritySystem.set_cabsignal_lock(false); - } - return true; - } - default: { - break; - } - } - } - // check signals ahead - if( Point.fDist > 0.0 ) { - // bail out early for signals which activate when passed - // TBD: make it an event method? - switch( Point.evEvent->input_command() ) { - case TCommandType::cm_EmergencyBrake: { - return true; - } - case TCommandType::cm_SecuritySystemMagnet: { - return true; - } - default: { - break; - } - } - - if( Point.IsProperSemaphor( OrderCurrentGet() ) ) { - // special rule for cars: ignore stop signals at distance too short to come to a stop - // as trying to stop in such situation is likely to place the car on train tracks - if( is_car() - && Point.fVelNext != -1.0 - && Point.fVelNext < 1.0 - && Point.fDist < -0.5 + std::min(fBrakeDist * 0.2, mvOccupied->Vel * 0.2) ) { - Point.Clear(); - return true; - } - // jeśli jest mienięty poprzedni semafor a wcześniej - // byl nowy to go dorzucamy do zmiennej, żeby cały czas widział najbliższy - if( SemNextIndex == npos ) { // NOSONAR - SemNextIndex = Pointindex; - if( Global.iWriteLogEnabled & 8 ) { - WriteLog( "Speed table update for " + OwnerName() + ", next semaphor is " + sSpeedTable[ SemNextIndex ].GetName() ); - } - } - if( SemNextStopIndex == npos - || ( sSpeedTable[SemNextStopIndex].fVelNext != 0 - && Point.fVelNext == 0 ) ) { - SemNextStopIndex = Pointindex; - } - } - } - if (Point.flags & SpeedPointFlag::outsideStation) - { // jeśli W5, to reakcja zależna od trybu jazdy - if (OrderCurrentGet() & DriverOrder::obeyTrain) - { // w trybie pociągowym: można przyspieszyć do wskazanej prędkości (po zjechaniu z rozjazdów) - Velocity = -1.0; // ignorować? - if ( Point.fDist < 0.0) { // jeśli wskaźnik został minięty - VelSignalLast = Velocity; //ustawienie prędkości na -1 - } - else if( ( false == drivingFlags.switchFound ) ) { // jeśli rozjazdy już minięte - VelSignalLast = Velocity; //!!! to też koniec ograniczenia - } - } - else - { // w trybie manewrowym: skanować od niego wstecz, stanąć po wyjechaniu za sygnalizator i zmienić kierunek - Velocity = 0.0; // zmiana kierunku może być podanym sygnałem, ale wypadało by zmienić światło wcześniej - if( ( false == drivingFlags.switchFound ) ) { // jeśli nie ma rozjazdu - // check for presence of a signal facing the opposite direction - // if there's one, we'll want to pass it before changing direction - basic_event *foundevent = nullptr; - if( Point.fDist - fMaxProximityDist > 0 ) { - auto scandistance{ Point.fDist + fLength - fMaxProximityDist }; - auto *scanvehicle{ pVehicles[ end::rear ] }; - auto scandirection{ scanvehicle->DirectionGet() * scanvehicle->RaDirectionGet() }; - auto *foundtrack = BackwardTraceRoute( scandistance, scandirection, scanvehicle, foundevent, -1, end::front, false ); - } - if( foundevent == nullptr ) { - drivingFlags.trackEnd = true; // to dalsza jazda trwale ograniczona (W5, koniec toru) - } - } - } - } - else if ( Point.flags & SpeedPointFlag::stopOnAutomaticBlock) { - // jeśli S1 na SBL - if( mvOccupied->Vel < 2.0 && Point.fDist < fMaxProximityDist && Obstacle.distance > 1000 ) { - // stanąć nie musi, ale zwolnić przynajmniej - // jest w maksymalnym zasięgu to można go pominąć (wziąć drugą prędkosć) - // as long as there isn't any obstacle in arbitrary view range - eSignSkip = Point.evEvent; - // jazda na widoczność - skanować możliwość kolizji i nie podjeżdżać zbyt blisko - // usunąć flagę po podjechaniu blisko semafora zezwalającego na jazdę - // ostrożnie interpretować sygnały - semafor może zezwalać na jazdę pociągu z przodu! - drivingFlags.visibility = true; - // store the ordered restricted speed and don't exceed it until the flag is cleared - VelRestricted = Point.evEvent->input_value(2); - } - if( eSignSkip != Point.evEvent ) { - // jeśli ten SBL nie jest do pominięcia to ma 0 odczytywać - Velocity = Point.evEvent->input_value( 1 ); - // TODO sprawdzić do której zmiennej jest przypisywane v i zmienić to tutaj - } - } - else if ( Point.IsProperSemaphor(OrderCurrentGet())) - { // to semaphor - if( Point.fDist < 0 ) { - // for human-driven vehicles ignore the signal if it was passed by sufficient distance - if( false == AIControllFlag - && Point.fDist < -1 * std::max(fLength + 100, 250.0) ) { - VelSignal = -1.0; - Point.Clear(); - return true; - } - // for ai-driven vehicles always play by the rules - else { - VelSignalLast = Point.fVelNext; //minięty daje prędkość obowiązującą - // a marker before this signal ends the interlocking area of an earlier signal, not the area of this one - // (a train longer than the way between the two, or one which started standing over the marker) - std::ranges::for_each( sSpeedTable | std::views::take( Pointindex ), clear_signal_area_end ); - } - } - else { - //jeśli z przodu to dajemy flagę, że jest - drivingFlags.signalFound = true; - Signaldistance = std::min( Point.fDist, Signaldistance ); - // if there's another vehicle closer to the signal, then it's likely its intended recipient - // HACK: if so, make it a stop point, to prevent non-signals farther down affect us - auto const isforsomeoneelse { is_train() && Obstacle.distance < Point.fDist }; - if( Point.fDist <= Signaldistance ) { - if( isforsomeoneelse ) { - VelSignalNext = 0.0; - Velocity = 0.0; - } - else { - VelSignalNext = Point.fVelNext; - if( Velocity < 0 ) { - Velocity = fVelMax; - VelSignal = fVelMax; - } - } - } - } - } - else if ( Point.flags & SpeedPointFlag::roadSpeed) - { // to W27/W27a - if( TableUpdateRoadVelocity( Point ) ) { - return true; - } - } - else if ( Point.flags & SpeedPointFlag::sectionSpeed && Point.fDist < 0) - { // to W9 - // teraz trzeba sprawdzić inne warunki - if (Point.fSectionVelocityDist == 0.0) - { - if (Global.iWriteLogEnabled & 8) - { - WriteLog("TableUpdate: Event is behind. SVD = 0: " + Point.evEvent->m_name); - } - Point.Clear(); // jeśli punktowy to kasujemy i nie dajemy ograniczenia na stałe - } - else if (Point.fSectionVelocityDist < 0.0) - { - // ograniczenie obowiązujące do następnego - if (Point.fVelNext == min_speed(Point.fVelNext, VelLimitLast) && Point.fVelNext != VelLimitLast) - { - // jeśli ograniczenie jest mniejsze niż obecne to obowiązuje od zaraz - VelLimitLast = Point.fVelNext; - } - else if (Point.fDist < -fLength) - { - // jeśli większe to musi wyjechać za poprzednie - VelLimitLast = Point.fVelNext; - if (Global.iWriteLogEnabled & 8) - { - WriteLog("TableUpdate: Event is behind. SVD < 0: " + Point.evEvent->m_name); - } - Point.Clear(); // wyjechaliśmy poza poprzednie, można skasować - } - } - else - { // jeśli większe to ograniczenie ma swoją długość - if (Point.fVelNext == min_speed(Point.fVelNext, VelLimitLast) && Point.fVelNext != VelLimitLast) - { - // jeśli ograniczenie jest mniejsze niż obecne to obowiązuje od zaraz - VelLimitLast = Point.fVelNext; - } - else if (Point.fDist < -fLength && Point.fVelNext != VelLimitLast) - { - // jeśli większe to musi wyjechać za poprzednie - VelLimitLast = Point.fVelNext; - } - else if (Point.fDist < -fLength - Point.fSectionVelocityDist) - { - VelLimitLast = -1.0; - if (Global.iWriteLogEnabled & 8) - { - WriteLog("TableUpdate: Event is behind. SVD > 0: " + Point.evEvent->m_name); - } - Point.Clear(); // wyjechaliśmy poza poprzednie, można skasować - } - } - } - - //sprawdzenie eventów pasywnych przed nami - { // zawalidrogi nie ma (albo pojazd jest samochodem), sprawdzić sygnał - if ( Point.flags & SpeedPointFlag::shuntSignal) // jeśli Tm - w zasadzie to sprawdzić komendę! - { // jeśli podana prędkość manewrowa - if( Velocity == 0.0 - && true == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { - // jeśli tryb pociągowy a tarcze ma ShuntVelocity 0 0 - Velocity = -1; // ignorować, chyba że prędkość stanie się niezerowa - if( true == Point.flags.HasAll(SpeedPointFlag::elapsed) ) { - // a jak przejechana to można usunąć, bo podstawowy automat usuwa tylko niezerowe - Point.Clear(); - } - } - else if( Command == TCommandType::cm_Unknown && Velocity != 0.0 ) { - // jeśli jeszcze nie ma komendy - // komenda jest tylko gdy ma jechać, bo stoi na podstawie tabelki - // jeśli nie było komendy wcześniej - pierwsza się liczy - ustawianie VelSignal - Command = TCommandType::cm_ShuntVelocity; // w trybie pociągowym tylko jeśli włącza tryb manewrowy (v!=0.0) - // Ra 2014-06: (VelSignal) nie może być tu ustawiane, bo Tm może być daleko - if (VelSignal == 0.0) - { - // aby stojący ruszył - VelSignal = Velocity; - } - if (Point.fDist < 0.0) - { - // jeśli przejechany - //!!! ustawienie, gdy przejechany jest lepsze niż wcale, ale to jeszcze nie to - VelSignal = Velocity; - // to można usunąć (nie mogą być usuwane w skanowaniu) - Point.Clear(); - } - } - } - else if( false == Point.flags.HasAny(SpeedPointFlag::sectionSpeed) ) { - //jeśli jakiś event pasywny ale nie ograniczenie - if( Command != TCommandType::cm_Unknown ) - { - } - else - { - // jeśli nie było komendy wcześniej - pierwsza się liczy - ustawianie VelSignal - if (Velocity < 0.0 || Velocity >= 1.0) - { - // bo wartość 0.1 służy do hamowania tylko - Command = TCommandType::cm_SetVelocity; // może odjechać - // Ra 2014-06: (VelSignal) nie może być tu ustawiane, bo semafor może być daleko - // VelSignal=v; //nie do końca tak, to jest druga prędkość; -1 nie wpisywać... - if (VelSignal == 0.0) - { - // aby stojący ruszył - VelSignal = -1.0; - } - if (Point.fDist < 0.0) - { - // jeśli przejechany - VelSignal = Velocity == 0.0 ? 0.0 : -1.0; - // ustawienie, gdy przejechany jest lepsze niż wcale, ale to jeszcze nie to - if (Point.flags & SpeedPointFlag::event && (Point.evEvent != eSignSkip || Point.fVelNext != VelRestricted)) - { - // jeśli event - // ale inny niż ten, na którym minięto S1, chyba że się już zmieniło - // sygnał zezwalający na jazdę wyłącza jazdę na widoczność (po S1 na SBL) - drivingFlags.visibility = false; - // remove restricted speed - VelRestricted = -1.0; - } - // jeśli nie jest ograniczeniem prędkości to można usunąć - // (nie mogą być usuwane w skanowaniu) - TableDropPassedEvent( Point ); - } - } - else if (Point.fDist > 0.0 && typeid(*Point.evEvent) == typeid(road_order)) - { - // a level crossing or a junction which holds the vehicle ahead: the road orders past it, which let the traffic - // through, aren't for this vehicle yet. without this the first of them would tell the standing vehicle to drive on - Command = TCommandType::cm_SetProximityVelocity; // taken, and not acted on - } - else if (Point.evEvent->is_command()) - { - // jeśli prędkość jest zerowa, a komórka zawiera komendę - eSignNext = Point.evEvent; // dla informacji - // make sure the command isn't for someone else - // TBD, TODO: revise this check for bank/loose_shunt; we might want to ignore obstacles with no owner in these modes - if (Point.fDist < Obstacle.distance) - { - if (true == drivingFlags.stopHere) - { - // jeśli ma stać, dostaje komendę od razu - Command = TCommandType::cm_Command; // komenda z komórki, do wykonania po zatrzymaniu - } - // NOTE: human drivers are likely to stop wherever and expect things to still work, so we give them more leeway - else if (Point.fDist <= (AIControllFlag ? fMaxProximityDist : std::max(250.0, fMaxProximityDist))) - { - // jeśli ma dociągnąć, to niech dociąga - // (moveStopCloser dotyczy dociągania do W4, nie semafora) - Command = TCommandType::cm_Command; // komenda z komórki, do wykonania po zatrzymaniu - } - } - } - } - } - } // jeśli nie ma zawalidrogi - - return false; -} - -// modifies brake distance for low target speeds, to ease braking rate in such situations -float -TController::braking_distance_multiplier( float const Targetvelocity ) const { - - auto const frictionmultiplier { 1.f / Global.FrictionWeatherFactor }; - - if( Targetvelocity > 65.f ) { return 1.f * frictionmultiplier; } - if( Targetvelocity < 5.f ) { - // HACK: engaged automatic transmission means extra/earlier braking effort is needed for the last leg before full stop - if( is_dmu() - && mvOccupied->Vel < 40.0 - && Targetvelocity == 0.f ) { - auto const multiplier { std::clamp( 1.f + iVehicles * 0.5f, 2.f, 4.f ) }; - return std::lerp(multiplier, 1.f, static_cast(mvOccupied->Vel / 40.0)) * frictionmultiplier; - } - // HACK: cargo trains or trains going downhill with high braking threshold need more distance to come to a full stop - if( fBrake_a0[1] > 0.2 - && ( true == IsCargoTrain - || fAccGravity > 0.025 ) ) { - return std::lerp(1.f, 2.f, std::clamp((fBrake_a0[1] - 0.2) / 0.2, 0.0, 1.0)) * frictionmultiplier; - } - - return 1.f * frictionmultiplier; - } - // stretch the braking distance up to 3 times; the lower the speed, the greater the stretch - return std::lerp(3.f, 1.f, (Targetvelocity - 5.f) / 60.f) * frictionmultiplier; -} - -void TController::TablePurger() -{ // odtykacz: usuwa mniej istotne pozycje ze środka tabelki, aby uniknąć zatkania - //(np. brak ograniczenia pomiędzy zwrotnicami, usunięte sygnały, minięte odcinki łuku) - if( sSpeedTable.size() < 2 ) { - return; - } - // simplest approach should be good enough for start -- just copy whatever is still relevant, then swap - auto const isexpendable = []( TSpeedPos const &Speedpoint ) { - return - false == Speedpoint.flags.HasAny( SpeedPointFlag::enabled ) - || ( ( Speedpoint.flags & ( SpeedPointFlag::elapsed | SpeedPointFlag::track | SpeedPointFlag::curve | SpeedPointFlag::switchTrack ) ) == ( SpeedPointFlag::elapsed | SpeedPointFlag::track | SpeedPointFlag::curve ) - && Speedpoint.fVelNext < 0.0 ); }; - // do a trial run first, to see if we need to bother at all - std::size_t trimcount{ 0 }; - for( std::size_t idx = 0; idx < sSpeedTable.size() - 1; ++idx ) { - // NOTE: we could break out early here, but running through entire thing gives us exact size needed for new table - if( isexpendable( sSpeedTable[ idx ] ) ) { - ++trimcount; - } - } - if( trimcount == 0 ) { - // there'd be no gain, may as well bail - return; - } - std::vector trimmedtable; trimmedtable.reserve( sSpeedTable.size() - trimcount ); - // the indices are only valid for the old table, so the new placements are recorded separately - // and assigned once the new table is complete - auto semnextindex { std::size_t( -1 ) }; - auto semnextstopindex { std::size_t( -1 ) }; - auto const trackplacement = [&]( std::size_t const Index, bool const Kept ) { - // a trimmed point leaves the index invalid, a kept one lands where the new table ends - if( Index == SemNextIndex ) { - semnextindex = ( Kept ? trimmedtable.size() : std::size_t( -1 ) ); - } - if( Index == SemNextStopIndex ) { - semnextstopindex = ( Kept ? trimmedtable.size() : std::size_t( -1 ) ); - } }; - - for( std::size_t idx = 0; idx < sSpeedTable.size() - 1; ++idx ) { - auto const &speedpoint = sSpeedTable[ idx ]; - auto const kept { false == isexpendable( speedpoint ) }; - trackplacement( idx, kept ); - if( false == kept ) { continue; } - // we're left with useful speed point record we should copy - trimmedtable.emplace_back( speedpoint ); - } - // always copy the last entry; an index pointing at it has to follow it as well - trackplacement( sSpeedTable.size() - 1, true ); - trimmedtable.emplace_back( sSpeedTable.back() ); - - SemNextIndex = semnextindex; - SemNextStopIndex = semnextstopindex; - - if( Global.iWriteLogEnabled & 8 ) { - WriteLog( "Speed table garbage collection for " + OwnerName() + " cut away " + std::to_string( trimcount ) + ( trimcount == 1 ? " record" : " records" ) ); - } - // update the data - std::swap( sSpeedTable, trimmedtable ); - iLast = sSpeedTable.size() - 1; -}; - -void TController::TableSort() { - - if( sSpeedTable.size() < 3 ) { - // we skip last slot and no point in checking if there's only one other entry - return; - } - // the last slot holds the track the scan stopped at and stays where it is. - // a single bubble pass is not enough: TableTraceRoute() adds the events of a track before the - // track itself, so a track with k scanned events lands k places too far and needs k passes - auto const sortedcount { static_cast( iLast ) }; - auto const inrange = [&]( std::size_t const Index ) { - return Index < sortedcount; }; - // the placements point at semaphor entries; remember which ones, the sort moves them around - auto const *semnextevent { inrange( SemNextIndex ) ? sSpeedTable[ SemNextIndex ].evEvent : nullptr }; - auto const *semnextstopevent { inrange( SemNextStopIndex ) ? sSpeedTable[ SemNextStopIndex ].evEvent : nullptr }; - - std::stable_sort( - std::begin( sSpeedTable ), std::begin( sSpeedTable ) + sortedcount, - []( TSpeedPos const &Left, TSpeedPos const &Right ) { - return Left.fDist < Right.fDist; } ); - - auto const relocate = [&]( basic_event const *Event, std::size_t &Index ) { - if( Event == nullptr ) { return; } - auto const lookup { - std::find_if( - std::begin( sSpeedTable ), std::begin( sSpeedTable ) + sortedcount, - [Event]( TSpeedPos const &Point ) { - return Point.evEvent == Event; } ) }; - Index = ( - lookup != std::begin( sSpeedTable ) + sortedcount ? - static_cast( std::distance( std::begin( sSpeedTable ), lookup ) ) : - std::size_t( -1 ) ); - }; - relocate( semnextevent, SemNextIndex ); - relocate( semnextstopevent, SemNextStopIndex ); -} - -//--------------------------------------------------------------------------- - -TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, bool Primary) :// czy ma aktywnie prowadzić? - AIControllFlag( AI ), pVehicle( NewControll ) -{ - if( pVehicle != nullptr ) { - pVehicles[ end::front ] = pVehicle->GetFirstDynamic( end::front ); // pierwszy w kierunku jazdy (Np. Pc1) - pVehicles[ end::rear ] = pVehicle->GetFirstDynamic( end::rear ); // ostatni w kierunku jazdy (końcówki) - } - else { - pVehicles[ end::front ] = nullptr; - pVehicles[ end::rear ] = nullptr; - } - ControllingSet(); // utworzenie połączenia do sterowanego pojazdu - if( mvOccupied != nullptr ) { - iDirectionOrder = mvOccupied->CabActive; // 1=do przodu (w kierunku sprzęgu 0) - VehicleName = mvOccupied->Name; - - if( is_car() ) { // samochody: na podst. http://www.prawko-kwartnik.info/hamowanie.html - // fDriverBraking=0.0065; //mnożone przez (v^2+40*v) [km/h] daje prawie drogę hamowania [m] - fDriverBraking = 0.03; // coś nie hamują te samochody zbyt dobrze - fDriverDist = 5.0; // 5m - zachowywany odstęp przed kolizją - fVelPlus = 10.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania - fVelMinus = 2.0; // margines prędkości powodujący załączenie napędu - } - else { // pociągi i statki - fDriverBraking = 0.06; // mnożone przez (v^2+40*v) [km/h] daje prawie drogę hamowania [m] - fDriverDist = 50.0; // 50m - zachowywany odstęp przed kolizją - fVelPlus = 5.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania - fVelMinus = 5.0; // margines prędkości powodujący załączenie napędu - } - - // fAccThreshold może podlegać uczeniu się - hamowanie powinno być rejestrowane, a potem analizowane - // próg opóźnienia dla zadziałania hamulca - fAccThreshold = is_emu() ? -0.55 : is_dmu() ? -0.45 : -0.2; -/* - // HACK: emu with induction motors need to start their braking a bit sooner than the ones with series motors - if( ( mvOccupied->TrainType == train_type::emu ) - && ( mvControlling->EngineType == TEngineType::ElectricInductionMotor ) ) { - fAccThreshold += 0.10; - } -*/ - } - // TrainParams=NewTrainParams; - // if (TrainParams) - // asNextStop=TrainParams.NextStop(); - // else - TrainParams = TTrainParameters("none"); // rozkład jazdy - // OrderCommand=""; - // OrderValue=0; - OrdersClear(); - - if( true == Primary ) { - drivingFlags.primary = true; // aktywnie prowadzące pojazd - } - - if( mvOccupied != nullptr ) { - SetDriverPsyche(); // na końcu, bo wymaga ustawienia zmiennych - } - TableClear(); - - // the logs of all, begun at once as they always were. one of a train only at its first line (update_logs): every - // crew is made primary here, and the drivers but one of a train with crews in more vehicles are made passive - // before it starts, so they get no file with only the header - if( WriteLogFlag ) { - begin_physicslog(); - } - - // HACK: give the simulation a small window to potentially replace the AI with a human driver - fActionTime = -5.0; -}; - -TController::~TController() -{ // wykopanie mechanika z roboty -}; - -// zamiana kodu rozkazu na opis -std::string TController::Order2Str(DriverOrders Order) const { - - if( Order.HasAny(DriverOrder::changeDirection) - && Order != DriverOrder::changeDirection ) { - // może być nałożona na inną i wtedy ma priorytet - return - Order2Str( DriverOrder::changeDirection ) - + " + " - + Order2Str( Order.Without(DriverOrder::changeDirection) ); - } - switch( SingleOrder( Order ) ) { - case DriverOrder::waitForOrders: return "Wait_for_orders"; - case DriverOrder::prepareEngine: return "Prepare_engine"; - case DriverOrder::releaseEngine: return "Release_engine"; - case DriverOrder::changeDirection: return "Change_direction"; - case DriverOrder::connect: return "Connect"; - case DriverOrder::disconnect: return "Disconnect"; - case DriverOrder::shunt: return "Shunt"; - case DriverOrder::looseShunt: return "Loose_shunt"; - case DriverOrder::obeyTrain: return "Obey_train"; - case DriverOrder::bank: return "Bank"; - case DriverOrder::jumpToFirstOrder: return "Jump_to_first_order"; - default: return "Undefined"; - } -} - -std::array orderbuffer; - -std::string TController::OrderCurrent() const -{ // pobranie aktualnego rozkazu celem wyświetlenia - auto const order { OrderCurrentGet() }; - // generally prioritize direction change... - if( order & DriverOrder::changeDirection && false == drivingFlags.connect ) { - // ...but not in the middle of coupling operation - return STR("Change direction"); - } - - switch( SingleOrder( order.Without(DriverOrder::changeDirection) ) ) { - case DriverOrder::waitForOrders: { return STR("Wait for orders"); } - case DriverOrder::prepareEngine: { return STR("Start the engine"); } - case DriverOrder::releaseEngine: { return STR("Shut down the engine"); } - case DriverOrder::changeDirection: { return STR("Change direction"); } - case DriverOrder::connect: { return STR("Couple to consist ahead"); } - case DriverOrder::disconnect: { - if( iVehicleCount < 0 ) { - // done with uncoupling, order should update shortly - return STR("Wait for orders"); - } - // try to provide some task details - auto const count { iVehicleCount }; - - if( iVehicleCount > 1 ) { - std::snprintf( - orderbuffer.data(), orderbuffer.size(), - STR_C("the engine plus %d next vehicles"), // TODO: implement plural forms - count ); - } - auto const countstring { ( - count == 0 ? STR("the engine") : - count == 1 ? STR("the engine plus the next vehicle") : - orderbuffer.data() ) }; - - std::snprintf( - orderbuffer.data(), orderbuffer.size(), - STR_C("Uncouple %s"), - countstring.c_str() ); - return orderbuffer.data(); - } - case DriverOrder::shunt: { return STR("Shunt according to signals"); } - case DriverOrder::looseShunt: { return STR("Loose shunt according to signals"); } - case DriverOrder::obeyTrain: { return STR("Drive according to signals and timetable"); } - case DriverOrder::bank: { return STR("Bank consist ahead"); } - default: { return{}; } - } -}; - -void TController::OrdersClear() -{ // czyszczenie tabeli rozkazów na starcie albo po dojściu do końca - OrderPos = 0; - OrderTop = 1; // szczyt stosu rozkazów - for (int b = 0; b < maxorders; b++) - OrderList[b] = DriverOrder::waitForOrders; -#if LOGORDERS - OrdersDump("OrdersClear", false); -#endif -}; - -void TController::Activation() -{ // umieszczenie obsady w odpowiednim członie, wykonywane wyłącznie gdy steruje AI - iDirection = iDirectionOrder; // kierunek (względem sprzęgów pojazdu z AI) właśnie został ustalony (zmieniony) - if (iDirection) - { // jeśli jest ustalony kierunek - auto *initialvehicle { pVehicle }; -/* - auto const initiallocalbrakelevel { mvOccupied->LocalBrakePosA }; -*/ - auto const initialspringbrakestate { mvOccupied->SpringBrake.Activate }; - // switch off tempomat - SpeedCntrl( 0.0 ); - mvControlling->DecScndCtrl( 2 ); - // reset controls - ZeroSpeed(); - ZeroDirection(); - mvOccupied->CabOccupied = mvOccupied->CabActive; // użytkownik moze zmienić CabOccupied wychodząc - mvOccupied->CabDeactivisation(); // tak jest w Train.cpp - if (pVehicle->MoverParameters->Couplers[iDirectionOrder < 0 ? end::rear : end::front].CouplingFlag.HasAll(Coupling::control)) { - ZeroLocalBrake(); - if( initialspringbrakestate ) { - mvOccupied->SpringBrakeActivate( false ); - } - // odcięcie na zaworze maszynisty, FVel6 po drugiej stronie nie luzuje - mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos(bh_NP) ); // odcięcie na zaworze maszynisty - BrakeLevelSet( mvOccupied->BrakeCtrlPos ); //ustawienie zmiennej GBH - } - // przejście AI na drugą stronę EN57, ET41 itp. - // TODO: clean this up, there's lot of redundancy with TMoverParameters::ChangeCab() and TTrain::MoveToVehicle() - { - int movedirection { ( iDirection < 0 ? end::rear : end::front ) }; - auto *targetvehicle { pVehicle->FirstFind( movedirection, Coupling::control ) }; - if( pVehicle != targetvehicle ) { - auto *targetvehicledriver { targetvehicle->Mechanik }; // zapamiętanie tego, co ewentualnie tam siedzi, żeby w razie dwóch zamienić miejscami - // move to the new vehicle - targetvehicle->Mechanik = this; // na razie bilokacja - targetvehicle->MoverParameters->SetInternalCommand(VehicleCommand::none, 0, 0); // usunięcie ewentualnie zalegającej komendy (Change_direction?) - if( targetvehicle->DirectionGet() != pVehicle->DirectionGet() ) { - // jeśli są przeciwne do siebie to będziemy jechać w drugą stronę względem zasiedzianego pojazdu - iDirection = -iDirection; - } - // move the other driver to our old vehicle - pVehicle->Mechanik = targetvehicledriver; // wsadzamy tego, co ewentualnie był (podwójna trakcja) - // NOTE: having caboccupied != 0 (by swapping in the driver from the target vehicle) may lead to dysfunctional brake - // TODO: investigate and resolve if necessary - pVehicle->MoverParameters->CabOccupied = targetvehicle->MoverParameters->CabOccupied; - if( pVehicle->Mechanik ) { // not guaranteed, as target vehicle can be empty - pVehicle->Mechanik->BrakeLevelSet( pVehicle->MoverParameters->BrakeCtrlPos ); - } - // finish driver swap - pVehicle = targetvehicle; - } - } - if (pVehicle != initialvehicle) - { // jeśli zmieniony został pojazd prowadzony - ControllingSet(); // utworzenie połączenia do sterowanego pojazdu (może się zmienić) - silnikowy dla EZT - if( mvOccupied->BrakeCtrlPosNo > 0 - && ( BrakeSystem == TBrakeSystem::Pneumatic - || BrakeSystem == TBrakeSystem::ElectroPneumatic ) ) { - mvOccupied->LimPipePress = mvOccupied->PipePress; - mvOccupied->ActFlowSpeed = 0; - } - BrakeLevelSet( mvOccupied->BrakeCtrlPos ); - } - if( mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->ShuntModeAllow ) { - // dla 2Ls150 - przed ustawieniem kierunku - można zmienić tryb pracy - mvControlling->CurrentSwitch(OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt) || fMass > 224000.0); // do tego na wzniesieniu może nie dać rady na liniowym - } - // Ra: to przełączanie poniżej jest tu bez sensu - mvOccupied->CabOccupied = iDirection; // aktywacja kabiny w prowadzonym pojeżdzie (silnikowy może być odwrotnie?) - mvOccupied->CabActivisation(); // uruchomienie kabin w członach - DirectionForward(true); // nawrotnik do przodu - mvOccupied->SpringBrakeActivate( initialspringbrakestate ); -/* - // NOTE: this won't restore local brake if the vehicle has integrated local brake control - // TBD, TODO: fix or let the ai activate the brake again as part of its standard logic? - if (initiallocalbrakelevel > 0.0) // hamowanie tylko jeśli był wcześniej zahamowany (bo możliwe, że jedzie!) - mvOccupied->LocalBrakePosA = initiallocalbrakelevel; // zahamuj jak wcześniej -*/ - if( pVehicle != initialvehicle ) { - auto *train { simulation::Trains.find( initialvehicle->name() ) }; - if( train ) { - train->MoveToVehicle( pVehicle ); - } - } - - CheckVehicles(); // sprawdzenie składu, AI zapali światła - TableClear(); // resetowanie tabelki skanowania torów - } -}; - -void TController::AutoRewident() -{ // autorewident: nastawianie hamulców w składzie - // 1. Zebranie informacji o składzie pociągu, od czoła do końca - std::vector consist; - for (auto const *d = pVehicles[0]; d != nullptr; d = d->Next()) { - consist.emplace_back(brake_setting::describe(*d->MoverParameters, d == pVehicle)); - } - // 2. Określenie typu pociągu i nastaw: by the brake instruction Cw-1 (eu07/maszyna#350), or as the releases before it did. - // brakes are cut out (Cw-1 §19.9) only in a train (a bank engine's run included), not in a consist being shunted - auto const train{brake_setting::runs_as_train(OrderCurrentGet())}; - auto const settings{Global.AIBrakeSettingCw1 ? brake_setting::choose(consist, train) : brake_setting::choose_legacy(consist)}; - // and only at a standstill, the train creeping to a stop included: a check on the run (the order changed mid-run, or - // the train was just formed by coupling, which the AI does above that speed) leaves them to reinspect_brakes() - auto const standstill{brake_setting::at_standstill(mvOccupied->Vel)}; - auto reinspect{false}; - // a light engine counts as a passenger train for the braking below - auto const passengertrain{brake_setting::passenger(brake_setting::choose_train_setting(consist))}; - // 3. Nastawianie - auto setting{settings.begin()}; - for (auto *d = pVehicles[0]; d != nullptr && setting != settings.end(); d = d->Next(), ++setting) { - if (false == AIControllFlag && d == pVehicle) { - // don't touch human-controlled vehicle, but others are free game - continue; - } - // the setting, a brake cut out in a train on G (Cw-1 §19.9) or put back when the train no longer needs it cut out - if (brake_setting::apply(*d->MoverParameters, *setting, standstill)) { - // a brake to cut out, with the train moving: left for the next standstill - reinspect = true; - } - // potentially release manual brake - d->MoverParameters->DecManualBrakeLevel( ManualBrakePosNo ); - d->MoverParameters->SpringBrake.Activate = false; - } - BrakeReinspectionPending = reinspect; - //ustawianie trybu pracy zadajnika hamulca, wystarczy raz po inicjalizacji AI - if( true == AIControllFlag ) { - // if a human is in charge leave the brake mode up to them, otherwise do as you like - for( int i = 1; i <= 8; i *= 2 ) { - if( ( mvOccupied->BrakeOpModes & i ) > 0 ) { - mvOccupied->BrakeOpModeFlag = i; - } - } - } - - // teraz zerujemy tabelkę opóźnienia hamowania - for (int i = 0; i < BrakeAccTableSize; ++i) - { - fBrake_a0[i+1] = 0; - fBrake_a1[i+1] = 0; - } - - if( OrderCurrentGet() & ( DriverOrder::shunt | DriverOrder::looseShunt ) ) { - // for uniform behaviour and compatibility with older scenarios set default acceleration table values for shunting - fAccThreshold = is_emu() ? -0.55 : is_dmu() ? -0.45 : -0.2; - // HACK: emu with induction motors need to start their braking a bit sooner than the ones with series motors - if( is_emu() - && mvControlling->EngineType == TEngineType::ElectricInductionMotor ) { - fAccThreshold += 0.10; - } - fNominalAccThreshold = fAccThreshold; - } - - BrakeSystem = consist_brake_system(); - // Change the EP fuse state only when AI is in charge, don't fiddle with controls when the user is controlling the vehicle - if (AIControllFlag) { - mvOccupied->EpFuseSwitch(BrakeSystem == TBrakeSystem::ElectroPneumatic); - } - - if( OrderCurrentGet() & ( DriverOrder::obeyTrain | DriverOrder::bank ) ) { - // 4. Przeliczanie siły hamowania - double const velstep = mvOccupied->Vmax * 0.5 / BrakeAccTableSize; - auto *d = pVehicles[0]; // pojazd na czele składu - while (d) { - // a vehicle with its brake cut out (by the inspector above or for a reason of its own) adds its mass only; - // the inspector of the earlier releases counted its brake in - auto const brakes{false == Global.AIBrakeSettingCw1 || false == brake_setting::is_cut_out(*d->MoverParameters)}; - for( int i = 0; i < BrakeAccTableSize && brakes; ++i ) { - fBrake_a0[ i + 1 ] += d->MoverParameters->BrakeForceR( 0.25, velstep*( 1 + 2 * i ) ); - fBrake_a1[ i + 1 ] += d->MoverParameters->BrakeForceR( 1.00, velstep*( 1 + 2 * i ) ); - } - d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) - } - for (int i = 0; i < BrakeAccTableSize; ++i) - { - fBrake_a1[i+1] -= fBrake_a0[i+1]; - fBrake_a0[i+1] /= fMass; - fBrake_a0[i + 1] += 0.001*velstep*(1 + 2 * i); - fBrake_a1[i+1] /= 12 * fMass; - } - - IsPassengerTrain = is_train() && false == is_emu() && false == is_dmu() && (mvOccupied->BrakeDelayFlag & bdelay_G) == 0; - IsCargoTrain = is_train() && (mvOccupied->BrakeDelayFlag & bdelay_G) != 0; - IsHeavyCargoTrain = true == IsCargoTrain && fBrake_a0[1] > 0.4 && iVehicles - ControlledEnginesCount > 0 && fMass / iVehicles > 50000; - - BrakingInitialLevel = IsHeavyCargoTrain ? 1.25 : IsCargoTrain ? 1.25 : 1.00; - - BrakingLevelIncrease = 0.25; - - if( is_emu() ) { - auto ep_factor { ( BrakeSystem == TBrakeSystem::ElectroPneumatic ? 8 : 4 ) }; - if( mvControlling->EngineType == TEngineType::ElectricInductionMotor ) { - // HACK: emu with induction motors need to start their braking a bit sooner than the ones with series motors - fNominalAccThreshold = std::max( -0.60, -fBrake_a0[ BrakeAccTableSize ] - ep_factor * fBrake_a1[ BrakeAccTableSize ] ); - } - else { - fNominalAccThreshold = std::max( -0.75, -fBrake_a0[ BrakeAccTableSize ] - ep_factor * fBrake_a1[ BrakeAccTableSize ] ); - } - fBrakeReaction = 0.25; - } - else if( is_dmu() ) { - fNominalAccThreshold = std::max( -0.75, -fBrake_a0[ BrakeAccTableSize ] - 8 * fBrake_a1[ BrakeAccTableSize ] ); - fBrakeReaction = 0.25; - } - else if (passengertrain) { - fNominalAccThreshold = -fBrake_a0[ BrakeAccTableSize ] - 4 * fBrake_a1[ BrakeAccTableSize ]; - fBrakeReaction = 1.00 + fLength*0.004; - } - else { - fNominalAccThreshold = -fBrake_a0[ BrakeAccTableSize ] - 1 * fBrake_a1[ BrakeAccTableSize ]; - fBrakeReaction = 1.00 + fLength*0.005; - } - fAccThreshold = fNominalAccThreshold; - } - -} - -// a brake the inspector had to cut out (Cw-1 §19.9) while the train was moving gets cut out once the train stands. -// a train formed by coupling is looked at as the buffers meet, above the speed the inspector takes for a standstill, -// and with no stop ahead nothing would look at it standing again (eu07/maszyna#350) -void TController::reinspect_brakes() -{ - if (false == BrakeReinspectionPending) { - return; - } - if (false == brake_setting::runs_as_train(OrderCurrentGet())) { - // no longer a train: nothing is cut out in a consist being shunted - BrakeReinspectionPending = false; - return; - } - if (brake_setting::at_standstill(mvOccupied->Vel)) { - // standing, the inspector leaves nothing for later: this clears the flag - AutoRewident(); - } -} - -double TController::ESMVelocity(bool Main) -{ - double fCurrentCoeff = 0.9; - double fFrictionCoeff = 0.85; - double ESMVel = 9999; - int MCPN = mvControlling->MainCtrlActualPos; - int SCPN = mvControlling->ScndCtrlActualPos; - if (Main) - MCPN += 1; - else - SCPN += 1; - if (mvControlling->RList[MCPN].ScndAct < 255 && mvControlling->ScndCtrlActualPos == 0) - SCPN = mvControlling->RList[MCPN].ScndAct; - double FrictionMax = mvControlling->Mass*9.81*mvControlling->Adhesive(mvControlling->RunningTrack.friction)*fFrictionCoeff; - double IF = mvControlling->Imax; - double MS = 0; - double Fmax = 0; - for (int i = 0; i < 5; i++) - { - MS = mvControlling->MomentumF(IF, IF, SCPN); - Fmax = MS * mvControlling->RList[MCPN].Bn * mvControlling->RList[MCPN].Mn * 2 / mvControlling->WheelDiameter * mvControlling->Transmision.Ratio; - if( Fmax != 0.0 ) { - IF = 0.5 * IF * ( 1 + FrictionMax / Fmax ); - } - else { - // NOTE: gets trimmed to actual highest acceptable value after the loop - IF = std::numeric_limits::max(); - break; - } - } - IF = std::min(IF, mvControlling->Imax*fCurrentCoeff); - double R = mvControlling->RList[MCPN].R + mvControlling->CircuitRes + mvControlling->RList[MCPN].Mn*mvControlling->WindingRes; - // SCPN may come from the .fiz (RList ScndAct) unchecked: read it with the bounds-safe accessor, as MomentumF() does - auto const &motorparam{mvControlling->motor_param(SCPN)}; - double pole = motorparam.fi * - std::max(abs(IF) / (abs(IF) + motorparam.Isat) - motorparam.fi0, 0.0); - double Us = abs(mvControlling->EngineVoltage) - IF*R; - double ns = std::max(0.0, Us / (pole*mvControlling->RList[MCPN].Mn)); - ESMVel = ns * mvControlling->WheelDiameter*M_PI*3.6/mvControlling->Transmision.Ratio; - return ESMVel; -} - -int TController::CheckDirection() { - - int d = mvOccupied->DirAbsolute; // który sprzęg jest z przodu - if( !d ) { - // jeśli nie ma ustalonego kierunku to jedziemy wg aktualnej kabiny - d = mvOccupied->CabActive; - } - return d; -} - -bool TController::CheckVehicles(DriverOrders user) -{ // sprawdzenie stanu posiadanych pojazdów w składzie i zapalenie świateł - TDynamicObject *p; // roboczy wskaźnik na pojazd - iVehicles = 0; // ilość pojazdów w składzie - auto d = CheckDirection(); - d = d >= 0 ? 0 : 1; // kierunek szukania czoła (numer sprzęgu) - p = pVehicle->FirstFind(d); // pojazd na czele składu - if (!p) - p = pVehicle; - auto *const frontvehicle { p }; // stays the consist head for the rest of this check - pVehicles[end::front] = frontvehicle; - // liczenie pojazdów w składzie i ustalenie parametrów - auto dir = d = 1 - d; // a dalej będziemy zliczać od czoła do tyłu - fLength = 0.0; // długość składu do badania wyjechania za ograniczenie - fMass = 0.0; // całkowita masa do liczenia stycznej składowej grawitacji - fVelMax = -1; // ustalenie prędkości dla składu - bool main = true; // czy jest głównym sterującym - drivingFlags.oerlikons = true; // zakładamy, że są same Oerlikony - // Ra 2014-09: ustawić moveMultiControl, jeśli wszystkie są w ukrotnieniu (i skrajne mają kabinę?) - while (p) - { // sprawdzanie, czy jest głównym sterującym, żeby nie było konfliktu - if( p->Mechanik // jeśli ma obsadę - && p->Mechanik != this && p->Mechanik->drivingFlags.primary ) { // ale chodzi o inny pojazd, niż aktualnie sprawdzający - // a tamten ma priorytet - // TODO: take into account drivers' operating modes, one or more of them might be on banking duty - if (drivingFlags.primary && mvOccupied->DirAbsolute && mvOccupied->BrakeCtrlPos >= -1) - { - // jeśli rządzi i ma kierunek - p->Mechanik->primary(false); // dezaktywuje tamtego - p->Mechanik->ZeroLocalBrake(); - p->MoverParameters->BrakeLevelSet(p->MoverParameters->Handle->GetPos(bh_NP)); // odcięcie na zaworze maszynisty - p->Mechanik->BrakeLevelSet(p->MoverParameters->BrakeCtrlPos); // ustawienie zmiennej GBH - } - else - { - main = false; // nici z rządzenia - } - } - ++iVehicles; // jest jeden pojazd więcej - pVehicles[end::rear] = p; // zapamiętanie ostatniego - fLength += p->MoverParameters->Dim.L; // dodanie długości pojazdu - fMass += p->MoverParameters->TotalMass; // dodanie masy łącznie z ładunkiem - fVelMax = min_speed( fVelMax, p->MoverParameters->Vmax ); // ustalenie maksymalnej prędkości dla składu - // reset oerlikon brakes consist flag as different type was detected - if( p->MoverParameters->BrakeSubsystem != TBrakeSubSystem::ss_ESt - && p->MoverParameters->BrakeSubsystem != TBrakeSubSystem::ss_LSt ) { - drivingFlags.oerlikons = false; - } - p = p->Neighbour(dir); // pojazd podłączony od wskazanej strony - } - if( main ) { - drivingFlags.primary = true; // nie znaleziono innego, można się porządzić - } - - ControllingSet(); // ustalenie członu do sterowania (może być inny niż zasiedziany) - - if (drivingFlags.primary) - { // jeśli jest aktywnie prowadzącym pojazd, może zrobić własny porządek - auto pantmask = 1; - p = frontvehicle; - // establish ownership and vehicle order - while (p) - { - if (p->MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) - { // jeśli pojazd posiada pantograf, to przydzielamy mu maskę, którą będzie informował o jeździe bezprądowej - p->iOverheadMask = pantmask; - pantmask = pantmask << 1; // przesunięcie bitów, max. 32 pojazdy z pantografami w składzie - } - - d = p->DirectionSet(d ? 1 : -1); // zwraca położenie następnego (1=zgodny,0=odwrócony - względem czoła składu) - p->ctOwner = this; // dominator oznacza swoje terytorium - p = p->Next(); // pojazd podłączony od tyłu (licząc od czoła) - } - // with the order established the virtual train manager can do their work - p = frontvehicle; - ControlledEnginesCount = p->MoverParameters->Power > 1.0 ? 1 : 0; - auto hasheaters { false }; - while (p) - { - if( p != pVehicle ) { - if( false == p->is_connected( pVehicle, Coupling::control ) ) { - // NOTE: don't set battery in controllable vehicles, let the user/ai do it explicitly - // HACK: wagony muszą mieć baterię załączoną do otwarcia drzwi... - p->MoverParameters->BatterySwitch( true ); - // enable heating and converter in carriages with can be heated - if( p->MoverParameters->HeatingPower > 0 ) { - p->MoverParameters->HeatingAllow = true; - p->MoverParameters->ConverterSwitch( true, range_t::local ); - hasheaters = true; - } - } - else { - if( p->MoverParameters->Power > 1.0 ) { - ++ControlledEnginesCount; - } - } - } - - if( p->asDestination == "none" ) { - p->DestinationSet( TrainParams.Relation2, TrainParams.TrainName ); // relacja docelowa, jeśli nie było - } - if( AIControllFlag ) { // jeśli prowadzi komputer - p->RaLightsSet( 0, 0 ); // gasimy światła - } - p = p->Next(); // pojazd podłączony od tyłu (licząc od czoła) - } - - if( user == DriverOrder::connect && true == main ) { - // HACK: with additional vehicles in the consist ensure all linked vehicles are set to move in the same direction - if( pVehicle->Prev(Coupling::control) != nullptr - || pVehicle->Next(Coupling::control) != nullptr ) { - sync_consist_reversers(); - } - // potentially sync compartment lighting state for the newly connected vehicles - if( mvOccupied->CompartmentLights.start_type == start_t::manual ) { - mvOccupied->CompartmentLightsSwitchOff( mvOccupied->CompartmentLights.is_disabled ); - mvOccupied->CompartmentLightsSwitch( mvOccupied->CompartmentLights.is_enabled ); - } - } - - // kasowanie pamieci hamowania kontrolnego - if (OrderCurrentGet() & (DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::disconnect | DriverOrder::connect | DriverOrder::changeDirection)) { - DynamicBrakeTest = 0; - DBT_VelocityBrake - = DBT_VelocityRelease - = DBT_VelocityFinish - = DBT_BrakingTime - = DBT_ReleasingTime - = DBT_MidPointAcc - = 0; - } - - if( brake_setting::inspects_train( OrderCurrentGet(), user == DriverOrder::connect ) ) { - // nastawianie hamulca do jazdy pociągowej - AutoRewident(); -/* - if( ( true == drivingFlags.connect ) - && ( true == OrderCurrentGet().HasAll(DriverOrder::connect) ) ) { - iCoupler = {}; // dalsza jazda manewrowa już bez łączenia - drivingFlags.connect = false; // zdjęcie flagi doczepiania - SetVelocity( 0, 0, stopJoin ); // wyłączyć przyspieszanie - JumpToNextOrder(); // wykonanie następnej komendy - } -*/ - } - - // detect push-pull train configurations and mark them accordingly - if( frontvehicle->is_connected( pVehicles[ end::rear ], Coupling::control ) ) { - // zmiana czoła przez zmianę kabiny - drivingFlags.pushPull = true; - } - else { - // zmiana czoła przez manewry - drivingFlags.pushPull = false; - } - - // HACK: ensure vehicle lights are active from the beginning, if it had pre-activated battery - if( mvOccupied->LightsPosNo > 0 ) { - pVehicle->SetLights(); - } - if( iEngineActive ) { - // potentially adjust light state - control_lights(); - // custom ai action for disconnect mode: switch off lights on disconnected vehicle(s) - if( is_train() && true == OrderCurrentGet().HasAll(DriverOrder::disconnect) && AIControllFlag ) { - // światła manewrowe (Tb1) tylko z przodu, aby nie pozostawić odczepionego ze światłem - if (mvOccupied->DirActive >= 0) - { // jak ma kierunek do przodu - pVehicles[end::rear]->RaLightsSet(-1, 0); - } - else - { // jak dociska - frontvehicle->RaLightsSet(0, -1); - } - } - // enable door locks - cue_action( driver_hint::consistdoorlockson ); - // potentially enable train heating - { - auto const ispassengertrain { IsPassengerTrain && iVehicles - ControlledEnginesCount > 0 }; - // TODO: replace connection test with connection check between last engine and first car, specifically - auto const isheatingcouplingactive { ( - ControlledEnginesCount == 1 ? - frontvehicle->is_connected( pVehicles[ end::rear ], Coupling::heating ) : - true ) }; - auto const isheatingneeded { - (is_emu() || is_dmu() ? true : - false == OrderCurrentGet().HasAny(DriverOrder::obeyTrain | DriverOrder::bank) ? false : - false == isheatingcouplingactive ? false : - ispassengertrain ? hasheaters : - false) }; - if( mvControlling->HeatingAllow != isheatingneeded ) { - cue_action( - isheatingneeded ? - driver_hint::consistheatingon : - driver_hint::consistheatingoff ); - } - } - } - - if( user == DriverOrder::connect - || user == DriverOrder::disconnect ) { - // HACK: force route table update on consist change, new consist length means distances to points of interest are now wrong - iTableDirection = 0; - } - } // blok wykonywany, gdy aktywnie prowadzi - return true; -} - -void TController::Lights(int head, int rear) -{ // zapalenie świateł w skłądzie - pVehicles[ end::front ]->RaLightsSet(head, -1); // zapalenie przednich w pierwszym - pVehicles[ end::rear ]->RaLightsSet(-1, rear); // zapalenie końcówek w ostatnim -} - -void TController::DirectionInitial() -{ // ustawienie kierunku po wczytaniu trainset (może jechać na wstecznym - mvOccupied->CabActivisationAuto(); // załączenie rozrządu (wirtualne kabiny) - if (mvOccupied->Vel > EU07_AI_NOMOVEMENT) - { // jeśli na starcie jedzie - iDirection = iDirectionOrder = - mvOccupied->V > 0 ? 1 : -1; // początkowa prędkość wymusza kierunek jazdy - DirectionForward(mvOccupied->V * mvOccupied->CabActive >= 0.0); // a dalej ustawienie nawrotnika - } - CheckVehicles(); // sprawdzenie świateł oraz skrajnych pojazdów do skanowania -}; - -void TController::DirectionChange() { - - auto const initialstate { iDirection }; - iDirection = CheckDirection(); - if( iDirection != initialstate ) { - CheckVehicles( DriverOrder::changeDirection ); - } -} - -TBrakeSystem TController::consist_brake_system() const { - - if( mvOccupied->BrakeSystem != TBrakeSystem::ElectroPneumatic ) { return mvOccupied->BrakeSystem; } - - auto isepcapable = true; - if( pVehicles[ end::front ] != pVehicles[ end::rear ] ) { - // more detailed version, will use manual braking also for coupled sets of controlled vehicles - auto *vehicle = pVehicles[ end::front ]; // start from first - while( true == isepcapable - && vehicle != nullptr ) { - // NOTE: we could simplify this by doing only check of the rear coupler, but this can be quite tricky in itself - // TODO: add easier ways to access front/rear coupler taking into account vehicle's direction - isepcapable = (vehicle->MoverParameters->Couplers[end::front].Connected == nullptr || - (vehicle->MoverParameters->Couplers[end::front].CouplingFlag & Coupling::control && vehicle->MoverParameters->Couplers[end::front].Connected->Power > -1)) && - (vehicle->MoverParameters->Couplers[end::rear].Connected == nullptr || - (vehicle->MoverParameters->Couplers[end::rear].CouplingFlag & Coupling::control && vehicle->MoverParameters->Couplers[end::rear].Connected->Power > -1)); - vehicle = vehicle->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) - } - } - return isepcapable ? TBrakeSystem::ElectroPneumatic : TBrakeSystem::Pneumatic; -} - -std::pair TController::next_speed_limit() const { - - auto const speedlimit { static_cast( VelDesired ) }; - auto nextspeedlimit { speedlimit }; - auto nextspeedlimitdistance { std::numeric_limits::max() }; - if( speedlimit == 0 ) { - // if we aren't allowed to move then any next speed limit is irrelevant - return { nextspeedlimit, nextspeedlimitdistance }; - } - // nie przekraczać rozkladowej - auto const schedulespeedlimit { ( - OrderCurrentGet().HasAny( DriverOrder::obeyTrain | DriverOrder::bank ) && TrainParams.TTVmax > 0.0 ? static_cast( TrainParams.TTVmax ) : - false == OrderCurrentGet().HasAny( DriverOrder::obeyTrain | DriverOrder::bank ) ? static_cast( fShuntVelocity ) : - -1 ) }; - // first take note of any speed change which should occur after passing potential current speed limit - if( VelLimitLastDist.second > 0 ) { - nextspeedlimit = min_speed( schedulespeedlimit, static_cast( VelLimitLastDist.first ) ); - nextspeedlimitdistance = VelLimitLastDist.second; - } - // then take into account speed change ahead, compare it with speed after potentially clearing last limit - // lower of these two takes priority; otherwise limit lasts at least until potential last limit is cleared - auto const noactivespeedlimit { VelLimitLastDist.second < 0 }; - if( auto const speedatproximitydistance { min_speed( schedulespeedlimit, static_cast( VelNext ) ) }; speedatproximitydistance == nextspeedlimit ) { - if( noactivespeedlimit ) { - nextspeedlimit = speedatproximitydistance; - nextspeedlimitdistance = ActualProximityDist; - } - } - else if( speedatproximitydistance < nextspeedlimit ) { - // if the speed limit ahead is more strict than our current limit, it's important enough to report - if( speedatproximitydistance < VelDesired ) { - nextspeedlimit = speedatproximitydistance; - nextspeedlimitdistance = ActualProximityDist; - } - // otherwise report it only if it's located after our current (lower) limit ends - else if( ActualProximityDist > nextspeedlimitdistance ) { - nextspeedlimit = speedatproximitydistance; - nextspeedlimitdistance = ActualProximityDist; - } - } - else if( noactivespeedlimit ) { // implicit proximity > last, report only if last limit isn't present - nextspeedlimit = speedatproximitydistance; - nextspeedlimitdistance = ActualProximityDist; - } - // HACK: if our current speed limit extends beyond our scan range don't display potentially misleading information about its length - if( nextspeedlimitdistance >= EU07_AI_SPEEDLIMITEXTENDSBEYONDSCANRANGE ) { - nextspeedlimit = speedlimit; - } - // HACK: hide next speed limit if the 'limit' is a vehicle in front of us - else if( ActualProximityDist == std::abs( TrackObstacle() ) ) { - nextspeedlimit = speedlimit; - } - return { nextspeedlimit, nextspeedlimitdistance }; -} - -blackbox::ai_reference TController::ai_reference() const { - - blackbox::ai_reference ai; - ai.target_kmh = static_cast( VelDesired ); - if( auto const [ limit, distance ] { next_speed_limit() }; limit != static_cast( VelDesired ) ) { - ai.next_limit_kmh = static_cast( limit ); - ai.next_limit_distance = static_cast( distance ); - } - ai.acceleration = static_cast( AccDesired ); - ai.braking_distance = static_cast( fBrakeDist ); - ai.timetable_vmax_kmh = ( TrainParams.TTVmax > 0.0 ? static_cast( TrainParams.TTVmax ) : -1.0f ); - ai.track_vmax_kmh = static_cast( mvOccupied->RunningTrack.Velmax ); - return ai; -} - -void TController::record_station( TSpeedPos const &Point, std::uint8_t const Kind ) const { - - if( Point.evEvent == nullptr ) { return; } - blackbox::station_event entry; - entry.kind = Kind; - auto const row { TrainParams.StationIndex }; - entry.row = static_cast( std::max( 0, row ) ); - entry.station = asNextStop; - entry.position = Point.evEvent->input_location(); - // the stop point may be moved back from the indicator, to where the head of the train is to stop - entry.distance = static_cast( Point.fDist + Point.fMoved ); - entry.stop_at = static_cast( Point.fMoved ); - entry.train_length = static_cast( fLength ); - entry.platform = static_cast( Point.evEvent->input_value( 2 ) ); - if( row >= 0 && row <= TrainParams.StationCount ) { - auto const &line { TrainParams.TimeTable[ row ] }; - entry.arrival = ( line.Ah >= 0 ? static_cast( line.Ah * 60 ) + line.Am : -1.0f ); - entry.departure = ( line.Dh >= 0 ? static_cast( line.Dh * 60 ) + line.Dm : -1.0f ); - } - simulation::Blackbox.station( pVehicles[ end::front ], std::move( entry ) ); -} - -int TController::OrderDirectionChange(int newdir, TMoverParameters *Vehicle) -{ // zmiana kierunku jazdy, niezależnie od kabiny - int testd = newdir; - if (Vehicle->Vel < 0.5) - { // jeśli prawie stoi, można zmienić kierunek, musi być wykonane dwukrotnie, bo za pierwszym razem daje na zero - switch (newdir * Vehicle->CabActive) - { // DirectionBackward() i DirectionForward() to zmiany względem kabiny - case -1: // if (!Vehicle->DirectionBackward()) testd=0; break; - DirectionForward(false); - break; - case 1: // if (!Vehicle->DirectionForward()) testd=0; break; - DirectionForward(true); - break; - } - if (testd == 0) - VelforDriver = -1; // kierunek został zmieniony na żądany, można jechać - } - else // jeśli jedzie - VelforDriver = 0; // ma się zatrzymać w celu zmiany kierunku - if (Vehicle->DirActive == 0 && VelforDriver < Vehicle->Vel) // Ra: to jest chyba bez sensu - IncBrake(); // niech hamuje - if (Vehicle->DirActive == testd * Vehicle->CabActive) - VelforDriver = -1; // można jechać, bo kierunek jest zgodny z żądanym - if (is_emu() && Vehicle->DirActive > 0) - // if () //tylko jeśli jazda pociągowa (tego nie wiemy w momencie odpalania silnika) - Vehicle->DirectionForward(); - // Ra: z przekazaniem do silnikowego - return (int)VelforDriver; // zwraca prędkość mechanika -} - -void TController::WaitingSet(double Seconds) -{ // ustawienie odczekania po zatrzymaniu (ustawienie w trakcie jazdy zatrzyma) - fStopTime = -Seconds; // ujemna wartość oznacza oczekiwanie (potem >=0.0) -} - -void TController::SetVelocity(double NewVel, double NewVelNext, TStopReason r) -{ // ustawienie nowej prędkości - WaitingTime = -WaitingExpireTime; // przypisujemy -WaitingExpireTime, a potem porównujemy z zerem - if (NewVel == 0.0) { // jeśli ma stanąć - if (r != stopNone) // a jest powód podany - eStopReason = r; // to zapamiętać nowy powód - } - else { - eStopReason = stopNone; // podana prędkość, to nie ma powodów do stania - // to całe poniżej to warunki zatrąbienia przed ruszeniem - if( is_train() // tylko pociągi trąbią (unimogi tylko na torach, więc trzeba raczej sprawdzać tor) - && OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank | DriverOrder::connect | DriverOrder::prepareEngine) // jeśli jedzie w dowolnym trybie - && drivingFlags.startHorn // jezeli trąbienie włączone - && ( false == drivingFlags.startHornDone && false == drivingFlags.connect ) // jeśli nie zatrąbione i nie jest to moment podłączania składu - && mvOccupied->Vel < 1.0 // jesli stoi (na razie, bo chyba powinien też, gdy hamuje przed semaforem) - && ( NewVel >= 1.0 || NewVel < 0.0 ) ) { // o ile prędkość jest znacząca zatrąb po odhamowaniu - drivingFlags.startHornNow = true; - } - } - VelSignal = NewVel; // prędkość zezwolona na aktualnym odcinku - VelNext = NewVelNext; // prędkość przy następnym obiekcie -} - -double TController::BrakeAccFactor() const -{ - double Factor = 1.0; - - if( fAccThreshold != 0.0 - && AccDesired < 0.0 - && ( ActualProximityDist > fMinProximityDist - || mvOccupied->Vel > VelDesired + fVelPlus ) ) { - Factor += fBrakeReaction * (/*mvOccupied->BrakeCtrlPosR*/ BrakeCtrlPosition < 0.5 ? 1.5 : 1) * mvOccupied->Vel / ( std::max( 0.0, ActualProximityDist ) + 1 ) * ( ( AccDesired - AbsAccS ) / fAccThreshold ); - } -/* - if (mvOccupied->TrainType == train_type::dmu && mvOccupied->Vel > 40 && VelNext<40) - Factor *= 1 + 0.25 * ( (1600 - VelNext * VelNext) / (mvOccupied->Vel * mvOccupied->Vel) ); -*/ - return Factor; -} - -void TController::SetDriverPsyche() { - - if (Psyche == Aggressive && OrderCurrentGet() == DriverOrder::obeyTrain) { - ReactionTime = HardReactionTime; // w zaleznosci od charakteru maszynisty - if (is_car()) { - WaitingExpireTime = 1; // tyle ma czekać samochód, zanim się ruszy - AccPreferred = 3.0; //[m/ss] agresywny - } - else { - WaitingExpireTime = 61; // tyle ma czekać, zanim się ruszy - AccPreferred = HardAcceleration; // agresywny - } - } - else { - ReactionTime = EasyReactionTime; // spokojny - if (is_car()) { - WaitingExpireTime = 3; // tyle ma czekać samochód, zanim się ruszy - AccPreferred = 2.0; //[m/ss] - } - else { - WaitingExpireTime = 65; // tyle ma czekać, zanim się ruszy - AccPreferred = EasyAcceleration; - } - } -} - -// closes the line breaker, or starts the engine, the relays reset first -void TController::close_line_breaker() -{ - cue_action( driver_hint::mastercontrollersetzerospeed ); - // consist-wide ground relay reset - cue_action( driver_hint::maincircuitgroundreset ); - cue_action( driver_hint::tractionnmotoroverloadreset ); - if( mvOccupied->EngineType == TEngineType::DieselEngine ) { - // specjalnie dla SN61 żeby nie zgasł - cue_action( driver_hint::mastercontrollersetidle ); - } - cue_action( driver_hint::linebreakerclose ); -} - -bool TController::PrepareEngine() -{ // odpalanie silnika - // HACK: don't immediately activate inert vehicle in case the simulation is about to replace us with human driver - if( mvOccupied->Vel < 1.0 && fActionTime < 0.0 ) { return false; } - - LastReactionTime = 0.0; - ReactionTime = mvOccupied->Vel < 5 ? PrepareTime : EasyReactionTime; // react faster with rolling start - - cue_action( driver_hint::batteryon ); - cue_action( driver_hint::cabactivation); - cue_action( driver_hint::radiofuseon ); - cue_action( driver_hint::radioon ); - - if( has_diesel_engine() ) { - cue_action( driver_hint::oilpumpon ); - PrepareHeating(); - if( true == IsHeatingTemperatureOK ) { - cue_action( driver_hint::fuelpumpon ); - } - else { - cue_action( driver_hint::waittemperaturetoolow ); - } - } - - if( mvControlling->PantographsRequireMains - && IsAnyLineBreakerOpen ) { - // the pantographs rise only through the closed line breaker, which closes without their voltage - PrepareDirection(); - close_line_breaker(); - } - - auto const sufficientpantographpressure { ( - is_emu() ? - 2.5 : // Ra 2013-12: Niebugocław mówi, że w EZT podnoszą się przy 2.5 - 3.5 ) - + 0.1 }; // leeway margin - - if( mvPantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector - && mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 0 ) { - // if our pantograph unit isn't a pantograph-devoid fallback - if (mvPantographUnit->PantPress < sufficientpantographpressure) { - // załączenie małej sprężarki - if( false == mvPantographUnit->PantAutoValve ) { - // odłączenie zbiornika głównego, bo z nim nie da rady napompować - cue_action( driver_hint::pantographairsourcesetauxiliary ); - } - cue_action( driver_hint::pantographcompressoron ); // załączenie sprężarki pantografów - if( mvPantographUnit->PantCompFlag ) { - cue_action( driver_hint::waitpantographpressuretoolow ); - } - } - else { - // jeżeli jest wystarczające ciśnienie w pantografach - if( false == mvPantographUnit->bPantKurek3 - || mvPantographUnit->PantPress <= mvPantographUnit->ScndPipePress ) { // kurek przełączony albo główna już pompuje - cue_action( driver_hint::pantographcompressoroff ); // sprężarkę pantografów można już wyłączyć - } - } - // TODO: make pantograph setup a part of control_pantographs() and call it here instead - if( fOverhead2 == -1.0 && iOverheadDown == 0 ) { - cue_action( driver_hint::pantographsvalveon ); - cue_action( driver_hint::frontpantographvalveon, iDirection >= 0 ? 5 : 0 ); - cue_action( driver_hint::rearpantographvalveon, iDirection >= 0 ? 0 : 5 ); - } - } - - auto const ispoweravailable = - mvControlling->EnginePowerSource.SourceType != TPowerSource::CurrentCollector - || std::max(mvControlling->GetTrainsetHighVoltage(), mvControlling->PantographVoltage) > mvControlling->EnginePowerSource.CollectorParameters.MinV; - // standing with the pantographs up and no voltage, nothing the driver does starts the vehicle. it says so, and keeps - // trying: towed back under the wire, or with the power switched on, the vehicle gets prepared after all - report_power_stall( ispoweravailable, sufficientpantographpressure ); - - bool isready = false; - - if( IsHeatingTemperatureOK - && ispoweravailable ) { - // najpierw ustalamy kierunek, jeśli nie został ustalony - PrepareDirection(); - - if( IsAnyConverterOverloadRelayOpen ) { - // wywalił bezpiecznik nadmiarowy przetwornicy - cue_action( driver_hint::compressoroff ); // TODO: discern whether compressor needs converter to operate - cue_action( driver_hint::converteroff ); - cue_action( driver_hint::primaryconverteroverloadreset ); // reset nadmiarowego - } - if( IsAnyLineBreakerOpen ) { - // activate main circuit or engine - close_line_breaker(); - } - else { - // main circuit or engine is on, set up vehicle devices and controls - if( false == IsAnyConverterOverloadRelayOpen ) { - if( IsAnyConverterPresent ) { - cue_action( driver_hint::converteron ); - } - // w EN57 sprężarka w ra jest zasilana z silnikowego - // TODO: change condition to presence of required voltage type - if( IsAnyCompressorPresent && IsAnyConverterEnabled ) { - cue_action( driver_hint::compressoron ); - } - if( mvControlling->ScndPipePress < 4.5 && mvControlling->VeselVolume > 0.0 ) { - cue_action( driver_hint::waitpressuretoolow ); - } - // enable motor blowers - if( mvOccupied->MotorBlowers[ end::front ].speed != 0 ) { - cue_action( driver_hint::frontmotorblowerson ); - } - if( mvOccupied->MotorBlowers[ end::rear ].speed != 0 ) { - cue_action( driver_hint::rearmotorblowerson ); - } - } - control_field_shunting(); - // sync virtual brake state with the 'real' one - if( mvOccupied->BrakeHandle != TBrakeHandle::NoHandle ) { - std::unordered_map const brakepositions{ - { static_cast( mvOccupied->Handle->GetPos( bh_RP ) ), gbh_RP }, - { static_cast( mvOccupied->Handle->GetPos( bh_NP ) ), gbh_NP }, - { static_cast( mvOccupied->Handle->GetPos( bh_FS ) ), gbh_FS } }; - auto const lookup{ brakepositions.find( static_cast( mvOccupied->fBrakeCtrlPos ) ) }; - if( lookup != brakepositions.end() ) { - BrakeLevelSet( lookup->second ); // GBH - } - } - // set up train brake - if( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) { - // standing: the locomotive brake first, then the pipe is filled - secure_standing_train(); - } - else if( ( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_RP ) ) - && ( ( false == mvOccupied->Handle->Time ) - || ( mvOccupied->Handle->GetCP() < mvOccupied->HighPipePress - 0.05 ) ) ) { - cue_action( driver_hint::trainbrakerelease ); - } - // sync spring brake state across consist - cue_action( - mvOccupied->SpringBrake.Activate ? - driver_hint::springbrakeon : - driver_hint::springbrakeoff ); - } - isready = false == IsAnyConverterOverloadRelayOpen - && mvOccupied->DirActive != 0 - && false == IsAnyLineBreakerOpen - && ( false == IsAnyConverterPresent || true == IsAnyConverterEnabled ) - && ( false == IsAnyCompressorPresent || true == IsAnyCompressorEnabled ) - && ( mvControlling->ScndPipePress > 4.5 || mvControlling->VeselVolume == 0.0 ); - } - - if( true == isready ) { - // jeśli dotychczas spał teraz nie ma powodu do stania - eAction = TAction::actUnknown; - if( eStopReason == stopSleep ) { - eStopReason = stopNone; - } - // może skanować sygnały i reagować na komendy - drivingFlags.active = true; - } - - iEngineActive = isready; - - return iEngineActive; -} - -// tells in the log, once, of standing with the pantographs up and no voltage at them, past the end of the overhead -// wire or under a wire switched off (eu07/maszyna#421). Poweravailable is what PrepareEngine() found, Pantographpressure -// the air the pantographs need to rise -void -TController::report_power_stall( bool const Poweravailable, double const Pantographpressure ) { - - ai_power::state state; - state.collector = mvControlling->EnginePowerSource.SourceType == TPowerSource::CurrentCollector; - state.power = Poweravailable; - state.standing = mvOccupied->Vel < EU07_AI_NOMOVEMENT; - if( mvPantographUnit->PantPress >= Pantographpressure ) { - state.pantographs_up = - mvPantographUnit->Pantographs[ end::front ].is_active - || mvPantographUnit->Pantographs[ end::rear ].is_active; - } - // the pantographs of the vehicle carrying them hold the wire they found above them - if( auto const *carrier { pVehicle->FindPantographCarrier() }; - carrier != nullptr && carrier->MoverParameters == mvPantographUnit ) { - auto const pantographcount { std::min( carrier->iAnimType[ ANIM_PANTS ], static_cast( carrier->MoverParameters->Pantographs.size() ) ) }; - for( auto index { 0 }; index < pantographcount; ++index ) { - if( true == carrier->MoverParameters->Pantographs[ index ].is_active - && carrier->pants[ index ].fParamPants->hvPowerWire != nullptr ) { - state.wire = true; - } - } - } - // a user driving the vehicle sees the voltmeters for themselves - if( auto const stall { m_powerstall.update( AIControllFlag ? ai_power::check( state ) : ai_power::stall::waiting, ElapsedTime ) }; - stall.has_value() ) { - ErrorLog( ai_power::message( *stall, pVehicle->asName, pVehicle->GetPosition() ), logtype::traction ); - } -} - -// wyłączanie silnika (test wyłączenia, a część wykonawcza tylko jeśli steruje komputer) -bool TController::ReleaseEngine() { -/* - if( mvOccupied->Vel > 0.01 ) { - VelDesired = 0.0; - AccDesired = std::min( AccDesired, -1.25 ); // hamuj solidnie - if( true == AIControllFlag ) { - // TBD, TODO: make a dedicated braking procedure out of it for potential reuse - ZeroSpeed(); - IncBrake(); - ReactionTime = 0.1; - } - // don't bother with the rest until we're standing still - return false; - } -*/ - // don't bother with the rest until we're standing still - if( mvOccupied->Vel > EU07_AI_NOMOVEMENT ) { return false; } - - LastReactionTime = 0.0; - ReactionTime = PrepareTime; - - cue_action( driver_hint::releaseroff ); - // release train brake if on flats... - if( std::abs( fAccGravity ) < 0.01 ) { - apply_independent_brake_only(); - } - // ... but on slopes engage train brake - else { -// AccDesired = std::min( AccDesired, -0.9 ); - cue_action( driver_hint::trainbrakeapply ); - } - - cue_action( driver_hint::mastercontrollersetreverserunlock ); - cue_action( driver_hint::directionnone ); - // zamykanie drzwi - cue_action( driver_hint::doorrightclose ); - cue_action( driver_hint::doorleftclose ); - // heating - cue_action( driver_hint::consistheatingoff ); - // devices - cue_action( driver_hint::compressoroff ); - cue_action( driver_hint::converteroff ); - // line breaker/engine - cue_action( driver_hint::linebreakeropen ); - // pantographs - cue_action( driver_hint::frontpantographvalveoff ); - cue_action( driver_hint::rearpantographvalveoff ); - - if( false == mvControlling->Mains ) { - // finish vehicle shutdown - if( has_diesel_engine() ) { - // heating/cooling subsystem - cue_action( driver_hint::waterheateroff ); - // optionally turn off the water pump as well - if( mvControlling->WaterPump.start_type != start_t::battery ) { - cue_action( driver_hint::waterpumpoff ); - } - // fuel and oil subsystems - cue_action( driver_hint::fuelpumpoff ); - cue_action( driver_hint::oilpumpoff ); - } - // gasimy światła - cue_action( driver_hint::lightsoff ); - // activate parking brake - // TBD: do it earlier? - cue_action( driver_hint::springbrakeon ); - if( mvOccupied->LocalBrake == TLocalBrake::ManualBrake - || mvOccupied->MBrake == true ) { - cue_action( driver_hint::manualbrakon ); - } - // switch off remaining power - cue_action( driver_hint::radiooff ); - cue_action( driver_hint::batteryoff ); - } - - auto const OK { - mvOccupied->DirActive == 0 -// && ( false == IsAnyCompressorEnabled ) -// && ( false == IsAnyConverterEnabled ) - && false == mvControlling->Mains - && false == mvOccupied->Power24vIsAvailable }; - - if (OK) { - // jeśli się zatrzymał - iEngineActive = false; - eStopReason = stopSleep; // stoimy z powodu wyłączenia - eAction = TAction::actSleep; //śpi (wygaszony) - - OrderNext(DriverOrder::waitForOrders); //żeby nie próbował coś robić dalej - drivingFlags.active = false; // ma nie skanować sygnałów i nie reagować na komendy - TableClear(); // zapominamy ograniczenia - VelSignalLast = -1.0; - } - return OK; -} - -// defined further down, with the braking demand it is used for -static double brake_response_horizon( TMoverParameters const *Vehicle, TBrakeSystem const Brakesystem, double const Acceleration, double const Brakea0 ); - -// one step more of the train brake, sized from the consist brake table against the deceleration asked for -bool -TController::increase_train_brake() { - - // dodane dla towarowego - float pos_corr = 0; - - TDynamicObject *d; - d = pVehicles[0]; // pojazd na czele składu - while (d) - { // przeliczanie dodatkowego potrzebnego spadku ciśnienia - if( ( d->MoverParameters->Hamulec->GetBrakeStatus() & b_dmg ) == 0 ) { - pos_corr -= ( std::min( 5.0, d->MoverParameters->Hamulec->GetCRP() ) - 5.0 ) * d->MoverParameters->TotalMass; - } - d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) - } - pos_corr = pos_corr / fMass * 2.5; - - if (mvOccupied->BrakeHandle == TBrakeHandle::FV4a) - { - pos_corr += mvOccupied->Handle->GetCP()*0.2; - - } - if( double const deltaAcc = -AccDesired*BrakeAccFactor() - (fBrake_a0[0] + 4.0 * (/*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition - 1 - pos_corr)*fBrake_a1[0]); - deltaAcc > brake_increase_margin() ) - { - if( /*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition < 0.1 ) { - auto const OK { /*mvOccupied->*/BrakeLevelAdd( BrakingInitialLevel ) }; //GBH - // HACK: stronger braking to overcome SA134 engine behaviour - if( is_dmu() - && VelNext == 0.0 - && fBrakeDist < 200.0 ) { - BrakeLevelAdd( - fBrakeDist / ActualProximityDist < 0.8 ? - 0.5 : - 1.0 ); - } - return OK; - } - auto const OK { /*mvOccupied->*/BrakeLevelAdd( BrakingLevelIncrease ) }; //GBH - // brake harder if the acceleration is much higher than desired - /*if( ( deltaAcc > 2 * fBrake_a1[ 0 ] ) - && ( mvOccupied->BrakeCtrlPosR + BrakingLevelIncrease <= 5.0 ) ) { - mvOccupied->BrakeLevelAdd( BrakingLevelIncrease ); - } GBH */ - if( deltaAcc > 2 * fBrake_a1[0] - && BrakeCtrlPosition + BrakingLevelIncrease <= 5.0 ) { - /*mvOccupied->*/BrakeLevelAdd( BrakingLevelIncrease ); - } - return OK; - } - if( BrakeCtrlPosition > 0.0 - && AccDesired < 0.0 // only while braking is asked for, not when called for a train slipping back while starting - && ( fBrakeHeldTime > ( - mvOccupied->BrakeDelayFlag > bdelay_G ? - mvOccupied->BrakeDelay[ 1 ] : - mvOccupied->BrakeDelay[ 3 ] ) - // a train falling further behind needs no full fill time to be seen not to get enough - || ( ( fShortfall > 0.02 ) - && ( fBrakeHeldTime > brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) ) { - // the table says the present position is enough, but the brake has had its full fill - // time since the handle last moved and the train is still not slowing down as asked: - // believe the train rather than the table - return BrakeLevelAdd( BrakingLevelIncrease ); - } - return false; -} - -bool TController::IncBrake() -{ // zwiększenie hamowania - auto OK { false }; - auto const bs { - BrakeSystem == TBrakeSystem::ElectroPneumatic && ForcePNBrake ? - TBrakeSystem::Pneumatic : - BrakeSystem }; - switch( bs ) { - case TBrakeSystem::Individual: { - if( mvOccupied->LocalBrake == TLocalBrake::ManualBrake ) { - OK = mvOccupied->IncManualBrakeLevel( 1 + static_cast( std::floor( 0.5 + std::fabs( AccDesired ) ) ) ); - } - else { - OK = mvOccupied->IncLocalBrakeLevel( std::floor( 1.5 + std::abs( AccDesired ) ) ); - } - break; - } - case TBrakeSystem::Pneumatic: { - if (bs != mvOccupied->BrakeSystem) - { - while (mvOccupied->BrakeOpModeFlag > bom_PN) - { - mvOccupied->BrakeOpModeFlag >>= 1; - } - } - // NOTE: can't perform just test whether connected vehicle == nullptr, due to virtual couplers formed with nearby vehicles - auto standalone { true }; - if( mvOccupied->TrainType == train_type::et41 - || mvOccupied->TrainType == train_type::et42 ) { - // NOTE: we're doing simplified checks full of presuptions here. - // they'll break if someone does strange thing like turning around the second unit - if( mvOccupied->Couplers[end::rear].CouplingFlag & Coupling::permanent - && mvOccupied->Couplers[end::rear].Connected->Couplers[end::rear].Connected != nullptr ) { - standalone = false; - } - if( mvOccupied->Couplers[end::front].CouplingFlag & Coupling::permanent - && mvOccupied->Couplers[end::front].Connected->Couplers[end::front].Connected != nullptr ) { - standalone = false; - } - } - else if( is_dmu() ) { - // enforce use of train brake for DMUs - standalone = false; - } - else if( OrderCurrentGet().HasAny(DriverOrder::looseShunt) - && mvOccupied->Vel - VelDesired < fVelPlus + fVelMinus ) { - // try to reduce train brake use in loose shunting mode - standalone = true; - } - else { -/* - standalone = - ( ( mvOccupied->Couplers[ 0 ].CouplingFlag.Empty() ) - && ( mvOccupied->Couplers[ 1 ].CouplingFlag.Empty() ) ); -*/ - if( pVehicles[ end::front ] != pVehicles[ end::rear ] ) { - // more detailed version, will use manual braking also for coupled sets of controlled vehicles - auto *vehicle = pVehicles[ end::front ]; // start from first - while( true == standalone - && vehicle != nullptr ) { - // NOTE: we could simplify this by doing only check of the rear coupler, but this can be quite tricky in itself - // TODO: add easier ways to access front/rear coupler taking into account vehicle's direction - standalone = - (vehicle->MoverParameters->Couplers[end::front].Connected == nullptr || - (vehicle->MoverParameters->Couplers[end::front].CouplingFlag & Coupling::control && vehicle->MoverParameters->Couplers[end::front].Connected->Power > 1)) && - (vehicle->MoverParameters->Couplers[end::rear].Connected == nullptr || - (vehicle->MoverParameters->Couplers[end::rear].CouplingFlag & Coupling::control && vehicle->MoverParameters->Couplers[end::rear].Connected->Power > 1)); - vehicle = vehicle->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) - } - } - } - - //standalone = standalone && ( mvControlling->EIMCtrlType == 0 ); - - if( true == standalone && false == ForcePNBrake ) { - if( mvControlling->EIMCtrlType > 0 ) { - OK = IncBrakeEIM(); - } - else { - OK = mvOccupied->IncLocalBrakeLevel( - 1 + static_cast( std::floor( 0.5 + std::fabs( AccDesired ) ) ) ); // hamowanie lokalnym bo luzem jedzie - } - } - else { - if( /*GBH mvOccupied->BrakeCtrlPos*/ BrakeCtrlPosition + 1 == gbh_MAX ) { - if (AccDesired < -1.5) // hamowanie nagle - OK = /*mvOccupied->*/BrakeLevelAdd(1.0); //GBH - else - OK = false; - } - else { - OK = increase_train_brake(); - } - } - if( /*GBH mvOccupied->BrakeCtrlPos*/ - /*GBH mvOccupied->BrakeCtrlPos*/ BrakeCtrlPosition > 0 && mvOccupied->Hamulec->Releaser() ) { - mvOccupied->BrakeReleaser(0); - } - break; - } - case TBrakeSystem::ElectroPneumatic: { - while( mvOccupied->BrakeOpModeFlag << 1 <= mvOccupied->BrakeOpModes ) { - mvOccupied->BrakeOpModeFlag <<= 1; - } - if( mvOccupied->EngineType == TEngineType::ElectricInductionMotor ) { - if (mvOccupied->BrakeHandle == TBrakeHandle::MHZ_EN57) { - if (mvOccupied->BrakeCtrlPos < mvOccupied->Handle->GetPos(bh_FB)) - OK = mvOccupied->BrakeLevelAdd(1.0); - } - else { - OK = IncBrakeEIM(); - } - } - else if( mvOccupied->Handle->TimeEP == false ) { - auto const initialbrakeposition { mvOccupied->fBrakeCtrlPos }; - auto const AccMax { std::min( fBrake_a0[ 0 ] + 12 * fBrake_a1[ 0 ], mvOccupied->MED_amax ) }; - mvOccupied->BrakeLevelSet( - std::lerp( - mvOccupied->Handle->GetPos( bh_EPR ), - mvOccupied->Handle->GetPos( bh_EPB ), - std::clamp( -AccDesired / AccMax * mvOccupied->AIHintLocalBrakeAccFactor, 0.0, 1.0 ) ) ); - OK = mvOccupied->fBrakeCtrlPos != initialbrakeposition; - } - else if( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_EPB ) ) { - mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_EPB ) ); - if( mvOccupied->Handle->GetPos( bh_EPR ) - mvOccupied->Handle->GetPos( bh_EPN ) < 0.1 ) - mvOccupied->SwitchEPBrake( 1 ); // to nie chce działać - OK = true; - } - else if( ( mvOccupied->Handle->GetPos( bh_EPR ) - mvOccupied->Handle->GetPos( bh_EPN ) < 0.1 ) - && ( mvOccupied->EpForce <= 0.0 ) - && ( mvOccupied->EPBrakeControlPowered() ) ) { - // the handle already in the EP brake position, but the EP brake dropped out with the control's - // supply (e.g. the EP fuse off in the running brake test): switch it on again - mvOccupied->SwitchEPBrake( 1 ); - OK = ( mvOccupied->EpForce > 0.0 ); - } - else - OK = false; - break; - } - default: { break; } - } - return OK; -} - -bool TController::IncBrakeEIM() -{ // zwiększenie hamowania - bool OK = false; - switch (mvOccupied->EIMCtrlType) - { - case 0: { - if( mvOccupied->MED_amax != 9.81 ) { - auto const maxpos{mvOccupied->EIMCtrlEmergency ? 0.9 : 1.0 }; - auto const brakelimit{ -2.2 * AccDesired / fMedAmax - 1.0}; //additional limit when hinted is too low - auto const brakehinted{ -1.0 * mvOccupied->AIHintLocalBrakeAccFactor * AccDesired / fMedAmax }; //preffered by AI - auto const brakeposition{ maxpos * std::clamp(std::max(brakelimit, brakehinted), 0.0, 1.0)}; - OK = brakeposition != mvOccupied->LocalBrakePosA; - mvOccupied->LocalBrakePosA = brakeposition; - } - else { - OK = mvOccupied->IncLocalBrakeLevel( 1 ); - } - break; - } - case 1: { - OK = mvOccupied->MainCtrlPos > 0; - if( OK ) - mvOccupied->MainCtrlPos = 0; - break; - } - case 2: { - // the braking position, above the emergency brake one where the controller has it - auto const brakepos{1 + mvOccupied->EIMCtrlEmergencyPositions()}; - OK = mvOccupied->MainCtrlPos > brakepos; - if( OK ) - mvOccupied->MainCtrlPos = brakepos; - break; - } - case 3: { - if( mvOccupied->UniCtrlIntegratedLocalBrakeCtrl ) { - OK = mvOccupied->MainCtrlPos > 0; - if( OK ) - mvOccupied->MainCtrlPos = 0; - } - else { - OK = mvOccupied->IncLocalBrakeLevel( 1 ); - } - break; - } - default: { - break; - } - } - return OK; -} - -// zmniejszenie siły hamowania -bool TController::DecBrake() { - - auto OK { false }; - auto const bs { - BrakeSystem == TBrakeSystem::ElectroPneumatic && ForcePNBrake ? - TBrakeSystem::Pneumatic : - BrakeSystem }; - switch( bs ) { - case TBrakeSystem::Individual: { - auto const positionchange { 1 + std::floor( 0.5 + std::abs( AccDesired ) ) }; - OK = mvOccupied->LocalBrake == TLocalBrake::ManualBrake ? mvOccupied->DecManualBrakeLevel(positionchange) : mvOccupied->DecLocalBrakeLevel(positionchange); - break; - } - case TBrakeSystem::Pneumatic: { - auto deltaAcc { -1.0 }; - if( fBrake_a0[0] != 0.0 - || fBrake_a1[0] != 0.0 ) { - auto const pos_diff { ( is_dmu() ? 0.25 : 1.0 ) }; - // a distributor applied at all gives at least its minimum stage, about what the first position does, so - // a position short of the first one brakes no weaker than that - deltaAcc = -AccDesired * BrakeAccFactor() - ( fBrake_a0[ 0 ] + 4 * std::max( 0.0, BrakeCtrlPosition - pos_diff ) * fBrake_a1[ 0 ] ); - } - if( bUphillStart && ( false == bUphillRelease ) ) { - // starting uphill the train brake holds the train until the power does - break; - } - if( ( BrakeCtrlPosition > 0.0 ) - && ( uphill_stop_hold() ) ) { - // any release now raises the pipe, and a long train releases more than the handle is moved back, too late - // to apply again before the train stands: keep the brake as it is, and the locomotive brake with it - break; - } - if( brake_charge::holds_application( - bBrakeChargeHold, IsConsistCharged, mvOccupied->Vel < EU07_AI_NOMOVEMENT, BrakeCtrlPosition ) ) { - // the order to go came while the train still charges: released now, the wagons let go as their - // reservoirs fill and the train stands on a locomotive brake that doesn't hold it. the locomotive - // brake stays on with it - break; - } - if (deltaAcc < 0 && /*GBH mvOccupied->BrakeCtrlPosR*/ BrakeCtrlPosition > 0) { - OK = /*mvOccupied->*/ BrakeLevelAdd(-0.25); - // if ((deltaAcc < 5 * fBrake_a1[0]) && (mvOccupied->BrakeCtrlPosR >= 1.2)) - // mvOccupied->BrakeLevelAdd(-1.0); - /* if (mvOccupied->BrakeCtrlPosR < 0.74) GBH */ - if (BrakeCtrlPosition < 0.74) - /*mvOccupied->*/ BrakeLevelSet(gbh_RP); - } - // standing, the locomotive brake holds the train until its brakes are charged: off before, a train - // released on a gradient rolls with no air to brake with. nor through DecBrakeEIM(), which takes it off - // as well (the locomotive brake of a vehicle without the integrated handle) - auto const holdlocomotive { - ( false == IsConsistCharged ) - && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) }; - if( ( !OK ) && ( false == holdlocomotive ) ) { - OK = mvOccupied->DecLocalBrakeLevel(2); - } - if( ( !OK ) && ( false == holdlocomotive ) ) { - OK = DecBrakeEIM(); - } - /* - // NOTE: disabled, duplicate of AI's behaviour in UpdateSituation() - if (mvOccupied->PipePress < 3.0) - Need_BrakeRelease = true; - */ - break; - } - case TBrakeSystem::ElectroPneumatic: { - if( mvOccupied->EngineType == TEngineType::ElectricInductionMotor ) { - if( mvOccupied->BrakeHandle == TBrakeHandle::MHZ_EN57 ) { - if( mvOccupied->BrakeCtrlPos > mvOccupied->Handle->GetPos( bh_RP ) ) { - OK = mvOccupied->BrakeLevelAdd( -1.0 ); - } - } - else { - OK = DecBrakeEIM(); - } - } - else if( mvOccupied->Handle->TimeEP == false ) { - auto const initialbrakeposition { mvOccupied->fBrakeCtrlPos }; - auto const AccMax { std::min( fBrake_a0[ 0 ] + 12 * fBrake_a1[ 0 ], mvOccupied->MED_amax ) }; - mvOccupied->BrakeLevelSet( - std::lerp( - mvOccupied->Handle->GetPos( bh_EPR ), - mvOccupied->Handle->GetPos( bh_EPB ), - std::clamp( -AccDesired / AccMax * mvOccupied->AIHintLocalBrakeAccFactor, 0.0, 1.0 ) ) ); - OK = mvOccupied->fBrakeCtrlPos != initialbrakeposition; - } - else { - OK = false; - if (mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos(bh_EPR)) { - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_EPR)); - OK = true; - } - if (mvOccupied->Handle->GetPos(bh_EPR) - mvOccupied->Handle->GetPos(bh_EPN) < 0.1) { - OK = OK || mvOccupied->SwitchEPBrake(1); - } - } - if( !OK ) { - OK = mvOccupied->DecLocalBrakeLevel( 2 ); - } - break; - } - default: { - break; - } - } - return OK; -} - -void TController::LapBrake() { - - if( mvOccupied->Handle->TimeEP ) { - if( mvOccupied->Handle->GetPos( bh_EPR ) - mvOccupied->Handle->GetPos( bh_EPN ) < 0.1 ) { - mvOccupied->SwitchEPBrake( 0 ); - } - else { - mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_EPN ) ); - } - } -} - -void TController::ZeroLocalBrake() { - - if( mvOccupied->UniCtrlIntegratedLocalBrakeCtrl ) { - while( DecBrakeEIM() ) { - ; - } - } - else { - mvOccupied->DecLocalBrakeLevel( LocalBrakePosNo ); - } -} - -bool TController::DecBrakeEIM() -{ // zmniejszenie siły hamowania - bool OK = false; - switch (mvOccupied->EIMCtrlType) - { - case 0: { - if( mvOccupied->MED_amax != 9.81 ) { - auto const desiredacceleration { ( mvOccupied->Vel > EU07_AI_NOMOVEMENT ? AccDesired : std::max( 0.0, AccDesired ) ) }; - auto const brakeposition { std::clamp( -1.0 * mvOccupied->AIHintLocalBrakeAccFactor * desiredacceleration / mvOccupied->MED_amax, 0.0, 1.0 ) }; - OK = brakeposition != mvOccupied->LocalBrakePosA; - mvOccupied->LocalBrakePosA = brakeposition; - } - else { - OK = mvOccupied->DecLocalBrakeLevel( 1 ); - } - break; - } - case 1: { - OK = mvOccupied->MainCtrlPos < 2; - if( OK ) - mvOccupied->MainCtrlPos = 2; - break; - } - case 2: { - auto const neutralpos{mvOccupied->MainCtrlNoPowerPos()}; - OK = mvOccupied->MainCtrlPos < neutralpos; - if( OK ) - mvOccupied->MainCtrlPos = neutralpos; - break; - } - case 3: { - OK = mvOccupied->MainCtrlPos < mvOccupied->MainCtrlMaxDirChangePos; - if( OK ) - mvOccupied->MainCtrlPos = mvOccupied->MainCtrlMaxDirChangePos; - break; - } - } - return OK; -} - -bool TController::IncSpeed() -{ // zwiększenie prędkości; zwraca false, jeśli dalej się nie da zwiększać - auto OK { false }; - switch (mvOccupied->EngineType) - { - case TEngineType::None: // McZapkie-041003: wagon sterowniczy - if (mvControlling->MainCtrlPosNo > 0) // jeśli ma czym kręcić - drivingFlags.incSpeed = true; // ustawienie flagi jazdy - return false; - case TEngineType::ElectricSeriesMotor: - if (mvPantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) // jeśli pantografujący - { - if (fOverhead2 >= 0.0) // a jazda bezprądowa ustawiana eventami (albo opuszczenie) - return false; // to nici z ruszania - if (iOverheadZero) // jazda bezprądowa z poziomu toru ustawia bity - return false; // to nici z ruszania - } - // TODO: move all fVoltage assignments to a single, more generic place - if( mvControlling->EnginePowerSource.SourceType == TPowerSource::Accumulator ) { - fVoltage = mvControlling->BatteryVoltage; - } - if (!IsAnyMotorOverloadRelayOpen && !mvControlling->ControlPressureSwitch && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->StLinFlag) && (Ready || drivingFlags.press)) { - // youBy polecił dodać 2012-09-08 v367 - // na pozycji 0 przejdzie, a na pozostałych będzie czekać, aż się załączą liniowe (zgaśnie DelayCtrlFlag) - auto const usehighoverloadrelaythreshold{mvControlling->TrainType != train_type::et42 // ET42 uses these variables for different purpose. TODO: fix this - && mvControlling->ImaxHi > mvControlling->ImaxLo && mvOccupied->Vel < (mvControlling->IsMotorOverloadRelayHighThresholdOn() ? 30.0 : 20.0) && - iVehicles - ControlledEnginesCount > 0 - // && ( std::fabs( mvControlling->Im ) > 0.85 * mvControlling->Imax ) - && mvControlling->Imax * mvControlling->EngineVoltage * ControlledEnginesCount / - (fMass * (fAccGravity == 0.025 ? -0.01 : // prevent div/0 - fAccGravity - 0.025)) < - -2.8}; - // use series mode: - // if high threshold is set for motor overload relay, - // if the power station is heavily burdened, - // if it generates enough traction force - // to build up speed to 30/40 km/h for passenger/cargo train (10 km/h less if going uphill) - auto const sufficienttractionforce{std::abs(mvControlling->Ft) * ControlledEnginesCount > (IsHeavyCargoTrain ? 75 : 50) * 1000.0}; - auto const sufficientacceleration{AbsAccS >= (IsHeavyCargoTrain ? 0.03 : IsCargoTrain ? 0.06 : 0.09)}; - auto const seriesmodefieldshunting{mvControlling->ScndCtrlPos > 0 && mvControlling->RList[mvControlling->MainCtrlPos].Bn == 1}; - auto const parallelmodefieldshunting{mvControlling->ScndCtrlPos > 0 && mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1}; - auto const minvoltage{(mvPantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? mvPantographUnit->EnginePowerSource.CollectorParameters.MinV : 0.0)}; - auto const maxvoltage{(mvPantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? mvPantographUnit->EnginePowerSource.CollectorParameters.MaxV : 0.0)}; - auto const seriesmodevoltage{std::lerp(minvoltage, maxvoltage, IsHeavyCargoTrain ? 0.35 : 0.40)}; - auto const useseriesmode = mvControlling->Imax > mvControlling->ImaxLo || true == usehighoverloadrelaythreshold || fVoltage < seriesmodevoltage || - (true == sufficientacceleration && true == sufficienttractionforce && - mvOccupied->Vel <= (IsCargoTrain ? 40 : 30) + (seriesmodefieldshunting ? 5 : 0) - (fAccGravity < -0.025 ? 10 : 0)); - // when not in series mode use the first available parallel mode configuration until 50/60 km/h for passenger/cargo train - // (if there's only one parallel mode configuration it'll be used regardless of current speed) - auto const usefieldshunting = mvControlling->StLinFlag && mvControlling->RList[mvControlling->MainCtrlPos].R < 0.01 && false == mvControlling->IsScndCtrlLockedByMainCtrl() && - (useseriesmode ? mvControlling->RList[mvControlling->MainCtrlPos].Bn == 1 : - true == sufficientacceleration && true == sufficienttractionforce && mvOccupied->Vel <= (IsCargoTrain ? 60 : 50) + (parallelmodefieldshunting ? 5 : 0) ? - mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1 : - mvControlling->MainCtrlPos == mvControlling->MainCtrlPosNo); - - // if needed enable high threshold for overload relay... - if (mvControlling->TrainType != train_type::et42) - { // ET42 uses these variables for different purpose. TODO: fix this - if (usehighoverloadrelaythreshold) - { - if (mvControlling->Imax < mvControlling->ImaxHi) - { - // to enable this setting we'll typically need the main controller in series mode (which is not guaranteed) - if (mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1) - { - if (false == mvControlling->IsScndCtrlNoPowerPos()) - { - mvControlling->DecScndCtrl(2); - } - while (false == mvControlling->IsMainCtrlNoPowerPos() && mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1) - { - mvControlling->DecMainCtrl(1); // kręcimy nastawnik jazdy o 1 wstecz - } - } - mvControlling->CurrentSwitch(true); // rozruch wysoki (za to może się ślizgać) - } - } - // ...or disable high threshold for overload relay if no longer needed - else - { - if (mvControlling->IsMotorOverloadRelayHighThresholdOn() && std::fabs(mvControlling->Im) < mvControlling->ImaxLo) - { - mvControlling->CurrentSwitch(false); // rozruch wysoki wyłącz - } - } - } - - double Vs = 99999; - if (usefieldshunting ? mvControlling->ScndCtrlPos < mvControlling->ScndCtrlPosNo : mvControlling->MainCtrlPos < mvControlling->MainCtrlPosNo) - { - Vs = ESMVelocity(!usefieldshunting); - } - - if (std::abs(mvControlling->Im) < (fReady < 0.4 ? mvControlling->Imin : mvControlling->IminLo) || mvControlling->Vel > Vs) - { - // Ra: wywalał nadmiarowy, bo Im może być ujemne; jak nie odhamowany, to nie przesadzać z prądem - if (usefieldshunting) - { - // to dać bocznik - // engage the shuntfield only if there's sufficient power margin to draw from - auto const sufficientpowermargin{fVoltage - seriesmodevoltage > (IsHeavyCargoTrain ? 100.0 : 75.0) * ControlledEnginesCount}; - - OK = sufficientpowermargin ? mvControlling->IncScndCtrl(1) : true; - } - else - { - // jeśli ustawiony bocznik to bocznik na zero po chamsku - if (mvControlling->ScndCtrlPos) - { - mvControlling->DecScndCtrl(2); - } - // kręcimy nastawnik jazdy - // don't draw too much power; - // keep from dropping into series mode when entering/using parallel mode, and from shutting down in the series mode - auto const sufficientpowermargin{fVoltage - - (mvControlling->RList[std::min(mvControlling->MainCtrlPos + 1, mvControlling->MainCtrlPosNo)].Bn == 1 ? minvoltage : seriesmodevoltage) > - (IsHeavyCargoTrain ? 100.0 : 75.0) * ControlledEnginesCount}; - - OK = sufficientpowermargin && false == mvControlling->DelayCtrlFlag ? mvControlling->IncMainCtrl(1) : true; - // czekaj na 1 pozycji, zanim się nie włączą liniowe - if (true == mvControlling->StLinFlag) - { - drivingFlags.incSpeed = true; - } - else - { - drivingFlags.incSpeed = false; - } - - if (mvControlling->Im == 0 && mvControlling->MainCtrlPowerPos() > 1) - { - // brak prądu na dalszych pozycjach - // nie załączona lokomotywa albo wywalił nadmiarowy - Need_TryAgain = true; - } - } - } - else - { - OK = false; - } - } -// mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania - break; - case TEngineType::Dumb: - if (!IsAnyMotorOverloadRelayOpen && (Ready || drivingFlags.press)) - //{(BrakePress<=0.01*MaxBrakePress)} - { - OK = IncSpeedEIM(); - if (!OK) - OK = mvControlling->IncMainCtrl(1); - if (!OK) - OK = mvControlling->IncScndCtrl(1); - } - break; - case TEngineType::DieselElectric: - if (!IsAnyMotorOverloadRelayOpen && !mvControlling->ControlPressureSwitch && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->StLinFlag) && (Ready || drivingFlags.press)) { - // youBy polecił dodać 2012-09-08 v367 - // na pozycji 0 przejdzie, a na pozostałych będzie czekać, aż się załączą liniowe (zgaśnie DelayCtrlFlag) - //{(BrakePress<=0.01*MaxBrakePress)} - OK = IncSpeedEIM(); - if (!OK) - OK = mvControlling->IncMainCtrl(1); - if (!OK) - OK = mvControlling->IncScndCtrl(1); - } - break; - case TEngineType::ElectricInductionMotor: - if( !IsAnyMotorOverloadRelayOpen && (Ready || drivingFlags.press || mvOccupied->ShuntMode) ) { - //{(BrakePress<=0.01*MaxBrakePress)} - OK = IncSpeedEIM(); - if (mvControlling->SpeedCtrl && mvControlling->Mains) - { - // cruise control - auto const couplinginprogress{true == drivingFlags.connect && true == OrderCurrentGet().HasAll(DriverOrder::connect)}; - auto const SpeedCntrlVel{(ActualProximityDist > std::max(50.0, fMaxProximityDist) || couplinginprogress ? VelDesired : min_speed(VelDesired, VelNext))}; - if (SpeedCntrlVel >= mvControlling->SpeedCtrlUnit.MinVelocity && - SpeedCntrlVel - mvControlling->SpeedCtrlUnit.MinVelocity == quantize(SpeedCntrlVel - mvControlling->SpeedCtrlUnit.MinVelocity, mvControlling->SpeedCtrlUnit.VelocityStep)) - { - SpeedCntrl(SpeedCntrlVel); - } - else if (SpeedCntrlVel > 0.1) - { - SpeedCntrl(0.0); - mvControlling->DecScndCtrl(2); - } - } - } - break; - case TEngineType::WheelsDriven: - if (!mvControlling->CabActive) - mvControlling->CabActivisation(); - if (sin(mvControlling->eAngle) > 0) - mvControlling->IncMainCtrl(3 + 3 * floor(0.5 + fabs(AccDesired))); - else - mvControlling->DecMainCtrl(3 + 3 * floor(0.5 + fabs(AccDesired))); - break; - case TEngineType::DieselEngine: - if (mvControlling->ShuntModeAllow) - { // dla 2Ls150 można zmienić tryb pracy, jeśli jest w liniowym i nie daje rady (wymaga zerowania kierunku) - // mvControlling->ShuntMode=(OrderList[OrderPos]&Shunt)||(fMass>224000.0); - } - if (mvControlling->SpeedCtrl && mvControlling->Mains) {// cruise control - auto const couplinginprogress { true == drivingFlags.connect && true == OrderCurrentGet().HasAll(DriverOrder::connect) }; - auto const SpeedCntrlVel { ( - ActualProximityDist > std::max(50.0, fMaxProximityDist) || couplinginprogress ? - VelDesired : - min_speed( VelDesired, VelNext ) ) }; - if( SpeedCntrlVel >= mvControlling->SpeedCtrlUnit.MinVelocity - && SpeedCntrlVel - mvControlling->SpeedCtrlUnit.MinVelocity == quantize(SpeedCntrlVel - mvControlling->SpeedCtrlUnit.MinVelocity, mvControlling->SpeedCtrlUnit.VelocityStep) ) { - SpeedCntrl(SpeedCntrlVel); - } - else if (SpeedCntrlVel > 0.1) { - SpeedCntrl(0.0); - mvControlling->DecScndCtrl( 2 ); - } - } - if (mvControlling->EIMCtrlType > 0) { - if (true == Ready) - { - bool max = mvControlling->Vel > mvControlling->dizel_minVelfullengage - || (mvControlling->SpeedCtrl && mvControlling->ScndCtrlPos > 0); - DizelPercentage = max ? 100 : 1; - } - break; - } - else { - if( true == Ready ) { - if( mvControlling->Vel > mvControlling->dizel_minVelfullengage - && mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0 ) { - OK = mvControlling->IncMainCtrl( 1 ); - } - if( mvControlling->RList[ mvControlling->MainCtrlPos ].Mn == 0 ) { - OK = mvControlling->IncMainCtrl( 1 ); - } - } - } - // TODO: move this check to a more suitable place, or scrap it - if( false == mvControlling->Mains ) { - SpeedCntrl(0.0); - mvControlling->DecScndCtrl( 2 ); - cue_action( driver_hint::linebreakerclose ); - cue_action( driver_hint::converteron ); - cue_action( driver_hint::compressoron ); - } - break; - } - return OK; -} - -void TController::ZeroSpeed( bool const Enforce ) { - - while( DecSpeed( Enforce ) ) { - ; - } -} - -bool TController::DecSpeed(bool force) -{ // zmniejszenie prędkości (ale nie hamowanie) - bool OK = false; // domyślnie false, aby wyszło z pętli while - switch (mvOccupied->EngineType) - { - case TEngineType::None: // McZapkie-041003: wagon sterowniczy - drivingFlags.incSpeed = false; // usunięcie flagi jazdy - if (force && mvControlling->MainCtrlPosNo > 0) // przy aktywacji kabiny jest potrzeba natychmiastowego wyzerowania - // McZapkie-041003: wagon sterowniczy, np. EZT - mvControlling->DecMainCtrl(std::min(mvControlling->MainCtrlPowerPos(), 2)); - // mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania - return false; - case TEngineType::ElectricSeriesMotor: - OK = mvControlling->DecScndCtrl(2); // najpierw bocznik na zero - if (!OK) - OK = mvControlling->DecMainCtrl( std::min( mvControlling->MainCtrlPowerPos(), 2 ) ); -// mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania - break; - case TEngineType::Dumb: - case TEngineType::DieselElectric: - OK = mvControlling->DecScndCtrl(2); - if (!OK) - OK = mvControlling->DecMainCtrl( std::min( mvControlling->MainCtrlPowerPos(), 2 + mvControlling->MainCtrlPowerPos() / 2 ) ); - break; - case TEngineType::ElectricInductionMotor: - OK = DecSpeedEIM(); - break; - case TEngineType::WheelsDriven: - if (!mvControlling->CabActive) - mvControlling->CabActivisation(); - if (sin(mvControlling->eAngle) < 0) - mvControlling->IncMainCtrl(3 + 3 * floor(0.5 + fabs(AccDesired))); - else - mvControlling->DecMainCtrl(3 + 3 * floor(0.5 + fabs(AccDesired))); - break; - case TEngineType::DieselEngine: - if (mvControlling->EIMCtrlType > 0) - { - DizelPercentage = 0; - if (force) { - SpeedCntrl(0.0); //wylacz od razu tempomat - mvControlling->DecScndCtrl(2); - } - if (VelDesired > 0.1 && mvControlling->SpeedCtrlUnit.MinVelocity > VelDesired) { - SpeedCntrl(0.0); //wylacz od razu tempomat - mvControlling->DecScndCtrl(2); - } - break; - } - - if (mvControlling->Vel > mvControlling->dizel_minVelfullengage) - { - if (mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0) - OK = mvControlling->DecMainCtrl(1); - } - else { - while( mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0 - && mvControlling->MainCtrlPowerPos() > 1 ) { - OK = mvControlling->DecMainCtrl( 1 ); - } - } - if (force) { // przy aktywacji kabiny jest potrzeba natychmiastowego wyzerowania - OK = mvControlling->DecMainCtrl(mvControlling->MainCtrlPowerPos() > 2 ? 2 : 1); - SpeedCntrl(0.0); //wylacz od razu tempomat - mvControlling->DecScndCtrl( 2 ); - } - break; - } - return OK; -}; - -bool TController::IncSpeedEIM() { - - bool OK = false; // domyślnie false, aby wyszło z pętli while - switch( mvControlling->EIMCtrlType ) { - case 0: - OK = mvControlling->IncMainCtrl( 1 ); - break; - case 1: - OK = mvControlling->MainCtrlPos < 6; - if( OK ) { - mvControlling->MainCtrlPos = 6; - } -/* - // TBD, TODO: set position based on desired acceleration? - OK = mvControlling->MainCtrlPos < mvControlling->MainCtrlPosNo; - if( OK ) { - mvControlling->MainCtrlPos = safe_clamp( mvControlling->MainCtrlPos + 1, 6, mvControlling->MainCtrlPosNo ); - } -*/ - break; - case 2: { - auto const powerpos{4 + mvControlling->EIMCtrlEmergencyPositions()}; - OK = mvControlling->MainCtrlPos < powerpos; - if( OK ) { - mvControlling->MainCtrlPos = powerpos; - } - break; - } - } - return OK; -} - -bool TController::DecSpeedEIM( int const Amount ) -{ // zmniejszenie prędkości (ale nie hamowanie) - bool OK = false; // domyślnie false, aby wyszło z pętli while - switch( mvControlling->EIMCtrlType ) { - case 0: { - OK = mvControlling->DecMainCtrl( Amount ); - break; - } - case 1: { - OK = mvControlling->MainCtrlPos > 4; - if( OK ) { - mvControlling->MainCtrlPos = 4; - } - break; - } - case 2: { - if( AccDesired > 0 - && mvControlling->SpeedCtrlUnit.IsActive - && mvControlling->SpeedCtrlUnit.PowerStep > 0 - && mvControlling->SpeedCtrlUnit.DesiredPower > mvControlling->SpeedCtrlUnit.MinPower ) { - mvControlling->SpeedCtrlPowerDec(); - } - else { - auto const holdpos{2 + mvControlling->EIMCtrlEmergencyPositions()}; - OK = mvControlling->MainCtrlPos > holdpos; - if( OK ) { - mvControlling->MainCtrlPos = holdpos; - } - } - break; - } - default: { - break; - } - } - return OK; -} - -void TController::BrakeLevelSet(double b) -{ // ustawienie pozycji hamulca na wartość (b) w zakresie od -2 do BrakeCtrlPosNo - // jedyny dopuszczalny sposób przestawienia hamulca zasadniczego - if (BrakeCtrlPosition == b) - return; // nie przeliczać, jak nie ma zmiany - BrakeCtrlPosition = std::clamp(b, (double)gbh_MIN, (double)gbh_MAX); - fBrakeHeldTime = 0.0; -} - -bool TController::BrakeLevelAdd(double b) -{ // dodanie wartości (b) do pozycji hamulca (w tym ujemnej) - // zwraca false, gdy po dodaniu było by poza zakresem - BrakeLevelSet(BrakeCtrlPosition + b); - return b > 0.0 ? BrakeCtrlPosition < gbh_MAX : - BrakeCtrlPosition > -1.0; // true, jeśli można kontynuować -} - -// Ra: regulacja prędkości, wykonywana w każdym przebłysku świadomości AI -// ma dokręcać do bezoporowych i zdejmować pozycje w przypadku przekroczenia prądu -void TController::SpeedSet() { - - if( false == AIControllFlag ) { return; } - - switch (mvOccupied->EngineType) - { - case TEngineType::None: { // McZapkie-041003: wagon sterowniczy - if (mvControlling->MainCtrlPosNo > 0) - { // jeśli ma czym kręcić - // TODO: sprawdzanie innego czlonu //if (!FuseFlagCheck()) - if( ( false == drivingFlags.incSpeed ) ) { - // przetok rozłączać od razu (no dependency on fActionTime) - while( mvControlling->MainCtrlPos - && mvControlling->DecMainCtrl(1) ) { - ; // na zero - } - if( fActionTime >= 0.0 ) { - fActionTime = -5.0; // niech trochę potrzyma - } -// mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania - } - else { - // jak ma jechać - if( fActionTime < 0.0 ) { break; } - if( false == Ready ) { break; } - - if( mvOccupied->DirActive > 0 ) { - mvOccupied->DirectionForward(); //żeby EN57 jechały na drugiej nastawie - } - - if( mvControlling->MainCtrlPos > 0 - && false == mvControlling->StLinFlag ) { - // jak niby jedzie, ale ma rozłączone liniowe to na zero i czekać na przewalenie kułakowego - mvControlling->DecMainCtrl( 2 ); - } - else { - // ruch nastawnika uzależniony jest od aktualnie ustawionej pozycji - switch( mvControlling->MainCtrlPos ) { - case 0: - if( mvControlling->MainCtrlActualPos ) { - // jeśli kułakowy nie jest wyzerowany to czekać na wyzerowanie - break; - } - mvControlling->IncMainCtrl( 1 ); // przetok; bez "break", bo nie ma czekania na 1. pozycji - case 1: - if( VelDesired >= 20 ) - mvControlling->IncMainCtrl( 1 ); // szeregowa - case 2: - if( VelDesired >= 50 ) - mvControlling->IncMainCtrl( 1 ); // równoległa - case 3: - if( VelDesired >= 80 ) - mvControlling->IncMainCtrl( 1 ); // bocznik 1 - case 4: - if( VelDesired >= 90 ) - mvControlling->IncMainCtrl( 1 ); // bocznik 2 - case 5: - if( VelDesired >= 100 ) - mvControlling->IncMainCtrl( 1 ); // bocznik 3 - } - } - if( mvControlling->MainCtrlPos ) // jak załączył pozycję - { - fActionTime = -5.0; // niech trochę potrzyma -// mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania - } - } - } - break; - } - case TEngineType::ElectricSeriesMotor: { -/* - if (Ready || (drivingFlags.press)) { // o ile może jechać -// if (fAccGravity < -0.10) // i jedzie pod górę większą niż 10 promil - { // procedura wjeżdżania na ekstremalne wzniesienia - if( std::fabs( mvControlling->Im ) > 0.85 * mvControlling->Imax ) { // a prąd jest większy niż 85% nadmiarowego - if( mvControlling->Imax * mvControlling->EngineVoltage / ( fMass * fAccGravity ) < -2.8 ) // a na niskim się za szybko nie pojedzie - { // włączenie wysokiego rozruchu; - // (I*U)[A*V=W=kg*m*m/sss]/(m[kg]*a[m/ss])=v[m/s]; 2.8m/ss=10km/h - if( mvControlling->RList[ mvControlling->MainCtrlPos ].Bn > 1 ) { // jeśli jedzie na równoległym, to zbijamy do szeregowego, aby włączyć wysoki rozruch - if( mvControlling->ScndCtrlPos > 0 ) { // jeżeli jest bocznik - mvControlling->DecScndCtrl( 2 ); // wyłączyć bocznik, bo może blokować skręcenie NJ - } - do { // skręcanie do bezoporowej na szeregowym - mvControlling->DecMainCtrl( 1 ); // kręcimy nastawnik jazdy o 1 wstecz - } - while( ( false == mvControlling->IsMainCtrlNoPowerPos() ) - && ( mvControlling->RList[ mvControlling->MainCtrlPos ].Bn > 1 ) ); // oporowa zapętla - } - if( mvControlling->Imax < mvControlling->ImaxHi ) { // jeśli da się na wysokim - mvControlling->CurrentSwitch( true ); // rozruch wysoki (za to może się ślizgać) - } - if( ReactionTime > 0.1 ) { - ReactionTime = 0.1; // orientuj się szybciej - } - } // if (Im>Imin) - } - if( std::fabs( mvControlling->Im ) > 0.96 * mvControlling->Imax ) {// jeśli prąd jest duży (można 690 na 750) - if( mvControlling->ScndCtrlPos > 0 ) { // jeżeli jest bocznik - mvControlling->DecScndCtrl( 2 ); // zmniejszyć bocznik - } - else { - mvControlling->DecMainCtrl( 1 ); // kręcimy nastawnik jazdy o 1 wstecz - } - } - } -// else // gdy nie jedzie ambitnie pod górę - { // sprawdzenie, czy rozruch wysoki jest potrzebny - if( ( mvControlling->Imax > mvControlling->ImaxLo ) - && ( mvOccupied->Vel >= 30.0 ) ) { // jak się rozpędził -// if (fAccGravity > -0.02) // a i pochylenie mnijsze niż 2‰ - mvControlling->CurrentSwitch( false ); // rozruch wysoki wyłącz - } - } - } -*/ - break; - } - case TEngineType::Dumb: { - break; - } - case TEngineType::DieselElectric: { - break; - } - case TEngineType::ElectricInductionMotor: { - break; - } - case TEngineType::DieselEngine: { - // Ra 2014-06: "automatyczna" skrzynia biegów... - auto const &motorparams { mvControlling->MotorParam[ mvControlling->ScndCtrlPos ] }; - auto const velocity { ( mvControlling->ShuntMode ? mvControlling->AnPos : 1.0 ) * mvControlling->Vel }; - if( false == motorparams.AutoSwitch ) { - // gdy biegi ręczne - // jak prędkość większa niż procent maksymalnej na danym biegu, wrzucić wyższy - if( velocity > 0.75 * motorparams.mfi ) { - // ...presuming there is a higher gear - if( mvControlling->ScndCtrlPos < mvControlling->ScndCtrlPosNo ) { - mvControlling->DecMainCtrl( 2 ); - while( mvControlling->IncScndCtrl(1) - && mvControlling->MotorParam[mvControlling->ScndCtrlPos].mIsat == 0.0 ) { // jeśli bieg jałowy to kolejny - ; - } - } - } - // jak prędkość mniejsza niż minimalna na danym biegu, wrzucić niższy - else if( velocity < motorparams.fi && mvControlling->ScndCtrlPos > 1 ) { - // ... but ensure we don't switch all way down to 0 - mvControlling->DecMainCtrl(2); - while (mvControlling->ScndCtrlPos > 1 // repeat the entry check as we're working in a loop - && mvControlling->DecScndCtrl(1) && mvControlling->MotorParam[mvControlling->ScndCtrlPos].mIsat == 0.0) - { // jeśli bieg jałowy to kolejny - ; - } - } - } - break; - } - default: { - break; - } - } // enginetype -}; - -void TController::SpeedCntrl(double DesiredSpeed) -{ - if( false == mvControlling->SpeedCtrl ) { return; } - - if (mvControlling->IsSpeedCtrlSeparate()) - { - // a switch of its own, the secondary controller left to the field shunting (eu07/maszyna#69) - if (DesiredSpeed < 0.1) { - DesiredSpeed = 0; - } - mvControlling->SpeedCtrlSwitch(DesiredSpeed > 0); - mvControlling->RunCommand(VehicleCommand::speedControl, DesiredSpeed, mvControlling->CabActive); - } - else if (mvControlling->EngineType == TEngineType::DieselEngine) - { - if (DesiredSpeed < 0.1) { - mvControlling->DecScndCtrl(2); - DesiredSpeed = 0; - } - else if (mvControlling->ScndCtrlPos < 1) { - mvControlling->IncScndCtrl(1); - } - mvControlling->RunCommand(VehicleCommand::speedControl, DesiredSpeed, mvControlling->CabActive); - } - else - if (mvControlling->ScndCtrlPosNo == 1) - { - mvControlling->IncScndCtrl(1); - mvControlling->RunCommand(VehicleCommand::speedControl, DesiredSpeed, mvControlling->CabActive); - } - else if (mvControlling->ScndCtrlPosNo > 1 && !mvOccupied->SpeedCtrlTypeTime) - { - int DesiredPos = 1 + mvControlling->ScndCtrlPosNo * ((DesiredSpeed - 1.0) / mvControlling->Vmax); - while( mvControlling->ScndCtrlPos > DesiredPos && true == mvControlling->DecScndCtrl(1) ) { ; } // all work is done in the condition loop - while( mvControlling->ScndCtrlPos < DesiredPos && true == mvControlling->IncScndCtrl(1) ) { ; } // all work is done in the condition loop - } - - if( mvControlling->SpeedCtrlUnit.PowerStep > 0 && mvControlling->IsSpeedCtrlEngaged() ) { - while (mvControlling->SpeedCtrlUnit.DesiredPower < mvControlling->SpeedCtrlUnit.MaxPower) - { - mvControlling->SpeedCtrlPowerInc(); - } - } -}; - -void TController::SetTimeControllers() -{ - // TBD, TODO: rework this method to use hint system and regardless of driver type - if( false == AIControllFlag || 0 == mvOccupied->CabActive ) { return; } - - //1. Check the type of Main Brake Handle - if( BrakeSystem == TBrakeSystem::Pneumatic || ForcePNBrake ) - { - if (mvOccupied->Handle->Time) - { - auto const pressuredifference { mvOccupied->Handle->GetCP() - ( mvOccupied->HighPipePress - BrakeCtrlPosition * 0.25*mvOccupied->DeltaPipePress ) }; - if (BrakeCtrlPosition > 0 && pressuredifference > 0.05) - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_FB)); - else if (BrakeCtrlPosition > 0 && pressuredifference < -0.05) - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_RP)); - else if (BrakeCtrlPosition == 0) - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_RP)); - else if (BrakeCtrlPosition == -1) - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_FS)); - else if (BrakeCtrlPosition == -2) - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_NP)); - } - if( mvOccupied->BrakeHandle == TBrakeHandle::FV4a ) { - mvOccupied->BrakeLevelSet( BrakeCtrlPosition ); - } - if( mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K8P - || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_EN57 ) { - if( BrakeCtrlPosition == 0 ) { - mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_RP ) ); - } - else if( BrakeCtrlPosition == -1 ) { - mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_FS ) ); - } - else if( BrakeCtrlPosition == -2 ) { - mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_NP ) ); - } - else if( BrakeCtrlPosition > 4.5 ) { - mvOccupied->BrakeLevelSet( 10 ); - } - else if( BrakeCtrlPosition > 3.70 ) { - mvOccupied->BrakeLevelSet( 9 ); - } - else { - mvOccupied->BrakeLevelSet( round( ( BrakeCtrlPosition * 0.4 - 0.1 ) / 0.15 ) ); - } - } - } - //2. Check the type of Secondary Brake Handle - - //3. Check the type od EIMCtrlType -/* - if (mvOccupied->EIMCtrlType > 0) - { - if (mvOccupied->EIMCtrlType == 1) //traxx - { - if (mvOccupied->LocalBrakePosA > 0.95) mvOccupied->MainCtrlPos = 0; - } - else if (mvOccupied->EIMCtrlType == 2) //elf - { - if (mvOccupied->LocalBrakePosA > 0.95) mvOccupied->MainCtrlPos = 1; - } - } -*/ - if( mvOccupied->UniCtrlIntegratedLocalBrakeCtrl - && mvOccupied->LocalBrakePosA > 0.95 ) { - while( IncBrakeEIM() ) { ; } - } - - //4. Check Speed Control System - if (mvOccupied->EngineType == TEngineType::ElectricInductionMotor && mvOccupied->ScndCtrlPosNo > 1 && mvOccupied->SpeedCtrlTypeTime) - { - double SpeedCntrlVel = - ActualProximityDist > std::max(50.0, fMaxProximityDist) ? - VelDesired : - min_speed(VelDesired, VelNext); - SpeedCntrlVel = 10 * std::floor(SpeedCntrlVel*0.1); - if (mvOccupied->ScndCtrlPosNo == 4) - { - if (mvOccupied->NewSpeed + 0.1 < SpeedCntrlVel) - mvOccupied->ScndCtrlPos = 3; - if (mvOccupied->NewSpeed - 0.1 > SpeedCntrlVel) - mvOccupied->ScndCtrlPos = 1; - } - } - //5. Check Main Controller in Dizels - //5.1. Digital controller in DMUs with hydro - if (mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->EIMCtrlType == 3) - { - - DizelPercentage_Speed = DizelPercentage; //wstepnie procenty - auto MinVel{ std::min(mvControlling->hydro_TC_LockupSpeed, mvControlling->Vmax / 6) }; //minimal velocity - //when speed controll unit is active - start with the procedure - if (mvControlling->SpeedCtrl && mvControlling->ScndCtrlPos > 0) { - if (mvControlling->ScndCtrlPos > 0 && mvControlling->Vel < 1 + mvControlling->SpeedCtrlUnit.StartVelocity && DizelPercentage > 0) - DizelPercentage_Speed = 101; //keep last position to start - } - else if (VelDesired > MinVel) //more power for faster ride - { - auto const Factor{ 10 * mvControlling->Vmax / (mvControlling->Vmax + 3 * mvControlling->Vel) }; - auto DesiredPercentage{ std::clamp( - VelDesired > mvControlling->Vel ? (VelDesired - mvControlling->Vel) / Factor : 0, - 0.0, 1.0) }; //correction for reaching desired velocity - if (VelDesired < 0.5 * mvControlling->Vmax //low velocity and reaching desired - && VelDesired - mvControlling->Vel < 10) { - DesiredPercentage = std::min(DesiredPercentage, 0.75); - } - DizelPercentage_Speed = std::round(DesiredPercentage * DizelPercentage); - } - else //slow acceleration during shunting wth minimal velocity - { - DizelPercentage_Speed = std::min(DizelPercentage, mvControlling->Vel < 0.99 * VelDesired ? 1 : 0); - } - - auto const DizelActualPercentage { int(100.4 * mvControlling->eimic_real) }; - - auto const PosInc { mvControlling->MainCtrlPosNo }; - auto PosDec { 0 }; - for( int i = PosInc; i >= 0; --i ) { - if( mvControlling->UniCtrlList[i].SetCtrlVal <= 0 - && mvControlling->UniCtrlList[i].SpeedDown > 0.01 ) { - PosDec = i; - break; - } - } - - if( std::abs( DizelPercentage_Speed - DizelActualPercentage ) > 0 ) { - - if( PosDec > 0 - && ( DizelActualPercentage - DizelPercentage_Speed > 50 - || ( DizelPercentage_Speed == 0 - && DizelActualPercentage > 10 ) ) ) { - //one position earlier should be fast decreasing - PosDec -= 1; - } - auto const DesiredPos { ( - DizelPercentage_Speed > DizelActualPercentage ? - PosInc : - PosDec ) }; - while( mvControlling->MainCtrlPos > DesiredPos ) { mvControlling->DecMainCtrl( 1 ); } - while( mvControlling->MainCtrlPos < DesiredPos ) { mvControlling->IncMainCtrl( 1 ); } - } - if (BrakeCtrlPosition < 0.1) //jesli nie hamuje - mvOccupied->BrakeLevelSet(mvControlling->UniCtrlList[mvControlling->MainCtrlPos].mode); //zeby nie bruzdzilo machanie zespolonym - } - else - //5.2. Analog direct controller - if (mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->Vmax > 30) - { - int MaxPos = mvControlling->MainCtrlPosNo; - int MinPos = MaxPos; - for (int i = MaxPos; i > 1 && mvControlling->RList[i].Mn > 0; i--) MinPos = i; - if (MaxPos > MinPos && mvControlling->MainCtrlPos > 0 && AccDesired > 0) - { - double Factor = 5 * mvControlling->Vmax / (mvControlling->Vmax + mvControlling->Vel); - int DesiredPos = MinPos + (MaxPos - MinPos)*(VelDesired > mvControlling->Vel ? (VelDesired - mvControlling->Vel) / Factor : 0); - if (DesiredPos > MaxPos) DesiredPos = MaxPos; - if (DesiredPos < MinPos) DesiredPos = MinPos; - if (!mvControlling->SlippingWheels) - { - while (mvControlling->MainCtrlPos > DesiredPos) mvControlling->DecMainCtrl(1); - if (mvControlling->Vel>mvControlling->dizel_minVelfullengage) - while (mvControlling->MainCtrlPos < DesiredPos) mvControlling->IncMainCtrl(1); - } - } - } - // 5.5 universal control for diesel electric vehicles - if (mvControlling->EngineType == TEngineType::DieselElectric && mvControlling->EIMCtrlType == 3 && AccDesired >= 0.0 && mvControlling->StLinFlag) - { - // NOTE: partial implementation for speedinc/dec - // TBD, TODO: implement fully? - auto const PosInc{mvControlling->MainCtrlPosNo}; - auto PosKeep{0}; - auto PosDec{0}; - for (int i = PosInc; i >= 0; --i) - { - if (mvControlling->UniCtrlList[i].SetCtrlVal <= 0) - { - if (mvControlling->UniCtrlList[i].SpeedDown == 0.0) - { - PosKeep = i; - } - if (mvControlling->UniCtrlList[i].SpeedDown > 0.01) - { - PosDec = i; - break; - } - } - } - - auto const DesiredPos{(AccDesired > AbsAccS + 0.05 ? PosInc : AccDesired < AbsAccS - 0.05 ? PosDec : PosKeep)}; - - while (mvControlling->MainCtrlPos > DesiredPos && mvControlling->DecMainCtrl(1)) - { - ; - } - while (mvControlling->MainCtrlPos < DesiredPos && mvControlling->IncMainCtrl(1)) - { - ; - } - } - //6. UniversalBrakeButtons - //6.1. Checking flags for Over pressure - if (std::abs(BrakeCtrlPosition - gbh_FS)<0.5) { - UniversalBrakeButtons |= TUniversalBrake::ub_HighPressure | TUniversalBrake::ub_Overload; - } - else { - UniversalBrakeButtons &= ~(TUniversalBrake::ub_HighPressure | TUniversalBrake::ub_Overload); - } - //6.2. Setting buttons - for (int i = 0; i < 3; i++) { - mvOccupied->UniversalBrakeButton(i, UniversalBrakeButtons & mvOccupied->UniversalBrakeButtonFlag[i]); - } -}; - -void TController::CheckTimeControllers() -{ - // TODO: rework this method to use hint system and regardless of driver type - if( false == AIControllFlag || 0 == mvControlling->CabActive ) { return; } - - //1. Check the type of Main Brake Handle - if( BrakeSystem == TBrakeSystem::ElectroPneumatic && mvOccupied->Handle->TimeEP && !ForcePNBrake ) - { - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_EPN)); - } - if( ( BrakeSystem == TBrakeSystem::Pneumatic || ForcePNBrake ) && mvOccupied->Handle->Time ) - { - if (BrakeCtrlPosition > 0) - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_MB)); - else - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_RP)); - } - //2. Check the type of Secondary Brake Handle - - //3. Check the type od EIMCtrlType - if (mvOccupied->EIMCtrlType > 0) - { - if (mvOccupied->EIMCtrlType == 1) //traxx - { - if (mvOccupied->MainCtrlPos > 3) mvOccupied->MainCtrlPos = 5; - if (mvOccupied->MainCtrlPos < 3) mvOccupied->MainCtrlPos = 1; - } - else if (mvOccupied->EIMCtrlType == 2) //elf - { - auto const emergencypositions{mvOccupied->EIMCtrlEmergencyPositions()}; - if (mvOccupied->eimic > 0) mvOccupied->MainCtrlPos = 3 + emergencypositions; - if (mvOccupied->eimic < 0) mvOccupied->MainCtrlPos = 2 + emergencypositions; - } - } - //4. Check Speed Control System - if (mvOccupied->EngineType == TEngineType::ElectricInductionMotor && mvOccupied->ScndCtrlPosNo > 1 && mvOccupied->SpeedCtrlTypeTime && mvOccupied->ScndCtrlPosNo == 4) - { - mvOccupied->ScndCtrlPos = 2; - } - - //5. Check Main Controller in Dizels - //5.1. Digital controller in DMUs with hydro - if (mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->EIMCtrlType == 3) - { - int DizelActualPercentage = 100.4 * mvControlling->eimic_real; - int NeutralPos = mvControlling->MainCtrlPosNo - 1; //przedostatnia powinna wstrzymywać - hipoteza robocza - for (int i = mvControlling->MainCtrlPosNo; i >= 0; i--) - if (mvControlling->UniCtrlList[i].SetCtrlVal <= 0 && mvControlling->UniCtrlList[i].SpeedDown < 0.01) //niby zero, ale nie zmniejsza procentów - { - NeutralPos = i; - break; - } - if (BrakeCtrlPosition < 0.1) //jesli nie hamuje - { - if (DizelActualPercentage >= DizelPercentage_Speed && mvControlling->MainCtrlPos > NeutralPos) - while (mvControlling->MainCtrlPos > NeutralPos) mvControlling->DecMainCtrl(1); - if (DizelActualPercentage <= DizelPercentage_Speed && mvControlling->MainCtrlPos < NeutralPos) - while (mvControlling->MainCtrlPos < NeutralPos) mvControlling->IncMainCtrl(1); - mvOccupied->BrakeLevelSet(mvControlling->UniCtrlList[mvControlling->MainCtrlPos].mode); //zeby nie bruzdzilo machanie zespolonym - } - } -}; - -// otwieranie/zamykanie drzwi w składzie albo (tylko AI) EZT -void TController::Doors( bool const Open, int const Side ) { - // otwieranie drzwi - if( true == Open ) { - - auto const lewe = pVehicle->DirectionGet() > 0 ? 1 : 2; - auto const prawe = 3 - lewe; - // doorsteps as the timetable asks, before the doors open (eu07/maszyna#95) - if( auto const doorstep { timetable::doorstep( m_stopflags ) }; - doorstep.has_value() && mvOccupied->Doors.step_enabled != *doorstep ) { - cue_action( *doorstep ? driver_hint::doorstepon : driver_hint::doorstepoff ); - } - // grant door control permission if it's not automatic - // TBD: stricter requirements? - if( true == pVehicle->MoverParameters->Doors.permit_needed ) { - if( Side & prawe ) { - cue_action( driver_hint::doorrightpermiton ); - } - if( Side & lewe ) { - cue_action( driver_hint::doorleftpermiton ); - } - } - // consist-wide remote signals to open doors doors - // NOTE: mixed controls are left up to passengers to open doors by themselves, unless the timetable has - // the driver open all the doors - if( true == timetable::opens_doors( *pVehicle->MoverParameters, m_stopflags ) ) { - if( Side & prawe ) { - cue_action( driver_hint::doorrightopen ); - } - if( Side & lewe ) { - cue_action( driver_hint::doorleftopen ); - } - } - } - // zamykanie drzwi - else { - // if the doors are already closed and locked then there's nothing to do - if( false == doors_permit_active() - && false == doors_open() ) { - drivingFlags.doorOpened = false; - drivingFlags.departureWarned = false; - return; - } - - if (mvOccupied->Doors.has_warning && !drivingFlags.departureWarned) - { - if (!mvOccupied->DepartureSignal) - { - // Not warned yet, not warning yet - start the warning signal. - cue_action( driver_hint::departuresignalon ); // załącenie bzyczka - fActionTime = Random( -0.8, -0.3 ); // 0.3-0.8 second buzzer - return; - } - // Not warned yet, warning now - stop the warning signal and mark it as done. - cue_action( driver_hint::departuresignaloff ); - fActionTime = Random( -0.2, 0.0 ); // Wait just a bit more before departing - drivingFlags.departureWarned = true; - return; - } - - if( true == doors_open() && (pVehicle->MoverParameters->Doors.close_control == control_t::conductor || pVehicle->MoverParameters->Doors.close_control == control_t::driver || - pVehicle->MoverParameters->Doors.close_control == control_t::mixed) ) { - // consist-wide remote signals to close doors - cue_action(driver_hint::doorrightclose); - cue_action(driver_hint::doorleftclose); - } - if( true == doors_permit_active() ) { - cue_action( driver_hint::doorrightpermitoff ); - cue_action( driver_hint::doorleftpermitoff ); - } - // if applicable close manually-operated doors in vehicles which may ignore remote signals - { - const auto *vehicle = pVehicles[ end::front ]; // pojazd na czole składu - while( vehicle != nullptr ) { - // zamykanie drzwi w pojazdach - flaga zezwolenia była by lepsza - auto const ismanualdoor { - vehicle->MoverParameters->Doors.auto_velocity == -1.f - && ( vehicle->MoverParameters->Doors.close_control == control_t::passenger - || vehicle->MoverParameters->Doors.close_control == control_t::mixed ) }; - - if( true == ismanualdoor - && ( vehicle->LoadExchangeTime() == 0.f - || vehicle->MoverParameters->Vel > EU07_AI_MOVEMENT ) ) { - vehicle->MoverParameters->OperateDoors( side::right, false, range_t::local ); - vehicle->MoverParameters->OperateDoors( side::left, false, range_t::local ); - } - vehicle = vehicle->Next(); // pojazd podłączony z tyłu (patrząc od czoła) - } - } - fActionTime = Random(-3.5, -1.0); // 1.0-3.5 sec wait - drivingFlags.doorOpened = false; // zostały zamknięte - nie wykonywać drugi raz - drivingFlags.departureWarned = false; - } -} - -// returns true if any vehicle in the consist has open doors -bool -TController::doors_open() const { - - return IsAnyDoorOpen[side::right] || IsAnyDoorOpen[side::left]; -} - -bool -TController::doors_permit_active() const { - - return IsAnyDoorPermitActive[side::right] || IsAnyDoorPermitActive[side::left]; -} - -void -TController::announce( announcement_t const Announcement ) { - - m_lastannouncement = Announcement; - - if( IsCargoTrain ) { - // cargo trains aren't likely to have announcement systems, so we can skip the procedure altogether - return; - } - - auto *vehicle { pVehicles[ end::front ] }; - while( vehicle ) { - vehicle->announce( Announcement ); - vehicle = vehicle->Next(); - } -} - -void TController::RecognizeCommand() -{ // odczytuje i wykonuje komendę przekazaną lokomotywie - TCommand *c = &mvOccupied->CommandIn; - PutCommand(c->Text, c->Value1, c->Value2, c->Location, stopComm); - c->Command = VehicleCommand::none; - c->Argument.clear(); - c->Text = ""; // usunięcie obsłużonej komendy -} - -void TController::PutCommand(std::string NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation, TStopReason reason) -{ // wysłanie komendy przez event PutValues, jak pojazd ma obsadę, to wysyła tutaj, a nie do pojazdu bezpośrednio - // zamiana na współrzędne scenerii - glm::dvec3 sl { -NewLocation.X, NewLocation.Z, NewLocation.Y }; - if (!PutCommand(NewCommand, NewValue1, NewValue2, &sl, reason)) - mvOccupied->PutCommand(NewCommand, NewValue1, NewValue2, NewLocation); -} - -bool TController::PutCommand( std::string NewCommand, double NewValue1, double NewValue2, glm::dvec3 const *NewLocation, TStopReason reason ) -{ // analiza komendy - if (NewCommand == "CabSignal") - { // SHP wyzwalane jest przez człon z obsadą, ale obsługiwane przez silnikowy - // nie jest to najlepiej zrobione, ale bez symulacji obwodów lepiej nie będzie - // Ra 2014-04: jednak przeniosłem do rozrządczego - mvOccupied->PutCommand(NewCommand, NewValue1, NewValue2, mvOccupied->Loc); - mvOccupied->RunInternalCommand(); // rozpoznaj komende bo lokomotywa jej nie rozpoznaje - return true; // załatwione - } - - if (NewCommand == "Overhead") - { // informacja o stanie sieci trakcyjnej - fOverhead1 = NewValue1; // informacja o napięciu w sieci trakcyjnej (0=brak drutu, zatrzymaj!) - fOverhead2 = NewValue2; // informacja o sposobie jazdy (-1=normalnie, 0=bez prądu, >0=z - // opuszczonym i ograniczeniem prędkości) - return true; // załatwione - } - - if (NewCommand == "Emergency_brake") // wymuszenie zatrzymania, niezależnie kto prowadzi - { // Ra: no nadal nie jest zbyt pięknie -// SetVelocity(0, 0, reason); - mvOccupied->PutCommand("Emergency_brake", 1.0, 1.0, mvOccupied->Loc); - return true; // załatwione - } - - if (NewCommand.compare(0, 10, "Timetable:") == 0) - { // przypisanie nowego rozkładu jazdy, również prowadzonemu przez użytkownika - NewCommand.erase(0, 10); // zostanie nazwa pliku z rozkładem -#if LOGSTOPS - WriteLog("New timetable for " + pVehicle->asName + ": " + NewCommand); // informacja -#endif - TrainParams = TTrainParameters(NewCommand); // rozkład jazdy - tsGuardSignal = sound_source { sound_placement::internal, 2 * EU07_SOUND_CABCONTROLSCUTOFFRANGE }; // wywalenie kierownika - m_lastexchangestop.clear(); - m_stopflags = {}; - if (NewCommand != "none") - { - if (false == TrainParams.LoadTTfile( - std::string(Global.asCurrentSceneryPath.c_str()), floor(NewValue2 + 0.5), - NewValue1)) // pierwszy parametr to przesunięcie rozkładu w czasie - { - if (ConversionError == -8) - ErrorLog("Missed timetable: " + NewCommand); - WriteLog("Cannot load timetable file " + NewCommand + "\r\nError " + - std::to_string(ConversionError) + " in position " + std::to_string(TrainParams.StationCount)); - NewCommand = ""; // puste, dla wymiennej tekstury - } - else - { // inicjacja pierwszego przystanku i pobranie jego nazwy - // HACK: clear the potentially set door state flag to ensure door get opened if applicable - if( true == AIControllFlag ) { - // simplified door closing procedure, to sync actual door state with the door state flag - // NOTE: this may result in visually ugly quick switch between closing and opening the doors, but eh - if( pVehicle->MoverParameters->Doors.close_control == control_t::driver - || pVehicle->MoverParameters->Doors.close_control == control_t::mixed ) { - pVehicle->MoverParameters->OperateDoors( side::right, false ); - pVehicle->MoverParameters->OperateDoors( side::left, false ); - } - if( pVehicle->MoverParameters->Doors.permit_needed ) { - pVehicle->MoverParameters->PermitDoors( side::right, false ); - pVehicle->MoverParameters->PermitDoors( side::left, false ); - } - } - drivingFlags.doorOpened = false; - - TrainParams.UpdateMTable( simulation::Time, TrainParams.NextStationName ); - TrainParams.StationIndexInc(); // przejście do następnej - TrainParams.StationStart = TrainParams.StationIndex; - asNextStop = TrainParams.NextStop(); - // the flags of the first station until the train stops there - m_stopflags = TrainParams.stop_flags(); - m_lastannouncement = announcement_t::idle; - drivingFlags.primary = true; // skoro dostał rozkład, to jest teraz głównym -// NewCommand = Global.asCurrentSceneryPath + NewCommand; - auto lookup = - FileExists( - { Global.asCurrentSceneryPath + NewCommand, paths::sounds + NewCommand }, - { ".ogg", ".flac", ".wav" } ); - if( false == lookup.first.empty() ) { - // wczytanie dźwięku odjazdu podawanego bezpośrenido - tsGuardSignal = sound_source( sound_placement::external, 75.f ).deserialize( lookup.first + lookup.second, sound_type::single ); - iGuardRadio = 0; // nie przez radio - } - else { - NewCommand += "radio"; - lookup = - FileExists( - { Global.asCurrentSceneryPath + NewCommand, paths::sounds + NewCommand }, - { ".ogg", ".flac", ".wav" } ); - if( false == lookup.first.empty() ) { - // wczytanie dźwięku odjazdu w wersji radiowej (słychać tylko w kabinie) - tsGuardSignal = sound_source( sound_placement::internal, EU07_SOUND_HANDHELDRADIORANGE ).deserialize( lookup.first + lookup.second, sound_type::single ); - iGuardRadio = iRadioChannel; - } - } - NewCommand = TrainParams.Relation2; // relacja docelowa z rozkładu - } - // jeszcze poustawiać tekstury na wyświetlaczach - TDynamicObject *p = pVehicles[end::front]; - while (p) - { - p->DestinationSet(NewCommand, TrainParams.TrainName); // relacja docelowa - p = p->Next(); // pojazd podłączony od tyłu (licząc od czoła) - } - } - if (NewLocation) // jeśli podane współrzędne eventu/komórki ustawiającej rozkład (trainset - // nie podaje) - { - auto v = *NewLocation - pVehicle->GetPosition(); // wektor do punktu sterującego - auto d = pVehicle->VectorFront(); // wektor wskazujący przód - iDirectionOrder = (v.x * d.x + v.z * d.z) * NewValue1 > 0 ? - 1 : - -1; // do przodu, gdy iloczyn skalarny i prędkość dodatnie - /* - if (NewValue1!=0.0) //jeśli ma jechać - if (iDirectionOrder==0) //a kierunek nie był określony (normalnie określany przez - reardriver/headdriver) - iDirectionOrder=NewValue1>0?1:-1; //ustalenie kierunku jazdy względem sprzęgów - else - if (NewValue1<0) //dla ujemnej prędkości - iDirectionOrder=-iDirectionOrder; //ma jechać w drugą stronę - */ - if (AIControllFlag) // jeśli prowadzi komputer - Activation(); // umieszczenie obsługi we właściwym członie, ustawienie nawrotnika w - // przód - } - /* - else - if (!iDirectionOrder) - {//jeśli nie ma kierunku, trzeba ustalić - if (mvOccupied->V!=0.0) - iDirectionOrder=mvOccupied->V>0?1:-1; - else - iDirectionOrder=mvOccupied->CabOccupied; - if (!iDirectionOrder) iDirectionOrder=1; - } - */ - // jeśli wysyłane z Trainset, to wszystko jest już odpowiednio ustawione - // if (!NewLocation) //jeśli wysyłane z Trainset - // if (mvOccupied->CabActive*mvOccupied->V*NewValue1<0) //jeśli zadana prędkość niezgodna z - // aktualnym kierunkiem jazdy - // DirectionForward(false); //jedziemy do tyłu (nawrotnik do tyłu) - // CheckVehicles(); //sprawdzenie składu, AI zapali światła - TableClear(); // wyczyszczenie tabelki prędkości, bo na nowo trzeba określić kierunek i - // sprawdzić przystanki - OrdersInit(fabs(NewValue1)); // ustalenie tabelki komend wg rozkładu oraz prędkości początkowej - // if (NewValue1!=0.0) if (!AIControllFlag) DirectionForward(NewValue1>0.0); //ustawienie - // nawrotnika użytkownikowi (propaguje się do członów) - // if (NewValue1>0) - // TrainNumber=floor(NewValue1); //i co potem ??? - return true; // załatwione - } - - if (NewCommand == "SetVelocity") - { - if (NewLocation) - vCommandLocation = *NewLocation; - if (NewValue1 != 0.0 && OrderCurrentGet() != DriverOrder::obeyTrain) - { // o ile jazda - if( false == iEngineActive ) { - // trzeba odpalić silnik najpierw, światła ustawi - OrderNext( DriverOrder::prepareEngine ); - } - OrderNext(DriverOrder::obeyTrain); // to uruchomić jazdę pociągową (od razu albo po odpaleniu silnika - OrderCheck(); // jeśli jazda pociągowa teraz, to wykonać niezbędne operacje - } - if (NewValue1 != 0.0) // jeśli jechać - drivingFlags.stopHere = false; // podjeżanie do semaforów zezwolone - else - drivingFlags.stopHere = true; // stać do momentu podania komendy jazdy - SetVelocity(NewValue1, NewValue2, reason); // bylo: nic nie rob bo SetVelocity zewnetrznie - // jest wywolywane przez dynobj.cpp - return true; - } - - if( NewCommand == "PointVelocity" ) { - // read by the speed table scan only; when the cell's event runs, there is nothing to do - return true; - } - - if (NewCommand == "SetProximityVelocity") - { - /* - if (SetProximityVelocity(NewValue1,NewValue2)) - if (NewLocation) - vCommandLocation=*NewLocation; - */ - return true; - } - - if (NewCommand == "ShuntVelocity") - { // uruchomienie jazdy manewrowej bądź zmiana prędkości - if (NewLocation) - vCommandLocation = *NewLocation; - // if (OrderList[OrderPos]=Obey_train) and (NewValue1<>0)) - if (false == iEngineActive) - OrderNext(DriverOrder::prepareEngine); // trzeba odpalić silnik najpierw - OrderNext(DriverOrder::shunt); // zamieniamy w aktualnej pozycji, albo dodajey za odpaleniem silnika - if (NewValue1 != 0.0) - { - // if (iVehicleCount>=0) WriteLog("Skasowano ilosć wagonów w ShuntVelocity!"); - iVehicleCount = -2; // wartość neutralna - CheckVehicles(); // zabrać to do OrderCheck() - } - // dla prędkości ujemnej przestawić nawrotnik do tyłu? ale -1=brak ograniczenia !!!! - drivingFlags.press = false; // bez dociskania - SetVelocity(NewValue1, NewValue2, reason); - if (NewValue1 != 0.0) - drivingFlags.stopHere = false; // podjeżanie do semaforów zezwolone - else - drivingFlags.stopHere = true; // ma stać w miejscu - if (fabs(NewValue1) > 2.0) // o ile wartość jest sensowna (-1 nie jest konkretną wartością) - fShuntVelocity = fabs(NewValue1); // zapamiętanie obowiązującej prędkości dla manewrów - - return true; - } - - if (NewCommand == "Wait_for_orders") - { // oczekiwanie; NewValue1 - czas oczekiwania, -1 = na inną komendę - if (NewValue1 > 0.0 ? NewValue1 > fStopTime : false) - fStopTime = NewValue1; // Ra: włączenie czekania bez zmiany komendy - else - OrderCurrentSet( DriverOrder::waitForOrders ); // czekanie na komendę (albo dać OrderPos=0) - - return true; - } - - if (NewCommand == "Prepare_engine") - { // włączenie albo wyłączenie silnika (w szerokim sensie) - OrdersClear(); // czyszczenie tabelki rozkazów, aby nic dalej nie robił - if (NewValue1 == 0.0) - OrderNext(DriverOrder::releaseEngine); // wyłączyć silnik (przygotować pojazd do jazdy) - else if (NewValue1 > 0.0) - OrderNext(DriverOrder::prepareEngine); // odpalić silnik (wyłączyć wszystko, co się da) - // po załączeniu przejdzie do kolejnej komendy, po wyłączeniu na Wait_for_orders - return true; - } - - if (NewCommand == "Change_direction") - { - DriverOrders o = OrderCurrentGet(); // co robił przed zmianą kierunku - if (false == iEngineActive) - OrderNext(DriverOrder::prepareEngine); // trzeba odpalić silnik najpierw - if (NewValue1 == 0.0) - iDirectionOrder = -iDirection; // zmiana na przeciwny niż obecny - else if (NewLocation) // jeśli podane współrzędne eventu/komórki ustawiającej rozkład - // (trainset nie podaje) - { - auto v = *NewLocation - pVehicle->GetPosition(); // wektor do punktu sterującego - auto d = pVehicle->VectorFront(); // wektor wskazujący przód - iDirectionOrder = (v.x * d.x + v.z * d.z) * NewValue1 > 0 ? - 1 : - -1; // do przodu, gdy iloczyn skalarny i prędkość dodatnie - // iDirectionOrder=1; else if (NewValue1<0.0) iDirectionOrder=-1; - } - if ( - - iDirectionOrder != iDirection) - OrderNext(DriverOrder::changeDirection); // zadanie komendy do wykonania - if (o.HasAny(movingOrders)) // jeśli jazda manewrowa albo pociągowa - OrderNext(o); // to samo robić po zmianie - else if (!o) // jeśli wcześniej było czekanie - OrderNext(DriverOrder::shunt); // to dalej jazda manewrowa - if (mvOccupied->Vel >= EU07_AI_MOVEMENT) // jeśli jedzie - drivingFlags.startHorn = false; // to bez trąbienia po ruszeniu z zatrzymania - // Change_direction wykona się samo i następnie przejdzie do kolejnej komendy - return true; - } - - if (NewCommand == "Obey_train") { - if( false == iEngineActive ) { - OrderNext( DriverOrder::prepareEngine ); // trzeba odpalić silnik najpierw - } - OrderNext( DriverOrder::obeyTrain ); - // if (NewValue1>0) TrainNumber=floor(NewValue1); //i co potem ??? - OrderCheck(); // jeśli jazda pociągowa teraz, to wykonać niezbędne operacje - - return true; - } - - if (NewCommand == "Bank") { - if( false == iEngineActive ) { - OrderNext( DriverOrder::prepareEngine ); // trzeba odpalić silnik najpierw - } - OrderNext( DriverOrder::bank ); - // if (NewValue1>0) TrainNumber=floor(NewValue1); //i co potem ??? - OrderCheck(); // jeśli jazda pociągowa teraz, to wykonać niezbędne operacje - - return true; - } - - if( NewCommand == "Shunt" || NewCommand == "Loose_shunt" ) - { // NewValue1 - ilość wagonów (-1=wszystkie); NewValue2: 0=odczep, 1..63=dołącz, -1=bez zmian - //-3,-y - podłączyć do całego stojącego składu (sprzęgiem y>=1), zmienić kierunek i czekać w trybie pociągowym - //-2,-y - podłączyć do całego stojącego składu (sprzęgiem y>=1), zmienić kierunek i czekać - //-2, y - podłączyć do całego stojącego składu (sprzęgiem y>=1) i czekać - //-1,-y - podłączyć do całego stojącego składu (sprzęgiem y>=1) i jechać w powrotną stronę - //-1, y - podłączyć do całego stojącego składu (sprzęgiem y>=1) i jechać dalej - //-1, 0 - tryb manewrowy bez zmian (odczepianie z pozostawieniem wagonów nie ma sensu) - // 0, 0 - odczepienie lokomotywy - // x,-y - podłączyć się do składu (sprzęgiem y>=1), a następnie odczepić i zabrać (x) wagonów - // 1, 0 - odczepienie lokomotywy z jednym wagonem - drivingFlags.stopHere = false; // podjeżanie do semaforów zezwolone - if( false == iEngineActive ) { - OrderNext( DriverOrder::prepareEngine ); // trzeba odpalić silnik najpierw - } - if (NewValue2 != 0) // jeśli podany jest sprzęg - { - iCoupler = CouplingSet::FromBits( static_cast( std::floor( std::abs( NewValue2 ) ) ) ); // jakim sprzęgiem - OrderNext(DriverOrder::connect); // najpierw połącz pojazdy - if (NewValue1 >= 0.0) // jeśli ilość wagonów inna niż wszystkie - { // to po podpięciu należy się odczepić - iDirectionOrder = -iDirection; // zmiana na ciągnięcie - OrderPush(DriverOrder::changeDirection); // najpierw zmień kierunek, bo odczepiamy z tyłu - OrderPush(DriverOrder::disconnect); // a odczep już po zmianie kierunku - if( NewValue2 > 0.0 - && NewCommand == "Loose_shunt" ) { - // after decoupling continue pushing in the original direction - // NOTE: for backward compatibility this option isn't supported for basic shunting mode - iDirectionOrder = iDirection; // back to pushing - OrderPush( DriverOrder::changeDirection ); - } - } - else if (NewValue2 < 0.0) // jeśli wszystkie, a sprzęg ujemny, to tylko zmiana kierunku po podczepieniu - { // np. Shunt -1 -3 - iDirectionOrder = -iDirection; // jak się podczepi, to jazda w przeciwną stronę - OrderNext(DriverOrder::changeDirection); - } - WaitingTime = 0.0; // nie ma co dalej czekać, można zatrąbić i jechać, chyba że już jedzie - } - else { // if (NewValue2==0.0) //zerowy sprzęg - if( NewValue1 >= 0.0 ) { - // jeśli ilość wagonów inna niż wszystkie będzie odczepianie, - // ale jeśli wagony są z przodu, to trzeba najpierw zmienić kierunek - if( mvOccupied->Couplers[mvOccupied->DirAbsolute > 0 ? end::rear : end::front].Connected == nullptr // z tyłu nic - && mvOccupied->Couplers[mvOccupied->DirAbsolute > 0 ? end::front : end::rear].Connected != nullptr ) { // a z przodu skład - iDirectionOrder = -iDirection; // zmiana na ciągnięcie - OrderNext( DriverOrder::changeDirection ); // najpierw zmień kierunek (zastąpi Disconnect) - OrderPush( DriverOrder::disconnect ); // a odczep już po zmianie kierunku - } - else if( mvOccupied->Couplers[ mvOccupied->DirAbsolute > 0 ? end::rear : end::front ].Connected != nullptr ) { // z tyłu coś - OrderNext( DriverOrder::disconnect ); // jak ciągnie, to tylko odczep (NewValue1) wagonów - } - else { - // both couplers empty - // NOTE: this condition implements legacy behavior (mis)used by some scenarios to keep vehicle idling without moving - SetVelocity( 0, 0, stopJoin ); - drivingFlags.stopHere = true; // nie podjeżdżać do semafora, jeśli droga nie jest wolna - } - WaitingTime = 0.0; // nie ma co dalej czekać, można zatrąbić i jechać, chyba że już jedzie - } - } - if (NewValue1 == -1.0) { - drivingFlags.stopHere = false; // ma jechać - WaitingTime = 0.0; // nie ma co dalej czekać, można zatrąbić i jechać - } - if( NewValue1 < -1.5 ) { // jeśli -2/-3, czyli czekanie z ruszeniem na sygnał - drivingFlags.stopHere = true; // nie podjeżdżać do semafora, jeśli droga nie jest wolna - } - // (nie dotyczy Connect) - if( NewValue1 < -2.5 ) { // jeśli -3 to potem jazda pociągowa - OrderNext( NewCommand == "Shunt" ? DriverOrder::obeyTrain : DriverOrder::bank ); - } - else { // otherwise continue shunting - OrderNext( NewCommand == "Shunt" ? DriverOrder::shunt : DriverOrder::looseShunt ); - } - CheckVehicles(); // sprawdzić światła - iVehicleCount = std::floor( NewValue1 ); - - return true; - } - - if( NewCommand == "Jump_to_first_order" ) { - JumpToFirstOrder(); - return true; - } - - if (NewCommand == "Jump_to_order") - { - if( NewValue1 == -1.0 ) { - JumpToNextOrder(); - } - else if (NewValue1 >= 0 && NewValue1 < maxorders) - { - OrderPos = floor(NewValue1); - if( !OrderPos ) { - // zgodność wstecz: dopiero pierwsza uruchamia - OrderPos = 1; - } -#if LOGORDERS - OrdersDump("Jump_to_order"); -#endif - } - return true; - } - - if (NewCommand == "Warning_signal") - { - if( NewValue1 > 0 && NewValue2 > 0 ) { - fWarningDuration = NewValue1; // czas trąbienia - cue_action( driver_hint::hornon, NewValue2 ); // horn combination flag - simulation::Blackbox.horn_requested( - pVehicles[ end::front ], NewValue1, NewValue2, NewLocation != nullptr ? *NewLocation : pVehicles[ end::front ]->GetPosition() ); - } - return true; - } - - if (NewCommand == "Radio_channel") { - // wybór kanału radiowego (którego powinien używać AI, ręczny maszynista musi go ustawić sam) - if (NewValue1 >= 0) { - // wartości ujemne są zarezerwowane, -1 = nie zmieniać kanału - if( AIControllFlag ) { - iRadioChannel = NewValue1; - } - if( iGuardRadio ) { - // kierownikowi też zmienić - iGuardRadio = NewValue1; - } - } - // NewValue2 może zawierać dodatkowo oczekiwany kod odpowiedzi, np. dla W29 "nawiązać - // łączność radiową z dyżurnym ruchu odcinkowym" - return true; - } - - if( NewCommand == "SetLights" ) { - // set consist lights pattern hints - m_lighthints[ end::front ] = static_cast( NewValue1 ); - m_lighthints[ end::rear ] = static_cast( NewValue2 ); - if( true == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { - // light hints only apply in the obey_train mode - CheckVehicles(); - } - return true; - } - - if (NewCommand == "SetSignal") { - auto const signal{std::lrint(NewValue1)}; - - drivingFlags.signalPc6 = false; - drivingFlags.signalA1 = false; - - if (NewValue2 > 0.5) - { - // another number set the bit of a driving flag of that number before - drivingFlags.signalPc6 = signal == Signal_Pc6; - drivingFlags.signalA1 = signal == Signal_A1; - } - else - CheckVehicles(); // restore light state - } - - return false; // nierozpoznana - wysłać bezpośrednio do pojazdu -}; - -std::string_view TController::physicslog_header() { - // the columns of the readers of these logs, the Hasler tape of the starter among them, stay where they are: - // a new one goes at the end - return "Time[s] Velocity[m/s] Acceleration[m/ss] " - "Coupler.Dist[m] Coupler.Force[N] TractionForce[kN] FrictionForce[kN] BrakeForce[kN] " - "BrakePress[MPa] PipePress[MPa] MotorCurrent[A] " - "MCP SCP BCP LBP Direction Command CVal1 CVal2 " - "Security Wheelslip " - "EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg] " - "VehicleVelocity[km/h]" - "\r\n"; -} - -std::string TController::physicslog_line() const { - std::ostringstream line; - line << std::fixed << std::setprecision( 4 ) - << ElapsedTime << " " - << fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot) << " " - << mvControlling->AccS << " " - << mvOccupied->Couplers[1].Dist << " " - << mvOccupied->Couplers[1].CForce << " " - << mvOccupied->Ft << " " - << mvOccupied->Ff << " " - << mvOccupied->Fb << " " - << mvOccupied->BrakePress << " " - << mvOccupied->PipePress << " " - << mvControlling->Im << " " - << int(mvControlling->MainCtrlPos) << " " - << int(mvControlling->ScndCtrlPos) << " " - << mvOccupied->fBrakeCtrlPos << " " - << mvOccupied->LocalBrakePosA << " " - << int(mvControlling->DirActive) << " " - << ( mvOccupied->CommandIn.Text.empty() ? "none" : mvOccupied->CommandIn.Text.c_str() ) << " " - << mvOccupied->CommandIn.Value1 << " " - << mvOccupied->CommandIn.Value2 << " " - << int(mvControlling->SecuritySystem.is_blinking()) << " " - << int(mvControlling->SlippingWheels) << " " - << mvControlling->dizel_heat.Ts << " " - << mvControlling->dizel_heat.To << " " - << mvControlling->dizel_heat.temperatura1 << " " - << mvControlling->dizel_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 - << mvOccupied->V * 3.6 - << "\r\n"; - return line.str(); -} - -void TController::begin_physicslog() -{ - // physicslog/.dat, written every two seconds along with the logs of the other drivers -#if LOGPRESS == 0 - PhysicsLogs.begin( VehicleName, physicslog_header() ); -#endif -#if LOGPRESS == 1 - PhysicsLogs.begin( VehicleName, "t\tVel\tAcc\tPP\tVVP\tBP\tBVP\tCVP\n" ); -#endif - PhysicsLogBegun = true; -} - -void TController::PhysicsLog() -{ // zapis logu - na razie tylko wypisanie parametrów -#if LOGPRESS == 0 - PhysicsLogs.append( VehicleName, physicslog_line() ); -#endif -#if LOGPRESS == 1 - std::ostringstream line; - line << ElapsedTime << "\t" << fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot) - << "\t"; - line << mvControlling->AccS << "\t"; - line << mvOccupied->PipePress << "\t" << mvOccupied->CntrlPipePress << "\t" - << mvOccupied->BrakePress << "\t"; - line << mvOccupied->Volume << "\t" << mvOccupied->Hamulec->GetCRP() << "\n"; - PhysicsLogs.append( VehicleName, line.str() ); -#endif -}; - -void -TController::Update( double const Timedelta ) { - // uruchamiać przynajmniej raz na sekundę - if( ( false == drivingFlags.primary ) ) { return; } // pasywny nic nie robi - if( false == simulation::is_ready ) { return; } - - update_timers( Timedelta ); - update_logs( Timedelta ); - - auto const reactiontime { std::min( ReactionTime, 2.0 ) }; - - if( LastReactionTime < reactiontime ) { return; } - LastReactionTime -= reactiontime; -/* - // TBD, TODO: put this in an appropriate place, or get rid of it - // NOTE: this section moved all cars to the edge of their respective roads - // it may have some use eventually for collision avoidance, - // but when enabled all the time it produces silly effect - if( mvOccupied->Vel > 1.0 ) { - // przy prowadzeniu samochodu trzeba każdą oś odsuwać oddzielnie, inaczej kicha wychodzi - if (mvOccupied->CategoryFlag & 2) // jeśli samochód - // if (fabs(mvOccupied->OffsetTrackH)Dim.W) //Ra: szerokość drogi tu powinna być? - if (!mvOccupied->ChangeOffsetH(-0.01 * mvOccupied->Vel * dt)) // ruch w poprzek drogi - mvOccupied->ChangeOffsetH(0.01 * mvOccupied->Vel * dt); // Ra: co to miało być, to nie wiem - } -*/ - update_hints(); - // main ai update routine - determine_consist_state(); - determine_braking_distance(); - determine_proximity_ranges(); - // vicinity check - auto const awarenessrange { - std::max( - 750.0, - mvOccupied->Vel > EU07_AI_MOVEMENT ? - 400 + fBrakeDist : - 30.0 * fDriverDist ) }; // 1500m dla stojących pociągów; - if( is_active() ) { - scan_route( awarenessrange ); - } - scan_obstacles( awarenessrange ); - // generic actions - control_security_system( reactiontime ); - if( iEngineActive ) { - control_wheelslip(); - control_horns( reactiontime ); - control_pantographs(); - if( fActionTime > 0.0 ) { - // potentially delayed and/or low priority actions - control_lights(); - control_doors(); - control_compartment_lights(); - } - } - CheckTimeControllers(); - // external command actions - UpdateCommand(); - // mode specific actions - handle_engine(); - handle_orders(); - // a brake the wagon inspector left to cut out while the train was moving - reinspect_brakes(); - // situational velocity and acceleration adjustments - pick_optimal_speed( awarenessrange ); - if( iEngineActive ) { - control_tractive_and_braking_force(); - } - SetTimeControllers(); -} - -// configures vehicle heating given current situation; returns: true if vehicle can be operated normally, false otherwise -bool -TController::PrepareHeating() { - - switch( mvControlling->EngineType ) { - - case TEngineType::DieselElectric: - case TEngineType::DieselEngine: { - - auto const &heat { mvControlling->dizel_heat }; - - // determine whether there's need to enable the water heater - // if the heater has configured maximum temperature, it'll disable itself automatically, so we can leave it always running - // otherwise enable the heater only to maintain minimum required temperature - auto const lowtemperature { ( - ( heat.water.config.temp_min > 0 && heat.temperatura1 < heat.water.config.temp_min + (mvControlling->WaterHeater.is_active ? 5 : 0) ) - || ( heat.water_aux.config.temp_min > 0 && heat.temperatura2 < heat.water_aux.config.temp_min + (mvControlling->WaterHeater.is_active ? 5 : 0) ) - || ( heat.oil.config.temp_min > 0 && heat.To < heat.oil.config.temp_min + (mvControlling->WaterHeater.is_active ? 5 : 0) ) ) }; - auto const heateron { ( - mvControlling->WaterHeater.config.temp_max > 0 - || true == lowtemperature ) }; - if( true == heateron ) { - // make sure the water pump is running before enabling the heater - if( false == mvControlling->WaterPump.is_active ) { - cue_action( driver_hint::waterpumpbreakeron ); - cue_action( driver_hint::waterpumpon ); - } - if( true == mvControlling->WaterPump.is_active ) { - cue_action( driver_hint::waterheaterbreakeron ); - cue_action( driver_hint::waterheateron ); - cue_action( driver_hint::watercircuitslinkon ); - } - } - else { - // no need to heat anything up, switch the heater off - cue_action( driver_hint::watercircuitslinkoff ); - cue_action( driver_hint::waterheateroff ); - cue_action( driver_hint::waterheaterbreakeroff ); - // optionally turn off the water pump as well - if( mvControlling->WaterPump.start_type != start_t::battery ) { - cue_action( driver_hint::waterpumpoff ); - cue_action( driver_hint::waterpumpbreakeroff ); - } - } - - IsHeatingTemperatureTooLow = lowtemperature; - break; - } - default: { - IsHeatingTemperatureTooLow = false; - break; - } - } - // TBD, TODO: potentially pay attention to too high temperature as well? - IsHeatingTemperatureOK = false == IsHeatingTemperatureTooLow; - - return IsHeatingTemperatureOK; -} - -void -TController::PrepareDirection() { - - if( iDirection == 0 ) { - // jeśli nie ma ustalonego kierunku - if( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) { // ustalenie kierunku, gdy stoi - iDirection = mvOccupied->CabActive; // wg wybranej kabiny -/* - if( iDirection == 0 ) { - // jeśli nie ma ustalonego kierunku - if( mvOccupied->Couplers[ end::rear ].Connected == nullptr ) { - // jeśli z tyłu nie ma nic - iDirection = -1; // jazda w kierunku sprzęgu 1 - } - if( mvOccupied->Couplers[ end::front ].Connected == nullptr ) { - // jeśli z przodu nie ma nic - iDirection = 1; // jazda w kierunku sprzęgu 0 - } - } -*/ - } - else { - // ustalenie kierunku, gdy jedzie - iDirection = mvOccupied->V >= 0 ? 1 : // jazda w kierunku sprzęgu 0 - -1; // jazda w kierunku sprzęgu 1 - } - } - cue_action( driver_hint::mastercontrollersetreverserunlock ); - cue_action( - iDirection > 0 ? - driver_hint::directionforward : - driver_hint::directionbackward ); -} - -void TController::JumpToNextOrder( bool const Ignoremergedchangedirection ) -{ // wykonanie kolejnej komendy z tablicy rozkazów - if (auto const currentorder { OrderCurrentGet() }; currentorder != DriverOrder::waitForOrders) - { - if( currentorder.HasAny(DriverOrder::changeDirection) // jeśli zmiana kierunku - && currentorder != DriverOrder::changeDirection && false == Ignoremergedchangedirection ) { // ale nałożona na coś - - // usunięcie zmiany kierunku z innej komendy - OrderCurrentSet( currentorder.Without(DriverOrder::changeDirection) ); - OrderCheck(); - return; - } - if (OrderPos < maxorders - 1) - ++OrderPos; - else - OrderPos = 0; - } - OrderCheck(); -#if LOGORDERS - OrdersDump("JumpToNextOrder"); // normalnie nie ma po co tego wypisywać -#endif -}; - -void TController::JumpToFirstOrder() -{ // taki relikt - OrderPos = 1; - if (OrderTop == 0) - OrderTop = 1; - OrderCheck(); -#if LOGORDERS - OrdersDump("JumpToFirstOrder"); // normalnie nie ma po co tego wypisywać -#endif -}; - -void TController::OrderCheck() -{ // reakcja na zmianę rozkazu - - if( OrderCurrentGet() != DriverOrder::obeyTrain ) { - // reset light hints - m_lighthints[ end::front ] = m_lighthints[ end::rear ] = -1; - } - if( OrderCurrentGet() & ( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect | DriverOrder::obeyTrain | DriverOrder::bank ) ) { - CheckVehicles(); // sprawdzić światła - } - if( OrderCurrentGet() & ( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect ) ) { - // HACK: ensure consist doors will be closed on departure - drivingFlags.doorOpened = true; - } - auto const currentorder { OrderCurrentGet() }; - if (currentorder & DriverOrder::changeDirection) // może być nałożona na inną i wtedy ma priorytet - iDirectionOrder = -iDirection; // trzeba zmienić jawnie, bo się nie domyśli - else if (currentorder == DriverOrder::obeyTrain) - drivingFlags.stopPoint = true; // W4 są widziane - else if (currentorder == DriverOrder::disconnect) - iVehicleCount = iVehicleCount < 0 ? 0 : iVehicleCount; // odczepianie lokomotywy - else if (currentorder == DriverOrder::connect) - drivingFlags.stopPoint = false; // podczas jazdy na połączenie nie zwracać uwagi na W4 - else if (currentorder == DriverOrder::waitForOrders) - OrdersClear(); // czyszczenie rozkazów i przeskok do zerowej pozycji -} - -void TController::OrderNext(DriverOrders NewOrder) -{ // ustawienie rozkazu do wykonania jako następny - if (OrderCurrentGet() == NewOrder) - return; // jeśli robi to, co trzeba, to koniec - if (!OrderPos) - OrderPos = 1; // na pozycji zerowej pozostaje czekanie - OrderTop = OrderPos; // ale może jest czymś zajęty na razie - if (NewOrder.HasAny(movingOrders)) // jeśli ma jechać - { // ale może być zajęty chwilowymi operacjami - while (OrderTop >= 0 && OrderTop < maxorders - 1 - && OrderList[OrderTop] != DriverOrder::waitForOrders && false == OrderList[OrderTop].HasAny(movingOrders)) // jeśli coś robi - ++OrderTop; // pomijamy wszystkie tymczasowe prace - } - else - { // jeśli ma ustawioną jazdę, to wyłączamy na rzecz operacji - while (OrderTop >= 0 && OrderTop < maxorders - 1 - && OrderList[OrderTop] != DriverOrder::waitForOrders && false == OrderList[OrderTop].HasAny(movingOrders) && OrderList[OrderTop] != NewOrder) // jeśli coś robi - ++OrderTop; // pomijamy wszystkie tymczasowe prace - } - if (OrderTop < 0 || OrderTop >= maxorders) - { - ErrorLog("Commands overflow: order \"" + Order2Str(NewOrder) + "\" dropped"); - return; - } - OrderList[OrderTop++] = NewOrder; // dodanie rozkazu jako następnego -#if LOGORDERS - OrdersDump( "OrderNext" ); // normalnie nie ma po co tego wypisywać -#endif -} - -void TController::OrderPush(DriverOrders NewOrder) -{ // zapisanie na stosie kolejnego rozkazu do wykonania - if (OrderPos == OrderTop && false == OrderCurrentGet().HasAny(movingOrders)) // jeśli miałby być zapis na aktalnej pozycji - // ale nie jedzie - ++OrderTop; - // niektóre operacje muszą zostać najpierw dokończone => zapis na kolejnej - if (OrderTop < 0 || OrderTop >= maxorders) - { - ErrorLog("Commands overflow: order \"" + Order2Str(NewOrder) + "\" dropped"); - return; - } - if (OrderList[OrderTop] != NewOrder) // jeśli jest to samo, to nie dodajemy - OrderList[OrderTop++] = NewOrder; // dodanie rozkazu na stos -#if LOGORDERS - OrdersDump( "OrderPush: [" + Order2Str( NewOrder ) + "]" ); // normalnie nie ma po co tego wypisywać -#endif -} - -void TController::OrdersDump( std::string const Neworder, bool const Verbose ) -{ // wypisanie kolejnych rozkazów do logu - WriteLog( "New order for [" + pVehicle->asName + "]: " + Neworder ); - if( false == Verbose ) { return; } - for (int b = 0; b < maxorders; ++b) - { - WriteLog( ( OrderPos == b ? ">" : " " ) + (std::to_string(b) + ": " + Order2Str(OrderList[b]))); - if (b && OrderList[b] == DriverOrder::waitForOrders) // z wyjątkiem pierwszej pozycji - // jeśli końcowa komenda - break; - // dalej nie trzeba - } -}; - -void TController::OrdersInit(double fVel) -{ // wypełnianie tabelki rozkazów na podstawie rozkładu - // ustawienie kolejności komend, niezależnie kto prowadzi - OrdersClear(); // usunięcie poprzedniej tabeli - OrderPush(DriverOrder::prepareEngine); // najpierw odpalenie silnika - if (TrainParams.StationCount == 0) - { // brak rozkładu to jazda manewrowa -// if (fVel > 0.05) // typowo 0.1 oznacza gotowość do jazdy, 0.01 tylko załączenie silnika - OrderPush(DriverOrder::shunt); // jeśli nie ma rozkładu, to manewruje - } - else - { // jeśli z rozkładem, to jedzie na szlak - if (fVel > 0.0 && fVel < 0.02) - OrderPush(DriverOrder::shunt); // dla prędkości 0.01 włączamy jazdę manewrową - else if (TrainParams.DirectionChange() ? // jeśli obrót na pierwszym przystanku - (drivingFlags.pushPull ? // SZT również! SN61 zależnie od wagonów... - TrainParams.TimeTable[1].StationName == TrainParams.Relation1 : - false) : - false) - OrderPush(DriverOrder::shunt); // a teraz start będzie w manewrowym, a tryb pociągowy włączy W4 - else - // jeśli start z pierwszej stacji i jednocześnie jest na niej zmiana kierunku, to EZT ma mieć Shunt - OrderPush(DriverOrder::obeyTrain); // dla starych scenerii start w trybie pociagowym - if (DebugModeFlag) // normalnie nie ma po co tego wypisywać - WriteLog("/* Timetable: " + TrainParams.ShowRelation()); - TMTableLine *t; - for (int i = 0; i <= TrainParams.StationCount; ++i) - { - t = TrainParams.TimeTable + i; - if (DebugModeFlag) { - // normalnie nie ma po co tego wypisywa? - WriteLog( - t->StationName - + " " + std::to_string(t->Ah) + ":" + std::to_string(t->Am) - + ", " + std::to_string(t->Dh) + ":" + std::to_string(t->Dm) - + " " + t->StationWare); - } - if ( contains( t->StationWare, '@' ) ) - { // zmiana kierunku i dalsza jazda wg rozk?adu - if (drivingFlags.pushPull) // SZT również! SN61 zależnie od wagonów... - { // jeśli skład zespolony, wystarczy zmienić kierunek jazdy - OrderPush(DriverOrder::changeDirection); // zmiana kierunku - } - else - { // dla zwykłego składu wagonowego odczepiamy lokomotywę - OrderPush(DriverOrder::disconnect); // odczepienie lokomotywy - OrderPush(DriverOrder::shunt); // a dalej manewry - } - if (i < TrainParams.StationCount) // jak nie ostatnia stacja - OrderPush(DriverOrder::obeyTrain); // to dalej wg rozkładu - } - } - if( DebugModeFlag ) { - // normalnie nie ma po co tego wypisywać - WriteLog( "*/" ); - } - OrderPush(DriverOrder::shunt); // po wykonaniu rozkładu przełączy się na manewry - } - // McZapkie-100302 - to ma byc wyzwalane ze scenerii - if( fVel == 0.0 ) { - // jeśli nie ma prędkości początkowej, to śpi - SetVelocity( 0, 0, stopSleep ); - } - else { - // jeśli podana niezerowa prędkość - if( fVel >= 1.0 - || fVel < 0.02 ) { - // jeśli ma jechać - dla 0.01 ma podjechać manewrowo po podaniu sygnału - // to do następnego W4 ma podjechać blisko - drivingFlags.stopHere = false; - drivingFlags.stopCloser = true; - } - else { - // czekać na sygnał - drivingFlags.stopHere = true; - } - JumpToFirstOrder(); - if (fVel >= 1.0) // jeśli ma jechać - SetVelocity(fVel, -1); // ma ustawić żądaną prędkość - else - SetVelocity(0, 0, stopSleep); // prędkość w przedziale (0;1) oznacza, że ma stać - } -#if LOGORDERS - OrdersDump( "OrdersInit", DebugModeFlag ); // wypisanie kontrolne tabelki rozkazów -#endif - // McZapkie! - zeby w ogole AI ruszyl to musi wykonac powyzsze rozkazy - // Ale mozna by je zapodac ze scenerii -}; - -std::string TController::StopReasonText() const -{ // informacja tekstowa o przyczynie zatrzymania - if (eStopReason != 7) // zawalidroga będzie inaczej - return StopReasonTable[eStopReason]; - else - return "Blocked by " + pVehicles[0]->PrevAny()->name(); -}; - -//---------------------------------------------------------------------------------------------------------------------- -// McZapkie: skanowanie semaforów -// Ra: stare funkcje skanujące, używane podczas manewrów do szukania sygnalizatora z tyłu -//- nie reagują na PutValues, bo nie ma takiej potrzeby -//- rozpoznają tylko zerową prędkość (jako koniec toru i brak podstaw do dalszego skanowania) -//---------------------------------------------------------------------------------------------------------------------- - -bool TController::IsOccupiedByAnotherConsist( TTrack *Track, double const Distance = 0 ) -{ // najpierw sprawdzamy, czy na danym torze są pojazdy z innego składu - if( false == Track->Dynamics.empty() ) { - for( auto dynamic : Track->Dynamics ) { - if( dynamic->ctOwner != this ) { - // jeśli jest jakiś cudzy to tor jest zajęty i skanowanie nie obowiązuje - if( Distance == 0 ) { - return true; - } - else { - // based on provided position of scanning vehicle and scan direction, filter out vehicles on irrelevant end - auto const scandirection { Distance > 0 ? 1 : -1 }; // positive value means scan towards point2 end of the track - auto const obstaclelocation { scandirection > 0 ? Track->Length() - dynamic->RaTranslationGet() : dynamic->RaTranslationGet() }; - // if detected vehicle is closer to the end of the track in scanned direction than we are, it means it's blocking our way - if( obstaclelocation < std::abs( Distance ) ) { - return true; - } - } - } - } - } - return false; // wolny -}; - -basic_event * TController::CheckTrackEventBackward(double fDirection, TTrack *Track, TDynamicObject *Vehicle, int const Eventdirection, end const End) -{ // sprawdzanie eventu w torze, czy jest sygnałowym - skanowanie do tyłu - // NOTE: this method returns only one event which meets the conditions, due to limitations in the caller - // TBD, TODO: clean up the caller and return all suitable events, as in theory things will go awry if the track has more than one signal - auto const dir{ Vehicle->VectorFront() * (double)Vehicle->DirectionGet() }; - auto const pos{ End == end::front ? Vehicle->RearPosition() : Vehicle->HeadPosition() }; - auto const &eventsequence { ( fDirection * Eventdirection > 0 ? Track->m_events2 : Track->m_events1 ) }; - for( auto const &event : eventsequence ) { - if( event.second != nullptr - && event.second->m_passive - && typeid(*event.second) == typeid(getvalues_event) ) { - // since we're checking for events behind us discard the sources in front of the scanning vehicle - auto const sl{ event.second->input_location() }; // położenie komórki pamięci - auto const sem{ sl - pos }; // wektor do komórki pamięci od końca składu - auto const isahead { dir.x * sem.x + dir.z * sem.z > 0 }; - if( End == end::front ? isahead : !isahead ) { - // iloczyn skalarny jest ujemny, gdy sygnał stoi z tyłu - return event.second; - } - } - } - return nullptr; -}; - -TTrack * TController::BackwardTraceRoute(double &fDistance, double &fDirection, TDynamicObject *Vehicle, basic_event *&Event, int const Eventdirection, end const End, bool const Untiloccupied ) -{ // szukanie sygnalizatora w kierunku przeciwnym jazdy (eventu odczytu komórki pamięci) - auto *Track = Vehicle->GetTrack(); - double fCurrentDistance = Vehicle->RaTranslationGet(); // aktualna pozycja na torze - if (fDirection > 0) // jeśli w kierunku Point2 toru - fCurrentDistance = Track->Length() - fCurrentDistance; - double s = 0; - - if( Track->VelocityGet() == 0.0 ) { // jak prędkosć 0 albo uszkadza, to nie ma po co skanować - fDistance = s; // to na tym torze stoimy - return nullptr; // stop, skanowanie nie dało sensownych rezultatów - } - // jak tor zajęty innym składem, to nie ma po co skanować - if( Untiloccupied && IsOccupiedByAnotherConsist( Track, fCurrentDistance * fDirection ) ) { - fDistance = s; // to na tym torze stoimy - return nullptr; // stop, skanowanie nie dało sensownych rezultatów - } - if ((Event = CheckTrackEventBackward(fDirection, Track, Vehicle, Eventdirection, End)) != nullptr) - { // jeśli jest semafor na tym torze - fDistance = s; // to na tym torze stoimy - return Track; - } - TTrack *pTrackFrom; // odcinek poprzedni, do znajdywania końca dróg - while (s < fDistance) - { - // Track->ScannedFlag=true; //do pokazywania przeskanowanych torów - pTrackFrom = Track; // zapamiętanie aktualnego odcinka - s += fCurrentDistance; // doliczenie kolejnego odcinka do przeskanowanej długości - if (fDirection > 0) - { // jeśli szukanie od Point1 w kierunku Point2 - if (Track->iNextDirection) - fDirection = -fDirection; - Track = Track->CurrentNext(); // może być NULL - } - else // if (fDirection<0) - { // jeśli szukanie od Point2 w kierunku Point1 - if (!Track->iPrevDirection) - fDirection = -fDirection; - Track = Track->CurrentPrev(); // może być NULL - } - if (Track == pTrackFrom) - Track = nullptr; // koniec, tak jak dla torów - - // gdy dalej toru nie ma albo zerowa prędkość, albo uszkadza pojazd - // zwraca NULL, że skanowanie nie dało sensownych rezultatów - if( Track == nullptr ) { - fDistance = s; - return nullptr; - } - if( Track->VelocityGet() == 0.0 ) - { - fDistance = s; - return nullptr; - } - if( Untiloccupied && IsOccupiedByAnotherConsist( Track ) ) { - fDistance = s; - return nullptr; - } - fCurrentDistance = Track->Length(); - if ((Event = CheckTrackEventBackward(fDirection, Track, Vehicle, Eventdirection, End)) != nullptr) - { // znaleziony tor z eventem - fDistance = s; - return Track; - } - } - Event = nullptr; // jak dojdzie tu, to nie ma semafora - // zwraca ostatni sprawdzony tor - fDistance = s; - return Track; -} - -// sprawdzanie zdarzeń semaforów i ograniczeń szlakowych -void TController::SetProximityVelocity( double dist, double vel, glm::dvec3 const *pos ) -{ // Ra:przeslanie do AI prędkości - /* - //!!!! zastąpić prawidłową reakcją AI na SetProximityVelocity !!!! - if (vel==0) - {//jeśli zatrzymanie, to zmniejszamy dystans o 10m - dist-=10.0; - }; - if (dist<0.0) dist=0.0; - if ((vel<0)?true:dist>0.1*(MoverParameters->Vel*MoverParameters->Vel-vel*vel)+50) - {//jeśli jest dalej od umownej drogi hamowania - */ - PutCommand( "SetProximityVelocity", dist, vel, pos ); - /* - } - else - {//jeśli jest zagrożenie, że przekroczy - Mechanik->SetVelocity(floor(0.2*sqrt(dist)+vel),vel,stopError); - } - */ -} - -TCommandType TController::BackwardScan( double const Range ) -{ // sprawdzanie zdarzeń semaforów z tyłu pojazdu, zwraca komendę - // dzięki temu będzie można stawać za wskazanym sygnalizatorem, a zwłaszcza jeśli będzie jazda na kozioł - // ograniczenia prędkości nie są wtedy istotne, również koniec toru jest do niczego nie przydatny - // zwraca true, jeśli należy odwrócić kierunek jazdy pojazdu - if( OrderCurrentGet().Without(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect) ) { - // skanowanie sygnałów tylko gdy jedzie w trybie manewrowym albo czeka na rozkazy - return TCommandType::cm_Unknown; - } - // kierunek jazdy względem sprzęgów pojazdu na czele - int const startdir = -pVehicles[0]->DirectionGet(); - if( startdir == 0 ) { - // jeśli kabina i kierunek nie jest określony nie robimy nic - return TCommandType::cm_Unknown; - } - // szukamy od pierwszej osi w wybranym kierunku - double scandir = startdir * pVehicles[0]->RaDirectionGet(); - - if( scandir == 0.0 ) { return TCommandType::cm_Unknown; } - - // skanowanie toru w poszukiwaniu eventów GetValues (PutValues nie są przydatne) - // Ra: przy wstecznym skanowaniu prędkość nie ma znaczenia - double scandist = Range; // zmodyfikuje na rzeczywiście przeskanowane - basic_event *e = nullptr; // event potencjalnie od semafora - // opcjonalnie może być skanowanie od "wskaźnika" z przodu, np. W5, Tm=Ms1, koniec toru wg - // drugiej osi w kierunku ruchu - auto const *scantrack{BackwardTraceRoute(scandist, scandir, pVehicles[end::front], e)}; - auto const dir{(double)startdir * - pVehicles[end::front]->VectorFront()}; // wektor w kierunku jazdy/szukania - - // jeśli wstecz wykryto koniec toru to raczej nic się nie da w takiej sytuacji zrobić - if (e == nullptr) - { - return TCommandType::cm_Unknown; - } - if (typeid(*e) != typeid(getvalues_event)) - { - return TCommandType::cm_Unknown; - } - - // jeśli jest jakiś sygnał na widoku - double scanvel; // prędkość ustawiona semaforem -#if LOGBACKSCAN - std::string edir{"Backward scan by " + pVehicle->asName + " - " + - ((scandir > 0) ? "Event2 " : "Event1 ")}; - edir += "(" + (e->name()) + ")"; -#endif - { - // najpierw sprawdzamy, czy semafor czy inny znak został przejechany - auto const sl{e->input_location()}; // położenie komórki pamięci - auto const pos{pVehicles[end::rear]->RearPosition()}; // pozycja tyłu - if (auto const sem{sl - pos}; dir.x * sem.x + dir.z * sem.z < 0) // wektor do komórki pamięci od końca składu - { - // jeśli został minięty - // iloczyn skalarny jest ujemny, gdy sygnał stoi z tyłu -#if LOGBACKSCAN - WriteLog(edir + " - ignored as not passed yet"); -#endif - return TCommandType::cm_Unknown; // nic - } - scanvel = e->input_value(1); // prędkość przy tym semaforze -#if LOGBACKSCAN - // przeliczamy odległość od semafora - potrzebne by były współrzędne początku składu - scandist = std::max(glm::length(sl - pos) - 2.0, 0.0); // 2m luzu przy manewrach wystarczy, ujemnych nie ma po co wysyłać -#endif - } - - auto move{false}; // czy AI w trybie manewerowym ma dociągnąć pod S1 - if (e->input_command() == TCommandType::cm_SetVelocity) - { - if (scanvel == 0.0 ? OrderCurrentGet() & (DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect) : - OrderCurrentGet() & DriverOrder::connect) - { // przy podczepianiu ignorować wyjazd? - move = true; // AI w trybie manewerowym ma dociągnąć pod S1 - } - else - { - // jeśli semafor jest daleko, a pojazd jedzie, to informujemy o zmianie prędkości - // jeśli jedzie manewrowo, musi dostać SetVelocity, żeby sie na pociągowy przełączył - // w przeciwnym razie ustawiamy prędkość tylko wtedy, gdy ma ruszyć, stanąć albo ma stać - // ruszać stop trzeba powtarzać, bo inaczej zatrąbi i pojedzie sam -#if LOGBACKSCAN - if (scandist > fMinProximityDist && - mvOccupied->Vel > EU07_AI_NOMOVEMENT && false == OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt)) - { - WriteLog(edir); - } - else - { - WriteLog(edir + " - [SetVelocity] [" + to_string(scanvel, 2) + "] [" + - to_string(e->input_value(2), 2) + "]"); - } -#endif - return scanvel > 0 ? TCommandType::cm_SetVelocity : TCommandType::cm_Unknown; - } - } - // reakcja AI w trybie manewrowym dodatkowo na sygnały manewrowe - if ((false == OrderCurrentGet().Empty() ? OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect) : true) && (move || e->input_command() == TCommandType::cm_ShuntVelocity)) // w Wait_for_orders też widzi tarcze - { - // jeśli powyżej było SetVelocity 0 0, to dociągamy pod S1 - /* - if ((scandist > fMinProximityDist) && - ((mvOccupied->Vel > EU07_AI_NOMOVEMENT) || (scanvel == 0.0))) - { - // jeśli tarcza jest daleko, to: - //- jesli pojazd jedzie, to informujemy o zmianie prędkości - //- jeśli stoi, to z własnej inicjatywy może podjechać pod zamkniętą tarczę - if (mvOccupied->Vel > EU07_AI_NOMOVEMENT) // tylko jeśli jedzie - { // Mechanik->PutCommand("SetProximityVelocity",scandist,scanvel,sl); - #if LOGBACKSCAN - // WriteLog(edir+"SetProximityVelocity "+AnsiString(scandist)+" - // "+AnsiString(scanvel)); - WriteLog(edir); - #endif - // SetProximityVelocity(scandist,scanvel,&sl); - // jeśli jedzie na W5 albo koniec toru, to można zmienić kierunek - return (drivingFlags.trackEnd) ? TCommandType::cm_ChangeDirection : - TCommandType::cm_Unknown; - // TBD: request direction change also if VelNext in current direction is 0, - // while signal behind requests movement? - } - } - else - { - // ustawiamy prędkość tylko wtedy, gdy ma ruszyć, albo stanąć albo ma stać pod - // tarczą stop trzeba powtarzać, bo inaczej zatrąbi i pojedzie sam if - // ((MoverParameters->Vel==0.0)||(scanvel==0.0)) //jeśli jedzie lub ma stanąć/stać - { // nie dostanie komendy jeśli jedzie i ma jechać - // PutCommand("ShuntVelocity",scanvel,e->Params[9].asMemCell->Value2(),&sl,stopSem); - #if LOGBACKSCAN - WriteLog(edir + " - [ShuntVelocity] [" + to_string(scanvel, 2) + "] [" + - to_string(e->input_value(2), 2) + "]"); - #endif - return (scanvel > 0 ? TCommandType::cm_ShuntVelocity : - TCommandType::cm_Unknown); - } - } - // NOTE: dead code due to returns in branching above - if ((scanvel != 0.0) && (scandist < 100.0)) - { - // jeśli Tm w odległości do 100m podaje zezwolenie na jazdę, to od razu ją - // ignorujemy, aby móc szukać kolejnej eSignSkip=e; //wtedy uznajemy ignorowaną przy - // poszukiwaniu nowej - #if LOGBACKSCAN - WriteLog(edir + " - will be ignored due to Ms2"); - #endif - return (scanvel > 0 ? TCommandType::cm_ShuntVelocity : TCommandType::cm_Unknown); - } - */ - return VelNext > 0 ? - TCommandType::cm_Unknown : // no need to bother if we can continue in current direction - scanvel == 0 ? - TCommandType::cm_Unknown : // no need to bother with a stop signal - TCommandType::cm_ShuntVelocity; // otherwise report a relevant shunt signal behind - // if (move?... - } // if (OrderCurrentGet()==Shunt) - - return e->m_passive && e->is_command() ? TCommandType::cm_Command : TCommandType::cm_Unknown; -}; - -std::string TController::NextStop() const -{ // informacja o następnym zatrzymaniu, wyświetlane pod [F1] - if (asNextStop == "[End of route]") - return ""; // nie zawiera nazwy stacji, gdy dojechał do końca - // dodać godzinę odjazdu - // the name the way the timetable spells it, in utf-8 as the user interface takes it - auto nextstop{ TrainParams.station_caption( asNextStop ) }; - auto const *t{ TrainParams.TimeTable + TrainParams.StationIndex }; - if( t->Ah >= 0 ) { - // przyjazd - nextstop += " przyj." + std::to_string( t->Ah ) + ":" - + to_minutes_str( t->Am, true, 3 ); - - } - if( t->Dh >= 0 ) { - // jeśli jest godzina odjazdu - nextstop += " odj." + std::to_string( t->Dh ) + ":" - + to_minutes_str( t->Dm, true, 3 ); - } - return nextstop; -}; - -void TController::UpdateDelayFlag() { - - if( TrainParams.CheckTrainLatency() < 0.0 ) { - // odnotowano spóźnienie - drivingFlags.late = true; - } - else { - // przyjazd o czasie - drivingFlags.late = false; - } -} - -//-----------koniec skanowania semaforow - -void TController::TakeControl( bool const Aidriver, bool const Forcevehiclecheck ) -{ // przejęcie kontroli przez AI albo oddanie - if (AIControllFlag == Aidriver && !Forcevehiclecheck) - return; // już jest jak ma być - if( AIControllFlag != Aidriver ) { - // the autopilot switched on or off - simulation::Blackbox.driver_changed( pVehicle, Aidriver ); - } - if (Aidriver) //żeby nie wykonywać dwa razy - { // teraz AI prowadzi - AIControllFlag = AIdriver; - pVehicle->Controller = AIdriver; - // the AI doesn't operate the headlight dimmer, drop the state left by the human driver - // so the lights set by the AI aren't hidden (dimmer in off position) or dimmed - pVehicle->HeadlightsAoff = false; - pVehicle->HeadlightsBoff = false; - pVehicle->DimHeadlights = false; - pVehicle->HighBeamLights = false; - control_lights(); // reinicjalizacja swiatel - mvOccupied->CabActivisation(true); - iDirection = 0; // kierunek jazdy trzeba dopiero zgadnąć - TableClear(); // ponowne utworzenie tabelki, bo człowiek mógł pojechać niezgodnie z sygnałami - if( action() != TAction::actSleep ) { - // gdy zgaszone światła, flaga podjeżdżania pod semafory pozostaje bez zmiany - // conditional below disabled to get around the situation where the AI train does nothing ever - // because it is waiting for orders which don't come until the engine is engaged, i.e. effectively never - if( OrderCurrentGet() ) { - // jeśli coś robi - PrepareEngine(); // niech sprawdzi stan silnika - } - else { - // jeśli nic nie robi - OrderNext( DriverOrder::prepareEngine ); - if( pVehicle->MoverParameters->iLights[ ( mvOccupied->CabActive < 0 ? - end::rear : - end::front ) ] - & ( light::headlight_left | light::headlight_right | light::headlight_upper ) ) // któreś ze świateł zapalone? - { // od wersji 357 oczekujemy podania komend dla AI przez scenerię -/* - if( pVehicle->MoverParameters->iLights[ mvOccupied->CabActive < 0 ? end::rear : end::front ] & light::headlight_upper ) // górne światło zapalone - OrderNext( DriverOrder::obeyTrain ); // jazda pociągowa - else - OrderNext( DriverOrder::shunt ); // jazda manewrowa -*/ - if( mvOccupied->Vel >= 1.0 ) // jeśli jedzie (dla 0.1 ma stać) - drivingFlags.stopHere = false; // to ma nie czekać na sygnał, tylko jechać - else - drivingFlags.stopHere = true; // a jak stoi, to niech czeka - } - } - CheckVehicles(); // ustawienie świateł - } - } - else - { // a teraz użytkownik - if (eAction == TAction::actSleep || OrderCurrentGet() == DriverOrder::waitForOrders) // gasimy swiatla jesli przejmujemy odstawione - pVehicle->RaLightsSet(0, 0); - auto const aiwasdriving { AIControllFlag == AIdriver }; - if( aiwasdriving ) { - // the horn, sandbox, departure signal and brake releaser the AI may have latched are momentary for the human driver - handover::release_ai_controls( *mvOccupied, *mvControlling ); - fWarningDuration = 0.0; - remove_hint( driver_hint::hornon ); - // the AI sets the lights directly, leave the selector in matching position so it doesn't revert them later - sync_lights_selector(); - } - AIControllFlag = Humandriver; - pVehicle->Controller = Humandriver; - if( aiwasdriving ) { - // same with the headlight dimmer, which is only applied for the human driver - sync_lights_dimmer(); - } - if( eAction == TAction::actSleep ) { - eAction = TAction::actUnknown; - } - if( Forcevehiclecheck ) { - // update consist ownership and other consist data - CheckVehicles(); - } - } -}; - -void TController::DirectionForward(bool forward) -{ // ustawienie jazdy do przodu dla true i do tyłu dla false (zależy od kabiny) - ZeroSpeed( true ); // TODO: check if force switch is needed anymore here - // HACK: make sure the master controller isn't set in position which prevents direction change - mvControlling->MainCtrlPos = std::min( mvControlling->MainCtrlPos, mvControlling->MainCtrlMaxDirChangePos ); - - if( forward ) { - // do przodu w obecnej kabinie - while( mvOccupied->DirActive <= 0 - && mvOccupied->DirectionForward() ) { - // force scan table update - iTableDirection = 0; - } - } - else { - // do tyłu w obecnej kabinie - while( mvOccupied->DirActive >= 0 - && mvOccupied->DirectionBackward() ) { - // force scan table update - iTableDirection = 0; - } - } - if( mvOccupied->TrainType == train_type::sn61 ) { - // specjalnie dla SN61 żeby nie zgasł - while( mvControlling->RList[mvControlling->MainCtrlPos].Mn == 0 - && mvControlling->IncMainCtrl(1) ) { - ; // all work is done in the header - } - } -} - -void TController::ZeroDirection() { - - while( mvOccupied->DirActive > 0 && mvOccupied->DirectionBackward() ) { ; } - while( mvOccupied->DirActive < 0 && mvOccupied->DirectionForward() ) { ; } -} - -void TController::sync_consist_reversers() { - - auto const currentdirection { mvOccupied->DirActive }; - auto const fastforward { is_emu() && mvOccupied->EngineType != TEngineType::ElectricInductionMotor - && mvOccupied->Imin == mvOccupied->IminHi }; - - // move reverser all way in the opposite direction... - for( auto idx = 0; idx < 3; ++idx ) { - if( currentdirection >= 0 ) { - mvOccupied->DirectionBackward(); - } - else { - mvOccupied->DirectionForward(); - - } - } - // ...then restore original setting - while( mvOccupied->DirActive != currentdirection ) { - if( false == ( - currentdirection >= 0 ? - mvOccupied->DirectionForward() : - mvOccupied->DirectionBackward() ) ) { - // sanity check for potential endless loop - break; - } - } - // potentially restore 'fast forward' setting - if( currentdirection > 0 && true == fastforward ) { - mvOccupied->DirectionForward(); - } -} - -Mtable::TTrainParameters const & -TController::TrainTimetable() const { - return TrainParams; -} - -std::string TController::Relation() const -{ // zwraca relację pociągu - return TrainParams.ShowRelation(); -}; - -const std::string& TController::TrainName() const -{ // zwraca numer pociągu - return TrainParams.TrainName; -}; - -int TController::StationCount() const -{ // zwraca ilość stacji (miejsc zatrzymania) - return TrainParams.StationCount; -}; - -int TController::StationIndex() const -{ // zwraca indeks aktualnej stacji (miejsca zatrzymania) - return TrainParams.StationIndex; -}; - -bool TController::IsStop() const -{ // informuje, czy jest zatrzymanie na najbliższej stacji - return TrainParams.IsStop(); -}; - -// returns most recently calculated distance to potential obstacle ahead -double -TController::TrackObstacle() const { - - return Obstacle.distance; -} - -void TController::MoveTo(TDynamicObject *to) -{ // przesunięcie AI do innego pojazdu (przy zmianie kabiny) - if( to->Mechanik != nullptr - && to->Mechanik != this ) { - // ai controller thunderdome, there can be only one - if( to->Mechanik->AIControllFlag ) { - if( to->Mechanik->primary() ) { - // take over boss duties - primary( true ); - } - SafeDelete( to->Mechanik ); - } - else { - // can't quite delete a human - if( AIControllFlag ) { - delete this; - } - return; - } - } - pVehicle->Mechanik = nullptr; - pVehicle = to; - ControllingSet(); // utworzenie połączenia do sterowanego pojazdu - pVehicle->Mechanik = this; - -}; - -void TController::ControllingSet() -{ // znajduje człon do sterowania w EZT będzie to silnikowy - // problematyczne jest sterowanie z członu biernego, dlatego damy AI silnikowy - // dzięki temu będzie wirtualna kabina w silnikowym, działająca w rozrządczym - // w plikach FIZ zostały zgubione ujemne maski sprzęgów, stąd problemy z EZT - if( pVehicle == nullptr ) { - // a driver of no vehicle has nothing to control - return; - } - mvOccupied = pVehicle->MoverParameters; // domyślny skrót do obiektu parametrów - BrakeSystem = mvOccupied->BrakeSystem; // domyślny sposób hamowania - mvControlling = pVehicle->FindPowered()->MoverParameters; // poszukiwanie członu sterowanego - { - auto *lookup { pVehicle->FindPantographCarrier() }; - mvPantographUnit = lookup != nullptr ? lookup->MoverParameters : mvControlling; - } - BrakeSystem = consist_brake_system(); -}; - -std::string TController::TableText( std::size_t const Index ) const -{ // pozycja tabelki prędkości - if( Index < sSpeedTable.size() ) { - return sSpeedTable[ Index ].TableText(); - } - else { - return ""; - } -}; - -int TController::CrossRoute(TTrack *tr) -{ // zwraca numer segmentu dla skrzyżowania (tr) - // pożądany numer segmentu jest określany podczas skanowania drogi - // droga powinna być określona sposobem przejazdu przez skrzyżowania albo współrzędnymi miejsca - // docelowego - for( std::size_t i = 0; i < sSpeedTable.size(); ++i ) - { // trzeba przejrzeć tabelę skanowania w poszukiwaniu (tr) - // i jak się znajdzie, to zwrócić zapamiętany numer segmentu i kierunek przejazdu - // (-6..-1,1..6) - if( true == sSpeedTable[i].flags.HasAll(SpeedPointFlag::enabled | SpeedPointFlag::track) - && sSpeedTable[i].trTrack == tr ) { - // jeśli pozycja odpowiadająca skrzyżowaniu (tr) - return sSpeedTable[i].crossRoute; // -8..7 - } - } - return 0; // nic nie znaleziono? -}; -/* -void TController::RouteSwitch(int d) -{ // ustawienie kierunku jazdy z kabiny - d &= 3; - if( ( d != 0 ) - && ( iRouteWanted != d ) ) { // nowy kierunek - iRouteWanted = d; // zapamiętanie - if( mvOccupied->CategoryFlag & 2 ) { - // jeśli samochód - for( std::size_t i = 0; i < sSpeedTable.size(); ++i ) { - // szukanie pierwszego skrzyżowania i resetowanie kierunku na nim - if( true == sSpeedTable[ i ].flags.HasAll(spEnabled | spTrack) ) { - // jeśli pozycja istotna (1) oraz odcinek (2) - if( false == sSpeedTable[ i ].flags.HasAll(spElapsed) ) { - // odcinek nie może być miniętym - if( sSpeedTable[ i ].trTrack->eType == tt_Cross ) // jeśli skrzyżowanie - { - while( sSpeedTable.size() >= i ) { - // NOTE: we're ignoring semaphor flags and not resetting them like we do for train route trimming - // but what if there's street lights? - // TODO: investigate - sSpeedTable.pop_back(); - } - iLast = sSpeedTable.size(); - } - } - } - } - } - } -}; -*/ -std::string TController::OwnerName() const -{ - return pVehicle ? pVehicle->MoverParameters->Name : "none"; -}; - -void -TController::update_timers( double dt ) { - - ElapsedTime += dt; - WaitingTime += dt; - fBrakeTime -= dt; // wpisana wartość jest zmniejszana do 0, gdy ujemna należy zmienić nastawę hamulca - fBrakeHeldTime += dt; - if( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_FS ) ) { - // brake charging timeout starts after charging ends - BrakeChargingCooldown += dt; - } - fStopTime += dt; // zliczanie czasu postoju, nie ruszy dopóki ujemne - fActionTime += dt; // czas używany przy regulacji prędkości i zamykaniu drzwi - LastReactionTime += dt; - if( mvOccupied->Vel < 0.05 - && OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank) ) { - IdleTime += dt; - } - else { - IdleTime = 0.0; - } - fWarningDuration -= dt; // horn activation while the value is positive -} - -void -TController::update_logs( double const dt ) { - // log vehicle data - if( false == writes_physicslog() ) { - // not counted while it isn't logged (the driver of a road vehicle, or no logs on): were the logs turned on, - // it would write a line every 0.05 s from then on, not one each update to make up for the time before - LastUpdatedTime = 0.0; - return; - } - LastUpdatedTime += dt; - if( LastUpdatedTime > deltalog ) { - // zapis do pliku DAT - if( false == PhysicsLogBegun ) { - begin_physicslog(); - } - PhysicsLog(); - LastUpdatedTime -= deltalog; - } -} - -void -TController::determine_consist_state() { - // ABu-160305 testowanie gotowości do jazdy - // Ra: przeniesione z DynObj, skład użytkownika też jest testowany, żeby mu przekazać, że ma odhamować - - if (mvOccupied->CabActive == 0 && mvOccupied->Power24vIsAvailable) - { - cue_action( driver_hint::cabactivation ); - } - else if (!mvOccupied->AutomaticCabActivation - && ( mvOccupied->CabActive == -mvOccupied->CabOccupied || !mvOccupied->CabMaster || !mvOccupied->Power24vIsAvailable ) ) - { - cue_action( driver_hint::cabdeactivation ); - } - - int index = double(BrakeAccTableSize) * (mvOccupied->Vel / mvOccupied->Vmax); - index = std::min(BrakeAccTableSize, std::max(1, index)); - fBrake_a0[0] = fBrake_a0[index]; - fBrake_a1[0] = fBrake_a1[index]; - - if (is_emu() || is_dmu()) { - auto Coeff = std::clamp( mvOccupied->Vel*0.015 , 0.5 , 1.0); - fAccThreshold = fNominalAccThreshold * Coeff - fBrake_a0[BrakeAccTableSize] * (1.0 - Coeff); - } - - Ready = true; // wstępnie gotowy - fReady = 0.0; // założenie, że odhamowany - IsConsistBraked = mvOccupied->BrakeSystem == TBrakeSystem::ElectroPneumatic && false == ForcePNBrake ? mvOccupied->BrakePress > 2.0 : - mvOccupied->PipePress < std::max(3.9, mvOccupied->BrakePressureActual.PipePressureVal) + 0.1; - fAccGravity = 0.0; // przyspieszenie wynikające z pochylenia - IsAnyCouplerStretched = false; - IsAnyDoorOnlyOpen[ side::right ] = IsAnyDoorOnlyOpen[ side::left ] = false; - IsAnyDoorOpen[ side::right ] = IsAnyDoorOpen[ side::left ] = false; - IsAnyDoorPermitActive[ side::right ] = IsAnyDoorPermitActive[ side::left ] = false; - auto doorclosure { door_closure_t::none }; - ConsistShade = 0.0; - auto *p { pVehicles[ end::front ] }; // pojazd na czole składu - double dy; // składowa styczna grawitacji, w przedziale <0,1> - // starting uphill the power is applied against the train brake on purpose, until the power holds the train and - // then while the brake releases - auto const heldforstart { bUphillStart }; - auto released { true }; // the brakes are off, the hold of an uphill start not counted - auto mostapplied { 0.0 }; // the most applied brake, the hold of an uphill start not counted - auto momentum { 0.0 }; - auto chargelevel { std::numeric_limits::max() }; // the lowest pipe or auxiliary reservoir pressure of a working brake - while (p) - { // sprawdzenie odhamowania wszystkich połączonych pojazdów - auto *vehicle { p->MoverParameters }; - auto const bp { std::max( 0.0, vehicle->BrakePress - ( vehicle->SpeedCtrlUnit.Parking ? vehicle->MaxBrakePress[ 0 ] * vehicle->StopBrakeDecc : 0.0 ) ) }; - momentum += vehicle->TotalMass * vehicle->V * ( p->DirectionGet() == iDirection ? 1 : -1 ); - mostapplied = std::max( bp, mostapplied ); - if( ( vehicle->BrakeSystem != TBrakeSystem::Individual ) - && ( vehicle->MaxBrakePress[ 3 ] > 0.0 ) - && ( false == TestFlag( vehicle->Hamulec->GetBrakeStatus(), b_dmg ) ) ) { // a brake cut out doesn't count - chargelevel = std::min( { chargelevel, vehicle->PipePress, vehicle->Hamulec->GetBRP() } ); - } - auto const wasready { Ready }; - if( released || Ready ) { - // bo jak coś nie odhamowane, to dalej nie ma co sprawdzać - auto const isbraking { TestFlagAny( vehicle->Hamulec->GetBrakeStatus(), b_hld | b_on ) }; - if( vehicle->Vel < 1.0 ? - isbraking || bp > 0.4 : // ensure the brakes are sufficiently released when starting to move - // once in motion a brake down to 0.4 bar counts as released (UIC), even if its distributor - // is still in the lap position while the brake pipe recharges - ( isbraking && bp > 0.4 ) || vehicle->Fb > 10000.0 ) { // 10 kN - released = false; - // ready all the same with the power going on against the brake on purpose: at a standstill, and once - // the power holds the train, while the brake releases; otherwise in motion a braking force left - // anywhere in the train (a hand brake) stops it as before - Ready = Ready && heldforstart && ( bUphillRelease || ( vehicle->Vel < 1.0 ) ); - } - } - if( wasready ) { - // Ra: odluźnianie przeładowanych lokomotyw, ciągniętych na zimno - prowizorka... - if( bp >= 0.4 && (AIControllFlag || Global.AITrainman && mvOccupied->Vel < EU07_AI_NOMOVEMENT && !is_emu() && !is_dmu()) && BrakeCtrlPosition == gbh_RP // jest pozycja jazdy - && false == TestFlag(vehicle->Hamulec->GetBrakeStatus(), b_dmg) // brake isn't broken - && vehicle->PipePress - mvOccupied->Handle->GetRP() > -0.1 // jeśli ciśnienie jak dla jazdy - && vehicle->Hamulec->GetCRP() > vehicle->PipePress + 0.12 ) { // wg UIC określone sztywno na 0.04 - // za dużo w zbiorniku - // indywidualne luzowanko - vehicle->BrakeReleaser(1); - } - if (bp < 0.1 && (AIControllFlag || Global.AITrainman) && false == TestFlag(vehicle->Hamulec->GetBrakeStatus(), b_dmg) // brake isn't broken - && vehicle->Hamulec->GetCRP() < vehicle->PipePress - 0.1) { - // już nie jest za dużo w zbiorniku - // koniec indywidualnego luzowanka - vehicle->BrakeReleaser(0); - } - } - // the brake held for the start counts again once it is being released - fReady = std::max( ( heldforstart && ( false == bUphillRelease ) ) ? 0.0 : bp, fReady ); // szukanie najbardziej zahamowanego - if( ( dy = p->VectorFront().y ) != 0.0 ) { - // istotne tylko dla pojazdów na pochyleniu - // ciężar razy składowa styczna grawitacji - fAccGravity -= vehicle->TotalMassxg * dy * ( p->DirectionGet() == iDirection ? 1 : -1 ); - } - // check coupler state - IsAnyCouplerStretched = - IsAnyCouplerStretched - || vehicle->Couplers[end::front].stretch_duration > 0.0 - || vehicle->Couplers[end::rear].stretch_duration > 0.0; - // check door state - { - auto const switchsides{ p->DirectionGet() != (iDirection == 0 ? mvOccupied->CabOccupied : iDirection) }; - auto const &rightdoor { vehicle->Doors.instances[ ( switchsides ? side::left : side::right ) ] }; - auto const &leftdoor { vehicle->Doors.instances[ ( switchsides ? side::right : side::left ) ] }; - if( vehicle->Doors.close_control != control_t::autonomous ) { - IsAnyDoorOpen[ side::right ] |= false == rightdoor.is_closed; - IsAnyDoorOpen[ side::left ] |= false == leftdoor.is_closed; - } - if (vehicle->Doors.close_control != control_t::autonomous) { - IsAnyDoorOnlyOpen[ side::right ] |= false == rightdoor.is_door_closed; - IsAnyDoorOnlyOpen[ side::left ] |= false == leftdoor.is_door_closed; - } - if( vehicle->Doors.permit_needed ) { - IsAnyDoorPermitActive[ side::right ] |= rightdoor.open_permit; - IsAnyDoorPermitActive[ side::left ] |= leftdoor.open_permit; - } - doorclosure = std::max( doorclosure, vehicle->door_closure() ); - } - // measure lighting level - // TBD: apply weight (multiplier) to partially lit vehicles? - ConsistShade += p->fShade > 0.0 ? p->fShade : 1.0; - p = p->Next(); // pojazd podłączony z tyłu (patrząc od czoła) - } - DoorClosure = doorclosure; - // calculate average amount of received sunlight - ConsistShade /= iVehicles; - - // test state of main devices in all vehicles under control - IsAnyConverterOverloadRelayOpen = false; - IsAnyMotorOverloadRelayOpen = false; - IsAnyGroundRelayOpen = false; - IsAnyLineBreakerOpen = false; - IsAnyCompressorPresent = false; - IsAnyCompressorEnabled = false; - IsAnyCompressorExplicitlyEnabled = false; - IsAnyConverterPresent = false; - IsAnyConverterEnabled = false; - IsAnyConverterExplicitlyEnabled = false; - // whether the line contactors of a vehicle wait for its own converter (LineContactorsInterlock), off with its local switch - auto islocalconverterswitchoff { false }; - - pVehicle->for_each( - Coupling::control, - [this, &islocalconverterswitchoff]( TDynamicObject * Vehicle ) { - auto const *vehicle { Vehicle->MoverParameters }; - islocalconverterswitchoff |= vehicle->LineContactorsHeldByLocalConverterSwitch(); - IsAnyConverterOverloadRelayOpen |= vehicle->ConvOvldFlag; - IsAnyMotorOverloadRelayOpen |= vehicle->FuseFlag; - IsAnyGroundRelayOpen |= !vehicle->GroundRelay; - IsAnyCompressorPresent |= vehicle->CompressorSpeed > 0.0; - IsAnyCompressorEnabled |= vehicle->CompressorSpeed > 0.0 ? (vehicle->CompressorAllow || vehicle->CompressorStart == start_t::automatic) && vehicle->CompressorAllowLocal : false; - IsAnyCompressorExplicitlyEnabled |= vehicle->CompressorSpeed > 0.0 ? vehicle->CompressorAllow && vehicle->CompressorAllowLocal : false; - IsAnyConverterPresent |= vehicle->ConverterStart != start_t::disabled; - IsAnyConverterEnabled |= ( vehicle->ConverterAllow || vehicle->ConverterStart == start_t::automatic ) && vehicle->ConverterAllowLocal; - IsAnyConverterExplicitlyEnabled |= vehicle->ConverterAllow && vehicle->ConverterAllowLocal; - if( vehicle->Power > 0.01 ) { - IsAnyLineBreakerOpen |= !vehicle->Mains; } } ); - - // siłę generują pojazdy na pochyleniu ale działa ona całość składu, więc a=F/m - fAccGravity *= iDirection >= 0 ? 1 : -1; - fAccGravity /= fMass; - { - auto absaccs { fAccGravity }; // Ra 2014-03: jesli skład stoi, to działa na niego składowa styczna grawitacji - if( mvOccupied->Vel > EU07_AI_NOMOVEMENT ) { - absaccs = 0; - auto *d = pVehicles[ end::front ]; // pojazd na czele składu - while( d ) { - absaccs += d->MoverParameters->TotalMass * d->MoverParameters->AccS * ( d->DirectionGet() == iDirection ? 1 : -1 ); - d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) - } - absaccs *= iDirection >= 0 ? 1 : -1; - absaccs /= fMass; - } - AbsAccS = absaccs; - } -#if LOGVELOCITY - WriteLog( "Vel=" + to_string( DirectionalVel() ) + ", AbsAccS=" + to_string( AbsAccS ) + ", AccGrav=" + to_string( fAccGravity ) ); -#endif - - if( !Ready // v367: jeśli wg powyższych warunków skład nie jest odhamowany - && fAccGravity < -0.05 // jeśli ma pod górę na tyle, by się stoczyć - && fReady < 0.8 ) { // delikatniejszy warunek, obejmuje wszystkie wagony - Ready = true; //żeby uznać za odhamowany - } - // the same test without the hold of an uphill start - IsConsistReleased = released || ( fAccGravity < -0.05 && mostapplied < 0.8 ); - // the frame of the vehicle the AI drives from, as for fAccGravity and AbsAccS - fConsistVelocity = 3.6 * momentum / std::max( 1.0, fMass ) * ( iDirection >= 0 ? 1 : -1 ); - // standing, the train starts only with its brakes charged: released alone, a train prepared from cold has no air to - // brake with while its auxiliary reservoirs fill. with the train brake applied (held for an uphill start, a light - // application while charging) they charge to what the head of the pipe has. - // only the start the charge is in question for: the first after the train was prepared standing, or one with the - // pipe near empty (after an emergency application, brake_charge::empty_level). after an ordinary stop the - // reservoirs refill as the brake releases, and waiting for the last tenths of a bar there only delays the train and - // those behind it. - // and only the pneumatic brake: multiple units with the electro-pneumatic one start as before - if( mvOccupied->Vel > 1.0 ) { - // the start is made. a shunting engine coupling wagons moves at a walking pace: a higher speed would leave its - // every start the first, waiting for each cut of wagons placed cold to charge - bBrakeChargeStart = false; - bBrakeChargeHold = false; - bHasRun = true; - } - auto const chargeable { - ( BrakeSystem == TBrakeSystem::Pneumatic ) - && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) - && ( chargelevel < std::numeric_limits::max() ) }; - if( chargeable && ( chargelevel < brake_charge::empty_level ) ) { - bBrakeChargeStart = true; - } - if( chargeable && bBrakeChargeStart ) { - if( ( VelDesired <= 0.0 ) || ( AccDesired <= EU07_AI_NOACCELERATION ) ) { - // to stand: the next start is checked anew - BrakeCharge.going = false; - } - auto const trainbrakeapplied { - AIControllFlag ? - BrakeCtrlPosition > 0.0 : - // a human driver's handle, which BrakeCtrlPosition doesn't follow - mvOccupied->fBrakeCtrlPos > mvOccupied->Handle->GetPos( bh_RP ) + 0.2 }; - auto const reference { - brake_charge::reference( mvOccupied->PipePress, std::min( mvOccupied->Handle->GetRP(), 5.0 ), trainbrakeapplied ) }; - // air to charge with: the engine prepared, the main reservoir above what the pipe charges to, and the driver's - // brake valve feeding the pipe at the head of the train. a train still being prepared from cold can't charge, - // nor one whose pipe is locked (unlocked by control_releaser()): it waits without that counting as a stall, held - // by its brakes as it can't release them either - auto const supplied { - iEngineActive - && ( std::max( mvControlling->Compressor, mvOccupied->Compressor ) > reference ) - && ( mvOccupied->PipePress >= reference - brake_charge::margin ) }; - auto const wasstalled { BrakeCharge.stalled }; - IsConsistCharged = brake_charge::charged( BrakeCharge, chargelevel, reference, ElapsedTime, supplied ); - if( BrakeCharge.stalled && ( false == wasstalled ) ) { - WriteLog( - "AI: " + mvOccupied->Name + " stopped charging its brakes at " + to_string( chargelevel, 2 ) - + " bar of " + to_string( reference, 2 ) + ", starting all the same" ); - } - if( false == IsConsistCharged ) { - // a human driver is told to wait as the ai does, the locomotive brake applied - cue_action( driver_hint::waitbrakecharge ); - } - } - else { - IsConsistCharged = true; - BrakeCharge = {}; - } - if( AIControllFlag - && ( false == IsConsistCharged ) - && ( false == heldforstart ) ) { - Ready = false; - } - auto const departblocked { - AIControllFlag - && mvOccupied->Vel < EU07_AI_NOMOVEMENT - && VelDesired > 0.0 - && ( false == Ready || fReady > 0.4 ) }; - if( false == departblocked ) { - DepartBlockedStart = -1.0; - } - else if( DepartBlockedStart < 0.0 ) { - DepartBlockedStart = ElapsedTime; - } - // second pass, for diesel engines verify the (live) engines are fully started - // TODO: cache presence of diesel engines in the consist, to skip this test if there isn't any - p = pVehicles[ end::front ]; // pojazd na czole składu - while( true == Ready - && p != nullptr ) { - - auto const *vehicle { p->MoverParameters }; - - if( has_diesel_engine() ) { - - Ready = vehicle->Vel > EU07_AI_MOVEMENT // already moving - || false == vehicle->Mains // deadweight vehicle - || vehicle->enrot > 0.8 * (vehicle->EngineType == TEngineType::DieselEngine ? vehicle->dizel_nmin : vehicle->DElist[0].RPM / 60.0); - } - p = p->Next(); // pojazd podłączony z tyłu (patrząc od czoła) - } - // test consist state for external events and/or weird things human user could've done - iEngineActive &= - false == IsAnyConverterOverloadRelayOpen - && false == IsAnyLineBreakerOpen - && ( false == IsAnyConverterPresent || true == IsAnyConverterEnabled ) - && ( false == IsAnyCompressorPresent || true == IsAnyCompressorEnabled ) - // the ai goes back to preparing the engine and switches that converter on, the human driver may run with it off - && ( false == AIControllFlag || false == islocalconverterswitchoff ); -} - -void -TController::control_wheelslip() { - // a start that has slipped once keeps the sand on until the train is under way. with the sand off as soon as the - // wheels grip again, the next notch slips again, and a heavy train on poor rails slips, grips and snatches over - // and over, and may never get going (#187). a vehicle without sand starts as before - auto const velocity { std::abs( mvOccupied->Vel ) }; - if( mvControlling->SlippingWheels - && velocity < EU07_AI_SANDEDSTARTVELOCITY - && false == mvControlling->IsMainCtrlNoPowerPos() - && mvControlling->Sand > 0.0 ) { - bSandedStart = true; - } - else if( velocity >= EU07_AI_SANDEDSTARTVELOCITY - || ( velocity < EU07_AI_NOMOVEMENT && VelDesired == 0.0 ) ) { - bSandedStart = false; - } - // wheel slip - if( mvControlling->SlippingWheels ) { - cue_action( driver_hint::sandingon ); // piasku! - if( false == bSandedStart ) { - cue_action( driver_hint::tractiveforcedecrease ); - cue_action( driver_hint::antislip ); - } - else if( ElapsedTime - fSandedStartDecreaseTime >= 1.0 ) { - // starting, a step down at a time, and no anti-slip brake: taking the power off at once and braking the - // locomotive brings a heavy train that has just got moving to a stand again, and the start begins anew - cue_action( driver_hint::tractiveforcedecrease ); - fSandedStartDecreaseTime = ElapsedTime; - } - cue_action( driver_hint::brakingforcedecrease ); - ++iDriverFailCount; - } - else if( ( std::fabs( mvControlling->Im ) > 0.75 * mvControlling->ImaxHi ) - || ( bSandedStart && false == mvControlling->IsMainCtrlNoPowerPos() ) ) { - cue_action( driver_hint::sandingon ); // piaskujemy tory, coby się nie ślizgać - } - else { - // deactivate sandbox if we aren't slipping - if( mvControlling->SandDose ) { - cue_action( driver_hint::sandingoff ); - } - } -} - -void -TController::control_pantographs() { - - if( mvPantographUnit->EnginePowerSource.SourceType != TPowerSource::CurrentCollector ) { return; } - - if( false == mvPantographUnit->PantAutoValve - && mvOccupied->ScndPipePress > 4.3 ) { - // gdy główna sprężarka bezpiecznie nabije ciśnienie to można przestawić kurek na zasilanie pantografów z głównej pneumatyki - cue_action( driver_hint::pantographairsourcesetmain ); - } - - // uśrednione napięcie sieci: przy spadku poniżej wartości minimalnej opóźnić rozruch o losowy czas - fVoltage = 0.5 * (fVoltage + std::max( mvControlling->GetTrainsetHighVoltage(), mvControlling->PantographVoltage ) ); - if( fVoltage < mvControlling->EnginePowerSource.CollectorParameters.MinV && fActionTime >= PrepareTime ) { - // gdy rozłączenie WS z powodu niskiego napięcia - // jeśli czas oczekiwania nie został ustawiony, losowy czas oczekiwania przed ponownym załączeniem jazdy - fActionTime = -2.0 - Random(10); - } - - // the pantograph setup the .fiz suggests for shunting (AI: ShuntPantstate=, eu07/maszyna#461), 0 when there's none - // or the vehicle isn't shunting - auto const shuntpantographsetup { - OrderCurrentGet().HasAny( DriverOrder::shunt | DriverOrder::looseShunt ) ? - mvOccupied->AIHintShuntPantstate : - 0 }; - - // raise/lower pantographs as needed - auto const useregularpantographlayout { - pVehicle->Next(Coupling::control) == nullptr // standalone - || is_emu() // special case - || mvControlling->TrainType == train_type::et41 }; // special case - - if( mvOccupied->Vel > EU07_AI_NOMOVEMENT ) { - - if( fOverhead2 >= 0.0 || iOverheadZero ) { - // jeśli jazda bezprądowa albo z opuszczonym pantografem - cue_action( driver_hint::mastercontrollersetzerospeed ); - } - - if( fOverhead2 > 0.0 || iOverheadDown ) { - // jazda z opuszczonymi pantografami - if( mvPantographUnit->Pantographs[ end::front ].is_active ) { - cue_action( driver_hint::frontpantographvalveoff ); - } - if( mvPantographUnit->Pantographs[ end::rear ].is_active ) { - cue_action( driver_hint::rearpantographvalveoff ); - } - } - else { - // jeśli nie trzeba opuszczać pantografów - // TODO: check if faction alone reduces frequency enough - if( fActionTime > 0.0 ) { - if( shuntpantographsetup != 0 ) { - // shunting with the pantograph setup the .fiz suggests for it - control_pantographs_setup( shuntpantographsetup ); - } - else if( mvOccupied->AIHintPantstate == 0 ) { - // jazda na tylnym - if( iDirection >= 0 && useregularpantographlayout ) { - // jak jedzie w kierunku sprzęgu 0 - if( mvPantographUnit->PantRearVolt == 0.0 - // filter out cases with single _other_ working pantograph so we don't try to raise something we can't - && ( mvPantographUnit->PantographVoltage == 0.0 - || mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 1 ) ) { - cue_action( driver_hint::rearpantographvalveon ); - } - } - else { - // jak jedzie w kierunku sprzęgu 0 - if( mvPantographUnit->PantFrontVolt == 0.0 - // filter out cases with single _other_ working pantograph so we don't try to raise something we can't - && ( mvPantographUnit->PantographVoltage == 0.0 - || mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 1 ) ) { - cue_action( driver_hint::frontpantographvalveon ); - } - } - - if( mvOccupied->Vel > 5 && mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 1 ) { - // opuszczenie przedniego po rozpędzeniu się o ile jest więcej niż jeden - if (iDirection >= 0 && useregularpantographlayout) // jak jedzie w kierunku sprzęgu 0 - { // poczekać na podniesienie tylnego - if (mvPantographUnit->PantFrontVolt != 0.0 && mvPantographUnit->PantRearVolt != 0.0) - { // czy jest napięcie zasilające na tylnym? - cue_action(driver_hint::frontpantographvalveoff); // opuszcza od sprzęgu 0 - } - } - else - { // poczekać na podniesienie przedniego - if (mvPantographUnit->PantRearVolt != 0.0 && mvPantographUnit->PantFrontVolt != 0.0) - { // czy jest napięcie zasilające na przednim? - cue_action(driver_hint::rearpantographvalveoff); // opuszcza od sprzęgu 1 - } - } - } - - } - else { - // use suggested pantograph setup - if( mvOccupied->Vel > 5 ) { - auto const pantographsetup{ mvOccupied->AIHintPantstate }; - cue_action( - pantographsetup & 1 << 0 ? driver_hint::frontpantographvalveon : driver_hint::frontpantographvalveoff ); - cue_action( - pantographsetup & 1 << 1 ? driver_hint::rearpantographvalveon : driver_hint::rearpantographvalveoff ); - } - } - } - } - } - else if( shuntpantographsetup != 0 ) { - // shunting with the suggested setup, also while standing, and without raising more pantographs when idling - if( fOverhead2 <= 0.0 && iOverheadDown == 0 ) { - control_pantographs_setup( shuntpantographsetup ); - } - } - else { - if( !mvOccupied->AIHintPantUpIfIdle || IdleTime <= 45.0 || std::abs(fStopTime) <= 15.0 || mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo <= 1 ) - { - } - else - { - // spending a longer at a stop, raise also front pantograph - if (iDirection >= 0 && useregularpantographlayout) - { - // jak jedzie w kierunku sprzęgu 0 - if (mvPantographUnit->PantFrontVolt == 0.0) - { - cue_action(driver_hint::frontpantographvalveon, 5); // discard the hint if speed exceeds 5 km/h - } - } - else - { - if (mvPantographUnit->PantRearVolt == 0.0) - { - cue_action(driver_hint::rearpantographvalveon, 5); // discard the hint if speed exceeds 5 km/h - } - } - } - } -} - -// raises the pantographs of the suggested setup (bit 0: front, bit 1: rear) and lowers the others, these only once -// a pantograph of the setup collects the voltage, so the vehicle doesn't lose its power on the way -void -TController::control_pantographs_setup( int const Setup ) { - - auto const front { ( Setup & 1 << 0 ) != 0 }; - auto const rear { ( Setup & 1 << 1 ) != 0 }; - if( front ) { - cue_action( driver_hint::frontpantographvalveon ); - } - if( rear ) { - cue_action( driver_hint::rearpantographvalveon ); - } - if( auto const setuplive { ( front && mvPantographUnit->PantFrontVolt != 0.0 ) || ( rear && mvPantographUnit->PantRearVolt != 0.0 ) }; - false == setuplive ) { - return; - } - if( false == front ) { - cue_action( driver_hint::frontpantographvalveoff ); - } - if( false == rear ) { - cue_action( driver_hint::rearpantographvalveoff ); - } -} - -void -TController::control_horns( double const Timedelta ) { - // horn control - if( fWarningDuration > 0.0 ) { - // jeśli pozostało coś do wytrąbienia trąbienie trwa nadal - if( mvOccupied->WarningSignal == 0 ) { - cue_action( driver_hint::hornon, 1 ); // low tone horn by default - } - } - else { - if( mvOccupied->WarningSignal != 0 ) { - cue_action( driver_hint::hornoff ); // a tu się kończy - } - } - if( mvOccupied->Vel > EU07_AI_MOVEMENT ) { - // jesli jedzie, można odblokować trąbienie, bo się wtedy nie włączy - drivingFlags.startHornDone = false; // zatrąbi dopiero jak następnym razem stanie - drivingFlags.startHorn = true; // i trąbić przed następnym ruszeniem - } - - if( true == drivingFlags.startHornNow - && true == Ready - && true == iEngineActive - && mvControlling->MainCtrlPowerPos() > 0 ) { - // uruchomienie trąbienia przed ruszeniem - fWarningDuration = 0.3; // czas trąbienia - cue_action( driver_hint::hornon, pVehicle->iHornWarning ); // wysokość tonu (2=wysoki) - drivingFlags.startHornDone = true; // nie trąbić aż do ruszenia - drivingFlags.startHornNow = false; // trąbienie zostało zorganizowane - } -} - -void -TController::control_security_system( double const Timedelta ) { - if( mvOccupied->SecuritySystem.is_cabsignal_blinking() && mvOccupied->SecuritySystem.has_separate_acknowledge()) { - // jak zadziałało SHP - if( false == is_emu() - && mvOccupied->DirActive == 0 ) { - cue_action( driver_hint::directionforward ); - } - cue_action( driver_hint::shpsystemreset ); // to skasuj - if( BrakeCtrlPosition == 0 // TODO: verify whether it's 0 in all vehicle types - && AccDesired > 0.0 - && mvOccupied->SecuritySystem.is_braking() ) { - cue_action( driver_hint::trainbrakerelease ); - } - } - - if( mvOccupied->SecuritySystem.is_blinking() ) { - // jak zadziałało CA/SHP - if( false == is_emu() - && mvOccupied->DirActive == 0 ) { - cue_action( driver_hint::directionforward ); - } - cue_action( driver_hint::securitysystemreset ); // to skasuj - if( BrakeCtrlPosition == 0 // TODO: verify whether it's 0 in all vehicle types - && AccDesired > 0.0 - && mvOccupied->SecuritySystem.is_braking() ) { - cue_action( driver_hint::trainbrakerelease ); - } - } - // basic emergency stop handling, while at it - if( true == mvOccupied->RadioStopFlag // radio-stop - && mvOccupied->Vel < 0.01 // and actual stop - && true == mvOccupied->Radio ) { // and we didn't touch the radio yet - // turning off the radio should reset the flag, during security system check - if( m_radiocontroltime > 5.0 ) { // arbitrary delay between stop and disabling the radio - cue_action( driver_hint::radiooff ); - } - else { - m_radiocontroltime += Timedelta; - } - } - if( iEngineActive - && ( false == mvOccupied->Radio || false == mvOccupied->RadioFuse ) - && false == mvOccupied->RadioStopFlag ) { - // otherwise if it's safe to do so, turn the radio back on - // arbitrary 5 sec delay before switching radio back on - m_radiocontroltime = std::min( m_radiocontroltime, 5.0 ); - if( m_radiocontroltime < 0.0 ) { - // hint at whichever of the two is open, the radio's switch or the cut-off in its power supply - if( false == mvOccupied->RadioFuse ) { - cue_action( driver_hint::radiofuseon ); - } - if( false == mvOccupied->Radio ) { - cue_action( driver_hint::radioon ); - } - } - else { - m_radiocontroltime -= Timedelta; - } - } -} - -void -TController::control_handles() { - - switch( mvControlling->EngineType ) { - case TEngineType::ElectricSeriesMotor: { - // styczniki liniowe rozłączone yBARC - if( false == mvControlling->StLinFlag - && false == mvControlling->DelayCtrlFlag - && mvControlling->MainCtrlPowerPos() > 1 ) { - cue_action( driver_hint::mastercontrollersetzerospeed ); - } - // if the power station is heavily burdened drop down to series mode to reduce the load - auto const useseriesmodevoltage { - std::lerp( - mvControlling->EnginePowerSource.CollectorParameters.MinV, - mvControlling->EnginePowerSource.CollectorParameters.MaxV, - IsHeavyCargoTrain ? 0.35 : 0.40 ) }; - - if( fVoltage <= useseriesmodevoltage ) { - cue_action( driver_hint::mastercontrollersetseriesmode ); - } - // sanity check - if( false == Ready - && mvControlling->MainCtrlPowerPos() > 1 ) { - cue_action( driver_hint::mastercontrollersetzerospeed ); - } - break; - } - case TEngineType::DieselElectric: { - // styczniki liniowe rozłączone yBARC - if( false == mvControlling->StLinFlag - && false == mvControlling->DelayCtrlFlag - && mvControlling->MainCtrlPowerPos() > 1 ) { - cue_action( driver_hint::mastercontrollersetzerospeed ); - } - // sanity check - if( false == Ready - && mvControlling->MainCtrlPowerPos() > 1 ) { - cue_action( driver_hint::mastercontrollersetzerospeed ); - } - break; - } - default: { - break; - } } // enginetype -} - -// moves the light preset selector to the position matching the lights set directly by the AI, -// otherwise the next SetLights() call (e.g. from CheckVehicles()) reverts them to the untouched selector position -void -TController::sync_lights_selector() { - - if( mvOccupied->LightsPosNo <= 0 ) { return; } - - auto const *headvehicle { pVehicles[ end::front ] }; - if( headvehicle == nullptr ) { return; } - // same choice of the light table as in TDynamicObject::SetLights() - auto const lightstable { ( mvOccupied->CabOccupied * pVehicle->DirectionGet() >= 0 ? end::front : end::rear ) }; - // same choice of the lit vehicle end as in TDynamicObject::RaLightsSet() - auto const headend { ( headvehicle->iDirection > 0 ? end::front : end::rear ) }; - auto const position { handover::light_selector_position( - *mvOccupied, lightstable, headvehicle->MoverParameters->iLights[ headend ], headvehicle->LightList( headend ) ) }; - if( position == mvOccupied->LightsPos ) { return; } - - mvOccupied->LightsPos = position; - // visual feedback - auto *train { simulation::Trains.find( pVehicle->name() ) }; - if( train != nullptr ) { - train->ggLightsButton.PutValue( static_cast( position - 1 ) ); - } -} - -// re-applies the headlight dimmer state after the AI handed the vehicle over to the human driver, -// moving the dimmer out of the off position if it'd hide the head lights set by the AI -void -TController::sync_lights_dimmer() { - - if( mvOccupied->dimPositions.empty() ) { return; } - - auto const *headvehicle { pVehicles[ end::front ] }; - auto const headend { ( headvehicle != nullptr && headvehicle->iDirection > 0 ? end::front : end::rear ) }; - auto const headlightson { - headvehicle != nullptr - && ( headvehicle->MoverParameters->iLights[ headend ] & ( light::headlight_left | light::headlight_right | light::headlight_upper ) ) != 0 }; - - auto const position { handover::dimmer_position( *mvOccupied, headlightson ) }; - if( position != mvOccupied->modernDimmerPosition ) { - mvOccupied->modernDimmerPosition = position; - // visual feedback - auto *train { simulation::Trains.find( pVehicle->name() ) }; - if( train != nullptr ) { - train->ggModernLightDimSw.PutValue( static_cast( position ) ); - } - } - if( position < 0 || position >= static_cast( mvOccupied->dimPositions.size() ) ) { return; } // SetLightDimmings() doesn't check the range - pVehicle->SetLightDimmings(); -} - -// activate consist lamp codes -void -TController::control_lights() { - - if( is_train() ) { - // jeśli jazda pociągowa - if( true == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { - // head lights - if( m_lighthints[ end::front ] == -1 ) { - cue_action( driver_hint::headcodepc1 ); - } - else if( m_lighthints[ end::front ] == ( light::redmarker_left | light::headlight_right | light::headlight_upper ) ) { - cue_action( driver_hint::headcodepc2 ); - } - else { - // custom light pattern - if( AIControllFlag ) { - pVehicles[ end::front ]->RaLightsSet( m_lighthints[ end::front ], -1 ); - } - } - // tail lights - if( m_lighthints[ end::rear ] == -1 ) { - cue_action( driver_hint::headcodepc5 ); - } - else { - if( AIControllFlag ) { - pVehicles[ end::rear ]->RaLightsSet( -1, m_lighthints[ end::rear ] ); - } - } - } - // for shunting mode - else if( OrderCurrentGet() & ( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect ) ) { - cue_action( driver_hint::headcodetb1 ); - } - } - else if( is_car() ) { - Lights( - light::headlight_left | light::headlight_right, - light::redmarker_left | light::redmarker_right ); - } -} - -void -TController::control_compartment_lights() { - // compartment lights - if( mvOccupied->CompartmentLights.start_type != start_t::manual ) { return; } - - auto const currentlightstate { mvOccupied->CompartmentLights.is_enabled }; - auto const lightlevel { Global.fLuminance * ConsistShade }; - auto const desiredlightstate{ ( - currentlightstate ? - lightlevel < 0.40 : // turn off if lighting level goes above 0.4 - lightlevel < 0.35 ) }; // turn on if lighting level goes below 0.35 - if( desiredlightstate != currentlightstate ) { - cue_action( desiredlightstate ? driver_hint::consistlightson : driver_hint::consistlightsoff ); - } -} - -void -TController::control_doors() { - - if( false == doors_open() ) { return; } - // jeżeli jedzie - // nie zamykać drzwi przy drganiach, bo zatrzymanie na W4 akceptuje niewielkie prędkości - if( mvOccupied->Vel > EU07_AI_MOVEMENT ) { - Doors( false ); - return; - } - // HACK: crude way to deal with automatic door opening on W4 preventing further ride - // for human-controlled vehicles with no door control and dynamic brake auto-activating with door open - // TODO: check if this situation still happens and the hack is still needed - if( false == AIControllFlag && (mvControlling->EngineType == TEngineType::DieselEngine ? mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0 : mvControlling->MainCtrlPowerPos() > 0) ) { - // for diesel engines react when engine is put past idle revolutions - // for others straightforward master controller check - Doors(false); - return; - } -} - -void -TController::UpdateCommand() { - - if( mvOccupied->CommandIn.Command != VehicleCommand::none && false == mvOccupied->RunInternalCommand() ) { - // rozpoznaj komende bo lokomotywa jej nie rozpoznaje - RecognizeCommand(); // samo czyta komendę wstawioną do pojazdu? - } -} - -void -TController::UpdateNextStop() { - - if( fLastStopExpDist > 0.0 - && mvOccupied->DistCounter > fLastStopExpDist ) { - // zaktualizować wyświetlanie rozkładu - TrainParams.StationStart = TrainParams.StationIndex; - fLastStopExpDist = -1.0; // usunąć licznik - if( true == m_makenextstopannouncement ) { - announce( announcement_t::next ); - m_makenextstopannouncement = false; // keep next stop announcements suppressed until another scheduled stop - } - } -} - -void -TController::determine_braking_distance() { - // przybliżona droga hamowania - // NOTE: we're ensuring some minimal braking distance to reduce ai flipping states between starting and braking - auto const velceil { std::max( 2.0, std::ceil( mvOccupied->Vel ) ) }; - fBrakeDist = fDriverBraking * velceil * ( 40.0 + velceil ); - if( fMass > 1000000.0 ) { - // korekta dla ciężkich, bo przeżynają - da to coś? - fBrakeDist *= 2.0; - } - if( -fAccThreshold > 0.05 - && mvOccupied->CategoryFlag == 1 ) { - fBrakeDist = velceil * velceil / 25.92 / -fAccThreshold; - } - if( mvOccupied->BrakeDelayFlag == bdelay_G ) { - // dla nastawienia G koniecznie należy wydłużyć drogę na czas reakcji - fBrakeDist += 2 * velceil; - } - if( mvOccupied->Vel > 15.0 - && mvControlling->EngineType == TEngineType::ElectricInductionMotor - && is_emu() ) { - // HACK: make the induction motor powered EMUs start braking slightly earlier - fBrakeDist += 10.0; - } -/* - // take into account effect of gravity (but to stay on safe side of calculations, only downhill) - if( fAccGravity > 0.025 ) { - fBrakeDist *= ( 1.0 + fAccGravity ); - // TBD: use version which shortens route going uphill, too - //fBrakeDist = std::max( fBrakeDist, fBrakeDist * ( 1.0 + fAccGravity ) ); - } -*/ -} - -void -TController::scan_route( double const Range ) { - - TableCheck( Range ); -} - -// check for potential collisions -void -TController::scan_obstacles( double const Range ) { - // HACK: vehicle order in the consist is based on intended travel direction - // if our actual travel direction doesn't match that, we should be scanning from the other end of the consist - // we cast to int to avoid getting confused by microstutters - auto *frontvehicle { pVehicles[ ( static_cast( mvOccupied->V ) * iDirection >= 0 ? end::front : end::rear ) ] }; - - int routescandirection; - // for moving vehicle determine heading from velocity; for standing fall back on the set direction - if( std::abs(frontvehicle->MoverParameters->V) > 0.5 ? // ignore potential micro-stutters in oposite direction during "almost stop" - frontvehicle->MoverParameters->V > 0.0 : - pVehicle->DirectionGet() == frontvehicle->DirectionGet() ? iDirection >= 0 : iDirection <= 0 ) { - // towards coupler 0 - routescandirection = end::front; - } - else { - // towards coupler 1 - routescandirection = end::rear; - } -/* - if( pVehicle->MoverParameters->CabOccupied < 0 ) { - // flip the scan direction in the rear cab - routescandirection ^= routescandirection; - } -*/ - Obstacle = neighbour_data(); - auto const obstaclescanrange { std::max( is_car() ? 250.0 : 1000.0, Range ) }; - auto const lookup { frontvehicle->find_vehicle( routescandirection, obstaclescanrange ) }; - - if( std::get( lookup ) == true ) { - - Obstacle.vehicle = std::get( lookup ); - Obstacle.vehicle_end = std::get( lookup ); - Obstacle.distance = std::get( lookup ); - - if( Obstacle.distance < ( is_car() ? 50 : 100 ) ) { - // at short distances (re)calculate range between couplers directly - Obstacle.distance = TMoverParameters::CouplerDist( frontvehicle->MoverParameters, Obstacle.vehicle->MoverParameters ); - } - } -} - -void -TController::determine_proximity_ranges() { - // ustalenie dystansów w pozostałych przypadkach - switch (SingleOrder(OrderCurrentGet())) - { - case DriverOrder::connect: { - // podłączanie do składu - if (drivingFlags.connect) { - // jeśli stanął już blisko, unikając zderzenia i można próbować podłączyć - fMinProximityDist = -1.0; - fMaxProximityDist = 0.0; //[m] dojechać maksymalnie - fVelPlus = 1.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania - fVelMinus = 0.5; // margines prędkości powodujący załączenie napędu - } - else { - // jak daleko, to jazda jak dla Shunt na kolizję - fMinProximityDist = 2.0; - fMaxProximityDist = 5.0; //[m] w takim przedziale odległości powinien stanąć - fVelPlus = 2.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania - fVelMinus = 1.0; // margines prędkości powodujący załączenie napędu - } - break; - } - case DriverOrder::disconnect: { - // 20.07.03 - manewrowanie wagonami - fMinProximityDist = 1.0; - fMaxProximityDist = 10.0; //[m] - fVelPlus = 1.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania - fVelMinus = 0.5; // margines prędkości powodujący załączenie napędu - break; - } - case DriverOrder::shunt: { - // na jaką odleglość i z jaką predkością ma podjechać - // TODO: test if we can use the distances calculation from obey_train - fMinProximityDist = std::min( 5 + iVehicles, 25 ); - fMaxProximityDist = std::min( 10 + iVehicles, 50 ); - // HACK: modern vehicles might brake slower at low speeds, increase safety margin as crude counter - if( mvControlling->EIMCtrlType > 0 ) { - fMinProximityDist += 5.0; - fMaxProximityDist += 5.0; - } - // take into account weather conditions - if (Global.FrictionWeatherFactor < 1.f - && iVehicles > 1 ) { - fMinProximityDist += 5.0; - fMaxProximityDist += 5.0; - } - fVelPlus = 2.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania - // margines prędkości powodujący załączenie napędu - // były problemy z jazdą np. 3km/h podczas ładowania wagonów - fVelMinus = std::min( 0.1 * fShuntVelocity, 3.0 ); - break; - } - case DriverOrder::looseShunt: { - fMinProximityDist = -1.0; - fMaxProximityDist = 0.0; //[m] dojechać maksymalnie - fVelPlus = 2.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania - fVelMinus = 0.5; // margines prędkości powodujący załączenie napędu - break; - } - case DriverOrder::obeyTrain: { - // na jaka odleglosc i z jaka predkoscia ma podjechac do przeszkody - // jeśli pociąg - if( is_train() ) { - auto const [ minproximity, maxproximity ] { train_proximity_margins( IsAtPassengerStop ) }; - fMinProximityDist = minproximity; - fMaxProximityDist = maxproximity; - - if( drivingFlags.late ) { - // jeśli spóźniony, to gna - fVelMinus = 1.0; - // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania - fVelPlus = 5.0; - } - else { - // gdy nie musi się sprężać - // margines prędkości powodujący załączenie napędu; min 1.0 żeby nie ruszał przy 0.1 - fVelMinus = std::clamp( std::round( 0.05 * VelDesired ), 1.0, 5.0 ); - // normalnie dopuszczalne przekroczenie to 5% prędkości ale nie więcej niż 5km/h - // bottom margin raised to 2 km/h to give the AI more leeway at low speed limits - fVelPlus = std::clamp( std::ceil( 0.05 * VelDesired ), 2.0, 5.0 ); - } - } - // samochod (sokista też) - else { - fMinProximityDist = std::max( 3.5, mvOccupied->Vel * 0.2 ); - fMaxProximityDist = std::max( 9.5, mvOccupied->Vel * 0.375 ); //[m] - if( Global.FrictionWeatherFactor < 1.f ) { - // take into account weather conditions - fMinProximityDist += 0.75; - fMaxProximityDist += 0.75; - } - // margines prędkości powodujący załączenie napędu - fVelMinus = 2.0; - // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania - fVelPlus = std::min( 10.0, mvOccupied->Vel * 0.1 ); - } - break; - } - case DriverOrder::bank: { - // TODO: implement - break; - } - default: { - fMinProximityDist = 5.0; - fMaxProximityDist = 10.0; //[m] - fVelPlus = 2.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania - fVelMinus = 5.0; // margines prędkości powodujący załączenie napędu - } - } // switch OrderList[OrderPos] -} - -void -TController::check_departure() { - - if(false == OrderCurrentGet().HasAny( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank | DriverOrder::connect ) ) { return; } - // odjechać sam może tylko jeśli jest w trybie jazdy - // automatyczne ruszanie po odstaniu albo spod SBL - if( VelSignal == 0.0 - && WaitingTime > 0.0 - && mvOccupied->RunningTrack.Velmax != 0.0 ) { - // jeśli stoi, a upłynął czas oczekiwania i tor ma niezerową prędkość - if( OrderCurrentGet() & (DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank) - && drivingFlags.stopHere ) { - // zakaz ruszania z miejsca bez otrzymania wolnej drogi - WaitingTime = -WaitingExpireTime; - } - else { - if( mvOccupied->CategoryFlag & 1 ) { // jeśli pociąg - PrepareDirection(); // zmieni ustawiony kierunek - SetVelocity( 20, 20 ); // jak się nastał, to niech jedzie 20km/h - WaitingTime = 0.0; - fWarningDuration = 1.5; // a zatrąbić trochę - } - else { // samochód ma stać, aż dostanie odjazd, chyba że stoi przez kolizję - if( eStopReason == stopBlock - && Obstacle.distance > fDriverDist ) { - PrepareDirection(); // zmieni ustawiony kierunek - SetVelocity( -1, -1 ); // jak się nastał, to niech jedzie - WaitingTime = 0.0; - } - } - } - } - else if( VelSignal == 0.0 && VelNext > 0.0 && mvOccupied->Vel < 1.0 && (false == iCoupler.Empty() || ( false == drivingFlags.stopHere )) ) { - // Ra: tu jest coś nie tak, bo bez tego warunku ruszało w manewrowym !!!! - SetVelocity(VelNext, VelNext, stopSem); // omijanie SBL - } -} - -// verify progress of load exchange -void -TController::check_load_exchange() { - - ExchangeTime = 0.f; - DoesAnyDoorNeedOpening = false; - - if( fStopTime > 0 ) { return; } - - // czas postoju przed dalszą jazdą (np. na przystanku) - auto *vehicle { pVehicles[ end::front ] }; - while( vehicle != nullptr ) { - auto const vehicleexchangetime { vehicle->LoadExchangeTime() }; - DoesAnyDoorNeedOpening |= vehicleexchangetime > 0 && vehicle->LoadExchangeSpeed() == 0; - ExchangeTime = std::max( ExchangeTime, vehicleexchangetime ); - vehicle = vehicle->Next(); - } - - if( pVehicle->DirectionGet() != m_lastexchangedirection ) { - // generally means the ai driver moved to the opposite end of the consist - // TODO: investigate whether user playing with the reverser can mess this up - auto const left { m_lastexchangedirection > 0 ? 1 : 2 }; - auto const right { 3 - left }; - m_lastexchangeplatforms = - ( ( m_lastexchangeplatforms & left ) != 0 ? right : 0 ) - + ( ( m_lastexchangeplatforms & right ) != 0 ? left : 0 ); - m_lastexchangedirection = pVehicle->DirectionGet(); - } - if( false == TrainParams.IsMaintenance() - && ( false == drivingFlags.doorOpened - || true == DoesAnyDoorNeedOpening ) ) { - drivingFlags.doorOpened = true; // nie wykonywać drugi raz - remove_hint( driver_hint::doorleftopen ); - remove_hint( driver_hint::doorrightopen ); - Doors( true, m_lastexchangeplatforms ); - } -} - -void -TController::UpdateChangeDirection() { - // TODO: rework into driver mode independent routine - if( false == OrderCurrentGet().HasAll(DriverOrder::changeDirection) ) { return; } - - if( true == AIControllFlag && mvOccupied->Vel < EU07_AI_NOMOVEMENT ) { - // sprobuj zmienic kierunek (może być zmieszane z jeszcze jakąś komendą) - // jeśli się zatrzymał, to zmieniamy kierunek jazdy, a nawet kabinę/człon - Activation(); // ustawienie zadanego wcześniej kierunku i ewentualne przemieszczenie AI - // Change_direction (tylko dla AI) - } - // shared part of the routine, implement if direction matches what was requested - if( mvOccupied->Vel < EU07_AI_NOMOVEMENT - && iDirection == iDirectionOrder ) { - // NOTE: we can't be sure there's a visible signal within scan range after direction change - // which would normally overwrite the old limit, so we reset signal value manually here - VelSignal = -1; - VelSignalNext = -1; - PrepareEngine(); - JumpToNextOrder(); // następnie robimy, co jest do zrobienia (Shunt albo Obey_train) - if( OrderCurrentGet() & (DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect) && false == drivingFlags.stopHere ) { - // jeśli dalej mamy manewry - // o ile nie ma stać w miejscu, - // jechać od razu w przeciwną stronę i nie trąbić z tego tytułu: - drivingFlags.startHorn = false; - SetVelocity(fShuntVelocity, fShuntVelocity); - } - } -} - -void -TController::UpdateLooseShunt() { - // when loose shunting try to detect situations where engaged brakes in a consist to be pushed prevent movement - // TODO: run also for potential settings-based virtual assistant - auto const autobrakerelease { ( true == AIControllFlag ) }; - - if( autobrakerelease - && Obstacle.distance < 1.0 - && AccDesired > 0.1 - && mvOccupied->Vel < 1.0 ) { - - auto *vehicle { Obstacle.vehicle }; - auto const direction { ( vehicle->Prev() != nullptr ? end::front : end::rear ) }; - while( vehicle != nullptr ) { - if( vehicle->MoverParameters->BrakePress > 0.2 ) { - vehicle->MoverParameters->BrakeLevelSet( 0 ); // hamulec na zero, aby nie hamował - vehicle->MoverParameters->BrakeReleaser( 1 ); // wyluzuj pojazd, aby dało się dopychać - } - // NOTE: we trust the consist to be arranged in a valid chain - // TBD, TODO: traversal direction validation? - vehicle = direction == end::front ? vehicle->Prev() : vehicle->Next(); - } - } -} - -void -TController::UpdateObeyTrain() { - - UpdateNextStop(); - - if( drivingFlags.guardSignal - && VelDesired > 0.0 ) { - // komunikat od kierownika tu, bo musi być wolna droga i odczekany czas stania - drivingFlags.guardSignal = false; // tylko raz nadać - drivingFlags.guardOpenDoor = false; // nie trzeba już otwierać drzwi - if( false == tsGuardSignal.empty() ) { - tsGuardSignal.stop(); - // w zasadzie to powinien mieć flagę, czy jest dźwiękiem radiowym, czy bezpośrednim - // albo trzeba zrobić dwa dźwięki, jeden bezpośredni, słyszalny w - // pobliżu, a drugi radiowy, słyszalny w innych lokomotywach - // na razie zakładam, że to nie jest dźwięk radiowy, bo trzeba by zrobić - // obsługę kanałów radiowych itd. - if( iGuardRadio == 0 ) { - // jeśli nie przez radio - tsGuardSignal.owner( pVehicle ); - // place virtual conductor some distance away - tsGuardSignal.offset( { pVehicle->MoverParameters->Dim.W * -0.75f, 1.7f, std::min( -20.0, -0.2 * fLength ) } ); - tsGuardSignal.play( sound_flags::exclusive ); - // NOTE: we can't rely on is_playing() check as sound playback is based on distance from local camera - fActionTime = -5.0; // niech trochę potrzyma - } - else { - // radio message - tsGuardSignal.owner( pVehicle ); -/* - tsGuardSignal.offset( { 0.f, 2.f, pVehicle->MoverParameters->Dim.L * 0.4f * ( pVehicle->MoverParameters->CabOccupied < 0 ? -1 : 1 ) } ); - tsGuardSignal.play( sound_flags::exclusive ); -*/ - simulation::radio_message( &tsGuardSignal, iGuardRadio ); - // NOTE: we can't rely on is_playing() check as sound playback is based on distance from local camera - fActionTime = -5.0; // niech trochę potrzyma - } - } - } -} - -void -TController::UpdateConnect() { - // podłączanie do składu - if (drivingFlags.connect) { - // sprzęgi sprawdzamy w pierwszej kolejności, bo jak połączony, to koniec - auto *vehicle { iCouplingVehicle.value().first }; - auto const couplingend { iCouplingVehicle.value().second }; - auto *vehicleparameters { vehicle->MoverParameters }; - auto const &neighbour { vehicleparameters->Neighbours[ couplingend ] }; - // vehicles which can't share their control get coupled without the control connection (eu07/maszyna#520) - auto expectedcoupling { iCoupler }; - if( neighbour.vehicle != nullptr ) { - auto const neighbourend { neighbour.vehicle_end != 2 ? neighbour.vehicle_end : vehicleparameters->Couplers[ couplingend ].ConnectedNr }; - expectedcoupling = vehicleparameters->CompatibleCoupling( couplingend, *neighbour.vehicle->MoverParameters, neighbourend, iCoupler ); - } - if( vehicleparameters->Couplers[ couplingend ].CouplingFlag != expectedcoupling ) { - if( neighbour.vehicle != nullptr && neighbour.distance < 10 ) { - // check whether we need to attach coupler adapter - auto coupleriscompatible{true}; - auto const &coupler{vehicleparameters->Couplers[couplingend]}; - if (coupler.type() != TCouplerType::Automatic) - { - auto const &othercoupler = neighbour.vehicle->MoverParameters->Couplers[(neighbour.vehicle_end != 2 ? neighbour.vehicle_end : coupler.ConnectedNr)]; - if (othercoupler.type() == TCouplerType::Automatic) - { - coupleriscompatible = false; - cue_action(driver_hint::couplingadapterattach, couplingend); - } - } - // próba podczepienia - if ((AIControllFlag || Global.AITrainman) && coupleriscompatible && neighbour.distance < 2) - { - vehicleparameters->Attach(couplingend, neighbour.vehicle_end, neighbour.vehicle->MoverParameters, iCoupler); - } - } - } - // NOTE: no else as the preceeding block can potentially establish expected connection - if( vehicleparameters->Couplers[ couplingend ].CouplingFlag == expectedcoupling ) { - // jeżeli został podłączony - CheckVehicles( DriverOrder::connect ); // sprawdzić światła nowego składu - - iCoupler = {}; // dalsza jazda manewrowa już bez łączenia - iCouplingVehicle.reset(); - drivingFlags.connect = false; // zdjęcie flagi doczepiania - JumpToNextOrder( true ); // wykonanie następnej komendy - } - } // moveConnect - else { - // początek podczepiania, z wyłączeniem sprawdzania fTrackBlock - if( Obstacle.distance <= 20.0 && !iCouplingVehicle ) { - // write down which vehicle should be coupled with the target consist, - // so we don't lose track of it if the user does something unexpected - iCouplingVehicle = {pVehicles[end::front], (pVehicles[end::front]->DirectionGet() > 0 ? end::front : end::rear)}; - drivingFlags.connect = true; - } - } -} - -void -TController::GuardOpenDoor() { - if (drivingFlags.guardOpenDoor) { - auto *vehicle{ pVehicles[end::front] }; - while (vehicle != nullptr && vehicle->MoverParameters->Doors.range == 0) { - vehicle = vehicle->Next(); - } - if (vehicle != nullptr && vehicle->MoverParameters->Doors.range > 0) { - auto const lewe = vehicle->DirectionGet() > 0 ? 1 : 2; - auto const prawe = 3 - lewe; - if (m_lastexchangeplatforms & lewe) { - vehicle->MoverParameters->OperateDoors(side::left, true, range_t::local); - } - if (m_lastexchangeplatforms & prawe) { - vehicle->MoverParameters->OperateDoors(side::right, true, range_t::local); - } - } - else { - drivingFlags.guardOpenDoor = false; - } - } -} - -int -TController::unit_count( int const Threshold ) const { - - auto *vehicle { pVehicle }; - auto unitcount { 1 }; - do { - auto const decoupledend{ ( vehicle->DirectionGet() > 0 ? // numer sprzęgu od strony czoła składu - end::rear : - end::front ) }; - auto const coupling { vehicle->MoverParameters->Couplers[ decoupledend ].CouplingFlag }; - if( coupling == Coupling::none ) { - break; - } - // jeżeli sprzęg zablokowany to liczymy człony jako jeden - if( false == coupling.HasAny( Coupling::permanent ) ) { - ++unitcount; - } - vehicle = vehicle->Next(); - } while( unitcount < Threshold ); - - return unitcount; -} - -void -TController::UpdateDisconnect() { - - if( iVehicleCount >= 0 ) { - // early test for human drivers, who might disregard the proper procedure, or perform it before they receive the order to - if( false == AIControllFlag && unit_count(iVehicleCount + 2) <= iVehicleCount + 1 ) { - // iVehicleCount = 0 means the consist should be reduced to (1) leading unit, thus we increase our test values by 1 - iVehicleCount = -2; // odczepiono, co było do odczepienia - return; // we'll wrap up the procedure on the next update beat - } - // regular uncoupling procedure, performed by ai and naively expected from the human drivers - // 3rd stage: change direction, compress buffers and uncouple - if( iDirection != iDirectionOrder ) { - cue_action( driver_hint::mastercontrollersetreverserunlock ); - cue_action( driver_hint::directionother ); - } - if( drivingFlags.press && iDirection == iDirectionOrder ) { - if( iVehicleCount >= 0 ) { - // zmieni się po odczepieniu - WriteLog( "Uncoupling [" + mvOccupied->Name + "]: actuating and compressing buffers..." ); - cue_action( driver_hint::independentbrakerelease ); - cue_action( driver_hint::bufferscompress ); - } - - WriteLog( "Uncoupling [" + mvOccupied->Name + "]: from " + ( mvOccupied->DirAbsolute > 0 ? "front" : "rear" ) ); - auto *decoupledvehicle { pVehicle }; // pojazd do odczepienia, w (pVehicle) siedzi AI - int decoupledend; // numer sprzęgu, który sprawdzamy albo odczepiamy - auto vehiclecount { iVehicleCount }; // ile wagonów ma zostać - // szukanie pojazdu do odczepienia - do { - decoupledend = decoupledvehicle->DirectionGet() > 0 ? // numer sprzęgu od strony czoła składu - end::front : - end::rear; - // jeżeli sprzęg zablokowany to liczymy człony jako jeden - if( decoupledvehicle->MoverParameters->Couplers[ decoupledend ].CouplingFlag & Coupling::permanent ) { - ++vehiclecount; - } - if( decoupledvehicle != pVehicle ) { - decoupledvehicle->MoverParameters->BrakeReleaser( 1 ); // wyluzuj pojazd, aby dało się dopychać - } - if( vehiclecount ) { // jeśli jeszcze nie koniec - decoupledvehicle = decoupledvehicle->Prev(); // kolejny w stronę czoła składu (licząc od tyłu), bo dociskamy - if( decoupledvehicle == nullptr ) { - vehiclecount = 0; // nie ma co dalej sprawdzać, odczepianie zakończone - } - } - } while( vehiclecount-- ); - if( decoupledvehicle == nullptr ) { - // no target, or already just virtual coupling - WriteLog( "Uncoupling [" + mvOccupied->Name + "]: didn't find anything to disconnect" ); - iVehicleCount = -2; // odczepiono, co było do odczepienia - } - else { - if( AIControllFlag || Global.AITrainman ) { - decoupledvehicle->Dettach( decoupledend ); - } - // tylko jeśli odepnie - if( decoupledvehicle->MoverParameters->Couplers[ decoupledend ].CouplingFlag == Coupling::none ) { - WriteLog( "Uncoupling [" + mvOccupied->Name + "]: uncoupled" ); - iVehicleCount = -2; - // update trainset state - CheckVehicles( DriverOrder::disconnect ); - // potentially remove coupler adapter -/* - if( decoupledvehicle->MoverParameters->Couplers[ decoupledend ].has_adapter() ) { - decoupledvehicle->remove_coupler_adapter( decoupledend ); - } -*/ - if( pVehicles[ end::front ]->MoverParameters->Couplers[ decoupledend ].has_adapter() ) { - cue_action( driver_hint::couplingadapterremove, decoupledend ); - } - } - } // a jak nie, to dociskać dalej - } - // 2nd stage: apply consist brakes and change direction - if( ( false == drivingFlags.press ) ) { - // store initial consist direction - if( !iDirectionBackup ) { - iDirectionBackup = iDirection; - } - if( false == IsConsistBraked ) { - WriteLog( "Uncoupling [" + mvOccupied->Name + "]: applying consist brakes..." ); - cue_action( driver_hint::trainbrakeapply ); - } - // jeśli w miarę został zahamowany (ciśnienie mniejsze niż podane na pozycji 3, zwyle 0.37) - else { - WriteLog( "Uncoupling [" + mvOccupied->Name + "]: direction change" ); -/* // TODO: test if this block is needed - if( BrakeSystem == TBrakeSystem::ElectroPneumatic ) { - // wyłączenie EP, gdy wystarczy (może nie być potrzebne, bo na początku jest) - mvOccupied->BrakeLevelSet( 0 ); - } -*/ - iDirectionOrder = -iDirection; // zmiana kierunku jazdy na przeciwny (dociskanie) - drivingFlags.press = true; // następnie będzie dociskanie - } - } - } // odczepianie - if( iVehicleCount < 0 ) { - // 4th stage: restore initial direction - if( iDirectionBackup ) { - iDirectionOrder = iDirectionBackup.value(); - iDirectionBackup.reset(); - } - if( iDirection != iDirectionOrder ) { - WriteLog( "Uncoupling [" + mvOccupied->Name + "]: second direction change" ); - cue_action( driver_hint::mastercontrollersetreverserunlock ); - cue_action( driver_hint::directionother ); // zmiana kierunku jazdy na właściwy - } - // 5th stage: clean up and move on to next order - if( iDirection == iDirectionOrder ) { - drivingFlags.press = false; // koniec dociskania - JumpToNextOrder( true ); // zmieni światła - TableClear(); // skanowanie od nowa - drivingFlags.startHorn = false; // bez trąbienia przed ruszeniem - } - } -} - -void -TController::handle_engine() { - // HACK: activate route scanning if an idling vehicle is activated by a human user - if( OrderCurrentGet() == DriverOrder::waitForOrders - && false == iEngineActive -// && ( false == AIControllFlag ) - && true == mvOccupied->Power24vIsAvailable ) { - OrderNext( DriverOrder::prepareEngine ); - } - // basic engine preparation - if( OrderCurrentGet() == DriverOrder::prepareEngine && PrepareEngine() ) { - // gotowy do drogi? - JumpToNextOrder(); - } - // engine state can potentially deteriorate in one of usual driving modes - if( OrderCurrentGet() & (DriverOrder::changeDirection | DriverOrder::connect | DriverOrder::disconnect | DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank) - && false == iEngineActive ) { - // jeśli coś ma robić to niech odpala do skutku - PrepareEngine(); - } -} - -void -TController::handle_orders() { - - switch (SingleOrder(OrderCurrentGet())) - { - case DriverOrder::releaseEngine: { - if( ReleaseEngine() ) { // zdana maszyna? - JumpToNextOrder(); - } - break; - } - case DriverOrder::obeyTrain: { - UpdateObeyTrain(); - break; - } - case DriverOrder::looseShunt: { - UpdateLooseShunt(); - break; - } - case DriverOrder::connect: { - UpdateConnect(); - break; - } - case DriverOrder::disconnect: { - UpdateDisconnect(); - break; - } - case DriverOrder::jumpToFirstOrder: { - if( OrderPos > 1 ) { - OrderPos = 1; // w zerowym zawsze jest czekanie - } - else { - ++OrderPos; - } -#if LOGORDERS - OrdersDump("Jump_to_first_order"); -#endif - break; - } - default: { - // special case, change_direction potentially received during partially completed coupling operation - // this is unlikely to happen for the AI, but can happen for a (slower) human user - if( drivingFlags.connect ) { - UpdateConnect(); - } - break; - } - } // switch OrderList[OrderPos] - UpdateChangeDirection(); -} - -// the stages of uncoupling: each one sets the speed for the next -void -TController::set_velocity_for_uncoupling() { - - if( iVehicleCount < 0 ) { - // 4th stage: restore initial direction - if( drivingFlags.press ) { - SetVelocity( 0, 0, stopJoin ); - } - return; - } - // 3rd stage: compress buffers and uncouple - if( drivingFlags.press && iDirection == iDirectionOrder ) { - SetVelocity( 2, 0 ); // jazda w ustawionym kierunku z prędkością 2 - return; - } - // 1st stage: bring it to stop - // 2nd stage: apply consist brakes and change direction - SetVelocity( 0, 0, stopJoin ); -} - -// uphill, the gradient alone brings a slow train to a stand within metres, far sooner than a released -// brake applies; so the train brake goes on while the train is coming to a stand, stays on while it -// stands, and is applied for real if the train has started to roll back -void -TController::hold_train_coming_to_stand_uphill() { - - if( ( false == is_train() ) - || ( false == OrderCurrentGet().HasAny(DriverOrder::obeyTrain) ) - || ( VelNext != 0.0 ) - || ( ActualProximityDist > fMaxProximityDist ) - || ( fAccGravity >= EU07_AI_UPHILLGRAVITY ) ) { - return; - } - auto const vel { DirectionalVel() }; - if( std::abs( vel ) < EU07_AI_NOMOVEMENT ) { - VelDesired = 0.0; - AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION ); - return; - } - if( ( vel < 0.0 ) - || ( ( vel < 5.0 ) && ( AccDesired < 0.0 ) ) - // rolling to a stand on the gradient alone, the brake has to be on its way before the train stops: - // once the time left to the stand is no longer than half of what the brake takes to apply, apply it; any - // sooner and the brake takes off more of the distance than the stop was planned with - || ( ( BrakeSystem == TBrakeSystem::Pneumatic ) - // not for a train that is short of where it is to stop and is to pull up further - && ( AccDesired <= 0.0 ) - && ( vel / 3.6 / -fAccGravity <= 0.5 * brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) { - // the gradient alone already slows the train down nearly this much; ask for enough on top of it that - // the brake is applied for sure, not held back by the margin against small corrections - AccDesired = std::min( AccDesired, fAccGravity - std::max( 0.15, fBrake_a0[ 0 ] ) - brake_increase_margin() ); - } -} - -void -TController::pick_optimal_speed( double const Range ) { - -// if( false == OrderCurrentGet().HasAny( Shunt | Loose_shunt | Obey_train | Bank | Connect | Disconnect | Change_direction ) ) { return; } - - // set initial velocity and acceleration values - SetDriverPsyche(); // ustawia AccPreferred (potrzebne tu?) - VelDesired = fVelMax; // wstępnie prędkość maksymalna dla pojazdu(-ów), będzie następnie ograniczana - AccDesired = AccPreferred; // AccPreferred wynika z osobowości mechanika - - // nie przekraczać rozkladowej - if( OrderCurrentGet().HasAny(DriverOrder::obeyTrain) - && TrainParams.TTVmax > 0.0 ) { - VelDesired = - min_speed( - VelDesired, - TrainParams.TTVmax ); - } - -// VelNext = VelDesired; // maksymalna prędkość wynikająca z innych czynników niż trajektoria ruchu - // HACK: -1 means we can pick up 0 speed limits in ( point.velnext > velnext ) tests aimed to find highest next speed, - // but also doubles as 'max speed' in min_speed tests, so it shouldn't interfere if we don't find any speed limits - VelNext = -1.0; - - // basic velocity and acceleration adjustments - // jeśli manewry, to ograniczamy prędkość - if( false == OrderCurrentGet().HasAny( DriverOrder::obeyTrain | DriverOrder::bank ) ) { // spokojne manewry - SetVelocity( fShuntVelocity, fShuntVelocity ); - VelDesired = - min_speed( - VelDesired, - fShuntVelocity ); - } - // uncoupling mode changes velocity/acceleration between stages - if( OrderCurrentGet().HasAny(DriverOrder::disconnect) ) { - set_velocity_for_uncoupling(); - } - - VelLimitLastDist = { VelDesired, -1 }; - SwitchClearDist = -1; - ActualProximityDist = Range; // funkcja Update() może pozostawić wartości bez zmian - - // if we're idling bail out early - if( false == is_active() ) { - VelDesired = 0.0; - VelNext = 0.0; - AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION ); - return; - } - - // Ra: odczyt (ActualProximityDist), (VelNext) i (AccPreferred) z tabelki prędkosci - check_route_ahead( Range ); - - check_departure(); - - // if ordered to turn off the vehicle, try to stop - if( true == OrderCurrentGet().HasAll(DriverOrder::releaseEngine) ) { - SetVelocity( 0, 0, stopSleep ); - } - // if ordered to change direction, try to stop - if( true == OrderCurrentGet().HasAll(DriverOrder::changeDirection) ) { - SetVelocity( 0, 0, stopDir ); - } - - adjust_desired_speed_for_obstacles(); - adjust_desired_speed_for_limits(); - adjust_desired_speed_for_target_speed( Range ); - adjust_desired_speed_for_current_speed(); - adjust_desired_speed_for_braking_test(); - - // Ra 2F1I: wyłączyć kiedyś to uśrednianie i przeanalizować skanowanie, czemu migocze - if( AccDesired > EU07_AI_NOACCELERATION ) { // hamowania lepeiej nie uśredniać - AccDesired = fAccDesiredAv = - 0.2 * AccDesired + - 0.8 * fAccDesiredAv; // uśrednione, żeby ograniczyć migotanie - } - if( VelDesired == 0.0 ) { - // Ra 2F1J: jeszcze jedna prowizoryczna łatka - AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION ); - } - - // last step sanity check, until the whole calculation is straightened out - AccDesired = std::min( AccDesired, AccPreferred ); - AccDesired = std::clamp( - AccDesired, - is_car() ? -2.0 : -0.9, - is_car() ? 2.0 : 0.9 ); - - // done last, so that none of the adjustments above, made for a train moving forward, can undo it - hold_train_coming_to_stand_uphill(); - - // if the route ahead is blocked we might need to head the other way - check_route_behind( 1000 ); // NOTE: legacy scan range value -} - -void -TController::adjust_desired_speed_for_obstacles() { - // prędkość w kierunku jazdy, ujemna gdy jedzie w przeciwną stronę niż powinien - auto const vel { DirectionalVel() }; - - if (VelDesired < 0.0) - VelDesired = fVelMax; // bo VelDesired<0 oznacza prędkość maksymalną - - // Ra: jazda na widoczność - if( Obstacle.distance < 5000 ) { - // mamy coś z przodu - // prędkość pojazdu z przodu (zakładając, że jedzie w tę samą stronę!!!) - auto const k { Obstacle.vehicle->MoverParameters->Vel }; - - if( k - vel < 5 ) { - // porównanie modułów prędkości [km/h] - // zatroszczyć się trzeba, jeśli tamten nie jedzie znacząco szybciej - if( Obstacle.distance < ActualProximityDist ) { - // the vehicle ahead, not the stop found by the scan, is what the train is now to stop short of - bStopTargetIsPassengerStop = false; - } - ActualProximityDist = std::min( - ActualProximityDist, - Obstacle.distance ); - - if( Obstacle.distance <= ( - mvOccupied->CategoryFlag & 2 ? - 100.0 : // cars - 250.0 ) ) { // others - // regardless of driving mode at close distance take precaution measures: - // match the other vehicle's speed or slow down if the other vehicle is stopped - VelDesired = - min_speed( - VelDesired, - std::max( - k, - mvOccupied->CategoryFlag & 2 ? - 40.0 : // cars - 20.0 ) ); // others - if( vel > VelDesired + fVelPlus ) { - // if going too fast force some prompt braking - AccPreferred = std::min( - mvOccupied->CategoryFlag & 2 ? -0.65 : // cars - -0.30, // others - AccPreferred ); - } - } - - double const distance = Obstacle.distance - fMaxProximityDist - fBrakeDist * 1.15; // odległość bezpieczna zależy od prędkości - if( distance < 0.0 ) { - // jeśli odległość jest zbyt mała - if( k < 10.0 ) // k - prędkość tego z przodu - { // jeśli tamten porusza się z niewielką prędkością albo stoi - // keep speed difference within a safer margin - VelDesired = std::floor( - min_speed( - VelDesired, - Obstacle.distance > 100 ? k + 20.0 : std::min(8.0, k + 4.0) ) ); - - if( OrderCurrentGet().HasAny( DriverOrder::connect | DriverOrder::looseShunt ) ) { - // jeśli spinanie, to jechać dalej - AccPreferred = std::min( 0.35, AccPreferred ); // nie hamuj - VelNext = std::floor( std::min( 8.0, k + 2.0 ) ); // i pakuj się na tamtego - } - else { - // a normalnie to hamować - VelNext = 0.0; - if( Obstacle.distance <= fMinProximityDist ) { - VelDesired = 0.0; - } - - if( mvOccupied->CategoryFlag & 1 - && OrderCurrentGet() & DriverOrder::obeyTrain ) { - // trains which move normally should try to stop at safe margin - ActualProximityDist -= fDriverDist; - } - } - } - else { - // jeśli oba jadą, to przyhamuj lekko i ogranicz prędkość - if( Obstacle.distance < ( - mvOccupied->CategoryFlag & 2 ? - fMaxProximityDist + 0.5 * vel : // cars - 2.0 * fMaxProximityDist + 2.0 * vel ) ) { //others - // jak tamten jedzie wolniej a jest w drodze hamowania - AccPreferred = std::min( -0.9, AccPreferred ); - VelNext = min_speed( std::round( k ) - 5.0, VelDesired ); - if( Obstacle.distance <= ( - mvOccupied->CategoryFlag & 2 ? - fMaxProximityDist : // cars - 2.0 * fMaxProximityDist ) ) { //others - // try to force speed change if obstacle is really close - VelDesired = VelNext; - } - } - } - ReactionTime = mvOccupied->Vel > EU07_AI_NOMOVEMENT ? 0.1 : // orientuj się, bo jest goraco - 2.0; // we're already standing still, so take it easy - } - else { - if( OrderCurrentGet() & DriverOrder::connect ) { - // if there's something nearby in the connect mode don't speed up too much - VelDesired = - min_speed( - VelDesired, - Obstacle.distance > 100 ? 20.0 : 4.0 ); - } - } - } - } -} - -void -TController::adjust_desired_speed_for_limits() { - // speed caps checks - // sprawdzamy możliwe ograniczenia prędkości - if( VelSignal >= 0 ) { - // jeśli skład był zatrzymany na początku i teraz już może jechać - VelDesired = - min_speed( - VelDesired, - VelSignal ); - } - if( mvOccupied->RunningTrack.Velmax >= 0 ) { - // ograniczenie prędkości z trajektorii ruchu - VelDesired = - min_speed( - VelDesired, - mvOccupied->RunningTrack.Velmax ); // uwaga na ograniczenia szlakowej! - } - if( VelforDriver >= 0 ) { - // tu jest zero przy zmianie kierunku jazdy - // Ra: tu może być 40, jeśli mechanik nie ma znajomości szlaaku, albo kierowca jeździ 70 - VelDesired = - min_speed( - VelDesired, - VelforDriver ); - } - - // recalculate potential load exchange duration - check_load_exchange(); - if( ExchangeTime > 0 - || mvOccupied->Vel > 2.0 ) { // HACK: force timer reset if the load exchange is cancelled due to departure - WaitingSet( ExchangeTime ); - } - if( fStopTime < 0 ) { - VelDesired = 0.0; // jak ma czekać, to nie ma jazdy - cue_action( driver_hint::waitloadexchange ); - return; // speed limit can't get any lower - } - - if( OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank) && drivingFlags.stopHere && mvOccupied->Vel < 0.01 && VelSignalNext == 0.0 ) { - // w Connect nie, bo moveStopHere odnosi się do stanu po połączeniu - // jeśli ma czekać na wolną drogę, stoi a wyjazdu nie ma, to ma stać - VelDesired = 0.0; - return; // speed limit can't get any lower - } - - if( OrderCurrentGet() == DriverOrder::waitForOrders ) { - // wait means sit and wait - VelDesired = 0.0; - return; // speed limit can't get any lower - } -} - -// how long the present acceleration of a consist lasts whatever is done with the handle now: half the time -// its pneumatic brake takes to apply (while speeding up) or to release (while slowing down), which in G -// is tens of seconds; never shorter than the look-ahead the AI has always used -static double -brake_response_horizon( TMoverParameters const *Vehicle, TBrakeSystem const Brakesystem, double const Acceleration, double const Brakea0 ) { - - auto horizon { ( 1.0 - Brakea0 ) * 30.0 / 3.6 }; - if( Brakesystem == TBrakeSystem::Pneumatic ) { - // BrakeDelay holds the release and the application time in G, then the same two in P - auto const delays { Vehicle->BrakeDelayFlag > bdelay_G ? 0 : 2 }; - auto const isrelease { Acceleration < 0.0 }; - horizon = std::max( horizon, 0.5 * Vehicle->BrakeDelay[ delays + ( isrelease ? 0 : 1 ) ] ); - } - return horizon; -} - -// distance [m] in which the gradient alone, with no brake and no power, brings a train rolling uphill at Velocity [km/h] to a stand -static double -uphill_stopping_distance( double const Velocity, double const Gravity ) { - return ( Velocity / 3.6 ) * ( Velocity / 3.6 ) / ( 2.0 * std::max( 0.01, -Gravity ) ); -} - -// speed [km/h] from which the gradient alone brings a train rolling uphill to a stand in Distance [m] -static double -uphill_coasting_speed( double const Distance, double const Gravity ) { - return 3.6 * std::sqrt( 2.0 * std::max( 0.01, -Gravity ) * std::max( 0.0, Distance ) ); -} - -// outside of max safe range: follow the braking curve down to the speed ahead, Vel is the present speed in the -// direction of travel -void -TController::adjust_desired_speed_for_braking_curve( double const Vel ) { - - AccDesired = AccPreferred; - if( Vel <= min_speed( ActualProximityDist > 10.0 ? 10.0 : 5.0, VelDesired ) ) { - return; - } - // allow to coast at reasonably low speed - auto const brakingdistance { fBrakeDist * braking_distance_multiplier( VelNext ) }; - if( auto const slowdowndistance { ( - mvOccupied->CategoryFlag == 2 ? // cars can stop on a dime, for bigger vehicles we enforce some minimal braking distance - brakingdistance : - std::max( - false == OrderCurrentGet().HasAny(DriverOrder::connect) ? 100.0 : 25.0, - brakingdistance ) ) }; - brakingdistance + std::max(slowdowndistance, fMaxProximityDist) < ActualProximityDist - fMaxProximityDist ) { - // don't slow down prematurely; as long as we have room to come to a full stop at a safe distance, we're good - return; - } - // ensure some minimal coasting speed, otherwise a vehicle entering this zone at very low speed will be crawling forever - auto const brakingpointoffset = ( - ( VelNext == 0.0 ) && is_train() && ( OrderCurrentGet() & DriverOrder::obeyTrain ) ? - stopping_margin() : // the same stopping point as the final approach - VelNext * braking_distance_multiplier( static_cast( VelNext ) ) ); - // both plans of a pneumatic brake are made from the brake table of the consist; with none (in shunting it isn't - // worked out) the braking curve is the constant deceleration over the distance left, as before them - braking_curve::brake_table const braketable { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax }; - // making for a passenger stop only the time the brake takes to fill: the look-ahead the horizon - // keeps as its floor was set for the stops at a signal, and a vehicle that brakes with its - // independent brake, which leaves the train brake handle where it is, kept braking earlier - // and earlier the whole way in, to crawl the last tens of metres to the stop point - auto const fillbrakea0 { bStopTargetIsPassengerStop ? 1.0 : fBrake_a0[ 0 ] }; - // once the brake is on, the room it takes to fill is behind; a vehicle running alone brakes with its - // independent brake and leaves the train brake handle in running, so that brake counts as well - braking_curve::approach const approach { - Vel, VelNext, ActualProximityDist, brakingpointoffset, fAccGravity, AbsAccS, - braking_curve::brake_acting( - BrakeCtrlPosition, - // IncLocalBrakeLevel() moves the independent brake handle on a vehicle without one too - ( mvOccupied->LocalBrake == TLocalBrake::PneumaticBrake || mvOccupied->LocalBrake == TLocalBrake::HydraulicBrake ) ? - mvOccupied->LocalBrakePosA : - 0.0 ), - brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ), - brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fillbrakea0 ) }; - auto const deceleration { braking_curve::demand( approach, BrakeSystem == TBrakeSystem::Pneumatic ? &braketable : nullptr ) }; - AccDesired = std::min( AccDesired, deceleration ); // najpierw hamuje mocniej, potem zluzuje - if( Vel <= VelNext ) { - return; - } - if( deceleration < fAccGravity - 0.001 ) { - // no power while still above the speed being braked for - AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION ); - } - else if( ( fAccGravity < -0.025 ) - && ( OrderCurrentGet().HasAny(DriverOrder::obeyTrain) ) - && ( false == uphill_brake_committed( Vel ) ) - && ( ActualProximityDist - uphill_stopping_distance( Vel, fAccGravity ) > brakingpointoffset ) ) { - // uphill the gradient alone slows the train down more than it is asked to; - // keep it rolling at the present speed until that changes - AccDesired = std::min( 0.0, AccPreferred ); - VelDesired = min_speed( VelDesired, uphill_coasting_speed( ActualProximityDist - brakingpointoffset, fAccGravity ) ); - } -} - -// the final approach to a stop, inside the proximity range: Vel is the present speed in the direction of travel -void -TController::adjust_desired_speed_for_final_approach( double const Vel ) { - - if( ( mvOccupied->CategoryFlag & 1 ) == 0 ) { - // for cars (and others) coast at low speed until we hit min proximity range - VelDesired = min_speed( VelDesired, 5.0 ); - return; - } - // trains - if( ( OrderCurrentGet() & ( DriverOrder::shunt | DriverOrder::connect ) ) - && ( Obstacle.distance < 50 ) ) { - // crude detection of edge case, if approaching another vehicle coast slowly until min distance - // this should allow to bunch up trainsets more on sidings - VelDesired = min_speed( 5.0, VelDesired ); - return; - } - // hamowanie tak, aby stanąć - if( false == OrderCurrentGet().HasAny(DriverOrder::obeyTrain) ) { - VelDesired = VelNext; - AccDesired = ( VelNext * VelNext - Vel * Vel ) / ( 25.92 * ( ActualProximityDist + 0.1 - 0.5*fMinProximityDist ) ); - AccDesired = std::min( AccDesired, fAccThreshold ); - return; - } - // a train keeps its desired speed until the lower edge of the stopping window (a desired - // speed of 0 here asks for hard braking whatever the distance left), aims at the middle - // of the window, and asks only for what that takes - auto const stoppingroom { std::max( 0.5, ActualProximityDist - stopping_margin() ) }; - AccDesired = ( - BrakeSystem == TBrakeSystem::Pneumatic ? - // cast iron blocks grip harder as the train comes to a stand - braking_curve::shaped_demand( - Vel, VelNext, stoppingroom, fAccGravity, - { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax } ) : - ( VelNext * VelNext - Vel * Vel ) / ( 25.92 * stoppingroom ) ); - if( ( fAccGravity < -0.025 ) - && ( AccDesired >= fAccGravity - 0.001 ) // no brake needed at all - && ( false == uphill_brake_committed( Vel ) ) - && ( ActualProximityDist - uphill_stopping_distance( Vel, fAccGravity ) > stopping_margin() ) ) { - // uphill the gradient alone would bring the train to a stand short of the - // middle of the stopping window; keep it rolling at the present speed until that changes, - // but no faster than the gradient alone can take off by the middle of the window - AccDesired = std::min( 0.0, AccPreferred ); - VelDesired = min_speed( VelDesired, uphill_coasting_speed( ActualProximityDist - stopping_margin(), fAccGravity ) ); - } -} - -void -TController::adjust_desired_speed_for_target_speed( double const Range ) { - // ustalanie zadanego przyspieszenia - //(ActualProximityDist) - odległość do miejsca zmniejszenia prędkości - //(AccPreferred) - wynika z psychyki oraz uwzglęnia już ewentualne zderzenie z pojazdem z przodu, ujemne gdy należy hamować - //(AccDesired) - uwzględnia sygnały na drodze ruchu, ujemne gdy należy hamować - //(fAccGravity) - chwilowe przspieszenie grawitacyjne, ujemne działa przeciwnie do zadanego kierunku jazdy - //(AbsAccS) - chwilowe przyspieszenie pojazu (uwzględnia grawitację), ujemne działa przeciwnie do zadanego kierunku jazdy - //(AccDesired) porównujemy z (fAccGravity) albo (AbsAccS) - - // gdy jedzie wolniej niż potrzeba, albo nie ma przeszkód na drodze - // normalna jazda - AccDesired = VelDesired != 0.0 ? AccPreferred : -0.01; - fAccDesiredGravity = 0.0; - - auto const vel { DirectionalVel() }; - - if( VelNext >= 0.0 - && ActualProximityDist <= Range - && vel >= VelNext ) { - // gdy zbliża się i jest za szybki do nowej prędkości, albo stoi na zatrzymaniu - if (vel > EU07_AI_NOMOVEMENT) { - // jeśli jedzie - if( vel < VelNext - && ActualProximityDist > fMaxProximityDist * (1.0 + 0.1 * vel) ) { - // jeśli jedzie wolniej niż można i jest wystarczająco daleko, to można przyspieszyć - if( AccPreferred > 0.0 ) { - // jeśli nie ma zawalidrogi dojedz do semafora/przeszkody - AccDesired = AccPreferred; - } - } - else if( ( ActualProximityDist > fMinProximityDist ) - // only a stop has a final approach of its own inside the proximity range; a lower speed ahead - // keeps the braking curve below right up to where it begins, or the train would stop braking - // (and even take power) that far out - && ( VelNext == 0.0 ) - && ( ActualProximityDist < fMaxProximityDist ) ) { - // jedzie szybciej, niż trzeba na końcu ActualProximityDist, ale jeszcze jest daleko - // jak minął już maksymalny dystans po prostu hamuj (niski stopień) - // ma stanąć, a jest w drodze hamowania albo ma jechać - adjust_desired_speed_for_final_approach( vel ); - AccDesired = std::min( AccDesired, AccPreferred ); - } - else if (ActualProximityDist > fMinProximityDist) { - // jedzie szybciej, niż trzeba na końcu ActualProximityDist, ale jeszcze jest daleko - adjust_desired_speed_for_braking_curve( vel ); - AccDesired = std::min( AccDesired, AccPreferred ); - } - else { - // jest bliżej niż fMinProximityDist - // utrzymuj predkosc bo juz blisko -/* - VelDesired = min_speed( VelDesired, VelNext ); -*/ - if( VelNext == 0.0 ) { - VelDesired = VelNext; - } - else { - if( vel <= VelNext + fVelPlus ) { - // jeśli niewielkie przekroczenie, ale ma jechać - AccDesired = std::max( 0.0, AccPreferred ); // to olej (zacznij luzować) - } - } - ReactionTime = 0.1; // i orientuj się szybciej - } - } - else { - // zatrzymany (vel==0.0) - if( VelNext > 0.0 ) { - // można jechać - AccDesired = AccPreferred; - } - else { - // jeśli daleko jechać nie można - if( ActualProximityDist > ( - mvOccupied->CategoryFlag & 2 ? - fMinProximityDist : // cars - fMaxProximityDist ) ) { // trains and others - // ale ma kawałek do sygnalizatora - if( AccPreferred > 0.0 ) { - // dociagnij do semafora; - AccDesired = AccPreferred; - } - else { - //stoj - VelDesired = 0.0; - } - } - else { - // VelNext=0 i stoi bliżej niż fMaxProximityDist - VelDesired = 0.0; - } - } - } - } -} - -void -TController::adjust_desired_speed_for_current_speed() { - // decisions based on current speed - auto const vel { DirectionalVel() }; - - if( is_train() ) { - // on flats or uphill we can be less careful - if( vel > VelDesired ) { - // jesli jedzie za szybko do AKTUALNEGO - if( VelDesired == 0.0 ) { - // jesli stoj, to hamuj, ale i tak juz za pozno :) - AccDesired = std::min( AccDesired, -0.85 ); // hamuj solidnie - } - else { - // slow down, not full stop - if( vel > VelDesired + fVelPlus ) { - // hamuj tak średnio - AccDesired = std::min( AccDesired, -0.05 + fAccThreshold ); - } - else { - // o 5 km/h to olej (zacznij luzować) - AccDesired = std::min( - AccDesired, // but don't override decceleration for VelNext - std::max( 0.0, AccPreferred ) ); - } - } - } - - if( fAccGravity > 0.025 ) { - // going sharply downhill we may need to start braking sooner than usual - // try to estimate increase of current velocity before engaged brakes start working - // look ahead for as long as the brake takes to respond, since that is how long the - // present acceleration will last whatever is done with the handle now; a pneumatic - // brake applies and releases on its own time scale, which in G is tens of seconds - auto const horizon { brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ) }; - auto const speedestimate = vel + 3.6 * horizon * AbsAccS; - // already below a lower limit ahead, the train has no business speeding up towards it - auto holdlimit { VelDesired }; - if( ( VelNext > 0.0 ) - && ( VelNext < holdlimit ) - && ( vel <= VelNext + fVelPlus ) - && ( ActualProximityDist < std::max( 2.0 * fBrakeDist, 500.0 ) ) ) { - holdlimit = VelNext; - } - // hold a band just below the limit; the steeper the descent the harder the train pulls - // away once the brake eases, so the band widens with the gradient (about 3 km/h at 20 per mille) - // an electro-pneumatic or electric brake responds at once and needs far less room - auto const holdspeed { holdlimit - ( - BrakeSystem == TBrakeSystem::Pneumatic ? - std::clamp( fAccGravity * 15.0, 1.0, 3.0 ) : - std::clamp( fAccGravity * 7.5, 1.0, 1.5 ) ) }; - // the predicted difference is to be made up over the time the brake takes to respond, not at once: with a - // slow brake, a demand sized to remove it at once comes on as a deep application, which then takes as - // long to let go, and the train ends up well below the speed it was to hold - auto const holdgain { std::min( 0.04, 1.0 / ( 3.6 * std::max( 1.0, horizon ) ) ) }; - if( ( speedestimate > VelDesired ) - && ( VelDesired == 0.0 ) ) { - // jesli stoj, to hamuj, ale i tak juz za pozno :) - AccDesired = std::min( AccDesired, -0.85 ); // hamuj solidnie - } - else { - // one continuous law on both sides of the target, proportional to the predicted - // difference: a demand that jumps to the braking threshold above the target and to - // full acceleration below it alternates, with a brake that responds in seconds, - // between a hard application and a full release - AccDesired = std::min( - AccDesired, // but don't override decceleration for VelNext - std::clamp( - EU07_AI_NOACCELERATION - holdgain * ( speedestimate - holdspeed ), - -0.05 + fAccThreshold, - std::max( EU07_AI_NOACCELERATION, AccPreferred ) ) ); - // HACK: for cargo trains with high braking threshold ensure we cross that threshold - auto const crossthreshold { IsCargoTrain && fBrake_a0[ 0 ] > 0.2 && speedestimate > holdlimit }; - AccDesired -= ( crossthreshold ? std::clamp( fBrake_a0[ 0 ] - 0.2, 0.0, 0.15 ) : 0.0 ); - } - // final tweaks - if( vel > EU07_AI_NOMOVEMENT ) { - // going downhill also take into account impact of gravity - AccDesired -= fAccGravity; - // from here on AccDesired is what the brake alone has to deliver, which is what - // IncBrake() sizes the handle position for; AbsAccS already contains the gravity, - // so the comparisons with it have to add this part back - fAccDesiredGravity = fAccGravity; - // HACK: if the max allowed speed was exceeded something went wrong; brake harder - AccDesired -= 0.15 * std::clamp( vel - VelDesired, 0.0, 5.0 ); - } - } - // HACK: limit acceleration for cargo trains, to reduce probability of breaking couplers on sudden jolts - auto MaxAcc{ 0.5 * mvOccupied->Couplers[(mvOccupied->DirAbsolute >= 0 ? end::rear : end::front)].FmaxC / fMass }; - if( iVehicles - ControlledEnginesCount > 0 ) { - MaxAcc *= std::clamp( vel * 0.025, 0.2, 1.0 ); - } - AccDesired = std::min(AccDesired, safe_clamp(MaxAcc, HeavyCargoTrainAcceleration, AccPreferred)); - // TBD: expand this behaviour to all trains with car(s) exceeding certain weight? - /* - if( ( IsPassengerTrain ) && ( iVehicles - ControlledEnginesCount > 0 ) ) { - AccDesired = std::min( AccDesired, ( iVehicles - ControlledEnginesCount > 8 ? HeavyPassengetTrainAcceleration : PassengetTrainAcceleration ) ); - } - if( ( IsCargoTrain ) && ( iVehicles - ControlledEnginesCount > 0 ) ) { - AccDesired = std::min( AccDesired, CargoTrainAcceleration ); - } - if( ( IsHeavyCargoTrain ) && ( iVehicles - ControlledEnginesCount > 0 ) ) { - AccDesired = std::min( AccDesired, HeavyCargoTrainAcceleration ); - } */ - } - else { - // for cars the older version works better - if( vel > VelDesired ) { - // jesli jedzie za szybko do AKTUALNEGO - if( VelDesired == 0.0 ) { - // jesli stoj, to hamuj, ale i tak juz za pozno :) - AccDesired = std::min( AccDesired, -0.9 ); // hamuj solidnie - } - else { - // slow down, not full stop - if( vel > VelDesired + fVelPlus ) { - // hamuj tak średnio - AccDesired = std::min( AccDesired, -fBrake_a0[ 0 ] * 0.5 ); - } - else { - // o 5 km/h to olej (zacznij luzować) - AccDesired = std::min( - AccDesired, // but don't override decceleration for VelNext - std::max( 0.0, AccPreferred ) ); - } - } - } - } - - // NOTE: as a stop-gap measure the routine is limited to trains only while car calculations seem off - if( is_train() && vel < VelDesired && - -AccDesired * BrakeAccFactor() < (false == Ready || VelNext > vel - 40.0 ? fBrake_a0[0] * 0.8 : -fAccThreshold) / (1.2 * braking_distance_multiplier(VelNext)) ) { - // don't adjust acceleration when going above current target speed - AccDesired = std::max(EU07_AI_NOACCELERATION, AccDesired); - } -} - -// hamowanie kontrolne -void -TController::adjust_desired_speed_for_braking_test() { - -// if( false == Global.DynamicBrakeTest ) { return; } - if( DynamicBrakeTest >= 5 ) { return; } // all done - if( ( DynamicBrakeTest == 0 ) - && ( false == timetable::makes_brake_test( TrainParams.run_flags() ) ) ) { return; } // the timetable says there's none (eu07/maszyna#95) - if( false == is_train() ) { return; } // not applicable - if( mvOccupied->BrakeHandle == TBrakeHandle::FVel6 ) { return; } // leads to bugs in DecBrake, disable for now - if( false == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { return; } // not applicable - if( false == AIControllFlag ) { return; } // TBD: add notification about braking test and enable it for human driver as well? - - auto const vel { DirectionalVel() }; - // what the route ahead asks for; the test may brake harder than that, never softer - auto const routeaccdesired { AccDesired }; - auto const routeaccdesiredgravity { fAccDesiredGravity }; - auto const routeveldesired { VelDesired }; - - switch( DynamicBrakeTest ) { - case 0: { - if( primary() - && vel < VelDesired - && fAccGravity >= 0.0 // not if going uphill - && AccDesired >= EU07_AI_ACCELERATION - && TrainParams.TTVmax >= 10.0 - && vel > std::min(TrainParams.TTVmax, 60.0) - 2.0 ) { - DynamicBrakeTest = 1; - DBT_BrakingTime = ElapsedTime; - DBT_VelocityBrake = vel; - } - break; - } - case 1: { - AccDesired = EU07_AI_BRAKINGTESTACCELERATION; - fAccDesiredGravity = 0.0; - VelDesired = DBT_VelocityBrake; - if( ElapsedTime - DBT_BrakingTime > 1 ) { - ForcePNBrake = true; - mvOccupied->EpFuseSwitch( false ); - DynamicBrakeTest = 2; - } - break; - } - case 2: { - AccDesired = EU07_AI_BRAKINGTESTACCELERATION; - fAccDesiredGravity = 0.0; - VelDesired = DBT_VelocityBrake; - if( ElapsedTime - DBT_BrakingTime > 2 ) { - DBT_BrakingTime = ElapsedTime; - DBT_VelocityBrake = vel; - DBT_VelocityRelease = vel - 8.0; - DynamicBrakeTest = 3; - } - break; - } - case 3: { - AccDesired = safe_clamp( -AbsAccS, fAccThreshold * 1.01, fAccThreshold * 1.21 ); - fAccDesiredGravity = 0.0; - VelDesired = DBT_VelocityBrake; - if( vel <= DBT_VelocityRelease ) { - DynamicBrakeTest = 4; - DBT_BrakingTime = ElapsedTime - DBT_BrakingTime; - DBT_MidPointAcc = AbsAccS; - DBT_ReleasingTime = ElapsedTime; - } - break; - } - case 4: { - if( Ready ) { - if( BrakeSystem == TBrakeSystem::ElectroPneumatic ) { - mvOccupied->EpFuseSwitch( true ); - } - ForcePNBrake = false; - DynamicBrakeTest = 5; - DBT_ReleasingTime = ElapsedTime - DBT_ReleasingTime; - DBT_VelocityFinish = vel; - } - break; - } - default: { - break; - } - } - // a stop or a restriction coming up while the test runs takes precedence - if( ( DynamicBrakeTest >= 1 ) - && ( DynamicBrakeTest <= 3 ) - && ( routeaccdesired < AccDesired ) ) { - AccDesired = routeaccdesired; - fAccDesiredGravity = routeaccdesiredgravity; - VelDesired = std::min( VelDesired, routeveldesired ); - } -} - -void -TController::control_tractive_and_braking_force() { - -#if LOGVELOCITY - WriteLog("Dist=" + FloatToStrF(ActualProximityDist, ffFixed, 7, 1) + - ", VelDesired=" + FloatToStrF(VelDesired, ffFixed, 7, 1) + - ", AccDesired=" + FloatToStrF(AccDesired, ffFixed, 7, 3) + - ", VelSignal=" + AnsiString(VelSignal) + ", VelNext=" + - AnsiString(VelNext)); -#endif - - if (iDriverFailCount > maxdriverfails) { - Psyche = Easyman; - if (iDriverFailCount > maxdriverfails * 2) - SetDriverPsyche(); - } - - control_relays(); - control_motor_connectors(); - - // if the radio-stop was issued don't waste effort trying to fight it - if( true == mvOccupied->RadioStopFlag // radio-stop - && mvOccupied->Vel > EU07_AI_NOMOVEMENT ) { // and still moving - cue_action( driver_hint::mastercontrollersetzerospeed ); // just throttle down... - return; // ...and don't touch any other controls - } - // if we're slipping leave the controls alone, there's a separate logic section trying to deal with it - if( true == mvControlling->SlippingWheels ) { - return; - } - - // ensure train brake isn't locked - if( BrakeCtrlPosition == gbh_NP ) { - cue_action( driver_hint::trainbrakerelease ); - } - control_releaser(); - control_main_pipe(); - - control_tractive_force(); - control_braking_force(); - -#if LOGVELOCITY - WriteLog("BrakePos=" + AnsiString(mvOccupied->BrakeCtrlPos) + ", MainCtrl=" + - AnsiString(mvControlling->MainCtrlPos)); -#endif -} - -// the switch of the field shunting of a diesel-electric that has one (AutoRelay=Optional with FieldShuntSwitch=Yes): off, -// the field stays full. checked while running too, since a vehicle taken over with its engine running doesn't go through -// PrepareEngine(). a diesel-electric with AutoRelay=Optional alone is left as before, shunting by hand with the switch off -void TController::control_field_shunting() { - - if( AIControllFlag - && mvControlling->EngineType == TEngineType::DieselElectric - && fieldshunting::has_switch( mvControlling->AutoRelayType, mvControlling->FieldShuntSwitch ) - && false == mvControlling->AutoRelayFlag ) { - mvControlling->AutoRelaySwitch( true ); - } -} - -// ensure relays are active -void TController::control_relays() { - - control_field_shunting(); - - if( fActionTime < 0.0 ) { return; } - - if( IsAnyMotorOverloadRelayOpen ) { - cue_action( driver_hint::mastercontrollersetzerospeed ); - cue_action( driver_hint::tractionnmotoroverloadreset ); - ++iDriverFailCount; - } - if( IsAnyGroundRelayOpen ) { - cue_action( driver_hint::mastercontrollersetzerospeed ); - cue_action( driver_hint::maincircuitgroundreset ); - ++iDriverFailCount; - } -} - -void TController::control_motor_connectors() { - // ensure motor connectors are active - if( (mvControlling->EngineType == TEngineType::ElectricSeriesMotor || mvControlling->EngineType == TEngineType::DieselElectric || is_emu()) && Need_TryAgain ) { - // true, jeśli druga pozycja w elektryku nie załapała - cue_action(driver_hint::mastercontrollersetzerospeed); - Need_TryAgain = false; - } -} - -void TController::control_tractive_force() { - - control_uphill_start(); - - auto const velocity { DirectionalVel() }; - // jeśli przyspieszenie pojazdu jest mniejsze niż żądane oraz... - if( AccDesired > EU07_AI_NOACCELERATION // don't add power if not asked for actual speed-up - && (AbsAccS < AccDesired /*- std::min( 0.05, 0.01 * iDriverFailCount )*/ || mvOccupied->SpeedCtrlUnit.IsActive && velocity < mvOccupied->SpeedCtrlUnit.FullPowerVelocity) && - false == drivingFlags.press && - // starting uphill against the releasing brake, the power that holds the train is enough: the brake coming off - // speeds the train up, more power only drags the brake and slips the wheels. nor is a notch past that taken - // back: the power got there in one notch from below, and the notch below doesn't hold the train - ( false == bUphillRelease || fUphillTractiveForce < uphill_start::holding_force * fUphillHoldingForce ) && - // nor while the train brake is still being applied further to hold the train - false == bUphillBrakeTopUp && - velocity < (VelDesired == 1.0 ? // work around for trains getting stuck on tracks with speed limit = 1 - VelDesired : - VelDesired - fVelMinus) && - (ActualProximityDist > (is_car() ? fMinProximityDist : // cars are allowed to move within min proximity distance - fMaxProximityDist) ? // other vehicle types keep wider margin - true : - velocity + 1.0 < VelNext - // uphill, a train told to hold its speed on the way to a stop needs the power to do it - || VelNext == 0.0 && OrderCurrentGet().HasAny(DriverOrder::obeyTrain) && AccDesired >= 0.0 && fAccGravity < -0.025 && ActualProximityDist > fMinProximityDist) ) { - // ...jeśli prędkość w kierunku czoła jest mniejsza od dozwolonej o margines... - // within proximity margin don't exceed next scheduled speed, outside of the margin accelerate as you like - // ...to można przyspieszyć - increase_tractive_force(); - } - // zmniejszanie predkosci - // margines dla prędkości jest doliczany tylko jeśli oczekiwana prędkość jest większa od 5km/h - if( false == drivingFlags.press ) { - double SpeedCtrlMargin = mvControlling->SpeedCtrlUnit.IsActive && VelDesired > 5 ? 3 : 0; - // jeśli nie dociskanie - if( AccDesired <= EU07_AI_NOACCELERATION ) { - cue_action( driver_hint::mastercontrollersetzerospeed ); - } - else if( velocity > VelDesired + SpeedCtrlMargin - || ( fAccGravity < -0.01 ? is_too_fast_uphill() : AbsAccS > AccDesired + 10.05 ) - || IsAnyCouplerStretched ) { - // jak za bardzo przyspiesza albo prędkość przekroczona - // dodany wyjatek na "pelna w przod" - cue_action( driver_hint::tractiveforcedecrease ); - } - } - - control_handles(); - SpeedSet(); // ciągla regulacja prędkości -} - -bool TController::is_too_fast_uphill() const { - - if( AccDesired < 0.0 ) { return true; } - // holding the speed uphill on the way to a stop asks for no speeding up - return ( VelNext == 0.0 && ActualProximityDist <= fMaxProximityDist && AbsAccS > AccDesired + 0.05 ); -} - -// starting uphill a driver of a heavy train keeps the train brake applied, lets the locomotive's own brake off (the -// independent brake, and its share of the train brake with the releaser), applies the power, and releases the train -// brake only once the power holds the train. releasing everything first lets the train roll back before the power is -// there, and holding the train on the locomotive brake is no way out where that brake cuts the power (asynchronous -// drives, the control pressure switch) -void TController::control_uphill_start() { - - auto const velocity { DirectionalVel() }; - if( auto const uphill { - ( BrakeSystem == TBrakeSystem::Pneumatic ) - && is_train() - && ( false == is_emu() ) && ( false == is_dmu() ) // a multiple unit has no locomotive to hold a train behind it - && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) }; - false == uphill ) { - end_uphill_start(); - return; - } - if( false == bUphillStart ) { - if( ( std::abs( velocity ) < EU07_AI_NOMOVEMENT ) - // the whole train at a stand, not only its head stopped for a moment while the train rolls back - && ( fConsistVelocity > -0.5 ) - && ( AccDesired > EU07_AI_NOACCELERATION ) - && ( VelDesired > 0.0 ) - && ( BrakeCtrlPosition > 0.0 ) // only with the train brake still applied to hold the train - && ( IsConsistCharged ) ) { // and charged to what the pipe has, or the brake that holds the train has no air - bUphillStart = true; - bUphillRelease = false; - UphillTopUp = {}; - fUphillStartTime = ElapsedTime; - } - else { - return; - } - } - if( AccDesired <= EU07_AI_NOACCELERATION ) { - // no longer to start: the standing rules take over - end_uphill_start(); - return; - } - if( fConsistVelocity < -0.5 ) { - // the train rolls back all the same: the rules for a train slipping back take over and apply the brakes. - // the train as a whole, not its head: with the locomotive brake off, the locomotive and the first vehicles - // run back into the slack of a long train still held by its brake - end_uphill_start(); - return; - } - fUphillTractiveForce = 0.0; - for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { - // Ft is signed in the vehicle's own frame, and turned into the direction of travel as AbsAccS is - fUphillTractiveForce += std::max( 0.0, vehicle->MoverParameters->Ft * ( vehicle->DirectionGet() == iDirection ? 1 : -1 ) * ( iDirection >= 0 ? 1 : -1 ) ); - } - fUphillHoldingForce = fMass * -fAccGravity; - bUphillBrakeTopUp = false; - if( false == bUphillRelease ) { - bUphillBrakeTopUp = uphill_brake_top_up(); - if( bUphillBrakeTopUp ) { - return; - } - if( ( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) - && ( mvOccupied->LocalBrakePosA > 0.0 ) ) { - cue_action( driver_hint::independentbrakerelease ); - } - if( ( velocity > 1.0 ) - || ( fUphillTractiveForce > uphill_start::holding_force * fUphillHoldingForce ) - // a locomotive that can't hold the train on its own power gets the brake off in the end all the same - || ( ElapsedTime - fUphillStartTime > 45.0 ) ) { - // the power holds the train: the train brake can be released - bUphillRelease = true; - fUphillReleaseTime = ElapsedTime; - } - return; - } - // the train brake is being released with the power on. the start ends once the brakes are off: ended before, - // the brake still on takes the power off, the train rolls back and has to be braked to a stand again - if( IsConsistReleased - // a brake that doesn't come off (a hand brake) ends it all the same - || ( ElapsedTime - fUphillReleaseTime > EU07_AI_UPHILLRELEASETIME ) ) { - end_uphill_start(); - } -} - -// the locomotive brake comes off only once the brake of the rest of the train holds the train on its own: a train -// stopped on a light application stands on the locomotive brake too, and rolls back as soon as it is off. until then -// the train brake is applied further, a step at a time; true while it is -bool TController::uphill_brake_top_up() { - - auto trainbrakeforce { 0.0 }; - auto haswagons { false }; - for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { - if( vehicle->MoverParameters->Power < 0.01 ) { - trainbrakeforce += vehicle->MoverParameters->Fb; - haswagons = true; - } - } - if( false == haswagons ) { - return false; - } - auto const action { uphill_start::brake_top_up( - UphillTopUp, trainbrakeforce, fUphillHoldingForce, BrakeCtrlPosition, fBrakeHeldTime, - mvOccupied->BrakeDelay[ mvOccupied->BrakeDelayFlag > bdelay_G ? 1 : 3 ] ) }; - if( action == uphill_start::top_up_action::none ) { - return false; - } - // the time for the power to hold the train starts once the brake does - fUphillStartTime = ElapsedTime; - if( action == uphill_start::top_up_action::step ) { - BrakeLevelAdd( BrakingLevelIncrease ); - } - return true; -} - -void TController::end_uphill_start() { - - bUphillStart = false; - bUphillRelease = false; - bUphillBrakeTopUp = false; -} - -// standing, a train is prepared as a driver does it: the locomotive brake first, then the brake pipe is filled. the pipe -// filled at once releases the distributors while the auxiliary reservoirs are still empty: the train has no brake left, -// and on a gradient rolls away as it releases. where the locomotive brake alone doesn't hold the train, the train brake -// is applied lightly, so the reservoirs charge with the train held. the locomotive brake comes off only once the train -// is charged and to start (DecBrake()) -void TController::secure_standing_train() { - - if( BrakeSystem != TBrakeSystem::Pneumatic ) { - // the electro-pneumatic brake of a multiple unit is released as before: nothing there takes the locomotive - // brake off again when the unit starts - cue_action( driver_hint::trainbrakerelease ); - return; - } - // the first start of a train that hasn't run yet waits for the brakes to charge. one that has run, prepared again - // (a change of direction, an engine started anew), has its reservoirs charged from the run and starts as before - if( false == bHasRun ) { - bBrakeChargeStart = true; - } - if( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) { - cue_action( driver_hint::independentbrakeapply ); - } - if( false == brake_charge::locomotive_brake_holds( locomotive_brake_force(), fMass * fAccGravity ) ) { - // the first service position: the pipe and the reservoirs charge to a little below the working pressure, the - // distributors keep a light application. a stronger application already there is left as it is, but not - // the emergency one or an empty pipe's, which don't charge - if( AIControllFlag - && ( ( BrakeCtrlPosition < 1.0 ) || ( BrakeCtrlPosition > uphill_start::top_up_position ) ) ) { - BrakeLevelSet( 1.0 ); - } - bBrakeChargeHold = true; - return; - } - bBrakeChargeHold = false; - cue_action( driver_hint::trainbrakerelease ); -} - -// the brake force of the locomotive brake at full application [N]. of the occupied vehicle alone: its handle acts on -// no other, not on a second section or a locomotive in multiple control either, let alone one hauled dead -double TController::locomotive_brake_force() const { - - if( ( mvOccupied->LocalBrake == TLocalBrake::ManualBrake ) - || ( mvOccupied->MaxBrakePress[ 0 ] <= 0.0 ) ) { - return 0.0; - } - return brake_charge::locomotive_brake_force( - mvOccupied->BrakeForceP( mvOccupied->MaxBrakePress[ 0 ], 0.0 ), - mvOccupied->TotalMassxg ); -} - -void TController::increase_tractive_force() { - - if( fActionTime < 0.0 ) { return; } // gdy jest nakaz poczekać z jazdą, to nie ruszać - if( IsAnyCouplerStretched ) { return; } // train is already stretched past its limits, don't pull even harder - - if( mvOccupied->SpringBrake.Activate ) { - cue_action( driver_hint::springbrakeoff ); - } - if( VelDesired > 0.0 // to prevent door shuffle on stop - && ( doors_open() || doors_permit_active() ) ) { - // zamykanie drzwi - tutaj wykonuje tylko AI (zmienia fActionTime) - Doors( false ); - // Doors() call can potentially adjust fActionTime - if( fActionTime < 0.0 ) { return; } - } - if( true == mvOccupied->DepartureSignal ) { - cue_action( driver_hint::departuresignaloff ); - } - - cue_action( driver_hint::tractiveforceincrease ); -} - -// how far the deceleration may fall short of the demand before the brake is applied harder. approaching a lower -// speed, a pneumatic brake given a full step only once that much is missing acts too late: the demand -// creeps up meanwhile, and in a long G train the next step takes many seconds to act, so half a step is enough -double -TController::brake_increase_margin() const { - - if( ( BrakeSystem == TBrakeSystem::Pneumatic ) - && ( VelNext > 0.0 ) - && ( VelNext < DirectionalVel() ) ) { - return 0.5 * fBrake_a1[ 0 ]; - } - return fBrake_a1[ 0 ]; -} - -// a train coming to a stand with at least part of it on an up gradient: a long train brake released now cannot be -// applied again before the train stops and starts to roll back, so the train brake is not released any further, and the -// locomotive brake, which acts at once, helps to hold the train -bool -TController::uphill_stop_hold() const { - - return ( - ( BrakeSystem == TBrakeSystem::Pneumatic ) && is_train() && ( OrderCurrentGet().HasAny(DriverOrder::obeyTrain) ) - && ( VelNext == 0.0 ) - && ( ActualProximityDist <= fMaxProximityDist ) - && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) - && ( std::abs( DirectionalVel() ) < 10.0 ) - // not while the train is to be driven on - && ( AccDesired <= 0.0 ) ); -} - -// uphill with the train brake applied, the gradient brings a slow train to a stand sooner than the brake of the consist -// can be released: letting the train roll on (or pulling up) at this speed only releases the brake for nothing, and the -// train stands with the brake on its way off instead -bool -TController::uphill_brake_committed( double const Velocity ) const { - - return ( - ( BrakeSystem == TBrakeSystem::Pneumatic ) - && ( BrakeCtrlPosition > 0.0 ) - && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) - && ( Velocity / 3.6 / -fAccGravity < brake_response_horizon( mvOccupied, BrakeSystem, -1.0, fBrake_a0[ 0 ] ) ) ); -} - -void TController::control_braking_force() { - - // don't touch the brakes when compressing buffers during coupling/uncoupling - if( drivingFlags.press ) { return; } - - auto const velocity { DirectionalVel() }; - // a train slipping back uphill is braked, also when it is to go on: released now it only rolls back further. - // its head, or the train as a whole: the locomotive may stop for a moment while the rest of the train runs into it - auto const slippingbackuphill { - ( fAccGravity < -0.05 ) - && ( std::min( velocity, fConsistVelocity ) < -0.1 ) - && ( false == bUphillStart ) }; - - // jeśli przyspieszamy, to nie hamujemy - if( AccDesired > 0.0 && OrderCurrentGet() != DriverOrder::disconnect // przy odłączaniu nie zwalniamy tu hamulca - && false == drivingFlags.press - && false == slippingbackuphill ) { - cue_action(driver_hint::brakingforcesetzero); - } - - // AbsAccS is the resultant acceleration, gravity included, so it is compared with the - // resultant the AI asks for, not with the brake-only demand AccDesired holds on a descent - auto const accdesiredresultant { AccDesired + fAccDesiredGravity }; - - // every few seconds, note how far the train falls short of the demand and whether that is getting worse: a brake - // still filling, or blocks gripping harder as the train slows down, make up a shortfall on their own, but a - // shortfall that keeps growing at a constant handle means the train is falling further behind its braking curve - if( ElapsedTime - fShortfallTime >= 3.0 ) { - auto const shortfall { AbsAccS - accdesiredresultant }; - iShortfallGrowth = ( - ( ( AccDesired < 0.0 ) && ( shortfall > fShortfall + 0.005 ) ) ? - iShortfallGrowth + 1 : - 0 ); - fShortfall = shortfall; - fShortfallTime = ElapsedTime; - } - - if( is_emu() && !ForcePNBrake ) { - // właściwie, to warunek powinien być na działający EP - // Ra: to dobrze hamuje EP w EZT - auto const accthreshold { ( - fAccGravity < 0.025 ? // HACK: when going downhill be more responsive to desired deceleration - fAccThreshold : - std::max( -0.2, fAccThreshold ) ) }; - auto const AccMax{ std::min(fBrake_a0[0] + 12 * fBrake_a1[0], mvOccupied->MED_amax) }; - auto const accmargin = AccMax > 1.1 * AccDesired && fAccGravity < 0.025 ? - 0.05 : 0.0; - if( ( AccDesired < accthreshold // jeśli hamować - u góry ustawia się hamowanie na fAccThreshold - && ( AbsAccS > accdesiredresultant + accmargin - || BrakeCtrlPosition < 0 ) ) - || ( fAccGravity < -0.05 && velocity < -0.1 && AccDesired < 0.0 ) ) { // also brake if uphill and slipping back - // hamować bardziej, gdy aktualne opóźnienie hamowania mniejsze niż (AccDesired) - cue_action( driver_hint::brakingforceincrease ); - } - else if( OrderCurrentGet() != DriverOrder::disconnect ) { // przy odłączaniu nie zwalniamy tu hamulca - if( AbsAccS < accdesiredresultant - 0.05 ) { - // jeśli opóźnienie większe od wymaganego (z histerezą) luzowanie, gdy za dużo - // TBD: check if the condition isn't redundant with the DecBrake() code - if( BrakeCtrlPosition >= 0 && VelDesired > 0.0 ) { - // sanity check to prevent unintended brake release on sharp slopes - cue_action(driver_hint::brakingforcedecrease); - } - } - else { - cue_action( driver_hint::brakingforcelap ); - } - } - } // type & dt_ezt - else { - // a stara wersja w miarę dobrze działa na składy wagonowe - if( (accdesiredresultant < fAccGravity - 0.1 && AbsAccS > accdesiredresultant + brake_increase_margin() // regular braking - || slippingbackuphill) && // also brake if uphill and slipping back - (fBrakeTime < 0.0 - // the size of the brake demand decides whether to skip the reaction time, so the brake-only part - // (on a descent a heavy train needs its brake built up at once, the gravity does not help it slow) - || AccDesired < fAccGravity - 0.5 || BrakeCtrlPosition <= 0) ) { - // u góry ustawia się hamowanie na fAccThreshold - // jeśli upłynął czas reakcji hamulca, chyba że nagłe albo luzował - // TODO: check whether brake delay variable still has any purpose - cue_action(driver_hint::brakingforceincrease, - // Ra: ten czas należy zmniejszyć, jeśli czas dojazdu do zatrzymania jest mniejszy - (3.0 + 0.5 * ((mvOccupied->BrakeDelayFlag > bdelay_G ? mvOccupied->BrakeDelay[1] : mvOccupied->BrakeDelay[3]) - 3.0)) * 0.5); // Ra: tymczasowo, bo przeżyna S1 - } - else if( ( BrakeSystem == TBrakeSystem::Pneumatic ) - && ( AccDesired < 0.0 ) - && ( BrakeCtrlPosition > 0.0 ) - && ( fShortfall > 0.02 ) - && ( iShortfallGrowth >= 2 ) - && ( fBrakeHeldTime > brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) { - // the train has been falling further behind the demand for a while at a handle left alone for longer than - // the brake takes to respond: a small step now, while it still is small, rather than the deep one the - // margin above would allow only once the train is far behind - cue_action( driver_hint::brakingforceincrease ); - iShortfallGrowth = 0; - } - if ( (accdesiredresultant < fAccGravity - 0.05 - || AccDesired >= EU07_AI_NOACCELERATION) // no braking asked for, yet the train is slowing down more than that - && accdesiredresultant - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 && OrderCurrentGet() != DriverOrder::disconnect && VelDesired > 0.0 - // a human driver standing with the train not charged yet keeps the locomotive brake on, told so by the - // waitbrakecharge hint; the ai is held back in DecBrake() - && ( AIControllFlag - || ( false == brake_charge::release_waits( - IsConsistCharged, - mvOccupied->Vel < EU07_AI_NOMOVEMENT, - mvOccupied->fBrakeCtrlPos > mvOccupied->Handle->GetPos( bh_RP ) + 0.2 ) ) ) ) { // the human driver's handle - // jak hamuje, to nie tykaj kranu za często - // yB: luzuje hamulec dopiero przy różnicy opóźnień rzędu 0.2 - // przy odłączaniu nie zwalniamy tu hamulca - // sanity check to prevent unintended brake release on sharp slopes - // TODO: check whether brake delay variable still has any purpose - cue_action(driver_hint::brakingforcedecrease, - (mvOccupied->BrakeDelayFlag > bdelay_G ? mvOccupied->BrakeDelay[0] : mvOccupied->BrakeDelay[2]) / 3.0 * 0.5); // Ra: tymczasowo, bo przeżyna S1 - } - // uphill, the locomotive brake acts at once while the train brake of a long train takes many seconds to apply: - // put it on as the train comes to a stand, and at once if the train has started to roll back - if( ( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) - && ( mvOccupied->LocalBrakePosA < 1.0 ) - && ( ( uphill_stop_hold() && ( std::abs( velocity ) < 3.0 ) - // a train that has slowed down short of where it is to stop and is to pull up further does not get it - && ( VelDesired <= std::abs( velocity ) + 0.5 ) - && ( ActualProximityDist - uphill_stopping_distance( std::abs( velocity ), fAccGravity ) <= stopping_margin() ) ) - || ( ( BrakeSystem == TBrakeSystem::Pneumatic ) && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) && ( velocity < -0.1 ) && ( AccDesired <= 0.0 ) ) ) ) { - cue_action( driver_hint::independentbrakeapply ); - } - // stop-gap measure to ensure cars actually brake to stop even when above calculactions go awry - // instead of releasing the brakes and creeping into obstacle at 1-2 km/h - if( is_car() && VelDesired == 0.0 && velocity > VelDesired && ActualProximityDist <= fMinProximityDist && mvOccupied->LocalBrakePosA < 0.01 ) { - cue_action(driver_hint::brakingforceincrease); - } - } - - // odhamowywanie składu po zatrzymaniu i zabezpieczanie lokomotywy - if( mvOccupied->Vel < EU07_AI_NOMOVEMENT - && ( VelDesired == 0.0 - || AccDesired <= EU07_AI_NOACCELERATION ) ) { - - if( false == OrderCurrentGet().HasAny(DriverOrder::disconnect | DriverOrder::connect | DriverOrder::changeDirection) // przy (p)odłączaniu nie zwalniamy tu hamulca - && std::abs(fAccGravity) < 0.01 ) { // only do this on flats, on slopes keep applied the train brake - apply_independent_brake_only(); - } - // if told to change direction don't confuse human driver with request to leave applied brake in the cab they're about to leave - if( OrderCurrentGet().HasAny(DriverOrder::changeDirection) ) { - cue_action( driver_hint::independentbrakerelease ); - } - } -} - -void TController::apply_independent_brake_only() { - - if( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) { - if( false == mvOccupied->ShuntMode // no need for independent brake if autobrake is active - && is_equal(mvOccupied->fBrakeCtrlPos, mvOccupied->Handle->GetPos(bh_RP), 0.2) ) { - cue_action( driver_hint::independentbrakeapply ); - } - else { - cue_action( driver_hint::trainbrakerelease ); - } - } -} - -void TController::control_releaser() { - // HACK: don't immediately touch releaser in inert vehicle, in case the simulation is about to replace us with human driver - if( mvOccupied->Vel < 1.0 && fActionTime < 0.0 ) { return; } - // TODO: combine all releaser handling in single decision tree instead of having bits all over the place - // TODO: replace handle and system conditions with flag indicating releaser presence - if( BrakeSystem != TBrakeSystem::Pneumatic ) { return; } - - auto const hasreleaser { - false == (is_dmu() || is_emu()) // TODO: a more refined test than rejecting these types wholesale - && ( mvOccupied->BrakeHandle == TBrakeHandle::FV4a - || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_6P - || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K5P - || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K8P - || mvOccupied->BrakeHandle == TBrakeHandle::M394 ) }; - - if( false == hasreleaser ) { return; } - - brake_releaser::conditions state; - state.acceleration_desired = AccDesired; - state.pipe_pressure = mvOccupied->PipePress; - state.cylinder_pressure = mvOccupied->BrakePress; - state.control_pressure = mvOccupied->Hamulec->GetCRP(); - state.velocity = mvOccupied->Vel; - state.uphill_start = bUphillStart; - state.pressing = drivingFlags.press; - // stage 3 of uncoupling (UpdateDisconnect), from the direction change until the coupler lets go - state.compressing_buffers = - state.pressing && OrderCurrentGet().HasAny(DriverOrder::disconnect) && iVehicleCount >= 0 && iDirection == iDirectionOrder; - // a train prepared standing charges its brakes before its first start. a pipe left below the lock of the driver's - // brake valve (a train placed cold, as after an emergency application) is unlocked as the train stands, not only - // once it is to go: else it charges only after the order to go, and starts on what the reservoirs got by then. - // a handle which has to be moved to unlock is left where it holds the train with the train brake - state.charging_standing = - bBrakeChargeStart - && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) - && ( ( mvOccupied->HandleUnlock == -3 ) || ( BrakeCtrlPosition <= 0.0 ) ); - auto const wanted { brake_releaser::decide( state ) }; - auto const actuate { wanted.actuate }; - auto isbrakehandleinrightposition { true }; - - // some vehicles require brake handle to be moved to specific position to fill up the brake pipe - if( wanted.fill_pipe - && mvOccupied->HandleUnlock != -3 ) { - cue_action( driver_hint::trainbrakesetpipeunlock ); - isbrakehandleinrightposition = ( BrakeCtrlPosition == mvOccupied->HandleUnlock ); - } - - if( actuate ) { - // some vehicles may require master controller in neutral position - cue_action( driver_hint::mastercontrollersetzerospeed ); - if( false == mvOccupied->Hamulec->Releaser() - && isbrakehandleinrightposition ) { - cue_action( driver_hint::releaseron ); - } - } - else { - if( true == mvOccupied->Hamulec->Releaser() ) { - cue_action( driver_hint::releaseroff ); - } - } -} - -void TController::control_main_pipe() { - - // unlocking main pipe - if( ( AccDesired > -0.03 - // standing to charge before the first start, as in control_releaser() - || ( bBrakeChargeStart && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) ) ) - && true == mvOccupied->LockPipe ) { - UniversalBrakeButtons |= TUniversalBrake::ub_UnlockPipe; - } - else if (false == mvOccupied->LockPipe ) { - UniversalBrakeButtons &= ~TUniversalBrake::ub_UnlockPipe; - } - - // napełnianie uderzeniowe - if( BrakeSystem != TBrakeSystem::Pneumatic ) { return; } - - if( mvOccupied->BrakeHandle == TBrakeHandle::FV4a - || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_6P - || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K5P - || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K8P - || mvOccupied->BrakeHandle == TBrakeHandle::M394 ) { - - auto const departblocked { is_departure_blocked( DepartBlockedFSDelay ) }; - if( (drivingFlags.oerlikons || true == IsCargoTrain || departblocked) && BrakeCtrlPosition == gbh_RP && AbsAccS < 0.03 && AccDesired > -0.03 && VelDesired - mvOccupied->Vel > 2.0 && fReady > 0.35 && - ( mvOccupied->EqvtPipePress < 4.5 || departblocked ) // don't charge with a risk of overcharging the main pipe - && mvOccupied->Compressor >= 7.5 // don't charge without sufficient pressure in the tank - && BrakeChargingCooldown >= 0.0 // don't charge while cooldown is active - && (ActualProximityDist > 100.0 // don't charge if we're about to be braking soon - || min_speed(mvOccupied->Vel, VelNext) >= mvOccupied->Vel) ) { - - BrakeLevelSet(gbh_FS); - // don't charge the brakes too often, or we risk overcharging - BrakeChargingCooldown = -1 * std::clamp(iVehicles * 3, 30, 90); - } - - update_brake_charging(); - - if( ( mvOccupied->Compressor < 5.0 - || ( BrakeCtrlPosition < gbh_RP - && ( mvOccupied->EqvtPipePress > (fReady < 0.25 ? 5.1 : 5.2) || is_brake_charging_done() ) ) ) - // the light application a charging train stands on stays, as in DecBrake() - && ( false == brake_charge::holds_application( - bBrakeChargeHold, IsConsistCharged, mvOccupied->Vel < EU07_AI_NOMOVEMENT, BrakeCtrlPosition ) ) ) { - cue_action( driver_hint::trainbrakerelease ); - } - } -} - -void TController::update_brake_charging() { - - if( std::abs( BrakeCtrlPosition - gbh_FS ) >= 0.5 ) { - BrakeChargingStart = -1.0; - BrakeChargingPipeOverchargeStart.clear(); - return; - } - if( BrakeChargingStart < 0.0 ) { - BrakeChargingStart = ElapsedTime; - } - for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { - auto const isovercharged { - vehicle->MoverParameters != mvOccupied - && vehicle->MoverParameters->PipePress > FSOverchargePipePress }; - if( isovercharged ) { - BrakeChargingPipeOverchargeStart.try_emplace( vehicle, ElapsedTime ); - } - else { - BrakeChargingPipeOverchargeStart.erase( vehicle ); - } - } -} - -bool TController::is_departure_blocked( double const Delay ) const { - - return DepartBlockedStart >= 0.0 - && ElapsedTime - DepartBlockedStart > Delay; -} - -double TController::consist_max_crp() const { - - auto result { 0.0 }; - for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { - result = std::max( result, vehicle->MoverParameters->Hamulec->GetCRP() ); - } - return result; -} - -bool TController::is_brake_charging_done() const { - - if( BrakeChargingStart < 0.0 ) { - return false; - } - return ElapsedTime - BrakeChargingStart > FSMaxTime - || consist_max_crp() > mvOccupied->HighPipePress + FSOverchargeCRP - || std::ranges::any_of( - BrakeChargingPipeOverchargeStart, - [this]( auto const &Vehicle ) { return ElapsedTime - Vehicle.second > FSOverchargeTime; } ); -} - -void -TController::check_route_ahead( double const Range ) { - - auto const comm { TableUpdate( VelDesired, ActualProximityDist, VelNext, AccDesired ) }; - - switch (comm) { - // ustawienie VelSignal - trochę proteza = do przemyślenia - case TCommandType::cm_Ready: { // W4 zezwolił na jazdę - // ewentualne doskanowanie trasy za W4, który zezwolił na jazdę - TableCheck( Range ); - TableUpdate( VelDesired, ActualProximityDist, VelNext, AccDesired ); // aktualizacja po skanowaniu - if( VelNext == 0.0 ) { - break; // ale jak coś z przodu zamyka, to ma stać - } - if( drivingFlags.stopCloser ) { - VelSignal = -1.0; // ma czekać na sygnał z sygnalizatora! - } - break; - } - case TCommandType::cm_SetVelocity: { // od wersji 357 semafor nie budzi wyłączonej lokomotywy - if( OrderCurrentGet().Without(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank).Empty() && std::fabs(VelSignal) >= 1.0 ) { // jedzie w dowolnym trybie albo Wait_for_orders - // 0.1 nie wysyła się do samochodow, bo potem nie ruszą - PutCommand("SetVelocity", VelSignal, VelNext, nullptr); // komenda robi dodatkowe operacje - } - break; - } - case TCommandType::cm_ShuntVelocity: { // od wersji 357 Tm nie budzi wyłączonej lokomotywy - if( OrderCurrentGet().Without( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank ).Empty() ) { // jedzie w dowolnym trybie albo Wait_for_orders - PutCommand( "ShuntVelocity", VelSignal, VelNext, nullptr ); - } - else if( false == iCoupler.Empty() ) { // jeśli jedzie w celu połączenia - SetVelocity( VelSignal, VelNext ); - } - break; - } - case TCommandType::cm_Command: { // komenda z komórki - if( OrderCurrentGet().Without(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank).Empty() && mvOccupied->Vel < 0.1 ) { - // jedzie w dowolnym trybie albo Wait_for_orders - // dopiero jak stanie - /* - PutCommand( eSignNext->text(), eSignNext->value( 1 ), eSignNext->value( 2 ), nullptr ); - eSignNext->StopCommandSent(); // się wykonało już - */ // replacement of the above - eSignNext->send_command(*this); - } - break; - } - default: { - break; - } - } -} - -void -TController::check_route_behind( double const Range ) { - - if( VelNext != 0.0 ) { return; } // not if we can move ahead - if( drivingFlags.connect ) { return; } // not if we're in middle of coupling operation - - if( OrderCurrentGet().Without( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect ).Empty() ) { - // jedzie w Shunt albo Connect, albo Wait_for_orders - // w trybie Connect skanować do tyłu tylko jeśli przed kolejnym sygnałem nie ma taboru do podłączenia - auto const couplinginprogress { - OrderCurrentGet().HasAll(DriverOrder::connect) - && ( Obstacle.distance < std::min(2000.0, FirstSemaphorDist) - || drivingFlags.connect ) }; - if( couplinginprogress ) { return; } - - auto const commandbehind { BackwardScan( Range ) }; - if( commandbehind != TCommandType::cm_Unknown ) { - // jeśli w drugą można jechać - // należy sprawdzać odległość od znalezionego sygnalizatora, - // aby w przypadku prędkości 0.1 wyciągnąć najpierw skład za sygnalizator - // i dopiero wtedy zmienić kierunek jazdy, oczekując podania prędkości >0.5 - if( commandbehind == TCommandType::cm_Command ) { - // jeśli komenda Shunt to ją odbierz bez przemieszczania się (np. odczep wagony po dopchnięciu do końca toru) - drivingFlags.stopHere = true; - } - iDirectionOrder = -iDirection; // zmiana kierunku jazdy - // zmiana kierunku bez psucia kolejnych komend - OrderCurrentSet( (OrderCurrentGet() | DriverOrder::changeDirection) ); - } - } -} - -void -TController::UpdateBrakingHelper() { - - if (HelperState > 0 && -AccDesired < fBrake_a0[0] + 2 * fBrake_a1[0] && mvOccupied->Vel > EU07_AI_NOMOVEMENT) { - HelperState = 0; - } - - switch( HelperState ) { - case 0: { - if( -AccDesired > fBrake_a0[0] + 8 * fBrake_a1[0] ) { - HelperState = 1; - } - break; - } - case 1: { - if( -AccDesired > fBrake_a0[0] + 12 * fBrake_a1[0] ) { - HelperState = 2; - } - break; - } - case 2: { - if( -AccDesired > 0 && -ActualProximityDist > 5 ) { - HelperState = 3; - } - break; - } - default: { - break; - } - } -} - -bool TController::is_train() const { - return TestFlag( mvOccupied->CategoryFlag, 1 ); } - -bool TController::is_car() const { - return TestFlag( mvOccupied->CategoryFlag, 2 ); } - -bool TController::is_emu() const { - return mvControlling->TrainType == train_type::emu; } - -bool TController::is_dmu() const { - return mvControlling->TrainType == train_type::dmu; } - -bool TController::has_diesel_engine() const { - return mvControlling->EngineType == TEngineType::DieselElectric || mvControlling->EngineType == TEngineType::DieselEngine; } - -double TController::DirectionalVel() const { - return mvOccupied->Vel * sign( iDirection * mvOccupied->V ); } - -std::vector DrivingFlags::ActiveNames() const { - std::vector> const flags { - { stopCloser, "StopCloser" }, { stopPoint, "StopPoint" }, { active, "Active" }, { press, "Press" }, - { connect, "Connect" }, { primary, "Primary" }, { late, "Late" }, { stopHere, "StopHere" }, - { startHorn, "StartHorn" }, { startHornNow, "StartHornNow" }, { startHornDone, "StartHornDone" }, - { oerlikons, "Oerlikons" }, { incSpeed, "IncSpeed" }, { trackEnd, "TrackEnd" }, { switchFound, "SwitchFound" }, - { guardSignal, "GuardSignal" }, { visibility, "Visibility" }, { doorOpened, "DoorOpened" }, - { pushPull, "PushPull" }, { signalFound, "SignalFound" }, { stopPointFound, "StopPointFound" }, - { guardOpenDoor, "GuardOpenDoor" }, { departureWarned, "DepartureWarned" } }; - std::vector names; - for( auto const &[ set, name ] : flags ) { - if( set ) { - names.emplace_back( name ); - } - } - return names; -} diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 7ce8c1cf1..945233f6d 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -617,7 +617,7 @@ private: void TableClear(); int TableDirection() { return iTableDirection; } // Ra: stare funkcje skanujące, używane do szukania sygnalizatora z tyłu - bool IsOccupiedByAnotherConsist( TTrack *Track, double const Distance ); + bool IsOccupiedByAnotherConsist( TTrack *Track, double const Distance = 0 ); basic_event *CheckTrackEventBackward( double fDirection, TTrack *Track, TDynamicObject *Vehicle, int const Eventdirection = 1, end const End = end::rear ); TTrack *BackwardTraceRoute( double &fDistance, double &fDirection, TDynamicObject *Vehicle, basic_event *&Event, int const Eventdirection = 1, end const End = end::rear, bool const Untiloccupied = true ); void SetProximityVelocity( double dist, double vel, glm::dvec3 const *pos ); diff --git a/vehicle/ai/consist.cpp b/vehicle/ai/consist.cpp new file mode 100644 index 000000000..d9994df93 --- /dev/null +++ b/vehicle/ai/consist.cpp @@ -0,0 +1,966 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the consist the driver runs: its vehicles, their direction, their brakes, the cab taken + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/mover.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + + +void TController::Activation() +{ // umieszczenie obsady w odpowiednim członie, wykonywane wyłącznie gdy steruje AI + iDirection = iDirectionOrder; // kierunek (względem sprzęgów pojazdu z AI) właśnie został ustalony (zmieniony) + if (iDirection) + { // jeśli jest ustalony kierunek + auto *initialvehicle { pVehicle }; +/* + auto const initiallocalbrakelevel { mvOccupied->LocalBrakePosA }; +*/ + auto const initialspringbrakestate { mvOccupied->SpringBrake.Activate }; + // switch off tempomat + SpeedCntrl( 0.0 ); + mvControlling->DecScndCtrl( 2 ); + // reset controls + ZeroSpeed(); + ZeroDirection(); + mvOccupied->CabOccupied = mvOccupied->CabActive; // użytkownik moze zmienić CabOccupied wychodząc + mvOccupied->CabDeactivisation(); // tak jest w Train.cpp + if (pVehicle->MoverParameters->Couplers[iDirectionOrder < 0 ? end::rear : end::front].CouplingFlag.HasAll(Coupling::control)) { + ZeroLocalBrake(); + if( initialspringbrakestate ) { + mvOccupied->SpringBrakeActivate( false ); + } + // odcięcie na zaworze maszynisty, FVel6 po drugiej stronie nie luzuje + mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos(bh_NP) ); // odcięcie na zaworze maszynisty + BrakeLevelSet( mvOccupied->BrakeCtrlPos ); //ustawienie zmiennej GBH + } + // przejście AI na drugą stronę EN57, ET41 itp. + // TODO: clean this up, there's lot of redundancy with TMoverParameters::ChangeCab() and TTrain::MoveToVehicle() + { + int movedirection { ( iDirection < 0 ? end::rear : end::front ) }; + auto *targetvehicle { pVehicle->FirstFind( movedirection, Coupling::control ) }; + if( pVehicle != targetvehicle ) { + auto *targetvehicledriver { targetvehicle->Mechanik }; // zapamiętanie tego, co ewentualnie tam siedzi, żeby w razie dwóch zamienić miejscami + // move to the new vehicle + targetvehicle->Mechanik = this; // na razie bilokacja + targetvehicle->MoverParameters->SetInternalCommand(VehicleCommand::none, 0, 0); // usunięcie ewentualnie zalegającej komendy (Change_direction?) + if( targetvehicle->DirectionGet() != pVehicle->DirectionGet() ) { + // jeśli są przeciwne do siebie to będziemy jechać w drugą stronę względem zasiedzianego pojazdu + iDirection = -iDirection; + } + // move the other driver to our old vehicle + pVehicle->Mechanik = targetvehicledriver; // wsadzamy tego, co ewentualnie był (podwójna trakcja) + // NOTE: having caboccupied != 0 (by swapping in the driver from the target vehicle) may lead to dysfunctional brake + // TODO: investigate and resolve if necessary + pVehicle->MoverParameters->CabOccupied = targetvehicle->MoverParameters->CabOccupied; + if( pVehicle->Mechanik ) { // not guaranteed, as target vehicle can be empty + pVehicle->Mechanik->BrakeLevelSet( pVehicle->MoverParameters->BrakeCtrlPos ); + } + // finish driver swap + pVehicle = targetvehicle; + } + } + if (pVehicle != initialvehicle) + { // jeśli zmieniony został pojazd prowadzony + ControllingSet(); // utworzenie połączenia do sterowanego pojazdu (może się zmienić) - silnikowy dla EZT + if( mvOccupied->BrakeCtrlPosNo > 0 + && ( BrakeSystem == TBrakeSystem::Pneumatic + || BrakeSystem == TBrakeSystem::ElectroPneumatic ) ) { + mvOccupied->LimPipePress = mvOccupied->PipePress; + mvOccupied->ActFlowSpeed = 0; + } + BrakeLevelSet( mvOccupied->BrakeCtrlPos ); + } + if( mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->ShuntModeAllow ) { + // dla 2Ls150 - przed ustawieniem kierunku - można zmienić tryb pracy + mvControlling->CurrentSwitch(OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt) || fMass > 224000.0); // do tego na wzniesieniu może nie dać rady na liniowym + } + // Ra: to przełączanie poniżej jest tu bez sensu + mvOccupied->CabOccupied = iDirection; // aktywacja kabiny w prowadzonym pojeżdzie (silnikowy może być odwrotnie?) + mvOccupied->CabActivisation(); // uruchomienie kabin w członach + DirectionForward(true); // nawrotnik do przodu + mvOccupied->SpringBrakeActivate( initialspringbrakestate ); +/* + // NOTE: this won't restore local brake if the vehicle has integrated local brake control + // TBD, TODO: fix or let the ai activate the brake again as part of its standard logic? + if (initiallocalbrakelevel > 0.0) // hamowanie tylko jeśli był wcześniej zahamowany (bo możliwe, że jedzie!) + mvOccupied->LocalBrakePosA = initiallocalbrakelevel; // zahamuj jak wcześniej +*/ + if( pVehicle != initialvehicle ) { + auto *train { simulation::Trains.find( initialvehicle->name() ) }; + if( train ) { + train->MoveToVehicle( pVehicle ); + } + } + + CheckVehicles(); // sprawdzenie składu, AI zapali światła + TableClear(); // resetowanie tabelki skanowania torów + } +}; + +void TController::AutoRewident() +{ // autorewident: nastawianie hamulców w składzie + // 1. Zebranie informacji o składzie pociągu, od czoła do końca + std::vector consist; + for (auto const *d = pVehicles[0]; d != nullptr; d = d->Next()) { + consist.emplace_back(brake_setting::describe(*d->MoverParameters, d == pVehicle)); + } + // 2. Określenie typu pociągu i nastaw: by the brake instruction Cw-1 (eu07/maszyna#350), or as the releases before it did. + // brakes are cut out (Cw-1 §19.9) only in a train (a bank engine's run included), not in a consist being shunted + auto const train{brake_setting::runs_as_train(OrderCurrentGet())}; + auto const settings{Global.AIBrakeSettingCw1 ? brake_setting::choose(consist, train) : brake_setting::choose_legacy(consist)}; + // and only at a standstill, the train creeping to a stop included: a check on the run (the order changed mid-run, or + // the train was just formed by coupling, which the AI does above that speed) leaves them to reinspect_brakes() + auto const standstill{brake_setting::at_standstill(mvOccupied->Vel)}; + auto reinspect{false}; + // a light engine counts as a passenger train for the braking below + auto const passengertrain{brake_setting::passenger(brake_setting::choose_train_setting(consist))}; + // 3. Nastawianie + auto setting{settings.begin()}; + for (auto *d = pVehicles[0]; d != nullptr && setting != settings.end(); d = d->Next(), ++setting) { + if (false == AIControllFlag && d == pVehicle) { + // don't touch human-controlled vehicle, but others are free game + continue; + } + // the setting, a brake cut out in a train on G (Cw-1 §19.9) or put back when the train no longer needs it cut out + if (brake_setting::apply(*d->MoverParameters, *setting, standstill)) { + // a brake to cut out, with the train moving: left for the next standstill + reinspect = true; + } + // potentially release manual brake + d->MoverParameters->DecManualBrakeLevel( ManualBrakePosNo ); + d->MoverParameters->SpringBrake.Activate = false; + } + BrakeReinspectionPending = reinspect; + //ustawianie trybu pracy zadajnika hamulca, wystarczy raz po inicjalizacji AI + if( true == AIControllFlag ) { + // if a human is in charge leave the brake mode up to them, otherwise do as you like + for( int i = 1; i <= 8; i *= 2 ) { + if( ( mvOccupied->BrakeOpModes & i ) > 0 ) { + mvOccupied->BrakeOpModeFlag = i; + } + } + } + + // teraz zerujemy tabelkę opóźnienia hamowania + for (int i = 0; i < BrakeAccTableSize; ++i) + { + fBrake_a0[i+1] = 0; + fBrake_a1[i+1] = 0; + } + + if( OrderCurrentGet() & ( DriverOrder::shunt | DriverOrder::looseShunt ) ) { + // for uniform behaviour and compatibility with older scenarios set default acceleration table values for shunting + fAccThreshold = is_emu() ? -0.55 : is_dmu() ? -0.45 : -0.2; + // HACK: emu with induction motors need to start their braking a bit sooner than the ones with series motors + if( is_emu() + && mvControlling->EngineType == TEngineType::ElectricInductionMotor ) { + fAccThreshold += 0.10; + } + fNominalAccThreshold = fAccThreshold; + } + + BrakeSystem = consist_brake_system(); + // Change the EP fuse state only when AI is in charge, don't fiddle with controls when the user is controlling the vehicle + if (AIControllFlag) { + mvOccupied->EpFuseSwitch(BrakeSystem == TBrakeSystem::ElectroPneumatic); + } + + if( OrderCurrentGet() & ( DriverOrder::obeyTrain | DriverOrder::bank ) ) { + // 4. Przeliczanie siły hamowania + double const velstep = mvOccupied->Vmax * 0.5 / BrakeAccTableSize; + auto *d = pVehicles[0]; // pojazd na czele składu + while (d) { + // a vehicle with its brake cut out (by the inspector above or for a reason of its own) adds its mass only; + // the inspector of the earlier releases counted its brake in + auto const brakes{false == Global.AIBrakeSettingCw1 || false == brake_setting::is_cut_out(*d->MoverParameters)}; + for( int i = 0; i < BrakeAccTableSize && brakes; ++i ) { + fBrake_a0[ i + 1 ] += d->MoverParameters->BrakeForceR( 0.25, velstep*( 1 + 2 * i ) ); + fBrake_a1[ i + 1 ] += d->MoverParameters->BrakeForceR( 1.00, velstep*( 1 + 2 * i ) ); + } + d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) + } + for (int i = 0; i < BrakeAccTableSize; ++i) + { + fBrake_a1[i+1] -= fBrake_a0[i+1]; + fBrake_a0[i+1] /= fMass; + fBrake_a0[i + 1] += 0.001*velstep*(1 + 2 * i); + fBrake_a1[i+1] /= 12 * fMass; + } + + IsPassengerTrain = is_train() && false == is_emu() && false == is_dmu() && (mvOccupied->BrakeDelayFlag & bdelay_G) == 0; + IsCargoTrain = is_train() && (mvOccupied->BrakeDelayFlag & bdelay_G) != 0; + IsHeavyCargoTrain = true == IsCargoTrain && fBrake_a0[1] > 0.4 && iVehicles - ControlledEnginesCount > 0 && fMass / iVehicles > 50000; + + BrakingInitialLevel = IsHeavyCargoTrain ? 1.25 : IsCargoTrain ? 1.25 : 1.00; + + BrakingLevelIncrease = 0.25; + + if( is_emu() ) { + auto ep_factor { ( BrakeSystem == TBrakeSystem::ElectroPneumatic ? 8 : 4 ) }; + if( mvControlling->EngineType == TEngineType::ElectricInductionMotor ) { + // HACK: emu with induction motors need to start their braking a bit sooner than the ones with series motors + fNominalAccThreshold = std::max( -0.60, -fBrake_a0[ BrakeAccTableSize ] - ep_factor * fBrake_a1[ BrakeAccTableSize ] ); + } + else { + fNominalAccThreshold = std::max( -0.75, -fBrake_a0[ BrakeAccTableSize ] - ep_factor * fBrake_a1[ BrakeAccTableSize ] ); + } + fBrakeReaction = 0.25; + } + else if( is_dmu() ) { + fNominalAccThreshold = std::max( -0.75, -fBrake_a0[ BrakeAccTableSize ] - 8 * fBrake_a1[ BrakeAccTableSize ] ); + fBrakeReaction = 0.25; + } + else if (passengertrain) { + fNominalAccThreshold = -fBrake_a0[ BrakeAccTableSize ] - 4 * fBrake_a1[ BrakeAccTableSize ]; + fBrakeReaction = 1.00 + fLength*0.004; + } + else { + fNominalAccThreshold = -fBrake_a0[ BrakeAccTableSize ] - 1 * fBrake_a1[ BrakeAccTableSize ]; + fBrakeReaction = 1.00 + fLength*0.005; + } + fAccThreshold = fNominalAccThreshold; + } + +} + +// a brake the inspector had to cut out (Cw-1 §19.9) while the train was moving gets cut out once the train stands. +// a train formed by coupling is looked at as the buffers meet, above the speed the inspector takes for a standstill, +// and with no stop ahead nothing would look at it standing again (eu07/maszyna#350) +void TController::reinspect_brakes() +{ + if (false == BrakeReinspectionPending) { + return; + } + if (false == brake_setting::runs_as_train(OrderCurrentGet())) { + // no longer a train: nothing is cut out in a consist being shunted + BrakeReinspectionPending = false; + return; + } + if (brake_setting::at_standstill(mvOccupied->Vel)) { + // standing, the inspector leaves nothing for later: this clears the flag + AutoRewident(); + } +} + +int TController::CheckDirection() { + + int d = mvOccupied->DirAbsolute; // który sprzęg jest z przodu + if( !d ) { + // jeśli nie ma ustalonego kierunku to jedziemy wg aktualnej kabiny + d = mvOccupied->CabActive; + } + return d; +} + +bool TController::CheckVehicles(DriverOrders user) +{ // sprawdzenie stanu posiadanych pojazdów w składzie i zapalenie świateł + TDynamicObject *p; // roboczy wskaźnik na pojazd + iVehicles = 0; // ilość pojazdów w składzie + auto d = CheckDirection(); + d = d >= 0 ? 0 : 1; // kierunek szukania czoła (numer sprzęgu) + p = pVehicle->FirstFind(d); // pojazd na czele składu + if (!p) + p = pVehicle; + auto *const frontvehicle { p }; // stays the consist head for the rest of this check + pVehicles[end::front] = frontvehicle; + // liczenie pojazdów w składzie i ustalenie parametrów + auto dir = d = 1 - d; // a dalej będziemy zliczać od czoła do tyłu + fLength = 0.0; // długość składu do badania wyjechania za ograniczenie + fMass = 0.0; // całkowita masa do liczenia stycznej składowej grawitacji + fVelMax = -1; // ustalenie prędkości dla składu + bool main = true; // czy jest głównym sterującym + drivingFlags.oerlikons = true; // zakładamy, że są same Oerlikony + // Ra 2014-09: ustawić moveMultiControl, jeśli wszystkie są w ukrotnieniu (i skrajne mają kabinę?) + while (p) + { // sprawdzanie, czy jest głównym sterującym, żeby nie było konfliktu + if( p->Mechanik // jeśli ma obsadę + && p->Mechanik != this && p->Mechanik->drivingFlags.primary ) { // ale chodzi o inny pojazd, niż aktualnie sprawdzający + // a tamten ma priorytet + // TODO: take into account drivers' operating modes, one or more of them might be on banking duty + if (drivingFlags.primary && mvOccupied->DirAbsolute && mvOccupied->BrakeCtrlPos >= -1) + { + // jeśli rządzi i ma kierunek + p->Mechanik->primary(false); // dezaktywuje tamtego + p->Mechanik->ZeroLocalBrake(); + p->MoverParameters->BrakeLevelSet(p->MoverParameters->Handle->GetPos(bh_NP)); // odcięcie na zaworze maszynisty + p->Mechanik->BrakeLevelSet(p->MoverParameters->BrakeCtrlPos); // ustawienie zmiennej GBH + } + else + { + main = false; // nici z rządzenia + } + } + ++iVehicles; // jest jeden pojazd więcej + pVehicles[end::rear] = p; // zapamiętanie ostatniego + fLength += p->MoverParameters->Dim.L; // dodanie długości pojazdu + fMass += p->MoverParameters->TotalMass; // dodanie masy łącznie z ładunkiem + fVelMax = min_speed( fVelMax, p->MoverParameters->Vmax ); // ustalenie maksymalnej prędkości dla składu + // reset oerlikon brakes consist flag as different type was detected + if( p->MoverParameters->BrakeSubsystem != TBrakeSubSystem::ss_ESt + && p->MoverParameters->BrakeSubsystem != TBrakeSubSystem::ss_LSt ) { + drivingFlags.oerlikons = false; + } + p = p->Neighbour(dir); // pojazd podłączony od wskazanej strony + } + if( main ) { + drivingFlags.primary = true; // nie znaleziono innego, można się porządzić + } + + ControllingSet(); // ustalenie członu do sterowania (może być inny niż zasiedziany) + + if (drivingFlags.primary) + { // jeśli jest aktywnie prowadzącym pojazd, może zrobić własny porządek + auto pantmask = 1; + p = frontvehicle; + // establish ownership and vehicle order + while (p) + { + if (p->MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) + { // jeśli pojazd posiada pantograf, to przydzielamy mu maskę, którą będzie informował o jeździe bezprądowej + p->iOverheadMask = pantmask; + pantmask = pantmask << 1; // przesunięcie bitów, max. 32 pojazdy z pantografami w składzie + } + + d = p->DirectionSet(d ? 1 : -1); // zwraca położenie następnego (1=zgodny,0=odwrócony - względem czoła składu) + p->ctOwner = this; // dominator oznacza swoje terytorium + p = p->Next(); // pojazd podłączony od tyłu (licząc od czoła) + } + // with the order established the virtual train manager can do their work + p = frontvehicle; + ControlledEnginesCount = p->MoverParameters->Power > 1.0 ? 1 : 0; + auto hasheaters { false }; + while (p) + { + if( p != pVehicle ) { + if( false == p->is_connected( pVehicle, Coupling::control ) ) { + // NOTE: don't set battery in controllable vehicles, let the user/ai do it explicitly + // HACK: wagony muszą mieć baterię załączoną do otwarcia drzwi... + p->MoverParameters->BatterySwitch( true ); + // enable heating and converter in carriages with can be heated + if( p->MoverParameters->HeatingPower > 0 ) { + p->MoverParameters->HeatingAllow = true; + p->MoverParameters->ConverterSwitch( true, range_t::local ); + hasheaters = true; + } + } + else { + if( p->MoverParameters->Power > 1.0 ) { + ++ControlledEnginesCount; + } + } + } + + if( p->asDestination == "none" ) { + p->DestinationSet( TrainParams.Relation2, TrainParams.TrainName ); // relacja docelowa, jeśli nie było + } + if( AIControllFlag ) { // jeśli prowadzi komputer + p->RaLightsSet( 0, 0 ); // gasimy światła + } + p = p->Next(); // pojazd podłączony od tyłu (licząc od czoła) + } + + if( user == DriverOrder::connect && true == main ) { + // HACK: with additional vehicles in the consist ensure all linked vehicles are set to move in the same direction + if( pVehicle->Prev(Coupling::control) != nullptr + || pVehicle->Next(Coupling::control) != nullptr ) { + sync_consist_reversers(); + } + // potentially sync compartment lighting state for the newly connected vehicles + if( mvOccupied->CompartmentLights.start_type == start_t::manual ) { + mvOccupied->CompartmentLightsSwitchOff( mvOccupied->CompartmentLights.is_disabled ); + mvOccupied->CompartmentLightsSwitch( mvOccupied->CompartmentLights.is_enabled ); + } + } + + // kasowanie pamieci hamowania kontrolnego + if (OrderCurrentGet() & (DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::disconnect | DriverOrder::connect | DriverOrder::changeDirection)) { + DynamicBrakeTest = 0; + DBT_VelocityBrake + = DBT_VelocityRelease + = DBT_VelocityFinish + = DBT_BrakingTime + = DBT_ReleasingTime + = DBT_MidPointAcc + = 0; + } + + if( brake_setting::inspects_train( OrderCurrentGet(), user == DriverOrder::connect ) ) { + // nastawianie hamulca do jazdy pociągowej + AutoRewident(); +/* + if( ( true == drivingFlags.connect ) + && ( true == OrderCurrentGet().HasAll(DriverOrder::connect) ) ) { + iCoupler = {}; // dalsza jazda manewrowa już bez łączenia + drivingFlags.connect = false; // zdjęcie flagi doczepiania + SetVelocity( 0, 0, stopJoin ); // wyłączyć przyspieszanie + JumpToNextOrder(); // wykonanie następnej komendy + } +*/ + } + + // detect push-pull train configurations and mark them accordingly + if( frontvehicle->is_connected( pVehicles[ end::rear ], Coupling::control ) ) { + // zmiana czoła przez zmianę kabiny + drivingFlags.pushPull = true; + } + else { + // zmiana czoła przez manewry + drivingFlags.pushPull = false; + } + + // HACK: ensure vehicle lights are active from the beginning, if it had pre-activated battery + if( mvOccupied->LightsPosNo > 0 ) { + pVehicle->SetLights(); + } + if( iEngineActive ) { + // potentially adjust light state + control_lights(); + // custom ai action for disconnect mode: switch off lights on disconnected vehicle(s) + if( is_train() && true == OrderCurrentGet().HasAll(DriverOrder::disconnect) && AIControllFlag ) { + // światła manewrowe (Tb1) tylko z przodu, aby nie pozostawić odczepionego ze światłem + if (mvOccupied->DirActive >= 0) + { // jak ma kierunek do przodu + pVehicles[end::rear]->RaLightsSet(-1, 0); + } + else + { // jak dociska + frontvehicle->RaLightsSet(0, -1); + } + } + // enable door locks + cue_action( driver_hint::consistdoorlockson ); + // potentially enable train heating + { + auto const ispassengertrain { IsPassengerTrain && iVehicles - ControlledEnginesCount > 0 }; + // TODO: replace connection test with connection check between last engine and first car, specifically + auto const isheatingcouplingactive { ( + ControlledEnginesCount == 1 ? + frontvehicle->is_connected( pVehicles[ end::rear ], Coupling::heating ) : + true ) }; + auto const isheatingneeded { + (is_emu() || is_dmu() ? true : + false == OrderCurrentGet().HasAny(DriverOrder::obeyTrain | DriverOrder::bank) ? false : + false == isheatingcouplingactive ? false : + ispassengertrain ? hasheaters : + false) }; + if( mvControlling->HeatingAllow != isheatingneeded ) { + cue_action( + isheatingneeded ? + driver_hint::consistheatingon : + driver_hint::consistheatingoff ); + } + } + } + + if( user == DriverOrder::connect + || user == DriverOrder::disconnect ) { + // HACK: force route table update on consist change, new consist length means distances to points of interest are now wrong + iTableDirection = 0; + } + } // blok wykonywany, gdy aktywnie prowadzi + return true; +} + +void TController::Lights(int head, int rear) +{ // zapalenie świateł w skłądzie + pVehicles[ end::front ]->RaLightsSet(head, -1); // zapalenie przednich w pierwszym + pVehicles[ end::rear ]->RaLightsSet(-1, rear); // zapalenie końcówek w ostatnim +} + +void TController::DirectionInitial() +{ // ustawienie kierunku po wczytaniu trainset (może jechać na wstecznym + mvOccupied->CabActivisationAuto(); // załączenie rozrządu (wirtualne kabiny) + if (mvOccupied->Vel > EU07_AI_NOMOVEMENT) + { // jeśli na starcie jedzie + iDirection = iDirectionOrder = + mvOccupied->V > 0 ? 1 : -1; // początkowa prędkość wymusza kierunek jazdy + DirectionForward(mvOccupied->V * mvOccupied->CabActive >= 0.0); // a dalej ustawienie nawrotnika + } + CheckVehicles(); // sprawdzenie świateł oraz skrajnych pojazdów do skanowania +}; + +void TController::DirectionChange() { + + auto const initialstate { iDirection }; + iDirection = CheckDirection(); + if( iDirection != initialstate ) { + CheckVehicles( DriverOrder::changeDirection ); + } +} + +int TController::OrderDirectionChange(int newdir, TMoverParameters *Vehicle) +{ // zmiana kierunku jazdy, niezależnie od kabiny + int testd = newdir; + if (Vehicle->Vel < 0.5) + { // jeśli prawie stoi, można zmienić kierunek, musi być wykonane dwukrotnie, bo za pierwszym razem daje na zero + switch (newdir * Vehicle->CabActive) + { // DirectionBackward() i DirectionForward() to zmiany względem kabiny + case -1: // if (!Vehicle->DirectionBackward()) testd=0; break; + DirectionForward(false); + break; + case 1: // if (!Vehicle->DirectionForward()) testd=0; break; + DirectionForward(true); + break; + } + if (testd == 0) + VelforDriver = -1; // kierunek został zmieniony na żądany, można jechać + } + else // jeśli jedzie + VelforDriver = 0; // ma się zatrzymać w celu zmiany kierunku + if (Vehicle->DirActive == 0 && VelforDriver < Vehicle->Vel) // Ra: to jest chyba bez sensu + IncBrake(); // niech hamuje + if (Vehicle->DirActive == testd * Vehicle->CabActive) + VelforDriver = -1; // można jechać, bo kierunek jest zgodny z żądanym + if (is_emu() && Vehicle->DirActive > 0) + // if () //tylko jeśli jazda pociągowa (tego nie wiemy w momencie odpalania silnika) + Vehicle->DirectionForward(); + // Ra: z przekazaniem do silnikowego + return (int)VelforDriver; // zwraca prędkość mechanika +} + +void TController::DirectionForward(bool forward) +{ // ustawienie jazdy do przodu dla true i do tyłu dla false (zależy od kabiny) + ZeroSpeed( true ); // TODO: check if force switch is needed anymore here + // HACK: make sure the master controller isn't set in position which prevents direction change + mvControlling->MainCtrlPos = std::min( mvControlling->MainCtrlPos, mvControlling->MainCtrlMaxDirChangePos ); + + if( forward ) { + // do przodu w obecnej kabinie + while( mvOccupied->DirActive <= 0 + && mvOccupied->DirectionForward() ) { + // force scan table update + iTableDirection = 0; + } + } + else { + // do tyłu w obecnej kabinie + while( mvOccupied->DirActive >= 0 + && mvOccupied->DirectionBackward() ) { + // force scan table update + iTableDirection = 0; + } + } + if( mvOccupied->TrainType == train_type::sn61 ) { + // specjalnie dla SN61 żeby nie zgasł + while( mvControlling->RList[mvControlling->MainCtrlPos].Mn == 0 + && mvControlling->IncMainCtrl(1) ) { + ; // all work is done in the header + } + } +} + +void TController::ZeroDirection() { + + while( mvOccupied->DirActive > 0 && mvOccupied->DirectionBackward() ) { ; } + while( mvOccupied->DirActive < 0 && mvOccupied->DirectionForward() ) { ; } +} + +void TController::sync_consist_reversers() { + + auto const currentdirection { mvOccupied->DirActive }; + auto const fastforward { is_emu() && mvOccupied->EngineType != TEngineType::ElectricInductionMotor + && mvOccupied->Imin == mvOccupied->IminHi }; + + // move reverser all way in the opposite direction... + for( auto idx = 0; idx < 3; ++idx ) { + if( currentdirection >= 0 ) { + mvOccupied->DirectionBackward(); + } + else { + mvOccupied->DirectionForward(); + + } + } + // ...then restore original setting + while( mvOccupied->DirActive != currentdirection ) { + if( false == ( + currentdirection >= 0 ? + mvOccupied->DirectionForward() : + mvOccupied->DirectionBackward() ) ) { + // sanity check for potential endless loop + break; + } + } + // potentially restore 'fast forward' setting + if( currentdirection > 0 && true == fastforward ) { + mvOccupied->DirectionForward(); + } +} + +void TController::MoveTo(TDynamicObject *to) +{ // przesunięcie AI do innego pojazdu (przy zmianie kabiny) + if( to->Mechanik != nullptr + && to->Mechanik != this ) { + // ai controller thunderdome, there can be only one + if( to->Mechanik->AIControllFlag ) { + if( to->Mechanik->primary() ) { + // take over boss duties + primary( true ); + } + SafeDelete( to->Mechanik ); + } + else { + // can't quite delete a human + if( AIControllFlag ) { + delete this; + } + return; + } + } + pVehicle->Mechanik = nullptr; + pVehicle = to; + ControllingSet(); // utworzenie połączenia do sterowanego pojazdu + pVehicle->Mechanik = this; + +}; + +void TController::ControllingSet() +{ // znajduje człon do sterowania w EZT będzie to silnikowy + // problematyczne jest sterowanie z członu biernego, dlatego damy AI silnikowy + // dzięki temu będzie wirtualna kabina w silnikowym, działająca w rozrządczym + // w plikach FIZ zostały zgubione ujemne maski sprzęgów, stąd problemy z EZT + if( pVehicle == nullptr ) { + // a driver of no vehicle has nothing to control + return; + } + mvOccupied = pVehicle->MoverParameters; // domyślny skrót do obiektu parametrów + BrakeSystem = mvOccupied->BrakeSystem; // domyślny sposób hamowania + mvControlling = pVehicle->FindPowered()->MoverParameters; // poszukiwanie członu sterowanego + { + auto *lookup { pVehicle->FindPantographCarrier() }; + mvPantographUnit = lookup != nullptr ? lookup->MoverParameters : mvControlling; + } + BrakeSystem = consist_brake_system(); +}; + +void +TController::determine_consist_state() { + // ABu-160305 testowanie gotowości do jazdy + // Ra: przeniesione z DynObj, skład użytkownika też jest testowany, żeby mu przekazać, że ma odhamować + + if (mvOccupied->CabActive == 0 && mvOccupied->Power24vIsAvailable) + { + cue_action( driver_hint::cabactivation ); + } + else if (!mvOccupied->AutomaticCabActivation + && ( mvOccupied->CabActive == -mvOccupied->CabOccupied || !mvOccupied->CabMaster || !mvOccupied->Power24vIsAvailable ) ) + { + cue_action( driver_hint::cabdeactivation ); + } + + int index = double(BrakeAccTableSize) * (mvOccupied->Vel / mvOccupied->Vmax); + index = std::min(BrakeAccTableSize, std::max(1, index)); + fBrake_a0[0] = fBrake_a0[index]; + fBrake_a1[0] = fBrake_a1[index]; + + if (is_emu() || is_dmu()) { + auto Coeff = std::clamp( mvOccupied->Vel*0.015 , 0.5 , 1.0); + fAccThreshold = fNominalAccThreshold * Coeff - fBrake_a0[BrakeAccTableSize] * (1.0 - Coeff); + } + + Ready = true; // wstępnie gotowy + fReady = 0.0; // założenie, że odhamowany + IsConsistBraked = mvOccupied->BrakeSystem == TBrakeSystem::ElectroPneumatic && false == ForcePNBrake ? mvOccupied->BrakePress > 2.0 : + mvOccupied->PipePress < std::max(3.9, mvOccupied->BrakePressureActual.PipePressureVal) + 0.1; + fAccGravity = 0.0; // przyspieszenie wynikające z pochylenia + IsAnyCouplerStretched = false; + IsAnyDoorOnlyOpen[ side::right ] = IsAnyDoorOnlyOpen[ side::left ] = false; + IsAnyDoorOpen[ side::right ] = IsAnyDoorOpen[ side::left ] = false; + IsAnyDoorPermitActive[ side::right ] = IsAnyDoorPermitActive[ side::left ] = false; + auto doorclosure { door_closure_t::none }; + ConsistShade = 0.0; + auto *p { pVehicles[ end::front ] }; // pojazd na czole składu + double dy; // składowa styczna grawitacji, w przedziale <0,1> + // starting uphill the power is applied against the train brake on purpose, until the power holds the train and + // then while the brake releases + auto const heldforstart { bUphillStart }; + auto released { true }; // the brakes are off, the hold of an uphill start not counted + auto mostapplied { 0.0 }; // the most applied brake, the hold of an uphill start not counted + auto momentum { 0.0 }; + auto chargelevel { std::numeric_limits::max() }; // the lowest pipe or auxiliary reservoir pressure of a working brake + while (p) + { // sprawdzenie odhamowania wszystkich połączonych pojazdów + auto *vehicle { p->MoverParameters }; + auto const bp { std::max( 0.0, vehicle->BrakePress - ( vehicle->SpeedCtrlUnit.Parking ? vehicle->MaxBrakePress[ 0 ] * vehicle->StopBrakeDecc : 0.0 ) ) }; + momentum += vehicle->TotalMass * vehicle->V * ( p->DirectionGet() == iDirection ? 1 : -1 ); + mostapplied = std::max( bp, mostapplied ); + if( ( vehicle->BrakeSystem != TBrakeSystem::Individual ) + && ( vehicle->MaxBrakePress[ 3 ] > 0.0 ) + && ( false == TestFlag( vehicle->Hamulec->GetBrakeStatus(), b_dmg ) ) ) { // a brake cut out doesn't count + chargelevel = std::min( { chargelevel, vehicle->PipePress, vehicle->Hamulec->GetBRP() } ); + } + auto const wasready { Ready }; + if( released || Ready ) { + // bo jak coś nie odhamowane, to dalej nie ma co sprawdzać + auto const isbraking { TestFlagAny( vehicle->Hamulec->GetBrakeStatus(), b_hld | b_on ) }; + if( vehicle->Vel < 1.0 ? + isbraking || bp > 0.4 : // ensure the brakes are sufficiently released when starting to move + // once in motion a brake down to 0.4 bar counts as released (UIC), even if its distributor + // is still in the lap position while the brake pipe recharges + ( isbraking && bp > 0.4 ) || vehicle->Fb > 10000.0 ) { // 10 kN + released = false; + // ready all the same with the power going on against the brake on purpose: at a standstill, and once + // the power holds the train, while the brake releases; otherwise in motion a braking force left + // anywhere in the train (a hand brake) stops it as before + Ready = Ready && heldforstart && ( bUphillRelease || ( vehicle->Vel < 1.0 ) ); + } + } + if( wasready ) { + // Ra: odluźnianie przeładowanych lokomotyw, ciągniętych na zimno - prowizorka... + if( bp >= 0.4 && (AIControllFlag || Global.AITrainman && mvOccupied->Vel < EU07_AI_NOMOVEMENT && !is_emu() && !is_dmu()) && BrakeCtrlPosition == gbh_RP // jest pozycja jazdy + && false == TestFlag(vehicle->Hamulec->GetBrakeStatus(), b_dmg) // brake isn't broken + && vehicle->PipePress - mvOccupied->Handle->GetRP() > -0.1 // jeśli ciśnienie jak dla jazdy + && vehicle->Hamulec->GetCRP() > vehicle->PipePress + 0.12 ) { // wg UIC określone sztywno na 0.04 + // za dużo w zbiorniku + // indywidualne luzowanko + vehicle->BrakeReleaser(1); + } + if (bp < 0.1 && (AIControllFlag || Global.AITrainman) && false == TestFlag(vehicle->Hamulec->GetBrakeStatus(), b_dmg) // brake isn't broken + && vehicle->Hamulec->GetCRP() < vehicle->PipePress - 0.1) { + // już nie jest za dużo w zbiorniku + // koniec indywidualnego luzowanka + vehicle->BrakeReleaser(0); + } + } + // the brake held for the start counts again once it is being released + fReady = std::max( ( heldforstart && ( false == bUphillRelease ) ) ? 0.0 : bp, fReady ); // szukanie najbardziej zahamowanego + if( ( dy = p->VectorFront().y ) != 0.0 ) { + // istotne tylko dla pojazdów na pochyleniu + // ciężar razy składowa styczna grawitacji + fAccGravity -= vehicle->TotalMassxg * dy * ( p->DirectionGet() == iDirection ? 1 : -1 ); + } + // check coupler state + IsAnyCouplerStretched = + IsAnyCouplerStretched + || vehicle->Couplers[end::front].stretch_duration > 0.0 + || vehicle->Couplers[end::rear].stretch_duration > 0.0; + // check door state + { + auto const switchsides{ p->DirectionGet() != (iDirection == 0 ? mvOccupied->CabOccupied : iDirection) }; + auto const &rightdoor { vehicle->Doors.instances[ ( switchsides ? side::left : side::right ) ] }; + auto const &leftdoor { vehicle->Doors.instances[ ( switchsides ? side::right : side::left ) ] }; + if( vehicle->Doors.close_control != control_t::autonomous ) { + IsAnyDoorOpen[ side::right ] |= false == rightdoor.is_closed; + IsAnyDoorOpen[ side::left ] |= false == leftdoor.is_closed; + } + if (vehicle->Doors.close_control != control_t::autonomous) { + IsAnyDoorOnlyOpen[ side::right ] |= false == rightdoor.is_door_closed; + IsAnyDoorOnlyOpen[ side::left ] |= false == leftdoor.is_door_closed; + } + if( vehicle->Doors.permit_needed ) { + IsAnyDoorPermitActive[ side::right ] |= rightdoor.open_permit; + IsAnyDoorPermitActive[ side::left ] |= leftdoor.open_permit; + } + doorclosure = std::max( doorclosure, vehicle->door_closure() ); + } + // measure lighting level + // TBD: apply weight (multiplier) to partially lit vehicles? + ConsistShade += p->fShade > 0.0 ? p->fShade : 1.0; + p = p->Next(); // pojazd podłączony z tyłu (patrząc od czoła) + } + DoorClosure = doorclosure; + // calculate average amount of received sunlight + ConsistShade /= iVehicles; + + // test state of main devices in all vehicles under control + IsAnyConverterOverloadRelayOpen = false; + IsAnyMotorOverloadRelayOpen = false; + IsAnyGroundRelayOpen = false; + IsAnyLineBreakerOpen = false; + IsAnyCompressorPresent = false; + IsAnyCompressorEnabled = false; + IsAnyCompressorExplicitlyEnabled = false; + IsAnyConverterPresent = false; + IsAnyConverterEnabled = false; + IsAnyConverterExplicitlyEnabled = false; + // whether the line contactors of a vehicle wait for its own converter (LineContactorsInterlock), off with its local switch + auto islocalconverterswitchoff { false }; + + pVehicle->for_each( + Coupling::control, + [this, &islocalconverterswitchoff]( TDynamicObject * Vehicle ) { + auto const *vehicle { Vehicle->MoverParameters }; + islocalconverterswitchoff |= vehicle->LineContactorsHeldByLocalConverterSwitch(); + IsAnyConverterOverloadRelayOpen |= vehicle->ConvOvldFlag; + IsAnyMotorOverloadRelayOpen |= vehicle->FuseFlag; + IsAnyGroundRelayOpen |= !vehicle->GroundRelay; + IsAnyCompressorPresent |= vehicle->CompressorSpeed > 0.0; + IsAnyCompressorEnabled |= vehicle->CompressorSpeed > 0.0 ? (vehicle->CompressorAllow || vehicle->CompressorStart == start_t::automatic) && vehicle->CompressorAllowLocal : false; + IsAnyCompressorExplicitlyEnabled |= vehicle->CompressorSpeed > 0.0 ? vehicle->CompressorAllow && vehicle->CompressorAllowLocal : false; + IsAnyConverterPresent |= vehicle->ConverterStart != start_t::disabled; + IsAnyConverterEnabled |= ( vehicle->ConverterAllow || vehicle->ConverterStart == start_t::automatic ) && vehicle->ConverterAllowLocal; + IsAnyConverterExplicitlyEnabled |= vehicle->ConverterAllow && vehicle->ConverterAllowLocal; + if( vehicle->Power > 0.01 ) { + IsAnyLineBreakerOpen |= !vehicle->Mains; } } ); + + // siłę generują pojazdy na pochyleniu ale działa ona całość składu, więc a=F/m + fAccGravity *= iDirection >= 0 ? 1 : -1; + fAccGravity /= fMass; + { + auto absaccs { fAccGravity }; // Ra 2014-03: jesli skład stoi, to działa na niego składowa styczna grawitacji + if( mvOccupied->Vel > EU07_AI_NOMOVEMENT ) { + absaccs = 0; + auto *d = pVehicles[ end::front ]; // pojazd na czele składu + while( d ) { + absaccs += d->MoverParameters->TotalMass * d->MoverParameters->AccS * ( d->DirectionGet() == iDirection ? 1 : -1 ); + d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) + } + absaccs *= iDirection >= 0 ? 1 : -1; + absaccs /= fMass; + } + AbsAccS = absaccs; + } +#if LOGVELOCITY + WriteLog( "Vel=" + to_string( DirectionalVel() ) + ", AbsAccS=" + to_string( AbsAccS ) + ", AccGrav=" + to_string( fAccGravity ) ); +#endif + + if( !Ready // v367: jeśli wg powyższych warunków skład nie jest odhamowany + && fAccGravity < -0.05 // jeśli ma pod górę na tyle, by się stoczyć + && fReady < 0.8 ) { // delikatniejszy warunek, obejmuje wszystkie wagony + Ready = true; //żeby uznać za odhamowany + } + // the same test without the hold of an uphill start + IsConsistReleased = released || ( fAccGravity < -0.05 && mostapplied < 0.8 ); + // the frame of the vehicle the AI drives from, as for fAccGravity and AbsAccS + fConsistVelocity = 3.6 * momentum / std::max( 1.0, fMass ) * ( iDirection >= 0 ? 1 : -1 ); + // standing, the train starts only with its brakes charged: released alone, a train prepared from cold has no air to + // brake with while its auxiliary reservoirs fill. with the train brake applied (held for an uphill start, a light + // application while charging) they charge to what the head of the pipe has. + // only the start the charge is in question for: the first after the train was prepared standing, or one with the + // pipe near empty (after an emergency application, brake_charge::empty_level). after an ordinary stop the + // reservoirs refill as the brake releases, and waiting for the last tenths of a bar there only delays the train and + // those behind it. + // and only the pneumatic brake: multiple units with the electro-pneumatic one start as before + if( mvOccupied->Vel > 1.0 ) { + // the start is made. a shunting engine coupling wagons moves at a walking pace: a higher speed would leave its + // every start the first, waiting for each cut of wagons placed cold to charge + bBrakeChargeStart = false; + bBrakeChargeHold = false; + bHasRun = true; + } + auto const chargeable { + ( BrakeSystem == TBrakeSystem::Pneumatic ) + && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) + && ( chargelevel < std::numeric_limits::max() ) }; + if( chargeable && ( chargelevel < brake_charge::empty_level ) ) { + bBrakeChargeStart = true; + } + if( chargeable && bBrakeChargeStart ) { + if( ( VelDesired <= 0.0 ) || ( AccDesired <= EU07_AI_NOACCELERATION ) ) { + // to stand: the next start is checked anew + BrakeCharge.going = false; + } + auto const trainbrakeapplied { + AIControllFlag ? + BrakeCtrlPosition > 0.0 : + // a human driver's handle, which BrakeCtrlPosition doesn't follow + mvOccupied->fBrakeCtrlPos > mvOccupied->Handle->GetPos( bh_RP ) + 0.2 }; + auto const reference { + brake_charge::reference( mvOccupied->PipePress, std::min( mvOccupied->Handle->GetRP(), 5.0 ), trainbrakeapplied ) }; + // air to charge with: the engine prepared, the main reservoir above what the pipe charges to, and the driver's + // brake valve feeding the pipe at the head of the train. a train still being prepared from cold can't charge, + // nor one whose pipe is locked (unlocked by control_releaser()): it waits without that counting as a stall, held + // by its brakes as it can't release them either + auto const supplied { + iEngineActive + && ( std::max( mvControlling->Compressor, mvOccupied->Compressor ) > reference ) + && ( mvOccupied->PipePress >= reference - brake_charge::margin ) }; + auto const wasstalled { BrakeCharge.stalled }; + IsConsistCharged = brake_charge::charged( BrakeCharge, chargelevel, reference, ElapsedTime, supplied ); + if( BrakeCharge.stalled && ( false == wasstalled ) ) { + WriteLog( + "AI: " + mvOccupied->Name + " stopped charging its brakes at " + to_string( chargelevel, 2 ) + + " bar of " + to_string( reference, 2 ) + ", starting all the same" ); + } + if( false == IsConsistCharged ) { + // a human driver is told to wait as the ai does, the locomotive brake applied + cue_action( driver_hint::waitbrakecharge ); + } + } + else { + IsConsistCharged = true; + BrakeCharge = {}; + } + if( AIControllFlag + && ( false == IsConsistCharged ) + && ( false == heldforstart ) ) { + Ready = false; + } + auto const departblocked { + AIControllFlag + && mvOccupied->Vel < EU07_AI_NOMOVEMENT + && VelDesired > 0.0 + && ( false == Ready || fReady > 0.4 ) }; + if( false == departblocked ) { + DepartBlockedStart = -1.0; + } + else if( DepartBlockedStart < 0.0 ) { + DepartBlockedStart = ElapsedTime; + } + // second pass, for diesel engines verify the (live) engines are fully started + // TODO: cache presence of diesel engines in the consist, to skip this test if there isn't any + p = pVehicles[ end::front ]; // pojazd na czole składu + while( true == Ready + && p != nullptr ) { + + auto const *vehicle { p->MoverParameters }; + + if( has_diesel_engine() ) { + + Ready = vehicle->Vel > EU07_AI_MOVEMENT // already moving + || false == vehicle->Mains // deadweight vehicle + || vehicle->enrot > 0.8 * (vehicle->EngineType == TEngineType::DieselEngine ? vehicle->dizel_nmin : vehicle->DElist[0].RPM / 60.0); + } + p = p->Next(); // pojazd podłączony z tyłu (patrząc od czoła) + } + // test consist state for external events and/or weird things human user could've done + iEngineActive &= + false == IsAnyConverterOverloadRelayOpen + && false == IsAnyLineBreakerOpen + && ( false == IsAnyConverterPresent || true == IsAnyConverterEnabled ) + && ( false == IsAnyCompressorPresent || true == IsAnyCompressorEnabled ) + // the ai goes back to preparing the engine and switches that converter on, the human driver may run with it off + && ( false == AIControllFlag || false == islocalconverterswitchoff ); +} diff --git a/vehicle/ai/controls.cpp b/vehicle/ai/controls.cpp new file mode 100644 index 000000000..cde186f61 --- /dev/null +++ b/vehicle/ai/controls.cpp @@ -0,0 +1,1390 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the controllers and the brake handles the driver works + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/mover.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + + +// one step more of the train brake, sized from the consist brake table against the deceleration asked for +bool +TController::increase_train_brake() { + + // dodane dla towarowego + float pos_corr = 0; + + TDynamicObject *d; + d = pVehicles[0]; // pojazd na czele składu + while (d) + { // przeliczanie dodatkowego potrzebnego spadku ciśnienia + if( ( d->MoverParameters->Hamulec->GetBrakeStatus() & b_dmg ) == 0 ) { + pos_corr -= ( std::min( 5.0, d->MoverParameters->Hamulec->GetCRP() ) - 5.0 ) * d->MoverParameters->TotalMass; + } + d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) + } + pos_corr = pos_corr / fMass * 2.5; + + if (mvOccupied->BrakeHandle == TBrakeHandle::FV4a) + { + pos_corr += mvOccupied->Handle->GetCP()*0.2; + + } + if( double const deltaAcc = -AccDesired*BrakeAccFactor() - (fBrake_a0[0] + 4.0 * (/*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition - 1 - pos_corr)*fBrake_a1[0]); + deltaAcc > brake_increase_margin() ) + { + if( /*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition < 0.1 ) { + auto const OK { /*mvOccupied->*/BrakeLevelAdd( BrakingInitialLevel ) }; //GBH + // HACK: stronger braking to overcome SA134 engine behaviour + if( is_dmu() + && VelNext == 0.0 + && fBrakeDist < 200.0 ) { + BrakeLevelAdd( + fBrakeDist / ActualProximityDist < 0.8 ? + 0.5 : + 1.0 ); + } + return OK; + } + auto const OK { /*mvOccupied->*/BrakeLevelAdd( BrakingLevelIncrease ) }; //GBH + // brake harder if the acceleration is much higher than desired + /*if( ( deltaAcc > 2 * fBrake_a1[ 0 ] ) + && ( mvOccupied->BrakeCtrlPosR + BrakingLevelIncrease <= 5.0 ) ) { + mvOccupied->BrakeLevelAdd( BrakingLevelIncrease ); + } GBH */ + if( deltaAcc > 2 * fBrake_a1[0] + && BrakeCtrlPosition + BrakingLevelIncrease <= 5.0 ) { + /*mvOccupied->*/BrakeLevelAdd( BrakingLevelIncrease ); + } + return OK; + } + if( BrakeCtrlPosition > 0.0 + && AccDesired < 0.0 // only while braking is asked for, not when called for a train slipping back while starting + && ( fBrakeHeldTime > ( + mvOccupied->BrakeDelayFlag > bdelay_G ? + mvOccupied->BrakeDelay[ 1 ] : + mvOccupied->BrakeDelay[ 3 ] ) + // a train falling further behind needs no full fill time to be seen not to get enough + || ( ( fShortfall > 0.02 ) + && ( fBrakeHeldTime > brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) ) { + // the table says the present position is enough, but the brake has had its full fill + // time since the handle last moved and the train is still not slowing down as asked: + // believe the train rather than the table + return BrakeLevelAdd( BrakingLevelIncrease ); + } + return false; +} + +bool TController::IncBrake() +{ // zwiększenie hamowania + auto OK { false }; + auto const bs { + BrakeSystem == TBrakeSystem::ElectroPneumatic && ForcePNBrake ? + TBrakeSystem::Pneumatic : + BrakeSystem }; + switch( bs ) { + case TBrakeSystem::Individual: { + if( mvOccupied->LocalBrake == TLocalBrake::ManualBrake ) { + OK = mvOccupied->IncManualBrakeLevel( 1 + static_cast( std::floor( 0.5 + std::fabs( AccDesired ) ) ) ); + } + else { + OK = mvOccupied->IncLocalBrakeLevel( std::floor( 1.5 + std::abs( AccDesired ) ) ); + } + break; + } + case TBrakeSystem::Pneumatic: { + if (bs != mvOccupied->BrakeSystem) + { + while (mvOccupied->BrakeOpModeFlag > bom_PN) + { + mvOccupied->BrakeOpModeFlag >>= 1; + } + } + // NOTE: can't perform just test whether connected vehicle == nullptr, due to virtual couplers formed with nearby vehicles + auto standalone { true }; + if( mvOccupied->TrainType == train_type::et41 + || mvOccupied->TrainType == train_type::et42 ) { + // NOTE: we're doing simplified checks full of presuptions here. + // they'll break if someone does strange thing like turning around the second unit + if( mvOccupied->Couplers[end::rear].CouplingFlag & Coupling::permanent + && mvOccupied->Couplers[end::rear].Connected->Couplers[end::rear].Connected != nullptr ) { + standalone = false; + } + if( mvOccupied->Couplers[end::front].CouplingFlag & Coupling::permanent + && mvOccupied->Couplers[end::front].Connected->Couplers[end::front].Connected != nullptr ) { + standalone = false; + } + } + else if( is_dmu() ) { + // enforce use of train brake for DMUs + standalone = false; + } + else if( OrderCurrentGet().HasAny(DriverOrder::looseShunt) + && mvOccupied->Vel - VelDesired < fVelPlus + fVelMinus ) { + // try to reduce train brake use in loose shunting mode + standalone = true; + } + else { +/* + standalone = + ( ( mvOccupied->Couplers[ 0 ].CouplingFlag.Empty() ) + && ( mvOccupied->Couplers[ 1 ].CouplingFlag.Empty() ) ); +*/ + if( pVehicles[ end::front ] != pVehicles[ end::rear ] ) { + // more detailed version, will use manual braking also for coupled sets of controlled vehicles + auto *vehicle = pVehicles[ end::front ]; // start from first + while( true == standalone + && vehicle != nullptr ) { + // NOTE: we could simplify this by doing only check of the rear coupler, but this can be quite tricky in itself + // TODO: add easier ways to access front/rear coupler taking into account vehicle's direction + standalone = + (vehicle->MoverParameters->Couplers[end::front].Connected == nullptr || + (vehicle->MoverParameters->Couplers[end::front].CouplingFlag & Coupling::control && vehicle->MoverParameters->Couplers[end::front].Connected->Power > 1)) && + (vehicle->MoverParameters->Couplers[end::rear].Connected == nullptr || + (vehicle->MoverParameters->Couplers[end::rear].CouplingFlag & Coupling::control && vehicle->MoverParameters->Couplers[end::rear].Connected->Power > 1)); + vehicle = vehicle->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) + } + } + } + + //standalone = standalone && ( mvControlling->EIMCtrlType == 0 ); + + if( true == standalone && false == ForcePNBrake ) { + if( mvControlling->EIMCtrlType > 0 ) { + OK = IncBrakeEIM(); + } + else { + OK = mvOccupied->IncLocalBrakeLevel( + 1 + static_cast( std::floor( 0.5 + std::fabs( AccDesired ) ) ) ); // hamowanie lokalnym bo luzem jedzie + } + } + else { + if( /*GBH mvOccupied->BrakeCtrlPos*/ BrakeCtrlPosition + 1 == gbh_MAX ) { + if (AccDesired < -1.5) // hamowanie nagle + OK = /*mvOccupied->*/BrakeLevelAdd(1.0); //GBH + else + OK = false; + } + else { + OK = increase_train_brake(); + } + } + if( /*GBH mvOccupied->BrakeCtrlPos*/ + /*GBH mvOccupied->BrakeCtrlPos*/ BrakeCtrlPosition > 0 && mvOccupied->Hamulec->Releaser() ) { + mvOccupied->BrakeReleaser(0); + } + break; + } + case TBrakeSystem::ElectroPneumatic: { + while( mvOccupied->BrakeOpModeFlag << 1 <= mvOccupied->BrakeOpModes ) { + mvOccupied->BrakeOpModeFlag <<= 1; + } + if( mvOccupied->EngineType == TEngineType::ElectricInductionMotor ) { + if (mvOccupied->BrakeHandle == TBrakeHandle::MHZ_EN57) { + if (mvOccupied->BrakeCtrlPos < mvOccupied->Handle->GetPos(bh_FB)) + OK = mvOccupied->BrakeLevelAdd(1.0); + } + else { + OK = IncBrakeEIM(); + } + } + else if( mvOccupied->Handle->TimeEP == false ) { + auto const initialbrakeposition { mvOccupied->fBrakeCtrlPos }; + auto const AccMax { std::min( fBrake_a0[ 0 ] + 12 * fBrake_a1[ 0 ], mvOccupied->MED_amax ) }; + mvOccupied->BrakeLevelSet( + std::lerp( + mvOccupied->Handle->GetPos( bh_EPR ), + mvOccupied->Handle->GetPos( bh_EPB ), + std::clamp( -AccDesired / AccMax * mvOccupied->AIHintLocalBrakeAccFactor, 0.0, 1.0 ) ) ); + OK = mvOccupied->fBrakeCtrlPos != initialbrakeposition; + } + else if( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_EPB ) ) { + mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_EPB ) ); + if( mvOccupied->Handle->GetPos( bh_EPR ) - mvOccupied->Handle->GetPos( bh_EPN ) < 0.1 ) + mvOccupied->SwitchEPBrake( 1 ); // to nie chce działać + OK = true; + } + else if( ( mvOccupied->Handle->GetPos( bh_EPR ) - mvOccupied->Handle->GetPos( bh_EPN ) < 0.1 ) + && ( mvOccupied->EpForce <= 0.0 ) + && ( mvOccupied->EPBrakeControlPowered() ) ) { + // the handle already in the EP brake position, but the EP brake dropped out with the control's + // supply (e.g. the EP fuse off in the running brake test): switch it on again + mvOccupied->SwitchEPBrake( 1 ); + OK = ( mvOccupied->EpForce > 0.0 ); + } + else + OK = false; + break; + } + default: { break; } + } + return OK; +} + +bool TController::IncBrakeEIM() +{ // zwiększenie hamowania + bool OK = false; + switch (mvOccupied->EIMCtrlType) + { + case 0: { + if( mvOccupied->MED_amax != 9.81 ) { + auto const maxpos{mvOccupied->EIMCtrlEmergency ? 0.9 : 1.0 }; + auto const brakelimit{ -2.2 * AccDesired / fMedAmax - 1.0}; //additional limit when hinted is too low + auto const brakehinted{ -1.0 * mvOccupied->AIHintLocalBrakeAccFactor * AccDesired / fMedAmax }; //preffered by AI + auto const brakeposition{ maxpos * std::clamp(std::max(brakelimit, brakehinted), 0.0, 1.0)}; + OK = brakeposition != mvOccupied->LocalBrakePosA; + mvOccupied->LocalBrakePosA = brakeposition; + } + else { + OK = mvOccupied->IncLocalBrakeLevel( 1 ); + } + break; + } + case 1: { + OK = mvOccupied->MainCtrlPos > 0; + if( OK ) + mvOccupied->MainCtrlPos = 0; + break; + } + case 2: { + // the braking position, above the emergency brake one where the controller has it + auto const brakepos{1 + mvOccupied->EIMCtrlEmergencyPositions()}; + OK = mvOccupied->MainCtrlPos > brakepos; + if( OK ) + mvOccupied->MainCtrlPos = brakepos; + break; + } + case 3: { + if( mvOccupied->UniCtrlIntegratedLocalBrakeCtrl ) { + OK = mvOccupied->MainCtrlPos > 0; + if( OK ) + mvOccupied->MainCtrlPos = 0; + } + else { + OK = mvOccupied->IncLocalBrakeLevel( 1 ); + } + break; + } + default: { + break; + } + } + return OK; +} + +// zmniejszenie siły hamowania +bool TController::DecBrake() { + + auto OK { false }; + auto const bs { + BrakeSystem == TBrakeSystem::ElectroPneumatic && ForcePNBrake ? + TBrakeSystem::Pneumatic : + BrakeSystem }; + switch( bs ) { + case TBrakeSystem::Individual: { + auto const positionchange { 1 + std::floor( 0.5 + std::abs( AccDesired ) ) }; + OK = mvOccupied->LocalBrake == TLocalBrake::ManualBrake ? mvOccupied->DecManualBrakeLevel(positionchange) : mvOccupied->DecLocalBrakeLevel(positionchange); + break; + } + case TBrakeSystem::Pneumatic: { + auto deltaAcc { -1.0 }; + if( fBrake_a0[0] != 0.0 + || fBrake_a1[0] != 0.0 ) { + auto const pos_diff { ( is_dmu() ? 0.25 : 1.0 ) }; + // a distributor applied at all gives at least its minimum stage, about what the first position does, so + // a position short of the first one brakes no weaker than that + deltaAcc = -AccDesired * BrakeAccFactor() - ( fBrake_a0[ 0 ] + 4 * std::max( 0.0, BrakeCtrlPosition - pos_diff ) * fBrake_a1[ 0 ] ); + } + if( bUphillStart && ( false == bUphillRelease ) ) { + // starting uphill the train brake holds the train until the power does + break; + } + if( ( BrakeCtrlPosition > 0.0 ) + && ( uphill_stop_hold() ) ) { + // any release now raises the pipe, and a long train releases more than the handle is moved back, too late + // to apply again before the train stands: keep the brake as it is, and the locomotive brake with it + break; + } + if( brake_charge::holds_application( + bBrakeChargeHold, IsConsistCharged, mvOccupied->Vel < EU07_AI_NOMOVEMENT, BrakeCtrlPosition ) ) { + // the order to go came while the train still charges: released now, the wagons let go as their + // reservoirs fill and the train stands on a locomotive brake that doesn't hold it. the locomotive + // brake stays on with it + break; + } + if (deltaAcc < 0 && /*GBH mvOccupied->BrakeCtrlPosR*/ BrakeCtrlPosition > 0) { + OK = /*mvOccupied->*/ BrakeLevelAdd(-0.25); + // if ((deltaAcc < 5 * fBrake_a1[0]) && (mvOccupied->BrakeCtrlPosR >= 1.2)) + // mvOccupied->BrakeLevelAdd(-1.0); + /* if (mvOccupied->BrakeCtrlPosR < 0.74) GBH */ + if (BrakeCtrlPosition < 0.74) + /*mvOccupied->*/ BrakeLevelSet(gbh_RP); + } + // standing, the locomotive brake holds the train until its brakes are charged: off before, a train + // released on a gradient rolls with no air to brake with. nor through DecBrakeEIM(), which takes it off + // as well (the locomotive brake of a vehicle without the integrated handle) + auto const holdlocomotive { + ( false == IsConsistCharged ) + && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) }; + if( ( !OK ) && ( false == holdlocomotive ) ) { + OK = mvOccupied->DecLocalBrakeLevel(2); + } + if( ( !OK ) && ( false == holdlocomotive ) ) { + OK = DecBrakeEIM(); + } + /* + // NOTE: disabled, duplicate of AI's behaviour in UpdateSituation() + if (mvOccupied->PipePress < 3.0) + Need_BrakeRelease = true; + */ + break; + } + case TBrakeSystem::ElectroPneumatic: { + if( mvOccupied->EngineType == TEngineType::ElectricInductionMotor ) { + if( mvOccupied->BrakeHandle == TBrakeHandle::MHZ_EN57 ) { + if( mvOccupied->BrakeCtrlPos > mvOccupied->Handle->GetPos( bh_RP ) ) { + OK = mvOccupied->BrakeLevelAdd( -1.0 ); + } + } + else { + OK = DecBrakeEIM(); + } + } + else if( mvOccupied->Handle->TimeEP == false ) { + auto const initialbrakeposition { mvOccupied->fBrakeCtrlPos }; + auto const AccMax { std::min( fBrake_a0[ 0 ] + 12 * fBrake_a1[ 0 ], mvOccupied->MED_amax ) }; + mvOccupied->BrakeLevelSet( + std::lerp( + mvOccupied->Handle->GetPos( bh_EPR ), + mvOccupied->Handle->GetPos( bh_EPB ), + std::clamp( -AccDesired / AccMax * mvOccupied->AIHintLocalBrakeAccFactor, 0.0, 1.0 ) ) ); + OK = mvOccupied->fBrakeCtrlPos != initialbrakeposition; + } + else { + OK = false; + if (mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos(bh_EPR)) { + mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_EPR)); + OK = true; + } + if (mvOccupied->Handle->GetPos(bh_EPR) - mvOccupied->Handle->GetPos(bh_EPN) < 0.1) { + OK = OK || mvOccupied->SwitchEPBrake(1); + } + } + if( !OK ) { + OK = mvOccupied->DecLocalBrakeLevel( 2 ); + } + break; + } + default: { + break; + } + } + return OK; +} + +void TController::LapBrake() { + + if( mvOccupied->Handle->TimeEP ) { + if( mvOccupied->Handle->GetPos( bh_EPR ) - mvOccupied->Handle->GetPos( bh_EPN ) < 0.1 ) { + mvOccupied->SwitchEPBrake( 0 ); + } + else { + mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_EPN ) ); + } + } +} + +void TController::ZeroLocalBrake() { + + if( mvOccupied->UniCtrlIntegratedLocalBrakeCtrl ) { + while( DecBrakeEIM() ) { + ; + } + } + else { + mvOccupied->DecLocalBrakeLevel( LocalBrakePosNo ); + } +} + +bool TController::DecBrakeEIM() +{ // zmniejszenie siły hamowania + bool OK = false; + switch (mvOccupied->EIMCtrlType) + { + case 0: { + if( mvOccupied->MED_amax != 9.81 ) { + auto const desiredacceleration { ( mvOccupied->Vel > EU07_AI_NOMOVEMENT ? AccDesired : std::max( 0.0, AccDesired ) ) }; + auto const brakeposition { std::clamp( -1.0 * mvOccupied->AIHintLocalBrakeAccFactor * desiredacceleration / mvOccupied->MED_amax, 0.0, 1.0 ) }; + OK = brakeposition != mvOccupied->LocalBrakePosA; + mvOccupied->LocalBrakePosA = brakeposition; + } + else { + OK = mvOccupied->DecLocalBrakeLevel( 1 ); + } + break; + } + case 1: { + OK = mvOccupied->MainCtrlPos < 2; + if( OK ) + mvOccupied->MainCtrlPos = 2; + break; + } + case 2: { + auto const neutralpos{mvOccupied->MainCtrlNoPowerPos()}; + OK = mvOccupied->MainCtrlPos < neutralpos; + if( OK ) + mvOccupied->MainCtrlPos = neutralpos; + break; + } + case 3: { + OK = mvOccupied->MainCtrlPos < mvOccupied->MainCtrlMaxDirChangePos; + if( OK ) + mvOccupied->MainCtrlPos = mvOccupied->MainCtrlMaxDirChangePos; + break; + } + } + return OK; +} + +bool TController::IncSpeed() +{ // zwiększenie prędkości; zwraca false, jeśli dalej się nie da zwiększać + auto OK { false }; + switch (mvOccupied->EngineType) + { + case TEngineType::None: // McZapkie-041003: wagon sterowniczy + if (mvControlling->MainCtrlPosNo > 0) // jeśli ma czym kręcić + drivingFlags.incSpeed = true; // ustawienie flagi jazdy + return false; + case TEngineType::ElectricSeriesMotor: + if (mvPantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) // jeśli pantografujący + { + if (fOverhead2 >= 0.0) // a jazda bezprądowa ustawiana eventami (albo opuszczenie) + return false; // to nici z ruszania + if (iOverheadZero) // jazda bezprądowa z poziomu toru ustawia bity + return false; // to nici z ruszania + } + // TODO: move all fVoltage assignments to a single, more generic place + if( mvControlling->EnginePowerSource.SourceType == TPowerSource::Accumulator ) { + fVoltage = mvControlling->BatteryVoltage; + } + if (!IsAnyMotorOverloadRelayOpen && !mvControlling->ControlPressureSwitch && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->StLinFlag) && (Ready || drivingFlags.press)) { + // youBy polecił dodać 2012-09-08 v367 + // na pozycji 0 przejdzie, a na pozostałych będzie czekać, aż się załączą liniowe (zgaśnie DelayCtrlFlag) + auto const usehighoverloadrelaythreshold{mvControlling->TrainType != train_type::et42 // ET42 uses these variables for different purpose. TODO: fix this + && mvControlling->ImaxHi > mvControlling->ImaxLo && mvOccupied->Vel < (mvControlling->IsMotorOverloadRelayHighThresholdOn() ? 30.0 : 20.0) && + iVehicles - ControlledEnginesCount > 0 + // && ( std::fabs( mvControlling->Im ) > 0.85 * mvControlling->Imax ) + && mvControlling->Imax * mvControlling->EngineVoltage * ControlledEnginesCount / + (fMass * (fAccGravity == 0.025 ? -0.01 : // prevent div/0 + fAccGravity - 0.025)) < + -2.8}; + // use series mode: + // if high threshold is set for motor overload relay, + // if the power station is heavily burdened, + // if it generates enough traction force + // to build up speed to 30/40 km/h for passenger/cargo train (10 km/h less if going uphill) + auto const sufficienttractionforce{std::abs(mvControlling->Ft) * ControlledEnginesCount > (IsHeavyCargoTrain ? 75 : 50) * 1000.0}; + auto const sufficientacceleration{AbsAccS >= (IsHeavyCargoTrain ? 0.03 : IsCargoTrain ? 0.06 : 0.09)}; + auto const seriesmodefieldshunting{mvControlling->ScndCtrlPos > 0 && mvControlling->RList[mvControlling->MainCtrlPos].Bn == 1}; + auto const parallelmodefieldshunting{mvControlling->ScndCtrlPos > 0 && mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1}; + auto const minvoltage{(mvPantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? mvPantographUnit->EnginePowerSource.CollectorParameters.MinV : 0.0)}; + auto const maxvoltage{(mvPantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? mvPantographUnit->EnginePowerSource.CollectorParameters.MaxV : 0.0)}; + auto const seriesmodevoltage{std::lerp(minvoltage, maxvoltage, IsHeavyCargoTrain ? 0.35 : 0.40)}; + auto const useseriesmode = mvControlling->Imax > mvControlling->ImaxLo || true == usehighoverloadrelaythreshold || fVoltage < seriesmodevoltage || + (true == sufficientacceleration && true == sufficienttractionforce && + mvOccupied->Vel <= (IsCargoTrain ? 40 : 30) + (seriesmodefieldshunting ? 5 : 0) - (fAccGravity < -0.025 ? 10 : 0)); + // when not in series mode use the first available parallel mode configuration until 50/60 km/h for passenger/cargo train + // (if there's only one parallel mode configuration it'll be used regardless of current speed) + auto const usefieldshunting = mvControlling->StLinFlag && mvControlling->RList[mvControlling->MainCtrlPos].R < 0.01 && false == mvControlling->IsScndCtrlLockedByMainCtrl() && + (useseriesmode ? mvControlling->RList[mvControlling->MainCtrlPos].Bn == 1 : + true == sufficientacceleration && true == sufficienttractionforce && mvOccupied->Vel <= (IsCargoTrain ? 60 : 50) + (parallelmodefieldshunting ? 5 : 0) ? + mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1 : + mvControlling->MainCtrlPos == mvControlling->MainCtrlPosNo); + + // if needed enable high threshold for overload relay... + if (mvControlling->TrainType != train_type::et42) + { // ET42 uses these variables for different purpose. TODO: fix this + if (usehighoverloadrelaythreshold) + { + if (mvControlling->Imax < mvControlling->ImaxHi) + { + // to enable this setting we'll typically need the main controller in series mode (which is not guaranteed) + if (mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1) + { + if (false == mvControlling->IsScndCtrlNoPowerPos()) + { + mvControlling->DecScndCtrl(2); + } + while (false == mvControlling->IsMainCtrlNoPowerPos() && mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1) + { + mvControlling->DecMainCtrl(1); // kręcimy nastawnik jazdy o 1 wstecz + } + } + mvControlling->CurrentSwitch(true); // rozruch wysoki (za to może się ślizgać) + } + } + // ...or disable high threshold for overload relay if no longer needed + else + { + if (mvControlling->IsMotorOverloadRelayHighThresholdOn() && std::fabs(mvControlling->Im) < mvControlling->ImaxLo) + { + mvControlling->CurrentSwitch(false); // rozruch wysoki wyłącz + } + } + } + + double Vs = 99999; + if (usefieldshunting ? mvControlling->ScndCtrlPos < mvControlling->ScndCtrlPosNo : mvControlling->MainCtrlPos < mvControlling->MainCtrlPosNo) + { + Vs = ESMVelocity(!usefieldshunting); + } + + if (std::abs(mvControlling->Im) < (fReady < 0.4 ? mvControlling->Imin : mvControlling->IminLo) || mvControlling->Vel > Vs) + { + // Ra: wywalał nadmiarowy, bo Im może być ujemne; jak nie odhamowany, to nie przesadzać z prądem + if (usefieldshunting) + { + // to dać bocznik + // engage the shuntfield only if there's sufficient power margin to draw from + auto const sufficientpowermargin{fVoltage - seriesmodevoltage > (IsHeavyCargoTrain ? 100.0 : 75.0) * ControlledEnginesCount}; + + OK = sufficientpowermargin ? mvControlling->IncScndCtrl(1) : true; + } + else + { + // jeśli ustawiony bocznik to bocznik na zero po chamsku + if (mvControlling->ScndCtrlPos) + { + mvControlling->DecScndCtrl(2); + } + // kręcimy nastawnik jazdy + // don't draw too much power; + // keep from dropping into series mode when entering/using parallel mode, and from shutting down in the series mode + auto const sufficientpowermargin{fVoltage - + (mvControlling->RList[std::min(mvControlling->MainCtrlPos + 1, mvControlling->MainCtrlPosNo)].Bn == 1 ? minvoltage : seriesmodevoltage) > + (IsHeavyCargoTrain ? 100.0 : 75.0) * ControlledEnginesCount}; + + OK = sufficientpowermargin && false == mvControlling->DelayCtrlFlag ? mvControlling->IncMainCtrl(1) : true; + // czekaj na 1 pozycji, zanim się nie włączą liniowe + if (true == mvControlling->StLinFlag) + { + drivingFlags.incSpeed = true; + } + else + { + drivingFlags.incSpeed = false; + } + + if (mvControlling->Im == 0 && mvControlling->MainCtrlPowerPos() > 1) + { + // brak prądu na dalszych pozycjach + // nie załączona lokomotywa albo wywalił nadmiarowy + Need_TryAgain = true; + } + } + } + else + { + OK = false; + } + } +// mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania + break; + case TEngineType::Dumb: + if (!IsAnyMotorOverloadRelayOpen && (Ready || drivingFlags.press)) + //{(BrakePress<=0.01*MaxBrakePress)} + { + OK = IncSpeedEIM(); + if (!OK) + OK = mvControlling->IncMainCtrl(1); + if (!OK) + OK = mvControlling->IncScndCtrl(1); + } + break; + case TEngineType::DieselElectric: + if (!IsAnyMotorOverloadRelayOpen && !mvControlling->ControlPressureSwitch && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->StLinFlag) && (Ready || drivingFlags.press)) { + // youBy polecił dodać 2012-09-08 v367 + // na pozycji 0 przejdzie, a na pozostałych będzie czekać, aż się załączą liniowe (zgaśnie DelayCtrlFlag) + //{(BrakePress<=0.01*MaxBrakePress)} + OK = IncSpeedEIM(); + if (!OK) + OK = mvControlling->IncMainCtrl(1); + if (!OK) + OK = mvControlling->IncScndCtrl(1); + } + break; + case TEngineType::ElectricInductionMotor: + if( !IsAnyMotorOverloadRelayOpen && (Ready || drivingFlags.press || mvOccupied->ShuntMode) ) { + //{(BrakePress<=0.01*MaxBrakePress)} + OK = IncSpeedEIM(); + if (mvControlling->SpeedCtrl && mvControlling->Mains) + { + // cruise control + auto const couplinginprogress{true == drivingFlags.connect && true == OrderCurrentGet().HasAll(DriverOrder::connect)}; + auto const SpeedCntrlVel{(ActualProximityDist > std::max(50.0, fMaxProximityDist) || couplinginprogress ? VelDesired : min_speed(VelDesired, VelNext))}; + if (SpeedCntrlVel >= mvControlling->SpeedCtrlUnit.MinVelocity && + SpeedCntrlVel - mvControlling->SpeedCtrlUnit.MinVelocity == quantize(SpeedCntrlVel - mvControlling->SpeedCtrlUnit.MinVelocity, mvControlling->SpeedCtrlUnit.VelocityStep)) + { + SpeedCntrl(SpeedCntrlVel); + } + else if (SpeedCntrlVel > 0.1) + { + SpeedCntrl(0.0); + mvControlling->DecScndCtrl(2); + } + } + } + break; + case TEngineType::WheelsDriven: + if (!mvControlling->CabActive) + mvControlling->CabActivisation(); + if (sin(mvControlling->eAngle) > 0) + mvControlling->IncMainCtrl(3 + 3 * floor(0.5 + fabs(AccDesired))); + else + mvControlling->DecMainCtrl(3 + 3 * floor(0.5 + fabs(AccDesired))); + break; + case TEngineType::DieselEngine: + if (mvControlling->ShuntModeAllow) + { // dla 2Ls150 można zmienić tryb pracy, jeśli jest w liniowym i nie daje rady (wymaga zerowania kierunku) + // mvControlling->ShuntMode=(OrderList[OrderPos]&Shunt)||(fMass>224000.0); + } + if (mvControlling->SpeedCtrl && mvControlling->Mains) {// cruise control + auto const couplinginprogress { true == drivingFlags.connect && true == OrderCurrentGet().HasAll(DriverOrder::connect) }; + auto const SpeedCntrlVel { ( + ActualProximityDist > std::max(50.0, fMaxProximityDist) || couplinginprogress ? + VelDesired : + min_speed( VelDesired, VelNext ) ) }; + if( SpeedCntrlVel >= mvControlling->SpeedCtrlUnit.MinVelocity + && SpeedCntrlVel - mvControlling->SpeedCtrlUnit.MinVelocity == quantize(SpeedCntrlVel - mvControlling->SpeedCtrlUnit.MinVelocity, mvControlling->SpeedCtrlUnit.VelocityStep) ) { + SpeedCntrl(SpeedCntrlVel); + } + else if (SpeedCntrlVel > 0.1) { + SpeedCntrl(0.0); + mvControlling->DecScndCtrl( 2 ); + } + } + if (mvControlling->EIMCtrlType > 0) { + if (true == Ready) + { + bool max = mvControlling->Vel > mvControlling->dizel_minVelfullengage + || (mvControlling->SpeedCtrl && mvControlling->ScndCtrlPos > 0); + DizelPercentage = max ? 100 : 1; + } + break; + } + else { + if( true == Ready ) { + if( mvControlling->Vel > mvControlling->dizel_minVelfullengage + && mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0 ) { + OK = mvControlling->IncMainCtrl( 1 ); + } + if( mvControlling->RList[ mvControlling->MainCtrlPos ].Mn == 0 ) { + OK = mvControlling->IncMainCtrl( 1 ); + } + } + } + // TODO: move this check to a more suitable place, or scrap it + if( false == mvControlling->Mains ) { + SpeedCntrl(0.0); + mvControlling->DecScndCtrl( 2 ); + cue_action( driver_hint::linebreakerclose ); + cue_action( driver_hint::converteron ); + cue_action( driver_hint::compressoron ); + } + break; + } + return OK; +} + +void TController::ZeroSpeed( bool const Enforce ) { + + while( DecSpeed( Enforce ) ) { + ; + } +} + +bool TController::DecSpeed(bool force) +{ // zmniejszenie prędkości (ale nie hamowanie) + bool OK = false; // domyślnie false, aby wyszło z pętli while + switch (mvOccupied->EngineType) + { + case TEngineType::None: // McZapkie-041003: wagon sterowniczy + drivingFlags.incSpeed = false; // usunięcie flagi jazdy + if (force && mvControlling->MainCtrlPosNo > 0) // przy aktywacji kabiny jest potrzeba natychmiastowego wyzerowania + // McZapkie-041003: wagon sterowniczy, np. EZT + mvControlling->DecMainCtrl(std::min(mvControlling->MainCtrlPowerPos(), 2)); + // mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania + return false; + case TEngineType::ElectricSeriesMotor: + OK = mvControlling->DecScndCtrl(2); // najpierw bocznik na zero + if (!OK) + OK = mvControlling->DecMainCtrl( std::min( mvControlling->MainCtrlPowerPos(), 2 ) ); +// mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania + break; + case TEngineType::Dumb: + case TEngineType::DieselElectric: + OK = mvControlling->DecScndCtrl(2); + if (!OK) + OK = mvControlling->DecMainCtrl( std::min( mvControlling->MainCtrlPowerPos(), 2 + mvControlling->MainCtrlPowerPos() / 2 ) ); + break; + case TEngineType::ElectricInductionMotor: + OK = DecSpeedEIM(); + break; + case TEngineType::WheelsDriven: + if (!mvControlling->CabActive) + mvControlling->CabActivisation(); + if (sin(mvControlling->eAngle) < 0) + mvControlling->IncMainCtrl(3 + 3 * floor(0.5 + fabs(AccDesired))); + else + mvControlling->DecMainCtrl(3 + 3 * floor(0.5 + fabs(AccDesired))); + break; + case TEngineType::DieselEngine: + if (mvControlling->EIMCtrlType > 0) + { + DizelPercentage = 0; + if (force) { + SpeedCntrl(0.0); //wylacz od razu tempomat + mvControlling->DecScndCtrl(2); + } + if (VelDesired > 0.1 && mvControlling->SpeedCtrlUnit.MinVelocity > VelDesired) { + SpeedCntrl(0.0); //wylacz od razu tempomat + mvControlling->DecScndCtrl(2); + } + break; + } + + if (mvControlling->Vel > mvControlling->dizel_minVelfullengage) + { + if (mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0) + OK = mvControlling->DecMainCtrl(1); + } + else { + while( mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0 + && mvControlling->MainCtrlPowerPos() > 1 ) { + OK = mvControlling->DecMainCtrl( 1 ); + } + } + if (force) { // przy aktywacji kabiny jest potrzeba natychmiastowego wyzerowania + OK = mvControlling->DecMainCtrl(mvControlling->MainCtrlPowerPos() > 2 ? 2 : 1); + SpeedCntrl(0.0); //wylacz od razu tempomat + mvControlling->DecScndCtrl( 2 ); + } + break; + } + return OK; +}; + +bool TController::IncSpeedEIM() { + + bool OK = false; // domyślnie false, aby wyszło z pętli while + switch( mvControlling->EIMCtrlType ) { + case 0: + OK = mvControlling->IncMainCtrl( 1 ); + break; + case 1: + OK = mvControlling->MainCtrlPos < 6; + if( OK ) { + mvControlling->MainCtrlPos = 6; + } +/* + // TBD, TODO: set position based on desired acceleration? + OK = mvControlling->MainCtrlPos < mvControlling->MainCtrlPosNo; + if( OK ) { + mvControlling->MainCtrlPos = safe_clamp( mvControlling->MainCtrlPos + 1, 6, mvControlling->MainCtrlPosNo ); + } +*/ + break; + case 2: { + auto const powerpos{4 + mvControlling->EIMCtrlEmergencyPositions()}; + OK = mvControlling->MainCtrlPos < powerpos; + if( OK ) { + mvControlling->MainCtrlPos = powerpos; + } + break; + } + } + return OK; +} + +bool TController::DecSpeedEIM( int const Amount ) +{ // zmniejszenie prędkości (ale nie hamowanie) + bool OK = false; // domyślnie false, aby wyszło z pętli while + switch( mvControlling->EIMCtrlType ) { + case 0: { + OK = mvControlling->DecMainCtrl( Amount ); + break; + } + case 1: { + OK = mvControlling->MainCtrlPos > 4; + if( OK ) { + mvControlling->MainCtrlPos = 4; + } + break; + } + case 2: { + if( AccDesired > 0 + && mvControlling->SpeedCtrlUnit.IsActive + && mvControlling->SpeedCtrlUnit.PowerStep > 0 + && mvControlling->SpeedCtrlUnit.DesiredPower > mvControlling->SpeedCtrlUnit.MinPower ) { + mvControlling->SpeedCtrlPowerDec(); + } + else { + auto const holdpos{2 + mvControlling->EIMCtrlEmergencyPositions()}; + OK = mvControlling->MainCtrlPos > holdpos; + if( OK ) { + mvControlling->MainCtrlPos = holdpos; + } + } + break; + } + default: { + break; + } + } + return OK; +} + +void TController::BrakeLevelSet(double b) +{ // ustawienie pozycji hamulca na wartość (b) w zakresie od -2 do BrakeCtrlPosNo + // jedyny dopuszczalny sposób przestawienia hamulca zasadniczego + if (BrakeCtrlPosition == b) + return; // nie przeliczać, jak nie ma zmiany + BrakeCtrlPosition = std::clamp(b, (double)gbh_MIN, (double)gbh_MAX); + fBrakeHeldTime = 0.0; +} + +bool TController::BrakeLevelAdd(double b) +{ // dodanie wartości (b) do pozycji hamulca (w tym ujemnej) + // zwraca false, gdy po dodaniu było by poza zakresem + BrakeLevelSet(BrakeCtrlPosition + b); + return b > 0.0 ? BrakeCtrlPosition < gbh_MAX : + BrakeCtrlPosition > -1.0; // true, jeśli można kontynuować +} + +// Ra: regulacja prędkości, wykonywana w każdym przebłysku świadomości AI +// ma dokręcać do bezoporowych i zdejmować pozycje w przypadku przekroczenia prądu +void TController::SpeedSet() { + + if( false == AIControllFlag ) { return; } + + switch (mvOccupied->EngineType) + { + case TEngineType::None: { // McZapkie-041003: wagon sterowniczy + if (mvControlling->MainCtrlPosNo > 0) + { // jeśli ma czym kręcić + // TODO: sprawdzanie innego czlonu //if (!FuseFlagCheck()) + if( ( false == drivingFlags.incSpeed ) ) { + // przetok rozłączać od razu (no dependency on fActionTime) + while( mvControlling->MainCtrlPos + && mvControlling->DecMainCtrl(1) ) { + ; // na zero + } + if( fActionTime >= 0.0 ) { + fActionTime = -5.0; // niech trochę potrzyma + } +// mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania + } + else { + // jak ma jechać + if( fActionTime < 0.0 ) { break; } + if( false == Ready ) { break; } + + if( mvOccupied->DirActive > 0 ) { + mvOccupied->DirectionForward(); //żeby EN57 jechały na drugiej nastawie + } + + if( mvControlling->MainCtrlPos > 0 + && false == mvControlling->StLinFlag ) { + // jak niby jedzie, ale ma rozłączone liniowe to na zero i czekać na przewalenie kułakowego + mvControlling->DecMainCtrl( 2 ); + } + else { + // ruch nastawnika uzależniony jest od aktualnie ustawionej pozycji + switch( mvControlling->MainCtrlPos ) { + case 0: + if( mvControlling->MainCtrlActualPos ) { + // jeśli kułakowy nie jest wyzerowany to czekać na wyzerowanie + break; + } + mvControlling->IncMainCtrl( 1 ); // przetok; bez "break", bo nie ma czekania na 1. pozycji + case 1: + if( VelDesired >= 20 ) + mvControlling->IncMainCtrl( 1 ); // szeregowa + case 2: + if( VelDesired >= 50 ) + mvControlling->IncMainCtrl( 1 ); // równoległa + case 3: + if( VelDesired >= 80 ) + mvControlling->IncMainCtrl( 1 ); // bocznik 1 + case 4: + if( VelDesired >= 90 ) + mvControlling->IncMainCtrl( 1 ); // bocznik 2 + case 5: + if( VelDesired >= 100 ) + mvControlling->IncMainCtrl( 1 ); // bocznik 3 + } + } + if( mvControlling->MainCtrlPos ) // jak załączył pozycję + { + fActionTime = -5.0; // niech trochę potrzyma +// mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania + } + } + } + break; + } + case TEngineType::ElectricSeriesMotor: { +/* + if (Ready || (drivingFlags.press)) { // o ile może jechać +// if (fAccGravity < -0.10) // i jedzie pod górę większą niż 10 promil + { // procedura wjeżdżania na ekstremalne wzniesienia + if( std::fabs( mvControlling->Im ) > 0.85 * mvControlling->Imax ) { // a prąd jest większy niż 85% nadmiarowego + if( mvControlling->Imax * mvControlling->EngineVoltage / ( fMass * fAccGravity ) < -2.8 ) // a na niskim się za szybko nie pojedzie + { // włączenie wysokiego rozruchu; + // (I*U)[A*V=W=kg*m*m/sss]/(m[kg]*a[m/ss])=v[m/s]; 2.8m/ss=10km/h + if( mvControlling->RList[ mvControlling->MainCtrlPos ].Bn > 1 ) { // jeśli jedzie na równoległym, to zbijamy do szeregowego, aby włączyć wysoki rozruch + if( mvControlling->ScndCtrlPos > 0 ) { // jeżeli jest bocznik + mvControlling->DecScndCtrl( 2 ); // wyłączyć bocznik, bo może blokować skręcenie NJ + } + do { // skręcanie do bezoporowej na szeregowym + mvControlling->DecMainCtrl( 1 ); // kręcimy nastawnik jazdy o 1 wstecz + } + while( ( false == mvControlling->IsMainCtrlNoPowerPos() ) + && ( mvControlling->RList[ mvControlling->MainCtrlPos ].Bn > 1 ) ); // oporowa zapętla + } + if( mvControlling->Imax < mvControlling->ImaxHi ) { // jeśli da się na wysokim + mvControlling->CurrentSwitch( true ); // rozruch wysoki (za to może się ślizgać) + } + if( ReactionTime > 0.1 ) { + ReactionTime = 0.1; // orientuj się szybciej + } + } // if (Im>Imin) + } + if( std::fabs( mvControlling->Im ) > 0.96 * mvControlling->Imax ) {// jeśli prąd jest duży (można 690 na 750) + if( mvControlling->ScndCtrlPos > 0 ) { // jeżeli jest bocznik + mvControlling->DecScndCtrl( 2 ); // zmniejszyć bocznik + } + else { + mvControlling->DecMainCtrl( 1 ); // kręcimy nastawnik jazdy o 1 wstecz + } + } + } +// else // gdy nie jedzie ambitnie pod górę + { // sprawdzenie, czy rozruch wysoki jest potrzebny + if( ( mvControlling->Imax > mvControlling->ImaxLo ) + && ( mvOccupied->Vel >= 30.0 ) ) { // jak się rozpędził +// if (fAccGravity > -0.02) // a i pochylenie mnijsze niż 2‰ + mvControlling->CurrentSwitch( false ); // rozruch wysoki wyłącz + } + } + } +*/ + break; + } + case TEngineType::Dumb: { + break; + } + case TEngineType::DieselElectric: { + break; + } + case TEngineType::ElectricInductionMotor: { + break; + } + case TEngineType::DieselEngine: { + // Ra 2014-06: "automatyczna" skrzynia biegów... + auto const &motorparams { mvControlling->MotorParam[ mvControlling->ScndCtrlPos ] }; + auto const velocity { ( mvControlling->ShuntMode ? mvControlling->AnPos : 1.0 ) * mvControlling->Vel }; + if( false == motorparams.AutoSwitch ) { + // gdy biegi ręczne + // jak prędkość większa niż procent maksymalnej na danym biegu, wrzucić wyższy + if( velocity > 0.75 * motorparams.mfi ) { + // ...presuming there is a higher gear + if( mvControlling->ScndCtrlPos < mvControlling->ScndCtrlPosNo ) { + mvControlling->DecMainCtrl( 2 ); + while( mvControlling->IncScndCtrl(1) + && mvControlling->MotorParam[mvControlling->ScndCtrlPos].mIsat == 0.0 ) { // jeśli bieg jałowy to kolejny + ; + } + } + } + // jak prędkość mniejsza niż minimalna na danym biegu, wrzucić niższy + else if( velocity < motorparams.fi && mvControlling->ScndCtrlPos > 1 ) { + // ... but ensure we don't switch all way down to 0 + mvControlling->DecMainCtrl(2); + while (mvControlling->ScndCtrlPos > 1 // repeat the entry check as we're working in a loop + && mvControlling->DecScndCtrl(1) && mvControlling->MotorParam[mvControlling->ScndCtrlPos].mIsat == 0.0) + { // jeśli bieg jałowy to kolejny + ; + } + } + } + break; + } + default: { + break; + } + } // enginetype +}; + +void TController::SpeedCntrl(double DesiredSpeed) +{ + if( false == mvControlling->SpeedCtrl ) { return; } + + if (mvControlling->IsSpeedCtrlSeparate()) + { + // a switch of its own, the secondary controller left to the field shunting (eu07/maszyna#69) + if (DesiredSpeed < 0.1) { + DesiredSpeed = 0; + } + mvControlling->SpeedCtrlSwitch(DesiredSpeed > 0); + mvControlling->RunCommand(VehicleCommand::speedControl, DesiredSpeed, mvControlling->CabActive); + } + else if (mvControlling->EngineType == TEngineType::DieselEngine) + { + if (DesiredSpeed < 0.1) { + mvControlling->DecScndCtrl(2); + DesiredSpeed = 0; + } + else if (mvControlling->ScndCtrlPos < 1) { + mvControlling->IncScndCtrl(1); + } + mvControlling->RunCommand(VehicleCommand::speedControl, DesiredSpeed, mvControlling->CabActive); + } + else + if (mvControlling->ScndCtrlPosNo == 1) + { + mvControlling->IncScndCtrl(1); + mvControlling->RunCommand(VehicleCommand::speedControl, DesiredSpeed, mvControlling->CabActive); + } + else if (mvControlling->ScndCtrlPosNo > 1 && !mvOccupied->SpeedCtrlTypeTime) + { + int DesiredPos = 1 + mvControlling->ScndCtrlPosNo * ((DesiredSpeed - 1.0) / mvControlling->Vmax); + while( mvControlling->ScndCtrlPos > DesiredPos && true == mvControlling->DecScndCtrl(1) ) { ; } // all work is done in the condition loop + while( mvControlling->ScndCtrlPos < DesiredPos && true == mvControlling->IncScndCtrl(1) ) { ; } // all work is done in the condition loop + } + + if( mvControlling->SpeedCtrlUnit.PowerStep > 0 && mvControlling->IsSpeedCtrlEngaged() ) { + while (mvControlling->SpeedCtrlUnit.DesiredPower < mvControlling->SpeedCtrlUnit.MaxPower) + { + mvControlling->SpeedCtrlPowerInc(); + } + } +}; + +void TController::SetTimeControllers() +{ + // TBD, TODO: rework this method to use hint system and regardless of driver type + if( false == AIControllFlag || 0 == mvOccupied->CabActive ) { return; } + + //1. Check the type of Main Brake Handle + if( BrakeSystem == TBrakeSystem::Pneumatic || ForcePNBrake ) + { + if (mvOccupied->Handle->Time) + { + auto const pressuredifference { mvOccupied->Handle->GetCP() - ( mvOccupied->HighPipePress - BrakeCtrlPosition * 0.25*mvOccupied->DeltaPipePress ) }; + if (BrakeCtrlPosition > 0 && pressuredifference > 0.05) + mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_FB)); + else if (BrakeCtrlPosition > 0 && pressuredifference < -0.05) + mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_RP)); + else if (BrakeCtrlPosition == 0) + mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_RP)); + else if (BrakeCtrlPosition == -1) + mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_FS)); + else if (BrakeCtrlPosition == -2) + mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_NP)); + } + if( mvOccupied->BrakeHandle == TBrakeHandle::FV4a ) { + mvOccupied->BrakeLevelSet( BrakeCtrlPosition ); + } + if( mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K8P + || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_EN57 ) { + if( BrakeCtrlPosition == 0 ) { + mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_RP ) ); + } + else if( BrakeCtrlPosition == -1 ) { + mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_FS ) ); + } + else if( BrakeCtrlPosition == -2 ) { + mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_NP ) ); + } + else if( BrakeCtrlPosition > 4.5 ) { + mvOccupied->BrakeLevelSet( 10 ); + } + else if( BrakeCtrlPosition > 3.70 ) { + mvOccupied->BrakeLevelSet( 9 ); + } + else { + mvOccupied->BrakeLevelSet( round( ( BrakeCtrlPosition * 0.4 - 0.1 ) / 0.15 ) ); + } + } + } + //2. Check the type of Secondary Brake Handle + + //3. Check the type od EIMCtrlType +/* + if (mvOccupied->EIMCtrlType > 0) + { + if (mvOccupied->EIMCtrlType == 1) //traxx + { + if (mvOccupied->LocalBrakePosA > 0.95) mvOccupied->MainCtrlPos = 0; + } + else if (mvOccupied->EIMCtrlType == 2) //elf + { + if (mvOccupied->LocalBrakePosA > 0.95) mvOccupied->MainCtrlPos = 1; + } + } +*/ + if( mvOccupied->UniCtrlIntegratedLocalBrakeCtrl + && mvOccupied->LocalBrakePosA > 0.95 ) { + while( IncBrakeEIM() ) { ; } + } + + //4. Check Speed Control System + if (mvOccupied->EngineType == TEngineType::ElectricInductionMotor && mvOccupied->ScndCtrlPosNo > 1 && mvOccupied->SpeedCtrlTypeTime) + { + double SpeedCntrlVel = + ActualProximityDist > std::max(50.0, fMaxProximityDist) ? + VelDesired : + min_speed(VelDesired, VelNext); + SpeedCntrlVel = 10 * std::floor(SpeedCntrlVel*0.1); + if (mvOccupied->ScndCtrlPosNo == 4) + { + if (mvOccupied->NewSpeed + 0.1 < SpeedCntrlVel) + mvOccupied->ScndCtrlPos = 3; + if (mvOccupied->NewSpeed - 0.1 > SpeedCntrlVel) + mvOccupied->ScndCtrlPos = 1; + } + } + //5. Check Main Controller in Dizels + //5.1. Digital controller in DMUs with hydro + if (mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->EIMCtrlType == 3) + { + + DizelPercentage_Speed = DizelPercentage; //wstepnie procenty + auto MinVel{ std::min(mvControlling->hydro_TC_LockupSpeed, mvControlling->Vmax / 6) }; //minimal velocity + //when speed controll unit is active - start with the procedure + if (mvControlling->SpeedCtrl && mvControlling->ScndCtrlPos > 0) { + if (mvControlling->ScndCtrlPos > 0 && mvControlling->Vel < 1 + mvControlling->SpeedCtrlUnit.StartVelocity && DizelPercentage > 0) + DizelPercentage_Speed = 101; //keep last position to start + } + else if (VelDesired > MinVel) //more power for faster ride + { + auto const Factor{ 10 * mvControlling->Vmax / (mvControlling->Vmax + 3 * mvControlling->Vel) }; + auto DesiredPercentage{ std::clamp( + VelDesired > mvControlling->Vel ? (VelDesired - mvControlling->Vel) / Factor : 0, + 0.0, 1.0) }; //correction for reaching desired velocity + if (VelDesired < 0.5 * mvControlling->Vmax //low velocity and reaching desired + && VelDesired - mvControlling->Vel < 10) { + DesiredPercentage = std::min(DesiredPercentage, 0.75); + } + DizelPercentage_Speed = std::round(DesiredPercentage * DizelPercentage); + } + else //slow acceleration during shunting wth minimal velocity + { + DizelPercentage_Speed = std::min(DizelPercentage, mvControlling->Vel < 0.99 * VelDesired ? 1 : 0); + } + + auto const DizelActualPercentage { int(100.4 * mvControlling->eimic_real) }; + + auto const PosInc { mvControlling->MainCtrlPosNo }; + auto PosDec { 0 }; + for( int i = PosInc; i >= 0; --i ) { + if( mvControlling->UniCtrlList[i].SetCtrlVal <= 0 + && mvControlling->UniCtrlList[i].SpeedDown > 0.01 ) { + PosDec = i; + break; + } + } + + if( std::abs( DizelPercentage_Speed - DizelActualPercentage ) > 0 ) { + + if( PosDec > 0 + && ( DizelActualPercentage - DizelPercentage_Speed > 50 + || ( DizelPercentage_Speed == 0 + && DizelActualPercentage > 10 ) ) ) { + //one position earlier should be fast decreasing + PosDec -= 1; + } + auto const DesiredPos { ( + DizelPercentage_Speed > DizelActualPercentage ? + PosInc : + PosDec ) }; + while( mvControlling->MainCtrlPos > DesiredPos ) { mvControlling->DecMainCtrl( 1 ); } + while( mvControlling->MainCtrlPos < DesiredPos ) { mvControlling->IncMainCtrl( 1 ); } + } + if (BrakeCtrlPosition < 0.1) //jesli nie hamuje + mvOccupied->BrakeLevelSet(mvControlling->UniCtrlList[mvControlling->MainCtrlPos].mode); //zeby nie bruzdzilo machanie zespolonym + } + else + //5.2. Analog direct controller + if (mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->Vmax > 30) + { + int MaxPos = mvControlling->MainCtrlPosNo; + int MinPos = MaxPos; + for (int i = MaxPos; i > 1 && mvControlling->RList[i].Mn > 0; i--) MinPos = i; + if (MaxPos > MinPos && mvControlling->MainCtrlPos > 0 && AccDesired > 0) + { + double Factor = 5 * mvControlling->Vmax / (mvControlling->Vmax + mvControlling->Vel); + int DesiredPos = MinPos + (MaxPos - MinPos)*(VelDesired > mvControlling->Vel ? (VelDesired - mvControlling->Vel) / Factor : 0); + if (DesiredPos > MaxPos) DesiredPos = MaxPos; + if (DesiredPos < MinPos) DesiredPos = MinPos; + if (!mvControlling->SlippingWheels) + { + while (mvControlling->MainCtrlPos > DesiredPos) mvControlling->DecMainCtrl(1); + if (mvControlling->Vel>mvControlling->dizel_minVelfullengage) + while (mvControlling->MainCtrlPos < DesiredPos) mvControlling->IncMainCtrl(1); + } + } + } + // 5.5 universal control for diesel electric vehicles + if (mvControlling->EngineType == TEngineType::DieselElectric && mvControlling->EIMCtrlType == 3 && AccDesired >= 0.0 && mvControlling->StLinFlag) + { + // NOTE: partial implementation for speedinc/dec + // TBD, TODO: implement fully? + auto const PosInc{mvControlling->MainCtrlPosNo}; + auto PosKeep{0}; + auto PosDec{0}; + for (int i = PosInc; i >= 0; --i) + { + if (mvControlling->UniCtrlList[i].SetCtrlVal <= 0) + { + if (mvControlling->UniCtrlList[i].SpeedDown == 0.0) + { + PosKeep = i; + } + if (mvControlling->UniCtrlList[i].SpeedDown > 0.01) + { + PosDec = i; + break; + } + } + } + + auto const DesiredPos{(AccDesired > AbsAccS + 0.05 ? PosInc : AccDesired < AbsAccS - 0.05 ? PosDec : PosKeep)}; + + while (mvControlling->MainCtrlPos > DesiredPos && mvControlling->DecMainCtrl(1)) + { + ; + } + while (mvControlling->MainCtrlPos < DesiredPos && mvControlling->IncMainCtrl(1)) + { + ; + } + } + //6. UniversalBrakeButtons + //6.1. Checking flags for Over pressure + if (std::abs(BrakeCtrlPosition - gbh_FS)<0.5) { + UniversalBrakeButtons |= TUniversalBrake::ub_HighPressure | TUniversalBrake::ub_Overload; + } + else { + UniversalBrakeButtons &= ~(TUniversalBrake::ub_HighPressure | TUniversalBrake::ub_Overload); + } + //6.2. Setting buttons + for (int i = 0; i < 3; i++) { + mvOccupied->UniversalBrakeButton(i, UniversalBrakeButtons & mvOccupied->UniversalBrakeButtonFlag[i]); + } +}; + +void TController::CheckTimeControllers() +{ + // TODO: rework this method to use hint system and regardless of driver type + if( false == AIControllFlag || 0 == mvControlling->CabActive ) { return; } + + //1. Check the type of Main Brake Handle + if( BrakeSystem == TBrakeSystem::ElectroPneumatic && mvOccupied->Handle->TimeEP && !ForcePNBrake ) + { + mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_EPN)); + } + if( ( BrakeSystem == TBrakeSystem::Pneumatic || ForcePNBrake ) && mvOccupied->Handle->Time ) + { + if (BrakeCtrlPosition > 0) + mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_MB)); + else + mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_RP)); + } + //2. Check the type of Secondary Brake Handle + + //3. Check the type od EIMCtrlType + if (mvOccupied->EIMCtrlType > 0) + { + if (mvOccupied->EIMCtrlType == 1) //traxx + { + if (mvOccupied->MainCtrlPos > 3) mvOccupied->MainCtrlPos = 5; + if (mvOccupied->MainCtrlPos < 3) mvOccupied->MainCtrlPos = 1; + } + else if (mvOccupied->EIMCtrlType == 2) //elf + { + auto const emergencypositions{mvOccupied->EIMCtrlEmergencyPositions()}; + if (mvOccupied->eimic > 0) mvOccupied->MainCtrlPos = 3 + emergencypositions; + if (mvOccupied->eimic < 0) mvOccupied->MainCtrlPos = 2 + emergencypositions; + } + } + //4. Check Speed Control System + if (mvOccupied->EngineType == TEngineType::ElectricInductionMotor && mvOccupied->ScndCtrlPosNo > 1 && mvOccupied->SpeedCtrlTypeTime && mvOccupied->ScndCtrlPosNo == 4) + { + mvOccupied->ScndCtrlPos = 2; + } + + //5. Check Main Controller in Dizels + //5.1. Digital controller in DMUs with hydro + if (mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->EIMCtrlType == 3) + { + int DizelActualPercentage = 100.4 * mvControlling->eimic_real; + int NeutralPos = mvControlling->MainCtrlPosNo - 1; //przedostatnia powinna wstrzymywać - hipoteza robocza + for (int i = mvControlling->MainCtrlPosNo; i >= 0; i--) + if (mvControlling->UniCtrlList[i].SetCtrlVal <= 0 && mvControlling->UniCtrlList[i].SpeedDown < 0.01) //niby zero, ale nie zmniejsza procentów + { + NeutralPos = i; + break; + } + if (BrakeCtrlPosition < 0.1) //jesli nie hamuje + { + if (DizelActualPercentage >= DizelPercentage_Speed && mvControlling->MainCtrlPos > NeutralPos) + while (mvControlling->MainCtrlPos > NeutralPos) mvControlling->DecMainCtrl(1); + if (DizelActualPercentage <= DizelPercentage_Speed && mvControlling->MainCtrlPos < NeutralPos) + while (mvControlling->MainCtrlPos < NeutralPos) mvControlling->IncMainCtrl(1); + mvOccupied->BrakeLevelSet(mvControlling->UniCtrlList[mvControlling->MainCtrlPos].mode); //zeby nie bruzdzilo machanie zespolonym + } + } +}; diff --git a/vehicle/ai/doors.cpp b/vehicle/ai/doors.cpp new file mode 100644 index 000000000..967e603cb --- /dev/null +++ b/vehicle/ai/doors.cpp @@ -0,0 +1,294 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the doors, the stops and the departure + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/mover.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + + +// otwieranie/zamykanie drzwi w składzie albo (tylko AI) EZT +void TController::Doors( bool const Open, int const Side ) { + // otwieranie drzwi + if( true == Open ) { + + auto const lewe = pVehicle->DirectionGet() > 0 ? 1 : 2; + auto const prawe = 3 - lewe; + // doorsteps as the timetable asks, before the doors open (eu07/maszyna#95) + if( auto const doorstep { timetable::doorstep( m_stopflags ) }; + doorstep.has_value() && mvOccupied->Doors.step_enabled != *doorstep ) { + cue_action( *doorstep ? driver_hint::doorstepon : driver_hint::doorstepoff ); + } + // grant door control permission if it's not automatic + // TBD: stricter requirements? + if( true == pVehicle->MoverParameters->Doors.permit_needed ) { + if( Side & prawe ) { + cue_action( driver_hint::doorrightpermiton ); + } + if( Side & lewe ) { + cue_action( driver_hint::doorleftpermiton ); + } + } + // consist-wide remote signals to open doors doors + // NOTE: mixed controls are left up to passengers to open doors by themselves, unless the timetable has + // the driver open all the doors + if( true == timetable::opens_doors( *pVehicle->MoverParameters, m_stopflags ) ) { + if( Side & prawe ) { + cue_action( driver_hint::doorrightopen ); + } + if( Side & lewe ) { + cue_action( driver_hint::doorleftopen ); + } + } + } + // zamykanie drzwi + else { + // if the doors are already closed and locked then there's nothing to do + if( false == doors_permit_active() + && false == doors_open() ) { + drivingFlags.doorOpened = false; + drivingFlags.departureWarned = false; + return; + } + + if (mvOccupied->Doors.has_warning && !drivingFlags.departureWarned) + { + if (!mvOccupied->DepartureSignal) + { + // Not warned yet, not warning yet - start the warning signal. + cue_action( driver_hint::departuresignalon ); // załącenie bzyczka + fActionTime = Random( -0.8, -0.3 ); // 0.3-0.8 second buzzer + return; + } + // Not warned yet, warning now - stop the warning signal and mark it as done. + cue_action( driver_hint::departuresignaloff ); + fActionTime = Random( -0.2, 0.0 ); // Wait just a bit more before departing + drivingFlags.departureWarned = true; + return; + } + + if( true == doors_open() && (pVehicle->MoverParameters->Doors.close_control == control_t::conductor || pVehicle->MoverParameters->Doors.close_control == control_t::driver || + pVehicle->MoverParameters->Doors.close_control == control_t::mixed) ) { + // consist-wide remote signals to close doors + cue_action(driver_hint::doorrightclose); + cue_action(driver_hint::doorleftclose); + } + if( true == doors_permit_active() ) { + cue_action( driver_hint::doorrightpermitoff ); + cue_action( driver_hint::doorleftpermitoff ); + } + // if applicable close manually-operated doors in vehicles which may ignore remote signals + { + const auto *vehicle = pVehicles[ end::front ]; // pojazd na czole składu + while( vehicle != nullptr ) { + // zamykanie drzwi w pojazdach - flaga zezwolenia była by lepsza + auto const ismanualdoor { + vehicle->MoverParameters->Doors.auto_velocity == -1.f + && ( vehicle->MoverParameters->Doors.close_control == control_t::passenger + || vehicle->MoverParameters->Doors.close_control == control_t::mixed ) }; + + if( true == ismanualdoor + && ( vehicle->LoadExchangeTime() == 0.f + || vehicle->MoverParameters->Vel > EU07_AI_MOVEMENT ) ) { + vehicle->MoverParameters->OperateDoors( side::right, false, range_t::local ); + vehicle->MoverParameters->OperateDoors( side::left, false, range_t::local ); + } + vehicle = vehicle->Next(); // pojazd podłączony z tyłu (patrząc od czoła) + } + } + fActionTime = Random(-3.5, -1.0); // 1.0-3.5 sec wait + drivingFlags.doorOpened = false; // zostały zamknięte - nie wykonywać drugi raz + drivingFlags.departureWarned = false; + } +} + +// returns true if any vehicle in the consist has open doors +bool +TController::doors_open() const { + + return IsAnyDoorOpen[side::right] || IsAnyDoorOpen[side::left]; +} + +bool +TController::doors_permit_active() const { + + return IsAnyDoorPermitActive[side::right] || IsAnyDoorPermitActive[side::left]; +} + +void +TController::announce( announcement_t const Announcement ) { + + m_lastannouncement = Announcement; + + if( IsCargoTrain ) { + // cargo trains aren't likely to have announcement systems, so we can skip the procedure altogether + return; + } + + auto *vehicle { pVehicles[ end::front ] }; + while( vehicle ) { + vehicle->announce( Announcement ); + vehicle = vehicle->Next(); + } +} + +void +TController::control_doors() { + + if( false == doors_open() ) { return; } + // jeżeli jedzie + // nie zamykać drzwi przy drganiach, bo zatrzymanie na W4 akceptuje niewielkie prędkości + if( mvOccupied->Vel > EU07_AI_MOVEMENT ) { + Doors( false ); + return; + } + // HACK: crude way to deal with automatic door opening on W4 preventing further ride + // for human-controlled vehicles with no door control and dynamic brake auto-activating with door open + // TODO: check if this situation still happens and the hack is still needed + if( false == AIControllFlag && (mvControlling->EngineType == TEngineType::DieselEngine ? mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0 : mvControlling->MainCtrlPowerPos() > 0) ) { + // for diesel engines react when engine is put past idle revolutions + // for others straightforward master controller check + Doors(false); + return; + } +} + +void +TController::check_departure() { + + if(false == OrderCurrentGet().HasAny( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank | DriverOrder::connect ) ) { return; } + // odjechać sam może tylko jeśli jest w trybie jazdy + // automatyczne ruszanie po odstaniu albo spod SBL + if( VelSignal == 0.0 + && WaitingTime > 0.0 + && mvOccupied->RunningTrack.Velmax != 0.0 ) { + // jeśli stoi, a upłynął czas oczekiwania i tor ma niezerową prędkość + if( OrderCurrentGet() & (DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank) + && drivingFlags.stopHere ) { + // zakaz ruszania z miejsca bez otrzymania wolnej drogi + WaitingTime = -WaitingExpireTime; + } + else { + if( mvOccupied->CategoryFlag & 1 ) { // jeśli pociąg + PrepareDirection(); // zmieni ustawiony kierunek + SetVelocity( 20, 20 ); // jak się nastał, to niech jedzie 20km/h + WaitingTime = 0.0; + fWarningDuration = 1.5; // a zatrąbić trochę + } + else { // samochód ma stać, aż dostanie odjazd, chyba że stoi przez kolizję + if( eStopReason == stopBlock + && Obstacle.distance > fDriverDist ) { + PrepareDirection(); // zmieni ustawiony kierunek + SetVelocity( -1, -1 ); // jak się nastał, to niech jedzie + WaitingTime = 0.0; + } + } + } + } + else if( VelSignal == 0.0 && VelNext > 0.0 && mvOccupied->Vel < 1.0 && (false == iCoupler.Empty() || ( false == drivingFlags.stopHere )) ) { + // Ra: tu jest coś nie tak, bo bez tego warunku ruszało w manewrowym !!!! + SetVelocity(VelNext, VelNext, stopSem); // omijanie SBL + } +} + +// verify progress of load exchange +void +TController::check_load_exchange() { + + ExchangeTime = 0.f; + DoesAnyDoorNeedOpening = false; + + if( fStopTime > 0 ) { return; } + + // czas postoju przed dalszą jazdą (np. na przystanku) + auto *vehicle { pVehicles[ end::front ] }; + while( vehicle != nullptr ) { + auto const vehicleexchangetime { vehicle->LoadExchangeTime() }; + DoesAnyDoorNeedOpening |= vehicleexchangetime > 0 && vehicle->LoadExchangeSpeed() == 0; + ExchangeTime = std::max( ExchangeTime, vehicleexchangetime ); + vehicle = vehicle->Next(); + } + + if( pVehicle->DirectionGet() != m_lastexchangedirection ) { + // generally means the ai driver moved to the opposite end of the consist + // TODO: investigate whether user playing with the reverser can mess this up + auto const left { m_lastexchangedirection > 0 ? 1 : 2 }; + auto const right { 3 - left }; + m_lastexchangeplatforms = + ( ( m_lastexchangeplatforms & left ) != 0 ? right : 0 ) + + ( ( m_lastexchangeplatforms & right ) != 0 ? left : 0 ); + m_lastexchangedirection = pVehicle->DirectionGet(); + } + if( false == TrainParams.IsMaintenance() + && ( false == drivingFlags.doorOpened + || true == DoesAnyDoorNeedOpening ) ) { + drivingFlags.doorOpened = true; // nie wykonywać drugi raz + remove_hint( driver_hint::doorleftopen ); + remove_hint( driver_hint::doorrightopen ); + Doors( true, m_lastexchangeplatforms ); + } +} + +void +TController::GuardOpenDoor() { + if (drivingFlags.guardOpenDoor) { + auto *vehicle{ pVehicles[end::front] }; + while (vehicle != nullptr && vehicle->MoverParameters->Doors.range == 0) { + vehicle = vehicle->Next(); + } + if (vehicle != nullptr && vehicle->MoverParameters->Doors.range > 0) { + auto const lewe = vehicle->DirectionGet() > 0 ? 1 : 2; + auto const prawe = 3 - lewe; + if (m_lastexchangeplatforms & lewe) { + vehicle->MoverParameters->OperateDoors(side::left, true, range_t::local); + } + if (m_lastexchangeplatforms & prawe) { + vehicle->MoverParameters->OperateDoors(side::right, true, range_t::local); + } + } + else { + drivingFlags.guardOpenDoor = false; + } + } +} diff --git a/vehicle/ai/driver.cpp b/vehicle/ai/driver.cpp new file mode 100644 index 000000000..20d6e6fa1 --- /dev/null +++ b/vehicle/ai/driver.cpp @@ -0,0 +1,599 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the AI driver: construction, its update, taking over a vehicle, what it tells about itself + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/mover.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + +const double HardReactionTime = 0.2; +const double EasyAcceleration = 0.85; //[m/ss] +const double HardAcceleration = 9.81; +bool WriteLogFlag = false; + +//--------------------------------------------------------------------------- + +TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, bool Primary) :// czy ma aktywnie prowadzić? + AIControllFlag( AI ), pVehicle( NewControll ) +{ + if( pVehicle != nullptr ) { + pVehicles[ end::front ] = pVehicle->GetFirstDynamic( end::front ); // pierwszy w kierunku jazdy (Np. Pc1) + pVehicles[ end::rear ] = pVehicle->GetFirstDynamic( end::rear ); // ostatni w kierunku jazdy (końcówki) + } + else { + pVehicles[ end::front ] = nullptr; + pVehicles[ end::rear ] = nullptr; + } + ControllingSet(); // utworzenie połączenia do sterowanego pojazdu + if( mvOccupied != nullptr ) { + iDirectionOrder = mvOccupied->CabActive; // 1=do przodu (w kierunku sprzęgu 0) + VehicleName = mvOccupied->Name; + + if( is_car() ) { // samochody: na podst. http://www.prawko-kwartnik.info/hamowanie.html + // fDriverBraking=0.0065; //mnożone przez (v^2+40*v) [km/h] daje prawie drogę hamowania [m] + fDriverBraking = 0.03; // coś nie hamują te samochody zbyt dobrze + fDriverDist = 5.0; // 5m - zachowywany odstęp przed kolizją + fVelPlus = 10.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania + fVelMinus = 2.0; // margines prędkości powodujący załączenie napędu + } + else { // pociągi i statki + fDriverBraking = 0.06; // mnożone przez (v^2+40*v) [km/h] daje prawie drogę hamowania [m] + fDriverDist = 50.0; // 50m - zachowywany odstęp przed kolizją + fVelPlus = 5.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania + fVelMinus = 5.0; // margines prędkości powodujący załączenie napędu + } + + // fAccThreshold może podlegać uczeniu się - hamowanie powinno być rejestrowane, a potem analizowane + // próg opóźnienia dla zadziałania hamulca + fAccThreshold = is_emu() ? -0.55 : is_dmu() ? -0.45 : -0.2; +/* + // HACK: emu with induction motors need to start their braking a bit sooner than the ones with series motors + if( ( mvOccupied->TrainType == train_type::emu ) + && ( mvControlling->EngineType == TEngineType::ElectricInductionMotor ) ) { + fAccThreshold += 0.10; + } +*/ + } + // TrainParams=NewTrainParams; + // if (TrainParams) + // asNextStop=TrainParams.NextStop(); + // else + TrainParams = TTrainParameters("none"); // rozkład jazdy + // OrderCommand=""; + // OrderValue=0; + OrdersClear(); + + if( true == Primary ) { + drivingFlags.primary = true; // aktywnie prowadzące pojazd + } + + if( mvOccupied != nullptr ) { + SetDriverPsyche(); // na końcu, bo wymaga ustawienia zmiennych + } + TableClear(); + + // the logs of all, begun at once as they always were. one of a train only at its first line (update_logs): every + // crew is made primary here, and the drivers but one of a train with crews in more vehicles are made passive + // before it starts, so they get no file with only the header + if( WriteLogFlag ) { + begin_physicslog(); + } + + // HACK: give the simulation a small window to potentially replace the AI with a human driver + fActionTime = -5.0; +}; + +TController::~TController() +{ // wykopanie mechanika z roboty +}; + +TBrakeSystem TController::consist_brake_system() const { + + if( mvOccupied->BrakeSystem != TBrakeSystem::ElectroPneumatic ) { return mvOccupied->BrakeSystem; } + + auto isepcapable = true; + if( pVehicles[ end::front ] != pVehicles[ end::rear ] ) { + // more detailed version, will use manual braking also for coupled sets of controlled vehicles + auto *vehicle = pVehicles[ end::front ]; // start from first + while( true == isepcapable + && vehicle != nullptr ) { + // NOTE: we could simplify this by doing only check of the rear coupler, but this can be quite tricky in itself + // TODO: add easier ways to access front/rear coupler taking into account vehicle's direction + isepcapable = (vehicle->MoverParameters->Couplers[end::front].Connected == nullptr || + (vehicle->MoverParameters->Couplers[end::front].CouplingFlag & Coupling::control && vehicle->MoverParameters->Couplers[end::front].Connected->Power > -1)) && + (vehicle->MoverParameters->Couplers[end::rear].Connected == nullptr || + (vehicle->MoverParameters->Couplers[end::rear].CouplingFlag & Coupling::control && vehicle->MoverParameters->Couplers[end::rear].Connected->Power > -1)); + vehicle = vehicle->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) + } + } + return isepcapable ? TBrakeSystem::ElectroPneumatic : TBrakeSystem::Pneumatic; +} + +std::pair TController::next_speed_limit() const { + + auto const speedlimit { static_cast( VelDesired ) }; + auto nextspeedlimit { speedlimit }; + auto nextspeedlimitdistance { std::numeric_limits::max() }; + if( speedlimit == 0 ) { + // if we aren't allowed to move then any next speed limit is irrelevant + return { nextspeedlimit, nextspeedlimitdistance }; + } + // nie przekraczać rozkladowej + auto const schedulespeedlimit { ( + OrderCurrentGet().HasAny( DriverOrder::obeyTrain | DriverOrder::bank ) && TrainParams.TTVmax > 0.0 ? static_cast( TrainParams.TTVmax ) : + false == OrderCurrentGet().HasAny( DriverOrder::obeyTrain | DriverOrder::bank ) ? static_cast( fShuntVelocity ) : + -1 ) }; + // first take note of any speed change which should occur after passing potential current speed limit + if( VelLimitLastDist.second > 0 ) { + nextspeedlimit = min_speed( schedulespeedlimit, static_cast( VelLimitLastDist.first ) ); + nextspeedlimitdistance = VelLimitLastDist.second; + } + // then take into account speed change ahead, compare it with speed after potentially clearing last limit + // lower of these two takes priority; otherwise limit lasts at least until potential last limit is cleared + auto const noactivespeedlimit { VelLimitLastDist.second < 0 }; + if( auto const speedatproximitydistance { min_speed( schedulespeedlimit, static_cast( VelNext ) ) }; speedatproximitydistance == nextspeedlimit ) { + if( noactivespeedlimit ) { + nextspeedlimit = speedatproximitydistance; + nextspeedlimitdistance = ActualProximityDist; + } + } + else if( speedatproximitydistance < nextspeedlimit ) { + // if the speed limit ahead is more strict than our current limit, it's important enough to report + if( speedatproximitydistance < VelDesired ) { + nextspeedlimit = speedatproximitydistance; + nextspeedlimitdistance = ActualProximityDist; + } + // otherwise report it only if it's located after our current (lower) limit ends + else if( ActualProximityDist > nextspeedlimitdistance ) { + nextspeedlimit = speedatproximitydistance; + nextspeedlimitdistance = ActualProximityDist; + } + } + else if( noactivespeedlimit ) { // implicit proximity > last, report only if last limit isn't present + nextspeedlimit = speedatproximitydistance; + nextspeedlimitdistance = ActualProximityDist; + } + // HACK: if our current speed limit extends beyond our scan range don't display potentially misleading information about its length + if( nextspeedlimitdistance >= EU07_AI_SPEEDLIMITEXTENDSBEYONDSCANRANGE ) { + nextspeedlimit = speedlimit; + } + // HACK: hide next speed limit if the 'limit' is a vehicle in front of us + else if( ActualProximityDist == std::abs( TrackObstacle() ) ) { + nextspeedlimit = speedlimit; + } + return { nextspeedlimit, nextspeedlimitdistance }; +} + +blackbox::ai_reference TController::ai_reference() const { + + blackbox::ai_reference ai; + ai.target_kmh = static_cast( VelDesired ); + if( auto const [ limit, distance ] { next_speed_limit() }; limit != static_cast( VelDesired ) ) { + ai.next_limit_kmh = static_cast( limit ); + ai.next_limit_distance = static_cast( distance ); + } + ai.acceleration = static_cast( AccDesired ); + ai.braking_distance = static_cast( fBrakeDist ); + ai.timetable_vmax_kmh = ( TrainParams.TTVmax > 0.0 ? static_cast( TrainParams.TTVmax ) : -1.0f ); + ai.track_vmax_kmh = static_cast( mvOccupied->RunningTrack.Velmax ); + return ai; +} + +void TController::record_station( TSpeedPos const &Point, std::uint8_t const Kind ) const { + + if( Point.evEvent == nullptr ) { return; } + blackbox::station_event entry; + entry.kind = Kind; + auto const row { TrainParams.StationIndex }; + entry.row = static_cast( std::max( 0, row ) ); + entry.station = asNextStop; + entry.position = Point.evEvent->input_location(); + // the stop point may be moved back from the indicator, to where the head of the train is to stop + entry.distance = static_cast( Point.fDist + Point.fMoved ); + entry.stop_at = static_cast( Point.fMoved ); + entry.train_length = static_cast( fLength ); + entry.platform = static_cast( Point.evEvent->input_value( 2 ) ); + if( row >= 0 && row <= TrainParams.StationCount ) { + auto const &line { TrainParams.TimeTable[ row ] }; + entry.arrival = ( line.Ah >= 0 ? static_cast( line.Ah * 60 ) + line.Am : -1.0f ); + entry.departure = ( line.Dh >= 0 ? static_cast( line.Dh * 60 ) + line.Dm : -1.0f ); + } + simulation::Blackbox.station( pVehicles[ end::front ], std::move( entry ) ); +} + +void TController::WaitingSet(double Seconds) +{ // ustawienie odczekania po zatrzymaniu (ustawienie w trakcie jazdy zatrzyma) + fStopTime = -Seconds; // ujemna wartość oznacza oczekiwanie (potem >=0.0) +} + +void TController::SetVelocity(double NewVel, double NewVelNext, TStopReason r) +{ // ustawienie nowej prędkości + WaitingTime = -WaitingExpireTime; // przypisujemy -WaitingExpireTime, a potem porównujemy z zerem + if (NewVel == 0.0) { // jeśli ma stanąć + if (r != stopNone) // a jest powód podany + eStopReason = r; // to zapamiętać nowy powód + } + else { + eStopReason = stopNone; // podana prędkość, to nie ma powodów do stania + // to całe poniżej to warunki zatrąbienia przed ruszeniem + if( is_train() // tylko pociągi trąbią (unimogi tylko na torach, więc trzeba raczej sprawdzać tor) + && OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank | DriverOrder::connect | DriverOrder::prepareEngine) // jeśli jedzie w dowolnym trybie + && drivingFlags.startHorn // jezeli trąbienie włączone + && ( false == drivingFlags.startHornDone && false == drivingFlags.connect ) // jeśli nie zatrąbione i nie jest to moment podłączania składu + && mvOccupied->Vel < 1.0 // jesli stoi (na razie, bo chyba powinien też, gdy hamuje przed semaforem) + && ( NewVel >= 1.0 || NewVel < 0.0 ) ) { // o ile prędkość jest znacząca zatrąb po odhamowaniu + drivingFlags.startHornNow = true; + } + } + VelSignal = NewVel; // prędkość zezwolona na aktualnym odcinku + VelNext = NewVelNext; // prędkość przy następnym obiekcie +} + +double TController::BrakeAccFactor() const +{ + double Factor = 1.0; + + if( fAccThreshold != 0.0 + && AccDesired < 0.0 + && ( ActualProximityDist > fMinProximityDist + || mvOccupied->Vel > VelDesired + fVelPlus ) ) { + Factor += fBrakeReaction * (/*mvOccupied->BrakeCtrlPosR*/ BrakeCtrlPosition < 0.5 ? 1.5 : 1) * mvOccupied->Vel / ( std::max( 0.0, ActualProximityDist ) + 1 ) * ( ( AccDesired - AbsAccS ) / fAccThreshold ); + } +/* + if (mvOccupied->TrainType == train_type::dmu && mvOccupied->Vel > 40 && VelNext<40) + Factor *= 1 + 0.25 * ( (1600 - VelNext * VelNext) / (mvOccupied->Vel * mvOccupied->Vel) ); +*/ + return Factor; +} + +void TController::SetDriverPsyche() { + + if (Psyche == Aggressive && OrderCurrentGet() == DriverOrder::obeyTrain) { + ReactionTime = HardReactionTime; // w zaleznosci od charakteru maszynisty + if (is_car()) { + WaitingExpireTime = 1; // tyle ma czekać samochód, zanim się ruszy + AccPreferred = 3.0; //[m/ss] agresywny + } + else { + WaitingExpireTime = 61; // tyle ma czekać, zanim się ruszy + AccPreferred = HardAcceleration; // agresywny + } + } + else { + ReactionTime = EasyReactionTime; // spokojny + if (is_car()) { + WaitingExpireTime = 3; // tyle ma czekać samochód, zanim się ruszy + AccPreferred = 2.0; //[m/ss] + } + else { + WaitingExpireTime = 65; // tyle ma czekać, zanim się ruszy + AccPreferred = EasyAcceleration; + } + } +} + +void +TController::Update( double const Timedelta ) { + // uruchamiać przynajmniej raz na sekundę + if( ( false == drivingFlags.primary ) ) { return; } // pasywny nic nie robi + if( false == simulation::is_ready ) { return; } + + update_timers( Timedelta ); + update_logs( Timedelta ); + + auto const reactiontime { std::min( ReactionTime, 2.0 ) }; + + if( LastReactionTime < reactiontime ) { return; } + LastReactionTime -= reactiontime; +/* + // TBD, TODO: put this in an appropriate place, or get rid of it + // NOTE: this section moved all cars to the edge of their respective roads + // it may have some use eventually for collision avoidance, + // but when enabled all the time it produces silly effect + if( mvOccupied->Vel > 1.0 ) { + // przy prowadzeniu samochodu trzeba każdą oś odsuwać oddzielnie, inaczej kicha wychodzi + if (mvOccupied->CategoryFlag & 2) // jeśli samochód + // if (fabs(mvOccupied->OffsetTrackH)Dim.W) //Ra: szerokość drogi tu powinna być? + if (!mvOccupied->ChangeOffsetH(-0.01 * mvOccupied->Vel * dt)) // ruch w poprzek drogi + mvOccupied->ChangeOffsetH(0.01 * mvOccupied->Vel * dt); // Ra: co to miało być, to nie wiem + } +*/ + update_hints(); + // main ai update routine + determine_consist_state(); + determine_braking_distance(); + determine_proximity_ranges(); + // vicinity check + auto const awarenessrange { + std::max( + 750.0, + mvOccupied->Vel > EU07_AI_MOVEMENT ? + 400 + fBrakeDist : + 30.0 * fDriverDist ) }; // 1500m dla stojących pociągów; + if( is_active() ) { + scan_route( awarenessrange ); + } + scan_obstacles( awarenessrange ); + // generic actions + control_security_system( reactiontime ); + if( iEngineActive ) { + control_wheelslip(); + control_horns( reactiontime ); + control_pantographs(); + if( fActionTime > 0.0 ) { + // potentially delayed and/or low priority actions + control_lights(); + control_doors(); + control_compartment_lights(); + } + } + CheckTimeControllers(); + // external command actions + UpdateCommand(); + // mode specific actions + handle_engine(); + handle_orders(); + // a brake the wagon inspector left to cut out while the train was moving + reinspect_brakes(); + // situational velocity and acceleration adjustments + pick_optimal_speed( awarenessrange ); + if( iEngineActive ) { + control_tractive_and_braking_force(); + } + SetTimeControllers(); +} + +//-----------koniec skanowania semaforow + +void TController::TakeControl( bool const Aidriver, bool const Forcevehiclecheck ) +{ // przejęcie kontroli przez AI albo oddanie + if (AIControllFlag == Aidriver && !Forcevehiclecheck) + return; // już jest jak ma być + if( AIControllFlag != Aidriver ) { + // the autopilot switched on or off + simulation::Blackbox.driver_changed( pVehicle, Aidriver ); + } + if (Aidriver) //żeby nie wykonywać dwa razy + { // teraz AI prowadzi + AIControllFlag = AIdriver; + pVehicle->Controller = AIdriver; + // the AI doesn't operate the headlight dimmer, drop the state left by the human driver + // so the lights set by the AI aren't hidden (dimmer in off position) or dimmed + pVehicle->HeadlightsAoff = false; + pVehicle->HeadlightsBoff = false; + pVehicle->DimHeadlights = false; + pVehicle->HighBeamLights = false; + control_lights(); // reinicjalizacja swiatel + mvOccupied->CabActivisation(true); + iDirection = 0; // kierunek jazdy trzeba dopiero zgadnąć + TableClear(); // ponowne utworzenie tabelki, bo człowiek mógł pojechać niezgodnie z sygnałami + if( action() != TAction::actSleep ) { + // gdy zgaszone światła, flaga podjeżdżania pod semafory pozostaje bez zmiany + // conditional below disabled to get around the situation where the AI train does nothing ever + // because it is waiting for orders which don't come until the engine is engaged, i.e. effectively never + if( OrderCurrentGet() ) { + // jeśli coś robi + PrepareEngine(); // niech sprawdzi stan silnika + } + else { + // jeśli nic nie robi + OrderNext( DriverOrder::prepareEngine ); + if( pVehicle->MoverParameters->iLights[ ( mvOccupied->CabActive < 0 ? + end::rear : + end::front ) ] + & ( light::headlight_left | light::headlight_right | light::headlight_upper ) ) // któreś ze świateł zapalone? + { // od wersji 357 oczekujemy podania komend dla AI przez scenerię +/* + if( pVehicle->MoverParameters->iLights[ mvOccupied->CabActive < 0 ? end::rear : end::front ] & light::headlight_upper ) // górne światło zapalone + OrderNext( DriverOrder::obeyTrain ); // jazda pociągowa + else + OrderNext( DriverOrder::shunt ); // jazda manewrowa +*/ + if( mvOccupied->Vel >= 1.0 ) // jeśli jedzie (dla 0.1 ma stać) + drivingFlags.stopHere = false; // to ma nie czekać na sygnał, tylko jechać + else + drivingFlags.stopHere = true; // a jak stoi, to niech czeka + } + } + CheckVehicles(); // ustawienie świateł + } + } + else + { // a teraz użytkownik + if (eAction == TAction::actSleep || OrderCurrentGet() == DriverOrder::waitForOrders) // gasimy swiatla jesli przejmujemy odstawione + pVehicle->RaLightsSet(0, 0); + auto const aiwasdriving { AIControllFlag == AIdriver }; + if( aiwasdriving ) { + // the horn, sandbox, departure signal and brake releaser the AI may have latched are momentary for the human driver + handover::release_ai_controls( *mvOccupied, *mvControlling ); + fWarningDuration = 0.0; + remove_hint( driver_hint::hornon ); + // the AI sets the lights directly, leave the selector in matching position so it doesn't revert them later + sync_lights_selector(); + } + AIControllFlag = Humandriver; + pVehicle->Controller = Humandriver; + if( aiwasdriving ) { + // same with the headlight dimmer, which is only applied for the human driver + sync_lights_dimmer(); + } + if( eAction == TAction::actSleep ) { + eAction = TAction::actUnknown; + } + if( Forcevehiclecheck ) { + // update consist ownership and other consist data + CheckVehicles(); + } + } +}; + +Mtable::TTrainParameters const & +TController::TrainTimetable() const { + return TrainParams; +} + +std::string TController::Relation() const +{ // zwraca relację pociągu + return TrainParams.ShowRelation(); +}; + +const std::string& TController::TrainName() const +{ // zwraca numer pociągu + return TrainParams.TrainName; +}; + +int TController::StationCount() const +{ // zwraca ilość stacji (miejsc zatrzymania) + return TrainParams.StationCount; +}; + +int TController::StationIndex() const +{ // zwraca indeks aktualnej stacji (miejsca zatrzymania) + return TrainParams.StationIndex; +}; + +bool TController::IsStop() const +{ // informuje, czy jest zatrzymanie na najbliższej stacji + return TrainParams.IsStop(); +}; + +std::string TController::TableText( std::size_t const Index ) const +{ // pozycja tabelki prędkości + if( Index < sSpeedTable.size() ) { + return sSpeedTable[ Index ].TableText(); + } + else { + return ""; + } +}; + +int TController::CrossRoute(TTrack *tr) +{ // zwraca numer segmentu dla skrzyżowania (tr) + // pożądany numer segmentu jest określany podczas skanowania drogi + // droga powinna być określona sposobem przejazdu przez skrzyżowania albo współrzędnymi miejsca + // docelowego + for( std::size_t i = 0; i < sSpeedTable.size(); ++i ) + { // trzeba przejrzeć tabelę skanowania w poszukiwaniu (tr) + // i jak się znajdzie, to zwrócić zapamiętany numer segmentu i kierunek przejazdu + // (-6..-1,1..6) + if( true == sSpeedTable[i].flags.HasAll(SpeedPointFlag::enabled | SpeedPointFlag::track) + && sSpeedTable[i].trTrack == tr ) { + // jeśli pozycja odpowiadająca skrzyżowaniu (tr) + return sSpeedTable[i].crossRoute; // -8..7 + } + } + return 0; // nic nie znaleziono? +}; +/* +void TController::RouteSwitch(int d) +{ // ustawienie kierunku jazdy z kabiny + d &= 3; + if( ( d != 0 ) + && ( iRouteWanted != d ) ) { // nowy kierunek + iRouteWanted = d; // zapamiętanie + if( mvOccupied->CategoryFlag & 2 ) { + // jeśli samochód + for( std::size_t i = 0; i < sSpeedTable.size(); ++i ) { + // szukanie pierwszego skrzyżowania i resetowanie kierunku na nim + if( true == sSpeedTable[ i ].flags.HasAll(spEnabled | spTrack) ) { + // jeśli pozycja istotna (1) oraz odcinek (2) + if( false == sSpeedTable[ i ].flags.HasAll(spElapsed) ) { + // odcinek nie może być miniętym + if( sSpeedTable[ i ].trTrack->eType == tt_Cross ) // jeśli skrzyżowanie + { + while( sSpeedTable.size() >= i ) { + // NOTE: we're ignoring semaphor flags and not resetting them like we do for train route trimming + // but what if there's street lights? + // TODO: investigate + sSpeedTable.pop_back(); + } + iLast = sSpeedTable.size(); + } + } + } + } + } + } +}; +*/ +std::string TController::OwnerName() const +{ + return pVehicle ? pVehicle->MoverParameters->Name : "none"; +}; + +bool TController::is_train() const { + return TestFlag( mvOccupied->CategoryFlag, 1 ); } + +bool TController::is_car() const { + return TestFlag( mvOccupied->CategoryFlag, 2 ); } + +bool TController::is_emu() const { + return mvControlling->TrainType == train_type::emu; } + +bool TController::is_dmu() const { + return mvControlling->TrainType == train_type::dmu; } + +bool TController::has_diesel_engine() const { + return mvControlling->EngineType == TEngineType::DieselElectric || mvControlling->EngineType == TEngineType::DieselEngine; } + +double TController::DirectionalVel() const { + return mvOccupied->Vel * sign( iDirection * mvOccupied->V ); } + +std::vector DrivingFlags::ActiveNames() const { + std::vector> const flags { + { stopCloser, "StopCloser" }, { stopPoint, "StopPoint" }, { active, "Active" }, { press, "Press" }, + { connect, "Connect" }, { primary, "Primary" }, { late, "Late" }, { stopHere, "StopHere" }, + { startHorn, "StartHorn" }, { startHornNow, "StartHornNow" }, { startHornDone, "StartHornDone" }, + { oerlikons, "Oerlikons" }, { incSpeed, "IncSpeed" }, { trackEnd, "TrackEnd" }, { switchFound, "SwitchFound" }, + { guardSignal, "GuardSignal" }, { visibility, "Visibility" }, { doorOpened, "DoorOpened" }, + { pushPull, "PushPull" }, { signalFound, "SignalFound" }, { stopPointFound, "StopPointFound" }, + { guardOpenDoor, "GuardOpenDoor" }, { departureWarned, "DepartureWarned" } }; + std::vector names; + for( auto const &[ set, name ] : flags ) { + if( set ) { + names.emplace_back( name ); + } + } + return names; +} diff --git a/vehicle/ai/engine.cpp b/vehicle/ai/engine.cpp new file mode 100644 index 000000000..7142d43c1 --- /dev/null +++ b/vehicle/ai/engine.cpp @@ -0,0 +1,449 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// preparing the vehicle and shutting it down: the engine, the heating, the direction + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/mover.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + + +// closes the line breaker, or starts the engine, the relays reset first +void TController::close_line_breaker() +{ + cue_action( driver_hint::mastercontrollersetzerospeed ); + // consist-wide ground relay reset + cue_action( driver_hint::maincircuitgroundreset ); + cue_action( driver_hint::tractionnmotoroverloadreset ); + if( mvOccupied->EngineType == TEngineType::DieselEngine ) { + // specjalnie dla SN61 żeby nie zgasł + cue_action( driver_hint::mastercontrollersetidle ); + } + cue_action( driver_hint::linebreakerclose ); +} + +bool TController::PrepareEngine() +{ // odpalanie silnika + // HACK: don't immediately activate inert vehicle in case the simulation is about to replace us with human driver + if( mvOccupied->Vel < 1.0 && fActionTime < 0.0 ) { return false; } + + LastReactionTime = 0.0; + ReactionTime = mvOccupied->Vel < 5 ? PrepareTime : EasyReactionTime; // react faster with rolling start + + cue_action( driver_hint::batteryon ); + cue_action( driver_hint::cabactivation); + cue_action( driver_hint::radiofuseon ); + cue_action( driver_hint::radioon ); + + if( has_diesel_engine() ) { + cue_action( driver_hint::oilpumpon ); + PrepareHeating(); + if( true == IsHeatingTemperatureOK ) { + cue_action( driver_hint::fuelpumpon ); + } + else { + cue_action( driver_hint::waittemperaturetoolow ); + } + } + + if( mvControlling->PantographsRequireMains + && IsAnyLineBreakerOpen ) { + // the pantographs rise only through the closed line breaker, which closes without their voltage + PrepareDirection(); + close_line_breaker(); + } + + auto const sufficientpantographpressure { ( + is_emu() ? + 2.5 : // Ra 2013-12: Niebugocław mówi, że w EZT podnoszą się przy 2.5 + 3.5 ) + + 0.1 }; // leeway margin + + if( mvPantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector + && mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 0 ) { + // if our pantograph unit isn't a pantograph-devoid fallback + if (mvPantographUnit->PantPress < sufficientpantographpressure) { + // załączenie małej sprężarki + if( false == mvPantographUnit->PantAutoValve ) { + // odłączenie zbiornika głównego, bo z nim nie da rady napompować + cue_action( driver_hint::pantographairsourcesetauxiliary ); + } + cue_action( driver_hint::pantographcompressoron ); // załączenie sprężarki pantografów + if( mvPantographUnit->PantCompFlag ) { + cue_action( driver_hint::waitpantographpressuretoolow ); + } + } + else { + // jeżeli jest wystarczające ciśnienie w pantografach + if( false == mvPantographUnit->bPantKurek3 + || mvPantographUnit->PantPress <= mvPantographUnit->ScndPipePress ) { // kurek przełączony albo główna już pompuje + cue_action( driver_hint::pantographcompressoroff ); // sprężarkę pantografów można już wyłączyć + } + } + // TODO: make pantograph setup a part of control_pantographs() and call it here instead + if( fOverhead2 == -1.0 && iOverheadDown == 0 ) { + cue_action( driver_hint::pantographsvalveon ); + cue_action( driver_hint::frontpantographvalveon, iDirection >= 0 ? 5 : 0 ); + cue_action( driver_hint::rearpantographvalveon, iDirection >= 0 ? 0 : 5 ); + } + } + + auto const ispoweravailable = + mvControlling->EnginePowerSource.SourceType != TPowerSource::CurrentCollector + || std::max(mvControlling->GetTrainsetHighVoltage(), mvControlling->PantographVoltage) > mvControlling->EnginePowerSource.CollectorParameters.MinV; + // standing with the pantographs up and no voltage, nothing the driver does starts the vehicle. it says so, and keeps + // trying: towed back under the wire, or with the power switched on, the vehicle gets prepared after all + report_power_stall( ispoweravailable, sufficientpantographpressure ); + + bool isready = false; + + if( IsHeatingTemperatureOK + && ispoweravailable ) { + // najpierw ustalamy kierunek, jeśli nie został ustalony + PrepareDirection(); + + if( IsAnyConverterOverloadRelayOpen ) { + // wywalił bezpiecznik nadmiarowy przetwornicy + cue_action( driver_hint::compressoroff ); // TODO: discern whether compressor needs converter to operate + cue_action( driver_hint::converteroff ); + cue_action( driver_hint::primaryconverteroverloadreset ); // reset nadmiarowego + } + if( IsAnyLineBreakerOpen ) { + // activate main circuit or engine + close_line_breaker(); + } + else { + // main circuit or engine is on, set up vehicle devices and controls + if( false == IsAnyConverterOverloadRelayOpen ) { + if( IsAnyConverterPresent ) { + cue_action( driver_hint::converteron ); + } + // w EN57 sprężarka w ra jest zasilana z silnikowego + // TODO: change condition to presence of required voltage type + if( IsAnyCompressorPresent && IsAnyConverterEnabled ) { + cue_action( driver_hint::compressoron ); + } + if( mvControlling->ScndPipePress < 4.5 && mvControlling->VeselVolume > 0.0 ) { + cue_action( driver_hint::waitpressuretoolow ); + } + // enable motor blowers + if( mvOccupied->MotorBlowers[ end::front ].speed != 0 ) { + cue_action( driver_hint::frontmotorblowerson ); + } + if( mvOccupied->MotorBlowers[ end::rear ].speed != 0 ) { + cue_action( driver_hint::rearmotorblowerson ); + } + } + control_field_shunting(); + // sync virtual brake state with the 'real' one + if( mvOccupied->BrakeHandle != TBrakeHandle::NoHandle ) { + std::unordered_map const brakepositions{ + { static_cast( mvOccupied->Handle->GetPos( bh_RP ) ), gbh_RP }, + { static_cast( mvOccupied->Handle->GetPos( bh_NP ) ), gbh_NP }, + { static_cast( mvOccupied->Handle->GetPos( bh_FS ) ), gbh_FS } }; + auto const lookup{ brakepositions.find( static_cast( mvOccupied->fBrakeCtrlPos ) ) }; + if( lookup != brakepositions.end() ) { + BrakeLevelSet( lookup->second ); // GBH + } + } + // set up train brake + if( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) { + // standing: the locomotive brake first, then the pipe is filled + secure_standing_train(); + } + else if( ( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_RP ) ) + && ( ( false == mvOccupied->Handle->Time ) + || ( mvOccupied->Handle->GetCP() < mvOccupied->HighPipePress - 0.05 ) ) ) { + cue_action( driver_hint::trainbrakerelease ); + } + // sync spring brake state across consist + cue_action( + mvOccupied->SpringBrake.Activate ? + driver_hint::springbrakeon : + driver_hint::springbrakeoff ); + } + isready = false == IsAnyConverterOverloadRelayOpen + && mvOccupied->DirActive != 0 + && false == IsAnyLineBreakerOpen + && ( false == IsAnyConverterPresent || true == IsAnyConverterEnabled ) + && ( false == IsAnyCompressorPresent || true == IsAnyCompressorEnabled ) + && ( mvControlling->ScndPipePress > 4.5 || mvControlling->VeselVolume == 0.0 ); + } + + if( true == isready ) { + // jeśli dotychczas spał teraz nie ma powodu do stania + eAction = TAction::actUnknown; + if( eStopReason == stopSleep ) { + eStopReason = stopNone; + } + // może skanować sygnały i reagować na komendy + drivingFlags.active = true; + } + + iEngineActive = isready; + + return iEngineActive; +} + +// tells in the log, once, of standing with the pantographs up and no voltage at them, past the end of the overhead +// wire or under a wire switched off (eu07/maszyna#421). Poweravailable is what PrepareEngine() found, Pantographpressure +// the air the pantographs need to rise +void +TController::report_power_stall( bool const Poweravailable, double const Pantographpressure ) { + + ai_power::state state; + state.collector = mvControlling->EnginePowerSource.SourceType == TPowerSource::CurrentCollector; + state.power = Poweravailable; + state.standing = mvOccupied->Vel < EU07_AI_NOMOVEMENT; + if( mvPantographUnit->PantPress >= Pantographpressure ) { + state.pantographs_up = + mvPantographUnit->Pantographs[ end::front ].is_active + || mvPantographUnit->Pantographs[ end::rear ].is_active; + } + // the pantographs of the vehicle carrying them hold the wire they found above them + if( auto const *carrier { pVehicle->FindPantographCarrier() }; + carrier != nullptr && carrier->MoverParameters == mvPantographUnit ) { + auto const pantographcount { std::min( carrier->iAnimType[ ANIM_PANTS ], static_cast( carrier->MoverParameters->Pantographs.size() ) ) }; + for( auto index { 0 }; index < pantographcount; ++index ) { + if( true == carrier->MoverParameters->Pantographs[ index ].is_active + && carrier->pants[ index ].fParamPants->hvPowerWire != nullptr ) { + state.wire = true; + } + } + } + // a user driving the vehicle sees the voltmeters for themselves + if( auto const stall { m_powerstall.update( AIControllFlag ? ai_power::check( state ) : ai_power::stall::waiting, ElapsedTime ) }; + stall.has_value() ) { + ErrorLog( ai_power::message( *stall, pVehicle->asName, pVehicle->GetPosition() ), logtype::traction ); + } +} + +// wyłączanie silnika (test wyłączenia, a część wykonawcza tylko jeśli steruje komputer) +bool TController::ReleaseEngine() { +/* + if( mvOccupied->Vel > 0.01 ) { + VelDesired = 0.0; + AccDesired = std::min( AccDesired, -1.25 ); // hamuj solidnie + if( true == AIControllFlag ) { + // TBD, TODO: make a dedicated braking procedure out of it for potential reuse + ZeroSpeed(); + IncBrake(); + ReactionTime = 0.1; + } + // don't bother with the rest until we're standing still + return false; + } +*/ + // don't bother with the rest until we're standing still + if( mvOccupied->Vel > EU07_AI_NOMOVEMENT ) { return false; } + + LastReactionTime = 0.0; + ReactionTime = PrepareTime; + + cue_action( driver_hint::releaseroff ); + // release train brake if on flats... + if( std::abs( fAccGravity ) < 0.01 ) { + apply_independent_brake_only(); + } + // ... but on slopes engage train brake + else { +// AccDesired = std::min( AccDesired, -0.9 ); + cue_action( driver_hint::trainbrakeapply ); + } + + cue_action( driver_hint::mastercontrollersetreverserunlock ); + cue_action( driver_hint::directionnone ); + // zamykanie drzwi + cue_action( driver_hint::doorrightclose ); + cue_action( driver_hint::doorleftclose ); + // heating + cue_action( driver_hint::consistheatingoff ); + // devices + cue_action( driver_hint::compressoroff ); + cue_action( driver_hint::converteroff ); + // line breaker/engine + cue_action( driver_hint::linebreakeropen ); + // pantographs + cue_action( driver_hint::frontpantographvalveoff ); + cue_action( driver_hint::rearpantographvalveoff ); + + if( false == mvControlling->Mains ) { + // finish vehicle shutdown + if( has_diesel_engine() ) { + // heating/cooling subsystem + cue_action( driver_hint::waterheateroff ); + // optionally turn off the water pump as well + if( mvControlling->WaterPump.start_type != start_t::battery ) { + cue_action( driver_hint::waterpumpoff ); + } + // fuel and oil subsystems + cue_action( driver_hint::fuelpumpoff ); + cue_action( driver_hint::oilpumpoff ); + } + // gasimy światła + cue_action( driver_hint::lightsoff ); + // activate parking brake + // TBD: do it earlier? + cue_action( driver_hint::springbrakeon ); + if( mvOccupied->LocalBrake == TLocalBrake::ManualBrake + || mvOccupied->MBrake == true ) { + cue_action( driver_hint::manualbrakon ); + } + // switch off remaining power + cue_action( driver_hint::radiooff ); + cue_action( driver_hint::batteryoff ); + } + + auto const OK { + mvOccupied->DirActive == 0 +// && ( false == IsAnyCompressorEnabled ) +// && ( false == IsAnyConverterEnabled ) + && false == mvControlling->Mains + && false == mvOccupied->Power24vIsAvailable }; + + if (OK) { + // jeśli się zatrzymał + iEngineActive = false; + eStopReason = stopSleep; // stoimy z powodu wyłączenia + eAction = TAction::actSleep; //śpi (wygaszony) + + OrderNext(DriverOrder::waitForOrders); //żeby nie próbował coś robić dalej + drivingFlags.active = false; // ma nie skanować sygnałów i nie reagować na komendy + TableClear(); // zapominamy ograniczenia + VelSignalLast = -1.0; + } + return OK; +} + +// configures vehicle heating given current situation; returns: true if vehicle can be operated normally, false otherwise +bool +TController::PrepareHeating() { + + switch( mvControlling->EngineType ) { + + case TEngineType::DieselElectric: + case TEngineType::DieselEngine: { + + auto const &heat { mvControlling->dizel_heat }; + + // determine whether there's need to enable the water heater + // if the heater has configured maximum temperature, it'll disable itself automatically, so we can leave it always running + // otherwise enable the heater only to maintain minimum required temperature + auto const lowtemperature { ( + ( heat.water.config.temp_min > 0 && heat.temperatura1 < heat.water.config.temp_min + (mvControlling->WaterHeater.is_active ? 5 : 0) ) + || ( heat.water_aux.config.temp_min > 0 && heat.temperatura2 < heat.water_aux.config.temp_min + (mvControlling->WaterHeater.is_active ? 5 : 0) ) + || ( heat.oil.config.temp_min > 0 && heat.To < heat.oil.config.temp_min + (mvControlling->WaterHeater.is_active ? 5 : 0) ) ) }; + auto const heateron { ( + mvControlling->WaterHeater.config.temp_max > 0 + || true == lowtemperature ) }; + if( true == heateron ) { + // make sure the water pump is running before enabling the heater + if( false == mvControlling->WaterPump.is_active ) { + cue_action( driver_hint::waterpumpbreakeron ); + cue_action( driver_hint::waterpumpon ); + } + if( true == mvControlling->WaterPump.is_active ) { + cue_action( driver_hint::waterheaterbreakeron ); + cue_action( driver_hint::waterheateron ); + cue_action( driver_hint::watercircuitslinkon ); + } + } + else { + // no need to heat anything up, switch the heater off + cue_action( driver_hint::watercircuitslinkoff ); + cue_action( driver_hint::waterheateroff ); + cue_action( driver_hint::waterheaterbreakeroff ); + // optionally turn off the water pump as well + if( mvControlling->WaterPump.start_type != start_t::battery ) { + cue_action( driver_hint::waterpumpoff ); + cue_action( driver_hint::waterpumpbreakeroff ); + } + } + + IsHeatingTemperatureTooLow = lowtemperature; + break; + } + default: { + IsHeatingTemperatureTooLow = false; + break; + } + } + // TBD, TODO: potentially pay attention to too high temperature as well? + IsHeatingTemperatureOK = false == IsHeatingTemperatureTooLow; + + return IsHeatingTemperatureOK; +} + +void +TController::PrepareDirection() { + + if( iDirection == 0 ) { + // jeśli nie ma ustalonego kierunku + if( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) { // ustalenie kierunku, gdy stoi + iDirection = mvOccupied->CabActive; // wg wybranej kabiny +/* + if( iDirection == 0 ) { + // jeśli nie ma ustalonego kierunku + if( mvOccupied->Couplers[ end::rear ].Connected == nullptr ) { + // jeśli z tyłu nie ma nic + iDirection = -1; // jazda w kierunku sprzęgu 1 + } + if( mvOccupied->Couplers[ end::front ].Connected == nullptr ) { + // jeśli z przodu nie ma nic + iDirection = 1; // jazda w kierunku sprzęgu 0 + } + } +*/ + } + else { + // ustalenie kierunku, gdy jedzie + iDirection = mvOccupied->V >= 0 ? 1 : // jazda w kierunku sprzęgu 0 + -1; // jazda w kierunku sprzęgu 1 + } + } + cue_action( driver_hint::mastercontrollersetreverserunlock ); + cue_action( + iDirection > 0 ? + driver_hint::directionforward : + driver_hint::directionbackward ); +} diff --git a/vehicle/ai/force.cpp b/vehicle/ai/force.cpp new file mode 100644 index 000000000..72c87dc28 --- /dev/null +++ b/vehicle/ai/force.cpp @@ -0,0 +1,783 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the traction and the brakes the driver applies for the speed it aims for + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/mover.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + +const double FSOverchargePipePress = 5.2; +const double FSOverchargeTime = 2.0; +const double FSOverchargeCRP = 0.05; +const double FSMaxTime = 10.0; +const double DepartBlockedFSDelay = 10.0; + +void +TController::control_tractive_and_braking_force() { + +#if LOGVELOCITY + WriteLog("Dist=" + FloatToStrF(ActualProximityDist, ffFixed, 7, 1) + + ", VelDesired=" + FloatToStrF(VelDesired, ffFixed, 7, 1) + + ", AccDesired=" + FloatToStrF(AccDesired, ffFixed, 7, 3) + + ", VelSignal=" + AnsiString(VelSignal) + ", VelNext=" + + AnsiString(VelNext)); +#endif + + if (iDriverFailCount > maxdriverfails) { + Psyche = Easyman; + if (iDriverFailCount > maxdriverfails * 2) + SetDriverPsyche(); + } + + control_relays(); + control_motor_connectors(); + + // if the radio-stop was issued don't waste effort trying to fight it + if( true == mvOccupied->RadioStopFlag // radio-stop + && mvOccupied->Vel > EU07_AI_NOMOVEMENT ) { // and still moving + cue_action( driver_hint::mastercontrollersetzerospeed ); // just throttle down... + return; // ...and don't touch any other controls + } + // if we're slipping leave the controls alone, there's a separate logic section trying to deal with it + if( true == mvControlling->SlippingWheels ) { + return; + } + + // ensure train brake isn't locked + if( BrakeCtrlPosition == gbh_NP ) { + cue_action( driver_hint::trainbrakerelease ); + } + control_releaser(); + control_main_pipe(); + + control_tractive_force(); + control_braking_force(); + +#if LOGVELOCITY + WriteLog("BrakePos=" + AnsiString(mvOccupied->BrakeCtrlPos) + ", MainCtrl=" + + AnsiString(mvControlling->MainCtrlPos)); +#endif +} + +// the switch of the field shunting of a diesel-electric that has one (AutoRelay=Optional with FieldShuntSwitch=Yes): off, +// the field stays full. checked while running too, since a vehicle taken over with its engine running doesn't go through +// PrepareEngine(). a diesel-electric with AutoRelay=Optional alone is left as before, shunting by hand with the switch off +void TController::control_field_shunting() { + + if( AIControllFlag + && mvControlling->EngineType == TEngineType::DieselElectric + && fieldshunting::has_switch( mvControlling->AutoRelayType, mvControlling->FieldShuntSwitch ) + && false == mvControlling->AutoRelayFlag ) { + mvControlling->AutoRelaySwitch( true ); + } +} + +// ensure relays are active +void TController::control_relays() { + + control_field_shunting(); + + if( fActionTime < 0.0 ) { return; } + + if( IsAnyMotorOverloadRelayOpen ) { + cue_action( driver_hint::mastercontrollersetzerospeed ); + cue_action( driver_hint::tractionnmotoroverloadreset ); + ++iDriverFailCount; + } + if( IsAnyGroundRelayOpen ) { + cue_action( driver_hint::mastercontrollersetzerospeed ); + cue_action( driver_hint::maincircuitgroundreset ); + ++iDriverFailCount; + } +} + +void TController::control_motor_connectors() { + // ensure motor connectors are active + if( (mvControlling->EngineType == TEngineType::ElectricSeriesMotor || mvControlling->EngineType == TEngineType::DieselElectric || is_emu()) && Need_TryAgain ) { + // true, jeśli druga pozycja w elektryku nie załapała + cue_action(driver_hint::mastercontrollersetzerospeed); + Need_TryAgain = false; + } +} + +void TController::control_tractive_force() { + + control_uphill_start(); + + auto const velocity { DirectionalVel() }; + // jeśli przyspieszenie pojazdu jest mniejsze niż żądane oraz... + if( AccDesired > EU07_AI_NOACCELERATION // don't add power if not asked for actual speed-up + && (AbsAccS < AccDesired /*- std::min( 0.05, 0.01 * iDriverFailCount )*/ || mvOccupied->SpeedCtrlUnit.IsActive && velocity < mvOccupied->SpeedCtrlUnit.FullPowerVelocity) && + false == drivingFlags.press && + // starting uphill against the releasing brake, the power that holds the train is enough: the brake coming off + // speeds the train up, more power only drags the brake and slips the wheels. nor is a notch past that taken + // back: the power got there in one notch from below, and the notch below doesn't hold the train + ( false == bUphillRelease || fUphillTractiveForce < uphill_start::holding_force * fUphillHoldingForce ) && + // nor while the train brake is still being applied further to hold the train + false == bUphillBrakeTopUp && + velocity < (VelDesired == 1.0 ? // work around for trains getting stuck on tracks with speed limit = 1 + VelDesired : + VelDesired - fVelMinus) && + (ActualProximityDist > (is_car() ? fMinProximityDist : // cars are allowed to move within min proximity distance + fMaxProximityDist) ? // other vehicle types keep wider margin + true : + velocity + 1.0 < VelNext + // uphill, a train told to hold its speed on the way to a stop needs the power to do it + || VelNext == 0.0 && OrderCurrentGet().HasAny(DriverOrder::obeyTrain) && AccDesired >= 0.0 && fAccGravity < -0.025 && ActualProximityDist > fMinProximityDist) ) { + // ...jeśli prędkość w kierunku czoła jest mniejsza od dozwolonej o margines... + // within proximity margin don't exceed next scheduled speed, outside of the margin accelerate as you like + // ...to można przyspieszyć + increase_tractive_force(); + } + // zmniejszanie predkosci + // margines dla prędkości jest doliczany tylko jeśli oczekiwana prędkość jest większa od 5km/h + if( false == drivingFlags.press ) { + double SpeedCtrlMargin = mvControlling->SpeedCtrlUnit.IsActive && VelDesired > 5 ? 3 : 0; + // jeśli nie dociskanie + if( AccDesired <= EU07_AI_NOACCELERATION ) { + cue_action( driver_hint::mastercontrollersetzerospeed ); + } + else if( velocity > VelDesired + SpeedCtrlMargin + || ( fAccGravity < -0.01 ? is_too_fast_uphill() : AbsAccS > AccDesired + 10.05 ) + || IsAnyCouplerStretched ) { + // jak za bardzo przyspiesza albo prędkość przekroczona + // dodany wyjatek na "pelna w przod" + cue_action( driver_hint::tractiveforcedecrease ); + } + } + + control_handles(); + SpeedSet(); // ciągla regulacja prędkości +} + +bool TController::is_too_fast_uphill() const { + + if( AccDesired < 0.0 ) { return true; } + // holding the speed uphill on the way to a stop asks for no speeding up + return ( VelNext == 0.0 && ActualProximityDist <= fMaxProximityDist && AbsAccS > AccDesired + 0.05 ); +} + +// starting uphill a driver of a heavy train keeps the train brake applied, lets the locomotive's own brake off (the +// independent brake, and its share of the train brake with the releaser), applies the power, and releases the train +// brake only once the power holds the train. releasing everything first lets the train roll back before the power is +// there, and holding the train on the locomotive brake is no way out where that brake cuts the power (asynchronous +// drives, the control pressure switch) +void TController::control_uphill_start() { + + auto const velocity { DirectionalVel() }; + if( auto const uphill { + ( BrakeSystem == TBrakeSystem::Pneumatic ) + && is_train() + && ( false == is_emu() ) && ( false == is_dmu() ) // a multiple unit has no locomotive to hold a train behind it + && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) }; + false == uphill ) { + end_uphill_start(); + return; + } + if( false == bUphillStart ) { + if( ( std::abs( velocity ) < EU07_AI_NOMOVEMENT ) + // the whole train at a stand, not only its head stopped for a moment while the train rolls back + && ( fConsistVelocity > -0.5 ) + && ( AccDesired > EU07_AI_NOACCELERATION ) + && ( VelDesired > 0.0 ) + && ( BrakeCtrlPosition > 0.0 ) // only with the train brake still applied to hold the train + && ( IsConsistCharged ) ) { // and charged to what the pipe has, or the brake that holds the train has no air + bUphillStart = true; + bUphillRelease = false; + UphillTopUp = {}; + fUphillStartTime = ElapsedTime; + } + else { + return; + } + } + if( AccDesired <= EU07_AI_NOACCELERATION ) { + // no longer to start: the standing rules take over + end_uphill_start(); + return; + } + if( fConsistVelocity < -0.5 ) { + // the train rolls back all the same: the rules for a train slipping back take over and apply the brakes. + // the train as a whole, not its head: with the locomotive brake off, the locomotive and the first vehicles + // run back into the slack of a long train still held by its brake + end_uphill_start(); + return; + } + fUphillTractiveForce = 0.0; + for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { + // Ft is signed in the vehicle's own frame, and turned into the direction of travel as AbsAccS is + fUphillTractiveForce += std::max( 0.0, vehicle->MoverParameters->Ft * ( vehicle->DirectionGet() == iDirection ? 1 : -1 ) * ( iDirection >= 0 ? 1 : -1 ) ); + } + fUphillHoldingForce = fMass * -fAccGravity; + bUphillBrakeTopUp = false; + if( false == bUphillRelease ) { + bUphillBrakeTopUp = uphill_brake_top_up(); + if( bUphillBrakeTopUp ) { + return; + } + if( ( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) + && ( mvOccupied->LocalBrakePosA > 0.0 ) ) { + cue_action( driver_hint::independentbrakerelease ); + } + if( ( velocity > 1.0 ) + || ( fUphillTractiveForce > uphill_start::holding_force * fUphillHoldingForce ) + // a locomotive that can't hold the train on its own power gets the brake off in the end all the same + || ( ElapsedTime - fUphillStartTime > 45.0 ) ) { + // the power holds the train: the train brake can be released + bUphillRelease = true; + fUphillReleaseTime = ElapsedTime; + } + return; + } + // the train brake is being released with the power on. the start ends once the brakes are off: ended before, + // the brake still on takes the power off, the train rolls back and has to be braked to a stand again + if( IsConsistReleased + // a brake that doesn't come off (a hand brake) ends it all the same + || ( ElapsedTime - fUphillReleaseTime > EU07_AI_UPHILLRELEASETIME ) ) { + end_uphill_start(); + } +} + +// the locomotive brake comes off only once the brake of the rest of the train holds the train on its own: a train +// stopped on a light application stands on the locomotive brake too, and rolls back as soon as it is off. until then +// the train brake is applied further, a step at a time; true while it is +bool TController::uphill_brake_top_up() { + + auto trainbrakeforce { 0.0 }; + auto haswagons { false }; + for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { + if( vehicle->MoverParameters->Power < 0.01 ) { + trainbrakeforce += vehicle->MoverParameters->Fb; + haswagons = true; + } + } + if( false == haswagons ) { + return false; + } + auto const action { uphill_start::brake_top_up( + UphillTopUp, trainbrakeforce, fUphillHoldingForce, BrakeCtrlPosition, fBrakeHeldTime, + mvOccupied->BrakeDelay[ mvOccupied->BrakeDelayFlag > bdelay_G ? 1 : 3 ] ) }; + if( action == uphill_start::top_up_action::none ) { + return false; + } + // the time for the power to hold the train starts once the brake does + fUphillStartTime = ElapsedTime; + if( action == uphill_start::top_up_action::step ) { + BrakeLevelAdd( BrakingLevelIncrease ); + } + return true; +} + +void TController::end_uphill_start() { + + bUphillStart = false; + bUphillRelease = false; + bUphillBrakeTopUp = false; +} + +// standing, a train is prepared as a driver does it: the locomotive brake first, then the brake pipe is filled. the pipe +// filled at once releases the distributors while the auxiliary reservoirs are still empty: the train has no brake left, +// and on a gradient rolls away as it releases. where the locomotive brake alone doesn't hold the train, the train brake +// is applied lightly, so the reservoirs charge with the train held. the locomotive brake comes off only once the train +// is charged and to start (DecBrake()) +void TController::secure_standing_train() { + + if( BrakeSystem != TBrakeSystem::Pneumatic ) { + // the electro-pneumatic brake of a multiple unit is released as before: nothing there takes the locomotive + // brake off again when the unit starts + cue_action( driver_hint::trainbrakerelease ); + return; + } + // the first start of a train that hasn't run yet waits for the brakes to charge. one that has run, prepared again + // (a change of direction, an engine started anew), has its reservoirs charged from the run and starts as before + if( false == bHasRun ) { + bBrakeChargeStart = true; + } + if( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) { + cue_action( driver_hint::independentbrakeapply ); + } + if( false == brake_charge::locomotive_brake_holds( locomotive_brake_force(), fMass * fAccGravity ) ) { + // the first service position: the pipe and the reservoirs charge to a little below the working pressure, the + // distributors keep a light application. a stronger application already there is left as it is, but not + // the emergency one or an empty pipe's, which don't charge + if( AIControllFlag + && ( ( BrakeCtrlPosition < 1.0 ) || ( BrakeCtrlPosition > uphill_start::top_up_position ) ) ) { + BrakeLevelSet( 1.0 ); + } + bBrakeChargeHold = true; + return; + } + bBrakeChargeHold = false; + cue_action( driver_hint::trainbrakerelease ); +} + +// the brake force of the locomotive brake at full application [N]. of the occupied vehicle alone: its handle acts on +// no other, not on a second section or a locomotive in multiple control either, let alone one hauled dead +double TController::locomotive_brake_force() const { + + if( ( mvOccupied->LocalBrake == TLocalBrake::ManualBrake ) + || ( mvOccupied->MaxBrakePress[ 0 ] <= 0.0 ) ) { + return 0.0; + } + return brake_charge::locomotive_brake_force( + mvOccupied->BrakeForceP( mvOccupied->MaxBrakePress[ 0 ], 0.0 ), + mvOccupied->TotalMassxg ); +} + +void TController::increase_tractive_force() { + + if( fActionTime < 0.0 ) { return; } // gdy jest nakaz poczekać z jazdą, to nie ruszać + if( IsAnyCouplerStretched ) { return; } // train is already stretched past its limits, don't pull even harder + + if( mvOccupied->SpringBrake.Activate ) { + cue_action( driver_hint::springbrakeoff ); + } + if( VelDesired > 0.0 // to prevent door shuffle on stop + && ( doors_open() || doors_permit_active() ) ) { + // zamykanie drzwi - tutaj wykonuje tylko AI (zmienia fActionTime) + Doors( false ); + // Doors() call can potentially adjust fActionTime + if( fActionTime < 0.0 ) { return; } + } + if( true == mvOccupied->DepartureSignal ) { + cue_action( driver_hint::departuresignaloff ); + } + + cue_action( driver_hint::tractiveforceincrease ); +} + +// how far the deceleration may fall short of the demand before the brake is applied harder. approaching a lower +// speed, a pneumatic brake given a full step only once that much is missing acts too late: the demand +// creeps up meanwhile, and in a long G train the next step takes many seconds to act, so half a step is enough +double +TController::brake_increase_margin() const { + + if( ( BrakeSystem == TBrakeSystem::Pneumatic ) + && ( VelNext > 0.0 ) + && ( VelNext < DirectionalVel() ) ) { + return 0.5 * fBrake_a1[ 0 ]; + } + return fBrake_a1[ 0 ]; +} + +// a train coming to a stand with at least part of it on an up gradient: a long train brake released now cannot be +// applied again before the train stops and starts to roll back, so the train brake is not released any further, and the +// locomotive brake, which acts at once, helps to hold the train +bool +TController::uphill_stop_hold() const { + + return ( + ( BrakeSystem == TBrakeSystem::Pneumatic ) && is_train() && ( OrderCurrentGet().HasAny(DriverOrder::obeyTrain) ) + && ( VelNext == 0.0 ) + && ( ActualProximityDist <= fMaxProximityDist ) + && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) + && ( std::abs( DirectionalVel() ) < 10.0 ) + // not while the train is to be driven on + && ( AccDesired <= 0.0 ) ); +} + +// uphill with the train brake applied, the gradient brings a slow train to a stand sooner than the brake of the consist +// can be released: letting the train roll on (or pulling up) at this speed only releases the brake for nothing, and the +// train stands with the brake on its way off instead +bool +TController::uphill_brake_committed( double const Velocity ) const { + + return ( + ( BrakeSystem == TBrakeSystem::Pneumatic ) + && ( BrakeCtrlPosition > 0.0 ) + && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) + && ( Velocity / 3.6 / -fAccGravity < brake_response_horizon( mvOccupied, BrakeSystem, -1.0, fBrake_a0[ 0 ] ) ) ); +} + +void TController::control_braking_force() { + + // don't touch the brakes when compressing buffers during coupling/uncoupling + if( drivingFlags.press ) { return; } + + auto const velocity { DirectionalVel() }; + // a train slipping back uphill is braked, also when it is to go on: released now it only rolls back further. + // its head, or the train as a whole: the locomotive may stop for a moment while the rest of the train runs into it + auto const slippingbackuphill { + ( fAccGravity < -0.05 ) + && ( std::min( velocity, fConsistVelocity ) < -0.1 ) + && ( false == bUphillStart ) }; + + // jeśli przyspieszamy, to nie hamujemy + if( AccDesired > 0.0 && OrderCurrentGet() != DriverOrder::disconnect // przy odłączaniu nie zwalniamy tu hamulca + && false == drivingFlags.press + && false == slippingbackuphill ) { + cue_action(driver_hint::brakingforcesetzero); + } + + // AbsAccS is the resultant acceleration, gravity included, so it is compared with the + // resultant the AI asks for, not with the brake-only demand AccDesired holds on a descent + auto const accdesiredresultant { AccDesired + fAccDesiredGravity }; + + // every few seconds, note how far the train falls short of the demand and whether that is getting worse: a brake + // still filling, or blocks gripping harder as the train slows down, make up a shortfall on their own, but a + // shortfall that keeps growing at a constant handle means the train is falling further behind its braking curve + if( ElapsedTime - fShortfallTime >= 3.0 ) { + auto const shortfall { AbsAccS - accdesiredresultant }; + iShortfallGrowth = ( + ( ( AccDesired < 0.0 ) && ( shortfall > fShortfall + 0.005 ) ) ? + iShortfallGrowth + 1 : + 0 ); + fShortfall = shortfall; + fShortfallTime = ElapsedTime; + } + + if( is_emu() && !ForcePNBrake ) { + // właściwie, to warunek powinien być na działający EP + // Ra: to dobrze hamuje EP w EZT + auto const accthreshold { ( + fAccGravity < 0.025 ? // HACK: when going downhill be more responsive to desired deceleration + fAccThreshold : + std::max( -0.2, fAccThreshold ) ) }; + auto const AccMax{ std::min(fBrake_a0[0] + 12 * fBrake_a1[0], mvOccupied->MED_amax) }; + auto const accmargin = AccMax > 1.1 * AccDesired && fAccGravity < 0.025 ? + 0.05 : 0.0; + if( ( AccDesired < accthreshold // jeśli hamować - u góry ustawia się hamowanie na fAccThreshold + && ( AbsAccS > accdesiredresultant + accmargin + || BrakeCtrlPosition < 0 ) ) + || ( fAccGravity < -0.05 && velocity < -0.1 && AccDesired < 0.0 ) ) { // also brake if uphill and slipping back + // hamować bardziej, gdy aktualne opóźnienie hamowania mniejsze niż (AccDesired) + cue_action( driver_hint::brakingforceincrease ); + } + else if( OrderCurrentGet() != DriverOrder::disconnect ) { // przy odłączaniu nie zwalniamy tu hamulca + if( AbsAccS < accdesiredresultant - 0.05 ) { + // jeśli opóźnienie większe od wymaganego (z histerezą) luzowanie, gdy za dużo + // TBD: check if the condition isn't redundant with the DecBrake() code + if( BrakeCtrlPosition >= 0 && VelDesired > 0.0 ) { + // sanity check to prevent unintended brake release on sharp slopes + cue_action(driver_hint::brakingforcedecrease); + } + } + else { + cue_action( driver_hint::brakingforcelap ); + } + } + } // type & dt_ezt + else { + // a stara wersja w miarę dobrze działa na składy wagonowe + if( (accdesiredresultant < fAccGravity - 0.1 && AbsAccS > accdesiredresultant + brake_increase_margin() // regular braking + || slippingbackuphill) && // also brake if uphill and slipping back + (fBrakeTime < 0.0 + // the size of the brake demand decides whether to skip the reaction time, so the brake-only part + // (on a descent a heavy train needs its brake built up at once, the gravity does not help it slow) + || AccDesired < fAccGravity - 0.5 || BrakeCtrlPosition <= 0) ) { + // u góry ustawia się hamowanie na fAccThreshold + // jeśli upłynął czas reakcji hamulca, chyba że nagłe albo luzował + // TODO: check whether brake delay variable still has any purpose + cue_action(driver_hint::brakingforceincrease, + // Ra: ten czas należy zmniejszyć, jeśli czas dojazdu do zatrzymania jest mniejszy + (3.0 + 0.5 * ((mvOccupied->BrakeDelayFlag > bdelay_G ? mvOccupied->BrakeDelay[1] : mvOccupied->BrakeDelay[3]) - 3.0)) * 0.5); // Ra: tymczasowo, bo przeżyna S1 + } + else if( ( BrakeSystem == TBrakeSystem::Pneumatic ) + && ( AccDesired < 0.0 ) + && ( BrakeCtrlPosition > 0.0 ) + && ( fShortfall > 0.02 ) + && ( iShortfallGrowth >= 2 ) + && ( fBrakeHeldTime > brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) { + // the train has been falling further behind the demand for a while at a handle left alone for longer than + // the brake takes to respond: a small step now, while it still is small, rather than the deep one the + // margin above would allow only once the train is far behind + cue_action( driver_hint::brakingforceincrease ); + iShortfallGrowth = 0; + } + if ( (accdesiredresultant < fAccGravity - 0.05 + || AccDesired >= EU07_AI_NOACCELERATION) // no braking asked for, yet the train is slowing down more than that + && accdesiredresultant - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 && OrderCurrentGet() != DriverOrder::disconnect && VelDesired > 0.0 + // a human driver standing with the train not charged yet keeps the locomotive brake on, told so by the + // waitbrakecharge hint; the ai is held back in DecBrake() + && ( AIControllFlag + || ( false == brake_charge::release_waits( + IsConsistCharged, + mvOccupied->Vel < EU07_AI_NOMOVEMENT, + mvOccupied->fBrakeCtrlPos > mvOccupied->Handle->GetPos( bh_RP ) + 0.2 ) ) ) ) { // the human driver's handle + // jak hamuje, to nie tykaj kranu za często + // yB: luzuje hamulec dopiero przy różnicy opóźnień rzędu 0.2 + // przy odłączaniu nie zwalniamy tu hamulca + // sanity check to prevent unintended brake release on sharp slopes + // TODO: check whether brake delay variable still has any purpose + cue_action(driver_hint::brakingforcedecrease, + (mvOccupied->BrakeDelayFlag > bdelay_G ? mvOccupied->BrakeDelay[0] : mvOccupied->BrakeDelay[2]) / 3.0 * 0.5); // Ra: tymczasowo, bo przeżyna S1 + } + // uphill, the locomotive brake acts at once while the train brake of a long train takes many seconds to apply: + // put it on as the train comes to a stand, and at once if the train has started to roll back + if( ( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) + && ( mvOccupied->LocalBrakePosA < 1.0 ) + && ( ( uphill_stop_hold() && ( std::abs( velocity ) < 3.0 ) + // a train that has slowed down short of where it is to stop and is to pull up further does not get it + && ( VelDesired <= std::abs( velocity ) + 0.5 ) + && ( ActualProximityDist - uphill_stopping_distance( std::abs( velocity ), fAccGravity ) <= stopping_margin() ) ) + || ( ( BrakeSystem == TBrakeSystem::Pneumatic ) && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) && ( velocity < -0.1 ) && ( AccDesired <= 0.0 ) ) ) ) { + cue_action( driver_hint::independentbrakeapply ); + } + // stop-gap measure to ensure cars actually brake to stop even when above calculactions go awry + // instead of releasing the brakes and creeping into obstacle at 1-2 km/h + if( is_car() && VelDesired == 0.0 && velocity > VelDesired && ActualProximityDist <= fMinProximityDist && mvOccupied->LocalBrakePosA < 0.01 ) { + cue_action(driver_hint::brakingforceincrease); + } + } + + // odhamowywanie składu po zatrzymaniu i zabezpieczanie lokomotywy + if( mvOccupied->Vel < EU07_AI_NOMOVEMENT + && ( VelDesired == 0.0 + || AccDesired <= EU07_AI_NOACCELERATION ) ) { + + if( false == OrderCurrentGet().HasAny(DriverOrder::disconnect | DriverOrder::connect | DriverOrder::changeDirection) // przy (p)odłączaniu nie zwalniamy tu hamulca + && std::abs(fAccGravity) < 0.01 ) { // only do this on flats, on slopes keep applied the train brake + apply_independent_brake_only(); + } + // if told to change direction don't confuse human driver with request to leave applied brake in the cab they're about to leave + if( OrderCurrentGet().HasAny(DriverOrder::changeDirection) ) { + cue_action( driver_hint::independentbrakerelease ); + } + } +} + +void TController::apply_independent_brake_only() { + + if( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) { + if( false == mvOccupied->ShuntMode // no need for independent brake if autobrake is active + && is_equal(mvOccupied->fBrakeCtrlPos, mvOccupied->Handle->GetPos(bh_RP), 0.2) ) { + cue_action( driver_hint::independentbrakeapply ); + } + else { + cue_action( driver_hint::trainbrakerelease ); + } + } +} + +void TController::control_releaser() { + // HACK: don't immediately touch releaser in inert vehicle, in case the simulation is about to replace us with human driver + if( mvOccupied->Vel < 1.0 && fActionTime < 0.0 ) { return; } + // TODO: combine all releaser handling in single decision tree instead of having bits all over the place + // TODO: replace handle and system conditions with flag indicating releaser presence + if( BrakeSystem != TBrakeSystem::Pneumatic ) { return; } + + auto const hasreleaser { + false == (is_dmu() || is_emu()) // TODO: a more refined test than rejecting these types wholesale + && ( mvOccupied->BrakeHandle == TBrakeHandle::FV4a + || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_6P + || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K5P + || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K8P + || mvOccupied->BrakeHandle == TBrakeHandle::M394 ) }; + + if( false == hasreleaser ) { return; } + + brake_releaser::conditions state; + state.acceleration_desired = AccDesired; + state.pipe_pressure = mvOccupied->PipePress; + state.cylinder_pressure = mvOccupied->BrakePress; + state.control_pressure = mvOccupied->Hamulec->GetCRP(); + state.velocity = mvOccupied->Vel; + state.uphill_start = bUphillStart; + state.pressing = drivingFlags.press; + // stage 3 of uncoupling (UpdateDisconnect), from the direction change until the coupler lets go + state.compressing_buffers = + state.pressing && OrderCurrentGet().HasAny(DriverOrder::disconnect) && iVehicleCount >= 0 && iDirection == iDirectionOrder; + // a train prepared standing charges its brakes before its first start. a pipe left below the lock of the driver's + // brake valve (a train placed cold, as after an emergency application) is unlocked as the train stands, not only + // once it is to go: else it charges only after the order to go, and starts on what the reservoirs got by then. + // a handle which has to be moved to unlock is left where it holds the train with the train brake + state.charging_standing = + bBrakeChargeStart + && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) + && ( ( mvOccupied->HandleUnlock == -3 ) || ( BrakeCtrlPosition <= 0.0 ) ); + auto const wanted { brake_releaser::decide( state ) }; + auto const actuate { wanted.actuate }; + auto isbrakehandleinrightposition { true }; + + // some vehicles require brake handle to be moved to specific position to fill up the brake pipe + if( wanted.fill_pipe + && mvOccupied->HandleUnlock != -3 ) { + cue_action( driver_hint::trainbrakesetpipeunlock ); + isbrakehandleinrightposition = ( BrakeCtrlPosition == mvOccupied->HandleUnlock ); + } + + if( actuate ) { + // some vehicles may require master controller in neutral position + cue_action( driver_hint::mastercontrollersetzerospeed ); + if( false == mvOccupied->Hamulec->Releaser() + && isbrakehandleinrightposition ) { + cue_action( driver_hint::releaseron ); + } + } + else { + if( true == mvOccupied->Hamulec->Releaser() ) { + cue_action( driver_hint::releaseroff ); + } + } +} + +void TController::control_main_pipe() { + + // unlocking main pipe + if( ( AccDesired > -0.03 + // standing to charge before the first start, as in control_releaser() + || ( bBrakeChargeStart && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) ) ) + && true == mvOccupied->LockPipe ) { + UniversalBrakeButtons |= TUniversalBrake::ub_UnlockPipe; + } + else if (false == mvOccupied->LockPipe ) { + UniversalBrakeButtons &= ~TUniversalBrake::ub_UnlockPipe; + } + + // napełnianie uderzeniowe + if( BrakeSystem != TBrakeSystem::Pneumatic ) { return; } + + if( mvOccupied->BrakeHandle == TBrakeHandle::FV4a + || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_6P + || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K5P + || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K8P + || mvOccupied->BrakeHandle == TBrakeHandle::M394 ) { + + auto const departblocked { is_departure_blocked( DepartBlockedFSDelay ) }; + if( (drivingFlags.oerlikons || true == IsCargoTrain || departblocked) && BrakeCtrlPosition == gbh_RP && AbsAccS < 0.03 && AccDesired > -0.03 && VelDesired - mvOccupied->Vel > 2.0 && fReady > 0.35 && + ( mvOccupied->EqvtPipePress < 4.5 || departblocked ) // don't charge with a risk of overcharging the main pipe + && mvOccupied->Compressor >= 7.5 // don't charge without sufficient pressure in the tank + && BrakeChargingCooldown >= 0.0 // don't charge while cooldown is active + && (ActualProximityDist > 100.0 // don't charge if we're about to be braking soon + || min_speed(mvOccupied->Vel, VelNext) >= mvOccupied->Vel) ) { + + BrakeLevelSet(gbh_FS); + // don't charge the brakes too often, or we risk overcharging + BrakeChargingCooldown = -1 * std::clamp(iVehicles * 3, 30, 90); + } + + update_brake_charging(); + + if( ( mvOccupied->Compressor < 5.0 + || ( BrakeCtrlPosition < gbh_RP + && ( mvOccupied->EqvtPipePress > (fReady < 0.25 ? 5.1 : 5.2) || is_brake_charging_done() ) ) ) + // the light application a charging train stands on stays, as in DecBrake() + && ( false == brake_charge::holds_application( + bBrakeChargeHold, IsConsistCharged, mvOccupied->Vel < EU07_AI_NOMOVEMENT, BrakeCtrlPosition ) ) ) { + cue_action( driver_hint::trainbrakerelease ); + } + } +} + +void TController::update_brake_charging() { + + if( std::abs( BrakeCtrlPosition - gbh_FS ) >= 0.5 ) { + BrakeChargingStart = -1.0; + BrakeChargingPipeOverchargeStart.clear(); + return; + } + if( BrakeChargingStart < 0.0 ) { + BrakeChargingStart = ElapsedTime; + } + for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { + auto const isovercharged { + vehicle->MoverParameters != mvOccupied + && vehicle->MoverParameters->PipePress > FSOverchargePipePress }; + if( isovercharged ) { + BrakeChargingPipeOverchargeStart.try_emplace( vehicle, ElapsedTime ); + } + else { + BrakeChargingPipeOverchargeStart.erase( vehicle ); + } + } +} + +bool TController::is_departure_blocked( double const Delay ) const { + + return DepartBlockedStart >= 0.0 + && ElapsedTime - DepartBlockedStart > Delay; +} + +double TController::consist_max_crp() const { + + auto result { 0.0 }; + for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { + result = std::max( result, vehicle->MoverParameters->Hamulec->GetCRP() ); + } + return result; +} + +bool TController::is_brake_charging_done() const { + + if( BrakeChargingStart < 0.0 ) { + return false; + } + return ElapsedTime - BrakeChargingStart > FSMaxTime + || consist_max_crp() > mvOccupied->HighPipePress + FSOverchargeCRP + || std::ranges::any_of( + BrakeChargingPipeOverchargeStart, + [this]( auto const &Vehicle ) { return ElapsedTime - Vehicle.second > FSOverchargeTime; } ); +} + +void +TController::UpdateBrakingHelper() { + + if (HelperState > 0 && -AccDesired < fBrake_a0[0] + 2 * fBrake_a1[0] && mvOccupied->Vel > EU07_AI_NOMOVEMENT) { + HelperState = 0; + } + + switch( HelperState ) { + case 0: { + if( -AccDesired > fBrake_a0[0] + 8 * fBrake_a1[0] ) { + HelperState = 1; + } + break; + } + case 1: { + if( -AccDesired > fBrake_a0[0] + 12 * fBrake_a1[0] ) { + HelperState = 2; + } + break; + } + case 2: { + if( -AccDesired > 0 && -ActualProximityDist > 5 ) { + HelperState = 3; + } + break; + } + default: { + break; + } + } +} diff --git a/vehicle/ai/internal.h b/vehicle/ai/internal.h new file mode 100644 index 000000000..379d139c3 --- /dev/null +++ b/vehicle/ai/internal.h @@ -0,0 +1,115 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the constants and helpers the files of the AI driver share: only they include this header + +#pragma once + +#include "vehicle/Driver.h" +#include "physics/mover.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include + +#define LOGVELOCITY 0 +#define LOGORDERS 1 +#define LOGSTOPS 1 +#define LOGBACKSCAN 0 +#define LOGPRESS 0 + + +/* + +Moduł obsługujący sterowanie pojazdami (składami pociągów, samochodami). +Ma działać zarówno jako AI oraz przy prowadzeniu przez człowieka. W tym +drugim przypadku jedynie informuje za pomocą napisów o tym, co by zrobił +w tym pierwszym. Obejmuje zarówno maszynistę jak i kierownika pociągu +(dawanie sygnału do odjazdu). + +Przeniesiona tutaj została zawartość ai_driver.pas przerobiona na C++. +Również niektóre funkcje dotyczące składów z DynObj.cpp. + +Teoria jest wtedy kiedy wszystko wiemy, ale nic nie działa. +Praktyka jest wtedy, kiedy wszystko działa, ale nikt nie wie dlaczego. +Tutaj łączymy teorię z praktyką - tu nic nie działa i nikt nie wie dlaczego… + +*/ + +// zrobione: +// 0. pobieranie komend z dwoma parametrami +// 1. przyspieszanie do zadanej predkosci, ew. hamowanie jesli przekroczona +// 2. hamowanie na zadanym odcinku do zadanej predkosci (ze stabilizacja przyspieszenia) +// 3. wychodzenie z sytuacji awaryjnych: bezpiecznik nadmiarowy, poslizg +// 4. przygotowanie pojazdu do drogi, zmiana kierunku ruchu +// 5. dwa sposoby jazdy - manewrowy i pociagowy +// 6. dwa zestawy psychiki: spokojny i agresywny +// 7. przejscie na zestaw spokojny jesli wystepuje duzo poslizgow lub wybic nadmiarowego. +// 8. lagodne ruszanie (przedluzony czas reakcji na 2 pierwszych nastawnikach) +// 9. unikanie jazdy na oporach rozruchowych +// 10. logowanie fizyki //Ra: nie przeniesione do C++ +// 11. kasowanie czuwaka/SHP +// 12. procedury wspomagajace "patrzenie" na odlegle semafory +// 13. ulepszone procedury sterowania +// 14. zglaszanie problemow z dlugim staniem na sygnale S1 +// 15. sterowanie EN57 +// 16. zmiana kierunku //Ra: z przesiadką po ukrotnieniu +// 17. otwieranie/zamykanie drzwi +// 18. Ra: odczepianie z zahamowaniem i podczepianie +// 19. dla Humandriver: tasma szybkosciomierza - zapis do pliku! +// 20. wybór pozycji zaworu maszynisty w oparciu o zadane opoznienie hamowania + + +// do zrobienia: +// 1. kierownik pociagu +// 2. madrzejsze unikanie grzania oporow rozruchowych i silnika +// 3. unikanie szarpniec, zerwania pociagu itp +// 4. obsluga innych awarii +// 5. raportowanie problemow, usterek nie do rozwiazania +// 7. samouczacy sie algorytm hamowania + +// stałe +const double EasyReactionTime = 0.5; //[s] przebłyski świadomości dla zwykłej jazdy + +const double PrepareTime = 2.0; //[s] przebłyski świadomości przy odpalaniu + +double brake_response_horizon( TMoverParameters const *Vehicle, TBrakeSystem const Brakesystem, double const Acceleration, double const Brakea0 ); + +double +uphill_stopping_distance( double const Velocity, double const Gravity ); + diff --git a/vehicle/ai/obstacles.cpp b/vehicle/ai/obstacles.cpp new file mode 100644 index 000000000..16c237684 --- /dev/null +++ b/vehicle/ai/obstacles.cpp @@ -0,0 +1,496 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the obstacles and the signals behind and ahead of the train + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/mover.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + + +basic_event * TController::CheckTrackEventBackward(double fDirection, TTrack *Track, TDynamicObject *Vehicle, int const Eventdirection, end const End) +{ // sprawdzanie eventu w torze, czy jest sygnałowym - skanowanie do tyłu + // NOTE: this method returns only one event which meets the conditions, due to limitations in the caller + // TBD, TODO: clean up the caller and return all suitable events, as in theory things will go awry if the track has more than one signal + auto const dir{ Vehicle->VectorFront() * (double)Vehicle->DirectionGet() }; + auto const pos{ End == end::front ? Vehicle->RearPosition() : Vehicle->HeadPosition() }; + auto const &eventsequence { ( fDirection * Eventdirection > 0 ? Track->m_events2 : Track->m_events1 ) }; + for( auto const &event : eventsequence ) { + if( event.second != nullptr + && event.second->m_passive + && typeid(*event.second) == typeid(getvalues_event) ) { + // since we're checking for events behind us discard the sources in front of the scanning vehicle + auto const sl{ event.second->input_location() }; // położenie komórki pamięci + auto const sem{ sl - pos }; // wektor do komórki pamięci od końca składu + auto const isahead { dir.x * sem.x + dir.z * sem.z > 0 }; + if( End == end::front ? isahead : !isahead ) { + // iloczyn skalarny jest ujemny, gdy sygnał stoi z tyłu + return event.second; + } + } + } + return nullptr; +}; + +TTrack * TController::BackwardTraceRoute(double &fDistance, double &fDirection, TDynamicObject *Vehicle, basic_event *&Event, int const Eventdirection, end const End, bool const Untiloccupied ) +{ // szukanie sygnalizatora w kierunku przeciwnym jazdy (eventu odczytu komórki pamięci) + auto *Track = Vehicle->GetTrack(); + double fCurrentDistance = Vehicle->RaTranslationGet(); // aktualna pozycja na torze + if (fDirection > 0) // jeśli w kierunku Point2 toru + fCurrentDistance = Track->Length() - fCurrentDistance; + double s = 0; + + if( Track->VelocityGet() == 0.0 ) { // jak prędkosć 0 albo uszkadza, to nie ma po co skanować + fDistance = s; // to na tym torze stoimy + return nullptr; // stop, skanowanie nie dało sensownych rezultatów + } + // jak tor zajęty innym składem, to nie ma po co skanować + if( Untiloccupied && IsOccupiedByAnotherConsist( Track, fCurrentDistance * fDirection ) ) { + fDistance = s; // to na tym torze stoimy + return nullptr; // stop, skanowanie nie dało sensownych rezultatów + } + if ((Event = CheckTrackEventBackward(fDirection, Track, Vehicle, Eventdirection, End)) != nullptr) + { // jeśli jest semafor na tym torze + fDistance = s; // to na tym torze stoimy + return Track; + } + TTrack *pTrackFrom; // odcinek poprzedni, do znajdywania końca dróg + while (s < fDistance) + { + // Track->ScannedFlag=true; //do pokazywania przeskanowanych torów + pTrackFrom = Track; // zapamiętanie aktualnego odcinka + s += fCurrentDistance; // doliczenie kolejnego odcinka do przeskanowanej długości + if (fDirection > 0) + { // jeśli szukanie od Point1 w kierunku Point2 + if (Track->iNextDirection) + fDirection = -fDirection; + Track = Track->CurrentNext(); // może być NULL + } + else // if (fDirection<0) + { // jeśli szukanie od Point2 w kierunku Point1 + if (!Track->iPrevDirection) + fDirection = -fDirection; + Track = Track->CurrentPrev(); // może być NULL + } + if (Track == pTrackFrom) + Track = nullptr; // koniec, tak jak dla torów + + // gdy dalej toru nie ma albo zerowa prędkość, albo uszkadza pojazd + // zwraca NULL, że skanowanie nie dało sensownych rezultatów + if( Track == nullptr ) { + fDistance = s; + return nullptr; + } + if( Track->VelocityGet() == 0.0 ) + { + fDistance = s; + return nullptr; + } + if( Untiloccupied && IsOccupiedByAnotherConsist( Track ) ) { + fDistance = s; + return nullptr; + } + fCurrentDistance = Track->Length(); + if ((Event = CheckTrackEventBackward(fDirection, Track, Vehicle, Eventdirection, End)) != nullptr) + { // znaleziony tor z eventem + fDistance = s; + return Track; + } + } + Event = nullptr; // jak dojdzie tu, to nie ma semafora + // zwraca ostatni sprawdzony tor + fDistance = s; + return Track; +} + +// sprawdzanie zdarzeń semaforów i ograniczeń szlakowych +void TController::SetProximityVelocity( double dist, double vel, glm::dvec3 const *pos ) +{ // Ra:przeslanie do AI prędkości + /* + //!!!! zastąpić prawidłową reakcją AI na SetProximityVelocity !!!! + if (vel==0) + {//jeśli zatrzymanie, to zmniejszamy dystans o 10m + dist-=10.0; + }; + if (dist<0.0) dist=0.0; + if ((vel<0)?true:dist>0.1*(MoverParameters->Vel*MoverParameters->Vel-vel*vel)+50) + {//jeśli jest dalej od umownej drogi hamowania + */ + PutCommand( "SetProximityVelocity", dist, vel, pos ); + /* + } + else + {//jeśli jest zagrożenie, że przekroczy + Mechanik->SetVelocity(floor(0.2*sqrt(dist)+vel),vel,stopError); + } + */ +} + +TCommandType TController::BackwardScan( double const Range ) +{ // sprawdzanie zdarzeń semaforów z tyłu pojazdu, zwraca komendę + // dzięki temu będzie można stawać za wskazanym sygnalizatorem, a zwłaszcza jeśli będzie jazda na kozioł + // ograniczenia prędkości nie są wtedy istotne, również koniec toru jest do niczego nie przydatny + // zwraca true, jeśli należy odwrócić kierunek jazdy pojazdu + if( OrderCurrentGet().Without(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect) ) { + // skanowanie sygnałów tylko gdy jedzie w trybie manewrowym albo czeka na rozkazy + return TCommandType::cm_Unknown; + } + // kierunek jazdy względem sprzęgów pojazdu na czele + int const startdir = -pVehicles[0]->DirectionGet(); + if( startdir == 0 ) { + // jeśli kabina i kierunek nie jest określony nie robimy nic + return TCommandType::cm_Unknown; + } + // szukamy od pierwszej osi w wybranym kierunku + double scandir = startdir * pVehicles[0]->RaDirectionGet(); + + if( scandir == 0.0 ) { return TCommandType::cm_Unknown; } + + // skanowanie toru w poszukiwaniu eventów GetValues (PutValues nie są przydatne) + // Ra: przy wstecznym skanowaniu prędkość nie ma znaczenia + double scandist = Range; // zmodyfikuje na rzeczywiście przeskanowane + basic_event *e = nullptr; // event potencjalnie od semafora + // opcjonalnie może być skanowanie od "wskaźnika" z przodu, np. W5, Tm=Ms1, koniec toru wg + // drugiej osi w kierunku ruchu + auto const *scantrack{BackwardTraceRoute(scandist, scandir, pVehicles[end::front], e)}; + auto const dir{(double)startdir * + pVehicles[end::front]->VectorFront()}; // wektor w kierunku jazdy/szukania + + // jeśli wstecz wykryto koniec toru to raczej nic się nie da w takiej sytuacji zrobić + if (e == nullptr) + { + return TCommandType::cm_Unknown; + } + if (typeid(*e) != typeid(getvalues_event)) + { + return TCommandType::cm_Unknown; + } + + // jeśli jest jakiś sygnał na widoku + double scanvel; // prędkość ustawiona semaforem +#if LOGBACKSCAN + std::string edir{"Backward scan by " + pVehicle->asName + " - " + + ((scandir > 0) ? "Event2 " : "Event1 ")}; + edir += "(" + (e->name()) + ")"; +#endif + { + // najpierw sprawdzamy, czy semafor czy inny znak został przejechany + auto const sl{e->input_location()}; // położenie komórki pamięci + auto const pos{pVehicles[end::rear]->RearPosition()}; // pozycja tyłu + if (auto const sem{sl - pos}; dir.x * sem.x + dir.z * sem.z < 0) // wektor do komórki pamięci od końca składu + { + // jeśli został minięty + // iloczyn skalarny jest ujemny, gdy sygnał stoi z tyłu +#if LOGBACKSCAN + WriteLog(edir + " - ignored as not passed yet"); +#endif + return TCommandType::cm_Unknown; // nic + } + scanvel = e->input_value(1); // prędkość przy tym semaforze +#if LOGBACKSCAN + // przeliczamy odległość od semafora - potrzebne by były współrzędne początku składu + scandist = std::max(glm::length(sl - pos) - 2.0, 0.0); // 2m luzu przy manewrach wystarczy, ujemnych nie ma po co wysyłać +#endif + } + + auto move{false}; // czy AI w trybie manewerowym ma dociągnąć pod S1 + if (e->input_command() == TCommandType::cm_SetVelocity) + { + if (scanvel == 0.0 ? OrderCurrentGet() & (DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect) : + OrderCurrentGet() & DriverOrder::connect) + { // przy podczepianiu ignorować wyjazd? + move = true; // AI w trybie manewerowym ma dociągnąć pod S1 + } + else + { + // jeśli semafor jest daleko, a pojazd jedzie, to informujemy o zmianie prędkości + // jeśli jedzie manewrowo, musi dostać SetVelocity, żeby sie na pociągowy przełączył + // w przeciwnym razie ustawiamy prędkość tylko wtedy, gdy ma ruszyć, stanąć albo ma stać + // ruszać stop trzeba powtarzać, bo inaczej zatrąbi i pojedzie sam +#if LOGBACKSCAN + if (scandist > fMinProximityDist && + mvOccupied->Vel > EU07_AI_NOMOVEMENT && false == OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt)) + { + WriteLog(edir); + } + else + { + WriteLog(edir + " - [SetVelocity] [" + to_string(scanvel, 2) + "] [" + + to_string(e->input_value(2), 2) + "]"); + } +#endif + return scanvel > 0 ? TCommandType::cm_SetVelocity : TCommandType::cm_Unknown; + } + } + // reakcja AI w trybie manewrowym dodatkowo na sygnały manewrowe + if ((false == OrderCurrentGet().Empty() ? OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect) : true) && (move || e->input_command() == TCommandType::cm_ShuntVelocity)) // w Wait_for_orders też widzi tarcze + { + // jeśli powyżej było SetVelocity 0 0, to dociągamy pod S1 + /* + if ((scandist > fMinProximityDist) && + ((mvOccupied->Vel > EU07_AI_NOMOVEMENT) || (scanvel == 0.0))) + { + // jeśli tarcza jest daleko, to: + //- jesli pojazd jedzie, to informujemy o zmianie prędkości + //- jeśli stoi, to z własnej inicjatywy może podjechać pod zamkniętą tarczę + if (mvOccupied->Vel > EU07_AI_NOMOVEMENT) // tylko jeśli jedzie + { // Mechanik->PutCommand("SetProximityVelocity",scandist,scanvel,sl); + #if LOGBACKSCAN + // WriteLog(edir+"SetProximityVelocity "+AnsiString(scandist)+" + // "+AnsiString(scanvel)); + WriteLog(edir); + #endif + // SetProximityVelocity(scandist,scanvel,&sl); + // jeśli jedzie na W5 albo koniec toru, to można zmienić kierunek + return (drivingFlags.trackEnd) ? TCommandType::cm_ChangeDirection : + TCommandType::cm_Unknown; + // TBD: request direction change also if VelNext in current direction is 0, + // while signal behind requests movement? + } + } + else + { + // ustawiamy prędkość tylko wtedy, gdy ma ruszyć, albo stanąć albo ma stać pod + // tarczą stop trzeba powtarzać, bo inaczej zatrąbi i pojedzie sam if + // ((MoverParameters->Vel==0.0)||(scanvel==0.0)) //jeśli jedzie lub ma stanąć/stać + { // nie dostanie komendy jeśli jedzie i ma jechać + // PutCommand("ShuntVelocity",scanvel,e->Params[9].asMemCell->Value2(),&sl,stopSem); + #if LOGBACKSCAN + WriteLog(edir + " - [ShuntVelocity] [" + to_string(scanvel, 2) + "] [" + + to_string(e->input_value(2), 2) + "]"); + #endif + return (scanvel > 0 ? TCommandType::cm_ShuntVelocity : + TCommandType::cm_Unknown); + } + } + // NOTE: dead code due to returns in branching above + if ((scanvel != 0.0) && (scandist < 100.0)) + { + // jeśli Tm w odległości do 100m podaje zezwolenie na jazdę, to od razu ją + // ignorujemy, aby móc szukać kolejnej eSignSkip=e; //wtedy uznajemy ignorowaną przy + // poszukiwaniu nowej + #if LOGBACKSCAN + WriteLog(edir + " - will be ignored due to Ms2"); + #endif + return (scanvel > 0 ? TCommandType::cm_ShuntVelocity : TCommandType::cm_Unknown); + } + */ + return VelNext > 0 ? + TCommandType::cm_Unknown : // no need to bother if we can continue in current direction + scanvel == 0 ? + TCommandType::cm_Unknown : // no need to bother with a stop signal + TCommandType::cm_ShuntVelocity; // otherwise report a relevant shunt signal behind + // if (move?... + } // if (OrderCurrentGet()==Shunt) + + return e->m_passive && e->is_command() ? TCommandType::cm_Command : TCommandType::cm_Unknown; +}; + +std::string TController::NextStop() const +{ // informacja o następnym zatrzymaniu, wyświetlane pod [F1] + if (asNextStop == "[End of route]") + return ""; // nie zawiera nazwy stacji, gdy dojechał do końca + // dodać godzinę odjazdu + // the name the way the timetable spells it, in utf-8 as the user interface takes it + auto nextstop{ TrainParams.station_caption( asNextStop ) }; + auto const *t{ TrainParams.TimeTable + TrainParams.StationIndex }; + if( t->Ah >= 0 ) { + // przyjazd + nextstop += " przyj." + std::to_string( t->Ah ) + ":" + + to_minutes_str( t->Am, true, 3 ); + + } + if( t->Dh >= 0 ) { + // jeśli jest godzina odjazdu + nextstop += " odj." + std::to_string( t->Dh ) + ":" + + to_minutes_str( t->Dm, true, 3 ); + } + return nextstop; +}; + +void TController::UpdateDelayFlag() { + + if( TrainParams.CheckTrainLatency() < 0.0 ) { + // odnotowano spóźnienie + drivingFlags.late = true; + } + else { + // przyjazd o czasie + drivingFlags.late = false; + } +} + +// returns most recently calculated distance to potential obstacle ahead +double +TController::TrackObstacle() const { + + return Obstacle.distance; +} + +// check for potential collisions +void +TController::scan_obstacles( double const Range ) { + // HACK: vehicle order in the consist is based on intended travel direction + // if our actual travel direction doesn't match that, we should be scanning from the other end of the consist + // we cast to int to avoid getting confused by microstutters + auto *frontvehicle { pVehicles[ ( static_cast( mvOccupied->V ) * iDirection >= 0 ? end::front : end::rear ) ] }; + + int routescandirection; + // for moving vehicle determine heading from velocity; for standing fall back on the set direction + if( std::abs(frontvehicle->MoverParameters->V) > 0.5 ? // ignore potential micro-stutters in oposite direction during "almost stop" + frontvehicle->MoverParameters->V > 0.0 : + pVehicle->DirectionGet() == frontvehicle->DirectionGet() ? iDirection >= 0 : iDirection <= 0 ) { + // towards coupler 0 + routescandirection = end::front; + } + else { + // towards coupler 1 + routescandirection = end::rear; + } +/* + if( pVehicle->MoverParameters->CabOccupied < 0 ) { + // flip the scan direction in the rear cab + routescandirection ^= routescandirection; + } +*/ + Obstacle = neighbour_data(); + auto const obstaclescanrange { std::max( is_car() ? 250.0 : 1000.0, Range ) }; + auto const lookup { frontvehicle->find_vehicle( routescandirection, obstaclescanrange ) }; + + if( std::get( lookup ) == true ) { + + Obstacle.vehicle = std::get( lookup ); + Obstacle.vehicle_end = std::get( lookup ); + Obstacle.distance = std::get( lookup ); + + if( Obstacle.distance < ( is_car() ? 50 : 100 ) ) { + // at short distances (re)calculate range between couplers directly + Obstacle.distance = TMoverParameters::CouplerDist( frontvehicle->MoverParameters, Obstacle.vehicle->MoverParameters ); + } + } +} + +void +TController::check_route_ahead( double const Range ) { + + auto const comm { TableUpdate( VelDesired, ActualProximityDist, VelNext, AccDesired ) }; + + switch (comm) { + // ustawienie VelSignal - trochę proteza = do przemyślenia + case TCommandType::cm_Ready: { // W4 zezwolił na jazdę + // ewentualne doskanowanie trasy za W4, który zezwolił na jazdę + TableCheck( Range ); + TableUpdate( VelDesired, ActualProximityDist, VelNext, AccDesired ); // aktualizacja po skanowaniu + if( VelNext == 0.0 ) { + break; // ale jak coś z przodu zamyka, to ma stać + } + if( drivingFlags.stopCloser ) { + VelSignal = -1.0; // ma czekać na sygnał z sygnalizatora! + } + break; + } + case TCommandType::cm_SetVelocity: { // od wersji 357 semafor nie budzi wyłączonej lokomotywy + if( OrderCurrentGet().Without(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank).Empty() && std::fabs(VelSignal) >= 1.0 ) { // jedzie w dowolnym trybie albo Wait_for_orders + // 0.1 nie wysyła się do samochodow, bo potem nie ruszą + PutCommand("SetVelocity", VelSignal, VelNext, nullptr); // komenda robi dodatkowe operacje + } + break; + } + case TCommandType::cm_ShuntVelocity: { // od wersji 357 Tm nie budzi wyłączonej lokomotywy + if( OrderCurrentGet().Without( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank ).Empty() ) { // jedzie w dowolnym trybie albo Wait_for_orders + PutCommand( "ShuntVelocity", VelSignal, VelNext, nullptr ); + } + else if( false == iCoupler.Empty() ) { // jeśli jedzie w celu połączenia + SetVelocity( VelSignal, VelNext ); + } + break; + } + case TCommandType::cm_Command: { // komenda z komórki + if( OrderCurrentGet().Without(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank).Empty() && mvOccupied->Vel < 0.1 ) { + // jedzie w dowolnym trybie albo Wait_for_orders + // dopiero jak stanie + /* + PutCommand( eSignNext->text(), eSignNext->value( 1 ), eSignNext->value( 2 ), nullptr ); + eSignNext->StopCommandSent(); // się wykonało już + */ // replacement of the above + eSignNext->send_command(*this); + } + break; + } + default: { + break; + } + } +} + +void +TController::check_route_behind( double const Range ) { + + if( VelNext != 0.0 ) { return; } // not if we can move ahead + if( drivingFlags.connect ) { return; } // not if we're in middle of coupling operation + + if( OrderCurrentGet().Without( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect ).Empty() ) { + // jedzie w Shunt albo Connect, albo Wait_for_orders + // w trybie Connect skanować do tyłu tylko jeśli przed kolejnym sygnałem nie ma taboru do podłączenia + auto const couplinginprogress { + OrderCurrentGet().HasAll(DriverOrder::connect) + && ( Obstacle.distance < std::min(2000.0, FirstSemaphorDist) + || drivingFlags.connect ) }; + if( couplinginprogress ) { return; } + + auto const commandbehind { BackwardScan( Range ) }; + if( commandbehind != TCommandType::cm_Unknown ) { + // jeśli w drugą można jechać + // należy sprawdzać odległość od znalezionego sygnalizatora, + // aby w przypadku prędkości 0.1 wyciągnąć najpierw skład za sygnalizator + // i dopiero wtedy zmienić kierunek jazdy, oczekując podania prędkości >0.5 + if( commandbehind == TCommandType::cm_Command ) { + // jeśli komenda Shunt to ją odbierz bez przemieszczania się (np. odczep wagony po dopchnięciu do końca toru) + drivingFlags.stopHere = true; + } + iDirectionOrder = -iDirection; // zmiana kierunku jazdy + // zmiana kierunku bez psucia kolejnych komend + OrderCurrentSet( (OrderCurrentGet() | DriverOrder::changeDirection) ); + } + } +} diff --git a/vehicle/ai/orders.cpp b/vehicle/ai/orders.cpp new file mode 100644 index 000000000..091a443ef --- /dev/null +++ b/vehicle/ai/orders.cpp @@ -0,0 +1,1246 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the orders of the driver and the commands it gets from the scenery + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/mover.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + + +std::string StopReasonTable[] = { + // przyczyny zatrzymania ruchu AI + "", // stopNone, //nie ma powodu - powinien jechać + "Off", // stopSleep, //nie został odpalony, to nie pojedzie + "Semaphore", // stopSem, //semafor zamknięty + "Time", // stopTime, //czekanie na godzinę odjazdu + "End of track", // stopEnd, //brak dalszej części toru + "Change direction", // stopDir, //trzeba stanąć, by zmienić kierunek jazdy + "Joining", // stopJoin, //zatrzymanie przy (p)odczepianiu + "Block", // stopBlock, //przeszkoda na drodze ruchu + "A command", // stopComm, //otrzymano taką komendę (niewiadomego pochodzenia) + "Out of station", // stopOut, //komenda wyjazdu poza stację (raczej nie powinna zatrzymywać!) + "Radiostop", // stopRadio, //komunikat przekazany radiem (Radiostop) + "External", // stopExt, //przesłany z zewnątrz + "Error", // stopError //z powodu błędu w obliczeniu drogi hamowania +}; + +// zamiana kodu rozkazu na opis +std::string TController::Order2Str(DriverOrders Order) const { + + if( Order.HasAny(DriverOrder::changeDirection) + && Order != DriverOrder::changeDirection ) { + // może być nałożona na inną i wtedy ma priorytet + return + Order2Str( DriverOrder::changeDirection ) + + " + " + + Order2Str( Order.Without(DriverOrder::changeDirection) ); + } + switch( SingleOrder( Order ) ) { + case DriverOrder::waitForOrders: return "Wait_for_orders"; + case DriverOrder::prepareEngine: return "Prepare_engine"; + case DriverOrder::releaseEngine: return "Release_engine"; + case DriverOrder::changeDirection: return "Change_direction"; + case DriverOrder::connect: return "Connect"; + case DriverOrder::disconnect: return "Disconnect"; + case DriverOrder::shunt: return "Shunt"; + case DriverOrder::looseShunt: return "Loose_shunt"; + case DriverOrder::obeyTrain: return "Obey_train"; + case DriverOrder::bank: return "Bank"; + case DriverOrder::jumpToFirstOrder: return "Jump_to_first_order"; + default: return "Undefined"; + } +} + +std::array orderbuffer; + +std::string TController::OrderCurrent() const +{ // pobranie aktualnego rozkazu celem wyświetlenia + auto const order { OrderCurrentGet() }; + // generally prioritize direction change... + if( order & DriverOrder::changeDirection && false == drivingFlags.connect ) { + // ...but not in the middle of coupling operation + return STR("Change direction"); + } + + switch( SingleOrder( order.Without(DriverOrder::changeDirection) ) ) { + case DriverOrder::waitForOrders: { return STR("Wait for orders"); } + case DriverOrder::prepareEngine: { return STR("Start the engine"); } + case DriverOrder::releaseEngine: { return STR("Shut down the engine"); } + case DriverOrder::changeDirection: { return STR("Change direction"); } + case DriverOrder::connect: { return STR("Couple to consist ahead"); } + case DriverOrder::disconnect: { + if( iVehicleCount < 0 ) { + // done with uncoupling, order should update shortly + return STR("Wait for orders"); + } + // try to provide some task details + auto const count { iVehicleCount }; + + if( iVehicleCount > 1 ) { + std::snprintf( + orderbuffer.data(), orderbuffer.size(), + STR_C("the engine plus %d next vehicles"), // TODO: implement plural forms + count ); + } + auto const countstring { ( + count == 0 ? STR("the engine") : + count == 1 ? STR("the engine plus the next vehicle") : + orderbuffer.data() ) }; + + std::snprintf( + orderbuffer.data(), orderbuffer.size(), + STR_C("Uncouple %s"), + countstring.c_str() ); + return orderbuffer.data(); + } + case DriverOrder::shunt: { return STR("Shunt according to signals"); } + case DriverOrder::looseShunt: { return STR("Loose shunt according to signals"); } + case DriverOrder::obeyTrain: { return STR("Drive according to signals and timetable"); } + case DriverOrder::bank: { return STR("Bank consist ahead"); } + default: { return{}; } + } +}; + +void TController::OrdersClear() +{ // czyszczenie tabeli rozkazów na starcie albo po dojściu do końca + OrderPos = 0; + OrderTop = 1; // szczyt stosu rozkazów + for (int b = 0; b < maxorders; b++) + OrderList[b] = DriverOrder::waitForOrders; +#if LOGORDERS + OrdersDump("OrdersClear", false); +#endif +}; + +void TController::RecognizeCommand() +{ // odczytuje i wykonuje komendę przekazaną lokomotywie + TCommand *c = &mvOccupied->CommandIn; + PutCommand(c->Text, c->Value1, c->Value2, c->Location, stopComm); + c->Command = VehicleCommand::none; + c->Argument.clear(); + c->Text = ""; // usunięcie obsłużonej komendy +} + +void TController::PutCommand(std::string NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation, TStopReason reason) +{ // wysłanie komendy przez event PutValues, jak pojazd ma obsadę, to wysyła tutaj, a nie do pojazdu bezpośrednio + // zamiana na współrzędne scenerii + glm::dvec3 sl { -NewLocation.X, NewLocation.Z, NewLocation.Y }; + if (!PutCommand(NewCommand, NewValue1, NewValue2, &sl, reason)) + mvOccupied->PutCommand(NewCommand, NewValue1, NewValue2, NewLocation); +} + +bool TController::PutCommand( std::string NewCommand, double NewValue1, double NewValue2, glm::dvec3 const *NewLocation, TStopReason reason ) +{ // analiza komendy + if (NewCommand == "CabSignal") + { // SHP wyzwalane jest przez człon z obsadą, ale obsługiwane przez silnikowy + // nie jest to najlepiej zrobione, ale bez symulacji obwodów lepiej nie będzie + // Ra 2014-04: jednak przeniosłem do rozrządczego + mvOccupied->PutCommand(NewCommand, NewValue1, NewValue2, mvOccupied->Loc); + mvOccupied->RunInternalCommand(); // rozpoznaj komende bo lokomotywa jej nie rozpoznaje + return true; // załatwione + } + + if (NewCommand == "Overhead") + { // informacja o stanie sieci trakcyjnej + fOverhead1 = NewValue1; // informacja o napięciu w sieci trakcyjnej (0=brak drutu, zatrzymaj!) + fOverhead2 = NewValue2; // informacja o sposobie jazdy (-1=normalnie, 0=bez prądu, >0=z + // opuszczonym i ograniczeniem prędkości) + return true; // załatwione + } + + if (NewCommand == "Emergency_brake") // wymuszenie zatrzymania, niezależnie kto prowadzi + { // Ra: no nadal nie jest zbyt pięknie +// SetVelocity(0, 0, reason); + mvOccupied->PutCommand("Emergency_brake", 1.0, 1.0, mvOccupied->Loc); + return true; // załatwione + } + + if (NewCommand.compare(0, 10, "Timetable:") == 0) + { // przypisanie nowego rozkładu jazdy, również prowadzonemu przez użytkownika + NewCommand.erase(0, 10); // zostanie nazwa pliku z rozkładem +#if LOGSTOPS + WriteLog("New timetable for " + pVehicle->asName + ": " + NewCommand); // informacja +#endif + TrainParams = TTrainParameters(NewCommand); // rozkład jazdy + tsGuardSignal = sound_source { sound_placement::internal, 2 * EU07_SOUND_CABCONTROLSCUTOFFRANGE }; // wywalenie kierownika + m_lastexchangestop.clear(); + m_stopflags = {}; + if (NewCommand != "none") + { + if (false == TrainParams.LoadTTfile( + std::string(Global.asCurrentSceneryPath.c_str()), floor(NewValue2 + 0.5), + NewValue1)) // pierwszy parametr to przesunięcie rozkładu w czasie + { + if (ConversionError == -8) + ErrorLog("Missed timetable: " + NewCommand); + WriteLog("Cannot load timetable file " + NewCommand + "\r\nError " + + std::to_string(ConversionError) + " in position " + std::to_string(TrainParams.StationCount)); + NewCommand = ""; // puste, dla wymiennej tekstury + } + else + { // inicjacja pierwszego przystanku i pobranie jego nazwy + // HACK: clear the potentially set door state flag to ensure door get opened if applicable + if( true == AIControllFlag ) { + // simplified door closing procedure, to sync actual door state with the door state flag + // NOTE: this may result in visually ugly quick switch between closing and opening the doors, but eh + if( pVehicle->MoverParameters->Doors.close_control == control_t::driver + || pVehicle->MoverParameters->Doors.close_control == control_t::mixed ) { + pVehicle->MoverParameters->OperateDoors( side::right, false ); + pVehicle->MoverParameters->OperateDoors( side::left, false ); + } + if( pVehicle->MoverParameters->Doors.permit_needed ) { + pVehicle->MoverParameters->PermitDoors( side::right, false ); + pVehicle->MoverParameters->PermitDoors( side::left, false ); + } + } + drivingFlags.doorOpened = false; + + TrainParams.UpdateMTable( simulation::Time, TrainParams.NextStationName ); + TrainParams.StationIndexInc(); // przejście do następnej + TrainParams.StationStart = TrainParams.StationIndex; + asNextStop = TrainParams.NextStop(); + // the flags of the first station until the train stops there + m_stopflags = TrainParams.stop_flags(); + m_lastannouncement = announcement_t::idle; + drivingFlags.primary = true; // skoro dostał rozkład, to jest teraz głównym +// NewCommand = Global.asCurrentSceneryPath + NewCommand; + auto lookup = + FileExists( + { Global.asCurrentSceneryPath + NewCommand, paths::sounds + NewCommand }, + { ".ogg", ".flac", ".wav" } ); + if( false == lookup.first.empty() ) { + // wczytanie dźwięku odjazdu podawanego bezpośrenido + tsGuardSignal = sound_source( sound_placement::external, 75.f ).deserialize( lookup.first + lookup.second, sound_type::single ); + iGuardRadio = 0; // nie przez radio + } + else { + NewCommand += "radio"; + lookup = + FileExists( + { Global.asCurrentSceneryPath + NewCommand, paths::sounds + NewCommand }, + { ".ogg", ".flac", ".wav" } ); + if( false == lookup.first.empty() ) { + // wczytanie dźwięku odjazdu w wersji radiowej (słychać tylko w kabinie) + tsGuardSignal = sound_source( sound_placement::internal, EU07_SOUND_HANDHELDRADIORANGE ).deserialize( lookup.first + lookup.second, sound_type::single ); + iGuardRadio = iRadioChannel; + } + } + NewCommand = TrainParams.Relation2; // relacja docelowa z rozkładu + } + // jeszcze poustawiać tekstury na wyświetlaczach + TDynamicObject *p = pVehicles[end::front]; + while (p) + { + p->DestinationSet(NewCommand, TrainParams.TrainName); // relacja docelowa + p = p->Next(); // pojazd podłączony od tyłu (licząc od czoła) + } + } + if (NewLocation) // jeśli podane współrzędne eventu/komórki ustawiającej rozkład (trainset + // nie podaje) + { + auto v = *NewLocation - pVehicle->GetPosition(); // wektor do punktu sterującego + auto d = pVehicle->VectorFront(); // wektor wskazujący przód + iDirectionOrder = (v.x * d.x + v.z * d.z) * NewValue1 > 0 ? + 1 : + -1; // do przodu, gdy iloczyn skalarny i prędkość dodatnie + /* + if (NewValue1!=0.0) //jeśli ma jechać + if (iDirectionOrder==0) //a kierunek nie był określony (normalnie określany przez + reardriver/headdriver) + iDirectionOrder=NewValue1>0?1:-1; //ustalenie kierunku jazdy względem sprzęgów + else + if (NewValue1<0) //dla ujemnej prędkości + iDirectionOrder=-iDirectionOrder; //ma jechać w drugą stronę + */ + if (AIControllFlag) // jeśli prowadzi komputer + Activation(); // umieszczenie obsługi we właściwym członie, ustawienie nawrotnika w + // przód + } + /* + else + if (!iDirectionOrder) + {//jeśli nie ma kierunku, trzeba ustalić + if (mvOccupied->V!=0.0) + iDirectionOrder=mvOccupied->V>0?1:-1; + else + iDirectionOrder=mvOccupied->CabOccupied; + if (!iDirectionOrder) iDirectionOrder=1; + } + */ + // jeśli wysyłane z Trainset, to wszystko jest już odpowiednio ustawione + // if (!NewLocation) //jeśli wysyłane z Trainset + // if (mvOccupied->CabActive*mvOccupied->V*NewValue1<0) //jeśli zadana prędkość niezgodna z + // aktualnym kierunkiem jazdy + // DirectionForward(false); //jedziemy do tyłu (nawrotnik do tyłu) + // CheckVehicles(); //sprawdzenie składu, AI zapali światła + TableClear(); // wyczyszczenie tabelki prędkości, bo na nowo trzeba określić kierunek i + // sprawdzić przystanki + OrdersInit(fabs(NewValue1)); // ustalenie tabelki komend wg rozkładu oraz prędkości początkowej + // if (NewValue1!=0.0) if (!AIControllFlag) DirectionForward(NewValue1>0.0); //ustawienie + // nawrotnika użytkownikowi (propaguje się do członów) + // if (NewValue1>0) + // TrainNumber=floor(NewValue1); //i co potem ??? + return true; // załatwione + } + + if (NewCommand == "SetVelocity") + { + if (NewLocation) + vCommandLocation = *NewLocation; + if (NewValue1 != 0.0 && OrderCurrentGet() != DriverOrder::obeyTrain) + { // o ile jazda + if( false == iEngineActive ) { + // trzeba odpalić silnik najpierw, światła ustawi + OrderNext( DriverOrder::prepareEngine ); + } + OrderNext(DriverOrder::obeyTrain); // to uruchomić jazdę pociągową (od razu albo po odpaleniu silnika + OrderCheck(); // jeśli jazda pociągowa teraz, to wykonać niezbędne operacje + } + if (NewValue1 != 0.0) // jeśli jechać + drivingFlags.stopHere = false; // podjeżanie do semaforów zezwolone + else + drivingFlags.stopHere = true; // stać do momentu podania komendy jazdy + SetVelocity(NewValue1, NewValue2, reason); // bylo: nic nie rob bo SetVelocity zewnetrznie + // jest wywolywane przez dynobj.cpp + return true; + } + + if( NewCommand == "PointVelocity" ) { + // read by the speed table scan only; when the cell's event runs, there is nothing to do + return true; + } + + if (NewCommand == "SetProximityVelocity") + { + /* + if (SetProximityVelocity(NewValue1,NewValue2)) + if (NewLocation) + vCommandLocation=*NewLocation; + */ + return true; + } + + if (NewCommand == "ShuntVelocity") + { // uruchomienie jazdy manewrowej bądź zmiana prędkości + if (NewLocation) + vCommandLocation = *NewLocation; + // if (OrderList[OrderPos]=Obey_train) and (NewValue1<>0)) + if (false == iEngineActive) + OrderNext(DriverOrder::prepareEngine); // trzeba odpalić silnik najpierw + OrderNext(DriverOrder::shunt); // zamieniamy w aktualnej pozycji, albo dodajey za odpaleniem silnika + if (NewValue1 != 0.0) + { + // if (iVehicleCount>=0) WriteLog("Skasowano ilosć wagonów w ShuntVelocity!"); + iVehicleCount = -2; // wartość neutralna + CheckVehicles(); // zabrać to do OrderCheck() + } + // dla prędkości ujemnej przestawić nawrotnik do tyłu? ale -1=brak ograniczenia !!!! + drivingFlags.press = false; // bez dociskania + SetVelocity(NewValue1, NewValue2, reason); + if (NewValue1 != 0.0) + drivingFlags.stopHere = false; // podjeżanie do semaforów zezwolone + else + drivingFlags.stopHere = true; // ma stać w miejscu + if (fabs(NewValue1) > 2.0) // o ile wartość jest sensowna (-1 nie jest konkretną wartością) + fShuntVelocity = fabs(NewValue1); // zapamiętanie obowiązującej prędkości dla manewrów + + return true; + } + + if (NewCommand == "Wait_for_orders") + { // oczekiwanie; NewValue1 - czas oczekiwania, -1 = na inną komendę + if (NewValue1 > 0.0 ? NewValue1 > fStopTime : false) + fStopTime = NewValue1; // Ra: włączenie czekania bez zmiany komendy + else + OrderCurrentSet( DriverOrder::waitForOrders ); // czekanie na komendę (albo dać OrderPos=0) + + return true; + } + + if (NewCommand == "Prepare_engine") + { // włączenie albo wyłączenie silnika (w szerokim sensie) + OrdersClear(); // czyszczenie tabelki rozkazów, aby nic dalej nie robił + if (NewValue1 == 0.0) + OrderNext(DriverOrder::releaseEngine); // wyłączyć silnik (przygotować pojazd do jazdy) + else if (NewValue1 > 0.0) + OrderNext(DriverOrder::prepareEngine); // odpalić silnik (wyłączyć wszystko, co się da) + // po załączeniu przejdzie do kolejnej komendy, po wyłączeniu na Wait_for_orders + return true; + } + + if (NewCommand == "Change_direction") + { + DriverOrders o = OrderCurrentGet(); // co robił przed zmianą kierunku + if (false == iEngineActive) + OrderNext(DriverOrder::prepareEngine); // trzeba odpalić silnik najpierw + if (NewValue1 == 0.0) + iDirectionOrder = -iDirection; // zmiana na przeciwny niż obecny + else if (NewLocation) // jeśli podane współrzędne eventu/komórki ustawiającej rozkład + // (trainset nie podaje) + { + auto v = *NewLocation - pVehicle->GetPosition(); // wektor do punktu sterującego + auto d = pVehicle->VectorFront(); // wektor wskazujący przód + iDirectionOrder = (v.x * d.x + v.z * d.z) * NewValue1 > 0 ? + 1 : + -1; // do przodu, gdy iloczyn skalarny i prędkość dodatnie + // iDirectionOrder=1; else if (NewValue1<0.0) iDirectionOrder=-1; + } + if ( + + iDirectionOrder != iDirection) + OrderNext(DriverOrder::changeDirection); // zadanie komendy do wykonania + if (o.HasAny(movingOrders)) // jeśli jazda manewrowa albo pociągowa + OrderNext(o); // to samo robić po zmianie + else if (!o) // jeśli wcześniej było czekanie + OrderNext(DriverOrder::shunt); // to dalej jazda manewrowa + if (mvOccupied->Vel >= EU07_AI_MOVEMENT) // jeśli jedzie + drivingFlags.startHorn = false; // to bez trąbienia po ruszeniu z zatrzymania + // Change_direction wykona się samo i następnie przejdzie do kolejnej komendy + return true; + } + + if (NewCommand == "Obey_train") { + if( false == iEngineActive ) { + OrderNext( DriverOrder::prepareEngine ); // trzeba odpalić silnik najpierw + } + OrderNext( DriverOrder::obeyTrain ); + // if (NewValue1>0) TrainNumber=floor(NewValue1); //i co potem ??? + OrderCheck(); // jeśli jazda pociągowa teraz, to wykonać niezbędne operacje + + return true; + } + + if (NewCommand == "Bank") { + if( false == iEngineActive ) { + OrderNext( DriverOrder::prepareEngine ); // trzeba odpalić silnik najpierw + } + OrderNext( DriverOrder::bank ); + // if (NewValue1>0) TrainNumber=floor(NewValue1); //i co potem ??? + OrderCheck(); // jeśli jazda pociągowa teraz, to wykonać niezbędne operacje + + return true; + } + + if( NewCommand == "Shunt" || NewCommand == "Loose_shunt" ) + { // NewValue1 - ilość wagonów (-1=wszystkie); NewValue2: 0=odczep, 1..63=dołącz, -1=bez zmian + //-3,-y - podłączyć do całego stojącego składu (sprzęgiem y>=1), zmienić kierunek i czekać w trybie pociągowym + //-2,-y - podłączyć do całego stojącego składu (sprzęgiem y>=1), zmienić kierunek i czekać + //-2, y - podłączyć do całego stojącego składu (sprzęgiem y>=1) i czekać + //-1,-y - podłączyć do całego stojącego składu (sprzęgiem y>=1) i jechać w powrotną stronę + //-1, y - podłączyć do całego stojącego składu (sprzęgiem y>=1) i jechać dalej + //-1, 0 - tryb manewrowy bez zmian (odczepianie z pozostawieniem wagonów nie ma sensu) + // 0, 0 - odczepienie lokomotywy + // x,-y - podłączyć się do składu (sprzęgiem y>=1), a następnie odczepić i zabrać (x) wagonów + // 1, 0 - odczepienie lokomotywy z jednym wagonem + drivingFlags.stopHere = false; // podjeżanie do semaforów zezwolone + if( false == iEngineActive ) { + OrderNext( DriverOrder::prepareEngine ); // trzeba odpalić silnik najpierw + } + if (NewValue2 != 0) // jeśli podany jest sprzęg + { + iCoupler = CouplingSet::FromBits( static_cast( std::floor( std::abs( NewValue2 ) ) ) ); // jakim sprzęgiem + OrderNext(DriverOrder::connect); // najpierw połącz pojazdy + if (NewValue1 >= 0.0) // jeśli ilość wagonów inna niż wszystkie + { // to po podpięciu należy się odczepić + iDirectionOrder = -iDirection; // zmiana na ciągnięcie + OrderPush(DriverOrder::changeDirection); // najpierw zmień kierunek, bo odczepiamy z tyłu + OrderPush(DriverOrder::disconnect); // a odczep już po zmianie kierunku + if( NewValue2 > 0.0 + && NewCommand == "Loose_shunt" ) { + // after decoupling continue pushing in the original direction + // NOTE: for backward compatibility this option isn't supported for basic shunting mode + iDirectionOrder = iDirection; // back to pushing + OrderPush( DriverOrder::changeDirection ); + } + } + else if (NewValue2 < 0.0) // jeśli wszystkie, a sprzęg ujemny, to tylko zmiana kierunku po podczepieniu + { // np. Shunt -1 -3 + iDirectionOrder = -iDirection; // jak się podczepi, to jazda w przeciwną stronę + OrderNext(DriverOrder::changeDirection); + } + WaitingTime = 0.0; // nie ma co dalej czekać, można zatrąbić i jechać, chyba że już jedzie + } + else { // if (NewValue2==0.0) //zerowy sprzęg + if( NewValue1 >= 0.0 ) { + // jeśli ilość wagonów inna niż wszystkie będzie odczepianie, + // ale jeśli wagony są z przodu, to trzeba najpierw zmienić kierunek + if( mvOccupied->Couplers[mvOccupied->DirAbsolute > 0 ? end::rear : end::front].Connected == nullptr // z tyłu nic + && mvOccupied->Couplers[mvOccupied->DirAbsolute > 0 ? end::front : end::rear].Connected != nullptr ) { // a z przodu skład + iDirectionOrder = -iDirection; // zmiana na ciągnięcie + OrderNext( DriverOrder::changeDirection ); // najpierw zmień kierunek (zastąpi Disconnect) + OrderPush( DriverOrder::disconnect ); // a odczep już po zmianie kierunku + } + else if( mvOccupied->Couplers[ mvOccupied->DirAbsolute > 0 ? end::rear : end::front ].Connected != nullptr ) { // z tyłu coś + OrderNext( DriverOrder::disconnect ); // jak ciągnie, to tylko odczep (NewValue1) wagonów + } + else { + // both couplers empty + // NOTE: this condition implements legacy behavior (mis)used by some scenarios to keep vehicle idling without moving + SetVelocity( 0, 0, stopJoin ); + drivingFlags.stopHere = true; // nie podjeżdżać do semafora, jeśli droga nie jest wolna + } + WaitingTime = 0.0; // nie ma co dalej czekać, można zatrąbić i jechać, chyba że już jedzie + } + } + if (NewValue1 == -1.0) { + drivingFlags.stopHere = false; // ma jechać + WaitingTime = 0.0; // nie ma co dalej czekać, można zatrąbić i jechać + } + if( NewValue1 < -1.5 ) { // jeśli -2/-3, czyli czekanie z ruszeniem na sygnał + drivingFlags.stopHere = true; // nie podjeżdżać do semafora, jeśli droga nie jest wolna + } + // (nie dotyczy Connect) + if( NewValue1 < -2.5 ) { // jeśli -3 to potem jazda pociągowa + OrderNext( NewCommand == "Shunt" ? DriverOrder::obeyTrain : DriverOrder::bank ); + } + else { // otherwise continue shunting + OrderNext( NewCommand == "Shunt" ? DriverOrder::shunt : DriverOrder::looseShunt ); + } + CheckVehicles(); // sprawdzić światła + iVehicleCount = std::floor( NewValue1 ); + + return true; + } + + if( NewCommand == "Jump_to_first_order" ) { + JumpToFirstOrder(); + return true; + } + + if (NewCommand == "Jump_to_order") + { + if( NewValue1 == -1.0 ) { + JumpToNextOrder(); + } + else if (NewValue1 >= 0 && NewValue1 < maxorders) + { + OrderPos = floor(NewValue1); + if( !OrderPos ) { + // zgodność wstecz: dopiero pierwsza uruchamia + OrderPos = 1; + } +#if LOGORDERS + OrdersDump("Jump_to_order"); +#endif + } + return true; + } + + if (NewCommand == "Warning_signal") + { + if( NewValue1 > 0 && NewValue2 > 0 ) { + fWarningDuration = NewValue1; // czas trąbienia + cue_action( driver_hint::hornon, NewValue2 ); // horn combination flag + simulation::Blackbox.horn_requested( + pVehicles[ end::front ], NewValue1, NewValue2, NewLocation != nullptr ? *NewLocation : pVehicles[ end::front ]->GetPosition() ); + } + return true; + } + + if (NewCommand == "Radio_channel") { + // wybór kanału radiowego (którego powinien używać AI, ręczny maszynista musi go ustawić sam) + if (NewValue1 >= 0) { + // wartości ujemne są zarezerwowane, -1 = nie zmieniać kanału + if( AIControllFlag ) { + iRadioChannel = NewValue1; + } + if( iGuardRadio ) { + // kierownikowi też zmienić + iGuardRadio = NewValue1; + } + } + // NewValue2 może zawierać dodatkowo oczekiwany kod odpowiedzi, np. dla W29 "nawiązać + // łączność radiową z dyżurnym ruchu odcinkowym" + return true; + } + + if( NewCommand == "SetLights" ) { + // set consist lights pattern hints + m_lighthints[ end::front ] = static_cast( NewValue1 ); + m_lighthints[ end::rear ] = static_cast( NewValue2 ); + if( true == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { + // light hints only apply in the obey_train mode + CheckVehicles(); + } + return true; + } + + if (NewCommand == "SetSignal") { + auto const signal{std::lrint(NewValue1)}; + + drivingFlags.signalPc6 = false; + drivingFlags.signalA1 = false; + + if (NewValue2 > 0.5) + { + // another number set the bit of a driving flag of that number before + drivingFlags.signalPc6 = signal == Signal_Pc6; + drivingFlags.signalA1 = signal == Signal_A1; + } + else + CheckVehicles(); // restore light state + } + + return false; // nierozpoznana - wysłać bezpośrednio do pojazdu +}; + +void TController::JumpToNextOrder( bool const Ignoremergedchangedirection ) +{ // wykonanie kolejnej komendy z tablicy rozkazów + if (auto const currentorder { OrderCurrentGet() }; currentorder != DriverOrder::waitForOrders) + { + if( currentorder.HasAny(DriverOrder::changeDirection) // jeśli zmiana kierunku + && currentorder != DriverOrder::changeDirection && false == Ignoremergedchangedirection ) { // ale nałożona na coś + + // usunięcie zmiany kierunku z innej komendy + OrderCurrentSet( currentorder.Without(DriverOrder::changeDirection) ); + OrderCheck(); + return; + } + if (OrderPos < maxorders - 1) + ++OrderPos; + else + OrderPos = 0; + } + OrderCheck(); +#if LOGORDERS + OrdersDump("JumpToNextOrder"); // normalnie nie ma po co tego wypisywać +#endif +}; + +void TController::JumpToFirstOrder() +{ // taki relikt + OrderPos = 1; + if (OrderTop == 0) + OrderTop = 1; + OrderCheck(); +#if LOGORDERS + OrdersDump("JumpToFirstOrder"); // normalnie nie ma po co tego wypisywać +#endif +}; + +void TController::OrderCheck() +{ // reakcja na zmianę rozkazu + + if( OrderCurrentGet() != DriverOrder::obeyTrain ) { + // reset light hints + m_lighthints[ end::front ] = m_lighthints[ end::rear ] = -1; + } + if( OrderCurrentGet() & ( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect | DriverOrder::obeyTrain | DriverOrder::bank ) ) { + CheckVehicles(); // sprawdzić światła + } + if( OrderCurrentGet() & ( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect ) ) { + // HACK: ensure consist doors will be closed on departure + drivingFlags.doorOpened = true; + } + auto const currentorder { OrderCurrentGet() }; + if (currentorder & DriverOrder::changeDirection) // może być nałożona na inną i wtedy ma priorytet + iDirectionOrder = -iDirection; // trzeba zmienić jawnie, bo się nie domyśli + else if (currentorder == DriverOrder::obeyTrain) + drivingFlags.stopPoint = true; // W4 są widziane + else if (currentorder == DriverOrder::disconnect) + iVehicleCount = iVehicleCount < 0 ? 0 : iVehicleCount; // odczepianie lokomotywy + else if (currentorder == DriverOrder::connect) + drivingFlags.stopPoint = false; // podczas jazdy na połączenie nie zwracać uwagi na W4 + else if (currentorder == DriverOrder::waitForOrders) + OrdersClear(); // czyszczenie rozkazów i przeskok do zerowej pozycji +} + +void TController::OrderNext(DriverOrders NewOrder) +{ // ustawienie rozkazu do wykonania jako następny + if (OrderCurrentGet() == NewOrder) + return; // jeśli robi to, co trzeba, to koniec + if (!OrderPos) + OrderPos = 1; // na pozycji zerowej pozostaje czekanie + OrderTop = OrderPos; // ale może jest czymś zajęty na razie + if (NewOrder.HasAny(movingOrders)) // jeśli ma jechać + { // ale może być zajęty chwilowymi operacjami + while (OrderTop >= 0 && OrderTop < maxorders - 1 + && OrderList[OrderTop] != DriverOrder::waitForOrders && false == OrderList[OrderTop].HasAny(movingOrders)) // jeśli coś robi + ++OrderTop; // pomijamy wszystkie tymczasowe prace + } + else + { // jeśli ma ustawioną jazdę, to wyłączamy na rzecz operacji + while (OrderTop >= 0 && OrderTop < maxorders - 1 + && OrderList[OrderTop] != DriverOrder::waitForOrders && false == OrderList[OrderTop].HasAny(movingOrders) && OrderList[OrderTop] != NewOrder) // jeśli coś robi + ++OrderTop; // pomijamy wszystkie tymczasowe prace + } + if (OrderTop < 0 || OrderTop >= maxorders) + { + ErrorLog("Commands overflow: order \"" + Order2Str(NewOrder) + "\" dropped"); + return; + } + OrderList[OrderTop++] = NewOrder; // dodanie rozkazu jako następnego +#if LOGORDERS + OrdersDump( "OrderNext" ); // normalnie nie ma po co tego wypisywać +#endif +} + +void TController::OrderPush(DriverOrders NewOrder) +{ // zapisanie na stosie kolejnego rozkazu do wykonania + if (OrderPos == OrderTop && false == OrderCurrentGet().HasAny(movingOrders)) // jeśli miałby być zapis na aktalnej pozycji + // ale nie jedzie + ++OrderTop; + // niektóre operacje muszą zostać najpierw dokończone => zapis na kolejnej + if (OrderTop < 0 || OrderTop >= maxorders) + { + ErrorLog("Commands overflow: order \"" + Order2Str(NewOrder) + "\" dropped"); + return; + } + if (OrderList[OrderTop] != NewOrder) // jeśli jest to samo, to nie dodajemy + OrderList[OrderTop++] = NewOrder; // dodanie rozkazu na stos +#if LOGORDERS + OrdersDump( "OrderPush: [" + Order2Str( NewOrder ) + "]" ); // normalnie nie ma po co tego wypisywać +#endif +} + +void TController::OrdersDump( std::string const Neworder, bool const Verbose ) +{ // wypisanie kolejnych rozkazów do logu + WriteLog( "New order for [" + pVehicle->asName + "]: " + Neworder ); + if( false == Verbose ) { return; } + for (int b = 0; b < maxorders; ++b) + { + WriteLog( ( OrderPos == b ? ">" : " " ) + (std::to_string(b) + ": " + Order2Str(OrderList[b]))); + if (b && OrderList[b] == DriverOrder::waitForOrders) // z wyjątkiem pierwszej pozycji + // jeśli końcowa komenda + break; + // dalej nie trzeba + } +}; + +void TController::OrdersInit(double fVel) +{ // wypełnianie tabelki rozkazów na podstawie rozkładu + // ustawienie kolejności komend, niezależnie kto prowadzi + OrdersClear(); // usunięcie poprzedniej tabeli + OrderPush(DriverOrder::prepareEngine); // najpierw odpalenie silnika + if (TrainParams.StationCount == 0) + { // brak rozkładu to jazda manewrowa +// if (fVel > 0.05) // typowo 0.1 oznacza gotowość do jazdy, 0.01 tylko załączenie silnika + OrderPush(DriverOrder::shunt); // jeśli nie ma rozkładu, to manewruje + } + else + { // jeśli z rozkładem, to jedzie na szlak + if (fVel > 0.0 && fVel < 0.02) + OrderPush(DriverOrder::shunt); // dla prędkości 0.01 włączamy jazdę manewrową + else if (TrainParams.DirectionChange() ? // jeśli obrót na pierwszym przystanku + (drivingFlags.pushPull ? // SZT również! SN61 zależnie od wagonów... + TrainParams.TimeTable[1].StationName == TrainParams.Relation1 : + false) : + false) + OrderPush(DriverOrder::shunt); // a teraz start będzie w manewrowym, a tryb pociągowy włączy W4 + else + // jeśli start z pierwszej stacji i jednocześnie jest na niej zmiana kierunku, to EZT ma mieć Shunt + OrderPush(DriverOrder::obeyTrain); // dla starych scenerii start w trybie pociagowym + if (DebugModeFlag) // normalnie nie ma po co tego wypisywać + WriteLog("/* Timetable: " + TrainParams.ShowRelation()); + TMTableLine *t; + for (int i = 0; i <= TrainParams.StationCount; ++i) + { + t = TrainParams.TimeTable + i; + if (DebugModeFlag) { + // normalnie nie ma po co tego wypisywa? + WriteLog( + t->StationName + + " " + std::to_string(t->Ah) + ":" + std::to_string(t->Am) + + ", " + std::to_string(t->Dh) + ":" + std::to_string(t->Dm) + + " " + t->StationWare); + } + if ( contains( t->StationWare, '@' ) ) + { // zmiana kierunku i dalsza jazda wg rozk?adu + if (drivingFlags.pushPull) // SZT również! SN61 zależnie od wagonów... + { // jeśli skład zespolony, wystarczy zmienić kierunek jazdy + OrderPush(DriverOrder::changeDirection); // zmiana kierunku + } + else + { // dla zwykłego składu wagonowego odczepiamy lokomotywę + OrderPush(DriverOrder::disconnect); // odczepienie lokomotywy + OrderPush(DriverOrder::shunt); // a dalej manewry + } + if (i < TrainParams.StationCount) // jak nie ostatnia stacja + OrderPush(DriverOrder::obeyTrain); // to dalej wg rozkładu + } + } + if( DebugModeFlag ) { + // normalnie nie ma po co tego wypisywać + WriteLog( "*/" ); + } + OrderPush(DriverOrder::shunt); // po wykonaniu rozkładu przełączy się na manewry + } + // McZapkie-100302 - to ma byc wyzwalane ze scenerii + if( fVel == 0.0 ) { + // jeśli nie ma prędkości początkowej, to śpi + SetVelocity( 0, 0, stopSleep ); + } + else { + // jeśli podana niezerowa prędkość + if( fVel >= 1.0 + || fVel < 0.02 ) { + // jeśli ma jechać - dla 0.01 ma podjechać manewrowo po podaniu sygnału + // to do następnego W4 ma podjechać blisko + drivingFlags.stopHere = false; + drivingFlags.stopCloser = true; + } + else { + // czekać na sygnał + drivingFlags.stopHere = true; + } + JumpToFirstOrder(); + if (fVel >= 1.0) // jeśli ma jechać + SetVelocity(fVel, -1); // ma ustawić żądaną prędkość + else + SetVelocity(0, 0, stopSleep); // prędkość w przedziale (0;1) oznacza, że ma stać + } +#if LOGORDERS + OrdersDump( "OrdersInit", DebugModeFlag ); // wypisanie kontrolne tabelki rozkazów +#endif + // McZapkie! - zeby w ogole AI ruszyl to musi wykonac powyzsze rozkazy + // Ale mozna by je zapodac ze scenerii +}; + +std::string TController::StopReasonText() const +{ // informacja tekstowa o przyczynie zatrzymania + if (eStopReason != 7) // zawalidroga będzie inaczej + return StopReasonTable[eStopReason]; + else + return "Blocked by " + pVehicles[0]->PrevAny()->name(); +}; + +//---------------------------------------------------------------------------------------------------------------------- +// McZapkie: skanowanie semaforów +// Ra: stare funkcje skanujące, używane podczas manewrów do szukania sygnalizatora z tyłu +//- nie reagują na PutValues, bo nie ma takiej potrzeby +//- rozpoznają tylko zerową prędkość (jako koniec toru i brak podstaw do dalszego skanowania) +//---------------------------------------------------------------------------------------------------------------------- + +bool TController::IsOccupiedByAnotherConsist( TTrack *Track, double const Distance ) +{ // najpierw sprawdzamy, czy na danym torze są pojazdy z innego składu + if( false == Track->Dynamics.empty() ) { + for( auto dynamic : Track->Dynamics ) { + if( dynamic->ctOwner != this ) { + // jeśli jest jakiś cudzy to tor jest zajęty i skanowanie nie obowiązuje + if( Distance == 0 ) { + return true; + } + else { + // based on provided position of scanning vehicle and scan direction, filter out vehicles on irrelevant end + auto const scandirection { Distance > 0 ? 1 : -1 }; // positive value means scan towards point2 end of the track + auto const obstaclelocation { scandirection > 0 ? Track->Length() - dynamic->RaTranslationGet() : dynamic->RaTranslationGet() }; + // if detected vehicle is closer to the end of the track in scanned direction than we are, it means it's blocking our way + if( obstaclelocation < std::abs( Distance ) ) { + return true; + } + } + } + } + } + return false; // wolny +}; + +void +TController::UpdateChangeDirection() { + // TODO: rework into driver mode independent routine + if( false == OrderCurrentGet().HasAll(DriverOrder::changeDirection) ) { return; } + + if( true == AIControllFlag && mvOccupied->Vel < EU07_AI_NOMOVEMENT ) { + // sprobuj zmienic kierunek (może być zmieszane z jeszcze jakąś komendą) + // jeśli się zatrzymał, to zmieniamy kierunek jazdy, a nawet kabinę/człon + Activation(); // ustawienie zadanego wcześniej kierunku i ewentualne przemieszczenie AI + // Change_direction (tylko dla AI) + } + // shared part of the routine, implement if direction matches what was requested + if( mvOccupied->Vel < EU07_AI_NOMOVEMENT + && iDirection == iDirectionOrder ) { + // NOTE: we can't be sure there's a visible signal within scan range after direction change + // which would normally overwrite the old limit, so we reset signal value manually here + VelSignal = -1; + VelSignalNext = -1; + PrepareEngine(); + JumpToNextOrder(); // następnie robimy, co jest do zrobienia (Shunt albo Obey_train) + if( OrderCurrentGet() & (DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect) && false == drivingFlags.stopHere ) { + // jeśli dalej mamy manewry + // o ile nie ma stać w miejscu, + // jechać od razu w przeciwną stronę i nie trąbić z tego tytułu: + drivingFlags.startHorn = false; + SetVelocity(fShuntVelocity, fShuntVelocity); + } + } +} + +void +TController::UpdateLooseShunt() { + // when loose shunting try to detect situations where engaged brakes in a consist to be pushed prevent movement + // TODO: run also for potential settings-based virtual assistant + auto const autobrakerelease { ( true == AIControllFlag ) }; + + if( autobrakerelease + && Obstacle.distance < 1.0 + && AccDesired > 0.1 + && mvOccupied->Vel < 1.0 ) { + + auto *vehicle { Obstacle.vehicle }; + auto const direction { ( vehicle->Prev() != nullptr ? end::front : end::rear ) }; + while( vehicle != nullptr ) { + if( vehicle->MoverParameters->BrakePress > 0.2 ) { + vehicle->MoverParameters->BrakeLevelSet( 0 ); // hamulec na zero, aby nie hamował + vehicle->MoverParameters->BrakeReleaser( 1 ); // wyluzuj pojazd, aby dało się dopychać + } + // NOTE: we trust the consist to be arranged in a valid chain + // TBD, TODO: traversal direction validation? + vehicle = direction == end::front ? vehicle->Prev() : vehicle->Next(); + } + } +} + +void +TController::UpdateObeyTrain() { + + UpdateNextStop(); + + if( drivingFlags.guardSignal + && VelDesired > 0.0 ) { + // komunikat od kierownika tu, bo musi być wolna droga i odczekany czas stania + drivingFlags.guardSignal = false; // tylko raz nadać + drivingFlags.guardOpenDoor = false; // nie trzeba już otwierać drzwi + if( false == tsGuardSignal.empty() ) { + tsGuardSignal.stop(); + // w zasadzie to powinien mieć flagę, czy jest dźwiękiem radiowym, czy bezpośrednim + // albo trzeba zrobić dwa dźwięki, jeden bezpośredni, słyszalny w + // pobliżu, a drugi radiowy, słyszalny w innych lokomotywach + // na razie zakładam, że to nie jest dźwięk radiowy, bo trzeba by zrobić + // obsługę kanałów radiowych itd. + if( iGuardRadio == 0 ) { + // jeśli nie przez radio + tsGuardSignal.owner( pVehicle ); + // place virtual conductor some distance away + tsGuardSignal.offset( { pVehicle->MoverParameters->Dim.W * -0.75f, 1.7f, std::min( -20.0, -0.2 * fLength ) } ); + tsGuardSignal.play( sound_flags::exclusive ); + // NOTE: we can't rely on is_playing() check as sound playback is based on distance from local camera + fActionTime = -5.0; // niech trochę potrzyma + } + else { + // radio message + tsGuardSignal.owner( pVehicle ); +/* + tsGuardSignal.offset( { 0.f, 2.f, pVehicle->MoverParameters->Dim.L * 0.4f * ( pVehicle->MoverParameters->CabOccupied < 0 ? -1 : 1 ) } ); + tsGuardSignal.play( sound_flags::exclusive ); +*/ + simulation::radio_message( &tsGuardSignal, iGuardRadio ); + // NOTE: we can't rely on is_playing() check as sound playback is based on distance from local camera + fActionTime = -5.0; // niech trochę potrzyma + } + } + } +} + +void +TController::UpdateConnect() { + // podłączanie do składu + if (drivingFlags.connect) { + // sprzęgi sprawdzamy w pierwszej kolejności, bo jak połączony, to koniec + auto *vehicle { iCouplingVehicle.value().first }; + auto const couplingend { iCouplingVehicle.value().second }; + auto *vehicleparameters { vehicle->MoverParameters }; + auto const &neighbour { vehicleparameters->Neighbours[ couplingend ] }; + // vehicles which can't share their control get coupled without the control connection (eu07/maszyna#520) + auto expectedcoupling { iCoupler }; + if( neighbour.vehicle != nullptr ) { + auto const neighbourend { neighbour.vehicle_end != 2 ? neighbour.vehicle_end : vehicleparameters->Couplers[ couplingend ].ConnectedNr }; + expectedcoupling = vehicleparameters->CompatibleCoupling( couplingend, *neighbour.vehicle->MoverParameters, neighbourend, iCoupler ); + } + if( vehicleparameters->Couplers[ couplingend ].CouplingFlag != expectedcoupling ) { + if( neighbour.vehicle != nullptr && neighbour.distance < 10 ) { + // check whether we need to attach coupler adapter + auto coupleriscompatible{true}; + auto const &coupler{vehicleparameters->Couplers[couplingend]}; + if (coupler.type() != TCouplerType::Automatic) + { + auto const &othercoupler = neighbour.vehicle->MoverParameters->Couplers[(neighbour.vehicle_end != 2 ? neighbour.vehicle_end : coupler.ConnectedNr)]; + if (othercoupler.type() == TCouplerType::Automatic) + { + coupleriscompatible = false; + cue_action(driver_hint::couplingadapterattach, couplingend); + } + } + // próba podczepienia + if ((AIControllFlag || Global.AITrainman) && coupleriscompatible && neighbour.distance < 2) + { + vehicleparameters->Attach(couplingend, neighbour.vehicle_end, neighbour.vehicle->MoverParameters, iCoupler); + } + } + } + // NOTE: no else as the preceeding block can potentially establish expected connection + if( vehicleparameters->Couplers[ couplingend ].CouplingFlag == expectedcoupling ) { + // jeżeli został podłączony + CheckVehicles( DriverOrder::connect ); // sprawdzić światła nowego składu + + iCoupler = {}; // dalsza jazda manewrowa już bez łączenia + iCouplingVehicle.reset(); + drivingFlags.connect = false; // zdjęcie flagi doczepiania + JumpToNextOrder( true ); // wykonanie następnej komendy + } + } // moveConnect + else { + // początek podczepiania, z wyłączeniem sprawdzania fTrackBlock + if( Obstacle.distance <= 20.0 && !iCouplingVehicle ) { + // write down which vehicle should be coupled with the target consist, + // so we don't lose track of it if the user does something unexpected + iCouplingVehicle = {pVehicles[end::front], (pVehicles[end::front]->DirectionGet() > 0 ? end::front : end::rear)}; + drivingFlags.connect = true; + } + } +} + +int +TController::unit_count( int const Threshold ) const { + + auto *vehicle { pVehicle }; + auto unitcount { 1 }; + do { + auto const decoupledend{ ( vehicle->DirectionGet() > 0 ? // numer sprzęgu od strony czoła składu + end::rear : + end::front ) }; + auto const coupling { vehicle->MoverParameters->Couplers[ decoupledend ].CouplingFlag }; + if( coupling == Coupling::none ) { + break; + } + // jeżeli sprzęg zablokowany to liczymy człony jako jeden + if( false == coupling.HasAny( Coupling::permanent ) ) { + ++unitcount; + } + vehicle = vehicle->Next(); + } while( unitcount < Threshold ); + + return unitcount; +} + +void +TController::UpdateDisconnect() { + + if( iVehicleCount >= 0 ) { + // early test for human drivers, who might disregard the proper procedure, or perform it before they receive the order to + if( false == AIControllFlag && unit_count(iVehicleCount + 2) <= iVehicleCount + 1 ) { + // iVehicleCount = 0 means the consist should be reduced to (1) leading unit, thus we increase our test values by 1 + iVehicleCount = -2; // odczepiono, co było do odczepienia + return; // we'll wrap up the procedure on the next update beat + } + // regular uncoupling procedure, performed by ai and naively expected from the human drivers + // 3rd stage: change direction, compress buffers and uncouple + if( iDirection != iDirectionOrder ) { + cue_action( driver_hint::mastercontrollersetreverserunlock ); + cue_action( driver_hint::directionother ); + } + if( drivingFlags.press && iDirection == iDirectionOrder ) { + if( iVehicleCount >= 0 ) { + // zmieni się po odczepieniu + WriteLog( "Uncoupling [" + mvOccupied->Name + "]: actuating and compressing buffers..." ); + cue_action( driver_hint::independentbrakerelease ); + cue_action( driver_hint::bufferscompress ); + } + + WriteLog( "Uncoupling [" + mvOccupied->Name + "]: from " + ( mvOccupied->DirAbsolute > 0 ? "front" : "rear" ) ); + auto *decoupledvehicle { pVehicle }; // pojazd do odczepienia, w (pVehicle) siedzi AI + int decoupledend; // numer sprzęgu, który sprawdzamy albo odczepiamy + auto vehiclecount { iVehicleCount }; // ile wagonów ma zostać + // szukanie pojazdu do odczepienia + do { + decoupledend = decoupledvehicle->DirectionGet() > 0 ? // numer sprzęgu od strony czoła składu + end::front : + end::rear; + // jeżeli sprzęg zablokowany to liczymy człony jako jeden + if( decoupledvehicle->MoverParameters->Couplers[ decoupledend ].CouplingFlag & Coupling::permanent ) { + ++vehiclecount; + } + if( decoupledvehicle != pVehicle ) { + decoupledvehicle->MoverParameters->BrakeReleaser( 1 ); // wyluzuj pojazd, aby dało się dopychać + } + if( vehiclecount ) { // jeśli jeszcze nie koniec + decoupledvehicle = decoupledvehicle->Prev(); // kolejny w stronę czoła składu (licząc od tyłu), bo dociskamy + if( decoupledvehicle == nullptr ) { + vehiclecount = 0; // nie ma co dalej sprawdzać, odczepianie zakończone + } + } + } while( vehiclecount-- ); + if( decoupledvehicle == nullptr ) { + // no target, or already just virtual coupling + WriteLog( "Uncoupling [" + mvOccupied->Name + "]: didn't find anything to disconnect" ); + iVehicleCount = -2; // odczepiono, co było do odczepienia + } + else { + if( AIControllFlag || Global.AITrainman ) { + decoupledvehicle->Dettach( decoupledend ); + } + // tylko jeśli odepnie + if( decoupledvehicle->MoverParameters->Couplers[ decoupledend ].CouplingFlag == Coupling::none ) { + WriteLog( "Uncoupling [" + mvOccupied->Name + "]: uncoupled" ); + iVehicleCount = -2; + // update trainset state + CheckVehicles( DriverOrder::disconnect ); + // potentially remove coupler adapter +/* + if( decoupledvehicle->MoverParameters->Couplers[ decoupledend ].has_adapter() ) { + decoupledvehicle->remove_coupler_adapter( decoupledend ); + } +*/ + if( pVehicles[ end::front ]->MoverParameters->Couplers[ decoupledend ].has_adapter() ) { + cue_action( driver_hint::couplingadapterremove, decoupledend ); + } + } + } // a jak nie, to dociskać dalej + } + // 2nd stage: apply consist brakes and change direction + if( ( false == drivingFlags.press ) ) { + // store initial consist direction + if( !iDirectionBackup ) { + iDirectionBackup = iDirection; + } + if( false == IsConsistBraked ) { + WriteLog( "Uncoupling [" + mvOccupied->Name + "]: applying consist brakes..." ); + cue_action( driver_hint::trainbrakeapply ); + } + // jeśli w miarę został zahamowany (ciśnienie mniejsze niż podane na pozycji 3, zwyle 0.37) + else { + WriteLog( "Uncoupling [" + mvOccupied->Name + "]: direction change" ); +/* // TODO: test if this block is needed + if( BrakeSystem == TBrakeSystem::ElectroPneumatic ) { + // wyłączenie EP, gdy wystarczy (może nie być potrzebne, bo na początku jest) + mvOccupied->BrakeLevelSet( 0 ); + } +*/ + iDirectionOrder = -iDirection; // zmiana kierunku jazdy na przeciwny (dociskanie) + drivingFlags.press = true; // następnie będzie dociskanie + } + } + } // odczepianie + if( iVehicleCount < 0 ) { + // 4th stage: restore initial direction + if( iDirectionBackup ) { + iDirectionOrder = iDirectionBackup.value(); + iDirectionBackup.reset(); + } + if( iDirection != iDirectionOrder ) { + WriteLog( "Uncoupling [" + mvOccupied->Name + "]: second direction change" ); + cue_action( driver_hint::mastercontrollersetreverserunlock ); + cue_action( driver_hint::directionother ); // zmiana kierunku jazdy na właściwy + } + // 5th stage: clean up and move on to next order + if( iDirection == iDirectionOrder ) { + drivingFlags.press = false; // koniec dociskania + JumpToNextOrder( true ); // zmieni światła + TableClear(); // skanowanie od nowa + drivingFlags.startHorn = false; // bez trąbienia przed ruszeniem + } + } +} + +void +TController::handle_engine() { + // HACK: activate route scanning if an idling vehicle is activated by a human user + if( OrderCurrentGet() == DriverOrder::waitForOrders + && false == iEngineActive +// && ( false == AIControllFlag ) + && true == mvOccupied->Power24vIsAvailable ) { + OrderNext( DriverOrder::prepareEngine ); + } + // basic engine preparation + if( OrderCurrentGet() == DriverOrder::prepareEngine && PrepareEngine() ) { + // gotowy do drogi? + JumpToNextOrder(); + } + // engine state can potentially deteriorate in one of usual driving modes + if( OrderCurrentGet() & (DriverOrder::changeDirection | DriverOrder::connect | DriverOrder::disconnect | DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank) + && false == iEngineActive ) { + // jeśli coś ma robić to niech odpala do skutku + PrepareEngine(); + } +} + +void +TController::handle_orders() { + + switch (SingleOrder(OrderCurrentGet())) + { + case DriverOrder::releaseEngine: { + if( ReleaseEngine() ) { // zdana maszyna? + JumpToNextOrder(); + } + break; + } + case DriverOrder::obeyTrain: { + UpdateObeyTrain(); + break; + } + case DriverOrder::looseShunt: { + UpdateLooseShunt(); + break; + } + case DriverOrder::connect: { + UpdateConnect(); + break; + } + case DriverOrder::disconnect: { + UpdateDisconnect(); + break; + } + case DriverOrder::jumpToFirstOrder: { + if( OrderPos > 1 ) { + OrderPos = 1; // w zerowym zawsze jest czekanie + } + else { + ++OrderPos; + } +#if LOGORDERS + OrdersDump("Jump_to_first_order"); +#endif + break; + } + default: { + // special case, change_direction potentially received during partially completed coupling operation + // this is unlikely to happen for the AI, but can happen for a (slower) human user + if( drivingFlags.connect ) { + UpdateConnect(); + } + break; + } + } // switch OrderList[OrderPos] + UpdateChangeDirection(); +} diff --git a/vehicle/ai/physicslog.cpp b/vehicle/ai/physicslog.cpp new file mode 100644 index 000000000..758bd1184 --- /dev/null +++ b/vehicle/ai/physicslog.cpp @@ -0,0 +1,125 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the log of the physics of the train the driver runs + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/mover.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + + +std::string_view TController::physicslog_header() { + // the columns of the readers of these logs, the Hasler tape of the starter among them, stay where they are: + // a new one goes at the end + return "Time[s] Velocity[m/s] Acceleration[m/ss] " + "Coupler.Dist[m] Coupler.Force[N] TractionForce[kN] FrictionForce[kN] BrakeForce[kN] " + "BrakePress[MPa] PipePress[MPa] MotorCurrent[A] " + "MCP SCP BCP LBP Direction Command CVal1 CVal2 " + "Security Wheelslip " + "EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg] " + "VehicleVelocity[km/h]" + "\r\n"; +} + +std::string TController::physicslog_line() const { + std::ostringstream line; + line << std::fixed << std::setprecision( 4 ) + << ElapsedTime << " " + << fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot) << " " + << mvControlling->AccS << " " + << mvOccupied->Couplers[1].Dist << " " + << mvOccupied->Couplers[1].CForce << " " + << mvOccupied->Ft << " " + << mvOccupied->Ff << " " + << mvOccupied->Fb << " " + << mvOccupied->BrakePress << " " + << mvOccupied->PipePress << " " + << mvControlling->Im << " " + << int(mvControlling->MainCtrlPos) << " " + << int(mvControlling->ScndCtrlPos) << " " + << mvOccupied->fBrakeCtrlPos << " " + << mvOccupied->LocalBrakePosA << " " + << int(mvControlling->DirActive) << " " + << ( mvOccupied->CommandIn.Text.empty() ? "none" : mvOccupied->CommandIn.Text.c_str() ) << " " + << mvOccupied->CommandIn.Value1 << " " + << mvOccupied->CommandIn.Value2 << " " + << int(mvControlling->SecuritySystem.is_blinking()) << " " + << int(mvControlling->SlippingWheels) << " " + << mvControlling->dizel_heat.Ts << " " + << mvControlling->dizel_heat.To << " " + << mvControlling->dizel_heat.temperatura1 << " " + << mvControlling->dizel_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 + << mvOccupied->V * 3.6 + << "\r\n"; + return line.str(); +} + +void TController::begin_physicslog() +{ + // physicslog/.dat, written every two seconds along with the logs of the other drivers +#if LOGPRESS == 0 + PhysicsLogs.begin( VehicleName, physicslog_header() ); +#endif +#if LOGPRESS == 1 + PhysicsLogs.begin( VehicleName, "t\tVel\tAcc\tPP\tVVP\tBP\tBVP\tCVP\n" ); +#endif + PhysicsLogBegun = true; +} + +void TController::PhysicsLog() +{ // zapis logu - na razie tylko wypisanie parametrów +#if LOGPRESS == 0 + PhysicsLogs.append( VehicleName, physicslog_line() ); +#endif +#if LOGPRESS == 1 + std::ostringstream line; + line << ElapsedTime << "\t" << fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot) + << "\t"; + line << mvControlling->AccS << "\t"; + line << mvOccupied->PipePress << "\t" << mvOccupied->CntrlPipePress << "\t" + << mvOccupied->BrakePress << "\t"; + line << mvOccupied->Volume << "\t" << mvOccupied->Hamulec->GetCRP() << "\n"; + PhysicsLogs.append( VehicleName, line.str() ); +#endif +}; diff --git a/vehicle/ai/routescan.cpp b/vehicle/ai/routescan.cpp new file mode 100644 index 000000000..35fd170fc --- /dev/null +++ b/vehicle/ai/routescan.cpp @@ -0,0 +1,625 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// scanning the route ahead into the speed table, the signals passed + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/mover.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + +// finds point of specified track nearest to specified event. returns: distance to that point from the specified end of the track +// TODO: move this to file with all generic routines, too easy to forget it's here and it may come useful +double +ProjectEventOnTrack( basic_event const *Event, TTrack const *Track, double const Direction ) { + + auto const segment = Track->CurrentSegment(); + auto const nearestpoint = segment->find_nearest_point( Event->input_location() ); + return Direction > 0 ? nearestpoint * segment->GetLength() : // measure from point1 + (1.0 - nearestpoint) * segment->GetLength(); // measure from point2 +}; + +double GetDistanceToEvent(TTrack const *track, basic_event const *event, double scan_dir, double start_dist, int iter = 0, bool back = false) +{ + if( track == nullptr ) { return start_dist; } + + auto const segment = track->CurrentSegment(); + auto const pos_event = event->input_location(); + double len1, len2; + double sd = scan_dir; + double seg_len = scan_dir > 0 ? 0.0 : 1.0; + double const dzielnik = 1.0 / segment->GetLength();// rozdzielczosc mniej wiecej 1m + int krok = 0; // krok obliczeniowy do sprawdzania czy odwracamy + len2 = glm::length2(pos_event - segment->FastGetPoint(seg_len)); + do + { + len1 = len2; + seg_len += scan_dir > 0 ? dzielnik : -dzielnik; + len2 = glm::length2(pos_event - segment->FastGetPoint(seg_len)); + ++krok; + } while (len1 > len2 && seg_len >= dzielnik && seg_len <= 1.0 - dzielnik); + //trzeba sprawdzić czy seg_len nie osiągnął skrajnych wartości, bo wtedy + // trzeba sprawdzić tor obok + if (1 == krok) + sd = -sd; // jeśli tylko jeden krok tzn, że event przy poprzednim sprawdzaym torze + if ((1 == krok || seg_len <= dzielnik || seg_len > 1.0 - dzielnik) && iter < 3) + { // przejście na inny tor + track = track->Connected(int(sd), sd); + start_dist += 1 == krok ? 0 : back ? -segment->GetLength() : segment->GetLength(); + if( track != nullptr + && track->eType == tt_Cross ) { + // NOTE: tracing through crossroads currently poses risk of tracing through wrong segment + // as it's possible to be performerd before setting a route through the crossroads + // as a stop-gap measure we don't trace through crossroads which should be reasonable in most cases + // TODO: establish route before the scan, or a way for the function to know which route to pick + return start_dist; + } + else { + return GetDistanceToEvent( track, event, sd, start_dist, ++iter, 1 == krok ? true : false ); + } + } + else + { // obliczenie mojego toru + seg_len -= scan_dir > 0 ? dzielnik : -dzielnik; //trzeba wrócić do pozycji len1 + seg_len = scan_dir < 0 ? 1 - seg_len : seg_len; + seg_len = back ? 1 - seg_len : seg_len; // odwracamy jeśli idzie do tyłu + start_dist -= back ? segment->GetLength() : 0; + return start_dist + segment->GetLength() * seg_len; + } +}; +namespace +{ + + +// the low 4 bits of a number as a number -8..7, as the route of a crossing was read from the top of the flags +int signedNibble(unsigned const value) +{ + auto const nibble{static_cast(value & 0xf)}; + return nibble >= 8 ? nibble - 16 : nibble; +} + +} // namespace + +//--------------------------------------------------------------------------- + +void TController::TableClear() +{ // wyczyszczenie tablicy + sSpeedTable.clear(); + iLast = -1; + iTableDirection = 0; // nieznany + tLast = nullptr; + fLastVel = -1.0; + SemNextIndex = npos; + SemNextStopIndex = npos; + eSignSkip = nullptr; // nic nie pomijamy +}; + +std::vector TController::CheckTrackEvent( TTrack *Track, double const fDirection ) const +{ // sprawdzanie eventów na podanym torze do podstawowego skanowania + std::vector events; + auto const &eventsequence { ( fDirection > 0 ? Track->m_events2 : Track->m_events1 ) }; + for( auto const &event : eventsequence ) { + if( event.second != nullptr + && event.second->m_passive ) { + events.emplace_back( event.second ); + } + } + return events; +} + +bool TController::TableAddNew() +{ // zwiększenie użytej tabelki o jeden rekord + sSpeedTable.emplace_back(); // add a new slot + iLast = sSpeedTable.size() - 1; + return true; // false gdy się nałoży +}; + +bool TController::TableNotFound(basic_event const *Event, double const Distance ) const +{ // sprawdzenie, czy nie został już dodany do tabelki (np. podwójne W4 robi problemy) + auto lookup = + std::find_if( + sSpeedTable.begin(), + sSpeedTable.end(), + [Event]( TSpeedPos const &speedpoint ){ + return true == speedpoint.flags.HasAll(SpeedPointFlag::enabled | SpeedPointFlag::event) && speedpoint.evEvent == Event; } ); + + if (Global.iWriteLogEnabled & 8 + && lookup != sSpeedTable.end() ) { + WriteLog( "Speed table for " + OwnerName() + " already contains event " + lookup->evEvent->m_name ); + } + + // ignore duplicates which seem to be reasonably apart from each other, on account of looping tracks + // NOTE: since supplied distance is only rough approximation of distance to the event, we're using large safety margin + return lookup == sSpeedTable.end() || Distance - lookup->fDist > 100.0; +}; + +void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) +{ // skanowanie trajektorii na odległość (fDistance) od (pVehicle) w kierunku przodu składu i + // uzupełnianie tabelki + // WriteLog("Starting TableTraceRoute"); + + TTrack *pTrack{ nullptr }; // zaczynamy od ostatniego analizowanego toru + double fTrackLength{ 0.0 }; // długość aktualnego toru (krótsza dla pierwszego) + double fCurrentDistance{ 0.0 }; // aktualna przeskanowana długość + double fLastDir{ 0.0 }; + + if (iTableDirection != iDirection ) { + // jeśli zmiana kierunku, zaczynamy od toru ze wskazanym pojazdem + TableClear(); +/* + // aktualna prędkość // changed to -1 to recognize speed limit, if any + fLastVel = -1.0; + sSpeedTable.clear(); + iLast = -1; + tLast = nullptr; //żaden nie sprawdzony + SemNextIndex = npos; + SemNextStopIndex = npos; +*/ + if( VelSignalLast == 0.0 ) { + // don't allow potential red light overrun keep us from reversing + VelSignalLast = -1.0; + } + iTableDirection = iDirection; // ustalenie w jakim kierunku jest wypełniana tabelka względem pojazdu + pTrack = pVehicle->GetTrack(); // odcinek, na którym stoi + fTrackLength = pVehicle->RaTranslationGet(); // pozycja na tym torze (odległość od Point1) + fLastDir = pVehicle->DirectionGet() * pVehicle->RaDirectionGet(); // ustalenie kierunku skanowania na torze + if( fLastDir < 0.0 ) { + // jeśli w kierunku Point2 toru + fTrackLength = pTrack->Length() - fTrackLength; // przeskanowana zostanie odległość do Point2 + } + // account for the fact tracing begins from active axle, not the actual front of the vehicle + // NOTE: position of the couplers is modified by track offset, but the axles ain't, so we need to account for this as well + fTrackLength -= glm::length( + pVehicle->AxlePositionGet() + - pVehicle->RearPosition() + + pVehicle->VectorLeft() * pVehicle->MoverParameters->OffsetTrackH ); + // aktualna odległość ma być ujemna gdyż jesteśmy na końcu składu + fCurrentDistance = -fLength - fTrackLength; + fTrackLength = pTrack->Length(); //skasowanie zmian w zmiennej żeby poprawnie liczyło w dalszych krokach + MoveDistanceReset(); // AI startuje 1s po zaczęciu jazdy i mógł już coś przejechać + } + else { + if( iTableDirection == 0 ) { return; } + // NOTE: belt and braces; TablePurger() used to leave these pointing past the end of the table. + // nothing is known to do that any more, so say so when it happens + auto const dropstaleindex = [this, fDistance]( std::size_t &Index, std::string_view const Name ) { + if( Index == npos + || Index < sSpeedTable.size() ) { + return; + } + ErrorLog( std::format( + "Speed table for {}: {} {} points past the end of the table ({} records), last track {} at {:.1f} m, scan range {:.1f} m; reset", + OwnerName(), Name, Index, sSpeedTable.size(), + ( iLast >= 0 && sSpeedTable[ iLast ].trTrack != nullptr ? sSpeedTable[ iLast ].trTrack->name() : "none" ), + ( iLast >= 0 ? sSpeedTable[ iLast ].fDist : 0.0 ), fDistance ) ); + Index = npos; }; + dropstaleindex( SemNextIndex, "SemNextIndex" ); + dropstaleindex( SemNextStopIndex, "SemNextStopIndex" ); + // kontynuacja skanowania od ostatnio sprawdzonego toru (w ostatniej pozycji zawsze jest tor) + if( SemNextStopIndex != npos + && sSpeedTable[SemNextStopIndex].fVelNext == 0.0 ) { + // znaleziono semafor lub tarczę lub tor z prędkością zero, trzeba sprawdzić czy to nadał semafor + // jeśli jest następny semafor to sprawdzamy czy to on nadał zero + if( OrderCurrentGet() & DriverOrder::obeyTrain + && sSpeedTable[SemNextStopIndex].flags & SpeedPointFlag::signal ) { + return; + } + else { + if( false == OrderCurrentGet().HasAny(trainOrders) + && sSpeedTable[SemNextStopIndex].flags & (SpeedPointFlag::signal | SpeedPointFlag::shuntSignal | SpeedPointFlag::outsideStation) ) { + return; + } + } + } + + auto const &lastspeedpoint = sSpeedTable[ iLast ]; + pTrack = lastspeedpoint.trTrack; + assert( pTrack != nullptr ); + // flaga ustawiona, gdy Point2 toru jest blizej + fLastDir = lastspeedpoint.flags.HasAny(SpeedPointFlag::reverse) ? -1.0 : 1.0; + fCurrentDistance = lastspeedpoint.fDist; // aktualna odleglosc do jego Point1 + fTrackLength = pTrack->Length(); + } + + if( iTableDirection == 0 ) { + // don't bother + return; + } + + while (fCurrentDistance < fDistance) + { + if (pTrack != tLast) // ostatni zapisany w tabelce nie był jeszcze sprawdzony + { // jeśli tor nie był jeszcze sprawdzany + if( Global.iWriteLogEnabled & 8 ) { + WriteLog( "Speed table for " + OwnerName() + " tracing through track " + pTrack->name() ); + } + + auto const events { CheckTrackEvent( pTrack, fLastDir ) }; + for( auto *pEvent : events ) { + if( pEvent != nullptr && TableNotFound(pEvent, fCurrentDistance) ) // jeśli jest semafor na tym torze + { // trzeba sprawdzić tabelkę, bo dodawanie drugi raz tego samego przystanku nie jest korzystne + // jeśli nie ma + TableAddNew(); // zawsze jest true + + if (Global.iWriteLogEnabled & 8) + { + WriteLog("Speed table for " + OwnerName() + " found new event, " + pEvent->m_name); + } + auto &newspeedpoint = sSpeedTable[iLast]; + /* + if( newspeedpoint.Set( + pEvent, + fCurrentDistance + ProjectEventOnTrack( pEvent, pTrack, fLastDir ), + OrderCurrentGet() ) ) { + */ + // an order of a road junction or a level crossing lies on the lane it's on. it's measured along that lane: the search + // for the events beside the track goes in steps of about a metre, and misplaces the ones on lanes shorter than a few metres + auto const eventdistance{ + typeid( *pEvent ) == typeid( road_order ) ? + fCurrentDistance + ProjectEventOnTrack( pEvent, pTrack, fLastDir ) : + GetDistanceToEvent( pTrack, pEvent, fLastDir, fCurrentDistance ) }; + if (newspeedpoint.Set(pEvent, eventdistance, fLength, OrderCurrentGet(), mvOccupied->Vel < EU07_AI_NOMOVEMENT)) + { + + fDistance = newspeedpoint.fDist; // jeśli sygnał stop, to nie ma potrzeby dalej skanować + SemNextStopIndex = iLast; + if (SemNextIndex == npos) + { + SemNextIndex = iLast; + } + if (Global.iWriteLogEnabled & 8) + { + WriteLog("(stop signal from " + (SemNextStopIndex != npos ? sSpeedTable[SemNextStopIndex].GetName() : "unknown semaphor") + ")"); + } + } + else + { + if (true == newspeedpoint.IsProperSemaphor(OrderCurrentGet()) && SemNextIndex == npos) + { + SemNextIndex = iLast; // sprawdzamy czy pierwszy na drodze + } + if (Global.iWriteLogEnabled & 8) + { + WriteLog("(forward signal for " + (SemNextIndex != npos ? sSpeedTable[SemNextIndex].GetName() : "unknown semaphor") + ")"); + } + } + } + } // event dodajemy najpierw, żeby móc sprawdzić, czy tor został dodany po odczytaniu prędkości następnego + + if( pTrack->VelocityGet() == 0.0 // zatrzymanie + || pTrack->iAction // jeśli tor ma własności istotne dla skanowania + || pTrack->VelocityGet() != fLastVel ) // następuje zmiana prędkości + { // odcinek dodajemy do tabelki, gdy jest istotny dla ruchu + TableAddNew(); + sSpeedTable[ iLast ].Set( + pTrack, fCurrentDistance, + fLastDir < 0 ? SpeedPointFlag::enabled | SpeedPointFlag::reverse : SpeedPointFlag::enabled ); // dodanie odcinka do tabelki z flagą kierunku wejścia + if (pTrack->eType == tt_Cross) { + // na skrzyżowaniach trzeba wybrać segment, po którym pojedzie pojazd + // dopiero tutaj jest ustalany kierunek segmentu na skrzyżowaniu +/* + // NOTE: manual selection disabled due to multiplayer + int routewanted; + if( false == AIControllFlag ) { + routewanted = ( + input::keys[ GLFW_KEY_LEFT ] != GLFW_RELEASE ? 1 : + input::keys[ GLFW_KEY_RIGHT ] != GLFW_RELEASE ? 2 : + 3 ); + } + else { + routewanted = 1 + std::floor( Random( static_cast( pTrack->RouteCount() ) - 0.001 ) ); + } +*/ + auto const routewanted { pTrack->RouteDraw() }; + sSpeedTable[iLast].crossRoute = signedNibble( ( static_cast( sSpeedTable[iLast].crossRoute ) | static_cast( pTrack->CrossSegment(fLastDir < 0 ? tLast->iPrevDirection : tLast->iNextDirection, + /* + iRouteWanted ) + */ + routewanted) ) ) & 0xf ); // ostatnie 4 bity pola flag + sSpeedTable[iLast].flags = sSpeedTable[iLast].flags.Without(SpeedPointFlag::reverse); // usunięcie flagi kierunku, bo może być błędna + if (sSpeedTable[iLast].crossRoute < 0) { + sSpeedTable[iLast].flags |= SpeedPointFlag::reverse; // ustawienie flagi kierunku na podstawie wybranego segmentu + } + if (int(fLastDir) * sSpeedTable[iLast].LegacyFlagsValue() < 0) { + fLastDir = -fLastDir; + } +/* + if (AIControllFlag) { + // dla AI na razie losujemy kierunek na kolejnym skrzyżowaniu + iRouteWanted = 1 + Random(3); + } +*/ + } + } + else if ( (pTrack->fRadius != 0.0 // odległość na łuku lepiej aproksymować cięciwami + || tLast != nullptr && tLast->fRadius != 0.0) && + TableAddNew()) // koniec łuku też jest istotny + { // albo dla liczenia odległości przy pomocy cięciw - te usuwać po przejechaniu + // dodanie odcinka do tabelki + sSpeedTable[iLast].Set(pTrack, fCurrentDistance, fLastDir < 0 ? SpeedPointFlag::enabled | SpeedPointFlag::curve | SpeedPointFlag::reverse : SpeedPointFlag::enabled | SpeedPointFlag::curve); + } + } + + fCurrentDistance += fTrackLength; // doliczenie kolejnego odcinka do przeskanowanej długości + tLast = pTrack; // odhaczenie, że sprawdzony + fLastVel = pTrack->VelocityGet(); // prędkość na poprzednio sprawdzonym odcinku + pTrack = pTrack->Connected( + pTrack->eType == tt_Cross ? sSpeedTable[iLast].crossRoute : static_cast(fLastDir), + fLastDir); // może być NULL + + if (pTrack != nullptr ) + { // jeśli kolejny istnieje + if( tLast != nullptr && tLast->VelocityGet() > 0 && (tLast->VelocityGet() < pTrack->VelocityGet() || pTrack->VelocityGet() < 0) ) { + + if (iLast != -1 && sSpeedTable[iLast].trTrack == tLast) + { + // if the track is already in the table we only need to mark it as relevant + sSpeedTable[iLast].flags |= SpeedPointFlag::enabled; + } + else + { + // otherwise add it + TableAddNew(); + sSpeedTable[iLast].Set(tLast, + fCurrentDistance - fTrackLength, // by now the current distance points to beginning of next track + (fLastDir > 0 ? pTrack->iPrevDirection : pTrack->iNextDirection) ? SpeedPointFlag::enabled : SpeedPointFlag::enabled | SpeedPointFlag::reverse); + } + } + // zwiększenie skanowanej odległości tylko jeśli istnieje dalszy tor + fTrackLength = pTrack->Length(); + } + else + { // definitywny koniec skanowania, chyba że dalej puszczamy samochód po gruncie... + if( iLast == -1 + || ( false == sSpeedTable[iLast].flags.HasAll(SpeedPointFlag::enabled | SpeedPointFlag::trackEnd) + && sSpeedTable[iLast].trTrack != tLast ) ) { + // only if we haven't already marked end of the track and if the new track doesn't duplicate last one + if( TableAddNew() ) { + // zapisanie ostatniego sprawdzonego toru + sSpeedTable[iLast].Set( + tLast, fCurrentDistance - fTrackLength, // by now the current distance points to beginning of next track, + fLastDir < 0 ? SpeedPointFlag::enabled | SpeedPointFlag::trackEnd | SpeedPointFlag::reverse : SpeedPointFlag::enabled | SpeedPointFlag::trackEnd); + } + } + else if( sSpeedTable[iLast].trTrack == tLast && false == TestFlag(sSpeedTable[iLast].trTrack->iCategoryFlag, 0x100) ) { + // otherwise just mark the last added track as the final one + // TODO: investigate exactly how we can wind up not marking the last existing track as actual end + // don't mark portals, as these aren't exactly track ends, but teleport devices + sSpeedTable[iLast].flags |= SpeedPointFlag::enabled | SpeedPointFlag::trackEnd; + } + // to ostatnia pozycja, bo NULL nic nie da, a może się podpiąć obrotnica, czy jakieś transportery + return; + } + } + if( TableAddNew() ) { + // zapisanie ostatniego sprawdzonego toru + sSpeedTable[ iLast ].Set( + pTrack, fCurrentDistance, + fLastDir < 0 ? SpeedPointFlag::none | SpeedPointFlag::reverse : SpeedPointFlag::none ); + } +}; + +void TController::TableCheck(double fDistance) +{ // przeliczenie odległości w tabelce, ewentualnie doskanowanie (bez analizy prędkości itp.) + if( iTableDirection != iDirection ) { + // jak zmiana kierunku, to skanujemy od końca składu + TableTraceRoute( fDistance, pVehicles[ end::rear ] ); + TableSort(); + } + else if (iTableDirection) + { // trzeba sprawdzić, czy coś się zmieniło + auto const distance = MoveDistanceGet(); + for (auto &sp : sSpeedTable) { + // aktualizacja odległości dla wszystkich pozycji tabeli + sp.UpdateDistance(distance); + } + MoveDistanceReset(); // kasowanie odległości po aktualizacji tabelki + for( int i = 0; i < iLast; ++i ) + { // aktualizacja rekordów z wyjątkiem ostatniego + if (sSpeedTable[i].flags & SpeedPointFlag::enabled) // jeśli pozycja istotna + { + auto const passedbefore { sSpeedTable[ i ].flags.HasAll(SpeedPointFlag::elapsed) }; + if (sSpeedTable[i].Update()) + { + if( Global.iWriteLogEnabled & 8 ) { + WriteLog( "Speed table for " + OwnerName() + " detected switch change at " + sSpeedTable[ i ].trTrack->name() + " (generating fresh trace)" ); + } + // usuwamy wszystko za tym torem + while (sSpeedTable.back().trTrack != sSpeedTable[i].trTrack) + { // usuwamy wszystko dopóki nie trafimy na tą zwrotnicę + sSpeedTable.pop_back(); + --iLast; + } + // a semaphor recorded beyond the switch went away with the discarded entries + if( SemNextIndex != npos + && SemNextIndex >= sSpeedTable.size() ) { + SemNextIndex = npos; + } + if( SemNextStopIndex != npos + && SemNextStopIndex >= sSpeedTable.size() ) { + SemNextStopIndex = npos; + } + tLast = sSpeedTable[ i ].trTrack; + TableTraceRoute( fDistance, pVehicles[ end::rear ] ); + TableSort(); + // nie kontynuujemy pętli, trzeba doskanować ciąg dalszy + break; + } + // a switch is a track, the update of a signal never ends the loop above + CheckSignalPassed( sSpeedTable[ i ], passedbefore ); + if (sSpeedTable[i].flags & SpeedPointFlag::track) // jeśli odcinek + { + if( sSpeedTable[ i ].fDist + sSpeedTable[ i ].trTrack->Length() < -fLength ) // a skład wyjechał całą długością poza + { // degradacja pozycji + sSpeedTable[i].flags = sSpeedTable[i].flags.Without(SpeedPointFlag::enabled); // nie liczy się + } + else if( sSpeedTable[i].crossRoute == 0 && ( sSpeedTable[i].flags & ( SpeedPointFlag::elapsed | SpeedPointFlag::switchTrack ) ) == SpeedPointFlag::elapsed && sSpeedTable[i].fVelNext < 0 ) { + // jest z tyłu (najechany) i nie jest zwrotnicą ani skrzyżowaniem + // a nie ma ograniczenia prędkości + sSpeedTable[i].ResetFlags(); // to nie ma go po co trzymać (odtykacz usunie ze środka) + } + } + else if (sSpeedTable[i].flags & SpeedPointFlag::event && false == sSpeedTable[i].flags.HasAny(SpeedPointFlag::pointSpeed) && sSpeedTable[i].fDist < (typeid(*sSpeedTable[i].evEvent) == typeid(putvalues_event) ? -fLength : 0) && mvOccupied->CategoryFlag == 2 && + sSpeedTable[i].fDist < -0.75) // jeśli event + { + // jeśli jest z tyłu + // pociąg staje zawsze, a samochód tylko jeśli nie przejedzie całą długością (może być zaskoczony zmianą) + // WriteLog("TableCheck: Event is behind. Delete from table: " + sSpeedTable[i].evEvent->asName); + sSpeedTable[i].flags = sSpeedTable[i].flags.Without(SpeedPointFlag::enabled); // degradacja pozycji dla samochodu; + // semafory usuwane tylko przy sprawdzaniu, bo wysyłają komendy + } + } + } + auto const lastpassedbefore { sSpeedTable[ iLast ].flags.HasAll(SpeedPointFlag::elapsed) }; + sSpeedTable[iLast].Update(); // aktualizacja ostatniego + // a signal at stop often is the last, the scan doesn't go past it + CheckSignalPassed( sSpeedTable[ iLast ], lastpassedbefore ); + // WriteLog("TableCheck: Upate last track. Dist=" + AnsiString(sSpeedTable[iLast].fDist)); + if( sSpeedTable[ iLast ].fDist < fDistance ) { + TableTraceRoute( fDistance, pVehicles[ end::rear ] ); // doskanowanie dalszego odcinka + TableSort(); + } + // garbage collection + TablePurger(); + } +}; +namespace +{ + + +// the position is a signal showing stop (SetVelocity 0 0). SetVelocity 0 x on automatic block isn't: it may be passed after a stop +bool is_signal_at_stop( TSpeedPos const &Point ) +{ + return Point.flags.HasAll(SpeedPointFlag::event) + && Point.flags.HasAll(SpeedPointFlag::signal) + && false == Point.flags.HasAll(SpeedPointFlag::stopOnAutomaticBlock) + && std::abs( Point.fVelNext ) <= 0.0 + && Point.evEvent != nullptr; +} + +// the position is a signal, a main or a shunting one: the aspect comes from its memory cell. putvalues events +// set speed limits by the track, and the flags they get don't make them signals +bool is_signal( TSpeedPos const &Point ) +{ + return Point.flags.HasAll(SpeedPointFlag::event) + && ( Point.flags.HasAll(SpeedPointFlag::signal) || Point.flags.HasAll(SpeedPointFlag::shuntSignal) ) + && Point.evEvent != nullptr + && typeid( *Point.evEvent ) == typeid( getvalues_event ); +} + +std::uint8_t passing_flags_of( TSpeedPos const &Point, double const Speedatsignal, bool const Trainmovement ) +{ + std::uint8_t flags { 0 }; + auto const shunting { Point.flags.HasAll(SpeedPointFlag::shuntSignal) }; + if( shunting ) { + flags |= blackbox::passing_flags::shunt; + } + // the speeds of the aspects are whole km/h, -1 for no limit; a shunting signal binds only the shunting + if( std::abs( Speedatsignal ) < 0.5 && ( false == shunting || false == Trainmovement ) ) { + flags |= ( Point.flags.HasAll(SpeedPointFlag::stopOnAutomaticBlock) ? blackbox::passing_flags::automatic_block : blackbox::passing_flags::at_stop ); + } + return flags; +} + +} // namespace + +void TController::CheckSignalPassed( TSpeedPos const &Point, bool const Passedbefore ) const +{ + // not bSeenAhead: found already behind the head, the train stood across it or past it, it didn't pass it + if( false == signal_passing::passed_now( Passedbefore, Point.flags.HasAll(SpeedPointFlag::elapsed), Point.bSeenAhead ) + || ( mvOccupied->CategoryFlag & 1 ) == 0 ) { // railway only + return; + } + if( is_signal_at_stop( Point ) ) { + simulation::test().signal_passed_at_danger( OwnerName(), Point.evEvent->m_name ); + } + if( is_signal( Point ) ) { + // the aspect the train had of it: the table keeps it once the signal is behind, while the memory cell + // may already show stop for the train itself, past the signal on the track it guards. the stop of an + // automatic block signal is kept as the speed allowed after it, with a flag of its own + auto const speedatsignal { Point.flags.HasAll(SpeedPointFlag::stopOnAutomaticBlock) ? 0.0 : Point.fVelNext }; + simulation::Blackbox.signal_passed( + pVehicles[ end::front ], *Point.evEvent, + speedatsignal, Point.evEvent->input_value( 2 ), + mvOccupied->Vel, -Point.fDist, + passing_flags_of( Point, speedatsignal, false == OrderCurrentGet().HasAny( DriverOrder::shunt | DriverOrder::looseShunt ) ) ); + } +} + +// the margins of the final approach of a train [m], closer than the first of which it stops at once and within the +// second of which it makes its final approach: at a passenger stop, or at a signal and anything else it stops at +std::pair +TController::train_proximity_margins( bool const Passengerstop ) const { + + auto minproximity { 0.0 }; + auto maxproximity { 0.0 }; + if( Passengerstop ) { + // a stop point keeps the margins its W4 parameters (head or middle of the consist, + // platform length) were set up against + minproximity = std::clamp( 5 + iVehicles, 10, 15 ) + ( IsCargoTrain ? 10.0 : 0.0 ); + maxproximity = std::clamp( 10 + iVehicles, 15, 40 ); + } + else { + // a train stops 8-15 m short of the signal whatever its length; closer than the lower + // edge it stops at once, the braking aims at the middle of the window, 3.5 m further out + minproximity = 8.0; + // the final approach begins far enough out to slow from the coasting speed down to the window, + // and at the same distance whether the train is moving or standing, so it does not flip + // between creeping closer and holding still when it comes to a stand short of the window + maxproximity = 50.0; + } + if( IsCargoTrain ) { + // start the final approach earlier for cargo trains, their brakes react more slowly + maxproximity += 10.0; + } + if( ( Global.FrictionWeatherFactor < 1.f ) + && ( iVehicles > 1 ) ) { + // take into account weather conditions + minproximity += 5.0; + maxproximity += 5.0; + } + if( mvOccupied->Vel < 0.1 ) { + // jak stanie za daleko, to niech nie dociąga paru metrów + maxproximity = std::max( maxproximity, 50.0 ); + } + return { minproximity, maxproximity }; +} diff --git a/vehicle/ai/situation.cpp b/vehicle/ai/situation.cpp new file mode 100644 index 000000000..06cab6d70 --- /dev/null +++ b/vehicle/ai/situation.cpp @@ -0,0 +1,730 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// what the driver sees and keeps an eye on: the consist, the braking distance, the pantographs, the lights, the horns + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/mover.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + +double const deltalog = 0.05; // przyrost czasu + +void +TController::update_timers( double dt ) { + + ElapsedTime += dt; + WaitingTime += dt; + fBrakeTime -= dt; // wpisana wartość jest zmniejszana do 0, gdy ujemna należy zmienić nastawę hamulca + fBrakeHeldTime += dt; + if( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_FS ) ) { + // brake charging timeout starts after charging ends + BrakeChargingCooldown += dt; + } + fStopTime += dt; // zliczanie czasu postoju, nie ruszy dopóki ujemne + fActionTime += dt; // czas używany przy regulacji prędkości i zamykaniu drzwi + LastReactionTime += dt; + if( mvOccupied->Vel < 0.05 + && OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank) ) { + IdleTime += dt; + } + else { + IdleTime = 0.0; + } + fWarningDuration -= dt; // horn activation while the value is positive +} + +void +TController::update_logs( double const dt ) { + // log vehicle data + if( false == writes_physicslog() ) { + // not counted while it isn't logged (the driver of a road vehicle, or no logs on): were the logs turned on, + // it would write a line every 0.05 s from then on, not one each update to make up for the time before + LastUpdatedTime = 0.0; + return; + } + LastUpdatedTime += dt; + if( LastUpdatedTime > deltalog ) { + // zapis do pliku DAT + if( false == PhysicsLogBegun ) { + begin_physicslog(); + } + PhysicsLog(); + LastUpdatedTime -= deltalog; + } +} + +void +TController::control_wheelslip() { + // a start that has slipped once keeps the sand on until the train is under way. with the sand off as soon as the + // wheels grip again, the next notch slips again, and a heavy train on poor rails slips, grips and snatches over + // and over, and may never get going (#187). a vehicle without sand starts as before + auto const velocity { std::abs( mvOccupied->Vel ) }; + if( mvControlling->SlippingWheels + && velocity < EU07_AI_SANDEDSTARTVELOCITY + && false == mvControlling->IsMainCtrlNoPowerPos() + && mvControlling->Sand > 0.0 ) { + bSandedStart = true; + } + else if( velocity >= EU07_AI_SANDEDSTARTVELOCITY + || ( velocity < EU07_AI_NOMOVEMENT && VelDesired == 0.0 ) ) { + bSandedStart = false; + } + // wheel slip + if( mvControlling->SlippingWheels ) { + cue_action( driver_hint::sandingon ); // piasku! + if( false == bSandedStart ) { + cue_action( driver_hint::tractiveforcedecrease ); + cue_action( driver_hint::antislip ); + } + else if( ElapsedTime - fSandedStartDecreaseTime >= 1.0 ) { + // starting, a step down at a time, and no anti-slip brake: taking the power off at once and braking the + // locomotive brings a heavy train that has just got moving to a stand again, and the start begins anew + cue_action( driver_hint::tractiveforcedecrease ); + fSandedStartDecreaseTime = ElapsedTime; + } + cue_action( driver_hint::brakingforcedecrease ); + ++iDriverFailCount; + } + else if( ( std::fabs( mvControlling->Im ) > 0.75 * mvControlling->ImaxHi ) + || ( bSandedStart && false == mvControlling->IsMainCtrlNoPowerPos() ) ) { + cue_action( driver_hint::sandingon ); // piaskujemy tory, coby się nie ślizgać + } + else { + // deactivate sandbox if we aren't slipping + if( mvControlling->SandDose ) { + cue_action( driver_hint::sandingoff ); + } + } +} + +void +TController::control_pantographs() { + + if( mvPantographUnit->EnginePowerSource.SourceType != TPowerSource::CurrentCollector ) { return; } + + if( false == mvPantographUnit->PantAutoValve + && mvOccupied->ScndPipePress > 4.3 ) { + // gdy główna sprężarka bezpiecznie nabije ciśnienie to można przestawić kurek na zasilanie pantografów z głównej pneumatyki + cue_action( driver_hint::pantographairsourcesetmain ); + } + + // uśrednione napięcie sieci: przy spadku poniżej wartości minimalnej opóźnić rozruch o losowy czas + fVoltage = 0.5 * (fVoltage + std::max( mvControlling->GetTrainsetHighVoltage(), mvControlling->PantographVoltage ) ); + if( fVoltage < mvControlling->EnginePowerSource.CollectorParameters.MinV && fActionTime >= PrepareTime ) { + // gdy rozłączenie WS z powodu niskiego napięcia + // jeśli czas oczekiwania nie został ustawiony, losowy czas oczekiwania przed ponownym załączeniem jazdy + fActionTime = -2.0 - Random(10); + } + + // the pantograph setup the .fiz suggests for shunting (AI: ShuntPantstate=, eu07/maszyna#461), 0 when there's none + // or the vehicle isn't shunting + auto const shuntpantographsetup { + OrderCurrentGet().HasAny( DriverOrder::shunt | DriverOrder::looseShunt ) ? + mvOccupied->AIHintShuntPantstate : + 0 }; + + // raise/lower pantographs as needed + auto const useregularpantographlayout { + pVehicle->Next(Coupling::control) == nullptr // standalone + || is_emu() // special case + || mvControlling->TrainType == train_type::et41 }; // special case + + if( mvOccupied->Vel > EU07_AI_NOMOVEMENT ) { + + if( fOverhead2 >= 0.0 || iOverheadZero ) { + // jeśli jazda bezprądowa albo z opuszczonym pantografem + cue_action( driver_hint::mastercontrollersetzerospeed ); + } + + if( fOverhead2 > 0.0 || iOverheadDown ) { + // jazda z opuszczonymi pantografami + if( mvPantographUnit->Pantographs[ end::front ].is_active ) { + cue_action( driver_hint::frontpantographvalveoff ); + } + if( mvPantographUnit->Pantographs[ end::rear ].is_active ) { + cue_action( driver_hint::rearpantographvalveoff ); + } + } + else { + // jeśli nie trzeba opuszczać pantografów + // TODO: check if faction alone reduces frequency enough + if( fActionTime > 0.0 ) { + if( shuntpantographsetup != 0 ) { + // shunting with the pantograph setup the .fiz suggests for it + control_pantographs_setup( shuntpantographsetup ); + } + else if( mvOccupied->AIHintPantstate == 0 ) { + // jazda na tylnym + if( iDirection >= 0 && useregularpantographlayout ) { + // jak jedzie w kierunku sprzęgu 0 + if( mvPantographUnit->PantRearVolt == 0.0 + // filter out cases with single _other_ working pantograph so we don't try to raise something we can't + && ( mvPantographUnit->PantographVoltage == 0.0 + || mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 1 ) ) { + cue_action( driver_hint::rearpantographvalveon ); + } + } + else { + // jak jedzie w kierunku sprzęgu 0 + if( mvPantographUnit->PantFrontVolt == 0.0 + // filter out cases with single _other_ working pantograph so we don't try to raise something we can't + && ( mvPantographUnit->PantographVoltage == 0.0 + || mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 1 ) ) { + cue_action( driver_hint::frontpantographvalveon ); + } + } + + if( mvOccupied->Vel > 5 && mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 1 ) { + // opuszczenie przedniego po rozpędzeniu się o ile jest więcej niż jeden + if (iDirection >= 0 && useregularpantographlayout) // jak jedzie w kierunku sprzęgu 0 + { // poczekać na podniesienie tylnego + if (mvPantographUnit->PantFrontVolt != 0.0 && mvPantographUnit->PantRearVolt != 0.0) + { // czy jest napięcie zasilające na tylnym? + cue_action(driver_hint::frontpantographvalveoff); // opuszcza od sprzęgu 0 + } + } + else + { // poczekać na podniesienie przedniego + if (mvPantographUnit->PantRearVolt != 0.0 && mvPantographUnit->PantFrontVolt != 0.0) + { // czy jest napięcie zasilające na przednim? + cue_action(driver_hint::rearpantographvalveoff); // opuszcza od sprzęgu 1 + } + } + } + + } + else { + // use suggested pantograph setup + if( mvOccupied->Vel > 5 ) { + auto const pantographsetup{ mvOccupied->AIHintPantstate }; + cue_action( + pantographsetup & 1 << 0 ? driver_hint::frontpantographvalveon : driver_hint::frontpantographvalveoff ); + cue_action( + pantographsetup & 1 << 1 ? driver_hint::rearpantographvalveon : driver_hint::rearpantographvalveoff ); + } + } + } + } + } + else if( shuntpantographsetup != 0 ) { + // shunting with the suggested setup, also while standing, and without raising more pantographs when idling + if( fOverhead2 <= 0.0 && iOverheadDown == 0 ) { + control_pantographs_setup( shuntpantographsetup ); + } + } + else { + if( !mvOccupied->AIHintPantUpIfIdle || IdleTime <= 45.0 || std::abs(fStopTime) <= 15.0 || mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo <= 1 ) + { + } + else + { + // spending a longer at a stop, raise also front pantograph + if (iDirection >= 0 && useregularpantographlayout) + { + // jak jedzie w kierunku sprzęgu 0 + if (mvPantographUnit->PantFrontVolt == 0.0) + { + cue_action(driver_hint::frontpantographvalveon, 5); // discard the hint if speed exceeds 5 km/h + } + } + else + { + if (mvPantographUnit->PantRearVolt == 0.0) + { + cue_action(driver_hint::rearpantographvalveon, 5); // discard the hint if speed exceeds 5 km/h + } + } + } + } +} + +// raises the pantographs of the suggested setup (bit 0: front, bit 1: rear) and lowers the others, these only once +// a pantograph of the setup collects the voltage, so the vehicle doesn't lose its power on the way +void +TController::control_pantographs_setup( int const Setup ) { + + auto const front { ( Setup & 1 << 0 ) != 0 }; + auto const rear { ( Setup & 1 << 1 ) != 0 }; + if( front ) { + cue_action( driver_hint::frontpantographvalveon ); + } + if( rear ) { + cue_action( driver_hint::rearpantographvalveon ); + } + if( auto const setuplive { ( front && mvPantographUnit->PantFrontVolt != 0.0 ) || ( rear && mvPantographUnit->PantRearVolt != 0.0 ) }; + false == setuplive ) { + return; + } + if( false == front ) { + cue_action( driver_hint::frontpantographvalveoff ); + } + if( false == rear ) { + cue_action( driver_hint::rearpantographvalveoff ); + } +} + +void +TController::control_horns( double const Timedelta ) { + // horn control + if( fWarningDuration > 0.0 ) { + // jeśli pozostało coś do wytrąbienia trąbienie trwa nadal + if( mvOccupied->WarningSignal == 0 ) { + cue_action( driver_hint::hornon, 1 ); // low tone horn by default + } + } + else { + if( mvOccupied->WarningSignal != 0 ) { + cue_action( driver_hint::hornoff ); // a tu się kończy + } + } + if( mvOccupied->Vel > EU07_AI_MOVEMENT ) { + // jesli jedzie, można odblokować trąbienie, bo się wtedy nie włączy + drivingFlags.startHornDone = false; // zatrąbi dopiero jak następnym razem stanie + drivingFlags.startHorn = true; // i trąbić przed następnym ruszeniem + } + + if( true == drivingFlags.startHornNow + && true == Ready + && true == iEngineActive + && mvControlling->MainCtrlPowerPos() > 0 ) { + // uruchomienie trąbienia przed ruszeniem + fWarningDuration = 0.3; // czas trąbienia + cue_action( driver_hint::hornon, pVehicle->iHornWarning ); // wysokość tonu (2=wysoki) + drivingFlags.startHornDone = true; // nie trąbić aż do ruszenia + drivingFlags.startHornNow = false; // trąbienie zostało zorganizowane + } +} + +void +TController::control_security_system( double const Timedelta ) { + if( mvOccupied->SecuritySystem.is_cabsignal_blinking() && mvOccupied->SecuritySystem.has_separate_acknowledge()) { + // jak zadziałało SHP + if( false == is_emu() + && mvOccupied->DirActive == 0 ) { + cue_action( driver_hint::directionforward ); + } + cue_action( driver_hint::shpsystemreset ); // to skasuj + if( BrakeCtrlPosition == 0 // TODO: verify whether it's 0 in all vehicle types + && AccDesired > 0.0 + && mvOccupied->SecuritySystem.is_braking() ) { + cue_action( driver_hint::trainbrakerelease ); + } + } + + if( mvOccupied->SecuritySystem.is_blinking() ) { + // jak zadziałało CA/SHP + if( false == is_emu() + && mvOccupied->DirActive == 0 ) { + cue_action( driver_hint::directionforward ); + } + cue_action( driver_hint::securitysystemreset ); // to skasuj + if( BrakeCtrlPosition == 0 // TODO: verify whether it's 0 in all vehicle types + && AccDesired > 0.0 + && mvOccupied->SecuritySystem.is_braking() ) { + cue_action( driver_hint::trainbrakerelease ); + } + } + // basic emergency stop handling, while at it + if( true == mvOccupied->RadioStopFlag // radio-stop + && mvOccupied->Vel < 0.01 // and actual stop + && true == mvOccupied->Radio ) { // and we didn't touch the radio yet + // turning off the radio should reset the flag, during security system check + if( m_radiocontroltime > 5.0 ) { // arbitrary delay between stop and disabling the radio + cue_action( driver_hint::radiooff ); + } + else { + m_radiocontroltime += Timedelta; + } + } + if( iEngineActive + && ( false == mvOccupied->Radio || false == mvOccupied->RadioFuse ) + && false == mvOccupied->RadioStopFlag ) { + // otherwise if it's safe to do so, turn the radio back on + // arbitrary 5 sec delay before switching radio back on + m_radiocontroltime = std::min( m_radiocontroltime, 5.0 ); + if( m_radiocontroltime < 0.0 ) { + // hint at whichever of the two is open, the radio's switch or the cut-off in its power supply + if( false == mvOccupied->RadioFuse ) { + cue_action( driver_hint::radiofuseon ); + } + if( false == mvOccupied->Radio ) { + cue_action( driver_hint::radioon ); + } + } + else { + m_radiocontroltime -= Timedelta; + } + } +} + +void +TController::control_handles() { + + switch( mvControlling->EngineType ) { + case TEngineType::ElectricSeriesMotor: { + // styczniki liniowe rozłączone yBARC + if( false == mvControlling->StLinFlag + && false == mvControlling->DelayCtrlFlag + && mvControlling->MainCtrlPowerPos() > 1 ) { + cue_action( driver_hint::mastercontrollersetzerospeed ); + } + // if the power station is heavily burdened drop down to series mode to reduce the load + auto const useseriesmodevoltage { + std::lerp( + mvControlling->EnginePowerSource.CollectorParameters.MinV, + mvControlling->EnginePowerSource.CollectorParameters.MaxV, + IsHeavyCargoTrain ? 0.35 : 0.40 ) }; + + if( fVoltage <= useseriesmodevoltage ) { + cue_action( driver_hint::mastercontrollersetseriesmode ); + } + // sanity check + if( false == Ready + && mvControlling->MainCtrlPowerPos() > 1 ) { + cue_action( driver_hint::mastercontrollersetzerospeed ); + } + break; + } + case TEngineType::DieselElectric: { + // styczniki liniowe rozłączone yBARC + if( false == mvControlling->StLinFlag + && false == mvControlling->DelayCtrlFlag + && mvControlling->MainCtrlPowerPos() > 1 ) { + cue_action( driver_hint::mastercontrollersetzerospeed ); + } + // sanity check + if( false == Ready + && mvControlling->MainCtrlPowerPos() > 1 ) { + cue_action( driver_hint::mastercontrollersetzerospeed ); + } + break; + } + default: { + break; + } } // enginetype +} + +// moves the light preset selector to the position matching the lights set directly by the AI, +// otherwise the next SetLights() call (e.g. from CheckVehicles()) reverts them to the untouched selector position +void +TController::sync_lights_selector() { + + if( mvOccupied->LightsPosNo <= 0 ) { return; } + + auto const *headvehicle { pVehicles[ end::front ] }; + if( headvehicle == nullptr ) { return; } + // same choice of the light table as in TDynamicObject::SetLights() + auto const lightstable { ( mvOccupied->CabOccupied * pVehicle->DirectionGet() >= 0 ? end::front : end::rear ) }; + // same choice of the lit vehicle end as in TDynamicObject::RaLightsSet() + auto const headend { ( headvehicle->iDirection > 0 ? end::front : end::rear ) }; + auto const position { handover::light_selector_position( + *mvOccupied, lightstable, headvehicle->MoverParameters->iLights[ headend ], headvehicle->LightList( headend ) ) }; + if( position == mvOccupied->LightsPos ) { return; } + + mvOccupied->LightsPos = position; + // visual feedback + auto *train { simulation::Trains.find( pVehicle->name() ) }; + if( train != nullptr ) { + train->ggLightsButton.PutValue( static_cast( position - 1 ) ); + } +} + +// re-applies the headlight dimmer state after the AI handed the vehicle over to the human driver, +// moving the dimmer out of the off position if it'd hide the head lights set by the AI +void +TController::sync_lights_dimmer() { + + if( mvOccupied->dimPositions.empty() ) { return; } + + auto const *headvehicle { pVehicles[ end::front ] }; + auto const headend { ( headvehicle != nullptr && headvehicle->iDirection > 0 ? end::front : end::rear ) }; + auto const headlightson { + headvehicle != nullptr + && ( headvehicle->MoverParameters->iLights[ headend ] & ( light::headlight_left | light::headlight_right | light::headlight_upper ) ) != 0 }; + + auto const position { handover::dimmer_position( *mvOccupied, headlightson ) }; + if( position != mvOccupied->modernDimmerPosition ) { + mvOccupied->modernDimmerPosition = position; + // visual feedback + auto *train { simulation::Trains.find( pVehicle->name() ) }; + if( train != nullptr ) { + train->ggModernLightDimSw.PutValue( static_cast( position ) ); + } + } + if( position < 0 || position >= static_cast( mvOccupied->dimPositions.size() ) ) { return; } // SetLightDimmings() doesn't check the range + pVehicle->SetLightDimmings(); +} + +// activate consist lamp codes +void +TController::control_lights() { + + if( is_train() ) { + // jeśli jazda pociągowa + if( true == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { + // head lights + if( m_lighthints[ end::front ] == -1 ) { + cue_action( driver_hint::headcodepc1 ); + } + else if( m_lighthints[ end::front ] == ( light::redmarker_left | light::headlight_right | light::headlight_upper ) ) { + cue_action( driver_hint::headcodepc2 ); + } + else { + // custom light pattern + if( AIControllFlag ) { + pVehicles[ end::front ]->RaLightsSet( m_lighthints[ end::front ], -1 ); + } + } + // tail lights + if( m_lighthints[ end::rear ] == -1 ) { + cue_action( driver_hint::headcodepc5 ); + } + else { + if( AIControllFlag ) { + pVehicles[ end::rear ]->RaLightsSet( -1, m_lighthints[ end::rear ] ); + } + } + } + // for shunting mode + else if( OrderCurrentGet() & ( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect ) ) { + cue_action( driver_hint::headcodetb1 ); + } + } + else if( is_car() ) { + Lights( + light::headlight_left | light::headlight_right, + light::redmarker_left | light::redmarker_right ); + } +} + +void +TController::control_compartment_lights() { + // compartment lights + if( mvOccupied->CompartmentLights.start_type != start_t::manual ) { return; } + + auto const currentlightstate { mvOccupied->CompartmentLights.is_enabled }; + auto const lightlevel { Global.fLuminance * ConsistShade }; + auto const desiredlightstate{ ( + currentlightstate ? + lightlevel < 0.40 : // turn off if lighting level goes above 0.4 + lightlevel < 0.35 ) }; // turn on if lighting level goes below 0.35 + if( desiredlightstate != currentlightstate ) { + cue_action( desiredlightstate ? driver_hint::consistlightson : driver_hint::consistlightsoff ); + } +} + +void +TController::UpdateCommand() { + + if( mvOccupied->CommandIn.Command != VehicleCommand::none && false == mvOccupied->RunInternalCommand() ) { + // rozpoznaj komende bo lokomotywa jej nie rozpoznaje + RecognizeCommand(); // samo czyta komendę wstawioną do pojazdu? + } +} + +void +TController::UpdateNextStop() { + + if( fLastStopExpDist > 0.0 + && mvOccupied->DistCounter > fLastStopExpDist ) { + // zaktualizować wyświetlanie rozkładu + TrainParams.StationStart = TrainParams.StationIndex; + fLastStopExpDist = -1.0; // usunąć licznik + if( true == m_makenextstopannouncement ) { + announce( announcement_t::next ); + m_makenextstopannouncement = false; // keep next stop announcements suppressed until another scheduled stop + } + } +} + +void +TController::determine_braking_distance() { + // przybliżona droga hamowania + // NOTE: we're ensuring some minimal braking distance to reduce ai flipping states between starting and braking + auto const velceil { std::max( 2.0, std::ceil( mvOccupied->Vel ) ) }; + fBrakeDist = fDriverBraking * velceil * ( 40.0 + velceil ); + if( fMass > 1000000.0 ) { + // korekta dla ciężkich, bo przeżynają - da to coś? + fBrakeDist *= 2.0; + } + if( -fAccThreshold > 0.05 + && mvOccupied->CategoryFlag == 1 ) { + fBrakeDist = velceil * velceil / 25.92 / -fAccThreshold; + } + if( mvOccupied->BrakeDelayFlag == bdelay_G ) { + // dla nastawienia G koniecznie należy wydłużyć drogę na czas reakcji + fBrakeDist += 2 * velceil; + } + if( mvOccupied->Vel > 15.0 + && mvControlling->EngineType == TEngineType::ElectricInductionMotor + && is_emu() ) { + // HACK: make the induction motor powered EMUs start braking slightly earlier + fBrakeDist += 10.0; + } +/* + // take into account effect of gravity (but to stay on safe side of calculations, only downhill) + if( fAccGravity > 0.025 ) { + fBrakeDist *= ( 1.0 + fAccGravity ); + // TBD: use version which shortens route going uphill, too + //fBrakeDist = std::max( fBrakeDist, fBrakeDist * ( 1.0 + fAccGravity ) ); + } +*/ +} + +void +TController::scan_route( double const Range ) { + + TableCheck( Range ); +} + +void +TController::determine_proximity_ranges() { + // ustalenie dystansów w pozostałych przypadkach + switch (SingleOrder(OrderCurrentGet())) + { + case DriverOrder::connect: { + // podłączanie do składu + if (drivingFlags.connect) { + // jeśli stanął już blisko, unikając zderzenia i można próbować podłączyć + fMinProximityDist = -1.0; + fMaxProximityDist = 0.0; //[m] dojechać maksymalnie + fVelPlus = 1.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania + fVelMinus = 0.5; // margines prędkości powodujący załączenie napędu + } + else { + // jak daleko, to jazda jak dla Shunt na kolizję + fMinProximityDist = 2.0; + fMaxProximityDist = 5.0; //[m] w takim przedziale odległości powinien stanąć + fVelPlus = 2.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania + fVelMinus = 1.0; // margines prędkości powodujący załączenie napędu + } + break; + } + case DriverOrder::disconnect: { + // 20.07.03 - manewrowanie wagonami + fMinProximityDist = 1.0; + fMaxProximityDist = 10.0; //[m] + fVelPlus = 1.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania + fVelMinus = 0.5; // margines prędkości powodujący załączenie napędu + break; + } + case DriverOrder::shunt: { + // na jaką odleglość i z jaką predkością ma podjechać + // TODO: test if we can use the distances calculation from obey_train + fMinProximityDist = std::min( 5 + iVehicles, 25 ); + fMaxProximityDist = std::min( 10 + iVehicles, 50 ); + // HACK: modern vehicles might brake slower at low speeds, increase safety margin as crude counter + if( mvControlling->EIMCtrlType > 0 ) { + fMinProximityDist += 5.0; + fMaxProximityDist += 5.0; + } + // take into account weather conditions + if (Global.FrictionWeatherFactor < 1.f + && iVehicles > 1 ) { + fMinProximityDist += 5.0; + fMaxProximityDist += 5.0; + } + fVelPlus = 2.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania + // margines prędkości powodujący załączenie napędu + // były problemy z jazdą np. 3km/h podczas ładowania wagonów + fVelMinus = std::min( 0.1 * fShuntVelocity, 3.0 ); + break; + } + case DriverOrder::looseShunt: { + fMinProximityDist = -1.0; + fMaxProximityDist = 0.0; //[m] dojechać maksymalnie + fVelPlus = 2.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania + fVelMinus = 0.5; // margines prędkości powodujący załączenie napędu + break; + } + case DriverOrder::obeyTrain: { + // na jaka odleglosc i z jaka predkoscia ma podjechac do przeszkody + // jeśli pociąg + if( is_train() ) { + auto const [ minproximity, maxproximity ] { train_proximity_margins( IsAtPassengerStop ) }; + fMinProximityDist = minproximity; + fMaxProximityDist = maxproximity; + + if( drivingFlags.late ) { + // jeśli spóźniony, to gna + fVelMinus = 1.0; + // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania + fVelPlus = 5.0; + } + else { + // gdy nie musi się sprężać + // margines prędkości powodujący załączenie napędu; min 1.0 żeby nie ruszał przy 0.1 + fVelMinus = std::clamp( std::round( 0.05 * VelDesired ), 1.0, 5.0 ); + // normalnie dopuszczalne przekroczenie to 5% prędkości ale nie więcej niż 5km/h + // bottom margin raised to 2 km/h to give the AI more leeway at low speed limits + fVelPlus = std::clamp( std::ceil( 0.05 * VelDesired ), 2.0, 5.0 ); + } + } + // samochod (sokista też) + else { + fMinProximityDist = std::max( 3.5, mvOccupied->Vel * 0.2 ); + fMaxProximityDist = std::max( 9.5, mvOccupied->Vel * 0.375 ); //[m] + if( Global.FrictionWeatherFactor < 1.f ) { + // take into account weather conditions + fMinProximityDist += 0.75; + fMaxProximityDist += 0.75; + } + // margines prędkości powodujący załączenie napędu + fVelMinus = 2.0; + // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania + fVelPlus = std::min( 10.0, mvOccupied->Vel * 0.1 ); + } + break; + } + case DriverOrder::bank: { + // TODO: implement + break; + } + default: { + fMinProximityDist = 5.0; + fMaxProximityDist = 10.0; //[m] + fVelPlus = 2.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania + fVelMinus = 5.0; // margines prędkości powodujący załączenie napędu + } + } // switch OrderList[OrderPos] +} diff --git a/vehicle/ai/speed.cpp b/vehicle/ai/speed.cpp new file mode 100644 index 000000000..84525a670 --- /dev/null +++ b/vehicle/ai/speed.cpp @@ -0,0 +1,907 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the speed the driver aims for + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/mover.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + +const double PassengetTrainAcceleration = 0.40; +const double HeavyPassengetTrainAcceleration = 0.20; +const double CargoTrainAcceleration = 0.25; +const double HeavyCargoTrainAcceleration = 0.10; + +// modifies brake distance for low target speeds, to ease braking rate in such situations +float +TController::braking_distance_multiplier( float const Targetvelocity ) const { + + auto const frictionmultiplier { 1.f / Global.FrictionWeatherFactor }; + + if( Targetvelocity > 65.f ) { return 1.f * frictionmultiplier; } + if( Targetvelocity < 5.f ) { + // HACK: engaged automatic transmission means extra/earlier braking effort is needed for the last leg before full stop + if( is_dmu() + && mvOccupied->Vel < 40.0 + && Targetvelocity == 0.f ) { + auto const multiplier { std::clamp( 1.f + iVehicles * 0.5f, 2.f, 4.f ) }; + return std::lerp(multiplier, 1.f, static_cast(mvOccupied->Vel / 40.0)) * frictionmultiplier; + } + // HACK: cargo trains or trains going downhill with high braking threshold need more distance to come to a full stop + if( fBrake_a0[1] > 0.2 + && ( true == IsCargoTrain + || fAccGravity > 0.025 ) ) { + return std::lerp(1.f, 2.f, std::clamp((fBrake_a0[1] - 0.2) / 0.2, 0.0, 1.0)) * frictionmultiplier; + } + + return 1.f * frictionmultiplier; + } + // stretch the braking distance up to 3 times; the lower the speed, the greater the stretch + return std::lerp(3.f, 1.f, (Targetvelocity - 5.f) / 60.f) * frictionmultiplier; +} + +double TController::ESMVelocity(bool Main) +{ + double fCurrentCoeff = 0.9; + double fFrictionCoeff = 0.85; + double ESMVel = 9999; + int MCPN = mvControlling->MainCtrlActualPos; + int SCPN = mvControlling->ScndCtrlActualPos; + if (Main) + MCPN += 1; + else + SCPN += 1; + if (mvControlling->RList[MCPN].ScndAct < 255 && mvControlling->ScndCtrlActualPos == 0) + SCPN = mvControlling->RList[MCPN].ScndAct; + double FrictionMax = mvControlling->Mass*9.81*mvControlling->Adhesive(mvControlling->RunningTrack.friction)*fFrictionCoeff; + double IF = mvControlling->Imax; + double MS = 0; + double Fmax = 0; + for (int i = 0; i < 5; i++) + { + MS = mvControlling->MomentumF(IF, IF, SCPN); + Fmax = MS * mvControlling->RList[MCPN].Bn * mvControlling->RList[MCPN].Mn * 2 / mvControlling->WheelDiameter * mvControlling->Transmision.Ratio; + if( Fmax != 0.0 ) { + IF = 0.5 * IF * ( 1 + FrictionMax / Fmax ); + } + else { + // NOTE: gets trimmed to actual highest acceptable value after the loop + IF = std::numeric_limits::max(); + break; + } + } + IF = std::min(IF, mvControlling->Imax*fCurrentCoeff); + double R = mvControlling->RList[MCPN].R + mvControlling->CircuitRes + mvControlling->RList[MCPN].Mn*mvControlling->WindingRes; + // SCPN may come from the .fiz (RList ScndAct) unchecked: read it with the bounds-safe accessor, as MomentumF() does + auto const &motorparam{mvControlling->motor_param(SCPN)}; + double pole = motorparam.fi * + std::max(abs(IF) / (abs(IF) + motorparam.Isat) - motorparam.fi0, 0.0); + double Us = abs(mvControlling->EngineVoltage) - IF*R; + double ns = std::max(0.0, Us / (pole*mvControlling->RList[MCPN].Mn)); + ESMVel = ns * mvControlling->WheelDiameter*M_PI*3.6/mvControlling->Transmision.Ratio; + return ESMVel; +} + +// the stages of uncoupling: each one sets the speed for the next +void +TController::set_velocity_for_uncoupling() { + + if( iVehicleCount < 0 ) { + // 4th stage: restore initial direction + if( drivingFlags.press ) { + SetVelocity( 0, 0, stopJoin ); + } + return; + } + // 3rd stage: compress buffers and uncouple + if( drivingFlags.press && iDirection == iDirectionOrder ) { + SetVelocity( 2, 0 ); // jazda w ustawionym kierunku z prędkością 2 + return; + } + // 1st stage: bring it to stop + // 2nd stage: apply consist brakes and change direction + SetVelocity( 0, 0, stopJoin ); +} + +// uphill, the gradient alone brings a slow train to a stand within metres, far sooner than a released +// brake applies; so the train brake goes on while the train is coming to a stand, stays on while it +// stands, and is applied for real if the train has started to roll back +void +TController::hold_train_coming_to_stand_uphill() { + + if( ( false == is_train() ) + || ( false == OrderCurrentGet().HasAny(DriverOrder::obeyTrain) ) + || ( VelNext != 0.0 ) + || ( ActualProximityDist > fMaxProximityDist ) + || ( fAccGravity >= EU07_AI_UPHILLGRAVITY ) ) { + return; + } + auto const vel { DirectionalVel() }; + if( std::abs( vel ) < EU07_AI_NOMOVEMENT ) { + VelDesired = 0.0; + AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION ); + return; + } + if( ( vel < 0.0 ) + || ( ( vel < 5.0 ) && ( AccDesired < 0.0 ) ) + // rolling to a stand on the gradient alone, the brake has to be on its way before the train stops: + // once the time left to the stand is no longer than half of what the brake takes to apply, apply it; any + // sooner and the brake takes off more of the distance than the stop was planned with + || ( ( BrakeSystem == TBrakeSystem::Pneumatic ) + // not for a train that is short of where it is to stop and is to pull up further + && ( AccDesired <= 0.0 ) + && ( vel / 3.6 / -fAccGravity <= 0.5 * brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) { + // the gradient alone already slows the train down nearly this much; ask for enough on top of it that + // the brake is applied for sure, not held back by the margin against small corrections + AccDesired = std::min( AccDesired, fAccGravity - std::max( 0.15, fBrake_a0[ 0 ] ) - brake_increase_margin() ); + } +} + +void +TController::pick_optimal_speed( double const Range ) { + +// if( false == OrderCurrentGet().HasAny( Shunt | Loose_shunt | Obey_train | Bank | Connect | Disconnect | Change_direction ) ) { return; } + + // set initial velocity and acceleration values + SetDriverPsyche(); // ustawia AccPreferred (potrzebne tu?) + VelDesired = fVelMax; // wstępnie prędkość maksymalna dla pojazdu(-ów), będzie następnie ograniczana + AccDesired = AccPreferred; // AccPreferred wynika z osobowości mechanika + + // nie przekraczać rozkladowej + if( OrderCurrentGet().HasAny(DriverOrder::obeyTrain) + && TrainParams.TTVmax > 0.0 ) { + VelDesired = + min_speed( + VelDesired, + TrainParams.TTVmax ); + } + +// VelNext = VelDesired; // maksymalna prędkość wynikająca z innych czynników niż trajektoria ruchu + // HACK: -1 means we can pick up 0 speed limits in ( point.velnext > velnext ) tests aimed to find highest next speed, + // but also doubles as 'max speed' in min_speed tests, so it shouldn't interfere if we don't find any speed limits + VelNext = -1.0; + + // basic velocity and acceleration adjustments + // jeśli manewry, to ograniczamy prędkość + if( false == OrderCurrentGet().HasAny( DriverOrder::obeyTrain | DriverOrder::bank ) ) { // spokojne manewry + SetVelocity( fShuntVelocity, fShuntVelocity ); + VelDesired = + min_speed( + VelDesired, + fShuntVelocity ); + } + // uncoupling mode changes velocity/acceleration between stages + if( OrderCurrentGet().HasAny(DriverOrder::disconnect) ) { + set_velocity_for_uncoupling(); + } + + VelLimitLastDist = { VelDesired, -1 }; + SwitchClearDist = -1; + ActualProximityDist = Range; // funkcja Update() może pozostawić wartości bez zmian + + // if we're idling bail out early + if( false == is_active() ) { + VelDesired = 0.0; + VelNext = 0.0; + AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION ); + return; + } + + // Ra: odczyt (ActualProximityDist), (VelNext) i (AccPreferred) z tabelki prędkosci + check_route_ahead( Range ); + + check_departure(); + + // if ordered to turn off the vehicle, try to stop + if( true == OrderCurrentGet().HasAll(DriverOrder::releaseEngine) ) { + SetVelocity( 0, 0, stopSleep ); + } + // if ordered to change direction, try to stop + if( true == OrderCurrentGet().HasAll(DriverOrder::changeDirection) ) { + SetVelocity( 0, 0, stopDir ); + } + + adjust_desired_speed_for_obstacles(); + adjust_desired_speed_for_limits(); + adjust_desired_speed_for_target_speed( Range ); + adjust_desired_speed_for_current_speed(); + adjust_desired_speed_for_braking_test(); + + // Ra 2F1I: wyłączyć kiedyś to uśrednianie i przeanalizować skanowanie, czemu migocze + if( AccDesired > EU07_AI_NOACCELERATION ) { // hamowania lepeiej nie uśredniać + AccDesired = fAccDesiredAv = + 0.2 * AccDesired + + 0.8 * fAccDesiredAv; // uśrednione, żeby ograniczyć migotanie + } + if( VelDesired == 0.0 ) { + // Ra 2F1J: jeszcze jedna prowizoryczna łatka + AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION ); + } + + // last step sanity check, until the whole calculation is straightened out + AccDesired = std::min( AccDesired, AccPreferred ); + AccDesired = std::clamp( + AccDesired, + is_car() ? -2.0 : -0.9, + is_car() ? 2.0 : 0.9 ); + + // done last, so that none of the adjustments above, made for a train moving forward, can undo it + hold_train_coming_to_stand_uphill(); + + // if the route ahead is blocked we might need to head the other way + check_route_behind( 1000 ); // NOTE: legacy scan range value +} + +void +TController::adjust_desired_speed_for_obstacles() { + // prędkość w kierunku jazdy, ujemna gdy jedzie w przeciwną stronę niż powinien + auto const vel { DirectionalVel() }; + + if (VelDesired < 0.0) + VelDesired = fVelMax; // bo VelDesired<0 oznacza prędkość maksymalną + + // Ra: jazda na widoczność + if( Obstacle.distance < 5000 ) { + // mamy coś z przodu + // prędkość pojazdu z przodu (zakładając, że jedzie w tę samą stronę!!!) + auto const k { Obstacle.vehicle->MoverParameters->Vel }; + + if( k - vel < 5 ) { + // porównanie modułów prędkości [km/h] + // zatroszczyć się trzeba, jeśli tamten nie jedzie znacząco szybciej + if( Obstacle.distance < ActualProximityDist ) { + // the vehicle ahead, not the stop found by the scan, is what the train is now to stop short of + bStopTargetIsPassengerStop = false; + } + ActualProximityDist = std::min( + ActualProximityDist, + Obstacle.distance ); + + if( Obstacle.distance <= ( + mvOccupied->CategoryFlag & 2 ? + 100.0 : // cars + 250.0 ) ) { // others + // regardless of driving mode at close distance take precaution measures: + // match the other vehicle's speed or slow down if the other vehicle is stopped + VelDesired = + min_speed( + VelDesired, + std::max( + k, + mvOccupied->CategoryFlag & 2 ? + 40.0 : // cars + 20.0 ) ); // others + if( vel > VelDesired + fVelPlus ) { + // if going too fast force some prompt braking + AccPreferred = std::min( + mvOccupied->CategoryFlag & 2 ? -0.65 : // cars + -0.30, // others + AccPreferred ); + } + } + + double const distance = Obstacle.distance - fMaxProximityDist - fBrakeDist * 1.15; // odległość bezpieczna zależy od prędkości + if( distance < 0.0 ) { + // jeśli odległość jest zbyt mała + if( k < 10.0 ) // k - prędkość tego z przodu + { // jeśli tamten porusza się z niewielką prędkością albo stoi + // keep speed difference within a safer margin + VelDesired = std::floor( + min_speed( + VelDesired, + Obstacle.distance > 100 ? k + 20.0 : std::min(8.0, k + 4.0) ) ); + + if( OrderCurrentGet().HasAny( DriverOrder::connect | DriverOrder::looseShunt ) ) { + // jeśli spinanie, to jechać dalej + AccPreferred = std::min( 0.35, AccPreferred ); // nie hamuj + VelNext = std::floor( std::min( 8.0, k + 2.0 ) ); // i pakuj się na tamtego + } + else { + // a normalnie to hamować + VelNext = 0.0; + if( Obstacle.distance <= fMinProximityDist ) { + VelDesired = 0.0; + } + + if( mvOccupied->CategoryFlag & 1 + && OrderCurrentGet() & DriverOrder::obeyTrain ) { + // trains which move normally should try to stop at safe margin + ActualProximityDist -= fDriverDist; + } + } + } + else { + // jeśli oba jadą, to przyhamuj lekko i ogranicz prędkość + if( Obstacle.distance < ( + mvOccupied->CategoryFlag & 2 ? + fMaxProximityDist + 0.5 * vel : // cars + 2.0 * fMaxProximityDist + 2.0 * vel ) ) { //others + // jak tamten jedzie wolniej a jest w drodze hamowania + AccPreferred = std::min( -0.9, AccPreferred ); + VelNext = min_speed( std::round( k ) - 5.0, VelDesired ); + if( Obstacle.distance <= ( + mvOccupied->CategoryFlag & 2 ? + fMaxProximityDist : // cars + 2.0 * fMaxProximityDist ) ) { //others + // try to force speed change if obstacle is really close + VelDesired = VelNext; + } + } + } + ReactionTime = mvOccupied->Vel > EU07_AI_NOMOVEMENT ? 0.1 : // orientuj się, bo jest goraco + 2.0; // we're already standing still, so take it easy + } + else { + if( OrderCurrentGet() & DriverOrder::connect ) { + // if there's something nearby in the connect mode don't speed up too much + VelDesired = + min_speed( + VelDesired, + Obstacle.distance > 100 ? 20.0 : 4.0 ); + } + } + } + } +} + +void +TController::adjust_desired_speed_for_limits() { + // speed caps checks + // sprawdzamy możliwe ograniczenia prędkości + if( VelSignal >= 0 ) { + // jeśli skład był zatrzymany na początku i teraz już może jechać + VelDesired = + min_speed( + VelDesired, + VelSignal ); + } + if( mvOccupied->RunningTrack.Velmax >= 0 ) { + // ograniczenie prędkości z trajektorii ruchu + VelDesired = + min_speed( + VelDesired, + mvOccupied->RunningTrack.Velmax ); // uwaga na ograniczenia szlakowej! + } + if( VelforDriver >= 0 ) { + // tu jest zero przy zmianie kierunku jazdy + // Ra: tu może być 40, jeśli mechanik nie ma znajomości szlaaku, albo kierowca jeździ 70 + VelDesired = + min_speed( + VelDesired, + VelforDriver ); + } + + // recalculate potential load exchange duration + check_load_exchange(); + if( ExchangeTime > 0 + || mvOccupied->Vel > 2.0 ) { // HACK: force timer reset if the load exchange is cancelled due to departure + WaitingSet( ExchangeTime ); + } + if( fStopTime < 0 ) { + VelDesired = 0.0; // jak ma czekać, to nie ma jazdy + cue_action( driver_hint::waitloadexchange ); + return; // speed limit can't get any lower + } + + if( OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank) && drivingFlags.stopHere && mvOccupied->Vel < 0.01 && VelSignalNext == 0.0 ) { + // w Connect nie, bo moveStopHere odnosi się do stanu po połączeniu + // jeśli ma czekać na wolną drogę, stoi a wyjazdu nie ma, to ma stać + VelDesired = 0.0; + return; // speed limit can't get any lower + } + + if( OrderCurrentGet() == DriverOrder::waitForOrders ) { + // wait means sit and wait + VelDesired = 0.0; + return; // speed limit can't get any lower + } +} + +// how long the present acceleration of a consist lasts whatever is done with the handle now: half the time +// its pneumatic brake takes to apply (while speeding up) or to release (while slowing down), which in G +// is tens of seconds; never shorter than the look-ahead the AI has always used +double +brake_response_horizon( TMoverParameters const *Vehicle, TBrakeSystem const Brakesystem, double const Acceleration, double const Brakea0 ) { + + auto horizon { ( 1.0 - Brakea0 ) * 30.0 / 3.6 }; + if( Brakesystem == TBrakeSystem::Pneumatic ) { + // BrakeDelay holds the release and the application time in G, then the same two in P + auto const delays { Vehicle->BrakeDelayFlag > bdelay_G ? 0 : 2 }; + auto const isrelease { Acceleration < 0.0 }; + horizon = std::max( horizon, 0.5 * Vehicle->BrakeDelay[ delays + ( isrelease ? 0 : 1 ) ] ); + } + return horizon; +} + +// distance [m] in which the gradient alone, with no brake and no power, brings a train rolling uphill at Velocity [km/h] to a stand +double +uphill_stopping_distance( double const Velocity, double const Gravity ) { + return ( Velocity / 3.6 ) * ( Velocity / 3.6 ) / ( 2.0 * std::max( 0.01, -Gravity ) ); +} + +// speed [km/h] from which the gradient alone brings a train rolling uphill to a stand in Distance [m] +static double +uphill_coasting_speed( double const Distance, double const Gravity ) { + return 3.6 * std::sqrt( 2.0 * std::max( 0.01, -Gravity ) * std::max( 0.0, Distance ) ); +} + +// outside of max safe range: follow the braking curve down to the speed ahead, Vel is the present speed in the +// direction of travel +void +TController::adjust_desired_speed_for_braking_curve( double const Vel ) { + + AccDesired = AccPreferred; + if( Vel <= min_speed( ActualProximityDist > 10.0 ? 10.0 : 5.0, VelDesired ) ) { + return; + } + // allow to coast at reasonably low speed + auto const brakingdistance { fBrakeDist * braking_distance_multiplier( VelNext ) }; + if( auto const slowdowndistance { ( + mvOccupied->CategoryFlag == 2 ? // cars can stop on a dime, for bigger vehicles we enforce some minimal braking distance + brakingdistance : + std::max( + false == OrderCurrentGet().HasAny(DriverOrder::connect) ? 100.0 : 25.0, + brakingdistance ) ) }; + brakingdistance + std::max(slowdowndistance, fMaxProximityDist) < ActualProximityDist - fMaxProximityDist ) { + // don't slow down prematurely; as long as we have room to come to a full stop at a safe distance, we're good + return; + } + // ensure some minimal coasting speed, otherwise a vehicle entering this zone at very low speed will be crawling forever + auto const brakingpointoffset = ( + ( VelNext == 0.0 ) && is_train() && ( OrderCurrentGet() & DriverOrder::obeyTrain ) ? + stopping_margin() : // the same stopping point as the final approach + VelNext * braking_distance_multiplier( static_cast( VelNext ) ) ); + // both plans of a pneumatic brake are made from the brake table of the consist; with none (in shunting it isn't + // worked out) the braking curve is the constant deceleration over the distance left, as before them + braking_curve::brake_table const braketable { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax }; + // making for a passenger stop only the time the brake takes to fill: the look-ahead the horizon + // keeps as its floor was set for the stops at a signal, and a vehicle that brakes with its + // independent brake, which leaves the train brake handle where it is, kept braking earlier + // and earlier the whole way in, to crawl the last tens of metres to the stop point + auto const fillbrakea0 { bStopTargetIsPassengerStop ? 1.0 : fBrake_a0[ 0 ] }; + // once the brake is on, the room it takes to fill is behind; a vehicle running alone brakes with its + // independent brake and leaves the train brake handle in running, so that brake counts as well + braking_curve::approach const approach { + Vel, VelNext, ActualProximityDist, brakingpointoffset, fAccGravity, AbsAccS, + braking_curve::brake_acting( + BrakeCtrlPosition, + // IncLocalBrakeLevel() moves the independent brake handle on a vehicle without one too + ( mvOccupied->LocalBrake == TLocalBrake::PneumaticBrake || mvOccupied->LocalBrake == TLocalBrake::HydraulicBrake ) ? + mvOccupied->LocalBrakePosA : + 0.0 ), + brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ), + brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fillbrakea0 ) }; + auto const deceleration { braking_curve::demand( approach, BrakeSystem == TBrakeSystem::Pneumatic ? &braketable : nullptr ) }; + AccDesired = std::min( AccDesired, deceleration ); // najpierw hamuje mocniej, potem zluzuje + if( Vel <= VelNext ) { + return; + } + if( deceleration < fAccGravity - 0.001 ) { + // no power while still above the speed being braked for + AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION ); + } + else if( ( fAccGravity < -0.025 ) + && ( OrderCurrentGet().HasAny(DriverOrder::obeyTrain) ) + && ( false == uphill_brake_committed( Vel ) ) + && ( ActualProximityDist - uphill_stopping_distance( Vel, fAccGravity ) > brakingpointoffset ) ) { + // uphill the gradient alone slows the train down more than it is asked to; + // keep it rolling at the present speed until that changes + AccDesired = std::min( 0.0, AccPreferred ); + VelDesired = min_speed( VelDesired, uphill_coasting_speed( ActualProximityDist - brakingpointoffset, fAccGravity ) ); + } +} + +// the final approach to a stop, inside the proximity range: Vel is the present speed in the direction of travel +void +TController::adjust_desired_speed_for_final_approach( double const Vel ) { + + if( ( mvOccupied->CategoryFlag & 1 ) == 0 ) { + // for cars (and others) coast at low speed until we hit min proximity range + VelDesired = min_speed( VelDesired, 5.0 ); + return; + } + // trains + if( ( OrderCurrentGet() & ( DriverOrder::shunt | DriverOrder::connect ) ) + && ( Obstacle.distance < 50 ) ) { + // crude detection of edge case, if approaching another vehicle coast slowly until min distance + // this should allow to bunch up trainsets more on sidings + VelDesired = min_speed( 5.0, VelDesired ); + return; + } + // hamowanie tak, aby stanąć + if( false == OrderCurrentGet().HasAny(DriverOrder::obeyTrain) ) { + VelDesired = VelNext; + AccDesired = ( VelNext * VelNext - Vel * Vel ) / ( 25.92 * ( ActualProximityDist + 0.1 - 0.5*fMinProximityDist ) ); + AccDesired = std::min( AccDesired, fAccThreshold ); + return; + } + // a train keeps its desired speed until the lower edge of the stopping window (a desired + // speed of 0 here asks for hard braking whatever the distance left), aims at the middle + // of the window, and asks only for what that takes + auto const stoppingroom { std::max( 0.5, ActualProximityDist - stopping_margin() ) }; + AccDesired = ( + BrakeSystem == TBrakeSystem::Pneumatic ? + // cast iron blocks grip harder as the train comes to a stand + braking_curve::shaped_demand( + Vel, VelNext, stoppingroom, fAccGravity, + { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax } ) : + ( VelNext * VelNext - Vel * Vel ) / ( 25.92 * stoppingroom ) ); + if( ( fAccGravity < -0.025 ) + && ( AccDesired >= fAccGravity - 0.001 ) // no brake needed at all + && ( false == uphill_brake_committed( Vel ) ) + && ( ActualProximityDist - uphill_stopping_distance( Vel, fAccGravity ) > stopping_margin() ) ) { + // uphill the gradient alone would bring the train to a stand short of the + // middle of the stopping window; keep it rolling at the present speed until that changes, + // but no faster than the gradient alone can take off by the middle of the window + AccDesired = std::min( 0.0, AccPreferred ); + VelDesired = min_speed( VelDesired, uphill_coasting_speed( ActualProximityDist - stopping_margin(), fAccGravity ) ); + } +} + +void +TController::adjust_desired_speed_for_target_speed( double const Range ) { + // ustalanie zadanego przyspieszenia + //(ActualProximityDist) - odległość do miejsca zmniejszenia prędkości + //(AccPreferred) - wynika z psychyki oraz uwzglęnia już ewentualne zderzenie z pojazdem z przodu, ujemne gdy należy hamować + //(AccDesired) - uwzględnia sygnały na drodze ruchu, ujemne gdy należy hamować + //(fAccGravity) - chwilowe przspieszenie grawitacyjne, ujemne działa przeciwnie do zadanego kierunku jazdy + //(AbsAccS) - chwilowe przyspieszenie pojazu (uwzględnia grawitację), ujemne działa przeciwnie do zadanego kierunku jazdy + //(AccDesired) porównujemy z (fAccGravity) albo (AbsAccS) + + // gdy jedzie wolniej niż potrzeba, albo nie ma przeszkód na drodze + // normalna jazda + AccDesired = VelDesired != 0.0 ? AccPreferred : -0.01; + fAccDesiredGravity = 0.0; + + auto const vel { DirectionalVel() }; + + if( VelNext >= 0.0 + && ActualProximityDist <= Range + && vel >= VelNext ) { + // gdy zbliża się i jest za szybki do nowej prędkości, albo stoi na zatrzymaniu + if (vel > EU07_AI_NOMOVEMENT) { + // jeśli jedzie + if( vel < VelNext + && ActualProximityDist > fMaxProximityDist * (1.0 + 0.1 * vel) ) { + // jeśli jedzie wolniej niż można i jest wystarczająco daleko, to można przyspieszyć + if( AccPreferred > 0.0 ) { + // jeśli nie ma zawalidrogi dojedz do semafora/przeszkody + AccDesired = AccPreferred; + } + } + else if( ( ActualProximityDist > fMinProximityDist ) + // only a stop has a final approach of its own inside the proximity range; a lower speed ahead + // keeps the braking curve below right up to where it begins, or the train would stop braking + // (and even take power) that far out + && ( VelNext == 0.0 ) + && ( ActualProximityDist < fMaxProximityDist ) ) { + // jedzie szybciej, niż trzeba na końcu ActualProximityDist, ale jeszcze jest daleko + // jak minął już maksymalny dystans po prostu hamuj (niski stopień) + // ma stanąć, a jest w drodze hamowania albo ma jechać + adjust_desired_speed_for_final_approach( vel ); + AccDesired = std::min( AccDesired, AccPreferred ); + } + else if (ActualProximityDist > fMinProximityDist) { + // jedzie szybciej, niż trzeba na końcu ActualProximityDist, ale jeszcze jest daleko + adjust_desired_speed_for_braking_curve( vel ); + AccDesired = std::min( AccDesired, AccPreferred ); + } + else { + // jest bliżej niż fMinProximityDist + // utrzymuj predkosc bo juz blisko +/* + VelDesired = min_speed( VelDesired, VelNext ); +*/ + if( VelNext == 0.0 ) { + VelDesired = VelNext; + } + else { + if( vel <= VelNext + fVelPlus ) { + // jeśli niewielkie przekroczenie, ale ma jechać + AccDesired = std::max( 0.0, AccPreferred ); // to olej (zacznij luzować) + } + } + ReactionTime = 0.1; // i orientuj się szybciej + } + } + else { + // zatrzymany (vel==0.0) + if( VelNext > 0.0 ) { + // można jechać + AccDesired = AccPreferred; + } + else { + // jeśli daleko jechać nie można + if( ActualProximityDist > ( + mvOccupied->CategoryFlag & 2 ? + fMinProximityDist : // cars + fMaxProximityDist ) ) { // trains and others + // ale ma kawałek do sygnalizatora + if( AccPreferred > 0.0 ) { + // dociagnij do semafora; + AccDesired = AccPreferred; + } + else { + //stoj + VelDesired = 0.0; + } + } + else { + // VelNext=0 i stoi bliżej niż fMaxProximityDist + VelDesired = 0.0; + } + } + } + } +} + +void +TController::adjust_desired_speed_for_current_speed() { + // decisions based on current speed + auto const vel { DirectionalVel() }; + + if( is_train() ) { + // on flats or uphill we can be less careful + if( vel > VelDesired ) { + // jesli jedzie za szybko do AKTUALNEGO + if( VelDesired == 0.0 ) { + // jesli stoj, to hamuj, ale i tak juz za pozno :) + AccDesired = std::min( AccDesired, -0.85 ); // hamuj solidnie + } + else { + // slow down, not full stop + if( vel > VelDesired + fVelPlus ) { + // hamuj tak średnio + AccDesired = std::min( AccDesired, -0.05 + fAccThreshold ); + } + else { + // o 5 km/h to olej (zacznij luzować) + AccDesired = std::min( + AccDesired, // but don't override decceleration for VelNext + std::max( 0.0, AccPreferred ) ); + } + } + } + + if( fAccGravity > 0.025 ) { + // going sharply downhill we may need to start braking sooner than usual + // try to estimate increase of current velocity before engaged brakes start working + // look ahead for as long as the brake takes to respond, since that is how long the + // present acceleration will last whatever is done with the handle now; a pneumatic + // brake applies and releases on its own time scale, which in G is tens of seconds + auto const horizon { brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ) }; + auto const speedestimate = vel + 3.6 * horizon * AbsAccS; + // already below a lower limit ahead, the train has no business speeding up towards it + auto holdlimit { VelDesired }; + if( ( VelNext > 0.0 ) + && ( VelNext < holdlimit ) + && ( vel <= VelNext + fVelPlus ) + && ( ActualProximityDist < std::max( 2.0 * fBrakeDist, 500.0 ) ) ) { + holdlimit = VelNext; + } + // hold a band just below the limit; the steeper the descent the harder the train pulls + // away once the brake eases, so the band widens with the gradient (about 3 km/h at 20 per mille) + // an electro-pneumatic or electric brake responds at once and needs far less room + auto const holdspeed { holdlimit - ( + BrakeSystem == TBrakeSystem::Pneumatic ? + std::clamp( fAccGravity * 15.0, 1.0, 3.0 ) : + std::clamp( fAccGravity * 7.5, 1.0, 1.5 ) ) }; + // the predicted difference is to be made up over the time the brake takes to respond, not at once: with a + // slow brake, a demand sized to remove it at once comes on as a deep application, which then takes as + // long to let go, and the train ends up well below the speed it was to hold + auto const holdgain { std::min( 0.04, 1.0 / ( 3.6 * std::max( 1.0, horizon ) ) ) }; + if( ( speedestimate > VelDesired ) + && ( VelDesired == 0.0 ) ) { + // jesli stoj, to hamuj, ale i tak juz za pozno :) + AccDesired = std::min( AccDesired, -0.85 ); // hamuj solidnie + } + else { + // one continuous law on both sides of the target, proportional to the predicted + // difference: a demand that jumps to the braking threshold above the target and to + // full acceleration below it alternates, with a brake that responds in seconds, + // between a hard application and a full release + AccDesired = std::min( + AccDesired, // but don't override decceleration for VelNext + std::clamp( + EU07_AI_NOACCELERATION - holdgain * ( speedestimate - holdspeed ), + -0.05 + fAccThreshold, + std::max( EU07_AI_NOACCELERATION, AccPreferred ) ) ); + // HACK: for cargo trains with high braking threshold ensure we cross that threshold + auto const crossthreshold { IsCargoTrain && fBrake_a0[ 0 ] > 0.2 && speedestimate > holdlimit }; + AccDesired -= ( crossthreshold ? std::clamp( fBrake_a0[ 0 ] - 0.2, 0.0, 0.15 ) : 0.0 ); + } + // final tweaks + if( vel > EU07_AI_NOMOVEMENT ) { + // going downhill also take into account impact of gravity + AccDesired -= fAccGravity; + // from here on AccDesired is what the brake alone has to deliver, which is what + // IncBrake() sizes the handle position for; AbsAccS already contains the gravity, + // so the comparisons with it have to add this part back + fAccDesiredGravity = fAccGravity; + // HACK: if the max allowed speed was exceeded something went wrong; brake harder + AccDesired -= 0.15 * std::clamp( vel - VelDesired, 0.0, 5.0 ); + } + } + // HACK: limit acceleration for cargo trains, to reduce probability of breaking couplers on sudden jolts + auto MaxAcc{ 0.5 * mvOccupied->Couplers[(mvOccupied->DirAbsolute >= 0 ? end::rear : end::front)].FmaxC / fMass }; + if( iVehicles - ControlledEnginesCount > 0 ) { + MaxAcc *= std::clamp( vel * 0.025, 0.2, 1.0 ); + } + AccDesired = std::min(AccDesired, safe_clamp(MaxAcc, HeavyCargoTrainAcceleration, AccPreferred)); + // TBD: expand this behaviour to all trains with car(s) exceeding certain weight? + /* + if( ( IsPassengerTrain ) && ( iVehicles - ControlledEnginesCount > 0 ) ) { + AccDesired = std::min( AccDesired, ( iVehicles - ControlledEnginesCount > 8 ? HeavyPassengetTrainAcceleration : PassengetTrainAcceleration ) ); + } + if( ( IsCargoTrain ) && ( iVehicles - ControlledEnginesCount > 0 ) ) { + AccDesired = std::min( AccDesired, CargoTrainAcceleration ); + } + if( ( IsHeavyCargoTrain ) && ( iVehicles - ControlledEnginesCount > 0 ) ) { + AccDesired = std::min( AccDesired, HeavyCargoTrainAcceleration ); + } */ + } + else { + // for cars the older version works better + if( vel > VelDesired ) { + // jesli jedzie za szybko do AKTUALNEGO + if( VelDesired == 0.0 ) { + // jesli stoj, to hamuj, ale i tak juz za pozno :) + AccDesired = std::min( AccDesired, -0.9 ); // hamuj solidnie + } + else { + // slow down, not full stop + if( vel > VelDesired + fVelPlus ) { + // hamuj tak średnio + AccDesired = std::min( AccDesired, -fBrake_a0[ 0 ] * 0.5 ); + } + else { + // o 5 km/h to olej (zacznij luzować) + AccDesired = std::min( + AccDesired, // but don't override decceleration for VelNext + std::max( 0.0, AccPreferred ) ); + } + } + } + } + + // NOTE: as a stop-gap measure the routine is limited to trains only while car calculations seem off + if( is_train() && vel < VelDesired && + -AccDesired * BrakeAccFactor() < (false == Ready || VelNext > vel - 40.0 ? fBrake_a0[0] * 0.8 : -fAccThreshold) / (1.2 * braking_distance_multiplier(VelNext)) ) { + // don't adjust acceleration when going above current target speed + AccDesired = std::max(EU07_AI_NOACCELERATION, AccDesired); + } +} + +// hamowanie kontrolne +void +TController::adjust_desired_speed_for_braking_test() { + +// if( false == Global.DynamicBrakeTest ) { return; } + if( DynamicBrakeTest >= 5 ) { return; } // all done + if( ( DynamicBrakeTest == 0 ) + && ( false == timetable::makes_brake_test( TrainParams.run_flags() ) ) ) { return; } // the timetable says there's none (eu07/maszyna#95) + if( false == is_train() ) { return; } // not applicable + if( mvOccupied->BrakeHandle == TBrakeHandle::FVel6 ) { return; } // leads to bugs in DecBrake, disable for now + if( false == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { return; } // not applicable + if( false == AIControllFlag ) { return; } // TBD: add notification about braking test and enable it for human driver as well? + + auto const vel { DirectionalVel() }; + // what the route ahead asks for; the test may brake harder than that, never softer + auto const routeaccdesired { AccDesired }; + auto const routeaccdesiredgravity { fAccDesiredGravity }; + auto const routeveldesired { VelDesired }; + + switch( DynamicBrakeTest ) { + case 0: { + if( primary() + && vel < VelDesired + && fAccGravity >= 0.0 // not if going uphill + && AccDesired >= EU07_AI_ACCELERATION + && TrainParams.TTVmax >= 10.0 + && vel > std::min(TrainParams.TTVmax, 60.0) - 2.0 ) { + DynamicBrakeTest = 1; + DBT_BrakingTime = ElapsedTime; + DBT_VelocityBrake = vel; + } + break; + } + case 1: { + AccDesired = EU07_AI_BRAKINGTESTACCELERATION; + fAccDesiredGravity = 0.0; + VelDesired = DBT_VelocityBrake; + if( ElapsedTime - DBT_BrakingTime > 1 ) { + ForcePNBrake = true; + mvOccupied->EpFuseSwitch( false ); + DynamicBrakeTest = 2; + } + break; + } + case 2: { + AccDesired = EU07_AI_BRAKINGTESTACCELERATION; + fAccDesiredGravity = 0.0; + VelDesired = DBT_VelocityBrake; + if( ElapsedTime - DBT_BrakingTime > 2 ) { + DBT_BrakingTime = ElapsedTime; + DBT_VelocityBrake = vel; + DBT_VelocityRelease = vel - 8.0; + DynamicBrakeTest = 3; + } + break; + } + case 3: { + AccDesired = safe_clamp( -AbsAccS, fAccThreshold * 1.01, fAccThreshold * 1.21 ); + fAccDesiredGravity = 0.0; + VelDesired = DBT_VelocityBrake; + if( vel <= DBT_VelocityRelease ) { + DynamicBrakeTest = 4; + DBT_BrakingTime = ElapsedTime - DBT_BrakingTime; + DBT_MidPointAcc = AbsAccS; + DBT_ReleasingTime = ElapsedTime; + } + break; + } + case 4: { + if( Ready ) { + if( BrakeSystem == TBrakeSystem::ElectroPneumatic ) { + mvOccupied->EpFuseSwitch( true ); + } + ForcePNBrake = false; + DynamicBrakeTest = 5; + DBT_ReleasingTime = ElapsedTime - DBT_ReleasingTime; + DBT_VelocityFinish = vel; + } + break; + } + default: { + break; + } + } + // a stop or a restriction coming up while the test runs takes precedence + if( ( DynamicBrakeTest >= 1 ) + && ( DynamicBrakeTest <= 3 ) + && ( routeaccdesired < AccDesired ) ) { + AccDesired = routeaccdesired; + fAccDesiredGravity = routeaccdesiredgravity; + VelDesired = std::min( VelDesired, routeveldesired ); + } +} diff --git a/vehicle/ai/speedpos.cpp b/vehicle/ai/speedpos.cpp new file mode 100644 index 000000000..0fb3b73b1 --- /dev/null +++ b/vehicle/ai/speedpos.cpp @@ -0,0 +1,329 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// a position of the speed table: a track, a switch or an event ahead and the speed it asks for + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/mover.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + + +TSpeedPos::TSpeedPos(TTrack *track, double dist, SpeedPointFlags flag) +{ + Set(track, dist, flag); +}; + +TSpeedPos::TSpeedPos(basic_event *event, double dist, double length, DriverOrders order) +{ + Set(event, dist, length, order); +}; + +void TSpeedPos::Clear() +{ + ResetFlags(); // brak flag to brak reakcji + fVelNext = -1.0; // prędkość bez ograniczeń + fSectionVelocityDist = 0.0; //brak długości + fPointDist = 0.0; + fDist = 0.0; + bSeenAhead = false; + vPos = glm::dvec3(0, 0, 0); + trTrack = nullptr; // brak wskaźnika +}; + +void TSpeedPos::CommandCheck() +{ // sprawdzenie typu komendy w evencie i określenie prędkości + TCommandType command = evEvent->input_command(); + double value1 = evEvent->input_value(1); + double value2 = evEvent->input_value(2); + // the point of a PointVelocity limit is taken anew from the current command + flags = flags.Without(SpeedPointFlag::pointSpeed); + fPointDist = 0.0; + switch (command) + { + case TCommandType::cm_ShuntVelocity: + // prędkość manewrową zapisać, najwyżej AI zignoruje przy analizie tabelki + fVelNext = value1; // powinno być value2, bo druga określa "za"? + flags |= SpeedPointFlag::shuntSignal; + break; + case TCommandType::cm_SetVelocity: + // w semaforze typu "m" jest ShuntVelocity dla Ms2 i SetVelocity dla S1 + // SetVelocity * 0 -> można jechać, ale stanąć przed + // SetVelocity 0 20 -> stanąć przed, potem można jechać 20 (SBL) + // SetVelocity -1 100 -> można jechać, przy następnym ograniczenie (SBL) + // SetVelocity 40 -1 -> PutValues: jechać 40 aż do minięcia (koniec ograniczenia( + fVelNext = value1; + flags = flags.Without((SpeedPointFlag::shuntSignal | SpeedPointFlag::passengerStop | SpeedPointFlag::stopOnAutomaticBlock)); + flags |= SpeedPointFlag::signal;// nie manewrowa, nie przystanek, nie zatrzymać na SBL, ale semafor + if (value1 == 0.0 && value2 != 0.0) // jeśli pierwsza zerowa + // a druga nie + { // S1 na SBL, można przejechać po zatrzymaniu (tu nie mamy prędkości ani odległości) + fVelNext = value2; // normalnie będzie zezwolenie na jazdę, aby się usunął z tabelki + flags |= SpeedPointFlag::stopOnAutomaticBlock; // flaga, że ma zatrzymać; na pewno nie zezwoli na manewry + } + break; + case TCommandType::cm_SectionVelocity: + // odcinek z ograniczeniem prędkości + fVelNext = value1; + fSectionVelocityDist = value2; + flags |= SpeedPointFlag::sectionSpeed; + break; + case TCommandType::cm_RoadVelocity: + // prędkość drogowa (od tej pory będzie jako domyślna najwyższa) + fVelNext = value1; + flags |= SpeedPointFlag::roadSpeed; + break; + case TCommandType::cm_PassengerStopPoint: + // nie ma dostępu do rozkładu + // przystanek, najwyżej AI zignoruje przy analizie tabelki + fVelNext = 0.0; + flags |= SpeedPointFlag::passengerStop; // niestety nie da się w tym miejscu współpracować z rozkładem +/* + // NOTE: not used for now as it might be unnecessary + // special case, potentially override any set speed limits if requested + // NOTE: we test it here because for the time being it's only used for passenger stops + if( flags.HasAll(spDontApplySpeedLimit) ) { + fVelNext = -1; + } +*/ + break; + case TCommandType::cm_SetProximityVelocity: + // musi zostać gdyż inaczej nie działają manewry + fVelNext = -1; + flags |= SpeedPointFlag::proximitySpeed; + // fSectionVelocityDist = value2; + break; + case TCommandType::cm_PointVelocity: + // PointVelocity v d: the head has to be at v (-1: no limit) at the point d metres beyond the cell, + // the limit ends when the head passes that point. the cell is read until the head passes the cell, + // what it says then holds for the point (the warning disc of a level crossing, Osp1/Osp2) + fVelNext = value1; + fPointDist = std::max( value2, 0.0 ); + flags = flags.Without((SpeedPointFlag::shuntSignal | SpeedPointFlag::passengerStop | SpeedPointFlag::stopOnAutomaticBlock | SpeedPointFlag::signal)); // not a signal, even if the cell was one before + flags |= SpeedPointFlag::pointSpeed; + break; + case TCommandType::cm_OutsideStation: + // w trybie manewrowym: skanować od niej wstecz i stanąć po wyjechaniu za sygnalizator i + // zmienić kierunek + // w trybie pociągowym: można przyspieszyć do wskazanej prędkości (po zjechaniu z rozjazdów) + fVelNext = -1; + flags |= SpeedPointFlag::outsideStation; // W5 + break; + case TCommandType::cm_EmergencyBrake: + fVelNext = -1; + break; + case TCommandType::cm_SecuritySystemMagnet: + fVelNext = -1; + break; + case TCommandType::cm_SignalAreaEnd: + // imposes no speed of its own, it only ends the reduced speed of the signal passed last + fVelNext = -1; + flags |= SpeedPointFlag::signalAreaEnd; + break; + default: + // inna komenda w evencie skanowanym powoduje zatrzymanie i wysłanie tej komendy + // nie manewrowa, nie przystanek, nie zatrzymać na SBL + // jak nieznana komenda w komórce sygnałowej, to zatrzymujemy + fVelNext = 0.0; +/* + fVelNext = ( + evEvent->is_command() ? 0.0 : // ask for a stop if we have a command for the vehicle + flags.HasAny(( spSemaphor | spShuntSemaphor )) ? fVelNext : // don't change semafor velocity + -1.0 ); // otherwise don't be a bother +*/ + // TODO: check whether clearing spShuntSemaphor flag doesn't cause problems + // potentially it can invalidate shunt semaphor used to transmit timetable or similar command + flags = flags.Without((SpeedPointFlag::shuntSignal | SpeedPointFlag::passengerStop | SpeedPointFlag::stopOnAutomaticBlock)); + } +}; + +bool TSpeedPos::Update() +{ + if( fDist < 0.0 ) { + // trzeba zazanaczyć, że minięty + flags |= SpeedPointFlag::elapsed; + } + bSeenAhead = signal_passing::seen_ahead_on_update( fDist, bSeenAhead ); + if (flags & SpeedPointFlag::track) { + // road/track + if (trTrack) { + // może być NULL, jeśli koniec toru (???) + fVelNext = trTrack->VelocityGet(); // aktualizacja prędkości (może być zmieniana eventem) + + if( trTrack->iCategoryFlag & 1 ) { + // railways + if( flags & SpeedPointFlag::switchTrack && (trTrack->GetSwitchState() & 1) != 0 != (flags.HasAny(SpeedPointFlag::switchState)) ) { + // jeśli odcinek zmienny + // czy stan się zmienił? + // Ra: zakładam, że są tylko 2 możliwe stany + flags ^= SpeedPointFlag::switchState; + if (false == flags.HasAny(SpeedPointFlag::elapsed)) + { + // jeszcze trzeba skanowanie wykonać od tego toru + // problem jest chyba, jeśli zwrotnica się przełoży zaraz po zjechaniu z niej + // na Mydelniczce potrafi skanować na wprost mimo pojechania na bok + return true; + } + } + } + else { + // roads and others + if( crossRoute != 0 && crossRoute != 1 ) { // as the top 4 bits read without the sign: -1 counts as turning + // jeśli skrzyżowanie, ograniczyć prędkość przy skręcaniu + // ±1 to jazda na wprost, ±2 nieby też, ale z przecięciem głównej drogi - chyba że jest równorzędne... + // TODO: uzależnić prędkość od promienia; + // albo niech będzie ograniczona w skrzyżowaniu (velocity z ujemną wartością) + fVelNext = 30.0; + } + } + } + } + else if (flags & SpeedPointFlag::event && (false == flags.HasAny(SpeedPointFlag::elapsed) || fVelNext == 0.0)) { + // jeśli event + // ignore already passed signals, but keep an eye on overrun stops + // (a PointVelocity cell is latched when the head passes it, except at 0, which has to be released by the cell) + // odczyt komórki pamięci najlepiej by było zrobić jako notyfikację, + // czyli zmiana komórki wywoła jakąś podaną funkcję + CommandCheck(); // sprawdzenie typu komendy w evencie i określenie prędkości + } + return false; +}; + +std::string TSpeedPos::GetName() const +{ + if( flags & SpeedPointFlag::track ) // jeśli tor + return trTrack->name(); + else if( flags & SpeedPointFlag::event ) // jeśli event + return + evEvent->m_name + + " [" + std::to_string( static_cast( evEvent->input_value( 1 ) ) ) + + ", " + std::to_string( static_cast( evEvent->input_value( 2 ) ) ) + + "]"; + else + return ""; +} + +std::string TSpeedPos::TableText() const +{ // pozycja tabelki pr?dko?ci + if (flags & SpeedPointFlag::enabled) + { // o ile pozycja istotna + return to_hex_str(LegacyFlagsValue(), 8) + " " + to_string(fDist, 1, 6) + + " " + (fVelNext == -1.0 ? " -" : to_string(static_cast(fVelNext), 0, 3)) + " " + GetName(); + } + return "Empty"; +} + +bool TSpeedPos::IsProperSemaphor(DriverOrders order) +{ // sprawdzenie czy semafor jest zgodny z trybem jazdy + if (false == order.HasAny(trainOrders)) // Wait_for_orders, Prepare_engine, Change_direction, Connect, Disconnect, Shunt + { + if (flags & (SpeedPointFlag::signal | SpeedPointFlag::shuntSignal)) + return true; + else if (flags & SpeedPointFlag::outsideStation) + return true; + } + else if (order & DriverOrder::obeyTrain && flags & SpeedPointFlag::signal) + { + return true; + } + return false; // true gdy zatrzymanie, wtedy nie ma po co skanować dalej +} + +bool TSpeedPos::Set(basic_event *event, double dist, double length, DriverOrders order, bool const Standing) +{ // zapamiętanie zdarzenia + fDist = dist; + // an event already behind the head when found (under a train set across a signal) wasn't passed by it. a moving + // train may be just passing it, and the distance is found in steps of a metre, so for a moving train an event a + // little behind the head still counts as seen ahead. a standing train passes nothing: an event found behind its + // head counts only once an update finds it ahead + bSeenAhead = signal_passing::seen_ahead_when_found( dist, Standing ); + flags = SpeedPointFlag::event; + crossRoute = 0; + evEvent = event; + vPos = event->input_location(); // współrzędne eventu albo komórki pamięci (zrzutować na tor?) + // ignore events located behind the consist, but with exception of stop points which may be needed to update freshly received timetable + if( dist + length < 0 + && event->input_command() != TCommandType::cm_PassengerStopPoint ) { + return false; + } + flags |= SpeedPointFlag::enabled; + CommandCheck(); // sprawdzenie typu komendy w evencie i określenie prędkości + // zależnie od trybu sprawdzenie czy jest tutaj gdzieś semafor lub tarcza manewrowa + // jeśli wskazuje stop wtedy wystawiamy true jako koniec sprawdzania + // WriteLog("EventSet: Vel=" + AnsiString(fVelNext) + " flags=" + AnsiString(flags) + " order="+AnsiString(order)); + if (false == order.HasAny(trainOrders)) // Wait_for_orders, Prepare_engine, Change_direction, Connect, Disconnect, Shunt + { + if (flags & (SpeedPointFlag::signal | SpeedPointFlag::shuntSignal) && fVelNext == 0.0) + return true; + else if (flags & SpeedPointFlag::outsideStation) + return true; + } + else if (order & DriverOrder::obeyTrain && flags & SpeedPointFlag::signal && fVelNext == 0.0) + { + return true; + } + return false; // true gdy zatrzymanie, wtedy nie ma po co skanować dalej +}; + +void TSpeedPos::Set(TTrack *track, double dist, SpeedPointFlags flag) +{ // zapamiętanie zmiany prędkości w torze + fDist = dist; // odległość do początku toru + trTrack = track; // TODO: (t) może być NULL i nie odczytamy końca poprzedniego :/ + if (trTrack) + { + crossRoute = 0; + flags = flag | (trTrack->eType == tt_Normal ? SpeedPointFlag::track : SpeedPointFlag::track | SpeedPointFlag::switchTrack ); // zapamiętanie kierunku wraz z typem + if (flags & SpeedPointFlag::switchTrack && trTrack->GetSwitchState() & 1) + flags |= SpeedPointFlag::switchState; + fVelNext = trTrack->VelocityGet(); + if (trTrack->iDamageFlag & 128) + fVelNext = 0.0; // jeśli uszkodzony, to też stój + if (flags & SpeedPointFlag::trackEnd) + fVelNext = trTrack->iCategoryFlag & 1 ? + 0.0 : + 20.0; // jeśli koniec, to pociąg stój, a samochód zwolnij + vPos = + flags & SpeedPointFlag::reverse ? + trTrack->CurrentSegment()->FastGetPoint_1() : + trTrack->CurrentSegment()->FastGetPoint_0(); + } +}; diff --git a/vehicle/ai/speedtable.cpp b/vehicle/ai/speedtable.cpp new file mode 100644 index 000000000..ca7f5511e --- /dev/null +++ b/vehicle/ai/speedtable.cpp @@ -0,0 +1,1362 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the speed table: what each position of it asks of the driver, the stop points, the speed limits and the signals + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/mover.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + +bool WriteTrainLogFlag = false; +namespace +{ + +void clear_signal_area_end( TSpeedPos &Point ) +{ + if( Point.flags.HasAll(SpeedPointFlag::signalAreaEnd) ) { + Point.Clear(); + } +} + +} // namespace + +auto const passengerstopmaxdistance { 400.0 }; // maximum allowed distance between passenger stop point and consist head + +TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fNext, double &fAcc) +{ // ustalenie parametrów, zwraca typ komendy, jeśli sygnał podaje prędkość do jazdy + // fVelDes - prędkość zadana + // fDist - dystans w jakim należy rozważyć ruch + // fNext - prędkość na końcu tego dystansu + // fAcc - zalecane przyspieszenie w chwili obecnej - kryterium wyboru dystansu + auto a { 0.0 }; // przyspieszenie + auto v { 0.0 }; // prędkość + auto d { 0.0 }; // droga + auto d_to_next_sem { 10000.0 }; //ustaiwamy na pewno dalej niż widzi AI + auto go { TCommandType::cm_Unknown }; + auto speedlimitiscontinuous { true }; // stays true if potential active speed limit is unbroken to the last (relevant) point in scan table + eSignNext = nullptr; + IsAtPassengerStop = false; + bStopTargetIsPassengerStop = false; + IsScheduledPassengerStopVisible = false; + mvOccupied->SecuritySystem.set_cabsignal_lock(false); + // te flagi są ustawiane tutaj, w razie potrzeby + drivingFlags.trackEnd = false; + drivingFlags.switchFound = false; + drivingFlags.signalFound = false; + drivingFlags.stopPointFound = false; + SignalAreaEndDist = -1.0; + update_point_limits(); + + for( std::size_t idx = 0; idx < sSpeedTable.size(); ++idx ) { + // o ile dana pozycja tabelki jest istotna + if( false == sSpeedTable[ idx ].flags.HasAny(SpeedPointFlag::enabled) ) { continue; } + + auto &point { sSpeedTable[ idx ] }; + + if( point.flags.HasAll(SpeedPointFlag::passengerStop) ) { + if( TableUpdateStopPoint( go, point, d_to_next_sem ) ) { continue; }; + } + v = point.fVelNext; // odczyt prędkości do zmiennej pomocniczej + if( point.flags.HasAll(SpeedPointFlag::switchTrack) ) { + // zwrotnice są usuwane z tabelki dopiero po zjechaniu z nich + drivingFlags.switchFound = true; // rozjazd z przodu/pod ogranicza np. sens skanowania wstecz + SwitchClearDist = point.fDist + point.trTrack->Length() + fLength; + } + else if ( point.flags.HasAll(SpeedPointFlag::event) && TableUpdateEvent(v, go, point, d_to_next_sem, idx) ) // W4 może się deaktywować + { // jeżeli event, może być potrzeba wysłania komendy, aby ruszył + continue; + } + + auto const railwaytrackend { true == point.flags.HasAll(SpeedPointFlag::trackEnd) && is_train() }; + if( v >= 0.0 // pozycje z prędkością -1 można spokojnie pomijać + || railwaytrackend ) { + + // a PointVelocity limit lies fPointDist beyond its entry and stays ahead of us until the head passes it + auto const ispointlimit { point.flags.HasAll(SpeedPointFlag::pointSpeed) }; + d = point.fDist + point.fPointDist; + + if( v >= 0.0 ) { + // points located in front of us can potentially affect our acceleration and target speed + if( d > 0.0 + && ( false == point.flags.HasAll(SpeedPointFlag::elapsed) || ispointlimit ) ) { + // sygnał lub ograniczenie z przodu (+32=przejechane) + // 2014-02: jeśli stoi, a ma do przejechania kawałek, to niech jedzie + if( mvOccupied->Vel < 0.01 + && true == point.flags.HasAll(SpeedPointFlag::enabled | SpeedPointFlag::event | SpeedPointFlag::passengerStop) + && false == IsAtPassengerStop ) { + // ma podjechać bliżej - czy na pewno w tym miejscu taki warunek? + a = d > passengerstopmaxdistance || drivingFlags.stopCloser ? fAcc : 0.0; + } + else { + // przyspieszenie: ujemne, gdy trzeba hamować + if( v >= 0.0 ) { + a = ( v * v - mvOccupied->Vel * mvOccupied->Vel ) / ( 25.92 * d ); + if( mvOccupied->Vel < v + || v == 0.0 ) { + // if we're going slower than the target velocity and there's enough room for safe stop, speed up + auto const brakingdistance { 1.2 * fBrakeDist * braking_distance_multiplier( v ) }; + if( brakingdistance > 0.0 ) { + // maintain desired acc while we have enough room to brake safely, when close enough start paying attention + // try to make a smooth transition instead of sharp change + a = std::lerp( a, AccPreferred, std::clamp( ( d - brakingdistance ) / brakingdistance, 0.0, 1.0 ) ); + } + } + if( d < ( ispointlimit && v > 0.0 ? point_limit_approach() : fMinProximityDist ) + && v < fVelDes ) { + // jak jest już blisko, ograniczenie aktualnej prędkości + fVelDes = v; + } + } + } + } + // points located behind can affect our current speed, but little else + else if ( point.flags & SpeedPointFlag::track) // jeśli tor + { // tor ogranicza prędkość, dopóki cały skład nie przejedzie, + if( v >= 1.0 && d + point.trTrack->Length() < -fLength && false == railwaytrackend ) { // EU06 się zawieszało po dojechaniu na koniec toru postojowego + // zapętlenie, jeśli już wyjechał za ten odcinek + continue; + } + if( v < fVelDes ) { + // ograniczenie aktualnej prędkości aż do wyjechania za ograniczenie + fVelDes = v; + } + if( v < VelLimitLastDist.first ) { + VelLimitLastDist.second = d + point.trTrack->Length() + fLength; + } + else if( VelLimitLastDist.second > 0 && false == point.flags.HasAny((SpeedPointFlag::switchTrack | SpeedPointFlag::passengerStop)) ) { // the speed limit can potentially start afterwards, so don't mark it as broken too soon + speedlimitiscontinuous = false; + } + if( false == railwaytrackend ) { + continue; // i tyle wystarczy + } + } + else { + // event trzyma tylko jeśli VelNext=0, nawet po przejechaniu (nie powinno dotyczyć samochodów?) + a = v > 0.0 ? + fAcc : + mvOccupied->Vel < 0.01 ? + 0.0 : // already standing still so no need to bother with brakes + -2.0; // ruszanie albo hamowanie + } + } + // track can potentially end, which creates another virtual point of interest with speed limit of 0 at the end of it + // TBD, TODO: when tracing the route create a dedicated table entry for it, to simplify the code? + if( railwaytrackend ) { + // if the railway track ends here set the velnext accordingly as well + // TODO: test this with turntables and such + auto const stopatendacceleration = -1.0 * mvOccupied->Vel * mvOccupied->Vel / ( 25.92 * ( d + point.trTrack->Length() ) ); + if( stopatendacceleration < a ) { + a = stopatendacceleration; + v = 0.0; + d += point.trTrack->Length(); + if( d < fMinProximityDist ) { + // jak jest już blisko, ograniczenie aktualnej prędkości + fVelDes = v; + } + } + } + + if( a <= fAcc + && ( v < fNext || fNext < 0 ) ) { // filter out consecutive, farther out blocks with the same speed limit; they'd make us accelerate slower due to their lower a value + // mniejsze przyspieszenie to mniejsza możliwość rozpędzenia się albo konieczność hamowania + // jeśli droga wolna, to może być a>1.0 i się tu nie załapuje + fAcc = a; // zalecane przyspieszenie (nie musi być uwzględniane przez AI) + fNext = v; // istotna jest prędkość na końcu tego odcinka + fDist = d; // dlugość odcinka + bStopTargetIsPassengerStop = ( v == 0.0 ) && ( point.flags.HasAny(SpeedPointFlag::passengerStop) ); + } +/* + else if ((fAcc > 0) && (v >= 0) && (v > fNext)) { + // jeśli nie ma wskazań do hamowania, można podać drogę i prędkość na jej końcu + fNext = v; // istotna jest prędkość na końcu tego odcinka + fDist = d; // dlugość odcinka (kolejne pozycje mogą wydłużać drogę, jeśli prędkość jest stała) + } +*/ + // we'll pick first scanned target speed as our goal + // farther scan table points can override it through previous clause, if they require lower acceleration or speed reduction + else if( a > 0 && a <= fAcc && v >= 0 && fNext < 0 ) { + fAcc = a; + fNext = v; + fDist = d; + bStopTargetIsPassengerStop = ( v == 0.0 ) && ( point.flags.HasAny(SpeedPointFlag::passengerStop) ); + } + // potentially update our current speed limit + // a point limit binds only the head at its point, it neither extends nor breaks a limit over a stretch of the line + if( false == ispointlimit + && v < VelLimitLastDist.first + && ( d < 0 // the point counts as part of last speed limit either if it's behind us + || VelLimitLastDist.second > 0 ) ) { // or if we already have the last limit ongoing + VelLimitLastDist.second = d + fLength; + if( point.flags.HasAny(SpeedPointFlag::track) ) { + VelLimitLastDist.second += point.trTrack->Length(); + } + } + else if( false == point.flags.HasAny(( SpeedPointFlag::switchTrack | SpeedPointFlag::passengerStop | SpeedPointFlag::pointSpeed )) ) { + // if we found a point which isn't part of the current speed limit mark the limit as broken + // NOTE: we exclude switches from this rule, as speed limits generally extend through these + speedlimitiscontinuous = false; + } + } // if (v>=0.0) + // finding a point which doesn't impose speed limit means any potential active speed limit can't extend through entire scan table + // NOTE: we test actual speed value for the given point, as events may receive (v = -1) as a way to disable them in irrelevant modes + if( point.fVelNext < 0 && false == point.flags.HasAny((SpeedPointFlag::switchTrack | SpeedPointFlag::passengerStop | SpeedPointFlag::pointSpeed)) ) { + // NOTE: we exclude switches from this rule, as speed limits generally extend through these + // and point limits, which say nothing of the line they lie on + speedlimitiscontinuous = false; + } + if (fNext >= 0.0) + { // jeśli ograniczenie + if( (point.flags & (SpeedPointFlag::enabled | SpeedPointFlag::event)) == (SpeedPointFlag::enabled | SpeedPointFlag::event) && false == point.flags.HasAny(SpeedPointFlag::pointSpeed) && eSignNext == nullptr ) { // tylko sygnał przypisujemy (a point limit isn't one) + // jeśli jeszcze nic nie zapisane tam + eSignNext = point.evEvent; // dla informacji + } + if( fNext == 0.0 ) { + break; // nie ma sensu analizować tabelki dalej + } + } + } + + // the point limits latched before, which aren't in the table any more + apply_point_limits( fVelDes, fDist, fNext, fAcc ); + + // jeśli mieliśmy ograniczenie z semafora i nie ma przed nami + if( VelSignalLast >= 0.0 + && ( false == drivingFlags.signalFound && false == drivingFlags.switchFound && false == drivingFlags.stopPointFound ) + && true == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { + VelSignalLast = -1.0; + } + // if there's unbroken speed limit through our scan table take a note of it + if( VelLimitLastDist.second > 0 + && speedlimitiscontinuous ) { + VelLimitLastDist.second = EU07_AI_SPEEDLIMITEXTENDSBEYONDSCANRANGE; + } + // take into account the effect switches have on duration of signal-imposed speed limit, in calculation of speed limit end point + // a reduced speed ends where the interlocking area does, if that is marked, and not past the switches farther on + if( auto const signallimitend { VelSignalLast > 0.0 && SignalAreaEndDist >= 0.0 ? SignalAreaEndDist : SwitchClearDist }; + VelSignalLast >= 0.0 && signallimitend >= 0.0 ) { + VelLimitLastDist.second = std::max( VelLimitLastDist.second, signallimitend ); + } + + //analiza spisanych z tabelki ograniczeń i nadpisanie aktualnego + // if stopped at a valid passenger stop, hold there + if( true == IsAtPassengerStop && mvOccupied->Vel < 0.01 ) { + fVelDes = 0.0; + } + else { + fVelDes = min_speed( fVelDes, VelSignalLast ); + fVelDes = min_speed( fVelDes, VelLimitLast ); + fVelDes = min_speed( fVelDes, VelRoad ); + fVelDes = min_speed( fVelDes, VelRestricted ); + } + // nastepnego semafora albo zwrotnicy to uznajemy, że mijamy W5 + FirstSemaphorDist = d_to_next_sem; // przepisanie znalezionej wartosci do zmiennej + return go; +}; + +bool +TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, double const Signaldistance ) { + // stop points are irrelevant when not in one of the basic modes + if( false == OrderCurrentGet().HasAny( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank ) ) { return true; } + // jeśli przystanek, trzeba obsłużyć wg rozkładu + drivingFlags.stopPointFound = true; + // the W4 and the timetable name the station each in its own file, so the two spellings are compared by their key: + // with or without the polish letters, in any case, with spaces or underscores + if( false == timetable::stop_point_is_for( Point.evEvent->input_text(), asNextStop ) ) + { // jeśli nazwa nie jest zgodna + if( false == IsScheduledPassengerStopVisible // check if our next scheduled stop didn't show up earlier in the scan + && Point.fDist < 1.15 * fBrakeDist + 300 + && Point.fDist > 0 ) // tylko jeśli W4 jest blisko, przy dwóch może zaczać szaleć + { + // porównuje do następnej stacji, więc trzeba przewinąć do poprzedniej + // nastepnie ustawić następną na aktualną tak żeby prawidłowo ją obsłużył w następnym kroku + if( true == TrainParams.RewindTimeTable( Point.evEvent->input_text() ) ) { + asNextStop = TrainParams.NextStop(); + TrainParams.StationStart = TrainParams.StationIndex; + } + } + else if( Point.fDist < -fLength ) { + // jeśli został przejechany + Point.ResetFlags(); // to można usunąć (nie mogą być usuwane w skanowaniu) + } + return true; // ignorowanie jakby nie było tej pozycji + } + else if (drivingFlags.stopPoint) // jeśli pomijanie W4, to nie sprawdza czasu odjazdu + { // tylko gdy nazwa zatrzymania się zgadza + if( OrderCurrentGet().HasAny( DriverOrder::obeyTrain | DriverOrder::bank ) ) { + // check whether the station specifies radio channel change + // NOTE: we don't do it in shunt mode, as shunting operations tend to use dedicated radio channel + // NOTE: there's a risk radio channel change was specified by a station which we skipped during timetable rewind + // we ignore this for the time being as it's not a high priority error + auto const radiochannel { TrainParams.radio_channel() }; + if( radiochannel > 0 ) { + if( iGuardRadio != 0 ) { + iGuardRadio = radiochannel; + } + if( iRadioChannel != radiochannel ) { + cue_action( driver_hint::radiochannel, radiochannel ); + } + } + } + IsScheduledPassengerStopVisible = true; // block potential timetable rewind if the next stop shows up later in the scan + if (false == TrainParams.IsStop()) + { // jeśli nie ma tu postoju + Point.fVelNext = -1; // maksymalna prędkość w tym miejscu + // przy 160km/h jedzie 44m/s, to da dokładność rzędu 5 sekund + if (Point.fDist < passengerstopmaxdistance * 0.5 ) { + // zaliczamy posterunek w pewnej odległości przed (choć W4 nie zasłania już semafora) +#if LOGSTOPS + WriteLog(std::format( + "{} as {}: at {}:{} passed {}", + pVehicle->asName, TrainParams.TrainName, simulation::Time.data().wHour, simulation::Time.data().wMinute, asNextStop)); // informacja +#endif + // przy jakim dystansie (stanie licznika) ma przesunąć na następny postój + fLastStopExpDist = mvOccupied->DistCounter + 0.250 + 0.001 * fLength; + TrainParams.UpdateMTable( simulation::Time, asNextStop ); + record_station( Point, blackbox::station_kinds::passed ); + UpdateDelayFlag(); + TrainParams.StationIndexInc(); // przejście do następnej + asNextStop = TrainParams.NextStop(); // pobranie kolejnego miejsca zatrzymania + Point.ResetFlags(); // nie liczy się już + return true; // table entry recognized and handled + } + } // koniec obsługi przelotu na W4 + else { + // zatrzymanie na W4 + // the margins of a passenger stop, whether the train is already making for it or not: the present ones + // depend on this very flag, and a check against them would turn it on and off every other scan + auto const [ stopminproximity, stopmaxproximity ] { + is_train() ? + train_proximity_margins( true ) : + std::pair{ fMinProximityDist, fMaxProximityDist } }; + if ( false == Point.bMoved ) { + // potentially shift the stop point in accordance with its defined parameters + /* + // https://rainsted.com/pl/Wersja/18.2.133#Okr.C4.99gi_dla_W4_i_W32 + Pierwszy parametr ujemny - preferowane zatrzymanie czoła składu (np. przed przejściem). + Pierwszy parametr dodatni - preferowane zatrzymanie środka składu (np. przy wiacie, przejściu podziemnym). + Drugi parametr ujemny - wskazanie zatrzymania dla krótszych składów (W32). + Drugi paramer dodatni - długość peronu (W4). + */ + auto L = 0.0; + auto Par1 = Point.evEvent->input_value(1); + auto Par2 = Point.evEvent->input_value(2); + if (Par2 >= 0 || fLength < -Par2) { //użyj tego W4 + if (Par1 < 0) { + L = -Par1; + } + else { + //środek + L = Par1 - stopminproximity - fLength * 0.5; + } + // the train comes to a stand anywhere up to the margin of a passenger stop short of this point, not + // that of the signals it may be making for when it first sees the W4, so the tail is to keep that far + // inside the platform + L = std::max(0.0, std::min(L, std::abs(Par2) - stopminproximity - fLength)); + Point.UpdateDistance(L); + Point.bMoved = true; + Point.fMoved = L; + } + else { + Point.ResetFlags(); + } + } + // for human-driven vehicles discard the stop point if they leave it far enough behind + if( false == AIControllFlag + && Point.fDist < -1 * std::max(fLength + 100, 250.0) - Point.fMoved ) { + record_station( Point, blackbox::station_kinds::missed ); + Point.ResetFlags(); // nie liczy się już zupełnie (nie wyśle SetVelocity) + Point.fVelNext = -1; // można jechać za W4 + if( Point.fDist <= 0.0 && eSignNext == Point.evEvent ) { + // sanity check, if we're held by this stop point, let us go + VelSignalLast = -1; + } + return true; + } + + IsAtPassengerStop = Point.fDist <= passengerstopmaxdistance + // Ra 2F1I: odległość plus długość pociągu musi być mniejsza od długości + // peronu, chyba że pociąg jest dłuższy, to wtedy minimalna. + // jeśli długość peronu ((sSpeedTable[i].evEvent->ValueGet(2)) nie podana, + // przyjąć odległość fMinProximityDist + && (drivingFlags.stopCloser ? + Point.fDist + fLength + (Point.fMoved - stopminproximity * 0.5f) <= std::max(std::abs(Point.evEvent->input_value(2)), + 2.0 * stopmaxproximity + fLength) : + Point.fDist < Signaldistance); + + if( !eSignNext ) { + //jeśli nie widzi następnego sygnału ustawia dotychczasową + eSignNext = Point.evEvent; + } + if( mvOccupied->Vel > EU07_AI_MOVEMENT ) { + // jeśli jedzie (nie trzeba czekać, aż się drgania wytłumią - drzwi zamykane od 1.0) to będzie zatrzymanie + Point.fVelNext = 0; + // potentially announce pending stop + if( m_lastannouncement != announcement_t::approaching + && Point.fDist < 750 + && Point.fDist > 250 ) { + announce( announcement_t::approaching ); + } + } else if( true == IsAtPassengerStop ) { + // jeśli się zatrzymał przy W4, albo stał w momencie zobaczenia W4 + if( !AIControllFlag ) { + // w razie przełączenia na AI ma nie podciągać do W4, gdy użytkownik zatrzymał za daleko + drivingFlags.stopCloser = false; + } + if (TrainParams.UpdateMTable( simulation::Time, asNextStop) ) { + // to się wykona tylko raz po zatrzymaniu na W4 + record_station( Point, blackbox::station_kinds::stopped ); + // the service flags of this stop hold for its doors and departure + m_stopflags = TrainParams.stop_flags(); + if( TrainParams.StationIndex < TrainParams.StationCount ) { + // jeśli są dalsze stacje, bez trąbienia przed odjazdem + // also ignore any horn cue that may be potentially set below 1 km/h and before the actual full stop + drivingFlags.startHorn = false; + drivingFlags.startHornNow = false; + } + UpdateDelayFlag(); + + // perform loading/unloading + // HACK: manual check if we didn't already do load exchange at this stop + // TODO: remove the check once the station system is in place + if( m_lastexchangestop != asNextStop ) { + m_lastexchangestop = asNextStop; + m_lastexchangedirection = pVehicle->DirectionGet(); + m_lastexchangeplatforms = static_cast( std::floor( std::abs( Point.evEvent->input_value( 2 ) ) ) ) % 10; + auto const exchangetime { simulation::Station.update_load( pVehicles[ end::front ], TrainParams, m_lastexchangeplatforms ) }; + WaitingSet( exchangetime ); + // announce the stop name while at it + announce( announcement_t::current ); + m_makenextstopannouncement = true; + } + + if (TrainParams.DirectionChange()) { + // jeśli "@" w rozkładzie, to wykonanie dalszych komend + // wykonanie kolejnej komendy, nie dotyczy ostatniej stacji + if (drivingFlags.pushPull) { + // SN61 ma się też nie ruszać, chyba że ma wagony + drivingFlags.stopHere = true; // EZT ma stać przy peronie + if (OrderNextGet() != DriverOrder::changeDirection) { + OrderPush(DriverOrder::changeDirection); // zmiana kierunku + OrderPush( + TrainParams.StationIndex < TrainParams.StationCount ? + DriverOrder::obeyTrain : + DriverOrder::shunt); // to dalej wg rozkładu + } + } + else { + // a dla lokomotyw... + // pozwolenie na przejechanie za W4 przed czasem i nie ma stać + drivingFlags.stopPoint = false; + drivingFlags.stopHere = false; + } + // przejście do kolejnego rozkazu (zmiana kierunku, odczepianie) + JumpToNextOrder(); + // ma nie podjeżdżać pod W4 po przeciwnej stronie + drivingFlags.stopCloser = false; + // ten W4 nie liczy się już zupełnie (nie wyśle SetVelocity) + Point.ResetFlags(); + // jechać + Point.fVelNext = -1; + // nie analizować prędkości + return true; + } + } + + if (OrderCurrentGet() & ( DriverOrder::shunt | DriverOrder::looseShunt )) { + OrderNext(DriverOrder::obeyTrain); // uruchomić jazdę pociągową + CheckVehicles(); // zmienić światła + } + + if (TrainParams.StationIndex < TrainParams.StationCount) { + // jeśli są dalsze stacje, czekamy do godziny odjazdu + if ( true == IsCargoTrain + || true == TrainParams.IsMaintenance() + || TrainParams.IsTimeToGo(simulation::Time.data().wHour, simulation::Time.data().wMinute + simulation::Time.data().wSecond * 0.0167) ) { + // z dalszą akcją czekamy do godziny odjazdu + // cargo trains and passenger trains at maintenance stop don't need to wait + IsAtPassengerStop = false; + record_station( Point, blackbox::station_kinds::ready ); + // przy jakim dystansie (stanie licznika) ma przesunąć na następny postój + fLastStopExpDist = mvOccupied->DistCounter + 0.050 + 0.001 * fLength; + TrainParams.StationIndexInc(); // przejście do następnej + asNextStop = TrainParams.NextStop(); // pobranie kolejnego miejsca zatrzymania +#if LOGSTOPS + WriteLog(std::format( + "{} as {}: at {}:{} next {}", + pVehicle->asName, TrainParams.TrainName, simulation::Time.data().wHour, simulation::Time.data().wMinute, asNextStop)); // informacja +#endif + // update consist weight, brake settings and ai braking tables + // NOTE: this calculation is expected to run after completing loading/unloading + CheckVehicles(); // nastawianie hamulca do jazdy pociągowej + + if( static_cast( std::floor( std::abs( Point.evEvent->input_value( 1 ) ) ) ) % 2 ) { + // nie podjeżdżać do semafora, jeśli droga nie jest wolna + drivingFlags.stopHere = true; + } + else { + //po czasie jedź dalej + drivingFlags.stopHere = false; + } + drivingFlags.stopCloser = true; // do następnego W4 podjechać blisko (z dociąganiem) + Point.ResetFlags(); // nie liczy się już zupełnie (nie wyśle SetVelocity) + Point.fVelNext = -1; // można jechać za W4 + if( Point.fDist <= 0.0 && eSignNext == Point.evEvent ) { + // sanity check, if we're held by this stop point, let us go + VelSignalLast = -1; + } + if( Command == TCommandType::cm_Unknown ) { // jeśli nie było komendy wcześniej + Command = TCommandType::cm_Ready; // gotów do odjazdu z W4 (semafor może zatrzymać) + } + if( false == tsGuardSignal.empty() + && true == timetable::has_conductor( m_stopflags ) ) { + // jeśli mamy głos kierownika, to odegrać + drivingFlags.guardSignal = true; + } + return true; // nie analizować prędkości + } // koniec startu z zatrzymania + else { + cue_action(driver_hint::waitdeparturetime); + if (timetable::has_conductor(m_stopflags) // no conductor, no door kept open for him + && TrainParams.IsTimeToGo(simulation::Time.data().wHour, simulation::Time.data().wMinute + simulation::Time.data().wSecond*0.0167 + 0.1)) { //if is less than 6 sec to departure + drivingFlags.guardOpenDoor = true; + GuardOpenDoor(); + } + } + } // koniec obsługi początkowych stacji + else { + // jeśli dojechaliśmy do końca rozkładu +#if LOGSTOPS + WriteLog(std::format( + "{} as {}: at {}:{} end of route.", + pVehicle->asName, TrainParams.TrainName, simulation::Time.data().wHour, simulation::Time.data().wMinute)); // informacja +#endif + asNextStop = TrainParams.NextStop(); // informacja o końcu trasy + TrainParams.NewName("none"); // czyszczenie nieaktualnego rozkładu + // koniec kursu, gasimy wyświetlacze relacji (tablice blaszane zostają) + for( auto *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { + vehicle->DestinationClear(); + } + // ma nie podjeżdżać pod W4 i ma je pomijać + drivingFlags.stopCloser = false; + if( false == drivingFlags.pushPull ) { + // if the consist can change direction through a simple cab change it doesn't need fiddling with recognition of passenger stops + drivingFlags.stopPoint = false; + } + fLastStopExpDist = -1.0f; // nie ma rozkładu, nie ma usuwania stacji + Point.ResetFlags(); // W4 nie liczy się już (nie wyśle SetVelocity) + Point.fVelNext = -1; // można jechać za W4 + if( Point.fDist <= 0.0 && eSignNext == Point.evEvent ) { + // sanity check, if we're held by this stop point, let us go + VelSignalLast = -1; + } + // wykonanie kolejnego rozkazu (Change_direction albo Shunt) + JumpToNextOrder(); + // ma się nie ruszać aż do momentu podania sygnału + drivingFlags.stopHere = true; + drivingFlags.startHorn = true; + return true; // nie analizować prędkości + } // koniec obsługi ostatniej stacji + } // vel 0, at passenger stop + else { + // HACK: momentarily deactivate W4 to trick the controller into moving closer + Point.fVelNext = -1; + } // vel 0, outside of passenger stop + } // koniec obsługi zatrzymania na W4 + } // koniec warunku pomijania W4 podczas zmiany czoła + else + { // skoro pomijanie, to jechać i ignorować W4 + Point.ResetFlags(); // W4 nie liczy się już (nie zatrzymuje jazdy) + Point.fVelNext = -1; + return true; // nie analizować prędkości + } + + return false; // +} + +// a road speed sign (W27/W27a) passed by the head stays in the table until the rear is past it too. not for cars: their +// passed events leave the table at the latest when the rear passes them (TableCheck), before the table update sees that +bool +TController::is_road_velocity_held( TSpeedPos const &Point ) const { + + return Point.flags.HasAll(SpeedPointFlag::roadSpeed) + && mvOccupied->CategoryFlag != 2 + && Point.fDist >= -fLength; +} + +// a passed event is handled once and then dropped from the table, except a road speed sign held for the rear +void +TController::TableDropPassedEvent( TSpeedPos &Point ) const { + + if( is_road_velocity_held( Point ) ) { + Point.flags |= SpeedPointFlag::roadSpeedHeld; + return; + } + Point.Clear(); +} + +// the lowest road speed of the signs past the given one that the head has passed: held until the rear is past them too, +// or passed in this very tick and not marked as held yet; -1 if there's none +double +TController::held_road_velocity_beyond( TSpeedPos const &Point ) const { + + auto lowest { -1.0 }; + for( auto const &held : sSpeedTable ) { + if( ( held.flags & ( SpeedPointFlag::enabled | SpeedPointFlag::roadSpeed ) ) != ( SpeedPointFlag::enabled | SpeedPointFlag::roadSpeed ) + || held.fDist >= 0.0 + || held.fDist <= Point.fDist ) { + continue; + } + lowest = min_speed( lowest, held.fVelNext ); + } + return lowest; +} + +// a road speed (W27/W27a) lower than the one in force holds once the head passes the sign, a higher one only once the +// whole train is past it (a car takes it from the head). the first pass after the head handles the sign as before, the +// entry is then only held for the rear: returns true for it, so the rest of the table update leaves it out +bool +TController::TableUpdateRoadVelocity( TSpeedPos &Point ) { + + if( Point.fDist >= 0.0 ) { return false; } + + if( mvOccupied->CategoryFlag == 2 ) { + VelRoad = Point.fVelNext; + return false; + } + + auto const isrearpast { Point.fDist < -fLength }; + if( isrearpast ) { + // the rear past it, but not past a sign after it the head has passed too: none of those may be exceeded, so a + // lower one (W27a 60 within a train's length after a 120) stays in force + VelRoad = min_speed( Point.fVelNext, held_road_velocity_beyond( Point ) ); + } + else if( Point.fVelNext == min_speed( Point.fVelNext, VelRoad ) ) { + VelRoad = Point.fVelNext; + } + if( false == Point.flags.HasAll(SpeedPointFlag::roadSpeedHeld) ) { + return false; + } + if( isrearpast ) { + Point.Clear(); + } + return true; +} + +// a reduced speed shown by a signal holds to the end of the interlocking area the signal guards (Ie-1), and that end is +// marked on the main track with a SignalAreaEnd event. on a track without the marker the speed holds as it did before: +// until the next signal, or until no signal, switch or stop point is left in the scan +void +TController::TableUpdateSignalAreaEnd( TSpeedPos &Point ) { + + // the switches lie in front of the marker, so the whole train has left them once its rear end is past it + if( Point.fDist >= -fLength ) { + if( SignalAreaEndDist < 0.0 + && OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { + // the table is sorted by distance, so the first marker is the nearest one + SignalAreaEndDist = Point.fDist + fLength; + } + return; + } + + // in shunting the marker stays, a train order given before the next signal still finds it + if( false == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { return; } + + // a passed signal at stop (0) keeps holding the train, only a reduced speed ends here + if( VelSignalLast > 0.0 ) { + if( Global.iWriteLogEnabled & 8 ) { + WriteLog( "Speed table update for " + OwnerName() + ", left the interlocking area at " + Point.evEvent->m_name ); + } + VelSignalLast = -1.0; + } + Point.Clear(); +} + +bool TController::point_limit_latched( basic_event const *Cell ) const { + + return std::any_of( + m_pointlimits.begin(), m_pointlimits.end(), + [&]( point_limit const &Limit ) { return Limit.source == Cell; } ); +} + +double TController::point_limit_end( glm::dvec3 const &Heading ) const { + + auto const origin { pVehicle->GetPosition() }; + auto result { 0.0 }; + auto first { true }; + for( auto const *vehicle : { pVehicles[ end::front ], pVehicles[ end::rear ] } ) { + if( vehicle == nullptr ) { continue; } + for( auto const side : { end::front, end::rear } ) { + auto const along { glm::dot( vehicle->CouplerPosition( side ) - origin, Heading ) }; + result = ( first ? along : std::max( result, along ) ); + first = false; + } + } + return result; +} + +void TController::latch_point_limit( TSpeedPos const &Point ) { + + if( point_limit_latched( Point.evEvent ) ) { return; } + m_pointlimits.push_back( + point_limit { Point.evEvent, Point.fVelNext, Point.fDist + Point.fPointDist, Point.fPointDist, travel_direction() } ); + if( Global.iWriteLogEnabled & 8 ) { + WriteLog( "Speed table update for " + OwnerName() + ", latched point limit of " + Point.evEvent->m_name + + ": " + to_string( Point.fVelNext, 0 ) + " in " + to_string( m_pointlimits.back().distance, 0 ) + " m" ); + } +} + +void TController::update_point_limits() { + + if( pVehicle == nullptr ) { return; } + auto const position { pVehicle->GetPosition() }; + if( m_pointlimitsvehicle == pVehicle ) { + auto const movement { position - m_pointlimitsposition }; + auto const length { glm::length( movement ) }; + if( length >= 200.0 ) { + // a longer jump between two updates isn't driving: the consist was moved elsewhere + m_pointlimits.clear(); + } + else if( length > 0.0 ) { + auto const step { movement / length }; + for( auto &limit : m_pointlimits ) { + if( glm::length( limit.heading ) < 0.5 ) { + // the way wasn't known when the limit was latched, the head was passing the cell + limit.heading = step; + } + auto const along { glm::dot( step, limit.heading ) }; + limit.distance += ( along >= 0.0 ? -length : length ); + // the way towards the point follows the line, step by step; a step far off it + // (a jolt of a standing vehicle) doesn't turn it + if( std::abs( along ) > 0.5 ) { + limit.heading = ( along >= 0.0 ? step : -step ); + } + } + } + } + // a change of the vehicle (another cab) starts the measure from its place + auto const vehiclechanged { m_pointlimitsvehicle != pVehicle }; + auto const previousposition { m_pointlimitsposition }; + m_pointlimitsvehicle = pVehicle; + m_pointlimitsposition = position; + // the consist, as its end vehicles and its length + auto const *front { pVehicles[ end::front ] }; + auto const *rear { pVehicles[ end::rear ] }; + auto const consistchanged { + false == ( ( front == m_pointlimitsends[ 0 ] && rear == m_pointlimitsends[ 1 ] ) + || ( front == m_pointlimitsends[ 1 ] && rear == m_pointlimitsends[ 0 ] ) ) + || std::abs( fLength - m_pointlimitslength ) > 0.5 }; + m_pointlimitsends[ 0 ] = front; + m_pointlimitsends[ 1 ] = rear; + m_pointlimitslength = fLength; + // vehicles coupled or uncoupled at the end towards the point move the head towards it or away. only a change of + // the consist counts, as the end measured from the vehicle shifts on curves. another vehicle measured from (a cab + // change, which may come with a coupling in the same order) moves the end measured before to its place + for( auto &limit : m_pointlimits ) { + if( glm::length( limit.heading ) < 0.5 ) { continue; } + auto const consistend { point_limit_end( limit.heading ) }; + if( limit.endknown && consistchanged ) { + auto const previousend { + vehiclechanged ? + limit.end + glm::dot( previousposition - position, limit.heading ) : + limit.end }; + limit.distance -= consistend - previousend; + } + limit.end = consistend; + limit.endknown = true; + } + + auto const travel { travel_direction() }; + std::erase_if( + m_pointlimits, + [&]( point_limit const &Limit ) { + // passed by the head + if( Limit.distance < 0.0 ) { + if( Global.iWriteLogEnabled & 8 ) { + WriteLog( "Speed table update for " + OwnerName() + ", passed point limit of " + Limit.source->m_name ); + } + return true; + } + // the head backed up behind the cell: the speed table reads it again if it is ahead + if( Limit.distance > Limit.celldistance + 1.0 ) { + if( Global.iWriteLogEnabled & 8 ) { + WriteLog( "Speed table update for " + OwnerName() + ", left behind point limit of " + Limit.source->m_name ); + } + return true; + } + // the cell ahead of the head again, going towards the point after backing up past the cell: it is read anew + // (not while backing up: the cell may as well be scanned from the other side) + return glm::dot( travel, Limit.heading ) > 0.0 + && std::any_of( + sSpeedTable.begin(), sSpeedTable.end(), + [&]( TSpeedPos const &Point ) { + return Point.evEvent == Limit.source + && Point.flags.HasAll(SpeedPointFlag::enabled | SpeedPointFlag::event | SpeedPointFlag::pointSpeed) + && Point.fDist > 0.0; } ); } ); +} + +void TController::apply_point_limits( double &Velocity, double &Distance, double &Next, double &Acceleration ) { + + auto const travel { travel_direction() }; + for( auto const &limit : m_pointlimits ) { + // latched with no limit, or passed (dropped at the next update) + if( limit.velocity < 0.0 || limit.distance <= 0.0 ) { continue; } + // going away from the point, or the way isn't known + if( glm::dot( travel, limit.heading ) <= 0.0 ) { continue; } + // the same as for a point of the speed table ahead + auto const v { limit.velocity }; + auto const d { limit.distance }; + auto a { ( v * v - mvOccupied->Vel * mvOccupied->Vel ) / ( 25.92 * d ) }; + if( mvOccupied->Vel < v ) { + auto const brakingdistance { 1.2 * fBrakeDist * braking_distance_multiplier( v ) }; + if( brakingdistance > 0.0 ) { + a = std::lerp( a, AccPreferred, std::clamp( ( d - brakingdistance ) / brakingdistance, 0.0, 1.0 ) ); + } + } + if( d < point_limit_approach() && v < Velocity ) { + Velocity = v; + } + if( a <= Acceleration + && ( v < Next || Next < 0 ) ) { + Acceleration = a; + Next = v; + Distance = d; + bStopTargetIsPassengerStop = false; + } + } +} + +double TController::point_limit_approach() const { + // a point limit holds at its point and not a metre beyond, so the braking curve alone leaves a slow consist + // coasting above it (the deceleration asked for is below what makes the driver brake). within the final + // approach, and five seconds of the present speed before it, the speed is held down to it already + return fMaxProximityDist + mvOccupied->Vel / 3.6 * 5.0; +} + +glm::dvec3 TController::travel_direction() const { + + if( pVehicle == nullptr || iDirection == 0 ) { return glm::dvec3 { 0.0 }; } + // the direction is given against the couplers of the vehicle the driver is in, which is the vehicle measured; + // along its own length it follows the track, where the chord of a long consist on a curve doesn't + auto const along { pVehicle->CouplerPosition( end::front ) - pVehicle->CouplerPosition( end::rear ) }; + auto const length { glm::length( along ) }; + if( length < 0.001 ) { return glm::dvec3 { 0.0 }; } + return ( iDirection > 0 ? along : -along ) / length; +} + +bool +TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPos &Point, double &Signaldistance, int const Pointindex ) { + + if( Point.flags.HasAll(SpeedPointFlag::signalAreaEnd) ) { + // not a signal: it neither sends a command nor counts as the end of a speed limit in the scan + TableUpdateSignalAreaEnd( Point ); + return true; + } + + if( Point.flags.HasAll(SpeedPointFlag::pointSpeed) ) { + // PointVelocity: no signal, no command, only the limit at its point + // done once the head passes the point + if( Point.fDist + Point.fPointDist < 0.0 ) { + if( Global.iWriteLogEnabled & 8 ) { + WriteLog( "Speed table update for " + OwnerName() + ", passed point limit of " + Point.GetName() ); + } + Point.Clear(); + return true; + } + if( Point.fDist < 0.0 ) { + if( point_limit_latched( Point.evEvent ) ) { + // a table built anew found under the consist a cell whose state holds already + Point.Clear(); + return true; + } + if( Point.fVelNext != 0.0 ) { + // the head passed the cell: what it says now holds at the point, whatever happens to the table. + // a stop at 0 stays in the table, where the cell can still release it + latch_point_limit( Point ); + Point.Clear(); + return true; + } + } + return false; + } + + // sprawdzanie eventów pasywnych miniętych + if( Point.fDist < 0.0 ) { + if( SemNextIndex == Pointindex ) { + if( Global.iWriteLogEnabled & 8 ) { + WriteLog( "Speed table update for " + OwnerName() + ", passed semaphor " + sSpeedTable[ SemNextIndex ].GetName() ); + } + SemNextIndex = npos; // jeśli minęliśmy semafor od ograniczenia to go kasujemy ze zmiennej sprawdzającej dla skanowania w przód + } + if( SemNextStopIndex == Pointindex ) { + if( Global.iWriteLogEnabled & 8 ) { + WriteLog( "Speed table update for " + OwnerName() + ", passed semaphor " + sSpeedTable[ SemNextStopIndex ].GetName() ); + } + SemNextStopIndex = npos; // jeśli minęliśmy semafor od ograniczenia to go kasujemy ze zmiennej sprawdzającej dla skanowania w przód + } + switch( Point.evEvent->input_command() ) { + // TBD, TODO: expand emergency_brake handling to a more generic security system signal + case TCommandType::cm_EmergencyBrake: { + pVehicle->RadioStop(); + Point.Clear(); // signal received, deactivate + return true; + } + case TCommandType::cm_SecuritySystemMagnet: { + // NOTE: magnet induction calculation presumes the driver is located in the front vehicle + // TBD, TODO: take into account actual position of controlled/occupied vehicle in the consist, whichever comes first + auto const magnetlocation { pVehicles[ end::front ]->MoverParameters->SecuritySystem.MagnetLocation }; + auto const magnetrange { 1.0 }; + auto const ismagnetpassed { Point.fDist < -( magnetlocation + magnetrange ) }; + if( Point.fDist < -magnetlocation && (mvOccupied->Vel > EU07_AI_NOMOVEMENT || false == ismagnetpassed) ) { + // NOTE: normally we'd activate the magnet once the leading vehicle passes it + // but on a fresh scan after direction change it would be detected as long as it's under consist, and meet the (simple) activation condition + // thus we're doing a more precise check in such situation (we presume direction change takes place only if the vehicle is standing still) + mvOccupied->SecuritySystem.set_cabsignal_lock(!AIControllFlag); // don't make life difficult for the ai, but a human driver is a fair game + PutCommand(Point.evEvent->input_text(), Point.evEvent->input_value(1), Point.evEvent->input_value(2), nullptr); + } + if( ismagnetpassed ) { + Point.Clear(); + mvOccupied->SecuritySystem.set_cabsignal_lock(false); + } + return true; + } + default: { + break; + } + } + } + // check signals ahead + if( Point.fDist > 0.0 ) { + // bail out early for signals which activate when passed + // TBD: make it an event method? + switch( Point.evEvent->input_command() ) { + case TCommandType::cm_EmergencyBrake: { + return true; + } + case TCommandType::cm_SecuritySystemMagnet: { + return true; + } + default: { + break; + } + } + + if( Point.IsProperSemaphor( OrderCurrentGet() ) ) { + // special rule for cars: ignore stop signals at distance too short to come to a stop + // as trying to stop in such situation is likely to place the car on train tracks + if( is_car() + && Point.fVelNext != -1.0 + && Point.fVelNext < 1.0 + && Point.fDist < -0.5 + std::min(fBrakeDist * 0.2, mvOccupied->Vel * 0.2) ) { + Point.Clear(); + return true; + } + // jeśli jest mienięty poprzedni semafor a wcześniej + // byl nowy to go dorzucamy do zmiennej, żeby cały czas widział najbliższy + if( SemNextIndex == npos ) { // NOSONAR + SemNextIndex = Pointindex; + if( Global.iWriteLogEnabled & 8 ) { + WriteLog( "Speed table update for " + OwnerName() + ", next semaphor is " + sSpeedTable[ SemNextIndex ].GetName() ); + } + } + if( SemNextStopIndex == npos + || ( sSpeedTable[SemNextStopIndex].fVelNext != 0 + && Point.fVelNext == 0 ) ) { + SemNextStopIndex = Pointindex; + } + } + } + if (Point.flags & SpeedPointFlag::outsideStation) + { // jeśli W5, to reakcja zależna od trybu jazdy + if (OrderCurrentGet() & DriverOrder::obeyTrain) + { // w trybie pociągowym: można przyspieszyć do wskazanej prędkości (po zjechaniu z rozjazdów) + Velocity = -1.0; // ignorować? + if ( Point.fDist < 0.0) { // jeśli wskaźnik został minięty + VelSignalLast = Velocity; //ustawienie prędkości na -1 + } + else if( ( false == drivingFlags.switchFound ) ) { // jeśli rozjazdy już minięte + VelSignalLast = Velocity; //!!! to też koniec ograniczenia + } + } + else + { // w trybie manewrowym: skanować od niego wstecz, stanąć po wyjechaniu za sygnalizator i zmienić kierunek + Velocity = 0.0; // zmiana kierunku może być podanym sygnałem, ale wypadało by zmienić światło wcześniej + if( ( false == drivingFlags.switchFound ) ) { // jeśli nie ma rozjazdu + // check for presence of a signal facing the opposite direction + // if there's one, we'll want to pass it before changing direction + basic_event *foundevent = nullptr; + if( Point.fDist - fMaxProximityDist > 0 ) { + auto scandistance{ Point.fDist + fLength - fMaxProximityDist }; + auto *scanvehicle{ pVehicles[ end::rear ] }; + auto scandirection{ scanvehicle->DirectionGet() * scanvehicle->RaDirectionGet() }; + auto *foundtrack = BackwardTraceRoute( scandistance, scandirection, scanvehicle, foundevent, -1, end::front, false ); + } + if( foundevent == nullptr ) { + drivingFlags.trackEnd = true; // to dalsza jazda trwale ograniczona (W5, koniec toru) + } + } + } + } + else if ( Point.flags & SpeedPointFlag::stopOnAutomaticBlock) { + // jeśli S1 na SBL + if( mvOccupied->Vel < 2.0 && Point.fDist < fMaxProximityDist && Obstacle.distance > 1000 ) { + // stanąć nie musi, ale zwolnić przynajmniej + // jest w maksymalnym zasięgu to można go pominąć (wziąć drugą prędkosć) + // as long as there isn't any obstacle in arbitrary view range + eSignSkip = Point.evEvent; + // jazda na widoczność - skanować możliwość kolizji i nie podjeżdżać zbyt blisko + // usunąć flagę po podjechaniu blisko semafora zezwalającego na jazdę + // ostrożnie interpretować sygnały - semafor może zezwalać na jazdę pociągu z przodu! + drivingFlags.visibility = true; + // store the ordered restricted speed and don't exceed it until the flag is cleared + VelRestricted = Point.evEvent->input_value(2); + } + if( eSignSkip != Point.evEvent ) { + // jeśli ten SBL nie jest do pominięcia to ma 0 odczytywać + Velocity = Point.evEvent->input_value( 1 ); + // TODO sprawdzić do której zmiennej jest przypisywane v i zmienić to tutaj + } + } + else if ( Point.IsProperSemaphor(OrderCurrentGet())) + { // to semaphor + if( Point.fDist < 0 ) { + // for human-driven vehicles ignore the signal if it was passed by sufficient distance + if( false == AIControllFlag + && Point.fDist < -1 * std::max(fLength + 100, 250.0) ) { + VelSignal = -1.0; + Point.Clear(); + return true; + } + // for ai-driven vehicles always play by the rules + else { + VelSignalLast = Point.fVelNext; //minięty daje prędkość obowiązującą + // a marker before this signal ends the interlocking area of an earlier signal, not the area of this one + // (a train longer than the way between the two, or one which started standing over the marker) + std::ranges::for_each( sSpeedTable | std::views::take( Pointindex ), clear_signal_area_end ); + } + } + else { + //jeśli z przodu to dajemy flagę, że jest + drivingFlags.signalFound = true; + Signaldistance = std::min( Point.fDist, Signaldistance ); + // if there's another vehicle closer to the signal, then it's likely its intended recipient + // HACK: if so, make it a stop point, to prevent non-signals farther down affect us + auto const isforsomeoneelse { is_train() && Obstacle.distance < Point.fDist }; + if( Point.fDist <= Signaldistance ) { + if( isforsomeoneelse ) { + VelSignalNext = 0.0; + Velocity = 0.0; + } + else { + VelSignalNext = Point.fVelNext; + if( Velocity < 0 ) { + Velocity = fVelMax; + VelSignal = fVelMax; + } + } + } + } + } + else if ( Point.flags & SpeedPointFlag::roadSpeed) + { // to W27/W27a + if( TableUpdateRoadVelocity( Point ) ) { + return true; + } + } + else if ( Point.flags & SpeedPointFlag::sectionSpeed && Point.fDist < 0) + { // to W9 + // teraz trzeba sprawdzić inne warunki + if (Point.fSectionVelocityDist == 0.0) + { + if (Global.iWriteLogEnabled & 8) + { + WriteLog("TableUpdate: Event is behind. SVD = 0: " + Point.evEvent->m_name); + } + Point.Clear(); // jeśli punktowy to kasujemy i nie dajemy ograniczenia na stałe + } + else if (Point.fSectionVelocityDist < 0.0) + { + // ograniczenie obowiązujące do następnego + if (Point.fVelNext == min_speed(Point.fVelNext, VelLimitLast) && Point.fVelNext != VelLimitLast) + { + // jeśli ograniczenie jest mniejsze niż obecne to obowiązuje od zaraz + VelLimitLast = Point.fVelNext; + } + else if (Point.fDist < -fLength) + { + // jeśli większe to musi wyjechać za poprzednie + VelLimitLast = Point.fVelNext; + if (Global.iWriteLogEnabled & 8) + { + WriteLog("TableUpdate: Event is behind. SVD < 0: " + Point.evEvent->m_name); + } + Point.Clear(); // wyjechaliśmy poza poprzednie, można skasować + } + } + else + { // jeśli większe to ograniczenie ma swoją długość + if (Point.fVelNext == min_speed(Point.fVelNext, VelLimitLast) && Point.fVelNext != VelLimitLast) + { + // jeśli ograniczenie jest mniejsze niż obecne to obowiązuje od zaraz + VelLimitLast = Point.fVelNext; + } + else if (Point.fDist < -fLength && Point.fVelNext != VelLimitLast) + { + // jeśli większe to musi wyjechać za poprzednie + VelLimitLast = Point.fVelNext; + } + else if (Point.fDist < -fLength - Point.fSectionVelocityDist) + { + VelLimitLast = -1.0; + if (Global.iWriteLogEnabled & 8) + { + WriteLog("TableUpdate: Event is behind. SVD > 0: " + Point.evEvent->m_name); + } + Point.Clear(); // wyjechaliśmy poza poprzednie, można skasować + } + } + } + + //sprawdzenie eventów pasywnych przed nami + { // zawalidrogi nie ma (albo pojazd jest samochodem), sprawdzić sygnał + if ( Point.flags & SpeedPointFlag::shuntSignal) // jeśli Tm - w zasadzie to sprawdzić komendę! + { // jeśli podana prędkość manewrowa + if( Velocity == 0.0 + && true == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { + // jeśli tryb pociągowy a tarcze ma ShuntVelocity 0 0 + Velocity = -1; // ignorować, chyba że prędkość stanie się niezerowa + if( true == Point.flags.HasAll(SpeedPointFlag::elapsed) ) { + // a jak przejechana to można usunąć, bo podstawowy automat usuwa tylko niezerowe + Point.Clear(); + } + } + else if( Command == TCommandType::cm_Unknown && Velocity != 0.0 ) { + // jeśli jeszcze nie ma komendy + // komenda jest tylko gdy ma jechać, bo stoi na podstawie tabelki + // jeśli nie było komendy wcześniej - pierwsza się liczy - ustawianie VelSignal + Command = TCommandType::cm_ShuntVelocity; // w trybie pociągowym tylko jeśli włącza tryb manewrowy (v!=0.0) + // Ra 2014-06: (VelSignal) nie może być tu ustawiane, bo Tm może być daleko + if (VelSignal == 0.0) + { + // aby stojący ruszył + VelSignal = Velocity; + } + if (Point.fDist < 0.0) + { + // jeśli przejechany + //!!! ustawienie, gdy przejechany jest lepsze niż wcale, ale to jeszcze nie to + VelSignal = Velocity; + // to można usunąć (nie mogą być usuwane w skanowaniu) + Point.Clear(); + } + } + } + else if( false == Point.flags.HasAny(SpeedPointFlag::sectionSpeed) ) { + //jeśli jakiś event pasywny ale nie ograniczenie + if( Command != TCommandType::cm_Unknown ) + { + } + else + { + // jeśli nie było komendy wcześniej - pierwsza się liczy - ustawianie VelSignal + if (Velocity < 0.0 || Velocity >= 1.0) + { + // bo wartość 0.1 służy do hamowania tylko + Command = TCommandType::cm_SetVelocity; // może odjechać + // Ra 2014-06: (VelSignal) nie może być tu ustawiane, bo semafor może być daleko + // VelSignal=v; //nie do końca tak, to jest druga prędkość; -1 nie wpisywać... + if (VelSignal == 0.0) + { + // aby stojący ruszył + VelSignal = -1.0; + } + if (Point.fDist < 0.0) + { + // jeśli przejechany + VelSignal = Velocity == 0.0 ? 0.0 : -1.0; + // ustawienie, gdy przejechany jest lepsze niż wcale, ale to jeszcze nie to + if (Point.flags & SpeedPointFlag::event && (Point.evEvent != eSignSkip || Point.fVelNext != VelRestricted)) + { + // jeśli event + // ale inny niż ten, na którym minięto S1, chyba że się już zmieniło + // sygnał zezwalający na jazdę wyłącza jazdę na widoczność (po S1 na SBL) + drivingFlags.visibility = false; + // remove restricted speed + VelRestricted = -1.0; + } + // jeśli nie jest ograniczeniem prędkości to można usunąć + // (nie mogą być usuwane w skanowaniu) + TableDropPassedEvent( Point ); + } + } + else if (Point.fDist > 0.0 && typeid(*Point.evEvent) == typeid(road_order)) + { + // a level crossing or a junction which holds the vehicle ahead: the road orders past it, which let the traffic + // through, aren't for this vehicle yet. without this the first of them would tell the standing vehicle to drive on + Command = TCommandType::cm_SetProximityVelocity; // taken, and not acted on + } + else if (Point.evEvent->is_command()) + { + // jeśli prędkość jest zerowa, a komórka zawiera komendę + eSignNext = Point.evEvent; // dla informacji + // make sure the command isn't for someone else + // TBD, TODO: revise this check for bank/loose_shunt; we might want to ignore obstacles with no owner in these modes + if (Point.fDist < Obstacle.distance) + { + if (true == drivingFlags.stopHere) + { + // jeśli ma stać, dostaje komendę od razu + Command = TCommandType::cm_Command; // komenda z komórki, do wykonania po zatrzymaniu + } + // NOTE: human drivers are likely to stop wherever and expect things to still work, so we give them more leeway + else if (Point.fDist <= (AIControllFlag ? fMaxProximityDist : std::max(250.0, fMaxProximityDist))) + { + // jeśli ma dociągnąć, to niech dociąga + // (moveStopCloser dotyczy dociągania do W4, nie semafora) + Command = TCommandType::cm_Command; // komenda z komórki, do wykonania po zatrzymaniu + } + } + } + } + } + } // jeśli nie ma zawalidrogi + + return false; +} + +void TController::TablePurger() +{ // odtykacz: usuwa mniej istotne pozycje ze środka tabelki, aby uniknąć zatkania + //(np. brak ograniczenia pomiędzy zwrotnicami, usunięte sygnały, minięte odcinki łuku) + if( sSpeedTable.size() < 2 ) { + return; + } + // simplest approach should be good enough for start -- just copy whatever is still relevant, then swap + auto const isexpendable = []( TSpeedPos const &Speedpoint ) { + return + false == Speedpoint.flags.HasAny( SpeedPointFlag::enabled ) + || ( ( Speedpoint.flags & ( SpeedPointFlag::elapsed | SpeedPointFlag::track | SpeedPointFlag::curve | SpeedPointFlag::switchTrack ) ) == ( SpeedPointFlag::elapsed | SpeedPointFlag::track | SpeedPointFlag::curve ) + && Speedpoint.fVelNext < 0.0 ); }; + // do a trial run first, to see if we need to bother at all + std::size_t trimcount{ 0 }; + for( std::size_t idx = 0; idx < sSpeedTable.size() - 1; ++idx ) { + // NOTE: we could break out early here, but running through entire thing gives us exact size needed for new table + if( isexpendable( sSpeedTable[ idx ] ) ) { + ++trimcount; + } + } + if( trimcount == 0 ) { + // there'd be no gain, may as well bail + return; + } + std::vector trimmedtable; trimmedtable.reserve( sSpeedTable.size() - trimcount ); + // the indices are only valid for the old table, so the new placements are recorded separately + // and assigned once the new table is complete + auto semnextindex { std::size_t( -1 ) }; + auto semnextstopindex { std::size_t( -1 ) }; + auto const trackplacement = [&]( std::size_t const Index, bool const Kept ) { + // a trimmed point leaves the index invalid, a kept one lands where the new table ends + if( Index == SemNextIndex ) { + semnextindex = ( Kept ? trimmedtable.size() : std::size_t( -1 ) ); + } + if( Index == SemNextStopIndex ) { + semnextstopindex = ( Kept ? trimmedtable.size() : std::size_t( -1 ) ); + } }; + + for( std::size_t idx = 0; idx < sSpeedTable.size() - 1; ++idx ) { + auto const &speedpoint = sSpeedTable[ idx ]; + auto const kept { false == isexpendable( speedpoint ) }; + trackplacement( idx, kept ); + if( false == kept ) { continue; } + // we're left with useful speed point record we should copy + trimmedtable.emplace_back( speedpoint ); + } + // always copy the last entry; an index pointing at it has to follow it as well + trackplacement( sSpeedTable.size() - 1, true ); + trimmedtable.emplace_back( sSpeedTable.back() ); + + SemNextIndex = semnextindex; + SemNextStopIndex = semnextstopindex; + + if( Global.iWriteLogEnabled & 8 ) { + WriteLog( "Speed table garbage collection for " + OwnerName() + " cut away " + std::to_string( trimcount ) + ( trimcount == 1 ? " record" : " records" ) ); + } + // update the data + std::swap( sSpeedTable, trimmedtable ); + iLast = sSpeedTable.size() - 1; +}; + +void TController::TableSort() { + + if( sSpeedTable.size() < 3 ) { + // we skip last slot and no point in checking if there's only one other entry + return; + } + // the last slot holds the track the scan stopped at and stays where it is. + // a single bubble pass is not enough: TableTraceRoute() adds the events of a track before the + // track itself, so a track with k scanned events lands k places too far and needs k passes + auto const sortedcount { static_cast( iLast ) }; + auto const inrange = [&]( std::size_t const Index ) { + return Index < sortedcount; }; + // the placements point at semaphor entries; remember which ones, the sort moves them around + auto const *semnextevent { inrange( SemNextIndex ) ? sSpeedTable[ SemNextIndex ].evEvent : nullptr }; + auto const *semnextstopevent { inrange( SemNextStopIndex ) ? sSpeedTable[ SemNextStopIndex ].evEvent : nullptr }; + + std::stable_sort( + std::begin( sSpeedTable ), std::begin( sSpeedTable ) + sortedcount, + []( TSpeedPos const &Left, TSpeedPos const &Right ) { + return Left.fDist < Right.fDist; } ); + + auto const relocate = [&]( basic_event const *Event, std::size_t &Index ) { + if( Event == nullptr ) { return; } + auto const lookup { + std::find_if( + std::begin( sSpeedTable ), std::begin( sSpeedTable ) + sortedcount, + [Event]( TSpeedPos const &Point ) { + return Point.evEvent == Event; } ) }; + Index = ( + lookup != std::begin( sSpeedTable ) + sortedcount ? + static_cast( std::distance( std::begin( sSpeedTable ), lookup ) ) : + std::size_t( -1 ) ); + }; + relocate( semnextevent, SemNextIndex ); + relocate( semnextstopevent, SemNextStopIndex ); +} From abf99e7d0d0bb33f7c97d5c89a253948a035511e Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sat, 28 Nov 2026 14:32:29 +0100 Subject: [PATCH 017/123] refactor(vehicle): vehicle/DynObj.cpp split into the files of its parts in vehicle/dynamic/ The 10 400 lines of the vehicle of the scenery go into vehicle/dynamic/: lifecycle.cpp made, set up from its definition, removed animations.cpp pantographs, doors, platforms, mirrors, wipers, axles destinations.cpp the destination boards, the announcements consist.cpp the neighbours, the ends, the vehicles along the couplings neighbours.cpp the vehicles near it on its track couplers.cpp coupling, uncoupling, the adapters movement.cpp moving along the track, the axles, the bogies offtrack.cpp derailed, off the track on the ground load.cpp the load and its exchange at the stops update.cpp the update of a step visual.cpp the model, the sway, the shake sounds.cpp the sounds lights.cpp the lights and their signals mmd.cpp reading the .mmd vehicletable.cpp all the vehicles of the scenery and their update Every definition moved as it was, in its original order. The macros of the file and the helpers used by several files (GetSubmodelFromName, outside, off_track_slow, off_track_clock, seconds_since) are in vehicle/dynamic/internal.h. Some functions stay very long (LoadMMediaFile 2000 lines, Update 1170, RenderSounds 815, Init 610): they are next. 1144/1144 tests, golden traces exact against staging 62f7a29b. --- CMakeLists.txt | 19 +- vehicle/DynObj.cpp | 10366 ----------------------------- vehicle/dynamic/animations.cpp | 662 ++ vehicle/dynamic/consist.cpp | 527 ++ vehicle/dynamic/couplers.cpp | 331 + vehicle/dynamic/destinations.cpp | 379 ++ vehicle/dynamic/internal.h | 80 + vehicle/dynamic/lifecycle.cpp | 889 +++ vehicle/dynamic/lights.cpp | 282 + vehicle/dynamic/load.cpp | 306 + vehicle/dynamic/mmd.cpp | 2151 ++++++ vehicle/dynamic/movement.cpp | 321 + vehicle/dynamic/neighbours.cpp | 313 + vehicle/dynamic/offtrack.cpp | 504 ++ vehicle/dynamic/sounds.cpp | 1414 ++++ vehicle/dynamic/update.cpp | 1435 ++++ vehicle/dynamic/vehicletable.cpp | 893 +++ vehicle/dynamic/visual.cpp | 780 +++ 18 files changed, 11284 insertions(+), 10368 deletions(-) delete mode 100644 vehicle/DynObj.cpp create mode 100644 vehicle/dynamic/animations.cpp create mode 100644 vehicle/dynamic/consist.cpp create mode 100644 vehicle/dynamic/couplers.cpp create mode 100644 vehicle/dynamic/destinations.cpp create mode 100644 vehicle/dynamic/internal.h create mode 100644 vehicle/dynamic/lifecycle.cpp create mode 100644 vehicle/dynamic/lights.cpp create mode 100644 vehicle/dynamic/load.cpp create mode 100644 vehicle/dynamic/mmd.cpp create mode 100644 vehicle/dynamic/movement.cpp create mode 100644 vehicle/dynamic/neighbours.cpp create mode 100644 vehicle/dynamic/offtrack.cpp create mode 100644 vehicle/dynamic/sounds.cpp create mode 100644 vehicle/dynamic/update.cpp create mode 100644 vehicle/dynamic/vehicletable.cpp create mode 100644 vehicle/dynamic/visual.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index bed372327..1d1532c6b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -81,7 +81,8 @@ file(GLOB HEADERS "*.h" "utilities/*.h" "world/*.h" "vehicle/*.h" -"vehicle/ai/*.h") +"vehicle/ai/*.h" +"vehicle/dynamic/*.h") set(GLOBAL_ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}") set(GLOBAL_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/global_include") @@ -187,7 +188,21 @@ set(SOURCES "vehicle/ai/speedtable.cpp" "vehicle/crewchange.cpp" "application/driverhints.cpp" -"vehicle/DynObj.cpp" +"vehicle/dynamic/animations.cpp" +"vehicle/dynamic/consist.cpp" +"vehicle/dynamic/couplers.cpp" +"vehicle/dynamic/destinations.cpp" +"vehicle/dynamic/lifecycle.cpp" +"vehicle/dynamic/lights.cpp" +"vehicle/dynamic/load.cpp" +"vehicle/dynamic/mmd.cpp" +"vehicle/dynamic/movement.cpp" +"vehicle/dynamic/neighbours.cpp" +"vehicle/dynamic/offtrack.cpp" +"vehicle/dynamic/sounds.cpp" +"vehicle/dynamic/update.cpp" +"vehicle/dynamic/vehicletable.cpp" +"vehicle/dynamic/visual.cpp" "EU07.cpp" "export_e3d_standalone.cpp" "export_btf_standalone.cpp" diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp deleted file mode 100644 index 7456749ff..000000000 --- a/vehicle/DynObj.cpp +++ /dev/null @@ -1,10366 +0,0 @@ -/* -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/. -*/ -/* - MaSzyna EU07 locomotive simulator - Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others - -*/ - -#include "stdafx.h" -#include "vehicle/DynObj.h" -#include "physics/mover.h" - -#include "vehicle/lightsprogrammer.h" - -#include "simulation/simulation.h" -#include "simulation/blackboxrecorder.h" -#include "rendering/lightarray.h" -#include "vehicle/Camera.h" -#include "vehicle/Train.h" -#include "vehicle/odometer.h" -#include "vehicle/pulleemode.h" -#include "vehicle/Driver.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "utilities/Globals.h" -#include "utilities/Timer.h" -#include "utilities/workerpool.h" -#include "utilities/Logs.h" -#include "utilities/glmHelpers.h" -#include "Console.h" -#include "world/Traction.h" -#include "audio/sound.h" -#include "model/MdlMngr.h" -#include "model/Model3d.h" -#include "vehicle/doorwings.h" -#include "rendering/renderer.h" -#include "editor/editorTerrainStreamer.hpp" -#include "application/uitranscripts.h" -#include "input/messaging.h" -#include "application/application.h" -#include "vehicle/Driver.h" - -// Ra: taki zapis funkcjonuje lepiej, ale może nie jest optymalny -#define vWorldFront glm::vec3(0, 0, 1) -#define vWorldUp glm::vec3(0, 1, 0) -#define vWorldLeft glm::cross(vWorldUp, vWorldFront) - -#define M_2PI 6.283185307179586476925286766559; -const float maxrot = (float)(M_PI / 3.0); // 60° - -std::string const TDynamicObject::MED_labels[] = { - "masa: ", "amax: ", "Fzad: ", "FmPN: ", "FmED: ", "FrED: ", "FzPN: ", "nPrF: " -}; - -bool TDynamicObject::bDynamicRemove { false }; - -// helper, locates submodel with specified name in specified 3d model; returns: pointer to the submodel, or null -TSubModel * -GetSubmodelFromName( TModel3d * const Model, std::string const Name ) { - - return Model ? Model->GetFromName(Name) : nullptr; -} - -//--------------------------------------------------------------------------- -void TAnimPant::common_pantograph_settings() -{ // wspólne ustawienia, liczone po przypisaniu wymiarów ramion - vPos = glm::dvec3(0, 0, 0); - fAngleL0 = glm::radians(2.8547285515689267247882521833308); - fAngleL = fAngleL0; // początkowy kąt dolnego ramienia - fAngleU0 = acos((fLenL1 * cos(fAngleL) + fHoriz) / fLenU1); // górne ramię - fAngleU = fAngleU0; // początkowy kąt - PantWys = fLenL1 * sin(fAngleL) + fLenU1 * sin(fAngleU) + fHeight; // wysokość początkowa - PantTraction = PantWys; - hvPowerWire = nullptr; - fWidthExtra = 0.381f; //(2.032m-1.027)/2 - // poza obszarem roboczym jest aproksymacja łamaną o 5 odcinkach - fHeightExtra[0] = 0.0f; //+0.0762 - fHeightExtra[1] = -0.01f; //+0.1524 - fHeightExtra[2] = -0.03f; //+0.2286 - fHeightExtra[3] = -0.07f; //+0.3048 - fHeightExtra[4] = -0.15f; //+0.3810 -} - -void TAnimPant::AKP_4E() -{ // ustawienie wymiarów dla pantografu AKP-4E - fLenL1 = 1.22; // 1.176289 w modelach - fLenU1 = 1.755; // 1.724482197 w modelach - fHoriz = 0.535; // 0.54555075 przesunięcie ślizgu w długości pojazdu względem - // osi obrotu dolnego - // ramienia - fHeight = 0.07; // wysokość ślizgu ponad oś obrotu - fWidth = 0.635; // połowa szerokości ślizgu, 0.635 dla AKP-1 i AKP-4E - common_pantograph_settings(); -}; -void TAnimPant::WBL85() -{ // ustawienie wymiarów dla pantografu WBL88 - // mnozniki animacji ramion dla pantografu WBL88 - rd1rf = 1.f; - rd2rf = 1.2; - rg1rf = 0.875; - rg2rf = 1.0; - slizgrf = 1.f; - - fLenL1 = 1.98374; - fLenU1 = 2.14199; - fHoriz = 0.142; // 0.54555075 przesunięcie ślizgu w długości pojazdu względem - // osi obrotu dolnego ramienia - fHeight = 0.09353; // wysokość ślizgu ponad oś obrotu - fWidth = 0.4969; // połowa szerokości ślizgu - common_pantograph_settings(); -}; -void TAnimPant::EC160_200() -{ // ustawienie wymiarów dla pantografow EC160 lub EC200 - // mnozniki animacji ramion dla pantografow EC160 lub EC200 - rd1rf = 1.f; - rd2rf = 0.85; - rg1rf = 1.f; - rg2rf = 1.f; // 0.833 - slizgrf = 1.f; - - fLenL1 = 1.98374; - fLenU1 = 2.14199; - fHoriz = 0.142; // 0.54555075 przesunięcie ślizgu w długości pojazdu względem - // osi obrotu dolnego ramienia - fHeight = 0.09353; // wysokość ślizgu ponad oś obrotu - fWidth = 0.4969; // połowa szerokości ślizgu - common_pantograph_settings(); -}; -void TAnimPant::DSAx() -{ // ustawienie wymiarów dla pantografow z rodziny DSA - // mnozniki animacji ramion dla pantografow z rodziny DSA - rd1rf = 1.f; - rd2rf = 1.025; - rg1rf = 0.875; - rg2rf = 1.f; - slizgrf = 1.f; - - fLenL1 = 1.98374; - fLenU1 = 2.14199; - fHoriz = 0.142; // 0.54555075 przesunięcie ślizgu w długości pojazdu względem - // osi obrotu dolnego ramienia - fHeight = 0.09353; // wysokość ślizgu ponad oś obrotu - fWidth = 0.4969; // połowa szerokości ślizgu - common_pantograph_settings(); -}; -//--------------------------------------------------------------------------- -int TAnim::TypeSet(int i, TMoverParameters currentMover, int fl) -{ // ustawienie typu animacji i zależnej od niego ilości animowanych submodeli - fMaxDist = -1.0; // normalnie nie pokazywać - switch (i) - { // maska 0x000F: ile używa wskaźników na submodele (0 gdy jeden, - // wtedy bez tablicy) - // maska 0x00F0: - // 0-osie,1-drzwi,2-obracane,3-zderzaki,4-wózki,5-pantografy,6-tłoki - // maska 0xFF00: ile używa liczb float dla współczynników i stanu - case 0: - iFlags = 0x000; - break; // 0-oś - case 1: - iFlags = 0x010; - break; // 1-drzwi - case 2: - iFlags = 0x020; - fParam = fl ? new float[fl] : nullptr; - iFlags += fl << 8; - break; // 2-wahacz, dźwignia itp. - case 3: - iFlags = 0x030; - break; // 3-zderzak - case 4: - iFlags = 0x040; - break; // 4-wózek - case 5: // 5-pantograf - 5 submodeli - iFlags = 0x055; - fParamPants = new TAnimPant(); - switch (currentMover.EnginePowerSource.CollectorParameters.PantographType) { - case TPantType::AKP_4E: - fParamPants->AKP_4E(); - break; - case TPantType::DSAx: - fParamPants->DSAx(); - break; - case TPantType::EC160_200: - fParamPants->EC160_200(); - break; - case TPantType::WBL85: - fParamPants->WBL85(); - break; - } - - break; - case 6: - iFlags = 0x068; - break; // 6-tłok i rozrząd - 8 submodeli - case 7: - iFlags = 0x070; - break; // doorstep - case 8: - iFlags = 0x080; - break; // mirror - case 9: - iFlags = 0x023; // 2: Rotating/Motion-based, 8: Uses 3 submodels - break; - default: - iFlags = 0; - } - yUpdate = nullptr; - return iFlags & 15; // ile wskaźników rezerwować dla danego typu animacji -}; - -TAnim::~TAnim() -{ // usuwanie animacji - switch (iFlags & 0xF0) - { // usuwanie struktur, zależnie ile zostało stworzonych - case 0x20: // 2-wahacz, dźwignia itp. - delete fParam; - break; - case 0x50: // 5-pantograf - delete fParamPants; - break; - default: - break; - } -}; -/* -void TAnim::Parovoz(){ - // animowanie tłoka i rozrządu parowozu -}; -*/ - - -namespace { - -// a luadestinationsign: or wasmdestinationsign: block, its script in the vehicle folder when it has no path of its own -void deserialize_script_sign( cParser &Parser, script_screens::screen_config &Sign, std::string const &Folder ) { - - Sign.deserialize( Parser ); - if( Sign.script.empty() ) { return; } - if( auto path { script_screens::screen_script_path( Folder, Sign.script ) }; path.has_value() ) { - Sign.script = std::move( *path ); - } - else { - ErrorLog( "Bad script sign: \"" + Sign.script + "\" leads outside the game's folder" ); - Sign.script.clear(); - } -} - -} // namespace - -void TDynamicObject::destination_data::deserialize( cParser &Input ) { - - while( true == deserialize_mapping( Input ) ) { - ; // all work done by while() - } -} - -bool TDynamicObject::destination_data::deserialize_mapping( cParser &Input ) { - // token can be a key or block end - auto const key { Input.getToken( true, "\n\r\t ,;[]" ) }; - - if( true == key.empty() || key == "}" ) { return false; } - - if( key == "{" ) { - script = Input.getToken(); - } - else if( key == "update:" ) { - auto const value { Input.getToken() }; - // TODO: implement - } - else if( key == "instance:" ) { - instancing = Input.getToken(); - } - else if( key == "parameters:" ) { - parameters = Input.getToken(); - } - else if( key == "background:" ) { - background = Input.getToken(); - } - - return true; -} - - -//--------------------------------------------------------------------------- -TDynamicObject * TDynamicObject::FirstFind(int &coupler_nr, CouplingSet const cf) -{ // szukanie skrajnego połączonego pojazdu w pociagu - // od strony sprzegu (coupler_nr) obiektu (start) - TDynamicObject *temp = this; - for (int i = 0; i < 300; i++) // ograniczenie do 300 na wypadek zapętlenia składu - { - if (!temp) - return nullptr; // Ra: zabezpieczenie przed ewentaulnymi błędami sprzęgów - if (false == temp->MoverParameters->Couplers[coupler_nr].CouplingFlag.HasAll(cf)) - return temp; // nic nie ma już dalej podłączone sprzęgiem cf - if (coupler_nr == end::front) - { // jeżeli szukamy od sprzęgu 0 - if (temp->PrevConnected()) // jeśli mamy coś z przodu - { - if (temp->PrevConnectedNo() == end::front) // jeśli pojazd od strony sprzęgu 0 jest odwrócony - coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu - temp = temp->PrevConnected(); // ten jest od strony 0 - } - else - return temp; // jeśli jednak z przodu nic nie ma - } - else - { - if (temp->NextConnected()) - { - if (temp->NextConnectedNo() == end::rear) // jeśli pojazd od strony sprzęgu 1 jest odwrócony - coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu - temp = temp->NextConnected(); // ten pojazd jest od strony 1 - } - else - return temp; // jeśli jednak z tyłu nic nie ma - } - } - return nullptr; // to tylko po wyczerpaniu pętli -}; - -//--------------------------------------------------------------------------- -float TDynamicObject::GetEPP() -{ // szukanie skrajnego połączonego pojazdu w pociagu - // od strony sprzegu (coupler_nr) obiektu (start) - TDynamicObject *temp = this; - int coupler_nr = 0; - double eq = 0.0; - double am = 0.0; - - for (int i = 0; i < 300; ++i) // ograniczenie do 300 na wypadek zapętlenia składu - { - if (!temp) - break; // Ra: zabezpieczenie przed ewentaulnymi błędami sprzęgów - eq += temp->MoverParameters->PipePress * temp->MoverParameters->Dim.L; - am += temp->MoverParameters->Dim.L; - if ((temp->MoverParameters->Couplers[coupler_nr].CouplingFlag & Coupling::brakeHose) != Coupling::brakeHose) - break; // nic nie ma już dalej podłączone - if (coupler_nr == 0) - { // jeżeli szukamy od sprzęgu 0 - if (temp->PrevConnected()) // jeśli mamy coś z przodu - { - if (temp->PrevConnectedNo() == end::front) // jeśli pojazd od strony sprzęgu 0 jest odwrócony - coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu - temp = temp->PrevConnected(); // ten jest od strony 0 - } - else - break; // jeśli jednak z przodu nic nie ma - } - else - { - if (temp->NextConnected()) - { - if (temp->NextConnectedNo() == end::rear) // jeśli pojazd od strony sprzęgu 1 jest odwrócony - coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu - temp = temp->NextConnected(); // ten pojazd jest od strony 1 - } - else - break; // jeśli jednak z tyłu nic nie ma - } - } - - temp = this; - coupler_nr = 1; - for (int i = 0; i < 300; i++) // ograniczenie do 300 na wypadek zapętlenia składu - { - if (!temp) - break; // Ra: zabezpieczenie przed ewentaulnymi błędami sprzęgów - eq += temp->MoverParameters->PipePress * temp->MoverParameters->Dim.L; - am += temp->MoverParameters->Dim.L; - if ((temp->MoverParameters->Couplers[coupler_nr].CouplingFlag & Coupling::brakeHose) != Coupling::brakeHose) - break; // nic nie ma już dalej podłączone - if (coupler_nr == 0) - { // jeżeli szukamy od sprzęgu 0 - if (temp->PrevConnected()) // jeśli mamy coś z przodu - { - if (temp->PrevConnectedNo() == end::front) // jeśli pojazd od strony sprzęgu 0 jest odwrócony - coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu - temp = temp->PrevConnected(); // ten jest od strony 0 - } - else - break; // jeśli jednak z przodu nic nie ma - } - else - { - if (temp->NextConnected()) - { - if (temp->NextConnectedNo() == end::rear) // jeśli pojazd od strony sprzęgu 1 jest odwrócony - coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu - temp = temp->NextConnected(); // ten pojazd jest od strony 1 - } - else - break; // jeśli jednak z tyłu nic nie ma - } - } - eq -= MoverParameters->PipePress * MoverParameters->Dim.L; - am -= MoverParameters->Dim.L; - return eq / am; -}; - -//--------------------------------------------------------------------------- -TDynamicObject * TDynamicObject::GetFirstDynamic(int cpl_type, CouplingSet const cf) -{ // Szukanie skrajnego połączonego pojazdu w pociagu - // od strony sprzegu (cpl_type) obiektu szukajacego - // Ra: wystarczy jedna funkcja do szukania w obu kierunkach - return FirstFind(cpl_type, cf); // używa referencji -}; - -void TDynamicObject::ABuSetModelShake(glm::dvec3 mShake) -{ - modelShake = mShake; -}; - -int TDynamicObject::GetPneumatic(bool front, bool red) -{ - int x, y, z; // 1=prosty, 2=skośny - if (red) - { - if (front) - { - x = btCPneumatic1.GetStatus(); - y = btCPneumatic1r.GetStatus(); - } - else - { - x = btCPneumatic2.GetStatus(); - y = btCPneumatic2r.GetStatus(); - } - } - else if (front) - { - x = btPneumatic1.GetStatus(); - y = btPneumatic1r.GetStatus(); - } - else - { - x = btPneumatic2.GetStatus(); - y = btPneumatic2r.GetStatus(); - } - z = 0; // brak węży? - if (x > 0 && y > 0) - z = 3; // dwa - if (x > 0 && y == 0) - z = 1; // lewy, brak prawego - if (x == 0 && y > 0) - z = 2; // brak lewego, prawy - - return z; -} - -void TDynamicObject::SetPneumatic(bool front, bool red) -{ - int x = 0, - ten = 0, - tamten = 0; - ten = GetPneumatic(front, red); // 1=lewy skos,2=prawy skos,3=dwa proste - if (front) - if (PrevConnected()) // pojazd od strony sprzęgu 0 - tamten = PrevConnected()->GetPneumatic(PrevConnectedNo() == end::front ? true : false, red); - if (!front) - if (NextConnected()) // pojazd od strony sprzęgu 1 - tamten = NextConnected()->GetPneumatic(NextConnectedNo() == end::front ? true : false, red); - if (ten == tamten) // jeśli układ jest symetryczny - switch (ten) - { - case 1: - x = 2; - break; // mamy lewy skos, dać lewe skosy - case 2: - x = 3; - break; // mamy prawy skos, dać prawe skosy - case 3: // wszystkie cztery na prosto - if (MoverParameters->Couplers[front ? end::front : end::rear].Render) - x = 1; - else - x = 4; - break; - } - else - { - if (ten == 2) - x = 4; - if (ten == 1) - x = 1; - if (ten == 3) - if (tamten == 1) - x = 4; - else - x = 1; - } - if (front) - { - if (red) - cp1 = x; - else - sp1 = x; - } // który pokazywać z przodu - else - { - if (red) - cp2 = x; - else - sp2 = x; - } // który pokazywać z tyłu -} - -void TDynamicObject::UpdateAxle(TAnim *pAnim) -{ // animacja osi - size_t wheel_id = pAnim->dWheelAngle; - pAnim->smAnimated->SetRotate(float3(1, 0, 0), dWheelAngle[wheel_id]); - pAnim->smAnimated->future_transform = glm::rotate((float)glm::radians(m_future_wheels_angle[wheel_id]), glm::vec3(1.0f, 0.0f, 0.0f)); -}; - -// angle of a slotted lever for given angle of the wheel, which drives the coupling rod with the pin -// all points of the coupling rod move along circles of crank radius, the lever follows the pin sliding in its slot -double TDynamicObject::slottedlever_angle( slottedlever_data const &Lever, double const Wheelangle ) { - // crank turned around X axis, the same way as the wheel - auto const wheelangle { glm::radians( Wheelangle ) }; - auto const crank { glm::dvec2( - Lever.crank.x * std::cos( wheelangle ) - Lever.crank.y * std::sin( wheelangle ), - Lever.crank.x * std::sin( wheelangle ) + Lever.crank.y * std::cos( wheelangle ) ) }; - auto const pin { Lever.pin - Lever.crank + crank }; - // angle relative to the pose of the lever in the model, which matches wheel angle 0 - return glm::degrees( std::atan2( pin.y, pin.x ) - std::atan2( Lever.pin.y, Lever.pin.x ) ); -} - -void TDynamicObject::update_slottedlevers() { - - for( auto const &lever : m_slottedlevers ) { - auto const wheelid { ( - ( lever.axle < iAnimType[ ANIM_WHEELS ] ) && ( lever.axle < static_cast( pAnimations.size() ) ) ? - pAnimations[ lever.axle ].dWheelAngle : - 1 ) }; // driving wheels and coupling rods by default - auto const angle { slottedlever_angle( lever, dWheelAngle[ wheelid ] ) }; - auto const futureangle { slottedlever_angle( lever, dWheelAngle[ wheelid ] + m_future_wheels_angle[ wheelid ] ) }; - lever.submodel->SetRotate( float3( 1, 0, 0 ), angle ); - lever.submodel->future_transform = glm::rotate( (float)glm::radians( std::remainder( futureangle - angle, 360.0 ) ), glm::vec3( 1.0f, 0.0f, 0.0f ) ); - } -} - -namespace { - -// the position of the door the animated wing belongs to: its shift or angle from closed -float door_position( TMoverParameters const &Mover, TAnim const *Animation ) { - - return Mover.Doors.instances[ ( - door_wings::on_right_side( Animation->iNumber ) ? - side::right : - side::left ) ].position; -} - -// the wing in the main model, and its namesake in the low poly interior; either can be missing -std::array wing_parts( TAnim const *Animation ) { - - return { Animation->smAnimated, Animation->smInterior }; -} - -// folding door: the smaller wing turns, the larger wing (its child) the other way, the step (child of that) under it -void fold_wing( TSubModel *Wing, door_wings::fold_angles const &Angles ) { - - if( Wing == nullptr ) { return; } - // skrzydło mniejsze - Wing->SetRotate( float3( 0, 0, 1 ), Angles.smaller ); - // skrzydło większe - auto *larger { Wing->ChildGet() }; - if( larger == nullptr ) { return; } - larger->SetRotate( float3( 0, 0, 1 ), Angles.larger ); - // podnóżek? - auto *step { larger->ChildGet() }; - if( step == nullptr ) { return; } - step->SetRotate( float3( 0, 1, 0 ), Angles.step ); -} - -} // namespace - -// animacja drzwi - przesuw -void TDynamicObject::UpdateDoorTranslate(TAnim *pAnim) { - - if( pAnim->smAnimated == nullptr ) { return; } - - auto const shift { door_wings::slide( door_position( *MoverParameters, pAnim ) ) }; - for( auto *wing : wing_parts( pAnim ) ) { - if( wing != nullptr ) { - wing->SetTranslate( shift ); - } - } -}; - -// animacja drzwi - obrót -void TDynamicObject::UpdateDoorRotate(TAnim *pAnim) { - - if( pAnim->smAnimated == nullptr ) { return; } - - auto const angle { door_position( *MoverParameters, pAnim ) }; - for( auto *wing : wing_parts( pAnim ) ) { - if( wing != nullptr ) { - wing->SetRotate( float3( 1, 0, 0 ), angle ); - } - } -}; - -// animacja drzwi - obrót -void TDynamicObject::UpdateDoorFold(TAnim *pAnim) { - - if( pAnim->smAnimated == nullptr ) { return; } - - auto const angles { door_wings::fold( door_position( *MoverParameters, pAnim ) ) }; - for( auto *wing : wing_parts( pAnim ) ) { - fold_wing( wing, angles ); - } -}; - -// animacja drzwi - odskokprzesuw -void TDynamicObject::UpdateDoorPlug(TAnim *pAnim) { - - if( pAnim->smAnimated == nullptr ) { return; } - - auto const shift { door_wings::plug( door_position( *MoverParameters, pAnim ), MoverParameters->Doors.range_out ) }; - for( auto *wing : wing_parts( pAnim ) ) { - if( wing != nullptr ) { - wing->SetTranslate( shift ); - } - } -} - -// a wing animated in its own way (animdoor: of the .mmd): as far along its own range as the door of its side is -void TDynamicObject::UpdateDoorWing( TAnim *pAnim, door_wings::wing_spec const &Spec ) { - - if( pAnim->smAnimated == nullptr ) { return; } - - auto const position { door_wings::wing_position( door_position( *MoverParameters, pAnim ), MoverParameters->Doors.range, Spec.range ) }; - for( auto *wing : wing_parts( pAnim ) ) { - if( wing == nullptr ) { continue; } - switch( Spec.type ) { - case door_wings::shift_type: { - wing->SetTranslate( door_wings::slide( position ) ); - break; - } - case door_wings::rotate_type: { - wing->SetRotate( float3( 1, 0, 0 ), position ); - break; - } - case door_wings::fold_type: { - fold_wing( wing, door_wings::fold( position ) ); - break; - } - case door_wings::plug_type: { - wing->SetTranslate( door_wings::plug( position, Spec.range_out ) ); - break; - } - default: { - break; - } - } - } -} - -void TDynamicObject::bind_door_animation( TAnim &Animation ) { - - if( auto const *spec { door_wings::find( m_doorwings, Animation.iNumber ) } ) { - Animation.yUpdate = [ this, spec = *spec ]( TAnim *pAnim ) { UpdateDoorWing( pAnim, spec ); }; - return; - } - switch( MoverParameters->Doors.type ) { // od razu zapinamy potrzebny typ animacji - case 1: - Animation.yUpdate = std::bind( &TDynamicObject::UpdateDoorTranslate, this, std::placeholders::_1 ); - break; - case 2: - Animation.yUpdate = std::bind( &TDynamicObject::UpdateDoorRotate, this, std::placeholders::_1 ); - break; - case 3: - Animation.yUpdate = std::bind( &TDynamicObject::UpdateDoorFold, this, std::placeholders::_1 ); - break; // obrót 3 kolejnych submodeli - case 4: - Animation.yUpdate = std::bind( &TDynamicObject::UpdateDoorPlug, this, std::placeholders::_1 ); - break; - default: - break; - } -} - -void TDynamicObject::UpdatePant(TAnim *pAnim) -{ // animacja pantografu - 4 obracane ramiona, ślizg piąty - float a, b, c; - a = glm::degrees(pAnim->fParamPants->fAngleL - pAnim->fParamPants->fAngleL0); - b = glm::degrees(pAnim->fParamPants->fAngleU - pAnim->fParamPants->fAngleU0); - c = a + b; - if (pAnim->smElement[0]) - pAnim->smElement[0]->SetRotate(float3(-1, 0, 0), a); // dolne ramie 1 - if (pAnim->smElement[1]) - pAnim->smElement[1]->SetRotate(float3(1, 0, 0), a * pAnim->fParamPants->rd2rf); // dolne ramie 2 - if (pAnim->smElement[2]) - pAnim->smElement[2]->SetRotate(float3(1, 0, 0), c); // górne ramie 1 - if (pAnim->smElement[3]) - pAnim->smElement[3]->SetRotate(float3(-1, 0, 0), c * pAnim->fParamPants->rg2rf); // gorne ramie 2 - if (pAnim->smElement[4]) - pAnim->smElement[4]->SetRotate(float3(-1, 0, 0), b * pAnim->fParamPants->slizgrf); // ślizg -} - -// doorstep animation, shift -void TDynamicObject::UpdatePlatformTranslate( TAnim *pAnim ) { - - if( pAnim->smAnimated == nullptr ) { return; } - - auto const &door { MoverParameters->Doors.instances[ ( - ( pAnim->iNumber & 1 ) == 0 ? - side::right : - side::left ) ] }; - - pAnim->smAnimated->SetTranslate( - glm::vec3{ - std::lerp( 0.f, MoverParameters->Doors.step_range, door.step_position ), - 0.0, - 0.0 } ); -} - -// doorstep animation, rotate -void TDynamicObject::UpdatePlatformRotate( TAnim *pAnim ) { - - if( pAnim->smAnimated == nullptr ) { return; } - - auto const &door { MoverParameters->Doors.instances[ ( - ( pAnim->iNumber & 1 ) == 0 ? - side::right : - side::left ) ] }; - - pAnim->smAnimated->SetRotate( - float3( 0, 1, 0 ), - std::lerp( 0.f, MoverParameters->Doors.step_range, door.step_position ) ); -} - -// mirror animation, rotate -void TDynamicObject::UpdateMirror( TAnim *pAnim ) { - - if( pAnim->smAnimated == nullptr ) { return; } - - // only animate the mirror if it's located on the same end of the vehicle as the active cab - auto const isactive { ( - MoverParameters->CabOccupied > 0 ? ( pAnim->iNumber >> 4 == end::front ? 1.0 : 0.0 ) : - MoverParameters->CabOccupied < 0 ? ( pAnim->iNumber >> 4 == end::rear ? 1.0 : 0.0 ) : - 0.0 ) }; - - if( pAnim->iNumber & 1 ) - pAnim->smAnimated->SetRotate( - float3( 0, 1, 0 ), - std::lerp( 0.0, MoverParameters->MirrorMaxShift, dMirrorMoveR * isactive ) ); - else - pAnim->smAnimated->SetRotate( - float3( 0, 1, 0 ), - std::lerp( 0.0, MoverParameters->MirrorMaxShift, dMirrorMoveL * isactive ) ); -} - -// wipers -void TDynamicObject::UpdateWiper(TAnim* pAnim) -{ - if (!pAnim || !pAnim->smElement) - return; - - int i = pAnim->iNumber; - // odwaramy animacje dla parzystych indexow - const double rotateAngle = (i + 1) % 2 == 0 ? -MoverParameters->WiperAngle : MoverParameters->WiperAngle; - - if (pAnim->smElement[0]) // ramie 1 - pAnim->smElement[0]->SetRotate(float3(0, 1, 0), smoothInterpolate(0.0, rotateAngle, dWiperPos[i])); - if (pAnim->smElement[1]) // ramie 2 - pAnim->smElement[1]->SetRotate(float3(0, 1, 0), smoothInterpolate(0.0, rotateAngle, dWiperPos[i])); - if (pAnim->smElement[2]) // pioro - pAnim->smElement[2]->SetRotate(float3(0, 1, 0), smoothInterpolate(0.0, -rotateAngle, dWiperPos[i])); -} - -/* -void TDynamicObject::UpdateLeverDouble(TAnim *pAnim) -{ // animacja gałki zależna od double - pAnim->smAnimated->SetRotate(float3(1, 0, 0), pAnim->fSpeed * *pAnim->fDoubleBase); -}; -void TDynamicObject::UpdateLeverFloat(TAnim *pAnim) -{ // animacja gałki zależna od float - pAnim->smAnimated->SetRotate(float3(1, 0, 0), pAnim->fSpeed * *pAnim->fFloatBase); -}; -void TDynamicObject::UpdateLeverInt(TAnim *pAnim) -{ // animacja gałki zależna od int - pAnim->smAnimated->SetRotate(float3(1, 0, 0), pAnim->fSpeed * *pAnim->iIntBase); -}; -void TDynamicObject::UpdateLeverEnum(TAnim *pAnim) -{ // ustawienie kąta na - // wartość wskazaną przez - // int z tablicy fParam - // pAnim->fParam[0]; - dodać lepkość - pAnim->smAnimated->SetRotate(float3(1, 0, 0), pAnim->fParam[*pAnim->iIntBase]); -}; -*/ -// sets light levels for registered interior sections -void -TDynamicObject::toggle_lights() { - - if( true == SectionLightsActive ) { - // switch all lights off... - for( auto §ion : Sections ) { - auto const sectionname { section.compartment->pName }; - if( sectionname.rfind( "cab", 0 ) != 0 ) { - section.light_level = 0.0; - } - } - SectionLightsActive = false; - } - else { - // set lights with probability depending on the compartment type. TODO: expose this in .mmd file - for( auto §ion : Sections ) { - - auto const sectionname { section.compartment->pName }; - if( sectionname.find("corridor") == 0 - || sectionname.find("korytarz") == 0 ) { - // corridors are lit 100% of time - section.light_level = 0.75f; - } - else if( - sectionname.find("compartment") == 0 - || sectionname.find("przedzial") == 0 ) { - // compartments are lit with 75% probability - section.light_level = Random() < 0.75 ? 0.75f : 0.10f; - } - } - SectionLightsActive = true; - } -} - -void -TDynamicObject::set_cab_lights( int const Cab, float const Level ) { - - for( auto §ion : Sections ) { - // cab compartments are placed at the beginning of the list, so we can bail out as soon as we find different compartment type - auto const sectionname { section.compartment->pName }; - if( sectionname.size() < 4 ) { return; } - if( sectionname.find( "cab" ) != 0 ) { return; } - if( sectionname[ 3 ] != Cab + '0' ) { continue; } // match the cab with correct index - - section.light_level = Level; - } -} - -// aktualizujemy submodele w zaleznosci od aktualnej pory roku -void TDynamicObject::on_season_update() -{ - if (sm_winter_variant != nullptr) // pokazujemy wariant zimowy - sm_winter_variant->SetVisibilityLevel(Global.Season == "winter:" ? 1 : 0, true, false); - if (sm_spring_variant != nullptr) // pokazujemy wariant wiosenny - sm_spring_variant->SetVisibilityLevel(Global.Season == "spring:" ? 1 : 0, true, false); - if (sm_summer_variant != nullptr) // pokazujemy wariant letni - sm_summer_variant->SetVisibilityLevel(Global.Season == "summer:" ? 1 : 0, true, false); - if (sm_autumn_variant != nullptr) // pokazujemy wariant jesienny - sm_autumn_variant->SetVisibilityLevel(Global.Season == "autumn:" ? 1 : 0, true, false); -} - -// ABu 29.01.05 przeklejone z render i renderalpha: ********************* -void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) -{ // ABu290105: pozbierane i uporzadkowane powtarzajace - // sie rzeczy z Render i RenderAlpha - // dodatkowy warunek, if (ObjSqrDist<...) zeby niepotrzebnie nie zmianiec w - // obiektach, - // ktorych i tak nie widac - // NBMX wrzesien, MC listopad: zuniwersalnione - btnOn = false; // czy przywrócić stan domyślny po renderowaniu - - // the submodels set below are shared with whatever else is drawn with the same models - for( auto *model : { mdModel, mdLoad, mdLowPolyInt, mdKabina } ) { - if( model != nullptr ) { - model->state_changed(); - } - } - for( auto *model : mdAttachments ) { - if( model != nullptr ) { - model->state_changed(); - } - } - - if (mdLoad) // tymczasowo ładunek na poziom podłogi - if (vFloor.z > 0.0) - mdLoad->GetSMRoot()->SetTranslate(modelShake + vFloor); - - // model jest współdzielony przez pojazdy, a pora roku może się zmienić w trakcie symulacji - if (Global.UpdateMaterials) - on_season_update(); - - if (ObjSqrDist < 400 * 400 ) // gdy bliżej niż 400m - { - for( auto &animation : pAnimations ) { - // wykonanie kolejnych animacji - if( ObjSqrDist < animation.fMaxDist - && animation.yUpdate ) { - // jeśli zdefiniowana funkcja aktualizacja animacji (położenia submodeli - animation.yUpdate( &animation ); - } - } - update_slottedlevers(); - - if( mdModel != nullptr - && ObjSqrDist < 50 * 50 ) { - // gdy bliżej niż 50m - // ABu290105: rzucanie pudlem - // te animacje wymagają bananów w modelach! - mdModel->GetSMRoot()->SetTranslate(modelShake); - if (mdKabina) - mdKabina->GetSMRoot()->SetTranslate(modelShake); - if (mdLoad) - mdLoad->GetSMRoot()->SetTranslate(modelShake + vFloor); - if (mdLowPolyInt) - mdLowPolyInt->GetSMRoot()->SetTranslate(modelShake); - // ABu: koniec rzucania - // ABu011104: liczenie obrotow wozkow - ABuBogies(); - // Mczapkie-100402: rysowanie lub nie - sprzegow - // ABu-240105: Dodatkowy warunek: if (...).Render, zeby rysowal tylko jeden z polaczonych sprzegow - // display _on if connected with another vehicle and the coupling owner (render flag) - // display _xon if connected with another vehicle and not the coupling owner - // display _xon if not connected, but equipped with coupling adapter - // display _off if not connected, not equipped with coupling adapter or if _xon model is missing - if( MoverParameters->Couplers[ end::front ].CouplingFlag.HasAll(Coupling::coupler) ) { - if( MoverParameters->Couplers[ end::front ].Render ) { - btCoupler1.TurnOn(); - } - else { - btCoupler1.TurnxOnWithOffAsFallback(); - } - btnOn = true; - } - else { - if( true == MoverParameters->Couplers[ end::front ].has_adapter() ) { - btCoupler1.TurnxOnWithOffAsFallback(); - btnOn = true; - } - } - if( MoverParameters->Couplers[ end::rear ].CouplingFlag.HasAll(Coupling::coupler) ) { - if( MoverParameters->Couplers[ end::rear ].Render ) { - btCoupler2.TurnOn(); - } - else { - btCoupler2.TurnxOnWithOffAsFallback(); - } - btnOn = true; - } - else { - if( true == MoverParameters->Couplers[ end::rear ].has_adapter() ) { - btCoupler2.TurnxOnWithOffAsFallback(); - btnOn = true; - } - } - //******************************************************************************** - // przewody powietrzne j.w., ABu: decyzja czy rysowac tylko na podstawie - // 'render' - juz - // nie - // przewody powietrzne, yB: decyzja na podstawie polaczen w t3d - if (Global.bnewAirCouplers) - { - SetPneumatic(false, false); // wczytywanie z t3d ulozenia wezykow - SetPneumatic(true, false); // i zapisywanie do zmiennej - SetPneumatic(true, true); // ktore z nich nalezy - SetPneumatic(false, true); // wyswietlic w tej klatce - - if (MoverParameters->Couplers[end::front].CouplingFlag.HasAll(Coupling::brakeHose)) - { - switch (cp1) - { - case 1: - btCPneumatic1.TurnOn(); - break; - case 2: - btCPneumatic1.TurnxOn(); - break; - case 3: - btCPneumatic1r.TurnxOn(); - break; - case 4: - btCPneumatic1r.TurnOn(); - break; - } - btnOn = true; - } - - if (MoverParameters->Couplers[end::rear].CouplingFlag.HasAll(Coupling::brakeHose)) - { - switch (cp2) - { - case 1: - btCPneumatic2.TurnOn(); - break; - case 2: - btCPneumatic2.TurnxOn(); - break; - case 3: - btCPneumatic2r.TurnxOn(); - break; - case 4: - btCPneumatic2r.TurnOn(); - break; - } - btnOn = true; - } - - // przewody zasilajace, j.w. (yB) - if (MoverParameters->Couplers[end::front].CouplingFlag.HasAll(Coupling::mainHose)) - { - switch (sp1) - { - case 1: - btPneumatic1.TurnOn(); - break; - case 2: - btPneumatic1.TurnxOn(); - break; - case 3: - btPneumatic1r.TurnxOn(); - break; - case 4: - btPneumatic1r.TurnOn(); - break; - } - btnOn = true; - } - - if (MoverParameters->Couplers[end::rear].CouplingFlag.HasAll(Coupling::mainHose)) - { - switch (sp2) - { - case 1: - btPneumatic2.TurnOn(); - break; - case 2: - btPneumatic2.TurnxOn(); - break; - case 3: - btPneumatic2r.TurnxOn(); - break; - case 4: - btPneumatic2r.TurnOn(); - break; - } - btnOn = true; - } - } - //*********************************************************************************/ - else // po staremu ABu'oewmu - { - // przewody powietrzne j.w., ABu: decyzja czy rysowac tylko na podstawie - // 'render' - if (MoverParameters->Couplers[end::front].CouplingFlag.HasAll(Coupling::brakeHose)) - { - if (MoverParameters->Couplers[end::front].Render) - btCPneumatic1.TurnOn(); - else - btCPneumatic1r.TurnOn(); - btnOn = true; - } - - if (MoverParameters->Couplers[end::rear].CouplingFlag.HasAll(Coupling::brakeHose)) - { - if (MoverParameters->Couplers[end::rear].Render) - btCPneumatic2.TurnOn(); - else - btCPneumatic2r.TurnOn(); - btnOn = true; - } - - // przewody powietrzne j.w., ABu: decyzja czy rysowac tylko na podstawie - // 'render' - // //yB - zasilajace - if (MoverParameters->Couplers[0].CouplingFlag.HasAll(Coupling::mainHose)) - { - if (MoverParameters->Couplers[0].Render) - btPneumatic1.TurnOn(); - else - btPneumatic1r.TurnOn(); - btnOn = true; - } - - if (MoverParameters->Couplers[1].CouplingFlag.HasAll(Coupling::mainHose)) - { - if (MoverParameters->Couplers[1].Render) - btPneumatic2.TurnOn(); - else - btPneumatic2r.TurnOn(); - btnOn = true; - } - } - //*************************************************************/// koniec - // wezykow - // uginanie zderzakow - for (int i = 0; i < 2; ++i) { - - if( MoverParameters->Couplers[ i ].has_adapter() ) { - // HACK: if there's coupler adapter on this side, we presume there's additional distance put between vehicles - // which prevents buffers from clashing against each other (or the other vehicle doesn't have buffers to begin with) - continue; - } - - auto const dist { safe_clamp( MoverParameters->Couplers[ i ].Dist / 2.0, -MoverParameters->Couplers[ i ].DmaxB, 0.0 ) }; - - if( dist >= 0.0 ) { continue; } - - if( smBuforLewy[ i ] ) { - smBuforLewy[ i ]->SetTranslate( glm::vec3( dist, 0, 0 ) ); - } - if( smBuforPrawy[ i ] ) { - smBuforPrawy[ i ]->SetTranslate( glm::vec3( dist, 0, 0 ) ); - } - } - } // vehicle within 50m - - // Winger 160204 - podnoszenie pantografow - - // przewody sterowania ukrotnionego - if (MoverParameters->Couplers[0].CouplingFlag.HasAll(Coupling::control)) - { - btCCtrl1.Turn( true ); - btnOn = true; - } - // else btCCtrl1.TurnOff(); - if (MoverParameters->Couplers[1].CouplingFlag.HasAll(Coupling::control)) - { - btCCtrl2.Turn( true ); - btnOn = true; - } - // else btCCtrl2.TurnOff(); - // McZapkie-181103: mostki przejsciowe - if (MoverParameters->Couplers[0].CouplingFlag.HasAll(Coupling::gangway)) - { - btCPass1.Turn( true ); - btnOn = true; - } - // else btCPass1.TurnOff(); - if (MoverParameters->Couplers[1].CouplingFlag.HasAll(Coupling::gangway)) - { - btCPass2.Turn( true ); - btnOn = true; - } - // else btCPass2.TurnOff(); - if (MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable) - { // sygnaly konca pociagu - if (m_endsignals1.Active()) { - if (TestFlag(MoverParameters->iLights[end::front], light::redmarker_left | light::redmarker_right ) ) { - m_endsignals1.Turn( true ); - btnOn = true; - } - } - else { - if (TestFlag(MoverParameters->iLights[end::front], light::redmarker_left) && !HeadlightsAoff) - { - m_endsignal13.Turn( true ); - btnOn = true; - } - if (TestFlag(MoverParameters->iLights[end::front], light::redmarker_right) && !HeadlightsAoff) - { - m_endsignal12.Turn( true ); - btnOn = true; - } - } - if (m_endsignals2.Active()) { - if (TestFlag(MoverParameters->iLights[end::rear], light::redmarker_left | light::redmarker_right ) ) { - m_endsignals2.Turn( true ); - btnOn = true; - } - } - else { - if (TestFlag(MoverParameters->iLights[end::rear], light::redmarker_left) && !HeadlightsBoff) - { - m_endsignal23.Turn( true ); - btnOn = true; - } - if (TestFlag(MoverParameters->iLights[end::rear], light::redmarker_right) && !HeadlightsBoff) - { - m_endsignal22.Turn( true ); - btnOn = true; - } - } - } - // tablice blaszane: - if (TestFlag(MoverParameters->iLights[end::front], light::rearendsignals)) { - m_endtab1.Turn( true ); - btnOn = true; - } - // else btEndSignalsTab1.TurnOff(); - if (TestFlag(MoverParameters->iLights[end::rear], light::rearendsignals)) { - m_endtab2.Turn( true ); - btnOn = true; - } - // destination signs - update_destinations(); - // else btEndSignalsTab2.TurnOff(); - // McZapkie-181002: krecenie wahaczem (korzysta z kata obrotu silnika) - if (iAnimType[ANIM_LEVERS]) - for (int i = 0; i < 4; ++i) - if (smWahacze[i]) - smWahacze[i]->SetRotate(float3(1, 0, 0), - fWahaczeAmp * cos(MoverParameters->eAngle)); - - // cooling shutters - // NOTE: shutters display _on state when they're closed, _off otherwise - if( true == MoverParameters->dizel_heat.water.config.shutters - && false == MoverParameters->dizel_heat.zaluzje1 ) { - btShutters1.Turn( true ); - btnOn = true; - } - if( true == MoverParameters->dizel_heat.water_aux.config.shutters - && false == MoverParameters->dizel_heat.zaluzje2 ) { - btShutters2.Turn( true ); - btnOn = true; - } - - // only external models ( external_only_on / external_only_off ) - btExteriorOnly.Turn(!bDisplayCab); // display only when cab is not rendered - - if( false == bDisplayCab // edge case, lowpoly may act as a stand-in for the hi-fi cab, so make sure not to show the driver when inside - && Mechanik != nullptr - && Mechanik->action() != TAction::actSleep ) { - // rysowanie figurki mechanika - btMechanik1.Turn(MoverParameters->CabOccupied > 0); - btMechanik2.Turn( MoverParameters->CabOccupied < 0 ); - if( MoverParameters->CabOccupied != 0 ) { - btnOn = true; - } - } - - } // vehicle within 400m - - if( MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable ) - { // sygnały czoła pociagu //Ra: wyświetlamy bez - // ograniczeń odległości, by były widoczne z - // daleka - - if (TestFlag(MoverParameters->iLights[end::front], light::headlight_left) - && !HeadlightsAoff && !HighBeamLights) - { - if( DimHeadlights ) { - m_headlamp13.TurnxOnWithOnAsFallback(); - } - else { - m_headlamp13.TurnOn(); - } - btnOn = true; - } - if (TestFlag(MoverParameters->iLights[end::front], light::headlight_upper) - && !HeadlightsAoff) - { - if( DimHeadlights ) { - m_headlamp11.TurnxOnWithOnAsFallback(); - } - else { - m_headlamp11.TurnOn(); - } - btnOn = true; - } - if (TestFlag(MoverParameters->iLights[end::front], light::headlight_right) - && !HeadlightsAoff && !HighBeamLights) - { - if( DimHeadlights ) { - m_headlamp12.TurnxOnWithOnAsFallback(); - } - else { - m_headlamp12.TurnOn(); - } - btnOn = true; - } - // else btHeadSignals13.TurnOff(); - if (TestFlag(MoverParameters->iLights[end::rear], light::headlight_left) - && !HeadlightsBoff && !HighBeamLights) - { - if( DimHeadlights ) { - m_headlamp23.TurnxOnWithOnAsFallback(); - } - else { - m_headlamp23.TurnOn(); - } - btnOn = true; - } - if (TestFlag(MoverParameters->iLights[end::rear], light::headlight_upper) - && !HeadlightsBoff) - { - if( DimHeadlights ) { - m_headlamp21.TurnxOnWithOnAsFallback(); - } - else { - m_headlamp21.TurnOn(); - } - btnOn = true; - } - if (TestFlag(MoverParameters->iLights[end::rear], light::headlight_right) - && !HeadlightsBoff && !HighBeamLights) - { - if( DimHeadlights ) { - m_headlamp22.TurnxOnWithOnAsFallback(); - } - else { - m_headlamp22.TurnOn(); - } - btnOn = true; - } - // auxiliary lights - if (TestFlag(MoverParameters->iLights[end::front], light::auxiliary_left) && !HeadlightsAoff) - { - if( DimHeadlights ) { - m_headsignal13.TurnxOnWithOnAsFallback(); - } - else { - m_headsignal13.TurnOn(); - } - btnOn = true; - } - if (TestFlag(MoverParameters->iLights[end::front], light::auxiliary_right) && !HeadlightsAoff) - { - if( DimHeadlights ) { - m_headsignal12.TurnxOnWithOnAsFallback(); - } - else { - m_headsignal12.TurnOn(); - } - btnOn = true; - } - if (TestFlag(MoverParameters->iLights[end::rear], light::auxiliary_left) && !HeadlightsBoff) - { - if( DimHeadlights ) { - m_headsignal23.TurnxOnWithOnAsFallback(); - } - else { - m_headsignal23.TurnOn(); - } - btnOn = true; - } - if (TestFlag(MoverParameters->iLights[end::rear], light::auxiliary_right) && !HeadlightsBoff) - { - if( DimHeadlights ) { - m_headsignal22.TurnxOnWithOnAsFallback(); - } - else { - m_headsignal22.TurnOn(); - } - btnOn = true; - } - - // logika dlugich - if (TestFlag(MoverParameters->iLights[end::front], light::headlight_left) - && !HeadlightsAoff && HighBeamLights) - m_highbeam13.TurnxOnWithOnAsFallback(); - else - m_highbeam13.TurnOff(); - - if (TestFlag(MoverParameters->iLights[end::front], light::headlight_right) - && !HeadlightsAoff && HighBeamLights) - m_highbeam12.TurnxOnWithOnAsFallback(); - else - m_highbeam12.TurnOff(); - - // i to samo od dupy strony - if (TestFlag(MoverParameters->iLights[end::rear], light::headlight_left) - && !HeadlightsBoff && HighBeamLights) - m_highbeam23.TurnxOnWithOnAsFallback(); - else - m_highbeam23.TurnOff(); - - if (TestFlag(MoverParameters->iLights[end::rear], light::headlight_right) - && !HeadlightsBoff && HighBeamLights) - m_highbeam22.TurnxOnWithOnAsFallback(); - else - m_highbeam22.TurnOff(); - } - // interior light levels - auto sectionlightcolor { glm::vec4( 1.f ) }; - bool cabsection{ true }; - for( auto const §ion : Sections ) { - if( cabsection ) { - // check whether we're still processing cab sections - auto const §ionname { section.compartment->pName }; - cabsection &= sectionname.size() >= 4 && sectionname.starts_with("cab"); - } - // TODO: add cablight devices - auto const sectionlightlevel { section.light_level * ( cabsection ? 1.0f : MoverParameters->CompartmentLights.intensity ) }; - sectionlightcolor = glm::vec4( - sectionlightlevel == 0.f || Global.fLuminance > section.compartment->fLight ? - glm::vec3(240.f / 255.f) : // TBD: save and restore initial submodel diffuse instead of enforcing one? - InteriorLight, // TODO: per-compartment (type) light color - sectionlightlevel ); - section.compartment->SetLightLevel( sectionlightcolor, true ); - if( section.load != nullptr ) { - section.load->SetLightLevel( sectionlightcolor, true ); - } - } - // load chunks visibility - for( auto const §ion : Sections ) { - // section isn't guaranteed to have load model, so check that first - if( section.load == nullptr ) { continue; } - section.load->iVisible = section.load_chunks_visible > 0; - // if the section root isn't visible we can skip meddling with its children - if( false == section.load->iVisible ) { continue; } - // if the section root is visible set the state of section chunks - auto *sectionchunk { section.load->ChildGet() }; - auto visiblechunkcount { section.load_chunks_visible }; - while( sectionchunk != nullptr ) { - sectionchunk->iVisible = visiblechunkcount > 0; - --visiblechunkcount; - sectionchunk = sectionchunk->NextGet(); - } - } - - // driver cabs visibility - for( int cabidx = 0; cabidx < LowPolyIntCabs.size(); ++cabidx ) { - if( LowPolyIntCabs[ cabidx ] == nullptr ) { continue; } - LowPolyIntCabs[ cabidx ]->iVisible = mdKabina == nullptr ? true : // there's no hi-fi cab - bDisplayCab == false ? true : // we're in external view - simulation::Train == nullptr ? true : // not a player-driven vehicle, implies external view - simulation::Train->Dynamic() != this ? true : // not a player-driven vehicle, implies external view - JointCabs ? false : // internal view, all cabs share the model so hide them 'all' - simulation::Train->iCabn != cabidx; // internal view, hide occupied cab and show others - } -} -// ABu 29.01.05 koniec przeklejenia ************************************* - -TDynamicObject * TDynamicObject::ABuFindNearestObject(glm::vec3 pos, TTrack *Track, TDynamicObject *MyPointer, int &CouplNr) -{ - // zwraca wskaznik do obiektu znajdujacego sie na torze (Track), którego sprzęg jest najblizszy punktowi - // służy np. do łączenia i rozpinania sprzęgów - // WE: Track - tor, na ktorym odbywa sie poszukiwanie - // MyPointer - wskaznik do obiektu szukajacego - // WY: CouplNr - który sprzęg znalezionego obiektu jest bliższy kamerze - - // Uwaga! Jesli CouplNr==-2 to szukamy njblizszego obiektu, a nie sprzegu!!! - for( auto dynamic : Track->Dynamics ) { - - if( CouplNr == -2 ) { - // wektor [kamera-obiekt] - poszukiwanie obiektu - // length2 is better than length for comparing because it does not require sqrt function - if (glm::length2(glm::dvec3(pos) - dynamic->vPosition) < sq(10.0)) - { - // 10 metrów - return dynamic; - } - } - else { - // jeśli (CouplNr) inne niz -2, szukamy sprzęgu - // length2 is better than length for comparing because it does not require sqrt function - if (glm::length2(glm::dvec3(pos) - dynamic->vCoulpler[0]) < sq(5.0)) { - // 5 metrów - CouplNr = 0; - return dynamic; - } - // length2 is better than length for comparing because it does not require sqrt function - if (glm::length2(glm::dvec3(pos) - dynamic->vCoulpler[1]) < sq(5.0)) { - // 5 metrów - CouplNr = 1; - return dynamic; - } - } - } - // empty track or nothing found - return nullptr; -} - -TDynamicObject * TDynamicObject::ABuScanNearestObject(glm::vec3 pos, TTrack *Track, double ScanDir, double ScanDist, int &CouplNr) -{ // skanowanie toru w poszukiwaniu obiektu najblizszego punktowi - if (ABuGetDirection() < 0) - ScanDir = -ScanDir; - TDynamicObject *FoundedObj; - FoundedObj = - ABuFindNearestObject(pos, Track, this, CouplNr); // zwraca numer sprzęgu znalezionego pojazdu - if (FoundedObj == nullptr && Track != nullptr) - { - double ActDist; // Przeskanowana odleglosc. - double CurrDist = 0; // Aktualna dlugosc toru. - if (ScanDir >= 0) - ActDist = - Track->Length() - RaTranslationGet(); //???-przesunięcie wózka względem Point1 toru - else - ActDist = RaTranslationGet(); // przesunięcie wózka względem Point1 toru - while (ActDist < ScanDist) - { - ActDist += CurrDist; - if (ScanDir > 0) // do przodu - { - if (Track->iNextDirection) // NOSONAR - { - Track = Track->CurrentNext(); - ScanDir = -ScanDir; - } - else - Track = Track->CurrentNext(); - } - else // do tyłu - { - if (Track->iPrevDirection) // NOSONAR - Track = Track->CurrentPrev(); - else - { - Track = Track->CurrentPrev(); - ScanDir = -ScanDir; - } - } - if (Track != nullptr) - { // jesli jest kolejny odcinek toru - CurrDist = Track->Length(); - FoundedObj = ABuFindNearestObject(pos, Track, this, CouplNr); - if (FoundedObj != nullptr) - ActDist = ScanDist; - } - else // Jesli nie ma, to wychodzimy. - break; - } - } // Koniec szukania najblizszego toru z jakims obiektem. - return FoundedObj; -} - -// ABu 01.11.04 poczatek wyliczania przechylow pudla ********************** -void TDynamicObject::ABuModelRoll() -{ // ustawienie przechyłki pojazdu i jego - // zawartości - // Ra: przechyłkę załatwiamy na etapie przesuwania modelu -} - -// ABu 06.05.04 poczatek wyliczania obrotow wozkow ********************** - -void TDynamicObject::ABuBogies() -{ // Obracanie wozkow na zakretach. Na razie - // uwzględnia tylko zakręty, - // bez zadnych gorek i innych przeszkod. - if( smBogie[ 0 ] != nullptr && smBogie[ 1 ] != nullptr && MoverParameters->OffTrack.active() ) { - // off the track the bogies stay straight under the body, they don't follow the track any more - bogieRot[ 0 ] = glm::vec3 { 0.f }; - bogieRot[ 1 ] = glm::vec3 { 0.f }; - smBogie[ 0 ]->SetRotateXYZ( bogieRot[ 0 ] ); - smBogie[ 1 ]->SetRotateXYZ( bogieRot[ 1 ] ); - return; - } - if (smBogie[0] != nullptr && smBogie[1] != nullptr) - { - // modelRot.z=ABuAcos(Axle0.pPosition-Axle1.pPosition); //kąt obrotu pojazdu - // [rad] - // bogieRot[0].z=ABuAcos(Axle0.pPosition-Axle3.pPosition); - bogieRot[0].z = Axle0.vAngles.z; - bogieRot[0] = glm::degrees(modelRot - bogieRot[0]); // mnożenie wektora przez stałą - smBogie[0]->SetRotateXYZ(bogieRot[0]); - // bogieRot[1].z=ABuAcos(Axle2.pPosition-Axle1.pPosition); - bogieRot[1].z = Axle1.vAngles.z; - bogieRot[1] = glm::degrees(modelRot - bogieRot[1]); - smBogie[1]->SetRotateXYZ(bogieRot[1]); - } -}; -// ABu 06.05.04 koniec wyliczania obrotow wozkow ************************ - -// ABu 16.03.03 sledzenie toru przed obiektem: ************************** -void TDynamicObject::ABuCheckMyTrack() -{ // Funkcja przypisujaca obiekt - // prawidlowej tablicy Dynamics, - // bo gdzies jest jakis blad i wszystkie obiekty z danego - // pociagu na poczatku stawiane sa na jednym torze i wpisywane - // do jednej tablicy. Wykonuje sie tylko raz - po to 'ABuChecked' - TTrack *OldTrack = MyTrack; - TTrack *NewTrack = Axle0.GetTrack(); - if( NewTrack != OldTrack ) { - if( OldTrack ) { - OldTrack->RemoveDynamicObject( this ); - } - NewTrack->AddDynamicObject(this); - } - iAxleFirst = 0; // pojazd powiązany z przednią osią - Axle0 -} - -// Ra: w poniższej funkcji jest problem ze sprzęgami -TDynamicObject * -TDynamicObject::ABuFindObject( int &Foundcoupler, double &Distance, TTrack const *Track, int const Direction, int const Mycoupler, bool const InLine ) const -{ // Zwraca wskaźnik najbliższego obiektu znajdującego się - // na torze w określonym kierunku, ale tylko wtedy, kiedy - // obiekty mogą się zderzyć, tzn. nie mijają się. - // WE: - // Track - tor, na ktorym odbywa sie poszukiwanie, - // Direction - kierunek szukania na torze (+1:w stronę Point2, -1:w stronę Point1) - // Mycoupler - nr sprzegu obiektu szukajacego; - // WY: - // wskaznik do znalezionego obiektu. - // Foundcoupler - nr sprzegu znalezionego obiektu - // Distance - distance to found object - - if( true == Track->Dynamics.empty() ) { - // sens szukania na tym torze jest tylko, gdy są na nim pojazdy - Distance += Track->Length(); // doliczenie długości odcinka do przeskanowanej odległości - return nullptr; // nie ma pojazdów na torze, to jest NULL - } - - double distance = Track->Length(); // najmniejsza znaleziona odleglość (zaczynamy od długości toru) - double myposition; // pozycja szukającego na torze - TDynamicObject *foundobject = nullptr; - if( MyTrack == Track ) { - // gdy szukanie na tym samym torze - myposition = RaTranslationGet(); // położenie wózka względem Point1 toru - } - else { - // gdy szukanie na innym torze - if( Direction > 0 ) { - // szukanie w kierunku Point2 (od zera) - jesteśmy w Point1 - myposition = 0; - } - else { - // szukanie w kierunku Point1 (do zera) - jesteśmy w Point2 - myposition = distance; - } - } - - double objectposition; // robocza odległość od kolejnych pojazdów na danym odcinku - for( auto dynamic : Track->Dynamics ) { - - if( dynamic == this ) { continue; } // szukający się nie liczy - // physics.derailment new: one of the two off the track beside the other one, they don't meet - if( InLine && ( MoverParameters->OffTrack.active() || dynamic->MoverParameters->OffTrack.active() ) && false == in_line_with( *dynamic ) ) { - continue; - } -/* - if( ( ( dynamic == PrevConnected ) && ( MoverParameters->Couplers[ TMoverParameters::side::front ].CouplingFlag != Coupling::none ) ) - || ( ( dynamic == NextConnected ) && ( MoverParameters->Couplers[ TMoverParameters::side::rear ].CouplingFlag != Coupling::none ) ) ){ - // stop-gap check to prevent 'detection' of attached vehicles - // which seems to be a side-effect of inaccurate location calculation in 'simple' mode? - // TODO: investigate actual cause - continue; - } -*/ - if( Direction > 0 ) { - // jeśli szukanie w kierunku Point2 - objectposition = dynamic->RaTranslationGet() - myposition; // odległogłość tamtego od szukającego - if( objectposition > 0 - && objectposition < distance ) { - // gdy jest po właściwej stronie i bliżej niż jakiś wcześniejszy - Foundcoupler = dynamic->RaDirectionGet() > 0 ? 1 : 0; // to, bo (ScanDir>=0) - } - else { continue; } - } - else { - objectposition = myposition - dynamic->RaTranslationGet(); //???-przesunięcie wózka względem Point1 toru - if( objectposition > 0 - && objectposition < distance ) { - Foundcoupler = dynamic->RaDirectionGet() > 0 ? 0 : 1; // odwrotnie, bo (ScanDir<0) - } - else { continue; } - } - - if( Track->iCategoryFlag & 254 ) { - // trajektoria innego typu niż tor kolejowy - // dla torów nie ma sensu tego sprawdzać, rzadko co jedzie po jednej szynie i się mija - // Ra: mijanie samochodów wcale nie jest proste - // Przesuniecie wzgledne pojazdow. Wyznaczane, zeby sprawdzic, - // czy pojazdy faktycznie sie zderzaja (moga byc przesuniete - // w/m siebie tak, ze nie zachodza na siebie i wtedy sie mijaja). - double relativeoffset; // wzajemna odległość poprzeczna - if( Foundcoupler != Mycoupler ) { - // facing the same direction - relativeoffset = std::abs( MoverParameters->OffsetTrackH - dynamic->MoverParameters->OffsetTrackH ); - } - else { - relativeoffset = std::abs( MoverParameters->OffsetTrackH + dynamic->MoverParameters->OffsetTrackH ); - } - if( relativeoffset + relativeoffset > MoverParameters->Dim.W + dynamic->MoverParameters->Dim.W ) { - // odległość większa od połowy sumy szerokości - kolizji nie będzie - continue; - } - // jeśli zahaczenie jest niewielkie, a jest miejsce na poboczu, to zjechać na pobocze - } - foundobject = dynamic; // potencjalna kolizja - distance = objectposition; // odleglość pomiędzy aktywnymi osiami pojazdów - } - - Distance += distance; // doliczenie odległości przeszkody albo długości odcinka do przeskanowanej odległości - return foundobject; -} - -int TDynamicObject::DettachStatus(int dir) -{ // sprawdzenie odległości sprzęgów - // rzeczywistych od strony (dir): - // 0=przód,1=tył - // Ra: dziwne, że ta funkcja nie jest używana - if( MoverParameters->Couplers[ dir ].CouplingFlag == Coupling::none ) { - return 0; // jeśli nic nie podłączone, to jest OK - } - return MoverParameters->DettachStatus(dir); // czy jest w odpowiedniej odległości? -} - -int TDynamicObject::Dettach(int dir) -{ // rozłączenie sprzęgów rzeczywistych od - // strony (dir): 0=przód,1=tył - // zwraca maskę bitową aktualnych sprzegów (0 jeśli rozłączony) - if (ctOwner) - { // jeśli pojazd ma przypisany obiekt nadzorujący skład, to póki - // są wskaźniki - TDynamicObject *d = this; - while (d) - { - d->ctOwner = nullptr; // usuwanie właściciela - d = d->Prev(); - } - d = Next(); - while (d) - { - d->ctOwner = nullptr; // usuwanie właściciela - d = d->Next(); // i w drugą stronę - } - } - if( MoverParameters->Couplers[ dir ].CouplingFlag ) { - // odczepianie, o ile coś podłączone - MoverParameters->Dettach( dir ); -/* - if( true == MoverParameters->Dettach( dir ) ) { - auto *othervehicle { dir ? NextConnected : PrevConnected }; - auto const othercoupler { dir ? NextConnectedNo() : PrevConnectedNo() }; - ( othercoupler ? othervehicle->NextConnected : othervehicle->PrevConnected ) = nullptr; - ( dir ? NextConnected : PrevConnected ) = nullptr; - }; -*/ - } - // sprzęg po rozłączaniu (czego się nie da odpiąć - return MoverParameters->Couplers[dir].CouplingFlag.Bits(); -} - -void -TDynamicObject::couple( int const Side ) { - - auto const &neighbour { MoverParameters->Neighbours[ Side ] }; - - if( neighbour.vehicle == nullptr ) { return; } - - auto const &coupler { MoverParameters->Couplers[ Side ] }; - auto *othervehicle { neighbour.vehicle }; - auto *othervehicleparams{ othervehicle->MoverParameters }; - auto const &othercoupler { othervehicleparams->Couplers[ neighbour.vehicle_end ] }; - - if( coupler.CouplingFlag == Coupling::none ) { - // najpierw hak - if( ( coupler.AllowedFlag - & othercoupler.AllowedFlag - & Coupling::coupler ) == Coupling::coupler ) { - if( MoverParameters->Attach( - Side, neighbour.vehicle_end, - othervehicleparams, - Coupling::coupler ) ) { - // one coupling type per key press - return; - } - else { - WriteLog( "Mechanical coupling failed." ); - } - } - } - if( false == MoverParameters->Couplers[ Side ].CouplingFlag.HasAll(Coupling::brakeHose) ) { - // pneumatyka - if( ( coupler.AllowedFlag - & othercoupler.AllowedFlag - & Coupling::brakeHose ) == Coupling::brakeHose ) { - if( MoverParameters->Attach( - Side, neighbour.vehicle_end, - othervehicleparams, - coupler.CouplingFlag | Coupling::brakeHose ) ) { - SetPneumatic( Side != 0, true ); - othervehicle->SetPneumatic( Side != 0, true ); - // one coupling type per key press - return; - } - } - } - if( false == MoverParameters->Couplers[ Side ].CouplingFlag.HasAll(Coupling::mainHose) ) { - // zasilajacy - if( ( coupler.AllowedFlag - & othercoupler.AllowedFlag - & Coupling::mainHose ) == Coupling::mainHose ) { - if( MoverParameters->Attach( - Side, neighbour.vehicle_end, - othervehicleparams, - coupler.CouplingFlag | Coupling::mainHose ) ) { - SetPneumatic( Side != 0, false ); - othervehicle->SetPneumatic( Side != 0, false ); - // one coupling type per key press - return; - } - } - } - if( false == MoverParameters->Couplers[ Side ].CouplingFlag.HasAll(Coupling::control) ) { - // ukrotnionko - if( (coupler.AllowedFlag & othercoupler.AllowedFlag & Coupling::control) == Coupling::control - && coupler.control_type == othercoupler.control_type - && MoverParameters->CompatibleCoupling( Side, *othervehicleparams, neighbour.vehicle_end, coupler.CouplingFlag | Coupling::control ).HasAny( Coupling::control ) ) { - if( MoverParameters->Attach( - Side, neighbour.vehicle_end, - othervehicleparams, - coupler.CouplingFlag | Coupling::control ) ) { - // one coupling type per key press - return; - } - } - } - if( false == MoverParameters->Couplers[ Side ].CouplingFlag.HasAll(Coupling::gangway) ) { - // mostek - if( ( coupler.AllowedFlag - & othercoupler.AllowedFlag - & Coupling::gangway ) == Coupling::gangway ) { - if( MoverParameters->Attach( - Side, neighbour.vehicle_end, - othervehicleparams, - coupler.CouplingFlag | Coupling::gangway ) ) { - // one coupling type per key press - return; - } - } - } - if( false == MoverParameters->Couplers[ Side ].CouplingFlag.HasAll(Coupling::heating) ) { - // heating - if( ( coupler.AllowedFlag - & othercoupler.AllowedFlag - & Coupling::heating ) == Coupling::heating ) { - if( MoverParameters->Attach( - Side, neighbour.vehicle_end, - othervehicleparams, - coupler.CouplingFlag | Coupling::heating ) ) { - // one coupling type per key press - return; - } - } - } - -} - -int -TDynamicObject::uncouple( int const Side ) { - - if( DettachStatus(Side) >= 0 - || true == MoverParameters->Couplers[Side].CouplingFlag.HasAll(Coupling::permanent) ) { - // can't uncouple, return existing coupling state - return MoverParameters->Couplers[ Side ].CouplingFlag.Bits(); - } - // jeżeli sprzęg niezablokowany, jest co odczepić i się da - auto const couplingflag { Dettach( Side ) }; - return couplingflag; -} - -bool -TDynamicObject::attach_coupler_adapter( int const Side, bool const Enforce ) { - - auto &coupler { MoverParameters->Couplers[ Side ] }; - // sanity check(s) - if( coupler.type() == TCouplerType::Automatic ) { return false; } - auto const *neighbour { MoverParameters->Neighbours[ Side ].vehicle }; - if( neighbour == nullptr - || MoverParameters->Neighbours[Side].distance > 25.0 ) { - // can only acquire the adapter from a nearby enough vehicle - return false; - } - // TBD: empty struct instead of fallback defaults, to allow vehicles without adapter? - auto adapterdata { - coupleradapter_data { - { 0.085f, 0.95f }, - "tabor/polsprzeg" } }; - if( false == neighbour->m_coupleradapter.model.empty() ) { - // explicit coupler adapter definition overrides default parameters - adapterdata = neighbour->m_coupleradapter; - } - if( MoverParameters->Neighbours[Side].distance - adapterdata.position.x < 0.5 - && false == Enforce ) { - // arbitrary amount of free room required to install the adapter - // NOTE: this also covers cases with established physical connection - return false; - } - - coupler.adapter_type = TCouplerType::Automatic; - coupler.adapter_length = adapterdata.position.x; - coupler.adapter_height = adapterdata.position.y; - // audio flag, visuals update - coupler.sounds |= sound::attachadapter; - m_coupleradapters[ Side ] = TModelsManager::GetModel( adapterdata.model ); - - return true; -} - -bool -TDynamicObject::remove_coupler_adapter( int const Side ) { - - auto &coupler{ MoverParameters->Couplers[ Side ] }; - - if( coupler.adapter_type == TCouplerType::NoCoupler ) { return false; } - // TODO: sanity check(s) - if( coupler.Connected != nullptr ) { - // TBD: disallow instead adapter removal if it's coupled with another vehicle? - uncouple( Side ); - } - coupler.adapter_type = TCouplerType::NoCoupler; - coupler.adapter_length = 0.0; - coupler.adapter_height = 0.0; - // audio flag, visuals update - coupler.sounds |= sound::removeadapter; - m_coupleradapters[ Side ] = nullptr; - - return true; -} - -TDynamicObject::TDynamicObject() { - modelShake = glm::dvec3(0, 0, 0); -// fTrackBlock = 10000.0; // brak przeszkody na drodze - btnOn = false; - vUp = vWorldUp; - vFront = vWorldFront; - vLeft = vWorldLeft; - iNumAxles = 0; - MoverParameters = nullptr; - Mechanik = nullptr; - MechInside = false; - // McZapkie-270202 - Controller = AIdriver; - bDisplayCab = false; // 030303 -// NextConnected = PrevConnected = NULL; -// NextConnectedNo = PrevConnectedNo = 2; // ABu: Numery sprzegow. 2=nie podłączony - bEnabled = true; - MyTrack = nullptr; - // McZapkie-260202 - dWheelAngle[0] = 0.0; - dWheelAngle[1] = 0.0; - dWheelAngle[2] = 0.0; - // Winger 160204 - pantografy - // PantVolume = 3.5; - NoVoltTime = 0; - mdModel = nullptr; - mdKabina = nullptr; - // smWiazary[0]=smWiazary[1]=NULL; - smWahacze[0] = smWahacze[1] = smWahacze[2] = smWahacze[3] = nullptr; - fWahaczeAmp = 0; - smBrakeMode = nullptr; - smLoadMode = nullptr; - mdLoad = nullptr; - mdLowPolyInt = nullptr; - //smMechanik0 = smMechanik1 = NULL; - smBuforLewy[0] = smBuforLewy[1] = nullptr; - smBuforPrawy[0] = smBuforPrawy[1] = nullptr; - smBogie[0] = smBogie[1] = nullptr; - bogieRot[0] = bogieRot[1] = glm::dvec3(0, 0, 0); - modelRot = glm::dvec3(0, 0, 0); - cp1 = cp2 = sp1 = sp2 = 0; - iDirection = 1; // stoi w kierunku tradycyjnym (0, gdy jest odwrócony) - iAxleFirst = 0; // numer pierwszej osi w kierunku ruchu (przełączenie - // następuje, gdy osie sa na - // tym samym torze) - RaLightsSet(0, 0); // początkowe zerowanie stanu świateł - // Ra: domyślne ilości animacji dla zgodności wstecz (gdy brak ilości podanych - // w MMD) - // ustawienie liczby modeli animowanych podczas konstruowania obiektu a nie na 0 - // prowadzi prosto do wysypów jeśli źle zdefiniowane mmd - iAnimations = 0; // na razie nie ma żadnego - pAnimated = nullptr; - fShade = 0.0; // standardowe oświetlenie na starcie - iHornWarning = 1; // numer syreny do użycia po otrzymaniu sygnału do jazdy - asDestination = "none"; // stojący nigdzie nie jedzie - pValveGear = nullptr; // Ra: tymczasowo - iCabs = 0; // maski bitowe modeli kabin - smBrakeSet = nullptr; // nastawa hamulca (wajcha) - smLoadSet = nullptr; // nastawa ładunku (wajcha) - smWiper = nullptr; // wycieraczka (poniekąd też wajcha) - ctOwner = nullptr; // na początek niczyj - iOverheadMask = 0; // maska przydzielana przez AI pojazdom posiadającym - // pantograf, aby wymuszały - // jazdę bezprądową - tmpTraction.TractionVoltage = 0; // Ra 2F1H: prowizorka, trzeba przechować - // napięcie, żeby nie wywalało WS pod - // izolatorem - fAdjustment = 0.0; // korekcja odległości pomiędzy wózkami (np. na łukach) -} - -TDynamicObject::~TDynamicObject() { - SafeDelete( Mechanik ); - SafeDelete( MoverParameters ); - SafeDeleteArray( pAnimated ); // lista animowanych submodeli -} - -void TDynamicObject::place_on_track(TTrack *Track, double fDist, bool Reversed) -{ - for( auto &axle : m_axlesounds ) { - // wyszukiwanie osi (0 jest na końcu, dlatego dodajemy długość?) - axle.distance = ( - Reversed ? - -axle.offset : - axle.offset + MoverParameters->Dim.L ) + fDist; - } - double fAxleDistHalf = fAxleDist * 0.5; - // przesuwanie pojazdu tak, aby jego początek był we wskazanym miejcu - fDist -= 0.5 * MoverParameters->Dim.L; // dodajemy pół długości pojazdu, bo ustawiamy jego środek (zliczanie na minus) - switch (iNumAxles) { - // Ra: pojazdy wstawiane są na tor początkowy, a potem przesuwane - case 2: // ustawianie osi na torze - Axle0.Reset(); - Axle0.Init(Track, this, iDirection ? 1 : -1); - Axle0.Move((iDirection ? fDist : -fDist) + fAxleDistHalf, false); - Axle1.Reset(); - Axle1.Init(Track, this, iDirection ? 1 : -1); - Axle1.Move((iDirection ? fDist : -fDist) - fAxleDistHalf, false); // false, żeby nie generować eventów - break; - } - // the stretches the criteria of derailment held over were on the track the vehicle left (consistteleport) - MoverParameters->derailment_monitor.reset(); - MoverParameters->derailment_distance = 0.0; - // potrzebne do wyliczenia aktualnej pozycji; nie może być zero, bo nie przeliczy pozycji - // teraz jeszcze trzeba przypisać pojazdy do nowego toru, bo przesuwanie początkowe osi nie - // zrobiło tego - Move( 0.0001 ); - ABuCheckMyTrack(); // zmiana toru na ten, co oś Axle0 (oś z przodu) -} - -double -TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" - std::string BaseDir, // z którego katalogu wczytany, np. "PKP/EU07" - std::string asReplacableSkin, // nazwa wymiennej tekstury - std::string Type_Name, // nazwa CHK/MMD, np. "303E" - TTrack *Track, // tor początkowy wstwawienia (początek składu) - double fDist, // dystans względem punktu 1 - std::string DriverType, // typ obsady - double fVel, // prędkość początkowa - std::string TrainName, // nazwa składu, np. "PE2307" albo Vmax, jeśli pliku nie ma a są cyfry - float Load, // ilość ładunku - std::string LoadType, // nazwa ładunku - bool Reversed, // true, jeśli ma stać odwrotnie w składzie - std::string MoreParams // dodatkowe parametry wczytywane w postaci tekstowej - ) -{ // Ustawienie początkowe pojazdu - iDirection = Reversed ? 0 : 1; // Ra: 0, jeśli ma być wstawiony jako obrócony tyłem - asBaseDir = paths::dynamic + BaseDir + "/"; // McZapkie-310302 - asName = Name; - // derived from the name and the seed of the simulation rather than drawn at random, so that the vehicle - // keeps the same look for the whole session and looks the same for everyone in a multiplayer game, while - // another run of the same scenario, with another seed, dresses it differently - m_variantseed = hash_string( asName, Global.random_seed ); - std::string asAnimName; // zmienna robocza do wyszukiwania osi i wózków - // a vehicle prepared for being hauled dead (parameter H after its coupling, MaSzyna-EU07/maszyna#64) has nobody - // driving it, whatever its crew entry says: its cab can't be activated, and a driver in it would either take - // the train or be one more for the train's driver to put to sleep - auto const hauled { pullee_mode::requested( MoreParams ) }; - if( hauled && ( DriverType == "headdriver" || DriverType == "reardriver" ) ) { - WriteLog( "Vehicle " + asName + " is prepared for hauling (parameter H), the driver it was given is left out" ); - DriverType = "nobody"; - } - // Ra: zmieniamy znaczenie obsady na jednoliterowe, żeby dosadzić kierownika - if (DriverType == "headdriver") - DriverType = "1"; // sterujący kabiną +1 - else if (DriverType == "reardriver") - DriverType = "2"; // sterujący kabiną -1 - else if (DriverType == "passenger") - DriverType = ""; // legacy type, no longer needed - else if (DriverType == "nobody") - DriverType = ""; // nikt nie siedzi - - int Cab = 0; // numer kabiny z obsadą (nie można zająć obu) - if (DriverType == "1") // od przodu składu - Cab = 1; // iDirection?1:-1; //iDirection=1 gdy normalnie, =0 odwrotnie - else if (DriverType == "2") // od tyłu składu - Cab = -1; // iDirection?-1:1; -/* - // NOTE: leave passenger in the middle section, this is most likely to be 'passenger' section in MU trains - else if (DriverType == "p") - { - if (Random(6) < 3) - Cab = 1; - else - Cab = -1; // losowy przydział kabiny - } -*/ - // utworzenie parametrów fizyki - MoverParameters = new TMoverParameters(iDirection ? fVel : -fVel, Type_Name, asName, Cab); - // the vehicle carries on with the odometer state of its earlier sessions (eu07/maszyna#72) - MoverParameters->Odometer = odometer::starting_state( odometer::states(), asName, asBaseDir ); - // McZapkie: TypeName musi byc nazwą CHK/MMD pojazdu - if (!MoverParameters->LoadFIZ(asBaseDir)) - { // jak wczytanie CHK się nie uda, to błąd - if (ConversionError == 666) - ErrorLog( "Bad vehicle: failed to locate definition file \"" + BaseDir + "/" + Type_Name + ".fiz" + "\"" ); - else { - ErrorLog( "Bad vehicle: failed to load definition from file \"" + BaseDir + "/" + Type_Name + ".fiz\" (error " + std::to_string( ConversionError ) + ")" ); - } - return 0.0; // zerowa długość to brak pojazdu - } - // load the cargo now that we know whether the vehicle will allow it - MoverParameters->AssignLoad( LoadType, Load ); - MoverParameters->ComputeMass(); - - bool driveractive = fVel != 0.0; // jeśli prędkość niezerowa, to aktywujemy ruch - if (!MoverParameters->CheckLocomotiveParameters( - driveractive, - (fVel > 0 ? 1 : -1) * Cab * - (iDirection ? 1 : -1))) // jak jedzie lub obsadzony to gotowy do drogi - { - Error("Parameters mismatch: dynamic object " + asName + " from \"" + BaseDir + "/" + Type_Name + "\"" ); - return 0.0; // zerowa długość to brak pojazdu - } - // controller position - MoverParameters->MainCtrlPos = MoverParameters->MainCtrlNoPowerPos(); - // ustawienie pozycji hamulca - MoverParameters->LocalBrakePosA = 0.0; - if (driveractive) - { - if (Cab == 0) - MoverParameters->BrakeCtrlPos = - static_cast( std::floor(MoverParameters->Handle->GetPos(bh_NP)) ); - else - MoverParameters->BrakeCtrlPos = static_cast( std::floor(MoverParameters->Handle->GetPos(bh_RP)) ); - - // engage independent brake if applicable, if the vehicle is to be on standby - // NOTE: with more than one driver in the consist this is likely to go awery, since all but one will be sent to sleep - // TBD, TODO: have the virtual helper release independent brakes during consist check? - if( DriverType != "" ) { - if( MoverParameters->LocalBrake != TLocalBrake::ManualBrake ) { - if( fVel < 1.0 ) { - MoverParameters->IncLocalBrakeLevel( LocalBrakePosNo ); - if ( MoverParameters->EIMCtrlEmergency ) { - MoverParameters->DecLocalBrakeLevel(1); - } - } - } - } - } - else - MoverParameters->BrakeCtrlPos = - static_cast( std::floor(MoverParameters->Handle->GetPos(bh_NP)) ); - - // poprawienie hamulca po ewentualnym przestawieniu przez Pascal - // TODO: check if needed, we're not in Pascal anymore, Toto - MoverParameters->BrakeLevelSet(MoverParameters->BrakeCtrlPos); - - // dodatkowe parametry yB - MoreParams += "."; // wykonuje o jedną iterację za mało, więc trzeba mu dodać - // kropkę na koniec - size_t kropka = MoreParams.find("."); // znajdź kropke - std::string ActPar; // na parametry - while (kropka != std::string::npos) // jesli sa kropki jeszcze - { - size_t dlugosc = MoreParams.length(); - ActPar = ToUpper(MoreParams.substr(0, kropka)); // pierwszy parametr; - MoreParams = MoreParams.substr(kropka + 1, dlugosc - kropka); // reszta do dalszej obrobki - kropka = MoreParams.find("."); - - if (ActPar.substr(0, 1) == "B") // jesli hamulce - { // sprawdzanie kolejno nastaw - WriteLog("Wpis hamulca: " + ActPar); - if ( contains( ActPar, 'G') ) - { - MoverParameters->BrakeDelaySwitch(bdelay_G); - } - if( contains( ActPar, 'P' ) ) - { - MoverParameters->BrakeDelaySwitch(bdelay_P); - } - if( contains( ActPar, 'R' ) ) - { - MoverParameters->BrakeDelaySwitch(bdelay_R); - } - if( contains( ActPar, 'M' ) ) - { - MoverParameters->BrakeDelaySwitch(bdelay_R); - MoverParameters->BrakeDelaySwitch(bdelay_R + bdelay_M); - } - // wylaczanie hamulca - if ( contains( ActPar, "<>") ) // wylaczanie na probe hamowania naglego - { - MoverParameters->Hamulec->SetBrakeStatus( MoverParameters->Hamulec->GetBrakeStatus() | b_dmg ); // wylacz - } - if ( contains( ActPar, '0' ) ) // wylaczanie na sztywno - { - MoverParameters->Hamulec->ForceEmptiness(); - MoverParameters->Hamulec->SetBrakeStatus( MoverParameters->Hamulec->GetBrakeStatus() | b_dmg ); // wylacz - } - if ( contains( ActPar, 'E' ) ) // oprozniony - { - MoverParameters->Hamulec->ForceEmptiness(); - MoverParameters->Pipe->CreatePress(0); - MoverParameters->Pipe2->CreatePress(0); - } - if ( contains( ActPar, 'Q' ) ) // oprozniony - { - MoverParameters->Hamulec->ForceEmptiness(); - MoverParameters->Pipe->CreatePress(0.0); - MoverParameters->PipePress = 0.0; - MoverParameters->Pipe2->CreatePress(0.0); - MoverParameters->ScndPipePress = 0.0; - MoverParameters->PantVolume = 0.1; - MoverParameters->PantPress = 0.0; - MoverParameters->CompressedVolume = 0.0; - } - - if ( contains( ActPar, '1' ) ) // wylaczanie 10% - { - if (Random(10) < 1) // losowanie 1/10 - { - MoverParameters->Hamulec->ForceEmptiness(); - MoverParameters->Hamulec->SetBrakeStatus( MoverParameters->Hamulec->GetBrakeStatus() | b_dmg ); // wylacz - } - } - if ( contains( ActPar, 'X') ) // agonalny wylaczanie 20%, usrednienie przekladni - { - if (Random(100) < 20) // losowanie 20/100 - { - MoverParameters->Hamulec->ForceEmptiness(); - MoverParameters->Hamulec->SetBrakeStatus( MoverParameters->Hamulec->GetBrakeStatus() | b_dmg ); // wylacz - } - if (MoverParameters->BrakeCylMult[2] * MoverParameters->BrakeCylMult[1] > - 0.01) // jesli jest nastawiacz mechaniczny PL - { - float rnd = Random(100); - if (rnd < 20) // losowanie 20/100 usrednienie - { - MoverParameters->BrakeCylMult[2] = MoverParameters->BrakeCylMult[1] = - (MoverParameters->BrakeCylMult[2] + MoverParameters->BrakeCylMult[1]) / - 2; - } - else if (rnd < 70) // losowanie 70/100-20/100 oslabienie - { - MoverParameters->BrakeCylMult[1] = MoverParameters->BrakeCylMult[1] * 0.50; - MoverParameters->BrakeCylMult[2] = MoverParameters->BrakeCylMult[2] * 0.75; - } - else if (rnd < 80) // losowanie 80/100-70/100 tylko prozny - { - MoverParameters->BrakeCylMult[2] = MoverParameters->BrakeCylMult[1]; - } - else // tylko ladowny - { - MoverParameters->BrakeCylMult[1] = MoverParameters->BrakeCylMult[2]; - } - } - } - // nastawianie ladunku - if ( contains( ActPar, 'T' ) ) // prozny - { - MoverParameters->DecBrakeMult(); - MoverParameters->DecBrakeMult(); - } // dwa razy w dol - if ( contains( ActPar, 'H' ) ) // ladowny I (dla P-Ł dalej prozny) - { - MoverParameters->IncBrakeMult(); - MoverParameters->IncBrakeMult(); - MoverParameters->DecBrakeMult(); - } // dwa razy w gore i obniz - if ( contains( ActPar, 'F' ) ) // ladowny II - { - MoverParameters->IncBrakeMult(); - MoverParameters->IncBrakeMult(); - } // dwa razy w gore - if ( contains( ActPar, 'N' ) ) // parametr neutralny - { - } - } // koniec hamulce - else if( ActPar.size() >= 3 - && ActPar.front() == 'W' ) { - // wheel - ActPar.erase( 0, 1 ); - - auto fixedflatsize { 0 }; - auto randomflatsize { 0 }; - auto flatchance { 100 }; - - while( false == ActPar.empty() ) { - // TODO: convert this whole copy and paste mess to something more elegant one day - switch( ActPar.front() ) { - case 'F': { - // fixed flat size - auto const indexstart { 1 }; - auto const indexend { ActPar.find_first_not_of( "1234567890", indexstart ) }; - fixedflatsize = std::atoi( ActPar.substr( indexstart, indexend ).c_str() ); - ActPar.erase( 0, indexend ); - break; - } - case 'R': { - // random flat size - auto const indexstart { 1 }; - auto const indexend { ActPar.find_first_not_of( "1234567890", indexstart ) }; - randomflatsize = std::atoi( ActPar.substr( indexstart, indexend ).c_str() ); - ActPar.erase( 0, indexend ); - break; - } - case 'P': { - // random flat probability - auto const indexstart { 1 }; - auto const indexend { ActPar.find_first_not_of( "1234567890", indexstart ) }; - flatchance = std::atoi( ActPar.substr( indexstart, indexend ).c_str() ); - ActPar.erase( 0, indexend ); - break; - } - case 'H': { - // truck hunting - auto const indexstart { 1 }; - auto const indexend { ActPar.find_first_not_of( "1234567890", indexstart ) }; - auto const huntingchance { std::atoi( ActPar.substr( indexstart, indexend ).c_str() ) }; - MoverParameters->TruckHunting = Random(0, 100) < huntingchance; - ActPar.erase( 0, indexend ); - break; - } - default: { - // unrecognized key - ActPar.erase( 0, 1 ); - break; - } - } - } - if( Random( 0, 100 ) <= flatchance ) { - MoverParameters->WheelFlat += fixedflatsize + Random( 0, randomflatsize ); - } - } // wheel - else if( ActPar.size() >= 2 - && ActPar.front() == 'T' ) { - // temperature - ActPar.erase( 0, 1 ); - - auto setambient { false }; - - while( false == ActPar.empty() ) { - switch( ActPar.front() ) { - case 'A': { - // cold start, set all temperatures to ambient level - setambient = true; - ActPar.erase( 0, 1 ); - break; - } - default: { - // unrecognized key - ActPar.erase( 0, 1 ); - break; - } - } - } - if( true == setambient ) { - // TODO: pull ambient temperature from environment data - MoverParameters->dizel_HeatSet( Global.AirTemperature ); - } - } // temperature - else if( ActPar.size() >= 2 - && ActPar.front() == 'L' ) { - // load - ActPar.erase( 0, 1 ); - // immediately followed by max load override - // TBD: make it instead an optional sub-parameter? - { - auto const indexstart { 0 }; - auto const indexend { ActPar.find_first_not_of( "1234567890", indexstart ) }; - MoverParameters->MaxLoad = std::atoi( ActPar.substr( indexstart, indexend ).c_str() ); - ActPar.erase( 0, indexend ); - } - while( false == ActPar.empty() ) { - switch( ActPar.front() ) { - default: { - // unrecognized key - ActPar.erase( 0, 1 ); - break; - } - } - } - } // load -/* else if (ActPar.substr(0, 1) == "") // tu mozna wpisac inny prefiks i inne rzeczy - { - // jakies inne prefiksy - } -*/ - } // koniec while kropka - - if( hauled ) { - // once the vehicle has its starting state: the hand brake and the spring brake of a standing one let go, battery off - MoverParameters->PulleeModeSwitch( true ); - } - - if (MoverParameters->CategoryFlag & 2) // jeśli samochód - { // ustawianie samochodow na poboczu albo na środku drogi - if( Track->fTrackWidth < 3.5 // jeśli droga wąska - || Track->m_road != nullptr ) // a lane of a road node is one-way, the vehicle keeps to its middle - MoverParameters->OffsetTrackH = 0.0; // to stawiamy na środku, niezależnie od stanu - // ruchu - else if( driveractive ) {// od 3.5m do 8.0m jedzie po środku pasa, dla - // szerszych w odległości - // 1.5m - auto const lanefreespace = 0.5 * Track->fTrackWidth - MoverParameters->Dim.W; - MoverParameters->OffsetTrackH = lanefreespace > 1.5 ? - -0.5 * MoverParameters->Dim.W - 0.75 : // wide road, keep near centre with safe margin - lanefreespace > 0.1 ? - -0.25 * Track->fTrackWidth : // narrow fit, stay on the middle - -0.5 * MoverParameters->Dim.W - 0.075; // too narrow, just keep some minimal clearance - } - else // jak stoi, to kołem na poboczu i pobieramy szerokość razem z - // poboczem, ale nie z - // chodnikiem - MoverParameters->OffsetTrackH = - -0.5 * (Track->WidthTotal() - MoverParameters->Dim.W) + 0.05; - iHornWarning = 0; // nie będzie trąbienia po podaniu zezwolenia na jazdę - if (fDist < 0.0) //-0.5*MoverParameters->Dim.L) //jeśli jest przesunięcie do tyłu - if (!Track->CurrentPrev()) // a nie ma tam odcinka i trzeba by coś - // wygenerować - fDist = -fDist; // to traktujemy, jakby przesunięcie było w drugą stronę - } - - create_controller( DriverType, !TrainName.empty() ); - - ShakeSpring.Init( 125.0 ); - BaseShake = baseshake_config {}; - ShakeState = shake_state {}; - ShakeStateBefore = shake_state {}; - - // McZapkie-250202 -/* - iAxles = std::min( MoverParameters->NAxles, MaxAxles ); // ilość osi -*/ - // wczytywanie z pliku nazwatypu.mmd, w tym model - erase_extension( asReplacableSkin ); - LoadMMediaFile(Type_Name, asReplacableSkin); - // McZapkie-100402: wyszukiwanie submodeli sprzegów - btCoupler1.Init( "coupler1", mdModel ); // false - ma być wyłączony - btCoupler2.Init( "coupler2", mdModel ); - // brake hoses - btCPneumatic1.Init("cpneumatic1", mdModel); - btCPneumatic2.Init("cpneumatic2", mdModel); - btCPneumatic1r.Init("cpneumatic1r", mdModel); - btCPneumatic2r.Init("cpneumatic2r", mdModel); - // main hoses - btPneumatic1.Init("pneumatic1", mdModel); - btPneumatic2.Init("pneumatic2", mdModel); - btPneumatic1r.Init("pneumatic1r", mdModel); - btPneumatic2r.Init("pneumatic2r", mdModel); - // control cables - btCCtrl1.Init( "cctrl1", mdModel, false); - btCCtrl2.Init( "cctrl2", mdModel, false); - // gangways - btCPass1.Init( "cpass1", mdModel, false); - btCPass2.Init( "cpass2", mdModel, false); - // sygnaly - m_endsignal12.Init( "endsignal12", mdModel, false ); - m_endsignal13.Init( "endsignal13", mdModel, false ); - m_endsignal22.Init( "endsignal22", mdModel, false ); - m_endsignal23.Init( "endsignal23", mdModel, false ); - m_endsignals1.Init( "endsignals1", mdModel, false ); - m_endsignals2.Init( "endsignals2", mdModel, false ); - m_endtab1.Init( "endtab1", mdModel, false ); - m_endtab2.Init( "endtab2", mdModel, false ); - m_headlamp11.Init( "headlamp11", mdModel ); // górne - m_headlamp12.Init( "headlamp12", mdModel ); // prawe - m_headlamp13.Init( "headlamp13", mdModel ); // lewe - m_highbeam12.Init("highbeam12", mdModel); // prawe dlugie - m_highbeam13.Init("highbeam13", mdModel); // lewe dlugie - m_headlamp21.Init( "headlamp21", mdModel ); - m_headlamp22.Init( "headlamp22", mdModel ); - m_headlamp23.Init( "headlamp23", mdModel ); - m_highbeam22.Init("highbeam22", mdModel); - m_highbeam23.Init("highbeam23", mdModel); - m_headsignal12.Init( "headsignal12", mdModel ); - m_headsignal13.Init( "headsignal13", mdModel ); - m_headsignal22.Init( "headsignal22", mdModel ); - m_headsignal23.Init( "headsignal23", mdModel ); - // informacja, czy ma poszczególne światła - iInventory[ end::front ] |= m_endsignal12.Active() ? light::redmarker_right : 0; - iInventory[ end::front ] |= m_endsignal13.Active() ? light::redmarker_left : 0; - iInventory[ end::rear ] |= m_endsignal22.Active() ? light::redmarker_right : 0; - iInventory[ end::rear ] |= m_endsignal23.Active() ? light::redmarker_left : 0; - iInventory[ end::front ] |= m_endsignals1.Active() ? light::redmarker_left | light::redmarker_right : 0; - iInventory[ end::rear ] |= m_endsignals2.Active() ? light::redmarker_left | light::redmarker_right : 0; - iInventory[ end::front ] |= m_endtab1.Active() ? light::rearendsignals : 0; // tabliczki blaszane - iInventory[ end::rear ] |= m_endtab2.Active() ? light::rearendsignals : 0; - iInventory[ end::front ] |= m_headlamp11.Active() ? light::headlight_upper : 0; - iInventory[ end::front ] |= m_headlamp12.Active() ? light::headlight_right : 0; - iInventory[ end::front ] |= m_headlamp13.Active() ? light::headlight_left : 0; - - iInventory[end::front] |= m_highbeam12.Active() ? light::highbeamlight_right : 0; - iInventory[end::front] |= m_highbeam13.Active() ? light::highbeamlight_left : 0; - - iInventory[ end::rear ] |= m_headlamp21.Active() ? light::headlight_upper : 0; - iInventory[ end::rear ] |= m_headlamp22.Active() ? light::headlight_right : 0; - iInventory[ end::rear ] |= m_headlamp23.Active() ? light::headlight_left : 0; - iInventory[ end::front ] |= m_headsignal12.Active() ? light::auxiliary_right : 0; - iInventory[ end::front ] |= m_headsignal13.Active() ? light::auxiliary_left : 0; - iInventory[ end::rear ] |= m_headsignal22.Active() ? light::auxiliary_right : 0; - iInventory[ end::rear ] |= m_headsignal23.Active() ? light::auxiliary_left : 0; - - iInventory[end::rear] |= m_highbeam22.Active() ? light::highbeamlight_right : 0; - iInventory[end::rear] |= m_highbeam23.Active() ? light::highbeamlight_left : 0; - - btExteriorOnly.Init("external_only", mdModel, false); - - btMechanik1.Init( "mechanik1", mdLowPolyInt, false); - btMechanik2.Init( "mechanik2", mdLowPolyInt, false); - - if( MoverParameters->dizel_heat.water.config.shutters ) { - btShutters1.Init( "shutters1", mdModel, false ); - } - if( MoverParameters->dizel_heat.water_aux.config.shutters ) { - btShutters2.Init( "shutters2", mdModel, false ); - } - TurnOff(); // resetowanie zmiennych submodeli - - if( mdLowPolyInt != nullptr ) { - // check the low poly interior for potential compartments of interest, ie ones which can be individually lit - // TODO: definition of relevant compartments in the .mmd file - TSubModel *submodel { nullptr }; - if( ( submodel = mdLowPolyInt->GetFromName( "cab0" ) ) != nullptr ) { - Sections.push_back( { submodel, nullptr, 0, 0.0f } ); - LowPolyIntCabs[ 0 ] = submodel; - } - if( ( submodel = mdLowPolyInt->GetFromName( "cab1" ) ) != nullptr ) { - Sections.push_back( { submodel, nullptr, 0, 0.0f } ); - LowPolyIntCabs[ 1 ] = submodel; - } - if( ( submodel = mdLowPolyInt->GetFromName( "cab2" ) ) != nullptr ) { - Sections.push_back( { submodel, nullptr, 0, 0.0f } ); - LowPolyIntCabs[ 2 ] = submodel; - } - // passenger car compartments - std::vector nameprefixes = { "corridor", "korytarz", "compartment", "przedzial" }; - for( auto const &nameprefix : nameprefixes ) { - init_sections( mdLowPolyInt, nameprefix, MoverParameters->CompartmentLights.start_type == start_t::manual ); - } - // the inside of the door wings, if the interior has them - init_interior_doors(); - } - // destination sign - if( mdModel ) { - init_destination( mdModel ); - } - // 'external_load' is an optional special section in the main model, pointing to submodel of external load - if( mdModel ) { - init_sections( mdModel, "external_load", false ); - } - update_load_sections(); - update_load_visibility(); - // wyszukiwanie zderzakow - if( mdModel ) { - // jeśli ma w czym szukać - for( int i = 0; i < 2; i++ ) { - asAnimName = std::string( "buffer_left0" ) + std::to_string( i + 1 ); - smBuforLewy[ i ] = mdModel->GetFromName( asAnimName ); - if( smBuforLewy[ i ] ) - smBuforLewy[ i ]->WillBeAnimated(); // ustawienie flagi animacji - asAnimName = std::string( "buffer_right0" ) + std::to_string( i + 1 ); - smBuforPrawy[ i ] = mdModel->GetFromName( asAnimName ); - if( smBuforPrawy[ i ] ) - smBuforPrawy[ i ]->WillBeAnimated(); - } - } - if( Track->fSoundDistance > 0.f ) { - for( auto &axle : m_axlesounds ) { - // wyszukiwanie osi (0 jest na końcu, dlatego dodajemy długość?) - axle.distance = - clamp_circular( - ( Reversed ? - -axle.offset : - axle.offset ) - - 0.5 * MoverParameters->Dim.L - + fDist, - Track->fSoundDistance ); - } - } - // McZapkie-250202 end. - Track->AddDynamicObject(this); // wstawiamy do toru na pozycję 0, a potem przesuniemy - // McZapkie: zmieniono na ilosc osi brane z chk - // iNumAxles=(MoverParameters->NAxles>3 ? 4 : 2 ); - initial_track = MyTrack; - iNumAxles = 2; - // McZapkie-090402: odleglosc miedzy czopami skretu lub osiami - fAxleDist = safe_clamp( - std::max( MoverParameters->BDist, MoverParameters->ADist ), - 0.2, //żeby się dało wektory policzyć - MoverParameters->Dim.L - 0.2 ); // nie mogą być za daleko bo będzie "walenie w mur" - double fAxleDistHalf = fAxleDist * 0.5; - // przesuwanie pojazdu tak, aby jego początek był we wskazanym miejcu - fDist -= 0.5 * MoverParameters->Dim.L; // dodajemy pół długości pojazdu, bo ustawiamy jego środek (zliczanie na minus) - switch (iNumAxles) { - // Ra: pojazdy wstawiane są na tor początkowy, a potem przesuwane - case 2: // ustawianie osi na torze - Axle0.Init(Track, this, iDirection ? 1 : -1); - Axle0.Move((iDirection ? fDist : -fDist) + fAxleDistHalf, false); - Axle1.Init(Track, this, iDirection ? 1 : -1); - Axle1.Move((iDirection ? fDist : -fDist) - fAxleDistHalf, false); // false, żeby nie generować eventów - break; - case 4: - Axle0.Init(Track, this, iDirection ? 1 : -1); - Axle0.Move((iDirection ? fDist : -fDist) + (fAxleDistHalf + MoverParameters->ADist * 0.5), false); - Axle1.Init(Track, this, iDirection ? 1 : -1); - Axle1.Move((iDirection ? fDist : -fDist) - (fAxleDistHalf + MoverParameters->ADist * 0.5), false); - // Axle2.Init(Track,this,iDirection?1:-1); - // Axle2.Move((iDirection?fDist:-fDist)-(fAxleDistHalf-MoverParameters->ADist*0.5),false); - // Axle3.Init(Track,this,iDirection?1:-1); - // Axle3.Move((iDirection?fDist:-fDist)+(fAxleDistHalf-MoverParameters->ADist*0.5),false); - break; - } - // potrzebne do wyliczenia aktualnej pozycji; nie może być zero, bo nie przeliczy pozycji - // teraz jeszcze trzeba przypisać pojazdy do nowego toru, bo przesuwanie początkowe osi nie - // zrobiło tego - Move( 0.0001 ); - ABuCheckMyTrack(); // zmiana toru na ten, co oś Axle0 (oś z przodu) - // Ra: ustawienie pozycji do obliczania sprzęgów - MoverParameters->Loc = { - -vPosition.x, - vPosition.z, - vPosition.y }; // normalnie przesuwa ComputeMovement() w Update() - // ABuWozki 060504 - if (mdModel) // jeśli ma w czym szukać - { - smBogie[0] = mdModel->GetFromName("bogie1"); // Ra: bo nazwy są małymi - smBogie[1] = mdModel->GetFromName("bogie2"); - if (!smBogie[0]) - smBogie[0] = mdModel->GetFromName("boogie01"); // Ra: alternatywna nazwa - if (!smBogie[1]) - smBogie[1] = mdModel->GetFromName("boogie02"); // Ra: alternatywna nazwa - if (smBogie[0]) - smBogie[0]->WillBeAnimated(); - if (smBogie[1]) - smBogie[1]->WillBeAnimated(); - sm_winter_variant = mdModel->GetFromName("winter_variant"); - sm_spring_variant = mdModel->GetFromName("spring_variant"); - sm_summer_variant = mdModel->GetFromName("summer_variant"); - sm_autumn_variant = mdModel->GetFromName("autumn_variant"); - } - // ABu: zainicjowanie zmiennej, zeby nic sie nie ruszylo w pierwszej klatce, - // potem juz liczona prawidlowa wartosc masy - MoverParameters->ComputeConstans(); - // wektor podłogi dla wagonów, przesuwa ładunek - vFloor = glm::dvec3(0, 0, MoverParameters->Floor); - - // długość większa od zera oznacza OK; 2mm docisku? - return MoverParameters->Dim.L; -} - -int -TDynamicObject::init_sections( TModel3d const *Model, std::string const &Nameprefix, bool const Overrideselfillum ) { - - auto sectioncount = 0; - auto sectionindex = 0; - TSubModel *sectionsubmodel { nullptr }; - - do { - // section names for index < 10 match either prefix0X or prefixX - // section names above 10 match prefixX - auto const sectionindexname { std::to_string( sectionindex ) }; - sectionsubmodel = Model->GetFromName( Nameprefix + sectionindexname ); - if( sectionsubmodel == nullptr - && sectionindex < 10 ) { - sectionsubmodel = Model->GetFromName( Nameprefix + "0" + sectionindexname ); - } - if( sectionsubmodel != nullptr ) { - // HACK: disable automatic self-illumination threshold, at least until 3d model update - if( Overrideselfillum ) { - sectionsubmodel->SetSelfIllum( 2.0f, true, false ); - } - Sections.push_back( { - sectionsubmodel, - nullptr, // pointers to load sections are generated afterwards - 0, - 0.0f } ); - ++sectioncount; - } - ++sectionindex; - } while( sectionsubmodel != nullptr - || sectionindex < 2 ); // chain can start from prefix00 or prefix01 - - return sectioncount; -} - -// a door wing of the main model is seen from the outside, lit as the exterior. its namesake in the low poly interior, -// if the model has one, follows its moves and is lit with the interior, by its compartment section if it's in one -void -TDynamicObject::init_interior_doors() { - - if( mdLowPolyInt == nullptr ) { return; } - - for( auto &animation : pAnimations ) { - // the door animation is only set up for a wing found in the main model - if( false == door_wings::is_wing( animation.iFlags ) ) { continue; } - if( ( animation.yUpdate == nullptr ) || ( animation.smAnimated == nullptr ) ) { continue; } - - auto *interiorwing { mdLowPolyInt->GetFromName( animation.smAnimated->pName ) }; - if( ( interiorwing == nullptr ) || ( interiorwing == animation.smAnimated ) ) { continue; } - - interiorwing->WillBeAnimated(); - animation.smInterior = interiorwing; - } -} - -bool -TDynamicObject::init_destination( TModel3d *Model ) { - - if( Model->GetSMRoot() == nullptr ) { return false; } - - std::tie( DestinationSign.sign, DestinationSign.has_light ) = Model->GetSMRoot()->find_replacable4(); - - return DestinationSign.sign != nullptr; -} - -void -TDynamicObject::create_controller( std::string const Type, bool const Trainset ) { - - if( Type == "" ) { return; } - - // McZapkie-151102: rozkład jazdy czytany z pliku *.txt z katalogu w którym jest sceneria - if( Type == "1" - || Type == "2" ) { - // McZapkie-110303: mechanik i rozklad tylko gdy jest obsada - Mechanik = new TController( Controller, this, Aggressive ); - - if( false == Trainset ) { - // jeśli nie w składzie - // załączenie rozrządu (wirtualne kabiny) itd. - Mechanik->DirectionInitial(); - // tryb pociągowy z ustaloną prędkością (względem sprzęgów) - Mechanik->PutCommand( - "Timetable:", - MoverParameters->V * 3.6 * ( iDirection ? -1.0 : 1.0 ), - 0, - nullptr ); - } - } - else if( Type == "p" ) { - // obserwator w charakterze pasażera - // Ra: to jest niebezpieczne, bo w razie co będzie pomagał hamulcem bezpieczeństwa - Mechanik = new TController( Controller, this, Easyman, false ); - } -} - -void TDynamicObject::FastMove(double fDistance) -{ - MoverParameters->dMoveLen = MoverParameters->dMoveLen + fDistance; -} - -void TDynamicObject::Move(double fDistance) -{ - if( MoverParameters->OffTrack.active() ) { - // physics.derailment new: off the track it goes on the ground - move_off_track( fDistance ); - return; - } - move_axles( fDistance ); - if( fDistance != 0.0 || m_offtrackplaced ) // nie liczyć ponownie, jeśli stoi - { // liczenie pozycji pojazdu tutaj, bo jest używane w wielu miejscach - // (also once the vehicle off the track is back on the rails) - m_offtrackplaced = false; - place_by_axles(); - } -} - -void TDynamicObject::move_axles(double fDistance) -{ // przesuwanie pojazdu po - // trajektorii polega na - // przesuwaniu poszczególnych osi - // Ra: wartość prędkości 2km/h ma ograniczyć aktywację eventów w przypadku - // drgań - if (Axle0.GetTrack() == Axle1.GetTrack()) // przed przesunięciem - { // powiązanie pojazdu z osią można zmienić tylko wtedy, gdy skrajne osie są - // na tym samym torze - if (MoverParameters->Vel > - 2) //|[km/h]| nie ma sensu zmiana osi, jesli pojazd drga na postoju - iAxleFirst = MoverParameters->V >= 0.0 ? - 1 : - 0; //[m/s] ?1:0 - aktywna druga oś w kierunku jazdy - // aktualnie eventy aktywuje druga oś, żeby AI nie wyłączało sobie semafora - // za szybko - } - if (fDistance > 0.0) - { // gdy ruch w stronę sprzęgu 0, doliczyć korektę do osi 1 - bEnabled &= Axle0.Move(fDistance, iAxleFirst == 0); // oś z przodu pojazdu - bEnabled &= Axle1.Move(fDistance /*-fAdjustment*/, iAxleFirst != 0); // oś z tyłu pojazdu - } - else if (fDistance < 0.0) - { // gdy ruch w stronę sprzęgu 1, doliczyć korektę do osi 0 - bEnabled &= Axle1.Move(fDistance, iAxleFirst != 0); // oś z tyłu pojazdu prusza się pierwsza - bEnabled &= Axle0.Move(fDistance /*-fAdjustment*/, iAxleFirst == 0); // oś z przodu pojazdu - } - else // gf: bez wywolania Move na postoju nie ma event0 - { - bEnabled &= Axle1.Move(fDistance, iAxleFirst != 0); // oś z tyłu pojazdu prusza się pierwsza - bEnabled &= Axle0.Move(fDistance, iAxleFirst == 0); // oś z przodu pojazdu - } -} - -void TDynamicObject::place_by_axles() -{ // liczenie pozycji pojazdu tutaj, bo jest używane w wielu miejscach - vPosition = 0.5 * (Axle1.pPosition + Axle0.pPosition); //środek między skrajnymi osiami - vFront = Axle0.pPosition - Axle1.pPosition; // wektor pomiędzy skrajnymi osiami - // Ra 2F1J: to nie jest stabilne (powoduje rzucanie taborem) i wymaga - // dopracowania - fAdjustment = glm::length(vFront) - fAxleDist; // na łuku będzie ujemny - // if (fabs(fAdjustment)>0.02) //jeśli jest zbyt dużo, to rozłożyć na kilka przeliczeń (wygasza drgania?) - //{//parę centymetrów trzeba by już skorygować; te błędy mogą się też - // generować na ostrych łukach - // fAdjustment*=0.5; //w jednym kroku korygowany jest ułamek błędu - //} - // else - // fAdjustment=0.0; - vFront = glm::normalize(vFront); // kierunek ustawienia pojazdu (wektor jednostkowy) - vLeft = glm::normalize(glm::cross(glm::dvec3(vWorldUp), vFront)); // wektor poziomy w lewo, - // normalizacja potrzebna z powodu pochylenia (vFront) - vUp = glm::cross(vFront, vLeft); // wektor w górę, będzie jednostkowy - modelRot.z = atan2(-vFront.x, vFront.z); // kąt obrotu pojazdu [rad]; z ABuBogies() - auto const roll { Roll() }; // suma przechyłek - if (roll != 0.0) - { // wyznaczanie przechylenia tylko jeśli jest przechyłka - // można by pobrać wektory normalne z toru... - mMatrix = glm::rotate(glm::dmat4(1.0), roll * 0.5, vFront); // ta macierz jest potrzebna głównie do wyświetlania // obrót wzdłuż osi o przechyłkę - vUp = glm::dvec3(mMatrix * glm::dvec4(vUp, 0.0)); // wektor w górę pojazdu (przekręcenie na przechyłce) - // vLeft=mMatrix*DynamicObject->vLeft; - // vUp=CrossProduct(vFront,vLeft); //wektor w górę - // vLeft=Normalize(CrossProduct(vWorldUp,vFront)); //wektor w lewo - vLeft = glm::normalize(glm::cross(vUp, vFront)); // wektor w lewo - // vUp=CrossProduct(vFront,vLeft); //wektor w górę - } - mMatrix = BasisChange(vLeft, vUp, vFront); // to też można by od razu policzyć, ale potrzebne jest do wyświetlania // przesuwanie jest jednak rzadziej niż renderowanie - mMatrix = glm::inverse(mMatrix); // wyliczenie macierzy dla pojazdu (potrzebna tylko do wyświetlania?) - // if (MoverParameters->CategoryFlag&2) - { // przesunięcia są używane po wyrzuceniu pociągu z toru - vPosition.x += MoverParameters->OffsetTrackH * vLeft.x; // dodanie przesunięcia w bok - vPosition.z += MoverParameters->OffsetTrackH * vLeft.z; // vLeft jest wektorem poprzecznym - // if () na przechyłce będzie dodatkowo zmiana wysokości samochodu - vPosition.y += MoverParameters->OffsetTrackV; // te offsety są liczone przez moverparam - } - // obliczanie pozycji sprzęgów do liczenia zderzeń - auto dir = 0.5 * MoverParameters->Dim.L * vFront; // wektor sprzęgu - vCoulpler[end::front] = vPosition + dir; // współrzędne sprzęgu na początku - vCoulpler[end::rear] = vPosition - dir; // współrzędne sprzęgu na końcu - // bCameraNear= - // if (bCameraNear) //jeśli istotne są szczegóły (blisko kamery) - { // przeliczenie cienia - TTrack *t0 = Axle0.GetTrack(); // już po przesunięciu - TTrack *t1 = Axle1.GetTrack(); - if (t0->eEnvironment == e_flat && t1->eEnvironment == e_flat) // może być e_bridge... - fShade = 0.0; // standardowe oświetlenie - else - { // jeżeli te tory mają niestandardowy stopień zacienienia - // (e_canyon, e_tunnel) - if (t0->eEnvironment == t1->eEnvironment) - { - switch (t0->eEnvironment) - { // typ zmiany oświetlenia - case e_canyon: - fShade = 0.65f; - break; // zacienienie w kanionie - case e_tunnel: - fShade = 0.20f; - break; // zacienienie w tunelu - } - } - else // dwa różne - { // liczymy proporcję - double d = Axle0.GetTranslation(); // aktualne położenie na torze - if (Axle0.GetDirection() < 0) - d = t0->Length() - d; // od drugiej strony liczona długość - d /= fAxleDist; // rozsataw osi procentowe znajdowanie się na torze - - float shadefrom = 1.0f, shadeto = 1.0f; - // NOTE, TODO: calculating brightness level is used enough times to warrant encapsulation into a function - switch( t0->eEnvironment ) { - case e_canyon: { shadeto = 0.65f; break; } - case e_tunnel: { shadeto = 0.2f; break; } - default: {break; } - } - switch( t1->eEnvironment ) { - case e_canyon: { shadefrom = 0.65f; break; } - case e_tunnel: { shadefrom = 0.2f; break; } - default: {break; } - } - fShade = std::lerp( shadefrom, shadeto, static_cast( d ) ); -/* - switch (t0->eEnvironment) - { // typ zmiany oświetlenia - zakładam, że - // drugi tor ma e_flat - case e_canyon: - fShade = (d * 0.65) + (1.0 - d); - break; // zacienienie w kanionie - case e_tunnel: - fShade = (d * 0.20) + (1.0 - d); - break; // zacienienie w tunelu - } - switch (t1->eEnvironment) - { // typ zmiany oświetlenia - zakładam, że - // pierwszy tor ma e_flat - case e_canyon: - fShade = d + (1.0 - d) * 0.65; - break; // zacienienie w kanionie - case e_tunnel: - fShade = d + (1.0 - d) * 0.20; - break; // zacienienie w tunelu - } -*/ - } - } - } -} - -namespace { - -using ground_triangles = std::vector; - -bool outside( glm::dvec3 const &Centre, double const Radius, glm::dvec2 const &Min, glm::dvec2 const &Max ) { - return Centre.x + Radius < Min.x || Centre.x - Radius > Max.x || Centre.z + Radius < Min.y || Centre.z - Radius > Max.y; -} - -void add_triangle( glm::dvec3 const &A, glm::dvec3 const &B, glm::dvec3 const &C, glm::dvec2 const &Min, glm::dvec2 const &Max, ground_triangles &Out ) { - if( std::max( { A.x, B.x, C.x } ) < Min.x || std::min( { A.x, B.x, C.x } ) > Max.x - || std::max( { A.z, B.z, C.z } ) < Min.y || std::min( { A.z, B.z, C.z } ) > Max.y ) { - return; - } - Out.push_back( { A, B, C } ); -} - -// the triangles of a piece of the scenery's geometry within the rectangle (x, z), as the editor gathers the ground -void add_shape( scene::shape_node const &Shape, glm::dvec2 const &Min, glm::dvec2 const &Max, ground_triangles &Out ) { - auto const &data { Shape.data() }; - if( data.area.radius >= 0.f && outside( data.area.center, data.area.radius, Min, Max ) ) { - return; - } - if( false == data.vertices.empty() ) { - for( std::size_t i = 0; i + 2 < data.vertices.size(); i += 3 ) { - add_triangle( data.vertices[ i ].position, data.vertices[ i + 1 ].position, data.vertices[ i + 2 ].position, Min, Max, Out ); - } - return; - } - // once the shape is uploaded its world-space source is released; the renderer keeps an origin-relative copy - if( data.geometry.bank == 0 && data.geometry.chunk == 0 ) { - return; - } - auto const &vertices { GfxRenderer->Vertices( data.geometry ) }; - auto const &indices { GfxRenderer->Indices( data.geometry ) }; - auto const point = [ &data, &vertices ]( std::size_t const Index ) { return data.origin + glm::dvec3 { vertices[ Index ].position }; }; - if( indices.empty() ) { - for( std::size_t i = 0; i + 2 < vertices.size(); i += 3 ) { - add_triangle( point( i ), point( i + 1 ), point( i + 2 ), Min, Max, Out ); - } - return; - } - for( std::size_t i = 0; i + 2 < indices.size(); i += 3 ) { - if( std::max( { indices[ i ], indices[ i + 1 ], indices[ i + 2 ] } ) >= vertices.size() ) { - continue; - } - add_triangle( point( indices[ i ] ), point( indices[ i + 1 ] ), point( indices[ i + 2 ] ), Min, Max, Out ); - } -} - -// the ground of the scenery within the rectangle (x, z): its terrain and the other opaque geometry of its sections, -// and the heightmap terrain where it is loaded. the models aren't ground -ground_triangles scenery_ground( glm::dvec2 const &Min, glm::dvec2 const &Max ) { - ground_triangles triangles; - if( simulation::Region == nullptr ) { - return triangles; - } - auto const centre { 0.5 * ( Min + Max ) }; - std::vector sections; - simulation::Region->sections( glm::dvec3 { centre.x, 0.0, centre.y }, static_cast( 0.5 * glm::length( Max - Min ) ), sections ); - for( auto const *section : sections ) { - for( auto const &shape : section->m_shapes ) { - add_shape( shape, Min, Max, triangles ); - } - for( auto const &cell : section->m_cells ) { - if( outside( cell.m_area.center, cell.m_area.radius, Min, Max ) ) { - continue; - } - for( auto const &shape : cell.m_shapesopaque ) { - add_shape( shape, Min, Max, triangles ); - } - } - } - if( EditorTerrain.active() ) { - EditorTerrain.gather_triangles( Min, Max, triangles ); - } - return triangles; -} - -glm::dvec3 level_left_of( glm::dvec3 const &Front ) { - return glm::dvec3 { Front.z, 0.0, -Front.x }; -} - -// the end of the vehicle where it meets the one coupled to it: the middle of its buffer beam, the way it faces. off the -// track, over its base on the ground as it stands: rolled over, its ends go with it as far as the coupling holds them, -// and the buffers of the side it rolled to miss those of an upright one -derail_motion::end_point end_point_of( TDynamicObject const &Vehicle, int const End ) { - auto const facing { End == end::front ? 1.0 : -1.0 }; - auto const &motion { Vehicle.MoverParameters->OffTrack }; - glm::dvec3 const front { Vehicle.VectorFront().x, 0.0, Vehicle.VectorFront().z }; - auto const length { glm::length( front ) }; - auto const axis { length > 1e-6 ? front / length : glm::dvec3 { 0.0, 0.0, 1.0 } }; - auto const middle { motion.active() ? motion.base() : Vehicle.GetPosition() }; - return derail_motion::end_point { - middle + glm::dvec3 { 0.0, derail_motion::buffer_height, 0.0 } + axis * ( facing * 0.5 * Vehicle.MoverParameters->Dim.L ), - axis * facing, - motion.active() ? motion.tipping() : 0.0 }; -} - -// the push of the buffers on the end of the vehicle [N], negative the pull of its coupling -double compression_of( TMoverParameters const &Vehicle, int const End ) { - return ( End == end::front ? -1.0 : 1.0 ) * Vehicle.Couplers[ End ].CForce; -} - -// the time spent off the track in a frame which makes it worth a warning [s] -constexpr double off_track_slow { 0.02 }; - -using off_track_clock = std::chrono::steady_clock; - -double seconds_since( off_track_clock::time_point const Start ) { - return std::chrono::duration( off_track_clock::now() - Start ).count(); -} - -std::string_view side_name( int const Side ) { - if( Side > 0 ) { - return "left"; - } - return Side < 0 ? "right" : "none"; -} - -} // namespace - -double TDynamicObject::off_track_gap( int const End ) const { - - auto const *neighbour { MoverParameters->Neighbours[ End ].vehicle }; - if( neighbour == nullptr ) { - return 0.0; - } - return derail_motion::meet( end_point_of( *this, End ), end_point_of( *neighbour, MoverParameters->Neighbours[ End ].vehicle_end ) ).gap; -} - -double TDynamicObject::off_track_offset() const { - - if( false == MoverParameters->OffTrack.active() ) { - return 0.0; - } - auto const middle { 0.5 * ( Axle0.pPosition + Axle1.pPosition ) }; - auto const offset { vPosition - middle }; - return glm::dot( glm::dvec3 { offset.x, 0.0, offset.z }, level_left_of( track_front() ) ); -} - -glm::dvec3 TDynamicObject::track_front() const { - - auto const along { Axle0.pPosition - Axle1.pPosition }; - glm::dvec3 const flat { along.x, 0.0, along.z }; - auto const length { glm::length( flat ) }; - return length > 1e-6 ? flat / length : glm::dvec3 { 0.0, 0.0, 1.0 }; -} - -derail_motion::formation TDynamicObject::track_bed() const { - - derail_motion::formation bed; - bed.point = 0.5 * ( Axle0.pPosition + Axle1.pPosition ); - bed.direction = track_front(); - if( auto const *track { RaTrackGet() }; track != nullptr ) { - // the ballast out of the rails, as wide as the track draws it - bed.half_width = std::clamp( 0.5 * std::abs( track->fTrackWidth ) + std::abs( track->fTexWidth ), 1.2, 3.5 ); - } - return bed; -} - -int TDynamicObject::outward_side() const { - - // the track as designed turns from the rear axle to the front one: the outside of its curve, or its inside where a - // buckle bends the line the other way more than the curve does (the criteria of derailment, physics/derailment.h) - if( auto const design { std::sin( Axle1.vAngles.z - Axle0.vAngles.z ) }; std::abs( design ) >= 1e-4 ) { - auto const outside { design > 0.0 ? -1 : 1 }; - return MoverParameters->DerailAcceleration < 0.0 ? -outside : outside; - } - // a straight track: the path under the vehicle as it is, a buckle on it, turns from the rear axle to the front one - auto const front { Axle0.PathDirection() }; - auto const rear { Axle1.PathDirection() }; - auto const turn { glm::dot( front, level_left_of( rear ) ) }; - // a turn under a tenth of a milliradian is a straight track - if( std::abs( turn ) < 1e-4 ) { - return 0; - } - // turning left, the outside of the curve is on the right - return turn > 0.0 ? -1 : 1; -} - -void TDynamicObject::gather_off_track_terrain() { - - auto const &mover { *MoverParameters }; - auto const &position { mover.OffTrack.active() ? mover.OffTrack.current().position : vPosition }; - // as far as it may slide, and some - auto const slide { derail_motion::stopping_distance( mover.V, derailment::off_rails_friction ).value_or( 0.0 ) }; - auto const reach { std::min( slide + mover.Dim.L + 50.0, 600.0 ) }; - m_offtrackgathered = m_offtracktotal; - m_offtrackcropped = false; - // the terrain of another vehicle, where it covers the way this one goes: around it and around where it stops going - // straight on, by its length and the margin the terrain is gathered again at - glm::dvec3 heading { vFront.x, 0.0, vFront.z }; - if( mover.OffTrack.active() ) { - heading = mover.OffTrack.heading(); - } - auto const length { glm::length( heading ) }; - auto const stop { length > 1e-6 ? position + heading * ( std::copysign( std::max( reach - mover.Dim.L - 50.0, 0.0 ), mover.V ) / length ) : position }; - auto const margin { mover.Dim.L + 30.0 }; - if( auto shared { simulation::Vehicles.off_track_terrain( - glm::dvec2 { std::min( position.x, stop.x ) - margin, std::min( position.z, stop.z ) - margin }, - glm::dvec2 { std::max( position.x, stop.x ) + margin, std::max( position.z, stop.z ) + margin } ) }; - shared != nullptr ) { - m_offtrackterrain = std::move( shared ); - m_offtrackmin = m_offtrackterrain->minimum(); - m_offtrackmax = m_offtrackterrain->maximum(); - m_offtracksite.terrain( m_offtrackterrain.get() ); - return; - } - m_offtrackmin = glm::dvec2 { position.x - reach, position.z - reach }; - m_offtrackmax = glm::dvec2 { position.x + reach, position.z + reach }; - auto const started { off_track_clock::now() }; - auto triangles { scenery_ground( m_offtrackmin, m_offtrackmax ) }; - auto const trimmed { triangles.size() > off_track_triangles }; - if( trimmed ) { - // a scenery dense enough to make it slow: the triangles nearest to it are enough - std::nth_element( triangles.begin(), triangles.begin() + off_track_triangles, triangles.end(), - [ &position ]( auto const &Left, auto const &Right ) { - auto const distance = [ &position ]( auto const &Triangle ) { - auto const middle { ( Triangle[ 0 ] + Triangle[ 1 ] + Triangle[ 2 ] ) / 3.0 }; - return std::max( std::abs( middle.x - position.x ), std::abs( middle.z - position.z ) ); }; - return distance( Left ) < distance( Right ); } ); - triangles.resize( off_track_triangles ); - ErrorLog( std::format( "derailment: warning: {} found more than {} triangles of terrain around it, took the nearest", MoverParameters->Name, off_track_triangles ) ); - } - if( triangles.empty() ) { - // a scenery without terrain: level with the top of the ballast - m_offtrackterrain.reset(); - } - else { - m_offtrackterrain = std::make_shared( triangles, m_offtrackmin, m_offtrackmax ); - // the vehicles sliding over it take it as it is; the nearest triangles of a dense scenery are its own - if( false == trimmed ) { - simulation::Vehicles.share_off_track_terrain( m_offtrackterrain ); - } - } - m_offtracksite.terrain( m_offtrackterrain.get() ); - auto const took { seconds_since( started ) }; - if( took > off_track_slow ) { - ErrorLog( std::format( "derailment: warning: gathering the terrain of {:.0f} m around {} took {:.0f} ms ({} triangles)", reach, MoverParameters->Name, took * 1000.0, triangles.size() ) ); - } -} - -void TDynamicObject::crop_off_track_terrain() { - - if( m_offtrackcropped || m_offtrackterrain == nullptr ) { - return; - } - m_offtrackcropped = true; - // the ground under it, and as far around as it gathers the terrain anew once it moves again - auto const &position { MoverParameters->OffTrack.current().position }; - auto const reach { 0.5 * MoverParameters->Dim.L + 40.0 }; - m_offtrackmin = glm::dvec2 { position.x - reach, position.z - reach }; - m_offtrackmax = glm::dvec2 { position.x + reach, position.z + reach }; - m_offtrackterrain = std::make_shared( m_offtrackterrain->cropped( m_offtrackmin, m_offtrackmax ) ); - m_offtracksite.terrain( m_offtrackterrain.get() ); -} - -void TDynamicObject::begin_off_track() { - - auto &mover { *MoverParameters }; - derail_motion::vehicle_shape shape; - shape.length = mover.Dim.L; - shape.width = mover.Dim.W > 0.5 ? mover.Dim.W : 3.0; - // a height up to 2 m in the definition is the height of the floor, the older meaning of the key - shape.height = mover.Dim.H > 2.0 ? mover.Dim.H : 4.0; - shape.centre_of_gravity = mover.centre_of_gravity(); - shape.contact_spacing = derailment::contact_spacing( mover.TrackW ); - shape.base = std::max( static_cast( fAxleDist ), 1.0 ); - shape.mass = mover.TotalMass; - - derail_motion::start start; - start.position = vPosition; - start.front = vFront; - start.line = track_front(); - start.speed = mover.V; - start.reason = mover.DerailCause; - start.outward = ( mover.DerailSide != 0 ? mover.DerailSide : outward_side() ); - start.acceleration = mover.DerailAcceleration; - - // the terrain as far as it may slide, and some - m_offtracktotal = 0.0; - gather_off_track_terrain(); - m_offtracksite = derail_motion::site { m_offtrackterrain.get(), track_bed() }; - // each vehicle its own way of going off, from the seed of the run (the same seed, the same way) - auto const scatter { derail_motion::draw_scatter( derail_motion::seed_of( Global.random_seed, mover.Name ) ) }; - mover.OffTrack.begin( start, shape, m_offtracksite, scatter ); - m_pulledoff = {}; - m_offtracklogdue = 0.0; - m_offtrackslowdue = 0.0; - m_offtrackaxles = 0.0; - m_offtrackfrom = mover.OffTrack.current().position; - - auto const heading { mover.OffTrack.heading() }; - auto const front { glm::dvec3 { vFront.x, 0.0, vFront.z } }; - auto const turn { std::asin( std::clamp( glm::dot( heading, level_left_of( glm::normalize( front ) ) ), -1.0, 1.0 ) ) }; - std::string terrain { "no terrain, level ground" }; - if( m_offtrackterrain != nullptr ) { - terrain = std::format( "{} triangles of terrain", m_offtrackterrain->size() ); - } - WriteLog( std::format( - "derailment: {} leaves the track at {:.0f} km/h on track {}, heading turned {:.1f} deg to the {}, the outside of the curve to the {}; {} around it", - mover.Name, std::abs( mover.V ) * 3.6, MyTrack != nullptr ? MyTrack->name() : std::string { "(none)" }, - std::abs( glm::degrees( turn ) ), side_name( turn >= 0.0 ? 1 : -1 ), side_name( start.outward ), terrain ) ); - WriteLog( std::format( - "derailment: {} scattered by {:+.2f} deg of departure, {:+.2f} deg of yaw at {:+.3f} rad/s, the friction under its ends x{:.2f} / x{:.2f}{}", - mover.Name, glm::degrees( scatter.departure ), glm::degrees( scatter.yaw ), scatter.yaw_rate, scatter.friction_front, scatter.friction_rear, - scatter.dig_in >= 0.0 ? std::format( ", its leading end digs in after {:.2f} s, x{:.2f} for {:.2f} s", scatter.dig_in, scatter.dig_in_friction, scatter.dig_in_time ) : std::string {} ) ); -} - -void TDynamicObject::move_off_track( double const Distance ) { - - auto const started { off_track_clock::now() }; - auto &motion { MoverParameters->OffTrack }; - auto const time { std::exchange( m_offtracktime, 0.0 ) }; - m_offtracktotal += time; - // near the edge of the terrain gathered, the terrain further on; not more than once a second, whatever happens - if( m_offtrackterrain != nullptr && Distance != 0.0 && m_offtracktotal - m_offtrackgathered >= 1.0 ) { - auto const &position { motion.current().position }; - constexpr double margin { 30.0 }; - if( position.x - margin < m_offtrackmin.x || position.x + margin > m_offtrackmax.x - || position.z - margin < m_offtrackmin.y || position.z + margin > m_offtrackmax.y ) { - gather_off_track_terrain(); - } - } - m_offtracksite.bed( track_bed() ); - // the buffers and the couplings of its ends push and pull it, at an angle to it where the vehicle coupled there is - std::array ends {}; - for( int end = end::front; end <= end::rear; ++end ) { - auto const *neighbour { MoverParameters->Neighbours[ end ].vehicle }; - auto const compression { compression_of( *MoverParameters, end ) }; - if( neighbour == nullptr || compression == 0.0 ) { - continue; - } - ends[ end ] = derail_motion::force_on( - derail_motion::meet( end_point_of( *this, end ), end_point_of( *neighbour, MoverParameters->Neighbours[ end ].vehicle_end ) ), compression ); - } - auto const reversals { motion.reversals() }; - motion.step( time, Distance, MoverParameters->V, m_offtracksite, ends ); - if( ( motion.reversals() - reversals ) % 2 != 0 ) { - // the body turned about against the way it goes: the vehicle goes rear first, its speed the other way along it - MoverParameters->V = -MoverParameters->V; - } - auto const &pose { motion.current() }; - // the axles go along the track as far as the vehicle went along it, for the track nearest to it: the vehicles on it - // find it there, the events of the track are passed. by 10 cm at least: a body turning or rocking in place moves - // the axles back and forth by millimetres, which over the end of a track would fire its events every frame. from - // where it was the last time, so the moves out of the other bodies between the frames go into the axles too - m_offtrackaxles += glm::dot( pose.position - std::exchange( m_offtrackfrom, pose.position ), track_front() ); - if( std::abs( m_offtrackaxles ) >= 0.1 ) { - move_axles( std::exchange( m_offtrackaxles, 0.0 ) ); - } - - place_off_track(); - if( motion.at_rest() ) { - crop_off_track_terrain(); - } - - pull_neighbours( Distance ); - - // what it cost: a frame of the vehicle off the track should take well under a millisecond - auto const took { seconds_since( started ) }; - m_offtrackslowdue -= time; - if( took > off_track_slow && m_offtrackslowdue <= 0.0 ) { - m_offtrackslowdue = 1.0; - ErrorLog( std::format( "derailment: warning: moving {} off the track took {:.0f} ms in a frame of {:.3f} s", MoverParameters->Name, took * 1000.0, time ) ); - } -} - -void TDynamicObject::place_off_track() { - - auto const &pose { MoverParameters->OffTrack.current() }; - vPosition = pose.position; - vFront = pose.front; - vLeft = pose.left; - vUp = pose.up; - modelRot.z = std::atan2( -vFront.x, vFront.z ); - mMatrix = glm::inverse( BasisChange( vLeft, vUp, vFront ) ); - auto const half { 0.5 * MoverParameters->Dim.L * vFront }; - vCoulpler[ end::front ] = vPosition + half; - vCoulpler[ end::rear ] = vPosition - half; - m_offtrackplaced = true; -} - -void TDynamicObject::pull_neighbours( double const Distance ) { - - for( int end = end::front; end <= end::rear; ++end ) { - auto const &coupler { MoverParameters->Couplers[ end ] }; - auto *neighbour { MoverParameters->Neighbours[ end ].vehicle }; - if( coupler.CouplingFlag == Coupling::none || neighbour == nullptr || neighbour->MoverParameters->OffTrack.active() - || neighbour->MoverParameters->DamageFlag.HasAll(VehicleDamage::derailed) ) { - m_pulledoff[ end ].reset(); - continue; - } - auto &other { *neighbour->MoverParameters }; - auto const otherend { MoverParameters->Neighbours[ end ].vehicle_end }; - glm::dvec3 const otherfront { neighbour->vFront.x, 0.0, neighbour->vFront.z }; - if( glm::length( otherfront ) < 1e-6 ) { - continue; - } - // the coupling pulls the end of the other vehicle towards the beam of this one, the buffers push it along the - // bisector of the bend between them: at an angle to its axis, the part across it on its leading wheels - auto const compression { compression_of( other, otherend ) }; - auto const force { derail_motion::force_on( derail_motion::meet( end_point_of( *neighbour, otherend ), end_point_of( *this, end ) ), compression ).force }; - auto const axis { glm::normalize( otherfront ) }; - auto const across { glm::dot( force, level_left_of( axis ) ) }; - auto const angle { std::atan2( std::abs( across ), std::abs( glm::dot( force, axis ) ) ) }; - auto const magnitude { glm::length( glm::dvec3 { force.x, 0.0, force.z } ) }; - auto const mass { other.TotalMass - other.Mred }; - auto const ratio { derail_motion::pull_ratio( magnitude, angle, mass, other.NAxles ) }; - if( false == m_pulledoff[ end ].update( ratio >= derailment::climbing_limit, Distance ) ) { - continue; - } - // the way the force across it goes: towards this one pulled, away from it pushed - auto const side { across >= 0.0 ? 1 : -1 }; - other.pull_off( - side, - mass > 0.0 ? std::abs( across ) / mass : 0.0, - std::format( "Y/Q {:.2f} from the {} of {} at {:.0f} deg, {:.0f} kN", ratio, compression > 0.0 ? "buffers" : "coupling", MoverParameters->Name, glm::degrees( angle ), magnitude / 1000.0 ) ); - m_pulledoff[ end ].reset(); - } -} - -void TDynamicObject::update_off_track( double const Deltatime ) { - - auto const &motion { MoverParameters->OffTrack }; - if( false == motion.active() || m_offtracklogdue < 0.0 ) { - // on the track, or came to rest and told so - return; - } - m_offtracklogdue -= Deltatime; - auto const resting { motion.at_rest() }; - if( m_offtracklogdue > 0.0 && false == resting ) { - return; - } - m_offtracklogdue = ( resting ? -1.0 : 1.0 ); - WriteLog( std::format( - "derailment: {} {} {:.1f} m from where it left the rails, {:.1f} m from the axis of the track, at {:.1f} km/h, sliding sideways at {:.1f} m/s, tipped {:.0f} deg, roll {:.0f} deg, yaw {:+.1f} deg turning at {:+.1f} deg/s{}", - MoverParameters->Name, resting ? "came to rest" : "off the track", motion.travelled(), off_track_offset(), std::abs( MoverParameters->V ) * 3.6, motion.sideways(), - glm::degrees( motion.tipping() ), glm::degrees( motion.roll() ), glm::degrees( motion.yaw() ), glm::degrees( motion.yaw_rate() ), motion.lying() ? ", lying on its side" : "" ) ); -} - -void TDynamicObject::AttachNext(TDynamicObject *Object, int iType) -{ // Ra: doczepia Object na końcu składu (nazwa funkcji może być myląca) - // Ra: używane tylko przy wczytywaniu scenerii - auto const vehicleend { iDirection }; - auto const othervehicleend { Object->iDirection ^ 1 }; - - MoverParameters->Attach( vehicleend, othervehicleend, Object->MoverParameters, CouplingSet::FromBits( iType ), true, false ); - // update neighbour data for both affected vehicles - update_neighbours(); - Object->update_neighbours(); - - // potentially attach automatic coupler adapter to allow the connection - // HACK: we're doing it after establishin actual connection, as the method needs valid neighbour data - auto &coupler { MoverParameters->Couplers[ vehicleend ] }; - auto &othercoupler { Object->MoverParameters->Couplers[ ( othervehicleend != 2 ? othervehicleend : coupler.ConnectedNr ) ] }; - - if( coupler.type() != othercoupler.type() ) { - if( othercoupler.type() == TCouplerType::Automatic ) { - // try to attach adapter to the vehicle - attach_coupler_adapter( - vehicleend, - true ); - } - else if( coupler.type() == TCouplerType::Automatic ) { - // try to attach adapter to the other vehicle - Object->attach_coupler_adapter( - othervehicleend != 2 ? othervehicleend : coupler.ConnectedNr, - true ); - } - // update distance to neighbours on account of potentially attached adapter - update_neighbours(); - Object->update_neighbours(); - } - // potentially adjust vehicle position to avoid collision at the simulation start - if( MoverParameters->Neighbours[ vehicleend ].distance > -0.001 ) { return; } - - Object->Move( MoverParameters->Neighbours[ vehicleend ].distance * Object->DirectionGet() ); - // HACK: manually update vehicle position as it's used by neighbour distance update we do next - Object->MoverParameters->Loc = { - -Object->vPosition.x, - Object->vPosition.z, - Object->vPosition.y }; - // update neighbour distance data after moving our vehicle - update_neighbours(); - Object->update_neighbours(); -} - -bool TDynamicObject::UpdateForce(double dt) -{ - if (!bEnabled) - return false; - if( dt > 0 ) { - // wywalenie WS zależy od ustawienia kierunku - MoverParameters->ComputeTotalForce( dt ); - } - return true; -} - -// initiates load change by specified amounts, with a platform on specified side -void TDynamicObject::LoadExchange( int const Disembark, int const Embark, int const Platforms ) { -/* - if( ( MoverParameters->Doors.open_control == control_t::passenger ) - || ( MoverParameters->Doors.open_control == control_t::mixed ) ) { - // jeśli jedzie do tyłu, to drzwi otwiera odwrotnie - auto const lewe = ( DirectionGet() > 0 ) ? 1 : 2; - auto const prawe = 3 - lewe; - if( Platform & lewe ) { - MoverParameters->OperateDoors( side::left, true, range_t::local ); - } - if( Platform & prawe ) { - MoverParameters->OperateDoors( side::right, true, range_t::local ); - } - } -*/ - if( Platforms == 0 ) { return; } // edge case, if there's no accessible platforms discard the request - - m_exchange.unload_count += Disembark; - m_exchange.load_count += Embark; - m_exchange.platforms = Platforms; - m_exchange.time = 0.0; -} - -// calculates time needed to complete current load change -float TDynamicObject::LoadExchangeTime( int const Platforms ) { - - m_exchange.platforms = Platforms; - return LoadExchangeTime(); -} - -float TDynamicObject::LoadExchangeTime() const { - - if( m_exchange.unload_count < 0.01 && m_exchange.load_count < 0.01 ) { return 0.f; } - - auto const baseexchangetime { m_exchange.unload_count / MoverParameters->UnLoadSpeed + m_exchange.load_count / MoverParameters->LoadSpeed }; - auto const nominalexchangespeedfactor { ( m_exchange.platforms == 3 ? 2.f : 1.f ) }; - auto const actualexchangespeedfactor { LoadExchangeSpeed() }; - - return baseexchangetime / ( actualexchangespeedfactor > 0.f ? actualexchangespeedfactor : nominalexchangespeedfactor ); -} - -// calculates current load exchange rate -float TDynamicObject::LoadExchangeSpeed() const { - // platforms (1:left, 2:right, 3:both) - // with exchange performed on both sides waiting times are halved - auto exchangespeedfactor { 0.f }; - auto const lewe { DirectionGet() > 0 ? 1 : 2 }; - auto const prawe { 3 - lewe }; - if( m_exchange.platforms & lewe ) { - exchangespeedfactor += MoverParameters->Doors.instances[side::left].is_open ? 1.f : 0.f; - } - if( m_exchange.platforms & prawe ) { - exchangespeedfactor += MoverParameters->Doors.instances[side::right].is_open ? 1.f : 0.f; - } - - return exchangespeedfactor; -} - -// update state of load exchange operation -void TDynamicObject::update_exchange( double const Deltatime ) { - - // TODO: move offset calculation after initial check, when the loading system is all unified - update_load_offset(); - - if( m_exchange.unload_count < 0.01 && m_exchange.load_count < 0.01 ) { return; } - - if( MoverParameters->Vel < 2.0 ) { - - auto const exchangespeed { LoadExchangeSpeed() }; - - if( exchangespeed < ( m_exchange.platforms == 3 ? 2.f : 1.f ) ) { - // the exchange isn't performed at optimal rate, or at all. try to open viable vehicle doors to speed it up - auto const lewe { DirectionGet() > 0 ? 1 : 2 }; - auto const prawe { 3 - lewe }; - if( m_exchange.platforms & lewe - && false == (MoverParameters->Doors.instances[side::left].is_open || MoverParameters->Doors.instances[side::left].is_opening) ) { - // try to open left door - MoverParameters->OperateDoors( side::left, true, range_t::local ); - } - if( m_exchange.platforms & prawe - && false == (MoverParameters->Doors.instances[side::right].is_open || MoverParameters->Doors.instances[side::right].is_opening) ) { - // try to open right door - MoverParameters->OperateDoors( side::right, true, range_t::local ); - } - } - - if( exchangespeed > 0.f ) { - - m_exchange.time += Deltatime; - while( m_exchange.unload_count > 0.01 - && m_exchange.time >= 1.0 ) { - - m_exchange.time -= 1.0; - auto const exchangesize = std::min( m_exchange.unload_count, MoverParameters->UnLoadSpeed * exchangespeed ); - m_exchange.unload_count -= exchangesize; - MoverParameters->LoadStatus = 1; - MoverParameters->LoadAmount = std::max( 0.f, MoverParameters->LoadAmount - exchangesize ); - MoverParameters->ComputeMass(); - update_load_visibility(); - } - if( m_exchange.unload_count < 0.01 ) { - // finish any potential unloading operation before adding new load - // don't load more than can fit - m_exchange.load_count = std::min( m_exchange.load_count, MoverParameters->MaxLoad - MoverParameters->LoadAmount ); - while( m_exchange.load_count > 0.01 - && m_exchange.time >= 1.0 ) { - - m_exchange.time -= 1.0; - auto const exchangesize = std::min( m_exchange.load_count, MoverParameters->LoadSpeed * exchangespeed ); - m_exchange.load_count -= exchangesize; - MoverParameters->LoadStatus = 2; - MoverParameters->LoadAmount = std::min( MoverParameters->MaxLoad, MoverParameters->LoadAmount + exchangesize ); // std::max not strictly needed but, eh - MoverParameters->ComputeMass(); - update_load_visibility(); - } - } - } - } - - if( MoverParameters->Vel > 2.0 ) { - // if the vehicle moves too fast cancel the exchange - m_exchange.unload_count = 0; - m_exchange.load_count = 0; - } - - if( m_exchange.unload_count < 0.01 - && m_exchange.load_count < 0.01 ) { - - MoverParameters->LoadStatus = 4; - // if the exchange is completed (or canceled) close the door, if applicable - if( MoverParameters->Doors.close_control == control_t::passenger - || MoverParameters->Doors.close_control == control_t::mixed ) { - - if( MoverParameters->Vel > 2.0 - || Random() < ( - // remotely controlled door are more likely to be left open - MoverParameters->Doors.close_control == control_t::passenger ? 0.75 : 0.50) ) { - - MoverParameters->OperateDoors( side::left, false, range_t::local ); - MoverParameters->OperateDoors( side::right, false, range_t::local ); - } - } - // if the vehicle was emptied potentially switch load visualization model - if( MoverParameters->LoadAmount == 0 ) { - MoverParameters->AssignLoad( "" ); - } - } -} - -void TDynamicObject::LoadUpdate() { - - MoverParameters->LoadStatus &= 1 | 2; // po zakończeniu będzie równe zero - // przeładowanie modelu ładunku - if( MoverParameters->LoadTypeChange ) { - // whether we succeed or not don't try more than once - MoverParameters->LoadTypeChange = false; - // bieżąca ścieżka do tekstur to dynamic/... - Global.asCurrentTexturePath = asBaseDir; - mdLoad = LoadMMediaFile_mdload( MoverParameters->LoadType.name ); - // TODO: discern from vehicle component which merely uses vehicle directory and has no animations, so it can be initialized outright - // and actual vehicles which get their initialization after their animations are set up - if( mdLoad != nullptr ) { - mdLoad->Init(); - } - // update bindings between lowpoly sections and potential load chunks placed inside them - update_load_sections(); - // z powrotem defaultowa sciezka do tekstur - Global.asCurrentTexturePath = std::string( paths::textures ); - } -} - -void -TDynamicObject::update_load_sections() { - - SectionLoadOrder.clear(); - - for( auto §ion : Sections ) { - - section.load = GetSubmodelFromName( mdLoad, section.compartment->pName ); - - if( section.load != nullptr ) { - // create entry for each load model chunk assigned to the section - // TBD, TODO: store also pointer to chunk submodel and control its visibility more directly, instead of per-section visibility flag? - auto loadchunkcount { section.load->count_children() }; - while( loadchunkcount-- ) { - SectionLoadOrder.push_back( §ion ); - } - // HACK: disable automatic self-illumination threshold, at least until 3d model update - if( MoverParameters->CompartmentLights.start_type == start_t::manual ) { - section.load->SetSelfIllum( 2.0f, true, false ); - } - } - } - shuffle_load_order(); -} - -void -TDynamicObject::update_load_visibility() { - // start with clean load chunk visibility slate - for( auto §ion : Sections ) { - section.load_chunks_visible = 0; - } - // each entry in load order sequence matches a single chunk of the section it points to - // the length of load order sequence matches total number of load chunks - auto const loadpercentage { ( - MoverParameters->MaxLoad == 0.f ? - 0.0 : - MoverParameters->LoadAmount / MoverParameters->MaxLoad ) }; - auto visiblechunkcount { ( - SectionLoadOrder.empty() ? - 0 : - static_cast( std::ceil( loadpercentage * SectionLoadOrder.size() - 0.001f ) ) ) }; - for( auto *section : SectionLoadOrder ) { - if( visiblechunkcount == 0 ) { break; } - section->load_chunks_visible++; - --visiblechunkcount; - } -} - -void -TDynamicObject::update_load_offset() { - - if( MoverParameters->LoadType.offset_min == 0.f ) { return; } - - auto const loadpercentage { ( - MoverParameters->MaxLoad == 0.f ? - 0.0 : - 100.0 * MoverParameters->LoadAmount / MoverParameters->MaxLoad ) }; - - LoadOffset = std::lerp( MoverParameters->LoadType.offset_min, 0.f, safe_clamp( 0.0, 1.0, loadpercentage * 0.01 ) ); -} - -void -TDynamicObject::shuffle_load_order() { - - // order of visible load chunks, nothing security related -- see the engines in Globals.h - std::shuffle( std::begin( SectionLoadOrder ), std::end( SectionLoadOrder ), Global.random_engine ); // NOSONAR - // shift chunks assigned to corridors to the end of the list, so they show up last - std::stable_partition( - std::begin( SectionLoadOrder ), std::end( SectionLoadOrder ), - []( vehicle_section const *section ) { - return section->compartment->pName.find("compartment") == 0 || section->compartment->pName.find("przedzial") == 0; } ); - // NOTE: potentially we're left with a mix of corridor and external section loads - // but that's not necessarily a wrong outcome, so we leave it this way for the time being -} - -/* -Ra: - Powinny być dwie funkcje wykonujące aktualizację fizyki. Jedna wykonująca -krok obliczeń, powtarzana odpowiednią liczbę razy, a druga wykonująca zbiorczą -aktualzację mniej istotnych elementów. - Ponadto należało by ustalić odległość składów od kamery i jeśli przekracza -ona np. 10km, to traktować składy jako uproszczone, np. bez wnikania w siły -na sprzęgach, opóźnienie działania hamulca itp. Oczywiście musi mieć to pewną -histerezę czasową, aby te tryby pracy nie przełączały się zbyt szybko. -*/ - -void TDynamicObject::update_destinations() { - - if( DestinationSign.sign == nullptr ) { return; } - - auto const lowvoltagepower { ( MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable ) }; - - DestinationSign.sign->fLight = DestinationSign.has_light && lowvoltagepower ? 2.0 : -1.0; - - // jak są 4 tekstury wymienne, to nie zmieniać rozkładem - if( std::abs( m_materialdata.multi_textures ) >= 4 ) { return; } - // TODO: dedicated setting to discern electronic signs, instead of fallback on light presence - m_materialdata.replacable_skins[ 4 ] = DestinationSign.destination != null_handle && (false == DestinationSign.has_light // physical destination signs remain up until manually changed - || (lowvoltagepower // lcd signs are off without power - && ctOwner != nullptr)) ? // lcd signs are off for carriages without engine, potentially left on a siding - DestinationSign.destination : - DestinationSign.destination_off; - - update_script_destination(); -} - -void TDynamicObject::update_script_destination() { - - if( DestinationSign.script_sign == nullptr ) { return; } - // only while the sign shows the destination it draws - if( m_materialdata.replacable_skins[ 4 ] != DestinationSign.destination ) { return; } - - auto &queue { Application.screens() }; - if( false == queue.due( *DestinationSign.script_sign ) ) { return; } - // read anew on every refresh, so the sign follows the timetable - queue.submit( DestinationSign.script_sign, std::make_shared( DestinationSign.script_request ), 0 ); -} - -bool TDynamicObject::Update(double dt, double dt1) -{ - if (dt1 == 0.0) - return true; // Ra: pauza - // physics.derailment new: all of the update of a vehicle off the track, timed; a warning once a second at most when it - // takes long, to find what makes a derailment slow - // (no vehicle when it is on the track: nothing is timed then) - class off_track_watch { - public: - off_track_watch( TDynamicObject *Vehicle, double const Frame ) : - vehicle { Vehicle }, frame { Frame } { - if( vehicle != nullptr ) { - started = off_track_clock::now(); - } - } - off_track_watch( off_track_watch const & ) = delete; - off_track_watch &operator=( off_track_watch const & ) = delete; - ~off_track_watch() { - if( vehicle == nullptr ) { - return; - } - auto const took { seconds_since( started ) }; - vehicle->m_offtrackupdatedue -= frame; - if( took > off_track_slow && vehicle->m_offtrackupdatedue <= 0.0 ) { - vehicle->m_offtrackupdatedue = 1.0; - ErrorLog( std::format( "derailment: warning: the update of {} off the track took {:.0f} ms in a frame of {:.3f} s", vehicle->MoverParameters->Name, took * 1000.0, frame ) ); - } - } - private: - TDynamicObject *vehicle; - double frame; - off_track_clock::time_point started {}; - }; - off_track_watch const watch { MoverParameters->OffTrack.active() ? this : nullptr, dt1 }; - if( m_offtrackterrain != nullptr && false == MoverParameters->OffTrack.active() ) { - // physics.derailment new: back on the rails (rerail()), the terrain it slid over is let go - m_offtrackterrain.reset(); - m_offtracksite.terrain( nullptr ); - } - if (!MoverParameters->PhysicActivation && - !MechInside) { // to drugie, bo będąc w maszynowym blokuje się fizyka - // physics.derailment new: a vehicle off the track stopped along its heading still settles: it slides down a - // slope, falls over, or comes to rest after the step its physics stopped in - if( MoverParameters->OffTrack.active() && false == MoverParameters->OffTrack.at_rest() && bEnabled ) { - m_offtracktime = dt1; - Move( 0.0 ); - update_off_track( dt1 ); - } - return true; // McZapkie: wylaczanie fizyki gdy nie potrzeba - } - if (!MyTrack) - return false; // pojazdy postawione na torach portalowych mają MyTrack==NULL - if (!bEnabled) - return false; // a normalnie powinny mieć bEnabled==false - - double dDOMoveLen; - // McZapkie: parametry powinny byc pobierane z toru - if (Axle0.vAngles.z != Axle1.vAngles.z) - { // wyliczenie promienia z obrotów osi - modyfikację zgłosił youBy - ts.R = Axle0.vAngles.z - Axle1.vAngles.z; // różnica może dawać stałą ±M_2PI - if( ts.R > 15000.0 || ts.R < -15000.0 ) { - // szkoda czasu na zbyt duże promienie, 4km to promień nie wymagający przechyłki - ts.R = 0.0; - } - else { - // normalizacja - if( ts.R > M_PI ) { ts.R -= M_2PI; } - else if( ts.R < -M_PI ) { ts.R += M_2PI; } - - if( ts.R != 0.0 ) { - // sin(0) results in division by zero - ts.R = -0.5 * MoverParameters->BDist / sin( ts.R * 0.5 ); - } - } - } - else - ts.R = 0.0; - // ts.R=ComputeRadius(Axle1.pPosition,Axle2.pPosition,Axle3.pPosition,Axle0.pPosition); - // Ra: składową pochylenia wzdłużnego mamy policzoną w jednostkowym wektorze - // vFront - ts.Len = 1.0; // std::max(MoverParameters->BDist,MoverParameters->ADist); - ts.dHtrack = -vFront.y; // Axle1.pPosition.y-Axle0.pPosition.y; //wektor - // między skrajnymi osiami - // (!!!odwrotny) - ts.dHrail = (Axle1.GetRoll() + Axle0.GetRoll()) * 0.5; //średnia przechyłka pudła - // the uneven track under the outer axles, for the criteria of derailment: its lateral curvature, and its cross level - ts.uneven_curvature = glm::dot( 0.5 * ( Axle0.UnevenBend() + Axle1.UnevenBend() ), vLeft ); - ts.uneven_cross = MyTrack->uneven_underway().cross; - // a buckle of the track under the body: the mean of the curvatures at the outer axles, each over the wheelbase of its bogie - ts.buckle_curvature = 0.5 * ( Axle0.BuckleCurvature( MoverParameters->ADist ) + Axle1.BuckleCurvature( MoverParameters->ADist ) ); - // TTrackParam tp; - tp.Width = MyTrack->fTrackWidth; - // McZapkie-250202 - tp.friction = MyTrack->Friction() * Global.fFriction * Global.FrictionWeatherFactor; - tp.CategoryFlag = MyTrack->iCategoryFlag & 15; - tp.DamageFlag = MyTrack->iDamageFlag; - tp.QualityFlag = MyTrack->iQualityFlag; - tp.Name = &MyTrack->name(); - - // couplers - if( MoverParameters->Couplers[0].CouplingFlag != Coupling::none - && MoverParameters->Couplers[1].CouplingFlag != Coupling::none ) { - MoverParameters->InsideConsist = true; - } - else { - MoverParameters->InsideConsist = false; - } - if( TestFlag( MoverParameters->AIFlag, sound::attachcoupler ) ) { - auto *driver{ ctOwner ? ctOwner : Mechanik }; - if( driver != nullptr ) { - driver->CheckVehicles( DriverOrder::connect ); - } - ClearFlag( MoverParameters->AIFlag, sound::attachcoupler ); - } - - // napiecie sieci trakcyjnej - if (MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) { // dla EZT tylko silnikowy - - tmpTraction.TractionVoltage = std::max( std::abs( MoverParameters->PantRearVolt ), std::abs( MoverParameters->PantFrontVolt ) ); - // jeśli brak zasilania dłużej niż 0.2 sekundy (25km/h pod izolatorem daje 0.15s) - // Ra 2F1H: prowizorka, trzeba przechować napięcie, żeby nie wywalało WS pod izolatorem - if( tmpTraction.TractionVoltage > 0.0) { - NoVoltTime = 0; - } - else { - NoVoltTime += dt1; - if( NoVoltTime <= 0.2 ) { - tmpTraction.TractionVoltage = MoverParameters->PantographVoltage; - } - else { - // jeśli jedzie - if( MoverParameters->Vel > 0.5 ) { - // Ra 2014-07: doraźna blokada logowania zimnych lokomotyw - zrobić to trzeba inaczej - if( MoverParameters->Pantographs[end::front].is_active - || MoverParameters->Pantographs[end::rear].is_active ) { - if( MoverParameters->Mains // Ra 15-01: logować tylko, jeśli WS załączony - && MoverParameters->GetTrainsetHighVoltage() < 0.1f // yB 16-03: i nie jest to asynchron zasilany z daleka - && false == MoverParameters->GensetSelected() ) { // nor a dual-mode vehicle running on its genset - // Ra 15-01: bezwzględne współrzędne pantografu nie są dostępne więc lepiej się tego nie zaloguje - ErrorLog( - "Bad traction: " + MoverParameters->Name - + " lost power for " + to_string( NoVoltTime, 2 ) + " sec. at " - + to_string(vPosition) ); - } - } - } - } - } - } - else { - tmpTraction.TractionVoltage = 0.95 * MoverParameters->EnginePowerSource.MaxVoltage; - } - tmpTraction.TractionFreq = 0; - tmpTraction.TractionMaxCurrent = 7500; // Ra: chyba za dużo? powinno wywalać przy 1500 - tmpTraction.TractionResistivity = 0.3; - - MoverParameters->PantographVoltage = tmpTraction.TractionVoltage; - // McZapkie: predkosc w torze przekazac do TrackParam - // McZapkie: Vel ma wymiar [km/h] (absolutny), V ma wymiar [m/s], taka przyjalem notacje - tp.Velmax = MyTrack->VelocityGet(); - - if (Mechanik) - { // Ra 2F3F: do Driver.cpp to przenieść? - if( Mechanik->primary() ) { - MoverParameters->EqvtPipePress = GetEPP(); // srednie cisnienie w PG - } - if (Mechanik->primary() && - (MoverParameters->EngineType == TEngineType::DieselEngine || - MoverParameters->EngineType == TEngineType::DieselElectric) - && MoverParameters->EIMCtrlType > 0) { - MoverParameters->CheckEIMIC(dt1); - if (MoverParameters->SpeedCtrl) - MoverParameters->CheckSpeedCtrl(dt1); - MoverParameters->eimic_real = std::min(MoverParameters->eimic,MoverParameters->eimicSpeedCtrl); - MoverParameters->SendCtrlToNext(VehicleCommand::integratedController, MoverParameters->eimic_real, MoverParameters->CabActive); - } - if( Mechanik->primary() - && MoverParameters->EngineType == TEngineType::ElectricInductionMotor ) { - // jesli glowny i z asynchronami, to niech steruje hamulcem i napedem lacznie dla calego pociagu/ezt - auto const kier = DirectionGet() * MoverParameters->CabOccupied > 0; - auto FED { 0.0 }; - auto np { 0 }; - auto masa { 0.0 }; - auto FrED { 0.0 }; - auto masamax { 0.0 }; - auto FmaxPN { 0.0 }; - auto FfulED { 0.0 }; - auto FmaxED { 0.0 }; - auto Frj { 0.0 }; - auto osie { 0 }; - // 0a. ustal aktualna nastawe zadania sily napedowej i hamowania - if( MoverParameters->Power < 1 - && ctOwner != nullptr ) { - MoverParameters->MainCtrlPos = ctOwner->Controlling()->MainCtrlPos*MoverParameters->MainCtrlPosNo / std::max(1, ctOwner->Controlling()->MainCtrlPosNo); - MoverParameters->SpeedCtrlValue = ctOwner->Controlling()->SpeedCtrlValue; - MoverParameters->SpeedCtrlUnit.IsActive = ctOwner->Controlling()->SpeedCtrlUnit.IsActive; - } - MoverParameters->CheckEIMIC(dt1); - MoverParameters->CheckSpeedCtrl(dt1); - - auto eimic = std::min(MoverParameters->eimic, MoverParameters->eimicSpeedCtrl); - MoverParameters->eimic_real = eimic; - // Elf: full braking at once in the lowest position, and in the emergency brake position below it - if (MoverParameters->EIMCtrlType == 2 && MoverParameters->MainCtrlPos <= MoverParameters->EIMCtrlEmergencyPositions()) - eimic = -1.0; - MoverParameters->SendCtrlToNext(VehicleCommand::integratedController, std::max(0., eimic), MoverParameters->CabActive); - auto LBR = std::max(-eimic, 0.); - auto eim_lb = Mechanik->AIControllFlag || !MoverParameters->LocHandleTimeTraxx ? 0 : MoverParameters->eim_localbrake; - - // 1. ustal wymagana sile hamowania calego pociagu - // - opoznienie moze byc ustalane na podstawie charakterystyki - // - opoznienie moze byc ustalane na podstawie mas i cisnien granicznych - // - - // 2. ustal mozliwa do realizacji sile hamowania ED - // - w szczegolnosci powinien brac pod uwage rozne sily hamowania - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, Coupling::control); p; - kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) - { - ++np; - masamax += - p->MoverParameters->MBPM - + ( p->MoverParameters->MBPM > 1.0 ? - 0.0 : - p->MoverParameters->Mass ) - + p->MoverParameters->Mred; - auto const Nmax = ((p->MoverParameters->P2FTrans * p->MoverParameters->MaxBrakePress[0] - - p->MoverParameters->BrakeCylSpring) * - p->MoverParameters->BrakeCylMult[0] - - p->MoverParameters->BrakeSlckAdj) * - p->MoverParameters->BrakeCylNo * p->MoverParameters->BrakeRigEff; - FmaxPN += Nmax * p->MoverParameters->Hamulec->GetFC( - Nmax / (p->MoverParameters->NAxles * p->MoverParameters->NBpA), - p->MoverParameters->MED_Vref) * - 1000; // sila hamowania pn - FmaxED += p->MoverParameters->Mains && p->MoverParameters->DirActive != 0 && p->MoverParameters->InvertersRatio == 1.0 && - p->MoverParameters->eimc[eimc_p_Fh] * p->MoverParameters->NPoweredAxles > 0 ? - p->MoverParameters->eimc[eimc_p_Fh] * 1000 : - 0; // chwilowy max ED -> do rozdzialu sil - FED -= std::min(p->MoverParameters->eimv[eimv_Fmax], 0.0) * - 1000; // chwilowy max ED -> do rozdzialu sil - FfulED = std::min(p->MoverParameters->eimv[eimv_Fful], 0.0) * - 1000; // chwilowy max ED -> do rozdzialu sil - FrED -= std::min(p->MoverParameters->eimv[eimv_Fmax], 0.0) * - 1000; // chwilowo realizowane ED -> do pneumatyki - Frj += std::max(p->MoverParameters->eimv[eimv_Fmax], 0.0) * - 1000;// chwilowo realizowany napęd -> do utrzymującego - masa += p->MoverParameters->TotalMass; - osie += p->MoverParameters->NAxles; - } - double RapidMult = 1.0; - if ((MoverParameters->BrakeDelays & bdelay_P + bdelay_R) == bdelay_P + bdelay_R - && MoverParameters->BrakeDelayFlag & bdelay_P) - RapidMult = MoverParameters->RapidMult; - - auto const amax = RapidMult * std::min(FmaxPN / masamax, MoverParameters->MED_amax); - - Mechanik->fMedAmax = amax; - auto doorisopen { - false == MoverParameters->Doors.instances[side::left].is_closed - || false == MoverParameters->Doors.instances[side::right].is_closed - || ( MoverParameters->Doors.permit_needed - && ( MoverParameters->Doors.instances[ side::left ].open_permit - || MoverParameters->Doors.instances[ side::right ].open_permit ) ) }; - doorisopen &= !(MoverParameters->ReleaseParkingBySpringBrakeWhenDoorIsOpen && MoverParameters->SpringBrake.IsActive); - - if (MoverParameters->Vel < 0.5 && (eimic < 0 || doorisopen || MoverParameters->Hamulec->GetEDBCP())) - { - MoverParameters->ShuntMode = true; - } - if (MoverParameters->ShuntMode) - { - MoverParameters->ShuntModeAllow = false == doorisopen && - LBR < 0.01; - } - if( MoverParameters->Vel > 1 && false == doorisopen ) - { - MoverParameters->ShuntMode = false; - MoverParameters->ShuntModeAllow = MoverParameters->BrakePress > 0.2 && - LBR < 0.01; - } - auto Fzad = amax * LBR * masa; - if ((MoverParameters->BrakeCtrlPos == MoverParameters->Handle->GetPos(bh_EB) - && MoverParameters->eimc[eimc_p_abed] < 0.001) || - MoverParameters->EmergencyValveFlow > 0) - Fzad = amax * masa; //pętla bezpieczeństwa - pełne służbowe - if (MoverParameters->ScndS && - MoverParameters->Vel > MoverParameters->eimc[eimc_p_Vh1] && FmaxED > 0) - { - Fzad = std::min(LBR * FmaxED, FfulED); - } - // the holding brake lets go once power has been demanded for its delay (SBDReleaseDelay, none by default) - auto const holdingbrakereleased { MoverParameters->UpdateStopBrakeRelease( eimic, dt1 ) }; - if (MoverParameters->ShuntMode && false == holdingbrakereleased || doorisopen /*|| - (MoverParameters->V * MoverParameters->DirAbsolute < -0.2)*/) - { - auto const sbd { ( MoverParameters->SpringBrake.IsActive && MoverParameters->ReleaseParkingBySpringBrake ? 0.0 : MoverParameters->StopBrakeDecc ) }; - Fzad = std::max( Fzad, sbd * masa ); - } - if (Fzad > 1 && !MEDLogFile.is_open() && MoverParameters->Vel > 1) - { - MEDLogFile.open( - "MEDLOGS/" + MoverParameters->Name + "_" + std::to_string( ++MEDLogCount ) + ".csv", - std::ios::in | std::ios::out | std::ios::trunc ); - MEDLogFile << "t\tVel\tMasa\tOsie\tFmaxPN\tFmaxED\tFfulED\tFrED\tFzad\tFzadED\tFzadPN"; - for(int k=1;k<=np;k++) - { - MEDLogFile << "\tBP" << k; - } - MEDLogFile << "\n"; - MEDLogFile.flush(); - MEDLogInactiveTime = 0; - MEDLogTime = 0; - } - auto FzadED { 0.0 }; - if( LBR > MoverParameters->MED_MinBrakeReqED - && ( MoverParameters->BrakeHandle == TBrakeHandle::MHZ_EN57 ? - (MoverParameters->BrakeOpModeFlag & bom_MED) != 0 : - MoverParameters->EpFuse ) ) { - FzadED = std::min( Fzad, FmaxED ); - } - /*/ELF - wdrazanie ED po powrocie na utrzymanie hamowania - do usuniecia - if (MoverParameters->EIMCtrlType == 2 && MoverParameters->MainCtrlPos < 2 && MoverParameters->eimic > -0.999) - { - FzadED = std::min(FzadED, MED_oldFED); - } //*/ - //opoznienie wdrazania ED - if (FzadED > MED_oldFED) - { - if (MoverParameters->MED_ED_DelayTimer <= 0) { - MoverParameters->MED_ED_DelayTimer += dt1; - if (MoverParameters->MED_ED_DelayTimer > 0) { - - } - else { - FzadED = std::min(FzadED, MED_oldFED); - } - } - else - { - FzadED = std::min(FzadED, MED_oldFED); - MoverParameters->MED_ED_DelayTimer = FrED > 0 ? -MoverParameters->MED_ED_Delay2 : -MoverParameters->MED_ED_Delay1; - } - } - if (MoverParameters->BrakeCtrlPos == MoverParameters->Handle->GetPos(bh_EB) - && MoverParameters->eimc[eimc_p_abed] < 0.001) - FzadED = 0; //pętla bezpieczeństwa - bez ED - auto const FzadPN = Fzad - FrED * MoverParameters->MED_FrED_factor; - std::vector PrzekrF( np ); - float nPrzekrF = 0; - bool test = true; - std::vector FzED( np ); - std::vector FzEP( np ); - std::vector FmaxEP( np ); - // 3. ustaw pojazdom sile hamowania ED - // - proporcjonalnie do mozliwosci - - // 4. ustal potrzebne dohamowanie pneumatyczne - // - od sily zadanej trzeba odjac realizowana przez ED - // 5. w razie potrzeby wlacz hamulec utrzymujacy - // - gdy zahamowany ma ponizej 2 km/h - // 6. ustaw pojazdom sile hamowania ep - // - proporcjonalnie do masy, do liczby osi, rowne cisnienia - jak - // bedzie, tak bedzie dobrze - float Fpoj = 0; // MoverParameters->CabOccupied < 0 - ////ALGORYTM 2 - KAZDEMU PO ROWNO, ale nie wiecej niz eped * masa - // 1. najpierw daj kazdemu tyle samo - int i = 0; - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, Coupling::control); p; - p = kier == true ? p->Next(Coupling::control) : p->Prev(Coupling::control) ) - { - auto const Nmax = ((p->MoverParameters->P2FTrans * p->MoverParameters->MaxBrakePress[0] - - p->MoverParameters->BrakeCylSpring) * - p->MoverParameters->BrakeCylMult[0] - - p->MoverParameters->BrakeSlckAdj) * - p->MoverParameters->BrakeCylNo * p->MoverParameters->BrakeRigEff; - FmaxEP[i] = Nmax * - p->MoverParameters->Hamulec->GetFC( - Nmax / (p->MoverParameters->NAxles * p->MoverParameters->NBpA), - p->MoverParameters->MED_Vref) * - 1000; // sila hamowania pn - - PrzekrF[i] = false; - FzED[i] = FmaxED > 0 ? FzadED / FmaxED : 0; - p->MoverParameters->AnPos = - MoverParameters->ScndS ? LBR : FzED[i]; - FzEP[ i ] = static_cast( FzadPN * p->MoverParameters->NAxles ) / static_cast( osie ); - ++i; - p->MoverParameters->ShuntMode = MoverParameters->ShuntMode; - p->MoverParameters->ShuntModeAllow = MoverParameters->ShuntModeAllow; - } - while (test) - { - test = false; - i = 0; - float przek = 0; - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, Coupling::control); p; - p = kier == true ? p->Next(Coupling::control) : p->Prev(Coupling::control) ) - { - if (FzEP[i] > 0.01 && - FzEP[i] > p->MoverParameters->TotalMass * p->MoverParameters->eimc[eimc_p_eped] + std::min(p->MoverParameters->eimv[eimv_Fmax], 0.) * 1000 && - !PrzekrF[i]) - { - float przek1 = -std::min(p->MoverParameters->eimv[eimv_Fmax], 0.) * 1000 + - FzEP[i] - - p->MoverParameters->TotalMass * - p->MoverParameters->eimc[eimc_p_eped] * 0.999; - PrzekrF[i] = true; - test = true; - nPrzekrF++; - przek1 = std::min(przek1, FzEP[i]); - FzEP[i] -= przek1; - if (FzEP[i] < 0) - FzEP[i] = 0; - przek += przek1; - } - ++i; - } - i = 0; - przek = przek / (np - nPrzekrF); - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, Coupling::control); p; - true == kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) - { - if (!PrzekrF[i]) - { - FzEP[i] += przek; - } - ++i; - } - } - i = 0; - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, Coupling::control); p; - true == kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) - { - float Nmax = ((p->MoverParameters->P2FTrans * p->MoverParameters->MaxBrakePress[0] - - p->MoverParameters->BrakeCylSpring) * - p->MoverParameters->BrakeCylMult[0] - - p->MoverParameters->BrakeSlckAdj) * - p->MoverParameters->BrakeCylNo * p->MoverParameters->BrakeRigEff; - if (FrED > 0.1) - p->MoverParameters->MED_EPVC_CurrentTime = 0; - else - p->MoverParameters->MED_EPVC_CurrentTime += dt1; - bool EPVC = p->MoverParameters->MED_EPVC && (p->MoverParameters->MED_EPVC_Time < 0 || p->MoverParameters->MED_EPVC_CurrentTime < p->MoverParameters->MED_EPVC_Time); - float VelC = EPVC ? safe_clamp(p->MoverParameters->Vel, p->MoverParameters->MED_Vmin, p->MoverParameters->MED_Vmax) : p->MoverParameters->MED_Vref;//korekcja EP po prędkości - float FmaxPoj = Nmax * - p->MoverParameters->Hamulec->GetFC( - Nmax / (p->MoverParameters->NAxles * p->MoverParameters->NBpA), VelC) * - 1000; // sila hamowania pn - p->MoverParameters->LocalBrakePosAEIM = FzEP[i] / FmaxPoj; - if (p->MoverParameters->LocalBrakePosAEIM>0.009) - if (p->MoverParameters->P2FTrans * p->MoverParameters->BrakeCylMult[0] * - p->MoverParameters->MaxBrakePress[0] != 0) - { - float x = (p->MoverParameters->BrakeSlckAdj / p->MoverParameters->BrakeCylMult[0] + - p->MoverParameters->BrakeCylSpring) / (p->MoverParameters->P2FTrans * - p->MoverParameters->MaxBrakePress[0]); - p->MoverParameters->LocalBrakePosAEIM = x + (1 - x) * p->MoverParameters->LocalBrakePosAEIM; - } - else - p->MoverParameters->LocalBrakePosAEIM = p->MoverParameters->LocalBrakePosAEIM; - else - p->MoverParameters->LocalBrakePosAEIM = 0; - if (p->MoverParameters->LocHandleTimeTraxx) - { - p->MoverParameters->eim_localbrake = eim_lb; - p->MoverParameters->LocalBrakePosAEIM = std::max(p->MoverParameters->LocalBrakePosAEIM, eim_lb); - } - ++i; - } - - MED[0][0] = masa*0.001; - MED[0][1] = amax; - MED[0][2] = Fzad*0.001; - MED[0][3] = FmaxPN*0.001; - MED[0][4] = FmaxED*0.001; - MED[0][5] = FrED*0.001; - MED[0][6] = FzadPN*0.001; - MED[0][7] = nPrzekrF; - - if (MEDLogFile.is_open()) - { - MEDLogFile << MEDLogTime << "\t" << MoverParameters->Vel << "\t" << masa*0.001 << "\t" << osie << "\t" << FmaxPN*0.001 << "\t" << FmaxED*0.001 << "\t" - << FfulED*0.001 << "\t" << FrED*0.001 << "\t" << Fzad*0.001 << "\t" << FzadED*0.001 << "\t" << FzadPN*0.001; - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, Coupling::control); p; - true == kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) - { - MEDLogFile << "\t" << p->MoverParameters->BrakePress; - } - MEDLogFile << "\n"; - if (floor(MEDLogTime + dt1) > floor(MEDLogTime)) - { - MEDLogFile.flush(); - } - MEDLogTime += dt1; - - if (MoverParameters->Vel < 0.1 || MoverParameters->MainCtrlPowerPos() > 0) - { - MEDLogInactiveTime += dt1; - } - else - { - MEDLogInactiveTime = 0; - } - if (MEDLogInactiveTime > 5) - { - MEDLogFile.flush(); - MEDLogFile.close(); - } - - } - - MED_oldFED = FzadED; - } - - Timer::subsystem.vehicles_ai.start(); - Mechanik->Update(dt1); // przebłyski świadomości AI - Timer::subsystem.vehicles_ai.stop(); - } - - // fragment "z EXE Kursa" - if( MoverParameters->Mains ) { // nie wchodzić w funkcję bez potrzeby - if( false == (MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable) -/* - // NOTE: disabled on account of multi-unit setups, where the unmanned unit wouldn't be affected - && ( Controller == Humandriver ) -*/ - && MoverParameters->EngineType != TEngineType::DieselEngine - && MoverParameters->EngineType != TEngineType::WheelsDriven ) { // jeśli bateria wyłączona, a nie diesel ani drezyna reczna - if( MoverParameters->MainSwitch( false, MoverParameters->TrainType == train_type::emu ? range_t::unit : range_t::local ) ) { - // wyłączyć zasilanie - // NOTE: we turn off entire EMU, but only the affected unit for other multi-unit consists - MoverParameters->EventFlag = true; - // drop pantographs - // NOTE: this isn't universal behaviour - // TODO: have this dependant on .fiz-driven flag - // NOTE: moved to pantspeed calculation part a little later in the function. all remarks and todo still apply -/* - MoverParameters->PantFront( false, ( MoverParameters->TrainType == train_type::emu ? range::unit : range::local ) ); - MoverParameters->PantRear( false, ( MoverParameters->TrainType == train_type::emu ? range::unit : range::local ) ); -*/ - } - } - } - - // przekazanie pozycji do fizyki - // NOTE: coordinate system swap - // TODO: replace with regular glm vectors - TLocation const l { - -vPosition.x, - vPosition.z, - vPosition.y }; - TRotation const r { - 0.0, - 0.0, - modelRot.z }; - // McZapkie-260202 - dMoveLen przyda sie przy stukocie kol - dDOMoveLen = GetdMoveLen() + MoverParameters->ComputeMovement(dt, dt1, ts, tp, tmpTraction, l, r); - if( Mechanik ) { - // dodanie aktualnego przemieszczenia - Mechanik->MoveDistanceAdd( dDOMoveLen ); - } - if( simulation::Train != nullptr - && simulation::Train->Dynamic() == this ) { - // update distance meter in user-controlled cab - // TBD: place the meter on mover logic level? - simulation::Train->add_distance( dDOMoveLen ); - } - // physics.derailment new: derailed, the vehicle leaves the track and goes on the ground - if( MoverParameters->leaves_track() ) { - begin_off_track(); - } - m_offtracktime = dt1; - glm::dvec3 old_pos = vPosition; - Move(dDOMoveLen); - update_off_track( dt1 ); - - m_future_movement = (vPosition - old_pos) / dt1 * Timer::GetDeltaRenderTime(); - - if (!bEnabled) // usuwane pojazdy nie mają toru - { // pojazd do usunięcia - bDynamicRemove = true; // sprawdzić - return false; - } - ResetdMoveLen(); - - // McZapkie-260202 - // tupot mew, tfu, stukot kol: - if( MyTrack->fSoundDistance != -1 ) { - - if( MyTrack->fSoundDistance != dRailLength ) { - if( dRailLength > 0.0 ) { - for( auto &axle : m_axlesounds ) { - axle.distance = axle.offset; - axle.atjoints = false; - } - } - dRailLength = MyTrack->fSoundDistance; - } - if( dRailLength > 0.0 ) { - if( MoverParameters->Vel > 0 ) { - // TODO: track quality and/or environment factors as separate subroutine - auto volume = - std::lerp( - 0.8, 1.2, - std::clamp( - MyTrack->iQualityFlag / 10.0, - 0.0, 1.5 ) ); - switch( MyTrack->eEnvironment ) { - case e_tunnel: { - volume *= 1.3; - break; - } - case e_bridge: { - volume *= 1.5; - break; - } - default: { - break; - } - } - if( dRailLength > 0.0 ) { - auto axleindex { 0 }; - auto const directioninconsist { ( - ctOwner == nullptr ? - 1 : - ctOwner->Vehicle()->DirectionGet() == DirectionGet() ? 1 : -1 ) }; - for( auto &axle : m_axlesounds ) { - if( axle_passed_joint( axle, dDOMoveLen, directioninconsist ) - && MoverParameters->Vel > 0.1 ) { - // NOTE: for combined clatter sound we supply 1/100th of actual value, as the sound module converts does the opposite, converting received (typically) 0-1 values to 0-100 range - auto const frequency = true == axle.clatter.is_combined() ? MoverParameters->Vel * 0.01 : 1.0; - axle.clatter - .pitch( frequency ) - .gain( volume ) - .play(); - // crude bump simulation, drop down on even axles, move back up on - // the odd ones - // MoverParameters->AccVert += (MoverParameters->Vel*0.1f) * - // the arguments keep the order they had up to 26.05.1, 0 in place of the value and the figure in place of the - // upper limit, so they work out as the old clamp worked them out up to 26.05.1: the headroom is - // Vmax - (Vel + 0.32 Vmax) whatever its sign, and the bump is capped from above only - double const headroom = safe_clamp( 0.0, MoverParameters->Vmax, MoverParameters->Vmax - ( MoverParameters->Vel + MoverParameters->Vmax * 0.32f ) ); - double const jolt = headroom * .05f * ( MyTrack->iDamageFlag * 0.25f ); - if (MyTrack->eType == tt_Normal) - { - MoverParameters->AccVert += safe_clamp( 0.0, 4.0, jolt ); - } - else if (MyTrack->eType == tt_Switch) - { - double const accHorizontal = safe_clamp( 0.0, 1.0, jolt ) * ((axleindex % 2) != 0 ? 1 : -1); - MoverParameters->AccS += accHorizontal; - MoverParameters->AccN += accHorizontal; - MoverParameters->AccVert += safe_clamp( 0.0, 2.0, jolt ); - } - } - ++axleindex; - } - } - } - } - } - // McZapkie-260202 end - - // fragment z EXE Kursa - /* if (MoverParameters->TrainType==train_type::et42) - { - if ((MoverParameters->DynamicBrakeType=dbrake_switch) && - ((MoverParameters->BrakePress > - 0.2) || ( MoverParameters->PipePress < 0.36 ))) - { - MoverParameters->StLinFlag=true; - } - else - if ((MoverParameters->DynamicBrakeType=dbrake_switch) && - (MoverParameters->BrakePress < - 0.1)) - { - MoverParameters->StLinFlag=false; - - } - } */ - - if (MoverParameters->Vel != 0) - { // McZapkie-050402: krecenie kolami: - glm::dvec3 old_wheels = glm::dvec3(dWheelAngle[0], dWheelAngle[1], dWheelAngle[2]); - - dWheelAngle[0] += 114.59155902616464175359630962821 * MoverParameters->V * dt1 / - MoverParameters->WheelDiameterL; // przednie toczne - dWheelAngle[1] += MoverParameters->nrot * dt1 * 360.0; // napędne - dWheelAngle[2] += 114.59155902616464175359630962821 * MoverParameters->V * dt1 / - MoverParameters->WheelDiameterT; // tylne toczne - - - m_future_wheels_angle = (glm::dvec3(dWheelAngle[0], dWheelAngle[1], dWheelAngle[2]) - old_wheels) / dt1 * Timer::GetDeltaRenderTime(); - - dWheelAngle[0] = clamp_circular( dWheelAngle[0] ); - dWheelAngle[1] = clamp_circular( dWheelAngle[1] ); - dWheelAngle[2] = clamp_circular( dWheelAngle[2] ); - } - if (pants) // pantograf może być w wagonie kuchennym albo pojeździe rewizyjnym (np. SR61) - { // przeliczanie kątów dla pantografów - double k; // tymczasowy kąt - double PantDiff; - TAnimPant *p; // wskaźnik do obiektu danych pantografu - // prąd pobierany przez pojazd z sieci: trakcyjny (on the genset of a dual-mode vehicle none) i TotalCurrent - // TotalCurrent to bedzie prad nietrakcyjny (niezwiazany z napedem) - double fCurrent = MoverParameters->CatenaryCurrent(); - // fCurrent+=fabs(MoverParameters->Voltage)*1e-6; //prąd płynący przez woltomierz, rozładowuje kondensator orgromowy 4µF -/* - double fPantCurrent = fCurrent; // normalnie cały prąd przez jeden pantograf - if (iAnimType[ANIM_PANTS] > 1) { // a jeśli są dwa pantografy //Ra 1014-11: proteza, trzeba zrobić sensowniej - if (pants[0].fParamPants->hvPowerWire && pants[1].fParamPants->hvPowerWire) { // i oba podłączone do drutów - fPantCurrent = fCurrent * 0.5; // to dzielimy prąd równo na oba (trochę bez sensu, ale lepiej tak niż podwoić prąd) - } - } -*/ - // test whether more than one pantograph touches the wire - // NOTE: we're duplicating lot of code from below - // TODO: clean this up - auto activepantographs { 0 }; - for( int idx = 0; idx < iAnimType[ ANIM_PANTS ]; ++idx ) { - auto const *pantograph { pants[ idx ].fParamPants }; - if( Global.bLiveTraction == false ) { - if( pantograph->PantWys >= 1.2 ) { - ++activepantographs; - } - } - else { - if( pantograph->hvPowerWire != nullptr - && true == MoverParameters->Pantographs[end::front].is_active - && pantograph->PantTraction - pantograph->PantWys < 0.01 ) { // tolerancja niedolegania - ++activepantographs; - } - } - } - auto const fPantCurrent { fCurrent / std::max( 1, activepantographs ) }; - - for (int i = 0; i < iAnimType[ANIM_PANTS]; ++i) - { // pętla po wszystkich pantografach - p = pants[i].fParamPants; - if (p->PantWys < 0) - { // patograf został połamany, liczony nie będzie - if (p->fAngleL > p->fAngleL0) - p->fAngleL -= 0.2 * dt1; // nieco szybciej niż jak dla opuszczania - if (p->fAngleL < p->fAngleL0) - p->fAngleL = p->fAngleL0; // kąt graniczny - if (p->fAngleU < M_PI) - p->fAngleU += 0.5 * dt1; // górne się musi ruszać szybciej. - if (p->fAngleU > M_PI) - p->fAngleU = M_PI; - if (i & 1) // zgłoszono, że po połamaniu potrafi zostać zasilanie - MoverParameters->PantRearVolt = 0.0; - else - MoverParameters->PantFrontVolt = 0.0; - continue; // reszta wtedy nie jest wykonywana - } - PantDiff = p->PantTraction - p->PantWys; // docelowy-aktualny - switch (i) // numer pantografu - { // trzeba usunąć to rozróżnienie - case 0: - if (Global.bLiveTraction == false - && p->hvPowerWire == nullptr ) { - // jeśli nie ma drutu, może pooszukiwać - MoverParameters->PantFrontVolt = - p->PantWys >= 1.2 ? - 0.95 * MoverParameters->EnginePowerSource.MaxVoltage : - 0.0; - } - else if( true == MoverParameters->Pantographs[end::front].is_active - && PantDiff < 0.01 ) // tolerancja niedolegania - { - if (p->hvPowerWire) { - auto const lastvoltage { MoverParameters->PantFrontVolt }; - // TODO: wyliczyć trzeba prąd przypadający na pantograf i wstawić do GetVoltage() - if( lastvoltage == 0.0 ) { - // HACK: retrieve the wire voltage for calculations down the road without blowing up the supply - MoverParameters->PantFrontVolt = p->hvPowerWire->VoltageGet( MoverParameters->PantographVoltage, 0.0 ); - } - else { - MoverParameters->PantFrontVolt = p->hvPowerWire->VoltageGet( MoverParameters->PantographVoltage, fPantCurrent ); - if( MoverParameters->PantFrontVolt > 0.0 ) { - fCurrent -= fPantCurrent; // taki prąd płynie przez powyższy pantograf (unless it doesn't) - } - } - // TODO: refactor reaction to voltage change to mover as sound event for specific pantograph - if( lastvoltage == 0.0 - && MoverParameters->PantFrontVolt > 0.0 ) { - for( auto &pantograph : m_pantographsounds ) { - if( pantograph.sPantUp.offset().z > 0 ) { - // limit to pantographs located in the front half of the vehicle - pantograph.sPantUp.play( sound_flags::exclusive ); - } - } - } - } - else - MoverParameters->PantFrontVolt = 0.0; - } - else - MoverParameters->PantFrontVolt = 0.0; - ( fPantCurrent > 0.0 ? MoverParameters->EnergyMeter.first : MoverParameters->EnergyMeter.second ) += MoverParameters->PantRearVolt * fPantCurrent * dt1 / 3600000.0; - break; - case 1: - if( false == Global.bLiveTraction - && nullptr == p->hvPowerWire ) { - // jeśli nie ma drutu, może pooszukiwać - MoverParameters->PantRearVolt = - p->PantWys >= 1.2 ? - 0.95 * MoverParameters->EnginePowerSource.MaxVoltage : - 0.0; - } - else if ( true == MoverParameters->Pantographs[end::rear].is_active - && PantDiff < 0.01 ) - { - if (p->hvPowerWire) { - auto const lastvoltage { MoverParameters->PantRearVolt }; - // TODO: wyliczyć trzeba prąd przypadający na pantograf i wstawić do GetVoltage() - if( lastvoltage == 0.0 ) { - // HACK: retrieve the wire voltage for calculations down the road without blowing up the supply - MoverParameters->PantRearVolt = p->hvPowerWire->VoltageGet( MoverParameters->PantographVoltage, 0.0 ); - } - else { - MoverParameters->PantRearVolt = p->hvPowerWire->VoltageGet( MoverParameters->PantographVoltage, fPantCurrent ); - if( MoverParameters->PantRearVolt > 0.0 ) { - fCurrent -= fPantCurrent; // taki prąd płynie przez powyższy pantograf (unless it doesn't) - } - } - // TODO: refactor reaction to voltage change to mover as sound event for specific pantograph - if( lastvoltage == 0.0 - && MoverParameters->PantRearVolt > 0.0 ) { - for( auto &pantograph : m_pantographsounds ) { - if( pantograph.sPantUp.offset().z < 0 ) { - // limit to pantographs located in the rear half of the vehicle - pantograph.sPantUp.play( sound_flags::exclusive ); - } - } - } - } - else - MoverParameters->PantRearVolt = 0.0; - } - else { -// Global.iPause ^= 2; - MoverParameters->PantRearVolt = 0.0; - } - ( fPantCurrent > 0.0 ? MoverParameters->EnergyMeter.first : MoverParameters->EnergyMeter.second ) += MoverParameters->PantFrontVolt * fPantCurrent * dt1 / 3600000.0; - break; - } // pozostałe na razie nie obsługiwane - if( MoverParameters->PantPress > ( - MoverParameters->TrainType == train_type::emu ? - 2.45 : // Ra 2013-12: Niebugocław mówi, że w EZT podnoszą się przy 2.5 - 3.45 ) ) { - // z EXE Kursa - // Ra: wysokość zależy od ciśnienia !!! - pantspeedfactor = 0.015 * MoverParameters->PantPress * dt1; - } - else { - pantspeedfactor = 0.0; - } - if( false == ( MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable ) ) { - pantspeedfactor = 0.0; - } - pantspeedfactor = std::max( 0.0, pantspeedfactor ); - k = p->fAngleL; - if( pantspeedfactor > 0.0 - && MoverParameters->Pantographs[i].is_active )// jeśli ma być podniesiony - { - if (PantDiff > 0.001) // jeśli nie dolega do drutu - { // jeśli poprzednia wysokość jest mniejsza niż pożądana, zwiększyć kąt dolnego - // ramienia zgodnie z ciśnieniem - if (pantspeedfactor > - 0.55 * PantDiff) // 0.55 to około pochodna kąta po wysokości - k += 0.55 * PantDiff; // ograniczenie "skoku" w danej klatce - else - k += pantspeedfactor; // dolne ramię - // jeśli przekroczono kąt graniczny, zablokować pantograf - // (wymaga interwencji pociągu sieciowego) - } - else if (PantDiff < -0.001) { - // drut się obniżył albo pantograf podniesiony za wysoko - // jeśli wysokość jest zbyt duża, wyznaczyć zmniejszenie kąta - // jeśli zmniejszenie kąta jest zbyt duże, przejść do trybu łamania pantografu - // if (PantFrontDiff<-0.05) //skok w dół o 5cm daje złąmanie pantografu - k += 0.4 * PantDiff; // mniej niż pochodna kąta po wysokości - } // jeśli wysokość jest dobra, nic więcej nie liczyć - } - else - { // jeśli ma być na dole - if (k > p->fAngleL0) // jeśli wyżej niż położenie wyjściowe - k -= 0.15 * dt1; // ruch w dół - if (k < p->fAngleL0) - k = p->fAngleL0; // położenie minimalne - } - if (k != p->fAngleL) - { //żeby nie liczyć w kilku miejscach ani gdy nie potrzeba - if (k + p->fAngleU < M_PI) - { // o ile nie został osiągnięty kąt maksymalny - p->fAngleL = k; // zmieniony kąt - // wyliczyć kąt górnego ramienia z wzoru (a)cosinusowego - //=acos((b*cos()+c)/a) - // p->dPantAngleT=acos((1.22*cos(k)+0.535)/1.755); //górne ramię - p->fAngleU = acos((p->fLenL1 * cos(k) + p->fHoriz) / p->fLenU1); // górne ramię - // wyliczyć aktualną wysokość z wzoru sinusowego - // h=a*sin()+b*sin() - // wysokość całości - p->PantWys = p->fLenL1 * sin(k) + p->fLenU1 * sin(p->fAngleU) + p->fHeight; - } - } - } // koniec pętli po pantografach - // TBD, TODO: generate sound event during mover update instead? - if( MoverParameters->Pantographs[end::front].sound_event != MoverParameters->Pantographs[ end::front ].is_active ) { - if( MoverParameters->Pantographs[ end::front ].is_active ) { - // pantograph moving up - // TBD: add a sound? - } - else { - // pantograph dropping - for( auto &pantograph : m_pantographsounds ) { - if( pantograph.sPantDown.offset().z > 0 ) { - // limit to pantographs located in the front half of the vehicle - pantograph.sPantDown.play( sound_flags::exclusive ); - } - } - } - MoverParameters->Pantographs[ end::front ].sound_event = MoverParameters->Pantographs[ end::front ].is_active; - } - if( MoverParameters->Pantographs[ end::rear ].sound_event != MoverParameters->Pantographs[ end::rear ].is_active ) { - if( MoverParameters->Pantographs[ end::rear ].is_active ) { - // pantograph moving up - // TBD: add a sound? - } - else { - // pantograph dropping - for( auto &pantograph : m_pantographsounds ) { - if( pantograph.sPantDown.offset().z < 0 ) { - // limit to pantographs located in the front half of the vehicle - pantograph.sPantDown.play( sound_flags::exclusive ); - } - } - } - MoverParameters->Pantographs[ end::rear ].sound_event = MoverParameters->Pantographs[ end::rear ].is_active; - } - } - else if (MoverParameters->EnginePowerSource.SourceType == TPowerSource::InternalSource) - if (MoverParameters->EnginePowerSource.PowerType == TPowerType::SteamPower) - // if (smPatykird1[0]) - { // Ra: animacja rozrządu parowozu, na razie nieoptymalizowane - /* //Ra: tymczasowo wyłączone ze względu na porządkowanie animacji - pantografów - double fi,dx,c2,ka,kc; - double sin_fi,cos_fi; - double L1=1.6688888888888889; - double L2=5.6666666666666667; //2550/450 - double Lc=0.4; - double L=5.686422222; //2558.89/450 - double G1,G2,G3,ksi,sin_ksi,gam; - double G1_2,G2_2,G3_2; //kwadraty - //ruch tłoków oraz korbowodów - for (int i=0;i<=1;++i) - {//obie strony w ten sam sposób - fi=DegToRad(dWheelAngle[1]+(i?pant2x:pant1x)); //kąt obrotu koła dla - tłoka 1 - sin_fi=sin(fi); - cos_fi=cos(fi); - dx=panty*cos_fi+sqrt(panth*panth-panty*panty*sin_fi*sin_fi)-panth; - //nieoptymalne - if (smPatykird1[i]) //na razie zabezpieczenie - smPatykird1[i]->SetTranslate(float3(dx,0,0)); - ka=-asin(panty/panth)*sin_fi; - if (smPatykirg1[i]) //na razie zabezpieczenie - smPatykirg1[i]->SetRotateXYZ(vector3(RadToDeg(ka),0,0)); - //smPatykirg1[0]->SetRotate(float3(0,1,0),RadToDeg(fi)); //obracamy - //ruch drążka mimośrodkowego oraz jarzma - //korzystałem z pliku PDF "mm.pdf" (opis czworoboku - korbowo-wahaczowego): - //"MECHANIKA MASZYN. Szkic wykładu i laboratorium komputerowego." - //Prof. dr hab. inż. Jerzy Zajączkowski, 2007, Politechnika Łódzka - //L1 - wysokość (w pionie) osi jarzma ponad osią koła - //L2 - odległość w poziomie osi jarzma od osi koła - //Lc - długość korby mimośrodu na kole - //Lr - promień jarzma =1.0 (pozostałe przeliczone proporcjonalnie) - //L - długość drążka mimośrodowego - //fi - kąt obrotu koła - //ksi - kąt obrotu jarzma (od pionu) - //gam - odchylenie drążka mimośrodowego od poziomu - //G1=(Lr*Lr+L1*L1+L2*L2+Kc*Lc-L*L-2.0*Lc*L2*cos(fi)+2.0*Lc*L1*sin(fi))/(Lr*Lr); - //G2=2.0*(L2-Lc*cos(fi))/Lr; - //G3=2.0*(L1-Lc*sin(fi))/Lr; - fi=DegToRad(dWheelAngle[1]+(i?pant2x:pant1x)-96.77416667); //kąt - obrotu koła dla - tłoka 1 - //1) dla dWheelAngle[1]=0° korba jest w dół, a mimośród w stronę - jarzma, czyli - fi=-7° - //2) dla dWheelAngle[1]=90° korba jest do tyłu, a mimośród w dół, - czyli fi=83° - sin_fi=sin(fi); - cos_fi=cos(fi); - G1=(1.0+L1*L1+L2*L2+Lc*Lc-L*L-2.0*Lc*L2*cos_fi+2.0*Lc*L1*sin_fi); - G1_2=G1*G1; - G2=2.0*(L2-Lc*cos_fi); - G2_2=G2*G2; - G3=2.0*(L1-Lc*sin_fi); - G3_2=G3*G3; - sin_ksi=(G1*G2-G3*_fm_sqrt(G2_2+G3_2-G1_2))/(G2_2+G3_2); //x1 (minus - delta) - ksi=asin(sin_ksi); //kąt jarzma - if (smPatykirg2[i]) - smPatykirg2[i]->SetRotateXYZ(vector3(RadToDeg(ksi),0,0)); //obrócenie - jarzma - //1) ksi=-23°, gam= - //2) ksi=10°, gam= - //gam=acos((L2-sin_ksi-Lc*cos_fi)/L); //kąt od poziomu, liczony - względem poziomu - //gam=asin((L1-cos_ksi-Lc*sin_fi)/L); //kąt od poziomu, liczony - względem pionu - gam=atan2((L1-cos(ksi)+Lc*sin_fi),(L2-sin_ksi+Lc*cos_fi)); //kąt od - poziomu - if (smPatykird2[i]) //na razie zabezpieczenie - smPatykird2[i]->SetRotateXYZ(vector3(RadToDeg(-gam-ksi),0,0)); - //obrócenie drążka - mimośrodowego - } - */ - } - - if (MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector - && MoverParameters->EnginePowerSource.CollectorParameters.FakePower) { - MoverParameters->PantRearVolt = 0.95 * MoverParameters->EnginePowerSource.MaxVoltage; - MoverParameters->PantFrontVolt = 0.95 * MoverParameters->EnginePowerSource.MaxVoltage; - } - - // wipers - if (dWiperPos.size() > 0) // tylko dla wozow ze zdefiniowanymi wycierakami - { - for (int i = 0; i < dWiperPos.size(); i++) // iteracja po kazdej wycieraczce - { - bool wipersActive; - auto const bytesum = MoverParameters->WiperList[MoverParameters->wiperSwitchPos].byteSum; - // rozroznienie kabinowe - if (MoverParameters->CabActive == 1) - { - wipersActive = (bytesum & 1 << i) != 0 && MoverParameters->Battery; - } - else if (MoverParameters->CabActive == -1) - { - // odwroconie indexow wycieraczek - wipersActive = (bytesum & 1 << dWiperPos.size() - 1 - i) != 0 && MoverParameters->Battery; - } - else { - wipersActive = false; - } - - auto const currentWiperParams = MoverParameters->WiperList[workingSwitchPos[i]]; - - wiperOutTimer[i] += dt1; // aktualizujemy zegarek - wiperParkTimer[i] += dt1; // aktualizujemy zegarek - - if (wipersActive || dWiperPos[i] > 0.0) // zeby wrocily do trybu park - { - if (dWiperPos[i] > 0.0 && !wipersActive) // bezwzgledny powrot do zera - { - dWiperPos[i] = std::max(0.0, dWiperPos[i] - 1.f / currentWiperParams.WiperSpeed * dt1); - } - else { - - if (dWiperPos[i] < 1.0 && !wiperDirection[i] && wiperParkTimer[i] > currentWiperParams.interval) - // go out - { - if (!sWiperFromParkPlayed) - { - sWiperFromPark.play(sound_flags::exclusive); - sWiperFromParkPlayed = true; - } - dWiperPos[i] = std::min(1.0, dWiperPos[i] + 1.f / currentWiperParams.WiperSpeed * dt1); - } - if (dWiperPos[i] > 0.0 && wiperDirection[i] && wiperOutTimer[i] > currentWiperParams.outBackDelay) - // return back - { - if (!sWiperToParkPlayed) - { - sWiperToPark.play(sound_flags::exclusive); - sWiperToParkPlayed = true; - } - dWiperPos[i] = std::max(0.0, dWiperPos[i] - 1.f / currentWiperParams.WiperSpeed * dt1); - } - if (dWiperPos[i] >= 1.0) // we reached end - { - sWiperFromPark.stop(); - sWiperFromParkPlayed = false; - wiperParkTimer[i] = 0.0; - wiperDirection[i] = true; // switch direction - } - if (dWiperPos[i] <= 0.0) - { - // when in park position - sWiperToPark.stop(); - sWiperToParkPlayed = false; - wiperOutTimer[i] = 0.0; - wiperDirection[i] = false; - workingSwitchPos[i] = MoverParameters->wiperSwitchPos; // update configuration - } - - } - } - } - } - - - - // mirrors - auto const mirrorleft { dMirrorMoveL }; - auto const mirrorright { dMirrorMoveR }; - if( MoverParameters->Vel > MoverParameters->MirrorVelClose - || MoverParameters->CabActive == 0 && activation::mirrors - || MoverParameters->MirrorForbidden ) { - // automatically fold mirrors when above velocity threshold - if( dMirrorMoveL > 0.0 ) { - dMirrorMoveL = std::max( - 0.0, - dMirrorMoveL - 1.0 * dt1 ); - } - if( dMirrorMoveR > 0.0 ) { - dMirrorMoveR = std::max( - 0.0, - dMirrorMoveR - 1.0 * dt1 ); - } - } - else { - // unfold mirror on the side with open doors, if not moving too fast - if( dMirrorMoveL < 1.0 - && true == MoverParameters->Doors.instances[side::left].open_permit ) { - dMirrorMoveL = std::min( - 1.0, - dMirrorMoveL + 1.0 * dt1 ); - } - if( dMirrorMoveR < 1.0 - && true == MoverParameters->Doors.instances[side::right].open_permit ) { - dMirrorMoveR = std::min( - 1.0, - dMirrorMoveR + 1.0 * dt1 ); - } - } - play_mirror_sounds( side::left, m_mirrormotion[ side::left ].update( dMirrorMoveL - mirrorleft ) ); - play_mirror_sounds( side::right, m_mirrormotion[ side::right ].update( dMirrorMoveR - mirrorright ) ); - - // compartment lights - // if the vehicle has a controller, we base the light state on state of the controller otherwise we check the vehicle itself - if( ctOwner != nullptr ? SectionLightsActive != MoverParameters->CompartmentLights.is_active : - Mechanik != nullptr ? SectionLightsActive != MoverParameters->CompartmentLights.is_active : - SectionLightsActive ) { // without controller switch the lights off - toggle_lights(); - } - - if (MoverParameters->InactiveCabPantsCheck) - { - pants_up(); - MoverParameters->InactiveCabPantsCheck = false; - } - - if( MoverParameters->LoadStatus ) { - LoadUpdate(); // zmiana modelu ładunku - } - update_exchange( dt ); - - return true; // Ra: chyba tak? -} - -void TDynamicObject::pants_up() -{ - TDynamicObject *d = this; - bool isAnyPantUp = false; - while (d) { - for (auto &item : d->MoverParameters->Pantographs) - { - isAnyPantUp |= item.is_active; - } - d = d->Next(Coupling::control); // pozostałe też - } - d = Prev(Coupling::control); - while (d) { - for (auto &item : d->MoverParameters->Pantographs) - { - isAnyPantUp |= item.is_active; - } - d = d->Prev(Coupling::control); // w drugą stronę też - } - if (isAnyPantUp) - { - d = this; - while (d) { - d->MoverParameters->OperatePantographValve(end::front, operation_t::enable, range_t::local); - d->MoverParameters->OperatePantographValve(end::rear, operation_t::enable, range_t::local); - d = d->Next(Coupling::control); // pozostałe też - } - d = Prev(Coupling::control); - while (d) { - d->MoverParameters->OperatePantographValve(end::front, operation_t::enable, range_t::local); - d->MoverParameters->OperatePantographValve(end::rear, operation_t::enable, range_t::local); - d = d->Prev(Coupling::control); // w drugą stronę też - } - } -} - -glm::dvec3 TDynamicObject::get_future_movement() const -{ - return m_future_movement; -} - -void TDynamicObject::move_set(double distance) -{ - TDynamicObject *d = this; - while( d ) { - d->Move( distance * d->DirectionGet() ); - d = d->Next(); // pozostałe też - } - d = Prev(); - while( d ) { - d->Move( distance * d->DirectionGet() ); - d = d->Prev(); // w drugą stronę też - } -} - -bool TDynamicObject::FastUpdate(double dt) -{ - if (dt == 0.0) - return true; // Ra: pauza - double dDOMoveLen; - if (!MoverParameters->PhysicActivation) - return true; // McZapkie: wylaczanie fizyki gdy nie potrzeba - - if (!bEnabled) - return false; - - // NOTE: coordinate system swap - // TODO: replace with regular glm vectors - TLocation const l { - -vPosition.x, - vPosition.z, - vPosition.y }; - TRotation const r { - 0.0, - 0.0, - modelRot.z }; - // McZapkie: parametry powinny byc pobierane z toru - // ts.R=MyTrack->fRadius; - // ts.Len= std::max(MoverParameters->BDist,MoverParameters->ADist); - // ts.dHtrack=Axle1.pPosition.y-Axle0.pPosition.y; - // ts.dHrail=((Axle1.GetRoll())+(Axle0.GetRoll()))*0.5f; - // tp.Width=MyTrack->fTrackWidth; - // McZapkie-250202 - // tp.friction= MyTrack->fFriction; - // tp.CategoryFlag= MyTrack->iCategoryFlag&15; - // tp.DamageFlag=MyTrack->iDamageFlag; - // tp.QualityFlag=MyTrack->iQualityFlag; - dDOMoveLen = MoverParameters->FastComputeMovement(dt, ts, tp, l, r); // ,ts,tp,tmpTraction); - // Move(dDOMoveLen); - // ResetdMoveLen(); - FastMove(dDOMoveLen); - - if( MoverParameters->LoadStatus ) { - LoadUpdate(); // zmiana modelu ładunku - } - update_exchange( dt ); - - return true; // Ra: chyba tak? -} - -// McZapkie-040402: liczenie pozycji uwzgledniajac wysokosc szyn itp. -// vector3 TDynamicObject::GetPosition() -//{//Ra: pozycja pojazdu jest liczona zaraz po przesunięciu -// return vPosition; -//}; - -void TDynamicObject::TurnOff() -{ // wyłączenie rysowania submodeli zmiennych dla - // egemplarza pojazdu - btnOn = false; - btCoupler1.TurnOff(); - btCoupler2.TurnOff(); - btCPneumatic1.TurnOff(); - btCPneumatic1r.TurnOff(); - btCPneumatic2.TurnOff(); - btCPneumatic2r.TurnOff(); - btPneumatic1.TurnOff(); - btPneumatic1r.TurnOff(); - btPneumatic2.TurnOff(); - btPneumatic2r.TurnOff(); - btCCtrl1.Turn( false ); - btCCtrl2.Turn( false ); - btCPass1.Turn( false ); - btCPass2.Turn( false ); - m_endsignal12.Turn( false ); - m_endsignal13.Turn( false ); - m_endsignal22.Turn( false ); - m_endsignal23.Turn( false ); - m_endsignals1.Turn( false ); - m_endsignals2.Turn( false ); - m_endtab1.Turn( false ); - m_endtab2.Turn( false ); - m_headlamp11.TurnOff(); - m_headlamp12.TurnOff(); - m_headlamp13.TurnOff(); - m_headlamp21.TurnOff(); - m_headlamp22.TurnOff(); - m_headlamp23.TurnOff(); - m_highbeam12.TurnOff(); - m_highbeam13.TurnOff(); - m_highbeam22.TurnOff(); - m_highbeam23.TurnOff(); - m_headsignal12.TurnOff(); - m_headsignal13.TurnOff(); - m_headsignal22.TurnOff(); - m_headsignal23.TurnOff(); - btMechanik1.Turn( false ); - btMechanik2.Turn( false ); - btShutters1.Turn( false ); - btShutters2.Turn( false ); -}; - -// przeliczanie dźwięków, bo będzie słychać bez wyświetlania sektora z pojazdem -void TDynamicObject::RenderSounds() { - - if( false == simulation::is_ready ) { return; } - if( Global.iPause != 0 ) { return; } - - if( m_startjoltplayed - && ( std::abs(MoverParameters->AccSVBased) < 0.01 - || GetVelocity() < 0.01 ) ) { - // if the vehicle comes to a stop set the movement jolt to play when it starts moving again - m_startjoltplayed = false; - } - - auto const dt{ Timer::GetDeltaRenderTime() }; - m_powertrainsounds.render( *MoverParameters, dt ); - - auto volume{ 0.0 }; - auto frequency{ 1.0 }; - - // NBMX dzwiek przetwornicy - if( MoverParameters->ConverterFlag ) { - if( MoverParameters->EngineType == TEngineType::ElectricSeriesMotor ) { - auto const voltage { std::max( MoverParameters->GetTrainsetHighVoltage(), MoverParameters->PantographVoltage ) }; - if( voltage > 0.0 ) { - // NOTE: we do sound modulation here to avoid sudden jump on voltage loss - frequency = voltage / (MoverParameters->NominalVoltage * MoverParameters->RList[MoverParameters->RlistSize].Mn); - frequency *= sConverter.m_frequencyfactor + sConverter.m_frequencyoffset; - sConverter.pitch( std::clamp( frequency, 0.75, 1.25 ) ); // arbitrary limits ) - } - } - else { - frequency = sConverter.m_frequencyoffset + sConverter.m_frequencyfactor * frequency; - sConverter.pitch( std::clamp( frequency, 0.75, 1.25 ) ); // arbitrary limits ) - } - sConverter.play( sound_flags::exclusive | sound_flags::looping ); - } - else { - sConverter.stop(); - } - - // Odtworzenie dzwieku wentylatora rezystora hamowania - - if (MoverParameters->BRVentilators) - { - sBRVent.play(sound_flags::exclusive | sound_flags::looping); - } - else - { - sBRVent.stop(); - } - - - - - - if( MoverParameters->CompressorSpeed > 0.0 ) { - // McZapkie! - dzwiek compressor.wav tylko gdy dziala sprezarka - if( MoverParameters->CompressorFlag ) { - // for compressor coupled with the diesel engine sound pitch is driven by engine revolutions - if( MoverParameters->CompressorPower == 3 ) { - // presume the compressor sound is recorded for idle revolutions - // increase the pitch according to increase of engine revolutions - auto const enginefactor { - std::clamp( // try to keep the sound pitch in semi-reasonable range - MoverParameters->EngineMaxRPM() / MoverParameters->EngineIdleRPM() * MoverParameters->EngineRPMRatio(), - 0.5, 2.5 ) }; - sCompressor.pitch( enginefactor ); - sCompressorIdle.pitch( enginefactor ); - } - if( sCompressorIdle.empty() ) { - // legacy sound path, if there's no dedicated idle sound - sCompressor.play( sound_flags::exclusive | sound_flags::looping ); - } - else { - // enhanced sound path, with dedicated sound for idling compressor - if( MoverParameters->CompressorGovernorLock ) { - sCompressor.stop(); - sCompressorIdle.play( sound_flags::exclusive | sound_flags::looping ); - } - else { - sCompressor.play( sound_flags::exclusive | sound_flags::looping ); - sCompressorIdle.stop(); - } - } - } - else { - sCompressor.stop(); - sCompressorIdle.stop(); - } - } - - // Winger 160404 - dzwiek malej sprezarki - if( MoverParameters->PantCompFlag ) { - sSmallCompressor.play( sound_flags::exclusive | sound_flags::looping ); - } - else { - sSmallCompressor.stop(); - } - - // heater sound - { - auto const isdieselenginepowered { MoverParameters->EngineType == TEngineType::DieselElectric || MoverParameters->EngineType == TEngineType::DieselEngine }; - if( true == MoverParameters->Heating - && ( false == isdieselenginepowered - || std::abs(MoverParameters->enrot) > 0.01 ) ) { - sHeater - .pitch( true == sHeater.is_combined() ? - std::abs( MoverParameters->enrot ) * 60.f * 0.01f : - 1.f ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - sHeater.stop(); - } - } - - // battery sound - if( MoverParameters->Battery ) { - m_batterysound.play( sound_flags::exclusive | sound_flags::looping ); - } - else { - m_batterysound.stop(); - } - - // brake system and braking sounds: - - // brake cylinder piston - auto const brakepressureratio { std::max( 0.0, MoverParameters->BrakePress ) / std::max( 1.0, MoverParameters->MaxBrakePress[ 3 ] ) }; - if( m_lastbrakepressure != -1.f ) { - // HACK: potentially reset playback of opening bookend sounds - if( false == m_brakecylinderpistonadvance.is_playing() ) { - m_brakecylinderpistonadvance.stop(); - } - if( false == m_brakecylinderpistonrecede.is_playing() ) { - m_brakecylinderpistonrecede.stop(); - } - // actual sound playback - auto const quantizedratio { static_cast( 15 * brakepressureratio ) }; - auto const lastbrakepressureratio { std::max( 0.f, m_lastbrakepressure ) / std::max( 1.0, MoverParameters->MaxBrakePress[ 3 ] ) }; - auto const quantizedratiochange { quantizedratio - static_cast( 15 * lastbrakepressureratio ) }; - if( quantizedratiochange > 0 ) { - m_brakecylinderpistonadvance - .pitch( - true == m_brakecylinderpistonadvance.is_combined() ? - quantizedratio * 0.01f : - m_brakecylinderpistonadvance.m_frequencyoffset + m_brakecylinderpistonadvance.m_frequencyfactor * 1.f ) - .play(); - } - else if( quantizedratiochange < 0 ) { - m_brakecylinderpistonrecede - .pitch( true == m_brakecylinderpistonrecede.is_combined() ? - quantizedratio * 0.01f : - m_brakecylinderpistonrecede.m_frequencyoffset + m_brakecylinderpistonrecede.m_frequencyfactor * 1.f ) - .play(); - } - } - - // epbrake - epcompact - if (MoverParameters->BrakeSystem == TBrakeSystem::ElectroPneumatic && MoverParameters->LocHandle) { - auto const epbrakepressureratio{ std::min( std::max( 0.0, MoverParameters->LocHandle->GetCP() ) / std::max( 1.0, MoverParameters->MaxBrakePress[0] ), - m_epbrakepressurechangedectimer > -1.0f ? - std::max( MoverParameters->LocalBrakePosAEIM, MoverParameters->Hamulec->GetEDBCP() / MoverParameters->MaxBrakePress[3]) : - 1.0 ) }; - if ( m_lastepbrakepressure != -1.f ) { - // HACK: potentially reset playback of opening bookend sounds - if ( false == m_epbrakepressureincrease.is_playing() ) { - m_epbrakepressureincrease.stop(); - } - if ( false == m_epbrakepressuredecrease.is_playing() ) { - m_epbrakepressuredecrease.stop(); - } - m_epbrakepressurechangeinctimer += dt; - m_epbrakepressurechangedectimer += dt; - // actual sound playback - auto const epquantizedratio{ static_cast( 50 * epbrakepressureratio) }; - auto const lastepbrakepressureratio { std::max( 0.f, m_lastepbrakepressure ) / std::max( 1.0, MoverParameters->MaxBrakePress[0] ) }; - auto const epquantizedratiochange { epquantizedratio - static_cast( 50 * lastepbrakepressureratio ) }; - if ( epquantizedratiochange > 0 && m_epbrakepressurechangeinctimer > 0.05f) { - m_epbrakepressureincrease - .pitch( - true == m_epbrakepressureincrease.is_combined() ? - epquantizedratio * 0.01f : - m_epbrakepressureincrease.m_frequencyoffset + m_epbrakepressureincrease.m_frequencyfactor * 1.f ) - .play(); - m_epbrakepressurechangeinctimer = 0; - } - else if ( epquantizedratiochange < 0 && m_epbrakepressurechangedectimer > 0.3f) { - m_epbrakepressuredecrease - .pitch(true == m_epbrakepressuredecrease.is_combined() ? - -epquantizedratiochange * 0.01f : - m_epbrakepressuredecrease.m_frequencyoffset + m_epbrakepressuredecrease.m_frequencyfactor * 1.f ) - .play(); - m_epbrakepressurechangedectimer = 0; - } - } - if ( m_epbrakepressurechangeinctimer == 0 || m_epbrakepressurechangedectimer == 0 ) - m_lastepbrakepressure = std::min( MoverParameters->LocHandle->GetCP(), - MoverParameters->LocalBrakePosAEIM * std::max( 1.0, MoverParameters->MaxBrakePress[0] ) ); - } - - // emergency brake - if( MoverParameters->EmergencyValveFlow > 0.025 ) { - // smooth out air flow rate - m_emergencybrakeflow = m_emergencybrakeflow == 0.0 ? MoverParameters->EmergencyValveFlow : std::lerp(m_emergencybrakeflow, MoverParameters->EmergencyValveFlow, 0.1); - // scale volume based on the flow rate and on the pressure in the main pipe - auto const flowpressure { std::clamp( m_emergencybrakeflow, 0.0, 1.0 ) + std::clamp( 0.1 * MoverParameters->PipePress, 0.0, 0.5 ) }; - m_emergencybrake - .pitch( m_emergencybrake.m_frequencyoffset + 1.0 * m_emergencybrake.m_frequencyfactor ) - .gain( m_emergencybrake.m_amplitudeoffset + std::clamp( flowpressure, 0.0, 1.0 ) * m_emergencybrake.m_amplitudefactor ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else if( MoverParameters->EmergencyValveFlow < 0.015 ) { - m_emergencybrakeflow = 0.0; - m_emergencybrake.stop(); - } - - // air release - if( m_lastbrakepressure != -1.f ) { - // calculate rate of pressure drop in brake cylinder, once it's been initialized - auto const brakepressuredifference{ m_lastbrakepressure - MoverParameters->BrakePress }; - m_brakepressurechange = std::lerp( m_brakepressurechange, brakepressuredifference / dt, 0.05f ); - } - m_lastbrakepressure = MoverParameters->BrakePress; - // ensure some basic level of volume and scale it up depending on pressure in the cylinder; scale this by the air release rate - volume = rsUnbrake.m_amplitudefactor * m_brakepressurechange * ( 0.25 + 0.75 * brakepressureratio ); - if( m_brakepressurechange > 0.05 && brakepressureratio > 0.05 ) { - rsUnbrake - .gain( volume ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - // don't stop the sound too abruptly - volume = std::max( 0.0, rsUnbrake.gain() - 0.5 * dt ); - rsUnbrake.gain( volume ); - if( volume < 0.05 ) { - rsUnbrake.stop(); - } - } - - // Dzwiek odluzniacza - if( MoverParameters->Hamulec->Releaser() ) { - sReleaser - .gain( - std::clamp( - MoverParameters->BrakePress * 1.25, // arbitrary multiplier - 0., 1. ) ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - sReleaser.stop(); - } - - // slipping wheels - if( MoverParameters->SlippingWheels ) { - - if( MoverParameters->UnitBrakeForce > 100.0 - && GetVelocity() > 1.0 ) { - - auto const velocitydifference{ GetVelocity() / MoverParameters->Vmax }; - rsSlippery - .gain( rsSlippery.m_amplitudeoffset + rsSlippery.m_amplitudefactor * velocitydifference ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - } - else { - rsSlippery.stop(); - } - - // Dzwiek piasecznicy - if( MoverParameters->SandDose ) { - sSand.play( sound_flags::exclusive | sound_flags::looping ); - } - else { - sSand.stop(); - } - - // brakes - auto brakeforceratio{ 0.0 }; - if( //( false == mvOccupied->SlippingWheels ) && - MoverParameters->UnitBrakeForce > 10.0 - && MoverParameters->Vel > 0.05 ) { - - brakeforceratio = - std::clamp( - MoverParameters->UnitBrakeForce / std::max( 1.0, MoverParameters->BrakeForceR( 1.0, MoverParameters->Vel ) / ( MoverParameters->NAxles * std::max( 1, MoverParameters->NBpA ) ) ), - 0.0, 1.0 ); - rsBrake - .pitch( rsBrake.m_frequencyoffset + MoverParameters->Vel * rsBrake.m_frequencyfactor ) - .gain( rsBrake.m_amplitudeoffset + std::sqrt( brakeforceratio * std::lerp( 0.4, 1.0, MoverParameters->Vel / (1 + MoverParameters->Vmax) ) ) * rsBrake.m_amplitudefactor ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - rsBrake.stop(); - } - - // yB: przyspieszacz (moze zadziala, ale dzwiek juz jest) - if( true == bBrakeAcc ) { - if( true == TestFlag( MoverParameters->Hamulec->GetSoundFlag(), sf_Acc ) ) { - sBrakeAcc.play( sound_flags::exclusive ); - } - } - - // McZapkie-280302 - pisk mocno zacisnietych hamulcow - if( MoverParameters->Vel > 2.5 ) { - - volume = rsPisk.m_amplitudeoffset + std::lerp( -1.0, 1.0, brakeforceratio ) * rsPisk.m_amplitudefactor; - if( volume > 0.075 ) { - rsPisk - .pitch( - true == rsPisk.is_combined() ? - MoverParameters->Vel * 0.01f : - rsPisk.m_frequencyoffset + rsPisk.m_frequencyfactor * 1.f ) - .gain( volume ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - } - else { - // don't stop the sound too abruptly - volume = std::max( 0.0, rsPisk.gain() - rsPisk.gain() * 2.5 * dt ); - rsPisk.gain( volume ); - } - if( volume < 0.05 ) { - rsPisk.stop(); - } - - // spring brake - if( m_springbrakesounds.state != MoverParameters->SpringBrake.Activate ) { - m_springbrakesounds.state = MoverParameters->SpringBrake.Activate; - if( m_springbrakesounds.state ) { - m_springbrakesounds.activate.play( sound_flags::exclusive ); - m_springbrakesounds.release.stop(); - } - else { - m_springbrakesounds.activate.stop(); - m_springbrakesounds.release.play( sound_flags::exclusive ); - } - } - - // other sounds - // load exchange - if( MoverParameters->LoadStatus & 1 ) { - m_exchangesounds.unloading.play( sound_flags::exclusive ); - } - else { - m_exchangesounds.unloading.stop(); - } - if( MoverParameters->LoadStatus & 2 ) { - m_exchangesounds.loading.play( sound_flags::exclusive ); - } - else { - m_exchangesounds.loading.stop(); - } - // NBMX sygnal odjazdu - if( MoverParameters->Doors.has_warning ) { - auto const lowvoltagepower { MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable }; - for( auto &doorspeaker : m_doorspeakers ) { - // TBD, TODO: per-location door state triggers? - if( MoverParameters->DepartureSignal - && lowvoltagepower -/* - || ( ( MoverParameters->DoorCloseCtrl = control::autonomous ) - && ( ( ( false == MoverParameters->DoorLeftOpened ) && ( dDoorMoveL > 0.0 ) ) - || ( ( false == MoverParameters->DoorRightOpened ) && ( dDoorMoveR > 0.0 ) ) ) ) -*/ - ) { - // for the autonomous doors play the warning automatically whenever a door is closing - // MC: pod warunkiem ze jest zdefiniowane w chk - doorspeaker.departure_signal.play( sound_flags::exclusive | sound_flags::looping ); - } - else { - doorspeaker.departure_signal.stop(); - } - } - } - // announcements - { - auto const lowvoltagepower { MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable }; - if( lowvoltagepower ) { - // system is powered up, can play queued announcements - if( false == m_pasystem.announcement_queue.empty() - && false == m_pasystem.announcement.is_playing() ) { - // pull first sound from the queue - m_pasystem.announcement = m_pasystem.announcement_queue.front(); - m_pasystem.announcement.owner( this ); - m_pasystem.announcement.range( 0.5 * MoverParameters->Dim.L * -1 ); - if( m_pasystem.soundproofing ) { - if( !m_pasystem.announcement.soundproofing() ) { - m_pasystem.announcement.soundproofing() = m_pasystem.soundproofing; - } - } - m_pasystem.announcement.play(); - m_pasystem.announcement_queue.pop_front(); - } - } - else { - m_pasystem.announcement.stop(); - m_pasystem.announcement_queue.clear(); - } - } - // NBMX Obsluga drzwi, MC: zuniwersalnione - std::array const sides { side::right, side::left }; - for( auto const side : sides ) { - - auto const &door { MoverParameters->Doors.instances[ side ] }; - - if( true == door.is_opening ) { - // door sounds - if( false == door.step_unfolding // no wait if no doorstep - || MoverParameters->Doors.step_type == 2 ) { // no wait for rotating doorstep - if( door.position < 0.5f ) { // safety measure, to keep slightly too short sounds from repeating - for( auto &doorsounds : m_doorsounds ) { - if( doorsounds.placement == side ) { - // determine left side doors from their offset - doorsounds.rsDoorOpen.play( sound_flags::exclusive ); - doorsounds.rsDoorClose.stop(); - } - } - } - } - } - if( true == door.is_closing ) { - // door sounds can start playing before the door begins moving but shouldn't cease once the door closes - if( door.position > 0.f ) { - for( auto &doorsounds : m_doorsounds ) { - if( doorsounds.placement == side ) { - // determine left side doors from their offset - doorsounds.rsDoorClose.play( sound_flags::exclusive ); - doorsounds.rsDoorOpen.stop(); - } - } - } - } - // doorstep sounds - if( door.step_unfolding ) { - for( auto &doorsounds : m_doorsounds ) { - if( doorsounds.placement == side ) { - doorsounds.step_open.play( sound_flags::exclusive ); - doorsounds.step_close.stop(); - } - } - } - if( door.step_folding ) { - if( door.step_position < 1.0f ) { // sanity check, the vehicles may keep the doorstep unfolded until the door close - for( auto &doorsounds : m_doorsounds ) { - if( doorsounds.placement == side ) { - // determine left side doors from their offset - doorsounds.step_close.play( sound_flags::exclusive ); - doorsounds.step_open.stop(); - } - } - } - } - } - // door locks - if( MoverParameters->Doors.is_locked != m_doorlocks ) { - // toggle state of the locks... - m_doorlocks = !m_doorlocks; - // ...and play relevant sounds - for( auto &door : m_doorsounds ) { - if( m_doorlocks ) { - door.lock.play( sound_flags::exclusive ); - } - else { - door.unlock.play( sound_flags::exclusive ); - } - } - } - - // horns - { - // for moving vehicle combine regular horn activation flag with emergency brake horn activation flag, if the brake is active; - // the horns without the air or the voltage they need stay silent - auto const warningsignal { MoverParameters->SoundingHorns( - ( MoverParameters->Vel > 0.5 && MoverParameters->AlarmChainFlag ? - MoverParameters->EmergencyBrakeWarningSignal : - 0 ) - | MoverParameters->WarningSignal ) }; - - if( TestFlag( warningsignal, 1 ) ) { - sHorn1.play( sound_flags::exclusive | sound_flags::looping ); - } - else { - sHorn1.stop(); - } - if( TestFlag( warningsignal, 2 ) ) { - sHorn2.play( sound_flags::exclusive | sound_flags::looping ); - } - else { - sHorn2.stop(); - } - if( TestFlag( warningsignal, 4 ) ) { - sHorn3.play( sound_flags::exclusive | sound_flags::looping ); - } - else { - sHorn3.stop(); - } - } - // szum w czasie jazdy - if( GetVelocity() > 0.5 -#ifdef EU07_SOUND_BOGIESOUNDS - && false == m_bogiesounds.empty() -#endif - && ( // compound test whether the vehicle belongs to user-driven consist (as these don't emit outer noise in cab view) - FreeFlyModeFlag ? true : // in external view all vehicles emit outer noise - simulation::Train == nullptr ? true : // no player train, e.g. it went through a portal and the view isn't switched yet - ctOwner == nullptr ? true : // standalone vehicle, can't be part of user-driven train - ctOwner != simulation::Train->Dynamic()->ctOwner ? true : // confirmed isn't a part of the user-driven train - Global.CabWindowOpen ? true : // sticking head out we get to hear outer noise - false ) ) { -#ifdef EU07_SOUND_BOGIESOUNDS - auto const &bogiesound { m_bogiesounds.front() }; -#else - auto const &bogiesound { m_outernoise }; -#endif - // frequency calculation - auto const normalizer { ( - true == bogiesound.is_combined() ? - MoverParameters->Vmax * 0.01f : - 1.f ) }; - frequency = - bogiesound.m_frequencyoffset - + bogiesound.m_frequencyfactor * MoverParameters->Vel * normalizer; - - // volume calculation - volume = - bogiesound.m_amplitudeoffset - + bogiesound.m_amplitudefactor * MoverParameters->Vel; - if( brakeforceratio > 0.0 ) { - // hamulce wzmagaja halas - volume *= 1 + 0.125 * brakeforceratio; - } - // scale volume by track quality - // TODO: track quality and/or environment factors as separate subroutine - volume *= - std::lerp( - 0.8, 1.2, - std::clamp( - MyTrack->iQualityFlag / 20.0, - 0.0, 1.0 ) ); - // for single sample sounds muffle the playback at low speeds - if( false == bogiesound.is_combined() ) { - volume *= - std::lerp( - 0.0, 1.0, - std::clamp( - MoverParameters->Vel / 40.0, - 0.0, 1.0 ) ); - } - switch( MyTrack->eEnvironment ) { - case e_tunnel: { - volume *= 1.3; - break; - } - case e_bridge: { - volume *= 1.5; - break; - } - default: { - break; - } - } - - if( volume > 0.05 ) { - // apply calculated parameters to all motor instances -#ifdef EU07_SOUND_BOGIESOUNDS - for( auto &bogiesound : m_bogiesounds ) { - bogiesound - .pitch( frequency ) // arbitrary limits to prevent the pitch going out of whack - .gain( volume ) - .play( sound_flags::exclusive | sound_flags::looping ); - } -#else - m_outernoise - .pitch( frequency ) // arbitrary limits to prevent the pitch going out of whack - .gain( volume ) - .play( sound_flags::exclusive | sound_flags::looping ); -#endif - } - else { - // stop all noise instances -#ifdef EU07_SOUND_BOGIESOUNDS - for( auto &bogiesound : m_bogiesounds ) { - bogiesound.stop(); - } -#else - m_outernoise.stop(); -#endif - } - } - else { - // don't play the optional ending sound if the listener switches views -#ifdef EU07_SOUND_BOGIESOUNDS - for( auto &bogiesound : m_bogiesounds ) { - bogiesound.stop( false == FreeFlyModeFlag ); - } -#else - m_outernoise.stop( false == FreeFlyModeFlag ); -#endif - } - // flat spot sound - if( MoverParameters->CategoryFlag == 1 ) { - // trains only - if( GetVelocity() > 1.0 - && MoverParameters->WheelFlat > 5.0 ) { - m_wheelflat - .pitch( m_wheelflat.m_frequencyoffset + std::abs( MoverParameters->nrot ) * m_wheelflat.m_frequencyfactor ) - .gain( m_wheelflat.m_amplitudeoffset + m_wheelflat.m_amplitudefactor * ( ( 1.0 + MoverParameters->Vel / MoverParameters->Vmax + std::clamp( MoverParameters->WheelFlat / 60.0, 0.0, 1.0 ) ) / 3.0 ) ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - m_wheelflat.stop(); - } - } - - // youBy: dzwiek ostrych lukow i ciasnych zwrotek - if( MoverParameters->Vel > 5.0 - && ts.R * ts.R > 1.0 - && std::abs(ts.R) < 15000.0 ) { - // scale volume with curve radius and vehicle speed - volume = - std::abs( MoverParameters->AccN ) // * MoverParameters->AccN - * std::lerp( - 0.5, 1.0, - std::clamp( - MoverParameters->Vel / 40.0, - 0.0, 1.0 ) ) - * ( MyTrack->eType == tt_Switch && std::abs(ts.R) < 1500.0 ? 100.0 : 1.0 ); - } - else { - volume = 0; - } - if( volume > 0.05 ) { - rscurve - .pitch( - true == rscurve.is_combined() ? - MoverParameters->Vel * 0.01f : - rscurve.m_frequencyoffset + rscurve.m_frequencyfactor * 1.f ) - .gain( 2.5 * volume ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - rscurve.stop(); - } - - // movement start jolt - if( false == m_startjoltplayed ) { - auto const velocity { GetVelocity() }; - if( ( MoverParameters->V > 0.0 ? MoverParameters->AccSVBased > 0.1 : MoverParameters->AccSVBased < 0.1 ) - && velocity > 1.0 - && velocity < 15.0 ) { - m_startjolt.play( sound_flags::exclusive ); - m_startjoltplayed = true; - } - } - - // McZapkie! - to wazne - SoundFlag wystawiane jest przez moje moduly gdy zachodza pewne wydarzenia komentowane dzwiekiem. - // pneumatic relay - if( TestFlag( MoverParameters->SoundFlag, sound::pneumatic ) ) { - dsbPneumaticRelay - .gain( - true == TestFlag( MoverParameters->SoundFlag, sound::loud ) ? - 1.0f : - 0.8f ) - .play(); - } - // door permit - if( TestFlag( MoverParameters->SoundFlag, sound::doorpermit ) ) { - // NOTE: current implementation doesn't discern between permit for left/right side, - // which may be undesired in weird setups with doors only on one side - // TBD, TODO: rework into dedicated sound event flag for each door location instance? - for( auto &door : m_doorsounds ) { - door.permit_granted.play( sound_flags::exclusive ); - } - } - - // couplers - int couplerindex { 0 }; - for( auto &couplersounds : m_couplersounds ) { - - auto &coupler { MoverParameters->Couplers[ couplerindex ] }; - - if( coupler.sounds == sound::none ) { - ++couplerindex; - continue; - } - - if( true == TestFlag( coupler.sounds, sound::bufferclash ) ) { - // zderzaki uderzaja o siebie - if( true == TestFlag( coupler.sounds, sound::loud ) ) { - // loud clash - if( false == couplersounds.dsbBufferClamp_loud.empty() ) { - // dedicated sound for loud clash - couplersounds.dsbBufferClamp_loud - .gain( 1.f ) - .play( sound_flags::exclusive ); - } - else { - // fallback on the standard sound - couplersounds.dsbBufferClamp - .gain( 1.f ) - .play( sound_flags::exclusive ); - } - } - else { - // basic clash - couplersounds.dsbBufferClamp - .gain( 1.f ) - .play( sound_flags::exclusive ); - } - } - - if( true == TestFlag( coupler.sounds, sound::couplerstretch ) ) { - // sprzegi sie rozciagaja - if( true == TestFlag( coupler.sounds, sound::loud ) ) { - // loud stretch - if( false == couplersounds.dsbCouplerStretch_loud.empty() ) { - // dedicated sound for loud stretch - couplersounds.dsbCouplerStretch_loud - .gain( 1.f ) - .play( sound_flags::exclusive ); - } - else { - // fallback on the standard sound - couplersounds.dsbCouplerStretch - .gain( 1.f ) - .play( sound_flags::exclusive ); - } - } - else { - // basic clash - couplersounds.dsbCouplerStretch - .gain( 1.f ) - .play( sound_flags::exclusive ); - } - } - // attach/detach sounds - if( ( coupler.sounds & sound::detach ) == 0 ) { - // potentially added some couplings - if( ( coupler.sounds & sound::attachcoupler ) != 0 ) { - couplersounds.attach_coupler.play(); - } - if( ( coupler.sounds & sound::attachbrakehose ) != 0 ) { - couplersounds.attach_brakehose.play(); - } - if( ( coupler.sounds & sound::attachmainhose ) != 0 ) { - couplersounds.attach_mainhose.play(); - } - if( ( coupler.sounds & sound::attachcontrol ) != 0 ) { - couplersounds.attach_control.play(); - } - if( ( coupler.sounds & sound::attachgangway ) != 0 ) { - couplersounds.attach_gangway.play(); - } - if( ( coupler.sounds & sound::attachheating ) != 0 ) { - couplersounds.attach_heating.play(); - } - } - else { - // potentially removed some couplings - if( ( coupler.sounds & sound::attachcoupler ) != 0 ) { - couplersounds.detach_coupler.play(); - } - if( ( coupler.sounds & sound::attachbrakehose ) != 0 ) { - couplersounds.detach_brakehose.play(); - } - if( ( coupler.sounds & sound::attachmainhose ) != 0 ) { - couplersounds.detach_mainhose.play(); - } - if( ( coupler.sounds & sound::attachcontrol ) != 0 ) { - couplersounds.detach_control.play(); - } - if( ( coupler.sounds & sound::attachgangway ) != 0 ) { - couplersounds.detach_gangway.play(); - } - if( ( coupler.sounds & sound::attachheating ) != 0 ) { - couplersounds.detach_heating.play(); - } - } - if( true == TestFlag( coupler.sounds, sound::attachadapter ) ) { - couplersounds.dsbAdapterAttach.play(); - } - if( true == TestFlag( coupler.sounds, sound::removeadapter ) ) { - couplersounds.dsbAdapterRemove.play(); - } - - ++couplerindex; - coupler.sounds = 0; - } - - MoverParameters->SoundFlag = 0; - // McZapkie! - koniec obslugi dzwiekow z mover.pas - - // physics.derailment new: off the track the vehicle scrapes along the ground until it stops, or until it is put back - // on the rails (rerail()) while still sliding - if( MoverParameters->OffTrack.active() && false == MoverParameters->OffTrack.at_rest() ) { - if( false == rsDerailment.is_playing() ) { - rsDerailment.play( sound_flags::exclusive | sound_flags::looping ); - } - m_offtrackscraping = true; - } - else if( std::exchange( m_offtrackscraping, false ) && rsDerailment.is_playing() ) { - rsDerailment.stop(); - } - -// special events - if( MoverParameters->EventFlag ) { - // McZapkie: w razie wykolejenia - if( true == MoverParameters->DamageFlag.HasAll(VehicleDamage::derailed) ) { - rsDerailment.play( sound_flags::exclusive ); - } - - MoverParameters->EventFlag = false; - } -} - -// calculates distance between event-starting axle and front of the vehicle -double -TDynamicObject::tracing_offset() const { - - auto const axletoend{ ( GetLength() - fAxleDist ) * 0.5 }; - return iAxleFirst ? axletoend : axletoend + iDirection * fAxleDist; -} - -// TODO: compute and cache radius during vehicle initialization -double -TDynamicObject::radius() const { - - glm::vec3 diagonal( - static_cast( MoverParameters->Dim.L ), - static_cast( MoverParameters->Dim.H ), - static_cast( MoverParameters->Dim.W ) ); - return glm::length( diagonal ) * 0.5f; -} - -// McZapkie-250202 -// wczytywanie pliku z danymi multimedialnymi (dzwieki) -void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string const &ReplacableSkin ) { - rTypeName = TypeName; - rReplacableSkin = ReplacableSkin; - Global.asCurrentDynamicPath = asBaseDir; - std::string asFileName = asBaseDir + TypeName + ".mmd"; - std::string asAnimName; - bool Stop_InternalData = false; - pants = nullptr; // wskaźnik pierwszego obiektu animującego dla pantografów - wipers = nullptr; // wskaznik pierwszego obiektu animujacego dla wycieraczek - { - // preliminary check whether the file exists - cParser parser( TypeName + ".mmd", cParser::buffer_FILE, asBaseDir ); - if( false == parser.ok() ) { - ErrorLog( "Failed to load appearance data for vehicle " + MoverParameters->Name ); - return; - } - } - // use #include wrapper to access the appearance data file - // this allows us to provide the file content with user-defined parameters - cParser parser( - "include " + TypeName + ".mmd" - + " " + asName // (p1) - + " " + TypeName // (p2) - + " " + ReplacableSkin // (p3) - + " end", - cParser::buffer_TEXT, - asBaseDir, true, std::vector(), true ); - std::string token; - do { - token = ""; - parser.getTokens(); parser >> token; - - if( token == "models:" ) { - // modele i podmodele - m_materialdata.multi_textures = 0; // czy jest wiele tekstur wymiennych? - parser.getTokens(); - parser >> asModel; - replace_slashes( asModel ); - if( asModel.back() == '#' ) // Ra 2015-01: nie podoba mi siê to - { // model wymaga wielu tekstur wymiennych - m_materialdata.multi_textures = 1; - asModel.erase( asModel.length() - 1 ); - } - // name can contain leading slash, erase it to avoid creation of double slashes when the name is combined with current directory - erase_leading_slashes( asModel ); - /* - // never really used, may as well get rid of it - std::size_t i = asModel.find( ',' ); - if ( i != std::string::npos ) - { // Ra 2015-01: może szukać przecinka w nazwie modelu, a po przecinku była by liczba tekstur? - if( i < asModel.length() ) { - m_materialdata.multi_textures = asModel[ i + 1 ] - '0'; - } - m_materialdata.multi_textures = std::clamp( m_materialdata.multi_textures, 0, 1 ); // na razie ustawiamy na 1 - } - */ - asModel = asBaseDir + asModel; // McZapkie 2002-07-20: dynamics maja swoje modele w dynamics/basedir - Global.asCurrentTexturePath = asBaseDir; // biezaca sciezka do tekstur to dynamic/... - mdModel = TModelsManager::GetModel(asModel, true); - if (ReplacableSkin != "none") { - m_materialdata.assign( ReplacableSkin ); - } - Global.asCurrentTexturePath = paths::textures; // z powrotem defaultowa sciezka do tekstur - do { - token = ""; - parser.getTokens(); parser >> token; - - if( token == "animations:" ) { - // Ra: ustawienie ilości poszczególnych animacji - musi być jako pierwsze, inaczej ilości będą domyślne -/* - if( nullptr == pAnimations ) -*/ - if( true == pAnimations.empty() ) - { // jeśli nie ma jeszcze tabeli animacji, można odczytać nowe ilości - int co = 0; - iAnimations = 0; - int ile; - do - { // kolejne liczby to ilość animacj, -1 to znacznik końca - ile = -1; - parser.getTokens( 1, false ); - parser >> ile; // ilość danego typu animacji - if (ile >= 0) - { - iAnimType[co] = ile; // zapamiętanie - iAnimations += ile; // ogólna ilość animacji - } - else { - iAnimType[co] = 0; - } - ++co; - } while ( ile >= 0 && co < ANIM_TYPES ); //-1 to znacznik końca - - pAnimations.resize( iAnimations ); - int i, j, k = 0, sm = 0; - for (j = 0; j < ANIM_TYPES; ++j) // petla po wszystkich wpisach w animations - for (i = 0; i < iAnimType[j]; ++i) // petla iteruje sie tyle razy ile mamy wpisane w animations - { - if (j == ANIM_PANTS) // zliczamy poprzednie animacje - if (!pants) - if (iAnimType[ANIM_PANTS]) // o ile jakieś pantografy są (a domyślnie są) - pants = &pAnimations[k]; // zapamiętanie na potrzeby wyszukania submodeli - if (j == ANIM_WIPERS) - if (!wipers) - if (iAnimType[ANIM_WIPERS]) - wipers = &pAnimations[k]; - pAnimations[k].iShift = sm; // przesunięcie do przydzielenia wskaźnika - sm += pAnimations[k++].TypeSet(j, *MoverParameters); // ustawienie typu animacji i zliczanie tablicowanych submodeli - } - if (sm) // o ile są bardziej złożone animacje - { - pAnimated = new TSubModel *[sm]; // tabela na animowane submodele - for (k = 0; k < iAnimations; ++k) - pAnimations[k].smElement = pAnimated + pAnimations[k].iShift; // przydzielenie wskaźnika do tabelki - } - } - } - - else if(token == "lowpolyinterior:") { - // ABu: wnetrze lowpoly - parser.getTokens(); - parser >> asModel; - - replace_slashes( asModel ); - erase_leading_slashes( asModel ); - asModel = asBaseDir + asModel; // McZapkie-200702 - dynamics maja swoje modele w dynamic/basedir - Global.asCurrentTexturePath = asBaseDir; // biezaca sciezka do tekstur to dynamic/... - mdLowPolyInt = TModelsManager::GetModel(asModel, true); - } - - else if(token == "coupleradapter:") { - // coupling adapter data - parser.getTokens( 3 ); - parser - >> m_coupleradapter.model - >> m_coupleradapter.position.x - >> m_coupleradapter.position.y; - replace_slashes( m_coupleradapter.model ); - erase_leading_slashes( m_coupleradapter.model ); - } - - else if(token == "attachments:") { - // additional 3d models attached to main body - // content provided as a series of values together enclosed in "{}" - // each value is a name of additional 3d model - // value can be optionally set of values enclosed in "[]" in which case one value will be picked randomly - // TBD: reconsider something more yaml-compliant and/or ability to define offset and rotation - while( (token = deserialize_random_set(parser)) != "" - && token != "}" ) { - if( token == "{" ) { continue; } - replace_slashes( token ); - Global.asCurrentTexturePath = asBaseDir; // biezaca sciezka do tekstur to dynamic/... - auto *attachmentmodel { TModelsManager::GetModel( asBaseDir + token, true ) }; - if( attachmentmodel != nullptr ) { - mdAttachments.emplace_back( attachmentmodel ); - } - } - } - - else if(token == "loads:") { - // default load visualization models overrides - // content provided as "key: value" pairs together enclosed in "{}" - // value can be optionally set of values enclosed in "[]" in which case one value will be picked randomly - while( (token = parser.getToken()) != "" - && token != "}" ) { - if( token.back() == ':' ) { - auto loadmodel { deserialize_random_set( parser ) }; - replace_slashes( loadmodel ); - LoadModelOverrides.emplace( token.erase( token.size() - 1 ), loadmodel ); - } - } - } - - else if( token == "brakemode:" ) { - // Ra 15-01: gałka nastawy hamulca - parser.getTokens(); - parser >> asAnimName; - smBrakeMode = GetSubmodelFromName( mdModel, asAnimName ); - // jeszcze wczytać kąty obrotu dla poszczególnych ustawień - } - - else if( token == "loadmode:" ) { - // Ra 15-01: gałka nastawy hamulca - parser.getTokens(); - parser >> asAnimName; - smLoadMode = GetSubmodelFromName( mdModel, asAnimName ); - // jeszcze wczytać kąty obrotu dla poszczególnych ustawień - } - - else if (token == "animwheelprefix:") { - // prefiks kręcących się kół - int i, k, m; - unsigned int j; - parser.getTokens( 1, false ); parser >> token; - for (i = 0; i < iAnimType[ANIM_WHEELS]; ++i) // liczba osi - { // McZapkie-050402: wyszukiwanie kol o nazwie str* - asAnimName = token + std::to_string(i + 1); - pAnimations[i].smAnimated = GetSubmodelFromName( mdModel, asAnimName ); - if (pAnimations[i].smAnimated) - { //++iAnimatedAxles; - pAnimations[i].smAnimated->WillBeAnimated(); // wyłączenie optymalizacji transformu - pAnimations[i].yUpdate = std::bind( &TDynamicObject::UpdateAxle, this, std::placeholders::_1 ); - pAnimations[i].fMaxDist = Global.fDistanceFactor * MoverParameters->WheelDiameter * 200; - pAnimations[i].fMaxDist *= pAnimations[i].fMaxDist; - } - } - // Ra: ustawianie indeksów osi - for (i = 0; i < iAnimType[ANIM_WHEELS]; ++i) // ilość osi (zabezpieczenie przed błędami w CHK) - pAnimations[i].dWheelAngle = 1; // domyślnie wskaźnik na napędzające - i = 0; - j = 1; - k = 0; - m = 0; // numer osi; kolejny znak; ile osi danego typu; która średnica - if (MoverParameters->WheelDiameterL != MoverParameters->WheelDiameter || - MoverParameters->WheelDiameterT != MoverParameters->WheelDiameter) - { // obsługa różnych średnic, o ile występują - while (i < iAnimType[ANIM_WHEELS] && - j <= MoverParameters->AxleArangement.length()) - { // wersja ze wskaźnikami jest bardziej elastyczna na nietypowe układy - if (k >= 'A' && k <= 'J') // 10 chyba maksimum? - { - pAnimations[i++].dWheelAngle = 1; // obrót osi napędzających - --k; // następna będzie albo taka sama, albo bierzemy kolejny znak - m = 2; // następujące toczne będą miały inną średnicę - } - else if (k >= '1' && k <= '9') - { - pAnimations[i++].dWheelAngle = m; // obrót osi tocznych - --k; // następna będzie albo taka sama, albo bierzemy kolejny znak - } - else - k = MoverParameters->AxleArangement[j++]; // pobranie kolejnego znaku - } - } - } - // else if (str==AnsiString("animrodprefix:")) //prefiks wiazarow dwoch - // { - // str= Parser->GetNextSymbol(); - // for (int i=1; i<=2; i++) - // {//McZapkie-050402: wyszukiwanie max 2 wiazarow o nazwie str* - // asAnimName=str+i; - // smWiazary[i-1]=mdModel->GetFromName(asAnimName.c_str()); - // smWiazary[i-1]->WillBeAnimated(); - // } - // } - - else if( token == "animpantprefix:" ) { - // Ra: pantografy po nowemu mają literki i numerki - } - // Pantografy - Winger 160204 - else if( token == "animpantrd1prefix:" ) { - // prefiks ramion dolnych 1 - parser.getTokens(); parser >> token; - float4x4 m; // macierz do wyliczenia pozycji i wektora ruchu pantografu - TSubModel *sm; - if (pants) - for (int i = 0; i < iAnimType[ANIM_PANTS]; i++) - { // Winger 160204: wyszukiwanie max 2 patykow o nazwie str* - asAnimName = token + std::to_string(i + 1); - sm = GetSubmodelFromName( mdModel, asAnimName ); - pants[i].smElement[0] = sm; // jak NULL, to nie będzie animowany - if (sm) - { // w EP09 wywalało się tu z powodu NULL - sm->WillBeAnimated(); - sm->ParentMatrix(&m); // pobranie macierzy transformacji - // m(3)[1]=m[3][1]+0.054; //w górę o wysokość ślizgu (na razie tak) - pants[i].fParamPants->vPos.z = m[3][0]; // przesunięcie w bok (asymetria) - pants[i].fParamPants->vPos.y = m[3][1]; // przesunięcie w górę odczytane z modelu - if ((sm = pants[i].smElement[0]->ChildGet()) != nullptr) - { // jeśli ma potomny, można policzyć długość (odległość potomnego od osi obrotu) - m = float4x4(*sm->GetMatrix()); // wystarczyłby wskaźnik, nie trzeba kopiować - // może trzeba: pobrać macierz dolnego ramienia, wyzerować przesunięcie, przemnożyć przez macierz górnego - pants[i].fParamPants->fHoriz = -fabs(m[3][1]); - pants[i].fParamPants->fLenL1 = hypot(m[3][1], m[3][2]); // po osi OX nie potrzeba - pants[i].fParamPants->fAngleL0 = atan2(fabs(m[3][2]), fabs(m[3][1])); - // if (pants[i].fParamPants->fAngleL0fAngleL0+=M_PI; //gdyby w odwrotną stronę wyszło - // if - // ((pants[i].fParamPants->fAngleL0<0.03)||(pants[i].fParamPants->fAngleL0>0.09)) - // //normalnie ok. 0.05 - // pants[i].fParamPants->fAngleL0=pants[i].fParamPants->fAngleL; - pants[i].fParamPants->fAngleL = pants[i].fParamPants->fAngleL0; // początkowy kąt dolnego ramienia - if ((sm = sm->ChildGet()) != nullptr) - { // jeśli dalej jest ślizg, można policzyć długość górnego ramienia - m = float4x4(*sm->GetMatrix()); // wystarczyłby wskaźnik, - // nie trzeba kopiować trzeba by uwzględnić macierz dolnego ramienia, żeby uzyskać kąt do poziomu... - pants[i].fParamPants->fHoriz += fabs(m(3)[1]); // różnica długości rzutów ramion na - // płaszczyznę podstawy (jedna dodatnia, druga ujemna) - pants[i].fParamPants->fLenU1 = hypot( m[3][1], m[3][2] ); // po osi OX nie potrzeba - // pants[i].fParamPants->pantu=acos((1.22*cos(pants[i].fParamPants->fAngleL)+0.535)/1.755); //górne ramię - // pants[i].fParamPants->fAngleU0=acos((1.176289*cos(pants[i].fParamPants->fAngleL)+0.54555075)/1.724482197); //górne ramię - pants[i].fParamPants->fAngleU0 = atan2( fabs(m[3][2]), fabs(m[3][1]) ); // początkowy kąt górnego ramienia, odczytany z modelu - // if (pants[i].fParamPants->fAngleU0fAngleU0+=M_PI; //gdyby w odwrotną stronę wyszło - // if (pants[i].fParamPants->fAngleU0<0) - // pants[i].fParamPants->fAngleU0=-pants[i].fParamPants->fAngleU0; - // if - // ((pants[i].fParamPants->fAngleU0<0.00)||(pants[i].fParamPants->fAngleU0>0.09)) //normalnie ok. 0.07 - // pants[i].fParamPants->fAngleU0=acos((pants[i].fParamPants->fLenL1*cos(pants[i].fParamPants->fAngleL)+pants[i].fParamPants->fHoriz)/pants[i].fParamPants->fLenU1); - pants[i].fParamPants->fAngleU = pants[i].fParamPants->fAngleU0; // początkowy kąt - // Ra: ze względu na to, że niektóre modele pantografów są zrąbane, ich mierzenie ma obecnie ograniczony sens - sm->ParentMatrix(&m); // pobranie macierzy transformacji pivota ślizgu względem wstawienia pojazdu - float det = Det(m); - if (std::fabs(det - 1.0) < 0.001) // dopuszczamy 1 promil błędu na skalowaniu ślizgu - { // skalowanie jest w normie, można pobrać wymiary z modelu - pants[i].fParamPants->fHeight = sm->MaxY(m); // przeliczenie maksimum wysokości wierzchołków względem macierzy - pants[i].fParamPants->fHeight -= m[3][1]; // odjęcie wysokości pivota ślizgu - pants[i].fParamPants->vPos.x = m[3][2]; // przy okazji odczytać z modelu pozycję w długości - // ErrorLog("Model OK: "+asModel+", - // height="+pants[i].fParamPants->fHeight); - // ErrorLog("Model OK: "+asModel+", - // pos.x="+pants[i].fParamPants->vPos.x); - } - else - { // gdy ktoś przesadził ze skalowaniem - pants[i].fParamPants->fHeight = 0.0; // niech będzie odczyt z pantfactors: - ErrorLog( - "Bad model: " + asModel + ", scale of " + sm->pName + " is " + std::to_string(100.0 * det) + "%", - logtype::model ); - } - } - } - } - else { - // brak ramienia - pants[ i ].fParamPants->fHeight = 0.0; // niech będzie odczyt z pantfactors: - ErrorLog( "Bad model: " + asFileName + " - missed submodel " + asAnimName, logtype::model ); - } - } - } - - else if( token == "animpantrd2prefix:" ) { - // prefiks ramion dolnych 2 - parser.getTokens(); parser >> token; - float4x4 m; // macierz do wyliczenia pozycji i wektora ruchu pantografu - TSubModel *sm; - if( pants ) { - for( int i = 0; i < iAnimType[ ANIM_PANTS ]; i++ ) { - // Winger 160204: wyszukiwanie max 2 patykow o nazwie str* - asAnimName = token + std::to_string( i + 1 ); - sm = GetSubmodelFromName( mdModel, asAnimName ); - pants[ i ].smElement[ 1 ] = sm; // jak NULL, to nie będzie animowany - if( sm ) { // w EP09 wywalało się tu z powodu NULL - sm->WillBeAnimated(); - if( pants[ i ].fParamPants->vPos.y == 0.0 ) { - // jeśli pierwsze ramię nie ustawiło tej wartości, próbować drugim - //!!!! docelowo zrobić niezależną animację ramion z każdej strony - m = float4x4( - *sm->GetMatrix()); // skopiowanie, bo będziemy mnożyć - m( 3 )[ 1 ] = - m[ 3 ][ 1 ] + 0.054; // w górę o wysokość ślizgu (na razie tak) - while( sm->Parent ) { - if( sm->Parent->GetMatrix() ) - m = *sm->Parent->GetMatrix() * m; - sm = sm->Parent; - } - pants[ i ].fParamPants->vPos.z = m[3][0]; // przesunięcie w bok (asymetria) - pants[ i ].fParamPants->vPos.y = m[3][1]; // przesunięcie w górę odczytane z modelu - } - } - else - ErrorLog( "Bad model: " + asFileName + " - missed submodel " + asAnimName, logtype::model ); // brak ramienia - } - } - } - - else if( token == "animpantrg1prefix:" ) { - // prefiks ramion górnych 1 - parser.getTokens(); parser >> token; - if( pants ) { - for( int i = 0; i < iAnimType[ ANIM_PANTS ]; i++ ) { - // Winger 160204: wyszukiwanie max 2 patykow o nazwie str* - asAnimName = token + std::to_string( i + 1 ); - pants[ i ].smElement[ 2 ] = GetSubmodelFromName( mdModel, asAnimName ); - if( pants[ i ].smElement[ 2 ] ) { - pants[ i ].smElement[ 2 ]->WillBeAnimated(); - } - else { - ErrorLog( "Bad model: " + asFileName + " - missed submodel " + asAnimName, logtype::model ); // brak ramienia - } - } - } - } - - else if( token == "animpantrg2prefix:" ) { - // prefiks ramion górnych 2 - parser.getTokens(); parser >> token; - if( pants ) { - for( int i = 0; i < iAnimType[ ANIM_PANTS ]; i++ ) { - // Winger 160204: wyszukiwanie max 2 patykow o nazwie str* - asAnimName = token + std::to_string( i + 1 ); - pants[ i ].smElement[ 3 ] = GetSubmodelFromName( mdModel, asAnimName ); - if( pants[ i ].smElement[ 3 ] ) { - pants[ i ].smElement[ 3 ]->WillBeAnimated(); - } - else { - ErrorLog( "Bad model: " + asFileName + " - missed submodel " + asAnimName, logtype::model ); // brak ramienia - } - } - } - } - - else if( token == "animpantslprefix:" ) { - // prefiks ślizgaczy - parser.getTokens(); parser >> token; - if( pants ) { - for( int i = 0; i < iAnimType[ ANIM_PANTS ]; i++ ) { - // Winger 160204: wyszukiwanie max 2 patykow o nazwie str* - asAnimName = token + std::to_string( i + 1 ); - pants[ i ].smElement[ 4 ] = GetSubmodelFromName( mdModel, asAnimName ); - if( pants[ i ].smElement[ 4 ] ) { - pants[ i ].smElement[ 4 ]->WillBeAnimated(); - pants[ i ].yUpdate = std::bind( &TDynamicObject::UpdatePant, this, std::placeholders::_1 ); - pants[ i ].fMaxDist = 300 * 300; // nie podnosić w większej odległości - pants[ i ].iNumber = i; - } - else { - ErrorLog( "Bad model: " + asFileName + " - missed submodel " + asAnimName, logtype::model ); // brak ramienia - } - } - } - } - - else if( token == "pantfactors:" ) { - // Winger 010304: - // parametry pantografow - double pant1x, pant2x, pant1h, pant2h; - parser.getTokens( 4, false ); - parser - >> pant1x - >> pant2x - >> pant1h // wysokość pierwszego ślizgu - >> pant2h;// wysokość drugiego ślizgu - if( pant1h > 0.5 ) { - pant1h = pant2h; // tu może być zbyt duża wartość - } - if (pant1x < 0 && - pant2x > 0) // pierwsza powinna być dodatnia, a druga ujemna - { - pant1x = -pant1x; - pant2x = -pant2x; - } - if( pants ) { - for( int i = 0; i < iAnimType[ ANIM_PANTS ]; ++i ) { - // przepisanie współczynników do pantografów (na razie nie będzie lepiej) - auto &pantograph { *pants[i].fParamPants }; - - pantograph.fAngleL = pantograph.fAngleL0; // początkowy kąt dolnego ramienia - pantograph.fAngleU = pantograph.fAngleU0; // początkowy kąt - // pants[i].fParamPants->PantWys=1.22*sin(pants[i].fParamPants->fAngleL)+1.755*sin(pants[i].fParamPants->fAngleU); - // //wysokość początkowa - // pants[i].fParamPants->PantWys=1.176289*sin(pants[i].fParamPants->fAngleL)+1.724482197*sin(pants[i].fParamPants->fAngleU); - // //wysokość początkowa - if( pantograph.fHeight == 0.0 ) // gdy jest nieprawdopodobna wartość (np. nie znaleziony ślizg) - { // gdy pomiary modelu nie udały się, odczyt podanych parametrów z MMD - pantograph.vPos.x = - i & 1 ? - pant2x : - pant1x; - pantograph.fHeight = - i & 1 ? - pant2h : - pant1h; // wysokość ślizgu jest zapisana w MMD - } - pantograph.PantWys = - pantograph.fLenL1 * sin( pantograph.fAngleL ) + - pantograph.fLenU1 * sin( pantograph.fAngleU ) + - pantograph.fHeight; // wysokość początkowa - // pants[i].fParamPants->vPos.y=panty-panth-pants[i].fParamPants->PantWys; //np. 4.429-0.097=4.332=~4.335 - if( pantograph.vPos.y == 0.0 ) { - // crude fallback, place the pantograph(s) atop of the vehicle-sized box - pantograph.vPos.y = MoverParameters->Dim.H - pantograph.fHeight - pantograph.PantWys; - } - // pants[i].fParamPants->vPos.z=0; //niezerowe dla pantografów asymetrycznych - pantograph.PantTraction = pantograph.PantWys; - // połowa szerokości ślizgu; jest w "Power: CSW=" - pantograph.fWidth = 0.5 * MoverParameters->EnginePowerSource.CollectorParameters.CSW; - - // create sound emitters for the pantograph - m_pantographsounds.emplace_back(); - } - } - } - - else if (token == "animpistonprefix:") { - // prefiks tłoczysk - na razie uzywamy modeli pantografów - parser.getTokens(1, false); parser >> token; - for( int i = 1; i <= 2; ++i ) - { - // asAnimName=str+i; - // smPatykird1[i-1]=mdModel->GetFromName(asAnimName.c_str()); - // smPatykird1[i-1]->WillBeAnimated(); - } - } - - else if( token == "animconrodprefix:" ) { - // prefiks korbowodów - na razie używamy modeli pantografów - parser.getTokens(); parser >> token; - for( int i = 1; i <= 2; i++ ) - { - // asAnimName=str+i; - // smPatykirg1[i-1]=mdModel->GetFromName(asAnimName.c_str()); - // smPatykirg1[i-1]->WillBeAnimated(); - } - } - - else if( token == "pistonfactors:" ) { - // Ra: parametry - // silnika parowego - // (tłoka) - /* //Ra: tymczasowo wyłączone ze względu na porządkowanie animacji - pantografów - pant1x=Parser->GetNextSymbol().ToDouble(); //kąt przesunięcia - dla - pierwszego tłoka - pant2x=Parser->GetNextSymbol().ToDouble(); //kąt przesunięcia - dla - drugiego tłoka - panty=Parser->GetNextSymbol().ToDouble(); //długość korby (r) - panth=Parser->GetNextSymbol().ToDouble(); //długoś korbowodu - (k) - */ - MoverParameters->EnginePowerSource.PowerType = - TPowerType::SteamPower; // Ra: po chamsku, ale z CHK nie działa - } - - else if( token == "animreturnprefix:" ) { - // prefiks drążka mimośrodowego - na razie używamy modeli pantografów - parser.getTokens(1, false); parser >> token; - for( int i = 1; i <= 2; i++ ) - { - // asAnimName=str+i; - // smPatykird2[i-1]=mdModel->GetFromName(asAnimName.c_str()); - // smPatykird2[i-1]->WillBeAnimated(); - } - } - - else if (token == "animexplinkprefix:"){ // animreturnprefix: - // prefiks jarzma - na razie używamy modeli pantografów - parser.getTokens(1, false); parser >> token; - for( int i = 1; i <= 2; i++ ) - { - // asAnimName=str+i; - // smPatykirg2[i-1]=mdModel->GetFromName(asAnimName.c_str()); - // smPatykirg2[i-1]->WillBeAnimated(); - } - } - - else if( token == "animpendulumprefix:" ) { - // prefiks wahaczy - parser.getTokens(); parser >> token; - asAnimName = ""; - for( int i = 1; i <= 4; ++i ) { - // McZapkie-050402: wyszukiwanie max 4 wahaczy o nazwie str* - asAnimName = token + std::to_string( i ); - smWahacze[ i - 1 ] = GetSubmodelFromName( mdModel, asAnimName ); - if( smWahacze[ i - 1 ] ) { - smWahacze[ i - 1 ]->WillBeAnimated(); - } - } - parser.getTokens(); parser >> token; - if( token == "pendulumamplitude:" ) { - parser.getTokens( 1, false ); - parser >> fWahaczeAmp; - } - } - - else if( token == "animslottedlever:" ) { - // lever with a slot, turned by a pin on the coupling rod (e.g. speedometer drive) - // parameters: submodel name, number of axle (from animwheelprefix) driving the coupling rod, crank radius [m], - // pin position relative to the lever axis [m] and crank angle [deg] for wheel angle 0, in local (Y, Z) plane of the lever - // angle is measured from Y axis towards Z axis, i.e. in the direction of rotation around X axis - slottedlever_data lever; - int axle { 1 }; - double crankradius { 0.0 }; - double crankangle { 0.0 }; - parser.getTokens( 6, false ); - parser - >> asAnimName - >> axle - >> crankradius - >> lever.pin.x - >> lever.pin.y - >> crankangle; - lever.submodel = GetSubmodelFromName( mdModel, asAnimName ); - if( lever.submodel != nullptr ) { - lever.submodel->WillBeAnimated(); - lever.axle = std::max( 0, axle - 1 ); - lever.crank = crankradius * glm::dvec2( std::cos( glm::radians( crankangle ) ), std::sin( glm::radians( crankangle ) ) ); - m_slottedlevers.emplace_back( lever ); - } - else { - ErrorLog( "Bad model: " + asFileName + " - missed submodel " + asAnimName, logtype::model ); - } - } - - else if( token == "animdoorprefix:" ) { - // nazwa animowanych drzwi - int i, j; - parser.getTokens(1, false); parser >> token; - for (i = 0, j = 0; i < ANIM_DOORS; ++i) - j += iAnimType[i]; // zliczanie wcześniejszych animacji - for (i = 0; i < iAnimType[ANIM_DOORS]; ++i) // liczba drzwi - { // NBMX wrzesien 2003: wyszukiwanie drzwi o nazwie str* - // ustalenie submodelu - asAnimName = token + std::to_string(i + 1); - pAnimations[ i + j ].smAnimated = GetSubmodelFromName( mdModel, asAnimName ); - if (pAnimations[i + j].smAnimated) - { //++iAnimatedDoors; - pAnimations[i + j].smAnimated->WillBeAnimated(); // wyłączenie optymalizacji transformu - pAnimations[i + j].iNumber = i + 1; // parzyste działają inaczej niż nieparzyste - bind_door_animation( pAnimations[ i + j ] ); // od razu zapinamy potrzebny typ animacji - pAnimations[i + j].fMaxDist = 300 * 300; // drzwi to z daleka widać -/* - // NOTE: no longer used - pAnimations[i + j].fSpeed = Random(150); // oryginalny koncept z DoorSpeedFactor - pAnimations[i + j].fSpeed = (pAnimations[i + j].fSpeed + 100) / 100; -*/ - } - } - } - - else if( token == "animdoor:" ) { - // own kind of animation of one door wing, in place of the one of the .fiz (eu07/maszyna#70): - // animdoor: { type: range: rangeout: } - // the keys left out keep the values of the .fiz. the wing still follows the door of its side - door_wings::wing_spec spec { - 0, - MoverParameters->Doors.type, - MoverParameters->Doors.range, - MoverParameters->Doors.range_out }; - auto error { door_wings::read_spec( parser, spec ) }; - if( error.empty() - && ( spec.number < 1 || spec.number > iAnimType[ ANIM_DOORS ] ) ) { - error = "no door wing " + std::to_string( spec.number ) + " among the door animations"; - } - if( false == error.empty() ) { - ErrorLog( "Bad model: " + asFileName + " - animdoor: " + error, logtype::model ); - } - else { - door_wings::store( m_doorwings, spec ); - // a wing animdoorprefix has found already gets the new kind of animation now; the ones it - // finds later get it then - auto const index { static_cast( std::accumulate( std::begin( iAnimType ), std::begin( iAnimType ) + ANIM_DOORS, 0 ) + spec.number - 1 ) }; - if( index < pAnimations.size() && pAnimations[ index ].yUpdate ) { - bind_door_animation( pAnimations[ index ] ); - } - } - } - - else if( token == "animstepprefix:" ) { - // animated doorstep submodel name prefix - int i, j; - parser.getTokens(1, false); parser >> token; - for (i = 0, j = 0; i < ANIM_DOORSTEPS; ++i) - j += iAnimType[i]; // zliczanie wcześniejszych animacji - for (i = 0; i < iAnimType[ANIM_DOORSTEPS]; ++i) // liczba drzwi - { // NBMX wrzesien 2003: wyszukiwanie drzwi o nazwie str* - // ustalenie submodelu - asAnimName = token + std::to_string(i + 1); - pAnimations[i + j].smAnimated = GetSubmodelFromName( mdModel, asAnimName ); - if (pAnimations[i + j].smAnimated) - { //++iAnimatedDoors; - pAnimations[i + j].smAnimated->WillBeAnimated(); // wyłączenie optymalizacji transformu - switch( MoverParameters->Doors.step_type ) - { // od razu zapinamy potrzebny typ animacji - case 1: // shift - pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdatePlatformTranslate, this, std::placeholders::_1 ); - break; - case 2: // rotate - pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdatePlatformRotate, this, std::placeholders::_1 ); - break; - default: - break; - } - pAnimations[i + j].iNumber = i + 1; // parzyste działają inaczej niż nieparzyste - pAnimations[i + j].fMaxDist = 150 * 150; // drzwi to z daleka widać -/* - // NOTE: no longer used - pAnimations[i + j].fSpeed = Random(150); // oryginalny koncept z DoorSpeedFactor - pAnimations[i + j].fSpeed = (pAnimations[i + j].fSpeed + 100) / 100; -*/ - } - } - } - - else if( token == "animmirrorprefix:" ) { - // animated mirror submodel name prefix - int i, j; - parser.getTokens( 1, false ); parser >> token; - for( i = 0, j = 0; i < ANIM_MIRRORS; ++i ) - j += iAnimType[ i ]; // zliczanie wcześniejszych animacji - for( i = 0; i < iAnimType[ ANIM_MIRRORS ]; ++i ) // liczba drzwi - { // NBMX wrzesien 2003: wyszukiwanie drzwi o nazwie str* - // ustalenie submodelu - asAnimName = token + std::to_string( i + 1 ); - pAnimations[ i + j ].smAnimated = GetSubmodelFromName( mdModel, asAnimName ); - if( pAnimations[ i + j ].smAnimated ) { - pAnimations[ i + j ].smAnimated->WillBeAnimated(); // wyłączenie optymalizacji transformu - // od razu zapinamy potrzebny typ animacji - auto const offset { pAnimations[ i + j ].smAnimated->offset() }; - pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdateMirror, this, std::placeholders::_1 ); - // we don't expect more than 2-4 mirrors, so it should be safe to store submodel location (front/rear) in the higher bits - // parzyste działają inaczej niż nieparzyste - pAnimations[ i + j ].iNumber = - ( ( pAnimations[ i + j ].smAnimated->offset().z > 0 ? - end::front : - end::rear ) << 4 ) - + i; - pAnimations[ i + j ].fMaxDist = 150 * 150; // drzwi to z daleka widać -/* - // NOTE: no longer used - pAnimations[i + j].fSpeed = Random(150); // oryginalny koncept z DoorSpeedFactor - pAnimations[i + j].fSpeed = (pAnimations[i + j].fSpeed + 100) / 100; -*/ - } - } - } - - else if (token == "animwiperprefix:") - { - parser.getTokens(1, false); - parser >> token; - TSubModel *sm; - if (wipers) - { - - for (int i = 0; i < iAnimType[ANIM_WIPERS]; i++) // zebranie wszystkich submodeli wycieraczek - { - dWiperPos.emplace_back(0.0); // dodajemy na koniec zeby sie miejsce tam zrobilo i nie bylo invalid addressow potem - - asAnimName = token + std::to_string(i + 1); - // element wycieraczki nr 1 - sm = GetSubmodelFromName(mdModel, asAnimName + "_p1"); - wipers[i].smElement[0] = sm; - if (sm) - { - wipers[i].smElement[0]->WillBeAnimated(); - // auto const offset{wipers[i].smElement[0]->offset()}; - } - - // element wycieraczki nr 2 - sm = GetSubmodelFromName(mdModel, asAnimName + "_p2"); - wipers[i].smElement[1] = sm; - if (sm) - { - wipers[i].smElement[1]->WillBeAnimated(); - // auto const offset{wipers[i].smElement[0]->offset()}; - } - - // element wycieraczki nr 3 - sm = GetSubmodelFromName(mdModel, asAnimName + "_p3"); - wipers[i].smElement[2] = sm; - if (sm) - { - wipers[i].smElement[2]->WillBeAnimated(); - // auto const offset{wipers[i].smElement[0]->offset()}; - } - wipers[i].yUpdate = std::bind(&TDynamicObject::UpdateWiper, this, std::placeholders::_1); - wipers[i].fMaxDist = 150 * 150; - wipers[i].iNumber = i; - } - } - } - - } while( token != "" - && token != "endmodels" ); - - if( false == MoverParameters->LoadAttributes.empty() ) { - // Ra: tu wczytywanie modelu ładunku jest w porządku - - // bieżąca ścieżka do tekstur to dynamic/... - Global.asCurrentTexturePath = asBaseDir; - - mdLoad = LoadMMediaFile_mdload( MoverParameters->LoadType.name ); - - // z powrotem defaultowa sciezka do tekstur - Global.asCurrentTexturePath = std::string( paths::textures ); - } - - } // models - - else if( token == "sounds:" ) { - // dzwieki - do { - token = ""; - parser.getTokens(); parser >> token; - if( token == "wheel_clatter:" ){ - // polozenia osi w/m srodka pojazdu - double dSDist; - parser.getTokens( 1, false ); - parser >> dSDist; - while( (token = parser.getToken()) != "" - && token != "end" ) { - // add another axle entry to the list - axle_sounds axle { - 0, - std::atof( token.c_str() ) * -1.0, // for axle locations negative value means ahead of centre but vehicle faces +Z in 'its' space - { sound_placement::external, static_cast( dSDist ) } }; - axle.clatter.deserialize( parser, sound_type::single ); - axle.clatter.owner( this ); - axle.clatter.offset( { 0, 0, axle.offset } ); - m_axlesounds.emplace_back( axle ); - } - // arrange the axles in case they're listed out of order - std::sort( - std::begin( m_axlesounds ), std::end( m_axlesounds ), - []( axle_sounds const &Left, axle_sounds const &Right ) { - return Left.offset > Right.offset; } ); - } - - else if( token == "engine:" - && MoverParameters->Power > 0 ) { - // plik z dzwiekiem silnika, mnozniki i ofsety amp. i czest. - m_powertrainsounds.engine.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); - m_powertrainsounds.engine.owner( this ); - - auto const amplitudedivisor = static_cast( MoverParameters->EngineType == TEngineType::DieselEngine ? 1 : - MoverParameters->EngineType == TEngineType::DieselElectric ? 1 : - MoverParameters->nmax * 60 + MoverParameters->Power * 3 ); - m_powertrainsounds.engine.m_amplitudefactor /= amplitudedivisor; - - } else if (token == "fakeengine:") { - m_powertrainsounds.fake_engine.deserialize(parser, sound_type::single); - m_powertrainsounds.fake_engine.owner(this); - } - - else if( token == "dieselinc:" ) { - // dzwiek przy wlazeniu na obroty woodwarda - m_powertrainsounds.engine_revving.deserialize( parser, sound_type::single, sound_parameters::range ); - m_powertrainsounds.engine_revving.owner( this ); - } - - else if( token == "oilpump:" ) { - m_powertrainsounds.oil_pump.deserialize( parser, sound_type::single ); - m_powertrainsounds.oil_pump.owner( this ); - } - - else if( token == "fuelpump:" ) { - m_powertrainsounds.fuel_pump.deserialize( parser, sound_type::single ); - m_powertrainsounds.fuel_pump.owner( this ); - } - - else if( token == "waterpump:" ) { - m_powertrainsounds.water_pump.deserialize( parser, sound_type::single ); - m_powertrainsounds.water_pump.owner( this ); - } - - else if( token == "waterheater:" ) { - m_powertrainsounds.water_heater.deserialize( parser, sound_type::single ); - m_powertrainsounds.water_heater.owner( this ); - } - - else if( token == "tractionmotor:" && MoverParameters->Power > 0 ) { - // plik z dzwiekiem silnika, mnozniki i ofsety amp. i czest. - sound_source motortemplate { sound_placement::external }; - motortemplate.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); - auto const amplitudedivisor { static_cast( MoverParameters->nmax * 60 + MoverParameters->Power * 3 ) }; - motortemplate.m_amplitudefactor /= amplitudedivisor; - motortemplate.owner( this ); - - auto &motors { m_powertrainsounds.motors }; - - if( true == motors.empty() ) { - // fallback for cases without specified motor locations, convert sound template to a single sound source - motors.emplace_back( motortemplate ); - } - else { - // apply configuration to all defined motors - for( auto &motor : motors ) { - // combine potential x- and y-axis offsets of the sound template with z-axis offsets of individual motors - auto motoroffset { motortemplate.offset() }; - motoroffset.z = motor.offset().z; - motor = motortemplate; - motor.offset( motoroffset ); - // apply randomized playback start offset for each instance, to reduce potential reverb with identical nearby sources - motor.start( LocalRandom( 0.0, 1.0 ) ); - } - } - } - - else if( token == "tractionacmotor:" && MoverParameters->Power > 0 ) { - // plik z dzwiekiem silnika, mnozniki i ofsety amp. i czest. - sound_source motortemplate { sound_placement::external }; - motortemplate.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); - motortemplate.owner( this ); - - auto &motors { m_powertrainsounds.acmotors }; - - if( true == motors.empty() ) { - // fallback for cases without specified motor locations, convert sound template to a single sound source - motors.emplace_back( motortemplate ); - } - else { - // apply configuration to all defined motors - for( auto &motor : motors ) { - // combine potential x- and y-axis offsets of the sound template with z-axis offsets of individual motors - auto motoroffset { motortemplate.offset() }; - motoroffset.z = motor.offset().z; - motor = motortemplate; - motor.offset( motoroffset ); - // apply randomized playback start offset for each instance, to reduce potential reverb with identical nearby sources - motor.start( LocalRandom( 0.0, 1.0 ) ); - } - } - } - - else if( token == "motorblower:" ) { - - sound_source blowertemplate { sound_placement::engine }; - blowertemplate.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); - blowertemplate.owner( this ); - - auto const amplitudedivisor { static_cast( - MoverParameters->MotorBlowers[ end::front ].speed > 0 ? MoverParameters->MotorBlowers[ end::front ].speed * MoverParameters->nmax * 60 + MoverParameters->Power * 3 : - blowertemplate.has_bookends() ? 1 : // NOTE: for motorblowers with fixed speed if the sound has defined bookends we skip revolutions-based part of frequency/volume adjustments - MoverParameters->MotorBlowers[ end::front ].speed * -1 ) }; - blowertemplate.m_amplitudefactor /= amplitudedivisor; - blowertemplate.m_frequencyfactor /= amplitudedivisor; - - if( true == m_powertrainsounds.motors.empty() ) { - // fallback for cases without specified motor locations, convert sound template to a single sound source - m_powertrainsounds.motorblowers.emplace_back( blowertemplate ); - } - else { - // apply configuration to all defined motor blowers - for( auto &blower : m_powertrainsounds.motorblowers ) { - // combine potential x- and y-axis offsets of the sound template with z-axis offsets of individual blowers - auto bloweroffset { blowertemplate.offset() }; - bloweroffset.z = blower.offset().z; - blower = blowertemplate; - blower.offset( bloweroffset ); - // apply randomized playback start offset for each instance, to reduce potential reverb with identical nearby sources - blower.start( LocalRandom( 0.0, 1.0 ) ); - } - } - } - - else if( token == "inverter:" ) { - // plik z dzwiekiem wentylatora, mnozniki i ofsety amp. i czest. - m_powertrainsounds.inverter.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); - m_powertrainsounds.inverter.owner( this ); - } - - else if( token == "ventilator:" ) { - // plik z dzwiekiem wentylatora, mnozniki i ofsety amp. i czest. - m_powertrainsounds.rsWentylator.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); - m_powertrainsounds.rsWentylator.owner( this ); - - m_powertrainsounds.rsWentylator.m_amplitudefactor /= MoverParameters->RVentnmax; - m_powertrainsounds.rsWentylator.m_frequencyfactor /= MoverParameters->RVentnmax; - } - - else if( token == "radiatorfan1:" ) { - // primary circuit radiator fan - m_powertrainsounds.radiator_fan.deserialize( parser, sound_type::single ); - m_powertrainsounds.radiator_fan.owner( this ); - } - - else if( token == "radiatorfan2" ) { - // auxiliary circuit radiator fan - m_powertrainsounds.radiator_fan_aux.deserialize( parser, sound_type::single ); - m_powertrainsounds.radiator_fan_aux.owner( this ); - } - - else if( token == "transmission:" ) { - // plik z dzwiekiem, mnozniki i ofsety amp. i czest. - // NOTE, fixed default parameters, legacy system leftover - auto &sound { m_powertrainsounds.transmission }; - sound.m_amplitudefactor = 0.029; - sound.m_amplitudeoffset = 0.1; - sound.m_frequencyfactor = 0.005; - sound.m_frequencyoffset = 1.0; - - sound.deserialize( parser, sound_type::single, sound_parameters::range ); - sound.owner( this ); - } - - else if( token == "brakesound:" ) { - // hamowanie zwykle: - rsBrake.deserialize( parser, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency ); - rsBrake.owner( this ); - // NOTE: can't pre-calculate amplitude normalization based on max brake force, as this varies depending on vehicle speed - rsBrake.m_frequencyfactor /= 1 + MoverParameters->Vmax; - } - - else if( token == "brake:" ) { - // plik z piskiem hamulca, mnozniki i ofsety amplitudy. - rsPisk.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude ); - rsPisk.owner( this ); - - if( rsPisk.m_amplitudefactor > 10.f ) { - // HACK: convert old style activation point threshold to the new, regular amplitude adjustment system - rsPisk.m_amplitudefactor = 1.f; - rsPisk.m_amplitudeoffset = 0.f; - } - rsPisk.m_amplitudeoffset *= ( 105.f - Random( 10.f ) ) / 100.f; - } - - else if( token == "brakecylinderinc:" ) { - // brake cylinder pressure increase sounds - m_brakecylinderpistonadvance.deserialize( parser, sound_type::single ); - m_brakecylinderpistonadvance.owner( this ); - } - - else if( token == "brakecylinderdec:" ) { - // brake cylinder pressure decrease sounds - m_brakecylinderpistonrecede.deserialize( parser, sound_type::single ); - m_brakecylinderpistonrecede.owner( this ); - } - - else if (token == "epbrakeinc:") { - // brake cylinder pressure increase sounds - m_epbrakepressureincrease.deserialize(parser, sound_type::single); - m_epbrakepressureincrease.owner(this); - } - - else if (token == "epbrakedec:") { - // brake cylinder pressure decrease sounds - m_epbrakepressuredecrease.deserialize(parser, sound_type::single); - m_epbrakepressuredecrease.owner(this); - } - - else if( token == "emergencybrake:" ) { - // emergency brake sound - m_emergencybrake.deserialize( parser, sound_type::single ); - m_emergencybrake.owner( this ); - } - - else if( token == "brakeacc:" ) { - // plik z przyspieszaczem (upust po zlapaniu hamowania) - sBrakeAcc.deserialize( parser, sound_type::single ); - sBrakeAcc.owner( this ); - - bBrakeAcc = true; - } - - else if( token == "unbrake:" ) { - // plik z piskiem hamulca, mnozniki i ofsety amplitudy. - rsUnbrake.m_amplitudefactor = 20.0f; - rsUnbrake.deserialize( parser, sound_type::single, sound_parameters::range ); - rsUnbrake.owner( this ); - } - // spring brake sounds - else if( token == "springbrake:" ) { - m_springbrakesounds.activate.deserialize( parser, sound_type::single ); - m_springbrakesounds.activate.owner( this ); - } - else if( token == "springbrakeoff:" ) { - m_springbrakesounds.release.deserialize( parser, sound_type::single ); - m_springbrakesounds.release.owner( this ); - } - - else if( token == "derail:" ) { - // dzwiek przy wykolejeniu - rsDerailment.deserialize( parser, sound_type::single, sound_parameters::range ); - rsDerailment.owner( this ); - } - - else if( token == "curve:" ) { - rscurve.deserialize( parser, sound_type::single, sound_parameters::range ); - rscurve.owner( this ); - } - - else if( token == "horn1:" ) { - // pliki z trabieniem - sHorn1.deserialize( parser, sound_type::multipart, sound_parameters::range ); - sHorn1.owner( this ); - } - - else if( token == "horn2:" ) { - // pliki z trabieniem wysokoton. - sHorn2.deserialize( parser, sound_type::multipart, sound_parameters::range ); - sHorn2.owner( this ); - // TBD, TODO: move horn selection to ai config file - if( iHornWarning ) { - iHornWarning = 2; // numer syreny do użycia po otrzymaniu sygnału do jazdy - } - } - - else if( token == "horn3:" ) { - sHorn3.deserialize( parser, sound_type::multipart, sound_parameters::range ); - sHorn3.owner( this ); - } - - else if( token == "pantographup:" ) { - // pliki dzwiekow pantografow - sound_source pantographup { sound_placement::external }; - pantographup.deserialize( parser, sound_type::single ); - pantographup.owner( this ); - for( auto &pantograph : m_pantographsounds ) { - pantograph.sPantUp = pantographup; - } - } - - else if( token == "pantographdown:" ) { - // pliki dzwiekow pantografow - sound_source pantographdown { sound_placement::external }; - pantographdown.deserialize( parser, sound_type::single ); - pantographdown.owner( this ); - for( auto &pantograph : m_pantographsounds ) { - pantograph.sPantDown = pantographdown; - } - } - - else if( token == "compressor:" ) { - // pliki ze sprezarka - sCompressor.deserialize( parser, sound_type::multipart, sound_parameters::range ); - sCompressor.owner( this ); - } - - else if( token == "compressoridle:" ) { - // pliki ze sprezarka - sCompressorIdle.deserialize( parser, sound_type::multipart, sound_parameters::range ); - sCompressorIdle.owner( this ); - } - - else if( token == "converter:" ) { - // pliki z przetwornica - sConverter.deserialize( parser, sound_type::multipart, sound_parameters::range ); - sConverter.owner( this ); - } - - // Dzwiek wentylatora rezystora hamowania - else if (token == "brakingresistorventilator:") - { - sBRVent.deserialize(parser, sound_type::multipart, sound_parameters::range); - sBRVent.owner(this); - } - - else if( token == "heater:" ) { - // train heating device - sHeater.deserialize( parser, sound_type::single ); - sHeater.owner( this ); - } - - else if( token == "battery:" ) { - // train heating device - m_batterysound.deserialize( parser, sound_type::single ); - m_batterysound.owner( this ); - } - - else if( token == "turbo:" ) { - // pliki z turbogeneratorem - m_powertrainsounds.engine_turbo.deserialize( parser, sound_type::multipart, sound_parameters::range ); - m_powertrainsounds.engine_turbo.owner( this ); - m_powertrainsounds.engine_turbo.gain( 0 ); - } - - else if( token == "small-compressor:" ) { - // pliki z przetwornica - sSmallCompressor.deserialize( parser, sound_type::multipart, sound_parameters::range ); - sSmallCompressor.owner( this ); - } - - else if( token == "departuresignal:" ) { - // pliki z sygnalem odjazdu - sound_source soundtemplate { sound_placement::general, 25.f }; - soundtemplate.deserialize( parser, sound_type::multipart, sound_parameters::range ); - soundtemplate.owner( this ); - for( auto &speaker : m_doorspeakers ) { - speaker.departure_signal = soundtemplate; - speaker.departure_signal.offset( speaker.offset ); - } - } - - else if( token == "dooropen:" ) { - sound_source soundtemplate { sound_placement::general }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &door : m_doorsounds ) { - // apply configuration to all defined doors, but preserve their individual offsets - auto const dooroffset { door.rsDoorOpen.offset() }; - door.rsDoorOpen = soundtemplate; - door.rsDoorOpen.offset( dooroffset ); - } - } - - else if( token == "doorclose:" ) { - sound_source soundtemplate { sound_placement::general }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &door : m_doorsounds ) { - // apply configuration to all defined doors, but preserve their individual offsets - auto const dooroffset { door.rsDoorClose.offset() }; - door.rsDoorClose = soundtemplate; - door.rsDoorClose.offset( dooroffset ); - } - } - - else if( token == "doorlock:" ) { - sound_source soundtemplate { sound_placement::general }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &door : m_doorsounds ) { - // apply configuration to all defined doors, but preserve their individual offsets - auto const dooroffset { door.lock.offset() }; - door.lock = soundtemplate; - door.lock.offset( dooroffset ); - } - } - - else if( token == "doorunlock:" ) { - sound_source soundtemplate { sound_placement::general }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &door : m_doorsounds ) { - // apply configuration to all defined doors, but preserve their individual offsets - auto const dooroffset { door.unlock.offset() }; - door.unlock = soundtemplate; - door.unlock.offset( dooroffset ); - } - } - - else if( token == "doorstepopen:" ) { - sound_source soundtemplate { sound_placement::general }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &door : m_doorsounds ) { - // apply configuration to all defined doors, but preserve their individual offsets - auto const dooroffset { door.step_open.offset() }; - door.step_open = soundtemplate; - door.step_open.offset( dooroffset ); - } - } - - else if( token == "mirroropen:" || token == "mirrorclose:" ) { - sound_source soundtemplate { sound_placement::general }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &mirror : m_mirrorsounds ) { - // apply configuration to all defined mirrors, but preserve their individual offsets - auto &sound { token == "mirroropen:" ? mirror.unfold : mirror.fold }; - auto const mirroroffset { sound.offset() }; - sound = soundtemplate; - sound.offset( mirroroffset ); - } - } - - else if( token == "doorstepclose:" ) { - sound_source soundtemplate { sound_placement::general }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &door : m_doorsounds ) { - // apply configuration to all defined doors, but preserve their individual offsets - auto const dooroffset { door.step_close.offset() }; - door.step_close = soundtemplate; - door.step_close.offset( dooroffset ); - } - } - - else if( token == "doorpermit:" ) { - sound_source soundtemplate { sound_placement::general }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &door : m_doorsounds ) { - // apply configuration to all defined doors, but preserve their individual offsets - auto const dooroffset { door.permit_granted.offset() }; - door.permit_granted = soundtemplate; - door.permit_granted.offset( dooroffset ); - } - } - - else if( token == "unloading:" ) { - m_exchangesounds.unloading.range( MoverParameters->Dim.L * 0.5f * -1 ); - m_exchangesounds.unloading.deserialize( parser, sound_type::single ); - m_exchangesounds.unloading.owner( this ); - } - - else if( token == "loading:" ) { - m_exchangesounds.loading.range( MoverParameters->Dim.L * 0.5f * -1 ); - m_exchangesounds.loading.deserialize( parser, sound_type::single ); - m_exchangesounds.loading.owner( this ); - } - - else if( token == "sand:" ) { - sSand.deserialize( parser, sound_type::multipart, sound_parameters::range ); - sSand.owner( this ); - } - - else if( token == "releaser:" ) { - // pliki z odluzniaczem - sReleaser.deserialize( parser, sound_type::multipart, sound_parameters::range ); - sReleaser.owner( this ); - } - - else if( token == "outernoise:" ) { - // szum podczas jazdy: - sound_source noisetemplate{ sound_placement::external, EU07_SOUND_RUNNINGNOISECUTOFFRANGE }; - noisetemplate.deserialize( parser, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency, MoverParameters->Vmax ); - noisetemplate.owner( this ); - - noisetemplate.m_amplitudefactor /= 1 + MoverParameters->Vmax; - noisetemplate.m_frequencyfactor /= 1 + MoverParameters->Vmax; -#ifdef EU07_SOUND_BOGIESOUNDS - if( true == m_bogiesounds.empty() ) { - // fallback for cases without specified noise locations, convert sound template to a single sound source - m_bogiesounds.emplace_back( noisetemplate ); - } - else { - // apply configuration to all defined bogies - for( auto &bogie : m_bogiesounds ) { - // combine potential x- and y-axis offsets of the sound template with z-axis offsets of individual motors - auto bogieoffset{ noisetemplate.offset() }; - bogieoffset.z = bogie.offset().z; - bogie = noisetemplate; - bogie.offset( bogieoffset ); - } - } - // apply randomized playback start offset for each bogie, to reduce potential reverb with identical nearby sources - auto bogieidx( 0 ); - for( auto &bogie : m_bogiesounds ) { - bogie.start( ( - bogieidx % 2 ? - LocalRandom( 0.0, 30.0 ) : - LocalRandom( 50.0, 80.0 ) ) - * 0.01 ); - ++bogieidx; - } -#else - m_outernoise = noisetemplate; - // apply randomized playback start offset, to reduce potential reverb with identical nearby sources - m_outernoise.start( Random( 0.0, 80.0 ) * 0.01 ); -#endif - } - - else if( token == "wheelflat:" ) { - // szum podczas jazdy: - m_wheelflat.deserialize( parser, sound_type::single, sound_parameters::frequency ); - m_wheelflat.owner( this ); - } - - else if(token == "announcements:") { - // announcement sounds - // content provided as "key: value" pairs together enclosed in "{}" - // value can be optionally set of values enclosed in "[]" in which case one value will be picked randomly - std::unordered_map const announcements = { - { "near_stop:", announcement_t::approaching }, - { "stop:", announcement_t::current }, - { "next_stop:", announcement_t::next }, - { "destination:", announcement_t::destination }, - { "chime:", announcement_t::chime } }; - while( (token = parser.getToken()) != "" - && token != "}" ) { - if( token.back() == ':' ) { - - if( token == "soundproofing:" ) { - // custom soundproofing in format [ p1, p2, p3, p4, p5, p6 ] - parser.getTokens( 6, false, "\n\r\t ,;[]" ); - std::array soundproofing; - parser - >> soundproofing[ 0 ] - >> soundproofing[ 1 ] - >> soundproofing[ 2 ] - >> soundproofing[ 3 ] - >> soundproofing[ 4 ] - >> soundproofing[ 5 ]; - for( auto & soundproofingelement : soundproofing ) { - if( soundproofingelement != -1.f ) { - soundproofingelement = std::sqrt( std::clamp( soundproofingelement, 0.f, 1.f ) ); - } - } - m_pasystem.soundproofing = soundproofing; - continue; - } - - auto const lookup { announcements.find( token ) }; - auto const announcementtype { ( - lookup != announcements.end() ? - lookup->second : - announcement_t::idle ) }; - // NOTE: we retrieve key value for all keys, not just recognized ones - if( announcementtype == announcement_t::idle ) { - token = parser.getToken(); - continue; - } -/* - auto announcementsound { deserialize_random_set( parser ) }; - replace_slashes( announcementsound ); -*/ - sound_source soundtemplate { sound_placement::engine }; // NOTE: sound range gets filled by pa system - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - m_pasystem.announcements[ static_cast( announcementtype ) ] = soundtemplate; - } - } - // set provided custom soundproofing to assigned sounds (for sounds without their own custom soundproofing) - if( m_pasystem.soundproofing ) { - for( auto &announcement : m_pasystem.announcements ) { - if( !announcement.soundproofing() ) { - announcement.soundproofing() = m_pasystem.soundproofing; - } - } - } - } - - } while( token != "" - && token != "endsounds" ); - - } // sounds: - - else if( token == "locations:" ) { - do { - token = ""; - parser.getTokens(); parser >> token; - - if( token == "doors:" ) { - // a list of pairs: offset along vehicle's z-axis and sides on which the door is present; followed with "end" - while( (token = parser.getToken()) != "" - && token != "end" ) { - // vehicle faces +Z in 'its' space, for door locations negative value means ahead of centre - auto const offset { std::atof( token.c_str() ) * -1.f }; - // recognized side specifications are "right", "left" and "both" - auto const sides { parser.getToken() }; - // NOTE: we skip setting owner of the sounds, it'll be done during individual sound deserialization - door_sounds door; - // add entries to the list: - if( sides == "both" - || sides == "left" ) { - // left... - auto const location { glm::vec3 { MoverParameters->Dim.W * 0.5f, MoverParameters->Dim.H * 0.5f, offset } }; - door.placement = side::left; - door.rsDoorClose.offset( location ); - door.rsDoorOpen.offset( location ); - door.lock.offset( location ); - door.unlock.offset( location ); - door.step_close.offset( location ); - door.step_open.offset( location ); - door.permit_granted.offset( location ); - m_doorsounds.emplace_back( door ); - } - if( sides == "both" - || sides == "right" ) { - // ...and right - auto const location { glm::vec3 { MoverParameters->Dim.W * -0.5f, 2.f, offset } }; - door.placement = side::right; - door.rsDoorClose.offset( location ); - door.rsDoorOpen.offset( location ); - door.lock.offset( location ); - door.unlock.offset( location ); - door.step_close.offset( location ); - door.step_open.offset( location ); - door.permit_granted.offset( location ); - m_doorsounds.emplace_back( door ); - } - m_doorspeakers.emplace_back( - doorspeaker_sounds { - { 0.f, 3.f, offset }, - {} } ); - } - } - - else if( token == "mirrors:" ) { - // a list of offsets along vehicle's z-axis of the mirror pairs, one at each cab; followed with "end" - while( (token = parser.getToken()) != "" - && token != "end" ) { - // vehicle faces +Z in 'its' space, as for the doors negative value means ahead of centre - auto const offset { std::atof( token.c_str() ) * -1.f }; - mirror_sounds mirror; - mirror.end = offset >= 0.f ? end::front : end::rear; - for( auto const mirrorside : { side::left, side::right } ) { - auto const location { glm::vec3 { - MoverParameters->Dim.W * ( mirrorside == side::left ? 0.5f : -0.5f ), - MoverParameters->Dim.H * 0.5f, - offset } }; - mirror.placement = mirrorside; - mirror.unfold.offset( location ); - mirror.fold.offset( location ); - m_mirrorsounds.emplace_back( mirror ); - } - } - } - - else if( token == "tractionmotors:" ) { - // a list of offsets along vehicle's z-axis; followed with "end" - while( (token = parser.getToken()) != "" - && token != "end" ) { - // vehicle faces +Z in 'its' space, for motor locations negative value means ahead of centre - auto const offset { std::atof( token.c_str() ) * -1.f }; - // NOTE: we skip setting owner of the sounds, it'll be done during individual sound deserialization - sound_source motor { sound_placement::external }; // generic traction motor sounds - sound_source acmotor { sound_placement::external }; // inverter-specific traction motor sounds - sound_source motorblower { sound_placement::engine }; // associated motor blowers - // add entry to the list - auto const location { glm::vec3 { 0.f, 0.f, offset } }; - motor.offset( location ); - m_powertrainsounds.motors.emplace_back( motor ); - acmotor.offset( location ); - m_powertrainsounds.acmotors.emplace_back( acmotor ); - motorblower.offset( location ); - m_powertrainsounds.motorblowers.emplace_back( motorblower ); - } - } - - else if( token == "bogies:" ) { - // a list of offsets along vehicle's z-axis; followed with "end" - while( (token = parser.getToken()) != "" - && token != "end" ) { - // vehicle faces +Z in 'its' space, for bogie locations negative value means ahead of centre - auto const offset { std::atof( token.c_str() ) * -1.f }; - // NOTE: we skip setting owner of the sounds, it'll be done during individual sound deserialization - sound_source bogienoise { sound_placement::external, EU07_SOUND_RUNNINGNOISECUTOFFRANGE }; - // add entry to the list - auto const location { glm::vec3 { 0.f, 0.f, offset } }; - bogienoise.offset( location ); -#ifdef EU07_SOUND_BOGIESOUNDS - m_bogiesounds.emplace_back( bogienoise ); -#endif - } - } - - } while( token != "" - && token != "endlocations" ); - - } // locations: - - else if( token == "internaldata:" ) { - // dalej nie czytaj - do { - // zbieranie informacji o kabinach - token = ""; - parser.getTokens(); parser >> token; - if( token == "cab0model:" ) { - parser.getTokens(); parser >> token; - if( token != "none" ) { iCabs |= 0x2; } - } - else if( token == "cab1model:" ) { - parser.getTokens(); parser >> token; - if( token != "none" ) { iCabs |= 0x1; } - } - else if( token == "cab2model:" ) { - parser.getTokens(); parser >> token; - if( token != "none" ) { iCabs |= 0x4; } - } - // engine sounds - else if( token == "ignition:" ) { - // odpalanie silnika - m_powertrainsounds.engine_ignition.deserialize( parser, sound_type::single ); - m_powertrainsounds.engine_ignition.owner( this ); - } else if (token == "shutdown:") { - m_powertrainsounds.engine_shutdown.deserialize(parser, sound_type::single); - m_powertrainsounds.engine_shutdown.owner(this); - } else if( token == "engageslippery:" ) { - // tarcie tarcz sprzegla: - m_powertrainsounds.rsEngageSlippery.deserialize( parser, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency ); - m_powertrainsounds.rsEngageSlippery.owner( this ); - - m_powertrainsounds.rsEngageSlippery.m_frequencyfactor /= 1 + MoverParameters->nmax; - } - - // dzwieki wycieraczkuf - else if (token == "wiperfrompark:") - { - sWiperFromPark.deserialize(parser, sound_type::single); - sWiperFromPark.owner(this); - } - else if (token == "wipertopark:") - { - sWiperToPark.deserialize(parser, sound_type::single); - sWiperToPark.owner(this); - } - - else if (token == "retarder:") { - m_powertrainsounds.retarder.deserialize(parser, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency); - m_powertrainsounds.retarder.owner(this); - } - else if( token == "linebreakerclose:" ) { - m_powertrainsounds.linebreaker_close.deserialize( parser, sound_type::single ); - m_powertrainsounds.linebreaker_close.owner( this ); - } - else if( token == "linebreakeropen:" ) { - m_powertrainsounds.linebreaker_open.deserialize( parser, sound_type::single ); - m_powertrainsounds.linebreaker_open.owner( this ); - } - else if( token == "relay:" ) { - // styczniki itp: - m_powertrainsounds.motor_relay.deserialize( parser, sound_type::single ); - m_powertrainsounds.motor_relay.owner( this ); - } - else if( token == "shuntfield:" ) { - // styczniki itp: - m_powertrainsounds.motor_shuntfield.deserialize( parser, sound_type::single ); - m_powertrainsounds.motor_shuntfield.owner( this ); - } - else if( token == "wejscie_na_bezoporow:" ) { - // hunter-111211: wydzielenie wejscia na bezoporowa i na drugi uklad do pliku - m_powertrainsounds.dsbWejscie_na_bezoporow.deserialize( parser, sound_type::single ); - m_powertrainsounds.dsbWejscie_na_bezoporow.owner( this ); - } - // przekazniki od kierunku jazdy - else if (token == "directionrelay_d:") { - // przekaznik od kierunku jazdy do przodu - sDirectionRelayD.deserialize(parser, sound_type::single); - sDirectionRelayD.owner(this); - } - else if (token == "directionrelay_r:") { - // przekaznik od kierunku jazdy do tylu - sDirectionRelayR.deserialize(parser, sound_type::single); - sDirectionRelayR.owner(this); - } - else if (token == "directionrelay_n:") - { - // przekaznik od kierunku jazdy do tylu - sDirectionRelayN.deserialize(parser, sound_type::single); - sDirectionRelayN.owner(this); - } - else if( token == "wejscie_na_drugi_uklad:" ) { - m_powertrainsounds.motor_parallel.deserialize( parser, sound_type::single ); - m_powertrainsounds.motor_parallel.owner( this ); - } - else if( token == "pneumaticrelay:" ) { - // wylaczniki pneumatyczne: - dsbPneumaticRelay.deserialize( parser, sound_type::single ); - dsbPneumaticRelay.owner( this ); - } - else if( token == "slipperysound:" ) { - // sanie: - rsSlippery.deserialize( parser, sound_type::single, sound_parameters::amplitude ); - rsSlippery.owner( this ); - - rsSlippery.m_amplitudefactor /= 1 + MoverParameters->Vmax; - } - // coupler sounds - else if( token == "couplerattach:" ) { - sound_source soundtemplate { sound_placement::external }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.attach_coupler = soundtemplate; - } - } - else if( token == "brakehoseattach:" ) { - // laczenie: - sound_source soundtemplate { sound_placement::external }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.attach_brakehose = soundtemplate; - } - } - else if( token == "mainhoseattach:" ) { - // laczenie: - sound_source soundtemplate{ sound_placement::external }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.attach_mainhose = soundtemplate; - } - } - else if( token == "controlattach:" ) { - // laczenie: - sound_source soundtemplate{ sound_placement::external }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.attach_control = soundtemplate; - } - } - else if( token == "gangwayattach:" ) { - // laczenie: - sound_source soundtemplate{ sound_placement::external }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.attach_gangway = soundtemplate; - } - } - else if( token == "heatingattach:" ) { - // laczenie: - sound_source soundtemplate{ sound_placement::external }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.attach_heating = soundtemplate; - } - } - else if( token == "couplerdetach:" ) { - // rozlaczanie: - sound_source soundtemplate { sound_placement::external }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.detach_coupler = soundtemplate; - } - } - else if( token == "brakehosedetach:" ) { - // rozlaczanie: - sound_source soundtemplate { sound_placement::external }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.detach_brakehose = soundtemplate; - } - } - else if( token == "mainhosedetach:" ) { - // rozlaczanie: - sound_source soundtemplate{ sound_placement::external }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.detach_mainhose = soundtemplate; - } - } - else if( token == "controldetach:" ) { - // rozlaczanie: - sound_source soundtemplate{ sound_placement::external }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.detach_control = soundtemplate; - } - } - else if( token == "gangwaydetach:" ) { - // rozlaczanie: - sound_source soundtemplate{ sound_placement::external }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.detach_gangway = soundtemplate; - } - } - else if( token == "heatingdetach:" ) { - // rozlaczanie: - sound_source soundtemplate{ sound_placement::external }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.detach_heating = soundtemplate; - } - } - else if( token == "couplerstretch:" ) { - // coupler stretching - sound_source couplerstretch { sound_placement::external }; - couplerstretch.deserialize( parser, sound_type::single ); - couplerstretch.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.dsbCouplerStretch = couplerstretch; - } - } - else if( token == "couplerstretch_loud:" ) { - // coupler stretching - sound_source couplerstretch { sound_placement::external }; - couplerstretch.deserialize( parser, sound_type::single ); - couplerstretch.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.dsbCouplerStretch_loud = couplerstretch; - } - } - else if( token == "bufferclamp:" ) { - // buffers hitting one another - sound_source bufferclash { sound_placement::external }; - bufferclash.deserialize( parser, sound_type::single ); - bufferclash.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.dsbBufferClamp = bufferclash; - } - } - else if( token == "bufferclamp_loud:" ) { - // buffers hitting one another - sound_source bufferclash { sound_placement::external }; - bufferclash.deserialize( parser, sound_type::single ); - bufferclash.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.dsbBufferClamp_loud = bufferclash; - } - } - else if( token == "coupleradapterattach:" ) { - // laczenie: - sound_source adapterattach { sound_placement::external }; - adapterattach.deserialize( parser, sound_type::single ); - adapterattach.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.dsbAdapterAttach = adapterattach; - } - } - else if( token == "coupleradapterremove:" ) { - // rozlaczanie: - sound_source adapterremove { sound_placement::external }; - adapterremove.deserialize( parser, sound_type::single ); - adapterremove.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.dsbAdapterRemove = adapterremove; - } - } - else if( token == "startjolt:" ) { - // movement start jolt - m_startjolt.deserialize( parser, sound_type::single ); - m_startjolt.owner( this ); - } - - else if (token == "mechspring:") - { - // parametry bujania kamery: - double ks, kd; - parser.getTokens(2, false); - parser - >> ks - >> kd; - ShakeSpring.Init(ks, kd); - parser.getTokens(6, false); - parser - >> BaseShake.jolt_scale.x - >> BaseShake.jolt_scale.y - >> BaseShake.jolt_scale.z - >> BaseShake.jolt_limit - >> BaseShake.angle_scale.x - >> BaseShake.angle_scale.z; - } - else if( token == "enginespring:" ) { - parser.getTokens( 5, false ); - parser - >> EngineShake.scale - >> EngineShake.fadein_offset - >> EngineShake.fadein_factor - >> EngineShake.fadeout_offset - >> EngineShake.fadeout_factor; - // offsets values are provided as rpm for convenience - EngineShake.fadein_offset /= 60.f; - EngineShake.fadeout_offset /= 60.f; - } - else if( token == "huntingspring:" ) { - parser.getTokens( 4, false ); - parser - >> HuntingShake.scale - >> HuntingShake.frequency - >> HuntingShake.fadein_begin - >> HuntingShake.fadein_end; - } - - else if( token == "soundproofing:" ) { - for( auto &soundproofingtable : m_soundproofing ) { - for( auto &soundproofingelement : soundproofingtable ) { - auto const value { parser.getToken( false ) }; - if( value != -1.f ) { - soundproofingelement = std::sqrt( std::clamp( value, 0.f, 1.f ) ); - } - } - } - } - - else if( token == "jointcabs:" ) { - parser.getTokens(); - parser >> JointCabs; - } - - else if( token == "cablight:" ) { - parser.getTokens( 3, false ); // low power light, ignore - parser.getTokens( 3, false ); // base light - parser - >> InteriorLight.r - >> InteriorLight.g - >> InteriorLight.b; - InteriorLight = glm::clamp( InteriorLight / 255.f, glm::vec3( 0.f ), glm::vec3( 1.f ) ); - parser.getTokens( 3, false ); // dimmed light, ignore - } - - else if( token == "pydestinationsign:" ) { - DestinationSign.deserialize( parser ); - // supply vehicle folder as script path if none is provided - if( false == DestinationSign.script.empty() - && substr_path(DestinationSign.script).empty() ) { - DestinationSign.script = asBaseDir + DestinationSign.script; - } - } - else if( token == "luadestinationsign:" ) { - deserialize_script_sign( parser, DestinationSign.lua, asBaseDir ); - } - else if( token == "wasmdestinationsign:" ) { - deserialize_script_sign( parser, DestinationSign.wasm, asBaseDir ); - } - // NOTE: legacy key, now expected as optional "background:" parameter in pydestinationsign: { parameter block } - else if( token == "destinationsignbackground:" ) { - parser.getTokens(); - parser >> DestinationSign.background; - } - - } while( token != "" ); - - } // internaldata: - - } while( token != "" ); - - if( !iAnimations ) { - // if the animations weren't defined the model is likely to be non-functional. warrants a warning. - ErrorLog( "Animations tag is missing from the .mmd file \"" + asFileName + "\"" ); - } - - if( ReplacableSkin != "none" ) { - // potentially set blank destination texture - auto language { script_language::lua }; - auto const *scriptsign { script_destination( language ) }; - auto const &background { ( scriptsign != nullptr && false == scriptsign->background.empty() ) ? scriptsign->background : DestinationSign.background }; - DestinationSign.destination_off = DestinationFind( background.empty() ? "nowhere" : background ); - // a blank sign a script draws, drawn once - DestinationSign.background_sign = draw_script_texture( background, DestinationSign.destination_off ); - } - - // assign default samples to sound emitters which weren't included in the config file - if( TestFlag( MoverParameters->CategoryFlag, 1 ) ) { - // rail vehicles: - // engine - if( MoverParameters->Power > 0 ) { - if( true == m_powertrainsounds.dsbWejscie_na_bezoporow.empty() ) { - // hunter-111211: domyslne, gdy brak - m_powertrainsounds.dsbWejscie_na_bezoporow.deserialize( "wejscie_na_bezoporow", sound_type::single ); - m_powertrainsounds.dsbWejscie_na_bezoporow.owner( this ); - } - if( true == m_powertrainsounds.motor_parallel.empty() ) { - m_powertrainsounds.motor_parallel.deserialize( "wescie_na_drugi_uklad", sound_type::single ); - m_powertrainsounds.motor_parallel.owner( this ); - } - } - // braking sounds - if( true == rsUnbrake.empty() ) { - rsUnbrake.deserialize( "[1007]estluz", sound_type::single ); - rsUnbrake.owner( this ); - } - // couplers - for( auto &couplersounds : m_couplersounds ) { - if( true == couplersounds.attach_coupler.empty() ) { - couplersounds.attach_coupler.deserialize( "couplerattach_default", sound_type::single ); - couplersounds.attach_coupler.owner( this ); - } - if( true == couplersounds.detach_coupler.empty() ) { - couplersounds.detach_coupler.deserialize( "couplerdetach_default", sound_type::single ); - couplersounds.detach_coupler.owner( this ); - } - if( true == couplersounds.dsbCouplerStretch.empty() ) { - couplersounds.dsbCouplerStretch.deserialize( "couplerstretch_default", sound_type::single ); - couplersounds.dsbCouplerStretch.owner( this ); - } - if( true == couplersounds.dsbBufferClamp.empty() ) { - couplersounds.dsbBufferClamp.deserialize( "bufferclamp_default", sound_type::single ); - couplersounds.dsbBufferClamp.owner( this ); - } - } - // other sounds - if( true == m_wheelflat.empty() ) { - m_wheelflat.deserialize( "lomotpodkucia 0.23 0.0", sound_type::single, sound_parameters::frequency ); - m_wheelflat.owner( this ); - } - if( true == rscurve.empty() ) { - // hunter-111211: domyslne, gdy brak - rscurve.deserialize( "curve", sound_type::single ); - rscurve.owner( this ); - } - } - - if (mdModel) - mdModel->Init(); // obrócenie modelu oraz optymalizacja, również zapisanie binarnego - if (mdLoad) - mdLoad->Init(); - if (mdLowPolyInt) - mdLowPolyInt->Init(); - for( auto *attachment : mdAttachments ) { - attachment->Init(); - } - - Global.asCurrentTexturePath = paths::textures; // kiedyś uproszczone wnętrze mieszało tekstury nieba - Global.asCurrentDynamicPath = ""; - - // position sound emitters which weren't defined in the config file - // engine sounds, centre of the vehicle - auto const enginelocation { glm::vec3 {0.f, MoverParameters->Dim.H * 0.5f, 0.f } }; - m_powertrainsounds.position( enginelocation ); - // other engine compartment sounds - auto const nullvector { glm::vec3() }; - std::vector enginesounds = { - &sConverter, &sBRVent, &sCompressor, &sCompressorIdle, &sSmallCompressor, &sHeater, &m_batterysound - }; - for( auto sound : enginesounds ) { - if( sound->offset() == nullvector ) { - sound->offset( enginelocation ); - } - } - - // pantographs - if( pants != nullptr ) { - std::size_t pantographindex { 0 }; - for( auto &pantographsounds : m_pantographsounds ) { - auto const pantographoffset { - glm::vec3( - 0.f, - pants[ pantographindex ].fParamPants->vPos.y, - -pants[ pantographindex ].fParamPants->vPos.x ) }; - pantographsounds.sPantUp.offset( pantographoffset ); - pantographsounds.sPantDown.offset( pantographoffset ); - ++pantographindex; - } - } - // doors - std::size_t dooranimationfirstindex { 0 }; - for( std::size_t i = 0; i < ANIM_DOORS; ++i ) { - // zliczanie wcześniejszych animacji - dooranimationfirstindex += iAnimType[ i ]; - } - // couplers - auto const frontcoupleroffset { glm::vec3{ 0.f, 1.f, MoverParameters->Dim.L * 0.5f } }; - m_couplersounds[ end::front ].attach_coupler.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].attach_brakehose.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].attach_mainhose.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].attach_control.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].attach_gangway.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].attach_heating.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].detach_coupler.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].detach_brakehose.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].detach_mainhose.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].detach_control.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].detach_gangway.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].detach_heating.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].dsbCouplerStretch.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].dsbCouplerStretch_loud.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].dsbBufferClamp.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].dsbBufferClamp_loud.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].dsbAdapterAttach.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].dsbAdapterRemove.offset( frontcoupleroffset ); - auto const rearcoupleroffset { glm::vec3{ 0.f, 1.f, MoverParameters->Dim.L * -0.5f } }; - m_couplersounds[ end::rear ].attach_coupler.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].attach_brakehose.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].attach_mainhose.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].attach_control.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].attach_gangway.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].attach_heating.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].detach_coupler.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].detach_brakehose.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].detach_mainhose.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].detach_control.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].detach_gangway.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].detach_heating.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].dsbCouplerStretch.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].dsbCouplerStretch_loud.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].dsbBufferClamp.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].dsbBufferClamp_loud.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].dsbAdapterAttach.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].dsbAdapterRemove.offset( rearcoupleroffset ); -} - -TModel3d * -TDynamicObject::LoadMMediaFile_mdload( std::string const &Name ) const { - - auto const loadname { ( Name.empty() ? "none" : Name ) }; - TModel3d *loadmodel { nullptr }; - - // check if we don't have model override for this load type - if ( loadmodel == nullptr ) - { - auto const lookup { LoadModelOverrides.find( loadname ) }; - if( lookup != LoadModelOverrides.end() ) { - loadmodel = TModelsManager::GetModel( asBaseDir + lookup->second, true ); - } - } - // regular routine if there's no override or it couldn't be loaded - // try first specialized version of the load model, vehiclename_loadname - if ( loadmodel == nullptr ) - { - auto const specializedloadfilename { asBaseDir + MoverParameters->TypeName + "_" + loadname }; - loadmodel = TModelsManager::GetModel( specializedloadfilename, true, false ); - } - // try generic version of the load model next, loadname - if ( loadmodel == nullptr ) - { - auto const genericloadfilename { asBaseDir + loadname }; - loadmodel = TModelsManager::GetModel( genericloadfilename, true, false ); - } - - if ( loadmodel != nullptr ) - loadmodel->GetSMRoot()->WillBeAnimated(); - - return loadmodel; -} - -//--------------------------------------------------------------------------- -void TDynamicObject::RadioStop() -{ // zatrzymanie pojazdu - if( Mechanik ) { - // o ile ktoś go prowadzi - if( MoverParameters->SecuritySystem.radiostop_available() - && MoverParameters->Radio - && MoverParameters->RadioFuse ) { - // jeśli pojazd ma RadioStop i jest on aktywny - // HACK cast until math types unification - glm::dvec3 pos = static_cast(vPosition); - Mechanik->PutCommand( "Emergency_brake", 1.0, 1.0, &pos, stopRadio ); - // add onscreen notification for human driver - // TODO: do it selectively for the 'local' driver once the multiplayer is in - if( false == Mechanik->AIControllFlag ) { - ui::Transcripts.AddLine( "!! RADIO-STOP !!", 0.0, 10.0, false ); - } - } - } -}; - -//--------------------------------------------------------------------------- -void TDynamicObject::Damage(char flag) -{ - if (flag & 1) //różnicówka nie robi nic - { - MoverParameters->MainSwitch(false); - MoverParameters->FuseOff(); - } - else - { - } - - if (flag & 2) //usterka sterowania - { - MoverParameters->StLinFlag = false; - if (MoverParameters->InitialCtrlDelay<100000000) - MoverParameters->InitialCtrlDelay += 100000001; - } - else - { - if (MoverParameters->InitialCtrlDelay>100000000) - MoverParameters->InitialCtrlDelay -= 100000001; - } - - if (flag & 4) //blokada przetwornicy - { - if( MoverParameters->ConverterStart != start_t::disabled ) { - MoverParameters->ConvOvldFlag = true; - } - } - else - { - } - - if (flag & 8) //blokada sprezarki - { - if (MoverParameters->MinCompressor>0) - MoverParameters->MinCompressor -= 100000001; - if (MoverParameters->MaxCompressor>0) - MoverParameters->MaxCompressor -= 100000001; - } - else - { - if (MoverParameters->MinCompressor<0) - MoverParameters->MinCompressor += 100000001; - if (MoverParameters->MaxCompressor<0) - MoverParameters->MaxCompressor += 100000001; - } - - if (flag & 16) //blokada wału - { - if (MoverParameters->CtrlDelay<100000000) - MoverParameters->CtrlDelay += 100000001; - if (MoverParameters->CtrlDownDelay<100000000) - MoverParameters->CtrlDownDelay += 100000001; - } - else - { - if (MoverParameters->CtrlDelay>100000000) - MoverParameters->CtrlDelay -= 100000001; - if (MoverParameters->CtrlDownDelay>100000000) - MoverParameters->CtrlDownDelay -= 100000001; - } - - if (flag & 32) //hamowanie nagŁe - { - } - else - { - } - - MoverParameters->EngDmgFlag = flag; -}; - -void TDynamicObject::SetLights() { - auto const isfrontcaboccupied { MoverParameters->CabOccupied * DirectionGet() >= 0 }; - int const automaticmarkers { MoverParameters->CabActive == 0 && MoverParameters->InactiveCabFlag & activation::redmarkers - ? light::redmarker_left + light::redmarker_right : 0 }; - auto const lightpos { MoverParameters->LightsPos - 1 }; - std::array const cablights { - automaticmarkers > 0 ? automaticmarkers : MoverParameters->Lights[ end::front ][ lightpos ], - automaticmarkers > 0 ? automaticmarkers : MoverParameters->Lights[ end::rear ][ lightpos ] }; - // the custom position keeps the lights lit at coupled ends as well - auto const ignorecouplings { MoverParameters->LightsPos == 18 }; - auto *vehicle { GetFirstDynamic( MoverParameters->CabOccupied >= 0 ? end::front : end::rear, Coupling::control ) }; - while( vehicle != nullptr ) { - // set lights on given side if there's no coupling with another vehicle, turn them off otherwise - auto const iscoupled { [ vehicle, ignorecouplings ]( end const Side ) { - return false == ignorecouplings - && vehicle->MoverParameters->Couplers[ Side ].CouplingFlag.HasAny(Coupling::coupler) - && vehicle->MoverParameters->Neighbours[ Side ].vehicle != nullptr; } }; - auto const lights { lights_programmer::vehicle_lights( - cablights, isfrontcaboccupied, vehicle->iDirection, { iscoupled( end::front ), iscoupled( end::rear ) } ) }; - vehicle->RaLightsSet( lights.head, lights.rear ); - vehicle = isfrontcaboccupied ? vehicle->Next(Coupling::control) : vehicle->Prev(Coupling::control); - } -}; - -void TDynamicObject::RaLightsSet(int head, int rear) -{ // zapalenie świateł z przodu i z - // tyłu, zależne od kierunku - // pojazdu - if (!MoverParameters) - return; // może tego nie być na początku - if (rear == ( light::redmarker_left | light::redmarker_right | light::rearendsignals ) ) - { // jeśli koniec pociągu, to trzeba ustalić, czy - // jest tam czynna lokomotywa - // EN57 może nie mieć końcówek od środka członu - if (MoverParameters->Power > 1.0) // jeśli ma moc napędową - if (!MoverParameters->DirActive) // jeśli nie ma ustawionego kierunku - { // jeśli ma zarówno światła jak i końcówki, ustalić, czy jest w stanie aktywnym - // np. lokomotywa na zimno będzie mieć końcówki a nie światła - rear = light::rearendsignals; // tablice blaszane - // trzeba to uzależnić od "załączenia baterii" w pojeździe - } - if( rear == ( light::redmarker_left | light::redmarker_right | light::rearendsignals ) ) // jeśli nadal obydwie możliwości - if( iInventory[ - ( iDirection ? - end::rear : - end::front ) ] & ( light::redmarker_left | light::redmarker_right ) ) { - // czy ma jakieś światła czerowone od danej strony - rear = light::redmarker_left | light::redmarker_right; // dwa światła czerwone - } - else { - rear = light::rearendsignals; // tablice blaszane - } - } - // w zależności od kierunku pojazdu w składzie - if( head >= 0 ) { - auto const vehicleend { iDirection > 0 ? end::front : end::rear }; - MoverParameters->iLights[ vehicleend ] = head & iInventory[vehicleend]; - bool tLeft = MoverParameters->iLights[vehicleend] & (light::auxiliary_left | light::headlight_left); // roboczo czy jakiekolwiek swiatlo z lewej jest zapalone - bool tRight = MoverParameters->iLights[vehicleend] & (light::auxiliary_right | light::headlight_right); // a tu z prawej - if (Controller == Humandriver) { - - auto const dps{MoverParameters->currentDimPosition()}; - - // domyślnie - HighBeamLights = false; - DimHeadlights = false; - - // obsługa OFF - if (dps.isOff) - { - //MoverParameters->iLights[vehicleend] &= 0 | light::rearendsignals; // zostawiamy tylko tabliczki jesli sa - HighBeamLights = false; - DimHeadlights = false; - switch (MoverParameters->CabActive) - { - case end::front: - HeadlightsAoff = true; - break; - case end::rear: - HeadlightsBoff = true; - break; - default: - break; - } - } - else - { - switch (MoverParameters->CabActive) - { - case end::front: - HeadlightsAoff = false; - break; - case end::rear: - HeadlightsBoff = false; - break; - default: - break; - } - } - - // obsługa przyciemnionych - DimHeadlights = dps.isDimmed; - - // obsługa długich - if (dps.isHighBeam) - { - HighBeamLights = true; - } - } - - } - if( rear >= 0 ) { - auto const vehicleend{ iDirection > 0 ? end::rear : end::front }; - MoverParameters->iLights[ vehicleend ] = rear & iInventory[vehicleend]; - } -}; - -void TDynamicObject::SetLightDimmings() -{ - auto const vehicleend{iDirection > 0 ? end::front : end::rear}; - if (Controller == Humandriver) - { - - auto const dps{MoverParameters->currentDimPosition()}; - - // domyślnie - HighBeamLights = false; - DimHeadlights = false; - - // obsługa OFF - if (dps.isOff) - { - // MoverParameters->iLights[vehicleend] &= 0 | light::rearendsignals; // zostawiamy tylko tabliczki jesli sa - HighBeamLights = false; - DimHeadlights = false; - switch (vehicleend) - { - case end::front: - HeadlightsAoff = true; - break; - case end::rear: - HeadlightsBoff = true; - break; - default: - break; - } - } - else - { - switch (vehicleend) - { - case end::front: - HeadlightsAoff = false; - break; - case end::rear: - HeadlightsBoff = false; - break; - default: - break; - } - } - - // obsługa przyciemnionych - DimHeadlights = dps.isDimmed; - - // obsługa długich - if (dps.isHighBeam) - { - // obsługa długich - if (dps.isHighBeam) - { - HighBeamLights = true; - } - } - } -} - -bool TDynamicObject::has_signal_pc1_on() const { - - auto const vehicleend { iDirection > 0 ? end::front : end::rear }; - auto const equippedlights { iInventory[ vehicleend ] }; - auto const pattern { equippedlights & ( light::headlight_left | light::headlight_right | light::headlight_upper ) }; - auto const patternfallback { equippedlights & ( light::auxiliary_left | light::auxiliary_right | light::headlight_upper ) }; - auto const hasauxiliarylights { ( equippedlights & ( light::auxiliary_left | light::auxiliary_right ) ) != 0 }; - auto const activelights { MoverParameters->iLights[ vehicleend ] }; - - return (pattern != 0 && activelights == pattern) || (hasauxiliarylights && activelights == patternfallback) || - (pattern == 0 && patternfallback == 0 && activelights == light::rearendsignals); // pc4 -} - -bool TDynamicObject::has_signal_pc2_on() const { - - auto const vehicleend { iDirection > 0 ? end::front : end::rear }; - auto const equippedlights { iInventory[ vehicleend ] }; - auto const pattern { equippedlights & ( light::redmarker_left | light::headlight_right | light::headlight_upper ) }; - auto const patternfallback { equippedlights & ( light::redmarker_left | light::auxiliary_right | light::headlight_upper ) }; - auto const hasauxiliarylights { ( equippedlights & ( light::auxiliary_left | light::auxiliary_right ) ) != 0 }; - auto const activelights { MoverParameters->iLights[ vehicleend ] }; - - return activelights == pattern || (hasauxiliarylights && activelights == patternfallback); -} - -bool TDynamicObject::has_signal_pc5_on() const { - - auto const vehicleend { iDirection > 0 ? end::rear : end::front }; - auto const equippedlights { iInventory[ vehicleend ] }; - auto const pattern { equippedlights & ( light::redmarker_left | light::redmarker_right ) }; - auto const patternfallback { equippedlights & light::rearendsignals }; - auto const activelights { MoverParameters->iLights[ vehicleend ] }; - - return (pattern != 0 && activelights == pattern) || (patternfallback != 0 && activelights == patternfallback); -} - -bool TDynamicObject::has_signal_on( int const Side, int const Pattern ) const { -/* - auto const vehicleend { iDirection > 0 ? Side : 1 - Side }; - auto const pattern { iInventory[ vehicleend ] & Pattern }; - - return ( MoverParameters->iLights[ vehicleend ] == pattern ); -*/ - return MoverParameters->iLights[Side] == (Pattern & iInventory[Side]); -} - -int TDynamicObject::DirectionSet(int d) -{ // ustawienie kierunku w składzie (wykonuje AI) - auto const lastdirection { iDirection }; - iDirection = d > 0 ? 1 : 0; // d:1=zgodny,-1=przeciwny; iDirection:1=zgodny,0=przeciwny; - - if( iDirection != lastdirection ) { - // direction was flipped, switch recorded servicable platform sides for potentially ongoing load exchange - auto const left { lastdirection > 0 ? 1 : 2 }; - auto const right { 3 - left }; - m_exchange.platforms = - ( ( m_exchange.platforms & left ) != 0 ? right : 0 ) - + ( ( m_exchange.platforms & right ) != 0 ? left : 0 ); - } - - if (MyTrack) - { // podczas wczytywania wstawiane jest AI, ale może jeszcze nie być toru - // AI ustawi kierunek ponownie po uruchomieniu silnika - update_neighbours(); - } - // informacja o położeniu następnego - return 1 - ( iDirection > 0 ? NextConnectedNo() : PrevConnectedNo() ); -}; - -// wskaźnik na poprzedni, nawet wirtualny -TDynamicObject * TDynamicObject::PrevAny() const { - return MoverParameters->Neighbours[ iDirection ^ 1 ].vehicle; -} -TDynamicObject * TDynamicObject::Prev(CouplingSet const couplings) const { - return MoverParameters->Couplers[iDirection ^ 1].CouplingFlag.HasAny(couplings) ? MoverParameters->Neighbours[iDirection ^ 1].vehicle : nullptr;// gdy sprzęg wirtualny, to jakby nic nie było -} -TDynamicObject * TDynamicObject::Next(CouplingSet const couplings) const { - return MoverParameters->Couplers[iDirection].CouplingFlag.HasAny(couplings) ? MoverParameters->Neighbours[iDirection].vehicle : nullptr;// gdy sprzęg wirtualny, to jakby nic nie było -} - -// checks whether there's unbroken connection of specified type to specified vehicle -bool -TDynamicObject::is_connected( TDynamicObject const *Vehicle, CouplingSet const couplings ) const { - - auto *vehicle { this }; - if( vehicle == Vehicle ) { - // edge case, vehicle is always "connected" with itself - return true; - } - // check ahead, it's more likely the "owner" using this method is located there - while( ( vehicle = vehicle->Prev( couplings ) ) != nullptr ) { - if( vehicle == Vehicle ) { - return true; - } - if( vehicle == this ) { - // edge case, looping consist - return false; - } - } - // start anew in the other direction - vehicle = this; - while( ( vehicle = vehicle->Next( couplings ) ) != nullptr ) { - if( vehicle == Vehicle ) { - return true; - } - } - // no luck in either direction, give up - return false; -} - -// ustalenie następnego (1) albo poprzedniego (0) w składzie bez względu na prawidłowość iDirection -TDynamicObject * -TDynamicObject::Neighbour(int &dir) { - - auto *neighbour { ( - MoverParameters->Couplers[ dir ].CouplingFlag != Coupling::none ? - MoverParameters->Neighbours[ dir ].vehicle : - nullptr ) }; - // nowa wartość - dir = 1 - MoverParameters->Neighbours[ dir ].vehicle_end; - - return neighbour; -}; - -// updates potential collision sources -void -TDynamicObject::update_neighbours() { - - for( int end = end::front; end <= end::rear; ++end ) { - - auto &neighbour { MoverParameters->Neighbours[ end ] }; - auto const &coupler { MoverParameters->Couplers[ end ] }; - - if( coupler.Connected != nullptr - && neighbour.vehicle != nullptr ) { - // physical connection with another vehicle locks down collision source on this end -// neighbour.vehicle = coupler.Connected; -// neighbour.vehicle_end = coupler.ConnectedNr; - neighbour.distance = TMoverParameters::CouplerDist( MoverParameters, coupler.Connected ); - if( MoverParameters->OffTrack.active() || neighbour.vehicle->MoverParameters->OffTrack.active() ) { - // physics.derailment new: off the track the bodies turn against each other, the ends meet where they are - // (the distance between the middles less the half lengths would press the buffers of a bent pair) - neighbour.distance = off_track_gap( end ); - } - // take into account potential adapters attached to the couplers - auto const &othercoupler { neighbour.vehicle->MoverParameters->Couplers[ neighbour.vehicle_end ] }; - neighbour.distance -= coupler.adapter_length; - neighbour.distance -= othercoupler.adapter_length; - } - else { - // if there's no connected vehicle check for potential collision sources in the vicinity - // NOTE: we perform a new scan on each update to ensure we always locate the nearest potential source - neighbour = neighbour_data(); - // 10m ~= 140 km/h at 4 fps + safety margin, potential distance between outer axles of involved vehicles - auto const scanrange { std::max( 10.0, std::abs( MoverParameters->V ) ) + 40.0 }; - // physics.derailment new: a vehicle off the track beside the other one doesn't run into it, the scan goes on - // past it to the vehicles beyond - auto const lookup { find_vehicle( end, scanrange, true ) }; - - if( false == std::get( lookup ) ) { continue; } - - neighbour.vehicle = std::get( lookup ); - neighbour.vehicle_end = std::get( lookup ); - neighbour.distance = std::get( lookup ); - - if( neighbour.vehicle - && neighbour.distance < (neighbour.vehicle->MoverParameters->CategoryFlag == 2 ? 50 : 100) ) { - // at short distances (re)calculate range between couplers directly - neighbour.distance = TMoverParameters::CouplerDist( MoverParameters, neighbour.vehicle->MoverParameters ); - if( MoverParameters->OffTrack.active() || neighbour.vehicle->MoverParameters->OffTrack.active() ) { - // physics.derailment new: the ends where they are, as for a coupled pair - neighbour.distance = off_track_gap( end ); - } - // take into account potential adapters attached to the couplers - auto const &othercoupler { neighbour.vehicle->MoverParameters->Couplers[ neighbour.vehicle_end ] }; - neighbour.distance -= coupler.adapter_length; - neighbour.distance -= othercoupler.adapter_length; - } - } - } -} - -bool -TDynamicObject::in_line_with( TDynamicObject const &Other ) const { - - // the middle of the other one off the axis of this one, and this one off the axis of the other one, by less than - // the half widths of both: their ends can meet - auto const reach { 0.5 * ( MoverParameters->Dim.W + Other.MoverParameters->Dim.W ) }; - auto const apart { Other.vPosition - vPosition }; - return std::abs( glm::dot( apart, vLeft ) ) < reach && std::abs( glm::dot( apart, Other.vLeft ) ) < reach; -} - -// locates potential collision source within specified range, scanning track in specified direction. returns: true if neighbour was located, false otherwise -// NOTE: reuses legacy code. TBD, TODO: review, refactor? -std::tuple -TDynamicObject::find_vehicle( int const Direction, double const Distance, bool const InLine ) const { - - auto direction { ( Direction == end::front ? 1 : -1 ) }; - auto const initialdirection { direction }; // zapamiętanie kierunku poszukiwań na torze początkowym, względem sprzęgów - - auto const *track { RaTrackGet() }; - if( RaDirectionGet() < 0 ) { - // czy oś jest ustawiona w stronę Point1? - direction = -direction; - } - - // (teraz względem toru) - auto const mycoupler { ( initialdirection < 0 ? end::rear : end::front ) }; // numer sprzęgu do podłączenia w obiekcie szukajacym - auto foundcoupler { -1 }; // numer sprzęgu w znalezionym obiekcie (znaleziony wypełni) - auto distance { 0.0 }; // przeskanowana odleglość; odległość do zawalidrogi - auto *foundobject { ABuFindObject( foundcoupler, distance, track, direction, mycoupler, InLine ) }; // zaczynamy szukać na tym samym torze - - if( foundobject == nullptr ) { - // jeśli nie ma na tym samym, szukamy po okolicy szukanie najblizszego toru z jakims obiektem - // praktycznie przeklejone z TraceRoute()... - if (direction >= 0) // uwzględniamy kawalek przeanalizowanego wcześniej toru - distance = track->Length() - RaTranslationGet(); // odległość osi od Point2 toru - else - distance = RaTranslationGet(); // odległość osi od Point1 toru - - while (distance < Distance) { - if (direction > 0) { - // w kierunku Point2 toru - if( track ? - track->iNextDirection : - false ) { - // jeśli następny tor jest podpięty od Point2 - direction = -direction; // to zmieniamy kierunek szukania na tym torze - } - if( track ) { - track = track->CurrentNext(); // potem dopiero zmieniamy wskaźnik - } - } - else { - // w kierunku Point1 - if( track ? - !track->iPrevDirection : - true ) { - // jeśli poprzedni tor nie jest podpięty od Point2 - direction = -direction; // to zmieniamy kierunek szukania na tym torze - } - if( track ) { - track = track->CurrentPrev(); // potem dopiero zmieniamy wskaźnik - } - } - if (track) { - // jesli jest kolejny odcinek toru - foundobject = ABuFindObject(foundcoupler, distance, track, direction, mycoupler, InLine); // przejrzenie pojazdów tego toru - if (foundobject) { - break; - } - } - else { - // jeśli toru nie ma, to wychodzimy - distance = Distance + 1.0; // koniec przeglądania torów - break; - } - } - } // Koniec szukania najbliższego toru z jakimś obiektem. - - if( foundobject == nullptr ) { return {}; } -/* - auto const *vehicle { MoverParameters }; - auto const *foundvehicle { foundobject->MoverParameters }; - if( ( false == TestFlag( track->iCategoryFlag, 1 ) ) - && ( distance > 50.0 ) ) { - // Ra: jeśli dwa samochody się mijają na odcinku przed zawrotką, to odległość między nimi nie może być liczona w linii prostej! - // NOTE: the distance is approximated, and additionally less accurate for cars heading in opposite direction - distance -= ( 0.5 * ( vehicle->Dim.L + foundvehicle->Dim.L ) ); - } - else if( distance < 100.0 ) { - // at short distances start to calculate range between couplers directly - // odległość do najbliższego pojazdu w linii prostej - distance = TMoverParameters::CouplerDist( vehicle, foundvehicle ); - } -*/ - return { foundobject, foundcoupler, distance, true }; -} - -TDynamicObject * TDynamicObject::FindPowered() -{ // taka proteza: - // chcę podłączyć kabinę EN57 bezpośrednio z silnikowym, aby nie robić tego przez ukrotnienie - // drugi silnikowy i tak musi być ukrotniony, podobnie jak kolejna jednostka - // lepiej by było przesyłać komendy sterowania, co jednak wymaga przebudowy transmisji komend (LD) - // problem się robi ze światłami, które będą zapalane w silnikowym, ale muszą świecić się w rozrządczych - // dla EZT światłą czołowe będą "zapalane w silnikowym", ale widziane z rozrządczych - // również wczytywanie MMD powinno dotyczyć aktualnego członu - // problematyczna może być kwestia wybranej kabiny (w silnikowym...) - // jeśli silnikowy będzie zapięty odwrotnie (tzn. -1), to i tak powinno jeździć dobrze - // również hamowanie wykonuje się zaworem w członie, a nie w silnikowym... - auto const coupling { MoverParameters->is_multiple_unit() ? - Coupling::permanent : - Coupling::control }; - - auto *lookup { - find_vehicle( - coupling, - []( TDynamicObject * vehicle ) { - return vehicle->MoverParameters->Power > 1.0; } ) }; - - return lookup != nullptr ? lookup : this; // always return valid vehicle for backward compatibility -} - -TDynamicObject * -TDynamicObject::FindPantographCarrier() { - - // try first within a single unit, broaden to all vehicles under our control if first attempt fails - std::array const couplings = { Coupling::permanent, Coupling::control }; - - for( auto const coupling : couplings ) { - auto *result = - find_vehicle( - coupling, - []( TDynamicObject * vehicle ) { - return vehicle->MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector && vehicle->MoverParameters->EnginePowerSource.CollectorParameters.CollectorsNo > 0; } ); - if( result != nullptr ) { - return result; - } - } - // if we're still here, admit failure - return nullptr; -} - -//--------------------------------------------------------------------------- - -void TDynamicObject::ParamSet(int what, int into) -{ // ustawienie lokalnego parametru (what) na stan (into) - switch (what & 0xFF00) - { - case 0x0100: // to np. są drzwi, bity 0..7 określają numer 1..254 albo maskę - // dla 8 różnych - if (what & 1) // na razie mamy lewe oraz prawe, czyli używamy maskę 1=lewe, - // 2=prawe, 3=wszystkie - if( MoverParameters->Doors.instances[side::left].is_open ) - { // są otwarte - if (!into) // jeśli zamykanie - { - // dźwięk zamykania - } - } - else - { // są zamknięte - if (into) // jeśli otwieranie - { - // dźwięk otwierania - } - } - if (what & 2) // prawe działają niezależnie od lewych - if( MoverParameters->Doors.instances[side::right].is_open ) - { // są otwarte - if (!into) // jeśli zamykanie - { - // dźwięk zamykania - } - } - else - { // są zamknięte - if (into) // jeśli otwieranie - { - // dźwięk otwierania - } - } - break; - } -}; - -int TDynamicObject::RouteWish(TTrack *tr) -{ // zapytanie do AI, po którym - // segmencie (-6..6) jechać na - // skrzyżowaniu (tr) - return Mechanik ? Mechanik->CrossRoute(tr) : 0; // wg AI albo prosto -}; - -void TDynamicObject::play_mirror_sounds( side const Side, mirror_moves::event const Event ) { - - if( Event == mirror_moves::event::none ) { return; } - // as UpdateMirror(), only the mirrors of the occupied cab move - if( MoverParameters->CabOccupied == 0 ) { return; } - auto const cabend { MoverParameters->CabOccupied > 0 ? end::front : end::rear }; - for( auto &mirror : m_mirrorsounds ) { - if( mirror.placement != Side || mirror.end != cabend ) { continue; } - auto &sound { Event == mirror_moves::event::unfolding ? mirror.unfold : mirror.fold }; - auto &other { Event == mirror_moves::event::unfolding ? mirror.fold : mirror.unfold }; - other.stop(); - sound.play( sound_flags::exclusive ); - } -} - -void TDynamicObject::DestinationClear() { - - if( false == DestinationSign.has_light ) { return; } // physical destination signs remain up until manually changed - // update_destinations() shows the blank sign in place of the missing destination - DestinationSign.destination = null_handle; - DestinationSign.script_sign.reset(); -} - -void TDynamicObject::DestinationSet(std::string const &to, std::string const &numer) { - // ustawienie stacji docelowej oraz wymiennej tekstury 4, jeśli istnieje plik - // w zasadzie, to każdy wagon mógłby mieć inną stację docelową - // zwłaszcza w towarowych, pod kątem zautomatyzowania maewrów albo pracy górki - // ale to jeszcze potrwa, zanim będzie możliwe, na razie można wpisać stację z - // rozkładu - - asDestination = to; - - if( std::abs( m_materialdata.multi_textures ) >= 4 ) { return; } // jak są 4 tekstury wymienne, to nie zmieniać rozkładem - if( DestinationSign.sign == nullptr ) { return; } // no sign submodel, no problem - // a sign drawn for the previous destination - DestinationSign.script_sign.reset(); - - // now see if we can find any version of the destination texture - std::vector const destinations = { - numer, // try dedicated timetable sign first... - to }; // ...then generic destination sign - - for( auto const &destination : destinations ) { - - DestinationSign.destination = DestinationFind( destination ); - if( DestinationSign.destination != null_handle ) { - // got what we wanted, we're done here - return; - } - } - // if we didn't get static texture we might be able to make one - if( true == destination_set_script( numer ) ) { return; } - if( DestinationSign.script.empty() ) { return; } // no script so no way to make the texture - if( numer == "none" ) { return; } // blank or incomplete/malformed timetable, don't bother - - DestinationSign.destination = GfxRenderer->Fetch_Material( destination_request( DestinationSign.script, DestinationSign.instancing, DestinationSign.parameters ) ); -} - -std::string TDynamicObject::destination_request( std::string const &Script, std::string const &Instancing, std::string const &Parameters ) const { - - auto const trainname { [this]() -> std::string { - if( ctOwner != nullptr ) { return ctOwner->TrainName(); } - if( Mechanik != nullptr ) { return Mechanik->TrainName(); } - return "none"; } }; // shouldn't get here but, eh - auto const instance { [this, &Instancing]() -> std::string { - if( Instancing == "name" ) { return MoverParameters->Name; } - if( Instancing == "type" ) { return MoverParameters->TypeName; } - return "none"; } }; - - std::string signrequest { - "make:" - + Script - + "?" - // timetable include - + "$timetable=" + ( - ctOwner == nullptr ? - MoverParameters->Name : // leading vehicle, can point to it directly - ctOwner->Vehicle()->MoverParameters->Name ) // owned vehicle, safer to point to owner as carriages can have identical names - // basic instancing string - // NOTE: underscore doesn't have any magic meaning for the time being, it's just less likely to conflict with regular dictionary keys - + "&_id1=" + trainname() }; - // TBD, TODO: replace instancing with support for variables in extra parameters string? - if( false == Instancing.empty() ) { - signrequest += "&_id2=" + instance(); - } - // optionl extra parameters - if( false == Parameters.empty() ) { - signrequest += "&" + Parameters; - } - return signrequest; -} - -script_screens::screen_config const *TDynamicObject::script_destination( script_language &Language ) const { - - auto const &screens { Application.screens() }; - if( false == DestinationSign.lua.script.empty() && screens.runs( script_language::lua ) ) { - Language = script_language::lua; - return &DestinationSign.lua; - } - if( false == DestinationSign.wasm.script.empty() && screens.runs( script_language::wasm ) ) { - Language = script_language::wasm; - return &DestinationSign.wasm; - } - return nullptr; // no script sign, maybe a python one -} - -bool TDynamicObject::destination_set_script( std::string const &Numer ) { - - if( Numer == "none" ) { return false; } // blank or incomplete/malformed timetable, don't bother - auto language { script_language::lua }; - auto const *scriptsign { script_destination( language ) }; - if( scriptsign == nullptr ) { return false; } - - auto const signrequest { destination_request( scriptsign->script, scriptsign->instancing, scriptsign->parameters ) }; - auto const signmaterial { GfxRenderer->Fetch_Material( signrequest ) }; - if( signmaterial == null_handle ) { return false; } - auto &signtexture { GfxRenderer->Texture( GfxRenderer->Material( signmaterial )->GetTexture( 0 ) ) }; - - // vehicles showing the same request (one train, one instance) share the screen, as they share the texture - auto sign { Application.screens().acquire( { - .kind = script_screen_kind::external, - .language = language, - .script = scriptsign->script, - .key = signrequest, - .texture = &signtexture, - .frames = scriptsign->frames } ) }; - if( sign == nullptr ) { return false; } - - DestinationSign.destination = signmaterial; - DestinationSign.script_sign = std::move( sign ); - DestinationSign.script_request = signrequest.substr( signrequest.find( '?' ) + 1 ); - return true; -} - -std::shared_ptr TDynamicObject::draw_script_texture( std::string const &Name, material_handle const Material ) { - - if( false == Name.starts_with( "make:" ) || Material == null_handle ) { return nullptr; } - auto const query { Name.find( '?' ) }; - auto const script { Name.substr( 5, query == std::string::npos ? std::string::npos : query - 5 ) }; - auto const language { script_language_of( script ) }; - if( false == language.has_value() ) { return nullptr; } // a python texture, made by the texture itself - if( false == script_screens::screen_script_path( "", script ).has_value() ) { - ErrorLog( "Bad script texture: \"" + script + "\" leads outside the game's folder" ); - return nullptr; - } - - auto &queue { Application.screens() }; - auto &texture { GfxRenderer->Texture( GfxRenderer->Material( Material )->GetTexture( 0 ) ) }; - auto screen { queue.acquire( { - .kind = script_screen_kind::external, - .language = *language, - .script = script, - .key = Name, - .texture = &texture, - .frames = 0 } ) }; - if( screen == nullptr ) { return nullptr; } - queue.submit( - screen, - query == std::string::npos ? - std::make_shared() : - std::make_shared( Name.substr( query + 1 ) ), - 0 ); - return screen; -} - -material_handle TDynamicObject::DestinationFind( std::string Destination ) { - - if( Destination.empty() ) { return null_handle; } - - // destination textures are kept in the vehicle's directory so we point the current texture path there - auto const currenttexturepath { Global.asCurrentTexturePath }; - Global.asCurrentTexturePath = asBaseDir; - - auto destinationhandle { null_handle }; - - if( Destination.starts_with("make:") ) { - // autogenerated texture - destinationhandle = GfxRenderer->Fetch_Material( Destination ); - } - else { - // regular texture - Destination = Bezogonkow( Destination ); // do szukania pliku obcinamy ogonki - // now see if we can find any version of the texture - std::vector const destinations { - Destination + '@' + MoverParameters->TypeName, - Destination }; - - for( auto const &destination : destinations ) { - auto material = TextureTest( ToLower( destination ) ); - if( false == material.empty() ) { - destinationhandle = GfxRenderer->Fetch_Material( material ); - break; - } - } - } - // whether we got anything, restore previous texture path - Global.asCurrentTexturePath = currenttexturepath; - - return destinationhandle; -} - -void TDynamicObject::announce( announcement_t const Announcement, bool const Chime ) { - - if( m_doorspeakers.empty() ) { return; } - - auto const *driver { ( - ctOwner != nullptr ? - ctOwner : - Mechanik ) }; - if( driver == nullptr ) { return; } - - auto const &timetable { driver->TrainTimetable() }; - auto const &announcements { m_pasystem.announcements }; - auto playchime { Chime }; - - if( announcements[ static_cast( Announcement ) ].empty() ) { - goto followup; - } - // if the announcement sound was defined queue playback - { - sound_source stopnamesound; - switch( Announcement ) { - case announcement_t::approaching: - case announcement_t::next: { - stopnamesound = timetable.next_stop_sound(); - break; - } - case announcement_t::current: { - stopnamesound = timetable.current_stop_sound(); - break; - } - case announcement_t::destination: { - stopnamesound = timetable.last_stop_sound(); - break; - } - default: { - break; - } - } - if( stopnamesound.empty() ) { - goto followup; - } - // potentially precede the announcement with a chime... - if( true == playchime - && false == announcements[static_cast(announcement_t::chime)].empty() ) { - m_pasystem.announcement_queue.emplace_back( announcements[ static_cast( announcement_t::chime ) ] ); - playchime = false; - } - // ...then play the announcement itself - m_pasystem.announcement_queue.emplace_back( announcements[ static_cast( Announcement ) ] ); - m_pasystem.announcement_queue.emplace_back( stopnamesound ); - } -followup: - // potentially follow up with another announcement - if( Announcement == announcement_t::next ) { - announce( announcement_t::destination, playchime ); - } -} - -void TDynamicObject::OverheadTrack(float o) -{ // ewentualne wymuszanie jazdy - // bezprądowej z powodu informacji - // w torze - if (ctOwner) // jeśli ma obiekt nadzorujący - { // trzeba zaktualizować mapę flag bitowych jazdy bezprądowej - if (o < 0.0) - { // normalna jazda po tym torze - ctOwner->iOverheadZero &= ~iOverheadMask; // zerowanie bitu - może pobierać prąd - ctOwner->iOverheadDown &= ~iOverheadMask; // zerowanie bitu - może podnieść pantograf - } - else if (o > 0.0) - { // opuszczenie pantografów - ctOwner->iOverheadZero |= iOverheadMask; // ustawienie bitu - ma jechać bez pobierania prądu - ctOwner->iOverheadDown |= iOverheadMask; // ustawienie bitu - ma opuścić pantograf - } - else - { // jazda bezprądowa z podniesionym pantografem - ctOwner->iOverheadZero |= iOverheadMask; // ustawienie bitu - ma jechać bez pobierania prądu - ctOwner->iOverheadDown &= ~iOverheadMask; // zerowanie bitu - może podnieść pantograf - } - } -}; - -void -TDynamicObject::update_shake( double const Timedelta ) { - - ShakeStateBefore = ShakeState; - // Ra: mechanik powinien być telepany niezależnie od pozycji pojazdu - // Ra: trzeba zrobić model bujania głową i wczepić go do pojazdu - - // Ra: tu by się przydało uwzględnić rozkład sił: - // - na postoju horyzont prosto, kabina skosem - // - przy szybkiej jeździe kabina prosto, horyzont pochylony - - // McZapkie: najpierw policzę pozycję w/m kabiny - - // ABu: rzucamy kabina tylko przy duzym FPS! - // Mala histereza, zeby bez przerwy nie przelaczalo przy FPS~17 - // Granice mozna ustalic doswiadczalnie. Ja proponuje 14:20 - if( Global.iSlowMotion == 0 ) { // musi być pełna prędkość - - glm::dvec3 shakevector; - if( MoverParameters->EngineType == TEngineType::DieselElectric - || MoverParameters->EngineType == TEngineType::DieselEngine ) { - if( std::abs( MoverParameters->enrot ) > 0.0 ) { - // engine vibration - shakevector.x += - std::sin(MoverParameters->eAngle * 4.0) * Timedelta * - EngineShake.scale - // fade in with rpm above threshold - * std::clamp( - ( MoverParameters->enrot - EngineShake.fadein_offset ) * EngineShake.fadein_factor, - 0.0, 1.0 ) - // fade out with rpm above threshold - * std::lerp( - 1.0, 0.0, - std::clamp( - ( MoverParameters->enrot - EngineShake.fadeout_offset ) * EngineShake.fadeout_factor, - 0.0, 1.0 ) ); - } - } - - if( HuntingShake.fadein_begin > 0.f - && true == MoverParameters->TruckHunting ) { - // hunting oscillation - HuntingAngle = clamp_circular( HuntingAngle + 4.0 * HuntingShake.frequency * Timedelta * MoverParameters->Vel, 360.0 ); - auto const huntingamount = - std::lerp( - 0.0, 1.0, - std::clamp( - ( MoverParameters->Vel - HuntingShake.fadein_begin ) / ( HuntingShake.fadein_end - HuntingShake.fadein_begin ), - 0.0, 1.0 ) ); - shakevector.x += - std::sin(glm::radians(HuntingAngle)) * Timedelta * HuntingShake.scale - * huntingamount; - IsHunting = huntingamount > 0.025; - } - - if (FreeFlyModeFlag) - shakevector *= 0; - - auto const iVel { std::min( GetVelocity(), 150.0 ) }; - // an uneven track shakes the cab by itself, in place of the sway drawn from the curve and the jolts drawn at random, as far as it does - auto const replaced { track_uneven::replaced_shake( MyTrack != nullptr ? MyTrack->uneven_underway() : track_uneven::amounts {} ) }; - if( iVel > 0.5 ) { - // acceleration-driven base shake - shakevector += glm::dvec3( - replaced.sway ? 0.0 : -MoverParameters->AccN * Timedelta * 5.0 * Global.ShakingMultiplierRL, // highlight side sway - -MoverParameters->AccVert * Timedelta * Global.ShakingMultiplierUD, - -MoverParameters->AccSVBased * Timedelta * 1.5 * Global.ShakingMultiplierBF); // accent acceleration/deceleration - // unevenness of the track under the outer axles - auto const ride { 0.5 * ( Axle0.UnevenBend() + Axle1.UnevenBend() ) * ( MoverParameters->V * MoverParameters->V ) }; - shakevector += glm::dvec3( - -glm::dot( ride, vLeft ) * Timedelta * 5.0 * Global.ShakingMultiplierRL, - -ride.y * Timedelta * Global.ShakingMultiplierUD, - 0.0 ); - } - - auto shake { 1.25 * ShakeSpring.ComputateForces( shakevector, ShakeState.offset ) }; - - if( false == replaced.jolts && LocalRandom( iVel ) > 25.0 ) { - // extra shake at increased velocity - shake += ShakeSpring.ComputateForces( - glm::dvec3( - ( LocalRandom( iVel * 2 ) - iVel ) / ( iVel * 2 * 4 ) * BaseShake.jolt_scale.x, - ( LocalRandom( iVel * 2 ) - iVel ) / ( iVel * 2 * 4 ) * BaseShake.jolt_scale.y, - ( LocalRandom( iVel * 2 ) - iVel ) / ( iVel * 2 * 4 ) * BaseShake.jolt_scale.z ) -// * (( 200 - DynamicObject->MyTrack->iQualityFlag ) * 0.0075 ) // scale to 75-150% based on track quality - * 1.25, - ShakeState.offset ); - } - shake *= 0.85; - - ShakeState.velocity -= ( shake + ShakeState.velocity * 100.0 ) * (double)( BaseShake.jolt_scale.x + BaseShake.jolt_scale.y + BaseShake.jolt_scale.z ) / 200.0; - - // McZapkie: - ShakeState.offset += ShakeState.velocity * Timedelta; - if( std::abs( ShakeState.offset.y ) > std::abs( BaseShake.jolt_limit ) ) { - ShakeState.velocity.y = -ShakeState.velocity.y; - } - } - else { // hamowanie rzucania przy spadku FPS - ShakeState.offset -= ShakeState.offset * std::min( Timedelta, 1.0 ); // po tym chyba potrafią zostać jakieś ułamki, które powodują zjazd - } -} - -bool -TDynamicObject::axle_passed_joint( axle_sounds &Axle, double const Move, int const Direction ) const { - - // from the follower on its side of the vehicle, as the two can be on different tracks. They stand fAxleDist apart, at the bogie pivots, and - // the offset of the axle is the place of its wheel set, so the two of a bogie come out half of ADist to either side of the pivot - auto const &follower { Axle.offset >= 0.0 ? Axle0 : Axle1 }; - if( auto const railphase { follower.RailPhase( Axle.offset - std::copysign( 0.5 * fAxleDist, Axle.offset ) ) }; railphase >= 0.0 ) { - // the rails under the axle, which aren't always those under the track the vehicle is on - auto const passed { Axle.atjoints && std::abs( railphase - Axle.distance ) > 0.5 * follower.GetTrack()->fSoundDistance }; - Axle.distance = railphase; - Axle.atjoints = true; - return passed; - } - Axle.atjoints = false; - Axle.distance += Move * Direction; - if( Axle.distance >= 0 && Axle.distance <= dRailLength ) { - return false; - } - Axle.distance = clamp_circular( Axle.distance, dRailLength ); - return true; -} - -std::pair -TDynamicObject::shake_angles() const { - - return shake_angles( ShakeState ); -} - -std::pair -TDynamicObject::shake_angles( shake_state const &State ) const { - - return { - std::atan( State.velocity.x * BaseShake.angle_scale.x ), - std::atan( State.velocity.z * BaseShake.angle_scale.z ) }; -} - -TDynamicObject::shake_state -TDynamicObject::shake_between( double const Fraction ) const { - - if( Fraction >= 1.0 ) { - return ShakeState; - } - auto const between { []( glm::dvec3 const &Before, glm::dvec3 const &After, double const Part ) { - return glm::dvec3 { - std::lerp( Before.x, After.x, Part ), - std::lerp( Before.y, After.y, Part ), - std::lerp( Before.z, After.z, Part ) }; } }; - auto const part { std::max( Fraction, 0.0 ) }; - return { - between( ShakeStateBefore.velocity, ShakeState.velocity, part ), - between( ShakeStateBefore.offset, ShakeState.offset, part ) }; -} - -void -TDynamicObject::powertrain_sounds::position( glm::vec3 const Location ) { - - auto const nullvector { glm::vec3() }; - std::vector enginesounds = { - &inverter, - &motor_relay, &dsbWejscie_na_bezoporow, &motor_parallel, &motor_shuntfield, &rsWentylator, - &engine, &engine_ignition, &engine_shutdown, &engine_revving, &engine_turbo, &oil_pump, &fuel_pump, &water_pump, &water_heater, &radiator_fan, &radiator_fan_aux, - &transmission, &rsEngageSlippery, &retarder - }; - for( auto sound : enginesounds ) { - if( sound->offset() == nullvector ) { - sound->offset( Location ); - } - } -} - -void -TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, double const Deltatime ) { - - if( Vehicle.Power == 0 ) { return; } - - double frequency { 1.0 }; - double volume { 0.0 }; - - // oil pump - if( true == Vehicle.OilPump.is_active ) { - oil_pump - .pitch( oil_pump.m_frequencyoffset + oil_pump.m_frequencyfactor * 1.f ) - .gain( oil_pump.m_amplitudeoffset + oil_pump.m_amplitudefactor * 1.f ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - oil_pump.stop(); - } - // fuel pump - if( true == Vehicle.FuelPump.is_active ) { - fuel_pump - .pitch( fuel_pump.m_frequencyoffset + fuel_pump.m_frequencyfactor * 1.f ) - .gain( fuel_pump.m_amplitudeoffset + fuel_pump.m_amplitudefactor * 1.f ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - fuel_pump.stop(); - } - // water pump - if( true == Vehicle.WaterPump.is_active ) { - water_pump - .pitch( water_pump.m_frequencyoffset + water_pump.m_frequencyfactor * 1.f ) - .gain( water_pump.m_amplitudeoffset + water_pump.m_amplitudefactor * 1.f ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - water_pump.stop(); - } - // water heater - if( true == Vehicle.WaterHeater.is_active ) { - water_heater - .pitch( water_heater.m_frequencyoffset + water_heater.m_frequencyfactor * 1.f ) - .gain( water_heater.m_amplitudeoffset + water_heater.m_amplitudefactor * 1.f ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - water_heater.stop(); - } - // engine sounds - // ignition - if( engine_state_last != Vehicle.Mains ) { - - if( true == Vehicle.Mains ) { - // TODO: separate engine and main circuit - // engine activation - engine_shutdown.stop(); - engine_ignition - .pitch( engine_ignition.m_frequencyoffset + engine_ignition.m_frequencyfactor * 1.f ) - .gain( engine_ignition.m_amplitudeoffset + engine_ignition.m_amplitudefactor * 1.f ) - .play( sound_flags::exclusive ); - // main circuit activation - linebreaker_close - .pitch( linebreaker_close.m_frequencyoffset + linebreaker_close.m_frequencyfactor * 1.f ) - .gain( linebreaker_close.m_amplitudeoffset + linebreaker_close.m_amplitudefactor * 1.f ) - .play(); - } - else { - // engine deactivation - engine_ignition.stop(); - engine_shutdown.pitch( engine_shutdown.m_frequencyoffset + engine_shutdown.m_frequencyfactor * 1.f ) - .gain( engine_shutdown.m_amplitudeoffset + engine_shutdown.m_amplitudefactor * 1.f ) - .play( sound_flags::exclusive ); - // main circuit deactivation - linebreaker_open - .pitch( linebreaker_open.m_frequencyoffset + linebreaker_open.m_frequencyfactor * 1.f ) - .gain( linebreaker_open.m_amplitudeoffset + linebreaker_open.m_amplitudefactor * 1.f ) - .play(); - } - engine_state_last = Vehicle.Mains; - } - // main engine sound - if( true == Vehicle.Mains ) { - - if( std::abs(Vehicle.enrot) > 0.01 - // McZapkie-280503: zeby dla dumb dzialal silnik na jalowych obrotach - || Vehicle.EngineType == TEngineType::Dumb ) { - - // frequency calculation - auto const normalizer { ( - true == engine.is_combined() ? - // for combined engine sound we calculate sound point in rpm, to make .mmd files setup easier - // NOTE: we supply 1/100th of actual value, as the sound module converts does the opposite, converting received (typically) 0-1 values to 0-100 range - 60.f * 0.01f : - // for legacy single-piece sounds the standard frequency calculation is left untouched - 1.f ) }; - frequency = - engine.m_frequencyoffset - + engine.m_frequencyfactor * std::abs( Vehicle.enrot ) * normalizer; - - if( Vehicle.EngineType == TEngineType::Dumb ) { - frequency -= 0.2 * Vehicle.EnginePower / ( 1 + Vehicle.Power * 1000 ); - } - - // base volume calculation - switch( Vehicle.EngineType ) { - // TODO: check calculated values - case TEngineType::DieselElectric: { - - volume = - engine.m_amplitudeoffset - + engine.m_amplitudefactor * ( - 0.25 * ( Vehicle.EnginePower / Vehicle.Power ) - + 0.75 * Vehicle.EngineRPMRatio() ); - break; - } - case TEngineType::DieselEngine: { - if( Vehicle.enrot > 0.0 ) { - volume = Vehicle.EnginePower > 0 ? engine.m_amplitudeoffset + engine.m_amplitudefactor * Vehicle.dizel_fill : - engine.m_amplitudeoffset + engine.m_amplitudefactor * std::fabs(Vehicle.enrot / Vehicle.dizel_nmax); - } - break; - } - default: { - volume = - engine.m_amplitudeoffset - + engine.m_amplitudefactor * ( Vehicle.EnginePower + std::fabs( Vehicle.enrot ) * 60.0 ); - break; - } - } - - if( engine_volume >= 0.05 ) { - - auto enginerevvolume { 0.f }; - if( Vehicle.EngineType == TEngineType::DieselElectric - || Vehicle.EngineType == TEngineType::DieselEngine ) { - // diesel engine revolutions increase; it can potentially decrease volume of base engine sound - if( engine_revs_last != -1.f ) { - // calculate potential recent increase of engine revolutions - auto const revolutionsperminute { Vehicle.enrot * 60 }; - auto const revolutionsdifference { revolutionsperminute - engine_revs_last }; - auto const idlerevolutionsthreshold { 1.01 * Vehicle.EngineIdleRPM() }; - engine_revs_change = std::max( 0.0, engine_revs_change - 2.5 * Deltatime ); - if( revolutionsperminute > idlerevolutionsthreshold - && revolutionsdifference > 1.0 * Deltatime ) { - engine_revs_change = std::clamp( engine_revs_change + 5.0 * Deltatime, 0.0, 1.25 ); - } - enginerevvolume = 0.8 * engine_revs_change; - } - engine_revs_last = Vehicle.enrot * 60; - - auto const enginerevfrequency { ( - true == engine_revving.is_combined() ? - // if the sound contains multiple samples we reuse rpm-based calculation from the engine - frequency : - engine_revving.m_frequencyoffset + 1.f * engine_revving.m_frequencyfactor ) }; - - if( enginerevvolume > 0.02 ) { - engine_revving - .pitch( enginerevfrequency ) - .gain( enginerevvolume ) - .play( sound_flags::exclusive ); - } - else { - engine_revving.stop(); - } - } // diesel engines - - // multi-part revving sound pieces replace base engine sound, single revving simply gets mixed with the base - auto const enginevolume { ( - enginerevvolume > 0.02 && true == engine_revving.is_combined() ? - std::max( 0.0, engine_volume - enginerevvolume ) : - engine_volume ) }; - engine - .pitch( frequency ) - .gain( enginevolume ) - .play( sound_flags::exclusive | sound_flags::looping ); - } // enginevolume > 0.05 - } - else { - engine.stop(); - } - } - - if (Vehicle.Mains) { - float power = std::clamp(Vehicle.eimv_pr, 0.0, 1.0); - - fake_engine - .pitch(fake_engine.m_frequencyoffset + power * fake_engine.m_frequencyfactor) - .gain(fake_engine.m_amplitudeoffset + power * fake_engine.m_amplitudefactor) - .play(sound_flags::exclusive | sound_flags::looping); - } - else { - fake_engine.stop(); - } - - engine_volume = std::lerp( engine_volume, volume, 0.25 ); - if( engine_volume < 0.05 ) { - engine.stop(); - } - - // youBy - przenioslem, bo diesel tez moze miec turbo - if( Vehicle.TurboTest > 0 ) { - // udawanie turbo: - auto const pitch_diesel{Vehicle.EngineType == TEngineType::DieselEngine || Vehicle.EngineType == TEngineType::DieselElectric ? Vehicle.enrot / Vehicle.dizel_nmax * Vehicle.dizel_fill : 1}; - auto const goalpitch { std::max( 0.025, ( /*engine_volume **/ pitch_diesel + engine_turbo.m_frequencyoffset ) * engine_turbo.m_frequencyfactor ) }; - auto const goalvolume { ( - Vehicle.MainCtrlPos >= Vehicle.TurboTest && Vehicle.enrot > 0.1 ? - std::max( 0.0, ( engine_turbo_pitch + engine_turbo.m_amplitudeoffset ) * engine_turbo.m_amplitudefactor ) : - 0.0 ) }; - auto const currentvolume { engine_turbo.gain() }; - auto const changerate { 0.4 * Deltatime }; - - engine_turbo_pitch = engine_turbo_pitch > goalpitch ? std::max(goalpitch, engine_turbo_pitch - changerate * 0.5) : std::min(goalpitch, engine_turbo_pitch + changerate); - - volume = currentvolume > goalvolume ? std::max(goalvolume, currentvolume - changerate) : std::min(goalvolume, currentvolume + changerate); - - engine_turbo - .pitch( 0.4 + engine_turbo_pitch * 0.4 ) - .gain( volume ); - - if( volume > 0.05 ) { - engine_turbo.play( sound_flags::exclusive | sound_flags::looping ); - } - else { - engine_turbo.stop(); - } - } - - if( Vehicle.dizel_engage > 0.1 ) { - if( std::abs( Vehicle.dizel_engagedeltaomega ) > 0.2 ) { - frequency = rsEngageSlippery.m_frequencyoffset + rsEngageSlippery.m_frequencyfactor * std::fabs( Vehicle.dizel_engagedeltaomega ); - volume = rsEngageSlippery.m_amplitudeoffset + rsEngageSlippery.m_amplitudefactor * Vehicle.dizel_engage; - } - else { - frequency = 1.f; // rsEngageSlippery.FA+0.7*rsEngageSlippery.FM*(fabs(mvControlled->enrot)+mvControlled->nmax); - volume = Vehicle.dizel_engage > 0.2 ? rsEngageSlippery.m_amplitudeoffset + 0.2 * rsEngageSlippery.m_amplitudefactor * (Vehicle.enrot / Vehicle.nmax) : 0.f; - } - - rsEngageSlippery - .pitch( frequency ) - .gain( volume ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - rsEngageSlippery.stop(); - } - - if (Vehicle.hydro_R) { - float speed = std::abs(Vehicle.hydro_R_n); - - retarder - .pitch(retarder.m_frequencyoffset + speed * retarder.m_frequencyfactor) - .gain(retarder.m_amplitudeoffset + Vehicle.hydro_R_Fill * retarder.m_amplitudefactor); - - if (retarder.gain() > 0.01 && speed > 1 && Vehicle.hydro_R_ClutchActive) { - retarder.play(sound_flags::exclusive | sound_flags::looping); - } - else { - retarder.stop(); - } - } - - // motor sounds - volume = 0.0; - // generic traction motor sounds - if( false == motors.empty() ) { - - if( std::abs( Vehicle.nrot ) > 0.01 ) { - - auto const &motor { motors.front() }; - // frequency calculation - auto normalizer { 1.f }; - if( true == motor.is_combined() ) { - // for combined motor sound we calculate sound point in rpm, to make .mmd files setup easier - // NOTE: we supply 1/100th of actual value, as the sound module converts does the opposite, converting received (typically) 0-1 values to 0-100 range - normalizer = 60.f * 0.01f; - } - auto const motorrevolutions { std::abs( Vehicle.nrot ) * Vehicle.Transmision.Ratio }; - frequency = - motor.m_frequencyoffset - + motor.m_frequencyfactor * motorrevolutions * normalizer; - - // base volume calculation - switch( Vehicle.EngineType ) { - case TEngineType::ElectricInductionMotor: { - volume = - motor.m_amplitudeoffset - + motor.m_amplitudefactor * ( Vehicle.EnginePower + motorrevolutions * 2 ); - break; - } - case TEngineType::ElectricSeriesMotor: { - volume = - motor.m_amplitudeoffset - + motor.m_amplitudefactor * ( Vehicle.EnginePower + motorrevolutions * 60.0 ); - break; - } - default: { - volume = - motor.m_amplitudeoffset - + motor.m_amplitudefactor * motorrevolutions * 60.0; - break; - } - } - - if( Vehicle.EngineType == TEngineType::ElectricSeriesMotor ) { - // volume variation - if( volume < 1.0 - && Vehicle.EnginePower < 100 ) { - - auto const volumevariation { LocalRandom( 100 ) * Vehicle.enrot / ( 1 + Vehicle.nmax ) }; - if( volumevariation < 2 ) { - volume += volumevariation / 200; - } - } - - if( Vehicle.DynamicBrakeFlag - && Vehicle.EnginePower > 0.1 ) { - // Szociu - 29012012 - jeżeli uruchomiony jest hamulec elektrodynamiczny, odtwarzany jest dźwięk silnika - volume += 0.8; - } - } - // scale motor volume based on whether they're active - motor_momentum = - std::clamp( - motor_momentum - - 1.0 * Deltatime // smooth out decay - + std::abs( Vehicle.Mm ) / 60.0 * Deltatime, - 0.0, 1.25 ); - volume *= std::max( 0.25f, motor_momentum ); - motor_volume = std::lerp( motor_volume, volume, 0.25 ); - if( motor_volume >= 0.05 ) { - // apply calculated parameters to all motor instances - for( auto &motor : motors ) { - motor - .pitch( frequency ) - .gain( motor_volume ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - } - else { - // stop all motor instances - for( auto &motor : motors ) { - motor.stop(); - } - } - } - else { - // stop all motor instances - motor_volume = 0.0; - for( auto &motor : motors ) { - motor.stop(); - } - } - } - // inverter-specific traction motor sounds - if( false == acmotors.empty() ) { - - if( Vehicle.EngineType == TEngineType::ElectricInductionMotor ) { - if( Vehicle.InverterFrequency > 0.001 ) { - - for( auto &motor : acmotors ) { - motor - .pitch( motor.m_frequencyoffset + motor.m_frequencyfactor * Vehicle.InverterFrequency ) - .gain( motor.m_amplitudeoffset + motor.m_amplitudefactor * std::sqrt( std::abs( Vehicle.eimv_pr ) ) ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - } - else { - for( auto &motor : acmotors ) { - motor.stop(); - } - } - } - } - // motor blowers - if( false == motorblowers.empty() ) { - for( auto &blowersound : motorblowers ) { - // match the motor blower and the sound source based on whether they're located in the front or the back of the vehicle - auto const &blower { Vehicle.MotorBlowers[ ( blowersound.offset().z > 0 ? end::front : end::rear ) ] }; - // TODO: for the sounds with provided bookends invoke stop() when the stop is triggered and revolutions start dropping, instead of after full stop - if( blower.revolutions > 1 ) { - // NOTE: for motorblowers with fixed speed if the sound has defined bookends we skip revolutions-based part of frequency/volume adjustments - auto const revolutionmodifier { Vehicle.MotorBlowers[end::front].speed < 0.f && blowersound.has_bookends() ? 1.f : blower.revolutions }; - blowersound - .pitch( - true == blowersound.is_combined() ? - blower.revolutions * 0.01f : - blowersound.m_frequencyoffset + blowersound.m_frequencyfactor * revolutionmodifier ) - .gain( blowersound.m_amplitudeoffset + blowersound.m_amplitudefactor * revolutionmodifier ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - blowersound.stop(); - } - } - } - // inverter sounds - if( Vehicle.EngineType == TEngineType::ElectricInductionMotor ) { - if( Vehicle.InverterFrequency > 0.001 ) { - - volume = inverter.m_amplitudeoffset + inverter.m_amplitudefactor * std::sqrt( std::abs( Vehicle.eimv_pr) ); - - inverter - .pitch( inverter.m_frequencyoffset + inverter.m_frequencyfactor * Vehicle.InverterFrequency ) - .gain( volume ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - inverter.stop(); - } - } - // ventillator sounds - if( Vehicle.RventRot > 0.1 ) { - - rsWentylator - .pitch( rsWentylator.m_frequencyoffset + rsWentylator.m_frequencyfactor * Vehicle.RventRot ) - .gain( rsWentylator.m_amplitudeoffset + rsWentylator.m_amplitudefactor * Vehicle.RventRot ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - // ...otherwise shut down the sound - rsWentylator.stop(); - } - // radiator fan sounds - if( Vehicle.EngineType == TEngineType::DieselEngine - || Vehicle.EngineType == TEngineType::DieselElectric ) { - - if( Vehicle.dizel_heat.rpmw > 0.1 ) { - // NOTE: fan speed tends to max out at ~100 rpm; by default we try to get pitch range of 0.5-1.5 and volume range of 0.5-1.0 - radiator_fan - .pitch( 0.5 + radiator_fan.m_frequencyoffset + radiator_fan.m_frequencyfactor * Vehicle.dizel_heat.rpmw * 0.01 ) - .gain( 0.5 + radiator_fan.m_amplitudeoffset + 0.5 * radiator_fan.m_amplitudefactor * Vehicle.dizel_heat.rpmw * 0.01 ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - // ...otherwise shut down the sound - radiator_fan.stop(); - } - - if( Vehicle.dizel_heat.rpmw2 > 0.1 ) { - // NOTE: fan speed tends to max out at ~100 rpm; by default we try to get pitch range of 0.5-1.5 and volume range of 0.5-1.0 - radiator_fan_aux - .pitch( 0.5 + radiator_fan_aux.m_frequencyoffset + radiator_fan_aux.m_frequencyfactor * Vehicle.dizel_heat.rpmw2 * 0.01 ) - .gain( 0.5 + radiator_fan_aux.m_amplitudeoffset + 0.5 * radiator_fan_aux.m_amplitudefactor * Vehicle.dizel_heat.rpmw2 * 0.01 ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - // ...otherwise shut down the sound - radiator_fan_aux.stop(); - } - } - - // relay sounds - auto const soundflags { Vehicle.SoundFlag }; - if( TestFlag( soundflags, sound::relay ) ) { - // przekaznik - gdy bezpiecznik, automatyczny rozruch itp - if( true == TestFlag( soundflags, sound::shuntfield ) ) { - // shunt field - motor_shuntfield - .pitch( - true == motor_shuntfield.is_combined() ? - Vehicle.ScndCtrlActualPos * 0.01f : - motor_shuntfield.m_frequencyoffset + motor_shuntfield.m_frequencyfactor * 1.f ) - .gain( - motor_shuntfield.m_amplitudeoffset + ( - true == TestFlag( soundflags, sound::loud ) ? - 1.0f : - 0.8f ) - * motor_shuntfield.m_amplitudefactor ) - .play(); - } - else if( true == TestFlag( soundflags, sound::parallel ) ) { - // parallel mode - if( TestFlag( soundflags, sound::loud ) ) { - dsbWejscie_na_bezoporow.play(); - } - else { - motor_parallel.play(); - } - } - else { - // series mode - motor_relay - .pitch( - true == motor_relay.is_combined() ? - Vehicle.MainCtrlActualPos * 0.01f : - motor_relay.m_frequencyoffset + motor_relay.m_frequencyfactor * 1.f ) - .gain( - motor_relay.m_amplitudeoffset + ( - true == TestFlag( soundflags, sound::loud ) ? - 1.0f : - 0.8f ) - * motor_relay.m_amplitudefactor ) - .play(); - } - } - - if( Vehicle.Vel > 0.1 ) { - transmission - .pitch( transmission.m_frequencyoffset + transmission.m_frequencyfactor * Vehicle.Vel ) - .gain( transmission.m_amplitudeoffset + transmission.m_amplitudefactor * Vehicle.Vel ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - transmission.stop(); - } -} - - -namespace { - -// a train on the same track this close to the end of the player's train is taken into the physical coupler model [m] -constexpr double coupler_physics_reach { 200.0 }; -// and let go of once none of its vehicles is this close to the player's train [m]; farther than the reach, so that -// the trains don't switch to and fro between the models -constexpr double coupler_physics_release { 500.0 }; - -// the vehicle and those coupled with it, one after the other -std::vector -coupled_train( TDynamicObject *Vehicle ) { - - std::vector train { Vehicle }; - for( int direction = end::front; direction <= end::rear; ++direction ) { - auto *vehicle { Vehicle }; - auto side { direction }; - // a train of more vehicles than are on the tracks would be one coupled into a ring - while( train.size() < 10000 ) { - auto const &mover { *vehicle->MoverParameters }; - auto *next { mover.Neighbours[ side ].vehicle }; - if( next == nullptr - || false == mover.Couplers[ side ].CouplingFlag.HasAny(Coupling::coupler) - || std::ranges::find( train, next ) != train.end() ) { - break; - } - train.emplace_back( next ); - // onwards from the end of the next vehicle away from this one - side = 1 - mover.Neighbours[ side ].vehicle_end; - vehicle = next; - } - } - return train; -} - -// the trains on the same track the player's train is closing in on: those found at its free ends, near enough -std::vector -trains_closing_in( std::vector const &Train ) { - - std::vector trains; - for( auto *vehicle : Train ) { - for( int side = end::front; side <= end::rear; ++side ) { - auto const &mover { *vehicle->MoverParameters }; - auto const &neighbour { mover.Neighbours[ side ] }; - if( neighbour.vehicle == nullptr - || mover.Couplers[ side ].CouplingFlag.HasAny(Coupling::coupler) - || neighbour.distance > coupler_physics_reach - || std::ranges::find( Train, neighbour.vehicle ) != Train.end() ) { - continue; - } - std::ranges::copy( coupled_train( neighbour.vehicle ), std::back_inserter( trains ) ); - } - } - return trains; -} - -// whether any vehicle of the train is within the distance of any vehicle of the other one -bool -trains_within( std::vector const &Train, std::vector const &Other, double const Distance ) { - - return std::ranges::any_of( Train, [&]( TDynamicObject const *Vehicle ) { - return std::ranges::any_of( Other, [&]( TDynamicObject const *Othervehicle ) { - return glm::distance( Vehicle->GetPosition(), Othervehicle->GetPosition() ) <= Distance; } ); } ); -} - -} // namespace - -// the physical coupler model covers the player's train and the trains it closes in on, on the same track; the others -// keep the legacy model, as the AI drives them in it -void -vehicle_table::update_coupler_physics() const { - - if( false == Global.coupler_physics - || true == Global.coupler_physics_all ) { - return; - } - auto *player { simulation::Train != nullptr ? simulation::Train->Dynamic() : nullptr }; - std::vector train; - if( player != nullptr ) { - train = coupled_train( player ); - } - std::unordered_set covered { train.begin(), train.end() }; - for( auto *vehicle : trains_closing_in( train ) ) { - covered.insert( vehicle ); - } - - std::unordered_set checked; - for( auto *vehicle : m_items ) { - if( covered.contains( vehicle ) ) { - vehicle->MoverParameters->CouplerPhysics = true; - continue; - } - if( false == vehicle->MoverParameters->CouplerPhysics - || checked.contains( vehicle ) ) { - continue; - } - // a train taken in before stays in the model until it's far from the player's one, all of it alike - auto const other { coupled_train( vehicle ) }; - checked.insert( other.begin(), other.end() ); - if( false == trains_within( other, train, coupler_physics_release ) ) { - for( auto *othervehicle : other ) { - othervehicle->MoverParameters->CouplerPhysics = false; - } - } - } -} - -// legacy method, calculates changes in simulation state over specified time -void -vehicle_table::update( double Deltatime, int Iterationcount ) { - // Ra: w zasadzie to trzeba by utworzyć oddzielną listę taboru do liczenia fizyki - // na którą by się zapisywały wszystkie pojazdy będące w ruchu - // pojazdy stojące nie potrzebują aktualizacji, chyba że np. ktoś im zmieni nastawę hamulca - // oddzielną listę można by zrobić na pojazdy z napędem, najlepiej posortowaną wg typu napędu - // what the update goes through, for the debug panel. the counts are of the last call in the frame - auto &counts { Timer::subsystem.vehicles }; - counts.all = static_cast( m_items.size() ); - counts.enabled = counts.road = counts.ai = counts.active = 0; - counts.kind = {}; - counts.standing = {}; - counts.awake = {}; - counts.steps += static_cast( std::max( Iterationcount, 1 ) ); - // the kind of each vehicle: rail or road, near the camera or farther. the time of each vehicle in the loops below goes to its - // kind, measured from the end of the one before it - static std::vector kinds; - kinds.resize( m_items.size() ); - // road vehicles far from the camera with nobody inside go by one step of the physics in the frame, as long as all the steps - // together (Global.physics_roadlod): their movement goes on, in coarser steps nobody is close enough to tell - // not in a network session: which vehicles go coarse depends on the camera of each machine, so their movement and the draws of - // Random() they make would part ways between the machines. nor with physics.fullphysics off, whose steps are long already: one - // step for all of them would be the time of the whole frame, with the collisions looked at once in it - static std::vector coarse; - coarse.assign( m_items.size(), 0 ); - auto const roadlod { - Global.physics_roadlod - && Global.FullPhysics - && 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 ) { - auto const *vehicle { m_items[ index ] }; - auto const road { ( vehicle->MoverParameters->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 == vehicle->bEnabled ) { continue; } - ++counts.kind[ kinds[ index ] ]; - auto const *mover { vehicle->MoverParameters }; - if( mover->Vel < 0.01 ) { - ++counts.standing[ kinds[ index ] ]; - if( ( false == road ) && mover->PhysicActivation ) { - // the test of TMoverParameters::ComputeTotalForce(), part by part - auto const moving = []( neighbour_data const &Neighbour ) { - return ( Neighbour.vehicle != nullptr ) - && ( ( Neighbour.vehicle->MoverParameters->Vel > 0.0001 ) || Neighbour.vehicle->MoverParameters->accelerating() ); }; - auto &awake { counts.awake }; - ++awake.vehicles; - if( mover->CabActive != 0 ) { ++awake.cab; } - if( mover->Vel > 0.0001 ) { ++awake.speed; } - if( mover->accelerating() ) { ++awake.acceleration; } - if( mover->LastSwitchingTime < 5 ) { ++awake.switching; } - if( mover->is_multiple_unit() ) { ++awake.multipleunit; } - if( moving( mover->Neighbours[ end::front ] ) || moving( mover->Neighbours[ end::rear ] ) ) { ++awake.neighbour; } - } - } - } - auto const lap = [ & ]( std::size_t const Index, std::array &Times, std::chrono::steady_clock::time_point &Mark ) { - auto const now { std::chrono::steady_clock::now() }; - if( Index < kinds.size() ) { - Times[ kinds[ Index ] ].add( std::chrono::duration( now - Mark ).count() ); - } - Mark = now; - }; - for( auto const *vehicle : m_items ) { - if( false == vehicle->bEnabled ) { continue; } - ++counts.enabled; - if( vehicle->MoverParameters->CategoryFlag & 2 ) { ++counts.road; } - if( ( vehicle->Mechanik != nullptr ) && vehicle->Mechanik->AIControllFlag ) { ++counts.ai; } - if( vehicle->MoverParameters->PhysicActivation || vehicle->MechInside ) { ++counts.active; } - } - - Timer::subsystem.vehicles_prepare.start(); - for( auto *vehicle : m_items ) { - if( false == vehicle->bEnabled ) { continue; } - // Ra: zmienić warunek na sprawdzanie pantografów w jednej zmiennej: czy pantografy i czy podniesione - if( vehicle->MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector ) { - update_traction( vehicle ); - } - vehicle->MoverParameters->ComputeConstans(); - vehicle->update_neighbours(); - } - update_coupler_physics(); - Timer::subsystem.vehicles_prepare.stop(); - Timer::subsystem.vehicles_forces.start(); - auto const totaltime { Deltatime * Iterationcount }; // całkowity czas - // the steps of the physics on many threads (Global.performance_multithreading), as many as the work is worth: a thread for each - // STEPS_PER_THREAD steps of vehicles with the physics on, up to all the cores. not in a network session (network.server, - // .client), which keeps the draws of Random() in step across the machines: the threads have engines of their own. the messages - // to external programs (Global.iMultiplayer) don't mind - auto constexpr STEPS_PER_THREAD { 128 }; - std::size_t work { 0 }; - for( std::size_t index = 0; index < m_items.size(); ++index ) { - auto const *vehicle { m_items[ index ] }; - if( vehicle->MoverParameters->PhysicActivation || vehicle->MechInside ) { - work += ( coarse[ index ] != 0 ? 1 : static_cast( std::max( Iterationcount, 1 ) ) ); - } - } - auto const network { ( false == Global.network_servers.empty() ) || Global.network_client.has_value() }; - auto const threads { ( - network ? - 1 : - std::min( worker_pool::capacity(), std::max( 1, ( work + STEPS_PER_THREAD / 2 ) / STEPS_PER_THREAD ) ) ) }; - // what keeps them in one thread, for the debug panel - counts.capacity = static_cast( worker_pool::capacity() ); - counts.singlethread = ( - false == Global.performance_multithreading ? std::string{ "performance.multithreading off" } : - network ? std::string{ "network session" } : - threads <= 1 ? std::string{ "too little work" } : - std::string{} ); - counts.threads = 1; - auto const parallel { ( threads > 1 ) && update_steps_parallel( Deltatime, Iterationcount, coarse, threads ) }; - if( parallel ) { - counts.threads = static_cast( threads ); - } - else { - if( threads > 1 ) { - counts.singlethread = "a vehicle coupled with one it doesn't see"; - } - auto mark { std::chrono::steady_clock::now() }; - if( Iterationcount > 1 ) { - // ABu: ponizsze wykonujemy tylko jesli wiecej niz jedna iteracja - for( int iteration = 0; iteration < Iterationcount - 1; ++iteration ) { - std::size_t index { 0 }; - for( auto *vehicle : m_items ) { - if( ( index >= coarse.size() ) || ( coarse[ index ] == 0 ) ) { - vehicle->UpdateForce( Deltatime ); - } - lap( index++, Timer::subsystem.vehicles_forces_kind, mark ); - } - index = 0; - for( auto *vehicle : m_items ) { - if( ( index >= coarse.size() ) || ( coarse[ index ] == 0 ) ) { - vehicle->FastUpdate( Deltatime ); - } - lap( index++, Timer::subsystem.vehicles_forces_kind, mark ); - } - update_brake_pipes( Deltatime ); - } - } - { - std::size_t index { 0 }; - for( auto *vehicle : m_items ) { - // the vehicles going by one step take it with the time of all of them - auto const coarsestep { ( index < coarse.size() ) && ( coarse[ index ] != 0 ) }; - vehicle->UpdateForce( coarsestep ? totaltime : Deltatime ); - lap( index++, Timer::subsystem.vehicles_forces_kind, mark ); - } - } - } - Timer::subsystem.vehicles_forces.stop(); - - update_off_track_contacts( totaltime ); - - Timer::subsystem.vehicles_update.start(); - { - std::size_t index { 0 }; - auto mark { std::chrono::steady_clock::now() }; - for( auto *vehicle : m_items ) { - auto const coarsestep { ( index < coarse.size() ) && ( coarse[ index ] != 0 ) }; - // Ra 2015-01: tylko tu przelicza sieć trakcyjną - vehicle->Update( coarsestep ? totaltime : Deltatime, totaltime ); - lap( index++, Timer::subsystem.vehicles_update_kind, mark ); - } - } - update_brake_pipes( Deltatime ); - Timer::subsystem.vehicles_update.stop(); - - // jeśli jest coś do usunięcia z listy, to trzeba na końcu - erase_disabled(); - - // the odometers are saved now and then, a crash doesn't lose more than the last minute - m_odometersavetimer += totaltime; - if( m_odometersavetimer >= 60.0 ) { - save_odometers(); - } -} - -namespace { - -// the body of the vehicle as it stands, for the contacts: off the track by its motion, on the track upright on it -derail_motion::footprint footprint_of( TDynamicObject const &Vehicle ) { - - auto const &mover { *Vehicle.MoverParameters }; - derail_motion::pose pose; - if( mover.OffTrack.active() ) { - pose = mover.OffTrack.current(); - } - else { - pose.position = Vehicle.GetPosition(); - pose.front = Vehicle.VectorFront(); - pose.left = Vehicle.VectorLeft(); - pose.up = Vehicle.VectorUp(); - } - auto const &shape { mover.OffTrack.shape() }; - return derail_motion::footprint_of( - pose, mover.Dim.L, - mover.OffTrack.active() ? shape.width : ( mover.Dim.W > 0.5 ? mover.Dim.W : 3.0 ), - mover.OffTrack.active() ? shape.height : ( mover.Dim.H > 2.0 ? mover.Dim.H : 4.0 ) ); -} - -// the vehicle as a body in a contact -derail_motion::contact_body contact_body_of( TDynamicObject const &Vehicle ) { - - auto const &mover { *Vehicle.MoverParameters }; - derail_motion::contact_body body; - body.mass = mover.TotalMass; - if( mover.OffTrack.active() ) { - body.base = mover.OffTrack.base(); - body.velocity = mover.OffTrack.velocity(); - body.yaw_rate = mover.OffTrack.yaw_rate(); - body.gyration = mover.OffTrack.gyration(); - } - else { - // on the rails it goes along them only - glm::dvec3 const front { Vehicle.VectorFront().x, 0.0, Vehicle.VectorFront().z }; - auto const length { glm::length( front ) }; - body.guided = true; - body.guide = length > 1e-6 ? front / length : glm::dvec3 { 0.0, 0.0, 1.0 }; - body.base = Vehicle.GetPosition(); - body.velocity = body.guide * mover.V; - } - return body; -} - -// how the two came to overlap, for the log -std::string_view overlap_kind( TDynamicObject const &First, TDynamicObject const &Second ) { - - auto const offtrack { First.MoverParameters->OffTrack.active() && Second.MoverParameters->OffTrack.active() }; - for( int end = end::front; end <= end::rear; ++end ) { - if( First.MoverParameters->Couplers[ end ].Connected == Second.MoverParameters - && First.MoverParameters->Couplers[ end ].CouplingFlag != Coupling::none ) { - return offtrack ? "coupled, both off the track" : "coupled, one on the rails"; - } - if( First.MoverParameters->Neighbours[ end ].vehicle == &Second ) { - return offtrack ? "neighbours, both off the track" : "neighbours, one on the rails"; - } - } - return offtrack ? "not neighbours, both off the track" : "not neighbours, one on the rails"; -} - -} // namespace - -void -vehicle_table::update_off_track_contacts( double const Deltatime ) { - - if( Global.derailment != global_settings::derailment_model::physical || Deltatime <= 0.0 ) { - return; - } - // by their places in the table: the order the pairs are taken in is the same in every run - std::vector offtrack; - for( std::size_t index = 0; index < m_items.size(); ++index ) { - if( m_items[ index ]->bEnabled && m_items[ index ]->MoverParameters->OffTrack.active() ) { - offtrack.push_back( index ); - } - } - if( offtrack.empty() ) { - return; - } - auto const started { off_track_clock::now() }; - auto deepest { 0.0 }; - std::string deepestpair; - auto resting { true }; - for( auto const place : offtrack ) { - auto *vehicle { m_items[ place ] }; - resting = resting && vehicle->MoverParameters->OffTrack.at_rest(); - auto const print { footprint_of( *vehicle ) }; - auto const reach { std::hypot( print.half_length, print.half_width ) }; - for( std::size_t otherplace = 0; otherplace < m_items.size(); ++otherplace ) { - auto *other { m_items[ otherplace ] }; - if( otherplace == place || false == other->bEnabled ) { - continue; - } - // each pair of two off the track once - auto const otheroff { other->MoverParameters->OffTrack.active() }; - if( otheroff && otherplace < place ) { - continue; - } - // the bounding circles first - auto const apart { other->GetPosition() - vehicle->GetPosition() }; - auto const otherreach { 0.5 * other->MoverParameters->Dim.L + std::max( other->MoverParameters->Dim.W, other->MoverParameters->Dim.H ) }; - if( glm::length( glm::dvec3 { apart.x, 0.0, apart.z } ) > reach + otherreach + 1.0 ) { - continue; - } - auto const otherprint { footprint_of( *other ) }; - auto const hit { derail_motion::collide( print, otherprint ) }; - if( false == hit.has_value() ) { - continue; - } - if( hit->depth > deepest ) { - deepest = hit->depth; - deepestpair = std::format( "{} and {}, {}", vehicle->MoverParameters->Name, other->MoverParameters->Name, overlap_kind( *vehicle, *other ) ); - } - auto const body { contact_body_of( *vehicle ) }; - auto const otherbody { contact_body_of( *other ) }; - auto const impulse { derail_motion::contact_impulse( *hit, body, otherbody ) }; - // the one off the track: kicked, and moved out of the other one (half of the way when both are off it) - auto const [ velocity, yawrate ] { derail_motion::impulse_change( body, -impulse, hit->point ) }; - auto &motion { vehicle->MoverParameters->OffTrack }; - auto const share { otheroff ? 0.5 : 1.0 }; - auto const correction { derail_motion::contact_correction * std::max( 0.0, hit->depth - derail_motion::contact_slop ) }; - if( glm::length( impulse ) > 0.0 ) { - motion.kick( velocity, yawrate ); - vehicle->MoverParameters->V = motion.speed(); - } - if( correction > 0.0 ) { - motion.nudge( -hit->normal * ( share * correction ) ); - vehicle->place_off_track(); - } - if( otheroff ) { - auto const [ othervelocity, otheryawrate ] { derail_motion::impulse_change( otherbody, impulse, hit->point ) }; - auto &othermotion { other->MoverParameters->OffTrack }; - if( glm::length( impulse ) > 0.0 ) { - othermotion.kick( othervelocity, otheryawrate ); - other->MoverParameters->V = othermotion.speed(); - } - if( correction > 0.0 ) { - othermotion.nudge( hit->normal * ( share * correction ) ); - other->place_off_track(); - } - continue; - } - // one on the rails: along them into its speed, across them on its wheels, as a coupling pulls them off - auto &othermover { *other->MoverParameters }; - othermover.V += glm::dot( impulse, otherbody.guide ) / std::max( othermover.TotalMass, 1.0 ); - if( othermover.DamageFlag.HasAll(VehicleDamage::derailed) ) { - continue; - } - glm::dvec3 const otherleft { otherbody.guide.z, 0.0, -otherbody.guide.x }; - auto const across { glm::dot( impulse, otherleft ) / Deltatime }; - auto const mass { othermover.TotalMass - othermover.Mred }; - auto const ratio { derail_motion::pull_ratio( std::abs( across ), 0.5 * std::numbers::pi, mass, othermover.NAxles ) }; - // held over the window of the climbing as the bodies slide along each other, or a hit three times as hard - // at once: the wheels jump the rail - auto const sliding { glm::length( derail_motion::velocity_at( body, hit->point ) - otherbody.velocity ) * Deltatime }; - if( other->m_struck.update( ratio >= derailment::climbing_limit, sliding ) || ratio >= 3.0 * derailment::climbing_limit ) { - othermover.pull_off( - across >= 0.0 ? 1 : -1, - mass > 0.0 ? std::abs( across ) / mass : 0.0, - std::format( "Y/Q {:.2f} from {} running into it, {:.0f} kN across", ratio, vehicle->MoverParameters->Name, std::abs( across ) / 1000.0 ) ); - other->m_struck.reset(); - } - } - } - // the log: every second the most the bodies overlapped by, once more when all of them are at rest - if( deepest > m_overlapmost ) { - m_overlapmost = deepest; - m_overlappair = deepestpair; - } - m_overlapdue -= Deltatime; - if( ( m_overlapdue <= 0.0 && false == resting ) || ( resting && false == m_overlaplogged ) ) { - WriteLog( std::format( - "derailment: the bodies overlap by up to {:.2f} m{} over the last second, {:.2f} m now{}", - m_overlapmost, m_overlapmost > 0.0 ? " (" + m_overlappair + ")" : std::string {}, deepest, resting ? ", all at rest" : "" ) ); - m_overlapmost = 0.0; - m_overlappair.clear(); - m_overlapdue = 1.0; - m_overlaplogged = resting; - } - if( false == resting ) { - m_overlaplogged = false; - } - auto const took { seconds_since( started ) }; - if( took > off_track_slow ) { - ErrorLog( std::format( "derailment: warning: the contacts of {} vehicles off the track took {:.0f} ms", offtrack.size(), took * 1000.0 ) ); - } -} - -std::shared_ptr -vehicle_table::off_track_terrain( glm::dvec2 const &Min, glm::dvec2 const &Max ) { - - std::erase_if( m_offtrackterrains, []( auto const &Terrain ) { return Terrain.expired(); } ); - for( auto const &terrain : m_offtrackterrains ) { - if( auto shared { terrain.lock() }; shared != nullptr && shared->covers( Min, Max ) ) { - return shared; - } - } - return {}; -} - -void -vehicle_table::share_off_track_terrain( std::shared_ptr const &Terrain ) { - - if( Terrain != nullptr ) { - m_offtrackterrains.emplace_back( Terrain ); - } -} - -// the air exchange through the brake and main reservoir hoses of the vehicles which stepped their physics, after all of them did -void -vehicle_table::update_brake_pipes( double const Deltatime ) { - - m_brakepipes.clear(); - for( auto *vehicle : m_items ) { - if( ( true == vehicle->MoverParameters->PipeCouplersPending ) - || ( true == vehicle->MoverParameters->ScndPipeCouplersPending ) ) { - m_brakepipes.push_back( vehicle->MoverParameters ); - } - } - TMoverParameters::UpdatePipeCouplers( m_brakepipes, Deltatime ); -} - -// records the odometer states of the vehicles and saves them for the next sessions (eu07/maszyna#72) -void -vehicle_table::save_odometers() { - - m_odometersavetimer = 0.0; - auto &odometers { odometer::states() }; - for( auto const *vehicle : m_items ) { - if( vehicle->MoverParameters != nullptr ) { - odometer::record( odometers, vehicle->name(), vehicle->MoverParameters->HasDriverCab(), vehicle->MoverParameters->Odometer ); - } - } - odometer::save(); -} - -// the steps of the physics of vehicle_table::update() (UpdateForce() and FastUpdate() of each vehicle, Iterationcount times) on up -// to Threads threads of worker_pool. a step acts on the vehicle itself, on the ones coupled with it, and on the ones seen ahead or -// behind it (CollisionDetect() changes the speed of the other one); the movement along the tracks, the events and the sounds wait -// for Update(). so the vehicles are put in groups which act on nothing outside them, and each group goes through all its steps in -// one thread, its vehicles in their order, the groups at once: what doing them one by one gives. the groups of vehicles exchanging -// their load, which can load the models of it, are done in the main thread. Coarse: as in update(). returns false, having done -// nothing, when a vehicle is coupled with one it doesn't see next to it, which the groups don't account for -bool -vehicle_table::update_steps_parallel( double const Deltatime, int const Iterationcount, std::vector const &Coarse, std::size_t const Threads ) { - - auto const itemcount { m_items.size() }; - for( std::size_t index = 0; index < itemcount; ++index ) { - m_items[ index ]->m_tableindex = static_cast( index ); - } - // the groups, by joining the vehicles with the ones they act on. the coupled ones are those next to them - m_groupparent.resize( itemcount ); - std::iota( std::begin( m_groupparent ), std::end( m_groupparent ), 0u ); - auto const root = [ this ]( std::uint32_t Index ) { - while( m_groupparent[ Index ] != Index ) { - m_groupparent[ Index ] = m_groupparent[ m_groupparent[ Index ] ]; - Index = m_groupparent[ Index ]; - } - return Index; }; - for( std::size_t index = 0; index < itemcount; ++index ) { - auto const *mover { m_items[ index ]->MoverParameters }; - for( auto const end : { end::front, end::rear } ) { - auto const *neighbour { mover->Neighbours[ end ].vehicle }; - if( ( mover->Couplers[ end ].Connected != nullptr ) - && ( ( neighbour == nullptr ) || ( neighbour->MoverParameters != mover->Couplers[ end ].Connected ) ) ) { - return false; - } - if( neighbour == nullptr ) { continue; } - auto const other { neighbour->m_tableindex }; - if( ( other >= itemcount ) || ( m_items[ other ] != neighbour ) ) { - // not in the table, shouldn't happen - return false; - } - auto const left { root( static_cast( index ) ) }; - auto const right { root( other ) }; - if( left != right ) { - m_groupparent[ std::max( left, right ) ] = std::min( left, right ); - } - } - } - auto constexpr none { std::numeric_limits::max() }; - m_groupof.assign( itemcount, none ); - std::size_t groupcount { 0 }; - for( std::size_t index = 0; index < itemcount; ++index ) { - auto &group { m_groupof[ root( static_cast( index ) ) ] }; - if( group == none ) { - group = static_cast( groupcount++ ); - if( m_groups.size() < groupcount ) { m_groups.emplace_back(); } - m_groups[ group ].clear(); - } - m_groups[ group ].push_back( static_cast( index ) ); - } - // the groups done in the main thread, and the others largest first, for the threads to end close to one another - m_threadgroups.clear(); - m_maingroups.clear(); - std::size_t largest { 0 }; - for( std::size_t group = 0; group < groupcount; ++group ) { - largest = std::max( largest, m_groups[ group ].size() ); - auto const loading { std::any_of( - std::begin( m_groups[ group ] ), std::end( m_groups[ group ] ), - [ this ]( std::uint32_t const Index ) { - auto const *vehicle { m_items[ Index ] }; - return ( vehicle->MoverParameters->LoadStatus != 0 ) || ( vehicle->LoadExchangeTime() > 0.f ); } ) }; - ( loading ? m_maingroups : m_threadgroups ).push_back( static_cast( group ) ); - } - std::sort( - std::begin( m_threadgroups ), std::end( m_threadgroups ), - [ this ]( std::uint32_t const Left, std::uint32_t const Right ) { - return m_groups[ Left ].size() > m_groups[ Right ].size(); } ); - auto &counts { Timer::subsystem.vehicles }; - counts.groups = static_cast( groupcount ); - counts.largestgroup = static_cast( largest ); - counts.maingroups = static_cast( m_maingroups.size() ); - - // all the steps of a group, in the order update() makes them - auto const totaltime { Deltatime * Iterationcount }; - auto const coarse = [ & ]( std::uint32_t const Index ) { - return ( Index < Coarse.size() ) && ( Coarse[ Index ] != 0 ); }; - // the draws of Random() a group makes come from an engine of its own, seeded from the run's engine and the group: the same in - // every run of a seed, whichever thread takes the group (the engines of the threads are seeded at random) - 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 ); - // 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; - if( Iterationcount > 1 ) { - // ABu: ponizsze wykonujemy tylko jesli wiecej niz jedna iteracja - for( int iteration = 0; iteration < Iterationcount - 1; ++iteration ) { - for( auto const index : members ) { - if( false == coarse( index ) ) { m_items[ index ]->UpdateForce( Deltatime ); } - } - for( auto const index : members ) { - if( false == coarse( index ) ) { m_items[ index ]->FastUpdate( Deltatime ); } - } - pipes.clear(); - for( auto const index : members ) { - auto *mover { m_items[ index ]->MoverParameters }; - if( mover->PipeCouplersPending || mover->ScndPipeCouplersPending ) { - pipes.push_back( mover ); - } - } - TMoverParameters::UpdatePipeCouplers( pipes, Deltatime ); - } - } - for( auto const index : members ) { - // 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 ); }; - - Workers().run( - m_threadgroups.size(), Threads, - [ & ]( std::size_t const Group ) { - steps( m_threadgroups[ Group ] ); } ); - for( auto const group : m_maingroups ) { - steps( group ); - } - return true; -} - -// legacy method, checks for presence and height of traction wire for specified vehicle -void -vehicle_table::update_traction( TDynamicObject *Vehicle ) { - auto const vFront = Vehicle->VectorFront(); // wektor normalny dla płaszczyzny ruchu pantografu - auto const vUp = Vehicle->VectorUp(); // wektor pionu pudła (pochylony od pionu na przechyłce) - auto const vLeft = Vehicle->VectorLeft(); // wektor odległości w bok (odchylony od poziomu na przechyłce) - auto const position = Vehicle->GetPosition(); // współrzędne środka pojazdu - - for( int pantographindex = 0; pantographindex < Vehicle->iAnimType[ ANIM_PANTS ]; ++pantographindex ) { - // pętla po pantografach - auto *pantograph { Vehicle->pants[ pantographindex ].fParamPants }; - if( true == Vehicle->MoverParameters->Pantographs[ pantographindex ].is_active ) { - // jeśli pantograf podniesiony - auto const pant0 { position + vLeft * pantograph->vPos.z + vUp * pantograph->vPos.y + vFront * pantograph->vPos.x }; - if( pantograph->hvPowerWire != nullptr ) { - // jeżeli znamy drut z poprzedniego przebiegu - for( int attempts = 0; attempts < 30; ++attempts ) { - // sanity check. shouldn't happen in theory, but did happen in practice - if( pantograph->hvPowerWire == nullptr ) { break; } - - // powtarzane aż do znalezienia odpowiedniego odcinka na liście dwukierunkowej - if( pantograph->hvPowerWire->iLast & 0x3 ) { - // dla ostatniego i przedostatniego przęsła wymuszamy szukanie innego - // nie to, że nie ma, ale trzeba sprawdzić inne - pantograph->hvPowerWire = nullptr; - break; - } - if( pantograph->hvPowerWire->hvParallel ) { - // jeśli przęsło tworzy bieżnię wspólną, to trzeba sprawdzić pozostałe - // nie to, że nie ma, ale trzeba sprawdzić inne - pantograph->hvPowerWire = nullptr; - break; - } - // obliczamy wyraz wolny równania płaszczyzny (to miejsce nie jest odpowienie) - // podstawiamy równanie parametryczne drutu do równania płaszczyzny pantografu - // TODO: investigate this routine with reardriver/negative speed, does it picks the right wire? - auto const fRaParam = - -( glm::dot( pantograph->hvPowerWire->pPoint1, vFront ) - glm::dot( pant0, vFront ) ) - / glm::dot( pantograph->hvPowerWire->vParametric, vFront ); - - if( fRaParam < -0.001 ) { - // histereza rzędu 7cm na 70m typowego przęsła daje 1 promil - pantograph->hvPowerWire = pantograph->hvPowerWire->hvNext[ 0 ]; - continue; - } - if( fRaParam > 1.001 ) { - pantograph->hvPowerWire = pantograph->hvPowerWire->hvNext[ 1 ]; - continue; - } - // jeśli t jest w przedziale, wyznaczyć odległość wzdłuż wektorów vUp i vLeft - // punkt styku płaszczyzny z drutem (dla generatora łuku el.) - auto const vStyk { pantograph->hvPowerWire->pPoint1 + fRaParam * pantograph->hvPowerWire->vParametric }; - auto const vGdzie { vStyk - pant0 }; // wektor - // odległość w pionie musi być w zasięgu ruchu "pionowego" pantografu - // musi się mieścić w przedziale ruchu pantografu - auto const fVertical { glm::dot( vGdzie, vUp ) }; - // odległość w bok powinna być mniejsza niż pół szerokości pantografu - // to się musi mieścić w przedziale zależnym od szerokości pantografu - auto const fHorizontal { std::abs( glm::dot( vGdzie, vLeft ) ) - pantograph->fWidth }; - // jeśli w pionie albo w bok jest za daleko, to dany drut jest nieużyteczny - if( fHorizontal <= 0.0 ) { - // koniec pętli, aktualny drut pasuje - pantograph->PantTraction = fVertical; - break; - } - else { - // the wire is outside contact area and as of now we don't have good detection of parallel sections - // as such there's no guaratee there isn't parallel section present. - // therefore we don't bother checking if the wire is still within range of guide horns - // but simply force area search for potential better option - pantograph->hvPowerWire = nullptr; - break; - } - } - } - - if( pantograph->hvPowerWire == nullptr ) { - // look in the region for a suitable traction piece if we don't already have any - simulation::Region->update_traction( Vehicle, pantographindex ); - } - - if( pantograph->hvPowerWire == nullptr - && false == Global.bLiveTraction ) { - // jeśli drut nie znaleziony ale można oszukiwać to dajemy coś tam dla picu - Vehicle->pants[ pantographindex ].fParamPants->PantTraction = 1.4; - } - } - else { - // pantograph is down - pantograph->hvPowerWire = nullptr; - } - } -} - -// legacy method, sends list of vehicles over network -void -vehicle_table::DynamicList( bool const Onlycontrolled ) const { - // odesłanie nazw pojazdów dostępnych na scenerii (nazwy, szczególnie wagonów, mogą się powtarzać!) - for( auto const *vehicle : m_items ) { - if( false == Onlycontrolled - || vehicle->Mechanik != nullptr ) { - // same nazwy pojazdów - multiplayer::WyslijString( vehicle->asName, 6 ); - } - } - // informacja o końcu listy - multiplayer::WyslijString( "none", 6 ); -} - -// maintenance; removes from tracks consists with vehicles marked as disabled -bool -vehicle_table::erase_disabled() { - - if( false == TDynamicObject::bDynamicRemove ) { return false; } - - // go through the list and retrieve vehicles scheduled for removal... - type_sequence disabledvehicles; - for( auto *vehicle : m_items ) { - if( false == vehicle->bEnabled ) { - disabledvehicles.emplace_back( vehicle ); - } - } - // ...now propagate removal flag through affected consists... - for( auto *vehicle : disabledvehicles ) { - TDynamicObject *coupledvehicle { vehicle }; - while( ( coupledvehicle = coupledvehicle->Next() ) != nullptr ) { - coupledvehicle->bEnabled = false; - } - // (try to) run propagation in both directions, it's simpler than branching based on direction etc - coupledvehicle = vehicle; - while( ( coupledvehicle = coupledvehicle->Prev() ) != nullptr ) { - coupledvehicle->bEnabled = false; - } - } - // ...then actually remove all disabled vehicles... - auto vehicleiter = std::begin( m_items ); - while( vehicleiter != std::end( m_items ) ) { - - auto *vehicle { *vehicleiter }; - - if( true == vehicle->bEnabled ) { - ++vehicleiter; - } - else { - // the distance the vehicle ran goes in the odometer store now, it doesn't depend on the vehicle being - // kept on the list until the next save (eu07/maszyna#72) - if( vehicle->MoverParameters != nullptr ) { - odometer::record( odometer::states(), vehicle->name(), vehicle->MoverParameters->HasDriverCab(), vehicle->MoverParameters->Odometer ); - } - if( vehicle->MyTrack != nullptr - && true == vehicle->MyTrack->RemoveDynamicObject(vehicle) ) { - vehicle->MyTrack = nullptr; - } - if( simulation::Train != nullptr - && simulation::Train->Dynamic() == vehicle ) { - // clear potential train binding - // TBD, TODO: kill vehicle sounds - simulation::Train = nullptr; - } - simulation::Trains.purge(vehicle->name()); - // remove potential entries in the light array - simulation::Lights.remove( vehicle ); - simulation::Blackbox.vehicle_removed( vehicle ); -/* - // finally get rid of the vehicle and its record themselves - // BUG: deleting the vehicle leaves dangling pointers in event->Activator and potentially elsewhere - // TBD, TODO: either mark 'dead' vehicles with additional flag, or delete the references as well - SafeDelete( vehicle ); - vehicleiter = m_items.erase( vehicleiter ); -*/ - ++vehicleiter; // NOTE: instead of the erase in the disabled section - } - } - // ...and call it a day - TDynamicObject::bDynamicRemove = false; - - return true; -} - -// the vehicles coupled at the ends, and the ends of theirs facing this one -TDynamicObject *TDynamicObject::NextConnected() { return MoverParameters->Neighbours[ end::rear ].vehicle; } -TDynamicObject *TDynamicObject::PrevConnected() { return MoverParameters->Neighbours[ end::front ].vehicle; } -TDynamicObject *TDynamicObject::NextConnected() const { return MoverParameters->Neighbours[ end::rear ].vehicle; } -TDynamicObject *TDynamicObject::PrevConnected() const { return MoverParameters->Neighbours[ end::front ].vehicle; } -int TDynamicObject::NextConnectedNo() const { return MoverParameters->Neighbours[ end::rear ].vehicle_end; } -int TDynamicObject::PrevConnectedNo() const { return MoverParameters->Neighbours[ end::front ].vehicle_end; } - -void TDynamicObject::SetdMoveLen( double dMoveLen ) { MoverParameters->dMoveLen = dMoveLen; } -void TDynamicObject::ResetdMoveLen() { MoverParameters->dMoveLen = 0; } -double TDynamicObject::GetdMoveLen() { return MoverParameters->dMoveLen; } - -double TDynamicObject::GetVelocity() const { return MoverParameters->Vel; } -double TDynamicObject::GetLength() const { return MoverParameters->Dim.L; } -double TDynamicObject::GetWidth() const { return MoverParameters->Dim.W; } diff --git a/vehicle/dynamic/animations.cpp b/vehicle/dynamic/animations.cpp new file mode 100644 index 000000000..72a853408 --- /dev/null +++ b/vehicle/dynamic/animations.cpp @@ -0,0 +1,662 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the animated parts of a vehicle: pantographs, doors, platforms, mirrors, wipers, axles, levers, hoses, lights + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/mover.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + + +//--------------------------------------------------------------------------- +void TAnimPant::common_pantograph_settings() +{ // wspólne ustawienia, liczone po przypisaniu wymiarów ramion + vPos = glm::dvec3(0, 0, 0); + fAngleL0 = glm::radians(2.8547285515689267247882521833308); + fAngleL = fAngleL0; // początkowy kąt dolnego ramienia + fAngleU0 = acos((fLenL1 * cos(fAngleL) + fHoriz) / fLenU1); // górne ramię + fAngleU = fAngleU0; // początkowy kąt + PantWys = fLenL1 * sin(fAngleL) + fLenU1 * sin(fAngleU) + fHeight; // wysokość początkowa + PantTraction = PantWys; + hvPowerWire = nullptr; + fWidthExtra = 0.381f; //(2.032m-1.027)/2 + // poza obszarem roboczym jest aproksymacja łamaną o 5 odcinkach + fHeightExtra[0] = 0.0f; //+0.0762 + fHeightExtra[1] = -0.01f; //+0.1524 + fHeightExtra[2] = -0.03f; //+0.2286 + fHeightExtra[3] = -0.07f; //+0.3048 + fHeightExtra[4] = -0.15f; //+0.3810 +} + +void TAnimPant::AKP_4E() +{ // ustawienie wymiarów dla pantografu AKP-4E + fLenL1 = 1.22; // 1.176289 w modelach + fLenU1 = 1.755; // 1.724482197 w modelach + fHoriz = 0.535; // 0.54555075 przesunięcie ślizgu w długości pojazdu względem + // osi obrotu dolnego + // ramienia + fHeight = 0.07; // wysokość ślizgu ponad oś obrotu + fWidth = 0.635; // połowa szerokości ślizgu, 0.635 dla AKP-1 i AKP-4E + common_pantograph_settings(); +}; +void TAnimPant::WBL85() +{ // ustawienie wymiarów dla pantografu WBL88 + // mnozniki animacji ramion dla pantografu WBL88 + rd1rf = 1.f; + rd2rf = 1.2; + rg1rf = 0.875; + rg2rf = 1.0; + slizgrf = 1.f; + + fLenL1 = 1.98374; + fLenU1 = 2.14199; + fHoriz = 0.142; // 0.54555075 przesunięcie ślizgu w długości pojazdu względem + // osi obrotu dolnego ramienia + fHeight = 0.09353; // wysokość ślizgu ponad oś obrotu + fWidth = 0.4969; // połowa szerokości ślizgu + common_pantograph_settings(); +}; +void TAnimPant::EC160_200() +{ // ustawienie wymiarów dla pantografow EC160 lub EC200 + // mnozniki animacji ramion dla pantografow EC160 lub EC200 + rd1rf = 1.f; + rd2rf = 0.85; + rg1rf = 1.f; + rg2rf = 1.f; // 0.833 + slizgrf = 1.f; + + fLenL1 = 1.98374; + fLenU1 = 2.14199; + fHoriz = 0.142; // 0.54555075 przesunięcie ślizgu w długości pojazdu względem + // osi obrotu dolnego ramienia + fHeight = 0.09353; // wysokość ślizgu ponad oś obrotu + fWidth = 0.4969; // połowa szerokości ślizgu + common_pantograph_settings(); +}; +void TAnimPant::DSAx() +{ // ustawienie wymiarów dla pantografow z rodziny DSA + // mnozniki animacji ramion dla pantografow z rodziny DSA + rd1rf = 1.f; + rd2rf = 1.025; + rg1rf = 0.875; + rg2rf = 1.f; + slizgrf = 1.f; + + fLenL1 = 1.98374; + fLenU1 = 2.14199; + fHoriz = 0.142; // 0.54555075 przesunięcie ślizgu w długości pojazdu względem + // osi obrotu dolnego ramienia + fHeight = 0.09353; // wysokość ślizgu ponad oś obrotu + fWidth = 0.4969; // połowa szerokości ślizgu + common_pantograph_settings(); +}; +//--------------------------------------------------------------------------- +int TAnim::TypeSet(int i, TMoverParameters currentMover, int fl) +{ // ustawienie typu animacji i zależnej od niego ilości animowanych submodeli + fMaxDist = -1.0; // normalnie nie pokazywać + switch (i) + { // maska 0x000F: ile używa wskaźników na submodele (0 gdy jeden, + // wtedy bez tablicy) + // maska 0x00F0: + // 0-osie,1-drzwi,2-obracane,3-zderzaki,4-wózki,5-pantografy,6-tłoki + // maska 0xFF00: ile używa liczb float dla współczynników i stanu + case 0: + iFlags = 0x000; + break; // 0-oś + case 1: + iFlags = 0x010; + break; // 1-drzwi + case 2: + iFlags = 0x020; + fParam = fl ? new float[fl] : nullptr; + iFlags += fl << 8; + break; // 2-wahacz, dźwignia itp. + case 3: + iFlags = 0x030; + break; // 3-zderzak + case 4: + iFlags = 0x040; + break; // 4-wózek + case 5: // 5-pantograf - 5 submodeli + iFlags = 0x055; + fParamPants = new TAnimPant(); + switch (currentMover.EnginePowerSource.CollectorParameters.PantographType) { + case TPantType::AKP_4E: + fParamPants->AKP_4E(); + break; + case TPantType::DSAx: + fParamPants->DSAx(); + break; + case TPantType::EC160_200: + fParamPants->EC160_200(); + break; + case TPantType::WBL85: + fParamPants->WBL85(); + break; + } + + break; + case 6: + iFlags = 0x068; + break; // 6-tłok i rozrząd - 8 submodeli + case 7: + iFlags = 0x070; + break; // doorstep + case 8: + iFlags = 0x080; + break; // mirror + case 9: + iFlags = 0x023; // 2: Rotating/Motion-based, 8: Uses 3 submodels + break; + default: + iFlags = 0; + } + yUpdate = nullptr; + return iFlags & 15; // ile wskaźników rezerwować dla danego typu animacji +}; + +TAnim::~TAnim() +{ // usuwanie animacji + switch (iFlags & 0xF0) + { // usuwanie struktur, zależnie ile zostało stworzonych + case 0x20: // 2-wahacz, dźwignia itp. + delete fParam; + break; + case 0x50: // 5-pantograf + delete fParamPants; + break; + default: + break; + } +}; + +int TDynamicObject::GetPneumatic(bool front, bool red) +{ + int x, y, z; // 1=prosty, 2=skośny + if (red) + { + if (front) + { + x = btCPneumatic1.GetStatus(); + y = btCPneumatic1r.GetStatus(); + } + else + { + x = btCPneumatic2.GetStatus(); + y = btCPneumatic2r.GetStatus(); + } + } + else if (front) + { + x = btPneumatic1.GetStatus(); + y = btPneumatic1r.GetStatus(); + } + else + { + x = btPneumatic2.GetStatus(); + y = btPneumatic2r.GetStatus(); + } + z = 0; // brak węży? + if (x > 0 && y > 0) + z = 3; // dwa + if (x > 0 && y == 0) + z = 1; // lewy, brak prawego + if (x == 0 && y > 0) + z = 2; // brak lewego, prawy + + return z; +} + +void TDynamicObject::SetPneumatic(bool front, bool red) +{ + int x = 0, + ten = 0, + tamten = 0; + ten = GetPneumatic(front, red); // 1=lewy skos,2=prawy skos,3=dwa proste + if (front) + if (PrevConnected()) // pojazd od strony sprzęgu 0 + tamten = PrevConnected()->GetPneumatic(PrevConnectedNo() == end::front ? true : false, red); + if (!front) + if (NextConnected()) // pojazd od strony sprzęgu 1 + tamten = NextConnected()->GetPneumatic(NextConnectedNo() == end::front ? true : false, red); + if (ten == tamten) // jeśli układ jest symetryczny + switch (ten) + { + case 1: + x = 2; + break; // mamy lewy skos, dać lewe skosy + case 2: + x = 3; + break; // mamy prawy skos, dać prawe skosy + case 3: // wszystkie cztery na prosto + if (MoverParameters->Couplers[front ? end::front : end::rear].Render) + x = 1; + else + x = 4; + break; + } + else + { + if (ten == 2) + x = 4; + if (ten == 1) + x = 1; + if (ten == 3) + if (tamten == 1) + x = 4; + else + x = 1; + } + if (front) + { + if (red) + cp1 = x; + else + sp1 = x; + } // który pokazywać z przodu + else + { + if (red) + cp2 = x; + else + sp2 = x; + } // który pokazywać z tyłu +} + +void TDynamicObject::UpdateAxle(TAnim *pAnim) +{ // animacja osi + size_t wheel_id = pAnim->dWheelAngle; + pAnim->smAnimated->SetRotate(float3(1, 0, 0), dWheelAngle[wheel_id]); + pAnim->smAnimated->future_transform = glm::rotate((float)glm::radians(m_future_wheels_angle[wheel_id]), glm::vec3(1.0f, 0.0f, 0.0f)); +}; + +// angle of a slotted lever for given angle of the wheel, which drives the coupling rod with the pin +// all points of the coupling rod move along circles of crank radius, the lever follows the pin sliding in its slot +double TDynamicObject::slottedlever_angle( slottedlever_data const &Lever, double const Wheelangle ) { + // crank turned around X axis, the same way as the wheel + auto const wheelangle { glm::radians( Wheelangle ) }; + auto const crank { glm::dvec2( + Lever.crank.x * std::cos( wheelangle ) - Lever.crank.y * std::sin( wheelangle ), + Lever.crank.x * std::sin( wheelangle ) + Lever.crank.y * std::cos( wheelangle ) ) }; + auto const pin { Lever.pin - Lever.crank + crank }; + // angle relative to the pose of the lever in the model, which matches wheel angle 0 + return glm::degrees( std::atan2( pin.y, pin.x ) - std::atan2( Lever.pin.y, Lever.pin.x ) ); +} + +void TDynamicObject::update_slottedlevers() { + + for( auto const &lever : m_slottedlevers ) { + auto const wheelid { ( + ( lever.axle < iAnimType[ ANIM_WHEELS ] ) && ( lever.axle < static_cast( pAnimations.size() ) ) ? + pAnimations[ lever.axle ].dWheelAngle : + 1 ) }; // driving wheels and coupling rods by default + auto const angle { slottedlever_angle( lever, dWheelAngle[ wheelid ] ) }; + auto const futureangle { slottedlever_angle( lever, dWheelAngle[ wheelid ] + m_future_wheels_angle[ wheelid ] ) }; + lever.submodel->SetRotate( float3( 1, 0, 0 ), angle ); + lever.submodel->future_transform = glm::rotate( (float)glm::radians( std::remainder( futureangle - angle, 360.0 ) ), glm::vec3( 1.0f, 0.0f, 0.0f ) ); + } +} +namespace +{ + + +// the position of the door the animated wing belongs to: its shift or angle from closed +float door_position( TMoverParameters const &Mover, TAnim const *Animation ) { + + return Mover.Doors.instances[ ( + door_wings::on_right_side( Animation->iNumber ) ? + side::right : + side::left ) ].position; +} + +// the wing in the main model, and its namesake in the low poly interior; either can be missing +std::array wing_parts( TAnim const *Animation ) { + + return { Animation->smAnimated, Animation->smInterior }; +} + +// folding door: the smaller wing turns, the larger wing (its child) the other way, the step (child of that) under it +void fold_wing( TSubModel *Wing, door_wings::fold_angles const &Angles ) { + + if( Wing == nullptr ) { return; } + // skrzydło mniejsze + Wing->SetRotate( float3( 0, 0, 1 ), Angles.smaller ); + // skrzydło większe + auto *larger { Wing->ChildGet() }; + if( larger == nullptr ) { return; } + larger->SetRotate( float3( 0, 0, 1 ), Angles.larger ); + // podnóżek? + auto *step { larger->ChildGet() }; + if( step == nullptr ) { return; } + step->SetRotate( float3( 0, 1, 0 ), Angles.step ); +} + +} // namespace + +// animacja drzwi - przesuw +void TDynamicObject::UpdateDoorTranslate(TAnim *pAnim) { + + if( pAnim->smAnimated == nullptr ) { return; } + + auto const shift { door_wings::slide( door_position( *MoverParameters, pAnim ) ) }; + for( auto *wing : wing_parts( pAnim ) ) { + if( wing != nullptr ) { + wing->SetTranslate( shift ); + } + } +}; + +// animacja drzwi - obrót +void TDynamicObject::UpdateDoorRotate(TAnim *pAnim) { + + if( pAnim->smAnimated == nullptr ) { return; } + + auto const angle { door_position( *MoverParameters, pAnim ) }; + for( auto *wing : wing_parts( pAnim ) ) { + if( wing != nullptr ) { + wing->SetRotate( float3( 1, 0, 0 ), angle ); + } + } +}; + +// animacja drzwi - obrót +void TDynamicObject::UpdateDoorFold(TAnim *pAnim) { + + if( pAnim->smAnimated == nullptr ) { return; } + + auto const angles { door_wings::fold( door_position( *MoverParameters, pAnim ) ) }; + for( auto *wing : wing_parts( pAnim ) ) { + fold_wing( wing, angles ); + } +}; + +// animacja drzwi - odskokprzesuw +void TDynamicObject::UpdateDoorPlug(TAnim *pAnim) { + + if( pAnim->smAnimated == nullptr ) { return; } + + auto const shift { door_wings::plug( door_position( *MoverParameters, pAnim ), MoverParameters->Doors.range_out ) }; + for( auto *wing : wing_parts( pAnim ) ) { + if( wing != nullptr ) { + wing->SetTranslate( shift ); + } + } +} + +// a wing animated in its own way (animdoor: of the .mmd): as far along its own range as the door of its side is +void TDynamicObject::UpdateDoorWing( TAnim *pAnim, door_wings::wing_spec const &Spec ) { + + if( pAnim->smAnimated == nullptr ) { return; } + + auto const position { door_wings::wing_position( door_position( *MoverParameters, pAnim ), MoverParameters->Doors.range, Spec.range ) }; + for( auto *wing : wing_parts( pAnim ) ) { + if( wing == nullptr ) { continue; } + switch( Spec.type ) { + case door_wings::shift_type: { + wing->SetTranslate( door_wings::slide( position ) ); + break; + } + case door_wings::rotate_type: { + wing->SetRotate( float3( 1, 0, 0 ), position ); + break; + } + case door_wings::fold_type: { + fold_wing( wing, door_wings::fold( position ) ); + break; + } + case door_wings::plug_type: { + wing->SetTranslate( door_wings::plug( position, Spec.range_out ) ); + break; + } + default: { + break; + } + } + } +} + +void TDynamicObject::bind_door_animation( TAnim &Animation ) { + + if( auto const *spec { door_wings::find( m_doorwings, Animation.iNumber ) } ) { + Animation.yUpdate = [ this, spec = *spec ]( TAnim *pAnim ) { UpdateDoorWing( pAnim, spec ); }; + return; + } + switch( MoverParameters->Doors.type ) { // od razu zapinamy potrzebny typ animacji + case 1: + Animation.yUpdate = std::bind( &TDynamicObject::UpdateDoorTranslate, this, std::placeholders::_1 ); + break; + case 2: + Animation.yUpdate = std::bind( &TDynamicObject::UpdateDoorRotate, this, std::placeholders::_1 ); + break; + case 3: + Animation.yUpdate = std::bind( &TDynamicObject::UpdateDoorFold, this, std::placeholders::_1 ); + break; // obrót 3 kolejnych submodeli + case 4: + Animation.yUpdate = std::bind( &TDynamicObject::UpdateDoorPlug, this, std::placeholders::_1 ); + break; + default: + break; + } +} + +void TDynamicObject::UpdatePant(TAnim *pAnim) +{ // animacja pantografu - 4 obracane ramiona, ślizg piąty + float a, b, c; + a = glm::degrees(pAnim->fParamPants->fAngleL - pAnim->fParamPants->fAngleL0); + b = glm::degrees(pAnim->fParamPants->fAngleU - pAnim->fParamPants->fAngleU0); + c = a + b; + if (pAnim->smElement[0]) + pAnim->smElement[0]->SetRotate(float3(-1, 0, 0), a); // dolne ramie 1 + if (pAnim->smElement[1]) + pAnim->smElement[1]->SetRotate(float3(1, 0, 0), a * pAnim->fParamPants->rd2rf); // dolne ramie 2 + if (pAnim->smElement[2]) + pAnim->smElement[2]->SetRotate(float3(1, 0, 0), c); // górne ramie 1 + if (pAnim->smElement[3]) + pAnim->smElement[3]->SetRotate(float3(-1, 0, 0), c * pAnim->fParamPants->rg2rf); // gorne ramie 2 + if (pAnim->smElement[4]) + pAnim->smElement[4]->SetRotate(float3(-1, 0, 0), b * pAnim->fParamPants->slizgrf); // ślizg +} + +// doorstep animation, shift +void TDynamicObject::UpdatePlatformTranslate( TAnim *pAnim ) { + + if( pAnim->smAnimated == nullptr ) { return; } + + auto const &door { MoverParameters->Doors.instances[ ( + ( pAnim->iNumber & 1 ) == 0 ? + side::right : + side::left ) ] }; + + pAnim->smAnimated->SetTranslate( + glm::vec3{ + std::lerp( 0.f, MoverParameters->Doors.step_range, door.step_position ), + 0.0, + 0.0 } ); +} + +// doorstep animation, rotate +void TDynamicObject::UpdatePlatformRotate( TAnim *pAnim ) { + + if( pAnim->smAnimated == nullptr ) { return; } + + auto const &door { MoverParameters->Doors.instances[ ( + ( pAnim->iNumber & 1 ) == 0 ? + side::right : + side::left ) ] }; + + pAnim->smAnimated->SetRotate( + float3( 0, 1, 0 ), + std::lerp( 0.f, MoverParameters->Doors.step_range, door.step_position ) ); +} + +// mirror animation, rotate +void TDynamicObject::UpdateMirror( TAnim *pAnim ) { + + if( pAnim->smAnimated == nullptr ) { return; } + + // only animate the mirror if it's located on the same end of the vehicle as the active cab + auto const isactive { ( + MoverParameters->CabOccupied > 0 ? ( pAnim->iNumber >> 4 == end::front ? 1.0 : 0.0 ) : + MoverParameters->CabOccupied < 0 ? ( pAnim->iNumber >> 4 == end::rear ? 1.0 : 0.0 ) : + 0.0 ) }; + + if( pAnim->iNumber & 1 ) + pAnim->smAnimated->SetRotate( + float3( 0, 1, 0 ), + std::lerp( 0.0, MoverParameters->MirrorMaxShift, dMirrorMoveR * isactive ) ); + else + pAnim->smAnimated->SetRotate( + float3( 0, 1, 0 ), + std::lerp( 0.0, MoverParameters->MirrorMaxShift, dMirrorMoveL * isactive ) ); +} + +// wipers +void TDynamicObject::UpdateWiper(TAnim* pAnim) +{ + if (!pAnim || !pAnim->smElement) + return; + + int i = pAnim->iNumber; + // odwaramy animacje dla parzystych indexow + const double rotateAngle = (i + 1) % 2 == 0 ? -MoverParameters->WiperAngle : MoverParameters->WiperAngle; + + if (pAnim->smElement[0]) // ramie 1 + pAnim->smElement[0]->SetRotate(float3(0, 1, 0), smoothInterpolate(0.0, rotateAngle, dWiperPos[i])); + if (pAnim->smElement[1]) // ramie 2 + pAnim->smElement[1]->SetRotate(float3(0, 1, 0), smoothInterpolate(0.0, rotateAngle, dWiperPos[i])); + if (pAnim->smElement[2]) // pioro + pAnim->smElement[2]->SetRotate(float3(0, 1, 0), smoothInterpolate(0.0, -rotateAngle, dWiperPos[i])); +} + +/* +void TDynamicObject::UpdateLeverDouble(TAnim *pAnim) +{ // animacja gałki zależna od double + pAnim->smAnimated->SetRotate(float3(1, 0, 0), pAnim->fSpeed * *pAnim->fDoubleBase); +}; +void TDynamicObject::UpdateLeverFloat(TAnim *pAnim) +{ // animacja gałki zależna od float + pAnim->smAnimated->SetRotate(float3(1, 0, 0), pAnim->fSpeed * *pAnim->fFloatBase); +}; +void TDynamicObject::UpdateLeverInt(TAnim *pAnim) +{ // animacja gałki zależna od int + pAnim->smAnimated->SetRotate(float3(1, 0, 0), pAnim->fSpeed * *pAnim->iIntBase); +}; +void TDynamicObject::UpdateLeverEnum(TAnim *pAnim) +{ // ustawienie kąta na + // wartość wskazaną przez + // int z tablicy fParam + // pAnim->fParam[0]; - dodać lepkość + pAnim->smAnimated->SetRotate(float3(1, 0, 0), pAnim->fParam[*pAnim->iIntBase]); +}; +*/ +// sets light levels for registered interior sections +void +TDynamicObject::toggle_lights() { + + if( true == SectionLightsActive ) { + // switch all lights off... + for( auto §ion : Sections ) { + auto const sectionname { section.compartment->pName }; + if( sectionname.rfind( "cab", 0 ) != 0 ) { + section.light_level = 0.0; + } + } + SectionLightsActive = false; + } + else { + // set lights with probability depending on the compartment type. TODO: expose this in .mmd file + for( auto §ion : Sections ) { + + auto const sectionname { section.compartment->pName }; + if( sectionname.find("corridor") == 0 + || sectionname.find("korytarz") == 0 ) { + // corridors are lit 100% of time + section.light_level = 0.75f; + } + else if( + sectionname.find("compartment") == 0 + || sectionname.find("przedzial") == 0 ) { + // compartments are lit with 75% probability + section.light_level = Random() < 0.75 ? 0.75f : 0.10f; + } + } + SectionLightsActive = true; + } +} + +void +TDynamicObject::set_cab_lights( int const Cab, float const Level ) { + + for( auto §ion : Sections ) { + // cab compartments are placed at the beginning of the list, so we can bail out as soon as we find different compartment type + auto const sectionname { section.compartment->pName }; + if( sectionname.size() < 4 ) { return; } + if( sectionname.find( "cab" ) != 0 ) { return; } + if( sectionname[ 3 ] != Cab + '0' ) { continue; } // match the cab with correct index + + section.light_level = Level; + } +} + +// aktualizujemy submodele w zaleznosci od aktualnej pory roku +void TDynamicObject::on_season_update() +{ + if (sm_winter_variant != nullptr) // pokazujemy wariant zimowy + sm_winter_variant->SetVisibilityLevel(Global.Season == "winter:" ? 1 : 0, true, false); + if (sm_spring_variant != nullptr) // pokazujemy wariant wiosenny + sm_spring_variant->SetVisibilityLevel(Global.Season == "spring:" ? 1 : 0, true, false); + if (sm_summer_variant != nullptr) // pokazujemy wariant letni + sm_summer_variant->SetVisibilityLevel(Global.Season == "summer:" ? 1 : 0, true, false); + if (sm_autumn_variant != nullptr) // pokazujemy wariant jesienny + sm_autumn_variant->SetVisibilityLevel(Global.Season == "autumn:" ? 1 : 0, true, false); +} diff --git a/vehicle/dynamic/consist.cpp b/vehicle/dynamic/consist.cpp new file mode 100644 index 000000000..d912c1693 --- /dev/null +++ b/vehicle/dynamic/consist.cpp @@ -0,0 +1,527 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// a vehicle among the others of its train: the neighbours, the ends, the vehicles found along the couplings + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/mover.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + + + +//--------------------------------------------------------------------------- +TDynamicObject * TDynamicObject::FirstFind(int &coupler_nr, CouplingSet const cf) +{ // szukanie skrajnego połączonego pojazdu w pociagu + // od strony sprzegu (coupler_nr) obiektu (start) + TDynamicObject *temp = this; + for (int i = 0; i < 300; i++) // ograniczenie do 300 na wypadek zapętlenia składu + { + if (!temp) + return nullptr; // Ra: zabezpieczenie przed ewentaulnymi błędami sprzęgów + if (false == temp->MoverParameters->Couplers[coupler_nr].CouplingFlag.HasAll(cf)) + return temp; // nic nie ma już dalej podłączone sprzęgiem cf + if (coupler_nr == end::front) + { // jeżeli szukamy od sprzęgu 0 + if (temp->PrevConnected()) // jeśli mamy coś z przodu + { + if (temp->PrevConnectedNo() == end::front) // jeśli pojazd od strony sprzęgu 0 jest odwrócony + coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu + temp = temp->PrevConnected(); // ten jest od strony 0 + } + else + return temp; // jeśli jednak z przodu nic nie ma + } + else + { + if (temp->NextConnected()) + { + if (temp->NextConnectedNo() == end::rear) // jeśli pojazd od strony sprzęgu 1 jest odwrócony + coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu + temp = temp->NextConnected(); // ten pojazd jest od strony 1 + } + else + return temp; // jeśli jednak z tyłu nic nie ma + } + } + return nullptr; // to tylko po wyczerpaniu pętli +}; + +//--------------------------------------------------------------------------- +float TDynamicObject::GetEPP() +{ // szukanie skrajnego połączonego pojazdu w pociagu + // od strony sprzegu (coupler_nr) obiektu (start) + TDynamicObject *temp = this; + int coupler_nr = 0; + double eq = 0.0; + double am = 0.0; + + for (int i = 0; i < 300; ++i) // ograniczenie do 300 na wypadek zapętlenia składu + { + if (!temp) + break; // Ra: zabezpieczenie przed ewentaulnymi błędami sprzęgów + eq += temp->MoverParameters->PipePress * temp->MoverParameters->Dim.L; + am += temp->MoverParameters->Dim.L; + if ((temp->MoverParameters->Couplers[coupler_nr].CouplingFlag & Coupling::brakeHose) != Coupling::brakeHose) + break; // nic nie ma już dalej podłączone + if (coupler_nr == 0) + { // jeżeli szukamy od sprzęgu 0 + if (temp->PrevConnected()) // jeśli mamy coś z przodu + { + if (temp->PrevConnectedNo() == end::front) // jeśli pojazd od strony sprzęgu 0 jest odwrócony + coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu + temp = temp->PrevConnected(); // ten jest od strony 0 + } + else + break; // jeśli jednak z przodu nic nie ma + } + else + { + if (temp->NextConnected()) + { + if (temp->NextConnectedNo() == end::rear) // jeśli pojazd od strony sprzęgu 1 jest odwrócony + coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu + temp = temp->NextConnected(); // ten pojazd jest od strony 1 + } + else + break; // jeśli jednak z tyłu nic nie ma + } + } + + temp = this; + coupler_nr = 1; + for (int i = 0; i < 300; i++) // ograniczenie do 300 na wypadek zapętlenia składu + { + if (!temp) + break; // Ra: zabezpieczenie przed ewentaulnymi błędami sprzęgów + eq += temp->MoverParameters->PipePress * temp->MoverParameters->Dim.L; + am += temp->MoverParameters->Dim.L; + if ((temp->MoverParameters->Couplers[coupler_nr].CouplingFlag & Coupling::brakeHose) != Coupling::brakeHose) + break; // nic nie ma już dalej podłączone + if (coupler_nr == 0) + { // jeżeli szukamy od sprzęgu 0 + if (temp->PrevConnected()) // jeśli mamy coś z przodu + { + if (temp->PrevConnectedNo() == end::front) // jeśli pojazd od strony sprzęgu 0 jest odwrócony + coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu + temp = temp->PrevConnected(); // ten jest od strony 0 + } + else + break; // jeśli jednak z przodu nic nie ma + } + else + { + if (temp->NextConnected()) + { + if (temp->NextConnectedNo() == end::rear) // jeśli pojazd od strony sprzęgu 1 jest odwrócony + coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu + temp = temp->NextConnected(); // ten pojazd jest od strony 1 + } + else + break; // jeśli jednak z tyłu nic nie ma + } + } + eq -= MoverParameters->PipePress * MoverParameters->Dim.L; + am -= MoverParameters->Dim.L; + return eq / am; +}; + +//--------------------------------------------------------------------------- +TDynamicObject * TDynamicObject::GetFirstDynamic(int cpl_type, CouplingSet const cf) +{ // Szukanie skrajnego połączonego pojazdu w pociagu + // od strony sprzegu (cpl_type) obiektu szukajacego + // Ra: wystarczy jedna funkcja do szukania w obu kierunkach + return FirstFind(cpl_type, cf); // używa referencji +}; + +int TDynamicObject::DirectionSet(int d) +{ // ustawienie kierunku w składzie (wykonuje AI) + auto const lastdirection { iDirection }; + iDirection = d > 0 ? 1 : 0; // d:1=zgodny,-1=przeciwny; iDirection:1=zgodny,0=przeciwny; + + if( iDirection != lastdirection ) { + // direction was flipped, switch recorded servicable platform sides for potentially ongoing load exchange + auto const left { lastdirection > 0 ? 1 : 2 }; + auto const right { 3 - left }; + m_exchange.platforms = + ( ( m_exchange.platforms & left ) != 0 ? right : 0 ) + + ( ( m_exchange.platforms & right ) != 0 ? left : 0 ); + } + + if (MyTrack) + { // podczas wczytywania wstawiane jest AI, ale może jeszcze nie być toru + // AI ustawi kierunek ponownie po uruchomieniu silnika + update_neighbours(); + } + // informacja o położeniu następnego + return 1 - ( iDirection > 0 ? NextConnectedNo() : PrevConnectedNo() ); +}; + +// wskaźnik na poprzedni, nawet wirtualny +TDynamicObject * TDynamicObject::PrevAny() const { + return MoverParameters->Neighbours[ iDirection ^ 1 ].vehicle; +} +TDynamicObject * TDynamicObject::Prev(CouplingSet const couplings) const { + return MoverParameters->Couplers[iDirection ^ 1].CouplingFlag.HasAny(couplings) ? MoverParameters->Neighbours[iDirection ^ 1].vehicle : nullptr;// gdy sprzęg wirtualny, to jakby nic nie było +} +TDynamicObject * TDynamicObject::Next(CouplingSet const couplings) const { + return MoverParameters->Couplers[iDirection].CouplingFlag.HasAny(couplings) ? MoverParameters->Neighbours[iDirection].vehicle : nullptr;// gdy sprzęg wirtualny, to jakby nic nie było +} + +// checks whether there's unbroken connection of specified type to specified vehicle +bool +TDynamicObject::is_connected( TDynamicObject const *Vehicle, CouplingSet const couplings ) const { + + auto *vehicle { this }; + if( vehicle == Vehicle ) { + // edge case, vehicle is always "connected" with itself + return true; + } + // check ahead, it's more likely the "owner" using this method is located there + while( ( vehicle = vehicle->Prev( couplings ) ) != nullptr ) { + if( vehicle == Vehicle ) { + return true; + } + if( vehicle == this ) { + // edge case, looping consist + return false; + } + } + // start anew in the other direction + vehicle = this; + while( ( vehicle = vehicle->Next( couplings ) ) != nullptr ) { + if( vehicle == Vehicle ) { + return true; + } + } + // no luck in either direction, give up + return false; +} + +// ustalenie następnego (1) albo poprzedniego (0) w składzie bez względu na prawidłowość iDirection +TDynamicObject * +TDynamicObject::Neighbour(int &dir) { + + auto *neighbour { ( + MoverParameters->Couplers[ dir ].CouplingFlag != Coupling::none ? + MoverParameters->Neighbours[ dir ].vehicle : + nullptr ) }; + // nowa wartość + dir = 1 - MoverParameters->Neighbours[ dir ].vehicle_end; + + return neighbour; +}; + +// updates potential collision sources +void +TDynamicObject::update_neighbours() { + + for( int end = end::front; end <= end::rear; ++end ) { + + auto &neighbour { MoverParameters->Neighbours[ end ] }; + auto const &coupler { MoverParameters->Couplers[ end ] }; + + if( coupler.Connected != nullptr + && neighbour.vehicle != nullptr ) { + // physical connection with another vehicle locks down collision source on this end +// neighbour.vehicle = coupler.Connected; +// neighbour.vehicle_end = coupler.ConnectedNr; + neighbour.distance = TMoverParameters::CouplerDist( MoverParameters, coupler.Connected ); + if( MoverParameters->OffTrack.active() || neighbour.vehicle->MoverParameters->OffTrack.active() ) { + // physics.derailment new: off the track the bodies turn against each other, the ends meet where they are + // (the distance between the middles less the half lengths would press the buffers of a bent pair) + neighbour.distance = off_track_gap( end ); + } + // take into account potential adapters attached to the couplers + auto const &othercoupler { neighbour.vehicle->MoverParameters->Couplers[ neighbour.vehicle_end ] }; + neighbour.distance -= coupler.adapter_length; + neighbour.distance -= othercoupler.adapter_length; + } + else { + // if there's no connected vehicle check for potential collision sources in the vicinity + // NOTE: we perform a new scan on each update to ensure we always locate the nearest potential source + neighbour = neighbour_data(); + // 10m ~= 140 km/h at 4 fps + safety margin, potential distance between outer axles of involved vehicles + auto const scanrange { std::max( 10.0, std::abs( MoverParameters->V ) ) + 40.0 }; + // physics.derailment new: a vehicle off the track beside the other one doesn't run into it, the scan goes on + // past it to the vehicles beyond + auto const lookup { find_vehicle( end, scanrange, true ) }; + + if( false == std::get( lookup ) ) { continue; } + + neighbour.vehicle = std::get( lookup ); + neighbour.vehicle_end = std::get( lookup ); + neighbour.distance = std::get( lookup ); + + if( neighbour.vehicle + && neighbour.distance < (neighbour.vehicle->MoverParameters->CategoryFlag == 2 ? 50 : 100) ) { + // at short distances (re)calculate range between couplers directly + neighbour.distance = TMoverParameters::CouplerDist( MoverParameters, neighbour.vehicle->MoverParameters ); + if( MoverParameters->OffTrack.active() || neighbour.vehicle->MoverParameters->OffTrack.active() ) { + // physics.derailment new: the ends where they are, as for a coupled pair + neighbour.distance = off_track_gap( end ); + } + // take into account potential adapters attached to the couplers + auto const &othercoupler { neighbour.vehicle->MoverParameters->Couplers[ neighbour.vehicle_end ] }; + neighbour.distance -= coupler.adapter_length; + neighbour.distance -= othercoupler.adapter_length; + } + } + } +} + +bool +TDynamicObject::in_line_with( TDynamicObject const &Other ) const { + + // the middle of the other one off the axis of this one, and this one off the axis of the other one, by less than + // the half widths of both: their ends can meet + auto const reach { 0.5 * ( MoverParameters->Dim.W + Other.MoverParameters->Dim.W ) }; + auto const apart { Other.vPosition - vPosition }; + return std::abs( glm::dot( apart, vLeft ) ) < reach && std::abs( glm::dot( apart, Other.vLeft ) ) < reach; +} + +// locates potential collision source within specified range, scanning track in specified direction. returns: true if neighbour was located, false otherwise +// NOTE: reuses legacy code. TBD, TODO: review, refactor? +std::tuple +TDynamicObject::find_vehicle( int const Direction, double const Distance, bool const InLine ) const { + + auto direction { ( Direction == end::front ? 1 : -1 ) }; + auto const initialdirection { direction }; // zapamiętanie kierunku poszukiwań na torze początkowym, względem sprzęgów + + auto const *track { RaTrackGet() }; + if( RaDirectionGet() < 0 ) { + // czy oś jest ustawiona w stronę Point1? + direction = -direction; + } + + // (teraz względem toru) + auto const mycoupler { ( initialdirection < 0 ? end::rear : end::front ) }; // numer sprzęgu do podłączenia w obiekcie szukajacym + auto foundcoupler { -1 }; // numer sprzęgu w znalezionym obiekcie (znaleziony wypełni) + auto distance { 0.0 }; // przeskanowana odleglość; odległość do zawalidrogi + auto *foundobject { ABuFindObject( foundcoupler, distance, track, direction, mycoupler, InLine ) }; // zaczynamy szukać na tym samym torze + + if( foundobject == nullptr ) { + // jeśli nie ma na tym samym, szukamy po okolicy szukanie najblizszego toru z jakims obiektem + // praktycznie przeklejone z TraceRoute()... + if (direction >= 0) // uwzględniamy kawalek przeanalizowanego wcześniej toru + distance = track->Length() - RaTranslationGet(); // odległość osi od Point2 toru + else + distance = RaTranslationGet(); // odległość osi od Point1 toru + + while (distance < Distance) { + if (direction > 0) { + // w kierunku Point2 toru + if( track ? + track->iNextDirection : + false ) { + // jeśli następny tor jest podpięty od Point2 + direction = -direction; // to zmieniamy kierunek szukania na tym torze + } + if( track ) { + track = track->CurrentNext(); // potem dopiero zmieniamy wskaźnik + } + } + else { + // w kierunku Point1 + if( track ? + !track->iPrevDirection : + true ) { + // jeśli poprzedni tor nie jest podpięty od Point2 + direction = -direction; // to zmieniamy kierunek szukania na tym torze + } + if( track ) { + track = track->CurrentPrev(); // potem dopiero zmieniamy wskaźnik + } + } + if (track) { + // jesli jest kolejny odcinek toru + foundobject = ABuFindObject(foundcoupler, distance, track, direction, mycoupler, InLine); // przejrzenie pojazdów tego toru + if (foundobject) { + break; + } + } + else { + // jeśli toru nie ma, to wychodzimy + distance = Distance + 1.0; // koniec przeglądania torów + break; + } + } + } // Koniec szukania najbliższego toru z jakimś obiektem. + + if( foundobject == nullptr ) { return {}; } +/* + auto const *vehicle { MoverParameters }; + auto const *foundvehicle { foundobject->MoverParameters }; + if( ( false == TestFlag( track->iCategoryFlag, 1 ) ) + && ( distance > 50.0 ) ) { + // Ra: jeśli dwa samochody się mijają na odcinku przed zawrotką, to odległość między nimi nie może być liczona w linii prostej! + // NOTE: the distance is approximated, and additionally less accurate for cars heading in opposite direction + distance -= ( 0.5 * ( vehicle->Dim.L + foundvehicle->Dim.L ) ); + } + else if( distance < 100.0 ) { + // at short distances start to calculate range between couplers directly + // odległość do najbliższego pojazdu w linii prostej + distance = TMoverParameters::CouplerDist( vehicle, foundvehicle ); + } +*/ + return { foundobject, foundcoupler, distance, true }; +} + +TDynamicObject * TDynamicObject::FindPowered() +{ // taka proteza: + // chcę podłączyć kabinę EN57 bezpośrednio z silnikowym, aby nie robić tego przez ukrotnienie + // drugi silnikowy i tak musi być ukrotniony, podobnie jak kolejna jednostka + // lepiej by było przesyłać komendy sterowania, co jednak wymaga przebudowy transmisji komend (LD) + // problem się robi ze światłami, które będą zapalane w silnikowym, ale muszą świecić się w rozrządczych + // dla EZT światłą czołowe będą "zapalane w silnikowym", ale widziane z rozrządczych + // również wczytywanie MMD powinno dotyczyć aktualnego członu + // problematyczna może być kwestia wybranej kabiny (w silnikowym...) + // jeśli silnikowy będzie zapięty odwrotnie (tzn. -1), to i tak powinno jeździć dobrze + // również hamowanie wykonuje się zaworem w członie, a nie w silnikowym... + auto const coupling { MoverParameters->is_multiple_unit() ? + Coupling::permanent : + Coupling::control }; + + auto *lookup { + find_vehicle( + coupling, + []( TDynamicObject * vehicle ) { + return vehicle->MoverParameters->Power > 1.0; } ) }; + + return lookup != nullptr ? lookup : this; // always return valid vehicle for backward compatibility +} + +TDynamicObject * +TDynamicObject::FindPantographCarrier() { + + // try first within a single unit, broaden to all vehicles under our control if first attempt fails + std::array const couplings = { Coupling::permanent, Coupling::control }; + + for( auto const coupling : couplings ) { + auto *result = + find_vehicle( + coupling, + []( TDynamicObject * vehicle ) { + return vehicle->MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector && vehicle->MoverParameters->EnginePowerSource.CollectorParameters.CollectorsNo > 0; } ); + if( result != nullptr ) { + return result; + } + } + // if we're still here, admit failure + return nullptr; +} + +//--------------------------------------------------------------------------- + +void TDynamicObject::ParamSet(int what, int into) +{ // ustawienie lokalnego parametru (what) na stan (into) + switch (what & 0xFF00) + { + case 0x0100: // to np. są drzwi, bity 0..7 określają numer 1..254 albo maskę + // dla 8 różnych + if (what & 1) // na razie mamy lewe oraz prawe, czyli używamy maskę 1=lewe, + // 2=prawe, 3=wszystkie + if( MoverParameters->Doors.instances[side::left].is_open ) + { // są otwarte + if (!into) // jeśli zamykanie + { + // dźwięk zamykania + } + } + else + { // są zamknięte + if (into) // jeśli otwieranie + { + // dźwięk otwierania + } + } + if (what & 2) // prawe działają niezależnie od lewych + if( MoverParameters->Doors.instances[side::right].is_open ) + { // są otwarte + if (!into) // jeśli zamykanie + { + // dźwięk zamykania + } + } + else + { // są zamknięte + if (into) // jeśli otwieranie + { + // dźwięk otwierania + } + } + break; + } +}; + +int TDynamicObject::RouteWish(TTrack *tr) +{ // zapytanie do AI, po którym + // segmencie (-6..6) jechać na + // skrzyżowaniu (tr) + return Mechanik ? Mechanik->CrossRoute(tr) : 0; // wg AI albo prosto +}; + +// the vehicles coupled at the ends, and the ends of theirs facing this one +TDynamicObject *TDynamicObject::NextConnected() { return MoverParameters->Neighbours[ end::rear ].vehicle; } +TDynamicObject *TDynamicObject::PrevConnected() { return MoverParameters->Neighbours[ end::front ].vehicle; } +TDynamicObject *TDynamicObject::NextConnected() const { return MoverParameters->Neighbours[ end::rear ].vehicle; } +TDynamicObject *TDynamicObject::PrevConnected() const { return MoverParameters->Neighbours[ end::front ].vehicle; } +int TDynamicObject::NextConnectedNo() const { return MoverParameters->Neighbours[ end::rear ].vehicle_end; } +int TDynamicObject::PrevConnectedNo() const { return MoverParameters->Neighbours[ end::front ].vehicle_end; } + +void TDynamicObject::SetdMoveLen( double dMoveLen ) { MoverParameters->dMoveLen = dMoveLen; } +void TDynamicObject::ResetdMoveLen() { MoverParameters->dMoveLen = 0; } +double TDynamicObject::GetdMoveLen() { return MoverParameters->dMoveLen; } + +double TDynamicObject::GetVelocity() const { return MoverParameters->Vel; } +double TDynamicObject::GetLength() const { return MoverParameters->Dim.L; } +double TDynamicObject::GetWidth() const { return MoverParameters->Dim.W; } diff --git a/vehicle/dynamic/couplers.cpp b/vehicle/dynamic/couplers.cpp new file mode 100644 index 000000000..706d9452e --- /dev/null +++ b/vehicle/dynamic/couplers.cpp @@ -0,0 +1,331 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// coupling and uncoupling a vehicle, the adapters of its couplers + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/mover.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + + +int TDynamicObject::DettachStatus(int dir) +{ // sprawdzenie odległości sprzęgów + // rzeczywistych od strony (dir): + // 0=przód,1=tył + // Ra: dziwne, że ta funkcja nie jest używana + if( MoverParameters->Couplers[ dir ].CouplingFlag == Coupling::none ) { + return 0; // jeśli nic nie podłączone, to jest OK + } + return MoverParameters->DettachStatus(dir); // czy jest w odpowiedniej odległości? +} + +int TDynamicObject::Dettach(int dir) +{ // rozłączenie sprzęgów rzeczywistych od + // strony (dir): 0=przód,1=tył + // zwraca maskę bitową aktualnych sprzegów (0 jeśli rozłączony) + if (ctOwner) + { // jeśli pojazd ma przypisany obiekt nadzorujący skład, to póki + // są wskaźniki + TDynamicObject *d = this; + while (d) + { + d->ctOwner = nullptr; // usuwanie właściciela + d = d->Prev(); + } + d = Next(); + while (d) + { + d->ctOwner = nullptr; // usuwanie właściciela + d = d->Next(); // i w drugą stronę + } + } + if( MoverParameters->Couplers[ dir ].CouplingFlag ) { + // odczepianie, o ile coś podłączone + MoverParameters->Dettach( dir ); +/* + if( true == MoverParameters->Dettach( dir ) ) { + auto *othervehicle { dir ? NextConnected : PrevConnected }; + auto const othercoupler { dir ? NextConnectedNo() : PrevConnectedNo() }; + ( othercoupler ? othervehicle->NextConnected : othervehicle->PrevConnected ) = nullptr; + ( dir ? NextConnected : PrevConnected ) = nullptr; + }; +*/ + } + // sprzęg po rozłączaniu (czego się nie da odpiąć + return MoverParameters->Couplers[dir].CouplingFlag.Bits(); +} + +void +TDynamicObject::couple( int const Side ) { + + auto const &neighbour { MoverParameters->Neighbours[ Side ] }; + + if( neighbour.vehicle == nullptr ) { return; } + + auto const &coupler { MoverParameters->Couplers[ Side ] }; + auto *othervehicle { neighbour.vehicle }; + auto *othervehicleparams{ othervehicle->MoverParameters }; + auto const &othercoupler { othervehicleparams->Couplers[ neighbour.vehicle_end ] }; + + if( coupler.CouplingFlag == Coupling::none ) { + // najpierw hak + if( ( coupler.AllowedFlag + & othercoupler.AllowedFlag + & Coupling::coupler ) == Coupling::coupler ) { + if( MoverParameters->Attach( + Side, neighbour.vehicle_end, + othervehicleparams, + Coupling::coupler ) ) { + // one coupling type per key press + return; + } + else { + WriteLog( "Mechanical coupling failed." ); + } + } + } + if( false == MoverParameters->Couplers[ Side ].CouplingFlag.HasAll(Coupling::brakeHose) ) { + // pneumatyka + if( ( coupler.AllowedFlag + & othercoupler.AllowedFlag + & Coupling::brakeHose ) == Coupling::brakeHose ) { + if( MoverParameters->Attach( + Side, neighbour.vehicle_end, + othervehicleparams, + coupler.CouplingFlag | Coupling::brakeHose ) ) { + SetPneumatic( Side != 0, true ); + othervehicle->SetPneumatic( Side != 0, true ); + // one coupling type per key press + return; + } + } + } + if( false == MoverParameters->Couplers[ Side ].CouplingFlag.HasAll(Coupling::mainHose) ) { + // zasilajacy + if( ( coupler.AllowedFlag + & othercoupler.AllowedFlag + & Coupling::mainHose ) == Coupling::mainHose ) { + if( MoverParameters->Attach( + Side, neighbour.vehicle_end, + othervehicleparams, + coupler.CouplingFlag | Coupling::mainHose ) ) { + SetPneumatic( Side != 0, false ); + othervehicle->SetPneumatic( Side != 0, false ); + // one coupling type per key press + return; + } + } + } + if( false == MoverParameters->Couplers[ Side ].CouplingFlag.HasAll(Coupling::control) ) { + // ukrotnionko + if( (coupler.AllowedFlag & othercoupler.AllowedFlag & Coupling::control) == Coupling::control + && coupler.control_type == othercoupler.control_type + && MoverParameters->CompatibleCoupling( Side, *othervehicleparams, neighbour.vehicle_end, coupler.CouplingFlag | Coupling::control ).HasAny( Coupling::control ) ) { + if( MoverParameters->Attach( + Side, neighbour.vehicle_end, + othervehicleparams, + coupler.CouplingFlag | Coupling::control ) ) { + // one coupling type per key press + return; + } + } + } + if( false == MoverParameters->Couplers[ Side ].CouplingFlag.HasAll(Coupling::gangway) ) { + // mostek + if( ( coupler.AllowedFlag + & othercoupler.AllowedFlag + & Coupling::gangway ) == Coupling::gangway ) { + if( MoverParameters->Attach( + Side, neighbour.vehicle_end, + othervehicleparams, + coupler.CouplingFlag | Coupling::gangway ) ) { + // one coupling type per key press + return; + } + } + } + if( false == MoverParameters->Couplers[ Side ].CouplingFlag.HasAll(Coupling::heating) ) { + // heating + if( ( coupler.AllowedFlag + & othercoupler.AllowedFlag + & Coupling::heating ) == Coupling::heating ) { + if( MoverParameters->Attach( + Side, neighbour.vehicle_end, + othervehicleparams, + coupler.CouplingFlag | Coupling::heating ) ) { + // one coupling type per key press + return; + } + } + } + +} + +int +TDynamicObject::uncouple( int const Side ) { + + if( DettachStatus(Side) >= 0 + || true == MoverParameters->Couplers[Side].CouplingFlag.HasAll(Coupling::permanent) ) { + // can't uncouple, return existing coupling state + return MoverParameters->Couplers[ Side ].CouplingFlag.Bits(); + } + // jeżeli sprzęg niezablokowany, jest co odczepić i się da + auto const couplingflag { Dettach( Side ) }; + return couplingflag; +} + +bool +TDynamicObject::attach_coupler_adapter( int const Side, bool const Enforce ) { + + auto &coupler { MoverParameters->Couplers[ Side ] }; + // sanity check(s) + if( coupler.type() == TCouplerType::Automatic ) { return false; } + auto const *neighbour { MoverParameters->Neighbours[ Side ].vehicle }; + if( neighbour == nullptr + || MoverParameters->Neighbours[Side].distance > 25.0 ) { + // can only acquire the adapter from a nearby enough vehicle + return false; + } + // TBD: empty struct instead of fallback defaults, to allow vehicles without adapter? + auto adapterdata { + coupleradapter_data { + { 0.085f, 0.95f }, + "tabor/polsprzeg" } }; + if( false == neighbour->m_coupleradapter.model.empty() ) { + // explicit coupler adapter definition overrides default parameters + adapterdata = neighbour->m_coupleradapter; + } + if( MoverParameters->Neighbours[Side].distance - adapterdata.position.x < 0.5 + && false == Enforce ) { + // arbitrary amount of free room required to install the adapter + // NOTE: this also covers cases with established physical connection + return false; + } + + coupler.adapter_type = TCouplerType::Automatic; + coupler.adapter_length = adapterdata.position.x; + coupler.adapter_height = adapterdata.position.y; + // audio flag, visuals update + coupler.sounds |= sound::attachadapter; + m_coupleradapters[ Side ] = TModelsManager::GetModel( adapterdata.model ); + + return true; +} + +bool +TDynamicObject::remove_coupler_adapter( int const Side ) { + + auto &coupler{ MoverParameters->Couplers[ Side ] }; + + if( coupler.adapter_type == TCouplerType::NoCoupler ) { return false; } + // TODO: sanity check(s) + if( coupler.Connected != nullptr ) { + // TBD: disallow instead adapter removal if it's coupled with another vehicle? + uncouple( Side ); + } + coupler.adapter_type = TCouplerType::NoCoupler; + coupler.adapter_length = 0.0; + coupler.adapter_height = 0.0; + // audio flag, visuals update + coupler.sounds |= sound::removeadapter; + m_coupleradapters[ Side ] = nullptr; + + return true; +} + +void TDynamicObject::AttachNext(TDynamicObject *Object, int iType) +{ // Ra: doczepia Object na końcu składu (nazwa funkcji może być myląca) + // Ra: używane tylko przy wczytywaniu scenerii + auto const vehicleend { iDirection }; + auto const othervehicleend { Object->iDirection ^ 1 }; + + MoverParameters->Attach( vehicleend, othervehicleend, Object->MoverParameters, CouplingSet::FromBits( iType ), true, false ); + // update neighbour data for both affected vehicles + update_neighbours(); + Object->update_neighbours(); + + // potentially attach automatic coupler adapter to allow the connection + // HACK: we're doing it after establishin actual connection, as the method needs valid neighbour data + auto &coupler { MoverParameters->Couplers[ vehicleend ] }; + auto &othercoupler { Object->MoverParameters->Couplers[ ( othervehicleend != 2 ? othervehicleend : coupler.ConnectedNr ) ] }; + + if( coupler.type() != othercoupler.type() ) { + if( othercoupler.type() == TCouplerType::Automatic ) { + // try to attach adapter to the vehicle + attach_coupler_adapter( + vehicleend, + true ); + } + else if( coupler.type() == TCouplerType::Automatic ) { + // try to attach adapter to the other vehicle + Object->attach_coupler_adapter( + othervehicleend != 2 ? othervehicleend : coupler.ConnectedNr, + true ); + } + // update distance to neighbours on account of potentially attached adapter + update_neighbours(); + Object->update_neighbours(); + } + // potentially adjust vehicle position to avoid collision at the simulation start + if( MoverParameters->Neighbours[ vehicleend ].distance > -0.001 ) { return; } + + Object->Move( MoverParameters->Neighbours[ vehicleend ].distance * Object->DirectionGet() ); + // HACK: manually update vehicle position as it's used by neighbour distance update we do next + Object->MoverParameters->Loc = { + -Object->vPosition.x, + Object->vPosition.z, + Object->vPosition.y }; + // update neighbour distance data after moving our vehicle + update_neighbours(); + Object->update_neighbours(); +} diff --git a/vehicle/dynamic/destinations.cpp b/vehicle/dynamic/destinations.cpp new file mode 100644 index 000000000..0bad55974 --- /dev/null +++ b/vehicle/dynamic/destinations.cpp @@ -0,0 +1,379 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the destination boards and the announcements of a vehicle + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/mover.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + + +void TDynamicObject::destination_data::deserialize( cParser &Input ) { + + while( true == deserialize_mapping( Input ) ) { + ; // all work done by while() + } +} + +bool TDynamicObject::destination_data::deserialize_mapping( cParser &Input ) { + // token can be a key or block end + auto const key { Input.getToken( true, "\n\r\t ,;[]" ) }; + + if( true == key.empty() || key == "}" ) { return false; } + + if( key == "{" ) { + script = Input.getToken(); + } + else if( key == "update:" ) { + auto const value { Input.getToken() }; + // TODO: implement + } + else if( key == "instance:" ) { + instancing = Input.getToken(); + } + else if( key == "parameters:" ) { + parameters = Input.getToken(); + } + else if( key == "background:" ) { + background = Input.getToken(); + } + + return true; +} + +/* +Ra: + Powinny być dwie funkcje wykonujące aktualizację fizyki. Jedna wykonująca +krok obliczeń, powtarzana odpowiednią liczbę razy, a druga wykonująca zbiorczą +aktualzację mniej istotnych elementów. + Ponadto należało by ustalić odległość składów od kamery i jeśli przekracza +ona np. 10km, to traktować składy jako uproszczone, np. bez wnikania w siły +na sprzęgach, opóźnienie działania hamulca itp. Oczywiście musi mieć to pewną +histerezę czasową, aby te tryby pracy nie przełączały się zbyt szybko. +*/ + +void TDynamicObject::update_destinations() { + + if( DestinationSign.sign == nullptr ) { return; } + + auto const lowvoltagepower { ( MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable ) }; + + DestinationSign.sign->fLight = DestinationSign.has_light && lowvoltagepower ? 2.0 : -1.0; + + // jak są 4 tekstury wymienne, to nie zmieniać rozkładem + if( std::abs( m_materialdata.multi_textures ) >= 4 ) { return; } + // TODO: dedicated setting to discern electronic signs, instead of fallback on light presence + m_materialdata.replacable_skins[ 4 ] = DestinationSign.destination != null_handle && (false == DestinationSign.has_light // physical destination signs remain up until manually changed + || (lowvoltagepower // lcd signs are off without power + && ctOwner != nullptr)) ? // lcd signs are off for carriages without engine, potentially left on a siding + DestinationSign.destination : + DestinationSign.destination_off; + + update_script_destination(); +} + +void TDynamicObject::update_script_destination() { + + if( DestinationSign.script_sign == nullptr ) { return; } + // only while the sign shows the destination it draws + if( m_materialdata.replacable_skins[ 4 ] != DestinationSign.destination ) { return; } + + auto &queue { Application.screens() }; + if( false == queue.due( *DestinationSign.script_sign ) ) { return; } + // read anew on every refresh, so the sign follows the timetable + queue.submit( DestinationSign.script_sign, std::make_shared( DestinationSign.script_request ), 0 ); +} + +void TDynamicObject::DestinationClear() { + + if( false == DestinationSign.has_light ) { return; } // physical destination signs remain up until manually changed + // update_destinations() shows the blank sign in place of the missing destination + DestinationSign.destination = null_handle; + DestinationSign.script_sign.reset(); +} + +void TDynamicObject::DestinationSet(std::string const &to, std::string const &numer) { + // ustawienie stacji docelowej oraz wymiennej tekstury 4, jeśli istnieje plik + // w zasadzie, to każdy wagon mógłby mieć inną stację docelową + // zwłaszcza w towarowych, pod kątem zautomatyzowania maewrów albo pracy górki + // ale to jeszcze potrwa, zanim będzie możliwe, na razie można wpisać stację z + // rozkładu + + asDestination = to; + + if( std::abs( m_materialdata.multi_textures ) >= 4 ) { return; } // jak są 4 tekstury wymienne, to nie zmieniać rozkładem + if( DestinationSign.sign == nullptr ) { return; } // no sign submodel, no problem + // a sign drawn for the previous destination + DestinationSign.script_sign.reset(); + + // now see if we can find any version of the destination texture + std::vector const destinations = { + numer, // try dedicated timetable sign first... + to }; // ...then generic destination sign + + for( auto const &destination : destinations ) { + + DestinationSign.destination = DestinationFind( destination ); + if( DestinationSign.destination != null_handle ) { + // got what we wanted, we're done here + return; + } + } + // if we didn't get static texture we might be able to make one + if( true == destination_set_script( numer ) ) { return; } + if( DestinationSign.script.empty() ) { return; } // no script so no way to make the texture + if( numer == "none" ) { return; } // blank or incomplete/malformed timetable, don't bother + + DestinationSign.destination = GfxRenderer->Fetch_Material( destination_request( DestinationSign.script, DestinationSign.instancing, DestinationSign.parameters ) ); +} + +std::string TDynamicObject::destination_request( std::string const &Script, std::string const &Instancing, std::string const &Parameters ) const { + + auto const trainname { [this]() -> std::string { + if( ctOwner != nullptr ) { return ctOwner->TrainName(); } + if( Mechanik != nullptr ) { return Mechanik->TrainName(); } + return "none"; } }; // shouldn't get here but, eh + auto const instance { [this, &Instancing]() -> std::string { + if( Instancing == "name" ) { return MoverParameters->Name; } + if( Instancing == "type" ) { return MoverParameters->TypeName; } + return "none"; } }; + + std::string signrequest { + "make:" + + Script + + "?" + // timetable include + + "$timetable=" + ( + ctOwner == nullptr ? + MoverParameters->Name : // leading vehicle, can point to it directly + ctOwner->Vehicle()->MoverParameters->Name ) // owned vehicle, safer to point to owner as carriages can have identical names + // basic instancing string + // NOTE: underscore doesn't have any magic meaning for the time being, it's just less likely to conflict with regular dictionary keys + + "&_id1=" + trainname() }; + // TBD, TODO: replace instancing with support for variables in extra parameters string? + if( false == Instancing.empty() ) { + signrequest += "&_id2=" + instance(); + } + // optionl extra parameters + if( false == Parameters.empty() ) { + signrequest += "&" + Parameters; + } + return signrequest; +} + +script_screens::screen_config const *TDynamicObject::script_destination( script_language &Language ) const { + + auto const &screens { Application.screens() }; + if( false == DestinationSign.lua.script.empty() && screens.runs( script_language::lua ) ) { + Language = script_language::lua; + return &DestinationSign.lua; + } + if( false == DestinationSign.wasm.script.empty() && screens.runs( script_language::wasm ) ) { + Language = script_language::wasm; + return &DestinationSign.wasm; + } + return nullptr; // no script sign, maybe a python one +} + +bool TDynamicObject::destination_set_script( std::string const &Numer ) { + + if( Numer == "none" ) { return false; } // blank or incomplete/malformed timetable, don't bother + auto language { script_language::lua }; + auto const *scriptsign { script_destination( language ) }; + if( scriptsign == nullptr ) { return false; } + + auto const signrequest { destination_request( scriptsign->script, scriptsign->instancing, scriptsign->parameters ) }; + auto const signmaterial { GfxRenderer->Fetch_Material( signrequest ) }; + if( signmaterial == null_handle ) { return false; } + auto &signtexture { GfxRenderer->Texture( GfxRenderer->Material( signmaterial )->GetTexture( 0 ) ) }; + + // vehicles showing the same request (one train, one instance) share the screen, as they share the texture + auto sign { Application.screens().acquire( { + .kind = script_screen_kind::external, + .language = language, + .script = scriptsign->script, + .key = signrequest, + .texture = &signtexture, + .frames = scriptsign->frames } ) }; + if( sign == nullptr ) { return false; } + + DestinationSign.destination = signmaterial; + DestinationSign.script_sign = std::move( sign ); + DestinationSign.script_request = signrequest.substr( signrequest.find( '?' ) + 1 ); + return true; +} + +std::shared_ptr TDynamicObject::draw_script_texture( std::string const &Name, material_handle const Material ) { + + if( false == Name.starts_with( "make:" ) || Material == null_handle ) { return nullptr; } + auto const query { Name.find( '?' ) }; + auto const script { Name.substr( 5, query == std::string::npos ? std::string::npos : query - 5 ) }; + auto const language { script_language_of( script ) }; + if( false == language.has_value() ) { return nullptr; } // a python texture, made by the texture itself + if( false == script_screens::screen_script_path( "", script ).has_value() ) { + ErrorLog( "Bad script texture: \"" + script + "\" leads outside the game's folder" ); + return nullptr; + } + + auto &queue { Application.screens() }; + auto &texture { GfxRenderer->Texture( GfxRenderer->Material( Material )->GetTexture( 0 ) ) }; + auto screen { queue.acquire( { + .kind = script_screen_kind::external, + .language = *language, + .script = script, + .key = Name, + .texture = &texture, + .frames = 0 } ) }; + if( screen == nullptr ) { return nullptr; } + queue.submit( + screen, + query == std::string::npos ? + std::make_shared() : + std::make_shared( Name.substr( query + 1 ) ), + 0 ); + return screen; +} + +material_handle TDynamicObject::DestinationFind( std::string Destination ) { + + if( Destination.empty() ) { return null_handle; } + + // destination textures are kept in the vehicle's directory so we point the current texture path there + auto const currenttexturepath { Global.asCurrentTexturePath }; + Global.asCurrentTexturePath = asBaseDir; + + auto destinationhandle { null_handle }; + + if( Destination.starts_with("make:") ) { + // autogenerated texture + destinationhandle = GfxRenderer->Fetch_Material( Destination ); + } + else { + // regular texture + Destination = Bezogonkow( Destination ); // do szukania pliku obcinamy ogonki + // now see if we can find any version of the texture + std::vector const destinations { + Destination + '@' + MoverParameters->TypeName, + Destination }; + + for( auto const &destination : destinations ) { + auto material = TextureTest( ToLower( destination ) ); + if( false == material.empty() ) { + destinationhandle = GfxRenderer->Fetch_Material( material ); + break; + } + } + } + // whether we got anything, restore previous texture path + Global.asCurrentTexturePath = currenttexturepath; + + return destinationhandle; +} + +void TDynamicObject::announce( announcement_t const Announcement, bool const Chime ) { + + if( m_doorspeakers.empty() ) { return; } + + auto const *driver { ( + ctOwner != nullptr ? + ctOwner : + Mechanik ) }; + if( driver == nullptr ) { return; } + + auto const &timetable { driver->TrainTimetable() }; + auto const &announcements { m_pasystem.announcements }; + auto playchime { Chime }; + + if( announcements[ static_cast( Announcement ) ].empty() ) { + goto followup; + } + // if the announcement sound was defined queue playback + { + sound_source stopnamesound; + switch( Announcement ) { + case announcement_t::approaching: + case announcement_t::next: { + stopnamesound = timetable.next_stop_sound(); + break; + } + case announcement_t::current: { + stopnamesound = timetable.current_stop_sound(); + break; + } + case announcement_t::destination: { + stopnamesound = timetable.last_stop_sound(); + break; + } + default: { + break; + } + } + if( stopnamesound.empty() ) { + goto followup; + } + // potentially precede the announcement with a chime... + if( true == playchime + && false == announcements[static_cast(announcement_t::chime)].empty() ) { + m_pasystem.announcement_queue.emplace_back( announcements[ static_cast( announcement_t::chime ) ] ); + playchime = false; + } + // ...then play the announcement itself + m_pasystem.announcement_queue.emplace_back( announcements[ static_cast( Announcement ) ] ); + m_pasystem.announcement_queue.emplace_back( stopnamesound ); + } +followup: + // potentially follow up with another announcement + if( Announcement == announcement_t::next ) { + announce( announcement_t::destination, playchime ); + } +} diff --git a/vehicle/dynamic/internal.h b/vehicle/dynamic/internal.h new file mode 100644 index 000000000..52ae88dec --- /dev/null +++ b/vehicle/dynamic/internal.h @@ -0,0 +1,80 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the constants and helpers the files of the vehicles of the scenery share: only they include this header + +#pragma once + +#include "vehicle/DynObj.h" +#include "physics/mover.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" + +// Ra: taki zapis funkcjonuje lepiej, ale może nie jest optymalny +#define vWorldFront glm::vec3(0, 0, 1) +#define vWorldUp glm::vec3(0, 1, 0) +#define vWorldLeft glm::cross(vWorldUp, vWorldFront) + +#define M_2PI 6.283185307179586476925286766559; + +TSubModel * +GetSubmodelFromName( TModel3d * const Model, std::string const Name ); + +bool outside( glm::dvec3 const &Centre, double const Radius, glm::dvec2 const &Min, glm::dvec2 const &Max ); + + +// the time spent off the track in a frame which makes it worth a warning [s] +constexpr double off_track_slow { 0.02 }; + + +using off_track_clock = std::chrono::steady_clock; + +double seconds_since( off_track_clock::time_point const Start ); + diff --git a/vehicle/dynamic/lifecycle.cpp b/vehicle/dynamic/lifecycle.cpp new file mode 100644 index 000000000..a442440d3 --- /dev/null +++ b/vehicle/dynamic/lifecycle.cpp @@ -0,0 +1,889 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// a vehicle of the scenery made, set up from its definition and removed + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/mover.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + +const float maxrot = (float)(M_PI / 3.0); // 60° + +std::string const TDynamicObject::MED_labels[] = { + "masa: ", "amax: ", "Fzad: ", "FmPN: ", "FmED: ", "FrED: ", "FzPN: ", "nPrF: " +}; + +bool TDynamicObject::bDynamicRemove { false }; + +// helper, locates submodel with specified name in specified 3d model; returns: pointer to the submodel, or null +TSubModel * +GetSubmodelFromName( TModel3d * const Model, std::string const Name ) { + + return Model ? Model->GetFromName(Name) : nullptr; +} + +TDynamicObject::TDynamicObject() { + modelShake = glm::dvec3(0, 0, 0); +// fTrackBlock = 10000.0; // brak przeszkody na drodze + btnOn = false; + vUp = vWorldUp; + vFront = vWorldFront; + vLeft = vWorldLeft; + iNumAxles = 0; + MoverParameters = nullptr; + Mechanik = nullptr; + MechInside = false; + // McZapkie-270202 + Controller = AIdriver; + bDisplayCab = false; // 030303 +// NextConnected = PrevConnected = NULL; +// NextConnectedNo = PrevConnectedNo = 2; // ABu: Numery sprzegow. 2=nie podłączony + bEnabled = true; + MyTrack = nullptr; + // McZapkie-260202 + dWheelAngle[0] = 0.0; + dWheelAngle[1] = 0.0; + dWheelAngle[2] = 0.0; + // Winger 160204 - pantografy + // PantVolume = 3.5; + NoVoltTime = 0; + mdModel = nullptr; + mdKabina = nullptr; + // smWiazary[0]=smWiazary[1]=NULL; + smWahacze[0] = smWahacze[1] = smWahacze[2] = smWahacze[3] = nullptr; + fWahaczeAmp = 0; + smBrakeMode = nullptr; + smLoadMode = nullptr; + mdLoad = nullptr; + mdLowPolyInt = nullptr; + //smMechanik0 = smMechanik1 = NULL; + smBuforLewy[0] = smBuforLewy[1] = nullptr; + smBuforPrawy[0] = smBuforPrawy[1] = nullptr; + smBogie[0] = smBogie[1] = nullptr; + bogieRot[0] = bogieRot[1] = glm::dvec3(0, 0, 0); + modelRot = glm::dvec3(0, 0, 0); + cp1 = cp2 = sp1 = sp2 = 0; + iDirection = 1; // stoi w kierunku tradycyjnym (0, gdy jest odwrócony) + iAxleFirst = 0; // numer pierwszej osi w kierunku ruchu (przełączenie + // następuje, gdy osie sa na + // tym samym torze) + RaLightsSet(0, 0); // początkowe zerowanie stanu świateł + // Ra: domyślne ilości animacji dla zgodności wstecz (gdy brak ilości podanych + // w MMD) + // ustawienie liczby modeli animowanych podczas konstruowania obiektu a nie na 0 + // prowadzi prosto do wysypów jeśli źle zdefiniowane mmd + iAnimations = 0; // na razie nie ma żadnego + pAnimated = nullptr; + fShade = 0.0; // standardowe oświetlenie na starcie + iHornWarning = 1; // numer syreny do użycia po otrzymaniu sygnału do jazdy + asDestination = "none"; // stojący nigdzie nie jedzie + pValveGear = nullptr; // Ra: tymczasowo + iCabs = 0; // maski bitowe modeli kabin + smBrakeSet = nullptr; // nastawa hamulca (wajcha) + smLoadSet = nullptr; // nastawa ładunku (wajcha) + smWiper = nullptr; // wycieraczka (poniekąd też wajcha) + ctOwner = nullptr; // na początek niczyj + iOverheadMask = 0; // maska przydzielana przez AI pojazdom posiadającym + // pantograf, aby wymuszały + // jazdę bezprądową + tmpTraction.TractionVoltage = 0; // Ra 2F1H: prowizorka, trzeba przechować + // napięcie, żeby nie wywalało WS pod + // izolatorem + fAdjustment = 0.0; // korekcja odległości pomiędzy wózkami (np. na łukach) +} + +TDynamicObject::~TDynamicObject() { + SafeDelete( Mechanik ); + SafeDelete( MoverParameters ); + SafeDeleteArray( pAnimated ); // lista animowanych submodeli +} + +void TDynamicObject::place_on_track(TTrack *Track, double fDist, bool Reversed) +{ + for( auto &axle : m_axlesounds ) { + // wyszukiwanie osi (0 jest na końcu, dlatego dodajemy długość?) + axle.distance = ( + Reversed ? + -axle.offset : + axle.offset + MoverParameters->Dim.L ) + fDist; + } + double fAxleDistHalf = fAxleDist * 0.5; + // przesuwanie pojazdu tak, aby jego początek był we wskazanym miejcu + fDist -= 0.5 * MoverParameters->Dim.L; // dodajemy pół długości pojazdu, bo ustawiamy jego środek (zliczanie na minus) + switch (iNumAxles) { + // Ra: pojazdy wstawiane są na tor początkowy, a potem przesuwane + case 2: // ustawianie osi na torze + Axle0.Reset(); + Axle0.Init(Track, this, iDirection ? 1 : -1); + Axle0.Move((iDirection ? fDist : -fDist) + fAxleDistHalf, false); + Axle1.Reset(); + Axle1.Init(Track, this, iDirection ? 1 : -1); + Axle1.Move((iDirection ? fDist : -fDist) - fAxleDistHalf, false); // false, żeby nie generować eventów + break; + } + // the stretches the criteria of derailment held over were on the track the vehicle left (consistteleport) + MoverParameters->derailment_monitor.reset(); + MoverParameters->derailment_distance = 0.0; + // potrzebne do wyliczenia aktualnej pozycji; nie może być zero, bo nie przeliczy pozycji + // teraz jeszcze trzeba przypisać pojazdy do nowego toru, bo przesuwanie początkowe osi nie + // zrobiło tego + Move( 0.0001 ); + ABuCheckMyTrack(); // zmiana toru na ten, co oś Axle0 (oś z przodu) +} + +double +TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" + std::string BaseDir, // z którego katalogu wczytany, np. "PKP/EU07" + std::string asReplacableSkin, // nazwa wymiennej tekstury + std::string Type_Name, // nazwa CHK/MMD, np. "303E" + TTrack *Track, // tor początkowy wstwawienia (początek składu) + double fDist, // dystans względem punktu 1 + std::string DriverType, // typ obsady + double fVel, // prędkość początkowa + std::string TrainName, // nazwa składu, np. "PE2307" albo Vmax, jeśli pliku nie ma a są cyfry + float Load, // ilość ładunku + std::string LoadType, // nazwa ładunku + bool Reversed, // true, jeśli ma stać odwrotnie w składzie + std::string MoreParams // dodatkowe parametry wczytywane w postaci tekstowej + ) +{ // Ustawienie początkowe pojazdu + iDirection = Reversed ? 0 : 1; // Ra: 0, jeśli ma być wstawiony jako obrócony tyłem + asBaseDir = paths::dynamic + BaseDir + "/"; // McZapkie-310302 + asName = Name; + // derived from the name and the seed of the simulation rather than drawn at random, so that the vehicle + // keeps the same look for the whole session and looks the same for everyone in a multiplayer game, while + // another run of the same scenario, with another seed, dresses it differently + m_variantseed = hash_string( asName, Global.random_seed ); + std::string asAnimName; // zmienna robocza do wyszukiwania osi i wózków + // a vehicle prepared for being hauled dead (parameter H after its coupling, MaSzyna-EU07/maszyna#64) has nobody + // driving it, whatever its crew entry says: its cab can't be activated, and a driver in it would either take + // the train or be one more for the train's driver to put to sleep + auto const hauled { pullee_mode::requested( MoreParams ) }; + if( hauled && ( DriverType == "headdriver" || DriverType == "reardriver" ) ) { + WriteLog( "Vehicle " + asName + " is prepared for hauling (parameter H), the driver it was given is left out" ); + DriverType = "nobody"; + } + // Ra: zmieniamy znaczenie obsady na jednoliterowe, żeby dosadzić kierownika + if (DriverType == "headdriver") + DriverType = "1"; // sterujący kabiną +1 + else if (DriverType == "reardriver") + DriverType = "2"; // sterujący kabiną -1 + else if (DriverType == "passenger") + DriverType = ""; // legacy type, no longer needed + else if (DriverType == "nobody") + DriverType = ""; // nikt nie siedzi + + int Cab = 0; // numer kabiny z obsadą (nie można zająć obu) + if (DriverType == "1") // od przodu składu + Cab = 1; // iDirection?1:-1; //iDirection=1 gdy normalnie, =0 odwrotnie + else if (DriverType == "2") // od tyłu składu + Cab = -1; // iDirection?-1:1; +/* + // NOTE: leave passenger in the middle section, this is most likely to be 'passenger' section in MU trains + else if (DriverType == "p") + { + if (Random(6) < 3) + Cab = 1; + else + Cab = -1; // losowy przydział kabiny + } +*/ + // utworzenie parametrów fizyki + MoverParameters = new TMoverParameters(iDirection ? fVel : -fVel, Type_Name, asName, Cab); + // the vehicle carries on with the odometer state of its earlier sessions (eu07/maszyna#72) + MoverParameters->Odometer = odometer::starting_state( odometer::states(), asName, asBaseDir ); + // McZapkie: TypeName musi byc nazwą CHK/MMD pojazdu + if (!MoverParameters->LoadFIZ(asBaseDir)) + { // jak wczytanie CHK się nie uda, to błąd + if (ConversionError == 666) + ErrorLog( "Bad vehicle: failed to locate definition file \"" + BaseDir + "/" + Type_Name + ".fiz" + "\"" ); + else { + ErrorLog( "Bad vehicle: failed to load definition from file \"" + BaseDir + "/" + Type_Name + ".fiz\" (error " + std::to_string( ConversionError ) + ")" ); + } + return 0.0; // zerowa długość to brak pojazdu + } + // load the cargo now that we know whether the vehicle will allow it + MoverParameters->AssignLoad( LoadType, Load ); + MoverParameters->ComputeMass(); + + bool driveractive = fVel != 0.0; // jeśli prędkość niezerowa, to aktywujemy ruch + if (!MoverParameters->CheckLocomotiveParameters( + driveractive, + (fVel > 0 ? 1 : -1) * Cab * + (iDirection ? 1 : -1))) // jak jedzie lub obsadzony to gotowy do drogi + { + Error("Parameters mismatch: dynamic object " + asName + " from \"" + BaseDir + "/" + Type_Name + "\"" ); + return 0.0; // zerowa długość to brak pojazdu + } + // controller position + MoverParameters->MainCtrlPos = MoverParameters->MainCtrlNoPowerPos(); + // ustawienie pozycji hamulca + MoverParameters->LocalBrakePosA = 0.0; + if (driveractive) + { + if (Cab == 0) + MoverParameters->BrakeCtrlPos = + static_cast( std::floor(MoverParameters->Handle->GetPos(bh_NP)) ); + else + MoverParameters->BrakeCtrlPos = static_cast( std::floor(MoverParameters->Handle->GetPos(bh_RP)) ); + + // engage independent brake if applicable, if the vehicle is to be on standby + // NOTE: with more than one driver in the consist this is likely to go awery, since all but one will be sent to sleep + // TBD, TODO: have the virtual helper release independent brakes during consist check? + if( DriverType != "" ) { + if( MoverParameters->LocalBrake != TLocalBrake::ManualBrake ) { + if( fVel < 1.0 ) { + MoverParameters->IncLocalBrakeLevel( LocalBrakePosNo ); + if ( MoverParameters->EIMCtrlEmergency ) { + MoverParameters->DecLocalBrakeLevel(1); + } + } + } + } + } + else + MoverParameters->BrakeCtrlPos = + static_cast( std::floor(MoverParameters->Handle->GetPos(bh_NP)) ); + + // poprawienie hamulca po ewentualnym przestawieniu przez Pascal + // TODO: check if needed, we're not in Pascal anymore, Toto + MoverParameters->BrakeLevelSet(MoverParameters->BrakeCtrlPos); + + // dodatkowe parametry yB + MoreParams += "."; // wykonuje o jedną iterację za mało, więc trzeba mu dodać + // kropkę na koniec + size_t kropka = MoreParams.find("."); // znajdź kropke + std::string ActPar; // na parametry + while (kropka != std::string::npos) // jesli sa kropki jeszcze + { + size_t dlugosc = MoreParams.length(); + ActPar = ToUpper(MoreParams.substr(0, kropka)); // pierwszy parametr; + MoreParams = MoreParams.substr(kropka + 1, dlugosc - kropka); // reszta do dalszej obrobki + kropka = MoreParams.find("."); + + if (ActPar.substr(0, 1) == "B") // jesli hamulce + { // sprawdzanie kolejno nastaw + WriteLog("Wpis hamulca: " + ActPar); + if ( contains( ActPar, 'G') ) + { + MoverParameters->BrakeDelaySwitch(bdelay_G); + } + if( contains( ActPar, 'P' ) ) + { + MoverParameters->BrakeDelaySwitch(bdelay_P); + } + if( contains( ActPar, 'R' ) ) + { + MoverParameters->BrakeDelaySwitch(bdelay_R); + } + if( contains( ActPar, 'M' ) ) + { + MoverParameters->BrakeDelaySwitch(bdelay_R); + MoverParameters->BrakeDelaySwitch(bdelay_R + bdelay_M); + } + // wylaczanie hamulca + if ( contains( ActPar, "<>") ) // wylaczanie na probe hamowania naglego + { + MoverParameters->Hamulec->SetBrakeStatus( MoverParameters->Hamulec->GetBrakeStatus() | b_dmg ); // wylacz + } + if ( contains( ActPar, '0' ) ) // wylaczanie na sztywno + { + MoverParameters->Hamulec->ForceEmptiness(); + MoverParameters->Hamulec->SetBrakeStatus( MoverParameters->Hamulec->GetBrakeStatus() | b_dmg ); // wylacz + } + if ( contains( ActPar, 'E' ) ) // oprozniony + { + MoverParameters->Hamulec->ForceEmptiness(); + MoverParameters->Pipe->CreatePress(0); + MoverParameters->Pipe2->CreatePress(0); + } + if ( contains( ActPar, 'Q' ) ) // oprozniony + { + MoverParameters->Hamulec->ForceEmptiness(); + MoverParameters->Pipe->CreatePress(0.0); + MoverParameters->PipePress = 0.0; + MoverParameters->Pipe2->CreatePress(0.0); + MoverParameters->ScndPipePress = 0.0; + MoverParameters->PantVolume = 0.1; + MoverParameters->PantPress = 0.0; + MoverParameters->CompressedVolume = 0.0; + } + + if ( contains( ActPar, '1' ) ) // wylaczanie 10% + { + if (Random(10) < 1) // losowanie 1/10 + { + MoverParameters->Hamulec->ForceEmptiness(); + MoverParameters->Hamulec->SetBrakeStatus( MoverParameters->Hamulec->GetBrakeStatus() | b_dmg ); // wylacz + } + } + if ( contains( ActPar, 'X') ) // agonalny wylaczanie 20%, usrednienie przekladni + { + if (Random(100) < 20) // losowanie 20/100 + { + MoverParameters->Hamulec->ForceEmptiness(); + MoverParameters->Hamulec->SetBrakeStatus( MoverParameters->Hamulec->GetBrakeStatus() | b_dmg ); // wylacz + } + if (MoverParameters->BrakeCylMult[2] * MoverParameters->BrakeCylMult[1] > + 0.01) // jesli jest nastawiacz mechaniczny PL + { + float rnd = Random(100); + if (rnd < 20) // losowanie 20/100 usrednienie + { + MoverParameters->BrakeCylMult[2] = MoverParameters->BrakeCylMult[1] = + (MoverParameters->BrakeCylMult[2] + MoverParameters->BrakeCylMult[1]) / + 2; + } + else if (rnd < 70) // losowanie 70/100-20/100 oslabienie + { + MoverParameters->BrakeCylMult[1] = MoverParameters->BrakeCylMult[1] * 0.50; + MoverParameters->BrakeCylMult[2] = MoverParameters->BrakeCylMult[2] * 0.75; + } + else if (rnd < 80) // losowanie 80/100-70/100 tylko prozny + { + MoverParameters->BrakeCylMult[2] = MoverParameters->BrakeCylMult[1]; + } + else // tylko ladowny + { + MoverParameters->BrakeCylMult[1] = MoverParameters->BrakeCylMult[2]; + } + } + } + // nastawianie ladunku + if ( contains( ActPar, 'T' ) ) // prozny + { + MoverParameters->DecBrakeMult(); + MoverParameters->DecBrakeMult(); + } // dwa razy w dol + if ( contains( ActPar, 'H' ) ) // ladowny I (dla P-Ł dalej prozny) + { + MoverParameters->IncBrakeMult(); + MoverParameters->IncBrakeMult(); + MoverParameters->DecBrakeMult(); + } // dwa razy w gore i obniz + if ( contains( ActPar, 'F' ) ) // ladowny II + { + MoverParameters->IncBrakeMult(); + MoverParameters->IncBrakeMult(); + } // dwa razy w gore + if ( contains( ActPar, 'N' ) ) // parametr neutralny + { + } + } // koniec hamulce + else if( ActPar.size() >= 3 + && ActPar.front() == 'W' ) { + // wheel + ActPar.erase( 0, 1 ); + + auto fixedflatsize { 0 }; + auto randomflatsize { 0 }; + auto flatchance { 100 }; + + while( false == ActPar.empty() ) { + // TODO: convert this whole copy and paste mess to something more elegant one day + switch( ActPar.front() ) { + case 'F': { + // fixed flat size + auto const indexstart { 1 }; + auto const indexend { ActPar.find_first_not_of( "1234567890", indexstart ) }; + fixedflatsize = std::atoi( ActPar.substr( indexstart, indexend ).c_str() ); + ActPar.erase( 0, indexend ); + break; + } + case 'R': { + // random flat size + auto const indexstart { 1 }; + auto const indexend { ActPar.find_first_not_of( "1234567890", indexstart ) }; + randomflatsize = std::atoi( ActPar.substr( indexstart, indexend ).c_str() ); + ActPar.erase( 0, indexend ); + break; + } + case 'P': { + // random flat probability + auto const indexstart { 1 }; + auto const indexend { ActPar.find_first_not_of( "1234567890", indexstart ) }; + flatchance = std::atoi( ActPar.substr( indexstart, indexend ).c_str() ); + ActPar.erase( 0, indexend ); + break; + } + case 'H': { + // truck hunting + auto const indexstart { 1 }; + auto const indexend { ActPar.find_first_not_of( "1234567890", indexstart ) }; + auto const huntingchance { std::atoi( ActPar.substr( indexstart, indexend ).c_str() ) }; + MoverParameters->TruckHunting = Random(0, 100) < huntingchance; + ActPar.erase( 0, indexend ); + break; + } + default: { + // unrecognized key + ActPar.erase( 0, 1 ); + break; + } + } + } + if( Random( 0, 100 ) <= flatchance ) { + MoverParameters->WheelFlat += fixedflatsize + Random( 0, randomflatsize ); + } + } // wheel + else if( ActPar.size() >= 2 + && ActPar.front() == 'T' ) { + // temperature + ActPar.erase( 0, 1 ); + + auto setambient { false }; + + while( false == ActPar.empty() ) { + switch( ActPar.front() ) { + case 'A': { + // cold start, set all temperatures to ambient level + setambient = true; + ActPar.erase( 0, 1 ); + break; + } + default: { + // unrecognized key + ActPar.erase( 0, 1 ); + break; + } + } + } + if( true == setambient ) { + // TODO: pull ambient temperature from environment data + MoverParameters->dizel_HeatSet( Global.AirTemperature ); + } + } // temperature + else if( ActPar.size() >= 2 + && ActPar.front() == 'L' ) { + // load + ActPar.erase( 0, 1 ); + // immediately followed by max load override + // TBD: make it instead an optional sub-parameter? + { + auto const indexstart { 0 }; + auto const indexend { ActPar.find_first_not_of( "1234567890", indexstart ) }; + MoverParameters->MaxLoad = std::atoi( ActPar.substr( indexstart, indexend ).c_str() ); + ActPar.erase( 0, indexend ); + } + while( false == ActPar.empty() ) { + switch( ActPar.front() ) { + default: { + // unrecognized key + ActPar.erase( 0, 1 ); + break; + } + } + } + } // load +/* else if (ActPar.substr(0, 1) == "") // tu mozna wpisac inny prefiks i inne rzeczy + { + // jakies inne prefiksy + } +*/ + } // koniec while kropka + + if( hauled ) { + // once the vehicle has its starting state: the hand brake and the spring brake of a standing one let go, battery off + MoverParameters->PulleeModeSwitch( true ); + } + + if (MoverParameters->CategoryFlag & 2) // jeśli samochód + { // ustawianie samochodow na poboczu albo na środku drogi + if( Track->fTrackWidth < 3.5 // jeśli droga wąska + || Track->m_road != nullptr ) // a lane of a road node is one-way, the vehicle keeps to its middle + MoverParameters->OffsetTrackH = 0.0; // to stawiamy na środku, niezależnie od stanu + // ruchu + else if( driveractive ) {// od 3.5m do 8.0m jedzie po środku pasa, dla + // szerszych w odległości + // 1.5m + auto const lanefreespace = 0.5 * Track->fTrackWidth - MoverParameters->Dim.W; + MoverParameters->OffsetTrackH = lanefreespace > 1.5 ? + -0.5 * MoverParameters->Dim.W - 0.75 : // wide road, keep near centre with safe margin + lanefreespace > 0.1 ? + -0.25 * Track->fTrackWidth : // narrow fit, stay on the middle + -0.5 * MoverParameters->Dim.W - 0.075; // too narrow, just keep some minimal clearance + } + else // jak stoi, to kołem na poboczu i pobieramy szerokość razem z + // poboczem, ale nie z + // chodnikiem + MoverParameters->OffsetTrackH = + -0.5 * (Track->WidthTotal() - MoverParameters->Dim.W) + 0.05; + iHornWarning = 0; // nie będzie trąbienia po podaniu zezwolenia na jazdę + if (fDist < 0.0) //-0.5*MoverParameters->Dim.L) //jeśli jest przesunięcie do tyłu + if (!Track->CurrentPrev()) // a nie ma tam odcinka i trzeba by coś + // wygenerować + fDist = -fDist; // to traktujemy, jakby przesunięcie było w drugą stronę + } + + create_controller( DriverType, !TrainName.empty() ); + + ShakeSpring.Init( 125.0 ); + BaseShake = baseshake_config {}; + ShakeState = shake_state {}; + ShakeStateBefore = shake_state {}; + + // McZapkie-250202 +/* + iAxles = std::min( MoverParameters->NAxles, MaxAxles ); // ilość osi +*/ + // wczytywanie z pliku nazwatypu.mmd, w tym model + erase_extension( asReplacableSkin ); + LoadMMediaFile(Type_Name, asReplacableSkin); + // McZapkie-100402: wyszukiwanie submodeli sprzegów + btCoupler1.Init( "coupler1", mdModel ); // false - ma być wyłączony + btCoupler2.Init( "coupler2", mdModel ); + // brake hoses + btCPneumatic1.Init("cpneumatic1", mdModel); + btCPneumatic2.Init("cpneumatic2", mdModel); + btCPneumatic1r.Init("cpneumatic1r", mdModel); + btCPneumatic2r.Init("cpneumatic2r", mdModel); + // main hoses + btPneumatic1.Init("pneumatic1", mdModel); + btPneumatic2.Init("pneumatic2", mdModel); + btPneumatic1r.Init("pneumatic1r", mdModel); + btPneumatic2r.Init("pneumatic2r", mdModel); + // control cables + btCCtrl1.Init( "cctrl1", mdModel, false); + btCCtrl2.Init( "cctrl2", mdModel, false); + // gangways + btCPass1.Init( "cpass1", mdModel, false); + btCPass2.Init( "cpass2", mdModel, false); + // sygnaly + m_endsignal12.Init( "endsignal12", mdModel, false ); + m_endsignal13.Init( "endsignal13", mdModel, false ); + m_endsignal22.Init( "endsignal22", mdModel, false ); + m_endsignal23.Init( "endsignal23", mdModel, false ); + m_endsignals1.Init( "endsignals1", mdModel, false ); + m_endsignals2.Init( "endsignals2", mdModel, false ); + m_endtab1.Init( "endtab1", mdModel, false ); + m_endtab2.Init( "endtab2", mdModel, false ); + m_headlamp11.Init( "headlamp11", mdModel ); // górne + m_headlamp12.Init( "headlamp12", mdModel ); // prawe + m_headlamp13.Init( "headlamp13", mdModel ); // lewe + m_highbeam12.Init("highbeam12", mdModel); // prawe dlugie + m_highbeam13.Init("highbeam13", mdModel); // lewe dlugie + m_headlamp21.Init( "headlamp21", mdModel ); + m_headlamp22.Init( "headlamp22", mdModel ); + m_headlamp23.Init( "headlamp23", mdModel ); + m_highbeam22.Init("highbeam22", mdModel); + m_highbeam23.Init("highbeam23", mdModel); + m_headsignal12.Init( "headsignal12", mdModel ); + m_headsignal13.Init( "headsignal13", mdModel ); + m_headsignal22.Init( "headsignal22", mdModel ); + m_headsignal23.Init( "headsignal23", mdModel ); + // informacja, czy ma poszczególne światła + iInventory[ end::front ] |= m_endsignal12.Active() ? light::redmarker_right : 0; + iInventory[ end::front ] |= m_endsignal13.Active() ? light::redmarker_left : 0; + iInventory[ end::rear ] |= m_endsignal22.Active() ? light::redmarker_right : 0; + iInventory[ end::rear ] |= m_endsignal23.Active() ? light::redmarker_left : 0; + iInventory[ end::front ] |= m_endsignals1.Active() ? light::redmarker_left | light::redmarker_right : 0; + iInventory[ end::rear ] |= m_endsignals2.Active() ? light::redmarker_left | light::redmarker_right : 0; + iInventory[ end::front ] |= m_endtab1.Active() ? light::rearendsignals : 0; // tabliczki blaszane + iInventory[ end::rear ] |= m_endtab2.Active() ? light::rearendsignals : 0; + iInventory[ end::front ] |= m_headlamp11.Active() ? light::headlight_upper : 0; + iInventory[ end::front ] |= m_headlamp12.Active() ? light::headlight_right : 0; + iInventory[ end::front ] |= m_headlamp13.Active() ? light::headlight_left : 0; + + iInventory[end::front] |= m_highbeam12.Active() ? light::highbeamlight_right : 0; + iInventory[end::front] |= m_highbeam13.Active() ? light::highbeamlight_left : 0; + + iInventory[ end::rear ] |= m_headlamp21.Active() ? light::headlight_upper : 0; + iInventory[ end::rear ] |= m_headlamp22.Active() ? light::headlight_right : 0; + iInventory[ end::rear ] |= m_headlamp23.Active() ? light::headlight_left : 0; + iInventory[ end::front ] |= m_headsignal12.Active() ? light::auxiliary_right : 0; + iInventory[ end::front ] |= m_headsignal13.Active() ? light::auxiliary_left : 0; + iInventory[ end::rear ] |= m_headsignal22.Active() ? light::auxiliary_right : 0; + iInventory[ end::rear ] |= m_headsignal23.Active() ? light::auxiliary_left : 0; + + iInventory[end::rear] |= m_highbeam22.Active() ? light::highbeamlight_right : 0; + iInventory[end::rear] |= m_highbeam23.Active() ? light::highbeamlight_left : 0; + + btExteriorOnly.Init("external_only", mdModel, false); + + btMechanik1.Init( "mechanik1", mdLowPolyInt, false); + btMechanik2.Init( "mechanik2", mdLowPolyInt, false); + + if( MoverParameters->dizel_heat.water.config.shutters ) { + btShutters1.Init( "shutters1", mdModel, false ); + } + if( MoverParameters->dizel_heat.water_aux.config.shutters ) { + btShutters2.Init( "shutters2", mdModel, false ); + } + TurnOff(); // resetowanie zmiennych submodeli + + if( mdLowPolyInt != nullptr ) { + // check the low poly interior for potential compartments of interest, ie ones which can be individually lit + // TODO: definition of relevant compartments in the .mmd file + TSubModel *submodel { nullptr }; + if( ( submodel = mdLowPolyInt->GetFromName( "cab0" ) ) != nullptr ) { + Sections.push_back( { submodel, nullptr, 0, 0.0f } ); + LowPolyIntCabs[ 0 ] = submodel; + } + if( ( submodel = mdLowPolyInt->GetFromName( "cab1" ) ) != nullptr ) { + Sections.push_back( { submodel, nullptr, 0, 0.0f } ); + LowPolyIntCabs[ 1 ] = submodel; + } + if( ( submodel = mdLowPolyInt->GetFromName( "cab2" ) ) != nullptr ) { + Sections.push_back( { submodel, nullptr, 0, 0.0f } ); + LowPolyIntCabs[ 2 ] = submodel; + } + // passenger car compartments + std::vector nameprefixes = { "corridor", "korytarz", "compartment", "przedzial" }; + for( auto const &nameprefix : nameprefixes ) { + init_sections( mdLowPolyInt, nameprefix, MoverParameters->CompartmentLights.start_type == start_t::manual ); + } + // the inside of the door wings, if the interior has them + init_interior_doors(); + } + // destination sign + if( mdModel ) { + init_destination( mdModel ); + } + // 'external_load' is an optional special section in the main model, pointing to submodel of external load + if( mdModel ) { + init_sections( mdModel, "external_load", false ); + } + update_load_sections(); + update_load_visibility(); + // wyszukiwanie zderzakow + if( mdModel ) { + // jeśli ma w czym szukać + for( int i = 0; i < 2; i++ ) { + asAnimName = std::string( "buffer_left0" ) + std::to_string( i + 1 ); + smBuforLewy[ i ] = mdModel->GetFromName( asAnimName ); + if( smBuforLewy[ i ] ) + smBuforLewy[ i ]->WillBeAnimated(); // ustawienie flagi animacji + asAnimName = std::string( "buffer_right0" ) + std::to_string( i + 1 ); + smBuforPrawy[ i ] = mdModel->GetFromName( asAnimName ); + if( smBuforPrawy[ i ] ) + smBuforPrawy[ i ]->WillBeAnimated(); + } + } + if( Track->fSoundDistance > 0.f ) { + for( auto &axle : m_axlesounds ) { + // wyszukiwanie osi (0 jest na końcu, dlatego dodajemy długość?) + axle.distance = + clamp_circular( + ( Reversed ? + -axle.offset : + axle.offset ) + - 0.5 * MoverParameters->Dim.L + + fDist, + Track->fSoundDistance ); + } + } + // McZapkie-250202 end. + Track->AddDynamicObject(this); // wstawiamy do toru na pozycję 0, a potem przesuniemy + // McZapkie: zmieniono na ilosc osi brane z chk + // iNumAxles=(MoverParameters->NAxles>3 ? 4 : 2 ); + initial_track = MyTrack; + iNumAxles = 2; + // McZapkie-090402: odleglosc miedzy czopami skretu lub osiami + fAxleDist = safe_clamp( + std::max( MoverParameters->BDist, MoverParameters->ADist ), + 0.2, //żeby się dało wektory policzyć + MoverParameters->Dim.L - 0.2 ); // nie mogą być za daleko bo będzie "walenie w mur" + double fAxleDistHalf = fAxleDist * 0.5; + // przesuwanie pojazdu tak, aby jego początek był we wskazanym miejcu + fDist -= 0.5 * MoverParameters->Dim.L; // dodajemy pół długości pojazdu, bo ustawiamy jego środek (zliczanie na minus) + switch (iNumAxles) { + // Ra: pojazdy wstawiane są na tor początkowy, a potem przesuwane + case 2: // ustawianie osi na torze + Axle0.Init(Track, this, iDirection ? 1 : -1); + Axle0.Move((iDirection ? fDist : -fDist) + fAxleDistHalf, false); + Axle1.Init(Track, this, iDirection ? 1 : -1); + Axle1.Move((iDirection ? fDist : -fDist) - fAxleDistHalf, false); // false, żeby nie generować eventów + break; + case 4: + Axle0.Init(Track, this, iDirection ? 1 : -1); + Axle0.Move((iDirection ? fDist : -fDist) + (fAxleDistHalf + MoverParameters->ADist * 0.5), false); + Axle1.Init(Track, this, iDirection ? 1 : -1); + Axle1.Move((iDirection ? fDist : -fDist) - (fAxleDistHalf + MoverParameters->ADist * 0.5), false); + // Axle2.Init(Track,this,iDirection?1:-1); + // Axle2.Move((iDirection?fDist:-fDist)-(fAxleDistHalf-MoverParameters->ADist*0.5),false); + // Axle3.Init(Track,this,iDirection?1:-1); + // Axle3.Move((iDirection?fDist:-fDist)+(fAxleDistHalf-MoverParameters->ADist*0.5),false); + break; + } + // potrzebne do wyliczenia aktualnej pozycji; nie może być zero, bo nie przeliczy pozycji + // teraz jeszcze trzeba przypisać pojazdy do nowego toru, bo przesuwanie początkowe osi nie + // zrobiło tego + Move( 0.0001 ); + ABuCheckMyTrack(); // zmiana toru na ten, co oś Axle0 (oś z przodu) + // Ra: ustawienie pozycji do obliczania sprzęgów + MoverParameters->Loc = { + -vPosition.x, + vPosition.z, + vPosition.y }; // normalnie przesuwa ComputeMovement() w Update() + // ABuWozki 060504 + if (mdModel) // jeśli ma w czym szukać + { + smBogie[0] = mdModel->GetFromName("bogie1"); // Ra: bo nazwy są małymi + smBogie[1] = mdModel->GetFromName("bogie2"); + if (!smBogie[0]) + smBogie[0] = mdModel->GetFromName("boogie01"); // Ra: alternatywna nazwa + if (!smBogie[1]) + smBogie[1] = mdModel->GetFromName("boogie02"); // Ra: alternatywna nazwa + if (smBogie[0]) + smBogie[0]->WillBeAnimated(); + if (smBogie[1]) + smBogie[1]->WillBeAnimated(); + sm_winter_variant = mdModel->GetFromName("winter_variant"); + sm_spring_variant = mdModel->GetFromName("spring_variant"); + sm_summer_variant = mdModel->GetFromName("summer_variant"); + sm_autumn_variant = mdModel->GetFromName("autumn_variant"); + } + // ABu: zainicjowanie zmiennej, zeby nic sie nie ruszylo w pierwszej klatce, + // potem juz liczona prawidlowa wartosc masy + MoverParameters->ComputeConstans(); + // wektor podłogi dla wagonów, przesuwa ładunek + vFloor = glm::dvec3(0, 0, MoverParameters->Floor); + + // długość większa od zera oznacza OK; 2mm docisku? + return MoverParameters->Dim.L; +} + +int +TDynamicObject::init_sections( TModel3d const *Model, std::string const &Nameprefix, bool const Overrideselfillum ) { + + auto sectioncount = 0; + auto sectionindex = 0; + TSubModel *sectionsubmodel { nullptr }; + + do { + // section names for index < 10 match either prefix0X or prefixX + // section names above 10 match prefixX + auto const sectionindexname { std::to_string( sectionindex ) }; + sectionsubmodel = Model->GetFromName( Nameprefix + sectionindexname ); + if( sectionsubmodel == nullptr + && sectionindex < 10 ) { + sectionsubmodel = Model->GetFromName( Nameprefix + "0" + sectionindexname ); + } + if( sectionsubmodel != nullptr ) { + // HACK: disable automatic self-illumination threshold, at least until 3d model update + if( Overrideselfillum ) { + sectionsubmodel->SetSelfIllum( 2.0f, true, false ); + } + Sections.push_back( { + sectionsubmodel, + nullptr, // pointers to load sections are generated afterwards + 0, + 0.0f } ); + ++sectioncount; + } + ++sectionindex; + } while( sectionsubmodel != nullptr + || sectionindex < 2 ); // chain can start from prefix00 or prefix01 + + return sectioncount; +} + +// a door wing of the main model is seen from the outside, lit as the exterior. its namesake in the low poly interior, +// if the model has one, follows its moves and is lit with the interior, by its compartment section if it's in one +void +TDynamicObject::init_interior_doors() { + + if( mdLowPolyInt == nullptr ) { return; } + + for( auto &animation : pAnimations ) { + // the door animation is only set up for a wing found in the main model + if( false == door_wings::is_wing( animation.iFlags ) ) { continue; } + if( ( animation.yUpdate == nullptr ) || ( animation.smAnimated == nullptr ) ) { continue; } + + auto *interiorwing { mdLowPolyInt->GetFromName( animation.smAnimated->pName ) }; + if( ( interiorwing == nullptr ) || ( interiorwing == animation.smAnimated ) ) { continue; } + + interiorwing->WillBeAnimated(); + animation.smInterior = interiorwing; + } +} + +bool +TDynamicObject::init_destination( TModel3d *Model ) { + + if( Model->GetSMRoot() == nullptr ) { return false; } + + std::tie( DestinationSign.sign, DestinationSign.has_light ) = Model->GetSMRoot()->find_replacable4(); + + return DestinationSign.sign != nullptr; +} + +void +TDynamicObject::create_controller( std::string const Type, bool const Trainset ) { + + if( Type == "" ) { return; } + + // McZapkie-151102: rozkład jazdy czytany z pliku *.txt z katalogu w którym jest sceneria + if( Type == "1" + || Type == "2" ) { + // McZapkie-110303: mechanik i rozklad tylko gdy jest obsada + Mechanik = new TController( Controller, this, Aggressive ); + + if( false == Trainset ) { + // jeśli nie w składzie + // załączenie rozrządu (wirtualne kabiny) itd. + Mechanik->DirectionInitial(); + // tryb pociągowy z ustaloną prędkością (względem sprzęgów) + Mechanik->PutCommand( + "Timetable:", + MoverParameters->V * 3.6 * ( iDirection ? -1.0 : 1.0 ), + 0, + nullptr ); + } + } + else if( Type == "p" ) { + // obserwator w charakterze pasażera + // Ra: to jest niebezpieczne, bo w razie co będzie pomagał hamulcem bezpieczeństwa + Mechanik = new TController( Controller, this, Easyman, false ); + } +} diff --git a/vehicle/dynamic/lights.cpp b/vehicle/dynamic/lights.cpp new file mode 100644 index 000000000..cd38662e1 --- /dev/null +++ b/vehicle/dynamic/lights.cpp @@ -0,0 +1,282 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the lights of a vehicle and the signals they make + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/mover.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + + +void TDynamicObject::SetLights() { + auto const isfrontcaboccupied { MoverParameters->CabOccupied * DirectionGet() >= 0 }; + int const automaticmarkers { MoverParameters->CabActive == 0 && MoverParameters->InactiveCabFlag & activation::redmarkers + ? light::redmarker_left + light::redmarker_right : 0 }; + auto const lightpos { MoverParameters->LightsPos - 1 }; + std::array const cablights { + automaticmarkers > 0 ? automaticmarkers : MoverParameters->Lights[ end::front ][ lightpos ], + automaticmarkers > 0 ? automaticmarkers : MoverParameters->Lights[ end::rear ][ lightpos ] }; + // the custom position keeps the lights lit at coupled ends as well + auto const ignorecouplings { MoverParameters->LightsPos == 18 }; + auto *vehicle { GetFirstDynamic( MoverParameters->CabOccupied >= 0 ? end::front : end::rear, Coupling::control ) }; + while( vehicle != nullptr ) { + // set lights on given side if there's no coupling with another vehicle, turn them off otherwise + auto const iscoupled { [ vehicle, ignorecouplings ]( end const Side ) { + return false == ignorecouplings + && vehicle->MoverParameters->Couplers[ Side ].CouplingFlag.HasAny(Coupling::coupler) + && vehicle->MoverParameters->Neighbours[ Side ].vehicle != nullptr; } }; + auto const lights { lights_programmer::vehicle_lights( + cablights, isfrontcaboccupied, vehicle->iDirection, { iscoupled( end::front ), iscoupled( end::rear ) } ) }; + vehicle->RaLightsSet( lights.head, lights.rear ); + vehicle = isfrontcaboccupied ? vehicle->Next(Coupling::control) : vehicle->Prev(Coupling::control); + } +}; + +void TDynamicObject::RaLightsSet(int head, int rear) +{ // zapalenie świateł z przodu i z + // tyłu, zależne od kierunku + // pojazdu + if (!MoverParameters) + return; // może tego nie być na początku + if (rear == ( light::redmarker_left | light::redmarker_right | light::rearendsignals ) ) + { // jeśli koniec pociągu, to trzeba ustalić, czy + // jest tam czynna lokomotywa + // EN57 może nie mieć końcówek od środka członu + if (MoverParameters->Power > 1.0) // jeśli ma moc napędową + if (!MoverParameters->DirActive) // jeśli nie ma ustawionego kierunku + { // jeśli ma zarówno światła jak i końcówki, ustalić, czy jest w stanie aktywnym + // np. lokomotywa na zimno będzie mieć końcówki a nie światła + rear = light::rearendsignals; // tablice blaszane + // trzeba to uzależnić od "załączenia baterii" w pojeździe + } + if( rear == ( light::redmarker_left | light::redmarker_right | light::rearendsignals ) ) // jeśli nadal obydwie możliwości + if( iInventory[ + ( iDirection ? + end::rear : + end::front ) ] & ( light::redmarker_left | light::redmarker_right ) ) { + // czy ma jakieś światła czerowone od danej strony + rear = light::redmarker_left | light::redmarker_right; // dwa światła czerwone + } + else { + rear = light::rearendsignals; // tablice blaszane + } + } + // w zależności od kierunku pojazdu w składzie + if( head >= 0 ) { + auto const vehicleend { iDirection > 0 ? end::front : end::rear }; + MoverParameters->iLights[ vehicleend ] = head & iInventory[vehicleend]; + bool tLeft = MoverParameters->iLights[vehicleend] & (light::auxiliary_left | light::headlight_left); // roboczo czy jakiekolwiek swiatlo z lewej jest zapalone + bool tRight = MoverParameters->iLights[vehicleend] & (light::auxiliary_right | light::headlight_right); // a tu z prawej + if (Controller == Humandriver) { + + auto const dps{MoverParameters->currentDimPosition()}; + + // domyślnie + HighBeamLights = false; + DimHeadlights = false; + + // obsługa OFF + if (dps.isOff) + { + //MoverParameters->iLights[vehicleend] &= 0 | light::rearendsignals; // zostawiamy tylko tabliczki jesli sa + HighBeamLights = false; + DimHeadlights = false; + switch (MoverParameters->CabActive) + { + case end::front: + HeadlightsAoff = true; + break; + case end::rear: + HeadlightsBoff = true; + break; + default: + break; + } + } + else + { + switch (MoverParameters->CabActive) + { + case end::front: + HeadlightsAoff = false; + break; + case end::rear: + HeadlightsBoff = false; + break; + default: + break; + } + } + + // obsługa przyciemnionych + DimHeadlights = dps.isDimmed; + + // obsługa długich + if (dps.isHighBeam) + { + HighBeamLights = true; + } + } + + } + if( rear >= 0 ) { + auto const vehicleend{ iDirection > 0 ? end::rear : end::front }; + MoverParameters->iLights[ vehicleend ] = rear & iInventory[vehicleend]; + } +}; + +void TDynamicObject::SetLightDimmings() +{ + auto const vehicleend{iDirection > 0 ? end::front : end::rear}; + if (Controller == Humandriver) + { + + auto const dps{MoverParameters->currentDimPosition()}; + + // domyślnie + HighBeamLights = false; + DimHeadlights = false; + + // obsługa OFF + if (dps.isOff) + { + // MoverParameters->iLights[vehicleend] &= 0 | light::rearendsignals; // zostawiamy tylko tabliczki jesli sa + HighBeamLights = false; + DimHeadlights = false; + switch (vehicleend) + { + case end::front: + HeadlightsAoff = true; + break; + case end::rear: + HeadlightsBoff = true; + break; + default: + break; + } + } + else + { + switch (vehicleend) + { + case end::front: + HeadlightsAoff = false; + break; + case end::rear: + HeadlightsBoff = false; + break; + default: + break; + } + } + + // obsługa przyciemnionych + DimHeadlights = dps.isDimmed; + + // obsługa długich + if (dps.isHighBeam) + { + // obsługa długich + if (dps.isHighBeam) + { + HighBeamLights = true; + } + } + } +} + +bool TDynamicObject::has_signal_pc1_on() const { + + auto const vehicleend { iDirection > 0 ? end::front : end::rear }; + auto const equippedlights { iInventory[ vehicleend ] }; + auto const pattern { equippedlights & ( light::headlight_left | light::headlight_right | light::headlight_upper ) }; + auto const patternfallback { equippedlights & ( light::auxiliary_left | light::auxiliary_right | light::headlight_upper ) }; + auto const hasauxiliarylights { ( equippedlights & ( light::auxiliary_left | light::auxiliary_right ) ) != 0 }; + auto const activelights { MoverParameters->iLights[ vehicleend ] }; + + return (pattern != 0 && activelights == pattern) || (hasauxiliarylights && activelights == patternfallback) || + (pattern == 0 && patternfallback == 0 && activelights == light::rearendsignals); // pc4 +} + +bool TDynamicObject::has_signal_pc2_on() const { + + auto const vehicleend { iDirection > 0 ? end::front : end::rear }; + auto const equippedlights { iInventory[ vehicleend ] }; + auto const pattern { equippedlights & ( light::redmarker_left | light::headlight_right | light::headlight_upper ) }; + auto const patternfallback { equippedlights & ( light::redmarker_left | light::auxiliary_right | light::headlight_upper ) }; + auto const hasauxiliarylights { ( equippedlights & ( light::auxiliary_left | light::auxiliary_right ) ) != 0 }; + auto const activelights { MoverParameters->iLights[ vehicleend ] }; + + return activelights == pattern || (hasauxiliarylights && activelights == patternfallback); +} + +bool TDynamicObject::has_signal_pc5_on() const { + + auto const vehicleend { iDirection > 0 ? end::rear : end::front }; + auto const equippedlights { iInventory[ vehicleend ] }; + auto const pattern { equippedlights & ( light::redmarker_left | light::redmarker_right ) }; + auto const patternfallback { equippedlights & light::rearendsignals }; + auto const activelights { MoverParameters->iLights[ vehicleend ] }; + + return (pattern != 0 && activelights == pattern) || (patternfallback != 0 && activelights == patternfallback); +} + +bool TDynamicObject::has_signal_on( int const Side, int const Pattern ) const { +/* + auto const vehicleend { iDirection > 0 ? Side : 1 - Side }; + auto const pattern { iInventory[ vehicleend ] & Pattern }; + + return ( MoverParameters->iLights[ vehicleend ] == pattern ); +*/ + return MoverParameters->iLights[Side] == (Pattern & iInventory[Side]); +} diff --git a/vehicle/dynamic/load.cpp b/vehicle/dynamic/load.cpp new file mode 100644 index 000000000..658a1ed0c --- /dev/null +++ b/vehicle/dynamic/load.cpp @@ -0,0 +1,306 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the load of a vehicle, its exchange at the stops, how it shows + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/mover.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + + +// initiates load change by specified amounts, with a platform on specified side +void TDynamicObject::LoadExchange( int const Disembark, int const Embark, int const Platforms ) { +/* + if( ( MoverParameters->Doors.open_control == control_t::passenger ) + || ( MoverParameters->Doors.open_control == control_t::mixed ) ) { + // jeśli jedzie do tyłu, to drzwi otwiera odwrotnie + auto const lewe = ( DirectionGet() > 0 ) ? 1 : 2; + auto const prawe = 3 - lewe; + if( Platform & lewe ) { + MoverParameters->OperateDoors( side::left, true, range_t::local ); + } + if( Platform & prawe ) { + MoverParameters->OperateDoors( side::right, true, range_t::local ); + } + } +*/ + if( Platforms == 0 ) { return; } // edge case, if there's no accessible platforms discard the request + + m_exchange.unload_count += Disembark; + m_exchange.load_count += Embark; + m_exchange.platforms = Platforms; + m_exchange.time = 0.0; +} + +// calculates time needed to complete current load change +float TDynamicObject::LoadExchangeTime( int const Platforms ) { + + m_exchange.platforms = Platforms; + return LoadExchangeTime(); +} + +float TDynamicObject::LoadExchangeTime() const { + + if( m_exchange.unload_count < 0.01 && m_exchange.load_count < 0.01 ) { return 0.f; } + + auto const baseexchangetime { m_exchange.unload_count / MoverParameters->UnLoadSpeed + m_exchange.load_count / MoverParameters->LoadSpeed }; + auto const nominalexchangespeedfactor { ( m_exchange.platforms == 3 ? 2.f : 1.f ) }; + auto const actualexchangespeedfactor { LoadExchangeSpeed() }; + + return baseexchangetime / ( actualexchangespeedfactor > 0.f ? actualexchangespeedfactor : nominalexchangespeedfactor ); +} + +// calculates current load exchange rate +float TDynamicObject::LoadExchangeSpeed() const { + // platforms (1:left, 2:right, 3:both) + // with exchange performed on both sides waiting times are halved + auto exchangespeedfactor { 0.f }; + auto const lewe { DirectionGet() > 0 ? 1 : 2 }; + auto const prawe { 3 - lewe }; + if( m_exchange.platforms & lewe ) { + exchangespeedfactor += MoverParameters->Doors.instances[side::left].is_open ? 1.f : 0.f; + } + if( m_exchange.platforms & prawe ) { + exchangespeedfactor += MoverParameters->Doors.instances[side::right].is_open ? 1.f : 0.f; + } + + return exchangespeedfactor; +} + +// update state of load exchange operation +void TDynamicObject::update_exchange( double const Deltatime ) { + + // TODO: move offset calculation after initial check, when the loading system is all unified + update_load_offset(); + + if( m_exchange.unload_count < 0.01 && m_exchange.load_count < 0.01 ) { return; } + + if( MoverParameters->Vel < 2.0 ) { + + auto const exchangespeed { LoadExchangeSpeed() }; + + if( exchangespeed < ( m_exchange.platforms == 3 ? 2.f : 1.f ) ) { + // the exchange isn't performed at optimal rate, or at all. try to open viable vehicle doors to speed it up + auto const lewe { DirectionGet() > 0 ? 1 : 2 }; + auto const prawe { 3 - lewe }; + if( m_exchange.platforms & lewe + && false == (MoverParameters->Doors.instances[side::left].is_open || MoverParameters->Doors.instances[side::left].is_opening) ) { + // try to open left door + MoverParameters->OperateDoors( side::left, true, range_t::local ); + } + if( m_exchange.platforms & prawe + && false == (MoverParameters->Doors.instances[side::right].is_open || MoverParameters->Doors.instances[side::right].is_opening) ) { + // try to open right door + MoverParameters->OperateDoors( side::right, true, range_t::local ); + } + } + + if( exchangespeed > 0.f ) { + + m_exchange.time += Deltatime; + while( m_exchange.unload_count > 0.01 + && m_exchange.time >= 1.0 ) { + + m_exchange.time -= 1.0; + auto const exchangesize = std::min( m_exchange.unload_count, MoverParameters->UnLoadSpeed * exchangespeed ); + m_exchange.unload_count -= exchangesize; + MoverParameters->LoadStatus = 1; + MoverParameters->LoadAmount = std::max( 0.f, MoverParameters->LoadAmount - exchangesize ); + MoverParameters->ComputeMass(); + update_load_visibility(); + } + if( m_exchange.unload_count < 0.01 ) { + // finish any potential unloading operation before adding new load + // don't load more than can fit + m_exchange.load_count = std::min( m_exchange.load_count, MoverParameters->MaxLoad - MoverParameters->LoadAmount ); + while( m_exchange.load_count > 0.01 + && m_exchange.time >= 1.0 ) { + + m_exchange.time -= 1.0; + auto const exchangesize = std::min( m_exchange.load_count, MoverParameters->LoadSpeed * exchangespeed ); + m_exchange.load_count -= exchangesize; + MoverParameters->LoadStatus = 2; + MoverParameters->LoadAmount = std::min( MoverParameters->MaxLoad, MoverParameters->LoadAmount + exchangesize ); // std::max not strictly needed but, eh + MoverParameters->ComputeMass(); + update_load_visibility(); + } + } + } + } + + if( MoverParameters->Vel > 2.0 ) { + // if the vehicle moves too fast cancel the exchange + m_exchange.unload_count = 0; + m_exchange.load_count = 0; + } + + if( m_exchange.unload_count < 0.01 + && m_exchange.load_count < 0.01 ) { + + MoverParameters->LoadStatus = 4; + // if the exchange is completed (or canceled) close the door, if applicable + if( MoverParameters->Doors.close_control == control_t::passenger + || MoverParameters->Doors.close_control == control_t::mixed ) { + + if( MoverParameters->Vel > 2.0 + || Random() < ( + // remotely controlled door are more likely to be left open + MoverParameters->Doors.close_control == control_t::passenger ? 0.75 : 0.50) ) { + + MoverParameters->OperateDoors( side::left, false, range_t::local ); + MoverParameters->OperateDoors( side::right, false, range_t::local ); + } + } + // if the vehicle was emptied potentially switch load visualization model + if( MoverParameters->LoadAmount == 0 ) { + MoverParameters->AssignLoad( "" ); + } + } +} + +void TDynamicObject::LoadUpdate() { + + MoverParameters->LoadStatus &= 1 | 2; // po zakończeniu będzie równe zero + // przeładowanie modelu ładunku + if( MoverParameters->LoadTypeChange ) { + // whether we succeed or not don't try more than once + MoverParameters->LoadTypeChange = false; + // bieżąca ścieżka do tekstur to dynamic/... + Global.asCurrentTexturePath = asBaseDir; + mdLoad = LoadMMediaFile_mdload( MoverParameters->LoadType.name ); + // TODO: discern from vehicle component which merely uses vehicle directory and has no animations, so it can be initialized outright + // and actual vehicles which get their initialization after their animations are set up + if( mdLoad != nullptr ) { + mdLoad->Init(); + } + // update bindings between lowpoly sections and potential load chunks placed inside them + update_load_sections(); + // z powrotem defaultowa sciezka do tekstur + Global.asCurrentTexturePath = std::string( paths::textures ); + } +} + +void +TDynamicObject::update_load_sections() { + + SectionLoadOrder.clear(); + + for( auto §ion : Sections ) { + + section.load = GetSubmodelFromName( mdLoad, section.compartment->pName ); + + if( section.load != nullptr ) { + // create entry for each load model chunk assigned to the section + // TBD, TODO: store also pointer to chunk submodel and control its visibility more directly, instead of per-section visibility flag? + auto loadchunkcount { section.load->count_children() }; + while( loadchunkcount-- ) { + SectionLoadOrder.push_back( §ion ); + } + // HACK: disable automatic self-illumination threshold, at least until 3d model update + if( MoverParameters->CompartmentLights.start_type == start_t::manual ) { + section.load->SetSelfIllum( 2.0f, true, false ); + } + } + } + shuffle_load_order(); +} + +void +TDynamicObject::update_load_visibility() { + // start with clean load chunk visibility slate + for( auto §ion : Sections ) { + section.load_chunks_visible = 0; + } + // each entry in load order sequence matches a single chunk of the section it points to + // the length of load order sequence matches total number of load chunks + auto const loadpercentage { ( + MoverParameters->MaxLoad == 0.f ? + 0.0 : + MoverParameters->LoadAmount / MoverParameters->MaxLoad ) }; + auto visiblechunkcount { ( + SectionLoadOrder.empty() ? + 0 : + static_cast( std::ceil( loadpercentage * SectionLoadOrder.size() - 0.001f ) ) ) }; + for( auto *section : SectionLoadOrder ) { + if( visiblechunkcount == 0 ) { break; } + section->load_chunks_visible++; + --visiblechunkcount; + } +} + +void +TDynamicObject::update_load_offset() { + + if( MoverParameters->LoadType.offset_min == 0.f ) { return; } + + auto const loadpercentage { ( + MoverParameters->MaxLoad == 0.f ? + 0.0 : + 100.0 * MoverParameters->LoadAmount / MoverParameters->MaxLoad ) }; + + LoadOffset = std::lerp( MoverParameters->LoadType.offset_min, 0.f, safe_clamp( 0.0, 1.0, loadpercentage * 0.01 ) ); +} + +void +TDynamicObject::shuffle_load_order() { + + // order of visible load chunks, nothing security related -- see the engines in Globals.h + std::shuffle( std::begin( SectionLoadOrder ), std::end( SectionLoadOrder ), Global.random_engine ); // NOSONAR + // shift chunks assigned to corridors to the end of the list, so they show up last + std::stable_partition( + std::begin( SectionLoadOrder ), std::end( SectionLoadOrder ), + []( vehicle_section const *section ) { + return section->compartment->pName.find("compartment") == 0 || section->compartment->pName.find("przedzial") == 0; } ); + // NOTE: potentially we're left with a mix of corridor and external section loads + // but that's not necessarily a wrong outcome, so we leave it this way for the time being +} diff --git a/vehicle/dynamic/mmd.cpp b/vehicle/dynamic/mmd.cpp new file mode 100644 index 000000000..edd971e4a --- /dev/null +++ b/vehicle/dynamic/mmd.cpp @@ -0,0 +1,2151 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// reading the definition of the model and the sounds of a vehicle (.mmd) + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/mover.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + +namespace +{ + + +// a luadestinationsign: or wasmdestinationsign: block, its script in the vehicle folder when it has no path of its own +void deserialize_script_sign( cParser &Parser, script_screens::screen_config &Sign, std::string const &Folder ) { + + Sign.deserialize( Parser ); + if( Sign.script.empty() ) { return; } + if( auto path { script_screens::screen_script_path( Folder, Sign.script ) }; path.has_value() ) { + Sign.script = std::move( *path ); + } + else { + ErrorLog( "Bad script sign: \"" + Sign.script + "\" leads outside the game's folder" ); + Sign.script.clear(); + } +} + +} // namespace + +// McZapkie-250202 +// wczytywanie pliku z danymi multimedialnymi (dzwieki) +void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string const &ReplacableSkin ) { + rTypeName = TypeName; + rReplacableSkin = ReplacableSkin; + Global.asCurrentDynamicPath = asBaseDir; + std::string asFileName = asBaseDir + TypeName + ".mmd"; + std::string asAnimName; + bool Stop_InternalData = false; + pants = nullptr; // wskaźnik pierwszego obiektu animującego dla pantografów + wipers = nullptr; // wskaznik pierwszego obiektu animujacego dla wycieraczek + { + // preliminary check whether the file exists + cParser parser( TypeName + ".mmd", cParser::buffer_FILE, asBaseDir ); + if( false == parser.ok() ) { + ErrorLog( "Failed to load appearance data for vehicle " + MoverParameters->Name ); + return; + } + } + // use #include wrapper to access the appearance data file + // this allows us to provide the file content with user-defined parameters + cParser parser( + "include " + TypeName + ".mmd" + + " " + asName // (p1) + + " " + TypeName // (p2) + + " " + ReplacableSkin // (p3) + + " end", + cParser::buffer_TEXT, + asBaseDir, true, std::vector(), true ); + std::string token; + do { + token = ""; + parser.getTokens(); parser >> token; + + if( token == "models:" ) { + // modele i podmodele + m_materialdata.multi_textures = 0; // czy jest wiele tekstur wymiennych? + parser.getTokens(); + parser >> asModel; + replace_slashes( asModel ); + if( asModel.back() == '#' ) // Ra 2015-01: nie podoba mi siê to + { // model wymaga wielu tekstur wymiennych + m_materialdata.multi_textures = 1; + asModel.erase( asModel.length() - 1 ); + } + // name can contain leading slash, erase it to avoid creation of double slashes when the name is combined with current directory + erase_leading_slashes( asModel ); + /* + // never really used, may as well get rid of it + std::size_t i = asModel.find( ',' ); + if ( i != std::string::npos ) + { // Ra 2015-01: może szukać przecinka w nazwie modelu, a po przecinku była by liczba tekstur? + if( i < asModel.length() ) { + m_materialdata.multi_textures = asModel[ i + 1 ] - '0'; + } + m_materialdata.multi_textures = std::clamp( m_materialdata.multi_textures, 0, 1 ); // na razie ustawiamy na 1 + } + */ + asModel = asBaseDir + asModel; // McZapkie 2002-07-20: dynamics maja swoje modele w dynamics/basedir + Global.asCurrentTexturePath = asBaseDir; // biezaca sciezka do tekstur to dynamic/... + mdModel = TModelsManager::GetModel(asModel, true); + if (ReplacableSkin != "none") { + m_materialdata.assign( ReplacableSkin ); + } + Global.asCurrentTexturePath = paths::textures; // z powrotem defaultowa sciezka do tekstur + do { + token = ""; + parser.getTokens(); parser >> token; + + if( token == "animations:" ) { + // Ra: ustawienie ilości poszczególnych animacji - musi być jako pierwsze, inaczej ilości będą domyślne +/* + if( nullptr == pAnimations ) +*/ + if( true == pAnimations.empty() ) + { // jeśli nie ma jeszcze tabeli animacji, można odczytać nowe ilości + int co = 0; + iAnimations = 0; + int ile; + do + { // kolejne liczby to ilość animacj, -1 to znacznik końca + ile = -1; + parser.getTokens( 1, false ); + parser >> ile; // ilość danego typu animacji + if (ile >= 0) + { + iAnimType[co] = ile; // zapamiętanie + iAnimations += ile; // ogólna ilość animacji + } + else { + iAnimType[co] = 0; + } + ++co; + } while ( ile >= 0 && co < ANIM_TYPES ); //-1 to znacznik końca + + pAnimations.resize( iAnimations ); + int i, j, k = 0, sm = 0; + for (j = 0; j < ANIM_TYPES; ++j) // petla po wszystkich wpisach w animations + for (i = 0; i < iAnimType[j]; ++i) // petla iteruje sie tyle razy ile mamy wpisane w animations + { + if (j == ANIM_PANTS) // zliczamy poprzednie animacje + if (!pants) + if (iAnimType[ANIM_PANTS]) // o ile jakieś pantografy są (a domyślnie są) + pants = &pAnimations[k]; // zapamiętanie na potrzeby wyszukania submodeli + if (j == ANIM_WIPERS) + if (!wipers) + if (iAnimType[ANIM_WIPERS]) + wipers = &pAnimations[k]; + pAnimations[k].iShift = sm; // przesunięcie do przydzielenia wskaźnika + sm += pAnimations[k++].TypeSet(j, *MoverParameters); // ustawienie typu animacji i zliczanie tablicowanych submodeli + } + if (sm) // o ile są bardziej złożone animacje + { + pAnimated = new TSubModel *[sm]; // tabela na animowane submodele + for (k = 0; k < iAnimations; ++k) + pAnimations[k].smElement = pAnimated + pAnimations[k].iShift; // przydzielenie wskaźnika do tabelki + } + } + } + + else if(token == "lowpolyinterior:") { + // ABu: wnetrze lowpoly + parser.getTokens(); + parser >> asModel; + + replace_slashes( asModel ); + erase_leading_slashes( asModel ); + asModel = asBaseDir + asModel; // McZapkie-200702 - dynamics maja swoje modele w dynamic/basedir + Global.asCurrentTexturePath = asBaseDir; // biezaca sciezka do tekstur to dynamic/... + mdLowPolyInt = TModelsManager::GetModel(asModel, true); + } + + else if(token == "coupleradapter:") { + // coupling adapter data + parser.getTokens( 3 ); + parser + >> m_coupleradapter.model + >> m_coupleradapter.position.x + >> m_coupleradapter.position.y; + replace_slashes( m_coupleradapter.model ); + erase_leading_slashes( m_coupleradapter.model ); + } + + else if(token == "attachments:") { + // additional 3d models attached to main body + // content provided as a series of values together enclosed in "{}" + // each value is a name of additional 3d model + // value can be optionally set of values enclosed in "[]" in which case one value will be picked randomly + // TBD: reconsider something more yaml-compliant and/or ability to define offset and rotation + while( (token = deserialize_random_set(parser)) != "" + && token != "}" ) { + if( token == "{" ) { continue; } + replace_slashes( token ); + Global.asCurrentTexturePath = asBaseDir; // biezaca sciezka do tekstur to dynamic/... + auto *attachmentmodel { TModelsManager::GetModel( asBaseDir + token, true ) }; + if( attachmentmodel != nullptr ) { + mdAttachments.emplace_back( attachmentmodel ); + } + } + } + + else if(token == "loads:") { + // default load visualization models overrides + // content provided as "key: value" pairs together enclosed in "{}" + // value can be optionally set of values enclosed in "[]" in which case one value will be picked randomly + while( (token = parser.getToken()) != "" + && token != "}" ) { + if( token.back() == ':' ) { + auto loadmodel { deserialize_random_set( parser ) }; + replace_slashes( loadmodel ); + LoadModelOverrides.emplace( token.erase( token.size() - 1 ), loadmodel ); + } + } + } + + else if( token == "brakemode:" ) { + // Ra 15-01: gałka nastawy hamulca + parser.getTokens(); + parser >> asAnimName; + smBrakeMode = GetSubmodelFromName( mdModel, asAnimName ); + // jeszcze wczytać kąty obrotu dla poszczególnych ustawień + } + + else if( token == "loadmode:" ) { + // Ra 15-01: gałka nastawy hamulca + parser.getTokens(); + parser >> asAnimName; + smLoadMode = GetSubmodelFromName( mdModel, asAnimName ); + // jeszcze wczytać kąty obrotu dla poszczególnych ustawień + } + + else if (token == "animwheelprefix:") { + // prefiks kręcących się kół + int i, k, m; + unsigned int j; + parser.getTokens( 1, false ); parser >> token; + for (i = 0; i < iAnimType[ANIM_WHEELS]; ++i) // liczba osi + { // McZapkie-050402: wyszukiwanie kol o nazwie str* + asAnimName = token + std::to_string(i + 1); + pAnimations[i].smAnimated = GetSubmodelFromName( mdModel, asAnimName ); + if (pAnimations[i].smAnimated) + { //++iAnimatedAxles; + pAnimations[i].smAnimated->WillBeAnimated(); // wyłączenie optymalizacji transformu + pAnimations[i].yUpdate = std::bind( &TDynamicObject::UpdateAxle, this, std::placeholders::_1 ); + pAnimations[i].fMaxDist = Global.fDistanceFactor * MoverParameters->WheelDiameter * 200; + pAnimations[i].fMaxDist *= pAnimations[i].fMaxDist; + } + } + // Ra: ustawianie indeksów osi + for (i = 0; i < iAnimType[ANIM_WHEELS]; ++i) // ilość osi (zabezpieczenie przed błędami w CHK) + pAnimations[i].dWheelAngle = 1; // domyślnie wskaźnik na napędzające + i = 0; + j = 1; + k = 0; + m = 0; // numer osi; kolejny znak; ile osi danego typu; która średnica + if (MoverParameters->WheelDiameterL != MoverParameters->WheelDiameter || + MoverParameters->WheelDiameterT != MoverParameters->WheelDiameter) + { // obsługa różnych średnic, o ile występują + while (i < iAnimType[ANIM_WHEELS] && + j <= MoverParameters->AxleArangement.length()) + { // wersja ze wskaźnikami jest bardziej elastyczna na nietypowe układy + if (k >= 'A' && k <= 'J') // 10 chyba maksimum? + { + pAnimations[i++].dWheelAngle = 1; // obrót osi napędzających + --k; // następna będzie albo taka sama, albo bierzemy kolejny znak + m = 2; // następujące toczne będą miały inną średnicę + } + else if (k >= '1' && k <= '9') + { + pAnimations[i++].dWheelAngle = m; // obrót osi tocznych + --k; // następna będzie albo taka sama, albo bierzemy kolejny znak + } + else + k = MoverParameters->AxleArangement[j++]; // pobranie kolejnego znaku + } + } + } + // else if (str==AnsiString("animrodprefix:")) //prefiks wiazarow dwoch + // { + // str= Parser->GetNextSymbol(); + // for (int i=1; i<=2; i++) + // {//McZapkie-050402: wyszukiwanie max 2 wiazarow o nazwie str* + // asAnimName=str+i; + // smWiazary[i-1]=mdModel->GetFromName(asAnimName.c_str()); + // smWiazary[i-1]->WillBeAnimated(); + // } + // } + + else if( token == "animpantprefix:" ) { + // Ra: pantografy po nowemu mają literki i numerki + } + // Pantografy - Winger 160204 + else if( token == "animpantrd1prefix:" ) { + // prefiks ramion dolnych 1 + parser.getTokens(); parser >> token; + float4x4 m; // macierz do wyliczenia pozycji i wektora ruchu pantografu + TSubModel *sm; + if (pants) + for (int i = 0; i < iAnimType[ANIM_PANTS]; i++) + { // Winger 160204: wyszukiwanie max 2 patykow o nazwie str* + asAnimName = token + std::to_string(i + 1); + sm = GetSubmodelFromName( mdModel, asAnimName ); + pants[i].smElement[0] = sm; // jak NULL, to nie będzie animowany + if (sm) + { // w EP09 wywalało się tu z powodu NULL + sm->WillBeAnimated(); + sm->ParentMatrix(&m); // pobranie macierzy transformacji + // m(3)[1]=m[3][1]+0.054; //w górę o wysokość ślizgu (na razie tak) + pants[i].fParamPants->vPos.z = m[3][0]; // przesunięcie w bok (asymetria) + pants[i].fParamPants->vPos.y = m[3][1]; // przesunięcie w górę odczytane z modelu + if ((sm = pants[i].smElement[0]->ChildGet()) != nullptr) + { // jeśli ma potomny, można policzyć długość (odległość potomnego od osi obrotu) + m = float4x4(*sm->GetMatrix()); // wystarczyłby wskaźnik, nie trzeba kopiować + // może trzeba: pobrać macierz dolnego ramienia, wyzerować przesunięcie, przemnożyć przez macierz górnego + pants[i].fParamPants->fHoriz = -fabs(m[3][1]); + pants[i].fParamPants->fLenL1 = hypot(m[3][1], m[3][2]); // po osi OX nie potrzeba + pants[i].fParamPants->fAngleL0 = atan2(fabs(m[3][2]), fabs(m[3][1])); + // if (pants[i].fParamPants->fAngleL0fAngleL0+=M_PI; //gdyby w odwrotną stronę wyszło + // if + // ((pants[i].fParamPants->fAngleL0<0.03)||(pants[i].fParamPants->fAngleL0>0.09)) + // //normalnie ok. 0.05 + // pants[i].fParamPants->fAngleL0=pants[i].fParamPants->fAngleL; + pants[i].fParamPants->fAngleL = pants[i].fParamPants->fAngleL0; // początkowy kąt dolnego ramienia + if ((sm = sm->ChildGet()) != nullptr) + { // jeśli dalej jest ślizg, można policzyć długość górnego ramienia + m = float4x4(*sm->GetMatrix()); // wystarczyłby wskaźnik, + // nie trzeba kopiować trzeba by uwzględnić macierz dolnego ramienia, żeby uzyskać kąt do poziomu... + pants[i].fParamPants->fHoriz += fabs(m(3)[1]); // różnica długości rzutów ramion na + // płaszczyznę podstawy (jedna dodatnia, druga ujemna) + pants[i].fParamPants->fLenU1 = hypot( m[3][1], m[3][2] ); // po osi OX nie potrzeba + // pants[i].fParamPants->pantu=acos((1.22*cos(pants[i].fParamPants->fAngleL)+0.535)/1.755); //górne ramię + // pants[i].fParamPants->fAngleU0=acos((1.176289*cos(pants[i].fParamPants->fAngleL)+0.54555075)/1.724482197); //górne ramię + pants[i].fParamPants->fAngleU0 = atan2( fabs(m[3][2]), fabs(m[3][1]) ); // początkowy kąt górnego ramienia, odczytany z modelu + // if (pants[i].fParamPants->fAngleU0fAngleU0+=M_PI; //gdyby w odwrotną stronę wyszło + // if (pants[i].fParamPants->fAngleU0<0) + // pants[i].fParamPants->fAngleU0=-pants[i].fParamPants->fAngleU0; + // if + // ((pants[i].fParamPants->fAngleU0<0.00)||(pants[i].fParamPants->fAngleU0>0.09)) //normalnie ok. 0.07 + // pants[i].fParamPants->fAngleU0=acos((pants[i].fParamPants->fLenL1*cos(pants[i].fParamPants->fAngleL)+pants[i].fParamPants->fHoriz)/pants[i].fParamPants->fLenU1); + pants[i].fParamPants->fAngleU = pants[i].fParamPants->fAngleU0; // początkowy kąt + // Ra: ze względu na to, że niektóre modele pantografów są zrąbane, ich mierzenie ma obecnie ograniczony sens + sm->ParentMatrix(&m); // pobranie macierzy transformacji pivota ślizgu względem wstawienia pojazdu + float det = Det(m); + if (std::fabs(det - 1.0) < 0.001) // dopuszczamy 1 promil błędu na skalowaniu ślizgu + { // skalowanie jest w normie, można pobrać wymiary z modelu + pants[i].fParamPants->fHeight = sm->MaxY(m); // przeliczenie maksimum wysokości wierzchołków względem macierzy + pants[i].fParamPants->fHeight -= m[3][1]; // odjęcie wysokości pivota ślizgu + pants[i].fParamPants->vPos.x = m[3][2]; // przy okazji odczytać z modelu pozycję w długości + // ErrorLog("Model OK: "+asModel+", + // height="+pants[i].fParamPants->fHeight); + // ErrorLog("Model OK: "+asModel+", + // pos.x="+pants[i].fParamPants->vPos.x); + } + else + { // gdy ktoś przesadził ze skalowaniem + pants[i].fParamPants->fHeight = 0.0; // niech będzie odczyt z pantfactors: + ErrorLog( + "Bad model: " + asModel + ", scale of " + sm->pName + " is " + std::to_string(100.0 * det) + "%", + logtype::model ); + } + } + } + } + else { + // brak ramienia + pants[ i ].fParamPants->fHeight = 0.0; // niech będzie odczyt z pantfactors: + ErrorLog( "Bad model: " + asFileName + " - missed submodel " + asAnimName, logtype::model ); + } + } + } + + else if( token == "animpantrd2prefix:" ) { + // prefiks ramion dolnych 2 + parser.getTokens(); parser >> token; + float4x4 m; // macierz do wyliczenia pozycji i wektora ruchu pantografu + TSubModel *sm; + if( pants ) { + for( int i = 0; i < iAnimType[ ANIM_PANTS ]; i++ ) { + // Winger 160204: wyszukiwanie max 2 patykow o nazwie str* + asAnimName = token + std::to_string( i + 1 ); + sm = GetSubmodelFromName( mdModel, asAnimName ); + pants[ i ].smElement[ 1 ] = sm; // jak NULL, to nie będzie animowany + if( sm ) { // w EP09 wywalało się tu z powodu NULL + sm->WillBeAnimated(); + if( pants[ i ].fParamPants->vPos.y == 0.0 ) { + // jeśli pierwsze ramię nie ustawiło tej wartości, próbować drugim + //!!!! docelowo zrobić niezależną animację ramion z każdej strony + m = float4x4( + *sm->GetMatrix()); // skopiowanie, bo będziemy mnożyć + m( 3 )[ 1 ] = + m[ 3 ][ 1 ] + 0.054; // w górę o wysokość ślizgu (na razie tak) + while( sm->Parent ) { + if( sm->Parent->GetMatrix() ) + m = *sm->Parent->GetMatrix() * m; + sm = sm->Parent; + } + pants[ i ].fParamPants->vPos.z = m[3][0]; // przesunięcie w bok (asymetria) + pants[ i ].fParamPants->vPos.y = m[3][1]; // przesunięcie w górę odczytane z modelu + } + } + else + ErrorLog( "Bad model: " + asFileName + " - missed submodel " + asAnimName, logtype::model ); // brak ramienia + } + } + } + + else if( token == "animpantrg1prefix:" ) { + // prefiks ramion górnych 1 + parser.getTokens(); parser >> token; + if( pants ) { + for( int i = 0; i < iAnimType[ ANIM_PANTS ]; i++ ) { + // Winger 160204: wyszukiwanie max 2 patykow o nazwie str* + asAnimName = token + std::to_string( i + 1 ); + pants[ i ].smElement[ 2 ] = GetSubmodelFromName( mdModel, asAnimName ); + if( pants[ i ].smElement[ 2 ] ) { + pants[ i ].smElement[ 2 ]->WillBeAnimated(); + } + else { + ErrorLog( "Bad model: " + asFileName + " - missed submodel " + asAnimName, logtype::model ); // brak ramienia + } + } + } + } + + else if( token == "animpantrg2prefix:" ) { + // prefiks ramion górnych 2 + parser.getTokens(); parser >> token; + if( pants ) { + for( int i = 0; i < iAnimType[ ANIM_PANTS ]; i++ ) { + // Winger 160204: wyszukiwanie max 2 patykow o nazwie str* + asAnimName = token + std::to_string( i + 1 ); + pants[ i ].smElement[ 3 ] = GetSubmodelFromName( mdModel, asAnimName ); + if( pants[ i ].smElement[ 3 ] ) { + pants[ i ].smElement[ 3 ]->WillBeAnimated(); + } + else { + ErrorLog( "Bad model: " + asFileName + " - missed submodel " + asAnimName, logtype::model ); // brak ramienia + } + } + } + } + + else if( token == "animpantslprefix:" ) { + // prefiks ślizgaczy + parser.getTokens(); parser >> token; + if( pants ) { + for( int i = 0; i < iAnimType[ ANIM_PANTS ]; i++ ) { + // Winger 160204: wyszukiwanie max 2 patykow o nazwie str* + asAnimName = token + std::to_string( i + 1 ); + pants[ i ].smElement[ 4 ] = GetSubmodelFromName( mdModel, asAnimName ); + if( pants[ i ].smElement[ 4 ] ) { + pants[ i ].smElement[ 4 ]->WillBeAnimated(); + pants[ i ].yUpdate = std::bind( &TDynamicObject::UpdatePant, this, std::placeholders::_1 ); + pants[ i ].fMaxDist = 300 * 300; // nie podnosić w większej odległości + pants[ i ].iNumber = i; + } + else { + ErrorLog( "Bad model: " + asFileName + " - missed submodel " + asAnimName, logtype::model ); // brak ramienia + } + } + } + } + + else if( token == "pantfactors:" ) { + // Winger 010304: + // parametry pantografow + double pant1x, pant2x, pant1h, pant2h; + parser.getTokens( 4, false ); + parser + >> pant1x + >> pant2x + >> pant1h // wysokość pierwszego ślizgu + >> pant2h;// wysokość drugiego ślizgu + if( pant1h > 0.5 ) { + pant1h = pant2h; // tu może być zbyt duża wartość + } + if (pant1x < 0 && + pant2x > 0) // pierwsza powinna być dodatnia, a druga ujemna + { + pant1x = -pant1x; + pant2x = -pant2x; + } + if( pants ) { + for( int i = 0; i < iAnimType[ ANIM_PANTS ]; ++i ) { + // przepisanie współczynników do pantografów (na razie nie będzie lepiej) + auto &pantograph { *pants[i].fParamPants }; + + pantograph.fAngleL = pantograph.fAngleL0; // początkowy kąt dolnego ramienia + pantograph.fAngleU = pantograph.fAngleU0; // początkowy kąt + // pants[i].fParamPants->PantWys=1.22*sin(pants[i].fParamPants->fAngleL)+1.755*sin(pants[i].fParamPants->fAngleU); + // //wysokość początkowa + // pants[i].fParamPants->PantWys=1.176289*sin(pants[i].fParamPants->fAngleL)+1.724482197*sin(pants[i].fParamPants->fAngleU); + // //wysokość początkowa + if( pantograph.fHeight == 0.0 ) // gdy jest nieprawdopodobna wartość (np. nie znaleziony ślizg) + { // gdy pomiary modelu nie udały się, odczyt podanych parametrów z MMD + pantograph.vPos.x = + i & 1 ? + pant2x : + pant1x; + pantograph.fHeight = + i & 1 ? + pant2h : + pant1h; // wysokość ślizgu jest zapisana w MMD + } + pantograph.PantWys = + pantograph.fLenL1 * sin( pantograph.fAngleL ) + + pantograph.fLenU1 * sin( pantograph.fAngleU ) + + pantograph.fHeight; // wysokość początkowa + // pants[i].fParamPants->vPos.y=panty-panth-pants[i].fParamPants->PantWys; //np. 4.429-0.097=4.332=~4.335 + if( pantograph.vPos.y == 0.0 ) { + // crude fallback, place the pantograph(s) atop of the vehicle-sized box + pantograph.vPos.y = MoverParameters->Dim.H - pantograph.fHeight - pantograph.PantWys; + } + // pants[i].fParamPants->vPos.z=0; //niezerowe dla pantografów asymetrycznych + pantograph.PantTraction = pantograph.PantWys; + // połowa szerokości ślizgu; jest w "Power: CSW=" + pantograph.fWidth = 0.5 * MoverParameters->EnginePowerSource.CollectorParameters.CSW; + + // create sound emitters for the pantograph + m_pantographsounds.emplace_back(); + } + } + } + + else if (token == "animpistonprefix:") { + // prefiks tłoczysk - na razie uzywamy modeli pantografów + parser.getTokens(1, false); parser >> token; + for( int i = 1; i <= 2; ++i ) + { + // asAnimName=str+i; + // smPatykird1[i-1]=mdModel->GetFromName(asAnimName.c_str()); + // smPatykird1[i-1]->WillBeAnimated(); + } + } + + else if( token == "animconrodprefix:" ) { + // prefiks korbowodów - na razie używamy modeli pantografów + parser.getTokens(); parser >> token; + for( int i = 1; i <= 2; i++ ) + { + // asAnimName=str+i; + // smPatykirg1[i-1]=mdModel->GetFromName(asAnimName.c_str()); + // smPatykirg1[i-1]->WillBeAnimated(); + } + } + + else if( token == "pistonfactors:" ) { + // Ra: parametry + // silnika parowego + // (tłoka) + /* //Ra: tymczasowo wyłączone ze względu na porządkowanie animacji + pantografów + pant1x=Parser->GetNextSymbol().ToDouble(); //kąt przesunięcia + dla + pierwszego tłoka + pant2x=Parser->GetNextSymbol().ToDouble(); //kąt przesunięcia + dla + drugiego tłoka + panty=Parser->GetNextSymbol().ToDouble(); //długość korby (r) + panth=Parser->GetNextSymbol().ToDouble(); //długoś korbowodu + (k) + */ + MoverParameters->EnginePowerSource.PowerType = + TPowerType::SteamPower; // Ra: po chamsku, ale z CHK nie działa + } + + else if( token == "animreturnprefix:" ) { + // prefiks drążka mimośrodowego - na razie używamy modeli pantografów + parser.getTokens(1, false); parser >> token; + for( int i = 1; i <= 2; i++ ) + { + // asAnimName=str+i; + // smPatykird2[i-1]=mdModel->GetFromName(asAnimName.c_str()); + // smPatykird2[i-1]->WillBeAnimated(); + } + } + + else if (token == "animexplinkprefix:"){ // animreturnprefix: + // prefiks jarzma - na razie używamy modeli pantografów + parser.getTokens(1, false); parser >> token; + for( int i = 1; i <= 2; i++ ) + { + // asAnimName=str+i; + // smPatykirg2[i-1]=mdModel->GetFromName(asAnimName.c_str()); + // smPatykirg2[i-1]->WillBeAnimated(); + } + } + + else if( token == "animpendulumprefix:" ) { + // prefiks wahaczy + parser.getTokens(); parser >> token; + asAnimName = ""; + for( int i = 1; i <= 4; ++i ) { + // McZapkie-050402: wyszukiwanie max 4 wahaczy o nazwie str* + asAnimName = token + std::to_string( i ); + smWahacze[ i - 1 ] = GetSubmodelFromName( mdModel, asAnimName ); + if( smWahacze[ i - 1 ] ) { + smWahacze[ i - 1 ]->WillBeAnimated(); + } + } + parser.getTokens(); parser >> token; + if( token == "pendulumamplitude:" ) { + parser.getTokens( 1, false ); + parser >> fWahaczeAmp; + } + } + + else if( token == "animslottedlever:" ) { + // lever with a slot, turned by a pin on the coupling rod (e.g. speedometer drive) + // parameters: submodel name, number of axle (from animwheelprefix) driving the coupling rod, crank radius [m], + // pin position relative to the lever axis [m] and crank angle [deg] for wheel angle 0, in local (Y, Z) plane of the lever + // angle is measured from Y axis towards Z axis, i.e. in the direction of rotation around X axis + slottedlever_data lever; + int axle { 1 }; + double crankradius { 0.0 }; + double crankangle { 0.0 }; + parser.getTokens( 6, false ); + parser + >> asAnimName + >> axle + >> crankradius + >> lever.pin.x + >> lever.pin.y + >> crankangle; + lever.submodel = GetSubmodelFromName( mdModel, asAnimName ); + if( lever.submodel != nullptr ) { + lever.submodel->WillBeAnimated(); + lever.axle = std::max( 0, axle - 1 ); + lever.crank = crankradius * glm::dvec2( std::cos( glm::radians( crankangle ) ), std::sin( glm::radians( crankangle ) ) ); + m_slottedlevers.emplace_back( lever ); + } + else { + ErrorLog( "Bad model: " + asFileName + " - missed submodel " + asAnimName, logtype::model ); + } + } + + else if( token == "animdoorprefix:" ) { + // nazwa animowanych drzwi + int i, j; + parser.getTokens(1, false); parser >> token; + for (i = 0, j = 0; i < ANIM_DOORS; ++i) + j += iAnimType[i]; // zliczanie wcześniejszych animacji + for (i = 0; i < iAnimType[ANIM_DOORS]; ++i) // liczba drzwi + { // NBMX wrzesien 2003: wyszukiwanie drzwi o nazwie str* + // ustalenie submodelu + asAnimName = token + std::to_string(i + 1); + pAnimations[ i + j ].smAnimated = GetSubmodelFromName( mdModel, asAnimName ); + if (pAnimations[i + j].smAnimated) + { //++iAnimatedDoors; + pAnimations[i + j].smAnimated->WillBeAnimated(); // wyłączenie optymalizacji transformu + pAnimations[i + j].iNumber = i + 1; // parzyste działają inaczej niż nieparzyste + bind_door_animation( pAnimations[ i + j ] ); // od razu zapinamy potrzebny typ animacji + pAnimations[i + j].fMaxDist = 300 * 300; // drzwi to z daleka widać +/* + // NOTE: no longer used + pAnimations[i + j].fSpeed = Random(150); // oryginalny koncept z DoorSpeedFactor + pAnimations[i + j].fSpeed = (pAnimations[i + j].fSpeed + 100) / 100; +*/ + } + } + } + + else if( token == "animdoor:" ) { + // own kind of animation of one door wing, in place of the one of the .fiz (eu07/maszyna#70): + // animdoor: { type: range: rangeout: } + // the keys left out keep the values of the .fiz. the wing still follows the door of its side + door_wings::wing_spec spec { + 0, + MoverParameters->Doors.type, + MoverParameters->Doors.range, + MoverParameters->Doors.range_out }; + auto error { door_wings::read_spec( parser, spec ) }; + if( error.empty() + && ( spec.number < 1 || spec.number > iAnimType[ ANIM_DOORS ] ) ) { + error = "no door wing " + std::to_string( spec.number ) + " among the door animations"; + } + if( false == error.empty() ) { + ErrorLog( "Bad model: " + asFileName + " - animdoor: " + error, logtype::model ); + } + else { + door_wings::store( m_doorwings, spec ); + // a wing animdoorprefix has found already gets the new kind of animation now; the ones it + // finds later get it then + auto const index { static_cast( std::accumulate( std::begin( iAnimType ), std::begin( iAnimType ) + ANIM_DOORS, 0 ) + spec.number - 1 ) }; + if( index < pAnimations.size() && pAnimations[ index ].yUpdate ) { + bind_door_animation( pAnimations[ index ] ); + } + } + } + + else if( token == "animstepprefix:" ) { + // animated doorstep submodel name prefix + int i, j; + parser.getTokens(1, false); parser >> token; + for (i = 0, j = 0; i < ANIM_DOORSTEPS; ++i) + j += iAnimType[i]; // zliczanie wcześniejszych animacji + for (i = 0; i < iAnimType[ANIM_DOORSTEPS]; ++i) // liczba drzwi + { // NBMX wrzesien 2003: wyszukiwanie drzwi o nazwie str* + // ustalenie submodelu + asAnimName = token + std::to_string(i + 1); + pAnimations[i + j].smAnimated = GetSubmodelFromName( mdModel, asAnimName ); + if (pAnimations[i + j].smAnimated) + { //++iAnimatedDoors; + pAnimations[i + j].smAnimated->WillBeAnimated(); // wyłączenie optymalizacji transformu + switch( MoverParameters->Doors.step_type ) + { // od razu zapinamy potrzebny typ animacji + case 1: // shift + pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdatePlatformTranslate, this, std::placeholders::_1 ); + break; + case 2: // rotate + pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdatePlatformRotate, this, std::placeholders::_1 ); + break; + default: + break; + } + pAnimations[i + j].iNumber = i + 1; // parzyste działają inaczej niż nieparzyste + pAnimations[i + j].fMaxDist = 150 * 150; // drzwi to z daleka widać +/* + // NOTE: no longer used + pAnimations[i + j].fSpeed = Random(150); // oryginalny koncept z DoorSpeedFactor + pAnimations[i + j].fSpeed = (pAnimations[i + j].fSpeed + 100) / 100; +*/ + } + } + } + + else if( token == "animmirrorprefix:" ) { + // animated mirror submodel name prefix + int i, j; + parser.getTokens( 1, false ); parser >> token; + for( i = 0, j = 0; i < ANIM_MIRRORS; ++i ) + j += iAnimType[ i ]; // zliczanie wcześniejszych animacji + for( i = 0; i < iAnimType[ ANIM_MIRRORS ]; ++i ) // liczba drzwi + { // NBMX wrzesien 2003: wyszukiwanie drzwi o nazwie str* + // ustalenie submodelu + asAnimName = token + std::to_string( i + 1 ); + pAnimations[ i + j ].smAnimated = GetSubmodelFromName( mdModel, asAnimName ); + if( pAnimations[ i + j ].smAnimated ) { + pAnimations[ i + j ].smAnimated->WillBeAnimated(); // wyłączenie optymalizacji transformu + // od razu zapinamy potrzebny typ animacji + auto const offset { pAnimations[ i + j ].smAnimated->offset() }; + pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdateMirror, this, std::placeholders::_1 ); + // we don't expect more than 2-4 mirrors, so it should be safe to store submodel location (front/rear) in the higher bits + // parzyste działają inaczej niż nieparzyste + pAnimations[ i + j ].iNumber = + ( ( pAnimations[ i + j ].smAnimated->offset().z > 0 ? + end::front : + end::rear ) << 4 ) + + i; + pAnimations[ i + j ].fMaxDist = 150 * 150; // drzwi to z daleka widać +/* + // NOTE: no longer used + pAnimations[i + j].fSpeed = Random(150); // oryginalny koncept z DoorSpeedFactor + pAnimations[i + j].fSpeed = (pAnimations[i + j].fSpeed + 100) / 100; +*/ + } + } + } + + else if (token == "animwiperprefix:") + { + parser.getTokens(1, false); + parser >> token; + TSubModel *sm; + if (wipers) + { + + for (int i = 0; i < iAnimType[ANIM_WIPERS]; i++) // zebranie wszystkich submodeli wycieraczek + { + dWiperPos.emplace_back(0.0); // dodajemy na koniec zeby sie miejsce tam zrobilo i nie bylo invalid addressow potem + + asAnimName = token + std::to_string(i + 1); + // element wycieraczki nr 1 + sm = GetSubmodelFromName(mdModel, asAnimName + "_p1"); + wipers[i].smElement[0] = sm; + if (sm) + { + wipers[i].smElement[0]->WillBeAnimated(); + // auto const offset{wipers[i].smElement[0]->offset()}; + } + + // element wycieraczki nr 2 + sm = GetSubmodelFromName(mdModel, asAnimName + "_p2"); + wipers[i].smElement[1] = sm; + if (sm) + { + wipers[i].smElement[1]->WillBeAnimated(); + // auto const offset{wipers[i].smElement[0]->offset()}; + } + + // element wycieraczki nr 3 + sm = GetSubmodelFromName(mdModel, asAnimName + "_p3"); + wipers[i].smElement[2] = sm; + if (sm) + { + wipers[i].smElement[2]->WillBeAnimated(); + // auto const offset{wipers[i].smElement[0]->offset()}; + } + wipers[i].yUpdate = std::bind(&TDynamicObject::UpdateWiper, this, std::placeholders::_1); + wipers[i].fMaxDist = 150 * 150; + wipers[i].iNumber = i; + } + } + } + + } while( token != "" + && token != "endmodels" ); + + if( false == MoverParameters->LoadAttributes.empty() ) { + // Ra: tu wczytywanie modelu ładunku jest w porządku + + // bieżąca ścieżka do tekstur to dynamic/... + Global.asCurrentTexturePath = asBaseDir; + + mdLoad = LoadMMediaFile_mdload( MoverParameters->LoadType.name ); + + // z powrotem defaultowa sciezka do tekstur + Global.asCurrentTexturePath = std::string( paths::textures ); + } + + } // models + + else if( token == "sounds:" ) { + // dzwieki + do { + token = ""; + parser.getTokens(); parser >> token; + if( token == "wheel_clatter:" ){ + // polozenia osi w/m srodka pojazdu + double dSDist; + parser.getTokens( 1, false ); + parser >> dSDist; + while( (token = parser.getToken()) != "" + && token != "end" ) { + // add another axle entry to the list + axle_sounds axle { + 0, + std::atof( token.c_str() ) * -1.0, // for axle locations negative value means ahead of centre but vehicle faces +Z in 'its' space + { sound_placement::external, static_cast( dSDist ) } }; + axle.clatter.deserialize( parser, sound_type::single ); + axle.clatter.owner( this ); + axle.clatter.offset( { 0, 0, axle.offset } ); + m_axlesounds.emplace_back( axle ); + } + // arrange the axles in case they're listed out of order + std::sort( + std::begin( m_axlesounds ), std::end( m_axlesounds ), + []( axle_sounds const &Left, axle_sounds const &Right ) { + return Left.offset > Right.offset; } ); + } + + else if( token == "engine:" + && MoverParameters->Power > 0 ) { + // plik z dzwiekiem silnika, mnozniki i ofsety amp. i czest. + m_powertrainsounds.engine.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); + m_powertrainsounds.engine.owner( this ); + + auto const amplitudedivisor = static_cast( MoverParameters->EngineType == TEngineType::DieselEngine ? 1 : + MoverParameters->EngineType == TEngineType::DieselElectric ? 1 : + MoverParameters->nmax * 60 + MoverParameters->Power * 3 ); + m_powertrainsounds.engine.m_amplitudefactor /= amplitudedivisor; + + } else if (token == "fakeengine:") { + m_powertrainsounds.fake_engine.deserialize(parser, sound_type::single); + m_powertrainsounds.fake_engine.owner(this); + } + + else if( token == "dieselinc:" ) { + // dzwiek przy wlazeniu na obroty woodwarda + m_powertrainsounds.engine_revving.deserialize( parser, sound_type::single, sound_parameters::range ); + m_powertrainsounds.engine_revving.owner( this ); + } + + else if( token == "oilpump:" ) { + m_powertrainsounds.oil_pump.deserialize( parser, sound_type::single ); + m_powertrainsounds.oil_pump.owner( this ); + } + + else if( token == "fuelpump:" ) { + m_powertrainsounds.fuel_pump.deserialize( parser, sound_type::single ); + m_powertrainsounds.fuel_pump.owner( this ); + } + + else if( token == "waterpump:" ) { + m_powertrainsounds.water_pump.deserialize( parser, sound_type::single ); + m_powertrainsounds.water_pump.owner( this ); + } + + else if( token == "waterheater:" ) { + m_powertrainsounds.water_heater.deserialize( parser, sound_type::single ); + m_powertrainsounds.water_heater.owner( this ); + } + + else if( token == "tractionmotor:" && MoverParameters->Power > 0 ) { + // plik z dzwiekiem silnika, mnozniki i ofsety amp. i czest. + sound_source motortemplate { sound_placement::external }; + motortemplate.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); + auto const amplitudedivisor { static_cast( MoverParameters->nmax * 60 + MoverParameters->Power * 3 ) }; + motortemplate.m_amplitudefactor /= amplitudedivisor; + motortemplate.owner( this ); + + auto &motors { m_powertrainsounds.motors }; + + if( true == motors.empty() ) { + // fallback for cases without specified motor locations, convert sound template to a single sound source + motors.emplace_back( motortemplate ); + } + else { + // apply configuration to all defined motors + for( auto &motor : motors ) { + // combine potential x- and y-axis offsets of the sound template with z-axis offsets of individual motors + auto motoroffset { motortemplate.offset() }; + motoroffset.z = motor.offset().z; + motor = motortemplate; + motor.offset( motoroffset ); + // apply randomized playback start offset for each instance, to reduce potential reverb with identical nearby sources + motor.start( LocalRandom( 0.0, 1.0 ) ); + } + } + } + + else if( token == "tractionacmotor:" && MoverParameters->Power > 0 ) { + // plik z dzwiekiem silnika, mnozniki i ofsety amp. i czest. + sound_source motortemplate { sound_placement::external }; + motortemplate.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); + motortemplate.owner( this ); + + auto &motors { m_powertrainsounds.acmotors }; + + if( true == motors.empty() ) { + // fallback for cases without specified motor locations, convert sound template to a single sound source + motors.emplace_back( motortemplate ); + } + else { + // apply configuration to all defined motors + for( auto &motor : motors ) { + // combine potential x- and y-axis offsets of the sound template with z-axis offsets of individual motors + auto motoroffset { motortemplate.offset() }; + motoroffset.z = motor.offset().z; + motor = motortemplate; + motor.offset( motoroffset ); + // apply randomized playback start offset for each instance, to reduce potential reverb with identical nearby sources + motor.start( LocalRandom( 0.0, 1.0 ) ); + } + } + } + + else if( token == "motorblower:" ) { + + sound_source blowertemplate { sound_placement::engine }; + blowertemplate.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); + blowertemplate.owner( this ); + + auto const amplitudedivisor { static_cast( + MoverParameters->MotorBlowers[ end::front ].speed > 0 ? MoverParameters->MotorBlowers[ end::front ].speed * MoverParameters->nmax * 60 + MoverParameters->Power * 3 : + blowertemplate.has_bookends() ? 1 : // NOTE: for motorblowers with fixed speed if the sound has defined bookends we skip revolutions-based part of frequency/volume adjustments + MoverParameters->MotorBlowers[ end::front ].speed * -1 ) }; + blowertemplate.m_amplitudefactor /= amplitudedivisor; + blowertemplate.m_frequencyfactor /= amplitudedivisor; + + if( true == m_powertrainsounds.motors.empty() ) { + // fallback for cases without specified motor locations, convert sound template to a single sound source + m_powertrainsounds.motorblowers.emplace_back( blowertemplate ); + } + else { + // apply configuration to all defined motor blowers + for( auto &blower : m_powertrainsounds.motorblowers ) { + // combine potential x- and y-axis offsets of the sound template with z-axis offsets of individual blowers + auto bloweroffset { blowertemplate.offset() }; + bloweroffset.z = blower.offset().z; + blower = blowertemplate; + blower.offset( bloweroffset ); + // apply randomized playback start offset for each instance, to reduce potential reverb with identical nearby sources + blower.start( LocalRandom( 0.0, 1.0 ) ); + } + } + } + + else if( token == "inverter:" ) { + // plik z dzwiekiem wentylatora, mnozniki i ofsety amp. i czest. + m_powertrainsounds.inverter.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); + m_powertrainsounds.inverter.owner( this ); + } + + else if( token == "ventilator:" ) { + // plik z dzwiekiem wentylatora, mnozniki i ofsety amp. i czest. + m_powertrainsounds.rsWentylator.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); + m_powertrainsounds.rsWentylator.owner( this ); + + m_powertrainsounds.rsWentylator.m_amplitudefactor /= MoverParameters->RVentnmax; + m_powertrainsounds.rsWentylator.m_frequencyfactor /= MoverParameters->RVentnmax; + } + + else if( token == "radiatorfan1:" ) { + // primary circuit radiator fan + m_powertrainsounds.radiator_fan.deserialize( parser, sound_type::single ); + m_powertrainsounds.radiator_fan.owner( this ); + } + + else if( token == "radiatorfan2" ) { + // auxiliary circuit radiator fan + m_powertrainsounds.radiator_fan_aux.deserialize( parser, sound_type::single ); + m_powertrainsounds.radiator_fan_aux.owner( this ); + } + + else if( token == "transmission:" ) { + // plik z dzwiekiem, mnozniki i ofsety amp. i czest. + // NOTE, fixed default parameters, legacy system leftover + auto &sound { m_powertrainsounds.transmission }; + sound.m_amplitudefactor = 0.029; + sound.m_amplitudeoffset = 0.1; + sound.m_frequencyfactor = 0.005; + sound.m_frequencyoffset = 1.0; + + sound.deserialize( parser, sound_type::single, sound_parameters::range ); + sound.owner( this ); + } + + else if( token == "brakesound:" ) { + // hamowanie zwykle: + rsBrake.deserialize( parser, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency ); + rsBrake.owner( this ); + // NOTE: can't pre-calculate amplitude normalization based on max brake force, as this varies depending on vehicle speed + rsBrake.m_frequencyfactor /= 1 + MoverParameters->Vmax; + } + + else if( token == "brake:" ) { + // plik z piskiem hamulca, mnozniki i ofsety amplitudy. + rsPisk.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude ); + rsPisk.owner( this ); + + if( rsPisk.m_amplitudefactor > 10.f ) { + // HACK: convert old style activation point threshold to the new, regular amplitude adjustment system + rsPisk.m_amplitudefactor = 1.f; + rsPisk.m_amplitudeoffset = 0.f; + } + rsPisk.m_amplitudeoffset *= ( 105.f - Random( 10.f ) ) / 100.f; + } + + else if( token == "brakecylinderinc:" ) { + // brake cylinder pressure increase sounds + m_brakecylinderpistonadvance.deserialize( parser, sound_type::single ); + m_brakecylinderpistonadvance.owner( this ); + } + + else if( token == "brakecylinderdec:" ) { + // brake cylinder pressure decrease sounds + m_brakecylinderpistonrecede.deserialize( parser, sound_type::single ); + m_brakecylinderpistonrecede.owner( this ); + } + + else if (token == "epbrakeinc:") { + // brake cylinder pressure increase sounds + m_epbrakepressureincrease.deserialize(parser, sound_type::single); + m_epbrakepressureincrease.owner(this); + } + + else if (token == "epbrakedec:") { + // brake cylinder pressure decrease sounds + m_epbrakepressuredecrease.deserialize(parser, sound_type::single); + m_epbrakepressuredecrease.owner(this); + } + + else if( token == "emergencybrake:" ) { + // emergency brake sound + m_emergencybrake.deserialize( parser, sound_type::single ); + m_emergencybrake.owner( this ); + } + + else if( token == "brakeacc:" ) { + // plik z przyspieszaczem (upust po zlapaniu hamowania) + sBrakeAcc.deserialize( parser, sound_type::single ); + sBrakeAcc.owner( this ); + + bBrakeAcc = true; + } + + else if( token == "unbrake:" ) { + // plik z piskiem hamulca, mnozniki i ofsety amplitudy. + rsUnbrake.m_amplitudefactor = 20.0f; + rsUnbrake.deserialize( parser, sound_type::single, sound_parameters::range ); + rsUnbrake.owner( this ); + } + // spring brake sounds + else if( token == "springbrake:" ) { + m_springbrakesounds.activate.deserialize( parser, sound_type::single ); + m_springbrakesounds.activate.owner( this ); + } + else if( token == "springbrakeoff:" ) { + m_springbrakesounds.release.deserialize( parser, sound_type::single ); + m_springbrakesounds.release.owner( this ); + } + + else if( token == "derail:" ) { + // dzwiek przy wykolejeniu + rsDerailment.deserialize( parser, sound_type::single, sound_parameters::range ); + rsDerailment.owner( this ); + } + + else if( token == "curve:" ) { + rscurve.deserialize( parser, sound_type::single, sound_parameters::range ); + rscurve.owner( this ); + } + + else if( token == "horn1:" ) { + // pliki z trabieniem + sHorn1.deserialize( parser, sound_type::multipart, sound_parameters::range ); + sHorn1.owner( this ); + } + + else if( token == "horn2:" ) { + // pliki z trabieniem wysokoton. + sHorn2.deserialize( parser, sound_type::multipart, sound_parameters::range ); + sHorn2.owner( this ); + // TBD, TODO: move horn selection to ai config file + if( iHornWarning ) { + iHornWarning = 2; // numer syreny do użycia po otrzymaniu sygnału do jazdy + } + } + + else if( token == "horn3:" ) { + sHorn3.deserialize( parser, sound_type::multipart, sound_parameters::range ); + sHorn3.owner( this ); + } + + else if( token == "pantographup:" ) { + // pliki dzwiekow pantografow + sound_source pantographup { sound_placement::external }; + pantographup.deserialize( parser, sound_type::single ); + pantographup.owner( this ); + for( auto &pantograph : m_pantographsounds ) { + pantograph.sPantUp = pantographup; + } + } + + else if( token == "pantographdown:" ) { + // pliki dzwiekow pantografow + sound_source pantographdown { sound_placement::external }; + pantographdown.deserialize( parser, sound_type::single ); + pantographdown.owner( this ); + for( auto &pantograph : m_pantographsounds ) { + pantograph.sPantDown = pantographdown; + } + } + + else if( token == "compressor:" ) { + // pliki ze sprezarka + sCompressor.deserialize( parser, sound_type::multipart, sound_parameters::range ); + sCompressor.owner( this ); + } + + else if( token == "compressoridle:" ) { + // pliki ze sprezarka + sCompressorIdle.deserialize( parser, sound_type::multipart, sound_parameters::range ); + sCompressorIdle.owner( this ); + } + + else if( token == "converter:" ) { + // pliki z przetwornica + sConverter.deserialize( parser, sound_type::multipart, sound_parameters::range ); + sConverter.owner( this ); + } + + // Dzwiek wentylatora rezystora hamowania + else if (token == "brakingresistorventilator:") + { + sBRVent.deserialize(parser, sound_type::multipart, sound_parameters::range); + sBRVent.owner(this); + } + + else if( token == "heater:" ) { + // train heating device + sHeater.deserialize( parser, sound_type::single ); + sHeater.owner( this ); + } + + else if( token == "battery:" ) { + // train heating device + m_batterysound.deserialize( parser, sound_type::single ); + m_batterysound.owner( this ); + } + + else if( token == "turbo:" ) { + // pliki z turbogeneratorem + m_powertrainsounds.engine_turbo.deserialize( parser, sound_type::multipart, sound_parameters::range ); + m_powertrainsounds.engine_turbo.owner( this ); + m_powertrainsounds.engine_turbo.gain( 0 ); + } + + else if( token == "small-compressor:" ) { + // pliki z przetwornica + sSmallCompressor.deserialize( parser, sound_type::multipart, sound_parameters::range ); + sSmallCompressor.owner( this ); + } + + else if( token == "departuresignal:" ) { + // pliki z sygnalem odjazdu + sound_source soundtemplate { sound_placement::general, 25.f }; + soundtemplate.deserialize( parser, sound_type::multipart, sound_parameters::range ); + soundtemplate.owner( this ); + for( auto &speaker : m_doorspeakers ) { + speaker.departure_signal = soundtemplate; + speaker.departure_signal.offset( speaker.offset ); + } + } + + else if( token == "dooropen:" ) { + sound_source soundtemplate { sound_placement::general }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &door : m_doorsounds ) { + // apply configuration to all defined doors, but preserve their individual offsets + auto const dooroffset { door.rsDoorOpen.offset() }; + door.rsDoorOpen = soundtemplate; + door.rsDoorOpen.offset( dooroffset ); + } + } + + else if( token == "doorclose:" ) { + sound_source soundtemplate { sound_placement::general }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &door : m_doorsounds ) { + // apply configuration to all defined doors, but preserve their individual offsets + auto const dooroffset { door.rsDoorClose.offset() }; + door.rsDoorClose = soundtemplate; + door.rsDoorClose.offset( dooroffset ); + } + } + + else if( token == "doorlock:" ) { + sound_source soundtemplate { sound_placement::general }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &door : m_doorsounds ) { + // apply configuration to all defined doors, but preserve their individual offsets + auto const dooroffset { door.lock.offset() }; + door.lock = soundtemplate; + door.lock.offset( dooroffset ); + } + } + + else if( token == "doorunlock:" ) { + sound_source soundtemplate { sound_placement::general }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &door : m_doorsounds ) { + // apply configuration to all defined doors, but preserve their individual offsets + auto const dooroffset { door.unlock.offset() }; + door.unlock = soundtemplate; + door.unlock.offset( dooroffset ); + } + } + + else if( token == "doorstepopen:" ) { + sound_source soundtemplate { sound_placement::general }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &door : m_doorsounds ) { + // apply configuration to all defined doors, but preserve their individual offsets + auto const dooroffset { door.step_open.offset() }; + door.step_open = soundtemplate; + door.step_open.offset( dooroffset ); + } + } + + else if( token == "mirroropen:" || token == "mirrorclose:" ) { + sound_source soundtemplate { sound_placement::general }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &mirror : m_mirrorsounds ) { + // apply configuration to all defined mirrors, but preserve their individual offsets + auto &sound { token == "mirroropen:" ? mirror.unfold : mirror.fold }; + auto const mirroroffset { sound.offset() }; + sound = soundtemplate; + sound.offset( mirroroffset ); + } + } + + else if( token == "doorstepclose:" ) { + sound_source soundtemplate { sound_placement::general }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &door : m_doorsounds ) { + // apply configuration to all defined doors, but preserve their individual offsets + auto const dooroffset { door.step_close.offset() }; + door.step_close = soundtemplate; + door.step_close.offset( dooroffset ); + } + } + + else if( token == "doorpermit:" ) { + sound_source soundtemplate { sound_placement::general }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &door : m_doorsounds ) { + // apply configuration to all defined doors, but preserve their individual offsets + auto const dooroffset { door.permit_granted.offset() }; + door.permit_granted = soundtemplate; + door.permit_granted.offset( dooroffset ); + } + } + + else if( token == "unloading:" ) { + m_exchangesounds.unloading.range( MoverParameters->Dim.L * 0.5f * -1 ); + m_exchangesounds.unloading.deserialize( parser, sound_type::single ); + m_exchangesounds.unloading.owner( this ); + } + + else if( token == "loading:" ) { + m_exchangesounds.loading.range( MoverParameters->Dim.L * 0.5f * -1 ); + m_exchangesounds.loading.deserialize( parser, sound_type::single ); + m_exchangesounds.loading.owner( this ); + } + + else if( token == "sand:" ) { + sSand.deserialize( parser, sound_type::multipart, sound_parameters::range ); + sSand.owner( this ); + } + + else if( token == "releaser:" ) { + // pliki z odluzniaczem + sReleaser.deserialize( parser, sound_type::multipart, sound_parameters::range ); + sReleaser.owner( this ); + } + + else if( token == "outernoise:" ) { + // szum podczas jazdy: + sound_source noisetemplate{ sound_placement::external, EU07_SOUND_RUNNINGNOISECUTOFFRANGE }; + noisetemplate.deserialize( parser, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency, MoverParameters->Vmax ); + noisetemplate.owner( this ); + + noisetemplate.m_amplitudefactor /= 1 + MoverParameters->Vmax; + noisetemplate.m_frequencyfactor /= 1 + MoverParameters->Vmax; +#ifdef EU07_SOUND_BOGIESOUNDS + if( true == m_bogiesounds.empty() ) { + // fallback for cases without specified noise locations, convert sound template to a single sound source + m_bogiesounds.emplace_back( noisetemplate ); + } + else { + // apply configuration to all defined bogies + for( auto &bogie : m_bogiesounds ) { + // combine potential x- and y-axis offsets of the sound template with z-axis offsets of individual motors + auto bogieoffset{ noisetemplate.offset() }; + bogieoffset.z = bogie.offset().z; + bogie = noisetemplate; + bogie.offset( bogieoffset ); + } + } + // apply randomized playback start offset for each bogie, to reduce potential reverb with identical nearby sources + auto bogieidx( 0 ); + for( auto &bogie : m_bogiesounds ) { + bogie.start( ( + bogieidx % 2 ? + LocalRandom( 0.0, 30.0 ) : + LocalRandom( 50.0, 80.0 ) ) + * 0.01 ); + ++bogieidx; + } +#else + m_outernoise = noisetemplate; + // apply randomized playback start offset, to reduce potential reverb with identical nearby sources + m_outernoise.start( Random( 0.0, 80.0 ) * 0.01 ); +#endif + } + + else if( token == "wheelflat:" ) { + // szum podczas jazdy: + m_wheelflat.deserialize( parser, sound_type::single, sound_parameters::frequency ); + m_wheelflat.owner( this ); + } + + else if(token == "announcements:") { + // announcement sounds + // content provided as "key: value" pairs together enclosed in "{}" + // value can be optionally set of values enclosed in "[]" in which case one value will be picked randomly + std::unordered_map const announcements = { + { "near_stop:", announcement_t::approaching }, + { "stop:", announcement_t::current }, + { "next_stop:", announcement_t::next }, + { "destination:", announcement_t::destination }, + { "chime:", announcement_t::chime } }; + while( (token = parser.getToken()) != "" + && token != "}" ) { + if( token.back() == ':' ) { + + if( token == "soundproofing:" ) { + // custom soundproofing in format [ p1, p2, p3, p4, p5, p6 ] + parser.getTokens( 6, false, "\n\r\t ,;[]" ); + std::array soundproofing; + parser + >> soundproofing[ 0 ] + >> soundproofing[ 1 ] + >> soundproofing[ 2 ] + >> soundproofing[ 3 ] + >> soundproofing[ 4 ] + >> soundproofing[ 5 ]; + for( auto & soundproofingelement : soundproofing ) { + if( soundproofingelement != -1.f ) { + soundproofingelement = std::sqrt( std::clamp( soundproofingelement, 0.f, 1.f ) ); + } + } + m_pasystem.soundproofing = soundproofing; + continue; + } + + auto const lookup { announcements.find( token ) }; + auto const announcementtype { ( + lookup != announcements.end() ? + lookup->second : + announcement_t::idle ) }; + // NOTE: we retrieve key value for all keys, not just recognized ones + if( announcementtype == announcement_t::idle ) { + token = parser.getToken(); + continue; + } +/* + auto announcementsound { deserialize_random_set( parser ) }; + replace_slashes( announcementsound ); +*/ + sound_source soundtemplate { sound_placement::engine }; // NOTE: sound range gets filled by pa system + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + m_pasystem.announcements[ static_cast( announcementtype ) ] = soundtemplate; + } + } + // set provided custom soundproofing to assigned sounds (for sounds without their own custom soundproofing) + if( m_pasystem.soundproofing ) { + for( auto &announcement : m_pasystem.announcements ) { + if( !announcement.soundproofing() ) { + announcement.soundproofing() = m_pasystem.soundproofing; + } + } + } + } + + } while( token != "" + && token != "endsounds" ); + + } // sounds: + + else if( token == "locations:" ) { + do { + token = ""; + parser.getTokens(); parser >> token; + + if( token == "doors:" ) { + // a list of pairs: offset along vehicle's z-axis and sides on which the door is present; followed with "end" + while( (token = parser.getToken()) != "" + && token != "end" ) { + // vehicle faces +Z in 'its' space, for door locations negative value means ahead of centre + auto const offset { std::atof( token.c_str() ) * -1.f }; + // recognized side specifications are "right", "left" and "both" + auto const sides { parser.getToken() }; + // NOTE: we skip setting owner of the sounds, it'll be done during individual sound deserialization + door_sounds door; + // add entries to the list: + if( sides == "both" + || sides == "left" ) { + // left... + auto const location { glm::vec3 { MoverParameters->Dim.W * 0.5f, MoverParameters->Dim.H * 0.5f, offset } }; + door.placement = side::left; + door.rsDoorClose.offset( location ); + door.rsDoorOpen.offset( location ); + door.lock.offset( location ); + door.unlock.offset( location ); + door.step_close.offset( location ); + door.step_open.offset( location ); + door.permit_granted.offset( location ); + m_doorsounds.emplace_back( door ); + } + if( sides == "both" + || sides == "right" ) { + // ...and right + auto const location { glm::vec3 { MoverParameters->Dim.W * -0.5f, 2.f, offset } }; + door.placement = side::right; + door.rsDoorClose.offset( location ); + door.rsDoorOpen.offset( location ); + door.lock.offset( location ); + door.unlock.offset( location ); + door.step_close.offset( location ); + door.step_open.offset( location ); + door.permit_granted.offset( location ); + m_doorsounds.emplace_back( door ); + } + m_doorspeakers.emplace_back( + doorspeaker_sounds { + { 0.f, 3.f, offset }, + {} } ); + } + } + + else if( token == "mirrors:" ) { + // a list of offsets along vehicle's z-axis of the mirror pairs, one at each cab; followed with "end" + while( (token = parser.getToken()) != "" + && token != "end" ) { + // vehicle faces +Z in 'its' space, as for the doors negative value means ahead of centre + auto const offset { std::atof( token.c_str() ) * -1.f }; + mirror_sounds mirror; + mirror.end = offset >= 0.f ? end::front : end::rear; + for( auto const mirrorside : { side::left, side::right } ) { + auto const location { glm::vec3 { + MoverParameters->Dim.W * ( mirrorside == side::left ? 0.5f : -0.5f ), + MoverParameters->Dim.H * 0.5f, + offset } }; + mirror.placement = mirrorside; + mirror.unfold.offset( location ); + mirror.fold.offset( location ); + m_mirrorsounds.emplace_back( mirror ); + } + } + } + + else if( token == "tractionmotors:" ) { + // a list of offsets along vehicle's z-axis; followed with "end" + while( (token = parser.getToken()) != "" + && token != "end" ) { + // vehicle faces +Z in 'its' space, for motor locations negative value means ahead of centre + auto const offset { std::atof( token.c_str() ) * -1.f }; + // NOTE: we skip setting owner of the sounds, it'll be done during individual sound deserialization + sound_source motor { sound_placement::external }; // generic traction motor sounds + sound_source acmotor { sound_placement::external }; // inverter-specific traction motor sounds + sound_source motorblower { sound_placement::engine }; // associated motor blowers + // add entry to the list + auto const location { glm::vec3 { 0.f, 0.f, offset } }; + motor.offset( location ); + m_powertrainsounds.motors.emplace_back( motor ); + acmotor.offset( location ); + m_powertrainsounds.acmotors.emplace_back( acmotor ); + motorblower.offset( location ); + m_powertrainsounds.motorblowers.emplace_back( motorblower ); + } + } + + else if( token == "bogies:" ) { + // a list of offsets along vehicle's z-axis; followed with "end" + while( (token = parser.getToken()) != "" + && token != "end" ) { + // vehicle faces +Z in 'its' space, for bogie locations negative value means ahead of centre + auto const offset { std::atof( token.c_str() ) * -1.f }; + // NOTE: we skip setting owner of the sounds, it'll be done during individual sound deserialization + sound_source bogienoise { sound_placement::external, EU07_SOUND_RUNNINGNOISECUTOFFRANGE }; + // add entry to the list + auto const location { glm::vec3 { 0.f, 0.f, offset } }; + bogienoise.offset( location ); +#ifdef EU07_SOUND_BOGIESOUNDS + m_bogiesounds.emplace_back( bogienoise ); +#endif + } + } + + } while( token != "" + && token != "endlocations" ); + + } // locations: + + else if( token == "internaldata:" ) { + // dalej nie czytaj + do { + // zbieranie informacji o kabinach + token = ""; + parser.getTokens(); parser >> token; + if( token == "cab0model:" ) { + parser.getTokens(); parser >> token; + if( token != "none" ) { iCabs |= 0x2; } + } + else if( token == "cab1model:" ) { + parser.getTokens(); parser >> token; + if( token != "none" ) { iCabs |= 0x1; } + } + else if( token == "cab2model:" ) { + parser.getTokens(); parser >> token; + if( token != "none" ) { iCabs |= 0x4; } + } + // engine sounds + else if( token == "ignition:" ) { + // odpalanie silnika + m_powertrainsounds.engine_ignition.deserialize( parser, sound_type::single ); + m_powertrainsounds.engine_ignition.owner( this ); + } else if (token == "shutdown:") { + m_powertrainsounds.engine_shutdown.deserialize(parser, sound_type::single); + m_powertrainsounds.engine_shutdown.owner(this); + } else if( token == "engageslippery:" ) { + // tarcie tarcz sprzegla: + m_powertrainsounds.rsEngageSlippery.deserialize( parser, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency ); + m_powertrainsounds.rsEngageSlippery.owner( this ); + + m_powertrainsounds.rsEngageSlippery.m_frequencyfactor /= 1 + MoverParameters->nmax; + } + + // dzwieki wycieraczkuf + else if (token == "wiperfrompark:") + { + sWiperFromPark.deserialize(parser, sound_type::single); + sWiperFromPark.owner(this); + } + else if (token == "wipertopark:") + { + sWiperToPark.deserialize(parser, sound_type::single); + sWiperToPark.owner(this); + } + + else if (token == "retarder:") { + m_powertrainsounds.retarder.deserialize(parser, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency); + m_powertrainsounds.retarder.owner(this); + } + else if( token == "linebreakerclose:" ) { + m_powertrainsounds.linebreaker_close.deserialize( parser, sound_type::single ); + m_powertrainsounds.linebreaker_close.owner( this ); + } + else if( token == "linebreakeropen:" ) { + m_powertrainsounds.linebreaker_open.deserialize( parser, sound_type::single ); + m_powertrainsounds.linebreaker_open.owner( this ); + } + else if( token == "relay:" ) { + // styczniki itp: + m_powertrainsounds.motor_relay.deserialize( parser, sound_type::single ); + m_powertrainsounds.motor_relay.owner( this ); + } + else if( token == "shuntfield:" ) { + // styczniki itp: + m_powertrainsounds.motor_shuntfield.deserialize( parser, sound_type::single ); + m_powertrainsounds.motor_shuntfield.owner( this ); + } + else if( token == "wejscie_na_bezoporow:" ) { + // hunter-111211: wydzielenie wejscia na bezoporowa i na drugi uklad do pliku + m_powertrainsounds.dsbWejscie_na_bezoporow.deserialize( parser, sound_type::single ); + m_powertrainsounds.dsbWejscie_na_bezoporow.owner( this ); + } + // przekazniki od kierunku jazdy + else if (token == "directionrelay_d:") { + // przekaznik od kierunku jazdy do przodu + sDirectionRelayD.deserialize(parser, sound_type::single); + sDirectionRelayD.owner(this); + } + else if (token == "directionrelay_r:") { + // przekaznik od kierunku jazdy do tylu + sDirectionRelayR.deserialize(parser, sound_type::single); + sDirectionRelayR.owner(this); + } + else if (token == "directionrelay_n:") + { + // przekaznik od kierunku jazdy do tylu + sDirectionRelayN.deserialize(parser, sound_type::single); + sDirectionRelayN.owner(this); + } + else if( token == "wejscie_na_drugi_uklad:" ) { + m_powertrainsounds.motor_parallel.deserialize( parser, sound_type::single ); + m_powertrainsounds.motor_parallel.owner( this ); + } + else if( token == "pneumaticrelay:" ) { + // wylaczniki pneumatyczne: + dsbPneumaticRelay.deserialize( parser, sound_type::single ); + dsbPneumaticRelay.owner( this ); + } + else if( token == "slipperysound:" ) { + // sanie: + rsSlippery.deserialize( parser, sound_type::single, sound_parameters::amplitude ); + rsSlippery.owner( this ); + + rsSlippery.m_amplitudefactor /= 1 + MoverParameters->Vmax; + } + // coupler sounds + else if( token == "couplerattach:" ) { + sound_source soundtemplate { sound_placement::external }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.attach_coupler = soundtemplate; + } + } + else if( token == "brakehoseattach:" ) { + // laczenie: + sound_source soundtemplate { sound_placement::external }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.attach_brakehose = soundtemplate; + } + } + else if( token == "mainhoseattach:" ) { + // laczenie: + sound_source soundtemplate{ sound_placement::external }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.attach_mainhose = soundtemplate; + } + } + else if( token == "controlattach:" ) { + // laczenie: + sound_source soundtemplate{ sound_placement::external }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.attach_control = soundtemplate; + } + } + else if( token == "gangwayattach:" ) { + // laczenie: + sound_source soundtemplate{ sound_placement::external }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.attach_gangway = soundtemplate; + } + } + else if( token == "heatingattach:" ) { + // laczenie: + sound_source soundtemplate{ sound_placement::external }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.attach_heating = soundtemplate; + } + } + else if( token == "couplerdetach:" ) { + // rozlaczanie: + sound_source soundtemplate { sound_placement::external }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.detach_coupler = soundtemplate; + } + } + else if( token == "brakehosedetach:" ) { + // rozlaczanie: + sound_source soundtemplate { sound_placement::external }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.detach_brakehose = soundtemplate; + } + } + else if( token == "mainhosedetach:" ) { + // rozlaczanie: + sound_source soundtemplate{ sound_placement::external }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.detach_mainhose = soundtemplate; + } + } + else if( token == "controldetach:" ) { + // rozlaczanie: + sound_source soundtemplate{ sound_placement::external }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.detach_control = soundtemplate; + } + } + else if( token == "gangwaydetach:" ) { + // rozlaczanie: + sound_source soundtemplate{ sound_placement::external }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.detach_gangway = soundtemplate; + } + } + else if( token == "heatingdetach:" ) { + // rozlaczanie: + sound_source soundtemplate{ sound_placement::external }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.detach_heating = soundtemplate; + } + } + else if( token == "couplerstretch:" ) { + // coupler stretching + sound_source couplerstretch { sound_placement::external }; + couplerstretch.deserialize( parser, sound_type::single ); + couplerstretch.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.dsbCouplerStretch = couplerstretch; + } + } + else if( token == "couplerstretch_loud:" ) { + // coupler stretching + sound_source couplerstretch { sound_placement::external }; + couplerstretch.deserialize( parser, sound_type::single ); + couplerstretch.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.dsbCouplerStretch_loud = couplerstretch; + } + } + else if( token == "bufferclamp:" ) { + // buffers hitting one another + sound_source bufferclash { sound_placement::external }; + bufferclash.deserialize( parser, sound_type::single ); + bufferclash.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.dsbBufferClamp = bufferclash; + } + } + else if( token == "bufferclamp_loud:" ) { + // buffers hitting one another + sound_source bufferclash { sound_placement::external }; + bufferclash.deserialize( parser, sound_type::single ); + bufferclash.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.dsbBufferClamp_loud = bufferclash; + } + } + else if( token == "coupleradapterattach:" ) { + // laczenie: + sound_source adapterattach { sound_placement::external }; + adapterattach.deserialize( parser, sound_type::single ); + adapterattach.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.dsbAdapterAttach = adapterattach; + } + } + else if( token == "coupleradapterremove:" ) { + // rozlaczanie: + sound_source adapterremove { sound_placement::external }; + adapterremove.deserialize( parser, sound_type::single ); + adapterremove.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.dsbAdapterRemove = adapterremove; + } + } + else if( token == "startjolt:" ) { + // movement start jolt + m_startjolt.deserialize( parser, sound_type::single ); + m_startjolt.owner( this ); + } + + else if (token == "mechspring:") + { + // parametry bujania kamery: + double ks, kd; + parser.getTokens(2, false); + parser + >> ks + >> kd; + ShakeSpring.Init(ks, kd); + parser.getTokens(6, false); + parser + >> BaseShake.jolt_scale.x + >> BaseShake.jolt_scale.y + >> BaseShake.jolt_scale.z + >> BaseShake.jolt_limit + >> BaseShake.angle_scale.x + >> BaseShake.angle_scale.z; + } + else if( token == "enginespring:" ) { + parser.getTokens( 5, false ); + parser + >> EngineShake.scale + >> EngineShake.fadein_offset + >> EngineShake.fadein_factor + >> EngineShake.fadeout_offset + >> EngineShake.fadeout_factor; + // offsets values are provided as rpm for convenience + EngineShake.fadein_offset /= 60.f; + EngineShake.fadeout_offset /= 60.f; + } + else if( token == "huntingspring:" ) { + parser.getTokens( 4, false ); + parser + >> HuntingShake.scale + >> HuntingShake.frequency + >> HuntingShake.fadein_begin + >> HuntingShake.fadein_end; + } + + else if( token == "soundproofing:" ) { + for( auto &soundproofingtable : m_soundproofing ) { + for( auto &soundproofingelement : soundproofingtable ) { + auto const value { parser.getToken( false ) }; + if( value != -1.f ) { + soundproofingelement = std::sqrt( std::clamp( value, 0.f, 1.f ) ); + } + } + } + } + + else if( token == "jointcabs:" ) { + parser.getTokens(); + parser >> JointCabs; + } + + else if( token == "cablight:" ) { + parser.getTokens( 3, false ); // low power light, ignore + parser.getTokens( 3, false ); // base light + parser + >> InteriorLight.r + >> InteriorLight.g + >> InteriorLight.b; + InteriorLight = glm::clamp( InteriorLight / 255.f, glm::vec3( 0.f ), glm::vec3( 1.f ) ); + parser.getTokens( 3, false ); // dimmed light, ignore + } + + else if( token == "pydestinationsign:" ) { + DestinationSign.deserialize( parser ); + // supply vehicle folder as script path if none is provided + if( false == DestinationSign.script.empty() + && substr_path(DestinationSign.script).empty() ) { + DestinationSign.script = asBaseDir + DestinationSign.script; + } + } + else if( token == "luadestinationsign:" ) { + deserialize_script_sign( parser, DestinationSign.lua, asBaseDir ); + } + else if( token == "wasmdestinationsign:" ) { + deserialize_script_sign( parser, DestinationSign.wasm, asBaseDir ); + } + // NOTE: legacy key, now expected as optional "background:" parameter in pydestinationsign: { parameter block } + else if( token == "destinationsignbackground:" ) { + parser.getTokens(); + parser >> DestinationSign.background; + } + + } while( token != "" ); + + } // internaldata: + + } while( token != "" ); + + if( !iAnimations ) { + // if the animations weren't defined the model is likely to be non-functional. warrants a warning. + ErrorLog( "Animations tag is missing from the .mmd file \"" + asFileName + "\"" ); + } + + if( ReplacableSkin != "none" ) { + // potentially set blank destination texture + auto language { script_language::lua }; + auto const *scriptsign { script_destination( language ) }; + auto const &background { ( scriptsign != nullptr && false == scriptsign->background.empty() ) ? scriptsign->background : DestinationSign.background }; + DestinationSign.destination_off = DestinationFind( background.empty() ? "nowhere" : background ); + // a blank sign a script draws, drawn once + DestinationSign.background_sign = draw_script_texture( background, DestinationSign.destination_off ); + } + + // assign default samples to sound emitters which weren't included in the config file + if( TestFlag( MoverParameters->CategoryFlag, 1 ) ) { + // rail vehicles: + // engine + if( MoverParameters->Power > 0 ) { + if( true == m_powertrainsounds.dsbWejscie_na_bezoporow.empty() ) { + // hunter-111211: domyslne, gdy brak + m_powertrainsounds.dsbWejscie_na_bezoporow.deserialize( "wejscie_na_bezoporow", sound_type::single ); + m_powertrainsounds.dsbWejscie_na_bezoporow.owner( this ); + } + if( true == m_powertrainsounds.motor_parallel.empty() ) { + m_powertrainsounds.motor_parallel.deserialize( "wescie_na_drugi_uklad", sound_type::single ); + m_powertrainsounds.motor_parallel.owner( this ); + } + } + // braking sounds + if( true == rsUnbrake.empty() ) { + rsUnbrake.deserialize( "[1007]estluz", sound_type::single ); + rsUnbrake.owner( this ); + } + // couplers + for( auto &couplersounds : m_couplersounds ) { + if( true == couplersounds.attach_coupler.empty() ) { + couplersounds.attach_coupler.deserialize( "couplerattach_default", sound_type::single ); + couplersounds.attach_coupler.owner( this ); + } + if( true == couplersounds.detach_coupler.empty() ) { + couplersounds.detach_coupler.deserialize( "couplerdetach_default", sound_type::single ); + couplersounds.detach_coupler.owner( this ); + } + if( true == couplersounds.dsbCouplerStretch.empty() ) { + couplersounds.dsbCouplerStretch.deserialize( "couplerstretch_default", sound_type::single ); + couplersounds.dsbCouplerStretch.owner( this ); + } + if( true == couplersounds.dsbBufferClamp.empty() ) { + couplersounds.dsbBufferClamp.deserialize( "bufferclamp_default", sound_type::single ); + couplersounds.dsbBufferClamp.owner( this ); + } + } + // other sounds + if( true == m_wheelflat.empty() ) { + m_wheelflat.deserialize( "lomotpodkucia 0.23 0.0", sound_type::single, sound_parameters::frequency ); + m_wheelflat.owner( this ); + } + if( true == rscurve.empty() ) { + // hunter-111211: domyslne, gdy brak + rscurve.deserialize( "curve", sound_type::single ); + rscurve.owner( this ); + } + } + + if (mdModel) + mdModel->Init(); // obrócenie modelu oraz optymalizacja, również zapisanie binarnego + if (mdLoad) + mdLoad->Init(); + if (mdLowPolyInt) + mdLowPolyInt->Init(); + for( auto *attachment : mdAttachments ) { + attachment->Init(); + } + + Global.asCurrentTexturePath = paths::textures; // kiedyś uproszczone wnętrze mieszało tekstury nieba + Global.asCurrentDynamicPath = ""; + + // position sound emitters which weren't defined in the config file + // engine sounds, centre of the vehicle + auto const enginelocation { glm::vec3 {0.f, MoverParameters->Dim.H * 0.5f, 0.f } }; + m_powertrainsounds.position( enginelocation ); + // other engine compartment sounds + auto const nullvector { glm::vec3() }; + std::vector enginesounds = { + &sConverter, &sBRVent, &sCompressor, &sCompressorIdle, &sSmallCompressor, &sHeater, &m_batterysound + }; + for( auto sound : enginesounds ) { + if( sound->offset() == nullvector ) { + sound->offset( enginelocation ); + } + } + + // pantographs + if( pants != nullptr ) { + std::size_t pantographindex { 0 }; + for( auto &pantographsounds : m_pantographsounds ) { + auto const pantographoffset { + glm::vec3( + 0.f, + pants[ pantographindex ].fParamPants->vPos.y, + -pants[ pantographindex ].fParamPants->vPos.x ) }; + pantographsounds.sPantUp.offset( pantographoffset ); + pantographsounds.sPantDown.offset( pantographoffset ); + ++pantographindex; + } + } + // doors + std::size_t dooranimationfirstindex { 0 }; + for( std::size_t i = 0; i < ANIM_DOORS; ++i ) { + // zliczanie wcześniejszych animacji + dooranimationfirstindex += iAnimType[ i ]; + } + // couplers + auto const frontcoupleroffset { glm::vec3{ 0.f, 1.f, MoverParameters->Dim.L * 0.5f } }; + m_couplersounds[ end::front ].attach_coupler.offset( frontcoupleroffset ); + m_couplersounds[ end::front ].attach_brakehose.offset( frontcoupleroffset ); + m_couplersounds[ end::front ].attach_mainhose.offset( frontcoupleroffset ); + m_couplersounds[ end::front ].attach_control.offset( frontcoupleroffset ); + m_couplersounds[ end::front ].attach_gangway.offset( frontcoupleroffset ); + m_couplersounds[ end::front ].attach_heating.offset( frontcoupleroffset ); + m_couplersounds[ end::front ].detach_coupler.offset( frontcoupleroffset ); + m_couplersounds[ end::front ].detach_brakehose.offset( frontcoupleroffset ); + m_couplersounds[ end::front ].detach_mainhose.offset( frontcoupleroffset ); + m_couplersounds[ end::front ].detach_control.offset( frontcoupleroffset ); + m_couplersounds[ end::front ].detach_gangway.offset( frontcoupleroffset ); + m_couplersounds[ end::front ].detach_heating.offset( frontcoupleroffset ); + m_couplersounds[ end::front ].dsbCouplerStretch.offset( frontcoupleroffset ); + m_couplersounds[ end::front ].dsbCouplerStretch_loud.offset( frontcoupleroffset ); + m_couplersounds[ end::front ].dsbBufferClamp.offset( frontcoupleroffset ); + m_couplersounds[ end::front ].dsbBufferClamp_loud.offset( frontcoupleroffset ); + m_couplersounds[ end::front ].dsbAdapterAttach.offset( frontcoupleroffset ); + m_couplersounds[ end::front ].dsbAdapterRemove.offset( frontcoupleroffset ); + auto const rearcoupleroffset { glm::vec3{ 0.f, 1.f, MoverParameters->Dim.L * -0.5f } }; + m_couplersounds[ end::rear ].attach_coupler.offset( rearcoupleroffset ); + m_couplersounds[ end::rear ].attach_brakehose.offset( rearcoupleroffset ); + m_couplersounds[ end::rear ].attach_mainhose.offset( rearcoupleroffset ); + m_couplersounds[ end::rear ].attach_control.offset( rearcoupleroffset ); + m_couplersounds[ end::rear ].attach_gangway.offset( rearcoupleroffset ); + m_couplersounds[ end::rear ].attach_heating.offset( rearcoupleroffset ); + m_couplersounds[ end::rear ].detach_coupler.offset( rearcoupleroffset ); + m_couplersounds[ end::rear ].detach_brakehose.offset( rearcoupleroffset ); + m_couplersounds[ end::rear ].detach_mainhose.offset( rearcoupleroffset ); + m_couplersounds[ end::rear ].detach_control.offset( rearcoupleroffset ); + m_couplersounds[ end::rear ].detach_gangway.offset( rearcoupleroffset ); + m_couplersounds[ end::rear ].detach_heating.offset( rearcoupleroffset ); + m_couplersounds[ end::rear ].dsbCouplerStretch.offset( rearcoupleroffset ); + m_couplersounds[ end::rear ].dsbCouplerStretch_loud.offset( rearcoupleroffset ); + m_couplersounds[ end::rear ].dsbBufferClamp.offset( rearcoupleroffset ); + m_couplersounds[ end::rear ].dsbBufferClamp_loud.offset( rearcoupleroffset ); + m_couplersounds[ end::rear ].dsbAdapterAttach.offset( rearcoupleroffset ); + m_couplersounds[ end::rear ].dsbAdapterRemove.offset( rearcoupleroffset ); +} + +TModel3d * +TDynamicObject::LoadMMediaFile_mdload( std::string const &Name ) const { + + auto const loadname { ( Name.empty() ? "none" : Name ) }; + TModel3d *loadmodel { nullptr }; + + // check if we don't have model override for this load type + if ( loadmodel == nullptr ) + { + auto const lookup { LoadModelOverrides.find( loadname ) }; + if( lookup != LoadModelOverrides.end() ) { + loadmodel = TModelsManager::GetModel( asBaseDir + lookup->second, true ); + } + } + // regular routine if there's no override or it couldn't be loaded + // try first specialized version of the load model, vehiclename_loadname + if ( loadmodel == nullptr ) + { + auto const specializedloadfilename { asBaseDir + MoverParameters->TypeName + "_" + loadname }; + loadmodel = TModelsManager::GetModel( specializedloadfilename, true, false ); + } + // try generic version of the load model next, loadname + if ( loadmodel == nullptr ) + { + auto const genericloadfilename { asBaseDir + loadname }; + loadmodel = TModelsManager::GetModel( genericloadfilename, true, false ); + } + + if ( loadmodel != nullptr ) + loadmodel->GetSMRoot()->WillBeAnimated(); + + return loadmodel; +} diff --git a/vehicle/dynamic/movement.cpp b/vehicle/dynamic/movement.cpp new file mode 100644 index 000000000..d5f0a4ccf --- /dev/null +++ b/vehicle/dynamic/movement.cpp @@ -0,0 +1,321 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// moving a vehicle along its track, its axles and its bogies + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/mover.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + + +void TDynamicObject::FastMove(double fDistance) +{ + MoverParameters->dMoveLen = MoverParameters->dMoveLen + fDistance; +} + +void TDynamicObject::Move(double fDistance) +{ + if( MoverParameters->OffTrack.active() ) { + // physics.derailment new: off the track it goes on the ground + move_off_track( fDistance ); + return; + } + move_axles( fDistance ); + if( fDistance != 0.0 || m_offtrackplaced ) // nie liczyć ponownie, jeśli stoi + { // liczenie pozycji pojazdu tutaj, bo jest używane w wielu miejscach + // (also once the vehicle off the track is back on the rails) + m_offtrackplaced = false; + place_by_axles(); + } +} + +void TDynamicObject::move_axles(double fDistance) +{ // przesuwanie pojazdu po + // trajektorii polega na + // przesuwaniu poszczególnych osi + // Ra: wartość prędkości 2km/h ma ograniczyć aktywację eventów w przypadku + // drgań + if (Axle0.GetTrack() == Axle1.GetTrack()) // przed przesunięciem + { // powiązanie pojazdu z osią można zmienić tylko wtedy, gdy skrajne osie są + // na tym samym torze + if (MoverParameters->Vel > + 2) //|[km/h]| nie ma sensu zmiana osi, jesli pojazd drga na postoju + iAxleFirst = MoverParameters->V >= 0.0 ? + 1 : + 0; //[m/s] ?1:0 - aktywna druga oś w kierunku jazdy + // aktualnie eventy aktywuje druga oś, żeby AI nie wyłączało sobie semafora + // za szybko + } + if (fDistance > 0.0) + { // gdy ruch w stronę sprzęgu 0, doliczyć korektę do osi 1 + bEnabled &= Axle0.Move(fDistance, iAxleFirst == 0); // oś z przodu pojazdu + bEnabled &= Axle1.Move(fDistance /*-fAdjustment*/, iAxleFirst != 0); // oś z tyłu pojazdu + } + else if (fDistance < 0.0) + { // gdy ruch w stronę sprzęgu 1, doliczyć korektę do osi 0 + bEnabled &= Axle1.Move(fDistance, iAxleFirst != 0); // oś z tyłu pojazdu prusza się pierwsza + bEnabled &= Axle0.Move(fDistance /*-fAdjustment*/, iAxleFirst == 0); // oś z przodu pojazdu + } + else // gf: bez wywolania Move na postoju nie ma event0 + { + bEnabled &= Axle1.Move(fDistance, iAxleFirst != 0); // oś z tyłu pojazdu prusza się pierwsza + bEnabled &= Axle0.Move(fDistance, iAxleFirst == 0); // oś z przodu pojazdu + } +} + +void TDynamicObject::place_by_axles() +{ // liczenie pozycji pojazdu tutaj, bo jest używane w wielu miejscach + vPosition = 0.5 * (Axle1.pPosition + Axle0.pPosition); //środek między skrajnymi osiami + vFront = Axle0.pPosition - Axle1.pPosition; // wektor pomiędzy skrajnymi osiami + // Ra 2F1J: to nie jest stabilne (powoduje rzucanie taborem) i wymaga + // dopracowania + fAdjustment = glm::length(vFront) - fAxleDist; // na łuku będzie ujemny + // if (fabs(fAdjustment)>0.02) //jeśli jest zbyt dużo, to rozłożyć na kilka przeliczeń (wygasza drgania?) + //{//parę centymetrów trzeba by już skorygować; te błędy mogą się też + // generować na ostrych łukach + // fAdjustment*=0.5; //w jednym kroku korygowany jest ułamek błędu + //} + // else + // fAdjustment=0.0; + vFront = glm::normalize(vFront); // kierunek ustawienia pojazdu (wektor jednostkowy) + vLeft = glm::normalize(glm::cross(glm::dvec3(vWorldUp), vFront)); // wektor poziomy w lewo, + // normalizacja potrzebna z powodu pochylenia (vFront) + vUp = glm::cross(vFront, vLeft); // wektor w górę, będzie jednostkowy + modelRot.z = atan2(-vFront.x, vFront.z); // kąt obrotu pojazdu [rad]; z ABuBogies() + auto const roll { Roll() }; // suma przechyłek + if (roll != 0.0) + { // wyznaczanie przechylenia tylko jeśli jest przechyłka + // można by pobrać wektory normalne z toru... + mMatrix = glm::rotate(glm::dmat4(1.0), roll * 0.5, vFront); // ta macierz jest potrzebna głównie do wyświetlania // obrót wzdłuż osi o przechyłkę + vUp = glm::dvec3(mMatrix * glm::dvec4(vUp, 0.0)); // wektor w górę pojazdu (przekręcenie na przechyłce) + // vLeft=mMatrix*DynamicObject->vLeft; + // vUp=CrossProduct(vFront,vLeft); //wektor w górę + // vLeft=Normalize(CrossProduct(vWorldUp,vFront)); //wektor w lewo + vLeft = glm::normalize(glm::cross(vUp, vFront)); // wektor w lewo + // vUp=CrossProduct(vFront,vLeft); //wektor w górę + } + mMatrix = BasisChange(vLeft, vUp, vFront); // to też można by od razu policzyć, ale potrzebne jest do wyświetlania // przesuwanie jest jednak rzadziej niż renderowanie + mMatrix = glm::inverse(mMatrix); // wyliczenie macierzy dla pojazdu (potrzebna tylko do wyświetlania?) + // if (MoverParameters->CategoryFlag&2) + { // przesunięcia są używane po wyrzuceniu pociągu z toru + vPosition.x += MoverParameters->OffsetTrackH * vLeft.x; // dodanie przesunięcia w bok + vPosition.z += MoverParameters->OffsetTrackH * vLeft.z; // vLeft jest wektorem poprzecznym + // if () na przechyłce będzie dodatkowo zmiana wysokości samochodu + vPosition.y += MoverParameters->OffsetTrackV; // te offsety są liczone przez moverparam + } + // obliczanie pozycji sprzęgów do liczenia zderzeń + auto dir = 0.5 * MoverParameters->Dim.L * vFront; // wektor sprzęgu + vCoulpler[end::front] = vPosition + dir; // współrzędne sprzęgu na początku + vCoulpler[end::rear] = vPosition - dir; // współrzędne sprzęgu na końcu + // bCameraNear= + // if (bCameraNear) //jeśli istotne są szczegóły (blisko kamery) + { // przeliczenie cienia + TTrack *t0 = Axle0.GetTrack(); // już po przesunięciu + TTrack *t1 = Axle1.GetTrack(); + if (t0->eEnvironment == e_flat && t1->eEnvironment == e_flat) // może być e_bridge... + fShade = 0.0; // standardowe oświetlenie + else + { // jeżeli te tory mają niestandardowy stopień zacienienia + // (e_canyon, e_tunnel) + if (t0->eEnvironment == t1->eEnvironment) + { + switch (t0->eEnvironment) + { // typ zmiany oświetlenia + case e_canyon: + fShade = 0.65f; + break; // zacienienie w kanionie + case e_tunnel: + fShade = 0.20f; + break; // zacienienie w tunelu + } + } + else // dwa różne + { // liczymy proporcję + double d = Axle0.GetTranslation(); // aktualne położenie na torze + if (Axle0.GetDirection() < 0) + d = t0->Length() - d; // od drugiej strony liczona długość + d /= fAxleDist; // rozsataw osi procentowe znajdowanie się na torze + + float shadefrom = 1.0f, shadeto = 1.0f; + // NOTE, TODO: calculating brightness level is used enough times to warrant encapsulation into a function + switch( t0->eEnvironment ) { + case e_canyon: { shadeto = 0.65f; break; } + case e_tunnel: { shadeto = 0.2f; break; } + default: {break; } + } + switch( t1->eEnvironment ) { + case e_canyon: { shadefrom = 0.65f; break; } + case e_tunnel: { shadefrom = 0.2f; break; } + default: {break; } + } + fShade = std::lerp( shadefrom, shadeto, static_cast( d ) ); +/* + switch (t0->eEnvironment) + { // typ zmiany oświetlenia - zakładam, że + // drugi tor ma e_flat + case e_canyon: + fShade = (d * 0.65) + (1.0 - d); + break; // zacienienie w kanionie + case e_tunnel: + fShade = (d * 0.20) + (1.0 - d); + break; // zacienienie w tunelu + } + switch (t1->eEnvironment) + { // typ zmiany oświetlenia - zakładam, że + // pierwszy tor ma e_flat + case e_canyon: + fShade = d + (1.0 - d) * 0.65; + break; // zacienienie w kanionie + case e_tunnel: + fShade = d + (1.0 - d) * 0.20; + break; // zacienienie w tunelu + } +*/ + } + } + } +} + +bool TDynamicObject::UpdateForce(double dt) +{ + if (!bEnabled) + return false; + if( dt > 0 ) { + // wywalenie WS zależy od ustawienia kierunku + MoverParameters->ComputeTotalForce( dt ); + } + return true; +} + +glm::dvec3 TDynamicObject::get_future_movement() const +{ + return m_future_movement; +} + +void TDynamicObject::move_set(double distance) +{ + TDynamicObject *d = this; + while( d ) { + d->Move( distance * d->DirectionGet() ); + d = d->Next(); // pozostałe też + } + d = Prev(); + while( d ) { + d->Move( distance * d->DirectionGet() ); + d = d->Prev(); // w drugą stronę też + } +} + +bool TDynamicObject::FastUpdate(double dt) +{ + if (dt == 0.0) + return true; // Ra: pauza + double dDOMoveLen; + if (!MoverParameters->PhysicActivation) + return true; // McZapkie: wylaczanie fizyki gdy nie potrzeba + + if (!bEnabled) + return false; + + // NOTE: coordinate system swap + // TODO: replace with regular glm vectors + TLocation const l { + -vPosition.x, + vPosition.z, + vPosition.y }; + TRotation const r { + 0.0, + 0.0, + modelRot.z }; + // McZapkie: parametry powinny byc pobierane z toru + // ts.R=MyTrack->fRadius; + // ts.Len= std::max(MoverParameters->BDist,MoverParameters->ADist); + // ts.dHtrack=Axle1.pPosition.y-Axle0.pPosition.y; + // ts.dHrail=((Axle1.GetRoll())+(Axle0.GetRoll()))*0.5f; + // tp.Width=MyTrack->fTrackWidth; + // McZapkie-250202 + // tp.friction= MyTrack->fFriction; + // tp.CategoryFlag= MyTrack->iCategoryFlag&15; + // tp.DamageFlag=MyTrack->iDamageFlag; + // tp.QualityFlag=MyTrack->iQualityFlag; + dDOMoveLen = MoverParameters->FastComputeMovement(dt, ts, tp, l, r); // ,ts,tp,tmpTraction); + // Move(dDOMoveLen); + // ResetdMoveLen(); + FastMove(dDOMoveLen); + + if( MoverParameters->LoadStatus ) { + LoadUpdate(); // zmiana modelu ładunku + } + update_exchange( dt ); + + return true; // Ra: chyba tak? +} + +// calculates distance between event-starting axle and front of the vehicle +double +TDynamicObject::tracing_offset() const { + + auto const axletoend{ ( GetLength() - fAxleDist ) * 0.5 }; + return iAxleFirst ? axletoend : axletoend + iDirection * fAxleDist; +} + +// TODO: compute and cache radius during vehicle initialization +double +TDynamicObject::radius() const { + + glm::vec3 diagonal( + static_cast( MoverParameters->Dim.L ), + static_cast( MoverParameters->Dim.H ), + static_cast( MoverParameters->Dim.W ) ); + return glm::length( diagonal ) * 0.5f; +} diff --git a/vehicle/dynamic/neighbours.cpp b/vehicle/dynamic/neighbours.cpp new file mode 100644 index 000000000..cc43d8e56 --- /dev/null +++ b/vehicle/dynamic/neighbours.cpp @@ -0,0 +1,313 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the vehicles near a vehicle on its track, found for the couplings and the collisions + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/mover.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + +// ABu 29.01.05 koniec przeklejenia ************************************* + +TDynamicObject * TDynamicObject::ABuFindNearestObject(glm::vec3 pos, TTrack *Track, TDynamicObject *MyPointer, int &CouplNr) +{ + // zwraca wskaznik do obiektu znajdujacego sie na torze (Track), którego sprzęg jest najblizszy punktowi + // służy np. do łączenia i rozpinania sprzęgów + // WE: Track - tor, na ktorym odbywa sie poszukiwanie + // MyPointer - wskaznik do obiektu szukajacego + // WY: CouplNr - który sprzęg znalezionego obiektu jest bliższy kamerze + + // Uwaga! Jesli CouplNr==-2 to szukamy njblizszego obiektu, a nie sprzegu!!! + for( auto dynamic : Track->Dynamics ) { + + if( CouplNr == -2 ) { + // wektor [kamera-obiekt] - poszukiwanie obiektu + // length2 is better than length for comparing because it does not require sqrt function + if (glm::length2(glm::dvec3(pos) - dynamic->vPosition) < sq(10.0)) + { + // 10 metrów + return dynamic; + } + } + else { + // jeśli (CouplNr) inne niz -2, szukamy sprzęgu + // length2 is better than length for comparing because it does not require sqrt function + if (glm::length2(glm::dvec3(pos) - dynamic->vCoulpler[0]) < sq(5.0)) { + // 5 metrów + CouplNr = 0; + return dynamic; + } + // length2 is better than length for comparing because it does not require sqrt function + if (glm::length2(glm::dvec3(pos) - dynamic->vCoulpler[1]) < sq(5.0)) { + // 5 metrów + CouplNr = 1; + return dynamic; + } + } + } + // empty track or nothing found + return nullptr; +} + +TDynamicObject * TDynamicObject::ABuScanNearestObject(glm::vec3 pos, TTrack *Track, double ScanDir, double ScanDist, int &CouplNr) +{ // skanowanie toru w poszukiwaniu obiektu najblizszego punktowi + if (ABuGetDirection() < 0) + ScanDir = -ScanDir; + TDynamicObject *FoundedObj; + FoundedObj = + ABuFindNearestObject(pos, Track, this, CouplNr); // zwraca numer sprzęgu znalezionego pojazdu + if (FoundedObj == nullptr && Track != nullptr) + { + double ActDist; // Przeskanowana odleglosc. + double CurrDist = 0; // Aktualna dlugosc toru. + if (ScanDir >= 0) + ActDist = + Track->Length() - RaTranslationGet(); //???-przesunięcie wózka względem Point1 toru + else + ActDist = RaTranslationGet(); // przesunięcie wózka względem Point1 toru + while (ActDist < ScanDist) + { + ActDist += CurrDist; + if (ScanDir > 0) // do przodu + { + if (Track->iNextDirection) // NOSONAR + { + Track = Track->CurrentNext(); + ScanDir = -ScanDir; + } + else + Track = Track->CurrentNext(); + } + else // do tyłu + { + if (Track->iPrevDirection) // NOSONAR + Track = Track->CurrentPrev(); + else + { + Track = Track->CurrentPrev(); + ScanDir = -ScanDir; + } + } + if (Track != nullptr) + { // jesli jest kolejny odcinek toru + CurrDist = Track->Length(); + FoundedObj = ABuFindNearestObject(pos, Track, this, CouplNr); + if (FoundedObj != nullptr) + ActDist = ScanDist; + } + else // Jesli nie ma, to wychodzimy. + break; + } + } // Koniec szukania najblizszego toru z jakims obiektem. + return FoundedObj; +} + +// ABu 01.11.04 poczatek wyliczania przechylow pudla ********************** +void TDynamicObject::ABuModelRoll() +{ // ustawienie przechyłki pojazdu i jego + // zawartości + // Ra: przechyłkę załatwiamy na etapie przesuwania modelu +} + +// ABu 06.05.04 poczatek wyliczania obrotow wozkow ********************** + +void TDynamicObject::ABuBogies() +{ // Obracanie wozkow na zakretach. Na razie + // uwzględnia tylko zakręty, + // bez zadnych gorek i innych przeszkod. + if( smBogie[ 0 ] != nullptr && smBogie[ 1 ] != nullptr && MoverParameters->OffTrack.active() ) { + // off the track the bogies stay straight under the body, they don't follow the track any more + bogieRot[ 0 ] = glm::vec3 { 0.f }; + bogieRot[ 1 ] = glm::vec3 { 0.f }; + smBogie[ 0 ]->SetRotateXYZ( bogieRot[ 0 ] ); + smBogie[ 1 ]->SetRotateXYZ( bogieRot[ 1 ] ); + return; + } + if (smBogie[0] != nullptr && smBogie[1] != nullptr) + { + // modelRot.z=ABuAcos(Axle0.pPosition-Axle1.pPosition); //kąt obrotu pojazdu + // [rad] + // bogieRot[0].z=ABuAcos(Axle0.pPosition-Axle3.pPosition); + bogieRot[0].z = Axle0.vAngles.z; + bogieRot[0] = glm::degrees(modelRot - bogieRot[0]); // mnożenie wektora przez stałą + smBogie[0]->SetRotateXYZ(bogieRot[0]); + // bogieRot[1].z=ABuAcos(Axle2.pPosition-Axle1.pPosition); + bogieRot[1].z = Axle1.vAngles.z; + bogieRot[1] = glm::degrees(modelRot - bogieRot[1]); + smBogie[1]->SetRotateXYZ(bogieRot[1]); + } +}; +// ABu 06.05.04 koniec wyliczania obrotow wozkow ************************ + +// ABu 16.03.03 sledzenie toru przed obiektem: ************************** +void TDynamicObject::ABuCheckMyTrack() +{ // Funkcja przypisujaca obiekt + // prawidlowej tablicy Dynamics, + // bo gdzies jest jakis blad i wszystkie obiekty z danego + // pociagu na poczatku stawiane sa na jednym torze i wpisywane + // do jednej tablicy. Wykonuje sie tylko raz - po to 'ABuChecked' + TTrack *OldTrack = MyTrack; + TTrack *NewTrack = Axle0.GetTrack(); + if( NewTrack != OldTrack ) { + if( OldTrack ) { + OldTrack->RemoveDynamicObject( this ); + } + NewTrack->AddDynamicObject(this); + } + iAxleFirst = 0; // pojazd powiązany z przednią osią - Axle0 +} + +// Ra: w poniższej funkcji jest problem ze sprzęgami +TDynamicObject * +TDynamicObject::ABuFindObject( int &Foundcoupler, double &Distance, TTrack const *Track, int const Direction, int const Mycoupler, bool const InLine ) const +{ // Zwraca wskaźnik najbliższego obiektu znajdującego się + // na torze w określonym kierunku, ale tylko wtedy, kiedy + // obiekty mogą się zderzyć, tzn. nie mijają się. + // WE: + // Track - tor, na ktorym odbywa sie poszukiwanie, + // Direction - kierunek szukania na torze (+1:w stronę Point2, -1:w stronę Point1) + // Mycoupler - nr sprzegu obiektu szukajacego; + // WY: + // wskaznik do znalezionego obiektu. + // Foundcoupler - nr sprzegu znalezionego obiektu + // Distance - distance to found object + + if( true == Track->Dynamics.empty() ) { + // sens szukania na tym torze jest tylko, gdy są na nim pojazdy + Distance += Track->Length(); // doliczenie długości odcinka do przeskanowanej odległości + return nullptr; // nie ma pojazdów na torze, to jest NULL + } + + double distance = Track->Length(); // najmniejsza znaleziona odleglość (zaczynamy od długości toru) + double myposition; // pozycja szukającego na torze + TDynamicObject *foundobject = nullptr; + if( MyTrack == Track ) { + // gdy szukanie na tym samym torze + myposition = RaTranslationGet(); // położenie wózka względem Point1 toru + } + else { + // gdy szukanie na innym torze + if( Direction > 0 ) { + // szukanie w kierunku Point2 (od zera) - jesteśmy w Point1 + myposition = 0; + } + else { + // szukanie w kierunku Point1 (do zera) - jesteśmy w Point2 + myposition = distance; + } + } + + double objectposition; // robocza odległość od kolejnych pojazdów na danym odcinku + for( auto dynamic : Track->Dynamics ) { + + if( dynamic == this ) { continue; } // szukający się nie liczy + // physics.derailment new: one of the two off the track beside the other one, they don't meet + if( InLine && ( MoverParameters->OffTrack.active() || dynamic->MoverParameters->OffTrack.active() ) && false == in_line_with( *dynamic ) ) { + continue; + } +/* + if( ( ( dynamic == PrevConnected ) && ( MoverParameters->Couplers[ TMoverParameters::side::front ].CouplingFlag != Coupling::none ) ) + || ( ( dynamic == NextConnected ) && ( MoverParameters->Couplers[ TMoverParameters::side::rear ].CouplingFlag != Coupling::none ) ) ){ + // stop-gap check to prevent 'detection' of attached vehicles + // which seems to be a side-effect of inaccurate location calculation in 'simple' mode? + // TODO: investigate actual cause + continue; + } +*/ + if( Direction > 0 ) { + // jeśli szukanie w kierunku Point2 + objectposition = dynamic->RaTranslationGet() - myposition; // odległogłość tamtego od szukającego + if( objectposition > 0 + && objectposition < distance ) { + // gdy jest po właściwej stronie i bliżej niż jakiś wcześniejszy + Foundcoupler = dynamic->RaDirectionGet() > 0 ? 1 : 0; // to, bo (ScanDir>=0) + } + else { continue; } + } + else { + objectposition = myposition - dynamic->RaTranslationGet(); //???-przesunięcie wózka względem Point1 toru + if( objectposition > 0 + && objectposition < distance ) { + Foundcoupler = dynamic->RaDirectionGet() > 0 ? 0 : 1; // odwrotnie, bo (ScanDir<0) + } + else { continue; } + } + + if( Track->iCategoryFlag & 254 ) { + // trajektoria innego typu niż tor kolejowy + // dla torów nie ma sensu tego sprawdzać, rzadko co jedzie po jednej szynie i się mija + // Ra: mijanie samochodów wcale nie jest proste + // Przesuniecie wzgledne pojazdow. Wyznaczane, zeby sprawdzic, + // czy pojazdy faktycznie sie zderzaja (moga byc przesuniete + // w/m siebie tak, ze nie zachodza na siebie i wtedy sie mijaja). + double relativeoffset; // wzajemna odległość poprzeczna + if( Foundcoupler != Mycoupler ) { + // facing the same direction + relativeoffset = std::abs( MoverParameters->OffsetTrackH - dynamic->MoverParameters->OffsetTrackH ); + } + else { + relativeoffset = std::abs( MoverParameters->OffsetTrackH + dynamic->MoverParameters->OffsetTrackH ); + } + if( relativeoffset + relativeoffset > MoverParameters->Dim.W + dynamic->MoverParameters->Dim.W ) { + // odległość większa od połowy sumy szerokości - kolizji nie będzie + continue; + } + // jeśli zahaczenie jest niewielkie, a jest miejsce na poboczu, to zjechać na pobocze + } + foundobject = dynamic; // potencjalna kolizja + distance = objectposition; // odleglość pomiędzy aktywnymi osiami pojazdów + } + + Distance += distance; // doliczenie odległości przeszkody albo długości odcinka do przeskanowanej odległości + return foundobject; +} diff --git a/vehicle/dynamic/offtrack.cpp b/vehicle/dynamic/offtrack.cpp new file mode 100644 index 000000000..ddd629fba --- /dev/null +++ b/vehicle/dynamic/offtrack.cpp @@ -0,0 +1,504 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// a derailed vehicle off the track, on the ground + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/mover.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + +namespace +{ + + +using ground_triangles = std::vector; + +} // namespace + +bool outside( glm::dvec3 const &Centre, double const Radius, glm::dvec2 const &Min, glm::dvec2 const &Max ) { + return Centre.x + Radius < Min.x || Centre.x - Radius > Max.x || Centre.z + Radius < Min.y || Centre.z - Radius > Max.y; +} +namespace +{ + +void add_triangle( glm::dvec3 const &A, glm::dvec3 const &B, glm::dvec3 const &C, glm::dvec2 const &Min, glm::dvec2 const &Max, ground_triangles &Out ) { + if( std::max( { A.x, B.x, C.x } ) < Min.x || std::min( { A.x, B.x, C.x } ) > Max.x + || std::max( { A.z, B.z, C.z } ) < Min.y || std::min( { A.z, B.z, C.z } ) > Max.y ) { + return; + } + Out.push_back( { A, B, C } ); +} + +// the triangles of a piece of the scenery's geometry within the rectangle (x, z), as the editor gathers the ground +void add_shape( scene::shape_node const &Shape, glm::dvec2 const &Min, glm::dvec2 const &Max, ground_triangles &Out ) { + auto const &data { Shape.data() }; + if( data.area.radius >= 0.f && outside( data.area.center, data.area.radius, Min, Max ) ) { + return; + } + if( false == data.vertices.empty() ) { + for( std::size_t i = 0; i + 2 < data.vertices.size(); i += 3 ) { + add_triangle( data.vertices[ i ].position, data.vertices[ i + 1 ].position, data.vertices[ i + 2 ].position, Min, Max, Out ); + } + return; + } + // once the shape is uploaded its world-space source is released; the renderer keeps an origin-relative copy + if( data.geometry.bank == 0 && data.geometry.chunk == 0 ) { + return; + } + auto const &vertices { GfxRenderer->Vertices( data.geometry ) }; + auto const &indices { GfxRenderer->Indices( data.geometry ) }; + auto const point = [ &data, &vertices ]( std::size_t const Index ) { return data.origin + glm::dvec3 { vertices[ Index ].position }; }; + if( indices.empty() ) { + for( std::size_t i = 0; i + 2 < vertices.size(); i += 3 ) { + add_triangle( point( i ), point( i + 1 ), point( i + 2 ), Min, Max, Out ); + } + return; + } + for( std::size_t i = 0; i + 2 < indices.size(); i += 3 ) { + if( std::max( { indices[ i ], indices[ i + 1 ], indices[ i + 2 ] } ) >= vertices.size() ) { + continue; + } + add_triangle( point( indices[ i ] ), point( indices[ i + 1 ] ), point( indices[ i + 2 ] ), Min, Max, Out ); + } +} + +// the ground of the scenery within the rectangle (x, z): its terrain and the other opaque geometry of its sections, +// and the heightmap terrain where it is loaded. the models aren't ground +ground_triangles scenery_ground( glm::dvec2 const &Min, glm::dvec2 const &Max ) { + ground_triangles triangles; + if( simulation::Region == nullptr ) { + return triangles; + } + auto const centre { 0.5 * ( Min + Max ) }; + std::vector sections; + simulation::Region->sections( glm::dvec3 { centre.x, 0.0, centre.y }, static_cast( 0.5 * glm::length( Max - Min ) ), sections ); + for( auto const *section : sections ) { + for( auto const &shape : section->m_shapes ) { + add_shape( shape, Min, Max, triangles ); + } + for( auto const &cell : section->m_cells ) { + if( outside( cell.m_area.center, cell.m_area.radius, Min, Max ) ) { + continue; + } + for( auto const &shape : cell.m_shapesopaque ) { + add_shape( shape, Min, Max, triangles ); + } + } + } + if( EditorTerrain.active() ) { + EditorTerrain.gather_triangles( Min, Max, triangles ); + } + return triangles; +} + +glm::dvec3 level_left_of( glm::dvec3 const &Front ) { + return glm::dvec3 { Front.z, 0.0, -Front.x }; +} + +// the end of the vehicle where it meets the one coupled to it: the middle of its buffer beam, the way it faces. off the +// track, over its base on the ground as it stands: rolled over, its ends go with it as far as the coupling holds them, +// and the buffers of the side it rolled to miss those of an upright one +derail_motion::end_point end_point_of( TDynamicObject const &Vehicle, int const End ) { + auto const facing { End == end::front ? 1.0 : -1.0 }; + auto const &motion { Vehicle.MoverParameters->OffTrack }; + glm::dvec3 const front { Vehicle.VectorFront().x, 0.0, Vehicle.VectorFront().z }; + auto const length { glm::length( front ) }; + auto const axis { length > 1e-6 ? front / length : glm::dvec3 { 0.0, 0.0, 1.0 } }; + auto const middle { motion.active() ? motion.base() : Vehicle.GetPosition() }; + return derail_motion::end_point { + middle + glm::dvec3 { 0.0, derail_motion::buffer_height, 0.0 } + axis * ( facing * 0.5 * Vehicle.MoverParameters->Dim.L ), + axis * facing, + motion.active() ? motion.tipping() : 0.0 }; +} + +// the push of the buffers on the end of the vehicle [N], negative the pull of its coupling +double compression_of( TMoverParameters const &Vehicle, int const End ) { + return ( End == end::front ? -1.0 : 1.0 ) * Vehicle.Couplers[ End ].CForce; +} + +} // namespace + +double seconds_since( off_track_clock::time_point const Start ) { + return std::chrono::duration( off_track_clock::now() - Start ).count(); +} +namespace +{ + +std::string_view side_name( int const Side ) { + if( Side > 0 ) { + return "left"; + } + return Side < 0 ? "right" : "none"; +} + +} // namespace + +double TDynamicObject::off_track_gap( int const End ) const { + + auto const *neighbour { MoverParameters->Neighbours[ End ].vehicle }; + if( neighbour == nullptr ) { + return 0.0; + } + return derail_motion::meet( end_point_of( *this, End ), end_point_of( *neighbour, MoverParameters->Neighbours[ End ].vehicle_end ) ).gap; +} + +double TDynamicObject::off_track_offset() const { + + if( false == MoverParameters->OffTrack.active() ) { + return 0.0; + } + auto const middle { 0.5 * ( Axle0.pPosition + Axle1.pPosition ) }; + auto const offset { vPosition - middle }; + return glm::dot( glm::dvec3 { offset.x, 0.0, offset.z }, level_left_of( track_front() ) ); +} + +glm::dvec3 TDynamicObject::track_front() const { + + auto const along { Axle0.pPosition - Axle1.pPosition }; + glm::dvec3 const flat { along.x, 0.0, along.z }; + auto const length { glm::length( flat ) }; + return length > 1e-6 ? flat / length : glm::dvec3 { 0.0, 0.0, 1.0 }; +} + +derail_motion::formation TDynamicObject::track_bed() const { + + derail_motion::formation bed; + bed.point = 0.5 * ( Axle0.pPosition + Axle1.pPosition ); + bed.direction = track_front(); + if( auto const *track { RaTrackGet() }; track != nullptr ) { + // the ballast out of the rails, as wide as the track draws it + bed.half_width = std::clamp( 0.5 * std::abs( track->fTrackWidth ) + std::abs( track->fTexWidth ), 1.2, 3.5 ); + } + return bed; +} + +int TDynamicObject::outward_side() const { + + // the track as designed turns from the rear axle to the front one: the outside of its curve, or its inside where a + // buckle bends the line the other way more than the curve does (the criteria of derailment, physics/derailment.h) + if( auto const design { std::sin( Axle1.vAngles.z - Axle0.vAngles.z ) }; std::abs( design ) >= 1e-4 ) { + auto const outside { design > 0.0 ? -1 : 1 }; + return MoverParameters->DerailAcceleration < 0.0 ? -outside : outside; + } + // a straight track: the path under the vehicle as it is, a buckle on it, turns from the rear axle to the front one + auto const front { Axle0.PathDirection() }; + auto const rear { Axle1.PathDirection() }; + auto const turn { glm::dot( front, level_left_of( rear ) ) }; + // a turn under a tenth of a milliradian is a straight track + if( std::abs( turn ) < 1e-4 ) { + return 0; + } + // turning left, the outside of the curve is on the right + return turn > 0.0 ? -1 : 1; +} + +void TDynamicObject::gather_off_track_terrain() { + + auto const &mover { *MoverParameters }; + auto const &position { mover.OffTrack.active() ? mover.OffTrack.current().position : vPosition }; + // as far as it may slide, and some + auto const slide { derail_motion::stopping_distance( mover.V, derailment::off_rails_friction ).value_or( 0.0 ) }; + auto const reach { std::min( slide + mover.Dim.L + 50.0, 600.0 ) }; + m_offtrackgathered = m_offtracktotal; + m_offtrackcropped = false; + // the terrain of another vehicle, where it covers the way this one goes: around it and around where it stops going + // straight on, by its length and the margin the terrain is gathered again at + glm::dvec3 heading { vFront.x, 0.0, vFront.z }; + if( mover.OffTrack.active() ) { + heading = mover.OffTrack.heading(); + } + auto const length { glm::length( heading ) }; + auto const stop { length > 1e-6 ? position + heading * ( std::copysign( std::max( reach - mover.Dim.L - 50.0, 0.0 ), mover.V ) / length ) : position }; + auto const margin { mover.Dim.L + 30.0 }; + if( auto shared { simulation::Vehicles.off_track_terrain( + glm::dvec2 { std::min( position.x, stop.x ) - margin, std::min( position.z, stop.z ) - margin }, + glm::dvec2 { std::max( position.x, stop.x ) + margin, std::max( position.z, stop.z ) + margin } ) }; + shared != nullptr ) { + m_offtrackterrain = std::move( shared ); + m_offtrackmin = m_offtrackterrain->minimum(); + m_offtrackmax = m_offtrackterrain->maximum(); + m_offtracksite.terrain( m_offtrackterrain.get() ); + return; + } + m_offtrackmin = glm::dvec2 { position.x - reach, position.z - reach }; + m_offtrackmax = glm::dvec2 { position.x + reach, position.z + reach }; + auto const started { off_track_clock::now() }; + auto triangles { scenery_ground( m_offtrackmin, m_offtrackmax ) }; + auto const trimmed { triangles.size() > off_track_triangles }; + if( trimmed ) { + // a scenery dense enough to make it slow: the triangles nearest to it are enough + std::nth_element( triangles.begin(), triangles.begin() + off_track_triangles, triangles.end(), + [ &position ]( auto const &Left, auto const &Right ) { + auto const distance = [ &position ]( auto const &Triangle ) { + auto const middle { ( Triangle[ 0 ] + Triangle[ 1 ] + Triangle[ 2 ] ) / 3.0 }; + return std::max( std::abs( middle.x - position.x ), std::abs( middle.z - position.z ) ); }; + return distance( Left ) < distance( Right ); } ); + triangles.resize( off_track_triangles ); + ErrorLog( std::format( "derailment: warning: {} found more than {} triangles of terrain around it, took the nearest", MoverParameters->Name, off_track_triangles ) ); + } + if( triangles.empty() ) { + // a scenery without terrain: level with the top of the ballast + m_offtrackterrain.reset(); + } + else { + m_offtrackterrain = std::make_shared( triangles, m_offtrackmin, m_offtrackmax ); + // the vehicles sliding over it take it as it is; the nearest triangles of a dense scenery are its own + if( false == trimmed ) { + simulation::Vehicles.share_off_track_terrain( m_offtrackterrain ); + } + } + m_offtracksite.terrain( m_offtrackterrain.get() ); + auto const took { seconds_since( started ) }; + if( took > off_track_slow ) { + ErrorLog( std::format( "derailment: warning: gathering the terrain of {:.0f} m around {} took {:.0f} ms ({} triangles)", reach, MoverParameters->Name, took * 1000.0, triangles.size() ) ); + } +} + +void TDynamicObject::crop_off_track_terrain() { + + if( m_offtrackcropped || m_offtrackterrain == nullptr ) { + return; + } + m_offtrackcropped = true; + // the ground under it, and as far around as it gathers the terrain anew once it moves again + auto const &position { MoverParameters->OffTrack.current().position }; + auto const reach { 0.5 * MoverParameters->Dim.L + 40.0 }; + m_offtrackmin = glm::dvec2 { position.x - reach, position.z - reach }; + m_offtrackmax = glm::dvec2 { position.x + reach, position.z + reach }; + m_offtrackterrain = std::make_shared( m_offtrackterrain->cropped( m_offtrackmin, m_offtrackmax ) ); + m_offtracksite.terrain( m_offtrackterrain.get() ); +} + +void TDynamicObject::begin_off_track() { + + auto &mover { *MoverParameters }; + derail_motion::vehicle_shape shape; + shape.length = mover.Dim.L; + shape.width = mover.Dim.W > 0.5 ? mover.Dim.W : 3.0; + // a height up to 2 m in the definition is the height of the floor, the older meaning of the key + shape.height = mover.Dim.H > 2.0 ? mover.Dim.H : 4.0; + shape.centre_of_gravity = mover.centre_of_gravity(); + shape.contact_spacing = derailment::contact_spacing( mover.TrackW ); + shape.base = std::max( static_cast( fAxleDist ), 1.0 ); + shape.mass = mover.TotalMass; + + derail_motion::start start; + start.position = vPosition; + start.front = vFront; + start.line = track_front(); + start.speed = mover.V; + start.reason = mover.DerailCause; + start.outward = ( mover.DerailSide != 0 ? mover.DerailSide : outward_side() ); + start.acceleration = mover.DerailAcceleration; + + // the terrain as far as it may slide, and some + m_offtracktotal = 0.0; + gather_off_track_terrain(); + m_offtracksite = derail_motion::site { m_offtrackterrain.get(), track_bed() }; + // each vehicle its own way of going off, from the seed of the run (the same seed, the same way) + auto const scatter { derail_motion::draw_scatter( derail_motion::seed_of( Global.random_seed, mover.Name ) ) }; + mover.OffTrack.begin( start, shape, m_offtracksite, scatter ); + m_pulledoff = {}; + m_offtracklogdue = 0.0; + m_offtrackslowdue = 0.0; + m_offtrackaxles = 0.0; + m_offtrackfrom = mover.OffTrack.current().position; + + auto const heading { mover.OffTrack.heading() }; + auto const front { glm::dvec3 { vFront.x, 0.0, vFront.z } }; + auto const turn { std::asin( std::clamp( glm::dot( heading, level_left_of( glm::normalize( front ) ) ), -1.0, 1.0 ) ) }; + std::string terrain { "no terrain, level ground" }; + if( m_offtrackterrain != nullptr ) { + terrain = std::format( "{} triangles of terrain", m_offtrackterrain->size() ); + } + WriteLog( std::format( + "derailment: {} leaves the track at {:.0f} km/h on track {}, heading turned {:.1f} deg to the {}, the outside of the curve to the {}; {} around it", + mover.Name, std::abs( mover.V ) * 3.6, MyTrack != nullptr ? MyTrack->name() : std::string { "(none)" }, + std::abs( glm::degrees( turn ) ), side_name( turn >= 0.0 ? 1 : -1 ), side_name( start.outward ), terrain ) ); + WriteLog( std::format( + "derailment: {} scattered by {:+.2f} deg of departure, {:+.2f} deg of yaw at {:+.3f} rad/s, the friction under its ends x{:.2f} / x{:.2f}{}", + mover.Name, glm::degrees( scatter.departure ), glm::degrees( scatter.yaw ), scatter.yaw_rate, scatter.friction_front, scatter.friction_rear, + scatter.dig_in >= 0.0 ? std::format( ", its leading end digs in after {:.2f} s, x{:.2f} for {:.2f} s", scatter.dig_in, scatter.dig_in_friction, scatter.dig_in_time ) : std::string {} ) ); +} + +void TDynamicObject::move_off_track( double const Distance ) { + + auto const started { off_track_clock::now() }; + auto &motion { MoverParameters->OffTrack }; + auto const time { std::exchange( m_offtracktime, 0.0 ) }; + m_offtracktotal += time; + // near the edge of the terrain gathered, the terrain further on; not more than once a second, whatever happens + if( m_offtrackterrain != nullptr && Distance != 0.0 && m_offtracktotal - m_offtrackgathered >= 1.0 ) { + auto const &position { motion.current().position }; + constexpr double margin { 30.0 }; + if( position.x - margin < m_offtrackmin.x || position.x + margin > m_offtrackmax.x + || position.z - margin < m_offtrackmin.y || position.z + margin > m_offtrackmax.y ) { + gather_off_track_terrain(); + } + } + m_offtracksite.bed( track_bed() ); + // the buffers and the couplings of its ends push and pull it, at an angle to it where the vehicle coupled there is + std::array ends {}; + for( int end = end::front; end <= end::rear; ++end ) { + auto const *neighbour { MoverParameters->Neighbours[ end ].vehicle }; + auto const compression { compression_of( *MoverParameters, end ) }; + if( neighbour == nullptr || compression == 0.0 ) { + continue; + } + ends[ end ] = derail_motion::force_on( + derail_motion::meet( end_point_of( *this, end ), end_point_of( *neighbour, MoverParameters->Neighbours[ end ].vehicle_end ) ), compression ); + } + auto const reversals { motion.reversals() }; + motion.step( time, Distance, MoverParameters->V, m_offtracksite, ends ); + if( ( motion.reversals() - reversals ) % 2 != 0 ) { + // the body turned about against the way it goes: the vehicle goes rear first, its speed the other way along it + MoverParameters->V = -MoverParameters->V; + } + auto const &pose { motion.current() }; + // the axles go along the track as far as the vehicle went along it, for the track nearest to it: the vehicles on it + // find it there, the events of the track are passed. by 10 cm at least: a body turning or rocking in place moves + // the axles back and forth by millimetres, which over the end of a track would fire its events every frame. from + // where it was the last time, so the moves out of the other bodies between the frames go into the axles too + m_offtrackaxles += glm::dot( pose.position - std::exchange( m_offtrackfrom, pose.position ), track_front() ); + if( std::abs( m_offtrackaxles ) >= 0.1 ) { + move_axles( std::exchange( m_offtrackaxles, 0.0 ) ); + } + + place_off_track(); + if( motion.at_rest() ) { + crop_off_track_terrain(); + } + + pull_neighbours( Distance ); + + // what it cost: a frame of the vehicle off the track should take well under a millisecond + auto const took { seconds_since( started ) }; + m_offtrackslowdue -= time; + if( took > off_track_slow && m_offtrackslowdue <= 0.0 ) { + m_offtrackslowdue = 1.0; + ErrorLog( std::format( "derailment: warning: moving {} off the track took {:.0f} ms in a frame of {:.3f} s", MoverParameters->Name, took * 1000.0, time ) ); + } +} + +void TDynamicObject::place_off_track() { + + auto const &pose { MoverParameters->OffTrack.current() }; + vPosition = pose.position; + vFront = pose.front; + vLeft = pose.left; + vUp = pose.up; + modelRot.z = std::atan2( -vFront.x, vFront.z ); + mMatrix = glm::inverse( BasisChange( vLeft, vUp, vFront ) ); + auto const half { 0.5 * MoverParameters->Dim.L * vFront }; + vCoulpler[ end::front ] = vPosition + half; + vCoulpler[ end::rear ] = vPosition - half; + m_offtrackplaced = true; +} + +void TDynamicObject::pull_neighbours( double const Distance ) { + + for( int end = end::front; end <= end::rear; ++end ) { + auto const &coupler { MoverParameters->Couplers[ end ] }; + auto *neighbour { MoverParameters->Neighbours[ end ].vehicle }; + if( coupler.CouplingFlag == Coupling::none || neighbour == nullptr || neighbour->MoverParameters->OffTrack.active() + || neighbour->MoverParameters->DamageFlag.HasAll(VehicleDamage::derailed) ) { + m_pulledoff[ end ].reset(); + continue; + } + auto &other { *neighbour->MoverParameters }; + auto const otherend { MoverParameters->Neighbours[ end ].vehicle_end }; + glm::dvec3 const otherfront { neighbour->vFront.x, 0.0, neighbour->vFront.z }; + if( glm::length( otherfront ) < 1e-6 ) { + continue; + } + // the coupling pulls the end of the other vehicle towards the beam of this one, the buffers push it along the + // bisector of the bend between them: at an angle to its axis, the part across it on its leading wheels + auto const compression { compression_of( other, otherend ) }; + auto const force { derail_motion::force_on( derail_motion::meet( end_point_of( *neighbour, otherend ), end_point_of( *this, end ) ), compression ).force }; + auto const axis { glm::normalize( otherfront ) }; + auto const across { glm::dot( force, level_left_of( axis ) ) }; + auto const angle { std::atan2( std::abs( across ), std::abs( glm::dot( force, axis ) ) ) }; + auto const magnitude { glm::length( glm::dvec3 { force.x, 0.0, force.z } ) }; + auto const mass { other.TotalMass - other.Mred }; + auto const ratio { derail_motion::pull_ratio( magnitude, angle, mass, other.NAxles ) }; + if( false == m_pulledoff[ end ].update( ratio >= derailment::climbing_limit, Distance ) ) { + continue; + } + // the way the force across it goes: towards this one pulled, away from it pushed + auto const side { across >= 0.0 ? 1 : -1 }; + other.pull_off( + side, + mass > 0.0 ? std::abs( across ) / mass : 0.0, + std::format( "Y/Q {:.2f} from the {} of {} at {:.0f} deg, {:.0f} kN", ratio, compression > 0.0 ? "buffers" : "coupling", MoverParameters->Name, glm::degrees( angle ), magnitude / 1000.0 ) ); + m_pulledoff[ end ].reset(); + } +} + +void TDynamicObject::update_off_track( double const Deltatime ) { + + auto const &motion { MoverParameters->OffTrack }; + if( false == motion.active() || m_offtracklogdue < 0.0 ) { + // on the track, or came to rest and told so + return; + } + m_offtracklogdue -= Deltatime; + auto const resting { motion.at_rest() }; + if( m_offtracklogdue > 0.0 && false == resting ) { + return; + } + m_offtracklogdue = ( resting ? -1.0 : 1.0 ); + WriteLog( std::format( + "derailment: {} {} {:.1f} m from where it left the rails, {:.1f} m from the axis of the track, at {:.1f} km/h, sliding sideways at {:.1f} m/s, tipped {:.0f} deg, roll {:.0f} deg, yaw {:+.1f} deg turning at {:+.1f} deg/s{}", + MoverParameters->Name, resting ? "came to rest" : "off the track", motion.travelled(), off_track_offset(), std::abs( MoverParameters->V ) * 3.6, motion.sideways(), + glm::degrees( motion.tipping() ), glm::degrees( motion.roll() ), glm::degrees( motion.yaw() ), glm::degrees( motion.yaw_rate() ), motion.lying() ? ", lying on its side" : "" ) ); +} diff --git a/vehicle/dynamic/sounds.cpp b/vehicle/dynamic/sounds.cpp new file mode 100644 index 000000000..fe661e2a4 --- /dev/null +++ b/vehicle/dynamic/sounds.cpp @@ -0,0 +1,1414 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the sounds of a vehicle + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/mover.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + + +// przeliczanie dźwięków, bo będzie słychać bez wyświetlania sektora z pojazdem +void TDynamicObject::RenderSounds() { + + if( false == simulation::is_ready ) { return; } + if( Global.iPause != 0 ) { return; } + + if( m_startjoltplayed + && ( std::abs(MoverParameters->AccSVBased) < 0.01 + || GetVelocity() < 0.01 ) ) { + // if the vehicle comes to a stop set the movement jolt to play when it starts moving again + m_startjoltplayed = false; + } + + auto const dt{ Timer::GetDeltaRenderTime() }; + m_powertrainsounds.render( *MoverParameters, dt ); + + auto volume{ 0.0 }; + auto frequency{ 1.0 }; + + // NBMX dzwiek przetwornicy + if( MoverParameters->ConverterFlag ) { + if( MoverParameters->EngineType == TEngineType::ElectricSeriesMotor ) { + auto const voltage { std::max( MoverParameters->GetTrainsetHighVoltage(), MoverParameters->PantographVoltage ) }; + if( voltage > 0.0 ) { + // NOTE: we do sound modulation here to avoid sudden jump on voltage loss + frequency = voltage / (MoverParameters->NominalVoltage * MoverParameters->RList[MoverParameters->RlistSize].Mn); + frequency *= sConverter.m_frequencyfactor + sConverter.m_frequencyoffset; + sConverter.pitch( std::clamp( frequency, 0.75, 1.25 ) ); // arbitrary limits ) + } + } + else { + frequency = sConverter.m_frequencyoffset + sConverter.m_frequencyfactor * frequency; + sConverter.pitch( std::clamp( frequency, 0.75, 1.25 ) ); // arbitrary limits ) + } + sConverter.play( sound_flags::exclusive | sound_flags::looping ); + } + else { + sConverter.stop(); + } + + // Odtworzenie dzwieku wentylatora rezystora hamowania + + if (MoverParameters->BRVentilators) + { + sBRVent.play(sound_flags::exclusive | sound_flags::looping); + } + else + { + sBRVent.stop(); + } + + + + + + if( MoverParameters->CompressorSpeed > 0.0 ) { + // McZapkie! - dzwiek compressor.wav tylko gdy dziala sprezarka + if( MoverParameters->CompressorFlag ) { + // for compressor coupled with the diesel engine sound pitch is driven by engine revolutions + if( MoverParameters->CompressorPower == 3 ) { + // presume the compressor sound is recorded for idle revolutions + // increase the pitch according to increase of engine revolutions + auto const enginefactor { + std::clamp( // try to keep the sound pitch in semi-reasonable range + MoverParameters->EngineMaxRPM() / MoverParameters->EngineIdleRPM() * MoverParameters->EngineRPMRatio(), + 0.5, 2.5 ) }; + sCompressor.pitch( enginefactor ); + sCompressorIdle.pitch( enginefactor ); + } + if( sCompressorIdle.empty() ) { + // legacy sound path, if there's no dedicated idle sound + sCompressor.play( sound_flags::exclusive | sound_flags::looping ); + } + else { + // enhanced sound path, with dedicated sound for idling compressor + if( MoverParameters->CompressorGovernorLock ) { + sCompressor.stop(); + sCompressorIdle.play( sound_flags::exclusive | sound_flags::looping ); + } + else { + sCompressor.play( sound_flags::exclusive | sound_flags::looping ); + sCompressorIdle.stop(); + } + } + } + else { + sCompressor.stop(); + sCompressorIdle.stop(); + } + } + + // Winger 160404 - dzwiek malej sprezarki + if( MoverParameters->PantCompFlag ) { + sSmallCompressor.play( sound_flags::exclusive | sound_flags::looping ); + } + else { + sSmallCompressor.stop(); + } + + // heater sound + { + auto const isdieselenginepowered { MoverParameters->EngineType == TEngineType::DieselElectric || MoverParameters->EngineType == TEngineType::DieselEngine }; + if( true == MoverParameters->Heating + && ( false == isdieselenginepowered + || std::abs(MoverParameters->enrot) > 0.01 ) ) { + sHeater + .pitch( true == sHeater.is_combined() ? + std::abs( MoverParameters->enrot ) * 60.f * 0.01f : + 1.f ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + sHeater.stop(); + } + } + + // battery sound + if( MoverParameters->Battery ) { + m_batterysound.play( sound_flags::exclusive | sound_flags::looping ); + } + else { + m_batterysound.stop(); + } + + // brake system and braking sounds: + + // brake cylinder piston + auto const brakepressureratio { std::max( 0.0, MoverParameters->BrakePress ) / std::max( 1.0, MoverParameters->MaxBrakePress[ 3 ] ) }; + if( m_lastbrakepressure != -1.f ) { + // HACK: potentially reset playback of opening bookend sounds + if( false == m_brakecylinderpistonadvance.is_playing() ) { + m_brakecylinderpistonadvance.stop(); + } + if( false == m_brakecylinderpistonrecede.is_playing() ) { + m_brakecylinderpistonrecede.stop(); + } + // actual sound playback + auto const quantizedratio { static_cast( 15 * brakepressureratio ) }; + auto const lastbrakepressureratio { std::max( 0.f, m_lastbrakepressure ) / std::max( 1.0, MoverParameters->MaxBrakePress[ 3 ] ) }; + auto const quantizedratiochange { quantizedratio - static_cast( 15 * lastbrakepressureratio ) }; + if( quantizedratiochange > 0 ) { + m_brakecylinderpistonadvance + .pitch( + true == m_brakecylinderpistonadvance.is_combined() ? + quantizedratio * 0.01f : + m_brakecylinderpistonadvance.m_frequencyoffset + m_brakecylinderpistonadvance.m_frequencyfactor * 1.f ) + .play(); + } + else if( quantizedratiochange < 0 ) { + m_brakecylinderpistonrecede + .pitch( true == m_brakecylinderpistonrecede.is_combined() ? + quantizedratio * 0.01f : + m_brakecylinderpistonrecede.m_frequencyoffset + m_brakecylinderpistonrecede.m_frequencyfactor * 1.f ) + .play(); + } + } + + // epbrake - epcompact + if (MoverParameters->BrakeSystem == TBrakeSystem::ElectroPneumatic && MoverParameters->LocHandle) { + auto const epbrakepressureratio{ std::min( std::max( 0.0, MoverParameters->LocHandle->GetCP() ) / std::max( 1.0, MoverParameters->MaxBrakePress[0] ), + m_epbrakepressurechangedectimer > -1.0f ? + std::max( MoverParameters->LocalBrakePosAEIM, MoverParameters->Hamulec->GetEDBCP() / MoverParameters->MaxBrakePress[3]) : + 1.0 ) }; + if ( m_lastepbrakepressure != -1.f ) { + // HACK: potentially reset playback of opening bookend sounds + if ( false == m_epbrakepressureincrease.is_playing() ) { + m_epbrakepressureincrease.stop(); + } + if ( false == m_epbrakepressuredecrease.is_playing() ) { + m_epbrakepressuredecrease.stop(); + } + m_epbrakepressurechangeinctimer += dt; + m_epbrakepressurechangedectimer += dt; + // actual sound playback + auto const epquantizedratio{ static_cast( 50 * epbrakepressureratio) }; + auto const lastepbrakepressureratio { std::max( 0.f, m_lastepbrakepressure ) / std::max( 1.0, MoverParameters->MaxBrakePress[0] ) }; + auto const epquantizedratiochange { epquantizedratio - static_cast( 50 * lastepbrakepressureratio ) }; + if ( epquantizedratiochange > 0 && m_epbrakepressurechangeinctimer > 0.05f) { + m_epbrakepressureincrease + .pitch( + true == m_epbrakepressureincrease.is_combined() ? + epquantizedratio * 0.01f : + m_epbrakepressureincrease.m_frequencyoffset + m_epbrakepressureincrease.m_frequencyfactor * 1.f ) + .play(); + m_epbrakepressurechangeinctimer = 0; + } + else if ( epquantizedratiochange < 0 && m_epbrakepressurechangedectimer > 0.3f) { + m_epbrakepressuredecrease + .pitch(true == m_epbrakepressuredecrease.is_combined() ? + -epquantizedratiochange * 0.01f : + m_epbrakepressuredecrease.m_frequencyoffset + m_epbrakepressuredecrease.m_frequencyfactor * 1.f ) + .play(); + m_epbrakepressurechangedectimer = 0; + } + } + if ( m_epbrakepressurechangeinctimer == 0 || m_epbrakepressurechangedectimer == 0 ) + m_lastepbrakepressure = std::min( MoverParameters->LocHandle->GetCP(), + MoverParameters->LocalBrakePosAEIM * std::max( 1.0, MoverParameters->MaxBrakePress[0] ) ); + } + + // emergency brake + if( MoverParameters->EmergencyValveFlow > 0.025 ) { + // smooth out air flow rate + m_emergencybrakeflow = m_emergencybrakeflow == 0.0 ? MoverParameters->EmergencyValveFlow : std::lerp(m_emergencybrakeflow, MoverParameters->EmergencyValveFlow, 0.1); + // scale volume based on the flow rate and on the pressure in the main pipe + auto const flowpressure { std::clamp( m_emergencybrakeflow, 0.0, 1.0 ) + std::clamp( 0.1 * MoverParameters->PipePress, 0.0, 0.5 ) }; + m_emergencybrake + .pitch( m_emergencybrake.m_frequencyoffset + 1.0 * m_emergencybrake.m_frequencyfactor ) + .gain( m_emergencybrake.m_amplitudeoffset + std::clamp( flowpressure, 0.0, 1.0 ) * m_emergencybrake.m_amplitudefactor ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else if( MoverParameters->EmergencyValveFlow < 0.015 ) { + m_emergencybrakeflow = 0.0; + m_emergencybrake.stop(); + } + + // air release + if( m_lastbrakepressure != -1.f ) { + // calculate rate of pressure drop in brake cylinder, once it's been initialized + auto const brakepressuredifference{ m_lastbrakepressure - MoverParameters->BrakePress }; + m_brakepressurechange = std::lerp( m_brakepressurechange, brakepressuredifference / dt, 0.05f ); + } + m_lastbrakepressure = MoverParameters->BrakePress; + // ensure some basic level of volume and scale it up depending on pressure in the cylinder; scale this by the air release rate + volume = rsUnbrake.m_amplitudefactor * m_brakepressurechange * ( 0.25 + 0.75 * brakepressureratio ); + if( m_brakepressurechange > 0.05 && brakepressureratio > 0.05 ) { + rsUnbrake + .gain( volume ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + // don't stop the sound too abruptly + volume = std::max( 0.0, rsUnbrake.gain() - 0.5 * dt ); + rsUnbrake.gain( volume ); + if( volume < 0.05 ) { + rsUnbrake.stop(); + } + } + + // Dzwiek odluzniacza + if( MoverParameters->Hamulec->Releaser() ) { + sReleaser + .gain( + std::clamp( + MoverParameters->BrakePress * 1.25, // arbitrary multiplier + 0., 1. ) ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + sReleaser.stop(); + } + + // slipping wheels + if( MoverParameters->SlippingWheels ) { + + if( MoverParameters->UnitBrakeForce > 100.0 + && GetVelocity() > 1.0 ) { + + auto const velocitydifference{ GetVelocity() / MoverParameters->Vmax }; + rsSlippery + .gain( rsSlippery.m_amplitudeoffset + rsSlippery.m_amplitudefactor * velocitydifference ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + } + else { + rsSlippery.stop(); + } + + // Dzwiek piasecznicy + if( MoverParameters->SandDose ) { + sSand.play( sound_flags::exclusive | sound_flags::looping ); + } + else { + sSand.stop(); + } + + // brakes + auto brakeforceratio{ 0.0 }; + if( //( false == mvOccupied->SlippingWheels ) && + MoverParameters->UnitBrakeForce > 10.0 + && MoverParameters->Vel > 0.05 ) { + + brakeforceratio = + std::clamp( + MoverParameters->UnitBrakeForce / std::max( 1.0, MoverParameters->BrakeForceR( 1.0, MoverParameters->Vel ) / ( MoverParameters->NAxles * std::max( 1, MoverParameters->NBpA ) ) ), + 0.0, 1.0 ); + rsBrake + .pitch( rsBrake.m_frequencyoffset + MoverParameters->Vel * rsBrake.m_frequencyfactor ) + .gain( rsBrake.m_amplitudeoffset + std::sqrt( brakeforceratio * std::lerp( 0.4, 1.0, MoverParameters->Vel / (1 + MoverParameters->Vmax) ) ) * rsBrake.m_amplitudefactor ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + rsBrake.stop(); + } + + // yB: przyspieszacz (moze zadziala, ale dzwiek juz jest) + if( true == bBrakeAcc ) { + if( true == TestFlag( MoverParameters->Hamulec->GetSoundFlag(), sf_Acc ) ) { + sBrakeAcc.play( sound_flags::exclusive ); + } + } + + // McZapkie-280302 - pisk mocno zacisnietych hamulcow + if( MoverParameters->Vel > 2.5 ) { + + volume = rsPisk.m_amplitudeoffset + std::lerp( -1.0, 1.0, brakeforceratio ) * rsPisk.m_amplitudefactor; + if( volume > 0.075 ) { + rsPisk + .pitch( + true == rsPisk.is_combined() ? + MoverParameters->Vel * 0.01f : + rsPisk.m_frequencyoffset + rsPisk.m_frequencyfactor * 1.f ) + .gain( volume ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + } + else { + // don't stop the sound too abruptly + volume = std::max( 0.0, rsPisk.gain() - rsPisk.gain() * 2.5 * dt ); + rsPisk.gain( volume ); + } + if( volume < 0.05 ) { + rsPisk.stop(); + } + + // spring brake + if( m_springbrakesounds.state != MoverParameters->SpringBrake.Activate ) { + m_springbrakesounds.state = MoverParameters->SpringBrake.Activate; + if( m_springbrakesounds.state ) { + m_springbrakesounds.activate.play( sound_flags::exclusive ); + m_springbrakesounds.release.stop(); + } + else { + m_springbrakesounds.activate.stop(); + m_springbrakesounds.release.play( sound_flags::exclusive ); + } + } + + // other sounds + // load exchange + if( MoverParameters->LoadStatus & 1 ) { + m_exchangesounds.unloading.play( sound_flags::exclusive ); + } + else { + m_exchangesounds.unloading.stop(); + } + if( MoverParameters->LoadStatus & 2 ) { + m_exchangesounds.loading.play( sound_flags::exclusive ); + } + else { + m_exchangesounds.loading.stop(); + } + // NBMX sygnal odjazdu + if( MoverParameters->Doors.has_warning ) { + auto const lowvoltagepower { MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable }; + for( auto &doorspeaker : m_doorspeakers ) { + // TBD, TODO: per-location door state triggers? + if( MoverParameters->DepartureSignal + && lowvoltagepower +/* + || ( ( MoverParameters->DoorCloseCtrl = control::autonomous ) + && ( ( ( false == MoverParameters->DoorLeftOpened ) && ( dDoorMoveL > 0.0 ) ) + || ( ( false == MoverParameters->DoorRightOpened ) && ( dDoorMoveR > 0.0 ) ) ) ) +*/ + ) { + // for the autonomous doors play the warning automatically whenever a door is closing + // MC: pod warunkiem ze jest zdefiniowane w chk + doorspeaker.departure_signal.play( sound_flags::exclusive | sound_flags::looping ); + } + else { + doorspeaker.departure_signal.stop(); + } + } + } + // announcements + { + auto const lowvoltagepower { MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable }; + if( lowvoltagepower ) { + // system is powered up, can play queued announcements + if( false == m_pasystem.announcement_queue.empty() + && false == m_pasystem.announcement.is_playing() ) { + // pull first sound from the queue + m_pasystem.announcement = m_pasystem.announcement_queue.front(); + m_pasystem.announcement.owner( this ); + m_pasystem.announcement.range( 0.5 * MoverParameters->Dim.L * -1 ); + if( m_pasystem.soundproofing ) { + if( !m_pasystem.announcement.soundproofing() ) { + m_pasystem.announcement.soundproofing() = m_pasystem.soundproofing; + } + } + m_pasystem.announcement.play(); + m_pasystem.announcement_queue.pop_front(); + } + } + else { + m_pasystem.announcement.stop(); + m_pasystem.announcement_queue.clear(); + } + } + // NBMX Obsluga drzwi, MC: zuniwersalnione + std::array const sides { side::right, side::left }; + for( auto const side : sides ) { + + auto const &door { MoverParameters->Doors.instances[ side ] }; + + if( true == door.is_opening ) { + // door sounds + if( false == door.step_unfolding // no wait if no doorstep + || MoverParameters->Doors.step_type == 2 ) { // no wait for rotating doorstep + if( door.position < 0.5f ) { // safety measure, to keep slightly too short sounds from repeating + for( auto &doorsounds : m_doorsounds ) { + if( doorsounds.placement == side ) { + // determine left side doors from their offset + doorsounds.rsDoorOpen.play( sound_flags::exclusive ); + doorsounds.rsDoorClose.stop(); + } + } + } + } + } + if( true == door.is_closing ) { + // door sounds can start playing before the door begins moving but shouldn't cease once the door closes + if( door.position > 0.f ) { + for( auto &doorsounds : m_doorsounds ) { + if( doorsounds.placement == side ) { + // determine left side doors from their offset + doorsounds.rsDoorClose.play( sound_flags::exclusive ); + doorsounds.rsDoorOpen.stop(); + } + } + } + } + // doorstep sounds + if( door.step_unfolding ) { + for( auto &doorsounds : m_doorsounds ) { + if( doorsounds.placement == side ) { + doorsounds.step_open.play( sound_flags::exclusive ); + doorsounds.step_close.stop(); + } + } + } + if( door.step_folding ) { + if( door.step_position < 1.0f ) { // sanity check, the vehicles may keep the doorstep unfolded until the door close + for( auto &doorsounds : m_doorsounds ) { + if( doorsounds.placement == side ) { + // determine left side doors from their offset + doorsounds.step_close.play( sound_flags::exclusive ); + doorsounds.step_open.stop(); + } + } + } + } + } + // door locks + if( MoverParameters->Doors.is_locked != m_doorlocks ) { + // toggle state of the locks... + m_doorlocks = !m_doorlocks; + // ...and play relevant sounds + for( auto &door : m_doorsounds ) { + if( m_doorlocks ) { + door.lock.play( sound_flags::exclusive ); + } + else { + door.unlock.play( sound_flags::exclusive ); + } + } + } + + // horns + { + // for moving vehicle combine regular horn activation flag with emergency brake horn activation flag, if the brake is active; + // the horns without the air or the voltage they need stay silent + auto const warningsignal { MoverParameters->SoundingHorns( + ( MoverParameters->Vel > 0.5 && MoverParameters->AlarmChainFlag ? + MoverParameters->EmergencyBrakeWarningSignal : + 0 ) + | MoverParameters->WarningSignal ) }; + + if( TestFlag( warningsignal, 1 ) ) { + sHorn1.play( sound_flags::exclusive | sound_flags::looping ); + } + else { + sHorn1.stop(); + } + if( TestFlag( warningsignal, 2 ) ) { + sHorn2.play( sound_flags::exclusive | sound_flags::looping ); + } + else { + sHorn2.stop(); + } + if( TestFlag( warningsignal, 4 ) ) { + sHorn3.play( sound_flags::exclusive | sound_flags::looping ); + } + else { + sHorn3.stop(); + } + } + // szum w czasie jazdy + if( GetVelocity() > 0.5 +#ifdef EU07_SOUND_BOGIESOUNDS + && false == m_bogiesounds.empty() +#endif + && ( // compound test whether the vehicle belongs to user-driven consist (as these don't emit outer noise in cab view) + FreeFlyModeFlag ? true : // in external view all vehicles emit outer noise + simulation::Train == nullptr ? true : // no player train, e.g. it went through a portal and the view isn't switched yet + ctOwner == nullptr ? true : // standalone vehicle, can't be part of user-driven train + ctOwner != simulation::Train->Dynamic()->ctOwner ? true : // confirmed isn't a part of the user-driven train + Global.CabWindowOpen ? true : // sticking head out we get to hear outer noise + false ) ) { +#ifdef EU07_SOUND_BOGIESOUNDS + auto const &bogiesound { m_bogiesounds.front() }; +#else + auto const &bogiesound { m_outernoise }; +#endif + // frequency calculation + auto const normalizer { ( + true == bogiesound.is_combined() ? + MoverParameters->Vmax * 0.01f : + 1.f ) }; + frequency = + bogiesound.m_frequencyoffset + + bogiesound.m_frequencyfactor * MoverParameters->Vel * normalizer; + + // volume calculation + volume = + bogiesound.m_amplitudeoffset + + bogiesound.m_amplitudefactor * MoverParameters->Vel; + if( brakeforceratio > 0.0 ) { + // hamulce wzmagaja halas + volume *= 1 + 0.125 * brakeforceratio; + } + // scale volume by track quality + // TODO: track quality and/or environment factors as separate subroutine + volume *= + std::lerp( + 0.8, 1.2, + std::clamp( + MyTrack->iQualityFlag / 20.0, + 0.0, 1.0 ) ); + // for single sample sounds muffle the playback at low speeds + if( false == bogiesound.is_combined() ) { + volume *= + std::lerp( + 0.0, 1.0, + std::clamp( + MoverParameters->Vel / 40.0, + 0.0, 1.0 ) ); + } + switch( MyTrack->eEnvironment ) { + case e_tunnel: { + volume *= 1.3; + break; + } + case e_bridge: { + volume *= 1.5; + break; + } + default: { + break; + } + } + + if( volume > 0.05 ) { + // apply calculated parameters to all motor instances +#ifdef EU07_SOUND_BOGIESOUNDS + for( auto &bogiesound : m_bogiesounds ) { + bogiesound + .pitch( frequency ) // arbitrary limits to prevent the pitch going out of whack + .gain( volume ) + .play( sound_flags::exclusive | sound_flags::looping ); + } +#else + m_outernoise + .pitch( frequency ) // arbitrary limits to prevent the pitch going out of whack + .gain( volume ) + .play( sound_flags::exclusive | sound_flags::looping ); +#endif + } + else { + // stop all noise instances +#ifdef EU07_SOUND_BOGIESOUNDS + for( auto &bogiesound : m_bogiesounds ) { + bogiesound.stop(); + } +#else + m_outernoise.stop(); +#endif + } + } + else { + // don't play the optional ending sound if the listener switches views +#ifdef EU07_SOUND_BOGIESOUNDS + for( auto &bogiesound : m_bogiesounds ) { + bogiesound.stop( false == FreeFlyModeFlag ); + } +#else + m_outernoise.stop( false == FreeFlyModeFlag ); +#endif + } + // flat spot sound + if( MoverParameters->CategoryFlag == 1 ) { + // trains only + if( GetVelocity() > 1.0 + && MoverParameters->WheelFlat > 5.0 ) { + m_wheelflat + .pitch( m_wheelflat.m_frequencyoffset + std::abs( MoverParameters->nrot ) * m_wheelflat.m_frequencyfactor ) + .gain( m_wheelflat.m_amplitudeoffset + m_wheelflat.m_amplitudefactor * ( ( 1.0 + MoverParameters->Vel / MoverParameters->Vmax + std::clamp( MoverParameters->WheelFlat / 60.0, 0.0, 1.0 ) ) / 3.0 ) ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + m_wheelflat.stop(); + } + } + + // youBy: dzwiek ostrych lukow i ciasnych zwrotek + if( MoverParameters->Vel > 5.0 + && ts.R * ts.R > 1.0 + && std::abs(ts.R) < 15000.0 ) { + // scale volume with curve radius and vehicle speed + volume = + std::abs( MoverParameters->AccN ) // * MoverParameters->AccN + * std::lerp( + 0.5, 1.0, + std::clamp( + MoverParameters->Vel / 40.0, + 0.0, 1.0 ) ) + * ( MyTrack->eType == tt_Switch && std::abs(ts.R) < 1500.0 ? 100.0 : 1.0 ); + } + else { + volume = 0; + } + if( volume > 0.05 ) { + rscurve + .pitch( + true == rscurve.is_combined() ? + MoverParameters->Vel * 0.01f : + rscurve.m_frequencyoffset + rscurve.m_frequencyfactor * 1.f ) + .gain( 2.5 * volume ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + rscurve.stop(); + } + + // movement start jolt + if( false == m_startjoltplayed ) { + auto const velocity { GetVelocity() }; + if( ( MoverParameters->V > 0.0 ? MoverParameters->AccSVBased > 0.1 : MoverParameters->AccSVBased < 0.1 ) + && velocity > 1.0 + && velocity < 15.0 ) { + m_startjolt.play( sound_flags::exclusive ); + m_startjoltplayed = true; + } + } + + // McZapkie! - to wazne - SoundFlag wystawiane jest przez moje moduly gdy zachodza pewne wydarzenia komentowane dzwiekiem. + // pneumatic relay + if( TestFlag( MoverParameters->SoundFlag, sound::pneumatic ) ) { + dsbPneumaticRelay + .gain( + true == TestFlag( MoverParameters->SoundFlag, sound::loud ) ? + 1.0f : + 0.8f ) + .play(); + } + // door permit + if( TestFlag( MoverParameters->SoundFlag, sound::doorpermit ) ) { + // NOTE: current implementation doesn't discern between permit for left/right side, + // which may be undesired in weird setups with doors only on one side + // TBD, TODO: rework into dedicated sound event flag for each door location instance? + for( auto &door : m_doorsounds ) { + door.permit_granted.play( sound_flags::exclusive ); + } + } + + // couplers + int couplerindex { 0 }; + for( auto &couplersounds : m_couplersounds ) { + + auto &coupler { MoverParameters->Couplers[ couplerindex ] }; + + if( coupler.sounds == sound::none ) { + ++couplerindex; + continue; + } + + if( true == TestFlag( coupler.sounds, sound::bufferclash ) ) { + // zderzaki uderzaja o siebie + if( true == TestFlag( coupler.sounds, sound::loud ) ) { + // loud clash + if( false == couplersounds.dsbBufferClamp_loud.empty() ) { + // dedicated sound for loud clash + couplersounds.dsbBufferClamp_loud + .gain( 1.f ) + .play( sound_flags::exclusive ); + } + else { + // fallback on the standard sound + couplersounds.dsbBufferClamp + .gain( 1.f ) + .play( sound_flags::exclusive ); + } + } + else { + // basic clash + couplersounds.dsbBufferClamp + .gain( 1.f ) + .play( sound_flags::exclusive ); + } + } + + if( true == TestFlag( coupler.sounds, sound::couplerstretch ) ) { + // sprzegi sie rozciagaja + if( true == TestFlag( coupler.sounds, sound::loud ) ) { + // loud stretch + if( false == couplersounds.dsbCouplerStretch_loud.empty() ) { + // dedicated sound for loud stretch + couplersounds.dsbCouplerStretch_loud + .gain( 1.f ) + .play( sound_flags::exclusive ); + } + else { + // fallback on the standard sound + couplersounds.dsbCouplerStretch + .gain( 1.f ) + .play( sound_flags::exclusive ); + } + } + else { + // basic clash + couplersounds.dsbCouplerStretch + .gain( 1.f ) + .play( sound_flags::exclusive ); + } + } + // attach/detach sounds + if( ( coupler.sounds & sound::detach ) == 0 ) { + // potentially added some couplings + if( ( coupler.sounds & sound::attachcoupler ) != 0 ) { + couplersounds.attach_coupler.play(); + } + if( ( coupler.sounds & sound::attachbrakehose ) != 0 ) { + couplersounds.attach_brakehose.play(); + } + if( ( coupler.sounds & sound::attachmainhose ) != 0 ) { + couplersounds.attach_mainhose.play(); + } + if( ( coupler.sounds & sound::attachcontrol ) != 0 ) { + couplersounds.attach_control.play(); + } + if( ( coupler.sounds & sound::attachgangway ) != 0 ) { + couplersounds.attach_gangway.play(); + } + if( ( coupler.sounds & sound::attachheating ) != 0 ) { + couplersounds.attach_heating.play(); + } + } + else { + // potentially removed some couplings + if( ( coupler.sounds & sound::attachcoupler ) != 0 ) { + couplersounds.detach_coupler.play(); + } + if( ( coupler.sounds & sound::attachbrakehose ) != 0 ) { + couplersounds.detach_brakehose.play(); + } + if( ( coupler.sounds & sound::attachmainhose ) != 0 ) { + couplersounds.detach_mainhose.play(); + } + if( ( coupler.sounds & sound::attachcontrol ) != 0 ) { + couplersounds.detach_control.play(); + } + if( ( coupler.sounds & sound::attachgangway ) != 0 ) { + couplersounds.detach_gangway.play(); + } + if( ( coupler.sounds & sound::attachheating ) != 0 ) { + couplersounds.detach_heating.play(); + } + } + if( true == TestFlag( coupler.sounds, sound::attachadapter ) ) { + couplersounds.dsbAdapterAttach.play(); + } + if( true == TestFlag( coupler.sounds, sound::removeadapter ) ) { + couplersounds.dsbAdapterRemove.play(); + } + + ++couplerindex; + coupler.sounds = 0; + } + + MoverParameters->SoundFlag = 0; + // McZapkie! - koniec obslugi dzwiekow z mover.pas + + // physics.derailment new: off the track the vehicle scrapes along the ground until it stops, or until it is put back + // on the rails (rerail()) while still sliding + if( MoverParameters->OffTrack.active() && false == MoverParameters->OffTrack.at_rest() ) { + if( false == rsDerailment.is_playing() ) { + rsDerailment.play( sound_flags::exclusive | sound_flags::looping ); + } + m_offtrackscraping = true; + } + else if( std::exchange( m_offtrackscraping, false ) && rsDerailment.is_playing() ) { + rsDerailment.stop(); + } + +// special events + if( MoverParameters->EventFlag ) { + // McZapkie: w razie wykolejenia + if( true == MoverParameters->DamageFlag.HasAll(VehicleDamage::derailed) ) { + rsDerailment.play( sound_flags::exclusive ); + } + + MoverParameters->EventFlag = false; + } +} + +void TDynamicObject::play_mirror_sounds( side const Side, mirror_moves::event const Event ) { + + if( Event == mirror_moves::event::none ) { return; } + // as UpdateMirror(), only the mirrors of the occupied cab move + if( MoverParameters->CabOccupied == 0 ) { return; } + auto const cabend { MoverParameters->CabOccupied > 0 ? end::front : end::rear }; + for( auto &mirror : m_mirrorsounds ) { + if( mirror.placement != Side || mirror.end != cabend ) { continue; } + auto &sound { Event == mirror_moves::event::unfolding ? mirror.unfold : mirror.fold }; + auto &other { Event == mirror_moves::event::unfolding ? mirror.fold : mirror.unfold }; + other.stop(); + sound.play( sound_flags::exclusive ); + } +} + +void +TDynamicObject::powertrain_sounds::position( glm::vec3 const Location ) { + + auto const nullvector { glm::vec3() }; + std::vector enginesounds = { + &inverter, + &motor_relay, &dsbWejscie_na_bezoporow, &motor_parallel, &motor_shuntfield, &rsWentylator, + &engine, &engine_ignition, &engine_shutdown, &engine_revving, &engine_turbo, &oil_pump, &fuel_pump, &water_pump, &water_heater, &radiator_fan, &radiator_fan_aux, + &transmission, &rsEngageSlippery, &retarder + }; + for( auto sound : enginesounds ) { + if( sound->offset() == nullvector ) { + sound->offset( Location ); + } + } +} + +void +TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, double const Deltatime ) { + + if( Vehicle.Power == 0 ) { return; } + + double frequency { 1.0 }; + double volume { 0.0 }; + + // oil pump + if( true == Vehicle.OilPump.is_active ) { + oil_pump + .pitch( oil_pump.m_frequencyoffset + oil_pump.m_frequencyfactor * 1.f ) + .gain( oil_pump.m_amplitudeoffset + oil_pump.m_amplitudefactor * 1.f ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + oil_pump.stop(); + } + // fuel pump + if( true == Vehicle.FuelPump.is_active ) { + fuel_pump + .pitch( fuel_pump.m_frequencyoffset + fuel_pump.m_frequencyfactor * 1.f ) + .gain( fuel_pump.m_amplitudeoffset + fuel_pump.m_amplitudefactor * 1.f ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + fuel_pump.stop(); + } + // water pump + if( true == Vehicle.WaterPump.is_active ) { + water_pump + .pitch( water_pump.m_frequencyoffset + water_pump.m_frequencyfactor * 1.f ) + .gain( water_pump.m_amplitudeoffset + water_pump.m_amplitudefactor * 1.f ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + water_pump.stop(); + } + // water heater + if( true == Vehicle.WaterHeater.is_active ) { + water_heater + .pitch( water_heater.m_frequencyoffset + water_heater.m_frequencyfactor * 1.f ) + .gain( water_heater.m_amplitudeoffset + water_heater.m_amplitudefactor * 1.f ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + water_heater.stop(); + } + // engine sounds + // ignition + if( engine_state_last != Vehicle.Mains ) { + + if( true == Vehicle.Mains ) { + // TODO: separate engine and main circuit + // engine activation + engine_shutdown.stop(); + engine_ignition + .pitch( engine_ignition.m_frequencyoffset + engine_ignition.m_frequencyfactor * 1.f ) + .gain( engine_ignition.m_amplitudeoffset + engine_ignition.m_amplitudefactor * 1.f ) + .play( sound_flags::exclusive ); + // main circuit activation + linebreaker_close + .pitch( linebreaker_close.m_frequencyoffset + linebreaker_close.m_frequencyfactor * 1.f ) + .gain( linebreaker_close.m_amplitudeoffset + linebreaker_close.m_amplitudefactor * 1.f ) + .play(); + } + else { + // engine deactivation + engine_ignition.stop(); + engine_shutdown.pitch( engine_shutdown.m_frequencyoffset + engine_shutdown.m_frequencyfactor * 1.f ) + .gain( engine_shutdown.m_amplitudeoffset + engine_shutdown.m_amplitudefactor * 1.f ) + .play( sound_flags::exclusive ); + // main circuit deactivation + linebreaker_open + .pitch( linebreaker_open.m_frequencyoffset + linebreaker_open.m_frequencyfactor * 1.f ) + .gain( linebreaker_open.m_amplitudeoffset + linebreaker_open.m_amplitudefactor * 1.f ) + .play(); + } + engine_state_last = Vehicle.Mains; + } + // main engine sound + if( true == Vehicle.Mains ) { + + if( std::abs(Vehicle.enrot) > 0.01 + // McZapkie-280503: zeby dla dumb dzialal silnik na jalowych obrotach + || Vehicle.EngineType == TEngineType::Dumb ) { + + // frequency calculation + auto const normalizer { ( + true == engine.is_combined() ? + // for combined engine sound we calculate sound point in rpm, to make .mmd files setup easier + // NOTE: we supply 1/100th of actual value, as the sound module converts does the opposite, converting received (typically) 0-1 values to 0-100 range + 60.f * 0.01f : + // for legacy single-piece sounds the standard frequency calculation is left untouched + 1.f ) }; + frequency = + engine.m_frequencyoffset + + engine.m_frequencyfactor * std::abs( Vehicle.enrot ) * normalizer; + + if( Vehicle.EngineType == TEngineType::Dumb ) { + frequency -= 0.2 * Vehicle.EnginePower / ( 1 + Vehicle.Power * 1000 ); + } + + // base volume calculation + switch( Vehicle.EngineType ) { + // TODO: check calculated values + case TEngineType::DieselElectric: { + + volume = + engine.m_amplitudeoffset + + engine.m_amplitudefactor * ( + 0.25 * ( Vehicle.EnginePower / Vehicle.Power ) + + 0.75 * Vehicle.EngineRPMRatio() ); + break; + } + case TEngineType::DieselEngine: { + if( Vehicle.enrot > 0.0 ) { + volume = Vehicle.EnginePower > 0 ? engine.m_amplitudeoffset + engine.m_amplitudefactor * Vehicle.dizel_fill : + engine.m_amplitudeoffset + engine.m_amplitudefactor * std::fabs(Vehicle.enrot / Vehicle.dizel_nmax); + } + break; + } + default: { + volume = + engine.m_amplitudeoffset + + engine.m_amplitudefactor * ( Vehicle.EnginePower + std::fabs( Vehicle.enrot ) * 60.0 ); + break; + } + } + + if( engine_volume >= 0.05 ) { + + auto enginerevvolume { 0.f }; + if( Vehicle.EngineType == TEngineType::DieselElectric + || Vehicle.EngineType == TEngineType::DieselEngine ) { + // diesel engine revolutions increase; it can potentially decrease volume of base engine sound + if( engine_revs_last != -1.f ) { + // calculate potential recent increase of engine revolutions + auto const revolutionsperminute { Vehicle.enrot * 60 }; + auto const revolutionsdifference { revolutionsperminute - engine_revs_last }; + auto const idlerevolutionsthreshold { 1.01 * Vehicle.EngineIdleRPM() }; + engine_revs_change = std::max( 0.0, engine_revs_change - 2.5 * Deltatime ); + if( revolutionsperminute > idlerevolutionsthreshold + && revolutionsdifference > 1.0 * Deltatime ) { + engine_revs_change = std::clamp( engine_revs_change + 5.0 * Deltatime, 0.0, 1.25 ); + } + enginerevvolume = 0.8 * engine_revs_change; + } + engine_revs_last = Vehicle.enrot * 60; + + auto const enginerevfrequency { ( + true == engine_revving.is_combined() ? + // if the sound contains multiple samples we reuse rpm-based calculation from the engine + frequency : + engine_revving.m_frequencyoffset + 1.f * engine_revving.m_frequencyfactor ) }; + + if( enginerevvolume > 0.02 ) { + engine_revving + .pitch( enginerevfrequency ) + .gain( enginerevvolume ) + .play( sound_flags::exclusive ); + } + else { + engine_revving.stop(); + } + } // diesel engines + + // multi-part revving sound pieces replace base engine sound, single revving simply gets mixed with the base + auto const enginevolume { ( + enginerevvolume > 0.02 && true == engine_revving.is_combined() ? + std::max( 0.0, engine_volume - enginerevvolume ) : + engine_volume ) }; + engine + .pitch( frequency ) + .gain( enginevolume ) + .play( sound_flags::exclusive | sound_flags::looping ); + } // enginevolume > 0.05 + } + else { + engine.stop(); + } + } + + if (Vehicle.Mains) { + float power = std::clamp(Vehicle.eimv_pr, 0.0, 1.0); + + fake_engine + .pitch(fake_engine.m_frequencyoffset + power * fake_engine.m_frequencyfactor) + .gain(fake_engine.m_amplitudeoffset + power * fake_engine.m_amplitudefactor) + .play(sound_flags::exclusive | sound_flags::looping); + } + else { + fake_engine.stop(); + } + + engine_volume = std::lerp( engine_volume, volume, 0.25 ); + if( engine_volume < 0.05 ) { + engine.stop(); + } + + // youBy - przenioslem, bo diesel tez moze miec turbo + if( Vehicle.TurboTest > 0 ) { + // udawanie turbo: + auto const pitch_diesel{Vehicle.EngineType == TEngineType::DieselEngine || Vehicle.EngineType == TEngineType::DieselElectric ? Vehicle.enrot / Vehicle.dizel_nmax * Vehicle.dizel_fill : 1}; + auto const goalpitch { std::max( 0.025, ( /*engine_volume **/ pitch_diesel + engine_turbo.m_frequencyoffset ) * engine_turbo.m_frequencyfactor ) }; + auto const goalvolume { ( + Vehicle.MainCtrlPos >= Vehicle.TurboTest && Vehicle.enrot > 0.1 ? + std::max( 0.0, ( engine_turbo_pitch + engine_turbo.m_amplitudeoffset ) * engine_turbo.m_amplitudefactor ) : + 0.0 ) }; + auto const currentvolume { engine_turbo.gain() }; + auto const changerate { 0.4 * Deltatime }; + + engine_turbo_pitch = engine_turbo_pitch > goalpitch ? std::max(goalpitch, engine_turbo_pitch - changerate * 0.5) : std::min(goalpitch, engine_turbo_pitch + changerate); + + volume = currentvolume > goalvolume ? std::max(goalvolume, currentvolume - changerate) : std::min(goalvolume, currentvolume + changerate); + + engine_turbo + .pitch( 0.4 + engine_turbo_pitch * 0.4 ) + .gain( volume ); + + if( volume > 0.05 ) { + engine_turbo.play( sound_flags::exclusive | sound_flags::looping ); + } + else { + engine_turbo.stop(); + } + } + + if( Vehicle.dizel_engage > 0.1 ) { + if( std::abs( Vehicle.dizel_engagedeltaomega ) > 0.2 ) { + frequency = rsEngageSlippery.m_frequencyoffset + rsEngageSlippery.m_frequencyfactor * std::fabs( Vehicle.dizel_engagedeltaomega ); + volume = rsEngageSlippery.m_amplitudeoffset + rsEngageSlippery.m_amplitudefactor * Vehicle.dizel_engage; + } + else { + frequency = 1.f; // rsEngageSlippery.FA+0.7*rsEngageSlippery.FM*(fabs(mvControlled->enrot)+mvControlled->nmax); + volume = Vehicle.dizel_engage > 0.2 ? rsEngageSlippery.m_amplitudeoffset + 0.2 * rsEngageSlippery.m_amplitudefactor * (Vehicle.enrot / Vehicle.nmax) : 0.f; + } + + rsEngageSlippery + .pitch( frequency ) + .gain( volume ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + rsEngageSlippery.stop(); + } + + if (Vehicle.hydro_R) { + float speed = std::abs(Vehicle.hydro_R_n); + + retarder + .pitch(retarder.m_frequencyoffset + speed * retarder.m_frequencyfactor) + .gain(retarder.m_amplitudeoffset + Vehicle.hydro_R_Fill * retarder.m_amplitudefactor); + + if (retarder.gain() > 0.01 && speed > 1 && Vehicle.hydro_R_ClutchActive) { + retarder.play(sound_flags::exclusive | sound_flags::looping); + } + else { + retarder.stop(); + } + } + + // motor sounds + volume = 0.0; + // generic traction motor sounds + if( false == motors.empty() ) { + + if( std::abs( Vehicle.nrot ) > 0.01 ) { + + auto const &motor { motors.front() }; + // frequency calculation + auto normalizer { 1.f }; + if( true == motor.is_combined() ) { + // for combined motor sound we calculate sound point in rpm, to make .mmd files setup easier + // NOTE: we supply 1/100th of actual value, as the sound module converts does the opposite, converting received (typically) 0-1 values to 0-100 range + normalizer = 60.f * 0.01f; + } + auto const motorrevolutions { std::abs( Vehicle.nrot ) * Vehicle.Transmision.Ratio }; + frequency = + motor.m_frequencyoffset + + motor.m_frequencyfactor * motorrevolutions * normalizer; + + // base volume calculation + switch( Vehicle.EngineType ) { + case TEngineType::ElectricInductionMotor: { + volume = + motor.m_amplitudeoffset + + motor.m_amplitudefactor * ( Vehicle.EnginePower + motorrevolutions * 2 ); + break; + } + case TEngineType::ElectricSeriesMotor: { + volume = + motor.m_amplitudeoffset + + motor.m_amplitudefactor * ( Vehicle.EnginePower + motorrevolutions * 60.0 ); + break; + } + default: { + volume = + motor.m_amplitudeoffset + + motor.m_amplitudefactor * motorrevolutions * 60.0; + break; + } + } + + if( Vehicle.EngineType == TEngineType::ElectricSeriesMotor ) { + // volume variation + if( volume < 1.0 + && Vehicle.EnginePower < 100 ) { + + auto const volumevariation { LocalRandom( 100 ) * Vehicle.enrot / ( 1 + Vehicle.nmax ) }; + if( volumevariation < 2 ) { + volume += volumevariation / 200; + } + } + + if( Vehicle.DynamicBrakeFlag + && Vehicle.EnginePower > 0.1 ) { + // Szociu - 29012012 - jeżeli uruchomiony jest hamulec elektrodynamiczny, odtwarzany jest dźwięk silnika + volume += 0.8; + } + } + // scale motor volume based on whether they're active + motor_momentum = + std::clamp( + motor_momentum + - 1.0 * Deltatime // smooth out decay + + std::abs( Vehicle.Mm ) / 60.0 * Deltatime, + 0.0, 1.25 ); + volume *= std::max( 0.25f, motor_momentum ); + motor_volume = std::lerp( motor_volume, volume, 0.25 ); + if( motor_volume >= 0.05 ) { + // apply calculated parameters to all motor instances + for( auto &motor : motors ) { + motor + .pitch( frequency ) + .gain( motor_volume ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + } + else { + // stop all motor instances + for( auto &motor : motors ) { + motor.stop(); + } + } + } + else { + // stop all motor instances + motor_volume = 0.0; + for( auto &motor : motors ) { + motor.stop(); + } + } + } + // inverter-specific traction motor sounds + if( false == acmotors.empty() ) { + + if( Vehicle.EngineType == TEngineType::ElectricInductionMotor ) { + if( Vehicle.InverterFrequency > 0.001 ) { + + for( auto &motor : acmotors ) { + motor + .pitch( motor.m_frequencyoffset + motor.m_frequencyfactor * Vehicle.InverterFrequency ) + .gain( motor.m_amplitudeoffset + motor.m_amplitudefactor * std::sqrt( std::abs( Vehicle.eimv_pr ) ) ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + } + else { + for( auto &motor : acmotors ) { + motor.stop(); + } + } + } + } + // motor blowers + if( false == motorblowers.empty() ) { + for( auto &blowersound : motorblowers ) { + // match the motor blower and the sound source based on whether they're located in the front or the back of the vehicle + auto const &blower { Vehicle.MotorBlowers[ ( blowersound.offset().z > 0 ? end::front : end::rear ) ] }; + // TODO: for the sounds with provided bookends invoke stop() when the stop is triggered and revolutions start dropping, instead of after full stop + if( blower.revolutions > 1 ) { + // NOTE: for motorblowers with fixed speed if the sound has defined bookends we skip revolutions-based part of frequency/volume adjustments + auto const revolutionmodifier { Vehicle.MotorBlowers[end::front].speed < 0.f && blowersound.has_bookends() ? 1.f : blower.revolutions }; + blowersound + .pitch( + true == blowersound.is_combined() ? + blower.revolutions * 0.01f : + blowersound.m_frequencyoffset + blowersound.m_frequencyfactor * revolutionmodifier ) + .gain( blowersound.m_amplitudeoffset + blowersound.m_amplitudefactor * revolutionmodifier ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + blowersound.stop(); + } + } + } + // inverter sounds + if( Vehicle.EngineType == TEngineType::ElectricInductionMotor ) { + if( Vehicle.InverterFrequency > 0.001 ) { + + volume = inverter.m_amplitudeoffset + inverter.m_amplitudefactor * std::sqrt( std::abs( Vehicle.eimv_pr) ); + + inverter + .pitch( inverter.m_frequencyoffset + inverter.m_frequencyfactor * Vehicle.InverterFrequency ) + .gain( volume ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + inverter.stop(); + } + } + // ventillator sounds + if( Vehicle.RventRot > 0.1 ) { + + rsWentylator + .pitch( rsWentylator.m_frequencyoffset + rsWentylator.m_frequencyfactor * Vehicle.RventRot ) + .gain( rsWentylator.m_amplitudeoffset + rsWentylator.m_amplitudefactor * Vehicle.RventRot ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + // ...otherwise shut down the sound + rsWentylator.stop(); + } + // radiator fan sounds + if( Vehicle.EngineType == TEngineType::DieselEngine + || Vehicle.EngineType == TEngineType::DieselElectric ) { + + if( Vehicle.dizel_heat.rpmw > 0.1 ) { + // NOTE: fan speed tends to max out at ~100 rpm; by default we try to get pitch range of 0.5-1.5 and volume range of 0.5-1.0 + radiator_fan + .pitch( 0.5 + radiator_fan.m_frequencyoffset + radiator_fan.m_frequencyfactor * Vehicle.dizel_heat.rpmw * 0.01 ) + .gain( 0.5 + radiator_fan.m_amplitudeoffset + 0.5 * radiator_fan.m_amplitudefactor * Vehicle.dizel_heat.rpmw * 0.01 ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + // ...otherwise shut down the sound + radiator_fan.stop(); + } + + if( Vehicle.dizel_heat.rpmw2 > 0.1 ) { + // NOTE: fan speed tends to max out at ~100 rpm; by default we try to get pitch range of 0.5-1.5 and volume range of 0.5-1.0 + radiator_fan_aux + .pitch( 0.5 + radiator_fan_aux.m_frequencyoffset + radiator_fan_aux.m_frequencyfactor * Vehicle.dizel_heat.rpmw2 * 0.01 ) + .gain( 0.5 + radiator_fan_aux.m_amplitudeoffset + 0.5 * radiator_fan_aux.m_amplitudefactor * Vehicle.dizel_heat.rpmw2 * 0.01 ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + // ...otherwise shut down the sound + radiator_fan_aux.stop(); + } + } + + // relay sounds + auto const soundflags { Vehicle.SoundFlag }; + if( TestFlag( soundflags, sound::relay ) ) { + // przekaznik - gdy bezpiecznik, automatyczny rozruch itp + if( true == TestFlag( soundflags, sound::shuntfield ) ) { + // shunt field + motor_shuntfield + .pitch( + true == motor_shuntfield.is_combined() ? + Vehicle.ScndCtrlActualPos * 0.01f : + motor_shuntfield.m_frequencyoffset + motor_shuntfield.m_frequencyfactor * 1.f ) + .gain( + motor_shuntfield.m_amplitudeoffset + ( + true == TestFlag( soundflags, sound::loud ) ? + 1.0f : + 0.8f ) + * motor_shuntfield.m_amplitudefactor ) + .play(); + } + else if( true == TestFlag( soundflags, sound::parallel ) ) { + // parallel mode + if( TestFlag( soundflags, sound::loud ) ) { + dsbWejscie_na_bezoporow.play(); + } + else { + motor_parallel.play(); + } + } + else { + // series mode + motor_relay + .pitch( + true == motor_relay.is_combined() ? + Vehicle.MainCtrlActualPos * 0.01f : + motor_relay.m_frequencyoffset + motor_relay.m_frequencyfactor * 1.f ) + .gain( + motor_relay.m_amplitudeoffset + ( + true == TestFlag( soundflags, sound::loud ) ? + 1.0f : + 0.8f ) + * motor_relay.m_amplitudefactor ) + .play(); + } + } + + if( Vehicle.Vel > 0.1 ) { + transmission + .pitch( transmission.m_frequencyoffset + transmission.m_frequencyfactor * Vehicle.Vel ) + .gain( transmission.m_amplitudeoffset + transmission.m_amplitudefactor * Vehicle.Vel ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + transmission.stop(); + } +} diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp new file mode 100644 index 000000000..ece70ca4d --- /dev/null +++ b/vehicle/dynamic/update.cpp @@ -0,0 +1,1435 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the update of a vehicle in a step of the simulation + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/mover.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + + +bool TDynamicObject::Update(double dt, double dt1) +{ + if (dt1 == 0.0) + return true; // Ra: pauza + // physics.derailment new: all of the update of a vehicle off the track, timed; a warning once a second at most when it + // takes long, to find what makes a derailment slow + // (no vehicle when it is on the track: nothing is timed then) + class off_track_watch { + public: + off_track_watch( TDynamicObject *Vehicle, double const Frame ) : + vehicle { Vehicle }, frame { Frame } { + if( vehicle != nullptr ) { + started = off_track_clock::now(); + } + } + off_track_watch( off_track_watch const & ) = delete; + off_track_watch &operator=( off_track_watch const & ) = delete; + ~off_track_watch() { + if( vehicle == nullptr ) { + return; + } + auto const took { seconds_since( started ) }; + vehicle->m_offtrackupdatedue -= frame; + if( took > off_track_slow && vehicle->m_offtrackupdatedue <= 0.0 ) { + vehicle->m_offtrackupdatedue = 1.0; + ErrorLog( std::format( "derailment: warning: the update of {} off the track took {:.0f} ms in a frame of {:.3f} s", vehicle->MoverParameters->Name, took * 1000.0, frame ) ); + } + } + private: + TDynamicObject *vehicle; + double frame; + off_track_clock::time_point started {}; + }; + off_track_watch const watch { MoverParameters->OffTrack.active() ? this : nullptr, dt1 }; + if( m_offtrackterrain != nullptr && false == MoverParameters->OffTrack.active() ) { + // physics.derailment new: back on the rails (rerail()), the terrain it slid over is let go + m_offtrackterrain.reset(); + m_offtracksite.terrain( nullptr ); + } + if (!MoverParameters->PhysicActivation && + !MechInside) { // to drugie, bo będąc w maszynowym blokuje się fizyka + // physics.derailment new: a vehicle off the track stopped along its heading still settles: it slides down a + // slope, falls over, or comes to rest after the step its physics stopped in + if( MoverParameters->OffTrack.active() && false == MoverParameters->OffTrack.at_rest() && bEnabled ) { + m_offtracktime = dt1; + Move( 0.0 ); + update_off_track( dt1 ); + } + return true; // McZapkie: wylaczanie fizyki gdy nie potrzeba + } + if (!MyTrack) + return false; // pojazdy postawione na torach portalowych mają MyTrack==NULL + if (!bEnabled) + return false; // a normalnie powinny mieć bEnabled==false + + double dDOMoveLen; + // McZapkie: parametry powinny byc pobierane z toru + if (Axle0.vAngles.z != Axle1.vAngles.z) + { // wyliczenie promienia z obrotów osi - modyfikację zgłosił youBy + ts.R = Axle0.vAngles.z - Axle1.vAngles.z; // różnica może dawać stałą ±M_2PI + if( ts.R > 15000.0 || ts.R < -15000.0 ) { + // szkoda czasu na zbyt duże promienie, 4km to promień nie wymagający przechyłki + ts.R = 0.0; + } + else { + // normalizacja + if( ts.R > M_PI ) { ts.R -= M_2PI; } + else if( ts.R < -M_PI ) { ts.R += M_2PI; } + + if( ts.R != 0.0 ) { + // sin(0) results in division by zero + ts.R = -0.5 * MoverParameters->BDist / sin( ts.R * 0.5 ); + } + } + } + else + ts.R = 0.0; + // ts.R=ComputeRadius(Axle1.pPosition,Axle2.pPosition,Axle3.pPosition,Axle0.pPosition); + // Ra: składową pochylenia wzdłużnego mamy policzoną w jednostkowym wektorze + // vFront + ts.Len = 1.0; // std::max(MoverParameters->BDist,MoverParameters->ADist); + ts.dHtrack = -vFront.y; // Axle1.pPosition.y-Axle0.pPosition.y; //wektor + // między skrajnymi osiami + // (!!!odwrotny) + ts.dHrail = (Axle1.GetRoll() + Axle0.GetRoll()) * 0.5; //średnia przechyłka pudła + // the uneven track under the outer axles, for the criteria of derailment: its lateral curvature, and its cross level + ts.uneven_curvature = glm::dot( 0.5 * ( Axle0.UnevenBend() + Axle1.UnevenBend() ), vLeft ); + ts.uneven_cross = MyTrack->uneven_underway().cross; + // a buckle of the track under the body: the mean of the curvatures at the outer axles, each over the wheelbase of its bogie + ts.buckle_curvature = 0.5 * ( Axle0.BuckleCurvature( MoverParameters->ADist ) + Axle1.BuckleCurvature( MoverParameters->ADist ) ); + // TTrackParam tp; + tp.Width = MyTrack->fTrackWidth; + // McZapkie-250202 + tp.friction = MyTrack->Friction() * Global.fFriction * Global.FrictionWeatherFactor; + tp.CategoryFlag = MyTrack->iCategoryFlag & 15; + tp.DamageFlag = MyTrack->iDamageFlag; + tp.QualityFlag = MyTrack->iQualityFlag; + tp.Name = &MyTrack->name(); + + // couplers + if( MoverParameters->Couplers[0].CouplingFlag != Coupling::none + && MoverParameters->Couplers[1].CouplingFlag != Coupling::none ) { + MoverParameters->InsideConsist = true; + } + else { + MoverParameters->InsideConsist = false; + } + if( TestFlag( MoverParameters->AIFlag, sound::attachcoupler ) ) { + auto *driver{ ctOwner ? ctOwner : Mechanik }; + if( driver != nullptr ) { + driver->CheckVehicles( DriverOrder::connect ); + } + ClearFlag( MoverParameters->AIFlag, sound::attachcoupler ); + } + + // napiecie sieci trakcyjnej + if (MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) { // dla EZT tylko silnikowy + + tmpTraction.TractionVoltage = std::max( std::abs( MoverParameters->PantRearVolt ), std::abs( MoverParameters->PantFrontVolt ) ); + // jeśli brak zasilania dłużej niż 0.2 sekundy (25km/h pod izolatorem daje 0.15s) + // Ra 2F1H: prowizorka, trzeba przechować napięcie, żeby nie wywalało WS pod izolatorem + if( tmpTraction.TractionVoltage > 0.0) { + NoVoltTime = 0; + } + else { + NoVoltTime += dt1; + if( NoVoltTime <= 0.2 ) { + tmpTraction.TractionVoltage = MoverParameters->PantographVoltage; + } + else { + // jeśli jedzie + if( MoverParameters->Vel > 0.5 ) { + // Ra 2014-07: doraźna blokada logowania zimnych lokomotyw - zrobić to trzeba inaczej + if( MoverParameters->Pantographs[end::front].is_active + || MoverParameters->Pantographs[end::rear].is_active ) { + if( MoverParameters->Mains // Ra 15-01: logować tylko, jeśli WS załączony + && MoverParameters->GetTrainsetHighVoltage() < 0.1f // yB 16-03: i nie jest to asynchron zasilany z daleka + && false == MoverParameters->GensetSelected() ) { // nor a dual-mode vehicle running on its genset + // Ra 15-01: bezwzględne współrzędne pantografu nie są dostępne więc lepiej się tego nie zaloguje + ErrorLog( + "Bad traction: " + MoverParameters->Name + + " lost power for " + to_string( NoVoltTime, 2 ) + " sec. at " + + to_string(vPosition) ); + } + } + } + } + } + } + else { + tmpTraction.TractionVoltage = 0.95 * MoverParameters->EnginePowerSource.MaxVoltage; + } + tmpTraction.TractionFreq = 0; + tmpTraction.TractionMaxCurrent = 7500; // Ra: chyba za dużo? powinno wywalać przy 1500 + tmpTraction.TractionResistivity = 0.3; + + MoverParameters->PantographVoltage = tmpTraction.TractionVoltage; + // McZapkie: predkosc w torze przekazac do TrackParam + // McZapkie: Vel ma wymiar [km/h] (absolutny), V ma wymiar [m/s], taka przyjalem notacje + tp.Velmax = MyTrack->VelocityGet(); + + if (Mechanik) + { // Ra 2F3F: do Driver.cpp to przenieść? + if( Mechanik->primary() ) { + MoverParameters->EqvtPipePress = GetEPP(); // srednie cisnienie w PG + } + if (Mechanik->primary() && + (MoverParameters->EngineType == TEngineType::DieselEngine || + MoverParameters->EngineType == TEngineType::DieselElectric) + && MoverParameters->EIMCtrlType > 0) { + MoverParameters->CheckEIMIC(dt1); + if (MoverParameters->SpeedCtrl) + MoverParameters->CheckSpeedCtrl(dt1); + MoverParameters->eimic_real = std::min(MoverParameters->eimic,MoverParameters->eimicSpeedCtrl); + MoverParameters->SendCtrlToNext(VehicleCommand::integratedController, MoverParameters->eimic_real, MoverParameters->CabActive); + } + if( Mechanik->primary() + && MoverParameters->EngineType == TEngineType::ElectricInductionMotor ) { + // jesli glowny i z asynchronami, to niech steruje hamulcem i napedem lacznie dla calego pociagu/ezt + auto const kier = DirectionGet() * MoverParameters->CabOccupied > 0; + auto FED { 0.0 }; + auto np { 0 }; + auto masa { 0.0 }; + auto FrED { 0.0 }; + auto masamax { 0.0 }; + auto FmaxPN { 0.0 }; + auto FfulED { 0.0 }; + auto FmaxED { 0.0 }; + auto Frj { 0.0 }; + auto osie { 0 }; + // 0a. ustal aktualna nastawe zadania sily napedowej i hamowania + if( MoverParameters->Power < 1 + && ctOwner != nullptr ) { + MoverParameters->MainCtrlPos = ctOwner->Controlling()->MainCtrlPos*MoverParameters->MainCtrlPosNo / std::max(1, ctOwner->Controlling()->MainCtrlPosNo); + MoverParameters->SpeedCtrlValue = ctOwner->Controlling()->SpeedCtrlValue; + MoverParameters->SpeedCtrlUnit.IsActive = ctOwner->Controlling()->SpeedCtrlUnit.IsActive; + } + MoverParameters->CheckEIMIC(dt1); + MoverParameters->CheckSpeedCtrl(dt1); + + auto eimic = std::min(MoverParameters->eimic, MoverParameters->eimicSpeedCtrl); + MoverParameters->eimic_real = eimic; + // Elf: full braking at once in the lowest position, and in the emergency brake position below it + if (MoverParameters->EIMCtrlType == 2 && MoverParameters->MainCtrlPos <= MoverParameters->EIMCtrlEmergencyPositions()) + eimic = -1.0; + MoverParameters->SendCtrlToNext(VehicleCommand::integratedController, std::max(0., eimic), MoverParameters->CabActive); + auto LBR = std::max(-eimic, 0.); + auto eim_lb = Mechanik->AIControllFlag || !MoverParameters->LocHandleTimeTraxx ? 0 : MoverParameters->eim_localbrake; + + // 1. ustal wymagana sile hamowania calego pociagu + // - opoznienie moze byc ustalane na podstawie charakterystyki + // - opoznienie moze byc ustalane na podstawie mas i cisnien granicznych + // + + // 2. ustal mozliwa do realizacji sile hamowania ED + // - w szczegolnosci powinien brac pod uwage rozne sily hamowania + for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, Coupling::control); p; + kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) + { + ++np; + masamax += + p->MoverParameters->MBPM + + ( p->MoverParameters->MBPM > 1.0 ? + 0.0 : + p->MoverParameters->Mass ) + + p->MoverParameters->Mred; + auto const Nmax = ((p->MoverParameters->P2FTrans * p->MoverParameters->MaxBrakePress[0] - + p->MoverParameters->BrakeCylSpring) * + p->MoverParameters->BrakeCylMult[0] - + p->MoverParameters->BrakeSlckAdj) * + p->MoverParameters->BrakeCylNo * p->MoverParameters->BrakeRigEff; + FmaxPN += Nmax * p->MoverParameters->Hamulec->GetFC( + Nmax / (p->MoverParameters->NAxles * p->MoverParameters->NBpA), + p->MoverParameters->MED_Vref) * + 1000; // sila hamowania pn + FmaxED += p->MoverParameters->Mains && p->MoverParameters->DirActive != 0 && p->MoverParameters->InvertersRatio == 1.0 && + p->MoverParameters->eimc[eimc_p_Fh] * p->MoverParameters->NPoweredAxles > 0 ? + p->MoverParameters->eimc[eimc_p_Fh] * 1000 : + 0; // chwilowy max ED -> do rozdzialu sil + FED -= std::min(p->MoverParameters->eimv[eimv_Fmax], 0.0) * + 1000; // chwilowy max ED -> do rozdzialu sil + FfulED = std::min(p->MoverParameters->eimv[eimv_Fful], 0.0) * + 1000; // chwilowy max ED -> do rozdzialu sil + FrED -= std::min(p->MoverParameters->eimv[eimv_Fmax], 0.0) * + 1000; // chwilowo realizowane ED -> do pneumatyki + Frj += std::max(p->MoverParameters->eimv[eimv_Fmax], 0.0) * + 1000;// chwilowo realizowany napęd -> do utrzymującego + masa += p->MoverParameters->TotalMass; + osie += p->MoverParameters->NAxles; + } + double RapidMult = 1.0; + if ((MoverParameters->BrakeDelays & bdelay_P + bdelay_R) == bdelay_P + bdelay_R + && MoverParameters->BrakeDelayFlag & bdelay_P) + RapidMult = MoverParameters->RapidMult; + + auto const amax = RapidMult * std::min(FmaxPN / masamax, MoverParameters->MED_amax); + + Mechanik->fMedAmax = amax; + auto doorisopen { + false == MoverParameters->Doors.instances[side::left].is_closed + || false == MoverParameters->Doors.instances[side::right].is_closed + || ( MoverParameters->Doors.permit_needed + && ( MoverParameters->Doors.instances[ side::left ].open_permit + || MoverParameters->Doors.instances[ side::right ].open_permit ) ) }; + doorisopen &= !(MoverParameters->ReleaseParkingBySpringBrakeWhenDoorIsOpen && MoverParameters->SpringBrake.IsActive); + + if (MoverParameters->Vel < 0.5 && (eimic < 0 || doorisopen || MoverParameters->Hamulec->GetEDBCP())) + { + MoverParameters->ShuntMode = true; + } + if (MoverParameters->ShuntMode) + { + MoverParameters->ShuntModeAllow = false == doorisopen && + LBR < 0.01; + } + if( MoverParameters->Vel > 1 && false == doorisopen ) + { + MoverParameters->ShuntMode = false; + MoverParameters->ShuntModeAllow = MoverParameters->BrakePress > 0.2 && + LBR < 0.01; + } + auto Fzad = amax * LBR * masa; + if ((MoverParameters->BrakeCtrlPos == MoverParameters->Handle->GetPos(bh_EB) + && MoverParameters->eimc[eimc_p_abed] < 0.001) || + MoverParameters->EmergencyValveFlow > 0) + Fzad = amax * masa; //pętla bezpieczeństwa - pełne służbowe + if (MoverParameters->ScndS && + MoverParameters->Vel > MoverParameters->eimc[eimc_p_Vh1] && FmaxED > 0) + { + Fzad = std::min(LBR * FmaxED, FfulED); + } + // the holding brake lets go once power has been demanded for its delay (SBDReleaseDelay, none by default) + auto const holdingbrakereleased { MoverParameters->UpdateStopBrakeRelease( eimic, dt1 ) }; + if (MoverParameters->ShuntMode && false == holdingbrakereleased || doorisopen /*|| + (MoverParameters->V * MoverParameters->DirAbsolute < -0.2)*/) + { + auto const sbd { ( MoverParameters->SpringBrake.IsActive && MoverParameters->ReleaseParkingBySpringBrake ? 0.0 : MoverParameters->StopBrakeDecc ) }; + Fzad = std::max( Fzad, sbd * masa ); + } + if (Fzad > 1 && !MEDLogFile.is_open() && MoverParameters->Vel > 1) + { + MEDLogFile.open( + "MEDLOGS/" + MoverParameters->Name + "_" + std::to_string( ++MEDLogCount ) + ".csv", + std::ios::in | std::ios::out | std::ios::trunc ); + MEDLogFile << "t\tVel\tMasa\tOsie\tFmaxPN\tFmaxED\tFfulED\tFrED\tFzad\tFzadED\tFzadPN"; + for(int k=1;k<=np;k++) + { + MEDLogFile << "\tBP" << k; + } + MEDLogFile << "\n"; + MEDLogFile.flush(); + MEDLogInactiveTime = 0; + MEDLogTime = 0; + } + auto FzadED { 0.0 }; + if( LBR > MoverParameters->MED_MinBrakeReqED + && ( MoverParameters->BrakeHandle == TBrakeHandle::MHZ_EN57 ? + (MoverParameters->BrakeOpModeFlag & bom_MED) != 0 : + MoverParameters->EpFuse ) ) { + FzadED = std::min( Fzad, FmaxED ); + } + /*/ELF - wdrazanie ED po powrocie na utrzymanie hamowania - do usuniecia + if (MoverParameters->EIMCtrlType == 2 && MoverParameters->MainCtrlPos < 2 && MoverParameters->eimic > -0.999) + { + FzadED = std::min(FzadED, MED_oldFED); + } //*/ + //opoznienie wdrazania ED + if (FzadED > MED_oldFED) + { + if (MoverParameters->MED_ED_DelayTimer <= 0) { + MoverParameters->MED_ED_DelayTimer += dt1; + if (MoverParameters->MED_ED_DelayTimer > 0) { + + } + else { + FzadED = std::min(FzadED, MED_oldFED); + } + } + else + { + FzadED = std::min(FzadED, MED_oldFED); + MoverParameters->MED_ED_DelayTimer = FrED > 0 ? -MoverParameters->MED_ED_Delay2 : -MoverParameters->MED_ED_Delay1; + } + } + if (MoverParameters->BrakeCtrlPos == MoverParameters->Handle->GetPos(bh_EB) + && MoverParameters->eimc[eimc_p_abed] < 0.001) + FzadED = 0; //pętla bezpieczeństwa - bez ED + auto const FzadPN = Fzad - FrED * MoverParameters->MED_FrED_factor; + std::vector PrzekrF( np ); + float nPrzekrF = 0; + bool test = true; + std::vector FzED( np ); + std::vector FzEP( np ); + std::vector FmaxEP( np ); + // 3. ustaw pojazdom sile hamowania ED + // - proporcjonalnie do mozliwosci + + // 4. ustal potrzebne dohamowanie pneumatyczne + // - od sily zadanej trzeba odjac realizowana przez ED + // 5. w razie potrzeby wlacz hamulec utrzymujacy + // - gdy zahamowany ma ponizej 2 km/h + // 6. ustaw pojazdom sile hamowania ep + // - proporcjonalnie do masy, do liczby osi, rowne cisnienia - jak + // bedzie, tak bedzie dobrze + float Fpoj = 0; // MoverParameters->CabOccupied < 0 + ////ALGORYTM 2 - KAZDEMU PO ROWNO, ale nie wiecej niz eped * masa + // 1. najpierw daj kazdemu tyle samo + int i = 0; + for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, Coupling::control); p; + p = kier == true ? p->Next(Coupling::control) : p->Prev(Coupling::control) ) + { + auto const Nmax = ((p->MoverParameters->P2FTrans * p->MoverParameters->MaxBrakePress[0] - + p->MoverParameters->BrakeCylSpring) * + p->MoverParameters->BrakeCylMult[0] - + p->MoverParameters->BrakeSlckAdj) * + p->MoverParameters->BrakeCylNo * p->MoverParameters->BrakeRigEff; + FmaxEP[i] = Nmax * + p->MoverParameters->Hamulec->GetFC( + Nmax / (p->MoverParameters->NAxles * p->MoverParameters->NBpA), + p->MoverParameters->MED_Vref) * + 1000; // sila hamowania pn + + PrzekrF[i] = false; + FzED[i] = FmaxED > 0 ? FzadED / FmaxED : 0; + p->MoverParameters->AnPos = + MoverParameters->ScndS ? LBR : FzED[i]; + FzEP[ i ] = static_cast( FzadPN * p->MoverParameters->NAxles ) / static_cast( osie ); + ++i; + p->MoverParameters->ShuntMode = MoverParameters->ShuntMode; + p->MoverParameters->ShuntModeAllow = MoverParameters->ShuntModeAllow; + } + while (test) + { + test = false; + i = 0; + float przek = 0; + for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, Coupling::control); p; + p = kier == true ? p->Next(Coupling::control) : p->Prev(Coupling::control) ) + { + if (FzEP[i] > 0.01 && + FzEP[i] > p->MoverParameters->TotalMass * p->MoverParameters->eimc[eimc_p_eped] + std::min(p->MoverParameters->eimv[eimv_Fmax], 0.) * 1000 && + !PrzekrF[i]) + { + float przek1 = -std::min(p->MoverParameters->eimv[eimv_Fmax], 0.) * 1000 + + FzEP[i] - + p->MoverParameters->TotalMass * + p->MoverParameters->eimc[eimc_p_eped] * 0.999; + PrzekrF[i] = true; + test = true; + nPrzekrF++; + przek1 = std::min(przek1, FzEP[i]); + FzEP[i] -= przek1; + if (FzEP[i] < 0) + FzEP[i] = 0; + przek += przek1; + } + ++i; + } + i = 0; + przek = przek / (np - nPrzekrF); + for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, Coupling::control); p; + true == kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) + { + if (!PrzekrF[i]) + { + FzEP[i] += przek; + } + ++i; + } + } + i = 0; + for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, Coupling::control); p; + true == kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) + { + float Nmax = ((p->MoverParameters->P2FTrans * p->MoverParameters->MaxBrakePress[0] - + p->MoverParameters->BrakeCylSpring) * + p->MoverParameters->BrakeCylMult[0] - + p->MoverParameters->BrakeSlckAdj) * + p->MoverParameters->BrakeCylNo * p->MoverParameters->BrakeRigEff; + if (FrED > 0.1) + p->MoverParameters->MED_EPVC_CurrentTime = 0; + else + p->MoverParameters->MED_EPVC_CurrentTime += dt1; + bool EPVC = p->MoverParameters->MED_EPVC && (p->MoverParameters->MED_EPVC_Time < 0 || p->MoverParameters->MED_EPVC_CurrentTime < p->MoverParameters->MED_EPVC_Time); + float VelC = EPVC ? safe_clamp(p->MoverParameters->Vel, p->MoverParameters->MED_Vmin, p->MoverParameters->MED_Vmax) : p->MoverParameters->MED_Vref;//korekcja EP po prędkości + float FmaxPoj = Nmax * + p->MoverParameters->Hamulec->GetFC( + Nmax / (p->MoverParameters->NAxles * p->MoverParameters->NBpA), VelC) * + 1000; // sila hamowania pn + p->MoverParameters->LocalBrakePosAEIM = FzEP[i] / FmaxPoj; + if (p->MoverParameters->LocalBrakePosAEIM>0.009) + if (p->MoverParameters->P2FTrans * p->MoverParameters->BrakeCylMult[0] * + p->MoverParameters->MaxBrakePress[0] != 0) + { + float x = (p->MoverParameters->BrakeSlckAdj / p->MoverParameters->BrakeCylMult[0] + + p->MoverParameters->BrakeCylSpring) / (p->MoverParameters->P2FTrans * + p->MoverParameters->MaxBrakePress[0]); + p->MoverParameters->LocalBrakePosAEIM = x + (1 - x) * p->MoverParameters->LocalBrakePosAEIM; + } + else + p->MoverParameters->LocalBrakePosAEIM = p->MoverParameters->LocalBrakePosAEIM; + else + p->MoverParameters->LocalBrakePosAEIM = 0; + if (p->MoverParameters->LocHandleTimeTraxx) + { + p->MoverParameters->eim_localbrake = eim_lb; + p->MoverParameters->LocalBrakePosAEIM = std::max(p->MoverParameters->LocalBrakePosAEIM, eim_lb); + } + ++i; + } + + MED[0][0] = masa*0.001; + MED[0][1] = amax; + MED[0][2] = Fzad*0.001; + MED[0][3] = FmaxPN*0.001; + MED[0][4] = FmaxED*0.001; + MED[0][5] = FrED*0.001; + MED[0][6] = FzadPN*0.001; + MED[0][7] = nPrzekrF; + + if (MEDLogFile.is_open()) + { + MEDLogFile << MEDLogTime << "\t" << MoverParameters->Vel << "\t" << masa*0.001 << "\t" << osie << "\t" << FmaxPN*0.001 << "\t" << FmaxED*0.001 << "\t" + << FfulED*0.001 << "\t" << FrED*0.001 << "\t" << Fzad*0.001 << "\t" << FzadED*0.001 << "\t" << FzadPN*0.001; + for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, Coupling::control); p; + true == kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) + { + MEDLogFile << "\t" << p->MoverParameters->BrakePress; + } + MEDLogFile << "\n"; + if (floor(MEDLogTime + dt1) > floor(MEDLogTime)) + { + MEDLogFile.flush(); + } + MEDLogTime += dt1; + + if (MoverParameters->Vel < 0.1 || MoverParameters->MainCtrlPowerPos() > 0) + { + MEDLogInactiveTime += dt1; + } + else + { + MEDLogInactiveTime = 0; + } + if (MEDLogInactiveTime > 5) + { + MEDLogFile.flush(); + MEDLogFile.close(); + } + + } + + MED_oldFED = FzadED; + } + + Timer::subsystem.vehicles_ai.start(); + Mechanik->Update(dt1); // przebłyski świadomości AI + Timer::subsystem.vehicles_ai.stop(); + } + + // fragment "z EXE Kursa" + if( MoverParameters->Mains ) { // nie wchodzić w funkcję bez potrzeby + if( false == (MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable) +/* + // NOTE: disabled on account of multi-unit setups, where the unmanned unit wouldn't be affected + && ( Controller == Humandriver ) +*/ + && MoverParameters->EngineType != TEngineType::DieselEngine + && MoverParameters->EngineType != TEngineType::WheelsDriven ) { // jeśli bateria wyłączona, a nie diesel ani drezyna reczna + if( MoverParameters->MainSwitch( false, MoverParameters->TrainType == train_type::emu ? range_t::unit : range_t::local ) ) { + // wyłączyć zasilanie + // NOTE: we turn off entire EMU, but only the affected unit for other multi-unit consists + MoverParameters->EventFlag = true; + // drop pantographs + // NOTE: this isn't universal behaviour + // TODO: have this dependant on .fiz-driven flag + // NOTE: moved to pantspeed calculation part a little later in the function. all remarks and todo still apply +/* + MoverParameters->PantFront( false, ( MoverParameters->TrainType == train_type::emu ? range::unit : range::local ) ); + MoverParameters->PantRear( false, ( MoverParameters->TrainType == train_type::emu ? range::unit : range::local ) ); +*/ + } + } + } + + // przekazanie pozycji do fizyki + // NOTE: coordinate system swap + // TODO: replace with regular glm vectors + TLocation const l { + -vPosition.x, + vPosition.z, + vPosition.y }; + TRotation const r { + 0.0, + 0.0, + modelRot.z }; + // McZapkie-260202 - dMoveLen przyda sie przy stukocie kol + dDOMoveLen = GetdMoveLen() + MoverParameters->ComputeMovement(dt, dt1, ts, tp, tmpTraction, l, r); + if( Mechanik ) { + // dodanie aktualnego przemieszczenia + Mechanik->MoveDistanceAdd( dDOMoveLen ); + } + if( simulation::Train != nullptr + && simulation::Train->Dynamic() == this ) { + // update distance meter in user-controlled cab + // TBD: place the meter on mover logic level? + simulation::Train->add_distance( dDOMoveLen ); + } + // physics.derailment new: derailed, the vehicle leaves the track and goes on the ground + if( MoverParameters->leaves_track() ) { + begin_off_track(); + } + m_offtracktime = dt1; + glm::dvec3 old_pos = vPosition; + Move(dDOMoveLen); + update_off_track( dt1 ); + + m_future_movement = (vPosition - old_pos) / dt1 * Timer::GetDeltaRenderTime(); + + if (!bEnabled) // usuwane pojazdy nie mają toru + { // pojazd do usunięcia + bDynamicRemove = true; // sprawdzić + return false; + } + ResetdMoveLen(); + + // McZapkie-260202 + // tupot mew, tfu, stukot kol: + if( MyTrack->fSoundDistance != -1 ) { + + if( MyTrack->fSoundDistance != dRailLength ) { + if( dRailLength > 0.0 ) { + for( auto &axle : m_axlesounds ) { + axle.distance = axle.offset; + axle.atjoints = false; + } + } + dRailLength = MyTrack->fSoundDistance; + } + if( dRailLength > 0.0 ) { + if( MoverParameters->Vel > 0 ) { + // TODO: track quality and/or environment factors as separate subroutine + auto volume = + std::lerp( + 0.8, 1.2, + std::clamp( + MyTrack->iQualityFlag / 10.0, + 0.0, 1.5 ) ); + switch( MyTrack->eEnvironment ) { + case e_tunnel: { + volume *= 1.3; + break; + } + case e_bridge: { + volume *= 1.5; + break; + } + default: { + break; + } + } + if( dRailLength > 0.0 ) { + auto axleindex { 0 }; + auto const directioninconsist { ( + ctOwner == nullptr ? + 1 : + ctOwner->Vehicle()->DirectionGet() == DirectionGet() ? 1 : -1 ) }; + for( auto &axle : m_axlesounds ) { + if( axle_passed_joint( axle, dDOMoveLen, directioninconsist ) + && MoverParameters->Vel > 0.1 ) { + // NOTE: for combined clatter sound we supply 1/100th of actual value, as the sound module converts does the opposite, converting received (typically) 0-1 values to 0-100 range + auto const frequency = true == axle.clatter.is_combined() ? MoverParameters->Vel * 0.01 : 1.0; + axle.clatter + .pitch( frequency ) + .gain( volume ) + .play(); + // crude bump simulation, drop down on even axles, move back up on + // the odd ones + // MoverParameters->AccVert += (MoverParameters->Vel*0.1f) * + // the arguments keep the order they had up to 26.05.1, 0 in place of the value and the figure in place of the + // upper limit, so they work out as the old clamp worked them out up to 26.05.1: the headroom is + // Vmax - (Vel + 0.32 Vmax) whatever its sign, and the bump is capped from above only + double const headroom = safe_clamp( 0.0, MoverParameters->Vmax, MoverParameters->Vmax - ( MoverParameters->Vel + MoverParameters->Vmax * 0.32f ) ); + double const jolt = headroom * .05f * ( MyTrack->iDamageFlag * 0.25f ); + if (MyTrack->eType == tt_Normal) + { + MoverParameters->AccVert += safe_clamp( 0.0, 4.0, jolt ); + } + else if (MyTrack->eType == tt_Switch) + { + double const accHorizontal = safe_clamp( 0.0, 1.0, jolt ) * ((axleindex % 2) != 0 ? 1 : -1); + MoverParameters->AccS += accHorizontal; + MoverParameters->AccN += accHorizontal; + MoverParameters->AccVert += safe_clamp( 0.0, 2.0, jolt ); + } + } + ++axleindex; + } + } + } + } + } + // McZapkie-260202 end + + // fragment z EXE Kursa + /* if (MoverParameters->TrainType==train_type::et42) + { + if ((MoverParameters->DynamicBrakeType=dbrake_switch) && + ((MoverParameters->BrakePress > + 0.2) || ( MoverParameters->PipePress < 0.36 ))) + { + MoverParameters->StLinFlag=true; + } + else + if ((MoverParameters->DynamicBrakeType=dbrake_switch) && + (MoverParameters->BrakePress < + 0.1)) + { + MoverParameters->StLinFlag=false; + + } + } */ + + if (MoverParameters->Vel != 0) + { // McZapkie-050402: krecenie kolami: + glm::dvec3 old_wheels = glm::dvec3(dWheelAngle[0], dWheelAngle[1], dWheelAngle[2]); + + dWheelAngle[0] += 114.59155902616464175359630962821 * MoverParameters->V * dt1 / + MoverParameters->WheelDiameterL; // przednie toczne + dWheelAngle[1] += MoverParameters->nrot * dt1 * 360.0; // napędne + dWheelAngle[2] += 114.59155902616464175359630962821 * MoverParameters->V * dt1 / + MoverParameters->WheelDiameterT; // tylne toczne + + + m_future_wheels_angle = (glm::dvec3(dWheelAngle[0], dWheelAngle[1], dWheelAngle[2]) - old_wheels) / dt1 * Timer::GetDeltaRenderTime(); + + dWheelAngle[0] = clamp_circular( dWheelAngle[0] ); + dWheelAngle[1] = clamp_circular( dWheelAngle[1] ); + dWheelAngle[2] = clamp_circular( dWheelAngle[2] ); + } + if (pants) // pantograf może być w wagonie kuchennym albo pojeździe rewizyjnym (np. SR61) + { // przeliczanie kątów dla pantografów + double k; // tymczasowy kąt + double PantDiff; + TAnimPant *p; // wskaźnik do obiektu danych pantografu + // prąd pobierany przez pojazd z sieci: trakcyjny (on the genset of a dual-mode vehicle none) i TotalCurrent + // TotalCurrent to bedzie prad nietrakcyjny (niezwiazany z napedem) + double fCurrent = MoverParameters->CatenaryCurrent(); + // fCurrent+=fabs(MoverParameters->Voltage)*1e-6; //prąd płynący przez woltomierz, rozładowuje kondensator orgromowy 4µF +/* + double fPantCurrent = fCurrent; // normalnie cały prąd przez jeden pantograf + if (iAnimType[ANIM_PANTS] > 1) { // a jeśli są dwa pantografy //Ra 1014-11: proteza, trzeba zrobić sensowniej + if (pants[0].fParamPants->hvPowerWire && pants[1].fParamPants->hvPowerWire) { // i oba podłączone do drutów + fPantCurrent = fCurrent * 0.5; // to dzielimy prąd równo na oba (trochę bez sensu, ale lepiej tak niż podwoić prąd) + } + } +*/ + // test whether more than one pantograph touches the wire + // NOTE: we're duplicating lot of code from below + // TODO: clean this up + auto activepantographs { 0 }; + for( int idx = 0; idx < iAnimType[ ANIM_PANTS ]; ++idx ) { + auto const *pantograph { pants[ idx ].fParamPants }; + if( Global.bLiveTraction == false ) { + if( pantograph->PantWys >= 1.2 ) { + ++activepantographs; + } + } + else { + if( pantograph->hvPowerWire != nullptr + && true == MoverParameters->Pantographs[end::front].is_active + && pantograph->PantTraction - pantograph->PantWys < 0.01 ) { // tolerancja niedolegania + ++activepantographs; + } + } + } + auto const fPantCurrent { fCurrent / std::max( 1, activepantographs ) }; + + for (int i = 0; i < iAnimType[ANIM_PANTS]; ++i) + { // pętla po wszystkich pantografach + p = pants[i].fParamPants; + if (p->PantWys < 0) + { // patograf został połamany, liczony nie będzie + if (p->fAngleL > p->fAngleL0) + p->fAngleL -= 0.2 * dt1; // nieco szybciej niż jak dla opuszczania + if (p->fAngleL < p->fAngleL0) + p->fAngleL = p->fAngleL0; // kąt graniczny + if (p->fAngleU < M_PI) + p->fAngleU += 0.5 * dt1; // górne się musi ruszać szybciej. + if (p->fAngleU > M_PI) + p->fAngleU = M_PI; + if (i & 1) // zgłoszono, że po połamaniu potrafi zostać zasilanie + MoverParameters->PantRearVolt = 0.0; + else + MoverParameters->PantFrontVolt = 0.0; + continue; // reszta wtedy nie jest wykonywana + } + PantDiff = p->PantTraction - p->PantWys; // docelowy-aktualny + switch (i) // numer pantografu + { // trzeba usunąć to rozróżnienie + case 0: + if (Global.bLiveTraction == false + && p->hvPowerWire == nullptr ) { + // jeśli nie ma drutu, może pooszukiwać + MoverParameters->PantFrontVolt = + p->PantWys >= 1.2 ? + 0.95 * MoverParameters->EnginePowerSource.MaxVoltage : + 0.0; + } + else if( true == MoverParameters->Pantographs[end::front].is_active + && PantDiff < 0.01 ) // tolerancja niedolegania + { + if (p->hvPowerWire) { + auto const lastvoltage { MoverParameters->PantFrontVolt }; + // TODO: wyliczyć trzeba prąd przypadający na pantograf i wstawić do GetVoltage() + if( lastvoltage == 0.0 ) { + // HACK: retrieve the wire voltage for calculations down the road without blowing up the supply + MoverParameters->PantFrontVolt = p->hvPowerWire->VoltageGet( MoverParameters->PantographVoltage, 0.0 ); + } + else { + MoverParameters->PantFrontVolt = p->hvPowerWire->VoltageGet( MoverParameters->PantographVoltage, fPantCurrent ); + if( MoverParameters->PantFrontVolt > 0.0 ) { + fCurrent -= fPantCurrent; // taki prąd płynie przez powyższy pantograf (unless it doesn't) + } + } + // TODO: refactor reaction to voltage change to mover as sound event for specific pantograph + if( lastvoltage == 0.0 + && MoverParameters->PantFrontVolt > 0.0 ) { + for( auto &pantograph : m_pantographsounds ) { + if( pantograph.sPantUp.offset().z > 0 ) { + // limit to pantographs located in the front half of the vehicle + pantograph.sPantUp.play( sound_flags::exclusive ); + } + } + } + } + else + MoverParameters->PantFrontVolt = 0.0; + } + else + MoverParameters->PantFrontVolt = 0.0; + ( fPantCurrent > 0.0 ? MoverParameters->EnergyMeter.first : MoverParameters->EnergyMeter.second ) += MoverParameters->PantRearVolt * fPantCurrent * dt1 / 3600000.0; + break; + case 1: + if( false == Global.bLiveTraction + && nullptr == p->hvPowerWire ) { + // jeśli nie ma drutu, może pooszukiwać + MoverParameters->PantRearVolt = + p->PantWys >= 1.2 ? + 0.95 * MoverParameters->EnginePowerSource.MaxVoltage : + 0.0; + } + else if ( true == MoverParameters->Pantographs[end::rear].is_active + && PantDiff < 0.01 ) + { + if (p->hvPowerWire) { + auto const lastvoltage { MoverParameters->PantRearVolt }; + // TODO: wyliczyć trzeba prąd przypadający na pantograf i wstawić do GetVoltage() + if( lastvoltage == 0.0 ) { + // HACK: retrieve the wire voltage for calculations down the road without blowing up the supply + MoverParameters->PantRearVolt = p->hvPowerWire->VoltageGet( MoverParameters->PantographVoltage, 0.0 ); + } + else { + MoverParameters->PantRearVolt = p->hvPowerWire->VoltageGet( MoverParameters->PantographVoltage, fPantCurrent ); + if( MoverParameters->PantRearVolt > 0.0 ) { + fCurrent -= fPantCurrent; // taki prąd płynie przez powyższy pantograf (unless it doesn't) + } + } + // TODO: refactor reaction to voltage change to mover as sound event for specific pantograph + if( lastvoltage == 0.0 + && MoverParameters->PantRearVolt > 0.0 ) { + for( auto &pantograph : m_pantographsounds ) { + if( pantograph.sPantUp.offset().z < 0 ) { + // limit to pantographs located in the rear half of the vehicle + pantograph.sPantUp.play( sound_flags::exclusive ); + } + } + } + } + else + MoverParameters->PantRearVolt = 0.0; + } + else { +// Global.iPause ^= 2; + MoverParameters->PantRearVolt = 0.0; + } + ( fPantCurrent > 0.0 ? MoverParameters->EnergyMeter.first : MoverParameters->EnergyMeter.second ) += MoverParameters->PantFrontVolt * fPantCurrent * dt1 / 3600000.0; + break; + } // pozostałe na razie nie obsługiwane + if( MoverParameters->PantPress > ( + MoverParameters->TrainType == train_type::emu ? + 2.45 : // Ra 2013-12: Niebugocław mówi, że w EZT podnoszą się przy 2.5 + 3.45 ) ) { + // z EXE Kursa + // Ra: wysokość zależy od ciśnienia !!! + pantspeedfactor = 0.015 * MoverParameters->PantPress * dt1; + } + else { + pantspeedfactor = 0.0; + } + if( false == ( MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable ) ) { + pantspeedfactor = 0.0; + } + pantspeedfactor = std::max( 0.0, pantspeedfactor ); + k = p->fAngleL; + if( pantspeedfactor > 0.0 + && MoverParameters->Pantographs[i].is_active )// jeśli ma być podniesiony + { + if (PantDiff > 0.001) // jeśli nie dolega do drutu + { // jeśli poprzednia wysokość jest mniejsza niż pożądana, zwiększyć kąt dolnego + // ramienia zgodnie z ciśnieniem + if (pantspeedfactor > + 0.55 * PantDiff) // 0.55 to około pochodna kąta po wysokości + k += 0.55 * PantDiff; // ograniczenie "skoku" w danej klatce + else + k += pantspeedfactor; // dolne ramię + // jeśli przekroczono kąt graniczny, zablokować pantograf + // (wymaga interwencji pociągu sieciowego) + } + else if (PantDiff < -0.001) { + // drut się obniżył albo pantograf podniesiony za wysoko + // jeśli wysokość jest zbyt duża, wyznaczyć zmniejszenie kąta + // jeśli zmniejszenie kąta jest zbyt duże, przejść do trybu łamania pantografu + // if (PantFrontDiff<-0.05) //skok w dół o 5cm daje złąmanie pantografu + k += 0.4 * PantDiff; // mniej niż pochodna kąta po wysokości + } // jeśli wysokość jest dobra, nic więcej nie liczyć + } + else + { // jeśli ma być na dole + if (k > p->fAngleL0) // jeśli wyżej niż położenie wyjściowe + k -= 0.15 * dt1; // ruch w dół + if (k < p->fAngleL0) + k = p->fAngleL0; // położenie minimalne + } + if (k != p->fAngleL) + { //żeby nie liczyć w kilku miejscach ani gdy nie potrzeba + if (k + p->fAngleU < M_PI) + { // o ile nie został osiągnięty kąt maksymalny + p->fAngleL = k; // zmieniony kąt + // wyliczyć kąt górnego ramienia z wzoru (a)cosinusowego + //=acos((b*cos()+c)/a) + // p->dPantAngleT=acos((1.22*cos(k)+0.535)/1.755); //górne ramię + p->fAngleU = acos((p->fLenL1 * cos(k) + p->fHoriz) / p->fLenU1); // górne ramię + // wyliczyć aktualną wysokość z wzoru sinusowego + // h=a*sin()+b*sin() + // wysokość całości + p->PantWys = p->fLenL1 * sin(k) + p->fLenU1 * sin(p->fAngleU) + p->fHeight; + } + } + } // koniec pętli po pantografach + // TBD, TODO: generate sound event during mover update instead? + if( MoverParameters->Pantographs[end::front].sound_event != MoverParameters->Pantographs[ end::front ].is_active ) { + if( MoverParameters->Pantographs[ end::front ].is_active ) { + // pantograph moving up + // TBD: add a sound? + } + else { + // pantograph dropping + for( auto &pantograph : m_pantographsounds ) { + if( pantograph.sPantDown.offset().z > 0 ) { + // limit to pantographs located in the front half of the vehicle + pantograph.sPantDown.play( sound_flags::exclusive ); + } + } + } + MoverParameters->Pantographs[ end::front ].sound_event = MoverParameters->Pantographs[ end::front ].is_active; + } + if( MoverParameters->Pantographs[ end::rear ].sound_event != MoverParameters->Pantographs[ end::rear ].is_active ) { + if( MoverParameters->Pantographs[ end::rear ].is_active ) { + // pantograph moving up + // TBD: add a sound? + } + else { + // pantograph dropping + for( auto &pantograph : m_pantographsounds ) { + if( pantograph.sPantDown.offset().z < 0 ) { + // limit to pantographs located in the front half of the vehicle + pantograph.sPantDown.play( sound_flags::exclusive ); + } + } + } + MoverParameters->Pantographs[ end::rear ].sound_event = MoverParameters->Pantographs[ end::rear ].is_active; + } + } + else if (MoverParameters->EnginePowerSource.SourceType == TPowerSource::InternalSource) + if (MoverParameters->EnginePowerSource.PowerType == TPowerType::SteamPower) + // if (smPatykird1[0]) + { // Ra: animacja rozrządu parowozu, na razie nieoptymalizowane + /* //Ra: tymczasowo wyłączone ze względu na porządkowanie animacji + pantografów + double fi,dx,c2,ka,kc; + double sin_fi,cos_fi; + double L1=1.6688888888888889; + double L2=5.6666666666666667; //2550/450 + double Lc=0.4; + double L=5.686422222; //2558.89/450 + double G1,G2,G3,ksi,sin_ksi,gam; + double G1_2,G2_2,G3_2; //kwadraty + //ruch tłoków oraz korbowodów + for (int i=0;i<=1;++i) + {//obie strony w ten sam sposób + fi=DegToRad(dWheelAngle[1]+(i?pant2x:pant1x)); //kąt obrotu koła dla + tłoka 1 + sin_fi=sin(fi); + cos_fi=cos(fi); + dx=panty*cos_fi+sqrt(panth*panth-panty*panty*sin_fi*sin_fi)-panth; + //nieoptymalne + if (smPatykird1[i]) //na razie zabezpieczenie + smPatykird1[i]->SetTranslate(float3(dx,0,0)); + ka=-asin(panty/panth)*sin_fi; + if (smPatykirg1[i]) //na razie zabezpieczenie + smPatykirg1[i]->SetRotateXYZ(vector3(RadToDeg(ka),0,0)); + //smPatykirg1[0]->SetRotate(float3(0,1,0),RadToDeg(fi)); //obracamy + //ruch drążka mimośrodkowego oraz jarzma + //korzystałem z pliku PDF "mm.pdf" (opis czworoboku + korbowo-wahaczowego): + //"MECHANIKA MASZYN. Szkic wykładu i laboratorium komputerowego." + //Prof. dr hab. inż. Jerzy Zajączkowski, 2007, Politechnika Łódzka + //L1 - wysokość (w pionie) osi jarzma ponad osią koła + //L2 - odległość w poziomie osi jarzma od osi koła + //Lc - długość korby mimośrodu na kole + //Lr - promień jarzma =1.0 (pozostałe przeliczone proporcjonalnie) + //L - długość drążka mimośrodowego + //fi - kąt obrotu koła + //ksi - kąt obrotu jarzma (od pionu) + //gam - odchylenie drążka mimośrodowego od poziomu + //G1=(Lr*Lr+L1*L1+L2*L2+Kc*Lc-L*L-2.0*Lc*L2*cos(fi)+2.0*Lc*L1*sin(fi))/(Lr*Lr); + //G2=2.0*(L2-Lc*cos(fi))/Lr; + //G3=2.0*(L1-Lc*sin(fi))/Lr; + fi=DegToRad(dWheelAngle[1]+(i?pant2x:pant1x)-96.77416667); //kąt + obrotu koła dla + tłoka 1 + //1) dla dWheelAngle[1]=0° korba jest w dół, a mimośród w stronę + jarzma, czyli + fi=-7° + //2) dla dWheelAngle[1]=90° korba jest do tyłu, a mimośród w dół, + czyli fi=83° + sin_fi=sin(fi); + cos_fi=cos(fi); + G1=(1.0+L1*L1+L2*L2+Lc*Lc-L*L-2.0*Lc*L2*cos_fi+2.0*Lc*L1*sin_fi); + G1_2=G1*G1; + G2=2.0*(L2-Lc*cos_fi); + G2_2=G2*G2; + G3=2.0*(L1-Lc*sin_fi); + G3_2=G3*G3; + sin_ksi=(G1*G2-G3*_fm_sqrt(G2_2+G3_2-G1_2))/(G2_2+G3_2); //x1 (minus + delta) + ksi=asin(sin_ksi); //kąt jarzma + if (smPatykirg2[i]) + smPatykirg2[i]->SetRotateXYZ(vector3(RadToDeg(ksi),0,0)); //obrócenie + jarzma + //1) ksi=-23°, gam= + //2) ksi=10°, gam= + //gam=acos((L2-sin_ksi-Lc*cos_fi)/L); //kąt od poziomu, liczony + względem poziomu + //gam=asin((L1-cos_ksi-Lc*sin_fi)/L); //kąt od poziomu, liczony + względem pionu + gam=atan2((L1-cos(ksi)+Lc*sin_fi),(L2-sin_ksi+Lc*cos_fi)); //kąt od + poziomu + if (smPatykird2[i]) //na razie zabezpieczenie + smPatykird2[i]->SetRotateXYZ(vector3(RadToDeg(-gam-ksi),0,0)); + //obrócenie drążka + mimośrodowego + } + */ + } + + if (MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector + && MoverParameters->EnginePowerSource.CollectorParameters.FakePower) { + MoverParameters->PantRearVolt = 0.95 * MoverParameters->EnginePowerSource.MaxVoltage; + MoverParameters->PantFrontVolt = 0.95 * MoverParameters->EnginePowerSource.MaxVoltage; + } + + // wipers + if (dWiperPos.size() > 0) // tylko dla wozow ze zdefiniowanymi wycierakami + { + for (int i = 0; i < dWiperPos.size(); i++) // iteracja po kazdej wycieraczce + { + bool wipersActive; + auto const bytesum = MoverParameters->WiperList[MoverParameters->wiperSwitchPos].byteSum; + // rozroznienie kabinowe + if (MoverParameters->CabActive == 1) + { + wipersActive = (bytesum & 1 << i) != 0 && MoverParameters->Battery; + } + else if (MoverParameters->CabActive == -1) + { + // odwroconie indexow wycieraczek + wipersActive = (bytesum & 1 << dWiperPos.size() - 1 - i) != 0 && MoverParameters->Battery; + } + else { + wipersActive = false; + } + + auto const currentWiperParams = MoverParameters->WiperList[workingSwitchPos[i]]; + + wiperOutTimer[i] += dt1; // aktualizujemy zegarek + wiperParkTimer[i] += dt1; // aktualizujemy zegarek + + if (wipersActive || dWiperPos[i] > 0.0) // zeby wrocily do trybu park + { + if (dWiperPos[i] > 0.0 && !wipersActive) // bezwzgledny powrot do zera + { + dWiperPos[i] = std::max(0.0, dWiperPos[i] - 1.f / currentWiperParams.WiperSpeed * dt1); + } + else { + + if (dWiperPos[i] < 1.0 && !wiperDirection[i] && wiperParkTimer[i] > currentWiperParams.interval) + // go out + { + if (!sWiperFromParkPlayed) + { + sWiperFromPark.play(sound_flags::exclusive); + sWiperFromParkPlayed = true; + } + dWiperPos[i] = std::min(1.0, dWiperPos[i] + 1.f / currentWiperParams.WiperSpeed * dt1); + } + if (dWiperPos[i] > 0.0 && wiperDirection[i] && wiperOutTimer[i] > currentWiperParams.outBackDelay) + // return back + { + if (!sWiperToParkPlayed) + { + sWiperToPark.play(sound_flags::exclusive); + sWiperToParkPlayed = true; + } + dWiperPos[i] = std::max(0.0, dWiperPos[i] - 1.f / currentWiperParams.WiperSpeed * dt1); + } + if (dWiperPos[i] >= 1.0) // we reached end + { + sWiperFromPark.stop(); + sWiperFromParkPlayed = false; + wiperParkTimer[i] = 0.0; + wiperDirection[i] = true; // switch direction + } + if (dWiperPos[i] <= 0.0) + { + // when in park position + sWiperToPark.stop(); + sWiperToParkPlayed = false; + wiperOutTimer[i] = 0.0; + wiperDirection[i] = false; + workingSwitchPos[i] = MoverParameters->wiperSwitchPos; // update configuration + } + + } + } + } + } + + + + // mirrors + auto const mirrorleft { dMirrorMoveL }; + auto const mirrorright { dMirrorMoveR }; + if( MoverParameters->Vel > MoverParameters->MirrorVelClose + || MoverParameters->CabActive == 0 && activation::mirrors + || MoverParameters->MirrorForbidden ) { + // automatically fold mirrors when above velocity threshold + if( dMirrorMoveL > 0.0 ) { + dMirrorMoveL = std::max( + 0.0, + dMirrorMoveL - 1.0 * dt1 ); + } + if( dMirrorMoveR > 0.0 ) { + dMirrorMoveR = std::max( + 0.0, + dMirrorMoveR - 1.0 * dt1 ); + } + } + else { + // unfold mirror on the side with open doors, if not moving too fast + if( dMirrorMoveL < 1.0 + && true == MoverParameters->Doors.instances[side::left].open_permit ) { + dMirrorMoveL = std::min( + 1.0, + dMirrorMoveL + 1.0 * dt1 ); + } + if( dMirrorMoveR < 1.0 + && true == MoverParameters->Doors.instances[side::right].open_permit ) { + dMirrorMoveR = std::min( + 1.0, + dMirrorMoveR + 1.0 * dt1 ); + } + } + play_mirror_sounds( side::left, m_mirrormotion[ side::left ].update( dMirrorMoveL - mirrorleft ) ); + play_mirror_sounds( side::right, m_mirrormotion[ side::right ].update( dMirrorMoveR - mirrorright ) ); + + // compartment lights + // if the vehicle has a controller, we base the light state on state of the controller otherwise we check the vehicle itself + if( ctOwner != nullptr ? SectionLightsActive != MoverParameters->CompartmentLights.is_active : + Mechanik != nullptr ? SectionLightsActive != MoverParameters->CompartmentLights.is_active : + SectionLightsActive ) { // without controller switch the lights off + toggle_lights(); + } + + if (MoverParameters->InactiveCabPantsCheck) + { + pants_up(); + MoverParameters->InactiveCabPantsCheck = false; + } + + if( MoverParameters->LoadStatus ) { + LoadUpdate(); // zmiana modelu ładunku + } + update_exchange( dt ); + + return true; // Ra: chyba tak? +} + +void TDynamicObject::pants_up() +{ + TDynamicObject *d = this; + bool isAnyPantUp = false; + while (d) { + for (auto &item : d->MoverParameters->Pantographs) + { + isAnyPantUp |= item.is_active; + } + d = d->Next(Coupling::control); // pozostałe też + } + d = Prev(Coupling::control); + while (d) { + for (auto &item : d->MoverParameters->Pantographs) + { + isAnyPantUp |= item.is_active; + } + d = d->Prev(Coupling::control); // w drugą stronę też + } + if (isAnyPantUp) + { + d = this; + while (d) { + d->MoverParameters->OperatePantographValve(end::front, operation_t::enable, range_t::local); + d->MoverParameters->OperatePantographValve(end::rear, operation_t::enable, range_t::local); + d = d->Next(Coupling::control); // pozostałe też + } + d = Prev(Coupling::control); + while (d) { + d->MoverParameters->OperatePantographValve(end::front, operation_t::enable, range_t::local); + d->MoverParameters->OperatePantographValve(end::rear, operation_t::enable, range_t::local); + d = d->Prev(Coupling::control); // w drugą stronę też + } + } +} + +// McZapkie-040402: liczenie pozycji uwzgledniajac wysokosc szyn itp. +// vector3 TDynamicObject::GetPosition() +//{//Ra: pozycja pojazdu jest liczona zaraz po przesunięciu +// return vPosition; +//}; + +void TDynamicObject::TurnOff() +{ // wyłączenie rysowania submodeli zmiennych dla + // egemplarza pojazdu + btnOn = false; + btCoupler1.TurnOff(); + btCoupler2.TurnOff(); + btCPneumatic1.TurnOff(); + btCPneumatic1r.TurnOff(); + btCPneumatic2.TurnOff(); + btCPneumatic2r.TurnOff(); + btPneumatic1.TurnOff(); + btPneumatic1r.TurnOff(); + btPneumatic2.TurnOff(); + btPneumatic2r.TurnOff(); + btCCtrl1.Turn( false ); + btCCtrl2.Turn( false ); + btCPass1.Turn( false ); + btCPass2.Turn( false ); + m_endsignal12.Turn( false ); + m_endsignal13.Turn( false ); + m_endsignal22.Turn( false ); + m_endsignal23.Turn( false ); + m_endsignals1.Turn( false ); + m_endsignals2.Turn( false ); + m_endtab1.Turn( false ); + m_endtab2.Turn( false ); + m_headlamp11.TurnOff(); + m_headlamp12.TurnOff(); + m_headlamp13.TurnOff(); + m_headlamp21.TurnOff(); + m_headlamp22.TurnOff(); + m_headlamp23.TurnOff(); + m_highbeam12.TurnOff(); + m_highbeam13.TurnOff(); + m_highbeam22.TurnOff(); + m_highbeam23.TurnOff(); + m_headsignal12.TurnOff(); + m_headsignal13.TurnOff(); + m_headsignal22.TurnOff(); + m_headsignal23.TurnOff(); + btMechanik1.Turn( false ); + btMechanik2.Turn( false ); + btShutters1.Turn( false ); + btShutters2.Turn( false ); +}; + +//--------------------------------------------------------------------------- +void TDynamicObject::RadioStop() +{ // zatrzymanie pojazdu + if( Mechanik ) { + // o ile ktoś go prowadzi + if( MoverParameters->SecuritySystem.radiostop_available() + && MoverParameters->Radio + && MoverParameters->RadioFuse ) { + // jeśli pojazd ma RadioStop i jest on aktywny + // HACK cast until math types unification + glm::dvec3 pos = static_cast(vPosition); + Mechanik->PutCommand( "Emergency_brake", 1.0, 1.0, &pos, stopRadio ); + // add onscreen notification for human driver + // TODO: do it selectively for the 'local' driver once the multiplayer is in + if( false == Mechanik->AIControllFlag ) { + ui::Transcripts.AddLine( "!! RADIO-STOP !!", 0.0, 10.0, false ); + } + } + } +}; + +//--------------------------------------------------------------------------- +void TDynamicObject::Damage(char flag) +{ + if (flag & 1) //różnicówka nie robi nic + { + MoverParameters->MainSwitch(false); + MoverParameters->FuseOff(); + } + else + { + } + + if (flag & 2) //usterka sterowania + { + MoverParameters->StLinFlag = false; + if (MoverParameters->InitialCtrlDelay<100000000) + MoverParameters->InitialCtrlDelay += 100000001; + } + else + { + if (MoverParameters->InitialCtrlDelay>100000000) + MoverParameters->InitialCtrlDelay -= 100000001; + } + + if (flag & 4) //blokada przetwornicy + { + if( MoverParameters->ConverterStart != start_t::disabled ) { + MoverParameters->ConvOvldFlag = true; + } + } + else + { + } + + if (flag & 8) //blokada sprezarki + { + if (MoverParameters->MinCompressor>0) + MoverParameters->MinCompressor -= 100000001; + if (MoverParameters->MaxCompressor>0) + MoverParameters->MaxCompressor -= 100000001; + } + else + { + if (MoverParameters->MinCompressor<0) + MoverParameters->MinCompressor += 100000001; + if (MoverParameters->MaxCompressor<0) + MoverParameters->MaxCompressor += 100000001; + } + + if (flag & 16) //blokada wału + { + if (MoverParameters->CtrlDelay<100000000) + MoverParameters->CtrlDelay += 100000001; + if (MoverParameters->CtrlDownDelay<100000000) + MoverParameters->CtrlDownDelay += 100000001; + } + else + { + if (MoverParameters->CtrlDelay>100000000) + MoverParameters->CtrlDelay -= 100000001; + if (MoverParameters->CtrlDownDelay>100000000) + MoverParameters->CtrlDownDelay -= 100000001; + } + + if (flag & 32) //hamowanie nagŁe + { + } + else + { + } + + MoverParameters->EngDmgFlag = flag; +}; + +void TDynamicObject::OverheadTrack(float o) +{ // ewentualne wymuszanie jazdy + // bezprądowej z powodu informacji + // w torze + if (ctOwner) // jeśli ma obiekt nadzorujący + { // trzeba zaktualizować mapę flag bitowych jazdy bezprądowej + if (o < 0.0) + { // normalna jazda po tym torze + ctOwner->iOverheadZero &= ~iOverheadMask; // zerowanie bitu - może pobierać prąd + ctOwner->iOverheadDown &= ~iOverheadMask; // zerowanie bitu - może podnieść pantograf + } + else if (o > 0.0) + { // opuszczenie pantografów + ctOwner->iOverheadZero |= iOverheadMask; // ustawienie bitu - ma jechać bez pobierania prądu + ctOwner->iOverheadDown |= iOverheadMask; // ustawienie bitu - ma opuścić pantograf + } + else + { // jazda bezprądowa z podniesionym pantografem + ctOwner->iOverheadZero |= iOverheadMask; // ustawienie bitu - ma jechać bez pobierania prądu + ctOwner->iOverheadDown &= ~iOverheadMask; // zerowanie bitu - może podnieść pantograf + } + } +}; diff --git a/vehicle/dynamic/vehicletable.cpp b/vehicle/dynamic/vehicletable.cpp new file mode 100644 index 000000000..7292576cc --- /dev/null +++ b/vehicle/dynamic/vehicletable.cpp @@ -0,0 +1,893 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// all the vehicles of the scenery and their update + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/mover.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + +namespace +{ + + +// a train on the same track this close to the end of the player's train is taken into the physical coupler model [m] +constexpr double coupler_physics_reach { 200.0 }; +// and let go of once none of its vehicles is this close to the player's train [m]; farther than the reach, so that +// the trains don't switch to and fro between the models +constexpr double coupler_physics_release { 500.0 }; + +// the vehicle and those coupled with it, one after the other +std::vector +coupled_train( TDynamicObject *Vehicle ) { + + std::vector train { Vehicle }; + for( int direction = end::front; direction <= end::rear; ++direction ) { + auto *vehicle { Vehicle }; + auto side { direction }; + // a train of more vehicles than are on the tracks would be one coupled into a ring + while( train.size() < 10000 ) { + auto const &mover { *vehicle->MoverParameters }; + auto *next { mover.Neighbours[ side ].vehicle }; + if( next == nullptr + || false == mover.Couplers[ side ].CouplingFlag.HasAny(Coupling::coupler) + || std::ranges::find( train, next ) != train.end() ) { + break; + } + train.emplace_back( next ); + // onwards from the end of the next vehicle away from this one + side = 1 - mover.Neighbours[ side ].vehicle_end; + vehicle = next; + } + } + return train; +} + +// the trains on the same track the player's train is closing in on: those found at its free ends, near enough +std::vector +trains_closing_in( std::vector const &Train ) { + + std::vector trains; + for( auto *vehicle : Train ) { + for( int side = end::front; side <= end::rear; ++side ) { + auto const &mover { *vehicle->MoverParameters }; + auto const &neighbour { mover.Neighbours[ side ] }; + if( neighbour.vehicle == nullptr + || mover.Couplers[ side ].CouplingFlag.HasAny(Coupling::coupler) + || neighbour.distance > coupler_physics_reach + || std::ranges::find( Train, neighbour.vehicle ) != Train.end() ) { + continue; + } + std::ranges::copy( coupled_train( neighbour.vehicle ), std::back_inserter( trains ) ); + } + } + return trains; +} + +// whether any vehicle of the train is within the distance of any vehicle of the other one +bool +trains_within( std::vector const &Train, std::vector const &Other, double const Distance ) { + + return std::ranges::any_of( Train, [&]( TDynamicObject const *Vehicle ) { + return std::ranges::any_of( Other, [&]( TDynamicObject const *Othervehicle ) { + return glm::distance( Vehicle->GetPosition(), Othervehicle->GetPosition() ) <= Distance; } ); } ); +} + +} // namespace + +// the physical coupler model covers the player's train and the trains it closes in on, on the same track; the others +// keep the legacy model, as the AI drives them in it +void +vehicle_table::update_coupler_physics() const { + + if( false == Global.coupler_physics + || true == Global.coupler_physics_all ) { + return; + } + auto *player { simulation::Train != nullptr ? simulation::Train->Dynamic() : nullptr }; + std::vector train; + if( player != nullptr ) { + train = coupled_train( player ); + } + std::unordered_set covered { train.begin(), train.end() }; + for( auto *vehicle : trains_closing_in( train ) ) { + covered.insert( vehicle ); + } + + std::unordered_set checked; + for( auto *vehicle : m_items ) { + if( covered.contains( vehicle ) ) { + vehicle->MoverParameters->CouplerPhysics = true; + continue; + } + if( false == vehicle->MoverParameters->CouplerPhysics + || checked.contains( vehicle ) ) { + continue; + } + // a train taken in before stays in the model until it's far from the player's one, all of it alike + auto const other { coupled_train( vehicle ) }; + checked.insert( other.begin(), other.end() ); + if( false == trains_within( other, train, coupler_physics_release ) ) { + for( auto *othervehicle : other ) { + othervehicle->MoverParameters->CouplerPhysics = false; + } + } + } +} + +// legacy method, calculates changes in simulation state over specified time +void +vehicle_table::update( double Deltatime, int Iterationcount ) { + // Ra: w zasadzie to trzeba by utworzyć oddzielną listę taboru do liczenia fizyki + // na którą by się zapisywały wszystkie pojazdy będące w ruchu + // pojazdy stojące nie potrzebują aktualizacji, chyba że np. ktoś im zmieni nastawę hamulca + // oddzielną listę można by zrobić na pojazdy z napędem, najlepiej posortowaną wg typu napędu + // what the update goes through, for the debug panel. the counts are of the last call in the frame + auto &counts { Timer::subsystem.vehicles }; + counts.all = static_cast( m_items.size() ); + counts.enabled = counts.road = counts.ai = counts.active = 0; + counts.kind = {}; + counts.standing = {}; + counts.awake = {}; + counts.steps += static_cast( std::max( Iterationcount, 1 ) ); + // the kind of each vehicle: rail or road, near the camera or farther. the time of each vehicle in the loops below goes to its + // kind, measured from the end of the one before it + static std::vector kinds; + kinds.resize( m_items.size() ); + // road vehicles far from the camera with nobody inside go by one step of the physics in the frame, as long as all the steps + // together (Global.physics_roadlod): their movement goes on, in coarser steps nobody is close enough to tell + // not in a network session: which vehicles go coarse depends on the camera of each machine, so their movement and the draws of + // Random() they make would part ways between the machines. nor with physics.fullphysics off, whose steps are long already: one + // step for all of them would be the time of the whole frame, with the collisions looked at once in it + static std::vector coarse; + coarse.assign( m_items.size(), 0 ); + auto const roadlod { + Global.physics_roadlod + && Global.FullPhysics + && 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 ) { + auto const *vehicle { m_items[ index ] }; + auto const road { ( vehicle->MoverParameters->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 == vehicle->bEnabled ) { continue; } + ++counts.kind[ kinds[ index ] ]; + auto const *mover { vehicle->MoverParameters }; + if( mover->Vel < 0.01 ) { + ++counts.standing[ kinds[ index ] ]; + if( ( false == road ) && mover->PhysicActivation ) { + // the test of TMoverParameters::ComputeTotalForce(), part by part + auto const moving = []( neighbour_data const &Neighbour ) { + return ( Neighbour.vehicle != nullptr ) + && ( ( Neighbour.vehicle->MoverParameters->Vel > 0.0001 ) || Neighbour.vehicle->MoverParameters->accelerating() ); }; + auto &awake { counts.awake }; + ++awake.vehicles; + if( mover->CabActive != 0 ) { ++awake.cab; } + if( mover->Vel > 0.0001 ) { ++awake.speed; } + if( mover->accelerating() ) { ++awake.acceleration; } + if( mover->LastSwitchingTime < 5 ) { ++awake.switching; } + if( mover->is_multiple_unit() ) { ++awake.multipleunit; } + if( moving( mover->Neighbours[ end::front ] ) || moving( mover->Neighbours[ end::rear ] ) ) { ++awake.neighbour; } + } + } + } + auto const lap = [ & ]( std::size_t const Index, std::array &Times, std::chrono::steady_clock::time_point &Mark ) { + auto const now { std::chrono::steady_clock::now() }; + if( Index < kinds.size() ) { + Times[ kinds[ Index ] ].add( std::chrono::duration( now - Mark ).count() ); + } + Mark = now; + }; + for( auto const *vehicle : m_items ) { + if( false == vehicle->bEnabled ) { continue; } + ++counts.enabled; + if( vehicle->MoverParameters->CategoryFlag & 2 ) { ++counts.road; } + if( ( vehicle->Mechanik != nullptr ) && vehicle->Mechanik->AIControllFlag ) { ++counts.ai; } + if( vehicle->MoverParameters->PhysicActivation || vehicle->MechInside ) { ++counts.active; } + } + + Timer::subsystem.vehicles_prepare.start(); + for( auto *vehicle : m_items ) { + if( false == vehicle->bEnabled ) { continue; } + // Ra: zmienić warunek na sprawdzanie pantografów w jednej zmiennej: czy pantografy i czy podniesione + if( vehicle->MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector ) { + update_traction( vehicle ); + } + vehicle->MoverParameters->ComputeConstans(); + vehicle->update_neighbours(); + } + update_coupler_physics(); + Timer::subsystem.vehicles_prepare.stop(); + Timer::subsystem.vehicles_forces.start(); + auto const totaltime { Deltatime * Iterationcount }; // całkowity czas + // the steps of the physics on many threads (Global.performance_multithreading), as many as the work is worth: a thread for each + // STEPS_PER_THREAD steps of vehicles with the physics on, up to all the cores. not in a network session (network.server, + // .client), which keeps the draws of Random() in step across the machines: the threads have engines of their own. the messages + // to external programs (Global.iMultiplayer) don't mind + auto constexpr STEPS_PER_THREAD { 128 }; + std::size_t work { 0 }; + for( std::size_t index = 0; index < m_items.size(); ++index ) { + auto const *vehicle { m_items[ index ] }; + if( vehicle->MoverParameters->PhysicActivation || vehicle->MechInside ) { + work += ( coarse[ index ] != 0 ? 1 : static_cast( std::max( Iterationcount, 1 ) ) ); + } + } + auto const network { ( false == Global.network_servers.empty() ) || Global.network_client.has_value() }; + auto const threads { ( + network ? + 1 : + std::min( worker_pool::capacity(), std::max( 1, ( work + STEPS_PER_THREAD / 2 ) / STEPS_PER_THREAD ) ) ) }; + // what keeps them in one thread, for the debug panel + counts.capacity = static_cast( worker_pool::capacity() ); + counts.singlethread = ( + false == Global.performance_multithreading ? std::string{ "performance.multithreading off" } : + network ? std::string{ "network session" } : + threads <= 1 ? std::string{ "too little work" } : + std::string{} ); + counts.threads = 1; + auto const parallel { ( threads > 1 ) && update_steps_parallel( Deltatime, Iterationcount, coarse, threads ) }; + if( parallel ) { + counts.threads = static_cast( threads ); + } + else { + if( threads > 1 ) { + counts.singlethread = "a vehicle coupled with one it doesn't see"; + } + auto mark { std::chrono::steady_clock::now() }; + if( Iterationcount > 1 ) { + // ABu: ponizsze wykonujemy tylko jesli wiecej niz jedna iteracja + for( int iteration = 0; iteration < Iterationcount - 1; ++iteration ) { + std::size_t index { 0 }; + for( auto *vehicle : m_items ) { + if( ( index >= coarse.size() ) || ( coarse[ index ] == 0 ) ) { + vehicle->UpdateForce( Deltatime ); + } + lap( index++, Timer::subsystem.vehicles_forces_kind, mark ); + } + index = 0; + for( auto *vehicle : m_items ) { + if( ( index >= coarse.size() ) || ( coarse[ index ] == 0 ) ) { + vehicle->FastUpdate( Deltatime ); + } + lap( index++, Timer::subsystem.vehicles_forces_kind, mark ); + } + update_brake_pipes( Deltatime ); + } + } + { + std::size_t index { 0 }; + for( auto *vehicle : m_items ) { + // the vehicles going by one step take it with the time of all of them + auto const coarsestep { ( index < coarse.size() ) && ( coarse[ index ] != 0 ) }; + vehicle->UpdateForce( coarsestep ? totaltime : Deltatime ); + lap( index++, Timer::subsystem.vehicles_forces_kind, mark ); + } + } + } + Timer::subsystem.vehicles_forces.stop(); + + update_off_track_contacts( totaltime ); + + Timer::subsystem.vehicles_update.start(); + { + std::size_t index { 0 }; + auto mark { std::chrono::steady_clock::now() }; + for( auto *vehicle : m_items ) { + auto const coarsestep { ( index < coarse.size() ) && ( coarse[ index ] != 0 ) }; + // Ra 2015-01: tylko tu przelicza sieć trakcyjną + vehicle->Update( coarsestep ? totaltime : Deltatime, totaltime ); + lap( index++, Timer::subsystem.vehicles_update_kind, mark ); + } + } + update_brake_pipes( Deltatime ); + Timer::subsystem.vehicles_update.stop(); + + // jeśli jest coś do usunięcia z listy, to trzeba na końcu + erase_disabled(); + + // the odometers are saved now and then, a crash doesn't lose more than the last minute + m_odometersavetimer += totaltime; + if( m_odometersavetimer >= 60.0 ) { + save_odometers(); + } +} +namespace +{ + + +// the body of the vehicle as it stands, for the contacts: off the track by its motion, on the track upright on it +derail_motion::footprint footprint_of( TDynamicObject const &Vehicle ) { + + auto const &mover { *Vehicle.MoverParameters }; + derail_motion::pose pose; + if( mover.OffTrack.active() ) { + pose = mover.OffTrack.current(); + } + else { + pose.position = Vehicle.GetPosition(); + pose.front = Vehicle.VectorFront(); + pose.left = Vehicle.VectorLeft(); + pose.up = Vehicle.VectorUp(); + } + auto const &shape { mover.OffTrack.shape() }; + return derail_motion::footprint_of( + pose, mover.Dim.L, + mover.OffTrack.active() ? shape.width : ( mover.Dim.W > 0.5 ? mover.Dim.W : 3.0 ), + mover.OffTrack.active() ? shape.height : ( mover.Dim.H > 2.0 ? mover.Dim.H : 4.0 ) ); +} + +// the vehicle as a body in a contact +derail_motion::contact_body contact_body_of( TDynamicObject const &Vehicle ) { + + auto const &mover { *Vehicle.MoverParameters }; + derail_motion::contact_body body; + body.mass = mover.TotalMass; + if( mover.OffTrack.active() ) { + body.base = mover.OffTrack.base(); + body.velocity = mover.OffTrack.velocity(); + body.yaw_rate = mover.OffTrack.yaw_rate(); + body.gyration = mover.OffTrack.gyration(); + } + else { + // on the rails it goes along them only + glm::dvec3 const front { Vehicle.VectorFront().x, 0.0, Vehicle.VectorFront().z }; + auto const length { glm::length( front ) }; + body.guided = true; + body.guide = length > 1e-6 ? front / length : glm::dvec3 { 0.0, 0.0, 1.0 }; + body.base = Vehicle.GetPosition(); + body.velocity = body.guide * mover.V; + } + return body; +} + +// how the two came to overlap, for the log +std::string_view overlap_kind( TDynamicObject const &First, TDynamicObject const &Second ) { + + auto const offtrack { First.MoverParameters->OffTrack.active() && Second.MoverParameters->OffTrack.active() }; + for( int end = end::front; end <= end::rear; ++end ) { + if( First.MoverParameters->Couplers[ end ].Connected == Second.MoverParameters + && First.MoverParameters->Couplers[ end ].CouplingFlag != Coupling::none ) { + return offtrack ? "coupled, both off the track" : "coupled, one on the rails"; + } + if( First.MoverParameters->Neighbours[ end ].vehicle == &Second ) { + return offtrack ? "neighbours, both off the track" : "neighbours, one on the rails"; + } + } + return offtrack ? "not neighbours, both off the track" : "not neighbours, one on the rails"; +} + +} // namespace + +void +vehicle_table::update_off_track_contacts( double const Deltatime ) { + + if( Global.derailment != global_settings::derailment_model::physical || Deltatime <= 0.0 ) { + return; + } + // by their places in the table: the order the pairs are taken in is the same in every run + std::vector offtrack; + for( std::size_t index = 0; index < m_items.size(); ++index ) { + if( m_items[ index ]->bEnabled && m_items[ index ]->MoverParameters->OffTrack.active() ) { + offtrack.push_back( index ); + } + } + if( offtrack.empty() ) { + return; + } + auto const started { off_track_clock::now() }; + auto deepest { 0.0 }; + std::string deepestpair; + auto resting { true }; + for( auto const place : offtrack ) { + auto *vehicle { m_items[ place ] }; + resting = resting && vehicle->MoverParameters->OffTrack.at_rest(); + auto const print { footprint_of( *vehicle ) }; + auto const reach { std::hypot( print.half_length, print.half_width ) }; + for( std::size_t otherplace = 0; otherplace < m_items.size(); ++otherplace ) { + auto *other { m_items[ otherplace ] }; + if( otherplace == place || false == other->bEnabled ) { + continue; + } + // each pair of two off the track once + auto const otheroff { other->MoverParameters->OffTrack.active() }; + if( otheroff && otherplace < place ) { + continue; + } + // the bounding circles first + auto const apart { other->GetPosition() - vehicle->GetPosition() }; + auto const otherreach { 0.5 * other->MoverParameters->Dim.L + std::max( other->MoverParameters->Dim.W, other->MoverParameters->Dim.H ) }; + if( glm::length( glm::dvec3 { apart.x, 0.0, apart.z } ) > reach + otherreach + 1.0 ) { + continue; + } + auto const otherprint { footprint_of( *other ) }; + auto const hit { derail_motion::collide( print, otherprint ) }; + if( false == hit.has_value() ) { + continue; + } + if( hit->depth > deepest ) { + deepest = hit->depth; + deepestpair = std::format( "{} and {}, {}", vehicle->MoverParameters->Name, other->MoverParameters->Name, overlap_kind( *vehicle, *other ) ); + } + auto const body { contact_body_of( *vehicle ) }; + auto const otherbody { contact_body_of( *other ) }; + auto const impulse { derail_motion::contact_impulse( *hit, body, otherbody ) }; + // the one off the track: kicked, and moved out of the other one (half of the way when both are off it) + auto const [ velocity, yawrate ] { derail_motion::impulse_change( body, -impulse, hit->point ) }; + auto &motion { vehicle->MoverParameters->OffTrack }; + auto const share { otheroff ? 0.5 : 1.0 }; + auto const correction { derail_motion::contact_correction * std::max( 0.0, hit->depth - derail_motion::contact_slop ) }; + if( glm::length( impulse ) > 0.0 ) { + motion.kick( velocity, yawrate ); + vehicle->MoverParameters->V = motion.speed(); + } + if( correction > 0.0 ) { + motion.nudge( -hit->normal * ( share * correction ) ); + vehicle->place_off_track(); + } + if( otheroff ) { + auto const [ othervelocity, otheryawrate ] { derail_motion::impulse_change( otherbody, impulse, hit->point ) }; + auto &othermotion { other->MoverParameters->OffTrack }; + if( glm::length( impulse ) > 0.0 ) { + othermotion.kick( othervelocity, otheryawrate ); + other->MoverParameters->V = othermotion.speed(); + } + if( correction > 0.0 ) { + othermotion.nudge( hit->normal * ( share * correction ) ); + other->place_off_track(); + } + continue; + } + // one on the rails: along them into its speed, across them on its wheels, as a coupling pulls them off + auto &othermover { *other->MoverParameters }; + othermover.V += glm::dot( impulse, otherbody.guide ) / std::max( othermover.TotalMass, 1.0 ); + if( othermover.DamageFlag.HasAll(VehicleDamage::derailed) ) { + continue; + } + glm::dvec3 const otherleft { otherbody.guide.z, 0.0, -otherbody.guide.x }; + auto const across { glm::dot( impulse, otherleft ) / Deltatime }; + auto const mass { othermover.TotalMass - othermover.Mred }; + auto const ratio { derail_motion::pull_ratio( std::abs( across ), 0.5 * std::numbers::pi, mass, othermover.NAxles ) }; + // held over the window of the climbing as the bodies slide along each other, or a hit three times as hard + // at once: the wheels jump the rail + auto const sliding { glm::length( derail_motion::velocity_at( body, hit->point ) - otherbody.velocity ) * Deltatime }; + if( other->m_struck.update( ratio >= derailment::climbing_limit, sliding ) || ratio >= 3.0 * derailment::climbing_limit ) { + othermover.pull_off( + across >= 0.0 ? 1 : -1, + mass > 0.0 ? std::abs( across ) / mass : 0.0, + std::format( "Y/Q {:.2f} from {} running into it, {:.0f} kN across", ratio, vehicle->MoverParameters->Name, std::abs( across ) / 1000.0 ) ); + other->m_struck.reset(); + } + } + } + // the log: every second the most the bodies overlapped by, once more when all of them are at rest + if( deepest > m_overlapmost ) { + m_overlapmost = deepest; + m_overlappair = deepestpair; + } + m_overlapdue -= Deltatime; + if( ( m_overlapdue <= 0.0 && false == resting ) || ( resting && false == m_overlaplogged ) ) { + WriteLog( std::format( + "derailment: the bodies overlap by up to {:.2f} m{} over the last second, {:.2f} m now{}", + m_overlapmost, m_overlapmost > 0.0 ? " (" + m_overlappair + ")" : std::string {}, deepest, resting ? ", all at rest" : "" ) ); + m_overlapmost = 0.0; + m_overlappair.clear(); + m_overlapdue = 1.0; + m_overlaplogged = resting; + } + if( false == resting ) { + m_overlaplogged = false; + } + auto const took { seconds_since( started ) }; + if( took > off_track_slow ) { + ErrorLog( std::format( "derailment: warning: the contacts of {} vehicles off the track took {:.0f} ms", offtrack.size(), took * 1000.0 ) ); + } +} + +std::shared_ptr +vehicle_table::off_track_terrain( glm::dvec2 const &Min, glm::dvec2 const &Max ) { + + std::erase_if( m_offtrackterrains, []( auto const &Terrain ) { return Terrain.expired(); } ); + for( auto const &terrain : m_offtrackterrains ) { + if( auto shared { terrain.lock() }; shared != nullptr && shared->covers( Min, Max ) ) { + return shared; + } + } + return {}; +} + +void +vehicle_table::share_off_track_terrain( std::shared_ptr const &Terrain ) { + + if( Terrain != nullptr ) { + m_offtrackterrains.emplace_back( Terrain ); + } +} + +// the air exchange through the brake and main reservoir hoses of the vehicles which stepped their physics, after all of them did +void +vehicle_table::update_brake_pipes( double const Deltatime ) { + + m_brakepipes.clear(); + for( auto *vehicle : m_items ) { + if( ( true == vehicle->MoverParameters->PipeCouplersPending ) + || ( true == vehicle->MoverParameters->ScndPipeCouplersPending ) ) { + m_brakepipes.push_back( vehicle->MoverParameters ); + } + } + TMoverParameters::UpdatePipeCouplers( m_brakepipes, Deltatime ); +} + +// records the odometer states of the vehicles and saves them for the next sessions (eu07/maszyna#72) +void +vehicle_table::save_odometers() { + + m_odometersavetimer = 0.0; + auto &odometers { odometer::states() }; + for( auto const *vehicle : m_items ) { + if( vehicle->MoverParameters != nullptr ) { + odometer::record( odometers, vehicle->name(), vehicle->MoverParameters->HasDriverCab(), vehicle->MoverParameters->Odometer ); + } + } + odometer::save(); +} + +// the steps of the physics of vehicle_table::update() (UpdateForce() and FastUpdate() of each vehicle, Iterationcount times) on up +// to Threads threads of worker_pool. a step acts on the vehicle itself, on the ones coupled with it, and on the ones seen ahead or +// behind it (CollisionDetect() changes the speed of the other one); the movement along the tracks, the events and the sounds wait +// for Update(). so the vehicles are put in groups which act on nothing outside them, and each group goes through all its steps in +// one thread, its vehicles in their order, the groups at once: what doing them one by one gives. the groups of vehicles exchanging +// their load, which can load the models of it, are done in the main thread. Coarse: as in update(). returns false, having done +// nothing, when a vehicle is coupled with one it doesn't see next to it, which the groups don't account for +bool +vehicle_table::update_steps_parallel( double const Deltatime, int const Iterationcount, std::vector const &Coarse, std::size_t const Threads ) { + + auto const itemcount { m_items.size() }; + for( std::size_t index = 0; index < itemcount; ++index ) { + m_items[ index ]->m_tableindex = static_cast( index ); + } + // the groups, by joining the vehicles with the ones they act on. the coupled ones are those next to them + m_groupparent.resize( itemcount ); + std::iota( std::begin( m_groupparent ), std::end( m_groupparent ), 0u ); + auto const root = [ this ]( std::uint32_t Index ) { + while( m_groupparent[ Index ] != Index ) { + m_groupparent[ Index ] = m_groupparent[ m_groupparent[ Index ] ]; + Index = m_groupparent[ Index ]; + } + return Index; }; + for( std::size_t index = 0; index < itemcount; ++index ) { + auto const *mover { m_items[ index ]->MoverParameters }; + for( auto const end : { end::front, end::rear } ) { + auto const *neighbour { mover->Neighbours[ end ].vehicle }; + if( ( mover->Couplers[ end ].Connected != nullptr ) + && ( ( neighbour == nullptr ) || ( neighbour->MoverParameters != mover->Couplers[ end ].Connected ) ) ) { + return false; + } + if( neighbour == nullptr ) { continue; } + auto const other { neighbour->m_tableindex }; + if( ( other >= itemcount ) || ( m_items[ other ] != neighbour ) ) { + // not in the table, shouldn't happen + return false; + } + auto const left { root( static_cast( index ) ) }; + auto const right { root( other ) }; + if( left != right ) { + m_groupparent[ std::max( left, right ) ] = std::min( left, right ); + } + } + } + auto constexpr none { std::numeric_limits::max() }; + m_groupof.assign( itemcount, none ); + std::size_t groupcount { 0 }; + for( std::size_t index = 0; index < itemcount; ++index ) { + auto &group { m_groupof[ root( static_cast( index ) ) ] }; + if( group == none ) { + group = static_cast( groupcount++ ); + if( m_groups.size() < groupcount ) { m_groups.emplace_back(); } + m_groups[ group ].clear(); + } + m_groups[ group ].push_back( static_cast( index ) ); + } + // the groups done in the main thread, and the others largest first, for the threads to end close to one another + m_threadgroups.clear(); + m_maingroups.clear(); + std::size_t largest { 0 }; + for( std::size_t group = 0; group < groupcount; ++group ) { + largest = std::max( largest, m_groups[ group ].size() ); + auto const loading { std::any_of( + std::begin( m_groups[ group ] ), std::end( m_groups[ group ] ), + [ this ]( std::uint32_t const Index ) { + auto const *vehicle { m_items[ Index ] }; + return ( vehicle->MoverParameters->LoadStatus != 0 ) || ( vehicle->LoadExchangeTime() > 0.f ); } ) }; + ( loading ? m_maingroups : m_threadgroups ).push_back( static_cast( group ) ); + } + std::sort( + std::begin( m_threadgroups ), std::end( m_threadgroups ), + [ this ]( std::uint32_t const Left, std::uint32_t const Right ) { + return m_groups[ Left ].size() > m_groups[ Right ].size(); } ); + auto &counts { Timer::subsystem.vehicles }; + counts.groups = static_cast( groupcount ); + counts.largestgroup = static_cast( largest ); + counts.maingroups = static_cast( m_maingroups.size() ); + + // all the steps of a group, in the order update() makes them + auto const totaltime { Deltatime * Iterationcount }; + auto const coarse = [ & ]( std::uint32_t const Index ) { + return ( Index < Coarse.size() ) && ( Coarse[ Index ] != 0 ); }; + // the draws of Random() a group makes come from an engine of its own, seeded from the run's engine and the group: the same in + // every run of a seed, whichever thread takes the group (the engines of the threads are seeded at random) + 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 ); + // 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; + if( Iterationcount > 1 ) { + // ABu: ponizsze wykonujemy tylko jesli wiecej niz jedna iteracja + for( int iteration = 0; iteration < Iterationcount - 1; ++iteration ) { + for( auto const index : members ) { + if( false == coarse( index ) ) { m_items[ index ]->UpdateForce( Deltatime ); } + } + for( auto const index : members ) { + if( false == coarse( index ) ) { m_items[ index ]->FastUpdate( Deltatime ); } + } + pipes.clear(); + for( auto const index : members ) { + auto *mover { m_items[ index ]->MoverParameters }; + if( mover->PipeCouplersPending || mover->ScndPipeCouplersPending ) { + pipes.push_back( mover ); + } + } + TMoverParameters::UpdatePipeCouplers( pipes, Deltatime ); + } + } + for( auto const index : members ) { + // 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 ); }; + + Workers().run( + m_threadgroups.size(), Threads, + [ & ]( std::size_t const Group ) { + steps( m_threadgroups[ Group ] ); } ); + for( auto const group : m_maingroups ) { + steps( group ); + } + return true; +} + +// legacy method, checks for presence and height of traction wire for specified vehicle +void +vehicle_table::update_traction( TDynamicObject *Vehicle ) { + auto const vFront = Vehicle->VectorFront(); // wektor normalny dla płaszczyzny ruchu pantografu + auto const vUp = Vehicle->VectorUp(); // wektor pionu pudła (pochylony od pionu na przechyłce) + auto const vLeft = Vehicle->VectorLeft(); // wektor odległości w bok (odchylony od poziomu na przechyłce) + auto const position = Vehicle->GetPosition(); // współrzędne środka pojazdu + + for( int pantographindex = 0; pantographindex < Vehicle->iAnimType[ ANIM_PANTS ]; ++pantographindex ) { + // pętla po pantografach + auto *pantograph { Vehicle->pants[ pantographindex ].fParamPants }; + if( true == Vehicle->MoverParameters->Pantographs[ pantographindex ].is_active ) { + // jeśli pantograf podniesiony + auto const pant0 { position + vLeft * pantograph->vPos.z + vUp * pantograph->vPos.y + vFront * pantograph->vPos.x }; + if( pantograph->hvPowerWire != nullptr ) { + // jeżeli znamy drut z poprzedniego przebiegu + for( int attempts = 0; attempts < 30; ++attempts ) { + // sanity check. shouldn't happen in theory, but did happen in practice + if( pantograph->hvPowerWire == nullptr ) { break; } + + // powtarzane aż do znalezienia odpowiedniego odcinka na liście dwukierunkowej + if( pantograph->hvPowerWire->iLast & 0x3 ) { + // dla ostatniego i przedostatniego przęsła wymuszamy szukanie innego + // nie to, że nie ma, ale trzeba sprawdzić inne + pantograph->hvPowerWire = nullptr; + break; + } + if( pantograph->hvPowerWire->hvParallel ) { + // jeśli przęsło tworzy bieżnię wspólną, to trzeba sprawdzić pozostałe + // nie to, że nie ma, ale trzeba sprawdzić inne + pantograph->hvPowerWire = nullptr; + break; + } + // obliczamy wyraz wolny równania płaszczyzny (to miejsce nie jest odpowienie) + // podstawiamy równanie parametryczne drutu do równania płaszczyzny pantografu + // TODO: investigate this routine with reardriver/negative speed, does it picks the right wire? + auto const fRaParam = + -( glm::dot( pantograph->hvPowerWire->pPoint1, vFront ) - glm::dot( pant0, vFront ) ) + / glm::dot( pantograph->hvPowerWire->vParametric, vFront ); + + if( fRaParam < -0.001 ) { + // histereza rzędu 7cm na 70m typowego przęsła daje 1 promil + pantograph->hvPowerWire = pantograph->hvPowerWire->hvNext[ 0 ]; + continue; + } + if( fRaParam > 1.001 ) { + pantograph->hvPowerWire = pantograph->hvPowerWire->hvNext[ 1 ]; + continue; + } + // jeśli t jest w przedziale, wyznaczyć odległość wzdłuż wektorów vUp i vLeft + // punkt styku płaszczyzny z drutem (dla generatora łuku el.) + auto const vStyk { pantograph->hvPowerWire->pPoint1 + fRaParam * pantograph->hvPowerWire->vParametric }; + auto const vGdzie { vStyk - pant0 }; // wektor + // odległość w pionie musi być w zasięgu ruchu "pionowego" pantografu + // musi się mieścić w przedziale ruchu pantografu + auto const fVertical { glm::dot( vGdzie, vUp ) }; + // odległość w bok powinna być mniejsza niż pół szerokości pantografu + // to się musi mieścić w przedziale zależnym od szerokości pantografu + auto const fHorizontal { std::abs( glm::dot( vGdzie, vLeft ) ) - pantograph->fWidth }; + // jeśli w pionie albo w bok jest za daleko, to dany drut jest nieużyteczny + if( fHorizontal <= 0.0 ) { + // koniec pętli, aktualny drut pasuje + pantograph->PantTraction = fVertical; + break; + } + else { + // the wire is outside contact area and as of now we don't have good detection of parallel sections + // as such there's no guaratee there isn't parallel section present. + // therefore we don't bother checking if the wire is still within range of guide horns + // but simply force area search for potential better option + pantograph->hvPowerWire = nullptr; + break; + } + } + } + + if( pantograph->hvPowerWire == nullptr ) { + // look in the region for a suitable traction piece if we don't already have any + simulation::Region->update_traction( Vehicle, pantographindex ); + } + + if( pantograph->hvPowerWire == nullptr + && false == Global.bLiveTraction ) { + // jeśli drut nie znaleziony ale można oszukiwać to dajemy coś tam dla picu + Vehicle->pants[ pantographindex ].fParamPants->PantTraction = 1.4; + } + } + else { + // pantograph is down + pantograph->hvPowerWire = nullptr; + } + } +} + +// legacy method, sends list of vehicles over network +void +vehicle_table::DynamicList( bool const Onlycontrolled ) const { + // odesłanie nazw pojazdów dostępnych na scenerii (nazwy, szczególnie wagonów, mogą się powtarzać!) + for( auto const *vehicle : m_items ) { + if( false == Onlycontrolled + || vehicle->Mechanik != nullptr ) { + // same nazwy pojazdów + multiplayer::WyslijString( vehicle->asName, 6 ); + } + } + // informacja o końcu listy + multiplayer::WyslijString( "none", 6 ); +} + +// maintenance; removes from tracks consists with vehicles marked as disabled +bool +vehicle_table::erase_disabled() { + + if( false == TDynamicObject::bDynamicRemove ) { return false; } + + // go through the list and retrieve vehicles scheduled for removal... + type_sequence disabledvehicles; + for( auto *vehicle : m_items ) { + if( false == vehicle->bEnabled ) { + disabledvehicles.emplace_back( vehicle ); + } + } + // ...now propagate removal flag through affected consists... + for( auto *vehicle : disabledvehicles ) { + TDynamicObject *coupledvehicle { vehicle }; + while( ( coupledvehicle = coupledvehicle->Next() ) != nullptr ) { + coupledvehicle->bEnabled = false; + } + // (try to) run propagation in both directions, it's simpler than branching based on direction etc + coupledvehicle = vehicle; + while( ( coupledvehicle = coupledvehicle->Prev() ) != nullptr ) { + coupledvehicle->bEnabled = false; + } + } + // ...then actually remove all disabled vehicles... + auto vehicleiter = std::begin( m_items ); + while( vehicleiter != std::end( m_items ) ) { + + auto *vehicle { *vehicleiter }; + + if( true == vehicle->bEnabled ) { + ++vehicleiter; + } + else { + // the distance the vehicle ran goes in the odometer store now, it doesn't depend on the vehicle being + // kept on the list until the next save (eu07/maszyna#72) + if( vehicle->MoverParameters != nullptr ) { + odometer::record( odometer::states(), vehicle->name(), vehicle->MoverParameters->HasDriverCab(), vehicle->MoverParameters->Odometer ); + } + if( vehicle->MyTrack != nullptr + && true == vehicle->MyTrack->RemoveDynamicObject(vehicle) ) { + vehicle->MyTrack = nullptr; + } + if( simulation::Train != nullptr + && simulation::Train->Dynamic() == vehicle ) { + // clear potential train binding + // TBD, TODO: kill vehicle sounds + simulation::Train = nullptr; + } + simulation::Trains.purge(vehicle->name()); + // remove potential entries in the light array + simulation::Lights.remove( vehicle ); + simulation::Blackbox.vehicle_removed( vehicle ); +/* + // finally get rid of the vehicle and its record themselves + // BUG: deleting the vehicle leaves dangling pointers in event->Activator and potentially elsewhere + // TBD, TODO: either mark 'dead' vehicles with additional flag, or delete the references as well + SafeDelete( vehicle ); + vehicleiter = m_items.erase( vehicleiter ); +*/ + ++vehicleiter; // NOTE: instead of the erase in the disabled section + } + } + // ...and call it a day + TDynamicObject::bDynamicRemove = false; + + return true; +} diff --git a/vehicle/dynamic/visual.cpp b/vehicle/dynamic/visual.cpp new file mode 100644 index 000000000..16b196acc --- /dev/null +++ b/vehicle/dynamic/visual.cpp @@ -0,0 +1,780 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// how a vehicle shows: its model, its sway and its shake + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/mover.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + + +void TDynamicObject::ABuSetModelShake(glm::dvec3 mShake) +{ + modelShake = mShake; +}; + +// ABu 29.01.05 przeklejone z render i renderalpha: ********************* +void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) +{ // ABu290105: pozbierane i uporzadkowane powtarzajace + // sie rzeczy z Render i RenderAlpha + // dodatkowy warunek, if (ObjSqrDist<...) zeby niepotrzebnie nie zmianiec w + // obiektach, + // ktorych i tak nie widac + // NBMX wrzesien, MC listopad: zuniwersalnione + btnOn = false; // czy przywrócić stan domyślny po renderowaniu + + // the submodels set below are shared with whatever else is drawn with the same models + for( auto *model : { mdModel, mdLoad, mdLowPolyInt, mdKabina } ) { + if( model != nullptr ) { + model->state_changed(); + } + } + for( auto *model : mdAttachments ) { + if( model != nullptr ) { + model->state_changed(); + } + } + + if (mdLoad) // tymczasowo ładunek na poziom podłogi + if (vFloor.z > 0.0) + mdLoad->GetSMRoot()->SetTranslate(modelShake + vFloor); + + // model jest współdzielony przez pojazdy, a pora roku może się zmienić w trakcie symulacji + if (Global.UpdateMaterials) + on_season_update(); + + if (ObjSqrDist < 400 * 400 ) // gdy bliżej niż 400m + { + for( auto &animation : pAnimations ) { + // wykonanie kolejnych animacji + if( ObjSqrDist < animation.fMaxDist + && animation.yUpdate ) { + // jeśli zdefiniowana funkcja aktualizacja animacji (położenia submodeli + animation.yUpdate( &animation ); + } + } + update_slottedlevers(); + + if( mdModel != nullptr + && ObjSqrDist < 50 * 50 ) { + // gdy bliżej niż 50m + // ABu290105: rzucanie pudlem + // te animacje wymagają bananów w modelach! + mdModel->GetSMRoot()->SetTranslate(modelShake); + if (mdKabina) + mdKabina->GetSMRoot()->SetTranslate(modelShake); + if (mdLoad) + mdLoad->GetSMRoot()->SetTranslate(modelShake + vFloor); + if (mdLowPolyInt) + mdLowPolyInt->GetSMRoot()->SetTranslate(modelShake); + // ABu: koniec rzucania + // ABu011104: liczenie obrotow wozkow + ABuBogies(); + // Mczapkie-100402: rysowanie lub nie - sprzegow + // ABu-240105: Dodatkowy warunek: if (...).Render, zeby rysowal tylko jeden z polaczonych sprzegow + // display _on if connected with another vehicle and the coupling owner (render flag) + // display _xon if connected with another vehicle and not the coupling owner + // display _xon if not connected, but equipped with coupling adapter + // display _off if not connected, not equipped with coupling adapter or if _xon model is missing + if( MoverParameters->Couplers[ end::front ].CouplingFlag.HasAll(Coupling::coupler) ) { + if( MoverParameters->Couplers[ end::front ].Render ) { + btCoupler1.TurnOn(); + } + else { + btCoupler1.TurnxOnWithOffAsFallback(); + } + btnOn = true; + } + else { + if( true == MoverParameters->Couplers[ end::front ].has_adapter() ) { + btCoupler1.TurnxOnWithOffAsFallback(); + btnOn = true; + } + } + if( MoverParameters->Couplers[ end::rear ].CouplingFlag.HasAll(Coupling::coupler) ) { + if( MoverParameters->Couplers[ end::rear ].Render ) { + btCoupler2.TurnOn(); + } + else { + btCoupler2.TurnxOnWithOffAsFallback(); + } + btnOn = true; + } + else { + if( true == MoverParameters->Couplers[ end::rear ].has_adapter() ) { + btCoupler2.TurnxOnWithOffAsFallback(); + btnOn = true; + } + } + //******************************************************************************** + // przewody powietrzne j.w., ABu: decyzja czy rysowac tylko na podstawie + // 'render' - juz + // nie + // przewody powietrzne, yB: decyzja na podstawie polaczen w t3d + if (Global.bnewAirCouplers) + { + SetPneumatic(false, false); // wczytywanie z t3d ulozenia wezykow + SetPneumatic(true, false); // i zapisywanie do zmiennej + SetPneumatic(true, true); // ktore z nich nalezy + SetPneumatic(false, true); // wyswietlic w tej klatce + + if (MoverParameters->Couplers[end::front].CouplingFlag.HasAll(Coupling::brakeHose)) + { + switch (cp1) + { + case 1: + btCPneumatic1.TurnOn(); + break; + case 2: + btCPneumatic1.TurnxOn(); + break; + case 3: + btCPneumatic1r.TurnxOn(); + break; + case 4: + btCPneumatic1r.TurnOn(); + break; + } + btnOn = true; + } + + if (MoverParameters->Couplers[end::rear].CouplingFlag.HasAll(Coupling::brakeHose)) + { + switch (cp2) + { + case 1: + btCPneumatic2.TurnOn(); + break; + case 2: + btCPneumatic2.TurnxOn(); + break; + case 3: + btCPneumatic2r.TurnxOn(); + break; + case 4: + btCPneumatic2r.TurnOn(); + break; + } + btnOn = true; + } + + // przewody zasilajace, j.w. (yB) + if (MoverParameters->Couplers[end::front].CouplingFlag.HasAll(Coupling::mainHose)) + { + switch (sp1) + { + case 1: + btPneumatic1.TurnOn(); + break; + case 2: + btPneumatic1.TurnxOn(); + break; + case 3: + btPneumatic1r.TurnxOn(); + break; + case 4: + btPneumatic1r.TurnOn(); + break; + } + btnOn = true; + } + + if (MoverParameters->Couplers[end::rear].CouplingFlag.HasAll(Coupling::mainHose)) + { + switch (sp2) + { + case 1: + btPneumatic2.TurnOn(); + break; + case 2: + btPneumatic2.TurnxOn(); + break; + case 3: + btPneumatic2r.TurnxOn(); + break; + case 4: + btPneumatic2r.TurnOn(); + break; + } + btnOn = true; + } + } + //*********************************************************************************/ + else // po staremu ABu'oewmu + { + // przewody powietrzne j.w., ABu: decyzja czy rysowac tylko na podstawie + // 'render' + if (MoverParameters->Couplers[end::front].CouplingFlag.HasAll(Coupling::brakeHose)) + { + if (MoverParameters->Couplers[end::front].Render) + btCPneumatic1.TurnOn(); + else + btCPneumatic1r.TurnOn(); + btnOn = true; + } + + if (MoverParameters->Couplers[end::rear].CouplingFlag.HasAll(Coupling::brakeHose)) + { + if (MoverParameters->Couplers[end::rear].Render) + btCPneumatic2.TurnOn(); + else + btCPneumatic2r.TurnOn(); + btnOn = true; + } + + // przewody powietrzne j.w., ABu: decyzja czy rysowac tylko na podstawie + // 'render' + // //yB - zasilajace + if (MoverParameters->Couplers[0].CouplingFlag.HasAll(Coupling::mainHose)) + { + if (MoverParameters->Couplers[0].Render) + btPneumatic1.TurnOn(); + else + btPneumatic1r.TurnOn(); + btnOn = true; + } + + if (MoverParameters->Couplers[1].CouplingFlag.HasAll(Coupling::mainHose)) + { + if (MoverParameters->Couplers[1].Render) + btPneumatic2.TurnOn(); + else + btPneumatic2r.TurnOn(); + btnOn = true; + } + } + //*************************************************************/// koniec + // wezykow + // uginanie zderzakow + for (int i = 0; i < 2; ++i) { + + if( MoverParameters->Couplers[ i ].has_adapter() ) { + // HACK: if there's coupler adapter on this side, we presume there's additional distance put between vehicles + // which prevents buffers from clashing against each other (or the other vehicle doesn't have buffers to begin with) + continue; + } + + auto const dist { safe_clamp( MoverParameters->Couplers[ i ].Dist / 2.0, -MoverParameters->Couplers[ i ].DmaxB, 0.0 ) }; + + if( dist >= 0.0 ) { continue; } + + if( smBuforLewy[ i ] ) { + smBuforLewy[ i ]->SetTranslate( glm::vec3( dist, 0, 0 ) ); + } + if( smBuforPrawy[ i ] ) { + smBuforPrawy[ i ]->SetTranslate( glm::vec3( dist, 0, 0 ) ); + } + } + } // vehicle within 50m + + // Winger 160204 - podnoszenie pantografow + + // przewody sterowania ukrotnionego + if (MoverParameters->Couplers[0].CouplingFlag.HasAll(Coupling::control)) + { + btCCtrl1.Turn( true ); + btnOn = true; + } + // else btCCtrl1.TurnOff(); + if (MoverParameters->Couplers[1].CouplingFlag.HasAll(Coupling::control)) + { + btCCtrl2.Turn( true ); + btnOn = true; + } + // else btCCtrl2.TurnOff(); + // McZapkie-181103: mostki przejsciowe + if (MoverParameters->Couplers[0].CouplingFlag.HasAll(Coupling::gangway)) + { + btCPass1.Turn( true ); + btnOn = true; + } + // else btCPass1.TurnOff(); + if (MoverParameters->Couplers[1].CouplingFlag.HasAll(Coupling::gangway)) + { + btCPass2.Turn( true ); + btnOn = true; + } + // else btCPass2.TurnOff(); + if (MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable) + { // sygnaly konca pociagu + if (m_endsignals1.Active()) { + if (TestFlag(MoverParameters->iLights[end::front], light::redmarker_left | light::redmarker_right ) ) { + m_endsignals1.Turn( true ); + btnOn = true; + } + } + else { + if (TestFlag(MoverParameters->iLights[end::front], light::redmarker_left) && !HeadlightsAoff) + { + m_endsignal13.Turn( true ); + btnOn = true; + } + if (TestFlag(MoverParameters->iLights[end::front], light::redmarker_right) && !HeadlightsAoff) + { + m_endsignal12.Turn( true ); + btnOn = true; + } + } + if (m_endsignals2.Active()) { + if (TestFlag(MoverParameters->iLights[end::rear], light::redmarker_left | light::redmarker_right ) ) { + m_endsignals2.Turn( true ); + btnOn = true; + } + } + else { + if (TestFlag(MoverParameters->iLights[end::rear], light::redmarker_left) && !HeadlightsBoff) + { + m_endsignal23.Turn( true ); + btnOn = true; + } + if (TestFlag(MoverParameters->iLights[end::rear], light::redmarker_right) && !HeadlightsBoff) + { + m_endsignal22.Turn( true ); + btnOn = true; + } + } + } + // tablice blaszane: + if (TestFlag(MoverParameters->iLights[end::front], light::rearendsignals)) { + m_endtab1.Turn( true ); + btnOn = true; + } + // else btEndSignalsTab1.TurnOff(); + if (TestFlag(MoverParameters->iLights[end::rear], light::rearendsignals)) { + m_endtab2.Turn( true ); + btnOn = true; + } + // destination signs + update_destinations(); + // else btEndSignalsTab2.TurnOff(); + // McZapkie-181002: krecenie wahaczem (korzysta z kata obrotu silnika) + if (iAnimType[ANIM_LEVERS]) + for (int i = 0; i < 4; ++i) + if (smWahacze[i]) + smWahacze[i]->SetRotate(float3(1, 0, 0), + fWahaczeAmp * cos(MoverParameters->eAngle)); + + // cooling shutters + // NOTE: shutters display _on state when they're closed, _off otherwise + if( true == MoverParameters->dizel_heat.water.config.shutters + && false == MoverParameters->dizel_heat.zaluzje1 ) { + btShutters1.Turn( true ); + btnOn = true; + } + if( true == MoverParameters->dizel_heat.water_aux.config.shutters + && false == MoverParameters->dizel_heat.zaluzje2 ) { + btShutters2.Turn( true ); + btnOn = true; + } + + // only external models ( external_only_on / external_only_off ) + btExteriorOnly.Turn(!bDisplayCab); // display only when cab is not rendered + + if( false == bDisplayCab // edge case, lowpoly may act as a stand-in for the hi-fi cab, so make sure not to show the driver when inside + && Mechanik != nullptr + && Mechanik->action() != TAction::actSleep ) { + // rysowanie figurki mechanika + btMechanik1.Turn(MoverParameters->CabOccupied > 0); + btMechanik2.Turn( MoverParameters->CabOccupied < 0 ); + if( MoverParameters->CabOccupied != 0 ) { + btnOn = true; + } + } + + } // vehicle within 400m + + if( MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable ) + { // sygnały czoła pociagu //Ra: wyświetlamy bez + // ograniczeń odległości, by były widoczne z + // daleka + + if (TestFlag(MoverParameters->iLights[end::front], light::headlight_left) + && !HeadlightsAoff && !HighBeamLights) + { + if( DimHeadlights ) { + m_headlamp13.TurnxOnWithOnAsFallback(); + } + else { + m_headlamp13.TurnOn(); + } + btnOn = true; + } + if (TestFlag(MoverParameters->iLights[end::front], light::headlight_upper) + && !HeadlightsAoff) + { + if( DimHeadlights ) { + m_headlamp11.TurnxOnWithOnAsFallback(); + } + else { + m_headlamp11.TurnOn(); + } + btnOn = true; + } + if (TestFlag(MoverParameters->iLights[end::front], light::headlight_right) + && !HeadlightsAoff && !HighBeamLights) + { + if( DimHeadlights ) { + m_headlamp12.TurnxOnWithOnAsFallback(); + } + else { + m_headlamp12.TurnOn(); + } + btnOn = true; + } + // else btHeadSignals13.TurnOff(); + if (TestFlag(MoverParameters->iLights[end::rear], light::headlight_left) + && !HeadlightsBoff && !HighBeamLights) + { + if( DimHeadlights ) { + m_headlamp23.TurnxOnWithOnAsFallback(); + } + else { + m_headlamp23.TurnOn(); + } + btnOn = true; + } + if (TestFlag(MoverParameters->iLights[end::rear], light::headlight_upper) + && !HeadlightsBoff) + { + if( DimHeadlights ) { + m_headlamp21.TurnxOnWithOnAsFallback(); + } + else { + m_headlamp21.TurnOn(); + } + btnOn = true; + } + if (TestFlag(MoverParameters->iLights[end::rear], light::headlight_right) + && !HeadlightsBoff && !HighBeamLights) + { + if( DimHeadlights ) { + m_headlamp22.TurnxOnWithOnAsFallback(); + } + else { + m_headlamp22.TurnOn(); + } + btnOn = true; + } + // auxiliary lights + if (TestFlag(MoverParameters->iLights[end::front], light::auxiliary_left) && !HeadlightsAoff) + { + if( DimHeadlights ) { + m_headsignal13.TurnxOnWithOnAsFallback(); + } + else { + m_headsignal13.TurnOn(); + } + btnOn = true; + } + if (TestFlag(MoverParameters->iLights[end::front], light::auxiliary_right) && !HeadlightsAoff) + { + if( DimHeadlights ) { + m_headsignal12.TurnxOnWithOnAsFallback(); + } + else { + m_headsignal12.TurnOn(); + } + btnOn = true; + } + if (TestFlag(MoverParameters->iLights[end::rear], light::auxiliary_left) && !HeadlightsBoff) + { + if( DimHeadlights ) { + m_headsignal23.TurnxOnWithOnAsFallback(); + } + else { + m_headsignal23.TurnOn(); + } + btnOn = true; + } + if (TestFlag(MoverParameters->iLights[end::rear], light::auxiliary_right) && !HeadlightsBoff) + { + if( DimHeadlights ) { + m_headsignal22.TurnxOnWithOnAsFallback(); + } + else { + m_headsignal22.TurnOn(); + } + btnOn = true; + } + + // logika dlugich + if (TestFlag(MoverParameters->iLights[end::front], light::headlight_left) + && !HeadlightsAoff && HighBeamLights) + m_highbeam13.TurnxOnWithOnAsFallback(); + else + m_highbeam13.TurnOff(); + + if (TestFlag(MoverParameters->iLights[end::front], light::headlight_right) + && !HeadlightsAoff && HighBeamLights) + m_highbeam12.TurnxOnWithOnAsFallback(); + else + m_highbeam12.TurnOff(); + + // i to samo od dupy strony + if (TestFlag(MoverParameters->iLights[end::rear], light::headlight_left) + && !HeadlightsBoff && HighBeamLights) + m_highbeam23.TurnxOnWithOnAsFallback(); + else + m_highbeam23.TurnOff(); + + if (TestFlag(MoverParameters->iLights[end::rear], light::headlight_right) + && !HeadlightsBoff && HighBeamLights) + m_highbeam22.TurnxOnWithOnAsFallback(); + else + m_highbeam22.TurnOff(); + } + // interior light levels + auto sectionlightcolor { glm::vec4( 1.f ) }; + bool cabsection{ true }; + for( auto const §ion : Sections ) { + if( cabsection ) { + // check whether we're still processing cab sections + auto const §ionname { section.compartment->pName }; + cabsection &= sectionname.size() >= 4 && sectionname.starts_with("cab"); + } + // TODO: add cablight devices + auto const sectionlightlevel { section.light_level * ( cabsection ? 1.0f : MoverParameters->CompartmentLights.intensity ) }; + sectionlightcolor = glm::vec4( + sectionlightlevel == 0.f || Global.fLuminance > section.compartment->fLight ? + glm::vec3(240.f / 255.f) : // TBD: save and restore initial submodel diffuse instead of enforcing one? + InteriorLight, // TODO: per-compartment (type) light color + sectionlightlevel ); + section.compartment->SetLightLevel( sectionlightcolor, true ); + if( section.load != nullptr ) { + section.load->SetLightLevel( sectionlightcolor, true ); + } + } + // load chunks visibility + for( auto const §ion : Sections ) { + // section isn't guaranteed to have load model, so check that first + if( section.load == nullptr ) { continue; } + section.load->iVisible = section.load_chunks_visible > 0; + // if the section root isn't visible we can skip meddling with its children + if( false == section.load->iVisible ) { continue; } + // if the section root is visible set the state of section chunks + auto *sectionchunk { section.load->ChildGet() }; + auto visiblechunkcount { section.load_chunks_visible }; + while( sectionchunk != nullptr ) { + sectionchunk->iVisible = visiblechunkcount > 0; + --visiblechunkcount; + sectionchunk = sectionchunk->NextGet(); + } + } + + // driver cabs visibility + for( int cabidx = 0; cabidx < LowPolyIntCabs.size(); ++cabidx ) { + if( LowPolyIntCabs[ cabidx ] == nullptr ) { continue; } + LowPolyIntCabs[ cabidx ]->iVisible = mdKabina == nullptr ? true : // there's no hi-fi cab + bDisplayCab == false ? true : // we're in external view + simulation::Train == nullptr ? true : // not a player-driven vehicle, implies external view + simulation::Train->Dynamic() != this ? true : // not a player-driven vehicle, implies external view + JointCabs ? false : // internal view, all cabs share the model so hide them 'all' + simulation::Train->iCabn != cabidx; // internal view, hide occupied cab and show others + } +} + +void +TDynamicObject::update_shake( double const Timedelta ) { + + ShakeStateBefore = ShakeState; + // Ra: mechanik powinien być telepany niezależnie od pozycji pojazdu + // Ra: trzeba zrobić model bujania głową i wczepić go do pojazdu + + // Ra: tu by się przydało uwzględnić rozkład sił: + // - na postoju horyzont prosto, kabina skosem + // - przy szybkiej jeździe kabina prosto, horyzont pochylony + + // McZapkie: najpierw policzę pozycję w/m kabiny + + // ABu: rzucamy kabina tylko przy duzym FPS! + // Mala histereza, zeby bez przerwy nie przelaczalo przy FPS~17 + // Granice mozna ustalic doswiadczalnie. Ja proponuje 14:20 + if( Global.iSlowMotion == 0 ) { // musi być pełna prędkość + + glm::dvec3 shakevector; + if( MoverParameters->EngineType == TEngineType::DieselElectric + || MoverParameters->EngineType == TEngineType::DieselEngine ) { + if( std::abs( MoverParameters->enrot ) > 0.0 ) { + // engine vibration + shakevector.x += + std::sin(MoverParameters->eAngle * 4.0) * Timedelta * + EngineShake.scale + // fade in with rpm above threshold + * std::clamp( + ( MoverParameters->enrot - EngineShake.fadein_offset ) * EngineShake.fadein_factor, + 0.0, 1.0 ) + // fade out with rpm above threshold + * std::lerp( + 1.0, 0.0, + std::clamp( + ( MoverParameters->enrot - EngineShake.fadeout_offset ) * EngineShake.fadeout_factor, + 0.0, 1.0 ) ); + } + } + + if( HuntingShake.fadein_begin > 0.f + && true == MoverParameters->TruckHunting ) { + // hunting oscillation + HuntingAngle = clamp_circular( HuntingAngle + 4.0 * HuntingShake.frequency * Timedelta * MoverParameters->Vel, 360.0 ); + auto const huntingamount = + std::lerp( + 0.0, 1.0, + std::clamp( + ( MoverParameters->Vel - HuntingShake.fadein_begin ) / ( HuntingShake.fadein_end - HuntingShake.fadein_begin ), + 0.0, 1.0 ) ); + shakevector.x += + std::sin(glm::radians(HuntingAngle)) * Timedelta * HuntingShake.scale + * huntingamount; + IsHunting = huntingamount > 0.025; + } + + if (FreeFlyModeFlag) + shakevector *= 0; + + auto const iVel { std::min( GetVelocity(), 150.0 ) }; + // an uneven track shakes the cab by itself, in place of the sway drawn from the curve and the jolts drawn at random, as far as it does + auto const replaced { track_uneven::replaced_shake( MyTrack != nullptr ? MyTrack->uneven_underway() : track_uneven::amounts {} ) }; + if( iVel > 0.5 ) { + // acceleration-driven base shake + shakevector += glm::dvec3( + replaced.sway ? 0.0 : -MoverParameters->AccN * Timedelta * 5.0 * Global.ShakingMultiplierRL, // highlight side sway + -MoverParameters->AccVert * Timedelta * Global.ShakingMultiplierUD, + -MoverParameters->AccSVBased * Timedelta * 1.5 * Global.ShakingMultiplierBF); // accent acceleration/deceleration + // unevenness of the track under the outer axles + auto const ride { 0.5 * ( Axle0.UnevenBend() + Axle1.UnevenBend() ) * ( MoverParameters->V * MoverParameters->V ) }; + shakevector += glm::dvec3( + -glm::dot( ride, vLeft ) * Timedelta * 5.0 * Global.ShakingMultiplierRL, + -ride.y * Timedelta * Global.ShakingMultiplierUD, + 0.0 ); + } + + auto shake { 1.25 * ShakeSpring.ComputateForces( shakevector, ShakeState.offset ) }; + + if( false == replaced.jolts && LocalRandom( iVel ) > 25.0 ) { + // extra shake at increased velocity + shake += ShakeSpring.ComputateForces( + glm::dvec3( + ( LocalRandom( iVel * 2 ) - iVel ) / ( iVel * 2 * 4 ) * BaseShake.jolt_scale.x, + ( LocalRandom( iVel * 2 ) - iVel ) / ( iVel * 2 * 4 ) * BaseShake.jolt_scale.y, + ( LocalRandom( iVel * 2 ) - iVel ) / ( iVel * 2 * 4 ) * BaseShake.jolt_scale.z ) +// * (( 200 - DynamicObject->MyTrack->iQualityFlag ) * 0.0075 ) // scale to 75-150% based on track quality + * 1.25, + ShakeState.offset ); + } + shake *= 0.85; + + ShakeState.velocity -= ( shake + ShakeState.velocity * 100.0 ) * (double)( BaseShake.jolt_scale.x + BaseShake.jolt_scale.y + BaseShake.jolt_scale.z ) / 200.0; + + // McZapkie: + ShakeState.offset += ShakeState.velocity * Timedelta; + if( std::abs( ShakeState.offset.y ) > std::abs( BaseShake.jolt_limit ) ) { + ShakeState.velocity.y = -ShakeState.velocity.y; + } + } + else { // hamowanie rzucania przy spadku FPS + ShakeState.offset -= ShakeState.offset * std::min( Timedelta, 1.0 ); // po tym chyba potrafią zostać jakieś ułamki, które powodują zjazd + } +} + +bool +TDynamicObject::axle_passed_joint( axle_sounds &Axle, double const Move, int const Direction ) const { + + // from the follower on its side of the vehicle, as the two can be on different tracks. They stand fAxleDist apart, at the bogie pivots, and + // the offset of the axle is the place of its wheel set, so the two of a bogie come out half of ADist to either side of the pivot + auto const &follower { Axle.offset >= 0.0 ? Axle0 : Axle1 }; + if( auto const railphase { follower.RailPhase( Axle.offset - std::copysign( 0.5 * fAxleDist, Axle.offset ) ) }; railphase >= 0.0 ) { + // the rails under the axle, which aren't always those under the track the vehicle is on + auto const passed { Axle.atjoints && std::abs( railphase - Axle.distance ) > 0.5 * follower.GetTrack()->fSoundDistance }; + Axle.distance = railphase; + Axle.atjoints = true; + return passed; + } + Axle.atjoints = false; + Axle.distance += Move * Direction; + if( Axle.distance >= 0 && Axle.distance <= dRailLength ) { + return false; + } + Axle.distance = clamp_circular( Axle.distance, dRailLength ); + return true; +} + +std::pair +TDynamicObject::shake_angles() const { + + return shake_angles( ShakeState ); +} + +std::pair +TDynamicObject::shake_angles( shake_state const &State ) const { + + return { + std::atan( State.velocity.x * BaseShake.angle_scale.x ), + std::atan( State.velocity.z * BaseShake.angle_scale.z ) }; +} + +TDynamicObject::shake_state +TDynamicObject::shake_between( double const Fraction ) const { + + if( Fraction >= 1.0 ) { + return ShakeState; + } + auto const between { []( glm::dvec3 const &Before, glm::dvec3 const &After, double const Part ) { + return glm::dvec3 { + std::lerp( Before.x, After.x, Part ), + std::lerp( Before.y, After.y, Part ), + std::lerp( Before.z, After.z, Part ) }; } }; + auto const part { std::max( Fraction, 0.0 ) }; + return { + between( ShakeStateBefore.velocity, ShakeState.velocity, part ), + between( ShakeStateBefore.offset, ShakeState.offset, part ) }; +} From b108e91793e0a74c2c27bc7b67ada2f5e0279790 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sat, 28 Nov 2026 14:43:27 +0100 Subject: [PATCH 018/123] refactor(cab): vehicle/Train.cpp split into the files of its parts in vehicle/cab/ The 13 300 lines of the cab go into vehicle/cab/: cab.cpp the gauges, the buttons, the control mapping commandtable.cpp the table of the handlers of the commands train.cpp construction, the state, taking a vehicle, the trains of the scenery controllercommands.cpp the master, secondary and dynamic brake controllers brakecommands.cpp the brake handles, the sand, the EP brake cabcommands.cpp the reverser, the battery, the cab activation pantographcommands.cpp the pantographs and their compressor powercommands.cpp the line breaker, the traction motors, the relays auxiliarycommands.cpp the pumps, the genset, the converter, the compressor lightcommands.cpp the lights equipmentcommands.cpp the heating, the generic switches, the speed control, the inverters doorcommands.cpp the doors and the mirrors couplingcommands.cpp the couplings and the departure signalcommands.cpp the horns and the radios update.cpp the update of a step sounds.cpp the sounds screens.cpp the screens setup.cpp setting the cab up from its definition Every definition moved as it was, in its original order. The helpers used by several files (EU07_CONTROLLER_BASERETURNDELAY, is_hold_coil_lever) are in vehicle/cab/internal.h. 1144/1144 tests, golden traces exact against staging 62f7a29b. --- CMakeLists.txt | 22 +- vehicle/Train.cpp | 13345 --------------------------- vehicle/cab/auxiliarycommands.cpp | 1308 +++ vehicle/cab/brakecommands.cpp | 943 ++ vehicle/cab/cab.cpp | 235 + vehicle/cab/cabcommands.cpp | 650 ++ vehicle/cab/commandtable.cpp | 455 + vehicle/cab/controllercommands.cpp | 667 ++ vehicle/cab/couplingcommands.cpp | 230 + vehicle/cab/doorcommands.cpp | 694 ++ vehicle/cab/equipmentcommands.cpp | 515 ++ vehicle/cab/internal.h | 61 + vehicle/cab/lightcommands.cpp | 1580 ++++ vehicle/cab/pantographcommands.cpp | 608 ++ vehicle/cab/powercommands.cpp | 569 ++ vehicle/cab/screens.cpp | 173 + vehicle/cab/setup.cpp | 2041 ++++ vehicle/cab/signalcommands.cpp | 517 ++ vehicle/cab/sounds.cpp | 563 ++ vehicle/cab/train.cpp | 944 ++ vehicle/cab/update.cpp | 1461 +++ 21 files changed, 14234 insertions(+), 13347 deletions(-) delete mode 100644 vehicle/Train.cpp create mode 100644 vehicle/cab/auxiliarycommands.cpp create mode 100644 vehicle/cab/brakecommands.cpp create mode 100644 vehicle/cab/cab.cpp create mode 100644 vehicle/cab/cabcommands.cpp create mode 100644 vehicle/cab/commandtable.cpp create mode 100644 vehicle/cab/controllercommands.cpp create mode 100644 vehicle/cab/couplingcommands.cpp create mode 100644 vehicle/cab/doorcommands.cpp create mode 100644 vehicle/cab/equipmentcommands.cpp create mode 100644 vehicle/cab/internal.h create mode 100644 vehicle/cab/lightcommands.cpp create mode 100644 vehicle/cab/pantographcommands.cpp create mode 100644 vehicle/cab/powercommands.cpp create mode 100644 vehicle/cab/screens.cpp create mode 100644 vehicle/cab/setup.cpp create mode 100644 vehicle/cab/signalcommands.cpp create mode 100644 vehicle/cab/sounds.cpp create mode 100644 vehicle/cab/train.cpp create mode 100644 vehicle/cab/update.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 1d1532c6b..6b7c5686e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -82,7 +82,8 @@ file(GLOB HEADERS "*.h" "world/*.h" "vehicle/*.h" "vehicle/ai/*.h" -"vehicle/dynamic/*.h") +"vehicle/dynamic/*.h" +"vehicle/cab/*.h") set(GLOBAL_ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}") set(GLOBAL_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/global_include") @@ -166,7 +167,24 @@ set(SOURCES "world/catenary_catalog.cpp" "world/catenary_scene_objects.cpp" "world/TractionPower.cpp" -"vehicle/Train.cpp" +"vehicle/cab/auxiliarycommands.cpp" +"vehicle/cab/brakecommands.cpp" +"vehicle/cab/cab.cpp" +"vehicle/cab/cabcommands.cpp" +"vehicle/cab/commandtable.cpp" +"vehicle/cab/controllercommands.cpp" +"vehicle/cab/couplingcommands.cpp" +"vehicle/cab/doorcommands.cpp" +"vehicle/cab/equipmentcommands.cpp" +"vehicle/cab/lightcommands.cpp" +"vehicle/cab/pantographcommands.cpp" +"vehicle/cab/powercommands.cpp" +"vehicle/cab/screens.cpp" +"vehicle/cab/setup.cpp" +"vehicle/cab/signalcommands.cpp" +"vehicle/cab/sounds.cpp" +"vehicle/cab/train.cpp" +"vehicle/cab/update.cpp" "world/TrkFoll.cpp" "vehicle/AirCoupler.cpp" "model/AnimModel.cpp" diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp deleted file mode 100644 index fd55f58a9..000000000 --- a/vehicle/Train.cpp +++ /dev/null @@ -1,13345 +0,0 @@ -/* -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/. -*/ -/* - MaSzyna EU07 locomotive simulator - Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others - -*/ - -#include "stdafx.h" -#include "vehicle/Train.h" -#include "vehicle/horn.h" -#include "vehicle/linebreaker.h" -#include "vehicle/holdcoillever.h" -#include "vehicle/compartmentlightsswitch.h" -#include "vehicle/odometer.h" -#include "vehicle/mainctrlact.h" - -#include "utilities/Globals.h" -#include "simulation/simulation.h" -#include "simulation/blackboxrecorder.h" -#include "world/Event.h" -#include "simulation/simulationtime.h" -#include "vehicle/Camera.h" -#include "utilities/Logs.h" -#include "model/MdlMngr.h" -#include "model/Model3d.h" -#include "utilities/Timer.h" -#include "vehicle/Driver.h" -#include "vehicle/DynObj.h" -#include "world/mtable.h" -#include "Console.h" -#include "application/application.h" -#include "rendering/renderer.h" -#include "physics/mover.h" -#include -#include -#include -#include -#include -/* -namespace input { - -extern user_command command; - -} -*/ -void control_mapper::clear() -{ - - *this = control_mapper(); -} - -void control_mapper::insert(TGauge const &Gauge, std::string const &Label) -{ - - if (Gauge.SubModel != nullptr) - { - m_controlnames.try_emplace(Gauge.SubModel, Label); - } - if (Gauge.SubModelOn != nullptr) - { - m_controlnames.try_emplace(Gauge.SubModelOn, Label); - } - // the duplicate submodels of a control (duplicate: yes) work the control as well (eu07/maszyna#527) - for (auto const &mirror : Gauge.mirrors()) - { - insert(mirror, Label); - } - - m_names.emplace(Label); -} - -std::string control_mapper::find(TSubModel const *Control) const -{ - - auto const lookup = m_controlnames.find(Control); - if (lookup != m_controlnames.end()) - { - return lookup->second; - } - else - { - return ""; - } -} - -bool control_mapper::contains(std::string const &Control) const -{ - - return m_names.contains(Control); -} - -void TTrain::screen_entry::deserialize(cParser &Input) -{ - - while (true == deserialize_mapping(Input)) - { - // all work done by while() - } -} - -bool TTrain::screen_entry::deserialize_mapping(cParser &Input) -{ - // token can be a key or block end - auto const key{Input.getToken(true, "\n\r\t ,;[]")}; - - if (true == key.empty() || key == "}") - { - return false; - } - - if (key == "{") - { - script = Input.getToken(); - } - else if (key == "target:") - { - target = Input.getToken(); - } - else if (key == "updatetime:") - { - updatetime = Input.getToken(); - } - else if (key == "parameters:") - { - parameters = dictionary_source(Input.getToken()); - } - else - { - // HACK: we expect this to be true only if the screen entry doesn't start with a { which means legacy configuration format - target = key; - script = Input.getToken(); - return false; - } - - return true; -} - -void TCab::Load(cParser &Parser) -{ - // NOTE: clearing control tables here is bit of a crutch, imposed by current scheme of loading compartments anew on each cab change - ggList.clear(); - btList.clear(); - - std::string token; - Parser.getTokens(); - Parser >> token; - if (token == "cablight:") - { - Parser.getTokens(9, false); - /* - Parser - >> dimm.r - >> dimm.g - >> dimm.b - >> intlit.r - >> intlit.g - >> intlit.b - >> intlitlow.r - >> intlitlow.g - >> intlitlow.b; - */ - Parser.getTokens(); - Parser >> token; - } - CabPos1.x = static_cast(std::stod(token)); - Parser.getTokens(5, false); - Parser >> CabPos1.y >> CabPos1.z >> CabPos2.x >> CabPos2.y >> CabPos2.z; - - bEnabled = true; - bOccupied = true; -} - -TGauge &TCab::Gauge(int n) -{ // pobranie adresu obiektu aniomowanego ruchem - /* - if (n < 0) - { // rezerwacja wolnego - ggList[iGauges].Clear(); - return ggList + iGauges++; - } - else if (n < iGauges) - return ggList + n; - return NULL; - */ - if (n < 0) - { - ggList.emplace_back(); - return ggList.back(); - } - else - { - return ggList[n]; - } -}; - -TButton &TCab::Button(int n) -{ // pobranie adresu obiektu animowanego wyborem 1 z 2 - /* - if (n < 0) - { // rezerwacja wolnego - return btList + iButtons++; - } - else if (n < iButtons) - return btList + n; - return NULL; - */ - if (n < 0) - { - btList.emplace_back(); - return btList.back(); - } - else - { - return btList[n]; - } -}; - -void TCab::Update(bool const Power) -{ // odczyt parametrów i ustawienie animacji submodelom - for (auto &gauge : ggList) - { - // animacje izometryczne - gauge.UpdateValue(); // odczyt parametru i przeliczenie na kąt - gauge.Update(); // ustawienie animacji - } - - for (auto &button : btList) - { - // animacje dwustanowe - button.Update(Power); // odczyt parametru i wybór submodelu - } -}; - -// NOTE: we're currently using universal handlers and static handler map but it may be beneficial to have these implemented on individual class instance basis -// TBD, TODO: consider this approach if we ever want to have customized consist behaviour to received commands, based on the consist/vehicle type or whatever -TTrain::commandhandler_map const TTrain::m_commandhandlers = { - - {user_command::aidriverenable, &TTrain::OnCommand_aidriverenable}, - {user_command::aidriverdisable, &TTrain::OnCommand_aidriverdisable}, - {user_command::jointcontrollerset, &TTrain::OnCommand_jointcontrollerset}, - {user_command::mastercontrollerincrease, &TTrain::OnCommand_mastercontrollerincrease}, - {user_command::mastercontrollerincreasefast, &TTrain::OnCommand_mastercontrollerincreasefast}, - {user_command::mastercontrollerdecrease, &TTrain::OnCommand_mastercontrollerdecrease}, - {user_command::mastercontrollerdecreasefast, &TTrain::OnCommand_mastercontrollerdecreasefast}, - {user_command::mastercontrollerset, &TTrain::OnCommand_mastercontrollerset}, - {user_command::secondcontrollerincrease, &TTrain::OnCommand_secondcontrollerincrease}, - {user_command::secondcontrollerincreasefast, &TTrain::OnCommand_secondcontrollerincreasefast}, - {user_command::secondcontrollerdecrease, &TTrain::OnCommand_secondcontrollerdecrease}, - {user_command::secondcontrollerdecreasefast, &TTrain::OnCommand_secondcontrollerdecreasefast}, - {user_command::secondcontrollerset, &TTrain::OnCommand_secondcontrollerset}, - {user_command::dynamicbrakecontrollerincrease, &TTrain::OnCommand_DynamicBrakeControllerIncrease}, - {user_command::dynamicbrakecontrollerincreasefast, &TTrain::OnCommand_DynamicBrakeControllerIncreaseFast}, - {user_command::dynamicbrakecontrollerdecrease, &TTrain::OnCommand_DynamicBrakeControllerDecrease}, - {user_command::dynamicbrakecontrollerdecreasefast, &TTrain::OnCommand_DynamicBrakeControllerDecreaseFast}, - {user_command::dynamicbrakecontrollerset, &TTrain::OnCommand_DynamicBrakeControllerSet}, - {user_command::notchingrelaytoggle, &TTrain::OnCommand_notchingrelaytoggle}, - {user_command::tempomattoggle, &TTrain::OnCommand_tempomattoggle}, - {user_command::mucurrentindicatorothersourceactivate, &TTrain::OnCommand_mucurrentindicatorothersourceactivate}, - {user_command::independentbrakeincrease, &TTrain::OnCommand_independentbrakeincrease}, - {user_command::independentbrakeincreasefast, &TTrain::OnCommand_independentbrakeincreasefast}, - {user_command::independentbrakedecrease, &TTrain::OnCommand_independentbrakedecrease}, - {user_command::independentbrakedecreasefast, &TTrain::OnCommand_independentbrakedecreasefast}, - {user_command::independentbrakeset, &TTrain::OnCommand_independentbrakeset}, - {user_command::independentbrakebailoff, &TTrain::OnCommand_independentbrakebailoff}, - {user_command::universalbrakebutton1, &TTrain::OnCommand_universalbrakebutton1}, - {user_command::universalbrakebutton2, &TTrain::OnCommand_universalbrakebutton2}, - {user_command::universalbrakebutton3, &TTrain::OnCommand_universalbrakebutton3}, - {user_command::trainbrakeincrease, &TTrain::OnCommand_trainbrakeincrease}, - {user_command::trainbrakedecrease, &TTrain::OnCommand_trainbrakedecrease}, - {user_command::trainbrakeset, &TTrain::OnCommand_trainbrakeset}, - {user_command::trainbrakecharging, &TTrain::OnCommand_trainbrakecharging}, - {user_command::trainbrakerelease, &TTrain::OnCommand_trainbrakerelease}, - {user_command::trainbrakefirstservice, &TTrain::OnCommand_trainbrakefirstservice}, - {user_command::trainbrakeservice, &TTrain::OnCommand_trainbrakeservice}, - {user_command::trainbrakefullservice, &TTrain::OnCommand_trainbrakefullservice}, - {user_command::trainbrakehandleoff, &TTrain::OnCommand_trainbrakehandleoff}, - {user_command::trainbrakeemergency, &TTrain::OnCommand_trainbrakeemergency}, - {user_command::trainbrakebasepressureincrease, &TTrain::OnCommand_trainbrakebasepressureincrease}, - {user_command::trainbrakebasepressuredecrease, &TTrain::OnCommand_trainbrakebasepressuredecrease}, - {user_command::trainbrakebasepressurereset, &TTrain::OnCommand_trainbrakebasepressurereset}, - {user_command::trainbrakeoperationtoggle, &TTrain::OnCommand_trainbrakeoperationtoggle}, - {user_command::manualbrakeincrease, &TTrain::OnCommand_manualbrakeincrease}, - {user_command::manualbrakedecrease, &TTrain::OnCommand_manualbrakedecrease}, - {user_command::alarmchaintoggle, &TTrain::OnCommand_alarmchaintoggle}, - {user_command::alarmchainenable, &TTrain::OnCommand_alarmchainenable}, - {user_command::alarmchaindisable, &TTrain::OnCommand_alarmchaindisable}, - {user_command::wheelspinbrakeactivate, &TTrain::OnCommand_wheelspinbrakeactivate}, - {user_command::sandboxactivate, &TTrain::OnCommand_sandboxactivate}, - {user_command::autosandboxtoggle, &TTrain::OnCommand_autosandboxtoggle}, - {user_command::autosandboxactivate, &TTrain::OnCommand_autosandboxactivate}, - {user_command::autosandboxdeactivate, &TTrain::OnCommand_autosandboxdeactivate}, - {user_command::epbrakecontroltoggle, &TTrain::OnCommand_epbrakecontroltoggle}, - {user_command::epbrakecontrolenable, &TTrain::OnCommand_epbrakecontrolenable}, - {user_command::epbrakecontroldisable, &TTrain::OnCommand_epbrakecontroldisable}, - {user_command::trainbrakeoperationmodeincrease, &TTrain::OnCommand_trainbrakeoperationmodeincrease}, - {user_command::trainbrakeoperationmodedecrease, &TTrain::OnCommand_trainbrakeoperationmodedecrease}, - {user_command::brakeactingspeedincrease, &TTrain::OnCommand_brakeactingspeedincrease}, - {user_command::brakeactingspeeddecrease, &TTrain::OnCommand_brakeactingspeeddecrease}, - {user_command::brakeactingspeedsetcargo, &TTrain::OnCommand_brakeactingspeedsetcargo}, - {user_command::brakeactingspeedsetpassenger, &TTrain::OnCommand_brakeactingspeedsetpassenger}, - {user_command::brakeactingspeedsetrapid, &TTrain::OnCommand_brakeactingspeedsetrapid}, - {user_command::brakeloadcompensationincrease, &TTrain::OnCommand_brakeloadcompensationincrease}, - {user_command::brakeloadcompensationdecrease, &TTrain::OnCommand_brakeloadcompensationdecrease}, - {user_command::mubrakingindicatortoggle, &TTrain::OnCommand_mubrakingindicatortoggle}, - {user_command::reverserincrease, &TTrain::OnCommand_reverserincrease}, - {user_command::reverserdecrease, &TTrain::OnCommand_reverserdecrease}, - {user_command::reverserforwardhigh, &TTrain::OnCommand_reverserforwardhigh}, - {user_command::reverserforward, &TTrain::OnCommand_reverserforward}, - {user_command::reverserneutral, &TTrain::OnCommand_reverserneutral}, - {user_command::reverserbackward, &TTrain::OnCommand_reverserbackward}, - {user_command::alerteracknowledge, &TTrain::OnCommand_alerteracknowledge}, - {user_command::cabsignalacknowledge, &TTrain::OnCommand_cabsignalacknowledge}, - {user_command::batterytoggle, &TTrain::OnCommand_batterytoggle}, - {user_command::batteryenable, &TTrain::OnCommand_batteryenable}, - {user_command::batterydisable, &TTrain::OnCommand_batterydisable}, - {user_command::cabactivationtoggle, &TTrain::OnCommand_cabactivationtoggle}, - {user_command::cabactivationenable, &TTrain::OnCommand_cabactivationenable}, - {user_command::cabactivationdisable, &TTrain::OnCommand_cabactivationdisable}, - {user_command::pantographcompressorvalvetoggle, &TTrain::OnCommand_pantographcompressorvalvetoggle}, - {user_command::pantographcompressorvalveenable, &TTrain::OnCommand_pantographcompressorvalveenable}, - {user_command::pantographcompressorvalvedisable, &TTrain::OnCommand_pantographcompressorvalvedisable}, - {user_command::pantographcompressoractivate, &TTrain::OnCommand_pantographcompressoractivate}, - {user_command::pantographtogglefront, &TTrain::OnCommand_pantographtogglefront}, - {user_command::pantographtogglerear, &TTrain::OnCommand_pantographtogglerear}, - {user_command::pantographraisefront, &TTrain::OnCommand_pantographraisefront}, - {user_command::pantographraiserear, &TTrain::OnCommand_pantographraiserear}, - {user_command::pantographlowerfront, &TTrain::OnCommand_pantographlowerfront}, - {user_command::pantographlowerrear, &TTrain::OnCommand_pantographlowerrear}, - - {user_command::wiperswitchincrease, &TTrain::OnCommand_wiperswitchincrease}, - {user_command::wiperswitchdecrease, &TTrain::OnCommand_wiperswitchdecrease}, - - {user_command::lightsset, &TTrain::OnCommand_lightsset}, - - {user_command::pantographlowerall, &TTrain::OnCommand_pantographlowerall}, - {user_command::pantographselectnext, &TTrain::OnCommand_pantographselectnext}, - {user_command::pantographselectprevious, &TTrain::OnCommand_pantographselectprevious}, - {user_command::pantographtoggleselected, &TTrain::OnCommand_pantographtoggleselected}, - {user_command::pantographraiseselected, &TTrain::OnCommand_pantographraiseselected}, - {user_command::pantographlowerselected, &TTrain::OnCommand_pantographlowerselected}, - {user_command::pantographvalvesupdate, &TTrain::OnCommand_pantographvalvesupdate}, - {user_command::pantographvalvesoff, &TTrain::OnCommand_pantographvalvesoff}, - {user_command::linebreakertoggle, &TTrain::OnCommand_linebreakertoggle}, - {user_command::linebreakeropen, &TTrain::OnCommand_linebreakeropen}, - {user_command::linebreakerclose, &TTrain::OnCommand_linebreakerclose}, - {user_command::linebreakertoggleb, &TTrain::OnCommand_linebreakertoggleremote}, - {user_command::linebreakeropenb, &TTrain::OnCommand_linebreakeropenremote}, - {user_command::linebreakercloseb, &TTrain::OnCommand_linebreakercloseremote}, - {user_command::linebreakertogglec, &TTrain::OnCommand_linebreakertoggleremote}, - {user_command::linebreakeropenc, &TTrain::OnCommand_linebreakeropenremote}, - {user_command::linebreakerclosec, &TTrain::OnCommand_linebreakercloseremote}, - {user_command::fuelpumptoggle, &TTrain::OnCommand_fuelpumptoggle}, - {user_command::fuelpumpenable, &TTrain::OnCommand_fuelpumpenable}, - {user_command::fuelpumpdisable, &TTrain::OnCommand_fuelpumpdisable}, - {user_command::oilpumptoggle, &TTrain::OnCommand_oilpumptoggle}, - {user_command::oilfuelpumptoggle, &TTrain::OnCommand_oilfuelpumptoggle}, - {user_command::oilpumpenable, &TTrain::OnCommand_oilpumpenable}, - {user_command::oilpumpdisable, &TTrain::OnCommand_oilpumpdisable}, - {user_command::tractionmodetoggle, &TTrain::OnCommand_tractionmodetoggle}, - {user_command::tractionmodecatenary, &TTrain::OnCommand_tractionmodecatenary}, - {user_command::tractionmodegenset, &TTrain::OnCommand_tractionmodegenset}, - {user_command::gensettoggle, &TTrain::OnCommand_gensettoggle}, - {user_command::gensetenable, &TTrain::OnCommand_gensetenable}, - {user_command::gensetdisable, &TTrain::OnCommand_gensetdisable}, - {user_command::waterheaterbreakertoggle, &TTrain::OnCommand_waterheaterbreakertoggle}, - {user_command::waterheaterbreakerclose, &TTrain::OnCommand_waterheaterbreakerclose}, - {user_command::waterheaterbreakeropen, &TTrain::OnCommand_waterheaterbreakeropen}, - {user_command::waterheatertoggle, &TTrain::OnCommand_waterheatertoggle}, - {user_command::waterheaterenable, &TTrain::OnCommand_waterheaterenable}, - {user_command::waterheaterdisable, &TTrain::OnCommand_waterheaterdisable}, - {user_command::waterpumpbreakertoggle, &TTrain::OnCommand_waterpumpbreakertoggle}, - {user_command::waterpumpbreakerclose, &TTrain::OnCommand_waterpumpbreakerclose}, - {user_command::waterpumpbreakeropen, &TTrain::OnCommand_waterpumpbreakeropen}, - {user_command::waterpumptoggle, &TTrain::OnCommand_waterpumptoggle}, - {user_command::waterpumpenable, &TTrain::OnCommand_waterpumpenable}, - {user_command::waterpumpdisable, &TTrain::OnCommand_waterpumpdisable}, - {user_command::watercircuitslinktoggle, &TTrain::OnCommand_watercircuitslinktoggle}, - {user_command::watercircuitslinkenable, &TTrain::OnCommand_watercircuitslinkenable}, - {user_command::watercircuitslinkdisable, &TTrain::OnCommand_watercircuitslinkdisable}, - {user_command::convertertoggle, &TTrain::OnCommand_convertertoggle}, - {user_command::converterenable, &TTrain::OnCommand_converterenable}, - {user_command::converterdisable, &TTrain::OnCommand_converterdisable}, - {user_command::convertertogglelocal, &TTrain::OnCommand_convertertogglelocal}, - {user_command::converteroverloadrelayreset, &TTrain::OnCommand_converteroverloadrelayreset}, - {user_command::compressortoggle, &TTrain::OnCommand_compressortoggle}, - {user_command::compressorenable, &TTrain::OnCommand_compressorenable}, - {user_command::compressordisable, &TTrain::OnCommand_compressordisable}, - {user_command::compressortogglelocal, &TTrain::OnCommand_compressortogglelocal}, - {user_command::compressorpresetactivatenext, &TTrain::OnCommand_compressorpresetactivatenext}, - {user_command::compressorpresetactivateprevious, &TTrain::OnCommand_compressorpresetactivateprevious}, - {user_command::compressorpresetactivatedefault, &TTrain::OnCommand_compressorpresetactivatedefault}, - {user_command::motorblowerstogglefront, &TTrain::OnCommand_motorblowerstogglefront}, - {user_command::motorblowerstogglerear, &TTrain::OnCommand_motorblowerstogglerear}, - {user_command::motorblowersdisableall, &TTrain::OnCommand_motorblowersdisableall}, - {user_command::coolingfanstoggle, &TTrain::OnCommand_coolingfanstoggle}, - {user_command::motorconnectorsopen, &TTrain::OnCommand_motorconnectorsopen}, - {user_command::motorconnectorsclose, &TTrain::OnCommand_motorconnectorsclose}, - {user_command::motordisconnect, &TTrain::OnCommand_motordisconnect}, - {user_command::motoroverloadrelaythresholdtoggle, &TTrain::OnCommand_motoroverloadrelaythresholdtoggle}, - {user_command::motoroverloadrelaythresholdsetlow, &TTrain::OnCommand_motoroverloadrelaythresholdsetlow}, - {user_command::motoroverloadrelaythresholdsethigh, &TTrain::OnCommand_motoroverloadrelaythresholdsethigh}, - {user_command::motoroverloadrelayreset, &TTrain::OnCommand_motoroverloadrelayreset}, - {user_command::universalrelayreset1, &TTrain::OnCommand_universalrelayreset}, - {user_command::universalrelayreset2, &TTrain::OnCommand_universalrelayreset}, - {user_command::universalrelayreset3, &TTrain::OnCommand_universalrelayreset}, - {user_command::heatingtoggle, &TTrain::OnCommand_heatingtoggle}, - {user_command::heatingenable, &TTrain::OnCommand_heatingenable}, - {user_command::heatingdisable, &TTrain::OnCommand_heatingdisable}, - {user_command::lightspresetactivatenext, &TTrain::OnCommand_lightspresetactivatenext}, - {user_command::lightspresetactivateprevious, &TTrain::OnCommand_lightspresetactivateprevious}, - {user_command::headlighttoggleleft, &TTrain::OnCommand_headlighttoggleleft}, - {user_command::headlightenableleft, &TTrain::OnCommand_headlightenableleft}, - {user_command::headlightdisableleft, &TTrain::OnCommand_headlightdisableleft}, - {user_command::headlighttoggleright, &TTrain::OnCommand_headlighttoggleright}, - {user_command::headlightenableright, &TTrain::OnCommand_headlightenableright}, - {user_command::headlightdisableright, &TTrain::OnCommand_headlightdisableright}, - {user_command::headlighttoggleupper, &TTrain::OnCommand_headlighttoggleupper}, - {user_command::headlightenableupper, &TTrain::OnCommand_headlightenableupper}, - {user_command::headlightdisableupper, &TTrain::OnCommand_headlightdisableupper}, - {user_command::redmarkertoggleleft, &TTrain::OnCommand_redmarkertoggleleft}, - {user_command::redmarkerenableleft, &TTrain::OnCommand_redmarkerenableleft}, - {user_command::redmarkerdisableleft, &TTrain::OnCommand_redmarkerdisableleft}, - {user_command::redmarkertoggleright, &TTrain::OnCommand_redmarkertoggleright}, - {user_command::redmarkerenableright, &TTrain::OnCommand_redmarkerenableright}, - {user_command::redmarkerdisableright, &TTrain::OnCommand_redmarkerdisableright}, - {user_command::headlighttogglerearleft, &TTrain::OnCommand_headlighttogglerearleft}, - {user_command::headlightenablerearleft, &TTrain::OnCommand_headlightenablerearleft}, - {user_command::headlightdisablerearleft, &TTrain::OnCommand_headlightdisablerearleft}, - {user_command::headlighttogglerearright, &TTrain::OnCommand_headlighttogglerearright}, - {user_command::headlightenablerearright, &TTrain::OnCommand_headlightenablerearright}, - {user_command::headlightdisablerearright, &TTrain::OnCommand_headlightdisablerearright}, - {user_command::headlighttogglerearupper, &TTrain::OnCommand_headlighttogglerearupper}, - {user_command::headlightenablerearupper, &TTrain::OnCommand_headlightenablerearupper}, - {user_command::headlightdisablerearupper, &TTrain::OnCommand_headlightdisablerearupper}, - {user_command::modernlightdimmerdecrease, &TTrain::OnCommand_modernlightdimmerdecrease}, - {user_command::modernlightdimmerincrease, &TTrain::OnCommand_modernlightdimmerincrease}, - {user_command::redmarkertogglerearleft, &TTrain::OnCommand_redmarkertogglerearleft}, - {user_command::redmarkerenablerearleft, &TTrain::OnCommand_redmarkerenablerearleft}, - {user_command::redmarkerdisablerearleft, &TTrain::OnCommand_redmarkerdisablerearleft}, - {user_command::redmarkertogglerearright, &TTrain::OnCommand_redmarkertogglerearright}, - {user_command::redmarkerenablerearright, &TTrain::OnCommand_redmarkerenablerearright}, - {user_command::redmarkerdisablerearright, &TTrain::OnCommand_redmarkerdisablerearright}, - {user_command::redmarkerstoggle, &TTrain::OnCommand_redmarkerstoggle}, - {user_command::endsignalstoggle, &TTrain::OnCommand_endsignalstoggle}, - {user_command::headlightsdimtoggle, &TTrain::OnCommand_headlightsdimtoggle}, - {user_command::headlightsdimenable, &TTrain::OnCommand_headlightsdimenable}, - {user_command::headlightsdimdisable, &TTrain::OnCommand_headlightsdimdisable}, - {user_command::interiorlighttoggle, &TTrain::OnCommand_interiorlighttoggle}, - {user_command::interiorlightenable, &TTrain::OnCommand_interiorlightenable}, - {user_command::interiorlightdisable, &TTrain::OnCommand_interiorlightdisable}, - {user_command::interiorlightdimtoggle, &TTrain::OnCommand_interiorlightdimtoggle}, - {user_command::interiorlightdimenable, &TTrain::OnCommand_interiorlightdimenable}, - {user_command::interiorlightdimdisable, &TTrain::OnCommand_interiorlightdimdisable}, - {user_command::compartmentlightstoggle, &TTrain::OnCommand_compartmentlightstoggle}, - {user_command::compartmentlightsenable, &TTrain::OnCommand_compartmentlightsenable}, - {user_command::compartmentlightsdisable, &TTrain::OnCommand_compartmentlightsdisable}, - {user_command::instrumentlighttoggle, &TTrain::OnCommand_instrumentlighttoggle}, - {user_command::instrumentlightenable, &TTrain::OnCommand_instrumentlightenable}, - {user_command::instrumentlightdisable, &TTrain::OnCommand_instrumentlightdisable}, - {user_command::dashboardlighttoggle, &TTrain::OnCommand_dashboardlighttoggle}, - {user_command::dashboardlightenable, &TTrain::OnCommand_dashboardlightenable}, - {user_command::dashboardlightdisable, &TTrain::OnCommand_dashboardlightdisable}, - {user_command::timetablelighttoggle, &TTrain::OnCommand_timetablelighttoggle}, - {user_command::timetablelightenable, &TTrain::OnCommand_timetablelightenable}, - {user_command::timetablelightdisable, &TTrain::OnCommand_timetablelightdisable}, - {user_command::doorlocktoggle, &TTrain::OnCommand_doorlocktoggle}, - {user_command::doortoggleleft, &TTrain::OnCommand_doortoggleleft}, - {user_command::doortoggleright, &TTrain::OnCommand_doortoggleright}, - {user_command::doorpermitleft, &TTrain::OnCommand_doorpermitleft}, - {user_command::doorpermitright, &TTrain::OnCommand_doorpermitright}, - {user_command::doorpermitpresetactivatenext, &TTrain::OnCommand_doorpermitpresetactivatenext}, - {user_command::doorpermitpresetactivateprevious, &TTrain::OnCommand_doorpermitpresetactivateprevious}, - {user_command::dooropenleft, &TTrain::OnCommand_dooropenleft}, - {user_command::dooropenright, &TTrain::OnCommand_dooropenright}, - {user_command::doorcloseleft, &TTrain::OnCommand_doorcloseleft}, - {user_command::doorcloseright, &TTrain::OnCommand_doorcloseright}, - {user_command::dooropenall, &TTrain::OnCommand_dooropenall}, - {user_command::doorcloseall, &TTrain::OnCommand_doorcloseall}, - {user_command::doorsteptoggle, &TTrain::OnCommand_doorsteptoggle}, - {user_command::doormodetoggle, &TTrain::OnCommand_doormodetoggle}, - {user_command::mirrorstoggle, &TTrain::OnCommand_mirrorstoggle}, - {user_command::nearestcarcouplingincrease, &TTrain::OnCommand_nearestcarcouplingincrease}, - {user_command::nearestcarcouplingdisconnect, &TTrain::OnCommand_nearestcarcouplingdisconnect}, - {user_command::nearestcarcoupleradapterattach, &TTrain::OnCommand_nearestcarcoupleradapterattach}, - {user_command::nearestcarcoupleradapterremove, &TTrain::OnCommand_nearestcarcoupleradapterremove}, - {user_command::occupiedcarcouplingdisconnect, &TTrain::OnCommand_occupiedcarcouplingdisconnect}, - {user_command::departureannounce, &TTrain::OnCommand_departureannounce}, - {user_command::hornlowactivate, &TTrain::OnCommand_hornlowactivate}, - {user_command::hornhighactivate, &TTrain::OnCommand_hornhighactivate}, - {user_command::whistleactivate, &TTrain::OnCommand_whistleactivate}, - {user_command::radiotoggle, &TTrain::OnCommand_radiotoggle}, - {user_command::radioenable, &TTrain::OnCommand_radioenable}, - {user_command::radiodisable, &TTrain::OnCommand_radiodisable}, - {user_command::radiochannelincrease, &TTrain::OnCommand_radiochannelincrease}, - {user_command::radiochanneldecrease, &TTrain::OnCommand_radiochanneldecrease}, - {user_command::radiochannelset, &TTrain::OnCommand_radiochannelset}, - {user_command::radiostopsend, &TTrain::OnCommand_radiostopsend}, - {user_command::radiostopenable, &TTrain::OnCommand_radiostopenable}, - {user_command::radiostopdisable, &TTrain::OnCommand_radiostopdisable}, - {user_command::radiostoptest, &TTrain::OnCommand_radiostoptest}, - {user_command::radiocall1send, &TTrain::OnCommand_radiocall1send}, - {user_command::radiocall3send, &TTrain::OnCommand_radiocall3send}, - {user_command::radiovolumeincrease, &TTrain::OnCommand_radiovolumeincrease}, - {user_command::radiovolumedecrease, &TTrain::OnCommand_radiovolumedecrease}, - {user_command::radiovolumeset, &TTrain::OnCommand_radiovolumeset}, - {user_command::fmradiotoggle, &TTrain::OnCommand_fmradiotoggle}, - {user_command::fmradiovolumeincrease, &TTrain::OnCommand_fmradiovolumeincrease}, - {user_command::fmradiovolumedecrease, &TTrain::OnCommand_fmradiovolumedecrease}, - {user_command::fmradiovolumeset, &TTrain::OnCommand_fmradiovolumeset}, - {user_command::fmradiotuneincrease, &TTrain::OnCommand_fmradiotuneincrease}, - {user_command::fmradiotunedecrease, &TTrain::OnCommand_fmradiotunedecrease}, - {user_command::fmradiotuneset, &TTrain::OnCommand_fmradiotuneset}, - {user_command::radiofusetoggle, &TTrain::OnCommand_radiofusetoggle}, - {user_command::radiofuseenable, &TTrain::OnCommand_radiofuseenable}, - {user_command::radiofusedisable, &TTrain::OnCommand_radiofusedisable}, - {user_command::cabchangeforward, &TTrain::OnCommand_cabchangeforward}, - {user_command::cabchangebackward, &TTrain::OnCommand_cabchangebackward}, - {user_command::generictoggle0, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle1, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle2, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle3, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle4, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle5, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle6, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle7, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle8, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle9, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle10, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle11, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle12, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle13, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle14, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle15, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle16, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle17, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle18, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle19, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle20, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle21, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle22, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle23, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle24, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle25, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle26, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle27, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle28, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle29, &TTrain::OnCommand_generictoggle}, - {user_command::genericset0, &TTrain::OnCommand_genericset}, - {user_command::genericset1, &TTrain::OnCommand_genericset}, - {user_command::genericset2, &TTrain::OnCommand_genericset}, - {user_command::genericset3, &TTrain::OnCommand_genericset}, - {user_command::genericset4, &TTrain::OnCommand_genericset}, - {user_command::genericset5, &TTrain::OnCommand_genericset}, - {user_command::genericset6, &TTrain::OnCommand_genericset}, - {user_command::genericset7, &TTrain::OnCommand_genericset}, - {user_command::genericset8, &TTrain::OnCommand_genericset}, - {user_command::genericset9, &TTrain::OnCommand_genericset}, - {user_command::genericset10, &TTrain::OnCommand_genericset}, - {user_command::genericset11, &TTrain::OnCommand_genericset}, - {user_command::genericset12, &TTrain::OnCommand_genericset}, - {user_command::genericset13, &TTrain::OnCommand_genericset}, - {user_command::genericset14, &TTrain::OnCommand_genericset}, - {user_command::genericset15, &TTrain::OnCommand_genericset}, - {user_command::genericset16, &TTrain::OnCommand_genericset}, - {user_command::genericset17, &TTrain::OnCommand_genericset}, - {user_command::genericset18, &TTrain::OnCommand_genericset}, - {user_command::genericset19, &TTrain::OnCommand_genericset}, - {user_command::genericset20, &TTrain::OnCommand_genericset}, - {user_command::genericset21, &TTrain::OnCommand_genericset}, - {user_command::genericset22, &TTrain::OnCommand_genericset}, - {user_command::genericset23, &TTrain::OnCommand_genericset}, - {user_command::genericset24, &TTrain::OnCommand_genericset}, - {user_command::genericset25, &TTrain::OnCommand_genericset}, - {user_command::genericset26, &TTrain::OnCommand_genericset}, - {user_command::genericset27, &TTrain::OnCommand_genericset}, - {user_command::genericset28, &TTrain::OnCommand_genericset}, - {user_command::genericset29, &TTrain::OnCommand_genericset}, - {user_command::vehiclemoveforwards, &TTrain::OnCommand_vehiclemoveforwards}, - {user_command::vehiclemovebackwards, &TTrain::OnCommand_vehiclemovebackwards}, - {user_command::vehicleboost, &TTrain::OnCommand_vehicleboost}, - {user_command::springbraketoggle, &TTrain::OnCommand_springbraketoggle}, - {user_command::springbrakeenable, &TTrain::OnCommand_springbrakeenable}, - {user_command::springbrakedisable, &TTrain::OnCommand_springbrakedisable}, - {user_command::springbrakeshutofftoggle, &TTrain::OnCommand_springbrakeshutofftoggle}, - {user_command::springbrakeshutoffenable, &TTrain::OnCommand_springbrakeshutoffenable}, - {user_command::springbrakeshutoffdisable, &TTrain::OnCommand_springbrakeshutoffdisable}, - {user_command::springbrakerelease, &TTrain::OnCommand_springbrakerelease}, - {user_command::distancecounteractivate, &TTrain::OnCommand_distancecounteractivate}, - {user_command::speedcontrolincrease, &TTrain::OnCommand_speedcontrolincrease}, - {user_command::speedcontroldecrease, &TTrain::OnCommand_speedcontroldecrease}, - {user_command::speedcontrolpowerincrease, &TTrain::OnCommand_speedcontrolpowerincrease}, - {user_command::speedcontrolpowerdecrease, &TTrain::OnCommand_speedcontrolpowerdecrease}, - {user_command::speedcontrolbutton0, &TTrain::OnCommand_speedcontrolbutton}, - {user_command::speedcontrolbutton1, &TTrain::OnCommand_speedcontrolbutton}, - {user_command::speedcontrolbutton2, &TTrain::OnCommand_speedcontrolbutton}, - {user_command::speedcontrolbutton3, &TTrain::OnCommand_speedcontrolbutton}, - {user_command::speedcontrolbutton4, &TTrain::OnCommand_speedcontrolbutton}, - {user_command::speedcontrolbutton5, &TTrain::OnCommand_speedcontrolbutton}, - {user_command::speedcontrolbutton6, &TTrain::OnCommand_speedcontrolbutton}, - {user_command::speedcontrolbutton7, &TTrain::OnCommand_speedcontrolbutton}, - {user_command::speedcontrolbutton8, &TTrain::OnCommand_speedcontrolbutton}, - {user_command::speedcontrolbutton9, &TTrain::OnCommand_speedcontrolbutton}, - {user_command::inverterenable1, &TTrain::OnCommand_inverterenable}, - {user_command::inverterenable2, &TTrain::OnCommand_inverterenable}, - {user_command::inverterenable3, &TTrain::OnCommand_inverterenable}, - {user_command::inverterenable4, &TTrain::OnCommand_inverterenable}, - {user_command::inverterenable5, &TTrain::OnCommand_inverterenable}, - {user_command::inverterenable6, &TTrain::OnCommand_inverterenable}, - {user_command::inverterenable7, &TTrain::OnCommand_inverterenable}, - {user_command::inverterenable8, &TTrain::OnCommand_inverterenable}, - {user_command::inverterenable9, &TTrain::OnCommand_inverterenable}, - {user_command::inverterenable10, &TTrain::OnCommand_inverterenable}, - {user_command::inverterenable11, &TTrain::OnCommand_inverterenable}, - {user_command::inverterenable12, &TTrain::OnCommand_inverterenable}, - {user_command::inverterdisable1, &TTrain::OnCommand_inverterdisable}, - {user_command::inverterdisable2, &TTrain::OnCommand_inverterdisable}, - {user_command::inverterdisable3, &TTrain::OnCommand_inverterdisable}, - {user_command::inverterdisable4, &TTrain::OnCommand_inverterdisable}, - {user_command::inverterdisable5, &TTrain::OnCommand_inverterdisable}, - {user_command::inverterdisable6, &TTrain::OnCommand_inverterdisable}, - {user_command::inverterdisable7, &TTrain::OnCommand_inverterdisable}, - {user_command::inverterdisable8, &TTrain::OnCommand_inverterdisable}, - {user_command::inverterdisable9, &TTrain::OnCommand_inverterdisable}, - {user_command::inverterdisable10, &TTrain::OnCommand_inverterdisable}, - {user_command::inverterdisable11, &TTrain::OnCommand_inverterdisable}, - {user_command::inverterdisable12, &TTrain::OnCommand_inverterdisable}, - {user_command::invertertoggle1, &TTrain::OnCommand_invertertoggle}, - {user_command::invertertoggle2, &TTrain::OnCommand_invertertoggle}, - {user_command::invertertoggle3, &TTrain::OnCommand_invertertoggle}, - {user_command::invertertoggle4, &TTrain::OnCommand_invertertoggle}, - {user_command::invertertoggle5, &TTrain::OnCommand_invertertoggle}, - {user_command::invertertoggle6, &TTrain::OnCommand_invertertoggle}, - {user_command::invertertoggle7, &TTrain::OnCommand_invertertoggle}, - {user_command::invertertoggle8, &TTrain::OnCommand_invertertoggle}, - {user_command::invertertoggle9, &TTrain::OnCommand_invertertoggle}, - {user_command::invertertoggle10, &TTrain::OnCommand_invertertoggle}, - {user_command::invertertoggle11, &TTrain::OnCommand_invertertoggle}, - {user_command::invertertoggle12, &TTrain::OnCommand_invertertoggle}, -}; - -std::vector const TTrain::fPress_labels = { - - "ch1: ", "ch2: ", "ch3: ", "ch4: ", "ch5: ", "ch6: ", "ch7: ", "ch8: ", "ch9: ", "ch0: "}; - -TTrain::TTrain() -{ - - // McZapkie-240302 - przyda sie do tachometru - - // asMessage=""; - DynamicSet(nullptr); // ustawia wszystkie mv* - //----- - - // - for (int i = 0; i < 8; i++) - { - bMains[i] = false; - fCntVol[i] = 0.0f; - bPants[i][0] = false; - bPants[i][1] = false; - bFuse[i] = false; - bBatt[i] = false; - bConv[i] = false; - bComp[i][0] = false; - bComp[i][1] = false; - // bComp[ i ][ 2 ] = false; - // bComp[ i ][ 3 ] = false; - bHeat[i] = false; - } - bCompressors.clear(); - for (int i = 0; i < 9; ++i) - for (int j = 0; j < 10; ++j) - { - fEIMParams[i][j] = 0.0; - fDieselParams[i][j] = 0.0; - } - - for (int i = 0; i < 20; ++i) - { - for (auto &press : fPress[i]) - press = 0.0; - bBrakes[i][0] = false; - bBrakes[i][1] = false; - } -} - -TTrain::~TTrain() = default; - -bool TTrain::Init(TDynamicObject *NewDynamicObject, bool e3d) -{ // powiązanie ręcznego sterowania kabiną z pojazdem - if (NewDynamicObject->Mechanik == nullptr) - { - /* - ErrorLog( "Bad config: can't take control of inactive vehicle \"" + NewDynamicObject->asName + "\"" ); - return false; - */ - auto const activecab{(NewDynamicObject->MoverParameters->CabOccupied > 0 ? "1" : NewDynamicObject->MoverParameters->CabOccupied < 0 ? "2" : "p")}; - NewDynamicObject->create_controller(activecab, NewDynamicObject->ctOwner != nullptr); - } - - DynamicSet(NewDynamicObject); - if (!e3d && DynamicObject->Mechanik == nullptr) - return false; - - DynamicObject->MechInside = true; - - fMainRelayTimer = 0; // Hunter, do k...y nędzy, ustawiaj wartości początkowe zmiennych! - - iCabn = mvOccupied->CabOccupied > 0 ? 1 : mvOccupied->CabOccupied < 0 ? 2 : 0; - - { - Global.CurrentMaxTextureSize = Global.iMaxCabTextureSize; - - auto const filename{mvOccupied->TypeName + ".mmd"}; - LoadMMediaFile(filename); - InitializeCab(mvOccupied->CabOccupied, filename); - - Global.CurrentMaxTextureSize = Global.iMaxTextureSize; - - if (DynamicObject->Controller == Humandriver) - { - // McZapkie-030303: mozliwosc wyswietlania kabiny, w przyszlosci dac opcje w mmd - DynamicObject->bDisplayCab = true; - } - } - - // Ra: taka proteza - przesłanie kierunku do członów connected - /* - if (mvControlled->DirActive > 0) - { // było do przodu - mvControlled->DirectionBackward(); - mvControlled->DirectionForward(); - } - else if (mvControlled->DirActive < 0) - { - mvControlled->DirectionForward(); - mvControlled->DirectionBackward(); - } - */ - if (false == DynamicObject->Mechanik->AIControllFlag) - { - DynamicObject->Mechanik->sync_consist_reversers(); - } - - return true; -} - -std::shared_ptr TTrain::GetTrainState(dictionary_source const &Extraparameters) -{ - - if (mvOccupied == nullptr || mvControlled == nullptr) - { - return nullptr; - } - - auto dict = std::make_shared(Extraparameters); - if (dict == nullptr) - { - return nullptr; - } - - dict->insert("name", DynamicObject->asName); - dict->insert("cab", mvOccupied->CabOccupied); - dict->insert("cabactive", mvOccupied->CabActive); - dict->insert("master", mvOccupied->CabMaster); - // basic systems state data - dict->insert("battery", mvOccupied->Power24vIsAvailable); - dict->insert("linebreaker", mvControlled->Mains); - dict->insert("main_init", mvControlled->MainsInitTimeCountdown < mvControlled->MainsInitTime && mvControlled->MainsInitTimeCountdown > 0.0); - dict->insert("main_ready", false == mvControlled->Mains && fHVoltage > 0.0 && mvControlled->MainsInitTimeCountdown <= 0.0); - dict->insert("converter", mvOccupied->Power110vIsAvailable); - dict->insert("converter_overload", mvControlled->ConvOvldFlag); - dict->insert("compress", mvControlled->CompressorFlag); - dict->insert("pant_compressor", mvPantographUnit->PantCompFlag); - dict->insert("lights_front", mvOccupied->iLights[end::front]); - dict->insert("lights_rear", mvOccupied->iLights[end::rear]); - dict->insert("off_from_dimmer", mvOccupied->currentDimPosition().isOff); - dict->insert("lights_compartments", mvOccupied->CompartmentLights.is_active || mvOccupied->CompartmentLights.is_disabled); - if (Dynamic()->Mechanik) - { - auto const *controller{Dynamic()->Mechanik}; - auto const cabmodifier{cab_to_end() == end::front ? 1 : -1}; - auto const traindirection{controller->Direction() * cabmodifier}; - auto const *frontvehicle{controller->Vehicle(traindirection >= 0 ? end::front : end::rear)}; - auto const *rearvehicle{controller->Vehicle(traindirection >= 0 ? end::rear : end::front)}; - auto const frontvehicledirection{(frontvehicle->DirectionGet() == controller->Vehicle()->DirectionGet() ? 1 : -1)}; - auto const rearvehicledirection{(rearvehicle->DirectionGet() == controller->Vehicle()->DirectionGet() ? 1 : -1)}; - auto const fronttrainlights{frontvehicle->MoverParameters->iLights[frontvehicledirection * cabmodifier >= 0 ? end::front : end::rear]}; - auto const reartrainlights{rearvehicle->MoverParameters->iLights[rearvehicledirection * cabmodifier >= 0 ? end::rear : end::front]}; - dict->insert("lights_train_front", fronttrainlights); - dict->insert("lights_train_rear", reartrainlights); - } - else - { - // fallback, in the unlikely case we lose the controller - dict->insert("lights_train_front", mvOccupied->iLights[end::front]); - dict->insert("lights_train_rear", mvOccupied->iLights[end::rear]); - } - // reverser - dict->insert("direction", mvOccupied->DirActive); - // throttle - dict->insert("mainctrl_pos", mvControlled->MainCtrlPos); - dict->insert("mainctrl_pos_count", mvControlled->MainCtrlPosNo); - dict->insert("main_ctrl_actual_pos", mvControlled->MainCtrlActualPos); - dict->insert("scndctrl_pos", mvControlled->ScndCtrlPos); - dict->insert("dynamicbrake_pos", mvControlled->DynamicBrakeCtrlPos); - dict->insert("scnd_ctrl_actual_pos", mvControlled->ScndCtrlActualPos); - dict->insert("brakectrl_pos", mvControlled->fBrakeCtrlPos); - dict->insert("localbrake_pos", mvControlled->LocalBrakePosA); - dict->insert("new_speed", mvOccupied->NewSpeed); - dict->insert("speedctrl", mvOccupied->SpeedCtrlValue); - dict->insert("speedctrlpower", mvOccupied->SpeedCtrlUnit.DesiredPower); - dict->insert("speedctrlactive", mvOccupied->SpeedCtrlUnit.IsActive); - dict->insert("speedctrlstandby", mvOccupied->SpeedCtrlUnit.Standby); - // brakes - dict->insert("manual_brake", mvOccupied->ManualBrakePos > 0); - bool const bEP = mvControlled->LocHandle->GetCP() > 0.2 || fEIMParams[0][5] > 0.01; - dict->insert("dir_brake", bEP); - bool bPN{false}; - auto const &brakevalve{*mvOccupied->Hamulec}; - if (auto const &brakevalvetype{typeid(brakevalve)}; brakevalvetype == typeid(TLSt) || brakevalvetype == typeid(TEStED)) - { - - TBrake *temp_ham = mvOccupied->Hamulec.get(); - bPN = static_cast(temp_ham)->GetEDBCP() > 0.2; - } - dict->insert("indir_brake", bPN); - dict->insert("emergency_brake", mvOccupied->AlarmChainFlag); - dict->insert("brake_delay_flag", mvOccupied->BrakeDelayFlag); - dict->insert("brake_op_mode_flag", mvOccupied->BrakeOpModeFlag); - dict->insert("pipelock", mvOccupied->LockPipe); - // other controls - dict->insert("ca", mvOccupied->SecuritySystem.is_vigilance_blinking()); - dict->insert("shp", mvOccupied->SecuritySystem.is_cabsignal_blinking()); - dict->insert("distance_counter", m_distancecounter); - dict->insert("pantpress", std::abs(mvPantographUnit->PantPress)); - dict->insert("universal3", InstrumentLightActive); - for (auto idx = 0; idx < ggUniversals.size(); idx++) - { - if (idx != 3) - { - dict->insert("universal" + std::to_string(idx), ggUniversals[idx].GetValue() > 0.5); - } - } - dict->insert("radio", mvOccupied->Radio); - dict->insert("radio_fuse", mvOccupied->RadioFuse); - dict->insert("radio_channel", RadioChannel()); - dict->insert("radio_volume", m_radiovolume); - dict->insert("door_lock", mvOccupied->Doors.lock_enabled); - dict->insert("door_step", mvOccupied->Doors.step_enabled); - dict->insert("door_permit_left", mvOccupied->Doors.instances[side::left].open_permit); - dict->insert("door_permit_right", mvOccupied->Doors.instances[side::right].open_permit); - // movement data - dict->insert("velocity", std::abs(mvOccupied->Vel)); - dict->insert("tractionforce", std::abs(mvOccupied->Ft)); - dict->insert("slipping_wheels", mvOccupied->SlippingWheels); - dict->insert("sanding", mvOccupied->SandDose); - dict->insert("odometer", mvOccupied->DistCounter); // distance run in the session, km - dict->insert("odometer_total", mvOccupied->Odometer.km); // the vehicle's odometer, kept between the sessions - // electric current data - dict->insert("traction_voltage", std::abs(mvPantographUnit->PantographVoltage)); - dict->insert("voltage", std::abs(mvControlled->EngineVoltage)); - dict->insert("im", std::abs(mvControlled->Im)); - dict->insert("fuse", mvControlled->FuseFlag); - dict->insert("epfuse", mvOccupied->EpFuse); - dict->insert("power_drawn", mvOccupied->EnergyMeter.first); - dict->insert("power_returned", mvOccupied->EnergyMeter.second); - - // induction motor state data - std::array const TXTT{"fd", "fdt", "fdb", "pd", "pdt", "pdb", "itothv", "1", "2", "3"}; - std::array const TXTC{"fr", "frt", "frb", "pr", "prt", "prb", "im", "vm", "ihv", "uhv"}; - std::array const TXTD{"enrot", "nrot", "fill_des", "fill_real", "clutch_des", "clutch_real", "water_temp", "oil_press", "engine_temp", "retarder_fill"}; - std::array const TXTP{"bc", "bp", "sp", "cp", "rp", "mass", "spring"}; - char const *TXTB[2] = {"spring_active", "spring_shutoff"}; - for (int j = 0; j < 10; ++j) - dict->insert("eimp_t_" + std::string(TXTT[j]), fEIMParams[0][j]); - for (int i = 0; i < 8; ++i) - { - auto const idx{std::to_string(i + 1)}; - for (int j = 0; j < 10; ++j) - dict->insert("eimp_c" + idx + "_" + std::string(TXTC[j]), fEIMParams[i + 1][j]); - - for (int j = 0; j < 10; ++j) - dict->insert("diesel_param_" + idx + "_" + std::string(TXTD[j]), fDieselParams[i + 1][j]); - - dict->insert("eimp_c" + idx + "_ms", bMains[i]); - dict->insert("eimp_c" + idx + "_cv", fCntVol[i]); - dict->insert("eimp_c" + idx + "_fuse", bFuse[i]); - dict->insert("eimp_c" + idx + "_batt", bBatt[i]); - dict->insert("eimp_c" + idx + "_conv", bConv[i]); - dict->insert("eimp_c" + idx + "_heat", bHeat[i]); - - dict->insert("eimp_u" + idx + "_pf", bPants[i][0]); - dict->insert("eimp_u" + idx + "_pr", bPants[i][1]); - dict->insert("eimp_u" + idx + "_comp_a", bComp[i][0]); - dict->insert("eimp_u" + idx + "_comp_w", bComp[i][1]); - } - - dict->insert("compressors_no", (int)bCompressors.size()); - for (int i = 0; i < bCompressors.size(); i++) - { - auto const idx{std::to_string(i + 1)}; - dict->insert("compressors_" + idx + "_allow", std::get<0>(bCompressors[i])); - dict->insert("compressors_" + idx + "_work", std::get<1>(bCompressors[i])); - dict->insert("compressors_" + idx + "_car_no", std::get<2>(bCompressors[i])); - } - - bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; - TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? end::rear : end::front, Coupling::control); - int in = 0; - while (p && in < 8) - { - if (p->MoverParameters->eimc[eimc_p_Pmax] > 1) - { - in++; - dict->insert("eimp_c" + std::to_string(in) + "_invno", p->MoverParameters->InvertersNo); - for (int j = 0; j < p->MoverParameters->InvertersNo; j++) - { - dict->insert("eimp_c" + std::to_string(in) + "_inv" + std::to_string(j + 1) + "_act", p->MoverParameters->Inverters[j].IsActive); - dict->insert("eimp_c" + std::to_string(in) + "_inv" + std::to_string(j + 1) + "_error", p->MoverParameters->Inverters[j].Error); - dict->insert("eimp_c" + std::to_string(in) + "_inv" + std::to_string(j + 1) + "_allow", p->MoverParameters->Inverters[j].Activate); - } - } - p = kier ? p->Next(Coupling::control) : p->Prev(Coupling::control); - } - for (int i = 0; i < 20; ++i) - { - for (int j = 0; j < 7; ++j) - { - dict->insert("eimp_pn" + std::to_string(i + 1) + "_" + TXTP[j], fPress[i][j]); - } - for (int j = 0; j < 2; ++j) - { - dict->insert("brakes_" + std::to_string(i + 1) + "_" + TXTB[j], bBrakes[i][j]); - } - } - // multi-unit state data - dict->insert("car_no", iCarNo); - dict->insert("power_no", iPowerNo); - dict->insert("unit_no", iUnitNo); - - for (int i = 0; i < 20; i++) - { - auto const caridx{std::to_string(i + 1)}; - dict->insert("doors_" + caridx, bDoors[i][0]); - dict->insert("doors_l_" + caridx, bDoors[i][1]); - dict->insert("doors_r_" + caridx, bDoors[i][2]); - dict->insert("doorstep_l_" + caridx, bDoors[i][3]); - dict->insert("doorstep_r_" + caridx, bDoors[i][4]); - dict->insert("doors_no_" + caridx, iDoorNo[i]); - dict->insert("code_" + caridx, std::to_string(iUnits[i]) + cCode[i]); - dict->insert("car_name" + caridx, asCarName[i]); - dict->insert("slip_" + caridx, bSlip[i]); - } - // ai state data - auto const *vehicledriver{(DynamicObject->ctOwner != nullptr ? DynamicObject->ctOwner : DynamicObject->Mechanik)}; - - dict->insert("velocity_desired", vehicledriver->VelDesired); - dict->insert("velroad", vehicledriver->VelRoad); - dict->insert("vellimitlast", vehicledriver->VelLimitLast); - dict->insert("velsignallast", vehicledriver->VelSignalLast); - dict->insert("velsignalnext", vehicledriver->VelSignalNext); - dict->insert("velnext", vehicledriver->VelNext); - dict->insert("actualproximitydist", vehicledriver->ActualProximityDist); - // train data - vehicledriver->TrainTimetable().serialize(dict.get()); - dict->insert("train_atpassengerstop", vehicledriver->IsAtPassengerStop); - dict->insert("train_length", vehicledriver->fLength); - // world state data - dict->insert("scenario", Global.SceneryFile); - dict->insert("hours", static_cast(simulation::Time.data().wHour)); - dict->insert("minutes", static_cast(simulation::Time.data().wMinute)); - dict->insert("seconds", static_cast(simulation::Time.second())); - dict->insert("air_temperature", Global.AirTemperature); - dict->insert("light_level", Global.fLuminance - std::max(0.f, Global.Overcast - 1.f)); - - return dict; -} - -TTrain::state_t TTrain::get_state() const -{ - - return { - btLampkaSHP.GetValue(), - btLampkaCzuwaka.GetValue(), - btLampkaRadioStop.GetValue(), - btLampkaOpory.GetValue(), - btLampkaWylSzybki.GetValue(), - btLampkaPrzekRozn.GetValue(), - btLampkaNadmSil.GetValue(), - btLampkaStyczn.GetValue(), - btLampkaPoslizg.GetValue(), - btLampkaNadmPrzetw.GetValue(), - btLampkaPrzetwOff.GetValue(), - btLampkaNadmSpr.GetValue(), - btLampkaNadmWent.GetValue(), - btLampkaWysRozr.GetValue(), - btLampkaOgrzewanieSkladu.GetValue(), - static_cast(iCabn), - btHaslerBrakes.GetValue(), - btHaslerCurrent.GetValue(), - mvOccupied->SecuritySystem.is_beeping(), - btLampkaHVoltageB.GetValue(), - fTachoVelocity, - static_cast(mvOccupied->Compressor), - static_cast(mvOccupied->PipePress), - static_cast(mvOccupied->BrakePress), - static_cast(mvPantographUnit->PantPress), - fHVoltage, - {fHCurrent[mvControlled->TrainType == train_type::emu ? 0 : 1], fHCurrent[2], fHCurrent[3]}, - ggLVoltage.GetValue(), - mvOccupied->DistCounter, - static_cast(RadioChannel()), - btLampkaSpringBrakeActive.GetValue(), - btLampkaNapNastHam.GetValue(), - mvOccupied->DirActive > 0, - mvOccupied->DirActive < 0, - mvOccupied->Doors.instances[mvOccupied->CabOccupied < 0 ? side::right : side::left].open_permit, - mvOccupied->Doors.instances[mvOccupied->CabOccupied < 0 ? side::right : side::left].is_open, - mvOccupied->Doors.instances[mvOccupied->CabOccupied < 0 ? side::left : side::right].open_permit, - mvOccupied->Doors.instances[mvOccupied->CabOccupied < 0 ? side::left : side::right].is_open, - mvOccupied->Doors.step_enabled, - mvOccupied->Power24vIsAvailable, - 0, - mvOccupied->LockPipe, - btLampkaRadioMessage.GetValue(), - }; -} - -bool TTrain::is_eztoer() const -{ - - return mvControlled->TrainType == train_type::emu && mvOccupied->BrakeSubsystem == TBrakeSubSystem::ss_ESt && mvControlled->Power24vIsAvailable == true && mvControlled->EpFuse == true && - mvControlled->DirActive != 0; // od yB -} - -// mover master controller to specified position -void TTrain::set_master_controller(double const Position) -{ - - auto positionchange{std::min(static_cast(Position), mvControlled->CoupledCtrl ? mvControlled->MainCtrlPosNo + mvControlled->ScndCtrlPosNo : mvControlled->MainCtrlPosNo) - - (mvControlled->CoupledCtrl ? mvControlled->MainCtrlPos + mvControlled->ScndCtrlPos : mvControlled->MainCtrlPos)}; - while (positionchange < 0 && true == mvControlled->DecMainCtrl(1)) - { - ++positionchange; - } - while (positionchange > 0 && true == mvControlled->IncMainCtrl(1)) - { - --positionchange; - } -} - -// moves train brake lever to specified position, potentially emits switch sound if conditions are met -void TTrain::set_train_brake(double const Position) -{ - - auto const originalbrakeposition{static_cast(100.0 * mvOccupied->fBrakeCtrlPos)}; - mvOccupied->BrakeLevelSet(Position); - - if (static_cast(100.0 * mvOccupied->fBrakeCtrlPos) == originalbrakeposition) - { - return; - } - - // sound feedback if the lever movement activates one of the switches - if (true == is_eztoer() && false == ((originalbrakeposition / 100 == 0 || originalbrakeposition / 100 >= 5) && (mvOccupied->BrakeCtrlPos == 0 || mvOccupied->BrakeCtrlPos >= 5)) && dsbPneumaticSwitch) - { - dsbPneumaticSwitch->play(); - } -} - -void TTrain::zero_charging_train_brake() -{ - using enum TBrakeHandle; - - if (mvOccupied->BrakeCtrlPos == -1 && DynamicObject->Controller != AIdriver && Global.iFeedbackMode < 3 && - (mvOccupied->BrakeHandle == FVel6 || mvOccupied->BrakeHandle == MHZ_EN57 || mvOccupied->BrakeHandle == MHZ_K8P)) - { - // Odskakiwanie hamulce EP - set_train_brake(0); - } -} - -void TTrain::set_train_brake_speed(TDynamicObject *Vehicle, int const Speed) -{ - - // visual feedback - // TODO: add setting indicator to vehicle class, for external lever/indicator - if (true == Vehicle->MoverParameters->BrakeDelaySwitch(Speed) && Vehicle == DynamicObject) - { - if (ggBrakeProfileCtrl.SubModel != nullptr) - { - ggBrakeProfileCtrl.UpdateValue((mvOccupied->BrakeDelayFlag & bdelay_R) != 0 ? 2.0 : static_cast(mvOccupied->BrakeDelayFlag - 1), dsbSwitch); - } - if (ggBrakeProfileG.SubModel != nullptr) - { - ggBrakeProfileG.UpdateValue(mvOccupied->BrakeDelayFlag == bdelay_G ? 1.0 : 0.0, dsbSwitch); - } - if (ggBrakeProfileR.SubModel != nullptr) - { - ggBrakeProfileR.UpdateValue((mvOccupied->BrakeDelayFlag & bdelay_R) != 0 ? 1.0 : 0.0, dsbSwitch); - } - } -} - -void TTrain::set_paired_open_motor_connectors_button(bool const State) -{ - - if (mvControlled->TrainType == train_type::et41 || mvControlled->TrainType == train_type::et42) - { - // crude implementation of the button affecting entire unit for multi-unit engines - // TODO: rework it into part of standard command propagation system - if (mvControlled->Couplers[end::front].Connected != nullptr && true == mvControlled->Couplers[end::front].CouplingFlag.HasAll(Coupling::permanent)) - { - mvControlled->Couplers[end::front].Connected->StLinSwitchOff = State; - } - if (mvControlled->Couplers[end::rear].Connected != nullptr && true == mvControlled->Couplers[end::rear].CouplingFlag.HasAll(Coupling::permanent)) - { - mvControlled->Couplers[end::rear].Connected->StLinSwitchOff = State; - } - } -} - -// locates nearest vehicle belonging to the consist -TDynamicObject *TTrain::find_nearest_consist_vehicle(bool freefly, glm::vec3 pos) const -{ - if (!freefly) - return DynamicObject; - - auto couplerindex{-2}; // scan for vehicle, not any specific coupler - auto *vehicle{DynamicObject->ABuScanNearestObject(pos, DynamicObject->GetTrack(), 1, 1500, couplerindex)}; - if (vehicle == nullptr) - vehicle = DynamicObject->ABuScanNearestObject(pos, DynamicObject->GetTrack(), -1, 1500, couplerindex); - // TBD, TODO: perform owner test for the located vehicle - return vehicle; -} - -// command handlers -void TTrain::OnCommand_aidriverenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // on press - if (Train->DynamicObject->Mechanik == nullptr) - { - return; - } - - if (true == Train->DynamicObject->Mechanik->AIControllFlag) - { - // żeby nie trzeba było rozłączać dla zresetowania - Train->DynamicObject->Mechanik->TakeControl(false); - } - Train->DynamicObject->Mechanik->TakeControl(true); - } -} - -void TTrain::OnCommand_aidriverdisable(TTrain *Train, command_data const &Command) -{ - - // on press - if (Command.action == GLFW_PRESS && Train->DynamicObject->Mechanik) - Train->DynamicObject->Mechanik->TakeControl(false); -} - -auto const EU07_CONTROLLER_BASERETURNDELAY{0.5f}; -auto const EU07_CONTROLLER_KEYBOARDETURNDELAY{1.5f}; - -void TTrain::OnCommand_jointcontrollerset(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - // on press or hold - // value controls brake in range 0-0.5, master controller in range 0.5-1.0 - if (Command.param1 >= 0.5) - { - Train->set_master_controller((Command.param1 * 2 - 1) * - (Train->mvControlled->CoupledCtrl ? Train->mvControlled->MainCtrlPosNo + Train->mvControlled->ScndCtrlPosNo : Train->mvControlled->MainCtrlPosNo)); - Train->m_mastercontrollerinuse = true; - // when SplitEDPneumaticBrake is active the joint controller's negative range - // commands the dedicated dynamic-brake lever instead of the local pneumatic brake - if (Train->mvControlled->SplitEDPneumaticBrake) - { - Train->mvControlled->DynamicBrakeLevelSet(0.0); - } - else - { - Train->mvOccupied->LocalBrakePosA = 0; - } - } - else - { - auto const negativeRange{std::clamp(1.0 - Command.param1 * 2, 0.0, 1.0)}; - if (Train->mvControlled->SplitEDPneumaticBrake) - { - // negative range of jointctrl drives only ED braking, local pneumatic brake stays untouched. - // snap to DBPN discrete stops so the lever animates step-by-step - auto const stepCount{std::max(1, Train->mvControlled->DynamicBrakeCtrlPosNo)}; - auto const snapped{std::round(negativeRange * stepCount) / stepCount}; - Train->mvControlled->DynamicBrakeLevelSet(snapped); - } - else - { - Train->mvOccupied->LocalBrakePosA = negativeRange; - } - if (Train->mvControlled->MainCtrlPowerPos() > 0) - { - Train->set_master_controller(Train->mvControlled->MainCtrlNoPowerPos()); - } - } - } - else - { - // release - Train->m_mastercontrollerinuse = false; - Train->m_mastercontrollerreturndelay = EU07_CONTROLLER_BASERETURNDELAY; // NOTE: keyboard return delay is omitted for other input sources - } -} - -void TTrain::OnCommand_mastercontrollerincrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - // on press or hold - auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; - // when SplitEDPneumaticBrake is true the joint controller's negative range maps - // to the dedicated dynamic-brake lever (DynamicBrakeCtrl) rather than to LocalBrake - auto const negativeRangeActive{splitMode ? Train->mvControlled->DynamicBrakeCtrlPos > 0.0 : Train->mvOccupied->LocalBrakePosA > 0.0}; - if (Train->ggJointCtrl.SubModel != nullptr && negativeRangeActive) - { - if (splitMode) - { - OnCommand_DynamicBrakeControllerDecrease(Train, Command); - Train->m_mastercontrollerinuse = true; - } - else - { - OnCommand_independentbrakedecrease(Train, Command); - } - } - else - { - Train->mvControlled->IncMainCtrl(1); - Train->m_mastercontrollerinuse = true; - } - } - else if (Command.action == GLFW_RELEASE) - { - // release - Train->m_mastercontrollerinuse = false; - Train->m_mastercontrollerreturndelay = EU07_CONTROLLER_KEYBOARDETURNDELAY + EU07_CONTROLLER_BASERETURNDELAY; - } -} - -void TTrain::OnCommand_mastercontrollerincreasefast(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - // on press or hold - auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; - auto const negativeRangeActive{splitMode ? Train->mvControlled->DynamicBrakeCtrlPos > 0.0 : Train->mvOccupied->LocalBrakePosA > 0.0}; - if (Train->ggJointCtrl.SubModel != nullptr && negativeRangeActive) - { - if (splitMode) - { - OnCommand_DynamicBrakeControllerDecreaseFast(Train, Command); - Train->m_mastercontrollerinuse = true; - } - else - { - OnCommand_independentbrakedecreasefast(Train, Command); - } - } - else - { - Train->mvControlled->IncMainCtrl(Train->mvControlled->MainCtrlPosNo); - Train->m_mastercontrollerinuse = true; - } - } - else - { - // release - Train->m_mastercontrollerinuse = false; - Train->m_mastercontrollerreturndelay = EU07_CONTROLLER_KEYBOARDETURNDELAY + EU07_CONTROLLER_BASERETURNDELAY; - } -} - -void TTrain::OnCommand_mastercontrollerdecrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - // on press or hold - auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; - if (Train->ggJointCtrl.SubModel != nullptr && Train->mvControlled->IsMainCtrlNoPowerPos()) - { - // negative range of jointctrl: ED brake when split, otherwise pneumatic local brake - if (splitMode) - { - OnCommand_DynamicBrakeControllerIncrease(Train, Command); - Train->m_mastercontrollerinuse = true; - } - else - { - OnCommand_independentbrakeincrease(Train, Command); - } - } - else - { - Train->mvControlled->DecMainCtrl(1); - Train->m_mastercontrollerinuse = true; - } - } - else if (Command.action == GLFW_RELEASE) - { - // release - Train->m_mastercontrollerinuse = false; - Train->m_mastercontrollerreturndelay = EU07_CONTROLLER_KEYBOARDETURNDELAY + EU07_CONTROLLER_BASERETURNDELAY; - } -} - -void TTrain::OnCommand_mastercontrollerdecreasefast(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - // on press or hold - auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; - if (Train->ggJointCtrl.SubModel != nullptr && Train->mvControlled->IsMainCtrlNoPowerPos()) - { - if (splitMode) - { - OnCommand_DynamicBrakeControllerIncreaseFast(Train, Command); - Train->m_mastercontrollerinuse = true; - } - else - { - OnCommand_independentbrakeincreasefast(Train, Command); - } - } - else - { - Train->mvControlled->DecMainCtrl(Train->mvControlled->MainCtrlPowerPos()); - Train->m_mastercontrollerinuse = true; - } - } - else - { - // release - Train->m_mastercontrollerinuse = false; - Train->m_mastercontrollerreturndelay = EU07_CONTROLLER_KEYBOARDETURNDELAY + EU07_CONTROLLER_BASERETURNDELAY; - } -} - -void TTrain::OnCommand_mastercontrollerset(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - // on press or hold - Train->set_master_controller(Command.param1); - Train->m_mastercontrollerinuse = true; - } - else - { - // release - Train->m_mastercontrollerinuse = false; - Train->m_mastercontrollerreturndelay = EU07_CONTROLLER_BASERETURNDELAY; // NOTE: keyboard return delay is omitted for other input sources - } -} -void TTrain::OnCommand_DynamicBrakeControllerIncrease(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_RELEASE) - { - return; - } - if (false == Train->mvControlled->SplitEDPneumaticBrake) - { - return; - } - - // step exactly one stop (1 / DBPN) per command, matching the discrete behaviour of jointctrl - Train->mvControlled->IncDynamicBrakeLevel(1.0f); -} - -void TTrain::OnCommand_DynamicBrakeControllerIncreaseFast(TTrain *Train, command_data const &Command) -{ - if (Command.action != GLFW_PRESS) - { - return; - } - if (false == Train->mvControlled->SplitEDPneumaticBrake) - { - return; - } - - Train->mvControlled->IncDynamicBrakeLevel(static_cast(Train->mvControlled->DynamicBrakeCtrlPosNo)); -} - -void TTrain::OnCommand_DynamicBrakeControllerDecrease(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_RELEASE) - { - return; - } - if (false == Train->mvControlled->SplitEDPneumaticBrake) - { - return; - } - - // step exactly one stop (1 / DBPN) per command, matching the discrete behaviour of jointctrl - Train->mvControlled->DecDynamicBrakeLevel(1.0f); -} - -void TTrain::OnCommand_DynamicBrakeControllerDecreaseFast(TTrain *Train, command_data const &Command) -{ - if (Command.action != GLFW_PRESS) - { - return; - } - if (false == Train->mvControlled->SplitEDPneumaticBrake) - { - return; - } - - Train->mvControlled->DecDynamicBrakeLevel(static_cast(Train->mvControlled->DynamicBrakeCtrlPosNo)); -} - -void TTrain::OnCommand_DynamicBrakeControllerSet(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_RELEASE) - { - return; - } - if (false == Train->mvControlled->SplitEDPneumaticBrake) - { - return; - } - - // when input source uses raw 0..1 value, snap to nearest DBPN step - auto const target{std::clamp(Command.param1, 0.0, 1.0)}; - auto const stepCount{std::max(1, Train->mvControlled->DynamicBrakeCtrlPosNo)}; - auto const snapped{std::round(target * stepCount) / stepCount}; - Train->mvControlled->DynamicBrakeLevelSet(snapped); -} - -void TTrain::OnCommand_secondcontrollerincrease(TTrain *Train, command_data const &Command) -{ - - if (Train->mvControlled->EngineType == TEngineType::DieselElectric && true == Train->mvControlled->ShuntModeAllow && true == Train->mvControlled->ShuntMode) - { - if (Command.action != GLFW_RELEASE) - { - Train->mvControlled->AnPos = std::clamp(Train->mvControlled->AnPos + 0.025, 0.0, 1.0); - } - } - else - { - // regular mode - // push or pushtoggle control type - if (Train->ggScndCtrl.is_push()) - { - if (Command.action == GLFW_PRESS) - { - // activate on press - Train->mvControlled->IncScndCtrl(1); - } - } - // toggle control type - else - { - if (Command.action != GLFW_RELEASE) - { - Train->mvControlled->IncScndCtrl(1); - } - } - // HACK: potentially animate push or pushtoggle control - if (Train->ggScndCtrl.is_push()) - { - auto const activeposition{1.f}; - auto const neutralposition{Train->ggScndCtrl.is_toggle() ? 0.5f : 0.f}; - Train->ggScndCtrl.UpdateValue(Command.action == GLFW_RELEASE ? neutralposition : activeposition, Train->dsbSwitch); - } - // potentially animate tempomat button, unless the cruise control has its own - if (Train->ggScndCtrlButton.is_push() && Train->mvControlled->ScndCtrlPos <= 1 && false == Train->mvControlled->IsSpeedCtrlSeparate()) - { - Train->ggScndCtrlButton.UpdateValue(Command.action == GLFW_RELEASE ? 0.f : 1.f, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_secondcontrollerincreasefast(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - // on press or hold - if (Train->mvControlled->EngineType == TEngineType::DieselElectric && true == Train->mvControlled->ShuntMode) - { - Train->mvControlled->AnPos = 1.0; - } - else - { - Train->mvControlled->IncScndCtrl(2); - } - } -} - -void TTrain::OnCommand_notchingrelaytoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvOccupied->AutoRelayFlag) - { - // turn on - Train->mvOccupied->AutoRelaySwitch(true); - } - else - { - // turn off - Train->mvOccupied->AutoRelaySwitch(false); - } - // visual feedback - Train->ggAutoRelayButton.UpdateValue(Train->mvOccupied->AutoRelayFlag ? 1.f : 0.f, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_tempomattoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggScndCtrlButton.is_push()) - { - // impulse switch - if (Command.action == GLFW_RELEASE) - { - // just move the button(s) back to default position - // visual feedback - Train->ggScndCtrlButton.UpdateValue(0.0, Train->dsbSwitch); - Train->ggScndCtrlOffButton.UpdateValue(0.0, Train->dsbSwitch); - return; - } - // glfw_press - if (false == Train->mvControlled->IsSpeedCtrlEngaged()) - { - // turn on if it's not active - Train->mvControlled->SpeedCtrlSwitch(true); - // visual feedback - Train->ggScndCtrlButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // otherwise turn off - Train->mvControlled->SpeedCtrlSwitch(false); - // visual feedback - if (Train->m_controlmapper.contains("tempomatoff_sw:")) - { - Train->ggScndCtrlOffButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - Train->ggScndCtrlButton.UpdateValue(1.0, Train->dsbSwitch); - } - } - } - else - { - // two-state switch - if (Command.action == GLFW_RELEASE) - { - return; - } - - if (false == Train->mvControlled->IsSpeedCtrlEngaged()) - { - // turn on - Train->mvControlled->SpeedCtrlSwitch(true); - // visual feedback - Train->ggScndCtrlButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // turn off - Train->mvControlled->SpeedCtrlSwitch(false); - // visual feedback - Train->ggScndCtrlButton.UpdateValue(0.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_distancecounteractivate(TTrain *Train, command_data const &Command) -{ - // NOTE: distance meter activation button is presumed to be of impulse type - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggDistanceCounterButton.UpdateValue(1.0, Train->dsbSwitch); - // activate or start anew - if (Train->mvOccupied->isDoubleClickForMeasureNeeded) - { - // handler tempomatu dla podwojnego kliku - if (Train->trainLenghtMeasureTimer >= 0.f) // jesli zdazylismy w czasie sekundy - Train->m_distancecounter = 0.f; // rozpoczynamy pomiar - else - Train->trainLenghtMeasureTimer = Train->mvOccupied->DistanceCounterDoublePressPeriod; // odpalamy zegarek od nowa - } - else - { - // dla pojedynczego kliku - Train->m_distancecounter = 0.f; - } - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggDistanceCounterButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_mucurrentindicatorothersourceactivate(TTrain *Train, command_data const &Command) -{ - - if (Train->ggNextCurrentButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Current Indicator Source switch is missing, or wasn't defined"); - } - return; - } - - if (Command.action == GLFW_PRESS) - { - // turn on - Train->ShowNextCurrent = true; - // visual feedback - Train->ggNextCurrentButton.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // turn off - Train->ShowNextCurrent = false; - // visual feedback - Train->ggNextCurrentButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_secondcontrollerdecrease(TTrain *Train, command_data const &Command) -{ - - if (Train->mvControlled->EngineType == TEngineType::DieselElectric && true == Train->mvControlled->ShuntMode) - { - if (Command.action != GLFW_RELEASE) - { - Train->mvControlled->AnPos = std::clamp(Train->mvControlled->AnPos - 0.025, 0.0, 1.0); - } - } - else - { - // regular mode - // push or pushtoggle control type - if (Train->ggScndCtrl.is_push()) - { - // basic push control can't decrease state, but pushtoggle can - if (true == Train->ggScndCtrl.is_toggle() && Command.action == GLFW_PRESS) - { - // activate on press - Train->mvControlled->DecScndCtrl(1); - } - } - // toggle control type - else - { - if (Command.action != GLFW_RELEASE) - { - Train->mvControlled->DecScndCtrl(1); - } - } - // HACK: potentially animate push or pushtoggle control - if (Train->ggScndCtrl.is_push()) - { - auto const activeposition{Train->ggScndCtrl.is_toggle() ? 0.f : 1.f}; - auto const neutralposition{Train->ggScndCtrl.is_toggle() ? 0.5f : 0.f}; - Train->ggScndCtrl.UpdateValue(Command.action == GLFW_RELEASE ? neutralposition : activeposition, Train->dsbSwitch); - } - // potentially animate tempomat button, unless the cruise control has its own - if (Train->ggScndCtrlButton.is_push() && Train->mvControlled->ScndCtrlPos <= 1 && false == Train->mvControlled->IsSpeedCtrlSeparate()) - { - if (Train->m_controlmapper.contains("tempomatoff_sw:")) - { - Train->ggScndCtrlOffButton.UpdateValue(Command.action == GLFW_RELEASE ? 0.f : 1.f, Train->dsbSwitch); - } - else - { - Train->ggScndCtrlButton.UpdateValue(Command.action == GLFW_RELEASE ? 0.f : 1.f, Train->dsbSwitch); - } - } - } -} - -void TTrain::OnCommand_secondcontrollerdecreasefast(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - // on press or hold - if (Train->mvControlled->EngineType == TEngineType::DieselElectric && true == Train->mvControlled->ShuntMode) - { - Train->mvControlled->AnPos = 0.0; - } - else - { - Train->mvControlled->DecScndCtrl(2); - } - } -} - -void TTrain::OnCommand_secondcontrollerset(TTrain *Train, command_data const &Command) -{ - - auto const targetposition{std::min(static_cast(Command.param1), Train->mvControlled->ScndCtrlPosNo)}; - // HACK: potentially animate push or pushtoggle control - if (Train->ggScndCtrl.is_push()) - { - auto const activeposition{Train->ggScndCtrl.is_toggle() ? - (targetposition < Train->mvControlled->ScndCtrlPos ? 0.f : - targetposition > Train->mvControlled->ScndCtrlPos ? 1.f : - Train->ggScndCtrl.GetDesiredValue()) : // leave the control in its current position if it hits the limit - targetposition == 0 ? 0.f : - 1.f}; - auto const neutralposition{Train->ggScndCtrl.is_toggle() ? 0.5f : 0.f}; - Train->ggScndCtrl.UpdateValue(Command.action == GLFW_RELEASE ? neutralposition : activeposition, Train->dsbSwitch); - } - // update control value - if (Command.action != GLFW_RELEASE) - { - // on press or hold - while (targetposition < Train->mvControlled->GetVirtualScndPos() && true == Train->mvControlled->DecScndCtrl(1)) - { - // all work is done in the header - } - while (targetposition > Train->mvControlled->GetVirtualScndPos() && true == Train->mvControlled->IncScndCtrl(1)) - { - // all work is done in the header - } - } -} - -void TTrain::OnCommand_independentbrakeincrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - - // when SplitEDPneumaticBrake is active the local brake key always operates - // the pneumatic local brake directly, never piggy-backing on the joint controller - auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; - auto const useStepped{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; - if (Train->mvOccupied->LocalBrake != TLocalBrake::ManualBrake) - { - if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->mvOccupied->MainCtrlPos > 0) - { - OnCommand_mastercontrollerdecrease(Train, Command); - } - else - { - Train->mvOccupied->IncLocalBrakeLevel(useStepped ? 1 : static_cast(Global.brake_speed * Command.time_delta * LocalBrakePosNo)); - if (useStepped) - { - Train->m_mastercontrollerinuse = true; - } - } - } - } -} - -void TTrain::OnCommand_independentbrakeincreasefast(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - - auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; - auto const useJointAnim{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; - if (Train->mvOccupied->LocalBrake != TLocalBrake::ManualBrake) - { - if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->mvOccupied->MainCtrlPos > 0) - { - OnCommand_mastercontrollerdecreasefast(Train, Command); - } - else - { - Train->mvOccupied->IncLocalBrakeLevel(LocalBrakePosNo); - if (useJointAnim) - { - Train->m_mastercontrollerinuse = true; - } - } - } - } -} - -void TTrain::OnCommand_independentbrakedecrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - - auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; - auto const useStepped{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; - if (Train->mvOccupied->LocalBrake != TLocalBrake::ManualBrake - // Ra 1014-06: AI potrafi zahamować pomocniczym mimo jego braku - odhamować jakoś trzeba - // TODO: sort AI out so it doesn't do things it doesn't have equipment for - || Train->mvOccupied->LocalBrakePosA > 0) - { - if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->mvOccupied->LocalBrakePosA == 0.0) - { - OnCommand_mastercontrollerincrease(Train, Command); - } - else - { - Train->mvOccupied->DecLocalBrakeLevel(useStepped ? 1 : static_cast(Global.brake_speed * Command.time_delta * LocalBrakePosNo)); - if (useStepped) - { - Train->m_mastercontrollerinuse = true; - } - } - } - } -} - -void TTrain::OnCommand_independentbrakedecreasefast(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - - auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; - auto const useJointAnim{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; - if (Train->mvOccupied->LocalBrake != TLocalBrake::ManualBrake - // Ra 1014-06: AI potrafi zahamować pomocniczym mimo jego braku - odhamować jakoś trzeba - // TODO: sort AI out so it doesn't do things it doesn't have equipment for - || Train->mvOccupied->LocalBrakePosA > 0) - { - if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->mvOccupied->LocalBrakePosA == 0.0) - { - OnCommand_mastercontrollerincreasefast(Train, Command); - } - else - { - Train->mvOccupied->DecLocalBrakeLevel(LocalBrakePosNo); - if (useJointAnim) - { - Train->m_mastercontrollerinuse = true; - } - } - } - } -} - -void TTrain::OnCommand_independentbrakeset(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - - Train->mvOccupied->LocalBrakePosA = std::clamp(Command.param1, 0.0, 1.0); - } - /* - Train->mvControlled->LocalBrakePos = ( - std::round( - interpolate( - 0.0, - LocalBrakePosNo, - clamp( - Command.param1, - 0.0, 1.0 ) ) ) ); - */ -} - -void TTrain::OnCommand_independentbrakebailoff(TTrain *Train, command_data const &Command) -{ - - if (false == Command.freefly) - { - // TODO: check if this set of conditions can be simplified. - // it'd be more flexible to have an attribute indicating whether bail off position is supported - if (Train->mvControlled->TrainType != train_type::emu && - (Train->mvControlled->EngineType == TEngineType::ElectricSeriesMotor || Train->mvControlled->EngineType == TEngineType::DieselElectric || - Train->mvControlled->EngineType == TEngineType::ElectricInductionMotor) && - Train->mvOccupied->BrakeCtrlPosNo > 0) - { - - if (Command.action == GLFW_PRESS) - { - // press or hold - // visual feedback - Train->ggReleaserButton.UpdateValue(1.0, Train->dsbSwitch); - - Train->mvOccupied->BrakeReleaser(1); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggReleaserButton.UpdateValue(0.0, Train->dsbSwitch); - - Train->mvOccupied->BrakeReleaser(0); - } - } - } - else - { - // car brake handling, while in walk mode - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; - if (vehicle != nullptr) - { - if (Command.action == GLFW_PRESS) - { - // press or hold - vehicle->MoverParameters->BrakeReleaser(1); - } - else if (Command.action == GLFW_RELEASE) - { - // release - vehicle->MoverParameters->BrakeReleaser(0); - } - } - } -} - -void TTrain::OnCommand_universalbrakebutton1(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // press or hold - // visual feedback - Train->ggUniveralBrakeButton1.UpdateValue(1.0, Train->dsbSwitch); - - Train->mvOccupied->UniversalBrakeButton(0, 1); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggUniveralBrakeButton1.UpdateValue(0.0, Train->dsbSwitch); - - Train->mvOccupied->UniversalBrakeButton(0, 0); - } -} - -void TTrain::OnCommand_universalbrakebutton2(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // press or hold - // visual feedback - Train->ggUniveralBrakeButton2.UpdateValue(1.0, Train->dsbSwitch); - - Train->mvOccupied->UniversalBrakeButton(1, 1); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggUniveralBrakeButton2.UpdateValue(0.0, Train->dsbSwitch); - - Train->mvOccupied->UniversalBrakeButton(1, 0); - } -} - -void TTrain::OnCommand_universalbrakebutton3(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // press or hold - // visual feedback - Train->ggUniveralBrakeButton3.UpdateValue(1.0, Train->dsbSwitch); - - Train->mvOccupied->UniversalBrakeButton(2, 1); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggUniveralBrakeButton3.UpdateValue(0.0, Train->dsbSwitch); - - Train->mvOccupied->UniversalBrakeButton(2, 0); - } -} - -void TTrain::OnCommand_trainbrakeincrease(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_REPEAT && Train->mvOccupied->BrakeHandle == TBrakeHandle::FV4a) - Train->mvOccupied->BrakeLevelAdd(Global.brake_speed * Command.time_delta * Train->mvOccupied->BrakeCtrlPosNo); - else if (Command.action == GLFW_PRESS && Train->mvOccupied->BrakeHandle != TBrakeHandle::FV4a) - Train->set_train_brake(Train->mvOccupied->fBrakeCtrlPos + Global.fBrakeStep); -} - -void TTrain::OnCommand_trainbrakedecrease(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_REPEAT && Train->mvOccupied->BrakeHandle == TBrakeHandle::FV4a) - Train->mvOccupied->BrakeLevelAdd(-Global.brake_speed * Command.time_delta * Train->mvOccupied->BrakeCtrlPosNo); - else if (Command.action == GLFW_PRESS && Train->mvOccupied->BrakeHandle != TBrakeHandle::FV4a) - Train->set_train_brake(Train->mvOccupied->fBrakeCtrlPos - Global.fBrakeStep); - else if (Command.action == GLFW_RELEASE) - { - // release - Train->zero_charging_train_brake(); - } -} - -void TTrain::OnCommand_trainbrakeset(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - // press or hold - Train->mvOccupied->BrakeLevelSet(std::lerp(Train->mvOccupied->Handle->GetPos(bh_MIN), Train->mvOccupied->Handle->GetPos(bh_MAX), std::clamp(Command.param1, 0.0, 1.0))); - } - else - { - // release - Train->zero_charging_train_brake(); - } -} - -void TTrain::OnCommand_trainbrakecharging(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - // press or hold - Train->set_train_brake(-1); - } - else - { - // release - Train->zero_charging_train_brake(); - } -} - -void TTrain::OnCommand_trainbrakerelease(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - Train->set_train_brake(0); - } -} - -void TTrain::OnCommand_trainbrakefirstservice(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - Train->set_train_brake(1); - } -} - -void TTrain::OnCommand_trainbrakeservice(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - Train->set_train_brake(Train->mvOccupied->BrakeCtrlPosNo / 2 + (Train->mvOccupied->BrakeHandle == TBrakeHandle::FV4a ? 1 : 0)); - } -} - -void TTrain::OnCommand_trainbrakefullservice(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - Train->set_train_brake(Train->mvOccupied->BrakeCtrlPosNo - 1); - } -} - -void TTrain::OnCommand_trainbrakehandleoff(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - Train->set_train_brake(Train->mvOccupied->Handle->GetPos(bh_NP)); - } -} - -void TTrain::OnCommand_trainbrakeemergency(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - Train->set_train_brake(Train->mvOccupied->Handle->GetPos(bh_EB)); - /* - if( Train->mvOccupied->BrakeCtrlPosNo <= 0.1 ) { - // hamulec bezpieczeństwa dla wagonów - Train->mvOccupied->RadioStopFlag = true; - } - */ - } -} - -void TTrain::OnCommand_trainbrakebasepressureincrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - - if (Train->mvOccupied->BrakeHandle == TBrakeHandle::FV4a) - { - Train->mvOccupied->BrakeCtrlPos2 = std::clamp(Train->mvOccupied->BrakeCtrlPos2 - 0.01, -1.5, 2.0); - } - else - { - Train->mvOccupied->BrakeLevelAdd(0.01); - } - } -} - -void TTrain::OnCommand_trainbrakebasepressuredecrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - - if (Train->mvOccupied->BrakeHandle == TBrakeHandle::FV4a) - { - Train->mvOccupied->BrakeCtrlPos2 = std::clamp(Train->mvOccupied->BrakeCtrlPos2 + 0.01, -1.5, 2.0); - } - else - { - Train->mvOccupied->BrakeLevelAdd(-0.01); - } - } -} - -void TTrain::OnCommand_trainbrakebasepressurereset(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - Train->mvOccupied->BrakeCtrlPos2 = 0; - } -} - -void TTrain::OnCommand_trainbrakeoperationtoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - auto const *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; - if (vehicle == nullptr) - { - return; - } - - vehicle->MoverParameters->Hamulec->SetBrakeStatus(vehicle->MoverParameters->Hamulec->GetBrakeStatus() ^ b_dmg); - // the brake is the player's now, the wagon inspector won't put it back on its own - vehicle->MoverParameters->BrakeCutOutByInspector = false; - } -} - -void TTrain::OnCommand_manualbrakeincrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; - if (vehicle == nullptr) - { - return; - } - - if (vehicle->MoverParameters->LocalBrake == TLocalBrake::ManualBrake || vehicle->MoverParameters->MBrake == true) - { - - vehicle->MoverParameters->IncManualBrakeLevel(1); - } - } -} - -void TTrain::OnCommand_manualbrakedecrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; - if (vehicle == nullptr) - { - return; - } - - if (vehicle->MoverParameters->LocalBrake == TLocalBrake::ManualBrake || vehicle->MoverParameters->MBrake == true) - { - - vehicle->MoverParameters->DecManualBrakeLevel(1); - } - } -} - -void TTrain::OnCommand_alarmchaintoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - if (false == Train->mvOccupied->AlarmChainFlag) - { - OnCommand_alarmchainenable(Train, Command); - } - else - { - OnCommand_alarmchaindisable(Train, Command); - } - } -} - -void TTrain::OnCommand_alarmchainenable(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - - // pull - Train->mvOccupied->AlarmChainSwitch(true); - // visual feedback - Train->ggAlarmChain.UpdateValue(1.0); - } -} - -void TTrain::OnCommand_alarmchaindisable(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - - // release - Train->mvOccupied->AlarmChainSwitch(false); - // visual feedback - Train->ggAlarmChain.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_wheelspinbrakeactivate(TTrain *Train, command_data const &Command) -{ - - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - if (Train->ggAntiSlipButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Wheelspin Brake button is missing, or wasn't defined"); - } - return; - } - - if (Train->mvOccupied->BrakeSystem != TBrakeSystem::ElectroPneumatic) - { - // standard behaviour - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggAntiSlipButton.UpdateValue(1.0, Train->dsbSwitch); - - // NOTE: system activation is (repeatedly) done in the train update routine - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggAntiSlipButton.UpdateValue(0.0); - } - } - else - { - // electro-pneumatic, custom case - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggAntiSlipButton.UpdateValue(1.0, Train->dsbPneumaticSwitch); - - // the EP fuse is the cab car's (Ctrl+Z switches mvOccupied's), checked by SwitchEPBrake with the rest of - // the control's supply - if (Train->mvOccupied->BrakeHandle == TBrakeHandle::St113) - { - Train->mvOccupied->SwitchEPBrake(1); - } - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggAntiSlipButton.UpdateValue(0.0); - - Train->mvOccupied->SwitchEPBrake(0); - } - } -} - -void TTrain::OnCommand_sandboxactivate(TTrain *Train, command_data const &Command) -{ - - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - if (Train->ggSandButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Sandbox activation button is missing, or wasn't defined"); - } - return; - } - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggSandButton.UpdateValue(1.0, Train->dsbSwitch); - - Train->mvControlled->SandboxManual(true); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggSandButton.UpdateValue(0.0); - - Train->mvControlled->SandboxManual(false); - } -} - -void TTrain::OnCommand_autosandboxtoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvOccupied->SandDoseAutoAllow) - { - // turn on - OnCommand_autosandboxactivate(Train, Command); - } - else - { - // turn off - OnCommand_autosandboxdeactivate(Train, Command); - } - } -}; - -void TTrain::OnCommand_autosandboxactivate(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SandboxAutoAllow(true); - Train->ggAutoSandButton.UpdateValue(1.0, Train->dsbSwitch); - } -}; - -void TTrain::OnCommand_autosandboxdeactivate(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SandboxAutoAllow(false); - Train->ggAutoSandButton.UpdateValue(0.0, Train->dsbSwitch); - } -}; - -void TTrain::OnCommand_epbrakecontrolenable(TTrain *Train, command_data const &Command) -{ - auto const istoggle{(static_cast(Train->ggEPFuseButton.type()) & static_cast(TGaugeType::toggle)) != 0}; - // command only works for bistable switch - if (Command.action == GLFW_PRESS && istoggle) - { - if (Train->mvOccupied->EpFuseSwitch(true)) - { - // audio feedback - if (Train->dsbPneumaticSwitch) - { - Train->dsbPneumaticSwitch->play(); - } - Train->ggEPFuseButton.UpdateValue(1.0f, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_epbrakecontroldisable(TTrain *Train, command_data const &Command) -{ - auto const istoggle{(static_cast(Train->ggEPFuseButton.type()) & static_cast(TGaugeType::toggle)) != 0}; - // command only works for bistable switch - if (Command.action == GLFW_PRESS && istoggle) - { - if (Train->mvOccupied->EpFuseSwitch(false)) - { - Train->ggEPFuseButton.UpdateValue(0.0f, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_epbrakecontroltoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - auto const ispush{(static_cast(Train->ggEPFuseButton.type()) & static_cast(TGaugeType::push)) != 0}; - auto const istoggle{(static_cast(Train->ggEPFuseButton.type()) & static_cast(TGaugeType::toggle)) != 0}; - - if (Command.action == GLFW_PRESS) - { - if (istoggle) - { - // switch state - if (false == Train->mvOccupied->EpFuse) - { - // turn on - // audio feedback - if (Train->mvOccupied->EpFuseSwitch(true) && Train->dsbPneumaticSwitch) - { - Train->dsbPneumaticSwitch->play(); - } - } - else - { - // turn off - Train->mvOccupied->EpFuseSwitch(false); - } - } - else if (ispush) - { - // potentially turn on - // audio feedback - if (Train->mvOccupied->EpFuseSwitch(true) && Train->dsbPneumaticSwitch) - { - Train->dsbPneumaticSwitch->play(); - } - } - // visual feedback - Train->ggEPFuseButton.UpdateValue(ispush ? 1.0f : // push or pushtoggle - Train->mvOccupied->EpFuse ? 1.0f : - 0.0f, // toggle - Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE && ispush) - { - // return the switch to neutral position - Train->ggEPFuseButton.UpdateValue(0.0f, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_trainbrakeoperationmodeincrease(TTrain *Train, command_data const &Command) -{ - - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Command.action == GLFW_PRESS && (Train->mvOccupied->BrakeOpModeFlag << 1 & Train->mvOccupied->BrakeOpModes) != 0) - { - // next mode - Train->mvOccupied->BrakeOpModeFlag <<= 1; - // visual feedback - Train->ggBrakeOperationModeCtrl.UpdateValue(Train->mvOccupied->BrakeOpModeFlag > 0 ? static_cast(std::log2(Train->mvOccupied->BrakeOpModeFlag)) : 0); // audio fallback - } -} - -void TTrain::OnCommand_trainbrakeoperationmodedecrease(TTrain *Train, command_data const &Command) -{ - - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Command.action == GLFW_PRESS && (Train->mvOccupied->BrakeOpModeFlag >> 1 & Train->mvOccupied->BrakeOpModes) != 0) - { - // previous mode - Train->mvOccupied->BrakeOpModeFlag >>= 1; - // visual feedback - Train->ggBrakeOperationModeCtrl.UpdateValue(Train->mvOccupied->BrakeOpModeFlag > 0 ? static_cast(std::log2(Train->mvOccupied->BrakeOpModeFlag)) : 0); - } -} - -void TTrain::OnCommand_brakeactingspeedincrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; - if (vehicle == nullptr) - { - return; - } - - if ((vehicle->MoverParameters->BrakeDelayFlag & bdelay_M) != 0) - { - // can't speed it up any more than this - return; - } - auto const fasterbrakesetting = vehicle->MoverParameters->BrakeDelayFlag < bdelay_R ? vehicle->MoverParameters->BrakeDelayFlag << 1 : vehicle->MoverParameters->BrakeDelayFlag | bdelay_M; - - Train->set_train_brake_speed(vehicle, fasterbrakesetting); - } -} - -void TTrain::OnCommand_brakeactingspeeddecrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; - if (vehicle == nullptr) - { - return; - } - - if (vehicle->MoverParameters->BrakeDelayFlag == bdelay_G) - { - // can't slow it down any more than this - return; - } - auto const slowerbrakesetting = vehicle->MoverParameters->BrakeDelayFlag < bdelay_M ? vehicle->MoverParameters->BrakeDelayFlag >> 1 : vehicle->MoverParameters->BrakeDelayFlag ^ bdelay_M; - - Train->set_train_brake_speed(vehicle, slowerbrakesetting); - } -} - -void TTrain::OnCommand_brakeactingspeedsetcargo(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; - if (vehicle == nullptr) - { - return; - } - - Train->set_train_brake_speed(vehicle, bdelay_G); - } -} - -void TTrain::OnCommand_brakeactingspeedsetpassenger(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; - if (vehicle == nullptr) - { - return; - } - - Train->set_train_brake_speed(vehicle, bdelay_P); - } -} - -void TTrain::OnCommand_brakeactingspeedsetrapid(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; - if (vehicle == nullptr) - { - return; - } - - Train->set_train_brake_speed(vehicle, bdelay_R); - } -} - -void TTrain::OnCommand_brakeloadcompensationincrease(TTrain *Train, command_data const &Command) -{ - - if (true == Command.freefly && Command.action == GLFW_PRESS) - { - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; - if (vehicle != nullptr) - { - vehicle->MoverParameters->IncBrakeMult(); - } - } -} - -void TTrain::OnCommand_brakeloadcompensationdecrease(TTrain *Train, command_data const &Command) -{ - - if (true == Command.freefly && Command.action == GLFW_PRESS) - { - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; - if (vehicle != nullptr) - { - vehicle->MoverParameters->DecBrakeMult(); - } - } -} - -void TTrain::OnCommand_mubrakingindicatortoggle(TTrain *Train, command_data const &Command) -{ - - if (Train->ggSignallingButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Braking Indicator switch is missing, or wasn't defined"); - } - return; - } - if (Train->mvControlled->TrainType != train_type::emu) - { - // - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvControlled->Signalling) - { - // turn on - Train->mvControlled->Signalling = true; - // visual feedback - Train->ggSignallingButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // turn off - Train->mvControlled->Signalling = false; - // visual feedback - Train->ggSignallingButton.UpdateValue(0.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_wiperswitchincrease(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - Train->mvOccupied->wiperSwitchPos++; - if (Train->mvOccupied->wiperSwitchPos > Train->mvOccupied->WiperListSize - 1) - Train->mvOccupied->wiperSwitchPos = Train->mvOccupied->WiperListSize - 1; - - // Visual feedback - Train->ggWiperSw.UpdateValue(static_cast(Train->mvOccupied->wiperSwitchPos), Train->dsbSwitch); - } -} -void TTrain::OnCommand_wiperswitchdecrease(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - Train->mvOccupied->wiperSwitchPos--; - if (Train->mvOccupied->wiperSwitchPos < 0) - Train->mvOccupied->wiperSwitchPos = 0; - - // visual feedback - Train->ggWiperSw.UpdateValue(static_cast(Train->mvOccupied->wiperSwitchPos), Train->dsbSwitch); - } -} - -void TTrain::OnCommand_reverserincrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - // HACK: master controller position isn't set in occupied vehicle in E(D)MUs - // so we do a manual check in relevant vehicle here - if (false == Train->mvControlled->EIMDirectionChangeAllow()) - { - return; - } - - // aktualizacja skrajnych pojazdów w składzie - if (Train->mvOccupied->DirectionForward() && Train->mvOccupied->DirActive && Train->DynamicObject->Mechanik) - { - - Train->DynamicObject->Mechanik->DirectionChange(); - } - } -} - -void TTrain::OnCommand_reverserdecrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - // HACK: master controller position isn't set in occupied vehicle in E(D)MUs - // so we do a manual check in relevant vehicle here - if (false == Train->mvControlled->EIMDirectionChangeAllow()) - { - return; - } - - // aktualizacja skrajnych pojazdów w składzie - if (Train->mvOccupied->DirectionBackward() && Train->mvOccupied->DirActive && Train->DynamicObject->Mechanik) - { - - Train->DynamicObject->Mechanik->DirectionChange(); - } - } -} - -void TTrain::OnCommand_reverserforwardhigh(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - // HACK: master controller position isn't set in occupied vehicle in E(D)MUs - // so we do a manual check in relevant vehicle here - if (false == Train->mvControlled->EIMDirectionChangeAllow()) - { - return; - } - - // HACK: try to move the reverser one position back, in case it's set to "high forward" - OnCommand_reverserdecrease(Train, Command); - - if (Train->mvOccupied->DirActive < 1) - { - - while (Train->mvOccupied->DirActive < 1 && true == Train->mvOccupied->DirectionForward()) - { - // all work is done in the header - } - // aktualizacja skrajnych pojazdów w składzie - if (Train->mvOccupied->DirActive == 1 && Train->DynamicObject->Mechanik) - { - - Train->DynamicObject->Mechanik->DirectionChange(); - } - } - OnCommand_reverserincrease(Train, Command); - } -} - -void TTrain::OnCommand_reverserforward(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - // HACK: master controller position isn't set in occupied vehicle in E(D)MUs - // so we do a manual check in relevant vehicle here - if (false == Train->mvControlled->EIMDirectionChangeAllow()) - { - return; - } - - // HACK: try to move the reverser one position back, in case it's set to "high forward" - // OnCommand_reverserdecrease( Train, Command ); - // visual feedback - Train->ggDirForwardButton.UpdateValue(1.0, Train->dsbSwitch); - - if (Train->mvOccupied->DirActive == 0) - { - - while (Train->mvOccupied->DirActive < 1 && true == Train->mvOccupied->DirectionForward()) - { - // all work is done in the header - } - // aktualizacja skrajnych pojazdów w składzie - if (Train->mvOccupied->DirActive == 1 && Train->DynamicObject->Mechanik) - { - - Train->DynamicObject->Mechanik->DirectionChange(); - } - } - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggDirForwardButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_reverserneutral(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - // HACK: master controller position isn't set in occupied vehicle in E(D)MUs - // so we do a manual check in relevant vehicle here - if (false == Train->mvControlled->EIMDirectionChangeAllow()) - { - return; - } - // visual feedback - Train->ggDirNeutralButton.UpdateValue(1.0, Train->dsbSwitch); - while (Train->mvOccupied->DirActive < 0 && true == Train->mvOccupied->DirectionForward()) - { - // all work is done in the header - } - while (Train->mvOccupied->DirActive > 0 && true == Train->mvOccupied->DirectionBackward()) - { - // all work is done in the header - } - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggDirNeutralButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_reverserbackward(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - // HACK: master controller position isn't set in occupied vehicle in E(D)MUs - // so we do a manual check in relevant vehicle here - if (false == Train->mvControlled->EIMDirectionChangeAllow()) - { - return; - } - Train->ggDirBackwardButton.UpdateValue(1.0, Train->dsbSwitch); - if (Train->mvOccupied->DirActive == 0) - { - - while (Train->mvOccupied->DirActive > -1 && true == Train->mvOccupied->DirectionBackward()) - { - // all work is done in the header - } - // aktualizacja skrajnych pojazdów w składzie - if (Train->mvOccupied->DirActive == -1 && Train->DynamicObject->Mechanik) - { - - Train->DynamicObject->Mechanik->DirectionChange(); - } - } - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggDirBackwardButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_alerteracknowledge(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggSecurityResetButton.UpdateValue(1.0, Train->dsbSwitch); - - if (Train->mvOccupied->TrainType == train_type::emu || Train->mvOccupied->DirActive != 0) - Train->mvOccupied->SecuritySystem.acknowledge_press(); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggSecurityResetButton.UpdateValue(0.0); - - if (Train->mvOccupied->TrainType == train_type::emu || Train->mvOccupied->DirActive != 0) - Train->mvOccupied->SecuritySystem.acknowledge_release(); - } -} - -void TTrain::OnCommand_cabsignalacknowledge(TTrain *Train, command_data const &Command) -{ - // TODO: visual feedback - if (Command.action == GLFW_PRESS) - { - if (Train->mvOccupied->SecuritySystem.has_separate_acknowledge()) - { - Train->mvOccupied->SecuritySystem.cabsignal_reset(); - Train->ggSHPResetButton.UpdateValue(1.0, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - Train->ggSHPResetButton.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_batterytoggle(TTrain *Train, command_data const &Command) -{ - if (Train->allowBatteryToggle || Command.action != GLFW_REPEAT) - { - // keep the switch from flipping back and forth if key is held down - if (false == Train->mvOccupied->Power24vIsAvailable) - { - // turn on - OnCommand_batteryenable(Train, Command); - } - else - { - // turn off - OnCommand_batterydisable(Train, Command); - } - } -} - -void TTrain::OnCommand_batteryenable(TTrain *Train, command_data const &Command) -{ - if (!Train->mvOccupied->isBatteryButtonImpulse) - { // regular button behavior - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); - Train->ggBatteryOnButton.UpdateValue(1.0f, Train->dsbSwitch); - - Train->mvOccupied->BatterySwitch(true); - Train->allowBatteryToggle = false; - // side-effects - if (Train->mvOccupied->LightsPosNo > 0) - { - Train->Dynamic()->SetLights(); - } - } - else if (Command.action == GLFW_RELEASE) - { - if (Train->ggBatteryButton.type() == TGaugeType::push) - { - // return the switch to neutral position - Train->ggBatteryButton.UpdateValue(0.5f); - } - Train->ggBatteryOnButton.UpdateValue(0.0f, Train->dsbSwitch); - Train->allowBatteryToggle = true; - } - } - else // impulse button behavior - { - if (Command.action == GLFW_PRESS) - { - if (Train->mvOccupied->shouldHoldBatteryButton) - { - // jesli przycisk trzeba przytrzymac - Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); - Train->ggBatteryOnButton.UpdateValue(1.0f, Train->dsbSwitch); - Train->fBatteryTimer = Train->mvOccupied->BatteryButtonHoldTime; // start timer - } - else - { - // jesli przycisk dziala od razu - Train->mvOccupied->BatterySwitch(true); - Train->allowBatteryToggle = false; - // side-effects - if (Train->mvOccupied->LightsPosNo > 0) - { - Train->Dynamic()->SetLights(); - } - - // visual feedback - Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); - Train->ggBatteryOnButton.UpdateValue(1.0f, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggBatteryButton.UpdateValue(0.0f, Train->dsbSwitch); - Train->ggBatteryOnButton.UpdateValue(0.0f, Train->dsbSwitch); - Train->fBatteryTimer = -1.f; // - Train->allowBatteryToggle = true; - Train->mvOccupied->batterySwAlreadyFired = false; - } - else if (Command.action == GLFW_REPEAT && Train->mvOccupied->shouldHoldBatteryButton) - { - // trzymamy przycisk - if (Train->fBatteryTimer <= 0.0 && Train->mvOccupied->Battery == false && !Train->mvOccupied->batterySwAlreadyFired) - { - Train->mvOccupied->BatterySwitch(true); - Train->mvOccupied->batterySwAlreadyFired = true; - - // side-effects - if (Train->mvOccupied->LightsPosNo > 0) - { - Train->Dynamic()->SetLights(); - } - Train->allowBatteryToggle = false; - } - } - } -} - -void TTrain::OnCommand_batterydisable(TTrain *Train, command_data const &Command) -{ - if (!Train->mvOccupied->isBatteryButtonImpulse) - { // regular button behavior - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggBatteryButton.UpdateValue(0.0f, Train->dsbSwitch); - Train->ggBatteryOffButton.UpdateValue(1.0f, Train->dsbSwitch); - - Train->mvOccupied->BatterySwitch(false); - - // side-effects - if (Train->mvOccupied->LightsPosNo > 0) - { - Train->Dynamic()->SetLights(); - } - } - else if (Command.action == GLFW_RELEASE) - { - if (Train->ggBatteryButton.type() == TGaugeType::push) - { - // return the switch to neutral position - Train->ggBatteryButton.UpdateValue(0.5f); - } - Train->ggBatteryOffButton.UpdateValue(0.0f, Train->dsbSwitch); - } - } - else // impulse button behavior - { - if (Command.action == GLFW_PRESS) - { - if (Train->mvOccupied->shouldHoldBatteryButton) - { - // jesli przycisk trzeba przytrzymac - Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); - Train->ggBatteryOffButton.UpdateValue(1.0f, Train->dsbSwitch); - Train->fBatteryTimer = Train->mvOccupied->BatteryButtonHoldTime; // start timer - } - else - { - // jesli przycisk dziala od razu - Train->mvOccupied->BatterySwitch(false); - Train->allowBatteryToggle = false; - - // side-effects - if (Train->mvOccupied->LightsPosNo > 0) - { - Train->Dynamic()->SetLights(); - } - // visual feedback - Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); - Train->ggBatteryOffButton.UpdateValue(1.0f, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggBatteryButton.UpdateValue(0.0f, Train->dsbSwitch); - Train->ggBatteryOffButton.UpdateValue(0.0f, Train->dsbSwitch); - Train->allowBatteryToggle = true; - Train->mvOccupied->batterySwAlreadyFired = false; - } - else if (Command.action == GLFW_REPEAT && Train->mvOccupied->shouldHoldBatteryButton) - { - // trzymamy przycisk - if (Train->fBatteryTimer <= 0.0 && Train->mvOccupied->Battery == true && !Train->mvOccupied->batterySwAlreadyFired) - { - Train->mvOccupied->BatterySwitch(false); - Train->mvOccupied->batterySwAlreadyFired = true; - - // side-effects - if (Train->mvOccupied->LightsPosNo > 0) - { - Train->Dynamic()->SetLights(); - } - Train->allowBatteryToggle = false; - } - } - } -} - -void TTrain::OnCommand_cabactivationtoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_REPEAT) - { - // keep the switch from flipping back and forth if key is held down - if (0 == Train->mvOccupied->CabActive) - { - // turn on - OnCommand_cabactivationenable(Train, Command); - } - else - { - // turn off - OnCommand_cabactivationdisable(Train, Command); - } - } -} - -void TTrain::OnCommand_cabactivationenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - if (Train->ggCabActivationButton.type() == TGaugeType::push) - { - Train->ggCabActivationButton.UpdateValue(1.0f, Train->dsbSwitch); - } - - Train->mvOccupied->CabActivisation(); - - // side-effects - if (Train->mvOccupied->LightsPosNo > 0) - { - Train->Dynamic()->SetLights(); - } - } - else if (Command.action == GLFW_RELEASE && Train->ggCabActivationButton.type() == TGaugeType::push) - { - // return the switch to neutral position - Train->ggCabActivationButton.UpdateValue(0.5f); - } -} - -void TTrain::OnCommand_cabactivationdisable(TTrain *Train, command_data const &Command) -{ - // TBD, TODO: ewentualnie zablokować z FIZ, np. w samochodach się nie odłącza akumulatora - if (Command.action == GLFW_PRESS) - { - // visual feedback - if (Train->ggCabActivationButton.type() == TGaugeType::push) - { - Train->ggCabActivationButton.UpdateValue(0.0f, Train->dsbSwitch); - } - - Train->mvOccupied->CabDeactivisation(); - if (Train->mvOccupied->LightsPosNo > 0 && Train->mvOccupied->InactiveCabFlag & activation::redmarkers) - { - Train->Dynamic()->SetLights(); - } - } - else if (Command.action == GLFW_RELEASE && Train->ggCabActivationButton.type() == TGaugeType::push) - { - // return the switch to neutral position - Train->ggCabActivationButton.UpdateValue(0.5f); - } -} - -void TTrain::OnCommand_pantographtogglefront(TTrain *Train, command_data const &Command) -{ - - // HACK: presence of pantograph selector prevents manual operation of the individual valves - if (Train->m_controlmapper.contains("pantselect_sw:")) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const &pantograph{Train->mvPantographUnit->Pantographs[end::front]}; - auto const state{pantograph.valve.is_enabled || pantograph.is_active}; // fallback for impulse switches - if (state) - { - OnCommand_pantographlowerfront(Train, Command); - } - else - { - OnCommand_pantographraisefront(Train, Command); - } - } - else if (Command.action == GLFW_RELEASE) - { - // impulse switches return automatically to neutral position - if (Train->mvOccupied->PantSwitchType == "impulse") - { - auto const ismanual{Train->iCabn == 0}; - Train->mvOccupied->OperatePantographValve(end::front, operation_t::none, ismanual ? range_t::local : range_t::consist); - } - } -} - -void TTrain::OnCommand_pantographtogglerear(TTrain *Train, command_data const &Command) -{ - - // HACK: presence of pantograph selector prevents manual operation of the individual valves - if (Train->m_controlmapper.contains("pantselect_sw:")) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const &pantograph{Train->mvPantographUnit->Pantographs[end::rear]}; - auto const state{pantograph.valve.is_enabled || pantograph.is_active}; // fallback for impulse switches - if (state) - { - OnCommand_pantographlowerrear(Train, Command); - } - else - { - OnCommand_pantographraiserear(Train, Command); - } - } - else if (Command.action == GLFW_RELEASE) - { - // impulse switches return automatically to neutral position - if (Train->mvOccupied->PantSwitchType == "impulse") - { - auto const ismanual{Train->iCabn == 0}; - Train->mvOccupied->OperatePantographValve(end::rear, operation_t::none, ismanual ? range_t::local : range_t::consist); - } - } -} - -void TTrain::OnCommand_pantographraisefront(TTrain *Train, command_data const &Command) -{ - - // HACK: presence of pantograph selector prevents manual operation of the individual valves - if (Train->m_controlmapper.contains("pantselect_sw:")) - { - return; - } - // prevent operation without submodel outside of engine compartment - if (Train->iCabn != 0 && false == Train->m_controlmapper.contains("pantfront_sw:")) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers - auto const ismanual{Train->iCabn == 0}; - Train->mvOccupied->OperatePantographValve(end::front, Train->mvOccupied->PantSwitchType == "impulse" ? operation_t::enable_on : operation_t::enable, - ismanual ? range_t::local : range_t::consist); - } - else if (Command.action == GLFW_RELEASE) - { - // NOTE: bit of a hax here, we're reusing button reset routine so we don't need a copy in every branch - OnCommand_pantographtogglefront(Train, Command); - } -} - -void TTrain::OnCommand_pantographraiserear(TTrain *Train, command_data const &Command) -{ - - // HACK: presence of pantograph selector prevents manual operation of the individual valves - if (Train->m_controlmapper.contains("pantselect_sw:")) - { - return; - } - // prevent operation without submodel outside of engine compartment - if (Train->iCabn != 0 && false == Train->m_controlmapper.contains("pantrear_sw:")) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers - auto const ismanual{Train->iCabn == 0}; - Train->mvOccupied->OperatePantographValve(end::rear, Train->mvOccupied->PantSwitchType == "impulse" ? operation_t::enable_on : operation_t::enable, - ismanual ? range_t::local : range_t::consist); - } - else if (Command.action == GLFW_RELEASE) - { - // NOTE: bit of a hax here, we're reusing button reset routine so we don't need a copy in every branch - OnCommand_pantographtogglerear(Train, Command); - } -} - -void TTrain::OnCommand_pantographlowerfront(TTrain *Train, command_data const &Command) -{ - - // HACK: presence of pantograph selector prevents manual operation of the individual valves - if (Train->m_controlmapper.contains("pantselect_sw:")) - { - return; - } - // prevent operation without submodel outside of engine compartment - if (Train->iCabn != 0 && false == Train->m_controlmapper.contains(Train->mvOccupied->PantSwitchType == "impulse" ? "pantfrontoff_sw:" : "pantfront_sw:")) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers - auto const ismanual{Train->iCabn == 0}; - Train->mvOccupied->OperatePantographValve(end::front, Train->mvOccupied->PantSwitchType == "impulse" ? operation_t::disable_on : operation_t::disable, - ismanual ? range_t::local : range_t::consist); - } - else if (Command.action == GLFW_RELEASE) - { - // NOTE: bit of a hax here, we're reusing button reset routine so we don't need a copy in every branch - OnCommand_pantographtogglefront(Train, Command); - } -} - -void TTrain::OnCommand_pantographlowerrear(TTrain *Train, command_data const &Command) -{ - - // HACK: presence of pantograph selector prevents manual operation of the individual valves - if (Train->m_controlmapper.contains("pantselect_sw:")) - { - return; - } - - if (Train->iCabn != 0 && false == Train->m_controlmapper.contains(Train->mvOccupied->PantSwitchType == "impulse" ? "pantrearoff_sw:" : "pantrear_sw:")) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers - auto const ismanual{Train->iCabn == 0}; - Train->mvOccupied->OperatePantographValve(end::rear, Train->mvOccupied->PantSwitchType == "impulse" ? operation_t::disable_on : operation_t::disable, - ismanual ? range_t::local : range_t::consist); - } - else if (Command.action == GLFW_RELEASE) - { - // NOTE: bit of a hax here, we're reusing button reset routine so we don't need a copy in every branch - OnCommand_pantographtogglerear(Train, Command); - } -} - -void TTrain::OnCommand_pantographlowerall(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggPantAllDownButton.SubModel == nullptr) - { - // TODO: expand definition of cab controls so we can know if the control is present without testing for presence of 3d switch - if (Command.action == GLFW_PRESS) - { - WriteLog("Lower All Pantographs switch is missing, or wasn't defined"); - } - return; - } - - if (Train->ggPantAllDownButton.type() == TGaugeType::toggle) - { - // two-state switch, only cares about press events - if (Command.action == GLFW_PRESS) - { - Train->mvPantographUnit->DropAllPantographs(false == Train->mvPantographUnit->PantAllDown); - // visual feedback - Train->ggPantAllDownButton.UpdateValue(Train->mvPantographUnit->PantAllDown ? 1.0 : 0.0, Train->dsbSwitch); - } - } - else - { - // impulse switch - Train->mvControlled->DropAllPantographs(Command.action == GLFW_PRESS); - // visual feedback - Train->ggPantAllDownButton.UpdateValue(Command.action == GLFW_PRESS ? 1.0 : 0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_pantographselectnext(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_PRESS) - { - return; - } - - if (false == Train->m_controlmapper.contains("pantselect_sw:")) - { - return; - } - - Train->change_pantograph_selection(1); -} - -void TTrain::OnCommand_pantographselectprevious(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_PRESS) - { - return; - } - - if (false == Train->m_controlmapper.contains("pantselect_sw:")) - { - return; - } - - Train->change_pantograph_selection(-1); -} - -void TTrain::OnCommand_pantographtoggleselected(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // recalculate pantograph state (hujhujhuj) - Train->change_pantograph_selection(1); - Train->change_pantograph_selection(-1); - - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const state{Train->mvPantographUnit->PantsValve.is_enabled || Train->mvPantographUnit->PantsValve.is_active}; // fallback for impulse switches - if (state) - { - OnCommand_pantographlowerselected(Train, Command); - } - else - { - OnCommand_pantographraiseselected(Train, Command); - } - } - else if (Command.action == GLFW_RELEASE) - { - // impulse switches return automatically to neutral position - if (Train->m_controlmapper.contains("pantselectedoff_sw:")) - { - // two buttons setup - if (Train->ggPantSelectedButton.type() != TGaugeType::toggle) - { - Train->mvOccupied->OperatePantographsValve(operation_t::enable_off); - // visual feedback - Train->ggPantSelectedButton.UpdateValue(0.0, Train->dsbSwitch); - } - if (Train->ggPantSelectedDownButton.type() != TGaugeType::toggle) - { - Train->mvOccupied->OperatePantographsValve(operation_t::disable_off); - // visual feedback - Train->ggPantSelectedDownButton.UpdateValue(0.0, Train->dsbSwitch); - } - } - else - { - if (Train->ggPantSelectedButton.type() != TGaugeType::toggle) - { - // special case, just one impulse switch controlling both states - // with neutral position mid-way - Train->mvOccupied->OperatePantographsValve(operation_t::none); - // visual feedback - Train->ggPantSelectedButton.UpdateValue(0.5, Train->dsbSwitch); - } - } - } -} - -void TTrain::OnCommand_pantographraiseselected(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // raise selected - Train->mvOccupied->OperatePantographsValve(Train->ggPantSelectedButton.type() != TGaugeType::toggle ? operation_t::enable_on : operation_t::enable); - // visual feedback - Train->ggPantSelectedButton.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // NOTE: bit of a hax here, we're reusing button reset routine so we don't need a copy in every branch - OnCommand_pantographtoggleselected(Train, Command); - } -} - -void TTrain::OnCommand_pantographlowerselected(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // lower selected - Train->mvOccupied->OperatePantographsValve(Train->ggPantSelectedDownButton.type() != TGaugeType::toggle ? operation_t::disable_on : operation_t::disable); - // visual feedback - if (Train->m_controlmapper.contains("pantselectedoff_sw:")) - { - // two button setup - Train->ggPantSelectedDownButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // single button - Train->ggPantSelectedButton.UpdateValue(0.0, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - // NOTE: bit of a hax here, we're reusing button reset routine so we don't need a copy in every branch - OnCommand_pantographtoggleselected(Train, Command); - } -} - -void TTrain::update_pantograph_valves() -{ - using enum operation_t; - - auto const &presets{mvOccupied->PantsPreset.first}; - auto const &selection{mvOccupied->PantsPreset.second[cab_to_end()]}; - - auto const preset{presets[selection] - '0'}; - auto const swapends{cab_to_end() != end::front}; - // check desired states for both pantographs; value: whether the pantograph should be raised - auto const frontstate{preset & (swapends ? 2 : 1)}; - auto const rearstate{preset & (swapends ? 1 : 2)}; - mvOccupied->OperatePantographValve(end::front, frontstate ? enable : disable); - mvOccupied->OperatePantographValve(end::rear, rearstate ? enable : disable); -} - -void TTrain::change_pantograph_selection(int const Change) -{ - - auto const &presets{mvOccupied->PantsPreset.first}; - auto &selection{mvOccupied->PantsPreset.second[cab_to_end()]}; - auto const initialstate{selection}; - selection = std::clamp(selection + Change, 0, std::max(static_cast(presets.size() - 1), 0)); - - if (selection == initialstate) - { - return; - } // no change, nothing to do - - // potentially adjust pantograph valves to match the new state - if (false == m_controlmapper.contains("pantvalves_sw:")) - { - update_pantograph_valves(); - } -} - -void TTrain::OnCommand_pantographvalvesupdate(TTrain *Train, command_data const &Command) -{ - - bool hasSeparateSwitches = Train->m_controlmapper.contains("pantvalvesupdate_bt:") && Train->m_controlmapper.contains("pantvalvesoff_bt:"); - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - if (hasSeparateSwitches) - { - // implement action - Train->update_pantograph_valves(); - // visual feedback - Train->ggPantValvesUpdate.UpdateValue(1.0, Train->dsbSwitch); - } - - // Old logic to maintain compatibility - else - { - Train->update_pantograph_valves(); - Train->ggPantValvesButton.UpdateValue(1.0, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - // NOTE: pantvalves_sw: is a specialized button, with no toggle behavior support - if (hasSeparateSwitches) - Train->ggPantValvesUpdate.UpdateValue(0.5, Train->dsbSwitch); - - // Old logic to maintain compatibility - else - Train->ggPantValvesButton.UpdateValue(0.5, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_pantographvalvesoff(TTrain *Train, command_data const &Command) -{ - - bool hasSeparateSwitches = Train->m_controlmapper.contains("pantvalvesupdate_bt:") && Train->m_controlmapper.contains("pantvalvesoff_bt:"); - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // implement action - Train->mvOccupied->OperatePantographValve(end::front, operation_t::disable); - Train->mvOccupied->OperatePantographValve(end::rear, operation_t::disable); - // visual feedback - if (hasSeparateSwitches) - Train->ggPantValvesOff.UpdateValue(1.0, Train->dsbSwitch); - else - Train->ggPantValvesButton.UpdateValue(0.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - // NOTE: pantvalves_sw: is a speciali zed button, with no toggle behavior support - if (hasSeparateSwitches) - Train->ggPantValvesOff.UpdateValue(0.f, Train->dsbSwitch); - else - Train->ggPantValvesButton.UpdateValue(0.5, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_pantographcompressorvalvetoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only react to press - if (Train->mvControlled->bPantKurek3 == false) - { - // connect pantographs with primary tank - OnCommand_pantographcompressorvalveenable(Train, Command); - } - else - { - // connect pantograps with pantograph compressor - OnCommand_pantographcompressorvalvedisable(Train, Command); - } - } -} - -void TTrain::OnCommand_pantographcompressorvalveenable(TTrain *Train, command_data const &Command) -{ - - - if (auto const valveispresent{Train->ggPantCompressorValve.SubModel != nullptr || (Train->mvOccupied == Train->mvPantographUnit && Train->iCabn == 0)}; false == valveispresent) - { - // tylko w maszynowym, unless actual device is present - return; - } - - if (Command.action == GLFW_PRESS) - { - // only react to press - // connect pantographs with primary tank - Train->mvControlled->bPantKurek3 = true; - // visual feedback: - Train->ggPantCompressorValve.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_pantographcompressorvalvedisable(TTrain *Train, command_data const &Command) -{ - - - if (auto const valveispresent{Train->ggPantCompressorValve.SubModel != nullptr || (Train->mvOccupied == Train->mvPantographUnit && Train->iCabn == 0)}; false == valveispresent) - { - // tylko w maszynowym, unless actual device is present - return; - } - - if (Command.action == GLFW_PRESS) - { - // only react to press - // connect pantograps with pantograph compressor - Train->mvControlled->bPantKurek3 = false; - // visual feedback: - Train->ggPantCompressorValve.UpdateValue(1.0); - } -} - -void TTrain::OnCommand_pantographcompressoractivate(TTrain *Train, command_data const &Command) -{ - - // tylko w maszynowym, unless actual device is present - if (auto const switchispresent{Train->m_controlmapper.contains("pantcompressor_sw:") || (Train->mvOccupied == Train->mvPantographUnit && Train->iCabn == 0)}; false == switchispresent) - { - return; - } - - if (Command.action != GLFW_RELEASE) - { - // press or hold to activate - if (Train->mvPantographUnit->PantPress < 4.8 && true == Train->mvPantographUnit->Power24vIsAvailable) - { - // needs live power source and low enough pressure to work - Train->mvPantographUnit->PantCompFlag = true; - } - // visual feedback - Train->ggPantCompressorButton.UpdateValue(1.0); - } - else - { - // release to disable - Train->mvPantographUnit->PantCompFlag = false; - // visual feedback - Train->ggPantCompressorButton.UpdateValue(0.0); - } -} - -namespace -{ -// whether the cab's main_off_bt is the bistable lever of the line breaker's hold coil (eu07/maszyna#364) -bool is_hold_coil_lever(TGauge const &Button) -{ - return Button.SubModel != nullptr && hold_coil_lever::is_bistable(Button.type_declared(), Button.type() == TGaugeType::toggle); -} -} // namespace - -void TTrain::OnCommand_linebreakertoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // press or hold... - // a single two-state lever stays where it was put, also when the line breaker gets knocked out - auto const latchinglever{Train->ggMainOnButton.SubModel == nullptr && Train->ggMainOffButton.SubModel == nullptr && Train->ggMainButton.SubModel != nullptr && - Train->ggMainButton.type() == TGaugeType::toggle}; - switch (linebreaker::pressed(Train->m_linebreakerstate, latchinglever, Train->ggMainButton.GetDesiredValue() > 0.5)) - { - case linebreaker::toggle::close: - // ...to close the circuit - if (is_hold_coil_lever(Train->ggMainOffButton) && hold_coil_lever::cuts_off(Train->ggMainOffButton.GetDesiredValue())) - { - // the one key works both controls: the hold coil lever goes back on first, or the line breaker couldn't close - Train->ggMainOffButton.UpdateValue(0.0, Train->dsbSwitch); - } - // NOTE: bit of a dirty shortcut here - OnCommand_linebreakerclose(Train, Command); - break; - case linebreaker::toggle::open: - // ...to open the circuit, or to put the lever off if the circuit was already opened - OnCommand_linebreakeropen(Train, Command); - break; - default: - break; - } - } - else if (Command.action == GLFW_RELEASE) - { - // release... - if (Train->ggMainOnButton.SubModel != nullptr || Train->ggMainButton.type() != TGaugeType::toggle) - { - // only impulse switches react to release events - // NOTE: we presume dedicated state switch is of impulse type - if (Train->m_linebreakerstate == linebreaker::state::open) - { - // ...after opening circuit, or holding for too short time to close it - OnCommand_linebreakeropen(Train, Command); - } - else - { - // ...after closing the circuit - // NOTE: bit of a dirty shortcut here - OnCommand_linebreakerclose(Train, Command); - } - } - // HACK: ignition key ignores lack of submodel, so we can start vehicles without any modeled controls - Train->ggIgnitionKey.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_linebreakeropen(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - if (is_hold_coil_lever(Train->ggMainOffButton)) - { - // the bistable lever goes over to its other position and stays there - auto const position{hold_coil_lever::operated(Train->ggMainOffButton.GetDesiredValue())}; - Train->ggMainOffButton.UpdateValue(position, Train->dsbSwitch); - if (false == hold_coil_lever::cuts_off(position)) - { - // the hold coil is fed again, which by itself doesn't close the line breaker - return; - } - } - else if (Train->ggMainOffButton.SubModel != nullptr) - { - Train->ggMainOffButton.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Train->ggMainButton.SubModel != nullptr) - { - Train->ggMainButton.UpdateValue(0.0, Train->dsbSwitch); - } - else if (Train->ggMainOnButton.SubModel != nullptr && false == Train->mvControlled->MainCircuitOpensWithStarterOnly()) - { - // NOTE: legacy behaviour, for vehicles equipped only with impulse close switch - // it doesn't make any real sense to animate this one, but some people can't get over how there's no visual reaction to their keypress - Train->ggMainOnButton.UpdateValue(1.0, Train->dsbSwitch); - return; - } - // a diesel with only the starter button gets its engine stopped. the button stays put: held down, it would start the engine again - // play sound immediately when the switch is hit, not after release - Train->fMainRelayTimer = 0.0f; - - if (Train->m_linebreakerstate == linebreaker::state::open) - { - return; - } // already in the desired state - - if (true == Train->mvControlled->MainSwitch(false, Train->mvControlled->MainSwitchRange())) - { - Train->m_linebreakerstate = linebreaker::state::open; - if (Train->mvControlled->MainSwitchRange() != range_t::local) - { - // the engines of the vehicles in multiple stopped along: their two-state switches go off too, left on - // they'd start them again after the delay - for (auto &controls : Train->m_remotelinebreakers) - { - if (controls.main_switch.SubModel != nullptr && controls.main_switch.type() == TGaugeType::toggle) - { - controls.main_switch.UpdateValue(0.0); - } - } - } - } - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - // we don't exactly know which of the two buttons was used, so reset both - // for setup with two separate swiches - if (Train->ggMainOnButton.SubModel != nullptr) - { - Train->ggMainOnButton.UpdateValue(0.0, Train->dsbSwitch); - } - if (Train->ggMainOffButton.SubModel != nullptr && false == is_hold_coil_lever(Train->ggMainOffButton)) - { - // (the bistable hold coil lever stays where it was put) - Train->ggMainOffButton.UpdateValue(0.0, Train->dsbSwitch); - } - // and the two-state switch too, for good measure - if (Train->ggMainButton.SubModel != nullptr) - { - Train->ggMainButton.UpdateValue(Train->ggMainButton.type() != TGaugeType::toggle ? 0.5 : 0.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_linebreakerclose(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - if (Train->ggMainOnButton.SubModel != nullptr) - { - // two separate switches to close and break the circuit - Train->ggMainOnButton.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Train->ggMainButton.SubModel != nullptr) - { - // single two-state switch - Train->ggMainButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // no switch capable of doing the job - // HACK: ignition key ignores lack of submodel, so we can start vehicles without any modeled controls - Train->ggIgnitionKey.UpdateValue(1.0); - return; - } - // the actual closing of the line breaker is handled in the train update routine - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - if (Train->ggMainOnButton.SubModel != nullptr) - { - // setup with two separate switches - Train->ggMainOnButton.UpdateValue(0.0, Train->dsbSwitch); - } - else if (Train->ggMainButton.SubModel != nullptr && Train->ggMainButton.type() != TGaugeType::toggle) - { - Train->ggMainButton.UpdateValue(0.5, Train->dsbSwitch); - } - - if (Train->m_linebreakerstate == linebreaker::state::closed) - { - return; - } // already in the desired state - - // we don't need to start the diesel twice, but the other types (with impulse switch setup) still need to be launched - // NOTE: this behaviour should depend on MainOnButton presence and type_delayed - // TODO: change it when/if vehicle definition files get their proper switch types - if (Train->m_linebreakerstate == linebreaker::state::closing && Train->mvControlled->EngineType == TEngineType::ElectricSeriesMotor) - { - // try to finalize state change of the line breaker, set the state based on the outcome - Train->m_linebreakerstate = Train->mvControlled->MainSwitch(true, Train->mvControlled->MainSwitchRange()) ? linebreaker::state::closed : linebreaker::state::open; - } - // on button release reset the closing timer - Train->fMainRelayTimer = 0.0f; - } -} - -namespace -{ - -// which of the switches of the other vehicles in multiple a command works: 0 the second vehicle's, 1 the third one's -std::size_t remote_linebreaker_index(user_command const Command) -{ - using enum user_command; - return (Command == linebreakertogglec || Command == linebreakeropenc || Command == linebreakerclosec) ? 1 : 0; -} - -// the impulse switches of another vehicle's line breaker spring back when let go, whichever way they were pressed -void release_remote_linebreaker(TTrain::remote_linebreaker &Controls, std::optional &Sound) -{ - if (Controls.on_button.SubModel != nullptr) - { - Controls.on_button.UpdateValue(0.0, Sound); - } - if (Controls.off_button.SubModel != nullptr) - { - Controls.off_button.UpdateValue(0.0, Sound); - } - if (Controls.main_switch.SubModel != nullptr && Controls.main_switch.type() != TGaugeType::toggle) - { - Controls.main_switch.UpdateValue(0.5, Sound); - } - Controls.held_without_switch = false; -} - -} // namespace - -TMoverParameters *TTrain::remote_engine(std::size_t const Index) const -{ - return engine_start::engine(*mvOccupied, *mvControlled, static_cast(Index) + 2); -} - -void TTrain::OnCommand_linebreakertoggleremote(TTrain *Train, command_data const &Command) -{ - auto const index{remote_linebreaker_index(Command.command)}; - auto &controls{Train->m_remotelinebreakers[index]}; - - if (Command.action == GLFW_PRESS) - { - // a two-state switch goes the other way than it stands, an impulse one the other way than the engine is - bool close{false}; - if (controls.main_switch.SubModel != nullptr && controls.main_switch.type() == TGaugeType::toggle) - { - close = controls.main_switch.GetDesiredValue() < 0.5; - } - else - { - auto const *engine{Train->remote_engine(index)}; - close = engine == nullptr || false == engine_start::remote_switch::is_running(*engine); - } - if (close) - { - OnCommand_linebreakercloseremote(Train, Command); - } - else - { - OnCommand_linebreakeropenremote(Train, Command); - } - } - else if (Command.action == GLFW_RELEASE) - { - if (controls.on_button.SubModel != nullptr || controls.main_switch.type() != TGaugeType::toggle) - { - // only impulse switches react to release events - release_remote_linebreaker(controls, Train->dsbSwitch); - } - controls.held_without_switch = false; - } -} - -void TTrain::OnCommand_linebreakeropenremote(TTrain *Train, command_data const &Command) -{ - auto const index{remote_linebreaker_index(Command.command)}; - auto &controls{Train->m_remotelinebreakers[index]}; - - if (Command.action == GLFW_PRESS) - { - // visual feedback - if (controls.off_button.SubModel != nullptr) - { - controls.off_button.UpdateValue(1.0, Train->dsbSwitch); - } - else if (controls.main_switch.SubModel != nullptr) - { - controls.main_switch.UpdateValue(0.0, Train->dsbSwitch); - } - controls.held_without_switch = false; - if (auto *engine{Train->remote_engine(index)}; engine != nullptr) - { - engine_start::remote_switch::open(*engine); - } - } - else if (Command.action == GLFW_RELEASE) - { - release_remote_linebreaker(controls, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_linebreakercloseremote(TTrain *Train, command_data const &Command) -{ - auto const index{remote_linebreaker_index(Command.command)}; - auto &controls{Train->m_remotelinebreakers[index]}; - - if (Command.action == GLFW_PRESS) - { - // visual feedback; the line breaker closes in the train update, once the switch was held long enough - if (controls.on_button.SubModel != nullptr) - { - controls.on_button.UpdateValue(1.0, Train->dsbSwitch); - } - else if (controls.main_switch.SubModel != nullptr) - { - controls.main_switch.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // no switch in the cab, the command alone holds it - controls.held_without_switch = true; - } - } - else if (Command.action == GLFW_RELEASE) - { - release_remote_linebreaker(controls, Train->dsbSwitch); - } -} - -void TTrain::update_remote_linebreakers(double const Deltatime) -{ - for (std::size_t index = 0; index < m_remotelinebreakers.size(); ++index) - { - auto &controls{m_remotelinebreakers[index]}; - auto *engine{remote_engine(index)}; - auto const closeheld{controls.held_without_switch || (controls.main_switch.SubModel != nullptr && controls.main_switch.GetDesiredValue() > 0.95) || - (controls.on_button.SubModel != nullptr && controls.on_button.GetDesiredValue() > 0.95)}; - auto const openheld{controls.off_button.SubModel != nullptr && controls.off_button.GetDesiredValue() > 0.95}; - // as with the cab's own switch, an electric locomotive's impulse switch closes the line breaker when let go - auto const closesonrelease{engine != nullptr && controls.on_button.SubModel != nullptr && engine->EngineType == TEngineType::ElectricSeriesMotor}; - controls.state.update(engine, closeheld, openheld, Deltatime, closesonrelease); - } -} - -void TTrain::OnCommand_fuelpumptoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggFuelPumpButton.type() == TGaugeType::push) - { - // impulse switch - // currently there's no off button so we always try to turn it on - OnCommand_fuelpumpenable(Train, Command); - } - else - { - // two-state switch - if (Command.action == GLFW_RELEASE) - { - return; - } - - if (false == Train->mvControlled->FuelPump.is_enabled) - { - // turn on - OnCommand_fuelpumpenable(Train, Command); - } - else - { - // turn off - OnCommand_fuelpumpdisable(Train, Command); - } - } -} - -void TTrain::OnCommand_fuelpumpenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggFuelPumpButton.type() == TGaugeType::push) - { - // impulse switch - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggFuelPumpButton.UpdateValue(1.0, Train->dsbSwitch); - Train->mvControlled->FuelPumpSwitch(true); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggFuelPumpButton.UpdateValue(0.0, Train->dsbSwitch); - Train->mvControlled->FuelPumpSwitch(false); - } - } - else - { - // two-state switch, only cares about press events - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggFuelPumpButton.UpdateValue(1.0, Train->dsbSwitch); - Train->mvControlled->FuelPumpSwitch(true); - Train->mvControlled->FuelPumpSwitchOff(false); - } - } -} - -void TTrain::OnCommand_fuelpumpdisable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggFuelPumpButton.type() == TGaugeType::push) - { - // impulse switch - // currently there's no disable return type switch - return; - } - else - { - // two-state switch, only cares about press events - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggFuelPumpButton.UpdateValue(0.0, Train->dsbSwitch); - Train->mvControlled->FuelPumpSwitch(false); - Train->mvControlled->FuelPumpSwitchOff(true); - } - } -} - -void TTrain::OnCommand_oilpumptoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggOilPumpButton.type() == TGaugeType::push) - { - // impulse switch - // currently there's no off button so we always try to turn it on - OnCommand_oilpumpenable(Train, Command); - } - else - { - // two-state switch - if (Command.action == GLFW_RELEASE) - { - return; - } - - if (false == Train->mvControlled->OilPump.is_enabled) - { - // turn on - OnCommand_oilpumpenable(Train, Command); - } - else - { - // turn off - OnCommand_oilpumpdisable(Train, Command); - } - } -} - -void TTrain::OnCommand_oilpumpenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggOilPumpButton.type() == TGaugeType::push) - { - // impulse switch - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggOilPumpButton.UpdateValue(1.0, Train->dsbSwitch); - Train->mvControlled->OilPumpSwitch(true); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggOilPumpButton.UpdateValue(0.0, Train->dsbSwitch); - Train->mvControlled->OilPumpSwitch(false); - } - } - else - { - // two-state switch, only cares about press events - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggOilPumpButton.UpdateValue(1.0, Train->dsbSwitch); - Train->mvControlled->OilPumpSwitch(true); - Train->mvControlled->OilPumpSwitchOff(false); - } - } -} - -void TTrain::OnCommand_oilpumpdisable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggOilPumpButton.type() == TGaugeType::push) - { - // impulse switch - // currently there's no disable return type switch - return; - } - else - { - // two-state switch, only cares about press events - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggOilPumpButton.UpdateValue(0.0, Train->dsbSwitch); - Train->mvControlled->OilPumpSwitch(false); - Train->mvControlled->OilPumpSwitchOff(true); - } - } -} - -void TTrain::OnCommand_oilfuelpumptoggle(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_REPEAT) - { - return; - } - - auto *vehicle{Train->mvControlled}; - if (Train->ggOilFuelPumpButton.type() == TGaugeType::push) - { - // impulse switch, as the separate ones: held to start both pumps - auto const pressed{Command.action == GLFW_PRESS}; - Train->ggOilFuelPumpButton.UpdateValue(pressed ? 1.0 : 0.0, Train->dsbSwitch); - vehicle->FuelPumpSwitch(pressed); - vehicle->OilPumpSwitch(pressed); - return; - } - // two-state switch, only cares about press events - if (Command.action != GLFW_PRESS) - { - return; - } - // both pumps go off if both were on, otherwise both go on; a pump started automatically doesn't take part - auto const enable{false == vehicle->OilFuelPumpsEnabled()}; - Train->ggOilFuelPumpButton.UpdateValue(enable ? 1.0 : 0.0, Train->dsbSwitch); - vehicle->FuelPumpSwitch(enable); - vehicle->FuelPumpSwitchOff(false == enable); - vehicle->OilPumpSwitch(enable); - vehicle->OilPumpSwitchOff(false == enable); -} - -// the traction selector of a dual-mode vehicle (eu07/maszyna#536), a two-state switch -void TTrain::OnCommand_tractionmodetoggle(TTrain *Train, command_data const &Command) -{ - if (Command.action != GLFW_PRESS) - { - return; - } - if (Train->mvControlled->GensetSelected()) - { - OnCommand_tractionmodecatenary(Train, Command); - } - else - { - OnCommand_tractionmodegenset(Train, Command); - } -} - -void TTrain::OnCommand_tractionmodecatenary(TTrain *Train, command_data const &Command) -{ - if (Command.action != GLFW_PRESS) - { - return; - } - // refused with the line breaker closed: then the switch doesn't move - Train->mvControlled->TractionModeSwitch(TMoverParameters::traction_mode::catenary, range_t::consist); - if (false == Train->mvControlled->GensetSelected()) - { - Train->ggTractionModeSwitch.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_tractionmodegenset(TTrain *Train, command_data const &Command) -{ - if (Command.action != GLFW_PRESS) - { - return; - } - // refused with the line breaker closed, or without a genset: then the switch doesn't move - Train->mvControlled->TractionModeSwitch(TMoverParameters::traction_mode::genset, range_t::consist); - if (Train->mvControlled->GensetSelected()) - { - Train->ggTractionModeSwitch.UpdateValue(1.0, Train->dsbSwitch); - } -} - -// the start request of the genset of a dual-mode vehicle, a two-state switch -void TTrain::OnCommand_gensettoggle(TTrain *Train, command_data const &Command) -{ - if (Command.action != GLFW_PRESS) - { - return; - } - if (false == Train->mvControlled->Genset.is_enabled) - { - OnCommand_gensetenable(Train, Command); - } - else - { - OnCommand_gensetdisable(Train, Command); - } -} - -void TTrain::OnCommand_gensetenable(TTrain *Train, command_data const &Command) -{ - if (Command.action != GLFW_PRESS) - { - return; - } - // ignored by a genset which starts on its own: then the switch doesn't move - Train->mvControlled->GensetSwitch(true, range_t::consist); - if (Train->mvControlled->Genset.is_enabled) - { - Train->ggGensetButton.UpdateValue(1.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_gensetdisable(TTrain *Train, command_data const &Command) -{ - if (Command.action != GLFW_PRESS) - { - return; - } - Train->mvControlled->GensetSwitch(false, range_t::consist); - if (false == Train->mvControlled->Genset.is_enabled) - { - Train->ggGensetButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_waterheaterbreakertoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvControlled->WaterHeater.breaker) - { - // turn on - OnCommand_waterheaterbreakerclose(Train, Command); - } - else - { - // turn off - OnCommand_waterheaterbreakeropen(Train, Command); - } - } -} - -void TTrain::OnCommand_waterheaterbreakerclose(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggWaterHeaterBreakerButton.UpdateValue(1.0, Train->dsbSwitch); - - if (true == Train->mvControlled->WaterHeater.breaker) - { - return; - } // already enabled - - Train->mvControlled->WaterHeaterBreakerSwitch(true); - } -} - -void TTrain::OnCommand_waterheaterbreakeropen(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggWaterHeaterBreakerButton.UpdateValue(0.0, Train->dsbSwitch); - - if (false == Train->mvControlled->WaterHeater.breaker) - { - return; - } // already enabled - - Train->mvControlled->WaterHeaterBreakerSwitch(false); - } -} - -void TTrain::OnCommand_waterheatertoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvControlled->WaterHeater.is_enabled) - { - // turn on - OnCommand_waterheaterenable(Train, Command); - } - else - { - // turn off - OnCommand_waterheaterdisable(Train, Command); - } - } -} - -void TTrain::OnCommand_waterheaterenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggWaterHeaterButton.UpdateValue(1.0, Train->dsbSwitch); - - if (true == Train->mvControlled->WaterHeater.is_enabled) - { - return; - } // already enabled - - Train->mvControlled->WaterHeaterSwitch(true); - } -} - -void TTrain::OnCommand_waterheaterdisable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggWaterHeaterButton.UpdateValue(0.0, Train->dsbSwitch); - - if (false == Train->mvControlled->WaterHeater.is_enabled) - { - return; - } // already disabled - - Train->mvControlled->WaterHeaterSwitch(false); - } -} - -void TTrain::OnCommand_waterpumpbreakertoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvControlled->WaterPump.breaker) - { - // turn on - OnCommand_waterpumpbreakerclose(Train, Command); - } - else - { - // turn off - OnCommand_waterpumpbreakeropen(Train, Command); - } - } -} - -void TTrain::OnCommand_waterpumpbreakerclose(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggWaterPumpBreakerButton.UpdateValue(1.0, Train->dsbSwitch); - - if (true == Train->mvControlled->WaterPump.breaker) - { - return; - } // already enabled - - Train->mvControlled->WaterPumpBreakerSwitch(true); - } -} - -void TTrain::OnCommand_waterpumpbreakeropen(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggWaterPumpBreakerButton.UpdateValue(0.0, Train->dsbSwitch); - - if (false == Train->mvControlled->WaterPump.breaker) - { - return; - } // already enabled - - Train->mvControlled->WaterPumpBreakerSwitch(false); - } -} - -void TTrain::OnCommand_waterpumptoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggWaterPumpButton.type() == TGaugeType::push) - { - // impulse switch - // currently there's no off button so we always try to turn it on - OnCommand_waterpumpenable(Train, Command); - } - else - { - // two-state switch - if (Command.action == GLFW_RELEASE) - { - return; - } - - if (false == Train->mvControlled->WaterPump.is_enabled) - { - // turn on - OnCommand_waterpumpenable(Train, Command); - } - else - { - // turn off - OnCommand_waterpumpdisable(Train, Command); - } - } -} - -void TTrain::OnCommand_waterpumpenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggWaterPumpButton.type() == TGaugeType::push) - { - // impulse switch - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggWaterPumpButton.UpdateValue(1.0, Train->dsbSwitch); - Train->mvControlled->WaterPumpSwitch(true); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggWaterPumpButton.UpdateValue(0.0, Train->dsbSwitch); - Train->mvControlled->WaterPumpSwitch(false); - } - } - else - { - // two-state switch, only cares about press events - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggWaterPumpButton.UpdateValue(1.0, Train->dsbSwitch); - Train->mvControlled->WaterPumpSwitch(true); - Train->mvControlled->WaterPumpSwitchOff(false); - } - } -} - -void TTrain::OnCommand_waterpumpdisable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggWaterPumpButton.type() == TGaugeType::push) - { - // impulse switch - // currently there's no disable return type switch - return; - } - else - { - // two-state switch, only cares about press events - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggWaterPumpButton.UpdateValue(0.0, Train->dsbSwitch); - Train->mvControlled->WaterPumpSwitch(false); - Train->mvControlled->WaterPumpSwitchOff(true); - } - } -} - -void TTrain::OnCommand_watercircuitslinktoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvControlled->WaterCircuitsLink) - { - // turn on - OnCommand_watercircuitslinkenable(Train, Command); - } - else - { - // turn off - OnCommand_watercircuitslinkdisable(Train, Command); - } - } -} - -void TTrain::OnCommand_watercircuitslinkenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggWaterCircuitsLinkButton.UpdateValue(1.0, Train->dsbSwitch); - - if (true == Train->mvControlled->WaterCircuitsLink) - { - return; - } // already enabled - - Train->mvControlled->WaterCircuitsLinkSwitch(true); - } -} - -void TTrain::OnCommand_watercircuitslinkdisable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggWaterCircuitsLinkButton.UpdateValue(0.0, Train->dsbSwitch); - - if (false == Train->mvControlled->WaterCircuitsLink) - { - return; - } // already disabled - - Train->mvControlled->WaterCircuitsLinkSwitch(false); - } -} - -void TTrain::OnCommand_convertertoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const overloadrelayisopen{(Train->Dynamic()->Mechanik != nullptr ? Train->Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : Train->mvOccupied->ConvOvldFlag)}; - - if (Train->mvOccupied->ConvSwitchType != "impulse" ? Train->ggConverterButton.GetValue() < 0.5 : false == Train->mvOccupied->Power110vIsAvailable && false == overloadrelayisopen) - { - // turn on - OnCommand_converterenable(Train, Command); - } - else - { - // turn off - OnCommand_converterdisable(Train, Command); - } - } - else if (Command.action == GLFW_RELEASE) - { - // on button release... - if (Train->mvOccupied->ConvSwitchType == "impulse") - { - // ...return switches to start position if applicable - Train->ggConverterButton.UpdateValue(0.0, Train->dsbSwitch); - Train->ggConverterOffButton.UpdateValue(0.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_converterenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggConverterButton.UpdateValue(1.0, Train->dsbSwitch); - - // impulse type switch has no effect if there's no power - // NOTE: this is most likely setup wrong, but the whole thing is smoke and mirrors anyway - if (Train->mvOccupied->ConvSwitchType != "impulse" || Train->mvControlled->Mains) - { - // won't start if the line breaker button is still held - Train->mvOccupied->ConverterSwitch(true); - } - } - else if (Command.action == GLFW_RELEASE) - { - // potentially reset impulse switch position, using shared code branch - OnCommand_convertertoggle(Train, Command); - } -} - -void TTrain::OnCommand_converterdisable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggConverterButton.UpdateValue(0.0, Train->dsbSwitch); - if (Train->ggConverterOffButton.SubModel != nullptr) - { - Train->ggConverterOffButton.UpdateValue(1.0, Train->dsbSwitch); - } - - Train->mvOccupied->ConverterSwitch(false); - } - else if (Command.action == GLFW_RELEASE) - { - // potentially reset impulse switch position, using shared code branch - OnCommand_convertertoggle(Train, Command); - } -} - -void TTrain::OnCommand_convertertogglelocal(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->ConverterStart == start_t::automatic) - { - // let the automatic thing do its automatic thing... - return; - } - if (Train->ggConverterLocalButton.SubModel == nullptr) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvOccupied->ConverterAllowLocal && Train->ggConverterLocalButton.GetValue() < 0.5) - { - // turn on - // visual feedback - Train->ggConverterLocalButton.UpdateValue(1.0, Train->dsbSwitch); - // effect - Train->mvOccupied->ConverterAllowLocal = true; - /* - if( true == Train->mvControlled->ConverterSwitch( true, range::local ) ) { - // side effects - // control the compressor, if it's paired with the converter - if( Train->mvControlled->CompressorPower == 2 ) { - // hunter-091012: tak jest poprawnie - Train->mvControlled->CompressorSwitch( true, range::local ); - } - } - */ - } - else - { - // turn off - // visual feedback - Train->ggConverterLocalButton.UpdateValue(0.0, Train->dsbSwitch); - // effect - Train->mvOccupied->ConverterAllowLocal = false; - /* - if( true == Train->mvControlled->ConverterSwitch( false, range::local ) ) { - // side effects - // control the compressor, if it's paired with the converter - if( Train->mvControlled->CompressorPower == 2 ) { - // hunter-091012: tak jest poprawnie - Train->mvControlled->CompressorSwitch( false, range::local ); - } - // if there's no (low voltage) power source left, drop pantographs - if( false == Train->mvControlled->Battery ) { - Train->mvControlled->PantFront( false, range::local ); - Train->mvControlled->PantRear( false, range::local ); - } - } - */ - } - } -} - -void TTrain::OnCommand_converteroverloadrelayreset(TTrain *Train, command_data const &Command) -{ - - if (Train->ggConverterFuseButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Converter Overload Relay Reset button is missing, or wasn't defined"); - } - // return; - } - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggConverterFuseButton.UpdateValue(1.0, Train->dsbSwitch); - - Train->mvControlled->RelayReset(relay_t::primaryconverteroverload); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggConverterFuseButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_compressortoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const compressorisenabled{(Train->Dynamic()->Mechanik ? Train->Dynamic()->Mechanik->IsAnyCompressorEnabled : Train->mvOccupied->CompressorAllow)}; - - if (false == compressorisenabled) - { - // turn on - OnCommand_compressorenable(Train, Command); - } - else - { - // turn off - OnCommand_compressordisable(Train, Command); - } - } - /* - // disabled because we don't have yet support for compressor switch type definition - else if( Command.action == GLFW_RELEASE ) { - // on button release... - if( Train->mvOccupied->CompSwitchType == "impulse" ) { - // ...return switches to start position if applicable - Train->ggCompressorButton.UpdateValue( 0.0, Train->dsbSwitch ); - Train->ggCompressorOffButton.UpdateValue( 0.0, Train->dsbSwitch ); - } - } - */ -} - -void TTrain::OnCommand_compressorenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggCompressorButton.UpdateValue(1.0, Train->dsbSwitch); - - // impulse type switch has no effect if there's no power - // NOTE: this is most likely setup wrong, but the whole thing is smoke and mirrors anyway - // if( ( Train->mvOccupied->CompSwitchType != "impulse" ) - // || ( Train->mvControlled->Mains ) ) { - - Train->mvOccupied->CompressorSwitch(true); - // } - } - else if (Command.action == GLFW_RELEASE) - { - // potentially reset impulse switch position, using shared code branch - OnCommand_compressortoggle(Train, Command); - } -} - -void TTrain::OnCommand_compressordisable(TTrain *Train, command_data const &Command) -{ - - if (Train->mvControlled->CompressorPower >= 2) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggCompressorButton.UpdateValue(0.0, Train->dsbSwitch); - /* - if( Train->ggCompressorOffButton.SubModel != nullptr ) { - Train->ggCompressorOffButton.UpdateValue( 1.0, Train->dsbSwitch ); - } - */ - Train->mvOccupied->CompressorSwitch(false); - } - else if (Command.action == GLFW_RELEASE) - { - // potentially reset impulse switch position, using shared code branch - OnCommand_compressortoggle(Train, Command); - } -} - -void TTrain::OnCommand_compressortogglelocal(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->CompressorPower >= 2) - { - return; - } - if (Train->ggCompressorLocalButton.SubModel == nullptr) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvOccupied->CompressorAllowLocal) - { - // turn on - // visual feedback - Train->ggCompressorLocalButton.UpdateValue(1.0, Train->dsbSwitch); - // effect - Train->mvOccupied->CompressorAllowLocal = true; - } - else - { - // turn off - // visual feedback - Train->ggCompressorLocalButton.UpdateValue(0.0, Train->dsbSwitch); - // effect - Train->mvOccupied->CompressorAllowLocal = false; - } - } -} - -void TTrain::OnCommand_compressorpresetactivatenext(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->CompressorListPosNo == 0) - { - return; - } - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggCompressorListButton.type() == TGaugeType::push) - { - // impulse switch - if (Train->mvOccupied->CompressorListPosNo < Train->mvOccupied->CompressorListDefPos + 1) - { - return; - } - - Train->mvOccupied->ChangeCompressorPreset(Command.action == GLFW_PRESS ? Train->mvOccupied->CompressorListDefPos + 1 : Train->mvOccupied->CompressorListDefPos); - // visual feedback - Train->ggCompressorListButton.UpdateValue(static_cast(Train->mvOccupied->CompressorListPos - 1), Train->dsbSwitch); - } - else - { - // multi-state switch - if (Command.action == GLFW_RELEASE) - { - return; - } - - if (Train->mvOccupied->CompressorListPos < Train->mvOccupied->CompressorListPosNo || true == Train->mvOccupied->CompressorListWrap) - { - // active light preset is stored as value in range 1-LigthPosNo - Train->mvOccupied->ChangeCompressorPreset(Train->mvOccupied->CompressorListPos < Train->mvOccupied->CompressorListPosNo ? Train->mvOccupied->CompressorListPos + 1 : 1); // wrap mode - // visual feedback - Train->ggCompressorListButton.UpdateValue(static_cast(Train->mvOccupied->CompressorListPos - 1), Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_compressorpresetactivateprevious(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->CompressorListPosNo == 0) - { - return; - } - if (Command.action != GLFW_PRESS) - { - return; - } // one change per key press - - if (Train->ggCompressorListButton.type() == TGaugeType::push) - { - // impulse switch toggles only between positions 'default' and 'default+1' - return; - } - - if (Train->mvOccupied->CompressorListPos > 1 || true == Train->mvOccupied->CompressorListWrap) - { - // active light preset is stored as value in range 1-LigthPosNo - Train->mvOccupied->ChangeCompressorPreset(Train->mvOccupied->CompressorListPos > 1 ? Train->mvOccupied->CompressorListPos - 1 : Train->mvOccupied->CompressorListPosNo); // wrap mode - - // visual feedback - if (Train->ggCompressorListButton.SubModel != nullptr) - { - Train->ggCompressorListButton.UpdateValue(static_cast(Train->mvOccupied->CompressorListPos - 1), Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_compressorpresetactivatedefault(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->CompressorListPosNo == 0) - { - return; - } - if (Command.action != GLFW_PRESS) - { - return; - } // one change per key press - - Train->mvOccupied->ChangeCompressorPreset(Train->mvOccupied->CompressorListDefPos); - - // visual feedback - if (Train->ggCompressorListButton.SubModel != nullptr) - { - Train->ggCompressorListButton.UpdateValue(static_cast(Train->mvOccupied->CompressorListPos - 1), Train->dsbSwitch); - } -} - -void TTrain::OnCommand_motorblowerstogglefront(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggMotorBlowersFrontButton.type() == TGaugeType::push) - { - // impulse switch - // currently there's no off button so we always try to turn it on - OnCommand_motorblowersenablefront(Train, Command); - } - else - { - // two-state switch - if (Command.action == GLFW_RELEASE) - { - return; - } - - if (false == Train->mvControlled->MotorBlowers[end::front].is_enabled) - { - // turn on - OnCommand_motorblowersenablefront(Train, Command); - } - else - { - // turn off - OnCommand_motorblowersdisablefront(Train, Command); - } - } -} - -void TTrain::OnCommand_motorblowersenablefront(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggMotorBlowersFrontButton.type() == TGaugeType::push) - { - // impulse switch - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggMotorBlowersFrontButton.UpdateValue(1.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(true, end::front); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggMotorBlowersFrontButton.UpdateValue(0.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(false, end::front); - } - } - else - { - // two-state switch, only cares about press events - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggMotorBlowersFrontButton.UpdateValue(1.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(true, end::front); - Train->mvControlled->MotorBlowersSwitchOff(false, end::front); - } - } -} - -void TTrain::OnCommand_motorblowersdisablefront(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggMotorBlowersFrontButton.type() == TGaugeType::push) - { - // impulse switch - // currently there's no disable return type switch - return; - } - else - { - // two-state switch, only cares about press events - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggMotorBlowersFrontButton.UpdateValue(0.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(false, end::front); - Train->mvControlled->MotorBlowersSwitchOff(true, end::front); - } - } -} - -void TTrain::OnCommand_motorblowerstogglerear(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggMotorBlowersRearButton.type() == TGaugeType::push) - { - // impulse switch - // currently there's no off button so we always try to turn it on - OnCommand_motorblowersenablerear(Train, Command); - } - else - { - // two-state switch - if (Command.action == GLFW_RELEASE) - { - return; - } - - if (false == Train->mvControlled->MotorBlowers[end::rear].is_enabled) - { - // turn on - OnCommand_motorblowersenablerear(Train, Command); - } - else - { - // turn off - OnCommand_motorblowersdisablerear(Train, Command); - } - } -} - -void TTrain::OnCommand_motorblowersenablerear(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggMotorBlowersRearButton.type() == TGaugeType::push) - { - // impulse switch - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggMotorBlowersRearButton.UpdateValue(1.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(true, end::rear); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggMotorBlowersRearButton.UpdateValue(0.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(false, end::rear); - } - } - else - { - // two-state switch, only cares about press events - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggMotorBlowersRearButton.UpdateValue(1.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(true, end::rear); - Train->mvControlled->MotorBlowersSwitchOff(false, end::rear); - } - } -} - -void TTrain::OnCommand_motorblowersdisablerear(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggMotorBlowersRearButton.type() == TGaugeType::push) - { - // impulse switch - // currently there's no disable return type switch - return; - } - else - { - // two-state switch, only cares about press events - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggMotorBlowersRearButton.UpdateValue(0.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(false, end::rear); - Train->mvControlled->MotorBlowersSwitchOff(true, end::rear); - } - } -} - -void TTrain::OnCommand_motorblowersdisableall(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggMotorBlowersAllOffButton.type() == TGaugeType::push) - { - // impulse switch - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggMotorBlowersAllOffButton.UpdateValue(1.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitchOff(true, end::front); - Train->mvControlled->MotorBlowersSwitchOff(true, end::rear); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggMotorBlowersAllOffButton.UpdateValue(0.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitchOff(false, end::front); - Train->mvControlled->MotorBlowersSwitchOff(false, end::rear); - } - } - else - { - // two-state switch, only cares about press events - // NOTE: generally this switch doesn't come in two-state form - if (Command.action == GLFW_PRESS) - { - if (Train->ggMotorBlowersAllOffButton.GetDesiredValue() < 0.5f) - { - // switch is off, activate - Train->mvControlled->MotorBlowersSwitchOff(true, end::front); - Train->mvControlled->MotorBlowersSwitchOff(true, end::rear); - // visual feedback - Train->ggMotorBlowersRearButton.UpdateValue(1.f, Train->dsbSwitch); - } - else - { - // deactivate - Train->mvControlled->MotorBlowersSwitchOff(false, end::front); - Train->mvControlled->MotorBlowersSwitchOff(false, end::rear); - // visual feedback - Train->ggMotorBlowersRearButton.UpdateValue(0.f, Train->dsbSwitch); - } - } - } -} - -void TTrain::OnCommand_coolingfanstoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_PRESS) - { - return; - } - - Train->mvControlled->RVentForceOn = !Train->mvControlled->RVentForceOn; -} - -void TTrain::OnCommand_motorconnectorsopen(TTrain *Train, command_data const &Command) -{ - - // TODO: don't rely on presense of 3d model to determine presence of the switch - if (Train->ggStLinOffButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Open Motor Power Connectors button is missing, or wasn't defined"); - } - return; - } - // HACK: because we don't have modeled actual circuits this is a simplification of the real mechanics - // namely, pressing the button will flip it in the entire unit, which isn't exactly physically possible - if (Command.action == GLFW_PRESS) - { - // button works while it's held down but we can ignore repeats - if (false == Train->mvControlled->StLinSwitchOff) - { - // open the connectors - // visual feedback - Train->ggStLinOffButton.UpdateValue(1.0, Train->dsbSwitch); - - Train->mvControlled->StLinSwitchOff = true; - Train->set_paired_open_motor_connectors_button(true); - } - else - { - // potentially close the connectors - OnCommand_motorconnectorsclose(Train, Command); - } - } - else if (Command.action == GLFW_RELEASE) - { - // button released - if (Train->mvControlled->StLinSwitchType != "toggle") - { - // default button type (impulse) ceases its work on button release - // visual feedback - Train->ggStLinOffButton.UpdateValue(0.0, Train->dsbSwitch); - - Train->mvControlled->StLinSwitchOff = false; - Train->set_paired_open_motor_connectors_button(false); - } - } -} - -void TTrain::OnCommand_motorconnectorsclose(TTrain *Train, command_data const &Command) -{ - - // TODO: don't rely on presense of 3d model to determine presence of the switch - if (Train->ggStLinOffButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Open Motor Power Connectors button is missing, or wasn't defined"); - } - return; - } - - if (Command.action == GLFW_PRESS) - { - if (Train->mvControlled->StLinSwitchType == "toggle") - { - // default type of button (impulse) has only one effect on press, but the toggle type can toggle the state - // visual feedback - Train->ggStLinOffButton.UpdateValue(0.0, Train->dsbSwitch); - } - - if (false == Train->mvControlled->StLinSwitchOff) - { - return; - } // already closed - - Train->mvControlled->StLinSwitchOff = false; - Train->set_paired_open_motor_connectors_button(false); - } -} - -void TTrain::OnCommand_motordisconnect(TTrain *Train, command_data const &Command) -{ - - if (Train->mvControlled->TrainType == train_type::emu ? Train->mvControlled != Train->mvOccupied : Train->iCabn != 0) - { - // tylko w maszynowym - return; - } - - if (Command.action == GLFW_PRESS) - { - Train->mvControlled->CutOffEngine(); - } -} - -void TTrain::OnCommand_motoroverloadrelaythresholdtoggle(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (true == Train->mvControlled->ShuntModeAllow ? false == Train->mvControlled->ShuntMode : false == Train->mvControlled->MotorOverloadRelayHighThreshold) - { - // turn on - OnCommand_motoroverloadrelaythresholdsethigh(Train, Command); - } - else - { - // turn off - OnCommand_motoroverloadrelaythresholdsetlow(Train, Command); - } - } -} - -void TTrain::OnCommand_motoroverloadrelaythresholdsetlow(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvControlled->CurrentSwitch(false); - // visual feedback - Train->ggMaxCurrentCtrl.UpdateValue(Train->mvControlled->MotorOverloadRelayHighThreshold ? 1 : 0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_motoroverloadrelaythresholdsethigh(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvControlled->CurrentSwitch(true); - // visual feedback - Train->ggMaxCurrentCtrl.UpdateValue(Train->mvControlled->MotorOverloadRelayHighThreshold ? 1 : 0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_motoroverloadrelayreset(TTrain *Train, command_data const &Command) -{ - - if (Train->ggFuseButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Motor Overload Relay Reset button is missing, or wasn't defined"); - } - // return; - } - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggFuseButton.UpdateValue(1.0, Train->dsbSwitch); - - Train->mvControlled->FuseOn(); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggFuseButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_universalrelayreset(TTrain *Train, command_data const &Command) -{ - - auto const itemindex = static_cast(Command.command) - static_cast(user_command::universalrelayreset1); - auto &item = Train->ggRelayResetButtons[itemindex]; - - // NOTE: relay reset switches are impulse-only - if (Command.action == GLFW_PRESS) - { - Train->mvOccupied->UniversalResetButton(itemindex); - // visual feedback - item.UpdateValue(1.0); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - item.UpdateValue(0.0); - } -} - -// the cab interior light set by the light preset just selected, if the preset sets one (eu07/maszyna#529). -// the cab light switch (cablight_sw:) is bound to the light state and follows it by itself -void TTrain::set_cab_light_from_lights_preset() -{ - auto const cablight{mvOccupied->LightsPresetCabLight(mvOccupied->LightsPos)}; - if (false == cablight.has_value()) - { - return; - } - auto const set{[&cablight](TCab &Cab) { - Cab.bLight = cablight->light; - Cab.bLightDim = cablight->dim; - }}; - if (false == DynamicObject->JointCabs) - { - // vehicles with separate cabs get separate lighting switch states - set(Cabine[iCabn]); - } - else - { - // joint virtual cabs share lighting switch states - for (auto &cab : Cabine) - { - set(cab); - } - } - // the dimmer switch is driven by commands only, move it along - if (ggCabLightDimButton.SubModel != nullptr) - { - ggCabLightDimButton.UpdateValue(cablight->dim ? 1.f : 0.f); - } -} - -void TTrain::OnCommand_lightspresetactivatenext(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo == 0) - { - // no preset selector - return; - } - if (Command.action != GLFW_PRESS) - { - // one change per key press - return; - } - - if (Train->mvOccupied->LightsPos < Train->mvOccupied->LightsPosNo || true == Train->mvOccupied->LightsWrap) - { - // active light preset is stored as value in range 1-LigthPosNo - auto const restartcycle{Train->mvOccupied->LightsPos >= Train->mvOccupied->LightsPosNo}; - Train->mvOccupied->LightsPos = false == restartcycle ? Train->mvOccupied->LightsPos + 1 : 1; // wrap mode - - Train->Dynamic()->SetLights(); - Train->set_cab_light_from_lights_preset(); - // visual feedback - if (Train->ggLightsButton.SubModel != nullptr) - { - if (false == restartcycle) - { - Train->ggLightsButton.UpdateValue(static_cast(Train->mvOccupied->LightsPos - 1), Train->dsbSwitch); - } - else - { - // past the last position to the first one: a knob turning all the way round turns on rather than - // back across all the positions, and the position reached sounds (eu07/maszyna#464) - Train->ggLightsButton.UpdateValueWrapped(static_cast(Train->mvOccupied->LightsPos - 1), true, Train->mvOccupied->LightsPosNo, Train->dsbSwitch); - } - } - } -} - -void TTrain::OnCommand_lightspresetactivateprevious(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo == 0) - { - // no preset selector - return; - } - if (Command.action != GLFW_PRESS) - { - // one change per key press - return; - } - - if (Train->mvOccupied->LightsPos > 1 || true == Train->mvOccupied->LightsWrap) - { - // active light preset is stored as value in range 1-LigthPosNo - auto const restartcycle{Train->mvOccupied->LightsPos <= 1}; - Train->mvOccupied->LightsPos = false == restartcycle ? Train->mvOccupied->LightsPos - 1 : Train->mvOccupied->LightsPosNo; // wrap mode - - Train->Dynamic()->SetLights(); - Train->set_cab_light_from_lights_preset(); - // visual feedback - if (Train->ggLightsButton.SubModel != nullptr) - { - if (false == restartcycle) - { - Train->ggLightsButton.UpdateValue(static_cast(Train->mvOccupied->LightsPos - 1), Train->dsbSwitch); - } - else - { - // back past the first position to the last one, the same way (eu07/maszyna#464) - Train->ggLightsButton.UpdateValueWrapped(static_cast(Train->mvOccupied->LightsPos - 1), false, Train->mvOccupied->LightsPosNo, Train->dsbSwitch); - } - } - } -} - -void TTrain::OnCommand_headlighttoggleleft(TTrain *Train, command_data const &Command) -{ - - auto const vehicleend{Train->cab_to_end()}; - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - - if (Train->ggLeftEndLightButton.SubModel != nullptr || Train->ggLeftLightButton.SubModel == nullptr) - { - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0) - { - // turn on - OnCommand_headlightenableleft(Train, Command); - } - else - { - // turn off - OnCommand_headlightdisableleft(Train, Command); - } - } else { - // if the light is controlled by 3-way switch, handle both headlight and redmarker - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0 && - (Train->mvOccupied->iLights[vehicleend] & light::redmarker_left) == 0) - { - // turn on - OnCommand_headlightenableleft(Train, Command); - } - else if (Train->mvOccupied->iLights[vehicleend] & light::headlight_left) - { - // switch to red - OnCommand_redmarkerenableleft(Train, Command); - } - else - { - // disable - OnCommand_redmarkerdisableleft(Train, Command); - } - } - } -} - -void TTrain::OnCommand_lightsset(TTrain *Train, command_data const &Command) -{ - // set custom item in Lights inventory - Train->mvOccupied->Lights[end::front][17] = static_cast(Command.param1); - Train->mvOccupied->Lights[end::rear][17] = static_cast(Command.param2); - Train->mvOccupied->LightsPos = 18; // nasza custom pozycja - Train->Dynamic()->SetLights(); -} - -void TTrain::OnCommand_headlightenableleft(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggLeftLightButton.UpdateValue(1.0, Train->dsbSwitch); - // implementation - auto const vehicleend{Train->cab_to_end()}; - - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0) - { - Train->mvOccupied->iLights[vehicleend] ^= light::headlight_left; - } - // if the light is controlled by 3-way switch, disable marker light - if (Train->ggLeftEndLightButton.SubModel == nullptr) - { - Train->mvOccupied->iLights[vehicleend] &= ~light::redmarker_left; - } - } -} - -void TTrain::OnCommand_headlightdisableleft(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - int const vehicleend{Train->cab_to_end()}; - - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0) - { - return; - } // already disabled - - Train->mvOccupied->iLights[vehicleend] ^= light::headlight_left; - // visual feedback - Train->ggLeftLightButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_headlighttoggleright(TTrain *Train, command_data const &Command) -{ - - auto const vehicleend{Train->cab_to_end()}; - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - - if (Train->ggRightEndLightButton.SubModel != nullptr || Train->ggRightLightButton.SubModel == nullptr) - { - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_right) == 0) - { - // turn on - OnCommand_headlightenableright(Train, Command); - } - else - { - // turn off - OnCommand_headlightdisableright(Train, Command); - } - } else { - // if the light is controlled by 3-way switch, handle both headlight and redmarker - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_right) == 0 && - (Train->mvOccupied->iLights[vehicleend] & light::redmarker_right) == 0) - { - // turn on - OnCommand_headlightenableright(Train, Command); - } - else if (Train->mvOccupied->iLights[vehicleend] & light::headlight_right) - { - // switch to red - OnCommand_redmarkerenableright(Train, Command); - } - else - { - // disable - OnCommand_redmarkerdisableright(Train, Command); - } - } - } -} - -void TTrain::OnCommand_headlightenableright(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggRightLightButton.UpdateValue(1.0, Train->dsbSwitch); - // implementation - auto const vehicleend{Train->cab_to_end()}; - - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_right) == 0) - { - Train->mvOccupied->iLights[vehicleend] ^= light::headlight_right; - } - // if the light is controlled by 3-way switch, disable marker light - if (Train->ggRightEndLightButton.SubModel == nullptr) - { - Train->mvOccupied->iLights[vehicleend] &= ~light::redmarker_right; - } - } -} - -void TTrain::OnCommand_headlightdisableright(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleend{Train->cab_to_end()}; - - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_right) == 0) - { - return; - } // already disabled - - Train->mvOccupied->iLights[vehicleend] ^= light::headlight_right; - // visual feedback - Train->ggRightLightButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_headlighttoggleupper(TTrain *Train, command_data const &Command) -{ - - auto const vehicleend{Train->cab_to_end()}; - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_upper) == 0) - { - // turn on - OnCommand_headlightenableupper(Train, Command); - } - else - { - // turn off - OnCommand_headlightdisableupper(Train, Command); - } - } -} - -void TTrain::OnCommand_headlightenableupper(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleend{Train->cab_to_end()}; - - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_upper) != 0) - { - return; - } // already enabled - - Train->mvOccupied->iLights[vehicleend] ^= light::headlight_upper; - // visual feedback - Train->ggUpperLightButton.UpdateValue(1.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_headlightdisableupper(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleend{Train->cab_to_end()}; - - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_upper) == 0) - { - return; - } // already disabled - - Train->mvOccupied->iLights[vehicleend] ^= light::headlight_upper; - // visual feedback - Train->ggUpperLightButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_redmarkertoggleleft(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleend{Train->cab_to_end()}; - - if ((Train->mvOccupied->iLights[vehicleend] & light::redmarker_left) == 0) - { - // turn on - OnCommand_redmarkerenableleft(Train, Command); - } - else - { - // turn off - OnCommand_redmarkerdisableleft(Train, Command); - } - } -} - -void TTrain::OnCommand_redmarkerenableleft(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleend{Train->cab_to_end()}; - - if ((Train->mvOccupied->iLights[vehicleend] & light::redmarker_left) != 0) - { - return; - } // already enabled - - Train->mvOccupied->iLights[vehicleend] ^= light::redmarker_left; - // visual feedback - if (Train->ggLeftEndLightButton.SubModel != nullptr) - { - Train->ggLeftEndLightButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // we interpret lack of dedicated switch as a sign the light is controlled with 3-way switch - // this is crude, but for now will do - Train->ggLeftLightButton.UpdateValue(-1.0, Train->dsbSwitch); - // if the light is controlled by 3-way switch, disable the headlight - Train->mvOccupied->iLights[vehicleend] &= ~light::headlight_left; - } - } -} - -void TTrain::OnCommand_redmarkerdisableleft(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleend{Train->cab_to_end()}; - - if ((Train->mvOccupied->iLights[vehicleend] & light::redmarker_left) == 0) - { - return; - } // already disabled - - Train->mvOccupied->iLights[vehicleend] ^= light::redmarker_left; - // visual feedback - if (Train->ggLeftEndLightButton.SubModel != nullptr) - { - Train->ggLeftEndLightButton.UpdateValue(0.0, Train->dsbSwitch); - } - else - { - // we interpret lack of dedicated switch as a sign the light is controlled with 3-way switch - // this is crude, but for now will do - Train->ggLeftLightButton.UpdateValue(0.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_redmarkertoggleright(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleend{Train->cab_to_end()}; - - if ((Train->mvOccupied->iLights[vehicleend] & light::redmarker_right) == 0) - { - // turn on - OnCommand_redmarkerenableright(Train, Command); - } - else - { - // turn off - OnCommand_redmarkerdisableright(Train, Command); - } - } -} - -void TTrain::OnCommand_redmarkerenableright(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleend{Train->cab_to_end()}; - - if ((Train->mvOccupied->iLights[vehicleend] & light::redmarker_right) != 0) - { - return; - } // already enabled - - Train->mvOccupied->iLights[vehicleend] ^= light::redmarker_right; - // visual feedback - if (Train->ggRightEndLightButton.SubModel != nullptr) - { - Train->ggRightEndLightButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // we interpret lack of dedicated switch as a sign the light is controlled with 3-way switch - // this is crude, but for now will do - Train->ggRightLightButton.UpdateValue(-1.0, Train->dsbSwitch); - // if the light is controlled by 3-way switch, disable the headlight - Train->mvOccupied->iLights[vehicleend] &= ~light::headlight_right; - } - } -} - -void TTrain::OnCommand_redmarkerdisableright(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleend{Train->cab_to_end()}; - - if ((Train->mvOccupied->iLights[vehicleend] & light::redmarker_right) == 0) - { - return; - } // already disabled - - Train->mvOccupied->iLights[vehicleend] ^= light::redmarker_right; - // visual feedback - if (Train->ggRightEndLightButton.SubModel != nullptr) - { - Train->ggRightEndLightButton.UpdateValue(0.0, Train->dsbSwitch); - } - else - { - // we interpret lack of dedicated switch as a sign the light is controlled with 3-way switch - // this is crude, but for now will do - Train->ggRightLightButton.UpdateValue(0.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_headlighttogglerearleft(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_right) == 0) - { - OnCommand_headlightenablerearleft(Train, Command); - } - else - { - OnCommand_headlightdisablerearleft(Train, Command); - } - } -} - -void TTrain::OnCommand_headlightenablerearleft(TTrain *Train, command_data const &Command) -{ - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - // already enabled - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_right) == 0) - { - // turn on - Train->mvOccupied->iLights[vehicleotherend] ^= light::headlight_right; - // visual feedback - Train->ggRearLeftLightButton.UpdateValue(1.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_headlightdisablerearleft(TTrain *Train, command_data const &Command) -{ - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - if (Command.action == GLFW_PRESS) - { - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - // already disabled - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_right) == 0) - { - return; - } - - // turn off - Train->mvOccupied->iLights[vehicleotherend] ^= light::headlight_right; - // visual feedback - Train->ggRearLeftLightButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_headlighttogglerearright(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_left) == 0) - { - OnCommand_headlightenablerearright(Train, Command); - } - else - { - OnCommand_headlightdisablerearright(Train, Command); - } - } -} - -void TTrain::OnCommand_headlightenablerearright(TTrain *Train, command_data const &Command) -{ - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_left) == 0) - { - // turn on - Train->mvOccupied->iLights[vehicleotherend] ^= light::headlight_left; - // visual feedback - Train->ggRearRightLightButton.UpdateValue(1.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_headlightdisablerearright(TTrain *Train, command_data const &Command) -{ - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - // already disabled - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_left) == 0) - { - return; - } - - // turn off - Train->mvOccupied->iLights[vehicleotherend] ^= light::headlight_left; - // visual feedback - Train->ggRearRightLightButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_headlighttogglerearupper(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_upper) == 0) - { - OnCommand_headlightenablerearupper(Train, Command); - } - else - { - OnCommand_headlightdisablerearupper(Train, Command); - } - } -} - -void TTrain::OnCommand_headlightenablerearupper(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_upper) == 0) - { - // turn on - Train->mvOccupied->iLights[vehicleotherend] ^= light::headlight_upper; - // visual feedback - Train->ggRearUpperLightButton.UpdateValue(1.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_headlightdisablerearupper(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - // already disabled? - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_upper) == 0) - { - return; - } - - // turn off - Train->mvOccupied->iLights[vehicleotherend] ^= light::headlight_upper; - // visual feedback - Train->ggRearUpperLightButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_modernlightdimmerincrease(TTrain *Train, command_data const &Command) -{ - if (!Train->mvOccupied->enableModernDimmer) - return; // if modern dimmer is disabled, skip entire command - if (Command.action == GLFW_PRESS) - { - // update modern dimmer state - if (false == Train->mvOccupied->stepDimmerPosition(1)) - return; // już na maksimum i nie można cyklicznie - auto const dimPos = Train->mvOccupied->modernDimmerPosition; - // update lightning - // Train->Dynamic()->SetLights(); - Train->Dynamic()->SetLightDimmings(); - - // visual feedback - if (Train->ggModernLightDimSw.SubModel != nullptr) - Train->ggModernLightDimSw.UpdateValue(static_cast(dimPos), Train->dsbSwitch); - } -} -void TTrain::OnCommand_modernlightdimmerdecrease(TTrain *Train, command_data const &Command) -{ - if (!Train->mvOccupied->enableModernDimmer) - return; // jeśli dimmer jest wyłączony, olewamy - - if (Command.action == GLFW_PRESS) - { - if (false == Train->mvOccupied->stepDimmerPosition(-1)) - return; // już na minimum i nie można cyklicznie - auto const dimPos = Train->mvOccupied->modernDimmerPosition; - - // Train->Dynamic()->SetLights(); - Train->Dynamic()->SetLightDimmings(); - - if (Train->ggModernLightDimSw.SubModel != nullptr) - Train->ggModernLightDimSw.UpdateValue(static_cast(dimPos), Train->dsbSwitch); - } -} - -void TTrain::OnCommand_redmarkertogglerearleft(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_right) == 0) - { - OnCommand_redmarkerenablerearleft(Train, Command); - } - else - { - OnCommand_redmarkerdisablerearleft(Train, Command); - } - } -} - -void TTrain::OnCommand_redmarkerenablerearleft(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_right) == 0) - { - // turn on - Train->mvOccupied->iLights[vehicleotherend] ^= light::redmarker_right; - // visual feedback - Train->ggRearLeftEndLightButton.UpdateValue(1.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_redmarkerdisablerearleft(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_right) == 0) - { - return; - } - // turn off - Train->mvOccupied->iLights[vehicleotherend] ^= light::redmarker_right; - // visual feedback - Train->ggRearLeftEndLightButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_redmarkertogglerearright(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_left) == 0) - { - OnCommand_redmarkerenablerearright(Train, Command); - } - else - { - OnCommand_redmarkerdisablerearright(Train, Command); - } - } -} - -void TTrain::OnCommand_redmarkerenablerearright(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_left) == 0) - { - // turn on - Train->mvOccupied->iLights[vehicleotherend] ^= light::redmarker_left; - // visual feedback - Train->ggRearRightEndLightButton.UpdateValue(1.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_redmarkerdisablerearright(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_left) == 0) - { - return; - } - // turn off - Train->mvOccupied->iLights[vehicleotherend] ^= light::redmarker_left; - // visual feedback - Train->ggRearRightEndLightButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_redmarkerstoggle(TTrain * /*Train*/, command_data const &Command) -{ - - if (true == Command.freefly && Command.action == GLFW_PRESS) - { - - auto *vehicle{std::get(simulation::Region->find_vehicle(Command.location, 10, false, true))}; - - if (vehicle == nullptr) - { - return; - } - - auto locationHead = vehicle->HeadPosition() - glm::dvec3(Command.location); // TODO: Maybe command_data should be dvec3? - auto locationRear = vehicle->RearPosition() - glm::dvec3(Command.location); - int const CouplNr{std::clamp(vehicle->DirectionGet() * (glm::dot(locationHead, locationHead) > glm::dot(locationRear, locationRear) ? 1 : -1), 0, 1)}; // z [-1,1] zrobić [0,1] - - auto const lightset{light::redmarker_left | light::redmarker_right}; - - vehicle->MoverParameters->iLights[CouplNr] = - false == TestFlag(vehicle->MoverParameters->iLights[CouplNr], lightset) ? - vehicle->MoverParameters->iLights[CouplNr] |= lightset : // turn signals on - vehicle->MoverParameters->iLights[CouplNr] ^= lightset; // turn signals off - } -} - -void TTrain::OnCommand_endsignalstoggle(TTrain * /*Train*/, command_data const &Command) -{ - - if (true == Command.freefly && Command.action == GLFW_PRESS) - { - - auto *vehicle{std::get(simulation::Region->find_vehicle(Command.location, 10, false, true))}; - - if (vehicle == nullptr) - { - return; - } - int const CouplNr{ - std::clamp(vehicle->DirectionGet() * (glm::length2(vehicle->HeadPosition() - glm::dvec3(Command.location)) > glm::length2(vehicle->RearPosition() - glm::dvec3(Command.location)) ? 1 : -1), 0, - 1)}; // z [-1,1] zrobić [0,1] - - auto const lightset{light::rearendsignals}; - - vehicle->MoverParameters->iLights[CouplNr] = - false == TestFlag(vehicle->MoverParameters->iLights[CouplNr], lightset) ? - vehicle->MoverParameters->iLights[CouplNr] |= lightset : // turn signals on - vehicle->MoverParameters->iLights[CouplNr] ^= lightset; // turn signals off - } -} - -void TTrain::OnCommand_headlightsdimtoggle(TTrain *Train, command_data const &Command) -{ - if (Train->DynamicObject->MoverParameters->enableModernDimmer) - return; - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Train->DynamicObject->MoverParameters->modernDimmerPosition == 0) - { - // turn on - OnCommand_headlightsdimenable(Train, Command); - } - else - { - // turn off - OnCommand_headlightsdimdisable(Train, Command); - } - } -} - -void TTrain::OnCommand_headlightsdimenable(TTrain *Train, command_data const &Command) -{ - - if (Train->DynamicObject->MoverParameters->enableModernDimmer) - return; - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Train->ggDimHeadlightsButton.SubModel != nullptr) - { - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - // visual feedback - Train->ggDimHeadlightsButton.UpdateValue(1.0, Train->dsbSwitch); - } - - /* // to jest stara logika - if (true == Train->DynamicObject->DimHeadlights) - { - return; - } // already enabled - - Train->DynamicObject->DimHeadlights = true; - */ - Train->DynamicObject->MoverParameters->modernDimmerPosition = Train->DynamicObject->MoverParameters->clampDimmerPosition(1); // ustawiamy modern dimmer na flage przyciemnienia - Train->DynamicObject->SetLightDimmings(); - } -} - -void TTrain::OnCommand_headlightsdimdisable(TTrain *Train, command_data const &Command) -{ - - if (Train->DynamicObject->MoverParameters->enableModernDimmer) // nie wiem dlaczego to tak dziala ze jest odwrocona logika - return; - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Train->ggDimHeadlightsButton.SubModel != nullptr) - { - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - // visual feedback - Train->ggDimHeadlightsButton.UpdateValue(0.0, Train->dsbSwitch); - } - - /* // stara logika przyciemniania - if( false == Train->DynamicObject->DimHeadlights ) { return; } // already enabled - - Train->DynamicObject->DimHeadlights = false; - - */ - Train->DynamicObject->MoverParameters->modernDimmerPosition = 0; // ustawiamy modern dimmer na flage rozjasnienia - Train->DynamicObject->SetLightDimmings(); - } -} - -void TTrain::OnCommand_interiorlighttoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->Cabine[Train->iCabn].bLight) - { - // turn on - OnCommand_interiorlightenable(Train, Command); - } - else - { - // turn off - OnCommand_interiorlightdisable(Train, Command); - } - } -} - -void TTrain::OnCommand_interiorlightenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->m_controlmapper.contains("cablight_sw:")) - { - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - WriteLog("Interior Light switch is missing, or wasn't defined"); - return; - } - // store lighting switch states - if (false == Train->DynamicObject->JointCabs) - { - // vehicles with separate cabs get separate lighting switch states - Train->Cabine[Train->iCabn].bLight = true; - } - else - { - // joint virtual cabs share lighting switch states - for (auto &cab : Train->Cabine) - { - cab.bLight = true; - } - } - } -} - -void TTrain::OnCommand_interiorlightdisable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->m_controlmapper.contains("cablight_sw:")) - { - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - WriteLog("Interior Light switch is missing, or wasn't defined"); - return; - } - // store lighting switch states - if (false == Train->DynamicObject->JointCabs) - { - // vehicles with separate cabs get separate lighting switch states - Train->Cabine[Train->iCabn].bLight = false; - } - else - { - // joint virtual cabs share lighting switch states - for (auto &cab : Train->Cabine) - { - cab.bLight = false; - } - } - } -} - -void TTrain::OnCommand_interiorlightdimtoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->Cabine[Train->iCabn].bLightDim) - { - // turn on - OnCommand_interiorlightdimenable(Train, Command); - } - else - { - // turn off - OnCommand_interiorlightdimdisable(Train, Command); - } - } -} - -void TTrain::OnCommand_interiorlightdimenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Train->ggCabLightDimButton.SubModel == nullptr) - { - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - WriteLog("Dim Interior Light switch is missing, or wasn't defined"); - return; - } - // visual feedback - Train->ggCabLightDimButton.UpdateValue(1.0, Train->dsbSwitch); - // store lighting switch states - if (false == Train->DynamicObject->JointCabs) - { - // vehicles with separate cabs get separate lighting switch states - Train->Cabine[Train->iCabn].bLightDim = true; - } - else - { - // joint virtual cabs share lighting switch states - for (auto &cab : Train->Cabine) - { - cab.bLightDim = true; - } - } - } -} - -void TTrain::OnCommand_interiorlightdimdisable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Train->ggCabLightDimButton.SubModel == nullptr) - { - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - WriteLog("Dim Interior Light switch is missing, or wasn't defined"); - return; - } - // visual feedback - Train->ggCabLightDimButton.UpdateValue(0.0, Train->dsbSwitch); - // store lighting switch states - if (false == Train->DynamicObject->JointCabs) - { - // vehicles with separate cabs get separate lighting switch states - Train->Cabine[Train->iCabn].bLightDim = false; - } - else - { - // joint virtual cabs share lighting switch states - for (auto &cab : Train->Cabine) - { - cab.bLightDim = false; - } - } - } -} - -void TTrain::OnCommand_compartmentlightstoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Command.action == GLFW_RELEASE) - { - // the press changed the state the command is picked from below, so a release picked from it went to the other - // command and the push button that was pressed never withdrew its request. The release goes to both commands: - // each returns its own push type control to the neutral position and withdraws its request - OnCommand_compartmentlightsenable(Train, Command); - OnCommand_compartmentlightsdisable(Train, Command); - return; - } - - // keep the switch from flipping back and forth if key is held down - if (false == Train->mvOccupied->CompartmentLights.is_active && false == Train->mvOccupied->CompartmentLights.is_enabled) - { - // turn on - OnCommand_compartmentlightsenable(Train, Command); - } - else - { - // turn off - OnCommand_compartmentlightsdisable(Train, Command); - } -} - -void TTrain::OnCommand_compartmentlightsenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - Train->mvOccupied->CompartmentLightsSwitch(true); - // withdraw the off request, unless a push type control in the cab withdraws it when released - if (compartment_lights_switch::withdraws_other_request(Train->m_controlmapper.contains("compartmentlights_sw:"), Train->ggCompartmentLightsButton.is_toggle(), - Train->m_controlmapper.contains("compartmentlightsoff_sw:"))) - { - Train->mvOccupied->CompartmentLightsSwitchOff(false); - } - // visual feedback - if (Train->m_controlmapper.contains("compartmentlights_sw:")) - { - Train->ggCompartmentLightsButton.UpdateValue(1.0f, Train->dsbSwitch); - } - if (Train->m_controlmapper.contains("compartmentlightson_sw:")) - { - Train->ggCompartmentLightsOnButton.UpdateValue(1.0f, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - if (Train->m_controlmapper.contains("compartmentlights_sw:") && Train->ggCompartmentLightsButton.type() == TGaugeType::push) - { - // return the switch to neutral position - Train->mvOccupied->CompartmentLightsSwitch(false); - Train->mvOccupied->CompartmentLightsSwitchOff(false); - Train->ggCompartmentLightsButton.UpdateValue(0.5f); - } - if (Train->m_controlmapper.contains("compartmentlightson_sw:")) - { - Train->mvOccupied->CompartmentLightsSwitch(false); - Train->ggCompartmentLightsOnButton.UpdateValue(0.0f, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_compartmentlightsdisable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - Train->mvOccupied->CompartmentLightsSwitchOff(true); - // withdraw the on request, unless a push type control in the cab withdraws it when released - if (compartment_lights_switch::withdraws_other_request(Train->m_controlmapper.contains("compartmentlights_sw:"), Train->ggCompartmentLightsButton.is_toggle(), - Train->m_controlmapper.contains("compartmentlightson_sw:"))) - { - Train->mvOccupied->CompartmentLightsSwitch(false); - } - // visual feedback - if (Train->m_controlmapper.contains("compartmentlights_sw:")) - { - Train->ggCompartmentLightsButton.UpdateValue(0.0f, Train->dsbSwitch); - } - if (Train->m_controlmapper.contains("compartmentlightsoff_sw:")) - { - Train->ggCompartmentLightsOffButton.UpdateValue(1.0f, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - if (Train->m_controlmapper.contains("compartmentlights_sw:") && Train->ggCompartmentLightsButton.type() == TGaugeType::push) - { - // return the switch to neutral position - Train->mvOccupied->CompartmentLightsSwitch(false); - Train->mvOccupied->CompartmentLightsSwitchOff(false); - Train->ggCompartmentLightsButton.UpdateValue(0.5f); - } - if (Train->m_controlmapper.contains("compartmentlightsoff_sw:")) - { - Train->mvOccupied->CompartmentLightsSwitchOff(false); - Train->ggCompartmentLightsOffButton.UpdateValue(0.0f, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_instrumentlighttoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->InstrumentLightActive) - { - // turn on - OnCommand_instrumentlightenable(Train, Command); - } - else - { - // turn off - OnCommand_instrumentlightdisable(Train, Command); - } - } -} - -void TTrain::OnCommand_instrumentlightenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Train->ggInstrumentLightButton.SubModel == nullptr) - { - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - WriteLog("Instrument Light switch is missing, or wasn't defined"); - return; - } - // visual feedback - Train->ggInstrumentLightButton.UpdateValue(1.0, Train->dsbSwitch); - - if (true == Train->InstrumentLightActive) - { - return; - } // already enabled - - Train->InstrumentLightActive = true; - } -} - -void TTrain::OnCommand_instrumentlightdisable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Train->ggInstrumentLightButton.SubModel == nullptr) - { - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - WriteLog("Instrument Light switch is missing, or wasn't defined"); - return; - } - // visual feedback - Train->ggInstrumentLightButton.UpdateValue(0.0, Train->dsbSwitch); - - if (false == Train->InstrumentLightActive) - { - return; - } // already disabled - - Train->InstrumentLightActive = false; - } -} - -void TTrain::OnCommand_dashboardlighttoggle(TTrain *Train, command_data const &Command) -{ - if (false == Train->DashboardLightActive) - { - OnCommand_dashboardlightenable(Train, Command); - } - else - { - OnCommand_dashboardlightdisable(Train, Command); - } -} - -void TTrain::OnCommand_dashboardlightenable(TTrain *Train, command_data const &Command) -{ - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Command.action != GLFW_PRESS) - { - return; - } - - if (Train->ggDashboardLightButton.SubModel == nullptr) - { - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - WriteLog("Dashboard Light switch is missing, or wasn't defined"); - return; - } - - if (false == Train->DashboardLightActive) - { - // turn on - Train->DashboardLightActive = true; - // visual feedback - Train->ggDashboardLightButton.UpdateValue(1.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_dashboardlightdisable(TTrain *Train, command_data const &Command) -{ - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Command.action != GLFW_PRESS) - { - return; - } - - if (Train->ggDashboardLightButton.SubModel == nullptr) - { - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - WriteLog("Dashboard Light switch is missing, or wasn't defined"); - return; - } - - if (Train->DashboardLightActive) - { - // turn off - Train->DashboardLightActive = false; - // visual feedback - Train->ggDashboardLightButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_timetablelighttoggle(TTrain *Train, command_data const &Command) -{ - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Command.action != GLFW_PRESS) - { - return; - } - - if (false == Train->TimetableLightActive) - { - OnCommand_timetablelightenable(Train, Command); - } - else - { - OnCommand_timetablelightdisable(Train, Command); - } -} - -void TTrain::OnCommand_timetablelightenable(TTrain *Train, command_data const &Command) -{ - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Command.action != GLFW_PRESS) - { - return; - } - - if (Train->ggTimetableLightButton.SubModel == nullptr) - { - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - WriteLog("Timetable Light switch is missing, or wasn't defined"); - return; - } - - if (false == Train->TimetableLightActive) - { - // turn on - Train->TimetableLightActive = true; - // visual feedback - Train->ggTimetableLightButton.UpdateValue(1.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_timetablelightdisable(TTrain *Train, command_data const &Command) -{ - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Command.action != GLFW_PRESS) - { - return; - } - - if (Train->ggTimetableLightButton.SubModel == nullptr) - { - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - WriteLog("Timetable Light switch is missing, or wasn't defined"); - return; - } - if (Train->TimetableLightActive) - { - // turn off - Train->TimetableLightActive = false; - // visual feedback - Train->ggTimetableLightButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_heatingtoggle(TTrain *Train, command_data const &Command) -{ - - if (Train->ggTrainHeatingButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Train Heating switch is missing, or wasn't defined"); - } - return; - } - - if (Command.action == GLFW_PRESS) - { - // ignore repeats so the switch doesn't flip back and forth if key is held down - if (false == Train->mvControlled->HeatingAllow) - { - // turn on - OnCommand_heatingenable(Train, Command); - } - else - { - // turn off - OnCommand_heatingdisable(Train, Command); - } - } - else if (Command.action == GLFW_RELEASE && (Train->ggTrainHeatingButton.type() == TGaugeType::push || Train->mvOccupied->HeatingSwitchImpulse)) - { - // impulse switch - // visual feedback - Train->ggTrainHeatingButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_heatingenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - Train->mvOccupied->HeatingSwitch(true); - // visual feedback - Train->ggTrainHeatingButton.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE && Train->mvOccupied->HeatingSwitchImpulse) - { - // the switch springs back to the middle - Train->ggTrainHeatingButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_heatingdisable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - Train->mvOccupied->HeatingSwitch(false); - // visual feedback: an impulse switch is pushed the other way, down - auto position{0.0}; - if (Train->mvOccupied->HeatingSwitchImpulse) - { - position = -1.0; - } - else if (Train->ggTrainHeatingButton.type() == TGaugeType::push) - { - position = 1.0; - } - Train->ggTrainHeatingButton.UpdateValue(position, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE && Train->mvOccupied->HeatingSwitchImpulse) - { - Train->ggTrainHeatingButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_generictoggle(TTrain *Train, command_data const &Command) -{ - - auto const itemindex = static_cast(Command.command) - static_cast(user_command::generictoggle0); - auto &item = Train->ggUniversals[itemindex]; - /* - if( item.SubModel == nullptr ) { - if( Command.action == GLFW_PRESS ) { - WriteLog( "Train generic item " + std::to_string( itemindex ) + " is missing, or wasn't defined" ); - } - return; - } - */ - - if (Command.action == GLFW_PRESS) - { - - if (item.type() == TGaugeType::push) - { - // impulse switch - // turn on - // visual feedback - item.UpdateValue(1.0); - } - else - { - // two-state switch, or one dragged in between its ends with the mouse: to the end farther from it - // visual feedback - item.UpdateValue(universal_drag::toggled(item.GetDesiredValue())); - } - } - else if (Command.action == GLFW_RELEASE && item.type() == TGaugeType::push) - { - // impulse switch - // turn off - // visual feedback - item.UpdateValue(0.0); - } -} - -// sets a universal control to the position given in param1, from 0 to 1 (MaSzyna-EU07/maszyna#62): the mouse drags -// the ones with drag: in their definition, and it can be bound to an axis of a gamepad. it stays where it is set -void TTrain::OnCommand_genericset(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_RELEASE) - { - return; - } - auto const itemindex = static_cast(Command.command) - static_cast(user_command::genericset0); - auto &item = Train->ggUniversals[itemindex]; - if (item.is_push()) - { - // an impulse switch springs back, it has no position to be left in - return; - } - // visual feedback - item.UpdateValue(universal_drag::clamp(Command.param1)); -} - -universal_drag::direction TTrain::universal_drag_direction(int const Index) const -{ - - if (Index < 0 || Index >= static_cast(ggUniversals.size()) || ggUniversals[Index].SubModel == nullptr) - { - return universal_drag::direction::none; - } - return ggUniversals[Index].drag(); -} - -float TTrain::universal_position(int const Index) const -{ - - if (Index < 0 || Index >= static_cast(ggUniversals.size())) - { - return 0.f; - } - return ggUniversals[Index].GetDesiredValue(); -} - -void TTrain::OnCommand_springbraketoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvOccupied->SpringBrake.Activate) - { - // turn on - OnCommand_springbrakeenable(Train, Command); - } - else - { - // turn off - OnCommand_springbrakedisable(Train, Command); - } - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggSpringBrakeOffButton.UpdateValue(0.0, Train->dsbSwitch); - Train->ggSpringBrakeOnButton.UpdateValue(0.0, Train->dsbSwitch); - } -}; - -void TTrain::OnCommand_springbrakeenable(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpringBrakeActivate(true); - // visual feedback - Train->ggSpringBrakeOnButton.UpdateValue(1.0, Train->dsbSwitch); - Train->ggSpringBrakeOffButton.UpdateValue(0.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggSpringBrakeOnButton.UpdateValue(0.0, Train->dsbSwitch); - } -}; - -void TTrain::OnCommand_springbrakedisable(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpringBrakeActivate(false); - // visual feedback - Train->ggSpringBrakeOffButton.UpdateValue(1.0, Train->dsbSwitch); - Train->ggSpringBrakeOnButton.UpdateValue(0.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggSpringBrakeOffButton.UpdateValue(0.0, Train->dsbSwitch); - } -}; -void TTrain::OnCommand_springbrakeshutofftoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvOccupied->SpringBrake.ShuttOff) - { - // turn on - OnCommand_springbrakeshutoffenable(Train, Command); - } - else - { - // turn off - OnCommand_springbrakeshutoffdisable(Train, Command); - } - } -}; - -void TTrain::OnCommand_springbrakeshutoffenable(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpringBrakeShutOff(true); - } -}; - -void TTrain::OnCommand_springbrakeshutoffdisable(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpringBrakeShutOff(false); - } -}; - -void TTrain::OnCommand_springbrakerelease(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - - if (auto const *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; vehicle == nullptr) - { - return; - } - Train->mvOccupied->SpringBrakeRelease(); - } -}; - -void TTrain::OnCommand_speedcontrolincrease(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpeedCtrlInc(); - // visual feedback - Train->ggSpeedControlIncreaseButton.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggSpeedControlIncreaseButton.UpdateValue(0.0, Train->dsbSwitch); - } -}; - -void TTrain::OnCommand_speedcontroldecrease(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpeedCtrlDec(); - // visual feedback - Train->ggSpeedControlDecreaseButton.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggSpeedControlDecreaseButton.UpdateValue(0.0, Train->dsbSwitch); - } -}; - -void TTrain::OnCommand_speedcontrolpowerincrease(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpeedCtrlPowerInc(); - // visual feedback - Train->ggSpeedControlPowerIncreaseButton.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggSpeedControlPowerIncreaseButton.UpdateValue(0.0, Train->dsbSwitch); - } -}; - -void TTrain::OnCommand_speedcontrolpowerdecrease(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpeedCtrlPowerDec(); - // visual feedback - Train->ggSpeedControlPowerDecreaseButton.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggSpeedControlPowerDecreaseButton.UpdateValue(0.0, Train->dsbSwitch); - } -}; - -void TTrain::OnCommand_speedcontrolbutton(TTrain *Train, command_data const &Command) -{ - - auto const itemindex = static_cast(Command.command) - static_cast(user_command::speedcontrolbutton0); - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpeedCtrlButton(itemindex); - // visual feedback - Train->ggSpeedCtrlButtons[itemindex].UpdateValue(1.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggSpeedCtrlButtons[itemindex].UpdateValue(0.0, Train->dsbSwitch); - } -}; - -void TTrain::OnCommand_inverterenable(TTrain *Train, command_data const &Command) -{ - - auto itemindex = static_cast(Command.command) - static_cast(user_command::inverterenable1); - auto &item = Train->ggInverterEnableButtons[itemindex]; - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; - auto const flag{CouplingSet::FromBits(Train->DynamicObject->MoverParameters->InverterControlCouplerFlag)}; - TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); - while (p) - { - if (p->MoverParameters->eimc[eimc_p_Pmax] > 1) - { - if (itemindex < p->MoverParameters->InvertersNo) - { - p->MoverParameters->Inverters[itemindex].Activate = true; - break; - } - else - { - itemindex -= p->MoverParameters->InvertersNo; - } - } - p = kier ? p->Next(flag) : p->Prev(flag); - } - // visual feedback - item.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - item.UpdateValue(0.0, Train->dsbSwitch); - } -}; - -void TTrain::OnCommand_inverterdisable(TTrain *Train, command_data const &Command) -{ - - auto itemindex = static_cast(Command.command) - static_cast(user_command::inverterdisable1); - auto &item = Train->ggInverterDisableButtons[itemindex]; - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; - auto const flag{CouplingSet::FromBits(Train->DynamicObject->MoverParameters->InverterControlCouplerFlag)}; - TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); - while (p) - { - if (p->MoverParameters->eimc[eimc_p_Pmax] > 1) - { - if (itemindex < p->MoverParameters->InvertersNo) - { - p->MoverParameters->Inverters[itemindex].Activate = false; - break; - } - else - { - itemindex -= p->MoverParameters->InvertersNo; - } - } - p = kier ? p->Next(flag) : p->Prev(flag); - } - // visual feedback - item.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - item.UpdateValue(0.0, Train->dsbSwitch); - } -}; - -void TTrain::OnCommand_invertertoggle(TTrain *Train, command_data const &Command) -{ - - auto itemindex = static_cast(Command.command) - static_cast(user_command::invertertoggle1); - auto &item = Train->ggInverterToggleButtons[itemindex]; - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; - auto const flag{CouplingSet::FromBits(Train->DynamicObject->MoverParameters->InverterControlCouplerFlag)}; - TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); - while (p) - { - if (p->MoverParameters->eimc[eimc_p_Pmax] > 1) - { - if (itemindex < p->MoverParameters->InvertersNo) - { - p->MoverParameters->Inverters[itemindex].Activate = !p->MoverParameters->Inverters[itemindex].Activate; - // visual feedback - item.UpdateValue(p->MoverParameters->Inverters[itemindex].Activate ? 1.0 : 0.0, Train->dsbSwitch); - break; - } - else - { - itemindex -= p->MoverParameters->InvertersNo; - } - } - p = kier ? p->Next(flag) : p->Prev(flag); - } - } -}; - -void TTrain::OnCommand_doorlocktoggle(TTrain *Train, command_data const &Command) -{ - - if (Train->ggDoorSignallingButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Door Lock switch is missing, or wasn't defined"); - } - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the sound can loop uninterrupted - if (false == Train->mvOccupied->Doors.lock_enabled) - { - // turn on - // TODO: door lock command to send through consist - Train->mvOccupied->LockDoors(true); - // visual feedback - Train->ggDoorSignallingButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // turn off - // TODO: door lock command to send through consist - Train->mvOccupied->LockDoors(false); - // visual feedback - Train->ggDoorSignallingButton.UpdateValue(0.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_doortoggleleft(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // NOTE: test how the door state check works with consists where the occupied vehicle doesn't have opening doors - if (false == (Train->ggDoorLeftButton.GetDesiredValue() > 0.5 || Train->ggDoorLeftOnButton.GetDesiredValue() > 0.5)) - { - // open - OnCommand_dooropenleft(Train, Command); - } - else - { - // close - if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorLeftOffButton.SubModel == nullptr) - { - // OnCommand_doorcloseall( Train, Command ); - // if two-button setup lacks dedicated closing button require the user to press appropriate button manually - return; - } - else - { - OnCommand_doorcloseleft(Train, Command); - } - } - } - else if (Command.action == GLFW_RELEASE) - { - - if (true == (Train->ggDoorLeftButton.GetDesiredValue() > 0.5 || Train->ggDoorLeftOnButton.GetDesiredValue() > 0.5)) - { - // open - if (Train->mvOccupied->Doors.has_autowarning && Train->mvOccupied->DepartureSignal) - { - // complete closing the doors - if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorLeftOffButton.SubModel == nullptr) - { - // OnCommand_doorcloseall( Train, Command ); - // if two-button setup lacks dedicated closing button require the user to press appropriate button manually - return; - } - else - { - OnCommand_doorcloseleft(Train, Command); - } - } - else - { - OnCommand_dooropenleft(Train, Command); - } - } - else - { - // close - if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorLeftOffButton.SubModel == nullptr) - { - // OnCommand_doorcloseall( Train, Command ); - // if two-button setup lacks dedicated closing button require the user to press appropriate button manually - return; - } - else - { - OnCommand_doorcloseleft(Train, Command); - } - } - // visual feedback - // dedicated closing buttons are presumed to be impulse switches and return automatically to neutral position - // NOTE: temporary arrangement, can be removed when LD system is in place - if (Train->ggDoorLeftOffButton.SubModel) - Train->ggDoorLeftOffButton.UpdateValue(0.0, Train->dsbSwitch); - if (Train->ggDoorLeftOnButton.SubModel) - Train->ggDoorLeftOnButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_doorpermitleft(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - if (false == Train->mvOccupied->Doors.permit_presets.empty()) - { - return; - } - - auto const side{(Train->cab_to_end() == end::front ? side::left : side::right)}; - - if (Command.action == GLFW_PRESS) - { - - if (Train->ggDoorLeftPermitButton.is_push()) - { - // impulse switch - Train->mvOccupied->PermitDoors(side); - // visual feedback - Train->ggDoorLeftPermitButton.UpdateValue(1.0, Train->dsbSwitch); - // start potential timer for remote door control - Train->m_doorpermittimers[side] = Train->mvOccupied->DoorsOpenWithPermitAfter; - } - else - { - // two-state switch - auto const newstate{!(Train->ggDoorLeftPermitButton.GetDesiredValue() > 0.5)}; - - Train->mvOccupied->PermitDoors(side, newstate); - // visual feedback - Train->ggDoorLeftPermitButton.UpdateValue(newstate ? 1.0 : 0.0, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE && Train->ggDoorLeftPermitButton.is_push()) - { - // impulse switch - // visual feedback - Train->ggDoorLeftPermitButton.UpdateValue(0.0, Train->dsbSwitch); - // reset potential remote door control timer - Train->m_doorpermittimers[side] = -1.f; - } -} - -void TTrain::OnCommand_doorpermitright(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - if (false == Train->mvOccupied->Doors.permit_presets.empty()) - { - return; - } - - auto const side{(Train->cab_to_end() == end::front ? side::right : side::left)}; - - if (Command.action == GLFW_PRESS) - { - - if (Train->ggDoorRightPermitButton.type() == TGaugeType::push) - { - // impulse switch - Train->mvOccupied->PermitDoors(side); - // visual feedback - Train->ggDoorRightPermitButton.UpdateValue(1.0, Train->dsbSwitch); - // start potential timer for remote door control - Train->m_doorpermittimers[side] = Train->mvOccupied->DoorsOpenWithPermitAfter; - } - else - { - // two-state switch - auto const newstate{!(Train->ggDoorRightPermitButton.GetDesiredValue() > 0.5)}; - - Train->mvOccupied->PermitDoors(side, newstate); - // visual feedback - Train->ggDoorRightPermitButton.UpdateValue(newstate ? 1.0 : 0.0, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE && Train->ggDoorRightPermitButton.type() == TGaugeType::push) - { - // impulse switch - // visual feedback - Train->ggDoorRightPermitButton.UpdateValue(0.0, Train->dsbSwitch); - // reset potential remote door control timer - Train->m_doorpermittimers[side] = -1.f; - } -} - -void TTrain::OnCommand_doorpermitpresetactivatenext(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - Train->mvOccupied->ChangeDoorPermitPreset(1); - // visual feedback - Train->ggDoorPermitPresetButton.UpdateValue(static_cast(Train->mvOccupied->Doors.permit_preset), Train->dsbSwitch); - } -} - -void TTrain::OnCommand_doorpermitpresetactivateprevious(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - Train->mvOccupied->ChangeDoorPermitPreset(-1); - // visual feedback - Train->ggDoorPermitPresetButton.UpdateValue(static_cast(Train->mvOccupied->Doors.permit_preset), Train->dsbSwitch); - } -} - -void TTrain::OnCommand_dooropenleft(TTrain *Train, command_data const &Command) -{ - - - if (auto const remoteopencontrol{Train->mvOccupied->Doors.open_control == control_t::driver || Train->mvOccupied->Doors.open_control == control_t::mixed}; false == remoteopencontrol) - { - return; - } - - if (Train->ggDoorLeftOnButton.SubModel == nullptr && Train->ggDoorLeftButton.SubModel == nullptr) - { - - return; - } - - if (Command.action == GLFW_PRESS) - { - Train->mvOccupied->OperateDoors(Train->cab_to_end() == end::front ? side::left : side::right, true); - // visual feedback - if (Train->ggDoorLeftOnButton.SubModel != nullptr) - { - // two separate impulse switches - Train->ggDoorLeftOnButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // single two-state switch - Train->ggDoorLeftButton.UpdateValue(1.0, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - if (Train->ggDoorLeftOnButton.SubModel != nullptr) - { - // two separate impulse switches - Train->ggDoorLeftOnButton.UpdateValue(0.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_doorcloseleft(TTrain *Train, command_data const &Command) -{ - - - if (auto const remoteclosecontrol{Train->mvOccupied->Doors.close_control == control_t::driver || Train->mvOccupied->Doors.close_control == control_t::mixed}; false == remoteclosecontrol) - { - return; - } - - if (Train->ggDoorLeftOffButton.SubModel == nullptr && Train->ggDoorLeftButton.SubModel == nullptr) - { - - return; - } - - if (Command.action == GLFW_PRESS) - { - - if (Train->mvOccupied->Doors.has_autowarning) - { - // automatic departure signal delays actual door closing until the button is released - Train->mvOccupied->signal_departure(true); - } - else - { - // TODO: move door opening/closing to the update, so the switch animation doesn't hinge on door working - Train->mvOccupied->OperateDoors(Train->cab_to_end() == end::front ? side::left : side::right, false); - } - // visual feedback - if (Train->ggDoorLeftOffButton.SubModel != nullptr) - { - // two separate switches to open and close the door - Train->ggDoorLeftOffButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // single two-state switch - Train->ggDoorLeftButton.UpdateValue(0.0, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - - if (Train->mvOccupied->Doors.has_autowarning) - { - // automatic departure signal delays actual door closing until the button is released - Train->mvOccupied->signal_departure(false); - // now we can actually close the door - Train->mvOccupied->OperateDoors(Train->cab_to_end() == end::front ? side::left : side::right, false); - } - // visual feedback - // dedicated closing buttons are presumed to be impulse switches and return automatically to neutral position - if (Train->ggDoorLeftOffButton.SubModel) - Train->ggDoorLeftOffButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_doortoggleright(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // NOTE: test how the door state check works with consists where the occupied vehicle doesn't have opening doors - if (false == (Train->ggDoorRightButton.GetDesiredValue() > 0.5 || Train->ggDoorRightOnButton.GetDesiredValue() > 0.5)) - { - // open - OnCommand_dooropenright(Train, Command); - } - else - { - // close - if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorRightOffButton.SubModel == nullptr) - { - // OnCommand_doorcloseall( Train, Command ); - // if two-button setup lacks dedicated closing button require the user to press appropriate button manually - return; - } - else - { - OnCommand_doorcloseright(Train, Command); - } - } - } - else if (Command.action == GLFW_RELEASE) - { - - if (true == (Train->ggDoorRightButton.GetDesiredValue() > 0.5 || Train->ggDoorRightOnButton.GetDesiredValue() > 0.5)) - { - // open - if (Train->mvOccupied->Doors.has_autowarning && Train->mvOccupied->DepartureSignal) - { - // complete closing the doors - if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorRightOffButton.SubModel == nullptr) - { - // OnCommand_doorcloseall( Train, Command ); - // if two-button setup lacks dedicated closing button require the user to press appropriate button manually - return; - } - else - { - OnCommand_doorcloseright(Train, Command); - } - } - else - { - OnCommand_dooropenright(Train, Command); - } - } - else - { - // close - if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorRightOffButton.SubModel == nullptr) - { - // OnCommand_doorcloseall( Train, Command ); - // if two-button setup lacks dedicated closing button require the user to press appropriate button manually - return; - } - else - { - OnCommand_doorcloseright(Train, Command); - } - } - // visual feedback - // dedicated closing buttons are presumed to be impulse switches and return automatically to neutral position - // NOTE: temporary arrangement, can be removed when LD system is in place - if (Train->ggDoorRightOffButton.SubModel) - Train->ggDoorRightOffButton.UpdateValue(0.0, Train->dsbSwitch); - if (Train->ggDoorRightOnButton.SubModel) - Train->ggDoorRightOnButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_dooropenright(TTrain *Train, command_data const &Command) -{ - - - if (auto const remoteopencontrol{Train->mvOccupied->Doors.open_control == control_t::driver || Train->mvOccupied->Doors.open_control == control_t::mixed}; false == remoteopencontrol) - { - return; - } - - if (Train->ggDoorRightOnButton.SubModel == nullptr && Train->ggDoorRightButton.SubModel == nullptr) - { - - return; - } - - if (Command.action == GLFW_PRESS) - { - - Train->mvOccupied->OperateDoors(Train->cab_to_end() == end::front ? side::right : side::left, true); - // visual feedback - if (Train->ggDoorRightOnButton.SubModel != nullptr) - { - // two separate impulse switches - Train->ggDoorRightOnButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // single two-state switch - Train->ggDoorRightButton.UpdateValue(1.0, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - if (Train->ggDoorRightOnButton.SubModel != nullptr) - { - // two separate impulse switches - Train->ggDoorRightOnButton.UpdateValue(0.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_doorcloseright(TTrain *Train, command_data const &Command) -{ - - - if (auto const remoteclosecontrol{Train->mvOccupied->Doors.close_control == control_t::driver || Train->mvOccupied->Doors.close_control == control_t::mixed}; false == remoteclosecontrol) - { - return; - } - - if (Train->ggDoorRightOffButton.SubModel == nullptr && Train->ggDoorRightButton.SubModel == nullptr) - { - - return; - } - - if (Command.action == GLFW_PRESS) - { - - if (Train->mvOccupied->Doors.has_autowarning) - { - // automatic departure signal delays actual door closing until the button is released - Train->mvOccupied->signal_departure(true); - } - else - { - Train->mvOccupied->OperateDoors(Train->cab_to_end() == end::front ? side::right : side::left, false); - } - // visual feedback - if (Train->ggDoorRightOffButton.SubModel != nullptr) - { - // two separate switches to open and close the door - Train->ggDoorRightOffButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // single two-state switch - Train->ggDoorRightButton.UpdateValue(0.0, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - - if (Train->mvOccupied->Doors.has_autowarning) - { - // automatic departure signal delays actual door closing until the button is released - Train->mvOccupied->signal_departure(false); - // now we can actually close the door - Train->mvOccupied->OperateDoors(Train->cab_to_end() == end::front ? side::right : side::left, false); - } - // visual feedback - // dedicated closing buttons are presumed to be impulse switches and return automatically to neutral position - if (Train->ggDoorRightOffButton.SubModel) - Train->ggDoorRightOffButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_dooropenall(TTrain *Train, command_data const &Command) -{ - - - if (auto const remoteopencontrol{Train->mvOccupied->Doors.open_control == control_t::driver || Train->mvOccupied->Doors.open_control == control_t::mixed}; false == remoteopencontrol) - { - return; - } - - if (Train->ggDoorAllOnButton.SubModel == nullptr) - { - // TODO: expand definition of cab controls so we can know if the control is present without testing for presence of 3d switch - if (Command.action == GLFW_PRESS) - { - WriteLog("Open All Doors switch is missing, or wasn't defined"); - } - return; - } - - if (Command.action == GLFW_PRESS) - { - - Train->mvOccupied->OperateDoors(side::right, true); - Train->mvOccupied->OperateDoors(side::left, true); - // visual feedback - Train->ggDoorAllOnButton.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggDoorAllOnButton.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_doorcloseall(TTrain *Train, command_data const &Command) -{ - - - if (auto const remoteclosecontrol{Train->mvOccupied->Doors.close_control == control_t::driver || Train->mvOccupied->Doors.close_control == control_t::mixed}; false == remoteclosecontrol) - { - return; - } - - if (Train->ggDoorAllOffButton.SubModel == nullptr) - { - // TODO: expand definition of cab controls so we can know if the control is present without testing for presence of 3d switch - if (Command.action == GLFW_PRESS) - { - WriteLog("Close All Doors switch is missing, or wasn't defined"); - } - return; - } - - if (Command.action == GLFW_PRESS) - { - - if (Train->mvOccupied->Doors.has_autowarning) - { - Train->mvOccupied->signal_departure(true); - } - if (Train->ggDoorAllOffButton.type() != TGaugeType::push_delayed) - { - // delays the action until the button is released - Train->mvOccupied->OperateDoors(side::right, false); - Train->mvOccupied->OperateDoors(side::left, false); - } - // visual feedback - Train->ggDoorLeftButton.UpdateValue(0.0, Train->dsbSwitch); - Train->ggDoorRightButton.UpdateValue(0.0, Train->dsbSwitch); - if (Train->ggDoorAllOffButton.SubModel) - Train->ggDoorAllOffButton.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - if (Train->mvOccupied->Doors.has_autowarning) - { - Train->mvOccupied->signal_departure(false); - } - if (Train->ggDoorAllOffButton.type() == TGaugeType::push_delayed) - { - // now we can actually close the door - Train->mvOccupied->OperateDoors(side::right, false); - Train->mvOccupied->OperateDoors(side::left, false); - } - // visual feedback - if (Train->ggDoorAllOffButton.SubModel) - Train->ggDoorAllOffButton.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_doorsteptoggle(TTrain *Train, command_data const &Command) -{ - // TODO: move logic/visualization code to the gauge, on_command() should return hint whether it should invoke a reaction - if (Command.action == GLFW_PRESS) - { - // effect - if (false == Train->ggDoorStepButton.is_delayed()) - { - Train->mvOccupied->PermitDoorStep(false == Train->mvOccupied->Doors.step_enabled); - } - // visual feedback - auto const isactive{(Train->ggDoorStepButton.is_push() // always press push button - || Train->mvOccupied->Doors.step_enabled)}; // for toggle buttons indicate item state - Train->ggDoorStepButton.UpdateValue(isactive ? 1 : 0); - } - else if (Command.action == GLFW_RELEASE) - { - // effect - if (Train->ggDoorStepButton.is_delayed()) - { - Train->mvOccupied->PermitDoorStep(false == Train->mvOccupied->Doors.step_enabled); - } - // visual feedback - if (Train->ggDoorStepButton.is_push()) - { - Train->ggDoorStepButton.UpdateValue(0); - } - } -} - -void TTrain::OnCommand_doormodetoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - Train->mvOccupied->ChangeDoorControlMode(false == Train->mvOccupied->Doors.remote_only); - } -} - -void TTrain::OnCommand_mirrorstoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_PRESS) - { - return; - } - - // only reacting to press, so the sound can loop uninterrupted - if (false == Train->mvOccupied->MirrorForbidden) - { - // turn on - Train->mvOccupied->MirrorForbidden = true; - } - else - { - // turn off - Train->mvOccupied->MirrorForbidden = false; - } -} - -void TTrain::OnCommand_nearestcarcouplingincrease(TTrain *Train, command_data const &Command) -{ - - if (true == Command.freefly && Command.action == GLFW_PRESS) - { - // tryb freefly, press only - auto couplerindex{-1}; - auto *vehicle{Train->DynamicObject->ABuScanNearestObject(Command.location, Train->DynamicObject->GetTrack(), 1, 1500, couplerindex)}; - if (vehicle == nullptr) - vehicle = Train->DynamicObject->ABuScanNearestObject(Command.location, Train->DynamicObject->GetTrack(), -1, 1500, couplerindex); - - if (couplerindex != -1 && vehicle != nullptr) - { - - vehicle->couple(couplerindex); - } - if (Train->DynamicObject->Mechanik) - { - // aktualizacja flag kierunku w składzie - Train->DynamicObject->Mechanik->CheckVehicles(DriverOrder::connect); - } - } -} - -void TTrain::OnCommand_nearestcarcouplingdisconnect(TTrain *Train, command_data const &Command) -{ - - if (true == Command.freefly && Command.action == GLFW_PRESS) - { - // tryb freefly, press only - auto couplerindex{-1}; - auto *vehicle{Train->DynamicObject->ABuScanNearestObject(Command.location, Train->DynamicObject->GetTrack(), 1, 1500, couplerindex)}; - if (vehicle == nullptr) - vehicle = Train->DynamicObject->ABuScanNearestObject(Command.location, Train->DynamicObject->GetTrack(), -1, 1500, couplerindex); - - if (couplerindex != -1 && vehicle != nullptr) - { - - vehicle->uncouple(couplerindex); - } - if (Train->DynamicObject->Mechanik) - { - // aktualizacja flag kierunku w składzie - Train->DynamicObject->Mechanik->CheckVehicles(DriverOrder::disconnect); - } - } -} - -void TTrain::OnCommand_nearestcarcoupleradapterattach(TTrain * /*Train*/, command_data const &Command) -{ - - if (true == Command.freefly && Command.action == GLFW_PRESS) - { - // tryb freefly, press only - auto *vehicle{std::get(simulation::Region->find_vehicle(Command.location, 50, false, true))}; - if (vehicle == nullptr) - { - return; - } - - auto const couplerindex = - glm::length2(glm::vec3{vehicle->CouplerPosition(end::front)} - Command.location) < glm::length2(glm::vec3{vehicle->CouplerPosition(end::rear)} - Command.location) ? end::front : end::rear; - - vehicle->attach_coupler_adapter(couplerindex); - } -} - -void TTrain::OnCommand_nearestcarcoupleradapterremove(TTrain * /*Train*/, command_data const &Command) -{ - - if (true == Command.freefly && Command.action == GLFW_PRESS) - { - // tryb freefly, press only - auto *vehicle{std::get(simulation::Region->find_vehicle(Command.location, 50, false, true))}; - if (vehicle == nullptr) - { - return; - } - - auto const couplerindex = - glm::length2(glm::vec3{vehicle->CouplerPosition(end::front)} - Command.location) < glm::length2(glm::vec3{vehicle->CouplerPosition(end::rear)} - Command.location) ? end::front : end::rear; - - vehicle->remove_coupler_adapter(couplerindex); - } -} - -void TTrain::OnCommand_occupiedcarcouplingdisconnect(TTrain *Train, command_data const &Command) -{ - - // if( false == Train->m_controlmapper.contains( "couplingdisconnect_sw:" ) ) { return; } - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->m_couplingdisconnect = true; - - if (Train->iCabn == 0) - { - return; - } - - if (Train->DynamicObject) - { - Train->DynamicObject->uncouple(Train->cab_to_end()); - if (Train->DynamicObject->Mechanik) - { - // aktualizacja flag kierunku w składzie - Train->DynamicObject->Mechanik->CheckVehicles(DriverOrder::disconnect); - } - } - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->m_couplingdisconnect = false; - } -} - -void TTrain::OnCommand_occupiedcarcouplingdisconnectback(TTrain *Train, command_data const &Command) -{ - - // if( false == Train->m_controlmapper.contains( "couplingdisconnect_sw:" ) ) { return; } - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->m_couplingdisconnectback = true; - - if (Train->iCabn == 0) - { - return; - } - - if (Train->DynamicObject) - { - Train->DynamicObject->uncouple(1 - Train->cab_to_end()); - if (Train->DynamicObject->Mechanik) - { - // aktualizacja flag kierunku w składzie - Train->DynamicObject->Mechanik->CheckVehicles(DriverOrder::disconnect); - } - } - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->m_couplingdisconnectback = false; - } -} - -void TTrain::OnCommand_departureannounce(TTrain *Train, command_data const &Command) -{ - - if (Train->ggDepartureSignalButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Departure Signal button is missing, or wasn't defined"); - } - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the sound can loop uninterrupted - if (false == Train->mvOccupied->DepartureSignal) - { - // turn on - Train->mvOccupied->signal_departure(true); - // visual feedback - Train->ggDepartureSignalButton.UpdateValue(1.0, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - // turn off - Train->mvOccupied->signal_departure(false); - // visual feedback - Train->ggDepartureSignalButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_hornlowactivate(TTrain *Train, command_data const &Command) -{ - - if (Train->ggHornButton.SubModel == nullptr && Train->ggHornLowButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Horn button is missing, or wasn't defined"); - } - return; - } - - if (Command.action == GLFW_PRESS) - { - // only need to react to press, sound will continue until stopped - if (false == TestFlag(Train->mvOccupied->WarningSignal, horn::low)) - { - // turn on - Train->mvOccupied->WarningSignal = horn::pressed(Train->mvOccupied->WarningSignal, horn::low, Train->has_single_horn_lever()); - // visual feedback - Train->ggHornButton.UpdateValue(-1.0); - Train->ggHornLowButton.UpdateValue(1.0); - } - } - else if (Command.action == GLFW_RELEASE) - { - // turn off - Train->mvOccupied->WarningSignal = horn::released(Train->mvOccupied->WarningSignal, horn::low); - // visual feedback - if (false == (Train->has_single_horn_lever() && TestFlag(Train->mvOccupied->WarningSignal, horn::high))) - { - // leave the single lever alone if it was moved to the other tone in the meantime - Train->ggHornButton.UpdateValue(0.0); - } - Train->ggHornLowButton.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_hornhighactivate(TTrain *Train, command_data const &Command) -{ - - if (Train->ggHornButton.SubModel == nullptr && Train->ggHornHighButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Horn button is missing, or wasn't defined"); - } - return; - } - - if (Command.action == GLFW_PRESS) - { - // only need to react to press, sound will continue until stopped - if (false == TestFlag(Train->mvOccupied->WarningSignal, horn::high)) - { - // turn on - Train->mvOccupied->WarningSignal = horn::pressed(Train->mvOccupied->WarningSignal, horn::high, Train->has_single_horn_lever()); - // visual feedback - Train->ggHornButton.UpdateValue(1.0); - Train->ggHornHighButton.UpdateValue(1.0); - } - } - else if (Command.action == GLFW_RELEASE) - { - // turn off - Train->mvOccupied->WarningSignal = horn::released(Train->mvOccupied->WarningSignal, horn::high); - // visual feedback - if (false == (Train->has_single_horn_lever() && TestFlag(Train->mvOccupied->WarningSignal, horn::low))) - { - // leave the single lever alone if it was moved to the other tone in the meantime - Train->ggHornButton.UpdateValue(0.0); - } - Train->ggHornHighButton.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_whistleactivate(TTrain *Train, command_data const &Command) -{ - - if (Train->ggWhistleButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Whistle button is missing, or wasn't defined"); - } - return; - } - - if (Command.action == GLFW_PRESS) - { - // only need to react to press, sound will continue until stopped - if (false == TestFlag(Train->mvOccupied->WarningSignal, 4)) - { - // turn on - Train->mvOccupied->WarningSignal |= 4; - // visual feedback - Train->ggWhistleButton.UpdateValue(1.0); - } - } - else if (Command.action == GLFW_RELEASE) - { - // turn off - Train->mvOccupied->WarningSignal &= ~4; - // visual feedback - Train->ggWhistleButton.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_radiotoggle(TTrain *Train, command_data const &Command) -{ - if (Command.action != GLFW_PRESS) - { - return; - } - - // NOTE: works without the switch in the 3d model too, to allow system reset after receiving radio-stop signal - // only reacting to press, so the sound can loop uninterrupted - // NOTE: flips the state directly rather than through radioenable/radiodisable, so it doesn't move the radioon_sw:/radiooff_sw: buttons - Train->mvOccupied->Radio = (false == Train->mvOccupied->Radio); -} - -void TTrain::OnCommand_radioenable(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - Train->mvOccupied->Radio = true; - // visual feedback - if (Train->m_controlmapper.contains("radioon_sw:")) - { - Train->ggRadioOnButton.UpdateValue(1.0f, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - if (Train->m_controlmapper.contains("radioon_sw:")) - { - Train->ggRadioOnButton.UpdateValue(0.0f, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_radiodisable(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - Train->mvOccupied->Radio = false; - // visual feedback - if (Train->m_controlmapper.contains("radiooff_sw:")) - { - Train->ggRadioOffButton.UpdateValue(1.0f, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - if (Train->m_controlmapper.contains("radiooff_sw:")) - { - Train->ggRadioOffButton.UpdateValue(0.0f, Train->dsbSwitch); - } - } -} - -// the cut-off in the radio's power supply (eu07/maszyna#438); opening it works like switching the radio off, the -// radio-stop flag included -void TTrain::OnCommand_radiofusetoggle(TTrain *Train, command_data const &Command) -{ - if (Command.action != GLFW_PRESS) - { - return; - } - - // NOTE: flips the state directly rather than through radiofuseenable/radiofusedisable, so it doesn't move the - // radiofuseon_sw:/radiofuseoff_sw: buttons - Train->mvOccupied->RadioFuse = (false == Train->mvOccupied->RadioFuse); -} - -void TTrain::OnCommand_radiofuseenable(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - Train->mvOccupied->RadioFuse = true; - // visual feedback - if (Train->m_controlmapper.contains("radiofuseon_sw:")) - { - Train->ggRadioFuseOnButton.UpdateValue(1.0f, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - if (Train->m_controlmapper.contains("radiofuseon_sw:")) - { - Train->ggRadioFuseOnButton.UpdateValue(0.0f, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_radiofusedisable(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - Train->mvOccupied->RadioFuse = false; - // visual feedback - if (Train->m_controlmapper.contains("radiofuseoff_sw:")) - { - Train->ggRadioFuseOffButton.UpdateValue(1.0f, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - if (Train->m_controlmapper.contains("radiofuseoff_sw:")) - { - Train->ggRadioFuseOffButton.UpdateValue(0.0f, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_radiochannelincrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // the channel buttons of a radio switched off or without power do nothing - if (Train->mvOccupied->RadioPowered()) - { - command_data newCommand = Command; - newCommand.param1 = Train->RadioChannel() + 1; - OnCommand_radiochannelset(Train, newCommand); - } - - Train->ggRadioChannelNext.UpdateValue(1.0); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggRadioChannelNext.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_radiochanneldecrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - if (Train->mvOccupied->RadioPowered()) - { - command_data newCommand = Command; - newCommand.param1 = Train->RadioChannel() - 1; - OnCommand_radiochannelset(Train, newCommand); - } - - Train->ggRadioChannelPrevious.UpdateValue(1.0); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggRadioChannelPrevious.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_radiochannelset(TTrain *Train, command_data const &Command) -{ - if (Command.action != GLFW_RELEASE) - { - // on press or hold - Train->RadioChannel() = std::clamp((int)Command.param1, 1, 10); - Train->ggRadioChannelSelector.UpdateValue(static_cast(Train->RadioChannel() - 1)); - } -} - -void TTrain::OnCommand_radiostopsend(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - if (Train->mvOccupied->RadioPowered()) - { - simulation::Region->RadioStop(Train->Dynamic()->GetPosition()); - } - // visual feedback - Train->ggRadioStop.UpdateValue(1.0); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggRadioStop.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_radiostopenable(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS && Train->ggRadioStop.GetValue() == 0) - { - if (Train->mvOccupied->RadioPowered()) - { - simulation::Region->RadioStop(Train->Dynamic()->GetPosition()); - } - // visual feedback - Train->ggRadioStop.UpdateValue(1.0); - } -} - -void TTrain::OnCommand_radiostopdisable(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS && Train->ggRadioStop.GetValue() > 0) - { - // visual feedback - Train->ggRadioStop.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_radiostoptest(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - if (Train->RadioChannel() == 10 && Train->mvOccupied->RadioPowered()) - { - Train->Dynamic()->RadioStop(); - } - // visual feedback - Train->ggRadioTest.UpdateValue(1.0); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggRadioTest.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_radiocall1send(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - if (Train->RadioChannel() != 10 && Train->mvOccupied->RadioPowered()) - { - simulation::Events.queue_receivers(radio_message::call1, Train->Dynamic()->GetPosition()); - } - // visual feedback - Train->ggRadioCall1.UpdateValue(1.0); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggRadioCall1.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_radiocall3send(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - if (Train->RadioChannel() != 10 && Train->mvOccupied->RadioPowered()) - { - simulation::Events.queue_receivers(radio_message::call3, Train->Dynamic()->GetPosition()); - } - // visual feedback - Train->ggRadioCall3.UpdateValue(1.0); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggRadioCall3.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_radiovolumeincrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // so do the volume buttons - if (Train->mvOccupied->RadioPowered()) - { - command_data newCommand = Command; - newCommand.param1 = Train->m_radiovolume + 0.125; - OnCommand_radiovolumeset(Train, newCommand); - } - Train->ggRadioVolumeNext.UpdateValue(1.0); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggRadioVolumeNext.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_radiovolumedecrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - if (Train->mvOccupied->RadioPowered()) - { - command_data newCommand = Command; - newCommand.param1 = Train->m_radiovolume - 0.125; - OnCommand_radiovolumeset(Train, newCommand); - } - Train->ggRadioVolumePrevious.UpdateValue(1.0); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggRadioVolumePrevious.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_radiovolumeset(TTrain *Train, command_data const &Command) -{ - if (Command.action != GLFW_RELEASE) - { - // on press or hold - Train->m_radiovolume = static_cast(std::clamp(Command.param1, 0.0, 1.0)); - Train->ggRadioVolumeSelector.UpdateValue(Train->m_radiovolume); - audio::event_volume_change = true; - } -} - -void TTrain::OnCommand_fmradiotoggle(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS && Train->m_fmradiopresent) - { - Train->m_fmradiopower = !Train->m_fmradiopower; - } -} - -void TTrain::OnCommand_fmradiovolumeincrease(TTrain *Train, command_data const &Command) -{ - // the knob keeps turning for as long as the control is held, the actual movement takes place in the update - Train->m_fmradiovolumechange = (Command.action != GLFW_RELEASE && Train->m_fmradiopresent ? 1 : 0); -} - -void TTrain::OnCommand_fmradiovolumedecrease(TTrain *Train, command_data const &Command) -{ - Train->m_fmradiovolumechange = (Command.action != GLFW_RELEASE && Train->m_fmradiopresent ? -1 : 0); -} - -void TTrain::OnCommand_fmradiovolumeset(TTrain *Train, command_data const &Command) -{ - if (Command.action != GLFW_RELEASE && Train->m_fmradiopresent) - { - Train->m_fmradiovolume = std::clamp(static_cast(Command.param1), 0.f, 1.f); - if (false == Train->m_controlmapper.contains("fmradio_sw:")) - { - // receivers without dedicated switch are switched with the volume knob - Train->m_fmradiopower = Train->m_fmradiovolume > 0.f; - } - } -} - -void TTrain::OnCommand_fmradiotuneincrease(TTrain *Train, command_data const &Command) -{ - Train->m_fmradiotunechange = (Command.action != GLFW_RELEASE && Train->m_fmradiopresent ? 1 : 0); -} - -void TTrain::OnCommand_fmradiotunedecrease(TTrain *Train, command_data const &Command) -{ - Train->m_fmradiotunechange = (Command.action != GLFW_RELEASE && Train->m_fmradiopresent ? -1 : 0); -} - -// sets the receiver to frequency specified in MHz -void TTrain::OnCommand_fmradiotuneset(TTrain *Train, command_data const &Command) -{ - if (Command.action != GLFW_RELEASE && Train->m_fmradiopresent) - { - Train->m_fmradiodial = std::clamp(100.f * (static_cast(Command.param1) - audio::EU07_FMRADIO_BANDSTART) / (audio::EU07_FMRADIO_BANDEND - audio::EU07_FMRADIO_BANDSTART), 0.f, 100.f); - Train->m_fmradiotuned = true; - } -} - -void TTrain::OnCommand_cabchangeforward(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - if (auto const movedirection{1}; false == Train->CabChange(movedirection)) - { - auto const exitdirection{(movedirection > 0 ? end::front : end::rear)}; - if (Train->mvOccupied->Couplers[exitdirection].CouplingFlag.HasAll(Coupling::gangway)) - { - // przejscie do nastepnego pojazdu - auto *targetvehicle = exitdirection == end::front ? Train->DynamicObject->PrevConnected() : Train->DynamicObject->NextConnected(); - targetvehicle->MoverParameters->CabOccupied = Train->mvOccupied->Neighbours[exitdirection].vehicle_end ? -1 : 1; - Train->MoveToVehicle(targetvehicle); - } - } - // HACK: match consist door permit state with the preset in the active cab - if (Train->ggDoorPermitPresetButton.SubModel != nullptr) - { - Train->mvOccupied->ChangeDoorPermitPreset(0); - } - // HACK: update lights state - if (Train->mvOccupied->LightsPosNo > 0) - { - Train->DynamicObject->SetLights(); - } - } -} - -void TTrain::OnCommand_cabchangebackward(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - if (auto const movedirection{-1}; false == Train->CabChange(movedirection)) - { - // current vehicle doesn't extend any farther in this direction, check if we there's one connected we can move to - auto const exitdirection{(movedirection > 0 ? end::front : end::rear)}; - if (Train->mvOccupied->Couplers[exitdirection].CouplingFlag.HasAll(Coupling::gangway)) - { - // przejscie do nastepnego pojazdu - auto *targetvehicle = exitdirection == end::front ? Train->DynamicObject->PrevConnected() : Train->DynamicObject->NextConnected(); - targetvehicle->MoverParameters->CabOccupied = Train->mvOccupied->Neighbours[exitdirection].vehicle_end ? -1 : 1; - Train->MoveToVehicle(targetvehicle); - } - } - // HACK: match consist door permit state with the preset in the active cab - if (Train->ggDoorPermitPresetButton.SubModel != nullptr) - { - Train->mvOccupied->ChangeDoorPermitPreset(0); - } - // HACK: update lights state - if (Train->mvOccupied->LightsPosNo > 0) - { - Train->DynamicObject->SetLights(); - } - } -} - -void TTrain::OnCommand_vehiclemoveforwards(TTrain *Train, const command_data &Command) -{ - if (Command.action == GLFW_RELEASE || !DebugModeFlag) - return; - - Train->DynamicObject->move_set(100.0); -} - -void TTrain::OnCommand_vehiclemovebackwards(TTrain *Train, const command_data &Command) -{ - if (Command.action == GLFW_RELEASE || !DebugModeFlag) - return; - - Train->DynamicObject->move_set(-100.0); -} - -void TTrain::OnCommand_vehicleboost(TTrain *Train, const command_data &Command) -{ - if (Command.action == GLFW_RELEASE || !DebugModeFlag) - return; - - double boost = Command.param1 != 0.0 ? Command.param1 : 2.78; - - if (Train->DynamicObject == nullptr) - { - return; - } - - auto *vehicle{Train->DynamicObject}; - while (vehicle) - { - vehicle->MoverParameters->V += vehicle->DirectionGet() * boost; - vehicle = vehicle->Next(); // pozostałe też - } - vehicle = Train->DynamicObject->Prev(); - while (vehicle) - { - vehicle->MoverParameters->V += vehicle->DirectionGet() * boost; - vehicle = vehicle->Prev(); // w drugą stronę też - } -} - -// cab movement update, fixed step part -void TTrain::UpdateCab() -{ - - // Ra: przesiadka, jeśli AI zmieniło kabinę (a człon?)... - if (DynamicObject->Mechanik // może nie być? - && DynamicObject->Mechanik->AIControllFlag && iCabn != ( // numer kabiny (-1: kabina B) - mvOccupied->CabOccupied == -1 ? 2 : mvOccupied->CabOccupied)) - { - - InitializeCab(mvOccupied->CabOccupied, mvOccupied->TypeName + ".mmd"); - } - iCabn = mvOccupied->CabOccupied == -1 ? 2 : mvOccupied->CabOccupied; -} - -bool TTrain::Update(double const Deltatime) -{ - // train state update - // line breaker: - if (m_linebreakerstate == linebreaker::state::open && true == mvControlled->Mains) - { - // crude way to sync state of the linebreaker with ai-issued commands - m_linebreakerstate = linebreaker::state::closed; - } - if (m_linebreakerstate == linebreaker::state::closed && false == (mvControlled->Mains || mvControlled->dizel_startup)) - { - // crude way to catch cases where the main was knocked out - // because the state of the line breaker isn't changed to match, we need to do it here manually - m_linebreakerstate = linebreaker::state::open; - } - if (is_hold_coil_lever(ggMainOffButton) && hold_coil_lever::cuts_off(ggMainOffButton.GetDesiredValue())) - { - if (true == mvControlled->Mains) - { - // the line breaker was closed with the hold coil lever off, by the AI or through the control cable: - // put the lever back on to match, like the line breaker state above - ggMainOffButton.UpdateValue(0.0); - } - else if (m_linebreakerstate == linebreaker::state::closing) - { - // the hold coil was cut off while the closing button was held, the line breaker won't close on its release - m_linebreakerstate = linebreaker::state::open; - } - } - - if ((ggMainButton.SubModel != nullptr && ggMainButton.GetDesiredValue() > 0.95) || - ggMainOnButton.SubModel != nullptr && ggMainOnButton.GetDesiredValue() > 0.95 || - ggIgnitionKey.GetDesiredValue() > 0.95) - { // HACK: fallback - // keep track of period the line breaker button is held down, to determine when/if circuit closes - if (mvControlled->MainSwitchCheck()) - { - fMainRelayTimer += static_cast(Deltatime); - } - } - else - { - // button isn't down, reset the timer - fMainRelayTimer = 0.0f; - } - if (ggMainOffButton.GetDesiredValue() > 0.95) - { - // if the button disconnecting the line breaker is down prevent the timer from accumulating - fMainRelayTimer = 0.0f; - } - if (m_linebreakerstate == linebreaker::state::open && fMainRelayTimer > mvControlled->InitialCtrlDelay) - { - // wlaczanie WSa z opoznieniem - // mark the line breaker as ready to close; for electric series vehicles with impulse switch the setup is completed on button release - m_linebreakerstate = linebreaker::state::closing; - } - // for diesels and/or vehicles with toggle switch setup we complete the engine start here - // TODO: make it a test for main_on_bt of type push_delayed instead - if (m_linebreakerstate == linebreaker::state::closing && (ggMainOnButton.SubModel == nullptr || mvControlled->EngineType != TEngineType::ElectricSeriesMotor)) - { - // try to finalize state change of the line breaker, set the state based on the outcome - m_linebreakerstate = mvControlled->MainSwitch(true, mvControlled->MainSwitchRange()) ? linebreaker::state::closed : linebreaker::state::open; - } - // the switches of the other vehicles in multiple - update_remote_linebreakers(Deltatime); - // door permits - for (auto idx = 0; idx < 2; ++idx) - { - auto &doorpermittimer{m_doorpermittimers[idx]}; - if (doorpermittimer < 0.f) - { - continue; - } - doorpermittimer -= static_cast(Deltatime); - if (doorpermittimer < 0.f) - { - mvOccupied->OperateDoors(static_cast(idx), true); - } - } - - // train measurement timer - if (trainLenghtMeasureTimer >= 0.f) - { - trainLenghtMeasureTimer -= static_cast(Deltatime); - if (trainLenghtMeasureTimer < 0.f) - trainLenghtMeasureTimer = -1.f; - } - - // battery timer - if (fBatteryTimer >= 0.f) - { - fBatteryTimer -= static_cast(Deltatime); - if (fBatteryTimer < 0.f) - fBatteryTimer = -1.f; - } - - // helper variables - if (DynamicObject->Mechanik != nullptr) - { - m_doors = DynamicObject->Mechanik->IsAnyDoorOpen[side::right] || DynamicObject->Mechanik->IsAnyDoorOpen[side::left]; - m_doorpermits = DynamicObject->Mechanik->IsAnyDoorPermitActive[side::right] || DynamicObject->Mechanik->IsAnyDoorPermitActive[side::left]; - m_doorspermitleft = mvOccupied->Doors.instances[cab_to_end() == end::front ? side::left : side::right].open_permit && - (simulation::Time.data().wSecond % 2 < 1 || mvOccupied->DoorsPermitLightBlinking < 1 || - mvOccupied->DoorsPermitLightBlinking < 2 && DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == end::front ? side::left : side::right] || - (mvOccupied->DoorsPermitLightBlinking < 3 && DynamicObject->Mechanik->IsAnyDoorOnlyOpen[cab_to_end() == end::front ? side::left : side::right])); - m_doorspermitright = mvOccupied->Doors.instances[cab_to_end() == end::front ? side::right : side::left].open_permit && - (simulation::Time.data().wSecond % 2 < 1 || mvOccupied->DoorsPermitLightBlinking < 1 || - mvOccupied->DoorsPermitLightBlinking < 2 && DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == end::front ? side::right : side::left] || - (mvOccupied->DoorsPermitLightBlinking < 3 && DynamicObject->Mechanik->IsAnyDoorOnlyOpen[cab_to_end() == end::front ? side::right : side::left])); - } - m_dirforward = mvControlled->DirActive > 0; - m_dirneutral = mvControlled->DirActive == 0; - m_dirbackward = mvControlled->DirActive < 0; - - // check for received user commands - // NOTE: this is a temporary arrangement, for the transition period from old command setup to the new one - // eventually commands are going to be retrieved directly by the vehicle, filtered through active control stand - // and ultimately executed, provided the stand allows it. - command_data commanddata; - while (simulation::Commands.pop(commanddata, static_cast(command_target::vehicle) | id())) - { - simulation::Blackbox.command(DynamicObject, commanddata.command, commanddata.action, commanddata.param1, commanddata.param2); - - auto lookup = m_commandhandlers.find(commanddata.command); - if (lookup != m_commandhandlers.end()) - { - // debug data - if (commanddata.action == GLFW_PRESS) - { - WriteLog(mvOccupied->Name + " received command: [" + simulation::Commands_descriptions[static_cast(commanddata.command)].name + "]"); - } - // pass the command to the assigned handler - lookup->second(this, commanddata); - } - } - - UpdateCab(); - - // nie blokujemy AI - if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag && (mvOccupied->TrainType == train_type::et40 || mvOccupied->TrainType == train_type::ep05 || mvOccupied->HasCamshaft)) - { - // dla ET40 i EU05 automatyczne cofanie nastawnika - i tak nie będzie to działać dobrze... - // TODO: use deltatime to stabilize speed - /* - if( false == ( - ( input::command == user_command::mastercontrollerset ) - || ( input::command == user_command::mastercontrollerincrease ) - || ( input::command == user_command::mastercontrollerdecrease ) ) ) { - */ - if (false == (m_mastercontrollerinuse || Global.ctrlState)) - { - m_mastercontrollerreturndelay -= static_cast(Deltatime); - if (m_mastercontrollerreturndelay < 0.f) - { - m_mastercontrollerreturndelay = EU07_CONTROLLER_BASERETURNDELAY; - if (mvOccupied->MainCtrlPos > mvOccupied->MainCtrlActualPos) - { - mvOccupied->DecMainCtrl(1); - } - else if (mvOccupied->MainCtrlPos < mvOccupied->MainCtrlActualPos) - { - // Ra 15-01: a to nie miało być tylko cofanie? - mvOccupied->IncMainCtrl(1); - } - } - } - } - - // McZapkie: predkosc wyswietlana na tachometrze brana jest z obrotow kol - auto const maxtacho{3.0}; - - double maxSpeed = mvControlled->Vmax * 1.05; // zachowanie starej logiki jak nie ma definicji max tarczki - if (mvOccupied->maxTachoSpeed != 0) - { - maxSpeed = mvOccupied->maxTachoSpeed; - } - fTachoVelocity = static_cast(std::min(std::abs(11.31 * mvControlled->WheelDiameter * mvControlled->nrot), maxSpeed)); - { // skacze osobna zmienna - float ff = simulation::Time.data().wSecond; // skacze co sekunde - pol sekundy - // pomiar, pol sekundy ustawienie - if (ff != fTachoTimer) // jesli w tej sekundzie nie zmienial - { - if (fTachoVelocity >= 5) // jedzie - fTachoVelocityJump = static_cast(fTachoVelocity + (2.0 - LocalRandom(3) + LocalRandom(3)) * 0.5); - else if (fTachoVelocity < 5 && fTachoVelocity > 1) - fTachoVelocityJump = static_cast(Random(0, 4)); // tu ma sie bujac jak wariat i zatrzymac na jakiejs predkosci - // fTachoVelocityJump = 0; // stoi - fTachoTimer = ff; // juz zmienil - } - } - if (fTachoVelocity > 1) // McZapkie-270503: podkrecanie tachometru - { - // szybciej zacznij stukac - fTachoCount = static_cast(std::min(maxtacho, fTachoCount + Deltatime * 3)); - } - else if (fTachoCount > 0) - { - // schodz powoli - niektore haslery to ze 4 sekundy potrafia stukac - fTachoCount = static_cast(std::max(0.0, fTachoCount - Deltatime * 0.66)); - } - - // Ra 2014-09: napięcia i prądy muszą być ustalone najpierw, bo wysyłane są ewentualnie na PoKeys - if (mvControlled->EngineType != TEngineType::DieselElectric && mvControlled->EngineType != TEngineType::ElectricInductionMotor) - { // Ra 2014-09: czy taki rozdzia? ma sens? - fHVoltage = static_cast(std::max(mvControlled->PantographVoltage, - mvControlled->GetTrainsetHighVoltage())); // Winger czy to nie jest zle? - } - // *mvControlled->Mains); - else - { - fHVoltage = static_cast(mvControlled->EngineVoltage); - } - if (ShowNextCurrent) - { // jeśli pokazywać drugi człon - if (mvSecond) - { // o ile jest ten drugi - fHCurrent[0] = static_cast(mvSecond->ShowCurrent(0) * 1.05); - fHCurrent[1] = static_cast(mvSecond->ShowCurrent(1) * 1.05); - fHCurrent[2] = static_cast(mvSecond->ShowCurrent(2) * 1.05); - fHCurrent[3] = static_cast(mvSecond->ShowCurrent(3) * 1.05); - } - else - { - fHCurrent[0] = 0.0; // gdy nie ma człona - fHCurrent[1] = 0.0; - fHCurrent[2] = 0.0; - fHCurrent[3] = 0.0; - } - } - else - { // normalne pokazywanie - fHCurrent[0] = static_cast(mvControlled->ShowCurrent(0)); - fHCurrent[1] = static_cast(mvControlled->ShowCurrent(1)); - fHCurrent[2] = static_cast(mvControlled->ShowCurrent(2)); - fHCurrent[3] = static_cast(mvControlled->ShowCurrent(3)); - } - - bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; - TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? end::rear : end::front, Coupling::control); - int in = 0; - fEIMParams[0][6] = 0; - iCarNo = 0; - iPowerNo = 0; - iUnitNo = 1; - - for (int i = 0; i < 8; i++) - { - bMains[i] = false; - fCntVol[i] = 0.0f; - bPants[i][0] = false; - bPants[i][1] = false; - bFuse[i] = false; - bBatt[i] = false; - bConv[i] = false; - bComp[i][0] = false; - bComp[i][1] = false; - // bComp[i][2] = false; - // bComp[i][3] = false; - bHeat[i] = false; - } - bCompressors.clear(); - for (int i = 0; i < 20; i++) - { - if (p) - { - fPress[i][0] = static_cast(p->MoverParameters->BrakePress); - fPress[i][1] = static_cast(p->MoverParameters->PipePress); - fPress[i][2] = static_cast(p->MoverParameters->ScndPipePress); - fPress[i][3] = static_cast(p->MoverParameters->CntrlPipePress); - fPress[i][4] = static_cast(p->MoverParameters->Hamulec->GetBRP()); - fPress[i][5] = static_cast((p->MoverParameters->TotalMass - p->MoverParameters->Mred) * 0.001); - fPress[i][6] = static_cast(p->MoverParameters->SpringBrake.SBP); - bBrakes[i][0] = p->MoverParameters->SpringBrake.IsActive; - bBrakes[i][1] = p->MoverParameters->SpringBrake.ShuttOff; - bDoors[i][1] = p->MoverParameters->Doors.instances[side::left].position > 0.f; - bDoors[i][2] = p->MoverParameters->Doors.instances[side::right].position > 0.f; - bDoors[i][3] = p->MoverParameters->Doors.instances[side::left].step_position > 0.f; - bDoors[i][4] = p->MoverParameters->Doors.instances[side::right].step_position > 0.f; - bDoors[i][0] = bDoors[i][1] || bDoors[i][2]; - iDoorNo[i] = p->iAnimType[ANIM_DOORS]; - iUnits[i] = iUnitNo; - cCode[i] = p->MoverParameters->TypeName[p->MoverParameters->TypeName.length() - 1]; - asCarName[i] = p->name(); - if (p->MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) - { - bPants[iUnitNo - 1][end::front] = bPants[iUnitNo - 1][end::front] || p->MoverParameters->Pantographs[end::front].is_active; - bPants[iUnitNo - 1][end::rear] = bPants[iUnitNo - 1][end::rear] || p->MoverParameters->Pantographs[end::rear].is_active; - } - // TBD, TODO: clean up compressor data arrangement? - if (iUnitNo <= 8) - { - bComp[iUnitNo - 1][0] = bComp[iUnitNo - 1][0] || p->MoverParameters->CompressorAllow || p->MoverParameters->CompressorStart == start_t::automatic; - } - if (p->MoverParameters->CompressorSpeed > 0.00001) - { - if (iUnitNo <= 8) - { - bComp[iUnitNo - 1][1] = bComp[iUnitNo - 1][1] || p->MoverParameters->CompressorFlag; - } - bCompressors.emplace_back(p->MoverParameters->CompressorAllow || p->MoverParameters->CompressorStart == start_t::automatic, p->MoverParameters->CompressorFlag, i); - } - bSlip[i] = p->MoverParameters->SlippingWheels; - if (in < 8 && p->MoverParameters->eimc[eimc_p_Pmax] > 1) - { - fEIMParams[1 + in][0] = static_cast(p->MoverParameters->eimv[eimv_Fmax]); - fEIMParams[1 + in][1] = std::max(fEIMParams[1 + in][0], 0.f); - fEIMParams[1 + in][2] = -std::min(fEIMParams[1 + in][0], 0.f); - fEIMParams[1 + in][3] = static_cast(p->MoverParameters->eimv[eimv_Fmax] / std::max(p->MoverParameters->eimv[eimv_Fful], 1.)); - fEIMParams[1 + in][4] = std::max(fEIMParams[1 + in][3], 0.f); - fEIMParams[1 + in][5] = -std::min(fEIMParams[1 + in][3], 0.f); - fEIMParams[1 + in][6] = static_cast(p->MoverParameters->eimv[eimv_If]); - fEIMParams[1 + in][7] = static_cast(p->MoverParameters->eimv[eimv_U]); - fEIMParams[1 + in][8] = static_cast(p->MoverParameters->Itot); // p->MoverParameters->eimv[eimv_Ipoj]; - fEIMParams[1 + in][9] = static_cast(p->MoverParameters->EngineVoltage); - fEIMParams[0][6] += fEIMParams[1 + in][8]; - bMains[in] = p->MoverParameters->Mains; - fCntVol[in] = static_cast(p->MoverParameters->BatteryVoltage); - bFuse[in] = p->MoverParameters->FuseFlag; - bBatt[in] = p->MoverParameters->Battery; - bConv[in] = p->MoverParameters->ConverterFlag; - bHeat[in] = p->MoverParameters->Heating; - // bComp[in][2] = (p->MoverParameters->CompressorAllow || (p->MoverParameters->CompressorStart == start_t::automatic)); - // bComp[in][3] = (p->MoverParameters->CompressorFlag); - in++; - iPowerNo = in; - } - if (in < 8 && (p->MoverParameters->EngineType == TEngineType::DieselEngine || p->MoverParameters->EngineType == TEngineType::DieselElectric)) - { - fDieselParams[1 + in][0] = static_cast(p->MoverParameters->enrot * 60); - fDieselParams[1 + in][1] = static_cast(p->MoverParameters->nrot); - fDieselParams[1 + in][2] = static_cast(p->MoverParameters->RList[p->MoverParameters->MainCtrlPos].R); - fDieselParams[1 + in][3] = static_cast(p->MoverParameters->dizel_fill); - fDieselParams[1 + in][4] = static_cast(p->MoverParameters->RList[p->MoverParameters->MainCtrlPos].Mn); - fDieselParams[1 + in][5] = static_cast(p->MoverParameters->dizel_engage); - fDieselParams[1 + in][6] = p->MoverParameters->dizel_heat.Twy; - fDieselParams[1 + in][7] = p->MoverParameters->OilPump.pressure; - fDieselParams[1 + in][8] = p->MoverParameters->dizel_heat.Ts; - fDieselParams[1 + in][9] = static_cast(p->MoverParameters->hydro_R_Fill); - bMains[in] = p->MoverParameters->Mains; - fCntVol[in] = static_cast(p->MoverParameters->BatteryVoltage); - bFuse[in] = p->MoverParameters->FuseFlag; - bBatt[in] = p->MoverParameters->Battery; - bConv[in] = p->MoverParameters->ConverterFlag; - bHeat[in] = p->MoverParameters->Heating; - in++; - iPowerNo = in; - } - if ((kier ? p->Next(Coupling::permanent) : p->Prev(Coupling::permanent)) != (kier ? p->Next(Coupling::control) : p->Prev(Coupling::control))) - iUnitNo++; - p = kier ? p->Next(Coupling::control) : p->Prev(Coupling::control); - iCarNo = i + 1; - } - else - { - fPress[i][0] = 0; - fPress[i][1] = 0; - fPress[i][2] = 0; - fPress[i][3] = 0; - fPress[i][4] = 0; - fPress[i][5] = 0; - bDoors[i][0] = false; - bDoors[i][1] = false; - bDoors[i][2] = false; - bDoors[i][3] = false; - bDoors[i][4] = false; - bBrakes[i][0] = false; - bBrakes[i][1] = false; - bSlip[i] = false; - iUnits[i] = 0; - cCode[i] = 0; //'0'; - asCarName[i] = ""; - } - } - - // if (mvControlled == mvOccupied) - // fEIMParams[0][3] = mvControlled->eimv[eimv_Fzad]; // procent zadany - // else - // fEIMParams[0][3] = - // mvControlled->eimv[eimv_Fzad] - mvOccupied->LocalBrakeRatio(); // procent zadany - fEIMParams[0][3] = static_cast(mvOccupied->eimic_real); - fEIMParams[0][4] = std::max(fEIMParams[0][3], 0.f); - fEIMParams[0][5] = -std::min(fEIMParams[0][3], 0.f); - fEIMParams[0][1] = static_cast(fEIMParams[0][4] * mvControlled->eimv[eimv_Fful]); - fEIMParams[0][2] = static_cast(fEIMParams[0][5] * mvControlled->eimv[eimv_Fful]); - fEIMParams[0][0] = fEIMParams[0][1] - fEIMParams[0][2]; - fEIMParams[0][7] = 0; - fEIMParams[0][8] = 0; - fEIMParams[0][9] = 0; - - for (int i = in; i < 8; i++) - { - for (int j = 0; j <= 9; j++) - { - fEIMParams[1 + i][j] = 0; - fDieselParams[1 + i][j] = 0; - } - } -#ifdef _WIN32 - if (Global.iFeedbackMode == 4) - { - // wykonywać tylko gdy wyprowadzone na pulpit - // Ra: sterowanie miernikiem: zbiornik główny - Console::ValueSet(0, mvOccupied->Compressor); - // Ra: sterowanie miernikiem: przewód główny - Console::ValueSet(1, mvOccupied->PipePress); - // Ra: sterowanie miernikiem: cylinder hamulcowy - Console::ValueSet(2, mvOccupied->BrakePress); - // woltomierz wysokiego napięcia - Console::ValueSet(3, fHVoltage); - // Ra: sterowanie miernikiem: drugi amperomierz - Console::ValueSet(4, fHCurrent[2]); - // pierwszy amperomierz; dla EZT prąd całkowity - Console::ValueSet(5, fHCurrent[mvControlled->TrainType == train_type::emu ? 0 : 1]); - // Ra: prędkość na pin 43 - wyjście analogowe (to nie jest PWM); skakanie zapewnia mechanika napędu - Console::ValueSet(6, fTachoVelocity); - } -#endif - //------------------ - // hunter-261211: nadmiarowy przetwornicy i ogrzewania - // Ra 15-01: to musi stąd wylecieć - zależności nie mogą być w kabinie - if (mvControlled->ConverterFlag == true) - { - fConverterTimer += static_cast(Deltatime); - if (mvControlled->CompressorFlag == true && mvControlled->CompressorPower == 1 && (mvControlled->EngineType == TEngineType::ElectricSeriesMotor || mvControlled->TrainType == train_type::emu) && - DynamicObject->Controller == Humandriver // hunter-110212: poprawka dla EZT - && false == DynamicObject->Mechanik->AIControllFlag) - { // hunter-091012: poprawka (zmiana warunku z CompressorPower /rozne od 0/ na /rowne 1/) - if (fConverterTimer < fConverterPrzekaznik) - { - mvControlled->ConvOvldFlag = true; - if (mvControlled->TrainType != train_type::emu) - mvControlled->MainSwitch(false, mvControlled->TrainType == train_type::emu ? range_t::unit : range_t::local); - } - else if (fConverterTimer >= fConverterPrzekaznik) - { - // changed switch from always true to take into account state of the compressor switch - mvControlled->CompressorSwitch(mvControlled->CompressorAllow); - } - } - } - else - fConverterTimer = 0; - //------------------ - auto const lowvoltagepower{mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable}; - - // youBy - prad w drugim czlonie: galaz lub calosc - { - TDynamicObject const *tmp{nullptr}; - if (DynamicObject->NextConnected() && mvControlled->Couplers[end::rear].CouplingFlag.HasAll(Coupling::control) && mvOccupied->CabOccupied == 1) - tmp = DynamicObject->NextConnected(); - if (DynamicObject->PrevConnected() && mvControlled->Couplers[end::front].CouplingFlag.HasAll(Coupling::control) && mvOccupied->CabOccupied == -1) - tmp = DynamicObject->PrevConnected(); - if (tmp && tmp->MoverParameters->Power > 0) - { - if (ggI1B.SubModel) - { - ggI1B.UpdateValue(static_cast(tmp->MoverParameters->ShowCurrent(1))); - ggI1B.Update(); - } - if (ggI2B.SubModel) - { - ggI2B.UpdateValue(static_cast(tmp->MoverParameters->ShowCurrent(2))); - ggI2B.Update(); - } - if (ggI3B.SubModel) - { - ggI3B.UpdateValue(static_cast(tmp->MoverParameters->ShowCurrent(3))); - ggI3B.Update(); - } - if (ggItotalB.SubModel) - { - ggItotalB.UpdateValue(static_cast(tmp->MoverParameters->ShowCurrent(0))); - ggItotalB.Update(); - } - if (ggWater1TempB.SubModel) - { - ggWater1TempB.UpdateValue(tmp->MoverParameters->dizel_heat.temperatura1); - ggWater1TempB.Update(); - } - if (ggOilPressB.SubModel) - { - ggOilPressB.UpdateValue(tmp->MoverParameters->OilPump.pressure); - ggOilPressB.Update(); - } - } - } - // McZapkie-300302: zegarek - if (ggClockMInd.SubModel) - { - ggClockSInd.UpdateValue(simulation::Time.data().wSecond); - ggClockSInd.Update(); - ggClockMInd.UpdateValue(simulation::Time.data().wMinute); - ggClockMInd.Update(); - ggClockHInd.UpdateValue(static_cast(simulation::Time.data().wHour + simulation::Time.data().wMinute / 60.0)); - ggClockHInd.Update(); - } - - Cabine[iCabn].Update(lowvoltagepower); // nowy sposób ustawienia animacji - /* - if (ggZbS.SubModel) - { - ggZbS.UpdateValue(mvOccupied->Handle->GetCP()); - ggZbS.Update(); - } - */ - // replacement for the above. TODO: move it to a more suitable place - m_brakehandlecp = mvOccupied->Handle->GetCP(); - - // youBy - napiecie na silnikach - if (ggEngineVoltage.SubModel) - { - if (mvControlled->DynamicBrakeFlag) - { - ggEngineVoltage.UpdateValue(static_cast(std::abs(mvControlled->Im * 5))); - } - else - { - int x; - if (mvControlled->TrainType == train_type::et42 && mvControlled->Imax == mvControlled->ImaxHi) - x = 1; - else - x = 2; - if (mvControlled->RList[mvControlled->MainCtrlActualPos].Mn > 0 && std::abs(mvControlled->Im) > 0) - { - ggEngineVoltage.UpdateValue(static_cast(x * (std::abs(mvControlled->EngineVoltage) - mvControlled->RList[mvControlled->MainCtrlActualPos].R * std::abs(mvControlled->Im)) / - mvControlled->RList[mvControlled->MainCtrlActualPos].Mn)); - } - else - { - ggEngineVoltage.UpdateValue(0); - } - } - ggEngineVoltage.Update(); - } - - // Winger 140404 - woltomierz NN - if (ggLVoltage.SubModel) - { - // NOTE: since we don't have functional converter object, we're faking it here by simple check whether converter is on - // TODO: implement object-based circuits and power systems model so we can have this working more properly - ggLVoltage.UpdateValue(static_cast(std::max(mvOccupied->Power110vIsAvailable ? mvOccupied->NominalBatteryVoltage : 0.0, mvOccupied->Power24vIsAvailable ? mvOccupied->BatteryVoltage : 0.0))); - ggLVoltage.Update(); - } - - if (mvControlled->EngineType == TEngineType::DieselElectric) - { // ustawienie zmiennych dla silnika spalinowego - fEngine[1] = static_cast(mvControlled->ShowEngineRotation(1)); - fEngine[2] = static_cast(mvControlled->ShowEngineRotation(2)); - } - - else if (mvControlled->EngineType == TEngineType::DieselEngine) - { // albo dla innego spalinowego - fEngine[1] = static_cast(mvControlled->ShowEngineRotation(1)); - fEngine[2] = static_cast(mvControlled->ShowEngineRotation(2)); - fEngine[3] = static_cast(mvControlled->ShowEngineRotation(3)); - if (ggMainGearStatus.SubModel) - { - if (mvControlled->Mains) - ggMainGearStatus.UpdateValue(static_cast(1.1 - std::abs(mvControlled->dizel_automaticgearstatus))); - else - ggMainGearStatus.UpdateValue(0.0); - ggMainGearStatus.Update(); - } - if (ggIgnitionKey.SubModel && ggIgnitionKey.GetDesiredValue() == 0.0) - { - ggIgnitionKey.UpdateValue(mvControlled->Mains || mvControlled->dizel_startup || fMainRelayTimer > 0.f || - (ggMainButton.SubModel != nullptr && ggMainButton.GetDesiredValue() > 0.95) || - (ggMainOnButton.SubModel != nullptr && ggMainOnButton.GetDesiredValue() > 0.95)); - } - ggIgnitionKey.Update(); - } - - if (mvControlled->SlippingWheels) - { - // Ra 2014-12: lokomotywy 181/182 dostają SlippingWheels po zahamowaniu powyżej 2.85 bara i buczały - double veldiff = (DynamicObject->GetVelocity() - fTachoVelocity) / mvControlled->Vmax; - // 1% Vmax rezerwy, żeby 181/182 nie buczały po zahamowaniu, ale to proteza - if (veldiff < -0.01 && std::abs(mvControlled->Im) > 10.0) - { - btLampkaPoslizg.Turn(true); - } - } - else - { - btLampkaPoslizg.Turn(false); - } - - // Lampka pracujacej sprezacki - if (mvControlled->CompressorFlag || mvOccupied->CompressorFlag) - btCompressors.Turn(true); - else - btCompressors.Turn(false); - - // Lampka zezwolenia na hamowanie ED - if (mvControlled->EpFuse) - btEDenabled.Turn(true); - else - btEDenabled.Turn(false); - - // Lampka aktywowanej kabiny - if (mvControlled->CabActive != 0) - { - btCabActived.Turn(true); - } - else - { - btCabActived.Turn(false); - } - - if (mvControlled->Battery && mvControlled->CabActive != 0) - btAKLVents.Turn(true); - else - btAKLVents.Turn(false); - - if (true == lowvoltagepower) - { - // McZapkie-141102: SHP i czuwak, TODO: sygnalizacja kabinowa - if (mvOccupied->SecuritySystem.is_vigilance_blinking()) - { - if (fBlinkTimer > fCzuwakBlink) - fBlinkTimer = -fCzuwakBlink; - else - fBlinkTimer += Deltatime; - - btLampkaCzuwaka.Turn(fBlinkTimer > 0); - } - else - { - fBlinkTimer = 0.0; - btLampkaCzuwaka.Turn(false); - } - - btLampkaSHP.Turn(mvOccupied->SecuritySystem.is_cabsignal_blinking()); - btLampkaCzuwakaSHP.Turn(btLampkaSHP.GetValue() || btLampkaCzuwaka.GetValue()); - - btLampkaWylSzybki.Turn(m_linebreakerstate == linebreaker::state::closing || mvControlled->Mains); - btLampkaWylSzybkiOff.Turn(m_linebreakerstate != linebreaker::state::closing && !mvControlled->Mains); - btLampkaMainBreakerReady.Turn(mvControlled->MainsInitTimeCountdown <= 0.0 && m_linebreakerstate != linebreaker::state::closing && !mvControlled->Mains); - btLampkaMainBreakerBlinkingIfReady.Turn(m_linebreakerstate == linebreaker::state::closing || mvControlled->Mains || mvControlled->MainsInitTimeCountdown < 0.0 && simulation::Time.data().wMilliseconds > 500); - - btLampkaPrzetw.Turn(mvOccupied->Power110vIsAvailable); - btLampkaPrzetwOff.Turn(!mvOccupied->Power110vIsAvailable); - btLampkaPrzetwAOff.Turn(!mvControlled->ConverterFlag); - btLampkaNadmPrzetw.Turn(Dynamic()->Mechanik ? Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : mvControlled->ConvOvldFlag); - - btLampkaOpory.Turn(mvControlled->StLinFlag && mvControlled->ResistorsFlagCheck()); - btLampkaBezoporowa.Turn(mvControlled->ResistorsFlagCheck() || mvControlled->MainCtrlActualPos == 0); // do EU04 - btLampkaStyczn.Turn(mvControlled->LineContactorsLampLit()); // mozna prowadzic rozruch - btLampkaPrzekRozn.Turn(!mvControlled->GroundRelay && mvControlled->MainCircuitLampsEnabled()); // relay is off and needs a reset - btLampkaNadmSil.Turn(mvControlled->FuseFlagCheck() && mvControlled->MainCircuitLampsEnabled()); // relay is off and needs a reset - btLampkaUkrotnienie.Turn(mvControlled->Couplers[mvControlled->CabOccupied == 1 ? rear : front].CouplingFlag.HasAll(Coupling::control)); - btLampkaHamPosp.Turn(TestFlag(mvOccupied->Hamulec->GetBrakeStatus(), 1)); // lampka drugiego stopnia hamowania - // TODO: youBy wyciągnąć flagę wysokiego stopnia - btLampkaNadmWent.Turn(mvControlled->RventRot < 5.0 && mvControlled->ResistorsFlagCheck()); // hunter-121211: lampka zanikowo-pradowego wentylatorow - btLampkaWysRozr.Turn(mvControlled->Imax >= mvControlled->ImaxHi); - - btLampkaNapNastHam.Turn(mvControlled->DirActive != 0); // napiecie na nastawniku hamulcowym - btLampkaSprezarka.Turn(mvControlled->CompressorFlag); // mutopsitka dziala - btLampkaSprezarkaOff.Turn(!mvControlled->CompressorFlag); - btLampkaFuelPumpOff.Turn(!mvControlled->FuelPump.is_active); - btLampkaOilPump.Turn(mvControlled->OilPump.is_active); // pre-lubrication pump, goes off once the engine is started - - // boczniki - // Ra: w SU45 boczniki wchodzą na ScndCtrlPos, a nie na ScndCtrlActualPos - // - pokićkał ktoś? - int scp = mvControlled->RList[mvControlled->MainCtrlPos].ScndAct; - scp = scp == 255 ? 0 : scp; // Ra: whatta hella is this? - btLampkaBoczniki.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlActualPos > 0 || scp > 0); - btLampkaBocznik1.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlPos > 0 || mvControlled->ScndCtrlActualPos > 0 || scp > 0); - btLampkaBocznik2.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlPos > 1 || mvControlled->ScndCtrlActualPos > 1 || scp > 1); - btLampkaBocznik3.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlPos > 2 || mvControlled->ScndCtrlActualPos > 2 || scp > 2); - btLampkaBocznik4.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlPos > 3 || mvControlled->ScndCtrlActualPos > 3 || scp > 3); - - // biegi dla motoraka - btLampkaGear1.Turn(mvControlled->ScndCtrlActualPos == 1 && mvControlled->dizel_engagestate > 0); // bieg 1 - btLampkaGear2.Turn(mvControlled->ScndCtrlActualPos == 2 && mvControlled->dizel_engagestate > 0); // bieg 2 - btLampkaHydroLockup.Turn(mvControlled->hydro_TC_Lockup); // zblokowanie skrzyni z silnikiem - - if (mvControlled->Signalling == true) - { - if (mvOccupied->BrakePress >= 1.45f) - { - btLampkaHamowanie1zes.Turn(true); - } - if (mvControlled->BrakePress < 0.75f) - { - btLampkaHamowanie1zes.Turn(false); - } - } - else - { - btLampkaHamowanie1zes.Turn(false); - } - - switch (mvControlled->TrainType) - { - // zależnie od typu lokomotywy - case train_type::emu: - { - btLampkaHamienie.Turn(mvControlled->BrakePress >= 0.2 && mvControlled->Signalling); - break; - } - case train_type::et41: - { - // odhamowanie drugiego członu - if (mvSecond) - { - // bo może komuś przyjść do głowy jeżdżenie jednym członem - btLampkaHamienie.Turn(mvSecond->BrakePress < 0.4); - } - break; - } - default: - { - btLampkaHamienie.Turn(mvOccupied->BrakePress >= 0.1 || mvControlled->DynamicBrakeFlag); - btLampkaBrakingOff.Turn(mvOccupied->BrakePress < 0.1 && !mvControlled->DynamicBrakeFlag); - break; - } - } - // KURS90 - btLampkaMaxSila.Turn(abs(mvControlled->Im) >= 350); - btLampkaPrzekrMaxSila.Turn(abs(mvControlled->Im) >= 450); - btLampkaRadio.Turn(mvOccupied->Radio && mvOccupied->RadioFuse); - btLampkaRadioMessage.Turn(radio_message_played); - btLampkaRadioStop.Turn(mvOccupied->Radio && mvOccupied->RadioFuse && mvOccupied->RadioStopFlag); - btLampkaHamulecReczny.Turn(mvOccupied->ManualBrakePos > 0); - // NBMX wrzesien 2003 - drzwi oraz sygnał odjazdu - if (DynamicObject->Mechanik != nullptr) - { - btLampkaDoorLeft.Turn(DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == end::front ? side::left : side::right]); - btLampkaDoorRight.Turn(DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == end::front ? side::right : side::left]); - } - if (DynamicObject->Mechanik != nullptr) - { - // with DoorClosureSignal in the definition of the cab's vehicle, the door closure signalling (SOD) of the whole - // consist: lit with all doors closed and locked, blinking with them closed but released, dark with a door open. - // without it, the lock of the vehicle's own doors, as before - btLampkaBlokadaDrzwi.Turn(mvOccupied->door_closure_lamp_lit(DynamicObject->Mechanik->DoorClosure, simulation::Time.data().wSecond % 2 < 1)); - } - else - { - btLampkaBlokadaDrzwi.Turn(mvOccupied->Doors.is_locked); - } - btLampkaDoorLockOff.Turn(false == mvOccupied->Doors.lock_enabled); - btLampkaDepartureSignal.Turn(mvControlled->DepartureSignal); - btLampkaNapNastHam.Turn(mvControlled->DirActive != 0 && mvOccupied->EpFuse); // napiecie na nastawniku hamulcowym - - // Wylaczanie lampek kierunku gdy jedziemy - // Feature uruchamiany z fiz z sekcji Ctrl. wpisem HideDirStatusWhenMoving=Yes (domyslnie No) - if (mvOccupied->HideDirStatusWhenMoving && // Czy ta funkcja jest w ogole wlaczona - mvOccupied->Vel > mvOccupied->HideDirStatusSpeed) // Uzaleznienie od predkosci - { - btLampkaForward.Turn(false); - btLampkaBackward.Turn(false); - btLampkaNeutral.Turn(false); - } - else - { - btLampkaForward.Turn(mvControlled->DirActive > 0); // jazda do przodu - btLampkaBackward.Turn(mvControlled->DirActive < 0); // jazda do tyłu - btLampkaNeutral.Turn(mvControlled->DirActive == 0); // kierunek neutral - } - - btLampkaED.Turn(mvControlled->DynamicBrakeFlag); // hamulec ED - btLampkaBrakeProfileG.Turn(TestFlag(mvOccupied->BrakeDelayFlag, bdelay_G)); - btLampkaBrakeProfileP.Turn(TestFlag(mvOccupied->BrakeDelayFlag, bdelay_P)); - btLampkaBrakeProfileR.Turn(TestFlag(mvOccupied->BrakeDelayFlag, bdelay_R)); - btLampkaSpringBrakeActive.Turn(mvOccupied->SpringBrake.IsActive); - btLampkaSpringBrakeInactive.Turn(!mvOccupied->SpringBrake.IsActive); - // light indicators - // NOTE: sides are hardcoded to deal with setups where single cab is equipped with all indicators - btLampkaUpperLight.Turn((mvOccupied->iLights[end::front] & light::headlight_upper) != 0); - btLampkaLeftLight.Turn((mvOccupied->iLights[end::front] & light::headlight_left) != 0); - btLampkaRightLight.Turn((mvOccupied->iLights[end::front] & light::headlight_right) != 0); - btLampkaLeftEndLight.Turn((mvOccupied->iLights[end::front] & light::redmarker_left) != 0); - btLampkaRightEndLight.Turn((mvOccupied->iLights[end::front] & light::redmarker_right) != 0); - btLampkaRearUpperLight.Turn((mvOccupied->iLights[end::rear] & light::headlight_upper) != 0); - btLampkaRearLeftLight.Turn((mvOccupied->iLights[end::rear] & light::headlight_left) != 0); - btLampkaRearRightLight.Turn((mvOccupied->iLights[end::rear] & light::headlight_right) != 0); - btLampkaRearLeftEndLight.Turn((mvOccupied->iLights[end::rear] & light::redmarker_left) != 0); - btLampkaRearRightEndLight.Turn((mvOccupied->iLights[end::rear] & light::redmarker_right) != 0); - // others - btLampkaMalfunction.Turn(mvControlled->dizel_heat.PA); - // overheat indicator lamps - btLampkaOilOverheat.Turn(mvControlled->dizel_heat.oil.is_hot); - btLampkaWaterOverheat.Turn(mvControlled->dizel_heat.water.is_hot); - btLampkaWaterAuxOverheat.Turn(mvControlled->dizel_heat.water_aux.is_hot); - btLampkaEngineOverheat.Turn(mvControlled->dizel_heat.engine_is_hot); - btLampkaMotorBlowers.Turn(mvControlled->MotorBlowers[end::front].is_active && mvControlled->MotorBlowers[end::rear].is_active); - btLampkaCoolingFans.Turn(mvControlled->RventRot > 1.0); - btLampkaLouvresClosed.Turn(mvControlled->LouvresClosed()); - btLampkaTempomat.Turn(mvOccupied->SpeedCtrlUnit.IsActive); - btLampkaDistanceCounter.Turn(m_distancecounter >= 0.f); - // universal devices state indicators - for (auto idx = 0; idx < btUniversals.size(); ++idx) - { - btUniversals[idx].Turn(ggUniversals[idx].GetValue() > 0.5); - } - } - else - { - // wylaczone - btLampkaCzuwaka.Turn(false); - btLampkaSHP.Turn(false); - btLampkaCzuwakaSHP.Turn(false); - btLampkaWylSzybki.Turn(false); - btLampkaWylSzybkiOff.Turn(false); - btLampkaMainBreakerReady.Turn(false); - btLampkaMainBreakerBlinkingIfReady.Turn(false); - btLampkaWysRozr.Turn(false); - btLampkaOpory.Turn(false); - btLampkaStyczn.Turn(false); - btLampkaPrzekRozn.Turn(false); - btLampkaNadmSil.Turn(false); - btLampkaUkrotnienie.Turn(false); - btLampkaHamPosp.Turn(false); - btLampkaBoczniki.Turn(false); - btLampkaBocznik1.Turn(false); - btLampkaBocznik2.Turn(false); - btLampkaBocznik3.Turn(false); - btLampkaBocznik4.Turn(false); - btLampkaGear1.Turn(false); - btLampkaGear2.Turn(false); - btLampkaHydroLockup.Turn(false); - btLampkaNapNastHam.Turn(false); - btLampkaPrzetw.Turn(false); - btLampkaPrzetwOff.Turn(false); - btLampkaPrzetwAOff.Turn(false); - btLampkaNadmPrzetw.Turn(false); - btLampkaSprezarka.Turn(false); - btLampkaSprezarkaOff.Turn(false); - btLampkaFuelPumpOff.Turn(false); - btLampkaOilPump.Turn(false); - btLampkaBezoporowa.Turn(false); - btLampkaHamowanie1zes.Turn(false); - btLampkaHamienie.Turn(false); - btLampkaBrakingOff.Turn(false); - btLampkaBrakeProfileG.Turn(false); - btLampkaBrakeProfileP.Turn(false); - btLampkaBrakeProfileR.Turn(false); - btLampkaSpringBrakeActive.Turn(false); - btLampkaSpringBrakeInactive.Turn(false); - // overheat indicator lamps off - btLampkaOilOverheat.Turn(false); - btLampkaWaterOverheat.Turn(false); - btLampkaWaterAuxOverheat.Turn(false); - btLampkaEngineOverheat.Turn(false); - btLampkaMaxSila.Turn(false); - btLampkaPrzekrMaxSila.Turn(false); - btLampkaRadio.Turn(false); - btLampkaRadioMessage.Turn(false); - btLampkaRadioStop.Turn(false); - btLampkaHamulecReczny.Turn(false); - btLampkaDoorLeft.Turn(false); - btLampkaDoorRight.Turn(false); - btLampkaBlokadaDrzwi.Turn(false); - btLampkaDoorLockOff.Turn(false); - btLampkaDepartureSignal.Turn(false); - btLampkaNapNastHam.Turn(false); - btLampkaForward.Turn(false); - btLampkaBackward.Turn(false); - btLampkaNeutral.Turn(false); - btLampkaED.Turn(false); - // light indicators - btLampkaUpperLight.Turn(false); - btLampkaLeftLight.Turn(false); - btLampkaRightLight.Turn(false); - btLampkaLeftEndLight.Turn(false); - btLampkaRightEndLight.Turn(false); - btLampkaRearUpperLight.Turn(false); - btLampkaRearLeftLight.Turn(false); - btLampkaRearRightLight.Turn(false); - btLampkaRearLeftEndLight.Turn(false); - btLampkaRearRightEndLight.Turn(false); - // others - btLampkaMalfunction.Turn(false); - btLampkaMotorBlowers.Turn(false); - btLampkaCoolingFans.Turn(false); - btLampkaLouvresClosed.Turn(false); - btLampkaTempomat.Turn(false); - btLampkaDistanceCounter.Turn(false); - // universal devices state indicators - for (auto &universal : btUniversals) - { - universal.Turn(false); - } - } - - { // yB - wskazniki drugiego czlonu - TDynamicObject const *tmp{nullptr}; //=mvControlled->mvSecond; //Ra 2014-07: trzeba to jeszcze wyjąć z kabiny... - // Ra 2014-07: no nie ma potrzeby szukać tego w każdej klatce - if (mvControlled->Couplers[1].CouplingFlag.HasAll(Coupling::control) && mvOccupied->CabOccupied > 0) - tmp = DynamicObject->NextConnected(); - if (mvControlled->Couplers[0].CouplingFlag.HasAll(Coupling::control) && mvOccupied->CabOccupied < 0) - tmp = DynamicObject->PrevConnected(); - - if (tmp) - { - if (lowvoltagepower) - { - - auto const *mover{tmp->MoverParameters}; - - btLampkaWylSzybkiB.Turn(mover->Mains); - btLampkaWylSzybkiBOff.Turn(false == mover->Mains - /*&& ( mover->MainsInitTimeCountdown <= 0.0 )*/ - /*&& ( fHVoltage != 0.0 )*/); - - btLampkaOporyB.Turn(mover->ResistorsFlagCheck()); - btLampkaBezoporowaB.Turn(true == mover->ResistorsFlagCheck() || mover->MainCtrlActualPos == 0); // do EU04 - - btLampkaStycznB.Turn(mover->LineContactorsLampLit()); // mozna prowadzic rozruch - // hunter-271211: sygnalizacja poslizgu w pierwszym pojezdzie, gdy wystapi w drugim - if (mover->SlippingWheels) - { - // Ra 2014-12: lokomotywy 181/182 dostają SlippingWheels po zahamowaniu powyżej 2.85 bara i buczały - auto const veldiff{(DynamicObject->GetVelocity() - fTachoVelocity) / mvControlled->Vmax}; - if (veldiff < -0.01) - { - // 1% Vmax rezerwy, żeby 181/182 nie buczały po zahamowaniu, ale to proteza - auto const lightstate{std::abs(mover->Im) > 10.0}; - btLampkaPoslizg.Turn(btLampkaPoslizg.GetValue() || lightstate); - } - } - - btLampkaSprezarkaB.Turn(mover->CompressorFlag); // mutopsitka dziala - btLampkaSprezarkaBOff.Turn(false == mover->CompressorFlag); - if (mvControlled->Signalling == true) - { - if (mover->BrakePress >= 1.45f) - { - btLampkaHamowanie2zes.Turn(true); - } - if (mover->BrakePress < 0.75f) - { - btLampkaHamowanie2zes.Turn(false); - } - } - else - { - btLampkaHamowanie2zes.Turn(false); - } - btLampkaNadmPrzetwB.Turn(mover->ConvOvldFlag); // nadmiarowy przetwornicy? - btLampkaPrzetwB.Turn(mover->ConverterFlag); // zalaczenie przetwornicy - btLampkaPrzetwBOff.Turn(false == mover->ConverterFlag); - btLampkaHVoltageB.Turn(mover->NoVoltRelay && mover->OvervoltageRelay); - btLampkaMalfunctionB.Turn(mover->dizel_heat.PA); - // motor fuse indicator turns on if the fuse was blown in any unit under control - if (mover->Mains) - { - btLampkaNadmSil.Turn(btLampkaNadmSil.GetValue() || mover->FuseFlagCheck()); - } - } - else // wylaczone - { - btLampkaWylSzybkiB.Turn(false); - btLampkaWylSzybkiBOff.Turn(false); - btLampkaOporyB.Turn(false); - btLampkaStycznB.Turn(false); - btLampkaSprezarkaB.Turn(false); - btLampkaSprezarkaBOff.Turn(false); - btLampkaBezoporowaB.Turn(false); - btLampkaHamowanie2zes.Turn(false); - btLampkaNadmPrzetwB.Turn(false); - btLampkaPrzetwB.Turn(false); - btLampkaPrzetwBOff.Turn(false); - btLampkaHVoltageB.Turn(false); - btLampkaMalfunctionB.Turn(false); - } - } - } - // McZapkie-080602: obroty (albo translacje) regulatorow - if (ggJointCtrl.SubModel != nullptr) - { - // joint master controller moves forward to adjust power and backward to adjust brakes - auto const brakerangemultiplier{/* NOTE: scaling disabled as it was conflicting with associating sounds with control positions - ( mvControlled->CoupledCtrl ? - mvControlled->MainCtrlPosNo + mvControlled->ScndCtrlPosNo : - mvControlled->MainCtrlPosNo ) - / static_cast(LocalBrakePosNo) - */ - 1}; - // when SplitEDPneumaticBrake is active the negative range of the joint controller - // represents the dedicated dynamic-brake lever (DBPN steps), not the pneumatic local brake - auto const negativePart{mvControlled->SplitEDPneumaticBrake ? - (mvControlled->DynamicBrakeCtrlPos > 0.0 ? mvControlled->DynamicBrakeCtrlPos * mvControlled->DynamicBrakeCtrlPosNo * -1 * brakerangemultiplier : 0.0) : - mvOccupied->LocalBrakePosA > 0.0 ? mvOccupied->LocalBrakePosA * LocalBrakePosNo * -1 * brakerangemultiplier : - 0.0}; - ggJointCtrl.UpdateValue(negativePart < 0.0 ? static_cast(negativePart) : - mvControlled->CoupledCtrl ? static_cast(double(mvControlled->MainCtrlPos + mvControlled->ScndCtrlPos)) : - static_cast(double(mvControlled->MainCtrlPos)), - dsbNastawnikJazdy); - ggJointCtrl.Update(); - } - if (ggMainCtrl.SubModel != nullptr) - { - -#ifdef _WIN32 - if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag // nie blokujemy AI - && Global.iFeedbackMode == 4 && Global.fCalibrateIn[2][1] != 0.0) - { - - set_master_controller(Console::AnalogCalibrateGet(2) * mvOccupied->MainCtrlPosNo); - mvOccupied->eimic_analog = Console::AnalogCalibrateGet(2); - } -#endif - - if (mvControlled->CoupledCtrl) - { - ggMainCtrl.UpdateValue(static_cast(double(mvControlled->MainCtrlPos + mvControlled->ScndCtrlPos)), dsbNastawnikJazdy); - } - else - { - ggMainCtrl.UpdateValue(static_cast(double(mvControlled->MainCtrlPos)), dsbNastawnikJazdy); - } - ggMainCtrl.Update(); - } - if (ggMainCtrlAct.SubModel != nullptr) - { - ggMainCtrlAct.UpdateValue(main_ctrl_act::position(*mvControlled, ggMainCtrlAct.has_scaletable())); - ggMainCtrlAct.Update(); - } - if (ggScndCtrl.SubModel != nullptr) - { - // Ra: od byte odejmowane boolean i konwertowane potem na double? - if (false == ggScndCtrl.is_push()) - { - ggScndCtrl.UpdateValue(static_cast(double(mvControlled->ScndCtrlPos - (mvControlled->TrainType == train_type::et42 && mvControlled->DynamicBrakeFlag))), dsbNastawnikBocz); - } - ggScndCtrl.Update(); - } - if (ggScndCtrlButton.SubModel != nullptr) - { - if (ggScndCtrlButton.is_toggle()) - { - ggScndCtrlButton.UpdateValue(mvControlled->IsSpeedCtrlEngaged() ? 1.f : 0.f, dsbSwitch); - } - ggScndCtrlButton.Update(lowvoltagepower); - } - if (ggScndCtrlOffButton.SubModel != nullptr) - { - ggScndCtrlOffButton.Update(lowvoltagepower); - } - if (ggDistanceCounterButton.SubModel != nullptr) - { - ggDistanceCounterButton.Update(); - } - if (ggDirKey.SubModel != nullptr) - { - if (mvControlled->TrainType != train_type::emu) - { - ggDirKey.UpdateValue(static_cast(double(mvControlled->DirActive)), dsbReverserKey); - } - else - { - ggDirKey.UpdateValue(static_cast(double(mvControlled->DirActive) + double(mvControlled->Imin == mvControlled->IminHi)), dsbReverserKey); - } - ggDirKey.Update(); - } - if (ggBrakeCtrl.SubModel != nullptr) - { -#ifdef _WIN32 - if (DynamicObject->Mechanik ? (DynamicObject->Mechanik->AIControllFlag ? false : Global.iFeedbackMode == 4 /*|| (Global.bMWDmasterEnable && Global.bMWDBreakEnable)*/) : - false && Global.fCalibrateIn[0][1] != 0.0) // nie blokujemy AI - { // Ra: nie najlepsze miejsce, ale na początek gdzieś to dać trzeba - // Firleju: dlatego kasujemy i zastepujemy funkcją w Console - if (mvOccupied->BrakeHandle == TBrakeHandle::FV4a) - { - double b = Console::AnalogCalibrateGet(0); - b = b * 8.0 - 2.0; - b = safe_clamp(b, -2.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic - ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia - mvOccupied->BrakeLevelSet(b); - } - else if (mvOccupied->BrakeHandle == TBrakeHandle::FVel6) // może można usunąć ograniczenie do FV4a i FVel6? - { - double b = Console::AnalogCalibrateGet(0); - b = b * 7.0 - 1.0; - b = safe_clamp(b, -1.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic - ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia - mvOccupied->BrakeLevelSet(b); - } - else - { - double b = Console::AnalogCalibrateGet(0); - b = b * (mvOccupied->Handle->GetPos(bh_MAX) - mvOccupied->Handle->GetPos(bh_MIN)) + mvOccupied->Handle->GetPos(bh_MIN); - b = safe_clamp(b, mvOccupied->Handle->GetPos(bh_MIN), mvOccupied->Handle->GetPos(bh_MAX)); // przycięcie zmiennej do granic - ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia - mvOccupied->BrakeLevelSet(b); - } - } - else -#endif - { - // else //standardowa prodedura z kranem powiązanym z klawiaturą - // ggBrakeCtrl.UpdateValue(double(mvOccupied->BrakeCtrlPos)); - ggBrakeCtrl.UpdateValue(static_cast(mvOccupied->fBrakeCtrlPos)); - ggBrakeCtrl.Update(); - } - } - - if (ggLocalBrake.SubModel != nullptr) - { -#ifdef _WIN32 - if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag // nie blokujemy AI - && mvOccupied->BrakeLocHandle == TBrakeHandle::FD1 && Global.iFeedbackMode == 4 && Global.fCalibrateIn[0][1] != 0.0) - { - // Ra: nie najlepsze miejsce, ale na początek gdzieś to dać trzeba - // Firleju: dlatego kasujemy i zastepujemy funkcją w Console - auto const b = std::clamp(Console::AnalogCalibrateGet(1), 0.f, 1.f); - mvOccupied->LocalBrakePosA = b; - ggLocalBrake.UpdateValue(b * LocalBrakePosNo); - } - else -#endif - { - // standardowa prodedura z kranem powiązanym z klawiaturą - ggLocalBrake.UpdateValue(static_cast(mvOccupied->LocalBrakePosA * LocalBrakePosNo)); - } - ggLocalBrake.Update(); - } - ggDirForwardButton.Update(lowvoltagepower); - ggDirNeutralButton.Update(lowvoltagepower); - ggDirBackwardButton.Update(lowvoltagepower); - ggAlarmChain.Update(); - ggBrakeProfileCtrl.Update(); - ggBrakeProfileG.Update(); - ggBrakeProfileR.Update(); - ggBrakeOperationModeCtrl.Update(); - ggWiperSw.Update(); - ggMaxCurrentCtrl.UpdateValue(true == mvControlled->ShuntModeAllow ? (true == mvControlled->ShuntMode ? 1.f : 0.f) : mvControlled->MotorOverloadRelayHighThreshold ? 1.f : 0.f); - ggMaxCurrentCtrl.Update(); - ggAutoRelayButton.UpdateValue(mvOccupied->AutoRelayFlag ? 1.f : 0.f); - ggAutoRelayButton.Update(); - // NBMX wrzesien 2003 - drzwi - ggDoorLeftPermitButton.Update(lowvoltagepower); - ggDoorRightPermitButton.Update(lowvoltagepower); - ggDoorPermitPresetButton.Update(lowvoltagepower); - ggDoorLeftButton.Update(lowvoltagepower); - ggDoorRightButton.Update(lowvoltagepower); - ggDoorLeftOnButton.Update(lowvoltagepower); - ggDoorRightOnButton.Update(lowvoltagepower); - ggDoorLeftOffButton.Update(lowvoltagepower); - ggDoorRightOffButton.Update(lowvoltagepower); - ggDoorAllOnButton.Update(lowvoltagepower); - ggDoorAllOffButton.Update(lowvoltagepower); - ggDoorSignallingButton.Update(lowvoltagepower); - ggDoorStepButton.Update(lowvoltagepower); - // NBMX dzwignia sprezarki - ggCompressorButton.Update(); - ggCompressorLocalButton.Update(); - ggCompressorListButton.Update(); - - //--------- - // hunter-080812: poprawka na ogrzewanie w elektrykach - usuniete uzaleznienie od przetwornicy - if (mvControlled->Heating == true && mvControlled->ConvOvldFlag == false) - btLampkaOgrzewanieSkladu.Turn(true); - else - btLampkaOgrzewanieSkladu.Turn(false); - - //---------- - - // lights - auto const lightpower{(InstrumentLightType == 0 ? mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable : - InstrumentLightType == 1 ? mvControlled->Mains : - InstrumentLightType == 2 ? mvOccupied->Power110vIsAvailable : - InstrumentLightType == 3 ? mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable : - InstrumentLightType == 4 ? mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable : - false)}; - InstrumentLightActive = InstrumentLightType == 3 ? true : // TODO: link the light state with the state of the master key - InstrumentLightType == 4 ? mvOccupied->iLights[end::front] != 0 || mvOccupied->iLights[end::rear] != 0 : - InstrumentLightActive; - btInstrumentLight.Turn(InstrumentLightActive && lightpower); - btDashboardLight.Turn(DashboardLightActive && lightpower); - btTimetableLight.Turn(TimetableLightActive && lightpower); - - // guziki: - ggMainOffButton.Update(); - ggMainOnButton.Update(); - ggMainButton.Update(); - for (auto &remotelinebreaker : m_remotelinebreakers) - { - remotelinebreaker.main_switch.Update(); - remotelinebreaker.on_button.Update(); - remotelinebreaker.off_button.Update(); - } - ggSecurityResetButton.Update(); - ggSHPResetButton.Update(); - ggReleaserButton.Update(); - ggSpringBrakeOnButton.Update(); - ggSpringBrakeOffButton.Update(); - ggUniveralBrakeButton1.Update(); - ggUniveralBrakeButton2.Update(); - ggUniveralBrakeButton3.Update(); - ggEPFuseButton.Update(); - ggAntiSlipButton.Update(); - ggSandButton.Update(); - ggAutoSandButton.Update(); - ggFuseButton.Update(); - ggConverterFuseButton.Update(); - ggStLinOffButton.Update(); - ggRadioChannelSelector.Update(); - ggRadioChannelPrevious.Update(); - ggRadioChannelNext.Update(); - ggRadioStop.Update(); - ggRadioTest.Update(); - ggRadioCall1.Update(); - ggRadioCall3.Update(); - ggRadioVolumeSelector.Update(); - ggRadioVolumePrevious.Update(); - ggRadioVolumeNext.Update(); - ggRadioOnButton.Update(); - ggRadioOffButton.Update(); - ggRadioFuseOnButton.Update(); - ggRadioFuseOffButton.Update(); - ggDepartureSignalButton.Update(); - /* - ggPantFrontButton.Update(); - ggPantRearButton.Update(); - ggPantFrontButtonOff.Update(); - ggPantRearButtonOff.Update(); - */ - ggPantAllDownButton.Update(); - ggPantSelectedDownButton.Update(); - ggPantSelectedButton.Update(); - ggPantValvesButton.Update(); - ggPantCompressorButton.Update(); - ggPantCompressorValve.Update(); - - ggPantValvesOff.Update(); - ggPantValvesUpdate.Update(); - - ggLightsButton.Update(); - ggUpperLightButton.Update(); - ggLeftLightButton.Update(); - ggRightLightButton.Update(); - ggLeftEndLightButton.Update(); - ggRightEndLightButton.Update(); - ggModernLightDimSw.Update(); - // hunter-230112 - ggRearUpperLightButton.Update(); - ggRearLeftLightButton.Update(); - ggRearRightLightButton.Update(); - ggRearLeftEndLightButton.Update(); - ggRearRightEndLightButton.Update(); - ggDimHeadlightsButton.Update(); - ggDimHeadlightsButton.Update(); - //------------ - // the converter switches follow the vehicle when something else flips them (the AI driver, the other cab, - // the pressure switch of an EMU), not only when the cab is entered (set_cab_controls()) - if (ggConverterButton.SubModel != nullptr && mvOccupied->ConvSwitchType != "impulse" && mvOccupied->ConverterStart == start_t::manual) - { - ggConverterButton.UpdateValue(mvOccupied->ConverterAllow ? 1.f : 0.f, dsbSwitch); - } - ggConverterButton.Update(); - if (ggConverterLocalButton.SubModel != nullptr) - { - ggConverterLocalButton.UpdateValue(mvOccupied->ConverterAllowLocal ? 1.f : 0.f, dsbSwitch); - } - ggConverterLocalButton.Update(); - ggConverterOffButton.Update(); - ggTrainHeatingButton.Update(); - ggSignallingButton.Update(); - ggNextCurrentButton.Update(); - ggHornButton.Update(); - ggHornLowButton.Update(); - ggHornHighButton.Update(); - ggWhistleButton.Update(); - if (DynamicObject->Mechanik != nullptr) - { - ggHelperButton.UpdateValue(static_cast(DynamicObject->Mechanik->HelperState)); - } - ggHelperButton.Update(); - - ggSpeedControlIncreaseButton.Update(lowvoltagepower); - ggSpeedControlDecreaseButton.Update(lowvoltagepower); - ggSpeedControlPowerIncreaseButton.Update(lowvoltagepower); - ggSpeedControlPowerDecreaseButton.Update(lowvoltagepower); - for (auto &speedctrlbutton : ggSpeedCtrlButtons) - { - speedctrlbutton.Update(lowvoltagepower); - } - for (auto &universal : ggUniversals) - { - universal.Update(); - } - for (auto &item : ggInverterEnableButtons) - { - item.Update(); - } - for (auto &item : ggInverterDisableButtons) - { - item.Update(); - } - for (auto &item : ggInverterToggleButtons) - { - item.Update(); - } - for (auto &relayresetbutton : ggRelayResetButtons) - { - relayresetbutton.Update(); - } - // hunter-091012 - ggInstrumentLightButton.Update(); - ggDashboardLightButton.Update(); - ggTimetableLightButton.Update(); - ggCabLightDimButton.Update(); - ggCompartmentLightsButton.Update(); - ggCompartmentLightsOnButton.Update(); - ggCompartmentLightsOffButton.Update(); - ggBatteryButton.Update(); - ggBatteryOnButton.Update(); - ggBatteryOffButton.Update(); - if (ggCabActivationButton.SubModel != nullptr && ggCabActivationButton.type() != TGaugeType::push) - { - ggCabActivationButton.UpdateValue(mvOccupied->IsCabMaster() ? 1.0 : 0.0); - } - ggCabActivationButton.Update(); - - ggWaterPumpBreakerButton.Update(); - ggWaterPumpButton.Update(); - ggWaterHeaterBreakerButton.Update(); - ggWaterHeaterButton.Update(); - ggWaterCircuitsLinkButton.Update(); - ggFuelPumpButton.Update(); - ggOilPumpButton.Update(); - ggOilFuelPumpButton.Update(); - ggTractionModeSwitch.Update(); - ggGensetButton.Update(); - ggMotorBlowersFrontButton.Update(); - ggMotorBlowersRearButton.Update(); - ggMotorBlowersAllOffButton.Update(); - - // wyprowadzenie sygnałów dla haslera na PoKeys (zaznaczanie na taśmie) - btHaslerBrakes.Turn(mvOccupied->BrakePress > 0.4); // ciśnienie w cylindrach - btHaslerCurrent.Turn(mvOccupied->Im != 0.0); // prąd na silnikach - - // calculate current level of interior illumination - { - // TODO: organize it along with rest of train update in a more sensible arrangement - // Ra: uzeleżnic od napięcia w obwodzie sterowania - // hunter-091012: uzaleznienie jasnosci od przetwornicy - int cabidx{0}; - for (auto &cab : Cabine) - { - - auto const cablightlevel = (cab.bLight == false ? 0.f : cab.bLightDim == true ? 0.4f : 1.f) * (mvOccupied->Power110vIsAvailable ? 1.f : 0.5f); - - if (cab.LightLevel != cablightlevel) - { - cab.LightLevel = cablightlevel; - DynamicObject->set_cab_lights(cabidx, cab.LightLevel); - } - if (cabidx == iCabn) - { - DynamicObject->InteriorLightLevel = cablightlevel; - } - - ++cabidx; - } - } - - // anti slip system activation, maintained while the control button is down - if (mvOccupied->BrakeSystem != TBrakeSystem::ElectroPneumatic && ggAntiSlipButton.GetDesiredValue() > 0.95) - { - mvControlled->AntiSlippingBrake(); - } - // screens - - if (!FreeFlyModeFlag && simulation::Train == this) // don't bother if we're outside - { - update_screens(Deltatime); - update_script_screens(); - } - - // update direction relay - if (prevBatState != mvOccupied->Power24vIsAvailable) - SetupDirectionRelays(); - if (prevDirection != mvOccupied->DirActive) - UpdateDirectionRelays(); - - prevBatState = mvOccupied->Power24vIsAvailable; - prevDirection = mvOccupied->DirActive; - - // sounds - update_sounds(Deltatime); - - return true; //(DynamicObject->Update(dt)); -} // koniec update - -void TTrain::UpdateDirectionRelays() -{ - if (mvOccupied->DirActive < 0 && mvOccupied->Power24vIsAvailable) // wstecz - Dynamic()->sDirectionRelayR.play(); - if (mvOccupied->DirActive == 0 && mvOccupied->Power24vIsAvailable) // neutral - Dynamic()->sDirectionRelayN.play(); - if (mvOccupied->DirActive > 0 && mvOccupied->Power24vIsAvailable) // przod - Dynamic()->sDirectionRelayD.play(); -} - -void TTrain::SetupDirectionRelays() -{ - if (mvOccupied->Power24vIsAvailable) - { - if (mvOccupied->DirActive < 0 && mvOccupied->Power24vIsAvailable) // wstecz - Dynamic()->sDirectionRelayR.play(); - if (mvOccupied->DirActive > 0 && mvOccupied->Power24vIsAvailable) // przod - Dynamic()->sDirectionRelayD.play(); - } - else if (mvOccupied->DirActive != 0) // neutral - Dynamic()->sDirectionRelayN.play(); -} - -void TTrain::update_sounds(double const Deltatime) -{ - - double volume{0.0}; - double const brakevolumescale{0.5}; - - // Winger-160404 - syczenie pomocniczego (luzowanie) - if (m_lastlocalbrakepressure != -1.f) - { - // calculate rate of pressure drop in local brake cylinder, once it's been initialized - auto const brakepressuredifference{mvOccupied->LocBrakePress - m_lastlocalbrakepressure}; - m_localbrakepressurechange = static_cast(std::lerp(m_localbrakepressurechange, 10 * (brakepressuredifference / Deltatime), 0.1f)); - } - m_lastlocalbrakepressure = static_cast(mvOccupied->LocBrakePress); - // local brake, release - if (rsSBHiss) - { - if (m_localbrakepressurechange < -0.05f && mvOccupied->LocBrakePress > mvOccupied->BrakePress - 0.05) - { - rsSBHiss->gain(static_cast(std::clamp(rsSBHiss->m_amplitudeoffset + rsSBHiss->m_amplitudefactor * -m_localbrakepressurechange * 0.05, 0.0, 1.5))); - rsSBHiss->play(sound_flags::exclusive | sound_flags::looping); - } - else - { - // don't stop the sound too abruptly - volume = std::max(0.0, rsSBHiss->gain() - 0.1 * Deltatime); - rsSBHiss->gain(static_cast(volume)); - if (volume < 0.05) - { - rsSBHiss->stop(); - } - } - } - // local brake, engage - if (rsSBHissU) - { - if (m_localbrakepressurechange > 0.05f) - { - rsSBHissU->gain(static_cast(std::clamp(rsSBHissU->m_amplitudeoffset + rsSBHissU->m_amplitudefactor * m_localbrakepressurechange * 0.05, 0.0, 1.5))); - rsSBHissU->play(sound_flags::exclusive | sound_flags::looping); - } - else - { - // don't stop the sound too abruptly - volume = std::max(0.0, rsSBHissU->gain() - 0.1 * Deltatime); - rsSBHissU->gain(static_cast(volume)); - if (volume < 0.05) - { - rsSBHissU->stop(); - } - } - } - - // McZapkie-280302 - syczenie - // TODO: softer volume reduction than plain abrupt stop, perhaps as reusable wrapper? - if (mvOccupied->BrakeHandle == TBrakeHandle::FV4a || mvOccupied->BrakeHandle == TBrakeHandle::FVel6) - { - // upuszczanie z PG - if (rsHiss) - { - fPPress = std::lerp(fPPress, static_cast(mvOccupied->Handle->GetSound(s_fv4a_b)), 0.05f); - volume = fPPress > 0 ? rsHiss->m_amplitudefactor * fPPress * 0.25 + rsHiss->m_amplitudeoffset : 0; - if (volume * brakevolumescale > 0.05) - { - rsHiss->gain(static_cast(volume * brakevolumescale)); - rsHiss->play(sound_flags::exclusive | sound_flags::looping); - } - else - { - rsHiss->stop(); - } - } - // napelnianie PG - if (rsHissU) - { - fNPress = std::lerp(fNPress, static_cast(mvOccupied->Handle->GetSound(s_fv4a_u)), 0.25f); - volume = fNPress > 0 ? rsHissU->m_amplitudefactor * fNPress + rsHissU->m_amplitudeoffset : 0; - if (volume * brakevolumescale > 0.05) - { - rsHissU->gain(static_cast(volume * brakevolumescale)); - rsHissU->play(sound_flags::exclusive | sound_flags::looping); - } - else - { - rsHissU->stop(); - } - } - // upuszczanie przy naglym - if (rsHissE) - { - volume = mvOccupied->Handle->GetSound(s_fv4a_e) * rsHissE->m_amplitudefactor + rsHissE->m_amplitudeoffset; - if (volume * brakevolumescale > 0.05) - { - rsHissE->gain(static_cast(volume * brakevolumescale)); - rsHissE->play(sound_flags::exclusive | sound_flags::looping); - } - else - { - rsHissE->stop(); - } - } - // upuszczanie sterujacego fala - if (rsHissX) - { - volume = mvOccupied->Handle->GetSound(s_fv4a_x) * rsHissX->m_amplitudefactor + rsHissX->m_amplitudeoffset; - if (volume * brakevolumescale > 0.05) - { - rsHissX->gain(static_cast(volume * brakevolumescale)); - rsHissX->play(sound_flags::exclusive | sound_flags::looping); - } - else - { - rsHissX->stop(); - } - } - // upuszczanie z czasowego - if (rsHissT) - { - volume = mvOccupied->Handle->GetSound(s_fv4a_t) * rsHissT->m_amplitudefactor + +rsHissT->m_amplitudeoffset; - if (volume * brakevolumescale > 0.05) - { - rsHissT->gain(static_cast(volume * brakevolumescale)); - rsHissT->play(sound_flags::exclusive | sound_flags::looping); - } - else - { - rsHissT->stop(); - } - } - } - else - { - // jesli nie FV4a - // upuszczanie z PG - if (rsHiss) - { - fPPress = static_cast((4.0f * fPPress + std::max(0.0, mvOccupied->dpMainValve)) / (4.0f + 1.0f)); - volume = fPPress > 0.0f ? 2.0 * rsHiss->m_amplitudefactor * fPPress + rsHiss->m_amplitudeoffset : 0.0; - if (volume > 0.05) - { - rsHiss->gain(static_cast(volume)); - rsHiss->play(sound_flags::exclusive | sound_flags::looping); - } - else - { - rsHiss->stop(); - } - } - // napelnianie PG - if (rsHissU) - { - fNPress = static_cast((4.0f * fNPress + std::min(0.0, mvOccupied->dpMainValve)) / (4.0f + 1.0f)); - volume = fNPress < 0.0f ? -1.0 * rsHissU->m_amplitudefactor * fNPress + rsHissU->m_amplitudeoffset : 0.0; - if (volume > 0.01) - { - rsHissU->gain(static_cast(volume)); - rsHissU->play(sound_flags::exclusive | sound_flags::looping); - } - else - { - rsHissU->stop(); - } - } - } // koniec nie FV4a - - // brakes - if (rsBrake) - { - if (mvOccupied->UnitBrakeForce > 10.0 && mvOccupied->Vel > 0.05) - { - - auto const brakeforceratio{ - std::clamp(mvOccupied->UnitBrakeForce / std::max(1.0, mvOccupied->BrakeForceR(1.0, mvOccupied->Vel) / (mvOccupied->NAxles * std::max(1, mvOccupied->NBpA))), 0.0, 1.0)}; - // HACK: in external view mute the sound rather than stop it, in case there's an opening bookend it'd (re)play on sound restart after returning inside - volume = FreeFlyModeFlag ? 0.0 : rsBrake->m_amplitudeoffset + std::sqrt(brakeforceratio * std::lerp(0.4, 1.0, mvOccupied->Vel / (1 + mvOccupied->Vmax))) * rsBrake->m_amplitudefactor; - rsBrake->pitch(static_cast(rsBrake->m_frequencyoffset + mvOccupied->Vel * rsBrake->m_frequencyfactor)); - rsBrake->gain(static_cast(volume)); - rsBrake->play(sound_flags::exclusive | sound_flags::looping); - } - else - { - rsBrake->stop(); - } - } - - // ambient sound - // since it's typically ticking of the clock we can center it on tachometer or on middle of compartment bounding area - if (rsFadeSound) - { - rsFadeSound->play(sound_flags::exclusive | sound_flags::looping); - } - - if (dsbSlipAlarm) - { - // alarm przy poslizgu dla 181/182 - BOMBARDIER - if (mvControlled->SlippingWheels && DynamicObject->GetVelocity() > 1.0) - { - dsbSlipAlarm->play(sound_flags::exclusive | sound_flags::looping); - } - else - { - dsbSlipAlarm->stop(); - } - } - - // dzwiek wiatru rozbijajacego sie o szyby w kabinie - if (rsWindSound) - { - if (!FreeFlyModeFlag && !Global.CabWindowOpen && DynamicObject->GetVelocity() > 0.5) - update_sounds_resonancenoise(*rsWindSound); - else - rsWindSound->stop(FreeFlyModeFlag); - } - - // dzwiek rezonansu (taki drugi runningnoise w sumie) - if (rsResonanceNoise) - { - if (!FreeFlyModeFlag && !Global.CabWindowOpen && DynamicObject->GetVelocity() > 0.5) - { - - update_sounds_resonancenoise(*rsResonanceNoise); - } - else - rsResonanceNoise->stop(FreeFlyModeFlag); - } - - // szum w czasie jazdy - if (rsRunningNoise) - { - if (false == FreeFlyModeFlag && false == Global.CabWindowOpen && DynamicObject->GetVelocity() > 0.5) - { - - update_sounds_runningnoise(*rsRunningNoise); - } - else - { - // don't play the optional ending sound if the listener switches views - rsRunningNoise->stop(true == FreeFlyModeFlag); - } - } - // hunting oscillation noise - if (rsHuntingNoise) - { - if (false == FreeFlyModeFlag && false == Global.CabWindowOpen && DynamicObject->GetVelocity() > 0.5 && DynamicObject->IsHunting) - { - - update_sounds_runningnoise(*rsHuntingNoise); - // modify calculated sound volume by hunting amount - auto const huntingamount = std::lerp( - 0.0, 1.0, std::clamp((mvOccupied->Vel - DynamicObject->HuntingShake.fadein_begin) / (DynamicObject->HuntingShake.fadein_end - DynamicObject->HuntingShake.fadein_begin), 0.0, 1.0)); - - rsHuntingNoise->gain(static_cast(rsHuntingNoise->gain() * huntingamount)); - } - else - { - // don't play the optional ending sound if the listener switches views - rsHuntingNoise->stop(true == FreeFlyModeFlag); - } - } - // rain sound - if (m_rainsound) - { - if (false == FreeFlyModeFlag && false == Global.CabWindowOpen && Global.Weather == "rain:") - { - if (m_rainsound->is_combined()) - { - m_rainsound->pitch(static_cast(Global.Overcast - 1.0)); - } - m_rainsound->gain(m_rainsound->m_amplitudeoffset + m_rainsound->m_amplitudefactor * 1.f); - m_rainsound->play(sound_flags::exclusive | sound_flags::looping); - } - else - { - m_rainsound->stop(); - } - } - - if (dsbHasler) - { - if (fTachoCount >= 3.f) - { - auto const soundfrequency{(true == dsbHasler->is_combined() ? fTachoVelocity * 0.01 : dsbHasler->m_frequencyoffset + dsbHasler->m_frequencyfactor)}; - dsbHasler->pitch(static_cast(soundfrequency)); - dsbHasler->gain(dsbHasler->m_amplitudeoffset + dsbHasler->m_amplitudefactor); - dsbHasler->play(sound_flags::exclusive | sound_flags::looping); - } - else if (fTachoCount < 1.f) - { - dsbHasler->stop(); - } - } - - // power-reliant sounds - if (mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable) - { - - // buzzer shp - if (mvOccupied->SecuritySystem.is_cabsignal_beeping()) - { - if (dsbBuzzerShp && false == dsbBuzzerShp->is_playing()) - { - dsbBuzzerShp->pitch(dsbBuzzerShp->m_frequencyoffset + dsbBuzzerShp->m_frequencyfactor); - dsbBuzzerShp->gain(dsbBuzzerShp->m_amplitudeoffset + dsbBuzzerShp->m_amplitudefactor); - dsbBuzzerShp->play(sound_flags::looping); - } - } - else - { - if (dsbBuzzerShp && true == dsbBuzzerShp->is_playing()) - { - dsbBuzzerShp->stop(); - } - } - - // McZapkie-141102: SHP i czuwak, TODO: sygnalizacja kabinowa - // hunter-091012: rozdzielenie alarmow - if (mvOccupied->SecuritySystem.is_beeping()) - { - if (dsbBuzzer && false == dsbBuzzer->is_playing()) - { - dsbBuzzer->pitch(dsbBuzzer->m_frequencyoffset + dsbBuzzer->m_frequencyfactor); - dsbBuzzer->gain(dsbBuzzer->m_amplitudeoffset + dsbBuzzer->m_amplitudefactor); - dsbBuzzer->play(sound_flags::looping); -#ifdef _WIN32 - Console::BitsSet(1 << 14); // ustawienie bitu 16 na PoKeys -#endif - } - } - else - { - if (dsbBuzzer && true == dsbBuzzer->is_playing()) - { - dsbBuzzer->stop(); -#ifdef _WIN32 - Console::BitsClear(1 << 14); // ustawienie bitu 16 na PoKeys -#endif - } - } - // distance meter alert - if (m_distancecounterclear) - { - auto const *owner{(DynamicObject->ctOwner != nullptr ? DynamicObject->ctOwner : DynamicObject->Mechanik)}; - if (m_distancecounter > owner->fLength) - { - // play assigned sound if the train travelled its full length since meter activation - // TBD: check all combinations of directions and active cab - m_distancecounter = -1.f; // turn off the meter after its task is done - m_distancecounterclear->pitch(m_distancecounterclear->m_frequencyoffset + m_distancecounterclear->m_frequencyfactor); - m_distancecounterclear->gain(m_distancecounterclear->m_amplitudeoffset + m_distancecounterclear->m_amplitudefactor); - m_distancecounterclear->play(sound_flags::exclusive); - } - } - } - else - { - // stop power-reliant sounds if power is cut - if (dsbBuzzer && true == dsbBuzzer->is_playing()) - { - dsbBuzzer->stop(); -#ifdef _WIN32 - Console::BitsClear(1 << 14); // ustawienie bitu 16 na PoKeys -#endif - } - - if (dsbBuzzerShp && dsbBuzzerShp->is_playing()) - { - dsbBuzzerShp->stop(); - } - - if (m_distancecounterclear) - { - m_distancecounterclear->stop(); - } - } - - update_sounds_radio(); - update_sounds_fmradio(Deltatime); -} - -void TTrain::update_sounds_resonancenoise(sound_source &Sound) const -{ - // frequency calculation - auto const normalizer{mvOccupied->Vmax * 0.01f}; - auto const soundfrequency{Sound.m_frequencyoffset + Sound.m_frequencyfactor * mvOccupied->Vel * normalizer}; - - // volume calculation - auto volume = Sound.m_amplitudeoffset + Sound.m_amplitudefactor * std::lerp(mvOccupied->Vel / (1 + mvOccupied->Vmax), 1.0, 0.5); // scale base volume between 0.5-1.0 - - if (volume > 0.05) - { - Sound.pitch(static_cast(soundfrequency)).gain(static_cast(volume)).play(sound_flags::exclusive | sound_flags::looping); - } - else - { - Sound.stop(); - } -} - -void TTrain::update_sounds_runningnoise(sound_source &Sound) -{ - // frequency calculation - auto const normalizer{(true == Sound.is_combined() ? mvOccupied->Vmax * 0.01f : 1.f)}; - auto const soundfrequency{Sound.m_frequencyoffset + Sound.m_frequencyfactor * mvOccupied->Vel * normalizer}; - - // volume calculation - auto volume = Sound.m_amplitudeoffset + Sound.m_amplitudefactor * std::lerp(mvOccupied->Vel / (1 + mvOccupied->Vmax), 1.0, - 0.5); // scale base volume between 0.5-1.0 - if (std::abs(mvOccupied->nrot) > 0.01) - { - // hamulce wzmagaja halas - auto const brakeforceratio{(std::clamp(mvOccupied->UnitBrakeForce / std::max(1.0, mvOccupied->BrakeForceR(1.0, mvOccupied->Vel) / (mvOccupied->NAxles * std::max(1, mvOccupied->NBpA))), 0.0, 1.0))}; - - volume *= 1 + 0.125 * brakeforceratio; - } - // scale volume by track quality - // TODO: track quality and/or environment factors as separate subroutine - volume *= std::lerp(0.8, 1.2, std::clamp(DynamicObject->MyTrack->iQualityFlag / 20.0, 0.0, 1.0)); - // for single sample sounds muffle the playback at low speeds - if (false == Sound.is_combined()) - { - volume *= std::lerp(0.0, 1.0, std::clamp(mvOccupied->Vel / 25.0, 0.0, 1.0)); - } - - if (volume > 0.05) - { - Sound.pitch(static_cast(soundfrequency)).gain(static_cast(volume)).play(sound_flags::exclusive | sound_flags::looping); - } - else - { - Sound.stop(); - } -} - -void TTrain::update_sounds_radio() -{ - - radio_message_played = false; - if (false == m_radiomessages.empty()) - { - // erase completed radio messages from the list - std::erase_if(m_radiomessages, [](auto const &source) { return false == source.second->is_playing(); }); - } - // adjust audibility of remaining messages based on current radio conditions - auto const radioenabled{mvOccupied->RadioPowered()}; - for (auto const &[messagechannel, messagesound] : m_radiomessages) - { - auto const volume{true == radioenabled && Dynamic()->Mechanik != nullptr && messagechannel == RadioChannel() ? m_radiovolume : 0.0}; - messagesound->gain(static_cast(volume)); - radio_message_played |= true == radioenabled && Dynamic()->Mechanik != nullptr && messagechannel == RadioChannel(); - } - // radiostop - if (m_radiostop) - { - if (true == radioenabled && true == mvOccupied->RadioStopFlag) - { - m_radiostop->play(sound_flags::exclusive | sound_flags::looping); - radio_message_played |= true; - } - else - { - m_radiostop->stop(); - } - } - if (radio_message_played) - { - btLampkaRadioMessage.gain(m_radiovolume); - } -} - -// operates the broadcast radio receiver -void TTrain::update_sounds_fmradio(double const Deltatime) -{ - // NOTE: there's a single receiver in the simulation, it plays in the cab occupied by the user - if (simulation::Train != this || false == m_fmradiopresent || false == Global.fmradio_enabled) - { - return; - } - auto &fmradio{audio::renderer.fmradio()}; - auto const bandwidth{audio::EU07_FMRADIO_BANDEND - audio::EU07_FMRADIO_BANDSTART}; - if (false == m_fmradiotuned) - { - // initially the receiver is tuned to the first station on the list - m_fmradiodial = 100.f * (fmradio.default_frequency() - audio::EU07_FMRADIO_BANDSTART) / bandwidth; - m_fmradiotuned = true; - } - // knobs - if (m_fmradiovolumechange != 0) - { - m_fmradiovolume = std::clamp(m_fmradiovolume + m_fmradiovolumechange * 0.5f * static_cast(Deltatime), 0.f, 1.f); - if (false == m_controlmapper.contains("fmradio_sw:")) - { - // receivers without dedicated switch are switched with the volume knob - m_fmradiopower = m_fmradiovolume > 0.f; - } - } - if (m_fmradiotunechange != 0) - { - // the knob moves slowly at first to allow fine tuning, then speeds up - m_fmradiotunetime += static_cast(Deltatime); - auto const tunerate{std::lerp(0.15f, 2.5f, std::clamp(m_fmradiotunetime * 0.5f, 0.f, 1.f))}; // MHz per second - m_fmradiodial = std::clamp(m_fmradiodial + 100.f * m_fmradiotunechange * tunerate * static_cast(Deltatime) / bandwidth, 0.f, 100.f); - } - else - { - m_fmradiotunetime = 0.f; - } - - fmradio.type(m_fmradiotype); - fmradio.tune(audio::EU07_FMRADIO_BANDSTART + m_fmradiodial * 0.01f * bandwidth); - fmradio.volume(m_fmradiovolume); - fmradio.placement(m_fmradiosound.location(), m_fmradiosound.soundproofing_factor(), m_fmradiosound.range()); - // NOTE: the receiver runs on batteries of its own, so it doesn't care about the state of the vehicle - fmradio.power(m_fmradiopower); -} - -void TTrain::update_screens(double dt) -{ - for (auto &screen : m_screens) - { - if (screen.updatetimecounter >= 0) - screen.updatetimecounter += dt; - - if (screen.updatetimecounter <= screen.updatetime) - continue; - - screen.updatetimecounter = screen.updatetime > 0 ? 0 : -1; - - auto state_dict = GetTrainState(screen.parameters); - - state_dict->insert("touches", *screen.touch_list); - screen.touch_list->clear(); - - Application.request({screen.script, state_dict, screen.rt}); - } -} - -void TTrain::update_script_screens() -{ - auto &queue{Application.screens()}; - for (auto &entry : m_scriptscreens) - { - if (false == queue.due(*entry.screen)) - { - continue; - } - auto input{GetTrainState(entry.parameters)}; - input->insert("touches", *entry.touch_list); - entry.touch_list->clear(); - queue.submit(entry.screen, std::move(input), id()); - } -} - -bool TTrain::find_screen_surface(std::string const &Target, std::string_view const Kind, TSubModel *&Submodel, ITexture *&Texture) const -{ - Submodel = DynamicObject->mdKabina ? DynamicObject->mdKabina->GetFromName(Target) : - DynamicObject->mdLowPolyInt ? DynamicObject->mdLowPolyInt->GetFromName(Target) : - nullptr; - if (Submodel == nullptr) - { - WriteLog(std::format("{}: submodel {} not found - Ignoring screen", Kind, Target)); - return false; - } - auto const material{Submodel->GetMaterial()}; - if (material <= 0) - { - // sub model nie posiada tekstury lub tekstura wymienna - nie obslugiwana - WriteLog(std::format("{}: invalid texture id {} - Ignoring screen", Kind, material)); - return false; - } - - Texture = &GfxRenderer->Texture(GfxRenderer->Material(material)->GetTexture(0)); - return true; -} - -void TTrain::load_script_screen(cParser &Parser, script_language const Language) -{ - script_screen_entry entry; - // the block is read whole even when the script screens are off - entry.config.deserialize(Parser); - if (entry.config.script.empty()) - { - return; - } - if (auto path{script_screens::screen_script_path(DynamicObject->asBaseDir, entry.config.script)}; path.has_value()) - { - entry.config.script = std::move(*path); - } - else - { - ErrorLog(std::format("Bad script screen: \"{}\" leads outside the game's folder", entry.config.script)); - return; - } - - TSubModel *submodel{nullptr}; - ITexture *texture{nullptr}; - auto &queue{Application.screens()}; - if (false == queue.runs(Language)) - { - // the screens of the language are off - return; - } - if (entry.config.target != "none" && - false == find_screen_surface(entry.config.target, Language == script_language::lua ? "Lua Screen" : "WASM Screen", submodel, texture)) - { - return; - } - - entry.screen = queue.acquire({.kind = script_screen_kind::cab, - .language = Language, - .script = entry.config.script, - .key = std::format("cab:{}:{}:{}", DynamicObject->name(), entry.config.target, entry.config.script), - .texture = texture, - .frames = entry.config.frames}); - if (entry.screen == nullptr) - { - return; - } - if (texture != nullptr) - { - // make the surface static so it doesn't get destroyed by garbage collector if the user spends long time outside cab - texture->create(true); - } - if (false == entry.config.parameters.empty()) - { - entry.parameters = dictionary_source(entry.config.parameters); - } - entry.touch_list = std::make_shared>(); - if (submodel != nullptr) - { - submodel->screen_touch_list = entry.touch_list; - } - m_scriptscreens.emplace_back(std::move(entry)); -} - -void TTrain::add_distance(double const Distance) -{ - - auto const meterenabled{m_distancecounter >= 0 && (mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable)}; - - if (true == meterenabled) - { - m_distancecounter += static_cast(Distance * Occupied()->CabOccupied); - } - else - { - m_distancecounter = -1.f; - } -} - -bool TTrain::CabChange(int iDirection) -{ // McZapkie-090902: zmiana kabiny 1->0->2 i z powrotem - if (DynamicObject->Mechanik == nullptr || true == DynamicObject->Mechanik->AIControllFlag) - { - // jeśli prowadzi AI albo jest w innym członie - // jak AI prowadzi, to nie można mu mieszać - if (std::abs(mvOccupied->CabOccupied + iDirection) > 1) - return false; // ewentualna zmiana pojazdu - mvOccupied->CabOccupied += iDirection; - } - else - { // jeśli pojazd prowadzony ręcznie albo wcale (wagon) - mvOccupied->CabDeactivisationAuto(); - if (mvOccupied->ChangeCab(iDirection) && InitializeCab(mvOccupied->CabOccupied, mvOccupied->TypeName + ".mmd")) - { - // zmiana kabiny w ramach tego samego pojazdu - mvOccupied->CabActivisationAuto(); // załączenie rozrządu (wirtualne kabiny) - DynamicObject->Mechanik->DirectionChange(); - return true; // udało się zmienić kabinę - } - // aktywizacja poprzedniej, bo jeszcze nie wiadomo, czy jakiś pojazd jest - mvOccupied->CabActivisationAuto(); - } - return false; // ewentualna zmiana pojazdu -} - -// McZapkie-310302 -// wczytywanie pliku z danymi multimedialnymi (dzwieki, kontrolki, kabiny) -bool TTrain::LoadMMediaFile(std::string const &asFileName) -{ - using enum sound_placement; - using enum sound_type; - // initialize sounds so potential entries from previous vehicle don't stick around - std::unordered_map &, sound_placement, float, sound_type, int, double>> internalsounds = { - {"ctrl:", {dsbNastawnikJazdy, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"ctrlscnd:", {dsbNastawnikBocz, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"reverserkey:", {dsbReverserKey, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"buzzer:", {dsbBuzzer, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"buzzershp:", {dsbBuzzerShp, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"radiostop:", {m_radiostop, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"slipalarm:", {dsbSlipAlarm, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"distancecounter:", {m_distancecounterclear, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"tachoclock:", {dsbHasler, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"switch:", {dsbSwitch, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"pneumaticswitch:", {dsbPneumaticSwitch, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"airsound:", {rsHiss, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, - {"airsound2:", {rsHissU, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, - {"airsound3:", {rsHissE, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, - {"airsound4:", {rsHissX, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, - {"airsound5:", {rsHissT, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, - {"localbrakesound:", {rsSBHiss, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, - {"localbrakesound2:", {rsSBHissU, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, - {"brakesound:", {rsBrake, internal, -1, single, sound_parameters::amplitude | sound_parameters::frequency, 100.0}}, - {"fadesound:", {rsFadeSound, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"runningnoise:", {rsRunningNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, mvOccupied->Vmax}}, - {"resonancenoise:", {rsResonanceNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, mvOccupied->Vmax}}, - {"windsound:", {rsWindSound, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, mvOccupied->Vmax}}, - {"huntingnoise:", {rsHuntingNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, mvOccupied->Vmax}}, - {"rainsound:", {m_rainsound, internal, -1, single, 0, 100.0}}, - }; - for (auto &[soundname, soundsource] : internalsounds) - { - std::get &>(soundsource).reset(); - } - // NOTE: since radiosound is an incomplete template not using std::optional it gets a special treatment - m_radiosound.owner(DynamicObject); - m_fmradiosound.owner(DynamicObject); - CabSoundLocations.clear(); - - cParser parser(asFileName, cParser::buffer_FILE, DynamicObject->asBaseDir, true, std::vector(), true); - // NOTE: yaml-style comments are disabled until conflict in use of # is resolved - // parser.addCommentStyle( "#", "\n" ); - std::string token; - do - { - token = ""; - parser.getTokens(); - parser >> token; - } while (token != "" && token != "internaldata:"); - - if (token == "internaldata:") - { - - do - { - token = ""; - parser.getTokens(); - parser >> token; - - auto lookup{internalsounds.find(token)}; - if (lookup == internalsounds.end()) - { - continue; - } - - auto const soundconfig{lookup->second}; - sound_source sound{std::get(soundconfig), std::get(soundconfig)}; - sound.deserialize(parser, std::get(soundconfig), std::get(soundconfig), static_cast(std::get(soundconfig))); - sound.owner(DynamicObject); - std::get &>(soundconfig) = sound; - } while (token != ""); - - // assign default samples to sound emitters which weren't included in the config file - if (!m_rainsound) - { - sound_source rainsound; - rainsound.deserialize("rainsound_default", single); - rainsound.owner(DynamicObject); - m_rainsound = rainsound; - } - if (!rsSBHiss) - { - // fallback for vehicles without defined local brake hiss sound - rsSBHiss = rsHiss; - } - if (!rsSBHissU) - { - // fallback for vehicles without defined local brake hiss sound - rsSBHissU = rsHissU; - } - if (rsBrake) - { - rsBrake->m_frequencyfactor /= static_cast(1 + mvOccupied->Vmax); - } - if (rsResonanceNoise) - { - rsResonanceNoise->m_frequencyfactor /= static_cast(1 + mvOccupied->Vmax); - } - if (rsWindSound) - { - rsWindSound->m_frequencyfactor /= static_cast(1 + mvOccupied->Vmax); - } - if (rsRunningNoise) - { - rsRunningNoise->m_frequencyfactor /= static_cast(1 + mvOccupied->Vmax); - } - if (rsHuntingNoise) - { - rsHuntingNoise->m_frequencyfactor /= static_cast(1 + mvOccupied->Vmax); - } - } - std::vector>> sounds = { - dsbReverserKey, dsbNastawnikJazdy, dsbNastawnikBocz, dsbSwitch, dsbPneumaticSwitch, rsHiss, rsHissU, rsHissE, rsHissX, rsHissT, rsSBHiss, - rsSBHissU, rsFadeSound, rsRunningNoise, rsResonanceNoise, rsWindSound, rsHuntingNoise, dsbHasler, dsbBuzzer, dsbBuzzerShp, dsbSlipAlarm, m_distancecounterclear, - m_rainsound, m_radiostop}; - for (auto &sound : sounds) - { - if (sound.get()) - { - CabSoundLocations.emplace_back(sound, sound.get()->offset()); - } - } - - return true; -} - -bool TTrain::InitializeCab(int NewCabNo, std::string const &asFileName) -{ - m_controlmapper.clear(); - // clear python screens - m_screens.clear(); - m_scriptscreens.clear(); - // reset sound positions - auto const nullvector{glm::vec3()}; - std::vector>> sounds = { - dsbReverserKey, dsbNastawnikJazdy, dsbNastawnikBocz, dsbSwitch, dsbPneumaticSwitch, rsHiss, rsHissU, rsHissE, rsHissX, rsHissT, rsSBHiss, - rsSBHissU, rsFadeSound, rsRunningNoise, rsResonanceNoise, rsWindSound, rsHuntingNoise, dsbHasler, dsbBuzzer, dsbBuzzerShp, dsbSlipAlarm, m_distancecounterclear, - m_rainsound, m_radiostop}; - for (auto const &sound : sounds) - { - if (sound.get()) - { - sound.get()->offset(nullvector); - } - } - m_radiosound.offset(nullvector); - m_fmradiosound.offset(nullvector); - m_fmradiopresent = false; - for (auto const &[soundsource, soundoffset] : CabSoundLocations) - { - if (soundsource.get() && soundsource.get()->offset() == nullvector) - { - soundsource.get()->offset(soundoffset); - } - } - // reset view angles - pMechViewAngle = {0.0, 0.0}; - - is_cab_initialized = true; // the attempt may fail, but it's the attempt that counts - - bool parse = false; - int cabindex = 0; - DynamicObject->mdKabina = nullptr; // likwidacja wskaźnika na dotychczasową kabinę - switch (NewCabNo) - { // ustalenie numeru kabiny do wczytania - case -1: - cabindex = 2; - break; - case 1: - cabindex = 1; - break; - case 0: - cabindex = 0; - break; - default: - break; - } - iCabn = cabindex; - - std::string cabstr("cab" + std::to_string(cabindex) + "definition:"); - - cParser parser(asFileName, cParser::buffer_FILE, DynamicObject->asBaseDir, true, std::vector(), true); - // NOTE: yaml-style comments are disabled until conflict in use of # is resolved - // parser.addCommentStyle( "#", "\n" ); - std::string token; - do - { - // szukanie kabiny - token = ""; - parser.getTokens(); - parser >> token; - } while (token != "" && token != cabstr); - - if (token == cabstr) - { - // jeśli znaleziony wpis kabiny - Cabine[cabindex].Load(parser); - // NOTE: the position and angle definitions depend on strict entry order - // TODO: refactor into more flexible arrangement - parser.getTokens(); - parser >> token; - if (token == std::string("driver" + std::to_string(cabindex) + "angle:")) - { - // camera view angle - parser.getTokens(2, false); - // angle is specified in degrees but internally stored in radians - glm::vec2 viewangle; - parser >> viewangle.y // yaw first, then pitch - >> viewangle.x; - pMechViewAngle = glm::radians(viewangle); - - Global.pCamera.Angle.x = pMechViewAngle.x; - Global.pCamera.Angle.y = pMechViewAngle.y; - - parser.getTokens(); - parser >> token; - } - if (token == std::string("driver" + std::to_string(cabindex) + "pos:")) - { - // pozycja poczatkowa maszynisty - parser.getTokens(3, false); - parser >> pMechOffset.x >> pMechOffset.y >> pMechOffset.z; - pMechSittingPosition = pMechOffset; - - parser.getTokens(); - parser >> token; - } - // ABu: pozycja siedzaca mechanika - if (token == std::string("driver" + std::to_string(cabindex) + "sitpos:")) - { - // ABu 180404 pozycja siedzaca maszynisty - parser.getTokens(3, false); - parser >> pMechSittingPosition.x >> pMechSittingPosition.y >> pMechSittingPosition.z; - - parser.getTokens(); - parser >> token; - } - // else parse=false; - do - { - if (parse == true) - { - token = ""; - parser.getTokens(); - parser >> token; - } - else - { - parse = true; - } - // inicjacja kabiny - // Ra 2014-08: zmieniamy zasady - zamiast przypisywać submodel do - // istniejących obiektów animujących - // będziemy teraz uaktywniać obiekty animujące z tablicy i podawać im - // submodel oraz wskaźnik na parametr - if (token == std::string("cab" + std::to_string(cabindex) + "model:")) - { - // model kabiny - parser.getTokens(); - parser >> token; - std::ranges::replace(token, '\\', '/'); - if (token != "none") - { - // bieżąca sciezka do tekstur to dynamic/... - Global.asCurrentTexturePath = DynamicObject->asBaseDir; - // szukaj kabinę jako oddzielny model - // name can contain leading slash, erase it to avoid creation of double slashes when the name is combined with current directory - replace_slashes(token); - erase_leading_slashes(token); - if (token[0] == '/') - { - token.erase(0, 1); - } - TModel3d *kabina = TModelsManager::GetModel(DynamicObject->asBaseDir + token, true, true, Global.network_servers.empty() && !Global.network_client ? 0 : id()); - // z powrotem defaultowa sciezka do tekstur - Global.asCurrentTexturePath = paths::textures; - // if (DynamicObject->mdKabina!=k) - if (kabina != nullptr) - { - DynamicObject->mdKabina = kabina; // nowa kabina - } - //(mdKabina) może zostać to samo po przejściu do innego członu bez - // zmiany kabiny, przy powrocie musi być wiązanie ponowne - // else - // break; //wyjście z pętli, bo model zostaje bez zmian - } - else if (cabindex == 1) - { - // model tylko, gdy nie ma kabiny 1 - // McZapkie-170103: szukaj elementy kabiny w glownym modelu - DynamicObject->mdKabina = DynamicObject->mdModel; - } - clear_cab_controls(); - } - /* - if (nullptr == DynamicObject->mdKabina) - { - // don't bother with other parts until the cab is initialised - continue; - } - */ - else if (true == initialize_gauge(parser, token, cabindex)) - { - // matched the token, grab the next one - continue; - } - else if (true == initialize_button(parser, token, cabindex)) - { - // matched the token, grab the next one - continue; - } - // TODO: add "pydestination:" - else if (token == "pyscreen:") - { - screen_entry screen; - screen.deserialize(parser); - if (false == screen.script.empty() && substr_path(screen.script).empty()) - { - screen.script = DynamicObject->asBaseDir + screen.script; - } - - ITexture *tex = nullptr; - TSubModel *submodel = nullptr; - if (screen.target != "none") - { - if (false == find_screen_surface(screen.target, "Python Screen", submodel, tex)) - { - continue; - } - } - else - { - // TODO: fix leak - tex = ITexture::null_texture(); - tex->make_stub(); - } - - tex->create(true); // make the surface static so it doesn't get destroyed by garbage - // collector if the user spends long time outside cab - // TBD, TODO: keep texture handles around, so we can undo the static switch when the - // user changes cabs? - auto rt = std::make_shared(); - rt->shared_tex = tex; - - // record renderer and material binding for future update requests - m_screens.emplace_back(screen); - m_screens.back().rt = rt; - - m_screens.back().touch_list = std::make_shared>(); - if (submodel) - submodel->screen_touch_list = m_screens.back().touch_list; - - if (Global.python_displaywindows) - m_screens.back().viewer = std::make_unique(rt, m_screens.back().touch_list, m_screens.back().script); - } - else if (token == "luascreen:") - { - load_script_screen(parser, script_language::lua); - } - else if (token == "wasmscreen:") - { - load_script_screen(parser, script_language::wasm); - } - else if (token == "pyscreenupdatetime:") - { - parser.getTokens(); - parser >> ScreenUpdateRate; - } - else if (token == "fmradio:") - { - // broadcast radio receiver, the parameter selects character of its sound - std::string fmradiotype; - parser.getTokens(); - parser >> fmradiotype; - m_fmradiotype = (fmradiotype == "wooden" ? audio::fmradio_type::wooden : audio::fmradio_type::cheap); - m_fmradiopresent = true; - } - else if (token == "fmradiospeaker:") - { - // submodel marking location of the receiver speaker, the sound is emitted from there - std::string speakername; - parser.getTokens(); - parser >> speakername; - TSubModel *speaker{nullptr}; - for (auto const *source : {DynamicObject->mdKabina, DynamicObject->mdLowPolyInt}) - { - if (source != nullptr && (speaker = source->GetFromName(speakername)) != nullptr) - { - break; - } - } - if (speaker != nullptr) - { - m_fmradiosound.offset(speaker->offset(1.f)); - } - else - { - ErrorLog("Bad config: failed to locate fm radio speaker submodel \"" + speakername + "\"", logtype::model); - } - m_fmradiopresent = true; - } - // btLampkaUnknown`"unknown",mdKabina,false); - } while (token != "" - // TODO: enable full per-cab deserialization when/if .mmd files get proper per-cab switch configuration - // && ( token != "cab1definition:" ) - // && ( token != "cab2definition:" ) - && token != "cab0definition:"); - for (auto &screen : m_screens) - { - if (screen.updatetime > 0) - { - screen.updatetime = std::max((int)screen.updatetime, Global.PythonScreenUpdateRate) * 0.001; - } - if (screen.updatetime == 0) - { - screen.updatetime = std::max(Global.PythonScreenUpdateRate, ScreenUpdateRate) * 0.001; - } - if (screen.updatetime < -1) - { - screen.updatetime = -screen.updatetime * 0.001; - } - } - } - else - { - return false; - } - /* - if (DynamicObject->mdKabina) - { - */ - // configure placement of sound emitters which aren't bound with any device model, and weren't placed manually - auto const caboffset{glm::dvec3{(Cabine[cabindex].CabPos1 + Cabine[cabindex].CabPos2) * 0.5f} + glm::dvec3{0, 1, 0}}; - // NOTE: since radiosound is an incomplete template not using std::optional it gets a special treatment - if (m_radiosound.offset() == nullvector) - { - m_radiosound.offset(btLampkaRadio.model_offset()); - } - if (m_radiosound.offset() == nullvector) - { - m_radiosound.offset(caboffset); - } - if (m_fmradiosound.offset() == nullvector) - { - m_fmradiosound.offset(caboffset); - } - if (m_fmradiopresent && false == m_fmradiopower && m_controlmapper.contains("fmradiovolume_sw:") && false == m_controlmapper.contains("fmradio_sw:")) - { - // receivers without dedicated switch are switched with the volume knob, so it has to start at the off position - m_fmradiovolume = 0.f; - } - std::vector>, glm::vec3>> soundlocations = { - {dsbReverserKey, ggDirKey.model_offset()}, - {dsbNastawnikJazdy, ggJointCtrl.model_offset()}, - {dsbNastawnikJazdy, ggMainCtrl.model_offset()}, // NOTE: fallback for vehicles without universal controller - {dsbNastawnikBocz, ggScndCtrl.model_offset()}, - {dsbSwitch, caboffset}, - {dsbPneumaticSwitch, caboffset}, - {rsHiss, ggBrakeCtrl.model_offset()}, - {rsHissU, ggBrakeCtrl.model_offset()}, - {rsHissE, ggBrakeCtrl.model_offset()}, - {rsHissX, ggBrakeCtrl.model_offset()}, - {rsHissT, ggBrakeCtrl.model_offset()}, - {rsSBHiss, ggLocalBrake.model_offset()}, - {rsSBHiss, ggBrakeCtrl.model_offset()}, // NOTE: fallback if the local brake model can't be located - {rsSBHissU, ggLocalBrake.model_offset()}, - {rsSBHissU, ggBrakeCtrl.model_offset()}, // NOTE: fallback if the local brake model can't be located - {rsFadeSound, caboffset}, - {rsRunningNoise, caboffset}, - {rsResonanceNoise, caboffset}, - {rsWindSound, caboffset}, - {rsHuntingNoise, caboffset}, - {dsbHasler, caboffset}, - {dsbBuzzer, btLampkaCzuwaka.model_offset()}, - {dsbBuzzerShp, btLampkaCzuwaka.model_offset()}, - {dsbSlipAlarm, caboffset}, - {m_distancecounterclear, btLampkaCzuwaka.model_offset()}, - {m_rainsound, caboffset}, - {m_radiostop, m_radiosound.offset()}, - }; - for (auto const &[soundsource, soundoffset] : soundlocations) - { - if (soundsource.get() && soundsource.get()->offset() == nullvector) - { - soundsource.get()->offset(soundoffset); - } - } - // second pass, in case some items received no positioning due to missing submodels etc - for (auto const &[soundsource, soundoffset] : soundlocations) - { - if (soundsource.get() && soundsource.get()->offset() == nullvector) - { - soundsource.get()->offset(caboffset); - } - } - - if (DynamicObject->mdKabina) - { - DynamicObject->mdKabina->Init(); // obrócenie modelu oraz optymalizacja, również zapisanie binarnego - // the vehicle has a cab, a player is in it: the odometer store keeps the vehicle also when its type has no - // driver's brake valve (eu07/maszyna#72) - DynamicObject->MoverParameters->Odometer.shown = true; - } - - set_cab_controls(NewCabNo < 0 ? 2 : NewCabNo); - - // set pantograpths (hujhujhuj) - change_pantograph_selection(0); - - /* - return true; -} -return (token == "none"); -*/ - return true; -} - -glm::dvec3 TTrain::MirrorPosition(bool lewe) -{ // zwraca współrzędne widoku kamery z lusterka - auto const shiftdirection{(lewe ? -1 : 1) * (iCabn == 2 ? 1 : -1)}; - - return DynamicObject->mMatrix * - glm::dvec4(mvOccupied->Dim.W * (0.5 * shiftdirection) + 0.2 * shiftdirection, 1.5 + Cabine[iCabn].CabPos1.y, std::lerp(Cabine[iCabn].CabPos1.z, Cabine[iCabn].CabPos2.z, 0.5), 1.0); -}; - -void TTrain::DynamicSet(TDynamicObject *d) -{ // taka proteza: chcę podłączyć - // kabinę EN57 bezpośrednio z - // silnikowym, aby nie robić tego - // przez ukrotnienie - // drugi silnikowy i tak musi być ukrotniony, podobnie jak kolejna jednostka - // problem się robi ze światłami, które będą zapalane w silnikowym, ale muszą - // świecić się w rozrządczych - // dla EZT światła czołowe będą "zapalane w silnikowym", ale widziane z - // rozrządczych - // również wczytywanie MMD powinno dotyczyć aktualnego członu - // problematyczna może być kwestia wybranej kabiny (w silnikowym...) - // jeśli silnikowy będzie zapięty odwrotnie (tzn. -1), to i tak powinno - // jeździć dobrze - // również hamowanie wykonuje się zaworem w członie, a nie w silnikowym... - DynamicObject = d; // jedyne miejsce zmiany - mvControlled = d ? DynamicObject->MoverParameters : nullptr; // albo silnikowy w EZT - mvOccupied = mvControlled; - - if (DynamicObject == nullptr) - { - return; - } - - mvControlled = DynamicObject->FindPowered()->MoverParameters; - mvSecond = nullptr; // gdyby się nic nie znalazło - if (mvOccupied->Power > 1.0) // dwuczłonowe lub ukrotnienia, żeby nie szukać każdorazowo - { - if (mvOccupied->Couplers[1].Connected != nullptr && mvOccupied->Couplers[1].AllowedFlag.HasAny(Coupling::control)) - { // gdy jest człon od sprzęgu 1, a sprzęg łączony - // warsztatowo (powiedzmy) - if (mvOccupied->Couplers[1].Connected->Power > 1.0) // ten drugi ma moc - mvSecond = mvOccupied->Couplers[1].Connected; // wskaźnik na drugiego - } - else if (mvOccupied->Couplers[0].Connected != nullptr && mvOccupied->Couplers[0].AllowedFlag.HasAny(Coupling::control)) - { // gdy jest człon od sprzęgu 0, a sprzęg łączony - // warsztatowo (powiedzmy) - if (mvOccupied->Couplers[0].Connected->Power > 1.0) // ale ten drugi ma moc - mvSecond = mvOccupied->Couplers[0].Connected; // wskaźnik na drugiego - } - } - // cache nearest unit equipped with pantographs - { - auto *lookup{DynamicObject->FindPantographCarrier()}; - // HACK: set pointer to existing vehicle to avoid error checking all over the place - mvPantographUnit = lookup != nullptr ? lookup->MoverParameters : mvControlled; - } -}; - -void TTrain::MoveToVehicle(TDynamicObject *target) -{ - // > Ra: to nie może być tak robione, to zbytnia proteza jest - // indeed, too much hacks... - // TODO: cleanup - TTrain *target_train = simulation::Trains.find(target->name()); - if (target_train) - { - // let's try to destroy this TTrain and move to already existing one - - if (!Dynamic()->Mechanik || !Dynamic()->Mechanik->AIControllFlag) - { - // tylko jeśli ręcznie prowadzony - // jeśli prowadzi AI, to mu nie robimy dywersji! - Occupied()->CabDeactivisation(); - Occupied()->CabOccupied = 0; - Occupied()->BrakeLevelSet(Occupied()->Handle->GetPos(bh_NP)); // rozwala sterowanie hamulcem GF 04-2016 - Occupied()->MainCtrlPos = Occupied()->MainCtrlNoPowerPos(); - Occupied()->ScndCtrlPos = 0; - Dynamic()->MechInside = false; - Dynamic()->Controller = AIdriver; - - Dynamic()->bDisplayCab = false; - Dynamic()->ABuSetModelShake({}); - - if (Dynamic()->Mechanik) - Dynamic()->Mechanik->MoveTo(target); - - target_train->Occupied()->LimPipePress = target_train->Occupied()->PipePress; - target_train->Occupied()->CabActivisationAuto(true); // załączenie rozrządu (wirtualne kabiny) - target_train->Dynamic()->MechInside = true; - if (target_train->Dynamic()->Mechanik) - { - target_train->Dynamic()->Controller = target_train->Dynamic()->Mechanik->AIControllFlag; - target_train->Dynamic()->Mechanik->DirectionChange(); - } - else - { - target_train->Dynamic()->Controller = Humandriver; - } - } - else - { - target_train->Dynamic()->bDisplayCab = false; - target_train->Dynamic()->ABuSetModelShake({}); - } - - target_train->Dynamic()->ABuSetModelShake({}); // zerowanie przesunięcia przed powrotem? - - // potentially move player - if (simulation::Train == this) - { - simulation::Train = target_train; - // our local driver may potentially be in external view mode, in which case we shouldn't activate cab visualization - target_train->Dynamic()->bDisplayCab |= !FreeFlyModeFlag; - } - - // delete this TTrain - pending_delete = true; - } - else - { - // move this TTrain to other dynamic - - // remove TTrain from global list, we're going to change dynamic anyway - simulation::Trains.detach(Dynamic()->name()); - - if (!Dynamic()->Mechanik || !Dynamic()->Mechanik->AIControllFlag) - { - // tylko jeśli ręcznie prowadzony - // jeśli prowadzi AI, to mu nie robimy dywersji! - - Occupied()->CabDeactivisation(); - Occupied()->CabOccupied = 0; - Occupied()->BrakeLevelSet(Occupied()->Handle->GetPos(bh_NP)); // rozwala sterowanie hamulcem GF 04-2016 - Occupied()->MainCtrlPos = Occupied()->MainCtrlNoPowerPos(); - Occupied()->ScndCtrlPos = 0; - Dynamic()->MechInside = false; - Dynamic()->Controller = AIdriver; - - Dynamic()->bDisplayCab = false; - Dynamic()->ABuSetModelShake({}); - - if (Dynamic()->Mechanik) - Dynamic()->Mechanik->MoveTo(target); - - DynamicSet(target); - - Dynamic()->MechInside = true; - if (Dynamic()->Mechanik) - { - Dynamic()->Controller = Dynamic()->Mechanik->AIControllFlag; - Dynamic()->Mechanik->DirectionChange(); - } - else - { - Dynamic()->Controller = Humandriver; - } - - Occupied()->LimPipePress = Occupied()->PipePress; - Occupied()->CabActivisationAuto(true); // załączenie rozrządu (wirtualne kabiny) - } - else - { - Dynamic()->bDisplayCab = false; - Dynamic()->ABuSetModelShake({}); - - DynamicSet(target); - } - - { - auto const filename{Occupied()->TypeName + ".mmd"}; - LoadMMediaFile(filename); - InitializeCab(Occupied()->CabActive, filename); - } - - Dynamic()->ABuSetModelShake({}); // zerowanie przesunięcia przed powrotem? - - if (simulation::Train == this) - { - // our local driver may potentially be in external view mode, in which case we shouldn't activate cab visualization - Dynamic()->bDisplayCab |= !FreeFlyModeFlag; - } - - // add it back with updated dynamic name - simulation::Trains.insert(this); - } -} - -// checks whether specified point is within boundaries of the active cab -bool TTrain::point_inside(glm::dvec3 const Point) const -{ - - return Point.x >= Cabine[iCabn].CabPos1.x && Point.x <= Cabine[iCabn].CabPos2.x && Point.y >= Cabine[iCabn].CabPos1.y + 0.5 && Point.y <= Cabine[iCabn].CabPos2.y + 1.8 && - Point.z >= Cabine[iCabn].CabPos1.z && Point.z <= Cabine[iCabn].CabPos2.z; -} - -glm::dvec3 TTrain::clamp_inside(glm::dvec3 const &Point) const -{ - - if (DebugModeFlag) - { - return Point; - } - - // the bounds come from the .mmd as written, and some cabs have them reversed (the B cars of SA134 and 21xM, - // ET40, 754...); std::clamp is undefined for those and on MSVC makes the camera jump between the two bounds - // every frame, as its result is fed back here. safe_clamp keeps the camera on the upper bound, as 26.05 did - return {safe_clamp(Point.x, (double)Cabine[iCabn].CabPos1.x, (double)Cabine[iCabn].CabPos2.x), safe_clamp(Point.y, (double)Cabine[iCabn].CabPos1.y + 0.5, (double)Cabine[iCabn].CabPos2.y + 1.8), - safe_clamp(Point.z, (double)Cabine[iCabn].CabPos1.z, (double)Cabine[iCabn].CabPos2.z)}; -} - -const TTrain::screenentry_sequence &TTrain::get_screens() -{ - update_screens(Timer::GetDeltaTime()); - return m_screens; -} - -void TTrain::radio_message(sound_source *Message, int const Channel) -{ - - if (auto const soundrange{Message->range()}; soundrange > 0 && glm::length2(Message->location() - glm::dvec3{DynamicObject->GetPosition()}) > sq(soundrange)) - { - // skip message playback if the receiver is outside of the emitter's range - return; - } - // NOTE: we initiate playback of all sounds in range, in case the user switches on the radio or tunes to the right channel mid-play - m_radiomessages.emplace_back(Channel, std::make_shared(m_radiosound)); - // assign sound to the template and play it - auto &message = *m_radiomessages.back().second.get(); - auto const radioenabled{mvOccupied->RadioPowered()}; - auto const volume{true == radioenabled && Dynamic()->Mechanik != nullptr && Channel == RadioChannel() ? 1.0 : 0.0}; - message.copy_sounds(*Message).gain(static_cast(volume)).play(); -} - -// clears state of all cabin controls -void TTrain::clear_cab_controls() -{ - // indicators exposed to custom control devices - btLampkaSHP.Clear(0); - btLampkaCzuwaka.Clear(1); - btLampkaOpory.Clear(2); - btLampkaWylSzybki.Clear(3); - btLampkaNadmSil.Clear(4); - btLampkaStyczn.Clear(5); - btLampkaPoslizg.Clear(6); - btLampkaNadmPrzetw.Clear(mvControlled->TrainType == train_type::emu ? -1 : 7); // EN57 nie ma tej lampki - btLampkaPrzetwOff.Clear(mvControlled->TrainType == train_type::emu ? 7 : -1); // za to ma tę - btLampkaNadmSpr.Clear(8); - btLampkaNadmWent.Clear(9); - btLampkaWysRozr.Clear(mvControlled->TrainType == train_type::et22 ? -1 : 10); // ET22 nie ma tej lampki - btLampkaOgrzewanieSkladu.Clear(11); - // overheat indicator lamps - btLampkaOilOverheat.Clear(-1); - btLampkaWaterOverheat.Clear(-1); - btLampkaWaterAuxOverheat.Clear(-1); - btLampkaEngineOverheat.Clear(-1); - btHaslerBrakes.Clear(12); // ciśnienie w cylindrach do odbijania na haslerze - btHaslerCurrent.Clear(13); // prąd na silnikach do odbijania na haslerze - // Numer 14 jest używany dla buczka SHP w update_sounds() - // Jeśli ustawiamy nową wartość dla PoKeys wolna jest 15 - - // other cab controls - // TODO: arrange in more readable manner, and eventually refactor - ggJointCtrl.Clear(); - ggMainCtrl.Clear(); - ggMainCtrlAct.Clear(); - ggScndCtrl.Clear(); - ggScndCtrlButton.Clear(); - ggScndCtrlOffButton.Clear(); - ggDistanceCounterButton.Clear(); - ggDirKey.Clear(); - ggDirForwardButton.Clear(); - ggDirNeutralButton.Clear(); - ggDirBackwardButton.Clear(); - ggBrakeCtrl.Clear(); - ggLocalBrake.Clear(); - ggAlarmChain.Clear(); - ggBrakeProfileCtrl.Clear(); - ggBrakeProfileG.Clear(); - ggBrakeProfileR.Clear(); - ggBrakeOperationModeCtrl.Clear(); - ggWiperSw.Clear(); - ggMaxCurrentCtrl.Clear(); - ggAutoRelayButton.Clear(); - ggMainOffButton.Clear(); - ggMainOnButton.Clear(); - for (auto &remotelinebreaker : m_remotelinebreakers) - { - remotelinebreaker.main_switch.Clear(); - remotelinebreaker.on_button.Clear(); - remotelinebreaker.off_button.Clear(); - remotelinebreaker.held_without_switch = false; - } - ggSecurityResetButton.Clear(); - ggSHPResetButton.Clear(); - ggReleaserButton.Clear(); - ggSpringBrakeOnButton.Clear(); - ggSpringBrakeOffButton.Clear(); - ggUniveralBrakeButton1.Clear(); - ggUniveralBrakeButton2.Clear(); - ggUniveralBrakeButton3.Clear(); - ggEPFuseButton.Clear(); - ggSandButton.Clear(); - ggAutoSandButton.Clear(); - ggAntiSlipButton.Clear(); - ggHornButton.Clear(); - ggHornLowButton.Clear(); - ggHornHighButton.Clear(); - ggWhistleButton.Clear(); - ggHelperButton.Clear(); - ggNextCurrentButton.Clear(); - ggSpeedControlIncreaseButton.Clear(); - ggSpeedControlDecreaseButton.Clear(); - ggSpeedControlPowerIncreaseButton.Clear(); - ggSpeedControlPowerDecreaseButton.Clear(); - for (auto &speedctrlbutton : ggSpeedCtrlButtons) - { - speedctrlbutton.Clear(); - } - for (auto &universal : ggUniversals) - { - universal.Clear(); - } - for (auto &item : ggInverterEnableButtons) - { - item.Clear(); - } - for (auto &item : ggInverterDisableButtons) - { - item.Clear(); - } - for (auto &item : ggInverterToggleButtons) - { - item.Clear(); - } - for (auto &relayresetbutton : ggRelayResetButtons) - { - relayresetbutton.Clear(); - } - ggInstrumentLightButton.Clear(); - ggDashboardLightButton.Clear(); - ggTimetableLightButton.Clear(); - // hunter-091012 - ggCabLightDimButton.Clear(); - ggCompartmentLightsButton.Clear(); - ggCompartmentLightsOnButton.Clear(); - ggCompartmentLightsOffButton.Clear(); - ggBatteryButton.Clear(); - ggBatteryOnButton.Clear(); - ggBatteryOffButton.Clear(); - ggCabActivationButton.Clear(); - //------- - ggFuseButton.Clear(); - ggConverterFuseButton.Clear(); - ggStLinOffButton.Clear(); - ggRadioChannelSelector.Clear(); - ggRadioChannelPrevious.Clear(); - ggRadioChannelNext.Clear(); - ggRadioStop.Clear(); - ggRadioTest.Clear(); - ggRadioCall1.Clear(); - ggRadioCall3.Clear(); - ggRadioVolumeSelector.Clear(); - ggRadioVolumePrevious.Clear(); - ggRadioVolumeNext.Clear(); - ggRadioOnButton.Clear(); - ggRadioOffButton.Clear(); - ggRadioFuseOnButton.Clear(); - ggRadioFuseOffButton.Clear(); - ggDoorLeftPermitButton.Clear(); - ggDoorRightPermitButton.Clear(); - ggDoorPermitPresetButton.Clear(); - ggDoorLeftButton.Clear(); - ggDoorRightButton.Clear(); - ggDoorLeftOnButton.Clear(); - ggDoorRightOnButton.Clear(); - ggDoorLeftOffButton.Clear(); - ggDoorRightOffButton.Clear(); - ggDoorAllOnButton.Clear(); - ggDoorAllOffButton.Clear(); - ggTrainHeatingButton.Clear(); - ggSignallingButton.Clear(); - ggDoorSignallingButton.Clear(); - ggDoorStepButton.Clear(); - ggDepartureSignalButton.Clear(); - ggCompressorButton.Clear(); - ggCompressorLocalButton.Clear(); - ggConverterButton.Clear(); - ggConverterOffButton.Clear(); - ggConverterLocalButton.Clear(); - ggMainButton.Clear(); - /* - ggPantFrontButton.Clear(); - ggPantRearButton.Clear(); - ggPantFrontButtonOff.Clear(); - ggPantRearButtonOff.Clear(); - */ - ggPantAllDownButton.Clear(); - ggPantSelectedButton.Clear(); - ggPantSelectedDownButton.Clear(); - ggPantValvesButton.Clear(); - ggPantCompressorButton.Clear(); - ggPantCompressorValve.Clear(); - - ggPantValvesOff.Clear(); - ggPantValvesUpdate.Clear(); - - ggI1B.Clear(); - ggI2B.Clear(); - ggI3B.Clear(); - ggItotalB.Clear(); - ggOilPressB.Clear(); - ggWater1TempB.Clear(); - - ggClockSInd.Clear(); - ggClockMInd.Clear(); - ggClockHInd.Clear(); - ggEngineVoltage.Clear(); - ggLVoltage.Clear(); - ggMainGearStatus.Clear(); - ggIgnitionKey.Clear(); - - ggWaterPumpBreakerButton.Clear(); - ggWaterPumpButton.Clear(); - ggWaterHeaterBreakerButton.Clear(); - ggWaterHeaterButton.Clear(); - ggWaterCircuitsLinkButton.Clear(); - ggFuelPumpButton.Clear(); - ggOilPumpButton.Clear(); - ggOilFuelPumpButton.Clear(); - ggTractionModeSwitch.Clear(); - ggGensetButton.Clear(); - ggMotorBlowersFrontButton.Clear(); - ggMotorBlowersRearButton.Clear(); - ggMotorBlowersAllOffButton.Clear(); - - btLampkaPrzetw.Clear(); - btLampkaPrzetwB.Clear(); - btLampkaPrzetwBOff.Clear(); - btLampkaPrzetwAOff.Clear(); - btLampkaPrzekRozn.Clear(); - btLampkaPrzekRoznPom.Clear(); - btLampkaUkrotnienie.Clear(); - btLampkaHamPosp.Clear(); - btLampkaWylSzybkiOff.Clear(); - btLampkaWylSzybkiB.Clear(); - btLampkaWylSzybkiBOff.Clear(); - btLampkaMainBreakerReady.Clear(); - btLampkaMainBreakerBlinkingIfReady.Clear(); - btLampkaBezoporowa.Clear(); - btLampkaBezoporowaB.Clear(); - btLampkaMaxSila.Clear(); - btLampkaPrzekrMaxSila.Clear(); - btLampkaRadio.Clear(); - btLampkaRadioMessage.Clear(); - btLampkaRadioStop.Clear(); - btLampkaHamulecReczny.Clear(); - btLampkaBlokadaDrzwi.Clear(); - btLampkaDoorLockOff.Clear(); - for (auto &universal : btUniversals) - { - universal.Clear(); - } - btInstrumentLight.Clear(); - btDashboardLight.Clear(); - btTimetableLight.Clear(); - btLampkaWentZaluzje.Clear(); - btLampkaDoorLeft.Clear(); - btLampkaDoorRight.Clear(); - btLampkaDepartureSignal.Clear(); - btLampkaRezerwa.Clear(); - btLampkaBoczniki.Clear(); - btLampkaBocznik1.Clear(); - btLampkaBocznik2.Clear(); - btLampkaBocznik3.Clear(); - btLampkaBocznik4.Clear(); - btLampkaGear1.Clear(); - btLampkaGear2.Clear(); - btLampkaHydroLockup.Clear(); - btLampkaRadiotelefon.Clear(); - btLampkaHamienie.Clear(); - btLampkaBrakingOff.Clear(); - btLampkaED.Clear(); - btLampkaBrakeProfileG.Clear(); - btLampkaBrakeProfileP.Clear(); - btLampkaBrakeProfileR.Clear(); - btLampkaSpringBrakeActive.Clear(); - btLampkaSpringBrakeInactive.Clear(); - btLampkaSprezarka.Clear(); - btLampkaSprezarkaB.Clear(); - btLampkaSprezarkaOff.Clear(); - btLampkaSprezarkaBOff.Clear(); - btLampkaFuelPumpOff.Clear(); - btLampkaOilPump.Clear(); - btLampkaNapNastHam.Clear(); - btLampkaOporyB.Clear(); - btLampkaStycznB.Clear(); - btLampkaHamowanie1zes.Clear(); - btLampkaHamowanie2zes.Clear(); - btLampkaNadmPrzetwB.Clear(); - btLampkaHVoltageB.Clear(); - btLampkaForward.Clear(); - btLampkaBackward.Clear(); - btLampkaNeutral.Clear(); - // light indicators - btLampkaUpperLight.Clear(); - btLampkaLeftLight.Clear(); - btLampkaRightLight.Clear(); - btLampkaLeftEndLight.Clear(); - btLampkaRightEndLight.Clear(); - btLampkaRearUpperLight.Clear(); - btLampkaRearLeftLight.Clear(); - btLampkaRearRightLight.Clear(); - btLampkaRearLeftEndLight.Clear(); - btLampkaRearRightEndLight.Clear(); - // others - btLampkaMalfunction.Clear(); - btLampkaMalfunctionB.Clear(); - btLampkaMotorBlowers.Clear(); - btLampkaCoolingFans.Clear(); - btLampkaLouvresClosed.Clear(); - btLampkaTempomat.Clear(); - btLampkaDistanceCounter.Clear(); - - ggLeftLightButton.Clear(); - ggRightLightButton.Clear(); - ggUpperLightButton.Clear(); - ggDimHeadlightsButton.Clear(); - ggModernLightDimSw.Clear(); - ggLeftEndLightButton.Clear(); - ggRightEndLightButton.Clear(); - ggLightsButton.Clear(); - ggCompressorListButton.Clear(); - // hunter-230112 - ggRearLeftLightButton.Clear(); - ggRearRightLightButton.Clear(); - ggRearUpperLightButton.Clear(); - ggRearLeftEndLightButton.Clear(); - ggRearRightEndLightButton.Clear(); -} - -// NOTE: we can get rid of this function once we have per-cab persistent state -void TTrain::set_cab_controls(int const Cab) -{ - // switches - // battery - ggBatteryButton.PutValue(ggBatteryButton.type() == TGaugeType::push ? 0.5f : mvOccupied->Power24vIsAvailable ? 1.f : 0.f); - // activation - ggCabActivationButton.PutValue(ggCabActivationButton.type() == TGaugeType::push ? 0.5f : mvOccupied->IsCabMaster() ? 1.f : 0.f); - // line breaker - if (ggMainButton.SubModel != nullptr) - { // instead of single main button there can be on/off pair - ggMainButton.PutValue(ggMainButton.type() == TGaugeType::push ? 0.5f : m_linebreakerstate != linebreaker::state::open ? 1.f : 0.f); - } - // line breakers of the other vehicles in multiple - for (std::size_t index = 0; index < m_remotelinebreakers.size(); ++index) - { - auto &mainswitch{m_remotelinebreakers[index].main_switch}; - if (mainswitch.SubModel == nullptr) - { - continue; - } - if (mainswitch.type() == TGaugeType::push) - { - mainswitch.PutValue(0.5f); - continue; - } - auto const *engine{remote_engine(index)}; - mainswitch.PutValue(engine != nullptr && engine_start::remote_switch::is_running(*engine) ? 1.f : 0.f); - } - - if (ggModernLightDimSw.SubModel != nullptr) - { - mvOccupied->modernDimmerPosition = mvOccupied->modernDimmerDefaultPosition; - ggModernLightDimSw.PutValue(static_cast(mvOccupied->modernDimmerDefaultPosition)); - } - - // Init separate buttons - if (ggPantValvesUpdate.SubModel != nullptr) - { - ggPantValvesUpdate.PutValue(0.f); - } - if (ggPantValvesOff.SubModel != nullptr) - { - ggPantValvesOff.PutValue(0.f); - } - - // motor connectors - ggStLinOffButton.PutValue(mvControlled->StLinSwitchOff ? 1.f : 0.f); - // radio - ggRadioChannelSelector.PutValue(static_cast((Dynamic()->Mechanik ? Dynamic()->Mechanik->iRadioChannel : 1) - 1)); - // pantographs - /* - if( mvOccupied->PantSwitchType != "impulse" ) { - if( ggPantFrontButton.SubModel ) { - ggPantFrontButton.PutValue( - ( mvControlled->Pantographs[end::front].valve.is_enabled ? - 1.f : - 0.f ) ); - } - if( ggPantFrontButtonOff.SubModel ) { - ggPantFrontButtonOff.PutValue( - ( mvControlled->Pantographs[end::front].valve.is_disabled ? - 1.f : - 0.f ) ); - } - } - if( mvOccupied->PantSwitchType != "impulse" ) { - if( ggPantRearButton.SubModel ) { - ggPantRearButton.PutValue( - ( mvControlled->Pantographs[end::rear].valve.is_enabled ? - 1.f : - 0.f ) ); - } - if( ggPantRearButtonOff.SubModel ) { - ggPantRearButtonOff.PutValue( - ( mvControlled->Pantographs[end::rear].valve.is_disabled ? - 1.f : - 0.f ) ); - } - } - */ - // front/end pantograph selection is relative to occupied cab - if (ggPantSelectedButton.type() == TGaugeType::toggle) - { - ggPantSelectedButton.PutValue(mvPantographUnit->PantsValve.is_enabled ? 1.f : 0.f); - } - else - { - if (false == m_controlmapper.contains("pantselectedoff_sw:")) - { - // single impulse switch arrangement, with neutral position mid-way - ggPantSelectedButton.PutValue(0.5f); - } - } - if (ggPantSelectedDownButton.type() == TGaugeType::toggle) - { - ggPantSelectedDownButton.PutValue(mvPantographUnit->PantsValve.is_disabled ? 1.f : 0.f); - } - - ggPantValvesButton.PutValue(0.5f); - - // auxiliary compressor - ggPantCompressorValve.PutValue(mvControlled->bPantKurek3 ? 0.f : // default setting is pantographs connected with primary tank - 1.f); - ggPantCompressorButton.PutValue(mvPantographUnit->PantCompFlag ? 1.f : 0.f); - // converter - if (mvOccupied->ConvSwitchType != "impulse") - { - ggConverterButton.PutValue(mvOccupied->ConverterAllow ? 1.f : 0.f); - } - ggConverterLocalButton.PutValue(mvOccupied->ConverterAllowLocal ? 1.f : 0.f); - // compressor - ggCompressorButton.PutValue(mvControlled->CompressorAllow ? 1.f : 0.f); - ggCompressorLocalButton.PutValue(mvControlled->CompressorAllowLocal ? 1.f : 0.f); - ggCompressorListButton.PutValue(static_cast(mvOccupied->CompressorListPos - 1)); - // motor overload relay threshold / shunt mode - ggMaxCurrentCtrl.PutValue(true == mvControlled->ShuntModeAllow ? (true == mvControlled->ShuntMode ? 1.f : 0.f) : mvControlled->MotorOverloadRelayHighThreshold ? 1.f : 0.f); - // automatic relays (AutoRelay) - ggAutoRelayButton.PutValue(mvOccupied->AutoRelayFlag ? 1.f : 0.f); - // lights - ggLightsButton.PutValue(static_cast(mvOccupied->LightsPos - 1)); - - auto const vehicleend{cab_to_end(Cab)}; - - if ((mvOccupied->iLights[vehicleend] & light::headlight_left) != 0) - { - ggLeftLightButton.PutValue(1.f); - } - if ((mvOccupied->iLights[vehicleend] & light::headlight_right) != 0) - { - ggRightLightButton.PutValue(1.f); - } - if ((mvOccupied->iLights[vehicleend] & light::headlight_upper) != 0) - { - ggUpperLightButton.PutValue(1.f); - } - if ((mvOccupied->iLights[vehicleend] & light::redmarker_left) != 0) - { - if (ggLeftEndLightButton.SubModel != nullptr) - { - ggLeftEndLightButton.PutValue(1.f); - } - else - { - ggLeftLightButton.PutValue(-1.f); - } - } - if ((mvOccupied->iLights[vehicleend] & light::redmarker_right) != 0) - { - if (ggRightEndLightButton.SubModel != nullptr) - { - ggRightEndLightButton.PutValue(1.f); - } - else - { - ggRightLightButton.PutValue(-1.f); - } - } - if (1 == DynamicObject->MoverParameters->modernDimmerPosition) - { - ggDimHeadlightsButton.PutValue(static_cast(DynamicObject->MoverParameters->modernDimmerPosition)); - } - // cab lights - if (true == Cabine[Cab].bLightDim) - { - ggCabLightDimButton.PutValue(1.f); - } - // compartment lights - ggCompartmentLightsButton.PutValue(ggCompartmentLightsButton.type() == TGaugeType::push ? 0.5f : mvOccupied->CompartmentLights.is_enabled ? 1.f : 0.f); - // instrument lights - ggInstrumentLightButton.PutValue(InstrumentLightActive ? 1.f : 0.f); - ggDashboardLightButton.PutValue(DashboardLightActive ? 1.f : 0.f); - ggTimetableLightButton.PutValue(TimetableLightActive ? 1.f : 0.f); - // doors permits - if (false == ggDoorLeftPermitButton.is_push()) - { - ggDoorLeftPermitButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == end::front ? side::left : side::right].open_permit ? 1.f : 0.f); - } - if (false == ggDoorRightPermitButton.is_push()) - { - ggDoorRightPermitButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == end::front ? side::right : side::left].open_permit ? 1.f : 0.f); - } - ggDoorPermitPresetButton.PutValue(static_cast(mvOccupied->Doors.permit_preset)); - // door controls - ggDoorLeftButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == end::front ? side::left : side::right].is_closed ? 0.f : 1.f); - ggDoorRightButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == end::front ? side::right : side::left].is_closed ? 0.f : 1.f); - // door lock - ggDoorSignallingButton.PutValue(mvOccupied->Doors.lock_enabled ? 1.f : 0.f); - // door step - if (false == ggDoorStepButton.is_push()) - { - ggDoorStepButton.PutValue(mvOccupied->Doors.step_enabled ? 1.f : 0.f); - } - // heating - if (false == ggTrainHeatingButton.is_push() && false == mvOccupied->HeatingSwitchImpulse) - { - ggTrainHeatingButton.PutValue(mvControlled->Heating ? 1.f : 0.f); - } - // brake acting time - if (ggBrakeProfileCtrl.SubModel != nullptr) - { - ggBrakeProfileCtrl.PutValue((mvOccupied->BrakeDelayFlag & bdelay_R) != 0 ? 2.f : static_cast(mvOccupied->BrakeDelayFlag - 1)); - } - if (ggBrakeProfileG.SubModel != nullptr) - { - ggBrakeProfileG.PutValue(mvOccupied->BrakeDelayFlag == bdelay_G ? 1.f : 0.f); - } - if (ggBrakeProfileR.SubModel != nullptr) - { - ggBrakeProfileR.PutValue((mvOccupied->BrakeDelayFlag & bdelay_R) != 0 ? 1.f : 0.f); - } - - if (ggWiperSw.SubModel != nullptr) - { - ggWiperSw.PutValue(static_cast(mvOccupied->wiperSwitchPos)); - } - - if (ggBrakeOperationModeCtrl.SubModel != nullptr) - { - ggBrakeOperationModeCtrl.PutValue(mvOccupied->BrakeOpModeFlag > 0 ? static_cast(std::log2(mvOccupied->BrakeOpModeFlag)) : 0); - } - // alarm chain - ggAlarmChain.PutValue(mvControlled->AlarmChainFlag ? 1.f : 0.f); - // brake signalling - ggSignallingButton.PutValue(mvControlled->Signalling ? 1.f : 0.f); - // multiple-unit current indicator source - ggNextCurrentButton.PutValue(ShowNextCurrent ? 1.f : 0.f); - // water pump - ggWaterPumpBreakerButton.PutValue(mvControlled->WaterPump.breaker ? 1.f : 0.f); - if (ggWaterPumpButton.type() != TGaugeType::push) - { - ggWaterPumpButton.PutValue(mvControlled->WaterPump.is_enabled ? 1.f : 0.f); - } - // water heater - ggWaterHeaterBreakerButton.PutValue(mvControlled->WaterHeater.breaker ? 1.f : 0.f); - ggWaterHeaterButton.PutValue(mvControlled->WaterHeater.is_enabled ? 1.f : 0.f); - ggWaterCircuitsLinkButton.PutValue(mvControlled->WaterCircuitsLink ? 1.f : 0.f); - // fuel pump - if (ggFuelPumpButton.type() != TGaugeType::push) - { - ggFuelPumpButton.PutValue(mvControlled->FuelPump.is_enabled ? 1.f : 0.f); - } - // oil pump - if (ggOilPumpButton.type() != TGaugeType::push) - { - ggOilPumpButton.PutValue(mvControlled->OilPump.is_enabled ? 1.f : 0.f); - } - // joint oil and fuel pump - if (ggOilFuelPumpButton.type() != TGaugeType::push) - { - ggOilFuelPumpButton.PutValue(mvControlled->OilFuelPumpsEnabled() ? 1.f : 0.f); - } - // traction selector and genset of a dual-mode vehicle - ggTractionModeSwitch.PutValue(mvControlled->GensetSelected() ? 1.f : 0.f); - if (ggGensetButton.type() != TGaugeType::push) - { - ggGensetButton.PutValue(mvControlled->Genset.is_enabled ? 1.f : 0.f); - } - // traction motor fans - if (ggMotorBlowersFrontButton.type() != TGaugeType::push) - { - ggMotorBlowersFrontButton.PutValue(mvControlled->MotorBlowers[end::front].is_enabled ? 1.f : 0.f); - } - if (ggMotorBlowersRearButton.type() != TGaugeType::push) - { - ggMotorBlowersRearButton.PutValue(mvControlled->MotorBlowers[end::rear].is_enabled ? 1.f : 0.f); - } - if (ggMotorBlowersAllOffButton.type() != TGaugeType::push) - { - ggMotorBlowersAllOffButton.PutValue(mvControlled->MotorBlowers[end::front].is_disabled || mvControlled->MotorBlowers[end::rear].is_disabled ? 1.f : 0.f); - } - // second controller - if (ggScndCtrl.is_push()) - { - ggScndCtrl.PutValue(ggScndCtrl.is_toggle() ? 0.5f : // pushtoggle is two-way control with neutral position in the middle - 0.f); // push is on/off control, active while held down, due to legacy use - } - // tempomat - if (false == ggScndCtrlButton.is_push()) - { - ggScndCtrlButton.PutValue(mvControlled->IsSpeedCtrlEngaged() ? 1.f : 0.f); - } - // sandbox - if (ggAutoSandButton.type() != TGaugeType::push) - { - ggAutoSandButton.PutValue(mvControlled->SandDoseAutoAllow ? 1.f : 0.f); - } - // radio - ggRadioVolumeSelector.PutValue(m_radiovolume); - - // finding each inverter - not so optimal, but action ins performed only during changing cabin - bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; - auto const flag{CouplingSet::FromBits(DynamicObject->MoverParameters->InverterControlCouplerFlag)}; - int itemstart = 0; - for ([[maybe_unused]] auto const &item : ggInverterToggleButtons) // for each button - { - int itemindex = itemstart; - itemstart++; - TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); - while (p) - { - if (p->MoverParameters->eimc[eimc_p_Pmax] > 1) - { - if (itemindex < p->MoverParameters->InvertersNo) - { - // visual feedback - ggInverterToggleButtons[itemstart - 1].PutValue(p->MoverParameters->Inverters[itemindex].Activate ? 1.0 : 0.0); - break; - } - else - { - itemindex -= p->MoverParameters->InvertersNo; - } - } - p = kier ? p->Next(flag) : p->Prev(flag); - } - } - - // we reset all indicators, as they're set during the update pass - // TODO: when cleaning up break setting indicator state into a separate function, so we can reuse it -} - -// initializes a button matching provided label. returns: true if the label was found, false otherwise -// TODO: refactor the cabin controls into some sensible structure -bool TTrain::initialize_button(cParser &Parser, std::string const &Label, int const Cabindex) -{ - - std::unordered_map const lights = { - {"i-maxft:", btLampkaMaxSila}, - {"i-maxftt:", btLampkaPrzekrMaxSila}, - {"i-radio:", btLampkaRadio}, - {"i-radiomessage:", btLampkaRadioMessage}, - {"i-radiostop:", btLampkaRadioStop}, - {"i-manual_brake:", btLampkaHamulecReczny}, - {"i-door_blocked:", btLampkaBlokadaDrzwi}, - {"i-door_blockedoff:", btLampkaDoorLockOff}, - {"i-slippery:", btLampkaPoslizg}, - {"i-contactors:", btLampkaStyczn}, - {"i-conv_ovld:", btLampkaNadmPrzetw}, - {"i-converter:", btLampkaPrzetw}, - {"i-converteroff:", btLampkaPrzetwOff}, - {"i-converteraoff:", btLampkaPrzetwAOff}, - {"i-converterb:", btLampkaPrzetwB}, - {"i-converterboff:", btLampkaPrzetwBOff}, - {"i-diff_relay:", btLampkaPrzekRozn}, - {"i-diff_relay2:", btLampkaPrzekRoznPom}, - {"i-motor_ovld:", btLampkaNadmSil}, - {"i-train_controll:", btLampkaUkrotnienie}, - {"i-brake_delay_r:", btLampkaHamPosp}, - {"i-mainbreaker:", btLampkaWylSzybki}, - {"i-mainbreakerb:", btLampkaWylSzybkiB}, - {"i-mainbreakeroff:", btLampkaWylSzybkiOff}, - {"i-mainbreakerboff:", btLampkaWylSzybkiBOff}, - {"i-mainbreakerready:", btLampkaMainBreakerReady}, - {"i-mainbreakerblinking:", btLampkaMainBreakerBlinkingIfReady}, - {"i-vent_ovld:", btLampkaNadmWent}, - {"i-comp_ovld:", btLampkaNadmSpr}, - // overheat indicator lamps - {"i-oil_overheat:", btLampkaOilOverheat}, - {"i-water_overheat:", btLampkaWaterOverheat}, - {"i-wateraux_overheat:", btLampkaWaterAuxOverheat}, - {"i-engine_overheat:", btLampkaEngineOverheat}, - {"i-resistors:", btLampkaOpory}, - {"i-no_resistors:", btLampkaBezoporowa}, - {"i-no_resistors_b:", btLampkaBezoporowaB}, - {"i-highcurrent:", btLampkaWysRozr}, - {"i-vent_trim:", btLampkaWentZaluzje}, - {"i-motorblowers:", btLampkaMotorBlowers}, - {"i-coolingfans:", btLampkaCoolingFans}, - {"i-louvresclosed:", btLampkaLouvresClosed}, - {"i-tempomat:", btLampkaTempomat}, - {"i-distancecounter:", btLampkaDistanceCounter}, - {"i-trainheating:", btLampkaOgrzewanieSkladu}, - {"i-security_aware:", btLampkaCzuwaka}, - {"i-security_cabsignal:", btLampkaSHP}, - {"i-security_aware_cabsignal:", btLampkaCzuwakaSHP}, - {"i-door_left:", btLampkaDoorLeft}, - {"i-door_right:", btLampkaDoorRight}, - {"i-departure_signal:", btLampkaDepartureSignal}, - {"i-reserve:", btLampkaRezerwa}, - {"i-scnd:", btLampkaBoczniki}, - {"i-scnd1:", btLampkaBocznik1}, - {"i-scnd2:", btLampkaBocznik2}, - {"i-scnd3:", btLampkaBocznik3}, - {"i-scnd4:", btLampkaBocznik4}, - {"i-gear1:", btLampkaGear1}, - {"i-gear2:", btLampkaGear2}, - {"i-hydrolockup:", btLampkaHydroLockup}, - {"i-braking:", btLampkaHamienie}, - {"i-brakingoff:", btLampkaBrakingOff}, - {"i-dynamicbrake:", btLampkaED}, - {"i-brakeprofileg:", btLampkaBrakeProfileG}, - {"i-brakeprofilep:", btLampkaBrakeProfileP}, - {"i-brakeprofiler:", btLampkaBrakeProfileR}, - {"i-springbrakeactive:", btLampkaSpringBrakeActive}, - {"i-springbrakeinactive:", btLampkaSpringBrakeInactive}, - {"i-braking-ezt:", btLampkaHamowanie1zes}, - {"i-braking-ezt2:", btLampkaHamowanie2zes}, - {"i-compressor:", btLampkaSprezarka}, - {"i-compressorb:", btLampkaSprezarkaB}, - {"i-compressoroff:", btLampkaSprezarkaOff}, - {"i-compressorboff:", btLampkaSprezarkaBOff}, - {"i-fuelpumpoff:", btLampkaFuelPumpOff}, - {"i-oilpump:", btLampkaOilPump}, - {"i-voltbrake:", btLampkaNapNastHam}, - {"i-resistorsb:", btLampkaOporyB}, - {"i-contactorsb:", btLampkaStycznB}, - {"i-conv_ovldb:", btLampkaNadmPrzetwB}, - {"i-hvoltageb:", btLampkaHVoltageB}, - {"i-malfunction:", btLampkaMalfunction}, - {"i-malfunctionb:", btLampkaMalfunctionB}, - {"i-forward:", btLampkaForward}, - {"i-backward:", btLampkaBackward}, - {"i-neutral:", btLampkaNeutral}, - {"i-upperlight:", btLampkaUpperLight}, - {"i-leftlight:", btLampkaLeftLight}, - {"i-rightlight:", btLampkaRightLight}, - {"i-leftend:", btLampkaLeftEndLight}, - {"i-rightend:", btLampkaRightEndLight}, - {"i-rearupperlight:", btLampkaRearUpperLight}, - {"i-rearleftlight:", btLampkaRearLeftLight}, - {"i-rearrightlight:", btLampkaRearRightLight}, - {"i-rearleftend:", btLampkaRearLeftEndLight}, - {"i-rearrightend:", btLampkaRearRightEndLight}, - {"i-dashboardlight:", btDashboardLight}, - {"i-timetablelight:", btTimetableLight}, - {"i-universal0:", btUniversals[0]}, - {"i-universal1:", btUniversals[1]}, - {"i-universal2:", btUniversals[2]}, - {"i-universal3:", btUniversals[3]}, - {"i-universal4:", btUniversals[4]}, - {"i-universal5:", btUniversals[5]}, - {"i-universal6:", btUniversals[6]}, - {"i-universal7:", btUniversals[7]}, - {"i-universal8:", btUniversals[8]}, - {"i-universal9:", btUniversals[9]}, - {"i-cabactived:", btCabActived}, - {"i-aklvents:", btAKLVents}, - {"i-compressorany:", btCompressors}, - {"i-edenabled", btEDenabled}, - }; - { - auto lookup = lights.find(Label); - if (lookup != lights.end()) - { - lookup->second.Load(Parser, DynamicObject); - return true; - } - } - // TODO: move viable dedicated lights to the automatic light array - std::unordered_map const autolights = { - {"i-doors:", &m_doors}, - {"i-doorpermit_left:", &m_doorspermitleft}, - {"i-doorpermit_right:", &m_doorspermitright}, - {"i-doorpermit_any:", &m_doorpermits}, - {"i-doorstep:", &mvOccupied->Doors.step_enabled}, - {"i-mainpipelock:", &mvOccupied->LockPipe}, - {"i-battery:", &mvOccupied->Power24vIsAvailable}, - {"i-cablight:", &Cabine[iCabn].bLight}, - {"i-compartmentlights:", &mvOccupied->CompartmentLights.is_active}, - }; - { - auto lookup = autolights.find(Label); - if (lookup != autolights.end()) - { - auto &button = Cabine[Cabindex].Button(-1); // pierwsza wolna lampka - button.Load(Parser, DynamicObject); - button.AssignBool(lookup->second); - return true; - } - } - // custom lights - if (Label == "i-instrumentlight:") - { - btInstrumentLight.Load(Parser, DynamicObject); - InstrumentLightType = 0; - } - else if (Label == "i-instrumentlight_m:") - { - btInstrumentLight.Load(Parser, DynamicObject); - InstrumentLightType = 1; - } - else if (Label == "i-instrumentlight_c:") - { - btInstrumentLight.Load(Parser, DynamicObject); - InstrumentLightType = 2; - } - else if (Label == "i-instrumentlight_a:") - { - btInstrumentLight.Load(Parser, DynamicObject); - InstrumentLightType = 3; - } - else if (Label == "i-instrumentlight_l:") - { - btInstrumentLight.Load(Parser, DynamicObject); - InstrumentLightType = 4; - } - else if (Label == "i-doors:") - { - int i = Parser.getToken() - 1; - auto &button = Cabine[Cabindex].Button(-1); // pierwsza wolna lampka - button.Load(Parser, DynamicObject); - button.AssignBool(bDoors[0] + 3 * i); - } - else - { - // failed to match the label - return false; - } - - return true; -} - -// initializes a gauge matching provided label. returns: true if the label was found, false otherwise -// TODO: refactor the cabin controls into some sensible structure -bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int const Cabindex) -{ - - std::unordered_map const gauges = {{"jointctrl:", ggJointCtrl}, - {"mainctrl:", ggMainCtrl}, - {"scndctrl:", ggScndCtrl}, - {"dirkey:", ggDirKey}, - {"brakectrl:", ggBrakeCtrl}, - {"localbrake:", ggLocalBrake}, - {"alarmchain:", ggAlarmChain}, - {"brakeprofile_sw:", ggBrakeProfileCtrl}, - {"brakeprofileg_sw:", ggBrakeProfileG}, - {"brakeprofiler_sw:", ggBrakeProfileR}, - {"brakeopmode_sw:", ggBrakeOperationModeCtrl}, - {"maxcurrent_sw:", ggMaxCurrentCtrl}, - {"autorelay_sw:", ggAutoRelayButton}, - {"main_off_bt:", ggMainOffButton}, - {"main_on_bt:", ggMainOnButton}, - {"mainb_sw:", m_remotelinebreakers[0].main_switch}, - {"mainb_off_bt:", m_remotelinebreakers[0].off_button}, - {"mainb_on_bt:", m_remotelinebreakers[0].on_button}, - {"mainc_sw:", m_remotelinebreakers[1].main_switch}, - {"mainc_off_bt:", m_remotelinebreakers[1].off_button}, - {"mainc_on_bt:", m_remotelinebreakers[1].on_button}, - {"security_reset_bt:", ggSecurityResetButton}, - {"shp_reset_bt:", ggSHPResetButton}, - {"releaser_bt:", ggReleaserButton}, - {"springbrakeon_bt:", ggSpringBrakeOnButton}, - {"springbrakeoff_bt:", ggSpringBrakeOffButton}, - {"universalbrake1_bt:", ggUniveralBrakeButton1}, - {"universalbrake2_bt:", ggUniveralBrakeButton2}, - {"universalbrake3_bt:", ggUniveralBrakeButton3}, - {"epbrake_bt:", ggEPFuseButton}, - {"sand_bt:", ggSandButton}, - {"autosandallow_sw:", ggAutoSandButton}, - {"antislip_bt:", ggAntiSlipButton}, - {"horn_bt:", ggHornButton}, - {"hornlow_bt:", ggHornLowButton}, - {"hornhigh_bt:", ggHornHighButton}, - {"whistle_bt:", ggWhistleButton}, - {"helper_bt:", ggHelperButton}, - {"fuse_bt:", ggFuseButton}, - {"converterfuse_bt:", ggConverterFuseButton}, - {"stlinoff_bt:", ggStLinOffButton}, - {"doorpermitpreset_sw:", ggDoorPermitPresetButton}, - {"door_left_sw:", ggDoorLeftButton}, - {"door_right_sw:", ggDoorRightButton}, - {"doorlefton_sw:", ggDoorLeftOnButton}, - {"doorrighton_sw:", ggDoorRightOnButton}, - {"doorleftoff_sw:", ggDoorLeftOffButton}, - {"doorrightoff_sw:", ggDoorRightOffButton}, - {"doorallon_sw:", ggDoorAllOnButton}, - {"departure_signal_bt:", ggDepartureSignalButton}, - {"upperlight_sw:", ggUpperLightButton}, - {"leftlight_sw:", ggLeftLightButton}, - {"rightlight_sw:", ggRightLightButton}, - {"dimheadlights_sw:", ggDimHeadlightsButton}, - {"leftend_sw:", ggLeftEndLightButton}, - {"rightend_sw:", ggRightEndLightButton}, - {"lights_sw:", ggLightsButton}, - {"moderndimmer_sw:", ggModernLightDimSw}, - {"rearupperlight_sw:", ggRearUpperLightButton}, - {"rearleftlight_sw:", ggRearLeftLightButton}, - {"rearrightlight_sw:", ggRearRightLightButton}, - {"rearleftend_sw:", ggRearLeftEndLightButton}, - {"rearrightend_sw:", ggRearRightEndLightButton}, - {"compressor_sw:", ggCompressorButton}, - {"compressorlocal_sw:", ggCompressorLocalButton}, - {"compressorlist_sw:", ggCompressorListButton}, - {"converter_sw:", ggConverterButton}, - {"converterlocal_sw:", ggConverterLocalButton}, - {"converteroff_sw:", ggConverterOffButton}, - {"main_sw:", ggMainButton}, - {"waterpumpbreaker_sw:", ggWaterPumpBreakerButton}, - {"waterpump_sw:", ggWaterPumpButton}, - {"waterheaterbreaker_sw:", ggWaterHeaterBreakerButton}, - {"waterheater_sw:", ggWaterHeaterButton}, - {"water1tempb:", ggWater1TempB}, - {"watercircuitslink_sw:", ggWaterCircuitsLinkButton}, - {"fuelpump_sw:", ggFuelPumpButton}, - {"oilpump_sw:", ggOilPumpButton}, - {"oilfuelpump_sw:", ggOilFuelPumpButton}, - {"tractionmode_sw:", ggTractionModeSwitch}, - {"genset_sw:", ggGensetButton}, - {"oilpressb:", ggOilPressB}, - {"motorblowersfront_sw:", ggMotorBlowersFrontButton}, - {"motorblowersrear_sw:", ggMotorBlowersRearButton}, - {"motorblowersalloff_sw:", ggMotorBlowersAllOffButton}, - {"radiochannel_sw:", ggRadioChannelSelector}, - {"radiochannelprev_sw:", ggRadioChannelPrevious}, - {"radiochannelnext_sw:", ggRadioChannelNext}, - {"radiostop_sw:", ggRadioStop}, - {"radiotest_sw:", ggRadioTest}, - {"radiocall1_sw:", ggRadioCall1}, - {"radiocall3_sw:", ggRadioCall3}, - {"radiovolume_sw:", ggRadioVolumeSelector}, - {"radiovolumeprev_sw:", ggRadioVolumePrevious}, - {"radiovolumenext_sw:", ggRadioVolumeNext}, - {"radioon_sw:", ggRadioOnButton}, - {"radiooff_sw:", ggRadioOffButton}, - {"radiofuseon_sw:", ggRadioFuseOnButton}, - {"radiofuseoff_sw:", ggRadioFuseOffButton}, - /* - { "pantfront_sw:", ggPantFrontButton }, - { "pantrear_sw:", ggPantRearButton }, - { "pantfrontoff_sw:", ggPantFrontButtonOff }, - { "pantrearoff_sw:", ggPantRearButtonOff }, - */ - {"pantalloff_sw:", ggPantAllDownButton}, - {"pantselected_sw:", ggPantSelectedButton}, - {"pantselectedoff_sw:", ggPantSelectedDownButton}, - {"pantvalves_sw:", ggPantValvesButton}, - {"pantcompressor_sw:", ggPantCompressorButton}, - {"pantcompressorvalve_sw:", ggPantCompressorValve}, - {"trainheating_sw:", ggTrainHeatingButton}, - {"signalling_sw:", ggSignallingButton}, - {"door_signalling_sw:", ggDoorSignallingButton}, - {"nextcurrent_sw:", ggNextCurrentButton}, - {"instrumentlight_sw:", ggInstrumentLightButton}, - {"dashboardlight_sw:", ggDashboardLightButton}, - {"timetablelight_sw:", ggTimetableLightButton}, - {"cablightdim_sw:", ggCabLightDimButton}, - {"compartmentlights_sw:", ggCompartmentLightsButton}, - {"compartmentlightson_sw:", ggCompartmentLightsOnButton}, - {"compartmentlightsoff_sw:", ggCompartmentLightsOffButton}, - {"battery_sw:", ggBatteryButton}, - {"batteryon_sw:", ggBatteryOnButton}, - {"batteryoff_sw:", ggBatteryOffButton}, - {"cabactivation_sw:", ggCabActivationButton}, - {"distancecounter_sw:", ggDistanceCounterButton}, - {"relayreset1_bt:", ggRelayResetButtons[0]}, - {"relayreset2_bt:", ggRelayResetButtons[1]}, - {"relayreset3_bt:", ggRelayResetButtons[2]}, - {"universal0:", ggUniversals[0]}, - {"universal1:", ggUniversals[1]}, - {"universal2:", ggUniversals[2]}, - {"universal3:", ggUniversals[3]}, - {"universal4:", ggUniversals[4]}, - {"universal5:", ggUniversals[5]}, - {"universal6:", ggUniversals[6]}, - {"universal7:", ggUniversals[7]}, - {"universal8:", ggUniversals[8]}, - {"universal9:", ggUniversals[9]}, - {"universal10:", ggUniversals[10]}, - {"universal11:", ggUniversals[11]}, - {"universal12:", ggUniversals[12]}, - {"universal13:", ggUniversals[13]}, - {"universal14:", ggUniversals[14]}, - {"universal15:", ggUniversals[15]}, - {"universal16:", ggUniversals[16]}, - {"universal17:", ggUniversals[17]}, - {"universal18:", ggUniversals[18]}, - {"universal19:", ggUniversals[19]}, - {"universal20:", ggUniversals[20]}, - {"universal21:", ggUniversals[21]}, - {"universal22:", ggUniversals[22]}, - {"universal23:", ggUniversals[23]}, - {"universal24:", ggUniversals[24]}, - {"universal25:", ggUniversals[25]}, - {"universal26:", ggUniversals[26]}, - {"universal27:", ggUniversals[27]}, - {"universal28:", ggUniversals[28]}, - {"universal29:", ggUniversals[29]}, - {"inverterenable1_bt:", ggInverterEnableButtons[0]}, - {"inverterenable2_bt:", ggInverterEnableButtons[1]}, - {"inverterenable3_bt:", ggInverterEnableButtons[2]}, - {"inverterenable4_bt:", ggInverterEnableButtons[3]}, - {"inverterenable5_bt:", ggInverterEnableButtons[4]}, - {"inverterenable6_bt:", ggInverterEnableButtons[5]}, - {"inverterenable7_bt:", ggInverterEnableButtons[6]}, - {"inverterenable8_bt:", ggInverterEnableButtons[7]}, - {"inverterenable9_bt:", ggInverterEnableButtons[8]}, - {"inverterenable10_bt:", ggInverterEnableButtons[9]}, - {"inverterenable11_bt:", ggInverterEnableButtons[10]}, - {"inverterenable12_bt:", ggInverterEnableButtons[11]}, - {"inverterdisable1_bt:", ggInverterDisableButtons[0]}, - {"inverterdisable2_bt:", ggInverterDisableButtons[1]}, - {"inverterdisable3_bt:", ggInverterDisableButtons[2]}, - {"inverterdisable4_bt:", ggInverterDisableButtons[3]}, - {"inverterdisable5_bt:", ggInverterDisableButtons[4]}, - {"inverterdisable6_bt:", ggInverterDisableButtons[5]}, - {"inverterdisable7_bt:", ggInverterDisableButtons[6]}, - {"inverterdisable8_bt:", ggInverterDisableButtons[7]}, - {"inverterdisable9_bt:", ggInverterDisableButtons[8]}, - {"inverterdisable10_bt:", ggInverterDisableButtons[9]}, - {"inverterdisable11_bt:", ggInverterDisableButtons[10]}, - {"inverterdisable12_bt:", ggInverterDisableButtons[11]}, - {"invertertoggle1_bt:", ggInverterToggleButtons[0]}, - {"invertertoggle2_bt:", ggInverterToggleButtons[1]}, - {"invertertoggle3_bt:", ggInverterToggleButtons[2]}, - {"invertertoggle4_bt:", ggInverterToggleButtons[3]}, - {"invertertoggle5_bt:", ggInverterToggleButtons[4]}, - {"invertertoggle6_bt:", ggInverterToggleButtons[5]}, - {"invertertoggle7_bt:", ggInverterToggleButtons[6]}, - {"invertertoggle8_bt:", ggInverterToggleButtons[7]}, - {"invertertoggle9_bt:", ggInverterToggleButtons[8]}, - {"invertertoggle10_bt:", ggInverterToggleButtons[9]}, - {"invertertoggle11_bt:", ggInverterToggleButtons[10]}, - {"invertertoggle12_bt:", ggInverterToggleButtons[11]}, - {"pantvalvesupdate_bt:", ggPantValvesUpdate}, - {"pantvalvesoff_bt:", ggPantValvesOff}, - {"wipers_sw:", ggWiperSw}}; - { - auto const lookup{gauges.find(Label)}; - if (lookup != gauges.end()) - { - lookup->second.Load(Parser, DynamicObject); - m_controlmapper.insert(lookup->second, lookup->first); - return true; - } - } - // dedicated gauges with state-driven optional submodel - // TODO: move viable gauges here - // TODO: convert dedicated gauges to auto-allocated ones, replace dedicated references in command handlers to mapper lookups - std::unordered_map> const stategauges = { - {"tempomat_sw:", {ggScndCtrlButton, &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"tempomatoff_sw:", {ggScndCtrlOffButton, &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedinc_bt:", {ggSpeedControlIncreaseButton, &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speeddec_bt:", {ggSpeedControlDecreaseButton, &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedctrlpowerinc_bt:", {ggSpeedControlPowerIncreaseButton, &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedctrlpowerdec_bt:", {ggSpeedControlPowerDecreaseButton, &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton0:", {ggSpeedCtrlButtons[0], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton1:", {ggSpeedCtrlButtons[1], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton2:", {ggSpeedCtrlButtons[2], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton3:", {ggSpeedCtrlButtons[3], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton4:", {ggSpeedCtrlButtons[4], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton5:", {ggSpeedCtrlButtons[5], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton6:", {ggSpeedCtrlButtons[6], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton7:", {ggSpeedCtrlButtons[7], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton8:", {ggSpeedCtrlButtons[8], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton9:", {ggSpeedCtrlButtons[9], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"doorleftpermit_sw:", {ggDoorLeftPermitButton, &m_doorspermitleft}}, - {"doorrightpermit_sw:", {ggDoorRightPermitButton, &m_doorspermitright}}, - {"dooralloff_sw:", {ggDoorAllOffButton, &m_doors}}, - {"doorstep_sw:", {ggDoorStepButton, &mvOccupied->Doors.step_enabled}}, - {"dirforward_bt:", {ggDirForwardButton, &m_dirforward}}, - {"dirneutral_bt:", {ggDirNeutralButton, &m_dirneutral}}, - {"dirbackward_bt:", {ggDirBackwardButton, &m_dirbackward}}, - }; - { - auto const lookup{stategauges.find(Label)}; - if (lookup != stategauges.end()) - { - auto &gauge{std::get(lookup->second)}; - gauge.Load(Parser, DynamicObject); - gauge.AssignState(std::get(lookup->second)); - m_controlmapper.insert(gauge, lookup->first); - return true; - } - } - // TODO: move viable dedicated gauges to the automatic array - std::unordered_map const autoboolgauges = { - {"doormode_sw:", &mvOccupied->Doors.remote_only}, - {"coolingfans_sw:", &mvControlled->RVentForceOn}, - {"pantfront_sw:", &mvPantographUnit->Pantographs[end::front].valve.is_enabled}, - {"pantrear_sw:", &mvPantographUnit->Pantographs[end::rear].valve.is_enabled}, - {"pantfrontoff_sw:", &mvPantographUnit->Pantographs[end::front].valve.is_disabled}, - {"pantrearoff_sw:", &mvPantographUnit->Pantographs[end::rear].valve.is_disabled}, - {"radio_sw:", &mvOccupied->Radio}, - {"radiofuse_sw:", &mvOccupied->RadioFuse}, - {"cablight_sw:", &Cabine[iCabn].bLight}, - {"springbraketoggle_bt:", &mvOccupied->SpringBrake.Activate}, - {"couplingdisconnect_sw:", &m_couplingdisconnect}, - {"couplingdisconnectback_sw:", &m_couplingdisconnectback}, - {"mirrors_sw:", &mvOccupied->MirrorForbidden}, - }; - { - auto lookup = autoboolgauges.find(Label); - if (lookup != autoboolgauges.end()) - { - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna lampka - gauge.Load(Parser, DynamicObject); - gauge.AssignBool(lookup->second); - m_controlmapper.insert(gauge, lookup->first); - return true; - } - } - // TODO: move viable dedicated gauges to the automatic array - std::unordered_map const autointgauges = { - {"manualbrake:", &mvOccupied->ManualBrakePos}, - {"pantselect_sw:", &mvOccupied->PantsPreset.second[cab_to_end()]}, - }; - { - auto lookup = autointgauges.find(Label); - if (lookup != autointgauges.end()) - { - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna lampka - gauge.Load(Parser, DynamicObject); - gauge.AssignInt(lookup->second); - m_controlmapper.insert(gauge, lookup->first); - return true; - } - } - - // broadcast radio receiver - if (Label == "fmradio_sw:" || Label == "fmradiovolume_sw:" || Label == "fmradiotune_sw:" || Label == "fmradioscale:") - { - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - if (Label == "fmradio_sw:") - { - gauge.AssignBool(&m_fmradiopower); - } - else - { - gauge.AssignFloat(Label == "fmradiovolume_sw:" ? &m_fmradiovolume : &m_fmradiodial); - } - if (Label != "fmradioscale:") - { - // the scale pointer is an indicator, the rest are controls - m_controlmapper.insert(gauge, Label); - } - m_fmradiopresent = true; - // unless the speaker location is defined explicitly, the sound comes from the first defined element of the receiver - if (m_fmradiosound.offset() == glm::vec3()) - { - m_fmradiosound.offset(gauge.model_offset()); - } - return true; - } - - // ABu 090305: uniwersalne przyciski lub inne rzeczy - if (Label == "mainctrlact:") - { - ggMainCtrlAct.Load(Parser, DynamicObject); - } - // SEKCJA WSKAZNIKOW - else if (Label == "tachometer:" || Label == "tachometerb:") - { - // predkosciomierz wskaźnikowy z szarpaniem - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(&fTachoVelocityJump); - // bind tachometer sound location to the meter - if (dsbHasler && dsbHasler->offset() == glm::vec3()) - { - dsbHasler->offset(gauge.model_offset()); - } - } - else if (Label == "tachometern:") - { - // predkosciomierz wskaźnikowy bez szarpania - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(&fTachoVelocity); - // bind tachometer sound location to the meter - if (dsbHasler && dsbHasler->offset() == glm::vec3()) - { - dsbHasler->offset(gauge.model_offset()); - } - } - else if (Label == "tachometerd:") - { - // predkosciomierz cyfrowy - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(&fTachoVelocity); - // bind tachometer sound location to the meter - if (dsbHasler && dsbHasler->offset() == glm::vec3()) - { - dsbHasler->offset(gauge.model_offset()); - } - } - else if (Label == "hvcurrent1:" || Label == "hvcurrent1b:") - { - // 1szy amperomierz - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(fHCurrent + 1); - } - else if (Label == "hvcurrent2:" || Label == "hvcurrent2b:") - { - // 2gi amperomierz - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(fHCurrent + 2); - } - else if (Label == "hvcurrent3:" || Label == "hvcurrent3b:") - { - // 3ci amperomierz - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałska - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(fHCurrent + 3); - } - else if (Label == "hvcurrent:" || Label == "hvcurrentb:") - { - // amperomierz calkowitego pradu - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(fHCurrent); - } - else if (Label == "eimscreen:") - { - // amperomierz calkowitego pradu - int i; - int j; - Parser.getTokens(2, false); - Parser >> i >> j; - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(&fEIMParams[i][j]); - } - else if (Label == "brakes:") - { - // specified pipe pressure of specified consist vehicle - int i; - int j; - Parser.getTokens(2, false); - Parser >> i >> j; - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignFloat(&fPress[std::clamp(i, 1, 20) - 1][std::clamp(j, 0, 3)]); - } - else if (Label == "brakepress:" || Label == "brakepressb:") - { - // manometr cylindrow hamulcowych - // Ra 2014-08: przeniesione do TCab - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&mvOccupied->BrakePress); - } - else if (Label == "pipepress:" || Label == "pipepressb:") - { - // manometr przewodu hamulcowego - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&mvOccupied->PipePress); - } - else if (Label == "scndpress:") - { - // manometr przewodu hamulcowego - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&mvOccupied->ScndPipePress); - } - else if (Label == "limpipepress:") - { - // manometr zbiornika sterujacego zaworu maszynisty - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&m_brakehandlecp); - } - else if (Label == "cntrlpress:") - { - // manometr zbiornika kontrolnego/rorzďż˝du - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&mvPantographUnit->PantPress); - } - else if (Label == "springbrakepress:") - { - // manometr cylindra hamulca sprężynowego - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&mvOccupied->SpringBrake.SBP); - } - else if (Label == "epctrlvalue:") - { - // wskazowka sterowania sila hamulca ep - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&mvOccupied->EpForce); - } - else if (Label == "compressor:" || Label == "compressorb:") - { - // manometr sprezarki/zbiornika glownego - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&mvOccupied->Compressor); - } - else if (Label == "oilpress:") - { - // oil pressure - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(&mvControlled->OilPump.pressure); - } - else if (Label == "oiltemp:") - { - // oil temperature - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(&mvControlled->dizel_heat.To); - } - else if (Label == "water1temp:") - { - // main circuit water temperature - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(&mvControlled->dizel_heat.temperatura1); - } - else if (Label == "water2temp:") - { - // auxiliary circuit water temperature - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(&mvControlled->dizel_heat.temperatura2); - } - else if (Label == "pantpress:") - { - // pantograph tank pressure - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&mvPantographUnit->PantPress); - } - // yB - dla drugiej sekcji - else if (Label == "hvbcurrent1:") - { - // 1szy amperomierz - ggI1B.Load(Parser, DynamicObject); - } - else if (Label == "hvbcurrent2:") - { - // 2gi amperomierz - ggI2B.Load(Parser, DynamicObject); - } - else if (Label == "hvbcurrent3:") - { - // 3ci amperomierz - ggI3B.Load(Parser, DynamicObject); - } - else if (Label == "hvbcurrent:") - { - // amperomierz calkowitego pradu - ggItotalB.Load(Parser, DynamicObject); - } - //************************************************************* - else if (Label == "clock:") - { - // zegar analogowy - if (Parser.getToken() == "analog" && DynamicObject->mdKabina) - { - // McZapkie-300302: zegarek - ggClockSInd.Init(DynamicObject->mdKabina->GetFromName("ClockShand"), nullptr, TGaugeAnimation::gt_Rotate, static_cast(1.0 / 60.0)); - ggClockMInd.Init(DynamicObject->mdKabina->GetFromName("ClockMhand"), nullptr, TGaugeAnimation::gt_Rotate, static_cast(1.0 / 60.0)); - ggClockHInd.Init(DynamicObject->mdKabina->GetFromName("ClockHhand"), nullptr, TGaugeAnimation::gt_Rotate, static_cast(1.0 / 12.0)); - } - } - else if (Label == "clock_seconds:") - { - ggClockSInd.Load(Parser, DynamicObject); - } - else if (Label == "evoltage:") - { - // woltomierz napiecia silnikow - ggEngineVoltage.Load(Parser, DynamicObject); - } - else if (Label == "hvoltage:") - { - // woltomierz wysokiego napiecia - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(&fHVoltage); - } - else if (Label == "lvoltage:") - { - // woltomierz niskiego napiecia - ggLVoltage.Load(Parser, DynamicObject); - } - else if (Label == "enrot1m:") - { - // obrotomierz - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(fEngine + 1); - } // ggEnrot1m.Load(Parser,DynamicObject->mdKabina); - else if (Label == "enrot2m:") - { - // obrotomierz - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(fEngine + 2); - } // ggEnrot2m.Load(Parser,DynamicObject->mdKabina); - else if (Label == "enrot3m:") - { // obrotomierz - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(fEngine + 3); - } // ggEnrot3m.Load(Parser,DynamicObject->mdKabina); - else if (Label == "engageratio:") - { - // np. ciśnienie sterownika sprzęgła - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignDouble(&mvControlled->dizel_engage); - } // ggEngageRatio.Load(Parser,DynamicObject->mdKabina); - else if (Label == "maingearstatus:") - { - // np. ciśnienie sterownika skrzyni biegów - ggMainGearStatus.Load(Parser, DynamicObject); - } - else if (Label == "ignitionkey:") - { - ggIgnitionKey.Load(Parser, DynamicObject); - } - else if (Label == "distcounter:") - { - // Ra 2014-07: licznik kilometrów - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - // the counter shows the odometer of the vehicle, kept between the sessions (eu07/maszyna#72). its offset - // was the state it started each session with, now it is that only for a vehicle with no known state - if (auto const seed{odometer::counter_seed(gauge.offset(), gauge.scale())}; seed.has_value()) - mvControlled->Odometer.seed(*seed); - gauge.offset(0.f); - gauge.AssignDouble(&mvControlled->Odometer.km); - // the vehicle the counter counts for is one the odometer store keeps, also in the sessions the counter seeds - // nothing (its state is a saved one by then) and when it's the motor car of the unit the cab is in - mvControlled->Odometer.shown = true; - } - else if (Label == "shuntmodepower:") - { - // shunt mode power slider - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignDouble(&mvControlled->AnPos); - m_controlmapper.insert(gauge, "shuntmodepower:"); - } - else if (Label == "heatingvoltage:") - { - if (mvControlled->HeatingPowerSource.SourceType == TPowerSource::Generator) - { - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignDouble(&mvControlled->HeatingPowerSource.EngineGenerator.voltage); - } - } - else if (Label == "heatingcurrent:") - { - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignDouble(&mvControlled->TotalCurrent); - } - else - { - // failed to match the label - return false; - } - - return true; -} - -uint16_t TTrain::id() -{ - if (vid == 0) - { - vid = ++simulation::prev_train_id; - WriteLog("net: assigning id " + std::to_string(vid) + " to vehicle " + Dynamic()->name(), logtype::net); - } - return vid; -} - -namespace -{ -// updates trains in range [Start, End) -void update_trains(std::deque const &Trains, std::size_t const Start, std::size_t const End, double const Dt) -{ - for (std::size_t j = Start; j < End; ++j) - { - if (Trains[j]) - Trains[j]->Update(Dt); - } -} -} // namespace - -void train_table::updateAsync(double dt) -{ - const int threads = std::max(1, Global.trainThreads); - const size_t total = m_items.size(); - const size_t chunkSize = (total + threads - 1) / threads; - auto const instance{TSubModel::iInstance}; - - std::vector workers; - std::vector> results; // przekazują wyjątki z wątków do głównego wątku - workers.reserve(threads); - results.reserve(threads); - - for (int i = 0; i < threads; ++i) - { - const size_t start = i * chunkSize; - const size_t end = std::min(start + chunkSize, total); - - if (start >= end) - break; // brak więcej danych - - // the instance whose animations the gauges set (TSubModel::iInstance, per thread since the walks of the vulkan renderer went on - // several threads) is the one the main thread set for the driven vehicle - std::packaged_task task([this, start, end, dt, instance]() { - TSubModel::iInstance = instance; - update_trains(m_items, start, end, dt); - }); - results.emplace_back(task.get_future()); - workers.emplace_back(std::move(task)); - } - - // Poczekaj aż wszystkie wątki skończą - for (auto &worker : workers) - worker.join(); - - for (auto &result : results) - result.get(); - - // Teraz kasowanie (tylko w głównym wątku) - for (TTrain *train : m_items) - { - if (!train) - continue; - - if (train->pending_delete) - { - purge(train->Dynamic()->name()); - if (simulation::Train == train) - simulation::Train = nullptr; - } - else if (simulation::Train != train && Global.network_servers.empty() && !Global.network_client) - { - purge(train->Dynamic()->name()); - } - } -} - -void train_table::update(double dt) -{ - for (TTrain *train : m_items) - { - if (!train) - continue; - - train->Update(dt); - - if (train->pending_delete) - { - purge(train->Dynamic()->name()); - if (simulation::Train == train) - simulation::Train = nullptr; - } - // for single-player destroy non-player trains - else if (simulation::Train != train && Global.network_servers.empty() && !Global.network_client) - { - purge(train->Dynamic()->name()); - } - } -} - -TTrain *train_table::find_id(std::uint16_t const Id) const -{ - - if (Id == 0) - { - return nullptr; - } - - for (TTrain *train : m_items) - { - if (!train) - { - continue; - } - if (train->id() == Id) - { - return train; - } - } - return nullptr; -} diff --git a/vehicle/cab/auxiliarycommands.cpp b/vehicle/cab/auxiliarycommands.cpp new file mode 100644 index 000000000..f24eb9cb6 --- /dev/null +++ b/vehicle/cab/auxiliarycommands.cpp @@ -0,0 +1,1308 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the commands of the auxiliaries: the pumps, the genset, the water, the converter, the compressor, the blowers + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/mover.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +void TTrain::OnCommand_fuelpumptoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggFuelPumpButton.type() == TGaugeType::push) + { + // impulse switch + // currently there's no off button so we always try to turn it on + OnCommand_fuelpumpenable(Train, Command); + } + else + { + // two-state switch + if (Command.action == GLFW_RELEASE) + { + return; + } + + if (false == Train->mvControlled->FuelPump.is_enabled) + { + // turn on + OnCommand_fuelpumpenable(Train, Command); + } + else + { + // turn off + OnCommand_fuelpumpdisable(Train, Command); + } + } +} + +void TTrain::OnCommand_fuelpumpenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggFuelPumpButton.type() == TGaugeType::push) + { + // impulse switch + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggFuelPumpButton.UpdateValue(1.0, Train->dsbSwitch); + Train->mvControlled->FuelPumpSwitch(true); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggFuelPumpButton.UpdateValue(0.0, Train->dsbSwitch); + Train->mvControlled->FuelPumpSwitch(false); + } + } + else + { + // two-state switch, only cares about press events + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggFuelPumpButton.UpdateValue(1.0, Train->dsbSwitch); + Train->mvControlled->FuelPumpSwitch(true); + Train->mvControlled->FuelPumpSwitchOff(false); + } + } +} + +void TTrain::OnCommand_fuelpumpdisable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggFuelPumpButton.type() == TGaugeType::push) + { + // impulse switch + // currently there's no disable return type switch + return; + } + else + { + // two-state switch, only cares about press events + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggFuelPumpButton.UpdateValue(0.0, Train->dsbSwitch); + Train->mvControlled->FuelPumpSwitch(false); + Train->mvControlled->FuelPumpSwitchOff(true); + } + } +} + +void TTrain::OnCommand_oilpumptoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggOilPumpButton.type() == TGaugeType::push) + { + // impulse switch + // currently there's no off button so we always try to turn it on + OnCommand_oilpumpenable(Train, Command); + } + else + { + // two-state switch + if (Command.action == GLFW_RELEASE) + { + return; + } + + if (false == Train->mvControlled->OilPump.is_enabled) + { + // turn on + OnCommand_oilpumpenable(Train, Command); + } + else + { + // turn off + OnCommand_oilpumpdisable(Train, Command); + } + } +} + +void TTrain::OnCommand_oilpumpenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggOilPumpButton.type() == TGaugeType::push) + { + // impulse switch + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggOilPumpButton.UpdateValue(1.0, Train->dsbSwitch); + Train->mvControlled->OilPumpSwitch(true); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggOilPumpButton.UpdateValue(0.0, Train->dsbSwitch); + Train->mvControlled->OilPumpSwitch(false); + } + } + else + { + // two-state switch, only cares about press events + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggOilPumpButton.UpdateValue(1.0, Train->dsbSwitch); + Train->mvControlled->OilPumpSwitch(true); + Train->mvControlled->OilPumpSwitchOff(false); + } + } +} + +void TTrain::OnCommand_oilpumpdisable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggOilPumpButton.type() == TGaugeType::push) + { + // impulse switch + // currently there's no disable return type switch + return; + } + else + { + // two-state switch, only cares about press events + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggOilPumpButton.UpdateValue(0.0, Train->dsbSwitch); + Train->mvControlled->OilPumpSwitch(false); + Train->mvControlled->OilPumpSwitchOff(true); + } + } +} + +void TTrain::OnCommand_oilfuelpumptoggle(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_REPEAT) + { + return; + } + + auto *vehicle{Train->mvControlled}; + if (Train->ggOilFuelPumpButton.type() == TGaugeType::push) + { + // impulse switch, as the separate ones: held to start both pumps + auto const pressed{Command.action == GLFW_PRESS}; + Train->ggOilFuelPumpButton.UpdateValue(pressed ? 1.0 : 0.0, Train->dsbSwitch); + vehicle->FuelPumpSwitch(pressed); + vehicle->OilPumpSwitch(pressed); + return; + } + // two-state switch, only cares about press events + if (Command.action != GLFW_PRESS) + { + return; + } + // both pumps go off if both were on, otherwise both go on; a pump started automatically doesn't take part + auto const enable{false == vehicle->OilFuelPumpsEnabled()}; + Train->ggOilFuelPumpButton.UpdateValue(enable ? 1.0 : 0.0, Train->dsbSwitch); + vehicle->FuelPumpSwitch(enable); + vehicle->FuelPumpSwitchOff(false == enable); + vehicle->OilPumpSwitch(enable); + vehicle->OilPumpSwitchOff(false == enable); +} + +// the traction selector of a dual-mode vehicle (eu07/maszyna#536), a two-state switch +void TTrain::OnCommand_tractionmodetoggle(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + if (Train->mvControlled->GensetSelected()) + { + OnCommand_tractionmodecatenary(Train, Command); + } + else + { + OnCommand_tractionmodegenset(Train, Command); + } +} + +void TTrain::OnCommand_tractionmodecatenary(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + // refused with the line breaker closed: then the switch doesn't move + Train->mvControlled->TractionModeSwitch(TMoverParameters::traction_mode::catenary, range_t::consist); + if (false == Train->mvControlled->GensetSelected()) + { + Train->ggTractionModeSwitch.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_tractionmodegenset(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + // refused with the line breaker closed, or without a genset: then the switch doesn't move + Train->mvControlled->TractionModeSwitch(TMoverParameters::traction_mode::genset, range_t::consist); + if (Train->mvControlled->GensetSelected()) + { + Train->ggTractionModeSwitch.UpdateValue(1.0, Train->dsbSwitch); + } +} + +// the start request of the genset of a dual-mode vehicle, a two-state switch +void TTrain::OnCommand_gensettoggle(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + if (false == Train->mvControlled->Genset.is_enabled) + { + OnCommand_gensetenable(Train, Command); + } + else + { + OnCommand_gensetdisable(Train, Command); + } +} + +void TTrain::OnCommand_gensetenable(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + // ignored by a genset which starts on its own: then the switch doesn't move + Train->mvControlled->GensetSwitch(true, range_t::consist); + if (Train->mvControlled->Genset.is_enabled) + { + Train->ggGensetButton.UpdateValue(1.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_gensetdisable(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + Train->mvControlled->GensetSwitch(false, range_t::consist); + if (false == Train->mvControlled->Genset.is_enabled) + { + Train->ggGensetButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_waterheaterbreakertoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->mvControlled->WaterHeater.breaker) + { + // turn on + OnCommand_waterheaterbreakerclose(Train, Command); + } + else + { + // turn off + OnCommand_waterheaterbreakeropen(Train, Command); + } + } +} + +void TTrain::OnCommand_waterheaterbreakerclose(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggWaterHeaterBreakerButton.UpdateValue(1.0, Train->dsbSwitch); + + if (true == Train->mvControlled->WaterHeater.breaker) + { + return; + } // already enabled + + Train->mvControlled->WaterHeaterBreakerSwitch(true); + } +} + +void TTrain::OnCommand_waterheaterbreakeropen(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggWaterHeaterBreakerButton.UpdateValue(0.0, Train->dsbSwitch); + + if (false == Train->mvControlled->WaterHeater.breaker) + { + return; + } // already enabled + + Train->mvControlled->WaterHeaterBreakerSwitch(false); + } +} + +void TTrain::OnCommand_waterheatertoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->mvControlled->WaterHeater.is_enabled) + { + // turn on + OnCommand_waterheaterenable(Train, Command); + } + else + { + // turn off + OnCommand_waterheaterdisable(Train, Command); + } + } +} + +void TTrain::OnCommand_waterheaterenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggWaterHeaterButton.UpdateValue(1.0, Train->dsbSwitch); + + if (true == Train->mvControlled->WaterHeater.is_enabled) + { + return; + } // already enabled + + Train->mvControlled->WaterHeaterSwitch(true); + } +} + +void TTrain::OnCommand_waterheaterdisable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggWaterHeaterButton.UpdateValue(0.0, Train->dsbSwitch); + + if (false == Train->mvControlled->WaterHeater.is_enabled) + { + return; + } // already disabled + + Train->mvControlled->WaterHeaterSwitch(false); + } +} + +void TTrain::OnCommand_waterpumpbreakertoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->mvControlled->WaterPump.breaker) + { + // turn on + OnCommand_waterpumpbreakerclose(Train, Command); + } + else + { + // turn off + OnCommand_waterpumpbreakeropen(Train, Command); + } + } +} + +void TTrain::OnCommand_waterpumpbreakerclose(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggWaterPumpBreakerButton.UpdateValue(1.0, Train->dsbSwitch); + + if (true == Train->mvControlled->WaterPump.breaker) + { + return; + } // already enabled + + Train->mvControlled->WaterPumpBreakerSwitch(true); + } +} + +void TTrain::OnCommand_waterpumpbreakeropen(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggWaterPumpBreakerButton.UpdateValue(0.0, Train->dsbSwitch); + + if (false == Train->mvControlled->WaterPump.breaker) + { + return; + } // already enabled + + Train->mvControlled->WaterPumpBreakerSwitch(false); + } +} + +void TTrain::OnCommand_waterpumptoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggWaterPumpButton.type() == TGaugeType::push) + { + // impulse switch + // currently there's no off button so we always try to turn it on + OnCommand_waterpumpenable(Train, Command); + } + else + { + // two-state switch + if (Command.action == GLFW_RELEASE) + { + return; + } + + if (false == Train->mvControlled->WaterPump.is_enabled) + { + // turn on + OnCommand_waterpumpenable(Train, Command); + } + else + { + // turn off + OnCommand_waterpumpdisable(Train, Command); + } + } +} + +void TTrain::OnCommand_waterpumpenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggWaterPumpButton.type() == TGaugeType::push) + { + // impulse switch + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggWaterPumpButton.UpdateValue(1.0, Train->dsbSwitch); + Train->mvControlled->WaterPumpSwitch(true); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggWaterPumpButton.UpdateValue(0.0, Train->dsbSwitch); + Train->mvControlled->WaterPumpSwitch(false); + } + } + else + { + // two-state switch, only cares about press events + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggWaterPumpButton.UpdateValue(1.0, Train->dsbSwitch); + Train->mvControlled->WaterPumpSwitch(true); + Train->mvControlled->WaterPumpSwitchOff(false); + } + } +} + +void TTrain::OnCommand_waterpumpdisable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggWaterPumpButton.type() == TGaugeType::push) + { + // impulse switch + // currently there's no disable return type switch + return; + } + else + { + // two-state switch, only cares about press events + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggWaterPumpButton.UpdateValue(0.0, Train->dsbSwitch); + Train->mvControlled->WaterPumpSwitch(false); + Train->mvControlled->WaterPumpSwitchOff(true); + } + } +} + +void TTrain::OnCommand_watercircuitslinktoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->mvControlled->WaterCircuitsLink) + { + // turn on + OnCommand_watercircuitslinkenable(Train, Command); + } + else + { + // turn off + OnCommand_watercircuitslinkdisable(Train, Command); + } + } +} + +void TTrain::OnCommand_watercircuitslinkenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggWaterCircuitsLinkButton.UpdateValue(1.0, Train->dsbSwitch); + + if (true == Train->mvControlled->WaterCircuitsLink) + { + return; + } // already enabled + + Train->mvControlled->WaterCircuitsLinkSwitch(true); + } +} + +void TTrain::OnCommand_watercircuitslinkdisable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggWaterCircuitsLinkButton.UpdateValue(0.0, Train->dsbSwitch); + + if (false == Train->mvControlled->WaterCircuitsLink) + { + return; + } // already disabled + + Train->mvControlled->WaterCircuitsLinkSwitch(false); + } +} + +void TTrain::OnCommand_convertertoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const overloadrelayisopen{(Train->Dynamic()->Mechanik != nullptr ? Train->Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : Train->mvOccupied->ConvOvldFlag)}; + + if (Train->mvOccupied->ConvSwitchType != "impulse" ? Train->ggConverterButton.GetValue() < 0.5 : false == Train->mvOccupied->Power110vIsAvailable && false == overloadrelayisopen) + { + // turn on + OnCommand_converterenable(Train, Command); + } + else + { + // turn off + OnCommand_converterdisable(Train, Command); + } + } + else if (Command.action == GLFW_RELEASE) + { + // on button release... + if (Train->mvOccupied->ConvSwitchType == "impulse") + { + // ...return switches to start position if applicable + Train->ggConverterButton.UpdateValue(0.0, Train->dsbSwitch); + Train->ggConverterOffButton.UpdateValue(0.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_converterenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggConverterButton.UpdateValue(1.0, Train->dsbSwitch); + + // impulse type switch has no effect if there's no power + // NOTE: this is most likely setup wrong, but the whole thing is smoke and mirrors anyway + if (Train->mvOccupied->ConvSwitchType != "impulse" || Train->mvControlled->Mains) + { + // won't start if the line breaker button is still held + Train->mvOccupied->ConverterSwitch(true); + } + } + else if (Command.action == GLFW_RELEASE) + { + // potentially reset impulse switch position, using shared code branch + OnCommand_convertertoggle(Train, Command); + } +} + +void TTrain::OnCommand_converterdisable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggConverterButton.UpdateValue(0.0, Train->dsbSwitch); + if (Train->ggConverterOffButton.SubModel != nullptr) + { + Train->ggConverterOffButton.UpdateValue(1.0, Train->dsbSwitch); + } + + Train->mvOccupied->ConverterSwitch(false); + } + else if (Command.action == GLFW_RELEASE) + { + // potentially reset impulse switch position, using shared code branch + OnCommand_convertertoggle(Train, Command); + } +} + +void TTrain::OnCommand_convertertogglelocal(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->ConverterStart == start_t::automatic) + { + // let the automatic thing do its automatic thing... + return; + } + if (Train->ggConverterLocalButton.SubModel == nullptr) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->mvOccupied->ConverterAllowLocal && Train->ggConverterLocalButton.GetValue() < 0.5) + { + // turn on + // visual feedback + Train->ggConverterLocalButton.UpdateValue(1.0, Train->dsbSwitch); + // effect + Train->mvOccupied->ConverterAllowLocal = true; + /* + if( true == Train->mvControlled->ConverterSwitch( true, range::local ) ) { + // side effects + // control the compressor, if it's paired with the converter + if( Train->mvControlled->CompressorPower == 2 ) { + // hunter-091012: tak jest poprawnie + Train->mvControlled->CompressorSwitch( true, range::local ); + } + } + */ + } + else + { + // turn off + // visual feedback + Train->ggConverterLocalButton.UpdateValue(0.0, Train->dsbSwitch); + // effect + Train->mvOccupied->ConverterAllowLocal = false; + /* + if( true == Train->mvControlled->ConverterSwitch( false, range::local ) ) { + // side effects + // control the compressor, if it's paired with the converter + if( Train->mvControlled->CompressorPower == 2 ) { + // hunter-091012: tak jest poprawnie + Train->mvControlled->CompressorSwitch( false, range::local ); + } + // if there's no (low voltage) power source left, drop pantographs + if( false == Train->mvControlled->Battery ) { + Train->mvControlled->PantFront( false, range::local ); + Train->mvControlled->PantRear( false, range::local ); + } + } + */ + } + } +} + +void TTrain::OnCommand_converteroverloadrelayreset(TTrain *Train, command_data const &Command) +{ + + if (Train->ggConverterFuseButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Converter Overload Relay Reset button is missing, or wasn't defined"); + } + // return; + } + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggConverterFuseButton.UpdateValue(1.0, Train->dsbSwitch); + + Train->mvControlled->RelayReset(relay_t::primaryconverteroverload); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggConverterFuseButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_compressortoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const compressorisenabled{(Train->Dynamic()->Mechanik ? Train->Dynamic()->Mechanik->IsAnyCompressorEnabled : Train->mvOccupied->CompressorAllow)}; + + if (false == compressorisenabled) + { + // turn on + OnCommand_compressorenable(Train, Command); + } + else + { + // turn off + OnCommand_compressordisable(Train, Command); + } + } + /* + // disabled because we don't have yet support for compressor switch type definition + else if( Command.action == GLFW_RELEASE ) { + // on button release... + if( Train->mvOccupied->CompSwitchType == "impulse" ) { + // ...return switches to start position if applicable + Train->ggCompressorButton.UpdateValue( 0.0, Train->dsbSwitch ); + Train->ggCompressorOffButton.UpdateValue( 0.0, Train->dsbSwitch ); + } + } + */ +} + +void TTrain::OnCommand_compressorenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggCompressorButton.UpdateValue(1.0, Train->dsbSwitch); + + // impulse type switch has no effect if there's no power + // NOTE: this is most likely setup wrong, but the whole thing is smoke and mirrors anyway + // if( ( Train->mvOccupied->CompSwitchType != "impulse" ) + // || ( Train->mvControlled->Mains ) ) { + + Train->mvOccupied->CompressorSwitch(true); + // } + } + else if (Command.action == GLFW_RELEASE) + { + // potentially reset impulse switch position, using shared code branch + OnCommand_compressortoggle(Train, Command); + } +} + +void TTrain::OnCommand_compressordisable(TTrain *Train, command_data const &Command) +{ + + if (Train->mvControlled->CompressorPower >= 2) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggCompressorButton.UpdateValue(0.0, Train->dsbSwitch); + /* + if( Train->ggCompressorOffButton.SubModel != nullptr ) { + Train->ggCompressorOffButton.UpdateValue( 1.0, Train->dsbSwitch ); + } + */ + Train->mvOccupied->CompressorSwitch(false); + } + else if (Command.action == GLFW_RELEASE) + { + // potentially reset impulse switch position, using shared code branch + OnCommand_compressortoggle(Train, Command); + } +} + +void TTrain::OnCommand_compressortogglelocal(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->CompressorPower >= 2) + { + return; + } + if (Train->ggCompressorLocalButton.SubModel == nullptr) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->mvOccupied->CompressorAllowLocal) + { + // turn on + // visual feedback + Train->ggCompressorLocalButton.UpdateValue(1.0, Train->dsbSwitch); + // effect + Train->mvOccupied->CompressorAllowLocal = true; + } + else + { + // turn off + // visual feedback + Train->ggCompressorLocalButton.UpdateValue(0.0, Train->dsbSwitch); + // effect + Train->mvOccupied->CompressorAllowLocal = false; + } + } +} + +void TTrain::OnCommand_compressorpresetactivatenext(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->CompressorListPosNo == 0) + { + return; + } + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggCompressorListButton.type() == TGaugeType::push) + { + // impulse switch + if (Train->mvOccupied->CompressorListPosNo < Train->mvOccupied->CompressorListDefPos + 1) + { + return; + } + + Train->mvOccupied->ChangeCompressorPreset(Command.action == GLFW_PRESS ? Train->mvOccupied->CompressorListDefPos + 1 : Train->mvOccupied->CompressorListDefPos); + // visual feedback + Train->ggCompressorListButton.UpdateValue(static_cast(Train->mvOccupied->CompressorListPos - 1), Train->dsbSwitch); + } + else + { + // multi-state switch + if (Command.action == GLFW_RELEASE) + { + return; + } + + if (Train->mvOccupied->CompressorListPos < Train->mvOccupied->CompressorListPosNo || true == Train->mvOccupied->CompressorListWrap) + { + // active light preset is stored as value in range 1-LigthPosNo + Train->mvOccupied->ChangeCompressorPreset(Train->mvOccupied->CompressorListPos < Train->mvOccupied->CompressorListPosNo ? Train->mvOccupied->CompressorListPos + 1 : 1); // wrap mode + // visual feedback + Train->ggCompressorListButton.UpdateValue(static_cast(Train->mvOccupied->CompressorListPos - 1), Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_compressorpresetactivateprevious(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->CompressorListPosNo == 0) + { + return; + } + if (Command.action != GLFW_PRESS) + { + return; + } // one change per key press + + if (Train->ggCompressorListButton.type() == TGaugeType::push) + { + // impulse switch toggles only between positions 'default' and 'default+1' + return; + } + + if (Train->mvOccupied->CompressorListPos > 1 || true == Train->mvOccupied->CompressorListWrap) + { + // active light preset is stored as value in range 1-LigthPosNo + Train->mvOccupied->ChangeCompressorPreset(Train->mvOccupied->CompressorListPos > 1 ? Train->mvOccupied->CompressorListPos - 1 : Train->mvOccupied->CompressorListPosNo); // wrap mode + + // visual feedback + if (Train->ggCompressorListButton.SubModel != nullptr) + { + Train->ggCompressorListButton.UpdateValue(static_cast(Train->mvOccupied->CompressorListPos - 1), Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_compressorpresetactivatedefault(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->CompressorListPosNo == 0) + { + return; + } + if (Command.action != GLFW_PRESS) + { + return; + } // one change per key press + + Train->mvOccupied->ChangeCompressorPreset(Train->mvOccupied->CompressorListDefPos); + + // visual feedback + if (Train->ggCompressorListButton.SubModel != nullptr) + { + Train->ggCompressorListButton.UpdateValue(static_cast(Train->mvOccupied->CompressorListPos - 1), Train->dsbSwitch); + } +} + +void TTrain::OnCommand_motorblowerstogglefront(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggMotorBlowersFrontButton.type() == TGaugeType::push) + { + // impulse switch + // currently there's no off button so we always try to turn it on + OnCommand_motorblowersenablefront(Train, Command); + } + else + { + // two-state switch + if (Command.action == GLFW_RELEASE) + { + return; + } + + if (false == Train->mvControlled->MotorBlowers[end::front].is_enabled) + { + // turn on + OnCommand_motorblowersenablefront(Train, Command); + } + else + { + // turn off + OnCommand_motorblowersdisablefront(Train, Command); + } + } +} + +void TTrain::OnCommand_motorblowersenablefront(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggMotorBlowersFrontButton.type() == TGaugeType::push) + { + // impulse switch + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggMotorBlowersFrontButton.UpdateValue(1.f, Train->dsbSwitch); + Train->mvControlled->MotorBlowersSwitch(true, end::front); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggMotorBlowersFrontButton.UpdateValue(0.f, Train->dsbSwitch); + Train->mvControlled->MotorBlowersSwitch(false, end::front); + } + } + else + { + // two-state switch, only cares about press events + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggMotorBlowersFrontButton.UpdateValue(1.f, Train->dsbSwitch); + Train->mvControlled->MotorBlowersSwitch(true, end::front); + Train->mvControlled->MotorBlowersSwitchOff(false, end::front); + } + } +} + +void TTrain::OnCommand_motorblowersdisablefront(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggMotorBlowersFrontButton.type() == TGaugeType::push) + { + // impulse switch + // currently there's no disable return type switch + return; + } + else + { + // two-state switch, only cares about press events + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggMotorBlowersFrontButton.UpdateValue(0.f, Train->dsbSwitch); + Train->mvControlled->MotorBlowersSwitch(false, end::front); + Train->mvControlled->MotorBlowersSwitchOff(true, end::front); + } + } +} + +void TTrain::OnCommand_motorblowerstogglerear(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggMotorBlowersRearButton.type() == TGaugeType::push) + { + // impulse switch + // currently there's no off button so we always try to turn it on + OnCommand_motorblowersenablerear(Train, Command); + } + else + { + // two-state switch + if (Command.action == GLFW_RELEASE) + { + return; + } + + if (false == Train->mvControlled->MotorBlowers[end::rear].is_enabled) + { + // turn on + OnCommand_motorblowersenablerear(Train, Command); + } + else + { + // turn off + OnCommand_motorblowersdisablerear(Train, Command); + } + } +} + +void TTrain::OnCommand_motorblowersenablerear(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggMotorBlowersRearButton.type() == TGaugeType::push) + { + // impulse switch + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggMotorBlowersRearButton.UpdateValue(1.f, Train->dsbSwitch); + Train->mvControlled->MotorBlowersSwitch(true, end::rear); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggMotorBlowersRearButton.UpdateValue(0.f, Train->dsbSwitch); + Train->mvControlled->MotorBlowersSwitch(false, end::rear); + } + } + else + { + // two-state switch, only cares about press events + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggMotorBlowersRearButton.UpdateValue(1.f, Train->dsbSwitch); + Train->mvControlled->MotorBlowersSwitch(true, end::rear); + Train->mvControlled->MotorBlowersSwitchOff(false, end::rear); + } + } +} + +void TTrain::OnCommand_motorblowersdisablerear(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggMotorBlowersRearButton.type() == TGaugeType::push) + { + // impulse switch + // currently there's no disable return type switch + return; + } + else + { + // two-state switch, only cares about press events + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggMotorBlowersRearButton.UpdateValue(0.f, Train->dsbSwitch); + Train->mvControlled->MotorBlowersSwitch(false, end::rear); + Train->mvControlled->MotorBlowersSwitchOff(true, end::rear); + } + } +} + +void TTrain::OnCommand_motorblowersdisableall(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggMotorBlowersAllOffButton.type() == TGaugeType::push) + { + // impulse switch + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggMotorBlowersAllOffButton.UpdateValue(1.f, Train->dsbSwitch); + Train->mvControlled->MotorBlowersSwitchOff(true, end::front); + Train->mvControlled->MotorBlowersSwitchOff(true, end::rear); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggMotorBlowersAllOffButton.UpdateValue(0.f, Train->dsbSwitch); + Train->mvControlled->MotorBlowersSwitchOff(false, end::front); + Train->mvControlled->MotorBlowersSwitchOff(false, end::rear); + } + } + else + { + // two-state switch, only cares about press events + // NOTE: generally this switch doesn't come in two-state form + if (Command.action == GLFW_PRESS) + { + if (Train->ggMotorBlowersAllOffButton.GetDesiredValue() < 0.5f) + { + // switch is off, activate + Train->mvControlled->MotorBlowersSwitchOff(true, end::front); + Train->mvControlled->MotorBlowersSwitchOff(true, end::rear); + // visual feedback + Train->ggMotorBlowersRearButton.UpdateValue(1.f, Train->dsbSwitch); + } + else + { + // deactivate + Train->mvControlled->MotorBlowersSwitchOff(false, end::front); + Train->mvControlled->MotorBlowersSwitchOff(false, end::rear); + // visual feedback + Train->ggMotorBlowersRearButton.UpdateValue(0.f, Train->dsbSwitch); + } + } + } +} + +void TTrain::OnCommand_coolingfanstoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_PRESS) + { + return; + } + + Train->mvControlled->RVentForceOn = !Train->mvControlled->RVentForceOn; +} diff --git a/vehicle/cab/brakecommands.cpp b/vehicle/cab/brakecommands.cpp new file mode 100644 index 000000000..6ebf453a2 --- /dev/null +++ b/vehicle/cab/brakecommands.cpp @@ -0,0 +1,943 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the commands of the brakes: the independent, the train, the manual and the spring brake handles, the sand + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/mover.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +void TTrain::OnCommand_independentbrakeincrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + + // when SplitEDPneumaticBrake is active the local brake key always operates + // the pneumatic local brake directly, never piggy-backing on the joint controller + auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; + auto const useStepped{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; + if (Train->mvOccupied->LocalBrake != TLocalBrake::ManualBrake) + { + if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->mvOccupied->MainCtrlPos > 0) + { + OnCommand_mastercontrollerdecrease(Train, Command); + } + else + { + Train->mvOccupied->IncLocalBrakeLevel(useStepped ? 1 : static_cast(Global.brake_speed * Command.time_delta * LocalBrakePosNo)); + if (useStepped) + { + Train->m_mastercontrollerinuse = true; + } + } + } + } +} + +void TTrain::OnCommand_independentbrakeincreasefast(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + + auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; + auto const useJointAnim{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; + if (Train->mvOccupied->LocalBrake != TLocalBrake::ManualBrake) + { + if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->mvOccupied->MainCtrlPos > 0) + { + OnCommand_mastercontrollerdecreasefast(Train, Command); + } + else + { + Train->mvOccupied->IncLocalBrakeLevel(LocalBrakePosNo); + if (useJointAnim) + { + Train->m_mastercontrollerinuse = true; + } + } + } + } +} + +void TTrain::OnCommand_independentbrakedecrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + + auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; + auto const useStepped{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; + if (Train->mvOccupied->LocalBrake != TLocalBrake::ManualBrake + // Ra 1014-06: AI potrafi zahamować pomocniczym mimo jego braku - odhamować jakoś trzeba + // TODO: sort AI out so it doesn't do things it doesn't have equipment for + || Train->mvOccupied->LocalBrakePosA > 0) + { + if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->mvOccupied->LocalBrakePosA == 0.0) + { + OnCommand_mastercontrollerincrease(Train, Command); + } + else + { + Train->mvOccupied->DecLocalBrakeLevel(useStepped ? 1 : static_cast(Global.brake_speed * Command.time_delta * LocalBrakePosNo)); + if (useStepped) + { + Train->m_mastercontrollerinuse = true; + } + } + } + } +} + +void TTrain::OnCommand_independentbrakedecreasefast(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + + auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; + auto const useJointAnim{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; + if (Train->mvOccupied->LocalBrake != TLocalBrake::ManualBrake + // Ra 1014-06: AI potrafi zahamować pomocniczym mimo jego braku - odhamować jakoś trzeba + // TODO: sort AI out so it doesn't do things it doesn't have equipment for + || Train->mvOccupied->LocalBrakePosA > 0) + { + if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->mvOccupied->LocalBrakePosA == 0.0) + { + OnCommand_mastercontrollerincreasefast(Train, Command); + } + else + { + Train->mvOccupied->DecLocalBrakeLevel(LocalBrakePosNo); + if (useJointAnim) + { + Train->m_mastercontrollerinuse = true; + } + } + } + } +} + +void TTrain::OnCommand_independentbrakeset(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + + Train->mvOccupied->LocalBrakePosA = std::clamp(Command.param1, 0.0, 1.0); + } + /* + Train->mvControlled->LocalBrakePos = ( + std::round( + interpolate( + 0.0, + LocalBrakePosNo, + clamp( + Command.param1, + 0.0, 1.0 ) ) ) ); + */ +} + +void TTrain::OnCommand_independentbrakebailoff(TTrain *Train, command_data const &Command) +{ + + if (false == Command.freefly) + { + // TODO: check if this set of conditions can be simplified. + // it'd be more flexible to have an attribute indicating whether bail off position is supported + if (Train->mvControlled->TrainType != train_type::emu && + (Train->mvControlled->EngineType == TEngineType::ElectricSeriesMotor || Train->mvControlled->EngineType == TEngineType::DieselElectric || + Train->mvControlled->EngineType == TEngineType::ElectricInductionMotor) && + Train->mvOccupied->BrakeCtrlPosNo > 0) + { + + if (Command.action == GLFW_PRESS) + { + // press or hold + // visual feedback + Train->ggReleaserButton.UpdateValue(1.0, Train->dsbSwitch); + + Train->mvOccupied->BrakeReleaser(1); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggReleaserButton.UpdateValue(0.0, Train->dsbSwitch); + + Train->mvOccupied->BrakeReleaser(0); + } + } + } + else + { + // car brake handling, while in walk mode + auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + if (vehicle != nullptr) + { + if (Command.action == GLFW_PRESS) + { + // press or hold + vehicle->MoverParameters->BrakeReleaser(1); + } + else if (Command.action == GLFW_RELEASE) + { + // release + vehicle->MoverParameters->BrakeReleaser(0); + } + } + } +} + +void TTrain::OnCommand_universalbrakebutton1(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // press or hold + // visual feedback + Train->ggUniveralBrakeButton1.UpdateValue(1.0, Train->dsbSwitch); + + Train->mvOccupied->UniversalBrakeButton(0, 1); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggUniveralBrakeButton1.UpdateValue(0.0, Train->dsbSwitch); + + Train->mvOccupied->UniversalBrakeButton(0, 0); + } +} + +void TTrain::OnCommand_universalbrakebutton2(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // press or hold + // visual feedback + Train->ggUniveralBrakeButton2.UpdateValue(1.0, Train->dsbSwitch); + + Train->mvOccupied->UniversalBrakeButton(1, 1); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggUniveralBrakeButton2.UpdateValue(0.0, Train->dsbSwitch); + + Train->mvOccupied->UniversalBrakeButton(1, 0); + } +} + +void TTrain::OnCommand_universalbrakebutton3(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // press or hold + // visual feedback + Train->ggUniveralBrakeButton3.UpdateValue(1.0, Train->dsbSwitch); + + Train->mvOccupied->UniversalBrakeButton(2, 1); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggUniveralBrakeButton3.UpdateValue(0.0, Train->dsbSwitch); + + Train->mvOccupied->UniversalBrakeButton(2, 0); + } +} + +void TTrain::OnCommand_trainbrakeincrease(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_REPEAT && Train->mvOccupied->BrakeHandle == TBrakeHandle::FV4a) + Train->mvOccupied->BrakeLevelAdd(Global.brake_speed * Command.time_delta * Train->mvOccupied->BrakeCtrlPosNo); + else if (Command.action == GLFW_PRESS && Train->mvOccupied->BrakeHandle != TBrakeHandle::FV4a) + Train->set_train_brake(Train->mvOccupied->fBrakeCtrlPos + Global.fBrakeStep); +} + +void TTrain::OnCommand_trainbrakedecrease(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_REPEAT && Train->mvOccupied->BrakeHandle == TBrakeHandle::FV4a) + Train->mvOccupied->BrakeLevelAdd(-Global.brake_speed * Command.time_delta * Train->mvOccupied->BrakeCtrlPosNo); + else if (Command.action == GLFW_PRESS && Train->mvOccupied->BrakeHandle != TBrakeHandle::FV4a) + Train->set_train_brake(Train->mvOccupied->fBrakeCtrlPos - Global.fBrakeStep); + else if (Command.action == GLFW_RELEASE) + { + // release + Train->zero_charging_train_brake(); + } +} + +void TTrain::OnCommand_trainbrakeset(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + // press or hold + Train->mvOccupied->BrakeLevelSet(std::lerp(Train->mvOccupied->Handle->GetPos(bh_MIN), Train->mvOccupied->Handle->GetPos(bh_MAX), std::clamp(Command.param1, 0.0, 1.0))); + } + else + { + // release + Train->zero_charging_train_brake(); + } +} + +void TTrain::OnCommand_trainbrakecharging(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + // press or hold + Train->set_train_brake(-1); + } + else + { + // release + Train->zero_charging_train_brake(); + } +} + +void TTrain::OnCommand_trainbrakerelease(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + Train->set_train_brake(0); + } +} + +void TTrain::OnCommand_trainbrakefirstservice(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + Train->set_train_brake(1); + } +} + +void TTrain::OnCommand_trainbrakeservice(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + Train->set_train_brake(Train->mvOccupied->BrakeCtrlPosNo / 2 + (Train->mvOccupied->BrakeHandle == TBrakeHandle::FV4a ? 1 : 0)); + } +} + +void TTrain::OnCommand_trainbrakefullservice(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + Train->set_train_brake(Train->mvOccupied->BrakeCtrlPosNo - 1); + } +} + +void TTrain::OnCommand_trainbrakehandleoff(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + Train->set_train_brake(Train->mvOccupied->Handle->GetPos(bh_NP)); + } +} + +void TTrain::OnCommand_trainbrakeemergency(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + Train->set_train_brake(Train->mvOccupied->Handle->GetPos(bh_EB)); + /* + if( Train->mvOccupied->BrakeCtrlPosNo <= 0.1 ) { + // hamulec bezpieczeństwa dla wagonów + Train->mvOccupied->RadioStopFlag = true; + } + */ + } +} + +void TTrain::OnCommand_trainbrakebasepressureincrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + + if (Train->mvOccupied->BrakeHandle == TBrakeHandle::FV4a) + { + Train->mvOccupied->BrakeCtrlPos2 = std::clamp(Train->mvOccupied->BrakeCtrlPos2 - 0.01, -1.5, 2.0); + } + else + { + Train->mvOccupied->BrakeLevelAdd(0.01); + } + } +} + +void TTrain::OnCommand_trainbrakebasepressuredecrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + + if (Train->mvOccupied->BrakeHandle == TBrakeHandle::FV4a) + { + Train->mvOccupied->BrakeCtrlPos2 = std::clamp(Train->mvOccupied->BrakeCtrlPos2 + 0.01, -1.5, 2.0); + } + else + { + Train->mvOccupied->BrakeLevelAdd(-0.01); + } + } +} + +void TTrain::OnCommand_trainbrakebasepressurereset(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + Train->mvOccupied->BrakeCtrlPos2 = 0; + } +} + +void TTrain::OnCommand_trainbrakeoperationtoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + auto const *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + if (vehicle == nullptr) + { + return; + } + + vehicle->MoverParameters->Hamulec->SetBrakeStatus(vehicle->MoverParameters->Hamulec->GetBrakeStatus() ^ b_dmg); + // the brake is the player's now, the wagon inspector won't put it back on its own + vehicle->MoverParameters->BrakeCutOutByInspector = false; + } +} + +void TTrain::OnCommand_manualbrakeincrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + + auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + if (vehicle == nullptr) + { + return; + } + + if (vehicle->MoverParameters->LocalBrake == TLocalBrake::ManualBrake || vehicle->MoverParameters->MBrake == true) + { + + vehicle->MoverParameters->IncManualBrakeLevel(1); + } + } +} + +void TTrain::OnCommand_manualbrakedecrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + + auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + if (vehicle == nullptr) + { + return; + } + + if (vehicle->MoverParameters->LocalBrake == TLocalBrake::ManualBrake || vehicle->MoverParameters->MBrake == true) + { + + vehicle->MoverParameters->DecManualBrakeLevel(1); + } + } +} + +void TTrain::OnCommand_alarmchaintoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + if (false == Train->mvOccupied->AlarmChainFlag) + { + OnCommand_alarmchainenable(Train, Command); + } + else + { + OnCommand_alarmchaindisable(Train, Command); + } + } +} + +void TTrain::OnCommand_alarmchainenable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + + // pull + Train->mvOccupied->AlarmChainSwitch(true); + // visual feedback + Train->ggAlarmChain.UpdateValue(1.0); + } +} + +void TTrain::OnCommand_alarmchaindisable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + + // release + Train->mvOccupied->AlarmChainSwitch(false); + // visual feedback + Train->ggAlarmChain.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_wheelspinbrakeactivate(TTrain *Train, command_data const &Command) +{ + + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + if (Train->ggAntiSlipButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Wheelspin Brake button is missing, or wasn't defined"); + } + return; + } + + if (Train->mvOccupied->BrakeSystem != TBrakeSystem::ElectroPneumatic) + { + // standard behaviour + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggAntiSlipButton.UpdateValue(1.0, Train->dsbSwitch); + + // NOTE: system activation is (repeatedly) done in the train update routine + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggAntiSlipButton.UpdateValue(0.0); + } + } + else + { + // electro-pneumatic, custom case + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggAntiSlipButton.UpdateValue(1.0, Train->dsbPneumaticSwitch); + + // the EP fuse is the cab car's (Ctrl+Z switches mvOccupied's), checked by SwitchEPBrake with the rest of + // the control's supply + if (Train->mvOccupied->BrakeHandle == TBrakeHandle::St113) + { + Train->mvOccupied->SwitchEPBrake(1); + } + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggAntiSlipButton.UpdateValue(0.0); + + Train->mvOccupied->SwitchEPBrake(0); + } + } +} + +void TTrain::OnCommand_sandboxactivate(TTrain *Train, command_data const &Command) +{ + + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + if (Train->ggSandButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Sandbox activation button is missing, or wasn't defined"); + } + return; + } + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggSandButton.UpdateValue(1.0, Train->dsbSwitch); + + Train->mvControlled->SandboxManual(true); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggSandButton.UpdateValue(0.0); + + Train->mvControlled->SandboxManual(false); + } +} + +void TTrain::OnCommand_autosandboxtoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->mvOccupied->SandDoseAutoAllow) + { + // turn on + OnCommand_autosandboxactivate(Train, Command); + } + else + { + // turn off + OnCommand_autosandboxdeactivate(Train, Command); + } + } +}; + +void TTrain::OnCommand_autosandboxactivate(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->mvOccupied->SandboxAutoAllow(true); + Train->ggAutoSandButton.UpdateValue(1.0, Train->dsbSwitch); + } +}; + +void TTrain::OnCommand_autosandboxdeactivate(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->mvOccupied->SandboxAutoAllow(false); + Train->ggAutoSandButton.UpdateValue(0.0, Train->dsbSwitch); + } +}; + +void TTrain::OnCommand_epbrakecontrolenable(TTrain *Train, command_data const &Command) +{ + auto const istoggle{(static_cast(Train->ggEPFuseButton.type()) & static_cast(TGaugeType::toggle)) != 0}; + // command only works for bistable switch + if (Command.action == GLFW_PRESS && istoggle) + { + if (Train->mvOccupied->EpFuseSwitch(true)) + { + // audio feedback + if (Train->dsbPneumaticSwitch) + { + Train->dsbPneumaticSwitch->play(); + } + Train->ggEPFuseButton.UpdateValue(1.0f, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_epbrakecontroldisable(TTrain *Train, command_data const &Command) +{ + auto const istoggle{(static_cast(Train->ggEPFuseButton.type()) & static_cast(TGaugeType::toggle)) != 0}; + // command only works for bistable switch + if (Command.action == GLFW_PRESS && istoggle) + { + if (Train->mvOccupied->EpFuseSwitch(false)) + { + Train->ggEPFuseButton.UpdateValue(0.0f, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_epbrakecontroltoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + auto const ispush{(static_cast(Train->ggEPFuseButton.type()) & static_cast(TGaugeType::push)) != 0}; + auto const istoggle{(static_cast(Train->ggEPFuseButton.type()) & static_cast(TGaugeType::toggle)) != 0}; + + if (Command.action == GLFW_PRESS) + { + if (istoggle) + { + // switch state + if (false == Train->mvOccupied->EpFuse) + { + // turn on + // audio feedback + if (Train->mvOccupied->EpFuseSwitch(true) && Train->dsbPneumaticSwitch) + { + Train->dsbPneumaticSwitch->play(); + } + } + else + { + // turn off + Train->mvOccupied->EpFuseSwitch(false); + } + } + else if (ispush) + { + // potentially turn on + // audio feedback + if (Train->mvOccupied->EpFuseSwitch(true) && Train->dsbPneumaticSwitch) + { + Train->dsbPneumaticSwitch->play(); + } + } + // visual feedback + Train->ggEPFuseButton.UpdateValue(ispush ? 1.0f : // push or pushtoggle + Train->mvOccupied->EpFuse ? 1.0f : + 0.0f, // toggle + Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE && ispush) + { + // return the switch to neutral position + Train->ggEPFuseButton.UpdateValue(0.0f, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_trainbrakeoperationmodeincrease(TTrain *Train, command_data const &Command) +{ + + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Command.action == GLFW_PRESS && (Train->mvOccupied->BrakeOpModeFlag << 1 & Train->mvOccupied->BrakeOpModes) != 0) + { + // next mode + Train->mvOccupied->BrakeOpModeFlag <<= 1; + // visual feedback + Train->ggBrakeOperationModeCtrl.UpdateValue(Train->mvOccupied->BrakeOpModeFlag > 0 ? static_cast(std::log2(Train->mvOccupied->BrakeOpModeFlag)) : 0); // audio fallback + } +} + +void TTrain::OnCommand_trainbrakeoperationmodedecrease(TTrain *Train, command_data const &Command) +{ + + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Command.action == GLFW_PRESS && (Train->mvOccupied->BrakeOpModeFlag >> 1 & Train->mvOccupied->BrakeOpModes) != 0) + { + // previous mode + Train->mvOccupied->BrakeOpModeFlag >>= 1; + // visual feedback + Train->ggBrakeOperationModeCtrl.UpdateValue(Train->mvOccupied->BrakeOpModeFlag > 0 ? static_cast(std::log2(Train->mvOccupied->BrakeOpModeFlag)) : 0); + } +} + +void TTrain::OnCommand_brakeactingspeedincrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + if (vehicle == nullptr) + { + return; + } + + if ((vehicle->MoverParameters->BrakeDelayFlag & bdelay_M) != 0) + { + // can't speed it up any more than this + return; + } + auto const fasterbrakesetting = vehicle->MoverParameters->BrakeDelayFlag < bdelay_R ? vehicle->MoverParameters->BrakeDelayFlag << 1 : vehicle->MoverParameters->BrakeDelayFlag | bdelay_M; + + Train->set_train_brake_speed(vehicle, fasterbrakesetting); + } +} + +void TTrain::OnCommand_brakeactingspeeddecrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + if (vehicle == nullptr) + { + return; + } + + if (vehicle->MoverParameters->BrakeDelayFlag == bdelay_G) + { + // can't slow it down any more than this + return; + } + auto const slowerbrakesetting = vehicle->MoverParameters->BrakeDelayFlag < bdelay_M ? vehicle->MoverParameters->BrakeDelayFlag >> 1 : vehicle->MoverParameters->BrakeDelayFlag ^ bdelay_M; + + Train->set_train_brake_speed(vehicle, slowerbrakesetting); + } +} + +void TTrain::OnCommand_brakeactingspeedsetcargo(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + if (vehicle == nullptr) + { + return; + } + + Train->set_train_brake_speed(vehicle, bdelay_G); + } +} + +void TTrain::OnCommand_brakeactingspeedsetpassenger(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + if (vehicle == nullptr) + { + return; + } + + Train->set_train_brake_speed(vehicle, bdelay_P); + } +} + +void TTrain::OnCommand_brakeactingspeedsetrapid(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + if (vehicle == nullptr) + { + return; + } + + Train->set_train_brake_speed(vehicle, bdelay_R); + } +} + +void TTrain::OnCommand_brakeloadcompensationincrease(TTrain *Train, command_data const &Command) +{ + + if (true == Command.freefly && Command.action == GLFW_PRESS) + { + auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + if (vehicle != nullptr) + { + vehicle->MoverParameters->IncBrakeMult(); + } + } +} + +void TTrain::OnCommand_brakeloadcompensationdecrease(TTrain *Train, command_data const &Command) +{ + + if (true == Command.freefly && Command.action == GLFW_PRESS) + { + auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + if (vehicle != nullptr) + { + vehicle->MoverParameters->DecBrakeMult(); + } + } +} + +void TTrain::OnCommand_mubrakingindicatortoggle(TTrain *Train, command_data const &Command) +{ + + if (Train->ggSignallingButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Braking Indicator switch is missing, or wasn't defined"); + } + return; + } + if (Train->mvControlled->TrainType != train_type::emu) + { + // + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->mvControlled->Signalling) + { + // turn on + Train->mvControlled->Signalling = true; + // visual feedback + Train->ggSignallingButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // turn off + Train->mvControlled->Signalling = false; + // visual feedback + Train->ggSignallingButton.UpdateValue(0.0, Train->dsbSwitch); + } + } +} diff --git a/vehicle/cab/cab.cpp b/vehicle/cab/cab.cpp new file mode 100644 index 000000000..bc5bc11a5 --- /dev/null +++ b/vehicle/cab/cab.cpp @@ -0,0 +1,235 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the cab: its gauges, its buttons, the mapping of the controls, the screens it has + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/mover.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + +void control_mapper::clear() +{ + + *this = control_mapper(); +} + +void control_mapper::insert(TGauge const &Gauge, std::string const &Label) +{ + + if (Gauge.SubModel != nullptr) + { + m_controlnames.try_emplace(Gauge.SubModel, Label); + } + if (Gauge.SubModelOn != nullptr) + { + m_controlnames.try_emplace(Gauge.SubModelOn, Label); + } + // the duplicate submodels of a control (duplicate: yes) work the control as well (eu07/maszyna#527) + for (auto const &mirror : Gauge.mirrors()) + { + insert(mirror, Label); + } + + m_names.emplace(Label); +} + +std::string control_mapper::find(TSubModel const *Control) const +{ + + auto const lookup = m_controlnames.find(Control); + if (lookup != m_controlnames.end()) + { + return lookup->second; + } + else + { + return ""; + } +} + +bool control_mapper::contains(std::string const &Control) const +{ + + return m_names.contains(Control); +} + +void TTrain::screen_entry::deserialize(cParser &Input) +{ + + while (true == deserialize_mapping(Input)) + { + // all work done by while() + } +} + +bool TTrain::screen_entry::deserialize_mapping(cParser &Input) +{ + // token can be a key or block end + auto const key{Input.getToken(true, "\n\r\t ,;[]")}; + + if (true == key.empty() || key == "}") + { + return false; + } + + if (key == "{") + { + script = Input.getToken(); + } + else if (key == "target:") + { + target = Input.getToken(); + } + else if (key == "updatetime:") + { + updatetime = Input.getToken(); + } + else if (key == "parameters:") + { + parameters = dictionary_source(Input.getToken()); + } + else + { + // HACK: we expect this to be true only if the screen entry doesn't start with a { which means legacy configuration format + target = key; + script = Input.getToken(); + return false; + } + + return true; +} + +void TCab::Load(cParser &Parser) +{ + // NOTE: clearing control tables here is bit of a crutch, imposed by current scheme of loading compartments anew on each cab change + ggList.clear(); + btList.clear(); + + std::string token; + Parser.getTokens(); + Parser >> token; + if (token == "cablight:") + { + Parser.getTokens(9, false); + /* + Parser + >> dimm.r + >> dimm.g + >> dimm.b + >> intlit.r + >> intlit.g + >> intlit.b + >> intlitlow.r + >> intlitlow.g + >> intlitlow.b; + */ + Parser.getTokens(); + Parser >> token; + } + CabPos1.x = static_cast(std::stod(token)); + Parser.getTokens(5, false); + Parser >> CabPos1.y >> CabPos1.z >> CabPos2.x >> CabPos2.y >> CabPos2.z; + + bEnabled = true; + bOccupied = true; +} + +TGauge &TCab::Gauge(int n) +{ // pobranie adresu obiektu aniomowanego ruchem + /* + if (n < 0) + { // rezerwacja wolnego + ggList[iGauges].Clear(); + return ggList + iGauges++; + } + else if (n < iGauges) + return ggList + n; + return NULL; + */ + if (n < 0) + { + ggList.emplace_back(); + return ggList.back(); + } + else + { + return ggList[n]; + } +}; + +TButton &TCab::Button(int n) +{ // pobranie adresu obiektu animowanego wyborem 1 z 2 + /* + if (n < 0) + { // rezerwacja wolnego + return btList + iButtons++; + } + else if (n < iButtons) + return btList + n; + return NULL; + */ + if (n < 0) + { + btList.emplace_back(); + return btList.back(); + } + else + { + return btList[n]; + } +}; + +void TCab::Update(bool const Power) +{ // odczyt parametrów i ustawienie animacji submodelom + for (auto &gauge : ggList) + { + // animacje izometryczne + gauge.UpdateValue(); // odczyt parametru i przeliczenie na kąt + gauge.Update(); // ustawienie animacji + } + + for (auto &button : btList) + { + // animacje dwustanowe + button.Update(Power); // odczyt parametru i wybór submodelu + } +}; diff --git a/vehicle/cab/cabcommands.cpp b/vehicle/cab/cabcommands.cpp new file mode 100644 index 000000000..496fbb917 --- /dev/null +++ b/vehicle/cab/cabcommands.cpp @@ -0,0 +1,650 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the commands of the cab itself: the reverser, the battery, its activation, changing it + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/mover.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +void TTrain::OnCommand_wiperswitchincrease(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + Train->mvOccupied->wiperSwitchPos++; + if (Train->mvOccupied->wiperSwitchPos > Train->mvOccupied->WiperListSize - 1) + Train->mvOccupied->wiperSwitchPos = Train->mvOccupied->WiperListSize - 1; + + // Visual feedback + Train->ggWiperSw.UpdateValue(static_cast(Train->mvOccupied->wiperSwitchPos), Train->dsbSwitch); + } +} +void TTrain::OnCommand_wiperswitchdecrease(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + Train->mvOccupied->wiperSwitchPos--; + if (Train->mvOccupied->wiperSwitchPos < 0) + Train->mvOccupied->wiperSwitchPos = 0; + + // visual feedback + Train->ggWiperSw.UpdateValue(static_cast(Train->mvOccupied->wiperSwitchPos), Train->dsbSwitch); + } +} + +void TTrain::OnCommand_reverserincrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + // HACK: master controller position isn't set in occupied vehicle in E(D)MUs + // so we do a manual check in relevant vehicle here + if (false == Train->mvControlled->EIMDirectionChangeAllow()) + { + return; + } + + // aktualizacja skrajnych pojazdów w składzie + if (Train->mvOccupied->DirectionForward() && Train->mvOccupied->DirActive && Train->DynamicObject->Mechanik) + { + + Train->DynamicObject->Mechanik->DirectionChange(); + } + } +} + +void TTrain::OnCommand_reverserdecrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + // HACK: master controller position isn't set in occupied vehicle in E(D)MUs + // so we do a manual check in relevant vehicle here + if (false == Train->mvControlled->EIMDirectionChangeAllow()) + { + return; + } + + // aktualizacja skrajnych pojazdów w składzie + if (Train->mvOccupied->DirectionBackward() && Train->mvOccupied->DirActive && Train->DynamicObject->Mechanik) + { + + Train->DynamicObject->Mechanik->DirectionChange(); + } + } +} + +void TTrain::OnCommand_reverserforwardhigh(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + // HACK: master controller position isn't set in occupied vehicle in E(D)MUs + // so we do a manual check in relevant vehicle here + if (false == Train->mvControlled->EIMDirectionChangeAllow()) + { + return; + } + + // HACK: try to move the reverser one position back, in case it's set to "high forward" + OnCommand_reverserdecrease(Train, Command); + + if (Train->mvOccupied->DirActive < 1) + { + + while (Train->mvOccupied->DirActive < 1 && true == Train->mvOccupied->DirectionForward()) + { + // all work is done in the header + } + // aktualizacja skrajnych pojazdów w składzie + if (Train->mvOccupied->DirActive == 1 && Train->DynamicObject->Mechanik) + { + + Train->DynamicObject->Mechanik->DirectionChange(); + } + } + OnCommand_reverserincrease(Train, Command); + } +} + +void TTrain::OnCommand_reverserforward(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + // HACK: master controller position isn't set in occupied vehicle in E(D)MUs + // so we do a manual check in relevant vehicle here + if (false == Train->mvControlled->EIMDirectionChangeAllow()) + { + return; + } + + // HACK: try to move the reverser one position back, in case it's set to "high forward" + // OnCommand_reverserdecrease( Train, Command ); + // visual feedback + Train->ggDirForwardButton.UpdateValue(1.0, Train->dsbSwitch); + + if (Train->mvOccupied->DirActive == 0) + { + + while (Train->mvOccupied->DirActive < 1 && true == Train->mvOccupied->DirectionForward()) + { + // all work is done in the header + } + // aktualizacja skrajnych pojazdów w składzie + if (Train->mvOccupied->DirActive == 1 && Train->DynamicObject->Mechanik) + { + + Train->DynamicObject->Mechanik->DirectionChange(); + } + } + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggDirForwardButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_reverserneutral(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + // HACK: master controller position isn't set in occupied vehicle in E(D)MUs + // so we do a manual check in relevant vehicle here + if (false == Train->mvControlled->EIMDirectionChangeAllow()) + { + return; + } + // visual feedback + Train->ggDirNeutralButton.UpdateValue(1.0, Train->dsbSwitch); + while (Train->mvOccupied->DirActive < 0 && true == Train->mvOccupied->DirectionForward()) + { + // all work is done in the header + } + while (Train->mvOccupied->DirActive > 0 && true == Train->mvOccupied->DirectionBackward()) + { + // all work is done in the header + } + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggDirNeutralButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_reverserbackward(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + // HACK: master controller position isn't set in occupied vehicle in E(D)MUs + // so we do a manual check in relevant vehicle here + if (false == Train->mvControlled->EIMDirectionChangeAllow()) + { + return; + } + Train->ggDirBackwardButton.UpdateValue(1.0, Train->dsbSwitch); + if (Train->mvOccupied->DirActive == 0) + { + + while (Train->mvOccupied->DirActive > -1 && true == Train->mvOccupied->DirectionBackward()) + { + // all work is done in the header + } + // aktualizacja skrajnych pojazdów w składzie + if (Train->mvOccupied->DirActive == -1 && Train->DynamicObject->Mechanik) + { + + Train->DynamicObject->Mechanik->DirectionChange(); + } + } + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggDirBackwardButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_alerteracknowledge(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggSecurityResetButton.UpdateValue(1.0, Train->dsbSwitch); + + if (Train->mvOccupied->TrainType == train_type::emu || Train->mvOccupied->DirActive != 0) + Train->mvOccupied->SecuritySystem.acknowledge_press(); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggSecurityResetButton.UpdateValue(0.0); + + if (Train->mvOccupied->TrainType == train_type::emu || Train->mvOccupied->DirActive != 0) + Train->mvOccupied->SecuritySystem.acknowledge_release(); + } +} + +void TTrain::OnCommand_cabsignalacknowledge(TTrain *Train, command_data const &Command) +{ + // TODO: visual feedback + if (Command.action == GLFW_PRESS) + { + if (Train->mvOccupied->SecuritySystem.has_separate_acknowledge()) + { + Train->mvOccupied->SecuritySystem.cabsignal_reset(); + Train->ggSHPResetButton.UpdateValue(1.0, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + Train->ggSHPResetButton.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_batterytoggle(TTrain *Train, command_data const &Command) +{ + if (Train->allowBatteryToggle || Command.action != GLFW_REPEAT) + { + // keep the switch from flipping back and forth if key is held down + if (false == Train->mvOccupied->Power24vIsAvailable) + { + // turn on + OnCommand_batteryenable(Train, Command); + } + else + { + // turn off + OnCommand_batterydisable(Train, Command); + } + } +} + +void TTrain::OnCommand_batteryenable(TTrain *Train, command_data const &Command) +{ + if (!Train->mvOccupied->isBatteryButtonImpulse) + { // regular button behavior + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); + Train->ggBatteryOnButton.UpdateValue(1.0f, Train->dsbSwitch); + + Train->mvOccupied->BatterySwitch(true); + Train->allowBatteryToggle = false; + // side-effects + if (Train->mvOccupied->LightsPosNo > 0) + { + Train->Dynamic()->SetLights(); + } + } + else if (Command.action == GLFW_RELEASE) + { + if (Train->ggBatteryButton.type() == TGaugeType::push) + { + // return the switch to neutral position + Train->ggBatteryButton.UpdateValue(0.5f); + } + Train->ggBatteryOnButton.UpdateValue(0.0f, Train->dsbSwitch); + Train->allowBatteryToggle = true; + } + } + else // impulse button behavior + { + if (Command.action == GLFW_PRESS) + { + if (Train->mvOccupied->shouldHoldBatteryButton) + { + // jesli przycisk trzeba przytrzymac + Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); + Train->ggBatteryOnButton.UpdateValue(1.0f, Train->dsbSwitch); + Train->fBatteryTimer = Train->mvOccupied->BatteryButtonHoldTime; // start timer + } + else + { + // jesli przycisk dziala od razu + Train->mvOccupied->BatterySwitch(true); + Train->allowBatteryToggle = false; + // side-effects + if (Train->mvOccupied->LightsPosNo > 0) + { + Train->Dynamic()->SetLights(); + } + + // visual feedback + Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); + Train->ggBatteryOnButton.UpdateValue(1.0f, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggBatteryButton.UpdateValue(0.0f, Train->dsbSwitch); + Train->ggBatteryOnButton.UpdateValue(0.0f, Train->dsbSwitch); + Train->fBatteryTimer = -1.f; // + Train->allowBatteryToggle = true; + Train->mvOccupied->batterySwAlreadyFired = false; + } + else if (Command.action == GLFW_REPEAT && Train->mvOccupied->shouldHoldBatteryButton) + { + // trzymamy przycisk + if (Train->fBatteryTimer <= 0.0 && Train->mvOccupied->Battery == false && !Train->mvOccupied->batterySwAlreadyFired) + { + Train->mvOccupied->BatterySwitch(true); + Train->mvOccupied->batterySwAlreadyFired = true; + + // side-effects + if (Train->mvOccupied->LightsPosNo > 0) + { + Train->Dynamic()->SetLights(); + } + Train->allowBatteryToggle = false; + } + } + } +} + +void TTrain::OnCommand_batterydisable(TTrain *Train, command_data const &Command) +{ + if (!Train->mvOccupied->isBatteryButtonImpulse) + { // regular button behavior + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggBatteryButton.UpdateValue(0.0f, Train->dsbSwitch); + Train->ggBatteryOffButton.UpdateValue(1.0f, Train->dsbSwitch); + + Train->mvOccupied->BatterySwitch(false); + + // side-effects + if (Train->mvOccupied->LightsPosNo > 0) + { + Train->Dynamic()->SetLights(); + } + } + else if (Command.action == GLFW_RELEASE) + { + if (Train->ggBatteryButton.type() == TGaugeType::push) + { + // return the switch to neutral position + Train->ggBatteryButton.UpdateValue(0.5f); + } + Train->ggBatteryOffButton.UpdateValue(0.0f, Train->dsbSwitch); + } + } + else // impulse button behavior + { + if (Command.action == GLFW_PRESS) + { + if (Train->mvOccupied->shouldHoldBatteryButton) + { + // jesli przycisk trzeba przytrzymac + Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); + Train->ggBatteryOffButton.UpdateValue(1.0f, Train->dsbSwitch); + Train->fBatteryTimer = Train->mvOccupied->BatteryButtonHoldTime; // start timer + } + else + { + // jesli przycisk dziala od razu + Train->mvOccupied->BatterySwitch(false); + Train->allowBatteryToggle = false; + + // side-effects + if (Train->mvOccupied->LightsPosNo > 0) + { + Train->Dynamic()->SetLights(); + } + // visual feedback + Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); + Train->ggBatteryOffButton.UpdateValue(1.0f, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggBatteryButton.UpdateValue(0.0f, Train->dsbSwitch); + Train->ggBatteryOffButton.UpdateValue(0.0f, Train->dsbSwitch); + Train->allowBatteryToggle = true; + Train->mvOccupied->batterySwAlreadyFired = false; + } + else if (Command.action == GLFW_REPEAT && Train->mvOccupied->shouldHoldBatteryButton) + { + // trzymamy przycisk + if (Train->fBatteryTimer <= 0.0 && Train->mvOccupied->Battery == true && !Train->mvOccupied->batterySwAlreadyFired) + { + Train->mvOccupied->BatterySwitch(false); + Train->mvOccupied->batterySwAlreadyFired = true; + + // side-effects + if (Train->mvOccupied->LightsPosNo > 0) + { + Train->Dynamic()->SetLights(); + } + Train->allowBatteryToggle = false; + } + } + } +} + +void TTrain::OnCommand_cabactivationtoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_REPEAT) + { + // keep the switch from flipping back and forth if key is held down + if (0 == Train->mvOccupied->CabActive) + { + // turn on + OnCommand_cabactivationenable(Train, Command); + } + else + { + // turn off + OnCommand_cabactivationdisable(Train, Command); + } + } +} + +void TTrain::OnCommand_cabactivationenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + if (Train->ggCabActivationButton.type() == TGaugeType::push) + { + Train->ggCabActivationButton.UpdateValue(1.0f, Train->dsbSwitch); + } + + Train->mvOccupied->CabActivisation(); + + // side-effects + if (Train->mvOccupied->LightsPosNo > 0) + { + Train->Dynamic()->SetLights(); + } + } + else if (Command.action == GLFW_RELEASE && Train->ggCabActivationButton.type() == TGaugeType::push) + { + // return the switch to neutral position + Train->ggCabActivationButton.UpdateValue(0.5f); + } +} + +void TTrain::OnCommand_cabactivationdisable(TTrain *Train, command_data const &Command) +{ + // TBD, TODO: ewentualnie zablokować z FIZ, np. w samochodach się nie odłącza akumulatora + if (Command.action == GLFW_PRESS) + { + // visual feedback + if (Train->ggCabActivationButton.type() == TGaugeType::push) + { + Train->ggCabActivationButton.UpdateValue(0.0f, Train->dsbSwitch); + } + + Train->mvOccupied->CabDeactivisation(); + if (Train->mvOccupied->LightsPosNo > 0 && Train->mvOccupied->InactiveCabFlag & activation::redmarkers) + { + Train->Dynamic()->SetLights(); + } + } + else if (Command.action == GLFW_RELEASE && Train->ggCabActivationButton.type() == TGaugeType::push) + { + // return the switch to neutral position + Train->ggCabActivationButton.UpdateValue(0.5f); + } +} + +void TTrain::OnCommand_cabchangeforward(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + if (auto const movedirection{1}; false == Train->CabChange(movedirection)) + { + auto const exitdirection{(movedirection > 0 ? end::front : end::rear)}; + if (Train->mvOccupied->Couplers[exitdirection].CouplingFlag.HasAll(Coupling::gangway)) + { + // przejscie do nastepnego pojazdu + auto *targetvehicle = exitdirection == end::front ? Train->DynamicObject->PrevConnected() : Train->DynamicObject->NextConnected(); + targetvehicle->MoverParameters->CabOccupied = Train->mvOccupied->Neighbours[exitdirection].vehicle_end ? -1 : 1; + Train->MoveToVehicle(targetvehicle); + } + } + // HACK: match consist door permit state with the preset in the active cab + if (Train->ggDoorPermitPresetButton.SubModel != nullptr) + { + Train->mvOccupied->ChangeDoorPermitPreset(0); + } + // HACK: update lights state + if (Train->mvOccupied->LightsPosNo > 0) + { + Train->DynamicObject->SetLights(); + } + } +} + +void TTrain::OnCommand_cabchangebackward(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + if (auto const movedirection{-1}; false == Train->CabChange(movedirection)) + { + // current vehicle doesn't extend any farther in this direction, check if we there's one connected we can move to + auto const exitdirection{(movedirection > 0 ? end::front : end::rear)}; + if (Train->mvOccupied->Couplers[exitdirection].CouplingFlag.HasAll(Coupling::gangway)) + { + // przejscie do nastepnego pojazdu + auto *targetvehicle = exitdirection == end::front ? Train->DynamicObject->PrevConnected() : Train->DynamicObject->NextConnected(); + targetvehicle->MoverParameters->CabOccupied = Train->mvOccupied->Neighbours[exitdirection].vehicle_end ? -1 : 1; + Train->MoveToVehicle(targetvehicle); + } + } + // HACK: match consist door permit state with the preset in the active cab + if (Train->ggDoorPermitPresetButton.SubModel != nullptr) + { + Train->mvOccupied->ChangeDoorPermitPreset(0); + } + // HACK: update lights state + if (Train->mvOccupied->LightsPosNo > 0) + { + Train->DynamicObject->SetLights(); + } + } +} + +void TTrain::OnCommand_vehiclemoveforwards(TTrain *Train, const command_data &Command) +{ + if (Command.action == GLFW_RELEASE || !DebugModeFlag) + return; + + Train->DynamicObject->move_set(100.0); +} + +void TTrain::OnCommand_vehiclemovebackwards(TTrain *Train, const command_data &Command) +{ + if (Command.action == GLFW_RELEASE || !DebugModeFlag) + return; + + Train->DynamicObject->move_set(-100.0); +} + +void TTrain::OnCommand_vehicleboost(TTrain *Train, const command_data &Command) +{ + if (Command.action == GLFW_RELEASE || !DebugModeFlag) + return; + + double boost = Command.param1 != 0.0 ? Command.param1 : 2.78; + + if (Train->DynamicObject == nullptr) + { + return; + } + + auto *vehicle{Train->DynamicObject}; + while (vehicle) + { + vehicle->MoverParameters->V += vehicle->DirectionGet() * boost; + vehicle = vehicle->Next(); // pozostałe też + } + vehicle = Train->DynamicObject->Prev(); + while (vehicle) + { + vehicle->MoverParameters->V += vehicle->DirectionGet() * boost; + vehicle = vehicle->Prev(); // w drugą stronę też + } +} diff --git a/vehicle/cab/commandtable.cpp b/vehicle/cab/commandtable.cpp new file mode 100644 index 000000000..e0632a5fb --- /dev/null +++ b/vehicle/cab/commandtable.cpp @@ -0,0 +1,455 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the handlers of the commands of the cab + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/mover.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +// NOTE: we're currently using universal handlers and static handler map but it may be beneficial to have these implemented on individual class instance basis +// TBD, TODO: consider this approach if we ever want to have customized consist behaviour to received commands, based on the consist/vehicle type or whatever +TTrain::commandhandler_map const TTrain::m_commandhandlers = { + + {user_command::aidriverenable, &TTrain::OnCommand_aidriverenable}, + {user_command::aidriverdisable, &TTrain::OnCommand_aidriverdisable}, + {user_command::jointcontrollerset, &TTrain::OnCommand_jointcontrollerset}, + {user_command::mastercontrollerincrease, &TTrain::OnCommand_mastercontrollerincrease}, + {user_command::mastercontrollerincreasefast, &TTrain::OnCommand_mastercontrollerincreasefast}, + {user_command::mastercontrollerdecrease, &TTrain::OnCommand_mastercontrollerdecrease}, + {user_command::mastercontrollerdecreasefast, &TTrain::OnCommand_mastercontrollerdecreasefast}, + {user_command::mastercontrollerset, &TTrain::OnCommand_mastercontrollerset}, + {user_command::secondcontrollerincrease, &TTrain::OnCommand_secondcontrollerincrease}, + {user_command::secondcontrollerincreasefast, &TTrain::OnCommand_secondcontrollerincreasefast}, + {user_command::secondcontrollerdecrease, &TTrain::OnCommand_secondcontrollerdecrease}, + {user_command::secondcontrollerdecreasefast, &TTrain::OnCommand_secondcontrollerdecreasefast}, + {user_command::secondcontrollerset, &TTrain::OnCommand_secondcontrollerset}, + {user_command::dynamicbrakecontrollerincrease, &TTrain::OnCommand_DynamicBrakeControllerIncrease}, + {user_command::dynamicbrakecontrollerincreasefast, &TTrain::OnCommand_DynamicBrakeControllerIncreaseFast}, + {user_command::dynamicbrakecontrollerdecrease, &TTrain::OnCommand_DynamicBrakeControllerDecrease}, + {user_command::dynamicbrakecontrollerdecreasefast, &TTrain::OnCommand_DynamicBrakeControllerDecreaseFast}, + {user_command::dynamicbrakecontrollerset, &TTrain::OnCommand_DynamicBrakeControllerSet}, + {user_command::notchingrelaytoggle, &TTrain::OnCommand_notchingrelaytoggle}, + {user_command::tempomattoggle, &TTrain::OnCommand_tempomattoggle}, + {user_command::mucurrentindicatorothersourceactivate, &TTrain::OnCommand_mucurrentindicatorothersourceactivate}, + {user_command::independentbrakeincrease, &TTrain::OnCommand_independentbrakeincrease}, + {user_command::independentbrakeincreasefast, &TTrain::OnCommand_independentbrakeincreasefast}, + {user_command::independentbrakedecrease, &TTrain::OnCommand_independentbrakedecrease}, + {user_command::independentbrakedecreasefast, &TTrain::OnCommand_independentbrakedecreasefast}, + {user_command::independentbrakeset, &TTrain::OnCommand_independentbrakeset}, + {user_command::independentbrakebailoff, &TTrain::OnCommand_independentbrakebailoff}, + {user_command::universalbrakebutton1, &TTrain::OnCommand_universalbrakebutton1}, + {user_command::universalbrakebutton2, &TTrain::OnCommand_universalbrakebutton2}, + {user_command::universalbrakebutton3, &TTrain::OnCommand_universalbrakebutton3}, + {user_command::trainbrakeincrease, &TTrain::OnCommand_trainbrakeincrease}, + {user_command::trainbrakedecrease, &TTrain::OnCommand_trainbrakedecrease}, + {user_command::trainbrakeset, &TTrain::OnCommand_trainbrakeset}, + {user_command::trainbrakecharging, &TTrain::OnCommand_trainbrakecharging}, + {user_command::trainbrakerelease, &TTrain::OnCommand_trainbrakerelease}, + {user_command::trainbrakefirstservice, &TTrain::OnCommand_trainbrakefirstservice}, + {user_command::trainbrakeservice, &TTrain::OnCommand_trainbrakeservice}, + {user_command::trainbrakefullservice, &TTrain::OnCommand_trainbrakefullservice}, + {user_command::trainbrakehandleoff, &TTrain::OnCommand_trainbrakehandleoff}, + {user_command::trainbrakeemergency, &TTrain::OnCommand_trainbrakeemergency}, + {user_command::trainbrakebasepressureincrease, &TTrain::OnCommand_trainbrakebasepressureincrease}, + {user_command::trainbrakebasepressuredecrease, &TTrain::OnCommand_trainbrakebasepressuredecrease}, + {user_command::trainbrakebasepressurereset, &TTrain::OnCommand_trainbrakebasepressurereset}, + {user_command::trainbrakeoperationtoggle, &TTrain::OnCommand_trainbrakeoperationtoggle}, + {user_command::manualbrakeincrease, &TTrain::OnCommand_manualbrakeincrease}, + {user_command::manualbrakedecrease, &TTrain::OnCommand_manualbrakedecrease}, + {user_command::alarmchaintoggle, &TTrain::OnCommand_alarmchaintoggle}, + {user_command::alarmchainenable, &TTrain::OnCommand_alarmchainenable}, + {user_command::alarmchaindisable, &TTrain::OnCommand_alarmchaindisable}, + {user_command::wheelspinbrakeactivate, &TTrain::OnCommand_wheelspinbrakeactivate}, + {user_command::sandboxactivate, &TTrain::OnCommand_sandboxactivate}, + {user_command::autosandboxtoggle, &TTrain::OnCommand_autosandboxtoggle}, + {user_command::autosandboxactivate, &TTrain::OnCommand_autosandboxactivate}, + {user_command::autosandboxdeactivate, &TTrain::OnCommand_autosandboxdeactivate}, + {user_command::epbrakecontroltoggle, &TTrain::OnCommand_epbrakecontroltoggle}, + {user_command::epbrakecontrolenable, &TTrain::OnCommand_epbrakecontrolenable}, + {user_command::epbrakecontroldisable, &TTrain::OnCommand_epbrakecontroldisable}, + {user_command::trainbrakeoperationmodeincrease, &TTrain::OnCommand_trainbrakeoperationmodeincrease}, + {user_command::trainbrakeoperationmodedecrease, &TTrain::OnCommand_trainbrakeoperationmodedecrease}, + {user_command::brakeactingspeedincrease, &TTrain::OnCommand_brakeactingspeedincrease}, + {user_command::brakeactingspeeddecrease, &TTrain::OnCommand_brakeactingspeeddecrease}, + {user_command::brakeactingspeedsetcargo, &TTrain::OnCommand_brakeactingspeedsetcargo}, + {user_command::brakeactingspeedsetpassenger, &TTrain::OnCommand_brakeactingspeedsetpassenger}, + {user_command::brakeactingspeedsetrapid, &TTrain::OnCommand_brakeactingspeedsetrapid}, + {user_command::brakeloadcompensationincrease, &TTrain::OnCommand_brakeloadcompensationincrease}, + {user_command::brakeloadcompensationdecrease, &TTrain::OnCommand_brakeloadcompensationdecrease}, + {user_command::mubrakingindicatortoggle, &TTrain::OnCommand_mubrakingindicatortoggle}, + {user_command::reverserincrease, &TTrain::OnCommand_reverserincrease}, + {user_command::reverserdecrease, &TTrain::OnCommand_reverserdecrease}, + {user_command::reverserforwardhigh, &TTrain::OnCommand_reverserforwardhigh}, + {user_command::reverserforward, &TTrain::OnCommand_reverserforward}, + {user_command::reverserneutral, &TTrain::OnCommand_reverserneutral}, + {user_command::reverserbackward, &TTrain::OnCommand_reverserbackward}, + {user_command::alerteracknowledge, &TTrain::OnCommand_alerteracknowledge}, + {user_command::cabsignalacknowledge, &TTrain::OnCommand_cabsignalacknowledge}, + {user_command::batterytoggle, &TTrain::OnCommand_batterytoggle}, + {user_command::batteryenable, &TTrain::OnCommand_batteryenable}, + {user_command::batterydisable, &TTrain::OnCommand_batterydisable}, + {user_command::cabactivationtoggle, &TTrain::OnCommand_cabactivationtoggle}, + {user_command::cabactivationenable, &TTrain::OnCommand_cabactivationenable}, + {user_command::cabactivationdisable, &TTrain::OnCommand_cabactivationdisable}, + {user_command::pantographcompressorvalvetoggle, &TTrain::OnCommand_pantographcompressorvalvetoggle}, + {user_command::pantographcompressorvalveenable, &TTrain::OnCommand_pantographcompressorvalveenable}, + {user_command::pantographcompressorvalvedisable, &TTrain::OnCommand_pantographcompressorvalvedisable}, + {user_command::pantographcompressoractivate, &TTrain::OnCommand_pantographcompressoractivate}, + {user_command::pantographtogglefront, &TTrain::OnCommand_pantographtogglefront}, + {user_command::pantographtogglerear, &TTrain::OnCommand_pantographtogglerear}, + {user_command::pantographraisefront, &TTrain::OnCommand_pantographraisefront}, + {user_command::pantographraiserear, &TTrain::OnCommand_pantographraiserear}, + {user_command::pantographlowerfront, &TTrain::OnCommand_pantographlowerfront}, + {user_command::pantographlowerrear, &TTrain::OnCommand_pantographlowerrear}, + + {user_command::wiperswitchincrease, &TTrain::OnCommand_wiperswitchincrease}, + {user_command::wiperswitchdecrease, &TTrain::OnCommand_wiperswitchdecrease}, + + {user_command::lightsset, &TTrain::OnCommand_lightsset}, + + {user_command::pantographlowerall, &TTrain::OnCommand_pantographlowerall}, + {user_command::pantographselectnext, &TTrain::OnCommand_pantographselectnext}, + {user_command::pantographselectprevious, &TTrain::OnCommand_pantographselectprevious}, + {user_command::pantographtoggleselected, &TTrain::OnCommand_pantographtoggleselected}, + {user_command::pantographraiseselected, &TTrain::OnCommand_pantographraiseselected}, + {user_command::pantographlowerselected, &TTrain::OnCommand_pantographlowerselected}, + {user_command::pantographvalvesupdate, &TTrain::OnCommand_pantographvalvesupdate}, + {user_command::pantographvalvesoff, &TTrain::OnCommand_pantographvalvesoff}, + {user_command::linebreakertoggle, &TTrain::OnCommand_linebreakertoggle}, + {user_command::linebreakeropen, &TTrain::OnCommand_linebreakeropen}, + {user_command::linebreakerclose, &TTrain::OnCommand_linebreakerclose}, + {user_command::linebreakertoggleb, &TTrain::OnCommand_linebreakertoggleremote}, + {user_command::linebreakeropenb, &TTrain::OnCommand_linebreakeropenremote}, + {user_command::linebreakercloseb, &TTrain::OnCommand_linebreakercloseremote}, + {user_command::linebreakertogglec, &TTrain::OnCommand_linebreakertoggleremote}, + {user_command::linebreakeropenc, &TTrain::OnCommand_linebreakeropenremote}, + {user_command::linebreakerclosec, &TTrain::OnCommand_linebreakercloseremote}, + {user_command::fuelpumptoggle, &TTrain::OnCommand_fuelpumptoggle}, + {user_command::fuelpumpenable, &TTrain::OnCommand_fuelpumpenable}, + {user_command::fuelpumpdisable, &TTrain::OnCommand_fuelpumpdisable}, + {user_command::oilpumptoggle, &TTrain::OnCommand_oilpumptoggle}, + {user_command::oilfuelpumptoggle, &TTrain::OnCommand_oilfuelpumptoggle}, + {user_command::oilpumpenable, &TTrain::OnCommand_oilpumpenable}, + {user_command::oilpumpdisable, &TTrain::OnCommand_oilpumpdisable}, + {user_command::tractionmodetoggle, &TTrain::OnCommand_tractionmodetoggle}, + {user_command::tractionmodecatenary, &TTrain::OnCommand_tractionmodecatenary}, + {user_command::tractionmodegenset, &TTrain::OnCommand_tractionmodegenset}, + {user_command::gensettoggle, &TTrain::OnCommand_gensettoggle}, + {user_command::gensetenable, &TTrain::OnCommand_gensetenable}, + {user_command::gensetdisable, &TTrain::OnCommand_gensetdisable}, + {user_command::waterheaterbreakertoggle, &TTrain::OnCommand_waterheaterbreakertoggle}, + {user_command::waterheaterbreakerclose, &TTrain::OnCommand_waterheaterbreakerclose}, + {user_command::waterheaterbreakeropen, &TTrain::OnCommand_waterheaterbreakeropen}, + {user_command::waterheatertoggle, &TTrain::OnCommand_waterheatertoggle}, + {user_command::waterheaterenable, &TTrain::OnCommand_waterheaterenable}, + {user_command::waterheaterdisable, &TTrain::OnCommand_waterheaterdisable}, + {user_command::waterpumpbreakertoggle, &TTrain::OnCommand_waterpumpbreakertoggle}, + {user_command::waterpumpbreakerclose, &TTrain::OnCommand_waterpumpbreakerclose}, + {user_command::waterpumpbreakeropen, &TTrain::OnCommand_waterpumpbreakeropen}, + {user_command::waterpumptoggle, &TTrain::OnCommand_waterpumptoggle}, + {user_command::waterpumpenable, &TTrain::OnCommand_waterpumpenable}, + {user_command::waterpumpdisable, &TTrain::OnCommand_waterpumpdisable}, + {user_command::watercircuitslinktoggle, &TTrain::OnCommand_watercircuitslinktoggle}, + {user_command::watercircuitslinkenable, &TTrain::OnCommand_watercircuitslinkenable}, + {user_command::watercircuitslinkdisable, &TTrain::OnCommand_watercircuitslinkdisable}, + {user_command::convertertoggle, &TTrain::OnCommand_convertertoggle}, + {user_command::converterenable, &TTrain::OnCommand_converterenable}, + {user_command::converterdisable, &TTrain::OnCommand_converterdisable}, + {user_command::convertertogglelocal, &TTrain::OnCommand_convertertogglelocal}, + {user_command::converteroverloadrelayreset, &TTrain::OnCommand_converteroverloadrelayreset}, + {user_command::compressortoggle, &TTrain::OnCommand_compressortoggle}, + {user_command::compressorenable, &TTrain::OnCommand_compressorenable}, + {user_command::compressordisable, &TTrain::OnCommand_compressordisable}, + {user_command::compressortogglelocal, &TTrain::OnCommand_compressortogglelocal}, + {user_command::compressorpresetactivatenext, &TTrain::OnCommand_compressorpresetactivatenext}, + {user_command::compressorpresetactivateprevious, &TTrain::OnCommand_compressorpresetactivateprevious}, + {user_command::compressorpresetactivatedefault, &TTrain::OnCommand_compressorpresetactivatedefault}, + {user_command::motorblowerstogglefront, &TTrain::OnCommand_motorblowerstogglefront}, + {user_command::motorblowerstogglerear, &TTrain::OnCommand_motorblowerstogglerear}, + {user_command::motorblowersdisableall, &TTrain::OnCommand_motorblowersdisableall}, + {user_command::coolingfanstoggle, &TTrain::OnCommand_coolingfanstoggle}, + {user_command::motorconnectorsopen, &TTrain::OnCommand_motorconnectorsopen}, + {user_command::motorconnectorsclose, &TTrain::OnCommand_motorconnectorsclose}, + {user_command::motordisconnect, &TTrain::OnCommand_motordisconnect}, + {user_command::motoroverloadrelaythresholdtoggle, &TTrain::OnCommand_motoroverloadrelaythresholdtoggle}, + {user_command::motoroverloadrelaythresholdsetlow, &TTrain::OnCommand_motoroverloadrelaythresholdsetlow}, + {user_command::motoroverloadrelaythresholdsethigh, &TTrain::OnCommand_motoroverloadrelaythresholdsethigh}, + {user_command::motoroverloadrelayreset, &TTrain::OnCommand_motoroverloadrelayreset}, + {user_command::universalrelayreset1, &TTrain::OnCommand_universalrelayreset}, + {user_command::universalrelayreset2, &TTrain::OnCommand_universalrelayreset}, + {user_command::universalrelayreset3, &TTrain::OnCommand_universalrelayreset}, + {user_command::heatingtoggle, &TTrain::OnCommand_heatingtoggle}, + {user_command::heatingenable, &TTrain::OnCommand_heatingenable}, + {user_command::heatingdisable, &TTrain::OnCommand_heatingdisable}, + {user_command::lightspresetactivatenext, &TTrain::OnCommand_lightspresetactivatenext}, + {user_command::lightspresetactivateprevious, &TTrain::OnCommand_lightspresetactivateprevious}, + {user_command::headlighttoggleleft, &TTrain::OnCommand_headlighttoggleleft}, + {user_command::headlightenableleft, &TTrain::OnCommand_headlightenableleft}, + {user_command::headlightdisableleft, &TTrain::OnCommand_headlightdisableleft}, + {user_command::headlighttoggleright, &TTrain::OnCommand_headlighttoggleright}, + {user_command::headlightenableright, &TTrain::OnCommand_headlightenableright}, + {user_command::headlightdisableright, &TTrain::OnCommand_headlightdisableright}, + {user_command::headlighttoggleupper, &TTrain::OnCommand_headlighttoggleupper}, + {user_command::headlightenableupper, &TTrain::OnCommand_headlightenableupper}, + {user_command::headlightdisableupper, &TTrain::OnCommand_headlightdisableupper}, + {user_command::redmarkertoggleleft, &TTrain::OnCommand_redmarkertoggleleft}, + {user_command::redmarkerenableleft, &TTrain::OnCommand_redmarkerenableleft}, + {user_command::redmarkerdisableleft, &TTrain::OnCommand_redmarkerdisableleft}, + {user_command::redmarkertoggleright, &TTrain::OnCommand_redmarkertoggleright}, + {user_command::redmarkerenableright, &TTrain::OnCommand_redmarkerenableright}, + {user_command::redmarkerdisableright, &TTrain::OnCommand_redmarkerdisableright}, + {user_command::headlighttogglerearleft, &TTrain::OnCommand_headlighttogglerearleft}, + {user_command::headlightenablerearleft, &TTrain::OnCommand_headlightenablerearleft}, + {user_command::headlightdisablerearleft, &TTrain::OnCommand_headlightdisablerearleft}, + {user_command::headlighttogglerearright, &TTrain::OnCommand_headlighttogglerearright}, + {user_command::headlightenablerearright, &TTrain::OnCommand_headlightenablerearright}, + {user_command::headlightdisablerearright, &TTrain::OnCommand_headlightdisablerearright}, + {user_command::headlighttogglerearupper, &TTrain::OnCommand_headlighttogglerearupper}, + {user_command::headlightenablerearupper, &TTrain::OnCommand_headlightenablerearupper}, + {user_command::headlightdisablerearupper, &TTrain::OnCommand_headlightdisablerearupper}, + {user_command::modernlightdimmerdecrease, &TTrain::OnCommand_modernlightdimmerdecrease}, + {user_command::modernlightdimmerincrease, &TTrain::OnCommand_modernlightdimmerincrease}, + {user_command::redmarkertogglerearleft, &TTrain::OnCommand_redmarkertogglerearleft}, + {user_command::redmarkerenablerearleft, &TTrain::OnCommand_redmarkerenablerearleft}, + {user_command::redmarkerdisablerearleft, &TTrain::OnCommand_redmarkerdisablerearleft}, + {user_command::redmarkertogglerearright, &TTrain::OnCommand_redmarkertogglerearright}, + {user_command::redmarkerenablerearright, &TTrain::OnCommand_redmarkerenablerearright}, + {user_command::redmarkerdisablerearright, &TTrain::OnCommand_redmarkerdisablerearright}, + {user_command::redmarkerstoggle, &TTrain::OnCommand_redmarkerstoggle}, + {user_command::endsignalstoggle, &TTrain::OnCommand_endsignalstoggle}, + {user_command::headlightsdimtoggle, &TTrain::OnCommand_headlightsdimtoggle}, + {user_command::headlightsdimenable, &TTrain::OnCommand_headlightsdimenable}, + {user_command::headlightsdimdisable, &TTrain::OnCommand_headlightsdimdisable}, + {user_command::interiorlighttoggle, &TTrain::OnCommand_interiorlighttoggle}, + {user_command::interiorlightenable, &TTrain::OnCommand_interiorlightenable}, + {user_command::interiorlightdisable, &TTrain::OnCommand_interiorlightdisable}, + {user_command::interiorlightdimtoggle, &TTrain::OnCommand_interiorlightdimtoggle}, + {user_command::interiorlightdimenable, &TTrain::OnCommand_interiorlightdimenable}, + {user_command::interiorlightdimdisable, &TTrain::OnCommand_interiorlightdimdisable}, + {user_command::compartmentlightstoggle, &TTrain::OnCommand_compartmentlightstoggle}, + {user_command::compartmentlightsenable, &TTrain::OnCommand_compartmentlightsenable}, + {user_command::compartmentlightsdisable, &TTrain::OnCommand_compartmentlightsdisable}, + {user_command::instrumentlighttoggle, &TTrain::OnCommand_instrumentlighttoggle}, + {user_command::instrumentlightenable, &TTrain::OnCommand_instrumentlightenable}, + {user_command::instrumentlightdisable, &TTrain::OnCommand_instrumentlightdisable}, + {user_command::dashboardlighttoggle, &TTrain::OnCommand_dashboardlighttoggle}, + {user_command::dashboardlightenable, &TTrain::OnCommand_dashboardlightenable}, + {user_command::dashboardlightdisable, &TTrain::OnCommand_dashboardlightdisable}, + {user_command::timetablelighttoggle, &TTrain::OnCommand_timetablelighttoggle}, + {user_command::timetablelightenable, &TTrain::OnCommand_timetablelightenable}, + {user_command::timetablelightdisable, &TTrain::OnCommand_timetablelightdisable}, + {user_command::doorlocktoggle, &TTrain::OnCommand_doorlocktoggle}, + {user_command::doortoggleleft, &TTrain::OnCommand_doortoggleleft}, + {user_command::doortoggleright, &TTrain::OnCommand_doortoggleright}, + {user_command::doorpermitleft, &TTrain::OnCommand_doorpermitleft}, + {user_command::doorpermitright, &TTrain::OnCommand_doorpermitright}, + {user_command::doorpermitpresetactivatenext, &TTrain::OnCommand_doorpermitpresetactivatenext}, + {user_command::doorpermitpresetactivateprevious, &TTrain::OnCommand_doorpermitpresetactivateprevious}, + {user_command::dooropenleft, &TTrain::OnCommand_dooropenleft}, + {user_command::dooropenright, &TTrain::OnCommand_dooropenright}, + {user_command::doorcloseleft, &TTrain::OnCommand_doorcloseleft}, + {user_command::doorcloseright, &TTrain::OnCommand_doorcloseright}, + {user_command::dooropenall, &TTrain::OnCommand_dooropenall}, + {user_command::doorcloseall, &TTrain::OnCommand_doorcloseall}, + {user_command::doorsteptoggle, &TTrain::OnCommand_doorsteptoggle}, + {user_command::doormodetoggle, &TTrain::OnCommand_doormodetoggle}, + {user_command::mirrorstoggle, &TTrain::OnCommand_mirrorstoggle}, + {user_command::nearestcarcouplingincrease, &TTrain::OnCommand_nearestcarcouplingincrease}, + {user_command::nearestcarcouplingdisconnect, &TTrain::OnCommand_nearestcarcouplingdisconnect}, + {user_command::nearestcarcoupleradapterattach, &TTrain::OnCommand_nearestcarcoupleradapterattach}, + {user_command::nearestcarcoupleradapterremove, &TTrain::OnCommand_nearestcarcoupleradapterremove}, + {user_command::occupiedcarcouplingdisconnect, &TTrain::OnCommand_occupiedcarcouplingdisconnect}, + {user_command::departureannounce, &TTrain::OnCommand_departureannounce}, + {user_command::hornlowactivate, &TTrain::OnCommand_hornlowactivate}, + {user_command::hornhighactivate, &TTrain::OnCommand_hornhighactivate}, + {user_command::whistleactivate, &TTrain::OnCommand_whistleactivate}, + {user_command::radiotoggle, &TTrain::OnCommand_radiotoggle}, + {user_command::radioenable, &TTrain::OnCommand_radioenable}, + {user_command::radiodisable, &TTrain::OnCommand_radiodisable}, + {user_command::radiochannelincrease, &TTrain::OnCommand_radiochannelincrease}, + {user_command::radiochanneldecrease, &TTrain::OnCommand_radiochanneldecrease}, + {user_command::radiochannelset, &TTrain::OnCommand_radiochannelset}, + {user_command::radiostopsend, &TTrain::OnCommand_radiostopsend}, + {user_command::radiostopenable, &TTrain::OnCommand_radiostopenable}, + {user_command::radiostopdisable, &TTrain::OnCommand_radiostopdisable}, + {user_command::radiostoptest, &TTrain::OnCommand_radiostoptest}, + {user_command::radiocall1send, &TTrain::OnCommand_radiocall1send}, + {user_command::radiocall3send, &TTrain::OnCommand_radiocall3send}, + {user_command::radiovolumeincrease, &TTrain::OnCommand_radiovolumeincrease}, + {user_command::radiovolumedecrease, &TTrain::OnCommand_radiovolumedecrease}, + {user_command::radiovolumeset, &TTrain::OnCommand_radiovolumeset}, + {user_command::fmradiotoggle, &TTrain::OnCommand_fmradiotoggle}, + {user_command::fmradiovolumeincrease, &TTrain::OnCommand_fmradiovolumeincrease}, + {user_command::fmradiovolumedecrease, &TTrain::OnCommand_fmradiovolumedecrease}, + {user_command::fmradiovolumeset, &TTrain::OnCommand_fmradiovolumeset}, + {user_command::fmradiotuneincrease, &TTrain::OnCommand_fmradiotuneincrease}, + {user_command::fmradiotunedecrease, &TTrain::OnCommand_fmradiotunedecrease}, + {user_command::fmradiotuneset, &TTrain::OnCommand_fmradiotuneset}, + {user_command::radiofusetoggle, &TTrain::OnCommand_radiofusetoggle}, + {user_command::radiofuseenable, &TTrain::OnCommand_radiofuseenable}, + {user_command::radiofusedisable, &TTrain::OnCommand_radiofusedisable}, + {user_command::cabchangeforward, &TTrain::OnCommand_cabchangeforward}, + {user_command::cabchangebackward, &TTrain::OnCommand_cabchangebackward}, + {user_command::generictoggle0, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle1, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle2, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle3, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle4, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle5, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle6, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle7, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle8, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle9, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle10, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle11, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle12, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle13, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle14, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle15, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle16, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle17, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle18, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle19, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle20, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle21, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle22, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle23, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle24, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle25, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle26, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle27, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle28, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle29, &TTrain::OnCommand_generictoggle}, + {user_command::genericset0, &TTrain::OnCommand_genericset}, + {user_command::genericset1, &TTrain::OnCommand_genericset}, + {user_command::genericset2, &TTrain::OnCommand_genericset}, + {user_command::genericset3, &TTrain::OnCommand_genericset}, + {user_command::genericset4, &TTrain::OnCommand_genericset}, + {user_command::genericset5, &TTrain::OnCommand_genericset}, + {user_command::genericset6, &TTrain::OnCommand_genericset}, + {user_command::genericset7, &TTrain::OnCommand_genericset}, + {user_command::genericset8, &TTrain::OnCommand_genericset}, + {user_command::genericset9, &TTrain::OnCommand_genericset}, + {user_command::genericset10, &TTrain::OnCommand_genericset}, + {user_command::genericset11, &TTrain::OnCommand_genericset}, + {user_command::genericset12, &TTrain::OnCommand_genericset}, + {user_command::genericset13, &TTrain::OnCommand_genericset}, + {user_command::genericset14, &TTrain::OnCommand_genericset}, + {user_command::genericset15, &TTrain::OnCommand_genericset}, + {user_command::genericset16, &TTrain::OnCommand_genericset}, + {user_command::genericset17, &TTrain::OnCommand_genericset}, + {user_command::genericset18, &TTrain::OnCommand_genericset}, + {user_command::genericset19, &TTrain::OnCommand_genericset}, + {user_command::genericset20, &TTrain::OnCommand_genericset}, + {user_command::genericset21, &TTrain::OnCommand_genericset}, + {user_command::genericset22, &TTrain::OnCommand_genericset}, + {user_command::genericset23, &TTrain::OnCommand_genericset}, + {user_command::genericset24, &TTrain::OnCommand_genericset}, + {user_command::genericset25, &TTrain::OnCommand_genericset}, + {user_command::genericset26, &TTrain::OnCommand_genericset}, + {user_command::genericset27, &TTrain::OnCommand_genericset}, + {user_command::genericset28, &TTrain::OnCommand_genericset}, + {user_command::genericset29, &TTrain::OnCommand_genericset}, + {user_command::vehiclemoveforwards, &TTrain::OnCommand_vehiclemoveforwards}, + {user_command::vehiclemovebackwards, &TTrain::OnCommand_vehiclemovebackwards}, + {user_command::vehicleboost, &TTrain::OnCommand_vehicleboost}, + {user_command::springbraketoggle, &TTrain::OnCommand_springbraketoggle}, + {user_command::springbrakeenable, &TTrain::OnCommand_springbrakeenable}, + {user_command::springbrakedisable, &TTrain::OnCommand_springbrakedisable}, + {user_command::springbrakeshutofftoggle, &TTrain::OnCommand_springbrakeshutofftoggle}, + {user_command::springbrakeshutoffenable, &TTrain::OnCommand_springbrakeshutoffenable}, + {user_command::springbrakeshutoffdisable, &TTrain::OnCommand_springbrakeshutoffdisable}, + {user_command::springbrakerelease, &TTrain::OnCommand_springbrakerelease}, + {user_command::distancecounteractivate, &TTrain::OnCommand_distancecounteractivate}, + {user_command::speedcontrolincrease, &TTrain::OnCommand_speedcontrolincrease}, + {user_command::speedcontroldecrease, &TTrain::OnCommand_speedcontroldecrease}, + {user_command::speedcontrolpowerincrease, &TTrain::OnCommand_speedcontrolpowerincrease}, + {user_command::speedcontrolpowerdecrease, &TTrain::OnCommand_speedcontrolpowerdecrease}, + {user_command::speedcontrolbutton0, &TTrain::OnCommand_speedcontrolbutton}, + {user_command::speedcontrolbutton1, &TTrain::OnCommand_speedcontrolbutton}, + {user_command::speedcontrolbutton2, &TTrain::OnCommand_speedcontrolbutton}, + {user_command::speedcontrolbutton3, &TTrain::OnCommand_speedcontrolbutton}, + {user_command::speedcontrolbutton4, &TTrain::OnCommand_speedcontrolbutton}, + {user_command::speedcontrolbutton5, &TTrain::OnCommand_speedcontrolbutton}, + {user_command::speedcontrolbutton6, &TTrain::OnCommand_speedcontrolbutton}, + {user_command::speedcontrolbutton7, &TTrain::OnCommand_speedcontrolbutton}, + {user_command::speedcontrolbutton8, &TTrain::OnCommand_speedcontrolbutton}, + {user_command::speedcontrolbutton9, &TTrain::OnCommand_speedcontrolbutton}, + {user_command::inverterenable1, &TTrain::OnCommand_inverterenable}, + {user_command::inverterenable2, &TTrain::OnCommand_inverterenable}, + {user_command::inverterenable3, &TTrain::OnCommand_inverterenable}, + {user_command::inverterenable4, &TTrain::OnCommand_inverterenable}, + {user_command::inverterenable5, &TTrain::OnCommand_inverterenable}, + {user_command::inverterenable6, &TTrain::OnCommand_inverterenable}, + {user_command::inverterenable7, &TTrain::OnCommand_inverterenable}, + {user_command::inverterenable8, &TTrain::OnCommand_inverterenable}, + {user_command::inverterenable9, &TTrain::OnCommand_inverterenable}, + {user_command::inverterenable10, &TTrain::OnCommand_inverterenable}, + {user_command::inverterenable11, &TTrain::OnCommand_inverterenable}, + {user_command::inverterenable12, &TTrain::OnCommand_inverterenable}, + {user_command::inverterdisable1, &TTrain::OnCommand_inverterdisable}, + {user_command::inverterdisable2, &TTrain::OnCommand_inverterdisable}, + {user_command::inverterdisable3, &TTrain::OnCommand_inverterdisable}, + {user_command::inverterdisable4, &TTrain::OnCommand_inverterdisable}, + {user_command::inverterdisable5, &TTrain::OnCommand_inverterdisable}, + {user_command::inverterdisable6, &TTrain::OnCommand_inverterdisable}, + {user_command::inverterdisable7, &TTrain::OnCommand_inverterdisable}, + {user_command::inverterdisable8, &TTrain::OnCommand_inverterdisable}, + {user_command::inverterdisable9, &TTrain::OnCommand_inverterdisable}, + {user_command::inverterdisable10, &TTrain::OnCommand_inverterdisable}, + {user_command::inverterdisable11, &TTrain::OnCommand_inverterdisable}, + {user_command::inverterdisable12, &TTrain::OnCommand_inverterdisable}, + {user_command::invertertoggle1, &TTrain::OnCommand_invertertoggle}, + {user_command::invertertoggle2, &TTrain::OnCommand_invertertoggle}, + {user_command::invertertoggle3, &TTrain::OnCommand_invertertoggle}, + {user_command::invertertoggle4, &TTrain::OnCommand_invertertoggle}, + {user_command::invertertoggle5, &TTrain::OnCommand_invertertoggle}, + {user_command::invertertoggle6, &TTrain::OnCommand_invertertoggle}, + {user_command::invertertoggle7, &TTrain::OnCommand_invertertoggle}, + {user_command::invertertoggle8, &TTrain::OnCommand_invertertoggle}, + {user_command::invertertoggle9, &TTrain::OnCommand_invertertoggle}, + {user_command::invertertoggle10, &TTrain::OnCommand_invertertoggle}, + {user_command::invertertoggle11, &TTrain::OnCommand_invertertoggle}, + {user_command::invertertoggle12, &TTrain::OnCommand_invertertoggle}, +}; diff --git a/vehicle/cab/controllercommands.cpp b/vehicle/cab/controllercommands.cpp new file mode 100644 index 000000000..1d2445a29 --- /dev/null +++ b/vehicle/cab/controllercommands.cpp @@ -0,0 +1,667 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the commands of the controllers: the master, the secondary and the dynamic brake one, the speed regulator + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/mover.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +// command handlers +void TTrain::OnCommand_aidriverenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // on press + if (Train->DynamicObject->Mechanik == nullptr) + { + return; + } + + if (true == Train->DynamicObject->Mechanik->AIControllFlag) + { + // żeby nie trzeba było rozłączać dla zresetowania + Train->DynamicObject->Mechanik->TakeControl(false); + } + Train->DynamicObject->Mechanik->TakeControl(true); + } +} + +void TTrain::OnCommand_aidriverdisable(TTrain *Train, command_data const &Command) +{ + + // on press + if (Command.action == GLFW_PRESS && Train->DynamicObject->Mechanik) + Train->DynamicObject->Mechanik->TakeControl(false); +} +auto const EU07_CONTROLLER_KEYBOARDETURNDELAY{1.5f}; + +void TTrain::OnCommand_jointcontrollerset(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + // on press or hold + // value controls brake in range 0-0.5, master controller in range 0.5-1.0 + if (Command.param1 >= 0.5) + { + Train->set_master_controller((Command.param1 * 2 - 1) * + (Train->mvControlled->CoupledCtrl ? Train->mvControlled->MainCtrlPosNo + Train->mvControlled->ScndCtrlPosNo : Train->mvControlled->MainCtrlPosNo)); + Train->m_mastercontrollerinuse = true; + // when SplitEDPneumaticBrake is active the joint controller's negative range + // commands the dedicated dynamic-brake lever instead of the local pneumatic brake + if (Train->mvControlled->SplitEDPneumaticBrake) + { + Train->mvControlled->DynamicBrakeLevelSet(0.0); + } + else + { + Train->mvOccupied->LocalBrakePosA = 0; + } + } + else + { + auto const negativeRange{std::clamp(1.0 - Command.param1 * 2, 0.0, 1.0)}; + if (Train->mvControlled->SplitEDPneumaticBrake) + { + // negative range of jointctrl drives only ED braking, local pneumatic brake stays untouched. + // snap to DBPN discrete stops so the lever animates step-by-step + auto const stepCount{std::max(1, Train->mvControlled->DynamicBrakeCtrlPosNo)}; + auto const snapped{std::round(negativeRange * stepCount) / stepCount}; + Train->mvControlled->DynamicBrakeLevelSet(snapped); + } + else + { + Train->mvOccupied->LocalBrakePosA = negativeRange; + } + if (Train->mvControlled->MainCtrlPowerPos() > 0) + { + Train->set_master_controller(Train->mvControlled->MainCtrlNoPowerPos()); + } + } + } + else + { + // release + Train->m_mastercontrollerinuse = false; + Train->m_mastercontrollerreturndelay = EU07_CONTROLLER_BASERETURNDELAY; // NOTE: keyboard return delay is omitted for other input sources + } +} + +void TTrain::OnCommand_mastercontrollerincrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + // on press or hold + auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; + // when SplitEDPneumaticBrake is true the joint controller's negative range maps + // to the dedicated dynamic-brake lever (DynamicBrakeCtrl) rather than to LocalBrake + auto const negativeRangeActive{splitMode ? Train->mvControlled->DynamicBrakeCtrlPos > 0.0 : Train->mvOccupied->LocalBrakePosA > 0.0}; + if (Train->ggJointCtrl.SubModel != nullptr && negativeRangeActive) + { + if (splitMode) + { + OnCommand_DynamicBrakeControllerDecrease(Train, Command); + Train->m_mastercontrollerinuse = true; + } + else + { + OnCommand_independentbrakedecrease(Train, Command); + } + } + else + { + Train->mvControlled->IncMainCtrl(1); + Train->m_mastercontrollerinuse = true; + } + } + else if (Command.action == GLFW_RELEASE) + { + // release + Train->m_mastercontrollerinuse = false; + Train->m_mastercontrollerreturndelay = EU07_CONTROLLER_KEYBOARDETURNDELAY + EU07_CONTROLLER_BASERETURNDELAY; + } +} + +void TTrain::OnCommand_mastercontrollerincreasefast(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + // on press or hold + auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; + auto const negativeRangeActive{splitMode ? Train->mvControlled->DynamicBrakeCtrlPos > 0.0 : Train->mvOccupied->LocalBrakePosA > 0.0}; + if (Train->ggJointCtrl.SubModel != nullptr && negativeRangeActive) + { + if (splitMode) + { + OnCommand_DynamicBrakeControllerDecreaseFast(Train, Command); + Train->m_mastercontrollerinuse = true; + } + else + { + OnCommand_independentbrakedecreasefast(Train, Command); + } + } + else + { + Train->mvControlled->IncMainCtrl(Train->mvControlled->MainCtrlPosNo); + Train->m_mastercontrollerinuse = true; + } + } + else + { + // release + Train->m_mastercontrollerinuse = false; + Train->m_mastercontrollerreturndelay = EU07_CONTROLLER_KEYBOARDETURNDELAY + EU07_CONTROLLER_BASERETURNDELAY; + } +} + +void TTrain::OnCommand_mastercontrollerdecrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + // on press or hold + auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; + if (Train->ggJointCtrl.SubModel != nullptr && Train->mvControlled->IsMainCtrlNoPowerPos()) + { + // negative range of jointctrl: ED brake when split, otherwise pneumatic local brake + if (splitMode) + { + OnCommand_DynamicBrakeControllerIncrease(Train, Command); + Train->m_mastercontrollerinuse = true; + } + else + { + OnCommand_independentbrakeincrease(Train, Command); + } + } + else + { + Train->mvControlled->DecMainCtrl(1); + Train->m_mastercontrollerinuse = true; + } + } + else if (Command.action == GLFW_RELEASE) + { + // release + Train->m_mastercontrollerinuse = false; + Train->m_mastercontrollerreturndelay = EU07_CONTROLLER_KEYBOARDETURNDELAY + EU07_CONTROLLER_BASERETURNDELAY; + } +} + +void TTrain::OnCommand_mastercontrollerdecreasefast(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + // on press or hold + auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; + if (Train->ggJointCtrl.SubModel != nullptr && Train->mvControlled->IsMainCtrlNoPowerPos()) + { + if (splitMode) + { + OnCommand_DynamicBrakeControllerIncreaseFast(Train, Command); + Train->m_mastercontrollerinuse = true; + } + else + { + OnCommand_independentbrakeincreasefast(Train, Command); + } + } + else + { + Train->mvControlled->DecMainCtrl(Train->mvControlled->MainCtrlPowerPos()); + Train->m_mastercontrollerinuse = true; + } + } + else + { + // release + Train->m_mastercontrollerinuse = false; + Train->m_mastercontrollerreturndelay = EU07_CONTROLLER_KEYBOARDETURNDELAY + EU07_CONTROLLER_BASERETURNDELAY; + } +} + +void TTrain::OnCommand_mastercontrollerset(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + // on press or hold + Train->set_master_controller(Command.param1); + Train->m_mastercontrollerinuse = true; + } + else + { + // release + Train->m_mastercontrollerinuse = false; + Train->m_mastercontrollerreturndelay = EU07_CONTROLLER_BASERETURNDELAY; // NOTE: keyboard return delay is omitted for other input sources + } +} +void TTrain::OnCommand_DynamicBrakeControllerIncrease(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_RELEASE) + { + return; + } + if (false == Train->mvControlled->SplitEDPneumaticBrake) + { + return; + } + + // step exactly one stop (1 / DBPN) per command, matching the discrete behaviour of jointctrl + Train->mvControlled->IncDynamicBrakeLevel(1.0f); +} + +void TTrain::OnCommand_DynamicBrakeControllerIncreaseFast(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + if (false == Train->mvControlled->SplitEDPneumaticBrake) + { + return; + } + + Train->mvControlled->IncDynamicBrakeLevel(static_cast(Train->mvControlled->DynamicBrakeCtrlPosNo)); +} + +void TTrain::OnCommand_DynamicBrakeControllerDecrease(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_RELEASE) + { + return; + } + if (false == Train->mvControlled->SplitEDPneumaticBrake) + { + return; + } + + // step exactly one stop (1 / DBPN) per command, matching the discrete behaviour of jointctrl + Train->mvControlled->DecDynamicBrakeLevel(1.0f); +} + +void TTrain::OnCommand_DynamicBrakeControllerDecreaseFast(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + if (false == Train->mvControlled->SplitEDPneumaticBrake) + { + return; + } + + Train->mvControlled->DecDynamicBrakeLevel(static_cast(Train->mvControlled->DynamicBrakeCtrlPosNo)); +} + +void TTrain::OnCommand_DynamicBrakeControllerSet(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_RELEASE) + { + return; + } + if (false == Train->mvControlled->SplitEDPneumaticBrake) + { + return; + } + + // when input source uses raw 0..1 value, snap to nearest DBPN step + auto const target{std::clamp(Command.param1, 0.0, 1.0)}; + auto const stepCount{std::max(1, Train->mvControlled->DynamicBrakeCtrlPosNo)}; + auto const snapped{std::round(target * stepCount) / stepCount}; + Train->mvControlled->DynamicBrakeLevelSet(snapped); +} + +void TTrain::OnCommand_secondcontrollerincrease(TTrain *Train, command_data const &Command) +{ + + if (Train->mvControlled->EngineType == TEngineType::DieselElectric && true == Train->mvControlled->ShuntModeAllow && true == Train->mvControlled->ShuntMode) + { + if (Command.action != GLFW_RELEASE) + { + Train->mvControlled->AnPos = std::clamp(Train->mvControlled->AnPos + 0.025, 0.0, 1.0); + } + } + else + { + // regular mode + // push or pushtoggle control type + if (Train->ggScndCtrl.is_push()) + { + if (Command.action == GLFW_PRESS) + { + // activate on press + Train->mvControlled->IncScndCtrl(1); + } + } + // toggle control type + else + { + if (Command.action != GLFW_RELEASE) + { + Train->mvControlled->IncScndCtrl(1); + } + } + // HACK: potentially animate push or pushtoggle control + if (Train->ggScndCtrl.is_push()) + { + auto const activeposition{1.f}; + auto const neutralposition{Train->ggScndCtrl.is_toggle() ? 0.5f : 0.f}; + Train->ggScndCtrl.UpdateValue(Command.action == GLFW_RELEASE ? neutralposition : activeposition, Train->dsbSwitch); + } + // potentially animate tempomat button, unless the cruise control has its own + if (Train->ggScndCtrlButton.is_push() && Train->mvControlled->ScndCtrlPos <= 1 && false == Train->mvControlled->IsSpeedCtrlSeparate()) + { + Train->ggScndCtrlButton.UpdateValue(Command.action == GLFW_RELEASE ? 0.f : 1.f, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_secondcontrollerincreasefast(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + // on press or hold + if (Train->mvControlled->EngineType == TEngineType::DieselElectric && true == Train->mvControlled->ShuntMode) + { + Train->mvControlled->AnPos = 1.0; + } + else + { + Train->mvControlled->IncScndCtrl(2); + } + } +} + +void TTrain::OnCommand_notchingrelaytoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->mvOccupied->AutoRelayFlag) + { + // turn on + Train->mvOccupied->AutoRelaySwitch(true); + } + else + { + // turn off + Train->mvOccupied->AutoRelaySwitch(false); + } + // visual feedback + Train->ggAutoRelayButton.UpdateValue(Train->mvOccupied->AutoRelayFlag ? 1.f : 0.f, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_tempomattoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggScndCtrlButton.is_push()) + { + // impulse switch + if (Command.action == GLFW_RELEASE) + { + // just move the button(s) back to default position + // visual feedback + Train->ggScndCtrlButton.UpdateValue(0.0, Train->dsbSwitch); + Train->ggScndCtrlOffButton.UpdateValue(0.0, Train->dsbSwitch); + return; + } + // glfw_press + if (false == Train->mvControlled->IsSpeedCtrlEngaged()) + { + // turn on if it's not active + Train->mvControlled->SpeedCtrlSwitch(true); + // visual feedback + Train->ggScndCtrlButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // otherwise turn off + Train->mvControlled->SpeedCtrlSwitch(false); + // visual feedback + if (Train->m_controlmapper.contains("tempomatoff_sw:")) + { + Train->ggScndCtrlOffButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + Train->ggScndCtrlButton.UpdateValue(1.0, Train->dsbSwitch); + } + } + } + else + { + // two-state switch + if (Command.action == GLFW_RELEASE) + { + return; + } + + if (false == Train->mvControlled->IsSpeedCtrlEngaged()) + { + // turn on + Train->mvControlled->SpeedCtrlSwitch(true); + // visual feedback + Train->ggScndCtrlButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // turn off + Train->mvControlled->SpeedCtrlSwitch(false); + // visual feedback + Train->ggScndCtrlButton.UpdateValue(0.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_distancecounteractivate(TTrain *Train, command_data const &Command) +{ + // NOTE: distance meter activation button is presumed to be of impulse type + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggDistanceCounterButton.UpdateValue(1.0, Train->dsbSwitch); + // activate or start anew + if (Train->mvOccupied->isDoubleClickForMeasureNeeded) + { + // handler tempomatu dla podwojnego kliku + if (Train->trainLenghtMeasureTimer >= 0.f) // jesli zdazylismy w czasie sekundy + Train->m_distancecounter = 0.f; // rozpoczynamy pomiar + else + Train->trainLenghtMeasureTimer = Train->mvOccupied->DistanceCounterDoublePressPeriod; // odpalamy zegarek od nowa + } + else + { + // dla pojedynczego kliku + Train->m_distancecounter = 0.f; + } + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggDistanceCounterButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_mucurrentindicatorothersourceactivate(TTrain *Train, command_data const &Command) +{ + + if (Train->ggNextCurrentButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Current Indicator Source switch is missing, or wasn't defined"); + } + return; + } + + if (Command.action == GLFW_PRESS) + { + // turn on + Train->ShowNextCurrent = true; + // visual feedback + Train->ggNextCurrentButton.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // turn off + Train->ShowNextCurrent = false; + // visual feedback + Train->ggNextCurrentButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_secondcontrollerdecrease(TTrain *Train, command_data const &Command) +{ + + if (Train->mvControlled->EngineType == TEngineType::DieselElectric && true == Train->mvControlled->ShuntMode) + { + if (Command.action != GLFW_RELEASE) + { + Train->mvControlled->AnPos = std::clamp(Train->mvControlled->AnPos - 0.025, 0.0, 1.0); + } + } + else + { + // regular mode + // push or pushtoggle control type + if (Train->ggScndCtrl.is_push()) + { + // basic push control can't decrease state, but pushtoggle can + if (true == Train->ggScndCtrl.is_toggle() && Command.action == GLFW_PRESS) + { + // activate on press + Train->mvControlled->DecScndCtrl(1); + } + } + // toggle control type + else + { + if (Command.action != GLFW_RELEASE) + { + Train->mvControlled->DecScndCtrl(1); + } + } + // HACK: potentially animate push or pushtoggle control + if (Train->ggScndCtrl.is_push()) + { + auto const activeposition{Train->ggScndCtrl.is_toggle() ? 0.f : 1.f}; + auto const neutralposition{Train->ggScndCtrl.is_toggle() ? 0.5f : 0.f}; + Train->ggScndCtrl.UpdateValue(Command.action == GLFW_RELEASE ? neutralposition : activeposition, Train->dsbSwitch); + } + // potentially animate tempomat button, unless the cruise control has its own + if (Train->ggScndCtrlButton.is_push() && Train->mvControlled->ScndCtrlPos <= 1 && false == Train->mvControlled->IsSpeedCtrlSeparate()) + { + if (Train->m_controlmapper.contains("tempomatoff_sw:")) + { + Train->ggScndCtrlOffButton.UpdateValue(Command.action == GLFW_RELEASE ? 0.f : 1.f, Train->dsbSwitch); + } + else + { + Train->ggScndCtrlButton.UpdateValue(Command.action == GLFW_RELEASE ? 0.f : 1.f, Train->dsbSwitch); + } + } + } +} + +void TTrain::OnCommand_secondcontrollerdecreasefast(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + // on press or hold + if (Train->mvControlled->EngineType == TEngineType::DieselElectric && true == Train->mvControlled->ShuntMode) + { + Train->mvControlled->AnPos = 0.0; + } + else + { + Train->mvControlled->DecScndCtrl(2); + } + } +} + +void TTrain::OnCommand_secondcontrollerset(TTrain *Train, command_data const &Command) +{ + + auto const targetposition{std::min(static_cast(Command.param1), Train->mvControlled->ScndCtrlPosNo)}; + // HACK: potentially animate push or pushtoggle control + if (Train->ggScndCtrl.is_push()) + { + auto const activeposition{Train->ggScndCtrl.is_toggle() ? + (targetposition < Train->mvControlled->ScndCtrlPos ? 0.f : + targetposition > Train->mvControlled->ScndCtrlPos ? 1.f : + Train->ggScndCtrl.GetDesiredValue()) : // leave the control in its current position if it hits the limit + targetposition == 0 ? 0.f : + 1.f}; + auto const neutralposition{Train->ggScndCtrl.is_toggle() ? 0.5f : 0.f}; + Train->ggScndCtrl.UpdateValue(Command.action == GLFW_RELEASE ? neutralposition : activeposition, Train->dsbSwitch); + } + // update control value + if (Command.action != GLFW_RELEASE) + { + // on press or hold + while (targetposition < Train->mvControlled->GetVirtualScndPos() && true == Train->mvControlled->DecScndCtrl(1)) + { + // all work is done in the header + } + while (targetposition > Train->mvControlled->GetVirtualScndPos() && true == Train->mvControlled->IncScndCtrl(1)) + { + // all work is done in the header + } + } +} diff --git a/vehicle/cab/couplingcommands.cpp b/vehicle/cab/couplingcommands.cpp new file mode 100644 index 000000000..618b64da4 --- /dev/null +++ b/vehicle/cab/couplingcommands.cpp @@ -0,0 +1,230 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the commands of the couplings and the departure + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/mover.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +void TTrain::OnCommand_nearestcarcouplingincrease(TTrain *Train, command_data const &Command) +{ + + if (true == Command.freefly && Command.action == GLFW_PRESS) + { + // tryb freefly, press only + auto couplerindex{-1}; + auto *vehicle{Train->DynamicObject->ABuScanNearestObject(Command.location, Train->DynamicObject->GetTrack(), 1, 1500, couplerindex)}; + if (vehicle == nullptr) + vehicle = Train->DynamicObject->ABuScanNearestObject(Command.location, Train->DynamicObject->GetTrack(), -1, 1500, couplerindex); + + if (couplerindex != -1 && vehicle != nullptr) + { + + vehicle->couple(couplerindex); + } + if (Train->DynamicObject->Mechanik) + { + // aktualizacja flag kierunku w składzie + Train->DynamicObject->Mechanik->CheckVehicles(DriverOrder::connect); + } + } +} + +void TTrain::OnCommand_nearestcarcouplingdisconnect(TTrain *Train, command_data const &Command) +{ + + if (true == Command.freefly && Command.action == GLFW_PRESS) + { + // tryb freefly, press only + auto couplerindex{-1}; + auto *vehicle{Train->DynamicObject->ABuScanNearestObject(Command.location, Train->DynamicObject->GetTrack(), 1, 1500, couplerindex)}; + if (vehicle == nullptr) + vehicle = Train->DynamicObject->ABuScanNearestObject(Command.location, Train->DynamicObject->GetTrack(), -1, 1500, couplerindex); + + if (couplerindex != -1 && vehicle != nullptr) + { + + vehicle->uncouple(couplerindex); + } + if (Train->DynamicObject->Mechanik) + { + // aktualizacja flag kierunku w składzie + Train->DynamicObject->Mechanik->CheckVehicles(DriverOrder::disconnect); + } + } +} + +void TTrain::OnCommand_nearestcarcoupleradapterattach(TTrain * /*Train*/, command_data const &Command) +{ + + if (true == Command.freefly && Command.action == GLFW_PRESS) + { + // tryb freefly, press only + auto *vehicle{std::get(simulation::Region->find_vehicle(Command.location, 50, false, true))}; + if (vehicle == nullptr) + { + return; + } + + auto const couplerindex = + glm::length2(glm::vec3{vehicle->CouplerPosition(end::front)} - Command.location) < glm::length2(glm::vec3{vehicle->CouplerPosition(end::rear)} - Command.location) ? end::front : end::rear; + + vehicle->attach_coupler_adapter(couplerindex); + } +} + +void TTrain::OnCommand_nearestcarcoupleradapterremove(TTrain * /*Train*/, command_data const &Command) +{ + + if (true == Command.freefly && Command.action == GLFW_PRESS) + { + // tryb freefly, press only + auto *vehicle{std::get(simulation::Region->find_vehicle(Command.location, 50, false, true))}; + if (vehicle == nullptr) + { + return; + } + + auto const couplerindex = + glm::length2(glm::vec3{vehicle->CouplerPosition(end::front)} - Command.location) < glm::length2(glm::vec3{vehicle->CouplerPosition(end::rear)} - Command.location) ? end::front : end::rear; + + vehicle->remove_coupler_adapter(couplerindex); + } +} + +void TTrain::OnCommand_occupiedcarcouplingdisconnect(TTrain *Train, command_data const &Command) +{ + + // if( false == Train->m_controlmapper.contains( "couplingdisconnect_sw:" ) ) { return; } + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->m_couplingdisconnect = true; + + if (Train->iCabn == 0) + { + return; + } + + if (Train->DynamicObject) + { + Train->DynamicObject->uncouple(Train->cab_to_end()); + if (Train->DynamicObject->Mechanik) + { + // aktualizacja flag kierunku w składzie + Train->DynamicObject->Mechanik->CheckVehicles(DriverOrder::disconnect); + } + } + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->m_couplingdisconnect = false; + } +} + +void TTrain::OnCommand_occupiedcarcouplingdisconnectback(TTrain *Train, command_data const &Command) +{ + + // if( false == Train->m_controlmapper.contains( "couplingdisconnect_sw:" ) ) { return; } + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->m_couplingdisconnectback = true; + + if (Train->iCabn == 0) + { + return; + } + + if (Train->DynamicObject) + { + Train->DynamicObject->uncouple(1 - Train->cab_to_end()); + if (Train->DynamicObject->Mechanik) + { + // aktualizacja flag kierunku w składzie + Train->DynamicObject->Mechanik->CheckVehicles(DriverOrder::disconnect); + } + } + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->m_couplingdisconnectback = false; + } +} + +void TTrain::OnCommand_departureannounce(TTrain *Train, command_data const &Command) +{ + + if (Train->ggDepartureSignalButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Departure Signal button is missing, or wasn't defined"); + } + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the sound can loop uninterrupted + if (false == Train->mvOccupied->DepartureSignal) + { + // turn on + Train->mvOccupied->signal_departure(true); + // visual feedback + Train->ggDepartureSignalButton.UpdateValue(1.0, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + // turn off + Train->mvOccupied->signal_departure(false); + // visual feedback + Train->ggDepartureSignalButton.UpdateValue(0.0, Train->dsbSwitch); + } +} diff --git a/vehicle/cab/doorcommands.cpp b/vehicle/cab/doorcommands.cpp new file mode 100644 index 000000000..1b57e69b3 --- /dev/null +++ b/vehicle/cab/doorcommands.cpp @@ -0,0 +1,694 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the commands of the doors and the mirrors + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/mover.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +void TTrain::OnCommand_doorlocktoggle(TTrain *Train, command_data const &Command) +{ + + if (Train->ggDoorSignallingButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Door Lock switch is missing, or wasn't defined"); + } + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the sound can loop uninterrupted + if (false == Train->mvOccupied->Doors.lock_enabled) + { + // turn on + // TODO: door lock command to send through consist + Train->mvOccupied->LockDoors(true); + // visual feedback + Train->ggDoorSignallingButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // turn off + // TODO: door lock command to send through consist + Train->mvOccupied->LockDoors(false); + // visual feedback + Train->ggDoorSignallingButton.UpdateValue(0.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_doortoggleleft(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // NOTE: test how the door state check works with consists where the occupied vehicle doesn't have opening doors + if (false == (Train->ggDoorLeftButton.GetDesiredValue() > 0.5 || Train->ggDoorLeftOnButton.GetDesiredValue() > 0.5)) + { + // open + OnCommand_dooropenleft(Train, Command); + } + else + { + // close + if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorLeftOffButton.SubModel == nullptr) + { + // OnCommand_doorcloseall( Train, Command ); + // if two-button setup lacks dedicated closing button require the user to press appropriate button manually + return; + } + else + { + OnCommand_doorcloseleft(Train, Command); + } + } + } + else if (Command.action == GLFW_RELEASE) + { + + if (true == (Train->ggDoorLeftButton.GetDesiredValue() > 0.5 || Train->ggDoorLeftOnButton.GetDesiredValue() > 0.5)) + { + // open + if (Train->mvOccupied->Doors.has_autowarning && Train->mvOccupied->DepartureSignal) + { + // complete closing the doors + if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorLeftOffButton.SubModel == nullptr) + { + // OnCommand_doorcloseall( Train, Command ); + // if two-button setup lacks dedicated closing button require the user to press appropriate button manually + return; + } + else + { + OnCommand_doorcloseleft(Train, Command); + } + } + else + { + OnCommand_dooropenleft(Train, Command); + } + } + else + { + // close + if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorLeftOffButton.SubModel == nullptr) + { + // OnCommand_doorcloseall( Train, Command ); + // if two-button setup lacks dedicated closing button require the user to press appropriate button manually + return; + } + else + { + OnCommand_doorcloseleft(Train, Command); + } + } + // visual feedback + // dedicated closing buttons are presumed to be impulse switches and return automatically to neutral position + // NOTE: temporary arrangement, can be removed when LD system is in place + if (Train->ggDoorLeftOffButton.SubModel) + Train->ggDoorLeftOffButton.UpdateValue(0.0, Train->dsbSwitch); + if (Train->ggDoorLeftOnButton.SubModel) + Train->ggDoorLeftOnButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_doorpermitleft(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + if (false == Train->mvOccupied->Doors.permit_presets.empty()) + { + return; + } + + auto const side{(Train->cab_to_end() == end::front ? side::left : side::right)}; + + if (Command.action == GLFW_PRESS) + { + + if (Train->ggDoorLeftPermitButton.is_push()) + { + // impulse switch + Train->mvOccupied->PermitDoors(side); + // visual feedback + Train->ggDoorLeftPermitButton.UpdateValue(1.0, Train->dsbSwitch); + // start potential timer for remote door control + Train->m_doorpermittimers[side] = Train->mvOccupied->DoorsOpenWithPermitAfter; + } + else + { + // two-state switch + auto const newstate{!(Train->ggDoorLeftPermitButton.GetDesiredValue() > 0.5)}; + + Train->mvOccupied->PermitDoors(side, newstate); + // visual feedback + Train->ggDoorLeftPermitButton.UpdateValue(newstate ? 1.0 : 0.0, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE && Train->ggDoorLeftPermitButton.is_push()) + { + // impulse switch + // visual feedback + Train->ggDoorLeftPermitButton.UpdateValue(0.0, Train->dsbSwitch); + // reset potential remote door control timer + Train->m_doorpermittimers[side] = -1.f; + } +} + +void TTrain::OnCommand_doorpermitright(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + if (false == Train->mvOccupied->Doors.permit_presets.empty()) + { + return; + } + + auto const side{(Train->cab_to_end() == end::front ? side::right : side::left)}; + + if (Command.action == GLFW_PRESS) + { + + if (Train->ggDoorRightPermitButton.type() == TGaugeType::push) + { + // impulse switch + Train->mvOccupied->PermitDoors(side); + // visual feedback + Train->ggDoorRightPermitButton.UpdateValue(1.0, Train->dsbSwitch); + // start potential timer for remote door control + Train->m_doorpermittimers[side] = Train->mvOccupied->DoorsOpenWithPermitAfter; + } + else + { + // two-state switch + auto const newstate{!(Train->ggDoorRightPermitButton.GetDesiredValue() > 0.5)}; + + Train->mvOccupied->PermitDoors(side, newstate); + // visual feedback + Train->ggDoorRightPermitButton.UpdateValue(newstate ? 1.0 : 0.0, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE && Train->ggDoorRightPermitButton.type() == TGaugeType::push) + { + // impulse switch + // visual feedback + Train->ggDoorRightPermitButton.UpdateValue(0.0, Train->dsbSwitch); + // reset potential remote door control timer + Train->m_doorpermittimers[side] = -1.f; + } +} + +void TTrain::OnCommand_doorpermitpresetactivatenext(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + Train->mvOccupied->ChangeDoorPermitPreset(1); + // visual feedback + Train->ggDoorPermitPresetButton.UpdateValue(static_cast(Train->mvOccupied->Doors.permit_preset), Train->dsbSwitch); + } +} + +void TTrain::OnCommand_doorpermitpresetactivateprevious(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + Train->mvOccupied->ChangeDoorPermitPreset(-1); + // visual feedback + Train->ggDoorPermitPresetButton.UpdateValue(static_cast(Train->mvOccupied->Doors.permit_preset), Train->dsbSwitch); + } +} + +void TTrain::OnCommand_dooropenleft(TTrain *Train, command_data const &Command) +{ + + + if (auto const remoteopencontrol{Train->mvOccupied->Doors.open_control == control_t::driver || Train->mvOccupied->Doors.open_control == control_t::mixed}; false == remoteopencontrol) + { + return; + } + + if (Train->ggDoorLeftOnButton.SubModel == nullptr && Train->ggDoorLeftButton.SubModel == nullptr) + { + + return; + } + + if (Command.action == GLFW_PRESS) + { + Train->mvOccupied->OperateDoors(Train->cab_to_end() == end::front ? side::left : side::right, true); + // visual feedback + if (Train->ggDoorLeftOnButton.SubModel != nullptr) + { + // two separate impulse switches + Train->ggDoorLeftOnButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // single two-state switch + Train->ggDoorLeftButton.UpdateValue(1.0, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + if (Train->ggDoorLeftOnButton.SubModel != nullptr) + { + // two separate impulse switches + Train->ggDoorLeftOnButton.UpdateValue(0.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_doorcloseleft(TTrain *Train, command_data const &Command) +{ + + + if (auto const remoteclosecontrol{Train->mvOccupied->Doors.close_control == control_t::driver || Train->mvOccupied->Doors.close_control == control_t::mixed}; false == remoteclosecontrol) + { + return; + } + + if (Train->ggDoorLeftOffButton.SubModel == nullptr && Train->ggDoorLeftButton.SubModel == nullptr) + { + + return; + } + + if (Command.action == GLFW_PRESS) + { + + if (Train->mvOccupied->Doors.has_autowarning) + { + // automatic departure signal delays actual door closing until the button is released + Train->mvOccupied->signal_departure(true); + } + else + { + // TODO: move door opening/closing to the update, so the switch animation doesn't hinge on door working + Train->mvOccupied->OperateDoors(Train->cab_to_end() == end::front ? side::left : side::right, false); + } + // visual feedback + if (Train->ggDoorLeftOffButton.SubModel != nullptr) + { + // two separate switches to open and close the door + Train->ggDoorLeftOffButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // single two-state switch + Train->ggDoorLeftButton.UpdateValue(0.0, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + + if (Train->mvOccupied->Doors.has_autowarning) + { + // automatic departure signal delays actual door closing until the button is released + Train->mvOccupied->signal_departure(false); + // now we can actually close the door + Train->mvOccupied->OperateDoors(Train->cab_to_end() == end::front ? side::left : side::right, false); + } + // visual feedback + // dedicated closing buttons are presumed to be impulse switches and return automatically to neutral position + if (Train->ggDoorLeftOffButton.SubModel) + Train->ggDoorLeftOffButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_doortoggleright(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // NOTE: test how the door state check works with consists where the occupied vehicle doesn't have opening doors + if (false == (Train->ggDoorRightButton.GetDesiredValue() > 0.5 || Train->ggDoorRightOnButton.GetDesiredValue() > 0.5)) + { + // open + OnCommand_dooropenright(Train, Command); + } + else + { + // close + if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorRightOffButton.SubModel == nullptr) + { + // OnCommand_doorcloseall( Train, Command ); + // if two-button setup lacks dedicated closing button require the user to press appropriate button manually + return; + } + else + { + OnCommand_doorcloseright(Train, Command); + } + } + } + else if (Command.action == GLFW_RELEASE) + { + + if (true == (Train->ggDoorRightButton.GetDesiredValue() > 0.5 || Train->ggDoorRightOnButton.GetDesiredValue() > 0.5)) + { + // open + if (Train->mvOccupied->Doors.has_autowarning && Train->mvOccupied->DepartureSignal) + { + // complete closing the doors + if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorRightOffButton.SubModel == nullptr) + { + // OnCommand_doorcloseall( Train, Command ); + // if two-button setup lacks dedicated closing button require the user to press appropriate button manually + return; + } + else + { + OnCommand_doorcloseright(Train, Command); + } + } + else + { + OnCommand_dooropenright(Train, Command); + } + } + else + { + // close + if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorRightOffButton.SubModel == nullptr) + { + // OnCommand_doorcloseall( Train, Command ); + // if two-button setup lacks dedicated closing button require the user to press appropriate button manually + return; + } + else + { + OnCommand_doorcloseright(Train, Command); + } + } + // visual feedback + // dedicated closing buttons are presumed to be impulse switches and return automatically to neutral position + // NOTE: temporary arrangement, can be removed when LD system is in place + if (Train->ggDoorRightOffButton.SubModel) + Train->ggDoorRightOffButton.UpdateValue(0.0, Train->dsbSwitch); + if (Train->ggDoorRightOnButton.SubModel) + Train->ggDoorRightOnButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_dooropenright(TTrain *Train, command_data const &Command) +{ + + + if (auto const remoteopencontrol{Train->mvOccupied->Doors.open_control == control_t::driver || Train->mvOccupied->Doors.open_control == control_t::mixed}; false == remoteopencontrol) + { + return; + } + + if (Train->ggDoorRightOnButton.SubModel == nullptr && Train->ggDoorRightButton.SubModel == nullptr) + { + + return; + } + + if (Command.action == GLFW_PRESS) + { + + Train->mvOccupied->OperateDoors(Train->cab_to_end() == end::front ? side::right : side::left, true); + // visual feedback + if (Train->ggDoorRightOnButton.SubModel != nullptr) + { + // two separate impulse switches + Train->ggDoorRightOnButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // single two-state switch + Train->ggDoorRightButton.UpdateValue(1.0, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + if (Train->ggDoorRightOnButton.SubModel != nullptr) + { + // two separate impulse switches + Train->ggDoorRightOnButton.UpdateValue(0.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_doorcloseright(TTrain *Train, command_data const &Command) +{ + + + if (auto const remoteclosecontrol{Train->mvOccupied->Doors.close_control == control_t::driver || Train->mvOccupied->Doors.close_control == control_t::mixed}; false == remoteclosecontrol) + { + return; + } + + if (Train->ggDoorRightOffButton.SubModel == nullptr && Train->ggDoorRightButton.SubModel == nullptr) + { + + return; + } + + if (Command.action == GLFW_PRESS) + { + + if (Train->mvOccupied->Doors.has_autowarning) + { + // automatic departure signal delays actual door closing until the button is released + Train->mvOccupied->signal_departure(true); + } + else + { + Train->mvOccupied->OperateDoors(Train->cab_to_end() == end::front ? side::right : side::left, false); + } + // visual feedback + if (Train->ggDoorRightOffButton.SubModel != nullptr) + { + // two separate switches to open and close the door + Train->ggDoorRightOffButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // single two-state switch + Train->ggDoorRightButton.UpdateValue(0.0, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + + if (Train->mvOccupied->Doors.has_autowarning) + { + // automatic departure signal delays actual door closing until the button is released + Train->mvOccupied->signal_departure(false); + // now we can actually close the door + Train->mvOccupied->OperateDoors(Train->cab_to_end() == end::front ? side::right : side::left, false); + } + // visual feedback + // dedicated closing buttons are presumed to be impulse switches and return automatically to neutral position + if (Train->ggDoorRightOffButton.SubModel) + Train->ggDoorRightOffButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_dooropenall(TTrain *Train, command_data const &Command) +{ + + + if (auto const remoteopencontrol{Train->mvOccupied->Doors.open_control == control_t::driver || Train->mvOccupied->Doors.open_control == control_t::mixed}; false == remoteopencontrol) + { + return; + } + + if (Train->ggDoorAllOnButton.SubModel == nullptr) + { + // TODO: expand definition of cab controls so we can know if the control is present without testing for presence of 3d switch + if (Command.action == GLFW_PRESS) + { + WriteLog("Open All Doors switch is missing, or wasn't defined"); + } + return; + } + + if (Command.action == GLFW_PRESS) + { + + Train->mvOccupied->OperateDoors(side::right, true); + Train->mvOccupied->OperateDoors(side::left, true); + // visual feedback + Train->ggDoorAllOnButton.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggDoorAllOnButton.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_doorcloseall(TTrain *Train, command_data const &Command) +{ + + + if (auto const remoteclosecontrol{Train->mvOccupied->Doors.close_control == control_t::driver || Train->mvOccupied->Doors.close_control == control_t::mixed}; false == remoteclosecontrol) + { + return; + } + + if (Train->ggDoorAllOffButton.SubModel == nullptr) + { + // TODO: expand definition of cab controls so we can know if the control is present without testing for presence of 3d switch + if (Command.action == GLFW_PRESS) + { + WriteLog("Close All Doors switch is missing, or wasn't defined"); + } + return; + } + + if (Command.action == GLFW_PRESS) + { + + if (Train->mvOccupied->Doors.has_autowarning) + { + Train->mvOccupied->signal_departure(true); + } + if (Train->ggDoorAllOffButton.type() != TGaugeType::push_delayed) + { + // delays the action until the button is released + Train->mvOccupied->OperateDoors(side::right, false); + Train->mvOccupied->OperateDoors(side::left, false); + } + // visual feedback + Train->ggDoorLeftButton.UpdateValue(0.0, Train->dsbSwitch); + Train->ggDoorRightButton.UpdateValue(0.0, Train->dsbSwitch); + if (Train->ggDoorAllOffButton.SubModel) + Train->ggDoorAllOffButton.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + if (Train->mvOccupied->Doors.has_autowarning) + { + Train->mvOccupied->signal_departure(false); + } + if (Train->ggDoorAllOffButton.type() == TGaugeType::push_delayed) + { + // now we can actually close the door + Train->mvOccupied->OperateDoors(side::right, false); + Train->mvOccupied->OperateDoors(side::left, false); + } + // visual feedback + if (Train->ggDoorAllOffButton.SubModel) + Train->ggDoorAllOffButton.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_doorsteptoggle(TTrain *Train, command_data const &Command) +{ + // TODO: move logic/visualization code to the gauge, on_command() should return hint whether it should invoke a reaction + if (Command.action == GLFW_PRESS) + { + // effect + if (false == Train->ggDoorStepButton.is_delayed()) + { + Train->mvOccupied->PermitDoorStep(false == Train->mvOccupied->Doors.step_enabled); + } + // visual feedback + auto const isactive{(Train->ggDoorStepButton.is_push() // always press push button + || Train->mvOccupied->Doors.step_enabled)}; // for toggle buttons indicate item state + Train->ggDoorStepButton.UpdateValue(isactive ? 1 : 0); + } + else if (Command.action == GLFW_RELEASE) + { + // effect + if (Train->ggDoorStepButton.is_delayed()) + { + Train->mvOccupied->PermitDoorStep(false == Train->mvOccupied->Doors.step_enabled); + } + // visual feedback + if (Train->ggDoorStepButton.is_push()) + { + Train->ggDoorStepButton.UpdateValue(0); + } + } +} + +void TTrain::OnCommand_doormodetoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + Train->mvOccupied->ChangeDoorControlMode(false == Train->mvOccupied->Doors.remote_only); + } +} + +void TTrain::OnCommand_mirrorstoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_PRESS) + { + return; + } + + // only reacting to press, so the sound can loop uninterrupted + if (false == Train->mvOccupied->MirrorForbidden) + { + // turn on + Train->mvOccupied->MirrorForbidden = true; + } + else + { + // turn off + Train->mvOccupied->MirrorForbidden = false; + } +} diff --git a/vehicle/cab/equipmentcommands.cpp b/vehicle/cab/equipmentcommands.cpp new file mode 100644 index 000000000..256141d9a --- /dev/null +++ b/vehicle/cab/equipmentcommands.cpp @@ -0,0 +1,515 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the commands of the heating, the generic switches, the spring brake, the speed control and the inverters + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/mover.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +void TTrain::OnCommand_heatingtoggle(TTrain *Train, command_data const &Command) +{ + + if (Train->ggTrainHeatingButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Train Heating switch is missing, or wasn't defined"); + } + return; + } + + if (Command.action == GLFW_PRESS) + { + // ignore repeats so the switch doesn't flip back and forth if key is held down + if (false == Train->mvControlled->HeatingAllow) + { + // turn on + OnCommand_heatingenable(Train, Command); + } + else + { + // turn off + OnCommand_heatingdisable(Train, Command); + } + } + else if (Command.action == GLFW_RELEASE && (Train->ggTrainHeatingButton.type() == TGaugeType::push || Train->mvOccupied->HeatingSwitchImpulse)) + { + // impulse switch + // visual feedback + Train->ggTrainHeatingButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_heatingenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + Train->mvOccupied->HeatingSwitch(true); + // visual feedback + Train->ggTrainHeatingButton.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE && Train->mvOccupied->HeatingSwitchImpulse) + { + // the switch springs back to the middle + Train->ggTrainHeatingButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_heatingdisable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + Train->mvOccupied->HeatingSwitch(false); + // visual feedback: an impulse switch is pushed the other way, down + auto position{0.0}; + if (Train->mvOccupied->HeatingSwitchImpulse) + { + position = -1.0; + } + else if (Train->ggTrainHeatingButton.type() == TGaugeType::push) + { + position = 1.0; + } + Train->ggTrainHeatingButton.UpdateValue(position, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE && Train->mvOccupied->HeatingSwitchImpulse) + { + Train->ggTrainHeatingButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_generictoggle(TTrain *Train, command_data const &Command) +{ + + auto const itemindex = static_cast(Command.command) - static_cast(user_command::generictoggle0); + auto &item = Train->ggUniversals[itemindex]; + /* + if( item.SubModel == nullptr ) { + if( Command.action == GLFW_PRESS ) { + WriteLog( "Train generic item " + std::to_string( itemindex ) + " is missing, or wasn't defined" ); + } + return; + } + */ + + if (Command.action == GLFW_PRESS) + { + + if (item.type() == TGaugeType::push) + { + // impulse switch + // turn on + // visual feedback + item.UpdateValue(1.0); + } + else + { + // two-state switch, or one dragged in between its ends with the mouse: to the end farther from it + // visual feedback + item.UpdateValue(universal_drag::toggled(item.GetDesiredValue())); + } + } + else if (Command.action == GLFW_RELEASE && item.type() == TGaugeType::push) + { + // impulse switch + // turn off + // visual feedback + item.UpdateValue(0.0); + } +} + +// sets a universal control to the position given in param1, from 0 to 1 (MaSzyna-EU07/maszyna#62): the mouse drags +// the ones with drag: in their definition, and it can be bound to an axis of a gamepad. it stays where it is set +void TTrain::OnCommand_genericset(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_RELEASE) + { + return; + } + auto const itemindex = static_cast(Command.command) - static_cast(user_command::genericset0); + auto &item = Train->ggUniversals[itemindex]; + if (item.is_push()) + { + // an impulse switch springs back, it has no position to be left in + return; + } + // visual feedback + item.UpdateValue(universal_drag::clamp(Command.param1)); +} + +universal_drag::direction TTrain::universal_drag_direction(int const Index) const +{ + + if (Index < 0 || Index >= static_cast(ggUniversals.size()) || ggUniversals[Index].SubModel == nullptr) + { + return universal_drag::direction::none; + } + return ggUniversals[Index].drag(); +} + +float TTrain::universal_position(int const Index) const +{ + + if (Index < 0 || Index >= static_cast(ggUniversals.size())) + { + return 0.f; + } + return ggUniversals[Index].GetDesiredValue(); +} + +void TTrain::OnCommand_springbraketoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->mvOccupied->SpringBrake.Activate) + { + // turn on + OnCommand_springbrakeenable(Train, Command); + } + else + { + // turn off + OnCommand_springbrakedisable(Train, Command); + } + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggSpringBrakeOffButton.UpdateValue(0.0, Train->dsbSwitch); + Train->ggSpringBrakeOnButton.UpdateValue(0.0, Train->dsbSwitch); + } +}; + +void TTrain::OnCommand_springbrakeenable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->mvOccupied->SpringBrakeActivate(true); + // visual feedback + Train->ggSpringBrakeOnButton.UpdateValue(1.0, Train->dsbSwitch); + Train->ggSpringBrakeOffButton.UpdateValue(0.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggSpringBrakeOnButton.UpdateValue(0.0, Train->dsbSwitch); + } +}; + +void TTrain::OnCommand_springbrakedisable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->mvOccupied->SpringBrakeActivate(false); + // visual feedback + Train->ggSpringBrakeOffButton.UpdateValue(1.0, Train->dsbSwitch); + Train->ggSpringBrakeOnButton.UpdateValue(0.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggSpringBrakeOffButton.UpdateValue(0.0, Train->dsbSwitch); + } +}; +void TTrain::OnCommand_springbrakeshutofftoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->mvOccupied->SpringBrake.ShuttOff) + { + // turn on + OnCommand_springbrakeshutoffenable(Train, Command); + } + else + { + // turn off + OnCommand_springbrakeshutoffdisable(Train, Command); + } + } +}; + +void TTrain::OnCommand_springbrakeshutoffenable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->mvOccupied->SpringBrakeShutOff(true); + } +}; + +void TTrain::OnCommand_springbrakeshutoffdisable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->mvOccupied->SpringBrakeShutOff(false); + } +}; + +void TTrain::OnCommand_springbrakerelease(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + + if (auto const *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; vehicle == nullptr) + { + return; + } + Train->mvOccupied->SpringBrakeRelease(); + } +}; + +void TTrain::OnCommand_speedcontrolincrease(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->mvOccupied->SpeedCtrlInc(); + // visual feedback + Train->ggSpeedControlIncreaseButton.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggSpeedControlIncreaseButton.UpdateValue(0.0, Train->dsbSwitch); + } +}; + +void TTrain::OnCommand_speedcontroldecrease(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->mvOccupied->SpeedCtrlDec(); + // visual feedback + Train->ggSpeedControlDecreaseButton.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggSpeedControlDecreaseButton.UpdateValue(0.0, Train->dsbSwitch); + } +}; + +void TTrain::OnCommand_speedcontrolpowerincrease(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->mvOccupied->SpeedCtrlPowerInc(); + // visual feedback + Train->ggSpeedControlPowerIncreaseButton.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggSpeedControlPowerIncreaseButton.UpdateValue(0.0, Train->dsbSwitch); + } +}; + +void TTrain::OnCommand_speedcontrolpowerdecrease(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->mvOccupied->SpeedCtrlPowerDec(); + // visual feedback + Train->ggSpeedControlPowerDecreaseButton.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggSpeedControlPowerDecreaseButton.UpdateValue(0.0, Train->dsbSwitch); + } +}; + +void TTrain::OnCommand_speedcontrolbutton(TTrain *Train, command_data const &Command) +{ + + auto const itemindex = static_cast(Command.command) - static_cast(user_command::speedcontrolbutton0); + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->mvOccupied->SpeedCtrlButton(itemindex); + // visual feedback + Train->ggSpeedCtrlButtons[itemindex].UpdateValue(1.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggSpeedCtrlButtons[itemindex].UpdateValue(0.0, Train->dsbSwitch); + } +}; + +void TTrain::OnCommand_inverterenable(TTrain *Train, command_data const &Command) +{ + + auto itemindex = static_cast(Command.command) - static_cast(user_command::inverterenable1); + auto &item = Train->ggInverterEnableButtons[itemindex]; + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; + auto const flag{CouplingSet::FromBits(Train->DynamicObject->MoverParameters->InverterControlCouplerFlag)}; + TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); + while (p) + { + if (p->MoverParameters->eimc[eimc_p_Pmax] > 1) + { + if (itemindex < p->MoverParameters->InvertersNo) + { + p->MoverParameters->Inverters[itemindex].Activate = true; + break; + } + else + { + itemindex -= p->MoverParameters->InvertersNo; + } + } + p = kier ? p->Next(flag) : p->Prev(flag); + } + // visual feedback + item.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + item.UpdateValue(0.0, Train->dsbSwitch); + } +}; + +void TTrain::OnCommand_inverterdisable(TTrain *Train, command_data const &Command) +{ + + auto itemindex = static_cast(Command.command) - static_cast(user_command::inverterdisable1); + auto &item = Train->ggInverterDisableButtons[itemindex]; + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; + auto const flag{CouplingSet::FromBits(Train->DynamicObject->MoverParameters->InverterControlCouplerFlag)}; + TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); + while (p) + { + if (p->MoverParameters->eimc[eimc_p_Pmax] > 1) + { + if (itemindex < p->MoverParameters->InvertersNo) + { + p->MoverParameters->Inverters[itemindex].Activate = false; + break; + } + else + { + itemindex -= p->MoverParameters->InvertersNo; + } + } + p = kier ? p->Next(flag) : p->Prev(flag); + } + // visual feedback + item.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + item.UpdateValue(0.0, Train->dsbSwitch); + } +}; + +void TTrain::OnCommand_invertertoggle(TTrain *Train, command_data const &Command) +{ + + auto itemindex = static_cast(Command.command) - static_cast(user_command::invertertoggle1); + auto &item = Train->ggInverterToggleButtons[itemindex]; + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; + auto const flag{CouplingSet::FromBits(Train->DynamicObject->MoverParameters->InverterControlCouplerFlag)}; + TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); + while (p) + { + if (p->MoverParameters->eimc[eimc_p_Pmax] > 1) + { + if (itemindex < p->MoverParameters->InvertersNo) + { + p->MoverParameters->Inverters[itemindex].Activate = !p->MoverParameters->Inverters[itemindex].Activate; + // visual feedback + item.UpdateValue(p->MoverParameters->Inverters[itemindex].Activate ? 1.0 : 0.0, Train->dsbSwitch); + break; + } + else + { + itemindex -= p->MoverParameters->InvertersNo; + } + } + p = kier ? p->Next(flag) : p->Prev(flag); + } + } +}; diff --git a/vehicle/cab/internal.h b/vehicle/cab/internal.h new file mode 100644 index 000000000..94bfcda9d --- /dev/null +++ b/vehicle/cab/internal.h @@ -0,0 +1,61 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the constants and helpers the files of the cab share: only they include this header + +#pragma once + +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/mover.h" +#include +#include +#include +#include +#include + +/* +namespace input { + +extern user_command command; + +} +*/ + + +auto const EU07_CONTROLLER_BASERETURNDELAY{0.5f}; + +bool is_hold_coil_lever(TGauge const &Button); + diff --git a/vehicle/cab/lightcommands.cpp b/vehicle/cab/lightcommands.cpp new file mode 100644 index 000000000..2c13201cd --- /dev/null +++ b/vehicle/cab/lightcommands.cpp @@ -0,0 +1,1580 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the commands of the lights + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/mover.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +// the cab interior light set by the light preset just selected, if the preset sets one (eu07/maszyna#529). +// the cab light switch (cablight_sw:) is bound to the light state and follows it by itself +void TTrain::set_cab_light_from_lights_preset() +{ + auto const cablight{mvOccupied->LightsPresetCabLight(mvOccupied->LightsPos)}; + if (false == cablight.has_value()) + { + return; + } + auto const set{[&cablight](TCab &Cab) { + Cab.bLight = cablight->light; + Cab.bLightDim = cablight->dim; + }}; + if (false == DynamicObject->JointCabs) + { + // vehicles with separate cabs get separate lighting switch states + set(Cabine[iCabn]); + } + else + { + // joint virtual cabs share lighting switch states + for (auto &cab : Cabine) + { + set(cab); + } + } + // the dimmer switch is driven by commands only, move it along + if (ggCabLightDimButton.SubModel != nullptr) + { + ggCabLightDimButton.UpdateValue(cablight->dim ? 1.f : 0.f); + } +} + +void TTrain::OnCommand_lightspresetactivatenext(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->LightsPosNo == 0) + { + // no preset selector + return; + } + if (Command.action != GLFW_PRESS) + { + // one change per key press + return; + } + + if (Train->mvOccupied->LightsPos < Train->mvOccupied->LightsPosNo || true == Train->mvOccupied->LightsWrap) + { + // active light preset is stored as value in range 1-LigthPosNo + auto const restartcycle{Train->mvOccupied->LightsPos >= Train->mvOccupied->LightsPosNo}; + Train->mvOccupied->LightsPos = false == restartcycle ? Train->mvOccupied->LightsPos + 1 : 1; // wrap mode + + Train->Dynamic()->SetLights(); + Train->set_cab_light_from_lights_preset(); + // visual feedback + if (Train->ggLightsButton.SubModel != nullptr) + { + if (false == restartcycle) + { + Train->ggLightsButton.UpdateValue(static_cast(Train->mvOccupied->LightsPos - 1), Train->dsbSwitch); + } + else + { + // past the last position to the first one: a knob turning all the way round turns on rather than + // back across all the positions, and the position reached sounds (eu07/maszyna#464) + Train->ggLightsButton.UpdateValueWrapped(static_cast(Train->mvOccupied->LightsPos - 1), true, Train->mvOccupied->LightsPosNo, Train->dsbSwitch); + } + } + } +} + +void TTrain::OnCommand_lightspresetactivateprevious(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->LightsPosNo == 0) + { + // no preset selector + return; + } + if (Command.action != GLFW_PRESS) + { + // one change per key press + return; + } + + if (Train->mvOccupied->LightsPos > 1 || true == Train->mvOccupied->LightsWrap) + { + // active light preset is stored as value in range 1-LigthPosNo + auto const restartcycle{Train->mvOccupied->LightsPos <= 1}; + Train->mvOccupied->LightsPos = false == restartcycle ? Train->mvOccupied->LightsPos - 1 : Train->mvOccupied->LightsPosNo; // wrap mode + + Train->Dynamic()->SetLights(); + Train->set_cab_light_from_lights_preset(); + // visual feedback + if (Train->ggLightsButton.SubModel != nullptr) + { + if (false == restartcycle) + { + Train->ggLightsButton.UpdateValue(static_cast(Train->mvOccupied->LightsPos - 1), Train->dsbSwitch); + } + else + { + // back past the first position to the last one, the same way (eu07/maszyna#464) + Train->ggLightsButton.UpdateValueWrapped(static_cast(Train->mvOccupied->LightsPos - 1), false, Train->mvOccupied->LightsPosNo, Train->dsbSwitch); + } + } + } +} + +void TTrain::OnCommand_headlighttoggleleft(TTrain *Train, command_data const &Command) +{ + + auto const vehicleend{Train->cab_to_end()}; + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + + if (Train->ggLeftEndLightButton.SubModel != nullptr || Train->ggLeftLightButton.SubModel == nullptr) + { + if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0) + { + // turn on + OnCommand_headlightenableleft(Train, Command); + } + else + { + // turn off + OnCommand_headlightdisableleft(Train, Command); + } + } else { + // if the light is controlled by 3-way switch, handle both headlight and redmarker + if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0 && + (Train->mvOccupied->iLights[vehicleend] & light::redmarker_left) == 0) + { + // turn on + OnCommand_headlightenableleft(Train, Command); + } + else if (Train->mvOccupied->iLights[vehicleend] & light::headlight_left) + { + // switch to red + OnCommand_redmarkerenableleft(Train, Command); + } + else + { + // disable + OnCommand_redmarkerdisableleft(Train, Command); + } + } + } +} + +void TTrain::OnCommand_lightsset(TTrain *Train, command_data const &Command) +{ + // set custom item in Lights inventory + Train->mvOccupied->Lights[end::front][17] = static_cast(Command.param1); + Train->mvOccupied->Lights[end::rear][17] = static_cast(Command.param2); + Train->mvOccupied->LightsPos = 18; // nasza custom pozycja + Train->Dynamic()->SetLights(); +} + +void TTrain::OnCommand_headlightenableleft(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggLeftLightButton.UpdateValue(1.0, Train->dsbSwitch); + // implementation + auto const vehicleend{Train->cab_to_end()}; + + if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0) + { + Train->mvOccupied->iLights[vehicleend] ^= light::headlight_left; + } + // if the light is controlled by 3-way switch, disable marker light + if (Train->ggLeftEndLightButton.SubModel == nullptr) + { + Train->mvOccupied->iLights[vehicleend] &= ~light::redmarker_left; + } + } +} + +void TTrain::OnCommand_headlightdisableleft(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + int const vehicleend{Train->cab_to_end()}; + + if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0) + { + return; + } // already disabled + + Train->mvOccupied->iLights[vehicleend] ^= light::headlight_left; + // visual feedback + Train->ggLeftLightButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_headlighttoggleright(TTrain *Train, command_data const &Command) +{ + + auto const vehicleend{Train->cab_to_end()}; + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + + if (Train->ggRightEndLightButton.SubModel != nullptr || Train->ggRightLightButton.SubModel == nullptr) + { + if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_right) == 0) + { + // turn on + OnCommand_headlightenableright(Train, Command); + } + else + { + // turn off + OnCommand_headlightdisableright(Train, Command); + } + } else { + // if the light is controlled by 3-way switch, handle both headlight and redmarker + if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_right) == 0 && + (Train->mvOccupied->iLights[vehicleend] & light::redmarker_right) == 0) + { + // turn on + OnCommand_headlightenableright(Train, Command); + } + else if (Train->mvOccupied->iLights[vehicleend] & light::headlight_right) + { + // switch to red + OnCommand_redmarkerenableright(Train, Command); + } + else + { + // disable + OnCommand_redmarkerdisableright(Train, Command); + } + } + } +} + +void TTrain::OnCommand_headlightenableright(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggRightLightButton.UpdateValue(1.0, Train->dsbSwitch); + // implementation + auto const vehicleend{Train->cab_to_end()}; + + if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_right) == 0) + { + Train->mvOccupied->iLights[vehicleend] ^= light::headlight_right; + } + // if the light is controlled by 3-way switch, disable marker light + if (Train->ggRightEndLightButton.SubModel == nullptr) + { + Train->mvOccupied->iLights[vehicleend] &= ~light::redmarker_right; + } + } +} + +void TTrain::OnCommand_headlightdisableright(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const vehicleend{Train->cab_to_end()}; + + if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_right) == 0) + { + return; + } // already disabled + + Train->mvOccupied->iLights[vehicleend] ^= light::headlight_right; + // visual feedback + Train->ggRightLightButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_headlighttoggleupper(TTrain *Train, command_data const &Command) +{ + + auto const vehicleend{Train->cab_to_end()}; + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_upper) == 0) + { + // turn on + OnCommand_headlightenableupper(Train, Command); + } + else + { + // turn off + OnCommand_headlightdisableupper(Train, Command); + } + } +} + +void TTrain::OnCommand_headlightenableupper(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const vehicleend{Train->cab_to_end()}; + + if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_upper) != 0) + { + return; + } // already enabled + + Train->mvOccupied->iLights[vehicleend] ^= light::headlight_upper; + // visual feedback + Train->ggUpperLightButton.UpdateValue(1.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_headlightdisableupper(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const vehicleend{Train->cab_to_end()}; + + if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_upper) == 0) + { + return; + } // already disabled + + Train->mvOccupied->iLights[vehicleend] ^= light::headlight_upper; + // visual feedback + Train->ggUpperLightButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_redmarkertoggleleft(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const vehicleend{Train->cab_to_end()}; + + if ((Train->mvOccupied->iLights[vehicleend] & light::redmarker_left) == 0) + { + // turn on + OnCommand_redmarkerenableleft(Train, Command); + } + else + { + // turn off + OnCommand_redmarkerdisableleft(Train, Command); + } + } +} + +void TTrain::OnCommand_redmarkerenableleft(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const vehicleend{Train->cab_to_end()}; + + if ((Train->mvOccupied->iLights[vehicleend] & light::redmarker_left) != 0) + { + return; + } // already enabled + + Train->mvOccupied->iLights[vehicleend] ^= light::redmarker_left; + // visual feedback + if (Train->ggLeftEndLightButton.SubModel != nullptr) + { + Train->ggLeftEndLightButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // we interpret lack of dedicated switch as a sign the light is controlled with 3-way switch + // this is crude, but for now will do + Train->ggLeftLightButton.UpdateValue(-1.0, Train->dsbSwitch); + // if the light is controlled by 3-way switch, disable the headlight + Train->mvOccupied->iLights[vehicleend] &= ~light::headlight_left; + } + } +} + +void TTrain::OnCommand_redmarkerdisableleft(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const vehicleend{Train->cab_to_end()}; + + if ((Train->mvOccupied->iLights[vehicleend] & light::redmarker_left) == 0) + { + return; + } // already disabled + + Train->mvOccupied->iLights[vehicleend] ^= light::redmarker_left; + // visual feedback + if (Train->ggLeftEndLightButton.SubModel != nullptr) + { + Train->ggLeftEndLightButton.UpdateValue(0.0, Train->dsbSwitch); + } + else + { + // we interpret lack of dedicated switch as a sign the light is controlled with 3-way switch + // this is crude, but for now will do + Train->ggLeftLightButton.UpdateValue(0.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_redmarkertoggleright(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const vehicleend{Train->cab_to_end()}; + + if ((Train->mvOccupied->iLights[vehicleend] & light::redmarker_right) == 0) + { + // turn on + OnCommand_redmarkerenableright(Train, Command); + } + else + { + // turn off + OnCommand_redmarkerdisableright(Train, Command); + } + } +} + +void TTrain::OnCommand_redmarkerenableright(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const vehicleend{Train->cab_to_end()}; + + if ((Train->mvOccupied->iLights[vehicleend] & light::redmarker_right) != 0) + { + return; + } // already enabled + + Train->mvOccupied->iLights[vehicleend] ^= light::redmarker_right; + // visual feedback + if (Train->ggRightEndLightButton.SubModel != nullptr) + { + Train->ggRightEndLightButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // we interpret lack of dedicated switch as a sign the light is controlled with 3-way switch + // this is crude, but for now will do + Train->ggRightLightButton.UpdateValue(-1.0, Train->dsbSwitch); + // if the light is controlled by 3-way switch, disable the headlight + Train->mvOccupied->iLights[vehicleend] &= ~light::headlight_right; + } + } +} + +void TTrain::OnCommand_redmarkerdisableright(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const vehicleend{Train->cab_to_end()}; + + if ((Train->mvOccupied->iLights[vehicleend] & light::redmarker_right) == 0) + { + return; + } // already disabled + + Train->mvOccupied->iLights[vehicleend] ^= light::redmarker_right; + // visual feedback + if (Train->ggRightEndLightButton.SubModel != nullptr) + { + Train->ggRightEndLightButton.UpdateValue(0.0, Train->dsbSwitch); + } + else + { + // we interpret lack of dedicated switch as a sign the light is controlled with 3-way switch + // this is crude, but for now will do + Train->ggRightLightButton.UpdateValue(0.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_headlighttogglerearleft(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc + auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_right) == 0) + { + OnCommand_headlightenablerearleft(Train, Command); + } + else + { + OnCommand_headlightdisablerearleft(Train, Command); + } + } +} + +void TTrain::OnCommand_headlightenablerearleft(TTrain *Train, command_data const &Command) +{ + if (Train->mvOccupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + // already enabled + if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_right) == 0) + { + // turn on + Train->mvOccupied->iLights[vehicleotherend] ^= light::headlight_right; + // visual feedback + Train->ggRearLeftLightButton.UpdateValue(1.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_headlightdisablerearleft(TTrain *Train, command_data const &Command) +{ + if (Train->mvOccupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + if (Command.action == GLFW_PRESS) + { + auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + // already disabled + if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_right) == 0) + { + return; + } + + // turn off + Train->mvOccupied->iLights[vehicleotherend] ^= light::headlight_right; + // visual feedback + Train->ggRearLeftLightButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_headlighttogglerearright(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc + auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_left) == 0) + { + OnCommand_headlightenablerearright(Train, Command); + } + else + { + OnCommand_headlightdisablerearright(Train, Command); + } + } +} + +void TTrain::OnCommand_headlightenablerearright(TTrain *Train, command_data const &Command) +{ + if (Train->mvOccupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc + auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + + if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_left) == 0) + { + // turn on + Train->mvOccupied->iLights[vehicleotherend] ^= light::headlight_left; + // visual feedback + Train->ggRearRightLightButton.UpdateValue(1.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_headlightdisablerearright(TTrain *Train, command_data const &Command) +{ + if (Train->mvOccupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc + auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + // already disabled + if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_left) == 0) + { + return; + } + + // turn off + Train->mvOccupied->iLights[vehicleotherend] ^= light::headlight_left; + // visual feedback + Train->ggRearRightLightButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_headlighttogglerearupper(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_upper) == 0) + { + OnCommand_headlightenablerearupper(Train, Command); + } + else + { + OnCommand_headlightdisablerearupper(Train, Command); + } + } +} + +void TTrain::OnCommand_headlightenablerearupper(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_upper) == 0) + { + // turn on + Train->mvOccupied->iLights[vehicleotherend] ^= light::headlight_upper; + // visual feedback + Train->ggRearUpperLightButton.UpdateValue(1.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_headlightdisablerearupper(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + // already disabled? + if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_upper) == 0) + { + return; + } + + // turn off + Train->mvOccupied->iLights[vehicleotherend] ^= light::headlight_upper; + // visual feedback + Train->ggRearUpperLightButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_modernlightdimmerincrease(TTrain *Train, command_data const &Command) +{ + if (!Train->mvOccupied->enableModernDimmer) + return; // if modern dimmer is disabled, skip entire command + if (Command.action == GLFW_PRESS) + { + // update modern dimmer state + if (false == Train->mvOccupied->stepDimmerPosition(1)) + return; // już na maksimum i nie można cyklicznie + auto const dimPos = Train->mvOccupied->modernDimmerPosition; + // update lightning + // Train->Dynamic()->SetLights(); + Train->Dynamic()->SetLightDimmings(); + + // visual feedback + if (Train->ggModernLightDimSw.SubModel != nullptr) + Train->ggModernLightDimSw.UpdateValue(static_cast(dimPos), Train->dsbSwitch); + } +} +void TTrain::OnCommand_modernlightdimmerdecrease(TTrain *Train, command_data const &Command) +{ + if (!Train->mvOccupied->enableModernDimmer) + return; // jeśli dimmer jest wyłączony, olewamy + + if (Command.action == GLFW_PRESS) + { + if (false == Train->mvOccupied->stepDimmerPosition(-1)) + return; // już na minimum i nie można cyklicznie + auto const dimPos = Train->mvOccupied->modernDimmerPosition; + + // Train->Dynamic()->SetLights(); + Train->Dynamic()->SetLightDimmings(); + + if (Train->ggModernLightDimSw.SubModel != nullptr) + Train->ggModernLightDimSw.UpdateValue(static_cast(dimPos), Train->dsbSwitch); + } +} + +void TTrain::OnCommand_redmarkertogglerearleft(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc + auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_right) == 0) + { + OnCommand_redmarkerenablerearleft(Train, Command); + } + else + { + OnCommand_redmarkerdisablerearleft(Train, Command); + } + } +} + +void TTrain::OnCommand_redmarkerenablerearleft(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc + auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_right) == 0) + { + // turn on + Train->mvOccupied->iLights[vehicleotherend] ^= light::redmarker_right; + // visual feedback + Train->ggRearLeftEndLightButton.UpdateValue(1.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_redmarkerdisablerearleft(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc + auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_right) == 0) + { + return; + } + // turn off + Train->mvOccupied->iLights[vehicleotherend] ^= light::redmarker_right; + // visual feedback + Train->ggRearLeftEndLightButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_redmarkertogglerearright(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc + auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_left) == 0) + { + OnCommand_redmarkerenablerearright(Train, Command); + } + else + { + OnCommand_redmarkerdisablerearright(Train, Command); + } + } +} + +void TTrain::OnCommand_redmarkerenablerearright(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc + auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_left) == 0) + { + // turn on + Train->mvOccupied->iLights[vehicleotherend] ^= light::redmarker_left; + // visual feedback + Train->ggRearRightEndLightButton.UpdateValue(1.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_redmarkerdisablerearright(TTrain *Train, command_data const &Command) +{ + + if (Train->mvOccupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc + auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_left) == 0) + { + return; + } + // turn off + Train->mvOccupied->iLights[vehicleotherend] ^= light::redmarker_left; + // visual feedback + Train->ggRearRightEndLightButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_redmarkerstoggle(TTrain * /*Train*/, command_data const &Command) +{ + + if (true == Command.freefly && Command.action == GLFW_PRESS) + { + + auto *vehicle{std::get(simulation::Region->find_vehicle(Command.location, 10, false, true))}; + + if (vehicle == nullptr) + { + return; + } + + auto locationHead = vehicle->HeadPosition() - glm::dvec3(Command.location); // TODO: Maybe command_data should be dvec3? + auto locationRear = vehicle->RearPosition() - glm::dvec3(Command.location); + int const CouplNr{std::clamp(vehicle->DirectionGet() * (glm::dot(locationHead, locationHead) > glm::dot(locationRear, locationRear) ? 1 : -1), 0, 1)}; // z [-1,1] zrobić [0,1] + + auto const lightset{light::redmarker_left | light::redmarker_right}; + + vehicle->MoverParameters->iLights[CouplNr] = + false == TestFlag(vehicle->MoverParameters->iLights[CouplNr], lightset) ? + vehicle->MoverParameters->iLights[CouplNr] |= lightset : // turn signals on + vehicle->MoverParameters->iLights[CouplNr] ^= lightset; // turn signals off + } +} + +void TTrain::OnCommand_endsignalstoggle(TTrain * /*Train*/, command_data const &Command) +{ + + if (true == Command.freefly && Command.action == GLFW_PRESS) + { + + auto *vehicle{std::get(simulation::Region->find_vehicle(Command.location, 10, false, true))}; + + if (vehicle == nullptr) + { + return; + } + int const CouplNr{ + std::clamp(vehicle->DirectionGet() * (glm::length2(vehicle->HeadPosition() - glm::dvec3(Command.location)) > glm::length2(vehicle->RearPosition() - glm::dvec3(Command.location)) ? 1 : -1), 0, + 1)}; // z [-1,1] zrobić [0,1] + + auto const lightset{light::rearendsignals}; + + vehicle->MoverParameters->iLights[CouplNr] = + false == TestFlag(vehicle->MoverParameters->iLights[CouplNr], lightset) ? + vehicle->MoverParameters->iLights[CouplNr] |= lightset : // turn signals on + vehicle->MoverParameters->iLights[CouplNr] ^= lightset; // turn signals off + } +} + +void TTrain::OnCommand_headlightsdimtoggle(TTrain *Train, command_data const &Command) +{ + if (Train->DynamicObject->MoverParameters->enableModernDimmer) + return; + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Train->DynamicObject->MoverParameters->modernDimmerPosition == 0) + { + // turn on + OnCommand_headlightsdimenable(Train, Command); + } + else + { + // turn off + OnCommand_headlightsdimdisable(Train, Command); + } + } +} + +void TTrain::OnCommand_headlightsdimenable(TTrain *Train, command_data const &Command) +{ + + if (Train->DynamicObject->MoverParameters->enableModernDimmer) + return; + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Train->ggDimHeadlightsButton.SubModel != nullptr) + { + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + // visual feedback + Train->ggDimHeadlightsButton.UpdateValue(1.0, Train->dsbSwitch); + } + + /* // to jest stara logika + if (true == Train->DynamicObject->DimHeadlights) + { + return; + } // already enabled + + Train->DynamicObject->DimHeadlights = true; + */ + Train->DynamicObject->MoverParameters->modernDimmerPosition = Train->DynamicObject->MoverParameters->clampDimmerPosition(1); // ustawiamy modern dimmer na flage przyciemnienia + Train->DynamicObject->SetLightDimmings(); + } +} + +void TTrain::OnCommand_headlightsdimdisable(TTrain *Train, command_data const &Command) +{ + + if (Train->DynamicObject->MoverParameters->enableModernDimmer) // nie wiem dlaczego to tak dziala ze jest odwrocona logika + return; + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Train->ggDimHeadlightsButton.SubModel != nullptr) + { + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + // visual feedback + Train->ggDimHeadlightsButton.UpdateValue(0.0, Train->dsbSwitch); + } + + /* // stara logika przyciemniania + if( false == Train->DynamicObject->DimHeadlights ) { return; } // already enabled + + Train->DynamicObject->DimHeadlights = false; + + */ + Train->DynamicObject->MoverParameters->modernDimmerPosition = 0; // ustawiamy modern dimmer na flage rozjasnienia + Train->DynamicObject->SetLightDimmings(); + } +} + +void TTrain::OnCommand_interiorlighttoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->Cabine[Train->iCabn].bLight) + { + // turn on + OnCommand_interiorlightenable(Train, Command); + } + else + { + // turn off + OnCommand_interiorlightdisable(Train, Command); + } + } +} + +void TTrain::OnCommand_interiorlightenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->m_controlmapper.contains("cablight_sw:")) + { + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + WriteLog("Interior Light switch is missing, or wasn't defined"); + return; + } + // store lighting switch states + if (false == Train->DynamicObject->JointCabs) + { + // vehicles with separate cabs get separate lighting switch states + Train->Cabine[Train->iCabn].bLight = true; + } + else + { + // joint virtual cabs share lighting switch states + for (auto &cab : Train->Cabine) + { + cab.bLight = true; + } + } + } +} + +void TTrain::OnCommand_interiorlightdisable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->m_controlmapper.contains("cablight_sw:")) + { + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + WriteLog("Interior Light switch is missing, or wasn't defined"); + return; + } + // store lighting switch states + if (false == Train->DynamicObject->JointCabs) + { + // vehicles with separate cabs get separate lighting switch states + Train->Cabine[Train->iCabn].bLight = false; + } + else + { + // joint virtual cabs share lighting switch states + for (auto &cab : Train->Cabine) + { + cab.bLight = false; + } + } + } +} + +void TTrain::OnCommand_interiorlightdimtoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->Cabine[Train->iCabn].bLightDim) + { + // turn on + OnCommand_interiorlightdimenable(Train, Command); + } + else + { + // turn off + OnCommand_interiorlightdimdisable(Train, Command); + } + } +} + +void TTrain::OnCommand_interiorlightdimenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Train->ggCabLightDimButton.SubModel == nullptr) + { + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + WriteLog("Dim Interior Light switch is missing, or wasn't defined"); + return; + } + // visual feedback + Train->ggCabLightDimButton.UpdateValue(1.0, Train->dsbSwitch); + // store lighting switch states + if (false == Train->DynamicObject->JointCabs) + { + // vehicles with separate cabs get separate lighting switch states + Train->Cabine[Train->iCabn].bLightDim = true; + } + else + { + // joint virtual cabs share lighting switch states + for (auto &cab : Train->Cabine) + { + cab.bLightDim = true; + } + } + } +} + +void TTrain::OnCommand_interiorlightdimdisable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Train->ggCabLightDimButton.SubModel == nullptr) + { + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + WriteLog("Dim Interior Light switch is missing, or wasn't defined"); + return; + } + // visual feedback + Train->ggCabLightDimButton.UpdateValue(0.0, Train->dsbSwitch); + // store lighting switch states + if (false == Train->DynamicObject->JointCabs) + { + // vehicles with separate cabs get separate lighting switch states + Train->Cabine[Train->iCabn].bLightDim = false; + } + else + { + // joint virtual cabs share lighting switch states + for (auto &cab : Train->Cabine) + { + cab.bLightDim = false; + } + } + } +} + +void TTrain::OnCommand_compartmentlightstoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Command.action == GLFW_RELEASE) + { + // the press changed the state the command is picked from below, so a release picked from it went to the other + // command and the push button that was pressed never withdrew its request. The release goes to both commands: + // each returns its own push type control to the neutral position and withdraws its request + OnCommand_compartmentlightsenable(Train, Command); + OnCommand_compartmentlightsdisable(Train, Command); + return; + } + + // keep the switch from flipping back and forth if key is held down + if (false == Train->mvOccupied->CompartmentLights.is_active && false == Train->mvOccupied->CompartmentLights.is_enabled) + { + // turn on + OnCommand_compartmentlightsenable(Train, Command); + } + else + { + // turn off + OnCommand_compartmentlightsdisable(Train, Command); + } +} + +void TTrain::OnCommand_compartmentlightsenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + Train->mvOccupied->CompartmentLightsSwitch(true); + // withdraw the off request, unless a push type control in the cab withdraws it when released + if (compartment_lights_switch::withdraws_other_request(Train->m_controlmapper.contains("compartmentlights_sw:"), Train->ggCompartmentLightsButton.is_toggle(), + Train->m_controlmapper.contains("compartmentlightsoff_sw:"))) + { + Train->mvOccupied->CompartmentLightsSwitchOff(false); + } + // visual feedback + if (Train->m_controlmapper.contains("compartmentlights_sw:")) + { + Train->ggCompartmentLightsButton.UpdateValue(1.0f, Train->dsbSwitch); + } + if (Train->m_controlmapper.contains("compartmentlightson_sw:")) + { + Train->ggCompartmentLightsOnButton.UpdateValue(1.0f, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + if (Train->m_controlmapper.contains("compartmentlights_sw:") && Train->ggCompartmentLightsButton.type() == TGaugeType::push) + { + // return the switch to neutral position + Train->mvOccupied->CompartmentLightsSwitch(false); + Train->mvOccupied->CompartmentLightsSwitchOff(false); + Train->ggCompartmentLightsButton.UpdateValue(0.5f); + } + if (Train->m_controlmapper.contains("compartmentlightson_sw:")) + { + Train->mvOccupied->CompartmentLightsSwitch(false); + Train->ggCompartmentLightsOnButton.UpdateValue(0.0f, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_compartmentlightsdisable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + Train->mvOccupied->CompartmentLightsSwitchOff(true); + // withdraw the on request, unless a push type control in the cab withdraws it when released + if (compartment_lights_switch::withdraws_other_request(Train->m_controlmapper.contains("compartmentlights_sw:"), Train->ggCompartmentLightsButton.is_toggle(), + Train->m_controlmapper.contains("compartmentlightson_sw:"))) + { + Train->mvOccupied->CompartmentLightsSwitch(false); + } + // visual feedback + if (Train->m_controlmapper.contains("compartmentlights_sw:")) + { + Train->ggCompartmentLightsButton.UpdateValue(0.0f, Train->dsbSwitch); + } + if (Train->m_controlmapper.contains("compartmentlightsoff_sw:")) + { + Train->ggCompartmentLightsOffButton.UpdateValue(1.0f, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + if (Train->m_controlmapper.contains("compartmentlights_sw:") && Train->ggCompartmentLightsButton.type() == TGaugeType::push) + { + // return the switch to neutral position + Train->mvOccupied->CompartmentLightsSwitch(false); + Train->mvOccupied->CompartmentLightsSwitchOff(false); + Train->ggCompartmentLightsButton.UpdateValue(0.5f); + } + if (Train->m_controlmapper.contains("compartmentlightsoff_sw:")) + { + Train->mvOccupied->CompartmentLightsSwitchOff(false); + Train->ggCompartmentLightsOffButton.UpdateValue(0.0f, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_instrumentlighttoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->InstrumentLightActive) + { + // turn on + OnCommand_instrumentlightenable(Train, Command); + } + else + { + // turn off + OnCommand_instrumentlightdisable(Train, Command); + } + } +} + +void TTrain::OnCommand_instrumentlightenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Train->ggInstrumentLightButton.SubModel == nullptr) + { + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + WriteLog("Instrument Light switch is missing, or wasn't defined"); + return; + } + // visual feedback + Train->ggInstrumentLightButton.UpdateValue(1.0, Train->dsbSwitch); + + if (true == Train->InstrumentLightActive) + { + return; + } // already enabled + + Train->InstrumentLightActive = true; + } +} + +void TTrain::OnCommand_instrumentlightdisable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Train->ggInstrumentLightButton.SubModel == nullptr) + { + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + WriteLog("Instrument Light switch is missing, or wasn't defined"); + return; + } + // visual feedback + Train->ggInstrumentLightButton.UpdateValue(0.0, Train->dsbSwitch); + + if (false == Train->InstrumentLightActive) + { + return; + } // already disabled + + Train->InstrumentLightActive = false; + } +} + +void TTrain::OnCommand_dashboardlighttoggle(TTrain *Train, command_data const &Command) +{ + if (false == Train->DashboardLightActive) + { + OnCommand_dashboardlightenable(Train, Command); + } + else + { + OnCommand_dashboardlightdisable(Train, Command); + } +} + +void TTrain::OnCommand_dashboardlightenable(TTrain *Train, command_data const &Command) +{ + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Command.action != GLFW_PRESS) + { + return; + } + + if (Train->ggDashboardLightButton.SubModel == nullptr) + { + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + WriteLog("Dashboard Light switch is missing, or wasn't defined"); + return; + } + + if (false == Train->DashboardLightActive) + { + // turn on + Train->DashboardLightActive = true; + // visual feedback + Train->ggDashboardLightButton.UpdateValue(1.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_dashboardlightdisable(TTrain *Train, command_data const &Command) +{ + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Command.action != GLFW_PRESS) + { + return; + } + + if (Train->ggDashboardLightButton.SubModel == nullptr) + { + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + WriteLog("Dashboard Light switch is missing, or wasn't defined"); + return; + } + + if (Train->DashboardLightActive) + { + // turn off + Train->DashboardLightActive = false; + // visual feedback + Train->ggDashboardLightButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_timetablelighttoggle(TTrain *Train, command_data const &Command) +{ + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Command.action != GLFW_PRESS) + { + return; + } + + if (false == Train->TimetableLightActive) + { + OnCommand_timetablelightenable(Train, Command); + } + else + { + OnCommand_timetablelightdisable(Train, Command); + } +} + +void TTrain::OnCommand_timetablelightenable(TTrain *Train, command_data const &Command) +{ + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Command.action != GLFW_PRESS) + { + return; + } + + if (Train->ggTimetableLightButton.SubModel == nullptr) + { + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + WriteLog("Timetable Light switch is missing, or wasn't defined"); + return; + } + + if (false == Train->TimetableLightActive) + { + // turn on + Train->TimetableLightActive = true; + // visual feedback + Train->ggTimetableLightButton.UpdateValue(1.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_timetablelightdisable(TTrain *Train, command_data const &Command) +{ + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Command.action != GLFW_PRESS) + { + return; + } + + if (Train->ggTimetableLightButton.SubModel == nullptr) + { + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + WriteLog("Timetable Light switch is missing, or wasn't defined"); + return; + } + if (Train->TimetableLightActive) + { + // turn off + Train->TimetableLightActive = false; + // visual feedback + Train->ggTimetableLightButton.UpdateValue(0.0, Train->dsbSwitch); + } +} diff --git a/vehicle/cab/pantographcommands.cpp b/vehicle/cab/pantographcommands.cpp new file mode 100644 index 000000000..7c96a8b3e --- /dev/null +++ b/vehicle/cab/pantographcommands.cpp @@ -0,0 +1,608 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the commands of the pantographs and their compressor + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/mover.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +void TTrain::OnCommand_pantographtogglefront(TTrain *Train, command_data const &Command) +{ + + // HACK: presence of pantograph selector prevents manual operation of the individual valves + if (Train->m_controlmapper.contains("pantselect_sw:")) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const &pantograph{Train->mvPantographUnit->Pantographs[end::front]}; + auto const state{pantograph.valve.is_enabled || pantograph.is_active}; // fallback for impulse switches + if (state) + { + OnCommand_pantographlowerfront(Train, Command); + } + else + { + OnCommand_pantographraisefront(Train, Command); + } + } + else if (Command.action == GLFW_RELEASE) + { + // impulse switches return automatically to neutral position + if (Train->mvOccupied->PantSwitchType == "impulse") + { + auto const ismanual{Train->iCabn == 0}; + Train->mvOccupied->OperatePantographValve(end::front, operation_t::none, ismanual ? range_t::local : range_t::consist); + } + } +} + +void TTrain::OnCommand_pantographtogglerear(TTrain *Train, command_data const &Command) +{ + + // HACK: presence of pantograph selector prevents manual operation of the individual valves + if (Train->m_controlmapper.contains("pantselect_sw:")) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const &pantograph{Train->mvPantographUnit->Pantographs[end::rear]}; + auto const state{pantograph.valve.is_enabled || pantograph.is_active}; // fallback for impulse switches + if (state) + { + OnCommand_pantographlowerrear(Train, Command); + } + else + { + OnCommand_pantographraiserear(Train, Command); + } + } + else if (Command.action == GLFW_RELEASE) + { + // impulse switches return automatically to neutral position + if (Train->mvOccupied->PantSwitchType == "impulse") + { + auto const ismanual{Train->iCabn == 0}; + Train->mvOccupied->OperatePantographValve(end::rear, operation_t::none, ismanual ? range_t::local : range_t::consist); + } + } +} + +void TTrain::OnCommand_pantographraisefront(TTrain *Train, command_data const &Command) +{ + + // HACK: presence of pantograph selector prevents manual operation of the individual valves + if (Train->m_controlmapper.contains("pantselect_sw:")) + { + return; + } + // prevent operation without submodel outside of engine compartment + if (Train->iCabn != 0 && false == Train->m_controlmapper.contains("pantfront_sw:")) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers + auto const ismanual{Train->iCabn == 0}; + Train->mvOccupied->OperatePantographValve(end::front, Train->mvOccupied->PantSwitchType == "impulse" ? operation_t::enable_on : operation_t::enable, + ismanual ? range_t::local : range_t::consist); + } + else if (Command.action == GLFW_RELEASE) + { + // NOTE: bit of a hax here, we're reusing button reset routine so we don't need a copy in every branch + OnCommand_pantographtogglefront(Train, Command); + } +} + +void TTrain::OnCommand_pantographraiserear(TTrain *Train, command_data const &Command) +{ + + // HACK: presence of pantograph selector prevents manual operation of the individual valves + if (Train->m_controlmapper.contains("pantselect_sw:")) + { + return; + } + // prevent operation without submodel outside of engine compartment + if (Train->iCabn != 0 && false == Train->m_controlmapper.contains("pantrear_sw:")) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers + auto const ismanual{Train->iCabn == 0}; + Train->mvOccupied->OperatePantographValve(end::rear, Train->mvOccupied->PantSwitchType == "impulse" ? operation_t::enable_on : operation_t::enable, + ismanual ? range_t::local : range_t::consist); + } + else if (Command.action == GLFW_RELEASE) + { + // NOTE: bit of a hax here, we're reusing button reset routine so we don't need a copy in every branch + OnCommand_pantographtogglerear(Train, Command); + } +} + +void TTrain::OnCommand_pantographlowerfront(TTrain *Train, command_data const &Command) +{ + + // HACK: presence of pantograph selector prevents manual operation of the individual valves + if (Train->m_controlmapper.contains("pantselect_sw:")) + { + return; + } + // prevent operation without submodel outside of engine compartment + if (Train->iCabn != 0 && false == Train->m_controlmapper.contains(Train->mvOccupied->PantSwitchType == "impulse" ? "pantfrontoff_sw:" : "pantfront_sw:")) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers + auto const ismanual{Train->iCabn == 0}; + Train->mvOccupied->OperatePantographValve(end::front, Train->mvOccupied->PantSwitchType == "impulse" ? operation_t::disable_on : operation_t::disable, + ismanual ? range_t::local : range_t::consist); + } + else if (Command.action == GLFW_RELEASE) + { + // NOTE: bit of a hax here, we're reusing button reset routine so we don't need a copy in every branch + OnCommand_pantographtogglefront(Train, Command); + } +} + +void TTrain::OnCommand_pantographlowerrear(TTrain *Train, command_data const &Command) +{ + + // HACK: presence of pantograph selector prevents manual operation of the individual valves + if (Train->m_controlmapper.contains("pantselect_sw:")) + { + return; + } + + if (Train->iCabn != 0 && false == Train->m_controlmapper.contains(Train->mvOccupied->PantSwitchType == "impulse" ? "pantrearoff_sw:" : "pantrear_sw:")) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers + auto const ismanual{Train->iCabn == 0}; + Train->mvOccupied->OperatePantographValve(end::rear, Train->mvOccupied->PantSwitchType == "impulse" ? operation_t::disable_on : operation_t::disable, + ismanual ? range_t::local : range_t::consist); + } + else if (Command.action == GLFW_RELEASE) + { + // NOTE: bit of a hax here, we're reusing button reset routine so we don't need a copy in every branch + OnCommand_pantographtogglerear(Train, Command); + } +} + +void TTrain::OnCommand_pantographlowerall(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggPantAllDownButton.SubModel == nullptr) + { + // TODO: expand definition of cab controls so we can know if the control is present without testing for presence of 3d switch + if (Command.action == GLFW_PRESS) + { + WriteLog("Lower All Pantographs switch is missing, or wasn't defined"); + } + return; + } + + if (Train->ggPantAllDownButton.type() == TGaugeType::toggle) + { + // two-state switch, only cares about press events + if (Command.action == GLFW_PRESS) + { + Train->mvPantographUnit->DropAllPantographs(false == Train->mvPantographUnit->PantAllDown); + // visual feedback + Train->ggPantAllDownButton.UpdateValue(Train->mvPantographUnit->PantAllDown ? 1.0 : 0.0, Train->dsbSwitch); + } + } + else + { + // impulse switch + Train->mvControlled->DropAllPantographs(Command.action == GLFW_PRESS); + // visual feedback + Train->ggPantAllDownButton.UpdateValue(Command.action == GLFW_PRESS ? 1.0 : 0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_pantographselectnext(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_PRESS) + { + return; + } + + if (false == Train->m_controlmapper.contains("pantselect_sw:")) + { + return; + } + + Train->change_pantograph_selection(1); +} + +void TTrain::OnCommand_pantographselectprevious(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_PRESS) + { + return; + } + + if (false == Train->m_controlmapper.contains("pantselect_sw:")) + { + return; + } + + Train->change_pantograph_selection(-1); +} + +void TTrain::OnCommand_pantographtoggleselected(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // recalculate pantograph state (hujhujhuj) + Train->change_pantograph_selection(1); + Train->change_pantograph_selection(-1); + + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const state{Train->mvPantographUnit->PantsValve.is_enabled || Train->mvPantographUnit->PantsValve.is_active}; // fallback for impulse switches + if (state) + { + OnCommand_pantographlowerselected(Train, Command); + } + else + { + OnCommand_pantographraiseselected(Train, Command); + } + } + else if (Command.action == GLFW_RELEASE) + { + // impulse switches return automatically to neutral position + if (Train->m_controlmapper.contains("pantselectedoff_sw:")) + { + // two buttons setup + if (Train->ggPantSelectedButton.type() != TGaugeType::toggle) + { + Train->mvOccupied->OperatePantographsValve(operation_t::enable_off); + // visual feedback + Train->ggPantSelectedButton.UpdateValue(0.0, Train->dsbSwitch); + } + if (Train->ggPantSelectedDownButton.type() != TGaugeType::toggle) + { + Train->mvOccupied->OperatePantographsValve(operation_t::disable_off); + // visual feedback + Train->ggPantSelectedDownButton.UpdateValue(0.0, Train->dsbSwitch); + } + } + else + { + if (Train->ggPantSelectedButton.type() != TGaugeType::toggle) + { + // special case, just one impulse switch controlling both states + // with neutral position mid-way + Train->mvOccupied->OperatePantographsValve(operation_t::none); + // visual feedback + Train->ggPantSelectedButton.UpdateValue(0.5, Train->dsbSwitch); + } + } + } +} + +void TTrain::OnCommand_pantographraiseselected(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // raise selected + Train->mvOccupied->OperatePantographsValve(Train->ggPantSelectedButton.type() != TGaugeType::toggle ? operation_t::enable_on : operation_t::enable); + // visual feedback + Train->ggPantSelectedButton.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // NOTE: bit of a hax here, we're reusing button reset routine so we don't need a copy in every branch + OnCommand_pantographtoggleselected(Train, Command); + } +} + +void TTrain::OnCommand_pantographlowerselected(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // lower selected + Train->mvOccupied->OperatePantographsValve(Train->ggPantSelectedDownButton.type() != TGaugeType::toggle ? operation_t::disable_on : operation_t::disable); + // visual feedback + if (Train->m_controlmapper.contains("pantselectedoff_sw:")) + { + // two button setup + Train->ggPantSelectedDownButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // single button + Train->ggPantSelectedButton.UpdateValue(0.0, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + // NOTE: bit of a hax here, we're reusing button reset routine so we don't need a copy in every branch + OnCommand_pantographtoggleselected(Train, Command); + } +} + +void TTrain::update_pantograph_valves() +{ + using enum operation_t; + + auto const &presets{mvOccupied->PantsPreset.first}; + auto const &selection{mvOccupied->PantsPreset.second[cab_to_end()]}; + + auto const preset{presets[selection] - '0'}; + auto const swapends{cab_to_end() != end::front}; + // check desired states for both pantographs; value: whether the pantograph should be raised + auto const frontstate{preset & (swapends ? 2 : 1)}; + auto const rearstate{preset & (swapends ? 1 : 2)}; + mvOccupied->OperatePantographValve(end::front, frontstate ? enable : disable); + mvOccupied->OperatePantographValve(end::rear, rearstate ? enable : disable); +} + +void TTrain::change_pantograph_selection(int const Change) +{ + + auto const &presets{mvOccupied->PantsPreset.first}; + auto &selection{mvOccupied->PantsPreset.second[cab_to_end()]}; + auto const initialstate{selection}; + selection = std::clamp(selection + Change, 0, std::max(static_cast(presets.size() - 1), 0)); + + if (selection == initialstate) + { + return; + } // no change, nothing to do + + // potentially adjust pantograph valves to match the new state + if (false == m_controlmapper.contains("pantvalves_sw:")) + { + update_pantograph_valves(); + } +} + +void TTrain::OnCommand_pantographvalvesupdate(TTrain *Train, command_data const &Command) +{ + + bool hasSeparateSwitches = Train->m_controlmapper.contains("pantvalvesupdate_bt:") && Train->m_controlmapper.contains("pantvalvesoff_bt:"); + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + if (hasSeparateSwitches) + { + // implement action + Train->update_pantograph_valves(); + // visual feedback + Train->ggPantValvesUpdate.UpdateValue(1.0, Train->dsbSwitch); + } + + // Old logic to maintain compatibility + else + { + Train->update_pantograph_valves(); + Train->ggPantValvesButton.UpdateValue(1.0, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + // NOTE: pantvalves_sw: is a specialized button, with no toggle behavior support + if (hasSeparateSwitches) + Train->ggPantValvesUpdate.UpdateValue(0.5, Train->dsbSwitch); + + // Old logic to maintain compatibility + else + Train->ggPantValvesButton.UpdateValue(0.5, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_pantographvalvesoff(TTrain *Train, command_data const &Command) +{ + + bool hasSeparateSwitches = Train->m_controlmapper.contains("pantvalvesupdate_bt:") && Train->m_controlmapper.contains("pantvalvesoff_bt:"); + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // implement action + Train->mvOccupied->OperatePantographValve(end::front, operation_t::disable); + Train->mvOccupied->OperatePantographValve(end::rear, operation_t::disable); + // visual feedback + if (hasSeparateSwitches) + Train->ggPantValvesOff.UpdateValue(1.0, Train->dsbSwitch); + else + Train->ggPantValvesButton.UpdateValue(0.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + // NOTE: pantvalves_sw: is a speciali zed button, with no toggle behavior support + if (hasSeparateSwitches) + Train->ggPantValvesOff.UpdateValue(0.f, Train->dsbSwitch); + else + Train->ggPantValvesButton.UpdateValue(0.5, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_pantographcompressorvalvetoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only react to press + if (Train->mvControlled->bPantKurek3 == false) + { + // connect pantographs with primary tank + OnCommand_pantographcompressorvalveenable(Train, Command); + } + else + { + // connect pantograps with pantograph compressor + OnCommand_pantographcompressorvalvedisable(Train, Command); + } + } +} + +void TTrain::OnCommand_pantographcompressorvalveenable(TTrain *Train, command_data const &Command) +{ + + + if (auto const valveispresent{Train->ggPantCompressorValve.SubModel != nullptr || (Train->mvOccupied == Train->mvPantographUnit && Train->iCabn == 0)}; false == valveispresent) + { + // tylko w maszynowym, unless actual device is present + return; + } + + if (Command.action == GLFW_PRESS) + { + // only react to press + // connect pantographs with primary tank + Train->mvControlled->bPantKurek3 = true; + // visual feedback: + Train->ggPantCompressorValve.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_pantographcompressorvalvedisable(TTrain *Train, command_data const &Command) +{ + + + if (auto const valveispresent{Train->ggPantCompressorValve.SubModel != nullptr || (Train->mvOccupied == Train->mvPantographUnit && Train->iCabn == 0)}; false == valveispresent) + { + // tylko w maszynowym, unless actual device is present + return; + } + + if (Command.action == GLFW_PRESS) + { + // only react to press + // connect pantograps with pantograph compressor + Train->mvControlled->bPantKurek3 = false; + // visual feedback: + Train->ggPantCompressorValve.UpdateValue(1.0); + } +} + +void TTrain::OnCommand_pantographcompressoractivate(TTrain *Train, command_data const &Command) +{ + + // tylko w maszynowym, unless actual device is present + if (auto const switchispresent{Train->m_controlmapper.contains("pantcompressor_sw:") || (Train->mvOccupied == Train->mvPantographUnit && Train->iCabn == 0)}; false == switchispresent) + { + return; + } + + if (Command.action != GLFW_RELEASE) + { + // press or hold to activate + if (Train->mvPantographUnit->PantPress < 4.8 && true == Train->mvPantographUnit->Power24vIsAvailable) + { + // needs live power source and low enough pressure to work + Train->mvPantographUnit->PantCompFlag = true; + } + // visual feedback + Train->ggPantCompressorButton.UpdateValue(1.0); + } + else + { + // release to disable + Train->mvPantographUnit->PantCompFlag = false; + // visual feedback + Train->ggPantCompressorButton.UpdateValue(0.0); + } +} diff --git a/vehicle/cab/powercommands.cpp b/vehicle/cab/powercommands.cpp new file mode 100644 index 000000000..d9f9576d1 --- /dev/null +++ b/vehicle/cab/powercommands.cpp @@ -0,0 +1,569 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the commands of the line breaker, the traction motors and their relays + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/mover.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +// whether the cab's main_off_bt is the bistable lever of the line breaker's hold coil (eu07/maszyna#364) +bool is_hold_coil_lever(TGauge const &Button) +{ + return Button.SubModel != nullptr && hold_coil_lever::is_bistable(Button.type_declared(), Button.type() == TGaugeType::toggle); +} + +void TTrain::OnCommand_linebreakertoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // press or hold... + // a single two-state lever stays where it was put, also when the line breaker gets knocked out + auto const latchinglever{Train->ggMainOnButton.SubModel == nullptr && Train->ggMainOffButton.SubModel == nullptr && Train->ggMainButton.SubModel != nullptr && + Train->ggMainButton.type() == TGaugeType::toggle}; + switch (linebreaker::pressed(Train->m_linebreakerstate, latchinglever, Train->ggMainButton.GetDesiredValue() > 0.5)) + { + case linebreaker::toggle::close: + // ...to close the circuit + if (is_hold_coil_lever(Train->ggMainOffButton) && hold_coil_lever::cuts_off(Train->ggMainOffButton.GetDesiredValue())) + { + // the one key works both controls: the hold coil lever goes back on first, or the line breaker couldn't close + Train->ggMainOffButton.UpdateValue(0.0, Train->dsbSwitch); + } + // NOTE: bit of a dirty shortcut here + OnCommand_linebreakerclose(Train, Command); + break; + case linebreaker::toggle::open: + // ...to open the circuit, or to put the lever off if the circuit was already opened + OnCommand_linebreakeropen(Train, Command); + break; + default: + break; + } + } + else if (Command.action == GLFW_RELEASE) + { + // release... + if (Train->ggMainOnButton.SubModel != nullptr || Train->ggMainButton.type() != TGaugeType::toggle) + { + // only impulse switches react to release events + // NOTE: we presume dedicated state switch is of impulse type + if (Train->m_linebreakerstate == linebreaker::state::open) + { + // ...after opening circuit, or holding for too short time to close it + OnCommand_linebreakeropen(Train, Command); + } + else + { + // ...after closing the circuit + // NOTE: bit of a dirty shortcut here + OnCommand_linebreakerclose(Train, Command); + } + } + // HACK: ignition key ignores lack of submodel, so we can start vehicles without any modeled controls + Train->ggIgnitionKey.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_linebreakeropen(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + if (is_hold_coil_lever(Train->ggMainOffButton)) + { + // the bistable lever goes over to its other position and stays there + auto const position{hold_coil_lever::operated(Train->ggMainOffButton.GetDesiredValue())}; + Train->ggMainOffButton.UpdateValue(position, Train->dsbSwitch); + if (false == hold_coil_lever::cuts_off(position)) + { + // the hold coil is fed again, which by itself doesn't close the line breaker + return; + } + } + else if (Train->ggMainOffButton.SubModel != nullptr) + { + Train->ggMainOffButton.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Train->ggMainButton.SubModel != nullptr) + { + Train->ggMainButton.UpdateValue(0.0, Train->dsbSwitch); + } + else if (Train->ggMainOnButton.SubModel != nullptr && false == Train->mvControlled->MainCircuitOpensWithStarterOnly()) + { + // NOTE: legacy behaviour, for vehicles equipped only with impulse close switch + // it doesn't make any real sense to animate this one, but some people can't get over how there's no visual reaction to their keypress + Train->ggMainOnButton.UpdateValue(1.0, Train->dsbSwitch); + return; + } + // a diesel with only the starter button gets its engine stopped. the button stays put: held down, it would start the engine again + // play sound immediately when the switch is hit, not after release + Train->fMainRelayTimer = 0.0f; + + if (Train->m_linebreakerstate == linebreaker::state::open) + { + return; + } // already in the desired state + + if (true == Train->mvControlled->MainSwitch(false, Train->mvControlled->MainSwitchRange())) + { + Train->m_linebreakerstate = linebreaker::state::open; + if (Train->mvControlled->MainSwitchRange() != range_t::local) + { + // the engines of the vehicles in multiple stopped along: their two-state switches go off too, left on + // they'd start them again after the delay + for (auto &controls : Train->m_remotelinebreakers) + { + if (controls.main_switch.SubModel != nullptr && controls.main_switch.type() == TGaugeType::toggle) + { + controls.main_switch.UpdateValue(0.0); + } + } + } + } + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + // we don't exactly know which of the two buttons was used, so reset both + // for setup with two separate swiches + if (Train->ggMainOnButton.SubModel != nullptr) + { + Train->ggMainOnButton.UpdateValue(0.0, Train->dsbSwitch); + } + if (Train->ggMainOffButton.SubModel != nullptr && false == is_hold_coil_lever(Train->ggMainOffButton)) + { + // (the bistable hold coil lever stays where it was put) + Train->ggMainOffButton.UpdateValue(0.0, Train->dsbSwitch); + } + // and the two-state switch too, for good measure + if (Train->ggMainButton.SubModel != nullptr) + { + Train->ggMainButton.UpdateValue(Train->ggMainButton.type() != TGaugeType::toggle ? 0.5 : 0.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_linebreakerclose(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + if (Train->ggMainOnButton.SubModel != nullptr) + { + // two separate switches to close and break the circuit + Train->ggMainOnButton.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Train->ggMainButton.SubModel != nullptr) + { + // single two-state switch + Train->ggMainButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // no switch capable of doing the job + // HACK: ignition key ignores lack of submodel, so we can start vehicles without any modeled controls + Train->ggIgnitionKey.UpdateValue(1.0); + return; + } + // the actual closing of the line breaker is handled in the train update routine + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + if (Train->ggMainOnButton.SubModel != nullptr) + { + // setup with two separate switches + Train->ggMainOnButton.UpdateValue(0.0, Train->dsbSwitch); + } + else if (Train->ggMainButton.SubModel != nullptr && Train->ggMainButton.type() != TGaugeType::toggle) + { + Train->ggMainButton.UpdateValue(0.5, Train->dsbSwitch); + } + + if (Train->m_linebreakerstate == linebreaker::state::closed) + { + return; + } // already in the desired state + + // we don't need to start the diesel twice, but the other types (with impulse switch setup) still need to be launched + // NOTE: this behaviour should depend on MainOnButton presence and type_delayed + // TODO: change it when/if vehicle definition files get their proper switch types + if (Train->m_linebreakerstate == linebreaker::state::closing && Train->mvControlled->EngineType == TEngineType::ElectricSeriesMotor) + { + // try to finalize state change of the line breaker, set the state based on the outcome + Train->m_linebreakerstate = Train->mvControlled->MainSwitch(true, Train->mvControlled->MainSwitchRange()) ? linebreaker::state::closed : linebreaker::state::open; + } + // on button release reset the closing timer + Train->fMainRelayTimer = 0.0f; + } +} +namespace +{ + + +// which of the switches of the other vehicles in multiple a command works: 0 the second vehicle's, 1 the third one's +std::size_t remote_linebreaker_index(user_command const Command) +{ + using enum user_command; + return (Command == linebreakertogglec || Command == linebreakeropenc || Command == linebreakerclosec) ? 1 : 0; +} + +// the impulse switches of another vehicle's line breaker spring back when let go, whichever way they were pressed +void release_remote_linebreaker(TTrain::remote_linebreaker &Controls, std::optional &Sound) +{ + if (Controls.on_button.SubModel != nullptr) + { + Controls.on_button.UpdateValue(0.0, Sound); + } + if (Controls.off_button.SubModel != nullptr) + { + Controls.off_button.UpdateValue(0.0, Sound); + } + if (Controls.main_switch.SubModel != nullptr && Controls.main_switch.type() != TGaugeType::toggle) + { + Controls.main_switch.UpdateValue(0.5, Sound); + } + Controls.held_without_switch = false; +} + +} // namespace + +TMoverParameters *TTrain::remote_engine(std::size_t const Index) const +{ + return engine_start::engine(*mvOccupied, *mvControlled, static_cast(Index) + 2); +} + +void TTrain::OnCommand_linebreakertoggleremote(TTrain *Train, command_data const &Command) +{ + auto const index{remote_linebreaker_index(Command.command)}; + auto &controls{Train->m_remotelinebreakers[index]}; + + if (Command.action == GLFW_PRESS) + { + // a two-state switch goes the other way than it stands, an impulse one the other way than the engine is + bool close{false}; + if (controls.main_switch.SubModel != nullptr && controls.main_switch.type() == TGaugeType::toggle) + { + close = controls.main_switch.GetDesiredValue() < 0.5; + } + else + { + auto const *engine{Train->remote_engine(index)}; + close = engine == nullptr || false == engine_start::remote_switch::is_running(*engine); + } + if (close) + { + OnCommand_linebreakercloseremote(Train, Command); + } + else + { + OnCommand_linebreakeropenremote(Train, Command); + } + } + else if (Command.action == GLFW_RELEASE) + { + if (controls.on_button.SubModel != nullptr || controls.main_switch.type() != TGaugeType::toggle) + { + // only impulse switches react to release events + release_remote_linebreaker(controls, Train->dsbSwitch); + } + controls.held_without_switch = false; + } +} + +void TTrain::OnCommand_linebreakeropenremote(TTrain *Train, command_data const &Command) +{ + auto const index{remote_linebreaker_index(Command.command)}; + auto &controls{Train->m_remotelinebreakers[index]}; + + if (Command.action == GLFW_PRESS) + { + // visual feedback + if (controls.off_button.SubModel != nullptr) + { + controls.off_button.UpdateValue(1.0, Train->dsbSwitch); + } + else if (controls.main_switch.SubModel != nullptr) + { + controls.main_switch.UpdateValue(0.0, Train->dsbSwitch); + } + controls.held_without_switch = false; + if (auto *engine{Train->remote_engine(index)}; engine != nullptr) + { + engine_start::remote_switch::open(*engine); + } + } + else if (Command.action == GLFW_RELEASE) + { + release_remote_linebreaker(controls, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_linebreakercloseremote(TTrain *Train, command_data const &Command) +{ + auto const index{remote_linebreaker_index(Command.command)}; + auto &controls{Train->m_remotelinebreakers[index]}; + + if (Command.action == GLFW_PRESS) + { + // visual feedback; the line breaker closes in the train update, once the switch was held long enough + if (controls.on_button.SubModel != nullptr) + { + controls.on_button.UpdateValue(1.0, Train->dsbSwitch); + } + else if (controls.main_switch.SubModel != nullptr) + { + controls.main_switch.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // no switch in the cab, the command alone holds it + controls.held_without_switch = true; + } + } + else if (Command.action == GLFW_RELEASE) + { + release_remote_linebreaker(controls, Train->dsbSwitch); + } +} + +void TTrain::update_remote_linebreakers(double const Deltatime) +{ + for (std::size_t index = 0; index < m_remotelinebreakers.size(); ++index) + { + auto &controls{m_remotelinebreakers[index]}; + auto *engine{remote_engine(index)}; + auto const closeheld{controls.held_without_switch || (controls.main_switch.SubModel != nullptr && controls.main_switch.GetDesiredValue() > 0.95) || + (controls.on_button.SubModel != nullptr && controls.on_button.GetDesiredValue() > 0.95)}; + auto const openheld{controls.off_button.SubModel != nullptr && controls.off_button.GetDesiredValue() > 0.95}; + // as with the cab's own switch, an electric locomotive's impulse switch closes the line breaker when let go + auto const closesonrelease{engine != nullptr && controls.on_button.SubModel != nullptr && engine->EngineType == TEngineType::ElectricSeriesMotor}; + controls.state.update(engine, closeheld, openheld, Deltatime, closesonrelease); + } +} + +void TTrain::OnCommand_motorconnectorsopen(TTrain *Train, command_data const &Command) +{ + + // TODO: don't rely on presense of 3d model to determine presence of the switch + if (Train->ggStLinOffButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Open Motor Power Connectors button is missing, or wasn't defined"); + } + return; + } + // HACK: because we don't have modeled actual circuits this is a simplification of the real mechanics + // namely, pressing the button will flip it in the entire unit, which isn't exactly physically possible + if (Command.action == GLFW_PRESS) + { + // button works while it's held down but we can ignore repeats + if (false == Train->mvControlled->StLinSwitchOff) + { + // open the connectors + // visual feedback + Train->ggStLinOffButton.UpdateValue(1.0, Train->dsbSwitch); + + Train->mvControlled->StLinSwitchOff = true; + Train->set_paired_open_motor_connectors_button(true); + } + else + { + // potentially close the connectors + OnCommand_motorconnectorsclose(Train, Command); + } + } + else if (Command.action == GLFW_RELEASE) + { + // button released + if (Train->mvControlled->StLinSwitchType != "toggle") + { + // default button type (impulse) ceases its work on button release + // visual feedback + Train->ggStLinOffButton.UpdateValue(0.0, Train->dsbSwitch); + + Train->mvControlled->StLinSwitchOff = false; + Train->set_paired_open_motor_connectors_button(false); + } + } +} + +void TTrain::OnCommand_motorconnectorsclose(TTrain *Train, command_data const &Command) +{ + + // TODO: don't rely on presense of 3d model to determine presence of the switch + if (Train->ggStLinOffButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Open Motor Power Connectors button is missing, or wasn't defined"); + } + return; + } + + if (Command.action == GLFW_PRESS) + { + if (Train->mvControlled->StLinSwitchType == "toggle") + { + // default type of button (impulse) has only one effect on press, but the toggle type can toggle the state + // visual feedback + Train->ggStLinOffButton.UpdateValue(0.0, Train->dsbSwitch); + } + + if (false == Train->mvControlled->StLinSwitchOff) + { + return; + } // already closed + + Train->mvControlled->StLinSwitchOff = false; + Train->set_paired_open_motor_connectors_button(false); + } +} + +void TTrain::OnCommand_motordisconnect(TTrain *Train, command_data const &Command) +{ + + if (Train->mvControlled->TrainType == train_type::emu ? Train->mvControlled != Train->mvOccupied : Train->iCabn != 0) + { + // tylko w maszynowym + return; + } + + if (Command.action == GLFW_PRESS) + { + Train->mvControlled->CutOffEngine(); + } +} + +void TTrain::OnCommand_motoroverloadrelaythresholdtoggle(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (true == Train->mvControlled->ShuntModeAllow ? false == Train->mvControlled->ShuntMode : false == Train->mvControlled->MotorOverloadRelayHighThreshold) + { + // turn on + OnCommand_motoroverloadrelaythresholdsethigh(Train, Command); + } + else + { + // turn off + OnCommand_motoroverloadrelaythresholdsetlow(Train, Command); + } + } +} + +void TTrain::OnCommand_motoroverloadrelaythresholdsetlow(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->mvControlled->CurrentSwitch(false); + // visual feedback + Train->ggMaxCurrentCtrl.UpdateValue(Train->mvControlled->MotorOverloadRelayHighThreshold ? 1 : 0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_motoroverloadrelaythresholdsethigh(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->mvControlled->CurrentSwitch(true); + // visual feedback + Train->ggMaxCurrentCtrl.UpdateValue(Train->mvControlled->MotorOverloadRelayHighThreshold ? 1 : 0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_motoroverloadrelayreset(TTrain *Train, command_data const &Command) +{ + + if (Train->ggFuseButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Motor Overload Relay Reset button is missing, or wasn't defined"); + } + // return; + } + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggFuseButton.UpdateValue(1.0, Train->dsbSwitch); + + Train->mvControlled->FuseOn(); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggFuseButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_universalrelayreset(TTrain *Train, command_data const &Command) +{ + + auto const itemindex = static_cast(Command.command) - static_cast(user_command::universalrelayreset1); + auto &item = Train->ggRelayResetButtons[itemindex]; + + // NOTE: relay reset switches are impulse-only + if (Command.action == GLFW_PRESS) + { + Train->mvOccupied->UniversalResetButton(itemindex); + // visual feedback + item.UpdateValue(1.0); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + item.UpdateValue(0.0); + } +} diff --git a/vehicle/cab/screens.cpp b/vehicle/cab/screens.cpp new file mode 100644 index 000000000..c30b1b283 --- /dev/null +++ b/vehicle/cab/screens.cpp @@ -0,0 +1,173 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the screens of the cab + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/mover.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +void TTrain::update_screens(double dt) +{ + for (auto &screen : m_screens) + { + if (screen.updatetimecounter >= 0) + screen.updatetimecounter += dt; + + if (screen.updatetimecounter <= screen.updatetime) + continue; + + screen.updatetimecounter = screen.updatetime > 0 ? 0 : -1; + + auto state_dict = GetTrainState(screen.parameters); + + state_dict->insert("touches", *screen.touch_list); + screen.touch_list->clear(); + + Application.request({screen.script, state_dict, screen.rt}); + } +} + +void TTrain::update_script_screens() +{ + auto &queue{Application.screens()}; + for (auto &entry : m_scriptscreens) + { + if (false == queue.due(*entry.screen)) + { + continue; + } + auto input{GetTrainState(entry.parameters)}; + input->insert("touches", *entry.touch_list); + entry.touch_list->clear(); + queue.submit(entry.screen, std::move(input), id()); + } +} + +bool TTrain::find_screen_surface(std::string const &Target, std::string_view const Kind, TSubModel *&Submodel, ITexture *&Texture) const +{ + Submodel = DynamicObject->mdKabina ? DynamicObject->mdKabina->GetFromName(Target) : + DynamicObject->mdLowPolyInt ? DynamicObject->mdLowPolyInt->GetFromName(Target) : + nullptr; + if (Submodel == nullptr) + { + WriteLog(std::format("{}: submodel {} not found - Ignoring screen", Kind, Target)); + return false; + } + auto const material{Submodel->GetMaterial()}; + if (material <= 0) + { + // sub model nie posiada tekstury lub tekstura wymienna - nie obslugiwana + WriteLog(std::format("{}: invalid texture id {} - Ignoring screen", Kind, material)); + return false; + } + + Texture = &GfxRenderer->Texture(GfxRenderer->Material(material)->GetTexture(0)); + return true; +} + +void TTrain::load_script_screen(cParser &Parser, script_language const Language) +{ + script_screen_entry entry; + // the block is read whole even when the script screens are off + entry.config.deserialize(Parser); + if (entry.config.script.empty()) + { + return; + } + if (auto path{script_screens::screen_script_path(DynamicObject->asBaseDir, entry.config.script)}; path.has_value()) + { + entry.config.script = std::move(*path); + } + else + { + ErrorLog(std::format("Bad script screen: \"{}\" leads outside the game's folder", entry.config.script)); + return; + } + + TSubModel *submodel{nullptr}; + ITexture *texture{nullptr}; + auto &queue{Application.screens()}; + if (false == queue.runs(Language)) + { + // the screens of the language are off + return; + } + if (entry.config.target != "none" && + false == find_screen_surface(entry.config.target, Language == script_language::lua ? "Lua Screen" : "WASM Screen", submodel, texture)) + { + return; + } + + entry.screen = queue.acquire({.kind = script_screen_kind::cab, + .language = Language, + .script = entry.config.script, + .key = std::format("cab:{}:{}:{}", DynamicObject->name(), entry.config.target, entry.config.script), + .texture = texture, + .frames = entry.config.frames}); + if (entry.screen == nullptr) + { + return; + } + if (texture != nullptr) + { + // make the surface static so it doesn't get destroyed by garbage collector if the user spends long time outside cab + texture->create(true); + } + if (false == entry.config.parameters.empty()) + { + entry.parameters = dictionary_source(entry.config.parameters); + } + entry.touch_list = std::make_shared>(); + if (submodel != nullptr) + { + submodel->screen_touch_list = entry.touch_list; + } + m_scriptscreens.emplace_back(std::move(entry)); +} + +const TTrain::screenentry_sequence &TTrain::get_screens() +{ + update_screens(Timer::GetDeltaTime()); + return m_screens; +} diff --git a/vehicle/cab/setup.cpp b/vehicle/cab/setup.cpp new file mode 100644 index 000000000..ba53920d7 --- /dev/null +++ b/vehicle/cab/setup.cpp @@ -0,0 +1,2041 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// setting the cab up from its definition: its gauges and its buttons + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/mover.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +// McZapkie-310302 +// wczytywanie pliku z danymi multimedialnymi (dzwieki, kontrolki, kabiny) +bool TTrain::LoadMMediaFile(std::string const &asFileName) +{ + using enum sound_placement; + using enum sound_type; + // initialize sounds so potential entries from previous vehicle don't stick around + std::unordered_map &, sound_placement, float, sound_type, int, double>> internalsounds = { + {"ctrl:", {dsbNastawnikJazdy, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"ctrlscnd:", {dsbNastawnikBocz, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"reverserkey:", {dsbReverserKey, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"buzzer:", {dsbBuzzer, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"buzzershp:", {dsbBuzzerShp, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"radiostop:", {m_radiostop, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"slipalarm:", {dsbSlipAlarm, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"distancecounter:", {m_distancecounterclear, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"tachoclock:", {dsbHasler, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"switch:", {dsbSwitch, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"pneumaticswitch:", {dsbPneumaticSwitch, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"airsound:", {rsHiss, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, + {"airsound2:", {rsHissU, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, + {"airsound3:", {rsHissE, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, + {"airsound4:", {rsHissX, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, + {"airsound5:", {rsHissT, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, + {"localbrakesound:", {rsSBHiss, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, + {"localbrakesound2:", {rsSBHissU, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, + {"brakesound:", {rsBrake, internal, -1, single, sound_parameters::amplitude | sound_parameters::frequency, 100.0}}, + {"fadesound:", {rsFadeSound, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"runningnoise:", {rsRunningNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, mvOccupied->Vmax}}, + {"resonancenoise:", {rsResonanceNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, mvOccupied->Vmax}}, + {"windsound:", {rsWindSound, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, mvOccupied->Vmax}}, + {"huntingnoise:", {rsHuntingNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, mvOccupied->Vmax}}, + {"rainsound:", {m_rainsound, internal, -1, single, 0, 100.0}}, + }; + for (auto &[soundname, soundsource] : internalsounds) + { + std::get &>(soundsource).reset(); + } + // NOTE: since radiosound is an incomplete template not using std::optional it gets a special treatment + m_radiosound.owner(DynamicObject); + m_fmradiosound.owner(DynamicObject); + CabSoundLocations.clear(); + + cParser parser(asFileName, cParser::buffer_FILE, DynamicObject->asBaseDir, true, std::vector(), true); + // NOTE: yaml-style comments are disabled until conflict in use of # is resolved + // parser.addCommentStyle( "#", "\n" ); + std::string token; + do + { + token = ""; + parser.getTokens(); + parser >> token; + } while (token != "" && token != "internaldata:"); + + if (token == "internaldata:") + { + + do + { + token = ""; + parser.getTokens(); + parser >> token; + + auto lookup{internalsounds.find(token)}; + if (lookup == internalsounds.end()) + { + continue; + } + + auto const soundconfig{lookup->second}; + sound_source sound{std::get(soundconfig), std::get(soundconfig)}; + sound.deserialize(parser, std::get(soundconfig), std::get(soundconfig), static_cast(std::get(soundconfig))); + sound.owner(DynamicObject); + std::get &>(soundconfig) = sound; + } while (token != ""); + + // assign default samples to sound emitters which weren't included in the config file + if (!m_rainsound) + { + sound_source rainsound; + rainsound.deserialize("rainsound_default", single); + rainsound.owner(DynamicObject); + m_rainsound = rainsound; + } + if (!rsSBHiss) + { + // fallback for vehicles without defined local brake hiss sound + rsSBHiss = rsHiss; + } + if (!rsSBHissU) + { + // fallback for vehicles without defined local brake hiss sound + rsSBHissU = rsHissU; + } + if (rsBrake) + { + rsBrake->m_frequencyfactor /= static_cast(1 + mvOccupied->Vmax); + } + if (rsResonanceNoise) + { + rsResonanceNoise->m_frequencyfactor /= static_cast(1 + mvOccupied->Vmax); + } + if (rsWindSound) + { + rsWindSound->m_frequencyfactor /= static_cast(1 + mvOccupied->Vmax); + } + if (rsRunningNoise) + { + rsRunningNoise->m_frequencyfactor /= static_cast(1 + mvOccupied->Vmax); + } + if (rsHuntingNoise) + { + rsHuntingNoise->m_frequencyfactor /= static_cast(1 + mvOccupied->Vmax); + } + } + std::vector>> sounds = { + dsbReverserKey, dsbNastawnikJazdy, dsbNastawnikBocz, dsbSwitch, dsbPneumaticSwitch, rsHiss, rsHissU, rsHissE, rsHissX, rsHissT, rsSBHiss, + rsSBHissU, rsFadeSound, rsRunningNoise, rsResonanceNoise, rsWindSound, rsHuntingNoise, dsbHasler, dsbBuzzer, dsbBuzzerShp, dsbSlipAlarm, m_distancecounterclear, + m_rainsound, m_radiostop}; + for (auto &sound : sounds) + { + if (sound.get()) + { + CabSoundLocations.emplace_back(sound, sound.get()->offset()); + } + } + + return true; +} + +bool TTrain::InitializeCab(int NewCabNo, std::string const &asFileName) +{ + m_controlmapper.clear(); + // clear python screens + m_screens.clear(); + m_scriptscreens.clear(); + // reset sound positions + auto const nullvector{glm::vec3()}; + std::vector>> sounds = { + dsbReverserKey, dsbNastawnikJazdy, dsbNastawnikBocz, dsbSwitch, dsbPneumaticSwitch, rsHiss, rsHissU, rsHissE, rsHissX, rsHissT, rsSBHiss, + rsSBHissU, rsFadeSound, rsRunningNoise, rsResonanceNoise, rsWindSound, rsHuntingNoise, dsbHasler, dsbBuzzer, dsbBuzzerShp, dsbSlipAlarm, m_distancecounterclear, + m_rainsound, m_radiostop}; + for (auto const &sound : sounds) + { + if (sound.get()) + { + sound.get()->offset(nullvector); + } + } + m_radiosound.offset(nullvector); + m_fmradiosound.offset(nullvector); + m_fmradiopresent = false; + for (auto const &[soundsource, soundoffset] : CabSoundLocations) + { + if (soundsource.get() && soundsource.get()->offset() == nullvector) + { + soundsource.get()->offset(soundoffset); + } + } + // reset view angles + pMechViewAngle = {0.0, 0.0}; + + is_cab_initialized = true; // the attempt may fail, but it's the attempt that counts + + bool parse = false; + int cabindex = 0; + DynamicObject->mdKabina = nullptr; // likwidacja wskaźnika na dotychczasową kabinę + switch (NewCabNo) + { // ustalenie numeru kabiny do wczytania + case -1: + cabindex = 2; + break; + case 1: + cabindex = 1; + break; + case 0: + cabindex = 0; + break; + default: + break; + } + iCabn = cabindex; + + std::string cabstr("cab" + std::to_string(cabindex) + "definition:"); + + cParser parser(asFileName, cParser::buffer_FILE, DynamicObject->asBaseDir, true, std::vector(), true); + // NOTE: yaml-style comments are disabled until conflict in use of # is resolved + // parser.addCommentStyle( "#", "\n" ); + std::string token; + do + { + // szukanie kabiny + token = ""; + parser.getTokens(); + parser >> token; + } while (token != "" && token != cabstr); + + if (token == cabstr) + { + // jeśli znaleziony wpis kabiny + Cabine[cabindex].Load(parser); + // NOTE: the position and angle definitions depend on strict entry order + // TODO: refactor into more flexible arrangement + parser.getTokens(); + parser >> token; + if (token == std::string("driver" + std::to_string(cabindex) + "angle:")) + { + // camera view angle + parser.getTokens(2, false); + // angle is specified in degrees but internally stored in radians + glm::vec2 viewangle; + parser >> viewangle.y // yaw first, then pitch + >> viewangle.x; + pMechViewAngle = glm::radians(viewangle); + + Global.pCamera.Angle.x = pMechViewAngle.x; + Global.pCamera.Angle.y = pMechViewAngle.y; + + parser.getTokens(); + parser >> token; + } + if (token == std::string("driver" + std::to_string(cabindex) + "pos:")) + { + // pozycja poczatkowa maszynisty + parser.getTokens(3, false); + parser >> pMechOffset.x >> pMechOffset.y >> pMechOffset.z; + pMechSittingPosition = pMechOffset; + + parser.getTokens(); + parser >> token; + } + // ABu: pozycja siedzaca mechanika + if (token == std::string("driver" + std::to_string(cabindex) + "sitpos:")) + { + // ABu 180404 pozycja siedzaca maszynisty + parser.getTokens(3, false); + parser >> pMechSittingPosition.x >> pMechSittingPosition.y >> pMechSittingPosition.z; + + parser.getTokens(); + parser >> token; + } + // else parse=false; + do + { + if (parse == true) + { + token = ""; + parser.getTokens(); + parser >> token; + } + else + { + parse = true; + } + // inicjacja kabiny + // Ra 2014-08: zmieniamy zasady - zamiast przypisywać submodel do + // istniejących obiektów animujących + // będziemy teraz uaktywniać obiekty animujące z tablicy i podawać im + // submodel oraz wskaźnik na parametr + if (token == std::string("cab" + std::to_string(cabindex) + "model:")) + { + // model kabiny + parser.getTokens(); + parser >> token; + std::ranges::replace(token, '\\', '/'); + if (token != "none") + { + // bieżąca sciezka do tekstur to dynamic/... + Global.asCurrentTexturePath = DynamicObject->asBaseDir; + // szukaj kabinę jako oddzielny model + // name can contain leading slash, erase it to avoid creation of double slashes when the name is combined with current directory + replace_slashes(token); + erase_leading_slashes(token); + if (token[0] == '/') + { + token.erase(0, 1); + } + TModel3d *kabina = TModelsManager::GetModel(DynamicObject->asBaseDir + token, true, true, Global.network_servers.empty() && !Global.network_client ? 0 : id()); + // z powrotem defaultowa sciezka do tekstur + Global.asCurrentTexturePath = paths::textures; + // if (DynamicObject->mdKabina!=k) + if (kabina != nullptr) + { + DynamicObject->mdKabina = kabina; // nowa kabina + } + //(mdKabina) może zostać to samo po przejściu do innego członu bez + // zmiany kabiny, przy powrocie musi być wiązanie ponowne + // else + // break; //wyjście z pętli, bo model zostaje bez zmian + } + else if (cabindex == 1) + { + // model tylko, gdy nie ma kabiny 1 + // McZapkie-170103: szukaj elementy kabiny w glownym modelu + DynamicObject->mdKabina = DynamicObject->mdModel; + } + clear_cab_controls(); + } + /* + if (nullptr == DynamicObject->mdKabina) + { + // don't bother with other parts until the cab is initialised + continue; + } + */ + else if (true == initialize_gauge(parser, token, cabindex)) + { + // matched the token, grab the next one + continue; + } + else if (true == initialize_button(parser, token, cabindex)) + { + // matched the token, grab the next one + continue; + } + // TODO: add "pydestination:" + else if (token == "pyscreen:") + { + screen_entry screen; + screen.deserialize(parser); + if (false == screen.script.empty() && substr_path(screen.script).empty()) + { + screen.script = DynamicObject->asBaseDir + screen.script; + } + + ITexture *tex = nullptr; + TSubModel *submodel = nullptr; + if (screen.target != "none") + { + if (false == find_screen_surface(screen.target, "Python Screen", submodel, tex)) + { + continue; + } + } + else + { + // TODO: fix leak + tex = ITexture::null_texture(); + tex->make_stub(); + } + + tex->create(true); // make the surface static so it doesn't get destroyed by garbage + // collector if the user spends long time outside cab + // TBD, TODO: keep texture handles around, so we can undo the static switch when the + // user changes cabs? + auto rt = std::make_shared(); + rt->shared_tex = tex; + + // record renderer and material binding for future update requests + m_screens.emplace_back(screen); + m_screens.back().rt = rt; + + m_screens.back().touch_list = std::make_shared>(); + if (submodel) + submodel->screen_touch_list = m_screens.back().touch_list; + + if (Global.python_displaywindows) + m_screens.back().viewer = std::make_unique(rt, m_screens.back().touch_list, m_screens.back().script); + } + else if (token == "luascreen:") + { + load_script_screen(parser, script_language::lua); + } + else if (token == "wasmscreen:") + { + load_script_screen(parser, script_language::wasm); + } + else if (token == "pyscreenupdatetime:") + { + parser.getTokens(); + parser >> ScreenUpdateRate; + } + else if (token == "fmradio:") + { + // broadcast radio receiver, the parameter selects character of its sound + std::string fmradiotype; + parser.getTokens(); + parser >> fmradiotype; + m_fmradiotype = (fmradiotype == "wooden" ? audio::fmradio_type::wooden : audio::fmradio_type::cheap); + m_fmradiopresent = true; + } + else if (token == "fmradiospeaker:") + { + // submodel marking location of the receiver speaker, the sound is emitted from there + std::string speakername; + parser.getTokens(); + parser >> speakername; + TSubModel *speaker{nullptr}; + for (auto const *source : {DynamicObject->mdKabina, DynamicObject->mdLowPolyInt}) + { + if (source != nullptr && (speaker = source->GetFromName(speakername)) != nullptr) + { + break; + } + } + if (speaker != nullptr) + { + m_fmradiosound.offset(speaker->offset(1.f)); + } + else + { + ErrorLog("Bad config: failed to locate fm radio speaker submodel \"" + speakername + "\"", logtype::model); + } + m_fmradiopresent = true; + } + // btLampkaUnknown`"unknown",mdKabina,false); + } while (token != "" + // TODO: enable full per-cab deserialization when/if .mmd files get proper per-cab switch configuration + // && ( token != "cab1definition:" ) + // && ( token != "cab2definition:" ) + && token != "cab0definition:"); + for (auto &screen : m_screens) + { + if (screen.updatetime > 0) + { + screen.updatetime = std::max((int)screen.updatetime, Global.PythonScreenUpdateRate) * 0.001; + } + if (screen.updatetime == 0) + { + screen.updatetime = std::max(Global.PythonScreenUpdateRate, ScreenUpdateRate) * 0.001; + } + if (screen.updatetime < -1) + { + screen.updatetime = -screen.updatetime * 0.001; + } + } + } + else + { + return false; + } + /* + if (DynamicObject->mdKabina) + { + */ + // configure placement of sound emitters which aren't bound with any device model, and weren't placed manually + auto const caboffset{glm::dvec3{(Cabine[cabindex].CabPos1 + Cabine[cabindex].CabPos2) * 0.5f} + glm::dvec3{0, 1, 0}}; + // NOTE: since radiosound is an incomplete template not using std::optional it gets a special treatment + if (m_radiosound.offset() == nullvector) + { + m_radiosound.offset(btLampkaRadio.model_offset()); + } + if (m_radiosound.offset() == nullvector) + { + m_radiosound.offset(caboffset); + } + if (m_fmradiosound.offset() == nullvector) + { + m_fmradiosound.offset(caboffset); + } + if (m_fmradiopresent && false == m_fmradiopower && m_controlmapper.contains("fmradiovolume_sw:") && false == m_controlmapper.contains("fmradio_sw:")) + { + // receivers without dedicated switch are switched with the volume knob, so it has to start at the off position + m_fmradiovolume = 0.f; + } + std::vector>, glm::vec3>> soundlocations = { + {dsbReverserKey, ggDirKey.model_offset()}, + {dsbNastawnikJazdy, ggJointCtrl.model_offset()}, + {dsbNastawnikJazdy, ggMainCtrl.model_offset()}, // NOTE: fallback for vehicles without universal controller + {dsbNastawnikBocz, ggScndCtrl.model_offset()}, + {dsbSwitch, caboffset}, + {dsbPneumaticSwitch, caboffset}, + {rsHiss, ggBrakeCtrl.model_offset()}, + {rsHissU, ggBrakeCtrl.model_offset()}, + {rsHissE, ggBrakeCtrl.model_offset()}, + {rsHissX, ggBrakeCtrl.model_offset()}, + {rsHissT, ggBrakeCtrl.model_offset()}, + {rsSBHiss, ggLocalBrake.model_offset()}, + {rsSBHiss, ggBrakeCtrl.model_offset()}, // NOTE: fallback if the local brake model can't be located + {rsSBHissU, ggLocalBrake.model_offset()}, + {rsSBHissU, ggBrakeCtrl.model_offset()}, // NOTE: fallback if the local brake model can't be located + {rsFadeSound, caboffset}, + {rsRunningNoise, caboffset}, + {rsResonanceNoise, caboffset}, + {rsWindSound, caboffset}, + {rsHuntingNoise, caboffset}, + {dsbHasler, caboffset}, + {dsbBuzzer, btLampkaCzuwaka.model_offset()}, + {dsbBuzzerShp, btLampkaCzuwaka.model_offset()}, + {dsbSlipAlarm, caboffset}, + {m_distancecounterclear, btLampkaCzuwaka.model_offset()}, + {m_rainsound, caboffset}, + {m_radiostop, m_radiosound.offset()}, + }; + for (auto const &[soundsource, soundoffset] : soundlocations) + { + if (soundsource.get() && soundsource.get()->offset() == nullvector) + { + soundsource.get()->offset(soundoffset); + } + } + // second pass, in case some items received no positioning due to missing submodels etc + for (auto const &[soundsource, soundoffset] : soundlocations) + { + if (soundsource.get() && soundsource.get()->offset() == nullvector) + { + soundsource.get()->offset(caboffset); + } + } + + if (DynamicObject->mdKabina) + { + DynamicObject->mdKabina->Init(); // obrócenie modelu oraz optymalizacja, również zapisanie binarnego + // the vehicle has a cab, a player is in it: the odometer store keeps the vehicle also when its type has no + // driver's brake valve (eu07/maszyna#72) + DynamicObject->MoverParameters->Odometer.shown = true; + } + + set_cab_controls(NewCabNo < 0 ? 2 : NewCabNo); + + // set pantograpths (hujhujhuj) + change_pantograph_selection(0); + + /* + return true; +} +return (token == "none"); +*/ + return true; +} + +glm::dvec3 TTrain::MirrorPosition(bool lewe) +{ // zwraca współrzędne widoku kamery z lusterka + auto const shiftdirection{(lewe ? -1 : 1) * (iCabn == 2 ? 1 : -1)}; + + return DynamicObject->mMatrix * + glm::dvec4(mvOccupied->Dim.W * (0.5 * shiftdirection) + 0.2 * shiftdirection, 1.5 + Cabine[iCabn].CabPos1.y, std::lerp(Cabine[iCabn].CabPos1.z, Cabine[iCabn].CabPos2.z, 0.5), 1.0); +}; + +// clears state of all cabin controls +void TTrain::clear_cab_controls() +{ + // indicators exposed to custom control devices + btLampkaSHP.Clear(0); + btLampkaCzuwaka.Clear(1); + btLampkaOpory.Clear(2); + btLampkaWylSzybki.Clear(3); + btLampkaNadmSil.Clear(4); + btLampkaStyczn.Clear(5); + btLampkaPoslizg.Clear(6); + btLampkaNadmPrzetw.Clear(mvControlled->TrainType == train_type::emu ? -1 : 7); // EN57 nie ma tej lampki + btLampkaPrzetwOff.Clear(mvControlled->TrainType == train_type::emu ? 7 : -1); // za to ma tę + btLampkaNadmSpr.Clear(8); + btLampkaNadmWent.Clear(9); + btLampkaWysRozr.Clear(mvControlled->TrainType == train_type::et22 ? -1 : 10); // ET22 nie ma tej lampki + btLampkaOgrzewanieSkladu.Clear(11); + // overheat indicator lamps + btLampkaOilOverheat.Clear(-1); + btLampkaWaterOverheat.Clear(-1); + btLampkaWaterAuxOverheat.Clear(-1); + btLampkaEngineOverheat.Clear(-1); + btHaslerBrakes.Clear(12); // ciśnienie w cylindrach do odbijania na haslerze + btHaslerCurrent.Clear(13); // prąd na silnikach do odbijania na haslerze + // Numer 14 jest używany dla buczka SHP w update_sounds() + // Jeśli ustawiamy nową wartość dla PoKeys wolna jest 15 + + // other cab controls + // TODO: arrange in more readable manner, and eventually refactor + ggJointCtrl.Clear(); + ggMainCtrl.Clear(); + ggMainCtrlAct.Clear(); + ggScndCtrl.Clear(); + ggScndCtrlButton.Clear(); + ggScndCtrlOffButton.Clear(); + ggDistanceCounterButton.Clear(); + ggDirKey.Clear(); + ggDirForwardButton.Clear(); + ggDirNeutralButton.Clear(); + ggDirBackwardButton.Clear(); + ggBrakeCtrl.Clear(); + ggLocalBrake.Clear(); + ggAlarmChain.Clear(); + ggBrakeProfileCtrl.Clear(); + ggBrakeProfileG.Clear(); + ggBrakeProfileR.Clear(); + ggBrakeOperationModeCtrl.Clear(); + ggWiperSw.Clear(); + ggMaxCurrentCtrl.Clear(); + ggAutoRelayButton.Clear(); + ggMainOffButton.Clear(); + ggMainOnButton.Clear(); + for (auto &remotelinebreaker : m_remotelinebreakers) + { + remotelinebreaker.main_switch.Clear(); + remotelinebreaker.on_button.Clear(); + remotelinebreaker.off_button.Clear(); + remotelinebreaker.held_without_switch = false; + } + ggSecurityResetButton.Clear(); + ggSHPResetButton.Clear(); + ggReleaserButton.Clear(); + ggSpringBrakeOnButton.Clear(); + ggSpringBrakeOffButton.Clear(); + ggUniveralBrakeButton1.Clear(); + ggUniveralBrakeButton2.Clear(); + ggUniveralBrakeButton3.Clear(); + ggEPFuseButton.Clear(); + ggSandButton.Clear(); + ggAutoSandButton.Clear(); + ggAntiSlipButton.Clear(); + ggHornButton.Clear(); + ggHornLowButton.Clear(); + ggHornHighButton.Clear(); + ggWhistleButton.Clear(); + ggHelperButton.Clear(); + ggNextCurrentButton.Clear(); + ggSpeedControlIncreaseButton.Clear(); + ggSpeedControlDecreaseButton.Clear(); + ggSpeedControlPowerIncreaseButton.Clear(); + ggSpeedControlPowerDecreaseButton.Clear(); + for (auto &speedctrlbutton : ggSpeedCtrlButtons) + { + speedctrlbutton.Clear(); + } + for (auto &universal : ggUniversals) + { + universal.Clear(); + } + for (auto &item : ggInverterEnableButtons) + { + item.Clear(); + } + for (auto &item : ggInverterDisableButtons) + { + item.Clear(); + } + for (auto &item : ggInverterToggleButtons) + { + item.Clear(); + } + for (auto &relayresetbutton : ggRelayResetButtons) + { + relayresetbutton.Clear(); + } + ggInstrumentLightButton.Clear(); + ggDashboardLightButton.Clear(); + ggTimetableLightButton.Clear(); + // hunter-091012 + ggCabLightDimButton.Clear(); + ggCompartmentLightsButton.Clear(); + ggCompartmentLightsOnButton.Clear(); + ggCompartmentLightsOffButton.Clear(); + ggBatteryButton.Clear(); + ggBatteryOnButton.Clear(); + ggBatteryOffButton.Clear(); + ggCabActivationButton.Clear(); + //------- + ggFuseButton.Clear(); + ggConverterFuseButton.Clear(); + ggStLinOffButton.Clear(); + ggRadioChannelSelector.Clear(); + ggRadioChannelPrevious.Clear(); + ggRadioChannelNext.Clear(); + ggRadioStop.Clear(); + ggRadioTest.Clear(); + ggRadioCall1.Clear(); + ggRadioCall3.Clear(); + ggRadioVolumeSelector.Clear(); + ggRadioVolumePrevious.Clear(); + ggRadioVolumeNext.Clear(); + ggRadioOnButton.Clear(); + ggRadioOffButton.Clear(); + ggRadioFuseOnButton.Clear(); + ggRadioFuseOffButton.Clear(); + ggDoorLeftPermitButton.Clear(); + ggDoorRightPermitButton.Clear(); + ggDoorPermitPresetButton.Clear(); + ggDoorLeftButton.Clear(); + ggDoorRightButton.Clear(); + ggDoorLeftOnButton.Clear(); + ggDoorRightOnButton.Clear(); + ggDoorLeftOffButton.Clear(); + ggDoorRightOffButton.Clear(); + ggDoorAllOnButton.Clear(); + ggDoorAllOffButton.Clear(); + ggTrainHeatingButton.Clear(); + ggSignallingButton.Clear(); + ggDoorSignallingButton.Clear(); + ggDoorStepButton.Clear(); + ggDepartureSignalButton.Clear(); + ggCompressorButton.Clear(); + ggCompressorLocalButton.Clear(); + ggConverterButton.Clear(); + ggConverterOffButton.Clear(); + ggConverterLocalButton.Clear(); + ggMainButton.Clear(); + /* + ggPantFrontButton.Clear(); + ggPantRearButton.Clear(); + ggPantFrontButtonOff.Clear(); + ggPantRearButtonOff.Clear(); + */ + ggPantAllDownButton.Clear(); + ggPantSelectedButton.Clear(); + ggPantSelectedDownButton.Clear(); + ggPantValvesButton.Clear(); + ggPantCompressorButton.Clear(); + ggPantCompressorValve.Clear(); + + ggPantValvesOff.Clear(); + ggPantValvesUpdate.Clear(); + + ggI1B.Clear(); + ggI2B.Clear(); + ggI3B.Clear(); + ggItotalB.Clear(); + ggOilPressB.Clear(); + ggWater1TempB.Clear(); + + ggClockSInd.Clear(); + ggClockMInd.Clear(); + ggClockHInd.Clear(); + ggEngineVoltage.Clear(); + ggLVoltage.Clear(); + ggMainGearStatus.Clear(); + ggIgnitionKey.Clear(); + + ggWaterPumpBreakerButton.Clear(); + ggWaterPumpButton.Clear(); + ggWaterHeaterBreakerButton.Clear(); + ggWaterHeaterButton.Clear(); + ggWaterCircuitsLinkButton.Clear(); + ggFuelPumpButton.Clear(); + ggOilPumpButton.Clear(); + ggOilFuelPumpButton.Clear(); + ggTractionModeSwitch.Clear(); + ggGensetButton.Clear(); + ggMotorBlowersFrontButton.Clear(); + ggMotorBlowersRearButton.Clear(); + ggMotorBlowersAllOffButton.Clear(); + + btLampkaPrzetw.Clear(); + btLampkaPrzetwB.Clear(); + btLampkaPrzetwBOff.Clear(); + btLampkaPrzetwAOff.Clear(); + btLampkaPrzekRozn.Clear(); + btLampkaPrzekRoznPom.Clear(); + btLampkaUkrotnienie.Clear(); + btLampkaHamPosp.Clear(); + btLampkaWylSzybkiOff.Clear(); + btLampkaWylSzybkiB.Clear(); + btLampkaWylSzybkiBOff.Clear(); + btLampkaMainBreakerReady.Clear(); + btLampkaMainBreakerBlinkingIfReady.Clear(); + btLampkaBezoporowa.Clear(); + btLampkaBezoporowaB.Clear(); + btLampkaMaxSila.Clear(); + btLampkaPrzekrMaxSila.Clear(); + btLampkaRadio.Clear(); + btLampkaRadioMessage.Clear(); + btLampkaRadioStop.Clear(); + btLampkaHamulecReczny.Clear(); + btLampkaBlokadaDrzwi.Clear(); + btLampkaDoorLockOff.Clear(); + for (auto &universal : btUniversals) + { + universal.Clear(); + } + btInstrumentLight.Clear(); + btDashboardLight.Clear(); + btTimetableLight.Clear(); + btLampkaWentZaluzje.Clear(); + btLampkaDoorLeft.Clear(); + btLampkaDoorRight.Clear(); + btLampkaDepartureSignal.Clear(); + btLampkaRezerwa.Clear(); + btLampkaBoczniki.Clear(); + btLampkaBocznik1.Clear(); + btLampkaBocznik2.Clear(); + btLampkaBocznik3.Clear(); + btLampkaBocznik4.Clear(); + btLampkaGear1.Clear(); + btLampkaGear2.Clear(); + btLampkaHydroLockup.Clear(); + btLampkaRadiotelefon.Clear(); + btLampkaHamienie.Clear(); + btLampkaBrakingOff.Clear(); + btLampkaED.Clear(); + btLampkaBrakeProfileG.Clear(); + btLampkaBrakeProfileP.Clear(); + btLampkaBrakeProfileR.Clear(); + btLampkaSpringBrakeActive.Clear(); + btLampkaSpringBrakeInactive.Clear(); + btLampkaSprezarka.Clear(); + btLampkaSprezarkaB.Clear(); + btLampkaSprezarkaOff.Clear(); + btLampkaSprezarkaBOff.Clear(); + btLampkaFuelPumpOff.Clear(); + btLampkaOilPump.Clear(); + btLampkaNapNastHam.Clear(); + btLampkaOporyB.Clear(); + btLampkaStycznB.Clear(); + btLampkaHamowanie1zes.Clear(); + btLampkaHamowanie2zes.Clear(); + btLampkaNadmPrzetwB.Clear(); + btLampkaHVoltageB.Clear(); + btLampkaForward.Clear(); + btLampkaBackward.Clear(); + btLampkaNeutral.Clear(); + // light indicators + btLampkaUpperLight.Clear(); + btLampkaLeftLight.Clear(); + btLampkaRightLight.Clear(); + btLampkaLeftEndLight.Clear(); + btLampkaRightEndLight.Clear(); + btLampkaRearUpperLight.Clear(); + btLampkaRearLeftLight.Clear(); + btLampkaRearRightLight.Clear(); + btLampkaRearLeftEndLight.Clear(); + btLampkaRearRightEndLight.Clear(); + // others + btLampkaMalfunction.Clear(); + btLampkaMalfunctionB.Clear(); + btLampkaMotorBlowers.Clear(); + btLampkaCoolingFans.Clear(); + btLampkaLouvresClosed.Clear(); + btLampkaTempomat.Clear(); + btLampkaDistanceCounter.Clear(); + + ggLeftLightButton.Clear(); + ggRightLightButton.Clear(); + ggUpperLightButton.Clear(); + ggDimHeadlightsButton.Clear(); + ggModernLightDimSw.Clear(); + ggLeftEndLightButton.Clear(); + ggRightEndLightButton.Clear(); + ggLightsButton.Clear(); + ggCompressorListButton.Clear(); + // hunter-230112 + ggRearLeftLightButton.Clear(); + ggRearRightLightButton.Clear(); + ggRearUpperLightButton.Clear(); + ggRearLeftEndLightButton.Clear(); + ggRearRightEndLightButton.Clear(); +} + +// NOTE: we can get rid of this function once we have per-cab persistent state +void TTrain::set_cab_controls(int const Cab) +{ + // switches + // battery + ggBatteryButton.PutValue(ggBatteryButton.type() == TGaugeType::push ? 0.5f : mvOccupied->Power24vIsAvailable ? 1.f : 0.f); + // activation + ggCabActivationButton.PutValue(ggCabActivationButton.type() == TGaugeType::push ? 0.5f : mvOccupied->IsCabMaster() ? 1.f : 0.f); + // line breaker + if (ggMainButton.SubModel != nullptr) + { // instead of single main button there can be on/off pair + ggMainButton.PutValue(ggMainButton.type() == TGaugeType::push ? 0.5f : m_linebreakerstate != linebreaker::state::open ? 1.f : 0.f); + } + // line breakers of the other vehicles in multiple + for (std::size_t index = 0; index < m_remotelinebreakers.size(); ++index) + { + auto &mainswitch{m_remotelinebreakers[index].main_switch}; + if (mainswitch.SubModel == nullptr) + { + continue; + } + if (mainswitch.type() == TGaugeType::push) + { + mainswitch.PutValue(0.5f); + continue; + } + auto const *engine{remote_engine(index)}; + mainswitch.PutValue(engine != nullptr && engine_start::remote_switch::is_running(*engine) ? 1.f : 0.f); + } + + if (ggModernLightDimSw.SubModel != nullptr) + { + mvOccupied->modernDimmerPosition = mvOccupied->modernDimmerDefaultPosition; + ggModernLightDimSw.PutValue(static_cast(mvOccupied->modernDimmerDefaultPosition)); + } + + // Init separate buttons + if (ggPantValvesUpdate.SubModel != nullptr) + { + ggPantValvesUpdate.PutValue(0.f); + } + if (ggPantValvesOff.SubModel != nullptr) + { + ggPantValvesOff.PutValue(0.f); + } + + // motor connectors + ggStLinOffButton.PutValue(mvControlled->StLinSwitchOff ? 1.f : 0.f); + // radio + ggRadioChannelSelector.PutValue(static_cast((Dynamic()->Mechanik ? Dynamic()->Mechanik->iRadioChannel : 1) - 1)); + // pantographs + /* + if( mvOccupied->PantSwitchType != "impulse" ) { + if( ggPantFrontButton.SubModel ) { + ggPantFrontButton.PutValue( + ( mvControlled->Pantographs[end::front].valve.is_enabled ? + 1.f : + 0.f ) ); + } + if( ggPantFrontButtonOff.SubModel ) { + ggPantFrontButtonOff.PutValue( + ( mvControlled->Pantographs[end::front].valve.is_disabled ? + 1.f : + 0.f ) ); + } + } + if( mvOccupied->PantSwitchType != "impulse" ) { + if( ggPantRearButton.SubModel ) { + ggPantRearButton.PutValue( + ( mvControlled->Pantographs[end::rear].valve.is_enabled ? + 1.f : + 0.f ) ); + } + if( ggPantRearButtonOff.SubModel ) { + ggPantRearButtonOff.PutValue( + ( mvControlled->Pantographs[end::rear].valve.is_disabled ? + 1.f : + 0.f ) ); + } + } + */ + // front/end pantograph selection is relative to occupied cab + if (ggPantSelectedButton.type() == TGaugeType::toggle) + { + ggPantSelectedButton.PutValue(mvPantographUnit->PantsValve.is_enabled ? 1.f : 0.f); + } + else + { + if (false == m_controlmapper.contains("pantselectedoff_sw:")) + { + // single impulse switch arrangement, with neutral position mid-way + ggPantSelectedButton.PutValue(0.5f); + } + } + if (ggPantSelectedDownButton.type() == TGaugeType::toggle) + { + ggPantSelectedDownButton.PutValue(mvPantographUnit->PantsValve.is_disabled ? 1.f : 0.f); + } + + ggPantValvesButton.PutValue(0.5f); + + // auxiliary compressor + ggPantCompressorValve.PutValue(mvControlled->bPantKurek3 ? 0.f : // default setting is pantographs connected with primary tank + 1.f); + ggPantCompressorButton.PutValue(mvPantographUnit->PantCompFlag ? 1.f : 0.f); + // converter + if (mvOccupied->ConvSwitchType != "impulse") + { + ggConverterButton.PutValue(mvOccupied->ConverterAllow ? 1.f : 0.f); + } + ggConverterLocalButton.PutValue(mvOccupied->ConverterAllowLocal ? 1.f : 0.f); + // compressor + ggCompressorButton.PutValue(mvControlled->CompressorAllow ? 1.f : 0.f); + ggCompressorLocalButton.PutValue(mvControlled->CompressorAllowLocal ? 1.f : 0.f); + ggCompressorListButton.PutValue(static_cast(mvOccupied->CompressorListPos - 1)); + // motor overload relay threshold / shunt mode + ggMaxCurrentCtrl.PutValue(true == mvControlled->ShuntModeAllow ? (true == mvControlled->ShuntMode ? 1.f : 0.f) : mvControlled->MotorOverloadRelayHighThreshold ? 1.f : 0.f); + // automatic relays (AutoRelay) + ggAutoRelayButton.PutValue(mvOccupied->AutoRelayFlag ? 1.f : 0.f); + // lights + ggLightsButton.PutValue(static_cast(mvOccupied->LightsPos - 1)); + + auto const vehicleend{cab_to_end(Cab)}; + + if ((mvOccupied->iLights[vehicleend] & light::headlight_left) != 0) + { + ggLeftLightButton.PutValue(1.f); + } + if ((mvOccupied->iLights[vehicleend] & light::headlight_right) != 0) + { + ggRightLightButton.PutValue(1.f); + } + if ((mvOccupied->iLights[vehicleend] & light::headlight_upper) != 0) + { + ggUpperLightButton.PutValue(1.f); + } + if ((mvOccupied->iLights[vehicleend] & light::redmarker_left) != 0) + { + if (ggLeftEndLightButton.SubModel != nullptr) + { + ggLeftEndLightButton.PutValue(1.f); + } + else + { + ggLeftLightButton.PutValue(-1.f); + } + } + if ((mvOccupied->iLights[vehicleend] & light::redmarker_right) != 0) + { + if (ggRightEndLightButton.SubModel != nullptr) + { + ggRightEndLightButton.PutValue(1.f); + } + else + { + ggRightLightButton.PutValue(-1.f); + } + } + if (1 == DynamicObject->MoverParameters->modernDimmerPosition) + { + ggDimHeadlightsButton.PutValue(static_cast(DynamicObject->MoverParameters->modernDimmerPosition)); + } + // cab lights + if (true == Cabine[Cab].bLightDim) + { + ggCabLightDimButton.PutValue(1.f); + } + // compartment lights + ggCompartmentLightsButton.PutValue(ggCompartmentLightsButton.type() == TGaugeType::push ? 0.5f : mvOccupied->CompartmentLights.is_enabled ? 1.f : 0.f); + // instrument lights + ggInstrumentLightButton.PutValue(InstrumentLightActive ? 1.f : 0.f); + ggDashboardLightButton.PutValue(DashboardLightActive ? 1.f : 0.f); + ggTimetableLightButton.PutValue(TimetableLightActive ? 1.f : 0.f); + // doors permits + if (false == ggDoorLeftPermitButton.is_push()) + { + ggDoorLeftPermitButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == end::front ? side::left : side::right].open_permit ? 1.f : 0.f); + } + if (false == ggDoorRightPermitButton.is_push()) + { + ggDoorRightPermitButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == end::front ? side::right : side::left].open_permit ? 1.f : 0.f); + } + ggDoorPermitPresetButton.PutValue(static_cast(mvOccupied->Doors.permit_preset)); + // door controls + ggDoorLeftButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == end::front ? side::left : side::right].is_closed ? 0.f : 1.f); + ggDoorRightButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == end::front ? side::right : side::left].is_closed ? 0.f : 1.f); + // door lock + ggDoorSignallingButton.PutValue(mvOccupied->Doors.lock_enabled ? 1.f : 0.f); + // door step + if (false == ggDoorStepButton.is_push()) + { + ggDoorStepButton.PutValue(mvOccupied->Doors.step_enabled ? 1.f : 0.f); + } + // heating + if (false == ggTrainHeatingButton.is_push() && false == mvOccupied->HeatingSwitchImpulse) + { + ggTrainHeatingButton.PutValue(mvControlled->Heating ? 1.f : 0.f); + } + // brake acting time + if (ggBrakeProfileCtrl.SubModel != nullptr) + { + ggBrakeProfileCtrl.PutValue((mvOccupied->BrakeDelayFlag & bdelay_R) != 0 ? 2.f : static_cast(mvOccupied->BrakeDelayFlag - 1)); + } + if (ggBrakeProfileG.SubModel != nullptr) + { + ggBrakeProfileG.PutValue(mvOccupied->BrakeDelayFlag == bdelay_G ? 1.f : 0.f); + } + if (ggBrakeProfileR.SubModel != nullptr) + { + ggBrakeProfileR.PutValue((mvOccupied->BrakeDelayFlag & bdelay_R) != 0 ? 1.f : 0.f); + } + + if (ggWiperSw.SubModel != nullptr) + { + ggWiperSw.PutValue(static_cast(mvOccupied->wiperSwitchPos)); + } + + if (ggBrakeOperationModeCtrl.SubModel != nullptr) + { + ggBrakeOperationModeCtrl.PutValue(mvOccupied->BrakeOpModeFlag > 0 ? static_cast(std::log2(mvOccupied->BrakeOpModeFlag)) : 0); + } + // alarm chain + ggAlarmChain.PutValue(mvControlled->AlarmChainFlag ? 1.f : 0.f); + // brake signalling + ggSignallingButton.PutValue(mvControlled->Signalling ? 1.f : 0.f); + // multiple-unit current indicator source + ggNextCurrentButton.PutValue(ShowNextCurrent ? 1.f : 0.f); + // water pump + ggWaterPumpBreakerButton.PutValue(mvControlled->WaterPump.breaker ? 1.f : 0.f); + if (ggWaterPumpButton.type() != TGaugeType::push) + { + ggWaterPumpButton.PutValue(mvControlled->WaterPump.is_enabled ? 1.f : 0.f); + } + // water heater + ggWaterHeaterBreakerButton.PutValue(mvControlled->WaterHeater.breaker ? 1.f : 0.f); + ggWaterHeaterButton.PutValue(mvControlled->WaterHeater.is_enabled ? 1.f : 0.f); + ggWaterCircuitsLinkButton.PutValue(mvControlled->WaterCircuitsLink ? 1.f : 0.f); + // fuel pump + if (ggFuelPumpButton.type() != TGaugeType::push) + { + ggFuelPumpButton.PutValue(mvControlled->FuelPump.is_enabled ? 1.f : 0.f); + } + // oil pump + if (ggOilPumpButton.type() != TGaugeType::push) + { + ggOilPumpButton.PutValue(mvControlled->OilPump.is_enabled ? 1.f : 0.f); + } + // joint oil and fuel pump + if (ggOilFuelPumpButton.type() != TGaugeType::push) + { + ggOilFuelPumpButton.PutValue(mvControlled->OilFuelPumpsEnabled() ? 1.f : 0.f); + } + // traction selector and genset of a dual-mode vehicle + ggTractionModeSwitch.PutValue(mvControlled->GensetSelected() ? 1.f : 0.f); + if (ggGensetButton.type() != TGaugeType::push) + { + ggGensetButton.PutValue(mvControlled->Genset.is_enabled ? 1.f : 0.f); + } + // traction motor fans + if (ggMotorBlowersFrontButton.type() != TGaugeType::push) + { + ggMotorBlowersFrontButton.PutValue(mvControlled->MotorBlowers[end::front].is_enabled ? 1.f : 0.f); + } + if (ggMotorBlowersRearButton.type() != TGaugeType::push) + { + ggMotorBlowersRearButton.PutValue(mvControlled->MotorBlowers[end::rear].is_enabled ? 1.f : 0.f); + } + if (ggMotorBlowersAllOffButton.type() != TGaugeType::push) + { + ggMotorBlowersAllOffButton.PutValue(mvControlled->MotorBlowers[end::front].is_disabled || mvControlled->MotorBlowers[end::rear].is_disabled ? 1.f : 0.f); + } + // second controller + if (ggScndCtrl.is_push()) + { + ggScndCtrl.PutValue(ggScndCtrl.is_toggle() ? 0.5f : // pushtoggle is two-way control with neutral position in the middle + 0.f); // push is on/off control, active while held down, due to legacy use + } + // tempomat + if (false == ggScndCtrlButton.is_push()) + { + ggScndCtrlButton.PutValue(mvControlled->IsSpeedCtrlEngaged() ? 1.f : 0.f); + } + // sandbox + if (ggAutoSandButton.type() != TGaugeType::push) + { + ggAutoSandButton.PutValue(mvControlled->SandDoseAutoAllow ? 1.f : 0.f); + } + // radio + ggRadioVolumeSelector.PutValue(m_radiovolume); + + // finding each inverter - not so optimal, but action ins performed only during changing cabin + bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; + auto const flag{CouplingSet::FromBits(DynamicObject->MoverParameters->InverterControlCouplerFlag)}; + int itemstart = 0; + for ([[maybe_unused]] auto const &item : ggInverterToggleButtons) // for each button + { + int itemindex = itemstart; + itemstart++; + TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); + while (p) + { + if (p->MoverParameters->eimc[eimc_p_Pmax] > 1) + { + if (itemindex < p->MoverParameters->InvertersNo) + { + // visual feedback + ggInverterToggleButtons[itemstart - 1].PutValue(p->MoverParameters->Inverters[itemindex].Activate ? 1.0 : 0.0); + break; + } + else + { + itemindex -= p->MoverParameters->InvertersNo; + } + } + p = kier ? p->Next(flag) : p->Prev(flag); + } + } + + // we reset all indicators, as they're set during the update pass + // TODO: when cleaning up break setting indicator state into a separate function, so we can reuse it +} + +// initializes a button matching provided label. returns: true if the label was found, false otherwise +// TODO: refactor the cabin controls into some sensible structure +bool TTrain::initialize_button(cParser &Parser, std::string const &Label, int const Cabindex) +{ + + std::unordered_map const lights = { + {"i-maxft:", btLampkaMaxSila}, + {"i-maxftt:", btLampkaPrzekrMaxSila}, + {"i-radio:", btLampkaRadio}, + {"i-radiomessage:", btLampkaRadioMessage}, + {"i-radiostop:", btLampkaRadioStop}, + {"i-manual_brake:", btLampkaHamulecReczny}, + {"i-door_blocked:", btLampkaBlokadaDrzwi}, + {"i-door_blockedoff:", btLampkaDoorLockOff}, + {"i-slippery:", btLampkaPoslizg}, + {"i-contactors:", btLampkaStyczn}, + {"i-conv_ovld:", btLampkaNadmPrzetw}, + {"i-converter:", btLampkaPrzetw}, + {"i-converteroff:", btLampkaPrzetwOff}, + {"i-converteraoff:", btLampkaPrzetwAOff}, + {"i-converterb:", btLampkaPrzetwB}, + {"i-converterboff:", btLampkaPrzetwBOff}, + {"i-diff_relay:", btLampkaPrzekRozn}, + {"i-diff_relay2:", btLampkaPrzekRoznPom}, + {"i-motor_ovld:", btLampkaNadmSil}, + {"i-train_controll:", btLampkaUkrotnienie}, + {"i-brake_delay_r:", btLampkaHamPosp}, + {"i-mainbreaker:", btLampkaWylSzybki}, + {"i-mainbreakerb:", btLampkaWylSzybkiB}, + {"i-mainbreakeroff:", btLampkaWylSzybkiOff}, + {"i-mainbreakerboff:", btLampkaWylSzybkiBOff}, + {"i-mainbreakerready:", btLampkaMainBreakerReady}, + {"i-mainbreakerblinking:", btLampkaMainBreakerBlinkingIfReady}, + {"i-vent_ovld:", btLampkaNadmWent}, + {"i-comp_ovld:", btLampkaNadmSpr}, + // overheat indicator lamps + {"i-oil_overheat:", btLampkaOilOverheat}, + {"i-water_overheat:", btLampkaWaterOverheat}, + {"i-wateraux_overheat:", btLampkaWaterAuxOverheat}, + {"i-engine_overheat:", btLampkaEngineOverheat}, + {"i-resistors:", btLampkaOpory}, + {"i-no_resistors:", btLampkaBezoporowa}, + {"i-no_resistors_b:", btLampkaBezoporowaB}, + {"i-highcurrent:", btLampkaWysRozr}, + {"i-vent_trim:", btLampkaWentZaluzje}, + {"i-motorblowers:", btLampkaMotorBlowers}, + {"i-coolingfans:", btLampkaCoolingFans}, + {"i-louvresclosed:", btLampkaLouvresClosed}, + {"i-tempomat:", btLampkaTempomat}, + {"i-distancecounter:", btLampkaDistanceCounter}, + {"i-trainheating:", btLampkaOgrzewanieSkladu}, + {"i-security_aware:", btLampkaCzuwaka}, + {"i-security_cabsignal:", btLampkaSHP}, + {"i-security_aware_cabsignal:", btLampkaCzuwakaSHP}, + {"i-door_left:", btLampkaDoorLeft}, + {"i-door_right:", btLampkaDoorRight}, + {"i-departure_signal:", btLampkaDepartureSignal}, + {"i-reserve:", btLampkaRezerwa}, + {"i-scnd:", btLampkaBoczniki}, + {"i-scnd1:", btLampkaBocznik1}, + {"i-scnd2:", btLampkaBocznik2}, + {"i-scnd3:", btLampkaBocznik3}, + {"i-scnd4:", btLampkaBocznik4}, + {"i-gear1:", btLampkaGear1}, + {"i-gear2:", btLampkaGear2}, + {"i-hydrolockup:", btLampkaHydroLockup}, + {"i-braking:", btLampkaHamienie}, + {"i-brakingoff:", btLampkaBrakingOff}, + {"i-dynamicbrake:", btLampkaED}, + {"i-brakeprofileg:", btLampkaBrakeProfileG}, + {"i-brakeprofilep:", btLampkaBrakeProfileP}, + {"i-brakeprofiler:", btLampkaBrakeProfileR}, + {"i-springbrakeactive:", btLampkaSpringBrakeActive}, + {"i-springbrakeinactive:", btLampkaSpringBrakeInactive}, + {"i-braking-ezt:", btLampkaHamowanie1zes}, + {"i-braking-ezt2:", btLampkaHamowanie2zes}, + {"i-compressor:", btLampkaSprezarka}, + {"i-compressorb:", btLampkaSprezarkaB}, + {"i-compressoroff:", btLampkaSprezarkaOff}, + {"i-compressorboff:", btLampkaSprezarkaBOff}, + {"i-fuelpumpoff:", btLampkaFuelPumpOff}, + {"i-oilpump:", btLampkaOilPump}, + {"i-voltbrake:", btLampkaNapNastHam}, + {"i-resistorsb:", btLampkaOporyB}, + {"i-contactorsb:", btLampkaStycznB}, + {"i-conv_ovldb:", btLampkaNadmPrzetwB}, + {"i-hvoltageb:", btLampkaHVoltageB}, + {"i-malfunction:", btLampkaMalfunction}, + {"i-malfunctionb:", btLampkaMalfunctionB}, + {"i-forward:", btLampkaForward}, + {"i-backward:", btLampkaBackward}, + {"i-neutral:", btLampkaNeutral}, + {"i-upperlight:", btLampkaUpperLight}, + {"i-leftlight:", btLampkaLeftLight}, + {"i-rightlight:", btLampkaRightLight}, + {"i-leftend:", btLampkaLeftEndLight}, + {"i-rightend:", btLampkaRightEndLight}, + {"i-rearupperlight:", btLampkaRearUpperLight}, + {"i-rearleftlight:", btLampkaRearLeftLight}, + {"i-rearrightlight:", btLampkaRearRightLight}, + {"i-rearleftend:", btLampkaRearLeftEndLight}, + {"i-rearrightend:", btLampkaRearRightEndLight}, + {"i-dashboardlight:", btDashboardLight}, + {"i-timetablelight:", btTimetableLight}, + {"i-universal0:", btUniversals[0]}, + {"i-universal1:", btUniversals[1]}, + {"i-universal2:", btUniversals[2]}, + {"i-universal3:", btUniversals[3]}, + {"i-universal4:", btUniversals[4]}, + {"i-universal5:", btUniversals[5]}, + {"i-universal6:", btUniversals[6]}, + {"i-universal7:", btUniversals[7]}, + {"i-universal8:", btUniversals[8]}, + {"i-universal9:", btUniversals[9]}, + {"i-cabactived:", btCabActived}, + {"i-aklvents:", btAKLVents}, + {"i-compressorany:", btCompressors}, + {"i-edenabled", btEDenabled}, + }; + { + auto lookup = lights.find(Label); + if (lookup != lights.end()) + { + lookup->second.Load(Parser, DynamicObject); + return true; + } + } + // TODO: move viable dedicated lights to the automatic light array + std::unordered_map const autolights = { + {"i-doors:", &m_doors}, + {"i-doorpermit_left:", &m_doorspermitleft}, + {"i-doorpermit_right:", &m_doorspermitright}, + {"i-doorpermit_any:", &m_doorpermits}, + {"i-doorstep:", &mvOccupied->Doors.step_enabled}, + {"i-mainpipelock:", &mvOccupied->LockPipe}, + {"i-battery:", &mvOccupied->Power24vIsAvailable}, + {"i-cablight:", &Cabine[iCabn].bLight}, + {"i-compartmentlights:", &mvOccupied->CompartmentLights.is_active}, + }; + { + auto lookup = autolights.find(Label); + if (lookup != autolights.end()) + { + auto &button = Cabine[Cabindex].Button(-1); // pierwsza wolna lampka + button.Load(Parser, DynamicObject); + button.AssignBool(lookup->second); + return true; + } + } + // custom lights + if (Label == "i-instrumentlight:") + { + btInstrumentLight.Load(Parser, DynamicObject); + InstrumentLightType = 0; + } + else if (Label == "i-instrumentlight_m:") + { + btInstrumentLight.Load(Parser, DynamicObject); + InstrumentLightType = 1; + } + else if (Label == "i-instrumentlight_c:") + { + btInstrumentLight.Load(Parser, DynamicObject); + InstrumentLightType = 2; + } + else if (Label == "i-instrumentlight_a:") + { + btInstrumentLight.Load(Parser, DynamicObject); + InstrumentLightType = 3; + } + else if (Label == "i-instrumentlight_l:") + { + btInstrumentLight.Load(Parser, DynamicObject); + InstrumentLightType = 4; + } + else if (Label == "i-doors:") + { + int i = Parser.getToken() - 1; + auto &button = Cabine[Cabindex].Button(-1); // pierwsza wolna lampka + button.Load(Parser, DynamicObject); + button.AssignBool(bDoors[0] + 3 * i); + } + else + { + // failed to match the label + return false; + } + + return true; +} + +// initializes a gauge matching provided label. returns: true if the label was found, false otherwise +// TODO: refactor the cabin controls into some sensible structure +bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int const Cabindex) +{ + + std::unordered_map const gauges = {{"jointctrl:", ggJointCtrl}, + {"mainctrl:", ggMainCtrl}, + {"scndctrl:", ggScndCtrl}, + {"dirkey:", ggDirKey}, + {"brakectrl:", ggBrakeCtrl}, + {"localbrake:", ggLocalBrake}, + {"alarmchain:", ggAlarmChain}, + {"brakeprofile_sw:", ggBrakeProfileCtrl}, + {"brakeprofileg_sw:", ggBrakeProfileG}, + {"brakeprofiler_sw:", ggBrakeProfileR}, + {"brakeopmode_sw:", ggBrakeOperationModeCtrl}, + {"maxcurrent_sw:", ggMaxCurrentCtrl}, + {"autorelay_sw:", ggAutoRelayButton}, + {"main_off_bt:", ggMainOffButton}, + {"main_on_bt:", ggMainOnButton}, + {"mainb_sw:", m_remotelinebreakers[0].main_switch}, + {"mainb_off_bt:", m_remotelinebreakers[0].off_button}, + {"mainb_on_bt:", m_remotelinebreakers[0].on_button}, + {"mainc_sw:", m_remotelinebreakers[1].main_switch}, + {"mainc_off_bt:", m_remotelinebreakers[1].off_button}, + {"mainc_on_bt:", m_remotelinebreakers[1].on_button}, + {"security_reset_bt:", ggSecurityResetButton}, + {"shp_reset_bt:", ggSHPResetButton}, + {"releaser_bt:", ggReleaserButton}, + {"springbrakeon_bt:", ggSpringBrakeOnButton}, + {"springbrakeoff_bt:", ggSpringBrakeOffButton}, + {"universalbrake1_bt:", ggUniveralBrakeButton1}, + {"universalbrake2_bt:", ggUniveralBrakeButton2}, + {"universalbrake3_bt:", ggUniveralBrakeButton3}, + {"epbrake_bt:", ggEPFuseButton}, + {"sand_bt:", ggSandButton}, + {"autosandallow_sw:", ggAutoSandButton}, + {"antislip_bt:", ggAntiSlipButton}, + {"horn_bt:", ggHornButton}, + {"hornlow_bt:", ggHornLowButton}, + {"hornhigh_bt:", ggHornHighButton}, + {"whistle_bt:", ggWhistleButton}, + {"helper_bt:", ggHelperButton}, + {"fuse_bt:", ggFuseButton}, + {"converterfuse_bt:", ggConverterFuseButton}, + {"stlinoff_bt:", ggStLinOffButton}, + {"doorpermitpreset_sw:", ggDoorPermitPresetButton}, + {"door_left_sw:", ggDoorLeftButton}, + {"door_right_sw:", ggDoorRightButton}, + {"doorlefton_sw:", ggDoorLeftOnButton}, + {"doorrighton_sw:", ggDoorRightOnButton}, + {"doorleftoff_sw:", ggDoorLeftOffButton}, + {"doorrightoff_sw:", ggDoorRightOffButton}, + {"doorallon_sw:", ggDoorAllOnButton}, + {"departure_signal_bt:", ggDepartureSignalButton}, + {"upperlight_sw:", ggUpperLightButton}, + {"leftlight_sw:", ggLeftLightButton}, + {"rightlight_sw:", ggRightLightButton}, + {"dimheadlights_sw:", ggDimHeadlightsButton}, + {"leftend_sw:", ggLeftEndLightButton}, + {"rightend_sw:", ggRightEndLightButton}, + {"lights_sw:", ggLightsButton}, + {"moderndimmer_sw:", ggModernLightDimSw}, + {"rearupperlight_sw:", ggRearUpperLightButton}, + {"rearleftlight_sw:", ggRearLeftLightButton}, + {"rearrightlight_sw:", ggRearRightLightButton}, + {"rearleftend_sw:", ggRearLeftEndLightButton}, + {"rearrightend_sw:", ggRearRightEndLightButton}, + {"compressor_sw:", ggCompressorButton}, + {"compressorlocal_sw:", ggCompressorLocalButton}, + {"compressorlist_sw:", ggCompressorListButton}, + {"converter_sw:", ggConverterButton}, + {"converterlocal_sw:", ggConverterLocalButton}, + {"converteroff_sw:", ggConverterOffButton}, + {"main_sw:", ggMainButton}, + {"waterpumpbreaker_sw:", ggWaterPumpBreakerButton}, + {"waterpump_sw:", ggWaterPumpButton}, + {"waterheaterbreaker_sw:", ggWaterHeaterBreakerButton}, + {"waterheater_sw:", ggWaterHeaterButton}, + {"water1tempb:", ggWater1TempB}, + {"watercircuitslink_sw:", ggWaterCircuitsLinkButton}, + {"fuelpump_sw:", ggFuelPumpButton}, + {"oilpump_sw:", ggOilPumpButton}, + {"oilfuelpump_sw:", ggOilFuelPumpButton}, + {"tractionmode_sw:", ggTractionModeSwitch}, + {"genset_sw:", ggGensetButton}, + {"oilpressb:", ggOilPressB}, + {"motorblowersfront_sw:", ggMotorBlowersFrontButton}, + {"motorblowersrear_sw:", ggMotorBlowersRearButton}, + {"motorblowersalloff_sw:", ggMotorBlowersAllOffButton}, + {"radiochannel_sw:", ggRadioChannelSelector}, + {"radiochannelprev_sw:", ggRadioChannelPrevious}, + {"radiochannelnext_sw:", ggRadioChannelNext}, + {"radiostop_sw:", ggRadioStop}, + {"radiotest_sw:", ggRadioTest}, + {"radiocall1_sw:", ggRadioCall1}, + {"radiocall3_sw:", ggRadioCall3}, + {"radiovolume_sw:", ggRadioVolumeSelector}, + {"radiovolumeprev_sw:", ggRadioVolumePrevious}, + {"radiovolumenext_sw:", ggRadioVolumeNext}, + {"radioon_sw:", ggRadioOnButton}, + {"radiooff_sw:", ggRadioOffButton}, + {"radiofuseon_sw:", ggRadioFuseOnButton}, + {"radiofuseoff_sw:", ggRadioFuseOffButton}, + /* + { "pantfront_sw:", ggPantFrontButton }, + { "pantrear_sw:", ggPantRearButton }, + { "pantfrontoff_sw:", ggPantFrontButtonOff }, + { "pantrearoff_sw:", ggPantRearButtonOff }, + */ + {"pantalloff_sw:", ggPantAllDownButton}, + {"pantselected_sw:", ggPantSelectedButton}, + {"pantselectedoff_sw:", ggPantSelectedDownButton}, + {"pantvalves_sw:", ggPantValvesButton}, + {"pantcompressor_sw:", ggPantCompressorButton}, + {"pantcompressorvalve_sw:", ggPantCompressorValve}, + {"trainheating_sw:", ggTrainHeatingButton}, + {"signalling_sw:", ggSignallingButton}, + {"door_signalling_sw:", ggDoorSignallingButton}, + {"nextcurrent_sw:", ggNextCurrentButton}, + {"instrumentlight_sw:", ggInstrumentLightButton}, + {"dashboardlight_sw:", ggDashboardLightButton}, + {"timetablelight_sw:", ggTimetableLightButton}, + {"cablightdim_sw:", ggCabLightDimButton}, + {"compartmentlights_sw:", ggCompartmentLightsButton}, + {"compartmentlightson_sw:", ggCompartmentLightsOnButton}, + {"compartmentlightsoff_sw:", ggCompartmentLightsOffButton}, + {"battery_sw:", ggBatteryButton}, + {"batteryon_sw:", ggBatteryOnButton}, + {"batteryoff_sw:", ggBatteryOffButton}, + {"cabactivation_sw:", ggCabActivationButton}, + {"distancecounter_sw:", ggDistanceCounterButton}, + {"relayreset1_bt:", ggRelayResetButtons[0]}, + {"relayreset2_bt:", ggRelayResetButtons[1]}, + {"relayreset3_bt:", ggRelayResetButtons[2]}, + {"universal0:", ggUniversals[0]}, + {"universal1:", ggUniversals[1]}, + {"universal2:", ggUniversals[2]}, + {"universal3:", ggUniversals[3]}, + {"universal4:", ggUniversals[4]}, + {"universal5:", ggUniversals[5]}, + {"universal6:", ggUniversals[6]}, + {"universal7:", ggUniversals[7]}, + {"universal8:", ggUniversals[8]}, + {"universal9:", ggUniversals[9]}, + {"universal10:", ggUniversals[10]}, + {"universal11:", ggUniversals[11]}, + {"universal12:", ggUniversals[12]}, + {"universal13:", ggUniversals[13]}, + {"universal14:", ggUniversals[14]}, + {"universal15:", ggUniversals[15]}, + {"universal16:", ggUniversals[16]}, + {"universal17:", ggUniversals[17]}, + {"universal18:", ggUniversals[18]}, + {"universal19:", ggUniversals[19]}, + {"universal20:", ggUniversals[20]}, + {"universal21:", ggUniversals[21]}, + {"universal22:", ggUniversals[22]}, + {"universal23:", ggUniversals[23]}, + {"universal24:", ggUniversals[24]}, + {"universal25:", ggUniversals[25]}, + {"universal26:", ggUniversals[26]}, + {"universal27:", ggUniversals[27]}, + {"universal28:", ggUniversals[28]}, + {"universal29:", ggUniversals[29]}, + {"inverterenable1_bt:", ggInverterEnableButtons[0]}, + {"inverterenable2_bt:", ggInverterEnableButtons[1]}, + {"inverterenable3_bt:", ggInverterEnableButtons[2]}, + {"inverterenable4_bt:", ggInverterEnableButtons[3]}, + {"inverterenable5_bt:", ggInverterEnableButtons[4]}, + {"inverterenable6_bt:", ggInverterEnableButtons[5]}, + {"inverterenable7_bt:", ggInverterEnableButtons[6]}, + {"inverterenable8_bt:", ggInverterEnableButtons[7]}, + {"inverterenable9_bt:", ggInverterEnableButtons[8]}, + {"inverterenable10_bt:", ggInverterEnableButtons[9]}, + {"inverterenable11_bt:", ggInverterEnableButtons[10]}, + {"inverterenable12_bt:", ggInverterEnableButtons[11]}, + {"inverterdisable1_bt:", ggInverterDisableButtons[0]}, + {"inverterdisable2_bt:", ggInverterDisableButtons[1]}, + {"inverterdisable3_bt:", ggInverterDisableButtons[2]}, + {"inverterdisable4_bt:", ggInverterDisableButtons[3]}, + {"inverterdisable5_bt:", ggInverterDisableButtons[4]}, + {"inverterdisable6_bt:", ggInverterDisableButtons[5]}, + {"inverterdisable7_bt:", ggInverterDisableButtons[6]}, + {"inverterdisable8_bt:", ggInverterDisableButtons[7]}, + {"inverterdisable9_bt:", ggInverterDisableButtons[8]}, + {"inverterdisable10_bt:", ggInverterDisableButtons[9]}, + {"inverterdisable11_bt:", ggInverterDisableButtons[10]}, + {"inverterdisable12_bt:", ggInverterDisableButtons[11]}, + {"invertertoggle1_bt:", ggInverterToggleButtons[0]}, + {"invertertoggle2_bt:", ggInverterToggleButtons[1]}, + {"invertertoggle3_bt:", ggInverterToggleButtons[2]}, + {"invertertoggle4_bt:", ggInverterToggleButtons[3]}, + {"invertertoggle5_bt:", ggInverterToggleButtons[4]}, + {"invertertoggle6_bt:", ggInverterToggleButtons[5]}, + {"invertertoggle7_bt:", ggInverterToggleButtons[6]}, + {"invertertoggle8_bt:", ggInverterToggleButtons[7]}, + {"invertertoggle9_bt:", ggInverterToggleButtons[8]}, + {"invertertoggle10_bt:", ggInverterToggleButtons[9]}, + {"invertertoggle11_bt:", ggInverterToggleButtons[10]}, + {"invertertoggle12_bt:", ggInverterToggleButtons[11]}, + {"pantvalvesupdate_bt:", ggPantValvesUpdate}, + {"pantvalvesoff_bt:", ggPantValvesOff}, + {"wipers_sw:", ggWiperSw}}; + { + auto const lookup{gauges.find(Label)}; + if (lookup != gauges.end()) + { + lookup->second.Load(Parser, DynamicObject); + m_controlmapper.insert(lookup->second, lookup->first); + return true; + } + } + // dedicated gauges with state-driven optional submodel + // TODO: move viable gauges here + // TODO: convert dedicated gauges to auto-allocated ones, replace dedicated references in command handlers to mapper lookups + std::unordered_map> const stategauges = { + {"tempomat_sw:", {ggScndCtrlButton, &mvOccupied->SpeedCtrlUnit.IsActive}}, + {"tempomatoff_sw:", {ggScndCtrlOffButton, &mvOccupied->SpeedCtrlUnit.IsActive}}, + {"speedinc_bt:", {ggSpeedControlIncreaseButton, &mvOccupied->SpeedCtrlUnit.IsActive}}, + {"speeddec_bt:", {ggSpeedControlDecreaseButton, &mvOccupied->SpeedCtrlUnit.IsActive}}, + {"speedctrlpowerinc_bt:", {ggSpeedControlPowerIncreaseButton, &mvOccupied->SpeedCtrlUnit.IsActive}}, + {"speedctrlpowerdec_bt:", {ggSpeedControlPowerDecreaseButton, &mvOccupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton0:", {ggSpeedCtrlButtons[0], &mvOccupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton1:", {ggSpeedCtrlButtons[1], &mvOccupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton2:", {ggSpeedCtrlButtons[2], &mvOccupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton3:", {ggSpeedCtrlButtons[3], &mvOccupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton4:", {ggSpeedCtrlButtons[4], &mvOccupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton5:", {ggSpeedCtrlButtons[5], &mvOccupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton6:", {ggSpeedCtrlButtons[6], &mvOccupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton7:", {ggSpeedCtrlButtons[7], &mvOccupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton8:", {ggSpeedCtrlButtons[8], &mvOccupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton9:", {ggSpeedCtrlButtons[9], &mvOccupied->SpeedCtrlUnit.IsActive}}, + {"doorleftpermit_sw:", {ggDoorLeftPermitButton, &m_doorspermitleft}}, + {"doorrightpermit_sw:", {ggDoorRightPermitButton, &m_doorspermitright}}, + {"dooralloff_sw:", {ggDoorAllOffButton, &m_doors}}, + {"doorstep_sw:", {ggDoorStepButton, &mvOccupied->Doors.step_enabled}}, + {"dirforward_bt:", {ggDirForwardButton, &m_dirforward}}, + {"dirneutral_bt:", {ggDirNeutralButton, &m_dirneutral}}, + {"dirbackward_bt:", {ggDirBackwardButton, &m_dirbackward}}, + }; + { + auto const lookup{stategauges.find(Label)}; + if (lookup != stategauges.end()) + { + auto &gauge{std::get(lookup->second)}; + gauge.Load(Parser, DynamicObject); + gauge.AssignState(std::get(lookup->second)); + m_controlmapper.insert(gauge, lookup->first); + return true; + } + } + // TODO: move viable dedicated gauges to the automatic array + std::unordered_map const autoboolgauges = { + {"doormode_sw:", &mvOccupied->Doors.remote_only}, + {"coolingfans_sw:", &mvControlled->RVentForceOn}, + {"pantfront_sw:", &mvPantographUnit->Pantographs[end::front].valve.is_enabled}, + {"pantrear_sw:", &mvPantographUnit->Pantographs[end::rear].valve.is_enabled}, + {"pantfrontoff_sw:", &mvPantographUnit->Pantographs[end::front].valve.is_disabled}, + {"pantrearoff_sw:", &mvPantographUnit->Pantographs[end::rear].valve.is_disabled}, + {"radio_sw:", &mvOccupied->Radio}, + {"radiofuse_sw:", &mvOccupied->RadioFuse}, + {"cablight_sw:", &Cabine[iCabn].bLight}, + {"springbraketoggle_bt:", &mvOccupied->SpringBrake.Activate}, + {"couplingdisconnect_sw:", &m_couplingdisconnect}, + {"couplingdisconnectback_sw:", &m_couplingdisconnectback}, + {"mirrors_sw:", &mvOccupied->MirrorForbidden}, + }; + { + auto lookup = autoboolgauges.find(Label); + if (lookup != autoboolgauges.end()) + { + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna lampka + gauge.Load(Parser, DynamicObject); + gauge.AssignBool(lookup->second); + m_controlmapper.insert(gauge, lookup->first); + return true; + } + } + // TODO: move viable dedicated gauges to the automatic array + std::unordered_map const autointgauges = { + {"manualbrake:", &mvOccupied->ManualBrakePos}, + {"pantselect_sw:", &mvOccupied->PantsPreset.second[cab_to_end()]}, + }; + { + auto lookup = autointgauges.find(Label); + if (lookup != autointgauges.end()) + { + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna lampka + gauge.Load(Parser, DynamicObject); + gauge.AssignInt(lookup->second); + m_controlmapper.insert(gauge, lookup->first); + return true; + } + } + + // broadcast radio receiver + if (Label == "fmradio_sw:" || Label == "fmradiovolume_sw:" || Label == "fmradiotune_sw:" || Label == "fmradioscale:") + { + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + if (Label == "fmradio_sw:") + { + gauge.AssignBool(&m_fmradiopower); + } + else + { + gauge.AssignFloat(Label == "fmradiovolume_sw:" ? &m_fmradiovolume : &m_fmradiodial); + } + if (Label != "fmradioscale:") + { + // the scale pointer is an indicator, the rest are controls + m_controlmapper.insert(gauge, Label); + } + m_fmradiopresent = true; + // unless the speaker location is defined explicitly, the sound comes from the first defined element of the receiver + if (m_fmradiosound.offset() == glm::vec3()) + { + m_fmradiosound.offset(gauge.model_offset()); + } + return true; + } + + // ABu 090305: uniwersalne przyciski lub inne rzeczy + if (Label == "mainctrlact:") + { + ggMainCtrlAct.Load(Parser, DynamicObject); + } + // SEKCJA WSKAZNIKOW + else if (Label == "tachometer:" || Label == "tachometerb:") + { + // predkosciomierz wskaźnikowy z szarpaniem + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(&fTachoVelocityJump); + // bind tachometer sound location to the meter + if (dsbHasler && dsbHasler->offset() == glm::vec3()) + { + dsbHasler->offset(gauge.model_offset()); + } + } + else if (Label == "tachometern:") + { + // predkosciomierz wskaźnikowy bez szarpania + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(&fTachoVelocity); + // bind tachometer sound location to the meter + if (dsbHasler && dsbHasler->offset() == glm::vec3()) + { + dsbHasler->offset(gauge.model_offset()); + } + } + else if (Label == "tachometerd:") + { + // predkosciomierz cyfrowy + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(&fTachoVelocity); + // bind tachometer sound location to the meter + if (dsbHasler && dsbHasler->offset() == glm::vec3()) + { + dsbHasler->offset(gauge.model_offset()); + } + } + else if (Label == "hvcurrent1:" || Label == "hvcurrent1b:") + { + // 1szy amperomierz + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(fHCurrent + 1); + } + else if (Label == "hvcurrent2:" || Label == "hvcurrent2b:") + { + // 2gi amperomierz + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(fHCurrent + 2); + } + else if (Label == "hvcurrent3:" || Label == "hvcurrent3b:") + { + // 3ci amperomierz + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałska + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(fHCurrent + 3); + } + else if (Label == "hvcurrent:" || Label == "hvcurrentb:") + { + // amperomierz calkowitego pradu + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(fHCurrent); + } + else if (Label == "eimscreen:") + { + // amperomierz calkowitego pradu + int i; + int j; + Parser.getTokens(2, false); + Parser >> i >> j; + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(&fEIMParams[i][j]); + } + else if (Label == "brakes:") + { + // specified pipe pressure of specified consist vehicle + int i; + int j; + Parser.getTokens(2, false); + Parser >> i >> j; + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject, 0.1); + gauge.AssignFloat(&fPress[std::clamp(i, 1, 20) - 1][std::clamp(j, 0, 3)]); + } + else if (Label == "brakepress:" || Label == "brakepressb:") + { + // manometr cylindrow hamulcowych + // Ra 2014-08: przeniesione do TCab + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject, 0.1); + gauge.AssignDouble(&mvOccupied->BrakePress); + } + else if (Label == "pipepress:" || Label == "pipepressb:") + { + // manometr przewodu hamulcowego + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject, 0.1); + gauge.AssignDouble(&mvOccupied->PipePress); + } + else if (Label == "scndpress:") + { + // manometr przewodu hamulcowego + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject, 0.1); + gauge.AssignDouble(&mvOccupied->ScndPipePress); + } + else if (Label == "limpipepress:") + { + // manometr zbiornika sterujacego zaworu maszynisty + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject, 0.1); + gauge.AssignDouble(&m_brakehandlecp); + } + else if (Label == "cntrlpress:") + { + // manometr zbiornika kontrolnego/rorzďż˝du + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject, 0.1); + gauge.AssignDouble(&mvPantographUnit->PantPress); + } + else if (Label == "springbrakepress:") + { + // manometr cylindra hamulca sprężynowego + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject, 0.1); + gauge.AssignDouble(&mvOccupied->SpringBrake.SBP); + } + else if (Label == "epctrlvalue:") + { + // wskazowka sterowania sila hamulca ep + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject, 0.1); + gauge.AssignDouble(&mvOccupied->EpForce); + } + else if (Label == "compressor:" || Label == "compressorb:") + { + // manometr sprezarki/zbiornika glownego + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject, 0.1); + gauge.AssignDouble(&mvOccupied->Compressor); + } + else if (Label == "oilpress:") + { + // oil pressure + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(&mvControlled->OilPump.pressure); + } + else if (Label == "oiltemp:") + { + // oil temperature + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(&mvControlled->dizel_heat.To); + } + else if (Label == "water1temp:") + { + // main circuit water temperature + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(&mvControlled->dizel_heat.temperatura1); + } + else if (Label == "water2temp:") + { + // auxiliary circuit water temperature + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(&mvControlled->dizel_heat.temperatura2); + } + else if (Label == "pantpress:") + { + // pantograph tank pressure + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject, 0.1); + gauge.AssignDouble(&mvPantographUnit->PantPress); + } + // yB - dla drugiej sekcji + else if (Label == "hvbcurrent1:") + { + // 1szy amperomierz + ggI1B.Load(Parser, DynamicObject); + } + else if (Label == "hvbcurrent2:") + { + // 2gi amperomierz + ggI2B.Load(Parser, DynamicObject); + } + else if (Label == "hvbcurrent3:") + { + // 3ci amperomierz + ggI3B.Load(Parser, DynamicObject); + } + else if (Label == "hvbcurrent:") + { + // amperomierz calkowitego pradu + ggItotalB.Load(Parser, DynamicObject); + } + //************************************************************* + else if (Label == "clock:") + { + // zegar analogowy + if (Parser.getToken() == "analog" && DynamicObject->mdKabina) + { + // McZapkie-300302: zegarek + ggClockSInd.Init(DynamicObject->mdKabina->GetFromName("ClockShand"), nullptr, TGaugeAnimation::gt_Rotate, static_cast(1.0 / 60.0)); + ggClockMInd.Init(DynamicObject->mdKabina->GetFromName("ClockMhand"), nullptr, TGaugeAnimation::gt_Rotate, static_cast(1.0 / 60.0)); + ggClockHInd.Init(DynamicObject->mdKabina->GetFromName("ClockHhand"), nullptr, TGaugeAnimation::gt_Rotate, static_cast(1.0 / 12.0)); + } + } + else if (Label == "clock_seconds:") + { + ggClockSInd.Load(Parser, DynamicObject); + } + else if (Label == "evoltage:") + { + // woltomierz napiecia silnikow + ggEngineVoltage.Load(Parser, DynamicObject); + } + else if (Label == "hvoltage:") + { + // woltomierz wysokiego napiecia + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(&fHVoltage); + } + else if (Label == "lvoltage:") + { + // woltomierz niskiego napiecia + ggLVoltage.Load(Parser, DynamicObject); + } + else if (Label == "enrot1m:") + { + // obrotomierz + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(fEngine + 1); + } // ggEnrot1m.Load(Parser,DynamicObject->mdKabina); + else if (Label == "enrot2m:") + { + // obrotomierz + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(fEngine + 2); + } // ggEnrot2m.Load(Parser,DynamicObject->mdKabina); + else if (Label == "enrot3m:") + { // obrotomierz + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(fEngine + 3); + } // ggEnrot3m.Load(Parser,DynamicObject->mdKabina); + else if (Label == "engageratio:") + { + // np. ciśnienie sterownika sprzęgła + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignDouble(&mvControlled->dizel_engage); + } // ggEngageRatio.Load(Parser,DynamicObject->mdKabina); + else if (Label == "maingearstatus:") + { + // np. ciśnienie sterownika skrzyni biegów + ggMainGearStatus.Load(Parser, DynamicObject); + } + else if (Label == "ignitionkey:") + { + ggIgnitionKey.Load(Parser, DynamicObject); + } + else if (Label == "distcounter:") + { + // Ra 2014-07: licznik kilometrów + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + // the counter shows the odometer of the vehicle, kept between the sessions (eu07/maszyna#72). its offset + // was the state it started each session with, now it is that only for a vehicle with no known state + if (auto const seed{odometer::counter_seed(gauge.offset(), gauge.scale())}; seed.has_value()) + mvControlled->Odometer.seed(*seed); + gauge.offset(0.f); + gauge.AssignDouble(&mvControlled->Odometer.km); + // the vehicle the counter counts for is one the odometer store keeps, also in the sessions the counter seeds + // nothing (its state is a saved one by then) and when it's the motor car of the unit the cab is in + mvControlled->Odometer.shown = true; + } + else if (Label == "shuntmodepower:") + { + // shunt mode power slider + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignDouble(&mvControlled->AnPos); + m_controlmapper.insert(gauge, "shuntmodepower:"); + } + else if (Label == "heatingvoltage:") + { + if (mvControlled->HeatingPowerSource.SourceType == TPowerSource::Generator) + { + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignDouble(&mvControlled->HeatingPowerSource.EngineGenerator.voltage); + } + } + else if (Label == "heatingcurrent:") + { + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignDouble(&mvControlled->TotalCurrent); + } + else + { + // failed to match the label + return false; + } + + return true; +} diff --git a/vehicle/cab/signalcommands.cpp b/vehicle/cab/signalcommands.cpp new file mode 100644 index 000000000..200781dbe --- /dev/null +++ b/vehicle/cab/signalcommands.cpp @@ -0,0 +1,517 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the commands of the horns and the radios + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/mover.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +void TTrain::OnCommand_hornlowactivate(TTrain *Train, command_data const &Command) +{ + + if (Train->ggHornButton.SubModel == nullptr && Train->ggHornLowButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Horn button is missing, or wasn't defined"); + } + return; + } + + if (Command.action == GLFW_PRESS) + { + // only need to react to press, sound will continue until stopped + if (false == TestFlag(Train->mvOccupied->WarningSignal, horn::low)) + { + // turn on + Train->mvOccupied->WarningSignal = horn::pressed(Train->mvOccupied->WarningSignal, horn::low, Train->has_single_horn_lever()); + // visual feedback + Train->ggHornButton.UpdateValue(-1.0); + Train->ggHornLowButton.UpdateValue(1.0); + } + } + else if (Command.action == GLFW_RELEASE) + { + // turn off + Train->mvOccupied->WarningSignal = horn::released(Train->mvOccupied->WarningSignal, horn::low); + // visual feedback + if (false == (Train->has_single_horn_lever() && TestFlag(Train->mvOccupied->WarningSignal, horn::high))) + { + // leave the single lever alone if it was moved to the other tone in the meantime + Train->ggHornButton.UpdateValue(0.0); + } + Train->ggHornLowButton.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_hornhighactivate(TTrain *Train, command_data const &Command) +{ + + if (Train->ggHornButton.SubModel == nullptr && Train->ggHornHighButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Horn button is missing, or wasn't defined"); + } + return; + } + + if (Command.action == GLFW_PRESS) + { + // only need to react to press, sound will continue until stopped + if (false == TestFlag(Train->mvOccupied->WarningSignal, horn::high)) + { + // turn on + Train->mvOccupied->WarningSignal = horn::pressed(Train->mvOccupied->WarningSignal, horn::high, Train->has_single_horn_lever()); + // visual feedback + Train->ggHornButton.UpdateValue(1.0); + Train->ggHornHighButton.UpdateValue(1.0); + } + } + else if (Command.action == GLFW_RELEASE) + { + // turn off + Train->mvOccupied->WarningSignal = horn::released(Train->mvOccupied->WarningSignal, horn::high); + // visual feedback + if (false == (Train->has_single_horn_lever() && TestFlag(Train->mvOccupied->WarningSignal, horn::low))) + { + // leave the single lever alone if it was moved to the other tone in the meantime + Train->ggHornButton.UpdateValue(0.0); + } + Train->ggHornHighButton.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_whistleactivate(TTrain *Train, command_data const &Command) +{ + + if (Train->ggWhistleButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Whistle button is missing, or wasn't defined"); + } + return; + } + + if (Command.action == GLFW_PRESS) + { + // only need to react to press, sound will continue until stopped + if (false == TestFlag(Train->mvOccupied->WarningSignal, 4)) + { + // turn on + Train->mvOccupied->WarningSignal |= 4; + // visual feedback + Train->ggWhistleButton.UpdateValue(1.0); + } + } + else if (Command.action == GLFW_RELEASE) + { + // turn off + Train->mvOccupied->WarningSignal &= ~4; + // visual feedback + Train->ggWhistleButton.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_radiotoggle(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + + // NOTE: works without the switch in the 3d model too, to allow system reset after receiving radio-stop signal + // only reacting to press, so the sound can loop uninterrupted + // NOTE: flips the state directly rather than through radioenable/radiodisable, so it doesn't move the radioon_sw:/radiooff_sw: buttons + Train->mvOccupied->Radio = (false == Train->mvOccupied->Radio); +} + +void TTrain::OnCommand_radioenable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + Train->mvOccupied->Radio = true; + // visual feedback + if (Train->m_controlmapper.contains("radioon_sw:")) + { + Train->ggRadioOnButton.UpdateValue(1.0f, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + if (Train->m_controlmapper.contains("radioon_sw:")) + { + Train->ggRadioOnButton.UpdateValue(0.0f, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_radiodisable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + Train->mvOccupied->Radio = false; + // visual feedback + if (Train->m_controlmapper.contains("radiooff_sw:")) + { + Train->ggRadioOffButton.UpdateValue(1.0f, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + if (Train->m_controlmapper.contains("radiooff_sw:")) + { + Train->ggRadioOffButton.UpdateValue(0.0f, Train->dsbSwitch); + } + } +} + +// the cut-off in the radio's power supply (eu07/maszyna#438); opening it works like switching the radio off, the +// radio-stop flag included +void TTrain::OnCommand_radiofusetoggle(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + + // NOTE: flips the state directly rather than through radiofuseenable/radiofusedisable, so it doesn't move the + // radiofuseon_sw:/radiofuseoff_sw: buttons + Train->mvOccupied->RadioFuse = (false == Train->mvOccupied->RadioFuse); +} + +void TTrain::OnCommand_radiofuseenable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + Train->mvOccupied->RadioFuse = true; + // visual feedback + if (Train->m_controlmapper.contains("radiofuseon_sw:")) + { + Train->ggRadioFuseOnButton.UpdateValue(1.0f, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + if (Train->m_controlmapper.contains("radiofuseon_sw:")) + { + Train->ggRadioFuseOnButton.UpdateValue(0.0f, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_radiofusedisable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + Train->mvOccupied->RadioFuse = false; + // visual feedback + if (Train->m_controlmapper.contains("radiofuseoff_sw:")) + { + Train->ggRadioFuseOffButton.UpdateValue(1.0f, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + if (Train->m_controlmapper.contains("radiofuseoff_sw:")) + { + Train->ggRadioFuseOffButton.UpdateValue(0.0f, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_radiochannelincrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // the channel buttons of a radio switched off or without power do nothing + if (Train->mvOccupied->RadioPowered()) + { + command_data newCommand = Command; + newCommand.param1 = Train->RadioChannel() + 1; + OnCommand_radiochannelset(Train, newCommand); + } + + Train->ggRadioChannelNext.UpdateValue(1.0); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggRadioChannelNext.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_radiochanneldecrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + if (Train->mvOccupied->RadioPowered()) + { + command_data newCommand = Command; + newCommand.param1 = Train->RadioChannel() - 1; + OnCommand_radiochannelset(Train, newCommand); + } + + Train->ggRadioChannelPrevious.UpdateValue(1.0); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggRadioChannelPrevious.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_radiochannelset(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_RELEASE) + { + // on press or hold + Train->RadioChannel() = std::clamp((int)Command.param1, 1, 10); + Train->ggRadioChannelSelector.UpdateValue(static_cast(Train->RadioChannel() - 1)); + } +} + +void TTrain::OnCommand_radiostopsend(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + if (Train->mvOccupied->RadioPowered()) + { + simulation::Region->RadioStop(Train->Dynamic()->GetPosition()); + } + // visual feedback + Train->ggRadioStop.UpdateValue(1.0); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggRadioStop.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_radiostopenable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS && Train->ggRadioStop.GetValue() == 0) + { + if (Train->mvOccupied->RadioPowered()) + { + simulation::Region->RadioStop(Train->Dynamic()->GetPosition()); + } + // visual feedback + Train->ggRadioStop.UpdateValue(1.0); + } +} + +void TTrain::OnCommand_radiostopdisable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS && Train->ggRadioStop.GetValue() > 0) + { + // visual feedback + Train->ggRadioStop.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_radiostoptest(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + if (Train->RadioChannel() == 10 && Train->mvOccupied->RadioPowered()) + { + Train->Dynamic()->RadioStop(); + } + // visual feedback + Train->ggRadioTest.UpdateValue(1.0); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggRadioTest.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_radiocall1send(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + if (Train->RadioChannel() != 10 && Train->mvOccupied->RadioPowered()) + { + simulation::Events.queue_receivers(radio_message::call1, Train->Dynamic()->GetPosition()); + } + // visual feedback + Train->ggRadioCall1.UpdateValue(1.0); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggRadioCall1.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_radiocall3send(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + if (Train->RadioChannel() != 10 && Train->mvOccupied->RadioPowered()) + { + simulation::Events.queue_receivers(radio_message::call3, Train->Dynamic()->GetPosition()); + } + // visual feedback + Train->ggRadioCall3.UpdateValue(1.0); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggRadioCall3.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_radiovolumeincrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // so do the volume buttons + if (Train->mvOccupied->RadioPowered()) + { + command_data newCommand = Command; + newCommand.param1 = Train->m_radiovolume + 0.125; + OnCommand_radiovolumeset(Train, newCommand); + } + Train->ggRadioVolumeNext.UpdateValue(1.0); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggRadioVolumeNext.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_radiovolumedecrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + if (Train->mvOccupied->RadioPowered()) + { + command_data newCommand = Command; + newCommand.param1 = Train->m_radiovolume - 0.125; + OnCommand_radiovolumeset(Train, newCommand); + } + Train->ggRadioVolumePrevious.UpdateValue(1.0); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggRadioVolumePrevious.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_radiovolumeset(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_RELEASE) + { + // on press or hold + Train->m_radiovolume = static_cast(std::clamp(Command.param1, 0.0, 1.0)); + Train->ggRadioVolumeSelector.UpdateValue(Train->m_radiovolume); + audio::event_volume_change = true; + } +} + +void TTrain::OnCommand_fmradiotoggle(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS && Train->m_fmradiopresent) + { + Train->m_fmradiopower = !Train->m_fmradiopower; + } +} + +void TTrain::OnCommand_fmradiovolumeincrease(TTrain *Train, command_data const &Command) +{ + // the knob keeps turning for as long as the control is held, the actual movement takes place in the update + Train->m_fmradiovolumechange = (Command.action != GLFW_RELEASE && Train->m_fmradiopresent ? 1 : 0); +} + +void TTrain::OnCommand_fmradiovolumedecrease(TTrain *Train, command_data const &Command) +{ + Train->m_fmradiovolumechange = (Command.action != GLFW_RELEASE && Train->m_fmradiopresent ? -1 : 0); +} + +void TTrain::OnCommand_fmradiovolumeset(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_RELEASE && Train->m_fmradiopresent) + { + Train->m_fmradiovolume = std::clamp(static_cast(Command.param1), 0.f, 1.f); + if (false == Train->m_controlmapper.contains("fmradio_sw:")) + { + // receivers without dedicated switch are switched with the volume knob + Train->m_fmradiopower = Train->m_fmradiovolume > 0.f; + } + } +} + +void TTrain::OnCommand_fmradiotuneincrease(TTrain *Train, command_data const &Command) +{ + Train->m_fmradiotunechange = (Command.action != GLFW_RELEASE && Train->m_fmradiopresent ? 1 : 0); +} + +void TTrain::OnCommand_fmradiotunedecrease(TTrain *Train, command_data const &Command) +{ + Train->m_fmradiotunechange = (Command.action != GLFW_RELEASE && Train->m_fmradiopresent ? -1 : 0); +} + +// sets the receiver to frequency specified in MHz +void TTrain::OnCommand_fmradiotuneset(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_RELEASE && Train->m_fmradiopresent) + { + Train->m_fmradiodial = std::clamp(100.f * (static_cast(Command.param1) - audio::EU07_FMRADIO_BANDSTART) / (audio::EU07_FMRADIO_BANDEND - audio::EU07_FMRADIO_BANDSTART), 0.f, 100.f); + Train->m_fmradiotuned = true; + } +} diff --git a/vehicle/cab/sounds.cpp b/vehicle/cab/sounds.cpp new file mode 100644 index 000000000..01a40da0a --- /dev/null +++ b/vehicle/cab/sounds.cpp @@ -0,0 +1,563 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the sounds of the cab + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/mover.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +void TTrain::update_sounds(double const Deltatime) +{ + + double volume{0.0}; + double const brakevolumescale{0.5}; + + // Winger-160404 - syczenie pomocniczego (luzowanie) + if (m_lastlocalbrakepressure != -1.f) + { + // calculate rate of pressure drop in local brake cylinder, once it's been initialized + auto const brakepressuredifference{mvOccupied->LocBrakePress - m_lastlocalbrakepressure}; + m_localbrakepressurechange = static_cast(std::lerp(m_localbrakepressurechange, 10 * (brakepressuredifference / Deltatime), 0.1f)); + } + m_lastlocalbrakepressure = static_cast(mvOccupied->LocBrakePress); + // local brake, release + if (rsSBHiss) + { + if (m_localbrakepressurechange < -0.05f && mvOccupied->LocBrakePress > mvOccupied->BrakePress - 0.05) + { + rsSBHiss->gain(static_cast(std::clamp(rsSBHiss->m_amplitudeoffset + rsSBHiss->m_amplitudefactor * -m_localbrakepressurechange * 0.05, 0.0, 1.5))); + rsSBHiss->play(sound_flags::exclusive | sound_flags::looping); + } + else + { + // don't stop the sound too abruptly + volume = std::max(0.0, rsSBHiss->gain() - 0.1 * Deltatime); + rsSBHiss->gain(static_cast(volume)); + if (volume < 0.05) + { + rsSBHiss->stop(); + } + } + } + // local brake, engage + if (rsSBHissU) + { + if (m_localbrakepressurechange > 0.05f) + { + rsSBHissU->gain(static_cast(std::clamp(rsSBHissU->m_amplitudeoffset + rsSBHissU->m_amplitudefactor * m_localbrakepressurechange * 0.05, 0.0, 1.5))); + rsSBHissU->play(sound_flags::exclusive | sound_flags::looping); + } + else + { + // don't stop the sound too abruptly + volume = std::max(0.0, rsSBHissU->gain() - 0.1 * Deltatime); + rsSBHissU->gain(static_cast(volume)); + if (volume < 0.05) + { + rsSBHissU->stop(); + } + } + } + + // McZapkie-280302 - syczenie + // TODO: softer volume reduction than plain abrupt stop, perhaps as reusable wrapper? + if (mvOccupied->BrakeHandle == TBrakeHandle::FV4a || mvOccupied->BrakeHandle == TBrakeHandle::FVel6) + { + // upuszczanie z PG + if (rsHiss) + { + fPPress = std::lerp(fPPress, static_cast(mvOccupied->Handle->GetSound(s_fv4a_b)), 0.05f); + volume = fPPress > 0 ? rsHiss->m_amplitudefactor * fPPress * 0.25 + rsHiss->m_amplitudeoffset : 0; + if (volume * brakevolumescale > 0.05) + { + rsHiss->gain(static_cast(volume * brakevolumescale)); + rsHiss->play(sound_flags::exclusive | sound_flags::looping); + } + else + { + rsHiss->stop(); + } + } + // napelnianie PG + if (rsHissU) + { + fNPress = std::lerp(fNPress, static_cast(mvOccupied->Handle->GetSound(s_fv4a_u)), 0.25f); + volume = fNPress > 0 ? rsHissU->m_amplitudefactor * fNPress + rsHissU->m_amplitudeoffset : 0; + if (volume * brakevolumescale > 0.05) + { + rsHissU->gain(static_cast(volume * brakevolumescale)); + rsHissU->play(sound_flags::exclusive | sound_flags::looping); + } + else + { + rsHissU->stop(); + } + } + // upuszczanie przy naglym + if (rsHissE) + { + volume = mvOccupied->Handle->GetSound(s_fv4a_e) * rsHissE->m_amplitudefactor + rsHissE->m_amplitudeoffset; + if (volume * brakevolumescale > 0.05) + { + rsHissE->gain(static_cast(volume * brakevolumescale)); + rsHissE->play(sound_flags::exclusive | sound_flags::looping); + } + else + { + rsHissE->stop(); + } + } + // upuszczanie sterujacego fala + if (rsHissX) + { + volume = mvOccupied->Handle->GetSound(s_fv4a_x) * rsHissX->m_amplitudefactor + rsHissX->m_amplitudeoffset; + if (volume * brakevolumescale > 0.05) + { + rsHissX->gain(static_cast(volume * brakevolumescale)); + rsHissX->play(sound_flags::exclusive | sound_flags::looping); + } + else + { + rsHissX->stop(); + } + } + // upuszczanie z czasowego + if (rsHissT) + { + volume = mvOccupied->Handle->GetSound(s_fv4a_t) * rsHissT->m_amplitudefactor + +rsHissT->m_amplitudeoffset; + if (volume * brakevolumescale > 0.05) + { + rsHissT->gain(static_cast(volume * brakevolumescale)); + rsHissT->play(sound_flags::exclusive | sound_flags::looping); + } + else + { + rsHissT->stop(); + } + } + } + else + { + // jesli nie FV4a + // upuszczanie z PG + if (rsHiss) + { + fPPress = static_cast((4.0f * fPPress + std::max(0.0, mvOccupied->dpMainValve)) / (4.0f + 1.0f)); + volume = fPPress > 0.0f ? 2.0 * rsHiss->m_amplitudefactor * fPPress + rsHiss->m_amplitudeoffset : 0.0; + if (volume > 0.05) + { + rsHiss->gain(static_cast(volume)); + rsHiss->play(sound_flags::exclusive | sound_flags::looping); + } + else + { + rsHiss->stop(); + } + } + // napelnianie PG + if (rsHissU) + { + fNPress = static_cast((4.0f * fNPress + std::min(0.0, mvOccupied->dpMainValve)) / (4.0f + 1.0f)); + volume = fNPress < 0.0f ? -1.0 * rsHissU->m_amplitudefactor * fNPress + rsHissU->m_amplitudeoffset : 0.0; + if (volume > 0.01) + { + rsHissU->gain(static_cast(volume)); + rsHissU->play(sound_flags::exclusive | sound_flags::looping); + } + else + { + rsHissU->stop(); + } + } + } // koniec nie FV4a + + // brakes + if (rsBrake) + { + if (mvOccupied->UnitBrakeForce > 10.0 && mvOccupied->Vel > 0.05) + { + + auto const brakeforceratio{ + std::clamp(mvOccupied->UnitBrakeForce / std::max(1.0, mvOccupied->BrakeForceR(1.0, mvOccupied->Vel) / (mvOccupied->NAxles * std::max(1, mvOccupied->NBpA))), 0.0, 1.0)}; + // HACK: in external view mute the sound rather than stop it, in case there's an opening bookend it'd (re)play on sound restart after returning inside + volume = FreeFlyModeFlag ? 0.0 : rsBrake->m_amplitudeoffset + std::sqrt(brakeforceratio * std::lerp(0.4, 1.0, mvOccupied->Vel / (1 + mvOccupied->Vmax))) * rsBrake->m_amplitudefactor; + rsBrake->pitch(static_cast(rsBrake->m_frequencyoffset + mvOccupied->Vel * rsBrake->m_frequencyfactor)); + rsBrake->gain(static_cast(volume)); + rsBrake->play(sound_flags::exclusive | sound_flags::looping); + } + else + { + rsBrake->stop(); + } + } + + // ambient sound + // since it's typically ticking of the clock we can center it on tachometer or on middle of compartment bounding area + if (rsFadeSound) + { + rsFadeSound->play(sound_flags::exclusive | sound_flags::looping); + } + + if (dsbSlipAlarm) + { + // alarm przy poslizgu dla 181/182 - BOMBARDIER + if (mvControlled->SlippingWheels && DynamicObject->GetVelocity() > 1.0) + { + dsbSlipAlarm->play(sound_flags::exclusive | sound_flags::looping); + } + else + { + dsbSlipAlarm->stop(); + } + } + + // dzwiek wiatru rozbijajacego sie o szyby w kabinie + if (rsWindSound) + { + if (!FreeFlyModeFlag && !Global.CabWindowOpen && DynamicObject->GetVelocity() > 0.5) + update_sounds_resonancenoise(*rsWindSound); + else + rsWindSound->stop(FreeFlyModeFlag); + } + + // dzwiek rezonansu (taki drugi runningnoise w sumie) + if (rsResonanceNoise) + { + if (!FreeFlyModeFlag && !Global.CabWindowOpen && DynamicObject->GetVelocity() > 0.5) + { + + update_sounds_resonancenoise(*rsResonanceNoise); + } + else + rsResonanceNoise->stop(FreeFlyModeFlag); + } + + // szum w czasie jazdy + if (rsRunningNoise) + { + if (false == FreeFlyModeFlag && false == Global.CabWindowOpen && DynamicObject->GetVelocity() > 0.5) + { + + update_sounds_runningnoise(*rsRunningNoise); + } + else + { + // don't play the optional ending sound if the listener switches views + rsRunningNoise->stop(true == FreeFlyModeFlag); + } + } + // hunting oscillation noise + if (rsHuntingNoise) + { + if (false == FreeFlyModeFlag && false == Global.CabWindowOpen && DynamicObject->GetVelocity() > 0.5 && DynamicObject->IsHunting) + { + + update_sounds_runningnoise(*rsHuntingNoise); + // modify calculated sound volume by hunting amount + auto const huntingamount = std::lerp( + 0.0, 1.0, std::clamp((mvOccupied->Vel - DynamicObject->HuntingShake.fadein_begin) / (DynamicObject->HuntingShake.fadein_end - DynamicObject->HuntingShake.fadein_begin), 0.0, 1.0)); + + rsHuntingNoise->gain(static_cast(rsHuntingNoise->gain() * huntingamount)); + } + else + { + // don't play the optional ending sound if the listener switches views + rsHuntingNoise->stop(true == FreeFlyModeFlag); + } + } + // rain sound + if (m_rainsound) + { + if (false == FreeFlyModeFlag && false == Global.CabWindowOpen && Global.Weather == "rain:") + { + if (m_rainsound->is_combined()) + { + m_rainsound->pitch(static_cast(Global.Overcast - 1.0)); + } + m_rainsound->gain(m_rainsound->m_amplitudeoffset + m_rainsound->m_amplitudefactor * 1.f); + m_rainsound->play(sound_flags::exclusive | sound_flags::looping); + } + else + { + m_rainsound->stop(); + } + } + + if (dsbHasler) + { + if (fTachoCount >= 3.f) + { + auto const soundfrequency{(true == dsbHasler->is_combined() ? fTachoVelocity * 0.01 : dsbHasler->m_frequencyoffset + dsbHasler->m_frequencyfactor)}; + dsbHasler->pitch(static_cast(soundfrequency)); + dsbHasler->gain(dsbHasler->m_amplitudeoffset + dsbHasler->m_amplitudefactor); + dsbHasler->play(sound_flags::exclusive | sound_flags::looping); + } + else if (fTachoCount < 1.f) + { + dsbHasler->stop(); + } + } + + // power-reliant sounds + if (mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable) + { + + // buzzer shp + if (mvOccupied->SecuritySystem.is_cabsignal_beeping()) + { + if (dsbBuzzerShp && false == dsbBuzzerShp->is_playing()) + { + dsbBuzzerShp->pitch(dsbBuzzerShp->m_frequencyoffset + dsbBuzzerShp->m_frequencyfactor); + dsbBuzzerShp->gain(dsbBuzzerShp->m_amplitudeoffset + dsbBuzzerShp->m_amplitudefactor); + dsbBuzzerShp->play(sound_flags::looping); + } + } + else + { + if (dsbBuzzerShp && true == dsbBuzzerShp->is_playing()) + { + dsbBuzzerShp->stop(); + } + } + + // McZapkie-141102: SHP i czuwak, TODO: sygnalizacja kabinowa + // hunter-091012: rozdzielenie alarmow + if (mvOccupied->SecuritySystem.is_beeping()) + { + if (dsbBuzzer && false == dsbBuzzer->is_playing()) + { + dsbBuzzer->pitch(dsbBuzzer->m_frequencyoffset + dsbBuzzer->m_frequencyfactor); + dsbBuzzer->gain(dsbBuzzer->m_amplitudeoffset + dsbBuzzer->m_amplitudefactor); + dsbBuzzer->play(sound_flags::looping); +#ifdef _WIN32 + Console::BitsSet(1 << 14); // ustawienie bitu 16 na PoKeys +#endif + } + } + else + { + if (dsbBuzzer && true == dsbBuzzer->is_playing()) + { + dsbBuzzer->stop(); +#ifdef _WIN32 + Console::BitsClear(1 << 14); // ustawienie bitu 16 na PoKeys +#endif + } + } + // distance meter alert + if (m_distancecounterclear) + { + auto const *owner{(DynamicObject->ctOwner != nullptr ? DynamicObject->ctOwner : DynamicObject->Mechanik)}; + if (m_distancecounter > owner->fLength) + { + // play assigned sound if the train travelled its full length since meter activation + // TBD: check all combinations of directions and active cab + m_distancecounter = -1.f; // turn off the meter after its task is done + m_distancecounterclear->pitch(m_distancecounterclear->m_frequencyoffset + m_distancecounterclear->m_frequencyfactor); + m_distancecounterclear->gain(m_distancecounterclear->m_amplitudeoffset + m_distancecounterclear->m_amplitudefactor); + m_distancecounterclear->play(sound_flags::exclusive); + } + } + } + else + { + // stop power-reliant sounds if power is cut + if (dsbBuzzer && true == dsbBuzzer->is_playing()) + { + dsbBuzzer->stop(); +#ifdef _WIN32 + Console::BitsClear(1 << 14); // ustawienie bitu 16 na PoKeys +#endif + } + + if (dsbBuzzerShp && dsbBuzzerShp->is_playing()) + { + dsbBuzzerShp->stop(); + } + + if (m_distancecounterclear) + { + m_distancecounterclear->stop(); + } + } + + update_sounds_radio(); + update_sounds_fmradio(Deltatime); +} + +void TTrain::update_sounds_resonancenoise(sound_source &Sound) const +{ + // frequency calculation + auto const normalizer{mvOccupied->Vmax * 0.01f}; + auto const soundfrequency{Sound.m_frequencyoffset + Sound.m_frequencyfactor * mvOccupied->Vel * normalizer}; + + // volume calculation + auto volume = Sound.m_amplitudeoffset + Sound.m_amplitudefactor * std::lerp(mvOccupied->Vel / (1 + mvOccupied->Vmax), 1.0, 0.5); // scale base volume between 0.5-1.0 + + if (volume > 0.05) + { + Sound.pitch(static_cast(soundfrequency)).gain(static_cast(volume)).play(sound_flags::exclusive | sound_flags::looping); + } + else + { + Sound.stop(); + } +} + +void TTrain::update_sounds_runningnoise(sound_source &Sound) +{ + // frequency calculation + auto const normalizer{(true == Sound.is_combined() ? mvOccupied->Vmax * 0.01f : 1.f)}; + auto const soundfrequency{Sound.m_frequencyoffset + Sound.m_frequencyfactor * mvOccupied->Vel * normalizer}; + + // volume calculation + auto volume = Sound.m_amplitudeoffset + Sound.m_amplitudefactor * std::lerp(mvOccupied->Vel / (1 + mvOccupied->Vmax), 1.0, + 0.5); // scale base volume between 0.5-1.0 + if (std::abs(mvOccupied->nrot) > 0.01) + { + // hamulce wzmagaja halas + auto const brakeforceratio{(std::clamp(mvOccupied->UnitBrakeForce / std::max(1.0, mvOccupied->BrakeForceR(1.0, mvOccupied->Vel) / (mvOccupied->NAxles * std::max(1, mvOccupied->NBpA))), 0.0, 1.0))}; + + volume *= 1 + 0.125 * brakeforceratio; + } + // scale volume by track quality + // TODO: track quality and/or environment factors as separate subroutine + volume *= std::lerp(0.8, 1.2, std::clamp(DynamicObject->MyTrack->iQualityFlag / 20.0, 0.0, 1.0)); + // for single sample sounds muffle the playback at low speeds + if (false == Sound.is_combined()) + { + volume *= std::lerp(0.0, 1.0, std::clamp(mvOccupied->Vel / 25.0, 0.0, 1.0)); + } + + if (volume > 0.05) + { + Sound.pitch(static_cast(soundfrequency)).gain(static_cast(volume)).play(sound_flags::exclusive | sound_flags::looping); + } + else + { + Sound.stop(); + } +} + +void TTrain::update_sounds_radio() +{ + + radio_message_played = false; + if (false == m_radiomessages.empty()) + { + // erase completed radio messages from the list + std::erase_if(m_radiomessages, [](auto const &source) { return false == source.second->is_playing(); }); + } + // adjust audibility of remaining messages based on current radio conditions + auto const radioenabled{mvOccupied->RadioPowered()}; + for (auto const &[messagechannel, messagesound] : m_radiomessages) + { + auto const volume{true == radioenabled && Dynamic()->Mechanik != nullptr && messagechannel == RadioChannel() ? m_radiovolume : 0.0}; + messagesound->gain(static_cast(volume)); + radio_message_played |= true == radioenabled && Dynamic()->Mechanik != nullptr && messagechannel == RadioChannel(); + } + // radiostop + if (m_radiostop) + { + if (true == radioenabled && true == mvOccupied->RadioStopFlag) + { + m_radiostop->play(sound_flags::exclusive | sound_flags::looping); + radio_message_played |= true; + } + else + { + m_radiostop->stop(); + } + } + if (radio_message_played) + { + btLampkaRadioMessage.gain(m_radiovolume); + } +} + +// operates the broadcast radio receiver +void TTrain::update_sounds_fmradio(double const Deltatime) +{ + // NOTE: there's a single receiver in the simulation, it plays in the cab occupied by the user + if (simulation::Train != this || false == m_fmradiopresent || false == Global.fmradio_enabled) + { + return; + } + auto &fmradio{audio::renderer.fmradio()}; + auto const bandwidth{audio::EU07_FMRADIO_BANDEND - audio::EU07_FMRADIO_BANDSTART}; + if (false == m_fmradiotuned) + { + // initially the receiver is tuned to the first station on the list + m_fmradiodial = 100.f * (fmradio.default_frequency() - audio::EU07_FMRADIO_BANDSTART) / bandwidth; + m_fmradiotuned = true; + } + // knobs + if (m_fmradiovolumechange != 0) + { + m_fmradiovolume = std::clamp(m_fmradiovolume + m_fmradiovolumechange * 0.5f * static_cast(Deltatime), 0.f, 1.f); + if (false == m_controlmapper.contains("fmradio_sw:")) + { + // receivers without dedicated switch are switched with the volume knob + m_fmradiopower = m_fmradiovolume > 0.f; + } + } + if (m_fmradiotunechange != 0) + { + // the knob moves slowly at first to allow fine tuning, then speeds up + m_fmradiotunetime += static_cast(Deltatime); + auto const tunerate{std::lerp(0.15f, 2.5f, std::clamp(m_fmradiotunetime * 0.5f, 0.f, 1.f))}; // MHz per second + m_fmradiodial = std::clamp(m_fmradiodial + 100.f * m_fmradiotunechange * tunerate * static_cast(Deltatime) / bandwidth, 0.f, 100.f); + } + else + { + m_fmradiotunetime = 0.f; + } + + fmradio.type(m_fmradiotype); + fmradio.tune(audio::EU07_FMRADIO_BANDSTART + m_fmradiodial * 0.01f * bandwidth); + fmradio.volume(m_fmradiovolume); + fmradio.placement(m_fmradiosound.location(), m_fmradiosound.soundproofing_factor(), m_fmradiosound.range()); + // NOTE: the receiver runs on batteries of its own, so it doesn't care about the state of the vehicle + fmradio.power(m_fmradiopower); +} diff --git a/vehicle/cab/train.cpp b/vehicle/cab/train.cpp new file mode 100644 index 000000000..3c1f86b62 --- /dev/null +++ b/vehicle/cab/train.cpp @@ -0,0 +1,944 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the train the user drives: construction, its state, taking a vehicle, the trains of the scenery + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/mover.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +std::vector const TTrain::fPress_labels = { + + "ch1: ", "ch2: ", "ch3: ", "ch4: ", "ch5: ", "ch6: ", "ch7: ", "ch8: ", "ch9: ", "ch0: "}; + +TTrain::TTrain() +{ + + // McZapkie-240302 - przyda sie do tachometru + + // asMessage=""; + DynamicSet(nullptr); // ustawia wszystkie mv* + //----- + + // + for (int i = 0; i < 8; i++) + { + bMains[i] = false; + fCntVol[i] = 0.0f; + bPants[i][0] = false; + bPants[i][1] = false; + bFuse[i] = false; + bBatt[i] = false; + bConv[i] = false; + bComp[i][0] = false; + bComp[i][1] = false; + // bComp[ i ][ 2 ] = false; + // bComp[ i ][ 3 ] = false; + bHeat[i] = false; + } + bCompressors.clear(); + for (int i = 0; i < 9; ++i) + for (int j = 0; j < 10; ++j) + { + fEIMParams[i][j] = 0.0; + fDieselParams[i][j] = 0.0; + } + + for (int i = 0; i < 20; ++i) + { + for (auto &press : fPress[i]) + press = 0.0; + bBrakes[i][0] = false; + bBrakes[i][1] = false; + } +} + +TTrain::~TTrain() = default; + +bool TTrain::Init(TDynamicObject *NewDynamicObject, bool e3d) +{ // powiązanie ręcznego sterowania kabiną z pojazdem + if (NewDynamicObject->Mechanik == nullptr) + { + /* + ErrorLog( "Bad config: can't take control of inactive vehicle \"" + NewDynamicObject->asName + "\"" ); + return false; + */ + auto const activecab{(NewDynamicObject->MoverParameters->CabOccupied > 0 ? "1" : NewDynamicObject->MoverParameters->CabOccupied < 0 ? "2" : "p")}; + NewDynamicObject->create_controller(activecab, NewDynamicObject->ctOwner != nullptr); + } + + DynamicSet(NewDynamicObject); + if (!e3d && DynamicObject->Mechanik == nullptr) + return false; + + DynamicObject->MechInside = true; + + fMainRelayTimer = 0; // Hunter, do k...y nędzy, ustawiaj wartości początkowe zmiennych! + + iCabn = mvOccupied->CabOccupied > 0 ? 1 : mvOccupied->CabOccupied < 0 ? 2 : 0; + + { + Global.CurrentMaxTextureSize = Global.iMaxCabTextureSize; + + auto const filename{mvOccupied->TypeName + ".mmd"}; + LoadMMediaFile(filename); + InitializeCab(mvOccupied->CabOccupied, filename); + + Global.CurrentMaxTextureSize = Global.iMaxTextureSize; + + if (DynamicObject->Controller == Humandriver) + { + // McZapkie-030303: mozliwosc wyswietlania kabiny, w przyszlosci dac opcje w mmd + DynamicObject->bDisplayCab = true; + } + } + + // Ra: taka proteza - przesłanie kierunku do członów connected + /* + if (mvControlled->DirActive > 0) + { // było do przodu + mvControlled->DirectionBackward(); + mvControlled->DirectionForward(); + } + else if (mvControlled->DirActive < 0) + { + mvControlled->DirectionForward(); + mvControlled->DirectionBackward(); + } + */ + if (false == DynamicObject->Mechanik->AIControllFlag) + { + DynamicObject->Mechanik->sync_consist_reversers(); + } + + return true; +} + +std::shared_ptr TTrain::GetTrainState(dictionary_source const &Extraparameters) +{ + + if (mvOccupied == nullptr || mvControlled == nullptr) + { + return nullptr; + } + + auto dict = std::make_shared(Extraparameters); + if (dict == nullptr) + { + return nullptr; + } + + dict->insert("name", DynamicObject->asName); + dict->insert("cab", mvOccupied->CabOccupied); + dict->insert("cabactive", mvOccupied->CabActive); + dict->insert("master", mvOccupied->CabMaster); + // basic systems state data + dict->insert("battery", mvOccupied->Power24vIsAvailable); + dict->insert("linebreaker", mvControlled->Mains); + dict->insert("main_init", mvControlled->MainsInitTimeCountdown < mvControlled->MainsInitTime && mvControlled->MainsInitTimeCountdown > 0.0); + dict->insert("main_ready", false == mvControlled->Mains && fHVoltage > 0.0 && mvControlled->MainsInitTimeCountdown <= 0.0); + dict->insert("converter", mvOccupied->Power110vIsAvailable); + dict->insert("converter_overload", mvControlled->ConvOvldFlag); + dict->insert("compress", mvControlled->CompressorFlag); + dict->insert("pant_compressor", mvPantographUnit->PantCompFlag); + dict->insert("lights_front", mvOccupied->iLights[end::front]); + dict->insert("lights_rear", mvOccupied->iLights[end::rear]); + dict->insert("off_from_dimmer", mvOccupied->currentDimPosition().isOff); + dict->insert("lights_compartments", mvOccupied->CompartmentLights.is_active || mvOccupied->CompartmentLights.is_disabled); + if (Dynamic()->Mechanik) + { + auto const *controller{Dynamic()->Mechanik}; + auto const cabmodifier{cab_to_end() == end::front ? 1 : -1}; + auto const traindirection{controller->Direction() * cabmodifier}; + auto const *frontvehicle{controller->Vehicle(traindirection >= 0 ? end::front : end::rear)}; + auto const *rearvehicle{controller->Vehicle(traindirection >= 0 ? end::rear : end::front)}; + auto const frontvehicledirection{(frontvehicle->DirectionGet() == controller->Vehicle()->DirectionGet() ? 1 : -1)}; + auto const rearvehicledirection{(rearvehicle->DirectionGet() == controller->Vehicle()->DirectionGet() ? 1 : -1)}; + auto const fronttrainlights{frontvehicle->MoverParameters->iLights[frontvehicledirection * cabmodifier >= 0 ? end::front : end::rear]}; + auto const reartrainlights{rearvehicle->MoverParameters->iLights[rearvehicledirection * cabmodifier >= 0 ? end::rear : end::front]}; + dict->insert("lights_train_front", fronttrainlights); + dict->insert("lights_train_rear", reartrainlights); + } + else + { + // fallback, in the unlikely case we lose the controller + dict->insert("lights_train_front", mvOccupied->iLights[end::front]); + dict->insert("lights_train_rear", mvOccupied->iLights[end::rear]); + } + // reverser + dict->insert("direction", mvOccupied->DirActive); + // throttle + dict->insert("mainctrl_pos", mvControlled->MainCtrlPos); + dict->insert("mainctrl_pos_count", mvControlled->MainCtrlPosNo); + dict->insert("main_ctrl_actual_pos", mvControlled->MainCtrlActualPos); + dict->insert("scndctrl_pos", mvControlled->ScndCtrlPos); + dict->insert("dynamicbrake_pos", mvControlled->DynamicBrakeCtrlPos); + dict->insert("scnd_ctrl_actual_pos", mvControlled->ScndCtrlActualPos); + dict->insert("brakectrl_pos", mvControlled->fBrakeCtrlPos); + dict->insert("localbrake_pos", mvControlled->LocalBrakePosA); + dict->insert("new_speed", mvOccupied->NewSpeed); + dict->insert("speedctrl", mvOccupied->SpeedCtrlValue); + dict->insert("speedctrlpower", mvOccupied->SpeedCtrlUnit.DesiredPower); + dict->insert("speedctrlactive", mvOccupied->SpeedCtrlUnit.IsActive); + dict->insert("speedctrlstandby", mvOccupied->SpeedCtrlUnit.Standby); + // brakes + dict->insert("manual_brake", mvOccupied->ManualBrakePos > 0); + bool const bEP = mvControlled->LocHandle->GetCP() > 0.2 || fEIMParams[0][5] > 0.01; + dict->insert("dir_brake", bEP); + bool bPN{false}; + auto const &brakevalve{*mvOccupied->Hamulec}; + if (auto const &brakevalvetype{typeid(brakevalve)}; brakevalvetype == typeid(TLSt) || brakevalvetype == typeid(TEStED)) + { + + TBrake *temp_ham = mvOccupied->Hamulec.get(); + bPN = static_cast(temp_ham)->GetEDBCP() > 0.2; + } + dict->insert("indir_brake", bPN); + dict->insert("emergency_brake", mvOccupied->AlarmChainFlag); + dict->insert("brake_delay_flag", mvOccupied->BrakeDelayFlag); + dict->insert("brake_op_mode_flag", mvOccupied->BrakeOpModeFlag); + dict->insert("pipelock", mvOccupied->LockPipe); + // other controls + dict->insert("ca", mvOccupied->SecuritySystem.is_vigilance_blinking()); + dict->insert("shp", mvOccupied->SecuritySystem.is_cabsignal_blinking()); + dict->insert("distance_counter", m_distancecounter); + dict->insert("pantpress", std::abs(mvPantographUnit->PantPress)); + dict->insert("universal3", InstrumentLightActive); + for (auto idx = 0; idx < ggUniversals.size(); idx++) + { + if (idx != 3) + { + dict->insert("universal" + std::to_string(idx), ggUniversals[idx].GetValue() > 0.5); + } + } + dict->insert("radio", mvOccupied->Radio); + dict->insert("radio_fuse", mvOccupied->RadioFuse); + dict->insert("radio_channel", RadioChannel()); + dict->insert("radio_volume", m_radiovolume); + dict->insert("door_lock", mvOccupied->Doors.lock_enabled); + dict->insert("door_step", mvOccupied->Doors.step_enabled); + dict->insert("door_permit_left", mvOccupied->Doors.instances[side::left].open_permit); + dict->insert("door_permit_right", mvOccupied->Doors.instances[side::right].open_permit); + // movement data + dict->insert("velocity", std::abs(mvOccupied->Vel)); + dict->insert("tractionforce", std::abs(mvOccupied->Ft)); + dict->insert("slipping_wheels", mvOccupied->SlippingWheels); + dict->insert("sanding", mvOccupied->SandDose); + dict->insert("odometer", mvOccupied->DistCounter); // distance run in the session, km + dict->insert("odometer_total", mvOccupied->Odometer.km); // the vehicle's odometer, kept between the sessions + // electric current data + dict->insert("traction_voltage", std::abs(mvPantographUnit->PantographVoltage)); + dict->insert("voltage", std::abs(mvControlled->EngineVoltage)); + dict->insert("im", std::abs(mvControlled->Im)); + dict->insert("fuse", mvControlled->FuseFlag); + dict->insert("epfuse", mvOccupied->EpFuse); + dict->insert("power_drawn", mvOccupied->EnergyMeter.first); + dict->insert("power_returned", mvOccupied->EnergyMeter.second); + + // induction motor state data + std::array const TXTT{"fd", "fdt", "fdb", "pd", "pdt", "pdb", "itothv", "1", "2", "3"}; + std::array const TXTC{"fr", "frt", "frb", "pr", "prt", "prb", "im", "vm", "ihv", "uhv"}; + std::array const TXTD{"enrot", "nrot", "fill_des", "fill_real", "clutch_des", "clutch_real", "water_temp", "oil_press", "engine_temp", "retarder_fill"}; + std::array const TXTP{"bc", "bp", "sp", "cp", "rp", "mass", "spring"}; + char const *TXTB[2] = {"spring_active", "spring_shutoff"}; + for (int j = 0; j < 10; ++j) + dict->insert("eimp_t_" + std::string(TXTT[j]), fEIMParams[0][j]); + for (int i = 0; i < 8; ++i) + { + auto const idx{std::to_string(i + 1)}; + for (int j = 0; j < 10; ++j) + dict->insert("eimp_c" + idx + "_" + std::string(TXTC[j]), fEIMParams[i + 1][j]); + + for (int j = 0; j < 10; ++j) + dict->insert("diesel_param_" + idx + "_" + std::string(TXTD[j]), fDieselParams[i + 1][j]); + + dict->insert("eimp_c" + idx + "_ms", bMains[i]); + dict->insert("eimp_c" + idx + "_cv", fCntVol[i]); + dict->insert("eimp_c" + idx + "_fuse", bFuse[i]); + dict->insert("eimp_c" + idx + "_batt", bBatt[i]); + dict->insert("eimp_c" + idx + "_conv", bConv[i]); + dict->insert("eimp_c" + idx + "_heat", bHeat[i]); + + dict->insert("eimp_u" + idx + "_pf", bPants[i][0]); + dict->insert("eimp_u" + idx + "_pr", bPants[i][1]); + dict->insert("eimp_u" + idx + "_comp_a", bComp[i][0]); + dict->insert("eimp_u" + idx + "_comp_w", bComp[i][1]); + } + + dict->insert("compressors_no", (int)bCompressors.size()); + for (int i = 0; i < bCompressors.size(); i++) + { + auto const idx{std::to_string(i + 1)}; + dict->insert("compressors_" + idx + "_allow", std::get<0>(bCompressors[i])); + dict->insert("compressors_" + idx + "_work", std::get<1>(bCompressors[i])); + dict->insert("compressors_" + idx + "_car_no", std::get<2>(bCompressors[i])); + } + + bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; + TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? end::rear : end::front, Coupling::control); + int in = 0; + while (p && in < 8) + { + if (p->MoverParameters->eimc[eimc_p_Pmax] > 1) + { + in++; + dict->insert("eimp_c" + std::to_string(in) + "_invno", p->MoverParameters->InvertersNo); + for (int j = 0; j < p->MoverParameters->InvertersNo; j++) + { + dict->insert("eimp_c" + std::to_string(in) + "_inv" + std::to_string(j + 1) + "_act", p->MoverParameters->Inverters[j].IsActive); + dict->insert("eimp_c" + std::to_string(in) + "_inv" + std::to_string(j + 1) + "_error", p->MoverParameters->Inverters[j].Error); + dict->insert("eimp_c" + std::to_string(in) + "_inv" + std::to_string(j + 1) + "_allow", p->MoverParameters->Inverters[j].Activate); + } + } + p = kier ? p->Next(Coupling::control) : p->Prev(Coupling::control); + } + for (int i = 0; i < 20; ++i) + { + for (int j = 0; j < 7; ++j) + { + dict->insert("eimp_pn" + std::to_string(i + 1) + "_" + TXTP[j], fPress[i][j]); + } + for (int j = 0; j < 2; ++j) + { + dict->insert("brakes_" + std::to_string(i + 1) + "_" + TXTB[j], bBrakes[i][j]); + } + } + // multi-unit state data + dict->insert("car_no", iCarNo); + dict->insert("power_no", iPowerNo); + dict->insert("unit_no", iUnitNo); + + for (int i = 0; i < 20; i++) + { + auto const caridx{std::to_string(i + 1)}; + dict->insert("doors_" + caridx, bDoors[i][0]); + dict->insert("doors_l_" + caridx, bDoors[i][1]); + dict->insert("doors_r_" + caridx, bDoors[i][2]); + dict->insert("doorstep_l_" + caridx, bDoors[i][3]); + dict->insert("doorstep_r_" + caridx, bDoors[i][4]); + dict->insert("doors_no_" + caridx, iDoorNo[i]); + dict->insert("code_" + caridx, std::to_string(iUnits[i]) + cCode[i]); + dict->insert("car_name" + caridx, asCarName[i]); + dict->insert("slip_" + caridx, bSlip[i]); + } + // ai state data + auto const *vehicledriver{(DynamicObject->ctOwner != nullptr ? DynamicObject->ctOwner : DynamicObject->Mechanik)}; + + dict->insert("velocity_desired", vehicledriver->VelDesired); + dict->insert("velroad", vehicledriver->VelRoad); + dict->insert("vellimitlast", vehicledriver->VelLimitLast); + dict->insert("velsignallast", vehicledriver->VelSignalLast); + dict->insert("velsignalnext", vehicledriver->VelSignalNext); + dict->insert("velnext", vehicledriver->VelNext); + dict->insert("actualproximitydist", vehicledriver->ActualProximityDist); + // train data + vehicledriver->TrainTimetable().serialize(dict.get()); + dict->insert("train_atpassengerstop", vehicledriver->IsAtPassengerStop); + dict->insert("train_length", vehicledriver->fLength); + // world state data + dict->insert("scenario", Global.SceneryFile); + dict->insert("hours", static_cast(simulation::Time.data().wHour)); + dict->insert("minutes", static_cast(simulation::Time.data().wMinute)); + dict->insert("seconds", static_cast(simulation::Time.second())); + dict->insert("air_temperature", Global.AirTemperature); + dict->insert("light_level", Global.fLuminance - std::max(0.f, Global.Overcast - 1.f)); + + return dict; +} + +TTrain::state_t TTrain::get_state() const +{ + + return { + btLampkaSHP.GetValue(), + btLampkaCzuwaka.GetValue(), + btLampkaRadioStop.GetValue(), + btLampkaOpory.GetValue(), + btLampkaWylSzybki.GetValue(), + btLampkaPrzekRozn.GetValue(), + btLampkaNadmSil.GetValue(), + btLampkaStyczn.GetValue(), + btLampkaPoslizg.GetValue(), + btLampkaNadmPrzetw.GetValue(), + btLampkaPrzetwOff.GetValue(), + btLampkaNadmSpr.GetValue(), + btLampkaNadmWent.GetValue(), + btLampkaWysRozr.GetValue(), + btLampkaOgrzewanieSkladu.GetValue(), + static_cast(iCabn), + btHaslerBrakes.GetValue(), + btHaslerCurrent.GetValue(), + mvOccupied->SecuritySystem.is_beeping(), + btLampkaHVoltageB.GetValue(), + fTachoVelocity, + static_cast(mvOccupied->Compressor), + static_cast(mvOccupied->PipePress), + static_cast(mvOccupied->BrakePress), + static_cast(mvPantographUnit->PantPress), + fHVoltage, + {fHCurrent[mvControlled->TrainType == train_type::emu ? 0 : 1], fHCurrent[2], fHCurrent[3]}, + ggLVoltage.GetValue(), + mvOccupied->DistCounter, + static_cast(RadioChannel()), + btLampkaSpringBrakeActive.GetValue(), + btLampkaNapNastHam.GetValue(), + mvOccupied->DirActive > 0, + mvOccupied->DirActive < 0, + mvOccupied->Doors.instances[mvOccupied->CabOccupied < 0 ? side::right : side::left].open_permit, + mvOccupied->Doors.instances[mvOccupied->CabOccupied < 0 ? side::right : side::left].is_open, + mvOccupied->Doors.instances[mvOccupied->CabOccupied < 0 ? side::left : side::right].open_permit, + mvOccupied->Doors.instances[mvOccupied->CabOccupied < 0 ? side::left : side::right].is_open, + mvOccupied->Doors.step_enabled, + mvOccupied->Power24vIsAvailable, + 0, + mvOccupied->LockPipe, + btLampkaRadioMessage.GetValue(), + }; +} + +bool TTrain::is_eztoer() const +{ + + return mvControlled->TrainType == train_type::emu && mvOccupied->BrakeSubsystem == TBrakeSubSystem::ss_ESt && mvControlled->Power24vIsAvailable == true && mvControlled->EpFuse == true && + mvControlled->DirActive != 0; // od yB +} + +// mover master controller to specified position +void TTrain::set_master_controller(double const Position) +{ + + auto positionchange{std::min(static_cast(Position), mvControlled->CoupledCtrl ? mvControlled->MainCtrlPosNo + mvControlled->ScndCtrlPosNo : mvControlled->MainCtrlPosNo) - + (mvControlled->CoupledCtrl ? mvControlled->MainCtrlPos + mvControlled->ScndCtrlPos : mvControlled->MainCtrlPos)}; + while (positionchange < 0 && true == mvControlled->DecMainCtrl(1)) + { + ++positionchange; + } + while (positionchange > 0 && true == mvControlled->IncMainCtrl(1)) + { + --positionchange; + } +} + +// moves train brake lever to specified position, potentially emits switch sound if conditions are met +void TTrain::set_train_brake(double const Position) +{ + + auto const originalbrakeposition{static_cast(100.0 * mvOccupied->fBrakeCtrlPos)}; + mvOccupied->BrakeLevelSet(Position); + + if (static_cast(100.0 * mvOccupied->fBrakeCtrlPos) == originalbrakeposition) + { + return; + } + + // sound feedback if the lever movement activates one of the switches + if (true == is_eztoer() && false == ((originalbrakeposition / 100 == 0 || originalbrakeposition / 100 >= 5) && (mvOccupied->BrakeCtrlPos == 0 || mvOccupied->BrakeCtrlPos >= 5)) && dsbPneumaticSwitch) + { + dsbPneumaticSwitch->play(); + } +} + +void TTrain::zero_charging_train_brake() +{ + using enum TBrakeHandle; + + if (mvOccupied->BrakeCtrlPos == -1 && DynamicObject->Controller != AIdriver && Global.iFeedbackMode < 3 && + (mvOccupied->BrakeHandle == FVel6 || mvOccupied->BrakeHandle == MHZ_EN57 || mvOccupied->BrakeHandle == MHZ_K8P)) + { + // Odskakiwanie hamulce EP + set_train_brake(0); + } +} + +void TTrain::set_train_brake_speed(TDynamicObject *Vehicle, int const Speed) +{ + + // visual feedback + // TODO: add setting indicator to vehicle class, for external lever/indicator + if (true == Vehicle->MoverParameters->BrakeDelaySwitch(Speed) && Vehicle == DynamicObject) + { + if (ggBrakeProfileCtrl.SubModel != nullptr) + { + ggBrakeProfileCtrl.UpdateValue((mvOccupied->BrakeDelayFlag & bdelay_R) != 0 ? 2.0 : static_cast(mvOccupied->BrakeDelayFlag - 1), dsbSwitch); + } + if (ggBrakeProfileG.SubModel != nullptr) + { + ggBrakeProfileG.UpdateValue(mvOccupied->BrakeDelayFlag == bdelay_G ? 1.0 : 0.0, dsbSwitch); + } + if (ggBrakeProfileR.SubModel != nullptr) + { + ggBrakeProfileR.UpdateValue((mvOccupied->BrakeDelayFlag & bdelay_R) != 0 ? 1.0 : 0.0, dsbSwitch); + } + } +} + +void TTrain::set_paired_open_motor_connectors_button(bool const State) +{ + + if (mvControlled->TrainType == train_type::et41 || mvControlled->TrainType == train_type::et42) + { + // crude implementation of the button affecting entire unit for multi-unit engines + // TODO: rework it into part of standard command propagation system + if (mvControlled->Couplers[end::front].Connected != nullptr && true == mvControlled->Couplers[end::front].CouplingFlag.HasAll(Coupling::permanent)) + { + mvControlled->Couplers[end::front].Connected->StLinSwitchOff = State; + } + if (mvControlled->Couplers[end::rear].Connected != nullptr && true == mvControlled->Couplers[end::rear].CouplingFlag.HasAll(Coupling::permanent)) + { + mvControlled->Couplers[end::rear].Connected->StLinSwitchOff = State; + } + } +} + +// locates nearest vehicle belonging to the consist +TDynamicObject *TTrain::find_nearest_consist_vehicle(bool freefly, glm::vec3 pos) const +{ + if (!freefly) + return DynamicObject; + + auto couplerindex{-2}; // scan for vehicle, not any specific coupler + auto *vehicle{DynamicObject->ABuScanNearestObject(pos, DynamicObject->GetTrack(), 1, 1500, couplerindex)}; + if (vehicle == nullptr) + vehicle = DynamicObject->ABuScanNearestObject(pos, DynamicObject->GetTrack(), -1, 1500, couplerindex); + // TBD, TODO: perform owner test for the located vehicle + return vehicle; +} + +// cab movement update, fixed step part +void TTrain::UpdateCab() +{ + + // Ra: przesiadka, jeśli AI zmieniło kabinę (a człon?)... + if (DynamicObject->Mechanik // może nie być? + && DynamicObject->Mechanik->AIControllFlag && iCabn != ( // numer kabiny (-1: kabina B) + mvOccupied->CabOccupied == -1 ? 2 : mvOccupied->CabOccupied)) + { + + InitializeCab(mvOccupied->CabOccupied, mvOccupied->TypeName + ".mmd"); + } + iCabn = mvOccupied->CabOccupied == -1 ? 2 : mvOccupied->CabOccupied; +} + +void TTrain::add_distance(double const Distance) +{ + + auto const meterenabled{m_distancecounter >= 0 && (mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable)}; + + if (true == meterenabled) + { + m_distancecounter += static_cast(Distance * Occupied()->CabOccupied); + } + else + { + m_distancecounter = -1.f; + } +} + +bool TTrain::CabChange(int iDirection) +{ // McZapkie-090902: zmiana kabiny 1->0->2 i z powrotem + if (DynamicObject->Mechanik == nullptr || true == DynamicObject->Mechanik->AIControllFlag) + { + // jeśli prowadzi AI albo jest w innym członie + // jak AI prowadzi, to nie można mu mieszać + if (std::abs(mvOccupied->CabOccupied + iDirection) > 1) + return false; // ewentualna zmiana pojazdu + mvOccupied->CabOccupied += iDirection; + } + else + { // jeśli pojazd prowadzony ręcznie albo wcale (wagon) + mvOccupied->CabDeactivisationAuto(); + if (mvOccupied->ChangeCab(iDirection) && InitializeCab(mvOccupied->CabOccupied, mvOccupied->TypeName + ".mmd")) + { + // zmiana kabiny w ramach tego samego pojazdu + mvOccupied->CabActivisationAuto(); // załączenie rozrządu (wirtualne kabiny) + DynamicObject->Mechanik->DirectionChange(); + return true; // udało się zmienić kabinę + } + // aktywizacja poprzedniej, bo jeszcze nie wiadomo, czy jakiś pojazd jest + mvOccupied->CabActivisationAuto(); + } + return false; // ewentualna zmiana pojazdu +} + +void TTrain::DynamicSet(TDynamicObject *d) +{ // taka proteza: chcę podłączyć + // kabinę EN57 bezpośrednio z + // silnikowym, aby nie robić tego + // przez ukrotnienie + // drugi silnikowy i tak musi być ukrotniony, podobnie jak kolejna jednostka + // problem się robi ze światłami, które będą zapalane w silnikowym, ale muszą + // świecić się w rozrządczych + // dla EZT światła czołowe będą "zapalane w silnikowym", ale widziane z + // rozrządczych + // również wczytywanie MMD powinno dotyczyć aktualnego członu + // problematyczna może być kwestia wybranej kabiny (w silnikowym...) + // jeśli silnikowy będzie zapięty odwrotnie (tzn. -1), to i tak powinno + // jeździć dobrze + // również hamowanie wykonuje się zaworem w członie, a nie w silnikowym... + DynamicObject = d; // jedyne miejsce zmiany + mvControlled = d ? DynamicObject->MoverParameters : nullptr; // albo silnikowy w EZT + mvOccupied = mvControlled; + + if (DynamicObject == nullptr) + { + return; + } + + mvControlled = DynamicObject->FindPowered()->MoverParameters; + mvSecond = nullptr; // gdyby się nic nie znalazło + if (mvOccupied->Power > 1.0) // dwuczłonowe lub ukrotnienia, żeby nie szukać każdorazowo + { + if (mvOccupied->Couplers[1].Connected != nullptr && mvOccupied->Couplers[1].AllowedFlag.HasAny(Coupling::control)) + { // gdy jest człon od sprzęgu 1, a sprzęg łączony + // warsztatowo (powiedzmy) + if (mvOccupied->Couplers[1].Connected->Power > 1.0) // ten drugi ma moc + mvSecond = mvOccupied->Couplers[1].Connected; // wskaźnik na drugiego + } + else if (mvOccupied->Couplers[0].Connected != nullptr && mvOccupied->Couplers[0].AllowedFlag.HasAny(Coupling::control)) + { // gdy jest człon od sprzęgu 0, a sprzęg łączony + // warsztatowo (powiedzmy) + if (mvOccupied->Couplers[0].Connected->Power > 1.0) // ale ten drugi ma moc + mvSecond = mvOccupied->Couplers[0].Connected; // wskaźnik na drugiego + } + } + // cache nearest unit equipped with pantographs + { + auto *lookup{DynamicObject->FindPantographCarrier()}; + // HACK: set pointer to existing vehicle to avoid error checking all over the place + mvPantographUnit = lookup != nullptr ? lookup->MoverParameters : mvControlled; + } +}; + +void TTrain::MoveToVehicle(TDynamicObject *target) +{ + // > Ra: to nie może być tak robione, to zbytnia proteza jest + // indeed, too much hacks... + // TODO: cleanup + TTrain *target_train = simulation::Trains.find(target->name()); + if (target_train) + { + // let's try to destroy this TTrain and move to already existing one + + if (!Dynamic()->Mechanik || !Dynamic()->Mechanik->AIControllFlag) + { + // tylko jeśli ręcznie prowadzony + // jeśli prowadzi AI, to mu nie robimy dywersji! + Occupied()->CabDeactivisation(); + Occupied()->CabOccupied = 0; + Occupied()->BrakeLevelSet(Occupied()->Handle->GetPos(bh_NP)); // rozwala sterowanie hamulcem GF 04-2016 + Occupied()->MainCtrlPos = Occupied()->MainCtrlNoPowerPos(); + Occupied()->ScndCtrlPos = 0; + Dynamic()->MechInside = false; + Dynamic()->Controller = AIdriver; + + Dynamic()->bDisplayCab = false; + Dynamic()->ABuSetModelShake({}); + + if (Dynamic()->Mechanik) + Dynamic()->Mechanik->MoveTo(target); + + target_train->Occupied()->LimPipePress = target_train->Occupied()->PipePress; + target_train->Occupied()->CabActivisationAuto(true); // załączenie rozrządu (wirtualne kabiny) + target_train->Dynamic()->MechInside = true; + if (target_train->Dynamic()->Mechanik) + { + target_train->Dynamic()->Controller = target_train->Dynamic()->Mechanik->AIControllFlag; + target_train->Dynamic()->Mechanik->DirectionChange(); + } + else + { + target_train->Dynamic()->Controller = Humandriver; + } + } + else + { + target_train->Dynamic()->bDisplayCab = false; + target_train->Dynamic()->ABuSetModelShake({}); + } + + target_train->Dynamic()->ABuSetModelShake({}); // zerowanie przesunięcia przed powrotem? + + // potentially move player + if (simulation::Train == this) + { + simulation::Train = target_train; + // our local driver may potentially be in external view mode, in which case we shouldn't activate cab visualization + target_train->Dynamic()->bDisplayCab |= !FreeFlyModeFlag; + } + + // delete this TTrain + pending_delete = true; + } + else + { + // move this TTrain to other dynamic + + // remove TTrain from global list, we're going to change dynamic anyway + simulation::Trains.detach(Dynamic()->name()); + + if (!Dynamic()->Mechanik || !Dynamic()->Mechanik->AIControllFlag) + { + // tylko jeśli ręcznie prowadzony + // jeśli prowadzi AI, to mu nie robimy dywersji! + + Occupied()->CabDeactivisation(); + Occupied()->CabOccupied = 0; + Occupied()->BrakeLevelSet(Occupied()->Handle->GetPos(bh_NP)); // rozwala sterowanie hamulcem GF 04-2016 + Occupied()->MainCtrlPos = Occupied()->MainCtrlNoPowerPos(); + Occupied()->ScndCtrlPos = 0; + Dynamic()->MechInside = false; + Dynamic()->Controller = AIdriver; + + Dynamic()->bDisplayCab = false; + Dynamic()->ABuSetModelShake({}); + + if (Dynamic()->Mechanik) + Dynamic()->Mechanik->MoveTo(target); + + DynamicSet(target); + + Dynamic()->MechInside = true; + if (Dynamic()->Mechanik) + { + Dynamic()->Controller = Dynamic()->Mechanik->AIControllFlag; + Dynamic()->Mechanik->DirectionChange(); + } + else + { + Dynamic()->Controller = Humandriver; + } + + Occupied()->LimPipePress = Occupied()->PipePress; + Occupied()->CabActivisationAuto(true); // załączenie rozrządu (wirtualne kabiny) + } + else + { + Dynamic()->bDisplayCab = false; + Dynamic()->ABuSetModelShake({}); + + DynamicSet(target); + } + + { + auto const filename{Occupied()->TypeName + ".mmd"}; + LoadMMediaFile(filename); + InitializeCab(Occupied()->CabActive, filename); + } + + Dynamic()->ABuSetModelShake({}); // zerowanie przesunięcia przed powrotem? + + if (simulation::Train == this) + { + // our local driver may potentially be in external view mode, in which case we shouldn't activate cab visualization + Dynamic()->bDisplayCab |= !FreeFlyModeFlag; + } + + // add it back with updated dynamic name + simulation::Trains.insert(this); + } +} + +// checks whether specified point is within boundaries of the active cab +bool TTrain::point_inside(glm::dvec3 const Point) const +{ + + return Point.x >= Cabine[iCabn].CabPos1.x && Point.x <= Cabine[iCabn].CabPos2.x && Point.y >= Cabine[iCabn].CabPos1.y + 0.5 && Point.y <= Cabine[iCabn].CabPos2.y + 1.8 && + Point.z >= Cabine[iCabn].CabPos1.z && Point.z <= Cabine[iCabn].CabPos2.z; +} + +glm::dvec3 TTrain::clamp_inside(glm::dvec3 const &Point) const +{ + + if (DebugModeFlag) + { + return Point; + } + + // the bounds come from the .mmd as written, and some cabs have them reversed (the B cars of SA134 and 21xM, + // ET40, 754...); std::clamp is undefined for those and on MSVC makes the camera jump between the two bounds + // every frame, as its result is fed back here. safe_clamp keeps the camera on the upper bound, as 26.05 did + return {safe_clamp(Point.x, (double)Cabine[iCabn].CabPos1.x, (double)Cabine[iCabn].CabPos2.x), safe_clamp(Point.y, (double)Cabine[iCabn].CabPos1.y + 0.5, (double)Cabine[iCabn].CabPos2.y + 1.8), + safe_clamp(Point.z, (double)Cabine[iCabn].CabPos1.z, (double)Cabine[iCabn].CabPos2.z)}; +} + +void TTrain::radio_message(sound_source *Message, int const Channel) +{ + + if (auto const soundrange{Message->range()}; soundrange > 0 && glm::length2(Message->location() - glm::dvec3{DynamicObject->GetPosition()}) > sq(soundrange)) + { + // skip message playback if the receiver is outside of the emitter's range + return; + } + // NOTE: we initiate playback of all sounds in range, in case the user switches on the radio or tunes to the right channel mid-play + m_radiomessages.emplace_back(Channel, std::make_shared(m_radiosound)); + // assign sound to the template and play it + auto &message = *m_radiomessages.back().second.get(); + auto const radioenabled{mvOccupied->RadioPowered()}; + auto const volume{true == radioenabled && Dynamic()->Mechanik != nullptr && Channel == RadioChannel() ? 1.0 : 0.0}; + message.copy_sounds(*Message).gain(static_cast(volume)).play(); +} + +uint16_t TTrain::id() +{ + if (vid == 0) + { + vid = ++simulation::prev_train_id; + WriteLog("net: assigning id " + std::to_string(vid) + " to vehicle " + Dynamic()->name(), logtype::net); + } + return vid; +} +namespace +{ + +// updates trains in range [Start, End) +void update_trains(std::deque const &Trains, std::size_t const Start, std::size_t const End, double const Dt) +{ + for (std::size_t j = Start; j < End; ++j) + { + if (Trains[j]) + Trains[j]->Update(Dt); + } +} + +} // namespace + +void train_table::updateAsync(double dt) +{ + const int threads = std::max(1, Global.trainThreads); + const size_t total = m_items.size(); + const size_t chunkSize = (total + threads - 1) / threads; + auto const instance{TSubModel::iInstance}; + + std::vector workers; + std::vector> results; // przekazują wyjątki z wątków do głównego wątku + workers.reserve(threads); + results.reserve(threads); + + for (int i = 0; i < threads; ++i) + { + const size_t start = i * chunkSize; + const size_t end = std::min(start + chunkSize, total); + + if (start >= end) + break; // brak więcej danych + + // the instance whose animations the gauges set (TSubModel::iInstance, per thread since the walks of the vulkan renderer went on + // several threads) is the one the main thread set for the driven vehicle + std::packaged_task task([this, start, end, dt, instance]() { + TSubModel::iInstance = instance; + update_trains(m_items, start, end, dt); + }); + results.emplace_back(task.get_future()); + workers.emplace_back(std::move(task)); + } + + // Poczekaj aż wszystkie wątki skończą + for (auto &worker : workers) + worker.join(); + + for (auto &result : results) + result.get(); + + // Teraz kasowanie (tylko w głównym wątku) + for (TTrain *train : m_items) + { + if (!train) + continue; + + if (train->pending_delete) + { + purge(train->Dynamic()->name()); + if (simulation::Train == train) + simulation::Train = nullptr; + } + else if (simulation::Train != train && Global.network_servers.empty() && !Global.network_client) + { + purge(train->Dynamic()->name()); + } + } +} + +void train_table::update(double dt) +{ + for (TTrain *train : m_items) + { + if (!train) + continue; + + train->Update(dt); + + if (train->pending_delete) + { + purge(train->Dynamic()->name()); + if (simulation::Train == train) + simulation::Train = nullptr; + } + // for single-player destroy non-player trains + else if (simulation::Train != train && Global.network_servers.empty() && !Global.network_client) + { + purge(train->Dynamic()->name()); + } + } +} + +TTrain *train_table::find_id(std::uint16_t const Id) const +{ + + if (Id == 0) + { + return nullptr; + } + + for (TTrain *train : m_items) + { + if (!train) + { + continue; + } + if (train->id() == Id) + { + return train; + } + } + return nullptr; +} diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp new file mode 100644 index 000000000..a68733c00 --- /dev/null +++ b/vehicle/cab/update.cpp @@ -0,0 +1,1461 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the update of the cab in a step of the simulation + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/mover.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +bool TTrain::Update(double const Deltatime) +{ + // train state update + // line breaker: + if (m_linebreakerstate == linebreaker::state::open && true == mvControlled->Mains) + { + // crude way to sync state of the linebreaker with ai-issued commands + m_linebreakerstate = linebreaker::state::closed; + } + if (m_linebreakerstate == linebreaker::state::closed && false == (mvControlled->Mains || mvControlled->dizel_startup)) + { + // crude way to catch cases where the main was knocked out + // because the state of the line breaker isn't changed to match, we need to do it here manually + m_linebreakerstate = linebreaker::state::open; + } + if (is_hold_coil_lever(ggMainOffButton) && hold_coil_lever::cuts_off(ggMainOffButton.GetDesiredValue())) + { + if (true == mvControlled->Mains) + { + // the line breaker was closed with the hold coil lever off, by the AI or through the control cable: + // put the lever back on to match, like the line breaker state above + ggMainOffButton.UpdateValue(0.0); + } + else if (m_linebreakerstate == linebreaker::state::closing) + { + // the hold coil was cut off while the closing button was held, the line breaker won't close on its release + m_linebreakerstate = linebreaker::state::open; + } + } + + if ((ggMainButton.SubModel != nullptr && ggMainButton.GetDesiredValue() > 0.95) || + ggMainOnButton.SubModel != nullptr && ggMainOnButton.GetDesiredValue() > 0.95 || + ggIgnitionKey.GetDesiredValue() > 0.95) + { // HACK: fallback + // keep track of period the line breaker button is held down, to determine when/if circuit closes + if (mvControlled->MainSwitchCheck()) + { + fMainRelayTimer += static_cast(Deltatime); + } + } + else + { + // button isn't down, reset the timer + fMainRelayTimer = 0.0f; + } + if (ggMainOffButton.GetDesiredValue() > 0.95) + { + // if the button disconnecting the line breaker is down prevent the timer from accumulating + fMainRelayTimer = 0.0f; + } + if (m_linebreakerstate == linebreaker::state::open && fMainRelayTimer > mvControlled->InitialCtrlDelay) + { + // wlaczanie WSa z opoznieniem + // mark the line breaker as ready to close; for electric series vehicles with impulse switch the setup is completed on button release + m_linebreakerstate = linebreaker::state::closing; + } + // for diesels and/or vehicles with toggle switch setup we complete the engine start here + // TODO: make it a test for main_on_bt of type push_delayed instead + if (m_linebreakerstate == linebreaker::state::closing && (ggMainOnButton.SubModel == nullptr || mvControlled->EngineType != TEngineType::ElectricSeriesMotor)) + { + // try to finalize state change of the line breaker, set the state based on the outcome + m_linebreakerstate = mvControlled->MainSwitch(true, mvControlled->MainSwitchRange()) ? linebreaker::state::closed : linebreaker::state::open; + } + // the switches of the other vehicles in multiple + update_remote_linebreakers(Deltatime); + // door permits + for (auto idx = 0; idx < 2; ++idx) + { + auto &doorpermittimer{m_doorpermittimers[idx]}; + if (doorpermittimer < 0.f) + { + continue; + } + doorpermittimer -= static_cast(Deltatime); + if (doorpermittimer < 0.f) + { + mvOccupied->OperateDoors(static_cast(idx), true); + } + } + + // train measurement timer + if (trainLenghtMeasureTimer >= 0.f) + { + trainLenghtMeasureTimer -= static_cast(Deltatime); + if (trainLenghtMeasureTimer < 0.f) + trainLenghtMeasureTimer = -1.f; + } + + // battery timer + if (fBatteryTimer >= 0.f) + { + fBatteryTimer -= static_cast(Deltatime); + if (fBatteryTimer < 0.f) + fBatteryTimer = -1.f; + } + + // helper variables + if (DynamicObject->Mechanik != nullptr) + { + m_doors = DynamicObject->Mechanik->IsAnyDoorOpen[side::right] || DynamicObject->Mechanik->IsAnyDoorOpen[side::left]; + m_doorpermits = DynamicObject->Mechanik->IsAnyDoorPermitActive[side::right] || DynamicObject->Mechanik->IsAnyDoorPermitActive[side::left]; + m_doorspermitleft = mvOccupied->Doors.instances[cab_to_end() == end::front ? side::left : side::right].open_permit && + (simulation::Time.data().wSecond % 2 < 1 || mvOccupied->DoorsPermitLightBlinking < 1 || + mvOccupied->DoorsPermitLightBlinking < 2 && DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == end::front ? side::left : side::right] || + (mvOccupied->DoorsPermitLightBlinking < 3 && DynamicObject->Mechanik->IsAnyDoorOnlyOpen[cab_to_end() == end::front ? side::left : side::right])); + m_doorspermitright = mvOccupied->Doors.instances[cab_to_end() == end::front ? side::right : side::left].open_permit && + (simulation::Time.data().wSecond % 2 < 1 || mvOccupied->DoorsPermitLightBlinking < 1 || + mvOccupied->DoorsPermitLightBlinking < 2 && DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == end::front ? side::right : side::left] || + (mvOccupied->DoorsPermitLightBlinking < 3 && DynamicObject->Mechanik->IsAnyDoorOnlyOpen[cab_to_end() == end::front ? side::right : side::left])); + } + m_dirforward = mvControlled->DirActive > 0; + m_dirneutral = mvControlled->DirActive == 0; + m_dirbackward = mvControlled->DirActive < 0; + + // check for received user commands + // NOTE: this is a temporary arrangement, for the transition period from old command setup to the new one + // eventually commands are going to be retrieved directly by the vehicle, filtered through active control stand + // and ultimately executed, provided the stand allows it. + command_data commanddata; + while (simulation::Commands.pop(commanddata, static_cast(command_target::vehicle) | id())) + { + simulation::Blackbox.command(DynamicObject, commanddata.command, commanddata.action, commanddata.param1, commanddata.param2); + + auto lookup = m_commandhandlers.find(commanddata.command); + if (lookup != m_commandhandlers.end()) + { + // debug data + if (commanddata.action == GLFW_PRESS) + { + WriteLog(mvOccupied->Name + " received command: [" + simulation::Commands_descriptions[static_cast(commanddata.command)].name + "]"); + } + // pass the command to the assigned handler + lookup->second(this, commanddata); + } + } + + UpdateCab(); + + // nie blokujemy AI + if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag && (mvOccupied->TrainType == train_type::et40 || mvOccupied->TrainType == train_type::ep05 || mvOccupied->HasCamshaft)) + { + // dla ET40 i EU05 automatyczne cofanie nastawnika - i tak nie będzie to działać dobrze... + // TODO: use deltatime to stabilize speed + /* + if( false == ( + ( input::command == user_command::mastercontrollerset ) + || ( input::command == user_command::mastercontrollerincrease ) + || ( input::command == user_command::mastercontrollerdecrease ) ) ) { + */ + if (false == (m_mastercontrollerinuse || Global.ctrlState)) + { + m_mastercontrollerreturndelay -= static_cast(Deltatime); + if (m_mastercontrollerreturndelay < 0.f) + { + m_mastercontrollerreturndelay = EU07_CONTROLLER_BASERETURNDELAY; + if (mvOccupied->MainCtrlPos > mvOccupied->MainCtrlActualPos) + { + mvOccupied->DecMainCtrl(1); + } + else if (mvOccupied->MainCtrlPos < mvOccupied->MainCtrlActualPos) + { + // Ra 15-01: a to nie miało być tylko cofanie? + mvOccupied->IncMainCtrl(1); + } + } + } + } + + // McZapkie: predkosc wyswietlana na tachometrze brana jest z obrotow kol + auto const maxtacho{3.0}; + + double maxSpeed = mvControlled->Vmax * 1.05; // zachowanie starej logiki jak nie ma definicji max tarczki + if (mvOccupied->maxTachoSpeed != 0) + { + maxSpeed = mvOccupied->maxTachoSpeed; + } + fTachoVelocity = static_cast(std::min(std::abs(11.31 * mvControlled->WheelDiameter * mvControlled->nrot), maxSpeed)); + { // skacze osobna zmienna + float ff = simulation::Time.data().wSecond; // skacze co sekunde - pol sekundy + // pomiar, pol sekundy ustawienie + if (ff != fTachoTimer) // jesli w tej sekundzie nie zmienial + { + if (fTachoVelocity >= 5) // jedzie + fTachoVelocityJump = static_cast(fTachoVelocity + (2.0 - LocalRandom(3) + LocalRandom(3)) * 0.5); + else if (fTachoVelocity < 5 && fTachoVelocity > 1) + fTachoVelocityJump = static_cast(Random(0, 4)); // tu ma sie bujac jak wariat i zatrzymac na jakiejs predkosci + // fTachoVelocityJump = 0; // stoi + fTachoTimer = ff; // juz zmienil + } + } + if (fTachoVelocity > 1) // McZapkie-270503: podkrecanie tachometru + { + // szybciej zacznij stukac + fTachoCount = static_cast(std::min(maxtacho, fTachoCount + Deltatime * 3)); + } + else if (fTachoCount > 0) + { + // schodz powoli - niektore haslery to ze 4 sekundy potrafia stukac + fTachoCount = static_cast(std::max(0.0, fTachoCount - Deltatime * 0.66)); + } + + // Ra 2014-09: napięcia i prądy muszą być ustalone najpierw, bo wysyłane są ewentualnie na PoKeys + if (mvControlled->EngineType != TEngineType::DieselElectric && mvControlled->EngineType != TEngineType::ElectricInductionMotor) + { // Ra 2014-09: czy taki rozdzia? ma sens? + fHVoltage = static_cast(std::max(mvControlled->PantographVoltage, + mvControlled->GetTrainsetHighVoltage())); // Winger czy to nie jest zle? + } + // *mvControlled->Mains); + else + { + fHVoltage = static_cast(mvControlled->EngineVoltage); + } + if (ShowNextCurrent) + { // jeśli pokazywać drugi człon + if (mvSecond) + { // o ile jest ten drugi + fHCurrent[0] = static_cast(mvSecond->ShowCurrent(0) * 1.05); + fHCurrent[1] = static_cast(mvSecond->ShowCurrent(1) * 1.05); + fHCurrent[2] = static_cast(mvSecond->ShowCurrent(2) * 1.05); + fHCurrent[3] = static_cast(mvSecond->ShowCurrent(3) * 1.05); + } + else + { + fHCurrent[0] = 0.0; // gdy nie ma człona + fHCurrent[1] = 0.0; + fHCurrent[2] = 0.0; + fHCurrent[3] = 0.0; + } + } + else + { // normalne pokazywanie + fHCurrent[0] = static_cast(mvControlled->ShowCurrent(0)); + fHCurrent[1] = static_cast(mvControlled->ShowCurrent(1)); + fHCurrent[2] = static_cast(mvControlled->ShowCurrent(2)); + fHCurrent[3] = static_cast(mvControlled->ShowCurrent(3)); + } + + bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; + TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? end::rear : end::front, Coupling::control); + int in = 0; + fEIMParams[0][6] = 0; + iCarNo = 0; + iPowerNo = 0; + iUnitNo = 1; + + for (int i = 0; i < 8; i++) + { + bMains[i] = false; + fCntVol[i] = 0.0f; + bPants[i][0] = false; + bPants[i][1] = false; + bFuse[i] = false; + bBatt[i] = false; + bConv[i] = false; + bComp[i][0] = false; + bComp[i][1] = false; + // bComp[i][2] = false; + // bComp[i][3] = false; + bHeat[i] = false; + } + bCompressors.clear(); + for (int i = 0; i < 20; i++) + { + if (p) + { + fPress[i][0] = static_cast(p->MoverParameters->BrakePress); + fPress[i][1] = static_cast(p->MoverParameters->PipePress); + fPress[i][2] = static_cast(p->MoverParameters->ScndPipePress); + fPress[i][3] = static_cast(p->MoverParameters->CntrlPipePress); + fPress[i][4] = static_cast(p->MoverParameters->Hamulec->GetBRP()); + fPress[i][5] = static_cast((p->MoverParameters->TotalMass - p->MoverParameters->Mred) * 0.001); + fPress[i][6] = static_cast(p->MoverParameters->SpringBrake.SBP); + bBrakes[i][0] = p->MoverParameters->SpringBrake.IsActive; + bBrakes[i][1] = p->MoverParameters->SpringBrake.ShuttOff; + bDoors[i][1] = p->MoverParameters->Doors.instances[side::left].position > 0.f; + bDoors[i][2] = p->MoverParameters->Doors.instances[side::right].position > 0.f; + bDoors[i][3] = p->MoverParameters->Doors.instances[side::left].step_position > 0.f; + bDoors[i][4] = p->MoverParameters->Doors.instances[side::right].step_position > 0.f; + bDoors[i][0] = bDoors[i][1] || bDoors[i][2]; + iDoorNo[i] = p->iAnimType[ANIM_DOORS]; + iUnits[i] = iUnitNo; + cCode[i] = p->MoverParameters->TypeName[p->MoverParameters->TypeName.length() - 1]; + asCarName[i] = p->name(); + if (p->MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) + { + bPants[iUnitNo - 1][end::front] = bPants[iUnitNo - 1][end::front] || p->MoverParameters->Pantographs[end::front].is_active; + bPants[iUnitNo - 1][end::rear] = bPants[iUnitNo - 1][end::rear] || p->MoverParameters->Pantographs[end::rear].is_active; + } + // TBD, TODO: clean up compressor data arrangement? + if (iUnitNo <= 8) + { + bComp[iUnitNo - 1][0] = bComp[iUnitNo - 1][0] || p->MoverParameters->CompressorAllow || p->MoverParameters->CompressorStart == start_t::automatic; + } + if (p->MoverParameters->CompressorSpeed > 0.00001) + { + if (iUnitNo <= 8) + { + bComp[iUnitNo - 1][1] = bComp[iUnitNo - 1][1] || p->MoverParameters->CompressorFlag; + } + bCompressors.emplace_back(p->MoverParameters->CompressorAllow || p->MoverParameters->CompressorStart == start_t::automatic, p->MoverParameters->CompressorFlag, i); + } + bSlip[i] = p->MoverParameters->SlippingWheels; + if (in < 8 && p->MoverParameters->eimc[eimc_p_Pmax] > 1) + { + fEIMParams[1 + in][0] = static_cast(p->MoverParameters->eimv[eimv_Fmax]); + fEIMParams[1 + in][1] = std::max(fEIMParams[1 + in][0], 0.f); + fEIMParams[1 + in][2] = -std::min(fEIMParams[1 + in][0], 0.f); + fEIMParams[1 + in][3] = static_cast(p->MoverParameters->eimv[eimv_Fmax] / std::max(p->MoverParameters->eimv[eimv_Fful], 1.)); + fEIMParams[1 + in][4] = std::max(fEIMParams[1 + in][3], 0.f); + fEIMParams[1 + in][5] = -std::min(fEIMParams[1 + in][3], 0.f); + fEIMParams[1 + in][6] = static_cast(p->MoverParameters->eimv[eimv_If]); + fEIMParams[1 + in][7] = static_cast(p->MoverParameters->eimv[eimv_U]); + fEIMParams[1 + in][8] = static_cast(p->MoverParameters->Itot); // p->MoverParameters->eimv[eimv_Ipoj]; + fEIMParams[1 + in][9] = static_cast(p->MoverParameters->EngineVoltage); + fEIMParams[0][6] += fEIMParams[1 + in][8]; + bMains[in] = p->MoverParameters->Mains; + fCntVol[in] = static_cast(p->MoverParameters->BatteryVoltage); + bFuse[in] = p->MoverParameters->FuseFlag; + bBatt[in] = p->MoverParameters->Battery; + bConv[in] = p->MoverParameters->ConverterFlag; + bHeat[in] = p->MoverParameters->Heating; + // bComp[in][2] = (p->MoverParameters->CompressorAllow || (p->MoverParameters->CompressorStart == start_t::automatic)); + // bComp[in][3] = (p->MoverParameters->CompressorFlag); + in++; + iPowerNo = in; + } + if (in < 8 && (p->MoverParameters->EngineType == TEngineType::DieselEngine || p->MoverParameters->EngineType == TEngineType::DieselElectric)) + { + fDieselParams[1 + in][0] = static_cast(p->MoverParameters->enrot * 60); + fDieselParams[1 + in][1] = static_cast(p->MoverParameters->nrot); + fDieselParams[1 + in][2] = static_cast(p->MoverParameters->RList[p->MoverParameters->MainCtrlPos].R); + fDieselParams[1 + in][3] = static_cast(p->MoverParameters->dizel_fill); + fDieselParams[1 + in][4] = static_cast(p->MoverParameters->RList[p->MoverParameters->MainCtrlPos].Mn); + fDieselParams[1 + in][5] = static_cast(p->MoverParameters->dizel_engage); + fDieselParams[1 + in][6] = p->MoverParameters->dizel_heat.Twy; + fDieselParams[1 + in][7] = p->MoverParameters->OilPump.pressure; + fDieselParams[1 + in][8] = p->MoverParameters->dizel_heat.Ts; + fDieselParams[1 + in][9] = static_cast(p->MoverParameters->hydro_R_Fill); + bMains[in] = p->MoverParameters->Mains; + fCntVol[in] = static_cast(p->MoverParameters->BatteryVoltage); + bFuse[in] = p->MoverParameters->FuseFlag; + bBatt[in] = p->MoverParameters->Battery; + bConv[in] = p->MoverParameters->ConverterFlag; + bHeat[in] = p->MoverParameters->Heating; + in++; + iPowerNo = in; + } + if ((kier ? p->Next(Coupling::permanent) : p->Prev(Coupling::permanent)) != (kier ? p->Next(Coupling::control) : p->Prev(Coupling::control))) + iUnitNo++; + p = kier ? p->Next(Coupling::control) : p->Prev(Coupling::control); + iCarNo = i + 1; + } + else + { + fPress[i][0] = 0; + fPress[i][1] = 0; + fPress[i][2] = 0; + fPress[i][3] = 0; + fPress[i][4] = 0; + fPress[i][5] = 0; + bDoors[i][0] = false; + bDoors[i][1] = false; + bDoors[i][2] = false; + bDoors[i][3] = false; + bDoors[i][4] = false; + bBrakes[i][0] = false; + bBrakes[i][1] = false; + bSlip[i] = false; + iUnits[i] = 0; + cCode[i] = 0; //'0'; + asCarName[i] = ""; + } + } + + // if (mvControlled == mvOccupied) + // fEIMParams[0][3] = mvControlled->eimv[eimv_Fzad]; // procent zadany + // else + // fEIMParams[0][3] = + // mvControlled->eimv[eimv_Fzad] - mvOccupied->LocalBrakeRatio(); // procent zadany + fEIMParams[0][3] = static_cast(mvOccupied->eimic_real); + fEIMParams[0][4] = std::max(fEIMParams[0][3], 0.f); + fEIMParams[0][5] = -std::min(fEIMParams[0][3], 0.f); + fEIMParams[0][1] = static_cast(fEIMParams[0][4] * mvControlled->eimv[eimv_Fful]); + fEIMParams[0][2] = static_cast(fEIMParams[0][5] * mvControlled->eimv[eimv_Fful]); + fEIMParams[0][0] = fEIMParams[0][1] - fEIMParams[0][2]; + fEIMParams[0][7] = 0; + fEIMParams[0][8] = 0; + fEIMParams[0][9] = 0; + + for (int i = in; i < 8; i++) + { + for (int j = 0; j <= 9; j++) + { + fEIMParams[1 + i][j] = 0; + fDieselParams[1 + i][j] = 0; + } + } +#ifdef _WIN32 + if (Global.iFeedbackMode == 4) + { + // wykonywać tylko gdy wyprowadzone na pulpit + // Ra: sterowanie miernikiem: zbiornik główny + Console::ValueSet(0, mvOccupied->Compressor); + // Ra: sterowanie miernikiem: przewód główny + Console::ValueSet(1, mvOccupied->PipePress); + // Ra: sterowanie miernikiem: cylinder hamulcowy + Console::ValueSet(2, mvOccupied->BrakePress); + // woltomierz wysokiego napięcia + Console::ValueSet(3, fHVoltage); + // Ra: sterowanie miernikiem: drugi amperomierz + Console::ValueSet(4, fHCurrent[2]); + // pierwszy amperomierz; dla EZT prąd całkowity + Console::ValueSet(5, fHCurrent[mvControlled->TrainType == train_type::emu ? 0 : 1]); + // Ra: prędkość na pin 43 - wyjście analogowe (to nie jest PWM); skakanie zapewnia mechanika napędu + Console::ValueSet(6, fTachoVelocity); + } +#endif + //------------------ + // hunter-261211: nadmiarowy przetwornicy i ogrzewania + // Ra 15-01: to musi stąd wylecieć - zależności nie mogą być w kabinie + if (mvControlled->ConverterFlag == true) + { + fConverterTimer += static_cast(Deltatime); + if (mvControlled->CompressorFlag == true && mvControlled->CompressorPower == 1 && (mvControlled->EngineType == TEngineType::ElectricSeriesMotor || mvControlled->TrainType == train_type::emu) && + DynamicObject->Controller == Humandriver // hunter-110212: poprawka dla EZT + && false == DynamicObject->Mechanik->AIControllFlag) + { // hunter-091012: poprawka (zmiana warunku z CompressorPower /rozne od 0/ na /rowne 1/) + if (fConverterTimer < fConverterPrzekaznik) + { + mvControlled->ConvOvldFlag = true; + if (mvControlled->TrainType != train_type::emu) + mvControlled->MainSwitch(false, mvControlled->TrainType == train_type::emu ? range_t::unit : range_t::local); + } + else if (fConverterTimer >= fConverterPrzekaznik) + { + // changed switch from always true to take into account state of the compressor switch + mvControlled->CompressorSwitch(mvControlled->CompressorAllow); + } + } + } + else + fConverterTimer = 0; + //------------------ + auto const lowvoltagepower{mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable}; + + // youBy - prad w drugim czlonie: galaz lub calosc + { + TDynamicObject const *tmp{nullptr}; + if (DynamicObject->NextConnected() && mvControlled->Couplers[end::rear].CouplingFlag.HasAll(Coupling::control) && mvOccupied->CabOccupied == 1) + tmp = DynamicObject->NextConnected(); + if (DynamicObject->PrevConnected() && mvControlled->Couplers[end::front].CouplingFlag.HasAll(Coupling::control) && mvOccupied->CabOccupied == -1) + tmp = DynamicObject->PrevConnected(); + if (tmp && tmp->MoverParameters->Power > 0) + { + if (ggI1B.SubModel) + { + ggI1B.UpdateValue(static_cast(tmp->MoverParameters->ShowCurrent(1))); + ggI1B.Update(); + } + if (ggI2B.SubModel) + { + ggI2B.UpdateValue(static_cast(tmp->MoverParameters->ShowCurrent(2))); + ggI2B.Update(); + } + if (ggI3B.SubModel) + { + ggI3B.UpdateValue(static_cast(tmp->MoverParameters->ShowCurrent(3))); + ggI3B.Update(); + } + if (ggItotalB.SubModel) + { + ggItotalB.UpdateValue(static_cast(tmp->MoverParameters->ShowCurrent(0))); + ggItotalB.Update(); + } + if (ggWater1TempB.SubModel) + { + ggWater1TempB.UpdateValue(tmp->MoverParameters->dizel_heat.temperatura1); + ggWater1TempB.Update(); + } + if (ggOilPressB.SubModel) + { + ggOilPressB.UpdateValue(tmp->MoverParameters->OilPump.pressure); + ggOilPressB.Update(); + } + } + } + // McZapkie-300302: zegarek + if (ggClockMInd.SubModel) + { + ggClockSInd.UpdateValue(simulation::Time.data().wSecond); + ggClockSInd.Update(); + ggClockMInd.UpdateValue(simulation::Time.data().wMinute); + ggClockMInd.Update(); + ggClockHInd.UpdateValue(static_cast(simulation::Time.data().wHour + simulation::Time.data().wMinute / 60.0)); + ggClockHInd.Update(); + } + + Cabine[iCabn].Update(lowvoltagepower); // nowy sposób ustawienia animacji + /* + if (ggZbS.SubModel) + { + ggZbS.UpdateValue(mvOccupied->Handle->GetCP()); + ggZbS.Update(); + } + */ + // replacement for the above. TODO: move it to a more suitable place + m_brakehandlecp = mvOccupied->Handle->GetCP(); + + // youBy - napiecie na silnikach + if (ggEngineVoltage.SubModel) + { + if (mvControlled->DynamicBrakeFlag) + { + ggEngineVoltage.UpdateValue(static_cast(std::abs(mvControlled->Im * 5))); + } + else + { + int x; + if (mvControlled->TrainType == train_type::et42 && mvControlled->Imax == mvControlled->ImaxHi) + x = 1; + else + x = 2; + if (mvControlled->RList[mvControlled->MainCtrlActualPos].Mn > 0 && std::abs(mvControlled->Im) > 0) + { + ggEngineVoltage.UpdateValue(static_cast(x * (std::abs(mvControlled->EngineVoltage) - mvControlled->RList[mvControlled->MainCtrlActualPos].R * std::abs(mvControlled->Im)) / + mvControlled->RList[mvControlled->MainCtrlActualPos].Mn)); + } + else + { + ggEngineVoltage.UpdateValue(0); + } + } + ggEngineVoltage.Update(); + } + + // Winger 140404 - woltomierz NN + if (ggLVoltage.SubModel) + { + // NOTE: since we don't have functional converter object, we're faking it here by simple check whether converter is on + // TODO: implement object-based circuits and power systems model so we can have this working more properly + ggLVoltage.UpdateValue(static_cast(std::max(mvOccupied->Power110vIsAvailable ? mvOccupied->NominalBatteryVoltage : 0.0, mvOccupied->Power24vIsAvailable ? mvOccupied->BatteryVoltage : 0.0))); + ggLVoltage.Update(); + } + + if (mvControlled->EngineType == TEngineType::DieselElectric) + { // ustawienie zmiennych dla silnika spalinowego + fEngine[1] = static_cast(mvControlled->ShowEngineRotation(1)); + fEngine[2] = static_cast(mvControlled->ShowEngineRotation(2)); + } + + else if (mvControlled->EngineType == TEngineType::DieselEngine) + { // albo dla innego spalinowego + fEngine[1] = static_cast(mvControlled->ShowEngineRotation(1)); + fEngine[2] = static_cast(mvControlled->ShowEngineRotation(2)); + fEngine[3] = static_cast(mvControlled->ShowEngineRotation(3)); + if (ggMainGearStatus.SubModel) + { + if (mvControlled->Mains) + ggMainGearStatus.UpdateValue(static_cast(1.1 - std::abs(mvControlled->dizel_automaticgearstatus))); + else + ggMainGearStatus.UpdateValue(0.0); + ggMainGearStatus.Update(); + } + if (ggIgnitionKey.SubModel && ggIgnitionKey.GetDesiredValue() == 0.0) + { + ggIgnitionKey.UpdateValue(mvControlled->Mains || mvControlled->dizel_startup || fMainRelayTimer > 0.f || + (ggMainButton.SubModel != nullptr && ggMainButton.GetDesiredValue() > 0.95) || + (ggMainOnButton.SubModel != nullptr && ggMainOnButton.GetDesiredValue() > 0.95)); + } + ggIgnitionKey.Update(); + } + + if (mvControlled->SlippingWheels) + { + // Ra 2014-12: lokomotywy 181/182 dostają SlippingWheels po zahamowaniu powyżej 2.85 bara i buczały + double veldiff = (DynamicObject->GetVelocity() - fTachoVelocity) / mvControlled->Vmax; + // 1% Vmax rezerwy, żeby 181/182 nie buczały po zahamowaniu, ale to proteza + if (veldiff < -0.01 && std::abs(mvControlled->Im) > 10.0) + { + btLampkaPoslizg.Turn(true); + } + } + else + { + btLampkaPoslizg.Turn(false); + } + + // Lampka pracujacej sprezacki + if (mvControlled->CompressorFlag || mvOccupied->CompressorFlag) + btCompressors.Turn(true); + else + btCompressors.Turn(false); + + // Lampka zezwolenia na hamowanie ED + if (mvControlled->EpFuse) + btEDenabled.Turn(true); + else + btEDenabled.Turn(false); + + // Lampka aktywowanej kabiny + if (mvControlled->CabActive != 0) + { + btCabActived.Turn(true); + } + else + { + btCabActived.Turn(false); + } + + if (mvControlled->Battery && mvControlled->CabActive != 0) + btAKLVents.Turn(true); + else + btAKLVents.Turn(false); + + if (true == lowvoltagepower) + { + // McZapkie-141102: SHP i czuwak, TODO: sygnalizacja kabinowa + if (mvOccupied->SecuritySystem.is_vigilance_blinking()) + { + if (fBlinkTimer > fCzuwakBlink) + fBlinkTimer = -fCzuwakBlink; + else + fBlinkTimer += Deltatime; + + btLampkaCzuwaka.Turn(fBlinkTimer > 0); + } + else + { + fBlinkTimer = 0.0; + btLampkaCzuwaka.Turn(false); + } + + btLampkaSHP.Turn(mvOccupied->SecuritySystem.is_cabsignal_blinking()); + btLampkaCzuwakaSHP.Turn(btLampkaSHP.GetValue() || btLampkaCzuwaka.GetValue()); + + btLampkaWylSzybki.Turn(m_linebreakerstate == linebreaker::state::closing || mvControlled->Mains); + btLampkaWylSzybkiOff.Turn(m_linebreakerstate != linebreaker::state::closing && !mvControlled->Mains); + btLampkaMainBreakerReady.Turn(mvControlled->MainsInitTimeCountdown <= 0.0 && m_linebreakerstate != linebreaker::state::closing && !mvControlled->Mains); + btLampkaMainBreakerBlinkingIfReady.Turn(m_linebreakerstate == linebreaker::state::closing || mvControlled->Mains || mvControlled->MainsInitTimeCountdown < 0.0 && simulation::Time.data().wMilliseconds > 500); + + btLampkaPrzetw.Turn(mvOccupied->Power110vIsAvailable); + btLampkaPrzetwOff.Turn(!mvOccupied->Power110vIsAvailable); + btLampkaPrzetwAOff.Turn(!mvControlled->ConverterFlag); + btLampkaNadmPrzetw.Turn(Dynamic()->Mechanik ? Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : mvControlled->ConvOvldFlag); + + btLampkaOpory.Turn(mvControlled->StLinFlag && mvControlled->ResistorsFlagCheck()); + btLampkaBezoporowa.Turn(mvControlled->ResistorsFlagCheck() || mvControlled->MainCtrlActualPos == 0); // do EU04 + btLampkaStyczn.Turn(mvControlled->LineContactorsLampLit()); // mozna prowadzic rozruch + btLampkaPrzekRozn.Turn(!mvControlled->GroundRelay && mvControlled->MainCircuitLampsEnabled()); // relay is off and needs a reset + btLampkaNadmSil.Turn(mvControlled->FuseFlagCheck() && mvControlled->MainCircuitLampsEnabled()); // relay is off and needs a reset + btLampkaUkrotnienie.Turn(mvControlled->Couplers[mvControlled->CabOccupied == 1 ? rear : front].CouplingFlag.HasAll(Coupling::control)); + btLampkaHamPosp.Turn(TestFlag(mvOccupied->Hamulec->GetBrakeStatus(), 1)); // lampka drugiego stopnia hamowania + // TODO: youBy wyciągnąć flagę wysokiego stopnia + btLampkaNadmWent.Turn(mvControlled->RventRot < 5.0 && mvControlled->ResistorsFlagCheck()); // hunter-121211: lampka zanikowo-pradowego wentylatorow + btLampkaWysRozr.Turn(mvControlled->Imax >= mvControlled->ImaxHi); + + btLampkaNapNastHam.Turn(mvControlled->DirActive != 0); // napiecie na nastawniku hamulcowym + btLampkaSprezarka.Turn(mvControlled->CompressorFlag); // mutopsitka dziala + btLampkaSprezarkaOff.Turn(!mvControlled->CompressorFlag); + btLampkaFuelPumpOff.Turn(!mvControlled->FuelPump.is_active); + btLampkaOilPump.Turn(mvControlled->OilPump.is_active); // pre-lubrication pump, goes off once the engine is started + + // boczniki + // Ra: w SU45 boczniki wchodzą na ScndCtrlPos, a nie na ScndCtrlActualPos + // - pokićkał ktoś? + int scp = mvControlled->RList[mvControlled->MainCtrlPos].ScndAct; + scp = scp == 255 ? 0 : scp; // Ra: whatta hella is this? + btLampkaBoczniki.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlActualPos > 0 || scp > 0); + btLampkaBocznik1.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlPos > 0 || mvControlled->ScndCtrlActualPos > 0 || scp > 0); + btLampkaBocznik2.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlPos > 1 || mvControlled->ScndCtrlActualPos > 1 || scp > 1); + btLampkaBocznik3.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlPos > 2 || mvControlled->ScndCtrlActualPos > 2 || scp > 2); + btLampkaBocznik4.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlPos > 3 || mvControlled->ScndCtrlActualPos > 3 || scp > 3); + + // biegi dla motoraka + btLampkaGear1.Turn(mvControlled->ScndCtrlActualPos == 1 && mvControlled->dizel_engagestate > 0); // bieg 1 + btLampkaGear2.Turn(mvControlled->ScndCtrlActualPos == 2 && mvControlled->dizel_engagestate > 0); // bieg 2 + btLampkaHydroLockup.Turn(mvControlled->hydro_TC_Lockup); // zblokowanie skrzyni z silnikiem + + if (mvControlled->Signalling == true) + { + if (mvOccupied->BrakePress >= 1.45f) + { + btLampkaHamowanie1zes.Turn(true); + } + if (mvControlled->BrakePress < 0.75f) + { + btLampkaHamowanie1zes.Turn(false); + } + } + else + { + btLampkaHamowanie1zes.Turn(false); + } + + switch (mvControlled->TrainType) + { + // zależnie od typu lokomotywy + case train_type::emu: + { + btLampkaHamienie.Turn(mvControlled->BrakePress >= 0.2 && mvControlled->Signalling); + break; + } + case train_type::et41: + { + // odhamowanie drugiego członu + if (mvSecond) + { + // bo może komuś przyjść do głowy jeżdżenie jednym członem + btLampkaHamienie.Turn(mvSecond->BrakePress < 0.4); + } + break; + } + default: + { + btLampkaHamienie.Turn(mvOccupied->BrakePress >= 0.1 || mvControlled->DynamicBrakeFlag); + btLampkaBrakingOff.Turn(mvOccupied->BrakePress < 0.1 && !mvControlled->DynamicBrakeFlag); + break; + } + } + // KURS90 + btLampkaMaxSila.Turn(abs(mvControlled->Im) >= 350); + btLampkaPrzekrMaxSila.Turn(abs(mvControlled->Im) >= 450); + btLampkaRadio.Turn(mvOccupied->Radio && mvOccupied->RadioFuse); + btLampkaRadioMessage.Turn(radio_message_played); + btLampkaRadioStop.Turn(mvOccupied->Radio && mvOccupied->RadioFuse && mvOccupied->RadioStopFlag); + btLampkaHamulecReczny.Turn(mvOccupied->ManualBrakePos > 0); + // NBMX wrzesien 2003 - drzwi oraz sygnał odjazdu + if (DynamicObject->Mechanik != nullptr) + { + btLampkaDoorLeft.Turn(DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == end::front ? side::left : side::right]); + btLampkaDoorRight.Turn(DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == end::front ? side::right : side::left]); + } + if (DynamicObject->Mechanik != nullptr) + { + // with DoorClosureSignal in the definition of the cab's vehicle, the door closure signalling (SOD) of the whole + // consist: lit with all doors closed and locked, blinking with them closed but released, dark with a door open. + // without it, the lock of the vehicle's own doors, as before + btLampkaBlokadaDrzwi.Turn(mvOccupied->door_closure_lamp_lit(DynamicObject->Mechanik->DoorClosure, simulation::Time.data().wSecond % 2 < 1)); + } + else + { + btLampkaBlokadaDrzwi.Turn(mvOccupied->Doors.is_locked); + } + btLampkaDoorLockOff.Turn(false == mvOccupied->Doors.lock_enabled); + btLampkaDepartureSignal.Turn(mvControlled->DepartureSignal); + btLampkaNapNastHam.Turn(mvControlled->DirActive != 0 && mvOccupied->EpFuse); // napiecie na nastawniku hamulcowym + + // Wylaczanie lampek kierunku gdy jedziemy + // Feature uruchamiany z fiz z sekcji Ctrl. wpisem HideDirStatusWhenMoving=Yes (domyslnie No) + if (mvOccupied->HideDirStatusWhenMoving && // Czy ta funkcja jest w ogole wlaczona + mvOccupied->Vel > mvOccupied->HideDirStatusSpeed) // Uzaleznienie od predkosci + { + btLampkaForward.Turn(false); + btLampkaBackward.Turn(false); + btLampkaNeutral.Turn(false); + } + else + { + btLampkaForward.Turn(mvControlled->DirActive > 0); // jazda do przodu + btLampkaBackward.Turn(mvControlled->DirActive < 0); // jazda do tyłu + btLampkaNeutral.Turn(mvControlled->DirActive == 0); // kierunek neutral + } + + btLampkaED.Turn(mvControlled->DynamicBrakeFlag); // hamulec ED + btLampkaBrakeProfileG.Turn(TestFlag(mvOccupied->BrakeDelayFlag, bdelay_G)); + btLampkaBrakeProfileP.Turn(TestFlag(mvOccupied->BrakeDelayFlag, bdelay_P)); + btLampkaBrakeProfileR.Turn(TestFlag(mvOccupied->BrakeDelayFlag, bdelay_R)); + btLampkaSpringBrakeActive.Turn(mvOccupied->SpringBrake.IsActive); + btLampkaSpringBrakeInactive.Turn(!mvOccupied->SpringBrake.IsActive); + // light indicators + // NOTE: sides are hardcoded to deal with setups where single cab is equipped with all indicators + btLampkaUpperLight.Turn((mvOccupied->iLights[end::front] & light::headlight_upper) != 0); + btLampkaLeftLight.Turn((mvOccupied->iLights[end::front] & light::headlight_left) != 0); + btLampkaRightLight.Turn((mvOccupied->iLights[end::front] & light::headlight_right) != 0); + btLampkaLeftEndLight.Turn((mvOccupied->iLights[end::front] & light::redmarker_left) != 0); + btLampkaRightEndLight.Turn((mvOccupied->iLights[end::front] & light::redmarker_right) != 0); + btLampkaRearUpperLight.Turn((mvOccupied->iLights[end::rear] & light::headlight_upper) != 0); + btLampkaRearLeftLight.Turn((mvOccupied->iLights[end::rear] & light::headlight_left) != 0); + btLampkaRearRightLight.Turn((mvOccupied->iLights[end::rear] & light::headlight_right) != 0); + btLampkaRearLeftEndLight.Turn((mvOccupied->iLights[end::rear] & light::redmarker_left) != 0); + btLampkaRearRightEndLight.Turn((mvOccupied->iLights[end::rear] & light::redmarker_right) != 0); + // others + btLampkaMalfunction.Turn(mvControlled->dizel_heat.PA); + // overheat indicator lamps + btLampkaOilOverheat.Turn(mvControlled->dizel_heat.oil.is_hot); + btLampkaWaterOverheat.Turn(mvControlled->dizel_heat.water.is_hot); + btLampkaWaterAuxOverheat.Turn(mvControlled->dizel_heat.water_aux.is_hot); + btLampkaEngineOverheat.Turn(mvControlled->dizel_heat.engine_is_hot); + btLampkaMotorBlowers.Turn(mvControlled->MotorBlowers[end::front].is_active && mvControlled->MotorBlowers[end::rear].is_active); + btLampkaCoolingFans.Turn(mvControlled->RventRot > 1.0); + btLampkaLouvresClosed.Turn(mvControlled->LouvresClosed()); + btLampkaTempomat.Turn(mvOccupied->SpeedCtrlUnit.IsActive); + btLampkaDistanceCounter.Turn(m_distancecounter >= 0.f); + // universal devices state indicators + for (auto idx = 0; idx < btUniversals.size(); ++idx) + { + btUniversals[idx].Turn(ggUniversals[idx].GetValue() > 0.5); + } + } + else + { + // wylaczone + btLampkaCzuwaka.Turn(false); + btLampkaSHP.Turn(false); + btLampkaCzuwakaSHP.Turn(false); + btLampkaWylSzybki.Turn(false); + btLampkaWylSzybkiOff.Turn(false); + btLampkaMainBreakerReady.Turn(false); + btLampkaMainBreakerBlinkingIfReady.Turn(false); + btLampkaWysRozr.Turn(false); + btLampkaOpory.Turn(false); + btLampkaStyczn.Turn(false); + btLampkaPrzekRozn.Turn(false); + btLampkaNadmSil.Turn(false); + btLampkaUkrotnienie.Turn(false); + btLampkaHamPosp.Turn(false); + btLampkaBoczniki.Turn(false); + btLampkaBocznik1.Turn(false); + btLampkaBocznik2.Turn(false); + btLampkaBocznik3.Turn(false); + btLampkaBocznik4.Turn(false); + btLampkaGear1.Turn(false); + btLampkaGear2.Turn(false); + btLampkaHydroLockup.Turn(false); + btLampkaNapNastHam.Turn(false); + btLampkaPrzetw.Turn(false); + btLampkaPrzetwOff.Turn(false); + btLampkaPrzetwAOff.Turn(false); + btLampkaNadmPrzetw.Turn(false); + btLampkaSprezarka.Turn(false); + btLampkaSprezarkaOff.Turn(false); + btLampkaFuelPumpOff.Turn(false); + btLampkaOilPump.Turn(false); + btLampkaBezoporowa.Turn(false); + btLampkaHamowanie1zes.Turn(false); + btLampkaHamienie.Turn(false); + btLampkaBrakingOff.Turn(false); + btLampkaBrakeProfileG.Turn(false); + btLampkaBrakeProfileP.Turn(false); + btLampkaBrakeProfileR.Turn(false); + btLampkaSpringBrakeActive.Turn(false); + btLampkaSpringBrakeInactive.Turn(false); + // overheat indicator lamps off + btLampkaOilOverheat.Turn(false); + btLampkaWaterOverheat.Turn(false); + btLampkaWaterAuxOverheat.Turn(false); + btLampkaEngineOverheat.Turn(false); + btLampkaMaxSila.Turn(false); + btLampkaPrzekrMaxSila.Turn(false); + btLampkaRadio.Turn(false); + btLampkaRadioMessage.Turn(false); + btLampkaRadioStop.Turn(false); + btLampkaHamulecReczny.Turn(false); + btLampkaDoorLeft.Turn(false); + btLampkaDoorRight.Turn(false); + btLampkaBlokadaDrzwi.Turn(false); + btLampkaDoorLockOff.Turn(false); + btLampkaDepartureSignal.Turn(false); + btLampkaNapNastHam.Turn(false); + btLampkaForward.Turn(false); + btLampkaBackward.Turn(false); + btLampkaNeutral.Turn(false); + btLampkaED.Turn(false); + // light indicators + btLampkaUpperLight.Turn(false); + btLampkaLeftLight.Turn(false); + btLampkaRightLight.Turn(false); + btLampkaLeftEndLight.Turn(false); + btLampkaRightEndLight.Turn(false); + btLampkaRearUpperLight.Turn(false); + btLampkaRearLeftLight.Turn(false); + btLampkaRearRightLight.Turn(false); + btLampkaRearLeftEndLight.Turn(false); + btLampkaRearRightEndLight.Turn(false); + // others + btLampkaMalfunction.Turn(false); + btLampkaMotorBlowers.Turn(false); + btLampkaCoolingFans.Turn(false); + btLampkaLouvresClosed.Turn(false); + btLampkaTempomat.Turn(false); + btLampkaDistanceCounter.Turn(false); + // universal devices state indicators + for (auto &universal : btUniversals) + { + universal.Turn(false); + } + } + + { // yB - wskazniki drugiego czlonu + TDynamicObject const *tmp{nullptr}; //=mvControlled->mvSecond; //Ra 2014-07: trzeba to jeszcze wyjąć z kabiny... + // Ra 2014-07: no nie ma potrzeby szukać tego w każdej klatce + if (mvControlled->Couplers[1].CouplingFlag.HasAll(Coupling::control) && mvOccupied->CabOccupied > 0) + tmp = DynamicObject->NextConnected(); + if (mvControlled->Couplers[0].CouplingFlag.HasAll(Coupling::control) && mvOccupied->CabOccupied < 0) + tmp = DynamicObject->PrevConnected(); + + if (tmp) + { + if (lowvoltagepower) + { + + auto const *mover{tmp->MoverParameters}; + + btLampkaWylSzybkiB.Turn(mover->Mains); + btLampkaWylSzybkiBOff.Turn(false == mover->Mains + /*&& ( mover->MainsInitTimeCountdown <= 0.0 )*/ + /*&& ( fHVoltage != 0.0 )*/); + + btLampkaOporyB.Turn(mover->ResistorsFlagCheck()); + btLampkaBezoporowaB.Turn(true == mover->ResistorsFlagCheck() || mover->MainCtrlActualPos == 0); // do EU04 + + btLampkaStycznB.Turn(mover->LineContactorsLampLit()); // mozna prowadzic rozruch + // hunter-271211: sygnalizacja poslizgu w pierwszym pojezdzie, gdy wystapi w drugim + if (mover->SlippingWheels) + { + // Ra 2014-12: lokomotywy 181/182 dostają SlippingWheels po zahamowaniu powyżej 2.85 bara i buczały + auto const veldiff{(DynamicObject->GetVelocity() - fTachoVelocity) / mvControlled->Vmax}; + if (veldiff < -0.01) + { + // 1% Vmax rezerwy, żeby 181/182 nie buczały po zahamowaniu, ale to proteza + auto const lightstate{std::abs(mover->Im) > 10.0}; + btLampkaPoslizg.Turn(btLampkaPoslizg.GetValue() || lightstate); + } + } + + btLampkaSprezarkaB.Turn(mover->CompressorFlag); // mutopsitka dziala + btLampkaSprezarkaBOff.Turn(false == mover->CompressorFlag); + if (mvControlled->Signalling == true) + { + if (mover->BrakePress >= 1.45f) + { + btLampkaHamowanie2zes.Turn(true); + } + if (mover->BrakePress < 0.75f) + { + btLampkaHamowanie2zes.Turn(false); + } + } + else + { + btLampkaHamowanie2zes.Turn(false); + } + btLampkaNadmPrzetwB.Turn(mover->ConvOvldFlag); // nadmiarowy przetwornicy? + btLampkaPrzetwB.Turn(mover->ConverterFlag); // zalaczenie przetwornicy + btLampkaPrzetwBOff.Turn(false == mover->ConverterFlag); + btLampkaHVoltageB.Turn(mover->NoVoltRelay && mover->OvervoltageRelay); + btLampkaMalfunctionB.Turn(mover->dizel_heat.PA); + // motor fuse indicator turns on if the fuse was blown in any unit under control + if (mover->Mains) + { + btLampkaNadmSil.Turn(btLampkaNadmSil.GetValue() || mover->FuseFlagCheck()); + } + } + else // wylaczone + { + btLampkaWylSzybkiB.Turn(false); + btLampkaWylSzybkiBOff.Turn(false); + btLampkaOporyB.Turn(false); + btLampkaStycznB.Turn(false); + btLampkaSprezarkaB.Turn(false); + btLampkaSprezarkaBOff.Turn(false); + btLampkaBezoporowaB.Turn(false); + btLampkaHamowanie2zes.Turn(false); + btLampkaNadmPrzetwB.Turn(false); + btLampkaPrzetwB.Turn(false); + btLampkaPrzetwBOff.Turn(false); + btLampkaHVoltageB.Turn(false); + btLampkaMalfunctionB.Turn(false); + } + } + } + // McZapkie-080602: obroty (albo translacje) regulatorow + if (ggJointCtrl.SubModel != nullptr) + { + // joint master controller moves forward to adjust power and backward to adjust brakes + auto const brakerangemultiplier{/* NOTE: scaling disabled as it was conflicting with associating sounds with control positions + ( mvControlled->CoupledCtrl ? + mvControlled->MainCtrlPosNo + mvControlled->ScndCtrlPosNo : + mvControlled->MainCtrlPosNo ) + / static_cast(LocalBrakePosNo) + */ + 1}; + // when SplitEDPneumaticBrake is active the negative range of the joint controller + // represents the dedicated dynamic-brake lever (DBPN steps), not the pneumatic local brake + auto const negativePart{mvControlled->SplitEDPneumaticBrake ? + (mvControlled->DynamicBrakeCtrlPos > 0.0 ? mvControlled->DynamicBrakeCtrlPos * mvControlled->DynamicBrakeCtrlPosNo * -1 * brakerangemultiplier : 0.0) : + mvOccupied->LocalBrakePosA > 0.0 ? mvOccupied->LocalBrakePosA * LocalBrakePosNo * -1 * brakerangemultiplier : + 0.0}; + ggJointCtrl.UpdateValue(negativePart < 0.0 ? static_cast(negativePart) : + mvControlled->CoupledCtrl ? static_cast(double(mvControlled->MainCtrlPos + mvControlled->ScndCtrlPos)) : + static_cast(double(mvControlled->MainCtrlPos)), + dsbNastawnikJazdy); + ggJointCtrl.Update(); + } + if (ggMainCtrl.SubModel != nullptr) + { + +#ifdef _WIN32 + if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag // nie blokujemy AI + && Global.iFeedbackMode == 4 && Global.fCalibrateIn[2][1] != 0.0) + { + + set_master_controller(Console::AnalogCalibrateGet(2) * mvOccupied->MainCtrlPosNo); + mvOccupied->eimic_analog = Console::AnalogCalibrateGet(2); + } +#endif + + if (mvControlled->CoupledCtrl) + { + ggMainCtrl.UpdateValue(static_cast(double(mvControlled->MainCtrlPos + mvControlled->ScndCtrlPos)), dsbNastawnikJazdy); + } + else + { + ggMainCtrl.UpdateValue(static_cast(double(mvControlled->MainCtrlPos)), dsbNastawnikJazdy); + } + ggMainCtrl.Update(); + } + if (ggMainCtrlAct.SubModel != nullptr) + { + ggMainCtrlAct.UpdateValue(main_ctrl_act::position(*mvControlled, ggMainCtrlAct.has_scaletable())); + ggMainCtrlAct.Update(); + } + if (ggScndCtrl.SubModel != nullptr) + { + // Ra: od byte odejmowane boolean i konwertowane potem na double? + if (false == ggScndCtrl.is_push()) + { + ggScndCtrl.UpdateValue(static_cast(double(mvControlled->ScndCtrlPos - (mvControlled->TrainType == train_type::et42 && mvControlled->DynamicBrakeFlag))), dsbNastawnikBocz); + } + ggScndCtrl.Update(); + } + if (ggScndCtrlButton.SubModel != nullptr) + { + if (ggScndCtrlButton.is_toggle()) + { + ggScndCtrlButton.UpdateValue(mvControlled->IsSpeedCtrlEngaged() ? 1.f : 0.f, dsbSwitch); + } + ggScndCtrlButton.Update(lowvoltagepower); + } + if (ggScndCtrlOffButton.SubModel != nullptr) + { + ggScndCtrlOffButton.Update(lowvoltagepower); + } + if (ggDistanceCounterButton.SubModel != nullptr) + { + ggDistanceCounterButton.Update(); + } + if (ggDirKey.SubModel != nullptr) + { + if (mvControlled->TrainType != train_type::emu) + { + ggDirKey.UpdateValue(static_cast(double(mvControlled->DirActive)), dsbReverserKey); + } + else + { + ggDirKey.UpdateValue(static_cast(double(mvControlled->DirActive) + double(mvControlled->Imin == mvControlled->IminHi)), dsbReverserKey); + } + ggDirKey.Update(); + } + if (ggBrakeCtrl.SubModel != nullptr) + { +#ifdef _WIN32 + if (DynamicObject->Mechanik ? (DynamicObject->Mechanik->AIControllFlag ? false : Global.iFeedbackMode == 4 /*|| (Global.bMWDmasterEnable && Global.bMWDBreakEnable)*/) : + false && Global.fCalibrateIn[0][1] != 0.0) // nie blokujemy AI + { // Ra: nie najlepsze miejsce, ale na początek gdzieś to dać trzeba + // Firleju: dlatego kasujemy i zastepujemy funkcją w Console + if (mvOccupied->BrakeHandle == TBrakeHandle::FV4a) + { + double b = Console::AnalogCalibrateGet(0); + b = b * 8.0 - 2.0; + b = safe_clamp(b, -2.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic + ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia + mvOccupied->BrakeLevelSet(b); + } + else if (mvOccupied->BrakeHandle == TBrakeHandle::FVel6) // może można usunąć ograniczenie do FV4a i FVel6? + { + double b = Console::AnalogCalibrateGet(0); + b = b * 7.0 - 1.0; + b = safe_clamp(b, -1.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic + ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia + mvOccupied->BrakeLevelSet(b); + } + else + { + double b = Console::AnalogCalibrateGet(0); + b = b * (mvOccupied->Handle->GetPos(bh_MAX) - mvOccupied->Handle->GetPos(bh_MIN)) + mvOccupied->Handle->GetPos(bh_MIN); + b = safe_clamp(b, mvOccupied->Handle->GetPos(bh_MIN), mvOccupied->Handle->GetPos(bh_MAX)); // przycięcie zmiennej do granic + ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia + mvOccupied->BrakeLevelSet(b); + } + } + else +#endif + { + // else //standardowa prodedura z kranem powiązanym z klawiaturą + // ggBrakeCtrl.UpdateValue(double(mvOccupied->BrakeCtrlPos)); + ggBrakeCtrl.UpdateValue(static_cast(mvOccupied->fBrakeCtrlPos)); + ggBrakeCtrl.Update(); + } + } + + if (ggLocalBrake.SubModel != nullptr) + { +#ifdef _WIN32 + if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag // nie blokujemy AI + && mvOccupied->BrakeLocHandle == TBrakeHandle::FD1 && Global.iFeedbackMode == 4 && Global.fCalibrateIn[0][1] != 0.0) + { + // Ra: nie najlepsze miejsce, ale na początek gdzieś to dać trzeba + // Firleju: dlatego kasujemy i zastepujemy funkcją w Console + auto const b = std::clamp(Console::AnalogCalibrateGet(1), 0.f, 1.f); + mvOccupied->LocalBrakePosA = b; + ggLocalBrake.UpdateValue(b * LocalBrakePosNo); + } + else +#endif + { + // standardowa prodedura z kranem powiązanym z klawiaturą + ggLocalBrake.UpdateValue(static_cast(mvOccupied->LocalBrakePosA * LocalBrakePosNo)); + } + ggLocalBrake.Update(); + } + ggDirForwardButton.Update(lowvoltagepower); + ggDirNeutralButton.Update(lowvoltagepower); + ggDirBackwardButton.Update(lowvoltagepower); + ggAlarmChain.Update(); + ggBrakeProfileCtrl.Update(); + ggBrakeProfileG.Update(); + ggBrakeProfileR.Update(); + ggBrakeOperationModeCtrl.Update(); + ggWiperSw.Update(); + ggMaxCurrentCtrl.UpdateValue(true == mvControlled->ShuntModeAllow ? (true == mvControlled->ShuntMode ? 1.f : 0.f) : mvControlled->MotorOverloadRelayHighThreshold ? 1.f : 0.f); + ggMaxCurrentCtrl.Update(); + ggAutoRelayButton.UpdateValue(mvOccupied->AutoRelayFlag ? 1.f : 0.f); + ggAutoRelayButton.Update(); + // NBMX wrzesien 2003 - drzwi + ggDoorLeftPermitButton.Update(lowvoltagepower); + ggDoorRightPermitButton.Update(lowvoltagepower); + ggDoorPermitPresetButton.Update(lowvoltagepower); + ggDoorLeftButton.Update(lowvoltagepower); + ggDoorRightButton.Update(lowvoltagepower); + ggDoorLeftOnButton.Update(lowvoltagepower); + ggDoorRightOnButton.Update(lowvoltagepower); + ggDoorLeftOffButton.Update(lowvoltagepower); + ggDoorRightOffButton.Update(lowvoltagepower); + ggDoorAllOnButton.Update(lowvoltagepower); + ggDoorAllOffButton.Update(lowvoltagepower); + ggDoorSignallingButton.Update(lowvoltagepower); + ggDoorStepButton.Update(lowvoltagepower); + // NBMX dzwignia sprezarki + ggCompressorButton.Update(); + ggCompressorLocalButton.Update(); + ggCompressorListButton.Update(); + + //--------- + // hunter-080812: poprawka na ogrzewanie w elektrykach - usuniete uzaleznienie od przetwornicy + if (mvControlled->Heating == true && mvControlled->ConvOvldFlag == false) + btLampkaOgrzewanieSkladu.Turn(true); + else + btLampkaOgrzewanieSkladu.Turn(false); + + //---------- + + // lights + auto const lightpower{(InstrumentLightType == 0 ? mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable : + InstrumentLightType == 1 ? mvControlled->Mains : + InstrumentLightType == 2 ? mvOccupied->Power110vIsAvailable : + InstrumentLightType == 3 ? mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable : + InstrumentLightType == 4 ? mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable : + false)}; + InstrumentLightActive = InstrumentLightType == 3 ? true : // TODO: link the light state with the state of the master key + InstrumentLightType == 4 ? mvOccupied->iLights[end::front] != 0 || mvOccupied->iLights[end::rear] != 0 : + InstrumentLightActive; + btInstrumentLight.Turn(InstrumentLightActive && lightpower); + btDashboardLight.Turn(DashboardLightActive && lightpower); + btTimetableLight.Turn(TimetableLightActive && lightpower); + + // guziki: + ggMainOffButton.Update(); + ggMainOnButton.Update(); + ggMainButton.Update(); + for (auto &remotelinebreaker : m_remotelinebreakers) + { + remotelinebreaker.main_switch.Update(); + remotelinebreaker.on_button.Update(); + remotelinebreaker.off_button.Update(); + } + ggSecurityResetButton.Update(); + ggSHPResetButton.Update(); + ggReleaserButton.Update(); + ggSpringBrakeOnButton.Update(); + ggSpringBrakeOffButton.Update(); + ggUniveralBrakeButton1.Update(); + ggUniveralBrakeButton2.Update(); + ggUniveralBrakeButton3.Update(); + ggEPFuseButton.Update(); + ggAntiSlipButton.Update(); + ggSandButton.Update(); + ggAutoSandButton.Update(); + ggFuseButton.Update(); + ggConverterFuseButton.Update(); + ggStLinOffButton.Update(); + ggRadioChannelSelector.Update(); + ggRadioChannelPrevious.Update(); + ggRadioChannelNext.Update(); + ggRadioStop.Update(); + ggRadioTest.Update(); + ggRadioCall1.Update(); + ggRadioCall3.Update(); + ggRadioVolumeSelector.Update(); + ggRadioVolumePrevious.Update(); + ggRadioVolumeNext.Update(); + ggRadioOnButton.Update(); + ggRadioOffButton.Update(); + ggRadioFuseOnButton.Update(); + ggRadioFuseOffButton.Update(); + ggDepartureSignalButton.Update(); + /* + ggPantFrontButton.Update(); + ggPantRearButton.Update(); + ggPantFrontButtonOff.Update(); + ggPantRearButtonOff.Update(); + */ + ggPantAllDownButton.Update(); + ggPantSelectedDownButton.Update(); + ggPantSelectedButton.Update(); + ggPantValvesButton.Update(); + ggPantCompressorButton.Update(); + ggPantCompressorValve.Update(); + + ggPantValvesOff.Update(); + ggPantValvesUpdate.Update(); + + ggLightsButton.Update(); + ggUpperLightButton.Update(); + ggLeftLightButton.Update(); + ggRightLightButton.Update(); + ggLeftEndLightButton.Update(); + ggRightEndLightButton.Update(); + ggModernLightDimSw.Update(); + // hunter-230112 + ggRearUpperLightButton.Update(); + ggRearLeftLightButton.Update(); + ggRearRightLightButton.Update(); + ggRearLeftEndLightButton.Update(); + ggRearRightEndLightButton.Update(); + ggDimHeadlightsButton.Update(); + ggDimHeadlightsButton.Update(); + //------------ + // the converter switches follow the vehicle when something else flips them (the AI driver, the other cab, + // the pressure switch of an EMU), not only when the cab is entered (set_cab_controls()) + if (ggConverterButton.SubModel != nullptr && mvOccupied->ConvSwitchType != "impulse" && mvOccupied->ConverterStart == start_t::manual) + { + ggConverterButton.UpdateValue(mvOccupied->ConverterAllow ? 1.f : 0.f, dsbSwitch); + } + ggConverterButton.Update(); + if (ggConverterLocalButton.SubModel != nullptr) + { + ggConverterLocalButton.UpdateValue(mvOccupied->ConverterAllowLocal ? 1.f : 0.f, dsbSwitch); + } + ggConverterLocalButton.Update(); + ggConverterOffButton.Update(); + ggTrainHeatingButton.Update(); + ggSignallingButton.Update(); + ggNextCurrentButton.Update(); + ggHornButton.Update(); + ggHornLowButton.Update(); + ggHornHighButton.Update(); + ggWhistleButton.Update(); + if (DynamicObject->Mechanik != nullptr) + { + ggHelperButton.UpdateValue(static_cast(DynamicObject->Mechanik->HelperState)); + } + ggHelperButton.Update(); + + ggSpeedControlIncreaseButton.Update(lowvoltagepower); + ggSpeedControlDecreaseButton.Update(lowvoltagepower); + ggSpeedControlPowerIncreaseButton.Update(lowvoltagepower); + ggSpeedControlPowerDecreaseButton.Update(lowvoltagepower); + for (auto &speedctrlbutton : ggSpeedCtrlButtons) + { + speedctrlbutton.Update(lowvoltagepower); + } + for (auto &universal : ggUniversals) + { + universal.Update(); + } + for (auto &item : ggInverterEnableButtons) + { + item.Update(); + } + for (auto &item : ggInverterDisableButtons) + { + item.Update(); + } + for (auto &item : ggInverterToggleButtons) + { + item.Update(); + } + for (auto &relayresetbutton : ggRelayResetButtons) + { + relayresetbutton.Update(); + } + // hunter-091012 + ggInstrumentLightButton.Update(); + ggDashboardLightButton.Update(); + ggTimetableLightButton.Update(); + ggCabLightDimButton.Update(); + ggCompartmentLightsButton.Update(); + ggCompartmentLightsOnButton.Update(); + ggCompartmentLightsOffButton.Update(); + ggBatteryButton.Update(); + ggBatteryOnButton.Update(); + ggBatteryOffButton.Update(); + if (ggCabActivationButton.SubModel != nullptr && ggCabActivationButton.type() != TGaugeType::push) + { + ggCabActivationButton.UpdateValue(mvOccupied->IsCabMaster() ? 1.0 : 0.0); + } + ggCabActivationButton.Update(); + + ggWaterPumpBreakerButton.Update(); + ggWaterPumpButton.Update(); + ggWaterHeaterBreakerButton.Update(); + ggWaterHeaterButton.Update(); + ggWaterCircuitsLinkButton.Update(); + ggFuelPumpButton.Update(); + ggOilPumpButton.Update(); + ggOilFuelPumpButton.Update(); + ggTractionModeSwitch.Update(); + ggGensetButton.Update(); + ggMotorBlowersFrontButton.Update(); + ggMotorBlowersRearButton.Update(); + ggMotorBlowersAllOffButton.Update(); + + // wyprowadzenie sygnałów dla haslera na PoKeys (zaznaczanie na taśmie) + btHaslerBrakes.Turn(mvOccupied->BrakePress > 0.4); // ciśnienie w cylindrach + btHaslerCurrent.Turn(mvOccupied->Im != 0.0); // prąd na silnikach + + // calculate current level of interior illumination + { + // TODO: organize it along with rest of train update in a more sensible arrangement + // Ra: uzeleżnic od napięcia w obwodzie sterowania + // hunter-091012: uzaleznienie jasnosci od przetwornicy + int cabidx{0}; + for (auto &cab : Cabine) + { + + auto const cablightlevel = (cab.bLight == false ? 0.f : cab.bLightDim == true ? 0.4f : 1.f) * (mvOccupied->Power110vIsAvailable ? 1.f : 0.5f); + + if (cab.LightLevel != cablightlevel) + { + cab.LightLevel = cablightlevel; + DynamicObject->set_cab_lights(cabidx, cab.LightLevel); + } + if (cabidx == iCabn) + { + DynamicObject->InteriorLightLevel = cablightlevel; + } + + ++cabidx; + } + } + + // anti slip system activation, maintained while the control button is down + if (mvOccupied->BrakeSystem != TBrakeSystem::ElectroPneumatic && ggAntiSlipButton.GetDesiredValue() > 0.95) + { + mvControlled->AntiSlippingBrake(); + } + // screens + + if (!FreeFlyModeFlag && simulation::Train == this) // don't bother if we're outside + { + update_screens(Deltatime); + update_script_screens(); + } + + // update direction relay + if (prevBatState != mvOccupied->Power24vIsAvailable) + SetupDirectionRelays(); + if (prevDirection != mvOccupied->DirActive) + UpdateDirectionRelays(); + + prevBatState = mvOccupied->Power24vIsAvailable; + prevDirection = mvOccupied->DirActive; + + // sounds + update_sounds(Deltatime); + + return true; //(DynamicObject->Update(dt)); +} // koniec update + +void TTrain::UpdateDirectionRelays() +{ + if (mvOccupied->DirActive < 0 && mvOccupied->Power24vIsAvailable) // wstecz + Dynamic()->sDirectionRelayR.play(); + if (mvOccupied->DirActive == 0 && mvOccupied->Power24vIsAvailable) // neutral + Dynamic()->sDirectionRelayN.play(); + if (mvOccupied->DirActive > 0 && mvOccupied->Power24vIsAvailable) // przod + Dynamic()->sDirectionRelayD.play(); +} + +void TTrain::SetupDirectionRelays() +{ + if (mvOccupied->Power24vIsAvailable) + { + if (mvOccupied->DirActive < 0 && mvOccupied->Power24vIsAvailable) // wstecz + Dynamic()->sDirectionRelayR.play(); + if (mvOccupied->DirActive > 0 && mvOccupied->Power24vIsAvailable) // przod + Dynamic()->sDirectionRelayD.play(); + } + else if (mvOccupied->DirActive != 0) // neutral + Dynamic()->sDirectionRelayN.play(); +} From 04f76951f52340f1bac8e6118bfecacedda4a7f4 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sat, 28 Nov 2026 15:23:36 +0100 Subject: [PATCH 019/123] refactor(physics): the diesel engine, the torque converter and the retarder are components of their own TMoverParameters held some 80 fields of the diesel engine and its hydraulic transmission among its other 600, named dizel_*, hydro_TC_* and hydro_R_*. They are now three structures of physics/components/dieselengine.h, with English names: - DieselEngine diesel: the definition (maxMoment, maxRevolutions, minRevolutions, the governor, the clutch, the fuel consumption, the tables) and the state (fill, clutchState, clutchPressure, torque, power, the start up, the fuel consumed) and its heat (EngineHeat, heat_data before) - TorqueConverter torqueConverter: present, the ratios, the lockup, the fill rates, the table, and its state (fill, lockedUp, torqueRatio, the revolutions in and out) - Retarder retarder: present, its placement, torque, power, fill rates, clutch, and its state The .fiz keywords, the keys of the dictionaries of the Python screens and the names of the golden channels (dizel_fill...) are unchanged; only the C++ names changed. The functions of the engine (dizel_Update, dizel_Momentum...) stay members of TMoverParameters for now. No change in behaviour: 1144/1144 tests, golden traces exact against staging 62f7a29b. --- application/driverhints.cpp | 4 +- application/driveruipanels.cpp | 50 ++-- physics/components/commands.cpp | 2 +- physics/components/diesel.cpp | 446 ++++++++++++++-------------- physics/components/dieselengine.h | 185 ++++++++++++ physics/components/drive.cpp | 12 +- physics/components/electrics.cpp | 8 +- physics/components/fizparser.cpp | 6 +- physics/components/fizsections.cpp | 174 +++++------ physics/mover.h | 162 +--------- rendering/particles.cpp | 10 +- simulation/blackboxrecorder.cpp | 12 +- tests/unit/golden.cpp | 2 +- tests/unit/invariants.cpp | 8 +- tests/unit/test_cab.cpp | 2 +- tests/unit/test_diesel.cpp | 34 +-- tests/unit/test_engine_shutdown.cpp | 6 +- tests/unit/test_engine_start.cpp | 4 +- tests/unit/test_oil_pump.cpp | 4 +- tests/unit/test_smoke.cpp | 26 +- vehicle/ai/consist.cpp | 2 +- vehicle/ai/controls.cpp | 10 +- vehicle/ai/engine.cpp | 2 +- vehicle/ai/physicslog.cpp | 8 +- vehicle/cab/setup.cpp | 8 +- vehicle/cab/update.cpp | 36 +-- vehicle/dynamic/lifecycle.cpp | 4 +- vehicle/dynamic/sounds.cpp | 36 +-- vehicle/dynamic/visual.cpp | 8 +- vehicle/enginestart.cpp | 2 +- vehicle/smoke.cpp | 4 +- vehicle/smoke.h | 2 +- widgets/vehicleparams.cpp | 6 +- 33 files changed, 660 insertions(+), 625 deletions(-) create mode 100644 physics/components/dieselengine.h diff --git a/application/driverhints.cpp b/application/driverhints.cpp index 890628964..e00158bc0 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -725,7 +725,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return mvControlling->dizel_heat.auxiliary_water_circuit == false || mvControlling->WaterCircuitsLink == true; } ); + return mvControlling->diesel.heat.auxiliary_water_circuit == false || mvControlling->WaterCircuitsLink == true; } ); break; } case driver_hint::watercircuitslinkoff: { @@ -736,7 +736,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return mvControlling->dizel_heat.auxiliary_water_circuit == false || mvControlling->WaterCircuitsLink == false; } ); + return mvControlling->diesel.heat.auxiliary_water_circuit == false || mvControlling->WaterCircuitsLink == false; } ); break; } case driver_hint::waittemperaturetoolow: { diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index cb9f9e6d8..a6fd2ee8b 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -900,8 +900,8 @@ debug_panel::update_section_vehicle( std::vector &Output ) { mover.RventRot * 60, std::abs( mover.MotorBlowers[end::front].revolutions ), std::abs( mover.MotorBlowers[end::rear].revolutions ), - mover.dizel_heat.rpmw, - mover.dizel_heat.rpmw2 ); + mover.diesel.heat.rpmw, + mover.diesel.heat.rpmw2 ); std::string textline { m_buffer.data() }; @@ -909,11 +909,11 @@ debug_panel::update_section_vehicle( std::vector &Output ) { std::snprintf( m_buffer.data(), m_buffer.size(), STR_C("\nTemperatures:\n engine: %.2f, oil: %.2f, water: %.2f%c%.2f"), - mover.dizel_heat.Ts, - mover.dizel_heat.To, - mover.dizel_heat.temperatura1, + mover.diesel.heat.Ts, + mover.diesel.heat.To, + mover.diesel.heat.temperatura1, mover.WaterCircuitsLink ? '-' : '|', - mover.dizel_heat.temperatura2 ); + mover.diesel.heat.temperatura2 ); textline += m_buffer.data(); } @@ -1122,22 +1122,22 @@ debug_panel::update_section_engine( std::vector &Output ) const { double fuel_mean = 0.0; if (mover.DistCounter > 0.5) { - fuel_mean = 100 * mover.dizel_FuelConsumptedTotal / mover.DistCounter; + fuel_mean = 100 * mover.diesel.fuelConsumedTotal / mover.DistCounter; } std::string parameterstext = "param value"; std::vector< std::pair > const paramvalues { { " rpm: ", mover.enrot * 60.0 }, - { "efill: ", mover.dizel_fill }, - { "etorq: ", mover.dizel_Torque }, - { "power: ", mover.dizel_Power }, - { "f_act: ", mover.dizel_FuelConsumptionActual }, - { "f_tot: ", mover.dizel_FuelConsumptedTotal }, + { "efill: ", mover.diesel.fill }, + { "etorq: ", mover.diesel.torque }, + { "power: ", mover.diesel.power }, + { "f_act: ", mover.diesel.fuelConsumptionActual }, + { "f_tot: ", mover.diesel.fuelConsumedTotal }, { "fmean: ", fuel_mean }, - { "creal: ", mover.dizel_engage }, - { "cdesi: ", mover.dizel_engagestate }, - { "cdelt: ", mover.dizel_engagedeltaomega }, - { "gears: ", mover.dizel_automaticgearstatus} }; + { "creal: ", mover.diesel.clutchPressure }, + { "cdesi: ", mover.diesel.clutchState }, + { "cdelt: ", mover.diesel.clutchSlip }, + { "gears: ", mover.diesel.automaticGearShift} }; for( auto const &[parametername, parametervalue] : paramvalues ) { parameterstext += "\n" + parametername + to_string( parametervalue, 2, 9 ); } @@ -1145,15 +1145,15 @@ debug_panel::update_section_engine( std::vector &Output ) const { parameterstext = "hydro value"; std::vector< std::pair > const hydrovalues { - { "hTCnI: ", mover.hydro_TC_nIn }, - { "hTCnO: ", mover.hydro_TC_nOut }, - { "hTCTM: ", mover.hydro_TC_TMRatio }, - { "hTCTI: ", mover.hydro_TC_TorqueIn }, - { "hTCTO: ", mover.hydro_TC_TorqueOut }, - { "hTCfl: ", mover.hydro_TC_Fill }, - { "hRtFl: ", mover.hydro_R_Fill } , - { " hRtn: ", mover.hydro_R_n } , - { "hRtTq: ", mover.hydro_R_Torque } + { "hTCnI: ", mover.torqueConverter.revolutionsIn }, + { "hTCnO: ", mover.torqueConverter.revolutionsOut }, + { "hTCTM: ", mover.torqueConverter.torqueRatio }, + { "hTCTI: ", mover.torqueConverter.torqueIn }, + { "hTCTO: ", mover.torqueConverter.torqueOut }, + { "hTCfl: ", mover.torqueConverter.fill }, + { "hRtFl: ", mover.retarder.fill } , + { " hRtn: ", mover.retarder.revolutions } , + { "hRtTq: ", mover.retarder.torque } }; for( auto const &[parametername, parametervalue] : hydrovalues ) { diff --git a/physics/components/commands.cpp b/physics/components/commands.cpp index 57d33dc8e..8a1ca64c5 100644 --- a/physics/components/commands.cpp +++ b/physics/components/commands.cpp @@ -463,7 +463,7 @@ bool TMoverParameters::RunPumpsCommand(VehicleCommand const Command, double CVal } else if (Command == VehicleCommand::waterCircuitsLinkSwitch) { - if (true == dizel_heat.auxiliary_water_circuit) + if (true == diesel.heat.auxiliary_water_circuit) { // can only link circuits if the vehicle has more than one of them WaterCircuitsLink = CValue1 == 1; diff --git a/physics/components/diesel.cpp b/physics/components/diesel.cpp index 0be62d9a2..8879fdd6e 100644 --- a/physics/components/diesel.cpp +++ b/physics/components/diesel.cpp @@ -59,11 +59,11 @@ void TMoverParameters::WaterHeaterCheck(double const /*Timestep*/) { WaterHeater.is_active = false == WaterHeater.is_damaged && true == (Power24vIsAvailable || Power110vIsAvailable) && true == WaterHeater.is_enabled && true == WaterHeater.breaker && - (WaterHeater.is_active || WaterHeater.config.temp_min < 0 || dizel_heat.temperatura1 < WaterHeater.config.temp_min); + (WaterHeater.is_active || WaterHeater.config.temp_min < 0 || diesel.heat.temperatura1 < WaterHeater.config.temp_min); WaterHeater.is_damaged = true == WaterHeater.is_damaged || (true == WaterHeater.is_active && false == WaterPump.is_active); - if (WaterHeater.config.temp_max > 0 && dizel_heat.temperatura1 > WaterHeater.config.temp_max) + if (WaterHeater.config.temp_max > 0 && diesel.heat.temperatura1 > WaterHeater.config.temp_max) { WaterHeater.is_active = false; } @@ -76,8 +76,8 @@ void TMoverParameters::FuelPumpCheck(double const /*Timestep*/) FuelPump.is_active = true == (Power24vIsAvailable || Power110vIsAvailable) && false == FuelPump.is_disabled && (FuelPump.is_active || (FuelPump.start_type == manual ? FuelPump.is_enabled : - FuelPump.start_type == automatic ? dizel_startup || Mains : - FuelPump.start_type == manualwithautofallback ? FuelPump.is_enabled || dizel_startup || Mains : + FuelPump.start_type == automatic ? diesel.startupRequested || Mains : + FuelPump.start_type == manualwithautofallback ? FuelPump.is_enabled || diesel.startupRequested || Mains : false)); // shouldn't ever get this far but, eh } @@ -87,8 +87,8 @@ void TMoverParameters::OilPumpCheck(double const Timestep) OilPump.is_active = true == (Power24vIsAvailable || Power110vIsAvailable) && false == Mains && false == OilPump.is_disabled && (OilPump.is_active || (OilPump.start_type == start_t::manual ? OilPump.is_enabled : - OilPump.start_type == start_t::automatic ? dizel_startup : - OilPump.start_type == start_t::manualwithautofallback ? OilPump.is_enabled || dizel_startup : + OilPump.start_type == start_t::automatic ? diesel.startupRequested : + OilPump.start_type == start_t::manualwithautofallback ? OilPump.is_enabled || diesel.startupRequested : false)); // shouldn't ever get this far but, eh auto const minpressure{OilPump.pressure_minimum > 0.f ? OilPump.pressure_minimum : 0.15f}; // arbitrary fallback value @@ -220,7 +220,7 @@ bool TMoverParameters::WaterHeaterSwitch(bool State, range_t const Notify) bool TMoverParameters::WaterCircuitsLinkSwitch(bool State, range_t const Notify) { - if (false == dizel_heat.auxiliary_water_circuit) + if (false == diesel.heat.auxiliary_water_circuit) { // can't link the circuits if the vehicle only has one return false; @@ -341,12 +341,12 @@ double TMoverParameters::UpdateEngineRevolutions(double dt, double &dtrans, doub else { tmp = 0.0; - dizel_fill = 0.0; + diesel.fill = 0.0; } if (enrot != tmp) { - enrot = safe_clamp(enrot + dt / dizel_AIM * (enrot < tmp ? 1.0 : -1.0 * dizel_RevolutionsDecreaseRate), // NOTE: revolutions typically drop faster than they rise + enrot = safe_clamp(enrot + dt / diesel.shaftInertia * (enrot < tmp ? 1.0 : -1.0 * diesel.revolutionsDecreaseRate), // NOTE: revolutions typically drop faster than they rise 0.0, std::max(tmp, enrot)); if (std::abs(tmp - enrot) < 0.001) { @@ -362,7 +362,7 @@ double TMoverParameters::UpdateEngineRevolutions(double dt, double &dtrans, doub else dtrans = Transmision.Ratio * motor_param(ScndCtrlActualPos).mIsat; - dmoment = dizel_Momentum(dizel_fill, dtrans * nrot * DirActive, dt); // oblicza tez enrot + dmoment = dizel_Momentum(diesel.fill, dtrans * nrot * DirActive, dt); // oblicza tez enrot break; } default: @@ -390,15 +390,15 @@ double TMoverParameters::DieselElectricTargetRevolutions() // bump engine revolutions up if needed, when heating is on tmp = std::max(tmp, std::min(EngineMaxRPM(), EngineHeatingRPM) / 60.0); } - // NOTE: fake dizel_fill calculation for the sake of smoke emitter which uses this parameter to determine smoke opacity - dizel_fill = std::clamp(0.2 + 0.35 * (tmp - enrot) + 0.5 * (std::abs(Im) / DElist[MainCtrlPosNo].Imax), 0.05, 1.0); + // NOTE: fake diesel.fill calculation for the sake of smoke emitter which uses this parameter to determine smoke opacity + diesel.fill = std::clamp(0.2 + 0.35 * (tmp - enrot) + 0.5 * (std::abs(Im) / DElist[MainCtrlPosNo].Imax), 0.05, 1.0); return tmp; } void TMoverParameters::DieselEngineTractionForce(double dt, double const dmoment, double const dtrans) { Mw = dmoment * dtrans * Transmision.Efficiency; // dmoment i dtrans policzone przy okazji enginerotation - if (hydro_R && hydro_R_Placement == 0) + if (retarder.present && retarder.placement == 0) Mw -= dizel_MomentumRetarder(nrot * Transmision.Ratio, dt) * Transmision.Ratio * Transmision.Efficiency; Fw = Mw * 2.0 / WheelDiameter / NPoweredAxles; Ft = Fw * NPoweredAxles; // sila trakcyjna @@ -692,9 +692,9 @@ void TMoverParameters::apply_dieselelectric_dynamic_brake(double const dt) // ************************************************************************************************* bool TMoverParameters::dizel_EngageSwitch(double state) { - if (EngineType == TEngineType::DieselEngine && state <= 1 && state >= 0 && state != dizel_engagestate) + if (EngineType == TEngineType::DieselEngine && state <= 1 && state >= 0 && state != diesel.clutchState) { - dizel_engagestate = state; + diesel.clutchState = state; return true; } else @@ -711,24 +711,24 @@ bool TMoverParameters::dizel_EngageChange(double dt) bool DEC; DEC = false; - if (dizel_engage - dizel_engagestate > 0) + if (diesel.clutchPressure - diesel.clutchState > 0) engagespeed = engagedownspeed; else engagespeed = engageupspeed; if (dt > 0.2) dt = 0.1; - if (abs(dizel_engage - dizel_engagestate) < 0.11) + if (abs(diesel.clutchPressure - diesel.clutchState) < 0.11) { - if (dizel_engage != dizel_engagestate) + if (diesel.clutchPressure != diesel.clutchState) { DEC = true; - dizel_engage = dizel_engagestate; + diesel.clutchPressure = diesel.clutchState; } // else OK:=false; //już jest false } else { - dizel_engage = dizel_engage + engagespeed * dt * (dizel_engagestate - dizel_engage); + diesel.clutchPressure = diesel.clutchPressure + engagespeed * dt * (diesel.clutchState - diesel.clutchPressure); // OK:=false; } // dizel_EngageChange:=OK; @@ -765,24 +765,24 @@ bool TMoverParameters::dizel_AutoGearCheck(void) bool TMoverParameters::dizel_GearShiftCheck(double const VelUp, double const VelDown) { auto OK{false}; - if (RList[MainCtrlPos].Mn == 0 && !hydro_TC) + if (RList[MainCtrlPos].Mn == 0 && !torqueConverter.present) { - if (dizel_engagestate > 0) + if (diesel.clutchState > 0) dizel_EngageSwitch(0); if (IsMainCtrlNoPowerPos() && ScndCtrlActualPos > 0) - dizel_automaticgearstatus = -1; + diesel.automaticGearShift = -1; } else { OK = dizel_GearShiftRequest(VelUp, VelDown); } - if (dizel_engage < 0.1 && dizel_automaticgearstatus != 0) + if (diesel.clutchPressure < 0.1 && diesel.automaticGearShift != 0) { - if (dizel_automaticgearstatus == 1) + if (diesel.automaticGearShift == 1) ScndCtrlActualPos++; else ScndCtrlActualPos--; - dizel_automaticgearstatus = 0; + diesel.automaticGearShift = 0; dizel_EngageSwitch(1.0); OK = true; } @@ -793,14 +793,14 @@ bool TMoverParameters::dizel_GearShiftCheck(double const VelUp, double const Vel bool TMoverParameters::dizel_GearShiftRequest(double const VelUp, double const VelDown) { auto OK{false}; - if (motor_param(ScndCtrlActualPos).AutoSwitch && dizel_automaticgearstatus == 0) // sprawdz czy zmienic biegi + if (motor_param(ScndCtrlActualPos).AutoSwitch && diesel.automaticGearShift == 0) // sprawdz czy zmienic biegi { if (Vel > VelUp) { // shift up if (ScndCtrlActualPos < ScndCtrlPosNo) { - dizel_automaticgearstatus = 1; + diesel.automaticGearShift = 1; OK = true; } } @@ -809,7 +809,7 @@ bool TMoverParameters::dizel_GearShiftRequest(double const VelUp, double const V // shift down if (ScndCtrlActualPos > 0) { - dizel_automaticgearstatus = -1; + diesel.automaticGearShift = -1; OK = true; } } @@ -824,7 +824,7 @@ void TMoverParameters::dizel_ClutchCheck() { dizel_ClutchByIntegratedController(); } - else if (dizel_automaticgearstatus == 0) // ustaw cisnienie w silowniku sprzegla} + else if (diesel.automaticGearShift == 0) // ustaw cisnienie w silowniku sprzegla} dizel_ClutchByController(); else dizel_EngageSwitch(0.0); @@ -846,25 +846,25 @@ void TMoverParameters::dizel_ClutchByController() dizel_EngageSwitch(1.0); break; case 3: - if (Vel > dizel_minVelfullengage) + if (Vel > diesel.fullEngageMinVelocity) dizel_EngageSwitch(1.0); else dizel_EngageSwitch(0.5); break; case 4: - if (Vel > dizel_minVelfullengage) + if (Vel > diesel.fullEngageMinVelocity) dizel_EngageSwitch(1.0); else dizel_EngageSwitch(0.66); break; case 5: - if (Vel > dizel_minVelfullengage) + if (Vel > diesel.fullEngageMinVelocity) dizel_EngageSwitch(1.0); else dizel_EngageSwitch(0.35 * (1 + RList[MainCtrlPos].R) * RList[MainCtrlPos].R); break; default: - if (hydro_TC && hydro_TC_Fill > 0.01) + if (torqueConverter.present && torqueConverter.fill > 0.01) dizel_EngageSwitch(1.0); else dizel_EngageSwitch(0.0); @@ -874,11 +874,11 @@ void TMoverParameters::dizel_ClutchByController() // the clutch of the integrated controller: in with the converter filled or the power asked, half in for the retarder void TMoverParameters::dizel_ClutchByIntegratedController() { - if (dizel_automaticgearstatus == 0) + if (diesel.automaticGearShift == 0) { - if ((hydro_TC && hydro_TC_Fill > 0.01) || eimic_real > 0.005) + if ((torqueConverter.present && torqueConverter.fill > 0.01) || eimic_real > 0.005) dizel_EngageSwitch(1.0); - else if (Vel > hydro_R_EngageVel && hydro_R && hydro_R_Fill > 0.01) + else if (Vel > retarder.engageVelocity && retarder.present && retarder.fill > 0.01) dizel_EngageSwitch(0.5); else dizel_EngageSwitch(0.0); @@ -900,7 +900,7 @@ bool TMoverParameters::dizel_StartupCheck() engineisready = false; // if( FuelPump.start_type == start_t::manual ) { // with manual pump control startup procedure is done only once per starter switch press - dizel_startup = false; + diesel.startupRequested = false; // } } // test the oil pump @@ -910,15 +910,15 @@ bool TMoverParameters::dizel_StartupCheck() if (OilPump.start_type == start_t::manual) { // with manual pump control startup procedure is done only once per starter switch press - dizel_startup = false; + diesel.startupRequested = false; } } // test the water circuits and water temperature - if (true == dizel_heat.PA) + if (true == diesel.heat.PA) { engineisready = false; // TBD, TODO: reset startup procedure depending on pump and heater control mode - dizel_startup = false; + diesel.startupRequested = false; } return engineisready; @@ -936,30 +936,30 @@ bool TMoverParameters::dizel_Update(double dt) OilPumpCheck(dt); FuelPumpCheck(dt); // the engine being started fires once the starter has turned it a while; one stopped meanwhile starts over - dizel_FiringCountdown = (Mains ? std::max(0.0, dizel_FiringCountdown - dt) : 0.0); + diesel.firingCountdown = (Mains ? std::max(0.0, diesel.firingCountdown - dt) : 0.0); - if (true == dizel_startup && true == dizel_StartupCheck()) + if (true == diesel.startupRequested && true == dizel_StartupCheck()) { - dizel_ignition = true; + diesel.ignitionRequested = true; } - if (true == dizel_ignition && LastSwitchingTime >= InitialCtrlDelay) + if (true == diesel.ignitionRequested && LastSwitchingTime >= InitialCtrlDelay) { - dizel_startup = false; - dizel_ignition = false; + diesel.startupRequested = false; + diesel.ignitionRequested = false; // TODO: split engine and main circuit state indicator in two separate flags LastSwitchingTime = 0; Timer::subsystem.switching.note(Timer::switching_counter::diesel, this, &TypeName, &Name); Mains = true; - dizel_spinup = true; - dizel_FiringCountdown = dizel_SmokeDelay; + diesel.spinningUp = true; + diesel.firingCountdown = diesel.smokeDelay; enrot = std::max(enrot, 0.35 * ( // TODO: dac zaleznie od temperatury i baterii - EngineType == TEngineType::DieselEngine ? dizel_nmin : DElist[0].RPM / 60.0)); + EngineType == TEngineType::DieselEngine ? diesel.minRevolutions : DElist[0].RPM / 60.0)); } - dizel_spinup = dizel_spinup && Mains && enrot < 0.95 * (EngineType == TEngineType::DieselEngine ? dizel_nmin : DElist[0].RPM / 60.0); + diesel.spinningUp = diesel.spinningUp && Mains && enrot < 0.95 * (EngineType == TEngineType::DieselEngine ? diesel.minRevolutions : DElist[0].RPM / 60.0); if (true == Mains && false == FuelPump.is_active) { @@ -976,7 +976,7 @@ bool TMoverParameters::dizel_Update(double dt) dizel_EngageChange(dt); DU = dizel_AutoGearCheck(); double const fillspeed{2}; - dizel_fill = dizel_fill + fillspeed * dt * (dizel_fillcheck(MainCtrlPos, dt) - dizel_fill); + diesel.fill = diesel.fill + fillspeed * dt * (dizel_fillcheck(MainCtrlPos, dt) - diesel.fill); } dizel_Heat(dt); @@ -995,7 +995,7 @@ double TMoverParameters::dizel_fillcheck(int mcp, double dt) if (true == Mains && MainCtrlPosNo > 0 && true == FuelPump.is_active) { - if (true == dizel_ignition && LastSwitchingTime >= 0.9 * InitialCtrlDelay) + if (true == diesel.ignitionRequested && LastSwitchingTime >= 0.9 * InitialCtrlDelay) { // wzbogacenie przy rozruchu // NOTE: ignition flag is reset before this code is executed @@ -1011,11 +1011,11 @@ double TMoverParameters::dizel_fillcheck(int mcp, double dt) } else { - dizel_nreg_max = dizel_nmax; + diesel.governorMaxRevolutions = diesel.maxRevolutions; realfill = RList[mcp].R; } } - if (dizel_nmax_cutoff > 0) + if (diesel.cutoffRevolutions > 0) { realfill = dizel_GovernorFill(mcp, realfill); } @@ -1029,24 +1029,24 @@ double TMoverParameters::dizel_DigitalFill(double dt) { double realfill; realfill = std::max(0.0, std::min(eimic_real, 1 - motor_param(ScndCtrlActualPos).Isat)); - if (eimic_real > 0.005 && !hydro_TC_Lockup) + if (eimic_real > 0.005 && !torqueConverter.lockedUp) { - dizel_nreg_min = std::min(dizel_nreg_min + 2.5 * dt, dizel_nmin_hdrive + eimic_real * dizel_nmin_hdrive_factor); + diesel.governorMinRevolutions = std::min(diesel.governorMinRevolutions + 2.5 * dt, diesel.hydraulicMinRevolutions + eimic_real * diesel.hydraulicMinRevolutionsFactor); } else { - if (Vel < hydro_R_EngageVel && hydro_R && hydro_R_Fill > 0.01) - dizel_nreg_min = std::min(dizel_nreg_min + 5.0 * dt, dizel_nmin_retarder); + if (Vel < retarder.engageVelocity && retarder.present && retarder.fill > 0.01) + diesel.governorMinRevolutions = std::min(diesel.governorMinRevolutions + 5.0 * dt, diesel.retarderRevolutions); else - dizel_nreg_min = dizel_nmin; + diesel.governorMinRevolutions = diesel.minRevolutions; } - if (!dizel_vel2nmax_Table.empty() && !hydro_TC_Lockup) + if (!diesel.speedMaxRevolutionsTable.empty() && !torqueConverter.lockedUp) { - dizel_nreg_max = std::min(std::min(dizel_nreg_max, enrot) + dizel_nreg_acc * dt, TableInterpolation(dizel_vel2nmax_Table, Vel)); + diesel.governorMaxRevolutions = std::min(std::min(diesel.governorMaxRevolutions, enrot) + diesel.governorAcceleration * dt, TableInterpolation(diesel.speedMaxRevolutionsTable, Vel)); } else { - dizel_nreg_max = dizel_nmax; + diesel.governorMaxRevolutions = diesel.maxRevolutions; } return realfill; } @@ -1056,12 +1056,12 @@ double TMoverParameters::dizel_GovernorFill(int const mcp, double realfill) cons { auto nreg{0.0}; if (EIMCtrlType > 0) - nreg = eimic_real > 0.005 ? dizel_nreg_max : dizel_nmin; + nreg = eimic_real > 0.005 ? diesel.governorMaxRevolutions : diesel.minRevolutions; else nreg = dizel_GovernorRevolutions(mcp, realfill); if (enrot > nreg) // nad predkoscia regulatora zeruj dawke realfill = 0; - if (enrot < dizel_nreg_min && RList[mcp].R > 0.001) // jesli ponizej biegu jalowego i niezerowa dawka, to dawaj pelna + if (enrot < diesel.governorMinRevolutions && RList[mcp].R > 0.001) // jesli ponizej biegu jalowego i niezerowa dawka, to dawaj pelna realfill = 1; return realfill; } @@ -1075,31 +1075,31 @@ double TMoverParameters::dizel_GovernorRevolutions(int const mcp, double &realfi { case 0: case 1: - nreg = dizel_nmin; + nreg = diesel.minRevolutions; break; case 2: - if (dizel_automaticgearstatus == 0 && true /*(!hydro_TC) || (dizel_engage>dizel_fill)*/) - nreg = dizel_nreg_max; + if (diesel.automaticGearShift == 0 && true /*(!torqueConverter.present) || (diesel.clutchPressure>diesel.fill)*/) + nreg = diesel.governorMaxRevolutions; else - nreg = dizel_nmin; + nreg = diesel.minRevolutions; break; case 3: - if (dizel_automaticgearstatus == 0 && Vel > dizel_minVelfullengage) - nreg = dizel_nreg_max; + if (diesel.automaticGearShift == 0 && Vel > diesel.fullEngageMinVelocity) + nreg = diesel.governorMaxRevolutions; else - nreg = dizel_nmin; + nreg = diesel.minRevolutions; break; case 4: - if (dizel_automaticgearstatus == 0 && Vel > dizel_minVelfullengage) - nreg = dizel_nmax; + if (diesel.automaticGearShift == 0 && Vel > diesel.fullEngageMinVelocity) + nreg = diesel.maxRevolutions; else - nreg = dizel_nmin * 0.75 + dizel_nreg_max * 0.25; + nreg = diesel.minRevolutions * 0.75 + diesel.governorMaxRevolutions * 0.25; break; case 5: - if (Vel > dizel_minVelfullengage) - nreg = dizel_nreg_max; + if (Vel > diesel.fullEngageMinVelocity) + nreg = diesel.governorMaxRevolutions; else - nreg = dizel_nmin + 0.8 * (dizel_nreg_max - dizel_nmin) * RList[mcp].R; + nreg = diesel.minRevolutions + 0.8 * (diesel.governorMaxRevolutions - diesel.minRevolutions) * RList[mcp].R; break; default: realfill = 0; // sluczaj @@ -1126,51 +1126,51 @@ double TMoverParameters::dizel_Momentum(double Fill, double n, double dt) n = n * CabActive; if (motor_param(ScndCtrlActualPos).mIsat < 0.001 || DirActive == 0) n = enrot; - friction = dizel_engagefriction; - hydro_TC_nIn = enrot; // wal wejsciowy przetwornika momentu - hydro_TC_nOut = dizel_n_old; // wal wyjsciowy przetwornika momentu + friction = diesel.clutchFriction; + torqueConverter.revolutionsIn = enrot; // wal wejsciowy przetwornika momentu + torqueConverter.revolutionsOut = diesel.previousRevolutions; // wal wyjsciowy przetwornika momentu if (enrot > 0) { - if (dizel_Momentum_Table.size() > 1) + if (diesel.momentTable.size() > 1) { - Moment = TableInterpolation(dizel_Momentum_Table, enrot) * Fill - dizel_Mstand; + Moment = TableInterpolation(diesel.momentTable, enrot) * Fill - diesel.standingMoment; } else { - Moment = (dizel_Mmax - (dizel_Mmax - dizel_Mnmax) * square((enrot - dizel_nMmax) / (dizel_nMmax - dizel_nmax))) * Fill - dizel_Mstand; + Moment = (diesel.maxMoment - (diesel.maxMoment - diesel.maxRevolutionsMoment) * square((enrot - diesel.maxMomentRevolutions) / (diesel.maxMomentRevolutions - diesel.maxRevolutions))) * Fill - diesel.standingMoment; } Mm = Moment; - dizel_FuelConsumptionActual = dizel_FuelConsumption * enrot * Fill; - dizel_FuelConsumptedTotal += dizel_FuelConsumptionActual * dt / 3600.0; - if (hydro_R && hydro_R_Placement == 2) + diesel.fuelConsumptionActual = diesel.fuelConsumption * enrot * Fill; + diesel.fuelConsumedTotal += diesel.fuelConsumptionActual * dt / 3600.0; + if (retarder.present && retarder.placement == 2) Moment -= dizel_MomentumRetarder(enrot, dt); } else { - Moment = -dizel_Mstand; + Moment = -diesel.standingMoment; } - if (enrot < dizel_nmin / 10.0 && eAngle < M_PI_2) + if (enrot < diesel.minRevolutions / 10.0 && eAngle < M_PI_2) { // wstrzymywanie przy malych obrotach - Moment -= dizel_Mstand; + Moment -= diesel.standingMoment; } - if (true == dizel_spinup) - Moment += dizel_Mstand / (0.3 + std::max(0.0, enrot / dizel_nmin)); // rozrusznik + if (true == diesel.spinningUp) + Moment += diesel.standingMoment / (0.3 + std::max(0.0, enrot / diesel.minRevolutions)); // rozrusznik - dizel_Torque = Moment; + diesel.torque = Moment; hydro_TCFillCheck(dt); // obliczanie momentow poszczegolnych sprzegiel // sprzeglo glowne (skrzynia biegow) - TorqueC = dizel_engageMaxForce * dizel_engage * dizel_engageDia * friction; + TorqueC = diesel.clutchMaxForce * diesel.clutchPressure * diesel.clutchDiameter * friction; - if (hydro_TC) // jesli hydro + if (torqueConverter.present) // jesli hydro { hydro_TCTorque(); - TorqueH = hydro_TC_TorqueOut; - TorqueL = hydro_TC_LockupTorque * hydro_TC_LockupRate; + TorqueH = torqueConverter.torqueOut; + TorqueL = torqueConverter.lockupTorque * torqueConverter.lockupRate; } else { @@ -1179,34 +1179,34 @@ double TMoverParameters::dizel_Momentum(double Fill, double n, double dt) } // sprawdzanie dociskow poszczegolnych sprzegiel - if (abs(Moment) > std::min(TorqueC, TorqueL + abs(hydro_TC_TorqueIn)) || abs(dizel_n_old - enrot) > 0.1) // slizga sie z powodu roznic predkosci albo przekroczenia momentu + if (abs(Moment) > std::min(TorqueC, TorqueL + abs(torqueConverter.torqueIn)) || abs(diesel.previousRevolutions - enrot) > 0.1) // slizga sie z powodu roznic predkosci albo przekroczenia momentu { - dizel_engagedeltaomega = enrot - dizel_n_old; + diesel.clutchSlip = enrot - diesel.previousRevolutions; if (TorqueC > TorqueL) { if (TorqueC > TorqueL + abs(TorqueH)) { - hydro_TC_nOut = n; - gearMoment = TorqueL + abs(TorqueH) * sign(dizel_engagedeltaomega); - enMoment = Moment - (TorqueL + abs(hydro_TC_TorqueIn)) * sign(dizel_engagedeltaomega); + torqueConverter.revolutionsOut = n; + gearMoment = TorqueL + abs(TorqueH) * sign(diesel.clutchSlip); + enMoment = Moment - (TorqueL + abs(torqueConverter.torqueIn)) * sign(diesel.clutchSlip); } else { - hydro_TC_nOut = enrot - (n - enrot) * (TorqueC - TorqueL) / TorqueH; // slizganie proporcjonalne, zeby przetwornik nadrabial - gearMoment = TorqueC * sign(dizel_engagedeltaomega); + torqueConverter.revolutionsOut = enrot - (n - enrot) * (TorqueC - TorqueL) / TorqueH; // slizganie proporcjonalne, zeby przetwornik nadrabial + gearMoment = TorqueC * sign(diesel.clutchSlip); enMoment = Moment - gearMoment; } } else { - hydro_TC_nOut = enrot; - gearMoment = TorqueC*sign(dizel_engagedeltaomega); + torqueConverter.revolutionsOut = enrot; + gearMoment = TorqueC*sign(diesel.clutchSlip); enMoment = Moment - gearMoment; } - eps = enMoment / dizel_AIM; + eps = enMoment / diesel.shaftInertia; newn = enrot + eps * dt; - if ((newn - n) * (enrot - dizel_n_old) < 0 && TorqueC > 0.1) // przejscie przez zero - slizgalo sie i przestało + if ((newn - n) * (enrot - diesel.previousRevolutions) < 0 && TorqueC > 0.1) // przejscie przez zero - slizgalo sie i przestało newn = n; if (newn * enrot <= 0 && eps * enrot < 0) // przejscie przez zero obrotow newn = 0; @@ -1214,16 +1214,16 @@ double TMoverParameters::dizel_Momentum(double Fill, double n, double dt) } else // nie slizga sie (jeszcze) { - dizel_engagedeltaomega = 0; + diesel.clutchSlip = 0; gearMoment = Moment; - double enrot_min = enrot - (std::min(TorqueC, TorqueL + abs(hydro_TC_TorqueIn)) - Moment) / dizel_AIM * dt; - double enrot_max = enrot + (std::min(TorqueC, TorqueL + abs(hydro_TC_TorqueIn)) + Moment) / dizel_AIM * dt; + double enrot_min = enrot - (std::min(TorqueC, TorqueL + abs(torqueConverter.torqueIn)) - Moment) / diesel.shaftInertia * dt; + double enrot_max = enrot + (std::min(TorqueC, TorqueL + abs(torqueConverter.torqueIn)) + Moment) / diesel.shaftInertia * dt; enrot = safe_clamp(n, enrot_min, enrot_max); } - if (hydro_R && hydro_R_Placement == 1) - gearMoment -= dizel_MomentumRetarder(hydro_TC_nOut, dt); + if (retarder.present && retarder.placement == 1) + gearMoment -= dizel_MomentumRetarder(torqueConverter.revolutionsOut, dt); - if (enrot <= 0 && false == dizel_spinup) + if (enrot <= 0 && false == diesel.spinningUp) { // an engine stalling stops those started together with it, once. one already stopped, from its own switch or // another vehicle's, or not started at all, has nothing to stop: it stays quiet, rather than stop every frame @@ -1235,7 +1235,7 @@ double TMoverParameters::dizel_Momentum(double Fill, double n, double dt) enrot = 0; } - dizel_n_old = n; // obecna predkosc katowa na potrzeby kolejnej klatki + diesel.previousRevolutions = n; // obecna predkosc katowa na potrzeby kolejnej klatki return gearMoment; } @@ -1243,37 +1243,37 @@ double TMoverParameters::dizel_Momentum(double Fill, double n, double dt) // the torque converter filled and emptied, and its lockup clutch engaged and released, by the power and the speed void TMoverParameters::hydro_TCFillCheck(double dt) { - if (hydro_TC) // jesli przetwornik momentu + if (torqueConverter.present) // jesli przetwornik momentu { // napelnianie przetwornika bool IsPower = EIMCtrlType > 0 ? eimic_real > 0.005 : MainCtrlPowerPos() > 0; - if (IsPower && Mains && enrot > dizel_nmin * 0.9) - hydro_TC_Fill += hydro_TC_FillRateInc * dt; + if (IsPower && Mains && enrot > diesel.minRevolutions * 0.9) + torqueConverter.fill += torqueConverter.fillRateIncrease * dt; // oproznianie przetwornika - if ((!IsPower && Vel < dizel_maxVelANS) || !Mains || enrot < dizel_nmin * 0.8) - hydro_TC_Fill -= hydro_TC_FillRateDec * dt; + if ((!IsPower && Vel < diesel.converterReleaseVelocity) || !Mains || enrot < diesel.minRevolutions * 0.8) + torqueConverter.fill -= torqueConverter.fillRateDecrease * dt; // obcinanie zakresu - hydro_TC_Fill = std::clamp(hydro_TC_Fill, 0.0, 1.0); + torqueConverter.fill = std::clamp(torqueConverter.fill, 0.0, 1.0); // blokowanie sprzegla blokującego - if (Vel > hydro_TC_LockupSpeed && Mains && enrot > 0.9 * dizel_nmin && IsPower) + if (Vel > torqueConverter.lockupSpeed && Mains && enrot > 0.9 * diesel.minRevolutions && IsPower) { - hydro_TC_Lockup = true; - hydro_TC_LockupRate += hydro_TC_FillRateInc * dt; + torqueConverter.lockedUp = true; + torqueConverter.lockupRate += torqueConverter.fillRateIncrease * dt; } // luzowanie sprzegla blokujacego - if (Vel < (IsPower ? hydro_TC_LockupSpeed : hydro_TC_UnlockSpeed) || !Mains || enrot < 0.8 * dizel_nmin) + if (Vel < (IsPower ? torqueConverter.lockupSpeed : torqueConverter.unlockSpeed) || !Mains || enrot < 0.8 * diesel.minRevolutions) { - hydro_TC_Lockup = false; - hydro_TC_LockupRate -= hydro_TC_FillRateDec * dt; + torqueConverter.lockedUp = false; + torqueConverter.lockupRate -= torqueConverter.fillRateDecrease * dt; } // obcinanie zakresu - hydro_TC_LockupRate = std::clamp(hydro_TC_LockupRate, 0.0, 1.0); + torqueConverter.lockupRate = std::clamp(torqueConverter.lockupRate, 0.0, 1.0); } else { - hydro_TC_Fill = 0.0; - hydro_TC_LockupRate = 0.0; + torqueConverter.fill = 0.0; + torqueConverter.lockupRate = 0.0; } } @@ -1281,29 +1281,29 @@ void TMoverParameters::hydro_TCFillCheck(double dt) void TMoverParameters::hydro_TCTorque() { double HydroTorque = 0; - HydroTorque += hydro_TC_nIn * hydro_TC_nIn * hydro_TC_TorqueInIn; - HydroTorque += (hydro_TC_nIn - hydro_TC_nOut) * hydro_TC_TorqueInOut; - HydroTorque += hydro_TC_nOut * hydro_TC_nOut * hydro_TC_TorqueOutOut; - double nOut2In = hydro_TC_nOut / std::max(0.01, hydro_TC_nIn); - if (hydro_TC_Table.size() > 1) + HydroTorque += torqueConverter.revolutionsIn * torqueConverter.revolutionsIn * torqueConverter.torqueInIn; + HydroTorque += (torqueConverter.revolutionsIn - torqueConverter.revolutionsOut) * torqueConverter.torqueInOut; + HydroTorque += torqueConverter.revolutionsOut * torqueConverter.revolutionsOut * torqueConverter.torqueOutOut; + double nOut2In = torqueConverter.revolutionsOut / std::max(0.01, torqueConverter.revolutionsIn); + if (torqueConverter.table.size() > 1) { - hydro_TC_TMRatio = TableInterpolation(hydro_TC_Table, nOut2In); - hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; - hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill * std::min(1.0, hydro_TC_TMRatio); + torqueConverter.torqueRatio = TableInterpolation(torqueConverter.table, nOut2In); + torqueConverter.torqueOut = HydroTorque * torqueConverter.fill * torqueConverter.torqueRatio; + torqueConverter.torqueIn = HydroTorque * torqueConverter.fill * std::min(1.0, torqueConverter.torqueRatio); } else { - if (nOut2In < hydro_TC_CouplingPoint) + if (nOut2In < torqueConverter.couplingPoint) { - hydro_TC_TMRatio = 1 + (hydro_TC_TMMax - 1) * square(1 - nOut2In / hydro_TC_CouplingPoint); - hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill; - hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; + torqueConverter.torqueRatio = 1 + (torqueConverter.maxTorqueRatio - 1) * square(1 - nOut2In / torqueConverter.couplingPoint); + torqueConverter.torqueIn = HydroTorque * torqueConverter.fill; + torqueConverter.torqueOut = HydroTorque * torqueConverter.fill * torqueConverter.torqueRatio; } else { - hydro_TC_TMRatio = (1 - nOut2In) / (1 - hydro_TC_CouplingPoint); - hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; - hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; + torqueConverter.torqueRatio = (1 - nOut2In) / (1 - torqueConverter.couplingPoint); + torqueConverter.torqueIn = HydroTorque * torqueConverter.fill * torqueConverter.torqueRatio; + torqueConverter.torqueOut = HydroTorque * torqueConverter.fill * torqueConverter.torqueRatio; } } } @@ -1311,46 +1311,46 @@ void TMoverParameters::hydro_TCTorque() double TMoverParameters::dizel_MomentumRetarder(double n, double dt) { double RetarderRequest = Mains ? std::max(0.0, -eimic_real) : 0; - if (hydro_R_WithIndividual) + if (retarder.withIndividual) RetarderRequest = LocalBrakeRatio(); - if (Vel < hydro_R_MinVel) + if (Vel < retarder.minVelocity) RetarderRequest = 0; - if (hydro_R_Placement == 2 && enrot < dizel_nmin) + if (retarder.placement == 2 && enrot < diesel.minRevolutions) { RetarderRequest = 0; } - hydro_R_ClutchActive = !hydro_R_Clutch || RetarderRequest > 0; - if (!hydro_R_Clutch || (hydro_R_ClutchActive && hydro_R_ClutchSpeed == 0)) + retarder.clutchActive = !retarder.hasClutch || RetarderRequest > 0; + if (!retarder.hasClutch || (retarder.clutchActive && retarder.clutchSpeed == 0)) { - hydro_R_n = n * 60; + retarder.revolutions = n * 60; } - else if (hydro_R_ClutchActive) + else if (retarder.clutchActive) { - hydro_R_n = sign(n) * std::min(std::abs(hydro_R_n + hydro_R_ClutchSpeed * dt), std::abs(n * 60)); + retarder.revolutions = sign(n) * std::min(std::abs(retarder.revolutions + retarder.clutchSpeed * dt), std::abs(n * 60)); } else { - hydro_R_n = 0; + retarder.revolutions = 0; } - n = hydro_R_n / 60.f; + n = retarder.revolutions / 60.f; - if (hydro_R_Fill < RetarderRequest) // gdy zadane hamowanie + if (retarder.fill < RetarderRequest) // gdy zadane hamowanie { - hydro_R_Fill = std::min(hydro_R_Fill + hydro_R_FillRateInc * dt, RetarderRequest); + retarder.fill = std::min(retarder.fill + retarder.fillRateIncrease * dt, RetarderRequest); } else { - hydro_R_Fill = std::max(hydro_R_Fill - hydro_R_FillRateDec * dt, RetarderRequest); + retarder.fill = std::max(retarder.fill - retarder.fillRateDecrease * dt, RetarderRequest); } - double Moment = hydro_R_MaxTorque; - if (double pwr = Moment * std::abs(n) * M_PI * 2 * 0.001; pwr > hydro_R_MaxPower) - Moment = Moment * hydro_R_MaxPower / pwr; - double moment_in = n * n * hydro_R_TorqueInIn; - Moment = std::min(moment_in, Moment * hydro_R_Fill); + double Moment = retarder.maxTorque; + if (double pwr = Moment * std::abs(n) * M_PI * 2 * 0.001; pwr > retarder.maxPower) + Moment = Moment * retarder.maxPower / pwr; + double moment_in = n * n * retarder.torqueInIn; + Moment = std::min(moment_in, Moment * retarder.fill); - hydro_R_Torque = Moment; + retarder.torque = Moment; return Moment; } @@ -1360,15 +1360,15 @@ void TMoverParameters::dizel_HeatSet(float const Value) { // TODO: don't include ambient temperature, pull it from environment data instead - dizel_heat.Te = Value; - dizel_heat.Ts = Value; - dizel_heat.To = Value; - dizel_heat.Tsr = Value; - dizel_heat.Twy = Value; - dizel_heat.Tsr2 = Value; - dizel_heat.Twy2 = Value; - dizel_heat.temperatura1 = Value; - dizel_heat.temperatura2 = Value; + diesel.heat.Te = Value; + diesel.heat.Ts = Value; + diesel.heat.To = Value; + diesel.heat.Tsr = Value; + diesel.heat.Twy = Value; + diesel.heat.Tsr2 = Value; + diesel.heat.Twy2 = Value; + diesel.heat.temperatura1 = Value; + diesel.heat.temperatura2 = Value; } // calculates diesel engine temperature and heat transfers @@ -1386,7 +1386,7 @@ void TMoverParameters::dizel_Heat(double const dt) auto const gwmin2{400.0}; auto const gwmax2{4000.0}; - dizel_heat.Te = Global.AirTemperature; + diesel.heat.Te = Global.AirTemperature; auto const engineon{(Mains ? 1 : 0)}; auto const engineoff{(Mains ? 0 : 1)}; @@ -1399,36 +1399,36 @@ void TMoverParameters::dizel_Heat(double const dt) auto const gw2 = engineon * std::lerp(gwmin2, gwmax2, revolutionsfactor) + waterpump * 1000 + engineoff * 200; auto const gwO = std::lerp(gwmin, gwmax, revolutionsfactor); - dizel_heat.water.is_cold = dizel_heat.water.config.temp_min > 0 && dizel_heat.temperatura1 < dizel_heat.water.config.temp_min - (Mains ? 5 : 0); - dizel_heat.water.is_hot = dizel_heat.water.config.temp_max > 0 && dizel_heat.temperatura1 > dizel_heat.water.config.temp_max - (dizel_heat.water.is_hot ? 8 : 0); - dizel_heat.water_aux.is_cold = dizel_heat.water_aux.config.temp_min > 0 && dizel_heat.temperatura2 < dizel_heat.water_aux.config.temp_min - (Mains ? 5 : 0); - dizel_heat.water_aux.is_hot = dizel_heat.water_aux.config.temp_max > 0 && dizel_heat.temperatura2 > dizel_heat.water_aux.config.temp_max - (dizel_heat.water_aux.is_hot ? 8 : 0); - dizel_heat.oil.is_cold = dizel_heat.oil.config.temp_min > 0 && dizel_heat.To < dizel_heat.oil.config.temp_min - (Mains ? 5 : 0); - dizel_heat.oil.is_hot = dizel_heat.oil.config.temp_max > 0 && dizel_heat.To > dizel_heat.oil.config.temp_max - (dizel_heat.oil.is_hot ? 8 : 0); + diesel.heat.water.is_cold = diesel.heat.water.config.temp_min > 0 && diesel.heat.temperatura1 < diesel.heat.water.config.temp_min - (Mains ? 5 : 0); + diesel.heat.water.is_hot = diesel.heat.water.config.temp_max > 0 && diesel.heat.temperatura1 > diesel.heat.water.config.temp_max - (diesel.heat.water.is_hot ? 8 : 0); + diesel.heat.water_aux.is_cold = diesel.heat.water_aux.config.temp_min > 0 && diesel.heat.temperatura2 < diesel.heat.water_aux.config.temp_min - (Mains ? 5 : 0); + diesel.heat.water_aux.is_hot = diesel.heat.water_aux.config.temp_max > 0 && diesel.heat.temperatura2 > diesel.heat.water_aux.config.temp_max - (diesel.heat.water_aux.is_hot ? 8 : 0); + diesel.heat.oil.is_cold = diesel.heat.oil.config.temp_min > 0 && diesel.heat.To < diesel.heat.oil.config.temp_min - (Mains ? 5 : 0); + diesel.heat.oil.is_hot = diesel.heat.oil.config.temp_max > 0 && diesel.heat.To > diesel.heat.oil.config.temp_max - (diesel.heat.oil.is_hot ? 8 : 0); // engine overheat check - dizel_heat.engine_is_hot = dizel_heat.engine_max_temp > 0 && dizel_heat.Ts > dizel_heat.engine_max_temp - (dizel_heat.engine_is_hot ? 8 : 0); + diesel.heat.engine_is_hot = diesel.heat.engine_max_temp > 0 && diesel.heat.Ts > diesel.heat.engine_max_temp - (diesel.heat.engine_is_hot ? 8 : 0); - auto const PT = false == dizel_heat.water.is_cold && false == dizel_heat.water.is_hot && false == dizel_heat.water_aux.is_cold && false == dizel_heat.water_aux.is_hot && - false == dizel_heat.oil.is_cold && false == dizel_heat.oil.is_hot && false == dizel_heat.engine.is_hot /* && ( false == awaria_termostatow ) */ + auto const PT = false == diesel.heat.water.is_cold && false == diesel.heat.water.is_hot && false == diesel.heat.water_aux.is_cold && false == diesel.heat.water_aux.is_hot && + false == diesel.heat.oil.is_cold && false == diesel.heat.oil.is_hot && false == diesel.heat.engine.is_hot /* && ( false == awaria_termostatow ) */ /* || PTp */; auto const PPT = false == PT /* && ( false == PPTp ) */; - dizel_heat.PA = /* ( ( !zamkniecie or niedomkniecie ) and !WBD ) || */ PPT /* || nurnik || ( woda < 7 ) */; + diesel.heat.PA = /* ( ( !zamkniecie or niedomkniecie ) and !WBD ) || */ PPT /* || nurnik || ( woda < 7 ) */; // engine heat transfers - auto const Ge{engineon * (0.21 * dizel_heat.powerfactor * EnginePower + 12) / 3600}; + auto const Ge{engineon * (0.21 * diesel.heat.powerfactor * EnginePower + 12) / 3600}; // TODO: replace fixed heating power cost with more accurate calculation - auto const obciazenie{engineon * (dizel_heat.powerfactor * EnginePower / 950 + (Heating ? HeatingPower : 0) + 70)}; + auto const obciazenie{engineon * (diesel.heat.powerfactor * EnginePower / 950 + (Heating ? HeatingPower : 0) + 70)}; auto const Qd{qs * Ge - obciazenie}; // silnik oddaje czesc ciepla do wody chlodzacej, a takze pewna niewielka czesc do otoczenia, modyfikowane przez okienko - auto const Qs{(Qd - dizel_heat.kfs * (dizel_heat.Ts - dizel_heat.Tsr) - dizel_heat.kfe * /* ( 0.3 + 0.7 * ( dizel_heat.okienko ? 1 : 0 ) ) * */ (dizel_heat.Ts - dizel_heat.Te))}; + auto const Qs{(Qd - diesel.heat.kfs * (diesel.heat.Ts - diesel.heat.Tsr) - diesel.heat.kfe * /* ( 0.3 + 0.7 * ( diesel.heat.okienko ? 1 : 0 ) ) * */ (diesel.heat.Ts - diesel.heat.Te))}; auto const dTss{Qs / Cs}; - dizel_heat.Ts += static_cast(dTss * dt); + diesel.heat.Ts += static_cast(dTss * dt); // oil heat transfers // olej oddaje cieplo do wody gdy krazy przez wymiennik ciepla == wlaczona pompka lub silnik - auto const dTo{(dizel_heat.auxiliary_water_circuit ? (dizel_heat.kfo * (dizel_heat.Ts - dizel_heat.To) - dizel_heat.kfo2 * (dizel_heat.To - dizel_heat.Tsr2)) / (gwO * Co) : - (dizel_heat.kfo * (dizel_heat.Ts - dizel_heat.To) - dizel_heat.kfo2 * (dizel_heat.To - dizel_heat.Tsr)) / (gwO * Co))}; - dizel_heat.To += static_cast(dTo * dt); + auto const dTo{(diesel.heat.auxiliary_water_circuit ? (diesel.heat.kfo * (diesel.heat.Ts - diesel.heat.To) - diesel.heat.kfo2 * (diesel.heat.To - diesel.heat.Tsr2)) / (gwO * Co) : + (diesel.heat.kfo * (diesel.heat.Ts - diesel.heat.To) - diesel.heat.kfo2 * (diesel.heat.To - diesel.heat.Tsr)) / (gwO * Co))}; + diesel.heat.To += static_cast(dTo * dt); // heater /* @@ -1436,54 +1436,54 @@ void TMoverParameters::dizel_Heat(double const dt) Qp = (float)( podgrzewacz and ( true == WaterPump.is_active ) and ( Twy < 55 ) and ( Twy2 < 55 ) ) * 1000; else */ - auto const Qp = (true == WaterHeater.is_active && true == WaterPump.is_active && dizel_heat.Twy < 60 && dizel_heat.Twy2 < 60 ? 1 : 0) * 1000; + auto const Qp = (true == WaterHeater.is_active && true == WaterPump.is_active && diesel.heat.Twy < 60 && diesel.heat.Twy2 < 60 ? 1 : 0) * 1000; auto const kurek07{1}; // unknown/unimplemented device TBD, TODO: identify and implement? - if (true == dizel_heat.auxiliary_water_circuit) + if (true == diesel.heat.auxiliary_water_circuit) { // auxiliary water circuit setup - dizel_heat.water_aux.is_warm = true == dizel_heat.cooling || + diesel.heat.water_aux.is_warm = true == diesel.heat.cooling || (true == Mains && BatteryVoltage > 0.75 * NominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ - && dizel_heat.water_aux.config.temp_cooling > 0 && dizel_heat.temperatura2 > dizel_heat.water_aux.config.temp_cooling - (dizel_heat.water_aux.is_warm ? 8 : 0)); - auto const PTC2{(dizel_heat.water_aux.is_warm /*or PTC2p*/ ? 1 : 0)}; - dizel_heat.rpmwz2 = static_cast(PTC2 * (dizel_heat.fan_speed >= 0 ? rpm * dizel_heat.fan_speed : dizel_heat.fan_speed * -1)); - dizel_heat.zaluzje2 = dizel_heat.water_aux.config.shutters ? PTC2 == 1 : true; // no shutters is an equivalent to having them open - auto const zaluzje2{(dizel_heat.zaluzje2 ? 1 : 0)}; + && diesel.heat.water_aux.config.temp_cooling > 0 && diesel.heat.temperatura2 > diesel.heat.water_aux.config.temp_cooling - (diesel.heat.water_aux.is_warm ? 8 : 0)); + auto const PTC2{(diesel.heat.water_aux.is_warm /*or PTC2p*/ ? 1 : 0)}; + diesel.heat.rpmwz2 = static_cast(PTC2 * (diesel.heat.fan_speed >= 0 ? rpm * diesel.heat.fan_speed : diesel.heat.fan_speed * -1)); + diesel.heat.zaluzje2 = diesel.heat.water_aux.config.shutters ? PTC2 == 1 : true; // no shutters is an equivalent to having them open + auto const zaluzje2{(diesel.heat.zaluzje2 ? 1 : 0)}; // auxiliary water circuit heat transfer values - auto const kf2{kurek07 * (dizel_heat.kw * (0.3 + 0.7 * zaluzje2) * dizel_heat.rpmw2 + dizel_heat.kv * (0.3 + 0.7 * zaluzje2) * Vel / 3.6) + 2}; - auto const dTs2{dizel_heat.kfo2 * (dizel_heat.To - dizel_heat.Tsr2) / (gw2 * Cw)}; + auto const kf2{kurek07 * (diesel.heat.kw * (0.3 + 0.7 * zaluzje2) * diesel.heat.rpmw2 + diesel.heat.kv * (0.3 + 0.7 * zaluzje2) * Vel / 3.6) + 2}; + auto const dTs2{diesel.heat.kfo2 * (diesel.heat.To - diesel.heat.Tsr2) / (gw2 * Cw)}; // przy otwartym kurku B ma³y obieg jest dogrzewany przez du¿y - stosujemy przy korzystaniu z podgrzewacza oraz w zimie - auto const Qch2{-kf2 * (dizel_heat.Tsr2 - dizel_heat.Te) + 80 * (true == WaterCircuitsLink ? 1 : 0) * (dizel_heat.Twy - dizel_heat.Tsr2)}; + auto const Qch2{-kf2 * (diesel.heat.Tsr2 - diesel.heat.Te) + 80 * (true == WaterCircuitsLink ? 1 : 0) * (diesel.heat.Twy - diesel.heat.Tsr2)}; auto const dTch2{Qch2 / (gw2 * Cw)}; // auxiliary water circuit heat transfers finalization // NOTE: since primary circuit doesn't read data from the auxiliary one, we can pretty safely finalize auxiliary updates before touching the primary circuit - auto const Twe2{dizel_heat.Twy2 + dTch2 * dt}; - dizel_heat.Twy2 = static_cast(Twe2 + dTs2 * dt); - dizel_heat.Tsr2 = static_cast(0.5 * (dizel_heat.Twy2 + Twe2)); - dizel_heat.temperatura2 = dizel_heat.Twy2; + auto const Twe2{diesel.heat.Twy2 + dTch2 * dt}; + diesel.heat.Twy2 = static_cast(Twe2 + dTs2 * dt); + diesel.heat.Tsr2 = static_cast(0.5 * (diesel.heat.Twy2 + Twe2)); + diesel.heat.temperatura2 = diesel.heat.Twy2; } // primary water circuit setup - dizel_heat.water.is_flowing = dizel_heat.water.config.temp_flow < 0 || dizel_heat.temperatura1 > dizel_heat.water.config.temp_flow - (dizel_heat.water.is_flowing ? 5 : 0); - auto const obieg{(dizel_heat.water.is_flowing ? 1 : 0)}; - dizel_heat.water.is_warm = - true == dizel_heat.cooling || (true == Mains && BatteryVoltage > 0.75 * NominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ - && dizel_heat.water.config.temp_cooling > 0 && dizel_heat.temperatura1 > dizel_heat.water.config.temp_cooling - (dizel_heat.water.is_warm ? 8 : 0)); - auto const PTC1{(dizel_heat.water.is_warm /*or PTC1p*/ ? 1 : 0)}; - dizel_heat.rpmwz = static_cast(PTC1 * (dizel_heat.fan_speed >= 0 ? rpm * dizel_heat.fan_speed : dizel_heat.fan_speed * -1)); - dizel_heat.zaluzje1 = dizel_heat.water.config.shutters ? PTC1 == 1 : true; // no shutters is an equivalent to having them open - auto const zaluzje1{(dizel_heat.zaluzje1 ? 1 : 0)}; + diesel.heat.water.is_flowing = diesel.heat.water.config.temp_flow < 0 || diesel.heat.temperatura1 > diesel.heat.water.config.temp_flow - (diesel.heat.water.is_flowing ? 5 : 0); + auto const obieg{(diesel.heat.water.is_flowing ? 1 : 0)}; + diesel.heat.water.is_warm = + true == diesel.heat.cooling || (true == Mains && BatteryVoltage > 0.75 * NominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ + && diesel.heat.water.config.temp_cooling > 0 && diesel.heat.temperatura1 > diesel.heat.water.config.temp_cooling - (diesel.heat.water.is_warm ? 8 : 0)); + auto const PTC1{(diesel.heat.water.is_warm /*or PTC1p*/ ? 1 : 0)}; + diesel.heat.rpmwz = static_cast(PTC1 * (diesel.heat.fan_speed >= 0 ? rpm * diesel.heat.fan_speed : diesel.heat.fan_speed * -1)); + diesel.heat.zaluzje1 = diesel.heat.water.config.shutters ? PTC1 == 1 : true; // no shutters is an equivalent to having them open + auto const zaluzje1{(diesel.heat.zaluzje1 ? 1 : 0)}; // primary water circuit heat transfer values - auto const kf{obieg * kurek07 * (dizel_heat.kw * (0.3 + 0.7 * zaluzje1) * dizel_heat.rpmw + dizel_heat.kv * (0.3 + 0.7 * zaluzje1) * Vel / 3.6 + 3) + 2}; - auto const dTs{(dizel_heat.auxiliary_water_circuit ? dizel_heat.kfs * (dizel_heat.Ts - dizel_heat.Tsr) / (gw * Cw) : - (dizel_heat.kfs * (dizel_heat.Ts - dizel_heat.Tsr) + dizel_heat.kfo2 * (dizel_heat.To - dizel_heat.Tsr)) / (gw * Cw))}; - auto const Qch{-kf * (dizel_heat.Tsr - dizel_heat.Te) + Qp}; + auto const kf{obieg * kurek07 * (diesel.heat.kw * (0.3 + 0.7 * zaluzje1) * diesel.heat.rpmw + diesel.heat.kv * (0.3 + 0.7 * zaluzje1) * Vel / 3.6 + 3) + 2}; + auto const dTs{(diesel.heat.auxiliary_water_circuit ? diesel.heat.kfs * (diesel.heat.Ts - diesel.heat.Tsr) / (gw * Cw) : + (diesel.heat.kfs * (diesel.heat.Ts - diesel.heat.Tsr) + diesel.heat.kfo2 * (diesel.heat.To - diesel.heat.Tsr)) / (gw * Cw))}; + auto const Qch{-kf * (diesel.heat.Tsr - diesel.heat.Te) + Qp}; auto const dTch{Qch / (gw * Cw)}; // primary water circuit heat transfers finalization - auto const Twe{dizel_heat.Twy + dTch * dt}; - dizel_heat.Twy = static_cast(Twe + dTs * dt); - dizel_heat.Tsr = static_cast(0.5 * (dizel_heat.Twy + Twe)); - dizel_heat.temperatura1 = dizel_heat.Twy; + auto const Twe{diesel.heat.Twy + dTch * dt}; + diesel.heat.Twy = static_cast(Twe + dTs * dt); + diesel.heat.Tsr = static_cast(0.5 * (diesel.heat.Twy + Twe)); + diesel.heat.temperatura1 = diesel.heat.Twy; /* fuelConsumed = fuelConsumed + ( Ge * 0.5 ); diff --git a/physics/components/dieselengine.h b/physics/components/dieselengine.h new file mode 100644 index 000000000..07937ffcb --- /dev/null +++ b/physics/components/dieselengine.h @@ -0,0 +1,185 @@ +/* +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 diesel engine of a vehicle and its hydraulic transmission: their definition from the .fiz and their state. +// a vehicle has them whatever its drive; the drives of a diesel engine (DieselEngine, DieselElectric) use them + +#pragma once + +#include + +// the heat of a diesel engine: its cooling circuits, their fans and shutters, the temperatures +struct EngineHeat +{ + // input, state of relevant devices + bool cooling{false}; // TODO: user controlled device, implement + // bool okienko { true }; // window in the engine compartment + // system configuration + bool auxiliary_water_circuit{false}; // cooling system has an extra water circuit + double fan_speed{0.075}; // cooling fan rpm; either fraction of engine rpm, or absolute value if negative + // heat exchange factors + double kw{0.35}; + double kv{0.6}; + double kfe{1.0}; + double kfs{80.0}; + double kfo{25.0}; + double kfo2{25.0}; + // system parts + struct fluid_circuit_t + { + + struct circuit_config_t + { + float temp_min{-1}; // lowest accepted temperature + float temp_max{-1}; // highest accepted temperature + float temp_cooling{-1}; // active cooling activation point + float temp_flow{-1}; // fluid flow activation point + bool shutters{false}; // the radiator has shutters to assist the cooling + }; + circuit_config_t config; + bool is_cold{false}; // fluid is too cold + bool is_warm{false}; // fluid is too hot + bool is_hot{false}; // fluid temperature crossed cooling threshold + bool is_flowing{false}; // fluid is being pushed through the circuit + }; + fluid_circuit_t water; + fluid_circuit_t water_aux; + fluid_circuit_t oil; + fluid_circuit_t engine; + // output, state of affected devices + bool PA{false}; // malfunction flag + float rpmw{0.0}; // current main circuit fan revolutions + float rpmwz{0.0}; // desired main circuit fan revolutions + bool zaluzje1{false}; + float rpmw2{0.0}; // current auxiliary circuit fan revolutions + float rpmwz2{0.0}; // desired auxiliary circuit fan revolutions + bool zaluzje2{false}; + // output, temperatures + float Te{15.0}; // ambient temperature TODO: get it from environment data + // NOTE: by default the engine is initialized in warm, startup-ready state + float Ts{50.0}; // engine temperature + float To{45.0}; // oil temperature + float Tsr{50.0}; // main circuit radiator temperature (?) + float Twy{50.0}; // main circuit water temperature + float Tsr2{40.0}; // secondary circuit radiator temperature (?) + float Twy2{40.0}; // secondary circuit water temperature + float temperatura1{50.0}; + float temperatura2{40.0}; + float powerfactor{1.0}; // coefficient of heat generation for engines other than su45 + // engine overheat threshold + float engine_max_temp{-1}; // maximum acceptable engine temperature, triggers overheat lamp when exceeded + bool engine_is_hot{false}; // engine temperature crossed cooling threshold +}; + +// the diesel engine, its governor, its clutch and its fuel (the dizel_ values before) +struct DieselEngine +{ + // the definition (the Engine section of the .fiz) + double maxMoment = 1.0; // Mmax + double maxMomentRevolutions = 1.0; // nMmax + double maxRevolutionsMoment = 2.0; // Mnmax + double maxRevolutions = 2.0; // nmax + double nominalFill = 0.0; + std::map momentTable; + std::map speedMaxRevolutionsTable; // vel2nmax + /*parametry aproksymacji silnika spalinowego*/ + double standingMoment = 0.0; /*moment oporow ruchu silnika dla enrot=0*/ + double cutoffRevolutions = 0.0; /*predkosc obrotowa zadzialania ogranicznika predkosci*/ + double minRevolutions = 0.0; /*najmniejsza dopuszczalna predkosc obrotowa*/ + double hydraulicMinRevolutions = 0.0; /*najmniejsza dopuszczalna predkosc obrotowa w czasie jazdy na hydro */ + double hydraulicMinRevolutionsFactor = 0.0; /*wspolczynnik wzrostu obrotow minimalnych hydro zaleznosci od zadanego procentu*/ + double retarderRevolutions = 0.0; /*obroty pracy podczas hamowania retarderem*/ + double governorAcceleration = 999.0; /*tempo zwiększania prędkości przez regulator dizla */ + double fullEngageMinVelocity = 0.0; /*najmniejsza predkosc przy jezdzie ze sprzeglem bez poslizgu*/ + double converterReleaseVelocity = 3.0; /*predkosc progowa rozlaczenia przetwornika momentu*/ + double shaftInertia = 1.0; /*moment bezwladnosci walu itp*/ + double revolutionsDecreaseRate{2.0}; + double nominalFuelConsumptionRate = 250.0; /*jednostkowe zużycie paliwa przy mocy nominalnej, wczytywane z fiz, g/kWh*/ + double fuelConsumption = 0.0; /*współczynnik zużycia paliwa przeliczony do jednostek maszynowych, l/obrót*/ + double clutchDiameter = 0.5; + double clutchMaxForce = 6000.0; + double clutchFriction = 0.5; /*parametry sprzegla*/ + // the starter turns the engine a while before it fires: smoke comes out only after SmokeDelay (the Engine section of the vehicle's + // .fiz, seconds from the start of the spin up) has passed. 0, the default, lets it out as soon as the starter turns, as before eu07/maszyna#523 + double smokeDelay{0.0}; + + // the state + double fill = 0.0; /*napelnienie*/ + double clutchState = 0.0; /*sprzeglo skrzyni biegow: 0 - luz, 1 - wlaczone, 0.5 - wlaczone 50% (z poslizgiem)*/ + double clutchPressure = 0.0; /*sprzeglo skrzyni biegow: aktualny docisk*/ + double automaticGearShift = 0.0; /*0 - bez zmiany, -1 zmiana na nizszy +1 zmiana na wyzszy*/ + bool startupRequested{false}; // engine startup procedure request indicator + bool ignitionRequested{false}; // engine ignition request indicator + bool spinningUp{false}; // engine spin up to idle speed flag + double firingCountdown{0.0}; // seconds left until the engine being started fires, 0 once it runs on its own + double clutchSlip = 0.0; /*roznica predkosci katowych tarcz sprzegla*/ + double previousRevolutions = 0.0; /*poredkosc na potrzeby obliczen sprzegiel*/ + double torque = 0.0; /*aktualny moment obrotowy silnika spalinowego*/ + double power = 0.0; /*aktualna moc silnika spalinowego*/ + double governorMinRevolutions = 0.0; /*predkosc regulatora minimalna, zmienna w hydro*/ + double governorMaxRevolutions = 0.0; /*predkosc regulatora maksymalna, zmienna w hydro*/ + double fuelConsumptionActual = 0.0; /*chwilowe spalanie paliwa w l/h*/ + double fuelConsumedTotal = 0.0; /*ilość paliwa zużyta od początku symulacji, l*/ + EngineHeat heat; +}; + +// the hydraulic torque converter (the hydro_TC values before) +struct TorqueConverter +{ + // the definition + bool present = false; /*obecnosc hydraulicznego przetwornika momentu*/ + double maxTorqueRatio = 2.0; /*maksymalne wzmocnienie momentu*/ + double couplingPoint = 0.85; /*wzgledna predkosc zasprzeglenia*/ + double lockupTorque = 3000.0; /*moment graniczny sprzegla blokujacego*/ + double lockupRate = 1.0; /*szybkosc zalaczania sprzegla blokujacego*/ + double unlockRate = 1.0; /*szybkosc rozlaczania sprzegla blokujacego*/ + double fillRateIncrease = 1.0; /*szybkosc napelniania sprzegla*/ + double fillRateDecrease = 1.0; /*szybkosc oprozniania sprzegla*/ + double torqueInIn = 4.5; /*stala momentu proporcjonalnego do kwadratu obrotow wejsciowych*/ + double torqueInOut = 0.0; /*stala momentu proporcjonalnego do roznica obrotow wejsciowych i wyjsciowych*/ + double torqueOutOut = 0.0; /*stala momentu proporcjonalnego do kwadratu obrotow wyjsciowych*/ + double lockupSpeed = 1.0; /*prog predkosci zalaczania sprzegla blokujacego*/ + double unlockSpeed = 1.0; /*prog predkosci rozlaczania sprzegla blokujacego*/ + std::map table; /*tablica przetwornika momentu*/ + + // the state + double fill = 0.0; /*napelnienie*/ + bool lockedUp = false; /*zapiecie sprzegla*/ + double torqueIn = 0.0; /*moment*/ + double torqueOut = 0.0; /*moment*/ + double torqueRatio = 1.0; /*aktualne przelozenie momentu*/ + double request = 0.0; /*zadanie sily*/ + double revolutionsIn = 0.0; /*predkosc obrotowa walu wejsciowego*/ + double revolutionsOut = 0.0; /*predkosc obrotowa walu wyjsciowego*/ +}; + +// the hydraulic retarder (the hydro_R values before) +struct Retarder +{ + // the definition + bool present = false; /*obecnosc retardera*/ + int placement = 0; /*umiejscowienie retardera: 0 - za skrzynia biegow, 1 - miedzy przetwornikiem a biegami, 2 - przed skrzynia biegow */ + double torqueInIn = 1.0; /*stala momentu proporcjonalnego do kwadratu obrotow wejsciowych*/ + double maxTorque = 1.0; /*maksymalny moment retardera*/ + double maxPower = 1.0; /*maksymalna moc retardera - ogranicza moment*/ + double fillRateIncrease = 1.0; /*szybkosc napelniania sprzegla*/ + double fillRateDecrease = 1.0; /*szybkosc oprozniania sprzegla*/ + double minVelocity = 1.0; /*minimalna predkosc, przy ktorej retarder dziala*/ + double engageVelocity = 1.0; /*minimalna predkosc hamowania, przy ktorej sprzeglo jest wciaz wlaczone*/ + bool hasClutch = false; /*czy retarder ma rozłączalne sprzęgło*/ + double clutchSpeed = 10.0; /*szybkość narastania obrotów po włączeniu sprzęgła retardera*/ + bool withIndividual = false; /*czy dla autobusów jest to łączone*/ + + // the state + double fill = 0.0; /*napelnienie*/ + double torque = 0.0; /*moment*/ + double request = 0.0; /*zadanie sily hamowania*/ + double revolutions = 0.0; /*predkosc obrotowa retardera*/ + bool clutchActive = false; /*czy retarder jest napędzany*/ +}; diff --git a/physics/components/drive.cpp b/physics/components/drive.cpp index 55284f396..16e2c5294 100644 --- a/physics/components/drive.cpp +++ b/physics/components/drive.cpp @@ -71,7 +71,7 @@ namespace // the radiator fans of a diesel engine follow their demanded revolutions while the engine runs, and run down without it void updateRadiatorFans(TMoverParameters &vehicle, double const dt) { - auto &heat{vehicle.dizel_heat}; + auto &heat{vehicle.diesel.heat}; if (true == vehicle.Mains) { heat.rpmw += static_cast(std::clamp(heat.rpmwz - heat.rpmw, -100.f, 50.f) * dt); @@ -164,12 +164,12 @@ class DieselMechanicalDrive final : public TractionDrive public: double UpdateEnginePower(TMoverParameters &vehicle) const override { - vehicle.dizel_Power = vehicle.Mm * vehicle.enrot * (2.0 * M_PI / 1000.0); - vehicle.EnginePower = (vehicle.dizel_Mstand + vehicle.Mm) * vehicle.enrot * (2.0 * M_PI / 1000.0); + vehicle.diesel.power = vehicle.Mm * vehicle.enrot * (2.0 * M_PI / 1000.0); + vehicle.EnginePower = (vehicle.diesel.standingMoment + vehicle.Mm) * vehicle.enrot * (2.0 * M_PI / 1000.0); if (vehicle.MainCtrlPowerPos() > 1) { // dodatkowe opory z powodu sprezarki} - // dmoment -= dizel_Mstand * ( 0.2 * enrot / dizel_nmax ); //yB: skąd to w ogóle się bierze?! + // dmoment -= diesel.standingMoment * ( 0.2 * enrot / diesel.maxRevolutions ); //yB: skąd to w ogóle się bierze?! } return 0.0; } @@ -188,11 +188,11 @@ public: } double EngineIdleRpm(TMoverParameters const &vehicle) const override { - return vehicle.dizel_nmin * 60; + return vehicle.diesel.minRevolutions * 60; } double EngineMaxRpm(TMoverParameters const &vehicle) const override { - return vehicle.dizel_nmax * 60; + return vehicle.diesel.maxRevolutions * 60; } }; diff --git a/physics/components/electrics.cpp b/physics/components/electrics.cpp index a14840bc3..6634c2496 100644 --- a/physics/components/electrics.cpp +++ b/physics/components/electrics.cpp @@ -308,7 +308,7 @@ void TMoverParameters::MainsCheck(double const Deltatime) else { // optional automatic circuit start - if (MainsStart != start_t::manual && false == (Mains || dizel_startup)) + if (MainsStart != start_t::manual && false == (Mains || diesel.startupRequested)) { MainSwitch(true); } @@ -919,7 +919,7 @@ bool TMoverParameters::CompartmentLightsSwitchOff(bool State, range_t const Noti bool TMoverParameters::MainSwitch(bool const State, range_t const Notify) { - bool const initialstate{Mains || dizel_startup}; + bool const initialstate{Mains || diesel.startupRequested}; MainSwitch_(State); @@ -930,7 +930,7 @@ bool TMoverParameters::MainSwitch(bool const State, range_t const Notify) SendCtrlToNext(VehicleCommand::mainSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } - return (Mains || dizel_startup) != initialstate; + return (Mains || diesel.startupRequested) != initialstate; } void TMoverParameters::MainSwitch_(bool const State) @@ -953,7 +953,7 @@ void TMoverParameters::MainSwitch_(bool const State) if (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric) { // launch diesel engine startup procedure - dizel_startup = true; + diesel.startupRequested = true; } else { diff --git a/physics/components/fizparser.cpp b/physics/components/fizparser.cpp index 32a50d653..c4c0fab0a 100644 --- a/physics/components/fizparser.cpp +++ b/physics/components/fizparser.cpp @@ -327,7 +327,7 @@ bool TMoverParameters::readDMList(std::string const &line) double y = 0.0; parser >> x >> y; - dizel_Momentum_Table.emplace(x / 60.0, y); + diesel.momentTable.emplace(x / 60.0, y); return true; } @@ -347,7 +347,7 @@ bool TMoverParameters::readV2NMAXList(std::string const &line) double y = 0.0; parser >> x >> y; - dizel_vel2nmax_Table.emplace(x, y / 60.0); + diesel.speedMaxRevolutionsTable.emplace(x, y / 60.0); return true; } @@ -367,7 +367,7 @@ bool TMoverParameters::readHTCList(std::string const &line) double y = 0.0; parser >> x >> y; - hydro_TC_Table.emplace(x, y); + torqueConverter.table.emplace(x, y); return true; } diff --git a/physics/components/fizsections.cpp b/physics/components/fizsections.cpp index b567b3712..440532edf 100644 --- a/physics/components/fizsections.cpp +++ b/physics/components/fizsections.cpp @@ -1270,32 +1270,32 @@ void TMoverParameters::LoadFIZ_Engine(std::string const &Input) void TMoverParameters::LoadFIZ_EngineDiesel(std::string const &Input) { - extract_value(dizel_nmin, "nmin", Input, ""); - dizel_nmin /= 60.0; - dizel_nreg_min = dizel_nmin * 0.98; - extract_value(dizel_nmin_hdrive, "nmin_hdrive", Input, ""); - dizel_nmin_hdrive /= 60.0; - if (dizel_nmin_hdrive == 0.0) + extract_value(diesel.minRevolutions, "nmin", Input, ""); + diesel.minRevolutions /= 60.0; + diesel.governorMinRevolutions = diesel.minRevolutions * 0.98; + extract_value(diesel.hydraulicMinRevolutions, "nmin_hdrive", Input, ""); + diesel.hydraulicMinRevolutions /= 60.0; + if (diesel.hydraulicMinRevolutions == 0.0) { - dizel_nmin_hdrive = dizel_nmin; + diesel.hydraulicMinRevolutions = diesel.minRevolutions; } - extract_value(dizel_nmin_hdrive_factor, "nmin_hdrive_factor", Input, ""); - dizel_nmin_hdrive_factor /= 60.0; - extract_value(dizel_nmin_retarder, "nmin_retarder", Input, ""); - dizel_nmin_retarder /= 60.0; - if (dizel_nmin_retarder == 0.0) + extract_value(diesel.hydraulicMinRevolutionsFactor, "nmin_hdrive_factor", Input, ""); + diesel.hydraulicMinRevolutionsFactor /= 60.0; + extract_value(diesel.retarderRevolutions, "nmin_retarder", Input, ""); + diesel.retarderRevolutions /= 60.0; + if (diesel.retarderRevolutions == 0.0) { - dizel_nmin_retarder = dizel_nmin; + diesel.retarderRevolutions = diesel.minRevolutions; } // TODO: unify naming scheme and sort out which diesel engine params are used where and how extract_value(nmax, "nmax", Input, ""); nmax /= 60.0; - extract_value(dizel_nmax_cutoff, "nmax_cutoff", Input, "0.0"); - dizel_nmax_cutoff /= 60.0; - extract_value(dizel_nreg_acc, "nreg_acc", Input, ""); - dizel_nreg_acc /= 60.0; - extract_value(dizel_AIM, "AIM", Input, "1.0"); - extract_value(dizel_RevolutionsDecreaseRate, "RPMDecRate", Input, ""); + extract_value(diesel.cutoffRevolutions, "nmax_cutoff", Input, "0.0"); + diesel.cutoffRevolutions /= 60.0; + extract_value(diesel.governorAcceleration, "nreg_acc", Input, ""); + diesel.governorAcceleration /= 60.0; + extract_value(diesel.shaftInertia, "AIM", Input, "1.0"); + extract_value(diesel.revolutionsDecreaseRate, "RPMDecRate", Input, ""); extract_value(engageupspeed, "EUS", Input, "0.5"); extract_value(engagedownspeed, "EDS", Input, "0.9"); @@ -1311,37 +1311,37 @@ void TMoverParameters::LoadFIZ_EngineDiesel(std::string const &Input) AnPos = 1.0 / AnPos; // im większa liczba, tym wolniej jedzie } } - extract_value(hydro_TC, "IsTC", Input, ""); - if (true == hydro_TC) + extract_value(torqueConverter.present, "IsTC", Input, ""); + if (true == torqueConverter.present) { - extract_value(hydro_TC_TMMax, "TC_TMMax", Input, ""); - extract_value(hydro_TC_CouplingPoint, "TC_CP", Input, ""); - extract_value(hydro_TC_LockupTorque, "TC_LT", Input, ""); - extract_value(hydro_TC_LockupRate, "TC_LR", Input, ""); - extract_value(hydro_TC_UnlockRate, "TC_ULR", Input, ""); - extract_value(hydro_TC_FillRateInc, "TC_FRI", Input, ""); - extract_value(hydro_TC_FillRateDec, "TC_FRD", Input, ""); - extract_value(hydro_TC_TorqueInIn, "TC_TII", Input, ""); - extract_value(hydro_TC_TorqueInOut, "TC_TIO", Input, ""); - extract_value(hydro_TC_TorqueOutOut, "TC_TOO", Input, ""); - extract_value(hydro_TC_LockupSpeed, "TC_LS", Input, ""); - extract_value(hydro_TC_UnlockSpeed, "TC_ULS", Input, ""); - extract_value(dizel_maxVelANS, "MaxVelANS", Input, ""); + extract_value(torqueConverter.maxTorqueRatio, "TC_TMMax", Input, ""); + extract_value(torqueConverter.couplingPoint, "TC_CP", Input, ""); + extract_value(torqueConverter.lockupTorque, "TC_LT", Input, ""); + extract_value(torqueConverter.lockupRate, "TC_LR", Input, ""); + extract_value(torqueConverter.unlockRate, "TC_ULR", Input, ""); + extract_value(torqueConverter.fillRateIncrease, "TC_FRI", Input, ""); + extract_value(torqueConverter.fillRateDecrease, "TC_FRD", Input, ""); + extract_value(torqueConverter.torqueInIn, "TC_TII", Input, ""); + extract_value(torqueConverter.torqueInOut, "TC_TIO", Input, ""); + extract_value(torqueConverter.torqueOutOut, "TC_TOO", Input, ""); + extract_value(torqueConverter.lockupSpeed, "TC_LS", Input, ""); + extract_value(torqueConverter.unlockSpeed, "TC_ULS", Input, ""); + extract_value(diesel.converterReleaseVelocity, "MaxVelANS", Input, ""); - extract_value(hydro_R, "IsRetarder", Input, ""); - if (true == hydro_R) + extract_value(retarder.present, "IsRetarder", Input, ""); + if (true == retarder.present) { - extract_value(hydro_R_Placement, "R_Place", Input, ""); - extract_value(hydro_R_TorqueInIn, "R_TII", Input, ""); - extract_value(hydro_R_MaxTorque, "R_MT", Input, ""); - extract_value(hydro_R_MaxPower, "R_MP", Input, ""); - extract_value(hydro_R_FillRateInc, "R_FRI", Input, ""); - extract_value(hydro_R_FillRateDec, "R_FRD", Input, ""); - extract_value(hydro_R_MinVel, "R_MinVel", Input, ""); - extract_value(hydro_R_EngageVel, "R_EngageVel", Input, ""); - extract_value(hydro_R_Clutch, "R_IsClutch", Input, ""); - extract_value(hydro_R_ClutchSpeed, "R_ClutchSpeed", Input, ""); - extract_value(hydro_R_WithIndividual, "R_WithIndividual", Input, ""); + extract_value(retarder.placement, "R_Place", Input, ""); + extract_value(retarder.torqueInIn, "R_TII", Input, ""); + extract_value(retarder.maxTorque, "R_MT", Input, ""); + extract_value(retarder.maxPower, "R_MP", Input, ""); + extract_value(retarder.fillRateIncrease, "R_FRI", Input, ""); + extract_value(retarder.fillRateDecrease, "R_FRD", Input, ""); + extract_value(retarder.minVelocity, "R_MinVel", Input, ""); + extract_value(retarder.engageVelocity, "R_EngageVel", Input, ""); + extract_value(retarder.hasClutch, "R_IsClutch", Input, ""); + extract_value(retarder.clutchSpeed, "R_ClutchSpeed", Input, ""); + extract_value(retarder.withIndividual, "R_WithIndividual", Input, ""); } } } @@ -1368,8 +1368,8 @@ void TMoverParameters::LoadFIZ_EngineDieselElectric(std::string const &Input) ImaxLo = 1; } extract_value(EngineHeatingRPM, "HeatingRPM", Input, ""); - extract_value(dizel_AIM, "AIM", Input, "1.25"); - extract_value(dizel_RevolutionsDecreaseRate, "RPMDecRate", Input, ""); + extract_value(diesel.shaftInertia, "AIM", Input, "1.25"); + extract_value(diesel.revolutionsDecreaseRate, "RPMDecRate", Input, ""); LoadFIZ_DieselElectricDynamicBrake(Input); } @@ -1432,36 +1432,36 @@ void TMoverParameters::LoadFIZ_EngineDieselShared(std::string const &Input) extract_value(OilPump.pressure_minimum, "OilMinPressure", Input, ""); extract_value(OilPump.pressure_maximum, "OilMaxPressure", Input, ""); // the time the starter turns the engine before it fires and smokes (eu07/maszyna#523) - extract_value(dizel_SmokeDelay, "SmokeDelay", Input, "0"); - dizel_SmokeDelay = std::max(0.0, dizel_SmokeDelay); + extract_value(diesel.smokeDelay, "SmokeDelay", Input, "0"); + diesel.smokeDelay = std::max(0.0, diesel.smokeDelay); // engine cooling factore - extract_value(dizel_heat.kw, "HeatKW", Input, ""); - extract_value(dizel_heat.kv, "HeatKV", Input, ""); - extract_value(dizel_heat.kfe, "HeatKFE", Input, ""); - extract_value(dizel_heat.kfs, "HeatKFS", Input, ""); - extract_value(dizel_heat.kfo, "HeatKFO", Input, ""); - extract_value(dizel_heat.kfo2, "HeatKFO2", Input, ""); + extract_value(diesel.heat.kw, "HeatKW", Input, ""); + extract_value(diesel.heat.kv, "HeatKV", Input, ""); + extract_value(diesel.heat.kfe, "HeatKFE", Input, ""); + extract_value(diesel.heat.kfs, "HeatKFS", Input, ""); + extract_value(diesel.heat.kfo, "HeatKFO", Input, ""); + extract_value(diesel.heat.kfo2, "HeatKFO2", Input, ""); // engine cooling systems - extract_value(dizel_heat.water.config.temp_min, "WaterMinTemperature", Input, ""); - extract_value(dizel_heat.water.config.temp_max, "WaterMaxTemperature", Input, ""); - extract_value(dizel_heat.water.config.temp_flow, "WaterFlowTemperature", Input, ""); - extract_value(dizel_heat.water.config.temp_cooling, "WaterCoolingTemperature", Input, ""); - extract_value(dizel_heat.water.config.shutters, "WaterShutters", Input, ""); - extract_value(dizel_heat.auxiliary_water_circuit, "WaterAuxCircuit", Input, ""); - extract_value(dizel_heat.water_aux.config.temp_min, "WaterAuxMinTemperature", Input, ""); - extract_value(dizel_heat.water_aux.config.temp_max, "WaterAuxMaxTemperature", Input, ""); - extract_value(dizel_heat.water_aux.config.temp_cooling, "WaterAuxCoolingTemperature", Input, ""); - extract_value(dizel_heat.water_aux.config.shutters, "WaterAuxShutters", Input, ""); - extract_value(dizel_heat.oil.config.temp_min, "OilMinTemperature", Input, ""); - extract_value(dizel_heat.oil.config.temp_max, "OilMaxTemperature", Input, ""); - extract_value(dizel_heat.engine_max_temp, "EngineMaxTemperature", Input, ""); - extract_value(dizel_heat.fan_speed, "WaterCoolingFanSpeed", Input, ""); + extract_value(diesel.heat.water.config.temp_min, "WaterMinTemperature", Input, ""); + extract_value(diesel.heat.water.config.temp_max, "WaterMaxTemperature", Input, ""); + extract_value(diesel.heat.water.config.temp_flow, "WaterFlowTemperature", Input, ""); + extract_value(diesel.heat.water.config.temp_cooling, "WaterCoolingTemperature", Input, ""); + extract_value(diesel.heat.water.config.shutters, "WaterShutters", Input, ""); + extract_value(diesel.heat.auxiliary_water_circuit, "WaterAuxCircuit", Input, ""); + extract_value(diesel.heat.water_aux.config.temp_min, "WaterAuxMinTemperature", Input, ""); + extract_value(diesel.heat.water_aux.config.temp_max, "WaterAuxMaxTemperature", Input, ""); + extract_value(diesel.heat.water_aux.config.temp_cooling, "WaterAuxCoolingTemperature", Input, ""); + extract_value(diesel.heat.water_aux.config.shutters, "WaterAuxShutters", Input, ""); + extract_value(diesel.heat.oil.config.temp_min, "OilMinTemperature", Input, ""); + extract_value(diesel.heat.oil.config.temp_max, "OilMaxTemperature", Input, ""); + extract_value(diesel.heat.engine_max_temp, "EngineMaxTemperature", Input, ""); + extract_value(diesel.heat.fan_speed, "WaterCoolingFanSpeed", Input, ""); // water heater extract_value(WaterHeater.config.temp_min, "HeaterMinTemperature", Input, ""); extract_value(WaterHeater.config.temp_max, "HeaterMaxTemperature", Input, ""); float pf{1235.f}; extract_value(pf, "NominalCoolingPower", Input, "1235"); - dizel_heat.powerfactor = 1235 / pf; + diesel.heat.powerfactor = 1235 / pf; } void TMoverParameters::LoadFIZ_Switches(std::string const &Input) @@ -1497,10 +1497,10 @@ void TMoverParameters::LoadFIZ_MotorParamTable(std::string const &Input) case TEngineType::DieselEngine: { - extract_value(dizel_minVelfullengage, "minVelfullengage", Input, ""); - extract_value(dizel_engageDia, "engageDia", Input, ""); - extract_value(dizel_engageMaxForce, "engageMaxForce", Input, ""); - extract_value(dizel_engagefriction, "engagefriction", Input, ""); + extract_value(diesel.fullEngageMinVelocity, "minVelfullengage", Input, ""); + extract_value(diesel.clutchDiameter, "engageDia", Input, ""); + extract_value(diesel.clutchMaxForce, "engageMaxForce", Input, ""); + extract_value(diesel.clutchFriction, "engagefriction", Input, ""); break; } default: @@ -1612,25 +1612,25 @@ void TMoverParameters::LoadFIZ_UCList(std::string const &Input) void TMoverParameters::LoadFIZ_DList(std::string const &Input) { - extract_value(dizel_Mmax, "Mmax", Input, ""); - extract_value(dizel_nMmax, "nMmax", Input, ""); - extract_value(dizel_Mnmax, "Mnmax", Input, ""); - extract_value(dizel_nmax, "nmax", Input, ""); - extract_value(dizel_nominalfill, "nominalfill", Input, ""); - extract_value(dizel_Mstand, "Mstand", Input, ""); - extract_value(dizel_NominalFuelConsumptionRate, "NomFuelConsRate", Input, ""); + extract_value(diesel.maxMoment, "Mmax", Input, ""); + extract_value(diesel.maxMomentRevolutions, "nMmax", Input, ""); + extract_value(diesel.maxRevolutionsMoment, "Mnmax", Input, ""); + extract_value(diesel.maxRevolutions, "nmax", Input, ""); + extract_value(diesel.nominalFill, "nominalfill", Input, ""); + extract_value(diesel.standingMoment, "Mstand", Input, ""); + extract_value(diesel.nominalFuelConsumptionRate, "NomFuelConsRate", Input, ""); - if (dizel_nMmax == dizel_nmax) + if (diesel.maxMomentRevolutions == diesel.maxRevolutions) { // HACK: guard against cases where nMmax == nmax, leading to division by 0 in momentum calculation - dizel_nMmax = dizel_nmax - 1.0 / 60.0; + diesel.maxMomentRevolutions = diesel.maxRevolutions - 1.0 / 60.0; } // Calculation of fuel consumption coefficient for futher calculation - double dizel_max_power = dizel_nmax * (dizel_Mnmax - dizel_Mstand) * M_PI * 2 * 0.001; // power in kW + double dizel_max_power = diesel.maxRevolutions * (diesel.maxRevolutionsMoment - diesel.standingMoment) * M_PI * 2 * 0.001; // power in kW double dizel_max_energy = dizel_max_power; // energy per one hour in kWh is equal to power in kW times 1 h double fuel_density = 850; // g/l - dizel_FuelConsumption = dizel_NominalFuelConsumptionRate * dizel_max_energy / fuel_density / dizel_nmax; + diesel.fuelConsumption = diesel.nominalFuelConsumptionRate * dizel_max_energy / fuel_density / diesel.maxRevolutions; } void TMoverParameters::LoadFIZ_FFList(std::string const &Input) diff --git a/physics/mover.h b/physics/mover.h index 25db352e1..6dd3eebe1 100644 --- a/physics/mover.h +++ b/physics/mover.h @@ -22,6 +22,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/derailmotion.h" #include "vehicle/odometerreading.h" #include "physics/vehicletypes.h" +#include "physics/components/dieselengine.h" class TractionDrive; @@ -810,68 +811,6 @@ class TMoverParameters bool is_damaged{false}; // device is damaged }; - struct heat_data - { - // input, state of relevant devices - bool cooling{false}; // TODO: user controlled device, implement - // bool okienko { true }; // window in the engine compartment - // system configuration - bool auxiliary_water_circuit{false}; // cooling system has an extra water circuit - double fan_speed{0.075}; // cooling fan rpm; either fraction of engine rpm, or absolute value if negative - // heat exchange factors - double kw{0.35}; - double kv{0.6}; - double kfe{1.0}; - double kfs{80.0}; - double kfo{25.0}; - double kfo2{25.0}; - // system parts - struct fluid_circuit_t - { - - struct circuit_config_t - { - float temp_min{-1}; // lowest accepted temperature - float temp_max{-1}; // highest accepted temperature - float temp_cooling{-1}; // active cooling activation point - float temp_flow{-1}; // fluid flow activation point - bool shutters{false}; // the radiator has shutters to assist the cooling - }; - circuit_config_t config; - bool is_cold{false}; // fluid is too cold - bool is_warm{false}; // fluid is too hot - bool is_hot{false}; // fluid temperature crossed cooling threshold - bool is_flowing{false}; // fluid is being pushed through the circuit - }; - fluid_circuit_t water; - fluid_circuit_t water_aux; - fluid_circuit_t oil; - fluid_circuit_t engine; - // output, state of affected devices - bool PA{false}; // malfunction flag - float rpmw{0.0}; // current main circuit fan revolutions - float rpmwz{0.0}; // desired main circuit fan revolutions - bool zaluzje1{false}; - float rpmw2{0.0}; // current auxiliary circuit fan revolutions - float rpmwz2{0.0}; // desired auxiliary circuit fan revolutions - bool zaluzje2{false}; - // output, temperatures - float Te{15.0}; // ambient temperature TODO: get it from environment data - // NOTE: by default the engine is initialized in warm, startup-ready state - float Ts{50.0}; // engine temperature - float To{45.0}; // oil temperature - float Tsr{50.0}; // main circuit radiator temperature (?) - float Twy{50.0}; // main circuit water temperature - float Tsr2{40.0}; // secondary circuit radiator temperature (?) - float Twy2{40.0}; // secondary circuit water temperature - float temperatura1{50.0}; - float temperatura2{40.0}; - float powerfactor{1.0}; // coefficient of heat generation for engines other than su45 - // engine overheat threshold - float engine_max_temp{-1}; // maximum acceptable engine temperature, triggers overheat lamp when exceeded - bool engine_is_hot{false}; // engine temperature crossed cooling threshold - }; - struct spring_brake { std::shared_ptr Cylinder; @@ -1184,64 +1123,12 @@ class TMoverParameters int SmallCompressorPower = 0; /*Winger ZROBIC*/ bool Trafo = false; /*pojazd wyposażony w transformator*/ - /*-sekcja parametrow dla lokomotywy spalinowej z przekladnia mechaniczna*/ - double dizel_Mmax = 1.0; - double dizel_nMmax = 1.0; - double dizel_Mnmax = 2.0; - double dizel_nmax = 2.0; - double dizel_nominalfill = 0.0; - std::map dizel_Momentum_Table; - std::map dizel_vel2nmax_Table; - /*parametry aproksymacji silnika spalinowego*/ - double dizel_Mstand = 0.0; /*moment oporow ruchu silnika dla enrot=0*/ - /* dizel_auto_min, dizel_auto_max: real; {predkosc obrotowa przelaczania automatycznej skrzyni biegow*/ - double dizel_nmax_cutoff = 0.0; /*predkosc obrotowa zadzialania ogranicznika predkosci*/ - double dizel_nmin = 0.0; /*najmniejsza dopuszczalna predkosc obrotowa*/ - double dizel_nmin_hdrive = 0.0; /*najmniejsza dopuszczalna predkosc obrotowa w czasie jazdy na hydro */ - double dizel_nmin_hdrive_factor = 0.0; /*wspolczynnik wzrostu obrotow minimalnych hydro zaleznosci od zadanego procentu*/ - double dizel_nmin_retarder = 0.0; /*obroty pracy podczas hamowania retarderem*/ - double dizel_nreg_acc = 999.0; /*tempo zwiększania prędkości przez regulator dizla */ - double dizel_minVelfullengage = 0.0; /*najmniejsza predkosc przy jezdzie ze sprzeglem bez poslizgu*/ - double dizel_maxVelANS = 3.0; /*predkosc progowa rozlaczenia przetwornika momentu*/ - double dizel_AIM = 1.0; /*moment bezwladnosci walu itp*/ - double dizel_RevolutionsDecreaseRate{2.0}; - double dizel_NominalFuelConsumptionRate = 250.0; /*jednostkowe zużycie paliwa przy mocy nominalnej, wczytywane z fiz, g/kWh*/ - double dizel_FuelConsumption = 0.0; /*współczynnik zużycia paliwa przeliczony do jednostek maszynowych, l/obrót*/ - double dizel_FuelConsumptionActual = 0.0; /*chwilowe spalanie paliwa w l/h*/ - double dizel_FuelConsumptedTotal = 0.0; /*ilość paliwa zużyta od początku symulacji, l*/ - double dizel_engageDia = 0.5; - double dizel_engageMaxForce = 6000.0; - double dizel_engagefriction = 0.5; /*parametry sprzegla*/ + // the diesel engine, its torque converter and its retarder (physics/components/dieselengine.h) + DieselEngine diesel; + TorqueConverter torqueConverter; + Retarder retarder; double engagedownspeed = 0.9; double engageupspeed = 0.5; - /*parametry przetwornika momentu*/ - bool hydro_TC = false; /*obecnosc hydraulicznego przetwornika momentu*/ - double hydro_TC_TMMax = 2.0; /*maksymalne wzmocnienie momentu*/ - double hydro_TC_CouplingPoint = 0.85; /*wzgledna predkosc zasprzeglenia*/ - double hydro_TC_LockupTorque = 3000.0; /*moment graniczny sprzegla blokujacego*/ - double hydro_TC_LockupRate = 1.0; /*szybkosc zalaczania sprzegla blokujacego*/ - double hydro_TC_UnlockRate = 1.0; /*szybkosc rozlaczania sprzegla blokujacego*/ - double hydro_TC_FillRateInc = 1.0; /*szybkosc napelniania sprzegla*/ - double hydro_TC_FillRateDec = 1.0; /*szybkosc oprozniania sprzegla*/ - double hydro_TC_TorqueInIn = 4.5; /*stala momentu proporcjonalnego do kwadratu obrotow wejsciowych*/ - double hydro_TC_TorqueInOut = 0.0; /*stala momentu proporcjonalnego do roznica obrotow wejsciowych i wyjsciowych*/ - double hydro_TC_TorqueOutOut = 0.0; /*stala momentu proporcjonalnego do kwadratu obrotow wyjsciowych*/ - double hydro_TC_LockupSpeed = 1.0; /*prog predkosci zalaczania sprzegla blokujacego*/ - double hydro_TC_UnlockSpeed = 1.0; /*prog predkosci rozlaczania sprzegla blokujacego*/ - std::map hydro_TC_Table; /*tablica przetwornika momentu*/ - /*parametry retardera*/ - bool hydro_R = false; /*obecnosc retardera*/ - int hydro_R_Placement = 0; /*umiejscowienie retardera: 0 - za skrzynia biegow, 1 - miedzy przetwornikiem a biegami, 2 - przed skrzynia biegow */ - double hydro_R_TorqueInIn = 1.0; /*stala momentu proporcjonalnego do kwadratu obrotow wejsciowych*/ - double hydro_R_MaxTorque = 1.0; /*maksymalny moment retardera*/ - double hydro_R_MaxPower = 1.0; /*maksymalna moc retardera - ogranicza moment*/ - double hydro_R_FillRateInc = 1.0; /*szybkosc napelniania sprzegla*/ - double hydro_R_FillRateDec = 1.0; /*szybkosc oprozniania sprzegla*/ - double hydro_R_MinVel = 1.0; /*minimalna predkosc, przy ktorej retarder dziala*/ - double hydro_R_EngageVel = 1.0; /*minimalna predkosc hamowania, przy ktorej sprzeglo jest wciaz wlaczone*/ - bool hydro_R_Clutch = false; /*czy retarder ma rozłączalne sprzęgło*/ - double hydro_R_ClutchSpeed = 10.0; /*szybkość narastania obrotów po włączeniu sprzęgła retardera*/ - bool hydro_R_WithIndividual = false; /*czy dla autobusów jest to łączone*/ /*- dla lokomotyw spalinowo-elektrycznych -*/ double AnPos = 0.0; // pozycja sterowania dokladnego (analogowego) bool AnalogCtrl = false; // @@ -1448,7 +1335,6 @@ class TMoverParameters water_pump WaterPump; water_heater WaterHeater; bool WaterCircuitsLink{false}; // optional connection between water circuits - heat_data dizel_heat; std::array MotorBlowers; door_data Doors; float DoorsOpenWithPermitAfter{-1.f}; // remote open if permit button is held for specified time. NOTE: separate from door data as its cab control thing @@ -1598,42 +1484,6 @@ class TMoverParameters bool s_CAtestebrake = false; // hunter-091012: zmienna dla testu ca std::array, 4> PowerCircuits; // 24v, 110v, 3x400v and 3000v power circuits, voltage from local sources and current draw pairs - /*-zmienne dla lokomotywy spalinowej z przekladnia mechaniczna*/ - double dizel_fill = 0.0; /*napelnienie*/ - double dizel_engagestate = 0.0; /*sprzeglo skrzyni biegow: 0 - luz, 1 - wlaczone, 0.5 - wlaczone 50% (z poslizgiem)*/ - double dizel_engage = 0.0; /*sprzeglo skrzyni biegow: aktualny docisk*/ - double dizel_automaticgearstatus = 0.0; /*0 - bez zmiany, -1 zmiana na nizszy +1 zmiana na wyzszy*/ - bool dizel_startup{false}; // engine startup procedure request indicator - bool dizel_ignition{false}; // engine ignition request indicator - bool dizel_spinup{false}; // engine spin up to idle speed flag - // the starter turns the engine a while before it fires: smoke comes out only after SmokeDelay (the Engine section of the vehicle's - // .fiz, seconds from the start of the spin up) has passed. 0, the default, lets it out as soon as the starter turns, as before eu07/maszyna#523 - double dizel_SmokeDelay{0.0}; - double dizel_FiringCountdown{0.0}; // seconds left until the engine being started fires, 0 once it runs on its own - double dizel_engagedeltaomega = 0.0; /*roznica predkosci katowych tarcz sprzegla*/ - double dizel_n_old = 0.0; /*poredkosc na potrzeby obliczen sprzegiel*/ - double dizel_Torque = 0.0; /*aktualny moment obrotowy silnika spalinowego*/ - double dizel_Power = 0.0; /*aktualna moc silnika spalinowego*/ - double dizel_nreg_min = 0.0; /*predkosc regulatora minimalna, zmienna w hydro*/ - double dizel_nreg_max = 0.0; /*predkosc regulatora maksymalna, zmienna w hydro*/ - - /* - zmienne dla przetowrnika momentu */ - double hydro_TC_Fill = 0.0; /*napelnienie*/ - bool hydro_TC_Lockup = false; /*zapiecie sprzegla*/ - double hydro_TC_TorqueIn = 0.0; /*moment*/ - double hydro_TC_TorqueOut = 0.0; /*moment*/ - double hydro_TC_TMRatio = 1.0; /*aktualne przelozenie momentu*/ - double hydro_TC_Request = 0.0; /*zadanie sily*/ - double hydro_TC_nIn = 0.0; /*predkosc obrotowa walu wejsciowego*/ - double hydro_TC_nOut = 0.0; /*predkosc obrotowa walu wyjsciowego*/ - - /* - zmienne dla przetowrnika momentu */ - double hydro_R_Fill = 0.0; /*napelnienie*/ - double hydro_R_Torque = 0.0; /*moment*/ - double hydro_R_Request = 0.0; /*zadanie sily hamowania*/ - double hydro_R_n = 0.0; /*predkosc obrotowa retardera*/ - bool hydro_R_ClutchActive = false; /*czy retarder jest napędzany*/ - /*- zmienne dla lokomotyw z silnikami indukcyjnymi -*/ double eimic = 0; /*aktualna pozycja zintegrowanego sterowania jazda i hamowaniem*/ double eimic_analog = 0; /*pozycja zadajnika analogowa*/ @@ -2329,7 +2179,7 @@ class TMoverParameters double dizel_DigitalFill(double dt); double dizel_GovernorFill(int mcp, double realfill) const; double dizel_GovernorRevolutions(int mcp, double &realfill) const; - double dizel_Momentum(double dizel_fill, double n, double dt); + double dizel_Momentum(double Fill, double n, double dt); void hydro_TCFillCheck(double dt); void hydro_TCTorque(); double dizel_MomentumRetarder(double n, double dt); // moment hamowania retardera diff --git a/rendering/particles.cpp b/rendering/particles.cpp index 67d81f3c2..391dd1903 100644 --- a/rendering/particles.cpp +++ b/rendering/particles.cpp @@ -346,19 +346,19 @@ smoke_source::launch_scales( float &Velocity, float &Opacity ) const { Opacity = 1.f; if( m_ownertype != owner_type::vehicle ) { return; } - Opacity = static_cast(m_owner.vehicle->MoverParameters->dizel_fill); + Opacity = static_cast(m_owner.vehicle->MoverParameters->diesel.fill); if (m_owner.vehicle->MoverParameters->EngineType == TEngineType::DieselElectric) { - if (m_owner.vehicle->MoverParameters->dizel_spinup == true) + if (m_owner.vehicle->MoverParameters->diesel.spinningUp == true) { - Velocity = static_cast(0.38*(((m_owner.vehicle->MoverParameters->enrot)/2)*0.5)); // / m_owner.vehicle->MoverParameters->dizel_fill *0.01)) ; + Velocity = static_cast(0.38*(((m_owner.vehicle->MoverParameters->enrot)/2)*0.5)); // / m_owner.vehicle->MoverParameters->diesel.fill *0.01)) ; } else { - Velocity = static_cast((((m_owner.vehicle->MoverParameters->enrot)/60)*0.6) * (m_owner.vehicle->MoverParameters->EnginePower *0.03)); // / m_owner.vehicle->MoverParameters->dizel_fill *0.01)) ; - //Particle.velocity *= m_owner.vehicle->GetVelocity(); // / m_owner.vehicle->MoverParameters->dizel_fill *0.01)) ; + Velocity = static_cast((((m_owner.vehicle->MoverParameters->enrot)/60)*0.6) * (m_owner.vehicle->MoverParameters->EnginePower *0.03)); // / m_owner.vehicle->MoverParameters->diesel.fill *0.01)) ; + //Particle.velocity *= m_owner.vehicle->GetVelocity(); // / m_owner.vehicle->MoverParameters->diesel.fill *0.01)) ; } } diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index 5d21c47d0..6b573e1ea 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -87,7 +87,7 @@ std::uint32_t devices_of(TMoverParameters const &Occupied, TMoverParameters cons on(Occupied.Hamulec != nullptr && Occupied.Hamulec->Releaser(), device::brake_releaser) | on(Controlling.FuelPump.is_active, device::fuel_pump) | on(Controlling.OilPump.is_active, device::oil_pump) | on(Controlling.MotorBlowers[end::front].is_active || Controlling.MotorBlowers[end::rear].is_active, device::motor_blowers) | - on(Controlling.dizel_heat.engine_is_hot, device::engine_hot) | on(Controlling.SpeedCtrl && Controlling.SpeedCtrlUnit.IsActive, device::speed_control); + on(Controlling.diesel.heat.engine_is_hot, device::engine_hot) | on(Controlling.SpeedCtrl && Controlling.SpeedCtrlUnit.IsActive, device::speed_control); } std::uint8_t engine_of(TMoverParameters const &Mover) { @@ -480,17 +480,17 @@ void blackbox_recorder::write_cab() { sample.driver_valve = occupied->Handle != nullptr ? static_cast(occupied->Handle->GetCP()) : 0.0f; sample.feed_pipe = static_cast(occupied->ScndPipePress); sample.oil_pressure = controlling->OilPump.pressure; - sample.water_temperature = controlling->dizel_heat.Twy; - sample.oil_temperature = controlling->dizel_heat.To; - sample.engine_temperature = controlling->dizel_heat.Ts; + sample.water_temperature = controlling->diesel.heat.Twy; + sample.oil_temperature = controlling->diesel.heat.To; + sample.engine_temperature = controlling->diesel.heat.Ts; sample.speed_control_kmh = controlling->SpeedCtrl ? static_cast(controlling->SpeedCtrlUnit.DesiredVelocity) : 0.0f; sample.engine_power = static_cast(controlling->EnginePower); sample.hand_brake = static_cast(std::clamp(occupied->ManualBrakePos, -128, 127)); sample.brake_mode = static_cast(occupied->BrakeOpModeFlag); sample.horn = static_cast(occupied->WarningSignal); sample.integrated_controller = static_cast(controlling->eimic); - sample.clutch = static_cast(controlling->dizel_engagestate); - sample.converter_fill = static_cast(controlling->hydro_TC_Fill); + sample.clutch = static_cast(controlling->diesel.clutchState); + sample.converter_fill = static_cast(controlling->torqueConverter.fill); // the brakes of the whole train: the highest of its cylinders, from the head to the tail auto brakes{occupied->BrakePress}; for (auto const *each{owner != nullptr ? owner->Vehicle(end::front) : nullptr}; each != nullptr; each = each->Next()) diff --git a/tests/unit/golden.cpp b/tests/unit/golden.cpp index 72cd31f9b..ce4225906 100644 --- a/tests/unit/golden.cpp +++ b/tests/unit/golden.cpp @@ -66,7 +66,7 @@ std::vector traction() { {"EngineVoltage", [](auto const &M) { return M.EngineVoltage; }}, {"EnginePower", [](auto const &M) { return M.EnginePower; }}, {"enrot", [](auto const &M) { return M.enrot; }}, - {"dizel_fill", [](auto const &M) { return M.dizel_fill; }}, + {"dizel_fill", [](auto const &M) { return M.diesel.fill; }}, {"eimv_pr", [](auto const &M) { return M.eimv_pr; }}, {"DynamicBrakeFlag", [](auto const &M) { return M.DynamicBrakeFlag ? 1.0 : 0.0; }}, }; diff --git a/tests/unit/invariants.cpp b/tests/unit/invariants.cpp index 4fafeb04d..e742fce41 100644 --- a/tests/unit/invariants.cpp +++ b/tests/unit/invariants.cpp @@ -84,14 +84,14 @@ std::vector const &invariants() { [](auto const &M, double, auto const *) { return M.Power >= 0.01 || std::abs(M.Ft) < 1.0; }, [](auto const &M) { return values({{"Power", M.Power}, {"Ft", M.Ft}}); }}, {"engine fill between none and full", - [](auto const &M, double, auto const *) { return M.dizel_fill >= 0.0 && M.dizel_fill <= 1.0; }, - [](auto const &M) { return values({{"dizel_fill", M.dizel_fill}}); }}, + [](auto const &M, double, auto const *) { return M.diesel.fill >= 0.0 && M.diesel.fill <= 1.0; }, + [](auto const &M) { return values({{"dizel_fill", M.diesel.fill}}); }}, {"diesel engine turning forward, no faster than its top speed", [](auto const &M, double, auto const *) { // the governor lets it overshoot a little (the SN61 by 1%) - return M.EngineType != TEngineType::DieselEngine || (M.enrot >= 0.0 && M.enrot <= 1.05 * M.dizel_nmax); + return M.EngineType != TEngineType::DieselEngine || (M.enrot >= 0.0 && M.enrot <= 1.05 * M.diesel.maxRevolutions); }, - [](auto const &M) { return values({{"enrot", M.enrot}, {"dizel_nmax", M.dizel_nmax}}); }}, + [](auto const &M) { return values({{"enrot", M.enrot}, {"dizel_nmax", M.diesel.maxRevolutions}}); }}, {"battery no higher than its nominal voltage", [](auto const &M, double, auto const *) { return M.NominalBatteryVoltage <= 0.0 || M.BatteryVoltage <= 1.05 * M.NominalBatteryVoltage; }, [](auto const &M) { return values({{"BatteryVoltage", M.BatteryVoltage}, {"NominalBatteryVoltage", M.NominalBatteryVoltage}}); }}, diff --git a/tests/unit/test_cab.cpp b/tests/unit/test_cab.cpp index c0896e6e3..ca58d6a65 100644 --- a/tests/unit/test_cab.cpp +++ b/tests/unit/test_cab.cpp @@ -60,7 +60,7 @@ TEST_CASE("cab: the lamps of the overload relay and the starting resistors, read TEST_CASE("cab: the engine's idle speed, and the ET42's second controller shown in its dynamic brake") { vehicle sn61{definition::fiz("sn61_v2/sn61")}; - CHECK(sn61->EngineIdleRPM() == doctest::Approx(sn61->dizel_nmin * 60.0)); + CHECK(sn61->EngineIdleRPM() == doctest::Approx(sn61->diesel.minRevolutions * 60.0)); vehicle su45{definition::fiz("su45_v2/301d")}; CHECK(su45->EngineIdleRPM() == doctest::Approx(su45->DElist[su45->MainCtrlNoPowerPos()].RPM)); vehicle eu07{definition::fiz("4e_v1/4e")}; diff --git a/tests/unit/test_diesel.cpp b/tests/unit/test_diesel.cpp index a902a0195..847633ec0 100644 --- a/tests/unit/test_diesel.cpp +++ b/tests/unit/test_diesel.cpp @@ -15,15 +15,15 @@ namespace { std::vector heat() { return { - {"Ts", [](auto const &M) { return M.dizel_heat.Ts; }}, - {"To", [](auto const &M) { return M.dizel_heat.To; }}, - {"Twy", [](auto const &M) { return M.dizel_heat.Twy; }}, - {"Twy2", [](auto const &M) { return M.dizel_heat.Twy2; }}, - {"PA", [](auto const &M) { return M.dizel_heat.PA ? 1.0 : 0.0; }}, + {"Ts", [](auto const &M) { return M.diesel.heat.Ts; }}, + {"To", [](auto const &M) { return M.diesel.heat.To; }}, + {"Twy", [](auto const &M) { return M.diesel.heat.Twy; }}, + {"Twy2", [](auto const &M) { return M.diesel.heat.Twy2; }}, + {"PA", [](auto const &M) { return M.diesel.heat.PA ? 1.0 : 0.0; }}, {"WaterHeater", [](auto const &M) { return M.WaterHeater.is_active ? 1.0 : 0.0; }}, {"WaterPump", [](auto const &M) { return M.WaterPump.is_active ? 1.0 : 0.0; }}, - {"zaluzje1", [](auto const &M) { return M.dizel_heat.zaluzje1 ? 1.0 : 0.0; }}, - {"zaluzje2", [](auto const &M) { return M.dizel_heat.zaluzje2 ? 1.0 : 0.0; }}, + {"zaluzje1", [](auto const &M) { return M.diesel.heat.zaluzje1 ? 1.0 : 0.0; }}, + {"zaluzje2", [](auto const &M) { return M.diesel.heat.zaluzje2 ? 1.0 : 0.0; }}, }; } @@ -43,12 +43,12 @@ TEST_CASE("diesel: an engine too cold to start, warmed by its heater") { auto &locomotive{scenario.cab()}; locomotive.dizel_HeatSet(-10.f); CHECK(scenario.start_up() == starts); - CHECK(locomotive.dizel_heat.PA != starts); + CHECK(locomotive.diesel.heat.PA != starts); CHECK(locomotive.WaterHeater.is_active); scenario.act("heating"); scenario.wait(1200.0); - CHECK_FALSE(locomotive.dizel_heat.PA); - CHECK(locomotive.dizel_heat.Twy > 50.f); + CHECK_FALSE(locomotive.diesel.heat.PA); + CHECK(locomotive.diesel.heat.Twy > 50.f); CHECK(scenario.start_up()); scenario.check(); } @@ -70,13 +70,13 @@ TEST_CASE("diesel: an engine started hot, and run at full power") { auto &locomotive{scenario.cab()}; locomotive.dizel_HeatSet(88.f); CHECK(scenario.start_up() == starts); - CHECK(locomotive.dizel_heat.PA != starts); + CHECK(locomotive.diesel.heat.PA != starts); if (starts) { scenario.get_going(); scenario.full_power(300.0); CHECK(locomotive.Vel > 50.0); - CHECK(locomotive.dizel_heat.zaluzje1); - CHECK(locomotive.dizel_heat.Twy < locomotive.dizel_heat.water.config.temp_max); + CHECK(locomotive.diesel.heat.zaluzje1); + CHECK(locomotive.diesel.heat.Twy < locomotive.diesel.heat.water.config.temp_max); } scenario.check(); } @@ -94,7 +94,7 @@ TEST_CASE("diesel: the 214M railbus's torque converter, gears and retarder") { scenario.full_power(60.0); CHECK(railbus.MainCtrlPos == 5); CHECK(railbus.eimic_real == doctest::Approx(1.0)); - CHECK(railbus.hydro_TC_Lockup); + CHECK(railbus.torqueConverter.lockedUp); CHECK(railbus.ScndCtrlActualPos == railbus.ScndCtrlPosNo); struct position { double eimic; @@ -109,8 +109,8 @@ TEST_CASE("diesel: the 214M railbus's torque converter, gears and retarder") { railbus.DecMainCtrl(1); scenario.wait(8.0); CHECK(railbus.eimic_real == doctest::Approx(eimic)); - CHECK((railbus.hydro_R_Fill > 0.99) == retarder); - CHECK((railbus.hydro_R_Torque > 1000.0) == retarder); + CHECK((railbus.retarder.fill > 0.99) == retarder); + CHECK((railbus.retarder.torque > 1000.0) == retarder); CHECK((railbus.BrakePress > 2.0) == air); } scenario.act("position 0"); @@ -160,7 +160,7 @@ TEST_CASE("diesel: the 214M railbus's speed control, up to the speed of a button scenario.wait(5.0); // the retarder does it at this speed, the air isn't needed CHECK(railbus.eimic_real == doctest::Approx(-1.0)); - CHECK(railbus.hydro_R_Fill == doctest::Approx(1.0)); + CHECK(railbus.retarder.fill == doctest::Approx(1.0)); CHECK(railbus.BrakePress < 0.1); CHECK_FALSE(railbus.SpeedCtrlUnit.BrakeInterventionBraking); scenario.wait(60.0); diff --git a/tests/unit/test_engine_shutdown.cpp b/tests/unit/test_engine_shutdown.cpp index 9230330f4..e9629c4ed 100644 --- a/tests/unit/test_engine_shutdown.cpp +++ b/tests/unit/test_engine_shutdown.cpp @@ -29,7 +29,7 @@ TEST_CASE("engine shutdown: the shunter starts with the starter button") { REQUIRE(shunter->FuelPump.start_type == start_t::automatic); CHECK(shunter->Mains); CHECK(shunter->FuelPump.is_active); - CHECK(shunter->enrot > 0.9 * shunter->dizel_nmin); + CHECK(shunter->enrot > 0.9 * shunter->diesel.minRevolutions); } TEST_CASE("engine shutdown: neither the fuel pump switch nor the battery switch stop the engine") { @@ -41,7 +41,7 @@ TEST_CASE("engine shutdown: neither the fuel pump switch nor the battery switch shunter.run(10.0); CHECK(shunter->Power110vIsAvailable); // the converter run by the engine keeps feeding the fuel pump CHECK(shunter->Mains); - CHECK(shunter->enrot > 0.9 * shunter->dizel_nmin); + CHECK(shunter->enrot > 0.9 * shunter->diesel.minRevolutions); } TEST_CASE("engine shutdown: the command opening the main circuit stops the engine and it stays stopped") { @@ -62,7 +62,7 @@ TEST_CASE("engine shutdown: the engine starts again after it was stopped") { shunter->MainSwitch(true); shunter.run(15.0); CHECK(shunter->Mains); - CHECK(shunter->enrot > 0.9 * shunter->dizel_nmin); + CHECK(shunter->enrot > 0.9 * shunter->diesel.minRevolutions); } TEST_CASE("engine shutdown: vehicles without a diesel keep ignoring the command with only the button closing the circuit") { diff --git a/tests/unit/test_engine_start.cpp b/tests/unit/test_engine_start.cpp index 59bb6af0e..a7aeff790 100644 --- a/tests/unit/test_engine_start.cpp +++ b/tests/unit/test_engine_start.cpp @@ -39,7 +39,7 @@ void prepare(consist &Train) { } bool running(TMoverParameters const &Vehicle) { - return Vehicle.Mains && Vehicle.enrot > 0.5 * Vehicle.dizel_nmin; + return Vehicle.Mains && Vehicle.enrot > 0.5 * Vehicle.diesel.minRevolutions; } // the time step of the train in the loops below @@ -185,7 +185,7 @@ TEST_CASE("engine start: the switch of another vehicle is held for the vehicle's hold(train, switchb, &second, 5.0); train.run(5.0); CHECK_FALSE(second.Mains); - CHECK_FALSE(second.dizel_startup); + CHECK_FALSE(second.diesel.startupRequested); prepare(train); // let go too early diff --git a/tests/unit/test_oil_pump.cpp b/tests/unit/test_oil_pump.cpp index a5f623233..aaac2e871 100644 --- a/tests/unit/test_oil_pump.cpp +++ b/tests/unit/test_oil_pump.cpp @@ -31,11 +31,11 @@ TEST_CASE("oil pump: the pump started with the engine start procedure stops once REQUIRE(loco->OilPump.start_type == start_t::automatic); loco->Power24vIsAvailable = true; - loco->dizel_startup = true; // starter button pressed + loco->diesel.startupRequested = true; // starter button pressed loco->OilPumpCheck(0.01); CHECK(loco->OilPump.is_active); - loco->dizel_startup = false; // start procedure done, the pump keeps working until the engine runs + loco->diesel.startupRequested = false; // start procedure done, the pump keeps working until the engine runs loco->OilPumpCheck(0.01); CHECK(loco->OilPump.is_active); diff --git a/tests/unit/test_smoke.cpp b/tests/unit/test_smoke.cpp index 281b5dbf6..e8c31d87b 100644 --- a/tests/unit/test_smoke.cpp +++ b/tests/unit/test_smoke.cpp @@ -28,7 +28,7 @@ test::vehicle diesel() { TEST_CASE("smoke: a vehicle taken off the tracks puffs no more (#90)") { auto vehicle{diesel()}; - SUBCASE("engine starting") { vehicle->dizel_spinup = true; } + SUBCASE("engine starting") { vehicle->diesel.spinningUp = true; } SUBCASE("engine idling") { vehicle->DirAbsolute = 0; } SUBCASE("engine under load") { vehicle->DirAbsolute = 1; @@ -68,7 +68,7 @@ TEST_CASE("smoke: the engine adds to the steady rate of the source") { CHECK(working > steady); // the faster the starting engine turns, the more it puffs - vehicle->dizel_spinup = true; + vehicle->diesel.spinningUp = true; vehicle->enrot = 100.0; auto const slow{smoke::vehicle_spawn_count(vehicle.mover(), true, source, update)}; vehicle->enrot = 400.0; @@ -77,7 +77,7 @@ TEST_CASE("smoke: the engine adds to the steady rate of the source") { TEST_CASE("smoke: the pending particles never outgrow the room of the source") { auto vehicle{diesel()}; - vehicle->dizel_spinup = true; + vehicle->diesel.spinningUp = true; vehicle->enrot = 100000.0; auto rate{source}; rate.pending = 99.f; @@ -87,14 +87,14 @@ TEST_CASE("smoke: the pending particles never outgrow the room of the source") { TEST_CASE("smoke: an engine the starter turns lets out no smoke until it fires (#523)") { auto vehicle{diesel()}; - vehicle->dizel_spinup = true; + vehicle->diesel.spinningUp = true; auto pending{source}; pending.pending = 5.f; - vehicle->dizel_FiringCountdown = 0.5; + vehicle->diesel.firingCountdown = 0.5; CHECK(smoke::vehicle_spawn_count(vehicle.mover(), true, pending, update) == 0.f); - vehicle->dizel_FiringCountdown = 0.0; + vehicle->diesel.firingCountdown = 0.0; CHECK(smoke::vehicle_spawn_count(vehicle.mover(), true, pending, update) >= 1.f); } @@ -118,16 +118,16 @@ TEST_CASE("smoke: a real diesel smokes only once its engine has fired, SmokeDela { // SmokeDelay set in the .fiz of the locomotive test::vehicle locomotive{test::definition{test::definition::fiz(path)}.set("Engine", "SmokeDelay", 2)}; - REQUIRE(locomotive->dizel_SmokeDelay == doctest::Approx(2.0)); + REQUIRE(locomotive->diesel.smokeDelay == doctest::Approx(2.0)); auto const driven{test::driving(locomotive)}; REQUIRE(start_engine(driven, track)); // the engine started less than a second ago: the starter still turns it - CHECK(locomotive->dizel_FiringCountdown > 0.5); + CHECK(locomotive->diesel.firingCountdown > 0.5); CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) == 0.f); // it has fired since test::drive(driven, track, 3.0); CHECK(locomotive->Mains); - CHECK(locomotive->dizel_FiringCountdown == 0.0); + CHECK(locomotive->diesel.firingCountdown == 0.0); CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) >= 1.f); } { @@ -149,13 +149,13 @@ TEST_CASE("smoke: without SmokeDelay in its .fiz a diesel smokes as soon as the test::track const track{}; // a locomotive which has the delay, loaded first, doesn't hand it on to the next one: the value is the vehicle's own test::vehicle delayed{test::definition{test::definition::fiz(path)}.set("Engine", "SmokeDelay", 3)}; - REQUIRE(delayed->dizel_SmokeDelay == doctest::Approx(3.0)); + REQUIRE(delayed->diesel.smokeDelay == doctest::Approx(3.0)); test::vehicle locomotive{test::definition::fiz(path)}; - REQUIRE(locomotive->dizel_SmokeDelay == 0.0); - CHECK(delayed->dizel_SmokeDelay == doctest::Approx(3.0)); + REQUIRE(locomotive->diesel.smokeDelay == 0.0); + CHECK(delayed->diesel.smokeDelay == doctest::Approx(3.0)); auto const driven{test::driving(locomotive)}; REQUIRE(start_engine(driven, track)); - CHECK(locomotive->dizel_FiringCountdown == 0.0); + CHECK(locomotive->diesel.firingCountdown == 0.0); CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) >= 1.f); } } diff --git a/vehicle/ai/consist.cpp b/vehicle/ai/consist.cpp index d9994df93..8fa123ed9 100644 --- a/vehicle/ai/consist.cpp +++ b/vehicle/ai/consist.cpp @@ -951,7 +951,7 @@ TController::determine_consist_state() { Ready = vehicle->Vel > EU07_AI_MOVEMENT // already moving || false == vehicle->Mains // deadweight vehicle - || vehicle->enrot > 0.8 * (vehicle->EngineType == TEngineType::DieselEngine ? vehicle->dizel_nmin : vehicle->DElist[0].RPM / 60.0); + || vehicle->enrot > 0.8 * (vehicle->EngineType == TEngineType::DieselEngine ? vehicle->diesel.minRevolutions : vehicle->DElist[0].RPM / 60.0); } p = p->Next(); // pojazd podłączony z tyłu (patrząc od czoła) } diff --git a/vehicle/ai/controls.cpp b/vehicle/ai/controls.cpp index cde186f61..4163afc9e 100644 --- a/vehicle/ai/controls.cpp +++ b/vehicle/ai/controls.cpp @@ -707,7 +707,7 @@ bool TController::IncSpeed() if (mvControlling->EIMCtrlType > 0) { if (true == Ready) { - bool max = mvControlling->Vel > mvControlling->dizel_minVelfullengage + bool max = mvControlling->Vel > mvControlling->diesel.fullEngageMinVelocity || (mvControlling->SpeedCtrl && mvControlling->ScndCtrlPos > 0); DizelPercentage = max ? 100 : 1; } @@ -715,7 +715,7 @@ bool TController::IncSpeed() } else { if( true == Ready ) { - if( mvControlling->Vel > mvControlling->dizel_minVelfullengage + if( mvControlling->Vel > mvControlling->diesel.fullEngageMinVelocity && mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0 ) { OK = mvControlling->IncMainCtrl( 1 ); } @@ -794,7 +794,7 @@ bool TController::DecSpeed(bool force) break; } - if (mvControlling->Vel > mvControlling->dizel_minVelfullengage) + if (mvControlling->Vel > mvControlling->diesel.fullEngageMinVelocity) { if (mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0) OK = mvControlling->DecMainCtrl(1); @@ -1202,7 +1202,7 @@ void TController::SetTimeControllers() { DizelPercentage_Speed = DizelPercentage; //wstepnie procenty - auto MinVel{ std::min(mvControlling->hydro_TC_LockupSpeed, mvControlling->Vmax / 6) }; //minimal velocity + auto MinVel{ std::min(mvControlling->torqueConverter.lockupSpeed, mvControlling->Vmax / 6) }; //minimal velocity //when speed controll unit is active - start with the procedure if (mvControlling->SpeedCtrl && mvControlling->ScndCtrlPos > 0) { if (mvControlling->ScndCtrlPos > 0 && mvControlling->Vel < 1 + mvControlling->SpeedCtrlUnit.StartVelocity && DizelPercentage > 0) @@ -1272,7 +1272,7 @@ void TController::SetTimeControllers() if (!mvControlling->SlippingWheels) { while (mvControlling->MainCtrlPos > DesiredPos) mvControlling->DecMainCtrl(1); - if (mvControlling->Vel>mvControlling->dizel_minVelfullengage) + if (mvControlling->Vel>mvControlling->diesel.fullEngageMinVelocity) while (mvControlling->MainCtrlPos < DesiredPos) mvControlling->IncMainCtrl(1); } } diff --git a/vehicle/ai/engine.cpp b/vehicle/ai/engine.cpp index 7142d43c1..8194aecb7 100644 --- a/vehicle/ai/engine.cpp +++ b/vehicle/ai/engine.cpp @@ -364,7 +364,7 @@ TController::PrepareHeating() { case TEngineType::DieselElectric: case TEngineType::DieselEngine: { - auto const &heat { mvControlling->dizel_heat }; + auto const &heat { mvControlling->diesel.heat }; // determine whether there's need to enable the water heater // if the heater has configured maximum temperature, it'll disable itself automatically, so we can leave it always running diff --git a/vehicle/ai/physicslog.cpp b/vehicle/ai/physicslog.cpp index 758bd1184..cc32e5738 100644 --- a/vehicle/ai/physicslog.cpp +++ b/vehicle/ai/physicslog.cpp @@ -85,10 +85,10 @@ std::string TController::physicslog_line() const { << mvOccupied->CommandIn.Value2 << " " << int(mvControlling->SecuritySystem.is_blinking()) << " " << int(mvControlling->SlippingWheels) << " " - << mvControlling->dizel_heat.Ts << " " - << mvControlling->dizel_heat.To << " " - << mvControlling->dizel_heat.temperatura1 << " " - << mvControlling->dizel_heat.temperatura2 << " " + << 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 << mvOccupied->V * 3.6 << "\r\n"; diff --git a/vehicle/cab/setup.cpp b/vehicle/cab/setup.cpp index ba53920d7..e72aefc54 100644 --- a/vehicle/cab/setup.cpp +++ b/vehicle/cab/setup.cpp @@ -1880,21 +1880,21 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con // oil temperature auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(&mvControlled->dizel_heat.To); + gauge.AssignFloat(&mvControlled->diesel.heat.To); } else if (Label == "water1temp:") { // main circuit water temperature auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(&mvControlled->dizel_heat.temperatura1); + gauge.AssignFloat(&mvControlled->diesel.heat.temperatura1); } else if (Label == "water2temp:") { // auxiliary circuit water temperature auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(&mvControlled->dizel_heat.temperatura2); + gauge.AssignFloat(&mvControlled->diesel.heat.temperatura2); } else if (Label == "pantpress:") { @@ -1982,7 +1982,7 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con // np. ciśnienie sterownika sprzęgła auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject); - gauge.AssignDouble(&mvControlled->dizel_engage); + gauge.AssignDouble(&mvControlled->diesel.clutchPressure); } // ggEngageRatio.Load(Parser,DynamicObject->mdKabina); else if (Label == "maingearstatus:") { diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index a68733c00..5d193a004 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -56,7 +56,7 @@ bool TTrain::Update(double const Deltatime) // crude way to sync state of the linebreaker with ai-issued commands m_linebreakerstate = linebreaker::state::closed; } - if (m_linebreakerstate == linebreaker::state::closed && false == (mvControlled->Mains || mvControlled->dizel_startup)) + if (m_linebreakerstate == linebreaker::state::closed && false == (mvControlled->Mains || mvControlled->diesel.startupRequested)) { // crude way to catch cases where the main was knocked out // because the state of the line breaker isn't changed to match, we need to do it here manually @@ -378,13 +378,13 @@ bool TTrain::Update(double const Deltatime) fDieselParams[1 + in][0] = static_cast(p->MoverParameters->enrot * 60); fDieselParams[1 + in][1] = static_cast(p->MoverParameters->nrot); fDieselParams[1 + in][2] = static_cast(p->MoverParameters->RList[p->MoverParameters->MainCtrlPos].R); - fDieselParams[1 + in][3] = static_cast(p->MoverParameters->dizel_fill); + fDieselParams[1 + in][3] = static_cast(p->MoverParameters->diesel.fill); fDieselParams[1 + in][4] = static_cast(p->MoverParameters->RList[p->MoverParameters->MainCtrlPos].Mn); - fDieselParams[1 + in][5] = static_cast(p->MoverParameters->dizel_engage); - fDieselParams[1 + in][6] = p->MoverParameters->dizel_heat.Twy; + fDieselParams[1 + in][5] = static_cast(p->MoverParameters->diesel.clutchPressure); + fDieselParams[1 + in][6] = p->MoverParameters->diesel.heat.Twy; fDieselParams[1 + in][7] = p->MoverParameters->OilPump.pressure; - fDieselParams[1 + in][8] = p->MoverParameters->dizel_heat.Ts; - fDieselParams[1 + in][9] = static_cast(p->MoverParameters->hydro_R_Fill); + fDieselParams[1 + in][8] = p->MoverParameters->diesel.heat.Ts; + fDieselParams[1 + in][9] = static_cast(p->MoverParameters->retarder.fill); bMains[in] = p->MoverParameters->Mains; fCntVol[in] = static_cast(p->MoverParameters->BatteryVoltage); bFuse[in] = p->MoverParameters->FuseFlag; @@ -523,7 +523,7 @@ bool TTrain::Update(double const Deltatime) } if (ggWater1TempB.SubModel) { - ggWater1TempB.UpdateValue(tmp->MoverParameters->dizel_heat.temperatura1); + ggWater1TempB.UpdateValue(tmp->MoverParameters->diesel.heat.temperatura1); ggWater1TempB.Update(); } if (ggOilPressB.SubModel) @@ -605,14 +605,14 @@ bool TTrain::Update(double const Deltatime) if (ggMainGearStatus.SubModel) { if (mvControlled->Mains) - ggMainGearStatus.UpdateValue(static_cast(1.1 - std::abs(mvControlled->dizel_automaticgearstatus))); + ggMainGearStatus.UpdateValue(static_cast(1.1 - std::abs(mvControlled->diesel.automaticGearShift))); else ggMainGearStatus.UpdateValue(0.0); ggMainGearStatus.Update(); } if (ggIgnitionKey.SubModel && ggIgnitionKey.GetDesiredValue() == 0.0) { - ggIgnitionKey.UpdateValue(mvControlled->Mains || mvControlled->dizel_startup || fMainRelayTimer > 0.f || + ggIgnitionKey.UpdateValue(mvControlled->Mains || mvControlled->diesel.startupRequested || fMainRelayTimer > 0.f || (ggMainButton.SubModel != nullptr && ggMainButton.GetDesiredValue() > 0.95) || (ggMainOnButton.SubModel != nullptr && ggMainOnButton.GetDesiredValue() > 0.95)); } @@ -721,9 +721,9 @@ bool TTrain::Update(double const Deltatime) btLampkaBocznik4.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlPos > 3 || mvControlled->ScndCtrlActualPos > 3 || scp > 3); // biegi dla motoraka - btLampkaGear1.Turn(mvControlled->ScndCtrlActualPos == 1 && mvControlled->dizel_engagestate > 0); // bieg 1 - btLampkaGear2.Turn(mvControlled->ScndCtrlActualPos == 2 && mvControlled->dizel_engagestate > 0); // bieg 2 - btLampkaHydroLockup.Turn(mvControlled->hydro_TC_Lockup); // zblokowanie skrzyni z silnikiem + btLampkaGear1.Turn(mvControlled->ScndCtrlActualPos == 1 && mvControlled->diesel.clutchState > 0); // bieg 1 + btLampkaGear2.Turn(mvControlled->ScndCtrlActualPos == 2 && mvControlled->diesel.clutchState > 0); // bieg 2 + btLampkaHydroLockup.Turn(mvControlled->torqueConverter.lockedUp); // zblokowanie skrzyni z silnikiem if (mvControlled->Signalling == true) { @@ -829,12 +829,12 @@ bool TTrain::Update(double const Deltatime) btLampkaRearLeftEndLight.Turn((mvOccupied->iLights[end::rear] & light::redmarker_left) != 0); btLampkaRearRightEndLight.Turn((mvOccupied->iLights[end::rear] & light::redmarker_right) != 0); // others - btLampkaMalfunction.Turn(mvControlled->dizel_heat.PA); + btLampkaMalfunction.Turn(mvControlled->diesel.heat.PA); // overheat indicator lamps - btLampkaOilOverheat.Turn(mvControlled->dizel_heat.oil.is_hot); - btLampkaWaterOverheat.Turn(mvControlled->dizel_heat.water.is_hot); - btLampkaWaterAuxOverheat.Turn(mvControlled->dizel_heat.water_aux.is_hot); - btLampkaEngineOverheat.Turn(mvControlled->dizel_heat.engine_is_hot); + btLampkaOilOverheat.Turn(mvControlled->diesel.heat.oil.is_hot); + btLampkaWaterOverheat.Turn(mvControlled->diesel.heat.water.is_hot); + btLampkaWaterAuxOverheat.Turn(mvControlled->diesel.heat.water_aux.is_hot); + btLampkaEngineOverheat.Turn(mvControlled->diesel.heat.engine_is_hot); btLampkaMotorBlowers.Turn(mvControlled->MotorBlowers[end::front].is_active && mvControlled->MotorBlowers[end::rear].is_active); btLampkaCoolingFans.Turn(mvControlled->RventRot > 1.0); btLampkaLouvresClosed.Turn(mvControlled->LouvresClosed()); @@ -993,7 +993,7 @@ bool TTrain::Update(double const Deltatime) btLampkaPrzetwB.Turn(mover->ConverterFlag); // zalaczenie przetwornicy btLampkaPrzetwBOff.Turn(false == mover->ConverterFlag); btLampkaHVoltageB.Turn(mover->NoVoltRelay && mover->OvervoltageRelay); - btLampkaMalfunctionB.Turn(mover->dizel_heat.PA); + btLampkaMalfunctionB.Turn(mover->diesel.heat.PA); // motor fuse indicator turns on if the fuse was blown in any unit under control if (mover->Mains) { diff --git a/vehicle/dynamic/lifecycle.cpp b/vehicle/dynamic/lifecycle.cpp index a442440d3..128fb73c2 100644 --- a/vehicle/dynamic/lifecycle.cpp +++ b/vehicle/dynamic/lifecycle.cpp @@ -653,10 +653,10 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" btMechanik1.Init( "mechanik1", mdLowPolyInt, false); btMechanik2.Init( "mechanik2", mdLowPolyInt, false); - if( MoverParameters->dizel_heat.water.config.shutters ) { + if( MoverParameters->diesel.heat.water.config.shutters ) { btShutters1.Init( "shutters1", mdModel, false ); } - if( MoverParameters->dizel_heat.water_aux.config.shutters ) { + if( MoverParameters->diesel.heat.water_aux.config.shutters ) { btShutters2.Init( "shutters2", mdModel, false ); } TurnOff(); // resetowanie zmiennych submodeli diff --git a/vehicle/dynamic/sounds.cpp b/vehicle/dynamic/sounds.cpp index fe661e2a4..3cde7887c 100644 --- a/vehicle/dynamic/sounds.cpp +++ b/vehicle/dynamic/sounds.cpp @@ -1022,8 +1022,8 @@ TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, doub } case TEngineType::DieselEngine: { if( Vehicle.enrot > 0.0 ) { - volume = Vehicle.EnginePower > 0 ? engine.m_amplitudeoffset + engine.m_amplitudefactor * Vehicle.dizel_fill : - engine.m_amplitudeoffset + engine.m_amplitudefactor * std::fabs(Vehicle.enrot / Vehicle.dizel_nmax); + volume = Vehicle.EnginePower > 0 ? engine.m_amplitudeoffset + engine.m_amplitudefactor * Vehicle.diesel.fill : + engine.m_amplitudeoffset + engine.m_amplitudefactor * std::fabs(Vehicle.enrot / Vehicle.diesel.maxRevolutions); } break; } @@ -1108,7 +1108,7 @@ TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, doub // youBy - przenioslem, bo diesel tez moze miec turbo if( Vehicle.TurboTest > 0 ) { // udawanie turbo: - auto const pitch_diesel{Vehicle.EngineType == TEngineType::DieselEngine || Vehicle.EngineType == TEngineType::DieselElectric ? Vehicle.enrot / Vehicle.dizel_nmax * Vehicle.dizel_fill : 1}; + auto const pitch_diesel{Vehicle.EngineType == TEngineType::DieselEngine || Vehicle.EngineType == TEngineType::DieselElectric ? Vehicle.enrot / Vehicle.diesel.maxRevolutions * Vehicle.diesel.fill : 1}; auto const goalpitch { std::max( 0.025, ( /*engine_volume **/ pitch_diesel + engine_turbo.m_frequencyoffset ) * engine_turbo.m_frequencyfactor ) }; auto const goalvolume { ( Vehicle.MainCtrlPos >= Vehicle.TurboTest && Vehicle.enrot > 0.1 ? @@ -1133,14 +1133,14 @@ TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, doub } } - if( Vehicle.dizel_engage > 0.1 ) { - if( std::abs( Vehicle.dizel_engagedeltaomega ) > 0.2 ) { - frequency = rsEngageSlippery.m_frequencyoffset + rsEngageSlippery.m_frequencyfactor * std::fabs( Vehicle.dizel_engagedeltaomega ); - volume = rsEngageSlippery.m_amplitudeoffset + rsEngageSlippery.m_amplitudefactor * Vehicle.dizel_engage; + if( Vehicle.diesel.clutchPressure > 0.1 ) { + if( std::abs( Vehicle.diesel.clutchSlip ) > 0.2 ) { + frequency = rsEngageSlippery.m_frequencyoffset + rsEngageSlippery.m_frequencyfactor * std::fabs( Vehicle.diesel.clutchSlip ); + volume = rsEngageSlippery.m_amplitudeoffset + rsEngageSlippery.m_amplitudefactor * Vehicle.diesel.clutchPressure; } else { frequency = 1.f; // rsEngageSlippery.FA+0.7*rsEngageSlippery.FM*(fabs(mvControlled->enrot)+mvControlled->nmax); - volume = Vehicle.dizel_engage > 0.2 ? rsEngageSlippery.m_amplitudeoffset + 0.2 * rsEngageSlippery.m_amplitudefactor * (Vehicle.enrot / Vehicle.nmax) : 0.f; + volume = Vehicle.diesel.clutchPressure > 0.2 ? rsEngageSlippery.m_amplitudeoffset + 0.2 * rsEngageSlippery.m_amplitudefactor * (Vehicle.enrot / Vehicle.nmax) : 0.f; } rsEngageSlippery @@ -1152,14 +1152,14 @@ TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, doub rsEngageSlippery.stop(); } - if (Vehicle.hydro_R) { - float speed = std::abs(Vehicle.hydro_R_n); + if (Vehicle.retarder.present) { + float speed = std::abs(Vehicle.retarder.revolutions); retarder .pitch(retarder.m_frequencyoffset + speed * retarder.m_frequencyfactor) - .gain(retarder.m_amplitudeoffset + Vehicle.hydro_R_Fill * retarder.m_amplitudefactor); + .gain(retarder.m_amplitudeoffset + Vehicle.retarder.fill * retarder.m_amplitudefactor); - if (retarder.gain() > 0.01 && speed > 1 && Vehicle.hydro_R_ClutchActive) { + if (retarder.gain() > 0.01 && speed > 1 && Vehicle.retarder.clutchActive) { retarder.play(sound_flags::exclusive | sound_flags::looping); } else { @@ -1332,11 +1332,11 @@ TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, doub if( Vehicle.EngineType == TEngineType::DieselEngine || Vehicle.EngineType == TEngineType::DieselElectric ) { - if( Vehicle.dizel_heat.rpmw > 0.1 ) { + if( Vehicle.diesel.heat.rpmw > 0.1 ) { // NOTE: fan speed tends to max out at ~100 rpm; by default we try to get pitch range of 0.5-1.5 and volume range of 0.5-1.0 radiator_fan - .pitch( 0.5 + radiator_fan.m_frequencyoffset + radiator_fan.m_frequencyfactor * Vehicle.dizel_heat.rpmw * 0.01 ) - .gain( 0.5 + radiator_fan.m_amplitudeoffset + 0.5 * radiator_fan.m_amplitudefactor * Vehicle.dizel_heat.rpmw * 0.01 ) + .pitch( 0.5 + radiator_fan.m_frequencyoffset + radiator_fan.m_frequencyfactor * Vehicle.diesel.heat.rpmw * 0.01 ) + .gain( 0.5 + radiator_fan.m_amplitudeoffset + 0.5 * radiator_fan.m_amplitudefactor * Vehicle.diesel.heat.rpmw * 0.01 ) .play( sound_flags::exclusive | sound_flags::looping ); } else { @@ -1344,11 +1344,11 @@ TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, doub radiator_fan.stop(); } - if( Vehicle.dizel_heat.rpmw2 > 0.1 ) { + if( Vehicle.diesel.heat.rpmw2 > 0.1 ) { // NOTE: fan speed tends to max out at ~100 rpm; by default we try to get pitch range of 0.5-1.5 and volume range of 0.5-1.0 radiator_fan_aux - .pitch( 0.5 + radiator_fan_aux.m_frequencyoffset + radiator_fan_aux.m_frequencyfactor * Vehicle.dizel_heat.rpmw2 * 0.01 ) - .gain( 0.5 + radiator_fan_aux.m_amplitudeoffset + 0.5 * radiator_fan_aux.m_amplitudefactor * Vehicle.dizel_heat.rpmw2 * 0.01 ) + .pitch( 0.5 + radiator_fan_aux.m_frequencyoffset + radiator_fan_aux.m_frequencyfactor * Vehicle.diesel.heat.rpmw2 * 0.01 ) + .gain( 0.5 + radiator_fan_aux.m_amplitudeoffset + 0.5 * radiator_fan_aux.m_amplitudefactor * Vehicle.diesel.heat.rpmw2 * 0.01 ) .play( sound_flags::exclusive | sound_flags::looping ); } else { diff --git a/vehicle/dynamic/visual.cpp b/vehicle/dynamic/visual.cpp index 16b196acc..3f01e16de 100644 --- a/vehicle/dynamic/visual.cpp +++ b/vehicle/dynamic/visual.cpp @@ -406,13 +406,13 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) // cooling shutters // NOTE: shutters display _on state when they're closed, _off otherwise - if( true == MoverParameters->dizel_heat.water.config.shutters - && false == MoverParameters->dizel_heat.zaluzje1 ) { + if( true == MoverParameters->diesel.heat.water.config.shutters + && false == MoverParameters->diesel.heat.zaluzje1 ) { btShutters1.Turn( true ); btnOn = true; } - if( true == MoverParameters->dizel_heat.water_aux.config.shutters - && false == MoverParameters->dizel_heat.zaluzje2 ) { + if( true == MoverParameters->diesel.heat.water_aux.config.shutters + && false == MoverParameters->diesel.heat.zaluzje2 ) { btShutters2.Turn( true ); btnOn = true; } diff --git a/vehicle/enginestart.cpp b/vehicle/enginestart.cpp index ca276b73c..a1178196e 100644 --- a/vehicle/enginestart.cpp +++ b/vehicle/enginestart.cpp @@ -103,7 +103,7 @@ bool remote_switch::open(TMoverParameters &Engine) { } bool remote_switch::is_running(TMoverParameters const &Engine) { - return Engine.Mains || Engine.dizel_startup; + return Engine.Mains || Engine.diesel.startupRequested; } } // namespace engine_start diff --git a/vehicle/smoke.cpp b/vehicle/smoke.cpp index 88897c722..b12c4d3ca 100644 --- a/vehicle/smoke.cpp +++ b/vehicle/smoke.cpp @@ -18,7 +18,7 @@ namespace { // how hard the engine works, scaling the spawn rate of the source double engine_load(TMoverParameters const &Mover) { - if (Mover.dizel_spinup) { + if (Mover.diesel.spinningUp) { // starting up, it puffs harder the faster it turns return ((Mover.enrot / 4) * 0.01); } @@ -34,7 +34,7 @@ double engine_load(TMoverParameters const &Mover) { } // namespace float vehicle_spawn_count(TMoverParameters const &Mover, bool const Ontracks, spawn_rate const &Rate, double const Timedelta) { - if (false == Ontracks || Mover.dizel_FiringCountdown > 0.0) { + if (false == Ontracks || Mover.diesel.firingCountdown > 0.0) { return 0.f; } // the steady rate of the source, the way a source of the scenery spawns... diff --git a/vehicle/smoke.h b/vehicle/smoke.h index dbcc131ae..e3c3adec5 100644 --- a/vehicle/smoke.h +++ b/vehicle/smoke.h @@ -25,7 +25,7 @@ struct spawn_rate { // number of particles the smoke source of a vehicle has to spawn after Timedelta seconds: the steady rate of the // source, plus a share which grows with the work of its engine. a vehicle taken off the tracks (Ontracks false: gone through a portal, or waiting in the pool of the road // traffic) puffs no more, the particles it already let out fade away as usual -// an engine the starter turns but which hasn't fired yet (TMoverParameters::dizel_FiringCountdown) lets out no smoke either +// an engine the starter turns but which hasn't fired yet (TMoverParameters::diesel.firingCountdown) lets out no smoke either float vehicle_spawn_count(TMoverParameters const &Mover, bool Ontracks, spawn_rate const &Rate, double Timedelta); } // namespace smoke diff --git a/widgets/vehicleparams.cpp b/widgets/vehicleparams.cpp index 56f28782b..02b924bad 100644 --- a/widgets/vehicleparams.cpp +++ b/widgets/vehicleparams.cpp @@ -173,14 +173,14 @@ void ui::vehicleparams_panel::render_contents() mover.EnginePower, std::abs(mover.TrainType == train_type::emu ? mover.ShowCurrent(0) : mover.Im), // revolutions std::abs(mover.enrot) * 60, std::abs(mover.nrot) * mover.Transmision.Ratio * 60, mover.RventRot * 60, std::abs(mover.MotorBlowers[end::front].revolutions), - std::abs(mover.MotorBlowers[end::rear].revolutions), mover.dizel_heat.rpmw, mover.dizel_heat.rpmw2); + std::abs(mover.MotorBlowers[end::rear].revolutions), mover.diesel.heat.rpmw, mover.diesel.heat.rpmw2); ImGui::TextUnformatted(buffer.data()); if (isdieselenginepowered) { - std::snprintf(buffer.data(), buffer.size(), STR_C("\nTemperatures:\n engine: %.2f, oil: %.2f, water: %.2f%c%.2f"), mover.dizel_heat.Ts, mover.dizel_heat.To, mover.dizel_heat.temperatura1, - (mover.WaterCircuitsLink ? '-' : '|'), mover.dizel_heat.temperatura2); + std::snprintf(buffer.data(), buffer.size(), STR_C("\nTemperatures:\n engine: %.2f, oil: %.2f, water: %.2f%c%.2f"), mover.diesel.heat.Ts, mover.diesel.heat.To, mover.diesel.heat.temperatura1, + (mover.WaterCircuitsLink ? '-' : '|'), mover.diesel.heat.temperatura2); ImGui::TextUnformatted(buffer.data()); } From ff739d23285e87f02f0a78e3a18209b53a2f06e5 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sat, 28 Nov 2026 15:43:22 +0100 Subject: [PATCH 020/123] refactor(physics): the induction motor drive is a component of its own The fields of the drive of asynchronous motors fed by inverters move from TMoverParameters into InductionMotor inductionMotor (physics/components/inductionmotor.h): eimc[26] config (std::array, indexed by eimc_* as before) eimv[21] state (std::array, indexed by eimv_*) eimv_pr forceShare InverterFrequency inverterFrequency InvertersNo, InvertersRatio inverterCount, inverterRatio Inverters inverters (of Inverter, inverter before) InverterControlCouplerFlag inverterControlCouplings EIM_Pmax_Table maxPowerTable EIMCLogForce logForce The integrated controller (eimic, EIMCtrlType), which the diesel-electric vehicles use too, and the ED/EP blending (MED_*) stay where they are. No change in behaviour: 1144/1144 tests, golden traces exact against staging 62f7a29b. --- application/driveruipanels.cpp | 6 +- physics/components/body.cpp | 12 +-- physics/components/controllers.cpp | 4 +- physics/components/drive.cpp | 2 +- physics/components/electrics.cpp | 2 +- physics/components/fizparser.cpp | 2 +- physics/components/fizsections.cpp | 64 +++++------ physics/components/inductionmotor.h | 45 ++++++++ physics/components/traction.cpp | 160 ++++++++++++++-------------- physics/mover.h | 26 +---- tests/unit/golden.cpp | 2 +- tests/unit/test_definition.cpp | 2 +- tests/unit/test_elf_controller.cpp | 2 +- tests/unit/test_fcfuh_default.cpp | 10 +- tests/unit/test_genset.cpp | 8 +- vehicle/cab/equipmentcommands.cpp | 32 +++--- vehicle/cab/setup.cpp | 10 +- vehicle/cab/train.cpp | 12 +-- vehicle/cab/update.cpp | 20 ++-- vehicle/dynamic/sounds.cpp | 14 +-- vehicle/dynamic/update.cpp | 26 ++--- 21 files changed, 244 insertions(+), 217 deletions(-) create mode 100644 physics/components/inductionmotor.h diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index a6fd2ee8b..06c703089 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -1098,9 +1098,9 @@ debug_panel::update_section_engine( std::vector &Output ) const { for( int i = 0; i <= 20; ++i ) { std::string parameters = - TMoverParameters::eimc_labels[ i ] + to_string( mover.eimc[ i ], 2, 9 ) + TMoverParameters::eimc_labels[ i ] + to_string( mover.inductionMotor.config[ i ], 2, 9 ) + " | " - + TMoverParameters::eimv_labels[ i ] + to_string( mover.eimv[ i ], 2, 9 ); + + TMoverParameters::eimv_labels[ i ] + to_string( mover.inductionMotor.state[ i ], 2, 9 ); if( i < 10 ) { parameters += @@ -1115,7 +1115,7 @@ debug_panel::update_section_engine( std::vector &Output ) const { Output.emplace_back( parameters, Global.UITextColor ); } - Output.emplace_back( "Inverter:\n frequency: " + to_string( mover.InverterFrequency, 2 ), Global.UITextColor ); + Output.emplace_back( "Inverter:\n frequency: " + to_string( mover.inductionMotor.inverterFrequency, 2 ), Global.UITextColor ); } // diesel engine data if( mover.EngineType == TEngineType::DieselEngine ) { diff --git a/physics/components/body.cpp b/physics/components/body.cpp index 90acf4544..6c700f1ec 100644 --- a/physics/components/body.cpp +++ b/physics/components/body.cpp @@ -136,11 +136,11 @@ TMoverParameters::TMoverParameters(double VelInitial, std::string const &TypeNam cylindermult = 0.0; } - for (auto &eimcvalue : eimc) + for (auto &eimcvalue : inductionMotor.config) { eimcvalue = 0.0; } - eimc[eimc_p_eped] = 1.5; + inductionMotor.config[eimc_p_eped] = 1.5; for (auto &couplerentry : Couplers) { @@ -162,7 +162,7 @@ TMoverParameters::TMoverParameters(double VelInitial, std::string const &TypeNam Vel = abs(VelInitial); V = VelInitial / 3.6; - for (auto &eimvvalue : eimv) + for (auto &eimvvalue : inductionMotor.state) { eimvvalue = 0.0; } @@ -456,7 +456,7 @@ void TMoverParameters::compute_movement_(double const Deltatime) // Prad oddawany na rezystor // Wlacz wentylator jesli prad rekuperacji przekroczy maksymalny dla pasywnego chlodzenia rezystora - if (double Irh = abs(eimv[eimv_Pe]) - abs(eimv[eimv_Ipoj]); Irh > Imaxrpc && eimv[eimv_Ipoj] < 0) + if (double Irh = abs(inductionMotor.state[eimv_Pe]) - abs(inductionMotor.state[eimv_Ipoj]); Irh > Imaxrpc && inductionMotor.state[eimv_Ipoj] < 0) { BRVtimer = 0; BRVentilators = true; @@ -896,9 +896,9 @@ void TMoverParameters::ComputeTotalForce(double dt) FTrain = Power > 0 ? TractionForce(dt) : 0; double FT_factor = 1.0; - if (EngineType == TEngineType::ElectricInductionMotor && InvertersRatio > 0.0) + if (EngineType == TEngineType::ElectricInductionMotor && inductionMotor.inverterRatio > 0.0) { - FT_factor = 1.0 / InvertersRatio; + FT_factor = 1.0 / inductionMotor.inverterRatio; FTrain *= FT_factor; } diff --git a/physics/components/controllers.cpp b/physics/components/controllers.cpp index 0dcfcbe75..df0dca529 100644 --- a/physics/components/controllers.cpp +++ b/physics/components/controllers.cpp @@ -1103,8 +1103,8 @@ void TMoverParameters::CheckEIMIC(double dt) double brakeDemand = SplitEDPneumaticBrake ? DynamicBrakeRatio() : LocalBrakeRatio(); if (SplitEDPneumaticBrake) { - double const vh0 = eimc[eimc_p_Vh0]; - double const vh1 = eimc[eimc_p_Vh1]; + double const vh0 = inductionMotor.config[eimc_p_Vh0]; + double const vh1 = inductionMotor.config[eimc_p_Vh1]; if (vh1 > vh0 + 0.001) { double const vhRamp = std::clamp((Vel - vh0) / (vh1 - vh0), 0.0, 1.0); diff --git a/physics/components/drive.cpp b/physics/components/drive.cpp index 16e2c5294..99989e1a2 100644 --- a/physics/components/drive.cpp +++ b/physics/components/drive.cpp @@ -151,7 +151,7 @@ public: case 1: return vehicle.WindingRes * vehicle.Mm / vehicle.Vadd; case 2: - return vehicle.eimv_pr * vehicle.WindingRes; + return vehicle.inductionMotor.forceShare * vehicle.WindingRes; default: return vehicle.ShowCurrentP(ammeter); } diff --git a/physics/components/electrics.cpp b/physics/components/electrics.cpp index 6634c2496..d83b6c560 100644 --- a/physics/components/electrics.cpp +++ b/physics/components/electrics.cpp @@ -804,7 +804,7 @@ void TMoverParameters::GensetCheck(double const Deltatime) } else { - auto const demand{GensetSelected() && Mains ? std::clamp(eimv_pr, 0.0, 1.0) : 0.0}; + auto const demand{GensetSelected() && Mains ? std::clamp(inductionMotor.forceShare, 0.0, 1.0) : 0.0}; auto const target{genset.is_active ? genset.revolutions_idle + (genset.revolutions_max - genset.revolutions_idle) * demand : 0.0}; genset.revolutions += (target - genset.revolutions) * std::min(1.0, Deltatime / genset.spinup_time); if (genset.revolutions < 0.001) diff --git a/physics/components/fizparser.cpp b/physics/components/fizparser.cpp index c4c0fab0a..ebc791caa 100644 --- a/physics/components/fizparser.cpp +++ b/physics/components/fizparser.cpp @@ -387,7 +387,7 @@ bool TMoverParameters::readPmaxList(std::string const &line) double y = 0.0; parser >> x >> y; - EIM_Pmax_Table.emplace(x, y); + inductionMotor.maxPowerTable.emplace(x, y); return true; } diff --git a/physics/components/fizsections.cpp b/physics/components/fizsections.cpp index 440532edf..3b2a4eaaa 100644 --- a/physics/components/fizsections.cpp +++ b/physics/components/fizsections.cpp @@ -1380,48 +1380,48 @@ void TMoverParameters::LoadFIZ_EngineInductionMotor(std::string const &Input) RVentnmax = 1.0; extract_value(NominalVoltage, "Volt", Input, ""); - extract_value(eimc[eimc_s_dfic], "dfic", Input, ""); - extract_value(eimc[eimc_s_dfmax], "dfmax", Input, ""); - extract_value(eimc[eimc_s_p], "p", Input, ""); - extract_value(eimc[eimc_s_cfu], "cfu", Input, ""); - extract_value(eimc[eimc_s_cim], "cim", Input, ""); - extract_value(eimc[eimc_s_icif], "icif", Input, ""); - extract_value(eimc[eimc_f_Uzmax], "Uzmax", Input, ""); - extract_value(eimc[eimc_f_Uzh], "Uzh", Input, ""); - extract_value(eimc[eimc_f_DU], "DU", Input, ""); - extract_value(eimc[eimc_f_I0], "I0", Input, ""); - extract_value(eimc[eimc_f_cfu], "fcfu", Input, ""); - if (false == extract_value(eimc[eimc_f_cfuH], "fcfuH", Input, "")) + extract_value(inductionMotor.config[eimc_s_dfic], "dfic", Input, ""); + extract_value(inductionMotor.config[eimc_s_dfmax], "dfmax", Input, ""); + extract_value(inductionMotor.config[eimc_s_p], "p", Input, ""); + extract_value(inductionMotor.config[eimc_s_cfu], "cfu", Input, ""); + extract_value(inductionMotor.config[eimc_s_cim], "cim", Input, ""); + extract_value(inductionMotor.config[eimc_s_icif], "icif", Input, ""); + extract_value(inductionMotor.config[eimc_f_Uzmax], "Uzmax", Input, ""); + extract_value(inductionMotor.config[eimc_f_Uzh], "Uzh", Input, ""); + extract_value(inductionMotor.config[eimc_f_DU], "DU", Input, ""); + extract_value(inductionMotor.config[eimc_f_I0], "I0", Input, ""); + extract_value(inductionMotor.config[eimc_f_cfu], "fcfu", Input, ""); + if (false == extract_value(inductionMotor.config[eimc_f_cfuH], "fcfuH", Input, "")) { // without its own figure the dynamic brake takes the one of the traction - eimc[eimc_f_cfuH] = eimc[eimc_f_cfu]; + inductionMotor.config[eimc_f_cfuH] = inductionMotor.config[eimc_f_cfu]; } - extract_value(eimc[eimc_p_F0], "F0", Input, ""); - extract_value(eimc[eimc_p_a1], "a1", Input, ""); - extract_value(eimc[eimc_p_Pmax], "Pmax", Input, ""); - extract_value(eimc[eimc_p_Fh], "Fh", Input, ""); - extract_value(eimc[eimc_p_Ph], "Ph", Input, ""); - extract_value(eimc[eimc_p_Vh0], "Vh0", Input, ""); - extract_value(eimc[eimc_p_Vh1], "Vh1", Input, ""); - extract_value(eimc[eimc_p_Imax], "Imax", Input, ""); - extract_value(eimc[eimc_p_abed], "abed", Input, ""); - extract_value(eimc[eimc_p_eped], "edep", Input, ""); - extract_value(EIMCLogForce, "eimclf", Input, ""); - extract_value(InvertersNo, "InvNo", Input, ""); - extract_value(InverterControlCouplerFlag, "InvCtrCplFlag", Input, ""); + extract_value(inductionMotor.config[eimc_p_F0], "F0", Input, ""); + extract_value(inductionMotor.config[eimc_p_a1], "a1", Input, ""); + extract_value(inductionMotor.config[eimc_p_Pmax], "Pmax", Input, ""); + extract_value(inductionMotor.config[eimc_p_Fh], "Fh", Input, ""); + extract_value(inductionMotor.config[eimc_p_Ph], "Ph", Input, ""); + extract_value(inductionMotor.config[eimc_p_Vh0], "Vh0", Input, ""); + extract_value(inductionMotor.config[eimc_p_Vh1], "Vh1", Input, ""); + extract_value(inductionMotor.config[eimc_p_Imax], "Imax", Input, ""); + extract_value(inductionMotor.config[eimc_p_abed], "abed", Input, ""); + extract_value(inductionMotor.config[eimc_p_eped], "edep", Input, ""); + extract_value(inductionMotor.logForce, "eimclf", Input, ""); + extract_value(inductionMotor.inverterCount, "InvNo", Input, ""); + extract_value(inductionMotor.inverterControlCouplings, "InvCtrCplFlag", Input, ""); extract_value(Imaxrpc, "Imaxrpc", Input, ""); extract_value(BRVto, "BRVto", Input, ""); extract_value(Flat, "Flat", Input, ""); - if (eimc[eimc_p_Pmax] > 0 && Power > 0 && InvertersNo == 0) + if (inductionMotor.config[eimc_p_Pmax] > 0 && Power > 0 && inductionMotor.inverterCount == 0) { - InvertersNo = 1; + inductionMotor.inverterCount = 1; } - Inverters.resize(InvertersNo); - /*for (int i = 0; i > InvertersNo; i++) + inductionMotor.inverters.resize(inductionMotor.inverterCount); + /*for (int i = 0; i > inductionMotor.inverterCount; i++) { - inverter x; - Inverters.emplace_back(x); + Inverter x; + inductionMotor.inverters.emplace_back(x); }*/ } diff --git a/physics/components/inductionmotor.h b/physics/components/inductionmotor.h new file mode 100644 index 000000000..0a53ffb5c --- /dev/null +++ b/physics/components/inductionmotor.h @@ -0,0 +1,45 @@ +/* +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 drive of asynchronous motors fed by inverters (ElectricInductionMotor): its definition from the .fiz and its state + +#pragma once + +#include +#include +#include + +// an inverter of the drive +struct Inverter +{ + double Freal = 0.0; + double Request = 0.0; + bool IsActive = true; + bool Activate = true; + bool Error = false; + bool Failure_Drive = false; + bool Failure_Const = false; +}; + +struct InductionMotor +{ + // the definition + std::array config; // the parameters, indexed by eimc_* (eimc before) + std::map maxPowerTable; /*tablica mocy maksymalnej od predkosci*/ + int inverterCount = 0; // number of inverters + double inverterRatio = 0.0; + int inverterControlCouplings = 4; // the couplings needed to control the inverters, the number of InvCtrCplFlag of the .fiz + bool logForce = false; // EIMCLogForce + + // the state + std::array state; // the values of the drive, indexed by eimv_* (eimv before) + double forceShare = 0; /*realizowany procent dostepnej sily rozruchu/hamowania*/ + double inverterFrequency{0.0}; // current frequency of power inverters + std::vector inverters; // all inverters +}; diff --git a/physics/components/traction.cpp b/physics/components/traction.cpp index ff3051c70..9e6f60d73 100644 --- a/physics/components/traction.cpp +++ b/physics/components/traction.cpp @@ -524,8 +524,8 @@ double TMoverParameters::DynamicBrakeRatio(void) const // ************************************************************************************************* bool TMoverParameters::DynamicBrakeAvailable(void) const { - double const vh0{eimc[eimc_p_Vh0]}; - if (double const vh1{eimc[eimc_p_Vh1]}; vh1 <= 0.001) + double const vh0{inductionMotor.config[eimc_p_Vh0]}; + if (double const vh1{inductionMotor.config[eimc_p_Vh1]}; vh1 <= 0.001) { // brak zdefiniowanej strefy - ED dziala zawsze return true; @@ -1062,15 +1062,15 @@ void TMoverParameters::InductionMotorTractionForce(double dt) double PosRatio; double tmp; double ActiveInverters = 0.0; - for (auto const &inv : Inverters) + for (auto const &inv : inductionMotor.inverters) { if (inv.IsActive) ActiveInverters += 1.0; } - InvertersRatio = ActiveInverters / (double)InvertersNo; - if (EIM_Pmax_Table.size() > 1) + inductionMotor.inverterRatio = ActiveInverters / (double)inductionMotor.inverterCount; + if (inductionMotor.maxPowerTable.size() > 1) { - eimc[eimc_p_Pmax] = TableInterpolation(EIM_Pmax_Table, Vel); + inductionMotor.config[eimc_p_Pmax] = TableInterpolation(inductionMotor.maxPowerTable, Vel); } InductionMotorSpeedControl(dt); InductionMotorBrakeBlending(ActiveInverters, PosRatio, tmp); @@ -1090,10 +1090,10 @@ void TMoverParameters::InductionMotorTractionForce(double dt) if (ActiveInverters == 0.0) { PosRatio = 0; - eimv_pr = 0; + inductionMotor.forceShare = 0; } - eimv_pr += std::max(std::min(PosRatio - eimv_pr, 0.02), -0.02) * 12 * tmp /*2{+4*byte(PosRatioGetEDBCP() * eimc[eimc_p_abed]}; // stala napedu + auto const edBCP{Hamulec->GetEDBCP() * inductionMotor.config[eimc_p_abed]}; // stala napedu if (DynamicBrakeFlag) { PosRatio = InductionMotorBrakeRatio(ActiveInverters, edBCP); @@ -1204,9 +1204,9 @@ void TMoverParameters::InductionMotorBrakeBlending(double const ActiveInverters, else { PosRatio = std::max(eimic_real, 0.); - eimv[eimv_Fzad] = PosRatio; - if (Flat && eimc[eimc_p_F0] * eimv[eimv_Fful] > 0) - PosRatio = std::min(PosRatio * eimc[eimc_p_F0] / eimv[eimv_Fful], 1.); + inductionMotor.state[eimv_Fzad] = PosRatio; + if (Flat && inductionMotor.config[eimc_p_F0] * inductionMotor.state[eimv_Fful] > 0) + PosRatio = std::min(PosRatio * inductionMotor.config[eimc_p_F0] / inductionMotor.state[eimv_Fful], 1.); /* if (ScndCtrlActualPos > 0) //speed control if (Vmax < 250) PosRatio = std::min(PosRatio, std::max(-1, 0.5 * (ScndCtrlActualPos - Vel))); @@ -1248,9 +1248,9 @@ double TMoverParameters::InductionMotorBrakeRatio(double const ActiveInverters, { double PosRatio; // ustalanie współczynnika blendingu do luzowania hamulca PN - if (eimv[eimv_Fmax] * Sign(V) * DirAbsolute < -1) + if (inductionMotor.state[eimv_Fmax] * Sign(V) * DirAbsolute < -1) { - PosRatio = -Sign(V) * DirAbsolute * eimv[eimv_Fr] / (eimc[eimc_p_Fh] * std::max(edBCP, std::max(0.01, Hamulec->GetEDBCP())) / MaxBrakePress[0]); + PosRatio = -Sign(V) * DirAbsolute * inductionMotor.state[eimv_Fr] / (inductionMotor.config[eimc_p_Fh] * std::max(edBCP, std::max(0.01, Hamulec->GetEDBCP())) / MaxBrakePress[0]); PosRatio = std::clamp(PosRatio, 0.0, 1.0); } else @@ -1262,27 +1262,27 @@ double TMoverParameters::InductionMotorBrakeRatio(double const ActiveInverters, PosRatio *= 0.9; Hamulec->SetED(std::max(0.0, std::min(PosRatio, 1.0))); // ustalenie stopnia zmniejszenia ciśnienia // ustalanie siły hamowania ED - if (Hamulec->GetEDBCP() > 0.25 && eimc[eimc_p_abed] < 0.001 || ActiveInverters < InvertersNo) // jeśli PN wyłącza ED + if (Hamulec->GetEDBCP() > 0.25 && inductionMotor.config[eimc_p_abed] < 0.001 || ActiveInverters < inductionMotor.inverterCount) // jeśli PN wyłącza ED { PosRatio = 0; - eimv[eimv_Fzad] = 0; + inductionMotor.state[eimv_Fzad] = 0; } else { // strefa wylaczenia ED (Vh0..Vh1) - mnoznik 0..1 zaleznie od predkosci - double const vhRamp = std::max(0.0, std::min(1.0, (Vel - eimc[eimc_p_Vh0]) / (eimc[eimc_p_Vh1] - eimc[eimc_p_Vh0]))); + double const vhRamp = std::max(0.0, std::min(1.0, (Vel - inductionMotor.config[eimc_p_Vh0]) / (inductionMotor.config[eimc_p_Vh1] - inductionMotor.config[eimc_p_Vh0]))); if (SplitEDPneumaticBrake) { // w trybie split LocalBrake nie zaleca ED; uzywany jest DynamicBrakeCtrl // oraz zwykle zapotrzebowanie z hamulca zespolonego (edBCP) double const edLeverDemand = DynamicBrakeRatio(); PosRatio = -std::max(std::max(edLeverDemand, std::min(edBCP / MaxBrakePress[0], 1.0)), AnPos) * vhRamp; - eimv[eimv_Fzad] = -std::min(1.0, std::max(edLeverDemand, edBCP / MaxBrakePress[0])); + inductionMotor.state[eimv_Fzad] = -std::min(1.0, std::max(edLeverDemand, edBCP / MaxBrakePress[0])); } else { PosRatio = -std::max(std::min(edBCP * 1.0 / MaxBrakePress[0], 1.0), AnPos) * vhRamp; - eimv[eimv_Fzad] = -std::min(1.0, std::max(LocalBrakeRatio(), edBCP / MaxBrakePress[0])); + inductionMotor.state[eimv_Fzad] = -std::min(1.0, std::max(LocalBrakeRatio(), edBCP / MaxBrakePress[0])); } } return PosRatio; @@ -1293,57 +1293,57 @@ void TMoverParameters::InductionMotorDrive(double dt) { double tmp; if (DynamicBrakeFlag) - tmp = eimc[eimc_f_Uzh]; + tmp = inductionMotor.config[eimc_f_Uzh]; else - tmp = eimc[eimc_f_Uzmax]; + tmp = inductionMotor.config[eimc_f_Uzmax]; - auto f_cfu{DynamicBrakeFlag ? eimc[eimc_f_cfuH] : eimc[eimc_f_cfu]}; + auto f_cfu{DynamicBrakeFlag ? inductionMotor.config[eimc_f_cfuH] : inductionMotor.config[eimc_f_cfu]}; - eimv[eimv_Uzsmax] = std::min(EngineVoltage - eimc[eimc_f_DU], tmp); - eimv[eimv_fkr] = eimv[eimv_Uzsmax] / f_cfu; - if (eimv_pr < 0) + inductionMotor.state[eimv_Uzsmax] = std::min(EngineVoltage - inductionMotor.config[eimc_f_DU], tmp); + inductionMotor.state[eimv_fkr] = inductionMotor.state[eimv_Uzsmax] / f_cfu; + if (inductionMotor.forceShare < 0) { - eimv[eimv_Pmax] = eimc[eimc_p_Ph]; + inductionMotor.state[eimv_Pmax] = inductionMotor.config[eimc_p_Ph]; } else { - eimv[eimv_Pmax] = std::min(eimc[eimc_p_Pmax], 0.001 * EngineVoltage * (eimc[eimc_p_Imax] - eimc[eimc_f_I0]) * Pirazy2 * eimc[eimc_s_cim] / eimc[eimc_s_p] / eimc[eimc_s_cfu]); + inductionMotor.state[eimv_Pmax] = std::min(inductionMotor.config[eimc_p_Pmax], 0.001 * EngineVoltage * (inductionMotor.config[eimc_p_Imax] - inductionMotor.config[eimc_f_I0]) * Pirazy2 * inductionMotor.config[eimc_s_cim] / inductionMotor.config[eimc_s_p] / inductionMotor.config[eimc_s_cfu]); if (GensetSelected()) { // on the genset of a dual-mode vehicle the traction takes no more than the genset gives - eimv[eimv_Pmax] = std::min(eimv[eimv_Pmax], GensetTractionPowerLimit()); + inductionMotor.state[eimv_Pmax] = std::min(inductionMotor.state[eimv_Pmax], GensetTractionPowerLimit()); } } - eimv[eimv_FMAXMAX] = 0.001 * - square(std::min(1.0, eimv[eimv_fkr] / std::max(abs(enrot) * eimc[eimc_s_p] + eimc[eimc_s_dfmax] * eimv[eimv_ks], eimc[eimc_s_dfmax])) * f_cfu / eimc[eimc_s_cfu]) * - (eimc[eimc_s_dfmax] * eimc[eimc_s_dfic] * eimc[eimc_s_cim]) * Transmision.Ratio * NPoweredAxles * 2.0 / WheelDiameter; + inductionMotor.state[eimv_FMAXMAX] = 0.001 * + square(std::min(1.0, inductionMotor.state[eimv_fkr] / std::max(abs(enrot) * inductionMotor.config[eimc_s_p] + inductionMotor.config[eimc_s_dfmax] * inductionMotor.state[eimv_ks], inductionMotor.config[eimc_s_dfmax])) * f_cfu / inductionMotor.config[eimc_s_cfu]) * + (inductionMotor.config[eimc_s_dfmax] * inductionMotor.config[eimc_s_dfic] * inductionMotor.config[eimc_s_cim]) * Transmision.Ratio * NPoweredAxles * 2.0 / WheelDiameter; InductionMotorForceLimits(); - for (auto &inv : Inverters) + for (auto &inv : inductionMotor.inverters) { - inv.Request = inv.IsActive ? eimv_pr : 0.0; + inv.Request = inv.IsActive ? inductionMotor.forceShare : 0.0; inv.Error = inv.Failure_Const || (inv.Failure_Drive && inv.Request != 0); inv.IsActive = inv.Activate && !inv.Error; } - eimv[eimv_ks] = eimv[eimv_Fr] / eimv[eimv_FMAXMAX]; - eimv[eimv_df] = eimv[eimv_ks] * eimc[eimc_s_dfmax]; - eimv[eimv_fp] = DirAbsolute * enrot * eimc[eimc_s_p] + eimv[eimv_df]; // do przemyslenia dzialanie pp z tmpV - // eimv[eimv_U]:=std::max(eimv[eimv_Uzsmax],std::min(eimc[eimc_f_cfu]*eimv[eimv_fp],eimv[eimv_Uzsmax])); - // eimv[eimv_pole]:=eimv[eimv_U]/(eimv[eimv_fp]*eimc[eimc_s_cfu]); - if (abs(eimv[eimv_fp]) <= eimv[eimv_fkr]) - eimv[eimv_pole] = f_cfu / eimc[eimc_s_cfu]; + inductionMotor.state[eimv_ks] = inductionMotor.state[eimv_Fr] / inductionMotor.state[eimv_FMAXMAX]; + inductionMotor.state[eimv_df] = inductionMotor.state[eimv_ks] * inductionMotor.config[eimc_s_dfmax]; + inductionMotor.state[eimv_fp] = DirAbsolute * enrot * inductionMotor.config[eimc_s_p] + inductionMotor.state[eimv_df]; // do przemyslenia dzialanie pp z tmpV + // inductionMotor.state[eimv_U]:=std::max(inductionMotor.state[eimv_Uzsmax],std::min(inductionMotor.config[eimc_f_cfu]*inductionMotor.state[eimv_fp],inductionMotor.state[eimv_Uzsmax])); + // inductionMotor.state[eimv_pole]:=inductionMotor.state[eimv_U]/(inductionMotor.state[eimv_fp]*inductionMotor.config[eimc_s_cfu]); + if (abs(inductionMotor.state[eimv_fp]) <= inductionMotor.state[eimv_fkr]) + inductionMotor.state[eimv_pole] = f_cfu / inductionMotor.config[eimc_s_cfu]; else - eimv[eimv_pole] = eimv[eimv_Uzsmax] / eimc[eimc_s_cfu] / abs(eimv[eimv_fp]); - eimv[eimv_U] = eimv[eimv_pole] * eimv[eimv_fp] * eimc[eimc_s_cfu]; - eimv[eimv_Ic] = (eimv[eimv_fp] - DirAbsolute * enrot * eimc[eimc_s_p]) * eimc[eimc_s_dfic] * eimv[eimv_pole]; - eimv[eimv_If] = eimv[eimv_Ic] * eimc[eimc_s_icif]; - eimv[eimv_M] = eimv[eimv_pole] * eimv[eimv_Ic] * eimc[eimc_s_cim]; - eimv[eimv_Ipoj] = eimv[eimv_Ic] * NPoweredAxles * InvertersRatio * eimv[eimv_U] / (EngineVoltage - eimc[eimc_f_DU]) + eimc[eimc_f_I0]; - eimv[eimv_Pm] = DirActive * eimv[eimv_M] * NPoweredAxles * InvertersRatio * enrot * Pirazy2 / 1000; - eimv[eimv_Pe] = eimv[eimv_Ipoj] * EngineVoltage / 1000; - eimv[eimv_eta] = eimv[eimv_Pm] / eimv[eimv_Pe]; + inductionMotor.state[eimv_pole] = inductionMotor.state[eimv_Uzsmax] / inductionMotor.config[eimc_s_cfu] / abs(inductionMotor.state[eimv_fp]); + inductionMotor.state[eimv_U] = inductionMotor.state[eimv_pole] * inductionMotor.state[eimv_fp] * inductionMotor.config[eimc_s_cfu]; + inductionMotor.state[eimv_Ic] = (inductionMotor.state[eimv_fp] - DirAbsolute * enrot * inductionMotor.config[eimc_s_p]) * inductionMotor.config[eimc_s_dfic] * inductionMotor.state[eimv_pole]; + inductionMotor.state[eimv_If] = inductionMotor.state[eimv_Ic] * inductionMotor.config[eimc_s_icif]; + inductionMotor.state[eimv_M] = inductionMotor.state[eimv_pole] * inductionMotor.state[eimv_Ic] * inductionMotor.config[eimc_s_cim]; + inductionMotor.state[eimv_Ipoj] = inductionMotor.state[eimv_Ic] * NPoweredAxles * inductionMotor.inverterRatio * inductionMotor.state[eimv_U] / (EngineVoltage - inductionMotor.config[eimc_f_DU]) + inductionMotor.config[eimc_f_I0]; + inductionMotor.state[eimv_Pm] = DirActive * inductionMotor.state[eimv_M] * NPoweredAxles * inductionMotor.inverterRatio * enrot * Pirazy2 / 1000; + inductionMotor.state[eimv_Pe] = inductionMotor.state[eimv_Ipoj] * EngineVoltage / 1000; + inductionMotor.state[eimv_eta] = inductionMotor.state[eimv_Pm] / inductionMotor.state[eimv_Pe]; - Im = eimv[eimv_If]; - if (eimv[eimv_Ipoj] >= 0) + Im = inductionMotor.state[eimv_If]; + if (inductionMotor.state[eimv_Ipoj] >= 0) Vadd *= 1.0 - 2.0 * dt; else if (GensetSelected()) Vadd = 1.0; // the genset of a dual-mode vehicle takes nothing back: all the braking energy to the resistors @@ -1351,57 +1351,57 @@ void TMoverParameters::InductionMotorDrive(double dt) Vadd *= 1.0 - dt; else Vadd = std::max(Vadd * (1.0 - 0.2 * dt), 0.007 * (std::abs(EngineVoltage) - (EnginePowerSource.CollectorParameters.MaxV - 100))); - Itot = eimv[eimv_Ipoj] * (0.01 + std::min(0.99, 0.99 - Vadd)); + Itot = inductionMotor.state[eimv_Ipoj] * (0.01 + std::min(0.99, 0.99 - Vadd)); - EnginePower = abs(eimv[eimv_Ic] * eimv[eimv_U] * NPoweredAxles) / 1000; + EnginePower = abs(inductionMotor.state[eimv_Ic] * inductionMotor.state[eimv_U] * NPoweredAxles) / 1000; // power inverters UpdateInverterFrequency(); - Mm = eimv[eimv_M] * DirAbsolute; + Mm = inductionMotor.state[eimv_M] * DirAbsolute; Mw = Mm * Transmision.Ratio * Transmision.Efficiency; Fw = Mw * 2.0 / WheelDiameter; - Ft = Fw * NPoweredAxles * InvertersRatio; - eimv[eimv_Fr] = DirAbsolute * Ft / 1000; + Ft = Fw * NPoweredAxles * inductionMotor.inverterRatio; + inductionMotor.state[eimv_Fr] = DirAbsolute * Ft / 1000; } -// the force the motors give at full and at the setting (eimv_pr), braking within the power and the force of the +// the force the motors give at full and at the setting (inductionMotor.forceShare), braking within the power and the force of the // electrodynamic brake, driving within the power and the starting force void TMoverParameters::InductionMotorForceLimits() { - if (eimv_pr < 0) + if (inductionMotor.forceShare < 0) { - eimv[eimv_Fful] = std::min(eimc[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(eimc[eimc_p_Fh], eimv[eimv_FMAXMAX])); - eimv[eimv_Fmax] = -Sign(V) * DirAbsolute*std::min(eimc[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-eimc[eimc_p_Fh] * eimv_pr, eimv[eimv_FMAXMAX])); - double pr = eimv_pr; - if (EIMCLogForce) + inductionMotor.state[eimv_Fful] = std::min(inductionMotor.config[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(inductionMotor.config[eimc_p_Fh], inductionMotor.state[eimv_FMAXMAX])); + inductionMotor.state[eimv_Fmax] = -Sign(V) * DirAbsolute*std::min(inductionMotor.config[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-inductionMotor.config[eimc_p_Fh] * inductionMotor.forceShare, inductionMotor.state[eimv_FMAXMAX])); + double pr = inductionMotor.forceShare; + if (inductionMotor.logForce) pr = -log(1 - 4 * pr) / log(5); - eimv[eimv_Fr] = -Sign(V) * DirAbsolute*std::min(eimc[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-eimc[eimc_p_Fh] * pr, eimv[eimv_FMAXMAX])); - if (InvertersRatio < 1.0) - eimv[eimv_Fful] = 0; - //*std::min(1,(Vel-eimc[eimc_p_Vh0])/(eimc[eimc_p_Vh1]-eimc[eimc_p_Vh0])) + inductionMotor.state[eimv_Fr] = -Sign(V) * DirAbsolute*std::min(inductionMotor.config[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-inductionMotor.config[eimc_p_Fh] * pr, inductionMotor.state[eimv_FMAXMAX])); + if (inductionMotor.inverterRatio < 1.0) + inductionMotor.state[eimv_Fful] = 0; + //*std::min(1,(Vel-inductionMotor.config[eimc_p_Vh0])/(inductionMotor.config[eimc_p_Vh1]-inductionMotor.config[eimc_p_Vh0])) } else { - eimv[eimv_Fful] = std::min(std::min(3.6 * eimv[eimv_Pmax] / std::max(Vel, 1.), eimc[eimc_p_F0] - Vel * eimc[eimc_p_a1]), eimv[eimv_FMAXMAX]); + inductionMotor.state[eimv_Fful] = std::min(std::min(3.6 * inductionMotor.state[eimv_Pmax] / std::max(Vel, 1.), inductionMotor.config[eimc_p_F0] - Vel * inductionMotor.config[eimc_p_a1]), inductionMotor.state[eimv_FMAXMAX]); // if(not Flat)then - eimv[eimv_Fmax] = eimv[eimv_Fful] * eimv_pr; + inductionMotor.state[eimv_Fmax] = inductionMotor.state[eimv_Fful] * inductionMotor.forceShare; // else - // eimv[eimv_Fmax]:=std::min(eimc[eimc_p_F0]*eimv_pr,eimv[eimv_Fful]); - double pr = eimv_pr; - if (EIMCLogForce) + // inductionMotor.state[eimv_Fmax]:=std::min(inductionMotor.config[eimc_p_F0]*inductionMotor.forceShare,inductionMotor.state[eimv_Fful]); + double pr = inductionMotor.forceShare; + if (inductionMotor.logForce) pr = log(1 + 4 * pr) / log(5); - eimv[eimv_Fr] = eimv[eimv_Fful] * pr; + inductionMotor.state[eimv_Fr] = inductionMotor.state[eimv_Fful] * pr; } } // the frequency of the inverters at the motors' slip frequency, from the list of the drive or of its brake void TMoverParameters::UpdateInverterFrequency() { - auto const tmpV{std::abs(eimv[eimv_fp])}; + auto const tmpV{std::abs(inductionMotor.state[eimv_fp])}; auto const useFFEDList = FFEDListSize > 0 && DynamicBrakeFlag; auto const list = useFFEDList ? FFEDlist : FFlist; - if (auto const listSize = useFFEDList ? FFEDListSize : FFListSize; listSize > 0 && std::abs(eimv[eimv_If]) > 1.0 && tmpV > 0.0001) + if (auto const listSize = useFFEDList ? FFEDListSize : FFListSize; listSize > 0 && std::abs(inductionMotor.state[eimv_If]) > 1.0 && tmpV > 0.0001) { int i = 0; @@ -1409,18 +1409,18 @@ void TMoverParameters::UpdateInverterFrequency() { ++i; } - InverterFrequency = (tmpV - list[i].v) / std::max(1.0, list[i + 1].v - list[i].v) * (list[i + 1].freq - list[i].freq) + list[i].freq; + inductionMotor.inverterFrequency = (tmpV - list[i].v) / std::max(1.0, list[i + 1].v - list[i].v) * (list[i + 1].freq - list[i].freq) + list[i].freq; } else { - InverterFrequency = 0.0; + inductionMotor.inverterFrequency = 0.0; } } // the induction motor drive without power, or blocked by the security system void TMoverParameters::InductionMotorOff() { - for (auto &inv : Inverters) + for (auto &inv : inductionMotor.inverters) { inv.Freal = 0.0; inv.IsActive = false; @@ -1431,14 +1431,14 @@ void TMoverParameters::InductionMotorOff() Fw = 0.0; Ft = 0.0; Itot = 0.0; - eimv_pr = 0.0; + inductionMotor.forceShare = 0.0; EnginePower = 0.0; { - for (auto &eimvvalue : eimv) + for (auto &eimvvalue : inductionMotor.state) eimvvalue = 0.0; } Hamulec->SetED(0.0); - InverterFrequency = 0.0; //(Hamulec as TLSt).SetLBP(LocBrakePress); + inductionMotor.inverterFrequency = 0.0; //(Hamulec as TLSt).SetLBP(LocBrakePress); } // ************************************************************************************************* diff --git a/physics/mover.h b/physics/mover.h index 6dd3eebe1..64a555d23 100644 --- a/physics/mover.h +++ b/physics/mover.h @@ -23,6 +23,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/odometerreading.h" #include "physics/vehicletypes.h" #include "physics/components/dieselengine.h" +#include "physics/components/inductionmotor.h" class TractionDrive; @@ -598,17 +599,6 @@ struct speed_control double PowerDownSpeed = 1000; }; -struct inverter -{ - double Freal = 0.0; - double Request = 0.0; - bool IsActive = true; - bool Activate = true; - bool Error = false; - bool Failure_Drive = false; - bool Failure_Const = false; -}; - class TMoverParameters { // Ra: wrapper na kod pascalowy, przejmujący jego funkcje Q: 20160824 - juz nie wrapper a klasa bazowa :) private: @@ -1156,18 +1146,12 @@ class TMoverParameters /*- dla uproszczonego modelu silnika (dumb) oraz dla drezyny*/ double Ftmax = 0.0; /*- dla lokomotyw z silnikami indukcyjnymi -*/ - double eimc[26]; - bool EIMCLogForce = false; // + // the drive of induction motors (physics/components/inductionmotor.h) + InductionMotor inductionMotor; static std::vector const eimc_labels; - double InverterFrequency{0.0}; // current frequency of power inverters - int InvertersNo = 0; // number of inverters - double InvertersRatio = 0.0; - std::vector Inverters; // all inverters - int InverterControlCouplerFlag = 4; // which coupling flag is necessary to controll inverters int Imaxrpc = 0; // Maksymalny prad rezystora hamowania chlodzonego pasywnie int BRVto = 0; // Czas jaki wentylatory jeszcze dodatkowo schladzaja rezystor double BRVtimer = 0; // Timer dla podtrzymania wentylatora - std::map EIM_Pmax_Table; /*tablica mocy maksymalnej od predkosci*/ /* -dla pojazdów z blendingiem EP/ED (MED) */ double MED_Vmax = 0; // predkosc maksymalna dla obliczen chwilowej sily hamowania EP w MED double MED_Vmin = 0; // predkosc minimalna dla obliczen chwilowej sily hamowania EP w MED @@ -1496,8 +1480,6 @@ class TMoverParameters bool EIMCtrlAdditionalZeros = false; /*czy ma dodatkowe zero jazdy i zero hamowania */ bool EIMCtrlEmergency = false; /*czy ma dodatkowe zero jazdy i zero hamowania */ bool EIMCtrlMainEmergency = false; /*czy zadajnik typu 2 (Elf) ma pozycje hamowania naglego ponizej swojej pozycji 0*/ - double eimv_pr = 0; /*realizowany procent dostepnej sily rozruchu/hamowania*/ - double eimv[21]; static std::vector const eimv_labels; double SpeedCtrlTimer = 0; /*zegar dzialania tempomatu z wybieralna predkoscia*/ double eimicSpeedCtrl = 1; /*pozycja sugerowana przez tempomat*/ @@ -1688,7 +1670,7 @@ class TMoverParameters bool EIMDirectionChangeAllow(void) const; inline double IsVehicleEIMBrakingFactor() const { - return DynamicBrakeFlag && ResistorsFlag ? 0.0 : eimv[eimv_Ipoj] < 0 ? -1.0 : 1.0; + return DynamicBrakeFlag && ResistorsFlag ? 0.0 : inductionMotor.state[eimv_Ipoj] < 0 ? -1.0 : 1.0; } void BrakeLevelSet(double b); bool BrakeLevelAdd(double b); diff --git a/tests/unit/golden.cpp b/tests/unit/golden.cpp index ce4225906..363d97718 100644 --- a/tests/unit/golden.cpp +++ b/tests/unit/golden.cpp @@ -67,7 +67,7 @@ std::vector traction() { {"EnginePower", [](auto const &M) { return M.EnginePower; }}, {"enrot", [](auto const &M) { return M.enrot; }}, {"dizel_fill", [](auto const &M) { return M.diesel.fill; }}, - {"eimv_pr", [](auto const &M) { return M.eimv_pr; }}, + {"eimv_pr", [](auto const &M) { return M.inductionMotor.forceShare; }}, {"DynamicBrakeFlag", [](auto const &M) { return M.DynamicBrakeFlag ? 1.0 : 0.0; }}, }; } diff --git a/tests/unit/test_definition.cpp b/tests/unit/test_definition.cpp index 6b0ce22b3..518f9b73f 100644 --- a/tests/unit/test_definition.cpp +++ b/tests/unit/test_definition.cpp @@ -131,7 +131,7 @@ TEST_CASE("definition: the highest power of an induction motor drive by the spee auto driven{test::driving(real)}; test::track const line{0.0, 0.0, test::catenary_3kv}; REQUIRE(test::start_up(driven, line)); - CHECK(real->eimc[eimc_p_Pmax] == doctest::Approx(table(real->Vel)).epsilon(0.01)); + CHECK(real->inductionMotor.config[eimc_p_Pmax] == doctest::Approx(table(real->Vel)).epsilon(0.01)); } } diff --git a/tests/unit/test_elf_controller.cpp b/tests/unit/test_elf_controller.cpp index f480951e1..138689f68 100644 --- a/tests/unit/test_elf_controller.cpp +++ b/tests/unit/test_elf_controller.cpp @@ -530,7 +530,7 @@ TEST_CASE("elf holding brake: the force of the motors at 1% against the holding unit.wait(5.0); auto const holding{cab.StopBrakeDecc * mass}; MESSAGE("mass " << mass << " kg, holding " << holding << " N, cars with motors " << powered << ", demand " << cab.eimic_real << ", cab car Ft " << cab.Ft - << " N, Fful " << cab.eimv[eimv_Fful] << " kN, speed " << cab.Vel << " km/h after 5 s"); + << " N, Fful " << cab.inductionMotor.state[eimv_Fful] << " kN, speed " << cab.Vel << " km/h after 5 s"); CHECK(cab.eimic_real == doctest::Approx(0.01).epsilon(0.02)); CHECK(cab.Ft * powered < 0.1 * holding); } diff --git a/tests/unit/test_fcfuh_default.cpp b/tests/unit/test_fcfuh_default.cpp index 437164060..e86f29e7b 100644 --- a/tests/unit/test_fcfuh_default.cpp +++ b/tests/unit/test_fcfuh_default.cpp @@ -142,12 +142,12 @@ TEST_CASE("fcfuH: the loader gives the dynamic brake the traction's figure when CAPTURE(fcfu); // the EU47's definition has fcfu only vehicle eu47{definition::fiz("e186_v2/eu47").set("Engine", "fcfu", fcfu)}; - CHECK(eu47->eimc[eimc_f_cfu] == read_fcfu(fcfu)); - CHECK(bits(eu47->eimc[eimc_f_cfuH]) == bits(eu47->eimc[eimc_f_cfu])); - CHECK(bits(eu47->eimc[eimc_f_cfuH]) == bits(fcfuh_before(read_fcfu(fcfu)))); + CHECK(eu47->inductionMotor.config[eimc_f_cfu] == read_fcfu(fcfu)); + CHECK(bits(eu47->inductionMotor.config[eimc_f_cfuH]) == bits(eu47->inductionMotor.config[eimc_f_cfu])); + CHECK(bits(eu47->inductionMotor.config[eimc_f_cfuH]) == bits(fcfuh_before(read_fcfu(fcfu)))); // its own figure is kept vehicle own{definition::fiz("e186_v2/eu47").set("Engine", "fcfu", fcfu).set("Engine", "fcfuH", "40.1")}; - CHECK(own->eimc[eimc_f_cfu] == read_fcfu(fcfu)); - CHECK(own->eimc[eimc_f_cfuH] == read_fcfu("40.1")); + CHECK(own->inductionMotor.config[eimc_f_cfu] == read_fcfu(fcfu)); + CHECK(own->inductionMotor.config[eimc_f_cfuH] == read_fcfu("40.1")); } } diff --git a/tests/unit/test_genset.cpp b/tests/unit/test_genset.cpp index 33af24480..cba96800f 100644 --- a/tests/unit/test_genset.cpp +++ b/tests/unit/test_genset.cpp @@ -309,11 +309,11 @@ TEST_CASE("genset: the revolutions follow the demand, so the power builds up") { notch_up(cab); // the demand of the traction builds up at the pace of the inverters, the revolutions follow it auto step_count{0L}; - for (; step_count < 3000 && cab.eimv_pr < 0.99; ++step_count) { + for (; step_count < 3000 && cab.inductionMotor.forceShare < 0.99; ++step_count) { step(dragon6, step_count); } CAPTURE(step_count); - REQUIRE(cab.eimv_pr >= 0.99); + REQUIRE(cab.inductionMotor.forceShare >= 0.99); run(dragon6, 3.0); auto const after3{cab.Genset.available_power()}; CAPTURE(after3); @@ -345,7 +345,7 @@ TEST_CASE("genset: running from the catenary is the same with the keys") { {"V", [&Values](TMoverParameters const &Vehicle) { Values.speed.push_back(Vehicle.V); return Vehicle.V; }}, {"EngineVoltage", [&Values](TMoverParameters const &Vehicle) { Values.voltage.push_back(Vehicle.EngineVoltage); return Vehicle.EngineVoltage; }}, {"Itot", [&Values](TMoverParameters const &Vehicle) { Values.current.push_back(Vehicle.Itot); return Vehicle.Itot; }}, - {"eimv_pr", [&Values](TMoverParameters const &Vehicle) { Values.demand.push_back(Vehicle.eimv_pr); return Vehicle.eimv_pr; }}, + {"eimv_pr", [&Values](TMoverParameters const &Vehicle) { Values.demand.push_back(Vehicle.inductionMotor.forceShare); return Vehicle.inductionMotor.forceShare; }}, }; }; auto const drive = [&record](definition const &Definition, values &Values) { @@ -492,7 +492,7 @@ braking brake_from_60(vehicle &Dragon, track const &Track) { for (auto step_count = 0L; step_count < 2000; ++step_count) { step(Dragon, step_count, Track); result.lowest_current = std::min(result.lowest_current, cab.Itot); - result.electrodynamic |= cab.eimv_pr < 0.0 && cab.eimv[eimv_Ipoj] < 0.0; + result.electrodynamic |= cab.inductionMotor.forceShare < 0.0 && cab.inductionMotor.state[eimv_Ipoj] < 0.0; } result.speed_lost = speed - cab.Vel; return result; diff --git a/vehicle/cab/equipmentcommands.cpp b/vehicle/cab/equipmentcommands.cpp index 256141d9a..a7c232c01 100644 --- a/vehicle/cab/equipmentcommands.cpp +++ b/vehicle/cab/equipmentcommands.cpp @@ -413,20 +413,20 @@ void TTrain::OnCommand_inverterenable(TTrain *Train, command_data const &Command { // only reacting to press, so the switch doesn't flip back and forth if key is held down bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; - auto const flag{CouplingSet::FromBits(Train->DynamicObject->MoverParameters->InverterControlCouplerFlag)}; + auto const flag{CouplingSet::FromBits(Train->DynamicObject->MoverParameters->inductionMotor.inverterControlCouplings)}; TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); while (p) { - if (p->MoverParameters->eimc[eimc_p_Pmax] > 1) + if (p->MoverParameters->inductionMotor.config[eimc_p_Pmax] > 1) { - if (itemindex < p->MoverParameters->InvertersNo) + if (itemindex < p->MoverParameters->inductionMotor.inverterCount) { - p->MoverParameters->Inverters[itemindex].Activate = true; + p->MoverParameters->inductionMotor.inverters[itemindex].Activate = true; break; } else { - itemindex -= p->MoverParameters->InvertersNo; + itemindex -= p->MoverParameters->inductionMotor.inverterCount; } } p = kier ? p->Next(flag) : p->Prev(flag); @@ -452,20 +452,20 @@ void TTrain::OnCommand_inverterdisable(TTrain *Train, command_data const &Comman { // only reacting to press, so the switch doesn't flip back and forth if key is held down bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; - auto const flag{CouplingSet::FromBits(Train->DynamicObject->MoverParameters->InverterControlCouplerFlag)}; + auto const flag{CouplingSet::FromBits(Train->DynamicObject->MoverParameters->inductionMotor.inverterControlCouplings)}; TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); while (p) { - if (p->MoverParameters->eimc[eimc_p_Pmax] > 1) + if (p->MoverParameters->inductionMotor.config[eimc_p_Pmax] > 1) { - if (itemindex < p->MoverParameters->InvertersNo) + if (itemindex < p->MoverParameters->inductionMotor.inverterCount) { - p->MoverParameters->Inverters[itemindex].Activate = false; + p->MoverParameters->inductionMotor.inverters[itemindex].Activate = false; break; } else { - itemindex -= p->MoverParameters->InvertersNo; + itemindex -= p->MoverParameters->inductionMotor.inverterCount; } } p = kier ? p->Next(flag) : p->Prev(flag); @@ -491,22 +491,22 @@ void TTrain::OnCommand_invertertoggle(TTrain *Train, command_data const &Command { // only reacting to press, so the switch doesn't flip back and forth if key is held down bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; - auto const flag{CouplingSet::FromBits(Train->DynamicObject->MoverParameters->InverterControlCouplerFlag)}; + auto const flag{CouplingSet::FromBits(Train->DynamicObject->MoverParameters->inductionMotor.inverterControlCouplings)}; TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); while (p) { - if (p->MoverParameters->eimc[eimc_p_Pmax] > 1) + if (p->MoverParameters->inductionMotor.config[eimc_p_Pmax] > 1) { - if (itemindex < p->MoverParameters->InvertersNo) + if (itemindex < p->MoverParameters->inductionMotor.inverterCount) { - p->MoverParameters->Inverters[itemindex].Activate = !p->MoverParameters->Inverters[itemindex].Activate; + p->MoverParameters->inductionMotor.inverters[itemindex].Activate = !p->MoverParameters->inductionMotor.inverters[itemindex].Activate; // visual feedback - item.UpdateValue(p->MoverParameters->Inverters[itemindex].Activate ? 1.0 : 0.0, Train->dsbSwitch); + item.UpdateValue(p->MoverParameters->inductionMotor.inverters[itemindex].Activate ? 1.0 : 0.0, Train->dsbSwitch); break; } else { - itemindex -= p->MoverParameters->InvertersNo; + itemindex -= p->MoverParameters->inductionMotor.inverterCount; } } p = kier ? p->Next(flag) : p->Prev(flag); diff --git a/vehicle/cab/setup.cpp b/vehicle/cab/setup.cpp index e72aefc54..80ffd7fe6 100644 --- a/vehicle/cab/setup.cpp +++ b/vehicle/cab/setup.cpp @@ -1175,7 +1175,7 @@ void TTrain::set_cab_controls(int const Cab) // finding each inverter - not so optimal, but action ins performed only during changing cabin bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; - auto const flag{CouplingSet::FromBits(DynamicObject->MoverParameters->InverterControlCouplerFlag)}; + auto const flag{CouplingSet::FromBits(DynamicObject->MoverParameters->inductionMotor.inverterControlCouplings)}; int itemstart = 0; for ([[maybe_unused]] auto const &item : ggInverterToggleButtons) // for each button { @@ -1184,17 +1184,17 @@ void TTrain::set_cab_controls(int const Cab) TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); while (p) { - if (p->MoverParameters->eimc[eimc_p_Pmax] > 1) + if (p->MoverParameters->inductionMotor.config[eimc_p_Pmax] > 1) { - if (itemindex < p->MoverParameters->InvertersNo) + if (itemindex < p->MoverParameters->inductionMotor.inverterCount) { // visual feedback - ggInverterToggleButtons[itemstart - 1].PutValue(p->MoverParameters->Inverters[itemindex].Activate ? 1.0 : 0.0); + ggInverterToggleButtons[itemstart - 1].PutValue(p->MoverParameters->inductionMotor.inverters[itemindex].Activate ? 1.0 : 0.0); break; } else { - itemindex -= p->MoverParameters->InvertersNo; + itemindex -= p->MoverParameters->inductionMotor.inverterCount; } } p = kier ? p->Next(flag) : p->Prev(flag); diff --git a/vehicle/cab/train.cpp b/vehicle/cab/train.cpp index 3c1f86b62..2bdb38b0b 100644 --- a/vehicle/cab/train.cpp +++ b/vehicle/cab/train.cpp @@ -319,15 +319,15 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const int in = 0; while (p && in < 8) { - if (p->MoverParameters->eimc[eimc_p_Pmax] > 1) + if (p->MoverParameters->inductionMotor.config[eimc_p_Pmax] > 1) { in++; - dict->insert("eimp_c" + std::to_string(in) + "_invno", p->MoverParameters->InvertersNo); - for (int j = 0; j < p->MoverParameters->InvertersNo; j++) + dict->insert("eimp_c" + std::to_string(in) + "_invno", p->MoverParameters->inductionMotor.inverterCount); + for (int j = 0; j < p->MoverParameters->inductionMotor.inverterCount; j++) { - dict->insert("eimp_c" + std::to_string(in) + "_inv" + std::to_string(j + 1) + "_act", p->MoverParameters->Inverters[j].IsActive); - dict->insert("eimp_c" + std::to_string(in) + "_inv" + std::to_string(j + 1) + "_error", p->MoverParameters->Inverters[j].Error); - dict->insert("eimp_c" + std::to_string(in) + "_inv" + std::to_string(j + 1) + "_allow", p->MoverParameters->Inverters[j].Activate); + dict->insert("eimp_c" + std::to_string(in) + "_inv" + std::to_string(j + 1) + "_act", p->MoverParameters->inductionMotor.inverters[j].IsActive); + dict->insert("eimp_c" + std::to_string(in) + "_inv" + std::to_string(j + 1) + "_error", p->MoverParameters->inductionMotor.inverters[j].Error); + dict->insert("eimp_c" + std::to_string(in) + "_inv" + std::to_string(j + 1) + "_allow", p->MoverParameters->inductionMotor.inverters[j].Activate); } } p = kier ? p->Next(Coupling::control) : p->Prev(Coupling::control); diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index 5d193a004..1f883ea4d 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -349,17 +349,17 @@ bool TTrain::Update(double const Deltatime) bCompressors.emplace_back(p->MoverParameters->CompressorAllow || p->MoverParameters->CompressorStart == start_t::automatic, p->MoverParameters->CompressorFlag, i); } bSlip[i] = p->MoverParameters->SlippingWheels; - if (in < 8 && p->MoverParameters->eimc[eimc_p_Pmax] > 1) + if (in < 8 && p->MoverParameters->inductionMotor.config[eimc_p_Pmax] > 1) { - fEIMParams[1 + in][0] = static_cast(p->MoverParameters->eimv[eimv_Fmax]); + fEIMParams[1 + in][0] = static_cast(p->MoverParameters->inductionMotor.state[eimv_Fmax]); fEIMParams[1 + in][1] = std::max(fEIMParams[1 + in][0], 0.f); fEIMParams[1 + in][2] = -std::min(fEIMParams[1 + in][0], 0.f); - fEIMParams[1 + in][3] = static_cast(p->MoverParameters->eimv[eimv_Fmax] / std::max(p->MoverParameters->eimv[eimv_Fful], 1.)); + fEIMParams[1 + in][3] = static_cast(p->MoverParameters->inductionMotor.state[eimv_Fmax] / std::max(p->MoverParameters->inductionMotor.state[eimv_Fful], 1.)); fEIMParams[1 + in][4] = std::max(fEIMParams[1 + in][3], 0.f); fEIMParams[1 + in][5] = -std::min(fEIMParams[1 + in][3], 0.f); - fEIMParams[1 + in][6] = static_cast(p->MoverParameters->eimv[eimv_If]); - fEIMParams[1 + in][7] = static_cast(p->MoverParameters->eimv[eimv_U]); - fEIMParams[1 + in][8] = static_cast(p->MoverParameters->Itot); // p->MoverParameters->eimv[eimv_Ipoj]; + fEIMParams[1 + in][6] = static_cast(p->MoverParameters->inductionMotor.state[eimv_If]); + fEIMParams[1 + in][7] = static_cast(p->MoverParameters->inductionMotor.state[eimv_U]); + fEIMParams[1 + in][8] = static_cast(p->MoverParameters->Itot); // p->MoverParameters->inductionMotor.state[eimv_Ipoj]; fEIMParams[1 + in][9] = static_cast(p->MoverParameters->EngineVoltage); fEIMParams[0][6] += fEIMParams[1 + in][8]; bMains[in] = p->MoverParameters->Mains; @@ -422,15 +422,15 @@ bool TTrain::Update(double const Deltatime) } // if (mvControlled == mvOccupied) - // fEIMParams[0][3] = mvControlled->eimv[eimv_Fzad]; // procent zadany + // fEIMParams[0][3] = mvControlled->inductionMotor.state[eimv_Fzad]; // procent zadany // else // fEIMParams[0][3] = - // mvControlled->eimv[eimv_Fzad] - mvOccupied->LocalBrakeRatio(); // procent zadany + // mvControlled->inductionMotor.state[eimv_Fzad] - mvOccupied->LocalBrakeRatio(); // procent zadany fEIMParams[0][3] = static_cast(mvOccupied->eimic_real); fEIMParams[0][4] = std::max(fEIMParams[0][3], 0.f); fEIMParams[0][5] = -std::min(fEIMParams[0][3], 0.f); - fEIMParams[0][1] = static_cast(fEIMParams[0][4] * mvControlled->eimv[eimv_Fful]); - fEIMParams[0][2] = static_cast(fEIMParams[0][5] * mvControlled->eimv[eimv_Fful]); + fEIMParams[0][1] = static_cast(fEIMParams[0][4] * mvControlled->inductionMotor.state[eimv_Fful]); + fEIMParams[0][2] = static_cast(fEIMParams[0][5] * mvControlled->inductionMotor.state[eimv_Fful]); fEIMParams[0][0] = fEIMParams[0][1] - fEIMParams[0][2]; fEIMParams[0][7] = 0; fEIMParams[0][8] = 0; diff --git a/vehicle/dynamic/sounds.cpp b/vehicle/dynamic/sounds.cpp index 3cde7887c..ee5828877 100644 --- a/vehicle/dynamic/sounds.cpp +++ b/vehicle/dynamic/sounds.cpp @@ -1089,7 +1089,7 @@ TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, doub } if (Vehicle.Mains) { - float power = std::clamp(Vehicle.eimv_pr, 0.0, 1.0); + float power = std::clamp(Vehicle.inductionMotor.forceShare, 0.0, 1.0); fake_engine .pitch(fake_engine.m_frequencyoffset + power * fake_engine.m_frequencyfactor) @@ -1263,12 +1263,12 @@ TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, doub if( false == acmotors.empty() ) { if( Vehicle.EngineType == TEngineType::ElectricInductionMotor ) { - if( Vehicle.InverterFrequency > 0.001 ) { + if( Vehicle.inductionMotor.inverterFrequency > 0.001 ) { for( auto &motor : acmotors ) { motor - .pitch( motor.m_frequencyoffset + motor.m_frequencyfactor * Vehicle.InverterFrequency ) - .gain( motor.m_amplitudeoffset + motor.m_amplitudefactor * std::sqrt( std::abs( Vehicle.eimv_pr ) ) ) + .pitch( motor.m_frequencyoffset + motor.m_frequencyfactor * Vehicle.inductionMotor.inverterFrequency ) + .gain( motor.m_amplitudeoffset + motor.m_amplitudefactor * std::sqrt( std::abs( Vehicle.inductionMotor.forceShare ) ) ) .play( sound_flags::exclusive | sound_flags::looping ); } } @@ -1303,12 +1303,12 @@ TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, doub } // inverter sounds if( Vehicle.EngineType == TEngineType::ElectricInductionMotor ) { - if( Vehicle.InverterFrequency > 0.001 ) { + if( Vehicle.inductionMotor.inverterFrequency > 0.001 ) { - volume = inverter.m_amplitudeoffset + inverter.m_amplitudefactor * std::sqrt( std::abs( Vehicle.eimv_pr) ); + volume = inverter.m_amplitudeoffset + inverter.m_amplitudefactor * std::sqrt( std::abs( Vehicle.inductionMotor.forceShare) ); inverter - .pitch( inverter.m_frequencyoffset + inverter.m_frequencyfactor * Vehicle.InverterFrequency ) + .pitch( inverter.m_frequencyoffset + inverter.m_frequencyfactor * Vehicle.inductionMotor.inverterFrequency ) .gain( volume ) .play( sound_flags::exclusive | sound_flags::looping ); } diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index ece70ca4d..9fd5df13d 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -293,17 +293,17 @@ bool TDynamicObject::Update(double dt, double dt1) Nmax / (p->MoverParameters->NAxles * p->MoverParameters->NBpA), p->MoverParameters->MED_Vref) * 1000; // sila hamowania pn - FmaxED += p->MoverParameters->Mains && p->MoverParameters->DirActive != 0 && p->MoverParameters->InvertersRatio == 1.0 && - p->MoverParameters->eimc[eimc_p_Fh] * p->MoverParameters->NPoweredAxles > 0 ? - p->MoverParameters->eimc[eimc_p_Fh] * 1000 : + FmaxED += p->MoverParameters->Mains && p->MoverParameters->DirActive != 0 && p->MoverParameters->inductionMotor.inverterRatio == 1.0 && + p->MoverParameters->inductionMotor.config[eimc_p_Fh] * p->MoverParameters->NPoweredAxles > 0 ? + p->MoverParameters->inductionMotor.config[eimc_p_Fh] * 1000 : 0; // chwilowy max ED -> do rozdzialu sil - FED -= std::min(p->MoverParameters->eimv[eimv_Fmax], 0.0) * + FED -= std::min(p->MoverParameters->inductionMotor.state[eimv_Fmax], 0.0) * 1000; // chwilowy max ED -> do rozdzialu sil - FfulED = std::min(p->MoverParameters->eimv[eimv_Fful], 0.0) * + FfulED = std::min(p->MoverParameters->inductionMotor.state[eimv_Fful], 0.0) * 1000; // chwilowy max ED -> do rozdzialu sil - FrED -= std::min(p->MoverParameters->eimv[eimv_Fmax], 0.0) * + FrED -= std::min(p->MoverParameters->inductionMotor.state[eimv_Fmax], 0.0) * 1000; // chwilowo realizowane ED -> do pneumatyki - Frj += std::max(p->MoverParameters->eimv[eimv_Fmax], 0.0) * + Frj += std::max(p->MoverParameters->inductionMotor.state[eimv_Fmax], 0.0) * 1000;// chwilowo realizowany napęd -> do utrzymującego masa += p->MoverParameters->TotalMass; osie += p->MoverParameters->NAxles; @@ -341,11 +341,11 @@ bool TDynamicObject::Update(double dt, double dt1) } auto Fzad = amax * LBR * masa; if ((MoverParameters->BrakeCtrlPos == MoverParameters->Handle->GetPos(bh_EB) - && MoverParameters->eimc[eimc_p_abed] < 0.001) || + && MoverParameters->inductionMotor.config[eimc_p_abed] < 0.001) || MoverParameters->EmergencyValveFlow > 0) Fzad = amax * masa; //pętla bezpieczeństwa - pełne służbowe if (MoverParameters->ScndS && - MoverParameters->Vel > MoverParameters->eimc[eimc_p_Vh1] && FmaxED > 0) + MoverParameters->Vel > MoverParameters->inductionMotor.config[eimc_p_Vh1] && FmaxED > 0) { Fzad = std::min(LBR * FmaxED, FfulED); } @@ -403,7 +403,7 @@ bool TDynamicObject::Update(double dt, double dt1) } } if (MoverParameters->BrakeCtrlPos == MoverParameters->Handle->GetPos(bh_EB) - && MoverParameters->eimc[eimc_p_abed] < 0.001) + && MoverParameters->inductionMotor.config[eimc_p_abed] < 0.001) FzadED = 0; //pętla bezpieczeństwa - bez ED auto const FzadPN = Fzad - FrED * MoverParameters->MED_FrED_factor; std::vector PrzekrF( np ); @@ -458,13 +458,13 @@ bool TDynamicObject::Update(double dt, double dt1) p = kier == true ? p->Next(Coupling::control) : p->Prev(Coupling::control) ) { if (FzEP[i] > 0.01 && - FzEP[i] > p->MoverParameters->TotalMass * p->MoverParameters->eimc[eimc_p_eped] + std::min(p->MoverParameters->eimv[eimv_Fmax], 0.) * 1000 && + FzEP[i] > p->MoverParameters->TotalMass * p->MoverParameters->inductionMotor.config[eimc_p_eped] + std::min(p->MoverParameters->inductionMotor.state[eimv_Fmax], 0.) * 1000 && !PrzekrF[i]) { - float przek1 = -std::min(p->MoverParameters->eimv[eimv_Fmax], 0.) * 1000 + + float przek1 = -std::min(p->MoverParameters->inductionMotor.state[eimv_Fmax], 0.) * 1000 + FzEP[i] - p->MoverParameters->TotalMass * - p->MoverParameters->eimc[eimc_p_eped] * 0.999; + p->MoverParameters->inductionMotor.config[eimc_p_eped] * 0.999; PrzekrF[i] = true; test = true; nPrzekrF++; From 95e7b5549550eaa8e398fde18bb86028ea940dbe Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sat, 28 Nov 2026 16:02:59 +0100 Subject: [PATCH 021/123] refactor(physics): the revolutions of the engine and the steps of the master controller in the drives Two more switches on EngineType go into the classes of the drives: - TractionDrive::UpdateEngineRevolutions(): the diesel-electric engine follows the revolutions it aims for, the diesel engine with a mechanical transmission gives its ratio and its moment, the others turn with the wheels (UpdateEngineRevolutions() before) - TractionDrive::IncreaseMainController(), DecreaseMainController(): a notch of the master controller as the kind of the engine takes it: the series motors through their own steps, the diesel engine running to the end at a fast step, the draisine by a push, the others one position at a time (IncMainCtrlByEngine(), DecMainCtrlByEngine() before) NoDrive splits in two: NoEngineDrive for a vehicle without an engine (its controller steps, for the vehicles it controls) and UnmodelledDrive for the steam engine and Main, which did nothing in these steps and still don't. No change in behaviour: 1144/1144 tests, golden traces exact against staging 62f7a29b. --- physics/components/controllers.cpp | 107 +---------------- physics/components/diesel.cpp | 46 +------- physics/components/drive.cpp | 180 ++++++++++++++++++++++++++++- physics/components/drive.h | 6 + 4 files changed, 185 insertions(+), 154 deletions(-) diff --git a/physics/components/controllers.cpp b/physics/components/controllers.cpp index df0dca529..c16a8104f 100644 --- a/physics/components/controllers.cpp +++ b/physics/components/controllers.cpp @@ -28,6 +28,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include "physics/components/internal.h" +#include "physics/components/drive.h" // ************************************************************************************************* @@ -108,62 +109,7 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) // a notch up, as the kind of the engine takes it; returns whether the controller moved bool TMoverParameters::IncMainCtrlByEngine(int const CtrlSpeed) { - bool OK = false; - switch (EngineType) - { - case TEngineType::None: - case TEngineType::Dumb: - case TEngineType::DieselElectric: - case TEngineType::ElectricInductionMotor: - { - if (CtrlSpeed > 1) - { - OK = IncMainCtrl(1) && IncMainCtrl(CtrlSpeed - 1); // a fail will propagate up the recursion chain. should this be || instead? - break; - } - ++MainCtrlPos; - OK = true; - if (EIMCtrlType == 0 && ( SpeedCtrlAutoTurnOffFlag & 1 ) == 1 && MainCtrlActualPos != MainCtrlPos) - { - SpeedCtrlSwitch(false); - SpeedCtrlUnit.IsActive = false; - } - break; - } - - case TEngineType::ElectricSeriesMotor: - { - OK = IncMainCtrlSeriesMotor(CtrlSpeed); - break; - } - - case TEngineType::DieselEngine: - { - if (CtrlSpeed > 1) - { - while (MainCtrlPos < MainCtrlPosNo && IncMainCtrl(1)) - { - // all work is done in the loop header - } - } - else - { - ++MainCtrlPos; - } - CompressorAllow = MainCtrlPowerPos() > 0; - OK = true; - break; - } - - case TEngineType::WheelsDriven: - { - OK = AddPulseForce(CtrlSpeed); - break; - } - default: - break; - } // switch EngineType of - return OK; + return Drive().IncreaseMainController(*this, CtrlSpeed); } // a notch up of the series motors' controller: CtrlSpeed over 1 runs it to the first position without resistors; @@ -292,54 +238,7 @@ bool TMoverParameters::DecMainCtrl(int CtrlSpeed) // a notch down, as the kind of the engine takes it; returns whether the controller moved bool TMoverParameters::DecMainCtrlByEngine(int const CtrlSpeed) { - bool OK = false; - switch (EngineType) - { - case TEngineType::None: - case TEngineType::Dumb: - case TEngineType::DieselElectric: - case TEngineType::ElectricInductionMotor: - { - if (CtrlSpeed == 1) - { - MainCtrlPos--; - OK = true; - if (EIMCtrlType == 0 && (SpeedCtrlAutoTurnOffFlag & 1) == 1 && MainCtrlActualPos != MainCtrlPos) - { - SpeedCtrlSwitch(false); - SpeedCtrlUnit.IsActive = false; - } - } - else if (CtrlSpeed > 1) - OK = DecMainCtrl(1) && DecMainCtrl(CtrlSpeed - 1); // CtrlSpeed-1); - break; - } - - case TEngineType::ElectricSeriesMotor: - { - OK = DecMainCtrlSeriesMotor(CtrlSpeed); - break; - } - - case TEngineType::DieselEngine: - { - if (CtrlSpeed == 1) - { - MainCtrlPos--; - OK = true; - } - else if (CtrlSpeed > 1) - { - while (MainCtrlPos > 0 || RList[MainCtrlPos].Mn > 0) - DecMainCtrl(1); - OK = true; - } - break; - } - default: - break; - } // switch EngineType - return OK; + return Drive().DecreaseMainController(*this, CtrlSpeed); } // a notch down of the series motors' controller: CtrlSpeed over 1 runs it down to the first position without resistors diff --git a/physics/components/diesel.cpp b/physics/components/diesel.cpp index 8879fdd6e..aee5d8e21 100644 --- a/physics/components/diesel.cpp +++ b/physics/components/diesel.cpp @@ -328,51 +328,7 @@ bool TMoverParameters::OilPumpSwitchOff(bool State, range_t const Notify) // for a diesel engine, the ratio of the transmission and the engine's moment double TMoverParameters::UpdateEngineRevolutions(double dt, double &dtrans, double &dmoment) { - double tmp{0.0}; - // youBy - switch (EngineType) - { - case TEngineType::DieselElectric: - { - if (true == Mains && true == FuelPump.is_active) - { - tmp = DieselElectricTargetRevolutions(); - } - else - { - tmp = 0.0; - diesel.fill = 0.0; - } - - if (enrot != tmp) - { - enrot = safe_clamp(enrot + dt / diesel.shaftInertia * (enrot < tmp ? 1.0 : -1.0 * diesel.revolutionsDecreaseRate), // NOTE: revolutions typically drop faster than they rise - 0.0, std::max(tmp, enrot)); - if (std::abs(tmp - enrot) < 0.001) - { - enrot = tmp; - } - } - break; - } - case TEngineType::DieselEngine: - { - if (ShuntMode) // dodatkowa przekładnia np. dla 2Ls150 - dtrans = AnPos * Transmision.Ratio * motor_param(ScndCtrlActualPos).mIsat; - else - dtrans = Transmision.Ratio * motor_param(ScndCtrlActualPos).mIsat; - - dmoment = dizel_Momentum(diesel.fill, dtrans * nrot * DirActive, dt); // oblicza tez enrot - break; - } - default: - { - enrot = Transmision.Ratio * nrot; - break; - } - } - - return tmp; + return Drive().UpdateEngineRevolutions(*this, dt, dtrans, dmoment); } // the revolutions a diesel-electric's engine aims at [1/s], by the controller and the heating; the fill shown by the smoke diff --git a/physics/components/drive.cpp b/physics/components/drive.cpp index 99989e1a2..323d2c044 100644 --- a/physics/components/drive.cpp +++ b/physics/components/drive.cpp @@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/. #include #include "physics/mover.h" +#include "utilities/utilities.h" // the defaults: a drive with no engine model and no engine of revolutions does nothing in the steps @@ -65,6 +66,22 @@ double TractionDrive::EngineMaxRpm(TMoverParameters const & /*vehicle*/) const return std::numeric_limits::max(); } +double TractionDrive::UpdateEngineRevolutions(TMoverParameters &vehicle, double /*dt*/, double & /*transmission*/, double & /*moment*/) const +{ + vehicle.enrot = vehicle.Transmision.Ratio * vehicle.nrot; + return 0.0; +} + +bool TractionDrive::IncreaseMainController(TMoverParameters & /*vehicle*/, int /*speed*/) const +{ + return false; +} + +bool TractionDrive::DecreaseMainController(TMoverParameters & /*vehicle*/, int /*speed*/) const +{ + return false; +} + namespace { @@ -84,8 +101,58 @@ void updateRadiatorFans(TMoverParameters &vehicle, double const dt) } } -// a vehicle without an engine (a wagon), or of an engine with no model (steam, Main) -class NoDrive final : public TractionDrive +// a notch of the master controller of the drives without steps of their own (no engine, Dumb, diesel-electric, +// induction): one position at a time, the speed control let go when the position leaves the one it holds +bool increaseNotch(TMoverParameters &vehicle, int const speed) +{ + if (speed > 1) + { + return vehicle.IncMainCtrl(1) && vehicle.IncMainCtrl(speed - 1); // a fail will propagate up the recursion chain. should this be || instead? + } + ++vehicle.MainCtrlPos; + if (vehicle.EIMCtrlType == 0 && (vehicle.SpeedCtrlAutoTurnOffFlag & 1) == 1 && vehicle.MainCtrlActualPos != vehicle.MainCtrlPos) + { + vehicle.SpeedCtrlSwitch(false); + vehicle.SpeedCtrlUnit.IsActive = false; + } + return true; +} + +bool decreaseNotch(TMoverParameters &vehicle, int const speed) +{ + if (speed == 1) + { + vehicle.MainCtrlPos--; + if (vehicle.EIMCtrlType == 0 && (vehicle.SpeedCtrlAutoTurnOffFlag & 1) == 1 && vehicle.MainCtrlActualPos != vehicle.MainCtrlPos) + { + vehicle.SpeedCtrlSwitch(false); + vehicle.SpeedCtrlUnit.IsActive = false; + } + return true; + } + if (speed > 1) + { + return vehicle.DecMainCtrl(1) && vehicle.DecMainCtrl(speed - 1); + } + return false; +} + +// a vehicle without an engine (a wagon, a control car): its controller still steps, for the vehicles it controls +class NoEngineDrive final : public TractionDrive +{ +public: + bool IncreaseMainController(TMoverParameters &vehicle, int const speed) const override + { + return increaseNotch(vehicle, speed); + } + bool DecreaseMainController(TMoverParameters &vehicle, int const speed) const override + { + return decreaseNotch(vehicle, speed); + } +}; + +// an engine with no model at all (steam, Main): nothing happens in the steps +class UnmodelledDrive final : public TractionDrive { }; @@ -103,6 +170,14 @@ public: { vehicle.DumbTractionForce(step.posRatio); } + bool IncreaseMainController(TMoverParameters &vehicle, int const speed) const override + { + return increaseNotch(vehicle, speed); + } + bool DecreaseMainController(TMoverParameters &vehicle, int const speed) const override + { + return decreaseNotch(vehicle, speed); + } }; // a draisine and the like, the wheels driven by hand @@ -113,6 +188,10 @@ public: { vehicle.WheelsDrivenTractionForce(step.dt); } + bool IncreaseMainController(TMoverParameters &vehicle, int const speed) const override + { + return vehicle.AddPulseForce(speed); + } }; // series wound direct current motors, started through resistors @@ -123,6 +202,14 @@ public: { vehicle.SeriesMotorTractionForce(step.dt); } + bool IncreaseMainController(TMoverParameters &vehicle, int const speed) const override + { + return vehicle.IncMainCtrlSeriesMotor(speed); + } + bool DecreaseMainController(TMoverParameters &vehicle, int const speed) const override + { + return vehicle.DecMainCtrlSeriesMotor(speed); + } void UpdateVentilators(TMoverParameters &vehicle, double const dt) const override { if (vehicle.MainCircuitPowered()) @@ -144,6 +231,14 @@ public: { vehicle.InductionMotorTractionForce(step.dt); } + bool IncreaseMainController(TMoverParameters &vehicle, int const speed) const override + { + return increaseNotch(vehicle, speed); + } + bool DecreaseMainController(TMoverParameters &vehicle, int const speed) const override + { + return decreaseNotch(vehicle, speed); + } double ShowCurrent(TMoverParameters const &vehicle, int const ammeter) const override { switch (ammeter) @@ -177,6 +272,47 @@ public: { vehicle.DieselEngineTractionForce(step.dt, step.moment, step.transmission); } + double UpdateEngineRevolutions(TMoverParameters &vehicle, double const dt, double &transmission, double &moment) const override + { + if (vehicle.ShuntMode) // dodatkowa przekładnia np. dla 2Ls150 + transmission = vehicle.AnPos * vehicle.Transmision.Ratio * vehicle.motor_param(vehicle.ScndCtrlActualPos).mIsat; + else + transmission = vehicle.Transmision.Ratio * vehicle.motor_param(vehicle.ScndCtrlActualPos).mIsat; + + moment = vehicle.dizel_Momentum(vehicle.diesel.fill, transmission * vehicle.nrot * vehicle.DirActive, dt); // oblicza tez enrot + return 0.0; + } + bool IncreaseMainController(TMoverParameters &vehicle, int const speed) const override + { + if (speed > 1) + { + while (vehicle.MainCtrlPos < vehicle.MainCtrlPosNo && vehicle.IncMainCtrl(1)) + { + // all work is done in the loop header + } + } + else + { + ++vehicle.MainCtrlPos; + } + vehicle.CompressorAllow = vehicle.MainCtrlPowerPos() > 0; + return true; + } + bool DecreaseMainController(TMoverParameters &vehicle, int const speed) const override + { + if (speed == 1) + { + vehicle.MainCtrlPos--; + return true; + } + if (speed > 1) + { + while (vehicle.MainCtrlPos > 0 || vehicle.RList[vehicle.MainCtrlPos].Mn > 0) + vehicle.DecMainCtrl(1); + return true; + } + return false; + } void UpdateVentilators(TMoverParameters &vehicle, double const dt) const override { // NOTE: we update only radiator fans, as vehicles with diesel engine don't have other ventilators @@ -221,6 +357,38 @@ public: vehicle.apply_dieselelectric_dynamic_brake(step.dt); } } + double UpdateEngineRevolutions(TMoverParameters &vehicle, double const dt, double & /*transmission*/, double & /*moment*/) const override + { + double target{0.0}; + if (true == vehicle.Mains && true == vehicle.FuelPump.is_active) + { + target = vehicle.DieselElectricTargetRevolutions(); + } + else + { + target = 0.0; + vehicle.diesel.fill = 0.0; + } + + if (vehicle.enrot != target) + { + vehicle.enrot = safe_clamp(vehicle.enrot + dt / vehicle.diesel.shaftInertia * (vehicle.enrot < target ? 1.0 : -1.0 * vehicle.diesel.revolutionsDecreaseRate), // NOTE: revolutions typically drop faster than they rise + 0.0, std::max(target, vehicle.enrot)); + if (std::abs(target - vehicle.enrot) < 0.001) + { + vehicle.enrot = target; + } + } + return target; + } + bool IncreaseMainController(TMoverParameters &vehicle, int const speed) const override + { + return increaseNotch(vehicle, speed); + } + bool DecreaseMainController(TMoverParameters &vehicle, int const speed) const override + { + return decreaseNotch(vehicle, speed); + } void AfterTractionForce(TMoverParameters &vehicle) const override { // rough approximation of extra effort to overcome friction etc @@ -258,7 +426,8 @@ public: } }; -NoDrive const noDrive{}; +NoEngineDrive const noEngineDrive{}; +UnmodelledDrive const unmodelledDrive{}; DumbDrive const dumbDrive{}; WheelsDrivenDrive const wheelsDrivenDrive{}; SeriesMotorDrive const seriesMotorDrive{}; @@ -285,9 +454,10 @@ TractionDrive const &DriveOf(TEngineType const type) case TEngineType::DieselElectric: return dieselElectricDrive; case TEngineType::None: + return noEngineDrive; case TEngineType::SteamEngine: case TEngineType::Main: - return noDrive; + return unmodelledDrive; } - return noDrive; + return unmodelledDrive; } diff --git a/physics/components/drive.h b/physics/components/drive.h index 0d13d94d9..a50f23d7c 100644 --- a/physics/components/drive.h +++ b/physics/components/drive.h @@ -50,6 +50,12 @@ public: // the revolutions of the engine idling and at most [rpm]; the largest double with no engine of revolutions virtual double EngineIdleRpm(TMoverParameters const &vehicle) const; virtual double EngineMaxRpm(TMoverParameters const &vehicle) const; + // the revolutions of the engine in the step (enrot); returns the revolutions a diesel-electric engine aims for, 0 for + // the others. a diesel engine with a mechanical transmission gives its ratio and its moment through the references + virtual double UpdateEngineRevolutions(TMoverParameters &vehicle, double dt, double &transmission, double &moment) const; + // a notch up and down of the master controller, as the kind of the engine takes it; return whether it moved + virtual bool IncreaseMainController(TMoverParameters &vehicle, int speed) const; + virtual bool DecreaseMainController(TMoverParameters &vehicle, int speed) const; }; // the drive of the given kind of engine From f4ef43feec6bd25cd7d937743dff594951eeff84 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sat, 28 Nov 2026 16:29:17 +0100 Subject: [PATCH 022/123] refactor(physics): the definition and the state of the induction motor drive as named fields The arrays eimc[26] and eimv[21] of InductionMotor, indexed by the eimc_* and eimv_* constants, become structs with named and described fields. The definition splits into blocks by what it describes: motor dfic currentPerSlip, dfmax maxSlipFrequency, p polePairs, cfu voltsPerHertz, cim torquePerCurrent, icif fieldCurrentRatio converter Uzmax maxLinkVoltage, Uzh brakingLinkVoltage, DU voltageDrop, I0 noLoadCurrent, fcfu voltsPerHertz, fcfuH brakingVoltsPerHertz traction F0 startingForce, a1 forceDropPerSpeed, Pmax maxPower, Imax maxCurrent braking Fh maxForce, Ph maxPower, Vh0 offSpeed, Vh1 fullSpeed, abed cylinderPressureGain, edep maxEpDeceleration and the state (InductionMotorState) groups the forces, the frequencies, the values of the motors and the powers: FMAXMAX absoluteMaxForce, Fmax maxForce, Fful fullForce, Fr force, Fzad forceDemand, ks slipShare, df slipFrequency, fp supplyFrequency, fkr criticalFrequency, Uzsmax linkVoltage, U voltage, pole flux, Ic torqueCurrent, If fieldCurrent, M torque, Ipoj lineCurrent, Imax currentLimit, Pmax powerLimit, Pm mechanicalPower, Pe electricalPower, eta efficiency. The old comments of the constants took the "h" entries (Uzh, fcfuH, Fh, Ph, Vh0, Vh1) for field weakening; the code uses them for the electrodynamic brake, and the new names say so. The .fiz keys don't change. The constants eimc_* / eimv_* are gone from physics/vehicletypes.h, and the labels of the debug panel (TMoverParameters::eimc_labels, eimv_labels) move into InductionMotor::ConfigListing() and StateListing(). One change on the screen: the eimc column of the debug panel (the engine section of an induction motor vehicle) showed the labels from "Uzmax:" on next to the wrong values (shifted by one entry, from "F0:" on by two), and never showed abed and eped. It now shows each label with its own value. The eimv column is as it was. No change in the simulation: 1144/1144 tests, golden traces exact against staging 62f7a29b. --- application/driveruipanels.cpp | 6 +- physics/components/body.cpp | 19 +--- physics/components/controllers.cpp | 4 +- physics/components/fizsections.cpp | 48 +++++----- physics/components/inductionmotor.h | 133 +++++++++++++++++++++++++++- physics/components/traction.cpp | 119 ++++++++++++------------- physics/mover.h | 4 +- physics/vehicletypes.h | 90 ------------------- tests/unit/test_definition.cpp | 4 +- tests/unit/test_elf_controller.cpp | 2 +- tests/unit/test_fcfuh_default.cpp | 10 +-- tests/unit/test_genset.cpp | 2 +- vehicle/cab/equipmentcommands.cpp | 6 +- vehicle/cab/setup.cpp | 2 +- vehicle/cab/train.cpp | 2 +- vehicle/cab/update.cpp | 20 ++--- vehicle/dynamic/update.cpp | 24 ++--- 17 files changed, 258 insertions(+), 237 deletions(-) diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 06c703089..304cf5d1a 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -1095,12 +1095,14 @@ debug_panel::update_section_engine( std::vector &Output ) const { if( mover.EngineType == TEngineType::ElectricInductionMotor ) { Output.emplace_back( " eimc: eimv: press:", Global.UITextColor ); + auto const config{ mover.inductionMotor.ConfigListing() }; + auto const state{ mover.inductionMotor.StateListing() }; for( int i = 0; i <= 20; ++i ) { std::string parameters = - TMoverParameters::eimc_labels[ i ] + to_string( mover.inductionMotor.config[ i ], 2, 9 ) + std::string( config[ i ].first ) + to_string( config[ i ].second, 2, 9 ) + " | " - + TMoverParameters::eimv_labels[ i ] + to_string( mover.inductionMotor.state[ i ], 2, 9 ); + + std::string( state[ i ].first ) + to_string( state[ i ].second, 2, 9 ); if( i < 10 ) { parameters += diff --git a/physics/components/body.cpp b/physics/components/body.cpp index 6c700f1ec..aeb604f34 100644 --- a/physics/components/body.cpp +++ b/physics/components/body.cpp @@ -30,12 +30,6 @@ http://mozilla.org/MPL/2.0/. #include "physics/components/internal.h" -std::vector const TMoverParameters::eimc_labels = {"dfic: ", "dfmax:", "p: ", "scfu: ", "cim: ", "icif: ", "Uzmax:", "Uzh: ", "DU: ", "I0: ", "fcfu: ", - "F0: ", "a1: ", "Pmax: ", "Fh: ", "Ph: ", "Vh0: ", "Vh1: ", "Imax: ", "abed: ", "eped: "}; - -std::vector const TMoverParameters::eimv_labels = { - "Fkrt:", "Fmax:", "ks: ", "df: ", "fp: ", "Us: ", "pole:", "Ic: ", "If: ", "M: ", "Fr: ", "Ipoj:", "Pm: ", "Pe: ", "eta: ", "fkr: ", "Uzsm:", "Pmax:", "Fzad:", "Imax:", "Fful:"}; - int DirPatch(int Coupler1, int Coupler2) { // poprawka dla liczenia sil przy ustawieniu przeciwnym obiektow return Coupler1 != Coupler2 ? 1 : -1; @@ -136,12 +130,6 @@ TMoverParameters::TMoverParameters(double VelInitial, std::string const &TypeNam cylindermult = 0.0; } - for (auto &eimcvalue : inductionMotor.config) - { - eimcvalue = 0.0; - } - inductionMotor.config[eimc_p_eped] = 1.5; - for (auto &couplerentry : Couplers) { couplerentry.AllowedFlag = Coupling::coupler | Coupling::brakeHose; // domyślnie hak i hamulec, inne trzeba włączyć jawnie w FIZ @@ -162,11 +150,6 @@ TMoverParameters::TMoverParameters(double VelInitial, std::string const &TypeNam Vel = abs(VelInitial); V = VelInitial / 3.6; - for (auto &eimvvalue : inductionMotor.state) - { - eimvvalue = 0.0; - } - RunningShape.Len = 1.0; RunningTrack.CategoryFlag = CategoryFlag; @@ -456,7 +439,7 @@ void TMoverParameters::compute_movement_(double const Deltatime) // Prad oddawany na rezystor // Wlacz wentylator jesli prad rekuperacji przekroczy maksymalny dla pasywnego chlodzenia rezystora - if (double Irh = abs(inductionMotor.state[eimv_Pe]) - abs(inductionMotor.state[eimv_Ipoj]); Irh > Imaxrpc && inductionMotor.state[eimv_Ipoj] < 0) + if (double Irh = abs(inductionMotor.state.electricalPower) - abs(inductionMotor.state.lineCurrent); Irh > Imaxrpc && inductionMotor.state.lineCurrent < 0) { BRVtimer = 0; BRVentilators = true; diff --git a/physics/components/controllers.cpp b/physics/components/controllers.cpp index c16a8104f..fc0e5e1ee 100644 --- a/physics/components/controllers.cpp +++ b/physics/components/controllers.cpp @@ -1002,8 +1002,8 @@ void TMoverParameters::CheckEIMIC(double dt) double brakeDemand = SplitEDPneumaticBrake ? DynamicBrakeRatio() : LocalBrakeRatio(); if (SplitEDPneumaticBrake) { - double const vh0 = inductionMotor.config[eimc_p_Vh0]; - double const vh1 = inductionMotor.config[eimc_p_Vh1]; + double const vh0 = inductionMotor.braking.offSpeed; + double const vh1 = inductionMotor.braking.fullSpeed; if (vh1 > vh0 + 0.001) { double const vhRamp = std::clamp((Vel - vh0) / (vh1 - vh0), 0.0, 1.0); diff --git a/physics/components/fizsections.cpp b/physics/components/fizsections.cpp index 3b2a4eaaa..7c2d082fc 100644 --- a/physics/components/fizsections.cpp +++ b/physics/components/fizsections.cpp @@ -1380,32 +1380,32 @@ void TMoverParameters::LoadFIZ_EngineInductionMotor(std::string const &Input) RVentnmax = 1.0; extract_value(NominalVoltage, "Volt", Input, ""); - extract_value(inductionMotor.config[eimc_s_dfic], "dfic", Input, ""); - extract_value(inductionMotor.config[eimc_s_dfmax], "dfmax", Input, ""); - extract_value(inductionMotor.config[eimc_s_p], "p", Input, ""); - extract_value(inductionMotor.config[eimc_s_cfu], "cfu", Input, ""); - extract_value(inductionMotor.config[eimc_s_cim], "cim", Input, ""); - extract_value(inductionMotor.config[eimc_s_icif], "icif", Input, ""); - extract_value(inductionMotor.config[eimc_f_Uzmax], "Uzmax", Input, ""); - extract_value(inductionMotor.config[eimc_f_Uzh], "Uzh", Input, ""); - extract_value(inductionMotor.config[eimc_f_DU], "DU", Input, ""); - extract_value(inductionMotor.config[eimc_f_I0], "I0", Input, ""); - extract_value(inductionMotor.config[eimc_f_cfu], "fcfu", Input, ""); - if (false == extract_value(inductionMotor.config[eimc_f_cfuH], "fcfuH", Input, "")) + extract_value(inductionMotor.motor.currentPerSlip, "dfic", Input, ""); + extract_value(inductionMotor.motor.maxSlipFrequency, "dfmax", Input, ""); + extract_value(inductionMotor.motor.polePairs, "p", Input, ""); + extract_value(inductionMotor.motor.voltsPerHertz, "cfu", Input, ""); + extract_value(inductionMotor.motor.torquePerCurrent, "cim", Input, ""); + extract_value(inductionMotor.motor.fieldCurrentRatio, "icif", Input, ""); + extract_value(inductionMotor.converter.maxLinkVoltage, "Uzmax", Input, ""); + extract_value(inductionMotor.converter.brakingLinkVoltage, "Uzh", Input, ""); + extract_value(inductionMotor.converter.voltageDrop, "DU", Input, ""); + extract_value(inductionMotor.converter.noLoadCurrent, "I0", Input, ""); + extract_value(inductionMotor.converter.voltsPerHertz, "fcfu", Input, ""); + if (false == extract_value(inductionMotor.converter.brakingVoltsPerHertz, "fcfuH", Input, "")) { // without its own figure the dynamic brake takes the one of the traction - inductionMotor.config[eimc_f_cfuH] = inductionMotor.config[eimc_f_cfu]; + inductionMotor.converter.brakingVoltsPerHertz = inductionMotor.converter.voltsPerHertz; } - extract_value(inductionMotor.config[eimc_p_F0], "F0", Input, ""); - extract_value(inductionMotor.config[eimc_p_a1], "a1", Input, ""); - extract_value(inductionMotor.config[eimc_p_Pmax], "Pmax", Input, ""); - extract_value(inductionMotor.config[eimc_p_Fh], "Fh", Input, ""); - extract_value(inductionMotor.config[eimc_p_Ph], "Ph", Input, ""); - extract_value(inductionMotor.config[eimc_p_Vh0], "Vh0", Input, ""); - extract_value(inductionMotor.config[eimc_p_Vh1], "Vh1", Input, ""); - extract_value(inductionMotor.config[eimc_p_Imax], "Imax", Input, ""); - extract_value(inductionMotor.config[eimc_p_abed], "abed", Input, ""); - extract_value(inductionMotor.config[eimc_p_eped], "edep", Input, ""); + extract_value(inductionMotor.traction.startingForce, "F0", Input, ""); + extract_value(inductionMotor.traction.forceDropPerSpeed, "a1", Input, ""); + extract_value(inductionMotor.traction.maxPower, "Pmax", Input, ""); + extract_value(inductionMotor.braking.maxForce, "Fh", Input, ""); + extract_value(inductionMotor.braking.maxPower, "Ph", Input, ""); + extract_value(inductionMotor.braking.offSpeed, "Vh0", Input, ""); + extract_value(inductionMotor.braking.fullSpeed, "Vh1", Input, ""); + extract_value(inductionMotor.traction.maxCurrent, "Imax", Input, ""); + extract_value(inductionMotor.braking.cylinderPressureGain, "abed", Input, ""); + extract_value(inductionMotor.braking.maxEpDeceleration, "edep", Input, ""); extract_value(inductionMotor.logForce, "eimclf", Input, ""); extract_value(inductionMotor.inverterCount, "InvNo", Input, ""); extract_value(inductionMotor.inverterControlCouplings, "InvCtrCplFlag", Input, ""); @@ -1413,7 +1413,7 @@ void TMoverParameters::LoadFIZ_EngineInductionMotor(std::string const &Input) extract_value(BRVto, "BRVto", Input, ""); extract_value(Flat, "Flat", Input, ""); - if (inductionMotor.config[eimc_p_Pmax] > 0 && Power > 0 && inductionMotor.inverterCount == 0) + if (inductionMotor.traction.maxPower > 0 && Power > 0 && inductionMotor.inverterCount == 0) { inductionMotor.inverterCount = 1; } diff --git a/physics/components/inductionmotor.h b/physics/components/inductionmotor.h index 0a53ffb5c..45fc35b12 100644 --- a/physics/components/inductionmotor.h +++ b/physics/components/inductionmotor.h @@ -13,6 +13,8 @@ http://mozilla.org/MPL/2.0/. #include #include +#include +#include #include // an inverter of the drive @@ -27,10 +29,87 @@ struct Inverter bool Failure_Const = false; }; +// the motor itself (the s_ entries of eimc before) +struct InductionMotorWinding +{ + double currentPerSlip = 0.0; // dfic: the torque current per hertz of slip, at full flux + double maxSlipFrequency = 0.0; // dfmax: the most slip the drive allows [Hz] + double polePairs = 0.0; // p: the pairs of poles + double voltsPerHertz = 0.0; // cfu: the voltage per hertz of full flux + double torquePerCurrent = 0.0; // cim: the torque per unit of flux and torque current + double fieldCurrentRatio = 0.0; // icif: the field current per unit of torque current +}; + +// the inverter feeding the motors (the f_ entries of eimc before) +struct InductionMotorConverter +{ + double maxLinkVoltage = 0.0; // Uzmax: the most voltage the inverter gives the motors in traction [V] + double brakingLinkVoltage = 0.0; // Uzh: the same in electrodynamic braking [V] + double voltageDrop = 0.0; // DU: the voltage lost in the inverter [V] + double noLoadCurrent = 0.0; // I0: the current the drive draws with no load [A] + double voltsPerHertz = 0.0; // fcfu: the voltage per hertz the inverter gives in traction + double brakingVoltsPerHertz = 0.0; // fcfuH: the same in electrodynamic braking, fcfu without it +}; + +// what the drive gives in traction (the p_ entries of eimc before) +struct InductionMotorTraction +{ + double startingForce = 0.0; // F0: the force at a standstill [kN] + double forceDropPerSpeed = 0.0; // a1: how much of the starting force each km/h takes away [kN/(km/h)] + double maxPower = 0.0; // Pmax: the most power [kW]; follows the table of the most power by the speed, where there is one + double maxCurrent = 0.0; // Imax: the most current of the motors [A] +}; + +// the electrodynamic brake of the drive (the p_ entries of eimc before) +struct InductionMotorBraking +{ + double maxForce = 0.0; // Fh: the most braking force [kN] + double maxPower = 0.0; // Ph: the most braking power [kW] + double offSpeed = 0.0; // Vh0: below this speed the electrodynamic brake gives nothing [km/h] + double fullSpeed = 0.0; // Vh1: above this speed the electrodynamic brake gives all it can; between the two it fades [km/h] + double cylinderPressureGain = 0.0; // abed: the share of the brake cylinder pressure the electrodynamic brake takes; 0: the air brake cuts it off + double maxEpDeceleration = 1.5; // edep: the most the electro-pneumatic brake of a vehicle decelerates its mass before the force goes elsewhere [m/s2] +}; + +// the values of the model of the drive in the step (eimv before) +struct InductionMotorState +{ + // the forces [kN] + double absoluteMaxForce = 0.0; // FMAXMAX: the most force the motors can give at the present speed and voltage + double maxForce = 0.0; // Fmax: the force at the present setting + double fullForce = 0.0; // Fful: the force at a full setting + double force = 0.0; // Fr: the force the motors give + double forceDemand = 0.0; // Fzad: the share of the force asked of the drive, negative in braking + // the frequencies + double slipShare = 0.0; // ks: the force against the most there is, the share of the most slip + double slipFrequency = 0.0; // df [Hz] + double supplyFrequency = 0.0; // fp: the frequency the inverter gives the motors [Hz] + double criticalFrequency = 0.0; // fkr: above this frequency the flux weakens [Hz] + // the motors + double linkVoltage = 0.0; // Uzsmax: the most voltage the inverter can give now [V] + double voltage = 0.0; // U: the voltage of the motors [V] + double flux = 0.0; // pole: the flux against the full one + double torqueCurrent = 0.0; // Ic + double fieldCurrent = 0.0; // If + double torque = 0.0; // M: of a motor + double lineCurrent = 0.0; // Ipoj: the current of the vehicle from the line [A] + double currentLimit = 0.0; // Imax: never set; shown in the debug panel + // the powers [kW] + double powerLimit = 0.0; // Pmax: the most power now, of traction or of braking + double mechanicalPower = 0.0; // Pm + double electricalPower = 0.0; // Pe + double efficiency = 0.0; // eta +}; + struct InductionMotor { + using Listing = std::array, 21>; + // the definition - std::array config; // the parameters, indexed by eimc_* (eimc before) + InductionMotorWinding motor; + InductionMotorConverter converter; + InductionMotorTraction traction; + InductionMotorBraking braking; std::map maxPowerTable; /*tablica mocy maksymalnej od predkosci*/ int inverterCount = 0; // number of inverters double inverterRatio = 0.0; @@ -38,8 +117,58 @@ struct InductionMotor bool logForce = false; // EIMCLogForce // the state - std::array state; // the values of the drive, indexed by eimv_* (eimv before) + InductionMotorState state; double forceShare = 0; /*realizowany procent dostepnej sily rozruchu/hamowania*/ double inverterFrequency{0.0}; // current frequency of power inverters std::vector inverters; // all inverters + + // the definition and the state with their labels, for the debug panel + Listing ConfigListing() const + { + return {{{"dfic: ", motor.currentPerSlip}, + {"dfmax:", motor.maxSlipFrequency}, + {"p: ", motor.polePairs}, + {"scfu: ", motor.voltsPerHertz}, + {"cim: ", motor.torquePerCurrent}, + {"icif: ", motor.fieldCurrentRatio}, + {"Uzmax:", converter.maxLinkVoltage}, + {"Uzh: ", converter.brakingLinkVoltage}, + {"DU: ", converter.voltageDrop}, + {"I0: ", converter.noLoadCurrent}, + {"fcfu: ", converter.voltsPerHertz}, + {"F0: ", traction.startingForce}, + {"a1: ", traction.forceDropPerSpeed}, + {"Pmax: ", traction.maxPower}, + {"Fh: ", braking.maxForce}, + {"Ph: ", braking.maxPower}, + {"Vh0: ", braking.offSpeed}, + {"Vh1: ", braking.fullSpeed}, + {"Imax: ", traction.maxCurrent}, + {"abed: ", braking.cylinderPressureGain}, + {"eped: ", braking.maxEpDeceleration}}}; + } + Listing StateListing() const + { + return {{{"Fkrt:", state.absoluteMaxForce}, + {"Fmax:", state.maxForce}, + {"ks: ", state.slipShare}, + {"df: ", state.slipFrequency}, + {"fp: ", state.supplyFrequency}, + {"Us: ", state.voltage}, + {"pole:", state.flux}, + {"Ic: ", state.torqueCurrent}, + {"If: ", state.fieldCurrent}, + {"M: ", state.torque}, + {"Fr: ", state.force}, + {"Ipoj:", state.lineCurrent}, + {"Pm: ", state.mechanicalPower}, + {"Pe: ", state.electricalPower}, + {"eta: ", state.efficiency}, + {"fkr: ", state.criticalFrequency}, + {"Uzsm:", state.linkVoltage}, + {"Pmax:", state.powerLimit}, + {"Fzad:", state.forceDemand}, + {"Imax:", state.currentLimit}, + {"Fful:", state.fullForce}}}; + } }; diff --git a/physics/components/traction.cpp b/physics/components/traction.cpp index 9e6f60d73..0c95bd223 100644 --- a/physics/components/traction.cpp +++ b/physics/components/traction.cpp @@ -524,8 +524,8 @@ double TMoverParameters::DynamicBrakeRatio(void) const // ************************************************************************************************* bool TMoverParameters::DynamicBrakeAvailable(void) const { - double const vh0{inductionMotor.config[eimc_p_Vh0]}; - if (double const vh1{inductionMotor.config[eimc_p_Vh1]}; vh1 <= 0.001) + double const vh0{inductionMotor.braking.offSpeed}; + if (double const vh1{inductionMotor.braking.fullSpeed}; vh1 <= 0.001) { // brak zdefiniowanej strefy - ED dziala zawsze return true; @@ -1070,7 +1070,7 @@ void TMoverParameters::InductionMotorTractionForce(double dt) inductionMotor.inverterRatio = ActiveInverters / (double)inductionMotor.inverterCount; if (inductionMotor.maxPowerTable.size() > 1) { - inductionMotor.config[eimc_p_Pmax] = TableInterpolation(inductionMotor.maxPowerTable, Vel); + inductionMotor.traction.maxPower = TableInterpolation(inductionMotor.maxPowerTable, Vel); } InductionMotorSpeedControl(dt); InductionMotorBrakeBlending(ActiveInverters, PosRatio, tmp); @@ -1195,7 +1195,7 @@ void TMoverParameters::SpeedControlByTime(double dt) void TMoverParameters::InductionMotorBrakeBlending(double const ActiveInverters, double &PosRatio, double &tmp) { InductionMotorDynamicBrakeFlag(); - auto const edBCP{Hamulec->GetEDBCP() * inductionMotor.config[eimc_p_abed]}; // stala napedu + auto const edBCP{Hamulec->GetEDBCP() * inductionMotor.braking.cylinderPressureGain}; // stala napedu if (DynamicBrakeFlag) { PosRatio = InductionMotorBrakeRatio(ActiveInverters, edBCP); @@ -1204,9 +1204,9 @@ void TMoverParameters::InductionMotorBrakeBlending(double const ActiveInverters, else { PosRatio = std::max(eimic_real, 0.); - inductionMotor.state[eimv_Fzad] = PosRatio; - if (Flat && inductionMotor.config[eimc_p_F0] * inductionMotor.state[eimv_Fful] > 0) - PosRatio = std::min(PosRatio * inductionMotor.config[eimc_p_F0] / inductionMotor.state[eimv_Fful], 1.); + inductionMotor.state.forceDemand = PosRatio; + if (Flat && inductionMotor.traction.startingForce * inductionMotor.state.fullForce > 0) + PosRatio = std::min(PosRatio * inductionMotor.traction.startingForce / inductionMotor.state.fullForce, 1.); /* if (ScndCtrlActualPos > 0) //speed control if (Vmax < 250) PosRatio = std::min(PosRatio, std::max(-1, 0.5 * (ScndCtrlActualPos - Vel))); @@ -1248,9 +1248,9 @@ double TMoverParameters::InductionMotorBrakeRatio(double const ActiveInverters, { double PosRatio; // ustalanie współczynnika blendingu do luzowania hamulca PN - if (inductionMotor.state[eimv_Fmax] * Sign(V) * DirAbsolute < -1) + if (inductionMotor.state.maxForce * Sign(V) * DirAbsolute < -1) { - PosRatio = -Sign(V) * DirAbsolute * inductionMotor.state[eimv_Fr] / (inductionMotor.config[eimc_p_Fh] * std::max(edBCP, std::max(0.01, Hamulec->GetEDBCP())) / MaxBrakePress[0]); + PosRatio = -Sign(V) * DirAbsolute * inductionMotor.state.force / (inductionMotor.braking.maxForce * std::max(edBCP, std::max(0.01, Hamulec->GetEDBCP())) / MaxBrakePress[0]); PosRatio = std::clamp(PosRatio, 0.0, 1.0); } else @@ -1262,27 +1262,27 @@ double TMoverParameters::InductionMotorBrakeRatio(double const ActiveInverters, PosRatio *= 0.9; Hamulec->SetED(std::max(0.0, std::min(PosRatio, 1.0))); // ustalenie stopnia zmniejszenia ciśnienia // ustalanie siły hamowania ED - if (Hamulec->GetEDBCP() > 0.25 && inductionMotor.config[eimc_p_abed] < 0.001 || ActiveInverters < inductionMotor.inverterCount) // jeśli PN wyłącza ED + if (Hamulec->GetEDBCP() > 0.25 && inductionMotor.braking.cylinderPressureGain < 0.001 || ActiveInverters < inductionMotor.inverterCount) // jeśli PN wyłącza ED { PosRatio = 0; - inductionMotor.state[eimv_Fzad] = 0; + inductionMotor.state.forceDemand = 0; } else { // strefa wylaczenia ED (Vh0..Vh1) - mnoznik 0..1 zaleznie od predkosci - double const vhRamp = std::max(0.0, std::min(1.0, (Vel - inductionMotor.config[eimc_p_Vh0]) / (inductionMotor.config[eimc_p_Vh1] - inductionMotor.config[eimc_p_Vh0]))); + double const vhRamp = std::max(0.0, std::min(1.0, (Vel - inductionMotor.braking.offSpeed) / (inductionMotor.braking.fullSpeed - inductionMotor.braking.offSpeed))); if (SplitEDPneumaticBrake) { // w trybie split LocalBrake nie zaleca ED; uzywany jest DynamicBrakeCtrl // oraz zwykle zapotrzebowanie z hamulca zespolonego (edBCP) double const edLeverDemand = DynamicBrakeRatio(); PosRatio = -std::max(std::max(edLeverDemand, std::min(edBCP / MaxBrakePress[0], 1.0)), AnPos) * vhRamp; - inductionMotor.state[eimv_Fzad] = -std::min(1.0, std::max(edLeverDemand, edBCP / MaxBrakePress[0])); + inductionMotor.state.forceDemand = -std::min(1.0, std::max(edLeverDemand, edBCP / MaxBrakePress[0])); } else { PosRatio = -std::max(std::min(edBCP * 1.0 / MaxBrakePress[0], 1.0), AnPos) * vhRamp; - inductionMotor.state[eimv_Fzad] = -std::min(1.0, std::max(LocalBrakeRatio(), edBCP / MaxBrakePress[0])); + inductionMotor.state.forceDemand = -std::min(1.0, std::max(LocalBrakeRatio(), edBCP / MaxBrakePress[0])); } } return PosRatio; @@ -1293,30 +1293,30 @@ void TMoverParameters::InductionMotorDrive(double dt) { double tmp; if (DynamicBrakeFlag) - tmp = inductionMotor.config[eimc_f_Uzh]; + tmp = inductionMotor.converter.brakingLinkVoltage; else - tmp = inductionMotor.config[eimc_f_Uzmax]; + tmp = inductionMotor.converter.maxLinkVoltage; - auto f_cfu{DynamicBrakeFlag ? inductionMotor.config[eimc_f_cfuH] : inductionMotor.config[eimc_f_cfu]}; + auto f_cfu{DynamicBrakeFlag ? inductionMotor.converter.brakingVoltsPerHertz : inductionMotor.converter.voltsPerHertz}; - inductionMotor.state[eimv_Uzsmax] = std::min(EngineVoltage - inductionMotor.config[eimc_f_DU], tmp); - inductionMotor.state[eimv_fkr] = inductionMotor.state[eimv_Uzsmax] / f_cfu; + inductionMotor.state.linkVoltage = std::min(EngineVoltage - inductionMotor.converter.voltageDrop, tmp); + inductionMotor.state.criticalFrequency = inductionMotor.state.linkVoltage / f_cfu; if (inductionMotor.forceShare < 0) { - inductionMotor.state[eimv_Pmax] = inductionMotor.config[eimc_p_Ph]; + inductionMotor.state.powerLimit = inductionMotor.braking.maxPower; } else { - inductionMotor.state[eimv_Pmax] = std::min(inductionMotor.config[eimc_p_Pmax], 0.001 * EngineVoltage * (inductionMotor.config[eimc_p_Imax] - inductionMotor.config[eimc_f_I0]) * Pirazy2 * inductionMotor.config[eimc_s_cim] / inductionMotor.config[eimc_s_p] / inductionMotor.config[eimc_s_cfu]); + inductionMotor.state.powerLimit = std::min(inductionMotor.traction.maxPower, 0.001 * EngineVoltage * (inductionMotor.traction.maxCurrent - inductionMotor.converter.noLoadCurrent) * Pirazy2 * inductionMotor.motor.torquePerCurrent / inductionMotor.motor.polePairs / inductionMotor.motor.voltsPerHertz); if (GensetSelected()) { // on the genset of a dual-mode vehicle the traction takes no more than the genset gives - inductionMotor.state[eimv_Pmax] = std::min(inductionMotor.state[eimv_Pmax], GensetTractionPowerLimit()); + inductionMotor.state.powerLimit = std::min(inductionMotor.state.powerLimit, GensetTractionPowerLimit()); } } - inductionMotor.state[eimv_FMAXMAX] = 0.001 * - square(std::min(1.0, inductionMotor.state[eimv_fkr] / std::max(abs(enrot) * inductionMotor.config[eimc_s_p] + inductionMotor.config[eimc_s_dfmax] * inductionMotor.state[eimv_ks], inductionMotor.config[eimc_s_dfmax])) * f_cfu / inductionMotor.config[eimc_s_cfu]) * - (inductionMotor.config[eimc_s_dfmax] * inductionMotor.config[eimc_s_dfic] * inductionMotor.config[eimc_s_cim]) * Transmision.Ratio * NPoweredAxles * 2.0 / WheelDiameter; + inductionMotor.state.absoluteMaxForce = 0.001 * + square(std::min(1.0, inductionMotor.state.criticalFrequency / std::max(abs(enrot) * inductionMotor.motor.polePairs + inductionMotor.motor.maxSlipFrequency * inductionMotor.state.slipShare, inductionMotor.motor.maxSlipFrequency)) * f_cfu / inductionMotor.motor.voltsPerHertz) * + (inductionMotor.motor.maxSlipFrequency * inductionMotor.motor.currentPerSlip * inductionMotor.motor.torquePerCurrent) * Transmision.Ratio * NPoweredAxles * 2.0 / WheelDiameter; InductionMotorForceLimits(); for (auto &inv : inductionMotor.inverters) { @@ -1324,26 +1324,26 @@ void TMoverParameters::InductionMotorDrive(double dt) inv.Error = inv.Failure_Const || (inv.Failure_Drive && inv.Request != 0); inv.IsActive = inv.Activate && !inv.Error; } - inductionMotor.state[eimv_ks] = inductionMotor.state[eimv_Fr] / inductionMotor.state[eimv_FMAXMAX]; - inductionMotor.state[eimv_df] = inductionMotor.state[eimv_ks] * inductionMotor.config[eimc_s_dfmax]; - inductionMotor.state[eimv_fp] = DirAbsolute * enrot * inductionMotor.config[eimc_s_p] + inductionMotor.state[eimv_df]; // do przemyslenia dzialanie pp z tmpV - // inductionMotor.state[eimv_U]:=std::max(inductionMotor.state[eimv_Uzsmax],std::min(inductionMotor.config[eimc_f_cfu]*inductionMotor.state[eimv_fp],inductionMotor.state[eimv_Uzsmax])); - // inductionMotor.state[eimv_pole]:=inductionMotor.state[eimv_U]/(inductionMotor.state[eimv_fp]*inductionMotor.config[eimc_s_cfu]); - if (abs(inductionMotor.state[eimv_fp]) <= inductionMotor.state[eimv_fkr]) - inductionMotor.state[eimv_pole] = f_cfu / inductionMotor.config[eimc_s_cfu]; + inductionMotor.state.slipShare = inductionMotor.state.force / inductionMotor.state.absoluteMaxForce; + inductionMotor.state.slipFrequency = inductionMotor.state.slipShare * inductionMotor.motor.maxSlipFrequency; + inductionMotor.state.supplyFrequency = DirAbsolute * enrot * inductionMotor.motor.polePairs + inductionMotor.state.slipFrequency; // do przemyslenia dzialanie pp z tmpV + // inductionMotor.state.voltage:=std::max(inductionMotor.state.linkVoltage,std::min(inductionMotor.converter.voltsPerHertz*inductionMotor.state.supplyFrequency,inductionMotor.state.linkVoltage)); + // inductionMotor.state.flux:=inductionMotor.state.voltage/(inductionMotor.state.supplyFrequency*inductionMotor.motor.voltsPerHertz); + if (abs(inductionMotor.state.supplyFrequency) <= inductionMotor.state.criticalFrequency) + inductionMotor.state.flux = f_cfu / inductionMotor.motor.voltsPerHertz; else - inductionMotor.state[eimv_pole] = inductionMotor.state[eimv_Uzsmax] / inductionMotor.config[eimc_s_cfu] / abs(inductionMotor.state[eimv_fp]); - inductionMotor.state[eimv_U] = inductionMotor.state[eimv_pole] * inductionMotor.state[eimv_fp] * inductionMotor.config[eimc_s_cfu]; - inductionMotor.state[eimv_Ic] = (inductionMotor.state[eimv_fp] - DirAbsolute * enrot * inductionMotor.config[eimc_s_p]) * inductionMotor.config[eimc_s_dfic] * inductionMotor.state[eimv_pole]; - inductionMotor.state[eimv_If] = inductionMotor.state[eimv_Ic] * inductionMotor.config[eimc_s_icif]; - inductionMotor.state[eimv_M] = inductionMotor.state[eimv_pole] * inductionMotor.state[eimv_Ic] * inductionMotor.config[eimc_s_cim]; - inductionMotor.state[eimv_Ipoj] = inductionMotor.state[eimv_Ic] * NPoweredAxles * inductionMotor.inverterRatio * inductionMotor.state[eimv_U] / (EngineVoltage - inductionMotor.config[eimc_f_DU]) + inductionMotor.config[eimc_f_I0]; - inductionMotor.state[eimv_Pm] = DirActive * inductionMotor.state[eimv_M] * NPoweredAxles * inductionMotor.inverterRatio * enrot * Pirazy2 / 1000; - inductionMotor.state[eimv_Pe] = inductionMotor.state[eimv_Ipoj] * EngineVoltage / 1000; - inductionMotor.state[eimv_eta] = inductionMotor.state[eimv_Pm] / inductionMotor.state[eimv_Pe]; + inductionMotor.state.flux = inductionMotor.state.linkVoltage / inductionMotor.motor.voltsPerHertz / abs(inductionMotor.state.supplyFrequency); + inductionMotor.state.voltage = inductionMotor.state.flux * inductionMotor.state.supplyFrequency * inductionMotor.motor.voltsPerHertz; + inductionMotor.state.torqueCurrent = (inductionMotor.state.supplyFrequency - DirAbsolute * enrot * inductionMotor.motor.polePairs) * inductionMotor.motor.currentPerSlip * inductionMotor.state.flux; + inductionMotor.state.fieldCurrent = inductionMotor.state.torqueCurrent * inductionMotor.motor.fieldCurrentRatio; + inductionMotor.state.torque = inductionMotor.state.flux * inductionMotor.state.torqueCurrent * inductionMotor.motor.torquePerCurrent; + inductionMotor.state.lineCurrent = inductionMotor.state.torqueCurrent * NPoweredAxles * inductionMotor.inverterRatio * inductionMotor.state.voltage / (EngineVoltage - inductionMotor.converter.voltageDrop) + inductionMotor.converter.noLoadCurrent; + inductionMotor.state.mechanicalPower = DirActive * inductionMotor.state.torque * NPoweredAxles * inductionMotor.inverterRatio * enrot * Pirazy2 / 1000; + inductionMotor.state.electricalPower = inductionMotor.state.lineCurrent * EngineVoltage / 1000; + inductionMotor.state.efficiency = inductionMotor.state.mechanicalPower / inductionMotor.state.electricalPower; - Im = inductionMotor.state[eimv_If]; - if (inductionMotor.state[eimv_Ipoj] >= 0) + Im = inductionMotor.state.fieldCurrent; + if (inductionMotor.state.lineCurrent >= 0) Vadd *= 1.0 - 2.0 * dt; else if (GensetSelected()) Vadd = 1.0; // the genset of a dual-mode vehicle takes nothing back: all the braking energy to the resistors @@ -1351,17 +1351,17 @@ void TMoverParameters::InductionMotorDrive(double dt) Vadd *= 1.0 - dt; else Vadd = std::max(Vadd * (1.0 - 0.2 * dt), 0.007 * (std::abs(EngineVoltage) - (EnginePowerSource.CollectorParameters.MaxV - 100))); - Itot = inductionMotor.state[eimv_Ipoj] * (0.01 + std::min(0.99, 0.99 - Vadd)); + Itot = inductionMotor.state.lineCurrent * (0.01 + std::min(0.99, 0.99 - Vadd)); - EnginePower = abs(inductionMotor.state[eimv_Ic] * inductionMotor.state[eimv_U] * NPoweredAxles) / 1000; + EnginePower = abs(inductionMotor.state.torqueCurrent * inductionMotor.state.voltage * NPoweredAxles) / 1000; // power inverters UpdateInverterFrequency(); - Mm = inductionMotor.state[eimv_M] * DirAbsolute; + Mm = inductionMotor.state.torque * DirAbsolute; Mw = Mm * Transmision.Ratio * Transmision.Efficiency; Fw = Mw * 2.0 / WheelDiameter; Ft = Fw * NPoweredAxles * inductionMotor.inverterRatio; - inductionMotor.state[eimv_Fr] = DirAbsolute * Ft / 1000; + inductionMotor.state.force = DirAbsolute * Ft / 1000; } // the force the motors give at full and at the setting (inductionMotor.forceShare), braking within the power and the force of the @@ -1370,38 +1370,38 @@ void TMoverParameters::InductionMotorForceLimits() { if (inductionMotor.forceShare < 0) { - inductionMotor.state[eimv_Fful] = std::min(inductionMotor.config[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(inductionMotor.config[eimc_p_Fh], inductionMotor.state[eimv_FMAXMAX])); - inductionMotor.state[eimv_Fmax] = -Sign(V) * DirAbsolute*std::min(inductionMotor.config[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-inductionMotor.config[eimc_p_Fh] * inductionMotor.forceShare, inductionMotor.state[eimv_FMAXMAX])); + inductionMotor.state.fullForce = std::min(inductionMotor.braking.maxPower * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(inductionMotor.braking.maxForce, inductionMotor.state.absoluteMaxForce)); + inductionMotor.state.maxForce = -Sign(V) * DirAbsolute*std::min(inductionMotor.braking.maxPower * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-inductionMotor.braking.maxForce * inductionMotor.forceShare, inductionMotor.state.absoluteMaxForce)); double pr = inductionMotor.forceShare; if (inductionMotor.logForce) pr = -log(1 - 4 * pr) / log(5); - inductionMotor.state[eimv_Fr] = -Sign(V) * DirAbsolute*std::min(inductionMotor.config[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-inductionMotor.config[eimc_p_Fh] * pr, inductionMotor.state[eimv_FMAXMAX])); + inductionMotor.state.force = -Sign(V) * DirAbsolute*std::min(inductionMotor.braking.maxPower * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-inductionMotor.braking.maxForce * pr, inductionMotor.state.absoluteMaxForce)); if (inductionMotor.inverterRatio < 1.0) - inductionMotor.state[eimv_Fful] = 0; - //*std::min(1,(Vel-inductionMotor.config[eimc_p_Vh0])/(inductionMotor.config[eimc_p_Vh1]-inductionMotor.config[eimc_p_Vh0])) + inductionMotor.state.fullForce = 0; + //*std::min(1,(Vel-inductionMotor.braking.offSpeed)/(inductionMotor.braking.fullSpeed-inductionMotor.braking.offSpeed)) } else { - inductionMotor.state[eimv_Fful] = std::min(std::min(3.6 * inductionMotor.state[eimv_Pmax] / std::max(Vel, 1.), inductionMotor.config[eimc_p_F0] - Vel * inductionMotor.config[eimc_p_a1]), inductionMotor.state[eimv_FMAXMAX]); + inductionMotor.state.fullForce = std::min(std::min(3.6 * inductionMotor.state.powerLimit / std::max(Vel, 1.), inductionMotor.traction.startingForce - Vel * inductionMotor.traction.forceDropPerSpeed), inductionMotor.state.absoluteMaxForce); // if(not Flat)then - inductionMotor.state[eimv_Fmax] = inductionMotor.state[eimv_Fful] * inductionMotor.forceShare; + inductionMotor.state.maxForce = inductionMotor.state.fullForce * inductionMotor.forceShare; // else - // inductionMotor.state[eimv_Fmax]:=std::min(inductionMotor.config[eimc_p_F0]*inductionMotor.forceShare,inductionMotor.state[eimv_Fful]); + // inductionMotor.state.maxForce:=std::min(inductionMotor.traction.startingForce*inductionMotor.forceShare,inductionMotor.state.fullForce); double pr = inductionMotor.forceShare; if (inductionMotor.logForce) pr = log(1 + 4 * pr) / log(5); - inductionMotor.state[eimv_Fr] = inductionMotor.state[eimv_Fful] * pr; + inductionMotor.state.force = inductionMotor.state.fullForce * pr; } } // the frequency of the inverters at the motors' slip frequency, from the list of the drive or of its brake void TMoverParameters::UpdateInverterFrequency() { - auto const tmpV{std::abs(inductionMotor.state[eimv_fp])}; + auto const tmpV{std::abs(inductionMotor.state.supplyFrequency)}; auto const useFFEDList = FFEDListSize > 0 && DynamicBrakeFlag; auto const list = useFFEDList ? FFEDlist : FFlist; - if (auto const listSize = useFFEDList ? FFEDListSize : FFListSize; listSize > 0 && std::abs(inductionMotor.state[eimv_If]) > 1.0 && tmpV > 0.0001) + if (auto const listSize = useFFEDList ? FFEDListSize : FFListSize; listSize > 0 && std::abs(inductionMotor.state.fieldCurrent) > 1.0 && tmpV > 0.0001) { int i = 0; @@ -1434,8 +1434,7 @@ void TMoverParameters::InductionMotorOff() inductionMotor.forceShare = 0.0; EnginePower = 0.0; { - for (auto &eimvvalue : inductionMotor.state) - eimvvalue = 0.0; + inductionMotor.state = {}; } Hamulec->SetED(0.0); inductionMotor.inverterFrequency = 0.0; //(Hamulec as TLSt).SetLBP(LocBrakePress); diff --git a/physics/mover.h b/physics/mover.h index 64a555d23..dba810ef7 100644 --- a/physics/mover.h +++ b/physics/mover.h @@ -1148,7 +1148,6 @@ class TMoverParameters /*- dla lokomotyw z silnikami indukcyjnymi -*/ // the drive of induction motors (physics/components/inductionmotor.h) InductionMotor inductionMotor; - static std::vector const eimc_labels; int Imaxrpc = 0; // Maksymalny prad rezystora hamowania chlodzonego pasywnie int BRVto = 0; // Czas jaki wentylatory jeszcze dodatkowo schladzaja rezystor double BRVtimer = 0; // Timer dla podtrzymania wentylatora @@ -1480,7 +1479,6 @@ class TMoverParameters bool EIMCtrlAdditionalZeros = false; /*czy ma dodatkowe zero jazdy i zero hamowania */ bool EIMCtrlEmergency = false; /*czy ma dodatkowe zero jazdy i zero hamowania */ bool EIMCtrlMainEmergency = false; /*czy zadajnik typu 2 (Elf) ma pozycje hamowania naglego ponizej swojej pozycji 0*/ - static std::vector const eimv_labels; double SpeedCtrlTimer = 0; /*zegar dzialania tempomatu z wybieralna predkoscia*/ double eimicSpeedCtrl = 1; /*pozycja sugerowana przez tempomat*/ double eimicSpeedCtrlIntegral = 0; /*calkowany blad ustawienia predkosci*/ @@ -1670,7 +1668,7 @@ class TMoverParameters bool EIMDirectionChangeAllow(void) const; inline double IsVehicleEIMBrakingFactor() const { - return DynamicBrakeFlag && ResistorsFlag ? 0.0 : inductionMotor.state[eimv_Ipoj] < 0 ? -1.0 : 1.0; + return DynamicBrakeFlag && ResistorsFlag ? 0.0 : inductionMotor.state.lineCurrent < 0 ? -1.0 : 1.0; } void BrakeLevelSet(double b); bool BrakeLevelAdd(double b); diff --git a/physics/vehicletypes.h b/physics/vehicletypes.h index d61ad32b1..3e133b0f7 100644 --- a/physics/vehicletypes.h +++ b/physics/vehicletypes.h @@ -421,96 +421,6 @@ enum class train_type skoda181, }; -// stałe dla asynchronów -/// EIM config index: dfic — frequency rise rate at start. -static int const eimc_s_dfic = 0; -/// EIM config index: dfmax — maximum frequency rate of change. -static int const eimc_s_dfmax = 1; -/// EIM config index: p — number of pole pairs. -static int const eimc_s_p = 2; -/// EIM config index: cfu — voltage / frequency conversion coefficient. -static int const eimc_s_cfu = 3; -/// EIM config index: cim — current / current conversion coefficient. -static int const eimc_s_cim = 4; -/// EIM config index: icif — magnetisation current ratio. -static int const eimc_s_icif = 5; -/// EIM config index: Uzmax — maximum DC link voltage. -static int const eimc_f_Uzmax = 7; -/// EIM config index: Uzh — DC link voltage at field-weakening transition. -static int const eimc_f_Uzh = 8; -/// EIM config index: DU — voltage drop at the converter. -static int const eimc_f_DU = 9; -/// EIM config index: I0 — no-load magnetising current. -static int const eimc_f_I0 = 10; -/// EIM config index: cfu — V/f gain in normal mode. -static int const eimc_f_cfu = 11; -/// EIM config index: cfuH — V/f gain in field-weakening region. -static int const eimc_f_cfuH = 12; -/// EIM config index: F0 — starting force at zero speed. -static int const eimc_p_F0 = 13; -/// EIM config index: a1 — force-frequency slope coefficient. -static int const eimc_p_a1 = 14; -/// EIM config index: Pmax — maximum power. -static int const eimc_p_Pmax = 15; -/// EIM config index: Fh — force at field-weakening point. -static int const eimc_p_Fh = 16; -/// EIM config index: Ph — power at field-weakening point. -static int const eimc_p_Ph = 17; -/// EIM config index: Vh0 — speed where field weakening begins. -static int const eimc_p_Vh0 = 18; -/// EIM config index: Vh1 — speed of full field weakening. -static int const eimc_p_Vh1 = 19; -/// EIM config index: Imax — maximum motor current. -static int const eimc_p_Imax = 20; -/// EIM config index: abed — anti-skid set point. -static int const eimc_p_abed = 21; -/// EIM config index: eped — EP brake intensity bias. -static int const eimc_p_eped = 22; - -// zmienne dla asynchronów -/// EIM variable index: FMAXMAX — absolute maximum allowable force. -static int const eimv_FMAXMAX = 0; -/// EIM variable index: Fmax — current force limit. -static int const eimv_Fmax = 1; -/// EIM variable index: ks — slip coefficient. -static int const eimv_ks = 2; -/// EIM variable index: df — frequency offset. -static int const eimv_df = 3; -/// EIM variable index: fp — base frequency. -static int const eimv_fp = 4; -/// EIM variable index: U — applied voltage. -static int const eimv_U = 5; -/// EIM variable index: pole — pole-pair indicator. -static int const eimv_pole = 6; -/// EIM variable index: Ic — control current. -static int const eimv_Ic = 7; -/// EIM variable index: If — field current. -static int const eimv_If = 8; -/// EIM variable index: M — torque. -static int const eimv_M = 9; -/// EIM variable index: Fr — actual force. -static int const eimv_Fr = 10; -/// EIM variable index: Ipoj — line current. -static int const eimv_Ipoj = 11; -/// EIM variable index: Pm — mechanical power. -static int const eimv_Pm = 12; -/// EIM variable index: Pe — electrical power. -static int const eimv_Pe = 13; -/// EIM variable index: eta — efficiency. -static int const eimv_eta = 14; -/// EIM variable index: fkr — critical frequency. -static int const eimv_fkr = 15; -/// EIM variable index: Uzsmax — maximum measured DC link voltage. -static int const eimv_Uzsmax = 16; -/// EIM variable index: Pmax — instantaneous power limit. -static int const eimv_Pmax = 17; -/// EIM variable index: Fzad — set-point force. -static int const eimv_Fzad = 18; -/// EIM variable index: Imax — maximum allowed current. -static int const eimv_Imax = 19; -/// EIM variable index: Fful — full force. -static int const eimv_Fful = 20; - /// Brake-of-mode flag: PS (pneumatic, primary). static int const bom_PS = 1; /// Brake-of-mode flag: PN (pneumatic, no electrodynamic). diff --git a/tests/unit/test_definition.cpp b/tests/unit/test_definition.cpp index 518f9b73f..e9a79d9e4 100644 --- a/tests/unit/test_definition.cpp +++ b/tests/unit/test_definition.cpp @@ -122,7 +122,7 @@ TEST_CASE("definition: the compressor's limits set apart for the rear cab") { } TEST_CASE("definition: the highest power of an induction motor drive by the speed (PmaxList)") { - // the drive's power limit (eimc_p_Pmax) follows the table, between its rows and, by the last two, past its end + // the drive's power limit (traction.maxPower) follows the table, between its rows and, by the last two, past its end auto eu47{definition::fiz("e186_v2/eu47").set("PmaxList", "Size", 3).set("PmaxList", "rows", {{0, 1000}, {50, 3000}, {100, 5600}})}; auto const table{[](double Speed) { return Speed < 50.0 ? 1000.0 + 40.0 * Speed : 3000.0 + 52.0 * (Speed - 50.0); }}; for (auto const speed : {25.0, 75.0, 150.0}) { @@ -131,7 +131,7 @@ TEST_CASE("definition: the highest power of an induction motor drive by the spee auto driven{test::driving(real)}; test::track const line{0.0, 0.0, test::catenary_3kv}; REQUIRE(test::start_up(driven, line)); - CHECK(real->inductionMotor.config[eimc_p_Pmax] == doctest::Approx(table(real->Vel)).epsilon(0.01)); + CHECK(real->inductionMotor.traction.maxPower == doctest::Approx(table(real->Vel)).epsilon(0.01)); } } diff --git a/tests/unit/test_elf_controller.cpp b/tests/unit/test_elf_controller.cpp index 138689f68..d099c3303 100644 --- a/tests/unit/test_elf_controller.cpp +++ b/tests/unit/test_elf_controller.cpp @@ -530,7 +530,7 @@ TEST_CASE("elf holding brake: the force of the motors at 1% against the holding unit.wait(5.0); auto const holding{cab.StopBrakeDecc * mass}; MESSAGE("mass " << mass << " kg, holding " << holding << " N, cars with motors " << powered << ", demand " << cab.eimic_real << ", cab car Ft " << cab.Ft - << " N, Fful " << cab.inductionMotor.state[eimv_Fful] << " kN, speed " << cab.Vel << " km/h after 5 s"); + << " N, Fful " << cab.inductionMotor.state.fullForce << " kN, speed " << cab.Vel << " km/h after 5 s"); CHECK(cab.eimic_real == doctest::Approx(0.01).epsilon(0.02)); CHECK(cab.Ft * powered < 0.1 * holding); } diff --git a/tests/unit/test_fcfuh_default.cpp b/tests/unit/test_fcfuh_default.cpp index e86f29e7b..f52a7cdd5 100644 --- a/tests/unit/test_fcfuh_default.cpp +++ b/tests/unit/test_fcfuh_default.cpp @@ -142,12 +142,12 @@ TEST_CASE("fcfuH: the loader gives the dynamic brake the traction's figure when CAPTURE(fcfu); // the EU47's definition has fcfu only vehicle eu47{definition::fiz("e186_v2/eu47").set("Engine", "fcfu", fcfu)}; - CHECK(eu47->inductionMotor.config[eimc_f_cfu] == read_fcfu(fcfu)); - CHECK(bits(eu47->inductionMotor.config[eimc_f_cfuH]) == bits(eu47->inductionMotor.config[eimc_f_cfu])); - CHECK(bits(eu47->inductionMotor.config[eimc_f_cfuH]) == bits(fcfuh_before(read_fcfu(fcfu)))); + CHECK(eu47->inductionMotor.converter.voltsPerHertz == read_fcfu(fcfu)); + CHECK(bits(eu47->inductionMotor.converter.brakingVoltsPerHertz) == bits(eu47->inductionMotor.converter.voltsPerHertz)); + CHECK(bits(eu47->inductionMotor.converter.brakingVoltsPerHertz) == bits(fcfuh_before(read_fcfu(fcfu)))); // its own figure is kept vehicle own{definition::fiz("e186_v2/eu47").set("Engine", "fcfu", fcfu).set("Engine", "fcfuH", "40.1")}; - CHECK(own->inductionMotor.config[eimc_f_cfu] == read_fcfu(fcfu)); - CHECK(own->inductionMotor.config[eimc_f_cfuH] == read_fcfu("40.1")); + CHECK(own->inductionMotor.converter.voltsPerHertz == read_fcfu(fcfu)); + CHECK(own->inductionMotor.converter.brakingVoltsPerHertz == read_fcfu("40.1")); } } diff --git a/tests/unit/test_genset.cpp b/tests/unit/test_genset.cpp index cba96800f..cb39e532d 100644 --- a/tests/unit/test_genset.cpp +++ b/tests/unit/test_genset.cpp @@ -492,7 +492,7 @@ braking brake_from_60(vehicle &Dragon, track const &Track) { for (auto step_count = 0L; step_count < 2000; ++step_count) { step(Dragon, step_count, Track); result.lowest_current = std::min(result.lowest_current, cab.Itot); - result.electrodynamic |= cab.inductionMotor.forceShare < 0.0 && cab.inductionMotor.state[eimv_Ipoj] < 0.0; + result.electrodynamic |= cab.inductionMotor.forceShare < 0.0 && cab.inductionMotor.state.lineCurrent < 0.0; } result.speed_lost = speed - cab.Vel; return result; diff --git a/vehicle/cab/equipmentcommands.cpp b/vehicle/cab/equipmentcommands.cpp index a7c232c01..38c90754d 100644 --- a/vehicle/cab/equipmentcommands.cpp +++ b/vehicle/cab/equipmentcommands.cpp @@ -417,7 +417,7 @@ void TTrain::OnCommand_inverterenable(TTrain *Train, command_data const &Command TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); while (p) { - if (p->MoverParameters->inductionMotor.config[eimc_p_Pmax] > 1) + if (p->MoverParameters->inductionMotor.traction.maxPower > 1) { if (itemindex < p->MoverParameters->inductionMotor.inverterCount) { @@ -456,7 +456,7 @@ void TTrain::OnCommand_inverterdisable(TTrain *Train, command_data const &Comman TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); while (p) { - if (p->MoverParameters->inductionMotor.config[eimc_p_Pmax] > 1) + if (p->MoverParameters->inductionMotor.traction.maxPower > 1) { if (itemindex < p->MoverParameters->inductionMotor.inverterCount) { @@ -495,7 +495,7 @@ void TTrain::OnCommand_invertertoggle(TTrain *Train, command_data const &Command TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); while (p) { - if (p->MoverParameters->inductionMotor.config[eimc_p_Pmax] > 1) + if (p->MoverParameters->inductionMotor.traction.maxPower > 1) { if (itemindex < p->MoverParameters->inductionMotor.inverterCount) { diff --git a/vehicle/cab/setup.cpp b/vehicle/cab/setup.cpp index 80ffd7fe6..3af70a82e 100644 --- a/vehicle/cab/setup.cpp +++ b/vehicle/cab/setup.cpp @@ -1184,7 +1184,7 @@ void TTrain::set_cab_controls(int const Cab) TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); while (p) { - if (p->MoverParameters->inductionMotor.config[eimc_p_Pmax] > 1) + if (p->MoverParameters->inductionMotor.traction.maxPower > 1) { if (itemindex < p->MoverParameters->inductionMotor.inverterCount) { diff --git a/vehicle/cab/train.cpp b/vehicle/cab/train.cpp index 2bdb38b0b..9920635bb 100644 --- a/vehicle/cab/train.cpp +++ b/vehicle/cab/train.cpp @@ -319,7 +319,7 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const int in = 0; while (p && in < 8) { - if (p->MoverParameters->inductionMotor.config[eimc_p_Pmax] > 1) + if (p->MoverParameters->inductionMotor.traction.maxPower > 1) { in++; dict->insert("eimp_c" + std::to_string(in) + "_invno", p->MoverParameters->inductionMotor.inverterCount); diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index 1f883ea4d..1639801b5 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -349,17 +349,17 @@ bool TTrain::Update(double const Deltatime) bCompressors.emplace_back(p->MoverParameters->CompressorAllow || p->MoverParameters->CompressorStart == start_t::automatic, p->MoverParameters->CompressorFlag, i); } bSlip[i] = p->MoverParameters->SlippingWheels; - if (in < 8 && p->MoverParameters->inductionMotor.config[eimc_p_Pmax] > 1) + if (in < 8 && p->MoverParameters->inductionMotor.traction.maxPower > 1) { - fEIMParams[1 + in][0] = static_cast(p->MoverParameters->inductionMotor.state[eimv_Fmax]); + fEIMParams[1 + in][0] = static_cast(p->MoverParameters->inductionMotor.state.maxForce); fEIMParams[1 + in][1] = std::max(fEIMParams[1 + in][0], 0.f); fEIMParams[1 + in][2] = -std::min(fEIMParams[1 + in][0], 0.f); - fEIMParams[1 + in][3] = static_cast(p->MoverParameters->inductionMotor.state[eimv_Fmax] / std::max(p->MoverParameters->inductionMotor.state[eimv_Fful], 1.)); + fEIMParams[1 + in][3] = static_cast(p->MoverParameters->inductionMotor.state.maxForce / std::max(p->MoverParameters->inductionMotor.state.fullForce, 1.)); fEIMParams[1 + in][4] = std::max(fEIMParams[1 + in][3], 0.f); fEIMParams[1 + in][5] = -std::min(fEIMParams[1 + in][3], 0.f); - fEIMParams[1 + in][6] = static_cast(p->MoverParameters->inductionMotor.state[eimv_If]); - fEIMParams[1 + in][7] = static_cast(p->MoverParameters->inductionMotor.state[eimv_U]); - fEIMParams[1 + in][8] = static_cast(p->MoverParameters->Itot); // p->MoverParameters->inductionMotor.state[eimv_Ipoj]; + fEIMParams[1 + in][6] = static_cast(p->MoverParameters->inductionMotor.state.fieldCurrent); + fEIMParams[1 + in][7] = static_cast(p->MoverParameters->inductionMotor.state.voltage); + fEIMParams[1 + in][8] = static_cast(p->MoverParameters->Itot); // p->MoverParameters->inductionMotor.state.lineCurrent; fEIMParams[1 + in][9] = static_cast(p->MoverParameters->EngineVoltage); fEIMParams[0][6] += fEIMParams[1 + in][8]; bMains[in] = p->MoverParameters->Mains; @@ -422,15 +422,15 @@ bool TTrain::Update(double const Deltatime) } // if (mvControlled == mvOccupied) - // fEIMParams[0][3] = mvControlled->inductionMotor.state[eimv_Fzad]; // procent zadany + // fEIMParams[0][3] = mvControlled->inductionMotor.state.forceDemand; // procent zadany // else // fEIMParams[0][3] = - // mvControlled->inductionMotor.state[eimv_Fzad] - mvOccupied->LocalBrakeRatio(); // procent zadany + // mvControlled->inductionMotor.state.forceDemand - mvOccupied->LocalBrakeRatio(); // procent zadany fEIMParams[0][3] = static_cast(mvOccupied->eimic_real); fEIMParams[0][4] = std::max(fEIMParams[0][3], 0.f); fEIMParams[0][5] = -std::min(fEIMParams[0][3], 0.f); - fEIMParams[0][1] = static_cast(fEIMParams[0][4] * mvControlled->inductionMotor.state[eimv_Fful]); - fEIMParams[0][2] = static_cast(fEIMParams[0][5] * mvControlled->inductionMotor.state[eimv_Fful]); + fEIMParams[0][1] = static_cast(fEIMParams[0][4] * mvControlled->inductionMotor.state.fullForce); + fEIMParams[0][2] = static_cast(fEIMParams[0][5] * mvControlled->inductionMotor.state.fullForce); fEIMParams[0][0] = fEIMParams[0][1] - fEIMParams[0][2]; fEIMParams[0][7] = 0; fEIMParams[0][8] = 0; diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index 9fd5df13d..03057e4f8 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -294,16 +294,16 @@ bool TDynamicObject::Update(double dt, double dt1) p->MoverParameters->MED_Vref) * 1000; // sila hamowania pn FmaxED += p->MoverParameters->Mains && p->MoverParameters->DirActive != 0 && p->MoverParameters->inductionMotor.inverterRatio == 1.0 && - p->MoverParameters->inductionMotor.config[eimc_p_Fh] * p->MoverParameters->NPoweredAxles > 0 ? - p->MoverParameters->inductionMotor.config[eimc_p_Fh] * 1000 : + p->MoverParameters->inductionMotor.braking.maxForce * p->MoverParameters->NPoweredAxles > 0 ? + p->MoverParameters->inductionMotor.braking.maxForce * 1000 : 0; // chwilowy max ED -> do rozdzialu sil - FED -= std::min(p->MoverParameters->inductionMotor.state[eimv_Fmax], 0.0) * + FED -= std::min(p->MoverParameters->inductionMotor.state.maxForce, 0.0) * 1000; // chwilowy max ED -> do rozdzialu sil - FfulED = std::min(p->MoverParameters->inductionMotor.state[eimv_Fful], 0.0) * + FfulED = std::min(p->MoverParameters->inductionMotor.state.fullForce, 0.0) * 1000; // chwilowy max ED -> do rozdzialu sil - FrED -= std::min(p->MoverParameters->inductionMotor.state[eimv_Fmax], 0.0) * + FrED -= std::min(p->MoverParameters->inductionMotor.state.maxForce, 0.0) * 1000; // chwilowo realizowane ED -> do pneumatyki - Frj += std::max(p->MoverParameters->inductionMotor.state[eimv_Fmax], 0.0) * + Frj += std::max(p->MoverParameters->inductionMotor.state.maxForce, 0.0) * 1000;// chwilowo realizowany napęd -> do utrzymującego masa += p->MoverParameters->TotalMass; osie += p->MoverParameters->NAxles; @@ -341,11 +341,11 @@ bool TDynamicObject::Update(double dt, double dt1) } auto Fzad = amax * LBR * masa; if ((MoverParameters->BrakeCtrlPos == MoverParameters->Handle->GetPos(bh_EB) - && MoverParameters->inductionMotor.config[eimc_p_abed] < 0.001) || + && MoverParameters->inductionMotor.braking.cylinderPressureGain < 0.001) || MoverParameters->EmergencyValveFlow > 0) Fzad = amax * masa; //pętla bezpieczeństwa - pełne służbowe if (MoverParameters->ScndS && - MoverParameters->Vel > MoverParameters->inductionMotor.config[eimc_p_Vh1] && FmaxED > 0) + MoverParameters->Vel > MoverParameters->inductionMotor.braking.fullSpeed && FmaxED > 0) { Fzad = std::min(LBR * FmaxED, FfulED); } @@ -403,7 +403,7 @@ bool TDynamicObject::Update(double dt, double dt1) } } if (MoverParameters->BrakeCtrlPos == MoverParameters->Handle->GetPos(bh_EB) - && MoverParameters->inductionMotor.config[eimc_p_abed] < 0.001) + && MoverParameters->inductionMotor.braking.cylinderPressureGain < 0.001) FzadED = 0; //pętla bezpieczeństwa - bez ED auto const FzadPN = Fzad - FrED * MoverParameters->MED_FrED_factor; std::vector PrzekrF( np ); @@ -458,13 +458,13 @@ bool TDynamicObject::Update(double dt, double dt1) p = kier == true ? p->Next(Coupling::control) : p->Prev(Coupling::control) ) { if (FzEP[i] > 0.01 && - FzEP[i] > p->MoverParameters->TotalMass * p->MoverParameters->inductionMotor.config[eimc_p_eped] + std::min(p->MoverParameters->inductionMotor.state[eimv_Fmax], 0.) * 1000 && + FzEP[i] > p->MoverParameters->TotalMass * p->MoverParameters->inductionMotor.braking.maxEpDeceleration + std::min(p->MoverParameters->inductionMotor.state.maxForce, 0.) * 1000 && !PrzekrF[i]) { - float przek1 = -std::min(p->MoverParameters->inductionMotor.state[eimv_Fmax], 0.) * 1000 + + float przek1 = -std::min(p->MoverParameters->inductionMotor.state.maxForce, 0.) * 1000 + FzEP[i] - p->MoverParameters->TotalMass * - p->MoverParameters->inductionMotor.config[eimc_p_eped] * 0.999; + p->MoverParameters->inductionMotor.braking.maxEpDeceleration * 0.999; PrzekrF[i] = true; test = true; nPrzekrF++; From 4679201cb92149a1d6dd6d8817eeffa19e454e63 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sat, 28 Nov 2026 17:02:37 +0100 Subject: [PATCH 023/123] refactor(physics): the line breaker, the voltage relays and the engine step in the drives Four more switches on EngineType go into the classes of the drives: - TractionDrive::MainsPowerAvailable(): whether the line breaker has the power to close; the low voltage circuits for the diesel engines and Dumb, the line (or the low voltage, closed ahead of the pantographs) for the series and the induction motors, always for the others (from MainSwitchCheck()) - TractionDrive::CheckVoltageRelays(): the undervoltage and the overvoltage relay of the series motors, the line voltage out of range of the induction motors, the line contactors of the diesel-electric (the body of VoltageRelaysCheck()) - TractionDrive::UpdateEngine(): the automatic start of the series motors, the step of the diesel engine; returns whether a relay clicked (from compute_movement_()) - TractionDrive::UpdateEngineVoltage(): the voltage of the motors, by the reverser for the series motors, which also count the time since their last relay, from the traction supply for the others (from ComputeTotalForce()) The reading of the Engine and MotorParamTable sections of the .fiz still switches on the engine type: it fills private members of the loader, and stays with it. No change in behaviour: 1144/1144 tests, golden traces exact against staging 62f7a29b. --- physics/components/body.cpp | 32 ++------- physics/components/drive.cpp | 112 +++++++++++++++++++++++++++++++ physics/components/drive.h | 9 +++ physics/components/electrics.cpp | 26 +------ physics/components/traction.cpp | 53 +-------------- 5 files changed, 128 insertions(+), 104 deletions(-) diff --git a/physics/components/body.cpp b/physics/components/body.cpp index aeb604f34..c91910ad2 100644 --- a/physics/components/body.cpp +++ b/physics/components/body.cpp @@ -28,6 +28,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include "physics/components/internal.h" +#include "physics/components/drive.h" int DirPatch(int Coupler1, int Coupler2) @@ -453,13 +454,8 @@ void TMoverParameters::compute_movement_(double const Deltatime) // the master controller set directly, not through IncMainCtrl()/DecMainCtrl() (AI, consist): the locked shunt follows it as well ScndCtrlResistiveLockCheck(); - // automatyczny rozruch - if (EngineType == TEngineType::ElectricSeriesMotor && AutoRelayCheck()) - { - SetFlag(SoundFlag, sound::relay); - } - - if ((EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric) && dizel_Update(Deltatime)) + // automatyczny rozruch, silnik spalinowy + if (Drive().UpdateEngine(*this, Deltatime)) { SetFlag(SoundFlag, sound::relay); } @@ -855,27 +851,7 @@ void TMoverParameters::ComputeTotalForce(double dt) // w charakterystykach jest wartość siły hamowania zamiast nacisku LastSwitchingTime += dt; - if (EngineType == TEngineType::ElectricSeriesMotor) - { - LastRelayTime += dt; - } - - if (EngineType == TEngineType::ElectricSeriesMotor) // potem ulepszyc! pantogtrafy! - { // Ra 2014-03: uwzględnienie kierunku jazdy w napięciu na silnikach, a powinien być zdefiniowany nawrotnik - EngineVoltage = Mains ? EnginePowerSourceVoltage() : 0.0; - if (CabActive == 0) - { - EngineVoltage *= DirActive; - } - else - { - EngineVoltage *= DirAbsolute; // the reverser of the active cab, relative to the couplers - } - } // bo nie dzialalo - else - { - EngineVoltage = Power > 1.0 ? TractionSupplyVoltage() : 0.0; - } + Drive().UpdateEngineVoltage(*this, dt); FTrain = Power > 0 ? TractionForce(dt) : 0; double FT_factor = 1.0; diff --git a/physics/components/drive.cpp b/physics/components/drive.cpp index 323d2c044..2b24c0d6e 100644 --- a/physics/components/drive.cpp +++ b/physics/components/drive.cpp @@ -82,6 +82,26 @@ bool TractionDrive::DecreaseMainController(TMoverParameters & /*vehicle*/, int / return false; } +bool TractionDrive::MainsPowerAvailable(TMoverParameters const & /*vehicle*/) const +{ + return true; +} + +void TractionDrive::CheckVoltageRelays(TMoverParameters & /*vehicle*/) const +{ + // no voltage relays +} + +bool TractionDrive::UpdateEngine(TMoverParameters & /*vehicle*/, double /*dt*/) const +{ + return false; +} + +void TractionDrive::UpdateEngineVoltage(TMoverParameters &vehicle, double /*dt*/) const +{ + vehicle.EngineVoltage = vehicle.Power > 1.0 ? vehicle.TractionSupplyVoltage() : 0.0; +} + namespace { @@ -101,6 +121,13 @@ void updateRadiatorFans(TMoverParameters &vehicle, double const dt) } } +// the line breaker of the drives fed from the line: closed ahead of the pantographs it runs on the low voltage circuits, +// else it needs the voltage of the source +bool linePowerAvailable(TMoverParameters const &vehicle) +{ + return vehicle.PantographsRequireMains ? vehicle.Power24vIsAvailable || vehicle.Power110vIsAvailable : vehicle.EnginePowerSourceVoltage() > 0.5 * vehicle.EnginePowerSource.MaxVoltage; +} + // a notch of the master controller of the drives without steps of their own (no engine, Dumb, diesel-electric, // induction): one position at a time, the speed control let go when the position leaves the one it holds bool increaseNotch(TMoverParameters &vehicle, int const speed) @@ -170,6 +197,10 @@ public: { vehicle.DumbTractionForce(step.posRatio); } + bool MainsPowerAvailable(TMoverParameters const &vehicle) const override + { + return vehicle.Power24vIsAvailable; + } bool IncreaseMainController(TMoverParameters &vehicle, int const speed) const override { return increaseNotch(vehicle, speed); @@ -221,6 +252,48 @@ public: vehicle.RventRot *= std::max(0.0, 1.0 - vehicle.RVentSpeed * dt); } } + bool MainsPowerAvailable(TMoverParameters const &vehicle) const override + { + return linePowerAvailable(vehicle); + } + void CheckVoltageRelays(TMoverParameters &vehicle) const override + { + // update the state of voltage relays + auto const voltage{std::max(vehicle.GetTrainsetHighVoltage(), vehicle.PantographVoltage)}; + // where the line breaker holds without voltage (closed ahead of the pantographs) the undervoltage relay opens the + // line contactors instead, see MotorConnectorsCheck(). it picks up again only with the master controller back + // where a start begins, as the line breaker it stands in for wouldn't close on a running position either: at + // zero, or at the first position, which is the first resistance step, where the line contactors close on any + // start, and where the AI waits for them rather than going back to zero + auto const novoltrelaypicksup{false == vehicle.PantographsRequireMains || vehicle.NoVoltRelay || vehicle.MainCtrlPowerPos() <= 1}; + auto const &source{vehicle.EnginePowerSource}; + vehicle.NoVoltRelay = source.SourceType != TPowerSource::CurrentCollector || (voltage >= source.CollectorParameters.MinV && novoltrelaypicksup); + vehicle.OvervoltageRelay = source.SourceType != TPowerSource::CurrentCollector || voltage <= source.CollectorParameters.MaxV || false == source.CollectorParameters.OVP; + // wywalanie szybkiego z powodu niewłaściwego napięcia + // (a line breaker closed ahead of the pantographs holds without voltage) + vehicle.EventFlag |= true == vehicle.Mains && ((false == vehicle.NoVoltRelay && false == vehicle.PantographsRequireMains) || false == vehicle.OvervoltageRelay) && + vehicle.MainSwitch(false, vehicle.TrainType == train_type::emu ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide + } + bool UpdateEngine(TMoverParameters &vehicle, double /*dt*/) const override + { + // automatyczny rozruch + return vehicle.AutoRelayCheck(); + } + void UpdateEngineVoltage(TMoverParameters &vehicle, double const dt) const override + { + vehicle.LastRelayTime += dt; + // potem ulepszyc! pantogtrafy! + // Ra 2014-03: uwzględnienie kierunku jazdy w napięciu na silnikach, a powinien być zdefiniowany nawrotnik + vehicle.EngineVoltage = vehicle.Mains ? vehicle.EnginePowerSourceVoltage() : 0.0; + if (vehicle.CabActive == 0) + { + vehicle.EngineVoltage *= vehicle.DirActive; + } + else + { + vehicle.EngineVoltage *= vehicle.DirAbsolute; // the reverser of the active cab, relative to the couplers + } + } }; // asynchronous motors fed by inverters @@ -251,6 +324,22 @@ public: return vehicle.ShowCurrentP(ammeter); } } + bool MainsPowerAvailable(TMoverParameters const &vehicle) const override + { + return linePowerAvailable(vehicle); + } + void CheckVoltageRelays(TMoverParameters &vehicle) const override + { + // TODO: check if we can use instead the code for electricseriesmotor + // nie wchodzić w funkcję bez potrzeby + // (a line breaker closed ahead of the pantographs holds without voltage) + // (the source by the traction selector of a dual-mode vehicle: the pantographs or the genset) + if (vehicle.Mains && ((vehicle.TractionSupplyVoltage() < vehicle.TractionSupplyMinVoltage() && false == vehicle.PantographsRequireMains) || + vehicle.TractionSupplyVoltage() > vehicle.EnginePowerSource.CollectorParameters.MaxV + 200)) + { + vehicle.MainSwitch(false, vehicle.TrainType == train_type::emu ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide + } + } }; // a diesel engine driving the wheels through a mechanical or hydraulic transmission @@ -330,6 +419,14 @@ public: { return vehicle.diesel.maxRevolutions * 60; } + bool MainsPowerAvailable(TMoverParameters const &vehicle) const override + { + return vehicle.Power24vIsAvailable; + } + bool UpdateEngine(TMoverParameters &vehicle, double const dt) const override + { + return vehicle.dizel_Update(dt); + } }; // a diesel engine driving a generator which feeds the traction motors @@ -424,6 +521,21 @@ public: { return vehicle.DElist[vehicle.MainCtrlPosNo].RPM; } + bool MainsPowerAvailable(TMoverParameters const &vehicle) const override + { + return vehicle.Power24vIsAvailable; + } + void CheckVoltageRelays(TMoverParameters &vehicle) const override + { + // TODO: move this to the auto relay check when the electric engine code paths are unified + vehicle.StLinFlag |= vehicle.Mains && false == vehicle.StLinFlag && vehicle.MainCtrlPowerPos() == 1; + vehicle.StLinFlag &= vehicle.MotorConnectorsCheck(); + vehicle.StLinFlag &= vehicle.MainCtrlPowerPos() > 0; + } + bool UpdateEngine(TMoverParameters &vehicle, double const dt) const override + { + return vehicle.dizel_Update(dt); + } }; NoEngineDrive const noEngineDrive{}; diff --git a/physics/components/drive.h b/physics/components/drive.h index a50f23d7c..b9f715b78 100644 --- a/physics/components/drive.h +++ b/physics/components/drive.h @@ -56,6 +56,15 @@ public: // a notch up and down of the master controller, as the kind of the engine takes it; return whether it moved virtual bool IncreaseMainController(TMoverParameters &vehicle, int speed) const; virtual bool DecreaseMainController(TMoverParameters &vehicle, int speed) const; + // whether the line breaker has the power it needs to close, before the genset of a dual-mode vehicle has its say + virtual bool MainsPowerAvailable(TMoverParameters const &vehicle) const; + // the relays that open the line breaker at a voltage out of range, or the line contactors + virtual void CheckVoltageRelays(TMoverParameters &vehicle) const; + // the engine in the step of the vehicle: the automatic start of the series motors, the diesel engine; returns + // whether a relay clicked + virtual bool UpdateEngine(TMoverParameters &vehicle, double dt) const; + // the voltage of the traction motors in the step (EngineVoltage) + virtual void UpdateEngineVoltage(TMoverParameters &vehicle, double dt) const; }; // the drive of the given kind of engine diff --git a/physics/components/electrics.cpp b/physics/components/electrics.cpp index d83b6c560..bfb0415db 100644 --- a/physics/components/electrics.cpp +++ b/physics/components/electrics.cpp @@ -28,6 +28,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include "physics/components/internal.h" +#include "physics/components/drive.h" // KURS90 - sprężarka pantografów; Ra 2014-07: teraz jest to zbiornik rozrządu, chociaż to jeszcze nie tak @@ -983,30 +984,7 @@ bool TMoverParameters::MainSwitchCheck() const // prevent the switch from working if there's no power // TODO: consider whether it makes sense for diesel engines and such - bool powerisavailable{true}; - - switch (EngineType) - { - case DieselElectric: - case DieselEngine: - case Dumb: - { - powerisavailable = Power24vIsAvailable; - break; - } - case ElectricSeriesMotor: - case ElectricInductionMotor: - { - // TODO: check whether we can simplify this check and skip the outer EngineType switch - // closed ahead of the pantographs, the line breaker runs on the low voltage circuits - powerisavailable = PantographsRequireMains ? Power24vIsAvailable || Power110vIsAvailable : EnginePowerSourceVoltage() > 0.5 * EnginePowerSource.MaxVoltage; - break; - } - default: - { - break; - } - } + bool powerisavailable{Drive().MainsPowerAvailable(*this)}; if (GensetSelected()) { // on the genset of a dual-mode vehicle the line breaker closes only on a running one, whatever the pantographs give diff --git a/physics/components/traction.cpp b/physics/components/traction.cpp index 0c95bd223..44f2d434d 100644 --- a/physics/components/traction.cpp +++ b/physics/components/traction.cpp @@ -663,58 +663,7 @@ double TMoverParameters::UpdateEnginePower() // the line breaker opened by a voltage out of the motors' range, and the line contactors of a diesel-electric void TMoverParameters::VoltageRelaysCheck() { - switch (EngineType) - { - - case TEngineType::ElectricSeriesMotor: - { - // update the state of voltage relays - auto const voltage{std::max(GetTrainsetHighVoltage(), PantographVoltage)}; - // where the line breaker holds without voltage (closed ahead of the pantographs) the undervoltage relay opens the - // line contactors instead, see MotorConnectorsCheck(). it picks up again only with the master controller back - // where a start begins, as the line breaker it stands in for wouldn't close on a running position either: at - // zero, or at the first position, which is the first resistance step, where the line contactors close on any - // start, and where the AI waits for them rather than going back to zero - auto const novoltrelaypicksup{false == PantographsRequireMains || NoVoltRelay || MainCtrlPowerPos() <= 1}; - NoVoltRelay = EnginePowerSource.SourceType != TPowerSource::CurrentCollector || (voltage >= EnginePowerSource.CollectorParameters.MinV && novoltrelaypicksup); - OvervoltageRelay = - EnginePowerSource.SourceType != TPowerSource::CurrentCollector || voltage <= EnginePowerSource.CollectorParameters.MaxV || false == EnginePowerSource.CollectorParameters.OVP; - // wywalanie szybkiego z powodu niewłaściwego napięcia - // (a line breaker closed ahead of the pantographs holds without voltage) - EventFlag |= true == Mains && ((false == NoVoltRelay && false == PantographsRequireMains) || false == OvervoltageRelay) && - MainSwitch(false, TrainType == train_type::emu ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide - break; - } - - case TEngineType::ElectricInductionMotor: - { - // TODO: check if we can use instead the code for electricseriesmotor - // nie wchodzić w funkcję bez potrzeby - // (a line breaker closed ahead of the pantographs holds without voltage) - // (the source by the traction selector of a dual-mode vehicle: the pantographs or the genset) - if (Mains && ((TractionSupplyVoltage() < TractionSupplyMinVoltage() && false == PantographsRequireMains) || - TractionSupplyVoltage() > EnginePowerSource.CollectorParameters.MaxV + 200)) - { - MainSwitch(false, TrainType == train_type::emu ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide - } - break; - } - - case TEngineType::DieselElectric: - { - // TODO: move this to the auto relay check when the electric engine code paths are unified - StLinFlag |= Mains && false == StLinFlag && MainCtrlPowerPos() == 1; - StLinFlag &= MotorConnectorsCheck(); - StLinFlag &= MainCtrlPowerPos() > 0; - - break; - } - - default: - { - break; - } - } + Drive().CheckVoltageRelays(*this); } void TMoverParameters::DumbTractionForce(double const PosRatio) From fbb9dc1e89e34ced198e2f78e0ef772a97ef33a7 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sat, 28 Nov 2026 18:32:58 +0100 Subject: [PATCH 024/123] refactor(physics): the ends and the sides of a vehicle as scoped enums end and side were unscoped enums: front, rear, left and right sat in the global namespace (the test PCH had to leave mover.h out for it), and an end went into any int, a side into an end, without a word from the compiler. They become enum class VehicleEnd and VehicleSide (physics/vehicletypes.h); the names follow the rule for types, and leave "end" and "side" to the many locals of that name. The numbers stay: front 0, rear 1, right 0, left 1. - ByEnd / BySide: two values indexed by the enum, and by a number where a loop or a format counts them. The arrays of the ends and the sides are these now: Couplers, Neighbours, Pantographs, MotorBlowers, Lights, iLights, Doors.instances, pVehicles, IsAnyDoor*, m_lighthints, vCoulpler, m_couplersounds, m_mirrormotion, iInventory, and the voltages of the couplers - VehicleEnds / VehicleSides to go through them, Opposite() in place of 1 - end, NumberOf() where a number is needed - the couplers and the collisions take the ends they work on as VehicleEnd: CouplerForce, CouplerVelocityDifference, CollisionDetect, crush_hit, CompatibleCoupling and the rest of their family, DirF, DirPatch, and of the vehicle couple, uncouple, the adapters, off_track_gap, has_signal_on; Attach, Dettach and DettachStatus have overloads by the ends - neighbour_data::FacingEnd() and TCoupling::ConnectedEnd() give the end of the other vehicle as VehicleEnd; the fields stay numbers, as they hold -1 and 2 for "none" in places The walks along the consist (FirstFind, Neighbour, the AI's coupling and uncoupling) still carry the ends as numbers; where one of them meets a typed end, NumberOf() and EndOf() say so, and keep the number as it was. Kept as it was, and worth a look: TDynamicObject::SetLights() switches the headlights A/B off by CabActive with the cases end::front and end::rear, that is CabActive 0 and 1, while CabActive is 1 or -1 for the cabs; the cases are NumberOf(VehicleEnd::front / rear) now, the same numbers. No change in behaviour: 1144/1144 tests, golden traces exact against staging 62f7a29b. betterRenderer/, not built, has had only end:: and side:: renamed. --- application/consistviews.cpp | 32 +-- application/consistviews.h | 3 +- application/driverhints.cpp | 94 ++++----- application/drivermode.cpp | 6 +- application/driveruipanels.cpp | 62 +++--- application/driveruipanels.h | 7 +- input/messaging.cpp | 4 +- physics/components/body.cpp | 38 ++-- physics/components/cab.cpp | 6 +- physics/components/collisions.cpp | 54 ++--- physics/components/commands.cpp | 32 +-- physics/components/controllers.cpp | 2 +- physics/components/couplers.cpp | 34 ++-- physics/components/doors.cpp | 30 +-- physics/components/electrics.cpp | 24 +-- physics/components/fizsections.cpp | 18 +- physics/components/internal.h | 6 +- physics/components/pneumatics.cpp | 4 +- physics/components/setup.cpp | 2 +- physics/components/traction.cpp | 12 +- physics/mover.h | 80 +++++--- physics/vehicletypes.h | 77 ++++++- rendering/common/scenewalk.cpp | 18 +- rendering/common/scenewalk.h | 3 +- rendering/lightarray.cpp | 10 +- simulation/blackboxrecorder.cpp | 32 +-- simulation/simulation.cpp | 2 +- simulation/simulationstateserializer.cpp | 6 +- tests/unit/consist.cpp | 12 +- tests/unit/drive.cpp | 4 +- tests/unit/golden.cpp | 4 +- tests/unit/scenario.h | 2 +- tests/unit/test_auxiliaries.cpp | 4 +- tests/unit/test_collisions.cpp | 72 +++---- tests/unit/test_commands.cpp | 82 ++++---- tests/unit/test_controls.cpp | 86 ++++---- tests/unit/test_coupler_physics.cpp | 102 +++++----- tests/unit/test_couplers.cpp | 192 +++++++++--------- tests/unit/test_couplers_trains.cpp | 82 ++++---- tests/unit/test_definition.cpp | 2 +- tests/unit/test_derailment_vehicle.cpp | 2 +- tests/unit/test_door_closure.cpp | 20 +- tests/unit/test_genset.cpp | 4 +- tests/unit/test_handover.cpp | 14 +- tests/unit/test_lights_preset_cablight.cpp | 12 +- tests/unit/test_lights_programmer.cpp | 36 ++-- tests/unit/test_line_contactors_interlock.cpp | 20 +- tests/unit/test_loads.cpp | 4 +- tests/unit/test_mains_before_pantographs.cpp | 36 ++-- tests/unit/test_pressure_switch.cpp | 30 +-- tests/unit/test_pullee.cpp | 2 +- tests/unit/test_queries.cpp | 2 +- tests/unit/vehicle.cpp | 14 +- tests/unit/vehicle.h | 6 +- vehicle/Driver.h | 18 +- vehicle/DynObj.h | 38 ++-- vehicle/Train.h | 10 +- vehicle/ai/consist.cpp | 50 ++--- vehicle/ai/controls.cpp | 20 +- vehicle/ai/doors.cpp | 20 +- vehicle/ai/driver.cpp | 28 +-- vehicle/ai/engine.cpp | 12 +- vehicle/ai/force.cpp | 8 +- vehicle/ai/obstacles.cpp | 20 +- vehicle/ai/orders.cpp | 44 ++-- vehicle/ai/routescan.cpp | 8 +- vehicle/ai/situation.cpp | 26 +-- vehicle/ai/speed.cpp | 2 +- vehicle/ai/speedtable.cpp | 20 +- vehicle/cab/auxiliarycommands.cpp | 44 ++-- vehicle/cab/cabcommands.cpp | 8 +- vehicle/cab/couplingcommands.cpp | 10 +- vehicle/cab/doorcommands.cpp | 28 +-- vehicle/cab/equipmentcommands.cpp | 6 +- vehicle/cab/lightcommands.cpp | 36 ++-- vehicle/cab/pantographcommands.cpp | 26 +-- vehicle/cab/setup.cpp | 32 +-- vehicle/cab/train.cpp | 40 ++-- vehicle/cab/update.cpp | 66 +++--- vehicle/crewchange.cpp | 2 +- vehicle/dynamic/animations.cpp | 22 +- vehicle/dynamic/consist.cpp | 43 ++-- vehicle/dynamic/couplers.cpp | 38 ++-- vehicle/dynamic/lifecycle.cpp | 44 ++-- vehicle/dynamic/lights.cpp | 46 ++--- vehicle/dynamic/load.cpp | 20 +- vehicle/dynamic/mmd.cpp | 92 ++++----- vehicle/dynamic/movement.cpp | 4 +- vehicle/dynamic/offtrack.cpp | 26 +-- vehicle/dynamic/sounds.cpp | 10 +- vehicle/dynamic/update.cpp | 58 +++--- vehicle/dynamic/vehicletable.cpp | 12 +- vehicle/dynamic/visual.cpp | 72 +++---- vehicle/enginestart.cpp | 2 +- vehicle/lightsprogrammer.h | 16 +- widgets/vehicleparams.cpp | 28 +-- 96 files changed, 1395 insertions(+), 1304 deletions(-) diff --git a/application/consistviews.cpp b/application/consistviews.cpp index 8c7847386..42cd41257 100644 --- a/application/consistviews.cpp +++ b/application/consistviews.cpp @@ -37,9 +37,9 @@ cameraviews::vehicle_pose pose_of(TDynamicObject const *Vehicle) { // the end of the Vehicle the Other vehicle is beyond, -1 when it's beyond neither int end_towards(TDynamicObject const *Vehicle, TDynamicObject const *Other) { - for (auto const side : {end::front, end::rear}) { + for (auto const side : VehicleEnds) { if (Vehicle->MoverParameters->Neighbours[side].vehicle == Other) { - return side; + return NumberOf(side); } } return -1; @@ -54,10 +54,10 @@ int outer_end(TDynamicObject const *Vehicle, TDynamicObject const *Inner, int co return inner < 0 ? Alone : 1 - inner; } -cameraviews::coupler coupler_of(TDynamicObject const *Vehicle, int const End) { +cameraviews::coupler coupler_of(TDynamicObject const *Vehicle, VehicleEnd const End) { cameraviews::coupler coupler; - coupler.position = Vehicle->CouplerPosition(static_cast(End)); - coupler.outward = Vehicle->VectorFront() * (End == end::front ? 1.0 : -1.0); + coupler.position = Vehicle->CouplerPosition(End); + coupler.outward = Vehicle->VectorFront() * (End == VehicleEnd::front ? 1.0 : -1.0); coupler.width = Vehicle->MoverParameters->Dim.W; return coupler; } @@ -71,8 +71,8 @@ int driven_way(TDynamicObject const *Driven) { // the coupler of the Vehicle furthest along the Way (or furthest back, with a negative Way) glm::dvec3 end_along(TDynamicObject const *Vehicle, glm::dvec3 const &Way) { - auto const front{Vehicle->CouplerPosition(end::front)}; - auto const rear{Vehicle->CouplerPosition(end::rear)}; + auto const front{Vehicle->CouplerPosition(VehicleEnd::front)}; + auto const rear{Vehicle->CouplerPosition(VehicleEnd::rear)}; return glm::dot(front - rear, Way) >= 0.0 ? front : rear; } @@ -103,7 +103,7 @@ std::vector consist_views::train_of(TDynamicObject *Driven) { return train; } auto const *controller{Driven->Mechanik != nullptr ? Driven->Mechanik : Driven->ctOwner}; - auto *first{controller != nullptr ? controller->Vehicle(end::front) : nullptr}; + auto *first{controller != nullptr ? controller->Vehicle(VehicleEnd::front) : nullptr}; if (first == nullptr) { first = Driven; } @@ -142,7 +142,7 @@ TDynamicObject *consist_views::pick(std::vector const &Train, return m_vehicle; } -double consist_views::gap_beyond(TDynamicObject const *Vehicle, int const End) { +double consist_views::gap_beyond(TDynamicObject const *Vehicle, VehicleEnd const End) { auto const &neighbour{Vehicle->MoverParameters->Neighbours[End]}; if (neighbour.vehicle == nullptr || false == Vehicle->MoverParameters->Couplers[End].CouplingFlag.Empty()) { return -1.0; @@ -163,23 +163,23 @@ consist_views::coupling_place consist_views::coupling_at(std::vectorCouplerPosition(static_cast(behindend < 0 ? end::front : behindend)); + place.otherposition = behind->CouplerPosition(behindend < 0 ? VehicleEnd::front : EndOf(behindend)); return place; } // an end of the train, perhaps with another vehicle coming closer to it auto const front{Index <= 0}; auto *vehicle{front ? Train.front() : Train.back()}; auto const *inner{count > 1 ? Train[front ? 1 : count - 2] : nullptr}; - auto const outer{outer_end(vehicle, inner, front ? end::front : end::rear)}; + auto const outer{outer_end(vehicle, inner, NumberOf(front ? VehicleEnd::front : VehicleEnd::rear))}; place.vehicle = vehicle; - place.coupler = coupler_of(vehicle, outer); + place.coupler = coupler_of(vehicle, EndOf(outer)); auto const &neighbour{vehicle->MoverParameters->Neighbours[outer]}; - place.gap = gap_beyond(vehicle, outer); - if (place.gap >= 0.0 && (neighbour.vehicle_end == end::front || neighbour.vehicle_end == end::rear)) { + place.gap = gap_beyond(vehicle, EndOf(outer)); + if (place.gap >= 0.0 && (neighbour.FacingEnd() == VehicleEnd::front || neighbour.FacingEnd() == VehicleEnd::rear)) { place.other = true; - place.otherposition = neighbour.vehicle->CouplerPosition(static_cast(neighbour.vehicle_end)); + place.otherposition = neighbour.vehicle->CouplerPosition(neighbour.FacingEnd()); } return place; } diff --git a/application/consistviews.h b/application/consistviews.h index 1c86345c0..d5bf6641e 100644 --- a/application/consistviews.h +++ b/application/consistviews.h @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #pragma once #include +#include "physics/vehicletypes.h" #include "vehicle/cameraviews.h" @@ -51,7 +52,7 @@ private: // the Index coupling of the Train, 0 its front end, Train.size() its rear end static coupling_place coupling_at(std::vector const &Train, int Index); // the distance to a vehicle not coupled beyond the End of the Vehicle, negative for none - static double gap_beyond(TDynamicObject const *Vehicle, int End); + static double gap_beyond(TDynamicObject const *Vehicle, VehicleEnd End); // keeps up the way the train goes and works out where its ends are, for the trackside view cameraviews::train_motion motion_of(std::vector const &Train, TDynamicObject const *Driven); diff --git a/application/driverhints.cpp b/application/driverhints.cpp index e00158bc0..93e2735fd 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -279,48 +279,48 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } case driver_hint::frontpantographvalveon: { if( AIControllFlag ) { - mvOccupied->OperatePantographValve( end::front, operation_t::enable ); + mvOccupied->OperatePantographValve( VehicleEnd::front, operation_t::enable ); } remove_hint( driver_hint::frontpantographvalveoff ); hint( Action, [ this ]( float const Parameter ) { - return mvPantographUnit->Pantographs[end::front].valve.is_active == true || (Parameter > 0 && mvOccupied->Vel > Parameter); }, + return mvPantographUnit->Pantographs[VehicleEnd::front].valve.is_active == true || (Parameter > 0 && mvOccupied->Vel > Parameter); }, Actionparameter ); break; } case driver_hint::frontpantographvalveoff: { if( AIControllFlag ) { - mvOccupied->OperatePantographValve( end::front, operation_t::disable ); + mvOccupied->OperatePantographValve( VehicleEnd::front, operation_t::disable ); } remove_hint( driver_hint::frontpantographvalveon ); hint( Action, [this](float const /*Parameter*/) { - return mvPantographUnit->Pantographs[end::front].valve.is_active == false; } ); + return mvPantographUnit->Pantographs[VehicleEnd::front].valve.is_active == false; } ); break; } case driver_hint::rearpantographvalveon: { if( AIControllFlag ) { - mvOccupied->OperatePantographValve( end::rear, operation_t::enable ); + mvOccupied->OperatePantographValve( VehicleEnd::rear, operation_t::enable ); } remove_hint( driver_hint::rearpantographvalveoff ); hint( Action, [ this ]( float const Parameter ) { - return mvPantographUnit->Pantographs[end::rear].valve.is_active == true || (Parameter > 0 && mvOccupied->Vel > Parameter); }, + return mvPantographUnit->Pantographs[VehicleEnd::rear].valve.is_active == true || (Parameter > 0 && mvOccupied->Vel > Parameter); }, Actionparameter ); break; } case driver_hint::rearpantographvalveoff: { if( AIControllFlag ) { - mvOccupied->OperatePantographValve( end::rear, operation_t::disable ); + mvOccupied->OperatePantographValve( VehicleEnd::rear, operation_t::disable ); } remove_hint( driver_hint::rearpantographvalveon ); hint( Action, [this](float const /*Parameter*/) { - return mvPantographUnit->Pantographs[end::rear].valve.is_active == false; } ); + return mvPantographUnit->Pantographs[VehicleEnd::rear].valve.is_active == false; } ); break; } // converter @@ -434,27 +434,27 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } case driver_hint::frontmotorblowerson: { if( AIControllFlag ) { - mvOccupied->MotorBlowersSwitchOff( false, end::front ); - mvOccupied->MotorBlowersSwitch( true, end::front ); + mvOccupied->MotorBlowersSwitchOff( false, VehicleEnd::front ); + mvOccupied->MotorBlowersSwitch( true, VehicleEnd::front ); } remove_hint( driver_hint::frontmotorblowersoff ); hint( Action, [this]( float const /*Parameter*/ ) { - auto const &device { mvOccupied->MotorBlowers[ end::front ] }; + auto const &device { mvOccupied->MotorBlowers[ VehicleEnd::front ] }; return device.start_type != start_t::manual || (device.is_enabled == true && device.is_disabled == false); } ); break; } case driver_hint::rearmotorblowerson: { if( AIControllFlag ) { - mvOccupied->MotorBlowersSwitchOff( false, end::rear ); - mvOccupied->MotorBlowersSwitch( true, end::rear ); + mvOccupied->MotorBlowersSwitchOff( false, VehicleEnd::rear ); + mvOccupied->MotorBlowersSwitch( true, VehicleEnd::rear ); } remove_hint( driver_hint::rearmotorblowersoff ); hint( Action, [this]( float const /*Parameter*/ ) { - auto const &device { mvOccupied->MotorBlowers[ end::rear ] }; + auto const &device { mvOccupied->MotorBlowers[ VehicleEnd::rear ] }; return device.start_type != start_t::manual || (device.is_enabled == true && device.is_disabled == false); } ); break; } @@ -1070,93 +1070,93 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) case driver_hint::doorrightopen: { if( AIControllFlag || pVehicle->MoverParameters->Doors.open_control == control_t::conductor ) { - pVehicle->MoverParameters->OperateDoors( side::right, true ); + pVehicle->MoverParameters->OperateDoors( VehicleSide::right, true ); } remove_hint( driver_hint::doorrightclose ); hint( Action, [this](float const /*Parameter*/) { - return IsAnyDoorOpen[side::right] == true; } ); + return IsAnyDoorOpen[VehicleSide::right] == true; } ); break; } case driver_hint::doorrightclose: { if( AIControllFlag || pVehicle->MoverParameters->Doors.open_control == control_t::conductor ) { - pVehicle->MoverParameters->OperateDoors( side::right, false ); + pVehicle->MoverParameters->OperateDoors( VehicleSide::right, false ); } remove_hint( driver_hint::doorrightopen ); hint( Action, [this](float const /*Parameter*/) { - return IsAnyDoorOpen[side::right] == false; } ); + return IsAnyDoorOpen[VehicleSide::right] == false; } ); break; } case driver_hint::doorleftopen: { if( AIControllFlag || pVehicle->MoverParameters->Doors.open_control == control_t::conductor ) { - pVehicle->MoverParameters->OperateDoors( side::left, true ); + pVehicle->MoverParameters->OperateDoors( VehicleSide::left, true ); } remove_hint( driver_hint::doorleftclose ); hint( Action, [this](float const /*Parameter*/) { - return IsAnyDoorOpen[side::left] == true; } ); + return IsAnyDoorOpen[VehicleSide::left] == true; } ); break; } case driver_hint::doorleftclose: { if( AIControllFlag || pVehicle->MoverParameters->Doors.open_control == control_t::conductor ) { - pVehicle->MoverParameters->OperateDoors( side::left, false ); + pVehicle->MoverParameters->OperateDoors( VehicleSide::left, false ); } remove_hint( driver_hint::doorleftopen ); hint( Action, [this](float const /*Parameter*/) { - return IsAnyDoorOpen[side::left] == false; } ); + return IsAnyDoorOpen[VehicleSide::left] == false; } ); break; } case driver_hint::doorrightpermiton: { if( AIControllFlag ) { - pVehicle->MoverParameters->PermitDoors( side::right, true ); + pVehicle->MoverParameters->PermitDoors( VehicleSide::right, true ); } remove_hint( driver_hint::doorrightpermitoff ); hint( Action, [this](float const /*Parameter*/) { - return IsAnyDoorPermitActive[side::right] == true; } ); + return IsAnyDoorPermitActive[VehicleSide::right] == true; } ); break; } case driver_hint::doorrightpermitoff: { if( AIControllFlag ) { - pVehicle->MoverParameters->PermitDoors( side::right, false ); + pVehicle->MoverParameters->PermitDoors( VehicleSide::right, false ); } remove_hint( driver_hint::doorrightpermiton ); hint( Action, [this](float const /*Parameter*/) { - return IsAnyDoorPermitActive[side::right] == false; } ); + return IsAnyDoorPermitActive[VehicleSide::right] == false; } ); break; } case driver_hint::doorleftpermiton: { if( AIControllFlag ) { - pVehicle->MoverParameters->PermitDoors( side::left, true ); + pVehicle->MoverParameters->PermitDoors( VehicleSide::left, true ); } remove_hint( driver_hint::doorleftpermitoff ); hint( Action, [this](float const /*Parameter*/) { - return IsAnyDoorPermitActive[side::left] == true; } ); + return IsAnyDoorPermitActive[VehicleSide::left] == true; } ); break; } case driver_hint::doorleftpermitoff: { if( AIControllFlag ) { - pVehicle->MoverParameters->PermitDoors( side::left, false ); + pVehicle->MoverParameters->PermitDoors( VehicleSide::left, false ); } remove_hint( driver_hint::doorleftpermiton ); hint( Action, [this](float const /*Parameter*/) { - return IsAnyDoorPermitActive[side::left] == false; } ); + return IsAnyDoorPermitActive[VehicleSide::left] == false; } ); break; } // doorsteps, as the timetable asks (eu07/maszyna#95) @@ -1254,30 +1254,30 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) case driver_hint::couplingadapterattach: { // TODO: run also for potential settings-based virtual assistant if( AIControllFlag ) { - pVehicles[ end::front ]->attach_coupler_adapter( static_cast(Actionparameter) ); + pVehicles[ VehicleEnd::front ]->attach_coupler_adapter( EndOf( static_cast(Actionparameter) ) ); } hint( Action, [this](float const Parameter) { - auto const &device { pVehicles[ end::front ]->MoverParameters->Couplers[ static_cast( Parameter ) ] }; + auto const &device { pVehicles[ VehicleEnd::front ]->MoverParameters->Couplers[ static_cast( Parameter ) ] }; return device.type() == TCouplerType::Automatic; } ); break; } case driver_hint::couplingadapterremove: { if( AIControllFlag || Global.AITrainman ) { - pVehicles[ end::front ]->remove_coupler_adapter( static_cast(Actionparameter) ); + pVehicles[ VehicleEnd::front ]->remove_coupler_adapter( EndOf( static_cast(Actionparameter) ) ); } hint( Action, [this](float const Parameter) { - auto const &device { pVehicles[ end::front ]->MoverParameters->Couplers[ static_cast( Parameter ) ] }; + auto const &device { pVehicles[ VehicleEnd::front ]->MoverParameters->Couplers[ static_cast( Parameter ) ] }; return false == device.has_adapter(); } ); break; } // lights case driver_hint::headcodepc1: { if( AIControllFlag ) { - pVehicles[ end::front ]->RaLightsSet( light::headlight_left | light::headlight_right | light::headlight_upper, -1 ); + pVehicles[ VehicleEnd::front ]->RaLightsSet( light::headlight_left | light::headlight_right | light::headlight_upper, -1 ); } remove_hint( driver_hint::headcodepc2 ); remove_hint( driver_hint::headcodetb1 ); @@ -1285,12 +1285,12 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return pVehicles[end::front]->has_signal_pc1_on(); } ); + return pVehicles[VehicleEnd::front]->has_signal_pc1_on(); } ); break; } case driver_hint::headcodepc2: { if( AIControllFlag ) { - pVehicles[ end::front ]->RaLightsSet( light::redmarker_left | light::headlight_right | light::headlight_upper, -1 ); + pVehicles[ VehicleEnd::front ]->RaLightsSet( light::redmarker_left | light::headlight_right | light::headlight_upper, -1 ); } remove_hint( driver_hint::headcodepc1 ); remove_hint( driver_hint::headcodetb1 ); @@ -1298,7 +1298,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return pVehicles[end::front]->has_signal_pc2_on(); } ); + return pVehicles[VehicleEnd::front]->has_signal_pc2_on(); } ); break; } case driver_hint::headcodetb1: { @@ -1315,22 +1315,22 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - auto const activeend { mvOccupied->CabActive >= 0 ? end::front : end::rear }; - auto const consistfront { mvOccupied->DirActive >= 0 ? end::front : end::rear }; - return pVehicles[consistfront]->has_signal_on(activeend, light::headlight_right) && pVehicles[1 - consistfront]->has_signal_on(1 - activeend, light::headlight_left); } ); + auto const activeend { mvOccupied->CabActive >= 0 ? VehicleEnd::front : VehicleEnd::rear }; + auto const consistfront { mvOccupied->DirActive >= 0 ? VehicleEnd::front : VehicleEnd::rear }; + return pVehicles[consistfront]->has_signal_on(activeend, light::headlight_right) && pVehicles[Opposite(consistfront)]->has_signal_on(Opposite(activeend), light::headlight_left); } ); break; } case driver_hint::headcodepc5: { if( AIControllFlag - || ( Global.AITrainman && false == pVehicles[end::rear]->is_connected(pVehicle, Coupling::control) ) ) { - pVehicles[ end::rear ]->RaLightsSet( -1, light::redmarker_left | light::redmarker_right | light::rearendsignals ); + || ( Global.AITrainman && false == pVehicles[VehicleEnd::rear]->is_connected(pVehicle, Coupling::control) ) ) { + pVehicles[ VehicleEnd::rear ]->RaLightsSet( -1, light::redmarker_left | light::redmarker_right | light::rearendsignals ); } remove_hint( driver_hint::headcodetb1 ); remove_hint( driver_hint::lightsoff ); hint( Action, [this](float const /*Parameter*/) { - return pVehicles[end::rear]->has_signal_pc5_on(); } ); + return pVehicles[VehicleEnd::rear]->has_signal_pc5_on(); } ); break; } case driver_hint::lightsoff: { @@ -1344,9 +1344,9 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - auto const activeend { mvOccupied->CabActive >= 0 ? end::front : end::rear }; - auto const consistfront { mvOccupied->DirActive >= 0 ? end::front : end::rear }; - return pVehicles[consistfront]->has_signal_on(activeend, 0) && pVehicles[1 - consistfront]->has_signal_on(1 - activeend, 0); } ); + auto const activeend { mvOccupied->CabActive >= 0 ? VehicleEnd::front : VehicleEnd::rear }; + auto const consistfront { mvOccupied->DirActive >= 0 ? VehicleEnd::front : VehicleEnd::rear }; + return pVehicles[consistfront]->has_signal_on(activeend, 0) && pVehicles[Opposite(consistfront)]->has_signal_on(Opposite(activeend), 0); } ); break; } // releaser diff --git a/application/drivermode.cpp b/application/drivermode.cpp index 20df43a3b..b121d7250 100644 --- a/application/drivermode.cpp +++ b/application/drivermode.cpp @@ -1242,7 +1242,7 @@ void driver_mode::ExternalView() case view::consistfront: { // bind camera with the vehicle - auto *owner{vehicle->Mechanik->Vehicle(end::front)}; + auto *owner{vehicle->Mechanik->Vehicle(VehicleEnd::front)}; Camera.m_owner = owner; @@ -1272,7 +1272,7 @@ void driver_mode::ExternalView() case view::consistrear: { // bind camera with the vehicle - auto *owner{vehicle->Mechanik->Vehicle(end::rear)}; + auto *owner{vehicle->Mechanik->Vehicle(VehicleEnd::rear)}; Camera.m_owner = owner; @@ -1300,7 +1300,7 @@ void driver_mode::ExternalView() } case view::bogie: { - auto *owner{vehicle->Mechanik->Vehicle(end::front)}; + auto *owner{vehicle->Mechanik->Vehicle(VehicleEnd::front)}; Camera.m_owner = owner; diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 304cf5d1a..53d988a29 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -55,13 +55,13 @@ namespace { constexpr float coupler_repair_radius { 5.f }; // the broken coupler nearest to the camera, within reach: the vehicle and its end, or no vehicle -std::pair broken_coupler_nearby( glm::dvec3 const &Camera ) { +std::pair broken_coupler_nearby( glm::dvec3 const &Camera ) { auto const *vehicle { std::get( simulation::Region->find_vehicle( Camera, coupler_repair_radius, false, true ) ) }; - if( vehicle == nullptr || vehicle->MoverParameters == nullptr ) { return { nullptr, end::front }; } - auto const front { glm::distance( vehicle->CouplerPosition( end::front ), Camera ) }; - auto const rear { glm::distance( vehicle->CouplerPosition( end::rear ), Camera ) }; - auto const nearest { front <= rear ? end::front : end::rear }; - if( std::min( front, rear ) > coupler_repair_radius || false == vehicle->MoverParameters->Couplers[ nearest ].broken ) { return { nullptr, end::front }; } + if( vehicle == nullptr || vehicle->MoverParameters == nullptr ) { return { nullptr, VehicleEnd::front }; } + auto const front { glm::distance( vehicle->CouplerPosition( VehicleEnd::front ), Camera ) }; + auto const rear { glm::distance( vehicle->CouplerPosition( VehicleEnd::rear ), Camera ) }; + auto const nearest { front <= rear ? VehicleEnd::front : VehicleEnd::rear }; + if( std::min( front, rear ) > coupler_repair_radius || false == vehicle->MoverParameters->Couplers[ nearest ].broken ) { return { nullptr, VehicleEnd::front }; } return { vehicle, nearest }; } @@ -232,7 +232,7 @@ drivingaid_panel::render_contents() { // only the coupler the camera is next to, and the one of the vehicle it was coupled with if( m_brokenvehicle != nullptr && ImGui::Button( STR_C( "Repair coupler" ) ) ) { command_relay commandrelay; - commandrelay.post( user_command::repaircoupler, m_brokenend, 0.0, GLFW_PRESS, 0, glm::vec3( 0.0f ), &m_brokenvehicle->name() ); + commandrelay.post( user_command::repaircoupler, NumberOf( m_brokenend ), 0.0, GLFW_PRESS, 0, glm::vec3( 0.0f ), &m_brokenvehicle->name() ); } ui_panel::render_contents(); @@ -807,8 +807,8 @@ debug_panel::update_section_vehicle( std::vector &Output ) { mover.EngineDescription( 0 ).c_str(), // TODO: put wheel flat reporting in the enginedescription() std::string( mover.WheelFlat > 0.01 ? " Flat: " + to_string( mover.WheelFlat, 1 ) + " mm" : "" ).c_str(), - update_vehicle_coupler( end::front ).c_str(), - update_vehicle_coupler( end::rear ).c_str() ); + update_vehicle_coupler( VehicleEnd::front ).c_str(), + update_vehicle_coupler( VehicleEnd::rear ).c_str() ); Output.emplace_back( std::string{ m_buffer.data() }, Global.UITextColor ); @@ -818,11 +818,11 @@ debug_panel::update_section_vehicle( std::vector &Output ) { // devices mover.Battery ? 'B' : '.', mover.PantsValve.is_active ? '+' : '.', - mover.Pantographs[end::rear].valve.is_active ? 'O' : - mover.Pantographs[end::rear].valve.is_enabled ? 'o' : + mover.Pantographs[VehicleEnd::rear].valve.is_active ? 'O' : + mover.Pantographs[VehicleEnd::rear].valve.is_enabled ? 'o' : '.', - mover.Pantographs[end::front].valve.is_active ? 'P' : - mover.Pantographs[end::front].valve.is_enabled ? 'p' : + mover.Pantographs[VehicleEnd::front].valve.is_active ? 'P' : + mover.Pantographs[VehicleEnd::front].valve.is_enabled ? 'p' : '.', mover.PantPressLockActive ? '!' : mover.PantPressSwitchActive ? '*' : @@ -866,21 +866,21 @@ debug_panel::update_section_vehicle( std::vector &Output ) { std::string( isdieselenginepowered ? STR(" oil pressure: ") + to_string( mover.OilPump.pressure, 2 ) : "" ).c_str(), // power transfers // 3000v - mover.Couplers[ end::front ].power_high.voltage, - mover.Couplers[ end::front ].power_high.current, - std::string( mover.Couplers[ end::front ].power_high.is_local ? ":" : ":=" ).c_str(), + mover.Couplers[ VehicleEnd::front ].power_high.voltage, + mover.Couplers[ VehicleEnd::front ].power_high.current, + std::string( mover.Couplers[ VehicleEnd::front ].power_high.is_local ? ":" : ":=" ).c_str(), mover.EngineVoltage, - std::string( mover.Couplers[ end::rear ].power_high.is_local ? ":" : "=:" ).c_str(), - mover.Couplers[ end::rear ].power_high.voltage, - mover.Couplers[ end::rear ].power_high.current, + std::string( mover.Couplers[ VehicleEnd::rear ].power_high.is_local ? ":" : "=:" ).c_str(), + mover.Couplers[ VehicleEnd::rear ].power_high.voltage, + mover.Couplers[ VehicleEnd::rear ].power_high.current, // 110v - mover.Couplers[ end::front ].power_110v.voltage, - mover.Couplers[ end::front ].power_110v.current, - std::string( mover.Couplers[ end::front ].power_110v.is_local ? ":" : ":=" ).c_str(), + mover.Couplers[ VehicleEnd::front ].power_110v.voltage, + mover.Couplers[ VehicleEnd::front ].power_110v.current, + std::string( mover.Couplers[ VehicleEnd::front ].power_110v.is_local ? ":" : ":=" ).c_str(), mover.PowerCircuits[ 1 ].first, - std::string( mover.Couplers[ end::rear ].power_110v.is_local ? ":" : "=:" ).c_str(), - mover.Couplers[ end::rear ].power_110v.voltage, - mover.Couplers[ end::rear ].power_110v.current ); + std::string( mover.Couplers[ VehicleEnd::rear ].power_110v.is_local ? ":" : "=:" ).c_str(), + mover.Couplers[ VehicleEnd::rear ].power_110v.voltage, + mover.Couplers[ VehicleEnd::rear ].power_110v.current ); Output.emplace_back( m_buffer.data(), Global.UITextColor ); @@ -898,8 +898,8 @@ debug_panel::update_section_vehicle( std::vector &Output ) { std::abs( mover.enrot ) * 60, std::abs( mover.nrot ) * mover.Transmision.Ratio * 60, mover.RventRot * 60, - std::abs( mover.MotorBlowers[end::front].revolutions ), - std::abs( mover.MotorBlowers[end::rear].revolutions ), + std::abs( mover.MotorBlowers[VehicleEnd::front].revolutions ), + std::abs( mover.MotorBlowers[VehicleEnd::rear].revolutions ), mover.diesel.heat.rpmw, mover.diesel.heat.rpmw2 ); @@ -1033,7 +1033,7 @@ void debug_panel::graph_data::render() { } std::string -debug_panel::update_vehicle_coupler( int const Side ) { +debug_panel::update_vehicle_coupler( VehicleEnd const Side ) { // NOTE: mover and vehicle are guaranteed to be valid by the caller auto const &mover { *m_input.mover }; @@ -1613,8 +1613,8 @@ debug_panel::update_section_coupler( std::vector &Output ) { Output.emplace_back( std::format( "No coupler within {:.0f} m of the camera", coupler_pick_radius ), Global.UITextColor ); return; } - auto const nearerfront { glm::distance( vehicle->CouplerPosition( end::front ), camera ) <= glm::distance( vehicle->CouplerPosition( end::rear ), camera ) }; - m_coupler = { vehicle, nearerfront ? end::front : end::rear }; + auto const nearerfront { glm::distance( vehicle->CouplerPosition( VehicleEnd::front ), camera ) <= glm::distance( vehicle->CouplerPosition( VehicleEnd::rear ), camera ) }; + m_coupler = { vehicle, nearerfront ? VehicleEnd::front : VehicleEnd::rear }; auto const &mover { *vehicle->MoverParameters }; auto const &coupler { mover.Couplers[ m_coupler.end ] }; @@ -1634,7 +1634,7 @@ debug_panel::update_section_coupler( std::vector &Output ) { Global.UITextColor ); if( neighbour.vehicle != nullptr ) { Output.emplace_back( - std::format( "Neighbour: {} ({} end), coupling [{}], gap {:.1f} mm", neighbour.vehicle->name(), neighbour.vehicle_end == end::front ? "front" : "rear", coupler.CouplingFlag.Bits(), neighbour.distance * 1000.0 ), + std::format( "Neighbour: {} ({} end), coupling [{}], gap {:.1f} mm", neighbour.vehicle->name(), neighbour.FacingEnd() == VehicleEnd::front ? "front" : "rear", coupler.CouplingFlag.Bits(), neighbour.distance * 1000.0 ), Global.UITextColor ); } else { diff --git a/application/driveruipanels.h b/application/driveruipanels.h index 0e8b6917e..c35ff12d6 100644 --- a/application/driveruipanels.h +++ b/application/driveruipanels.h @@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/. #include "application/uilayer.h" #include "utilities/Classes.h" +#include "physics/vehicletypes.h" #include "rendering/renderer.h" class drivingaid_panel : public ui_expandable_panel { @@ -28,7 +29,7 @@ private: std::array m_buffer; // the broken coupler next to the camera, which the panel offers to repair: the vehicle and its end TDynamicObject const *m_brokenvehicle { nullptr }; - int m_brokenend { 0 }; + VehicleEnd m_brokenend { VehicleEnd::front }; }; class timetable_panel : public ui_expandable_panel { @@ -99,7 +100,7 @@ private: void update_section_uart( std::vector &Output ) const; #endif // section update helpers - std::string update_vehicle_coupler( int const Side ); + std::string update_vehicle_coupler( VehicleEnd const Side ); std::string update_vehicle_brake() const; // renders provided lines, under specified collapsing header bool render_section( std::string const &Header, std::vector const &Lines ); @@ -130,7 +131,7 @@ private: // the coupler nearest to the camera struct coupler_pick { TDynamicObject const *vehicle { nullptr }; - int end { 0 }; + VehicleEnd end { VehicleEnd::front }; }; coupler_pick m_coupler; bool m_couplerbothends { true }; // changes to the parameters apply to the end of the other vehicle of the pair too diff --git a/input/messaging.cpp b/input/messaging.cpp index f91da91bd..0f1530199 100644 --- a/input/messaging.cpp +++ b/input/messaging.cpp @@ -302,8 +302,8 @@ WyslijNamiary([[maybe_unused]] TDynamicObject const *Vehicle) + Vehicle->MoverParameters->DoorLeftOpened * 16 + Vehicle->MoverParameters->DoorRightOpened * 32 #else - + ( false == Vehicle->MoverParameters->Doors.instances[side::left].is_closed ) * 16 - + ( false == Vehicle->MoverParameters->Doors.instances[side::right].is_closed ) * 32 + + ( false == Vehicle->MoverParameters->Doors.instances[VehicleSide::left].is_closed ) * 16 + + ( false == Vehicle->MoverParameters->Doors.instances[VehicleSide::right].is_closed ) * 32 #endif + Vehicle->MoverParameters->FuseFlag * 64 + Vehicle->MoverParameters->DepartureSignal * 128; diff --git a/physics/components/body.cpp b/physics/components/body.cpp index c91910ad2..698f19d98 100644 --- a/physics/components/body.cpp +++ b/physics/components/body.cpp @@ -31,7 +31,7 @@ http://mozilla.org/MPL/2.0/. #include "physics/components/drive.h" -int DirPatch(int Coupler1, int Coupler2) +int DirPatch(VehicleEnd const Coupler1, VehicleEnd const Coupler2) { // poprawka dla liczenia sil przy ustawieniu przeciwnym obiektow return Coupler1 != Coupler2 ? 1 : -1; } @@ -51,13 +51,13 @@ bool legacy_derailed_slides(TMoverParameters const &Vehicle) } // namespace -int DirF(int CouplerN) +int DirF(VehicleEnd CouplerN) { switch (CouplerN) { - case 0: + case VehicleEnd::front: return -1; - case 1: + case VehicleEnd::rear: return 1; default: return 0; @@ -173,7 +173,7 @@ void TMoverParameters::change_train_velocity(double const Change) for (std::size_t i = 0; i < train.size(); ++i) { auto const [vehicle, direction] = train[i]; - for (int end = end::front; end <= end::rear; ++end) + for (auto const end : VehicleEnds) { auto const &coupler{vehicle->Couplers[end]}; auto *other{coupler.Connected}; @@ -181,7 +181,7 @@ void TMoverParameters::change_train_velocity(double const Change) { continue; } - auto const otherdirection{direction * DirPatch(end, coupler.ConnectedNr)}; + auto const otherdirection{direction * DirPatch(end, coupler.ConnectedEnd())}; other->V += Change * otherdirection; train.emplace_back(other, otherdirection); } @@ -308,7 +308,7 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap } derailment_distance = 0.0; // ale jesli jest kolizja (zas. zach. pedu) to...} - for (int b = 0; b < 2; b++) + for (auto const b : VehicleEnds) if (Couplers[b].CheckCollision) CollisionDetect(b, dt); // zmienia niejawnie AccS, V !!! check_pushed_off(dt, std::abs(dL)); @@ -386,7 +386,7 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Sh // the criteria of derailment go by the distance, checked in the full step which ends the frame derailment_distance += std::abs(dL); // ale jesli jest kolizja (zas. zach. pedu) to... - for (int b = 0; b < 2; b++) + for (auto const b : VehicleEnds) if (Couplers[b].CheckCollision) CollisionDetect(b, dt); // zmienia niejawnie AccS, V !!! check_pushed_off(dt, std::abs(dL)); @@ -501,13 +501,13 @@ void TMoverParameters::compute_movement_(double const Deltatime) UpdateBatteryVoltage(Deltatime); UpdateScndPipePressure(Deltatime); // druga rurka, youBy - if ((DCEMUED_CC & 1) != 0 && Couplers[end::front].CouplingFlag.HasAny(Coupling::control)) + if ((DCEMUED_CC & 1) != 0 && Couplers[VehicleEnd::front].CouplingFlag.HasAny(Coupling::control)) { - DynamicBrakeEMUStatus &= Couplers[end::front].Connected->DynamicBrakeEMUStatus; + DynamicBrakeEMUStatus &= Couplers[VehicleEnd::front].Connected->DynamicBrakeEMUStatus; } - if ((DCEMUED_CC & 2) != 0 && Couplers[end::rear].CouplingFlag.HasAny(Coupling::control)) + if ((DCEMUED_CC & 2) != 0 && Couplers[VehicleEnd::rear].CouplingFlag.HasAny(Coupling::control)) { - DynamicBrakeEMUStatus &= Couplers[end::rear].Connected->DynamicBrakeEMUStatus; + DynamicBrakeEMUStatus &= Couplers[VehicleEnd::rear].Connected->DynamicBrakeEMUStatus; } if (BrakeSlippingTimer > 0.8 && ASBType != 128) @@ -721,7 +721,7 @@ void TMoverParameters::ComputeConstans(void) // drag calculation { // NOTE: draft effect of previous vehicle is simplified and doesn't have much to do with reality - auto const *previousvehicle{Couplers[V >= 0.0 ? end::front : end::rear].Connected}; + auto const *previousvehicle{Couplers[V >= 0.0 ? VehicleEnd::front : VehicleEnd::rear].Connected}; auto dragarea{Dim.W * Dim.H}; if (previousvehicle) { @@ -797,11 +797,11 @@ void TMoverParameters::ComputeTotalForce(double dt) auto const vehicleisactive{CabActive != 0 || Vel > 0.0001 || accelerating() || LastSwitchingTime < 5 || is_multiple_unit()}; - auto const movingvehicleahead{Neighbours[end::front].vehicle != nullptr && - (Neighbours[end::front].vehicle->MoverParameters->Vel > 0.0001 || Neighbours[end::front].vehicle->MoverParameters->accelerating())}; + auto const movingvehicleahead{Neighbours[VehicleEnd::front].vehicle != nullptr && + (Neighbours[VehicleEnd::front].vehicle->MoverParameters->Vel > 0.0001 || Neighbours[VehicleEnd::front].vehicle->MoverParameters->accelerating())}; - auto const movingvehiclebehind{Neighbours[end::rear].vehicle != nullptr && - (Neighbours[end::rear].vehicle->MoverParameters->Vel > 0.0001 || Neighbours[end::rear].vehicle->MoverParameters->accelerating())}; + auto const movingvehiclebehind{Neighbours[VehicleEnd::rear].vehicle != nullptr && + (Neighbours[VehicleEnd::rear].vehicle->MoverParameters->Vel > 0.0001 || Neighbours[VehicleEnd::rear].vehicle->MoverParameters->accelerating())}; auto const calculatephysics{vehicleisactive || movingvehicleahead || movingvehiclebehind}; @@ -914,7 +914,7 @@ void TMoverParameters::ComputeTotalForce(double dt) } nrot_eps = (abs(nrot) - old_nrot) / dt; // doliczenie sił z innych pojazdów - for (int end = end::front; end <= end::rear; ++end) + for (auto const end : VehicleEnds) { // a new step: the hit of the pair not taken by either vehicle yet Couplers[end].hit_handled = false; @@ -924,7 +924,7 @@ void TMoverParameters::ComputeTotalForce(double dt) if (Neighbours[end].vehicle != nullptr) { // the velocities before the step, the forces of all the vehicles come before their movement - Couplers[end].closing = -CouplerVelocityDifference(end, *Neighbours[end].vehicle->MoverParameters, Neighbours[end].vehicle_end) * DirF(end); + Couplers[end].closing = -CouplerVelocityDifference(end, *Neighbours[end].vehicle->MoverParameters, Neighbours[end].FacingEnd()) * DirF(end); Couplers[end].CForce = CouplerForce(end, dt); FTrain += Couplers[end].CForce; // what the buffers of the pair take in, for the budget of the crush (physics.collisions new and monitor) diff --git a/physics/components/cab.cpp b/physics/components/cab.cpp index 02bd95d0e..2accee006 100644 --- a/physics/components/cab.cpp +++ b/physics/components/cab.cpp @@ -82,7 +82,7 @@ int TMoverParameters::SoundingHorns(int const Signal) const } // a vehicle without a main reservoir of its own takes the air from the main pipe, a vehicle without either // (a road vehicle, say) has no air to check - auto const mainpipe{(Couplers[end::front].AllowedFlag | Couplers[end::rear].AllowedFlag).HasAny(Coupling::mainHose)}; + auto const mainpipe{(Couplers[VehicleEnd::front].AllowedFlag | Couplers[VehicleEnd::rear].AllowedFlag).HasAny(Coupling::mainHose)}; return false == mainpipe || ScndPipePress >= HornMinPressure; }}; auto horns{0}; @@ -154,8 +154,8 @@ bool TMoverParameters::CabDeactivisation(bool const Enforce) } if (InactiveCabFlag & activation::doorpermition) { - PermitDoors(side::right, true, range_t::consist); - PermitDoors(side::left, true, range_t::consist); + PermitDoors(VehicleSide::right, true, range_t::consist); + PermitDoors(VehicleSide::left, true, range_t::consist); } if (InactiveCabFlag & activation::neutraldirection) { diff --git a/physics/components/collisions.cpp b/physics/components/collisions.cpp index 12266fed8..db73aa29a 100644 --- a/physics/components/collisions.cpp +++ b/physics/components/collisions.cpp @@ -69,7 +69,7 @@ void tear_brake_hoses(TMoverParameters &Vehicle) // Q: 20160716 // Wykrywanie kolizji // ************************************************************************************************* -void TMoverParameters::CollisionDetect(int const End, double const dt) +void TMoverParameters::CollisionDetect(VehicleEnd const End, double const dt) { if (Neighbours[End].vehicle == nullptr) { @@ -78,7 +78,7 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) auto const &thiscoupler{Couplers[End]}; auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; - auto const otherend{Neighbours[End].vehicle_end}; + auto const otherend{Neighbours[End].FacingEnd()}; auto const &othercoupler{othervehicle->Couplers[otherend]}; auto const physical{coupler_physics_at(End)}; @@ -114,12 +114,12 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) switch (End) { - case 0: + case VehicleEnd::front: { CCF = ComputeCollision(velocity, othervehiclevelocity, TotalMass, othervehicle->TotalMass, loss, VirtualCoupling) / dt; break; // yB: ej ej ej, a po } - case 1: + case VehicleEnd::rear: { CCF = ComputeCollision(othervehiclevelocity, velocity, othervehicle->TotalMass, TotalMass, loss, VirtualCoupling) / dt; break; @@ -188,7 +188,7 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) } } -void TMoverParameters::damage_coupler(int const End) +void TMoverParameters::damage_coupler(VehicleEnd const End) { auto &thiscoupler{Couplers[End]}; @@ -241,12 +241,12 @@ collision::vehicle_kind TMoverParameters::collision_kind() const return collision::kind_of(powered, unit || passengers || (false == powered && HeatingPower > 0.0), false); } -collision::crush_curve TMoverParameters::crush_curve_at(int const End) const +collision::crush_curve TMoverParameters::crush_curve_at(VehicleEnd const End) const { return collision::crush_of(Couplers[End].collision, collision_kind()); } -double TMoverParameters::buffer_height_at(int const End) const +double TMoverParameters::buffer_height_at(VehicleEnd const End) const { auto const loadshare{MaxLoad > 0.f ? LoadAmount / MaxLoad : 0.0}; return collision::buffer_height(Couplers[End].collision, collision_kind(), loadshare); @@ -282,9 +282,9 @@ namespace { -char const *end_name(int const End) +char const *end_name(VehicleEnd const End) { - return End == end::front ? "front" : "rear"; + return End == VehicleEnd::front ? "front" : "rear"; } char const *kind_name(collision::vehicle_kind const Kind) @@ -306,9 +306,9 @@ char const *kind_name(collision::vehicle_kind const Kind) } // namespace // the force pressing the end in, of the coupling or of the buffers touching [N]: forwards at the front pulls -double compression_at(TCoupling const &Coupler, int const End) +double compression_at(TCoupling const &Coupler, VehicleEnd const End) { - return std::max(0.0, (End == end::front ? -1.0 : 1.0) * Coupler.CForce); + return std::max(0.0, (End == VehicleEnd::front ? -1.0 : 1.0) * Coupler.CForce); } namespace { @@ -330,11 +330,11 @@ void record_hit(TCoupling &Coupler, double const Force, double const Duration) } // namespace -bool TMoverParameters::crush_hit(int const End, double const dt) +bool TMoverParameters::crush_hit(VehicleEnd const End, double const dt) { auto &thiscoupler{Couplers[End]}; auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; - auto const otherend{Neighbours[End].vehicle_end}; + auto const otherend{Neighbours[End].FacingEnd()}; auto &othercoupler{othervehicle->Couplers[otherend]}; auto const physical{coupler_physics_at(End)}; @@ -465,7 +465,7 @@ bool TMoverParameters::crush_hit(int const End, double const dt) // the hit at the force the weaker end gives at pushes the vehicles apart: the velocities alone change, along this // vehicle's axis as in CollisionDetect() auto const otherdirection{DirPatch(End, otherend)}; - auto const apart{End == end::front ? -1.0 : 1.0}; + auto const apart{End == VehicleEnd::front ? -1.0 : 1.0}; if (false == wall) { V += apart * hit.impulse / mass; @@ -491,10 +491,10 @@ bool TMoverParameters::crush_hit(int const End, double const dt) secondcurve.force(othercoupler.crush) / 1000.0, hit.force / 1000.0, springs / 1000.0, input.start_velocity * 3.6, kinetic / 1000.0, thiscoupler.contact.absorbed() / 1000.0, capacity / 1000.0, thiscoupler.contact.crush_work() / 1000.0); }; - auto const crushed = [&](TMoverParameters const &Vehicle, int const VehicleEnd, double const Before, double const After) { + auto const crushed = [&](TMoverParameters const &Vehicle, VehicleEnd const crushedEnd, double const Before, double const After) { if (Before < collision::crush_mark && After >= collision::crush_mark) { - ErrorLog(std::format("Bad driving: {} and {} collided at {:.0f} km/h, the {} end of {} crushed ({})", Name, othervehicle->Name, closing * 3.6, end_name(VehicleEnd), Vehicle.Name, pair())); + ErrorLog(std::format("Bad driving: {} and {} collided at {:.0f} km/h, the {} end of {} crushed ({})", Name, othervehicle->Name, closing * 3.6, end_name(crushedEnd), Vehicle.Name, pair())); } }; auto const before{thiscoupler.crush}; @@ -566,8 +566,8 @@ void TMoverParameters::check_pushed_off(double const dt, double const Distance) auto duration{0.0}; auto worst{0.0}; auto worstforce{0.0}; - auto worstend{static_cast(end::front)}; - for (int end = end::front; end <= end::rear; ++end) + auto worstend{VehicleEnd::front}; + for (auto const end : VehicleEnds) { auto const *other{Neighbours[end].vehicle}; if (other == nullptr) @@ -612,9 +612,9 @@ void TMoverParameters::check_pushed_off(double const dt, double const Distance) lifted ? std::format("its wheels lifted off the rail for {:.3f} s", pushed_off_monitor.time()) : std::format("the flange climbing over {:.2f} m", pushed_off_monitor.distance()), Vel, std::abs(RunningShape.R), std::min(worst, 99.0), - vehicle.mass / 1000.0, kind_name(collision_kind()), vehicle.axles, compression_at(Couplers[end::front], end::front) / 1000.0, - compression_at(Couplers[end::rear], end::rear) / 1000.0, Couplers[end::front].hit_force / 1000.0, Couplers[end::rear].hit_force / 1000.0, - Couplers[end::front].crush, Couplers[end::rear].crush)); + vehicle.mass / 1000.0, kind_name(collision_kind()), vehicle.axles, compression_at(Couplers[VehicleEnd::front], VehicleEnd::front) / 1000.0, + compression_at(Couplers[VehicleEnd::rear], VehicleEnd::rear) / 1000.0, Couplers[VehicleEnd::front].hit_force / 1000.0, Couplers[VehicleEnd::rear].hit_force / 1000.0, + Couplers[VehicleEnd::front].crush, Couplers[VehicleEnd::rear].crush)); } } namespace @@ -641,7 +641,7 @@ void repair(TMoverParameters &Vehicle, TCoupling &Coupler) Coupler.stretch_duration = 0.f; Coupler.physics_state.couple(); restore_end(Coupler); - if (Vehicle.Couplers[end::front].broken || Vehicle.Couplers[end::rear].broken) + if (Vehicle.Couplers[VehicleEnd::front].broken || Vehicle.Couplers[VehicleEnd::rear].broken) { return; } @@ -652,7 +652,7 @@ void repair(TMoverParameters &Vehicle, TCoupling &Coupler) } // namespace -bool TMoverParameters::repair_coupler(int const End) +bool TMoverParameters::repair_coupler(VehicleEnd const End) { auto &thiscoupler{Couplers[End]}; if (false == thiscoupler.broken) @@ -665,7 +665,7 @@ bool TMoverParameters::repair_coupler(int const End) { repair(*other, other->Couplers[thiscoupler.ConnectedNr]); } - WriteLog(std::format("Coupler of {} repaired, at its {} end", Name, End == end::front ? "front" : "rear")); + WriteLog(std::format("Coupler of {} repaired, at its {} end", Name, End == VehicleEnd::front ? "front" : "rear")); return true; } @@ -694,7 +694,7 @@ void TMoverParameters::check_derailment(TTrackShape const &Shape, TTrackParam co vehicle.length = Dim.L; vehicle.axle_base = ADist > 0.0 ? ADist : BDist; vehicle.centre_of_gravity = centre_of_gravity(); - for (int end = end::front; end <= end::rear; ++end) + for (auto const end : VehicleEnds) { auto const *other{Neighbours[end].vehicle}; if (other == nullptr) @@ -702,8 +702,8 @@ void TMoverParameters::check_derailment(TTrackShape const &Shape, TTrackParam co continue; } // the force of the coupling, or of the buffers touching, along this vehicle: forwards at the front pulls - vehicle.ends[end].compression = (end == end::front ? -1.0 : 1.0) * Couplers[end].CForce; - vehicle.ends[end].other_length = other->MoverParameters->Dim.L; + vehicle.ends[NumberOf(end)].compression = (end == VehicleEnd::front ? -1.0 : 1.0) * Couplers[end].CForce; + vehicle.ends[NumberOf(end)].other_length = other->MoverParameters->Dim.L; } derailment::track_state track; track.radius = Shape.R; diff --git a/physics/components/commands.cpp b/physics/components/commands.cpp index 8a1ca64c5..1477b3c37 100644 --- a/physics/components/commands.cpp +++ b/physics/components/commands.cpp @@ -518,37 +518,37 @@ bool TMoverParameters::RunBlowersCommand(VehicleCommand const Command, double CV { if (Command == VehicleCommand::motorBlowersFrontSwitch) { - if (MotorBlowers[end::front].start_type != start_t::manual && MotorBlowers[end::front].start_type != start_t::manualwithautofallback) + if (MotorBlowers[VehicleEnd::front].start_type != start_t::manual && MotorBlowers[VehicleEnd::front].start_type != start_t::manualwithautofallback) { // automatic device ignores 'manual' state commands - MotorBlowers[end::front].is_enabled = CValue1 == 1; + MotorBlowers[VehicleEnd::front].is_enabled = CValue1 == 1; } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } else if (Command == VehicleCommand::motorBlowersFrontSwitchOff) { - if (MotorBlowers[end::front].start_type != start_t::manual && MotorBlowers[end::front].start_type != start_t::manualwithautofallback) + if (MotorBlowers[VehicleEnd::front].start_type != start_t::manual && MotorBlowers[VehicleEnd::front].start_type != start_t::manualwithautofallback) { // automatic device ignores 'manual' state commands - MotorBlowers[end::front].is_disabled = CValue1 == 1; + MotorBlowers[VehicleEnd::front].is_disabled = CValue1 == 1; } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } else if (Command == VehicleCommand::motorBlowersRearSwitch) { - if (MotorBlowers[end::rear].start_type != start_t::manual && MotorBlowers[end::rear].start_type != start_t::manualwithautofallback) + if (MotorBlowers[VehicleEnd::rear].start_type != start_t::manual && MotorBlowers[VehicleEnd::rear].start_type != start_t::manualwithautofallback) { // automatic device ignores 'manual' state commands - MotorBlowers[end::rear].is_enabled = CValue1 == 1; + MotorBlowers[VehicleEnd::rear].is_enabled = CValue1 == 1; } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } else if (Command == VehicleCommand::motorBlowersRearSwitchOff) { - if (MotorBlowers[end::rear].start_type != start_t::manual && MotorBlowers[end::rear].start_type != start_t::manualwithautofallback) + if (MotorBlowers[VehicleEnd::rear].start_type != start_t::manual && MotorBlowers[VehicleEnd::rear].start_type != start_t::manualwithautofallback) { // automatic device ignores 'manual' state commands - MotorBlowers[end::rear].is_disabled = CValue1 == 1; + MotorBlowers[VehicleEnd::rear].is_disabled = CValue1 == 1; } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } @@ -598,12 +598,12 @@ bool TMoverParameters::RunPowerCommand(VehicleCommand const Command, double CVal auto const inputcab{(static_cast(CValue1) & 0x40) != 0 ? 1 : 0}; auto const inputoperation{static_cast(CValue1) & ~(0x80 | 0x40)}; auto const noswap{TrainType == train_type::emu || TrainType == train_type::et41}; - auto swap{false == noswap && Couplers[CValue2 == -1 ? end::rear : end::front].CouplingFlag.HasAll(Coupling::control)}; + auto swap{false == noswap && Couplers[CValue2 == -1 ? VehicleEnd::rear : VehicleEnd::front].CouplingFlag.HasAll(Coupling::control)}; if (auto const reversed{inputcab != (CabActive != -1 ? 1 : 0)}; reversed) { swap = !swap; } // TODO: check whether this part has RL equivalent - OperatePantographValve(static_cast(swap ? 1 - inputend : inputend), static_cast(inputoperation), range_t::local); + OperatePantographValve(static_cast(swap ? 1 - inputend : inputend), static_cast(inputoperation), range_t::local); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } else if (Command == VehicleCommand::pantographsValve) @@ -680,11 +680,11 @@ void TMoverParameters::DoorPermitCommand(double const CValue1, double const CVal auto const leftside{CValue2 > 0 ? 1 : 2}; if (auto const rightside{3 - leftside}; std::abs(static_cast(CValue1)) & rightside) { - PermitDoors_(side::right, CValue1 > 0); + PermitDoors_(VehicleSide::right, CValue1 > 0); } if (std::abs(static_cast(CValue1)) & leftside) { - PermitDoors_(side::left, CValue1 > 0); + PermitDoors_(VehicleSide::left, CValue1 > 0); } } @@ -700,13 +700,13 @@ void TMoverParameters::DoorRemoteCommand(bool const Open, double const CValue1, auto const leftside{CValue2 > 0 ? 1 : 2}; if (auto const rightside{3 - leftside}; static_cast(CValue1) & rightside) { - Doors.instances[side::right].remote_open = Open; - Doors.instances[side::right].remote_close = false == Open; + Doors.instances[VehicleSide::right].remote_open = Open; + Doors.instances[VehicleSide::right].remote_close = false == Open; } if (static_cast(CValue1) & leftside) { - Doors.instances[side::left].remote_open = Open; - Doors.instances[side::left].remote_close = false == Open; + Doors.instances[VehicleSide::left].remote_open = Open; + Doors.instances[VehicleSide::left].remote_close = false == Open; } } diff --git a/physics/components/controllers.cpp b/physics/components/controllers.cpp index fc0e5e1ee..d5e41b2c3 100644 --- a/physics/components/controllers.cpp +++ b/physics/components/controllers.cpp @@ -1215,7 +1215,7 @@ void TMoverParameters::EIMICLimit() auto const eimicpowerenabled{(MainCircuitPowered() || Power == 0.0) && (!SpringBrake.IsActive || !SpringBrakeCutsOffDrive) && !LockPipe && DirAbsolute != 0}; auto const eimicdoorenabled{(SpringBrake.IsActive && ReleaseParkingBySpringBrakeWhenDoorIsOpen)}; double eimic_max = 0.0; - if (Doors.instances[side::left].open_permit == false && Doors.instances[side::right].open_permit == false) + if (Doors.instances[VehicleSide::left].open_permit == false && Doors.instances[VehicleSide::right].open_permit == false) { if (eimicpowerenabled) { diff --git a/physics/components/couplers.cpp b/physics/components/couplers.cpp index b6f750e86..7bf797524 100644 --- a/physics/components/couplers.cpp +++ b/physics/components/couplers.cpp @@ -68,7 +68,7 @@ bool TMoverParameters::Attach(int ConnectNo, int ConnectToNr, TMoverParameters * // no multiple-unit control between an electric and a diesel locomotive, whoever asks for it: the scenario, the AI // or the player (eu07/maszyna#520) - if (auto const compatible{CompatibleCoupling(ConnectNo, *ConnectTo, otherend, CouplingType)}; compatible != CouplingType) + if (auto const compatible{CompatibleCoupling(static_cast(ConnectNo), *ConnectTo, static_cast(otherend), CouplingType)}; compatible != CouplingType) { WriteLog(std::format("Vehicles \"{}\" and \"{}\" can't share their control, coupled without the control connection", Name, ConnectTo->Name)); CouplingType = compatible; @@ -183,21 +183,21 @@ bool TMoverParameters::Dettach(int ConnectNo) // ************************************************************************************************* // prędkość zbliżania się stykających się końców pojazdów przy zderzeniu, w km/h // ************************************************************************************************* -double TMoverParameters::CollisionVelocity(int const End, TMoverParameters const &Other, int const OtherEnd) const +double TMoverParameters::CollisionVelocity(VehicleEnd const End, TMoverParameters const &Other, VehicleEnd const OtherEnd) const { auto const velocitydifference{CouplerVelocityDifference(End, Other, OtherEnd)}; // the front end closes in on the other vehicle when this one moves forward faster, the rear end when it's slower - return (End == end::front ? velocitydifference : -velocitydifference) * 3.6; // m/s -> km/h + return (End == VehicleEnd::front ? velocitydifference : -velocitydifference) * 3.6; // m/s -> km/h } -double TMoverParameters::CouplerVelocityDifference(int const End, TMoverParameters const &Other, int const OtherEnd) const +double TMoverParameters::CouplerVelocityDifference(VehicleEnd const End, TMoverParameters const &Other, VehicleEnd const OtherEnd) const { // V runs along the vehicle's own axis, towards its front; the other vehicle's velocity is turned around when the // vehicles face each other (touch with the same ends) return V - Other.V * DirPatch(End, OtherEnd); } -bool TMoverParameters::AutomaticCouplingSafe(int const End, TMoverParameters const &Other, int const OtherEnd) const +bool TMoverParameters::AutomaticCouplingSafe(VehicleEnd const End, TMoverParameters const &Other, VehicleEnd const OtherEnd) const { return false == Global.crash_damage || CollisionVelocity(End, Other, OtherEnd) <= SafeCollisionVelocity; } @@ -230,7 +230,7 @@ traction_kind traction_of(TEngineType const Engine) } // namespace -bool TMoverParameters::ControlCouplingAllowed(int const End, TMoverParameters const &Other, int const OtherEnd) const +bool TMoverParameters::ControlCouplingAllowed(VehicleEnd const End, TMoverParameters const &Other, VehicleEnd const OtherEnd) const { if (false == Global.control_coupling_engine_check) { @@ -246,7 +246,7 @@ bool TMoverParameters::ControlCouplingAllowed(int const End, TMoverParameters co return traction == traction_kind::none || othertraction == traction_kind::none || traction == othertraction; } -CouplingSet TMoverParameters::CompatibleCoupling(int const End, TMoverParameters const &Other, int const OtherEnd, CouplingSet const CouplingType) const +CouplingSet TMoverParameters::CompatibleCoupling(VehicleEnd const End, TMoverParameters const &Other, VehicleEnd const OtherEnd, CouplingSet const CouplingType) const { if (false == CouplingType.HasAny(Coupling::control) || CouplingType.HasAny(Coupling::permanent) || ControlCouplingAllowed(End, Other, OtherEnd)) { @@ -259,7 +259,7 @@ CouplingSet TMoverParameters::CompatibleCoupling(int const End, TMoverParameters // Q: 20160713 // Obliczanie sił dzialających na sprzęgach // ************************************************************************************************* -double TMoverParameters::CouplerForce(int const End, double dt) +double TMoverParameters::CouplerForce(VehicleEnd const End, double dt) { if (coupler_physics_at(End)) { @@ -268,12 +268,12 @@ double TMoverParameters::CouplerForce(int const End, double dt) auto &thiscoupler{Couplers[End]}; auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; - auto const otherend{Neighbours[End].vehicle_end}; + auto const otherend{Neighbours[End].FacingEnd()}; auto const &othercoupler{othervehicle->Couplers[otherend]}; auto const othervehiclemove{(othervehicle->dMoveLen * DirPatch(End, otherend))}; auto const initialdistance{Neighbours[End].distance}; // odległość od sprzęgu sąsiada - auto const distancedelta{(End == end::front ? othervehiclemove - dMoveLen : dMoveLen - othervehiclemove)}; + auto const distancedelta{(End == VehicleEnd::front ? othervehiclemove - dMoveLen : dMoveLen - othervehiclemove)}; // the ends crushed for good (physics.collisions new, see collision.h) let the buffers meet that much closer auto const crushed{thiscoupler.crush + othercoupler.crush}; @@ -385,7 +385,7 @@ double TMoverParameters::CouplerForce(int const End, double dt) } // a coupler stretched with more than its strength for over a second breaks, the more likely the longer, with crash damage on -void TMoverParameters::CouplerStretchCheck(int const End, double const CF, double dt) +void TMoverParameters::CouplerStretchCheck(VehicleEnd const End, double const CF, double dt) { auto &thiscoupler{Couplers[End]}; if (std::abs(CF) > thiscoupler.FmaxC) @@ -405,7 +405,7 @@ void TMoverParameters::CouplerStretchCheck(int const End, double const CF, doubl } } -bool TMoverParameters::coupler_physics_at(int const End) const +bool TMoverParameters::coupler_physics_at(VehicleEnd const End) const { if (false == Global.coupler_physics) { @@ -420,7 +420,7 @@ bool TMoverParameters::coupler_physics_at(int const End) const return other != nullptr && other->MoverParameters->CouplerPhysics; } -void TMoverParameters::automatic_coupling(int const End, TMoverParameters &Other, int const OtherEnd) +void TMoverParameters::automatic_coupling(VehicleEnd const End, TMoverParameters &Other, VehicleEnd const OtherEnd) { auto &thiscoupler{Couplers[End]}; auto &othercoupler{Other.Couplers[OtherEnd]}; @@ -490,17 +490,17 @@ int coupler_sounds(coupler_sound_input const &Input) } // namespace -double TMoverParameters::coupler_force_physical(int const End, double const dt) +double TMoverParameters::coupler_force_physical(VehicleEnd const End, double const dt) { auto &thiscoupler{Couplers[End]}; auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; - auto const otherend{Neighbours[End].vehicle_end}; + auto const otherend{Neighbours[End].FacingEnd()}; auto &othercoupler{othervehicle->Couplers[otherend]}; auto &state{thiscoupler.physics_state}; // the gap as it is now: the distance found at the start of the frame, and the movement of both vehicles since auto const othervehiclemove{othervehicle->dMoveLen * DirPatch(End, otherend)}; - auto const gap{Neighbours[End].distance + (End == end::front ? othervehiclemove - dMoveLen : dMoveLen - othervehiclemove)}; + auto const gap{Neighbours[End].distance + (End == VehicleEnd::front ? othervehiclemove - dMoveLen : dMoveLen - othervehiclemove)}; // the gap opens up when the front end falls behind the vehicle ahead of it, or the rear end runs ahead of the one behind auto const gaprate{CouplerVelocityDifference(End, *othervehicle, otherend) * DirF(End)}; auto const coupled{thiscoupler.CouplingFlag != Coupling::none}; @@ -547,7 +547,7 @@ double TMoverParameters::coupler_force_physical(int const End, double const dt) return force; } -bool TMoverParameters::coupler_stop_hit(int const End, TMoverParameters &Other, int const OtherEnd) +bool TMoverParameters::coupler_stop_hit(VehicleEnd const End, TMoverParameters &Other, VehicleEnd const OtherEnd) { auto &thiscoupler{Couplers[End]}; auto &othercoupler{Other.Couplers[OtherEnd]}; diff --git a/physics/components/doors.cpp b/physics/components/doors.cpp index c9334a56e..216279bef 100644 --- a/physics/components/doors.cpp +++ b/physics/components/doors.cpp @@ -47,22 +47,22 @@ bool TMoverParameters::AssignLoad(std::string const &Loadname, float const Amoun { if (DoubleTr == 1) { - OperatePantographValve(end::front, operation_t::enable, range_t::local); + OperatePantographValve(VehicleEnd::front, operation_t::enable, range_t::local); } else { - OperatePantographValve(end::rear, operation_t::enable, range_t::local); + OperatePantographValve(VehicleEnd::rear, operation_t::enable, range_t::local); } } if (pantographsetup & 1 << 1) { if (DoubleTr == 1) { - OperatePantographValve(end::rear, operation_t::enable, range_t::local); + OperatePantographValve(VehicleEnd::rear, operation_t::enable, range_t::local); } else { - OperatePantographValve(end::front, operation_t::enable, range_t::local); + OperatePantographValve(VehicleEnd::front, operation_t::enable, range_t::local); } } return true; @@ -183,8 +183,8 @@ bool TMoverParameters::ChangeDoorPermitPreset(int const Change, range_t const No auto const permitleft{((doors & 1) != 0)}; auto const permitright{((doors & 2) != 0)}; - PermitDoors(CabActive > 0 ? side::left : side::right, permitleft, Notify); - PermitDoors(CabActive > 0 ? side::right : side::left, permitright, Notify); + PermitDoors(CabActive > 0 ? VehicleSide::left : VehicleSide::right, permitleft, Notify); + PermitDoors(CabActive > 0 ? VehicleSide::right : VehicleSide::left, permitright, Notify); } return Doors.permit_preset != initialstate; @@ -205,7 +205,7 @@ bool TMoverParameters::PermitDoorStep(bool const State, range_t const Notify) return Doors.step_enabled != initialstate; } -bool TMoverParameters::PermitDoors(side const Door, bool const State, range_t const Notify) +bool TMoverParameters::PermitDoors(VehicleSide const Door, bool const State, range_t const Notify) { bool const initialstate{Doors.instances[Door].open_permit}; @@ -217,7 +217,7 @@ bool TMoverParameters::PermitDoors(side const Door, bool const State, range_t co SendCtrlToNext(VehicleCommand::doorPermit, (State ? 1 : -1) // positive: grant, negative: revoke - * (Door == (CabActive > 0 ? side::left : side::right) ? // 1=lewe, 2=prawe (swap if reversed) + * (Door == (CabActive > 0 ? VehicleSide::left : VehicleSide::right) ? // 1=lewe, 2=prawe (swap if reversed) 1 : 2), CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); @@ -226,7 +226,7 @@ bool TMoverParameters::PermitDoors(side const Door, bool const State, range_t co return Doors.instances[Door].open_permit != initialstate; } -void TMoverParameters::PermitDoors_(side const Door, bool const State) +void TMoverParameters::PermitDoors_(VehicleSide const Door, bool const State) { if (State && State != Doors.instances[Door].open_permit) @@ -252,14 +252,14 @@ bool TMoverParameters::ChangeDoorControlMode(bool const State, range_t const Not { // when door are put in remote control mode they're automatically open // TBD, TODO: make it dependant on config switch? - OperateDoors(side::left, true); - OperateDoors(side::right, true); + OperateDoors(VehicleSide::left, true); + OperateDoors(VehicleSide::right, true); } return Doors.remote_only != initialstate; } -bool TMoverParameters::OperateDoors(side const Door, bool const State, range_t const Notify) +bool TMoverParameters::OperateDoors(VehicleSide const Door, bool const State, range_t const Notify) { auto &door{Doors.instances[Door]}; @@ -293,7 +293,7 @@ bool TMoverParameters::OperateDoors(side const Door, bool const State, range_t c { SendCtrlToNext(State == true ? VehicleCommand::doorOpen : VehicleCommand::doorClose, - Door == (CabActive > 0 ? side::left : side::right) ? // 1=lewe, 2=prawe (swap if reversed) + Door == (CabActive > 0 ? VehicleSide::left : VehicleSide::right) ? // 1=lewe, 2=prawe (swap if reversed) 1 : 2, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); @@ -403,7 +403,7 @@ void TMoverParameters::update_doors(double const Deltatime) move_door(door, Deltatime); } - if (false == Doors.instances[side::right].is_open && false == Doors.instances[side::left].is_open) + if (false == Doors.instances[VehicleSide::right].is_open && false == Doors.instances[VehicleSide::left].is_open) { return; } @@ -414,7 +414,7 @@ void TMoverParameters::update_doors(double const Deltatime) } /* // the door are closed if their timer goes below 0, or if the vehicle is moving faster than defined threshold - std::array const doorids { side::right, side::left }; + std::array const doorids { VehicleSide::right, VehicleSide::left }; for( auto const doorid : doorids ) { auto const &door { Doors.instances[ doorid ] }; if( true == door.is_open ) { diff --git a/physics/components/electrics.cpp b/physics/components/electrics.cpp index bfb0415db..7cdb75bd1 100644 --- a/physics/components/electrics.cpp +++ b/physics/components/electrics.cpp @@ -37,7 +37,7 @@ void TMoverParameters::UpdatePantVolume(double dt) // check the pantograph compressor while at it // TODO: move the check to a separate method // automatic start if the pressure is too low - PantCompFlag |= PantPress < 4.2 && true == (Pantographs[end::front].is_active | Pantographs[end::rear].is_active) // TODO: any_pantograph_is_active method + PantCompFlag |= PantPress < 4.2 && true == (Pantographs[VehicleEnd::front].is_active | Pantographs[VehicleEnd::rear].is_active) // TODO: any_pantograph_is_active method && (PantographCompressorStart == start_t::automatic || PantographCompressorStart == start_t::manualwithautofallback); auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; @@ -463,17 +463,17 @@ double TMoverParameters::LocalPowerVoltage(Coupling const kind) // the voltage passed through the vehicle to the coupler at its other end, from the coupled vehicle or its own source void TMoverParameters::PowerCouplersVoltage(Coupling const kind, double const abslocalvoltage, bool const localpowersource) { - if (Couplers[end::front].power(kind) == nullptr) + if (Couplers[VehicleEnd::front].power(kind) == nullptr) { // not a power coupling, there's no voltage to pass return; } - for (auto side = 0; side < 2; ++side) + for (auto const side : VehicleEnds) { auto const &thiscoupler{Couplers[side]}; // NOTE: in the loop we actually update the state of the coupler on the opposite end of the vehicle - auto &oppositecoupler{Couplers[side == end::front ? end::rear : end::front]}; + auto &oppositecoupler{Couplers[Opposite(side)]}; bool oppositecouplingispresent; bool localpowerexportisenabled; @@ -539,8 +539,8 @@ void TMoverParameters::PowerCouplersVoltage(Coupling const kind, double const ab // the current drawn through the couplers, shared by their voltages, or added to the vehicle's own void TMoverParameters::PowerCouplersCurrent(Coupling const kind, bool const localpowersource) { - auto const *frontcoupling{Couplers[end::front].power(kind)}; - auto const *rearcoupling{Couplers[end::rear].power(kind)}; + auto const *frontcoupling{Couplers[VehicleEnd::front].power(kind)}; + auto const *rearcoupling{Couplers[VehicleEnd::rear].power(kind)}; auto *totalcurrent{PowerCircuitCurrent(kind)}; if (frontcoupling == nullptr || rearcoupling == nullptr || totalcurrent == nullptr) { @@ -560,7 +560,7 @@ void TMoverParameters::PowerCouplersCurrent(Coupling const kind, bool const loca continue; } - auto const &connectedothercoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr == end::front ? end::rear : end::front]}; + auto const &connectedothercoupler{thiscoupler.Connected->Couplers[Opposite(thiscoupler.ConnectedEnd())]}; auto const *connectedothercoupling = connectedothercoupler.power(kind); auto const extracurrent = kind == Coupling::highVoltage ? std::abs(Itot) * IsVehicleEIMBrakingFactor() : 0.0; @@ -1191,7 +1191,7 @@ bool TMoverParameters::OperatePantographsValve(operation_t const State, range_t return true; } -bool TMoverParameters::OperatePantographValve(end const End, operation_t const State, range_t const Notify) +bool TMoverParameters::OperatePantographValve(VehicleEnd const End, operation_t const State, range_t const Notify) { if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector && EnginePowerSource.CollectorParameters.CollectorsNo > 0) @@ -1248,7 +1248,7 @@ bool TMoverParameters::OperatePantographValve(end const End, operation_t const S SendCtrlToNext(VehicleCommand::pantographValve, // HACK: pack the state, pantograph index and sender cab into 8-bit value // with high bit storing front/rear pantograph, and 7th bit storing sender cab - static_cast(0x80 * (End == end::front ? 0 : 1) + 0x40 * (CabActive != -1 ? 1 : 0) + static_cast(State)), CabActive, + static_cast(0x80 * (End == VehicleEnd::front ? 0 : 1) + 0x40 * (CabActive != -1 ? 1 : 0) + static_cast(State)), CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } @@ -1277,8 +1277,8 @@ bool TMoverParameters::DropAllPantographs(bool const State, range_t const Notify double TMoverParameters::GetTrainsetVoltage(CouplingSet const couplings) const { // ABu: funkcja zwracajaca napiecie dla calego skladu, przydatna dla EZT // TBD, TODO: call once per vehicle update, return cached results? - std::array voltages{0.0, 0.0}; - for (int end = end::front; end <= end::rear; ++end) + ByEnd voltages{0.0, 0.0}; + for (auto const end : VehicleEnds) { if (Couplers[end].Connected == nullptr) { @@ -1298,7 +1298,7 @@ double TMoverParameters::GetTrainsetVoltage(CouplingSet const couplings) const voltages[end] = connectedpowercoupling->voltage; } } - return std::max(voltages[end::front], voltages[end::rear]); + return std::max(voltages[VehicleEnd::front], voltages[VehicleEnd::rear]); } double TMoverParameters::GetTrainsetHighVoltage() const diff --git a/physics/components/fizsections.cpp b/physics/components/fizsections.cpp index 7c2d082fc..d3de6cc60 100644 --- a/physics/components/fizsections.cpp +++ b/physics/components/fizsections.cpp @@ -660,11 +660,11 @@ void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Inde Couplers[1] = Couplers[0]; } // each coupling as made is a little stronger than its rated force, a different one at each end - for (int end = end::front; end <= end::rear; ++end) + for (auto const end : VehicleEnds) { - if (Index == 0 || end == (Index == 2 ? end::rear : end::front)) + if (Index == 0 || end == (Index == 2 ? VehicleEnd::rear : VehicleEnd::front)) { - scale_strength(Couplers[end].physics.link, coupler_physics::strength_scatter(Name, end)); + scale_strength(Couplers[end].physics.link, coupler_physics::strength_scatter(Name, NumberOf(end))); } } } @@ -986,8 +986,8 @@ void TMoverParameters::LoadFIZ_CntrlStarts(std::string const &line) // traction motor fans { auto lookup = starts.find(extract_value("MotorBlowersStart", line)); - MotorBlowers[end::rear].start_type = lookup != starts.end() ? lookup->second : manual; - MotorBlowers[end::front].start_type = MotorBlowers[end::rear].start_type; + MotorBlowers[VehicleEnd::rear].start_type = lookup != starts.end() ? lookup->second : manual; + MotorBlowers[VehicleEnd::front].start_type = MotorBlowers[VehicleEnd::rear].start_type; } // what else the line contactors need to close { @@ -1256,10 +1256,10 @@ void TMoverParameters::LoadFIZ_Engine(std::string const &Input) } // traction motors - extract_value(MotorBlowers[end::front].speed, "MotorBlowersSpeed", Input, ""); - extract_value(MotorBlowers[end::front].sustain_time, "MotorBlowersSustainTime", Input, ""); - extract_value(MotorBlowers[end::front].min_start_velocity, "MotorBlowersStartVelocity", Input, ""); - MotorBlowers[end::rear] = MotorBlowers[end::front]; + extract_value(MotorBlowers[VehicleEnd::front].speed, "MotorBlowersSpeed", Input, ""); + extract_value(MotorBlowers[VehicleEnd::front].sustain_time, "MotorBlowersSustainTime", Input, ""); + extract_value(MotorBlowers[VehicleEnd::front].min_start_velocity, "MotorBlowersStartVelocity", Input, ""); + MotorBlowers[VehicleEnd::rear] = MotorBlowers[VehicleEnd::front]; // pressure switch extract_value(HasControlPressureSwitch, "PressureSwitch", Input, TrainType != train_type::emu ? "yes" : "no"); // its brake cylinder half; the brake pipe one stays diff --git a/physics/components/internal.h b/physics/components/internal.h index a43782492..baf916278 100644 --- a/physics/components/internal.h +++ b/physics/components/internal.h @@ -21,13 +21,13 @@ inline double square(double val) // SQR() zle liczylo w current() ... return val * val; } -int DirPatch(int Coupler1, int Coupler2); +int DirPatch(VehicleEnd Coupler1, VehicleEnd Coupler2); -int DirF(int CouplerN); +int DirF(VehicleEnd CouplerN); double TableInterpolation(std::map &Map, double Parameter); -double compression_at(TCoupling const &Coupler, int const End); +double compression_at(TCoupling const &Coupler, VehicleEnd const End); bool issection(std::string_view Name, std::string_view Input); diff --git a/physics/components/pneumatics.cpp b/physics/components/pneumatics.cpp index 1e4e44f2b..8a7f0555a 100644 --- a/physics/components/pneumatics.cpp +++ b/physics/components/pneumatics.cpp @@ -828,8 +828,8 @@ void TMoverParameters::CompressorCheck(double dt) // NOTE: this is crude implementation, limited only to adjacent vehicles // TODO: re-implement when a more elegant/flexible system is in place auto const coupledgovernorlock{ - (Couplers[end::rear].Connected != nullptr && true == Couplers[end::rear].CouplingFlag.HasAll(Coupling::permanent) && Couplers[end::rear].Connected->CompressorGovernorLock) || - (Couplers[end::front].Connected != nullptr && true == Couplers[end::front].CouplingFlag.HasAll(Coupling::permanent) && Couplers[end::front].Connected->CompressorGovernorLock)}; + (Couplers[VehicleEnd::rear].Connected != nullptr && true == Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::permanent) && Couplers[VehicleEnd::rear].Connected->CompressorGovernorLock) || + (Couplers[VehicleEnd::front].Connected != nullptr && true == Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::permanent) && Couplers[VehicleEnd::front].Connected->CompressorGovernorLock)}; auto const governorlock{CompressorGovernorLock || coupledgovernorlock}; auto const compressorflag{CompressorFlag}; diff --git a/physics/components/setup.cpp b/physics/components/setup.cpp index d4a8aae70..086e37ddc 100644 --- a/physics/components/setup.cpp +++ b/physics/components/setup.cpp @@ -410,7 +410,7 @@ double TMoverParameters::InitialScndPipePress(double const HosePressure) const { return CompressedVolume / VeselVolume; } - if (Couplers[end::front].AllowedFlag.HasAny(Coupling::mainHose) || Couplers[end::rear].AllowedFlag.HasAny(Coupling::mainHose)) + if (Couplers[VehicleEnd::front].AllowedFlag.HasAny(Coupling::mainHose) || Couplers[VehicleEnd::rear].AllowedFlag.HasAny(Coupling::mainHose)) { return HosePressure; } diff --git a/physics/components/traction.cpp b/physics/components/traction.cpp index 44f2d434d..de089e04b 100644 --- a/physics/components/traction.cpp +++ b/physics/components/traction.cpp @@ -394,7 +394,7 @@ double TMoverParameters::ShowCurrent(int AmpN) const return Drive().ShowCurrent(*this, AmpN); }; -bool TMoverParameters::MotorBlowersSwitch(bool State, end const Side, range_t const Notify) +bool TMoverParameters::MotorBlowersSwitch(bool State, VehicleEnd const Side, range_t const Notify) { auto &fan{MotorBlowers[Side]}; @@ -411,14 +411,14 @@ bool TMoverParameters::MotorBlowersSwitch(bool State, end const Side, range_t co if (Notify != range_t::local) { - SendCtrlToNext(Side == end::front ? VehicleCommand::motorBlowersFrontSwitch : VehicleCommand::motorBlowersRearSwitch, fan.is_enabled ? 1 : 0, CabActive, + SendCtrlToNext(Side == VehicleEnd::front ? VehicleCommand::motorBlowersFrontSwitch : VehicleCommand::motorBlowersRearSwitch, fan.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } return fan.is_enabled != initialstate; } -bool TMoverParameters::MotorBlowersSwitchOff(bool State, end const Side, range_t const Notify) +bool TMoverParameters::MotorBlowersSwitchOff(bool State, VehicleEnd const Side, range_t const Notify) { auto &fan{MotorBlowers[Side]}; @@ -435,7 +435,7 @@ bool TMoverParameters::MotorBlowersSwitchOff(bool State, end const Side, range_t if (Notify != range_t::local) { - SendCtrlToNext(Side == end::front ? VehicleCommand::motorBlowersFrontSwitchOff : VehicleCommand::motorBlowersRearSwitchOff, fan.is_disabled ? 1 : 0, CabActive, + SendCtrlToNext(Side == VehicleEnd::front ? VehicleCommand::motorBlowersFrontSwitchOff : VehicleCommand::motorBlowersRearSwitchOff, fan.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } @@ -1179,8 +1179,8 @@ void TMoverParameters::InductionMotorDynamicBrakeFlag() // zalaczenia hamulca elektrodynamicznego - ED jest sterowany wlasnym nastawnikiem auto const dynbrakectrlactive{SplitEDPneumaticBrake && DynamicBrakeRatio() > 0.01 && DynamicBrakeAvailable()}; auto const localbrakeforED{SplitEDPneumaticBrake ? false : localbrakeactive}; - if (false == Doors.instances[side::left].is_closed || false == Doors.instances[side::right].is_closed || - (Doors.permit_needed && (Doors.instances[side::left].open_permit || Doors.instances[side::right].open_permit))) + if (false == Doors.instances[VehicleSide::left].is_closed || false == Doors.instances[VehicleSide::right].is_closed || + (Doors.permit_needed && (Doors.instances[VehicleSide::left].open_permit || Doors.instances[VehicleSide::right].open_permit))) { DynamicBrakeFlag = true; } diff --git a/physics/mover.h b/physics/mover.h index dba810ef7..439574ce6 100644 --- a/physics/mover.h +++ b/physics/mover.h @@ -490,6 +490,11 @@ struct TCoupling CouplingSet CouplingFlag; // what the coupling joins; none: the vehicles only see each other class TMoverParameters *Connected = nullptr; /*co jest podlaczone*/ int ConnectedNr = 0; // Ra: od której strony podłączony do (Connected): 0=przód, 1=tył + // the end of the vehicle connected to, while there is one + VehicleEnd ConnectedEnd() const + { + return static_cast(ConnectedNr); + } double CForce = 0.0; /*sila z jaka dzialal*/ double Dist = 0.0; /*strzalka ugiecia zderzaków*/ bool CheckCollision = false; /*czy sprawdzac sile czy pedy*/ @@ -778,7 +783,7 @@ class TMoverParameters // internal data int permit_preset{-1}; // curent position of preset selection switch // vehicle parts - std::array instances; // door on the right and left side of the vehicle + BySide instances; // door on the right and left side of the vehicle // ld outputs bool is_locked{false}; double doorLockSpeed = 10.0; // predkosc przy ktorej wyzwalana jest blokada drzwi @@ -981,7 +986,7 @@ class TMoverParameters int LightsPosNo = 0; int LightsDefPos = 1; bool LightsWrap = false; - int Lights[2][18]; // pozycje świateł, przód - tył, 1 .. 16 (17 do lightsset) + ByEnd> Lights; // pozycje świateł, przód - tył, 1 .. 16 (17 do lightsset) // the cab interior light each light preset sets, from the optional third column of LightsList (bits of // lights_preset_cablight::flag); -1: the preset leaves the cab light as it is (eu07/maszyna#529) std::array LightsCabLight{[] { @@ -1021,7 +1026,7 @@ class TMoverParameters // 5% steps of the 6Dg), one at once when moved to a raising or lowering position, then one each time its SpeedUp / SpeedDown // covers a step; 0 (the default) changes it continuously double UniCtrlValStep{0.0}; - std::pair> PantsPreset{"0132", {0, 0}}; // pantograph preset switches; .first holds possible setups as chars, .second holds currently selected preset in each cab + std::pair> PantsPreset{"0132", {0, 0}}; // pantograph preset switches; .first holds possible setups as chars, .second holds currently selected preset in each cab /*-sekcja parametrow dla lokomotywy elektrycznej*/ TSchemeTable RList; /*lista rezystorow rozruchowych i polaczen silnikow, dla dizla: napelnienia*/ @@ -1216,11 +1221,11 @@ class TMoverParameters TRotation Rot{0.0, 0.0, 0.0}; glm::vec3 Front{}; std::string Name; /*nazwa wlasna*/ - TCoupling Couplers[2]; // urzadzenia zderzno-sprzegowe, polaczenia miedzy wagonami + ByEnd Couplers; // urzadzenia zderzno-sprzegowe, polaczenia miedzy wagonami // the physical coupler model covers the vehicle: it's in the player's train or in one the player's train closes in on // (vehicle_table::update_coupler_physics()); with couplerphysics all in eu07.ini every vehicle is covered bool CouplerPhysics{false}; - std::array Neighbours; // potential collision sources + ByEnd Neighbours; // potential collision sources bool Power110vIsAvailable = false; // cached availability of 110v power bool Power24vIsAvailable = false; // cached availability of 110v power double Power24vVoltage{0.0}; // cached battery voltage @@ -1294,7 +1299,7 @@ class TMoverParameters start_t CompressorStart{start_t::manual}; // whether the compressor is started manually, or another way start_t PantographCompressorStart{start_t::manual}; basic_valve PantsValve; - std::array Pantographs; + ByEnd Pantographs; bool PantAllDown{false}; double PantFrontVolt = 0.0; // pantograf pod napieciem? 'Winger 160404 double PantRearVolt = 0.0; @@ -1318,7 +1323,7 @@ class TMoverParameters water_pump WaterPump; water_heater WaterHeater; bool WaterCircuitsLink{false}; // optional connection between water circuits - std::array MotorBlowers; + ByEnd MotorBlowers; door_data Doors; float DoorsOpenWithPermitAfter{-1.f}; // remote open if permit button is held for specified time. NOTE: separate from door data as its cab control thing int DoorsPermitLightBlinking{0}; // when the doors permit signal light is blinking @@ -1541,7 +1546,7 @@ class TMoverParameters bool bPantKurek3 = true; // kurek trójdrogowy (pantografu): true=połączenie z ZG, false=połączenie z małą sprężarką // domyślnie zbiornik pantografu połączony jest ze zbiornikiem głównym bool PantAutoValve{false}; // type of installed pantograph compressor valve int iProblem = 0; // flagi problemów z taborem, aby AI nie musiało porównywać; 0=może jechać - int iLights[2]; // bity zapalonych świateł tutaj, żeby dało się liczyć pobór prądu + ByEnd iLights; // bity zapalonych świateł tutaj, żeby dało się liczyć pobór prądu // Status nowszego hebelka od przyciemniania swiatel/swiatel dlugich // 0 - swiatla wylaczone (opcja dziala tylko gdy w fiz zdefiniowano OffState w sekcji Switches; w przeciwnym wypadku pstryk startuje z wartoscia == 1 @@ -1600,12 +1605,25 @@ class TMoverParameters static double Distance(const TLocation &Loc1, const TLocation &Loc2, const TDimension &Dim1, const TDimension &Dim2); bool Attach(int ConnectNo, int ConnectToNr, TMoverParameters *ConnectTo, CouplingSet CouplingType, bool Enforce = false, bool Audible = true); int DettachStatus(int ConnectNo); + int DettachStatus(VehicleEnd const ConnectNo) + { + return DettachStatus(NumberOf(ConnectNo)); + } bool Dettach(int ConnectNo); - void damage_coupler(int const End); + // the same by the ends, where they are known to be ends + bool Attach(VehicleEnd const ConnectNo, VehicleEnd const ConnectToNr, TMoverParameters *ConnectTo, CouplingSet CouplingType, bool Enforce = false, bool Audible = true) + { + return Attach(NumberOf(ConnectNo), NumberOf(ConnectToNr), ConnectTo, CouplingType, Enforce, Audible); + } + bool Dettach(VehicleEnd const ConnectNo) + { + return Dettach(NumberOf(ConnectNo)); + } + void damage_coupler(VehicleEnd const End); // repairs the broken coupler of the end, and the one of the vehicle it was coupled with, so they can be coupled // again; the vehicles clear their coupler damage once neither of their couplers is broken. returns: whether there // was a broken coupler to repair - bool repair_coupler(int const End); + bool repair_coupler(VehicleEnd const End); void Derail(DerailReason Reason); // the velocity of the vehicles coupled to this one changes by the Change along the axis of this one [m/s], as the // legacy derailment changes the velocity of this one (physics.collisions new) @@ -1645,8 +1663,8 @@ class TMoverParameters // physics.collisions new: what the vehicle is for the defaults of its crush and its buffers, the crush curve and the // height of the buffers of an end, and how long the push of its ends held its wheels over the climbing limit collision::vehicle_kind collision_kind() const; - collision::crush_curve crush_curve_at(int End) const; - double buffer_height_at(int End) const; + collision::crush_curve crush_curve_at(VehicleEnd End) const; + double buffer_height_at(VehicleEnd End) const; collision::pushed_monitor pushed_off_monitor; // how the vehicle left the rails in a collision (physics.collisions new): overriding or pushed off, NONE otherwise DerailReason CollisionDerail{NONE}; @@ -1656,7 +1674,7 @@ class TMoverParameters // weaker end and may let one vehicle climb onto the other one, see collision.h. returns: whether it did, and the // velocities took the hit; the legacy collision takes the rest. physics.collisions monitor: the log tells what the // crush of the whole hit would be, once for a hit, nothing changes, and it returns false - bool crush_hit(int End, double dt); + bool crush_hit(VehicleEnd End, double dt); // the force pressing the ends pushes the vehicle off the track (physics.collisions new), the step travelled the // Distance [m]: the flange climbs while the wheels roll on void check_pushed_off(double dt, double Distance); @@ -1909,39 +1927,39 @@ class TMoverParameters double BrakeForceR(double ratio, double velocity) const; double BrakeForceP(double press, double velocity) const; double BrakeForce(const TTrackParam &Track); - double CouplerForce(int const End, double dt); - void CouplerStretchCheck(int End, double CF, double dt); + double CouplerForce(VehicleEnd const End, double dt); + void CouplerStretchCheck(VehicleEnd End, double CF, double dt); // whether the coupling at the end is computed by the physical model: couplerphysics set in eu07.ini, and this // vehicle or the one at the end covered by it (CouplerPhysics), or every vehicle with couplerphysics all - bool coupler_physics_at(int const End) const; + bool coupler_physics_at(VehicleEnd const End) const; // the force of the coupling at the end by the physical model (couplerphysics in eu07.ini), see couplerphysics.h - double coupler_force_physical(int const End, double const dt); + double coupler_force_physical(VehicleEnd const End, double const dt); // with the physical model: whether the vehicles at the end hit the stop of their springs at the last update and // still close in on it, so that they collide; a hit hard enough breaks the coupling or crushes the buffers - bool coupler_stop_hit(int const End, TMoverParameters &Other, int const OtherEnd); + bool coupler_stop_hit(VehicleEnd const End, TMoverParameters &Other, VehicleEnd const OtherEnd); // couples the automatic couplers of the end and of the other vehicle pressed against each other, unless the hit // is too fast for them to catch - void automatic_coupling(int const End, TMoverParameters &Other, int const OtherEnd); - void CollisionDetect(int const End, double const dt); + void automatic_coupling(VehicleEnd const End, TMoverParameters &Other, VehicleEnd const OtherEnd); + void CollisionDetect(VehicleEnd const End, double const dt); // closing speed of a collision [km/h] above which the vehicles involved may derail, adjusted for their mass ratio static constexpr double SafeCollisionVelocity{15.0}; // closing speed [km/h] of the End of this vehicle and the OtherEnd of the other vehicle it touches, along the coupler // axis: the sum of the speeds in a head-on collision, the difference in a rear-end one, negative when they part - double CollisionVelocity(int const End, TMoverParameters const &Other, int const OtherEnd) const; + double CollisionVelocity(VehicleEnd const End, TMoverParameters const &Other, VehicleEnd const OtherEnd) const; // velocity [m/s] of this vehicle relative to the other vehicle it touches with its End and the OtherEnd of the // other one, along this vehicle's axis - double CouplerVelocityDifference(int const End, TMoverParameters const &Other, int const OtherEnd) const; + double CouplerVelocityDifference(VehicleEnd const End, TMoverParameters const &Other, VehicleEnd const OtherEnd) const; // whether the automatic couplers at the End of this vehicle and the OtherEnd of the other one can catch each other on // contact, rather than the vehicles colliding (with crash damage enabled, only at a closing speed which doesn't derail them) - bool AutomaticCouplingSafe(int const End, TMoverParameters const &Other, int const OtherEnd) const; + bool AutomaticCouplingSafe(VehicleEnd const End, TMoverParameters const &Other, VehicleEnd const OtherEnd) const; // whether the control coupling (multiple-unit control) can join the End of this vehicle and the OtherEnd of the other // one: not between an electric and a diesel traction vehicle, unless both couplers name the same control system // (ControlType). Vehicles without own traction (cars, control trailers) take any. Global.control_coupling_engine_check // off allows it always (eu07/maszyna#520) - bool ControlCouplingAllowed(int const End, TMoverParameters const &Other, int const OtherEnd) const; + bool ControlCouplingAllowed(VehicleEnd const End, TMoverParameters const &Other, VehicleEnd const OtherEnd) const; // the CouplingType to join the End of this vehicle and the OtherEnd of the other one with, without the control coupling // when ControlCouplingAllowed() rules it out. a permanent coupling (of the vehicles of one unit) is kept whole - CouplingSet CompatibleCoupling(int const End, TMoverParameters const &Other, int const OtherEnd, CouplingSet const CouplingType) const; + CouplingSet CompatibleCoupling(VehicleEnd const End, TMoverParameters const &Other, VehicleEnd const OtherEnd, CouplingSet const CouplingType) const; // the horns of the Signal (WarningSignal bits) which have the air or the voltage they need to sound int SoundingHorns(int const Signal) const; // whether the signal lamps of the main circuit (line contactors, ground relay, motor overload relays) can light: @@ -2026,8 +2044,8 @@ class TMoverParameters bool FuelPumpSwitchOff(bool State, range_t const Notify = range_t::consist); // fuel pump state toggle bool OilPumpSwitch(bool State, range_t const Notify = range_t::consist); // oil pump state toggle bool OilPumpSwitchOff(bool State, range_t const Notify = range_t::consist); // oil pump state toggle - bool MotorBlowersSwitch(bool State, end const Side, range_t const Notify = range_t::consist); // traction motor fan state toggle - bool MotorBlowersSwitchOff(bool State, end const Side, range_t const Notify = range_t::consist); // traction motor fan state toggle + bool MotorBlowersSwitch(bool State, VehicleEnd const Side, range_t const Notify = range_t::consist); // traction motor fan state toggle + bool MotorBlowersSwitchOff(bool State, VehicleEnd const Side, range_t const Notify = range_t::consist); // traction motor fan state toggle bool CompartmentLightsSwitch(bool State, range_t const Notify = range_t::consist); // compartment lights state toggle bool CompartmentLightsSwitchOff(bool State, range_t const Notify = range_t::consist); // compartment lights state toggle bool MainSwitch(bool const State, range_t const Notify = range_t::consist); /*! wylacznik glowny*/ @@ -2115,7 +2133,7 @@ class TMoverParameters bool ResistorsFlagCheck(void) const; // sprawdzenie kontrolki oporow rozruchowych NBMX bool OperatePantographsValve(operation_t const State, range_t const Notify = range_t::consist); - bool OperatePantographValve(end const End, operation_t const State, range_t const Notify = range_t::consist); + bool OperatePantographValve(VehicleEnd const End, operation_t const State, range_t const Notify = range_t::consist); bool DropAllPantographs(bool const State, range_t const Notify = range_t::consist); void CheckEIMIC(double dt); // sprawdzenie i zmiana nastawy zintegrowanego nastawnika jazdy/hamowania @@ -2171,12 +2189,12 @@ class TMoverParameters /* funckje dla wagonow*/ bool AssignLoad(std::string const &Name, float const Amount = 0.f); bool LoadingDone(double LSpeed, std::string_view Loadname); - bool PermitDoors(side const Door, bool const State = true, range_t const Notify = range_t::consist); - void PermitDoors_(side const Door, bool const State = true); + bool PermitDoors(VehicleSide const Door, bool const State = true, range_t const Notify = range_t::consist); + void PermitDoors_(VehicleSide const Door, bool const State = true); bool ChangeDoorPermitPreset(int const Change, range_t const Notify = range_t::consist); bool PermitDoorStep(bool const State, range_t const Notify = range_t::consist); bool ChangeDoorControlMode(bool const State, range_t const Notify = range_t::consist); - bool OperateDoors(side const Door, bool const State, range_t const Notify = range_t::consist); + bool OperateDoors(VehicleSide const Door, bool const State, range_t const Notify = range_t::consist); bool LockDoors(bool const State, range_t const Notify = range_t::consist); bool signal_departure(bool const State, range_t const Notify = range_t::consist); // toggles departure warning void update_doors(double const Deltatime); // door controller update diff --git a/physics/vehicletypes.h b/physics/vehicletypes.h index 3e133b0f7..8d0a6bf61 100644 --- a/physics/vehicletypes.h +++ b/physics/vehicletypes.h @@ -12,6 +12,8 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include +#include #include #include @@ -126,8 +128,9 @@ enum DerailReason /// Fuzzy-logic probability weight: damage caused by wheel slip. #define p_slippdmg (1e-03) -/// Vehicle ends — front or rear (mutually exclusive). -enum end +/// Vehicle ends — front or rear (mutually exclusive). The numbers are the ones of the formats (the +/// couplers of the .scn, the network) and the places in a . +enum class VehicleEnd : int { /// Front end. front = 0, @@ -135,8 +138,8 @@ enum end rear = 1 }; -/// Vehicle sides — right or left (mutually exclusive). -enum side +/// Vehicle sides — right or left (mutually exclusive), the places in a . +enum class VehicleSide : int { /// Right side. right = 0, @@ -144,6 +147,66 @@ enum side left = 1 }; +/// Both ends and both sides, to go through them. +constexpr std::array VehicleEnds{VehicleEnd::front, VehicleEnd::rear}; +constexpr std::array VehicleSides{VehicleSide::right, VehicleSide::left}; + +/// The other end of the vehicle. +constexpr VehicleEnd Opposite(VehicleEnd const vehicleEnd) +{ + return vehicleEnd == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front; +} + +/// The other side of the vehicle. +constexpr VehicleSide Opposite(VehicleSide const vehicleSide) +{ + return vehicleSide == VehicleSide::right ? VehicleSide::left : VehicleSide::right; +} + +/// The number of the end or the side, where a format or a count needs it. +constexpr int NumberOf(VehicleEnd const vehicleEnd) +{ + return static_cast(vehicleEnd); +} + +constexpr int NumberOf(VehicleSide const vehicleSide) +{ + return static_cast(vehicleSide); +} + +/// The end of the given number (0 front, 1 rear), as the formats have it; the number is kept as it is. +constexpr VehicleEnd EndOf(int const number) +{ + return static_cast(number); +} + +/// The side of the given number (0 right, 1 left); the number is kept as it is. +constexpr VehicleSide SideOf(int const number) +{ + return static_cast(number); +} + +/// Two values, one for each end or side of a vehicle, indexed by the enum; by a number too, where a loop +/// counts them. +template +struct EnumPair : std::array +{ + using std::array::operator[]; + constexpr Value &operator[](Key const key) + { + return std::array::operator[](static_cast(key)); + } + constexpr Value const &operator[](Key const key) const + { + return std::array::operator[](static_cast(key)); + } +}; + +template +using ByEnd = EnumPair; +template +using BySide = EnumPair; + /// The kinds of connection a coupling between two vehicles makes. The numbers are the ones of the scenery /// files and the vehicle definitions (AllowedFlag, the coupling of a vehicle in a train), where they add up. enum class Coupling : unsigned @@ -710,4 +773,10 @@ struct neighbour_data TDynamicObject *vehicle{nullptr}; // detected obstacle int vehicle_end{-1}; // facing end of the obstacle float distance{10000.f}; // distance to the obstacle // NOTE: legacy value. TBD, TODO: use standard -1 instead? + + // the facing end of the obstacle there is + VehicleEnd FacingEnd() const + { + return static_cast(vehicle_end); + } }; diff --git a/rendering/common/scenewalk.cpp b/rendering/common/scenewalk.cpp index ebceae0ff..cb1b5621f 100644 --- a/rendering/common/scenewalk.cpp +++ b/rendering/common/scenewalk.cpp @@ -288,7 +288,7 @@ bool scene_walk::Render_lowpoly( TDynamicObject *Dynamic, float const Squaredist return true; } -bool scene_walk::Render_coupler_adapter( TDynamicObject *Dynamic, float const Squaredistance, int const End, bool const Alpha ) { +bool scene_walk::Render_coupler_adapter( TDynamicObject *Dynamic, float const Squaredistance, VehicleEnd const End, bool const Alpha ) { if( Dynamic->m_coupleradapters[ End ] == nullptr ) { return false; } gfx::walk_sync::vehicle_hold hold; @@ -296,11 +296,11 @@ bool scene_walk::Render_coupler_adapter( TDynamicObject *Dynamic, float const Sq auto const position { glm::dvec3 { 0.f, Dynamic->MoverParameters->Couplers[ End ].adapter_height, - ( Dynamic->MoverParameters->Couplers[ End ].adapter_length + Dynamic->MoverParameters->Dim.L * 0.5 ) * ( End == end::front ? 1 : -1 ) } }; + ( Dynamic->MoverParameters->Couplers[ End ].adapter_length + Dynamic->MoverParameters->Dim.L * 0.5 ) * ( End == VehicleEnd::front ? 1 : -1 ) } }; auto const angle { glm::vec3{ 0, - ( End == end::front ? 0 : 180 ), + ( End == VehicleEnd::front ? 0 : 180 ), 0 } }; if( Alpha ) { @@ -1931,8 +1931,8 @@ bool scene_walk::Render(TDynamicObject *Dynamic) Render( attachment, Dynamic->Material(), squaredistance ); } // optional coupling adapters - Render_coupler_adapter( Dynamic, squaredistance, end::front ); - Render_coupler_adapter( Dynamic, squaredistance, end::rear ); + Render_coupler_adapter( Dynamic, squaredistance, VehicleEnd::front ); + Render_coupler_adapter( Dynamic, squaredistance, VehicleEnd::rear ); // post-render cleanup if (gfx::vehicle_shade(Dynamic) > 0.0f) @@ -1957,8 +1957,8 @@ bool scene_walk::Render(TDynamicObject *Dynamic) Render( attachment, Dynamic->Material(), squaredistance ); } // optional coupling adapters - Render_coupler_adapter( Dynamic, squaredistance, end::front ); - Render_coupler_adapter( Dynamic, squaredistance, end::rear ); + Render_coupler_adapter( Dynamic, squaredistance, VehicleEnd::front ); + Render_coupler_adapter( Dynamic, squaredistance, VehicleEnd::rear ); if( Dynamic->mdLoad ) { // renderowanie nieprzezroczystego ładunku Render( Dynamic->mdLoad, Dynamic->Material(), squaredistance, { 0.f, Dynamic->LoadOffset, 0.f }, {} ); @@ -3099,8 +3099,8 @@ bool scene_walk::Render_Alpha(TDynamicObject *Dynamic) Render_Alpha( attachment, Dynamic->Material(), squaredistance ); } // optional coupling adapters - Render_coupler_adapter( Dynamic, squaredistance, end::front, true ); - Render_coupler_adapter( Dynamic, squaredistance, end::rear, true ); + Render_coupler_adapter( Dynamic, squaredistance, VehicleEnd::front, true ); + Render_coupler_adapter( Dynamic, squaredistance, VehicleEnd::rear, true ); if( Dynamic->mdLoad ) { // renderowanie nieprzezroczystego ładunku Render_Alpha( Dynamic->mdLoad, Dynamic->Material(), squaredistance, { 0.f, Dynamic->LoadOffset, 0.f }, {} ); diff --git a/rendering/common/scenewalk.h b/rendering/common/scenewalk.h index 37dbb1b7c..0db605644 100644 --- a/rendering/common/scenewalk.h +++ b/rendering/common/scenewalk.h @@ -19,6 +19,7 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include "physics/vehicletypes.h" #include "rendering/geometrybank.h" #include "rendering/openglcamera.h" #include "scene/scene.h" @@ -178,7 +179,7 @@ class scene_walk bool Render_cab(TDynamicObject const *Dynamic, float const Lightlevel, bool const Alpha = false); bool Render_interior(bool const Alpha = false); bool Render_lowpoly(TDynamicObject *Dynamic, float const Squaredistance, bool const Setup, bool const Alpha = false); - bool Render_coupler_adapter(TDynamicObject *Dynamic, float const Squaredistance, int const End, bool const Alpha = false); + bool Render_coupler_adapter(TDynamicObject *Dynamic, float const Squaredistance, VehicleEnd const End, bool const Alpha = false); void Render(TMemCell *Memcell); void Render_Alpha(scene::basic_region *Region); void Render_Alpha(cell_sequence::reverse_iterator First, cell_sequence::reverse_iterator Last); diff --git a/rendering/lightarray.cpp b/rendering/lightarray.cpp index f34a4d183..eef1c6a2f 100644 --- a/rendering/lightarray.cpp +++ b/rendering/lightarray.cpp @@ -23,8 +23,8 @@ light_array::insert( TDynamicObject const *Owner ) { // we're only storing lights for locos, which have two sets of lights, front and rear // for a more generic role this function would have to be tweaked to add vehicle type-specific light combinations - data.emplace_back( Owner, end::front ); - data.emplace_back( Owner, end::rear ); + data.emplace_back( Owner, NumberOf( VehicleEnd::front ) ); + data.emplace_back( Owner, NumberOf( VehicleEnd::rear ) ); } void @@ -39,7 +39,7 @@ light_array::update() { for( auto &light : data ) { // update light parameters to match current data of the owner - if( light.index == end::front ) { + if( EndOf( light.index ) == VehicleEnd::front ) { // front light set light.position = light.owner->GetPosition() + ( light.owner->VectorFront() * ( std::max( 0.0, light.owner->GetLength() * 0.5 - 2.0 ) ) );// +( light.owner->VectorUp() * 0.25 ); light.direction = glm::make_vec3( glm::value_ptr(light.owner->VectorFront()) ); // TODO: It is needed to get value_ptr and then make_vec3? @@ -56,7 +56,7 @@ light_array::update() { || ( true == light.owner->MoverParameters->Power110vIsAvailable ) ) { // with power on, the intensity depends on the state of activated switches // first we cross-check the list of enabled lights with the lights installed in the vehicle... - auto const lights { light.owner->MoverParameters->iLights[ light.index ] & light.owner->LightList( static_cast( light.index ) ) }; + auto const lights { light.owner->MoverParameters->iLights[ light.index ] & light.owner->LightList( static_cast( light.index ) ) }; // ...then check their individual state light.count = 0 + ( ( lights & light::headlight_left ) ? 1 : 0 ) @@ -67,7 +67,7 @@ light_array::update() { // set intensity if( light.count > 0 ) { - bool isEnabled = light.index == end::front ? !light.owner->HeadlightsAoff : !light.owner->HeadlightsBoff; + bool isEnabled = EndOf( light.index ) == VehicleEnd::front ? !light.owner->HeadlightsAoff : !light.owner->HeadlightsBoff; light.intensity = std::max(0.0f, std::log((float)light.count + 1.0f)); if (light.owner->DimHeadlights && !light.owner->HighBeamLights && isEnabled) // tylko przyciemnione diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index 6b573e1ea..be6fc0000 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -74,19 +74,19 @@ std::uint32_t devices_of(TMoverParameters const &Occupied, TMoverParameters cons namespace device = blackbox::cab_devices; auto const on{[](bool const State, std::uint32_t const Bit) { return State ? Bit : 0u; }}; return on(Occupied.Battery || Controlling.Battery, device::battery) | on(Controlling.Mains, device::main_breaker) | - on(Controlling.Pantographs[end::front].is_active, device::pantograph_front) | on(Controlling.Pantographs[end::rear].is_active, device::pantograph_rear) | + on(Controlling.Pantographs[VehicleEnd::front].is_active, device::pantograph_front) | on(Controlling.Pantographs[VehicleEnd::rear].is_active, device::pantograph_rear) | on(Controlling.ConverterFlag, device::converter) | on(Controlling.CompressorFlag, device::compressor) | on(Controlling.StLinFlag, device::line_contactors) | on(Controlling.FuseFlag, device::overload_relay) | on(Controlling.SandDose, device::sanding) | on(Occupied.WarningSignal != 0, device::horn) | - on(false == Occupied.Doors.instances[side::left].is_closed, device::doors_left) | - on(false == Occupied.Doors.instances[side::right].is_closed, device::doors_right) | on(Occupied.Radio, device::radio) | + on(false == Occupied.Doors.instances[VehicleSide::left].is_closed, device::doors_left) | + on(false == Occupied.Doors.instances[VehicleSide::right].is_closed, device::doors_right) | on(Occupied.Radio, device::radio) | on(Controlling.Heating, device::heating) | on(Occupied.SpringBrake.IsActive, device::spring_brake) | on(Controlling.ShuntMode, device::shunt_mode) | // the doors as the cab works them: the permits, the departure signal, the steps and the lock - on(Occupied.DepartureSignal, device::departure_signal) | on(Occupied.Doors.instances[side::left].open_permit, device::door_permit_left) | - on(Occupied.Doors.instances[side::right].open_permit, device::door_permit_right) | on(Occupied.Doors.step_enabled, device::door_step) | + on(Occupied.DepartureSignal, device::departure_signal) | on(Occupied.Doors.instances[VehicleSide::left].open_permit, device::door_permit_left) | + on(Occupied.Doors.instances[VehicleSide::right].open_permit, device::door_permit_right) | on(Occupied.Doors.step_enabled, device::door_step) | on(Occupied.Doors.lock_enabled, device::door_lock) | on(Occupied.Doors.is_locked, device::doors_locked) | on(Occupied.Hamulec != nullptr && Occupied.Hamulec->Releaser(), device::brake_releaser) | on(Controlling.FuelPump.is_active, device::fuel_pump) | on(Controlling.OilPump.is_active, device::oil_pump) | - on(Controlling.MotorBlowers[end::front].is_active || Controlling.MotorBlowers[end::rear].is_active, device::motor_blowers) | + on(Controlling.MotorBlowers[VehicleEnd::front].is_active || Controlling.MotorBlowers[VehicleEnd::rear].is_active, device::motor_blowers) | on(Controlling.diesel.heat.engine_is_hot, device::engine_hot) | on(Controlling.SpeedCtrl && Controlling.SpeedCtrlUnit.IsActive, device::speed_control); } @@ -112,7 +112,7 @@ std::uint16_t outward_lights(TDynamicObject const *Vehicle, bool const Head) { if (Vehicle == nullptr || Vehicle->MoverParameters == nullptr) return 0; auto const along{Vehicle->iDirection > 0}; - return static_cast(Vehicle->MoverParameters->iLights[Head == along ? end::front : end::rear]); + return static_cast(Vehicle->MoverParameters->iLights[Head == along ? VehicleEnd::front : VehicleEnd::rear]); } // the lamps the vehicle has at that end: the driver checks a pattern against those of it there are @@ -120,7 +120,7 @@ std::uint16_t outward_lamps(TDynamicObject const *Vehicle, bool const Head) { if (Vehicle == nullptr) return 0; auto const along{Vehicle->iDirection > 0}; - return static_cast(Vehicle->LightList(Head == along ? end::front : end::rear)); + return static_cast(Vehicle->LightList(Head == along ? VehicleEnd::front : VehicleEnd::rear)); } // the scenario file without the starter's $, the folders and the extension, safe for a file name @@ -438,8 +438,8 @@ void blackbox_recorder::write_cab() { auto const order{owner->order_current()}; sample.movement = order.HasAny(DriverOrder::obeyTrain) ? blackbox::movements::train : order.HasAny(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect) ? blackbox::movements::shunting : blackbox::movements::other; - sample.light_hint_head = static_cast(owner->light_hint(end::front)); - sample.light_hint_tail = static_cast(owner->light_hint(end::rear)); + sample.light_hint_head = static_cast(owner->light_hint(VehicleEnd::front)); + sample.light_hint_tail = static_cast(owner->light_hint(VehicleEnd::rear)); } sample.odometer_km = static_cast(occupied->DistCounter); sample.driving = driver_of(*vehicle); @@ -462,10 +462,10 @@ void blackbox_recorder::write_cab() { sample.voltage = static_cast(controlling->EngineVoltage); sample.engine_rpm = static_cast(std::abs(controlling->enrot) * 60.0); // the lights at the ends of the train: of the vehicles at its ends, at their ends turned away from the rest - sample.lights_head = outward_lights(owner != nullptr ? owner->Vehicle(end::front) : vehicle, true); - sample.lights_tail = outward_lights(owner != nullptr ? owner->Vehicle(end::rear) : vehicle, false); - sample.equipped_head = outward_lamps(owner != nullptr ? owner->Vehicle(end::front) : vehicle, true); - sample.equipped_tail = outward_lamps(owner != nullptr ? owner->Vehicle(end::rear) : vehicle, false); + sample.lights_head = outward_lights(owner != nullptr ? owner->Vehicle(VehicleEnd::front) : vehicle, true); + sample.lights_tail = outward_lights(owner != nullptr ? owner->Vehicle(VehicleEnd::rear) : vehicle, false); + sample.equipped_head = outward_lamps(owner != nullptr ? owner->Vehicle(VehicleEnd::front) : vehicle, true); + sample.equipped_tail = outward_lamps(owner != nullptr ? owner->Vehicle(VehicleEnd::rear) : vehicle, false); auto const &security{controlling->SecuritySystem}; namespace flag = blackbox::security_flags; sample.security = static_cast((security.is_vigilance_blinking() ? flag::vigilance : 0) | (security.is_cabsignal_blinking() ? flag::cabsignal : 0) | @@ -493,7 +493,7 @@ void blackbox_recorder::write_cab() { sample.converter_fill = static_cast(controlling->torqueConverter.fill); // the brakes of the whole train: the highest of its cylinders, from the head to the tail auto brakes{occupied->BrakePress}; - for (auto const *each{owner != nullptr ? owner->Vehicle(end::front) : nullptr}; each != nullptr; each = each->Next()) + for (auto const *each{owner != nullptr ? owner->Vehicle(VehicleEnd::front) : nullptr}; each != nullptr; each = each->Next()) if (each->MoverParameters != nullptr) brakes = std::max(brakes, each->MoverParameters->BrakePress); sample.consist_brake_cylinder = static_cast(brakes); @@ -646,7 +646,7 @@ void blackbox_recorder::look_at_couplers() { change.flags = static_cast(now.flags); change.previous_flags = static_cast(entry.couplers_known ? before.flags : 0); change.previous_other = entry.couplers_known ? known_id(before.other) : blackbox::no_vehicle; - change.position = vehicle->CouplerPosition(static_cast(side)); + change.position = vehicle->CouplerPosition(static_cast(side)); m_writer->coupling(change); } entry.couplers_known = true; diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp index 477203061..ab3ec3a56 100644 --- a/simulation/simulation.cpp +++ b/simulation/simulation.cpp @@ -461,7 +461,7 @@ void state_manager::process_commands() { if (commanddata.command == user_command::repaircoupler) { if (auto *vehicle{simulation::Vehicles.find(commanddata.payload)}; vehicle != nullptr) { - vehicle->MoverParameters->repair_coupler(static_cast(commanddata.param1) == end::rear ? end::rear : end::front); + vehicle->MoverParameters->repair_coupler(EndOf(static_cast(commanddata.param1)) == VehicleEnd::rear ? VehicleEnd::rear : VehicleEnd::front); } } diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index 7c4644868..a12113496 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -580,8 +580,8 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch } if( vehicle->MoverParameters->CategoryFlag == 1 // trains only - && ( (vehicle->LightList(end::front) & (light::headlight_left | light::headlight_right | light::headlight_upper)) != 0 - || (vehicle->LightList(end::rear) & (light::headlight_left | light::headlight_right | light::headlight_upper)) != 0 ) ) { + && ( (vehicle->LightList(VehicleEnd::front) & (light::headlight_left | light::headlight_right | light::headlight_upper)) != 0 + || (vehicle->LightList(VehicleEnd::rear) & (light::headlight_left | light::headlight_right | light::headlight_upper)) != 0 ) ) { simulation::Lights.insert( vehicle ); } } @@ -1692,7 +1692,7 @@ state_serializer::deserialize_dynamic( cParser &Input, scene::scratch_data &Scra } // automatically establish permanent connections for couplers which specify them in their definitions if( coupling != 0 - && vehicle->MoverParameters->Couplers[(offset == -1.0 ? end::front : end::rear)].AllowedFlag & Coupling::permanent ) { + && vehicle->MoverParameters->Couplers[(offset == -1.0 ? VehicleEnd::front : VehicleEnd::rear)].AllowedFlag & Coupling::permanent ) { coupling = ( CouplingSet::FromBits( coupling ) | Coupling::permanent ).Bits(); } if( true == Scratchpad.trainset.is_open ) { diff --git a/tests/unit/consist.cpp b/tests/unit/consist.cpp index 141abe5af..2c17ca5b8 100644 --- a/tests/unit/consist.cpp +++ b/tests/unit/consist.cpp @@ -21,8 +21,8 @@ vehicle &consist::add(definition const &Definition, int Cab, CouplingSet const c position = m_positions.back() - 0.5 * (last.Dim.L + mover.Dim.L) - Gap; mover.Loc = TLocation{position, 0.0, 0.0}; if (false == couplings.Empty()) { - last.Attach(end::rear, end::front, &mover, couplings, true, false); - mover.Attach(end::front, end::rear, &last, couplings, true, false); + last.Attach(VehicleEnd::rear, VehicleEnd::front, &mover, couplings, true, false); + mover.Attach(VehicleEnd::front, VehicleEnd::rear, &last, couplings, true, false); } } else { @@ -39,15 +39,15 @@ void consist::update_neighbours() { // TDynamicObject::update_neighbours(), for vehicles coupled in a line for (std::size_t i = 0; i < m_vehicles.size(); ++i) { auto &mover{m_vehicles[i]->mover()}; - for (int end = end::front; end <= end::rear; ++end) { + for (auto const end : VehicleEnds) { auto &neighbour{mover.Neighbours[end]}; - auto const other{end == end::front ? static_cast(i) - 1 : static_cast(i) + 1}; + auto const other{end == VehicleEnd::front ? static_cast(i) - 1 : static_cast(i) + 1}; if (other < 0 || other >= static_cast(m_vehicles.size())) { neighbour = neighbour_data(); continue; } auto const &othermover{m_vehicles[other]->mover()}; - auto const otherend{end == end::front ? end::rear : end::front}; + auto const otherend{Opposite(end)}; auto const distance{TMoverParameters::CouplerDist(&mover, &othermover) - mover.Couplers[end].adapter_length - othermover.Couplers[otherend].adapter_length}; // a vehicle not coupled is a collision source when it's within the range the game scans @@ -56,7 +56,7 @@ void consist::update_neighbours() { continue; } neighbour.vehicle = reinterpret_cast(m_objects[other].data()); // NOSONAR see m_objects - neighbour.vehicle_end = otherend; + neighbour.vehicle_end = NumberOf(otherend); neighbour.distance = static_cast(distance); } } diff --git a/tests/unit/drive.cpp b/tests/unit/drive.cpp index 7663d8363..03785730e 100644 --- a/tests/unit/drive.cpp +++ b/tests/unit/drive.cpp @@ -118,7 +118,7 @@ void raise_pantographs(driven const &Driven) { pantographs.PantCompFlag = false; } Driven.cab.OperatePantographsValve(operation_t::enable); - Driven.cab.OperatePantographValve(end::rear, operation_t::enable); + Driven.cab.OperatePantographValve(VehicleEnd::rear, operation_t::enable); } // the line breaker closed, which it does only with the controller at zero, and after the relays are reset @@ -143,7 +143,7 @@ void close_line_breaker(driven const &Driven) { void switch_auxiliaries_on(TMoverParameters &Cab) { Cab.ConverterSwitch(true); Cab.CompressorSwitch(true); - for (auto const side : {end::front, end::rear}) { + for (auto const side : VehicleEnds) { if (Cab.MotorBlowers[side].speed != 0) { Cab.MotorBlowersSwitchOff(false, side); Cab.MotorBlowersSwitch(true, side); diff --git a/tests/unit/golden.cpp b/tests/unit/golden.cpp index 363d97718..da6a3ce8c 100644 --- a/tests/unit/golden.cpp +++ b/tests/unit/golden.cpp @@ -112,8 +112,8 @@ std::vector doors() { std::vector result{ {"DoorsLocked", [](auto const &M) { return M.Doors.is_locked ? 1.0 : 0.0; }}, }; - for (int side : {side::right, side::left}) { - auto const name{std::string{side == side::right ? "Right" : "Left"}}; + for (auto const side : VehicleSides) { + auto const name{std::string{side == VehicleSide::right ? "Right" : "Left"}}; result.emplace_back(name + "Position", [side](auto const &M) { return M.Doors.instances[side].position; }); result.emplace_back(name + "Step", [side](auto const &M) { return M.Doors.instances[side].step_position; }); result.emplace_back(name + "Open", [side](auto const &M) { return M.Doors.instances[side].is_open ? 1.0 : 0.0; }); diff --git a/tests/unit/scenario.h b/tests/unit/scenario.h index 54678af5d..29a9f5592 100644 --- a/tests/unit/scenario.h +++ b/tests/unit/scenario.h @@ -17,7 +17,7 @@ namespace test { // scenario.add("elf_v1/21we-a", 1).add("elf_v1/21we-b").add("elf_v1/21we-c"); // scenario.start_up(); // scenario.act("open left"); -// scenario.cab().OperateDoors(side::left, true); +// scenario.cab().OperateDoors(VehicleSide::left, true); // scenario.wait(10.0); // scenario.check(); class scenario { diff --git a/tests/unit/test_auxiliaries.cpp b/tests/unit/test_auxiliaries.cpp index bb823a4cf..4da5c1f51 100644 --- a/tests/unit/test_auxiliaries.cpp +++ b/tests/unit/test_auxiliaries.cpp @@ -38,8 +38,8 @@ TEST_CASE("auxiliaries: the battery drained by the lights and the pantographs' c REQUIRE(eu07.BatteryVoltage == doctest::Approx(eu07.NominalBatteryVoltage)); scenario.act("converter off, lights on, small compressor on"); eu07.ConverterSwitch(false); - eu07.iLights[end::front] = 1 | 2 | 4; - eu07.iLights[end::rear] = 16; + eu07.iLights[VehicleEnd::front] = 1 | 2 | 4; + eu07.iLights[VehicleEnd::rear] = 16; eu07.PantCompFlag = true; scenario.wait(30.0); CHECK(eu07.BatteryVoltage < 0.83 * eu07.NominalBatteryVoltage); diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index efc144e69..bb0395df7 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -116,7 +116,7 @@ bool derailed(TMoverParameters const &Vehicle) { } double crush_of(TMoverParameters const &Vehicle) { - return std::max(Vehicle.Couplers[end::front].crush, Vehicle.Couplers[end::rear].crush); + return std::max(Vehicle.Couplers[VehicleEnd::front].crush, Vehicle.Couplers[VehicleEnd::rear].crush); } // a mixed freight train as the PoC has it: every third wagon from the given one an empty two-axle 3WL (10.5 t), the @@ -172,7 +172,7 @@ crash_outcome freight_crash(double const Speed, double const Radius, double cons for (std::size_t i = 0; i < train.size(); ++i) { auto const &vehicle{train[i].mover()}; auto const name{i < standing ? std::format("standing {}", standing - 1 - i) : i == standing ? std::string{"locomotive"} : std::format("running {}", i - standing - 1)}; - for (auto const end : {end::front, end::rear}) { + for (auto const end : VehicleEnds) { if (vehicle.Couplers[end].crush >= cl::crush_mark) { ++result.crushed; } @@ -190,7 +190,7 @@ crash_outcome freight_crash(double const Speed, double const Radius, double cons } } for (std::size_t i = 0; i + 1 < train.size(); ++i) { - result.broken += train[i]->Couplers[end::rear].broken; + result.broken += train[i]->Couplers[VehicleEnd::rear].broken; } return result; } @@ -204,16 +204,16 @@ double locomotive_into_wagon(double const Speed, double const Dt) { // behind the wagon, running forwards into its rear end auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, Coupling::none, Speed, 0.5)}; train.run(3.0, {}, Dt); - return wagon->Couplers[end::rear].crush + locomotive->Couplers[end::front].crush; + return wagon->Couplers[VehicleEnd::rear].crush + locomotive->Couplers[VehicleEnd::front].crush; } // the energy the crush of both ends of the pair took, by their curves [J] -double crush_energy(TMoverParameters const &First, int const FirstEnd, TMoverParameters const &Second, int const SecondEnd) { +double crush_energy(TMoverParameters const &First, VehicleEnd const FirstEnd, TMoverParameters const &Second, VehicleEnd const SecondEnd) { return First.crush_curve_at(FirstEnd).energy(0.0, First.Couplers[FirstEnd].crush) + Second.crush_curve_at(SecondEnd).energy(0.0, Second.Couplers[SecondEnd].crush); } // what the buffers of EN 15551 of the two ends take in [J] -double capacity_of(TMoverParameters const &First, int const FirstEnd, TMoverParameters const &Second, int const SecondEnd) { +double capacity_of(TMoverParameters const &First, VehicleEnd const FirstEnd, TMoverParameters const &Second, VehicleEnd const SecondEnd) { return cl::buffer_capacity(First.Couplers[FirstEnd].collision, First.collision_kind()) + cl::buffer_capacity(Second.Couplers[SecondEnd].collision, Second.collision_kind()); } @@ -238,9 +238,9 @@ contact_outcome contact(definition const &Front, definition const &Back, double auto &back{train.add(Back, 0, Coupling::none, Speed, Gap)}; train.run(Seconds, {}, Dt); contact_outcome result; - result.crush = front->Couplers[end::rear].crush + back->Couplers[end::front].crush; - result.energy = crush_energy(front.mover(), end::rear, back.mover(), end::front); - result.available = std::max(0.0, relative_energy(front.mover(), back.mover(), Speed * kmh) - capacity_of(front.mover(), end::rear, back.mover(), end::front)); + result.crush = front->Couplers[VehicleEnd::rear].crush + back->Couplers[VehicleEnd::front].crush; + result.energy = crush_energy(front.mover(), VehicleEnd::rear, back.mover(), VehicleEnd::front); + result.available = std::max(0.0, relative_energy(front.mover(), back.mover(), Speed * kmh) - capacity_of(front.mover(), VehicleEnd::rear, back.mover(), VehicleEnd::front)); result.derailed = derailed(front.mover()) || derailed(back.mover()); return result; } @@ -251,7 +251,7 @@ definition coach(double const Mass) { } // Y / Q of the leading wheel of the vehicle at the end pressed in by its coupling, as check_pushed_off() takes it -double pushed_ratio_of(TMoverParameters const &Vehicle, int const End, double const OtherLength, double const Radius) { +double pushed_ratio_of(TMoverParameters const &Vehicle, VehicleEnd const End, double const OtherLength, double const Radius) { cl::pushed_vehicle pushed; pushed.mass = Vehicle.TotalMass - Vehicle.Mred; pushed.axles = Vehicle.NAxles > 0 ? Vehicle.NAxles : 4; @@ -259,7 +259,7 @@ double pushed_ratio_of(TMoverParameters const &Vehicle, int const End, double co pushed.pivots = Vehicle.BDist; pushed.axle_base = Vehicle.ADist > 0.0 ? Vehicle.ADist : Vehicle.BDist; cl::pushed_end end; - end.force = std::max(0.0, (End == end::front ? -1.0 : 1.0) * Vehicle.Couplers[End].CForce); + end.force = std::max(0.0, (End == VehicleEnd::front ? -1.0 : 1.0) * Vehicle.Couplers[End].CForce); end.other_length = OtherLength; end.crush = Vehicle.Couplers[End].crush; return cl::pushed_ratio(pushed, end, Radius); @@ -591,8 +591,8 @@ TEST_CASE("collisions: a locomotive at its starting effort against a braked trai auto pushed{0.0}; auto worst{0.0}; auto const watch = [&]() { - pushed = std::max(pushed, -locomotive->Couplers[end::front].CForce); - worst = std::max(worst, pushed_ratio_of(empty.mover(), end::rear, locomotive->Dim.L, line.radius)); + pushed = std::max(pushed, -locomotive->Couplers[VehicleEnd::front].CForce); + worst = std::max(worst, pushed_ratio_of(empty.mover(), VehicleEnd::rear, locomotive->Dim.L, line.radius)); }; // the line contactors close at the first position, once their delay and the pressure switch let them locomotive->IncMainCtrl(1); @@ -631,8 +631,8 @@ TEST_CASE("collisions: a locomotive running onto an empty wagon at 9 km/h doesn' auto over{0}; // steps past the climbing limit for (int step = 0; step < 500; ++step) { train.step(curve); - pushed = std::max(pushed, empty->Couplers[end::rear].CForce); - auto const ratio{pushed_ratio_of(empty.mover(), end::rear, locomotive->Dim.L, curve.radius)}; + pushed = std::max(pushed, empty->Couplers[VehicleEnd::rear].CForce); + auto const ratio{pushed_ratio_of(empty.mover(), VehicleEnd::rear, locomotive->Dim.L, curve.radius)}; worst = std::max(worst, ratio); over += ratio >= derailment::climbing_limit; } @@ -684,7 +684,7 @@ TEST_CASE("collisions: a repaired vehicle has its ends rebuilt and is back on th auto &wagon{add_loaded(train, Coupling::none, 0.0, 0.0)}; auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, Coupling::none, 30.0, 0.5)}; train.run(3.0); - REQUIRE(wagon->Couplers[end::rear].crush + locomotive->Couplers[end::front].crush > cl::override_crush); + REQUIRE(wagon->Couplers[VehicleEnd::rear].crush + locomotive->Couplers[VehicleEnd::front].crush > cl::override_crush); REQUIRE((derailed(wagon.mover()) || derailed(locomotive.mover()))); for (auto *vehicle : {&wagon, &locomotive}) { auto &mover{vehicle->mover()}; @@ -708,12 +708,12 @@ TEST_CASE("collisions: a repaired vehicle has its ends rebuilt and is back on th TEST_CASE("collisions: the repair of a coupler torn off by the crush rebuilds its end") { vehicle wagon{definition::fiz("430w_v2/430w")}; - auto &coupler{wagon->Couplers[end::rear]}; + auto &coupler{wagon->Couplers[VehicleEnd::rear]}; coupler.crush = 0.3; coupler.broken = true; coupler.hit_force = 2.0e6; wagon->DamageFlag.Set(VehicleDamage::coupling); - REQUIRE(wagon->repair_coupler(end::rear)); + REQUIRE(wagon->repair_coupler(VehicleEnd::rear)); CHECK(coupler.crush == 0.0); CHECK(coupler.hit_force == 0.0); CHECK_FALSE(coupler.broken); @@ -768,7 +768,7 @@ TEST_CASE("collisions: the legacy rule with physics.collisions old, the crush wi train.run(10.0); CHECK(derailed(train[0].mover()) == (physical ? frontout_new : frontout_old)); CHECK(derailed(train[1].mover()) == (physical ? backout_new : backout_old)); - auto const crush{train[0]->Couplers[end::rear].crush + train[1]->Couplers[end::front].crush}; + auto const crush{train[0]->Couplers[VehicleEnd::rear].crush + train[1]->Couplers[VehicleEnd::front].crush}; if (physical) { MESSAGE(name, ": crush ", crush, " m"); CHECK(crush > 0.05); @@ -808,7 +808,7 @@ TEST_CASE("collisions: the model of the collisions goes apart from the one of th train.add(definition::fiz("4e_v1/4e"), 0, Coupling::none, 25.0, 20.0); train.run(10.0); Global.derailment = previous; - auto const crush{train[0]->Couplers[end::rear].crush + train[1]->Couplers[end::front].crush}; + auto const crush{train[0]->Couplers[VehicleEnd::rear].crush + train[1]->Couplers[VehicleEnd::front].crush}; CHECK((crush > 0.05) == (collisions == global_settings::collision_model::physical)); } } @@ -849,24 +849,24 @@ TEST_CASE("collisions: automatic couplers hit too fast don't catch, the ends cru CAPTURE(speed); vehicle moving{automatic, speed, "moving"}; vehicle standing{automatic, 0.0, "standing"}; - test::pair pair{moving, end::front, standing, end::rear, 1.0}; + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 1.0}; auto coupled{false}; auto fast{false}; // coupled while closing in faster than the couplers catch for (int i = 0; i < 1000; ++i) { - auto const closing{moving->CollisionVelocity(end::front, standing.mover(), end::rear)}; + auto const closing{moving->CollisionVelocity(VehicleEnd::front, standing.mover(), VehicleEnd::rear)}; pair.step(); fast = fast || (pair.coupled() && false == coupled && closing > TMoverParameters::SafeCollisionVelocity); coupled = coupled || pair.coupled(); } - auto const crush{moving->Couplers[end::front].crush + standing->Couplers[end::rear].crush}; + auto const crush{moving->Couplers[VehicleEnd::front].crush + standing->Couplers[VehicleEnd::rear].crush}; MESSAGE(speed, " km/h: crush ", crush, " m, derailed ", derailed(moving.mover()), " ", derailed(standing.mover()), ", coupled later ", coupled); CHECK_FALSE(fast); CHECK(crush > 0.0); // crushed past the draw gear, the coupler is gone; short of it, the wagons may roll together again slowly // after the hit, and couple then - if (std::max(moving->Couplers[end::front].crush, standing->Couplers[end::rear].crush) >= cl::draw_gear_crush) { + if (std::max(moving->Couplers[VehicleEnd::front].crush, standing->Couplers[VehicleEnd::rear].crush) >= cl::draw_gear_crush) { CHECK_FALSE(coupled); - CHECK((moving->Couplers[end::front].broken || standing->Couplers[end::rear].broken)); + CHECK((moving->Couplers[VehicleEnd::front].broken || standing->Couplers[VehicleEnd::rear].broken)); } // the two alike: neither climbs onto the other until the crush is deep enough for both to CHECK(derailed(moving.mover()) == derailed(standing.mover())); @@ -886,7 +886,7 @@ TEST_CASE("collisions: road vehicles keep the legacy rule") { road.run(5.0); CHECK(derailed(road[0].mover())); CHECK(derailed(road[1].mover())); - CHECK(road[0]->Couplers[end::rear].crush == 0.0); + CHECK(road[0]->Couplers[VehicleEnd::rear].crush == 0.0); CHECK(road[1]->CollisionDerail == NONE); CHECK(road[0]->crush_reports + road[1]->crush_reports == 0); } @@ -954,7 +954,7 @@ TEST_CASE("collisions: identical units built to EN 15227 at 36 km/h") { double inner; int derailed; bool higher; - } result{train[1]->Couplers[end::rear].crush + train[2]->Couplers[end::front].crush, std::max(crush_of(train[0].mover()), crush_of(train[3].mover())), 0, + } result{train[1]->Couplers[VehicleEnd::rear].crush + train[2]->Couplers[VehicleEnd::front].crush, std::max(crush_of(train[0].mover()), crush_of(train[3].mover())), 0, derailed(train[2].mover())}; for (std::size_t i = 0; i < train.size(); ++i) { result.derailed += derailed(train[i].mover()); @@ -997,9 +997,9 @@ TEST_CASE("collisions: the buffers of EN 15551 of an end take in their energy, o CHECK(cl::buffer_capacity(category_c, cl::vehicle_kind::wagon) == doctest::Approx(140.0e3)); // the key of the .fiz vehicle wagon{definition::load("wagon").set("BuffCoupl", "BufferCategory", "B")}; - REQUIRE(wagon->Couplers[end::front].collision.buffers.has_value()); - CHECK(*wagon->Couplers[end::front].collision.buffers == cl::buffer_category::B); - CHECK(cl::buffer_capacity(wagon->Couplers[end::rear].collision, wagon->collision_kind()) == doctest::Approx(100.0e3)); + REQUIRE(wagon->Couplers[VehicleEnd::front].collision.buffers.has_value()); + CHECK(*wagon->Couplers[VehicleEnd::front].collision.buffers == cl::buffer_category::B); + CHECK(cl::buffer_capacity(wagon->Couplers[VehicleEnd::rear].collision, wagon->collision_kind()) == doctest::Approx(100.0e3)); } TEST_CASE("collisions: the budget of a contact, by what the hit brings to the buffers") { @@ -1207,7 +1207,7 @@ TEST_CASE("collisions: two coaches (36 t and 41.6 t) at 8 km/h don't crush, nor REQUIRE(derailed(wall.mover())); auto &running{train.add(heavy, 0, Coupling::none, 5.0, gap)}; train.run(5.0); - CHECK(wall->Couplers[end::rear].crush + running->Couplers[end::front].crush == 0.0); + CHECK(wall->Couplers[VehicleEnd::rear].crush + running->Couplers[VehicleEnd::front].crush == 0.0); CHECK(running->CollisionDerail == NONE); } } @@ -1242,7 +1242,7 @@ TEST_CASE("collisions: a locomotive pushing a standing braked train at full powe auto pushed{0.0}; auto seconds{0}; // pushing with 100 kN or more auto const push = [&]() { - auto const force{std::max(0.0, -locomotive->Couplers[end::front].CForce)}; + auto const force{std::max(0.0, -locomotive->Couplers[VehicleEnd::front].CForce)}; pushed = std::max(pushed, force); seconds += force >= 100.0e3; }; @@ -1328,12 +1328,12 @@ train_damage damage_of(consist &Train) { for (std::size_t i = 0; i < Train.size(); ++i) { auto const &vehicle{Train[i].mover()}; result.crush = std::max(result.crush, crush_of(vehicle)); - for (auto const end : {end::front, end::rear}) { + for (auto const end : VehicleEnds) { result.energy += vehicle.crush_curve_at(end).energy(0.0, vehicle.Couplers[end].crush); } result.derailed += vehicle.CollisionDerail != NONE; if (i + 1 < Train.size()) { - result.broken += vehicle.Couplers[end::rear].broken; + result.broken += vehicle.Couplers[VehicleEnd::rear].broken; } if (crush_of(vehicle) > 0.0 || vehicle.CollisionDerail != NONE) { result.list += std::format("{} crushed {:.2f} m{}; ", i, crush_of(vehicle), vehicle.CollisionDerail != NONE ? ", derailed" : ""); @@ -1487,12 +1487,12 @@ TEST_CASE("collisions: a pair parting at the start of the step isn't crushed (l0 for (auto *vehicle : {&front, &back}) { vehicle->forces(dt); } - REQUIRE((front->Couplers[end::rear].closing < 0.0) == parting); + REQUIRE((front->Couplers[VehicleEnd::rear].closing < 0.0) == parting); back->V = 25.0 * kmh; for (auto *vehicle : {&front, &back}) { vehicle->move({}, dt, (*vehicle)->Loc, 5.0); } - auto const crush{front->Couplers[end::rear].crush + back->Couplers[end::front].crush}; + auto const crush{front->Couplers[VehicleEnd::rear].crush + back->Couplers[VehicleEnd::front].crush}; if (parting) { CHECK(crush == 0.0); // the legacy collision pushed them apart diff --git a/tests/unit/test_commands.cpp b/tests/unit/test_commands.cpp index ac9d72fee..2304de2d8 100644 --- a/tests/unit/test_commands.cpp +++ b/tests/unit/test_commands.cpp @@ -75,14 +75,14 @@ std::vector state() { {"SpeedCtrlParking", [](auto const &M) { return flag(M.SpeedCtrlUnit.Parking); }}, {"SpringBrakeActivate", [](auto const &M) { return flag(M.SpringBrake.Activate); }}, }; - for (int end : {end::front, end::rear}) { - auto const name{std::string{end == end::front ? "Front" : "Rear"}}; + for (auto const end : VehicleEnds) { + auto const name{std::string{end == VehicleEnd::front ? "Front" : "Rear"}}; result.emplace_back("MotorBlowers" + name + "Enabled", [end](auto const &M) { return flag(M.MotorBlowers[end].is_enabled); }); result.emplace_back("MotorBlowers" + name + "Disabled", [end](auto const &M) { return flag(M.MotorBlowers[end].is_disabled); }); result.emplace_back("Pant" + name + "Valve", [end](auto const &M) { return flag(M.Pantographs[end].valve.is_enabled) + 2 * flag(M.Pantographs[end].valve.is_disabled); }); } - for (int side : {side::right, side::left}) { - auto const name{std::string{side == side::right ? "Right" : "Left"}}; + for (auto const side : VehicleSides) { + auto const name{std::string{side == VehicleSide::right ? "Right" : "Left"}}; result.emplace_back(name + "DoorPermit", [side](auto const &M) { return flag(M.Doors.instances[side].open_permit); }); result.emplace_back(name + "DoorRemoteOpen", [side](auto const &M) { return flag(M.Doors.instances[side].remote_open); }); result.emplace_back(name + "DoorRemoteClose", [side](auto const &M) { return flag(M.Doors.instances[side].remote_close); }); @@ -285,16 +285,16 @@ std::vector const actions{ {"OilPumpSwitch on", [](auto &M) { return M.OilPumpSwitch(true, range_t::consist); }}, {"OilPumpSwitchOff on", [](auto &M) { return M.OilPumpSwitchOff(true, range_t::unit); }}, {"OilPumpSwitchOff off", [](auto &M) { return M.OilPumpSwitchOff(false, range_t::consist); }}, - {"MotorBlowersSwitch front on", [](auto &M) { return M.MotorBlowersSwitch(true, end::front, range_t::consist); }}, - {"MotorBlowersSwitch rear on", [](auto &M) { return M.MotorBlowersSwitch(true, end::rear, range_t::unit); }}, - {"MotorBlowersSwitchOff front on", [](auto &M) { return M.MotorBlowersSwitchOff(true, end::front, range_t::consist); }}, - {"MotorBlowersSwitchOff rear on", [](auto &M) { return M.MotorBlowersSwitchOff(true, end::rear, range_t::unit); }}, - {"MotorBlowersSwitchOff front off", [](auto &M) { return M.MotorBlowersSwitchOff(false, end::front, range_t::consist); }}, - {"MotorBlowersSwitchOff rear off", [](auto &M) { return M.MotorBlowersSwitchOff(false, end::rear, range_t::consist); }}, + {"MotorBlowersSwitch front on", [](auto &M) { return M.MotorBlowersSwitch(true, VehicleEnd::front, range_t::consist); }}, + {"MotorBlowersSwitch rear on", [](auto &M) { return M.MotorBlowersSwitch(true, VehicleEnd::rear, range_t::unit); }}, + {"MotorBlowersSwitchOff front on", [](auto &M) { return M.MotorBlowersSwitchOff(true, VehicleEnd::front, range_t::consist); }}, + {"MotorBlowersSwitchOff rear on", [](auto &M) { return M.MotorBlowersSwitchOff(true, VehicleEnd::rear, range_t::unit); }}, + {"MotorBlowersSwitchOff front off", [](auto &M) { return M.MotorBlowersSwitchOff(false, VehicleEnd::front, range_t::consist); }}, + {"MotorBlowersSwitchOff rear off", [](auto &M) { return M.MotorBlowersSwitchOff(false, VehicleEnd::rear, range_t::consist); }}, {"OperatePantographsValve enable", [](auto &M) { return M.OperatePantographsValve(operation_t::enable, range_t::consist); }}, - {"OperatePantographValve front enable", [](auto &M) { return M.OperatePantographValve(end::front, operation_t::enable, range_t::consist); }}, - {"OperatePantographValve rear enable_on", [](auto &M) { return M.OperatePantographValve(end::rear, operation_t::enable_on, range_t::unit); }}, - {"OperatePantographValve rear enable_off", [](auto &M) { return M.OperatePantographValve(end::rear, operation_t::enable_off, range_t::unit); }}, + {"OperatePantographValve front enable", [](auto &M) { return M.OperatePantographValve(VehicleEnd::front, operation_t::enable, range_t::consist); }}, + {"OperatePantographValve rear enable_on", [](auto &M) { return M.OperatePantographValve(VehicleEnd::rear, operation_t::enable_on, range_t::unit); }}, + {"OperatePantographValve rear enable_off", [](auto &M) { return M.OperatePantographValve(VehicleEnd::rear, operation_t::enable_off, range_t::unit); }}, {"DirectionForward", [](auto &M) { return M.DirectionForward(); }}, {"ConverterSwitch on", [](auto &M) { return M.ConverterSwitch(true, range_t::consist); }}, {"CompressorSwitch on", [](auto &M) { return M.CompressorSwitch(true, range_t::consist); }}, @@ -330,30 +330,30 @@ std::vector const actions{ {"SandboxAuto off", [](auto &M) { return M.SandboxAuto(false, range_t::consist); }}, {"SandboxManual off", [](auto &M) { return M.SandboxManual(false, range_t::consist); }}, {"Sandbox off", [](auto &M) { return M.Sandbox(false, range_t::consist); }}, - {"PermitDoors right", [](auto &M) { return M.PermitDoors(side::right, true, range_t::consist); }}, - {"PermitDoors left", [](auto &M) { return M.PermitDoors(side::left, true, range_t::unit); }}, + {"PermitDoors right", [](auto &M) { return M.PermitDoors(VehicleSide::right, true, range_t::consist); }}, + {"PermitDoors left", [](auto &M) { return M.PermitDoors(VehicleSide::left, true, range_t::unit); }}, {"ChangeDoorPermitPreset +1", [](auto &M) { return M.ChangeDoorPermitPreset(1, range_t::consist); }}, {"ChangeDoorPermitPreset -1", [](auto &M) { return M.ChangeDoorPermitPreset(-1, range_t::consist); }}, {"PermitDoorStep off", [](auto &M) { return M.PermitDoorStep(false, range_t::consist); }}, {"PermitDoorStep on", [](auto &M) { return M.PermitDoorStep(true, range_t::unit); }}, {"LockDoors off", [](auto &M) { return M.LockDoors(false, range_t::consist); }}, - {"OperateDoors right open local", [](auto &M) { return M.OperateDoors(side::right, true, range_t::local); }}, - {"OperateDoors left open", [](auto &M) { return M.OperateDoors(side::left, true, range_t::consist); }}, - {"OperateDoors right close", [](auto &M) { return M.OperateDoors(side::right, false, range_t::unit); }}, + {"OperateDoors right open local", [](auto &M) { return M.OperateDoors(VehicleSide::right, true, range_t::local); }}, + {"OperateDoors left open", [](auto &M) { return M.OperateDoors(VehicleSide::left, true, range_t::consist); }}, + {"OperateDoors right close", [](auto &M) { return M.OperateDoors(VehicleSide::right, false, range_t::unit); }}, {"ChangeDoorControlMode remote", [](auto &M) { return M.ChangeDoorControlMode(true, range_t::consist); }}, {"ChangeDoorControlMode local", [](auto &M) { return M.ChangeDoorControlMode(false, range_t::unit); }}, {"LockDoors on", [](auto &M) { return M.LockDoors(true, range_t::unit); }}, {"signal_departure on", [](auto &M) { return M.signal_departure(true, range_t::consist); }}, {"signal_departure off", [](auto &M) { return M.signal_departure(false, range_t::unit); }}, - {"PermitDoors right off", [](auto &M) { return M.PermitDoors(side::right, false, range_t::consist); }}, + {"PermitDoors right off", [](auto &M) { return M.PermitDoors(VehicleSide::right, false, range_t::consist); }}, {"HeatingSwitch off", [](auto &M) { return M.HeatingSwitch(false, range_t::unit); }}, {"MainSwitch off", [](auto &M) { return M.MainSwitch(false, range_t::consist); }}, {"DropAllPantographs", [](auto &M) { return M.DropAllPantographs(true, range_t::consist); }}, {"DropAllPantographs released", [](auto &M) { return M.DropAllPantographs(false, range_t::unit); }}, {"OperatePantographsValve disable", [](auto &M) { return M.OperatePantographsValve(operation_t::disable, range_t::unit); }}, - {"OperatePantographValve front disable_on", [](auto &M) { return M.OperatePantographValve(end::front, operation_t::disable_on, range_t::consist); }}, - {"OperatePantographValve front disable_off", [](auto &M) { return M.OperatePantographValve(end::front, operation_t::disable_off, range_t::consist); }}, - {"OperatePantographValve front none", [](auto &M) { return M.OperatePantographValve(end::front, operation_t::none, range_t::local); }}, + {"OperatePantographValve front disable_on", [](auto &M) { return M.OperatePantographValve(VehicleEnd::front, operation_t::disable_on, range_t::consist); }}, + {"OperatePantographValve front disable_off", [](auto &M) { return M.OperatePantographValve(VehicleEnd::front, operation_t::disable_off, range_t::consist); }}, + {"OperatePantographValve front none", [](auto &M) { return M.OperatePantographValve(VehicleEnd::front, operation_t::none, range_t::local); }}, {"CompressorSwitch off", [](auto &M) { return M.CompressorSwitch(false, range_t::unit); }}, {"ConverterSwitch off", [](auto &M) { return M.ConverterSwitch(false, range_t::unit); }}, {"WaterCircuitsLinkSwitch off", [](auto &M) { return M.WaterCircuitsLinkSwitch(false, range_t::unit); }}, @@ -363,8 +363,8 @@ std::vector const actions{ {"WaterPumpBreakerSwitch off", [](auto &M) { return M.WaterPumpBreakerSwitch(false, range_t::unit); }}, {"FuelPumpSwitch off", [](auto &M) { return M.FuelPumpSwitch(false, range_t::unit); }}, {"OilPumpSwitch off", [](auto &M) { return M.OilPumpSwitch(false, range_t::unit); }}, - {"MotorBlowersSwitch front off", [](auto &M) { return M.MotorBlowersSwitch(false, end::front, range_t::unit); }}, - {"MotorBlowersSwitch rear off", [](auto &M) { return M.MotorBlowersSwitch(false, end::rear, range_t::consist); }}, + {"MotorBlowersSwitch front off", [](auto &M) { return M.MotorBlowersSwitch(false, VehicleEnd::front, range_t::unit); }}, + {"MotorBlowersSwitch rear off", [](auto &M) { return M.MotorBlowersSwitch(false, VehicleEnd::rear, range_t::consist); }}, {"CompartmentLightsSwitch off", [](auto &M) { return M.CompartmentLightsSwitch(false, range_t::unit); }}, {"BatterySwitch off", [](auto &M) { return M.BatterySwitch(false, range_t::unit); }}, {"CabDeactivisation", [](auto &M) { return M.CabDeactivisation(); }}, @@ -378,7 +378,7 @@ TEST_CASE("commands: every switch of the cab, sent to the next vehicle") { test::reseed_random(); vehicle driven{definition::fiz(path), 0.0, "driven", 1}; vehicle next{definition::fiz(path), 0.0, "next"}; - driven->Attach(end::rear, end::front, &next.mover(), test::consist::full_coupling, true, false); + driven->Attach(VehicleEnd::rear, VehicleEnd::front, &next.mover(), test::consist::full_coupling, true, false); auto done{false}; auto channels{state()}; for (auto const &channel : state()) { @@ -408,8 +408,8 @@ TEST_CASE("commands: every switch of the cab, worked on a pair standing under th auto done{false}; auto channels{state()}; channels.insert(channels.end(), { - {"PantFrontActive", [](auto const &M) { return flag(M.Pantographs[end::front].is_active); }}, - {"PantRearActive", [](auto const &M) { return flag(M.Pantographs[end::rear].is_active); }}, + {"PantFrontActive", [](auto const &M) { return flag(M.Pantographs[VehicleEnd::front].is_active); }}, + {"PantRearActive", [](auto const &M) { return flag(M.Pantographs[VehicleEnd::rear].is_active); }}, {"PantPress", [](auto const &M) { return M.PantPress; }}, {"GroundRelay", [](auto const &M) { return flag(M.GroundRelay); }}, {"ConverterFlag", [](auto const &M) { return flag(M.ConverterFlag); }}, @@ -449,8 +449,8 @@ struct train { vehicle last{definition::fiz("4e_v1/4e"), 0.0, "last"}; explicit train(CouplingSet const couplings) { - head->Attach(end::rear, end::rear, &middle.mover(), couplings, true, false); - middle->Attach(end::front, end::front, &last.mover(), couplings, true, false); + head->Attach(VehicleEnd::rear, VehicleEnd::rear, &middle.mover(), couplings, true, false); + middle->Attach(VehicleEnd::front, VehicleEnd::front, &last.mover(), couplings, true, false); } }; @@ -468,21 +468,21 @@ TEST_CASE("commands: travel along the train, turned round for a vehicle facing b CHECK(consist.last->CommandIn.Command == VehicleCommand::none); SUBCASE("door permits: the right side of the sender is the left one of a vehicle facing backwards") { - consist.head->PermitDoors(side::right, true, range_t::consist); - CHECK(consist.head->Doors.instances[side::right].open_permit); - CHECK(consist.middle->Doors.instances[side::left].open_permit); - CHECK_FALSE(consist.middle->Doors.instances[side::right].open_permit); - CHECK(consist.last->Doors.instances[side::right].open_permit); + consist.head->PermitDoors(VehicleSide::right, true, range_t::consist); + CHECK(consist.head->Doors.instances[VehicleSide::right].open_permit); + CHECK(consist.middle->Doors.instances[VehicleSide::left].open_permit); + CHECK_FALSE(consist.middle->Doors.instances[VehicleSide::right].open_permit); + CHECK(consist.last->Doors.instances[VehicleSide::right].open_permit); // and revoked the same way - consist.head->PermitDoors(side::right, false, range_t::consist); - CHECK_FALSE(consist.middle->Doors.instances[side::left].open_permit); - CHECK_FALSE(consist.last->Doors.instances[side::right].open_permit); + consist.head->PermitDoors(VehicleSide::right, false, range_t::consist); + CHECK_FALSE(consist.middle->Doors.instances[VehicleSide::left].open_permit); + CHECK_FALSE(consist.last->Doors.instances[VehicleSide::right].open_permit); } SUBCASE("a pantograph valve: the vehicles past one coupled by its control cable take the other pantograph") { - consist.head->OperatePantographValve(end::front, operation_t::enable, range_t::consist); - CHECK(consist.head->Pantographs[end::front].valve.is_enabled); - CHECK(consist.middle->Pantographs[end::front].valve.is_enabled); - CHECK(consist.last->Pantographs[end::rear].valve.is_enabled); + consist.head->OperatePantographValve(VehicleEnd::front, operation_t::enable, range_t::consist); + CHECK(consist.head->Pantographs[VehicleEnd::front].valve.is_enabled); + CHECK(consist.middle->Pantographs[VehicleEnd::front].valve.is_enabled); + CHECK(consist.last->Pantographs[VehicleEnd::rear].valve.is_enabled); } SUBCASE("sent backwards, it goes no further than the sender: nothing is coupled at its front") { consist.head->RunCommand(VehicleCommand::doorLock, 0, -1, Coupling::control); diff --git a/tests/unit/test_controls.cpp b/tests/unit/test_controls.cpp index 133794ccd..55ce1cc0e 100644 --- a/tests/unit/test_controls.cpp +++ b/tests/unit/test_controls.cpp @@ -69,16 +69,16 @@ bool released(scenario &Scenario, double Pressure = 0.1) { return true; } -bool open(TMoverParameters const &Vehicle, int Side) { +bool open(TMoverParameters const &Vehicle, VehicleSide Side) { return Vehicle.Doors.instances[Side].is_open; } // the leaf shut, whatever the step does (closed, is_closed, wants the step folded too) -bool shut(TMoverParameters const &Vehicle, int Side) { +bool shut(TMoverParameters const &Vehicle, VehicleSide Side) { return Vehicle.Doors.instances[Side].position <= 0.f; } -bool closed(TMoverParameters const &Vehicle, int Side) { +bool closed(TMoverParameters const &Vehicle, VehicleSide Side) { return Vehicle.Doors.instances[Side].is_closed; } @@ -100,30 +100,30 @@ TEST_CASE("controls: the doors of an electric unit, opened, locked, permitted an auto &cab{scenario.cab()}; auto const &last{scenario.vehicle(scenario.train().size() - 1)}; scenario.act("permit left"); - cab.PermitDoors(side::left, true); + cab.PermitDoors(VehicleSide::left, true); scenario.wait(2.0); scenario.act("open left"); - cab.OperateDoors(side::left, true); + cab.OperateDoors(VehicleSide::left, true); scenario.wait(10.0); - CHECK(open(cab, side::left)); - CHECK(open(last, side::left)); - CHECK(closed(cab, side::right)); + CHECK(open(cab, VehicleSide::left)); + CHECK(open(last, VehicleSide::left)); + CHECK(closed(cab, VehicleSide::right)); scenario.act("close left"); - cab.OperateDoors(side::left, false); + cab.OperateDoors(VehicleSide::left, false); scenario.wait(10.0); - CHECK(shut(cab, side::left)); - CHECK(shut(last, side::left)); + CHECK(shut(cab, VehicleSide::left)); + CHECK(shut(last, VehicleSide::left)); scenario.act("open right without permit"); - cab.OperateDoors(side::right, true); + cab.OperateDoors(VehicleSide::right, true); scenario.wait(5.0); // the EN57 needs no permit - CHECK(shut(cab, side::right) == cab.Doors.permit_needed); + CHECK(shut(cab, VehicleSide::right) == cab.Doors.permit_needed); scenario.act("permit right, open"); - cab.PermitDoors(side::right, true); - cab.OperateDoors(side::right, true); + cab.PermitDoors(VehicleSide::right, true); + cab.OperateDoors(VehicleSide::right, true); scenario.wait(10.0); - CHECK(open(cab, side::right)); - CHECK(open(last, side::right)); + CHECK(open(cab, VehicleSide::right)); + CHECK(open(last, VehicleSide::right)); scenario.act("lock"); cab.LockDoors(true); scenario.wait(5.0); @@ -136,29 +136,29 @@ TEST_CASE("controls: the doors of an electric unit, opened, locked, permitted an cab.PermitDoorStep(true); cab.ChangeDoorControlMode(false); scenario.act("close all, unlock"); - cab.OperateDoors(side::right, false); - cab.OperateDoors(side::left, false); + cab.OperateDoors(VehicleSide::right, false); + cab.OperateDoors(VehicleSide::left, false); cab.LockDoors(false); scenario.wait(10.0); - CHECK(shut(cab, side::left)); - CHECK(shut(cab, side::right)); + CHECK(shut(cab, VehicleSide::left)); + CHECK(shut(cab, VehicleSide::right)); scenario.act("open both and drive off"); - cab.PermitDoors(side::left, true); - cab.PermitDoors(side::right, true); - cab.OperateDoors(side::left, true); - cab.OperateDoors(side::right, true); + cab.PermitDoors(VehicleSide::left, true); + cab.PermitDoors(VehicleSide::right, true); + cab.OperateDoors(VehicleSide::left, true); + cab.OperateDoors(VehicleSide::right, true); scenario.wait(5.0); - CHECK_FALSE(shut(cab, side::left)); - CHECK_FALSE(shut(cab, side::right)); + CHECK_FALSE(shut(cab, VehicleSide::left)); + CHECK_FALSE(shut(cab, VehicleSide::right)); scenario.get_going(); notch_up(scenario, 4, 2.0); scenario.wait(20.0); // the doors of a train ready to run close as the driver starts off. no CHECK of the speed: the Elf and // the Impuls keep their steps out under the permit, which keeps them from moving (COVERAGE.md) - CHECK(shut(cab, side::left) == ready); - CHECK(shut(cab, side::right) == ready); - CHECK(shut(last, side::left) == ready); - CHECK(shut(last, side::right) == ready); + CHECK(shut(cab, VehicleSide::left) == ready); + CHECK(shut(cab, VehicleSide::right) == ready); + CHECK(shut(last, VehicleSide::left) == ready); + CHECK(shut(last, VehicleSide::right) == ready); notch_down(scenario); brake_to_stop(scenario); scenario.check(); @@ -177,28 +177,28 @@ TEST_CASE("controls: the doors of wagons, worked from the locomotive") { for (auto const range : {range_t::consist, range_t::unit, range_t::local}) { CAPTURE(static_cast(range)); scenario.act(std::format("open right {}", static_cast(range))); - cab.PermitDoors(side::right, true, range); - cab.OperateDoors(side::right, true, range); + cab.PermitDoors(VehicleSide::right, true, range); + cab.OperateDoors(VehicleSide::right, true, range); scenario.wait(10.0); - CHECK(open(coach, side::right) == (range != range_t::local)); - CHECK(shut(coach, side::left)); - CHECK(shut(freight, side::right)); + CHECK(open(coach, VehicleSide::right) == (range != range_t::local)); + CHECK(shut(coach, VehicleSide::left)); + CHECK(shut(freight, VehicleSide::right)); scenario.act("close right"); - cab.OperateDoors(side::right, false, range); + cab.OperateDoors(VehicleSide::right, false, range); scenario.wait(10.0); - CHECK(shut(coach, side::right)); + CHECK(shut(coach, VehicleSide::right)); } scenario.act("wagon opens its own"); - coach.OperateDoors(side::left, true, range_t::local); + coach.OperateDoors(VehicleSide::left, true, range_t::local); // a second at a time, the same run as one wait. the coach's doors close by themselves 5 s after they // opened (DoorStayOpen) scenario.wait(1.0); - CHECK_FALSE(shut(coach, side::left)); + CHECK_FALSE(shut(coach, VehicleSide::left)); scenario.wait(9.0); - CHECK(shut(coach, side::left)); - coach.OperateDoors(side::left, false, range_t::local); + CHECK(shut(coach, VehicleSide::left)); + coach.OperateDoors(VehicleSide::left, false, range_t::local); scenario.wait(10.0); - CHECK(shut(coach, side::left)); + CHECK(shut(coach, VehicleSide::left)); scenario.check(); } diff --git a/tests/unit/test_coupler_physics.cpp b/tests/unit/test_coupler_physics.cpp index bbb935365..60c760fb5 100644 --- a/tests/unit/test_coupler_physics.cpp +++ b/tests/unit/test_coupler_physics.cpp @@ -268,7 +268,7 @@ TEST_CASE("coupler physics: a jerk on the solid draw gear breaks the coupling by namespace { // couples the facing ends of the two vehicles, as the scenery does -void join(vehicle &First, int FirstEnd, vehicle &Second, int SecondEnd, CouplingSet const couplings = Coupling::coupler) { +void join(vehicle &First, VehicleEnd FirstEnd, vehicle &Second, VehicleEnd SecondEnd, CouplingSet const couplings = Coupling::coupler) { REQUIRE(First->Attach(FirstEnd, SecondEnd, &Second.mover(), couplings, true, false)); REQUIRE(Second->Attach(SecondEnd, FirstEnd, &First.mover(), couplings, true, false)); } @@ -286,9 +286,9 @@ bool coupler_damaged(vehicle &Vehicle) { TEST_CASE("coupler physics: the play of the coupling and the parameters of the model come from the vehicle definition") { auto loose{loose_wagon(0.05, 0.0, "loose")}; - auto const &physics{loose->Couplers[end::front].physics}; + auto const &physics{loose->Couplers[VehicleEnd::front].physics}; CHECK(physics.slack == doctest::Approx(0.05)); - CHECK(loose->Couplers[end::rear].physics.slack == doctest::Approx(0.05)); + CHECK(loose->Couplers[VehicleEnd::rear].physics.slack == doctest::Approx(0.05)); CHECK(physics.buffers.stiffness == doctest::Approx(9200e3)); CHECK(physics.buffers.travel == doctest::Approx(0.11)); CHECK(physics.draw_gear.end_force() == doctest::Approx(450e3)); @@ -300,11 +300,11 @@ TEST_CASE("coupler physics: the play of the coupling and the parameters of the m CHECK(physics.link.breakable); auto tight{vehicle{definition::load("wagon"), 0.0, "tight"}}; - CHECK(tight->Couplers[end::front].physics.slack == 0.0); + CHECK(tight->Couplers[VehicleEnd::front].physics.slack == 0.0); auto automatic{vehicle{definition::load("wagon").set("BuffCoupl", "CType", "Automatic"), 0.0, "automatic"}}; - CHECK(automatic->Couplers[end::front].physics.slack == doctest::Approx(0.005)); + CHECK(automatic->Couplers[VehicleEnd::front].physics.slack == doctest::Approx(0.005)); auto articulated{vehicle{definition::load("wagon").set("BuffCoupl", "CType", "Articulated"), 0.0, "articulated"}}; - CHECK_FALSE(articulated->Couplers[end::front].physics.link.breakable); + CHECK_FALSE(articulated->Couplers[VehicleEnd::front].physics.link.breakable); } TEST_CASE("coupler physics: a coupling with play pulls only once the play is taken up") { @@ -313,15 +313,15 @@ TEST_CASE("coupler physics: a coupling with play pulls only once the play is tak flag_setting const crashdamage{Global.crash_damage, true}; auto front{loose_wagon(0.05, 3.0, "front")}; auto rear{loose_wagon(0.05, 0.1, "rear")}; - join(rear, end::front, front, end::rear); - test::pair pair{rear, end::front, front, end::rear, 0.0}; + join(rear, VehicleEnd::front, front, VehicleEnd::rear); + test::pair pair{rear, VehicleEnd::front, front, VehicleEnd::rear, 0.0}; front.hold_brake_pipe(5.0); rear.hold_brake_pipe(5.0); auto pulledwithinplay{false}; for (int i = 0; i < 300 && pair.gap() < 0.09; ++i) { pair.step(); - pulledwithinplay = pulledwithinplay || rear->Couplers[end::front].CForce != 0.0; + pulledwithinplay = pulledwithinplay || rear->Couplers[VehicleEnd::front].CForce != 0.0; } REQUIRE(pair.gap() >= 0.09); CHECK_FALSE(pulledwithinplay); @@ -343,7 +343,7 @@ TEST_CASE("coupler physics: buffers hit at a walking pace give back less than th auto moving{vehicle{definition::load("wagon"), 5.0, "moving"}}; // barely moving, so that its brakes are released auto standing{vehicle{definition::load("wagon"), 0.1, "standing"}}; - test::pair pair{moving, end::front, standing, end::rear, 0.3}; + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 0.3}; moving.hold_brake_pipe(5.0); standing.hold_brake_pipe(5.0); @@ -352,7 +352,7 @@ TEST_CASE("coupler physics: buffers hit at a walking pace give back less than th for (int i = 0; i < 500; ++i) { pair.step(); touched = touched || pair.gap() < 0.0; - solid = solid || moving->Couplers[end::front].physics_state.stop != 0; + solid = solid || moving->Couplers[VehicleEnd::front].physics_state.stop != 0; if (touched && pair.gap() > 0.3) { break; // parted } @@ -377,8 +377,8 @@ TEST_CASE("coupler physics: coupled vehicles at rest stay at rest") { flag_setting const everywhere{Global.coupler_physics_all, true}; auto first{vehicle{definition::load("wagon"), 0.0, "first"}}; auto second{vehicle{definition::load("wagon"), 0.0, "second"}}; - join(first, end::rear, second, end::front); - test::pair pair{first, end::rear, second, end::front, 0.0}; + join(first, VehicleEnd::rear, second, VehicleEnd::front); + test::pair pair{first, VehicleEnd::rear, second, VehicleEnd::front, 0.0}; pair.run(5.0); CHECK(std::abs(first.speed()) < 0.01); @@ -391,8 +391,8 @@ TEST_CASE("coupler physics: a jerk on a coupling with play breaks it, the brake flag_setting const everywhere{Global.coupler_physics_all, true}; auto front{loose_wagon(0.05, 20.0, "front")}; auto rear{loose_wagon(0.05, 0.1, "rear")}; - join(rear, end::front, front, end::rear, Coupling::coupler | Coupling::brakeHose); - test::pair pair{rear, end::front, front, end::rear, 0.0}; + join(rear, VehicleEnd::front, front, VehicleEnd::rear, Coupling::coupler | Coupling::brakeHose); + test::pair pair{rear, VehicleEnd::front, front, VehicleEnd::rear, 0.0}; front.hold_brake_pipe(5.0); rear.hold_brake_pipe(5.0); @@ -424,15 +424,15 @@ TEST_CASE("coupler physics: a gentle pull on a coupling with play doesn't hurt i flag_setting const crashdamage{Global.crash_damage, true}; auto front{loose_wagon(0.05, 3.0, "front")}; auto rear{loose_wagon(0.05, 0.1, "rear")}; - join(rear, end::front, front, end::rear); - test::pair pair{rear, end::front, front, end::rear, 0.0}; + join(rear, VehicleEnd::front, front, VehicleEnd::rear); + test::pair pair{rear, VehicleEnd::front, front, VehicleEnd::rear, 0.0}; front.hold_brake_pipe(5.0); rear.hold_brake_pipe(5.0); pair.run(3.0); CHECK(pair.coupled()); CHECK_FALSE(coupler_damaged(rear)); - CHECK(rear->Couplers[end::front].physics_state.elongation == 0.0); + CHECK(rear->Couplers[VehicleEnd::front].physics_state.elongation == 0.0); } TEST_CASE("coupler physics: automatic couplers still catch a wagon rolling into a standing one") { @@ -442,7 +442,7 @@ TEST_CASE("coupler physics: automatic couplers still catch a wagon rolling into auto automatic{definition::load("wagon").set("BuffCoupl", "CType", "Automatic").set("BuffCoupl", "AutomaticFlag", Coupling::coupler | Coupling::brakeHose)}; auto moving{vehicle{automatic, 5.0, "moving"}}; auto standing{vehicle{automatic, 0.0, "standing"}}; - test::pair pair{moving, end::front, standing, end::rear, 1.0}; + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 1.0}; pair.run(3.0); REQUIRE(pair.coupled()); @@ -456,51 +456,51 @@ TEST_CASE("couplers: a broken coupling of vehicles facing each other uncouples t auto first{vehicle{definition::load("wagon"), 0.0, "first"}}; auto second{vehicle{definition::load("wagon"), 0.0, "second"}}; auto third{vehicle{definition::load("wagon"), 0.0, "third"}}; - join(first, end::front, second, end::front); - join(second, end::rear, third, end::front); + join(first, VehicleEnd::front, second, VehicleEnd::front); + join(second, VehicleEnd::rear, third, VehicleEnd::front); - first->damage_coupler(end::front); - CHECK(first->Couplers[end::front].CouplingFlag == Coupling::none); - CHECK(second->Couplers[end::front].CouplingFlag == Coupling::none); + first->damage_coupler(VehicleEnd::front); + CHECK(first->Couplers[VehicleEnd::front].CouplingFlag == Coupling::none); + CHECK(second->Couplers[VehicleEnd::front].CouplingFlag == Coupling::none); // the other coupling of the second vehicle stays - CHECK(second->Couplers[end::rear].CouplingFlag == Coupling::coupler); + CHECK(second->Couplers[VehicleEnd::rear].CouplingFlag == Coupling::coupler); } TEST_CASE("couplers: a broken coupler is repaired alone, with the one of the vehicle it was coupled with") { auto first{vehicle{definition::load("wagon"), 0.0, "first"}}; auto second{vehicle{definition::load("wagon"), 0.0, "second"}}; auto third{vehicle{definition::load("wagon"), 0.0, "third"}}; - join(first, end::rear, second, end::front, Coupling::coupler | Coupling::brakeHose); - join(second, end::rear, third, end::front, Coupling::coupler | Coupling::brakeHose); + join(first, VehicleEnd::rear, second, VehicleEnd::front, Coupling::coupler | Coupling::brakeHose); + join(second, VehicleEnd::rear, third, VehicleEnd::front, Coupling::coupler | Coupling::brakeHose); // both couplings of the second wagon break - second->damage_coupler(end::front); - second->damage_coupler(end::rear); - REQUIRE(second->Couplers[end::front].broken); - REQUIRE(first->Couplers[end::rear].broken); - REQUIRE(third->Couplers[end::front].broken); + second->damage_coupler(VehicleEnd::front); + second->damage_coupler(VehicleEnd::rear); + REQUIRE(second->Couplers[VehicleEnd::front].broken); + REQUIRE(first->Couplers[VehicleEnd::rear].broken); + REQUIRE(third->Couplers[VehicleEnd::front].broken); REQUIRE(second->DamageFlag.HasAll(VehicleDamage::coupling)); // nothing to repair at the far end of the first wagon - CHECK_FALSE(first->repair_coupler(end::front)); + CHECK_FALSE(first->repair_coupler(VehicleEnd::front)); // repaired from the first wagon: the coupling between the first two, the other one stays broken - CHECK(first->repair_coupler(end::rear)); - CHECK_FALSE(first->Couplers[end::rear].broken); - CHECK_FALSE(second->Couplers[end::front].broken); - CHECK(second->Couplers[end::rear].broken); - CHECK(third->Couplers[end::front].broken); + CHECK(first->repair_coupler(VehicleEnd::rear)); + CHECK_FALSE(first->Couplers[VehicleEnd::rear].broken); + CHECK_FALSE(second->Couplers[VehicleEnd::front].broken); + CHECK(second->Couplers[VehicleEnd::rear].broken); + CHECK(third->Couplers[VehicleEnd::front].broken); // the second wagon keeps its damage, and its emergency braking, while a coupler of it is broken CHECK(second->DamageFlag.HasAll(VehicleDamage::coupling)); CHECK(second->AlarmChainFlag); - CHECK(third->repair_coupler(end::front)); - CHECK_FALSE(second->Couplers[end::rear].broken); + CHECK(third->repair_coupler(VehicleEnd::front)); + CHECK_FALSE(second->Couplers[VehicleEnd::rear].broken); CHECK_FALSE(second->DamageFlag.HasAll(VehicleDamage::coupling)); CHECK_FALSE(second->AlarmChainFlag); // repaired, not coupled: the vehicles are coupled again as usual - CHECK(second->Couplers[end::rear].CouplingFlag == Coupling::none); - CHECK(second->Attach(end::rear, end::front, &third.mover(), Coupling::coupler, true, false)); + CHECK(second->Couplers[VehicleEnd::rear].CouplingFlag == Coupling::none); + CHECK(second->Attach(VehicleEnd::rear, VehicleEnd::front, &third.mover(), Coupling::coupler, true, false)); } TEST_CASE("coupler physics: with couplerphysics yes, only the pairs with a vehicle covered take the physical model") { @@ -508,28 +508,28 @@ TEST_CASE("coupler physics: with couplerphysics yes, only the pairs with a vehic flag_setting const everywhere{Global.coupler_physics_all, false}; auto moving{vehicle{definition::load("wagon"), 5.0, "moving"}}; auto standing{vehicle{definition::load("wagon"), 0.1, "standing"}}; - test::pair pair{moving, end::front, standing, end::rear, 0.1}; + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 0.1}; SUBCASE("neither covered: the legacy model") { pair.run(1.0); - CHECK_FALSE(moving->coupler_physics_at(end::front)); - CHECK_FALSE(standing->coupler_physics_at(end::rear)); + CHECK_FALSE(moving->coupler_physics_at(VehicleEnd::front)); + CHECK_FALSE(standing->coupler_physics_at(VehicleEnd::rear)); // the state of the physical model untouched - CHECK(moving->Couplers[end::front].physics_state.gap == 0.0); + CHECK(moving->Couplers[VehicleEnd::front].physics_state.gap == 0.0); } SUBCASE("one covered: both compute the pair physically") { // as the player's train closing in on the other one moving->CouplerPhysics = true; pair.run(1.0); - CHECK(moving->coupler_physics_at(end::front)); - CHECK(standing->coupler_physics_at(end::rear)); - CHECK(moving->Couplers[end::front].physics_state.gap != 0.0); - CHECK(standing->Couplers[end::rear].physics_state.gap == moving->Couplers[end::front].physics_state.gap); + CHECK(moving->coupler_physics_at(VehicleEnd::front)); + CHECK(standing->coupler_physics_at(VehicleEnd::rear)); + CHECK(moving->Couplers[VehicleEnd::front].physics_state.gap != 0.0); + CHECK(standing->Couplers[VehicleEnd::rear].physics_state.gap == moving->Couplers[VehicleEnd::front].physics_state.gap); } SUBCASE("the setting off: the legacy model, covered or not") { flag_setting const off{Global.coupler_physics, false}; moving->CouplerPhysics = true; - CHECK_FALSE(moving->coupler_physics_at(end::front)); + CHECK_FALSE(moving->coupler_physics_at(VehicleEnd::front)); } } diff --git a/tests/unit/test_couplers.cpp b/tests/unit/test_couplers.cpp index 825102f9a..c816bf19b 100644 --- a/tests/unit/test_couplers.cpp +++ b/tests/unit/test_couplers.cpp @@ -70,13 +70,13 @@ TEST_CASE("couplers: automatic couplers catch a standing wagon hit at a walking crash_damage_setting const crashdamage{true}; auto moving{automatic_wagon(10.0, "moving")}; auto standing{automatic_wagon(0.0, "standing")}; - REQUIRE(moving->Couplers[end::front].type() == TCouplerType::Automatic); + REQUIRE(moving->Couplers[VehicleEnd::front].type() == TCouplerType::Automatic); REQUIRE(moving.speed() == doctest::Approx(10.0)); // the front of the moving wagon runs into the rear of the standing one - CHECK(moving->CollisionVelocity(end::front, standing.mover(), end::rear) == doctest::Approx(10.0)); - CHECK(moving->AutomaticCouplingSafe(end::front, standing.mover(), end::rear)); - CHECK(standing->AutomaticCouplingSafe(end::rear, moving.mover(), end::front)); + CHECK(moving->CollisionVelocity(VehicleEnd::front, standing.mover(), VehicleEnd::rear) == doctest::Approx(10.0)); + CHECK(moving->AutomaticCouplingSafe(VehicleEnd::front, standing.mover(), VehicleEnd::rear)); + CHECK(standing->AutomaticCouplingSafe(VehicleEnd::rear, moving.mover(), VehicleEnd::front)); } TEST_CASE("couplers: automatic couplers don't catch a wagon hit too fast, the wagons collide instead") { @@ -85,9 +85,9 @@ TEST_CASE("couplers: automatic couplers don't catch a wagon hit too fast, the wa auto standing{automatic_wagon(0.0, "standing")}; REQUIRE(moving.speed() == doctest::Approx(30.0)); - CHECK(moving->CollisionVelocity(end::front, standing.mover(), end::rear) > TMoverParameters::SafeCollisionVelocity); - CHECK_FALSE(moving->AutomaticCouplingSafe(end::front, standing.mover(), end::rear)); - CHECK_FALSE(standing->AutomaticCouplingSafe(end::rear, moving.mover(), end::front)); + CHECK(moving->CollisionVelocity(VehicleEnd::front, standing.mover(), VehicleEnd::rear) > TMoverParameters::SafeCollisionVelocity); + CHECK_FALSE(moving->AutomaticCouplingSafe(VehicleEnd::front, standing.mover(), VehicleEnd::rear)); + CHECK_FALSE(standing->AutomaticCouplingSafe(VehicleEnd::rear, moving.mover(), VehicleEnd::front)); } TEST_CASE("couplers: automatic couplers catch a wagon running ahead only a little slower") { @@ -95,9 +95,9 @@ TEST_CASE("couplers: automatic couplers catch a wagon running ahead only a littl auto faster{automatic_wagon(60.0, "faster")}; auto slower{automatic_wagon(50.0, "slower")}; - CHECK(faster->CollisionVelocity(end::front, slower.mover(), end::rear) == doctest::Approx(10.0)); - CHECK(slower->CollisionVelocity(end::rear, faster.mover(), end::front) == doctest::Approx(10.0)); - CHECK(faster->AutomaticCouplingSafe(end::front, slower.mover(), end::rear)); + CHECK(faster->CollisionVelocity(VehicleEnd::front, slower.mover(), VehicleEnd::rear) == doctest::Approx(10.0)); + CHECK(slower->CollisionVelocity(VehicleEnd::rear, faster.mover(), VehicleEnd::front) == doctest::Approx(10.0)); + CHECK(faster->AutomaticCouplingSafe(VehicleEnd::front, slower.mover(), VehicleEnd::rear)); } TEST_CASE("couplers: without crash damage automatic couplers catch at any speed") { @@ -105,7 +105,7 @@ TEST_CASE("couplers: without crash damage automatic couplers catch at any speed" auto moving{automatic_wagon(30.0, "moving")}; auto standing{automatic_wagon(0.0, "standing")}; - CHECK(moving->AutomaticCouplingSafe(end::front, standing.mover(), end::rear)); + CHECK(moving->AutomaticCouplingSafe(VehicleEnd::front, standing.mover(), VehicleEnd::rear)); } // the closing speed used to treat the speed of each vehicle as a vector turned by half its heading, so for vehicles @@ -116,16 +116,16 @@ TEST_CASE("couplers: the closing speed of a rear-end collision is the difference auto slower{automatic_wagon(25.0, "slower")}; // running forwards, the front of the faster wagon hits the rear of the slower one - CHECK(faster->CollisionVelocity(end::front, slower.mover(), end::rear) == doctest::Approx(15.0)); - CHECK(slower->CollisionVelocity(end::rear, faster.mover(), end::front) == doctest::Approx(15.0)); + CHECK(faster->CollisionVelocity(VehicleEnd::front, slower.mover(), VehicleEnd::rear) == doctest::Approx(15.0)); + CHECK(slower->CollisionVelocity(VehicleEnd::rear, faster.mover(), VehicleEnd::front) == doctest::Approx(15.0)); // the wagons running ahead of each other are parting - CHECK(slower->CollisionVelocity(end::front, faster.mover(), end::rear) == doctest::Approx(-15.0)); + CHECK(slower->CollisionVelocity(VehicleEnd::front, faster.mover(), VehicleEnd::rear) == doctest::Approx(-15.0)); // backing up, the rear of the faster wagon hits the front of the slower one auto backingfaster{automatic_wagon(-40.0, "backing faster")}; auto backingslower{automatic_wagon(-25.0, "backing slower")}; - CHECK(backingfaster->CollisionVelocity(end::rear, backingslower.mover(), end::front) == doctest::Approx(15.0)); - CHECK(backingslower->CollisionVelocity(end::front, backingfaster.mover(), end::rear) == doctest::Approx(15.0)); + CHECK(backingfaster->CollisionVelocity(VehicleEnd::rear, backingslower.mover(), VehicleEnd::front) == doctest::Approx(15.0)); + CHECK(backingslower->CollisionVelocity(VehicleEnd::front, backingfaster.mover(), VehicleEnd::rear) == doctest::Approx(15.0)); } TEST_CASE("couplers: the closing speed of a head-on collision is the sum of the speeds") { @@ -134,27 +134,27 @@ TEST_CASE("couplers: the closing speed of a head-on collision is the sum of the auto second{automatic_wagon(10.0, "second")}; // both wagons run forwards, their fronts meet - CHECK(first->CollisionVelocity(end::front, second.mover(), end::front) == doctest::Approx(20.0)); - CHECK(second->CollisionVelocity(end::front, first.mover(), end::front) == doctest::Approx(20.0)); + CHECK(first->CollisionVelocity(VehicleEnd::front, second.mover(), VehicleEnd::front) == doctest::Approx(20.0)); + CHECK(second->CollisionVelocity(VehicleEnd::front, first.mover(), VehicleEnd::front) == doctest::Approx(20.0)); // 20 km/h is above the limit, the couplers don't catch (the old formula gave 14.1 km/h and coupled them) - CHECK(first->CollisionVelocity(end::front, second.mover(), end::front) > TMoverParameters::SafeCollisionVelocity); - CHECK_FALSE(first->AutomaticCouplingSafe(end::front, second.mover(), end::front)); - CHECK_FALSE(second->AutomaticCouplingSafe(end::front, first.mover(), end::front)); + CHECK(first->CollisionVelocity(VehicleEnd::front, second.mover(), VehicleEnd::front) > TMoverParameters::SafeCollisionVelocity); + CHECK_FALSE(first->AutomaticCouplingSafe(VehicleEnd::front, second.mover(), VehicleEnd::front)); + CHECK_FALSE(second->AutomaticCouplingSafe(VehicleEnd::front, first.mover(), VehicleEnd::front)); // both wagons back up, their rears meet auto firstbacking{automatic_wagon(-10.0, "first backing")}; auto secondbacking{automatic_wagon(-10.0, "second backing")}; - CHECK(firstbacking->CollisionVelocity(end::rear, secondbacking.mover(), end::rear) == doctest::Approx(20.0)); + CHECK(firstbacking->CollisionVelocity(VehicleEnd::rear, secondbacking.mover(), VehicleEnd::rear) == doctest::Approx(20.0)); // running back to back, the wagons part - CHECK(first->CollisionVelocity(end::rear, second.mover(), end::rear) == doctest::Approx(-20.0)); - CHECK(first->AutomaticCouplingSafe(end::rear, second.mover(), end::rear)); + CHECK(first->CollisionVelocity(VehicleEnd::rear, second.mover(), VehicleEnd::rear) == doctest::Approx(-20.0)); + CHECK(first->AutomaticCouplingSafe(VehicleEnd::rear, second.mover(), VehicleEnd::rear)); // slow enough, the couplers catch auto slowfirst{automatic_wagon(5.0, "slow first")}; auto slowsecond{automatic_wagon(5.0, "slow second")}; - CHECK(slowfirst->CollisionVelocity(end::front, slowsecond.mover(), end::front) == doctest::Approx(10.0)); - CHECK(slowfirst->AutomaticCouplingSafe(end::front, slowsecond.mover(), end::front)); + CHECK(slowfirst->CollisionVelocity(VehicleEnd::front, slowsecond.mover(), VehicleEnd::front) == doctest::Approx(10.0)); + CHECK(slowfirst->AutomaticCouplingSafe(VehicleEnd::front, slowsecond.mover(), VehicleEnd::front)); } TEST_CASE("couplers: the closing speed of a hit on a standing vehicle is the speed of the moving one, whichever way it faces") { @@ -162,17 +162,17 @@ TEST_CASE("couplers: the closing speed of a hit on a standing vehicle is the spe auto standing{automatic_wagon(0.0, "standing")}; // the standing wagon faces away from the moving one - CHECK(moving->CollisionVelocity(end::front, standing.mover(), end::rear) == doctest::Approx(20.0)); - CHECK(standing->CollisionVelocity(end::rear, moving.mover(), end::front) == doctest::Approx(20.0)); + CHECK(moving->CollisionVelocity(VehicleEnd::front, standing.mover(), VehicleEnd::rear) == doctest::Approx(20.0)); + CHECK(standing->CollisionVelocity(VehicleEnd::rear, moving.mover(), VehicleEnd::front) == doctest::Approx(20.0)); // the standing wagon faces the moving one - CHECK(moving->CollisionVelocity(end::front, standing.mover(), end::front) == doctest::Approx(20.0)); - CHECK(standing->CollisionVelocity(end::front, moving.mover(), end::front) == doctest::Approx(20.0)); + CHECK(moving->CollisionVelocity(VehicleEnd::front, standing.mover(), VehicleEnd::front) == doctest::Approx(20.0)); + CHECK(standing->CollisionVelocity(VehicleEnd::front, moving.mover(), VehicleEnd::front) == doctest::Approx(20.0)); // the moving wagon backs up into the standing one auto backing{automatic_wagon(-20.0, "backing")}; - CHECK(backing->CollisionVelocity(end::rear, standing.mover(), end::front) == doctest::Approx(20.0)); - CHECK(backing->CollisionVelocity(end::rear, standing.mover(), end::rear) == doctest::Approx(20.0)); + CHECK(backing->CollisionVelocity(VehicleEnd::rear, standing.mover(), VehicleEnd::front) == doctest::Approx(20.0)); + CHECK(backing->CollisionVelocity(VehicleEnd::rear, standing.mover(), VehicleEnd::rear) == doctest::Approx(20.0)); // the moving wagon runs away from the standing one - CHECK(moving->CollisionVelocity(end::rear, standing.mover(), end::front) == doctest::Approx(-20.0)); + CHECK(moving->CollisionVelocity(VehicleEnd::rear, standing.mover(), VehicleEnd::front) == doctest::Approx(-20.0)); } // the coupling as the simulation runs it: two vehicles on a track, closing in on each other until the couplers (or @@ -183,28 +183,28 @@ TEST_CASE("couplers: automatic couplers catch right up to the safe closing speed auto standing{automatic_wagon(0.0, "standing")}; auto below{automatic_wagon(14.9, "below")}; - CHECK(below->CollisionVelocity(end::front, standing.mover(), end::rear) == doctest::Approx(14.9)); - CHECK(below->AutomaticCouplingSafe(end::front, standing.mover(), end::rear)); + CHECK(below->CollisionVelocity(VehicleEnd::front, standing.mover(), VehicleEnd::rear) == doctest::Approx(14.9)); + CHECK(below->AutomaticCouplingSafe(VehicleEnd::front, standing.mover(), VehicleEnd::rear)); auto above{automatic_wagon(15.1, "above")}; - CHECK(above->CollisionVelocity(end::front, standing.mover(), end::rear) == doctest::Approx(15.1)); - CHECK_FALSE(above->AutomaticCouplingSafe(end::front, standing.mover(), end::rear)); + CHECK(above->CollisionVelocity(VehicleEnd::front, standing.mover(), VehicleEnd::rear) == doctest::Approx(15.1)); + CHECK_FALSE(above->AutomaticCouplingSafe(VehicleEnd::front, standing.mover(), VehicleEnd::rear)); auto faster{automatic_wagon(15.5, "faster")}; - CHECK_FALSE(faster->AutomaticCouplingSafe(end::front, standing.mover(), end::rear)); + CHECK_FALSE(faster->AutomaticCouplingSafe(VehicleEnd::front, standing.mover(), VehicleEnd::rear)); } TEST_CASE("couplers: a wagon rolling slowly into a standing one couples with it") { crash_damage_setting const crashdamage{true}; auto moving{automatic_wagon(5.0, "moving")}; auto standing{automatic_wagon(0.0, "standing")}; - test::pair pair{moving, end::front, standing, end::rear, 1.0}; + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 1.0}; pair.run(3.0); REQUIRE(pair.coupled()); - CHECK(moving->Couplers[end::front].CouplingFlag == (Coupling::coupler | Coupling::brakeHose)); - CHECK(standing->Couplers[end::rear].CouplingFlag == (Coupling::coupler | Coupling::brakeHose)); - CHECK(moving->Couplers[end::front].Connected == &standing.mover()); + CHECK(moving->Couplers[VehicleEnd::front].CouplingFlag == (Coupling::coupler | Coupling::brakeHose)); + CHECK(standing->Couplers[VehicleEnd::rear].CouplingFlag == (Coupling::coupler | Coupling::brakeHose)); + CHECK(moving->Couplers[VehicleEnd::front].Connected == &standing.mover()); CHECK_FALSE(derailed(moving)); CHECK_FALSE(derailed(standing)); // coupled, they run on together @@ -218,7 +218,7 @@ TEST_CASE("couplers: a wagon hitting a standing one too fast doesn't couple, nor legacy_collisions const legacy; auto moving{automatic_wagon(30.0, "moving")}; auto standing{automatic_wagon(0.0, "standing")}; - test::pair pair{moving, end::front, standing, end::rear, 1.0}; + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 1.0}; auto touched{false}; auto parted{false}; @@ -227,12 +227,12 @@ TEST_CASE("couplers: a wagon hitting a standing one too fast doesn't couple, nor for (int i = 0; i < 1000; ++i) { pair.step(); // as far as the couplers know: the distance between them at the start of the step - auto const distance{moving->Neighbours[end::front].distance}; + auto const distance{moving->Neighbours[VehicleEnd::front].distance}; touched = touched || distance < 0.0; parted = parted || (touched && distance > 0.05); coupled = coupled || pair.coupled(); if (touched && false == parted) { - locked = locked && false == moving->Couplers[end::front].AutomaticCouplingAllowed && false == standing->Couplers[end::rear].AutomaticCouplingAllowed; + locked = locked && false == moving->Couplers[VehicleEnd::front].AutomaticCouplingAllowed && false == standing->Couplers[VehicleEnd::rear].AutomaticCouplingAllowed; } } @@ -253,17 +253,17 @@ TEST_CASE("couplers: the automatic coupling locked by a hit is unlocked once the auto moving{automatic_wagon(3.0, "moving")}; auto standing{automatic_wagon(0.0, "standing")}; // as a hit too fast or manual uncoupling leaves them - moving->Couplers[end::front].AutomaticCouplingAllowed = false; - standing->Couplers[end::rear].AutomaticCouplingAllowed = false; + moving->Couplers[VehicleEnd::front].AutomaticCouplingAllowed = false; + standing->Couplers[VehicleEnd::rear].AutomaticCouplingAllowed = false; SUBCASE("parted by more than 5 cm, they couple on the next approach") { - test::pair pair{moving, end::front, standing, end::rear, 0.5}; + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 0.5}; pair.step(); - CHECK(moving->Couplers[end::front].AutomaticCouplingAllowed); + CHECK(moving->Couplers[VehicleEnd::front].AutomaticCouplingAllowed); CHECK(couple_during(pair, 3.0)); } SUBCASE("kept together, they don't") { - test::pair pair{moving, end::front, standing, end::rear, 0.0}; + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 0.0}; auto coupled{false}; for (int i = 0; i < 300; ++i) { pair.step(); @@ -285,7 +285,7 @@ TEST_CASE("couplers: a hit a little too fast for the couplers bounces the vehicl legacy_collisions const legacy; auto moving{automatic_wagon(20.0, "moving")}; auto standing{automatic_wagon(0.0, "standing")}; - test::pair pair{moving, end::front, standing, end::rear, 1.0}; + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 1.0}; CHECK_FALSE(couple_during(pair, 3.0)); CHECK_FALSE(derailed(moving)); @@ -301,7 +301,7 @@ TEST_CASE("couplers: a hit too fast for the couplers derails the vehicles over t SUBCASE("equal masses: both derail") { auto moving{automatic_wagon(30.0, "moving")}; auto standing{automatic_wagon(0.0, "standing")}; - test::pair pair{moving, end::front, standing, end::rear, 1.0}; + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 1.0}; CHECK_FALSE(couple_during(pair, 5.0)); CHECK(derailed(moving)); CHECK(derailed(standing)); @@ -309,7 +309,7 @@ TEST_CASE("couplers: a hit too fast for the couplers derails the vehicles over t SUBCASE("half the mass: between the safe closing speed and twice that, only the lighter one derails") { auto light{automatic_wagon(27.0, "light")}; auto heavy{heavy_automatic_wagon(0.0, "heavy")}; - test::pair pair{light, end::front, heavy, end::rear, 1.0}; + test::pair pair{light, VehicleEnd::front, heavy, VehicleEnd::rear, 1.0}; CHECK_FALSE(couple_during(pair, 5.0)); CHECK(derailed(light)); CHECK_FALSE(derailed(heavy)); @@ -317,7 +317,7 @@ TEST_CASE("couplers: a hit too fast for the couplers derails the vehicles over t SUBCASE("half the mass: above twice the safe closing speed both derail") { auto light{automatic_wagon(45.0, "light")}; auto heavy{heavy_automatic_wagon(0.0, "heavy")}; - test::pair pair{light, end::front, heavy, end::rear, 1.0}; + test::pair pair{light, VehicleEnd::front, heavy, VehicleEnd::rear, 1.0}; CHECK_FALSE(couple_during(pair, 5.0)); CHECK(derailed(light)); CHECK(derailed(heavy)); @@ -325,7 +325,7 @@ TEST_CASE("couplers: a hit too fast for the couplers derails the vehicles over t SUBCASE("half the mass: below the safe closing speed the couplers catch, nothing derails") { auto light{automatic_wagon(12.0, "light")}; auto heavy{heavy_automatic_wagon(0.0, "heavy")}; - test::pair pair{light, end::front, heavy, end::rear, 1.0}; + test::pair pair{light, VehicleEnd::front, heavy, VehicleEnd::rear, 1.0}; CHECK(couple_during(pair, 5.0)); CHECK_FALSE(derailed(light)); CHECK_FALSE(derailed(heavy)); @@ -339,7 +339,7 @@ TEST_CASE("couplers: wagons running head-on into each other couple only up to th SUBCASE("7 + 7 km/h, the couplers catch") { auto first{automatic_wagon(7.0, "first")}; auto second{automatic_wagon(7.0, "second")}; - test::pair pair{first, end::front, second, end::front, 1.0}; + test::pair pair{first, VehicleEnd::front, second, VehicleEnd::front, 1.0}; CHECK(couple_during(pair, 3.0)); CHECK_FALSE(derailed(first)); CHECK_FALSE(derailed(second)); @@ -347,7 +347,7 @@ TEST_CASE("couplers: wagons running head-on into each other couple only up to th SUBCASE("8 + 8 km/h, the wagons bounce apart") { auto first{automatic_wagon(8.0, "first")}; auto second{automatic_wagon(8.0, "second")}; - test::pair pair{first, end::front, second, end::front, 1.0}; + test::pair pair{first, VehicleEnd::front, second, VehicleEnd::front, 1.0}; CHECK_FALSE(couple_during(pair, 3.0)); CHECK_FALSE(derailed(first)); CHECK_FALSE(derailed(second)); @@ -358,7 +358,7 @@ TEST_CASE("couplers: wagons running head-on into each other couple only up to th SUBCASE("backing up, 8 + 8 km/h, the wagons bounce apart") { auto first{automatic_wagon(-8.0, "first")}; auto second{automatic_wagon(-8.0, "second")}; - test::pair pair{first, end::rear, second, end::rear, 1.0}; + test::pair pair{first, VehicleEnd::rear, second, VehicleEnd::rear, 1.0}; CHECK_FALSE(couple_during(pair, 3.0)); CHECK(first.speed() > 0.0); CHECK(second.speed() > 0.0); @@ -366,7 +366,7 @@ TEST_CASE("couplers: wagons running head-on into each other couple only up to th SUBCASE("15 + 15 km/h, both derail") { auto first{automatic_wagon(15.0, "first")}; auto second{automatic_wagon(15.0, "second")}; - test::pair pair{first, end::front, second, end::front, 1.0}; + test::pair pair{first, VehicleEnd::front, second, VehicleEnd::front, 1.0}; CHECK_FALSE(couple_during(pair, 5.0)); CHECK(derailed(first)); CHECK(derailed(second)); @@ -380,10 +380,10 @@ TEST_CASE("couplers: wagons running head-on into each other couple only up to th TEST_CASE("couplers: a wagon hit head-on runs off the same as one hit from behind") { // without automatic couplers or crash damage, the collision alone crash_damage_setting const crashdamage{false}; - auto speeds_after_hit = [](int StruckEnd) { + auto speeds_after_hit = [](VehicleEnd StruckEnd) { auto moving{vehicle{definition::load("wagon"), 20.0, "moving"}}; auto struck{vehicle{definition::load("wagon"), 0.0, "struck"}}; - test::pair pair{moving, end::front, struck, StruckEnd, 0.5}; + test::pair pair{moving, VehicleEnd::front, struck, StruckEnd, 0.5}; auto touched{false}; for (int i = 0; i < 300; ++i) { pair.step(); @@ -398,8 +398,8 @@ TEST_CASE("couplers: a wagon hit head-on runs off the same as one hit from behin return std::make_pair(moving.speed(), struck.speed()); }; - auto const [hitterfrombehind, struckfrombehind]{speeds_after_hit(end::rear)}; - auto const [hitterheadon, struckheadon]{speeds_after_hit(end::front)}; + auto const [hitterfrombehind, struckfrombehind]{speeds_after_hit(VehicleEnd::rear)}; + auto const [hitterheadon, struckheadon]{speeds_after_hit(VehicleEnd::front)}; // hit from behind, the struck wagon runs off forwards, faster than the hitter CHECK(struckfrombehind > 10.0); @@ -415,8 +415,8 @@ TEST_CASE("couplers: an automatic coupler doesn't catch a coupler of another typ crash_damage_setting const crashdamage{true}; auto moving{automatic_wagon(5.0, "moving")}; auto standing{vehicle{definition::load("wagon"), 0.0, "standing"}}; - REQUIRE(standing->Couplers[end::rear].type() == TCouplerType::Screw); - test::pair pair{moving, end::front, standing, end::rear, 1.0}; + REQUIRE(standing->Couplers[VehicleEnd::rear].type() == TCouplerType::Screw); + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 1.0}; CHECK_FALSE(couple_during(pair, 3.0)); } @@ -428,15 +428,15 @@ TEST_CASE("couplers: automatic couplers of different control systems couple with SUBCASE("the same control system") { auto standing{vehicle{automatic_definition(flag).set("BuffCoupl", "ControlType", "first"), 0.0, "standing"}}; - REQUIRE(standing->Couplers[end::rear].control_type == "first"); - test::pair pair{moving, end::front, standing, end::rear, 1.0}; + REQUIRE(standing->Couplers[VehicleEnd::rear].control_type == "first"); + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 1.0}; REQUIRE(couple_during(pair, 3.0)); CHECK(pair.coupling() == flag); } SUBCASE("a different one") { auto standing{vehicle{automatic_definition(flag).set("BuffCoupl", "ControlType", "second"), 0.0, "standing"}}; - REQUIRE(standing->Couplers[end::rear].control_type == "second"); - test::pair pair{moving, end::front, standing, end::rear, 1.0}; + REQUIRE(standing->Couplers[VehicleEnd::rear].control_type == "second"); + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 1.0}; REQUIRE(couple_during(pair, 3.0)); CHECK(pair.coupling() == (Coupling::coupler | Coupling::brakeHose)); } @@ -451,26 +451,26 @@ TEST_CASE("couplers: the coupler force of vehicles facing each other lands on th auto second{automatic_wagon(0.0, "second")}; SUBCASE("facing each other") { - test::pair pair{first, end::front, second, end::front, 1.0}; + test::pair pair{first, VehicleEnd::front, second, VehicleEnd::front, 1.0}; pair.run(5.0); REQUIRE(pair.coupled()); pair.step(); - REQUIRE(second->Couplers[end::front].CForce != 0.0); - CHECK(first->Couplers[end::front].CForce == doctest::Approx(second->Couplers[end::front].CForce)); - CHECK(first->Couplers[end::rear].CForce == 0.0); // nothing there - CHECK(second->Couplers[end::rear].CForce == 0.0); + REQUIRE(second->Couplers[VehicleEnd::front].CForce != 0.0); + CHECK(first->Couplers[VehicleEnd::front].CForce == doctest::Approx(second->Couplers[VehicleEnd::front].CForce)); + CHECK(first->Couplers[VehicleEnd::rear].CForce == 0.0); // nothing there + CHECK(second->Couplers[VehicleEnd::rear].CForce == 0.0); } SUBCASE("facing the same way") { - test::pair pair{first, end::front, second, end::rear, 1.0}; + test::pair pair{first, VehicleEnd::front, second, VehicleEnd::rear, 1.0}; pair.run(5.0); REQUIRE(pair.coupled()); pair.step(); - REQUIRE(second->Couplers[end::rear].CForce != 0.0); - CHECK(first->Couplers[end::front].CForce == doctest::Approx(-second->Couplers[end::rear].CForce)); - CHECK(first->Couplers[end::rear].CForce == 0.0); - CHECK(second->Couplers[end::front].CForce == 0.0); + REQUIRE(second->Couplers[VehicleEnd::rear].CForce != 0.0); + CHECK(first->Couplers[VehicleEnd::front].CForce == doctest::Approx(-second->Couplers[VehicleEnd::rear].CForce)); + CHECK(first->Couplers[VehicleEnd::rear].CForce == 0.0); + CHECK(second->Couplers[VehicleEnd::front].CForce == 0.0); } } @@ -487,7 +487,7 @@ vehicle articulated_wagon(double Velocity, std::string const &Name) { } // couples the facing ends of the two vehicles for good, as the scenery does for an articulated set -void join(vehicle &First, int FirstEnd, vehicle &Second, int SecondEnd) { +void join(vehicle &First, VehicleEnd FirstEnd, vehicle &Second, VehicleEnd SecondEnd) { REQUIRE(First->Attach(FirstEnd, SecondEnd, &Second.mover(), Coupling::coupler, true, false)); REQUIRE(Second->Attach(SecondEnd, FirstEnd, &First.mover(), Coupling::coupler, true, false)); } @@ -496,7 +496,7 @@ void join(vehicle &First, int FirstEnd, vehicle &Second, int SecondEnd) { TEST_CASE("couplers: an articulated joint takes its full tensile force within its travel") { auto wagon{articulated_wagon(0.0, "wagon")}; - auto const &joint{wagon->Couplers[end::front]}; + auto const &joint{wagon->Couplers[VehicleEnd::front]}; REQUIRE(joint.type() == TCouplerType::Articulated); CHECK(joint.SpringKC * joint.DmaxC >= doctest::Approx(joint.FmaxC)); @@ -511,8 +511,8 @@ TEST_CASE("couplers: an articulated set keeps its momentum when one section jerk // and run on together at half the speed, as the momentum they have between them dictates auto front_section{articulated_wagon(20.0, "front")}; auto rear_section{articulated_wagon(0.1, "rear")}; - join(rear_section, end::front, front_section, end::rear); - test::pair pair{rear_section, end::front, front_section, end::rear, 0.0}; + join(rear_section, VehicleEnd::front, front_section, VehicleEnd::rear); + test::pair pair{rear_section, VehicleEnd::front, front_section, VehicleEnd::rear, 0.0}; REQUIRE(pair.coupled()); // brakes released, as a locomotive keeps them front_section.hold_brake_pipe(5.0); @@ -531,8 +531,8 @@ TEST_CASE("couplers: a collision of coupled vehicles keeps the momentum of the p // the same jerk through screw couplers, which collide when stretched beyond their travel as well auto front_wagon{vehicle{definition::load("wagon"), 30.0, "front"}}; auto rear_wagon{vehicle{definition::load("wagon"), 0.1, "rear"}}; - join(rear_wagon, end::front, front_wagon, end::rear); - test::pair pair{rear_wagon, end::front, front_wagon, end::rear, 0.0}; + join(rear_wagon, VehicleEnd::front, front_wagon, VehicleEnd::rear); + test::pair pair{rear_wagon, VehicleEnd::front, front_wagon, VehicleEnd::rear, 0.0}; REQUIRE(pair.coupled()); front_wagon.hold_brake_pipe(5.0); rear_wagon.hold_brake_pipe(5.0); @@ -565,9 +565,9 @@ constexpr CouplingSet scenario_coupling{Coupling::coupler | Coupling::brakeHose // couples the rear of the first vehicle to the front of the second one the way the scenery does (forced, from the // first one only), returns the coupling the pair got CouplingSet scenario_couple(vehicle &First, vehicle &Second, CouplingSet const couplings = scenario_coupling) { - REQUIRE(First->Attach(end::rear, end::front, &Second.mover(), couplings, true, false)); - CHECK(Second->Couplers[end::front].CouplingFlag == First->Couplers[end::rear].CouplingFlag); - return First->Couplers[end::rear].CouplingFlag; + REQUIRE(First->Attach(VehicleEnd::rear, VehicleEnd::front, &Second.mover(), couplings, true, false)); + CHECK(Second->Couplers[VehicleEnd::front].CouplingFlag == First->Couplers[VehicleEnd::rear].CouplingFlag); + return First->Couplers[VehicleEnd::rear].CouplingFlag; } } // namespace @@ -581,13 +581,13 @@ TEST_CASE("couplers: an electric and a diesel locomotive don't share their contr SUBCASE("a diesel-electric one with its own control system") { auto diesel{vehicle{definition::fiz("sm42_v1/6d1"), 0.0, "diesel"}}; REQUIRE(diesel->EngineType == TEngineType::DieselElectric); - CHECK_FALSE(electric->ControlCouplingAllowed(end::rear, diesel.mover(), end::front)); + CHECK_FALSE(electric->ControlCouplingAllowed(VehicleEnd::rear, diesel.mover(), VehicleEnd::front)); CHECK(scenario_couple(electric, diesel) == scenario_coupling.Without(Coupling::control)); } SUBCASE("a diesel-mechanical one without a control system named, either") { auto diesel{vehicle{definition::fiz("sm03_v1/sm03"), 0.0, "diesel"}}; REQUIRE(diesel->EngineType == TEngineType::DieselEngine); - CHECK_FALSE(diesel->ControlCouplingAllowed(end::front, electric.mover(), end::rear)); + CHECK_FALSE(diesel->ControlCouplingAllowed(VehicleEnd::front, electric.mover(), VehicleEnd::rear)); CHECK(scenario_couple(diesel, electric) == scenario_coupling.Without(Coupling::control)); } SUBCASE("unless both name the same control system") { @@ -603,7 +603,7 @@ TEST_CASE("couplers: an electric and a diesel locomotive don't share their contr SUBCASE("unless the check is turned off") { control_coupling_check_setting const off{false}; auto diesel{vehicle{definition::fiz("sm42_v1/6d1"), 0.0, "diesel"}}; - CHECK(electric->ControlCouplingAllowed(end::rear, diesel.mover(), end::front)); + CHECK(electric->ControlCouplingAllowed(VehicleEnd::rear, diesel.mover(), VehicleEnd::front)); CHECK(scenario_couple(electric, diesel) == scenario_coupling); } } @@ -646,13 +646,13 @@ TEST_CASE("couplers: automatic couplers of an electric and a diesel locomotive c SUBCASE("a diesel one") { auto standing{vehicle{automatic("sm03_v1/sm03"), 0.0, "standing"}}; - test::pair pair{moving, end::front, standing, end::rear, 1.0}; + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 1.0}; REQUIRE(couple_during(pair, 3.0)); CHECK(pair.coupling() == (Coupling::coupler | Coupling::brakeHose)); } SUBCASE("an electric one") { auto standing{vehicle{automatic("ep09_v2/104e"), 0.0, "standing"}}; - test::pair pair{moving, end::front, standing, end::rear, 1.0}; + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 1.0}; REQUIRE(couple_during(pair, 3.0)); CHECK(pair.coupling() == flag); } @@ -664,8 +664,8 @@ TEST_CASE("couplers: the AI and the player get the coupling the vehicles can tak auto diesel{vehicle{definition::fiz("sm42_v1/6d1"), 0.0, "diesel"}}; auto other{vehicle{definition::fiz("ep09_v2/104e"), 0.0, "other"}}; - CHECK(electric->CompatibleCoupling(end::rear, diesel.mover(), end::front, scenario_coupling) == scenario_coupling.Without(Coupling::control)); - CHECK(electric->CompatibleCoupling(end::rear, other.mover(), end::front, scenario_coupling) == scenario_coupling); + CHECK(electric->CompatibleCoupling(VehicleEnd::rear, diesel.mover(), VehicleEnd::front, scenario_coupling) == scenario_coupling.Without(Coupling::control)); + CHECK(electric->CompatibleCoupling(VehicleEnd::rear, other.mover(), VehicleEnd::front, scenario_coupling) == scenario_coupling); // nothing to take away without the control connection asked for - CHECK(electric->CompatibleCoupling(end::rear, diesel.mover(), end::front, Coupling::coupler) == Coupling::coupler); + CHECK(electric->CompatibleCoupling(VehicleEnd::rear, diesel.mover(), VehicleEnd::front, Coupling::coupler) == Coupling::coupler); } diff --git a/tests/unit/test_couplers_trains.cpp b/tests/unit/test_couplers_trains.cpp index ccd0ffae4..cdd4cd9a3 100644 --- a/tests/unit/test_couplers_trains.cpp +++ b/tests/unit/test_couplers_trains.cpp @@ -39,35 +39,35 @@ TEST_CASE("couplers: coupled by hand, touching or apart, of the same kind or not train.step(); // nothing to couple to, or nothing to couple - CHECK_FALSE(locomotive.Attach(end::rear, end::front, nullptr, Coupling::coupler)); - CHECK_FALSE(locomotive.Attach(end::rear, end::front, &wagon, Coupling::none)); + CHECK_FALSE(locomotive.Attach(VehicleEnd::rear, VehicleEnd::front, nullptr, Coupling::coupler)); + CHECK_FALSE(locomotive.Attach(VehicleEnd::rear, VehicleEnd::front, &wagon, Coupling::none)); // the hook first: the coupler alone, which sounds - locomotive.Couplers[end::rear].sounds = 0; - REQUIRE(locomotive.Attach(end::rear, end::front, &wagon, Coupling::coupler)); - CHECK(locomotive.Couplers[end::rear].Connected == &wagon); - CHECK(wagon.Couplers[end::front].Connected == &locomotive); - CHECK(wagon.Couplers[end::front].CouplingFlag == Coupling::coupler); - CHECK(locomotive.Couplers[end::rear].sounds == sound::attachcoupler); + locomotive.Couplers[VehicleEnd::rear].sounds = 0; + REQUIRE(locomotive.Attach(VehicleEnd::rear, VehicleEnd::front, &wagon, Coupling::coupler)); + CHECK(locomotive.Couplers[VehicleEnd::rear].Connected == &wagon); + CHECK(wagon.Couplers[VehicleEnd::front].Connected == &locomotive); + CHECK(wagon.Couplers[VehicleEnd::front].CouplingFlag == Coupling::coupler); + CHECK(locomotive.Couplers[VehicleEnd::rear].sounds == sound::attachcoupler); // then the hoses: only what changes sounds - locomotive.Couplers[end::rear].sounds = 0; - REQUIRE(locomotive.Attach(end::rear, end::front, &wagon, Coupling::coupler | Coupling::brakeHose | Coupling::mainHose)); - CHECK(locomotive.Couplers[end::rear].sounds == (sound::attachbrakehose | sound::attachmainhose)); + locomotive.Couplers[VehicleEnd::rear].sounds = 0; + REQUIRE(locomotive.Attach(VehicleEnd::rear, VehicleEnd::front, &wagon, Coupling::coupler | Coupling::brakeHose | Coupling::mainHose)); + CHECK(locomotive.Couplers[VehicleEnd::rear].sounds == (sound::attachbrakehose | sound::attachmainhose)); // and again, quietly, the other side naming the coupler by the one it's connected to (2) - locomotive.Couplers[end::rear].sounds = 0; - REQUIRE(wagon.Attach(end::front, 2, &locomotive, Coupling::coupler | Coupling::brakeHose, false, false)); - CHECK(locomotive.Couplers[end::rear].CouplingFlag == (Coupling::coupler | Coupling::brakeHose)); - CHECK(locomotive.Couplers[end::rear].sounds == 0); + locomotive.Couplers[VehicleEnd::rear].sounds = 0; + REQUIRE(wagon.Attach(NumberOf(VehicleEnd::front), 2, &locomotive, Coupling::coupler | Coupling::brakeHose, false, false)); + CHECK(locomotive.Couplers[VehicleEnd::rear].CouplingFlag == (Coupling::coupler | Coupling::brakeHose)); + CHECK(locomotive.Couplers[VehicleEnd::rear].sounds == 0); // a screw coupler with the buffers pressed together comes apart whole train.step(); - CHECK(locomotive.DettachStatus(end::rear) < 0); - locomotive.Couplers[end::rear].sounds = 0; - CHECK(locomotive.Dettach(end::rear)); - CHECK(locomotive.Couplers[end::rear].Connected == nullptr); - CHECK(wagon.Couplers[end::front].Connected == nullptr); - CHECK(locomotive.Couplers[end::rear].sounds == (sound::detach | sound::attachcoupler | sound::attachbrakehose)); - CHECK(locomotive.DettachStatus(end::rear) == 0); - CHECK(locomotive.Dettach(end::rear)); + CHECK(locomotive.DettachStatus(VehicleEnd::rear) < 0); + locomotive.Couplers[VehicleEnd::rear].sounds = 0; + CHECK(locomotive.Dettach(VehicleEnd::rear)); + CHECK(locomotive.Couplers[VehicleEnd::rear].Connected == nullptr); + CHECK(wagon.Couplers[VehicleEnd::front].Connected == nullptr); + CHECK(locomotive.Couplers[VehicleEnd::rear].sounds == (sound::detach | sound::attachcoupler | sound::attachbrakehose)); + CHECK(locomotive.DettachStatus(VehicleEnd::rear) == 0); + CHECK(locomotive.Dettach(VehicleEnd::rear)); } TEST_CASE("couplers: a screw coupler uncoupled with the buffers apart, or with the hoses alone, or broken") { @@ -88,24 +88,24 @@ TEST_CASE("couplers: a screw coupler uncoupled with the buffers apart, or with t consist train; auto &locomotive{train.add(definition::fiz("4e_v1/4e")).mover()}; auto &wagon{train.add(definition::fiz("3wl_v2/3wl"), 0, Coupling::none, 0.0, gap).mover()}; - REQUIRE(locomotive.Attach(end::rear, end::front, &wagon, couplingtype, true)); + REQUIRE(locomotive.Attach(VehicleEnd::rear, VehicleEnd::front, &wagon, couplingtype, true)); if (damaged) { locomotive.DamageFlag.Set(VehicleDamage::coupling); } train.step(); - CHECK((locomotive.DettachStatus(end::rear) < 0) == apart); - CHECK(locomotive.Dettach(end::rear) == apart); + CHECK((locomotive.DettachStatus(VehicleEnd::rear) < 0) == apart); + CHECK(locomotive.Dettach(VehicleEnd::rear) == apart); // what's left when it doesn't come apart is the coupler, the hoses taken off - CHECK(locomotive.Couplers[end::rear].CouplingFlag == (apart ? Coupling::none : Coupling::coupler)); - CHECK(wagon.Couplers[end::front].CouplingFlag == (apart ? Coupling::none : Coupling::coupler)); + CHECK(locomotive.Couplers[VehicleEnd::rear].CouplingFlag == (apart ? Coupling::none : Coupling::coupler)); + CHECK(wagon.Couplers[VehicleEnd::front].CouplingFlag == (apart ? Coupling::none : Coupling::coupler)); } // couplers of different kinds don't couple, unless forced consist train; auto &locomotive{train.add(definition::fiz("4e_v1/4e")).mover()}; auto &unit{train.add(definition::fiz("en57_v1/5bgb"), 0, Coupling::none).mover()}; train.step(); - CHECK_FALSE(locomotive.Attach(end::rear, end::front, &unit, Coupling::coupler)); - CHECK(locomotive.Attach(end::rear, end::front, &unit, Coupling::coupler, true)); + CHECK_FALSE(locomotive.Attach(VehicleEnd::rear, VehicleEnd::front, &unit, Coupling::coupler)); + CHECK(locomotive.Attach(VehicleEnd::rear, VehicleEnd::front, &unit, Coupling::coupler, true)); } TEST_CASE("couplers: automatic couplers coupling on contact") { @@ -129,11 +129,11 @@ TEST_CASE("couplers: automatic couplers coupling on contact") { scenario.wait(10.0); auto &first{scenario.vehicle(0)}; auto &second{scenario.vehicle(1)}; - CHECK(first.Couplers[end::rear].CouplingFlag == couplingtype); - CHECK(second.Couplers[end::front].CouplingFlag == couplingtype); + CHECK(first.Couplers[VehicleEnd::rear].CouplingFlag == couplingtype); + CHECK(second.Couplers[VehicleEnd::front].CouplingFlag == couplingtype); // once coupled, not again until uncoupled; the vehicle which coupled marks it for the AI - CHECK_FALSE(first.Couplers[end::rear].AutomaticCouplingAllowed); - CHECK_FALSE(second.Couplers[end::front].AutomaticCouplingAllowed); + CHECK_FALSE(first.Couplers[VehicleEnd::rear].AutomaticCouplingAllowed); + CHECK_FALSE(second.Couplers[VehicleEnd::front].AutomaticCouplingAllowed); CHECK((TestFlag(first.AIFlag, sound::attachcoupler) || TestFlag(second.AIFlag, sound::attachcoupler))); scenario.check(); } @@ -143,23 +143,23 @@ TEST_CASE("couplers: a coupler broken, with its brake hose torn off") { consist train; auto &locomotive{train.add(definition::fiz("4e_v1/4e")).mover()}; auto &wagon{train.add(definition::fiz("3wl_v2/3wl")).mover()}; - REQUIRE(locomotive.Couplers[end::rear].Connected == &wagon); - locomotive.damage_coupler(end::rear); + REQUIRE(locomotive.Couplers[VehicleEnd::rear].Connected == &wagon); + locomotive.damage_coupler(VehicleEnd::rear); CHECK(locomotive.DamageFlag.HasAll(VehicleDamage::coupling)); CHECK(locomotive.AlarmChainFlag); - CHECK(locomotive.Couplers[end::rear].CouplingFlag == Coupling::none); - CHECK(wagon.Couplers[end::front].CouplingFlag == Coupling::none); + CHECK(locomotive.Couplers[VehicleEnd::rear].CouplingFlag == Coupling::none); + CHECK(wagon.Couplers[VehicleEnd::front].CouplingFlag == Coupling::none); // the front coupler of the wagon, broken on its own: no hose to tear - wagon.damage_coupler(end::front); + wagon.damage_coupler(VehicleEnd::front); CHECK(wagon.DamageFlag.HasAll(VehicleDamage::coupling)); CHECK_FALSE(wagon.AlarmChainFlag); // articulated couplers don't break consist articulated; auto &unit{articulated.add(definition::fiz("impuls_v1/31we-a_pr")).mover()}; articulated.add(definition::fiz("impuls_v1/31we-b_pr")); - unit.damage_coupler(end::rear); + unit.damage_coupler(VehicleEnd::rear); CHECK_FALSE(unit.DamageFlag.HasAll(VehicleDamage::coupling)); - CHECK(unit.Couplers[end::rear].CouplingFlag != Coupling::none); + CHECK(unit.Couplers[VehicleEnd::rear].CouplingFlag != Coupling::none); } TEST_CASE("couplers: collisions fast enough to derail") { diff --git a/tests/unit/test_definition.cpp b/tests/unit/test_definition.cpp index e9a79d9e4..2f87906ae 100644 --- a/tests/unit/test_definition.cpp +++ b/tests/unit/test_definition.cpp @@ -42,7 +42,7 @@ TEST_CASE("definition: rows of a table section reach the vehicle") { CHECK(wagon->LightsPosNo == 2); CHECK(wagon->LightsPos == 1); - CHECK(wagon->Lights[end::front][1] == pc1); + CHECK(wagon->Lights[VehicleEnd::front][1] == pc1); } TEST_CASE("definition: lines the loader skips or trims: comments, a hash anywhere, leading spaces, carriage returns") { diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp index 1c96b4f52..32feec44d 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -134,7 +134,7 @@ TEST_CASE("derailment: the model of eu07.ini") { TEST_CASE("derailment: the brake hoses tear") { model_setting const physical{global_settings::derailment_model::physical}; vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 150.0}; - eu07vehicle->Couplers[end::rear].CouplingFlag = Coupling::coupler | Coupling::brakeHose; + eu07vehicle->Couplers[VehicleEnd::rear].CouplingFlag = Coupling::coupler | Coupling::brakeHose; test::track curve; curve.radius = 300.0; for (int step = 0; step < 20; ++step) { diff --git a/tests/unit/test_door_closure.cpp b/tests/unit/test_door_closure.cpp index c92d8fef8..4c80670f0 100644 --- a/tests/unit/test_door_closure.cpp +++ b/tests/unit/test_door_closure.cpp @@ -50,13 +50,13 @@ TEST_CASE("door closure: a unit with permits, locked, released by the permit and CHECK(consist_closure(scenario) == door_closure_t::locked); scenario.act("permit left"); - cab.PermitDoors(side::left, true); + cab.PermitDoors(VehicleSide::left, true); scenario.wait(2.0); CHECK(last.door_closure() == door_closure_t::released); CHECK(consist_closure(scenario) == door_closure_t::released); scenario.act("the last car opens its own door"); - last.OperateDoors(side::left, true, range_t::local); + last.OperateDoors(VehicleSide::left, true, range_t::local); scenario.wait(5.0); // the cab's own doors stay closed, the train is open all the same CHECK(cab.door_closure() == door_closure_t::released); @@ -64,15 +64,15 @@ TEST_CASE("door closure: a unit with permits, locked, released by the permit and CHECK(consist_closure(scenario) == door_closure_t::open); scenario.act("close, the steps stay out under the permit"); - last.OperateDoors(side::left, false, range_t::local); - cab.OperateDoors(side::left, false); + last.OperateDoors(VehicleSide::left, false, range_t::local); + cab.OperateDoors(VehicleSide::left, false); scenario.wait(10.0); - CHECK(last.Doors.instances[side::left].position <= 0.f); + CHECK(last.Doors.instances[VehicleSide::left].position <= 0.f); // a step out isn't a closed door CHECK(consist_closure(scenario) == door_closure_t::open); scenario.act("revoke the permit"); - cab.PermitDoors(side::left, false); + cab.PermitDoors(VehicleSide::left, false); scenario.wait(10.0); CHECK(consist_closure(scenario) == door_closure_t::locked); } @@ -90,11 +90,11 @@ TEST_CASE("door closure: the doors of a unit without permits are released at a s CHECK(middle.door_closure() == door_closure_t::locked); CHECK(consist_closure(scenario) == door_closure_t::released); scenario.act("open right"); - cab.OperateDoors(side::right, true); + cab.OperateDoors(VehicleSide::right, true); scenario.wait(10.0); CHECK(consist_closure(scenario) == door_closure_t::open); scenario.act("close right"); - cab.OperateDoors(side::right, false); + cab.OperateDoors(VehicleSide::right, false); scenario.wait(10.0); CHECK(consist_closure(scenario) == door_closure_t::released); } @@ -105,8 +105,8 @@ TEST_CASE("door closure: a locomotive has no doors to signal, its coach does") { scenario.start_up(); CHECK(scenario.cab().door_closure() == door_closure_t::none); scenario.act("open right"); - scenario.cab().PermitDoors(side::right, true); - scenario.cab().OperateDoors(side::right, true); + scenario.cab().PermitDoors(VehicleSide::right, true); + scenario.cab().OperateDoors(VehicleSide::right, true); scenario.wait(10.0); CHECK(scenario.vehicle(1).door_closure() == door_closure_t::open); CHECK(consist_closure(scenario) == door_closure_t::open); diff --git a/tests/unit/test_genset.cpp b/tests/unit/test_genset.cpp index cb39e532d..be52eab9a 100644 --- a/tests/unit/test_genset.cpp +++ b/tests/unit/test_genset.cpp @@ -527,7 +527,7 @@ TEST_CASE("genset: one genset feeds the next car through the high voltage coupli consist train; auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 1).mover()}; auto &second{train.add(dragon().set("BuffCoupl", "AllowedFlag", 47)).mover()}; - REQUIRE(first.Couplers[end::rear].CouplingFlag.HasAny(Coupling::highVoltage)); + REQUIRE(first.Couplers[VehicleEnd::rear].CouplingFlag.HasAny(Coupling::highVoltage)); wake(first); REQUIRE(first.TractionModeSwitch(traction_mode::genset)); first.GensetSwitch(true); @@ -557,7 +557,7 @@ TEST_CASE("genset: the selector command travels along the train") { consist train; auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 1).mover()}; auto &second{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 0, coupling).mover()}; - REQUIRE(first.Couplers[end::rear].CouplingFlag.HasAny(Coupling::control)); + REQUIRE(first.Couplers[VehicleEnd::rear].CouplingFlag.HasAny(Coupling::control)); wake(first); train.run(1.0, no_wire); CHECK(first.TractionModeSwitch(traction_mode::genset, range_t::consist)); diff --git a/tests/unit/test_handover.cpp b/tests/unit/test_handover.cpp index ff4a0df82..3cecb9b51 100644 --- a/tests/unit/test_handover.cpp +++ b/tests/unit/test_handover.cpp @@ -95,17 +95,17 @@ TEST_CASE("handover: the light selector moves to the position giving the head li REQUIRE(cab->LightsPos == 1); // untouched selector: lights off SUBCASE("Pc1") { - CHECK(handover::light_selector_position(cab.mover(), end::front, pc1, allheadlights) == 2); + CHECK(handover::light_selector_position(cab.mover(), NumberOf(VehicleEnd::front), pc1, allheadlights) == 2); } SUBCASE("lights off") { - CHECK(handover::light_selector_position(cab.mover(), end::front, 0, allheadlights) == 1); + CHECK(handover::light_selector_position(cab.mover(), NumberOf(VehicleEnd::front), 0, allheadlights) == 1); } SUBCASE("vehicle without the upper headlight, which the AI's Pc1 can't light") { auto const inventory{allheadlights & ~light::headlight_upper}; - CHECK(handover::light_selector_position(cab.mover(), end::front, pc1 & inventory, inventory) == 2); + CHECK(handover::light_selector_position(cab.mover(), NumberOf(VehicleEnd::front), pc1 & inventory, inventory) == 2); } SUBCASE("no position matches: the selector stays") { - CHECK(handover::light_selector_position(cab.mover(), end::front, light::headlight_left, allheadlights) == 1); + CHECK(handover::light_selector_position(cab.mover(), NumberOf(VehicleEnd::front), light::headlight_left, allheadlights) == 1); } } @@ -118,8 +118,8 @@ TEST_CASE("handover: the light selector stays within its table") { std::fill(std::begin(table) + cab->LightsPosNo, std::end(table), 0); } cab->LightsPosNo = 100; - CHECK(handover::light_selector_position(cab.mover(), end::front, pc1, allheadlights) == 2); - CHECK(handover::light_selector_position(cab.mover(), end::front, light::headlight_left, allheadlights) == 1); + CHECK(handover::light_selector_position(cab.mover(), NumberOf(VehicleEnd::front), pc1, allheadlights) == 2); + CHECK(handover::light_selector_position(cab.mover(), NumberOf(VehicleEnd::front), light::headlight_left, allheadlights) == 1); } SUBCASE("table other than the front or rear one: the selector stays") { CHECK(handover::light_selector_position(cab.mover(), -1, pc1, allheadlights) == 1); @@ -131,7 +131,7 @@ TEST_CASE("handover: the light selector already matching the lights stays") { auto cab{cab_vehicle()}; cab->LightsPos = 2; // Pc1 - CHECK(handover::light_selector_position(cab.mover(), end::front, pc1, allheadlights) == 2); + CHECK(handover::light_selector_position(cab.mover(), NumberOf(VehicleEnd::front), pc1, allheadlights) == 2); } TEST_CASE("handover: the headlight dimmer leaves the off position when the head lights are lit") { diff --git a/tests/unit/test_lights_preset_cablight.cpp b/tests/unit/test_lights_preset_cablight.cpp index 7c64c7d5a..fe079bfd4 100644 --- a/tests/unit/test_lights_preset_cablight.cpp +++ b/tests/unit/test_lights_preset_cablight.cpp @@ -21,7 +21,7 @@ TEST_CASE("lights preset cab light: a table without the column sets no position' .set("LightsList", "rows", {{0, 0}, {shunting, shunting}})}; REQUIRE(wagon->LightsPosNo == 2); - CHECK(wagon->Lights[end::front][1] == shunting); + CHECK(wagon->Lights[VehicleEnd::front][1] == shunting); CHECK_FALSE(wagon->LightsPresetCabLight(1).has_value()); CHECK_FALSE(wagon->LightsPresetCabLight(2).has_value()); } @@ -35,9 +35,9 @@ TEST_CASE("lights preset cab light: the third column turns the cab light off, on REQUIRE(wagon->LightsPosNo == 5); // the light columns read as before - CHECK(wagon->Lights[end::front][2] == shunting); - CHECK(wagon->Lights[end::rear][2] == shunting); - CHECK(wagon->Lights[end::rear][4] == 0); + CHECK(wagon->Lights[VehicleEnd::front][2] == shunting); + CHECK(wagon->Lights[VehicleEnd::rear][2] == shunting); + CHECK(wagon->Lights[VehicleEnd::rear][4] == 0); auto const off{wagon->LightsPresetCabLight(1)}; REQUIRE(off.has_value()); @@ -90,7 +90,7 @@ TEST_CASE("lights preset cab light: a stray note after the two columns is not re TMoverParameters wagon(0.0, "wagon", "test", 0); REQUIRE(wagon.LoadFIZ_Text(text)); REQUIRE(wagon.LightsPosNo == 2); - CHECK(wagon.Lights[end::front][1] == 38); - CHECK(wagon.Lights[end::rear][1] == 38); + CHECK(wagon.Lights[VehicleEnd::front][1] == 38); + CHECK(wagon.Lights[VehicleEnd::rear][1] == 38); CHECK_FALSE(wagon.LightsPresetCabLight(2).has_value()); } diff --git a/tests/unit/test_lights_programmer.cpp b/tests/unit/test_lights_programmer.cpp index 8a31563d8..cb6e65103 100644 --- a/tests/unit/test_lights_programmer.cpp +++ b/tests/unit/test_lights_programmer.cpp @@ -11,18 +11,18 @@ namespace { int const pc1{light::headlight_left | light::headlight_upper | light::headlight_right}; int const tailmarkers{light::redmarker_left | light::redmarker_right}; -std::array const cablights{pc1, tailmarkers}; // Lights[end::front], Lights[end::rear] +ByEnd const cablights{pc1, tailmarkers}; // Lights[VehicleEnd::front], Lights[VehicleEnd::rear] // the lights at the vehicle's own end, placed the way TDynamicObject::RaLightsSet() places them -int lights_at(lights_programmer::consist_lights const &Lights, int const Direction, end const Side) { - auto const headend{Direction > 0 ? end::front : end::rear}; +int lights_at(lights_programmer::consist_lights const &Lights, int const Direction, VehicleEnd const Side) { + auto const headend{Direction > 0 ? VehicleEnd::front : VehicleEnd::rear}; return Side == headend ? Lights.head : Lights.rear; } struct setup { int cab; // CabOccupied of the vehicle with the programmer int direction; // its iDirection - std::array coupled; // vehicle coupled at its end::front / end::rear + ByEnd coupled; // vehicle coupled at its VehicleEnd::front / VehicleEnd::rear }; lights_programmer::consist_lights lights_for(setup const &Setup) { @@ -36,14 +36,14 @@ lights_programmer::consist_lights lights_for(setup const &Setup) { TEST_CASE("lights programmer: a lone vehicle gets the cab's front lights ahead of the cab and its back lights behind it") { for (auto const direction : {0, 1}) { CAPTURE(direction); - // cab 1 faces end::front + // cab 1 faces VehicleEnd::front auto const fromcab1{lights_for({1, direction, {false, false}})}; - CHECK(lights_at(fromcab1, direction, end::front) == pc1); - CHECK(lights_at(fromcab1, direction, end::rear) == tailmarkers); - // cab -1 faces end::rear + CHECK(lights_at(fromcab1, direction, VehicleEnd::front) == pc1); + CHECK(lights_at(fromcab1, direction, VehicleEnd::rear) == tailmarkers); + // cab -1 faces VehicleEnd::rear auto const fromcab2{lights_for({-1, direction, {false, false}})}; - CHECK(lights_at(fromcab2, direction, end::rear) == pc1); - CHECK(lights_at(fromcab2, direction, end::front) == tailmarkers); + CHECK(lights_at(fromcab2, direction, VehicleEnd::rear) == pc1); + CHECK(lights_at(fromcab2, direction, VehicleEnd::front) == tailmarkers); } } @@ -52,14 +52,14 @@ TEST_CASE("lights programmer: the end with the train coupled goes dark, not the // the end with the train goes dark, the free end shows the lights meant for it for (auto const direction : {0, 1}) { for (auto const cab : {1, -1}) { - for (auto const trainend : {end::front, end::rear}) { + for (auto const trainend : VehicleEnds) { CAPTURE(direction); CAPTURE(cab); CAPTURE(trainend); - std::array coupled{false, false}; + ByEnd coupled{false, false}; coupled[trainend] = true; - auto const freeend{trainend == end::front ? end::rear : end::front}; - auto const cabfront{cab > 0 ? end::front : end::rear}; + auto const freeend{trainend == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front}; + auto const cabfront{cab > 0 ? VehicleEnd::front : VehicleEnd::rear}; auto const lights{lights_for({cab, direction, coupled})}; @@ -71,13 +71,13 @@ TEST_CASE("lights programmer: the end with the train coupled goes dark, not the } TEST_CASE("lights programmer: 6Dg driven backwards from its second cab position pulls the train with its head lights lit (eu07/maszyna#395)") { - // the reported case: the train coupled behind the driver (end::front, which cab -1 has at its back), the - // locomotive running towards end::rear, the train in tow. the head lights stay lit, the end with the train goes dark; + // the reported case: the train coupled behind the driver (VehicleEnd::front, which cab -1 has at its back), the + // locomotive running towards VehicleEnd::rear, the train in tow. the head lights stay lit, the end with the train goes dark; // before the fix the couplings were looked up at the swapped ends and it was the other way round auto const lights{lights_for({-1, 1, {true, false}})}; - CHECK(lights_at(lights, 1, end::rear) == pc1); - CHECK(lights_at(lights, 1, end::front) == 0); + CHECK(lights_at(lights, 1, VehicleEnd::rear) == pc1); + CHECK(lights_at(lights, 1, VehicleEnd::front) == 0); } TEST_CASE("lights programmer: a vehicle coupled at both ends stays dark") { diff --git a/tests/unit/test_line_contactors_interlock.cpp b/tests/unit/test_line_contactors_interlock.cpp index 28bfee94e..91274ad35 100644 --- a/tests/unit/test_line_contactors_interlock.cpp +++ b/tests/unit/test_line_contactors_interlock.cpp @@ -62,10 +62,10 @@ TEST_CASE("line contactors interlock: on the converter, they close only with the TEST_CASE("line contactors interlock: on the motor blowers, they close only with all of them running") { auto locomotive{ready("MotorBlowers")}; - locomotive->MotorBlowers[end::front].is_active = true; - locomotive->MotorBlowers[end::rear].is_active = false; + locomotive->MotorBlowers[VehicleEnd::front].is_active = true; + locomotive->MotorBlowers[VehicleEnd::rear].is_active = false; CHECK_FALSE(locomotive->MotorConnectorsCheck()); - locomotive->MotorBlowers[end::rear].is_active = true; + locomotive->MotorBlowers[VehicleEnd::rear].is_active = true; CHECK(locomotive->MotorConnectorsCheck()); } @@ -80,10 +80,10 @@ TEST_CASE("line contactors interlock: a blower starting with the speed needs to blower.is_enabled = true; // switched on by the driver blower.is_active = false; // the vehicle stands } - REQUIRE(locomotive->MotorBlowers[end::front].start_type == start_t::manual); + REQUIRE(locomotive->MotorBlowers[VehicleEnd::front].start_type == start_t::manual); CHECK(locomotive->MotorConnectorsCheck()); - auto &rear{locomotive->MotorBlowers[end::rear]}; + auto &rear{locomotive->MotorBlowers[VehicleEnd::rear]}; SUBCASE("switched off, it holds the contactors open") { rear.is_disabled = true; CHECK_FALSE(locomotive->MotorConnectorsCheck()); @@ -118,7 +118,7 @@ TEST_CASE("line contactors interlock: a blower starting with the speed needs to namespace { bool blowers_run(TMoverParameters const &Mover) { - return Mover.MotorBlowers[end::front].is_active && Mover.MotorBlowers[end::rear].is_active; + return Mover.MotorBlowers[VehicleEnd::front].is_active && Mover.MotorBlowers[VehicleEnd::rear].is_active; } // the driver's first power position, held until the line contactors close (their delay, the pressure switch) @@ -155,8 +155,8 @@ TEST_CASE("line contactors interlock: with blowers starting with the speed the v 0.0, "test", 1}; auto &mover{eu07.mover()}; REQUIRE(mover.LineContactorsInterlock == line_contactors_interlock::motor_blowers); - REQUIRE(mover.MotorBlowers[end::front].min_start_velocity == doctest::Approx(5.0)); - REQUIRE(mover.MotorBlowers[end::rear].sustain_time == doctest::Approx(10.0)); + REQUIRE(mover.MotorBlowers[VehicleEnd::front].min_start_velocity == doctest::Approx(5.0)); + REQUIRE(mover.MotorBlowers[VehicleEnd::rear].sustain_time == doctest::Approx(10.0)); auto driven{test::driving(eu07)}; REQUIRE(test::start_up(driven, line)); release(driven); @@ -221,7 +221,7 @@ TEST_CASE("line contactors interlock: a blower starting with the speed, switched REQUIRE(close_line_contactors(driven)); // the switch of the rear blower: off, the contactors open and stay open, standing as well as later - REQUIRE(mover.MotorBlowersSwitchOff(true, end::rear)); + REQUIRE(mover.MotorBlowersSwitchOff(true, VehicleEnd::rear)); test::drive(driven, line, 2.0); CHECK_FALSE(mover.StLinFlag); CHECK(std::abs(mover.Im) < 0.5); @@ -232,7 +232,7 @@ TEST_CASE("line contactors interlock: a blower starting with the speed, switched CHECK_FALSE(close_line_contactors(driven)); // back on, the vehicle starts - REQUIRE(mover.MotorBlowersSwitchOff(false, end::rear)); + REQUIRE(mover.MotorBlowersSwitchOff(false, VehicleEnd::rear)); while (mover.DecMainCtrl(1)) { // down to zero } diff --git a/tests/unit/test_loads.cpp b/tests/unit/test_loads.cpp index b4a9da62a..9440cd450 100644 --- a/tests/unit/test_loads.cpp +++ b/tests/unit/test_loads.cpp @@ -23,8 +23,8 @@ TEST_CASE("loads: the pantographs of an electric vehicle set up by the amount of vehicle et42{definition::fiz("et42_v2/112e-a")}; CHECK(et42->AssignLoad("pantstate", static_cast(amount))); CHECK(et42->DoubleTr == ((amount & 4) != 0 ? -1 : 1)); - CHECK(et42->Pantographs[end::front].valve.is_enabled == frontraised); - CHECK(et42->Pantographs[end::rear].valve.is_enabled == rearraised); + CHECK(et42->Pantographs[VehicleEnd::front].valve.is_enabled == frontraised); + CHECK(et42->Pantographs[VehicleEnd::rear].valve.is_enabled == rearraised); // the load itself stays as it was CHECK(et42->LoadAmount == doctest::Approx(0.0)); } diff --git a/tests/unit/test_mains_before_pantographs.cpp b/tests/unit/test_mains_before_pantographs.cpp index e9c70bb4c..efab5a572 100644 --- a/tests/unit/test_mains_before_pantographs.cpp +++ b/tests/unit/test_mains_before_pantographs.cpp @@ -39,7 +39,7 @@ void prepare(test::vehicle &Loco) { void raise_pantograph(test::vehicle &Loco, test::track const &Track = line) { Loco->OperatePantographsValve(operation_t::enable); - Loco->OperatePantographValve(end::rear, operation_t::enable); + Loco->OperatePantographValve(VehicleEnd::rear, operation_t::enable); Loco.run(5.0, Track); } @@ -93,17 +93,17 @@ TEST_CASE("mains before pantographs: without the flag the line breaker needs the close_line_breaker(loco); CHECK_FALSE(loco->Mains); raise_pantograph(loco); - CHECK(loco->Pantographs[end::rear].is_active); + CHECK(loco->Pantographs[VehicleEnd::rear].is_active); CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); close_line_breaker(loco); CHECK(loco->Mains); // the pantographs stay up with the line breaker open, and the line breaker opens without voltage loco->MainSwitch(false); loco.run(2.0, line); - CHECK(loco->Pantographs[end::rear].is_active); + CHECK(loco->Pantographs[VehicleEnd::rear].is_active); close_line_breaker(loco); REQUIRE(loco->Mains); - loco->OperatePantographValve(end::rear, operation_t::disable); + loco->OperatePantographValve(VehicleEnd::rear, operation_t::disable); loco.run(2.0, line); CHECK_FALSE(loco->Mains); } @@ -114,28 +114,28 @@ TEST_CASE("mains before pantographs: with the flag the pantographs rise only thr prepare(loco); // the pantographs stay down while the line breaker is open raise_pantograph(loco); - CHECK_FALSE(loco->Pantographs[end::rear].is_active); + CHECK_FALSE(loco->Pantographs[VehicleEnd::rear].is_active); CHECK(loco->PantographVoltage == 0.0); // the line breaker closes without voltage, and the pantograph rises through it close_line_breaker(loco); CHECK(loco->Mains); raise_pantograph(loco); - CHECK(loco->Pantographs[end::rear].is_active); + CHECK(loco->Pantographs[VehicleEnd::rear].is_active); CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); CHECK(loco->Mains); // opening the line breaker drops the pantograph, which stays down until the line breaker closes again loco->MainSwitch(false); loco.run(2.0, line); CHECK_FALSE(loco->Mains); - CHECK_FALSE(loco->Pantographs[end::rear].is_active); + CHECK_FALSE(loco->Pantographs[VehicleEnd::rear].is_active); CHECK(loco->PantographVoltage == 0.0); // a pantograph lowered under the closed line breaker leaves it closed close_line_breaker(loco); raise_pantograph(loco); - REQUIRE(loco->Pantographs[end::rear].is_active); - loco->OperatePantographValve(end::rear, operation_t::disable); + REQUIRE(loco->Pantographs[VehicleEnd::rear].is_active); + loco->OperatePantographValve(VehicleEnd::rear, operation_t::disable); loco.run(5.0, line); - CHECK_FALSE(loco->Pantographs[end::rear].is_active); + CHECK_FALSE(loco->Pantographs[VehicleEnd::rear].is_active); CHECK(loco->Mains); } @@ -190,14 +190,14 @@ TEST_CASE("mains before pantographs: with the flag the converter and the compres // the voltage gone they stop, behind the line breaker which stays closed auto const *track{&line}; SUBCASE("the pantograph lowered again") { - loco->OperatePantographValve(end::rear, operation_t::disable); + loco->OperatePantographValve(VehicleEnd::rear, operation_t::disable); loco.run(5.0, line); - REQUIRE_FALSE(loco->Pantographs[end::rear].is_active); + REQUIRE_FALSE(loco->Pantographs[VehicleEnd::rear].is_active); } SUBCASE("no voltage in the catenary") { track = &dead; loco.run(5.0, dead); - REQUIRE(loco->Pantographs[end::rear].is_active); + REQUIRE(loco->Pantographs[VehicleEnd::rear].is_active); } SUBCASE("the voltage in the catenary below the one the locomotive works on") { track = &weak; @@ -222,14 +222,14 @@ TEST_CASE("mains before pantographs: with the flag whatever else the main circui close_line_breaker(loco); REQUIRE(loco->Mains); loco->CompressorSwitch(true); - loco->MotorBlowersSwitch(true, end::front); + loco->MotorBlowersSwitch(true, VehicleEnd::front); loco->RVentForceOn = true; loco->HeatingSwitch(true); loco.hold_main_reservoir(-1.0); CHECK(reservoir_gain(loco, 10.0, line) < 0.01); CHECK_FALSE(loco->CompressorFlag); - CHECK_FALSE(loco->MotorBlowers[end::front].is_active); + CHECK_FALSE(loco->MotorBlowers[VehicleEnd::front].is_active); CHECK(loco->RventRot == 0.0); CHECK_FALSE(loco->Heating); @@ -239,7 +239,7 @@ TEST_CASE("mains before pantographs: with the flag whatever else the main circui CHECK(reservoir_gain(loco, 10.0, weak) < 0.01); CHECK(loco->Mains); CHECK_FALSE(loco->CompressorFlag); - CHECK_FALSE(loco->MotorBlowers[end::front].is_active); + CHECK_FALSE(loco->MotorBlowers[VehicleEnd::front].is_active); CHECK(loco->RventRot == 0.0); CHECK_FALSE(loco->Heating); } @@ -248,7 +248,7 @@ TEST_CASE("mains before pantographs: with the flag whatever else the main circui REQUIRE(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); CHECK(reservoir_gain(loco, 10.0, line) > 0.1); CHECK(loco->CompressorFlag); - CHECK(loco->MotorBlowers[end::front].is_active); + CHECK(loco->MotorBlowers[VehicleEnd::front].is_active); CHECK(loco->RventRot > 0.0); CHECK(loco->Heating); } @@ -288,7 +288,7 @@ TEST_CASE("mains before pantographs: with the flag the line contactors open when // the voltage goes: the line breaker holds, the pantograph stays up, the motors are cut off test::drive(driven, dead, 3.0); CHECK(loco->Mains); - CHECK(loco->Pantographs[end::rear].is_active); + CHECK(loco->Pantographs[VehicleEnd::rear].is_active); CHECK_FALSE(loco->NoVoltRelay); CHECK_FALSE(loco->StLinFlag); CHECK(loco->Im == 0.0); diff --git a/tests/unit/test_pressure_switch.cpp b/tests/unit/test_pressure_switch.cpp index df142574d..bb548ecb4 100644 --- a/tests/unit/test_pressure_switch.cpp +++ b/tests/unit/test_pressure_switch.cpp @@ -50,7 +50,7 @@ void get_ready(test::vehicle &Loco, test::driven const &Driven) { } REQUIRE_FALSE(Loco->ControlPressureSwitch); REQUIRE(Loco->Mains); - REQUIRE(Loco->Pantographs[end::rear].is_active); + REQUIRE(Loco->Pantographs[VehicleEnd::rear].is_active); } // the master controller taken to the given position a notch a second @@ -109,7 +109,7 @@ TEST_CASE("pressure switch: with the brake cylinders at 3.8 bar the EP05 takes n CHECK_FALSE(loco->StLinFlag); CHECK(loco->Im == 0.0); CHECK(loco->Mains); - CHECK(loco->Pantographs[end::rear].is_active); + CHECK(loco->Pantographs[VehicleEnd::rear].is_active); } TEST_CASE("pressure switch: without its brake cylinder half the EP05 takes current with the brake cylinders at 3.8 bar") { @@ -149,7 +149,7 @@ TEST_CASE("pressure switch: without its brake cylinder half the brake pipe still CHECK(loco->Im == 0.0); // nothing else lets go without the other key CHECK(loco->Mains); - CHECK(loco->Pantographs[end::rear].is_active); + CHECK(loco->Pantographs[VehicleEnd::rear].is_active); } TEST_CASE("pressure switch: an emergency application with the master controller on a power position opens the line breaker and drops the pantographs") { @@ -167,8 +167,8 @@ TEST_CASE("pressure switch: an emergency application with the master controller REQUIRE(loco->PipePress < emergency_pressure); REQUIRE(loco->MainCtrlPos == 5); CHECK_FALSE(loco->Mains); - CHECK_FALSE(loco->Pantographs[end::front].is_active); - CHECK_FALSE(loco->Pantographs[end::rear].is_active); + CHECK_FALSE(loco->Pantographs[VehicleEnd::front].is_active); + CHECK_FALSE(loco->Pantographs[VehicleEnd::rear].is_active); CHECK(loco->PantographVoltage == 0.0); CHECK_FALSE(loco->StLinFlag); CHECK(loco->Im == 0.0); @@ -177,7 +177,7 @@ TEST_CASE("pressure switch: an emergency application with the master controller loco->MainSwitch(true); test::drive(driven, line, 2.0); CHECK_FALSE(loco->Mains); - CHECK_FALSE(loco->Pantographs[end::rear].is_active); + CHECK_FALSE(loco->Pantographs[VehicleEnd::rear].is_active); } TEST_CASE("pressure switch: an emergency application with the master controller at zero leaves the line breaker and the pantographs alone") { @@ -192,7 +192,7 @@ TEST_CASE("pressure switch: an emergency application with the master controller emergency_application(loco, driven); CHECK(loco->Mains); - CHECK(loco->Pantographs[end::rear].is_active); + CHECK(loco->Pantographs[VehicleEnd::rear].is_active); CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); CHECK(loco->Im == 0.0); @@ -200,7 +200,7 @@ TEST_CASE("pressure switch: an emergency application with the master controller loco->IncMainCtrl(1); test::drive(driven, line, 2.0); CHECK_FALSE(loco->Mains); - CHECK_FALSE(loco->Pantographs[end::rear].is_active); + CHECK_FALSE(loco->Pantographs[VehicleEnd::rear].is_active); } TEST_CASE("pressure switch: a service application with the master controller on a power position doesn't open the line breaker") { @@ -219,7 +219,7 @@ TEST_CASE("pressure switch: a service application with the master controller on REQUIRE(lowest < 3.0); CHECK(lowest > emergency_pressure); CHECK(loco->Mains); - CHECK(loco->Pantographs[end::rear].is_active); + CHECK(loco->Pantographs[VehicleEnd::rear].is_active); // the pressure switch has cut the motors off CHECK_FALSE(loco->StLinFlag); CHECK(loco->Im == 0.0); @@ -233,7 +233,7 @@ TEST_CASE("pressure switch: without the key an emergency application leaves the emergency_application(loco, driven); REQUIRE(loco->MainCtrlPos == 5); CHECK(loco->Mains); - CHECK(loco->Pantographs[end::rear].is_active); + CHECK(loco->Pantographs[VehicleEnd::rear].is_active); CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); // the pressure switch cuts the motors off CHECK(loco->ControlPressureSwitch); @@ -249,7 +249,7 @@ TEST_CASE("pressure switch: where the pantographs don't hang on the line breaker emergency_application(loco, driven); CHECK_FALSE(loco->Mains); - CHECK(loco->Pantographs[end::rear].is_active); + CHECK(loco->Pantographs[VehicleEnd::rear].is_active); CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); CHECK_FALSE(loco->StLinFlag); CHECK(loco->Im == 0.0); @@ -264,20 +264,20 @@ TEST_CASE("pressure switch: after the emergency application the driver's start-u get_under_power(loco, driven, 5); emergency_application(loco, driven); REQUIRE_FALSE(loco->Mains); - REQUIRE_FALSE(loco->Pantographs[end::rear].is_active); - REQUIRE(loco->Pantographs[end::rear].valve.is_enabled); + REQUIRE_FALSE(loco->Pantographs[VehicleEnd::rear].is_active); + REQUIRE(loco->Pantographs[VehicleEnd::rear].valve.is_enabled); // with the brake pipe still empty REQUIRE(test::start_up(driven, line, 60.0)); CHECK(loco->MainCtrlPos == 0); CHECK(loco->Mains); - CHECK(loco->Pantographs[end::rear].is_active); + CHECK(loco->Pantographs[VehicleEnd::rear].is_active); CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); REQUIRE(loco->PipePress < emergency_pressure); // and it stays so test::drive(driven, line, 30.0); CHECK(loco->Mains); - CHECK(loco->Pantographs[end::rear].is_active); + CHECK(loco->Pantographs[VehicleEnd::rear].is_active); // the brakes released (the AI fills an emptied pipe with the releaser held, TController::control_releaser()), // the pressure switch lets the start be made diff --git a/tests/unit/test_pullee.cpp b/tests/unit/test_pullee.cpp index 41a3b69e2..dc5235c08 100644 --- a/tests/unit/test_pullee.cpp +++ b/tests/unit/test_pullee.cpp @@ -49,7 +49,7 @@ void drain_feed_air(TMoverParameters &Vehicle) { // whether the real vehicle can go in a train at all: the road vehicles can't, nor can the draisine, which has no coupler bool can_be_hauled(std::string const &Path) { vehicle probe{definition::fiz(Path)}; - return (probe->CategoryFlag & 1) != 0 && probe->Couplers[end::front].CouplerType != TCouplerType::NoCoupler; + return (probe->CategoryFlag & 1) != 0 && probe->Couplers[VehicleEnd::front].CouplerType != TCouplerType::NoCoupler; } } // namespace diff --git a/tests/unit/test_queries.cpp b/tests/unit/test_queries.cpp index 677b993eb..490c57be4 100644 --- a/tests/unit/test_queries.cpp +++ b/tests/unit/test_queries.cpp @@ -51,7 +51,7 @@ TEST_CASE("queries: the damage of a vehicle as the driver's panel describes it") TEST_CASE("queries: the ammeters of a vehicle without power show the current of the ones it controls") { vehicle unpowered{definition::fiz("en57_v1/6ba_840")}; vehicle powered{definition::fiz("en57_v1/5bgb")}; - unpowered->Attach(end::rear, end::front, &powered.mover(), Coupling::control, true, false); + unpowered->Attach(VehicleEnd::rear, VehicleEnd::front, &powered.mover(), Coupling::control, true, false); powered->Power = 600.0; powered->Itot = 321.7; unpowered->Power = 0.0; diff --git a/tests/unit/vehicle.cpp b/tests/unit/vehicle.cpp index 7946d3d84..fa9c99746 100644 --- a/tests/unit/vehicle.cpp +++ b/tests/unit/vehicle.cpp @@ -225,8 +225,8 @@ double vehicle::move(track const &Track, double Dt, TLocation const &Location, d // what TDynamicObject::Update() does before the movement. a raised pantograph touches the wire at once, // the game animates its rise auto &mover{*m_mover}; - mover.PantFrontVolt = mover.Pantographs[end::front].is_active ? Track.voltage : 0.0; - mover.PantRearVolt = mover.Pantographs[end::rear].is_active ? Track.voltage : 0.0; + mover.PantFrontVolt = mover.Pantographs[VehicleEnd::front].is_active ? Track.voltage : 0.0; + mover.PantRearVolt = mover.Pantographs[VehicleEnd::rear].is_active ? Track.voltage : 0.0; TTractionParam traction; traction.TractionVoltage = mover.EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? std::max(std::abs(mover.PantRearVolt), std::abs(mover.PantFrontVolt)) : 0.95 * mover.EnginePowerSource.MaxVoltage; @@ -291,12 +291,12 @@ TDynamicObject *as_neighbour(std::byte *Standin) { } // namespace -pair::pair(vehicle &First, int FirstEnd, vehicle &Second, int SecondEnd, double Gap) { +pair::pair(vehicle &First, VehicleEnd FirstEnd, vehicle &Second, VehicleEnd SecondEnd, double Gap) { auto const &first{First.mover()}; auto const &second{Second.mover()}; // the first vehicle in the middle, its FirstEnd towards the second one - m_vehicles[0] = {&First, FirstEnd, 0.0, FirstEnd == end::front ? 1.0 : -1.0, make_standin(First.mover())}; - m_vehicles[1] = {&Second, SecondEnd, 0.5 * first.Dim.L + Gap + 0.5 * second.Dim.L, SecondEnd == end::front ? -1.0 : 1.0, make_standin(Second.mover())}; + m_vehicles[0] = {&First, FirstEnd, 0.0, FirstEnd == VehicleEnd::front ? 1.0 : -1.0, make_standin(First.mover())}; + m_vehicles[1] = {&Second, SecondEnd, 0.5 * first.Dim.L + Gap + 0.5 * second.Dim.L, SecondEnd == VehicleEnd::front ? -1.0 : 1.0, make_standin(Second.mover())}; } pair::~pair() { @@ -320,10 +320,10 @@ void pair::find_neighbours() { auto const &othermover{other.owner->mover()}; auto &neighbour{mover.Neighbours[self.end]}; neighbour.vehicle = as_neighbour(other.standin.data()); - neighbour.vehicle_end = other.end; + neighbour.vehicle_end = NumberOf(other.end); neighbour.distance = static_cast(TMoverParameters::CouplerDist(&mover, &othermover) - mover.Couplers[self.end].adapter_length - othermover.Couplers[other.end].adapter_length); - mover.Neighbours[1 - self.end] = neighbour_data(); + mover.Neighbours[Opposite(self.end)] = neighbour_data(); } } diff --git a/tests/unit/vehicle.h b/tests/unit/vehicle.h index 97c4cf6a1..f83c50b7e 100644 --- a/tests/unit/vehicle.h +++ b/tests/unit/vehicle.h @@ -133,12 +133,12 @@ private: // vehicles of a scene (vehicle_table::update()): each one finds its neighbour, then both take the forces, the // coupler and buffer ones among them (CouplerForce()), then both move and handle the collisions (CollisionDetect()). // they couple and part on their own, as the couplers let them; the speed of each runs along its own axis -// test::pair pair{moving, end::front, standing, end::rear, 1.0}; // 1 m apart +// test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 1.0}; // 1 m apart // pair.run(5.0); // for 5 s // CHECK(pair.coupled()); class pair { public: - pair(vehicle &First, int FirstEnd, vehicle &Second, int SecondEnd, double Gap); + pair(vehicle &First, VehicleEnd FirstEnd, vehicle &Second, VehicleEnd SecondEnd, double Gap); ~pair(); pair(pair const &) = delete; pair &operator=(pair const &) = delete; @@ -159,7 +159,7 @@ public: private: struct placement { vehicle *owner{nullptr}; - int end{0}; // the end facing the other vehicle + VehicleEnd end{VehicleEnd::front}; // the end facing the other vehicle double position{0.0}; // of the middle of the vehicle along the track [m] double heading{1.0}; // +1 when the vehicle runs forwards towards the growing position, -1 otherwise std::vector standin; // what the other vehicle sees as this one, see vehicle.cpp diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 945233f6d..2cde64ee6 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -275,7 +275,7 @@ public: // what the AI would do at this place and speed, worked out also while a human drives, for the black box blackbox::ai_reference ai_reference() const; // the light pattern the timetable or the scenery asks for at an end of the train, -1 the usual one - int light_hint( int const End ) const { return m_lighthints[ End ]; } + int light_hint( VehicleEnd const End ) const { return m_lighthints[ End ]; } // the order the driver goes by now: a train run, shunting and the like DriverOrders order_current() const { return OrderCurrentGet(); } private: @@ -424,7 +424,7 @@ private: TMoverParameters *mvOccupied = nullptr; // jakim pojazdem hamuje TMoverParameters *mvPantographUnit = nullptr; //pantograph equipped vehicle in the occupied/controlled set std::string VehicleName; - std::array m_lighthints = { -1, -1 }; // suggested light patterns + ByEnd m_lighthints = { -1, -1 }; // suggested light patterns double AccPreferred = 0.0; // preferowane przyspieszenie (wg psychiki kierującego, zmniejszana przy wykryciu kolizji) double AccDesired = 0.0; // przyspieszenie, jakie ma utrzymywać (<0:nie przyspieszaj,<-0.1:hamuj) double VelDesired = 0.0; // predkość, z jaką ma jechać, wynikająca z analizy tableki; <=VelSignal @@ -618,8 +618,8 @@ private: int TableDirection() { return iTableDirection; } // Ra: stare funkcje skanujące, używane do szukania sygnalizatora z tyłu bool IsOccupiedByAnotherConsist( TTrack *Track, double const Distance = 0 ); - basic_event *CheckTrackEventBackward( double fDirection, TTrack *Track, TDynamicObject *Vehicle, int const Eventdirection = 1, end const End = end::rear ); - TTrack *BackwardTraceRoute( double &fDistance, double &fDirection, TDynamicObject *Vehicle, basic_event *&Event, int const Eventdirection = 1, end const End = end::rear, bool const Untiloccupied = true ); + basic_event *CheckTrackEventBackward( double fDirection, TTrack *Track, TDynamicObject *Vehicle, int const Eventdirection = 1, VehicleEnd const End = VehicleEnd::rear ); + TTrack *BackwardTraceRoute( double &fDistance, double &fDirection, TDynamicObject *Vehicle, basic_event *&Event, int const Eventdirection = 1, VehicleEnd const End = VehicleEnd::rear, bool const Untiloccupied = true ); void SetProximityVelocity( double dist, double vel, glm::dvec3 const *pos ); TCommandType BackwardScan( double const Range ); std::string TableText( std::size_t const Index ) const; @@ -718,11 +718,11 @@ private: bool Ready = false; // ABu: stan gotowosci do odjazdu - sprawdzenie odhamowania wagonow bool IsConsistBraked { false }; double ConsistShade{ 1.0 }; // averaged amount of sunlight received by the consist - TDynamicObject *pVehicles[ 2 ]; // skrajne pojazdy w składzie (niekoniecznie bezpośrednio sterowane) + ByEnd pVehicles; // skrajne pojazdy w składzie (niekoniecznie bezpośrednio sterowane) bool DoesAnyDoorNeedOpening{ false }; - bool IsAnyDoorOpen[ 2 ]; // state of door in the consist - bool IsAnyDoorOnlyOpen[ 2 ]; // state of door in the consist regardless of step - bool IsAnyDoorPermitActive[ 2 ]; // state of door permit in the consist + BySide IsAnyDoorOpen; // state of door in the consist + BySide IsAnyDoorOnlyOpen; // state of door in the consist regardless of step + BySide IsAnyDoorPermitActive; // state of door permit in the consist door_closure_t DoorClosure{ door_closure_t::none }; // state of the door closure signalling (SOD) of the consist bool IsAnyLineBreakerOpen{ false }; // state of line breaker in all powered vehicles under control bool IsAnyConverterOverloadRelayOpen{ false }; // state of converter overload relays in all vehicles under control @@ -762,7 +762,7 @@ public: return WriteLogFlag || ( WriteTrainLogFlag && is_train() && primary() ); } static std::string_view physicslog_header(); std::string physicslog_line() const; - TDynamicObject *Vehicle( end const Side ) const { + TDynamicObject *Vehicle( VehicleEnd const Side ) const { return pVehicles[ Side ]; } private: std::string OwnerName() const; diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index afe730d07..bd6fba732 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -200,7 +200,7 @@ public: //private: // położenie pojazdu w świecie oraz parametry ruchu glm::dvec3 vPosition; // Ra: pozycja pojazdu liczona zaraz po przesunięciu - glm::dvec3 vCoulpler[2]; // współrzędne sprzęgów do liczenia zderzeń czołowych + ByEnd vCoulpler; // współrzędne sprzęgów do liczenia zderzeń czołowych glm::dvec3 vUp, vFront, vLeft; // wektory jednostkowe ustawienia pojazdu int iDirection; // kierunek pojazdu względem czoła składu (1=zgodny,0=przeciwny) TTrackShape ts; // parametry toru przekazywane do fizyki @@ -415,14 +415,14 @@ private: sound_source step_open { sound_placement::general }; sound_source step_close { sound_placement::general }; sound_source permit_granted { sound_placement::general }; - side placement {}; + VehicleSide placement {}; }; struct mirror_sounds { sound_source unfold { sound_placement::general }; sound_source fold { sound_placement::general }; - side placement {}; - int end {}; // of the vehicle, the mirror moves with the cab at this end occupied + VehicleSide placement {}; + VehicleEnd end {}; // of the vehicle, the mirror moves with the cab at this end occupied }; struct exchange_sounds { @@ -509,7 +509,7 @@ private: // members AirCoupler btCoupler1; // sprzegi AirCoupler btCoupler2; - std::array m_coupleradapters = { nullptr, nullptr }; + ByEnd m_coupleradapters = { nullptr, nullptr }; AirCoupler btCPneumatic1; // sprzegi powietrzne //yB - zmienione z Button na AirCoupler - krzyzyki AirCoupler btCPneumatic2; AirCoupler btCPneumatic1r; // ABu: to zeby nie bylo problemow przy laczeniu wagonow, @@ -598,12 +598,12 @@ private: // moving part and other external sounds sound_source m_startjolt { sound_placement::general }; // movement start jolt, played once on initial acceleration at slow enough speed bool m_startjoltplayed { false }; - std::array m_couplersounds; // always front and rear + ByEnd m_couplersounds; // always front and rear std::vector m_pantographsounds; // typically 2 but can be less (or more?) std::vector m_doorsounds; // can expect symmetrical arrangement, but don't count on it bool m_doorlocks { false }; // sound helper, current state of door locks std::vector m_mirrorsounds; - std::array m_mirrormotion; // indexed by side: right, left + BySide m_mirrormotion; // indexed by side: right, left sound_source sHorn1 { sound_placement::external, 5 * EU07_SOUND_RUNNINGNOISECUTOFFRANGE }; sound_source sHorn2 { sound_placement::external, 5 * EU07_SOUND_RUNNINGNOISECUTOFFRANGE }; sound_source sHorn3 { sound_placement::external, 5 * EU07_SOUND_RUNNINGNOISECUTOFFRANGE }; @@ -636,7 +636,7 @@ private: bool renderme; // yB - czy renderowac float ModCamRot; - int iInventory[ 2 ] { 0, 0 }; // flagi bitowe posiadanych submodeli (np. świateł) + ByEnd iInventory { 0, 0 }; // flagi bitowe posiadanych submodeli (np. świateł) bool btnOn; // ABu: czy byly uzywane buttony, jesli tak, to po renderingu wylacz // bo ten sam model moze byc jeszcze wykorzystany przez inny obiekt! @@ -687,7 +687,7 @@ private: TDynamicObject * ABuScanNearestObject(glm::vec3 pos, TTrack *Track, double ScanDir, double ScanDist, int &CouplNr); - TDynamicObject * GetFirstDynamic(int cpl_type, CouplingSet cf = Coupling::coupler); + TDynamicObject * GetFirstDynamic(VehicleEnd cpl_type, CouplingSet cf = Coupling::coupler); void ABuSetModelShake(glm::dvec3 mShake); // place in vehicle_table::m_items, set by its update for the groups of the physics steps on many threads @@ -747,7 +747,7 @@ private: double off_track_offset() const; // the gap between the ends of the vehicle and the one at its End, as they meet off the track [m]: negative the // buffers pressed in - double off_track_gap( int End ) const; + double off_track_gap( VehicleEnd End ) const; private: // the axles moved along their tracks by the distance void move_axles( double Distance ); @@ -792,14 +792,14 @@ private: // the most triangles of terrain taken around the vehicle off the track static constexpr std::size_t off_track_triangles { 400000 }; bool m_offtrackplaced { false }; // placed off the track: placed on it again once it's back on the rails - std::array m_pulledoff; // the distance the coupling of an end pulled the vehicle coupled there over the climbing limit + ByEnd m_pulledoff; // the distance the coupling of an end pulled the vehicle coupled there over the climbing limit derailment::stretch m_struck; // on the rails: the distance a body off the track pushed it sideways over the climbing limit // the model, the axes and the coupling points placed by the motion off the track void place_off_track(); public: void RenderSounds(); // plays the sounds of the mirrors on the Side, of the occupied cab, starting the Event - void play_mirror_sounds( side const Side, mirror_moves::event const Event ); + void play_mirror_sounds( VehicleSide const Side, mirror_moves::event const Event ); inline glm::dvec3 GetPosition() const { return vPosition; }; // converts location from vehicle coordinates frame to world frame @@ -811,7 +811,7 @@ public: // pobranie współrzędnych tyłu inline glm::dvec3 RearPosition() const { return vCoulpler[iDirection]; }; - inline glm::dvec3 CouplerPosition( end const End ) const { + inline glm::dvec3 CouplerPosition( VehicleEnd const End ) const { return vCoulpler[ End ]; } inline glm::dvec3 AxlePositionGet() { return iAxleFirst ? @@ -870,21 +870,21 @@ public: Axle1.GetTrack() : Axle0.GetTrack(); }; - void couple( int const Side ); - int uncouple( int const Side ); - bool attach_coupler_adapter( int const Side, bool const Enforce = false ); - bool remove_coupler_adapter( int const Side ); + void couple( VehicleEnd const Side ); + int uncouple( VehicleEnd const Side ); + bool attach_coupler_adapter( VehicleEnd const Side, bool const Enforce = false ); + bool remove_coupler_adapter( VehicleEnd const Side ); void RadioStop(); void Damage(char flag); void pants_up(); void SetLights(); void SetLightDimmings(); void RaLightsSet(int head, int rear); - int LightList( end const Side ) const { return iInventory[ Side ]; } + int LightList( VehicleEnd const Side ) const { return iInventory[ Side ]; } bool has_signal_pc1_on() const; bool has_signal_pc2_on() const; bool has_signal_pc5_on() const; - bool has_signal_on( int const Side, int const Pattern ) const; + bool has_signal_on( VehicleEnd const Side, int const Pattern ) const; void set_cab_lights( int const Cab, float const Level ); TDynamicObject * FirstFind(int &coupler_nr, CouplingSet cf = Coupling::coupler); float GetEPP(); // wyliczanie sredniego cisnienia w PG diff --git a/vehicle/Train.h b/vehicle/Train.h index 8e51447ce..9c017a628 100644 --- a/vehicle/Train.h +++ b/vehicle/Train.h @@ -243,10 +243,10 @@ class TTrain { void update_sounds_radio(); void update_sounds_fmradio( double const Deltatime ); inline - end cab_to_end( int const End ) const { - return End == 2 ? end::rear : end::front; } + VehicleEnd cab_to_end( int const End ) const { + return End == 2 ? VehicleEnd::rear : VehicleEnd::front; } inline - end cab_to_end() const { + VehicleEnd cab_to_end() const { return cab_to_end( iCabn ); } void update_screens(double dt); void update_script_screens(); @@ -961,7 +961,7 @@ private: std::string asCarName[20]; // nazwa czlonu bool bMains[8]; // WSy float fCntVol[8]; // napiecie NN - bool bPants[8][2]; // podniesienie pantografow + std::array, 8> bPants; // podniesienie pantografow bool bFuse[8]; // nadmiarowe bool bBatt[8]; // baterie bool bConv[8]; // przetwornice @@ -985,7 +985,7 @@ private: bool m_dirneutral{ false }; // helper, true if direction set to neutral bool m_dirbackward{ false }; // helper, true if direction set to backward bool m_doorpermits{ false }; // helper, true if any door permit is active - float m_doorpermittimers[2] = { -1.f, -1.f }; + BySide m_doorpermittimers = { -1.f, -1.f }; float trainLenghtMeasureTimer = { -1.f }; // ld substitute bool m_couplingdisconnect { false }; diff --git a/vehicle/ai/consist.cpp b/vehicle/ai/consist.cpp index 8fa123ed9..b0774eccf 100644 --- a/vehicle/ai/consist.cpp +++ b/vehicle/ai/consist.cpp @@ -66,7 +66,7 @@ void TController::Activation() ZeroDirection(); mvOccupied->CabOccupied = mvOccupied->CabActive; // użytkownik moze zmienić CabOccupied wychodząc mvOccupied->CabDeactivisation(); // tak jest w Train.cpp - if (pVehicle->MoverParameters->Couplers[iDirectionOrder < 0 ? end::rear : end::front].CouplingFlag.HasAll(Coupling::control)) { + if (pVehicle->MoverParameters->Couplers[iDirectionOrder < 0 ? VehicleEnd::rear : VehicleEnd::front].CouplingFlag.HasAll(Coupling::control)) { ZeroLocalBrake(); if( initialspringbrakestate ) { mvOccupied->SpringBrakeActivate( false ); @@ -78,7 +78,7 @@ void TController::Activation() // przejście AI na drugą stronę EN57, ET41 itp. // TODO: clean this up, there's lot of redundancy with TMoverParameters::ChangeCab() and TTrain::MoveToVehicle() { - int movedirection { ( iDirection < 0 ? end::rear : end::front ) }; + int movedirection { NumberOf( iDirection < 0 ? VehicleEnd::rear : VehicleEnd::front ) }; auto *targetvehicle { pVehicle->FirstFind( movedirection, Coupling::control ) }; if( pVehicle != targetvehicle ) { auto *targetvehicledriver { targetvehicle->Mechanik }; // zapamiętanie tego, co ewentualnie tam siedzi, żeby w razie dwóch zamienić miejscami @@ -304,7 +304,7 @@ bool TController::CheckVehicles(DriverOrders user) if (!p) p = pVehicle; auto *const frontvehicle { p }; // stays the consist head for the rest of this check - pVehicles[end::front] = frontvehicle; + pVehicles[VehicleEnd::front] = frontvehicle; // liczenie pojazdów w składzie i ustalenie parametrów auto dir = d = 1 - d; // a dalej będziemy zliczać od czoła do tyłu fLength = 0.0; // długość składu do badania wyjechania za ograniczenie @@ -333,7 +333,7 @@ bool TController::CheckVehicles(DriverOrders user) } } ++iVehicles; // jest jeden pojazd więcej - pVehicles[end::rear] = p; // zapamiętanie ostatniego + pVehicles[VehicleEnd::rear] = p; // zapamiętanie ostatniego fLength += p->MoverParameters->Dim.L; // dodanie długości pojazdu fMass += p->MoverParameters->TotalMass; // dodanie masy łącznie z ładunkiem fVelMax = min_speed( fVelMax, p->MoverParameters->Vmax ); // ustalenie maksymalnej prędkości dla składu @@ -441,7 +441,7 @@ bool TController::CheckVehicles(DriverOrders user) } // detect push-pull train configurations and mark them accordingly - if( frontvehicle->is_connected( pVehicles[ end::rear ], Coupling::control ) ) { + if( frontvehicle->is_connected( pVehicles[ VehicleEnd::rear ], Coupling::control ) ) { // zmiana czoła przez zmianę kabiny drivingFlags.pushPull = true; } @@ -462,7 +462,7 @@ bool TController::CheckVehicles(DriverOrders user) // światła manewrowe (Tb1) tylko z przodu, aby nie pozostawić odczepionego ze światłem if (mvOccupied->DirActive >= 0) { // jak ma kierunek do przodu - pVehicles[end::rear]->RaLightsSet(-1, 0); + pVehicles[VehicleEnd::rear]->RaLightsSet(-1, 0); } else { // jak dociska @@ -477,7 +477,7 @@ bool TController::CheckVehicles(DriverOrders user) // TODO: replace connection test with connection check between last engine and first car, specifically auto const isheatingcouplingactive { ( ControlledEnginesCount == 1 ? - frontvehicle->is_connected( pVehicles[ end::rear ], Coupling::heating ) : + frontvehicle->is_connected( pVehicles[ VehicleEnd::rear ], Coupling::heating ) : true ) }; auto const isheatingneeded { (is_emu() || is_dmu() ? true : @@ -505,8 +505,8 @@ bool TController::CheckVehicles(DriverOrders user) void TController::Lights(int head, int rear) { // zapalenie świateł w skłądzie - pVehicles[ end::front ]->RaLightsSet(head, -1); // zapalenie przednich w pierwszym - pVehicles[ end::rear ]->RaLightsSet(-1, rear); // zapalenie końcówek w ostatnim + pVehicles[ VehicleEnd::front ]->RaLightsSet(head, -1); // zapalenie przednich w pierwszym + pVehicles[ VehicleEnd::rear ]->RaLightsSet(-1, rear); // zapalenie końcówek w ostatnim } void TController::DirectionInitial() @@ -706,12 +706,12 @@ TController::determine_consist_state() { mvOccupied->PipePress < std::max(3.9, mvOccupied->BrakePressureActual.PipePressureVal) + 0.1; fAccGravity = 0.0; // przyspieszenie wynikające z pochylenia IsAnyCouplerStretched = false; - IsAnyDoorOnlyOpen[ side::right ] = IsAnyDoorOnlyOpen[ side::left ] = false; - IsAnyDoorOpen[ side::right ] = IsAnyDoorOpen[ side::left ] = false; - IsAnyDoorPermitActive[ side::right ] = IsAnyDoorPermitActive[ side::left ] = false; + IsAnyDoorOnlyOpen[ VehicleSide::right ] = IsAnyDoorOnlyOpen[ VehicleSide::left ] = false; + IsAnyDoorOpen[ VehicleSide::right ] = IsAnyDoorOpen[ VehicleSide::left ] = false; + IsAnyDoorPermitActive[ VehicleSide::right ] = IsAnyDoorPermitActive[ VehicleSide::left ] = false; auto doorclosure { door_closure_t::none }; ConsistShade = 0.0; - auto *p { pVehicles[ end::front ] }; // pojazd na czole składu + auto *p { pVehicles[ VehicleEnd::front ] }; // pojazd na czole składu double dy; // składowa styczna grawitacji, w przedziale <0,1> // starting uphill the power is applied against the train brake on purpose, until the power holds the train and // then while the brake releases @@ -774,24 +774,24 @@ TController::determine_consist_state() { // check coupler state IsAnyCouplerStretched = IsAnyCouplerStretched - || vehicle->Couplers[end::front].stretch_duration > 0.0 - || vehicle->Couplers[end::rear].stretch_duration > 0.0; + || vehicle->Couplers[VehicleEnd::front].stretch_duration > 0.0 + || vehicle->Couplers[VehicleEnd::rear].stretch_duration > 0.0; // check door state { auto const switchsides{ p->DirectionGet() != (iDirection == 0 ? mvOccupied->CabOccupied : iDirection) }; - auto const &rightdoor { vehicle->Doors.instances[ ( switchsides ? side::left : side::right ) ] }; - auto const &leftdoor { vehicle->Doors.instances[ ( switchsides ? side::right : side::left ) ] }; + auto const &rightdoor { vehicle->Doors.instances[ ( switchsides ? VehicleSide::left : VehicleSide::right ) ] }; + auto const &leftdoor { vehicle->Doors.instances[ ( switchsides ? VehicleSide::right : VehicleSide::left ) ] }; if( vehicle->Doors.close_control != control_t::autonomous ) { - IsAnyDoorOpen[ side::right ] |= false == rightdoor.is_closed; - IsAnyDoorOpen[ side::left ] |= false == leftdoor.is_closed; + IsAnyDoorOpen[ VehicleSide::right ] |= false == rightdoor.is_closed; + IsAnyDoorOpen[ VehicleSide::left ] |= false == leftdoor.is_closed; } if (vehicle->Doors.close_control != control_t::autonomous) { - IsAnyDoorOnlyOpen[ side::right ] |= false == rightdoor.is_door_closed; - IsAnyDoorOnlyOpen[ side::left ] |= false == leftdoor.is_door_closed; + IsAnyDoorOnlyOpen[ VehicleSide::right ] |= false == rightdoor.is_door_closed; + IsAnyDoorOnlyOpen[ VehicleSide::left ] |= false == leftdoor.is_door_closed; } if( vehicle->Doors.permit_needed ) { - IsAnyDoorPermitActive[ side::right ] |= rightdoor.open_permit; - IsAnyDoorPermitActive[ side::left ] |= leftdoor.open_permit; + IsAnyDoorPermitActive[ VehicleSide::right ] |= rightdoor.open_permit; + IsAnyDoorPermitActive[ VehicleSide::left ] |= leftdoor.open_permit; } doorclosure = std::max( doorclosure, vehicle->door_closure() ); } @@ -842,7 +842,7 @@ TController::determine_consist_state() { auto absaccs { fAccGravity }; // Ra 2014-03: jesli skład stoi, to działa na niego składowa styczna grawitacji if( mvOccupied->Vel > EU07_AI_NOMOVEMENT ) { absaccs = 0; - auto *d = pVehicles[ end::front ]; // pojazd na czele składu + auto *d = pVehicles[ VehicleEnd::front ]; // pojazd na czele składu while( d ) { absaccs += d->MoverParameters->TotalMass * d->MoverParameters->AccS * ( d->DirectionGet() == iDirection ? 1 : -1 ); d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) @@ -941,7 +941,7 @@ TController::determine_consist_state() { } // second pass, for diesel engines verify the (live) engines are fully started // TODO: cache presence of diesel engines in the consist, to skip this test if there isn't any - p = pVehicles[ end::front ]; // pojazd na czole składu + p = pVehicles[ VehicleEnd::front ]; // pojazd na czole składu while( true == Ready && p != nullptr ) { diff --git a/vehicle/ai/controls.cpp b/vehicle/ai/controls.cpp index 4163afc9e..ac39a106a 100644 --- a/vehicle/ai/controls.cpp +++ b/vehicle/ai/controls.cpp @@ -147,12 +147,12 @@ bool TController::IncBrake() || mvOccupied->TrainType == train_type::et42 ) { // NOTE: we're doing simplified checks full of presuptions here. // they'll break if someone does strange thing like turning around the second unit - if( mvOccupied->Couplers[end::rear].CouplingFlag & Coupling::permanent - && mvOccupied->Couplers[end::rear].Connected->Couplers[end::rear].Connected != nullptr ) { + if( mvOccupied->Couplers[VehicleEnd::rear].CouplingFlag & Coupling::permanent + && mvOccupied->Couplers[VehicleEnd::rear].Connected->Couplers[VehicleEnd::rear].Connected != nullptr ) { standalone = false; } - if( mvOccupied->Couplers[end::front].CouplingFlag & Coupling::permanent - && mvOccupied->Couplers[end::front].Connected->Couplers[end::front].Connected != nullptr ) { + if( mvOccupied->Couplers[VehicleEnd::front].CouplingFlag & Coupling::permanent + && mvOccupied->Couplers[VehicleEnd::front].Connected->Couplers[VehicleEnd::front].Connected != nullptr ) { standalone = false; } } @@ -171,18 +171,18 @@ bool TController::IncBrake() ( ( mvOccupied->Couplers[ 0 ].CouplingFlag.Empty() ) && ( mvOccupied->Couplers[ 1 ].CouplingFlag.Empty() ) ); */ - if( pVehicles[ end::front ] != pVehicles[ end::rear ] ) { + if( pVehicles[ VehicleEnd::front ] != pVehicles[ VehicleEnd::rear ] ) { // more detailed version, will use manual braking also for coupled sets of controlled vehicles - auto *vehicle = pVehicles[ end::front ]; // start from first + auto *vehicle = pVehicles[ VehicleEnd::front ]; // start from first while( true == standalone && vehicle != nullptr ) { // NOTE: we could simplify this by doing only check of the rear coupler, but this can be quite tricky in itself // TODO: add easier ways to access front/rear coupler taking into account vehicle's direction standalone = - (vehicle->MoverParameters->Couplers[end::front].Connected == nullptr || - (vehicle->MoverParameters->Couplers[end::front].CouplingFlag & Coupling::control && vehicle->MoverParameters->Couplers[end::front].Connected->Power > 1)) && - (vehicle->MoverParameters->Couplers[end::rear].Connected == nullptr || - (vehicle->MoverParameters->Couplers[end::rear].CouplingFlag & Coupling::control && vehicle->MoverParameters->Couplers[end::rear].Connected->Power > 1)); + (vehicle->MoverParameters->Couplers[VehicleEnd::front].Connected == nullptr || + (vehicle->MoverParameters->Couplers[VehicleEnd::front].CouplingFlag & Coupling::control && vehicle->MoverParameters->Couplers[VehicleEnd::front].Connected->Power > 1)) && + (vehicle->MoverParameters->Couplers[VehicleEnd::rear].Connected == nullptr || + (vehicle->MoverParameters->Couplers[VehicleEnd::rear].CouplingFlag & Coupling::control && vehicle->MoverParameters->Couplers[VehicleEnd::rear].Connected->Power > 1)); vehicle = vehicle->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) } } diff --git a/vehicle/ai/doors.cpp b/vehicle/ai/doors.cpp index 967e603cb..665c6de5f 100644 --- a/vehicle/ai/doors.cpp +++ b/vehicle/ai/doors.cpp @@ -120,7 +120,7 @@ void TController::Doors( bool const Open, int const Side ) { } // if applicable close manually-operated doors in vehicles which may ignore remote signals { - const auto *vehicle = pVehicles[ end::front ]; // pojazd na czole składu + const auto *vehicle = pVehicles[ VehicleEnd::front ]; // pojazd na czole składu while( vehicle != nullptr ) { // zamykanie drzwi w pojazdach - flaga zezwolenia była by lepsza auto const ismanualdoor { @@ -131,8 +131,8 @@ void TController::Doors( bool const Open, int const Side ) { if( true == ismanualdoor && ( vehicle->LoadExchangeTime() == 0.f || vehicle->MoverParameters->Vel > EU07_AI_MOVEMENT ) ) { - vehicle->MoverParameters->OperateDoors( side::right, false, range_t::local ); - vehicle->MoverParameters->OperateDoors( side::left, false, range_t::local ); + vehicle->MoverParameters->OperateDoors( VehicleSide::right, false, range_t::local ); + vehicle->MoverParameters->OperateDoors( VehicleSide::left, false, range_t::local ); } vehicle = vehicle->Next(); // pojazd podłączony z tyłu (patrząc od czoła) } @@ -147,13 +147,13 @@ void TController::Doors( bool const Open, int const Side ) { bool TController::doors_open() const { - return IsAnyDoorOpen[side::right] || IsAnyDoorOpen[side::left]; + return IsAnyDoorOpen[VehicleSide::right] || IsAnyDoorOpen[VehicleSide::left]; } bool TController::doors_permit_active() const { - return IsAnyDoorPermitActive[side::right] || IsAnyDoorPermitActive[side::left]; + return IsAnyDoorPermitActive[VehicleSide::right] || IsAnyDoorPermitActive[VehicleSide::left]; } void @@ -166,7 +166,7 @@ TController::announce( announcement_t const Announcement ) { return; } - auto *vehicle { pVehicles[ end::front ] }; + auto *vehicle { pVehicles[ VehicleEnd::front ] }; while( vehicle ) { vehicle->announce( Announcement ); vehicle = vehicle->Next(); @@ -242,7 +242,7 @@ TController::check_load_exchange() { if( fStopTime > 0 ) { return; } // czas postoju przed dalszą jazdą (np. na przystanku) - auto *vehicle { pVehicles[ end::front ] }; + auto *vehicle { pVehicles[ VehicleEnd::front ] }; while( vehicle != nullptr ) { auto const vehicleexchangetime { vehicle->LoadExchangeTime() }; DoesAnyDoorNeedOpening |= vehicleexchangetime > 0 && vehicle->LoadExchangeSpeed() == 0; @@ -273,7 +273,7 @@ TController::check_load_exchange() { void TController::GuardOpenDoor() { if (drivingFlags.guardOpenDoor) { - auto *vehicle{ pVehicles[end::front] }; + auto *vehicle{ pVehicles[VehicleEnd::front] }; while (vehicle != nullptr && vehicle->MoverParameters->Doors.range == 0) { vehicle = vehicle->Next(); } @@ -281,10 +281,10 @@ TController::GuardOpenDoor() { auto const lewe = vehicle->DirectionGet() > 0 ? 1 : 2; auto const prawe = 3 - lewe; if (m_lastexchangeplatforms & lewe) { - vehicle->MoverParameters->OperateDoors(side::left, true, range_t::local); + vehicle->MoverParameters->OperateDoors(VehicleSide::left, true, range_t::local); } if (m_lastexchangeplatforms & prawe) { - vehicle->MoverParameters->OperateDoors(side::right, true, range_t::local); + vehicle->MoverParameters->OperateDoors(VehicleSide::right, true, range_t::local); } } else { diff --git a/vehicle/ai/driver.cpp b/vehicle/ai/driver.cpp index 20d6e6fa1..7ad7d61d3 100644 --- a/vehicle/ai/driver.cpp +++ b/vehicle/ai/driver.cpp @@ -58,12 +58,12 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, AIControllFlag( AI ), pVehicle( NewControll ) { if( pVehicle != nullptr ) { - pVehicles[ end::front ] = pVehicle->GetFirstDynamic( end::front ); // pierwszy w kierunku jazdy (Np. Pc1) - pVehicles[ end::rear ] = pVehicle->GetFirstDynamic( end::rear ); // ostatni w kierunku jazdy (końcówki) + pVehicles[ VehicleEnd::front ] = pVehicle->GetFirstDynamic( VehicleEnd::front ); // pierwszy w kierunku jazdy (Np. Pc1) + pVehicles[ VehicleEnd::rear ] = pVehicle->GetFirstDynamic( VehicleEnd::rear ); // ostatni w kierunku jazdy (końcówki) } else { - pVehicles[ end::front ] = nullptr; - pVehicles[ end::rear ] = nullptr; + pVehicles[ VehicleEnd::front ] = nullptr; + pVehicles[ VehicleEnd::rear ] = nullptr; } ControllingSet(); // utworzenie połączenia do sterowanego pojazdu if( mvOccupied != nullptr ) { @@ -133,17 +133,17 @@ TBrakeSystem TController::consist_brake_system() const { if( mvOccupied->BrakeSystem != TBrakeSystem::ElectroPneumatic ) { return mvOccupied->BrakeSystem; } auto isepcapable = true; - if( pVehicles[ end::front ] != pVehicles[ end::rear ] ) { + if( pVehicles[ VehicleEnd::front ] != pVehicles[ VehicleEnd::rear ] ) { // more detailed version, will use manual braking also for coupled sets of controlled vehicles - auto *vehicle = pVehicles[ end::front ]; // start from first + auto *vehicle = pVehicles[ VehicleEnd::front ]; // start from first while( true == isepcapable && vehicle != nullptr ) { // NOTE: we could simplify this by doing only check of the rear coupler, but this can be quite tricky in itself // TODO: add easier ways to access front/rear coupler taking into account vehicle's direction - isepcapable = (vehicle->MoverParameters->Couplers[end::front].Connected == nullptr || - (vehicle->MoverParameters->Couplers[end::front].CouplingFlag & Coupling::control && vehicle->MoverParameters->Couplers[end::front].Connected->Power > -1)) && - (vehicle->MoverParameters->Couplers[end::rear].Connected == nullptr || - (vehicle->MoverParameters->Couplers[end::rear].CouplingFlag & Coupling::control && vehicle->MoverParameters->Couplers[end::rear].Connected->Power > -1)); + isepcapable = (vehicle->MoverParameters->Couplers[VehicleEnd::front].Connected == nullptr || + (vehicle->MoverParameters->Couplers[VehicleEnd::front].CouplingFlag & Coupling::control && vehicle->MoverParameters->Couplers[VehicleEnd::front].Connected->Power > -1)) && + (vehicle->MoverParameters->Couplers[VehicleEnd::rear].Connected == nullptr || + (vehicle->MoverParameters->Couplers[VehicleEnd::rear].CouplingFlag & Coupling::control && vehicle->MoverParameters->Couplers[VehicleEnd::rear].Connected->Power > -1)); vehicle = vehicle->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) } } @@ -239,7 +239,7 @@ void TController::record_station( TSpeedPos const &Point, std::uint8_t const Kin entry.arrival = ( line.Ah >= 0 ? static_cast( line.Ah * 60 ) + line.Am : -1.0f ); entry.departure = ( line.Dh >= 0 ? static_cast( line.Dh * 60 ) + line.Dm : -1.0f ); } - simulation::Blackbox.station( pVehicles[ end::front ], std::move( entry ) ); + simulation::Blackbox.station( pVehicles[ VehicleEnd::front ], std::move( entry ) ); } void TController::WaitingSet(double Seconds) @@ -420,12 +420,12 @@ void TController::TakeControl( bool const Aidriver, bool const Forcevehiclecheck // jeśli nic nie robi OrderNext( DriverOrder::prepareEngine ); if( pVehicle->MoverParameters->iLights[ ( mvOccupied->CabActive < 0 ? - end::rear : - end::front ) ] + VehicleEnd::rear : + VehicleEnd::front ) ] & ( light::headlight_left | light::headlight_right | light::headlight_upper ) ) // któreś ze świateł zapalone? { // od wersji 357 oczekujemy podania komend dla AI przez scenerię /* - if( pVehicle->MoverParameters->iLights[ mvOccupied->CabActive < 0 ? end::rear : end::front ] & light::headlight_upper ) // górne światło zapalone + if( pVehicle->MoverParameters->iLights[ mvOccupied->CabActive < 0 ? VehicleEnd::rear : VehicleEnd::front ] & light::headlight_upper ) // górne światło zapalone OrderNext( DriverOrder::obeyTrain ); // jazda pociągowa else OrderNext( DriverOrder::shunt ); // jazda manewrowa diff --git a/vehicle/ai/engine.cpp b/vehicle/ai/engine.cpp index 8194aecb7..7c134e4b5 100644 --- a/vehicle/ai/engine.cpp +++ b/vehicle/ai/engine.cpp @@ -167,10 +167,10 @@ bool TController::PrepareEngine() cue_action( driver_hint::waitpressuretoolow ); } // enable motor blowers - if( mvOccupied->MotorBlowers[ end::front ].speed != 0 ) { + if( mvOccupied->MotorBlowers[ VehicleEnd::front ].speed != 0 ) { cue_action( driver_hint::frontmotorblowerson ); } - if( mvOccupied->MotorBlowers[ end::rear ].speed != 0 ) { + if( mvOccupied->MotorBlowers[ VehicleEnd::rear ].speed != 0 ) { cue_action( driver_hint::rearmotorblowerson ); } } @@ -237,8 +237,8 @@ TController::report_power_stall( bool const Poweravailable, double const Pantogr state.standing = mvOccupied->Vel < EU07_AI_NOMOVEMENT; if( mvPantographUnit->PantPress >= Pantographpressure ) { state.pantographs_up = - mvPantographUnit->Pantographs[ end::front ].is_active - || mvPantographUnit->Pantographs[ end::rear ].is_active; + mvPantographUnit->Pantographs[ VehicleEnd::front ].is_active + || mvPantographUnit->Pantographs[ VehicleEnd::rear ].is_active; } // the pantographs of the vehicle carrying them hold the wire they found above them if( auto const *carrier { pVehicle->FindPantographCarrier() }; @@ -424,11 +424,11 @@ TController::PrepareDirection() { /* if( iDirection == 0 ) { // jeśli nie ma ustalonego kierunku - if( mvOccupied->Couplers[ end::rear ].Connected == nullptr ) { + if( mvOccupied->Couplers[ VehicleEnd::rear ].Connected == nullptr ) { // jeśli z tyłu nie ma nic iDirection = -1; // jazda w kierunku sprzęgu 1 } - if( mvOccupied->Couplers[ end::front ].Connected == nullptr ) { + if( mvOccupied->Couplers[ VehicleEnd::front ].Connected == nullptr ) { // jeśli z przodu nie ma nic iDirection = 1; // jazda w kierunku sprzęgu 0 } diff --git a/vehicle/ai/force.cpp b/vehicle/ai/force.cpp index 72c87dc28..33db87ede 100644 --- a/vehicle/ai/force.cpp +++ b/vehicle/ai/force.cpp @@ -245,7 +245,7 @@ void TController::control_uphill_start() { return; } fUphillTractiveForce = 0.0; - for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { + for( auto const *vehicle { pVehicles[ VehicleEnd::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { // Ft is signed in the vehicle's own frame, and turned into the direction of travel as AbsAccS is fUphillTractiveForce += std::max( 0.0, vehicle->MoverParameters->Ft * ( vehicle->DirectionGet() == iDirection ? 1 : -1 ) * ( iDirection >= 0 ? 1 : -1 ) ); } @@ -286,7 +286,7 @@ bool TController::uphill_brake_top_up() { auto trainbrakeforce { 0.0 }; auto haswagons { false }; - for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { + for( auto const *vehicle { pVehicles[ VehicleEnd::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { if( vehicle->MoverParameters->Power < 0.01 ) { trainbrakeforce += vehicle->MoverParameters->Fb; haswagons = true; @@ -710,7 +710,7 @@ void TController::update_brake_charging() { if( BrakeChargingStart < 0.0 ) { BrakeChargingStart = ElapsedTime; } - for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { + for( auto const *vehicle { pVehicles[ VehicleEnd::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { auto const isovercharged { vehicle->MoverParameters != mvOccupied && vehicle->MoverParameters->PipePress > FSOverchargePipePress }; @@ -732,7 +732,7 @@ bool TController::is_departure_blocked( double const Delay ) const { double TController::consist_max_crp() const { auto result { 0.0 }; - for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { + for( auto const *vehicle { pVehicles[ VehicleEnd::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { result = std::max( result, vehicle->MoverParameters->Hamulec->GetCRP() ); } return result; diff --git a/vehicle/ai/obstacles.cpp b/vehicle/ai/obstacles.cpp index 16c237684..4ddd60df1 100644 --- a/vehicle/ai/obstacles.cpp +++ b/vehicle/ai/obstacles.cpp @@ -48,12 +48,12 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/ai/internal.h" -basic_event * TController::CheckTrackEventBackward(double fDirection, TTrack *Track, TDynamicObject *Vehicle, int const Eventdirection, end const End) +basic_event * TController::CheckTrackEventBackward(double fDirection, TTrack *Track, TDynamicObject *Vehicle, int const Eventdirection, VehicleEnd const End) { // sprawdzanie eventu w torze, czy jest sygnałowym - skanowanie do tyłu // NOTE: this method returns only one event which meets the conditions, due to limitations in the caller // TBD, TODO: clean up the caller and return all suitable events, as in theory things will go awry if the track has more than one signal auto const dir{ Vehicle->VectorFront() * (double)Vehicle->DirectionGet() }; - auto const pos{ End == end::front ? Vehicle->RearPosition() : Vehicle->HeadPosition() }; + auto const pos{ End == VehicleEnd::front ? Vehicle->RearPosition() : Vehicle->HeadPosition() }; auto const &eventsequence { ( fDirection * Eventdirection > 0 ? Track->m_events2 : Track->m_events1 ) }; for( auto const &event : eventsequence ) { if( event.second != nullptr @@ -63,7 +63,7 @@ basic_event * TController::CheckTrackEventBackward(double fDirection, TTrack *Tr auto const sl{ event.second->input_location() }; // położenie komórki pamięci auto const sem{ sl - pos }; // wektor do komórki pamięci od końca składu auto const isahead { dir.x * sem.x + dir.z * sem.z > 0 }; - if( End == end::front ? isahead : !isahead ) { + if( End == VehicleEnd::front ? isahead : !isahead ) { // iloczyn skalarny jest ujemny, gdy sygnał stoi z tyłu return event.second; } @@ -72,7 +72,7 @@ basic_event * TController::CheckTrackEventBackward(double fDirection, TTrack *Tr return nullptr; }; -TTrack * TController::BackwardTraceRoute(double &fDistance, double &fDirection, TDynamicObject *Vehicle, basic_event *&Event, int const Eventdirection, end const End, bool const Untiloccupied ) +TTrack * TController::BackwardTraceRoute(double &fDistance, double &fDirection, TDynamicObject *Vehicle, basic_event *&Event, int const Eventdirection, VehicleEnd const End, bool const Untiloccupied ) { // szukanie sygnalizatora w kierunku przeciwnym jazdy (eventu odczytu komórki pamięci) auto *Track = Vehicle->GetTrack(); double fCurrentDistance = Vehicle->RaTranslationGet(); // aktualna pozycja na torze @@ -192,9 +192,9 @@ TCommandType TController::BackwardScan( double const Range ) basic_event *e = nullptr; // event potencjalnie od semafora // opcjonalnie może być skanowanie od "wskaźnika" z przodu, np. W5, Tm=Ms1, koniec toru wg // drugiej osi w kierunku ruchu - auto const *scantrack{BackwardTraceRoute(scandist, scandir, pVehicles[end::front], e)}; + auto const *scantrack{BackwardTraceRoute(scandist, scandir, pVehicles[VehicleEnd::front], e)}; auto const dir{(double)startdir * - pVehicles[end::front]->VectorFront()}; // wektor w kierunku jazdy/szukania + pVehicles[VehicleEnd::front]->VectorFront()}; // wektor w kierunku jazdy/szukania // jeśli wstecz wykryto koniec toru to raczej nic się nie da w takiej sytuacji zrobić if (e == nullptr) @@ -216,7 +216,7 @@ TCommandType TController::BackwardScan( double const Range ) { // najpierw sprawdzamy, czy semafor czy inny znak został przejechany auto const sl{e->input_location()}; // położenie komórki pamięci - auto const pos{pVehicles[end::rear]->RearPosition()}; // pozycja tyłu + auto const pos{pVehicles[VehicleEnd::rear]->RearPosition()}; // pozycja tyłu if (auto const sem{sl - pos}; dir.x * sem.x + dir.z * sem.z < 0) // wektor do komórki pamięci od końca składu { // jeśli został minięty @@ -373,7 +373,7 @@ TController::scan_obstacles( double const Range ) { // HACK: vehicle order in the consist is based on intended travel direction // if our actual travel direction doesn't match that, we should be scanning from the other end of the consist // we cast to int to avoid getting confused by microstutters - auto *frontvehicle { pVehicles[ ( static_cast( mvOccupied->V ) * iDirection >= 0 ? end::front : end::rear ) ] }; + auto *frontvehicle { pVehicles[ ( static_cast( mvOccupied->V ) * iDirection >= 0 ? VehicleEnd::front : VehicleEnd::rear ) ] }; int routescandirection; // for moving vehicle determine heading from velocity; for standing fall back on the set direction @@ -381,11 +381,11 @@ TController::scan_obstacles( double const Range ) { frontvehicle->MoverParameters->V > 0.0 : pVehicle->DirectionGet() == frontvehicle->DirectionGet() ? iDirection >= 0 : iDirection <= 0 ) { // towards coupler 0 - routescandirection = end::front; + routescandirection = NumberOf( VehicleEnd::front ); } else { // towards coupler 1 - routescandirection = end::rear; + routescandirection = NumberOf( VehicleEnd::rear ); } /* if( pVehicle->MoverParameters->CabOccupied < 0 ) { diff --git a/vehicle/ai/orders.cpp b/vehicle/ai/orders.cpp index 091a443ef..ce905afec 100644 --- a/vehicle/ai/orders.cpp +++ b/vehicle/ai/orders.cpp @@ -226,12 +226,12 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N // NOTE: this may result in visually ugly quick switch between closing and opening the doors, but eh if( pVehicle->MoverParameters->Doors.close_control == control_t::driver || pVehicle->MoverParameters->Doors.close_control == control_t::mixed ) { - pVehicle->MoverParameters->OperateDoors( side::right, false ); - pVehicle->MoverParameters->OperateDoors( side::left, false ); + pVehicle->MoverParameters->OperateDoors( VehicleSide::right, false ); + pVehicle->MoverParameters->OperateDoors( VehicleSide::left, false ); } if( pVehicle->MoverParameters->Doors.permit_needed ) { - pVehicle->MoverParameters->PermitDoors( side::right, false ); - pVehicle->MoverParameters->PermitDoors( side::left, false ); + pVehicle->MoverParameters->PermitDoors( VehicleSide::right, false ); + pVehicle->MoverParameters->PermitDoors( VehicleSide::left, false ); } } drivingFlags.doorOpened = false; @@ -269,7 +269,7 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N NewCommand = TrainParams.Relation2; // relacja docelowa z rozkładu } // jeszcze poustawiać tekstury na wyświetlaczach - TDynamicObject *p = pVehicles[end::front]; + TDynamicObject *p = pVehicles[VehicleEnd::front]; while (p) { p->DestinationSet(NewCommand, TrainParams.TrainName); // relacja docelowa @@ -505,13 +505,13 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N if( NewValue1 >= 0.0 ) { // jeśli ilość wagonów inna niż wszystkie będzie odczepianie, // ale jeśli wagony są z przodu, to trzeba najpierw zmienić kierunek - if( mvOccupied->Couplers[mvOccupied->DirAbsolute > 0 ? end::rear : end::front].Connected == nullptr // z tyłu nic - && mvOccupied->Couplers[mvOccupied->DirAbsolute > 0 ? end::front : end::rear].Connected != nullptr ) { // a z przodu skład + if( mvOccupied->Couplers[mvOccupied->DirAbsolute > 0 ? VehicleEnd::rear : VehicleEnd::front].Connected == nullptr // z tyłu nic + && mvOccupied->Couplers[mvOccupied->DirAbsolute > 0 ? VehicleEnd::front : VehicleEnd::rear].Connected != nullptr ) { // a z przodu skład iDirectionOrder = -iDirection; // zmiana na ciągnięcie OrderNext( DriverOrder::changeDirection ); // najpierw zmień kierunek (zastąpi Disconnect) OrderPush( DriverOrder::disconnect ); // a odczep już po zmianie kierunku } - else if( mvOccupied->Couplers[ mvOccupied->DirAbsolute > 0 ? end::rear : end::front ].Connected != nullptr ) { // z tyłu coś + else if( mvOccupied->Couplers[ mvOccupied->DirAbsolute > 0 ? VehicleEnd::rear : VehicleEnd::front ].Connected != nullptr ) { // z tyłu coś OrderNext( DriverOrder::disconnect ); // jak ciągnie, to tylko odczep (NewValue1) wagonów } else { @@ -573,7 +573,7 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N fWarningDuration = NewValue1; // czas trąbienia cue_action( driver_hint::hornon, NewValue2 ); // horn combination flag simulation::Blackbox.horn_requested( - pVehicles[ end::front ], NewValue1, NewValue2, NewLocation != nullptr ? *NewLocation : pVehicles[ end::front ]->GetPosition() ); + pVehicles[ VehicleEnd::front ], NewValue1, NewValue2, NewLocation != nullptr ? *NewLocation : pVehicles[ VehicleEnd::front ]->GetPosition() ); } return true; } @@ -597,8 +597,8 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N if( NewCommand == "SetLights" ) { // set consist lights pattern hints - m_lighthints[ end::front ] = static_cast( NewValue1 ); - m_lighthints[ end::rear ] = static_cast( NewValue2 ); + m_lighthints[ VehicleEnd::front ] = static_cast( NewValue1 ); + m_lighthints[ VehicleEnd::rear ] = static_cast( NewValue2 ); if( true == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { // light hints only apply in the obey_train mode CheckVehicles(); @@ -664,7 +664,7 @@ void TController::OrderCheck() if( OrderCurrentGet() != DriverOrder::obeyTrain ) { // reset light hints - m_lighthints[ end::front ] = m_lighthints[ end::rear ] = -1; + m_lighthints[ VehicleEnd::front ] = m_lighthints[ VehicleEnd::rear ] = -1; } if( OrderCurrentGet() & ( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect | DriverOrder::obeyTrain | DriverOrder::bank ) ) { CheckVehicles(); // sprawdzić światła @@ -918,7 +918,7 @@ TController::UpdateLooseShunt() { && mvOccupied->Vel < 1.0 ) { auto *vehicle { Obstacle.vehicle }; - auto const direction { ( vehicle->Prev() != nullptr ? end::front : end::rear ) }; + auto const direction { ( vehicle->Prev() != nullptr ? VehicleEnd::front : VehicleEnd::rear ) }; while( vehicle != nullptr ) { if( vehicle->MoverParameters->BrakePress > 0.2 ) { vehicle->MoverParameters->BrakeLevelSet( 0 ); // hamulec na zero, aby nie hamował @@ -926,7 +926,7 @@ TController::UpdateLooseShunt() { } // NOTE: we trust the consist to be arranged in a valid chain // TBD, TODO: traversal direction validation? - vehicle = direction == end::front ? vehicle->Prev() : vehicle->Next(); + vehicle = direction == VehicleEnd::front ? vehicle->Prev() : vehicle->Next(); } } } @@ -985,7 +985,7 @@ TController::UpdateConnect() { auto expectedcoupling { iCoupler }; if( neighbour.vehicle != nullptr ) { auto const neighbourend { neighbour.vehicle_end != 2 ? neighbour.vehicle_end : vehicleparameters->Couplers[ couplingend ].ConnectedNr }; - expectedcoupling = vehicleparameters->CompatibleCoupling( couplingend, *neighbour.vehicle->MoverParameters, neighbourend, iCoupler ); + expectedcoupling = vehicleparameters->CompatibleCoupling( EndOf( couplingend ), *neighbour.vehicle->MoverParameters, EndOf( neighbourend ), iCoupler ); } if( vehicleparameters->Couplers[ couplingend ].CouplingFlag != expectedcoupling ) { if( neighbour.vehicle != nullptr && neighbour.distance < 10 ) { @@ -1024,7 +1024,7 @@ TController::UpdateConnect() { if( Obstacle.distance <= 20.0 && !iCouplingVehicle ) { // write down which vehicle should be coupled with the target consist, // so we don't lose track of it if the user does something unexpected - iCouplingVehicle = {pVehicles[end::front], (pVehicles[end::front]->DirectionGet() > 0 ? end::front : end::rear)}; + iCouplingVehicle = {pVehicles[VehicleEnd::front], NumberOf(pVehicles[VehicleEnd::front]->DirectionGet() > 0 ? VehicleEnd::front : VehicleEnd::rear)}; drivingFlags.connect = true; } } @@ -1037,8 +1037,8 @@ TController::unit_count( int const Threshold ) const { auto unitcount { 1 }; do { auto const decoupledend{ ( vehicle->DirectionGet() > 0 ? // numer sprzęgu od strony czoła składu - end::rear : - end::front ) }; + VehicleEnd::rear : + VehicleEnd::front ) }; auto const coupling { vehicle->MoverParameters->Couplers[ decoupledend ].CouplingFlag }; if( coupling == Coupling::none ) { break; @@ -1083,9 +1083,9 @@ TController::UpdateDisconnect() { auto vehiclecount { iVehicleCount }; // ile wagonów ma zostać // szukanie pojazdu do odczepienia do { - decoupledend = decoupledvehicle->DirectionGet() > 0 ? // numer sprzęgu od strony czoła składu - end::front : - end::rear; + decoupledend = NumberOf( decoupledvehicle->DirectionGet() > 0 ? // numer sprzęgu od strony czoła składu + VehicleEnd::front : + VehicleEnd::rear ); // jeżeli sprzęg zablokowany to liczymy człony jako jeden if( decoupledvehicle->MoverParameters->Couplers[ decoupledend ].CouplingFlag & Coupling::permanent ) { ++vehiclecount; @@ -1121,7 +1121,7 @@ TController::UpdateDisconnect() { decoupledvehicle->remove_coupler_adapter( decoupledend ); } */ - if( pVehicles[ end::front ]->MoverParameters->Couplers[ decoupledend ].has_adapter() ) { + if( pVehicles[ VehicleEnd::front ]->MoverParameters->Couplers[ decoupledend ].has_adapter() ) { cue_action( driver_hint::couplingadapterremove, decoupledend ); } } diff --git a/vehicle/ai/routescan.cpp b/vehicle/ai/routescan.cpp index 35fd170fc..aaf7f3988 100644 --- a/vehicle/ai/routescan.cpp +++ b/vehicle/ai/routescan.cpp @@ -442,7 +442,7 @@ void TController::TableCheck(double fDistance) { // przeliczenie odległości w tabelce, ewentualnie doskanowanie (bez analizy prędkości itp.) if( iTableDirection != iDirection ) { // jak zmiana kierunku, to skanujemy od końca składu - TableTraceRoute( fDistance, pVehicles[ end::rear ] ); + TableTraceRoute( fDistance, pVehicles[ VehicleEnd::rear ] ); TableSort(); } else if (iTableDirection) @@ -479,7 +479,7 @@ void TController::TableCheck(double fDistance) SemNextStopIndex = npos; } tLast = sSpeedTable[ i ].trTrack; - TableTraceRoute( fDistance, pVehicles[ end::rear ] ); + TableTraceRoute( fDistance, pVehicles[ VehicleEnd::rear ] ); TableSort(); // nie kontynuujemy pętli, trzeba doskanować ciąg dalszy break; @@ -515,7 +515,7 @@ void TController::TableCheck(double fDistance) CheckSignalPassed( sSpeedTable[ iLast ], lastpassedbefore ); // WriteLog("TableCheck: Upate last track. Dist=" + AnsiString(sSpeedTable[iLast].fDist)); if( sSpeedTable[ iLast ].fDist < fDistance ) { - TableTraceRoute( fDistance, pVehicles[ end::rear ] ); // doskanowanie dalszego odcinka + TableTraceRoute( fDistance, pVehicles[ VehicleEnd::rear ] ); // doskanowanie dalszego odcinka TableSort(); } // garbage collection @@ -578,7 +578,7 @@ void TController::CheckSignalPassed( TSpeedPos const &Point, bool const Passedbe // automatic block signal is kept as the speed allowed after it, with a flag of its own auto const speedatsignal { Point.flags.HasAll(SpeedPointFlag::stopOnAutomaticBlock) ? 0.0 : Point.fVelNext }; simulation::Blackbox.signal_passed( - pVehicles[ end::front ], *Point.evEvent, + pVehicles[ VehicleEnd::front ], *Point.evEvent, speedatsignal, Point.evEvent->input_value( 2 ), mvOccupied->Vel, -Point.fDist, passing_flags_of( Point, speedatsignal, false == OrderCurrentGet().HasAny( DriverOrder::shunt | DriverOrder::looseShunt ) ) ); diff --git a/vehicle/ai/situation.cpp b/vehicle/ai/situation.cpp index 06cab6d70..9ef52112f 100644 --- a/vehicle/ai/situation.cpp +++ b/vehicle/ai/situation.cpp @@ -178,10 +178,10 @@ TController::control_pantographs() { if( fOverhead2 > 0.0 || iOverheadDown ) { // jazda z opuszczonymi pantografami - if( mvPantographUnit->Pantographs[ end::front ].is_active ) { + if( mvPantographUnit->Pantographs[ VehicleEnd::front ].is_active ) { cue_action( driver_hint::frontpantographvalveoff ); } - if( mvPantographUnit->Pantographs[ end::rear ].is_active ) { + if( mvPantographUnit->Pantographs[ VehicleEnd::rear ].is_active ) { cue_action( driver_hint::rearpantographvalveoff ); } } @@ -451,14 +451,14 @@ TController::sync_lights_selector() { if( mvOccupied->LightsPosNo <= 0 ) { return; } - auto const *headvehicle { pVehicles[ end::front ] }; + auto const *headvehicle { pVehicles[ VehicleEnd::front ] }; if( headvehicle == nullptr ) { return; } // same choice of the light table as in TDynamicObject::SetLights() - auto const lightstable { ( mvOccupied->CabOccupied * pVehicle->DirectionGet() >= 0 ? end::front : end::rear ) }; + auto const lightstable { ( mvOccupied->CabOccupied * pVehicle->DirectionGet() >= 0 ? VehicleEnd::front : VehicleEnd::rear ) }; // same choice of the lit vehicle end as in TDynamicObject::RaLightsSet() - auto const headend { ( headvehicle->iDirection > 0 ? end::front : end::rear ) }; + auto const headend { ( headvehicle->iDirection > 0 ? VehicleEnd::front : VehicleEnd::rear ) }; auto const position { handover::light_selector_position( - *mvOccupied, lightstable, headvehicle->MoverParameters->iLights[ headend ], headvehicle->LightList( headend ) ) }; + *mvOccupied, NumberOf( lightstable ), headvehicle->MoverParameters->iLights[ headend ], headvehicle->LightList( headend ) ) }; if( position == mvOccupied->LightsPos ) { return; } mvOccupied->LightsPos = position; @@ -476,8 +476,8 @@ TController::sync_lights_dimmer() { if( mvOccupied->dimPositions.empty() ) { return; } - auto const *headvehicle { pVehicles[ end::front ] }; - auto const headend { ( headvehicle != nullptr && headvehicle->iDirection > 0 ? end::front : end::rear ) }; + auto const *headvehicle { pVehicles[ VehicleEnd::front ] }; + auto const headend { ( headvehicle != nullptr && headvehicle->iDirection > 0 ? VehicleEnd::front : VehicleEnd::rear ) }; auto const headlightson { headvehicle != nullptr && ( headvehicle->MoverParameters->iLights[ headend ] & ( light::headlight_left | light::headlight_right | light::headlight_upper ) ) != 0 }; @@ -503,25 +503,25 @@ TController::control_lights() { // jeśli jazda pociągowa if( true == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { // head lights - if( m_lighthints[ end::front ] == -1 ) { + if( m_lighthints[ VehicleEnd::front ] == -1 ) { cue_action( driver_hint::headcodepc1 ); } - else if( m_lighthints[ end::front ] == ( light::redmarker_left | light::headlight_right | light::headlight_upper ) ) { + else if( m_lighthints[ VehicleEnd::front ] == ( light::redmarker_left | light::headlight_right | light::headlight_upper ) ) { cue_action( driver_hint::headcodepc2 ); } else { // custom light pattern if( AIControllFlag ) { - pVehicles[ end::front ]->RaLightsSet( m_lighthints[ end::front ], -1 ); + pVehicles[ VehicleEnd::front ]->RaLightsSet( m_lighthints[ VehicleEnd::front ], -1 ); } } // tail lights - if( m_lighthints[ end::rear ] == -1 ) { + if( m_lighthints[ VehicleEnd::rear ] == -1 ) { cue_action( driver_hint::headcodepc5 ); } else { if( AIControllFlag ) { - pVehicles[ end::rear ]->RaLightsSet( -1, m_lighthints[ end::rear ] ); + pVehicles[ VehicleEnd::rear ]->RaLightsSet( -1, m_lighthints[ VehicleEnd::rear ] ); } } } diff --git a/vehicle/ai/speed.cpp b/vehicle/ai/speed.cpp index 84525a670..1e461e3f9 100644 --- a/vehicle/ai/speed.cpp +++ b/vehicle/ai/speed.cpp @@ -763,7 +763,7 @@ TController::adjust_desired_speed_for_current_speed() { } } // HACK: limit acceleration for cargo trains, to reduce probability of breaking couplers on sudden jolts - auto MaxAcc{ 0.5 * mvOccupied->Couplers[(mvOccupied->DirAbsolute >= 0 ? end::rear : end::front)].FmaxC / fMass }; + auto MaxAcc{ 0.5 * mvOccupied->Couplers[(mvOccupied->DirAbsolute >= 0 ? VehicleEnd::rear : VehicleEnd::front)].FmaxC / fMass }; if( iVehicles - ControlledEnginesCount > 0 ) { MaxAcc *= std::clamp( vel * 0.025, 0.2, 1.0 ); } diff --git a/vehicle/ai/speedtable.cpp b/vehicle/ai/speedtable.cpp index ca7f5511e..12fa2f964 100644 --- a/vehicle/ai/speedtable.cpp +++ b/vehicle/ai/speedtable.cpp @@ -462,7 +462,7 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub m_lastexchangestop = asNextStop; m_lastexchangedirection = pVehicle->DirectionGet(); m_lastexchangeplatforms = static_cast( std::floor( std::abs( Point.evEvent->input_value( 2 ) ) ) ) % 10; - auto const exchangetime { simulation::Station.update_load( pVehicles[ end::front ], TrainParams, m_lastexchangeplatforms ) }; + auto const exchangetime { simulation::Station.update_load( pVehicles[ VehicleEnd::front ], TrainParams, m_lastexchangeplatforms ) }; WaitingSet( exchangetime ); // announce the stop name while at it announce( announcement_t::current ); @@ -573,7 +573,7 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub asNextStop = TrainParams.NextStop(); // informacja o końcu trasy TrainParams.NewName("none"); // czyszczenie nieaktualnego rozkładu // koniec kursu, gasimy wyświetlacze relacji (tablice blaszane zostają) - for( auto *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { + for( auto *vehicle { pVehicles[ VehicleEnd::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { vehicle->DestinationClear(); } // ma nie podjeżdżać pod W4 i ma je pomijać @@ -723,9 +723,9 @@ double TController::point_limit_end( glm::dvec3 const &Heading ) const { auto const origin { pVehicle->GetPosition() }; auto result { 0.0 }; auto first { true }; - for( auto const *vehicle : { pVehicles[ end::front ], pVehicles[ end::rear ] } ) { + for( auto const *vehicle : { pVehicles[ VehicleEnd::front ], pVehicles[ VehicleEnd::rear ] } ) { if( vehicle == nullptr ) { continue; } - for( auto const side : { end::front, end::rear } ) { + for (auto const side : VehicleEnds) { auto const along { glm::dot( vehicle->CouplerPosition( side ) - origin, Heading ) }; result = ( first ? along : std::max( result, along ) ); first = false; @@ -779,8 +779,8 @@ void TController::update_point_limits() { m_pointlimitsvehicle = pVehicle; m_pointlimitsposition = position; // the consist, as its end vehicles and its length - auto const *front { pVehicles[ end::front ] }; - auto const *rear { pVehicles[ end::rear ] }; + auto const *front { pVehicles[ VehicleEnd::front ] }; + auto const *rear { pVehicles[ VehicleEnd::rear ] }; auto const consistchanged { false == ( ( front == m_pointlimitsends[ 0 ] && rear == m_pointlimitsends[ 1 ] ) || ( front == m_pointlimitsends[ 1 ] && rear == m_pointlimitsends[ 0 ] ) ) @@ -877,7 +877,7 @@ glm::dvec3 TController::travel_direction() const { if( pVehicle == nullptr || iDirection == 0 ) { return glm::dvec3 { 0.0 }; } // the direction is given against the couplers of the vehicle the driver is in, which is the vehicle measured; // along its own length it follows the track, where the chord of a long consist on a curve doesn't - auto const along { pVehicle->CouplerPosition( end::front ) - pVehicle->CouplerPosition( end::rear ) }; + auto const along { pVehicle->CouplerPosition( VehicleEnd::front ) - pVehicle->CouplerPosition( VehicleEnd::rear ) }; auto const length { glm::length( along ) }; if( length < 0.001 ) { return glm::dvec3 { 0.0 }; } return ( iDirection > 0 ? along : -along ) / length; @@ -943,7 +943,7 @@ TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPo case TCommandType::cm_SecuritySystemMagnet: { // NOTE: magnet induction calculation presumes the driver is located in the front vehicle // TBD, TODO: take into account actual position of controlled/occupied vehicle in the consist, whichever comes first - auto const magnetlocation { pVehicles[ end::front ]->MoverParameters->SecuritySystem.MagnetLocation }; + auto const magnetlocation { pVehicles[ VehicleEnd::front ]->MoverParameters->SecuritySystem.MagnetLocation }; auto const magnetrange { 1.0 }; auto const ismagnetpassed { Point.fDist < -( magnetlocation + magnetrange ) }; if( Point.fDist < -magnetlocation && (mvOccupied->Vel > EU07_AI_NOMOVEMENT || false == ismagnetpassed) ) { @@ -1026,9 +1026,9 @@ TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPo basic_event *foundevent = nullptr; if( Point.fDist - fMaxProximityDist > 0 ) { auto scandistance{ Point.fDist + fLength - fMaxProximityDist }; - auto *scanvehicle{ pVehicles[ end::rear ] }; + auto *scanvehicle{ pVehicles[ VehicleEnd::rear ] }; auto scandirection{ scanvehicle->DirectionGet() * scanvehicle->RaDirectionGet() }; - auto *foundtrack = BackwardTraceRoute( scandistance, scandirection, scanvehicle, foundevent, -1, end::front, false ); + auto *foundtrack = BackwardTraceRoute( scandistance, scandirection, scanvehicle, foundevent, -1, VehicleEnd::front, false ); } if( foundevent == nullptr ) { drivingFlags.trackEnd = true; // to dalsza jazda trwale ograniczona (W5, koniec toru) diff --git a/vehicle/cab/auxiliarycommands.cpp b/vehicle/cab/auxiliarycommands.cpp index f24eb9cb6..92685e888 100644 --- a/vehicle/cab/auxiliarycommands.cpp +++ b/vehicle/cab/auxiliarycommands.cpp @@ -1068,7 +1068,7 @@ void TTrain::OnCommand_motorblowerstogglefront(TTrain *Train, command_data const return; } - if (false == Train->mvControlled->MotorBlowers[end::front].is_enabled) + if (false == Train->mvControlled->MotorBlowers[VehicleEnd::front].is_enabled) { // turn on OnCommand_motorblowersenablefront(Train, Command); @@ -1096,13 +1096,13 @@ void TTrain::OnCommand_motorblowersenablefront(TTrain *Train, command_data const { // visual feedback Train->ggMotorBlowersFrontButton.UpdateValue(1.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(true, end::front); + Train->mvControlled->MotorBlowersSwitch(true, VehicleEnd::front); } else if (Command.action == GLFW_RELEASE) { // visual feedback Train->ggMotorBlowersFrontButton.UpdateValue(0.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(false, end::front); + Train->mvControlled->MotorBlowersSwitch(false, VehicleEnd::front); } } else @@ -1112,8 +1112,8 @@ void TTrain::OnCommand_motorblowersenablefront(TTrain *Train, command_data const { // visual feedback Train->ggMotorBlowersFrontButton.UpdateValue(1.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(true, end::front); - Train->mvControlled->MotorBlowersSwitchOff(false, end::front); + Train->mvControlled->MotorBlowersSwitch(true, VehicleEnd::front); + Train->mvControlled->MotorBlowersSwitchOff(false, VehicleEnd::front); } } } @@ -1139,8 +1139,8 @@ void TTrain::OnCommand_motorblowersdisablefront(TTrain *Train, command_data cons { // visual feedback Train->ggMotorBlowersFrontButton.UpdateValue(0.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(false, end::front); - Train->mvControlled->MotorBlowersSwitchOff(true, end::front); + Train->mvControlled->MotorBlowersSwitch(false, VehicleEnd::front); + Train->mvControlled->MotorBlowersSwitchOff(true, VehicleEnd::front); } } } @@ -1167,7 +1167,7 @@ void TTrain::OnCommand_motorblowerstogglerear(TTrain *Train, command_data const return; } - if (false == Train->mvControlled->MotorBlowers[end::rear].is_enabled) + if (false == Train->mvControlled->MotorBlowers[VehicleEnd::rear].is_enabled) { // turn on OnCommand_motorblowersenablerear(Train, Command); @@ -1195,13 +1195,13 @@ void TTrain::OnCommand_motorblowersenablerear(TTrain *Train, command_data const { // visual feedback Train->ggMotorBlowersRearButton.UpdateValue(1.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(true, end::rear); + Train->mvControlled->MotorBlowersSwitch(true, VehicleEnd::rear); } else if (Command.action == GLFW_RELEASE) { // visual feedback Train->ggMotorBlowersRearButton.UpdateValue(0.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(false, end::rear); + Train->mvControlled->MotorBlowersSwitch(false, VehicleEnd::rear); } } else @@ -1211,8 +1211,8 @@ void TTrain::OnCommand_motorblowersenablerear(TTrain *Train, command_data const { // visual feedback Train->ggMotorBlowersRearButton.UpdateValue(1.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(true, end::rear); - Train->mvControlled->MotorBlowersSwitchOff(false, end::rear); + Train->mvControlled->MotorBlowersSwitch(true, VehicleEnd::rear); + Train->mvControlled->MotorBlowersSwitchOff(false, VehicleEnd::rear); } } } @@ -1238,8 +1238,8 @@ void TTrain::OnCommand_motorblowersdisablerear(TTrain *Train, command_data const { // visual feedback Train->ggMotorBlowersRearButton.UpdateValue(0.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(false, end::rear); - Train->mvControlled->MotorBlowersSwitchOff(true, end::rear); + Train->mvControlled->MotorBlowersSwitch(false, VehicleEnd::rear); + Train->mvControlled->MotorBlowersSwitchOff(true, VehicleEnd::rear); } } } @@ -1259,15 +1259,15 @@ void TTrain::OnCommand_motorblowersdisableall(TTrain *Train, command_data const { // visual feedback Train->ggMotorBlowersAllOffButton.UpdateValue(1.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitchOff(true, end::front); - Train->mvControlled->MotorBlowersSwitchOff(true, end::rear); + Train->mvControlled->MotorBlowersSwitchOff(true, VehicleEnd::front); + Train->mvControlled->MotorBlowersSwitchOff(true, VehicleEnd::rear); } else if (Command.action == GLFW_RELEASE) { // visual feedback Train->ggMotorBlowersAllOffButton.UpdateValue(0.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitchOff(false, end::front); - Train->mvControlled->MotorBlowersSwitchOff(false, end::rear); + Train->mvControlled->MotorBlowersSwitchOff(false, VehicleEnd::front); + Train->mvControlled->MotorBlowersSwitchOff(false, VehicleEnd::rear); } } else @@ -1279,16 +1279,16 @@ void TTrain::OnCommand_motorblowersdisableall(TTrain *Train, command_data const if (Train->ggMotorBlowersAllOffButton.GetDesiredValue() < 0.5f) { // switch is off, activate - Train->mvControlled->MotorBlowersSwitchOff(true, end::front); - Train->mvControlled->MotorBlowersSwitchOff(true, end::rear); + Train->mvControlled->MotorBlowersSwitchOff(true, VehicleEnd::front); + Train->mvControlled->MotorBlowersSwitchOff(true, VehicleEnd::rear); // visual feedback Train->ggMotorBlowersRearButton.UpdateValue(1.f, Train->dsbSwitch); } else { // deactivate - Train->mvControlled->MotorBlowersSwitchOff(false, end::front); - Train->mvControlled->MotorBlowersSwitchOff(false, end::rear); + Train->mvControlled->MotorBlowersSwitchOff(false, VehicleEnd::front); + Train->mvControlled->MotorBlowersSwitchOff(false, VehicleEnd::rear); // visual feedback Train->ggMotorBlowersRearButton.UpdateValue(0.f, Train->dsbSwitch); } diff --git a/vehicle/cab/cabcommands.cpp b/vehicle/cab/cabcommands.cpp index 496fbb917..5b505ed85 100644 --- a/vehicle/cab/cabcommands.cpp +++ b/vehicle/cab/cabcommands.cpp @@ -555,11 +555,11 @@ void TTrain::OnCommand_cabchangeforward(TTrain *Train, command_data const &Comma { if (auto const movedirection{1}; false == Train->CabChange(movedirection)) { - auto const exitdirection{(movedirection > 0 ? end::front : end::rear)}; + auto const exitdirection{(movedirection > 0 ? VehicleEnd::front : VehicleEnd::rear)}; if (Train->mvOccupied->Couplers[exitdirection].CouplingFlag.HasAll(Coupling::gangway)) { // przejscie do nastepnego pojazdu - auto *targetvehicle = exitdirection == end::front ? Train->DynamicObject->PrevConnected() : Train->DynamicObject->NextConnected(); + auto *targetvehicle = exitdirection == VehicleEnd::front ? Train->DynamicObject->PrevConnected() : Train->DynamicObject->NextConnected(); targetvehicle->MoverParameters->CabOccupied = Train->mvOccupied->Neighbours[exitdirection].vehicle_end ? -1 : 1; Train->MoveToVehicle(targetvehicle); } @@ -585,11 +585,11 @@ void TTrain::OnCommand_cabchangebackward(TTrain *Train, command_data const &Comm if (auto const movedirection{-1}; false == Train->CabChange(movedirection)) { // current vehicle doesn't extend any farther in this direction, check if we there's one connected we can move to - auto const exitdirection{(movedirection > 0 ? end::front : end::rear)}; + auto const exitdirection{(movedirection > 0 ? VehicleEnd::front : VehicleEnd::rear)}; if (Train->mvOccupied->Couplers[exitdirection].CouplingFlag.HasAll(Coupling::gangway)) { // przejscie do nastepnego pojazdu - auto *targetvehicle = exitdirection == end::front ? Train->DynamicObject->PrevConnected() : Train->DynamicObject->NextConnected(); + auto *targetvehicle = exitdirection == VehicleEnd::front ? Train->DynamicObject->PrevConnected() : Train->DynamicObject->NextConnected(); targetvehicle->MoverParameters->CabOccupied = Train->mvOccupied->Neighbours[exitdirection].vehicle_end ? -1 : 1; Train->MoveToVehicle(targetvehicle); } diff --git a/vehicle/cab/couplingcommands.cpp b/vehicle/cab/couplingcommands.cpp index 618b64da4..4013fa0fd 100644 --- a/vehicle/cab/couplingcommands.cpp +++ b/vehicle/cab/couplingcommands.cpp @@ -61,7 +61,7 @@ void TTrain::OnCommand_nearestcarcouplingincrease(TTrain *Train, command_data co if (couplerindex != -1 && vehicle != nullptr) { - vehicle->couple(couplerindex); + vehicle->couple(EndOf(couplerindex)); } if (Train->DynamicObject->Mechanik) { @@ -85,7 +85,7 @@ void TTrain::OnCommand_nearestcarcouplingdisconnect(TTrain *Train, command_data if (couplerindex != -1 && vehicle != nullptr) { - vehicle->uncouple(couplerindex); + vehicle->uncouple(EndOf(couplerindex)); } if (Train->DynamicObject->Mechanik) { @@ -108,7 +108,7 @@ void TTrain::OnCommand_nearestcarcoupleradapterattach(TTrain * /*Train*/, comman } auto const couplerindex = - glm::length2(glm::vec3{vehicle->CouplerPosition(end::front)} - Command.location) < glm::length2(glm::vec3{vehicle->CouplerPosition(end::rear)} - Command.location) ? end::front : end::rear; + glm::length2(glm::vec3{vehicle->CouplerPosition(VehicleEnd::front)} - Command.location) < glm::length2(glm::vec3{vehicle->CouplerPosition(VehicleEnd::rear)} - Command.location) ? VehicleEnd::front : VehicleEnd::rear; vehicle->attach_coupler_adapter(couplerindex); } @@ -127,7 +127,7 @@ void TTrain::OnCommand_nearestcarcoupleradapterremove(TTrain * /*Train*/, comman } auto const couplerindex = - glm::length2(glm::vec3{vehicle->CouplerPosition(end::front)} - Command.location) < glm::length2(glm::vec3{vehicle->CouplerPosition(end::rear)} - Command.location) ? end::front : end::rear; + glm::length2(glm::vec3{vehicle->CouplerPosition(VehicleEnd::front)} - Command.location) < glm::length2(glm::vec3{vehicle->CouplerPosition(VehicleEnd::rear)} - Command.location) ? VehicleEnd::front : VehicleEnd::rear; vehicle->remove_coupler_adapter(couplerindex); } @@ -182,7 +182,7 @@ void TTrain::OnCommand_occupiedcarcouplingdisconnectback(TTrain *Train, command_ if (Train->DynamicObject) { - Train->DynamicObject->uncouple(1 - Train->cab_to_end()); + Train->DynamicObject->uncouple(Opposite(Train->cab_to_end())); if (Train->DynamicObject->Mechanik) { // aktualizacja flag kierunku w składzie diff --git a/vehicle/cab/doorcommands.cpp b/vehicle/cab/doorcommands.cpp index 1b57e69b3..6205647c6 100644 --- a/vehicle/cab/doorcommands.cpp +++ b/vehicle/cab/doorcommands.cpp @@ -168,7 +168,7 @@ void TTrain::OnCommand_doorpermitleft(TTrain *Train, command_data const &Command return; } - auto const side{(Train->cab_to_end() == end::front ? side::left : side::right)}; + auto const side{(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right)}; if (Command.action == GLFW_PRESS) { @@ -214,7 +214,7 @@ void TTrain::OnCommand_doorpermitright(TTrain *Train, command_data const &Comman return; } - auto const side{(Train->cab_to_end() == end::front ? side::right : side::left)}; + auto const side{(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left)}; if (Command.action == GLFW_PRESS) { @@ -289,7 +289,7 @@ void TTrain::OnCommand_dooropenleft(TTrain *Train, command_data const &Command) if (Command.action == GLFW_PRESS) { - Train->mvOccupied->OperateDoors(Train->cab_to_end() == end::front ? side::left : side::right, true); + Train->mvOccupied->OperateDoors(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right, true); // visual feedback if (Train->ggDoorLeftOnButton.SubModel != nullptr) { @@ -339,7 +339,7 @@ void TTrain::OnCommand_doorcloseleft(TTrain *Train, command_data const &Command) else { // TODO: move door opening/closing to the update, so the switch animation doesn't hinge on door working - Train->mvOccupied->OperateDoors(Train->cab_to_end() == end::front ? side::left : side::right, false); + Train->mvOccupied->OperateDoors(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right, false); } // visual feedback if (Train->ggDoorLeftOffButton.SubModel != nullptr) @@ -361,7 +361,7 @@ void TTrain::OnCommand_doorcloseleft(TTrain *Train, command_data const &Command) // automatic departure signal delays actual door closing until the button is released Train->mvOccupied->signal_departure(false); // now we can actually close the door - Train->mvOccupied->OperateDoors(Train->cab_to_end() == end::front ? side::left : side::right, false); + Train->mvOccupied->OperateDoors(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right, false); } // visual feedback // dedicated closing buttons are presumed to be impulse switches and return automatically to neutral position @@ -463,7 +463,7 @@ void TTrain::OnCommand_dooropenright(TTrain *Train, command_data const &Command) if (Command.action == GLFW_PRESS) { - Train->mvOccupied->OperateDoors(Train->cab_to_end() == end::front ? side::right : side::left, true); + Train->mvOccupied->OperateDoors(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left, true); // visual feedback if (Train->ggDoorRightOnButton.SubModel != nullptr) { @@ -512,7 +512,7 @@ void TTrain::OnCommand_doorcloseright(TTrain *Train, command_data const &Command } else { - Train->mvOccupied->OperateDoors(Train->cab_to_end() == end::front ? side::right : side::left, false); + Train->mvOccupied->OperateDoors(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left, false); } // visual feedback if (Train->ggDoorRightOffButton.SubModel != nullptr) @@ -534,7 +534,7 @@ void TTrain::OnCommand_doorcloseright(TTrain *Train, command_data const &Command // automatic departure signal delays actual door closing until the button is released Train->mvOccupied->signal_departure(false); // now we can actually close the door - Train->mvOccupied->OperateDoors(Train->cab_to_end() == end::front ? side::right : side::left, false); + Train->mvOccupied->OperateDoors(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left, false); } // visual feedback // dedicated closing buttons are presumed to be impulse switches and return automatically to neutral position @@ -565,8 +565,8 @@ void TTrain::OnCommand_dooropenall(TTrain *Train, command_data const &Command) if (Command.action == GLFW_PRESS) { - Train->mvOccupied->OperateDoors(side::right, true); - Train->mvOccupied->OperateDoors(side::left, true); + Train->mvOccupied->OperateDoors(VehicleSide::right, true); + Train->mvOccupied->OperateDoors(VehicleSide::left, true); // visual feedback Train->ggDoorAllOnButton.UpdateValue(1.0, Train->dsbSwitch); } @@ -606,8 +606,8 @@ void TTrain::OnCommand_doorcloseall(TTrain *Train, command_data const &Command) if (Train->ggDoorAllOffButton.type() != TGaugeType::push_delayed) { // delays the action until the button is released - Train->mvOccupied->OperateDoors(side::right, false); - Train->mvOccupied->OperateDoors(side::left, false); + Train->mvOccupied->OperateDoors(VehicleSide::right, false); + Train->mvOccupied->OperateDoors(VehicleSide::left, false); } // visual feedback Train->ggDoorLeftButton.UpdateValue(0.0, Train->dsbSwitch); @@ -624,8 +624,8 @@ void TTrain::OnCommand_doorcloseall(TTrain *Train, command_data const &Command) if (Train->ggDoorAllOffButton.type() == TGaugeType::push_delayed) { // now we can actually close the door - Train->mvOccupied->OperateDoors(side::right, false); - Train->mvOccupied->OperateDoors(side::left, false); + Train->mvOccupied->OperateDoors(VehicleSide::right, false); + Train->mvOccupied->OperateDoors(VehicleSide::left, false); } // visual feedback if (Train->ggDoorAllOffButton.SubModel) diff --git a/vehicle/cab/equipmentcommands.cpp b/vehicle/cab/equipmentcommands.cpp index 38c90754d..fc0128325 100644 --- a/vehicle/cab/equipmentcommands.cpp +++ b/vehicle/cab/equipmentcommands.cpp @@ -414,7 +414,7 @@ void TTrain::OnCommand_inverterenable(TTrain *Train, command_data const &Command // only reacting to press, so the switch doesn't flip back and forth if key is held down bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; auto const flag{CouplingSet::FromBits(Train->DynamicObject->MoverParameters->inductionMotor.inverterControlCouplings)}; - TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); + TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, flag); while (p) { if (p->MoverParameters->inductionMotor.traction.maxPower > 1) @@ -453,7 +453,7 @@ void TTrain::OnCommand_inverterdisable(TTrain *Train, command_data const &Comman // only reacting to press, so the switch doesn't flip back and forth if key is held down bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; auto const flag{CouplingSet::FromBits(Train->DynamicObject->MoverParameters->inductionMotor.inverterControlCouplings)}; - TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); + TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, flag); while (p) { if (p->MoverParameters->inductionMotor.traction.maxPower > 1) @@ -492,7 +492,7 @@ void TTrain::OnCommand_invertertoggle(TTrain *Train, command_data const &Command // only reacting to press, so the switch doesn't flip back and forth if key is held down bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; auto const flag{CouplingSet::FromBits(Train->DynamicObject->MoverParameters->inductionMotor.inverterControlCouplings)}; - TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); + TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, flag); while (p) { if (p->MoverParameters->inductionMotor.traction.maxPower > 1) diff --git a/vehicle/cab/lightcommands.cpp b/vehicle/cab/lightcommands.cpp index 2c13201cd..5089e3f85 100644 --- a/vehicle/cab/lightcommands.cpp +++ b/vehicle/cab/lightcommands.cpp @@ -203,8 +203,8 @@ void TTrain::OnCommand_headlighttoggleleft(TTrain *Train, command_data const &Co void TTrain::OnCommand_lightsset(TTrain *Train, command_data const &Command) { // set custom item in Lights inventory - Train->mvOccupied->Lights[end::front][17] = static_cast(Command.param1); - Train->mvOccupied->Lights[end::rear][17] = static_cast(Command.param2); + Train->mvOccupied->Lights[VehicleEnd::front][17] = static_cast(Command.param1); + Train->mvOccupied->Lights[VehicleEnd::rear][17] = static_cast(Command.param2); Train->mvOccupied->LightsPos = 18; // nasza custom pozycja Train->Dynamic()->SetLights(); } @@ -249,7 +249,7 @@ void TTrain::OnCommand_headlightdisableleft(TTrain *Train, command_data const &C if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - int const vehicleend{Train->cab_to_end()}; + auto const vehicleend{Train->cab_to_end()}; if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0) { @@ -623,7 +623,7 @@ void TTrain::OnCommand_headlighttogglerearleft(TTrain *Train, command_data const if (Command.action == GLFW_PRESS) { // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; // only reacting to press, so the switch doesn't flip back and forth if key is held down if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_right) == 0) { @@ -646,7 +646,7 @@ void TTrain::OnCommand_headlightenablerearleft(TTrain *Train, command_data const if (Command.action == GLFW_PRESS) { - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; // already enabled if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_right) == 0) { @@ -667,7 +667,7 @@ void TTrain::OnCommand_headlightdisablerearleft(TTrain *Train, command_data cons } if (Command.action == GLFW_PRESS) { - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; // already disabled if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_right) == 0) { @@ -686,7 +686,7 @@ void TTrain::OnCommand_headlighttogglerearright(TTrain *Train, command_data cons if (Command.action == GLFW_PRESS) { // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; // only reacting to press, so the switch doesn't flip back and forth if key is held down if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_left) == 0) { @@ -710,7 +710,7 @@ void TTrain::OnCommand_headlightenablerearright(TTrain *Train, command_data cons if (Command.action == GLFW_PRESS) { // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_left) == 0) { @@ -733,7 +733,7 @@ void TTrain::OnCommand_headlightdisablerearright(TTrain *Train, command_data con if (Command.action == GLFW_PRESS) { // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; // already disabled if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_left) == 0) { @@ -759,7 +759,7 @@ void TTrain::OnCommand_headlighttogglerearupper(TTrain *Train, command_data cons if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_upper) == 0) { OnCommand_headlightenablerearupper(Train, Command); @@ -783,7 +783,7 @@ void TTrain::OnCommand_headlightenablerearupper(TTrain *Train, command_data cons if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_upper) == 0) { // turn on @@ -806,7 +806,7 @@ void TTrain::OnCommand_headlightdisablerearupper(TTrain *Train, command_data con if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; // already disabled? if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_upper) == 0) { @@ -863,7 +863,7 @@ void TTrain::OnCommand_redmarkertogglerearleft(TTrain *Train, command_data const if (Command.action == GLFW_PRESS) { // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; // only reacting to press, so the switch doesn't flip back and forth if key is held down if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_right) == 0) { @@ -888,7 +888,7 @@ void TTrain::OnCommand_redmarkerenablerearleft(TTrain *Train, command_data const if (Command.action == GLFW_PRESS) { // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_right) == 0) { // turn on @@ -911,7 +911,7 @@ void TTrain::OnCommand_redmarkerdisablerearleft(TTrain *Train, command_data cons if (Command.action == GLFW_PRESS) { // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_right) == 0) { return; @@ -935,7 +935,7 @@ void TTrain::OnCommand_redmarkertogglerearright(TTrain *Train, command_data cons if (Command.action == GLFW_PRESS) { // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; // only reacting to press, so the switch doesn't flip back and forth if key is held down if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_left) == 0) { @@ -960,7 +960,7 @@ void TTrain::OnCommand_redmarkerenablerearright(TTrain *Train, command_data cons if (Command.action == GLFW_PRESS) { // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_left) == 0) { // turn on @@ -983,7 +983,7 @@ void TTrain::OnCommand_redmarkerdisablerearright(TTrain *Train, command_data con if (Command.action == GLFW_PRESS) { // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_left) == 0) { return; diff --git a/vehicle/cab/pantographcommands.cpp b/vehicle/cab/pantographcommands.cpp index 7c96a8b3e..2bf0f0d46 100644 --- a/vehicle/cab/pantographcommands.cpp +++ b/vehicle/cab/pantographcommands.cpp @@ -59,7 +59,7 @@ void TTrain::OnCommand_pantographtogglefront(TTrain *Train, command_data const & if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const &pantograph{Train->mvPantographUnit->Pantographs[end::front]}; + auto const &pantograph{Train->mvPantographUnit->Pantographs[VehicleEnd::front]}; auto const state{pantograph.valve.is_enabled || pantograph.is_active}; // fallback for impulse switches if (state) { @@ -76,7 +76,7 @@ void TTrain::OnCommand_pantographtogglefront(TTrain *Train, command_data const & if (Train->mvOccupied->PantSwitchType == "impulse") { auto const ismanual{Train->iCabn == 0}; - Train->mvOccupied->OperatePantographValve(end::front, operation_t::none, ismanual ? range_t::local : range_t::consist); + Train->mvOccupied->OperatePantographValve(VehicleEnd::front, operation_t::none, ismanual ? range_t::local : range_t::consist); } } } @@ -93,7 +93,7 @@ void TTrain::OnCommand_pantographtogglerear(TTrain *Train, command_data const &C if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const &pantograph{Train->mvPantographUnit->Pantographs[end::rear]}; + auto const &pantograph{Train->mvPantographUnit->Pantographs[VehicleEnd::rear]}; auto const state{pantograph.valve.is_enabled || pantograph.is_active}; // fallback for impulse switches if (state) { @@ -110,7 +110,7 @@ void TTrain::OnCommand_pantographtogglerear(TTrain *Train, command_data const &C if (Train->mvOccupied->PantSwitchType == "impulse") { auto const ismanual{Train->iCabn == 0}; - Train->mvOccupied->OperatePantographValve(end::rear, operation_t::none, ismanual ? range_t::local : range_t::consist); + Train->mvOccupied->OperatePantographValve(VehicleEnd::rear, operation_t::none, ismanual ? range_t::local : range_t::consist); } } } @@ -134,7 +134,7 @@ void TTrain::OnCommand_pantographraisefront(TTrain *Train, command_data const &C // only reacting to press, so the switch doesn't flip back and forth if key is held down // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers auto const ismanual{Train->iCabn == 0}; - Train->mvOccupied->OperatePantographValve(end::front, Train->mvOccupied->PantSwitchType == "impulse" ? operation_t::enable_on : operation_t::enable, + Train->mvOccupied->OperatePantographValve(VehicleEnd::front, Train->mvOccupied->PantSwitchType == "impulse" ? operation_t::enable_on : operation_t::enable, ismanual ? range_t::local : range_t::consist); } else if (Command.action == GLFW_RELEASE) @@ -163,7 +163,7 @@ void TTrain::OnCommand_pantographraiserear(TTrain *Train, command_data const &Co // only reacting to press, so the switch doesn't flip back and forth if key is held down // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers auto const ismanual{Train->iCabn == 0}; - Train->mvOccupied->OperatePantographValve(end::rear, Train->mvOccupied->PantSwitchType == "impulse" ? operation_t::enable_on : operation_t::enable, + Train->mvOccupied->OperatePantographValve(VehicleEnd::rear, Train->mvOccupied->PantSwitchType == "impulse" ? operation_t::enable_on : operation_t::enable, ismanual ? range_t::local : range_t::consist); } else if (Command.action == GLFW_RELEASE) @@ -192,7 +192,7 @@ void TTrain::OnCommand_pantographlowerfront(TTrain *Train, command_data const &C // only reacting to press, so the switch doesn't flip back and forth if key is held down // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers auto const ismanual{Train->iCabn == 0}; - Train->mvOccupied->OperatePantographValve(end::front, Train->mvOccupied->PantSwitchType == "impulse" ? operation_t::disable_on : operation_t::disable, + Train->mvOccupied->OperatePantographValve(VehicleEnd::front, Train->mvOccupied->PantSwitchType == "impulse" ? operation_t::disable_on : operation_t::disable, ismanual ? range_t::local : range_t::consist); } else if (Command.action == GLFW_RELEASE) @@ -221,7 +221,7 @@ void TTrain::OnCommand_pantographlowerrear(TTrain *Train, command_data const &Co // only reacting to press, so the switch doesn't flip back and forth if key is held down // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers auto const ismanual{Train->iCabn == 0}; - Train->mvOccupied->OperatePantographValve(end::rear, Train->mvOccupied->PantSwitchType == "impulse" ? operation_t::disable_on : operation_t::disable, + Train->mvOccupied->OperatePantographValve(VehicleEnd::rear, Train->mvOccupied->PantSwitchType == "impulse" ? operation_t::disable_on : operation_t::disable, ismanual ? range_t::local : range_t::consist); } else if (Command.action == GLFW_RELEASE) @@ -419,12 +419,12 @@ void TTrain::update_pantograph_valves() auto const &selection{mvOccupied->PantsPreset.second[cab_to_end()]}; auto const preset{presets[selection] - '0'}; - auto const swapends{cab_to_end() != end::front}; + auto const swapends{cab_to_end() != VehicleEnd::front}; // check desired states for both pantographs; value: whether the pantograph should be raised auto const frontstate{preset & (swapends ? 2 : 1)}; auto const rearstate{preset & (swapends ? 1 : 2)}; - mvOccupied->OperatePantographValve(end::front, frontstate ? enable : disable); - mvOccupied->OperatePantographValve(end::rear, rearstate ? enable : disable); + mvOccupied->OperatePantographValve(VehicleEnd::front, frontstate ? enable : disable); + mvOccupied->OperatePantographValve(VehicleEnd::rear, rearstate ? enable : disable); } void TTrain::change_pantograph_selection(int const Change) @@ -500,8 +500,8 @@ void TTrain::OnCommand_pantographvalvesoff(TTrain *Train, command_data const &Co if (Command.action == GLFW_PRESS) { // implement action - Train->mvOccupied->OperatePantographValve(end::front, operation_t::disable); - Train->mvOccupied->OperatePantographValve(end::rear, operation_t::disable); + Train->mvOccupied->OperatePantographValve(VehicleEnd::front, operation_t::disable); + Train->mvOccupied->OperatePantographValve(VehicleEnd::rear, operation_t::disable); // visual feedback if (hasSeparateSwitches) Train->ggPantValvesOff.UpdateValue(1.0, Train->dsbSwitch); diff --git a/vehicle/cab/setup.cpp b/vehicle/cab/setup.cpp index 3af70a82e..d1bac2763 100644 --- a/vehicle/cab/setup.cpp +++ b/vehicle/cab/setup.cpp @@ -938,13 +938,13 @@ void TTrain::set_cab_controls(int const Cab) if( mvOccupied->PantSwitchType != "impulse" ) { if( ggPantFrontButton.SubModel ) { ggPantFrontButton.PutValue( - ( mvControlled->Pantographs[end::front].valve.is_enabled ? + ( mvControlled->Pantographs[VehicleEnd::front].valve.is_enabled ? 1.f : 0.f ) ); } if( ggPantFrontButtonOff.SubModel ) { ggPantFrontButtonOff.PutValue( - ( mvControlled->Pantographs[end::front].valve.is_disabled ? + ( mvControlled->Pantographs[VehicleEnd::front].valve.is_disabled ? 1.f : 0.f ) ); } @@ -952,13 +952,13 @@ void TTrain::set_cab_controls(int const Cab) if( mvOccupied->PantSwitchType != "impulse" ) { if( ggPantRearButton.SubModel ) { ggPantRearButton.PutValue( - ( mvControlled->Pantographs[end::rear].valve.is_enabled ? + ( mvControlled->Pantographs[VehicleEnd::rear].valve.is_enabled ? 1.f : 0.f ) ); } if( ggPantRearButtonOff.SubModel ) { ggPantRearButtonOff.PutValue( - ( mvControlled->Pantographs[end::rear].valve.is_disabled ? + ( mvControlled->Pantographs[VehicleEnd::rear].valve.is_disabled ? 1.f : 0.f ) ); } @@ -1059,16 +1059,16 @@ void TTrain::set_cab_controls(int const Cab) // doors permits if (false == ggDoorLeftPermitButton.is_push()) { - ggDoorLeftPermitButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == end::front ? side::left : side::right].open_permit ? 1.f : 0.f); + ggDoorLeftPermitButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right].open_permit ? 1.f : 0.f); } if (false == ggDoorRightPermitButton.is_push()) { - ggDoorRightPermitButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == end::front ? side::right : side::left].open_permit ? 1.f : 0.f); + ggDoorRightPermitButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left].open_permit ? 1.f : 0.f); } ggDoorPermitPresetButton.PutValue(static_cast(mvOccupied->Doors.permit_preset)); // door controls - ggDoorLeftButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == end::front ? side::left : side::right].is_closed ? 0.f : 1.f); - ggDoorRightButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == end::front ? side::right : side::left].is_closed ? 0.f : 1.f); + ggDoorLeftButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right].is_closed ? 0.f : 1.f); + ggDoorRightButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left].is_closed ? 0.f : 1.f); // door lock ggDoorSignallingButton.PutValue(mvOccupied->Doors.lock_enabled ? 1.f : 0.f); // door step @@ -1144,15 +1144,15 @@ void TTrain::set_cab_controls(int const Cab) // traction motor fans if (ggMotorBlowersFrontButton.type() != TGaugeType::push) { - ggMotorBlowersFrontButton.PutValue(mvControlled->MotorBlowers[end::front].is_enabled ? 1.f : 0.f); + ggMotorBlowersFrontButton.PutValue(mvControlled->MotorBlowers[VehicleEnd::front].is_enabled ? 1.f : 0.f); } if (ggMotorBlowersRearButton.type() != TGaugeType::push) { - ggMotorBlowersRearButton.PutValue(mvControlled->MotorBlowers[end::rear].is_enabled ? 1.f : 0.f); + ggMotorBlowersRearButton.PutValue(mvControlled->MotorBlowers[VehicleEnd::rear].is_enabled ? 1.f : 0.f); } if (ggMotorBlowersAllOffButton.type() != TGaugeType::push) { - ggMotorBlowersAllOffButton.PutValue(mvControlled->MotorBlowers[end::front].is_disabled || mvControlled->MotorBlowers[end::rear].is_disabled ? 1.f : 0.f); + ggMotorBlowersAllOffButton.PutValue(mvControlled->MotorBlowers[VehicleEnd::front].is_disabled || mvControlled->MotorBlowers[VehicleEnd::rear].is_disabled ? 1.f : 0.f); } // second controller if (ggScndCtrl.is_push()) @@ -1181,7 +1181,7 @@ void TTrain::set_cab_controls(int const Cab) { int itemindex = itemstart; itemstart++; - TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); + TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, flag); while (p) { if (p->MoverParameters->inductionMotor.traction.maxPower > 1) @@ -1652,10 +1652,10 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con std::unordered_map const autoboolgauges = { {"doormode_sw:", &mvOccupied->Doors.remote_only}, {"coolingfans_sw:", &mvControlled->RVentForceOn}, - {"pantfront_sw:", &mvPantographUnit->Pantographs[end::front].valve.is_enabled}, - {"pantrear_sw:", &mvPantographUnit->Pantographs[end::rear].valve.is_enabled}, - {"pantfrontoff_sw:", &mvPantographUnit->Pantographs[end::front].valve.is_disabled}, - {"pantrearoff_sw:", &mvPantographUnit->Pantographs[end::rear].valve.is_disabled}, + {"pantfront_sw:", &mvPantographUnit->Pantographs[VehicleEnd::front].valve.is_enabled}, + {"pantrear_sw:", &mvPantographUnit->Pantographs[VehicleEnd::rear].valve.is_enabled}, + {"pantfrontoff_sw:", &mvPantographUnit->Pantographs[VehicleEnd::front].valve.is_disabled}, + {"pantrearoff_sw:", &mvPantographUnit->Pantographs[VehicleEnd::rear].valve.is_disabled}, {"radio_sw:", &mvOccupied->Radio}, {"radiofuse_sw:", &mvOccupied->RadioFuse}, {"cablight_sw:", &Cabine[iCabn].bLight}, diff --git a/vehicle/cab/train.cpp b/vehicle/cab/train.cpp index 9920635bb..757be2871 100644 --- a/vehicle/cab/train.cpp +++ b/vehicle/cab/train.cpp @@ -181,29 +181,29 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("converter_overload", mvControlled->ConvOvldFlag); dict->insert("compress", mvControlled->CompressorFlag); dict->insert("pant_compressor", mvPantographUnit->PantCompFlag); - dict->insert("lights_front", mvOccupied->iLights[end::front]); - dict->insert("lights_rear", mvOccupied->iLights[end::rear]); + dict->insert("lights_front", mvOccupied->iLights[VehicleEnd::front]); + dict->insert("lights_rear", mvOccupied->iLights[VehicleEnd::rear]); dict->insert("off_from_dimmer", mvOccupied->currentDimPosition().isOff); dict->insert("lights_compartments", mvOccupied->CompartmentLights.is_active || mvOccupied->CompartmentLights.is_disabled); if (Dynamic()->Mechanik) { auto const *controller{Dynamic()->Mechanik}; - auto const cabmodifier{cab_to_end() == end::front ? 1 : -1}; + auto const cabmodifier{cab_to_end() == VehicleEnd::front ? 1 : -1}; auto const traindirection{controller->Direction() * cabmodifier}; - auto const *frontvehicle{controller->Vehicle(traindirection >= 0 ? end::front : end::rear)}; - auto const *rearvehicle{controller->Vehicle(traindirection >= 0 ? end::rear : end::front)}; + auto const *frontvehicle{controller->Vehicle(traindirection >= 0 ? VehicleEnd::front : VehicleEnd::rear)}; + auto const *rearvehicle{controller->Vehicle(traindirection >= 0 ? VehicleEnd::rear : VehicleEnd::front)}; auto const frontvehicledirection{(frontvehicle->DirectionGet() == controller->Vehicle()->DirectionGet() ? 1 : -1)}; auto const rearvehicledirection{(rearvehicle->DirectionGet() == controller->Vehicle()->DirectionGet() ? 1 : -1)}; - auto const fronttrainlights{frontvehicle->MoverParameters->iLights[frontvehicledirection * cabmodifier >= 0 ? end::front : end::rear]}; - auto const reartrainlights{rearvehicle->MoverParameters->iLights[rearvehicledirection * cabmodifier >= 0 ? end::rear : end::front]}; + auto const fronttrainlights{frontvehicle->MoverParameters->iLights[frontvehicledirection * cabmodifier >= 0 ? VehicleEnd::front : VehicleEnd::rear]}; + auto const reartrainlights{rearvehicle->MoverParameters->iLights[rearvehicledirection * cabmodifier >= 0 ? VehicleEnd::rear : VehicleEnd::front]}; dict->insert("lights_train_front", fronttrainlights); dict->insert("lights_train_rear", reartrainlights); } else { // fallback, in the unlikely case we lose the controller - dict->insert("lights_train_front", mvOccupied->iLights[end::front]); - dict->insert("lights_train_rear", mvOccupied->iLights[end::rear]); + dict->insert("lights_train_front", mvOccupied->iLights[VehicleEnd::front]); + dict->insert("lights_train_rear", mvOccupied->iLights[VehicleEnd::rear]); } // reverser dict->insert("direction", mvOccupied->DirActive); @@ -257,8 +257,8 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("radio_volume", m_radiovolume); dict->insert("door_lock", mvOccupied->Doors.lock_enabled); dict->insert("door_step", mvOccupied->Doors.step_enabled); - dict->insert("door_permit_left", mvOccupied->Doors.instances[side::left].open_permit); - dict->insert("door_permit_right", mvOccupied->Doors.instances[side::right].open_permit); + dict->insert("door_permit_left", mvOccupied->Doors.instances[VehicleSide::left].open_permit); + dict->insert("door_permit_right", mvOccupied->Doors.instances[VehicleSide::right].open_permit); // movement data dict->insert("velocity", std::abs(mvOccupied->Vel)); dict->insert("tractionforce", std::abs(mvOccupied->Ft)); @@ -315,7 +315,7 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const } bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; - TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? end::rear : end::front, Coupling::control); + TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); int in = 0; while (p && in < 8) { @@ -424,10 +424,10 @@ TTrain::state_t TTrain::get_state() const btLampkaNapNastHam.GetValue(), mvOccupied->DirActive > 0, mvOccupied->DirActive < 0, - mvOccupied->Doors.instances[mvOccupied->CabOccupied < 0 ? side::right : side::left].open_permit, - mvOccupied->Doors.instances[mvOccupied->CabOccupied < 0 ? side::right : side::left].is_open, - mvOccupied->Doors.instances[mvOccupied->CabOccupied < 0 ? side::left : side::right].open_permit, - mvOccupied->Doors.instances[mvOccupied->CabOccupied < 0 ? side::left : side::right].is_open, + mvOccupied->Doors.instances[mvOccupied->CabOccupied < 0 ? VehicleSide::right : VehicleSide::left].open_permit, + mvOccupied->Doors.instances[mvOccupied->CabOccupied < 0 ? VehicleSide::right : VehicleSide::left].is_open, + mvOccupied->Doors.instances[mvOccupied->CabOccupied < 0 ? VehicleSide::left : VehicleSide::right].open_permit, + mvOccupied->Doors.instances[mvOccupied->CabOccupied < 0 ? VehicleSide::left : VehicleSide::right].is_open, mvOccupied->Doors.step_enabled, mvOccupied->Power24vIsAvailable, 0, @@ -519,13 +519,13 @@ void TTrain::set_paired_open_motor_connectors_button(bool const State) { // crude implementation of the button affecting entire unit for multi-unit engines // TODO: rework it into part of standard command propagation system - if (mvControlled->Couplers[end::front].Connected != nullptr && true == mvControlled->Couplers[end::front].CouplingFlag.HasAll(Coupling::permanent)) + if (mvControlled->Couplers[VehicleEnd::front].Connected != nullptr && true == mvControlled->Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::permanent)) { - mvControlled->Couplers[end::front].Connected->StLinSwitchOff = State; + mvControlled->Couplers[VehicleEnd::front].Connected->StLinSwitchOff = State; } - if (mvControlled->Couplers[end::rear].Connected != nullptr && true == mvControlled->Couplers[end::rear].CouplingFlag.HasAll(Coupling::permanent)) + if (mvControlled->Couplers[VehicleEnd::rear].Connected != nullptr && true == mvControlled->Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::permanent)) { - mvControlled->Couplers[end::rear].Connected->StLinSwitchOff = State; + mvControlled->Couplers[VehicleEnd::rear].Connected->StLinSwitchOff = State; } } } diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index 1639801b5..23441daa4 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -123,7 +123,7 @@ bool TTrain::Update(double const Deltatime) doorpermittimer -= static_cast(Deltatime); if (doorpermittimer < 0.f) { - mvOccupied->OperateDoors(static_cast(idx), true); + mvOccupied->OperateDoors(static_cast(idx), true); } } @@ -146,16 +146,16 @@ bool TTrain::Update(double const Deltatime) // helper variables if (DynamicObject->Mechanik != nullptr) { - m_doors = DynamicObject->Mechanik->IsAnyDoorOpen[side::right] || DynamicObject->Mechanik->IsAnyDoorOpen[side::left]; - m_doorpermits = DynamicObject->Mechanik->IsAnyDoorPermitActive[side::right] || DynamicObject->Mechanik->IsAnyDoorPermitActive[side::left]; - m_doorspermitleft = mvOccupied->Doors.instances[cab_to_end() == end::front ? side::left : side::right].open_permit && + m_doors = DynamicObject->Mechanik->IsAnyDoorOpen[VehicleSide::right] || DynamicObject->Mechanik->IsAnyDoorOpen[VehicleSide::left]; + m_doorpermits = DynamicObject->Mechanik->IsAnyDoorPermitActive[VehicleSide::right] || DynamicObject->Mechanik->IsAnyDoorPermitActive[VehicleSide::left]; + m_doorspermitleft = mvOccupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right].open_permit && (simulation::Time.data().wSecond % 2 < 1 || mvOccupied->DoorsPermitLightBlinking < 1 || - mvOccupied->DoorsPermitLightBlinking < 2 && DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == end::front ? side::left : side::right] || - (mvOccupied->DoorsPermitLightBlinking < 3 && DynamicObject->Mechanik->IsAnyDoorOnlyOpen[cab_to_end() == end::front ? side::left : side::right])); - m_doorspermitright = mvOccupied->Doors.instances[cab_to_end() == end::front ? side::right : side::left].open_permit && + mvOccupied->DoorsPermitLightBlinking < 2 && DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right] || + (mvOccupied->DoorsPermitLightBlinking < 3 && DynamicObject->Mechanik->IsAnyDoorOnlyOpen[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right])); + m_doorspermitright = mvOccupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left].open_permit && (simulation::Time.data().wSecond % 2 < 1 || mvOccupied->DoorsPermitLightBlinking < 1 || - mvOccupied->DoorsPermitLightBlinking < 2 && DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == end::front ? side::right : side::left] || - (mvOccupied->DoorsPermitLightBlinking < 3 && DynamicObject->Mechanik->IsAnyDoorOnlyOpen[cab_to_end() == end::front ? side::right : side::left])); + mvOccupied->DoorsPermitLightBlinking < 2 && DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left] || + (mvOccupied->DoorsPermitLightBlinking < 3 && DynamicObject->Mechanik->IsAnyDoorOnlyOpen[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left])); } m_dirforward = mvControlled->DirActive > 0; m_dirneutral = mvControlled->DirActive == 0; @@ -285,7 +285,7 @@ bool TTrain::Update(double const Deltatime) } bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; - TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? end::rear : end::front, Coupling::control); + TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); int in = 0; fEIMParams[0][6] = 0; iCarNo = 0; @@ -321,10 +321,10 @@ bool TTrain::Update(double const Deltatime) fPress[i][6] = static_cast(p->MoverParameters->SpringBrake.SBP); bBrakes[i][0] = p->MoverParameters->SpringBrake.IsActive; bBrakes[i][1] = p->MoverParameters->SpringBrake.ShuttOff; - bDoors[i][1] = p->MoverParameters->Doors.instances[side::left].position > 0.f; - bDoors[i][2] = p->MoverParameters->Doors.instances[side::right].position > 0.f; - bDoors[i][3] = p->MoverParameters->Doors.instances[side::left].step_position > 0.f; - bDoors[i][4] = p->MoverParameters->Doors.instances[side::right].step_position > 0.f; + bDoors[i][1] = p->MoverParameters->Doors.instances[VehicleSide::left].position > 0.f; + bDoors[i][2] = p->MoverParameters->Doors.instances[VehicleSide::right].position > 0.f; + bDoors[i][3] = p->MoverParameters->Doors.instances[VehicleSide::left].step_position > 0.f; + bDoors[i][4] = p->MoverParameters->Doors.instances[VehicleSide::right].step_position > 0.f; bDoors[i][0] = bDoors[i][1] || bDoors[i][2]; iDoorNo[i] = p->iAnimType[ANIM_DOORS]; iUnits[i] = iUnitNo; @@ -332,8 +332,8 @@ bool TTrain::Update(double const Deltatime) asCarName[i] = p->name(); if (p->MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) { - bPants[iUnitNo - 1][end::front] = bPants[iUnitNo - 1][end::front] || p->MoverParameters->Pantographs[end::front].is_active; - bPants[iUnitNo - 1][end::rear] = bPants[iUnitNo - 1][end::rear] || p->MoverParameters->Pantographs[end::rear].is_active; + bPants[iUnitNo - 1][VehicleEnd::front] = bPants[iUnitNo - 1][VehicleEnd::front] || p->MoverParameters->Pantographs[VehicleEnd::front].is_active; + bPants[iUnitNo - 1][VehicleEnd::rear] = bPants[iUnitNo - 1][VehicleEnd::rear] || p->MoverParameters->Pantographs[VehicleEnd::rear].is_active; } // TBD, TODO: clean up compressor data arrangement? if (iUnitNo <= 8) @@ -495,9 +495,9 @@ bool TTrain::Update(double const Deltatime) // youBy - prad w drugim czlonie: galaz lub calosc { TDynamicObject const *tmp{nullptr}; - if (DynamicObject->NextConnected() && mvControlled->Couplers[end::rear].CouplingFlag.HasAll(Coupling::control) && mvOccupied->CabOccupied == 1) + if (DynamicObject->NextConnected() && mvControlled->Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::control) && mvOccupied->CabOccupied == 1) tmp = DynamicObject->NextConnected(); - if (DynamicObject->PrevConnected() && mvControlled->Couplers[end::front].CouplingFlag.HasAll(Coupling::control) && mvOccupied->CabOccupied == -1) + if (DynamicObject->PrevConnected() && mvControlled->Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::control) && mvOccupied->CabOccupied == -1) tmp = DynamicObject->PrevConnected(); if (tmp && tmp->MoverParameters->Power > 0) { @@ -697,7 +697,7 @@ bool TTrain::Update(double const Deltatime) btLampkaStyczn.Turn(mvControlled->LineContactorsLampLit()); // mozna prowadzic rozruch btLampkaPrzekRozn.Turn(!mvControlled->GroundRelay && mvControlled->MainCircuitLampsEnabled()); // relay is off and needs a reset btLampkaNadmSil.Turn(mvControlled->FuseFlagCheck() && mvControlled->MainCircuitLampsEnabled()); // relay is off and needs a reset - btLampkaUkrotnienie.Turn(mvControlled->Couplers[mvControlled->CabOccupied == 1 ? rear : front].CouplingFlag.HasAll(Coupling::control)); + btLampkaUkrotnienie.Turn(mvControlled->Couplers[mvControlled->CabOccupied == 1 ? VehicleEnd::rear : VehicleEnd::front].CouplingFlag.HasAll(Coupling::control)); btLampkaHamPosp.Turn(TestFlag(mvOccupied->Hamulec->GetBrakeStatus(), 1)); // lampka drugiego stopnia hamowania // TODO: youBy wyciągnąć flagę wysokiego stopnia btLampkaNadmWent.Turn(mvControlled->RventRot < 5.0 && mvControlled->ResistorsFlagCheck()); // hunter-121211: lampka zanikowo-pradowego wentylatorow @@ -776,8 +776,8 @@ bool TTrain::Update(double const Deltatime) // NBMX wrzesien 2003 - drzwi oraz sygnał odjazdu if (DynamicObject->Mechanik != nullptr) { - btLampkaDoorLeft.Turn(DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == end::front ? side::left : side::right]); - btLampkaDoorRight.Turn(DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == end::front ? side::right : side::left]); + btLampkaDoorLeft.Turn(DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right]); + btLampkaDoorRight.Turn(DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left]); } if (DynamicObject->Mechanik != nullptr) { @@ -818,16 +818,16 @@ bool TTrain::Update(double const Deltatime) btLampkaSpringBrakeInactive.Turn(!mvOccupied->SpringBrake.IsActive); // light indicators // NOTE: sides are hardcoded to deal with setups where single cab is equipped with all indicators - btLampkaUpperLight.Turn((mvOccupied->iLights[end::front] & light::headlight_upper) != 0); - btLampkaLeftLight.Turn((mvOccupied->iLights[end::front] & light::headlight_left) != 0); - btLampkaRightLight.Turn((mvOccupied->iLights[end::front] & light::headlight_right) != 0); - btLampkaLeftEndLight.Turn((mvOccupied->iLights[end::front] & light::redmarker_left) != 0); - btLampkaRightEndLight.Turn((mvOccupied->iLights[end::front] & light::redmarker_right) != 0); - btLampkaRearUpperLight.Turn((mvOccupied->iLights[end::rear] & light::headlight_upper) != 0); - btLampkaRearLeftLight.Turn((mvOccupied->iLights[end::rear] & light::headlight_left) != 0); - btLampkaRearRightLight.Turn((mvOccupied->iLights[end::rear] & light::headlight_right) != 0); - btLampkaRearLeftEndLight.Turn((mvOccupied->iLights[end::rear] & light::redmarker_left) != 0); - btLampkaRearRightEndLight.Turn((mvOccupied->iLights[end::rear] & light::redmarker_right) != 0); + btLampkaUpperLight.Turn((mvOccupied->iLights[VehicleEnd::front] & light::headlight_upper) != 0); + btLampkaLeftLight.Turn((mvOccupied->iLights[VehicleEnd::front] & light::headlight_left) != 0); + btLampkaRightLight.Turn((mvOccupied->iLights[VehicleEnd::front] & light::headlight_right) != 0); + btLampkaLeftEndLight.Turn((mvOccupied->iLights[VehicleEnd::front] & light::redmarker_left) != 0); + btLampkaRightEndLight.Turn((mvOccupied->iLights[VehicleEnd::front] & light::redmarker_right) != 0); + btLampkaRearUpperLight.Turn((mvOccupied->iLights[VehicleEnd::rear] & light::headlight_upper) != 0); + btLampkaRearLeftLight.Turn((mvOccupied->iLights[VehicleEnd::rear] & light::headlight_left) != 0); + btLampkaRearRightLight.Turn((mvOccupied->iLights[VehicleEnd::rear] & light::headlight_right) != 0); + btLampkaRearLeftEndLight.Turn((mvOccupied->iLights[VehicleEnd::rear] & light::redmarker_left) != 0); + btLampkaRearRightEndLight.Turn((mvOccupied->iLights[VehicleEnd::rear] & light::redmarker_right) != 0); // others btLampkaMalfunction.Turn(mvControlled->diesel.heat.PA); // overheat indicator lamps @@ -835,7 +835,7 @@ bool TTrain::Update(double const Deltatime) btLampkaWaterOverheat.Turn(mvControlled->diesel.heat.water.is_hot); btLampkaWaterAuxOverheat.Turn(mvControlled->diesel.heat.water_aux.is_hot); btLampkaEngineOverheat.Turn(mvControlled->diesel.heat.engine_is_hot); - btLampkaMotorBlowers.Turn(mvControlled->MotorBlowers[end::front].is_active && mvControlled->MotorBlowers[end::rear].is_active); + btLampkaMotorBlowers.Turn(mvControlled->MotorBlowers[VehicleEnd::front].is_active && mvControlled->MotorBlowers[VehicleEnd::rear].is_active); btLampkaCoolingFans.Turn(mvControlled->RventRot > 1.0); btLampkaLouvresClosed.Turn(mvControlled->LouvresClosed()); btLampkaTempomat.Turn(mvOccupied->SpeedCtrlUnit.IsActive); @@ -1217,7 +1217,7 @@ bool TTrain::Update(double const Deltatime) InstrumentLightType == 4 ? mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable : false)}; InstrumentLightActive = InstrumentLightType == 3 ? true : // TODO: link the light state with the state of the master key - InstrumentLightType == 4 ? mvOccupied->iLights[end::front] != 0 || mvOccupied->iLights[end::rear] != 0 : + InstrumentLightType == 4 ? mvOccupied->iLights[VehicleEnd::front] != 0 || mvOccupied->iLights[VehicleEnd::rear] != 0 : InstrumentLightActive; btInstrumentLight.Turn(InstrumentLightActive && lightpower); btDashboardLight.Turn(DashboardLightActive && lightpower); diff --git a/vehicle/crewchange.cpp b/vehicle/crewchange.cpp index 8f44556b4..06d72ab12 100644 --- a/vehicle/crewchange.cpp +++ b/vehicle/crewchange.cpp @@ -31,7 +31,7 @@ constexpr int consist_walk_limit{300}; // alone, as the driver's own check of the consist does, so it works for a consist nobody has put in order template void for_each_in_consist(TDynamicObject &Vehicle, Function_ const Function) { - auto side{static_cast(end::front)}; + auto side{static_cast(VehicleEnd::front)}; auto *vehicle{Vehicle.FirstFind(side)}; side = 1 - side; auto count{0}; diff --git a/vehicle/dynamic/animations.cpp b/vehicle/dynamic/animations.cpp index 72a853408..f726ee58d 100644 --- a/vehicle/dynamic/animations.cpp +++ b/vehicle/dynamic/animations.cpp @@ -265,10 +265,10 @@ void TDynamicObject::SetPneumatic(bool front, bool red) ten = GetPneumatic(front, red); // 1=lewy skos,2=prawy skos,3=dwa proste if (front) if (PrevConnected()) // pojazd od strony sprzęgu 0 - tamten = PrevConnected()->GetPneumatic(PrevConnectedNo() == end::front ? true : false, red); + tamten = PrevConnected()->GetPneumatic(EndOf(PrevConnectedNo()) == VehicleEnd::front ? true : false, red); if (!front) if (NextConnected()) // pojazd od strony sprzęgu 1 - tamten = NextConnected()->GetPneumatic(NextConnectedNo() == end::front ? true : false, red); + tamten = NextConnected()->GetPneumatic(EndOf(NextConnectedNo()) == VehicleEnd::front ? true : false, red); if (ten == tamten) // jeśli układ jest symetryczny switch (ten) { @@ -279,7 +279,7 @@ void TDynamicObject::SetPneumatic(bool front, bool red) x = 3; break; // mamy prawy skos, dać prawe skosy case 3: // wszystkie cztery na prosto - if (MoverParameters->Couplers[front ? end::front : end::rear].Render) + if (MoverParameters->Couplers[front ? VehicleEnd::front : VehicleEnd::rear].Render) x = 1; else x = 4; @@ -355,8 +355,8 @@ float door_position( TMoverParameters const &Mover, TAnim const *Animation ) { return Mover.Doors.instances[ ( door_wings::on_right_side( Animation->iNumber ) ? - side::right : - side::left ) ].position; + VehicleSide::right : + VehicleSide::left ) ].position; } // the wing in the main model, and its namesake in the low poly interior; either can be missing @@ -514,8 +514,8 @@ void TDynamicObject::UpdatePlatformTranslate( TAnim *pAnim ) { auto const &door { MoverParameters->Doors.instances[ ( ( pAnim->iNumber & 1 ) == 0 ? - side::right : - side::left ) ] }; + VehicleSide::right : + VehicleSide::left ) ] }; pAnim->smAnimated->SetTranslate( glm::vec3{ @@ -531,8 +531,8 @@ void TDynamicObject::UpdatePlatformRotate( TAnim *pAnim ) { auto const &door { MoverParameters->Doors.instances[ ( ( pAnim->iNumber & 1 ) == 0 ? - side::right : - side::left ) ] }; + VehicleSide::right : + VehicleSide::left ) ] }; pAnim->smAnimated->SetRotate( float3( 0, 1, 0 ), @@ -546,8 +546,8 @@ void TDynamicObject::UpdateMirror( TAnim *pAnim ) { // only animate the mirror if it's located on the same end of the vehicle as the active cab auto const isactive { ( - MoverParameters->CabOccupied > 0 ? ( pAnim->iNumber >> 4 == end::front ? 1.0 : 0.0 ) : - MoverParameters->CabOccupied < 0 ? ( pAnim->iNumber >> 4 == end::rear ? 1.0 : 0.0 ) : + MoverParameters->CabOccupied > 0 ? ( EndOf( pAnim->iNumber >> 4 ) == VehicleEnd::front ? 1.0 : 0.0 ) : + MoverParameters->CabOccupied < 0 ? ( EndOf( pAnim->iNumber >> 4 ) == VehicleEnd::rear ? 1.0 : 0.0 ) : 0.0 ) }; if( pAnim->iNumber & 1 ) diff --git a/vehicle/dynamic/consist.cpp b/vehicle/dynamic/consist.cpp index d912c1693..2a53e7d2b 100644 --- a/vehicle/dynamic/consist.cpp +++ b/vehicle/dynamic/consist.cpp @@ -70,11 +70,11 @@ TDynamicObject * TDynamicObject::FirstFind(int &coupler_nr, CouplingSet const cf return nullptr; // Ra: zabezpieczenie przed ewentaulnymi błędami sprzęgów if (false == temp->MoverParameters->Couplers[coupler_nr].CouplingFlag.HasAll(cf)) return temp; // nic nie ma już dalej podłączone sprzęgiem cf - if (coupler_nr == end::front) + if (EndOf(coupler_nr) == VehicleEnd::front) { // jeżeli szukamy od sprzęgu 0 if (temp->PrevConnected()) // jeśli mamy coś z przodu { - if (temp->PrevConnectedNo() == end::front) // jeśli pojazd od strony sprzęgu 0 jest odwrócony + if (EndOf(temp->PrevConnectedNo()) == VehicleEnd::front) // jeśli pojazd od strony sprzęgu 0 jest odwrócony coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu temp = temp->PrevConnected(); // ten jest od strony 0 } @@ -85,7 +85,7 @@ TDynamicObject * TDynamicObject::FirstFind(int &coupler_nr, CouplingSet const cf { if (temp->NextConnected()) { - if (temp->NextConnectedNo() == end::rear) // jeśli pojazd od strony sprzęgu 1 jest odwrócony + if (EndOf(temp->NextConnectedNo()) == VehicleEnd::rear) // jeśli pojazd od strony sprzęgu 1 jest odwrócony coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu temp = temp->NextConnected(); // ten pojazd jest od strony 1 } @@ -117,7 +117,7 @@ float TDynamicObject::GetEPP() { // jeżeli szukamy od sprzęgu 0 if (temp->PrevConnected()) // jeśli mamy coś z przodu { - if (temp->PrevConnectedNo() == end::front) // jeśli pojazd od strony sprzęgu 0 jest odwrócony + if (EndOf(temp->PrevConnectedNo()) == VehicleEnd::front) // jeśli pojazd od strony sprzęgu 0 jest odwrócony coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu temp = temp->PrevConnected(); // ten jest od strony 0 } @@ -128,7 +128,7 @@ float TDynamicObject::GetEPP() { if (temp->NextConnected()) { - if (temp->NextConnectedNo() == end::rear) // jeśli pojazd od strony sprzęgu 1 jest odwrócony + if (EndOf(temp->NextConnectedNo()) == VehicleEnd::rear) // jeśli pojazd od strony sprzęgu 1 jest odwrócony coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu temp = temp->NextConnected(); // ten pojazd jest od strony 1 } @@ -151,7 +151,7 @@ float TDynamicObject::GetEPP() { // jeżeli szukamy od sprzęgu 0 if (temp->PrevConnected()) // jeśli mamy coś z przodu { - if (temp->PrevConnectedNo() == end::front) // jeśli pojazd od strony sprzęgu 0 jest odwrócony + if (EndOf(temp->PrevConnectedNo()) == VehicleEnd::front) // jeśli pojazd od strony sprzęgu 0 jest odwrócony coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu temp = temp->PrevConnected(); // ten jest od strony 0 } @@ -162,7 +162,7 @@ float TDynamicObject::GetEPP() { if (temp->NextConnected()) { - if (temp->NextConnectedNo() == end::rear) // jeśli pojazd od strony sprzęgu 1 jest odwrócony + if (EndOf(temp->NextConnectedNo()) == VehicleEnd::rear) // jeśli pojazd od strony sprzęgu 1 jest odwrócony coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu temp = temp->NextConnected(); // ten pojazd jest od strony 1 } @@ -176,11 +176,12 @@ float TDynamicObject::GetEPP() }; //--------------------------------------------------------------------------- -TDynamicObject * TDynamicObject::GetFirstDynamic(int cpl_type, CouplingSet const cf) +TDynamicObject * TDynamicObject::GetFirstDynamic(VehicleEnd const cpl_type, CouplingSet const cf) { // Szukanie skrajnego połączonego pojazdu w pociagu // od strony sprzegu (cpl_type) obiektu szukajacego // Ra: wystarczy jedna funkcja do szukania w obu kierunkach - return FirstFind(cpl_type, cf); // używa referencji + int coupler { NumberOf( cpl_type ) }; + return FirstFind(coupler, cf); // używa referencji }; int TDynamicObject::DirectionSet(int d) @@ -265,7 +266,7 @@ TDynamicObject::Neighbour(int &dir) { void TDynamicObject::update_neighbours() { - for( int end = end::front; end <= end::rear; ++end ) { + for (auto const end : VehicleEnds) { auto &neighbour { MoverParameters->Neighbours[ end ] }; auto const &coupler { MoverParameters->Couplers[ end ] }; @@ -294,7 +295,7 @@ TDynamicObject::update_neighbours() { auto const scanrange { std::max( 10.0, std::abs( MoverParameters->V ) ) + 40.0 }; // physics.derailment new: a vehicle off the track beside the other one doesn't run into it, the scan goes on // past it to the vehicles beyond - auto const lookup { find_vehicle( end, scanrange, true ) }; + auto const lookup { find_vehicle( NumberOf( end ), scanrange, true ) }; if( false == std::get( lookup ) ) { continue; } @@ -334,7 +335,7 @@ TDynamicObject::in_line_with( TDynamicObject const &Other ) const { std::tuple TDynamicObject::find_vehicle( int const Direction, double const Distance, bool const InLine ) const { - auto direction { ( Direction == end::front ? 1 : -1 ) }; + auto direction { ( EndOf( Direction ) == VehicleEnd::front ? 1 : -1 ) }; auto const initialdirection { direction }; // zapamiętanie kierunku poszukiwań na torze początkowym, względem sprzęgów auto const *track { RaTrackGet() }; @@ -344,7 +345,7 @@ TDynamicObject::find_vehicle( int const Direction, double const Distance, bool c } // (teraz względem toru) - auto const mycoupler { ( initialdirection < 0 ? end::rear : end::front ) }; // numer sprzęgu do podłączenia w obiekcie szukajacym + auto const mycoupler { NumberOf( initialdirection < 0 ? VehicleEnd::rear : VehicleEnd::front ) }; // numer sprzęgu do podłączenia w obiekcie szukajacym auto foundcoupler { -1 }; // numer sprzęgu w znalezionym obiekcie (znaleziony wypełni) auto distance { 0.0 }; // przeskanowana odleglość; odległość do zawalidrogi auto *foundobject { ABuFindObject( foundcoupler, distance, track, direction, mycoupler, InLine ) }; // zaczynamy szukać na tym samym torze @@ -470,7 +471,7 @@ void TDynamicObject::ParamSet(int what, int into) // dla 8 różnych if (what & 1) // na razie mamy lewe oraz prawe, czyli używamy maskę 1=lewe, // 2=prawe, 3=wszystkie - if( MoverParameters->Doors.instances[side::left].is_open ) + if( MoverParameters->Doors.instances[VehicleSide::left].is_open ) { // są otwarte if (!into) // jeśli zamykanie { @@ -485,7 +486,7 @@ void TDynamicObject::ParamSet(int what, int into) } } if (what & 2) // prawe działają niezależnie od lewych - if( MoverParameters->Doors.instances[side::right].is_open ) + if( MoverParameters->Doors.instances[VehicleSide::right].is_open ) { // są otwarte if (!into) // jeśli zamykanie { @@ -511,12 +512,12 @@ int TDynamicObject::RouteWish(TTrack *tr) }; // the vehicles coupled at the ends, and the ends of theirs facing this one -TDynamicObject *TDynamicObject::NextConnected() { return MoverParameters->Neighbours[ end::rear ].vehicle; } -TDynamicObject *TDynamicObject::PrevConnected() { return MoverParameters->Neighbours[ end::front ].vehicle; } -TDynamicObject *TDynamicObject::NextConnected() const { return MoverParameters->Neighbours[ end::rear ].vehicle; } -TDynamicObject *TDynamicObject::PrevConnected() const { return MoverParameters->Neighbours[ end::front ].vehicle; } -int TDynamicObject::NextConnectedNo() const { return MoverParameters->Neighbours[ end::rear ].vehicle_end; } -int TDynamicObject::PrevConnectedNo() const { return MoverParameters->Neighbours[ end::front ].vehicle_end; } +TDynamicObject *TDynamicObject::NextConnected() { return MoverParameters->Neighbours[ VehicleEnd::rear ].vehicle; } +TDynamicObject *TDynamicObject::PrevConnected() { return MoverParameters->Neighbours[ VehicleEnd::front ].vehicle; } +TDynamicObject *TDynamicObject::NextConnected() const { return MoverParameters->Neighbours[ VehicleEnd::rear ].vehicle; } +TDynamicObject *TDynamicObject::PrevConnected() const { return MoverParameters->Neighbours[ VehicleEnd::front ].vehicle; } +int TDynamicObject::NextConnectedNo() const { return MoverParameters->Neighbours[ VehicleEnd::rear ].vehicle_end; } +int TDynamicObject::PrevConnectedNo() const { return MoverParameters->Neighbours[ VehicleEnd::front ].vehicle_end; } void TDynamicObject::SetdMoveLen( double dMoveLen ) { MoverParameters->dMoveLen = dMoveLen; } void TDynamicObject::ResetdMoveLen() { MoverParameters->dMoveLen = 0; } diff --git a/vehicle/dynamic/couplers.cpp b/vehicle/dynamic/couplers.cpp index 706d9452e..90ab27a1b 100644 --- a/vehicle/dynamic/couplers.cpp +++ b/vehicle/dynamic/couplers.cpp @@ -106,7 +106,7 @@ int TDynamicObject::Dettach(int dir) } void -TDynamicObject::couple( int const Side ) { +TDynamicObject::couple( VehicleEnd const Side ) { auto const &neighbour { MoverParameters->Neighbours[ Side ] }; @@ -123,7 +123,7 @@ TDynamicObject::couple( int const Side ) { & othercoupler.AllowedFlag & Coupling::coupler ) == Coupling::coupler ) { if( MoverParameters->Attach( - Side, neighbour.vehicle_end, + Side, neighbour.FacingEnd(), othervehicleparams, Coupling::coupler ) ) { // one coupling type per key press @@ -140,11 +140,11 @@ TDynamicObject::couple( int const Side ) { & othercoupler.AllowedFlag & Coupling::brakeHose ) == Coupling::brakeHose ) { if( MoverParameters->Attach( - Side, neighbour.vehicle_end, + Side, neighbour.FacingEnd(), othervehicleparams, coupler.CouplingFlag | Coupling::brakeHose ) ) { - SetPneumatic( Side != 0, true ); - othervehicle->SetPneumatic( Side != 0, true ); + SetPneumatic( Side != VehicleEnd::front, true ); + othervehicle->SetPneumatic( Side != VehicleEnd::front, true ); // one coupling type per key press return; } @@ -156,11 +156,11 @@ TDynamicObject::couple( int const Side ) { & othercoupler.AllowedFlag & Coupling::mainHose ) == Coupling::mainHose ) { if( MoverParameters->Attach( - Side, neighbour.vehicle_end, + Side, neighbour.FacingEnd(), othervehicleparams, coupler.CouplingFlag | Coupling::mainHose ) ) { - SetPneumatic( Side != 0, false ); - othervehicle->SetPneumatic( Side != 0, false ); + SetPneumatic( Side != VehicleEnd::front, false ); + othervehicle->SetPneumatic( Side != VehicleEnd::front, false ); // one coupling type per key press return; } @@ -170,9 +170,9 @@ TDynamicObject::couple( int const Side ) { // ukrotnionko if( (coupler.AllowedFlag & othercoupler.AllowedFlag & Coupling::control) == Coupling::control && coupler.control_type == othercoupler.control_type - && MoverParameters->CompatibleCoupling( Side, *othervehicleparams, neighbour.vehicle_end, coupler.CouplingFlag | Coupling::control ).HasAny( Coupling::control ) ) { + && MoverParameters->CompatibleCoupling( Side, *othervehicleparams, neighbour.FacingEnd(), coupler.CouplingFlag | Coupling::control ).HasAny( Coupling::control ) ) { if( MoverParameters->Attach( - Side, neighbour.vehicle_end, + Side, neighbour.FacingEnd(), othervehicleparams, coupler.CouplingFlag | Coupling::control ) ) { // one coupling type per key press @@ -186,7 +186,7 @@ TDynamicObject::couple( int const Side ) { & othercoupler.AllowedFlag & Coupling::gangway ) == Coupling::gangway ) { if( MoverParameters->Attach( - Side, neighbour.vehicle_end, + Side, neighbour.FacingEnd(), othervehicleparams, coupler.CouplingFlag | Coupling::gangway ) ) { // one coupling type per key press @@ -200,7 +200,7 @@ TDynamicObject::couple( int const Side ) { & othercoupler.AllowedFlag & Coupling::heating ) == Coupling::heating ) { if( MoverParameters->Attach( - Side, neighbour.vehicle_end, + Side, neighbour.FacingEnd(), othervehicleparams, coupler.CouplingFlag | Coupling::heating ) ) { // one coupling type per key press @@ -212,20 +212,20 @@ TDynamicObject::couple( int const Side ) { } int -TDynamicObject::uncouple( int const Side ) { +TDynamicObject::uncouple( VehicleEnd const Side ) { - if( DettachStatus(Side) >= 0 + if( DettachStatus( NumberOf( Side ) ) >= 0 || true == MoverParameters->Couplers[Side].CouplingFlag.HasAll(Coupling::permanent) ) { // can't uncouple, return existing coupling state return MoverParameters->Couplers[ Side ].CouplingFlag.Bits(); } // jeżeli sprzęg niezablokowany, jest co odczepić i się da - auto const couplingflag { Dettach( Side ) }; + auto const couplingflag { Dettach( NumberOf( Side ) ) }; return couplingflag; } bool -TDynamicObject::attach_coupler_adapter( int const Side, bool const Enforce ) { +TDynamicObject::attach_coupler_adapter( VehicleEnd const Side, bool const Enforce ) { auto &coupler { MoverParameters->Couplers[ Side ] }; // sanity check(s) @@ -263,7 +263,7 @@ TDynamicObject::attach_coupler_adapter( int const Side, bool const Enforce ) { } bool -TDynamicObject::remove_coupler_adapter( int const Side ) { +TDynamicObject::remove_coupler_adapter( VehicleEnd const Side ) { auto &coupler{ MoverParameters->Couplers[ Side ] }; @@ -303,13 +303,13 @@ void TDynamicObject::AttachNext(TDynamicObject *Object, int iType) if( othercoupler.type() == TCouplerType::Automatic ) { // try to attach adapter to the vehicle attach_coupler_adapter( - vehicleend, + EndOf( vehicleend ), true ); } else if( coupler.type() == TCouplerType::Automatic ) { // try to attach adapter to the other vehicle Object->attach_coupler_adapter( - othervehicleend != 2 ? othervehicleend : coupler.ConnectedNr, + EndOf( othervehicleend != 2 ? othervehicleend : coupler.ConnectedNr ), true ); } // update distance to neighbours on account of potentially attached adapter diff --git a/vehicle/dynamic/lifecycle.cpp b/vehicle/dynamic/lifecycle.cpp index 128fb73c2..e63aa4c0e 100644 --- a/vehicle/dynamic/lifecycle.cpp +++ b/vehicle/dynamic/lifecycle.cpp @@ -622,31 +622,31 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" m_headsignal22.Init( "headsignal22", mdModel ); m_headsignal23.Init( "headsignal23", mdModel ); // informacja, czy ma poszczególne światła - iInventory[ end::front ] |= m_endsignal12.Active() ? light::redmarker_right : 0; - iInventory[ end::front ] |= m_endsignal13.Active() ? light::redmarker_left : 0; - iInventory[ end::rear ] |= m_endsignal22.Active() ? light::redmarker_right : 0; - iInventory[ end::rear ] |= m_endsignal23.Active() ? light::redmarker_left : 0; - iInventory[ end::front ] |= m_endsignals1.Active() ? light::redmarker_left | light::redmarker_right : 0; - iInventory[ end::rear ] |= m_endsignals2.Active() ? light::redmarker_left | light::redmarker_right : 0; - iInventory[ end::front ] |= m_endtab1.Active() ? light::rearendsignals : 0; // tabliczki blaszane - iInventory[ end::rear ] |= m_endtab2.Active() ? light::rearendsignals : 0; - iInventory[ end::front ] |= m_headlamp11.Active() ? light::headlight_upper : 0; - iInventory[ end::front ] |= m_headlamp12.Active() ? light::headlight_right : 0; - iInventory[ end::front ] |= m_headlamp13.Active() ? light::headlight_left : 0; + iInventory[ VehicleEnd::front ] |= m_endsignal12.Active() ? light::redmarker_right : 0; + iInventory[ VehicleEnd::front ] |= m_endsignal13.Active() ? light::redmarker_left : 0; + iInventory[ VehicleEnd::rear ] |= m_endsignal22.Active() ? light::redmarker_right : 0; + iInventory[ VehicleEnd::rear ] |= m_endsignal23.Active() ? light::redmarker_left : 0; + iInventory[ VehicleEnd::front ] |= m_endsignals1.Active() ? light::redmarker_left | light::redmarker_right : 0; + iInventory[ VehicleEnd::rear ] |= m_endsignals2.Active() ? light::redmarker_left | light::redmarker_right : 0; + iInventory[ VehicleEnd::front ] |= m_endtab1.Active() ? light::rearendsignals : 0; // tabliczki blaszane + iInventory[ VehicleEnd::rear ] |= m_endtab2.Active() ? light::rearendsignals : 0; + iInventory[ VehicleEnd::front ] |= m_headlamp11.Active() ? light::headlight_upper : 0; + iInventory[ VehicleEnd::front ] |= m_headlamp12.Active() ? light::headlight_right : 0; + iInventory[ VehicleEnd::front ] |= m_headlamp13.Active() ? light::headlight_left : 0; - iInventory[end::front] |= m_highbeam12.Active() ? light::highbeamlight_right : 0; - iInventory[end::front] |= m_highbeam13.Active() ? light::highbeamlight_left : 0; + iInventory[VehicleEnd::front] |= m_highbeam12.Active() ? light::highbeamlight_right : 0; + iInventory[VehicleEnd::front] |= m_highbeam13.Active() ? light::highbeamlight_left : 0; - iInventory[ end::rear ] |= m_headlamp21.Active() ? light::headlight_upper : 0; - iInventory[ end::rear ] |= m_headlamp22.Active() ? light::headlight_right : 0; - iInventory[ end::rear ] |= m_headlamp23.Active() ? light::headlight_left : 0; - iInventory[ end::front ] |= m_headsignal12.Active() ? light::auxiliary_right : 0; - iInventory[ end::front ] |= m_headsignal13.Active() ? light::auxiliary_left : 0; - iInventory[ end::rear ] |= m_headsignal22.Active() ? light::auxiliary_right : 0; - iInventory[ end::rear ] |= m_headsignal23.Active() ? light::auxiliary_left : 0; + iInventory[ VehicleEnd::rear ] |= m_headlamp21.Active() ? light::headlight_upper : 0; + iInventory[ VehicleEnd::rear ] |= m_headlamp22.Active() ? light::headlight_right : 0; + iInventory[ VehicleEnd::rear ] |= m_headlamp23.Active() ? light::headlight_left : 0; + iInventory[ VehicleEnd::front ] |= m_headsignal12.Active() ? light::auxiliary_right : 0; + iInventory[ VehicleEnd::front ] |= m_headsignal13.Active() ? light::auxiliary_left : 0; + iInventory[ VehicleEnd::rear ] |= m_headsignal22.Active() ? light::auxiliary_right : 0; + iInventory[ VehicleEnd::rear ] |= m_headsignal23.Active() ? light::auxiliary_left : 0; - iInventory[end::rear] |= m_highbeam22.Active() ? light::highbeamlight_right : 0; - iInventory[end::rear] |= m_highbeam23.Active() ? light::highbeamlight_left : 0; + iInventory[VehicleEnd::rear] |= m_highbeam22.Active() ? light::highbeamlight_right : 0; + iInventory[VehicleEnd::rear] |= m_highbeam23.Active() ? light::highbeamlight_left : 0; btExteriorOnly.Init("external_only", mdModel, false); diff --git a/vehicle/dynamic/lights.cpp b/vehicle/dynamic/lights.cpp index cd38662e1..9fcd1bc02 100644 --- a/vehicle/dynamic/lights.cpp +++ b/vehicle/dynamic/lights.cpp @@ -63,20 +63,20 @@ void TDynamicObject::SetLights() { int const automaticmarkers { MoverParameters->CabActive == 0 && MoverParameters->InactiveCabFlag & activation::redmarkers ? light::redmarker_left + light::redmarker_right : 0 }; auto const lightpos { MoverParameters->LightsPos - 1 }; - std::array const cablights { - automaticmarkers > 0 ? automaticmarkers : MoverParameters->Lights[ end::front ][ lightpos ], - automaticmarkers > 0 ? automaticmarkers : MoverParameters->Lights[ end::rear ][ lightpos ] }; + ByEnd const cablights { + automaticmarkers > 0 ? automaticmarkers : MoverParameters->Lights[ VehicleEnd::front ][ lightpos ], + automaticmarkers > 0 ? automaticmarkers : MoverParameters->Lights[ VehicleEnd::rear ][ lightpos ] }; // the custom position keeps the lights lit at coupled ends as well auto const ignorecouplings { MoverParameters->LightsPos == 18 }; - auto *vehicle { GetFirstDynamic( MoverParameters->CabOccupied >= 0 ? end::front : end::rear, Coupling::control ) }; + auto *vehicle { GetFirstDynamic( MoverParameters->CabOccupied >= 0 ? VehicleEnd::front : VehicleEnd::rear, Coupling::control ) }; while( vehicle != nullptr ) { // set lights on given side if there's no coupling with another vehicle, turn them off otherwise - auto const iscoupled { [ vehicle, ignorecouplings ]( end const Side ) { + auto const iscoupled { [ vehicle, ignorecouplings ]( VehicleEnd const Side ) { return false == ignorecouplings && vehicle->MoverParameters->Couplers[ Side ].CouplingFlag.HasAny(Coupling::coupler) && vehicle->MoverParameters->Neighbours[ Side ].vehicle != nullptr; } }; auto const lights { lights_programmer::vehicle_lights( - cablights, isfrontcaboccupied, vehicle->iDirection, { iscoupled( end::front ), iscoupled( end::rear ) } ) }; + cablights, isfrontcaboccupied, vehicle->iDirection, { iscoupled( VehicleEnd::front ), iscoupled( VehicleEnd::rear ) } ) }; vehicle->RaLightsSet( lights.head, lights.rear ); vehicle = isfrontcaboccupied ? vehicle->Next(Coupling::control) : vehicle->Prev(Coupling::control); } @@ -102,8 +102,8 @@ void TDynamicObject::RaLightsSet(int head, int rear) if( rear == ( light::redmarker_left | light::redmarker_right | light::rearendsignals ) ) // jeśli nadal obydwie możliwości if( iInventory[ ( iDirection ? - end::rear : - end::front ) ] & ( light::redmarker_left | light::redmarker_right ) ) { + VehicleEnd::rear : + VehicleEnd::front ) ] & ( light::redmarker_left | light::redmarker_right ) ) { // czy ma jakieś światła czerowone od danej strony rear = light::redmarker_left | light::redmarker_right; // dwa światła czerwone } @@ -113,7 +113,7 @@ void TDynamicObject::RaLightsSet(int head, int rear) } // w zależności od kierunku pojazdu w składzie if( head >= 0 ) { - auto const vehicleend { iDirection > 0 ? end::front : end::rear }; + auto const vehicleend { iDirection > 0 ? VehicleEnd::front : VehicleEnd::rear }; MoverParameters->iLights[ vehicleend ] = head & iInventory[vehicleend]; bool tLeft = MoverParameters->iLights[vehicleend] & (light::auxiliary_left | light::headlight_left); // roboczo czy jakiekolwiek swiatlo z lewej jest zapalone bool tRight = MoverParameters->iLights[vehicleend] & (light::auxiliary_right | light::headlight_right); // a tu z prawej @@ -133,10 +133,10 @@ void TDynamicObject::RaLightsSet(int head, int rear) DimHeadlights = false; switch (MoverParameters->CabActive) { - case end::front: + case NumberOf(VehicleEnd::front): HeadlightsAoff = true; break; - case end::rear: + case NumberOf(VehicleEnd::rear): HeadlightsBoff = true; break; default: @@ -147,10 +147,10 @@ void TDynamicObject::RaLightsSet(int head, int rear) { switch (MoverParameters->CabActive) { - case end::front: + case NumberOf(VehicleEnd::front): HeadlightsAoff = false; break; - case end::rear: + case NumberOf(VehicleEnd::rear): HeadlightsBoff = false; break; default: @@ -170,14 +170,14 @@ void TDynamicObject::RaLightsSet(int head, int rear) } if( rear >= 0 ) { - auto const vehicleend{ iDirection > 0 ? end::rear : end::front }; + auto const vehicleend{ iDirection > 0 ? VehicleEnd::rear : VehicleEnd::front }; MoverParameters->iLights[ vehicleend ] = rear & iInventory[vehicleend]; } }; void TDynamicObject::SetLightDimmings() { - auto const vehicleend{iDirection > 0 ? end::front : end::rear}; + auto const vehicleend{iDirection > 0 ? VehicleEnd::front : VehicleEnd::rear}; if (Controller == Humandriver) { @@ -195,10 +195,10 @@ void TDynamicObject::SetLightDimmings() DimHeadlights = false; switch (vehicleend) { - case end::front: + case VehicleEnd::front: HeadlightsAoff = true; break; - case end::rear: + case VehicleEnd::rear: HeadlightsBoff = true; break; default: @@ -209,10 +209,10 @@ void TDynamicObject::SetLightDimmings() { switch (vehicleend) { - case end::front: + case VehicleEnd::front: HeadlightsAoff = false; break; - case end::rear: + case VehicleEnd::rear: HeadlightsBoff = false; break; default: @@ -237,7 +237,7 @@ void TDynamicObject::SetLightDimmings() bool TDynamicObject::has_signal_pc1_on() const { - auto const vehicleend { iDirection > 0 ? end::front : end::rear }; + auto const vehicleend { iDirection > 0 ? VehicleEnd::front : VehicleEnd::rear }; auto const equippedlights { iInventory[ vehicleend ] }; auto const pattern { equippedlights & ( light::headlight_left | light::headlight_right | light::headlight_upper ) }; auto const patternfallback { equippedlights & ( light::auxiliary_left | light::auxiliary_right | light::headlight_upper ) }; @@ -250,7 +250,7 @@ bool TDynamicObject::has_signal_pc1_on() const { bool TDynamicObject::has_signal_pc2_on() const { - auto const vehicleend { iDirection > 0 ? end::front : end::rear }; + auto const vehicleend { iDirection > 0 ? VehicleEnd::front : VehicleEnd::rear }; auto const equippedlights { iInventory[ vehicleend ] }; auto const pattern { equippedlights & ( light::redmarker_left | light::headlight_right | light::headlight_upper ) }; auto const patternfallback { equippedlights & ( light::redmarker_left | light::auxiliary_right | light::headlight_upper ) }; @@ -262,7 +262,7 @@ bool TDynamicObject::has_signal_pc2_on() const { bool TDynamicObject::has_signal_pc5_on() const { - auto const vehicleend { iDirection > 0 ? end::rear : end::front }; + auto const vehicleend { iDirection > 0 ? VehicleEnd::rear : VehicleEnd::front }; auto const equippedlights { iInventory[ vehicleend ] }; auto const pattern { equippedlights & ( light::redmarker_left | light::redmarker_right ) }; auto const patternfallback { equippedlights & light::rearendsignals }; @@ -271,7 +271,7 @@ bool TDynamicObject::has_signal_pc5_on() const { return (pattern != 0 && activelights == pattern) || (patternfallback != 0 && activelights == patternfallback); } -bool TDynamicObject::has_signal_on( int const Side, int const Pattern ) const { +bool TDynamicObject::has_signal_on( VehicleEnd const Side, int const Pattern ) const { /* auto const vehicleend { iDirection > 0 ? Side : 1 - Side }; auto const pattern { iInventory[ vehicleend ] & Pattern }; diff --git a/vehicle/dynamic/load.cpp b/vehicle/dynamic/load.cpp index 658a1ed0c..42c9e7913 100644 --- a/vehicle/dynamic/load.cpp +++ b/vehicle/dynamic/load.cpp @@ -67,10 +67,10 @@ void TDynamicObject::LoadExchange( int const Disembark, int const Embark, int co auto const lewe = ( DirectionGet() > 0 ) ? 1 : 2; auto const prawe = 3 - lewe; if( Platform & lewe ) { - MoverParameters->OperateDoors( side::left, true, range_t::local ); + MoverParameters->OperateDoors( VehicleSide::left, true, range_t::local ); } if( Platform & prawe ) { - MoverParameters->OperateDoors( side::right, true, range_t::local ); + MoverParameters->OperateDoors( VehicleSide::right, true, range_t::local ); } } */ @@ -108,10 +108,10 @@ float TDynamicObject::LoadExchangeSpeed() const { auto const lewe { DirectionGet() > 0 ? 1 : 2 }; auto const prawe { 3 - lewe }; if( m_exchange.platforms & lewe ) { - exchangespeedfactor += MoverParameters->Doors.instances[side::left].is_open ? 1.f : 0.f; + exchangespeedfactor += MoverParameters->Doors.instances[VehicleSide::left].is_open ? 1.f : 0.f; } if( m_exchange.platforms & prawe ) { - exchangespeedfactor += MoverParameters->Doors.instances[side::right].is_open ? 1.f : 0.f; + exchangespeedfactor += MoverParameters->Doors.instances[VehicleSide::right].is_open ? 1.f : 0.f; } return exchangespeedfactor; @@ -134,14 +134,14 @@ void TDynamicObject::update_exchange( double const Deltatime ) { auto const lewe { DirectionGet() > 0 ? 1 : 2 }; auto const prawe { 3 - lewe }; if( m_exchange.platforms & lewe - && false == (MoverParameters->Doors.instances[side::left].is_open || MoverParameters->Doors.instances[side::left].is_opening) ) { + && false == (MoverParameters->Doors.instances[VehicleSide::left].is_open || MoverParameters->Doors.instances[VehicleSide::left].is_opening) ) { // try to open left door - MoverParameters->OperateDoors( side::left, true, range_t::local ); + MoverParameters->OperateDoors( VehicleSide::left, true, range_t::local ); } if( m_exchange.platforms & prawe - && false == (MoverParameters->Doors.instances[side::right].is_open || MoverParameters->Doors.instances[side::right].is_opening) ) { + && false == (MoverParameters->Doors.instances[VehicleSide::right].is_open || MoverParameters->Doors.instances[VehicleSide::right].is_opening) ) { // try to open right door - MoverParameters->OperateDoors( side::right, true, range_t::local ); + MoverParameters->OperateDoors( VehicleSide::right, true, range_t::local ); } } @@ -197,8 +197,8 @@ void TDynamicObject::update_exchange( double const Deltatime ) { // remotely controlled door are more likely to be left open MoverParameters->Doors.close_control == control_t::passenger ? 0.75 : 0.50) ) { - MoverParameters->OperateDoors( side::left, false, range_t::local ); - MoverParameters->OperateDoors( side::right, false, range_t::local ); + MoverParameters->OperateDoors( VehicleSide::left, false, range_t::local ); + MoverParameters->OperateDoors( VehicleSide::right, false, range_t::local ); } } // if the vehicle was emptied potentially switch load visualization model diff --git a/vehicle/dynamic/mmd.cpp b/vehicle/dynamic/mmd.cpp index edd971e4a..190ba7153 100644 --- a/vehicle/dynamic/mmd.cpp +++ b/vehicle/dynamic/mmd.cpp @@ -784,9 +784,9 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co // we don't expect more than 2-4 mirrors, so it should be safe to store submodel location (front/rear) in the higher bits // parzyste działają inaczej niż nieparzyste pAnimations[ i + j ].iNumber = - ( ( pAnimations[ i + j ].smAnimated->offset().z > 0 ? - end::front : - end::rear ) << 4 ) + ( NumberOf( pAnimations[ i + j ].smAnimated->offset().z > 0 ? + VehicleEnd::front : + VehicleEnd::rear ) << 4 ) + i; pAnimations[ i + j ].fMaxDist = 150 * 150; // drzwi to z daleka widać /* @@ -993,9 +993,9 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co blowertemplate.owner( this ); auto const amplitudedivisor { static_cast( - MoverParameters->MotorBlowers[ end::front ].speed > 0 ? MoverParameters->MotorBlowers[ end::front ].speed * MoverParameters->nmax * 60 + MoverParameters->Power * 3 : + MoverParameters->MotorBlowers[ VehicleEnd::front ].speed > 0 ? MoverParameters->MotorBlowers[ VehicleEnd::front ].speed * MoverParameters->nmax * 60 + MoverParameters->Power * 3 : blowertemplate.has_bookends() ? 1 : // NOTE: for motorblowers with fixed speed if the sound has defined bookends we skip revolutions-based part of frequency/volume adjustments - MoverParameters->MotorBlowers[ end::front ].speed * -1 ) }; + MoverParameters->MotorBlowers[ VehicleEnd::front ].speed * -1 ) }; blowertemplate.m_amplitudefactor /= amplitudedivisor; blowertemplate.m_frequencyfactor /= amplitudedivisor; @@ -1500,7 +1500,7 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co || sides == "left" ) { // left... auto const location { glm::vec3 { MoverParameters->Dim.W * 0.5f, MoverParameters->Dim.H * 0.5f, offset } }; - door.placement = side::left; + door.placement = VehicleSide::left; door.rsDoorClose.offset( location ); door.rsDoorOpen.offset( location ); door.lock.offset( location ); @@ -1514,7 +1514,7 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co || sides == "right" ) { // ...and right auto const location { glm::vec3 { MoverParameters->Dim.W * -0.5f, 2.f, offset } }; - door.placement = side::right; + door.placement = VehicleSide::right; door.rsDoorClose.offset( location ); door.rsDoorOpen.offset( location ); door.lock.offset( location ); @@ -1538,10 +1538,10 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co // vehicle faces +Z in 'its' space, as for the doors negative value means ahead of centre auto const offset { std::atof( token.c_str() ) * -1.f }; mirror_sounds mirror; - mirror.end = offset >= 0.f ? end::front : end::rear; - for( auto const mirrorside : { side::left, side::right } ) { + mirror.end = offset >= 0.f ? VehicleEnd::front : VehicleEnd::rear; + for( auto const mirrorside : { VehicleSide::left, VehicleSide::right } ) { auto const location { glm::vec3 { - MoverParameters->Dim.W * ( mirrorside == side::left ? 0.5f : -0.5f ), + MoverParameters->Dim.W * ( mirrorside == VehicleSide::left ? 0.5f : -0.5f ), MoverParameters->Dim.H * 0.5f, offset } }; mirror.placement = mirrorside; @@ -2077,43 +2077,43 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co } // couplers auto const frontcoupleroffset { glm::vec3{ 0.f, 1.f, MoverParameters->Dim.L * 0.5f } }; - m_couplersounds[ end::front ].attach_coupler.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].attach_brakehose.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].attach_mainhose.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].attach_control.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].attach_gangway.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].attach_heating.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].detach_coupler.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].detach_brakehose.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].detach_mainhose.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].detach_control.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].detach_gangway.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].detach_heating.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].dsbCouplerStretch.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].dsbCouplerStretch_loud.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].dsbBufferClamp.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].dsbBufferClamp_loud.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].dsbAdapterAttach.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].dsbAdapterRemove.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].attach_coupler.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].attach_brakehose.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].attach_mainhose.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].attach_control.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].attach_gangway.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].attach_heating.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].detach_coupler.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].detach_brakehose.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].detach_mainhose.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].detach_control.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].detach_gangway.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].detach_heating.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].dsbCouplerStretch.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].dsbCouplerStretch_loud.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].dsbBufferClamp.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].dsbBufferClamp_loud.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].dsbAdapterAttach.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].dsbAdapterRemove.offset( frontcoupleroffset ); auto const rearcoupleroffset { glm::vec3{ 0.f, 1.f, MoverParameters->Dim.L * -0.5f } }; - m_couplersounds[ end::rear ].attach_coupler.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].attach_brakehose.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].attach_mainhose.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].attach_control.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].attach_gangway.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].attach_heating.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].detach_coupler.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].detach_brakehose.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].detach_mainhose.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].detach_control.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].detach_gangway.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].detach_heating.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].dsbCouplerStretch.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].dsbCouplerStretch_loud.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].dsbBufferClamp.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].dsbBufferClamp_loud.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].dsbAdapterAttach.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].dsbAdapterRemove.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].attach_coupler.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].attach_brakehose.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].attach_mainhose.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].attach_control.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].attach_gangway.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].attach_heating.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].detach_coupler.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].detach_brakehose.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].detach_mainhose.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].detach_control.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].detach_gangway.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].detach_heating.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].dsbCouplerStretch.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].dsbCouplerStretch_loud.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].dsbBufferClamp.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].dsbBufferClamp_loud.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].dsbAdapterAttach.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].dsbAdapterRemove.offset( rearcoupleroffset ); } TModel3d * diff --git a/vehicle/dynamic/movement.cpp b/vehicle/dynamic/movement.cpp index d5f0a4ccf..77bcfbfff 100644 --- a/vehicle/dynamic/movement.cpp +++ b/vehicle/dynamic/movement.cpp @@ -155,8 +155,8 @@ void TDynamicObject::place_by_axles() } // obliczanie pozycji sprzęgów do liczenia zderzeń auto dir = 0.5 * MoverParameters->Dim.L * vFront; // wektor sprzęgu - vCoulpler[end::front] = vPosition + dir; // współrzędne sprzęgu na początku - vCoulpler[end::rear] = vPosition - dir; // współrzędne sprzęgu na końcu + vCoulpler[VehicleEnd::front] = vPosition + dir; // współrzędne sprzęgu na początku + vCoulpler[VehicleEnd::rear] = vPosition - dir; // współrzędne sprzęgu na końcu // bCameraNear= // if (bCameraNear) //jeśli istotne są szczegóły (blisko kamery) { // przeliczenie cienia diff --git a/vehicle/dynamic/offtrack.cpp b/vehicle/dynamic/offtrack.cpp index ddd629fba..c1dab3d46 100644 --- a/vehicle/dynamic/offtrack.cpp +++ b/vehicle/dynamic/offtrack.cpp @@ -148,8 +148,8 @@ glm::dvec3 level_left_of( glm::dvec3 const &Front ) { // the end of the vehicle where it meets the one coupled to it: the middle of its buffer beam, the way it faces. off the // track, over its base on the ground as it stands: rolled over, its ends go with it as far as the coupling holds them, // and the buffers of the side it rolled to miss those of an upright one -derail_motion::end_point end_point_of( TDynamicObject const &Vehicle, int const End ) { - auto const facing { End == end::front ? 1.0 : -1.0 }; +derail_motion::end_point end_point_of( TDynamicObject const &Vehicle, VehicleEnd const End ) { + auto const facing { End == VehicleEnd::front ? 1.0 : -1.0 }; auto const &motion { Vehicle.MoverParameters->OffTrack }; glm::dvec3 const front { Vehicle.VectorFront().x, 0.0, Vehicle.VectorFront().z }; auto const length { glm::length( front ) }; @@ -162,8 +162,8 @@ derail_motion::end_point end_point_of( TDynamicObject const &Vehicle, int const } // the push of the buffers on the end of the vehicle [N], negative the pull of its coupling -double compression_of( TMoverParameters const &Vehicle, int const End ) { - return ( End == end::front ? -1.0 : 1.0 ) * Vehicle.Couplers[ End ].CForce; +double compression_of( TMoverParameters const &Vehicle, VehicleEnd const End ) { + return ( End == VehicleEnd::front ? -1.0 : 1.0 ) * Vehicle.Couplers[ End ].CForce; } } // namespace @@ -183,13 +183,13 @@ std::string_view side_name( int const Side ) { } // namespace -double TDynamicObject::off_track_gap( int const End ) const { +double TDynamicObject::off_track_gap( VehicleEnd const End ) const { auto const *neighbour { MoverParameters->Neighbours[ End ].vehicle }; if( neighbour == nullptr ) { return 0.0; } - return derail_motion::meet( end_point_of( *this, End ), end_point_of( *neighbour, MoverParameters->Neighbours[ End ].vehicle_end ) ).gap; + return derail_motion::meet( end_point_of( *this, End ), end_point_of( *neighbour, MoverParameters->Neighbours[ End ].FacingEnd() ) ).gap; } double TDynamicObject::off_track_offset() const { @@ -389,14 +389,14 @@ void TDynamicObject::move_off_track( double const Distance ) { m_offtracksite.bed( track_bed() ); // the buffers and the couplings of its ends push and pull it, at an angle to it where the vehicle coupled there is std::array ends {}; - for( int end = end::front; end <= end::rear; ++end ) { + for (auto const end : VehicleEnds) { auto const *neighbour { MoverParameters->Neighbours[ end ].vehicle }; auto const compression { compression_of( *MoverParameters, end ) }; if( neighbour == nullptr || compression == 0.0 ) { continue; } - ends[ end ] = derail_motion::force_on( - derail_motion::meet( end_point_of( *this, end ), end_point_of( *neighbour, MoverParameters->Neighbours[ end ].vehicle_end ) ), compression ); + ends[ NumberOf( end ) ] = derail_motion::force_on( + derail_motion::meet( end_point_of( *this, end ), end_point_of( *neighbour, MoverParameters->Neighbours[ end ].FacingEnd() ) ), compression ); } auto const reversals { motion.reversals() }; motion.step( time, Distance, MoverParameters->V, m_offtracksite, ends ); @@ -440,14 +440,14 @@ void TDynamicObject::place_off_track() { modelRot.z = std::atan2( -vFront.x, vFront.z ); mMatrix = glm::inverse( BasisChange( vLeft, vUp, vFront ) ); auto const half { 0.5 * MoverParameters->Dim.L * vFront }; - vCoulpler[ end::front ] = vPosition + half; - vCoulpler[ end::rear ] = vPosition - half; + vCoulpler[ VehicleEnd::front ] = vPosition + half; + vCoulpler[ VehicleEnd::rear ] = vPosition - half; m_offtrackplaced = true; } void TDynamicObject::pull_neighbours( double const Distance ) { - for( int end = end::front; end <= end::rear; ++end ) { + for (auto const end : VehicleEnds) { auto const &coupler { MoverParameters->Couplers[ end ] }; auto *neighbour { MoverParameters->Neighbours[ end ].vehicle }; if( coupler.CouplingFlag == Coupling::none || neighbour == nullptr || neighbour->MoverParameters->OffTrack.active() @@ -456,7 +456,7 @@ void TDynamicObject::pull_neighbours( double const Distance ) { continue; } auto &other { *neighbour->MoverParameters }; - auto const otherend { MoverParameters->Neighbours[ end ].vehicle_end }; + auto const otherend { MoverParameters->Neighbours[ end ].FacingEnd() }; glm::dvec3 const otherfront { neighbour->vFront.x, 0.0, neighbour->vFront.z }; if( glm::length( otherfront ) < 1e-6 ) { continue; diff --git a/vehicle/dynamic/sounds.cpp b/vehicle/dynamic/sounds.cpp index ee5828877..a9c402145 100644 --- a/vehicle/dynamic/sounds.cpp +++ b/vehicle/dynamic/sounds.cpp @@ -458,7 +458,7 @@ void TDynamicObject::RenderSounds() { } } // NBMX Obsluga drzwi, MC: zuniwersalnione - std::array const sides { side::right, side::left }; + auto const &sides { VehicleSides }; for( auto const side : sides ) { auto const &door { MoverParameters->Doors.instances[ side ] }; @@ -873,12 +873,12 @@ void TDynamicObject::RenderSounds() { } } -void TDynamicObject::play_mirror_sounds( side const Side, mirror_moves::event const Event ) { +void TDynamicObject::play_mirror_sounds( VehicleSide const Side, mirror_moves::event const Event ) { if( Event == mirror_moves::event::none ) { return; } // as UpdateMirror(), only the mirrors of the occupied cab move if( MoverParameters->CabOccupied == 0 ) { return; } - auto const cabend { MoverParameters->CabOccupied > 0 ? end::front : end::rear }; + auto const cabend { MoverParameters->CabOccupied > 0 ? VehicleEnd::front : VehicleEnd::rear }; for( auto &mirror : m_mirrorsounds ) { if( mirror.placement != Side || mirror.end != cabend ) { continue; } auto &sound { Event == mirror_moves::event::unfolding ? mirror.unfold : mirror.fold }; @@ -1283,11 +1283,11 @@ TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, doub if( false == motorblowers.empty() ) { for( auto &blowersound : motorblowers ) { // match the motor blower and the sound source based on whether they're located in the front or the back of the vehicle - auto const &blower { Vehicle.MotorBlowers[ ( blowersound.offset().z > 0 ? end::front : end::rear ) ] }; + auto const &blower { Vehicle.MotorBlowers[ ( blowersound.offset().z > 0 ? VehicleEnd::front : VehicleEnd::rear ) ] }; // TODO: for the sounds with provided bookends invoke stop() when the stop is triggered and revolutions start dropping, instead of after full stop if( blower.revolutions > 1 ) { // NOTE: for motorblowers with fixed speed if the sound has defined bookends we skip revolutions-based part of frequency/volume adjustments - auto const revolutionmodifier { Vehicle.MotorBlowers[end::front].speed < 0.f && blowersound.has_bookends() ? 1.f : blower.revolutions }; + auto const revolutionmodifier { Vehicle.MotorBlowers[VehicleEnd::front].speed < 0.f && blowersound.has_bookends() ? 1.f : blower.revolutions }; blowersound .pitch( true == blowersound.is_combined() ? diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index 03057e4f8..275e4996c 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -191,8 +191,8 @@ bool TDynamicObject::Update(double dt, double dt1) // jeśli jedzie if( MoverParameters->Vel > 0.5 ) { // Ra 2014-07: doraźna blokada logowania zimnych lokomotyw - zrobić to trzeba inaczej - if( MoverParameters->Pantographs[end::front].is_active - || MoverParameters->Pantographs[end::rear].is_active ) { + if( MoverParameters->Pantographs[VehicleEnd::front].is_active + || MoverParameters->Pantographs[VehicleEnd::rear].is_active ) { if( MoverParameters->Mains // Ra 15-01: logować tylko, jeśli WS załączony && MoverParameters->GetTrainsetHighVoltage() < 0.1f // yB 16-03: i nie jest to asynchron zasilany z daleka && false == MoverParameters->GensetSelected() ) { // nor a dual-mode vehicle running on its genset @@ -274,7 +274,7 @@ bool TDynamicObject::Update(double dt, double dt1) // 2. ustal mozliwa do realizacji sile hamowania ED // - w szczegolnosci powinien brac pod uwage rozne sily hamowania - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, Coupling::control); p; + for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) { ++np; @@ -317,11 +317,11 @@ bool TDynamicObject::Update(double dt, double dt1) Mechanik->fMedAmax = amax; auto doorisopen { - false == MoverParameters->Doors.instances[side::left].is_closed - || false == MoverParameters->Doors.instances[side::right].is_closed + false == MoverParameters->Doors.instances[VehicleSide::left].is_closed + || false == MoverParameters->Doors.instances[VehicleSide::right].is_closed || ( MoverParameters->Doors.permit_needed - && ( MoverParameters->Doors.instances[ side::left ].open_permit - || MoverParameters->Doors.instances[ side::right ].open_permit ) ) }; + && ( MoverParameters->Doors.instances[ VehicleSide::left ].open_permit + || MoverParameters->Doors.instances[ VehicleSide::right ].open_permit ) ) }; doorisopen &= !(MoverParameters->ReleaseParkingBySpringBrakeWhenDoorIsOpen && MoverParameters->SpringBrake.IsActive); if (MoverParameters->Vel < 0.5 && (eimic < 0 || doorisopen || MoverParameters->Hamulec->GetEDBCP())) @@ -426,7 +426,7 @@ bool TDynamicObject::Update(double dt, double dt1) ////ALGORYTM 2 - KAZDEMU PO ROWNO, ale nie wiecej niz eped * masa // 1. najpierw daj kazdemu tyle samo int i = 0; - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, Coupling::control); p; + for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; p = kier == true ? p->Next(Coupling::control) : p->Prev(Coupling::control) ) { auto const Nmax = ((p->MoverParameters->P2FTrans * p->MoverParameters->MaxBrakePress[0] - @@ -454,7 +454,7 @@ bool TDynamicObject::Update(double dt, double dt1) test = false; i = 0; float przek = 0; - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, Coupling::control); p; + for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; p = kier == true ? p->Next(Coupling::control) : p->Prev(Coupling::control) ) { if (FzEP[i] > 0.01 && @@ -478,7 +478,7 @@ bool TDynamicObject::Update(double dt, double dt1) } i = 0; przek = przek / (np - nPrzekrF); - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, Coupling::control); p; + for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; true == kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) { if (!PrzekrF[i]) @@ -489,7 +489,7 @@ bool TDynamicObject::Update(double dt, double dt1) } } i = 0; - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, Coupling::control); p; + for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; true == kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) { float Nmax = ((p->MoverParameters->P2FTrans * p->MoverParameters->MaxBrakePress[0] - @@ -542,7 +542,7 @@ bool TDynamicObject::Update(double dt, double dt1) { MEDLogFile << MEDLogTime << "\t" << MoverParameters->Vel << "\t" << masa*0.001 << "\t" << osie << "\t" << FmaxPN*0.001 << "\t" << FmaxED*0.001 << "\t" << FfulED*0.001 << "\t" << FrED*0.001 << "\t" << Fzad*0.001 << "\t" << FzadED*0.001 << "\t" << FzadPN*0.001; - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, Coupling::control); p; + for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; true == kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) { MEDLogFile << "\t" << p->MoverParameters->BrakePress; @@ -788,7 +788,7 @@ bool TDynamicObject::Update(double dt, double dt1) } else { if( pantograph->hvPowerWire != nullptr - && true == MoverParameters->Pantographs[end::front].is_active + && true == MoverParameters->Pantographs[VehicleEnd::front].is_active && pantograph->PantTraction - pantograph->PantWys < 0.01 ) { // tolerancja niedolegania ++activepantographs; } @@ -827,7 +827,7 @@ bool TDynamicObject::Update(double dt, double dt1) 0.95 * MoverParameters->EnginePowerSource.MaxVoltage : 0.0; } - else if( true == MoverParameters->Pantographs[end::front].is_active + else if( true == MoverParameters->Pantographs[VehicleEnd::front].is_active && PantDiff < 0.01 ) // tolerancja niedolegania { if (p->hvPowerWire) { @@ -870,7 +870,7 @@ bool TDynamicObject::Update(double dt, double dt1) 0.95 * MoverParameters->EnginePowerSource.MaxVoltage : 0.0; } - else if ( true == MoverParameters->Pantographs[end::rear].is_active + else if ( true == MoverParameters->Pantographs[VehicleEnd::rear].is_active && PantDiff < 0.01 ) { if (p->hvPowerWire) { @@ -969,8 +969,8 @@ bool TDynamicObject::Update(double dt, double dt1) } } // koniec pętli po pantografach // TBD, TODO: generate sound event during mover update instead? - if( MoverParameters->Pantographs[end::front].sound_event != MoverParameters->Pantographs[ end::front ].is_active ) { - if( MoverParameters->Pantographs[ end::front ].is_active ) { + if( MoverParameters->Pantographs[VehicleEnd::front].sound_event != MoverParameters->Pantographs[ VehicleEnd::front ].is_active ) { + if( MoverParameters->Pantographs[ VehicleEnd::front ].is_active ) { // pantograph moving up // TBD: add a sound? } @@ -983,10 +983,10 @@ bool TDynamicObject::Update(double dt, double dt1) } } } - MoverParameters->Pantographs[ end::front ].sound_event = MoverParameters->Pantographs[ end::front ].is_active; + MoverParameters->Pantographs[ VehicleEnd::front ].sound_event = MoverParameters->Pantographs[ VehicleEnd::front ].is_active; } - if( MoverParameters->Pantographs[ end::rear ].sound_event != MoverParameters->Pantographs[ end::rear ].is_active ) { - if( MoverParameters->Pantographs[ end::rear ].is_active ) { + if( MoverParameters->Pantographs[ VehicleEnd::rear ].sound_event != MoverParameters->Pantographs[ VehicleEnd::rear ].is_active ) { + if( MoverParameters->Pantographs[ VehicleEnd::rear ].is_active ) { // pantograph moving up // TBD: add a sound? } @@ -999,7 +999,7 @@ bool TDynamicObject::Update(double dt, double dt1) } } } - MoverParameters->Pantographs[ end::rear ].sound_event = MoverParameters->Pantographs[ end::rear ].is_active; + MoverParameters->Pantographs[ VehicleEnd::rear ].sound_event = MoverParameters->Pantographs[ VehicleEnd::rear ].is_active; } } else if (MoverParameters->EnginePowerSource.SourceType == TPowerSource::InternalSource) @@ -1190,20 +1190,20 @@ bool TDynamicObject::Update(double dt, double dt1) else { // unfold mirror on the side with open doors, if not moving too fast if( dMirrorMoveL < 1.0 - && true == MoverParameters->Doors.instances[side::left].open_permit ) { + && true == MoverParameters->Doors.instances[VehicleSide::left].open_permit ) { dMirrorMoveL = std::min( 1.0, dMirrorMoveL + 1.0 * dt1 ); } if( dMirrorMoveR < 1.0 - && true == MoverParameters->Doors.instances[side::right].open_permit ) { + && true == MoverParameters->Doors.instances[VehicleSide::right].open_permit ) { dMirrorMoveR = std::min( 1.0, dMirrorMoveR + 1.0 * dt1 ); } } - play_mirror_sounds( side::left, m_mirrormotion[ side::left ].update( dMirrorMoveL - mirrorleft ) ); - play_mirror_sounds( side::right, m_mirrormotion[ side::right ].update( dMirrorMoveR - mirrorright ) ); + play_mirror_sounds( VehicleSide::left, m_mirrormotion[ VehicleSide::left ].update( dMirrorMoveL - mirrorleft ) ); + play_mirror_sounds( VehicleSide::right, m_mirrormotion[ VehicleSide::right ].update( dMirrorMoveR - mirrorright ) ); // compartment lights // if the vehicle has a controller, we base the light state on state of the controller otherwise we check the vehicle itself @@ -1250,14 +1250,14 @@ void TDynamicObject::pants_up() { d = this; while (d) { - d->MoverParameters->OperatePantographValve(end::front, operation_t::enable, range_t::local); - d->MoverParameters->OperatePantographValve(end::rear, operation_t::enable, range_t::local); + d->MoverParameters->OperatePantographValve(VehicleEnd::front, operation_t::enable, range_t::local); + d->MoverParameters->OperatePantographValve(VehicleEnd::rear, operation_t::enable, range_t::local); d = d->Next(Coupling::control); // pozostałe też } d = Prev(Coupling::control); while (d) { - d->MoverParameters->OperatePantographValve(end::front, operation_t::enable, range_t::local); - d->MoverParameters->OperatePantographValve(end::rear, operation_t::enable, range_t::local); + d->MoverParameters->OperatePantographValve(VehicleEnd::front, operation_t::enable, range_t::local); + d->MoverParameters->OperatePantographValve(VehicleEnd::rear, operation_t::enable, range_t::local); d = d->Prev(Coupling::control); // w drugą stronę też } } diff --git a/vehicle/dynamic/vehicletable.cpp b/vehicle/dynamic/vehicletable.cpp index 7292576cc..689ef28c4 100644 --- a/vehicle/dynamic/vehicletable.cpp +++ b/vehicle/dynamic/vehicletable.cpp @@ -72,7 +72,7 @@ std::vector coupled_train( TDynamicObject *Vehicle ) { std::vector train { Vehicle }; - for( int direction = end::front; direction <= end::rear; ++direction ) { + for (auto const direction : VehicleEnds) { auto *vehicle { Vehicle }; auto side { direction }; // a train of more vehicles than are on the tracks would be one coupled into a ring @@ -86,7 +86,7 @@ coupled_train( TDynamicObject *Vehicle ) { } train.emplace_back( next ); // onwards from the end of the next vehicle away from this one - side = 1 - mover.Neighbours[ side ].vehicle_end; + side = EndOf( 1 - mover.Neighbours[ side ].vehicle_end ); vehicle = next; } } @@ -99,7 +99,7 @@ trains_closing_in( std::vector const &Train ) { std::vector trains; for( auto *vehicle : Train ) { - for( int side = end::front; side <= end::rear; ++side ) { + for (auto const side : VehicleEnds) { auto const &mover { *vehicle->MoverParameters }; auto const &neighbour { mover.Neighbours[ side ] }; if( neighbour.vehicle == nullptr @@ -220,7 +220,7 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { if( mover->accelerating() ) { ++awake.acceleration; } if( mover->LastSwitchingTime < 5 ) { ++awake.switching; } if( mover->is_multiple_unit() ) { ++awake.multipleunit; } - if( moving( mover->Neighbours[ end::front ] ) || moving( mover->Neighbours[ end::rear ] ) ) { ++awake.neighbour; } + if( moving( mover->Neighbours[ VehicleEnd::front ] ) || moving( mover->Neighbours[ VehicleEnd::rear ] ) ) { ++awake.neighbour; } } } } @@ -397,7 +397,7 @@ derail_motion::contact_body contact_body_of( TDynamicObject const &Vehicle ) { std::string_view overlap_kind( TDynamicObject const &First, TDynamicObject const &Second ) { auto const offtrack { First.MoverParameters->OffTrack.active() && Second.MoverParameters->OffTrack.active() }; - for( int end = end::front; end <= end::rear; ++end ) { + for (auto const end : VehicleEnds) { if( First.MoverParameters->Couplers[ end ].Connected == Second.MoverParameters && First.MoverParameters->Couplers[ end ].CouplingFlag != Coupling::none ) { return offtrack ? "coupled, both off the track" : "coupled, one on the rails"; @@ -609,7 +609,7 @@ vehicle_table::update_steps_parallel( double const Deltatime, int const Iteratio return Index; }; for( std::size_t index = 0; index < itemcount; ++index ) { auto const *mover { m_items[ index ]->MoverParameters }; - for( auto const end : { end::front, end::rear } ) { + for (auto const end : VehicleEnds) { auto const *neighbour { mover->Neighbours[ end ].vehicle }; if( ( mover->Couplers[ end ].Connected != nullptr ) && ( ( neighbour == nullptr ) || ( neighbour->MoverParameters != mover->Couplers[ end ].Connected ) ) ) { diff --git a/vehicle/dynamic/visual.cpp b/vehicle/dynamic/visual.cpp index 3f01e16de..5d7e83562 100644 --- a/vehicle/dynamic/visual.cpp +++ b/vehicle/dynamic/visual.cpp @@ -126,8 +126,8 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) // display _xon if connected with another vehicle and not the coupling owner // display _xon if not connected, but equipped with coupling adapter // display _off if not connected, not equipped with coupling adapter or if _xon model is missing - if( MoverParameters->Couplers[ end::front ].CouplingFlag.HasAll(Coupling::coupler) ) { - if( MoverParameters->Couplers[ end::front ].Render ) { + if( MoverParameters->Couplers[ VehicleEnd::front ].CouplingFlag.HasAll(Coupling::coupler) ) { + if( MoverParameters->Couplers[ VehicleEnd::front ].Render ) { btCoupler1.TurnOn(); } else { @@ -136,13 +136,13 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) btnOn = true; } else { - if( true == MoverParameters->Couplers[ end::front ].has_adapter() ) { + if( true == MoverParameters->Couplers[ VehicleEnd::front ].has_adapter() ) { btCoupler1.TurnxOnWithOffAsFallback(); btnOn = true; } } - if( MoverParameters->Couplers[ end::rear ].CouplingFlag.HasAll(Coupling::coupler) ) { - if( MoverParameters->Couplers[ end::rear ].Render ) { + if( MoverParameters->Couplers[ VehicleEnd::rear ].CouplingFlag.HasAll(Coupling::coupler) ) { + if( MoverParameters->Couplers[ VehicleEnd::rear ].Render ) { btCoupler2.TurnOn(); } else { @@ -151,7 +151,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) btnOn = true; } else { - if( true == MoverParameters->Couplers[ end::rear ].has_adapter() ) { + if( true == MoverParameters->Couplers[ VehicleEnd::rear ].has_adapter() ) { btCoupler2.TurnxOnWithOffAsFallback(); btnOn = true; } @@ -168,7 +168,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) SetPneumatic(true, true); // ktore z nich nalezy SetPneumatic(false, true); // wyswietlic w tej klatce - if (MoverParameters->Couplers[end::front].CouplingFlag.HasAll(Coupling::brakeHose)) + if (MoverParameters->Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::brakeHose)) { switch (cp1) { @@ -188,7 +188,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) btnOn = true; } - if (MoverParameters->Couplers[end::rear].CouplingFlag.HasAll(Coupling::brakeHose)) + if (MoverParameters->Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::brakeHose)) { switch (cp2) { @@ -209,7 +209,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } // przewody zasilajace, j.w. (yB) - if (MoverParameters->Couplers[end::front].CouplingFlag.HasAll(Coupling::mainHose)) + if (MoverParameters->Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::mainHose)) { switch (sp1) { @@ -229,7 +229,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) btnOn = true; } - if (MoverParameters->Couplers[end::rear].CouplingFlag.HasAll(Coupling::mainHose)) + if (MoverParameters->Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::mainHose)) { switch (sp2) { @@ -254,18 +254,18 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) { // przewody powietrzne j.w., ABu: decyzja czy rysowac tylko na podstawie // 'render' - if (MoverParameters->Couplers[end::front].CouplingFlag.HasAll(Coupling::brakeHose)) + if (MoverParameters->Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::brakeHose)) { - if (MoverParameters->Couplers[end::front].Render) + if (MoverParameters->Couplers[VehicleEnd::front].Render) btCPneumatic1.TurnOn(); else btCPneumatic1r.TurnOn(); btnOn = true; } - if (MoverParameters->Couplers[end::rear].CouplingFlag.HasAll(Coupling::brakeHose)) + if (MoverParameters->Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::brakeHose)) { - if (MoverParameters->Couplers[end::rear].Render) + if (MoverParameters->Couplers[VehicleEnd::rear].Render) btCPneumatic2.TurnOn(); else btCPneumatic2r.TurnOn(); @@ -348,36 +348,36 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) if (MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable) { // sygnaly konca pociagu if (m_endsignals1.Active()) { - if (TestFlag(MoverParameters->iLights[end::front], light::redmarker_left | light::redmarker_right ) ) { + if (TestFlag(MoverParameters->iLights[VehicleEnd::front], light::redmarker_left | light::redmarker_right ) ) { m_endsignals1.Turn( true ); btnOn = true; } } else { - if (TestFlag(MoverParameters->iLights[end::front], light::redmarker_left) && !HeadlightsAoff) + if (TestFlag(MoverParameters->iLights[VehicleEnd::front], light::redmarker_left) && !HeadlightsAoff) { m_endsignal13.Turn( true ); btnOn = true; } - if (TestFlag(MoverParameters->iLights[end::front], light::redmarker_right) && !HeadlightsAoff) + if (TestFlag(MoverParameters->iLights[VehicleEnd::front], light::redmarker_right) && !HeadlightsAoff) { m_endsignal12.Turn( true ); btnOn = true; } } if (m_endsignals2.Active()) { - if (TestFlag(MoverParameters->iLights[end::rear], light::redmarker_left | light::redmarker_right ) ) { + if (TestFlag(MoverParameters->iLights[VehicleEnd::rear], light::redmarker_left | light::redmarker_right ) ) { m_endsignals2.Turn( true ); btnOn = true; } } else { - if (TestFlag(MoverParameters->iLights[end::rear], light::redmarker_left) && !HeadlightsBoff) + if (TestFlag(MoverParameters->iLights[VehicleEnd::rear], light::redmarker_left) && !HeadlightsBoff) { m_endsignal23.Turn( true ); btnOn = true; } - if (TestFlag(MoverParameters->iLights[end::rear], light::redmarker_right) && !HeadlightsBoff) + if (TestFlag(MoverParameters->iLights[VehicleEnd::rear], light::redmarker_right) && !HeadlightsBoff) { m_endsignal22.Turn( true ); btnOn = true; @@ -385,12 +385,12 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } } // tablice blaszane: - if (TestFlag(MoverParameters->iLights[end::front], light::rearendsignals)) { + if (TestFlag(MoverParameters->iLights[VehicleEnd::front], light::rearendsignals)) { m_endtab1.Turn( true ); btnOn = true; } // else btEndSignalsTab1.TurnOff(); - if (TestFlag(MoverParameters->iLights[end::rear], light::rearendsignals)) { + if (TestFlag(MoverParameters->iLights[VehicleEnd::rear], light::rearendsignals)) { m_endtab2.Turn( true ); btnOn = true; } @@ -438,7 +438,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) // ograniczeń odległości, by były widoczne z // daleka - if (TestFlag(MoverParameters->iLights[end::front], light::headlight_left) + if (TestFlag(MoverParameters->iLights[VehicleEnd::front], light::headlight_left) && !HeadlightsAoff && !HighBeamLights) { if( DimHeadlights ) { @@ -449,7 +449,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } btnOn = true; } - if (TestFlag(MoverParameters->iLights[end::front], light::headlight_upper) + if (TestFlag(MoverParameters->iLights[VehicleEnd::front], light::headlight_upper) && !HeadlightsAoff) { if( DimHeadlights ) { @@ -460,7 +460,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } btnOn = true; } - if (TestFlag(MoverParameters->iLights[end::front], light::headlight_right) + if (TestFlag(MoverParameters->iLights[VehicleEnd::front], light::headlight_right) && !HeadlightsAoff && !HighBeamLights) { if( DimHeadlights ) { @@ -472,7 +472,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) btnOn = true; } // else btHeadSignals13.TurnOff(); - if (TestFlag(MoverParameters->iLights[end::rear], light::headlight_left) + if (TestFlag(MoverParameters->iLights[VehicleEnd::rear], light::headlight_left) && !HeadlightsBoff && !HighBeamLights) { if( DimHeadlights ) { @@ -483,7 +483,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } btnOn = true; } - if (TestFlag(MoverParameters->iLights[end::rear], light::headlight_upper) + if (TestFlag(MoverParameters->iLights[VehicleEnd::rear], light::headlight_upper) && !HeadlightsBoff) { if( DimHeadlights ) { @@ -494,7 +494,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } btnOn = true; } - if (TestFlag(MoverParameters->iLights[end::rear], light::headlight_right) + if (TestFlag(MoverParameters->iLights[VehicleEnd::rear], light::headlight_right) && !HeadlightsBoff && !HighBeamLights) { if( DimHeadlights ) { @@ -506,7 +506,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) btnOn = true; } // auxiliary lights - if (TestFlag(MoverParameters->iLights[end::front], light::auxiliary_left) && !HeadlightsAoff) + if (TestFlag(MoverParameters->iLights[VehicleEnd::front], light::auxiliary_left) && !HeadlightsAoff) { if( DimHeadlights ) { m_headsignal13.TurnxOnWithOnAsFallback(); @@ -516,7 +516,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } btnOn = true; } - if (TestFlag(MoverParameters->iLights[end::front], light::auxiliary_right) && !HeadlightsAoff) + if (TestFlag(MoverParameters->iLights[VehicleEnd::front], light::auxiliary_right) && !HeadlightsAoff) { if( DimHeadlights ) { m_headsignal12.TurnxOnWithOnAsFallback(); @@ -526,7 +526,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } btnOn = true; } - if (TestFlag(MoverParameters->iLights[end::rear], light::auxiliary_left) && !HeadlightsBoff) + if (TestFlag(MoverParameters->iLights[VehicleEnd::rear], light::auxiliary_left) && !HeadlightsBoff) { if( DimHeadlights ) { m_headsignal23.TurnxOnWithOnAsFallback(); @@ -536,7 +536,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } btnOn = true; } - if (TestFlag(MoverParameters->iLights[end::rear], light::auxiliary_right) && !HeadlightsBoff) + if (TestFlag(MoverParameters->iLights[VehicleEnd::rear], light::auxiliary_right) && !HeadlightsBoff) { if( DimHeadlights ) { m_headsignal22.TurnxOnWithOnAsFallback(); @@ -548,26 +548,26 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } // logika dlugich - if (TestFlag(MoverParameters->iLights[end::front], light::headlight_left) + if (TestFlag(MoverParameters->iLights[VehicleEnd::front], light::headlight_left) && !HeadlightsAoff && HighBeamLights) m_highbeam13.TurnxOnWithOnAsFallback(); else m_highbeam13.TurnOff(); - if (TestFlag(MoverParameters->iLights[end::front], light::headlight_right) + if (TestFlag(MoverParameters->iLights[VehicleEnd::front], light::headlight_right) && !HeadlightsAoff && HighBeamLights) m_highbeam12.TurnxOnWithOnAsFallback(); else m_highbeam12.TurnOff(); // i to samo od dupy strony - if (TestFlag(MoverParameters->iLights[end::rear], light::headlight_left) + if (TestFlag(MoverParameters->iLights[VehicleEnd::rear], light::headlight_left) && !HeadlightsBoff && HighBeamLights) m_highbeam23.TurnxOnWithOnAsFallback(); else m_highbeam23.TurnOff(); - if (TestFlag(MoverParameters->iLights[end::rear], light::headlight_right) + if (TestFlag(MoverParameters->iLights[VehicleEnd::rear], light::headlight_right) && !HeadlightsBoff && HighBeamLights) m_highbeam22.TurnxOnWithOnAsFallback(); else diff --git a/vehicle/enginestart.cpp b/vehicle/enginestart.cpp index a1178196e..df29fae07 100644 --- a/vehicle/enginestart.cpp +++ b/vehicle/enginestart.cpp @@ -59,7 +59,7 @@ TMoverParameters *engine(TMoverParameters const &Occupied, TMoverParameters &Con // the cab's own vehicle is the first one auto others{Number - 1}; // behind the cab is the rear end of a vehicle driven from its front cab, and the other way round - int const behind{Occupied.CabOccupied < 0 ? end::front : end::rear}; + int const behind{NumberOf(Occupied.CabOccupied < 0 ? VehicleEnd::front : VehicleEnd::rear)}; if (auto *found{find_along(Occupied, behind, Controlled, others)}; found != nullptr) { return found; } diff --git a/vehicle/lightsprogrammer.h b/vehicle/lightsprogrammer.h index c603ace27..bf9728b1e 100644 --- a/vehicle/lightsprogrammer.h +++ b/vehicle/lightsprogrammer.h @@ -23,18 +23,18 @@ struct consist_lights { int rear; }; -// Cablights: the selector's lights for the occupied cab's front and back (Lights[end::front / end::rear]). +// Cablights: the selector's lights for the occupied cab's front and back (Lights[VehicleEnd::front / VehicleEnd::rear]). // Cabfacinghead: the occupied cab faces the head of the consist. -// Direction: the vehicle's iDirection, 1 when its end::front is towards the head of the consist. -// Coupled: whether another vehicle is coupled at the vehicle's end::front / end::rear; an end with a coupled +// Direction: the vehicle's iDirection, 1 when its VehicleEnd::front is towards the head of the consist. +// Coupled: whether another vehicle is coupled at the vehicle's VehicleEnd::front / VehicleEnd::rear; an end with a coupled // vehicle stays dark -inline consist_lights vehicle_lights(std::array const &Cablights, bool const Cabfacinghead, int const Direction, std::array const &Coupled) { - auto const headlights{Cablights[Cabfacinghead ? end::front : end::rear]}; - auto const rearlights{Cablights[Cabfacinghead ? end::rear : end::front]}; +inline consist_lights vehicle_lights(ByEnd const &Cablights, bool const Cabfacinghead, int const Direction, ByEnd const &Coupled) { + auto const headlights{Cablights[Cabfacinghead ? VehicleEnd::front : VehicleEnd::rear]}; + auto const rearlights{Cablights[Cabfacinghead ? VehicleEnd::rear : VehicleEnd::front]}; // the head lights go to the vehicle's end towards the head of the consist whichever way the cab faces, // so the coupling which keeps them dark is the one at that same end (eu07/maszyna#395) - auto const headend{Direction > 0 ? end::front : end::rear}; - auto const rearend{Direction > 0 ? end::rear : end::front}; + auto const headend{Direction > 0 ? VehicleEnd::front : VehicleEnd::rear}; + auto const rearend{Direction > 0 ? VehicleEnd::rear : VehicleEnd::front}; return {Coupled[headend] ? 0 : headlights, Coupled[rearend] ? 0 : rearlights}; } diff --git a/widgets/vehicleparams.cpp b/widgets/vehicleparams.cpp index 02b924bad..86966de40 100644 --- a/widgets/vehicleparams.cpp +++ b/widgets/vehicleparams.cpp @@ -63,9 +63,9 @@ void ui::vehicleparams_panel::draw_mini(const TMoverParameters &mover) { ImGui::Image((ImTextureID)(intptr_t)(tex.get_id()), ImVec2(x, y), ImVec2(0, 1), ImVec2(1, 0)); - if (mover.Pantographs[end::rear].is_active) + if (mover.Pantographs[VehicleEnd::rear].is_active) draw_infobutton("╨╨╨", ImVec2(126, 10)); - if (mover.Pantographs[end::front].is_active) + if (mover.Pantographs[VehicleEnd::front].is_active) draw_infobutton("╨╨╨", ImVec2(290, 10)); if (mover.Battery) @@ -80,17 +80,17 @@ void ui::vehicleparams_panel::draw_mini(const TMoverParameters &mover) if (mover.WarningSignal) draw_infobutton(STR_C("horn"), ImVec2(361, 11)); - if (mover.iLights[end::front] & light::redmarker_left) + if (mover.iLights[VehicleEnd::front] & light::redmarker_left) draw_infobutton("o", ImVec2(490, 71), ImVec4(1.0f, 0.0f, 0.0f, 1.0f)); - else if (mover.iLights[end::front] & light::headlight_left) + else if (mover.iLights[VehicleEnd::front] & light::headlight_left) draw_infobutton("O", ImVec2(490, 71), ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); - if (mover.iLights[end::front] & light::redmarker_right) + if (mover.iLights[VehicleEnd::front] & light::redmarker_right) draw_infobutton("o", ImVec2(443, 71), ImVec4(1.0f, 0.0f, 0.0f, 1.0f)); - else if (mover.iLights[end::front] & light::headlight_right) + else if (mover.iLights[VehicleEnd::front] & light::headlight_right) draw_infobutton("O", ImVec2(443, 71), ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); - if (mover.iLights[end::front] & light::headlight_upper) + if (mover.iLights[VehicleEnd::front] & light::headlight_upper) draw_infobutton("O", ImVec2(467, 18), ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); } ImGui::EndChild(); @@ -148,8 +148,8 @@ void ui::vehicleparams_panel::render_contents() std::snprintf(buffer.data(), buffer.size(), STR_C("Devices: %c%c%c%c%c%c%c%c%c%c%c%c%c%c%s%s\nPower transfers: %.0f@%.0f%s%s%s%.0f@%.0f"), // devices - (mover.Battery ? 'B' : '.'), (mover.Mains ? 'M' : '.'), (mover.FuseFlag ? '!' : '.'), (mover.Pantographs[end::rear].is_active ? (mover.PantRearVolt > 0.0 ? 'O' : 'o') : '.'), - (mover.Pantographs[end::front].is_active ? (mover.PantFrontVolt > 0.0 ? 'P' : 'p') : '.'), (mover.PantPressLockActive ? '!' : (mover.PantPressSwitchActive ? '*' : '.')), + (mover.Battery ? 'B' : '.'), (mover.Mains ? 'M' : '.'), (mover.FuseFlag ? '!' : '.'), (mover.Pantographs[VehicleEnd::rear].is_active ? (mover.PantRearVolt > 0.0 ? 'O' : 'o') : '.'), + (mover.Pantographs[VehicleEnd::front].is_active ? (mover.PantFrontVolt > 0.0 ? 'P' : 'p') : '.'), (mover.PantPressLockActive ? '!' : (mover.PantPressSwitchActive ? '*' : '.')), (mover.WaterPump.is_active ? 'W' : (false == mover.WaterPump.breaker ? '-' : (mover.WaterPump.is_enabled ? 'w' : '.'))), (true == mover.WaterHeater.is_damaged ? '!' : (mover.WaterHeater.is_active ? 'H' : (false == mover.WaterHeater.breaker ? '-' : (mover.WaterHeater.is_enabled ? 'h' : '.')))), (mover.FuelPump.is_active ? 'F' : (mover.FuelPump.is_enabled ? 'f' : '.')), (mover.OilPump.is_active ? 'O' : (mover.OilPump.is_enabled ? 'o' : '.')), @@ -157,9 +157,9 @@ void ui::vehicleparams_panel::render_contents() (mover.CompressorFlag ? 'C' : (false == mover.CompressorAllowLocal ? '-' : ((mover.CompressorAllow || mover.CompressorStart == start_t::automatic) ? 'c' : '.'))), (mover.CompressorGovernorLock ? '!' : '.'), "", std::string(isdieselenginepowered ? STR(" oil pressure: ") + to_string(mover.OilPump.pressure, 2) : "").c_str(), // power transfers - mover.Couplers[end::front].power_high.voltage, mover.Couplers[end::front].power_high.current, std::string(mover.Couplers[end::front].power_high.is_local ? "" : "-").c_str(), - std::string(vehicle.DirectionGet() ? ":<<:" : ":>>:").c_str(), std::string(mover.Couplers[end::rear].power_high.is_local ? "" : "-").c_str(), - mover.Couplers[end::rear].power_high.voltage, mover.Couplers[end::rear].power_high.current); + mover.Couplers[VehicleEnd::front].power_high.voltage, mover.Couplers[VehicleEnd::front].power_high.current, std::string(mover.Couplers[VehicleEnd::front].power_high.is_local ? "" : "-").c_str(), + std::string(vehicle.DirectionGet() ? ":<<:" : ":>>:").c_str(), std::string(mover.Couplers[VehicleEnd::rear].power_high.is_local ? "" : "-").c_str(), + mover.Couplers[VehicleEnd::rear].power_high.voltage, mover.Couplers[VehicleEnd::rear].power_high.current); ImGui::TextUnformatted(buffer.data()); @@ -172,8 +172,8 @@ void ui::vehicleparams_panel::render_contents() // engine mover.EnginePower, std::abs(mover.TrainType == train_type::emu ? mover.ShowCurrent(0) : mover.Im), // revolutions - std::abs(mover.enrot) * 60, std::abs(mover.nrot) * mover.Transmision.Ratio * 60, mover.RventRot * 60, std::abs(mover.MotorBlowers[end::front].revolutions), - std::abs(mover.MotorBlowers[end::rear].revolutions), mover.diesel.heat.rpmw, mover.diesel.heat.rpmw2); + std::abs(mover.enrot) * 60, std::abs(mover.nrot) * mover.Transmision.Ratio * 60, mover.RventRot * 60, std::abs(mover.MotorBlowers[VehicleEnd::front].revolutions), + std::abs(mover.MotorBlowers[VehicleEnd::rear].revolutions), mover.diesel.heat.rpmw, mover.diesel.heat.rpmw2); ImGui::TextUnformatted(buffer.data()); From 401995d4e2c0a2027253f7dcc946d513d5b9e1e5 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sat, 28 Nov 2026 19:04:54 +0100 Subject: [PATCH 025/123] refactor(vehicle): the giant functions of the vehicle and the cab split into named steps The four largest functions of the vehicle code become short sequences of calls to named private helpers; the code moves verbatim, in the same order: - TDynamicObject::LoadMMediaFile (2036 lines, now ~50): a helper for each section of the .mmd (models, sounds, locations, internaldata) and for the finish; the long keyword chains split into groups tried in their old order, each group telling whether it took the keyword, so a keyword still goes to the first branch that matches it and no other - TTrain::Update (1389 lines, now ~90): the line breaker, the timers, the states of the units in multiple, the gauges, the lamps (with the low voltage and without it), the controllers, the switches and the buttons - TDynamicObject::Update (1168 lines, now ~125): the track, the couplers, the traction voltage, the AI, the braking of a consist of induction motors (its locals gathered in InductionBrakeState, of the very types auto gave them), the movement, the clatter of the axles, the pantographs, the wipers and the mirrors - TDynamicObject::RenderSounds (813 lines, now ~50) and powertrain_sounds::render (506 lines, now ~17): a helper for each subsystem; the volume and the frequency, shared by the whole function before, are locals of the helpers that use them, each written before it is read as it was The helpers of LoadMMediaFile keep the indentation of the old function, so the diff shows only the seams. No change in behaviour: 1144/1144 tests, golden traces exact against staging 62f7a29b. --- vehicle/DynObj.h | 99 +++ vehicle/Train.h | 30 + vehicle/cab/update.cpp | 781 ++++++++++++-------- vehicle/dynamic/mmd.cpp | 292 ++++++-- vehicle/dynamic/sounds.cpp | 228 +++++- vehicle/dynamic/update.cpp | 1430 ++++++++++++++++++++---------------- 6 files changed, 1854 insertions(+), 1006 deletions(-) diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index bd6fba732..acf6c0461 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -477,6 +477,20 @@ private: void position( glm::vec3 const Location ); void render( TMoverParameters const &Vehicle, double const Deltatime ); + private: + // the parts of render(), by subsystem + void renderPumpSounds( TMoverParameters const &Vehicle ); + void renderIgnitionSounds( TMoverParameters const &Vehicle ); + void renderEngineSounds( TMoverParameters const &Vehicle, double const Deltatime ); + void renderTurboSound( TMoverParameters const &Vehicle, double const Deltatime ); + void renderClutchSound( TMoverParameters const &Vehicle ); + void renderRetarderSound( TMoverParameters const &Vehicle ); + void renderTractionMotorSounds( TMoverParameters const &Vehicle, double const Deltatime ); + void renderMotorBlowerSounds( TMoverParameters const &Vehicle ); + void renderInverterSound( TMoverParameters const &Vehicle ); + void renderFanSounds( TMoverParameters const &Vehicle ); + void renderRelaySounds( TMoverParameters const &Vehicle ); + void renderTransmissionSound( TMoverParameters const &Vehicle ); }; // single source per door (pair) on the centreline struct doorspeaker_sounds { @@ -739,6 +753,36 @@ private: // feeds the script destination sign with fresh data, when it is shown and due void update_script_destination(); bool Update(double dt, double dt1); +private: + // the steps of Update() (vehicle/dynamic/update.cpp) + struct InductionBrakeState; + void updateTrackParameters(); + void updateCouplingState(); + void updateTractionVoltage( double dt1 ); + void updateDriver( double dt1 ); + void distributeInductionBraking( double dt1 ); + void setInductionControl( InductionBrakeState &state, double dt1 ); + void sumConsistBrakeForces( InductionBrakeState &state ); + void computeBrakeDeceleration( InductionBrakeState &state ); + void updateShuntMode( InductionBrakeState &state ); + void computeBrakeDemand( InductionBrakeState &state, double dt1 ); + void openMedLog( InductionBrakeState const &state ); + void computeElectrodynamicDemand( InductionBrakeState &state, double dt1 ); + void distributeBrakeForces( InductionBrakeState &state, double dt1 ); + void recordMedState( InductionBrakeState const &state, double dt1 ); + void switchOffMainsWithoutBattery(); + double moveByPhysics( double dt, double dt1 ); + void updateAxleClatter( double dDOMoveLen ); + void applyJointJolt( int axleindex ); + void updateWheelAngles( double dt1 ); + void updateCurrentCollectors( double dt1 ); + void updatePantograph( int i, double fPantCurrent, double &fCurrent, double dt1 ); + void updatePantographVoltage( int i, TAnimPant const *p, double PantDiff, double fPantCurrent, double &fCurrent, double dt1 ); + void updatePantographMotion( int i, TAnimPant *p, double PantDiff, double dt1 ); + void playPantographDropSounds(); + void updateWipers( double dt1 ); + void updateMirrors( double dt1 ); +public: bool FastUpdate(double dt); void Move(double fDistance); void FastMove(double fDistance); @@ -798,6 +842,29 @@ private: void place_off_track(); public: void RenderSounds(); +private: + // the parts of RenderSounds(), by subsystem + void renderAuxiliarySounds(); + void renderBrakeCylinderSounds( double const brakepressureratio ); + void renderEpBrakeSounds( double const dt ); + void renderEmergencyBrakeSound(); + void renderAirReleaseSounds( double const dt, double const brakepressureratio ); + void renderSlipAndSandSounds(); + double renderBrakeFrictionSounds( double const dt ); + void renderSpringBrakeSounds(); + void renderLoadExchangeSounds(); + void renderDepartureSignalSounds(); + void renderAnnouncementSounds(); + void renderDoorSounds(); + void renderHornSounds(); + void renderRunningNoise( double const brakeforceratio ); + void renderWheelFlatSound(); + void renderCurveSound(); + void renderStartJoltSound(); + void renderMoverEventSounds(); + void renderCouplerSounds(); + void renderDerailmentSounds(); +public: // plays the sounds of the mirrors on the Side, of the occupied cab, starting the Event void play_mirror_sounds( VehicleSide const Side, mirror_moves::event const Event ); inline glm::dvec3 GetPosition() const { @@ -850,6 +917,38 @@ public: // McZapkie-260202 void LoadMMediaFile(std::string const &TypeName, std::string const &ReplacableSkin); + // the parts of LoadMMediaFile (vehicle/dynamic/mmd.cpp): the sections of the .mmd file, their groups of keywords and the end of loading +private: + void loadModelsSection( cParser &parser, std::string &token, std::string &asAnimName, std::string const &asFileName, std::string const &ReplacableSkin ); + void loadModelsKeyword( cParser &parser, std::string &token, std::string &asAnimName, std::string const &asFileName ); + bool loadModelsGeneralKeyword( cParser &parser, std::string &token, std::string &asAnimName ); + bool loadModelsWheelKeyword( cParser &parser, std::string &token, std::string &asAnimName ); + bool loadModelsPantographLowerKeyword( cParser &parser, std::string &token, std::string &asAnimName, std::string const &asFileName ); + bool loadModelsPantographUpperKeyword( cParser &parser, std::string &token, std::string &asAnimName, std::string const &asFileName ); + bool loadModelsLinkageKeyword( cParser &parser, std::string &token, std::string &asAnimName, std::string const &asFileName ); + bool loadModelsDoorKeyword( cParser &parser, std::string &token, std::string &asAnimName, std::string const &asFileName ); + void loadModelsMirrorWiperKeyword( cParser &parser, std::string &token, std::string &asAnimName ); + void loadSoundsSection( cParser &parser, std::string &token ); + void loadSoundsKeyword( cParser &parser, std::string &token ); + bool loadSoundsEngineKeyword( cParser &parser, std::string &token ); + bool loadSoundsMotorKeyword( cParser &parser, std::string_view token ); + bool loadSoundsBrakeKeyword( cParser &parser, std::string_view token ); + bool loadSoundsDeviceKeyword( cParser &parser, std::string_view token ); + bool loadSoundsDoorKeyword( cParser &parser, std::string_view token ); + bool loadSoundsOtherKeyword( cParser &parser, std::string_view token ); + void loadSoundsAnnouncementKeyword( cParser &parser, std::string &token ); + void loadLocationsSection( cParser &parser, std::string &token ); + void loadInternalDataSection( cParser &parser, std::string &token ); + void loadInternalDataKeyword( cParser &parser, std::string &token ); + bool loadInternalDataDeviceKeyword( cParser &parser, std::string &token ); + bool loadInternalDataCouplerKeyword( cParser &parser, std::string_view token ); + bool loadInternalDataBufferKeyword( cParser &parser, std::string_view token ); + void loadInternalDataCabKeyword( cParser &parser, std::string_view token ); + void finishLoadingMMediaFile( std::string const &asFileName, std::string const &ReplacableSkin ); + void assignDefaultMMediaSounds(); + void initMMediaModels(); + void positionMMediaSoundEmitters(); +public: TModel3d *LoadMMediaFile_mdload( std::string const &Name ) const; inline double ABuGetDirection() const { // ABu. diff --git a/vehicle/Train.h b/vehicle/Train.h index 9c017a628..7ef51c28d 100644 --- a/vehicle/Train.h +++ b/vehicle/Train.h @@ -180,6 +180,36 @@ class TTrain { float universal_position( int const Index ) const; void UpdateCab(); bool Update( double const Deltatime ); + // the parts of Update, in the order it calls them (vehicle/cab/update.cpp) + private: + void updateLineBreakerState( double const Deltatime ); + void updateTimers( double const Deltatime ); + void updateDoorAndDirectionStates(); + void processReceivedCommands(); + void returnMasterController( double const Deltatime ); + void updateTachometer( double const Deltatime ); + void updateVoltagesAndCurrents(); + void resetUnitStates(); + void updateUnitStates(); + void completeUnitStates( int const in ); + void updateFeedbackGauges() const; + void updateConverterOverload( double const Deltatime ); + void updateSecondUnitGauges(); + void updateClock(); + void updateEngineGauges(); + void updateBasicLamps(); + void updateCircuitLamps( double const Deltatime ); + void updateTrainLamps(); + void turnOffLamps(); + void updateSecondUnitLamps( bool const lowvoltagepower ); + void updateMasterControllers( bool const lowvoltagepower ); + void updateBrakeControllers(); + void updateCabSwitches( bool const lowvoltagepower ); + void updateHeatingAndInstrumentLights(); + void updateButtons(); + void updateAuxiliaryButtons( bool const lowvoltagepower ); + void updateCabLightLevels(); + public: void UpdateDirectionRelays(); void SetupDirectionRelays(); bool prevBatState = false; diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index 23441daa4..987591455 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -50,6 +50,95 @@ http://mozilla.org/MPL/2.0/. bool TTrain::Update(double const Deltatime) { // train state update + updateLineBreakerState(Deltatime); + // the switches of the other vehicles in multiple + update_remote_linebreakers(Deltatime); + updateTimers(Deltatime); + updateDoorAndDirectionStates(); + processReceivedCommands(); + + UpdateCab(); + + returnMasterController(Deltatime); + updateTachometer(Deltatime); + updateVoltagesAndCurrents(); + updateUnitStates(); + updateFeedbackGauges(); + updateConverterOverload(Deltatime); + auto const lowvoltagepower{mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable}; + + updateSecondUnitGauges(); + updateClock(); + + Cabine[iCabn].Update(lowvoltagepower); // nowy sposób ustawienia animacji + /* + if (ggZbS.SubModel) + { + ggZbS.UpdateValue(mvOccupied->Handle->GetCP()); + ggZbS.Update(); + } + */ + // replacement for the above. TODO: move it to a more suitable place + m_brakehandlecp = mvOccupied->Handle->GetCP(); + + updateEngineGauges(); + updateBasicLamps(); + + if (true == lowvoltagepower) + { + updateCircuitLamps(Deltatime); + updateTrainLamps(); + } + else + { + turnOffLamps(); + } + + updateSecondUnitLamps(lowvoltagepower); + updateMasterControllers(lowvoltagepower); + updateBrakeControllers(); + updateCabSwitches(lowvoltagepower); + updateHeatingAndInstrumentLights(); + updateButtons(); + updateAuxiliaryButtons(lowvoltagepower); + + // wyprowadzenie sygnałów dla haslera na PoKeys (zaznaczanie na taśmie) + btHaslerBrakes.Turn(mvOccupied->BrakePress > 0.4); // ciśnienie w cylindrach + btHaslerCurrent.Turn(mvOccupied->Im != 0.0); // prąd na silnikach + + updateCabLightLevels(); + + // anti slip system activation, maintained while the control button is down + if (mvOccupied->BrakeSystem != TBrakeSystem::ElectroPneumatic && ggAntiSlipButton.GetDesiredValue() > 0.95) + { + mvControlled->AntiSlippingBrake(); + } + // screens + + if (!FreeFlyModeFlag && simulation::Train == this) // don't bother if we're outside + { + update_screens(Deltatime); + update_script_screens(); + } + + // update direction relay + if (prevBatState != mvOccupied->Power24vIsAvailable) + SetupDirectionRelays(); + if (prevDirection != mvOccupied->DirActive) + UpdateDirectionRelays(); + + prevBatState = mvOccupied->Power24vIsAvailable; + prevDirection = mvOccupied->DirActive; + + // sounds + update_sounds(Deltatime); + + return true; //(DynamicObject->Update(dt)); +} // koniec update + +// keeps the state of the line breaker in step with the vehicle and with the buttons that close and open it +void TTrain::updateLineBreakerState(double const Deltatime) +{ // line breaker: if (m_linebreakerstate == linebreaker::state::open && true == mvControlled->Mains) { @@ -110,8 +199,11 @@ bool TTrain::Update(double const Deltatime) // try to finalize state change of the line breaker, set the state based on the outcome m_linebreakerstate = mvControlled->MainSwitch(true, mvControlled->MainSwitchRange()) ? linebreaker::state::closed : linebreaker::state::open; } - // the switches of the other vehicles in multiple - update_remote_linebreakers(Deltatime); +} + +// counts down the door permit, the train length measurement and the battery timers +void TTrain::updateTimers(double const Deltatime) +{ // door permits for (auto idx = 0; idx < 2; ++idx) { @@ -142,7 +234,11 @@ bool TTrain::Update(double const Deltatime) if (fBatteryTimer < 0.f) fBatteryTimer = -1.f; } +} +// sets the helper flags of the open doors, the door permits and the direction of travel +void TTrain::updateDoorAndDirectionStates() +{ // helper variables if (DynamicObject->Mechanik != nullptr) { @@ -160,7 +256,11 @@ bool TTrain::Update(double const Deltatime) m_dirforward = mvControlled->DirActive > 0; m_dirneutral = mvControlled->DirActive == 0; m_dirbackward = mvControlled->DirActive < 0; +} +// passes the user commands received by the vehicle to their handlers +void TTrain::processReceivedCommands() +{ // check for received user commands // NOTE: this is a temporary arrangement, for the transition period from old command setup to the new one // eventually commands are going to be retrieved directly by the vehicle, filtered through active control stand @@ -182,9 +282,11 @@ bool TTrain::Update(double const Deltatime) lookup->second(this, commanddata); } } +} - UpdateCab(); - +// moves the master controller a step towards the actual position of the switch group when the driver leaves it (ET40, EP05, camshaft) +void TTrain::returnMasterController(double const Deltatime) +{ // nie blokujemy AI if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag && (mvOccupied->TrainType == train_type::et40 || mvOccupied->TrainType == train_type::ep05 || mvOccupied->HasCamshaft)) { @@ -214,7 +316,11 @@ bool TTrain::Update(double const Deltatime) } } } +} +// sets the speed shown by the tachometer, its jumps and the ticking of the speed recorder +void TTrain::updateTachometer(double const Deltatime) +{ // McZapkie: predkosc wyswietlana na tachometrze brana jest z obrotow kol auto const maxtacho{3.0}; @@ -247,7 +353,11 @@ bool TTrain::Update(double const Deltatime) // schodz powoli - niektore haslery to ze 4 sekundy potrafia stukac fTachoCount = static_cast(std::max(0.0, fTachoCount - Deltatime * 0.66)); } +} +// sets the high voltage and the currents shown in the cab, of the controlled vehicle or of the second unit +void TTrain::updateVoltagesAndCurrents() +{ // Ra 2014-09: napięcia i prądy muszą być ustalone najpierw, bo wysyłane są ewentualnie na PoKeys if (mvControlled->EngineType != TEngineType::DieselElectric && mvControlled->EngineType != TEngineType::ElectricInductionMotor) { // Ra 2014-09: czy taki rozdzia? ma sens? @@ -283,15 +393,11 @@ bool TTrain::Update(double const Deltatime) fHCurrent[2] = static_cast(mvControlled->ShowCurrent(2)); fHCurrent[3] = static_cast(mvControlled->ShowCurrent(3)); } +} - bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; - TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); - int in = 0; - fEIMParams[0][6] = 0; - iCarNo = 0; - iPowerNo = 0; - iUnitNo = 1; - +// clears the states of the units in multiple before they are read again +void TTrain::resetUnitStates() +{ for (int i = 0; i < 8; i++) { bMains[i] = false; @@ -308,6 +414,20 @@ bool TTrain::Update(double const Deltatime) bHeat[i] = false; } bCompressors.clear(); +} + +// reads the states of the vehicles and the units in multiple, from the cab along the control coupling +void TTrain::updateUnitStates() +{ + bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; + TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); + int in = 0; + fEIMParams[0][6] = 0; + iCarNo = 0; + iPowerNo = 0; + iUnitNo = 1; + + resetUnitStates(); for (int i = 0; i < 20; i++) { if (p) @@ -421,6 +541,12 @@ bool TTrain::Update(double const Deltatime) } } + completeUnitStates(in); +} + +// sets the induction motor values of the whole train and clears the slots of the units after the first in ones +void TTrain::completeUnitStates(int const in) +{ // if (mvControlled == mvOccupied) // fEIMParams[0][3] = mvControlled->inductionMotor.state.forceDemand; // procent zadany // else @@ -444,6 +570,11 @@ bool TTrain::Update(double const Deltatime) fDieselParams[1 + i][j] = 0; } } +} + +// sets the gauges of the PoKeys desk from the state of the cab +void TTrain::updateFeedbackGauges() const +{ #ifdef _WIN32 if (Global.iFeedbackMode == 4) { @@ -464,6 +595,11 @@ bool TTrain::Update(double const Deltatime) Console::ValueSet(6, fTachoVelocity); } #endif +} + +// trips the converter overload relay when the compressor starts too soon after the converter, in the vehicles driven by hand +void TTrain::updateConverterOverload(double const Deltatime) +{ //------------------ // hunter-261211: nadmiarowy przetwornicy i ogrzewania // Ra 15-01: to musi stąd wylecieć - zależności nie mogą być w kabinie @@ -490,8 +626,11 @@ bool TTrain::Update(double const Deltatime) else fConverterTimer = 0; //------------------ - auto const lowvoltagepower{mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable}; +} +// sets the current, the water temperature and the oil pressure gauges of the second unit +void TTrain::updateSecondUnitGauges() +{ // youBy - prad w drugim czlonie: galaz lub calosc { TDynamicObject const *tmp{nullptr}; @@ -533,6 +672,11 @@ bool TTrain::Update(double const Deltatime) } } } +} + +// sets the hands of the cab clock +void TTrain::updateClock() +{ // McZapkie-300302: zegarek if (ggClockMInd.SubModel) { @@ -543,18 +687,11 @@ bool TTrain::Update(double const Deltatime) ggClockHInd.UpdateValue(static_cast(simulation::Time.data().wHour + simulation::Time.data().wMinute / 60.0)); ggClockHInd.Update(); } +} - Cabine[iCabn].Update(lowvoltagepower); // nowy sposób ustawienia animacji - /* - if (ggZbS.SubModel) - { - ggZbS.UpdateValue(mvOccupied->Handle->GetCP()); - ggZbS.Update(); - } - */ - // replacement for the above. TODO: move it to a more suitable place - m_brakehandlecp = mvOccupied->Handle->GetCP(); - +// sets the gauges of the motor and the low voltage, and the gauges and the ignition key of a diesel engine +void TTrain::updateEngineGauges() +{ // youBy - napiecie na silnikach if (ggEngineVoltage.SubModel) { @@ -618,7 +755,11 @@ bool TTrain::Update(double const Deltatime) } ggIgnitionKey.Update(); } +} +// sets the lamps of the wheel slip, the compressors, the dynamic brake permit and the active cab +void TTrain::updateBasicLamps() +{ if (mvControlled->SlippingWheels) { // Ra 2014-12: lokomotywy 181/182 dostają SlippingWheels po zahamowaniu powyżej 2.85 bara i buczały @@ -660,281 +801,292 @@ bool TTrain::Update(double const Deltatime) btAKLVents.Turn(true); else btAKLVents.Turn(false); +} - if (true == lowvoltagepower) +// sets the lamps of the vigilance, the line breaker, the converter, the circuits and the controllers, with the low voltage on +void TTrain::updateCircuitLamps(double const Deltatime) +{ + // McZapkie-141102: SHP i czuwak, TODO: sygnalizacja kabinowa + if (mvOccupied->SecuritySystem.is_vigilance_blinking()) { - // McZapkie-141102: SHP i czuwak, TODO: sygnalizacja kabinowa - if (mvOccupied->SecuritySystem.is_vigilance_blinking()) - { - if (fBlinkTimer > fCzuwakBlink) - fBlinkTimer = -fCzuwakBlink; - else - fBlinkTimer += Deltatime; - - btLampkaCzuwaka.Turn(fBlinkTimer > 0); - } + if (fBlinkTimer > fCzuwakBlink) + fBlinkTimer = -fCzuwakBlink; else + fBlinkTimer += Deltatime; + + btLampkaCzuwaka.Turn(fBlinkTimer > 0); + } + else + { + fBlinkTimer = 0.0; + btLampkaCzuwaka.Turn(false); + } + + btLampkaSHP.Turn(mvOccupied->SecuritySystem.is_cabsignal_blinking()); + btLampkaCzuwakaSHP.Turn(btLampkaSHP.GetValue() || btLampkaCzuwaka.GetValue()); + + btLampkaWylSzybki.Turn(m_linebreakerstate == linebreaker::state::closing || mvControlled->Mains); + btLampkaWylSzybkiOff.Turn(m_linebreakerstate != linebreaker::state::closing && !mvControlled->Mains); + btLampkaMainBreakerReady.Turn(mvControlled->MainsInitTimeCountdown <= 0.0 && m_linebreakerstate != linebreaker::state::closing && !mvControlled->Mains); + btLampkaMainBreakerBlinkingIfReady.Turn(m_linebreakerstate == linebreaker::state::closing || mvControlled->Mains || mvControlled->MainsInitTimeCountdown < 0.0 && simulation::Time.data().wMilliseconds > 500); + + btLampkaPrzetw.Turn(mvOccupied->Power110vIsAvailable); + btLampkaPrzetwOff.Turn(!mvOccupied->Power110vIsAvailable); + btLampkaPrzetwAOff.Turn(!mvControlled->ConverterFlag); + btLampkaNadmPrzetw.Turn(Dynamic()->Mechanik ? Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : mvControlled->ConvOvldFlag); + + btLampkaOpory.Turn(mvControlled->StLinFlag && mvControlled->ResistorsFlagCheck()); + btLampkaBezoporowa.Turn(mvControlled->ResistorsFlagCheck() || mvControlled->MainCtrlActualPos == 0); // do EU04 + btLampkaStyczn.Turn(mvControlled->LineContactorsLampLit()); // mozna prowadzic rozruch + btLampkaPrzekRozn.Turn(!mvControlled->GroundRelay && mvControlled->MainCircuitLampsEnabled()); // relay is off and needs a reset + btLampkaNadmSil.Turn(mvControlled->FuseFlagCheck() && mvControlled->MainCircuitLampsEnabled()); // relay is off and needs a reset + btLampkaUkrotnienie.Turn(mvControlled->Couplers[mvControlled->CabOccupied == 1 ? VehicleEnd::rear : VehicleEnd::front].CouplingFlag.HasAll(Coupling::control)); + btLampkaHamPosp.Turn(TestFlag(mvOccupied->Hamulec->GetBrakeStatus(), 1)); // lampka drugiego stopnia hamowania + // TODO: youBy wyciągnąć flagę wysokiego stopnia + btLampkaNadmWent.Turn(mvControlled->RventRot < 5.0 && mvControlled->ResistorsFlagCheck()); // hunter-121211: lampka zanikowo-pradowego wentylatorow + btLampkaWysRozr.Turn(mvControlled->Imax >= mvControlled->ImaxHi); + + btLampkaNapNastHam.Turn(mvControlled->DirActive != 0); // napiecie na nastawniku hamulcowym + btLampkaSprezarka.Turn(mvControlled->CompressorFlag); // mutopsitka dziala + btLampkaSprezarkaOff.Turn(!mvControlled->CompressorFlag); + btLampkaFuelPumpOff.Turn(!mvControlled->FuelPump.is_active); + btLampkaOilPump.Turn(mvControlled->OilPump.is_active); // pre-lubrication pump, goes off once the engine is started + + // boczniki + // Ra: w SU45 boczniki wchodzą na ScndCtrlPos, a nie na ScndCtrlActualPos + // - pokićkał ktoś? + int scp = mvControlled->RList[mvControlled->MainCtrlPos].ScndAct; + scp = scp == 255 ? 0 : scp; // Ra: whatta hella is this? + btLampkaBoczniki.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlActualPos > 0 || scp > 0); + btLampkaBocznik1.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlPos > 0 || mvControlled->ScndCtrlActualPos > 0 || scp > 0); + btLampkaBocznik2.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlPos > 1 || mvControlled->ScndCtrlActualPos > 1 || scp > 1); + btLampkaBocznik3.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlPos > 2 || mvControlled->ScndCtrlActualPos > 2 || scp > 2); + btLampkaBocznik4.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlPos > 3 || mvControlled->ScndCtrlActualPos > 3 || scp > 3); + + // biegi dla motoraka + btLampkaGear1.Turn(mvControlled->ScndCtrlActualPos == 1 && mvControlled->diesel.clutchState > 0); // bieg 1 + btLampkaGear2.Turn(mvControlled->ScndCtrlActualPos == 2 && mvControlled->diesel.clutchState > 0); // bieg 2 + btLampkaHydroLockup.Turn(mvControlled->torqueConverter.lockedUp); // zblokowanie skrzyni z silnikiem + + if (mvControlled->Signalling == true) + { + if (mvOccupied->BrakePress >= 1.45f) { - fBlinkTimer = 0.0; - btLampkaCzuwaka.Turn(false); + btLampkaHamowanie1zes.Turn(true); } - - btLampkaSHP.Turn(mvOccupied->SecuritySystem.is_cabsignal_blinking()); - btLampkaCzuwakaSHP.Turn(btLampkaSHP.GetValue() || btLampkaCzuwaka.GetValue()); - - btLampkaWylSzybki.Turn(m_linebreakerstate == linebreaker::state::closing || mvControlled->Mains); - btLampkaWylSzybkiOff.Turn(m_linebreakerstate != linebreaker::state::closing && !mvControlled->Mains); - btLampkaMainBreakerReady.Turn(mvControlled->MainsInitTimeCountdown <= 0.0 && m_linebreakerstate != linebreaker::state::closing && !mvControlled->Mains); - btLampkaMainBreakerBlinkingIfReady.Turn(m_linebreakerstate == linebreaker::state::closing || mvControlled->Mains || mvControlled->MainsInitTimeCountdown < 0.0 && simulation::Time.data().wMilliseconds > 500); - - btLampkaPrzetw.Turn(mvOccupied->Power110vIsAvailable); - btLampkaPrzetwOff.Turn(!mvOccupied->Power110vIsAvailable); - btLampkaPrzetwAOff.Turn(!mvControlled->ConverterFlag); - btLampkaNadmPrzetw.Turn(Dynamic()->Mechanik ? Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : mvControlled->ConvOvldFlag); - - btLampkaOpory.Turn(mvControlled->StLinFlag && mvControlled->ResistorsFlagCheck()); - btLampkaBezoporowa.Turn(mvControlled->ResistorsFlagCheck() || mvControlled->MainCtrlActualPos == 0); // do EU04 - btLampkaStyczn.Turn(mvControlled->LineContactorsLampLit()); // mozna prowadzic rozruch - btLampkaPrzekRozn.Turn(!mvControlled->GroundRelay && mvControlled->MainCircuitLampsEnabled()); // relay is off and needs a reset - btLampkaNadmSil.Turn(mvControlled->FuseFlagCheck() && mvControlled->MainCircuitLampsEnabled()); // relay is off and needs a reset - btLampkaUkrotnienie.Turn(mvControlled->Couplers[mvControlled->CabOccupied == 1 ? VehicleEnd::rear : VehicleEnd::front].CouplingFlag.HasAll(Coupling::control)); - btLampkaHamPosp.Turn(TestFlag(mvOccupied->Hamulec->GetBrakeStatus(), 1)); // lampka drugiego stopnia hamowania - // TODO: youBy wyciągnąć flagę wysokiego stopnia - btLampkaNadmWent.Turn(mvControlled->RventRot < 5.0 && mvControlled->ResistorsFlagCheck()); // hunter-121211: lampka zanikowo-pradowego wentylatorow - btLampkaWysRozr.Turn(mvControlled->Imax >= mvControlled->ImaxHi); - - btLampkaNapNastHam.Turn(mvControlled->DirActive != 0); // napiecie na nastawniku hamulcowym - btLampkaSprezarka.Turn(mvControlled->CompressorFlag); // mutopsitka dziala - btLampkaSprezarkaOff.Turn(!mvControlled->CompressorFlag); - btLampkaFuelPumpOff.Turn(!mvControlled->FuelPump.is_active); - btLampkaOilPump.Turn(mvControlled->OilPump.is_active); // pre-lubrication pump, goes off once the engine is started - - // boczniki - // Ra: w SU45 boczniki wchodzą na ScndCtrlPos, a nie na ScndCtrlActualPos - // - pokićkał ktoś? - int scp = mvControlled->RList[mvControlled->MainCtrlPos].ScndAct; - scp = scp == 255 ? 0 : scp; // Ra: whatta hella is this? - btLampkaBoczniki.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlActualPos > 0 || scp > 0); - btLampkaBocznik1.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlPos > 0 || mvControlled->ScndCtrlActualPos > 0 || scp > 0); - btLampkaBocznik2.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlPos > 1 || mvControlled->ScndCtrlActualPos > 1 || scp > 1); - btLampkaBocznik3.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlPos > 2 || mvControlled->ScndCtrlActualPos > 2 || scp > 2); - btLampkaBocznik4.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlPos > 3 || mvControlled->ScndCtrlActualPos > 3 || scp > 3); - - // biegi dla motoraka - btLampkaGear1.Turn(mvControlled->ScndCtrlActualPos == 1 && mvControlled->diesel.clutchState > 0); // bieg 1 - btLampkaGear2.Turn(mvControlled->ScndCtrlActualPos == 2 && mvControlled->diesel.clutchState > 0); // bieg 2 - btLampkaHydroLockup.Turn(mvControlled->torqueConverter.lockedUp); // zblokowanie skrzyni z silnikiem - - if (mvControlled->Signalling == true) - { - if (mvOccupied->BrakePress >= 1.45f) - { - btLampkaHamowanie1zes.Turn(true); - } - if (mvControlled->BrakePress < 0.75f) - { - btLampkaHamowanie1zes.Turn(false); - } - } - else + if (mvControlled->BrakePress < 0.75f) { btLampkaHamowanie1zes.Turn(false); } - - switch (mvControlled->TrainType) - { - // zależnie od typu lokomotywy - case train_type::emu: - { - btLampkaHamienie.Turn(mvControlled->BrakePress >= 0.2 && mvControlled->Signalling); - break; - } - case train_type::et41: - { - // odhamowanie drugiego członu - if (mvSecond) - { - // bo może komuś przyjść do głowy jeżdżenie jednym członem - btLampkaHamienie.Turn(mvSecond->BrakePress < 0.4); - } - break; - } - default: - { - btLampkaHamienie.Turn(mvOccupied->BrakePress >= 0.1 || mvControlled->DynamicBrakeFlag); - btLampkaBrakingOff.Turn(mvOccupied->BrakePress < 0.1 && !mvControlled->DynamicBrakeFlag); - break; - } - } - // KURS90 - btLampkaMaxSila.Turn(abs(mvControlled->Im) >= 350); - btLampkaPrzekrMaxSila.Turn(abs(mvControlled->Im) >= 450); - btLampkaRadio.Turn(mvOccupied->Radio && mvOccupied->RadioFuse); - btLampkaRadioMessage.Turn(radio_message_played); - btLampkaRadioStop.Turn(mvOccupied->Radio && mvOccupied->RadioFuse && mvOccupied->RadioStopFlag); - btLampkaHamulecReczny.Turn(mvOccupied->ManualBrakePos > 0); - // NBMX wrzesien 2003 - drzwi oraz sygnał odjazdu - if (DynamicObject->Mechanik != nullptr) - { - btLampkaDoorLeft.Turn(DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right]); - btLampkaDoorRight.Turn(DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left]); - } - if (DynamicObject->Mechanik != nullptr) - { - // with DoorClosureSignal in the definition of the cab's vehicle, the door closure signalling (SOD) of the whole - // consist: lit with all doors closed and locked, blinking with them closed but released, dark with a door open. - // without it, the lock of the vehicle's own doors, as before - btLampkaBlokadaDrzwi.Turn(mvOccupied->door_closure_lamp_lit(DynamicObject->Mechanik->DoorClosure, simulation::Time.data().wSecond % 2 < 1)); - } - else - { - btLampkaBlokadaDrzwi.Turn(mvOccupied->Doors.is_locked); - } - btLampkaDoorLockOff.Turn(false == mvOccupied->Doors.lock_enabled); - btLampkaDepartureSignal.Turn(mvControlled->DepartureSignal); - btLampkaNapNastHam.Turn(mvControlled->DirActive != 0 && mvOccupied->EpFuse); // napiecie na nastawniku hamulcowym - - // Wylaczanie lampek kierunku gdy jedziemy - // Feature uruchamiany z fiz z sekcji Ctrl. wpisem HideDirStatusWhenMoving=Yes (domyslnie No) - if (mvOccupied->HideDirStatusWhenMoving && // Czy ta funkcja jest w ogole wlaczona - mvOccupied->Vel > mvOccupied->HideDirStatusSpeed) // Uzaleznienie od predkosci - { - btLampkaForward.Turn(false); - btLampkaBackward.Turn(false); - btLampkaNeutral.Turn(false); - } - else - { - btLampkaForward.Turn(mvControlled->DirActive > 0); // jazda do przodu - btLampkaBackward.Turn(mvControlled->DirActive < 0); // jazda do tyłu - btLampkaNeutral.Turn(mvControlled->DirActive == 0); // kierunek neutral - } - - btLampkaED.Turn(mvControlled->DynamicBrakeFlag); // hamulec ED - btLampkaBrakeProfileG.Turn(TestFlag(mvOccupied->BrakeDelayFlag, bdelay_G)); - btLampkaBrakeProfileP.Turn(TestFlag(mvOccupied->BrakeDelayFlag, bdelay_P)); - btLampkaBrakeProfileR.Turn(TestFlag(mvOccupied->BrakeDelayFlag, bdelay_R)); - btLampkaSpringBrakeActive.Turn(mvOccupied->SpringBrake.IsActive); - btLampkaSpringBrakeInactive.Turn(!mvOccupied->SpringBrake.IsActive); - // light indicators - // NOTE: sides are hardcoded to deal with setups where single cab is equipped with all indicators - btLampkaUpperLight.Turn((mvOccupied->iLights[VehicleEnd::front] & light::headlight_upper) != 0); - btLampkaLeftLight.Turn((mvOccupied->iLights[VehicleEnd::front] & light::headlight_left) != 0); - btLampkaRightLight.Turn((mvOccupied->iLights[VehicleEnd::front] & light::headlight_right) != 0); - btLampkaLeftEndLight.Turn((mvOccupied->iLights[VehicleEnd::front] & light::redmarker_left) != 0); - btLampkaRightEndLight.Turn((mvOccupied->iLights[VehicleEnd::front] & light::redmarker_right) != 0); - btLampkaRearUpperLight.Turn((mvOccupied->iLights[VehicleEnd::rear] & light::headlight_upper) != 0); - btLampkaRearLeftLight.Turn((mvOccupied->iLights[VehicleEnd::rear] & light::headlight_left) != 0); - btLampkaRearRightLight.Turn((mvOccupied->iLights[VehicleEnd::rear] & light::headlight_right) != 0); - btLampkaRearLeftEndLight.Turn((mvOccupied->iLights[VehicleEnd::rear] & light::redmarker_left) != 0); - btLampkaRearRightEndLight.Turn((mvOccupied->iLights[VehicleEnd::rear] & light::redmarker_right) != 0); - // others - btLampkaMalfunction.Turn(mvControlled->diesel.heat.PA); - // overheat indicator lamps - btLampkaOilOverheat.Turn(mvControlled->diesel.heat.oil.is_hot); - btLampkaWaterOverheat.Turn(mvControlled->diesel.heat.water.is_hot); - btLampkaWaterAuxOverheat.Turn(mvControlled->diesel.heat.water_aux.is_hot); - btLampkaEngineOverheat.Turn(mvControlled->diesel.heat.engine_is_hot); - btLampkaMotorBlowers.Turn(mvControlled->MotorBlowers[VehicleEnd::front].is_active && mvControlled->MotorBlowers[VehicleEnd::rear].is_active); - btLampkaCoolingFans.Turn(mvControlled->RventRot > 1.0); - btLampkaLouvresClosed.Turn(mvControlled->LouvresClosed()); - btLampkaTempomat.Turn(mvOccupied->SpeedCtrlUnit.IsActive); - btLampkaDistanceCounter.Turn(m_distancecounter >= 0.f); - // universal devices state indicators - for (auto idx = 0; idx < btUniversals.size(); ++idx) - { - btUniversals[idx].Turn(ggUniversals[idx].GetValue() > 0.5); - } } else { - // wylaczone - btLampkaCzuwaka.Turn(false); - btLampkaSHP.Turn(false); - btLampkaCzuwakaSHP.Turn(false); - btLampkaWylSzybki.Turn(false); - btLampkaWylSzybkiOff.Turn(false); - btLampkaMainBreakerReady.Turn(false); - btLampkaMainBreakerBlinkingIfReady.Turn(false); - btLampkaWysRozr.Turn(false); - btLampkaOpory.Turn(false); - btLampkaStyczn.Turn(false); - btLampkaPrzekRozn.Turn(false); - btLampkaNadmSil.Turn(false); - btLampkaUkrotnienie.Turn(false); - btLampkaHamPosp.Turn(false); - btLampkaBoczniki.Turn(false); - btLampkaBocznik1.Turn(false); - btLampkaBocznik2.Turn(false); - btLampkaBocznik3.Turn(false); - btLampkaBocznik4.Turn(false); - btLampkaGear1.Turn(false); - btLampkaGear2.Turn(false); - btLampkaHydroLockup.Turn(false); - btLampkaNapNastHam.Turn(false); - btLampkaPrzetw.Turn(false); - btLampkaPrzetwOff.Turn(false); - btLampkaPrzetwAOff.Turn(false); - btLampkaNadmPrzetw.Turn(false); - btLampkaSprezarka.Turn(false); - btLampkaSprezarkaOff.Turn(false); - btLampkaFuelPumpOff.Turn(false); - btLampkaOilPump.Turn(false); - btLampkaBezoporowa.Turn(false); btLampkaHamowanie1zes.Turn(false); - btLampkaHamienie.Turn(false); - btLampkaBrakingOff.Turn(false); - btLampkaBrakeProfileG.Turn(false); - btLampkaBrakeProfileP.Turn(false); - btLampkaBrakeProfileR.Turn(false); - btLampkaSpringBrakeActive.Turn(false); - btLampkaSpringBrakeInactive.Turn(false); - // overheat indicator lamps off - btLampkaOilOverheat.Turn(false); - btLampkaWaterOverheat.Turn(false); - btLampkaWaterAuxOverheat.Turn(false); - btLampkaEngineOverheat.Turn(false); - btLampkaMaxSila.Turn(false); - btLampkaPrzekrMaxSila.Turn(false); - btLampkaRadio.Turn(false); - btLampkaRadioMessage.Turn(false); - btLampkaRadioStop.Turn(false); - btLampkaHamulecReczny.Turn(false); - btLampkaDoorLeft.Turn(false); - btLampkaDoorRight.Turn(false); - btLampkaBlokadaDrzwi.Turn(false); - btLampkaDoorLockOff.Turn(false); - btLampkaDepartureSignal.Turn(false); - btLampkaNapNastHam.Turn(false); + } +} + +// sets the lamps of the braking, the radio, the doors, the direction, the lights and the overheating, with the low voltage on +void TTrain::updateTrainLamps() +{ + switch (mvControlled->TrainType) + { + // zależnie od typu lokomotywy + case train_type::emu: + { + btLampkaHamienie.Turn(mvControlled->BrakePress >= 0.2 && mvControlled->Signalling); + break; + } + case train_type::et41: + { + // odhamowanie drugiego członu + if (mvSecond) + { + // bo może komuś przyjść do głowy jeżdżenie jednym członem + btLampkaHamienie.Turn(mvSecond->BrakePress < 0.4); + } + break; + } + default: + { + btLampkaHamienie.Turn(mvOccupied->BrakePress >= 0.1 || mvControlled->DynamicBrakeFlag); + btLampkaBrakingOff.Turn(mvOccupied->BrakePress < 0.1 && !mvControlled->DynamicBrakeFlag); + break; + } + } + // KURS90 + btLampkaMaxSila.Turn(abs(mvControlled->Im) >= 350); + btLampkaPrzekrMaxSila.Turn(abs(mvControlled->Im) >= 450); + btLampkaRadio.Turn(mvOccupied->Radio && mvOccupied->RadioFuse); + btLampkaRadioMessage.Turn(radio_message_played); + btLampkaRadioStop.Turn(mvOccupied->Radio && mvOccupied->RadioFuse && mvOccupied->RadioStopFlag); + btLampkaHamulecReczny.Turn(mvOccupied->ManualBrakePos > 0); + // NBMX wrzesien 2003 - drzwi oraz sygnał odjazdu + if (DynamicObject->Mechanik != nullptr) + { + btLampkaDoorLeft.Turn(DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right]); + btLampkaDoorRight.Turn(DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left]); + } + if (DynamicObject->Mechanik != nullptr) + { + // with DoorClosureSignal in the definition of the cab's vehicle, the door closure signalling (SOD) of the whole + // consist: lit with all doors closed and locked, blinking with them closed but released, dark with a door open. + // without it, the lock of the vehicle's own doors, as before + btLampkaBlokadaDrzwi.Turn(mvOccupied->door_closure_lamp_lit(DynamicObject->Mechanik->DoorClosure, simulation::Time.data().wSecond % 2 < 1)); + } + else + { + btLampkaBlokadaDrzwi.Turn(mvOccupied->Doors.is_locked); + } + btLampkaDoorLockOff.Turn(false == mvOccupied->Doors.lock_enabled); + btLampkaDepartureSignal.Turn(mvControlled->DepartureSignal); + btLampkaNapNastHam.Turn(mvControlled->DirActive != 0 && mvOccupied->EpFuse); // napiecie na nastawniku hamulcowym + + // Wylaczanie lampek kierunku gdy jedziemy + // Feature uruchamiany z fiz z sekcji Ctrl. wpisem HideDirStatusWhenMoving=Yes (domyslnie No) + if (mvOccupied->HideDirStatusWhenMoving && // Czy ta funkcja jest w ogole wlaczona + mvOccupied->Vel > mvOccupied->HideDirStatusSpeed) // Uzaleznienie od predkosci + { btLampkaForward.Turn(false); btLampkaBackward.Turn(false); btLampkaNeutral.Turn(false); - btLampkaED.Turn(false); - // light indicators - btLampkaUpperLight.Turn(false); - btLampkaLeftLight.Turn(false); - btLampkaRightLight.Turn(false); - btLampkaLeftEndLight.Turn(false); - btLampkaRightEndLight.Turn(false); - btLampkaRearUpperLight.Turn(false); - btLampkaRearLeftLight.Turn(false); - btLampkaRearRightLight.Turn(false); - btLampkaRearLeftEndLight.Turn(false); - btLampkaRearRightEndLight.Turn(false); - // others - btLampkaMalfunction.Turn(false); - btLampkaMotorBlowers.Turn(false); - btLampkaCoolingFans.Turn(false); - btLampkaLouvresClosed.Turn(false); - btLampkaTempomat.Turn(false); - btLampkaDistanceCounter.Turn(false); - // universal devices state indicators - for (auto &universal : btUniversals) - { - universal.Turn(false); - } + } + else + { + btLampkaForward.Turn(mvControlled->DirActive > 0); // jazda do przodu + btLampkaBackward.Turn(mvControlled->DirActive < 0); // jazda do tyłu + btLampkaNeutral.Turn(mvControlled->DirActive == 0); // kierunek neutral } + btLampkaED.Turn(mvControlled->DynamicBrakeFlag); // hamulec ED + btLampkaBrakeProfileG.Turn(TestFlag(mvOccupied->BrakeDelayFlag, bdelay_G)); + btLampkaBrakeProfileP.Turn(TestFlag(mvOccupied->BrakeDelayFlag, bdelay_P)); + btLampkaBrakeProfileR.Turn(TestFlag(mvOccupied->BrakeDelayFlag, bdelay_R)); + btLampkaSpringBrakeActive.Turn(mvOccupied->SpringBrake.IsActive); + btLampkaSpringBrakeInactive.Turn(!mvOccupied->SpringBrake.IsActive); + // light indicators + // NOTE: sides are hardcoded to deal with setups where single cab is equipped with all indicators + btLampkaUpperLight.Turn((mvOccupied->iLights[VehicleEnd::front] & light::headlight_upper) != 0); + btLampkaLeftLight.Turn((mvOccupied->iLights[VehicleEnd::front] & light::headlight_left) != 0); + btLampkaRightLight.Turn((mvOccupied->iLights[VehicleEnd::front] & light::headlight_right) != 0); + btLampkaLeftEndLight.Turn((mvOccupied->iLights[VehicleEnd::front] & light::redmarker_left) != 0); + btLampkaRightEndLight.Turn((mvOccupied->iLights[VehicleEnd::front] & light::redmarker_right) != 0); + btLampkaRearUpperLight.Turn((mvOccupied->iLights[VehicleEnd::rear] & light::headlight_upper) != 0); + btLampkaRearLeftLight.Turn((mvOccupied->iLights[VehicleEnd::rear] & light::headlight_left) != 0); + btLampkaRearRightLight.Turn((mvOccupied->iLights[VehicleEnd::rear] & light::headlight_right) != 0); + btLampkaRearLeftEndLight.Turn((mvOccupied->iLights[VehicleEnd::rear] & light::redmarker_left) != 0); + btLampkaRearRightEndLight.Turn((mvOccupied->iLights[VehicleEnd::rear] & light::redmarker_right) != 0); + // others + btLampkaMalfunction.Turn(mvControlled->diesel.heat.PA); + // overheat indicator lamps + btLampkaOilOverheat.Turn(mvControlled->diesel.heat.oil.is_hot); + btLampkaWaterOverheat.Turn(mvControlled->diesel.heat.water.is_hot); + btLampkaWaterAuxOverheat.Turn(mvControlled->diesel.heat.water_aux.is_hot); + btLampkaEngineOverheat.Turn(mvControlled->diesel.heat.engine_is_hot); + btLampkaMotorBlowers.Turn(mvControlled->MotorBlowers[VehicleEnd::front].is_active && mvControlled->MotorBlowers[VehicleEnd::rear].is_active); + btLampkaCoolingFans.Turn(mvControlled->RventRot > 1.0); + btLampkaLouvresClosed.Turn(mvControlled->LouvresClosed()); + btLampkaTempomat.Turn(mvOccupied->SpeedCtrlUnit.IsActive); + btLampkaDistanceCounter.Turn(m_distancecounter >= 0.f); + // universal devices state indicators + for (auto idx = 0; idx < btUniversals.size(); ++idx) + { + btUniversals[idx].Turn(ggUniversals[idx].GetValue() > 0.5); + } +} + +// turns off the lamps of the cab when there's no low voltage +void TTrain::turnOffLamps() +{ + // wylaczone + btLampkaCzuwaka.Turn(false); + btLampkaSHP.Turn(false); + btLampkaCzuwakaSHP.Turn(false); + btLampkaWylSzybki.Turn(false); + btLampkaWylSzybkiOff.Turn(false); + btLampkaMainBreakerReady.Turn(false); + btLampkaMainBreakerBlinkingIfReady.Turn(false); + btLampkaWysRozr.Turn(false); + btLampkaOpory.Turn(false); + btLampkaStyczn.Turn(false); + btLampkaPrzekRozn.Turn(false); + btLampkaNadmSil.Turn(false); + btLampkaUkrotnienie.Turn(false); + btLampkaHamPosp.Turn(false); + btLampkaBoczniki.Turn(false); + btLampkaBocznik1.Turn(false); + btLampkaBocznik2.Turn(false); + btLampkaBocznik3.Turn(false); + btLampkaBocznik4.Turn(false); + btLampkaGear1.Turn(false); + btLampkaGear2.Turn(false); + btLampkaHydroLockup.Turn(false); + btLampkaNapNastHam.Turn(false); + btLampkaPrzetw.Turn(false); + btLampkaPrzetwOff.Turn(false); + btLampkaPrzetwAOff.Turn(false); + btLampkaNadmPrzetw.Turn(false); + btLampkaSprezarka.Turn(false); + btLampkaSprezarkaOff.Turn(false); + btLampkaFuelPumpOff.Turn(false); + btLampkaOilPump.Turn(false); + btLampkaBezoporowa.Turn(false); + btLampkaHamowanie1zes.Turn(false); + btLampkaHamienie.Turn(false); + btLampkaBrakingOff.Turn(false); + btLampkaBrakeProfileG.Turn(false); + btLampkaBrakeProfileP.Turn(false); + btLampkaBrakeProfileR.Turn(false); + btLampkaSpringBrakeActive.Turn(false); + btLampkaSpringBrakeInactive.Turn(false); + // overheat indicator lamps off + btLampkaOilOverheat.Turn(false); + btLampkaWaterOverheat.Turn(false); + btLampkaWaterAuxOverheat.Turn(false); + btLampkaEngineOverheat.Turn(false); + btLampkaMaxSila.Turn(false); + btLampkaPrzekrMaxSila.Turn(false); + btLampkaRadio.Turn(false); + btLampkaRadioMessage.Turn(false); + btLampkaRadioStop.Turn(false); + btLampkaHamulecReczny.Turn(false); + btLampkaDoorLeft.Turn(false); + btLampkaDoorRight.Turn(false); + btLampkaBlokadaDrzwi.Turn(false); + btLampkaDoorLockOff.Turn(false); + btLampkaDepartureSignal.Turn(false); + btLampkaNapNastHam.Turn(false); + btLampkaForward.Turn(false); + btLampkaBackward.Turn(false); + btLampkaNeutral.Turn(false); + btLampkaED.Turn(false); + // light indicators + btLampkaUpperLight.Turn(false); + btLampkaLeftLight.Turn(false); + btLampkaRightLight.Turn(false); + btLampkaLeftEndLight.Turn(false); + btLampkaRightEndLight.Turn(false); + btLampkaRearUpperLight.Turn(false); + btLampkaRearLeftLight.Turn(false); + btLampkaRearRightLight.Turn(false); + btLampkaRearLeftEndLight.Turn(false); + btLampkaRearRightEndLight.Turn(false); + // others + btLampkaMalfunction.Turn(false); + btLampkaMotorBlowers.Turn(false); + btLampkaCoolingFans.Turn(false); + btLampkaLouvresClosed.Turn(false); + btLampkaTempomat.Turn(false); + btLampkaDistanceCounter.Turn(false); + // universal devices state indicators + for (auto &universal : btUniversals) + { + universal.Turn(false); + } +} + +// sets the lamps of the second unit, from the vehicle coupled behind the cab with the control coupling +void TTrain::updateSecondUnitLamps(bool const lowvoltagepower) +{ { // yB - wskazniki drugiego czlonu TDynamicObject const *tmp{nullptr}; //=mvControlled->mvSecond; //Ra 2014-07: trzeba to jeszcze wyjąć z kabiny... // Ra 2014-07: no nie ma potrzeby szukać tego w każdej klatce @@ -1018,6 +1170,11 @@ bool TTrain::Update(double const Deltatime) } } } +} + +// sets the master and the secondary controllers, the speed control buttons and the reverser +void TTrain::updateMasterControllers(bool const lowvoltagepower) +{ // McZapkie-080602: obroty (albo translacje) regulatorow if (ggJointCtrl.SubModel != nullptr) { @@ -1106,6 +1263,11 @@ bool TTrain::Update(double const Deltatime) } ggDirKey.Update(); } +} + +// sets the train brake and the local brake handles, from the PoKeys desk when it drives them +void TTrain::updateBrakeControllers() +{ if (ggBrakeCtrl.SubModel != nullptr) { #ifdef _WIN32 @@ -1168,6 +1330,11 @@ bool TTrain::Update(double const Deltatime) } ggLocalBrake.Update(); } +} + +// updates the direction, the brake setting, the door and the compressor switches and buttons +void TTrain::updateCabSwitches(bool const lowvoltagepower) +{ ggDirForwardButton.Update(lowvoltagepower); ggDirNeutralButton.Update(lowvoltagepower); ggDirBackwardButton.Update(lowvoltagepower); @@ -1199,7 +1366,11 @@ bool TTrain::Update(double const Deltatime) ggCompressorButton.Update(); ggCompressorLocalButton.Update(); ggCompressorListButton.Update(); +} +// sets the train heating lamp and the instrument, the dashboard and the timetable lights +void TTrain::updateHeatingAndInstrumentLights() +{ //--------- // hunter-080812: poprawka na ogrzewanie w elektrykach - usuniete uzaleznienie od przetwornicy if (mvControlled->Heating == true && mvControlled->ConvOvldFlag == false) @@ -1222,7 +1393,11 @@ bool TTrain::Update(double const Deltatime) btInstrumentLight.Turn(InstrumentLightActive && lightpower); btDashboardLight.Turn(DashboardLightActive && lightpower); btTimetableLight.Turn(TimetableLightActive && lightpower); +} +// updates the buttons of the line breaker, the brakes, the radio, the pantographs and the lights +void TTrain::updateButtons() +{ // guziki: ggMainOffButton.Update(); ggMainOnButton.Update(); @@ -1294,6 +1469,11 @@ bool TTrain::Update(double const Deltatime) ggRearRightEndLightButton.Update(); ggDimHeadlightsButton.Update(); ggDimHeadlightsButton.Update(); +} + +// updates the buttons of the converter, the horns, the speed control, the universal devices, the cab and the engine auxiliaries +void TTrain::updateAuxiliaryButtons(bool const lowvoltagepower) +{ //------------ // the converter switches follow the vehicle when something else flips them (the AI driver, the other cab, // the pressure switch of an EMU), not only when the cab is entered (set_cab_controls()) @@ -1379,11 +1559,11 @@ bool TTrain::Update(double const Deltatime) ggMotorBlowersFrontButton.Update(); ggMotorBlowersRearButton.Update(); ggMotorBlowersAllOffButton.Update(); +} - // wyprowadzenie sygnałów dla haslera na PoKeys (zaznaczanie na taśmie) - btHaslerBrakes.Turn(mvOccupied->BrakePress > 0.4); // ciśnienie w cylindrach - btHaslerCurrent.Turn(mvOccupied->Im != 0.0); // prąd na silnikach - +// sets the light level of each cab and of the interior of the vehicle +void TTrain::updateCabLightLevels() +{ // calculate current level of interior illumination { // TODO: organize it along with rest of train update in a more sensible arrangement @@ -1408,34 +1588,7 @@ bool TTrain::Update(double const Deltatime) ++cabidx; } } - - // anti slip system activation, maintained while the control button is down - if (mvOccupied->BrakeSystem != TBrakeSystem::ElectroPneumatic && ggAntiSlipButton.GetDesiredValue() > 0.95) - { - mvControlled->AntiSlippingBrake(); - } - // screens - - if (!FreeFlyModeFlag && simulation::Train == this) // don't bother if we're outside - { - update_screens(Deltatime); - update_script_screens(); - } - - // update direction relay - if (prevBatState != mvOccupied->Power24vIsAvailable) - SetupDirectionRelays(); - if (prevDirection != mvOccupied->DirActive) - UpdateDirectionRelays(); - - prevBatState = mvOccupied->Power24vIsAvailable; - prevDirection = mvOccupied->DirActive; - - // sounds - update_sounds(Deltatime); - - return true; //(DynamicObject->Update(dt)); -} // koniec update +} void TTrain::UpdateDirectionRelays() { diff --git a/vehicle/dynamic/mmd.cpp b/vehicle/dynamic/mmd.cpp index 190ba7153..ac779d972 100644 --- a/vehicle/dynamic/mmd.cpp +++ b/vehicle/dynamic/mmd.cpp @@ -112,6 +112,28 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co parser.getTokens(); parser >> token; if( token == "models:" ) { + loadModelsSection( parser, token, asAnimName, asFileName, ReplacableSkin ); + } // models + + else if( token == "sounds:" ) { + loadSoundsSection( parser, token ); + } // sounds: + + else if( token == "locations:" ) { + loadLocationsSection( parser, token ); + } // locations: + + else if( token == "internaldata:" ) { + loadInternalDataSection( parser, token ); + } // internaldata: + + } while( token != "" ); + + finishLoadingMMediaFile( asFileName, ReplacableSkin ); +} + +// the models: section of the .mmd file: the 3d models of the vehicle and the submodels of its animations +void TDynamicObject::loadModelsSection( cParser &parser, std::string &token, std::string &asAnimName, std::string const &asFileName, std::string const &ReplacableSkin ) { // modele i podmodele m_materialdata.multi_textures = 0; // czy jest wiele tekstur wymiennych? parser.getTokens(); @@ -146,6 +168,37 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co token = ""; parser.getTokens(); parser >> token; + loadModelsKeyword( parser, token, asAnimName, asFileName ); + + } while( token != "" + && token != "endmodels" ); + + if( false == MoverParameters->LoadAttributes.empty() ) { + // Ra: tu wczytywanie modelu ładunku jest w porządku + + // bieżąca ścieżka do tekstur to dynamic/... + Global.asCurrentTexturePath = asBaseDir; + + mdLoad = LoadMMediaFile_mdload( MoverParameters->LoadType.name ); + + // z powrotem defaultowa sciezka do tekstur + Global.asCurrentTexturePath = std::string( paths::textures ); + } +} + +// a keyword of the models: section, read by the first group of keywords that knows it +void TDynamicObject::loadModelsKeyword( cParser &parser, std::string &token, std::string &asAnimName, std::string const &asFileName ) { + if( loadModelsGeneralKeyword( parser, token, asAnimName ) ) { return; } + if( loadModelsWheelKeyword( parser, token, asAnimName ) ) { return; } + if( loadModelsPantographLowerKeyword( parser, token, asAnimName, asFileName ) ) { return; } + if( loadModelsPantographUpperKeyword( parser, token, asAnimName, asFileName ) ) { return; } + if( loadModelsLinkageKeyword( parser, token, asAnimName, asFileName ) ) { return; } + if( loadModelsDoorKeyword( parser, token, asAnimName, asFileName ) ) { return; } + loadModelsMirrorWiperKeyword( parser, token, asAnimName ); +} + +// the animation counts, the other models, the loads and the knobs in the models: section; false when the token is none of them +bool TDynamicObject::loadModelsGeneralKeyword( cParser &parser, std::string &token, std::string &asAnimName ) { if( token == "animations:" ) { // Ra: ustawienie ilości poszczególnych animacji - musi być jako pierwsze, inaczej ilości będą domyślne /* @@ -267,8 +320,15 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co smLoadMode = GetSubmodelFromName( mdModel, asAnimName ); // jeszcze wczytać kąty obrotu dla poszczególnych ustawień } + else { + return false; + } + return true; +} - else if (token == "animwheelprefix:") { +// the wheels in the models: section; false when the token is another one +bool TDynamicObject::loadModelsWheelKeyword( cParser &parser, std::string &token, std::string &asAnimName ) { + if (token == "animwheelprefix:") { // prefiks kręcących się kół int i, k, m; unsigned int j; @@ -325,7 +385,15 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co // } // } - else if( token == "animpantprefix:" ) { + else { + return false; + } + return true; +} + +// the lower arms of the pantographs in the models: section; false when the token is none of them +bool TDynamicObject::loadModelsPantographLowerKeyword( cParser &parser, std::string &token, std::string &asAnimName, std::string const &asFileName ) { + if( token == "animpantprefix:" ) { // Ra: pantografy po nowemu mają literki i numerki } // Pantografy - Winger 160204 @@ -445,7 +513,15 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co } } - else if( token == "animpantrg1prefix:" ) { + else { + return false; + } + return true; +} + +// the upper arms and the shoes of the pantographs and their factors in the models: section; false when the token is none of them +bool TDynamicObject::loadModelsPantographUpperKeyword( cParser &parser, std::string &token, std::string &asAnimName, std::string const &asFileName ) { + if( token == "animpantrg1prefix:" ) { // prefiks ramion górnych 1 parser.getTokens(); parser >> token; if( pants ) { @@ -563,7 +639,15 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co } } - else if (token == "animpistonprefix:") { + else { + return false; + } + return true; +} + +// the pistons, the rods, the pendulums and the slotted levers in the models: section; false when the token is none of them +bool TDynamicObject::loadModelsLinkageKeyword( cParser &parser, std::string &token, std::string &asAnimName, std::string const &asFileName ) { + if (token == "animpistonprefix:") { // prefiks tłoczysk - na razie uzywamy modeli pantografów parser.getTokens(1, false); parser >> token; for( int i = 1; i <= 2; ++i ) @@ -675,7 +759,15 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co } } - else if( token == "animdoorprefix:" ) { + else { + return false; + } + return true; +} + +// the doors and the door steps in the models: section; false when the token is none of them +bool TDynamicObject::loadModelsDoorKeyword( cParser &parser, std::string &token, std::string &asAnimName, std::string const &asFileName ) { + if( token == "animdoorprefix:" ) { // nazwa animowanych drzwi int i, j; parser.getTokens(1, false); parser >> token; @@ -765,7 +857,15 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co } } - else if( token == "animmirrorprefix:" ) { + else { + return false; + } + return true; +} + +// the mirrors and the wipers in the models: section +void TDynamicObject::loadModelsMirrorWiperKeyword( cParser &parser, std::string &token, std::string &asAnimName ) { + if( token == "animmirrorprefix:" ) { // animated mirror submodel name prefix int i, j; parser.getTokens( 1, false ); parser >> token; @@ -843,29 +943,32 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co } } } +} - } while( token != "" - && token != "endmodels" ); - - if( false == MoverParameters->LoadAttributes.empty() ) { - // Ra: tu wczytywanie modelu ładunku jest w porządku - - // bieżąca ścieżka do tekstur to dynamic/... - Global.asCurrentTexturePath = asBaseDir; - - mdLoad = LoadMMediaFile_mdload( MoverParameters->LoadType.name ); - - // z powrotem defaultowa sciezka do tekstur - Global.asCurrentTexturePath = std::string( paths::textures ); - } - - } // models - - else if( token == "sounds:" ) { +// the sounds: section of the .mmd file: the sounds of the vehicle +void TDynamicObject::loadSoundsSection( cParser &parser, std::string &token ) { // dzwieki do { token = ""; parser.getTokens(); parser >> token; + loadSoundsKeyword( parser, token ); + } while( token != "" + && token != "endsounds" ); +} + +// a keyword of the sounds: section, read by the first group of keywords that knows it +void TDynamicObject::loadSoundsKeyword( cParser &parser, std::string &token ) { + if( loadSoundsEngineKeyword( parser, token ) ) { return; } + if( loadSoundsMotorKeyword( parser, token ) ) { return; } + if( loadSoundsBrakeKeyword( parser, token ) ) { return; } + if( loadSoundsDeviceKeyword( parser, token ) ) { return; } + if( loadSoundsDoorKeyword( parser, token ) ) { return; } + if( loadSoundsOtherKeyword( parser, token ) ) { return; } + loadSoundsAnnouncementKeyword( parser, token ); +} + +// the clatter of the wheels and the sounds of the engine and its pumps in the sounds: section; false when the token is none of them +bool TDynamicObject::loadSoundsEngineKeyword( cParser &parser, std::string &token ) { if( token == "wheel_clatter:" ){ // polozenia osi w/m srodka pojazdu double dSDist; @@ -932,7 +1035,15 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co m_powertrainsounds.water_heater.owner( this ); } - else if( token == "tractionmotor:" && MoverParameters->Power > 0 ) { + else { + return false; + } + return true; +} + +// the sounds of the traction motors, their blowers, the inverter, the fans and the transmission in the sounds: section; false when the token is none of them +bool TDynamicObject::loadSoundsMotorKeyword( cParser &parser, std::string_view token ) { + if( token == "tractionmotor:" && MoverParameters->Power > 0 ) { // plik z dzwiekiem silnika, mnozniki i ofsety amp. i czest. sound_source motortemplate { sound_placement::external }; motortemplate.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); @@ -1057,7 +1168,15 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co sound.owner( this ); } - else if( token == "brakesound:" ) { + else { + return false; + } + return true; +} + +// the sounds of the brakes in the sounds: section; false when the token is none of them +bool TDynamicObject::loadSoundsBrakeKeyword( cParser &parser, std::string_view token ) { + if( token == "brakesound:" ) { // hamowanie zwykle: rsBrake.deserialize( parser, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency ); rsBrake.owner( this ); @@ -1132,7 +1251,15 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co m_springbrakesounds.release.owner( this ); } - else if( token == "derail:" ) { + else { + return false; + } + return true; +} + +// the sounds of the derailment, the curves, the horns, the pantographs, the compressors and other devices in the sounds: section; false when the token is none of them +bool TDynamicObject::loadSoundsDeviceKeyword( cParser &parser, std::string_view token ) { + if( token == "derail:" ) { // dzwiek przy wykolejeniu rsDerailment.deserialize( parser, sound_type::single, sound_parameters::range ); rsDerailment.owner( this ); @@ -1234,7 +1361,15 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co sSmallCompressor.owner( this ); } - else if( token == "departuresignal:" ) { + else { + return false; + } + return true; +} + +// the sounds of the doors, the door steps and the mirrors in the sounds: section; false when the token is none of them +bool TDynamicObject::loadSoundsDoorKeyword( cParser &parser, std::string_view token ) { + if( token == "departuresignal:" ) { // pliki z sygnalem odjazdu sound_source soundtemplate { sound_placement::general, 25.f }; soundtemplate.deserialize( parser, sound_type::multipart, sound_parameters::range ); @@ -1342,7 +1477,15 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co } } - else if( token == "unloading:" ) { + else { + return false; + } + return true; +} + +// the sounds of the load exchange, the sanders, the releaser and the running noise in the sounds: section; false when the token is none of them +bool TDynamicObject::loadSoundsOtherKeyword( cParser &parser, std::string_view token ) { + if( token == "unloading:" ) { m_exchangesounds.unloading.range( MoverParameters->Dim.L * 0.5f * -1 ); m_exchangesounds.unloading.deserialize( parser, sound_type::single ); m_exchangesounds.unloading.owner( this ); @@ -1411,7 +1554,15 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co m_wheelflat.owner( this ); } - else if(token == "announcements:") { + else { + return false; + } + return true; +} + +// the announcements of the passenger information system in the sounds: section +void TDynamicObject::loadSoundsAnnouncementKeyword( cParser &parser, std::string &token ) { + if(token == "announcements:") { // announcement sounds // content provided as "key: value" pairs together enclosed in "{}" // value can be optionally set of values enclosed in "[]" in which case one value will be picked randomly @@ -1474,13 +1625,10 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co } } } +} - } while( token != "" - && token != "endsounds" ); - - } // sounds: - - else if( token == "locations:" ) { +// the locations: section of the .mmd file: the places of the doors, the mirrors, the motors and the bogies for their sounds +void TDynamicObject::loadLocationsSection( cParser &parser, std::string &token ) { do { token = ""; parser.getTokens(); parser >> token; @@ -1592,15 +1740,29 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co } while( token != "" && token != "endlocations" ); +} - } // locations: - - else if( token == "internaldata:" ) { +// the internaldata: section of the .mmd file: the cabs, the sounds of the devices, the couplers and the cab +void TDynamicObject::loadInternalDataSection( cParser &parser, std::string &token ) { // dalej nie czytaj do { // zbieranie informacji o kabinach token = ""; parser.getTokens(); parser >> token; + loadInternalDataKeyword( parser, token ); + } while( token != "" ); +} + +// a keyword of the internaldata: section, read by the first group of keywords that knows it +void TDynamicObject::loadInternalDataKeyword( cParser &parser, std::string &token ) { + if( loadInternalDataDeviceKeyword( parser, token ) ) { return; } + if( loadInternalDataCouplerKeyword( parser, token ) ) { return; } + if( loadInternalDataBufferKeyword( parser, token ) ) { return; } + loadInternalDataCabKeyword( parser, token ); +} + +// the cab models and the sounds of the engine and its devices in the internaldata: section; false when the token is none of them +bool TDynamicObject::loadInternalDataDeviceKeyword( cParser &parser, std::string &token ) { if( token == "cab0model:" ) { parser.getTokens(); parser >> token; if( token != "none" ) { iCabs |= 0x2; } @@ -1701,8 +1863,16 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co rsSlippery.m_amplitudefactor /= 1 + MoverParameters->Vmax; } + else { + return false; + } + return true; +} + +// the sounds of attaching and detaching the couplers and the connections in the internaldata: section; false when the token is none of them +bool TDynamicObject::loadInternalDataCouplerKeyword( cParser &parser, std::string_view token ) { // coupler sounds - else if( token == "couplerattach:" ) { + if( token == "couplerattach:" ) { sound_source soundtemplate { sound_placement::external }; soundtemplate.deserialize( parser, sound_type::single ); soundtemplate.owner( this ); @@ -1809,7 +1979,15 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co couplersounds.detach_heating = soundtemplate; } } - else if( token == "couplerstretch:" ) { + else { + return false; + } + return true; +} + +// the sounds of the stretched couplers, the buffers and the coupler adapters in the internaldata: section; false when the token is none of them +bool TDynamicObject::loadInternalDataBufferKeyword( cParser &parser, std::string_view token ) { + if( token == "couplerstretch:" ) { // coupler stretching sound_source couplerstretch { sound_placement::external }; couplerstretch.deserialize( parser, sound_type::single ); @@ -1863,7 +2041,15 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co couplersounds.dsbAdapterRemove = adapterremove; } } - else if( token == "startjolt:" ) { + else { + return false; + } + return true; +} + +// the start jolt, the shaking, the soundproofing, the light and the destination sign of the cab in the internaldata: section +void TDynamicObject::loadInternalDataCabKeyword( cParser &parser, std::string_view token ) { + if( token == "startjolt:" ) { // movement start jolt m_startjolt.deserialize( parser, sound_type::single ); m_startjolt.owner( this ); @@ -1954,13 +2140,10 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co parser.getTokens(); parser >> DestinationSign.background; } +} - } while( token != "" ); - - } // internaldata: - - } while( token != "" ); - +// the end of loading the .mmd file: the checks, the destination sign and what the file left out +void TDynamicObject::finishLoadingMMediaFile( std::string const &asFileName, std::string const &ReplacableSkin ) { if( !iAnimations ) { // if the animations weren't defined the model is likely to be non-functional. warrants a warning. ErrorLog( "Animations tag is missing from the .mmd file \"" + asFileName + "\"" ); @@ -1976,6 +2159,13 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co DestinationSign.background_sign = draw_script_texture( background, DestinationSign.destination_off ); } + assignDefaultMMediaSounds(); + initMMediaModels(); + positionMMediaSoundEmitters(); +} + +// assigns the default samples to the sound emitters the .mmd file left out +void TDynamicObject::assignDefaultMMediaSounds() { // assign default samples to sound emitters which weren't included in the config file if( TestFlag( MoverParameters->CategoryFlag, 1 ) ) { // rail vehicles: @@ -2026,7 +2216,10 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co rscurve.owner( this ); } } +} +// initialises the loaded 3d models and restores the default paths +void TDynamicObject::initMMediaModels() { if (mdModel) mdModel->Init(); // obrócenie modelu oraz optymalizacja, również zapisanie binarnego if (mdLoad) @@ -2039,7 +2232,10 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co Global.asCurrentTexturePath = paths::textures; // kiedyś uproszczone wnętrze mieszało tekstury nieba Global.asCurrentDynamicPath = ""; +} +// places the sound emitters the .mmd file left without a location +void TDynamicObject::positionMMediaSoundEmitters() { // position sound emitters which weren't defined in the config file // engine sounds, centre of the vehicle auto const enginelocation { glm::vec3 {0.f, MoverParameters->Dim.H * 0.5f, 0.f } }; diff --git a/vehicle/dynamic/sounds.cpp b/vehicle/dynamic/sounds.cpp index a9c402145..6a5821bb9 100644 --- a/vehicle/dynamic/sounds.cpp +++ b/vehicle/dynamic/sounds.cpp @@ -74,7 +74,44 @@ void TDynamicObject::RenderSounds() { auto const dt{ Timer::GetDeltaRenderTime() }; m_powertrainsounds.render( *MoverParameters, dt ); - auto volume{ 0.0 }; + renderAuxiliarySounds(); + + // brake system and braking sounds: + + // brake cylinder piston + auto const brakepressureratio { std::max( 0.0, MoverParameters->BrakePress ) / std::max( 1.0, MoverParameters->MaxBrakePress[ 3 ] ) }; + renderBrakeCylinderSounds( brakepressureratio ); + renderEpBrakeSounds( dt ); + renderEmergencyBrakeSound(); + renderAirReleaseSounds( dt, brakepressureratio ); + renderSlipAndSandSounds(); + auto const brakeforceratio { renderBrakeFrictionSounds( dt ) }; + renderSpringBrakeSounds(); + + // other sounds + renderLoadExchangeSounds(); + renderDepartureSignalSounds(); + renderAnnouncementSounds(); + renderDoorSounds(); + renderHornSounds(); + renderRunningNoise( brakeforceratio ); + renderWheelFlatSound(); + renderCurveSound(); + renderStartJoltSound(); + + // McZapkie! - to wazne - SoundFlag wystawiane jest przez moje moduly gdy zachodza pewne wydarzenia komentowane dzwiekiem. + renderMoverEventSounds(); + renderCouplerSounds(); + + MoverParameters->SoundFlag = 0; + // McZapkie! - koniec obslugi dzwiekow z mover.pas + + renderDerailmentSounds(); +} + +// the sounds of the converter, the braking resistor fans, the compressors, the heater and the battery +void TDynamicObject::renderAuxiliarySounds() { + auto frequency{ 1.0 }; // NBMX dzwiek przetwornicy @@ -181,11 +218,11 @@ void TDynamicObject::RenderSounds() { else { m_batterysound.stop(); } +} - // brake system and braking sounds: +// the sounds of the brake cylinder piston as the pressure in the cylinder rises or falls +void TDynamicObject::renderBrakeCylinderSounds( double const brakepressureratio ) { - // brake cylinder piston - auto const brakepressureratio { std::max( 0.0, MoverParameters->BrakePress ) / std::max( 1.0, MoverParameters->MaxBrakePress[ 3 ] ) }; if( m_lastbrakepressure != -1.f ) { // HACK: potentially reset playback of opening bookend sounds if( false == m_brakecylinderpistonadvance.is_playing() ) { @@ -214,6 +251,10 @@ void TDynamicObject::RenderSounds() { .play(); } } +} + +// the sounds of the electro-pneumatic brake as its pressure rises or falls +void TDynamicObject::renderEpBrakeSounds( double const dt ) { // epbrake - epcompact if (MoverParameters->BrakeSystem == TBrakeSystem::ElectroPneumatic && MoverParameters->LocHandle) { @@ -257,6 +298,10 @@ void TDynamicObject::RenderSounds() { m_lastepbrakepressure = std::min( MoverParameters->LocHandle->GetCP(), MoverParameters->LocalBrakePosAEIM * std::max( 1.0, MoverParameters->MaxBrakePress[0] ) ); } +} + +// the sound of the air flowing out through the emergency brake valve +void TDynamicObject::renderEmergencyBrakeSound() { // emergency brake if( MoverParameters->EmergencyValveFlow > 0.025 ) { @@ -273,6 +318,12 @@ void TDynamicObject::RenderSounds() { m_emergencybrakeflow = 0.0; m_emergencybrake.stop(); } +} + +// the sounds of the air released from the brake cylinder and of the releaser +void TDynamicObject::renderAirReleaseSounds( double const dt, double const brakepressureratio ) { + + auto volume{ 0.0 }; // air release if( m_lastbrakepressure != -1.f ) { @@ -309,6 +360,10 @@ void TDynamicObject::RenderSounds() { else { sReleaser.stop(); } +} + +// the sounds of the slipping wheels and of the sander +void TDynamicObject::renderSlipAndSandSounds() { // slipping wheels if( MoverParameters->SlippingWheels ) { @@ -333,6 +388,12 @@ void TDynamicObject::RenderSounds() { else { sSand.stop(); } +} + +// the sounds of the brake shoes, of the brake accelerator and the squeal of tight brakes; returns the brake force ratio +double TDynamicObject::renderBrakeFrictionSounds( double const dt ) { + + auto volume{ 0.0 }; // brakes auto brakeforceratio{ 0.0 }; @@ -383,6 +444,12 @@ void TDynamicObject::RenderSounds() { rsPisk.stop(); } + return brakeforceratio; +} + +// the sounds of the spring brake being activated or released +void TDynamicObject::renderSpringBrakeSounds() { + // spring brake if( m_springbrakesounds.state != MoverParameters->SpringBrake.Activate ) { m_springbrakesounds.state = MoverParameters->SpringBrake.Activate; @@ -395,8 +462,11 @@ void TDynamicObject::RenderSounds() { m_springbrakesounds.release.play( sound_flags::exclusive ); } } +} + +// the sounds of the load being loaded or unloaded +void TDynamicObject::renderLoadExchangeSounds() { - // other sounds // load exchange if( MoverParameters->LoadStatus & 1 ) { m_exchangesounds.unloading.play( sound_flags::exclusive ); @@ -410,6 +480,11 @@ void TDynamicObject::RenderSounds() { else { m_exchangesounds.loading.stop(); } +} + +// the departure signal of the door speakers +void TDynamicObject::renderDepartureSignalSounds() { + // NBMX sygnal odjazdu if( MoverParameters->Doors.has_warning ) { auto const lowvoltagepower { MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable }; @@ -432,6 +507,11 @@ void TDynamicObject::RenderSounds() { } } } +} + +// the queued announcements of the passenger information system +void TDynamicObject::renderAnnouncementSounds() { + // announcements { auto const lowvoltagepower { MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable }; @@ -457,6 +537,11 @@ void TDynamicObject::RenderSounds() { m_pasystem.announcement_queue.clear(); } } +} + +// the sounds of the doors, the doorsteps and the door locks +void TDynamicObject::renderDoorSounds() { + // NBMX Obsluga drzwi, MC: zuniwersalnione auto const &sides { VehicleSides }; for( auto const side : sides ) { @@ -525,6 +610,10 @@ void TDynamicObject::RenderSounds() { } } } +} + +// the sounds of the horns +void TDynamicObject::renderHornSounds() { // horns { @@ -555,6 +644,14 @@ void TDynamicObject::RenderSounds() { sHorn3.stop(); } } +} + +// the outer noise of the running vehicle, louder with the brakes applied by brakeforceratio +void TDynamicObject::renderRunningNoise( double const brakeforceratio ) { + + auto volume{ 0.0 }; + auto frequency{ 1.0 }; + // szum w czasie jazdy if( GetVelocity() > 0.5 #ifdef EU07_SOUND_BOGIESOUNDS @@ -657,6 +754,11 @@ void TDynamicObject::RenderSounds() { m_outernoise.stop( false == FreeFlyModeFlag ); #endif } +} + +// the sound of the flat spots on the wheels +void TDynamicObject::renderWheelFlatSound() { + // flat spot sound if( MoverParameters->CategoryFlag == 1 ) { // trains only @@ -671,6 +773,12 @@ void TDynamicObject::RenderSounds() { m_wheelflat.stop(); } } +} + +// the squeal of the wheels in sharp curves and on switches +void TDynamicObject::renderCurveSound() { + + auto volume{ 0.0 }; // youBy: dzwiek ostrych lukow i ciasnych zwrotek if( MoverParameters->Vel > 5.0 @@ -701,6 +809,10 @@ void TDynamicObject::RenderSounds() { else { rscurve.stop(); } +} + +// the jolt of the vehicle starting to move +void TDynamicObject::renderStartJoltSound() { // movement start jolt if( false == m_startjoltplayed ) { @@ -712,8 +824,11 @@ void TDynamicObject::RenderSounds() { m_startjoltplayed = true; } } +} + +// the sounds of the pneumatic relay and of the door permit, set in the sound flags of the mover +void TDynamicObject::renderMoverEventSounds() { - // McZapkie! - to wazne - SoundFlag wystawiane jest przez moje moduly gdy zachodza pewne wydarzenia komentowane dzwiekiem. // pneumatic relay if( TestFlag( MoverParameters->SoundFlag, sound::pneumatic ) ) { dsbPneumaticRelay @@ -732,6 +847,10 @@ void TDynamicObject::RenderSounds() { door.permit_granted.play( sound_flags::exclusive ); } } +} + +// the sounds of the buffers, of the couplers stretching and of the couplings attached or detached, and clears their sound flags +void TDynamicObject::renderCouplerSounds() { // couplers int couplerindex { 0 }; @@ -846,9 +965,10 @@ void TDynamicObject::RenderSounds() { ++couplerindex; coupler.sounds = 0; } +} - MoverParameters->SoundFlag = 0; - // McZapkie! - koniec obslugi dzwiekow z mover.pas +// the scraping of the vehicle off the track and the sounds of the special events (derailment), and clears the event flag +void TDynamicObject::renderDerailmentSounds() { // physics.derailment new: off the track the vehicle scrapes along the ground until it stops, or until it is put back // on the rails (rerail()) while still sliding @@ -910,8 +1030,23 @@ TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, doub if( Vehicle.Power == 0 ) { return; } - double frequency { 1.0 }; - double volume { 0.0 }; + renderPumpSounds( Vehicle ); + renderIgnitionSounds( Vehicle ); + renderEngineSounds( Vehicle, Deltatime ); + renderTurboSound( Vehicle, Deltatime ); + renderClutchSound( Vehicle ); + renderRetarderSound( Vehicle ); + renderTractionMotorSounds( Vehicle, Deltatime ); + renderMotorBlowerSounds( Vehicle ); + renderInverterSound( Vehicle ); + renderFanSounds( Vehicle ); + renderRelaySounds( Vehicle ); + renderTransmissionSound( Vehicle ); +} + +// the sounds of the oil, fuel and water pumps and of the water heater +void +TDynamicObject::powertrain_sounds::renderPumpSounds( TMoverParameters const &Vehicle ) { // oil pump if( true == Vehicle.OilPump.is_active ) { @@ -953,6 +1088,12 @@ TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, doub else { water_heater.stop(); } +} + +// the sounds of the engine and the main circuit being switched on or off +void +TDynamicObject::powertrain_sounds::renderIgnitionSounds( TMoverParameters const &Vehicle ) { + // engine sounds // ignition if( engine_state_last != Vehicle.Mains ) { @@ -985,6 +1126,15 @@ TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, doub } engine_state_last = Vehicle.Mains; } +} + +// the sounds of the running engine, of its revving and of the fake engine, and the smoothed engine volume +void +TDynamicObject::powertrain_sounds::renderEngineSounds( TMoverParameters const &Vehicle, double const Deltatime ) { + + double frequency { 1.0 }; + double volume { 0.0 }; + // main engine sound if( true == Vehicle.Mains ) { @@ -1104,6 +1254,13 @@ TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, doub if( engine_volume < 0.05 ) { engine.stop(); } +} + +// the sound of the turbocharger +void +TDynamicObject::powertrain_sounds::renderTurboSound( TMoverParameters const &Vehicle, double const Deltatime ) { + + double volume { 0.0 }; // youBy - przenioslem, bo diesel tez moze miec turbo if( Vehicle.TurboTest > 0 ) { @@ -1132,6 +1289,14 @@ TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, doub engine_turbo.stop(); } } +} + +// the sound of the slipping clutch +void +TDynamicObject::powertrain_sounds::renderClutchSound( TMoverParameters const &Vehicle ) { + + double frequency { 1.0 }; + double volume { 0.0 }; if( Vehicle.diesel.clutchPressure > 0.1 ) { if( std::abs( Vehicle.diesel.clutchSlip ) > 0.2 ) { @@ -1151,6 +1316,11 @@ TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, doub else { rsEngageSlippery.stop(); } +} + +// the sound of the retarder +void +TDynamicObject::powertrain_sounds::renderRetarderSound( TMoverParameters const &Vehicle ) { if (Vehicle.retarder.present) { float speed = std::abs(Vehicle.retarder.revolutions); @@ -1166,6 +1336,14 @@ TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, doub retarder.stop(); } } +} + +// the sounds of the traction motors, the generic ones and the inverter-specific ones +void +TDynamicObject::powertrain_sounds::renderTractionMotorSounds( TMoverParameters const &Vehicle, double const Deltatime ) { + + double frequency { 1.0 }; + double volume { 0.0 }; // motor sounds volume = 0.0; @@ -1279,6 +1457,12 @@ TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, doub } } } +} + +// the sounds of the motor blowers, each matched with the blower at its end of the vehicle +void +TDynamicObject::powertrain_sounds::renderMotorBlowerSounds( TMoverParameters const &Vehicle ) { + // motor blowers if( false == motorblowers.empty() ) { for( auto &blowersound : motorblowers ) { @@ -1301,6 +1485,14 @@ TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, doub } } } +} + +// the sound of the inverter +void +TDynamicObject::powertrain_sounds::renderInverterSound( TMoverParameters const &Vehicle ) { + + double volume { 0.0 }; + // inverter sounds if( Vehicle.EngineType == TEngineType::ElectricInductionMotor ) { if( Vehicle.inductionMotor.inverterFrequency > 0.001 ) { @@ -1316,6 +1508,12 @@ TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, doub inverter.stop(); } } +} + +// the sounds of the ventilator and of the radiator fans +void +TDynamicObject::powertrain_sounds::renderFanSounds( TMoverParameters const &Vehicle ) { + // ventillator sounds if( Vehicle.RventRot > 0.1 ) { @@ -1356,6 +1554,11 @@ TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, doub radiator_fan_aux.stop(); } } +} + +// the sounds of the relays, set in the sound flags of the vehicle +void +TDynamicObject::powertrain_sounds::renderRelaySounds( TMoverParameters const &Vehicle ) { // relay sounds auto const soundflags { Vehicle.SoundFlag }; @@ -1401,6 +1604,11 @@ TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, doub .play(); } } +} + +// the sound of the transmission +void +TDynamicObject::powertrain_sounds::renderTransmissionSound( TMoverParameters const &Vehicle ) { if( Vehicle.Vel > 0.1 ) { transmission diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index 275e4996c..c934f2724 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -113,7 +113,80 @@ bool TDynamicObject::Update(double dt, double dt1) if (!bEnabled) return false; // a normalnie powinny mieć bEnabled==false - double dDOMoveLen; + updateTrackParameters(); + updateCouplingState(); + updateTractionVoltage( dt1 ); + // McZapkie: predkosc w torze przekazac do TrackParam + // McZapkie: Vel ma wymiar [km/h] (absolutny), V ma wymiar [m/s], taka przyjalem notacje + tp.Velmax = MyTrack->VelocityGet(); + + if (Mechanik) + { // Ra 2F3F: do Driver.cpp to przenieść? + updateDriver( dt1 ); + } + + switchOffMainsWithoutBattery(); + + double const dDOMoveLen { moveByPhysics( dt, dt1 ) }; + + if (!bEnabled) // usuwane pojazdy nie mają toru + { // pojazd do usunięcia + bDynamicRemove = true; // sprawdzić + return false; + } + ResetdMoveLen(); + + updateAxleClatter( dDOMoveLen ); + + // fragment z EXE Kursa + /* if (MoverParameters->TrainType==train_type::et42) + { + if ((MoverParameters->DynamicBrakeType=dbrake_switch) && + ((MoverParameters->BrakePress > + 0.2) || ( MoverParameters->PipePress < 0.36 ))) + { + MoverParameters->StLinFlag=true; + } + else + if ((MoverParameters->DynamicBrakeType=dbrake_switch) && + (MoverParameters->BrakePress < + 0.1)) + { + MoverParameters->StLinFlag=false; + + } + } */ + + updateWheelAngles( dt1 ); + updateCurrentCollectors( dt1 ); + 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 + if( ctOwner != nullptr ? SectionLightsActive != MoverParameters->CompartmentLights.is_active : + Mechanik != nullptr ? SectionLightsActive != MoverParameters->CompartmentLights.is_active : + SectionLightsActive ) { // without controller switch the lights off + toggle_lights(); + } + + if (MoverParameters->InactiveCabPantsCheck) + { + pants_up(); + MoverParameters->InactiveCabPantsCheck = false; + } + + if( MoverParameters->LoadStatus ) { + LoadUpdate(); // zmiana modelu ładunku + } + update_exchange( dt ); + + return true; // Ra: chyba tak? +} + +// the shape and the parameters of the track under the vehicle, for its physics +void TDynamicObject::updateTrackParameters() +{ // McZapkie: parametry powinny byc pobierane z toru if (Axle0.vAngles.z != Axle1.vAngles.z) { // wyliczenie promienia z obrotów osi - modyfikację zgłosił youBy @@ -156,7 +229,11 @@ bool TDynamicObject::Update(double dt, double dt1) tp.DamageFlag = MyTrack->iDamageFlag; tp.QualityFlag = MyTrack->iQualityFlag; tp.Name = &MyTrack->name(); +} +// the vehicle inside the consist or at its end, and the consist checked once a coupler was attached +void TDynamicObject::updateCouplingState() +{ // couplers if( MoverParameters->Couplers[0].CouplingFlag != Coupling::none && MoverParameters->Couplers[1].CouplingFlag != Coupling::none ) { @@ -172,7 +249,11 @@ bool TDynamicObject::Update(double dt, double dt1) } ClearFlag( MoverParameters->AIFlag, sound::attachcoupler ); } +} +// the voltage of the supply of the vehicle, kept over a short loss of contact, passed to its physics +void TDynamicObject::updateTractionVoltage( double const dt1 ) +{ // napiecie sieci trakcyjnej if (MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) { // dla EZT tylko silnikowy @@ -215,369 +296,443 @@ bool TDynamicObject::Update(double dt, double dt1) tmpTraction.TractionResistivity = 0.3; MoverParameters->PantographVoltage = tmpTraction.TractionVoltage; - // McZapkie: predkosc w torze przekazac do TrackParam - // McZapkie: Vel ma wymiar [km/h] (absolutny), V ma wymiar [m/s], taka przyjalem notacje - tp.Velmax = MyTrack->VelocityGet(); +} - if (Mechanik) - { // Ra 2F3F: do Driver.cpp to przenieść? - if( Mechanik->primary() ) { - MoverParameters->EqvtPipePress = GetEPP(); // srednie cisnienie w PG - } - if (Mechanik->primary() && - (MoverParameters->EngineType == TEngineType::DieselEngine || - MoverParameters->EngineType == TEngineType::DieselElectric) - && MoverParameters->EIMCtrlType > 0) { - MoverParameters->CheckEIMIC(dt1); - if (MoverParameters->SpeedCtrl) - MoverParameters->CheckSpeedCtrl(dt1); - MoverParameters->eimic_real = std::min(MoverParameters->eimic,MoverParameters->eimicSpeedCtrl); - MoverParameters->SendCtrlToNext(VehicleCommand::integratedController, MoverParameters->eimic_real, MoverParameters->CabActive); - } - if( Mechanik->primary() - && MoverParameters->EngineType == TEngineType::ElectricInductionMotor ) { - // jesli glowny i z asynchronami, to niech steruje hamulcem i napedem lacznie dla calego pociagu/ezt - auto const kier = DirectionGet() * MoverParameters->CabOccupied > 0; - auto FED { 0.0 }; - auto np { 0 }; - auto masa { 0.0 }; - auto FrED { 0.0 }; - auto masamax { 0.0 }; - auto FmaxPN { 0.0 }; - auto FfulED { 0.0 }; - auto FmaxED { 0.0 }; - auto Frj { 0.0 }; - auto osie { 0 }; - // 0a. ustal aktualna nastawe zadania sily napedowej i hamowania - if( MoverParameters->Power < 1 - && ctOwner != nullptr ) { - MoverParameters->MainCtrlPos = ctOwner->Controlling()->MainCtrlPos*MoverParameters->MainCtrlPosNo / std::max(1, ctOwner->Controlling()->MainCtrlPosNo); - MoverParameters->SpeedCtrlValue = ctOwner->Controlling()->SpeedCtrlValue; - MoverParameters->SpeedCtrlUnit.IsActive = ctOwner->Controlling()->SpeedCtrlUnit.IsActive; - } - MoverParameters->CheckEIMIC(dt1); - MoverParameters->CheckSpeedCtrl(dt1); - - auto eimic = std::min(MoverParameters->eimic, MoverParameters->eimicSpeedCtrl); - MoverParameters->eimic_real = eimic; - // Elf: full braking at once in the lowest position, and in the emergency brake position below it - if (MoverParameters->EIMCtrlType == 2 && MoverParameters->MainCtrlPos <= MoverParameters->EIMCtrlEmergencyPositions()) - eimic = -1.0; - MoverParameters->SendCtrlToNext(VehicleCommand::integratedController, std::max(0., eimic), MoverParameters->CabActive); - auto LBR = std::max(-eimic, 0.); - auto eim_lb = Mechanik->AIControllFlag || !MoverParameters->LocHandleTimeTraxx ? 0 : MoverParameters->eim_localbrake; - - // 1. ustal wymagana sile hamowania calego pociagu - // - opoznienie moze byc ustalane na podstawie charakterystyki - // - opoznienie moze byc ustalane na podstawie mas i cisnien granicznych - // - - // 2. ustal mozliwa do realizacji sile hamowania ED - // - w szczegolnosci powinien brac pod uwage rozne sily hamowania - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; - kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) - { - ++np; - masamax += - p->MoverParameters->MBPM - + ( p->MoverParameters->MBPM > 1.0 ? - 0.0 : - p->MoverParameters->Mass ) - + p->MoverParameters->Mred; - auto const Nmax = ((p->MoverParameters->P2FTrans * p->MoverParameters->MaxBrakePress[0] - - p->MoverParameters->BrakeCylSpring) * - p->MoverParameters->BrakeCylMult[0] - - p->MoverParameters->BrakeSlckAdj) * - p->MoverParameters->BrakeCylNo * p->MoverParameters->BrakeRigEff; - FmaxPN += Nmax * p->MoverParameters->Hamulec->GetFC( - Nmax / (p->MoverParameters->NAxles * p->MoverParameters->NBpA), - p->MoverParameters->MED_Vref) * - 1000; // sila hamowania pn - FmaxED += p->MoverParameters->Mains && p->MoverParameters->DirActive != 0 && p->MoverParameters->inductionMotor.inverterRatio == 1.0 && - p->MoverParameters->inductionMotor.braking.maxForce * p->MoverParameters->NPoweredAxles > 0 ? - p->MoverParameters->inductionMotor.braking.maxForce * 1000 : - 0; // chwilowy max ED -> do rozdzialu sil - FED -= std::min(p->MoverParameters->inductionMotor.state.maxForce, 0.0) * - 1000; // chwilowy max ED -> do rozdzialu sil - FfulED = std::min(p->MoverParameters->inductionMotor.state.fullForce, 0.0) * - 1000; // chwilowy max ED -> do rozdzialu sil - FrED -= std::min(p->MoverParameters->inductionMotor.state.maxForce, 0.0) * - 1000; // chwilowo realizowane ED -> do pneumatyki - Frj += std::max(p->MoverParameters->inductionMotor.state.maxForce, 0.0) * - 1000;// chwilowo realizowany napęd -> do utrzymującego - masa += p->MoverParameters->TotalMass; - osie += p->MoverParameters->NAxles; - } - double RapidMult = 1.0; - if ((MoverParameters->BrakeDelays & bdelay_P + bdelay_R) == bdelay_P + bdelay_R - && MoverParameters->BrakeDelayFlag & bdelay_P) - RapidMult = MoverParameters->RapidMult; - - auto const amax = RapidMult * std::min(FmaxPN / masamax, MoverParameters->MED_amax); - - Mechanik->fMedAmax = amax; - auto doorisopen { - false == MoverParameters->Doors.instances[VehicleSide::left].is_closed - || false == MoverParameters->Doors.instances[VehicleSide::right].is_closed - || ( MoverParameters->Doors.permit_needed - && ( MoverParameters->Doors.instances[ VehicleSide::left ].open_permit - || MoverParameters->Doors.instances[ VehicleSide::right ].open_permit ) ) }; - doorisopen &= !(MoverParameters->ReleaseParkingBySpringBrakeWhenDoorIsOpen && MoverParameters->SpringBrake.IsActive); - - if (MoverParameters->Vel < 0.5 && (eimic < 0 || doorisopen || MoverParameters->Hamulec->GetEDBCP())) - { - MoverParameters->ShuntMode = true; - } - if (MoverParameters->ShuntMode) - { - MoverParameters->ShuntModeAllow = false == doorisopen && - LBR < 0.01; - } - if( MoverParameters->Vel > 1 && false == doorisopen ) - { - MoverParameters->ShuntMode = false; - MoverParameters->ShuntModeAllow = MoverParameters->BrakePress > 0.2 && - LBR < 0.01; - } - auto Fzad = amax * LBR * masa; - if ((MoverParameters->BrakeCtrlPos == MoverParameters->Handle->GetPos(bh_EB) - && MoverParameters->inductionMotor.braking.cylinderPressureGain < 0.001) || - MoverParameters->EmergencyValveFlow > 0) - Fzad = amax * masa; //pętla bezpieczeństwa - pełne służbowe - if (MoverParameters->ScndS && - MoverParameters->Vel > MoverParameters->inductionMotor.braking.fullSpeed && FmaxED > 0) - { - Fzad = std::min(LBR * FmaxED, FfulED); - } - // the holding brake lets go once power has been demanded for its delay (SBDReleaseDelay, none by default) - auto const holdingbrakereleased { MoverParameters->UpdateStopBrakeRelease( eimic, dt1 ) }; - if (MoverParameters->ShuntMode && false == holdingbrakereleased || doorisopen /*|| - (MoverParameters->V * MoverParameters->DirAbsolute < -0.2)*/) - { - auto const sbd { ( MoverParameters->SpringBrake.IsActive && MoverParameters->ReleaseParkingBySpringBrake ? 0.0 : MoverParameters->StopBrakeDecc ) }; - Fzad = std::max( Fzad, sbd * masa ); - } - if (Fzad > 1 && !MEDLogFile.is_open() && MoverParameters->Vel > 1) - { - MEDLogFile.open( - "MEDLOGS/" + MoverParameters->Name + "_" + std::to_string( ++MEDLogCount ) + ".csv", - std::ios::in | std::ios::out | std::ios::trunc ); - MEDLogFile << "t\tVel\tMasa\tOsie\tFmaxPN\tFmaxED\tFfulED\tFrED\tFzad\tFzadED\tFzadPN"; - for(int k=1;k<=np;k++) - { - MEDLogFile << "\tBP" << k; - } - MEDLogFile << "\n"; - MEDLogFile.flush(); - MEDLogInactiveTime = 0; - MEDLogTime = 0; - } - auto FzadED { 0.0 }; - if( LBR > MoverParameters->MED_MinBrakeReqED - && ( MoverParameters->BrakeHandle == TBrakeHandle::MHZ_EN57 ? - (MoverParameters->BrakeOpModeFlag & bom_MED) != 0 : - MoverParameters->EpFuse ) ) { - FzadED = std::min( Fzad, FmaxED ); - } - /*/ELF - wdrazanie ED po powrocie na utrzymanie hamowania - do usuniecia - if (MoverParameters->EIMCtrlType == 2 && MoverParameters->MainCtrlPos < 2 && MoverParameters->eimic > -0.999) - { - FzadED = std::min(FzadED, MED_oldFED); - } //*/ - //opoznienie wdrazania ED - if (FzadED > MED_oldFED) - { - if (MoverParameters->MED_ED_DelayTimer <= 0) { - MoverParameters->MED_ED_DelayTimer += dt1; - if (MoverParameters->MED_ED_DelayTimer > 0) { - - } - else { - FzadED = std::min(FzadED, MED_oldFED); - } - } - else - { - FzadED = std::min(FzadED, MED_oldFED); - MoverParameters->MED_ED_DelayTimer = FrED > 0 ? -MoverParameters->MED_ED_Delay2 : -MoverParameters->MED_ED_Delay1; - } - } - if (MoverParameters->BrakeCtrlPos == MoverParameters->Handle->GetPos(bh_EB) - && MoverParameters->inductionMotor.braking.cylinderPressureGain < 0.001) - FzadED = 0; //pętla bezpieczeństwa - bez ED - auto const FzadPN = Fzad - FrED * MoverParameters->MED_FrED_factor; - std::vector PrzekrF( np ); - float nPrzekrF = 0; - bool test = true; - std::vector FzED( np ); - std::vector FzEP( np ); - std::vector FmaxEP( np ); - // 3. ustaw pojazdom sile hamowania ED - // - proporcjonalnie do mozliwosci - - // 4. ustal potrzebne dohamowanie pneumatyczne - // - od sily zadanej trzeba odjac realizowana przez ED - // 5. w razie potrzeby wlacz hamulec utrzymujacy - // - gdy zahamowany ma ponizej 2 km/h - // 6. ustaw pojazdom sile hamowania ep - // - proporcjonalnie do masy, do liczby osi, rowne cisnienia - jak - // bedzie, tak bedzie dobrze - float Fpoj = 0; // MoverParameters->CabOccupied < 0 - ////ALGORYTM 2 - KAZDEMU PO ROWNO, ale nie wiecej niz eped * masa - // 1. najpierw daj kazdemu tyle samo - int i = 0; - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; - p = kier == true ? p->Next(Coupling::control) : p->Prev(Coupling::control) ) - { - auto const Nmax = ((p->MoverParameters->P2FTrans * p->MoverParameters->MaxBrakePress[0] - - p->MoverParameters->BrakeCylSpring) * - p->MoverParameters->BrakeCylMult[0] - - p->MoverParameters->BrakeSlckAdj) * - p->MoverParameters->BrakeCylNo * p->MoverParameters->BrakeRigEff; - FmaxEP[i] = Nmax * - p->MoverParameters->Hamulec->GetFC( - Nmax / (p->MoverParameters->NAxles * p->MoverParameters->NBpA), - p->MoverParameters->MED_Vref) * - 1000; // sila hamowania pn - - PrzekrF[i] = false; - FzED[i] = FmaxED > 0 ? FzadED / FmaxED : 0; - p->MoverParameters->AnPos = - MoverParameters->ScndS ? LBR : FzED[i]; - FzEP[ i ] = static_cast( FzadPN * p->MoverParameters->NAxles ) / static_cast( osie ); - ++i; - p->MoverParameters->ShuntMode = MoverParameters->ShuntMode; - p->MoverParameters->ShuntModeAllow = MoverParameters->ShuntModeAllow; - } - while (test) - { - test = false; - i = 0; - float przek = 0; - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; - p = kier == true ? p->Next(Coupling::control) : p->Prev(Coupling::control) ) - { - if (FzEP[i] > 0.01 && - FzEP[i] > p->MoverParameters->TotalMass * p->MoverParameters->inductionMotor.braking.maxEpDeceleration + std::min(p->MoverParameters->inductionMotor.state.maxForce, 0.) * 1000 && - !PrzekrF[i]) - { - float przek1 = -std::min(p->MoverParameters->inductionMotor.state.maxForce, 0.) * 1000 + - FzEP[i] - - p->MoverParameters->TotalMass * - p->MoverParameters->inductionMotor.braking.maxEpDeceleration * 0.999; - PrzekrF[i] = true; - test = true; - nPrzekrF++; - przek1 = std::min(przek1, FzEP[i]); - FzEP[i] -= przek1; - if (FzEP[i] < 0) - FzEP[i] = 0; - przek += przek1; - } - ++i; - } - i = 0; - przek = przek / (np - nPrzekrF); - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; - true == kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) - { - if (!PrzekrF[i]) - { - FzEP[i] += przek; - } - ++i; - } - } - i = 0; - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; - true == kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) - { - float Nmax = ((p->MoverParameters->P2FTrans * p->MoverParameters->MaxBrakePress[0] - - p->MoverParameters->BrakeCylSpring) * - p->MoverParameters->BrakeCylMult[0] - - p->MoverParameters->BrakeSlckAdj) * - p->MoverParameters->BrakeCylNo * p->MoverParameters->BrakeRigEff; - if (FrED > 0.1) - p->MoverParameters->MED_EPVC_CurrentTime = 0; - else - p->MoverParameters->MED_EPVC_CurrentTime += dt1; - bool EPVC = p->MoverParameters->MED_EPVC && (p->MoverParameters->MED_EPVC_Time < 0 || p->MoverParameters->MED_EPVC_CurrentTime < p->MoverParameters->MED_EPVC_Time); - float VelC = EPVC ? safe_clamp(p->MoverParameters->Vel, p->MoverParameters->MED_Vmin, p->MoverParameters->MED_Vmax) : p->MoverParameters->MED_Vref;//korekcja EP po prędkości - float FmaxPoj = Nmax * - p->MoverParameters->Hamulec->GetFC( - Nmax / (p->MoverParameters->NAxles * p->MoverParameters->NBpA), VelC) * - 1000; // sila hamowania pn - p->MoverParameters->LocalBrakePosAEIM = FzEP[i] / FmaxPoj; - if (p->MoverParameters->LocalBrakePosAEIM>0.009) - if (p->MoverParameters->P2FTrans * p->MoverParameters->BrakeCylMult[0] * - p->MoverParameters->MaxBrakePress[0] != 0) - { - float x = (p->MoverParameters->BrakeSlckAdj / p->MoverParameters->BrakeCylMult[0] + - p->MoverParameters->BrakeCylSpring) / (p->MoverParameters->P2FTrans * - p->MoverParameters->MaxBrakePress[0]); - p->MoverParameters->LocalBrakePosAEIM = x + (1 - x) * p->MoverParameters->LocalBrakePosAEIM; - } - else - p->MoverParameters->LocalBrakePosAEIM = p->MoverParameters->LocalBrakePosAEIM; - else - p->MoverParameters->LocalBrakePosAEIM = 0; - if (p->MoverParameters->LocHandleTimeTraxx) - { - p->MoverParameters->eim_localbrake = eim_lb; - p->MoverParameters->LocalBrakePosAEIM = std::max(p->MoverParameters->LocalBrakePosAEIM, eim_lb); - } - ++i; - } - - MED[0][0] = masa*0.001; - MED[0][1] = amax; - MED[0][2] = Fzad*0.001; - MED[0][3] = FmaxPN*0.001; - MED[0][4] = FmaxED*0.001; - MED[0][5] = FrED*0.001; - MED[0][6] = FzadPN*0.001; - MED[0][7] = nPrzekrF; - - if (MEDLogFile.is_open()) - { - MEDLogFile << MEDLogTime << "\t" << MoverParameters->Vel << "\t" << masa*0.001 << "\t" << osie << "\t" << FmaxPN*0.001 << "\t" << FmaxED*0.001 << "\t" - << FfulED*0.001 << "\t" << FrED*0.001 << "\t" << Fzad*0.001 << "\t" << FzadED*0.001 << "\t" << FzadPN*0.001; - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; - true == kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) - { - MEDLogFile << "\t" << p->MoverParameters->BrakePress; - } - MEDLogFile << "\n"; - if (floor(MEDLogTime + dt1) > floor(MEDLogTime)) - { - MEDLogFile.flush(); - } - MEDLogTime += dt1; - - if (MoverParameters->Vel < 0.1 || MoverParameters->MainCtrlPowerPos() > 0) - { - MEDLogInactiveTime += dt1; - } - else - { - MEDLogInactiveTime = 0; - } - if (MEDLogInactiveTime > 5) - { - MEDLogFile.flush(); - MEDLogFile.close(); - } - - } - - MED_oldFED = FzadED; - } - - Timer::subsystem.vehicles_ai.start(); - Mechanik->Update(dt1); // przebłyski świadomości AI - Timer::subsystem.vehicles_ai.stop(); +// the driver of the vehicle: the integrated controller, the brakes blended over a consist with induction motors, the AI +void TDynamicObject::updateDriver( double const dt1 ) +{ + if( Mechanik->primary() ) { + MoverParameters->EqvtPipePress = GetEPP(); // srednie cisnienie w PG + } + if (Mechanik->primary() && + (MoverParameters->EngineType == TEngineType::DieselEngine || + MoverParameters->EngineType == TEngineType::DieselElectric) + && MoverParameters->EIMCtrlType > 0) { + MoverParameters->CheckEIMIC(dt1); + if (MoverParameters->SpeedCtrl) + MoverParameters->CheckSpeedCtrl(dt1); + MoverParameters->eimic_real = std::min(MoverParameters->eimic,MoverParameters->eimicSpeedCtrl); + MoverParameters->SendCtrlToNext(VehicleCommand::integratedController, MoverParameters->eimic_real, MoverParameters->CabActive); + } + if( Mechanik->primary() + && MoverParameters->EngineType == TEngineType::ElectricInductionMotor ) { + // jesli glowny i z asynchronami, to niech steruje hamulcem i napedem lacznie dla calego pociagu/ezt + distributeInductionBraking( dt1 ); } + Timer::subsystem.vehicles_ai.start(); + Mechanik->Update(dt1); // przebłyski świadomości AI + Timer::subsystem.vehicles_ai.stop(); +} + +// the state shared by the steps of the blending of the brakes over a consist with induction motors +struct TDynamicObject::InductionBrakeState { + bool kier { false }; + int np { 0 }; + double masa { 0.0 }; + double FrED { 0.0 }; + double masamax { 0.0 }; + double FmaxPN { 0.0 }; + double FfulED { 0.0 }; + double FmaxED { 0.0 }; + int osie { 0 }; + double eimic { 0.0 }; + double LBR { 0.0 }; + double eim_lb { 0.0 }; + double amax { 0.0 }; + bool doorisopen { false }; + double Fzad { 0.0 }; + double FzadED { 0.0 }; + double FzadPN { 0.0 }; + float nPrzekrF { 0.f }; +}; + +// the consist with induction motors driven and braked as a whole, its braking split between the ED and the EP brakes +void TDynamicObject::distributeInductionBraking( double const dt1 ) +{ + InductionBrakeState state; + state.kier = DirectionGet() * MoverParameters->CabOccupied > 0; + setInductionControl( state, dt1 ); + sumConsistBrakeForces( state ); + computeBrakeDeceleration( state ); + updateShuntMode( state ); + computeBrakeDemand( state, dt1 ); + openMedLog( state ); + computeElectrodynamicDemand( state, dt1 ); + distributeBrakeForces( state, dt1 ); + recordMedState( state, dt1 ); + + MED_oldFED = state.FzadED; +} + +// step 0a of the blending: the demand of the integrated controller read and passed down the consist +void TDynamicObject::setInductionControl( InductionBrakeState &state, double const dt1 ) +{ + // 0a. ustal aktualna nastawe zadania sily napedowej i hamowania + if( MoverParameters->Power < 1 + && ctOwner != nullptr ) { + MoverParameters->MainCtrlPos = ctOwner->Controlling()->MainCtrlPos*MoverParameters->MainCtrlPosNo / std::max(1, ctOwner->Controlling()->MainCtrlPosNo); + MoverParameters->SpeedCtrlValue = ctOwner->Controlling()->SpeedCtrlValue; + MoverParameters->SpeedCtrlUnit.IsActive = ctOwner->Controlling()->SpeedCtrlUnit.IsActive; + } + MoverParameters->CheckEIMIC(dt1); + MoverParameters->CheckSpeedCtrl(dt1); + + state.eimic = std::min(MoverParameters->eimic, MoverParameters->eimicSpeedCtrl); + MoverParameters->eimic_real = state.eimic; + // Elf: full braking at once in the lowest position, and in the emergency brake position below it + if (MoverParameters->EIMCtrlType == 2 && MoverParameters->MainCtrlPos <= MoverParameters->EIMCtrlEmergencyPositions()) + state.eimic = -1.0; + MoverParameters->SendCtrlToNext(VehicleCommand::integratedController, std::max(0., state.eimic), MoverParameters->CabActive); + state.LBR = std::max(-state.eimic, 0.); + state.eim_lb = Mechanik->AIControllFlag || !MoverParameters->LocHandleTimeTraxx ? 0 : MoverParameters->eim_localbrake; +} + +// steps 1-2 of the blending: the masses and the most braking forces, pneumatic and ED, summed over the consist +void TDynamicObject::sumConsistBrakeForces( InductionBrakeState &state ) +{ + auto FED { 0.0 }; + auto Frj { 0.0 }; + + // 1. ustal wymagana sile hamowania calego pociagu + // - opoznienie moze byc ustalane na podstawie charakterystyki + // - opoznienie moze byc ustalane na podstawie mas i cisnien granicznych + // + + // 2. ustal mozliwa do realizacji sile hamowania ED + // - w szczegolnosci powinien brac pod uwage rozne sily hamowania + for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; + state.kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) + { + ++state.np; + state.masamax += + p->MoverParameters->MBPM + + ( p->MoverParameters->MBPM > 1.0 ? + 0.0 : + p->MoverParameters->Mass ) + + p->MoverParameters->Mred; + auto const Nmax = ((p->MoverParameters->P2FTrans * p->MoverParameters->MaxBrakePress[0] - + p->MoverParameters->BrakeCylSpring) * + p->MoverParameters->BrakeCylMult[0] - + p->MoverParameters->BrakeSlckAdj) * + p->MoverParameters->BrakeCylNo * p->MoverParameters->BrakeRigEff; + state.FmaxPN += Nmax * p->MoverParameters->Hamulec->GetFC( + Nmax / (p->MoverParameters->NAxles * p->MoverParameters->NBpA), + p->MoverParameters->MED_Vref) * + 1000; // sila hamowania pn + state.FmaxED += p->MoverParameters->Mains && p->MoverParameters->DirActive != 0 && p->MoverParameters->inductionMotor.inverterRatio == 1.0 && + p->MoverParameters->inductionMotor.braking.maxForce * p->MoverParameters->NPoweredAxles > 0 ? + p->MoverParameters->inductionMotor.braking.maxForce * 1000 : + 0; // chwilowy max ED -> do rozdzialu sil + FED -= std::min(p->MoverParameters->inductionMotor.state.maxForce, 0.0) * + 1000; // chwilowy max ED -> do rozdzialu sil + state.FfulED = std::min(p->MoverParameters->inductionMotor.state.fullForce, 0.0) * + 1000; // chwilowy max ED -> do rozdzialu sil + state.FrED -= std::min(p->MoverParameters->inductionMotor.state.maxForce, 0.0) * + 1000; // chwilowo realizowane ED -> do pneumatyki + Frj += std::max(p->MoverParameters->inductionMotor.state.maxForce, 0.0) * + 1000;// chwilowo realizowany napęd -> do utrzymującego + state.masa += p->MoverParameters->TotalMass; + state.osie += p->MoverParameters->NAxles; + } +} + +// the most deceleration of the service braking of the consist, given to the driver too +void TDynamicObject::computeBrakeDeceleration( InductionBrakeState &state ) +{ + double RapidMult = 1.0; + if ((MoverParameters->BrakeDelays & bdelay_P + bdelay_R) == bdelay_P + bdelay_R + && MoverParameters->BrakeDelayFlag & bdelay_P) + RapidMult = MoverParameters->RapidMult; + + state.amax = RapidMult * std::min(state.FmaxPN / state.masamax, MoverParameters->MED_amax); + + Mechanik->fMedAmax = state.amax; +} + +// the doors open or closed, and from them, the demand and the speed the shunting mode (the holding brake) of the consist +void TDynamicObject::updateShuntMode( InductionBrakeState &state ) +{ + state.doorisopen = + false == MoverParameters->Doors.instances[VehicleSide::left].is_closed + || false == MoverParameters->Doors.instances[VehicleSide::right].is_closed + || ( MoverParameters->Doors.permit_needed + && ( MoverParameters->Doors.instances[ VehicleSide::left ].open_permit + || MoverParameters->Doors.instances[ VehicleSide::right ].open_permit ) ); + state.doorisopen &= !(MoverParameters->ReleaseParkingBySpringBrakeWhenDoorIsOpen && MoverParameters->SpringBrake.IsActive); + + if (MoverParameters->Vel < 0.5 && (state.eimic < 0 || state.doorisopen || MoverParameters->Hamulec->GetEDBCP())) + { + MoverParameters->ShuntMode = true; + } + if (MoverParameters->ShuntMode) + { + MoverParameters->ShuntModeAllow = false == state.doorisopen && + state.LBR < 0.01; + } + if( MoverParameters->Vel > 1 && false == state.doorisopen ) + { + MoverParameters->ShuntMode = false; + MoverParameters->ShuntModeAllow = MoverParameters->BrakePress > 0.2 && + state.LBR < 0.01; + } +} +// the braking force demanded of the whole consist +void TDynamicObject::computeBrakeDemand( InductionBrakeState &state, double const dt1 ) +{ + state.Fzad = state.amax * state.LBR * state.masa; + if ((MoverParameters->BrakeCtrlPos == MoverParameters->Handle->GetPos(bh_EB) + && MoverParameters->inductionMotor.braking.cylinderPressureGain < 0.001) || + MoverParameters->EmergencyValveFlow > 0) + state.Fzad = state.amax * state.masa; //pętla bezpieczeństwa - pełne służbowe + if (MoverParameters->ScndS && + MoverParameters->Vel > MoverParameters->inductionMotor.braking.fullSpeed && state.FmaxED > 0) + { + state.Fzad = std::min(state.LBR * state.FmaxED, state.FfulED); + } + // the holding brake lets go once power has been demanded for its delay (SBDReleaseDelay, none by default) + auto const holdingbrakereleased { MoverParameters->UpdateStopBrakeRelease( state.eimic, dt1 ) }; + if (MoverParameters->ShuntMode && false == holdingbrakereleased || state.doorisopen /*|| + (MoverParameters->V * MoverParameters->DirAbsolute < -0.2)*/) + { + auto const sbd { ( MoverParameters->SpringBrake.IsActive && MoverParameters->ReleaseParkingBySpringBrake ? 0.0 : MoverParameters->StopBrakeDecc ) }; + state.Fzad = std::max( state.Fzad, sbd * state.masa ); + } +} + +// the log of the braking of the consist opened, once it brakes while moving +void TDynamicObject::openMedLog( InductionBrakeState const &state ) +{ + if (state.Fzad > 1 && !MEDLogFile.is_open() && MoverParameters->Vel > 1) + { + MEDLogFile.open( + "MEDLOGS/" + MoverParameters->Name + "_" + std::to_string( ++MEDLogCount ) + ".csv", + std::ios::in | std::ios::out | std::ios::trunc ); + MEDLogFile << "t\tVel\tMasa\tOsie\tFmaxPN\tFmaxED\tFfulED\tFrED\tFzad\tFzadED\tFzadPN"; + for(int k=1;k<=state.np;k++) + { + MEDLogFile << "\tBP" << k; + } + MEDLogFile << "\n"; + MEDLogFile.flush(); + MEDLogInactiveTime = 0; + MEDLogTime = 0; + } +} + +// the part of the demand the ED brake takes, brought in with a delay, and the rest left to the pneumatic brake +void TDynamicObject::computeElectrodynamicDemand( InductionBrakeState &state, double const dt1 ) +{ + state.FzadED = 0.0; + if( state.LBR > MoverParameters->MED_MinBrakeReqED + && ( MoverParameters->BrakeHandle == TBrakeHandle::MHZ_EN57 ? + (MoverParameters->BrakeOpModeFlag & bom_MED) != 0 : + MoverParameters->EpFuse ) ) { + state.FzadED = std::min( state.Fzad, state.FmaxED ); + } + /*/ELF - wdrazanie ED po powrocie na utrzymanie hamowania - do usuniecia + if (MoverParameters->EIMCtrlType == 2 && MoverParameters->MainCtrlPos < 2 && MoverParameters->eimic > -0.999) + { + FzadED = std::min(FzadED, MED_oldFED); + } //*/ + //opoznienie wdrazania ED + if (state.FzadED > MED_oldFED) + { + if (MoverParameters->MED_ED_DelayTimer <= 0) { + MoverParameters->MED_ED_DelayTimer += dt1; + if (MoverParameters->MED_ED_DelayTimer > 0) { + + } + else { + state.FzadED = std::min(state.FzadED, MED_oldFED); + } + } + else + { + state.FzadED = std::min(state.FzadED, MED_oldFED); + MoverParameters->MED_ED_DelayTimer = state.FrED > 0 ? -MoverParameters->MED_ED_Delay2 : -MoverParameters->MED_ED_Delay1; + } + } + if (MoverParameters->BrakeCtrlPos == MoverParameters->Handle->GetPos(bh_EB) + && MoverParameters->inductionMotor.braking.cylinderPressureGain < 0.001) + state.FzadED = 0; //pętla bezpieczeństwa - bez ED + state.FzadPN = state.Fzad - state.FrED * MoverParameters->MED_FrED_factor; +} +// steps 3-6 of the blending: the ED and the pneumatic braking forces set to the vehicles of the consist +void TDynamicObject::distributeBrakeForces( InductionBrakeState &state, double const dt1 ) +{ + std::vector PrzekrF( state.np ); + state.nPrzekrF = 0; + bool test = true; + std::vector FzED( state.np ); + std::vector FzEP( state.np ); + std::vector FmaxEP( state.np ); + // 3. ustaw pojazdom sile hamowania ED + // - proporcjonalnie do mozliwosci + + // 4. ustal potrzebne dohamowanie pneumatyczne + // - od sily zadanej trzeba odjac realizowana przez ED + // 5. w razie potrzeby wlacz hamulec utrzymujacy + // - gdy zahamowany ma ponizej 2 km/h + // 6. ustaw pojazdom sile hamowania ep + // - proporcjonalnie do masy, do liczby osi, rowne cisnienia - jak + // bedzie, tak bedzie dobrze + float Fpoj = 0; // MoverParameters->CabOccupied < 0 + ////ALGORYTM 2 - KAZDEMU PO ROWNO, ale nie wiecej niz eped * masa + // 1. najpierw daj kazdemu tyle samo + int i = 0; + for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; + p = state.kier == true ? p->Next(Coupling::control) : p->Prev(Coupling::control) ) + { + auto const Nmax = ((p->MoverParameters->P2FTrans * p->MoverParameters->MaxBrakePress[0] - + p->MoverParameters->BrakeCylSpring) * + p->MoverParameters->BrakeCylMult[0] - + p->MoverParameters->BrakeSlckAdj) * + p->MoverParameters->BrakeCylNo * p->MoverParameters->BrakeRigEff; + FmaxEP[i] = Nmax * + p->MoverParameters->Hamulec->GetFC( + Nmax / (p->MoverParameters->NAxles * p->MoverParameters->NBpA), + p->MoverParameters->MED_Vref) * + 1000; // sila hamowania pn + + PrzekrF[i] = false; + FzED[i] = state.FmaxED > 0 ? state.FzadED / state.FmaxED : 0; + p->MoverParameters->AnPos = + MoverParameters->ScndS ? state.LBR : FzED[i]; + FzEP[ i ] = static_cast( state.FzadPN * p->MoverParameters->NAxles ) / static_cast( state.osie ); + ++i; + p->MoverParameters->ShuntMode = MoverParameters->ShuntMode; + p->MoverParameters->ShuntModeAllow = MoverParameters->ShuntModeAllow; + } + while (test) + { + test = false; + i = 0; + float przek = 0; + for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; + p = state.kier == true ? p->Next(Coupling::control) : p->Prev(Coupling::control) ) + { + if (FzEP[i] > 0.01 && + FzEP[i] > p->MoverParameters->TotalMass * p->MoverParameters->inductionMotor.braking.maxEpDeceleration + std::min(p->MoverParameters->inductionMotor.state.maxForce, 0.) * 1000 && + !PrzekrF[i]) + { + float przek1 = -std::min(p->MoverParameters->inductionMotor.state.maxForce, 0.) * 1000 + + FzEP[i] - + p->MoverParameters->TotalMass * + p->MoverParameters->inductionMotor.braking.maxEpDeceleration * 0.999; + PrzekrF[i] = true; + test = true; + state.nPrzekrF++; + przek1 = std::min(przek1, FzEP[i]); + FzEP[i] -= przek1; + if (FzEP[i] < 0) + FzEP[i] = 0; + przek += przek1; + } + ++i; + } + i = 0; + przek = przek / (state.np - state.nPrzekrF); + for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; + true == state.kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) + { + if (!PrzekrF[i]) + { + FzEP[i] += przek; + } + ++i; + } + } + i = 0; + for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; + true == state.kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) + { + float Nmax = ((p->MoverParameters->P2FTrans * p->MoverParameters->MaxBrakePress[0] - + p->MoverParameters->BrakeCylSpring) * + p->MoverParameters->BrakeCylMult[0] - + p->MoverParameters->BrakeSlckAdj) * + p->MoverParameters->BrakeCylNo * p->MoverParameters->BrakeRigEff; + if (state.FrED > 0.1) + p->MoverParameters->MED_EPVC_CurrentTime = 0; + else + p->MoverParameters->MED_EPVC_CurrentTime += dt1; + bool EPVC = p->MoverParameters->MED_EPVC && (p->MoverParameters->MED_EPVC_Time < 0 || p->MoverParameters->MED_EPVC_CurrentTime < p->MoverParameters->MED_EPVC_Time); + float VelC = EPVC ? safe_clamp(p->MoverParameters->Vel, p->MoverParameters->MED_Vmin, p->MoverParameters->MED_Vmax) : p->MoverParameters->MED_Vref;//korekcja EP po prędkości + float FmaxPoj = Nmax * + p->MoverParameters->Hamulec->GetFC( + Nmax / (p->MoverParameters->NAxles * p->MoverParameters->NBpA), VelC) * + 1000; // sila hamowania pn + p->MoverParameters->LocalBrakePosAEIM = FzEP[i] / FmaxPoj; + if (p->MoverParameters->LocalBrakePosAEIM>0.009) + if (p->MoverParameters->P2FTrans * p->MoverParameters->BrakeCylMult[0] * + p->MoverParameters->MaxBrakePress[0] != 0) + { + float x = (p->MoverParameters->BrakeSlckAdj / p->MoverParameters->BrakeCylMult[0] + + p->MoverParameters->BrakeCylSpring) / (p->MoverParameters->P2FTrans * + p->MoverParameters->MaxBrakePress[0]); + p->MoverParameters->LocalBrakePosAEIM = x + (1 - x) * p->MoverParameters->LocalBrakePosAEIM; + } + else + p->MoverParameters->LocalBrakePosAEIM = p->MoverParameters->LocalBrakePosAEIM; + else + p->MoverParameters->LocalBrakePosAEIM = 0; + if (p->MoverParameters->LocHandleTimeTraxx) + { + p->MoverParameters->eim_localbrake = state.eim_lb; + p->MoverParameters->LocalBrakePosAEIM = std::max(p->MoverParameters->LocalBrakePosAEIM, state.eim_lb); + } + ++i; + } +} + +// the state of the blending kept for the debug screen, and written to the log of the braking while it is open +void TDynamicObject::recordMedState( InductionBrakeState const &state, double const dt1 ) +{ + MED[0][0] = state.masa*0.001; + MED[0][1] = state.amax; + MED[0][2] = state.Fzad*0.001; + MED[0][3] = state.FmaxPN*0.001; + MED[0][4] = state.FmaxED*0.001; + MED[0][5] = state.FrED*0.001; + MED[0][6] = state.FzadPN*0.001; + MED[0][7] = state.nPrzekrF; + + if (MEDLogFile.is_open()) + { + MEDLogFile << MEDLogTime << "\t" << MoverParameters->Vel << "\t" << state.masa*0.001 << "\t" << state.osie << "\t" << state.FmaxPN*0.001 << "\t" << state.FmaxED*0.001 << "\t" + << state.FfulED*0.001 << "\t" << state.FrED*0.001 << "\t" << state.Fzad*0.001 << "\t" << state.FzadED*0.001 << "\t" << state.FzadPN*0.001; + for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; + true == state.kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) + { + MEDLogFile << "\t" << p->MoverParameters->BrakePress; + } + MEDLogFile << "\n"; + if (floor(MEDLogTime + dt1) > floor(MEDLogTime)) + { + MEDLogFile.flush(); + } + MEDLogTime += dt1; + + if (MoverParameters->Vel < 0.1 || MoverParameters->MainCtrlPowerPos() > 0) + { + MEDLogInactiveTime += dt1; + } + else + { + MEDLogInactiveTime = 0; + } + if (MEDLogInactiveTime > 5) + { + MEDLogFile.flush(); + MEDLogFile.close(); + } + + } +} + +// the main switch off, with the supply of the vehicle's circuits off, but for diesel engines and hand cars +void TDynamicObject::switchOffMainsWithoutBattery() +{ // fragment "z EXE Kursa" if( MoverParameters->Mains ) { // nie wchodzić w funkcję bez potrzeby if( false == (MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable) @@ -602,7 +757,11 @@ bool TDynamicObject::Update(double dt, double dt1) } } } +} +// the vehicle moved by its physics in the step; the distance it went returned +double TDynamicObject::moveByPhysics( double const dt, double const dt1 ) +{ // przekazanie pozycji do fizyki // NOTE: coordinate system swap // TODO: replace with regular glm vectors @@ -615,7 +774,7 @@ bool TDynamicObject::Update(double dt, double dt1) 0.0, modelRot.z }; // McZapkie-260202 - dMoveLen przyda sie przy stukocie kol - dDOMoveLen = GetdMoveLen() + MoverParameters->ComputeMovement(dt, dt1, ts, tp, tmpTraction, l, r); + double const dDOMoveLen = GetdMoveLen() + MoverParameters->ComputeMovement(dt, dt1, ts, tp, tmpTraction, l, r); if( Mechanik ) { // dodanie aktualnego przemieszczenia Mechanik->MoveDistanceAdd( dDOMoveLen ); @@ -636,14 +795,12 @@ bool TDynamicObject::Update(double dt, double dt1) update_off_track( dt1 ); m_future_movement = (vPosition - old_pos) / dt1 * Timer::GetDeltaRenderTime(); + return dDOMoveLen; +} - if (!bEnabled) // usuwane pojazdy nie mają toru - { // pojazd do usunięcia - bDynamicRemove = true; // sprawdzić - return false; - } - ResetdMoveLen(); - +// the clatter of the wheels over the rail joints, and the jolts they give +void TDynamicObject::updateAxleClatter( double const dDOMoveLen ) +{ // McZapkie-260202 // tupot mew, tfu, stukot kol: if( MyTrack->fSoundDistance != -1 ) { @@ -694,25 +851,7 @@ bool TDynamicObject::Update(double dt, double dt1) .pitch( frequency ) .gain( volume ) .play(); - // crude bump simulation, drop down on even axles, move back up on - // the odd ones - // MoverParameters->AccVert += (MoverParameters->Vel*0.1f) * - // the arguments keep the order they had up to 26.05.1, 0 in place of the value and the figure in place of the - // upper limit, so they work out as the old clamp worked them out up to 26.05.1: the headroom is - // Vmax - (Vel + 0.32 Vmax) whatever its sign, and the bump is capped from above only - double const headroom = safe_clamp( 0.0, MoverParameters->Vmax, MoverParameters->Vmax - ( MoverParameters->Vel + MoverParameters->Vmax * 0.32f ) ); - double const jolt = headroom * .05f * ( MyTrack->iDamageFlag * 0.25f ); - if (MyTrack->eType == tt_Normal) - { - MoverParameters->AccVert += safe_clamp( 0.0, 4.0, jolt ); - } - else if (MyTrack->eType == tt_Switch) - { - double const accHorizontal = safe_clamp( 0.0, 1.0, jolt ) * ((axleindex % 2) != 0 ? 1 : -1); - MoverParameters->AccS += accHorizontal; - MoverParameters->AccN += accHorizontal; - MoverParameters->AccVert += safe_clamp( 0.0, 2.0, jolt ); - } + applyJointJolt( axleindex ); } ++axleindex; } @@ -721,26 +860,35 @@ bool TDynamicObject::Update(double dt, double dt1) } } // McZapkie-260202 end +} - // fragment z EXE Kursa - /* if (MoverParameters->TrainType==train_type::et42) - { - if ((MoverParameters->DynamicBrakeType=dbrake_switch) && - ((MoverParameters->BrakePress > - 0.2) || ( MoverParameters->PipePress < 0.36 ))) - { - MoverParameters->StLinFlag=true; - } - else - if ((MoverParameters->DynamicBrakeType=dbrake_switch) && - (MoverParameters->BrakePress < - 0.1)) - { - MoverParameters->StLinFlag=false; - - } - } */ +// the jolt of an axle over a rail joint: vertical on a plain track, vertical and sideways on a switch +void TDynamicObject::applyJointJolt( int const axleindex ) +{ + // crude bump simulation, drop down on even axles, move back up on + // the odd ones + // MoverParameters->AccVert += (MoverParameters->Vel*0.1f) * + // the arguments keep the order they had up to 26.05.1, 0 in place of the value and the figure in place of the + // upper limit, so they work out as the old clamp worked them out up to 26.05.1: the headroom is + // Vmax - (Vel + 0.32 Vmax) whatever its sign, and the bump is capped from above only + double const headroom = safe_clamp( 0.0, MoverParameters->Vmax, MoverParameters->Vmax - ( MoverParameters->Vel + MoverParameters->Vmax * 0.32f ) ); + double const jolt = headroom * .05f * ( MyTrack->iDamageFlag * 0.25f ); + if (MyTrack->eType == tt_Normal) + { + MoverParameters->AccVert += safe_clamp( 0.0, 4.0, jolt ); + } + else if (MyTrack->eType == tt_Switch) + { + double const accHorizontal = safe_clamp( 0.0, 1.0, jolt ) * ((axleindex % 2) != 0 ? 1 : -1); + MoverParameters->AccS += accHorizontal; + MoverParameters->AccN += accHorizontal; + MoverParameters->AccVert += safe_clamp( 0.0, 2.0, jolt ); + } +} +// the wheels turned by the distance the vehicle went +void TDynamicObject::updateWheelAngles( double const dt1 ) +{ if (MoverParameters->Vel != 0) { // McZapkie-050402: krecenie kolami: glm::dvec3 old_wheels = glm::dvec3(dWheelAngle[0], dWheelAngle[1], dWheelAngle[2]); @@ -758,11 +906,13 @@ bool TDynamicObject::Update(double dt, double dt1) dWheelAngle[1] = clamp_circular( dWheelAngle[1] ); dWheelAngle[2] = clamp_circular( dWheelAngle[2] ); } +} + +// the pantographs, or the valve gear of a steam engine, and the supply of a vehicle that fakes it +void TDynamicObject::updateCurrentCollectors( double const dt1 ) +{ if (pants) // pantograf może być w wagonie kuchennym albo pojeździe rewizyjnym (np. SR61) { // przeliczanie kątów dla pantografów - double k; // tymczasowy kąt - double PantDiff; - TAnimPant *p; // wskaźnik do obiektu danych pantografu // prąd pobierany przez pojazd z sieci: trakcyjny (on the genset of a dual-mode vehicle none) i TotalCurrent // TotalCurrent to bedzie prad nietrakcyjny (niezwiazany z napedem) double fCurrent = MoverParameters->CatenaryCurrent(); @@ -798,209 +948,9 @@ bool TDynamicObject::Update(double dt, double dt1) for (int i = 0; i < iAnimType[ANIM_PANTS]; ++i) { // pętla po wszystkich pantografach - p = pants[i].fParamPants; - if (p->PantWys < 0) - { // patograf został połamany, liczony nie będzie - if (p->fAngleL > p->fAngleL0) - p->fAngleL -= 0.2 * dt1; // nieco szybciej niż jak dla opuszczania - if (p->fAngleL < p->fAngleL0) - p->fAngleL = p->fAngleL0; // kąt graniczny - if (p->fAngleU < M_PI) - p->fAngleU += 0.5 * dt1; // górne się musi ruszać szybciej. - if (p->fAngleU > M_PI) - p->fAngleU = M_PI; - if (i & 1) // zgłoszono, że po połamaniu potrafi zostać zasilanie - MoverParameters->PantRearVolt = 0.0; - else - MoverParameters->PantFrontVolt = 0.0; - continue; // reszta wtedy nie jest wykonywana - } - PantDiff = p->PantTraction - p->PantWys; // docelowy-aktualny - switch (i) // numer pantografu - { // trzeba usunąć to rozróżnienie - case 0: - if (Global.bLiveTraction == false - && p->hvPowerWire == nullptr ) { - // jeśli nie ma drutu, może pooszukiwać - MoverParameters->PantFrontVolt = - p->PantWys >= 1.2 ? - 0.95 * MoverParameters->EnginePowerSource.MaxVoltage : - 0.0; - } - else if( true == MoverParameters->Pantographs[VehicleEnd::front].is_active - && PantDiff < 0.01 ) // tolerancja niedolegania - { - if (p->hvPowerWire) { - auto const lastvoltage { MoverParameters->PantFrontVolt }; - // TODO: wyliczyć trzeba prąd przypadający na pantograf i wstawić do GetVoltage() - if( lastvoltage == 0.0 ) { - // HACK: retrieve the wire voltage for calculations down the road without blowing up the supply - MoverParameters->PantFrontVolt = p->hvPowerWire->VoltageGet( MoverParameters->PantographVoltage, 0.0 ); - } - else { - MoverParameters->PantFrontVolt = p->hvPowerWire->VoltageGet( MoverParameters->PantographVoltage, fPantCurrent ); - if( MoverParameters->PantFrontVolt > 0.0 ) { - fCurrent -= fPantCurrent; // taki prąd płynie przez powyższy pantograf (unless it doesn't) - } - } - // TODO: refactor reaction to voltage change to mover as sound event for specific pantograph - if( lastvoltage == 0.0 - && MoverParameters->PantFrontVolt > 0.0 ) { - for( auto &pantograph : m_pantographsounds ) { - if( pantograph.sPantUp.offset().z > 0 ) { - // limit to pantographs located in the front half of the vehicle - pantograph.sPantUp.play( sound_flags::exclusive ); - } - } - } - } - else - MoverParameters->PantFrontVolt = 0.0; - } - else - MoverParameters->PantFrontVolt = 0.0; - ( fPantCurrent > 0.0 ? MoverParameters->EnergyMeter.first : MoverParameters->EnergyMeter.second ) += MoverParameters->PantRearVolt * fPantCurrent * dt1 / 3600000.0; - break; - case 1: - if( false == Global.bLiveTraction - && nullptr == p->hvPowerWire ) { - // jeśli nie ma drutu, może pooszukiwać - MoverParameters->PantRearVolt = - p->PantWys >= 1.2 ? - 0.95 * MoverParameters->EnginePowerSource.MaxVoltage : - 0.0; - } - else if ( true == MoverParameters->Pantographs[VehicleEnd::rear].is_active - && PantDiff < 0.01 ) - { - if (p->hvPowerWire) { - auto const lastvoltage { MoverParameters->PantRearVolt }; - // TODO: wyliczyć trzeba prąd przypadający na pantograf i wstawić do GetVoltage() - if( lastvoltage == 0.0 ) { - // HACK: retrieve the wire voltage for calculations down the road without blowing up the supply - MoverParameters->PantRearVolt = p->hvPowerWire->VoltageGet( MoverParameters->PantographVoltage, 0.0 ); - } - else { - MoverParameters->PantRearVolt = p->hvPowerWire->VoltageGet( MoverParameters->PantographVoltage, fPantCurrent ); - if( MoverParameters->PantRearVolt > 0.0 ) { - fCurrent -= fPantCurrent; // taki prąd płynie przez powyższy pantograf (unless it doesn't) - } - } - // TODO: refactor reaction to voltage change to mover as sound event for specific pantograph - if( lastvoltage == 0.0 - && MoverParameters->PantRearVolt > 0.0 ) { - for( auto &pantograph : m_pantographsounds ) { - if( pantograph.sPantUp.offset().z < 0 ) { - // limit to pantographs located in the rear half of the vehicle - pantograph.sPantUp.play( sound_flags::exclusive ); - } - } - } - } - else - MoverParameters->PantRearVolt = 0.0; - } - else { -// Global.iPause ^= 2; - MoverParameters->PantRearVolt = 0.0; - } - ( fPantCurrent > 0.0 ? MoverParameters->EnergyMeter.first : MoverParameters->EnergyMeter.second ) += MoverParameters->PantFrontVolt * fPantCurrent * dt1 / 3600000.0; - break; - } // pozostałe na razie nie obsługiwane - if( MoverParameters->PantPress > ( - MoverParameters->TrainType == train_type::emu ? - 2.45 : // Ra 2013-12: Niebugocław mówi, że w EZT podnoszą się przy 2.5 - 3.45 ) ) { - // z EXE Kursa - // Ra: wysokość zależy od ciśnienia !!! - pantspeedfactor = 0.015 * MoverParameters->PantPress * dt1; - } - else { - pantspeedfactor = 0.0; - } - if( false == ( MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable ) ) { - pantspeedfactor = 0.0; - } - pantspeedfactor = std::max( 0.0, pantspeedfactor ); - k = p->fAngleL; - if( pantspeedfactor > 0.0 - && MoverParameters->Pantographs[i].is_active )// jeśli ma być podniesiony - { - if (PantDiff > 0.001) // jeśli nie dolega do drutu - { // jeśli poprzednia wysokość jest mniejsza niż pożądana, zwiększyć kąt dolnego - // ramienia zgodnie z ciśnieniem - if (pantspeedfactor > - 0.55 * PantDiff) // 0.55 to około pochodna kąta po wysokości - k += 0.55 * PantDiff; // ograniczenie "skoku" w danej klatce - else - k += pantspeedfactor; // dolne ramię - // jeśli przekroczono kąt graniczny, zablokować pantograf - // (wymaga interwencji pociągu sieciowego) - } - else if (PantDiff < -0.001) { - // drut się obniżył albo pantograf podniesiony za wysoko - // jeśli wysokość jest zbyt duża, wyznaczyć zmniejszenie kąta - // jeśli zmniejszenie kąta jest zbyt duże, przejść do trybu łamania pantografu - // if (PantFrontDiff<-0.05) //skok w dół o 5cm daje złąmanie pantografu - k += 0.4 * PantDiff; // mniej niż pochodna kąta po wysokości - } // jeśli wysokość jest dobra, nic więcej nie liczyć - } - else - { // jeśli ma być na dole - if (k > p->fAngleL0) // jeśli wyżej niż położenie wyjściowe - k -= 0.15 * dt1; // ruch w dół - if (k < p->fAngleL0) - k = p->fAngleL0; // położenie minimalne - } - if (k != p->fAngleL) - { //żeby nie liczyć w kilku miejscach ani gdy nie potrzeba - if (k + p->fAngleU < M_PI) - { // o ile nie został osiągnięty kąt maksymalny - p->fAngleL = k; // zmieniony kąt - // wyliczyć kąt górnego ramienia z wzoru (a)cosinusowego - //=acos((b*cos()+c)/a) - // p->dPantAngleT=acos((1.22*cos(k)+0.535)/1.755); //górne ramię - p->fAngleU = acos((p->fLenL1 * cos(k) + p->fHoriz) / p->fLenU1); // górne ramię - // wyliczyć aktualną wysokość z wzoru sinusowego - // h=a*sin()+b*sin() - // wysokość całości - p->PantWys = p->fLenL1 * sin(k) + p->fLenU1 * sin(p->fAngleU) + p->fHeight; - } - } + updatePantograph( i, fPantCurrent, fCurrent, dt1 ); } // koniec pętli po pantografach - // TBD, TODO: generate sound event during mover update instead? - if( MoverParameters->Pantographs[VehicleEnd::front].sound_event != MoverParameters->Pantographs[ VehicleEnd::front ].is_active ) { - if( MoverParameters->Pantographs[ VehicleEnd::front ].is_active ) { - // pantograph moving up - // TBD: add a sound? - } - else { - // pantograph dropping - for( auto &pantograph : m_pantographsounds ) { - if( pantograph.sPantDown.offset().z > 0 ) { - // limit to pantographs located in the front half of the vehicle - pantograph.sPantDown.play( sound_flags::exclusive ); - } - } - } - MoverParameters->Pantographs[ VehicleEnd::front ].sound_event = MoverParameters->Pantographs[ VehicleEnd::front ].is_active; - } - if( MoverParameters->Pantographs[ VehicleEnd::rear ].sound_event != MoverParameters->Pantographs[ VehicleEnd::rear ].is_active ) { - if( MoverParameters->Pantographs[ VehicleEnd::rear ].is_active ) { - // pantograph moving up - // TBD: add a sound? - } - else { - // pantograph dropping - for( auto &pantograph : m_pantographsounds ) { - if( pantograph.sPantDown.offset().z < 0 ) { - // limit to pantographs located in the front half of the vehicle - pantograph.sPantDown.play( sound_flags::exclusive ); - } - } - } - MoverParameters->Pantographs[ VehicleEnd::rear ].sound_event = MoverParameters->Pantographs[ VehicleEnd::rear ].is_active; - } + playPantographDropSounds(); } else if (MoverParameters->EnginePowerSource.SourceType == TPowerSource::InternalSource) if (MoverParameters->EnginePowerSource.PowerType == TPowerType::SteamPower) @@ -1090,7 +1040,238 @@ bool TDynamicObject::Update(double dt, double dt1) MoverParameters->PantRearVolt = 0.95 * MoverParameters->EnginePowerSource.MaxVoltage; MoverParameters->PantFrontVolt = 0.95 * MoverParameters->EnginePowerSource.MaxVoltage; } +} +// one pantograph: broken, it only folds down; otherwise the voltage at it, and its arms moved +void TDynamicObject::updatePantograph( int const i, double const fPantCurrent, double &fCurrent, double const dt1 ) +{ + double PantDiff; + TAnimPant *p; // wskaźnik do obiektu danych pantografu + p = pants[i].fParamPants; + if (p->PantWys < 0) + { // patograf został połamany, liczony nie będzie + if (p->fAngleL > p->fAngleL0) + p->fAngleL -= 0.2 * dt1; // nieco szybciej niż jak dla opuszczania + if (p->fAngleL < p->fAngleL0) + p->fAngleL = p->fAngleL0; // kąt graniczny + if (p->fAngleU < M_PI) + p->fAngleU += 0.5 * dt1; // górne się musi ruszać szybciej. + if (p->fAngleU > M_PI) + p->fAngleU = M_PI; + if (i & 1) // zgłoszono, że po połamaniu potrafi zostać zasilanie + MoverParameters->PantRearVolt = 0.0; + else + MoverParameters->PantFrontVolt = 0.0; + return; // reszta wtedy nie jest wykonywana + } + PantDiff = p->PantTraction - p->PantWys; // docelowy-aktualny + updatePantographVoltage( i, p, PantDiff, fPantCurrent, fCurrent, dt1 ); + updatePantographMotion( i, p, PantDiff, dt1 ); +} + +// the voltage at one pantograph, from the wire it touches, and the energy drawn through it metered +void TDynamicObject::updatePantographVoltage( int const i, TAnimPant const *p, double const PantDiff, double const fPantCurrent, double &fCurrent, double const dt1 ) +{ + switch (i) // numer pantografu + { // trzeba usunąć to rozróżnienie + case 0: + if (Global.bLiveTraction == false + && p->hvPowerWire == nullptr ) { + // jeśli nie ma drutu, może pooszukiwać + MoverParameters->PantFrontVolt = + p->PantWys >= 1.2 ? + 0.95 * MoverParameters->EnginePowerSource.MaxVoltage : + 0.0; + } + else if( true == MoverParameters->Pantographs[VehicleEnd::front].is_active + && PantDiff < 0.01 ) // tolerancja niedolegania + { + if (p->hvPowerWire) { + auto const lastvoltage { MoverParameters->PantFrontVolt }; + // TODO: wyliczyć trzeba prąd przypadający na pantograf i wstawić do GetVoltage() + if( lastvoltage == 0.0 ) { + // HACK: retrieve the wire voltage for calculations down the road without blowing up the supply + MoverParameters->PantFrontVolt = p->hvPowerWire->VoltageGet( MoverParameters->PantographVoltage, 0.0 ); + } + else { + MoverParameters->PantFrontVolt = p->hvPowerWire->VoltageGet( MoverParameters->PantographVoltage, fPantCurrent ); + if( MoverParameters->PantFrontVolt > 0.0 ) { + fCurrent -= fPantCurrent; // taki prąd płynie przez powyższy pantograf (unless it doesn't) + } + } + // TODO: refactor reaction to voltage change to mover as sound event for specific pantograph + if( lastvoltage == 0.0 + && MoverParameters->PantFrontVolt > 0.0 ) { + for( auto &pantograph : m_pantographsounds ) { + if( pantograph.sPantUp.offset().z > 0 ) { + // limit to pantographs located in the front half of the vehicle + pantograph.sPantUp.play( sound_flags::exclusive ); + } + } + } + } + else + MoverParameters->PantFrontVolt = 0.0; + } + else + MoverParameters->PantFrontVolt = 0.0; + ( fPantCurrent > 0.0 ? MoverParameters->EnergyMeter.first : MoverParameters->EnergyMeter.second ) += MoverParameters->PantRearVolt * fPantCurrent * dt1 / 3600000.0; + break; + case 1: + if( false == Global.bLiveTraction + && nullptr == p->hvPowerWire ) { + // jeśli nie ma drutu, może pooszukiwać + MoverParameters->PantRearVolt = + p->PantWys >= 1.2 ? + 0.95 * MoverParameters->EnginePowerSource.MaxVoltage : + 0.0; + } + else if ( true == MoverParameters->Pantographs[VehicleEnd::rear].is_active + && PantDiff < 0.01 ) + { + if (p->hvPowerWire) { + auto const lastvoltage { MoverParameters->PantRearVolt }; + // TODO: wyliczyć trzeba prąd przypadający na pantograf i wstawić do GetVoltage() + if( lastvoltage == 0.0 ) { + // HACK: retrieve the wire voltage for calculations down the road without blowing up the supply + MoverParameters->PantRearVolt = p->hvPowerWire->VoltageGet( MoverParameters->PantographVoltage, 0.0 ); + } + else { + MoverParameters->PantRearVolt = p->hvPowerWire->VoltageGet( MoverParameters->PantographVoltage, fPantCurrent ); + if( MoverParameters->PantRearVolt > 0.0 ) { + fCurrent -= fPantCurrent; // taki prąd płynie przez powyższy pantograf (unless it doesn't) + } + } + // TODO: refactor reaction to voltage change to mover as sound event for specific pantograph + if( lastvoltage == 0.0 + && MoverParameters->PantRearVolt > 0.0 ) { + for( auto &pantograph : m_pantographsounds ) { + if( pantograph.sPantUp.offset().z < 0 ) { + // limit to pantographs located in the rear half of the vehicle + pantograph.sPantUp.play( sound_flags::exclusive ); + } + } + } + } + else + MoverParameters->PantRearVolt = 0.0; + } + else { +// Global.iPause ^= 2; + MoverParameters->PantRearVolt = 0.0; + } + ( fPantCurrent > 0.0 ? MoverParameters->EnergyMeter.first : MoverParameters->EnergyMeter.second ) += MoverParameters->PantFrontVolt * fPantCurrent * dt1 / 3600000.0; + break; + } // pozostałe na razie nie obsługiwane +} + +// the arms of one pantograph raised by the pressure towards the wire, or lowered +void TDynamicObject::updatePantographMotion( int const i, TAnimPant *p, double const PantDiff, double const dt1 ) +{ + double k; // tymczasowy kąt + if( MoverParameters->PantPress > ( + MoverParameters->TrainType == train_type::emu ? + 2.45 : // Ra 2013-12: Niebugocław mówi, że w EZT podnoszą się przy 2.5 + 3.45 ) ) { + // z EXE Kursa + // Ra: wysokość zależy od ciśnienia !!! + pantspeedfactor = 0.015 * MoverParameters->PantPress * dt1; + } + else { + pantspeedfactor = 0.0; + } + if( false == ( MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable ) ) { + pantspeedfactor = 0.0; + } + pantspeedfactor = std::max( 0.0, pantspeedfactor ); + k = p->fAngleL; + if( pantspeedfactor > 0.0 + && MoverParameters->Pantographs[i].is_active )// jeśli ma być podniesiony + { + if (PantDiff > 0.001) // jeśli nie dolega do drutu + { // jeśli poprzednia wysokość jest mniejsza niż pożądana, zwiększyć kąt dolnego + // ramienia zgodnie z ciśnieniem + if (pantspeedfactor > + 0.55 * PantDiff) // 0.55 to około pochodna kąta po wysokości + k += 0.55 * PantDiff; // ograniczenie "skoku" w danej klatce + else + k += pantspeedfactor; // dolne ramię + // jeśli przekroczono kąt graniczny, zablokować pantograf + // (wymaga interwencji pociągu sieciowego) + } + else if (PantDiff < -0.001) { + // drut się obniżył albo pantograf podniesiony za wysoko + // jeśli wysokość jest zbyt duża, wyznaczyć zmniejszenie kąta + // jeśli zmniejszenie kąta jest zbyt duże, przejść do trybu łamania pantografu + // if (PantFrontDiff<-0.05) //skok w dół o 5cm daje złąmanie pantografu + k += 0.4 * PantDiff; // mniej niż pochodna kąta po wysokości + } // jeśli wysokość jest dobra, nic więcej nie liczyć + } + else + { // jeśli ma być na dole + if (k > p->fAngleL0) // jeśli wyżej niż położenie wyjściowe + k -= 0.15 * dt1; // ruch w dół + if (k < p->fAngleL0) + k = p->fAngleL0; // położenie minimalne + } + if (k != p->fAngleL) + { //żeby nie liczyć w kilku miejscach ani gdy nie potrzeba + if (k + p->fAngleU < M_PI) + { // o ile nie został osiągnięty kąt maksymalny + p->fAngleL = k; // zmieniony kąt + // wyliczyć kąt górnego ramienia z wzoru (a)cosinusowego + //=acos((b*cos()+c)/a) + // p->dPantAngleT=acos((1.22*cos(k)+0.535)/1.755); //górne ramię + p->fAngleU = acos((p->fLenL1 * cos(k) + p->fHoriz) / p->fLenU1); // górne ramię + // wyliczyć aktualną wysokość z wzoru sinusowego + // h=a*sin()+b*sin() + // wysokość całości + p->PantWys = p->fLenL1 * sin(k) + p->fLenU1 * sin(p->fAngleU) + p->fHeight; + } + } +} + +// the sound of the pantographs dropping, at the end whose pantograph went down +void TDynamicObject::playPantographDropSounds() +{ + // TBD, TODO: generate sound event during mover update instead? + if( MoverParameters->Pantographs[VehicleEnd::front].sound_event != MoverParameters->Pantographs[ VehicleEnd::front ].is_active ) { + if( MoverParameters->Pantographs[ VehicleEnd::front ].is_active ) { + // pantograph moving up + // TBD: add a sound? + } + else { + // pantograph dropping + for( auto &pantograph : m_pantographsounds ) { + if( pantograph.sPantDown.offset().z > 0 ) { + // limit to pantographs located in the front half of the vehicle + pantograph.sPantDown.play( sound_flags::exclusive ); + } + } + } + MoverParameters->Pantographs[ VehicleEnd::front ].sound_event = MoverParameters->Pantographs[ VehicleEnd::front ].is_active; + } + if( MoverParameters->Pantographs[ VehicleEnd::rear ].sound_event != MoverParameters->Pantographs[ VehicleEnd::rear ].is_active ) { + if( MoverParameters->Pantographs[ VehicleEnd::rear ].is_active ) { + // pantograph moving up + // TBD: add a sound? + } + else { + // pantograph dropping + for( auto &pantograph : m_pantographsounds ) { + if( pantograph.sPantDown.offset().z < 0 ) { + // limit to pantographs located in the front half of the vehicle + pantograph.sPantDown.play( sound_flags::exclusive ); + } + } + } + MoverParameters->Pantographs[ VehicleEnd::rear ].sound_event = MoverParameters->Pantographs[ VehicleEnd::rear ].is_active; + } +} + +// the wipers moved, each on its own timing, out and back to the park position +void TDynamicObject::updateWipers( double const dt1 ) +{ // wipers if (dWiperPos.size() > 0) // tylko dla wozow ze zdefiniowanymi wycierakami { @@ -1166,9 +1347,11 @@ bool TDynamicObject::Update(double dt, double dt1) } } } +} - - +// the mirrors folded above their speed or when they may not be out, otherwise unfolded on the side of open doors +void TDynamicObject::updateMirrors( double const dt1 ) +{ // mirrors auto const mirrorleft { dMirrorMoveL }; auto const mirrorright { dMirrorMoveR }; @@ -1204,27 +1387,6 @@ bool TDynamicObject::Update(double dt, double dt1) } play_mirror_sounds( VehicleSide::left, m_mirrormotion[ VehicleSide::left ].update( dMirrorMoveL - mirrorleft ) ); play_mirror_sounds( VehicleSide::right, m_mirrormotion[ VehicleSide::right ].update( dMirrorMoveR - mirrorright ) ); - - // compartment lights - // if the vehicle has a controller, we base the light state on state of the controller otherwise we check the vehicle itself - if( ctOwner != nullptr ? SectionLightsActive != MoverParameters->CompartmentLights.is_active : - Mechanik != nullptr ? SectionLightsActive != MoverParameters->CompartmentLights.is_active : - SectionLightsActive ) { // without controller switch the lights off - toggle_lights(); - } - - if (MoverParameters->InactiveCabPantsCheck) - { - pants_up(); - MoverParameters->InactiveCabPantsCheck = false; - } - - if( MoverParameters->LoadStatus ) { - LoadUpdate(); // zmiana modelu ładunku - } - update_exchange( dt ); - - return true; // Ra: chyba tak? } void TDynamicObject::pants_up() From 9568dba9e4541e9627b98a047f62fc42b209b504 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sat, 28 Nov 2026 22:13:19 +0100 Subject: [PATCH 026/123] fix(vehicle): the bugs the split of the giant functions brought to light What changes for the player: - the OFF position of the headlights dimmer puts out the headlights at the end of the active cab: A from cab 1, B from cab -1. It took the numbers of the ends for the numbers of the cabs, so cab 1 put out B, the end behind the driver, and cab -1 nothing (eff9fe88) - each pantograph meters the energy it draws at its own voltage; it took the voltage of the other one, so a vehicle of one pantograph metered none - with the live traction, a pantograph counts as touching the wire by the switch of its own end (the current shared between the pantographs); every one was counted by the switch of the front one - radiatorfan2: in the sounds of the .mmd is read as radiatorfan1: is; only radiatorfan2 without the colon was. No vehicle of the game data uses either form of it, so no vehicle sounds different, and the old form is still read Faults that couldn't show in a usual consist, fixed: - the pantographs of more than 8 units in multiple went past the end of the table of the cab (TTrain::bPants), the compressors next to them had the check already - the overload relay of the converter dereferenced the driver of the vehicle without checking there is one - an empty row of the table of the consist kept the spring brake pressure of the vehicle there before - more than 8 wipers went past the end of the state of the wipers And a tidy-up of no effect: a motor blower sound looks at the speed of its own blower, not of the front one (both are the speed of the .fiz). CabEnd() and PantographEnd() (physics/vehicletypes.h) give the end of a cab and of a pantograph of the model; test_vehicle_ends.cpp tests them and the rest of the vocabulary of the ends. Left as they are, for someone who knows what they should do: FfulED of the braking of a consist of induction motors (TDynamicObject::Update) is assigned rather than summed and is never above 0, so with ScndS above fullSpeed the force asked of the ED brake is 0; and the calibration check of the brake handle of the PoKeys desk (TTrain::updateBrakeControllers) is never tested, by the precedence of ?: and &&. 1149/1149 tests; golden traces exact against staging 62f7a29b. --- physics/vehicletypes.h | 23 ++++++++++++ tests/unit/test_vehicle_ends.cpp | 63 ++++++++++++++++++++++++++++++++ vehicle/cab/update.cpp | 5 ++- vehicle/dynamic/lights.cpp | 25 +++---------- vehicle/dynamic/mmd.cpp | 10 ++++- vehicle/dynamic/sounds.cpp | 2 +- vehicle/dynamic/update.cpp | 6 +-- 7 files changed, 107 insertions(+), 27 deletions(-) create mode 100644 tests/unit/test_vehicle_ends.cpp diff --git a/physics/vehicletypes.h b/physics/vehicletypes.h index 8d0a6bf61..7c1c01572 100644 --- a/physics/vehicletypes.h +++ b/physics/vehicletypes.h @@ -15,6 +15,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include "utilities/enumset.h" @@ -186,6 +187,28 @@ constexpr VehicleSide SideOf(int const number) return static_cast(number); } +/// The end of the vehicle the cab of the given number is at (CabActive, CabOccupied): cab 1 at the front, +/// cab -1 at the rear; none for 0, no cab. +constexpr std::optional CabEnd(int const cab) +{ + if (cab > 0) + { + return VehicleEnd::front; + } + if (cab < 0) + { + return VehicleEnd::rear; + } + return std::nullopt; +} + +/// The end a pantograph of the model counts for, by its number among the pantograph animations: the even +/// ones the front (Pantographs[front], PantFrontVolt), the odd ones the rear. +constexpr VehicleEnd PantographEnd(int const index) +{ + return (index & 1) != 0 ? VehicleEnd::rear : VehicleEnd::front; +} + /// Two values, one for each end or side of a vehicle, indexed by the enum; by a number too, where a loop /// counts them. template diff --git a/tests/unit/test_vehicle_ends.cpp b/tests/unit/test_vehicle_ends.cpp new file mode 100644 index 000000000..b385b12ec --- /dev/null +++ b/tests/unit/test_vehicle_ends.cpp @@ -0,0 +1,63 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "physics/vehicletypes.h" + +// the ends and the sides of a vehicle: the numbers the formats give them, the other one, the arrays indexed by them, +// the end of a cab and of a pantograph of the model + +TEST_CASE("vehicle ends and sides keep the numbers of the formats") { + CHECK(NumberOf(VehicleEnd::front) == 0); + CHECK(NumberOf(VehicleEnd::rear) == 1); + CHECK(NumberOf(VehicleSide::right) == 0); + CHECK(NumberOf(VehicleSide::left) == 1); + // a number goes through as it is, also the -1 and the 2 some fields hold for "none" + for (auto const number : {-1, 0, 1, 2}) { + CAPTURE(number); + CHECK(NumberOf(EndOf(number)) == number); + CHECK(NumberOf(SideOf(number)) == number); + } +} + +TEST_CASE("vehicle ends and sides: the other one") { + CHECK(Opposite(VehicleEnd::front) == VehicleEnd::rear); + CHECK(Opposite(VehicleEnd::rear) == VehicleEnd::front); + CHECK(Opposite(VehicleSide::right) == VehicleSide::left); + CHECK(Opposite(VehicleSide::left) == VehicleSide::right); + CHECK(VehicleEnds[0] == VehicleEnd::front); + CHECK(VehicleEnds[1] == VehicleEnd::rear); + CHECK(VehicleSides[0] == VehicleSide::right); + CHECK(VehicleSides[1] == VehicleSide::left); +} + +TEST_CASE("an array of the ends is indexed by the end and by its number alike") { + ByEnd values{10, 20}; + CHECK(values[VehicleEnd::front] == 10); + CHECK(values[VehicleEnd::rear] == 20); + CHECK(values[0] == 10); + CHECK(values[1] == 20); + values[VehicleEnd::rear] = 30; + CHECK(values[1] == 30); + BySide doors{}; + doors[VehicleSide::left] = true; + CHECK_FALSE(doors[VehicleSide::right]); + CHECK(doors[1]); +} + +TEST_CASE("the cab of a vehicle is at its front for cab 1, at its rear for cab -1") { + // the OFF position of the headlights dimmer puts out the headlights at the end of the active cab (A at the front, + // B at the rear); with the numbers of the ends taken for the numbers of the cabs, cab 1 put out B and cab -1 nothing + CHECK(CabEnd(1) == VehicleEnd::front); + CHECK(CabEnd(-1) == VehicleEnd::rear); + CHECK_FALSE(CabEnd(0).has_value()); +} + +TEST_CASE("the pantographs of a model count for the front and the rear in turn") { + // each pantograph has the voltage, the switch and the energy of its own end: the first one the front's, the second + // one the rear's. the energy meter took the voltage of the other one, the count of the pantographs touching the + // wire the switch of the front for both + CHECK(PantographEnd(0) == VehicleEnd::front); + CHECK(PantographEnd(1) == VehicleEnd::rear); + CHECK(PantographEnd(2) == VehicleEnd::front); + CHECK(PantographEnd(3) == VehicleEnd::rear); +} diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index 987591455..538fc968b 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -450,7 +450,7 @@ void TTrain::updateUnitStates() iUnits[i] = iUnitNo; cCode[i] = p->MoverParameters->TypeName[p->MoverParameters->TypeName.length() - 1]; asCarName[i] = p->name(); - if (p->MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) + if (p->MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector && iUnitNo <= 8) { bPants[iUnitNo - 1][VehicleEnd::front] = bPants[iUnitNo - 1][VehicleEnd::front] || p->MoverParameters->Pantographs[VehicleEnd::front].is_active; bPants[iUnitNo - 1][VehicleEnd::rear] = bPants[iUnitNo - 1][VehicleEnd::rear] || p->MoverParameters->Pantographs[VehicleEnd::rear].is_active; @@ -527,6 +527,7 @@ void TTrain::updateUnitStates() fPress[i][3] = 0; fPress[i][4] = 0; fPress[i][5] = 0; + fPress[i][6] = 0; bDoors[i][0] = false; bDoors[i][1] = false; bDoors[i][2] = false; @@ -608,7 +609,7 @@ void TTrain::updateConverterOverload(double const Deltatime) fConverterTimer += static_cast(Deltatime); if (mvControlled->CompressorFlag == true && mvControlled->CompressorPower == 1 && (mvControlled->EngineType == TEngineType::ElectricSeriesMotor || mvControlled->TrainType == train_type::emu) && DynamicObject->Controller == Humandriver // hunter-110212: poprawka dla EZT - && false == DynamicObject->Mechanik->AIControllFlag) + && DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag) { // hunter-091012: poprawka (zmiana warunku z CompressorPower /rozne od 0/ na /rowne 1/) if (fConverterTimer < fConverterPrzekaznik) { diff --git a/vehicle/dynamic/lights.cpp b/vehicle/dynamic/lights.cpp index 9fcd1bc02..0da7ae5b7 100644 --- a/vehicle/dynamic/lights.cpp +++ b/vehicle/dynamic/lights.cpp @@ -131,30 +131,15 @@ void TDynamicObject::RaLightsSet(int head, int rear) //MoverParameters->iLights[vehicleend] &= 0 | light::rearendsignals; // zostawiamy tylko tabliczki jesli sa HighBeamLights = false; DimHeadlights = false; - switch (MoverParameters->CabActive) - { - case NumberOf(VehicleEnd::front): - HeadlightsAoff = true; - break; - case NumberOf(VehicleEnd::rear): - HeadlightsBoff = true; - break; - default: - break; + // the headlights at the end of the active cab: A at the front, B at the rear + if( auto const cabend { CabEnd( MoverParameters->CabActive ) }; cabend.has_value() ) { + ( *cabend == VehicleEnd::front ? HeadlightsAoff : HeadlightsBoff ) = true; } } else { - switch (MoverParameters->CabActive) - { - case NumberOf(VehicleEnd::front): - HeadlightsAoff = false; - break; - case NumberOf(VehicleEnd::rear): - HeadlightsBoff = false; - break; - default: - break; + if( auto const cabend { CabEnd( MoverParameters->CabActive ) }; cabend.has_value() ) { + ( *cabend == VehicleEnd::front ? HeadlightsAoff : HeadlightsBoff ) = false; } } diff --git a/vehicle/dynamic/mmd.cpp b/vehicle/dynamic/mmd.cpp index ac779d972..b851379cd 100644 --- a/vehicle/dynamic/mmd.cpp +++ b/vehicle/dynamic/mmd.cpp @@ -909,6 +909,14 @@ void TDynamicObject::loadModelsMirrorWiperKeyword( cParser &parser, std::string for (int i = 0; i < iAnimType[ANIM_WIPERS]; i++) // zebranie wszystkich submodeli wycieraczek { dWiperPos.emplace_back(0.0); // dodajemy na koniec zeby sie miejsce tam zrobilo i nie bylo invalid addressow potem + if (wiperOutTimer.size() < dWiperPos.size()) + { + // more wipers than the state of the wipers has room for at the start + wiperOutTimer.resize(dWiperPos.size(), 0.0); + wiperParkTimer.resize(dWiperPos.size(), 0.0); + workingSwitchPos.resize(dWiperPos.size(), 0); + wiperDirection.resize(dWiperPos.size(), false); + } asAnimName = token + std::to_string(i + 1); // element wycieraczki nr 1 @@ -1149,7 +1157,7 @@ bool TDynamicObject::loadSoundsMotorKeyword( cParser &parser, std::string_view t m_powertrainsounds.radiator_fan.owner( this ); } - else if( token == "radiatorfan2" ) { + else if( token == "radiatorfan2:" || token == "radiatorfan2" ) { // auxiliary circuit radiator fan m_powertrainsounds.radiator_fan_aux.deserialize( parser, sound_type::single ); m_powertrainsounds.radiator_fan_aux.owner( this ); diff --git a/vehicle/dynamic/sounds.cpp b/vehicle/dynamic/sounds.cpp index 6a5821bb9..62684280f 100644 --- a/vehicle/dynamic/sounds.cpp +++ b/vehicle/dynamic/sounds.cpp @@ -1471,7 +1471,7 @@ TDynamicObject::powertrain_sounds::renderMotorBlowerSounds( TMoverParameters con // TODO: for the sounds with provided bookends invoke stop() when the stop is triggered and revolutions start dropping, instead of after full stop if( blower.revolutions > 1 ) { // NOTE: for motorblowers with fixed speed if the sound has defined bookends we skip revolutions-based part of frequency/volume adjustments - auto const revolutionmodifier { Vehicle.MotorBlowers[VehicleEnd::front].speed < 0.f && blowersound.has_bookends() ? 1.f : blower.revolutions }; + auto const revolutionmodifier { blower.speed < 0.f && blowersound.has_bookends() ? 1.f : blower.revolutions }; blowersound .pitch( true == blowersound.is_combined() ? diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index c934f2724..ec942b9a7 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -938,7 +938,7 @@ void TDynamicObject::updateCurrentCollectors( double const dt1 ) } else { if( pantograph->hvPowerWire != nullptr - && true == MoverParameters->Pantographs[VehicleEnd::front].is_active + && true == MoverParameters->Pantographs[PantographEnd( idx )].is_active && pantograph->PantTraction - pantograph->PantWys < 0.01 ) { // tolerancja niedolegania ++activepantographs; } @@ -1115,7 +1115,7 @@ void TDynamicObject::updatePantographVoltage( int const i, TAnimPant const *p, d } else MoverParameters->PantFrontVolt = 0.0; - ( fPantCurrent > 0.0 ? MoverParameters->EnergyMeter.first : MoverParameters->EnergyMeter.second ) += MoverParameters->PantRearVolt * fPantCurrent * dt1 / 3600000.0; + ( fPantCurrent > 0.0 ? MoverParameters->EnergyMeter.first : MoverParameters->EnergyMeter.second ) += MoverParameters->PantFrontVolt * fPantCurrent * dt1 / 3600000.0; break; case 1: if( false == Global.bLiveTraction @@ -1160,7 +1160,7 @@ void TDynamicObject::updatePantographVoltage( int const i, TAnimPant const *p, d // Global.iPause ^= 2; MoverParameters->PantRearVolt = 0.0; } - ( fPantCurrent > 0.0 ? MoverParameters->EnergyMeter.first : MoverParameters->EnergyMeter.second ) += MoverParameters->PantFrontVolt * fPantCurrent * dt1 / 3600000.0; + ( fPantCurrent > 0.0 ? MoverParameters->EnergyMeter.first : MoverParameters->EnergyMeter.second ) += MoverParameters->PantRearVolt * fPantCurrent * dt1 / 3600000.0; break; } // pozostałe na razie nie obsługiwane } From d0387753f87e12273e80ef79f0df80ce3e19364b Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sat, 28 Nov 2026 23:56:46 +0100 Subject: [PATCH 027/123] refactor(physics): TMoverParameters becomes physics::Vehicle, the mover is gone The physics of a vehicle loses the name it had from the Pascal of 2001. Done by tools/rename/mover_to_physics.py, committed with it: physics/mover.h physics/vehicle.h TMoverParameters physics::Vehicle (in namespace physics) TDynamicObject::MoverParameters physics mvOccupied, mvControlled occupied, controlled (TTrain, TController) mvSecond, mvThird secondUnit, thirdUnit mvPantographUnit pantographUnit mover, Mover, movers physics, Physics, vehicles (locals, params) m_mover, othermover, currentMover, from_movers, renderMoverEventSounds m_physics, otherPhysics, currentPhysics, from_vehicles, renderPhysicsEventSounds The code and the comments are renamed, the string literals are not: no text the game shows, logs or looks up has changed (none had the names). The movers of the editor, the tracks a slide moves, keep their name. By hand: two member functions of TDynamicObject (gather_off_track_terrain, begin_off_track) had a local mover aliasing their own MoverParameters, which the rename made physics { *physics }; the alias is gone, they use physics->. No other function has a renamed local meeting a renamed member (checked over all the functions of the code before the rename). For the branches made before it: run the script on the branch (python tools/rename/mover_to_physics.py, from the root of the repository) before merging it with this one, and the names don't conflict. It can be run again; the second time it changes nothing. The class is the same as it was; breaking it into its parts (braking, electrics, controls, load) and making its data private are the next stages. No change in behaviour: 1149/1149 tests, golden traces exact against staging 62f7a29b. --- AGENTS.md | 6 +- application/application.cpp | 2 +- application/consistviews.cpp | 28 +- application/driverhints.cpp | 296 ++++---- application/drivermode.cpp | 38 +- application/driveruipanels.cpp | 374 +++++----- application/driveruipanels.h | 2 +- application/editormode.cpp | 4 +- application/editormodejoints.cpp | 22 +- application/editormodeselftestscene.cpp | 4 +- audio/sound.cpp | 4 +- directoryDescription.md | 2 +- input/drivermouseinput.cpp | 4 +- input/messaging.cpp | 70 +- physics/brakes.cpp | 2 +- physics/brakes.h | 2 +- physics/collision.h | 2 +- physics/components/body.cpp | 64 +- physics/components/cab.cpp | 22 +- physics/components/collisions.cpp | 56 +- physics/components/commands.cpp | 38 +- physics/components/controllers.cpp | 108 +-- physics/components/couplers.cpp | 44 +- physics/components/diesel.cpp | 104 +-- physics/components/doors.cpp | 44 +- physics/components/drive.cpp | 142 ++-- physics/components/drive.h | 36 +- physics/components/electrics.cpp | 94 +-- physics/components/fizparser.cpp | 62 +- physics/components/fizsections.cpp | 96 +-- physics/components/internal.h | 2 +- physics/components/pneumatics.cpp | 162 ++--- physics/components/securitysystem.cpp | 8 +- physics/components/setup.cpp | 20 +- physics/components/traction.cpp | 126 ++-- physics/couplerphysics.h | 2 +- physics/derailment.h | 4 +- physics/{mover.h => vehicle.h} | 47 +- rendering/common/locallights.cpp | 4 +- rendering/common/localshadows.cpp | 4 +- rendering/common/scenewalk.cpp | 6 +- rendering/common/screenreflections.cpp | 4 +- rendering/common/windscreenwater.cpp | 6 +- rendering/lightarray.cpp | 30 +- rendering/opengl46/opengl46renderer.cpp | 10 +- rendering/particles.cpp | 18 +- rendering/vulkan14/vulkan14frame.cpp | 10 +- scene/scene.cpp | 8 +- scripting/lua.cpp | 4 +- simulation/blackboxrecorder.cpp | 48 +- simulation/simulation.cpp | 24 +- simulation/simulationstateserializer.cpp | 8 +- tests/unit/COVERAGE.md | 12 +- tests/unit/README.md | 2 +- tests/unit/consist.cpp | 40 +- tests/unit/consist.h | 2 +- tests/unit/drive.cpp | 44 +- tests/unit/drive.h | 12 +- tests/unit/figures.cpp | 2 +- tests/unit/figures.h | 4 +- tests/unit/fiz.h | 2 +- tests/unit/golden.cpp | 2 +- tests/unit/golden.h | 6 +- tests/unit/invariants.cpp | 4 +- tests/unit/invariants.h | 6 +- tests/unit/scenario.cpp | 2 +- tests/unit/scenario.h | 4 +- tests/unit/test_brake_pipe.cpp | 8 +- tests/unit/test_brake_setting.cpp | 72 +- tests/unit/test_brakes.cpp | 4 +- tests/unit/test_cab.cpp | 14 +- tests/unit/test_camshaft.cpp | 48 +- tests/unit/test_cntrl.cpp | 10 +- tests/unit/test_collisions.cpp | 100 +-- tests/unit/test_commands.cpp | 28 +- tests/unit/test_consist.cpp | 2 +- tests/unit/test_controls.cpp | 6 +- tests/unit/test_coupler_physics.cpp | 6 +- tests/unit/test_couplers.cpp | 94 +-- tests/unit/test_couplers_trains.cpp | 18 +- tests/unit/test_crew.cpp | 14 +- tests/unit/test_definition.cpp | 2 +- tests/unit/test_derail_motion.cpp | 10 +- tests/unit/test_derailment_vehicle.cpp | 4 +- tests/unit/test_door_wings.cpp | 4 +- tests/unit/test_drivingaid.cpp | 14 +- tests/unit/test_dynamic_brake_diesel.cpp | 12 +- tests/unit/test_elf_controller.cpp | 94 +-- tests/unit/test_engine_start.cpp | 52 +- tests/unit/test_est3al2_relay.cpp | 2 +- tests/unit/test_fcfuh_default.cpp | 2 +- tests/unit/test_feed_pipe.cpp | 36 +- tests/unit/test_figures.cpp | 26 +- tests/unit/test_fiz.cpp | 2 +- tests/unit/test_gauge_scale.cpp | 6 +- tests/unit/test_genset.cpp | 76 +-- tests/unit/test_handover.cpp | 40 +- tests/unit/test_horn.cpp | 4 +- tests/unit/test_invariants.cpp | 8 +- tests/unit/test_lights_preset_cablight.cpp | 2 +- tests/unit/test_line_contactors_interlock.cpp | 54 +- tests/unit/test_linebreaker.cpp | 14 +- tests/unit/test_motor_param_bounds.cpp | 2 +- tests/unit/test_parser.cpp | 2 +- tests/unit/test_pullee.cpp | 24 +- tests/unit/test_queries.cpp | 2 +- tests/unit/test_smoke.cpp | 32 +- tests/unit/test_speed_control.cpp | 4 +- tests/unit/test_timetable.cpp | 18 +- tests/unit/test_traction.cpp | 2 +- tests/unit/test_wheelslip.cpp | 2 +- tests/unit/vehicle.cpp | 126 ++-- tests/unit/vehicle.h | 10 +- tools/rename/mover_to_physics.py | 190 ++++++ utilities/Classes.h | 2 +- utilities/Globals.h | 4 +- utilities/Timer.h | 8 +- utilities/motiontelemetry.cpp | 2 +- utilities/translation.cpp | 2 +- utilities/uart.cpp | 2 +- vehicle/Camera.cpp | 2 +- vehicle/Driver.h | 14 +- vehicle/DynObj.h | 34 +- vehicle/Train.h | 22 +- vehicle/ai/consist.cpp | 212 +++--- vehicle/ai/controls.cpp | 382 +++++------ vehicle/ai/doors.cpp | 44 +- vehicle/ai/driver.cpp | 66 +- vehicle/ai/engine.cpp | 84 +-- vehicle/ai/force.cpp | 136 ++-- vehicle/ai/internal.h | 4 +- vehicle/ai/obstacles.cpp | 24 +- vehicle/ai/orders.cpp | 96 +-- vehicle/ai/physicslog.cpp | 38 +- vehicle/ai/routescan.cpp | 14 +- vehicle/ai/situation.cpp | 130 ++-- vehicle/ai/speed.cpp | 62 +- vehicle/ai/speedpos.cpp | 2 +- vehicle/ai/speedtable.cpp | 44 +- vehicle/brakesetting.cpp | 8 +- vehicle/brakesetting.h | 8 +- vehicle/cab/auxiliarycommands.cpp | 242 +++---- vehicle/cab/brakecommands.cpp | 198 +++--- vehicle/cab/cab.cpp | 2 +- vehicle/cab/cabcommands.cpp | 152 ++--- vehicle/cab/commandtable.cpp | 2 +- vehicle/cab/controllercommands.cpp | 134 ++-- vehicle/cab/couplingcommands.cpp | 8 +- vehicle/cab/doorcommands.cpp | 110 +-- vehicle/cab/equipmentcommands.cpp | 84 +-- vehicle/cab/internal.h | 2 +- vehicle/cab/lightcommands.cpp | 262 +++---- vehicle/cab/pantographcommands.cpp | 78 +-- vehicle/cab/powercommands.cpp | 48 +- vehicle/cab/screens.cpp | 2 +- vehicle/cab/setup.cpp | 276 ++++---- vehicle/cab/signalcommands.cpp | 54 +- vehicle/cab/sounds.cpp | 64 +- vehicle/cab/train.cpp | 288 ++++---- vehicle/cab/update.cpp | 642 +++++++++--------- vehicle/crew.cpp | 6 +- vehicle/crew.h | 6 +- vehicle/crewchange.cpp | 14 +- vehicle/derailmotion.h | 4 +- vehicle/doorwings.h | 4 +- vehicle/drivingaid.cpp | 4 +- vehicle/drivingaid.h | 4 +- vehicle/dynamic/animations.cpp | 42 +- vehicle/dynamic/consist.cpp | 94 +-- vehicle/dynamic/couplers.cpp | 70 +- vehicle/dynamic/destinations.cpp | 14 +- vehicle/dynamic/internal.h | 2 +- vehicle/dynamic/lifecycle.cpp | 188 ++--- vehicle/dynamic/lights.cpp | 56 +- vehicle/dynamic/load.cpp | 86 +-- vehicle/dynamic/mmd.cpp | 92 +-- vehicle/dynamic/movement.cpp | 36 +- vehicle/dynamic/neighbours.cpp | 16 +- vehicle/dynamic/offtrack.cpp | 108 ++- vehicle/dynamic/sounds.cpp | 218 +++--- vehicle/dynamic/update.cpp | 588 ++++++++-------- vehicle/dynamic/vehicletable.cpp | 164 ++--- vehicle/dynamic/visual.cpp | 142 ++-- vehicle/enginestart.cpp | 14 +- vehicle/enginestart.h | 16 +- vehicle/handover.cpp | 8 +- vehicle/handover.h | 8 +- vehicle/lightsprogrammer.h | 2 +- vehicle/linebreaker.h | 2 +- vehicle/mainctrlact.h | 6 +- vehicle/odometer.h | 2 +- vehicle/odometerreading.h | 2 +- vehicle/pulleemode.h | 2 +- vehicle/smoke.cpp | 22 +- vehicle/smoke.h | 6 +- vehicle/timetableservice.cpp | 4 +- vehicle/timetableservice.h | 4 +- widgets/trainingcard.cpp | 4 +- widgets/vehicleparams.cpp | 102 +-- widgets/vehicleparams.h | 2 +- world/Event.cpp | 24 +- world/Road.cpp | 6 +- world/RoadPoint.cpp | 16 +- world/Track.cpp | 4 +- world/TrackBuckle.cpp | 6 +- world/TrkFoll.cpp | 6 +- world/station.cpp | 4 +- 207 files changed, 5147 insertions(+), 4950 deletions(-) rename physics/{mover.h => vehicle.h} (98%) create mode 100644 tools/rename/mover_to_physics.py diff --git a/AGENTS.md b/AGENTS.md index 82285b488..533d09efa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -107,12 +107,12 @@ Code that isn't otherwise touched keeps its names; renaming a member goes togeth scripts and the log read stays byte for byte the same whatever the C++ names are: the keywords of the `.fiz` and the scenery, the keys of the dictionaries of the Python screens, the texts of the log and of `STR(...)`. -The vehicle code is in `physics/` (the physics of the vehicles: `mover.h` and `physics/components/*.cpp` by subsystem, `brakes.*`, +The vehicle code is in `physics/` (the physics of the vehicles: `vehicle.h` with the class `physics::Vehicle`, and `physics/components/*.cpp` by subsystem, `brakes.*`, couplers, collisions, derailment) and `vehicle/` (the vehicle in the scenery, the cab, the AI). Keep it that way: - `physics/vehicletypes.h` holds the vocabulary the rest of the simulator passes around (vehicle ends, sides, couplings, lights, - sounds, the types of drive and brake). A header that only names these includes it, not `physics/mover.h`; a header that only - points at a `TMoverParameters` or a `TDynamicObject` declares it (`utilities/Classes.h`) and includes neither. + sounds, the types of drive and brake). A header that only names these includes it, not `physics/vehicle.h`; a header that only + points at a `physics::Vehicle` or a `TDynamicObject` declares it (`utilities/Classes.h`) and includes neither. - A state of several mutually exclusive values is an `enum class`, a set of independent conditions is named fields, not the bits of an `int`. Numbers of the formats (`.scn`, events, the network) are read into these where they come in and written where they go out. - The commands between the vehicles are `VehicleCommand` (`physics/vehiclecommand.h`); their text names only matter where a command diff --git a/application/application.cpp b/application/application.cpp index 8181c014e..6b3cc4a8f 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -47,7 +47,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include "utilities/translation.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #if WITH_DISCORD_RPC #include "ref/discord-rpc/include/discord_rpc.h" diff --git a/application/consistviews.cpp b/application/consistviews.cpp index 42cd41257..4d9fe76ab 100644 --- a/application/consistviews.cpp +++ b/application/consistviews.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Camera.h" #include "vehicle/Driver.h" #include "vehicle/DynObj.h" -#include "physics/mover.h" +#include "physics/vehicle.h" namespace { @@ -29,16 +29,16 @@ cameraviews::vehicle_pose pose_of(TDynamicObject const *Vehicle) { cameraviews::vehicle_pose pose; pose.position = Vehicle->GetPosition(); pose.front = Vehicle->VectorFront(); - pose.length = Vehicle->MoverParameters->Dim.L; - pose.width = Vehicle->MoverParameters->Dim.W; - pose.height = Vehicle->MoverParameters->Dim.H; + pose.length = Vehicle->physics->Dim.L; + pose.width = Vehicle->physics->Dim.W; + pose.height = Vehicle->physics->Dim.H; return pose; } // the end of the Vehicle the Other vehicle is beyond, -1 when it's beyond neither int end_towards(TDynamicObject const *Vehicle, TDynamicObject const *Other) { for (auto const side : VehicleEnds) { - if (Vehicle->MoverParameters->Neighbours[side].vehicle == Other) { + if (Vehicle->physics->Neighbours[side].vehicle == Other) { return NumberOf(side); } } @@ -58,14 +58,14 @@ cameraviews::coupler coupler_of(TDynamicObject const *Vehicle, VehicleEnd const cameraviews::coupler coupler; coupler.position = Vehicle->CouplerPosition(End); coupler.outward = Vehicle->VectorFront() * (End == VehicleEnd::front ? 1.0 : -1.0); - coupler.width = Vehicle->MoverParameters->Dim.W; + coupler.width = Vehicle->physics->Dim.W; return coupler; } // the driver's way: the front (1) or the rear (-1) of the Driven vehicle, as the user drives it int driven_way(TDynamicObject const *Driven) { - auto const cab{Driven->MoverParameters->CabOccupied < 0 ? -1 : 1}; - auto const direction{Driven->MoverParameters->DirActive < 0 ? -1 : 1}; + auto const cab{Driven->physics->CabOccupied < 0 ? -1 : 1}; + auto const direction{Driven->physics->DirActive < 0 ? -1 : 1}; return cab * direction; } @@ -143,8 +143,8 @@ TDynamicObject *consist_views::pick(std::vector const &Train, } double consist_views::gap_beyond(TDynamicObject const *Vehicle, VehicleEnd const End) { - auto const &neighbour{Vehicle->MoverParameters->Neighbours[End]}; - if (neighbour.vehicle == nullptr || false == Vehicle->MoverParameters->Couplers[End].CouplingFlag.Empty()) { + auto const &neighbour{Vehicle->physics->Neighbours[End]}; + if (neighbour.vehicle == nullptr || false == Vehicle->physics->Couplers[End].CouplingFlag.Empty()) { return -1.0; } if (neighbour.distance > cameraviews::coupler_watch_range) { @@ -175,7 +175,7 @@ consist_views::coupling_place consist_views::coupling_at(std::vectorMoverParameters->Neighbours[outer]}; + auto const &neighbour{vehicle->physics->Neighbours[outer]}; place.gap = gap_beyond(vehicle, EndOf(outer)); if (place.gap >= 0.0 && (neighbour.FacingEnd() == VehicleEnd::front || neighbour.FacingEnd() == VehicleEnd::rear)) { place.other = true; @@ -208,7 +208,7 @@ cameraviews::train_motion consist_views::motion_of(std::vector motion.head = end_along(Train[head], m_direction); motion.tail = end_along(Train[tail], -m_direction); motion.speed = std::abs(m_vehicle->GetVelocity()) / 3.6; - motion.width = m_vehicle->MoverParameters->Dim.W; + motion.width = m_vehicle->physics->Dim.W; if (Train.size() > 1) { auto const *behind{Train[head == 0 ? 1 : head - 1]}; motion.curvature = cameraviews::line_curvature(Train[head]->GetPosition(), facing_along(Train[head], m_direction), behind->GetPosition(), facing_along(behind, m_direction)); @@ -232,10 +232,10 @@ cameraviews::placement consist_views::place_shunting(TCamera const &Camera, std: auto const pose{pose_of(m_vehicle)}; auto length{0.0}; for (auto const *vehicle : Train) { - length += vehicle->MoverParameters->Dim.L; + length += vehicle->physics->Dim.L; } m_topdown = cameraviews::topdown_moved(m_topdown, Camera.Velocity, Seconds, pose, 0.5 * length + 50.0); - auto const facing{cameraviews::driving_facing(m_vehicle->VectorFront(), Driven->VectorFront(), Driven->MoverParameters->CabOccupied)}; + auto const facing{cameraviews::driving_facing(m_vehicle->VectorFront(), Driven->VectorFront(), Driven->physics->CabOccupied)}; return cameraviews::topdown_placement(m_topdown, pose, facing); } diff --git a/application/driverhints.cpp b/application/driverhints.cpp index 93e2735fd..721636949 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -11,7 +11,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Driver.h" #include "utilities/Globals.h" #include "utilities/utilities.h" -#include "physics/mover.h" +#include "physics/vehicle.h" void TController::hint( driver_hint const Value, hintpredicate const Predicate, float const Predicateparameter ) { @@ -83,70 +83,70 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // battery case driver_hint::batteryon: { if( AIControllFlag ) { - mvOccupied->BatterySwitch( true ); + occupied->BatterySwitch( true ); } remove_hint( driver_hint::batteryoff ); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->BatteryStart != start_t::manual || mvOccupied->Power24vIsAvailable == true; } ); + return occupied->BatteryStart != start_t::manual || occupied->Power24vIsAvailable == true; } ); break; } case driver_hint::batteryoff: { if( AIControllFlag ) { - mvOccupied->BatterySwitch( false ); + occupied->BatterySwitch( false ); } remove_hint( driver_hint::batteryon ); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->BatteryStart != start_t::manual || mvOccupied->Power24vIsAvailable == false; } ); + return occupied->BatteryStart != start_t::manual || occupied->Power24vIsAvailable == false; } ); break; } // battery case driver_hint::cabactivation: { - if (AIControllFlag && mvOccupied->Power24vIsAvailable) { - mvOccupied->CabActivisation(); + if (AIControllFlag && occupied->Power24vIsAvailable) { + occupied->CabActivisation(); CheckVehicles(); } remove_hint( driver_hint::cabdeactivation ); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->AutomaticCabActivation || mvOccupied->IsCabMaster(); } ); + return occupied->AutomaticCabActivation || occupied->IsCabMaster(); } ); break; } case driver_hint::cabdeactivation: { if (AIControllFlag) { - mvOccupied->CabDeactivisation(); + occupied->CabDeactivisation(); } remove_hint( driver_hint::cabactivation ); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->AutomaticCabActivation || (mvOccupied->CabMaster == false && mvOccupied->CabActive == 0); } ); + return occupied->AutomaticCabActivation || (occupied->CabMaster == false && occupied->CabActive == 0); } ); break; } // radio case driver_hint::radioon: { if( AIControllFlag ) { - mvOccupied->Radio = true; + occupied->Radio = true; } remove_hint( driver_hint::radiooff ); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->Radio == true; } ); + return occupied->Radio == true; } ); break; } case driver_hint::radiofuseon: { if( AIControllFlag ) { - mvOccupied->RadioFuse = true; + occupied->RadioFuse = true; } hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->RadioFuse == true; } ); + return occupied->RadioFuse == true; } ); break; } case driver_hint::radiochannel: { @@ -162,177 +162,177 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } case driver_hint::radiooff: { if( AIControllFlag ) { - mvOccupied->Radio = false; + occupied->Radio = false; } remove_hint( driver_hint::radioon ); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->Radio == false; } ); + return occupied->Radio == false; } ); break; } // oil pump case driver_hint::oilpumpon: { if( AIControllFlag ) { - mvOccupied->OilPumpSwitch( true ); + occupied->OilPumpSwitch( true ); } remove_hint( driver_hint::oilpumpoff ); hint( Action, [this](float const /*Parameter*/) { - auto const &device { mvOccupied->OilPump }; - return device.start_type != start_t::manual || device.is_enabled == true || device.is_active == true || mvOccupied->Mains; } ); + auto const &device { occupied->OilPump }; + return device.start_type != start_t::manual || device.is_enabled == true || device.is_active == true || occupied->Mains; } ); break; } case driver_hint::oilpumpoff: { if( AIControllFlag ) { - mvOccupied->OilPumpSwitch( false ); + occupied->OilPumpSwitch( false ); } remove_hint( driver_hint::oilpumpon ); hint( Action, [this](float const /*Parameter*/) { - auto const &device { mvOccupied->OilPump }; + auto const &device { occupied->OilPump }; return device.start_type != start_t::manual || (device.is_enabled == false && device.is_active == false); } ); break; } // fuel pump case driver_hint::fuelpumpon: { if( AIControllFlag ) { - mvOccupied->FuelPumpSwitch( true ); + occupied->FuelPumpSwitch( true ); } remove_hint( driver_hint::fuelpumpoff ); hint( Action, [this](float const /*Parameter*/) { - auto const &device { mvOccupied->FuelPump }; + auto const &device { occupied->FuelPump }; return device.start_type != start_t::manual || device.is_enabled == true || device.is_active == true; } ); break; } case driver_hint::fuelpumpoff: { if( AIControllFlag ) { - mvOccupied->FuelPumpSwitch( false ); + occupied->FuelPumpSwitch( false ); } remove_hint( driver_hint::fuelpumpon ); hint( Action, [this](float const /*Parameter*/) { - auto const &device { mvOccupied->FuelPump }; + auto const &device { occupied->FuelPump }; return device.start_type != start_t::manual || (device.is_enabled == false && device.is_active == false); } ); break; } // pantographs case driver_hint::pantographairsourcesetmain: { if( AIControllFlag ) { - mvPantographUnit->bPantKurek3 = true; + pantographUnit->bPantKurek3 = true; } remove_hint( driver_hint::pantographairsourcesetauxiliary ); hint( Action, [this](float const /*Parameter*/) { - return mvPantographUnit->bPantKurek3 == true; } ); + return pantographUnit->bPantKurek3 == true; } ); break; } case driver_hint::pantographairsourcesetauxiliary: { if( AIControllFlag ) { - mvPantographUnit->bPantKurek3 = false; + pantographUnit->bPantKurek3 = false; } remove_hint( driver_hint::pantographcompressoron ); hint( Action, [this](float const /*Parameter*/) { - return mvPantographUnit->bPantKurek3 == false; } ); + return pantographUnit->bPantKurek3 == false; } ); break; } case driver_hint::pantographcompressoron: { if( AIControllFlag ) { - mvPantographUnit->PantCompFlag = true; + pantographUnit->PantCompFlag = true; } remove_hint( driver_hint::pantographcompressoroff ); hint( Action, [this](float const /*Parameter*/) { - return mvPantographUnit->PantCompFlag == true; } ); + return pantographUnit->PantCompFlag == true; } ); break; } case driver_hint::pantographcompressoroff: { if( AIControllFlag ) { - mvPantographUnit->PantCompFlag = false; + pantographUnit->PantCompFlag = false; } remove_hint( driver_hint::pantographcompressoron ); hint( Action, [this](float const /*Parameter*/) { - return mvPantographUnit->PantCompFlag == false; } ); + return pantographUnit->PantCompFlag == false; } ); break; } case driver_hint::pantographsvalveon: { if( AIControllFlag ) { - mvOccupied->OperatePantographsValve( operation_t::enable ); + occupied->OperatePantographsValve( operation_t::enable ); } remove_hint( driver_hint::pantographsvalveoff ); hint( Action, [this](float const /*Parameter*/) { - return mvPantographUnit->PantsValve.is_active == true; } ); + return pantographUnit->PantsValve.is_active == true; } ); break; } case driver_hint::frontpantographvalveon: { if( AIControllFlag ) { - mvOccupied->OperatePantographValve( VehicleEnd::front, operation_t::enable ); + occupied->OperatePantographValve( VehicleEnd::front, operation_t::enable ); } remove_hint( driver_hint::frontpantographvalveoff ); hint( Action, [ this ]( float const Parameter ) { - return mvPantographUnit->Pantographs[VehicleEnd::front].valve.is_active == true || (Parameter > 0 && mvOccupied->Vel > Parameter); }, + return pantographUnit->Pantographs[VehicleEnd::front].valve.is_active == true || (Parameter > 0 && occupied->Vel > Parameter); }, Actionparameter ); break; } case driver_hint::frontpantographvalveoff: { if( AIControllFlag ) { - mvOccupied->OperatePantographValve( VehicleEnd::front, operation_t::disable ); + occupied->OperatePantographValve( VehicleEnd::front, operation_t::disable ); } remove_hint( driver_hint::frontpantographvalveon ); hint( Action, [this](float const /*Parameter*/) { - return mvPantographUnit->Pantographs[VehicleEnd::front].valve.is_active == false; } ); + return pantographUnit->Pantographs[VehicleEnd::front].valve.is_active == false; } ); break; } case driver_hint::rearpantographvalveon: { if( AIControllFlag ) { - mvOccupied->OperatePantographValve( VehicleEnd::rear, operation_t::enable ); + occupied->OperatePantographValve( VehicleEnd::rear, operation_t::enable ); } remove_hint( driver_hint::rearpantographvalveoff ); hint( Action, [ this ]( float const Parameter ) { - return mvPantographUnit->Pantographs[VehicleEnd::rear].valve.is_active == true || (Parameter > 0 && mvOccupied->Vel > Parameter); }, + return pantographUnit->Pantographs[VehicleEnd::rear].valve.is_active == true || (Parameter > 0 && occupied->Vel > Parameter); }, Actionparameter ); break; } case driver_hint::rearpantographvalveoff: { if( AIControllFlag ) { - mvOccupied->OperatePantographValve( VehicleEnd::rear, operation_t::disable ); + occupied->OperatePantographValve( VehicleEnd::rear, operation_t::disable ); } remove_hint( driver_hint::rearpantographvalveon ); hint( Action, [this](float const /*Parameter*/) { - return mvPantographUnit->Pantographs[VehicleEnd::rear].valve.is_active == false; } ); + return pantographUnit->Pantographs[VehicleEnd::rear].valve.is_active == false; } ); break; } // converter case driver_hint::converteron: { if( AIControllFlag ) { - mvOccupied->ConverterSwitch( true ); + occupied->ConverterSwitch( true ); // the local switch of the converter too, where the line contactors wait for the vehicle's own converter // (LineContactorsInterlock): left off by the human driver, that vehicle would never take power pVehicle->for_each( Coupling::control, []( TDynamicObject * Vehicle ) { - auto *vehicle { Vehicle->MoverParameters }; + auto *vehicle { Vehicle->physics }; if( vehicle->LineContactorsHeldByLocalConverterSwitch() ) { vehicle->ConverterAllowLocal = true; } } ); } @@ -345,7 +345,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } case driver_hint::converteroff: { if( AIControllFlag ) { - mvOccupied->ConverterSwitch( false ); + occupied->ConverterSwitch( false ); } remove_hint( driver_hint::converteron ); hint( @@ -357,38 +357,38 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // relays case driver_hint::primaryconverteroverloadreset: { if( AIControllFlag ) { - mvOccupied->RelayReset( relay_t::primaryconverteroverload ); + occupied->RelayReset( relay_t::primaryconverteroverload ); } hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->ConverterOverloadRelayStart != start_t::manual || mvOccupied->ConvOvldFlag == false; } ); + return occupied->ConverterOverloadRelayStart != start_t::manual || occupied->ConvOvldFlag == false; } ); break; } case driver_hint::maincircuitgroundreset: { if( AIControllFlag ) { - mvOccupied->RelayReset( relay_t::maincircuitground ); + occupied->RelayReset( relay_t::maincircuitground ); } hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->GroundRelayStart != start_t::manual || mvOccupied->GroundRelay == true; } ); + return occupied->GroundRelayStart != start_t::manual || occupied->GroundRelay == true; } ); break; } case driver_hint::tractionnmotoroverloadreset: { if( AIControllFlag ) { - mvOccupied->RelayReset( relay_t::tractionnmotoroverload ); + occupied->RelayReset( relay_t::tractionnmotoroverload ); } hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->FuseFlag == false; } ); + return occupied->FuseFlag == false; } ); break; } // line breaker case driver_hint::linebreakerclose: { if( AIControllFlag ) { - mvOccupied->MainSwitch( true ); + occupied->MainSwitch( true ); } remove_hint( driver_hint::linebreakeropen ); hint( @@ -399,7 +399,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } case driver_hint::linebreakeropen: { if( AIControllFlag ) { - mvOccupied->MainSwitch( false ); + occupied->MainSwitch( false ); } remove_hint( driver_hint::linebreakerclose ); hint( @@ -412,7 +412,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // compressor case driver_hint::compressoron: { if( AIControllFlag ) { - mvOccupied->CompressorSwitch( true ); + occupied->CompressorSwitch( true ); } remove_hint( driver_hint::compressoroff ); hint( @@ -423,7 +423,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } case driver_hint::compressoroff: { if( AIControllFlag ) { - mvOccupied->CompressorSwitch( false ); + occupied->CompressorSwitch( false ); } remove_hint( driver_hint::compressoron ); hint( @@ -434,74 +434,74 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } case driver_hint::frontmotorblowerson: { if( AIControllFlag ) { - mvOccupied->MotorBlowersSwitchOff( false, VehicleEnd::front ); - mvOccupied->MotorBlowersSwitch( true, VehicleEnd::front ); + occupied->MotorBlowersSwitchOff( false, VehicleEnd::front ); + occupied->MotorBlowersSwitch( true, VehicleEnd::front ); } remove_hint( driver_hint::frontmotorblowersoff ); hint( Action, [this]( float const /*Parameter*/ ) { - auto const &device { mvOccupied->MotorBlowers[ VehicleEnd::front ] }; + auto const &device { occupied->MotorBlowers[ VehicleEnd::front ] }; return device.start_type != start_t::manual || (device.is_enabled == true && device.is_disabled == false); } ); break; } case driver_hint::rearmotorblowerson: { if( AIControllFlag ) { - mvOccupied->MotorBlowersSwitchOff( false, VehicleEnd::rear ); - mvOccupied->MotorBlowersSwitch( true, VehicleEnd::rear ); + occupied->MotorBlowersSwitchOff( false, VehicleEnd::rear ); + occupied->MotorBlowersSwitch( true, VehicleEnd::rear ); } remove_hint( driver_hint::rearmotorblowersoff ); hint( Action, [this]( float const /*Parameter*/ ) { - auto const &device { mvOccupied->MotorBlowers[ VehicleEnd::rear ] }; + auto const &device { occupied->MotorBlowers[ VehicleEnd::rear ] }; return device.start_type != start_t::manual || (device.is_enabled == true && device.is_disabled == false); } ); break; } // spring brake case driver_hint::springbrakeon: { if( AIControllFlag ) { - mvOccupied->SpringBrakeActivate( true ); + occupied->SpringBrakeActivate( true ); } remove_hint( driver_hint::springbrakeoff ); hint( Action, [this]( float const /*Parameter*/ ) { - return mvOccupied->SpringBrake.Activate == true; } ); + return occupied->SpringBrake.Activate == true; } ); break; } case driver_hint::springbrakeoff: { if( AIControllFlag ) { - mvOccupied->SpringBrakeActivate( false ); + occupied->SpringBrakeActivate( false ); } remove_hint( driver_hint::springbrakeon ); hint( Action, [this]( float const /*Parameter*/ ) { - return mvOccupied->SpringBrake.Activate == false; } ); + return occupied->SpringBrake.Activate == false; } ); break; } // manual brake case driver_hint::manualbrakon: { if( AIControllFlag ) { - mvOccupied->IncManualBrakeLevel( ManualBrakePosNo ); + occupied->IncManualBrakeLevel( ManualBrakePosNo ); } remove_hint( driver_hint::manualbrakoff ); hint( Action, [this]( float const /*Parameter*/ ) { - return mvOccupied->LocalBrake != TLocalBrake::ManualBrake || mvOccupied->MBrake == false || mvOccupied->ManualBrakePos == ManualBrakePosNo; } ); + return occupied->LocalBrake != TLocalBrake::ManualBrake || occupied->MBrake == false || occupied->ManualBrakePos == ManualBrakePosNo; } ); break; } case driver_hint::manualbrakoff: { if( AIControllFlag ) { - mvOccupied->DecManualBrakeLevel( ManualBrakePosNo ); + occupied->DecManualBrakeLevel( ManualBrakePosNo ); } remove_hint( driver_hint::manualbrakon ); hint( Action, [this]( float const /*Parameter*/ ) { - return mvOccupied->LocalBrake != TLocalBrake::ManualBrake || mvOccupied->MBrake == false || mvOccupied->ManualBrakePos == 0; } ); + return occupied->LocalBrake != TLocalBrake::ManualBrake || occupied->MBrake == false || occupied->ManualBrakePos == 0; } ); break; } // master controller @@ -593,8 +593,8 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return AccDesired <= EU07_AI_NOACCELERATION || (false == Ready && false == mvOccupied->ShuntMode) || AccDesired - AbsAccS <= 0.05 || - (mvOccupied->EIMCtrlType > 0 ? mvControlling->eimic_real >= 1.0 : mvControlling->IsScndCtrlMaxPowerPos() && mvControlling->IsMainCtrlMaxPowerPos()); } ); + return AccDesired <= EU07_AI_NOACCELERATION || (false == Ready && false == occupied->ShuntMode) || AccDesired - AbsAccS <= 0.05 || + (occupied->EIMCtrlType > 0 ? mvControlling->eimic_real >= 1.0 : mvControlling->IsScndCtrlMaxPowerPos() && mvControlling->IsMainCtrlMaxPowerPos()); } ); break; } case driver_hint::bufferscompress: { @@ -760,7 +760,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return mvPantographUnit->PantPress >= (is_emu() ? (mvPantographUnit->PantPressLockActive ? 4.6 : 2.6) : 4.2); } ); + return pantographUnit->PantPress >= (is_emu() ? (pantographUnit->PantPressLockActive ? 4.6 : 2.6) : 4.2); } ); break; } case driver_hint::waitbrakecharge: { @@ -796,8 +796,8 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // driver_hint_brakingforcesetzero // driver_hint_brakingforcelap case driver_hint::trainbrakesetpipeunlock: { - if (AIControllFlag && mvOccupied->HandleUnlock != -3) { - while( BrakeCtrlPosition >= mvOccupied->HandleUnlock + if (AIControllFlag && occupied->HandleUnlock != -3) { + while( BrakeCtrlPosition >= occupied->HandleUnlock && BrakeLevelAdd(-1) ) { // all work is done in the header } @@ -806,19 +806,19 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->HandleUnlock == -3 || BrakeCtrlPosition == mvOccupied->HandleUnlock; } ); + return occupied->HandleUnlock == -3 || BrakeCtrlPosition == occupied->HandleUnlock; } ); break; } case driver_hint::trainbrakerelease: { if( AIControllFlag ) { -// mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_RP ) ); +// occupied->BrakeLevelSet( occupied->Handle->GetPos( bh_RP ) ); BrakeLevelSet( gbh_RP ); } remove_train_brake_hints(); hint( Action, [this](float const /*Parameter*/) { - return is_equal(mvOccupied->fBrakeCtrlPos, mvOccupied->Handle->GetPos(bh_RP), 0.2) || (mvOccupied->Handle->Time && mvOccupied->Handle->GetCP() > mvOccupied->HighPipePress - 0.05); } ); + return is_equal(occupied->fBrakeCtrlPos, occupied->Handle->GetPos(bh_RP), 0.2) || (occupied->Handle->Time && occupied->Handle->GetCP() > occupied->HighPipePress - 0.05); } ); // return ( BrakeCtrlPosition == gbh_RP ); } ); break; } @@ -826,7 +826,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) if( AIControllFlag ) { // za radą yB ustawiamy pozycję 3 kranu (ruszanie kranem w innych miejscach powino zostać wyłączone) if( BrakeSystem == TBrakeSystem::ElectroPneumatic && false == ForcePNBrake ) { - mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_EPB ) ); + occupied->BrakeLevelSet( occupied->Handle->GetPos( bh_EPB ) ); } else { BrakeCtrlPosition = 3; @@ -867,7 +867,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const Parameter) { - return std::abs(mvControlling->Fb) > Parameter || is_equal(mvOccupied->fBrakeCtrlPos, mvOccupied->Handle->GetPos(bh_EB), 0.2); }, + return std::abs(mvControlling->Fb) > Parameter || is_equal(occupied->fBrakeCtrlPos, occupied->Handle->GetPos(bh_EB), 0.2); }, static_cast(std::max( 0.0, std::max( @@ -885,7 +885,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return Ready && fReady < 0.4 && is_equal(mvOccupied->fBrakeCtrlPos, mvOccupied->Handle->GetPos(bh_RP), 0.2); } ); + return Ready && fReady < 0.4 && is_equal(occupied->fBrakeCtrlPos, occupied->Handle->GetPos(bh_RP), 0.2); } ); break; } case driver_hint::brakingforcelap: { @@ -899,18 +899,18 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // independent brake case driver_hint::independentbrakeapply: { - if (AIControllFlag && mvOccupied->LocalBrakePosA < 1.0) { - mvOccupied->IncLocalBrakeLevel( LocalBrakePosNo ); - if (mvOccupied->EIMCtrlEmergency) { - mvOccupied->DecLocalBrakeLevel(1); + if (AIControllFlag && occupied->LocalBrakePosA < 1.0) { + occupied->IncLocalBrakeLevel( LocalBrakePosNo ); + if (occupied->EIMCtrlEmergency) { + occupied->DecLocalBrakeLevel(1); } } remove_hint( driver_hint::independentbrakerelease ); hint( Action, [this](float const Parameter) { - return mvOccupied->LocalBrakePosA >= Parameter; }, - ( LocalBrakePosNo - ( mvOccupied->EIMCtrlEmergency ? 1 : 0 ) ) / LocalBrakePosNo ); + return occupied->LocalBrakePosA >= Parameter; }, + ( LocalBrakePosNo - ( occupied->EIMCtrlEmergency ? 1 : 0 ) ) / LocalBrakePosNo ); break; } case driver_hint::independentbrakerelease: { @@ -921,36 +921,36 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->LocalBrakePosA < 0.05; } ); + return occupied->LocalBrakePosA < 0.05; } ); break; } // reverser case driver_hint::directionforward: { if( AIControllFlag ) { - OrderDirectionChange( 1, mvOccupied ); + OrderDirectionChange( 1, occupied ); } remove_reverser_hints(); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->DirActive * mvOccupied->CabActive > 0; } ); + return occupied->DirActive * occupied->CabActive > 0; } ); break; } case driver_hint::directionbackward: { if( AIControllFlag ) { - OrderDirectionChange( -1, mvOccupied ); + OrderDirectionChange( -1, occupied ); } remove_reverser_hints(); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->DirActive * mvOccupied->CabActive < 0; } ); + return occupied->DirActive * occupied->CabActive < 0; } ); break; } case driver_hint::directionother: { if( AIControllFlag ) { -// DirectionForward( mvOccupied->DirAbsolute < 0 ); - OrderDirectionChange( iDirectionOrder, mvOccupied ); +// DirectionForward( occupied->DirAbsolute < 0 ); + OrderDirectionChange( iDirectionOrder, occupied ); DirectionChange(); } remove_reverser_hints(); @@ -968,7 +968,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->DirActive == 0; } ); + return occupied->DirActive == 0; } ); break; } // anti-slip systems @@ -1007,19 +1007,19 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // horns case driver_hint::hornon: { if( AIControllFlag ) { - mvOccupied->WarningSignal = static_cast( Actionparameter ); + occupied->WarningSignal = static_cast( Actionparameter ); } remove_hint( driver_hint::hornoff ); hint( Action, [this](float const /*Parameter*/) { // NOTE: we provide slightly larger horn activation window for human driver - return fWarningDuration + 5.0 < 0.05 || mvOccupied->WarningSignal != 0; } ); + return fWarningDuration + 5.0 < 0.05 || occupied->WarningSignal != 0; } ); break; } case driver_hint::hornoff: { if( AIControllFlag ) { - mvOccupied->WarningSignal = 0; + occupied->WarningSignal = 0; } /* // NOTE: for human driver the hint to switch horn on will disappear automatically @@ -1027,50 +1027,50 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const Parameter) -> bool { - return ( mvOccupied->WarningSignal == 0 ); } ); + return ( occupied->WarningSignal == 0 ); } ); */ break; } // door locks case driver_hint::consistdoorlockson: { if( AIControllFlag ) { - mvOccupied->LockDoors( true ); + occupied->LockDoors( true ); } // TODO: remove other door lock hints hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->Doors.has_lock == false || mvOccupied->Doors.lock_enabled == true; } ); + return occupied->Doors.has_lock == false || occupied->Doors.lock_enabled == true; } ); break; } // departure signal case driver_hint::departuresignalon: { if( AIControllFlag ) { - mvOccupied->signal_departure( true ); + occupied->signal_departure( true ); } remove_hint( driver_hint::departuresignaloff ); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->Doors.has_warning == false || mvOccupied->Doors.has_autowarning == true || mvOccupied->DepartureSignal == true || mvOccupied->Vel > 5.0; } ); + return occupied->Doors.has_warning == false || occupied->Doors.has_autowarning == true || occupied->DepartureSignal == true || occupied->Vel > 5.0; } ); break; } case driver_hint::departuresignaloff: { if( AIControllFlag ) { - mvOccupied->signal_departure( false ); + occupied->signal_departure( false ); } remove_hint( driver_hint::departuresignalon ); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->Doors.has_warning == false || mvOccupied->Doors.has_autowarning == true || mvOccupied->DepartureSignal == false; } ); + return occupied->Doors.has_warning == false || occupied->Doors.has_autowarning == true || occupied->DepartureSignal == false; } ); break; } // consist doors case driver_hint::doorrightopen: { if( AIControllFlag - || pVehicle->MoverParameters->Doors.open_control == control_t::conductor ) { - pVehicle->MoverParameters->OperateDoors( VehicleSide::right, true ); + || pVehicle->physics->Doors.open_control == control_t::conductor ) { + pVehicle->physics->OperateDoors( VehicleSide::right, true ); } remove_hint( driver_hint::doorrightclose ); hint( @@ -1081,8 +1081,8 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } case driver_hint::doorrightclose: { if( AIControllFlag - || pVehicle->MoverParameters->Doors.open_control == control_t::conductor ) { - pVehicle->MoverParameters->OperateDoors( VehicleSide::right, false ); + || pVehicle->physics->Doors.open_control == control_t::conductor ) { + pVehicle->physics->OperateDoors( VehicleSide::right, false ); } remove_hint( driver_hint::doorrightopen ); hint( @@ -1093,8 +1093,8 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } case driver_hint::doorleftopen: { if( AIControllFlag - || pVehicle->MoverParameters->Doors.open_control == control_t::conductor ) { - pVehicle->MoverParameters->OperateDoors( VehicleSide::left, true ); + || pVehicle->physics->Doors.open_control == control_t::conductor ) { + pVehicle->physics->OperateDoors( VehicleSide::left, true ); } remove_hint( driver_hint::doorleftclose ); hint( @@ -1105,8 +1105,8 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } case driver_hint::doorleftclose: { if( AIControllFlag - || pVehicle->MoverParameters->Doors.open_control == control_t::conductor ) { - pVehicle->MoverParameters->OperateDoors( VehicleSide::left, false ); + || pVehicle->physics->Doors.open_control == control_t::conductor ) { + pVehicle->physics->OperateDoors( VehicleSide::left, false ); } remove_hint( driver_hint::doorleftopen ); hint( @@ -1117,7 +1117,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } case driver_hint::doorrightpermiton: { if( AIControllFlag ) { - pVehicle->MoverParameters->PermitDoors( VehicleSide::right, true ); + pVehicle->physics->PermitDoors( VehicleSide::right, true ); } remove_hint( driver_hint::doorrightpermitoff ); hint( @@ -1128,7 +1128,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } case driver_hint::doorrightpermitoff: { if( AIControllFlag ) { - pVehicle->MoverParameters->PermitDoors( VehicleSide::right, false ); + pVehicle->physics->PermitDoors( VehicleSide::right, false ); } remove_hint( driver_hint::doorrightpermiton ); hint( @@ -1139,7 +1139,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } case driver_hint::doorleftpermiton: { if( AIControllFlag ) { - pVehicle->MoverParameters->PermitDoors( VehicleSide::left, true ); + pVehicle->physics->PermitDoors( VehicleSide::left, true ); } remove_hint( driver_hint::doorleftpermitoff ); hint( @@ -1150,7 +1150,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } case driver_hint::doorleftpermitoff: { if( AIControllFlag ) { - pVehicle->MoverParameters->PermitDoors( VehicleSide::left, false ); + pVehicle->physics->PermitDoors( VehicleSide::left, false ); } remove_hint( driver_hint::doorleftpermiton ); hint( @@ -1162,93 +1162,93 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // doorsteps, as the timetable asks (eu07/maszyna#95) case driver_hint::doorstepon: { if( AIControllFlag ) { - mvOccupied->PermitDoorStep( true ); + occupied->PermitDoorStep( true ); } remove_hint( driver_hint::doorstepoff ); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->Doors.step_enabled == true; } ); + return occupied->Doors.step_enabled == true; } ); break; } case driver_hint::doorstepoff: { if( AIControllFlag ) { - mvOccupied->PermitDoorStep( false ); + occupied->PermitDoorStep( false ); } remove_hint( driver_hint::doorstepon ); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->Doors.step_enabled == false; } ); + return occupied->Doors.step_enabled == false; } ); break; } // consist lights case driver_hint::consistlightson: { if( AIControllFlag ) { - mvOccupied->CompartmentLightsSwitch( true ); - mvOccupied->CompartmentLightsSwitchOff( false ); + occupied->CompartmentLightsSwitch( true ); + occupied->CompartmentLightsSwitchOff( false ); } remove_hint( driver_hint::consistlightsoff ); hint( Action, [this](float const /*Parameter*/) { - auto const &device { mvOccupied->CompartmentLights }; + auto const &device { occupied->CompartmentLights }; return Global.fLuminance * ConsistShade > 0.40 || device.start_type != start_t::manual || (device.is_enabled == true && device.is_disabled == false) || device.is_active == true; } ); break; } case driver_hint::consistlightsoff: { if( AIControllFlag ) { - mvOccupied->CompartmentLightsSwitch( false ); - mvOccupied->CompartmentLightsSwitchOff( true ); + occupied->CompartmentLightsSwitch( false ); + occupied->CompartmentLightsSwitchOff( true ); } remove_hint( driver_hint::consistlightson ); hint( Action, [this](float const /*Parameter*/) { - auto const &device { mvOccupied->CompartmentLights }; + auto const &device { occupied->CompartmentLights }; return Global.fLuminance * ConsistShade < 0.35 || device.start_type != start_t::manual || (device.is_enabled == false && device.is_active == false); } ); break; } // consist heating case driver_hint::consistheatingon: { if( AIControllFlag ) { - mvOccupied->HeatingSwitch( true ); + occupied->HeatingSwitch( true ); } remove_hint( driver_hint::consistheatingoff ); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->HeatingAllow == true; } ); + return occupied->HeatingAllow == true; } ); break; } case driver_hint::consistheatingoff: { if( AIControllFlag ) { - mvOccupied->HeatingSwitch( false ); + occupied->HeatingSwitch( false ); } remove_hint( driver_hint::consistheatingon ); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->HeatingAllow == false; } ); + return occupied->HeatingAllow == false; } ); break; } case driver_hint::securitysystemreset: { - if (AIControllFlag && mvOccupied->SecuritySystem.is_blinking()) - mvOccupied->SecuritySystemReset(); + if (AIControllFlag && occupied->SecuritySystem.is_blinking()) + occupied->SecuritySystemReset(); hint( Action, [this](float const /*Parameter*/) { - return !mvOccupied->SecuritySystem.is_vigilance_blinking(); } ); + return !occupied->SecuritySystem.is_vigilance_blinking(); } ); break; } case driver_hint::shpsystemreset: { - if (AIControllFlag && mvOccupied->SecuritySystem.is_cabsignal_blinking()) - mvOccupied->SecuritySystem.cabsignal_reset(); + if (AIControllFlag && occupied->SecuritySystem.is_cabsignal_blinking()) + occupied->SecuritySystem.cabsignal_reset(); hint( Action, [this](float const /*Parameter*/) { - return !mvOccupied->SecuritySystem.is_cabsignal_blinking(); } ); + return !occupied->SecuritySystem.is_cabsignal_blinking(); } ); break; } case driver_hint::couplingadapterattach: { @@ -1259,7 +1259,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const Parameter) { - auto const &device { pVehicles[ VehicleEnd::front ]->MoverParameters->Couplers[ static_cast( Parameter ) ] }; + auto const &device { pVehicles[ VehicleEnd::front ]->physics->Couplers[ static_cast( Parameter ) ] }; return device.type() == TCouplerType::Automatic; } ); break; } @@ -1270,7 +1270,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const Parameter) { - auto const &device { pVehicles[ VehicleEnd::front ]->MoverParameters->Couplers[ static_cast( Parameter ) ] }; + auto const &device { pVehicles[ VehicleEnd::front ]->physics->Couplers[ static_cast( Parameter ) ] }; return false == device.has_adapter(); } ); break; } @@ -1305,7 +1305,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // HACK: the 'front' and 'rear' of the consist is determined by current consist direction // since direction shouldn't affect Tb1 light configuration, we 'counter' this behaviour by virtually swapping end vehicles if( AIControllFlag ) { - if( mvOccupied->DirActive >= 0 ) { Lights( light::headlight_right, light::headlight_left ); } + if( occupied->DirActive >= 0 ) { Lights( light::headlight_right, light::headlight_left ); } else { Lights( light::headlight_left, light::headlight_right ); } } remove_hint( driver_hint::headcodepc1 ); @@ -1315,8 +1315,8 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - auto const activeend { mvOccupied->CabActive >= 0 ? VehicleEnd::front : VehicleEnd::rear }; - auto const consistfront { mvOccupied->DirActive >= 0 ? VehicleEnd::front : VehicleEnd::rear }; + auto const activeend { occupied->CabActive >= 0 ? VehicleEnd::front : VehicleEnd::rear }; + auto const consistfront { occupied->DirActive >= 0 ? VehicleEnd::front : VehicleEnd::rear }; return pVehicles[consistfront]->has_signal_on(activeend, light::headlight_right) && pVehicles[Opposite(consistfront)]->has_signal_on(Opposite(activeend), light::headlight_left); } ); break; } @@ -1344,32 +1344,32 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - auto const activeend { mvOccupied->CabActive >= 0 ? VehicleEnd::front : VehicleEnd::rear }; - auto const consistfront { mvOccupied->DirActive >= 0 ? VehicleEnd::front : VehicleEnd::rear }; + auto const activeend { occupied->CabActive >= 0 ? VehicleEnd::front : VehicleEnd::rear }; + auto const consistfront { occupied->DirActive >= 0 ? VehicleEnd::front : VehicleEnd::rear }; return pVehicles[consistfront]->has_signal_on(activeend, 0) && pVehicles[Opposite(consistfront)]->has_signal_on(Opposite(activeend), 0); } ); break; } // releaser case driver_hint::releaseron: { if( AIControllFlag ) { - mvOccupied->BrakeReleaser( 1 ); + occupied->BrakeReleaser( 1 ); } remove_hint( driver_hint::releaseroff ); hint( Action, [this](float const /*Parameter*/) { - return true == mvOccupied->Hamulec->Releaser(); } ); + return true == occupied->Hamulec->Releaser(); } ); break; } case driver_hint::releaseroff: { if( AIControllFlag ) { - mvOccupied->BrakeReleaser( 0 ); + occupied->BrakeReleaser( 0 ); } remove_hint( driver_hint::releaseron ); hint( Action, [this](float const /*Parameter*/) { - return false == mvOccupied->Hamulec->Releaser(); } ); + return false == occupied->Hamulec->Releaser(); } ); break; } diff --git a/application/drivermode.cpp b/application/drivermode.cpp index b121d7250..3b132cb60 100644 --- a/application/drivermode.cpp +++ b/application/drivermode.cpp @@ -31,7 +31,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "rendering/renderer.h" #include "utilities/Logs.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include @@ -682,7 +682,7 @@ void driver_mode::update_camera(double const Deltatime) if (controlled && glm::length2(controlled->GetPosition() - Camera.Pos) < sq(1500)) // length2 is better than length for comparing because it does not require sqrt function { // gdy bliżej niż 1.5km - Camera.LookAt = controlled->GetPosition() + 0.4 * controlled->VectorUp() * controlled->MoverParameters->Dim.H; + Camera.LookAt = controlled->GetPosition() + 0.4 * controlled->VectorUp() * controlled->physics->Dim.H; } else { @@ -702,7 +702,7 @@ void driver_mode::update_camera(double const Deltatime) if (d) pDynamicNearest = d; // zmiana na nowy, jeśli coś znaleziony niepusty if (pDynamicNearest) - Camera.LookAt = pDynamicNearest->GetPosition() + 0.4 * pDynamicNearest->VectorUp() * pDynamicNearest->MoverParameters->Dim.H; + Camera.LookAt = pDynamicNearest->GetPosition() + 0.4 * pDynamicNearest->VectorUp() * pDynamicNearest->physics->Dim.H; } Camera.RaLook(); // jednorazowe przestawienie kamery } @@ -787,7 +787,7 @@ void driver_mode::update_camera(double const Deltatime) { // jeśli jazda w kabinie, przeliczyć trzeba parametry kamery /* - auto tempangle = controlled->VectorFront() * ( controlled->MoverParameters->CabOccupied == -1 ? -1 : 1 ); + auto tempangle = controlled->VectorFront() * ( controlled->physics->CabOccupied == -1 ? -1 : 1 ); double modelrotate = atan2( -tempangle.x, tempangle.z ); */ if (false == FreeFlyModeFlag && true == Global.ctrlState && (m_input.keyboard.key(GLFW_KEY_LEFT) != GLFW_RELEASE || m_input.keyboard.key(GLFW_KEY_RIGHT) != GLFW_RELEASE)) @@ -1192,7 +1192,7 @@ void driver_mode::DistantView(bool const Near) return; } - auto const cab = vehicle->MoverParameters->CabOccupied == 0 ? 1 : vehicle->MoverParameters->CabOccupied; + auto const cab = vehicle->physics->CabOccupied == 0 ? 1 : vehicle->physics->CabOccupied; auto const left = vehicle->VectorLeft() * (double)cab; if (true == Near) @@ -1203,7 +1203,7 @@ void driver_mode::DistantView(bool const Near) else { - Camera.Pos = vehicle->GetPosition() + vehicle->VectorFront() * (double)vehicle->MoverParameters->CabOccupied * 50.0 + glm::dvec3(-10.0 * left.x, 1.6, -10.0 * left.z); + Camera.Pos = vehicle->GetPosition() + vehicle->VectorFront() * (double)vehicle->physics->CabOccupied * 50.0 + glm::dvec3(-10.0 * left.x, 1.6, -10.0 * left.z); } Camera.m_owner = nullptr; @@ -1256,12 +1256,12 @@ void driver_mode::ExternalView() else { // default view setup - auto const offsetflip{(vehicle->MoverParameters->CabOccupied == 0 ? 1 : vehicle->MoverParameters->CabOccupied) * - (vehicle->MoverParameters->DirActive == 0 ? 1 : vehicle->MoverParameters->DirActive)}; + auto const offsetflip{(vehicle->physics->CabOccupied == 0 ? 1 : vehicle->physics->CabOccupied) * + (vehicle->physics->DirActive == 0 ? 1 : vehicle->physics->DirActive)}; - Camera.m_owneroffset = {1.5 * owner->MoverParameters->Dim.W * offsetflip, std::max(5.0, 1.25 * owner->MoverParameters->Dim.H), -0.4 * owner->MoverParameters->Dim.L * offsetflip}; + Camera.m_owneroffset = {1.5 * owner->physics->Dim.W * offsetflip, std::max(5.0, 1.25 * owner->physics->Dim.H), -0.4 * owner->physics->Dim.L * offsetflip}; - Camera.Angle.y = glm::radians(vehicle->MoverParameters->DirActive < 0 ? 180.0 : 0.0); + Camera.Angle.y = glm::radians(vehicle->physics->DirActive < 0 ? 180.0 : 0.0); } auto const shakeangles{owner->shake_angles()}; Camera.Angle.x -= 0.5 * shakeangles.second; // hustanie kamery przod tyl @@ -1286,12 +1286,12 @@ void driver_mode::ExternalView() else { // default view setup - auto const offsetflip{(vehicle->MoverParameters->CabOccupied == 0 ? 1 : vehicle->MoverParameters->CabOccupied) * - (vehicle->MoverParameters->DirActive == 0 ? 1 : vehicle->MoverParameters->DirActive) * -1}; + auto const offsetflip{(vehicle->physics->CabOccupied == 0 ? 1 : vehicle->physics->CabOccupied) * + (vehicle->physics->DirActive == 0 ? 1 : vehicle->physics->DirActive) * -1}; - Camera.m_owneroffset = {1.5 * owner->MoverParameters->Dim.W * offsetflip, std::max(5.0, 1.25 * owner->MoverParameters->Dim.H), 0.2 * owner->MoverParameters->Dim.L * offsetflip}; + Camera.m_owneroffset = {1.5 * owner->physics->Dim.W * offsetflip, std::max(5.0, 1.25 * owner->physics->Dim.H), 0.2 * owner->physics->Dim.L * offsetflip}; - Camera.Angle.y = glm::radians(vehicle->MoverParameters->DirActive < 0 ? 0.0 : 180.0); + Camera.Angle.y = glm::radians(vehicle->physics->DirActive < 0 ? 0.0 : 180.0); } auto const shakeangles{owner->shake_angles()}; Camera.Angle.x -= 0.5 * shakeangles.second; // hustanie kamery przod tyl @@ -1314,12 +1314,12 @@ void driver_mode::ExternalView() else { // default view setup - auto const offsetflip{(vehicle->MoverParameters->CabOccupied == 0 ? 1 : vehicle->MoverParameters->CabOccupied) * - (vehicle->MoverParameters->DirActive == 0 ? 1 : vehicle->MoverParameters->DirActive)}; + auto const offsetflip{(vehicle->physics->CabOccupied == 0 ? 1 : vehicle->physics->CabOccupied) * + (vehicle->physics->DirActive == 0 ? 1 : vehicle->physics->DirActive)}; - Camera.m_owneroffset = {-0.65 * owner->MoverParameters->Dim.W * offsetflip, 0.90, 0.15 * owner->MoverParameters->Dim.L * offsetflip}; + Camera.m_owneroffset = {-0.65 * owner->physics->Dim.W * offsetflip, 0.90, 0.15 * owner->physics->Dim.L * offsetflip}; - Camera.Angle.y = glm::radians(vehicle->MoverParameters->DirActive < 0 ? 180.0 : 0.0); + Camera.Angle.y = glm::radians(vehicle->physics->DirActive < 0 ? 180.0 : 0.0); } auto const shakeangles{owner->shake_angles()}; Camera.Angle.x -= 0.5 * shakeangles.second; // hustanie kamery przod tyl @@ -1389,7 +1389,7 @@ void driver_mode::CabView() else { // patrz w strone wlasciwej kabiny - Camera.LookAt = Camera.m_owner->GetWorldPosition(Camera.m_owneroffset) + Camera.m_owner->VectorFront() * 5.0 * (double)Camera.m_owner->MoverParameters->CabOccupied; + Camera.LookAt = Camera.m_owner->GetWorldPosition(Camera.m_owneroffset) + Camera.m_owner->VectorFront() * 5.0 * (double)Camera.m_owner->physics->CabOccupied; } train->pMechOffset = Camera.m_owneroffset; } diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 53d988a29..f811d8df0 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -34,7 +34,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "widgets/vehicleparams.h" #include "utilities/U8.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #define DRIVER_HINT_CONTENT #include "application/driverhints.h" @@ -57,11 +57,11 @@ constexpr float coupler_repair_radius { 5.f }; // the broken coupler nearest to the camera, within reach: the vehicle and its end, or no vehicle std::pair broken_coupler_nearby( glm::dvec3 const &Camera ) { auto const *vehicle { std::get( simulation::Region->find_vehicle( Camera, coupler_repair_radius, false, true ) ) }; - if( vehicle == nullptr || vehicle->MoverParameters == nullptr ) { return { nullptr, VehicleEnd::front }; } + if( vehicle == nullptr || vehicle->physics == nullptr ) { return { nullptr, VehicleEnd::front }; } auto const front { glm::distance( vehicle->CouplerPosition( VehicleEnd::front ), Camera ) }; auto const rear { glm::distance( vehicle->CouplerPosition( VehicleEnd::rear ), Camera ) }; auto const nearest { front <= rear ? VehicleEnd::front : VehicleEnd::rear }; - if( std::min( front, rear ) > coupler_repair_radius || false == vehicle->MoverParameters->Couplers[ nearest ].broken ) { return { nullptr, VehicleEnd::front }; } + if( std::min( front, rear ) > coupler_repair_radius || false == vehicle->physics->Couplers[ nearest ].broken ) { return { nullptr, VehicleEnd::front }; } return { vehicle, nearest }; } @@ -82,12 +82,12 @@ drivingaid_panel::update() { if( controlled == nullptr || controlled->Mechanik == nullptr ) { return; } - auto const *mover = controlled->MoverParameters; + auto const *physics = controlled->physics; auto const *vehicledriver = controlled->Mechanik; auto const *owner = controlled->ctOwner != nullptr ? controlled->ctOwner : controlled->Mechanik; // the numbers of the throttle and brakes lines, with the controls of the cab the driver is in - auto const readout { drivingaid::compute( drivingaid::from_movers( - *mover, + auto const readout { drivingaid::compute( drivingaid::from_vehicles( + *physics, *vehicledriver->Controlling(), drivingaid::cab_controls { train->ggLocalBrake.SubModel != nullptr, @@ -98,7 +98,7 @@ drivingaid_panel::update() { if( is_expanded ) { // grade std::string gradetext; - auto const reverser { ( mover->DirActive > 0 ? 1 : -1 ) }; + auto const reverser { ( physics->DirActive > 0 ? 1 : -1 ) }; if( auto const grade { controlled->VectorFront().y * 100 * ( controlled->DirectionGet() == reverser ? 1 : -1 ) * reverser }; std::abs( grade ) >= 0.25 ) { std::snprintf( m_buffer.data(), m_buffer.size(), @@ -122,7 +122,7 @@ drivingaid_panel::update() { std::snprintf( m_buffer.data(), m_buffer.size(), STR_C(" Speed: %d km/h (limit %d km/h%s)%s"), - static_cast( std::floor( mover->Vel ) ), + static_cast( std::floor( physics->Vel ) ), speedlimit, nextspeedlimittext.c_str(), gradetext.c_str() ); @@ -134,9 +134,9 @@ drivingaid_panel::update() { STR_C("Throttle: %3d+%d %c%s"), readout.throttle_first, readout.throttle_second, - mover->SpeedCtrlUnit.IsActive ? 'T' : - mover->DirActive > 0 ? 'D' : - mover->DirActive < 0 ? 'R' : + physics->SpeedCtrlUnit.IsActive ? 'T' : + physics->DirActive > 0 ? 'D' : + physics->DirActive < 0 ? 'R' : 'N', expandedtext.c_str()); @@ -149,8 +149,8 @@ drivingaid_panel::update() { std::snprintf ( m_buffer.data(), m_buffer.size(), STR_C(" Pressure: %.2f kPa (train pipe: %.2f kPa)"), - mover->BrakePress * 100, - mover->PipePress * 100 ); + physics->BrakePress * 100, + physics->PipePress * 100 ); expandedtext = m_buffer.data(); } if( readout.ed_percent ) { @@ -167,7 +167,7 @@ drivingaid_panel::update() { STR_C("Brakes: %5.1f+%-2.0f%c%s"), readout.brake_first, readout.local_brake, - mover->SlippingWheels ? '!' : ' ', + physics->SlippingWheels ? '!' : ' ', expandedtext.c_str() ); } else { @@ -176,7 +176,7 @@ drivingaid_panel::update() { m_buffer.data(), m_buffer.size(), STR_C("Brakes: %5.1f%c%s"), readout.brake_first, - mover->SlippingWheels ? '!' : ' ', + physics->SlippingWheels ? '!' : ' ', expandedtext.c_str() ); } @@ -206,9 +206,9 @@ drivingaid_panel::update() { } } std::string textline = - mover->SecuritySystem.is_vigilance_blinking() && (train != nullptr ? train->fBlinkTimer > 0 : true) ? STR("!ALERTER! ") : " "; + physics->SecuritySystem.is_vigilance_blinking() && (train != nullptr ? train->fBlinkTimer > 0 : true) ? STR("!ALERTER! ") : " "; textline += - mover->SecuritySystem.is_cabsignal_blinking() ? STR("!SHP!") : " "; + physics->SecuritySystem.is_cabsignal_blinking() ? STR("!SHP!") : " "; text_lines.emplace_back( textline + " " + expandedtext, Global.UITextColor ); } @@ -386,11 +386,11 @@ timetable_panel::update() { if( false == owner->is_dmu() && false == owner->is_emu() ) { //odejmij lokomotywy czynne, a przynajmniej aktualną - consistmass -= owner->pVehicle->MoverParameters->TotalMass; + consistmass -= owner->pVehicle->physics->TotalMass; // subtract potential other half of a two-part vehicle - if( auto const *previous { owner->pVehicle->Prev( Coupling::permanent ) }; previous != nullptr ) { consistmass -= previous->MoverParameters->TotalMass; } + if( auto const *previous { owner->pVehicle->Prev( Coupling::permanent ) }; previous != nullptr ) { consistmass -= previous->physics->TotalMass; } auto const *next { owner->pVehicle->Next( Coupling::permanent ) }; - if( next != nullptr ) { consistmass -= next->MoverParameters->TotalMass; } + if( next != nullptr ) { consistmass -= next->physics->TotalMass; } } std::snprintf( m_buffer.data(), m_buffer.size(), @@ -452,7 +452,7 @@ timetable_panel::update() { || tableline->is_maintenance // maintenance stop, always valid || time.wHour * 60 + time.wMinute + time.wSecond * 0.0167 >= static_cast(tableline->Dh * 60) + tableline->Dm ) ) }; auto const loadchangeinprogress { ( static_cast(std::ceil(-1.0 * owner->fStopTime)) > 0 ) }; - auto const isatpassengerstop { true == owner->IsAtPassengerStop && vehicle->MoverParameters->Vel < 1.0 }; + auto const isatpassengerstop { true == owner->IsAtPassengerStop && vehicle->physics->Vel < 1.0 }; auto const traveltime { ( i < 2 ? " " : tableline->Ah >= 0 ? to_minutes_str( static_cast(CompareTime( table.TimeTable[ i - 1 ].Dh, table.TimeTable[ i - 1 ].Dm, tableline->Ah, tableline->Am )), false, 3 ) : @@ -537,8 +537,8 @@ void debug_panel::update() m_input.vehicle = false == FreeFlyModeFlag ? m_input.controlled : m_input.camera->m_owner != nullptr ? m_input.camera->m_owner : std::get(simulation::Region->find_vehicle(m_input.camera->Pos, 20, false, false)); // w trybie latania lokalizujemy wg mapy - m_input.mover = - m_input.vehicle != nullptr ? m_input.vehicle->MoverParameters : nullptr; + m_input.physics = + m_input.vehicle != nullptr ? m_input.vehicle->physics : nullptr; m_input.mechanik = m_input.vehicle != nullptr ? m_input.vehicle->Mechanik : nullptr; // header section @@ -618,7 +618,7 @@ debug_panel::render() { } // sections ImGui::Separator(); - if (true == render_section( "Vehicle", m_vehiclelines ) && DebugModeFlag && m_input.mover && false == m_input.mover->DamageFlag.Empty() && true == ImGui::Button( "Stop and repair consist" )) { + if (true == render_section( "Vehicle", m_vehiclelines ) && DebugModeFlag && m_input.physics && false == m_input.physics->DamageFlag.Empty() && true == ImGui::Button( "Stop and repair consist" )) { command_relay commandrelay; commandrelay.post(user_command::resetconsist, 0.0, 0.0, GLFW_PRESS, 0, glm::vec3(0.0f), &m_input.vehicle->name()); } @@ -788,25 +788,25 @@ void debug_panel::update_section_vehicle( std::vector &Output ) { if( m_input.vehicle == nullptr ) { return; } - if( m_input.mover == nullptr ) { return; } + if( m_input.physics == nullptr ) { return; } auto const &vehicle { *m_input.vehicle }; - auto const &mover { *m_input.mover }; + auto const &physics { *m_input.physics }; auto const isowned { /* ( vehicle.Mechanik == nullptr ) && */ vehicle.ctOwner != nullptr && vehicle.ctOwner->Vehicle() != m_input.vehicle }; - auto const isdieselenginepowered { mover.EngineType == TEngineType::DieselElectric || mover.EngineType == TEngineType::DieselEngine }; - auto const isdieselinshuntmode { mover.ShuntMode && mover.EngineType == TEngineType::DieselElectric }; + auto const isdieselenginepowered { physics.EngineType == TEngineType::DieselElectric || physics.EngineType == TEngineType::DieselEngine }; + auto const isdieselinshuntmode { physics.ShuntMode && physics.EngineType == TEngineType::DieselElectric }; std::snprintf( m_buffer.data(), m_buffer.size(), STR_C("Name: %s%s\nLoad: %.0f %s\nStatus: %s%s\nCouplers:\n front: %s\n rear: %s"), - mover.Name.c_str(), + physics.Name.c_str(), std::string( isowned ? STR(", owned by: ") + vehicle.ctOwner->OwnerName() : "" ).c_str(), - mover.LoadAmount, - mover.LoadType.name.c_str(), - mover.EngineDescription( 0 ).c_str(), + physics.LoadAmount, + physics.LoadType.name.c_str(), + physics.EngineDescription( 0 ).c_str(), // TODO: put wheel flat reporting in the enginedescription() - std::string( mover.WheelFlat > 0.01 ? " Flat: " + to_string( mover.WheelFlat, 1 ) + " mm" : "" ).c_str(), + std::string( physics.WheelFlat > 0.01 ? " Flat: " + to_string( physics.WheelFlat, 1 ) + " mm" : "" ).c_str(), update_vehicle_coupler( VehicleEnd::front ).c_str(), update_vehicle_coupler( VehicleEnd::rear ).c_str() ); @@ -816,71 +816,71 @@ debug_panel::update_section_vehicle( std::vector &Output ) { m_buffer.data(), m_buffer.size(), STR_C("Devices: %c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%s%s\nPower transfers: %.0f@%.0f%s[%.0f]%s%.0f@%.0f :: %.0f@%.0f%s[%.0f]%s%.0f@%.0f"), // devices - mover.Battery ? 'B' : '.', - mover.PantsValve.is_active ? '+' : '.', - mover.Pantographs[VehicleEnd::rear].valve.is_active ? 'O' : - mover.Pantographs[VehicleEnd::rear].valve.is_enabled ? 'o' : + physics.Battery ? 'B' : '.', + physics.PantsValve.is_active ? '+' : '.', + physics.Pantographs[VehicleEnd::rear].valve.is_active ? 'O' : + physics.Pantographs[VehicleEnd::rear].valve.is_enabled ? 'o' : '.', - mover.Pantographs[VehicleEnd::front].valve.is_active ? 'P' : - mover.Pantographs[VehicleEnd::front].valve.is_enabled ? 'p' : + physics.Pantographs[VehicleEnd::front].valve.is_active ? 'P' : + physics.Pantographs[VehicleEnd::front].valve.is_enabled ? 'p' : '.', - mover.PantPressLockActive ? '!' : - mover.PantPressSwitchActive ? '*' : + physics.PantPressLockActive ? '!' : + physics.PantPressSwitchActive ? '*' : '.', - mover.WaterPump.is_active ? 'W' : - false == mover.WaterPump.breaker ? '-' : - mover.WaterPump.is_enabled ? 'w' : + physics.WaterPump.is_active ? 'W' : + false == physics.WaterPump.breaker ? '-' : + physics.WaterPump.is_enabled ? 'w' : '.', - mover.WaterHeater.is_damaged ? '!' : - mover.WaterHeater.is_active ? 'H' : - false == mover.WaterHeater.breaker ? '-' : - mover.WaterHeater.is_enabled ? 'h' : + physics.WaterHeater.is_damaged ? '!' : + physics.WaterHeater.is_active ? 'H' : + false == physics.WaterHeater.breaker ? '-' : + physics.WaterHeater.is_enabled ? 'h' : '.', - mover.FuelPump.is_active ? 'F' : - mover.FuelPump.is_enabled ? 'f' : + physics.FuelPump.is_active ? 'F' : + physics.FuelPump.is_enabled ? 'f' : '.', - mover.OilPump.is_active ? 'O' : - mover.OilPump.is_enabled ? 'o' : + physics.OilPump.is_active ? 'O' : + physics.OilPump.is_enabled ? 'o' : '.', - mover.Mains ? 'M' : '.', - mover.FuseFlag ? '!' : '.', - mover.ConverterFlag ? 'X' : - false == mover.ConverterAllowLocal ? '-' : - mover.ConverterAllow ? 'x' : + physics.Mains ? 'M' : '.', + physics.FuseFlag ? '!' : '.', + physics.ConverterFlag ? 'X' : + false == physics.ConverterAllowLocal ? '-' : + physics.ConverterAllow ? 'x' : '.', - mover.ConvOvldFlag ? '!' : '.', - mover.CompressorFlag ? 'C' : - false == mover.CompressorAllowLocal ? '-' : - mover.CompressorAllow || (mover.CompressorStart == start_t::automatic && mover.CompressorSpeed > 0.0) ? 'c' : + physics.ConvOvldFlag ? '!' : '.', + physics.CompressorFlag ? 'C' : + false == physics.CompressorAllowLocal ? '-' : + physics.CompressorAllow || (physics.CompressorStart == start_t::automatic && physics.CompressorSpeed > 0.0) ? 'c' : '.', - mover.CompressorGovernorLock ? '!' : '.', - mover.StLinSwitchOff ? '-' : - mover.ControlPressureSwitch ? '!' : - mover.StLinFlag ? '+' : + physics.CompressorGovernorLock ? '!' : '.', + physics.StLinSwitchOff ? '-' : + physics.ControlPressureSwitch ? '!' : + physics.StLinFlag ? '+' : '.', - mover.Heating ? 'H' : - mover.HeatingAllow ? 'h' : + physics.Heating ? 'H' : + physics.HeatingAllow ? 'h' : '.', - mover.Hamulec->Releaser() ? '^' : '.', - std::string( m_input.mechanik ? STR(" R") + ( mover.Radio && mover.RadioFuse ? std::to_string( m_input.mechanik->iRadioChannel ) : "-" ) : "" ).c_str(), - std::string( isdieselenginepowered ? STR(" oil pressure: ") + to_string( mover.OilPump.pressure, 2 ) : "" ).c_str(), + physics.Hamulec->Releaser() ? '^' : '.', + std::string( m_input.mechanik ? STR(" R") + ( physics.Radio && physics.RadioFuse ? std::to_string( m_input.mechanik->iRadioChannel ) : "-" ) : "" ).c_str(), + std::string( isdieselenginepowered ? STR(" oil pressure: ") + to_string( physics.OilPump.pressure, 2 ) : "" ).c_str(), // power transfers // 3000v - mover.Couplers[ VehicleEnd::front ].power_high.voltage, - mover.Couplers[ VehicleEnd::front ].power_high.current, - std::string( mover.Couplers[ VehicleEnd::front ].power_high.is_local ? ":" : ":=" ).c_str(), - mover.EngineVoltage, - std::string( mover.Couplers[ VehicleEnd::rear ].power_high.is_local ? ":" : "=:" ).c_str(), - mover.Couplers[ VehicleEnd::rear ].power_high.voltage, - mover.Couplers[ VehicleEnd::rear ].power_high.current, + physics.Couplers[ VehicleEnd::front ].power_high.voltage, + physics.Couplers[ VehicleEnd::front ].power_high.current, + std::string( physics.Couplers[ VehicleEnd::front ].power_high.is_local ? ":" : ":=" ).c_str(), + physics.EngineVoltage, + std::string( physics.Couplers[ VehicleEnd::rear ].power_high.is_local ? ":" : "=:" ).c_str(), + physics.Couplers[ VehicleEnd::rear ].power_high.voltage, + physics.Couplers[ VehicleEnd::rear ].power_high.current, // 110v - mover.Couplers[ VehicleEnd::front ].power_110v.voltage, - mover.Couplers[ VehicleEnd::front ].power_110v.current, - std::string( mover.Couplers[ VehicleEnd::front ].power_110v.is_local ? ":" : ":=" ).c_str(), - mover.PowerCircuits[ 1 ].first, - std::string( mover.Couplers[ VehicleEnd::rear ].power_110v.is_local ? ":" : "=:" ).c_str(), - mover.Couplers[ VehicleEnd::rear ].power_110v.voltage, - mover.Couplers[ VehicleEnd::rear ].power_110v.current ); + physics.Couplers[ VehicleEnd::front ].power_110v.voltage, + physics.Couplers[ VehicleEnd::front ].power_110v.current, + std::string( physics.Couplers[ VehicleEnd::front ].power_110v.is_local ? ":" : ":=" ).c_str(), + physics.PowerCircuits[ 1 ].first, + std::string( physics.Couplers[ VehicleEnd::rear ].power_110v.is_local ? ":" : "=:" ).c_str(), + physics.Couplers[ VehicleEnd::rear ].power_110v.voltage, + physics.Couplers[ VehicleEnd::rear ].power_110v.current ); Output.emplace_back( m_buffer.data(), Global.UITextColor ); @@ -888,20 +888,20 @@ debug_panel::update_section_vehicle( std::vector &Output ) { m_buffer.data(), m_buffer.size(), STR_C("Controllers:\n master: %d(%d), secondary: %s\nEngine output: %.1f, current: %.0f\nRevolutions:\n engine: %.0f, motors: %.0f\n engine fans: %.0f, motor fans: %.0f+%.0f, cooling fans: %.0f+%.0f"), // controllers - mover.MainCtrlPos, - mover.MainCtrlActualPos, - std::string( isdieselinshuntmode ? to_string( mover.AnPos, 2 ) + STR(" (shunt mode)") : std::to_string( mover.ScndCtrlPos ) + "(" + std::to_string( mover.ScndCtrlActualPos ) + ")" ).c_str(), + physics.MainCtrlPos, + physics.MainCtrlActualPos, + std::string( isdieselinshuntmode ? to_string( physics.AnPos, 2 ) + STR(" (shunt mode)") : std::to_string( physics.ScndCtrlPos ) + "(" + std::to_string( physics.ScndCtrlActualPos ) + ")" ).c_str(), // engine - mover.EnginePower, - std::abs( mover.TrainType == train_type::emu ? mover.ShowCurrent( 0 ) : mover.Im ), + physics.EnginePower, + std::abs( physics.TrainType == train_type::emu ? physics.ShowCurrent( 0 ) : physics.Im ), // revolutions - std::abs( mover.enrot ) * 60, - std::abs( mover.nrot ) * mover.Transmision.Ratio * 60, - mover.RventRot * 60, - std::abs( mover.MotorBlowers[VehicleEnd::front].revolutions ), - std::abs( mover.MotorBlowers[VehicleEnd::rear].revolutions ), - mover.diesel.heat.rpmw, - mover.diesel.heat.rpmw2 ); + std::abs( physics.enrot ) * 60, + std::abs( physics.nrot ) * physics.Transmision.Ratio * 60, + physics.RventRot * 60, + std::abs( physics.MotorBlowers[VehicleEnd::front].revolutions ), + std::abs( physics.MotorBlowers[VehicleEnd::rear].revolutions ), + physics.diesel.heat.rpmw, + physics.diesel.heat.rpmw2 ); std::string textline { m_buffer.data() }; @@ -909,11 +909,11 @@ debug_panel::update_section_vehicle( std::vector &Output ) { std::snprintf( m_buffer.data(), m_buffer.size(), STR_C("\nTemperatures:\n engine: %.2f, oil: %.2f, water: %.2f%c%.2f"), - mover.diesel.heat.Ts, - mover.diesel.heat.To, - mover.diesel.heat.temperatura1, - mover.WaterCircuitsLink ? '-' : '|', - mover.diesel.heat.temperatura2 ); + physics.diesel.heat.Ts, + physics.diesel.heat.To, + physics.diesel.heat.temperatura1, + physics.WaterCircuitsLink ? '-' : '|', + physics.diesel.heat.temperatura2 ); textline += m_buffer.data(); } @@ -923,36 +923,36 @@ debug_panel::update_section_vehicle( std::vector &Output ) { m_buffer.data(), m_buffer.size(), STR_C("Brakes:\n train: %.2f (mode: %d, delay: %s, load flag: %d)\n independent: %.2f (%.2f), manual: %.2f, spring: %.2f\nBrake cylinder pressures:\n train: %.2f, independent: %.2f, status: 0x%.2x\nPipe pressures:\n brake: %.2f (hat: %.2f), main: %.2f, control: %.2f\nTank pressures:\n auxiliary: %.2f, main: %.2f, control: %.2f"), // brakes - mover.fBrakeCtrlPos, - mover.BrakeOpModeFlag, + physics.fBrakeCtrlPos, + physics.BrakeOpModeFlag, update_vehicle_brake().c_str(), - mover.LoadFlag, - mover.LocalBrakePosA, - mover.LocalBrakePosAEIM, - static_cast(mover.ManualBrakePos) / static_cast(ManualBrakePosNo), - mover.SpringBrake.Activate ? 1.f : 0.f, + physics.LoadFlag, + physics.LocalBrakePosA, + physics.LocalBrakePosAEIM, + static_cast(physics.ManualBrakePos) / static_cast(ManualBrakePosNo), + physics.SpringBrake.Activate ? 1.f : 0.f, // cylinders - mover.BrakePress, - mover.LocBrakePress, - mover.Hamulec->GetBrakeStatus(), + physics.BrakePress, + physics.LocBrakePress, + physics.Hamulec->GetBrakeStatus(), // pipes - mover.PipePress, - mover.BrakeCtrlPos2, - mover.ScndPipePress, - mover.CntrlPipePress, + physics.PipePress, + physics.BrakeCtrlPos2, + physics.ScndPipePress, + physics.CntrlPipePress, // tanks - mover.Hamulec->GetBRP(), - mover.Compressor, - mover.Hamulec->GetCRP() ); + physics.Hamulec->GetBRP(), + physics.Compressor, + physics.Hamulec->GetCRP() ); textline = m_buffer.data(); - if( mover.EnginePowerSource.SourceType == TPowerSource::CurrentCollector ) { + if( physics.EnginePowerSource.SourceType == TPowerSource::CurrentCollector ) { std::snprintf( m_buffer.data(), m_buffer.size(), STR_C(" pantograph: %.2f%cMT"), - mover.PantPress, - mover.bPantKurek3 ? '-' : '|' ); + physics.PantPress, + physics.bPantKurek3 ? '-' : '|' ); textline += m_buffer.data(); } @@ -962,17 +962,17 @@ debug_panel::update_section_vehicle( std::vector &Output ) { m_buffer.data(), m_buffer.size(), STR_C("Forces:\n tractive: %.1f, brake: %.1f, drag: %.2f%s\nAcceleration:\n tangential: %.2f, normal: %.2f (path radius: %s)\nVelocity: %.2f, distance traveled: %.2f\nPosition: [%.2f, %.2f, %.2f]"), // forces - mover.Ft * 0.001f * ( mover.CabOccupied ? mover.CabOccupied : vehicle.ctOwner ? vehicle.ctOwner->Controlling()->CabOccupied : 1 ) + 0.001f, - mover.Fb * 0.001f, - mover.FrictionForce() * 0.001f, - mover.SlippingWheels ? " (!)" : "", + physics.Ft * 0.001f * ( physics.CabOccupied ? physics.CabOccupied : vehicle.ctOwner ? vehicle.ctOwner->Controlling()->CabOccupied : 1 ) + 0.001f, + physics.Fb * 0.001f, + physics.FrictionForce() * 0.001f, + physics.SlippingWheels ? " (!)" : "", // acceleration - mover.AccSVBased, - mover.AccN + 0.001f, - std::string( std::abs( mover.RunningShape.R ) > 15000.0 ? "~0" : to_string( mover.RunningShape.R, 0 ) ).c_str(), + physics.AccSVBased, + physics.AccN + 0.001f, + std::string( std::abs( physics.RunningShape.R ) > 15000.0 ? "~0" : to_string( physics.RunningShape.R, 0 ) ).c_str(), // velocity vehicle.GetVelocity(), - mover.DistCounter, + physics.DistCounter, // position vehicle.GetPosition().x, vehicle.GetPosition().y, @@ -980,9 +980,9 @@ debug_panel::update_section_vehicle( std::vector &Output ) { Output.emplace_back( m_buffer.data(), Global.UITextColor ); - if( mover.EnginePowerSource.SourceType == TPowerSource::CurrentCollector ) { + if( physics.EnginePowerSource.SourceType == TPowerSource::CurrentCollector ) { std::snprintf(m_buffer.data(), m_buffer.size(), STR_C("Power use:\n drawn: %.1f kWh\n returned: %.1f kWh\n balance: %.1f kWh"), - mover.EnergyMeter.first, -mover.EnergyMeter.second, mover.EnergyMeter.first + mover.EnergyMeter.second); + physics.EnergyMeter.first, -physics.EnergyMeter.second, physics.EnergyMeter.first + physics.EnergyMeter.second); textline = m_buffer.data(); if( DebugTractionFlag ) { for( int i = 0; i < vehicle.iAnimType[ ANIM_PANTS ]; ++i ) { // pętla po wszystkich pantografach @@ -1007,11 +1007,11 @@ debug_panel::update_section_vehicle( std::vector &Output ) { if (!std::isnan(last_time)) { double dt = Timer::GetTime() - last_time; - AccN_jerk_graph.update(static_cast((mover.AccN - last_AccN) / dt)); - AccN_acc_graph.update(static_cast(mover.AccN)); + AccN_jerk_graph.update(static_cast((physics.AccN - last_AccN) / dt)); + AccN_acc_graph.update(static_cast(physics.AccN)); } - last_AccN = static_cast(mover.AccN); + last_AccN = static_cast(physics.AccN); last_time = Timer::GetTime(); } @@ -1034,14 +1034,14 @@ void debug_panel::graph_data::render() { std::string debug_panel::update_vehicle_coupler( VehicleEnd const Side ) { - // NOTE: mover and vehicle are guaranteed to be valid by the caller - auto const &mover { *m_input.mover }; + // NOTE: physics and vehicle are guaranteed to be valid by the caller + auto const &physics { *m_input.physics }; - std::string const controltype{ ( mover.Couplers[ Side ].control_type.empty() ? "[*]" : "[" + mover.Couplers[ Side ].control_type + "]" ) }; + std::string const controltype{ ( physics.Couplers[ Side ].control_type.empty() ? "[*]" : "[" + physics.Couplers[ Side ].control_type + "]" ) }; std::string couplerstatus { STR("none") }; - std::string const adapterstatus { ( mover.Couplers[ Side ].adapter_type == TCouplerType::NoCoupler ? "" : "[A]" ) }; + std::string const adapterstatus { ( physics.Couplers[ Side ].adapter_type == TCouplerType::NoCoupler ? "" : "[A]" ) }; - auto const *connected { m_input.vehicle->MoverParameters->Neighbours[ Side ].vehicle }; + auto const *connected { m_input.vehicle->physics->Neighbours[ Side ].vehicle }; if( connected == nullptr ) { @@ -1054,16 +1054,16 @@ debug_panel::update_vehicle_coupler( VehicleEnd const Side ) { controltype.c_str(), connected->name().c_str(), adapterstatus.c_str(), - mover.Couplers[ Side ].CouplingFlag, - mover.Neighbours[ Side ].distance ); + physics.Couplers[ Side ].CouplingFlag, + physics.Neighbours[ Side ].distance ); return { m_buffer.data() }; } std::string debug_panel::update_vehicle_brake() const { - // NOTE: mover is guaranteed to be valid by the caller - auto const &mover { *m_input.mover }; + // NOTE: physics is guaranteed to be valid by the caller + auto const &physics { *m_input.physics }; std::string brakedelay; @@ -1074,7 +1074,7 @@ debug_panel::update_vehicle_brake() const { { bdelay_M, "+Mg" } }; for( auto const &[delayflag, delayname] : delays ) { - if( ( mover.BrakeDelayFlag & delayflag ) == delayflag ) { + if( ( physics.BrakeDelayFlag & delayflag ) == delayflag ) { brakedelay += delayname; } } @@ -1086,17 +1086,17 @@ void debug_panel::update_section_engine( std::vector &Output ) const { if( m_input.vehicle == nullptr ) { return; } - if( m_input.mover == nullptr ) { return; } + if( m_input.physics == nullptr ) { return; } auto const &vehicle{ *m_input.vehicle }; - auto const &mover{ *m_input.mover }; + auto const &physics{ *m_input.physics }; // induction motor data - if( mover.EngineType == TEngineType::ElectricInductionMotor ) { + if( physics.EngineType == TEngineType::ElectricInductionMotor ) { Output.emplace_back( " eimc: eimv: press:", Global.UITextColor ); - auto const config{ mover.inductionMotor.ConfigListing() }; - auto const state{ mover.inductionMotor.StateListing() }; + auto const config{ physics.inductionMotor.ConfigListing() }; + auto const state{ physics.inductionMotor.StateListing() }; for( int i = 0; i <= 20; ++i ) { std::string parameters = @@ -1117,29 +1117,29 @@ debug_panel::update_section_engine( std::vector &Output ) const { Output.emplace_back( parameters, Global.UITextColor ); } - Output.emplace_back( "Inverter:\n frequency: " + to_string( mover.inductionMotor.inverterFrequency, 2 ), Global.UITextColor ); + Output.emplace_back( "Inverter:\n frequency: " + to_string( physics.inductionMotor.inverterFrequency, 2 ), Global.UITextColor ); } // diesel engine data - if( mover.EngineType == TEngineType::DieselEngine ) { + if( physics.EngineType == TEngineType::DieselEngine ) { double fuel_mean = 0.0; - if (mover.DistCounter > 0.5) { - fuel_mean = 100 * mover.diesel.fuelConsumedTotal / mover.DistCounter; + if (physics.DistCounter > 0.5) { + fuel_mean = 100 * physics.diesel.fuelConsumedTotal / physics.DistCounter; } std::string parameterstext = "param value"; std::vector< std::pair > const paramvalues { - { " rpm: ", mover.enrot * 60.0 }, - { "efill: ", mover.diesel.fill }, - { "etorq: ", mover.diesel.torque }, - { "power: ", mover.diesel.power }, - { "f_act: ", mover.diesel.fuelConsumptionActual }, - { "f_tot: ", mover.diesel.fuelConsumedTotal }, + { " rpm: ", physics.enrot * 60.0 }, + { "efill: ", physics.diesel.fill }, + { "etorq: ", physics.diesel.torque }, + { "power: ", physics.diesel.power }, + { "f_act: ", physics.diesel.fuelConsumptionActual }, + { "f_tot: ", physics.diesel.fuelConsumedTotal }, { "fmean: ", fuel_mean }, - { "creal: ", mover.diesel.clutchPressure }, - { "cdesi: ", mover.diesel.clutchState }, - { "cdelt: ", mover.diesel.clutchSlip }, - { "gears: ", mover.diesel.automaticGearShift} }; + { "creal: ", physics.diesel.clutchPressure }, + { "cdesi: ", physics.diesel.clutchState }, + { "cdelt: ", physics.diesel.clutchSlip }, + { "gears: ", physics.diesel.automaticGearShift} }; for( auto const &[parametername, parametervalue] : paramvalues ) { parameterstext += "\n" + parametername + to_string( parametervalue, 2, 9 ); } @@ -1147,15 +1147,15 @@ debug_panel::update_section_engine( std::vector &Output ) const { parameterstext = "hydro value"; std::vector< std::pair > const hydrovalues { - { "hTCnI: ", mover.torqueConverter.revolutionsIn }, - { "hTCnO: ", mover.torqueConverter.revolutionsOut }, - { "hTCTM: ", mover.torqueConverter.torqueRatio }, - { "hTCTI: ", mover.torqueConverter.torqueIn }, - { "hTCTO: ", mover.torqueConverter.torqueOut }, - { "hTCfl: ", mover.torqueConverter.fill }, - { "hRtFl: ", mover.retarder.fill } , - { " hRtn: ", mover.retarder.revolutions } , - { "hRtTq: ", mover.retarder.torque } + { "hTCnI: ", physics.torqueConverter.revolutionsIn }, + { "hTCnO: ", physics.torqueConverter.revolutionsOut }, + { "hTCTM: ", physics.torqueConverter.torqueRatio }, + { "hTCTI: ", physics.torqueConverter.torqueIn }, + { "hTCTO: ", physics.torqueConverter.torqueOut }, + { "hTCfl: ", physics.torqueConverter.fill }, + { "hRtFl: ", physics.retarder.fill } , + { " hRtn: ", physics.retarder.revolutions } , + { "hRtTq: ", physics.retarder.torque } }; for( auto const &[parametername, parametervalue] : hydrovalues ) { @@ -1168,10 +1168,10 @@ debug_panel::update_section_engine( std::vector &Output ) const { void debug_panel::update_section_ai( std::vector &Output ) const { - if( m_input.mover == nullptr ) { return; } + if( m_input.physics == nullptr ) { return; } if( m_input.mechanik == nullptr ) { return; } - auto const &mover{ *m_input.mover }; + auto const &physics{ *m_input.physics }; auto const &mechanik{ *m_input.mechanik }; // biezaca komenda dla AI @@ -1220,14 +1220,14 @@ debug_panel::update_section_ai( std::vector &Output ) const { textline = "Velocity:\n desired: " + to_string( mechanik.VelDesired, 0 ) + ", next: " + to_string( mechanik.VelNext, 0 ) - + "\n current: " + to_string( mover.Vel + 0.001f, 2 ); + + "\n current: " + to_string( physics.Vel + 0.001f, 2 ); std::vector< std::pair< double, std::string > > const restrictions{ { mechanik.VelSignalLast, "signal" }, { mechanik.VelLimitLast, "limit" }, { mechanik.VelRoad, "road" }, { mechanik.VelRestricted, "restricted" }, - { mover.RunningTrack.Velmax, "track" } }; + { physics.RunningTrack.Velmax, "track" } }; std::string restrictionstext; for( auto const &[restrictionspeed, restrictionsource] : restrictions ) { @@ -1609,16 +1609,16 @@ debug_panel::update_section_coupler( std::vector &Output ) { if( m_input.camera == nullptr ) { return; } auto const &camera { m_input.camera->Pos }; auto const *vehicle { std::get( simulation::Region->find_vehicle( camera, coupler_pick_radius, false, true ) ) }; - if( vehicle == nullptr || vehicle->MoverParameters == nullptr ) { + if( vehicle == nullptr || vehicle->physics == nullptr ) { Output.emplace_back( std::format( "No coupler within {:.0f} m of the camera", coupler_pick_radius ), Global.UITextColor ); return; } auto const nearerfront { glm::distance( vehicle->CouplerPosition( VehicleEnd::front ), camera ) <= glm::distance( vehicle->CouplerPosition( VehicleEnd::rear ), camera ) }; m_coupler = { vehicle, nearerfront ? VehicleEnd::front : VehicleEnd::rear }; - auto const &mover { *vehicle->MoverParameters }; - auto const &coupler { mover.Couplers[ m_coupler.end ] }; - auto const &neighbour { mover.Neighbours[ m_coupler.end ] }; + auto const &physics { *vehicle->physics }; + auto const &coupler { physics.Couplers[ m_coupler.end ] }; + auto const &neighbour { physics.Neighbours[ m_coupler.end ] }; auto const &state { coupler.physics_state }; Output.emplace_back( @@ -1627,9 +1627,9 @@ debug_panel::update_section_coupler( std::vector &Output ) { Output.emplace_back( std::format( "Model: {} (couplerphysics {}, vehicle {}covered), crash damage {}", - mover.coupler_physics_at( m_coupler.end ) ? "physical" : "legacy", + physics.coupler_physics_at( m_coupler.end ) ? "physical" : "legacy", coupler_physics_setting(), - mover.CouplerPhysics ? "" : "not ", + physics.CouplerPhysics ? "" : "not ", Global.crash_damage ? "on" : "off" ), Global.UITextColor ); if( neighbour.vehicle != nullptr ) { @@ -1665,10 +1665,10 @@ debug_panel::render_section_coupler() { ImGui::Checkbox( "Crash damage", &Global.crash_damage ); ImGui::Checkbox( "Apply to the other end of the pair too", &m_couplerbothends ); - auto &mover { *m_coupler.vehicle->MoverParameters }; - auto &coupler { mover.Couplers[ m_coupler.end ] }; - auto const &neighbour { mover.Neighbours[ m_coupler.end ] }; - auto *othercoupler { neighbour.vehicle != nullptr ? &neighbour.vehicle->MoverParameters->Couplers[ neighbour.vehicle_end ] : nullptr }; + auto &physics { *m_coupler.vehicle->physics }; + auto &coupler { physics.Couplers[ m_coupler.end ] }; + auto const &neighbour { physics.Neighbours[ m_coupler.end ] }; + auto *othercoupler { neighbour.vehicle != nullptr ? &neighbour.vehicle->physics->Couplers[ neighbour.vehicle_end ] : nullptr }; if( auto parameters { coupler.physics }; edit_coupler_parameters( parameters ) ) { coupler.physics = parameters; @@ -1740,7 +1740,7 @@ bool debug_panel::render_section_developer() const ImGui::TextColored(ImVec4(1.0f, 0.0f, 0.0f, 1.0f), "These settings may crash your simulator!"); if (ImGui::Button("Reload current vehicle .fiz") == true) { - m_input.vehicle->MoverParameters->reload_FIZ(); // reload fiz + m_input.vehicle->physics->reload_FIZ(); // reload fiz } ImGui::PopStyleColor(); return true; diff --git a/application/driveruipanels.h b/application/driveruipanels.h index c35ff12d6..4d685806d 100644 --- a/application/driveruipanels.h +++ b/application/driveruipanels.h @@ -80,7 +80,7 @@ private: TDynamicObject const *controlled; TCamera const *camera; TDynamicObject const *vehicle; - TMoverParameters *mover; + physics::Vehicle *physics; TController const *mechanik; }; // methods diff --git a/application/editormode.cpp b/application/editormode.cpp index 1f8b2d224..f6507f9c3 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -20,7 +20,7 @@ http://mozilla.org/MPL/2.0/. #include "application/editorgestures.h" #include "scene/scenenodegroups.h" #include "application/editoruilayer.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/DynObj.h" #ifndef _WIN32 #include @@ -7598,7 +7598,7 @@ void editor_mode::enter() auto const *vehicle = Camera.m_owner; if (vehicle) { - const int cab = vehicle->MoverParameters->CabOccupied == 0 ? 1 : vehicle->MoverParameters->CabOccupied; + const int cab = vehicle->physics->CabOccupied == 0 ? 1 : vehicle->physics->CabOccupied; const glm::dvec3 left = vehicle->VectorLeft() * (double)cab; Camera.Pos = glm::dvec3(Camera.Pos.x, vehicle->GetPosition().y, Camera.Pos.z) + left * vehicle->GetWidth() + glm::dvec3(1.25f * left.x, 1.6f, 1.25f * left.z); Camera.m_owner = nullptr; diff --git a/application/editormodejoints.cpp b/application/editormodejoints.cpp index 12c1e4357..9a3bf5bf6 100644 --- a/application/editormodejoints.cpp +++ b/application/editormodejoints.cpp @@ -490,30 +490,30 @@ bool joints_tool::joint_fix(joint_issue &Issue, std::vectoreType == tt_Normal && editor_track::can_edit_geometry(*Track, reason) && scene::Layers.editable(Track); }; - TTrack *mover{nullptr}; + TTrack *physics{nullptr}; editor_track::point_ref moved; TTrack *fixed{nullptr}; editor_track::point_ref held; if (movable(Issue.track)) { - mover = Issue.track; + physics = Issue.track; moved = Issue.point; fixed = Issue.other; held = Issue.theirs; } else if (movable(Issue.other) && (Issue.type != kind::gap || false == editor_track::is_connected(*Issue.other, Issue.theirs))) { - mover = Issue.other; + physics = Issue.other; moved = Issue.theirs; fixed = Issue.track; held = Issue.point; } - if (mover == nullptr) + if (physics == nullptr) return false; - if (std::none_of(States.begin(), States.end(), [&](auto const &Entry) { return Entry.first == mover; })) - States.emplace_back(mover, editor_track::capture(*mover)); - if (std::find(Changed.begin(), Changed.end(), mover) == Changed.end()) - Changed.push_back(mover); + if (std::none_of(States.begin(), States.end(), [&](auto const &Entry) { return Entry.first == physics; })) + States.emplace_back(physics, editor_track::capture(*physics)); + if (std::find(Changed.begin(), Changed.end(), physics) == Changed.end()) + Changed.push_back(physics); editor_track::snap_target target; target.track = fixed; target.point = held; @@ -524,14 +524,14 @@ bool joints_tool::joint_fix(joint_issue &Issue, std::vectorm_paths[moved.path]}; + auto &path{physics->m_paths[moved.path]}; auto const roll{static_cast(roll_into(*fixed, held))}; if (at_start(moved)) path.rolls[0] = -roll; diff --git a/application/editormodeselftestscene.cpp b/application/editormodeselftestscene.cpp index 2868b22db..93387ff72 100644 --- a/application/editormodeselftestscene.cpp +++ b/application/editormodeselftestscene.cpp @@ -47,7 +47,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include "application/editormodeselftest.h" -#include "physics/mover.h" +#include "physics/vehicle.h" editor_mode::selftest_result editor_mode::selftest_scene(std::string const &command, std::istringstream &words) { @@ -267,7 +267,7 @@ editor_mode::selftest_result editor_mode::selftest_scene(std::string const &comm auto const head{vehicle->HeadPosition()}; auto const front{vehicle->VectorFront()}; auto const coupler = [&](int const End) { - auto const &coupler{vehicle->MoverParameters->Couplers[End]}; + auto const &coupler{vehicle->physics->Couplers[End]}; return coupler.Connected != nullptr ? coupler.Connected->Name + "/" + std::to_string(coupler.CouplingFlag.Bits()) : std::string{"-"}; }; WriteLog(format("SELFTEST vehicle %s head %.2f %.2f front %.2f %.2f dir %d coupler0 %s coupler1 %s", vehicle->name().c_str(), head.x, head.z, front.x, front.z, vehicle->iDirection, coupler(0).c_str(), coupler(1).c_str())); diff --git a/audio/sound.cpp b/audio/sound.cpp index 6e5b8ab28..a9a249ce5 100644 --- a/audio/sound.cpp +++ b/audio/sound.cpp @@ -17,7 +17,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/DynObj.h" #include "simulation/simulation.h" #include "audio/audiorenderer_extra.h" -#include "physics/mover.h" +#include "physics/vehicle.h" // constructors sound_source::sound_source( sound_placement const Placement, float const Range ) : @@ -978,7 +978,7 @@ sound_source::update_soundproofing() { listenervehicle ? 3 : // external view 4 ) : // free roam view - listenervehicle->MoverParameters->CabOccupied ) }; // some internal view so we can be sure listener isn't a nullptr + listenervehicle->physics->CabOccupied ) }; // some internal view so we can be sure listener isn't a nullptr // location-based gain factor: std::uintptr_t soundproofingstamp = reinterpret_cast( listenervehicle ) diff --git a/directoryDescription.md b/directoryDescription.md index 51ba37f32..a26eeed9a 100644 --- a/directoryDescription.md +++ b/directoryDescription.md @@ -2,7 +2,7 @@ # File structure | Directory| Description| |--|--| -| physics/ | Vehicle physics: the mover, brakes, couplers, collisions, derailment | +| physics/ | Vehicle physics: the physics, brakes, couplers, collisions, derailment | | gl/ | OpenGL Abstraction Layer| | network/ | Multiplayer Support | launcher/ | Scenario/Vehicle Selection (built in starter)| diff --git a/input/drivermouseinput.cpp b/input/drivermouseinput.cpp index 468a51dc4..087365c77 100644 --- a/input/drivermouseinput.cpp +++ b/input/drivermouseinput.cpp @@ -21,7 +21,7 @@ http://mozilla.org/MPL/2.0/. #include "application/uilayer.h" #include "utilities/Logs.h" #include "utilities/utilities.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/DynObj.h" auto const EU07_CONTROLLER_MOUSESLIDERSIZE{ 0.6 }; @@ -34,7 +34,7 @@ mouse_slider::bind( user_command const &Command ) { m_universaldrag.reset(); auto const *train { simulation::Train }; - TMoverParameters const *vehicle { nullptr }; + physics::Vehicle const *vehicle { nullptr }; switch( m_command ) { using enum user_command; case jointcontrollerset: diff --git a/input/messaging.cpp b/input/messaging.cpp index 0f1530199..4c17eedf1 100644 --- a/input/messaging.cpp +++ b/input/messaging.cpp @@ -19,7 +19,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Driver.h" #include "world/mtable.h" #include "utilities/Logs.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #ifdef _WIN32 extern "C" @@ -188,7 +188,7 @@ OnCommandGet(multiplayer::DaneRozkaz const *pRozkaz) d->Damage( pRozkaz->cString[ 0 ] ); d = d->Prev(); // w drugą stronę też } - WyslijUszkodzenia( lookup->asName, static_cast(lookup->MoverParameters->EngDmgFlag) ); // zwrot informacji o pojeździe + WyslijUszkodzenia( lookup->asName, static_cast(lookup->physics->EngDmgFlag) ); // zwrot informacji o pojeździe } break; default: @@ -273,40 +273,40 @@ WyslijNamiary([[maybe_unused]] TDynamicObject const *Vehicle) size_t j = Vehicle->asName.length(); r.iPar[0] = i; // ilość danych liczbowych r.fPar[1] = Global.fTimeAngleDeg / 360.0; // aktualny czas (1.0=doba) - r.fPar[2] = Vehicle->MoverParameters->Loc.X; // pozycja X - r.fPar[3] = Vehicle->MoverParameters->Loc.Y; // pozycja Y - r.fPar[4] = Vehicle->MoverParameters->Loc.Z; // pozycja Z - r.fPar[5] = Vehicle->MoverParameters->V; // prędkość ruchu X - r.fPar[6] = Vehicle->MoverParameters->nrot * M_PI * - Vehicle->MoverParameters->WheelDiameter; // prędkość obrotowa kóŁ + r.fPar[2] = Vehicle->physics->Loc.X; // pozycja X + r.fPar[3] = Vehicle->physics->Loc.Y; // pozycja Y + r.fPar[4] = Vehicle->physics->Loc.Z; // pozycja Z + r.fPar[5] = Vehicle->physics->V; // prędkość ruchu X + r.fPar[6] = Vehicle->physics->nrot * M_PI * + Vehicle->physics->WheelDiameter; // prędkość obrotowa kóŁ r.fPar[7] = 0; // prędkość ruchu Z - r.fPar[8] = Vehicle->MoverParameters->AccS; // przyspieszenie X - r.fPar[9] = Vehicle->MoverParameters->AccN; // przyspieszenie Y //na razie nie - r.fPar[10] = Vehicle->MoverParameters->AccVert; // przyspieszenie Z - r.fPar[11] = Vehicle->MoverParameters->DistCounter; // przejechana odległość w km - r.fPar[12] = Vehicle->MoverParameters->PipePress; // ciśnienie w PG - r.fPar[13] = Vehicle->MoverParameters->ScndPipePress; // ciśnienie w PZ - r.fPar[14] = Vehicle->MoverParameters->BrakePress; // ciśnienie w CH - r.fPar[15] = Vehicle->MoverParameters->Compressor; // ciśnienie w ZG - r.fPar[16] = Vehicle->MoverParameters->Itot; // Prąd całkowity - r.iPar[17] = Vehicle->MoverParameters->MainCtrlPos; // Pozycja NJ - r.iPar[18] = Vehicle->MoverParameters->ScndCtrlPos; // Pozycja NB - r.iPar[19] = Vehicle->MoverParameters->MainCtrlActualPos; // Pozycja jezdna - r.iPar[20] = Vehicle->MoverParameters->ScndCtrlActualPos; // Pozycja bocznikowania - r.iPar[21] = Vehicle->MoverParameters->ScndCtrlActualPos; // Pozycja bocznikowania - r.iPar[22] = Vehicle->MoverParameters->ResistorsFlag * 1 - + Vehicle->MoverParameters->ConverterFlag * 2 - + Vehicle->MoverParameters->CompressorFlag * 4 - + Vehicle->MoverParameters->Mains * 8 + r.fPar[8] = Vehicle->physics->AccS; // przyspieszenie X + r.fPar[9] = Vehicle->physics->AccN; // przyspieszenie Y //na razie nie + r.fPar[10] = Vehicle->physics->AccVert; // przyspieszenie Z + r.fPar[11] = Vehicle->physics->DistCounter; // przejechana odległość w km + r.fPar[12] = Vehicle->physics->PipePress; // ciśnienie w PG + r.fPar[13] = Vehicle->physics->ScndPipePress; // ciśnienie w PZ + r.fPar[14] = Vehicle->physics->BrakePress; // ciśnienie w CH + r.fPar[15] = Vehicle->physics->Compressor; // ciśnienie w ZG + r.fPar[16] = Vehicle->physics->Itot; // Prąd całkowity + r.iPar[17] = Vehicle->physics->MainCtrlPos; // Pozycja NJ + r.iPar[18] = Vehicle->physics->ScndCtrlPos; // Pozycja NB + r.iPar[19] = Vehicle->physics->MainCtrlActualPos; // Pozycja jezdna + r.iPar[20] = Vehicle->physics->ScndCtrlActualPos; // Pozycja bocznikowania + r.iPar[21] = Vehicle->physics->ScndCtrlActualPos; // Pozycja bocznikowania + r.iPar[22] = Vehicle->physics->ResistorsFlag * 1 + + Vehicle->physics->ConverterFlag * 2 + + Vehicle->physics->CompressorFlag * 4 + + Vehicle->physics->Mains * 8 #ifdef EU07_USEOLDDOORCODE - + Vehicle->MoverParameters->DoorLeftOpened * 16 - + Vehicle->MoverParameters->DoorRightOpened * 32 + + Vehicle->physics->DoorLeftOpened * 16 + + Vehicle->physics->DoorRightOpened * 32 #else - + ( false == Vehicle->MoverParameters->Doors.instances[VehicleSide::left].is_closed ) * 16 - + ( false == Vehicle->MoverParameters->Doors.instances[VehicleSide::right].is_closed ) * 32 + + ( false == Vehicle->physics->Doors.instances[VehicleSide::left].is_closed ) * 16 + + ( false == Vehicle->physics->Doors.instances[VehicleSide::right].is_closed ) * 32 #endif - + Vehicle->MoverParameters->FuseFlag * 64 - + Vehicle->MoverParameters->DepartureSignal * 128; + + Vehicle->physics->FuseFlag * 64 + + Vehicle->physics->DepartureSignal * 128; // WriteLog("Zapisalem stare"); // WriteLog("Mam patykow "+IntToStr(t->DynamicObject->iAnimType[ANIM_PANTS])); for (int p = 0; p < 4; p++) @@ -326,10 +326,10 @@ WyslijNamiary([[maybe_unused]] TDynamicObject const *Vehicle) // WriteLog("Zapisalem pantografy"); for (int p = 0; p < 3; p++) r.fPar[27 + p] = - Vehicle->MoverParameters->ShowCurrent(p + 1); // amperomierze kolejnych grup + Vehicle->physics->ShowCurrent(p + 1); // amperomierze kolejnych grup // WriteLog("zapisalem prady"); - r.iPar[30] = Vehicle->MoverParameters->WarningSignal; // trabienie - r.fPar[31] = Vehicle->MoverParameters->PantographVoltage; // napiecie WN + r.iPar[30] = Vehicle->physics->WarningSignal; // trabienie + r.fPar[31] = Vehicle->physics->PantographVoltage; // napiecie WN // WriteLog("Parametry gotowe"); i <<= 2; // ilość bajtów r.cString[i] = char(j); // na końcu nazwa, żeby jakoś zidentyfikować diff --git a/physics/brakes.cpp b/physics/brakes.cpp index 65d38663f..7cd66b1d5 100644 --- a/physics/brakes.cpp +++ b/physics/brakes.cpp @@ -15,7 +15,7 @@ Copyright (C) 2007-2014 Maciej Cierniak #include "stdafx.h" #include "physics/brakes.h" #include -#include "physics/mover.h" +#include "physics/vehicle.h" #include "utilities/utilities.h" //---FUNKCJE OGOLNE--- diff --git a/physics/brakes.h b/physics/brakes.h index dd07f0630..4fb4b7f9f 100644 --- a/physics/brakes.h +++ b/physics/brakes.h @@ -25,7 +25,7 @@ ESt3, ESt3AL2, ESt4R, LSt, FV4a, FD1, EP2, prosty westinghouse duzo wersji żeliwa KE Tarcze od 152A -Magnetyki (implementacja w mover.pas) +Magnetyki (implementacja w physics.pas) Matrosow 394 H14K1 (zasadniczy), H1405 (pomocniczy), St113 (ep) Knorr/West EP - żeby był diff --git a/physics/collision.h b/physics/collision.h index 62d16669e..9b9258169 100644 --- a/physics/collision.h +++ b/physics/collision.h @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "physics/derailment.h" // what a collision of two vehicles does to them past their buffers (physics.collisions new in eu07.ini, see -// TMoverParameters::CollisionDetect()), as plain functions of the vehicles and the hit: +// physics::Vehicle::CollisionDetect()), as plain functions of the vehicles and the hit: // // crush: once the buffers of the pair are pressed all the way, the underframes carry the rest of the hit, up to the // force the weaker end gives at. only the energy the hit brings past what the buffers of EN 15551 of both ends take diff --git a/physics/components/body.cpp b/physics/components/body.cpp index 698f19d98..f3da81add 100644 --- a/physics/components/body.cpp +++ b/physics/components/body.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. // the vehicle as a body: construction, the forces on it, its movement along the track, adhesion and sand #include "stdafx.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/DynObj.h" #include "physics/oerlikonest.h" #include "utilities/Globals.h" @@ -43,7 +43,7 @@ namespace // friction of its weight, and the forces of the vehicles coupled to it act on it as on any other: the train behind it // pushes it on, and it holds the train back. alone it stops as the legacy model has it. the legacy model stops it // whatever pushes it, and the train behind it stopped at once against it, in a hit no train had -bool legacy_derailed_slides(TMoverParameters const &Vehicle) +bool legacy_derailed_slides(physics::Vehicle const &Vehicle) { return Global.collisions == global_settings::collision_model::physical && TestFlag(Vehicle.CategoryFlag, 1) && Vehicle.DamageFlag.HasAll(VehicleDamage::derailed) && Vehicle.Derailed == derailment::outcome::none; @@ -67,7 +67,7 @@ int DirF(VehicleEnd CouplerN) // ************************************************************************************************* // główny konstruktor // ************************************************************************************************* -TMoverParameters::TMoverParameters(double VelInitial, std::string const &TypeNameInit, std::string const &NameInit, int Cab) : TypeName(TypeNameInit), Name(NameInit), CabOccupied(Cab) +physics::Vehicle::Vehicle(double VelInitial, std::string const &TypeNameInit, std::string const &NameInit, int Cab) : TypeName(TypeNameInit), Name(NameInit), CabOccupied(Cab) { WriteLog("------------------------------------------------------"); WriteLog("init default physic values for " + NameInit + ", [" + TypeNameInit + "]"); @@ -166,10 +166,10 @@ TMoverParameters::TMoverParameters(double VelInitial, std::string const &TypeNam RunningTraction.TractionResistivity = 1.0; }; -void TMoverParameters::change_train_velocity(double const Change) +void physics::Vehicle::change_train_velocity(double const Change) { // the vehicles coupled to this one in a line, each with the direction of its axis to the axis of this one - std::vector> train{{this, 1}}; + std::vector> train{{this, 1}}; for (std::size_t i = 0; i < train.size(); ++i) { auto const [vehicle, direction] = train[i]; @@ -191,7 +191,7 @@ void TMoverParameters::change_train_velocity(double const Change) // ************************************************************************************************* // Oblicza przemieszczenie taboru // ************************************************************************************************* -double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShape &Shape, TTrackParam const &Track, TTractionParam const &ElectricTraction, TLocation const &NewLoc, TRotation const &NewRot) +double physics::Vehicle::ComputeMovement(double dt, double dt1, const TTrackShape &Shape, TTrackParam const &Track, TTractionParam const &ElectricTraction, TLocation const &NewLoc, TRotation const &NewRot) { if (!DamageFlag.HasAll(VehicleDamage::derailed)) @@ -335,9 +335,9 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap // Oblicza przemieszczenie taboru - uproszczona wersja // ************************************************************************************************* -double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Shape*/, TTrackParam & /*Track*/, TLocation const &NewLoc, TRotation const &NewRot) +double physics::Vehicle::FastComputeMovement(double dt, const TTrackShape & /*Shape*/, TTrackParam & /*Track*/, TLocation const &NewLoc, TRotation const &NewRot) { - // T_MoverParameters::FastComputeMovement(dt, Shape, Track, NewLoc, NewRot); + // physics::Vehicle::FastComputeMovement(dt, Shape, Track, NewLoc, NewRot); Loc = NewLoc; Rot = NewRot; @@ -406,7 +406,7 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Sh }; // updates shared between 'fast' and regular movement computation methods -void TMoverParameters::compute_movement_(double const Deltatime) +void physics::Vehicle::compute_movement_(double const Deltatime) { // sprawdzanie i ewentualnie wykonywanie->kasowanie poleceń @@ -534,7 +534,7 @@ void TMoverParameters::compute_movement_(double const Deltatime) // Q: 20160710 // Siła napędzająca drezynę po naciśnięciu wajhy // ************************************************************************************************* -bool TMoverParameters::AddPulseForce(int Multipler) +bool physics::Vehicle::AddPulseForce(int Multipler) { bool APF; if (EngineType == TEngineType::WheelsDriven && EnginePowerSource.SourceType == TPowerSource::InternalSource && EnginePowerSource.PowerType == TPowerType::BioPower) @@ -561,7 +561,7 @@ bool TMoverParameters::AddPulseForce(int Multipler) // yB: 20190909 // sypanie piasku reczne // ************************************************************************************************* -bool TMoverParameters::SandboxManual(bool const State, range_t const Notify) +bool physics::Vehicle::SandboxManual(bool const State, range_t const Notify) { bool result{false}; @@ -593,7 +593,7 @@ bool TMoverParameters::SandboxManual(bool const State, range_t const Notify) // yB: 20190909 // sypanie piasku automatyczne // ************************************************************************************************* -bool TMoverParameters::SandboxAuto(bool const State, range_t const Notify) +bool physics::Vehicle::SandboxAuto(bool const State, range_t const Notify) { bool result{false}; if (bool NewState = State && SandDoseAutoAllow; SandDoseAuto != NewState) @@ -624,7 +624,7 @@ bool TMoverParameters::SandboxAuto(bool const State, range_t const Notify) // Q: 20160713 // sypanie piasku // ************************************************************************************************* -bool TMoverParameters::Sandbox(bool const State, range_t const Notify) +bool physics::Vehicle::Sandbox(bool const State, range_t const Notify) { bool result{false}; @@ -671,7 +671,7 @@ bool TMoverParameters::Sandbox(bool const State, range_t const Notify) // yB: 20190909 // włączenie / wyłączenie automatycznej piasecznicy // ************************************************************************************************* -bool TMoverParameters::SandboxAutoAllow(bool State) +bool physics::Vehicle::SandboxAutoAllow(bool State) { // SendCtrlToNext(VehicleCommand::sandboxAutoAllow, int(State), CabActive, Coupling::control); @@ -688,7 +688,7 @@ bool TMoverParameters::SandboxAutoAllow(bool State) // Q: 20160713 // Obliczenie stałych potrzebnych do dalszych obliczeń // ************************************************************************************************* -void TMoverParameters::ComputeConstans(void) +void physics::Vehicle::ComputeConstans(void) { double BearingF; double RollF; @@ -750,7 +750,7 @@ void TMoverParameters::ComputeConstans(void) // Q: 20160713 // Oblicza masę ładunku // ************************************************************************************************* -void TMoverParameters::ComputeMass() +void physics::Vehicle::ComputeMass() { // Ra: na razie tak, ale nie wszędzie masy wirujące się wliczają TotalMass = Mass + Mred; @@ -781,7 +781,7 @@ void TMoverParameters::ComputeMass() // Obliczanie wypadkowej siły z wszystkich działających sił // ************************************************************************************************* // TBD, TODO: move some of the calculations out of the method, they're relevant to more than just force calculations -void TMoverParameters::ComputeTotalForce(double dt) +void physics::Vehicle::ComputeTotalForce(double dt) { Vel = std::abs(V) * 3.6; // prędkość w km/h @@ -798,10 +798,10 @@ void TMoverParameters::ComputeTotalForce(double dt) auto const vehicleisactive{CabActive != 0 || Vel > 0.0001 || accelerating() || LastSwitchingTime < 5 || is_multiple_unit()}; auto const movingvehicleahead{Neighbours[VehicleEnd::front].vehicle != nullptr && - (Neighbours[VehicleEnd::front].vehicle->MoverParameters->Vel > 0.0001 || Neighbours[VehicleEnd::front].vehicle->MoverParameters->accelerating())}; + (Neighbours[VehicleEnd::front].vehicle->physics->Vel > 0.0001 || Neighbours[VehicleEnd::front].vehicle->physics->accelerating())}; auto const movingvehiclebehind{Neighbours[VehicleEnd::rear].vehicle != nullptr && - (Neighbours[VehicleEnd::rear].vehicle->MoverParameters->Vel > 0.0001 || Neighbours[VehicleEnd::rear].vehicle->MoverParameters->accelerating())}; + (Neighbours[VehicleEnd::rear].vehicle->physics->Vel > 0.0001 || Neighbours[VehicleEnd::rear].vehicle->physics->accelerating())}; auto const calculatephysics{vehicleisactive || movingvehicleahead || movingvehiclebehind}; @@ -924,7 +924,7 @@ void TMoverParameters::ComputeTotalForce(double dt) if (Neighbours[end].vehicle != nullptr) { // the velocities before the step, the forces of all the vehicles come before their movement - Couplers[end].closing = -CouplerVelocityDifference(end, *Neighbours[end].vehicle->MoverParameters, Neighbours[end].FacingEnd()) * DirF(end); + Couplers[end].closing = -CouplerVelocityDifference(end, *Neighbours[end].vehicle->physics, Neighbours[end].FacingEnd()) * DirF(end); Couplers[end].CForce = CouplerForce(end, dt); FTrain += Couplers[end].CForce; // what the buffers of the pair take in, for the budget of the crush (physics.collisions new and monitor) @@ -946,7 +946,7 @@ void TMoverParameters::ComputeTotalForce(double dt) FTotal = FTrain - Sign(V) * FStand; } -double TMoverParameters::BrakeForceR(double ratio, double velocity) const +double physics::Vehicle::BrakeForceR(double ratio, double velocity) const { double press = 0; ratio = Hamulec->GetBrakeRatio(ratio); @@ -976,7 +976,7 @@ double TMoverParameters::BrakeForceR(double ratio, double velocity) const return BrakeForceP(press * ratio, velocity); } -double TMoverParameters::BrakeForceP(double press, double velocity) const +double physics::Vehicle::BrakeForceP(double press, double velocity) const { double BFP = 0; double K = ((press * P2FTrans - BrakeCylSpring) * BrakeCylMult[0] - BrakeSlckAdj) * BrakeRigEff; @@ -989,7 +989,7 @@ double TMoverParameters::BrakeForceP(double press, double velocity) const // Q: 20160713 // oblicza siłę na styku koła i szyny // ************************************************************************************************* -double TMoverParameters::BrakeForce(TTrackParam const & /*Track*/) +double physics::Vehicle::BrakeForce(TTrackParam const & /*Track*/) { double K{0}; @@ -1062,7 +1062,7 @@ double TMoverParameters::BrakeForce(TTrackParam const & /*Track*/) // Q: 20160713 // Obliczanie siły tarcia // ************************************************************************************************* -double TMoverParameters::FrictionForce() const +double physics::Vehicle::FrictionForce() const { double FF = 0; // ABu 240205: chyba juz ekstremalnie zoptymalizowana funkcja liczaca sily tarcia @@ -1077,7 +1077,7 @@ double TMoverParameters::FrictionForce() const // Q: 20160713 // Oblicza przyczepność // ************************************************************************************************* -double TMoverParameters::Adhesive(double staticfriction) const +double physics::Vehicle::Adhesive(double staticfriction) const { double adhesion = 0.0; const double adh_factor = 0.25; // współczynnik określający, jak bardzo spada tarcie przy poślizgu @@ -1132,7 +1132,7 @@ double TMoverParameters::Adhesive(double staticfriction) const // Q: 20160713 // Obliczenie predkości obrotowej kół??? // ************************************************************************************************* -double TMoverParameters::ComputeRotatingWheel(double WForce, double dt, double n) const +double physics::Vehicle::ComputeRotatingWheel(double WForce, double dt, double n) const { double newn = 0; double eps = 0; @@ -1152,7 +1152,7 @@ double TMoverParameters::ComputeRotatingWheel(double WForce, double dt, double n // Q: 20160713 // Przesuwa pojazd o podaną wartość w bok względem toru (dla samochodów) // ************************************************************************************************* -bool TMoverParameters::ChangeOffsetH(double DeltaOffset) +bool physics::Vehicle::ChangeOffsetH(double DeltaOffset) { bool COH = false; if (TestFlag(CategoryFlag, 2) && TestFlag(RunningTrack.CategoryFlag, 2)) @@ -1174,7 +1174,7 @@ bool TMoverParameters::ChangeOffsetH(double DeltaOffset) // Q: 20160713 // Testuje zmienną (narazie tylko 0) i na podstawie uszkodzenia zwraca informację tekstową // ************************************************************************************************* -std::string TMoverParameters::EngineDescription(int what) const +std::string physics::Vehicle::EngineDescription(int what) const { std::string outstr{"OK"}; if (what == 0) @@ -1238,7 +1238,7 @@ std::string TMoverParameters::EngineDescription(int what) const // ************************************************************************************************* // whether the vehicle accelerates, for the test which turns the physics off in vehicles standing still // ************************************************************************************************* -bool TMoverParameters::accelerating() const +bool physics::Vehicle::accelerating() const { if (std::abs(AccS) <= 0.0001) return false; @@ -1251,7 +1251,7 @@ bool TMoverParameters::accelerating() const return false == held; } -void TMoverParameters::wake_for_brake() +void physics::Vehicle::wake_for_brake() { if (Global.physics_sleepheld) { @@ -1268,7 +1268,7 @@ void TMoverParameters::wake_for_brake() // which the cylinder gives no force: a release ends with the vehicle asleep and no force left. a cylinder holding its // pressure, or settling within that, leaves the vehicle asleep // ************************************************************************************************* -bool TMoverParameters::brakes_changed_asleep() const +bool physics::Vehicle::brakes_changed_asleep() const { if (PhysicActivation) return false; @@ -1280,7 +1280,7 @@ bool TMoverParameters::brakes_changed_asleep() const // ************************************************************************************************* // Kasowanie zmiennych pracy fizyki // ************************************************************************************************* -bool TMoverParameters::switch_physics(bool const State, wake_cause const Cause) // DO PRZETLUMACZENIA NA KONCU +bool physics::Vehicle::switch_physics(bool const State, wake_cause const Cause) // DO PRZETLUMACZENIA NA KONCU { if (PhysicActivation == State) { diff --git a/physics/components/cab.cpp b/physics/components/cab.cpp index 2accee006..0ac0324ce 100644 --- a/physics/components/cab.cpp +++ b/physics/components/cab.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. // the cab: activation, the direction, the horns, the pullee mode #include "stdafx.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/DynObj.h" #include "physics/oerlikonest.h" #include "utilities/Globals.h" @@ -30,7 +30,7 @@ http://mozilla.org/MPL/2.0/. #include "physics/components/internal.h" -bool TMoverParameters::DirectionForward() +bool physics::Vehicle::DirectionForward() { if (false == EIMDirectionChangeAllow()) { @@ -49,7 +49,7 @@ bool TMoverParameters::DirectionForward() return false; }; -bool TMoverParameters::ChangeCab(int direction) +bool physics::Vehicle::ChangeCab(int direction) { // zmiana kabiny i resetowanie ustawien if (std::abs(CabOccupied + direction) < 2) { @@ -69,7 +69,7 @@ bool TMoverParameters::ChangeCab(int direction) return false; }; -int TMoverParameters::SoundingHorns(int const Signal) const +int physics::Vehicle::SoundingHorns(int const Signal) const { auto const supplied{[this](horn_supply const Supply) { if (Supply == horn_supply::electric) @@ -101,7 +101,7 @@ int TMoverParameters::SoundingHorns(int const Signal) const // Q: 20160710 // załączenie rozrządu // ************************************************************************************************* -bool TMoverParameters::CabActivisation(bool const Enforce) +bool physics::Vehicle::CabActivisation(bool const Enforce) { bool OK = false; @@ -127,7 +127,7 @@ bool TMoverParameters::CabActivisation(bool const Enforce) return OK; } -bool TMoverParameters::CabActivisationAuto(bool const Enforce) +bool physics::Vehicle::CabActivisationAuto(bool const Enforce) { bool OK = AutomaticCabActivation ? CabActivisation(Enforce) : false; return OK; @@ -137,7 +137,7 @@ bool TMoverParameters::CabActivisationAuto(bool const Enforce) // Q: 20160710 // wyłączenie rozrządu // ************************************************************************************************* -bool TMoverParameters::CabDeactivisation(bool const Enforce) +bool physics::Vehicle::CabDeactivisation(bool const Enforce) { bool OK = false; @@ -174,7 +174,7 @@ bool TMoverParameters::CabDeactivisation(bool const Enforce) return OK; } -bool TMoverParameters::CabDeactivisationAuto(bool const Enforce) +bool physics::Vehicle::CabDeactivisationAuto(bool const Enforce) { bool OK = AutomaticCabActivation ? CabDeactivisation(Enforce) : false; return OK; @@ -192,7 +192,7 @@ bool TMoverParameters::CabDeactivisationAuto(bool const Enforce) // entering it also lets go of the hand brake and of the spring brake switch. // returns whether the mode changed; a vehicle driven from can't enter it // ************************************************************************************************* -bool TMoverParameters::PulleeModeSwitch(bool const State) +bool physics::Vehicle::PulleeModeSwitch(bool const State) { if (PulleeMode == State || (State && CabActive != 0)) { @@ -213,7 +213,7 @@ bool TMoverParameters::PulleeModeSwitch(bool const State) // Q: 20160710 // kierunek do tyłu // ************************************************************************************************* -bool TMoverParameters::DirectionBackward(void) +bool physics::Vehicle::DirectionBackward(void) { if (false == EIMDirectionChangeAllow()) { @@ -238,7 +238,7 @@ bool TMoverParameters::DirectionBackward(void) return false; } -bool TMoverParameters::EIMDirectionChangeAllow(void) const +bool physics::Vehicle::EIMDirectionChangeAllow(void) const { bool OK = false; /* diff --git a/physics/components/collisions.cpp b/physics/components/collisions.cpp index db73aa29a..eeb711535 100644 --- a/physics/components/collisions.cpp +++ b/physics/components/collisions.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. // collisions of the ends, their crush and repair, derailment and putting back on the rails #include "stdafx.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/DynObj.h" #include "physics/oerlikonest.h" #include "utilities/Globals.h" @@ -55,7 +55,7 @@ namespace { // a derailed vehicle tears its brake hoses: the brake pipe vents and the rest of the train brakes in emergency -void tear_brake_hoses(TMoverParameters &Vehicle) +void tear_brake_hoses(physics::Vehicle &Vehicle) { if (std::any_of(std::begin(Vehicle.Couplers), std::end(Vehicle.Couplers), [](auto const &Coupler) { return Coupler.CouplingFlag.HasAll(Coupling::brakeHose); })) { @@ -69,7 +69,7 @@ void tear_brake_hoses(TMoverParameters &Vehicle) // Q: 20160716 // Wykrywanie kolizji // ************************************************************************************************* -void TMoverParameters::CollisionDetect(VehicleEnd const End, double const dt) +void physics::Vehicle::CollisionDetect(VehicleEnd const End, double const dt) { if (Neighbours[End].vehicle == nullptr) { @@ -77,7 +77,7 @@ void TMoverParameters::CollisionDetect(VehicleEnd const End, double const dt) } // shouldn't normally happen but, eh auto const &thiscoupler{Couplers[End]}; - auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; + auto *othervehicle{Neighbours[End].vehicle->physics}; auto const otherend{Neighbours[End].FacingEnd()}; auto const &othercoupler{othervehicle->Couplers[otherend]}; @@ -170,7 +170,7 @@ void TMoverParameters::CollisionDetect(VehicleEnd const End, double const dt) // derailed the legacy way a vehicle is a wall, off the rails by the new criteria it slides on and takes the hit. with // the crush, the vehicles coupled to the wall push it on (crush_hit()) auto const coupled{thiscoupler.CouplingFlag != Coupling::none}; - auto const wall = [crushing, coupled](TMoverParameters const &Vehicle) { + auto const wall = [crushing, coupled](physics::Vehicle const &Vehicle) { return Vehicle.DamageFlag.HasAll(VehicleDamage::derailed) && (false == crushing || (Vehicle.Derailed == derailment::outcome::none && false == coupled)); }; if (false == wall(*this)) @@ -188,7 +188,7 @@ void TMoverParameters::CollisionDetect(VehicleEnd const End, double const dt) } } -void TMoverParameters::damage_coupler(VehicleEnd const End) +void physics::Vehicle::damage_coupler(VehicleEnd const End) { auto &thiscoupler{Couplers[End]}; @@ -232,7 +232,7 @@ void TMoverParameters::damage_coupler(VehicleEnd const End) // ************************************************************************************************* // physics.collisions new: the collisions past the buffers, see collision.h // ************************************************************************************************* -collision::vehicle_kind TMoverParameters::collision_kind() const +collision::vehicle_kind physics::Vehicle::collision_kind() const { auto const powered{EngineType != TEngineType::None && EngineType != TEngineType::Dumb}; auto const unit{is_multiple_unit()}; @@ -241,18 +241,18 @@ collision::vehicle_kind TMoverParameters::collision_kind() const return collision::kind_of(powered, unit || passengers || (false == powered && HeatingPower > 0.0), false); } -collision::crush_curve TMoverParameters::crush_curve_at(VehicleEnd const End) const +collision::crush_curve physics::Vehicle::crush_curve_at(VehicleEnd const End) const { return collision::crush_of(Couplers[End].collision, collision_kind()); } -double TMoverParameters::buffer_height_at(VehicleEnd const End) const +double physics::Vehicle::buffer_height_at(VehicleEnd const End) const { auto const loadshare{MaxLoad > 0.f ? LoadAmount / MaxLoad : 0.0}; return collision::buffer_height(Couplers[End].collision, collision_kind(), loadshare); } -void TMoverParameters::derail_in_collision(DerailReason const Reason, std::string const &Why) +void physics::Vehicle::derail_in_collision(DerailReason const Reason, std::string const &Why) { if (false == DamageFlag.Set(VehicleDamage::derailed)) { @@ -330,10 +330,10 @@ void record_hit(TCoupling &Coupler, double const Force, double const Duration) } // namespace -bool TMoverParameters::crush_hit(VehicleEnd const End, double const dt) +bool physics::Vehicle::crush_hit(VehicleEnd const End, double const dt) { auto &thiscoupler{Couplers[End]}; - auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; + auto *othervehicle{Neighbours[End].vehicle->physics}; auto const otherend{Neighbours[End].FacingEnd()}; auto &othercoupler{othervehicle->Couplers[otherend]}; @@ -491,7 +491,7 @@ bool TMoverParameters::crush_hit(VehicleEnd const End, double const dt) secondcurve.force(othercoupler.crush) / 1000.0, hit.force / 1000.0, springs / 1000.0, input.start_velocity * 3.6, kinetic / 1000.0, thiscoupler.contact.absorbed() / 1000.0, capacity / 1000.0, thiscoupler.contact.crush_work() / 1000.0); }; - auto const crushed = [&](TMoverParameters const &Vehicle, VehicleEnd const crushedEnd, double const Before, double const After) { + auto const crushed = [&](physics::Vehicle const &Vehicle, VehicleEnd const crushedEnd, double const Before, double const After) { if (Before < collision::crush_mark && After >= collision::crush_mark) { ErrorLog(std::format("Bad driving: {} and {} collided at {:.0f} km/h, the {} end of {} crushed ({})", Name, othervehicle->Name, closing * 3.6, end_name(crushedEnd), Vehicle.Name, pair())); @@ -530,7 +530,7 @@ bool TMoverParameters::crush_hit(VehicleEnd const End, double const dt) // the end crushed deep enough lets one vehicle climb onto the other one auto const climbing{climbing_of(thiscoupler.crush, othercoupler.crush)}; auto const climbed{collision::override_of(climbing)}; - auto const why = [&](TMoverParameters const &Climber, TMoverParameters const &Other) { + auto const why = [&](physics::Vehicle const &Climber, physics::Vehicle const &Other) { return std::format("{} rode up onto {} at {:.0f} km/h, the ends crushed by {:.2f} m, buffers at {:.0f} / {:.0f} mm, anticlimbers {} ({})", Climber.Name, Other.Name, closing * 3.6, thiscoupler.crush + othercoupler.crush, climbing.height1 * 1000.0, climbing.height2 * 1000.0, climbing.anticlimbers ? "yes" : "no", pair()); }; @@ -545,7 +545,7 @@ bool TMoverParameters::crush_hit(VehicleEnd const End, double const dt) return true; } -void TMoverParameters::check_pushed_off(double const dt, double const Distance) +void physics::Vehicle::check_pushed_off(double const dt, double const Distance) { if (Global.collisions != global_settings::collision_model::physical || false == Global.crash_damage || DamageFlag.HasAll(VehicleDamage::derailed) || false == TestFlag(CategoryFlag, 1) || DebugModeFlag) @@ -576,7 +576,7 @@ void TMoverParameters::check_pushed_off(double const dt, double const Distance) } auto const &coupler{Couplers[end]}; collision::pushed_end pushed; - pushed.other_length = other->MoverParameters->Dim.L; + pushed.other_length = other->physics->Dim.L; pushed.crush = coupler.crush; // the steady push of the springs over the step, or the peak of a hit for as long as it lasted: the flange climbs // over the distance the wheels rolled meanwhile, a wheel lifted off the rail goes in a short time, rolling or not @@ -635,7 +635,7 @@ void restore_end(TCoupling &Coupler) // the coupler as good as new, its end with it (the crush that tore the draw gear off), the vehicle without the coupler // damage (and the emergency braking of the torn brake hose) once neither of its couplers is broken -void repair(TMoverParameters &Vehicle, TCoupling &Coupler) +void repair(physics::Vehicle &Vehicle, TCoupling &Coupler) { Coupler.broken = false; Coupler.stretch_duration = 0.f; @@ -652,7 +652,7 @@ void repair(TMoverParameters &Vehicle, TCoupling &Coupler) } // namespace -bool TMoverParameters::repair_coupler(VehicleEnd const End) +bool physics::Vehicle::repair_coupler(VehicleEnd const End) { auto &thiscoupler{Couplers[End]}; if (false == thiscoupler.broken) @@ -672,7 +672,7 @@ bool TMoverParameters::repair_coupler(VehicleEnd const End) static_assert(derailment::track_damage::railwear == dtrack_railwear && derailment::track_damage::freerail == dtrack_freerail && derailment::track_damage::thinrail == dtrack_thinrail && derailment::track_damage::railbend == dtrack_railbend); -double TMoverParameters::centre_of_gravity() const +double physics::Vehicle::centre_of_gravity() const { auto const kind{EngineType == TEngineType::None ? derailment::vehicle_class::unpowered : derailment::vehicle_class::powered}; auto const empty{CentreOfGravity > 0.0 ? CentreOfGravity : derailment::default_centre_of_gravity(Dim.H, kind)}; @@ -681,7 +681,7 @@ double TMoverParameters::centre_of_gravity() const return derailment::loaded_centre_of_gravity(empty, Mass, loadmass, loadshare, Floor, Dim.H); } -void TMoverParameters::check_derailment(TTrackShape const &Shape, TTrackParam const &Track, double const Distance) +void physics::Vehicle::check_derailment(TTrackShape const &Shape, TTrackParam const &Track, double const Distance) { if (DamageFlag.HasAll(VehicleDamage::derailed) || false == TestFlag(CategoryFlag, 1) || DebugModeFlag) { @@ -703,7 +703,7 @@ void TMoverParameters::check_derailment(TTrackShape const &Shape, TTrackParam co } // the force of the coupling, or of the buffers touching, along this vehicle: forwards at the front pulls vehicle.ends[NumberOf(end)].compression = (end == VehicleEnd::front ? -1.0 : 1.0) * Couplers[end].CForce; - vehicle.ends[NumberOf(end)].other_length = other->MoverParameters->Dim.L; + vehicle.ends[NumberOf(end)].other_length = other->physics->Dim.L; } derailment::track_state track; track.radius = Shape.R; @@ -734,7 +734,7 @@ void TMoverParameters::check_derailment(TTrackShape const &Shape, TTrackParam co WriteLog("derailment monitor: " + Name + " " + derailment::report(verdict, vehicle, track, V, Track.Name != nullptr ? *Track.Name : std::string{})); } -void TMoverParameters::derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track, std::string const *TrackName) +void physics::Vehicle::derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track, std::string const *TrackName) { if (false == DamageFlag.Set(VehicleDamage::derailed)) { @@ -757,7 +757,7 @@ void TMoverParameters::derail(derailment::verdict const &Verdict, derailment::ve } } -void TMoverParameters::rerail() +void physics::Vehicle::rerail() { DamageFlag.Clear(VehicleDamage::derailed); Derailed = derailment::outcome::none; @@ -785,7 +785,7 @@ void TMoverParameters::rerail() switch_physics(true, wake_cause::command); } -void TMoverParameters::repair_damage() +void physics::Vehicle::repair_damage() { DamageFlag = {}; EngDmgFlag = 0; @@ -799,7 +799,7 @@ void TMoverParameters::repair_damage() rerail(); } -void TMoverParameters::Derail(DerailReason const Reason) +void physics::Vehicle::Derail(DerailReason const Reason) { if (DamageFlag.Set(VehicleDamage::derailed)) { @@ -844,19 +844,19 @@ void TMoverParameters::Derail(DerailReason const Reason) else if (Reason == WRONG_TRACK_TYPE) ErrorLog("Bad dynamic: " + Name + " derailed due to wrong track type"); // błąd w scenerii else if (Reason == COLLISION) - WriteLog("Bad driving: " + Name + " derailed"); // This reason also generates its own message in `TMoverParameters::CollisionDetect()` + WriteLog("Bad driving: " + Name + " derailed"); // This reason also generates its own message in `physics::Vehicle::CollisionDetect()` else if (Reason == TRAILED_SWITCH) ErrorLog("Bad driving: " + Name + " derailed trailing through a switch with a movable nose set the other way"); } } -bool TMoverParameters::leaves_track() const +bool physics::Vehicle::leaves_track() const { return Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1) && DamageFlag.HasAll(VehicleDamage::derailed) && Derailed != derailment::outcome::none && false == OffTrack.active(); } -void TMoverParameters::pull_off(int const Side, double const Acceleration, std::string const &Why) +void physics::Vehicle::pull_off(int const Side, double const Acceleration, std::string const &Why) { if (Global.derailment != global_settings::derailment_model::physical || false == DamageFlag.Set(VehicleDamage::derailed)) { diff --git a/physics/components/commands.cpp b/physics/components/commands.cpp index 1477b3c37..22d1b8558 100644 --- a/physics/components/commands.cpp +++ b/physics/components/commands.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. // the commands passed between the vehicles of a train #include "stdafx.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/DynObj.h" #include "physics/oerlikonest.h" #include "utilities/Globals.h" @@ -34,7 +34,7 @@ http://mozilla.org/MPL/2.0/. // Q: 20160714 // Wstawia komendę z parametrem, od sprzęgu i w lokalizacji do pojazdu // ************************************************************************************************* -void TMoverParameters::PutCommand(std::string const &NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation) +void physics::Vehicle::PutCommand(std::string const &NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation) { auto const parsed{ParseVehicleCommand(NewCommand)}; CommandIn.Command = parsed.command; @@ -50,7 +50,7 @@ void TMoverParameters::PutCommand(std::string const &NewCommand, double NewValue // Q: 20160714 // Ustawienie komendy wraz z parametrami // ************************************************************************************************* -bool TMoverParameters::SetInternalCommand(VehicleCommand const NewCommand, double NewValue1, double NewValue2, CouplingSet const Couplertype) +bool physics::Vehicle::SetInternalCommand(VehicleCommand const NewCommand, double NewValue1, double NewValue2, CouplingSet const Couplertype) { bool SIC; if (CommandIn.Command == NewCommand && CommandIn.Argument.empty() && CommandIn.Value1 == NewValue1 && CommandIn.Value2 == NewValue2 && CommandIn.couplings == Couplertype) @@ -74,7 +74,7 @@ bool TMoverParameters::SetInternalCommand(VehicleCommand const NewCommand, doubl // Q: 20160714 // wysyłanie komendy w kierunku dir (1=przód, -1=tył) do kolejnego pojazdu (jednego) // ************************************************************************************************* -bool TMoverParameters::SendCtrlToNext(VehicleCommand const CtrlCommand, double const ctrlvalue, double const dir, CouplingSet const Couplertype) +bool physics::Vehicle::SendCtrlToNext(VehicleCommand const CtrlCommand, double const ctrlvalue, double const dir, CouplingSet const Couplertype) { bool OK; int d; // numer sprzęgu w kierunku którego wysyłamy @@ -114,7 +114,7 @@ bool TMoverParameters::SendCtrlToNext(VehicleCommand const CtrlCommand, double c // Komenda musi być zdefiniowana tutaj, a jeśli się wywołuje funkcję, to ona nie może // sama przesyłać do kolejnych pojazdów. Należy też się zastanowić, czy dla uzyskania // jakiejś zmiany (np. IncMainCtrl) lepiej wywołać funkcję, czy od razu wysłać komendę. -bool TMoverParameters::RunCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, std::string_view const Argument) +bool physics::Vehicle::RunCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, std::string_view const Argument) { // the group of the command sets OK; a command none of them knows isn't done if (bool OK{false}; RunControllerCommand(Command, CValue1, CValue2, Couplertype, OK) || RunRelaysCommand(Command, CValue1, CValue2, Couplertype, OK) || @@ -134,7 +134,7 @@ bool TMoverParameters::RunCommand(VehicleCommand const Command, double CValue1, } // RunCommand() for the controllers; returns whether the command is one of them -bool TMoverParameters::RunControllerCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) +bool physics::Vehicle::RunControllerCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) { if (Command == VehicleCommand::mainController) { @@ -183,7 +183,7 @@ bool TMoverParameters::RunControllerCommand(VehicleCommand const Command, double } // RunCommand() for the direction, the automatic start and the current relays; returns whether the command is one of them -bool TMoverParameters::RunRelaysCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) +bool physics::Vehicle::RunRelaysCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) { if (Command == VehicleCommand::direction) { @@ -217,7 +217,7 @@ bool TMoverParameters::RunRelaysCommand(VehicleCommand const Command, double CVa } // RunCommand() for the cab and the speed control; returns whether the command is one of them -bool TMoverParameters::RunCabCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) +bool physics::Vehicle::RunCabCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) { if (Command == VehicleCommand::cabActivation) { @@ -268,7 +268,7 @@ bool TMoverParameters::RunCabCommand(VehicleCommand const Command, double CValue } // RunCommand() for the train brake, the releaser and the emergency brake; returns whether the command is one of them -bool TMoverParameters::RunBrakeCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) +bool physics::Vehicle::RunBrakeCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) { if (Command == VehicleCommand::brake) // youBy - jak sie EP hamuje, to trza sygnal wyslac... { @@ -308,7 +308,7 @@ bool TMoverParameters::RunBrakeCommand(VehicleCommand const Command, double CVal } // RunCommand() for the brake delays, the spring brake, the sand and the cab signalling; returns whether the command is one of them -bool TMoverParameters::RunBrakeEquipmentCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) +bool physics::Vehicle::RunBrakeEquipmentCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) { if (Command == VehicleCommand::brakeDelay) { @@ -355,7 +355,7 @@ bool TMoverParameters::RunBrakeEquipmentCommand(VehicleCommand const Command, do } // RunCommand() for the heating, the converter, the battery and the compressor; returns whether the command is one of them -bool TMoverParameters::RunAuxiliariesCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) +bool physics::Vehicle::RunAuxiliariesCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) { if (Command == VehicleCommand::heatingSwitch) { @@ -403,7 +403,7 @@ bool TMoverParameters::RunAuxiliariesCommand(VehicleCommand const Command, doubl } // RunCommand() for the water, fuel and oil pumps and the water heater; returns whether the command is one of them -bool TMoverParameters::RunPumpsCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) +bool physics::Vehicle::RunPumpsCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) { if (Command == VehicleCommand::waterPumpBreakerSwitch) { @@ -514,7 +514,7 @@ bool TMoverParameters::RunPumpsCommand(VehicleCommand const Command, double CVal } // RunCommand() for the motor blowers and the compartment lights; returns whether the command is one of them -bool TMoverParameters::RunBlowersCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) +bool physics::Vehicle::RunBlowersCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) { if (Command == VehicleCommand::motorBlowersFrontSwitch) { @@ -580,7 +580,7 @@ bool TMoverParameters::RunBlowersCommand(VehicleCommand const Command, double CV } // RunCommand() for the line breaker, the relays and the pantographs; returns whether the command is one of them -bool TMoverParameters::RunPowerCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) +bool physics::Vehicle::RunPowerCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) { if (Command == VehicleCommand::mainSwitch) { @@ -634,7 +634,7 @@ bool TMoverParameters::RunPowerCommand(VehicleCommand const Command, double CVal } // RunCommand() for the doors and the departure signal; returns whether the command is one of them -bool TMoverParameters::RunDoorsCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) +bool physics::Vehicle::RunDoorsCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) { if (Command == VehicleCommand::doorPermit) { @@ -675,7 +675,7 @@ bool TMoverParameters::RunDoorsCommand(VehicleCommand const Command, double CVal // the doors' permits, on the sides the command names: CValue1 the sides, negative to take the permit back, CValue2 the // direction the command comes from -void TMoverParameters::DoorPermitCommand(double const CValue1, double const CValue2) +void physics::Vehicle::DoorPermitCommand(double const CValue1, double const CValue2) { auto const leftside{CValue2 > 0 ? 1 : 2}; if (auto const rightside{3 - leftside}; std::abs(static_cast(CValue1)) & rightside) @@ -689,7 +689,7 @@ void TMoverParameters::DoorPermitCommand(double const CValue1, double const CVal } // the doors opened or closed from afar on the sides the command names, unless they're only worked locally -void TMoverParameters::DoorRemoteCommand(bool const Open, double const CValue1, double const CValue2) +void physics::Vehicle::DoorRemoteCommand(bool const Open, double const CValue1, double const CValue2) { using enum control_t; if (auto const doorcontrol{Open ? Doors.open_control : Doors.close_control}; @@ -731,7 +731,7 @@ bool setOrClear(DamageSet &damage, int const number) } // namespace // RunCommand() for the load and the damage; returns whether the command is one of them -bool TMoverParameters::RunLoadCommand(VehicleCommand const Command, double CValue1, double CValue2, std::string_view const Argument, bool &OK) +bool physics::Vehicle::RunLoadCommand(VehicleCommand const Command, double CValue1, double CValue2, std::string_view const Argument, bool &OK) { if (Command == VehicleCommand::load) { @@ -794,7 +794,7 @@ bool TMoverParameters::RunLoadCommand(VehicleCommand const Command, double CValu // Q: 20160714 // Uruchamia funkcję RunCommand aż do skutku. Jeśli będzie pozytywny to kasuje komendę. // ************************************************************************************************* -bool TMoverParameters::RunInternalCommand() +bool physics::Vehicle::RunInternalCommand() { bool OK; diff --git a/physics/components/controllers.cpp b/physics/components/controllers.cpp index d5e41b2c3..902eecc4b 100644 --- a/physics/components/controllers.cpp +++ b/physics/components/controllers.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. // the master and the secondary controllers, the automatic relay and the camshaft, the integrated controller, the speed control #include "stdafx.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/DynObj.h" #include "physics/oerlikonest.h" #include "utilities/Globals.h" @@ -40,7 +40,7 @@ http://mozilla.org/MPL/2.0/. // zwiększenie nastawinika // ************************************************************************************************* -bool TMoverParameters::IncMainCtrl(int CtrlSpeed) +bool physics::Vehicle::IncMainCtrl(int CtrlSpeed) { // basic fail conditions: if (MainCtrlPosNo <= 0 || CabActive == 0) @@ -107,14 +107,14 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) } // a notch up, as the kind of the engine takes it; returns whether the controller moved -bool TMoverParameters::IncMainCtrlByEngine(int const CtrlSpeed) +bool physics::Vehicle::IncMainCtrlByEngine(int const CtrlSpeed) { return Drive().IncreaseMainController(*this, CtrlSpeed); } // a notch up of the series motors' controller: CtrlSpeed over 1 runs it to the first position without resistors; // returns whether it moved as asked -bool TMoverParameters::IncMainCtrlSeriesMotor(int const CtrlSpeed) +bool physics::Vehicle::IncMainCtrlSeriesMotor(int const CtrlSpeed) { bool OK = false; if (DirActive == 0) @@ -179,7 +179,7 @@ bool TMoverParameters::IncMainCtrlSeriesMotor(int const CtrlSpeed) // Q: 20160710 // zmniejszenie nastawnika // ***************************************************************************** -bool TMoverParameters::DecMainCtrl(int CtrlSpeed) +bool physics::Vehicle::DecMainCtrl(int CtrlSpeed) { bool OK = false; // basic fail conditions: @@ -236,13 +236,13 @@ bool TMoverParameters::DecMainCtrl(int CtrlSpeed) } // a notch down, as the kind of the engine takes it; returns whether the controller moved -bool TMoverParameters::DecMainCtrlByEngine(int const CtrlSpeed) +bool physics::Vehicle::DecMainCtrlByEngine(int const CtrlSpeed) { return Drive().DecreaseMainController(*this, CtrlSpeed); } // a notch down of the series motors' controller: CtrlSpeed over 1 runs it down to the first position without resistors -bool TMoverParameters::DecMainCtrlSeriesMotor(int const CtrlSpeed) +bool physics::Vehicle::DecMainCtrlSeriesMotor(int const CtrlSpeed) { bool OK = false; if (CtrlSpeed == 1) /*and (ScndCtrlPos=0)*/ @@ -267,25 +267,25 @@ bool TMoverParameters::DecMainCtrlSeriesMotor(int const CtrlSpeed) return OK; } -bool TMoverParameters::IsMainCtrlActualNoPowerPos() const +bool physics::Vehicle::IsMainCtrlActualNoPowerPos() const { // TODO: wrap controller pieces into a class for potential specializations, similar to brake subsystems return MainCtrlActualPos <= MainCtrlNoPowerPos(); } -bool TMoverParameters::IsMainCtrlNoPowerPos() const +bool physics::Vehicle::IsMainCtrlNoPowerPos() const { // TODO: wrap controller pieces into a class for potential specializations, similar to brake subsystems return MainCtrlPos <= MainCtrlNoPowerPos(); } -bool TMoverParameters::IsMainCtrlMaxPowerPos() const +bool physics::Vehicle::IsMainCtrlMaxPowerPos() const { // TODO: wrap controller pieces into a class for potential specializations, similar to brake subsystems return MainCtrlPos == MainCtrlPosNo; } -int TMoverParameters::MainCtrlNoPowerPos() const +int physics::Vehicle::MainCtrlNoPowerPos() const { switch (EIMCtrlType) @@ -309,35 +309,35 @@ int TMoverParameters::MainCtrlNoPowerPos() const } } -int TMoverParameters::MainCtrlActualPowerPos() const +int physics::Vehicle::MainCtrlActualPowerPos() const { return MainCtrlActualPos - MainCtrlNoPowerPos(); } -int TMoverParameters::MainCtrlPowerPos() const +int physics::Vehicle::MainCtrlPowerPos() const { return MainCtrlPos - MainCtrlNoPowerPos(); } -int TMoverParameters::EIMCtrlEmergencyPositions() const +int physics::Vehicle::EIMCtrlEmergencyPositions() const { return (EIMCtrlType == 2 && EIMCtrlMainEmergency) ? 1 : 0; } -bool TMoverParameters::IsMainCtrlEmergencyPos() const +bool physics::Vehicle::IsMainCtrlEmergencyPos() const { return MainCtrlPos < EIMCtrlEmergencyPositions(); } -int TMoverParameters::MainCtrlPosForCoupled() const +int physics::Vehicle::MainCtrlPosForCoupled() const { // the emergency brake itself reaches the train through the brake pipe, vented by the vehicle driven from return std::max(0, MainCtrlPos - EIMCtrlEmergencyPositions()); } -int TMoverParameters::MainCtrlPosFromCoupled(int const Position) const +int physics::Vehicle::MainCtrlPosFromCoupled(int const Position) const { return Position + EIMCtrlEmergencyPositions(); } @@ -346,7 +346,7 @@ int TMoverParameters::MainCtrlPosFromCoupled(int const Position) const // Q: 20160710 // zwiększenie bocznika // ************************************************************************************************* -bool TMoverParameters::IncScndCtrl(int CtrlSpeed) +bool physics::Vehicle::IncScndCtrl(int CtrlSpeed) { bool OK = false; @@ -419,7 +419,7 @@ bool TMoverParameters::IncScndCtrl(int CtrlSpeed) // Q: 20160710 // zmniejszenie bocznika // ************************************************************************************************* -bool TMoverParameters::DecScndCtrl(int CtrlSpeed) +bool physics::Vehicle::DecScndCtrl(int CtrlSpeed) { bool OK = false; @@ -480,13 +480,13 @@ bool TMoverParameters::DecScndCtrl(int CtrlSpeed) return OK; } -bool TMoverParameters::IsScndCtrlLockedByMainCtrl() const +bool physics::Vehicle::IsScndCtrlLockedByMainCtrl() const { // ET21, ET22, EP09: the field shunting engages only on the resistance-free positions of the master controller (eu07/maszyna#402) return ScndCtrlResistiveLock && (IsMainCtrlNoPowerPos() || RList[MainCtrlPos].R >= 0.01); } -void TMoverParameters::ScndCtrlResistiveLockCheck() +void physics::Vehicle::ScndCtrlResistiveLockCheck() { // the shunt controller, locked in both directions on zero and the resistive positions, would otherwise stay engaged there once the // master controller is taken back (or set from elsewhere, e.g. by the AI or another vehicle of the consist) with the shunt on @@ -496,20 +496,20 @@ void TMoverParameters::ScndCtrlResistiveLockCheck() } } -int TMoverParameters::GetVirtualScndPos() const +int physics::Vehicle::GetVirtualScndPos() const { if (TrainType == train_type::et42 && DynamicBrakeFlag && !ScndCtrlPos) return -1; return ScndCtrlPos; } -bool TMoverParameters::IsScndCtrlNoPowerPos() const +bool physics::Vehicle::IsScndCtrlNoPowerPos() const { // TODO: refine the check on account of potential electric series vehicles with speed control return ScndCtrlPos == 0 || true == SpeedCtrl; } -bool TMoverParameters::IsScndCtrlMaxPowerPos() const +bool physics::Vehicle::IsScndCtrlMaxPowerPos() const { // TODO: refine the check on account of potential electric series vehicles with speed control return ScndCtrlPos == ScndCtrlPosNo || true == SpeedCtrl; @@ -519,7 +519,7 @@ bool TMoverParameters::IsScndCtrlMaxPowerPos() const // Q: 20160713 // Włączenie / wyłączenie automatycznego rozruchu // ************************************************************************************************* -bool TMoverParameters::AutoRelaySwitch(bool State) +bool physics::Vehicle::AutoRelaySwitch(bool State) { bool ARS; if (AutoRelayType == 2 && AutoRelayFlag != State) @@ -539,7 +539,7 @@ bool TMoverParameters::AutoRelaySwitch(bool State) // Sprawdzenie warunków pracy automatycznego rozruchu // ************************************************************************************************* -bool TMoverParameters::AutoRelayCheck(void) +bool physics::Vehicle::AutoRelayCheck(void) { bool OK = false; // b:int; @@ -592,7 +592,7 @@ bool TMoverParameters::AutoRelayCheck(void) } // a step of the shunt field on a position without resistors, up or down to the second controller -bool TMoverParameters::AutoRelayShuntStep(bool const ARFASI2) +bool physics::Vehicle::AutoRelayShuntStep(bool const ARFASI2) { bool OK = false; // scnd bez samoczynnego rozruchu @@ -620,7 +620,7 @@ bool TMoverParameters::AutoRelayShuntStep(bool const ARFASI2) } // a step of the main controller's relays, up or down to its position, or the shunt field off on the resistors -bool TMoverParameters::AutoRelayMainStep(bool const ARFASI) +bool physics::Vehicle::AutoRelayMainStep(bool const ARFASI) { bool OK = false; // running backwards, the motors don't get joined in more branches than allowed (the series connection @@ -654,7 +654,7 @@ bool TMoverParameters::AutoRelayMainStep(bool const ARFASI) // a step of the main relays up to the controller's position, at once to the parallel position without resistors // on a fast serial circuit (303E); returns whether the relays moved, never into parallel with the overload relay high -bool TMoverParameters::AutoRelayMainUp(bool const ARFASI) +bool physics::Vehicle::AutoRelayMainUp(bool const ARFASI) { bool OK = false; // prevent switch to parallel mode if motor overload relay is set to high threshold mode @@ -690,7 +690,7 @@ bool TMoverParameters::AutoRelayMainUp(bool const ARFASI) // a notch up of the main relays after their delay, through the group switch of the ET22, and the sounds of the // parallel positions; returns whether they moved -bool TMoverParameters::AutoRelayMainNotchUp() +bool physics::Vehicle::AutoRelayMainNotchUp() { bool OK = false; // WriteLog("LRT = " + FloatToStr(LastRelayTime) + ", " + @@ -739,7 +739,7 @@ bool TMoverParameters::AutoRelayMainNotchUp() } // a step of the main relays down to the controller's position; returns whether they moved -bool TMoverParameters::AutoRelayMainDown() +bool physics::Vehicle::AutoRelayMainDown() { bool OK = false; if (RList[MainCtrlPos].R == 0 && MainCtrlPos > 0 && !(MainCtrlPos == MainCtrlPosNo) && FastSerialCircuit == 1) @@ -771,7 +771,7 @@ bool TMoverParameters::AutoRelayMainDown() } // the line contactors closed at the first position, or, open, the camshaft run back to zero -bool TMoverParameters::AutoRelayLineContactorsStep(bool const motorconnectorsoff) +bool physics::Vehicle::AutoRelayLineContactorsStep(bool const motorconnectorsoff) { bool OK = false; // ybARC - zalaczenie stycznikow liniowych @@ -802,7 +802,7 @@ bool TMoverParameters::AutoRelayLineContactorsStep(bool const motorconnectorsoff // the camshaft, the line contactors open, run back to its zero position a step at a time, or at once without one; // returns whether it moved -bool TMoverParameters::CamshaftRunDown() +bool physics::Vehicle::CamshaftRunDown() { bool OK = false; @@ -850,7 +850,7 @@ bool TMoverParameters::CamshaftRunDown() } // the one way camshaft of the EN57 run on to its end and round to zero; returns whether it moved -bool TMoverParameters::CamshaftRunDownEMU() +bool physics::Vehicle::CamshaftRunDownEMU() { bool OK = false; // EN57 wal jednokierunkowy calosciowy @@ -889,7 +889,7 @@ bool TMoverParameters::CamshaftRunDownEMU() return OK; } -bool TMoverParameters::MotorConnectorsCheck() +bool physics::Vehicle::MotorConnectorsCheck() { // hunter-111211: wylacznik cisnieniowy @@ -910,7 +910,7 @@ bool TMoverParameters::MotorConnectorsCheck() return false == connectorsoff && LineContactorsInterlockReleased(); } -bool TMoverParameters::LineContactorsInterlockReleased() const +bool physics::Vehicle::LineContactorsInterlockReleased() const { switch (LineContactorsInterlock) { @@ -990,7 +990,7 @@ double stepped_uc_value(double const Current, double const Ramped, TUniversalCtr } // namespace -void TMoverParameters::CheckEIMIC(double dt) +void physics::Vehicle::CheckEIMIC(double dt) { double offset = EIMCtrlAdditionalZeros ? 1.0 : 0.0; double multiplier = (EIMCtrlEmergency ? 1.0 : 0.0) + offset; @@ -1034,7 +1034,7 @@ void TMoverParameters::CheckEIMIC(double dt) } // the controller (EIMCtrlType 0): the position of the main controller, or the analog one, or the brake asked -void TMoverParameters::EIMICFromController(double const brakeDemand, double const offset, double const multiplier) +void physics::Vehicle::EIMICFromController(double const brakeDemand, double const offset, double const multiplier) { eimic = brakeDemand > 0.01 ? -brakeDemand : eimic_analog > 0.01 ? eimic_analog : (double)MainCtrlPos / (double)MainCtrlPosNo; if (EIMCtrlAdditionalZeros || EIMCtrlEmergency) @@ -1049,7 +1049,7 @@ void TMoverParameters::EIMICFromController(double const brakeDemand, double cons } // EIMCtrlType 1: the positions B+ to TMax move the value at a steady pace -void TMoverParameters::EIMICFromSteps(double dt) +void physics::Vehicle::EIMICFromSteps(double dt) { switch (MainCtrlPos) { @@ -1085,7 +1085,7 @@ void TMoverParameters::EIMICFromSteps(double dt) // EIMCtrlType 2: the positions 0 to 4 move the value towards -1, 0 or 1, from the controller's delay on; the // emergency brake position below them, where the controller has one, brakes in full at once -void TMoverParameters::EIMICFromFourPositions(double dt) +void physics::Vehicle::EIMICFromFourPositions(double dt) { if (IsMainCtrlEmergencyPos()) { @@ -1129,7 +1129,7 @@ void TMoverParameters::EIMICFromFourPositions(double dt) } // EIMCtrlType 3: the universal controller of UniCtrlList, with the train brake built in or not -void TMoverParameters::EIMICFromUniversalController(double dt, double const brakeDemand) +void physics::Vehicle::EIMICFromUniversalController(double dt, double const brakeDemand) { if (UniCtrlIntegratedBrakePNCtrl) { @@ -1166,7 +1166,7 @@ void TMoverParameters::EIMICFromUniversalController(double dt, double const brak // the train brake built into the universal controller: the handle set to the controller's position, or the // controller, at a brake handle moved alone, to the nearest position of the handle's -void TMoverParameters::UniversalControllerTrainBrake() +void physics::Vehicle::UniversalControllerTrainBrake() { if (UniCtrlList[MainCtrlPos].mode != BrakeCtrlPos && MainCtrlActualPos == MainCtrlPos) // there was no move of controller, but brake only { @@ -1187,7 +1187,7 @@ void TMoverParameters::UniversalControllerTrainBrake() } // the local brake of the TRAXX locomotives, by time: released, held or applied, which cuts the drive off -void TMoverParameters::EIMICTraxxLocalBrake(double dt) +void physics::Vehicle::EIMICTraxxLocalBrake(double dt) { if (LocalBrakeRatio() < 0.4) // pozycja 0, odhamowywanie { @@ -1210,7 +1210,7 @@ void TMoverParameters::EIMICTraxxLocalBrake(double dt) } // the value limited by the power, the spring brake, the pipe lock, the direction and the doors' permits -void TMoverParameters::EIMICLimit() +void physics::Vehicle::EIMICLimit() { auto const eimicpowerenabled{(MainCircuitPowered() || Power == 0.0) && (!SpringBrake.IsActive || !SpringBrakeCutsOffDrive) && !LockPipe && DirAbsolute != 0}; auto const eimicdoorenabled{(SpringBrake.IsActive && ReleaseParkingBySpringBrakeWhenDoorIsOpen)}; @@ -1236,7 +1236,7 @@ void TMoverParameters::EIMICLimit() eimic = safe_clamp(eimic, -1.0, eimicpowerenabled ? eimic_max : 0.0); } -void TMoverParameters::CheckSpeedCtrl(double dt) +void physics::Vehicle::CheckSpeedCtrl(double dt) { if (EIMCtrlType == 0) { @@ -1301,7 +1301,7 @@ void TMoverParameters::CheckSpeedCtrl(double dt) // the PI regulator of the speed control: the power asked of the drive, or its brake intervention, from the error of // the speed; accfactor, the most power it may ask -void TMoverParameters::SpeedCtrlRegulator(double dt, double const accfactor) +void physics::Vehicle::SpeedCtrlRegulator(double dt, double const accfactor) { if (SpeedCtrlUnit.ManualStateOverride && eimic > 0.0009) eimic = 1.0; @@ -1339,18 +1339,18 @@ void TMoverParameters::SpeedCtrlRegulator(double dt, double const accfactor) } } -bool TMoverParameters::IsSpeedCtrlSeparate() const +bool physics::Vehicle::IsSpeedCtrlSeparate() const { // no secondary controller, or one of these engines', which shunts the field of the traction motors (eu07/maszyna#69) return SpeedCtrl && (ScndCtrlPosNo == 0 || EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric); } -bool TMoverParameters::IsSpeedCtrlEngaged() const +bool physics::Vehicle::IsSpeedCtrlEngaged() const { return IsSpeedCtrlSeparate() ? SpeedCtrlUnit.IsActive : ScndCtrlPos > 0; } -bool TMoverParameters::SpeedCtrlSwitch(bool const State) +bool physics::Vehicle::SpeedCtrlSwitch(bool const State) { if (false == IsSpeedCtrlSeparate()) { @@ -1377,7 +1377,7 @@ bool TMoverParameters::SpeedCtrlSwitch(bool const State) return wasactive; } -void TMoverParameters::SpeedCtrlButton(int button) +void physics::Vehicle::SpeedCtrlButton(int button) { if (SpeedCtrl && IsSpeedCtrlEngaged()) { @@ -1385,7 +1385,7 @@ void TMoverParameters::SpeedCtrlButton(int button) } } -void TMoverParameters::SpeedCtrlInc() +void physics::Vehicle::SpeedCtrlInc() { if (SpeedCtrl && IsSpeedCtrlEngaged()) { @@ -1394,7 +1394,7 @@ void TMoverParameters::SpeedCtrlInc() } } -void TMoverParameters::SpeedCtrlDec() +void physics::Vehicle::SpeedCtrlDec() { if (SpeedCtrl && IsSpeedCtrlEngaged()) { @@ -1403,7 +1403,7 @@ void TMoverParameters::SpeedCtrlDec() } } -bool TMoverParameters::SpeedCtrlPowerInc() +bool physics::Vehicle::SpeedCtrlPowerInc() { if (!(SpeedCtrl && IsSpeedCtrlEngaged())) return false; @@ -1415,7 +1415,7 @@ bool TMoverParameters::SpeedCtrlPowerInc() return true; } -bool TMoverParameters::SpeedCtrlPowerDec() +bool physics::Vehicle::SpeedCtrlPowerDec() { if (!(SpeedCtrl && IsSpeedCtrlEngaged())) return false; diff --git a/physics/components/couplers.cpp b/physics/components/couplers.cpp index 7bf797524..6de010fff 100644 --- a/physics/components/couplers.cpp +++ b/physics/components/couplers.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. // attaching and detaching, the forces in the couplers and the automatic coupling #include "stdafx.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/DynObj.h" #include "physics/oerlikonest.h" #include "utilities/Globals.h" @@ -29,23 +29,23 @@ http://mozilla.org/MPL/2.0/. #include #include "physics/components/internal.h" -// Ra: tu należy przenosić funcje z mover.pas, które nie są z niego wywoływane. -// Jeśli jakieś zmienne nie są używane w mover.pas, też można je przenosić. +// Ra: tu należy przenosić funcje z physics.pas, które nie są z niego wywoływane. +// Jeśli jakieś zmienne nie są używane w physics.pas, też można je przenosić. // Przeniesienie wszystkiego na raz zrobiło by zbyt wielki chaos do ogarnięcia. const double dEpsilon = 0.01; // 1cm (zależy od typu sprzęgu...) -double TMoverParameters::Distance(const TLocation &Loc1, const TLocation &Loc2, const TDimension &Dim1, const TDimension &Dim2) +double physics::Vehicle::Distance(const TLocation &Loc1, const TLocation &Loc2, const TDimension &Dim1, const TDimension &Dim2) { // zwraca odległość pomiędzy pojazdami (Loc1) i (Loc2) z uwzględnieneim ich długości (kule!) return hypot(Loc2.X - Loc1.X, Loc1.Y - Loc2.Y) - 0.5 * (Dim2.L + Dim1.L); }; -double TMoverParameters::CouplerDist(TMoverParameters const *Left, TMoverParameters const *Right) +double physics::Vehicle::CouplerDist(physics::Vehicle const *Left, physics::Vehicle const *Right) { // obliczenie odległości pomiędzy sprzęgami (kula!) return Distance(Left->Loc, Right->Loc, Left->Dim, Right->Dim); // odległość pomiędzy sprzęgami (kula!) }; -bool TMoverParameters::Attach(int ConnectNo, int ConnectToNr, TMoverParameters *ConnectTo, CouplingSet CouplingType, bool Enforce, bool Audible) +bool physics::Vehicle::Attach(int ConnectNo, int ConnectToNr, physics::Vehicle *ConnectTo, CouplingSet CouplingType, bool Enforce, bool Audible) { // łączenie do swojego sprzęgu (ConnectNo) pojazdu (ConnectTo) stroną (ConnectToNr) // Ra: zwykle wykonywane dwukrotnie, dla każdego pojazdu oddzielnie // Ra: trzeba by odróżnić wymóg dociśnięcia od uszkodzenia sprzęgu przy podczepianiu AI do składu @@ -119,7 +119,7 @@ bool TMoverParameters::Attach(int ConnectNo, int ConnectToNr, TMoverParameters * return true; } -int TMoverParameters::DettachStatus(int ConnectNo) +int physics::Vehicle::DettachStatus(int ConnectNo) { // Ra: sprawdzenie, czy odległość jest dobra do rozłączania // powinny być 3 informacje: =0 sprzęg już rozłączony, <0 da się rozłączyć. >0 nie da się rozłączyć if (!Couplers[ConnectNo].Connected) @@ -134,7 +134,7 @@ int TMoverParameters::DettachStatus(int ConnectNo) return Neighbours[ConnectNo].distance > 0.2 ? -Couplers[ConnectNo].CouplingFlag.Bits() : Couplers[ConnectNo].CouplingFlag.Bits(); }; -bool TMoverParameters::Dettach(int ConnectNo) +bool physics::Vehicle::Dettach(int ConnectNo) { // rozlaczanie auto &thiscoupler{Couplers[ConnectNo]}; @@ -183,21 +183,21 @@ bool TMoverParameters::Dettach(int ConnectNo) // ************************************************************************************************* // prędkość zbliżania się stykających się końców pojazdów przy zderzeniu, w km/h // ************************************************************************************************* -double TMoverParameters::CollisionVelocity(VehicleEnd const End, TMoverParameters const &Other, VehicleEnd const OtherEnd) const +double physics::Vehicle::CollisionVelocity(VehicleEnd const End, physics::Vehicle const &Other, VehicleEnd const OtherEnd) const { auto const velocitydifference{CouplerVelocityDifference(End, Other, OtherEnd)}; // the front end closes in on the other vehicle when this one moves forward faster, the rear end when it's slower return (End == VehicleEnd::front ? velocitydifference : -velocitydifference) * 3.6; // m/s -> km/h } -double TMoverParameters::CouplerVelocityDifference(VehicleEnd const End, TMoverParameters const &Other, VehicleEnd const OtherEnd) const +double physics::Vehicle::CouplerVelocityDifference(VehicleEnd const End, physics::Vehicle const &Other, VehicleEnd const OtherEnd) const { // V runs along the vehicle's own axis, towards its front; the other vehicle's velocity is turned around when the // vehicles face each other (touch with the same ends) return V - Other.V * DirPatch(End, OtherEnd); } -bool TMoverParameters::AutomaticCouplingSafe(VehicleEnd const End, TMoverParameters const &Other, VehicleEnd const OtherEnd) const +bool physics::Vehicle::AutomaticCouplingSafe(VehicleEnd const End, physics::Vehicle const &Other, VehicleEnd const OtherEnd) const { return false == Global.crash_damage || CollisionVelocity(End, Other, OtherEnd) <= SafeCollisionVelocity; } @@ -230,7 +230,7 @@ traction_kind traction_of(TEngineType const Engine) } // namespace -bool TMoverParameters::ControlCouplingAllowed(VehicleEnd const End, TMoverParameters const &Other, VehicleEnd const OtherEnd) const +bool physics::Vehicle::ControlCouplingAllowed(VehicleEnd const End, physics::Vehicle const &Other, VehicleEnd const OtherEnd) const { if (false == Global.control_coupling_engine_check) { @@ -246,7 +246,7 @@ bool TMoverParameters::ControlCouplingAllowed(VehicleEnd const End, TMoverParame return traction == traction_kind::none || othertraction == traction_kind::none || traction == othertraction; } -CouplingSet TMoverParameters::CompatibleCoupling(VehicleEnd const End, TMoverParameters const &Other, VehicleEnd const OtherEnd, CouplingSet const CouplingType) const +CouplingSet physics::Vehicle::CompatibleCoupling(VehicleEnd const End, physics::Vehicle const &Other, VehicleEnd const OtherEnd, CouplingSet const CouplingType) const { if (false == CouplingType.HasAny(Coupling::control) || CouplingType.HasAny(Coupling::permanent) || ControlCouplingAllowed(End, Other, OtherEnd)) { @@ -259,7 +259,7 @@ CouplingSet TMoverParameters::CompatibleCoupling(VehicleEnd const End, TMoverPar // Q: 20160713 // Obliczanie sił dzialających na sprzęgach // ************************************************************************************************* -double TMoverParameters::CouplerForce(VehicleEnd const End, double dt) +double physics::Vehicle::CouplerForce(VehicleEnd const End, double dt) { if (coupler_physics_at(End)) { @@ -267,7 +267,7 @@ double TMoverParameters::CouplerForce(VehicleEnd const End, double dt) } auto &thiscoupler{Couplers[End]}; - auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; + auto *othervehicle{Neighbours[End].vehicle->physics}; auto const otherend{Neighbours[End].FacingEnd()}; auto const &othercoupler{othervehicle->Couplers[otherend]}; @@ -385,7 +385,7 @@ double TMoverParameters::CouplerForce(VehicleEnd const End, double dt) } // a coupler stretched with more than its strength for over a second breaks, the more likely the longer, with crash damage on -void TMoverParameters::CouplerStretchCheck(VehicleEnd const End, double const CF, double dt) +void physics::Vehicle::CouplerStretchCheck(VehicleEnd const End, double const CF, double dt) { auto &thiscoupler{Couplers[End]}; if (std::abs(CF) > thiscoupler.FmaxC) @@ -405,7 +405,7 @@ void TMoverParameters::CouplerStretchCheck(VehicleEnd const End, double const CF } } -bool TMoverParameters::coupler_physics_at(VehicleEnd const End) const +bool physics::Vehicle::coupler_physics_at(VehicleEnd const End) const { if (false == Global.coupler_physics) { @@ -417,10 +417,10 @@ bool TMoverParameters::coupler_physics_at(VehicleEnd const End) const } // either vehicle of the pair covered takes the pair in, so both of them compute it the same way auto const *other{Neighbours[End].vehicle}; - return other != nullptr && other->MoverParameters->CouplerPhysics; + return other != nullptr && other->physics->CouplerPhysics; } -void TMoverParameters::automatic_coupling(VehicleEnd const End, TMoverParameters &Other, VehicleEnd const OtherEnd) +void physics::Vehicle::automatic_coupling(VehicleEnd const End, physics::Vehicle &Other, VehicleEnd const OtherEnd) { auto &thiscoupler{Couplers[End]}; auto &othercoupler{Other.Couplers[OtherEnd]}; @@ -490,10 +490,10 @@ int coupler_sounds(coupler_sound_input const &Input) } // namespace -double TMoverParameters::coupler_force_physical(VehicleEnd const End, double const dt) +double physics::Vehicle::coupler_force_physical(VehicleEnd const End, double const dt) { auto &thiscoupler{Couplers[End]}; - auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; + auto *othervehicle{Neighbours[End].vehicle->physics}; auto const otherend{Neighbours[End].FacingEnd()}; auto &othercoupler{othervehicle->Couplers[otherend]}; auto &state{thiscoupler.physics_state}; @@ -547,7 +547,7 @@ double TMoverParameters::coupler_force_physical(VehicleEnd const End, double con return force; } -bool TMoverParameters::coupler_stop_hit(VehicleEnd const End, TMoverParameters &Other, VehicleEnd const OtherEnd) +bool physics::Vehicle::coupler_stop_hit(VehicleEnd const End, physics::Vehicle &Other, VehicleEnd const OtherEnd) { auto &thiscoupler{Couplers[End]}; auto &othercoupler{Other.Couplers[OtherEnd]}; diff --git a/physics/components/diesel.cpp b/physics/components/diesel.cpp index aee5d8e21..034a11793 100644 --- a/physics/components/diesel.cpp +++ b/physics/components/diesel.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. // the diesel engine: its revolutions, the gearbox, the clutch, the hydraulic transmission, its heat and pumps #include "stdafx.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/DynObj.h" #include "physics/oerlikonest.h" #include "utilities/Globals.h" @@ -31,23 +31,23 @@ http://mozilla.org/MPL/2.0/. #include "physics/components/drive.h" -double TMoverParameters::EngineRPMRatio() const +double physics::Vehicle::EngineRPMRatio() const { return Drive().EngineRpmRatio(*this); } -double TMoverParameters::EngineIdleRPM() const +double physics::Vehicle::EngineIdleRPM() const { return Drive().EngineIdleRpm(*this); } -double TMoverParameters::EngineMaxRPM() const +double physics::Vehicle::EngineMaxRPM() const { return Drive().EngineMaxRpm(*this); } // water pump status check -void TMoverParameters::WaterPumpCheck(double const /*Timestep*/) +void physics::Vehicle::WaterPumpCheck(double const /*Timestep*/) { // NOTE: breaker override with start type is sm42 specific hack, replace with ability to define the presence of the breaker WaterPump.is_active = true == (Power24vIsAvailable || Power110vIsAvailable) && true == WaterPump.breaker && false == WaterPump.is_disabled && @@ -55,7 +55,7 @@ void TMoverParameters::WaterPumpCheck(double const /*Timestep*/) } // water heater status check -void TMoverParameters::WaterHeaterCheck(double const /*Timestep*/) +void physics::Vehicle::WaterHeaterCheck(double const /*Timestep*/) { WaterHeater.is_active = false == WaterHeater.is_damaged && true == (Power24vIsAvailable || Power110vIsAvailable) && true == WaterHeater.is_enabled && true == WaterHeater.breaker && @@ -70,7 +70,7 @@ void TMoverParameters::WaterHeaterCheck(double const /*Timestep*/) } // fuel pump status update -void TMoverParameters::FuelPumpCheck(double const /*Timestep*/) +void physics::Vehicle::FuelPumpCheck(double const /*Timestep*/) { using enum start_t; @@ -82,7 +82,7 @@ void TMoverParameters::FuelPumpCheck(double const /*Timestep*/) } // oil pump status update -void TMoverParameters::OilPumpCheck(double const Timestep) +void physics::Vehicle::OilPumpCheck(double const Timestep) { OilPump.is_active = true == (Power24vIsAvailable || Power110vIsAvailable) && false == Mains && false == OilPump.is_disabled && @@ -110,7 +110,7 @@ void TMoverParameters::OilPumpCheck(double const Timestep) } // water pump breaker state toggle -bool TMoverParameters::WaterPumpBreakerSwitch(bool State, range_t const Notify) +bool physics::Vehicle::WaterPumpBreakerSwitch(bool State, range_t const Notify) { /* if( FuelPump.start_type == start::automatic ) { @@ -131,7 +131,7 @@ bool TMoverParameters::WaterPumpBreakerSwitch(bool State, range_t const Notify) } // water pump state toggle -bool TMoverParameters::WaterPumpSwitch(bool State, range_t const Notify) +bool physics::Vehicle::WaterPumpSwitch(bool State, range_t const Notify) { if (WaterPump.start_type == start_t::battery) @@ -153,7 +153,7 @@ bool TMoverParameters::WaterPumpSwitch(bool State, range_t const Notify) } // water pump state toggle -bool TMoverParameters::WaterPumpSwitchOff(bool State, range_t const Notify) +bool physics::Vehicle::WaterPumpSwitchOff(bool State, range_t const Notify) { if (WaterPump.start_type == start_t::battery) @@ -175,7 +175,7 @@ bool TMoverParameters::WaterPumpSwitchOff(bool State, range_t const Notify) } // water heater breaker state toggle -bool TMoverParameters::WaterHeaterBreakerSwitch(bool State, range_t const Notify) +bool physics::Vehicle::WaterHeaterBreakerSwitch(bool State, range_t const Notify) { /* if( FuelPump.start_type == start::automatic ) { @@ -196,7 +196,7 @@ bool TMoverParameters::WaterHeaterBreakerSwitch(bool State, range_t const Notify } // water heater state toggle -bool TMoverParameters::WaterHeaterSwitch(bool State, range_t const Notify) +bool physics::Vehicle::WaterHeaterSwitch(bool State, range_t const Notify) { /* if( FuelPump.start_type == start::automatic ) { @@ -217,7 +217,7 @@ bool TMoverParameters::WaterHeaterSwitch(bool State, range_t const Notify) } // water circuits link state toggle -bool TMoverParameters::WaterCircuitsLinkSwitch(bool State, range_t const Notify) +bool physics::Vehicle::WaterCircuitsLinkSwitch(bool State, range_t const Notify) { if (false == diesel.heat.auxiliary_water_circuit) @@ -239,7 +239,7 @@ bool TMoverParameters::WaterCircuitsLinkSwitch(bool State, range_t const Notify) } // fuel pump state toggle -bool TMoverParameters::FuelPumpSwitch(bool State, range_t const Notify) +bool physics::Vehicle::FuelPumpSwitch(bool State, range_t const Notify) { if (FuelPump.start_type == start_t::automatic) @@ -260,7 +260,7 @@ bool TMoverParameters::FuelPumpSwitch(bool State, range_t const Notify) return FuelPump.is_enabled != initialstate; } -bool TMoverParameters::FuelPumpSwitchOff(bool State, range_t const Notify) +bool physics::Vehicle::FuelPumpSwitchOff(bool State, range_t const Notify) { if (FuelPump.start_type == start_t::automatic) @@ -282,7 +282,7 @@ bool TMoverParameters::FuelPumpSwitchOff(bool State, range_t const Notify) } // oil pump state toggle -bool TMoverParameters::OilPumpSwitch(bool State, range_t const Notify) +bool physics::Vehicle::OilPumpSwitch(bool State, range_t const Notify) { if (OilPump.start_type == start_t::automatic) @@ -303,7 +303,7 @@ bool TMoverParameters::OilPumpSwitch(bool State, range_t const Notify) return OilPump.is_enabled != initialstate; } -bool TMoverParameters::OilPumpSwitchOff(bool State, range_t const Notify) +bool physics::Vehicle::OilPumpSwitchOff(bool State, range_t const Notify) { if (OilPump.start_type == start_t::automatic) @@ -326,13 +326,13 @@ bool TMoverParameters::OilPumpSwitchOff(bool State, range_t const Notify) // the revolutions of the engine; returns those a diesel-electric engine aims at [1/s], 0 for the others. // for a diesel engine, the ratio of the transmission and the engine's moment -double TMoverParameters::UpdateEngineRevolutions(double dt, double &dtrans, double &dmoment) +double physics::Vehicle::UpdateEngineRevolutions(double dt, double &dtrans, double &dmoment) { return Drive().UpdateEngineRevolutions(*this, dt, dtrans, dmoment); } // the revolutions a diesel-electric's engine aims at [1/s], by the controller and the heating; the fill shown by the smoke -double TMoverParameters::DieselElectricTargetRevolutions() +double physics::Vehicle::DieselElectricTargetRevolutions() { double tmp; @@ -351,7 +351,7 @@ double TMoverParameters::DieselElectricTargetRevolutions() return tmp; } -void TMoverParameters::DieselEngineTractionForce(double dt, double const dmoment, double const dtrans) +void physics::Vehicle::DieselEngineTractionForce(double dt, double const dmoment, double const dtrans) { Mw = dmoment * dtrans * Transmision.Efficiency; // dmoment i dtrans policzone przy okazji enginerotation if (retarder.present && retarder.placement == 0) @@ -362,7 +362,7 @@ void TMoverParameters::DieselEngineTractionForce(double dt, double const dmoment } // tmp: the revolutions the engine aims at [1/s], see UpdateEngineRevolutions() -void TMoverParameters::DieselElectricTractionForce(double tmp) +void physics::Vehicle::DieselElectricTractionForce(double tmp) { double PosRatio; // tmpV:=V*CabActive*DirActive; @@ -446,7 +446,7 @@ void TMoverParameters::DieselElectricTractionForce(double tmp) // the tractive force of a diesel-electric shunting, by the generator's table SST and the shunting controller AnPos; // tmp, the power the generator gives -void TMoverParameters::DieselElectricShuntForce(double const tmpV, double &tmp) +void physics::Vehicle::DieselElectricShuntForce(double const tmpV, double &tmp) { if (true == StLinFlag) { @@ -465,7 +465,7 @@ void TMoverParameters::DieselElectricShuntForce(double const tmpV, double &tmp) // the tractive force of a diesel-electric set by the integrated controller, at the speed tmpV; the generator's // voltage and current limits too. returns the power the generator gives -double TMoverParameters::DieselElectricDigitalForce(double const tmpV, double &tempUmax, double &tempImax) +double physics::Vehicle::DieselElectricDigitalForce(double const tmpV, double &tempUmax, double &tempImax) { auto eimic_positive = std::max(0.0, eimic_real); auto const rpmratio{EngineRPMRatio()}; @@ -481,7 +481,7 @@ double TMoverParameters::DieselElectricDigitalForce(double const tmpV, double &t // the tractive force of a diesel-electric at the speed tmpV: on the straight part of its characteristic under the speed // Vhyp gives at the power LinePower, at the share Ratio of it, on the hyperbola of the power HyperbolaPower over it -double TMoverParameters::DieselElectricForce(double const tmpV, double const LinePower, double const Ratio, double const HyperbolaPower) const +double physics::Vehicle::DieselElectricForce(double const tmpV, double const LinePower, double const Ratio, double const HyperbolaPower) const { if (tmpV < Vhyp * LinePower / DElist[MainCtrlPosNo].GenPower) { @@ -494,7 +494,7 @@ double TMoverParameters::DieselElectricForce(double const tmpV, double const Lin } // in the shunting mode, the generator's power limited to tmp, the power the engine gives -void TMoverParameters::DieselElectricShuntPower(double const tmp) +void physics::Vehicle::DieselElectricShuntPower(double const tmp) { EnginePower = EngineVoltage * Im / 1000.0; if (EnginePower > tmp) @@ -509,7 +509,7 @@ void TMoverParameters::DieselElectricShuntPower(double const tmp) } // the generator's current limited to tempImax and its voltage by its characteristic, under tempUmax and the power tmp -void TMoverParameters::DieselElectricGenerator(double const tmp, double const tempUmax, double const tempImax) +void physics::Vehicle::DieselElectricGenerator(double const tmp, double const tempUmax, double const tempImax) { if (abs(Im) > tempImax) { // nie ma nadmiarowego, tylko Imax i zwarcie na pradnicy @@ -555,7 +555,7 @@ void TMoverParameters::DieselElectricGenerator(double const tmp, double const te } // the current of a diesel-electric vehicle's traction motors giving the moment [N m] of one motor -double TMoverParameters::dieselelectric_motor_current(double const Moment) const +double physics::Vehicle::dieselelectric_motor_current(double const Moment) const { // with MotorParam[ScndCtrlPos] do if (abs(Moment) > motor_param(ScndCtrlPos).fi) @@ -565,7 +565,7 @@ double TMoverParameters::dieselelectric_motor_current(double const Moment) const } // the effort of a diesel-electric vehicle's dynamic brake the driver asks for, 0..1 -double TMoverParameters::dieselelectric_dynamic_brake_demand() const +double physics::Vehicle::dieselelectric_dynamic_brake_demand() const { switch (DEDynamicBrake.source) { @@ -582,7 +582,7 @@ double TMoverParameters::dieselelectric_dynamic_brake_demand() const // (the current), above the speed where the resistors' power takes over, the power; under EDBrakeV1 it fades, down to // nothing at EDBrakeV0. a brake of direct current motors, whose force grows with the speed (the voltage they generate // into the resistors), fades from 0 to the speed of its whole force; an inverter's only at the stop -double TMoverParameters::dieselelectric_dynamic_brake_limit() const +double physics::Vehicle::dieselelectric_dynamic_brake_limit() const { auto const &brake{DEDynamicBrake}; auto limit{brake.max_force}; @@ -605,7 +605,7 @@ double TMoverParameters::dieselelectric_dynamic_brake_limit() const // is the share of the most at the speed. the motors brake while the engine runs (it excites them, or keeps the // control of the inverters going), with the direction set, the overload relay closed, no power asked for and the // wheels rolling; otherwise there's no brake at once -void TMoverParameters::update_dieselelectric_dynamic_brake(double const dt) +void physics::Vehicle::update_dieselelectric_dynamic_brake(double const dt) { auto &brake{DEDynamicBrake}; auto const nopower{brake.source == diesel_electric_dynamic_brake::control::controller ? eimic_real <= 0.0 : IsMainCtrlNoPowerPos()}; @@ -630,7 +630,7 @@ void TMoverParameters::update_dieselelectric_dynamic_brake(double const dt) // work as generators into the resistors, the ammeter shows their current, the main generator gives nothing. near the // stop no more than what stops the vehicle within the step dt: with no fade (EDBrakeV0 = EDBrakeV1 = 0) the whole force // would turn round each time the speed crosses zero, and in FTrain it never lets the stop of ComputeMovement() catch it -void TMoverParameters::apply_dieselelectric_dynamic_brake(double const dt) +void physics::Vehicle::apply_dieselelectric_dynamic_brake(double const dt) { auto const force{dt > 0.0 ? std::min(DEDynamicBrake.force, TotalMass * std::abs(V) / dt) : DEDynamicBrake.force}; Ft = V > 0.0 ? -force : V < 0.0 ? force : 0.0; @@ -646,7 +646,7 @@ void TMoverParameters::apply_dieselelectric_dynamic_brake(double const dt) // Q: 20160715 // Zmienia parametr do którego dąży sprzęgło // ************************************************************************************************* -bool TMoverParameters::dizel_EngageSwitch(double state) +bool physics::Vehicle::dizel_EngageSwitch(double state) { if (EngineType == TEngineType::DieselEngine && state <= 1 && state >= 0 && state != diesel.clutchState) { @@ -661,7 +661,7 @@ bool TMoverParameters::dizel_EngageSwitch(double state) // Q: 20160715 // Zmienia parametr do którego dąży sprzęgło // ************************************************************************************************* -bool TMoverParameters::dizel_EngageChange(double dt) +bool physics::Vehicle::dizel_EngageChange(double dt) { double engagespeed = 0; // OK:boolean; bool DEC; @@ -695,7 +695,7 @@ bool TMoverParameters::dizel_EngageChange(double dt) // Q: 20160715 // Automatyczna zmiana biegów gdy prędkość przekroczy widełki // ************************************************************************************************* -bool TMoverParameters::dizel_AutoGearCheck(void) +bool physics::Vehicle::dizel_AutoGearCheck(void) { auto OK{false}; @@ -718,7 +718,7 @@ bool TMoverParameters::dizel_AutoGearCheck(void) } // the automatic gearbox: a gear up over VelUp, down under VelDown, changed once the clutch is out; returns whether it acted -bool TMoverParameters::dizel_GearShiftCheck(double const VelUp, double const VelDown) +bool physics::Vehicle::dizel_GearShiftCheck(double const VelUp, double const VelDown) { auto OK{false}; if (RList[MainCtrlPos].Mn == 0 && !torqueConverter.present) @@ -746,7 +746,7 @@ bool TMoverParameters::dizel_GearShiftCheck(double const VelUp, double const Vel } // a gear up asked over VelUp, down under VelDown, where the gearbox shifts by itself; returns whether one is -bool TMoverParameters::dizel_GearShiftRequest(double const VelUp, double const VelDown) +bool physics::Vehicle::dizel_GearShiftRequest(double const VelUp, double const VelDown) { auto OK{false}; if (motor_param(ScndCtrlActualPos).AutoSwitch && diesel.automaticGearShift == 0) // sprawdz czy zmienic biegi @@ -774,7 +774,7 @@ bool TMoverParameters::dizel_GearShiftRequest(double const VelUp, double const V } // the pressure in the clutch's cylinder, by the controller's position or the integrated controller -void TMoverParameters::dizel_ClutchCheck() +void physics::Vehicle::dizel_ClutchCheck() { if (EIMCtrlType > 0) // sterowanie komputerowe { @@ -791,7 +791,7 @@ void TMoverParameters::dizel_ClutchCheck() } // the clutch by the controller's position: half or fully in, fully over the speed of the full engagement -void TMoverParameters::dizel_ClutchByController() +void physics::Vehicle::dizel_ClutchByController() { switch (RList[MainCtrlPos].Mn) { @@ -828,7 +828,7 @@ void TMoverParameters::dizel_ClutchByController() } // the clutch of the integrated controller: in with the converter filled or the power asked, half in for the retarder -void TMoverParameters::dizel_ClutchByIntegratedController() +void physics::Vehicle::dizel_ClutchByIntegratedController() { if (diesel.automaticGearShift == 0) { @@ -844,7 +844,7 @@ void TMoverParameters::dizel_ClutchByIntegratedController() } // performs diesel engine startup procedure; potentially clears startup switch; returns: true if the engine can be started, false otherwise -bool TMoverParameters::dizel_StartupCheck() +bool physics::Vehicle::dizel_StartupCheck() { auto engineisready{true}; // make inital optimistic presumption, then watch the reality crush it @@ -884,7 +884,7 @@ bool TMoverParameters::dizel_StartupCheck() // Q: 20160715 // Aktualizacja stanu silnika // ************************************************************************************************* -bool TMoverParameters::dizel_Update(double dt) +bool physics::Vehicle::dizel_Update(double dt) { WaterPumpCheck(dt); @@ -944,7 +944,7 @@ bool TMoverParameters::dizel_Update(double dt) // Q: 20160715 // oblicza napelnienie, uzwglednia regulator obrotow // ************************************************************************************************* -double TMoverParameters::dizel_fillcheck(int mcp, double dt) +double physics::Vehicle::dizel_fillcheck(int mcp, double dt) { auto realfill{0.0}; @@ -981,7 +981,7 @@ double TMoverParameters::dizel_fillcheck(int mcp, double dt) } // the fill set by the integrated controller, and the idle and top revolutions the governor keeps to -double TMoverParameters::dizel_DigitalFill(double dt) +double physics::Vehicle::dizel_DigitalFill(double dt) { double realfill; realfill = std::max(0.0, std::min(eimic_real, 1 - motor_param(ScndCtrlActualPos).Isat)); @@ -1008,7 +1008,7 @@ double TMoverParameters::dizel_DigitalFill(double dt) } // the fill cut off over the revolutions the governor allows at the controller's position, or full under the idle ones -double TMoverParameters::dizel_GovernorFill(int const mcp, double realfill) const +double physics::Vehicle::dizel_GovernorFill(int const mcp, double realfill) const { auto nreg{0.0}; if (EIMCtrlType > 0) @@ -1024,7 +1024,7 @@ double TMoverParameters::dizel_GovernorFill(int const mcp, double realfill) cons // the revolutions the governor allows at the controller's position, the gearbox and the speed; the fill cut off at // a position the governor doesn't know -double TMoverParameters::dizel_GovernorRevolutions(int const mcp, double &realfill) const +double physics::Vehicle::dizel_GovernorRevolutions(int const mcp, double &realfill) const { auto nreg{0.0}; switch (RList[MainCtrlPos].Mn) @@ -1068,7 +1068,7 @@ double TMoverParameters::dizel_GovernorRevolutions(int const mcp, double &realfi // Q: 20160715 // Oblicza moment siły wytwarzany przez silnik spalinowy // ************************************************************************************************* -double TMoverParameters::dizel_Momentum(double Fill, double n, double dt) +double physics::Vehicle::dizel_Momentum(double Fill, double n, double dt) { // liczy moment sily wytwarzany przez silnik spalinowy} double Moment = 0; double enMoment = 0; @@ -1197,7 +1197,7 @@ double TMoverParameters::dizel_Momentum(double Fill, double n, double dt) } // the torque converter filled and emptied, and its lockup clutch engaged and released, by the power and the speed -void TMoverParameters::hydro_TCFillCheck(double dt) +void physics::Vehicle::hydro_TCFillCheck(double dt) { if (torqueConverter.present) // jesli przetwornik momentu { @@ -1234,7 +1234,7 @@ void TMoverParameters::hydro_TCFillCheck(double dt) } // the torque converter's moments on its input and output shafts, by their revolutions and its fill -void TMoverParameters::hydro_TCTorque() +void physics::Vehicle::hydro_TCTorque() { double HydroTorque = 0; HydroTorque += torqueConverter.revolutionsIn * torqueConverter.revolutionsIn * torqueConverter.torqueInIn; @@ -1264,7 +1264,7 @@ void TMoverParameters::hydro_TCTorque() } } -double TMoverParameters::dizel_MomentumRetarder(double n, double dt) +double physics::Vehicle::dizel_MomentumRetarder(double n, double dt) { double RetarderRequest = Mains ? std::max(0.0, -eimic_real) : 0; if (retarder.withIndividual) @@ -1312,7 +1312,7 @@ double TMoverParameters::dizel_MomentumRetarder(double n, double dt) } // sets component temperatures to specified value -void TMoverParameters::dizel_HeatSet(float const Value) +void physics::Vehicle::dizel_HeatSet(float const Value) { // TODO: don't include ambient temperature, pull it from environment data instead @@ -1330,7 +1330,7 @@ void TMoverParameters::dizel_HeatSet(float const Value) // calculates diesel engine temperature and heat transfers // adapted from scripts written by adamst // NOTE: originally executed twice per second -void TMoverParameters::dizel_Heat(double const dt) +void physics::Vehicle::dizel_Heat(double const dt) { auto const qs{44700.0}; diff --git a/physics/components/doors.cpp b/physics/components/doors.cpp index 216279bef..2e90c2a88 100644 --- a/physics/components/doors.cpp +++ b/physics/components/doors.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. // the doors and the exchange of the load #include "stdafx.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/DynObj.h" #include "physics/oerlikonest.h" #include "utilities/Globals.h" @@ -30,7 +30,7 @@ http://mozilla.org/MPL/2.0/. #include "physics/components/internal.h" -bool TMoverParameters::AssignLoad(std::string const &Loadname, float const Amount) +bool physics::Vehicle::AssignLoad(std::string const &Loadname, float const Amount) { if (Loadname == "pantstate") @@ -104,7 +104,7 @@ bool TMoverParameters::AssignLoad(std::string const &Loadname, float const Amoun // Q: 20160713 // Test zakończenia załadunku / rozładunku // ************************************************************************************************* -bool TMoverParameters::LoadingDone(double const LSpeed, std::string_view Loadname) +bool physics::Vehicle::LoadingDone(double const LSpeed, std::string_view Loadname) { if (LSpeed == 0.0) @@ -170,7 +170,7 @@ bool TMoverParameters::LoadingDone(double const LSpeed, std::string_view Loadnam return LoadStatus >= 4; } -bool TMoverParameters::ChangeDoorPermitPreset(int const Change, range_t const Notify) +bool physics::Vehicle::ChangeDoorPermitPreset(int const Change, range_t const Notify) { auto const initialstate{Doors.permit_preset}; @@ -190,7 +190,7 @@ bool TMoverParameters::ChangeDoorPermitPreset(int const Change, range_t const No return Doors.permit_preset != initialstate; } -bool TMoverParameters::PermitDoorStep(bool const State, range_t const Notify) +bool physics::Vehicle::PermitDoorStep(bool const State, range_t const Notify) { auto const initialstate{Doors.step_enabled}; @@ -205,7 +205,7 @@ bool TMoverParameters::PermitDoorStep(bool const State, range_t const Notify) return Doors.step_enabled != initialstate; } -bool TMoverParameters::PermitDoors(VehicleSide const Door, bool const State, range_t const Notify) +bool physics::Vehicle::PermitDoors(VehicleSide const Door, bool const State, range_t const Notify) { bool const initialstate{Doors.instances[Door].open_permit}; @@ -226,7 +226,7 @@ bool TMoverParameters::PermitDoors(VehicleSide const Door, bool const State, ran return Doors.instances[Door].open_permit != initialstate; } -void TMoverParameters::PermitDoors_(VehicleSide const Door, bool const State) +void physics::Vehicle::PermitDoors_(VehicleSide const Door, bool const State) { if (State && State != Doors.instances[Door].open_permit) @@ -236,7 +236,7 @@ void TMoverParameters::PermitDoors_(VehicleSide const Door, bool const State) Doors.instances[Door].open_permit = State; } -bool TMoverParameters::ChangeDoorControlMode(bool const State, range_t const Notify) +bool physics::Vehicle::ChangeDoorControlMode(bool const State, range_t const Notify) { auto const initialstate{Doors.remote_only}; @@ -259,7 +259,7 @@ bool TMoverParameters::ChangeDoorControlMode(bool const State, range_t const Not return Doors.remote_only != initialstate; } -bool TMoverParameters::OperateDoors(VehicleSide const Door, bool const State, range_t const Notify) +bool physics::Vehicle::OperateDoors(VehicleSide const Door, bool const State, range_t const Notify) { auto &door{Doors.instances[Door]}; @@ -303,7 +303,7 @@ bool TMoverParameters::OperateDoors(VehicleSide const Door, bool const State, ra } // toggle door lock -bool TMoverParameters::LockDoors(bool const State, range_t const Notify) +bool physics::Vehicle::LockDoors(bool const State, range_t const Notify) { auto const initialstate{Doors.lock_enabled}; @@ -319,7 +319,7 @@ bool TMoverParameters::LockDoors(bool const State, range_t const Notify) } // toggles departure warning -bool TMoverParameters::signal_departure(bool const State, range_t const Notify) +bool physics::Vehicle::signal_departure(bool const State, range_t const Notify) { if (DepartureSignal == State) @@ -341,7 +341,7 @@ bool TMoverParameters::signal_departure(bool const State, range_t const Notify) // state of the door closure signalling (SOD) of this vehicle: open while a door isn't fully closed, released while // the closed doors can be opened (a permit given, or, for doors that need none, no lock engaged), locked otherwise. // doors the crew doesn't close (autonomous) aren't signalled, the same as for the door lights of the consist -door_closure_t TMoverParameters::door_closure() const +door_closure_t physics::Vehicle::door_closure() const { if (Doors.range == 0.f || Doors.close_control == control_t::autonomous) { @@ -362,7 +362,7 @@ door_closure_t TMoverParameters::door_closure() const return door_closure_t::released; } -bool TMoverParameters::door_closure_lamp_lit(door_closure_t const Consist, bool const BlinkLit) const +bool physics::Vehicle::door_closure_lamp_lit(door_closure_t const Consist, bool const BlinkLit) const { return Doors.closure_signal ? door_closure_lamp(Consist, BlinkLit) : Doors.is_locked; } @@ -381,7 +381,7 @@ bool door_closure_lamp(door_closure_t const State, bool const BlinkLit) } // automatic door controller update -void TMoverParameters::update_doors(double const Deltatime) +void physics::Vehicle::update_doors(double const Deltatime) { if (Doors.range == 0.f) @@ -429,7 +429,7 @@ void TMoverParameters::update_doors(double const Deltatime) } // the permit, the state and the requests of a door, and whether it and its step open or close -void TMoverParameters::update_door_requests(basic_door &door, bool const localopencontrol, bool const remoteopencontrol, bool const localclosecontrol, bool const remoteclosecontrol) +void physics::Vehicle::update_door_requests(basic_door &door, bool const localopencontrol, bool const remoteopencontrol, bool const localclosecontrol, bool const remoteclosecontrol) { // revoke permit if... door.open_permit = true == door.open_permit // ...we already have one... @@ -462,7 +462,7 @@ void TMoverParameters::update_door_requests(basic_door &door, bool const localop } // whether the door is asked to open, by the passengers, from afar or by itself -bool TMoverParameters::door_open_request(basic_door const &door, bool const localopencontrol, bool const remoteopencontrol) const +bool physics::Vehicle::door_open_request(basic_door const &door, bool const localopencontrol, bool const remoteopencontrol) const { auto const autoopenrequest{Doors.open_control == control_t::autonomous && (false == Doors.permit_needed || door.open_permit)}; return (localopencontrol && door.local_open) || (remoteopencontrol && door.remote_open) || (autoopenrequest && false == door.is_open); @@ -470,7 +470,7 @@ bool TMoverParameters::door_open_request(basic_door const &door, bool const loca // whether the door is asked to close, by the passengers, from afar, or by itself: over the speed, after its time or // with its permit taken back -bool TMoverParameters::door_close_request(basic_door const &door, bool const localclosecontrol, bool const remoteclosecontrol) const +bool physics::Vehicle::door_close_request(basic_door const &door, bool const localclosecontrol, bool const remoteclosecontrol) const { auto const autocloserequest{(Doors.auto_velocity != -1.f && Vel > Doors.auto_velocity) || (door.auto_timer != -1.f && door.auto_timer <= 0.f) || (Doors.permit_needed && false == door.open_permit)}; @@ -478,7 +478,7 @@ bool TMoverParameters::door_close_request(basic_door const &door, bool const loc } // whether the doors have the voltage they work on -bool TMoverParameters::doors_powered() const +bool physics::Vehicle::doors_powered() const { if (Doors.voltage == 0) { @@ -493,7 +493,7 @@ bool TMoverParameters::doors_powered() const // whether the unfolded step folds: without the permission to stay out, or with the door closing, once it's about to // close or closed -bool TMoverParameters::door_step_folding(basic_door const &door) const +bool physics::Vehicle::door_step_folding(basic_door const &door) const { auto const unfolded{door.step_position > 0.f}; auto const mayfold{false == Doors.step_enabled || (Doors.permit_needed ? false == door.open_permit : door.is_closing)}; @@ -502,7 +502,7 @@ bool TMoverParameters::door_step_folding(basic_door const &door) const // how long the opening door stays open: the time of the doors, for the passengers' opening and, if it counts, the // opening from afar; none otherwise -float TMoverParameters::door_open_duration(basic_door const &door, bool const localopencontrol, bool const remoteopencontrol) const +float physics::Vehicle::door_open_duration(basic_door const &door, bool const localopencontrol, bool const remoteopencontrol) const { if (localopencontrol && door.local_open) { @@ -516,7 +516,7 @@ float TMoverParameters::door_open_duration(basic_door const &door, bool const lo } // a door and its step moved as they open or close -void TMoverParameters::move_door(basic_door &door, double const Deltatime) +void physics::Vehicle::move_door(basic_door &door, double const Deltatime) { // doors if (true == door.is_opening) @@ -568,7 +568,7 @@ void TMoverParameters::move_door(basic_door &door, double const Deltatime) } // the timers of the open doors which close after a while, kept running while the load is exchanged -void TMoverParameters::update_door_timers(double const Deltatime) +void physics::Vehicle::update_door_timers(double const Deltatime) { // update door timers if the door close after defined time for (auto &door : Doors.instances) diff --git a/physics/components/drive.cpp b/physics/components/drive.cpp index 2b24c0d6e..537bba01d 100644 --- a/physics/components/drive.cpp +++ b/physics/components/drive.cpp @@ -16,88 +16,88 @@ http://mozilla.org/MPL/2.0/. #include #include -#include "physics/mover.h" +#include "physics/vehicle.h" #include "utilities/utilities.h" // the defaults: a drive with no engine model and no engine of revolutions does nothing in the steps -double TractionDrive::UpdateEnginePower(TMoverParameters & /*vehicle*/) const +double TractionDrive::UpdateEnginePower(physics::Vehicle & /*vehicle*/) const { return 0.0; } -void TractionDrive::BeforeTractionForce(TMoverParameters & /*vehicle*/, double /*dt*/) const +void TractionDrive::BeforeTractionForce(physics::Vehicle & /*vehicle*/, double /*dt*/) const { // nothing before the force } -void TractionDrive::UpdateTractionForce(TMoverParameters & /*vehicle*/, DriveStep const & /*step*/) const +void TractionDrive::UpdateTractionForce(physics::Vehicle & /*vehicle*/, DriveStep const & /*step*/) const { // no force } -void TractionDrive::AfterTractionForce(TMoverParameters & /*vehicle*/) const +void TractionDrive::AfterTractionForce(physics::Vehicle & /*vehicle*/) const { // nothing after the force } -void TractionDrive::UpdateVentilators(TMoverParameters & /*vehicle*/, double /*dt*/) const +void TractionDrive::UpdateVentilators(physics::Vehicle & /*vehicle*/, double /*dt*/) const { // no ventilators } -double TractionDrive::ShowCurrent(TMoverParameters const &vehicle, int const ammeter) const +double TractionDrive::ShowCurrent(physics::Vehicle const &vehicle, int const ammeter) const { return vehicle.ShowCurrentP(ammeter); } -double TractionDrive::EngineRpmRatio(TMoverParameters const & /*vehicle*/) const +double TractionDrive::EngineRpmRatio(physics::Vehicle const & /*vehicle*/) const { return 1.0; } -double TractionDrive::EngineIdleRpm(TMoverParameters const & /*vehicle*/) const +double TractionDrive::EngineIdleRpm(physics::Vehicle const & /*vehicle*/) const { return std::numeric_limits::max(); } -double TractionDrive::EngineMaxRpm(TMoverParameters const & /*vehicle*/) const +double TractionDrive::EngineMaxRpm(physics::Vehicle const & /*vehicle*/) const { return std::numeric_limits::max(); } -double TractionDrive::UpdateEngineRevolutions(TMoverParameters &vehicle, double /*dt*/, double & /*transmission*/, double & /*moment*/) const +double TractionDrive::UpdateEngineRevolutions(physics::Vehicle &vehicle, double /*dt*/, double & /*transmission*/, double & /*moment*/) const { vehicle.enrot = vehicle.Transmision.Ratio * vehicle.nrot; return 0.0; } -bool TractionDrive::IncreaseMainController(TMoverParameters & /*vehicle*/, int /*speed*/) const +bool TractionDrive::IncreaseMainController(physics::Vehicle & /*vehicle*/, int /*speed*/) const { return false; } -bool TractionDrive::DecreaseMainController(TMoverParameters & /*vehicle*/, int /*speed*/) const +bool TractionDrive::DecreaseMainController(physics::Vehicle & /*vehicle*/, int /*speed*/) const { return false; } -bool TractionDrive::MainsPowerAvailable(TMoverParameters const & /*vehicle*/) const +bool TractionDrive::MainsPowerAvailable(physics::Vehicle const & /*vehicle*/) const { return true; } -void TractionDrive::CheckVoltageRelays(TMoverParameters & /*vehicle*/) const +void TractionDrive::CheckVoltageRelays(physics::Vehicle & /*vehicle*/) const { // no voltage relays } -bool TractionDrive::UpdateEngine(TMoverParameters & /*vehicle*/, double /*dt*/) const +bool TractionDrive::UpdateEngine(physics::Vehicle & /*vehicle*/, double /*dt*/) const { return false; } -void TractionDrive::UpdateEngineVoltage(TMoverParameters &vehicle, double /*dt*/) const +void TractionDrive::UpdateEngineVoltage(physics::Vehicle &vehicle, double /*dt*/) const { vehicle.EngineVoltage = vehicle.Power > 1.0 ? vehicle.TractionSupplyVoltage() : 0.0; } @@ -106,7 +106,7 @@ namespace { // the radiator fans of a diesel engine follow their demanded revolutions while the engine runs, and run down without it -void updateRadiatorFans(TMoverParameters &vehicle, double const dt) +void updateRadiatorFans(physics::Vehicle &vehicle, double const dt) { auto &heat{vehicle.diesel.heat}; if (true == vehicle.Mains) @@ -123,14 +123,14 @@ void updateRadiatorFans(TMoverParameters &vehicle, double const dt) // the line breaker of the drives fed from the line: closed ahead of the pantographs it runs on the low voltage circuits, // else it needs the voltage of the source -bool linePowerAvailable(TMoverParameters const &vehicle) +bool linePowerAvailable(physics::Vehicle const &vehicle) { return vehicle.PantographsRequireMains ? vehicle.Power24vIsAvailable || vehicle.Power110vIsAvailable : vehicle.EnginePowerSourceVoltage() > 0.5 * vehicle.EnginePowerSource.MaxVoltage; } // a notch of the master controller of the drives without steps of their own (no engine, Dumb, diesel-electric, // induction): one position at a time, the speed control let go when the position leaves the one it holds -bool increaseNotch(TMoverParameters &vehicle, int const speed) +bool increaseNotch(physics::Vehicle &vehicle, int const speed) { if (speed > 1) { @@ -145,7 +145,7 @@ bool increaseNotch(TMoverParameters &vehicle, int const speed) return true; } -bool decreaseNotch(TMoverParameters &vehicle, int const speed) +bool decreaseNotch(physics::Vehicle &vehicle, int const speed) { if (speed == 1) { @@ -168,11 +168,11 @@ bool decreaseNotch(TMoverParameters &vehicle, int const speed) class NoEngineDrive final : public TractionDrive { public: - bool IncreaseMainController(TMoverParameters &vehicle, int const speed) const override + bool IncreaseMainController(physics::Vehicle &vehicle, int const speed) const override { return increaseNotch(vehicle, speed); } - bool DecreaseMainController(TMoverParameters &vehicle, int const speed) const override + bool DecreaseMainController(physics::Vehicle &vehicle, int const speed) const override { return decreaseNotch(vehicle, speed); } @@ -187,25 +187,25 @@ class UnmodelledDrive final : public TractionDrive class DumbDrive final : public TractionDrive { public: - double UpdateEnginePower(TMoverParameters &vehicle) const override + double UpdateEnginePower(physics::Vehicle &vehicle) const override { auto const posRatio{(vehicle.MainCtrlPos + vehicle.ScndCtrlPos) / (vehicle.MainCtrlPosNo + vehicle.ScndCtrlPosNo + 0.01)}; vehicle.EnginePower = /*1000.0 **/ vehicle.Power * posRatio; return posRatio; } - void UpdateTractionForce(TMoverParameters &vehicle, DriveStep const &step) const override + void UpdateTractionForce(physics::Vehicle &vehicle, DriveStep const &step) const override { vehicle.DumbTractionForce(step.posRatio); } - bool MainsPowerAvailable(TMoverParameters const &vehicle) const override + bool MainsPowerAvailable(physics::Vehicle const &vehicle) const override { return vehicle.Power24vIsAvailable; } - bool IncreaseMainController(TMoverParameters &vehicle, int const speed) const override + bool IncreaseMainController(physics::Vehicle &vehicle, int const speed) const override { return increaseNotch(vehicle, speed); } - bool DecreaseMainController(TMoverParameters &vehicle, int const speed) const override + bool DecreaseMainController(physics::Vehicle &vehicle, int const speed) const override { return decreaseNotch(vehicle, speed); } @@ -215,11 +215,11 @@ public: class WheelsDrivenDrive final : public TractionDrive { public: - void UpdateTractionForce(TMoverParameters &vehicle, DriveStep const &step) const override + void UpdateTractionForce(physics::Vehicle &vehicle, DriveStep const &step) const override { vehicle.WheelsDrivenTractionForce(step.dt); } - bool IncreaseMainController(TMoverParameters &vehicle, int const speed) const override + bool IncreaseMainController(physics::Vehicle &vehicle, int const speed) const override { return vehicle.AddPulseForce(speed); } @@ -229,19 +229,19 @@ public: class SeriesMotorDrive final : public TractionDrive { public: - void UpdateTractionForce(TMoverParameters &vehicle, DriveStep const &step) const override + void UpdateTractionForce(physics::Vehicle &vehicle, DriveStep const &step) const override { vehicle.SeriesMotorTractionForce(step.dt); } - bool IncreaseMainController(TMoverParameters &vehicle, int const speed) const override + bool IncreaseMainController(physics::Vehicle &vehicle, int const speed) const override { return vehicle.IncMainCtrlSeriesMotor(speed); } - bool DecreaseMainController(TMoverParameters &vehicle, int const speed) const override + bool DecreaseMainController(physics::Vehicle &vehicle, int const speed) const override { return vehicle.DecMainCtrlSeriesMotor(speed); } - void UpdateVentilators(TMoverParameters &vehicle, double const dt) const override + void UpdateVentilators(physics::Vehicle &vehicle, double const dt) const override { if (vehicle.MainCircuitPowered()) { @@ -252,11 +252,11 @@ public: vehicle.RventRot *= std::max(0.0, 1.0 - vehicle.RVentSpeed * dt); } } - bool MainsPowerAvailable(TMoverParameters const &vehicle) const override + bool MainsPowerAvailable(physics::Vehicle const &vehicle) const override { return linePowerAvailable(vehicle); } - void CheckVoltageRelays(TMoverParameters &vehicle) const override + void CheckVoltageRelays(physics::Vehicle &vehicle) const override { // update the state of voltage relays auto const voltage{std::max(vehicle.GetTrainsetHighVoltage(), vehicle.PantographVoltage)}; @@ -274,12 +274,12 @@ public: vehicle.EventFlag |= true == vehicle.Mains && ((false == vehicle.NoVoltRelay && false == vehicle.PantographsRequireMains) || false == vehicle.OvervoltageRelay) && vehicle.MainSwitch(false, vehicle.TrainType == train_type::emu ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide } - bool UpdateEngine(TMoverParameters &vehicle, double /*dt*/) const override + bool UpdateEngine(physics::Vehicle &vehicle, double /*dt*/) const override { // automatyczny rozruch return vehicle.AutoRelayCheck(); } - void UpdateEngineVoltage(TMoverParameters &vehicle, double const dt) const override + void UpdateEngineVoltage(physics::Vehicle &vehicle, double const dt) const override { vehicle.LastRelayTime += dt; // potem ulepszyc! pantogtrafy! @@ -300,19 +300,19 @@ public: class InductionMotorDrive final : public TractionDrive { public: - void UpdateTractionForce(TMoverParameters &vehicle, DriveStep const &step) const override + void UpdateTractionForce(physics::Vehicle &vehicle, DriveStep const &step) const override { vehicle.InductionMotorTractionForce(step.dt); } - bool IncreaseMainController(TMoverParameters &vehicle, int const speed) const override + bool IncreaseMainController(physics::Vehicle &vehicle, int const speed) const override { return increaseNotch(vehicle, speed); } - bool DecreaseMainController(TMoverParameters &vehicle, int const speed) const override + bool DecreaseMainController(physics::Vehicle &vehicle, int const speed) const override { return decreaseNotch(vehicle, speed); } - double ShowCurrent(TMoverParameters const &vehicle, int const ammeter) const override + double ShowCurrent(physics::Vehicle const &vehicle, int const ammeter) const override { switch (ammeter) { // do asynchronicznych @@ -324,11 +324,11 @@ public: return vehicle.ShowCurrentP(ammeter); } } - bool MainsPowerAvailable(TMoverParameters const &vehicle) const override + bool MainsPowerAvailable(physics::Vehicle const &vehicle) const override { return linePowerAvailable(vehicle); } - void CheckVoltageRelays(TMoverParameters &vehicle) const override + void CheckVoltageRelays(physics::Vehicle &vehicle) const override { // TODO: check if we can use instead the code for electricseriesmotor // nie wchodzić w funkcję bez potrzeby @@ -346,7 +346,7 @@ public: class DieselMechanicalDrive final : public TractionDrive { public: - double UpdateEnginePower(TMoverParameters &vehicle) const override + double UpdateEnginePower(physics::Vehicle &vehicle) const override { vehicle.diesel.power = vehicle.Mm * vehicle.enrot * (2.0 * M_PI / 1000.0); vehicle.EnginePower = (vehicle.diesel.standingMoment + vehicle.Mm) * vehicle.enrot * (2.0 * M_PI / 1000.0); @@ -357,11 +357,11 @@ public: } return 0.0; } - void UpdateTractionForce(TMoverParameters &vehicle, DriveStep const &step) const override + void UpdateTractionForce(physics::Vehicle &vehicle, DriveStep const &step) const override { vehicle.DieselEngineTractionForce(step.dt, step.moment, step.transmission); } - double UpdateEngineRevolutions(TMoverParameters &vehicle, double const dt, double &transmission, double &moment) const override + double UpdateEngineRevolutions(physics::Vehicle &vehicle, double const dt, double &transmission, double &moment) const override { if (vehicle.ShuntMode) // dodatkowa przekładnia np. dla 2Ls150 transmission = vehicle.AnPos * vehicle.Transmision.Ratio * vehicle.motor_param(vehicle.ScndCtrlActualPos).mIsat; @@ -371,7 +371,7 @@ public: moment = vehicle.dizel_Momentum(vehicle.diesel.fill, transmission * vehicle.nrot * vehicle.DirActive, dt); // oblicza tez enrot return 0.0; } - bool IncreaseMainController(TMoverParameters &vehicle, int const speed) const override + bool IncreaseMainController(physics::Vehicle &vehicle, int const speed) const override { if (speed > 1) { @@ -387,7 +387,7 @@ public: vehicle.CompressorAllow = vehicle.MainCtrlPowerPos() > 0; return true; } - bool DecreaseMainController(TMoverParameters &vehicle, int const speed) const override + bool DecreaseMainController(physics::Vehicle &vehicle, int const speed) const override { if (speed == 1) { @@ -402,28 +402,28 @@ public: } return false; } - void UpdateVentilators(TMoverParameters &vehicle, double const dt) const override + void UpdateVentilators(physics::Vehicle &vehicle, double const dt) const override { // NOTE: we update only radiator fans, as vehicles with diesel engine don't have other ventilators updateRadiatorFans(vehicle, dt); } - double EngineRpmRatio(TMoverParameters const &vehicle) const override + double EngineRpmRatio(physics::Vehicle const &vehicle) const override { return std::clamp(std::abs(vehicle.enrot) / vehicle.nmax, 0.0, 1.0); } - double EngineIdleRpm(TMoverParameters const &vehicle) const override + double EngineIdleRpm(physics::Vehicle const &vehicle) const override { return vehicle.diesel.minRevolutions * 60; } - double EngineMaxRpm(TMoverParameters const &vehicle) const override + double EngineMaxRpm(physics::Vehicle const &vehicle) const override { return vehicle.diesel.maxRevolutions * 60; } - bool MainsPowerAvailable(TMoverParameters const &vehicle) const override + bool MainsPowerAvailable(physics::Vehicle const &vehicle) const override { return vehicle.Power24vIsAvailable; } - bool UpdateEngine(TMoverParameters &vehicle, double const dt) const override + bool UpdateEngine(physics::Vehicle &vehicle, double const dt) const override { return vehicle.dizel_Update(dt); } @@ -433,19 +433,19 @@ public: class DieselElectricDrive final : public TractionDrive { public: - double UpdateEnginePower(TMoverParameters &vehicle) const override + double UpdateEnginePower(physics::Vehicle &vehicle) const override { vehicle.EnginePower = 0; // the actual calculation is done in two steps later in the method return 0.0; } - void BeforeTractionForce(TMoverParameters &vehicle, double const dt) const override + void BeforeTractionForce(physics::Vehicle &vehicle, double const dt) const override { - if (vehicle.DEDynamicBrake.source != TMoverParameters::diesel_electric_dynamic_brake::control::none) + if (vehicle.DEDynamicBrake.source != physics::Vehicle::diesel_electric_dynamic_brake::control::none) { vehicle.update_dieselelectric_dynamic_brake(dt); } } - void UpdateTractionForce(TMoverParameters &vehicle, DriveStep const &step) const override + void UpdateTractionForce(physics::Vehicle &vehicle, DriveStep const &step) const override { vehicle.DieselElectricTractionForce(step.revolutions); if (vehicle.DEDynamicBrake.level > 0.0) @@ -454,7 +454,7 @@ public: vehicle.apply_dieselelectric_dynamic_brake(step.dt); } } - double UpdateEngineRevolutions(TMoverParameters &vehicle, double const dt, double & /*transmission*/, double & /*moment*/) const override + double UpdateEngineRevolutions(physics::Vehicle &vehicle, double const dt, double & /*transmission*/, double & /*moment*/) const override { double target{0.0}; if (true == vehicle.Mains && true == vehicle.FuelPump.is_active) @@ -478,20 +478,20 @@ public: } return target; } - bool IncreaseMainController(TMoverParameters &vehicle, int const speed) const override + bool IncreaseMainController(physics::Vehicle &vehicle, int const speed) const override { return increaseNotch(vehicle, speed); } - bool DecreaseMainController(TMoverParameters &vehicle, int const speed) const override + bool DecreaseMainController(physics::Vehicle &vehicle, int const speed) const override { return decreaseNotch(vehicle, speed); } - void AfterTractionForce(TMoverParameters &vehicle) const override + void AfterTractionForce(physics::Vehicle &vehicle) const override { // rough approximation of extra effort to overcome friction etc vehicle.EnginePower += EngineRpmRatio(vehicle) * 0.15 * vehicle.DElist[vehicle.MainCtrlPosNo].GenPower; } - void UpdateVentilators(TMoverParameters &vehicle, double const dt) const override + void UpdateVentilators(physics::Vehicle &vehicle, double const dt) const override { // NOTE: for this type RventRot is the speed of motor blowers; we also update radiator fans while at it if (true == vehicle.Mains) @@ -505,34 +505,34 @@ public: } updateRadiatorFans(vehicle, dt); } - double ShowCurrent(TMoverParameters const &vehicle, int const /*ammeter*/) const override + double ShowCurrent(physics::Vehicle const &vehicle, int const /*ammeter*/) const override { return std::fabs(vehicle.Im); } - double EngineRpmRatio(TMoverParameters const &vehicle) const override + double EngineRpmRatio(physics::Vehicle const &vehicle) const override { return std::clamp(60.0 * std::abs(vehicle.enrot) / vehicle.DElist[vehicle.MainCtrlPosNo].RPM, 0.0, 1.0); } - double EngineIdleRpm(TMoverParameters const &vehicle) const override + double EngineIdleRpm(physics::Vehicle const &vehicle) const override { return vehicle.DElist[vehicle.MainCtrlNoPowerPos()].RPM; } - double EngineMaxRpm(TMoverParameters const &vehicle) const override + double EngineMaxRpm(physics::Vehicle const &vehicle) const override { return vehicle.DElist[vehicle.MainCtrlPosNo].RPM; } - bool MainsPowerAvailable(TMoverParameters const &vehicle) const override + bool MainsPowerAvailable(physics::Vehicle const &vehicle) const override { return vehicle.Power24vIsAvailable; } - void CheckVoltageRelays(TMoverParameters &vehicle) const override + void CheckVoltageRelays(physics::Vehicle &vehicle) const override { // TODO: move this to the auto relay check when the electric engine code paths are unified vehicle.StLinFlag |= vehicle.Mains && false == vehicle.StLinFlag && vehicle.MainCtrlPowerPos() == 1; vehicle.StLinFlag &= vehicle.MotorConnectorsCheck(); vehicle.StLinFlag &= vehicle.MainCtrlPowerPos() > 0; } - bool UpdateEngine(TMoverParameters &vehicle, double const dt) const override + bool UpdateEngine(physics::Vehicle &vehicle, double const dt) const override { return vehicle.dizel_Update(dt); } diff --git a/physics/components/drive.h b/physics/components/drive.h index b9f715b78..ac8dc9c70 100644 --- a/physics/components/drive.h +++ b/physics/components/drive.h @@ -9,13 +9,13 @@ http://mozilla.org/MPL/2.0/. // the drive of a vehicle, by the kind of its engine (EngineType, the Engine section of the .fiz): what each kind of // drive does in the step of the vehicle, in place of a switch on the engine type in each of those places. the drives -// hold no state of their own yet (it is in TMoverParameters): there is one of each kind, shared by the vehicles +// hold no state of their own yet (it is in physics::Vehicle): there is one of each kind, shared by the vehicles #pragma once #include "physics/vehicletypes.h" -class TMoverParameters; +namespace physics { class Vehicle; } // what the step of the traction gives the drive struct DriveStep @@ -33,38 +33,38 @@ public: virtual ~TractionDrive() = default; // the power of the engine for the controller positions; returns the share of the positions (Dumb), 0 for the others - virtual double UpdateEnginePower(TMoverParameters &vehicle) const; + virtual double UpdateEnginePower(physics::Vehicle &vehicle) const; // before the traction force, whether the reverser is set or not - virtual void BeforeTractionForce(TMoverParameters &vehicle, double dt) const; + virtual void BeforeTractionForce(physics::Vehicle &vehicle, double dt) const; // the traction force of the step (Ft), the reverser set - virtual void UpdateTractionForce(TMoverParameters &vehicle, DriveStep const &step) const; + virtual void UpdateTractionForce(physics::Vehicle &vehicle, DriveStep const &step) const; // after the traction force, whether the reverser is set or not - virtual void AfterTractionForce(TMoverParameters &vehicle) const; + virtual void AfterTractionForce(physics::Vehicle &vehicle) const; // the blowers of the starting resistors and the fans of the radiators - virtual void UpdateVentilators(TMoverParameters &vehicle, double dt) const; + virtual void UpdateVentilators(physics::Vehicle &vehicle, double dt) const; // the current the given ammeter of the cab shows - virtual double ShowCurrent(TMoverParameters const &vehicle, int ammeter) const; + virtual double ShowCurrent(physics::Vehicle const &vehicle, int ammeter) const; // the revolutions of the engine against the most it gives at the present controller position, 0..1; 1 with no // engine of revolutions - virtual double EngineRpmRatio(TMoverParameters const &vehicle) const; + virtual double EngineRpmRatio(physics::Vehicle const &vehicle) const; // the revolutions of the engine idling and at most [rpm]; the largest double with no engine of revolutions - virtual double EngineIdleRpm(TMoverParameters const &vehicle) const; - virtual double EngineMaxRpm(TMoverParameters const &vehicle) const; + virtual double EngineIdleRpm(physics::Vehicle const &vehicle) const; + virtual double EngineMaxRpm(physics::Vehicle const &vehicle) const; // the revolutions of the engine in the step (enrot); returns the revolutions a diesel-electric engine aims for, 0 for // the others. a diesel engine with a mechanical transmission gives its ratio and its moment through the references - virtual double UpdateEngineRevolutions(TMoverParameters &vehicle, double dt, double &transmission, double &moment) const; + virtual double UpdateEngineRevolutions(physics::Vehicle &vehicle, double dt, double &transmission, double &moment) const; // a notch up and down of the master controller, as the kind of the engine takes it; return whether it moved - virtual bool IncreaseMainController(TMoverParameters &vehicle, int speed) const; - virtual bool DecreaseMainController(TMoverParameters &vehicle, int speed) const; + virtual bool IncreaseMainController(physics::Vehicle &vehicle, int speed) const; + virtual bool DecreaseMainController(physics::Vehicle &vehicle, int speed) const; // whether the line breaker has the power it needs to close, before the genset of a dual-mode vehicle has its say - virtual bool MainsPowerAvailable(TMoverParameters const &vehicle) const; + virtual bool MainsPowerAvailable(physics::Vehicle const &vehicle) const; // the relays that open the line breaker at a voltage out of range, or the line contactors - virtual void CheckVoltageRelays(TMoverParameters &vehicle) const; + virtual void CheckVoltageRelays(physics::Vehicle &vehicle) const; // the engine in the step of the vehicle: the automatic start of the series motors, the diesel engine; returns // whether a relay clicked - virtual bool UpdateEngine(TMoverParameters &vehicle, double dt) const; + virtual bool UpdateEngine(physics::Vehicle &vehicle, double dt) const; // the voltage of the traction motors in the step (EngineVoltage) - virtual void UpdateEngineVoltage(TMoverParameters &vehicle, double dt) const; + virtual void UpdateEngineVoltage(physics::Vehicle &vehicle, double dt) const; }; // the drive of the given kind of engine diff --git a/physics/components/electrics.cpp b/physics/components/electrics.cpp index 7cdb75bd1..ebab2cbf0 100644 --- a/physics/components/electrics.cpp +++ b/physics/components/electrics.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. // the power supply: the batteries, the main switch, the pantographs, the converter, heating, lights, the genset #include "stdafx.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/DynObj.h" #include "physics/oerlikonest.h" #include "utilities/Globals.h" @@ -32,7 +32,7 @@ http://mozilla.org/MPL/2.0/. // KURS90 - sprężarka pantografów; Ra 2014-07: teraz jest to zbiornik rozrządu, chociaż to jeszcze nie tak -void TMoverParameters::UpdatePantVolume(double dt) +void physics::Vehicle::UpdatePantVolume(double dt) { // check the pantograph compressor while at it // TODO: move the check to a separate method @@ -82,7 +82,7 @@ void TMoverParameters::UpdatePantVolume(double dt) // the pantographs' pressure switch: low, it opens the line breaker (or locks the converter of a unit) once; // primed again over 4.6 bar, where the pantographs' compressor stops at 4.8 -void TMoverParameters::PantPressureSwitchCheck() +void physics::Vehicle::PantPressureSwitchCheck() { if (PantPress < EnginePowerSource.CollectorParameters.MinPress) { @@ -115,7 +115,7 @@ void TMoverParameters::PantPressureSwitchCheck() // the pantographs' pressure switch tripped by the low pressure: the line breaker opened, unless the voltage comes from // elsewhere, or the converter of a unit locked; spent until primed again -void TMoverParameters::PantPressureSwitchTrip() +void physics::Vehicle::PantPressureSwitchTrip() { // opuszczenie pantografów przy niskim ciśnieniu if (TrainType != train_type::emu) @@ -140,7 +140,7 @@ void TMoverParameters::PantPressureSwitchTrip() PantPressSwitchActive = false; } -void TMoverParameters::UpdateBatteryVoltage(double dt) +void physics::Vehicle::UpdateBatteryVoltage(double dt) { // przeliczenie obciążenia baterii using enum TEngineType; if (BatteryVoltage > 0 && EngineType != DieselEngine && EngineType != WheelsDriven && NominalBatteryVoltage > 0) @@ -167,7 +167,7 @@ void TMoverParameters::UpdateBatteryVoltage(double dt) }; // the drop of the battery's voltage in dt, by what draws from it, or its rise by the converter charging it -double TMoverParameters::BatteryDrain(double dt, bool const converteractive) const +double physics::Vehicle::BatteryDrain(double dt, bool const converteractive) const { if (NominalBatteryVoltage / BatteryVoltage < 1.22 && Battery) { // 110V @@ -185,7 +185,7 @@ double TMoverParameters::BatteryDrain(double dt, bool const converteractive) con } // the drain of a battery at its voltage, the converter charging it -double TMoverParameters::BatteryDrainCharged(double dt, bool const converteractive) const +double physics::Vehicle::BatteryDrainCharged(double dt, bool const converteractive) const { double sn1; double sn2; @@ -216,7 +216,7 @@ double TMoverParameters::BatteryDrainCharged(double dt, bool const converteracti } // the drain of a battery run down to 90 V, the converter charging it -double TMoverParameters::BatteryDrainLow(double dt, bool const converteractive) const +double physics::Vehicle::BatteryDrainLow(double dt, bool const converteractive) const { double sn1; double sn2; @@ -247,7 +247,7 @@ double TMoverParameters::BatteryDrainLow(double dt, bool const converteractive) } // the drain of a battery switched off, very slow -double TMoverParameters::BatteryDrainSwitchedOff(double dt) const +double physics::Vehicle::BatteryDrainSwitchedOff(double dt) const { double sn1; double sn2; @@ -265,7 +265,7 @@ double TMoverParameters::BatteryDrainSwitchedOff(double dt) const return sn1 + sn2 + sn3 + sn4 + sn5; } -void TMoverParameters::MainsCheck(double const Deltatime) +void physics::Vehicle::MainsCheck(double const Deltatime) { // if( MainsInitTime == 0.0 ) { return; } @@ -328,7 +328,7 @@ void TMoverParameters::MainsCheck(double const Deltatime) } } -void TMoverParameters::LowVoltagePowerCheck(double const /*Deltatime*/) +void physics::Vehicle::LowVoltagePowerCheck(double const /*Deltatime*/) { auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; @@ -345,7 +345,7 @@ void TMoverParameters::LowVoltagePowerCheck(double const /*Deltatime*/) } } -void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, Coupling const kind) +void physics::Vehicle::PowerCouplersCheck(double const /*Deltatime*/, Coupling const kind) { if (kind != Coupling::highVoltage && kind != Coupling::power110v && kind != Coupling::power24v) { @@ -366,7 +366,7 @@ void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, Coupling c } // the current the vehicle draws from the circuit of the power coupling given -double *TMoverParameters::PowerCircuitCurrent(Coupling const kind) +double *physics::Vehicle::PowerCircuitCurrent(Coupling const kind) { switch (kind) { @@ -382,7 +382,7 @@ double *TMoverParameters::PowerCircuitCurrent(Coupling const kind) } // the voltage of the vehicle's own source for the coupling given; notes the low voltage circuits' too -double TMoverParameters::LocalPowerVoltage(Coupling const kind) +double physics::Vehicle::LocalPowerVoltage(Coupling const kind) { auto localvoltage{0.0}; @@ -461,7 +461,7 @@ double TMoverParameters::LocalPowerVoltage(Coupling const kind) } // the voltage passed through the vehicle to the coupler at its other end, from the coupled vehicle or its own source -void TMoverParameters::PowerCouplersVoltage(Coupling const kind, double const abslocalvoltage, bool const localpowersource) +void physics::Vehicle::PowerCouplersVoltage(Coupling const kind, double const abslocalvoltage, bool const localpowersource) { if (Couplers[VehicleEnd::front].power(kind) == nullptr) { @@ -537,7 +537,7 @@ void TMoverParameters::PowerCouplersVoltage(Coupling const kind, double const ab } // the current drawn through the couplers, shared by their voltages, or added to the vehicle's own -void TMoverParameters::PowerCouplersCurrent(Coupling const kind, bool const localpowersource) +void physics::Vehicle::PowerCouplersCurrent(Coupling const kind, bool const localpowersource) { auto const *frontcoupling{Couplers[VehicleEnd::front].power(kind)}; auto const *rearcoupling{Couplers[VehicleEnd::rear].power(kind)}; @@ -588,7 +588,7 @@ void TMoverParameters::PowerCouplersCurrent(Coupling const kind, bool const loca } // sprawdzanie przetwornicy -void TMoverParameters::ConverterCheck(double const Timestep) +void physics::Vehicle::ConverterCheck(double const Timestep) { // TODO: move other converter checks here, to have it all in one place for potential device object if (ConverterStart != start_t::disabled && ConverterOverloadRelayOffWhenMainIsOff) @@ -648,7 +648,7 @@ void TMoverParameters::ConverterCheck(double const Timestep) }; // heating system status check -void TMoverParameters::HeatingCheck(double const /*Timestep*/) +void physics::Vehicle::HeatingCheck(double const /*Timestep*/) { // update heating devices @@ -725,7 +725,7 @@ void TMoverParameters::HeatingCheck(double const /*Timestep*/) } } -void TMoverParameters::PantographsCheck(double const /*Timestep*/) +void physics::Vehicle::PantographsCheck(double const /*Timestep*/) { using enum start_t; @@ -767,7 +767,7 @@ void TMoverParameters::PantographsCheck(double const /*Timestep*/) // the genset of a dual-mode vehicle: started on request with the battery on, it cranks for start_time, then runs at // idle and up to full revolutions with the traction demand; stopped, it coasts down. regulated voltage from idle up -void TMoverParameters::GensetCheck(double const Deltatime) +void physics::Vehicle::GensetCheck(double const Deltatime) { if (false == Genset.fitted()) { @@ -822,7 +822,7 @@ void TMoverParameters::GensetCheck(double const Deltatime) } } -void TMoverParameters::LightsCheck(double const /*Timestep*/) +void physics::Vehicle::LightsCheck(double const /*Timestep*/) { auto &light{CompartmentLights}; @@ -844,7 +844,7 @@ void TMoverParameters::LightsCheck(double const /*Timestep*/) // Q: 20160710 // włączenie / wyłączenie baterii // ************************************************************************************************* -bool TMoverParameters::BatterySwitch(bool State, range_t const Notify) +bool physics::Vehicle::BatterySwitch(bool State, range_t const Notify) { using enum range_t; if (PulleeMode && State) @@ -870,7 +870,7 @@ bool TMoverParameters::BatterySwitch(bool State, range_t const Notify) return Battery != initialstate; } -bool TMoverParameters::CompartmentLightsSwitch(bool State, range_t const Notify) +bool physics::Vehicle::CompartmentLightsSwitch(bool State, range_t const Notify) { if (CompartmentLights.start_type == start_t::automatic) @@ -892,7 +892,7 @@ bool TMoverParameters::CompartmentLightsSwitch(bool State, range_t const Notify) } // water pump state toggle -bool TMoverParameters::CompartmentLightsSwitchOff(bool State, range_t const Notify) +bool physics::Vehicle::CompartmentLightsSwitchOff(bool State, range_t const Notify) { if (CompartmentLights.start_type == start_t::automatic) @@ -917,7 +917,7 @@ bool TMoverParameters::CompartmentLightsSwitchOff(bool State, range_t const Noti // Q: 20160713 // włączenie / wyłączenie obwodu głownego // ************************************************************************************************* -bool TMoverParameters::MainSwitch(bool const State, range_t const Notify) +bool physics::Vehicle::MainSwitch(bool const State, range_t const Notify) { bool const initialstate{Mains || diesel.startupRequested}; @@ -934,7 +934,7 @@ bool TMoverParameters::MainSwitch(bool const State, range_t const Notify) return (Mains || diesel.startupRequested) != initialstate; } -void TMoverParameters::MainSwitch_(bool const State) +void physics::Vehicle::MainSwitch_(bool const State) { if (Mains == State || MainCtrlPosNo == 0) @@ -978,7 +978,7 @@ void TMoverParameters::MainSwitch_(bool const State) } } -bool TMoverParameters::MainSwitchCheck() const +bool physics::Vehicle::MainSwitchCheck() const { using enum TEngineType; @@ -1004,7 +1004,7 @@ bool TMoverParameters::MainSwitchCheck() const // Q: 20160713 // włączenie / wyłączenie przetwornicy // ************************************************************************************************* -bool TMoverParameters::ConverterSwitch(bool State, range_t const Notify) +bool physics::Vehicle::ConverterSwitch(bool State, range_t const Notify) { auto const initialstate{ConverterAllow}; @@ -1022,7 +1022,7 @@ bool TMoverParameters::ConverterSwitch(bool State, range_t const Notify) return ConverterAllow != initialstate; } -bool TMoverParameters::HeatingSwitch(bool const State, range_t const Notify) +bool physics::Vehicle::HeatingSwitch(bool const State, range_t const Notify) { bool const initialstate{HeatingAllow}; @@ -1039,7 +1039,7 @@ bool TMoverParameters::HeatingSwitch(bool const State, range_t const Notify) return HeatingAllow != initialstate; } -void TMoverParameters::HeatingSwitch_(bool const State) +void physics::Vehicle::HeatingSwitch_(bool const State) { // TBD, TODO: activation dependencies? @@ -1048,7 +1048,7 @@ void TMoverParameters::HeatingSwitch_(bool const State) // the start request of the genset of a dual-mode vehicle; one which starts on its own ignores it, but passes it on to // the cars behind, which may start theirs on request -bool TMoverParameters::GensetSwitch(bool const State, range_t const Notify) +bool physics::Vehicle::GensetSwitch(bool const State, range_t const Notify) { auto const initialstate{Genset.is_enabled}; @@ -1067,26 +1067,26 @@ bool TMoverParameters::GensetSwitch(bool const State, range_t const Notify) // the voltage of the vehicle's own source the traction selector picks: the catenary through the pantographs, or the // genset of a dual-mode vehicle -double TMoverParameters::TractionSourceVoltage() const +double physics::Vehicle::TractionSourceVoltage() const { return GensetSelected() ? Genset.voltage : PantographVoltage; } // the voltage the traction circuit gets: from the vehicle's own source, or through the train's high voltage line -double TMoverParameters::TractionSupplyVoltage() const +double physics::Vehicle::TractionSupplyVoltage() const { return std::max(GetTrainsetHighVoltage(), TractionSourceVoltage()); } // below it the undervoltage trip opens the line breaker -double TMoverParameters::TractionSupplyMinVoltage() const +double physics::Vehicle::TractionSupplyMinVoltage() const { return GensetSelected() ? 0.5 * Genset.voltage_nominal : EnginePowerSource.CollectorParameters.MinV; } // the power the traction may take [kW, at the wheels]: the genset's share at its present revolutions on the genset, // no limit otherwise -double TMoverParameters::GensetTractionPowerLimit() const +double physics::Vehicle::GensetTractionPowerLimit() const { return GensetSelected() ? Genset.available_power() * Genset.traction_share : std::numeric_limits::max(); } @@ -1094,7 +1094,7 @@ double TMoverParameters::GensetTractionPowerLimit() const // the current the vehicle draws through its pantographs [A], if they touch the wire: the traction's (none while // braking on the resistors) and the heating's. on the genset the genset feeds the traction circuit, so only a heating // fed straight from the pantographs is left -double TMoverParameters::CatenaryCurrent() const +double physics::Vehicle::CatenaryCurrent() const { if (GensetSelected()) { @@ -1104,7 +1104,7 @@ double TMoverParameters::CatenaryCurrent() const } // returns voltage of defined main engine power source -double TMoverParameters::EnginePowerSourceVoltage() const +double physics::Vehicle::EnginePowerSourceVoltage() const { return EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? TractionSupplyVoltage() : @@ -1114,7 +1114,7 @@ double TMoverParameters::EnginePowerSourceVoltage() const // whether the main circuit feeds what runs on it: the converter, a compressor, the heating, the motor and resistor // blowers, the traction motors -bool TMoverParameters::MainCircuitPowered() const +bool physics::Vehicle::MainCircuitPowered() const { if (false == Mains) { @@ -1131,7 +1131,7 @@ bool TMoverParameters::MainCircuitPowered() const return EnginePowerSourceVoltage() >= TractionSupplyMinVoltage(); } -bool TMoverParameters::OperatePantographsValve(operation_t const State, range_t const Notify) +bool physics::Vehicle::OperatePantographsValve(operation_t const State, range_t const Notify) { if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector && EnginePowerSource.CollectorParameters.CollectorsNo > 0) @@ -1191,7 +1191,7 @@ bool TMoverParameters::OperatePantographsValve(operation_t const State, range_t return true; } -bool TMoverParameters::OperatePantographValve(VehicleEnd const End, operation_t const State, range_t const Notify) +bool physics::Vehicle::OperatePantographValve(VehicleEnd const End, operation_t const State, range_t const Notify) { if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector && EnginePowerSource.CollectorParameters.CollectorsNo > 0) @@ -1255,7 +1255,7 @@ bool TMoverParameters::OperatePantographValve(VehicleEnd const End, operation_t return true; } -bool TMoverParameters::DropAllPantographs(bool const State, range_t const Notify) +bool physics::Vehicle::DropAllPantographs(bool const State, range_t const Notify) { auto const initialstate{PantAllDown}; @@ -1274,7 +1274,7 @@ bool TMoverParameters::DropAllPantographs(bool const State, range_t const Notify // Q: 20160709 // Funkcja zwracajaca napiecie dla calego skladu, przydatna dla EZT // ************************************************************************************************* -double TMoverParameters::GetTrainsetVoltage(CouplingSet const couplings) const +double physics::Vehicle::GetTrainsetVoltage(CouplingSet const couplings) const { // ABu: funkcja zwracajaca napiecie dla calego skladu, przydatna dla EZT // TBD, TODO: call once per vehicle update, return cached results? ByEnd voltages{0.0, 0.0}; @@ -1301,13 +1301,13 @@ double TMoverParameters::GetTrainsetVoltage(CouplingSet const couplings) const return std::max(voltages[VehicleEnd::front], voltages[VehicleEnd::rear]); } -double TMoverParameters::GetTrainsetHighVoltage() const +double physics::Vehicle::GetTrainsetHighVoltage() const { return std::max(GetTrainsetVoltage(Coupling::highVoltage), HeatingAllow ? GetTrainsetVoltage(Coupling::heating) : 0.0); } -int TMoverParameters::clampDimmerPosition(int const Position) const +int physics::Vehicle::clampDimmerPosition(int const Position) const { if (dimPositions.empty()) { @@ -1316,7 +1316,7 @@ int TMoverParameters::clampDimmerPosition(int const Position) const return std::clamp(Position, 0, static_cast(dimPositions.size()) - 1); } -TMoverParameters::dimPosition TMoverParameters::currentDimPosition() const +physics::Vehicle::dimPosition physics::Vehicle::currentDimPosition() const { if (modernDimmerPosition < 0 || modernDimmerPosition >= static_cast(dimPositions.size())) { @@ -1325,7 +1325,7 @@ TMoverParameters::dimPosition TMoverParameters::currentDimPosition() const return dimPositions[modernDimmerPosition]; } -bool TMoverParameters::stepDimmerPosition(int const Step) +bool physics::Vehicle::stepDimmerPosition(int const Step) { if (dimPositions.empty()) { @@ -1353,7 +1353,7 @@ bool TMoverParameters::stepDimmerPosition(int const Step) return true; } -std::optional TMoverParameters::LightsPresetCabLight(int const Position) const +std::optional physics::Vehicle::LightsPresetCabLight(int const Position) const { if (Position < 1 || Position > static_cast(LightsCabLight.size())) { diff --git a/physics/components/fizparser.cpp b/physics/components/fizparser.cpp index ebc791caa..5d7f3fc63 100644 --- a/physics/components/fizparser.cpp +++ b/physics/components/fizparser.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. // reading the vehicle definition (.fiz): the parser and its tables #include "stdafx.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/DynObj.h" #include "physics/oerlikonest.h" #include "utilities/Globals.h" @@ -75,7 +75,7 @@ static bool is_valid_mpt_index(int const Index) return false; } -bool TMoverParameters::readMPT0(std::string const &line) +bool physics::Vehicle::readMPT0(std::string const &line) { // TBD, TODO: split into separate functions similar to readMPT if more varied schemes appear? @@ -112,7 +112,7 @@ bool TMoverParameters::readMPT0(std::string const &line) return true; } -bool TMoverParameters::readMPT(std::string const &line) +bool physics::Vehicle::readMPT(std::string const &line) { ++LISTLINE; @@ -139,7 +139,7 @@ bool TMoverParameters::readMPT(std::string const &line) } } -bool TMoverParameters::readMPTElectricSeries(std::string const &line) +bool physics::Vehicle::readMPTElectricSeries(std::string const &line) { cParser parser(line); @@ -168,7 +168,7 @@ bool TMoverParameters::readMPTElectricSeries(std::string const &line) return true; } -bool TMoverParameters::readMPTDieselElectric(std::string const &line) +bool physics::Vehicle::readMPTDieselElectric(std::string const &line) { cParser parser(line); @@ -188,7 +188,7 @@ bool TMoverParameters::readMPTDieselElectric(std::string const &line) return true; } -bool TMoverParameters::readMPTDieselEngine(std::string const &line) +bool physics::Vehicle::readMPTDieselEngine(std::string const &line) { cParser parser(line); @@ -217,7 +217,7 @@ bool TMoverParameters::readMPTDieselEngine(std::string const &line) return true; } -bool TMoverParameters::readBPT(std::string const &line) +bool physics::Vehicle::readBPT(std::string const &line) { cParser parser(line); @@ -248,7 +248,7 @@ bool TMoverParameters::readBPT(std::string const &line) return true; } -bool TMoverParameters::readRList(std::string const &Input) +bool physics::Vehicle::readRList(std::string const &Input) { cParser parser(Input); @@ -278,7 +278,7 @@ bool TMoverParameters::readRList(std::string const &Input) return true; } -bool TMoverParameters::readUCList(std::string const &line) +bool physics::Vehicle::readUCList(std::string const &line) { cParser parser(line); @@ -296,7 +296,7 @@ bool TMoverParameters::readUCList(std::string const &line) return true; } -bool TMoverParameters::readDList(std::string const &line) +bool physics::Vehicle::readDList(std::string const &line) { cParser parser(line); @@ -312,7 +312,7 @@ bool TMoverParameters::readDList(std::string const &line) return true; } -bool TMoverParameters::readDMList(std::string const &line) +bool physics::Vehicle::readDMList(std::string const &line) { cParser parser(line); @@ -332,7 +332,7 @@ bool TMoverParameters::readDMList(std::string const &line) return true; } -bool TMoverParameters::readV2NMAXList(std::string const &line) +bool physics::Vehicle::readV2NMAXList(std::string const &line) { cParser parser(line); @@ -352,7 +352,7 @@ bool TMoverParameters::readV2NMAXList(std::string const &line) return true; } -bool TMoverParameters::readHTCList(std::string const &line) +bool physics::Vehicle::readHTCList(std::string const &line) { cParser parser(line); @@ -372,7 +372,7 @@ bool TMoverParameters::readHTCList(std::string const &line) return true; } -bool TMoverParameters::readPmaxList(std::string const &line) +bool physics::Vehicle::readPmaxList(std::string const &line) { cParser parser(line); @@ -392,7 +392,7 @@ bool TMoverParameters::readPmaxList(std::string const &line) return true; } -bool TMoverParameters::readFFList(std::string const &line) +bool physics::Vehicle::readFFList(std::string const &line) { cParser parser(line); @@ -412,7 +412,7 @@ bool TMoverParameters::readFFList(std::string const &line) return true; } -bool TMoverParameters::readFFEDList(std::string const &line) +bool physics::Vehicle::readFFEDList(std::string const &line) { cParser parser(line); @@ -433,7 +433,7 @@ bool TMoverParameters::readFFEDList(std::string const &line) } // parsowanie wiperList -bool TMoverParameters::readWiperList(std::string const &line) +bool physics::Vehicle::readWiperList(std::string const &line) { cParser parser(line); if (false == parser.getTokens(4, false)) @@ -451,7 +451,7 @@ bool TMoverParameters::readWiperList(std::string const &line) return true; } -bool TMoverParameters::readDimmerList(std::string const &line) +bool physics::Vehicle::readDimmerList(std::string const &line) { cParser parser(line); if (false == parser.getTokens(3, false)) @@ -468,7 +468,7 @@ bool TMoverParameters::readDimmerList(std::string const &line) } // parsowanie WWList -bool TMoverParameters::readWWList(std::string const &line) +bool physics::Vehicle::readWWList(std::string const &line) { cParser parser(line); @@ -496,7 +496,7 @@ bool TMoverParameters::readWWList(std::string const &line) return true; } -bool TMoverParameters::readLightsList(std::string const &Input) +bool physics::Vehicle::readLightsList(std::string const &Input) { cParser parser(Input); @@ -530,7 +530,7 @@ bool TMoverParameters::readLightsList(std::string const &Input) return true; } -bool TMoverParameters::readCompressorList(std::string const &Input) +bool physics::Vehicle::readCompressorList(std::string const &Input) { cParser parser(Input); @@ -554,7 +554,7 @@ bool TMoverParameters::readCompressorList(std::string const &Input) // ************************************************************************************************* // Q: 20160719 // ************************************************************************************************* -void TMoverParameters::BrakeValveDecode(std::string const &Valve) +void physics::Vehicle::BrakeValveDecode(std::string const &Valve) { using enum TBrakeValve; @@ -599,7 +599,7 @@ void TMoverParameters::BrakeValveDecode(std::string const &Valve) // ************************************************************************************************* // Q: 20160719 // ************************************************************************************************* -void TMoverParameters::BrakeSubsystemDecode() +void physics::Vehicle::BrakeSubsystemDecode() { using enum TBrakeSubSystem; BrakeSubsystem = ss_None; @@ -641,7 +641,7 @@ void TMoverParameters::BrakeSubsystemDecode() // TDynamicObject::Init() // Po niej wykonywana jest CreateBrakeSys(), ktora jest odpowiednikiem CheckLocomotiveParameters() // ************************************************************************************************* -bool TMoverParameters::LoadFIZ(std::string const &chkpath) +bool physics::Vehicle::LoadFIZ(std::string const &chkpath) { chkPath = chkpath; // assign class path for reloading @@ -668,14 +668,14 @@ bool TMoverParameters::LoadFIZ(std::string const &chkpath) } // reads the vehicle definition from text in the .fiz format, e.g. one made up by a unit test -bool TMoverParameters::LoadFIZ_Text(std::string const &Text) +bool physics::Vehicle::LoadFIZ_Text(std::string const &Text) { ConversionError = 666; cParser fizparser(Text, cParser::buffer_TEXT); return LoadFIZ_Parse(fizparser); } -bool TMoverParameters::LoadFIZ_Parse(cParser &fizparser) +bool physics::Vehicle::LoadFIZ_Parse(cParser &fizparser) { LISTLINE = 0; startBPT = false; @@ -764,7 +764,7 @@ bool TMoverParameters::LoadFIZ_Parse(cParser &fizparser) } // the end of the table being read; returns whether the line is one -bool TMoverParameters::LoadFIZ_TableEnd(std::string const &inputline) const +bool physics::Vehicle::LoadFIZ_TableEnd(std::string const &inputline) const { // checking if table parsing should be switched off goes first... if (issection("END-MPT", inputline)) @@ -859,7 +859,7 @@ bool TMoverParameters::LoadFIZ_TableEnd(std::string const &inputline) const } // a section of the definition giving values, kept in fizlines by its name; returns whether the line is one -bool TMoverParameters::LoadFIZ_Section(std::string const &inputline, std::map> &fizlines) +bool physics::Vehicle::LoadFIZ_Section(std::string const &inputline, std::map> &fizlines) { // ...then all recognized sections... if (issection("Param.", inputline)) @@ -1074,7 +1074,7 @@ bool TMoverParameters::LoadFIZ_Section(std::string const &inputline, std::map> &fizlines) +bool physics::Vehicle::LoadFIZ_TableSection(std::string const &inputline, std::map> &fizlines) { if (issection("MotorParamTable:", inputline)) { @@ -1231,7 +1231,7 @@ bool TMoverParameters::LoadFIZ_TableSection(std::string const &inputline, std::m } // a row of the table being read -void TMoverParameters::LoadFIZ_TableRow(std::string const &inputline) +void physics::Vehicle::LoadFIZ_TableRow(std::string const &inputline) { // ...and finally, table parsers. // NOTE: once table parsing is enabled it lasts until switched off, when another section is recognized @@ -1321,7 +1321,7 @@ void TMoverParameters::LoadFIZ_TableRow(std::string const &inputline) } } -bool TMoverParameters::reload_FIZ() +bool physics::Vehicle::reload_FIZ() { WriteLog("[DEV] Reloading FIZ for " + Name); // pause simulation diff --git a/physics/components/fizsections.cpp b/physics/components/fizsections.cpp index d3de6cc60..a58837090 100644 --- a/physics/components/fizsections.cpp +++ b/physics/components/fizsections.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. // reading the vehicle definition (.fiz): the sections and their keywords #include "stdafx.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/DynObj.h" #include "physics/oerlikonest.h" #include "utilities/Globals.h" @@ -54,7 +54,7 @@ int s2NNW(std::string s) return NNW; } -void TMoverParameters::LoadFIZ_Param(std::string const &line) +void physics::Vehicle::LoadFIZ_Param(std::string const &line) { extract_value(Mass, "M", line, "0"); @@ -106,7 +106,7 @@ void TMoverParameters::LoadFIZ_Param(std::string const &line) } } -void TMoverParameters::LoadFIZ_Load(std::string const &line) +void physics::Vehicle::LoadFIZ_Load(std::string const &line) { auto const acceptedloads{Split(extract_value("LoadAccepted", line), ',')}; @@ -138,7 +138,7 @@ void TMoverParameters::LoadFIZ_Load(std::string const &line) extract_value(UnLoadSpeed, "UnLoadSpeed", line, ""); } -void TMoverParameters::LoadFIZ_Headlights(std::string const &line) +void physics::Vehicle::LoadFIZ_Headlights(std::string const &line) { extract_value(refR, "LampRed", line, ""); extract_value(refG, "LampGreen", line, ""); @@ -150,7 +150,7 @@ void TMoverParameters::LoadFIZ_Headlights(std::string const &line) extract_value(highMultiplier, "HighBeamMultiplier", line, ""); } -void TMoverParameters::LoadFIZ_Dimensions(std::string const &line) +void physics::Vehicle::LoadFIZ_Dimensions(std::string const &line) { extract_value(Dim.L, "L", line, ""); @@ -173,7 +173,7 @@ void TMoverParameters::LoadFIZ_Dimensions(std::string const &line) extract_value(Floor, "Floor", line, ""); } -void TMoverParameters::LoadFIZ_Wheels(std::string const &line) +void physics::Vehicle::LoadFIZ_Wheels(std::string const &line) { extract_value(WheelDiameter, "D", line, ""); @@ -206,7 +206,7 @@ void TMoverParameters::LoadFIZ_Wheels(std::string const &line) } } -void TMoverParameters::LoadFIZ_Brake(std::string const &line) +void physics::Vehicle::LoadFIZ_Brake(std::string const &line) { extract_value(BrakeValveParams, "BrakeValve", line, ""); @@ -353,7 +353,7 @@ void TMoverParameters::LoadFIZ_Brake(std::string const &line) } } -void TMoverParameters::LoadFIZ_Doors(std::string const &line) +void physics::Vehicle::LoadFIZ_Doors(std::string const &line) { std::map> doorcontrols{ @@ -552,7 +552,7 @@ collision::end_definition collision_definition(std::string const &Line) } // namespace -void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Index) +void physics::Vehicle::LoadFIZ_BuffCoupl(std::string const &line, int const Index) { TCoupling *thiscoupler; @@ -669,13 +669,13 @@ void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Inde } } -void TMoverParameters::LoadFIZ_TurboPos(std::string const &Input) +void physics::Vehicle::LoadFIZ_TurboPos(std::string const &Input) { extract_value(TurboTest, "TurboPos", Input, ""); } -void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) +void physics::Vehicle::LoadFIZ_Cntrl(std::string const &line) { LoadFIZ_CntrlBrakes(line); @@ -684,7 +684,7 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) } // Cntrl.: the brake system, the handles, the brake delays and the local and manual brakes -void TMoverParameters::LoadFIZ_CntrlBrakes(std::string const &line) +void physics::Vehicle::LoadFIZ_CntrlBrakes(std::string const &line) { { using enum TBrakeSystem; @@ -709,7 +709,7 @@ void TMoverParameters::LoadFIZ_CntrlBrakes(std::string const &line) } // Cntrl.: of a vehicle with a train brake, its positions, delays, modes, handles, load weighing and anti-slip brake -void TMoverParameters::LoadFIZ_CntrlTrainBrake(std::string const &line) +void physics::Vehicle::LoadFIZ_CntrlTrainBrake(std::string const &line) { using enum TBrakeHandle; @@ -777,7 +777,7 @@ void TMoverParameters::LoadFIZ_CntrlTrainBrake(std::string const &line) } // Cntrl.: the kind of the anti-slip brake, by hand or automatic only for a vehicle with a brake handle -void TMoverParameters::LoadFIZ_CntrlAntiSlipBrake(std::string_view const asb) +void physics::Vehicle::LoadFIZ_CntrlAntiSlipBrake(std::string_view const asb) { if (asb == "yes") { @@ -794,7 +794,7 @@ void TMoverParameters::LoadFIZ_CntrlAntiSlipBrake(std::string_view const asb) } // Cntrl.: the controllers, their delays, the cab and the switches of the driver's desk -void TMoverParameters::LoadFIZ_CntrlControllers(std::string const &line) +void physics::Vehicle::LoadFIZ_CntrlControllers(std::string const &line) { // maksymalna predkosc dostepna na tarczce predkosciomierza extract_value(maxTachoSpeed, "MaxTachoSpeed", line, ""); @@ -901,7 +901,7 @@ void TMoverParameters::LoadFIZ_CntrlControllers(std::string const &line) } // Cntrl.: how the devices start (MainStart, BatteryStart, ...) and their relays -void TMoverParameters::LoadFIZ_CntrlStarts(std::string const &line) +void physics::Vehicle::LoadFIZ_CntrlStarts(std::string const &line) { using enum start_t; std::map> starts{{"Disabled", disabled}, {"Manual", manual}, {"Automatic", automatic}, {"Mixed", manualwithautofallback}, @@ -1017,7 +1017,7 @@ void TMoverParameters::LoadFIZ_CntrlStarts(std::string const &line) } } -void TMoverParameters::LoadFIZ_Blending(std::string const &line) +void physics::Vehicle::LoadFIZ_Blending(std::string const &line) { extract_value(MED_Vmax, "MED_Vmax", line, std::to_string(Vmax)); @@ -1032,7 +1032,7 @@ void TMoverParameters::LoadFIZ_Blending(std::string const &line) extract_value(MED_ED_Delay2, "MED_ScndDelayED", line, ""); } -void TMoverParameters::LoadFIZ_DCEMUED(std::string const &line) +void physics::Vehicle::LoadFIZ_DCEMUED(std::string const &line) { extract_value(DCEMUED_CC, "CouplerCheck", line, "0"); @@ -1041,7 +1041,7 @@ void TMoverParameters::LoadFIZ_DCEMUED(std::string const &line) extract_value(DCEMUED_EP_delay, "EP_delay", line, "0"); } -void TMoverParameters::LoadFIZ_SpringBrake(std::string const &line) +void physics::Vehicle::LoadFIZ_SpringBrake(std::string const &line) { double vol{1.0}; @@ -1065,7 +1065,7 @@ void TMoverParameters::LoadFIZ_SpringBrake(std::string const &line) SpringBrake.IsReady = true; } -void TMoverParameters::LoadFIZ_Light(std::string const &line) +void physics::Vehicle::LoadFIZ_Light(std::string const &line) { LightPowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("Light", line)); @@ -1079,7 +1079,7 @@ void TMoverParameters::LoadFIZ_Light(std::string const &line) NominalBatteryVoltage = static_cast(BatteryVoltage); } -void TMoverParameters::LoadFIZ_Clima(std::string const &line) +void physics::Vehicle::LoadFIZ_Clima(std::string const &line) { HeatingPowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("Heating", line)); @@ -1088,7 +1088,7 @@ void TMoverParameters::LoadFIZ_Clima(std::string const &line) LoadFIZ_PowerParamsDecode(AlterHeatPowerSource, "AlterH", line); } -void TMoverParameters::LoadFIZ_Power(std::string const &Line) +void physics::Vehicle::LoadFIZ_Power(std::string const &Line) { EnginePowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("EnginePower", Line)); @@ -1115,7 +1115,7 @@ void TMoverParameters::LoadFIZ_Power(std::string const &Line) } // the genset of a dual-mode vehicle (eu07/maszyna#536), on the Power: line; all optional, no genset without GensetPower -void TMoverParameters::LoadFIZ_Genset(std::string const &Line) +void physics::Vehicle::LoadFIZ_Genset(std::string const &Line) { extract_value(Genset.power, "GensetPower", Line, ""); if (false == Genset.fitted()) @@ -1139,7 +1139,7 @@ void TMoverParameters::LoadFIZ_Genset(std::string const &Line) Genset.traction_share = std::clamp(Genset.traction_share, 0.0, 1.0); } -void TMoverParameters::LoadFIZ_SpeedControl(std::string const &Line) +void physics::Vehicle::LoadFIZ_SpeedControl(std::string const &Line) { // speed control extract_value(SpeedCtrl, "SpeedCtrl", Line, ""); @@ -1178,7 +1178,7 @@ void TMoverParameters::LoadFIZ_SpeedControl(std::string const &Line) extract_value(SpeedCtrlUnit.PowerDownSpeed, "PowerDownSpeed", Line, ""); } -void TMoverParameters::LoadFIZ_Engine(std::string const &Input) +void physics::Vehicle::LoadFIZ_Engine(std::string const &Input) { EngineType = LoadFIZ_EngineDecode(extract_value("EngineType", Input)); @@ -1267,7 +1267,7 @@ void TMoverParameters::LoadFIZ_Engine(std::string const &Input) } // Engine: of a diesel engine, its revolutions, gears, hydraulic transmission and retarder -void TMoverParameters::LoadFIZ_EngineDiesel(std::string const &Input) +void physics::Vehicle::LoadFIZ_EngineDiesel(std::string const &Input) { extract_value(diesel.minRevolutions, "nmin", Input, ""); @@ -1347,7 +1347,7 @@ void TMoverParameters::LoadFIZ_EngineDiesel(std::string const &Input) } // Engine: of a diesel-electric -void TMoverParameters::LoadFIZ_EngineDieselElectric(std::string const &Input) +void physics::Vehicle::LoadFIZ_EngineDieselElectric(std::string const &Input) { extract_value(Ftmax, "Ftmax", Input, ""); @@ -1374,7 +1374,7 @@ void TMoverParameters::LoadFIZ_EngineDieselElectric(std::string const &Input) } // Engine: of an induction motor drive -void TMoverParameters::LoadFIZ_EngineInductionMotor(std::string const &Input) +void physics::Vehicle::LoadFIZ_EngineInductionMotor(std::string const &Input) { RVentnmax = 1.0; @@ -1426,7 +1426,7 @@ void TMoverParameters::LoadFIZ_EngineInductionMotor(std::string const &Input) } // Engine: what both kinds of diesels have, their heat among it -void TMoverParameters::LoadFIZ_EngineDieselShared(std::string const &Input) +void physics::Vehicle::LoadFIZ_EngineDieselShared(std::string const &Input) { // oil pump extract_value(OilPump.pressure_minimum, "OilMinPressure", Input, ""); @@ -1464,7 +1464,7 @@ void TMoverParameters::LoadFIZ_EngineDieselShared(std::string const &Input) diesel.heat.powerfactor = 1235 / pf; } -void TMoverParameters::LoadFIZ_Switches(std::string const &Input) +void physics::Vehicle::LoadFIZ_Switches(std::string const &Input) { extract_value(PantSwitchType, "Pantograph", Input, ""); @@ -1488,7 +1488,7 @@ void TMoverParameters::LoadFIZ_Switches(std::string const &Input) } } -void TMoverParameters::LoadFIZ_MotorParamTable(std::string const &Input) +void physics::Vehicle::LoadFIZ_MotorParamTable(std::string const &Input) { switch (EngineType) @@ -1510,7 +1510,7 @@ void TMoverParameters::LoadFIZ_MotorParamTable(std::string const &Input) } } -void TMoverParameters::LoadFIZ_Circuit(std::string const &Input) +void physics::Vehicle::LoadFIZ_Circuit(std::string const &Input) { extract_value(CircuitRes, "CircuitRes", Input, ""); @@ -1530,7 +1530,7 @@ void TMoverParameters::LoadFIZ_Circuit(std::string const &Input) extract_value(TUHEX_Stages, "TUHEX_Stages", Input, "0"); } -void TMoverParameters::LoadFIZ_AI(std::string const &Input) +void physics::Vehicle::LoadFIZ_AI(std::string const &Input) { extract_value(AIHintPantstate, "Pantstate", Input, ""); @@ -1539,7 +1539,7 @@ void TMoverParameters::LoadFIZ_AI(std::string const &Input) extract_value(AIHintLocalBrakeAccFactor, "LocalBrakeAccFactor", Input, ""); } -void TMoverParameters::LoadFIZ_RList(std::string const &Input) +void physics::Vehicle::LoadFIZ_RList(std::string const &Input) { extract_value(RlistSize, "Size", Input, ""); @@ -1570,7 +1570,7 @@ void TMoverParameters::LoadFIZ_RList(std::string const &Input) } // the dynamic brake of a diesel-electric vehicle, from its Engine section: none without EDBrake -void TMoverParameters::LoadFIZ_DieselElectricDynamicBrake(std::string const &Input) +void physics::Vehicle::LoadFIZ_DieselElectricDynamicBrake(std::string const &Input) { using enum diesel_electric_dynamic_brake::control; std::map> const sources{{"Controller", controller}, {"Lever", lever}}; @@ -1598,7 +1598,7 @@ void TMoverParameters::LoadFIZ_DieselElectricDynamicBrake(std::string const &Inp } } -void TMoverParameters::LoadFIZ_UCList(std::string const &Input) +void physics::Vehicle::LoadFIZ_UCList(std::string const &Input) { extract_value(UniCtrlListSize, "Size", Input, ""); @@ -1609,7 +1609,7 @@ void TMoverParameters::LoadFIZ_UCList(std::string const &Input) UniCtrlValStep = std::max(UniCtrlValStep, 0.0); } -void TMoverParameters::LoadFIZ_DList(std::string const &Input) +void physics::Vehicle::LoadFIZ_DList(std::string const &Input) { extract_value(diesel.maxMoment, "Mmax", Input, ""); @@ -1633,30 +1633,30 @@ void TMoverParameters::LoadFIZ_DList(std::string const &Input) diesel.fuelConsumption = diesel.nominalFuelConsumptionRate * dizel_max_energy / fuel_density / diesel.maxRevolutions; } -void TMoverParameters::LoadFIZ_FFList(std::string const &Input) +void physics::Vehicle::LoadFIZ_FFList(std::string const &Input) { extract_value(FFListSize, "Size", Input, ""); } -void TMoverParameters::LoadFIZ_FFEDList(std::string const &Input) +void physics::Vehicle::LoadFIZ_FFEDList(std::string const &Input) { extract_value(FFEDListSize, "Size", Input, ""); } -void TMoverParameters::LoadFIZ_WiperList(std::string const &Input) +void physics::Vehicle::LoadFIZ_WiperList(std::string const &Input) { extract_value(WiperListSize, "Size", Input, ""); extract_value(WiperAngle, "Angle", Input, ""); extract_value(WiperDefaultPos, "Default", Input, ""); } -void TMoverParameters::LoadFIZ_DimmerList(std::string const &Input) +void physics::Vehicle::LoadFIZ_DimmerList(std::string const &Input) { // extract_value(modernWpierListSize, "Size", Input, ""); extract_value(modernDimmerCanCycle, "Cycle", Input, ""); extract_value(modernDimmerDefaultPosition, "DefaultPos", Input, ""); } -void TMoverParameters::LoadFIZ_LightsList(std::string const &Input) +void physics::Vehicle::LoadFIZ_LightsList(std::string const &Input) { extract_value(LightsPosNo, "Size", Input, ""); @@ -1664,7 +1664,7 @@ void TMoverParameters::LoadFIZ_LightsList(std::string const &Input) extract_value(LightsDefPos, "Default", Input, ""); } -void TMoverParameters::LoadFIZ_CompressorList(std::string const &Input) +void physics::Vehicle::LoadFIZ_CompressorList(std::string const &Input) { extract_value(CompressorListPosNo, "Size", Input, ""); @@ -1672,7 +1672,7 @@ void TMoverParameters::LoadFIZ_CompressorList(std::string const &Input) extract_value(CompressorListDefPos, "Default", Input, ""); } -void TMoverParameters::LoadFIZ_PowerParamsDecode(TPowerParameters &Powerparameters, std::string const &Prefix, std::string const &Line) +void physics::Vehicle::LoadFIZ_PowerParamsDecode(TPowerParameters &Powerparameters, std::string const &Prefix, std::string const &Line) { switch (Powerparameters.SourceType) @@ -1693,7 +1693,7 @@ void TMoverParameters::LoadFIZ_PowerParamsDecode(TPowerParameters &Powerparamete } case TPowerSource::Generator: { - // prime mover for the generator + // prime physics for the generator auto &generatorparameters{Powerparameters.EngineGenerator}; if (auto const enginetype{LoadFIZ_EngineDecode(extract_value(Prefix + "GeneratorEngine", Line))}; enginetype == TEngineType::Main) @@ -1792,7 +1792,7 @@ void TMoverParameters::LoadFIZ_PowerParamsDecode(TPowerParameters &Powerparamete } } -TPowerType TMoverParameters::LoadFIZ_PowerDecode(std::string const &Powertype) const +TPowerType physics::Vehicle::LoadFIZ_PowerDecode(std::string const &Powertype) const { using enum TPowerType; @@ -1802,7 +1802,7 @@ TPowerType TMoverParameters::LoadFIZ_PowerDecode(std::string const &Powertype) c return lookup != powertypes.end() ? lookup->second : NoPower; } -TPowerSource TMoverParameters::LoadFIZ_SourceDecode(std::string const &Source) const +TPowerSource physics::Vehicle::LoadFIZ_SourceDecode(std::string const &Source) const { using enum TPowerSource; @@ -1815,7 +1815,7 @@ TPowerSource TMoverParameters::LoadFIZ_SourceDecode(std::string const &Source) c return lookup != powersources.end() ? lookup->second : NotDefined; } -TEngineType TMoverParameters::LoadFIZ_EngineDecode(std::string const &Engine) const +TEngineType physics::Vehicle::LoadFIZ_EngineDecode(std::string const &Engine) const { using enum TEngineType; diff --git a/physics/components/internal.h b/physics/components/internal.h index baf916278..4cdcbe668 100644 --- a/physics/components/internal.h +++ b/physics/components/internal.h @@ -11,7 +11,7 @@ http://mozilla.org/MPL/2.0/. #pragma once -#include "physics/mover.h" +#include "physics/vehicle.h" const double CouplerTune = 0.1; // skalowanie tlumiennosci diff --git a/physics/components/pneumatics.cpp b/physics/components/pneumatics.cpp index 8a7f0555a..4ba3c0276 100644 --- a/physics/components/pneumatics.cpp +++ b/physics/components/pneumatics.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. // the brakes and the air: the brake controls, the pipes, the valves, the compressor, the spring brake #include "stdafx.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/DynObj.h" #include "physics/oerlikonest.h" #include "utilities/Globals.h" @@ -32,7 +32,7 @@ http://mozilla.org/MPL/2.0/. // Nastawianie hamulców -void TMoverParameters::BrakeLevelSet(double b) +void physics::Vehicle::BrakeLevelSet(double b) { // ustawienie pozycji hamulca na wartość (b) w zakresie od -2 do BrakeCtrlPosNo // jedyny dopuszczalny sposób przestawienia hamulca zasadniczego if (fBrakeCtrlPos == b) @@ -47,10 +47,10 @@ void TMoverParameters::BrakeLevelSet(double b) auto x = static_cast(std::floor(fBrakeCtrlPos)); // jeśli odwołujemy się do BrakeCtrlPos w pośrednich, to musi być // obcięte a nie zaokrągone while (x > BrakeCtrlPos && BrakeCtrlPos < BrakeCtrlPosNo) // jeśli zwiększyło się o 1 - if (!IncBrakeLevelOld()) // T_MoverParameters:: + if (!IncBrakeLevelOld()) // physics::Vehicle:: break; // wyjście awaryjne while (x < BrakeCtrlPos && BrakeCtrlPos >= -1) // jeśli zmniejszyło się o 1 - if (!DecBrakeLevelOld()) // T_MoverParameters:: + if (!DecBrakeLevelOld()) // physics::Vehicle:: break; BrakePressureActual = BrakePressureTable[BrakeCtrlPos]; // skopiowanie pozycji /* @@ -73,19 +73,19 @@ void TMoverParameters::BrakeLevelSet(double b) */ }; -bool TMoverParameters::BrakeLevelAdd(double b) +bool physics::Vehicle::BrakeLevelAdd(double b) { // dodanie wartości (b) do pozycji hamulca (w tym ujemnej) // zwraca false, gdy po dodaniu było by poza zakresem BrakeLevelSet(fBrakeCtrlPos + b); return b > 0.0 ? fBrakeCtrlPos < BrakeCtrlPosNo : BrakeCtrlPos > -1.0; // true, jeśli można kontynuować }; -bool TMoverParameters::IncBrakeLevel() +bool physics::Vehicle::IncBrakeLevel() { // nowa wersja na użytek AI, false gdy osiągnięto pozycję BrakeCtrlPosNo return BrakeLevelAdd(1.0); }; -bool TMoverParameters::DecBrakeLevel() +bool physics::Vehicle::DecBrakeLevel() { return BrakeLevelAdd(-1.0); }; // nowa wersja na użytek AI, false gdy osiągnięto pozycję -1 @@ -133,7 +133,7 @@ ZN //masa // Q: 20160714 // Oblicza iloraz aktualnej pozycji do maksymalnej hamulca pomocnicznego // ***************************************************************************** -double TMoverParameters::LocalBrakeRatio(void) const +double physics::Vehicle::LocalBrakeRatio(void) const { double LBR; if (BrakeHandle == TBrakeHandle::MHZ_EN57) @@ -157,7 +157,7 @@ double TMoverParameters::LocalBrakeRatio(void) const // Q: 20160714 // Oblicza iloraz aktualnej pozycji do maksymalnej hamulca ręcznego // ***************************************************************************** -double TMoverParameters::ManualBrakeRatio(void) const +double physics::Vehicle::ManualBrakeRatio(void) const { double MBR; @@ -172,7 +172,7 @@ double TMoverParameters::ManualBrakeRatio(void) const // Q: 20160713 // Zwraca objętość // ***************************************************************************** -double TMoverParameters::BrakeVP(void) const +double physics::Vehicle::BrakeVP(void) const { if (BrakeVVolume > 0) return Volume / (10.0 * BrakeVVolume); @@ -184,7 +184,7 @@ double TMoverParameters::BrakeVP(void) const // Q: 20160713 // Zwraca iloraz różnicy między przewodem kontrolnym i głównym oraz DeltaPipePress // ***************************************************************************** -double TMoverParameters::RealPipeRatio(void) const +double physics::Vehicle::RealPipeRatio(void) const { double rpp; @@ -199,7 +199,7 @@ double TMoverParameters::RealPipeRatio(void) const // Q: 20160713 // Zwraca iloraz ciśnienia w przewodzie do DeltaPipePress // ***************************************************************************** -double TMoverParameters::PipeRatio(void) const +double physics::Vehicle::PipeRatio(void) const { double pr; @@ -227,7 +227,7 @@ double TMoverParameters::PipeRatio(void) const // Q: 20160710 // włączenie / wyłączenie hamulca elektro-pneumatycznego // ************************************************************************************************* -bool TMoverParameters::EpFuseSwitch(bool State) +bool physics::Vehicle::EpFuseSwitch(bool State) { if (EpFuse != State) { @@ -244,7 +244,7 @@ bool TMoverParameters::EpFuseSwitch(bool State) // yB: 20190906 // włączenie / wyłączenie hamulca sprezynowego // ************************************************************************************************* -bool TMoverParameters::SpringBrakeActivate(bool State) +bool physics::Vehicle::SpringBrakeActivate(bool State) { if (Power24vIsAvailable || Power110vIsAvailable) { @@ -264,7 +264,7 @@ bool TMoverParameters::SpringBrakeActivate(bool State) // yB: 20190906 // włączenie / wyłączenie odciecia hamulca sprezynowego // ************************************************************************************************* -bool TMoverParameters::SpringBrakeShutOff(bool State) +bool physics::Vehicle::SpringBrakeShutOff(bool State) { if (SpringBrake.ShuttOff != State) { @@ -279,7 +279,7 @@ bool TMoverParameters::SpringBrakeShutOff(bool State) // yB: 20190906 // wyluzowanie hamulca sprezynowego // ************************************************************************************************* -bool TMoverParameters::SpringBrakeRelease() +bool physics::Vehicle::SpringBrakeRelease() { if (SpringBrake.IsReady && SpringBrake.Cylinder->P() < SpringBrake.MinForcePressure) { @@ -295,7 +295,7 @@ bool TMoverParameters::SpringBrakeRelease() // Q: 20160710 // załączenie przycisku przeciwpoślizgowego // ************************************************************************************************* -bool TMoverParameters::AntiSlippingButton(void) +bool physics::Vehicle::AntiSlippingButton(void) { // NOTE: disabled the sandbox part, it's already controlled by another part of the AI routine return AntiSlippingBrake() /*|| Sandbox(true)*/; @@ -305,7 +305,7 @@ bool TMoverParameters::AntiSlippingButton(void) // Q: 20160713 // włączenie / wyłączenie sprężarki // ************************************************************************************************* -bool TMoverParameters::CompressorSwitch(bool State, range_t const Notify) +bool physics::Vehicle::CompressorSwitch(bool State, range_t const Notify) { if (CompressorStart != start_t::manual) @@ -329,7 +329,7 @@ bool TMoverParameters::CompressorSwitch(bool State, range_t const Notify) return CompressorAllow != initialstate; } -bool TMoverParameters::ChangeCompressorPreset(int const State, range_t const Notify) +bool physics::Vehicle::ChangeCompressorPreset(int const State, range_t const Notify) { auto const initialstate{CompressorListPos}; @@ -348,7 +348,7 @@ bool TMoverParameters::ChangeCompressorPreset(int const State, range_t const Not // Q: 20160711 // zwiększenie nastawy hamulca // ************************************************************************************************* -bool TMoverParameters::IncBrakeLevelOld(void) +bool physics::Vehicle::IncBrakeLevelOld(void) { bool IBLO = false; @@ -375,7 +375,7 @@ bool TMoverParameters::IncBrakeLevelOld(void) // Q: 20160711 // zmniejszenie nastawy hamulca // ***************************************************************************** -bool TMoverParameters::DecBrakeLevelOld(void) +bool physics::Vehicle::DecBrakeLevelOld(void) { bool DBLO = false; @@ -401,7 +401,7 @@ bool TMoverParameters::DecBrakeLevelOld(void) // Q: 20160711 // zwiększenie nastawy hamulca pomocnicznego // ************************************************************************************************* -bool TMoverParameters::IncLocalBrakeLevel(float const CtrlSpeed) +bool physics::Vehicle::IncLocalBrakeLevel(float const CtrlSpeed) { bool IBL; if (LocalBrakePosA < 1.0 /*and (BrakeCtrlPos<1)*/) @@ -420,7 +420,7 @@ bool TMoverParameters::IncLocalBrakeLevel(float const CtrlSpeed) // Q: 20160711 // zmniejszenie nastawy hamulca pomocniczego // ************************************************************************************************* -bool TMoverParameters::DecLocalBrakeLevel(float const CtrlSpeed) +bool physics::Vehicle::DecLocalBrakeLevel(float const CtrlSpeed) { bool DBL; if (LocalBrakePosA > 0) @@ -439,7 +439,7 @@ bool TMoverParameters::DecLocalBrakeLevel(float const CtrlSpeed) // Q: 20160711 // zwiększenie nastawy hamulca ręcznego // ************************************************************************************************* -bool TMoverParameters::IncManualBrakeLevel(int CtrlSpeed) +bool physics::Vehicle::IncManualBrakeLevel(int CtrlSpeed) { bool IMBL; if (ManualBrakePos < ManualBrakePosNo) /*and (BrakeCtrlPos<1)*/ @@ -462,7 +462,7 @@ bool TMoverParameters::IncManualBrakeLevel(int CtrlSpeed) // Q: 20160711 // zmniejszenie nastawy hamulca ręcznego // ************************************************************************************************* -bool TMoverParameters::DecManualBrakeLevel(int CtrlSpeed) +bool physics::Vehicle::DecManualBrakeLevel(int CtrlSpeed) { bool DMBL; if (ManualBrakePos > 0) @@ -480,7 +480,7 @@ bool TMoverParameters::DecManualBrakeLevel(int CtrlSpeed) return DMBL; } -bool TMoverParameters::AlarmChainSwitch(bool const State) +bool physics::Vehicle::AlarmChainSwitch(bool const State) { if (AlarmChainFlag != State) @@ -496,7 +496,7 @@ bool TMoverParameters::AlarmChainSwitch(bool const State) // Q: 20160710 // hamowanie przeciwpoślizgowe // ************************************************************************************************* -bool TMoverParameters::AntiSlippingBrake(void) +bool physics::Vehicle::AntiSlippingBrake(void) { bool ASB = false; // Ra: przeniesione z końca if (ASBType == 1) @@ -512,7 +512,7 @@ bool TMoverParameters::AntiSlippingBrake(void) // Q: 20160711 // włączenie / wyłączenie odluźniacza // ************************************************************************************************* -bool TMoverParameters::BrakeReleaser(int state) +bool physics::Vehicle::BrakeReleaser(int state) { bool OK = true; // false tylko jeśli nie uda się wysłać, GF 20161124 if (state != 0) @@ -536,7 +536,7 @@ bool TMoverParameters::BrakeReleaser(int state) // yB: 20160711 // włączenie / wyłączenie uniwersalnego przycisku hamulcowego // ************************************************************************************************* -bool TMoverParameters::UniversalBrakeButton(int button, int state) +bool physics::Vehicle::UniversalBrakeButton(int button, int state) { bool OK = true; // false tylko jeśli nie uda się wysłać, GF 20161124 UniversalBrakeButtonActive[button] = state > 0; @@ -566,7 +566,7 @@ bool TMoverParameters::UniversalBrakeButton(int button, int state) // Q: 20160711 // włączenie / wyłączenie hamulca elektro-pneumatycznego // ************************************************************************************************* -bool TMoverParameters::SwitchEPBrake(int state) +bool physics::Vehicle::SwitchEPBrake(int state) { bool OK; @@ -586,7 +586,7 @@ bool TMoverParameters::SwitchEPBrake(int state) return OK; } -bool TMoverParameters::EPBrakeControlPowered() const +bool physics::Vehicle::EPBrakeControlPowered() const { return Power24vIsAvailable && DirActive != 0 && EpFuse; } @@ -595,7 +595,7 @@ bool TMoverParameters::EPBrakeControlPowered() const // Q: 20160711 // zwiększenie ciśnienia hamowania // ************************************************************************************************* -bool TMoverParameters::IncBrakePress(double &brake, double PressLimit, double dp) +bool physics::Vehicle::IncBrakePress(double &brake, double PressLimit, double dp) { bool IBP; // if (DynamicBrakeType<>dbrake_switch) and (DynamicBrakeType<>dbrake_none) and @@ -624,7 +624,7 @@ bool TMoverParameters::IncBrakePress(double &brake, double PressLimit, double dp // Q: 20160711 // zmniejszenie ciśnienia hamowania // ************************************************************************************************* -bool TMoverParameters::DecBrakePress(double &brake, double PressLimit, double dp) +bool physics::Vehicle::DecBrakePress(double &brake, double PressLimit, double dp) { bool DBP; @@ -650,7 +650,7 @@ bool TMoverParameters::DecBrakePress(double &brake, double PressLimit, double dp // Q: 20160711 // przełączenie nastawy hamulca O/P/T // ************************************************************************************************* -bool TMoverParameters::BrakeDelaySwitch(int BDS) +bool physics::Vehicle::BrakeDelaySwitch(int BDS) { bool rBDS; if (Hamulec->SetBDF(BDS)) @@ -672,7 +672,7 @@ bool TMoverParameters::BrakeDelaySwitch(int BDS) // Q: 20160712 // zwiększenie przełożenia hamulca // ************************************************************************************************* -bool TMoverParameters::IncBrakeMult(void) +bool physics::Vehicle::IncBrakeMult(void) { bool IBM; @@ -696,7 +696,7 @@ bool TMoverParameters::IncBrakeMult(void) // Q: 20160712 // zmniejszenie przełożenia hamulca // ************************************************************************************************* -bool TMoverParameters::DecBrakeMult(void) +bool physics::Vehicle::DecBrakeMult(void) { bool DBM; if (LoadFlag > 1 && MBPM < 2) @@ -719,7 +719,7 @@ bool TMoverParameters::DecBrakeMult(void) // Q: 20160712 // zaktualizowanie ciśnienia w hamulcach // ************************************************************************************************* -void TMoverParameters::UpdateBrakePressure(double dt) +void physics::Vehicle::UpdateBrakePressure(double dt) { // const double LBDelay = 5.0; // stala czasowa hamulca // double Rate, Speed, dp, sm; @@ -745,7 +745,7 @@ void TMoverParameters::UpdateBrakePressure(double dt) // Q: 20160712 // Obliczanie pracy sprężarki // ************************************************************************************************* -void TMoverParameters::CompressorCheck(double dt) +void physics::Vehicle::CompressorCheck(double dt) { if (CompressorSpeed == 0.0) @@ -891,7 +891,7 @@ void TMoverParameters::CompressorCheck(double dt) // Q: 20160712 // aktualizacja ciśnienia w przewodzie głównym // ************************************************************************************************* -void TMoverParameters::UpdatePipePressure(double dt) +void physics::Vehicle::UpdatePipePressure(double dt) { if (PipePress > 1.0) { @@ -900,7 +900,7 @@ void TMoverParameters::UpdatePipePressure(double dt) } // double dV; - // TMoverParameters *c; // T_MoverParameters + // physics::Vehicle *c; // physics::Vehicle double temp; // int b; @@ -976,7 +976,7 @@ void TMoverParameters::UpdatePipePressure(double dt) } // the flow of the local brake valve, by the handle, the TRAXX's timed one, the integrated controller or the parking -void TMoverParameters::UpdateLocalBrakeValve(double dt) +void physics::Vehicle::UpdateLocalBrakeValve(double dt) { // the local brake of a vehicle prepared for hauling (PulleeMode) is held released, whatever asks for it if (EngineType != TEngineType::ElectricInductionMotor) @@ -1016,7 +1016,7 @@ void TMoverParameters::UpdateLocalBrakeValve(double dt) } // the lock of the brake pipe and the flow of the driver's handle, from the main reservoir or into the air -void TMoverParameters::UpdateMainValve(double dt) +void physics::Vehicle::UpdateMainValve(double dt) { auto const temp{MainValveSupply()}; Handle->SetReductor(BrakeCtrlPos2); @@ -1056,7 +1056,7 @@ void TMoverParameters::UpdateMainValve(double dt) } // the pressure the driver's handle is fed from: the main pipe's, or the brake pipe's own with the pipe locked -double TMoverParameters::MainValveSupply() +double physics::Vehicle::MainValveSupply() { LockPipe = PipePress < (LockPipe ? LockPipeOff : LockPipeOn); bool lock_new = (LockPipe && !UnlockPipe && BrakeCtrlPosR > HandleUnlock) || (EmergencyCutsOffHandle && EmergencyValveFlow > 0); // new simple codition based on .fiz @@ -1071,7 +1071,7 @@ double TMoverParameters::MainValveSupply() } // the position the driver's handle works at: its own, or the one the speed control's brake intervention sets -double TMoverParameters::MainValveHandlePosition() const +double physics::Vehicle::MainValveHandlePosition() const { double pos = BrakeCtrlPosR; if (SpeedCtrlUnit.IsActive && SpeedCtrlUnit.BrakeIntervention && !SpeedCtrlUnit.Standby && BrakeCtrlPos != Handle->GetPos(bh_EB)) @@ -1085,7 +1085,7 @@ double TMoverParameters::MainValveHandlePosition() const return pos; } -void TMoverParameters::UpdateEmergencyValve(double dt) +void physics::Vehicle::UpdateEmergencyValve(double dt) { // ulepszony hamulec bezp. EmergencyValveFlow = 0.0; @@ -1107,7 +1107,7 @@ void TMoverParameters::UpdateEmergencyValve(double dt) } // what the distributor valve gets of the local brake and the load, by its kind -void TMoverParameters::UpdateDistributorSettings() +void physics::Vehicle::UpdateDistributorSettings() { switch (BrakeValve) { @@ -1218,7 +1218,7 @@ void TMoverParameters::UpdateDistributorSettings() } // the ep brake of the FVel6 and FVE408 handles, passed along the unit -void TMoverParameters::UpdateEPBrake() +void physics::Vehicle::UpdateEPBrake() { if (EPBrakeControlPowered()) // tu powinien byc jeszcze bezpiecznik EP i baterie - // temp = (Handle as TFVel6).GetCP @@ -1244,7 +1244,7 @@ void TMoverParameters::UpdateEPBrake() // Q: 20160713 // Aktualizacja ciśnienia w przewodzie zasilającym // ************************************************************************************************* -void TMoverParameters::UpdateScndPipePressure(double dt) +void physics::Vehicle::UpdateScndPipePressure(double dt) { if (ScndPipePress > 1.0) { @@ -1281,7 +1281,7 @@ void TMoverParameters::UpdateScndPipePressure(double dt) // yB: 20190906 // Aktualizacja ciśnienia w hamulcu sprezynowym // ************************************************************************************************* -void TMoverParameters::UpdateSpringBrake(double /*dt*/) +void physics::Vehicle::UpdateSpringBrake(double /*dt*/) { double BP = SpringBrake.PNBrakeConnection ? BrakePress : 0; double MSP = SpringBrake.ShuttOff ? 0 : SpringBrake.MaxSetPressure; @@ -1326,7 +1326,7 @@ bool pipe_wakes(double const Flow, double const Pressure, TReservoir const &Pipe // the pressure in the pipe of a coupled vehicle the flow to it goes by. the pressure the vehicle keeps is the one of its last step: // with Global.physics_pipewake one asleep can take air for a long time without waking, and the flow, going by that pressure, would // carry on past the pressure of the vehicle it comes from. so of one asleep, the pressure with what has flown in since -double neighbour_pipe_pressure(TMoverParameters const &Neighbour, double const Pressure, TReservoir const &Pipe) +double neighbour_pipe_pressure(physics::Vehicle const &Neighbour, double const Pressure, TReservoir const &Pipe) { if ((Global.physics_pipewake <= 0.f) || Neighbour.PhysicActivation) return Pressure; @@ -1339,10 +1339,10 @@ double neighbour_pipe_pressure(TMoverParameters const &Neighbour, double const P // Q: 20160715 // oblicza i zwraca przepływ powietrza pomiędzy pojazdami // ************************************************************************************************* -double TMoverParameters::GetDVc(double dt) +double physics::Vehicle::GetDVc(double dt) { - // T_MoverParameters *c; - TMoverParameters *c; + // physics::Vehicle *c; + physics::Vehicle *c; double dv1; double dv2; // , dV; @@ -1384,10 +1384,10 @@ double TMoverParameters::GetDVc(double dt) // the air the main reservoir hoses carry between the vehicle's pipe and the neighbours' in dt: the neighbours' // share is sent to them, the vehicle's own returned // ************************************************************************************************* -double TMoverParameters::GetScndDVc(double dt) +double physics::Vehicle::GetScndDVc(double dt) { const double Spz = 0.5067; - TMoverParameters *c; + physics::Vehicle *c; double dv1 = 0; double dv2 = 0; @@ -1421,35 +1421,35 @@ namespace { -// a pipe along the train, whose air the hoses between the vehicles carry (TMoverParameters::UpdatePipeCouplers()) +// a pipe along the train, whose air the hoses between the vehicles carry (physics::Vehicle::UpdatePipeCouplers()) struct train_pipe { - std::shared_ptr TMoverParameters::*reservoir; - double TMoverParameters::*pressure; - bool TMoverParameters::*pending; // the vehicle stepped the pipe, the exchange through its hoses is yet to come + std::shared_ptr physics::Vehicle::*reservoir; + double physics::Vehicle::*pressure; + bool physics::Vehicle::*pending; // the vehicle stepped the pipe, the exchange through its hoses is yet to come CouplingSet hose; // the coupling of the pipe's hose - double (TMoverParameters::*exchange)(double); // the air the hoses carry in a step, the neighbours' share sent to them - double (*area)(TMoverParameters const &); // the cross-section of the hose, as the exchange takes it + double (physics::Vehicle::*exchange)(double); // the air the hoses carry in a step, the neighbours' share sent to them + double (*area)(physics::Vehicle const &); // the cross-section of the hose, as the exchange takes it }; // the brake pipe, GetDVc() -train_pipe const brake_pipe{&TMoverParameters::Pipe, - &TMoverParameters::PipePress, - &TMoverParameters::PipeCouplersPending, +train_pipe const brake_pipe{&physics::Vehicle::Pipe, + &physics::Vehicle::PipePress, + &physics::Vehicle::PipeCouplersPending, Coupling::brakeHose, - &TMoverParameters::GetDVc, - [](TMoverParameters const &Vehicle) { return Vehicle.Spg / (1.0 + 0.015 / Vehicle.Spg * Vehicle.Dim.L); }}; + &physics::Vehicle::GetDVc, + [](physics::Vehicle const &Vehicle) { return Vehicle.Spg / (1.0 + 0.015 / Vehicle.Spg * Vehicle.Dim.L); }}; // the main reservoir pipe, GetScndDVc() -train_pipe const main_reservoir_pipe{&TMoverParameters::Pipe2, - &TMoverParameters::ScndPipePress, - &TMoverParameters::ScndPipeCouplersPending, +train_pipe const main_reservoir_pipe{&physics::Vehicle::Pipe2, + &physics::Vehicle::ScndPipePress, + &physics::Vehicle::ScndPipeCouplersPending, Coupling::mainHose, - &TMoverParameters::GetScndDVc, - [](TMoverParameters const &) { return 0.5067 * 0.75; }}; + &physics::Vehicle::GetScndDVc, + [](physics::Vehicle const &) { return 0.5067 * 0.75; }}; // the number of sub-steps of dt the air exchange through the hoses of the vehicle's pipe needs: in one, the air a // hose carries stays below what evens out the pipes on its ends -int hose_substeps(TMoverParameters const &Vehicle, train_pipe const &Pipe, double const dt) +int hose_substeps(physics::Vehicle const &Vehicle, train_pipe const &Pipe, double const dt) { auto substeps{1}; auto const area{Pipe.area(Vehicle)}; @@ -1474,12 +1474,12 @@ int hose_substeps(TMoverParameters const &Vehicle, train_pipe const &Pipe, doubl // the vehicles of the list which stepped the pipe, each with the number of the train it is in: the ones joined by the hoses // of the pipe, directly, numbered in the order of their first vehicle in the list. a vehicle which didn't step the pipe // (its physics sleeps) takes the air sent to it without passing it on, so it ends a train -std::vector hose_trains(std::vector const &Vehicles, train_pipe const &Pipe) +std::vector hose_trains(std::vector const &Vehicles, train_pipe const &Pipe) { auto constexpr none{std::numeric_limits::max()}; std::vector trains(Vehicles.size(), none); // the vehicles by their address, for finding the neighbours in the list - std::vector> byaddress; + std::vector> byaddress; byaddress.reserve(Vehicles.size()); for (std::size_t index = 0; index < Vehicles.size(); ++index) { @@ -1489,8 +1489,8 @@ std::vector hose_trains(std::vector const &Vehi } } std::ranges::sort(byaddress); - auto const find = [&byaddress](TMoverParameters const *Vehicle) { - auto const found{std::ranges::lower_bound(byaddress, Vehicle, std::less<>{}, &std::pair::first)}; + auto const find = [&byaddress](physics::Vehicle const *Vehicle) { + auto const found{std::ranges::lower_bound(byaddress, Vehicle, std::less<>{}, &std::pair::first)}; return (found != byaddress.end() && found->first == Vehicle) ? found->second : none; }; std::size_t count{0}; @@ -1530,7 +1530,7 @@ std::vector hose_trains(std::vector const &Vehi // 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 &Pipe, double const dt) +void exchange_through_hoses(std::vector const &Vehicles, train_pipe const &Pipe, double const dt) { auto const trains{hose_trains(Vehicles, Pipe)}; std::vector substeps; @@ -1581,7 +1581,7 @@ void exchange_through_hoses(std::vector const &Vehicles, tra // pipes overshoot each other in turns and the distributors see the pressure up to 0.28 bar off what's in the pipe // (eu07/maszyna#368) // ************************************************************************************************* -int TMoverParameters::PipeCouplersSubsteps(double const dt) const +int physics::Vehicle::PipeCouplersSubsteps(double const dt) const { return hose_substeps(*this, brake_pipe, dt); } @@ -1592,7 +1592,7 @@ int TMoverParameters::PipeCouplersSubsteps(double const dt) const // the vehicles' own main reservoirs feeding the pipe in the same step, the pipes of the middle vehicles of a // multiple unit or of locomotives in multiple traction kept jumping 0.8 bar to and fro between the steps // ************************************************************************************************* -int TMoverParameters::ScndPipeCouplersSubsteps(double const dt) const +int physics::Vehicle::ScndPipeCouplersSubsteps(double const dt) const { return hose_substeps(*this, main_reservoir_pipe, dt); } @@ -1601,13 +1601,13 @@ int TMoverParameters::ScndPipeCouplersSubsteps(double const dt) const // the air exchange through the brake and the main reservoir hoses of the vehicles which stepped their pipes // (UpdatePipePressure(), UpdateScndPipePressure()) since the last call, each pipe in its own sub-steps // ************************************************************************************************* -void TMoverParameters::UpdatePipeCouplers(std::vector const &Vehicles, double const dt) +void physics::Vehicle::UpdatePipeCouplers(std::vector const &Vehicles, double const dt) { exchange_through_hoses(Vehicles, brake_pipe, dt); exchange_through_hoses(Vehicles, main_reservoir_pipe, dt); } -bool TMoverParameters::UpdateStopBrakeRelease(double const Demand, double const Dt) +bool physics::Vehicle::UpdateStopBrakeRelease(double const Demand, double const Dt) { if (Demand <= 0.0) { diff --git a/physics/components/securitysystem.cpp b/physics/components/securitysystem.cpp index 3b94ca658..ed943661c 100644 --- a/physics/components/securitysystem.cpp +++ b/physics/components/securitysystem.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. // the security system (vigilance, cab signalling, radio-stop) #include "stdafx.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/DynObj.h" #include "physics/oerlikonest.h" #include "utilities/Globals.h" @@ -234,7 +234,7 @@ void TSecuritySystem::load(std::string const &line, double Vmax) // zbicie czuwaka / SHP // ***************************************************************************** // hunter-091012: rozbicie alarmow, dodanie testu czuwaka -void TMoverParameters::SecuritySystemReset(void) // zbijanie czuwaka/SHP +void physics::Vehicle::SecuritySystemReset(void) // zbijanie czuwaka/SHP { // reset all, used by AI SecuritySystem.acknowledge_press(); @@ -246,7 +246,7 @@ void TMoverParameters::SecuritySystemReset(void) // zbijanie czuwaka/SHP // Q: 20160711 // sprawdzanie stanu CA/SHP // ************************************************************************************************* -void TMoverParameters::SecuritySystemCheck(double dt) +void physics::Vehicle::SecuritySystemCheck(double dt) { bool isPower = Power24vIsAvailable || Power110vIsAvailable; // the shunt mode of the SM42 switches its vigilance device (CA) off, on the vehicles with AwareOffInShuntMode=Yes (eu07/maszyna#457) @@ -263,7 +263,7 @@ void TMoverParameters::SecuritySystemCheck(double dt) // Q: 20160711 // włączenie / wyłączenie hamowania awaryjnego // ************************************************************************************************* -bool TMoverParameters::RadiostopSwitch(bool Switch) +bool physics::Vehicle::RadiostopSwitch(bool Switch) { bool EBS; if (BrakeSystem != TBrakeSystem::Individual && BrakeCtrlPosNo > 0) diff --git a/physics/components/setup.cpp b/physics/components/setup.cpp index 086e37ddc..f5c8944bd 100644 --- a/physics/components/setup.cpp +++ b/physics/components/setup.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. // setting the vehicle up after reading its definition: the checks, the brake valves, the handles and the pipes #include "stdafx.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/DynObj.h" #include "physics/oerlikonest.h" #include "utilities/Globals.h" @@ -34,7 +34,7 @@ http://mozilla.org/MPL/2.0/. // Q: 20160717 // ************************************************************************************************* -bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) +bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) { WriteLog("check locomotive parameters..."); bool OK = true; @@ -152,13 +152,13 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) { IncBrakeMult(); IncBrakeMult(); - DecBrakeMult(); // TODO: przeinesiono do mover.cpp + DecBrakeMult(); // TODO: przeinesiono do physics.cpp if (LoadAmount < MaxLoad * 0.35) DecBrakeMult(); } else { - IncBrakeMult(); // TODO: przeinesiono do mover.cpp + IncBrakeMult(); // TODO: przeinesiono do physics.cpp if (LoadAmount >= MaxLoad * 0.55) IncBrakeMult(); } @@ -219,7 +219,7 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) } // the distributor valve of the vehicle's kind -void TMoverParameters::CreateBrakeValve() +void physics::Vehicle::CreateBrakeValve() { switch (BrakeValve) { @@ -318,7 +318,7 @@ void TMoverParameters::CreateBrakeValve() } // the driver's handle and the local brake handle of the vehicle's kinds -void TMoverParameters::CreateBrakeHandles() +void physics::Vehicle::CreateBrakeHandles() { switch (BrakeHandle) { @@ -384,7 +384,7 @@ void TMoverParameters::CreateBrakeHandles() } // the brake pipe, the main pipe and the spring brake's cylinder -void TMoverParameters::CreateBrakePipes() +void physics::Vehicle::CreateBrakePipes() { if (true == TestFlag(BrakeDelays, bdelay_G) && (false == TestFlag(BrakeDelays, bdelay_R) || Power > 1.0)) // ustalanie srednicy przewodu glownego (lokomotywa lub napędowy Spg = 0.792; @@ -404,7 +404,7 @@ void TMoverParameters::CreateBrakePipes() } // the pressure of the main pipe at the start: the main reservoir's, or HosePressure fed through a main hose, or none -double TMoverParameters::InitialScndPipePress(double const HosePressure) const +double physics::Vehicle::InitialScndPipePress(double const HosePressure) const { if (VeselVolume > 0.0) { @@ -418,7 +418,7 @@ double TMoverParameters::InitialScndPipePress(double const HosePressure) const } // the air and the controls of a vehicle ready to depart -void TMoverParameters::SetReadyToDepart() +void physics::Vehicle::SetReadyToDepart() { WriteLog("Ready to depart"); CompressedVolume = VeselVolume * MinCompressor * 9.8 / 10.0; @@ -445,7 +445,7 @@ void TMoverParameters::SetReadyToDepart() } // the air and the brakes of a vehicle standing braked -void TMoverParameters::SetBraked() +void physics::Vehicle::SetBraked() { WriteLog("Braked"); Volume = BrakeVVolume * MaxBrakePress[3]; diff --git a/physics/components/traction.cpp b/physics/components/traction.cpp index de089e04b..62b45c2c2 100644 --- a/physics/components/traction.cpp +++ b/physics/components/traction.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. // the traction motors and their forces for each kind of drive, the relays, the fuses, the dynamic brake #include "stdafx.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/DynObj.h" #include "physics/oerlikonest.h" #include "utilities/Globals.h" @@ -59,7 +59,7 @@ double TableInterpolation(std::map &Map, double Parameter) // Q: 20160716 // Obliczanie natężenie prądu w silnikach // ************************************************************************************************* -double TMoverParameters::Current(double n, double U) +double physics::Vehicle::Current(double n, double U) { // wazna funkcja - liczy prad plynacy przez silniki polaczone szeregowo lub rownolegle // w zaleznosci od polozenia nastawnikow MainCtrl i ScndCtrl oraz predkosci obrotowej n @@ -130,7 +130,7 @@ double TMoverParameters::Current(double n, double U) } // the automatic dynamic brake of the series motors (EP09, the units) on or off, and the distributor told of it -void TMoverParameters::UpdateSeriesMotorDynamicBrakeFlag() +void physics::Vehicle::UpdateSeriesMotorDynamicBrakeFlag() { // i dzialanie hamulca ED w EP09 if (DynamicBrakeType == dbrake_automatic && TrainType != train_type::emu) @@ -165,7 +165,7 @@ void TMoverParameters::UpdateSeriesMotorDynamicBrakeFlag() // the current of the series motors connected, at the revolutions n and the voltage U, through the resistance R of // Mn motors in series -double TMoverParameters::SeriesMotorCurrent(double const n, double const U, double const R, double const Mn) const +double physics::Vehicle::SeriesMotorCurrent(double const n, double const U, double const R, double const Mn) const { double MotorCurrent{0.0}; double Rz; @@ -210,7 +210,7 @@ double TMoverParameters::SeriesMotorCurrent(double const n, double const U, doub // the current of the series motors driving, at the revolutions n, the voltage U and the resistance Rz of Mn motors in // series, by the motor parameters of the shunt field SP -double TMoverParameters::SeriesMotorDrivingCurrent(double const n, double const U, double const Rz, double const Mn, int const SP) const +double physics::Vehicle::SeriesMotorDrivingCurrent(double const n, double const U, double const Rz, double const Mn, int const SP) const { double MotorCurrent; double Delta; @@ -240,7 +240,7 @@ double TMoverParameters::SeriesMotorDrivingCurrent(double const n, double const } // the line breaker opened, and the motors damaged, by too high revolutions or current -void TMoverParameters::MotorFailuresCheck(double const n) +void physics::Vehicle::MotorFailuresCheck(double const n) { double MotorCurrent; // awarie @@ -260,7 +260,7 @@ void TMoverParameters::MotorFailuresCheck(double const n) } // rozruch wysoki (true) albo niski (false) -bool TMoverParameters::CurrentSwitch(bool const State) +bool physics::Vehicle::CurrentSwitch(bool const State) { // TBD, TODO: split off shunt mode toggle into a separate command? It doesn't make much sense to have these two together like that // the diesels with a shunt mode have no motor overload relay threshold to switch, the switch sets their shunt mode alone. @@ -288,13 +288,13 @@ bool TMoverParameters::CurrentSwitch(bool const State) return false; }; -bool TMoverParameters::IsMotorOverloadRelayHighThresholdOn() const +bool physics::Vehicle::IsMotorOverloadRelayHighThresholdOn() const { return ImaxHi > ImaxLo && Imax > ImaxLo; } -double TMoverParameters::ShowEngineRotation(int VehN) const +double physics::Vehicle::ShowEngineRotation(int VehN) const { // Zwraca wartość prędkości obrotowej silnika wybranego pojazdu. Do 3 pojazdów (3×SN61). int b; switch (VehN) @@ -317,7 +317,7 @@ double TMoverParameters::ShowEngineRotation(int VehN) const return 0.0; }; -void TMoverParameters::MotorBlowersCheck(double const Timestep) +void physics::Vehicle::MotorBlowersCheck(double const Timestep) { // activation check for (auto &blower : MotorBlowers) @@ -376,7 +376,7 @@ void TMoverParameters::MotorBlowersCheck(double const Timestep) } } -bool TMoverParameters::MotorBlowerPowerIsAvailable(cooling_fan const &Blower) const +bool physics::Vehicle::MotorBlowerPowerIsAvailable(cooling_fan const &Blower) const { switch (Blower.start_type) { @@ -389,12 +389,12 @@ bool TMoverParameters::MotorBlowerPowerIsAvailable(cooling_fan const &Blower) co } } -double TMoverParameters::ShowCurrent(int AmpN) const +double physics::Vehicle::ShowCurrent(int AmpN) const { // Odczyt poboru prądu na podanym amperomierzu return Drive().ShowCurrent(*this, AmpN); }; -bool TMoverParameters::MotorBlowersSwitch(bool State, VehicleEnd const Side, range_t const Notify) +bool physics::Vehicle::MotorBlowersSwitch(bool State, VehicleEnd const Side, range_t const Notify) { auto &fan{MotorBlowers[Side]}; @@ -418,7 +418,7 @@ bool TMoverParameters::MotorBlowersSwitch(bool State, VehicleEnd const Side, ran return fan.is_enabled != initialstate; } -bool TMoverParameters::MotorBlowersSwitchOff(bool State, VehicleEnd const Side, range_t const Notify) +bool physics::Vehicle::MotorBlowersSwitchOff(bool State, VehicleEnd const Side, range_t const Notify) { auto &fan{MotorBlowers[Side]}; @@ -443,7 +443,7 @@ bool TMoverParameters::MotorBlowersSwitchOff(bool State, VehicleEnd const Side, } // the traction selector of a dual-mode vehicle: moves only with the line breaker open, and only where a genset is -bool TMoverParameters::TractionModeSwitch(traction_mode const Mode, range_t const Notify) +bool physics::Vehicle::TractionModeSwitch(traction_mode const Mode, range_t const Notify) { auto const initialstate{TractionMode}; // refused with the line breaker closed, and then not passed on either, so the train stays on one source @@ -466,7 +466,7 @@ bool TMoverParameters::TractionModeSwitch(traction_mode const Mode, range_t cons // zwiększenie nastawy nastawnika hamulca elektrodynamicznego (DynamicBrakeCtrl) // uzywane gdy SplitEDPneumaticBrake = true // ************************************************************************************************* -bool TMoverParameters::IncDynamicBrakeLevel(float const CtrlSpeed) +bool physics::Vehicle::IncDynamicBrakeLevel(float const CtrlSpeed) { if (false == SplitEDPneumaticBrake) return false; @@ -483,7 +483,7 @@ bool TMoverParameters::IncDynamicBrakeLevel(float const CtrlSpeed) // ************************************************************************************************* // zmniejszenie nastawy nastawnika hamulca elektrodynamicznego (DynamicBrakeCtrl) // ************************************************************************************************* -bool TMoverParameters::DecDynamicBrakeLevel(float const CtrlSpeed) +bool physics::Vehicle::DecDynamicBrakeLevel(float const CtrlSpeed) { if (false == SplitEDPneumaticBrake) return false; @@ -500,7 +500,7 @@ bool TMoverParameters::DecDynamicBrakeLevel(float const CtrlSpeed) // ************************************************************************************************* // bezposrednie ustawienie nastawnika hamulca elektrodynamicznego (DynamicBrakeCtrl) // ************************************************************************************************* -bool TMoverParameters::DynamicBrakeLevelSet(double Position) +bool physics::Vehicle::DynamicBrakeLevelSet(double Position) { if (false == SplitEDPneumaticBrake) return false; @@ -512,7 +512,7 @@ bool TMoverParameters::DynamicBrakeLevelSet(double Position) // odczyt nastawy nastawnika hamulca elektrodynamicznego (DynamicBrakeCtrl) // zwraca 0 jezeli SplitEDPneumaticBrake nie jest aktywne (dla zachowania starej logiki) // ************************************************************************************************* -double TMoverParameters::DynamicBrakeRatio(void) const +double physics::Vehicle::DynamicBrakeRatio(void) const { if (false == SplitEDPneumaticBrake) return 0.0; @@ -522,7 +522,7 @@ double TMoverParameters::DynamicBrakeRatio(void) const // ************************************************************************************************* // czy hamulec ED jest aktualnie dostepny w oknie predkosci Vh0..Vh1 // ************************************************************************************************* -bool TMoverParameters::DynamicBrakeAvailable(void) const +bool physics::Vehicle::DynamicBrakeAvailable(void) const { double const vh0{inductionMotor.braking.offSpeed}; if (double const vh1{inductionMotor.braking.fullSpeed}; vh1 <= 0.001) @@ -538,7 +538,7 @@ bool TMoverParameters::DynamicBrakeAvailable(void) const // Q: 20160713 // reczne przelaczanie hamulca elektrodynamicznego // ************************************************************************************************* -bool TMoverParameters::DynamicBrakeSwitch(bool Switch) +bool physics::Vehicle::DynamicBrakeSwitch(bool Switch) { bool DBS; @@ -566,7 +566,7 @@ bool TMoverParameters::DynamicBrakeSwitch(bool Switch) // Q: 20160714 // oblicza sile trakcyjna lokomotywy (dla elektrowozu tez calkowity prad) // ************************************************************************************************* -double TMoverParameters::TractionForce(double dt) +double physics::Vehicle::TractionForce(double dt) { Ft = 0; double dtrans{0.0}; @@ -600,13 +600,13 @@ double TMoverParameters::TractionForce(double dt) } // the starting resistors' blowers, and the diesels' radiator fans -void TMoverParameters::UpdateVentilators(double dt) +void physics::Vehicle::UpdateVentilators(double dt) { Drive().UpdateVentilators(*this, dt); } // the starting resistors' blowers of the series motors with the line breaker closed, worked by hand or by the current -void TMoverParameters::UpdateResistorBlowers(double dt) +void physics::Vehicle::UpdateResistorBlowers(double dt) { switch (RVentType) { @@ -655,18 +655,18 @@ void TMoverParameters::UpdateResistorBlowers(double dt) } // the power of a dumb or diesel engine; returns the ratio of the power a dumb engine is set to -double TMoverParameters::UpdateEnginePower() +double physics::Vehicle::UpdateEnginePower() { return Drive().UpdateEnginePower(*this); } // the line breaker opened by a voltage out of the motors' range, and the line contactors of a diesel-electric -void TMoverParameters::VoltageRelaysCheck() +void physics::Vehicle::VoltageRelaysCheck() { Drive().CheckVoltageRelays(*this); } -void TMoverParameters::DumbTractionForce(double const PosRatio) +void physics::Vehicle::DumbTractionForce(double const PosRatio) { if (Mains && CabActive != 0) { @@ -686,7 +686,7 @@ void TMoverParameters::DumbTractionForce(double const PosRatio) } } -void TMoverParameters::WheelsDrivenTractionForce(double dt) +void physics::Vehicle::WheelsDrivenTractionForce(double dt) { if (EnginePowerSource.SourceType == TPowerSource::InternalSource && EnginePowerSource.PowerType == TPowerType::BioPower) Ft = Sign(sin(eAngle)) * PulseForce * Transmision.Ratio; @@ -700,7 +700,7 @@ void TMoverParameters::WheelsDrivenTractionForce(double dt) EnginePower = Ft * (1.0 + Vel); } -void TMoverParameters::SeriesMotorTractionForce(double dt) +void physics::Vehicle::SeriesMotorTractionForce(double dt) { // enrot:=Transmision.Ratio*nrot; // yB: szereg dwoch sekcji w ET42 @@ -712,7 +712,7 @@ void TMoverParameters::SeriesMotorTractionForce(double dt) { if (Imax == ImaxHi) EngineVoltage = EngineVoltage * 2; - if (DynamicBrakeFlag && abs(Im) > 300) // przeiesione do mover.cpp + if (DynamicBrakeFlag && abs(Im) > 300) // przeiesione do physics.cpp FuseOff(); } if (DynamicBrakeType == dbrake_automatic && DynamicBrakeFlag) @@ -742,7 +742,7 @@ void TMoverParameters::SeriesMotorTractionForce(double dt) } // the automatic dynamic brake of the series motors: the excitation current, by the stages of the ep brake (TUHEX) -void TMoverParameters::SeriesMotorDynamicBrake(double dt) +void physics::Vehicle::SeriesMotorDynamicBrake(double dt) { if (TUHEX_Stages > 0) // hamowanie wielostopniowe, nadpisuje wartości domyślne { @@ -794,7 +794,7 @@ void TMoverParameters::SeriesMotorDynamicBrake(double dt) // the shunt field relays of a diesel-electric, each kind its own conditions on the current, the speed or the // power (tmp, the power the engine gives) -void TMoverParameters::ShuntFieldRelaysCheck(double const tmpV, double const PosRatio, double const tmp) +void physics::Vehicle::ShuntFieldRelaysCheck(double const tmpV, double const PosRatio, double const tmp) { auto const shuntfieldstate{ScndCtrlPos}; @@ -861,7 +861,7 @@ void TMoverParameters::ShuntFieldRelaysCheck(double const tmpV, double const Pos } // the relays of type 2: up by the speed while the engine has power to spare (tmp, the power it gives), down by the current -void TMoverParameters::ShuntFieldRelaysType2(double const tmp) +void physics::Vehicle::ShuntFieldRelaysType2(double const tmp) { if (ScndCtrlPos < ScndCtrlPosNo && MPTRelay[ScndCtrlPos].Iup < Vel && EnginePower < tmp * 0.99) { @@ -874,7 +874,7 @@ void TMoverParameters::ShuntFieldRelaysType2(double const tmp) } // the relays of type 41: up by the speed tmpV at full power, the engine slowed down, down by the current -void TMoverParameters::ShuntFieldRelaysType41(double const tmpV) +void physics::Vehicle::ShuntFieldRelaysType41(double const tmpV) { if (ScndCtrlPos < ScndCtrlPosNo && MainCtrlPos == MainCtrlPosNo && tmpV * 3.6 > MPTRelay[ScndCtrlPos].Iup) { @@ -888,7 +888,7 @@ void TMoverParameters::ShuntFieldRelaysType41(double const tmpV) } // the relays of type 45, by the current and the speed: up from the 11th position, at most two under it, none under the 8th -void TMoverParameters::ShuntFieldRelaysType45() +void physics::Vehicle::ShuntFieldRelaysType45() { if (ScndCtrlPos < ScndCtrlPosNo && MainCtrlPos >= 11) { @@ -943,7 +943,7 @@ void TMoverParameters::ShuntFieldRelaysType45() // the relays of type 46, by the current and the speed: up from the 12th position, down under it below 50 km/h, at most two // under the 11th, none under the 8th -void TMoverParameters::ShuntFieldRelaysType46() +void physics::Vehicle::ShuntFieldRelaysType46() { // wzrastanie if (MainCtrlPos >= 12 && ScndCtrlPos < ScndCtrlPosNo) @@ -966,7 +966,7 @@ void TMoverParameters::ShuntFieldRelaysType46() } // a relay of type 46 down: an even one by the current, an odd one by the current and the speed -void TMoverParameters::ShuntFieldRelaysType46Down() +void physics::Vehicle::ShuntFieldRelaysType46Down() { // above 50 km/h already active shunt field can be maintained until lower controller setting if (ScndCtrlPos % 2 == 0) @@ -986,7 +986,7 @@ void TMoverParameters::ShuntFieldRelaysType46Down() } // a relay of type 46 up: an even one by the current, an odd one by the current and the speed -void TMoverParameters::ShuntFieldRelaysType46Up() +void physics::Vehicle::ShuntFieldRelaysType46Up() { if (ScndCtrlPos % 2 == 0) { @@ -1004,7 +1004,7 @@ void TMoverParameters::ShuntFieldRelaysType46Up() } } -void TMoverParameters::InductionMotorTractionForce(double dt) +void physics::Vehicle::InductionMotorTractionForce(double dt) { if (MainCircuitPowered() && !SecuritySystem.is_engine_blocked()) { @@ -1053,7 +1053,7 @@ void TMoverParameters::InductionMotorTractionForce(double dt) } // the speed control (tempomat) of an induction motor drive, set by its second controller -void TMoverParameters::InductionMotorSpeedControl(double dt) +void physics::Vehicle::InductionMotorSpeedControl(double dt) { // tempomat if (ScndCtrlPosNo == 4 && SpeedCtrlTypeTime) @@ -1067,7 +1067,7 @@ void TMoverParameters::InductionMotorSpeedControl(double dt) } // the speed control set by the position of the second controller, after it's been held for its delay -void TMoverParameters::SpeedControlByPosition(double dt) +void physics::Vehicle::SpeedControlByPosition(double dt) { if (ScndCtrlPos != NewSpeed) { @@ -1093,7 +1093,7 @@ void TMoverParameters::SpeedControlByPosition(double dt) // the speed control of a four position second controller, by time: the speed set down or up by 10 km/h a step, held, // or off and at the top -void TMoverParameters::SpeedControlByTime(double dt) +void physics::Vehicle::SpeedControlByTime(double dt) { SpeedCtrlUnit.IsActive = SpeedCtrlValue > 0; switch (ScndCtrlPos) @@ -1141,7 +1141,7 @@ void TMoverParameters::SpeedControlByTime(double dt) // whether the induction motors brake, and the share of the electrodynamic and the pneumatic brake; sets the // force asked of the motors (PosRatio) and how fast the drive follows it (tmp) -void TMoverParameters::InductionMotorBrakeBlending(double const ActiveInverters, double &PosRatio, double &tmp) +void physics::Vehicle::InductionMotorBrakeBlending(double const ActiveInverters, double &PosRatio, double &tmp) { InductionMotorDynamicBrakeFlag(); auto const edBCP{Hamulec->GetEDBCP() * inductionMotor.braking.cylinderPressureGain}; // stala napedu @@ -1171,7 +1171,7 @@ void TMoverParameters::InductionMotorBrakeBlending(double const ActiveInverters, // the electrodynamic brake of the induction motors on: with the doors open or permitted, by the train brake, the local // brake or its own controller; off without them -void TMoverParameters::InductionMotorDynamicBrakeFlag() +void physics::Vehicle::InductionMotorDynamicBrakeFlag() { double const edBCP = Hamulec->GetEDBCP(); auto const localbrakeactive{CabOccupied != 0 && LocHandle->GetCP() > 0.25}; @@ -1193,7 +1193,7 @@ void TMoverParameters::InductionMotorDynamicBrakeFlag() // the share of the electrodynamic brake (negative), and the distributor told how much of the air to let out; none // when the air brake cuts the electrodynamic one off, or an inverter is out -double TMoverParameters::InductionMotorBrakeRatio(double const ActiveInverters, double const edBCP) +double physics::Vehicle::InductionMotorBrakeRatio(double const ActiveInverters, double const edBCP) { double PosRatio; // ustalanie współczynnika blendingu do luzowania hamulca PN @@ -1238,7 +1238,7 @@ double TMoverParameters::InductionMotorBrakeRatio(double const ActiveInverters, } // the model of the induction motors and their inverters: voltage, frequency, currents, moment and force -void TMoverParameters::InductionMotorDrive(double dt) +void physics::Vehicle::InductionMotorDrive(double dt) { double tmp; if (DynamicBrakeFlag) @@ -1315,7 +1315,7 @@ void TMoverParameters::InductionMotorDrive(double dt) // the force the motors give at full and at the setting (inductionMotor.forceShare), braking within the power and the force of the // electrodynamic brake, driving within the power and the starting force -void TMoverParameters::InductionMotorForceLimits() +void physics::Vehicle::InductionMotorForceLimits() { if (inductionMotor.forceShare < 0) { @@ -1344,7 +1344,7 @@ void TMoverParameters::InductionMotorForceLimits() } // the frequency of the inverters at the motors' slip frequency, from the list of the drive or of its brake -void TMoverParameters::UpdateInverterFrequency() +void physics::Vehicle::UpdateInverterFrequency() { auto const tmpV{std::abs(inductionMotor.state.supplyFrequency)}; auto const useFFEDList = FFEDListSize > 0 && DynamicBrakeFlag; @@ -1367,7 +1367,7 @@ void TMoverParameters::UpdateInverterFrequency() } // the induction motor drive without power, or blocked by the security system -void TMoverParameters::InductionMotorOff() +void physics::Vehicle::InductionMotorOff() { for (auto &inv : inductionMotor.inverters) { @@ -1393,7 +1393,7 @@ void TMoverParameters::InductionMotorOff() // Q: 20160713 // Sprawdzenie bezpiecznika nadmiarowego // ************************************************************************************************* -bool TMoverParameters::FuseFlagCheck(void) const +bool physics::Vehicle::FuseFlagCheck(void) const { bool FFC; @@ -1412,7 +1412,7 @@ bool TMoverParameters::FuseFlagCheck(void) const // Q: 20160713 // Załączenie bezpiecznika nadmiarowego // ************************************************************************************************* -bool TMoverParameters::FuseOn(range_t const Notify) +bool physics::Vehicle::FuseOn(range_t const Notify) { auto const result{RelayReset(relay_t::maincircuitground | relay_t::tractionnmotoroverload, Notify)}; @@ -1423,7 +1423,7 @@ bool TMoverParameters::FuseOn(range_t const Notify) // Q: 20160713 // Wyłączenie bezpiecznika nadmiarowego // ************************************************************************************************* -void TMoverParameters::FuseOff(void) +void physics::Vehicle::FuseOff(void) { if (!FuseFlag) { @@ -1434,7 +1434,7 @@ void TMoverParameters::FuseOff(void) } // resets relays assigned to specified customizable reset button -bool TMoverParameters::UniversalResetButton(int const Button, range_t const Notify) +bool physics::Vehicle::UniversalResetButton(int const Button, range_t const Notify) { if (auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; false == lowvoltagepower) @@ -1454,7 +1454,7 @@ bool TMoverParameters::UniversalResetButton(int const Button, range_t const Noti } // resets state of specified relays -bool TMoverParameters::RelayReset(int const Relays, range_t const Notify) +bool physics::Vehicle::RelayReset(int const Relays, range_t const Notify) { auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; @@ -1507,7 +1507,7 @@ bool TMoverParameters::RelayReset(int const Relays, range_t const Notify) // Q: 20160713 // Przeliczenie prędkości liniowej na obrotową // ************************************************************************************************* -double TMoverParameters::v2n(void) +double physics::Vehicle::v2n(void) { // przelicza predkosc liniowa na obrotowa const double dmgn = 0.5; @@ -1534,7 +1534,7 @@ double TMoverParameters::v2n(void) // Q: 20160714 // Oblicza moment siły wytwarzany przez silnik // ************************************************************************************************* -double TMoverParameters::Momentum(double I) const +double physics::Vehicle::Momentum(double I) const { // liczy moment sily wytwarzany przez silnik elektryczny} int SP; @@ -1551,7 +1551,7 @@ double TMoverParameters::Momentum(double I) const // Q: 20160714 // Oblicza moment siły do sterowania wzbudzeniem // ************************************************************************************************* -double TMoverParameters::MomentumF(double I, double Iw, int SCP) const +double physics::Vehicle::MomentumF(double I, double Iw, int SCP) const { // umozliwia dokladne sterowanie wzbudzeniem @@ -1562,7 +1562,7 @@ double TMoverParameters::MomentumF(double I, double Iw, int SCP) const // Q: 20160713 // Odłączenie uszkodzonych silników // ************************************************************************************************* -bool TMoverParameters::CutOffEngine(void) +bool physics::Vehicle::CutOffEngine(void) { bool COE = false; // Ra: wartość domyślna, sprawdzić to trzeba if (NPoweredAxles > 0 && CabActive == 0 && EngineType == TEngineType::ElectricSeriesMotor && DamageFlag.Clear(VehicleDamage::engine)) @@ -1577,7 +1577,7 @@ bool TMoverParameters::CutOffEngine(void) // Q: 20160713 // Przełączenie wysoki / niski prąd rozruchu // ************************************************************************************************* -bool TMoverParameters::MaxCurrentSwitch(bool State, range_t const Notify) +bool physics::Vehicle::MaxCurrentSwitch(bool State, range_t const Notify) { auto const initialstate{MotorOverloadRelayHighThreshold}; @@ -1595,7 +1595,7 @@ bool TMoverParameters::MaxCurrentSwitch(bool State, range_t const Notify) // Q: 20160713 // Przełączenie wysoki / niski prąd rozruchu automatycznego // ************************************************************************************************* -bool TMoverParameters::MinCurrentSwitch(bool State) +bool physics::Vehicle::MinCurrentSwitch(bool State) { bool MCS = false; if ((EngineType == TEngineType::ElectricSeriesMotor && IminHi > IminLo) || (TrainType == train_type::emu && EngineType != TEngineType::ElectricInductionMotor)) @@ -1623,7 +1623,7 @@ bool TMoverParameters::MinCurrentSwitch(bool State) // Q: 20160713 // Sprawdzenie wskaźnika jazdy na oporach // ************************************************************************************************* -bool TMoverParameters::ResistorsFlagCheck(void) const +bool physics::Vehicle::ResistorsFlagCheck(void) const { bool RFC = false; @@ -1642,7 +1642,7 @@ bool TMoverParameters::ResistorsFlagCheck(void) const // Q: 20160714 // Zwraca wartość natężenia prądu na wybranym amperomierzu. Podfunkcja do ShowCurrent. // ************************************************************************************************* -double TMoverParameters::ShowCurrentP(int AmpN) const +double physics::Vehicle::ShowCurrentP(int AmpN) const { int Bn; bool Grupowy; @@ -1677,7 +1677,7 @@ double TMoverParameters::ShowCurrentP(int AmpN) const } // the drive of the kind of engine of the vehicle -TractionDrive const &TMoverParameters::Drive() const +TractionDrive const &physics::Vehicle::Drive() const { return DriveOf(EngineType); } diff --git a/physics/couplerphysics.h b/physics/couplerphysics.h index 8d7f9b06e..d7278cf63 100644 --- a/physics/couplerphysics.h +++ b/physics/couplerphysics.h @@ -4,7 +4,7 @@ #include // the physical model of the coupling of two vehicles, used with couplerphysics set in eu07.ini (the legacy model of -// TMoverParameters::CouplerForce() otherwise). each vehicle end brings its buffers and its draw gear: progressive +// physics::Vehicle::CouplerForce() otherwise). each vehicle end brings its buffers and its draw gear: progressive // springs with friction hysteresis, pressed in series against those of the other end. the coupling has play (slack) // in tension, or pulls the buffers in when its screw is tightened, and its steel link stretches for good past its // yield force and breaks at its ultimate one, under a steady pull or the jerk of a run-out of the slack diff --git a/physics/derailment.h b/physics/derailment.h index e25e027cc..d0b095b0d 100644 --- a/physics/derailment.h +++ b/physics/derailment.h @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. // the criteria of a vehicle leaving the rails, as plain functions of what the vehicle and the track under it are // like, so the collisions and the buckled track can use them as well as the speed in a curve does -// (physics.derailment new in eu07.ini, see TMoverParameters::check_derailment()). two ways off the rails: +// (physics.derailment new in eu07.ini, see physics::Vehicle::check_derailment()). two ways off the rails: // // overturning: the lateral acceleration the cant doesn't balance, a = v^2 / R - g * sin(cant), takes the load off the // inner wheels; the unloading ratio D = dQ / Q = 2 / s * a / g * (h + s_flex * (h - h_c)) reaches 1 when they lift. @@ -112,7 +112,7 @@ struct vehicle_state { std::array ends{}; }; -// the dtrack_* flags of the track (mover.h) the criteria look at +// the dtrack_* flags of the track (vehicle.h) the criteria look at namespace track_damage { inline constexpr int railwear{2}; inline constexpr int freerail{4}; diff --git a/physics/mover.h b/physics/vehicle.h similarity index 98% rename from physics/mover.h rename to physics/vehicle.h index 439574ce6..1b2f5c8d8 100644 --- a/physics/mover.h +++ b/physics/vehicle.h @@ -28,6 +28,10 @@ http://mozilla.org/MPL/2.0/. class TractionDrive; class cParser; +namespace physics +{ +class Vehicle; +} /* MaSzyna EU07 locomotive simulator Copyright (C) 2001-2004 Maciej Czapkiewicz and others @@ -202,8 +206,8 @@ enum class TPowerSource struct engine_generator { // ld inputs - /// Pointer to the prime-mover revolutions [rev/s]. - double *engine_revolutions; // revs per second of the prime mover + /// Pointer to the prime-physics revolutions [rev/s]. + double *engine_revolutions; // revs per second of the prime physics // config /// Minimum working rev rate [rev/s]. double revolutions_min; // min working revolutions rate, in revs per second @@ -227,7 +231,7 @@ struct TAccumulator double MaxCapacity; /// Source used to recharge the battery. TPowerSource RechargeSource; - // inline _mover__1() { + // inline _vehicle__1() { // MaxCapacity = 0.0; // RechargeSource = NotDefined; // } @@ -240,7 +244,7 @@ struct TPowerCable TPowerType PowerTrans; /// Steam pressure (when SteamPower is transmitted) [bar]. double SteamPressure; - // inline _mover__2() { + // inline _vehicle__2() { // SteamPressure = 0.0; // PowerTrans = NoPower; // } @@ -488,7 +492,7 @@ struct TCoupling /*zmienne*/ bool AutomaticCouplingAllowed{true}; // whether automatic coupling can be currently performed CouplingSet CouplingFlag; // what the coupling joins; none: the vehicles only see each other - class TMoverParameters *Connected = nullptr; /*co jest podlaczone*/ + class physics::Vehicle *Connected = nullptr; /*co jest podlaczone*/ int ConnectedNr = 0; // Ra: od której strony podłączony do (Connected): 0=przód, 1=tył // the end of the vehicle connected to, while there is one VehicleEnd ConnectedEnd() const @@ -604,7 +608,10 @@ struct speed_control double PowerDownSpeed = 1000; }; -class TMoverParameters +namespace physics +{ + +class Vehicle { // Ra: wrapper na kod pascalowy, przejmujący jego funkcje Q: 20160824 - juz nie wrapper a klasa bazowa :) private: // types @@ -1303,7 +1310,7 @@ class TMoverParameters bool PantAllDown{false}; double PantFrontVolt = 0.0; // pantograf pod napieciem? 'Winger 160404 double PantRearVolt = 0.0; - // TODO converter parameters, for when we start cleaning up mover parameters + // TODO converter parameters, for when we start cleaning up physics parameters start_t ConverterStart{start_t::manual}; // whether converter is started manually, or by other means float ConverterStartDelay{0.0f}; // delay (in seconds) before the converter is started, once its activation conditions are met double ConverterStartDelayTimer{0.0}; // helper, for tracking whether converter start delay passed @@ -1599,11 +1606,11 @@ class TMoverParameters bool AIHintPantUpIfIdle{true}; // whether raise both pantographs if idling for a while double AIHintLocalBrakeAccFactor{1.05}; // suggested acceleration weight for local brake operation - TMoverParameters(double VelInitial, std::string const &TypeNameInit, std::string const &NameInit, int Cab); + Vehicle(double VelInitial, std::string const &TypeNameInit, std::string const &NameInit, int Cab); // obsługa sprzęgów - static double CouplerDist(TMoverParameters const *Left, TMoverParameters const *Right); + static double CouplerDist(physics::Vehicle const *Left, physics::Vehicle const *Right); static double Distance(const TLocation &Loc1, const TLocation &Loc2, const TDimension &Dim1, const TDimension &Dim2); - bool Attach(int ConnectNo, int ConnectToNr, TMoverParameters *ConnectTo, CouplingSet CouplingType, bool Enforce = false, bool Audible = true); + bool Attach(int ConnectNo, int ConnectToNr, physics::Vehicle *ConnectTo, CouplingSet CouplingType, bool Enforce = false, bool Audible = true); int DettachStatus(int ConnectNo); int DettachStatus(VehicleEnd const ConnectNo) { @@ -1611,7 +1618,7 @@ class TMoverParameters } bool Dettach(int ConnectNo); // the same by the ends, where they are known to be ends - bool Attach(VehicleEnd const ConnectNo, VehicleEnd const ConnectToNr, TMoverParameters *ConnectTo, CouplingSet CouplingType, bool Enforce = false, bool Audible = true) + bool Attach(VehicleEnd const ConnectNo, VehicleEnd const ConnectToNr, physics::Vehicle *ConnectTo, CouplingSet CouplingType, bool Enforce = false, bool Audible = true) { return Attach(NumberOf(ConnectNo), NumberOf(ConnectToNr), ConnectTo, CouplingType, Enforce, Audible); } @@ -1873,7 +1880,7 @@ class TMoverParameters double GetScndDVc(double dt); int ScndPipeCouplersSubsteps(double dt) const; // the air exchange through the brake and main reservoir hoses, after the vehicles stepped - static void UpdatePipeCouplers(std::vector const &Vehicles, double dt); + static void UpdatePipeCouplers(std::vector const &Vehicles, double dt); /*funkcje obliczajace sily*/ void ComputeConstans(void); // ABu: wczesniejsze wyznaczenie stalych dla liczenia sil @@ -1936,30 +1943,30 @@ class TMoverParameters double coupler_force_physical(VehicleEnd const End, double const dt); // with the physical model: whether the vehicles at the end hit the stop of their springs at the last update and // still close in on it, so that they collide; a hit hard enough breaks the coupling or crushes the buffers - bool coupler_stop_hit(VehicleEnd const End, TMoverParameters &Other, VehicleEnd const OtherEnd); + bool coupler_stop_hit(VehicleEnd const End, physics::Vehicle &Other, VehicleEnd const OtherEnd); // couples the automatic couplers of the end and of the other vehicle pressed against each other, unless the hit // is too fast for them to catch - void automatic_coupling(VehicleEnd const End, TMoverParameters &Other, VehicleEnd const OtherEnd); + void automatic_coupling(VehicleEnd const End, physics::Vehicle &Other, VehicleEnd const OtherEnd); void CollisionDetect(VehicleEnd const End, double const dt); // closing speed of a collision [km/h] above which the vehicles involved may derail, adjusted for their mass ratio static constexpr double SafeCollisionVelocity{15.0}; // closing speed [km/h] of the End of this vehicle and the OtherEnd of the other vehicle it touches, along the coupler // axis: the sum of the speeds in a head-on collision, the difference in a rear-end one, negative when they part - double CollisionVelocity(VehicleEnd const End, TMoverParameters const &Other, VehicleEnd const OtherEnd) const; + double CollisionVelocity(VehicleEnd const End, physics::Vehicle const &Other, VehicleEnd const OtherEnd) const; // velocity [m/s] of this vehicle relative to the other vehicle it touches with its End and the OtherEnd of the // other one, along this vehicle's axis - double CouplerVelocityDifference(VehicleEnd const End, TMoverParameters const &Other, VehicleEnd const OtherEnd) const; + double CouplerVelocityDifference(VehicleEnd const End, physics::Vehicle const &Other, VehicleEnd const OtherEnd) const; // whether the automatic couplers at the End of this vehicle and the OtherEnd of the other one can catch each other on // contact, rather than the vehicles colliding (with crash damage enabled, only at a closing speed which doesn't derail them) - bool AutomaticCouplingSafe(VehicleEnd const End, TMoverParameters const &Other, VehicleEnd const OtherEnd) const; + bool AutomaticCouplingSafe(VehicleEnd const End, physics::Vehicle const &Other, VehicleEnd const OtherEnd) const; // whether the control coupling (multiple-unit control) can join the End of this vehicle and the OtherEnd of the other // one: not between an electric and a diesel traction vehicle, unless both couplers name the same control system // (ControlType). Vehicles without own traction (cars, control trailers) take any. Global.control_coupling_engine_check // off allows it always (eu07/maszyna#520) - bool ControlCouplingAllowed(VehicleEnd const End, TMoverParameters const &Other, VehicleEnd const OtherEnd) const; + bool ControlCouplingAllowed(VehicleEnd const End, physics::Vehicle const &Other, VehicleEnd const OtherEnd) const; // the CouplingType to join the End of this vehicle and the OtherEnd of the other one with, without the control coupling // when ControlCouplingAllowed() rules it out. a permanent coupling (of the vehicles of one unit) is kept whole - CouplingSet CompatibleCoupling(VehicleEnd const End, TMoverParameters const &Other, VehicleEnd const OtherEnd, CouplingSet const CouplingType) const; + CouplingSet CompatibleCoupling(VehicleEnd const End, physics::Vehicle const &Other, VehicleEnd const OtherEnd, CouplingSet const CouplingType) const; // the horns of the Signal (WarningSignal bits) which have the air or the voltage they need to sound int SoundingHorns(int const Signal) const; // whether the signal lamps of the main circuit (line contactors, ground relay, motor overload relays) can light: @@ -2308,6 +2315,8 @@ class TMoverParameters void BrakeSubsystemDecode(); // Q 20160719 }; +} // namespace physics + // double Distance(TLocation Loc1, TLocation Loc2, TDimension Dim1, TDimension Dim2); namespace simulation diff --git a/rendering/common/locallights.cpp b/rendering/common/locallights.cpp index 5f04155cf..524dbb6e4 100644 --- a/rendering/common/locallights.cpp +++ b/rendering/common/locallights.cpp @@ -29,7 +29,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Train.h" #include "simulation/simulation.h" #include "rendering/geometrybank.h" -#include "physics/mover.h" +#include "physics/vehicle.h" namespace { @@ -374,7 +374,7 @@ void gfx::local_lights::gather_vehicle(TDynamicObject *Vehicle, glm::dvec3 const { auto const &name{section.compartment->pName}; cabsection &= (name.size() >= 4) && name.starts_with("cab"); - auto const level{section.light_level * (cabsection ? 1.f : Vehicle->MoverParameters->CompartmentLights.intensity)}; + auto const level{section.light_level * (cabsection ? 1.f : Vehicle->physics->CompartmentLights.intensity)}; if ((level <= 0.f) || (Global.fLuminance > section.compartment->fLight) || (section.compartment->iVisible == 0)) { continue; diff --git a/rendering/common/localshadows.cpp b/rendering/common/localshadows.cpp index 49ce195ce..7e0d780c1 100644 --- a/rendering/common/localshadows.cpp +++ b/rendering/common/localshadows.cpp @@ -18,7 +18,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/DynObj.h" #include "vehicle/Train.h" #include "rendering/common/skyocclusion.h" -#include "physics/mover.h" +#include "physics/vehicle.h" namespace gfx { @@ -584,7 +584,7 @@ std::vector const &local_shadows::pick_headli if (std::max(beam.r, std::max(beam.g, beam.b)) <= 0.f) continue; // the part of the beam the shadows are cast in: from the end of the vehicle to the reach ahead of it - auto const &dimensions{light.owner->MoverParameters->Dim}; + auto const &dimensions{light.owner->physics->Dim}; auto const radius{range * 0.5 + std::max(dimensions.W, dimensions.H) + 2.0}; auto const centre{light.position + glm::dvec3{light.direction} * (range * 0.5 + 2.0)}; if (glm::length(centre - camera) - radius > range) diff --git a/rendering/common/scenewalk.cpp b/rendering/common/scenewalk.cpp index cb1b5621f..de01564f4 100644 --- a/rendering/common/scenewalk.cpp +++ b/rendering/common/scenewalk.cpp @@ -30,7 +30,7 @@ http://mozilla.org/MPL/2.0/. #include "model/AnimModel.h" #include "model/Model3d.h" #include "rendering/common/skyocclusion.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include #include #include @@ -295,8 +295,8 @@ bool scene_walk::Render_coupler_adapter( TDynamicObject *Dynamic, float const Sq auto const position { glm::dvec3 { 0.f, - Dynamic->MoverParameters->Couplers[ End ].adapter_height, - ( Dynamic->MoverParameters->Couplers[ End ].adapter_length + Dynamic->MoverParameters->Dim.L * 0.5 ) * ( End == VehicleEnd::front ? 1 : -1 ) } }; + Dynamic->physics->Couplers[ End ].adapter_height, + ( Dynamic->physics->Couplers[ End ].adapter_length + Dynamic->physics->Dim.L * 0.5 ) * ( End == VehicleEnd::front ? 1 : -1 ) } }; auto const angle { glm::vec3{ 0, diff --git a/rendering/common/screenreflections.cpp b/rendering/common/screenreflections.cpp index 0976305b5..e519b21ff 100644 --- a/rendering/common/screenreflections.cpp +++ b/rendering/common/screenreflections.cpp @@ -13,7 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/DynObj.h" #include "gl/ubo.h" #include "utilities/Globals.h" -#include "physics/mover.h" +#include "physics/vehicle.h" namespace { @@ -60,7 +60,7 @@ void gfx::screen_reflections::begin_frame(glm::mat4 const &Projection, glm::dmat { m_reprojectioncab = glm::mat4{m_history.projection * glm::dmat4{m_history.view} * m_history.cab * glm::inverse(m_current.cab) * toworld}; // the vehicle stands on the origin of its model, along z, up to its height - auto const &dimensions{Cab->MoverParameters->Dim}; + auto const &dimensions{Cab->physics->Dim}; glm::dvec3 const lower{-0.5 * dimensions.W - CAB_BOX_MARGIN, -CAB_BOX_MARGIN, -0.5 * dimensions.L - CAB_BOX_MARGIN}; glm::dvec3 const upper{0.5 * dimensions.W + CAB_BOX_MARGIN, dimensions.H + CAB_BOX_MARGIN, 0.5 * dimensions.L + CAB_BOX_MARGIN}; auto const centre{0.5 * (lower + upper)}; diff --git a/rendering/common/windscreenwater.cpp b/rendering/common/windscreenwater.cpp index 78d3a2edc..619b6bf33 100644 --- a/rendering/common/windscreenwater.cpp +++ b/rendering/common/windscreenwater.cpp @@ -19,7 +19,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "vehicle/DynObj.h" #include "vehicle/Train.h" -#include "physics/mover.h" +#include "physics/vehicle.h" namespace gfx { @@ -340,7 +340,7 @@ void windscreen_water::update(double const Seconds) // the blades of the wipers of the vehicle, as the glasses read them (the channels of the mask follow the wipers of the cab // the vehicle is driven from) glm::vec4 blades{-1.f}; - if (auto const cabactive{vehicle->MoverParameters->CabActive}; cabactive != 0) + if (auto const cabactive{vehicle->physics->CabActive}; cabactive != 0) { auto const count{static_cast(vehicle->dWiperPos.size())}; for (int i = 0; i < 4; ++i) @@ -356,7 +356,7 @@ void windscreen_water::update(double const Seconds) auto const toworld{glm::dmat3{vehicle->mMatrix}}; auto const tomodel{glm::inverse(toworld)}; auto const up{glm::normalize(glm::vec3{tomodel * glm::dvec3{0.0, 1.0, 0.0}})}; - auto const air{glm::vec3{tomodel * (glm::dvec3{simulation::Environment.wind()} * WIND_SHARE - vehicle->VectorFront() * vehicle->MoverParameters->V)}}; + auto const air{glm::vec3{tomodel * (glm::dvec3{simulation::Environment.wind()} * WIND_SHARE - vehicle->VectorFront() * vehicle->physics->V)}}; auto const heavy{std::clamp(Global.Overcast - 1.f, 0.f, 1.f)}; auto const snow{Global.Weather == "snow:"}; auto const fall{snow ? SNOW_FALL : RAIN_FALL}; diff --git a/rendering/lightarray.cpp b/rendering/lightarray.cpp index eef1c6a2f..8e9b561ff 100644 --- a/rendering/lightarray.cpp +++ b/rendering/lightarray.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "rendering/lightarray.h" #include "vehicle/DynObj.h" -#include "physics/mover.h" +#include "physics/vehicle.h" void light_array::insert( TDynamicObject const *Owner ) { @@ -52,11 +52,11 @@ light_array::update() { light.direction.z = -light.direction.z; } // determine intensity of this light set - if( ( true == light.owner->MoverParameters->Power24vIsAvailable ) - || ( true == light.owner->MoverParameters->Power110vIsAvailable ) ) { + if( ( true == light.owner->physics->Power24vIsAvailable ) + || ( true == light.owner->physics->Power110vIsAvailable ) ) { // with power on, the intensity depends on the state of activated switches // first we cross-check the list of enabled lights with the lights installed in the vehicle... - auto const lights { light.owner->MoverParameters->iLights[ light.index ] & light.owner->LightList( static_cast( light.index ) ) }; + auto const lights { light.owner->physics->iLights[ light.index ] & light.owner->LightList( static_cast( light.index ) ) }; // ...then check their individual state light.count = 0 + ( ( lights & light::headlight_left ) ? 1 : 0 ) @@ -71,13 +71,13 @@ light_array::update() { light.intensity = std::max(0.0f, std::log((float)light.count + 1.0f)); if (light.owner->DimHeadlights && !light.owner->HighBeamLights && isEnabled) // tylko przyciemnione - light.intensity *= static_cast(light.owner->MoverParameters->dimMultiplier); + light.intensity *= static_cast(light.owner->physics->dimMultiplier); else if (!light.owner->DimHeadlights && !light.owner->HighBeamLights && isEnabled) // normalne - light.intensity *= static_cast(light.owner->MoverParameters->normMultiplier); + light.intensity *= static_cast(light.owner->physics->normMultiplier); else if (light.owner->DimHeadlights && light.owner->HighBeamLights && isEnabled) // przyciemnione dlugie - light.intensity *= static_cast(light.owner->MoverParameters->highDimMultiplier); + light.intensity *= static_cast(light.owner->physics->highDimMultiplier); else if (!light.owner->DimHeadlights && light.owner->HighBeamLights && isEnabled) // dlugie zwykle - light.intensity *= static_cast(light.owner->MoverParameters->highMultiplier); + light.intensity *= static_cast(light.owner->physics->highMultiplier); else if (!isEnabled) { light.intensity = 0.0f; @@ -90,19 +90,19 @@ light_array::update() { ( ( lights & light::headlight_right | light::highbeamlight_right) ? 1.f : 0.f ) }; light.color = { - static_cast(light.owner->MoverParameters->refR) / 255.0f, - static_cast(light.owner->MoverParameters->refG) / 255.0f, - static_cast(light.owner->MoverParameters->refB) / 255.0f + static_cast(light.owner->physics->refR) / 255.0f, + static_cast(light.owner->physics->refG) / 255.0f, + static_cast(light.owner->physics->refB) / 255.0f }; if (light.owner->DimHeadlights && !light.owner->HighBeamLights) // tylko przyciemnione - light.state *= light.owner->MoverParameters->dimMultiplier; + light.state *= light.owner->physics->dimMultiplier; else if (!light.owner->DimHeadlights && !light.owner->HighBeamLights) // normalne - light.state *= light.owner->MoverParameters->normMultiplier; + light.state *= light.owner->physics->normMultiplier; else if (light.owner->DimHeadlights && light.owner->HighBeamLights) // przyciemnione dlugie - light.state *= light.owner->MoverParameters->highDimMultiplier; + light.state *= light.owner->physics->highDimMultiplier; else if (!light.owner->DimHeadlights && light.owner->HighBeamLights) // dlugie zwykle - light.state *= light.owner->MoverParameters->highMultiplier; + light.state *= light.owner->physics->highMultiplier; else if (!isEnabled) { light.state = glm::vec3{0.f}; diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index f2e611859..e1b65aa44 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -29,7 +29,7 @@ http://mozilla.org/MPL/2.0/. #include "rendering/opengl46/opengl46geometrybank.h" #include "rendering/screenshot.h" #include "rendering/editoroverlay.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/DynObj.h" #include @@ -1682,16 +1682,16 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) // vehicle (V is along the front of the vehicle) glm::dvec3 air{glm::dvec3{simulation::Environment.wind()} * 0.5}; if (TDynamicObject const *owner = Global.pCamera.m_owner) - air -= owner->VectorFront() * owner->MoverParameters->V; + air -= owner->VectorFront() * owner->physics->V; scene_ubs.rain_wind = glm::vec4{glm::vec3{air}, 0.f}; } - if (TDynamicObject const *owner = Global.pCamera.m_owner; owner && !!owner->MoverParameters->CabActive) + if (TDynamicObject const *owner = Global.pCamera.m_owner; owner && !!owner->physics->CabActive) { for (int i = 0; i < 4; ++i) { if (i < owner->dWiperPos.size()) { - int index = owner->MoverParameters->CabActive > 0 ? i : static_cast(owner->dWiperPos.size() - 1) - i; + int index = owner->physics->CabActive > 0 ? i : static_cast(owner->dWiperPos.size() - 1) - i; scene_ubs.wiper_pos[i] = owner->dWiperPos[index]; if (owner->dWiperPos[index] > 0. && owner->wiperDirection[index]) { @@ -6761,7 +6761,7 @@ void opengl46_renderer::Render_lamp_shadow(std::size_t const Slot, bool const Ve void opengl46_renderer::Headlight_Projector(light_array::light_record const &Light, glm::dvec3 &Position, glm::mat3 &Rotation, glm::mat4 &Projection, float &Near, float &Fieldofview) { - auto const &ownerdimensions{Light.owner->MoverParameters->Dim}; + auto const &ownerdimensions{Light.owner->physics->Dim}; auto const up{static_cast(Light.owner->VectorUp())}; auto const size{static_cast(std::max(ownerdimensions.W, ownerdimensions.H) * 1.0)}; // ensure square ratio auto const cone{5.f}; diff --git a/rendering/particles.cpp b/rendering/particles.cpp index 391dd1903..c0245be12 100644 --- a/rendering/particles.cpp +++ b/rendering/particles.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationenvironment.h" #include "utilities/Logs.h" #include "vehicle/smoke.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/DynObj.h" @@ -176,7 +176,7 @@ smoke_source::accumulate_spawns( double const Timedelta, bool const Onlydespawn if( m_ownertype == owner_type::vehicle ) { - auto const &mover { *m_owner.vehicle->MoverParameters }; + auto const &physics { *m_owner.vehicle->physics }; // NOTE: the smoke keeps the colour of its template, cold engine or not. a grey for a cold engine was once meant // here, but the line compared instead of assigning; made an assignment, it set 128 on the 0-1 scale of the // emitter colour, so the smoke turned pure white, glowing at night, and never changed back @@ -185,7 +185,7 @@ smoke_source::accumulate_spawns( double const Timedelta, bool const Onlydespawn m_spawncount = ( ( true == spawning ) ? smoke::vehicle_spawn_count( - mover, m_owner.vehicle->bEnabled, + physics, m_owner.vehicle->bEnabled, { m_spawncount, m_spawnrate, Global.SmokeFidelity, static_cast( m_max_particles ) }, Timedelta ) : 0.f ); @@ -346,19 +346,19 @@ smoke_source::launch_scales( float &Velocity, float &Opacity ) const { Opacity = 1.f; if( m_ownertype != owner_type::vehicle ) { return; } - Opacity = static_cast(m_owner.vehicle->MoverParameters->diesel.fill); - if (m_owner.vehicle->MoverParameters->EngineType == TEngineType::DieselElectric) + Opacity = static_cast(m_owner.vehicle->physics->diesel.fill); + if (m_owner.vehicle->physics->EngineType == TEngineType::DieselElectric) { - if (m_owner.vehicle->MoverParameters->diesel.spinningUp == true) + if (m_owner.vehicle->physics->diesel.spinningUp == true) { - Velocity = static_cast(0.38*(((m_owner.vehicle->MoverParameters->enrot)/2)*0.5)); // / m_owner.vehicle->MoverParameters->diesel.fill *0.01)) ; + Velocity = static_cast(0.38*(((m_owner.vehicle->physics->enrot)/2)*0.5)); // / m_owner.vehicle->physics->diesel.fill *0.01)) ; } else { - Velocity = static_cast((((m_owner.vehicle->MoverParameters->enrot)/60)*0.6) * (m_owner.vehicle->MoverParameters->EnginePower *0.03)); // / m_owner.vehicle->MoverParameters->diesel.fill *0.01)) ; - //Particle.velocity *= m_owner.vehicle->GetVelocity(); // / m_owner.vehicle->MoverParameters->diesel.fill *0.01)) ; + Velocity = static_cast((((m_owner.vehicle->physics->enrot)/60)*0.6) * (m_owner.vehicle->physics->EnginePower *0.03)); // / m_owner.vehicle->physics->diesel.fill *0.01)) ; + //Particle.velocity *= m_owner.vehicle->GetVelocity(); // / m_owner.vehicle->physics->diesel.fill *0.01)) ; } } diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index 12f3cf9b0..6963dbd85 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -32,7 +32,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "utilities/utilities.h" #include "utilities/color.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include @@ -1569,16 +1569,16 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) // vehicle (V is along the front of the vehicle) glm::dvec3 air{glm::dvec3{simulation::Environment.wind()} * 0.5}; if (TDynamicObject const *owner = Global.pCamera.m_owner) - air -= owner->VectorFront() * owner->MoverParameters->V; + air -= owner->VectorFront() * owner->physics->V; scene_ubs.rain_wind = glm::vec4{glm::vec3{air}, 0.f}; } - if (TDynamicObject const *owner = Global.pCamera.m_owner; owner && !!owner->MoverParameters->CabActive) + if (TDynamicObject const *owner = Global.pCamera.m_owner; owner && !!owner->physics->CabActive) { for (int i = 0; i < 4; ++i) { if (i < owner->dWiperPos.size()) { - int index = owner->MoverParameters->CabActive > 0 ? i : static_cast(owner->dWiperPos.size() - 1) - i; + int index = owner->physics->CabActive > 0 ? i : static_cast(owner->dWiperPos.size() - 1) - i; scene_ubs.wiper_pos[i] = owner->dWiperPos[index]; if (owner->dWiperPos[index] > 0. && owner->wiperDirection[index]) { @@ -4159,7 +4159,7 @@ void vulkan14_renderer::write_local_light(gl::light_element &Light, gfx::local_l void vulkan14_renderer::headlight_projector(light_array::light_record const &Light, glm::dvec3 &Position, glm::mat3 &Rotation, glm::mat4 &Projection, float &Near, float &Fieldofview) { - auto const &ownerdimensions{Light.owner->MoverParameters->Dim}; + auto const &ownerdimensions{Light.owner->physics->Dim}; auto const up{static_cast(Light.owner->VectorUp())}; auto const size{static_cast(std::max(ownerdimensions.W, ownerdimensions.H) * 1.0)}; auto const cone{5.f}; diff --git a/scene/scene.cpp b/scene/scene.cpp index 3f67b4d31..03b10d8f1 100644 --- a/scene/scene.cpp +++ b/scene/scene.cpp @@ -24,7 +24,7 @@ http://mozilla.org/MPL/2.0/. #include "rendering/renderer.h" #include "widgets/map_objects.h" #include "vehicle/aiwire.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/DynObj.h" #include @@ -131,12 +131,12 @@ basic_cell::update_traction( TDynamicObject *Vehicle, int const Pantographindex // i do tego jeszcze wejdzie pod ślizg if( fHorizontal <= 0.0 ) { // 0.635 dla AKP-1 AKP-4E - Vehicle->MoverParameters->DamageFlag.Set(VehicleDamage::pantograph); + Vehicle->physics->DamageFlag.Set(VehicleDamage::pantograph); pantograph->PantWys = -1.0; // ujemna liczba oznacza połamanie pantograph->hvPowerWire = nullptr; // bo inaczej się zasila w nieskończoność z połamanego - if( Vehicle->MoverParameters->EnginePowerSource.CollectorParameters.CollectorsNo > 0 ) { + if( Vehicle->physics->EnginePowerSource.CollectorParameters.CollectorsNo > 0 ) { // liczba pantografów teraz będzie mniejsza - --Vehicle->MoverParameters->EnginePowerSource.CollectorParameters.CollectorsNo; + --Vehicle->physics->EnginePowerSource.CollectorParameters.CollectorsNo; } ErrorLog( "Bad traction: " + Vehicle->name() + " broke pantograph at " + to_string( pantographposition ), logtype::traction ); diff --git a/scripting/lua.cpp b/scripting/lua.cpp index 27224605f..93e542742 100644 --- a/scripting/lua.cpp +++ b/scripting/lua.cpp @@ -7,7 +7,7 @@ #include "simulation/simulation.h" #include "scripting/luasandbox.h" #include "utilities/utilities.h" -#include "physics/mover.h" +#include "physics/vehicle.h" lua::lua() { @@ -351,7 +351,7 @@ int lua::scriptapi_dynobj_putvalues(lua_State *L) if (dyn->Mechanik) dyn->Mechanik->PutCommand(str, num1, num2, loc); else - dyn->MoverParameters->PutCommand(str, num1, num2, loc); + dyn->physics->PutCommand(str, num1, num2, loc); return 0; } diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index be6fc0000..9f8a44378 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -26,7 +26,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/physicslog.h" #include "utilities/utilities.h" #include "world/stationnames.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include #include @@ -70,7 +70,7 @@ blackbox::driver driver_of(TDynamicObject const &Vehicle) { } // the switches of the user's train: those of its own vehicle, and those of the one with the motors it drives -std::uint32_t devices_of(TMoverParameters const &Occupied, TMoverParameters const &Controlling) { +std::uint32_t devices_of(physics::Vehicle const &Occupied, physics::Vehicle const &Controlling) { namespace device = blackbox::cab_devices; auto const on{[](bool const State, std::uint32_t const Bit) { return State ? Bit : 0u; }}; return on(Occupied.Battery || Controlling.Battery, device::battery) | on(Controlling.Mains, device::main_breaker) | @@ -90,8 +90,8 @@ std::uint32_t devices_of(TMoverParameters const &Occupied, TMoverParameters cons on(Controlling.diesel.heat.engine_is_hot, device::engine_hot) | on(Controlling.SpeedCtrl && Controlling.SpeedCtrlUnit.IsActive, device::speed_control); } -std::uint8_t engine_of(TMoverParameters const &Mover) { - switch (Mover.EngineType) { +std::uint8_t engine_of(physics::Vehicle const &Physics) { + switch (Physics.EngineType) { case TEngineType::ElectricSeriesMotor: return blackbox::engines::electric; case TEngineType::ElectricInductionMotor: @@ -109,10 +109,10 @@ std::uint8_t engine_of(TMoverParameters const &Mover) { // the lights at an end of the train: of its head or of its tail, at the end of that vehicle turned away from the rest std::uint16_t outward_lights(TDynamicObject const *Vehicle, bool const Head) { - if (Vehicle == nullptr || Vehicle->MoverParameters == nullptr) + if (Vehicle == nullptr || Vehicle->physics == nullptr) return 0; auto const along{Vehicle->iDirection > 0}; - return static_cast(Vehicle->MoverParameters->iLights[Head == along ? VehicleEnd::front : VehicleEnd::rear]); + return static_cast(Vehicle->physics->iLights[Head == along ? VehicleEnd::front : VehicleEnd::rear]); } // the lamps the vehicle has at that end: the driver checks a pattern against those of it there are @@ -206,9 +206,9 @@ bool coupled(TDynamicObject const *From, TDynamicObject const *To) { auto side{start}; // going on away from the first vehicle: through the coupler opposite the one each was reached by for (int step = 0; step < 1000 && vehicle != nullptr; ++step) { - auto const *mover{vehicle->MoverParameters}; - auto const &neighbour{mover->Neighbours[side]}; - if (mover->Couplers[side].CouplingFlag.Empty() || neighbour.vehicle == nullptr) + auto const *physics{vehicle->physics}; + auto const &neighbour{physics->Neighbours[side]}; + if (physics->Couplers[side].CouplingFlag.Empty() || neighbour.vehicle == nullptr) break; if (neighbour.vehicle == To) return true; @@ -225,7 +225,7 @@ blackbox::vehicle_state state_of(TDynamicObject const &Vehicle, std::uint32_t co state.position = glm::vec3{Vehicle.GetPosition()}; auto const front{Vehicle.VectorFront()}; state.heading = static_cast(std::atan2(front.x, front.z)); - state.speed_kmh = static_cast(Vehicle.MoverParameters->V * 3.6); + state.speed_kmh = static_cast(Vehicle.physics->V * 3.6); state.driving = driver_of(Vehicle); return state; } @@ -415,7 +415,7 @@ void blackbox_recorder::write_cab() { if (train == nullptr || train->Dynamic() == nullptr) return; auto const *vehicle{train->Dynamic()}; - auto const *occupied{vehicle->MoverParameters}; + auto const *occupied{vehicle->physics}; // the one which drives the consist, as the driving aid tells it auto const *owner{vehicle->ctOwner != nullptr ? vehicle->ctOwner : vehicle->Mechanik}; auto const *controlling{owner != nullptr ? owner->Controlling() : occupied}; @@ -431,7 +431,7 @@ void blackbox_recorder::write_cab() { // the vehicle itself, if none in the unit is powered auto const *powered{train->Dynamic()->FindPowered()}; auto const facing{powered->DirectionGet() * vehicle->DirectionGet()}; - sample.wheel_speed_kmh = static_cast(facing * M_PI * powered->MoverParameters->WheelDiameter * powered->MoverParameters->nrot * 3.6); + sample.wheel_speed_kmh = static_cast(facing * M_PI * powered->physics->WheelDiameter * powered->physics->nrot * 3.6); sample.acceleration = static_cast(controlling->AccS); sample.lateral_acceleration = static_cast(occupied->AccN); if (owner != nullptr && owner->is_train()) { @@ -494,8 +494,8 @@ void blackbox_recorder::write_cab() { // the brakes of the whole train: the highest of its cylinders, from the head to the tail auto brakes{occupied->BrakePress}; for (auto const *each{owner != nullptr ? owner->Vehicle(VehicleEnd::front) : nullptr}; each != nullptr; each = each->Next()) - if (each->MoverParameters != nullptr) - brakes = std::max(brakes, each->MoverParameters->BrakePress); + if (each->physics != nullptr) + brakes = std::max(brakes, each->physics->BrakePress); sample.consist_brake_cylinder = static_cast(brakes); m_writer->cab(sample); } @@ -528,7 +528,7 @@ void blackbox_recorder::look_around(bool const Keyframe) { auto *train{simulation::Train}; auto const uservehicle{train != nullptr && train->Dynamic() != nullptr ? vehicle_id(train->Dynamic()) : blackbox::no_vehicle}; auto const userincab{uservehicle != blackbox::no_vehicle && false == FreeFlyModeFlag}; - auto const usercab{uservehicle != blackbox::no_vehicle ? static_cast(train->Dynamic()->MoverParameters->CabOccupied) : std::int8_t{0}}; + auto const usercab{uservehicle != blackbox::no_vehicle ? static_cast(train->Dynamic()->physics->CabOccupied) : std::int8_t{0}}; if (false == m_userknown || uservehicle != m_uservehicle || userincab != m_userincab || usercab != m_usercab) { m_writer->user_vehicle(m_time, uservehicle, userincab, usercab); m_uservehicle = uservehicle; @@ -582,7 +582,7 @@ void blackbox_recorder::look_at_derailments() { for (auto *vehicle : simulation::Vehicles.sequence()) { if (false == vehicle->bEnabled) continue; - auto const &motion{vehicle->MoverParameters->OffTrack}; + auto const &motion{vehicle->physics->OffTrack}; auto const id{vehicle_id(vehicle)}; auto &entry{m_vehicles[vehicle]}; if (false == motion.active()) { @@ -598,7 +598,7 @@ void blackbox_recorder::look_at_derailments() { state.cause = cause_of(motion.reason()); state.position = vehicle->GetPosition(); state.heading = static_cast(std::atan2(vehicle->VectorFront().x, vehicle->VectorFront().z)); - state.speed_kmh = static_cast(vehicle->MoverParameters->V * 3.6); + state.speed_kmh = static_cast(vehicle->physics->V * 3.6); state.offset = static_cast(vehicle->off_track_offset()); state.roll = static_cast(motion.roll()); state.travelled = static_cast(motion.travelled()); @@ -617,12 +617,12 @@ void blackbox_recorder::look_at_couplers() { if (false == vehicle->bEnabled) continue; auto &entry{m_vehicles[vehicle]}; - auto const *mover{vehicle->MoverParameters}; + auto const *physics{vehicle->physics}; for (int side = 0; side < 2; ++side) { - auto const flags{mover->Couplers[side].CouplingFlag}; + auto const flags{physics->Couplers[side].CouplingFlag}; // a neighbour not coupled is only seen on the same track - auto const *other{false == flags.Empty() ? mover->Neighbours[side].vehicle : nullptr}; - coupler_entry const now{other, other != nullptr ? mover->Neighbours[side].vehicle_end : 0, other != nullptr ? flags.Bits() : 0}; + auto const *other{false == flags.Empty() ? physics->Neighbours[side].vehicle : nullptr}; + coupler_entry const now{other, other != nullptr ? physics->Neighbours[side].vehicle_end : 0, other != nullptr ? flags.Bits() : 0}; auto &last{entry.couplers[side]}; auto const changed{now.other != last.other || now.other_side != last.other_side || now.flags != last.flags}; auto const before{last}; @@ -764,11 +764,11 @@ std::uint32_t blackbox_recorder::vehicle_id(TDynamicObject const *Vehicle) { auto &entry{m_vehicles[Vehicle]}; entry.id = m_nextvehicle++; - auto const *mover{Vehicle->MoverParameters}; + auto const *physics{Vehicle->physics}; auto const *driver{Vehicle->Mechanik}; auto const train{driver != nullptr && driver->TrainName() != "none" ? driver->TrainName() : std::string{}}; - m_writer->vehicle({entry.id, text_of(Vehicle->name()), text_of(mover->TypeName), text_of(train), static_cast(mover->Dim.L), static_cast(mover->Dim.W), - static_cast(mover->CategoryFlag)}); + m_writer->vehicle({entry.id, text_of(Vehicle->name()), text_of(physics->TypeName), text_of(train), static_cast(physics->Dim.L), static_cast(physics->Dim.W), + static_cast(physics->CategoryFlag)}); return entry.id; } diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp index ab3ec3a56..82ae73792 100644 --- a/simulation/simulation.cpp +++ b/simulation/simulation.cpp @@ -37,7 +37,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "vehicle/Driver.h" #include "world/catenary_scene.h" -#include "physics/mover.h" +#include "physics/vehicle.h" namespace simulation { @@ -244,13 +244,13 @@ void state_manager::process_commands() { TDynamicObject *vehicle = found_vehicle; while (vehicle) { - vehicle->MoverParameters->Hamulec->Releaser(commanddata.action != GLFW_RELEASE ? 1 : 0); + vehicle->physics->Hamulec->Releaser(commanddata.action != GLFW_RELEASE ? 1 : 0); vehicle = vehicle->Next(); } vehicle = found_vehicle; while (vehicle) { - vehicle->MoverParameters->Hamulec->Releaser(commanddata.action != GLFW_RELEASE ? 1 : 0); + vehicle->physics->Hamulec->Releaser(commanddata.action != GLFW_RELEASE ? 1 : 0); vehicle = vehicle->Prev(); } } @@ -436,11 +436,11 @@ void state_manager::process_commands() { while (vehicle) { // no damage, back on the rails with the state of the derailment cleared - vehicle->MoverParameters->repair_damage(); - vehicle->MoverParameters->V = 0.000001; // HACK: force vehicle position re-calculation - vehicle->MoverParameters->DistCounter = 0.0; - vehicle->MoverParameters->OffsetTrackH = 0.0; - vehicle->MoverParameters->OffsetTrackV = 0.0; + vehicle->physics->repair_damage(); + vehicle->physics->V = 0.000001; // HACK: force vehicle position re-calculation + vehicle->physics->DistCounter = 0.0; + vehicle->physics->OffsetTrackH = 0.0; + vehicle->physics->OffsetTrackV = 0.0; // pantographs for( auto idx = 0; idx < vehicle->iAnimType[ ANIM_PANTS ]; ++idx ) { @@ -461,13 +461,13 @@ void state_manager::process_commands() { if (commanddata.command == user_command::repaircoupler) { if (auto *vehicle{simulation::Vehicles.find(commanddata.payload)}; vehicle != nullptr) { - vehicle->MoverParameters->repair_coupler(EndOf(static_cast(commanddata.param1)) == VehicleEnd::rear ? VehicleEnd::rear : VehicleEnd::front); + vehicle->physics->repair_coupler(EndOf(static_cast(commanddata.param1)) == VehicleEnd::rear ? VehicleEnd::rear : VehicleEnd::front); } } if (commanddata.command == user_command::fillcompressor) { TDynamicObject *vehicle = simulation::Vehicles.find(commanddata.payload); - vehicle->MoverParameters->CompressedVolume = 8.0f * vehicle->MoverParameters->VeselVolume; + vehicle->physics->CompressedVolume = 8.0f * vehicle->physics->VeselVolume; } if (commanddata.command == user_command::dynamicmove) { @@ -497,7 +497,7 @@ void state_manager::process_commands() { double offset = 0.0; while (vehicle) { - offset += vehicle->MoverParameters->Dim.L; + offset += vehicle->physics->Dim.L; vehicle->place_on_track(track, offset, false); vehicle = vehicle->Prev(); } @@ -510,7 +510,7 @@ void state_manager::process_commands() { if (commanddata.command == user_command::pullalarmchain) { TDynamicObject *vehicle = simulation::Vehicles.find(commanddata.payload); if (vehicle) - vehicle->MoverParameters->AlarmChainSwitch(true); + vehicle->physics->AlarmChainSwitch(true); } if (commanddata.command == user_command::sendaicommand) { diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index a12113496..848e1d655 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -37,7 +37,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/utilities.h" #include "editor/editorTerrainStreamer.hpp" -#include "physics/mover.h" +#include "physics/vehicle.h" #include @@ -47,7 +47,7 @@ namespace { double vehicle_length( std::string const &Folder, std::string const &Type ) { - TMoverParameters probe( 0.0, Type, Type, 0 ); + physics::Vehicle probe( 0.0, Type, Type, 0 ); return probe.LoadFIZ( paths::dynamic + Folder + "/" ) ? probe.Dim.L : 0.0; } @@ -579,7 +579,7 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch ErrorLog( "Bad scenario: duplicate vehicle name \"" + vehicle->name() + "\" defined in file \"" + Input.Name() + "\" (line " + std::to_string( inputline ) + ")" ); } - if( vehicle->MoverParameters->CategoryFlag == 1 // trains only + if( vehicle->physics->CategoryFlag == 1 // trains only && ( (vehicle->LightList(VehicleEnd::front) & (light::headlight_left | light::headlight_right | light::headlight_upper)) != 0 || (vehicle->LightList(VehicleEnd::rear) & (light::headlight_left | light::headlight_right | light::headlight_upper)) != 0 ) ) { simulation::Lights.insert( vehicle ); @@ -1692,7 +1692,7 @@ state_serializer::deserialize_dynamic( cParser &Input, scene::scratch_data &Scra } // automatically establish permanent connections for couplers which specify them in their definitions if( coupling != 0 - && vehicle->MoverParameters->Couplers[(offset == -1.0 ? VehicleEnd::front : VehicleEnd::rear)].AllowedFlag & Coupling::permanent ) { + && vehicle->physics->Couplers[(offset == -1.0 ? VehicleEnd::front : VehicleEnd::rear)].AllowedFlag & Coupling::permanent ) { coupling = ( CouplingSet::FromBits( coupling ) | Coupling::permanent ).Bits(); } if( true == Scratchpad.trainset.is_open ) { diff --git a/tests/unit/COVERAGE.md b/tests/unit/COVERAGE.md index 7299267c9..9757288a3 100644 --- a/tests/unit/COVERAGE.md +++ b/tests/unit/COVERAGE.md @@ -1,6 +1,6 @@ # Coverage of the simulation core by the unit tests -These tests characterise the physics of the vehicles (`physics/mover.cpp`, `brakes.cpp`, `oerlikonest.cpp`, `friction.cpp`). They exist to show that refactors of those files, such as splitting `TractionForce` or `RunCommand`, leave the behaviour as it was. This page lists: +These tests characterise the physics of the vehicles (`physics/physics.cpp`, `brakes.cpp`, `oerlikonest.cpp`, `friction.cpp`). They exist to show that refactors of those files, such as splitting `TractionForce` or `RunCommand`, leave the behaviour as it was. This page lists: - what the tests reach; - what nothing in the game ever runs; @@ -14,7 +14,7 @@ Coverage was measured on Windows with MSVC's SanitizerCoverage (`/fsanitize-cove | File | Blocks run, at the start | Now | |---|---|---| -| `mover.cpp` | 8.9% | 80.7% (3323 of 4118) | +| `physics.cpp` | 8.9% | 80.7% (3323 of 4118) | | `brakes.cpp` | 30% | 76.3% (649 of 851) | | `oerlikonest.cpp` | 58% | 87.4% (118 of 135) | | `friction.cpp` | 9% | 90.9% (10 of 11) | @@ -35,7 +35,7 @@ Nothing creates these objects or calls these functions anywhere in the game, whi - **Base implementations always overridden:** `TFricMat::GetFC` (every material, the default P10 too, has its own) and `TPrzekladnik::Update` (every relay has its own). - **Functions without callers:** - In `brakes.cpp`: `PF_old`, `TBrake::GetBCF`, `TDriverHandle::OvrldButton`, `TReservoir::pa` and `TBrakeCyl::pa`. - - In `mover.cpp`: `BrakeVP`, `PipeRatio`, `RealPipeRatio`, `IncBrakeLevel`, `DecBrakeLevel`, `IncBrakePress`, `DecBrakePress` and `MainCtrlActualPowerPos`. (`GetExternalCommand` was removed.) + - In `physics.cpp`: `BrakeVP`, `PipeRatio`, `RealPipeRatio`, `IncBrakeLevel`, `DecBrakeLevel`, `IncBrakePress`, `DecBrakePress` and `MainCtrlActualPowerPos`. (`GetExternalCommand` was removed.) - **Inverter failures** of the induction motor drives (`inverter::Failure_Drive`, `Failure_Const`, `Activate`): nothing ever sets them. The cab only shows them. The branches reading them in `TractionForce` can't be reached. ## Code only data no game vehicle has would run @@ -153,7 +153,7 @@ The tests are written for the first two columns, and for what the game doesn't c **Code nothing in the game runs** (checked against the whole source tree): -- **The PLC as a whole.** A vehicle has one (`TMoverParameters::m_plc`) and runs it in every step (`m_plc.update()`), but nothing calls `load()`, so its program is always empty; nothing calls `find_or_insert()`, `input()` or `output()` either, so no file of the game data can be a program for it. Of `ladderlogic.cpp` the game runs the 9 lines of an update without timers and without operations. The tests run the rest with programs made up for them. +- **The PLC as a whole.** A vehicle has one (`physics::Vehicle::m_plc`) and runs it in every step (`m_plc.update()`), but nothing calls `load()`, so its program is always empty; nothing calls `find_or_insert()`, `input()` or `output()` either, so no file of the game data can be a program for it. Of `ladderlogic.cpp` the game runs the 9 lines of an update without timers and without operations. The tests run the rest with programs made up for them. - **In `parser.cpp`:** `countTokens()` with its `count()`, and `addCommentStyle()`. No caller gives the separators as a null pointer either, which `updateCharClasses()` allows for. - **In `utilities.cpp`:** `generate_uuid_v4()`, `FuzzyLogicAI()` and `last_modified()`. In `utilities.h`: `BorlandTime()`. @@ -163,9 +163,9 @@ The tests are written for the first two columns, and for what the game doesn't c The tests record the behaviour as it is. The following points may deserve a look by someone who knows how the real vehicles behave. -- **`Random(10) - Random(10)` (`mover.cpp`, the noise of the control pipe pressure `CntrlPipePress`):** the order the two calls were evaluated in isn't specified. MSVC Release, MSVC Debug and GCC gave different traces, a control pipe pressure mirrored around 5 bar, which failed 32 tests on the Linux CI. Fixed: the draws are sequenced in the order of MSVC Release, which the golden traces were recorded with. +- **`Random(10) - Random(10)` (`physics.cpp`, the noise of the control pipe pressure `CntrlPipePress`):** the order the two calls were evaluated in isn't specified. MSVC Release, MSVC Debug and GCC gave different traces, a control pipe pressure mirrored around 5 bar, which failed 32 tests on the Linux CI. Fixed: the draws are sequenced in the order of MSVC Release, which the golden traces were recorded with. - **`TCommand::Location` isn't initialised** in a new vehicle. The game always sets it through `PutCommand()`, but a test calling `RunCommand()` directly got different results run to run. -- **`CompressorList` is `int[4][9]`** (`mover.h`), though its factors are fractions: 0.9 is read as 0. No game vehicle has the list yet. +- **`CompressorList` is `int[4][9]`** (`vehicle.h`), though its factors are fractions: 0.9 is read as 0. No game vehicle has the list yet. - **A train whose pipe leaks under 2.75 bar before its start-up can't be released:** - Where this happens: an FV4a handle and an LSt valve, for example 4 minutes standing with wagons, waiting for a hot engine. - The cause: the pipe gets cut off the main reservoir (`lock_old` in `UpdatePipePressure`). The AI presses its unlock button only for the lock set by `LPOn` and `LPOff` (`control_main_pipe`). diff --git a/tests/unit/README.md b/tests/unit/README.md index 80deab5e4..301717221 100644 --- a/tests/unit/README.md +++ b/tests/unit/README.md @@ -68,7 +68,7 @@ TEST_CASE("brakes: service braking stops a heavier wagon too") { physics iterations a frame. With a cab (`vehicle{definition, 0.0, "name", 1}`) it has a driver. - `consist` (`consist.h`) couples vehicles into a train and steps them together, coupler forces, air, control and power passing between them. The physics reaches a neighbour through its - `TDynamicObject`, for its `MoverParameters` only; the tests have a stand-in of it with just that. + `TDynamicObject`, for its `physics` only; the tests have a stand-in of it with just that. - `drive.h` has the driver's part, made of the AI's steps: `start_up()` (battery, pumps, pantographs, line breaker, converter, compressor), `drive()` (running, acknowledging the vigilance), `release_brakes()`, `drive_cycle()` (a whole run from start-up to a stop). diff --git a/tests/unit/consist.cpp b/tests/unit/consist.cpp index 2c17ca5b8..0d6dbb5bf 100644 --- a/tests/unit/consist.cpp +++ b/tests/unit/consist.cpp @@ -10,23 +10,23 @@ consist::~consist() = default; vehicle &consist::add(definition const &Definition, int Cab, CouplingSet const couplings, double Velocity, double Gap) { auto added{std::make_unique(Definition, Velocity, std::format("test{}", m_vehicles.size()), Cab)}; - auto &mover{added->mover()}; + auto &physics{added->physics()}; std::vector object(sizeof(TDynamicObject)); - reinterpret_cast(object.data())->MoverParameters = &mover; // NOSONAR see m_objects + reinterpret_cast(object.data())->physics = &physics; // NOSONAR see m_objects auto position{0.0}; if (false == m_vehicles.empty()) { - auto &last{m_vehicles.back()->mover()}; - position = m_positions.back() - 0.5 * (last.Dim.L + mover.Dim.L) - Gap; - mover.Loc = TLocation{position, 0.0, 0.0}; + auto &last{m_vehicles.back()->physics()}; + position = m_positions.back() - 0.5 * (last.Dim.L + physics.Dim.L) - Gap; + physics.Loc = TLocation{position, 0.0, 0.0}; if (false == couplings.Empty()) { - last.Attach(VehicleEnd::rear, VehicleEnd::front, &mover, couplings, true, false); - mover.Attach(VehicleEnd::front, VehicleEnd::rear, &last, couplings, true, false); + last.Attach(VehicleEnd::rear, VehicleEnd::front, &physics, couplings, true, false); + physics.Attach(VehicleEnd::front, VehicleEnd::rear, &last, couplings, true, false); } } else { - mover.Loc = TLocation{position, 0.0, 0.0}; + physics.Loc = TLocation{position, 0.0, 0.0}; } m_vehicles.push_back(std::move(added)); m_positions.push_back(position); @@ -38,20 +38,20 @@ vehicle &consist::add(definition const &Definition, int Cab, CouplingSet const c void consist::update_neighbours() { // TDynamicObject::update_neighbours(), for vehicles coupled in a line for (std::size_t i = 0; i < m_vehicles.size(); ++i) { - auto &mover{m_vehicles[i]->mover()}; + auto &physics{m_vehicles[i]->physics()}; for (auto const end : VehicleEnds) { - auto &neighbour{mover.Neighbours[end]}; + auto &neighbour{physics.Neighbours[end]}; auto const other{end == VehicleEnd::front ? static_cast(i) - 1 : static_cast(i) + 1}; if (other < 0 || other >= static_cast(m_vehicles.size())) { neighbour = neighbour_data(); continue; } - auto const &othermover{m_vehicles[other]->mover()}; + auto const &otherPhysics{m_vehicles[other]->physics()}; auto const otherend{Opposite(end)}; - auto const distance{TMoverParameters::CouplerDist(&mover, &othermover) - mover.Couplers[end].adapter_length - - othermover.Couplers[otherend].adapter_length}; + auto const distance{physics::Vehicle::CouplerDist(&physics, &otherPhysics) - physics.Couplers[end].adapter_length - + otherPhysics.Couplers[otherend].adapter_length}; // a vehicle not coupled is a collision source when it's within the range the game scans - if (mover.Couplers[end].Connected == nullptr && distance > std::max(10.0, std::abs(mover.V)) + 40.0) { + if (physics.Couplers[end].Connected == nullptr && distance > std::max(10.0, std::abs(physics.V)) + 40.0) { neighbour = neighbour_data(); continue; } @@ -84,8 +84,8 @@ void consist::step(track const &Track, double Dt) { auto pipe{0.0}; auto length{0.0}; for (auto const &vehicle : m_vehicles) { - pipe += vehicle->mover().PipePress * vehicle->mover().Dim.L; - length += vehicle->mover().Dim.L; + pipe += vehicle->physics().PipePress * vehicle->physics().Dim.L; + length += vehicle->physics().Dim.L; } pipe /= length; for (std::size_t i = 0; i < m_vehicles.size(); ++i) { @@ -96,11 +96,11 @@ void consist::step(track const &Track, double Dt) { void consist::update_brake_pipes(double Dt) const { // vehicle_table::update_brake_pipes() - std::vector movers; + std::vector vehicles; for (auto const &vehicle : m_vehicles) { - movers.push_back(&vehicle->mover()); + vehicles.push_back(&vehicle->physics()); } - TMoverParameters::UpdatePipeCouplers(movers, Dt); + physics::Vehicle::UpdatePipeCouplers(vehicles, Dt); } void consist::run(double Seconds, track const &Track, double Dt) { @@ -111,7 +111,7 @@ void consist::run(double Seconds, track const &Track, double Dt) { } double consist::gap(std::size_t Index) const { - return TMoverParameters::CouplerDist(&m_vehicles[Index]->mover(), &m_vehicles[Index + 1]->mover()); + return physics::Vehicle::CouplerDist(&m_vehicles[Index]->physics(), &m_vehicles[Index + 1]->physics()); } } // namespace test diff --git a/tests/unit/consist.h b/tests/unit/consist.h index eb330e787..73daa6294 100644 --- a/tests/unit/consist.h +++ b/tests/unit/consist.h @@ -49,7 +49,7 @@ private: std::vector> m_vehicles; std::vector m_positions; // of the vehicles' middles along the track - // the physics reaches a neighbouring vehicle through its TDynamicObject, for its MoverParameters alone. + // the physics reaches a neighbouring vehicle through its TDynamicObject, for its physics alone. // 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; diff --git a/tests/unit/drive.cpp b/tests/unit/drive.cpp index 03785730e..ea60924f5 100644 --- a/tests/unit/drive.cpp +++ b/tests/unit/drive.cpp @@ -15,40 +15,40 @@ void mark(trace *Trace, std::string const &Event) { } } -bool is_powered(TMoverParameters const &Vehicle) { +bool is_powered(physics::Vehicle const &Vehicle) { using enum TEngineType; auto const type{Vehicle.EngineType}; return Vehicle.Power > 1.0 && (type == ElectricSeriesMotor || type == ElectricInductionMotor || type == DieselEngine || type == DieselElectric); } driven driving(vehicle &Vehicle) { - return {Vehicle.mover(), Vehicle.mover(), Vehicle.mover(), [&Vehicle](double Seconds, track const &Track) { Vehicle.run(Seconds, Track); }}; + return {Vehicle.physics(), Vehicle.physics(), Vehicle.physics(), [&Vehicle](double Seconds, track const &Track) { Vehicle.run(Seconds, Track); }}; } driven driving(consist &Consist) { - // the AI's mvControlling and mvPantographUnit: the first vehicle with an engine, and with pantographs - auto *controlling{&Consist[0].mover()}; - auto *pantographs{&Consist[0].mover()}; + // the AI's mvControlling and pantographUnit: the first vehicle with an engine, and with pantographs + auto *controlling{&Consist[0].physics()}; + auto *pantographs{&Consist[0].physics()}; for (auto i = Consist.size(); i-- > 0;) { - auto &mover{Consist[i].mover()}; - if (is_powered(mover)) { - controlling = &mover; + auto &physics{Consist[i].physics()}; + if (is_powered(physics)) { + controlling = &physics; } - if (mover.EnginePowerSource.SourceType == TPowerSource::CurrentCollector && mover.EnginePowerSource.CollectorParameters.CollectorsNo > 0) { - pantographs = &mover; + if (physics.EnginePowerSource.SourceType == TPowerSource::CurrentCollector && physics.EnginePowerSource.CollectorParameters.CollectorsNo > 0) { + pantographs = &physics; } } - return {Consist[0].mover(), *controlling, *pantographs, [&Consist](double Seconds, track const &Track) { Consist.run(Seconds, Track); }}; + return {Consist[0].physics(), *controlling, *pantographs, [&Consist](double Seconds, track const &Track) { Consist.run(Seconds, Track); }}; } namespace { -void attend(TMoverParameters &Mover) { - if (Mover.SecuritySystem.is_cabsignal_blinking() && Mover.SecuritySystem.has_separate_acknowledge()) { - Mover.SecuritySystem.cabsignal_reset(); +void attend(physics::Vehicle &Physics) { + if (Physics.SecuritySystem.is_cabsignal_blinking() && Physics.SecuritySystem.has_separate_acknowledge()) { + Physics.SecuritySystem.cabsignal_reset(); } - if (Mover.SecuritySystem.is_blinking()) { - Mover.SecuritySystemReset(); + if (Physics.SecuritySystem.is_blinking()) { + Physics.SecuritySystemReset(); } } @@ -62,7 +62,7 @@ void drive(driven Driven, track const &Track, double Seconds) { } } -void release_brakes(TMoverParameters &Cab) { +void release_brakes(physics::Vehicle &Cab) { Cab.BrakeLevelSet(Cab.Handle->GetPos(bh_RP)); Cab.DecLocalBrakeLevel(LocalBrakePosNo); Cab.DecManualBrakeLevel(ManualBrakePosNo); @@ -85,12 +85,12 @@ void release_brakes(TMoverParameters &Cab) { } bool is_ready(driven const &Driven) { - auto const &mover{Driven.controlling}; - auto const air{mover.VeselVolume <= 0.0 || mover.ScndPipePress >= 4.5}; + auto const &physics{Driven.controlling}; + auto const air{physics.VeselVolume <= 0.0 || physics.ScndPipePress >= 4.5}; // the converter feeds the 110 V circuits (the electrodynamic brake's control among them); the AI switches // it on once the line breaker is closed, so a train already charged with air isn't ready before it runs - auto const converter{mover.ConverterStart != start_t::manual || mover.ConverterFlag}; - return mover.Mains && air && converter; + auto const converter{physics.ConverterStart != start_t::manual || physics.ConverterFlag}; + return physics.Mains && air && converter; } namespace { @@ -140,7 +140,7 @@ void close_line_breaker(driven const &Driven) { // the converter, the compressor and the motor blowers, once the line breaker is closed; and the switch of the // field shunting of a diesel-electric that has one (AutoRelay=Optional with FieldShuntSwitch=Yes), as the AI does -void switch_auxiliaries_on(TMoverParameters &Cab) { +void switch_auxiliaries_on(physics::Vehicle &Cab) { Cab.ConverterSwitch(true); Cab.CompressorSwitch(true); for (auto const side : VehicleEnds) { diff --git a/tests/unit/drive.h b/tests/unit/drive.h index a1aed95be..dce224af9 100644 --- a/tests/unit/drive.h +++ b/tests/unit/drive.h @@ -15,12 +15,12 @@ class consist; // (Cab != 0): a lone one, or the first one of a consist, and drives the whole of it // what the driver drives: the vehicle with the driver in it, the vehicles the driver controls the engine and -// the pantographs of (the AI's mvOccupied, mvControlling, mvPantographUnit; all the same one in a lone +// the pantographs of (the AI's occupied, mvControlling, pantographUnit; all the same one in a lone // vehicle or a locomotive), and the way to run the whole of it struct driven { - TMoverParameters &cab; - TMoverParameters &controlling; - TMoverParameters &pantographs; + physics::Vehicle &cab; + physics::Vehicle &controlling; + physics::Vehicle &pantographs; std::function run; }; driven driving(vehicle &Vehicle); @@ -37,13 +37,13 @@ void drive(driven Driven, track const &Track, double Seconds); // releases every brake the driver has a hand on: the train brake to running, the independent brake, the // hand brake and the spring brake; and the hand and spring brakes of the vehicles coupled to the cab's -void release_brakes(TMoverParameters &Cab); +void release_brakes(physics::Vehicle &Cab); // whether the vehicle is ready to run: line breaker closed (or the engine running), air in the main reservoir bool is_ready(driven const &Driven); // whether the vehicle drives itself -bool is_powered(TMoverParameters const &Vehicle); +bool is_powered(physics::Vehicle const &Vehicle); // a trace mark, when there's a trace void mark(trace *Trace, std::string const &Event); diff --git a/tests/unit/figures.cpp b/tests/unit/figures.cpp index 96f5a3d74..949a53061 100644 --- a/tests/unit/figures.cpp +++ b/tests/unit/figures.cpp @@ -59,7 +59,7 @@ constexpr double pipe_back{4.9}; } // namespace -void figures::sample(double Time, TMoverParameters const &Vehicle) { +void figures::sample(double Time, physics::Vehicle const &Vehicle) { auto &part{m_parts.back()}; auto const speed{Vehicle.V * 3.6}; auto const pipe{Vehicle.PipePress}; diff --git a/tests/unit/figures.h b/tests/unit/figures.h index 576852dbb..793eaecb8 100644 --- a/tests/unit/figures.h +++ b/tests/unit/figures.h @@ -3,7 +3,7 @@ #include #include -#include "physics/mover.h" +#include "physics/vehicle.h" namespace test { @@ -26,7 +26,7 @@ namespace test { class figures { public: // called on every step of the vehicle - void sample(double Time, TMoverParameters const &Vehicle); + void sample(double Time, physics::Vehicle const &Vehicle); // a part of the run starts with the event void mark(std::string const &Event); diff --git a/tests/unit/fiz.h b/tests/unit/fiz.h index 1e65049fc..5deec2c5f 100644 --- a/tests/unit/fiz.h +++ b/tests/unit/fiz.h @@ -6,7 +6,7 @@ class cParser; -// what the game's vehicle loader (TMoverParameters::LoadFIZ_Parse) makes of the lines of a vehicle definition, +// what the game's vehicle loader (physics::Vehicle::LoadFIZ_Parse) makes of the lines of a vehicle definition, // for the test definitions to give it the same and for checking they do namespace test::fiz { diff --git a/tests/unit/golden.cpp b/tests/unit/golden.cpp index da6a3ce8c..aff0890f7 100644 --- a/tests/unit/golden.cpp +++ b/tests/unit/golden.cpp @@ -266,7 +266,7 @@ bool same(std::string const &Recorded, std::string const &Now, bool const Exact) trace::trace(std::string Name, std::vector Channels, int Every, bool Figures) : m_name(std::move(Name)), m_channels(std::move(Channels)), m_every(Every), m_keep_figures(Figures) {} -void trace::sample(double Time, TMoverParameters const &Vehicle) { +void trace::sample(double Time, physics::Vehicle const &Vehicle) { // the invariants on every step, the first time each is broken for (auto const &invariant : invariants()) { if (std::ranges::find(m_broken, invariant.name) != m_broken.end()) { diff --git a/tests/unit/golden.h b/tests/unit/golden.h index d53acfa8d..a4714a925 100644 --- a/tests/unit/golden.h +++ b/tests/unit/golden.h @@ -5,7 +5,7 @@ #include #include -#include "physics/mover.h" +#include "physics/vehicle.h" #include "figures.h" #include "invariants.h" @@ -14,7 +14,7 @@ namespace test { // one value of the vehicle a trace follows struct channel { std::string name; - std::function value; + std::function value; }; // sets of channels for the usual subjects of a test, which can be put together @@ -55,7 +55,7 @@ public: trace(std::string Name, std::vector Channels, int Every = 10, bool Figures = true); // called by the vehicle after every step - void sample(double Time, TMoverParameters const &Vehicle); + void sample(double Time, physics::Vehicle const &Vehicle); // adds an event of the test to the trace, so a difference can be told apart from the moment of the action void mark(std::string const &Event); diff --git a/tests/unit/invariants.cpp b/tests/unit/invariants.cpp index e742fce41..d2e938d94 100644 --- a/tests/unit/invariants.cpp +++ b/tests/unit/invariants.cpp @@ -18,11 +18,11 @@ std::string values(std::initializer_list> Values return result; } -bool electric(TMoverParameters const &M) { +bool electric(physics::Vehicle const &M) { return M.EngineType == TEngineType::ElectricSeriesMotor || M.EngineType == TEngineType::ElectricInductionMotor; } -double max_brake_press(TMoverParameters const &M) { +double max_brake_press(physics::Vehicle const &M) { auto result{0.0}; for (auto const press : M.MaxBrakePress) { result = std::max(result, press); diff --git a/tests/unit/invariants.h b/tests/unit/invariants.h index 83e10e7d9..59550633d 100644 --- a/tests/unit/invariants.h +++ b/tests/unit/invariants.h @@ -5,7 +5,7 @@ #include #include -#include "physics/mover.h" +#include "physics/vehicle.h" namespace test { @@ -23,9 +23,9 @@ struct snapshot { struct invariant { std::string name; // Before is null at the first step of a trace - std::function holds; + std::function holds; // the values the rule looks at, shown when it's broken - std::function explain; + std::function explain; }; std::vector const &invariants(); diff --git a/tests/unit/scenario.cpp b/tests/unit/scenario.cpp index 9dfee124f..b26300a35 100644 --- a/tests/unit/scenario.cpp +++ b/tests/unit/scenario.cpp @@ -11,7 +11,7 @@ namespace { // switch is on when the controller leaves zero doesn't close its line contactors until the controller is back at zero bool start_cut_off(consist &Train) { for (std::size_t i = 0; i < Train.size(); ++i) { - if (Train[i].mover().ControlPressureSwitch) { + if (Train[i].physics().ControlPressureSwitch) { return true; } } diff --git a/tests/unit/scenario.h b/tests/unit/scenario.h index 29a9f5592..195e6fc3a 100644 --- a/tests/unit/scenario.h +++ b/tests/unit/scenario.h @@ -28,8 +28,8 @@ public: scenario &add(std::string const &Path, int Cab = 0, CouplingSet couplings = consist::full_coupling, double Velocity = 0.0, double Gap = 0.0); consist &train() { return m_train; } - TMoverParameters &vehicle(std::size_t Index) { return m_train[Index].mover(); } - TMoverParameters &cab() { return m_train[0].mover(); } + physics::Vehicle &vehicle(std::size_t Index) { return m_train[Index].physics(); } + physics::Vehicle &cab() { return m_train[0].physics(); } driven driver() { return driving(m_train); } track &line() { return m_track; } diff --git a/tests/unit/test_brake_pipe.cpp b/tests/unit/test_brake_pipe.cpp index 7f6b8257e..e7f9a3dd7 100644 --- a/tests/unit/test_brake_pipe.cpp +++ b/tests/unit/test_brake_pipe.cpp @@ -1,12 +1,12 @@ #include "stdafx.h" #include "doctest.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "physics/brakes.h" #include "consist.h" #include "vehicle.h" -// the air exchange through the brake hoses between the vehicles of a train (TMoverParameters::UpdatePipeCouplers()). +// 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 // 0.28 bar off what was in it, lapped at the first stage of braking and kept the AI's train from leaving @@ -70,7 +70,7 @@ TEST_CASE("brake pipe: the distributors of a standing freight train see the pres train.run(300.0); for (std::size_t i = 1; i < train.size(); ++i) { CAPTURE(i); - auto &wagon{train[i].mover()}; + auto &wagon{train[i].physics()}; // the distributor's valve chamber follows the pressure the distributor works with: the pipe's own CHECK(std::abs(wagon.Hamulec->GetVRP() - wagon.PipePress) < 0.005); CHECK(wagon.PipePress > 4.9); @@ -105,7 +105,7 @@ TEST_CASE("brake pipe: a passenger train, whose exchange was stable in one step, train.run(300.0); for (std::size_t i = 1; i < train.size(); ++i) { CAPTURE(i); - auto &car{train[i].mover()}; + auto &car{train[i].physics()}; CHECK(std::abs(car.Hamulec->GetVRP() - car.PipePress) < 0.005); CHECK((car.Hamulec->GetBrakeStatus() & (b_on | b_hld)) == 0); CHECK(car.BrakePress < 0.1); diff --git a/tests/unit/test_brake_setting.cpp b/tests/unit/test_brake_setting.cpp index ce9d09075..a8d5fb0af 100644 --- a/tests/unit/test_brake_setting.cpp +++ b/tests/unit/test_brake_setting.cpp @@ -1,7 +1,7 @@ #include "stdafx.h" #include "doctest.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "physics/brakes.h" #include "vehicle.h" #include "vehicle/brakesetting.h" @@ -209,18 +209,18 @@ void charge_and_apply(test::vehicle &Vehicle) { // running it as a train or shunting it, standing or on the run int inspect_heavy_train(test::vehicle &Vehicle, bool const Train = as_train, bool const Standstill = standstill) { auto consist{train(locomotive(), 30, freight_wagon(15.0, 80.0))}; - consist.emplace_back(brake_setting::describe(Vehicle.mover(), false)); + consist.emplace_back(brake_setting::describe(Vehicle.physics(), false)); auto const setting{brake_setting::choose(consist, Train).back()}; - brake_setting::apply(Vehicle.mover(), setting, Standstill); + brake_setting::apply(Vehicle.physics(), setting, Standstill); return setting; } // the same on a light train, which runs on P int inspect_light_train(test::vehicle &Vehicle) { auto consist{train(locomotive(), 4, freight_wagon())}; - consist.emplace_back(brake_setting::describe(Vehicle.mover(), false)); + consist.emplace_back(brake_setting::describe(Vehicle.physics(), false)); auto const setting{brake_setting::choose(consist, as_train).back()}; - brake_setting::apply(Vehicle.mover(), setting, standstill); + brake_setting::apply(Vehicle.physics(), setting, standstill); return setting; } @@ -229,13 +229,13 @@ int inspect_light_train(test::vehicle &Vehicle) { bool inspection_pending(std::vector const &Vehicles, bool const Train, bool const Standstill) { auto consist{train(locomotive(), 30, freight_wagon(15.0, 80.0))}; for (auto *vehicle : Vehicles) { - consist.emplace_back(brake_setting::describe(vehicle->mover(), false)); + consist.emplace_back(brake_setting::describe(vehicle->physics(), false)); } auto const settings{brake_setting::choose(consist, Train)}; auto setting{settings.end() - static_cast(Vehicles.size())}; auto pending{false}; for (auto *vehicle : Vehicles) { - if (brake_setting::apply(vehicle->mover(), *setting++, Standstill)) { + if (brake_setting::apply(vehicle->physics(), *setting++, Standstill)) { pending = true; } } @@ -251,7 +251,7 @@ TEST_CASE("brake setting: the inspector cuts the brake out in a train on G and p // made up into a heavy train on G: the brake is cut out and released REQUIRE(inspect_heavy_train(car) == brake_setting::cut_out); - CHECK(brake_setting::is_cut_out(car.mover())); + CHECK(brake_setting::is_cut_out(car.physics())); CHECK(car->BrakeCutOutByInspector); car.run(30.0); CHECK(car->BrakePress < 0.1); @@ -265,13 +265,13 @@ TEST_CASE("brake setting: the inspector cuts the brake out in a train on G and p car.run(20.0); CHECK(car->BrakePress < 0.1); // to the inspector looking at the train again it's a car like any other, and the train needs it cut out still - CHECK(false == brake_setting::describe(car.mover(), false).cut_out); + CHECK(false == brake_setting::describe(car.physics(), false).cut_out); REQUIRE(inspect_heavy_train(car) == brake_setting::cut_out); CHECK(car->BrakeCutOutByInspector); // made up into a light train: the brake is back on P, charges and brakes again CHECK(inspect_light_train(car) == P); - CHECK(false == brake_setting::is_cut_out(car.mover())); + CHECK(false == brake_setting::is_cut_out(car.physics())); CHECK(false == car->BrakeCutOutByInspector); CHECK(car->BrakeDelayFlag == P); // the reservoirs emptied when it was cut out take some five minutes to charge from the brake pipe @@ -288,14 +288,14 @@ TEST_CASE("brake setting: the inspector never puts back a brake cut out for anot // cut out the way the scenery's '0' does it car->Hamulec->ForceEmptiness(); car->Hamulec->SetBrakeStatus(car->Hamulec->GetBrakeStatus() | b_dmg); - CHECK(brake_setting::describe(car.mover(), false).cut_out); + CHECK(brake_setting::describe(car.physics(), false).cut_out); // a train on G wants it cut out anyway: it isn't the inspector's to put back CHECK(inspect_heavy_train(car) == brake_setting::cut_out); CHECK(false == car->BrakeCutOutByInspector); // a train on P would want it working: it stays cut out CHECK(inspect_light_train(car) == P); - CHECK(brake_setting::is_cut_out(car.mover())); + CHECK(brake_setting::is_cut_out(car.physics())); charge_and_apply(car); CHECK(car->BrakePress < 0.1); @@ -310,7 +310,7 @@ TEST_CASE("brake setting: the inspector never puts back a brake cut out for anot CHECK(false == other->BrakeCutOutByInspector); other->Hamulec->SetBrakeStatus(other->Hamulec->GetBrakeStatus() | b_dmg); CHECK(inspect_light_train(other) == P); - CHECK(brake_setting::is_cut_out(other.mover())); + CHECK(brake_setting::is_cut_out(other.physics())); } TEST_CASE("brake setting: shunting puts back a brake the inspector cut out, and cuts none out") { @@ -318,7 +318,7 @@ TEST_CASE("brake setting: shunting puts back a brake the inspector cut out, and charge_and_apply(car); // shunted in a heavy consist: nothing is cut out, the car is on P and brakes CHECK(inspect_heavy_train(car, shunting) == P); - CHECK(false == brake_setting::is_cut_out(car.mover())); + CHECK(false == brake_setting::is_cut_out(car.physics())); CHECK(car->BrakeDelayFlag == P); CHECK(car->BrakePress > 1.0); @@ -326,7 +326,7 @@ TEST_CASE("brake setting: shunting puts back a brake the inspector cut out, and REQUIRE(inspect_heavy_train(car) == brake_setting::cut_out); REQUIRE(car->BrakeCutOutByInspector); CHECK(inspect_heavy_train(car, shunting) == P); - CHECK(false == brake_setting::is_cut_out(car.mover())); + CHECK(false == brake_setting::is_cut_out(car.physics())); CHECK(false == car->BrakeCutOutByInspector); car.hold_brake_pipe(5.0); car.run(300.0); @@ -337,7 +337,7 @@ TEST_CASE("brake setting: shunting puts back a brake the inspector cut out, and test::vehicle other{passenger_car_definition()}; other->Hamulec->SetBrakeStatus(other->Hamulec->GetBrakeStatus() | b_dmg); CHECK(inspect_heavy_train(other, shunting) == P); - CHECK(brake_setting::is_cut_out(other.mover())); + CHECK(brake_setting::is_cut_out(other.physics())); } TEST_CASE("brake setting: the inspector doesn't cut a brake out on the run, it waits for a standstill") { @@ -347,20 +347,20 @@ TEST_CASE("brake setting: the inspector doesn't cut a brake out on the run, it w // the train checked on the run (the order changed mid-run): the car keeps its brake and its setting auto const setting{car->BrakeDelayFlag}; CHECK(inspect_heavy_train(car, as_train, moving) == brake_setting::cut_out); - CHECK(false == brake_setting::is_cut_out(car.mover())); + CHECK(false == brake_setting::is_cut_out(car.physics())); CHECK(false == car->BrakeCutOutByInspector); CHECK(car->BrakeDelayFlag == setting); car.run(5.0); CHECK(car->BrakePress > 1.0); // the next check, standing, cuts it out CHECK(inspect_heavy_train(car) == brake_setting::cut_out); - CHECK(brake_setting::is_cut_out(car.mover())); + CHECK(brake_setting::is_cut_out(car.physics())); CHECK(car->BrakeCutOutByInspector); // a brake cut out already stays cut out on the run, and one put back on the run is back CHECK(inspect_heavy_train(car, as_train, moving) == brake_setting::cut_out); CHECK(car->BrakeCutOutByInspector); CHECK(inspect_heavy_train(car, shunting, moving) == P); - CHECK(false == brake_setting::is_cut_out(car.mover())); + CHECK(false == brake_setting::is_cut_out(car.physics())); CHECK(false == car->BrakeCutOutByInspector); } @@ -378,8 +378,8 @@ TEST_CASE("brake setting: a cut-out skipped on the run is reported, and done at // moving: nothing is cut out, and the inspector tells it has to come back CHECK(inspection_pending(vehicles, as_train, brake_setting::at_standstill(3.0))); for (auto *vehicle : vehicles) { - CHECK(false == brake_setting::is_cut_out(vehicle->mover())); - CHECK(false == vehicle->mover().BrakeCutOutByInspector); + CHECK(false == brake_setting::is_cut_out(vehicle->physics())); + CHECK(false == vehicle->physics().BrakeCutOutByInspector); } CHECK(first->BrakeDelayFlag == setting); CHECK(wagon->BrakeDelayFlag == G); @@ -387,14 +387,14 @@ TEST_CASE("brake setting: a cut-out skipped on the run is reported, and done at CHECK(inspection_pending(vehicles, as_train, moving)); // the train stands (its brake pipe charging after the coupling): the cars get cut out, nothing is left CHECK(false == inspection_pending(vehicles, as_train, brake_setting::at_standstill(0.0))); - CHECK(brake_setting::is_cut_out(first.mover())); + CHECK(brake_setting::is_cut_out(first.physics())); CHECK(first->BrakeCutOutByInspector); - CHECK(brake_setting::is_cut_out(second.mover())); + CHECK(brake_setting::is_cut_out(second.physics())); CHECK(second->BrakeCutOutByInspector); - CHECK(false == brake_setting::is_cut_out(wagon.mover())); + CHECK(false == brake_setting::is_cut_out(wagon.physics())); // and nothing is pending when the train moves off CHECK(false == inspection_pending(vehicles, as_train, moving)); - CHECK(brake_setting::is_cut_out(first.mover())); + CHECK(brake_setting::is_cut_out(first.physics())); } TEST_CASE("brake setting: an inspection on the run with nothing to cut out leaves nothing pending") { @@ -405,7 +405,7 @@ TEST_CASE("brake setting: an inspection on the run with nothing to cut out leave // a car without G in a consist being shunted: it keeps its brake, on P test::vehicle car{passenger_car_definition()}; CHECK(false == inspection_pending({&car}, shunting, moving)); - CHECK(false == brake_setting::is_cut_out(car.mover())); + CHECK(false == brake_setting::is_cut_out(car.physics())); // a car whose brake is cut out already, for a reason of its own or by the inspector test::vehicle damaged{passenger_car_definition()}; damaged->Hamulec->SetBrakeStatus(damaged->Hamulec->GetBrakeStatus() | b_dmg); @@ -417,14 +417,14 @@ TEST_CASE("brake setting: an inspection on the run with nothing to cut out leave CHECK(false == inspection_pending({&done}, as_train, moving)); // a brake put back on the run (the train became a consist being shunted) leaves nothing either CHECK(false == inspection_pending({&done}, shunting, moving)); - CHECK(false == brake_setting::is_cut_out(done.mover())); + CHECK(false == brake_setting::is_cut_out(done.physics())); // a single vehicle's apply() tells the same test::vehicle single{passenger_car_definition()}; - CHECK(brake_setting::apply(single.mover(), brake_setting::cut_out, moving)); - CHECK(false == brake_setting::apply(single.mover(), P, moving)); - CHECK(false == brake_setting::apply(single.mover(), 0, moving)); - CHECK(false == brake_setting::apply(single.mover(), brake_setting::cut_out, standstill)); - CHECK(false == brake_setting::apply(single.mover(), brake_setting::cut_out, moving)); + CHECK(brake_setting::apply(single.physics(), brake_setting::cut_out, moving)); + CHECK(false == brake_setting::apply(single.physics(), P, moving)); + CHECK(false == brake_setting::apply(single.physics(), 0, moving)); + CHECK(false == brake_setting::apply(single.physics(), brake_setting::cut_out, standstill)); + CHECK(false == brake_setting::apply(single.physics(), brake_setting::cut_out, moving)); } TEST_CASE("brake setting: a train creeping to a stop counts as standing, one on the run or coupling doesn't") { @@ -443,13 +443,13 @@ TEST_CASE("brake setting: a train creeping to a stop counts as standing, one on test::vehicle creeping{passenger_car_definition()}; charge_and_apply(creeping); CHECK(inspect_heavy_train(creeping, as_train, brake_setting::at_standstill(0.9)) == brake_setting::cut_out); - CHECK(brake_setting::is_cut_out(creeping.mover())); + CHECK(brake_setting::is_cut_out(creeping.physics())); CHECK(creeping->BrakeCutOutByInspector); // checked at 30 km/h: the car keeps its brake test::vehicle running{passenger_car_definition()}; charge_and_apply(running); CHECK(inspect_heavy_train(running, as_train, brake_setting::at_standstill(30.0)) == brake_setting::cut_out); - CHECK(false == brake_setting::is_cut_out(running.mover())); + CHECK(false == brake_setting::is_cut_out(running.physics())); CHECK(false == running->BrakeCutOutByInspector); running.run(5.0); CHECK(running->BrakePress > 1.0); @@ -468,10 +468,10 @@ TEST_CASE("brake setting: a bank engine's run counts as a train, shunting doesn' test::vehicle car{passenger_car_definition()}; charge_and_apply(car); CHECK(inspect_heavy_train(car, brake_setting::runs_as_train(DriverOrder::bank)) == brake_setting::cut_out); - CHECK(brake_setting::is_cut_out(car.mover())); + CHECK(brake_setting::is_cut_out(car.physics())); // shunted: it's back on P CHECK(inspect_heavy_train(car, brake_setting::runs_as_train(DriverOrder::shunt)) == P); - CHECK(false == brake_setting::is_cut_out(car.mover())); + CHECK(false == brake_setting::is_cut_out(car.physics())); } TEST_CASE("brake setting: the AI looks at its train under the orders it drives it under, Connect included") { diff --git a/tests/unit/test_brakes.cpp b/tests/unit/test_brakes.cpp index 5c5246798..cb83e2f0e 100644 --- a/tests/unit/test_brakes.cpp +++ b/tests/unit/test_brakes.cpp @@ -107,7 +107,7 @@ TEST_CASE("brakes: a dead EN57 hauled with the brake hose alone charges from the train.add(definition::fiz("en57_v1/5bgaiii_led_spot")); // a unit standing dead: no air anywhere, nothing in its main reservoir pipe for (std::size_t i = 1; i < train.size(); ++i) { - auto &car{train[i].mover()}; + auto &car{train[i].physics()}; REQUIRE(car.BrakeValve == TBrakeValve::EP2); car.Hamulec->ForceEmptiness(); car.Pipe->CreatePress(0.0); @@ -120,7 +120,7 @@ TEST_CASE("brakes: a dead EN57 hauled with the brake hose alone charges from the train.run(900.0); for (std::size_t i = 1; i < train.size(); ++i) { CAPTURE(i); - auto &car{train[i].mover()}; + auto &car{train[i].physics()}; REQUIRE(car.ScndPipePress < 0.1); // no main reservoir pipe CHECK(car.Hamulec->GetBRP() > 4.8); CHECK(car.Hamulec->GetCRP() > 4.8); diff --git a/tests/unit/test_cab.cpp b/tests/unit/test_cab.cpp index ca58d6a65..14c5e163d 100644 --- a/tests/unit/test_cab.cpp +++ b/tests/unit/test_cab.cpp @@ -21,9 +21,9 @@ using namespace test::channels; TEST_CASE("cab: the engine rotation of up to three vehicles in multiple, on the tachometers of the SN61") { consist train; - auto &first{train.add(definition::fiz("sn61_v2/sn61"), 1).mover()}; - auto &second{train.add(definition::fiz("sn61_v2/sn61")).mover()}; - auto &third{train.add(definition::fiz("sn61_v2/sn61")).mover()}; + auto &first{train.add(definition::fiz("sn61_v2/sn61"), 1).physics()}; + auto &second{train.add(definition::fiz("sn61_v2/sn61")).physics()}; + auto &third{train.add(definition::fiz("sn61_v2/sn61")).physics()}; first.enrot = -10.0; second.enrot = 20.0; third.enrot = 30.0; @@ -37,15 +37,15 @@ TEST_CASE("cab: the engine rotation of up to three vehicles in multiple, on the CHECK(third.ShowEngineRotation(3) == doctest::Approx(10.0)); // no control cable, no reading consist apart; - auto const &alone{apart.add(definition::fiz("sn61_v2/sn61"), 1).mover()}; + auto const &alone{apart.add(definition::fiz("sn61_v2/sn61"), 1).physics()}; apart.add(definition::fiz("sn61_v2/sn61"), 0, Coupling::coupler | Coupling::brakeHose); CHECK(alone.ShowEngineRotation(2) == doctest::Approx(0.0)); } TEST_CASE("cab: the lamps of the overload relay and the starting resistors, read through the control cable") { consist unit; - auto &trailer{unit.add(definition::fiz("ed72_v1/5bs-ra"), 1).mover()}; - auto &motor{unit.add(definition::fiz("ed72_v1/6bs-sa")).mover()}; + auto &trailer{unit.add(definition::fiz("ed72_v1/5bs-ra"), 1).physics()}; + auto &motor{unit.add(definition::fiz("ed72_v1/6bs-sa")).physics()}; REQUIRE(trailer.Power < 0.01); REQUIRE(motor.Power > 0.01); CHECK_FALSE(trailer.FuseFlagCheck()); @@ -91,7 +91,7 @@ TEST_CASE("cab: the controller of the electrodynamic brake apart from the local CHECK_FALSE(eu47.IncDynamicBrakeLevel(1.f)); CHECK(eu47.DynamicBrakeRatio() == doctest::Approx(0.0)); - scenario.train()[0].mover().SplitEDPneumaticBrake = true; + scenario.train()[0].physics().SplitEDPneumaticBrake = true; REQUIRE(scenario.start_up()); REQUIRE(eu47.DynamicBrakeCtrlPosNo == 10); CHECK(eu47.DynamicBrakeAvailable()); diff --git a/tests/unit/test_camshaft.cpp b/tests/unit/test_camshaft.cpp index 940616a62..959c81d37 100644 --- a/tests/unit/test_camshaft.cpp +++ b/tests/unit/test_camshaft.cpp @@ -67,7 +67,7 @@ definition skoda() { // the locomotive running with the line contactors closed and the camshaft at Position, the master controller moved // to Controller, in the given direction; the time since the last step of the camshaft long enough for the next one -void running(TMoverParameters &Locomotive, int const Direction, int const Position, int const Controller) { +void running(physics::Vehicle &Locomotive, int const Direction, int const Position, int const Controller) { Locomotive.CabActive = 1; Locomotive.DirActive = Direction; Locomotive.Mains = true; @@ -81,7 +81,7 @@ void running(TMoverParameters &Locomotive, int const Direction, int const Positi // steps the camshaft as the physics does, each step once the delay since the previous one passed; returns where it // ended up -int run_camshaft(TMoverParameters &Locomotive, int const Steps) { +int run_camshaft(physics::Vehicle &Locomotive, int const Steps) { for (int step = 0; step < Steps; ++step) { Locomotive.LastRelayTime = 10.0; Locomotive.AutoRelayCheck(); @@ -93,43 +93,43 @@ int run_camshaft(TMoverParameters &Locomotive, int const Steps) { TEST_CASE("camshaft: running backwards, the camshaft goes back down from the last series position (eu07/maszyna#393)") { vehicle locomotive{skoda()}; - auto &mover{locomotive.mover()}; - REQUIRE(mover.HasCamshaft); - REQUIRE(mover.RlistSize == 43); - REQUIRE(mover.RList[22].Bn == 1); - REQUIRE(mover.RList[23].Bn == 2); + auto &physics{locomotive.physics()}; + REQUIRE(physics.HasCamshaft); + REQUIRE(physics.RlistSize == 43); + REQUIRE(physics.RList[22].Bn == 1); + REQUIRE(physics.RList[23].Bn == 2); SUBCASE("the controller turned back a few positions") { - running(mover, -1, 22, 15); - CHECK(run_camshaft(mover, 1) == 21); // it used to stay at 22 - CHECK(run_camshaft(mover, 10) == 15); + running(physics, -1, 22, 15); + CHECK(run_camshaft(physics, 1) == 21); // it used to stay at 22 + CHECK(run_camshaft(physics, 10) == 15); } SUBCASE("the controller turned back to zero: the camshaft runs down and the line contactors open") { - running(mover, -1, 22, 0); - run_camshaft(mover, 30); - CHECK(mover.MainCtrlActualPos == 0); - CHECK_FALSE(mover.StLinFlag); // the motors don't pull any more + running(physics, -1, 22, 0); + run_camshaft(physics, 30); + CHECK(physics.MainCtrlActualPos == 0); + CHECK_FALSE(physics.StLinFlag); // the motors don't pull any more } } TEST_CASE("camshaft: running backwards, the camshaft still doesn't go past the series connection") { vehicle locomotive{skoda()}; - auto &mover{locomotive.mover()}; - running(mover, -1, 20, 43); - CHECK(run_camshaft(mover, 10) == 22); + auto &physics{locomotive.physics()}; + running(physics, -1, 20, 43); + CHECK(run_camshaft(physics, 10) == 22); SUBCASE("unless more branches are allowed backwards") { - mover.BackwardsBranchesAllowed = 2; - CHECK(run_camshaft(mover, 20) == 34); + physics.BackwardsBranchesAllowed = 2; + CHECK(run_camshaft(physics, 20) == 34); } } TEST_CASE("camshaft: running forwards, the camshaft goes through all the connections and back") { vehicle locomotive{skoda()}; - auto &mover{locomotive.mover()}; - running(mover, 1, 20, 43); - CHECK(run_camshaft(mover, 30) == 43); + auto &physics{locomotive.physics()}; + running(physics, 1, 20, 43); + CHECK(run_camshaft(physics, 30) == 43); - mover.MainCtrlPos = 10; - CHECK(run_camshaft(mover, 40) == 10); + physics.MainCtrlPos = 10; + CHECK(run_camshaft(physics, 40) == 10); } diff --git a/tests/unit/test_cntrl.cpp b/tests/unit/test_cntrl.cpp index bff7759ea..425a2b07a 100644 --- a/tests/unit/test_cntrl.cpp +++ b/tests/unit/test_cntrl.cpp @@ -5,7 +5,7 @@ using test::definition; using test::vehicle; -// the Cntrl. section of the vehicle definition, as read by TMoverParameters::LoadFIZ_Cntrl() +// the Cntrl. section of the vehicle definition, as read by physics::Vehicle::LoadFIZ_Cntrl() TEST_CASE("cntrl: the brake delays of the settings come from BDelay1 to BDelay4") { vehicle wagon{definition::load("wagon").set("Cntrl", "BDelay1", 10.0).set("Cntrl", "BDelay2", 20.0).set("Cntrl", "BDelay3", 30.0).set("Cntrl", "BDelay4", 40.0)}; @@ -41,7 +41,7 @@ TEST_CASE("cntrl: the relays of a multiple unit start on their own, of other veh namespace { // the first position of the master controller after Position without the starting resistors in the circuit -int resistance_free_position(TMoverParameters const &Vehicle, int Position = 0) { +int resistance_free_position(physics::Vehicle const &Vehicle, int Position = 0) { for (auto position{Position + 1}; position <= Vehicle.MainCtrlPosNo; ++position) { if (Vehicle.RList[position].R < 0.01) { return position; @@ -65,7 +65,7 @@ TEST_CASE("cntrl: ScndCtrlResistiveLock keeps the field shunting off at zero and vehicle locked{definition::fiz(path).set("Cntrl", "ScndCtrlResistiveLock", "Yes"), 0.0, "test", 1}; REQUIRE(locked->ScndCtrlResistiveLock); REQUIRE(locked->ScndCtrlPosNo > 0); - auto const resistancefree{resistance_free_position(locked.mover())}; + auto const resistancefree{resistance_free_position(locked.physics())}; REQUIRE(resistancefree > 1); if (resistancefree <= 1) { continue; // not reached, the REQUIRE above ends the test; tells the static analysis the index below is in range @@ -88,7 +88,7 @@ TEST_CASE("cntrl: ScndCtrlResistiveLock keeps the field shunting off at zero and } } SUBCASE("every resistance-free position") { - for (auto position{resistancefree}; position > 0; position = resistance_free_position(locked.mover(), position)) { + for (auto position{resistancefree}; position > 0; position = resistance_free_position(locked.physics(), position)) { CAPTURE(position); controllers_at(locked, position); CHECK_FALSE(locked->IsScndCtrlLockedByMainCtrl()); @@ -142,7 +142,7 @@ TEST_CASE("cntrl: ScndCtrlResistiveLock keeps the field shunting off at zero and SUBCASE("the master controller moved up from a shunt step onto a resistive position drops the shunt") { // the last series position, followed by the resistive parallel ones auto lastseries{0}; - for (auto position{resistancefree}; position > 0 && position < locked->MainCtrlPosNo; position = resistance_free_position(locked.mover(), position)) { + for (auto position{resistancefree}; position > 0 && position < locked->MainCtrlPosNo; position = resistance_free_position(locked.physics(), position)) { if (locked->RList[position + 1].R >= 0.01) { lastseries = position; break; diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index bb0395df7..24dc4d545 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -4,7 +4,7 @@ #include "drive.h" #include "vehicle.h" #include "physics/collision.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "utilities/Globals.h" #include @@ -111,11 +111,11 @@ cl::crush_curve const locomotive_curve{cl::default_crush(cl::vehicle_kind::locom // ---- trains of real vehicles -bool derailed(TMoverParameters const &Vehicle) { +bool derailed(physics::Vehicle const &Vehicle) { return Vehicle.DamageFlag.HasAll(VehicleDamage::derailed); } -double crush_of(TMoverParameters const &Vehicle) { +double crush_of(physics::Vehicle const &Vehicle) { return std::max(Vehicle.Couplers[VehicleEnd::front].crush, Vehicle.Couplers[VehicleEnd::rear].crush); } @@ -170,7 +170,7 @@ crash_outcome freight_crash(double const Speed, double const Radius, double cons crash_outcome result; for (std::size_t i = 0; i < train.size(); ++i) { - auto const &vehicle{train[i].mover()}; + auto const &vehicle{train[i].physics()}; auto const name{i < standing ? std::format("standing {}", standing - 1 - i) : i == standing ? std::string{"locomotive"} : std::format("running {}", i - standing - 1)}; for (auto const end : VehicleEnds) { if (vehicle.Couplers[end].crush >= cl::crush_mark) { @@ -208,17 +208,17 @@ double locomotive_into_wagon(double const Speed, double const Dt) { } // the energy the crush of both ends of the pair took, by their curves [J] -double crush_energy(TMoverParameters const &First, VehicleEnd const FirstEnd, TMoverParameters const &Second, VehicleEnd const SecondEnd) { +double crush_energy(physics::Vehicle const &First, VehicleEnd const FirstEnd, physics::Vehicle const &Second, VehicleEnd const SecondEnd) { return First.crush_curve_at(FirstEnd).energy(0.0, First.Couplers[FirstEnd].crush) + Second.crush_curve_at(SecondEnd).energy(0.0, Second.Couplers[SecondEnd].crush); } // what the buffers of EN 15551 of the two ends take in [J] -double capacity_of(TMoverParameters const &First, VehicleEnd const FirstEnd, TMoverParameters const &Second, VehicleEnd const SecondEnd) { +double capacity_of(physics::Vehicle const &First, VehicleEnd const FirstEnd, physics::Vehicle const &Second, VehicleEnd const SecondEnd) { return cl::buffer_capacity(First.Couplers[FirstEnd].collision, First.collision_kind()) + cl::buffer_capacity(Second.Couplers[SecondEnd].collision, Second.collision_kind()); } // the kinetic energy of the relative motion of two vehicles closing in at the velocity [J] -double relative_energy(TMoverParameters const &First, TMoverParameters const &Second, double const Velocity) { +double relative_energy(physics::Vehicle const &First, physics::Vehicle const &Second, double const Velocity) { auto const mass{First.TotalMass * Second.TotalMass / (First.TotalMass + Second.TotalMass)}; return 0.5 * mass * Velocity * Velocity; } @@ -239,9 +239,9 @@ contact_outcome contact(definition const &Front, definition const &Back, double train.run(Seconds, {}, Dt); contact_outcome result; result.crush = front->Couplers[VehicleEnd::rear].crush + back->Couplers[VehicleEnd::front].crush; - result.energy = crush_energy(front.mover(), VehicleEnd::rear, back.mover(), VehicleEnd::front); - result.available = std::max(0.0, relative_energy(front.mover(), back.mover(), Speed * kmh) - capacity_of(front.mover(), VehicleEnd::rear, back.mover(), VehicleEnd::front)); - result.derailed = derailed(front.mover()) || derailed(back.mover()); + result.energy = crush_energy(front.physics(), VehicleEnd::rear, back.physics(), VehicleEnd::front); + result.available = std::max(0.0, relative_energy(front.physics(), back.physics(), Speed * kmh) - capacity_of(front.physics(), VehicleEnd::rear, back.physics(), VehicleEnd::front)); + result.derailed = derailed(front.physics()) || derailed(back.physics()); return result; } @@ -251,7 +251,7 @@ definition coach(double const Mass) { } // Y / Q of the leading wheel of the vehicle at the end pressed in by its coupling, as check_pushed_off() takes it -double pushed_ratio_of(TMoverParameters const &Vehicle, VehicleEnd const End, double const OtherLength, double const Radius) { +double pushed_ratio_of(physics::Vehicle const &Vehicle, VehicleEnd const End, double const OtherLength, double const Radius) { cl::pushed_vehicle pushed; pushed.mass = Vehicle.TotalMass - Vehicle.Mred; pushed.axles = Vehicle.NAxles > 0 ? Vehicle.NAxles : 4; @@ -580,9 +580,9 @@ TEST_CASE("collisions: a locomotive at its starting effort against a braked trai } train.run(30.0, line); auto &locomotive{train.add(definition::fiz("st44_v2/m62-1151"), 1, Coupling::none, 0.0, 0.0)}; - test::driven const driver{locomotive.mover(), locomotive.mover(), locomotive.mover(), [&train](double const Seconds, test::track const &Track) { train.run(Seconds, Track); }}; + test::driven const driver{locomotive.physics(), locomotive.physics(), locomotive.physics(), [&train](double const Seconds, test::track const &Track) { train.run(Seconds, Track); }}; REQUIRE(test::start_up(driver, line)); - test::release_brakes(locomotive.mover()); + test::release_brakes(locomotive.physics()); for (int i = 0; i < 3 && locomotive->DirActive <= 0; ++i) { locomotive->DirectionForward(); } @@ -592,7 +592,7 @@ TEST_CASE("collisions: a locomotive at its starting effort against a braked trai auto worst{0.0}; auto const watch = [&]() { pushed = std::max(pushed, -locomotive->Couplers[VehicleEnd::front].CForce); - worst = std::max(worst, pushed_ratio_of(empty.mover(), VehicleEnd::rear, locomotive->Dim.L, line.radius)); + worst = std::max(worst, pushed_ratio_of(empty.physics(), VehicleEnd::rear, locomotive->Dim.L, line.radius)); }; // the line contactors close at the first position, once their delay and the pressure switch let them locomotive->IncMainCtrl(1); @@ -612,7 +612,7 @@ TEST_CASE("collisions: a locomotive at its starting effort against a braked trai MESSAGE(std::format("ST44 pushing at up to {:.0f} kN, the empty 3WL at Y/Q {:.2f}, rolled {:.3f} m", pushed / 1000.0, worst, rolled)); REQUIRE(worst >= derailment::climbing_limit); CHECK(rolled < 0.5); - CHECK_FALSE(derailed(empty.mover())); + CHECK_FALSE(derailed(empty.physics())); CHECK(empty->CollisionDerail == NONE); } @@ -632,7 +632,7 @@ TEST_CASE("collisions: a locomotive running onto an empty wagon at 9 km/h doesn' for (int step = 0; step < 500; ++step) { train.step(curve); pushed = std::max(pushed, empty->Couplers[VehicleEnd::rear].CForce); - auto const ratio{pushed_ratio_of(empty.mover(), VehicleEnd::rear, locomotive->Dim.L, curve.radius)}; + auto const ratio{pushed_ratio_of(empty.physics(), VehicleEnd::rear, locomotive->Dim.L, curve.radius)}; worst = std::max(worst, ratio); over += ratio >= derailment::climbing_limit; } @@ -640,8 +640,8 @@ TEST_CASE("collisions: a locomotive running onto an empty wagon at 9 km/h doesn' empty.speed())); REQUIRE(worst >= derailment::climbing_limit); REQUIRE(over >= 5); - CHECK_FALSE(derailed(empty.mover())); - CHECK_FALSE(derailed(locomotive.mover())); + CHECK_FALSE(derailed(empty.physics())); + CHECK_FALSE(derailed(locomotive.physics())); } TEST_CASE("collisions: a train propelling an empty wagon into a braked one in a curve pushes it off as it rolls on") { @@ -668,7 +668,7 @@ TEST_CASE("collisions: a train propelling an empty wagon into a braked one in a } auto const start{empty->DistCounter}; train.run(10.0, curve); - MESSAGE(std::format("the empty 3WL: derailed {}, {}, rolled {:.2f} m", derailed(empty.mover()), empty->CollisionDerail == COLLISION_PUSHED_OFF ? "pushed off" : "not pushed off", + MESSAGE(std::format("the empty 3WL: derailed {}, {}, rolled {:.2f} m", derailed(empty.physics()), empty->CollisionDerail == COLLISION_PUSHED_OFF ? "pushed off" : "not pushed off", (empty->DistCounter - start) * 1000.0)); CHECK(empty->CollisionDerail == COLLISION_PUSHED_OFF); } @@ -685,16 +685,16 @@ TEST_CASE("collisions: a repaired vehicle has its ends rebuilt and is back on th auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, Coupling::none, 30.0, 0.5)}; train.run(3.0); REQUIRE(wagon->Couplers[VehicleEnd::rear].crush + locomotive->Couplers[VehicleEnd::front].crush > cl::override_crush); - REQUIRE((derailed(wagon.mover()) || derailed(locomotive.mover()))); + REQUIRE((derailed(wagon.physics()) || derailed(locomotive.physics()))); for (auto *vehicle : {&wagon, &locomotive}) { - auto &mover{vehicle->mover()}; - mover.repair_damage(); - CHECK(mover.DamageFlag.Empty()); - CHECK(mover.Derailed == derailment::outcome::none); - CHECK(mover.CollisionDerail == NONE); - CHECK(mover.pushed_off_monitor.distance() == 0.0); - CHECK(mover.pushed_off_monitor.time() == 0.0); - for (auto const &coupler : mover.Couplers) { + auto &physics{vehicle->physics()}; + physics.repair_damage(); + CHECK(physics.DamageFlag.Empty()); + CHECK(physics.Derailed == derailment::outcome::none); + CHECK(physics.CollisionDerail == NONE); + CHECK(physics.pushed_off_monitor.distance() == 0.0); + CHECK(physics.pushed_off_monitor.time() == 0.0); + for (auto const &coupler : physics.Couplers) { CHECK(coupler.crush == 0.0); CHECK(coupler.contact.absorbed() == 0.0); CHECK(coupler.contact.crush_work() == 0.0); @@ -766,8 +766,8 @@ TEST_CASE("collisions: the legacy rule with physics.collisions old, the crush wi train.add(definition::fiz(front)); train.add(definition::fiz(back), 0, Coupling::none, speed, 20.0); train.run(10.0); - CHECK(derailed(train[0].mover()) == (physical ? frontout_new : frontout_old)); - CHECK(derailed(train[1].mover()) == (physical ? backout_new : backout_old)); + CHECK(derailed(train[0].physics()) == (physical ? frontout_new : frontout_old)); + CHECK(derailed(train[1].physics()) == (physical ? backout_new : backout_old)); auto const crush{train[0]->Couplers[VehicleEnd::rear].crush + train[1]->Couplers[VehicleEnd::front].crush}; if (physical) { MESSAGE(name, ": crush ", crush, " m"); @@ -853,13 +853,13 @@ TEST_CASE("collisions: automatic couplers hit too fast don't catch, the ends cru auto coupled{false}; auto fast{false}; // coupled while closing in faster than the couplers catch for (int i = 0; i < 1000; ++i) { - auto const closing{moving->CollisionVelocity(VehicleEnd::front, standing.mover(), VehicleEnd::rear)}; + auto const closing{moving->CollisionVelocity(VehicleEnd::front, standing.physics(), VehicleEnd::rear)}; pair.step(); - fast = fast || (pair.coupled() && false == coupled && closing > TMoverParameters::SafeCollisionVelocity); + fast = fast || (pair.coupled() && false == coupled && closing > physics::Vehicle::SafeCollisionVelocity); coupled = coupled || pair.coupled(); } auto const crush{moving->Couplers[VehicleEnd::front].crush + standing->Couplers[VehicleEnd::rear].crush}; - MESSAGE(speed, " km/h: crush ", crush, " m, derailed ", derailed(moving.mover()), " ", derailed(standing.mover()), ", coupled later ", coupled); + MESSAGE(speed, " km/h: crush ", crush, " m, derailed ", derailed(moving.physics()), " ", derailed(standing.physics()), ", coupled later ", coupled); CHECK_FALSE(fast); CHECK(crush > 0.0); // crushed past the draw gear, the coupler is gone; short of it, the wagons may roll together again slowly @@ -869,8 +869,8 @@ TEST_CASE("collisions: automatic couplers hit too fast don't catch, the ends cru CHECK((moving->Couplers[VehicleEnd::front].broken || standing->Couplers[VehicleEnd::rear].broken)); } // the two alike: neither climbs onto the other until the crush is deep enough for both to - CHECK(derailed(moving.mover()) == derailed(standing.mover())); - CHECK(derailed(moving.mover()) == (crush > cl::override_both)); + CHECK(derailed(moving.physics()) == derailed(standing.physics())); + CHECK(derailed(moving.physics()) == (crush > cl::override_both)); } } @@ -884,8 +884,8 @@ TEST_CASE("collisions: road vehicles keep the legacy rule") { road.add(definition::fiz("road/man/nl293")); road.add(definition::fiz("road/man/nl293"), 0, Coupling::none, 40.0, 5.0); road.run(5.0); - CHECK(derailed(road[0].mover())); - CHECK(derailed(road[1].mover())); + CHECK(derailed(road[0].physics())); + CHECK(derailed(road[1].physics())); CHECK(road[0]->Couplers[VehicleEnd::rear].crush == 0.0); CHECK(road[1]->CollisionDerail == NONE); CHECK(road[0]->crush_reports + road[1]->crush_reports == 0); @@ -899,7 +899,7 @@ TEST_CASE("collisions: a vehicle off the rails by the new model stays in the cha auto &wagon{train.add(definition::fiz("430w_v2/430w"))}; auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, Coupling::none, 10.0, 0.5)}; wagon->derail_in_collision(COLLISION_PUSHED_OFF, "for the test"); - REQUIRE(derailed(wagon.mover())); + REQUIRE(derailed(wagon.physics())); auto const before{wagon->TotalMass * wagon->V + locomotive->TotalMass * locomotive->V}; // the hit is over within a second, the friction of the derailed wagon slows the pair down over it train.run(1.0); @@ -954,10 +954,10 @@ TEST_CASE("collisions: identical units built to EN 15227 at 36 km/h") { double inner; int derailed; bool higher; - } result{train[1]->Couplers[VehicleEnd::rear].crush + train[2]->Couplers[VehicleEnd::front].crush, std::max(crush_of(train[0].mover()), crush_of(train[3].mover())), 0, - derailed(train[2].mover())}; + } result{train[1]->Couplers[VehicleEnd::rear].crush + train[2]->Couplers[VehicleEnd::front].crush, std::max(crush_of(train[0].physics()), crush_of(train[3].physics())), 0, + derailed(train[2].physics())}; for (std::size_t i = 0; i < train.size(); ++i) { - result.derailed += derailed(train[i].mover()); + result.derailed += derailed(train[i].physics()); } return result; }; @@ -1204,7 +1204,7 @@ TEST_CASE("collisions: two coaches (36 t and 41.6 t) at 8 km/h don't crush, nor consist train; auto &wall{train.add(light)}; wall->Derail(END_OF_TRACK); - REQUIRE(derailed(wall.mover())); + REQUIRE(derailed(wall.physics())); auto &running{train.add(heavy, 0, Coupling::none, 5.0, gap)}; train.run(5.0); CHECK(wall->Couplers[VehicleEnd::rear].crush + running->Couplers[VehicleEnd::front].crush == 0.0); @@ -1232,9 +1232,9 @@ TEST_CASE("collisions: a locomotive pushing a standing braked train at full powe train.run(30.0, line); // the locomotive behind them, touching, driven forwards into them at full power auto &locomotive{train.add(definition::fiz(path), 1, Coupling::none, 0.0, 0.0)}; - test::driven const driver{locomotive.mover(), locomotive.mover(), locomotive.mover(), [&train](double const Seconds, test::track const &Track) { train.run(Seconds, Track); }}; + test::driven const driver{locomotive.physics(), locomotive.physics(), locomotive.physics(), [&train](double const Seconds, test::track const &Track) { train.run(Seconds, Track); }}; REQUIRE(test::start_up(driver, line)); - test::release_brakes(locomotive.mover()); + test::release_brakes(locomotive.physics()); for (int i = 0; i < 3 && locomotive->DirActive <= 0; ++i) { locomotive->DirectionForward(); } @@ -1265,8 +1265,8 @@ TEST_CASE("collisions: a locomotive pushing a standing braked train at full powe CHECK(seconds >= 55); for (std::size_t i = 0; i < train.size(); ++i) { CAPTURE(i); - CHECK(crush_of(train[i].mover()) == 0.0); - CHECK_FALSE(derailed(train[i].mover())); + CHECK(crush_of(train[i].physics()) == 0.0); + CHECK_FALSE(derailed(train[i].physics())); } } } @@ -1326,7 +1326,7 @@ struct train_damage { train_damage damage_of(consist &Train) { train_damage result; for (std::size_t i = 0; i < Train.size(); ++i) { - auto const &vehicle{Train[i].mover()}; + auto const &vehicle{Train[i].physics()}; result.crush = std::max(result.crush, crush_of(vehicle)); for (auto const end : VehicleEnds) { result.energy += vehicle.crush_curve_at(end).energy(0.0, vehicle.Couplers[end].crush); @@ -1382,7 +1382,7 @@ TEST_CASE("collisions: the cut of the speed of the legacy derailment is no hit i locomotive->Derail(reason); } train.step(); - REQUIRE(derailed(locomotive.mover())); + REQUIRE(derailed(locomotive.physics())); // the train loses the speed with it for (std::size_t i = 1; i < train.size(); ++i) { CAPTURE(i); @@ -1432,7 +1432,7 @@ TEST_CASE("collisions: the train behind a vehicle that ran off the end of the tr auto const kinetic{kinetic_of(train)}; train[0].damage_track(dtrack_norail); train.run(20.0); - REQUIRE(derailed(train[0].mover())); + REQUIRE(derailed(train[0].physics())); auto const damage{damage_of(train)}; INFO(damage.list); MESSAGE(std::format("{}: crush {:.3f} m, {:.0f} kJ of the {:.0f} kJ of the train", pushed ? "pushed" : "pulled", damage.crush, damage.energy / 1000.0, kinetic / 1000.0)); @@ -1442,7 +1442,7 @@ TEST_CASE("collisions: the train behind a vehicle that ran off the end of the tr CHECK(damage.broken == 0); for (std::size_t i = 1; i < train.size(); ++i) { CAPTURE(i); - CHECK_FALSE(derailed(train[i].mover())); + CHECK_FALSE(derailed(train[i].physics())); } } } diff --git a/tests/unit/test_commands.cpp b/tests/unit/test_commands.cpp index 2304de2d8..ac84c075e 100644 --- a/tests/unit/test_commands.cpp +++ b/tests/unit/test_commands.cpp @@ -244,13 +244,13 @@ TEST_CASE("commands: every command run on every real vehicle") { auto channels{state()}; channels.emplace_back("Done", [&done](auto const &) { return flag(done); }); test::trace trace{"commands/" + path, channels, 1, false}; - trace.sample(0.0, real.mover()); + trace.sample(0.0, real.physics()); for (std::size_t i = 0; i < commands.size(); ++i) { auto const &command{commands[i]}; trace.mark(std::format("{} {} {}", command.name, command.value1, command.value2)); auto const parsed{ParseVehicleCommand(command.name)}; done = real->RunCommand(parsed.command, command.value1, command.value2, Coupling::control, parsed.argument); - trace.sample(static_cast(i + 1), real.mover()); + trace.sample(static_cast(i + 1), real.physics()); } trace.check(); } @@ -261,7 +261,7 @@ namespace { // a switch of the cab, worked on the driven vehicle struct action { std::string name; - std::function work; + std::function work; }; // every switch sending its state to the rest of the train, each way and to each range, in the order a crew @@ -378,19 +378,19 @@ TEST_CASE("commands: every switch of the cab, sent to the next vehicle") { test::reseed_random(); vehicle driven{definition::fiz(path), 0.0, "driven", 1}; vehicle next{definition::fiz(path), 0.0, "next"}; - driven->Attach(VehicleEnd::rear, VehicleEnd::front, &next.mover(), test::consist::full_coupling, true, false); + driven->Attach(VehicleEnd::rear, VehicleEnd::front, &next.physics(), test::consist::full_coupling, true, false); auto done{false}; auto channels{state()}; for (auto const &channel : state()) { - channels.emplace_back("next." + channel.name, [&next, value = channel.value](auto const &) { return value(next.mover()); }); + channels.emplace_back("next." + channel.name, [&next, value = channel.value](auto const &) { return value(next.physics()); }); } channels.emplace_back("Done", [&done](auto const &) { return flag(done); }); test::trace trace{"switches/" + path, channels, 1, false}; - trace.sample(0.0, driven.mover()); + trace.sample(0.0, driven.physics()); for (std::size_t i = 0; i < actions.size(); ++i) { trace.mark(actions[i].name); - done = actions[i].work(driven.mover()); - trace.sample(static_cast(i + 1), driven.mover()); + done = actions[i].work(driven.physics()); + trace.sample(static_cast(i + 1), driven.physics()); } trace.check(); } @@ -422,17 +422,17 @@ TEST_CASE("commands: every switch of the cab, worked on a pair standing under th }); auto const own{channels.size()}; for (std::size_t i = 0; i < own; ++i) { - channels.emplace_back("next." + channels[i].name, [&pair, value = channels[i].value](auto const &) { return value(pair[1].mover()); }); + channels.emplace_back("next." + channels[i].name, [&pair, value = channels[i].value](auto const &) { return value(pair[1].physics()); }); } channels.emplace_back("Done", [&done](auto const &) { return flag(done); }); test::trace trace{"switches_live/" + path, channels, 1, false}; - trace.sample(0.0, pair[0].mover()); + trace.sample(0.0, pair[0].physics()); test::track const catenary{.voltage = test::catenary_3kv}; for (std::size_t i = 0; i < actions.size(); ++i) { trace.mark(actions[i].name); - done = actions[i].work(pair[0].mover()); + done = actions[i].work(pair[0].physics()); pair.run(2.0, catenary); - trace.sample(static_cast(i + 1), pair[0].mover()); + trace.sample(static_cast(i + 1), pair[0].physics()); } trace.check(); } @@ -449,8 +449,8 @@ struct train { vehicle last{definition::fiz("4e_v1/4e"), 0.0, "last"}; explicit train(CouplingSet const couplings) { - head->Attach(VehicleEnd::rear, VehicleEnd::rear, &middle.mover(), couplings, true, false); - middle->Attach(VehicleEnd::front, VehicleEnd::front, &last.mover(), couplings, true, false); + head->Attach(VehicleEnd::rear, VehicleEnd::rear, &middle.physics(), couplings, true, false); + middle->Attach(VehicleEnd::front, VehicleEnd::front, &last.physics(), couplings, true, false); } }; diff --git a/tests/unit/test_consist.cpp b/tests/unit/test_consist.cpp index da831c6a8..f3524f678 100644 --- a/tests/unit/test_consist.cpp +++ b/tests/unit/test_consist.cpp @@ -67,7 +67,7 @@ TEST_CASE("consist: every real electric unit driven whole from its front cab") { // the drive cycle marks the events in the trace it gets; the first car's carries them test::drive_cycle(test::driving(train), test::track{0.15, 0.0, test::catenary_3kv}, *traces.front()); // every unit runs off and is braked to a stop, but the EN57, which doesn't get ready (COVERAGE.md) - auto const &leading{train[0].mover()}; + auto const &leading{train[0].physics()}; CHECK((leading.DistCounter > 0.2 /* km */) != (std::string{unit.name} == "en57")); CHECK(leading.Vel < 0.5); for (auto const &trace : traces) { diff --git a/tests/unit/test_controls.cpp b/tests/unit/test_controls.cpp index 55ce1cc0e..c2f7bb9d5 100644 --- a/tests/unit/test_controls.cpp +++ b/tests/unit/test_controls.cpp @@ -69,16 +69,16 @@ bool released(scenario &Scenario, double Pressure = 0.1) { return true; } -bool open(TMoverParameters const &Vehicle, VehicleSide Side) { +bool open(physics::Vehicle const &Vehicle, VehicleSide Side) { return Vehicle.Doors.instances[Side].is_open; } // the leaf shut, whatever the step does (closed, is_closed, wants the step folded too) -bool shut(TMoverParameters const &Vehicle, VehicleSide Side) { +bool shut(physics::Vehicle const &Vehicle, VehicleSide Side) { return Vehicle.Doors.instances[Side].position <= 0.f; } -bool closed(TMoverParameters const &Vehicle, VehicleSide Side) { +bool closed(physics::Vehicle const &Vehicle, VehicleSide Side) { return Vehicle.Doors.instances[Side].is_closed; } diff --git a/tests/unit/test_coupler_physics.cpp b/tests/unit/test_coupler_physics.cpp index 60c760fb5..534104473 100644 --- a/tests/unit/test_coupler_physics.cpp +++ b/tests/unit/test_coupler_physics.cpp @@ -269,8 +269,8 @@ namespace { // couples the facing ends of the two vehicles, as the scenery does void join(vehicle &First, VehicleEnd FirstEnd, vehicle &Second, VehicleEnd SecondEnd, CouplingSet const couplings = Coupling::coupler) { - REQUIRE(First->Attach(FirstEnd, SecondEnd, &Second.mover(), couplings, true, false)); - REQUIRE(Second->Attach(SecondEnd, FirstEnd, &First.mover(), couplings, true, false)); + REQUIRE(First->Attach(FirstEnd, SecondEnd, &Second.physics(), couplings, true, false)); + REQUIRE(Second->Attach(SecondEnd, FirstEnd, &First.physics(), couplings, true, false)); } // the wagon of data/wagon.json with the given play of its screw couplings @@ -500,7 +500,7 @@ TEST_CASE("couplers: a broken coupler is repaired alone, with the one of the veh CHECK_FALSE(second->AlarmChainFlag); // repaired, not coupled: the vehicles are coupled again as usual CHECK(second->Couplers[VehicleEnd::rear].CouplingFlag == Coupling::none); - CHECK(second->Attach(VehicleEnd::rear, VehicleEnd::front, &third.mover(), Coupling::coupler, true, false)); + CHECK(second->Attach(VehicleEnd::rear, VehicleEnd::front, &third.physics(), Coupling::coupler, true, false)); } TEST_CASE("coupler physics: with couplerphysics yes, only the pairs with a vehicle covered take the physical model") { diff --git a/tests/unit/test_couplers.cpp b/tests/unit/test_couplers.cpp index c816bf19b..5cacb2c4b 100644 --- a/tests/unit/test_couplers.cpp +++ b/tests/unit/test_couplers.cpp @@ -74,9 +74,9 @@ TEST_CASE("couplers: automatic couplers catch a standing wagon hit at a walking REQUIRE(moving.speed() == doctest::Approx(10.0)); // the front of the moving wagon runs into the rear of the standing one - CHECK(moving->CollisionVelocity(VehicleEnd::front, standing.mover(), VehicleEnd::rear) == doctest::Approx(10.0)); - CHECK(moving->AutomaticCouplingSafe(VehicleEnd::front, standing.mover(), VehicleEnd::rear)); - CHECK(standing->AutomaticCouplingSafe(VehicleEnd::rear, moving.mover(), VehicleEnd::front)); + CHECK(moving->CollisionVelocity(VehicleEnd::front, standing.physics(), VehicleEnd::rear) == doctest::Approx(10.0)); + CHECK(moving->AutomaticCouplingSafe(VehicleEnd::front, standing.physics(), VehicleEnd::rear)); + CHECK(standing->AutomaticCouplingSafe(VehicleEnd::rear, moving.physics(), VehicleEnd::front)); } TEST_CASE("couplers: automatic couplers don't catch a wagon hit too fast, the wagons collide instead") { @@ -85,9 +85,9 @@ TEST_CASE("couplers: automatic couplers don't catch a wagon hit too fast, the wa auto standing{automatic_wagon(0.0, "standing")}; REQUIRE(moving.speed() == doctest::Approx(30.0)); - CHECK(moving->CollisionVelocity(VehicleEnd::front, standing.mover(), VehicleEnd::rear) > TMoverParameters::SafeCollisionVelocity); - CHECK_FALSE(moving->AutomaticCouplingSafe(VehicleEnd::front, standing.mover(), VehicleEnd::rear)); - CHECK_FALSE(standing->AutomaticCouplingSafe(VehicleEnd::rear, moving.mover(), VehicleEnd::front)); + CHECK(moving->CollisionVelocity(VehicleEnd::front, standing.physics(), VehicleEnd::rear) > physics::Vehicle::SafeCollisionVelocity); + CHECK_FALSE(moving->AutomaticCouplingSafe(VehicleEnd::front, standing.physics(), VehicleEnd::rear)); + CHECK_FALSE(standing->AutomaticCouplingSafe(VehicleEnd::rear, moving.physics(), VehicleEnd::front)); } TEST_CASE("couplers: automatic couplers catch a wagon running ahead only a little slower") { @@ -95,9 +95,9 @@ TEST_CASE("couplers: automatic couplers catch a wagon running ahead only a littl auto faster{automatic_wagon(60.0, "faster")}; auto slower{automatic_wagon(50.0, "slower")}; - CHECK(faster->CollisionVelocity(VehicleEnd::front, slower.mover(), VehicleEnd::rear) == doctest::Approx(10.0)); - CHECK(slower->CollisionVelocity(VehicleEnd::rear, faster.mover(), VehicleEnd::front) == doctest::Approx(10.0)); - CHECK(faster->AutomaticCouplingSafe(VehicleEnd::front, slower.mover(), VehicleEnd::rear)); + CHECK(faster->CollisionVelocity(VehicleEnd::front, slower.physics(), VehicleEnd::rear) == doctest::Approx(10.0)); + CHECK(slower->CollisionVelocity(VehicleEnd::rear, faster.physics(), VehicleEnd::front) == doctest::Approx(10.0)); + CHECK(faster->AutomaticCouplingSafe(VehicleEnd::front, slower.physics(), VehicleEnd::rear)); } TEST_CASE("couplers: without crash damage automatic couplers catch at any speed") { @@ -105,7 +105,7 @@ TEST_CASE("couplers: without crash damage automatic couplers catch at any speed" auto moving{automatic_wagon(30.0, "moving")}; auto standing{automatic_wagon(0.0, "standing")}; - CHECK(moving->AutomaticCouplingSafe(VehicleEnd::front, standing.mover(), VehicleEnd::rear)); + CHECK(moving->AutomaticCouplingSafe(VehicleEnd::front, standing.physics(), VehicleEnd::rear)); } // the closing speed used to treat the speed of each vehicle as a vector turned by half its heading, so for vehicles @@ -116,16 +116,16 @@ TEST_CASE("couplers: the closing speed of a rear-end collision is the difference auto slower{automatic_wagon(25.0, "slower")}; // running forwards, the front of the faster wagon hits the rear of the slower one - CHECK(faster->CollisionVelocity(VehicleEnd::front, slower.mover(), VehicleEnd::rear) == doctest::Approx(15.0)); - CHECK(slower->CollisionVelocity(VehicleEnd::rear, faster.mover(), VehicleEnd::front) == doctest::Approx(15.0)); + CHECK(faster->CollisionVelocity(VehicleEnd::front, slower.physics(), VehicleEnd::rear) == doctest::Approx(15.0)); + CHECK(slower->CollisionVelocity(VehicleEnd::rear, faster.physics(), VehicleEnd::front) == doctest::Approx(15.0)); // the wagons running ahead of each other are parting - CHECK(slower->CollisionVelocity(VehicleEnd::front, faster.mover(), VehicleEnd::rear) == doctest::Approx(-15.0)); + CHECK(slower->CollisionVelocity(VehicleEnd::front, faster.physics(), VehicleEnd::rear) == doctest::Approx(-15.0)); // backing up, the rear of the faster wagon hits the front of the slower one auto backingfaster{automatic_wagon(-40.0, "backing faster")}; auto backingslower{automatic_wagon(-25.0, "backing slower")}; - CHECK(backingfaster->CollisionVelocity(VehicleEnd::rear, backingslower.mover(), VehicleEnd::front) == doctest::Approx(15.0)); - CHECK(backingslower->CollisionVelocity(VehicleEnd::front, backingfaster.mover(), VehicleEnd::rear) == doctest::Approx(15.0)); + CHECK(backingfaster->CollisionVelocity(VehicleEnd::rear, backingslower.physics(), VehicleEnd::front) == doctest::Approx(15.0)); + CHECK(backingslower->CollisionVelocity(VehicleEnd::front, backingfaster.physics(), VehicleEnd::rear) == doctest::Approx(15.0)); } TEST_CASE("couplers: the closing speed of a head-on collision is the sum of the speeds") { @@ -134,27 +134,27 @@ TEST_CASE("couplers: the closing speed of a head-on collision is the sum of the auto second{automatic_wagon(10.0, "second")}; // both wagons run forwards, their fronts meet - CHECK(first->CollisionVelocity(VehicleEnd::front, second.mover(), VehicleEnd::front) == doctest::Approx(20.0)); - CHECK(second->CollisionVelocity(VehicleEnd::front, first.mover(), VehicleEnd::front) == doctest::Approx(20.0)); + CHECK(first->CollisionVelocity(VehicleEnd::front, second.physics(), VehicleEnd::front) == doctest::Approx(20.0)); + CHECK(second->CollisionVelocity(VehicleEnd::front, first.physics(), VehicleEnd::front) == doctest::Approx(20.0)); // 20 km/h is above the limit, the couplers don't catch (the old formula gave 14.1 km/h and coupled them) - CHECK(first->CollisionVelocity(VehicleEnd::front, second.mover(), VehicleEnd::front) > TMoverParameters::SafeCollisionVelocity); - CHECK_FALSE(first->AutomaticCouplingSafe(VehicleEnd::front, second.mover(), VehicleEnd::front)); - CHECK_FALSE(second->AutomaticCouplingSafe(VehicleEnd::front, first.mover(), VehicleEnd::front)); + CHECK(first->CollisionVelocity(VehicleEnd::front, second.physics(), VehicleEnd::front) > physics::Vehicle::SafeCollisionVelocity); + CHECK_FALSE(first->AutomaticCouplingSafe(VehicleEnd::front, second.physics(), VehicleEnd::front)); + CHECK_FALSE(second->AutomaticCouplingSafe(VehicleEnd::front, first.physics(), VehicleEnd::front)); // both wagons back up, their rears meet auto firstbacking{automatic_wagon(-10.0, "first backing")}; auto secondbacking{automatic_wagon(-10.0, "second backing")}; - CHECK(firstbacking->CollisionVelocity(VehicleEnd::rear, secondbacking.mover(), VehicleEnd::rear) == doctest::Approx(20.0)); + CHECK(firstbacking->CollisionVelocity(VehicleEnd::rear, secondbacking.physics(), VehicleEnd::rear) == doctest::Approx(20.0)); // running back to back, the wagons part - CHECK(first->CollisionVelocity(VehicleEnd::rear, second.mover(), VehicleEnd::rear) == doctest::Approx(-20.0)); - CHECK(first->AutomaticCouplingSafe(VehicleEnd::rear, second.mover(), VehicleEnd::rear)); + CHECK(first->CollisionVelocity(VehicleEnd::rear, second.physics(), VehicleEnd::rear) == doctest::Approx(-20.0)); + CHECK(first->AutomaticCouplingSafe(VehicleEnd::rear, second.physics(), VehicleEnd::rear)); // slow enough, the couplers catch auto slowfirst{automatic_wagon(5.0, "slow first")}; auto slowsecond{automatic_wagon(5.0, "slow second")}; - CHECK(slowfirst->CollisionVelocity(VehicleEnd::front, slowsecond.mover(), VehicleEnd::front) == doctest::Approx(10.0)); - CHECK(slowfirst->AutomaticCouplingSafe(VehicleEnd::front, slowsecond.mover(), VehicleEnd::front)); + CHECK(slowfirst->CollisionVelocity(VehicleEnd::front, slowsecond.physics(), VehicleEnd::front) == doctest::Approx(10.0)); + CHECK(slowfirst->AutomaticCouplingSafe(VehicleEnd::front, slowsecond.physics(), VehicleEnd::front)); } TEST_CASE("couplers: the closing speed of a hit on a standing vehicle is the speed of the moving one, whichever way it faces") { @@ -162,17 +162,17 @@ TEST_CASE("couplers: the closing speed of a hit on a standing vehicle is the spe auto standing{automatic_wagon(0.0, "standing")}; // the standing wagon faces away from the moving one - CHECK(moving->CollisionVelocity(VehicleEnd::front, standing.mover(), VehicleEnd::rear) == doctest::Approx(20.0)); - CHECK(standing->CollisionVelocity(VehicleEnd::rear, moving.mover(), VehicleEnd::front) == doctest::Approx(20.0)); + CHECK(moving->CollisionVelocity(VehicleEnd::front, standing.physics(), VehicleEnd::rear) == doctest::Approx(20.0)); + CHECK(standing->CollisionVelocity(VehicleEnd::rear, moving.physics(), VehicleEnd::front) == doctest::Approx(20.0)); // the standing wagon faces the moving one - CHECK(moving->CollisionVelocity(VehicleEnd::front, standing.mover(), VehicleEnd::front) == doctest::Approx(20.0)); - CHECK(standing->CollisionVelocity(VehicleEnd::front, moving.mover(), VehicleEnd::front) == doctest::Approx(20.0)); + CHECK(moving->CollisionVelocity(VehicleEnd::front, standing.physics(), VehicleEnd::front) == doctest::Approx(20.0)); + CHECK(standing->CollisionVelocity(VehicleEnd::front, moving.physics(), VehicleEnd::front) == doctest::Approx(20.0)); // the moving wagon backs up into the standing one auto backing{automatic_wagon(-20.0, "backing")}; - CHECK(backing->CollisionVelocity(VehicleEnd::rear, standing.mover(), VehicleEnd::front) == doctest::Approx(20.0)); - CHECK(backing->CollisionVelocity(VehicleEnd::rear, standing.mover(), VehicleEnd::rear) == doctest::Approx(20.0)); + CHECK(backing->CollisionVelocity(VehicleEnd::rear, standing.physics(), VehicleEnd::front) == doctest::Approx(20.0)); + CHECK(backing->CollisionVelocity(VehicleEnd::rear, standing.physics(), VehicleEnd::rear) == doctest::Approx(20.0)); // the moving wagon runs away from the standing one - CHECK(moving->CollisionVelocity(VehicleEnd::rear, standing.mover(), VehicleEnd::front) == doctest::Approx(-20.0)); + CHECK(moving->CollisionVelocity(VehicleEnd::rear, standing.physics(), VehicleEnd::front) == doctest::Approx(-20.0)); } // the coupling as the simulation runs it: two vehicles on a track, closing in on each other until the couplers (or @@ -183,14 +183,14 @@ TEST_CASE("couplers: automatic couplers catch right up to the safe closing speed auto standing{automatic_wagon(0.0, "standing")}; auto below{automatic_wagon(14.9, "below")}; - CHECK(below->CollisionVelocity(VehicleEnd::front, standing.mover(), VehicleEnd::rear) == doctest::Approx(14.9)); - CHECK(below->AutomaticCouplingSafe(VehicleEnd::front, standing.mover(), VehicleEnd::rear)); + CHECK(below->CollisionVelocity(VehicleEnd::front, standing.physics(), VehicleEnd::rear) == doctest::Approx(14.9)); + CHECK(below->AutomaticCouplingSafe(VehicleEnd::front, standing.physics(), VehicleEnd::rear)); auto above{automatic_wagon(15.1, "above")}; - CHECK(above->CollisionVelocity(VehicleEnd::front, standing.mover(), VehicleEnd::rear) == doctest::Approx(15.1)); - CHECK_FALSE(above->AutomaticCouplingSafe(VehicleEnd::front, standing.mover(), VehicleEnd::rear)); + CHECK(above->CollisionVelocity(VehicleEnd::front, standing.physics(), VehicleEnd::rear) == doctest::Approx(15.1)); + CHECK_FALSE(above->AutomaticCouplingSafe(VehicleEnd::front, standing.physics(), VehicleEnd::rear)); auto faster{automatic_wagon(15.5, "faster")}; - CHECK_FALSE(faster->AutomaticCouplingSafe(VehicleEnd::front, standing.mover(), VehicleEnd::rear)); + CHECK_FALSE(faster->AutomaticCouplingSafe(VehicleEnd::front, standing.physics(), VehicleEnd::rear)); } TEST_CASE("couplers: a wagon rolling slowly into a standing one couples with it") { @@ -204,7 +204,7 @@ TEST_CASE("couplers: a wagon rolling slowly into a standing one couples with it" REQUIRE(pair.coupled()); CHECK(moving->Couplers[VehicleEnd::front].CouplingFlag == (Coupling::coupler | Coupling::brakeHose)); CHECK(standing->Couplers[VehicleEnd::rear].CouplingFlag == (Coupling::coupler | Coupling::brakeHose)); - CHECK(moving->Couplers[VehicleEnd::front].Connected == &standing.mover()); + CHECK(moving->Couplers[VehicleEnd::front].Connected == &standing.physics()); CHECK_FALSE(derailed(moving)); CHECK_FALSE(derailed(standing)); // coupled, they run on together @@ -488,8 +488,8 @@ vehicle articulated_wagon(double Velocity, std::string const &Name) { // couples the facing ends of the two vehicles for good, as the scenery does for an articulated set void join(vehicle &First, VehicleEnd FirstEnd, vehicle &Second, VehicleEnd SecondEnd) { - REQUIRE(First->Attach(FirstEnd, SecondEnd, &Second.mover(), Coupling::coupler, true, false)); - REQUIRE(Second->Attach(SecondEnd, FirstEnd, &First.mover(), Coupling::coupler, true, false)); + REQUIRE(First->Attach(FirstEnd, SecondEnd, &Second.physics(), Coupling::coupler, true, false)); + REQUIRE(Second->Attach(SecondEnd, FirstEnd, &First.physics(), Coupling::coupler, true, false)); } } // namespace @@ -565,7 +565,7 @@ constexpr CouplingSet scenario_coupling{Coupling::coupler | Coupling::brakeHose // couples the rear of the first vehicle to the front of the second one the way the scenery does (forced, from the // first one only), returns the coupling the pair got CouplingSet scenario_couple(vehicle &First, vehicle &Second, CouplingSet const couplings = scenario_coupling) { - REQUIRE(First->Attach(VehicleEnd::rear, VehicleEnd::front, &Second.mover(), couplings, true, false)); + REQUIRE(First->Attach(VehicleEnd::rear, VehicleEnd::front, &Second.physics(), couplings, true, false)); CHECK(Second->Couplers[VehicleEnd::front].CouplingFlag == First->Couplers[VehicleEnd::rear].CouplingFlag); return First->Couplers[VehicleEnd::rear].CouplingFlag; } @@ -581,13 +581,13 @@ TEST_CASE("couplers: an electric and a diesel locomotive don't share their contr SUBCASE("a diesel-electric one with its own control system") { auto diesel{vehicle{definition::fiz("sm42_v1/6d1"), 0.0, "diesel"}}; REQUIRE(diesel->EngineType == TEngineType::DieselElectric); - CHECK_FALSE(electric->ControlCouplingAllowed(VehicleEnd::rear, diesel.mover(), VehicleEnd::front)); + CHECK_FALSE(electric->ControlCouplingAllowed(VehicleEnd::rear, diesel.physics(), VehicleEnd::front)); CHECK(scenario_couple(electric, diesel) == scenario_coupling.Without(Coupling::control)); } SUBCASE("a diesel-mechanical one without a control system named, either") { auto diesel{vehicle{definition::fiz("sm03_v1/sm03"), 0.0, "diesel"}}; REQUIRE(diesel->EngineType == TEngineType::DieselEngine); - CHECK_FALSE(diesel->ControlCouplingAllowed(VehicleEnd::front, electric.mover(), VehicleEnd::rear)); + CHECK_FALSE(diesel->ControlCouplingAllowed(VehicleEnd::front, electric.physics(), VehicleEnd::rear)); CHECK(scenario_couple(diesel, electric) == scenario_coupling.Without(Coupling::control)); } SUBCASE("unless both name the same control system") { @@ -603,7 +603,7 @@ TEST_CASE("couplers: an electric and a diesel locomotive don't share their contr SUBCASE("unless the check is turned off") { control_coupling_check_setting const off{false}; auto diesel{vehicle{definition::fiz("sm42_v1/6d1"), 0.0, "diesel"}}; - CHECK(electric->ControlCouplingAllowed(VehicleEnd::rear, diesel.mover(), VehicleEnd::front)); + CHECK(electric->ControlCouplingAllowed(VehicleEnd::rear, diesel.physics(), VehicleEnd::front)); CHECK(scenario_couple(electric, diesel) == scenario_coupling); } } @@ -664,8 +664,8 @@ TEST_CASE("couplers: the AI and the player get the coupling the vehicles can tak auto diesel{vehicle{definition::fiz("sm42_v1/6d1"), 0.0, "diesel"}}; auto other{vehicle{definition::fiz("ep09_v2/104e"), 0.0, "other"}}; - CHECK(electric->CompatibleCoupling(VehicleEnd::rear, diesel.mover(), VehicleEnd::front, scenario_coupling) == scenario_coupling.Without(Coupling::control)); - CHECK(electric->CompatibleCoupling(VehicleEnd::rear, other.mover(), VehicleEnd::front, scenario_coupling) == scenario_coupling); + CHECK(electric->CompatibleCoupling(VehicleEnd::rear, diesel.physics(), VehicleEnd::front, scenario_coupling) == scenario_coupling.Without(Coupling::control)); + CHECK(electric->CompatibleCoupling(VehicleEnd::rear, other.physics(), VehicleEnd::front, scenario_coupling) == scenario_coupling); // nothing to take away without the control connection asked for - CHECK(electric->CompatibleCoupling(VehicleEnd::rear, diesel.mover(), VehicleEnd::front, Coupling::coupler) == Coupling::coupler); + CHECK(electric->CompatibleCoupling(VehicleEnd::rear, diesel.physics(), VehicleEnd::front, Coupling::coupler) == Coupling::coupler); } diff --git a/tests/unit/test_couplers_trains.cpp b/tests/unit/test_couplers_trains.cpp index cdd4cd9a3..6eed2c6ac 100644 --- a/tests/unit/test_couplers_trains.cpp +++ b/tests/unit/test_couplers_trains.cpp @@ -33,9 +33,9 @@ private: TEST_CASE("couplers: coupled by hand, touching or apart, of the same kind or not") { consist train; - auto &locomotive{train.add(definition::fiz("4e_v1/4e")).mover()}; + auto &locomotive{train.add(definition::fiz("4e_v1/4e")).physics()}; // the wagon's buffers touch the locomotive's, the unit's car stands a metre away - auto &wagon{train.add(definition::fiz("3wl_v2/3wl"), 0, Coupling::none).mover()}; + auto &wagon{train.add(definition::fiz("3wl_v2/3wl"), 0, Coupling::none).physics()}; train.step(); // nothing to couple to, or nothing to couple @@ -86,8 +86,8 @@ TEST_CASE("couplers: a screw coupler uncoupled with the buffers apart, or with t }) { CAPTURE(name); consist train; - auto &locomotive{train.add(definition::fiz("4e_v1/4e")).mover()}; - auto &wagon{train.add(definition::fiz("3wl_v2/3wl"), 0, Coupling::none, 0.0, gap).mover()}; + auto &locomotive{train.add(definition::fiz("4e_v1/4e")).physics()}; + auto &wagon{train.add(definition::fiz("3wl_v2/3wl"), 0, Coupling::none, 0.0, gap).physics()}; REQUIRE(locomotive.Attach(VehicleEnd::rear, VehicleEnd::front, &wagon, couplingtype, true)); if (damaged) { locomotive.DamageFlag.Set(VehicleDamage::coupling); @@ -101,8 +101,8 @@ TEST_CASE("couplers: a screw coupler uncoupled with the buffers apart, or with t } // couplers of different kinds don't couple, unless forced consist train; - auto &locomotive{train.add(definition::fiz("4e_v1/4e")).mover()}; - auto &unit{train.add(definition::fiz("en57_v1/5bgb"), 0, Coupling::none).mover()}; + auto &locomotive{train.add(definition::fiz("4e_v1/4e")).physics()}; + auto &unit{train.add(definition::fiz("en57_v1/5bgb"), 0, Coupling::none).physics()}; train.step(); CHECK_FALSE(locomotive.Attach(VehicleEnd::rear, VehicleEnd::front, &unit, Coupling::coupler)); CHECK(locomotive.Attach(VehicleEnd::rear, VehicleEnd::front, &unit, Coupling::coupler, true)); @@ -141,8 +141,8 @@ TEST_CASE("couplers: automatic couplers coupling on contact") { TEST_CASE("couplers: a coupler broken, with its brake hose torn off") { consist train; - auto &locomotive{train.add(definition::fiz("4e_v1/4e")).mover()}; - auto &wagon{train.add(definition::fiz("3wl_v2/3wl")).mover()}; + auto &locomotive{train.add(definition::fiz("4e_v1/4e")).physics()}; + auto &wagon{train.add(definition::fiz("3wl_v2/3wl")).physics()}; REQUIRE(locomotive.Couplers[VehicleEnd::rear].Connected == &wagon); locomotive.damage_coupler(VehicleEnd::rear); CHECK(locomotive.DamageFlag.HasAll(VehicleDamage::coupling)); @@ -155,7 +155,7 @@ TEST_CASE("couplers: a coupler broken, with its brake hose torn off") { CHECK_FALSE(wagon.AlarmChainFlag); // articulated couplers don't break consist articulated; - auto &unit{articulated.add(definition::fiz("impuls_v1/31we-a_pr")).mover()}; + auto &unit{articulated.add(definition::fiz("impuls_v1/31we-a_pr")).physics()}; articulated.add(definition::fiz("impuls_v1/31we-b_pr")); unit.damage_coupler(VehicleEnd::rear); CHECK_FALSE(unit.DamageFlag.HasAll(VehicleDamage::coupling)); diff --git a/tests/unit/test_crew.cpp b/tests/unit/test_crew.cpp index 112560d61..3c1b17664 100644 --- a/tests/unit/test_crew.cpp +++ b/tests/unit/test_crew.cpp @@ -191,7 +191,7 @@ TEST_CASE("crew: a locomotive under power left by its driver stops and stays bra consist train; train.add(definition::fiz("4e_v1/4e"), 1); get_under_way(train, 20, 30.0); - auto &eu07{train[0].mover()}; + auto &eu07{train[0].physics()}; REQUIRE(train[0].speed() > 20.0); REQUIRE(eu07.MainCtrlPos > 0); REQUIRE(eu07.Mains); @@ -227,7 +227,7 @@ TEST_CASE("crew: what the AI held is let go when the driver leaves") { REQUIRE(cab->DepartureSignal); REQUIRE(cab->SandDose); - crew::secure(cab.mover(), cab.mover()); + crew::secure(cab.physics(), cab.physics()); CHECK(cab->WarningSignal == 0); CHECK_FALSE(cab->DepartureSignal); @@ -241,8 +241,8 @@ TEST_CASE("crew: a train left by its driver is braked through the whole of it") train.add(definition::fiz("11xa_v2/93a")); train.add(definition::fiz("11xa_v2/93a")); get_under_way(train, 20, 40.0); - auto &eu07{train[0].mover()}; - auto &last{train[2].mover()}; + auto &eu07{train[0].physics()}; + auto &last{train[2].physics()}; REQUIRE(train[0].speed() > 15.0); REQUIRE(last.BrakePress < 0.1); @@ -263,7 +263,7 @@ TEST_CASE("crew: a standing locomotive left by its driver is braked too") { auto driver{test::driving(train)}; REQUIRE(test::start_up(driver, line)); test::release_brakes(driver.cab); - auto &eu07{train[0].mover()}; + auto &eu07{train[0].physics()}; // the cylinders of a locomotive started up cold take their time to empty for (int i = 0; i < 180 && eu07.BrakePress >= 0.1; ++i) { test::drive(driver, line, 1.0); @@ -288,7 +288,7 @@ TEST_CASE("crew: the power an integrated handle asked for goes when the driver l impuls->eimic = 0.8; impuls->eimic_real = 0.8; - crew::secure(impuls.mover(), impuls.mover()); + crew::secure(impuls.physics(), impuls.physics()); CHECK(impuls->MainCtrlPos == impuls->MainCtrlNoPowerPos()); CHECK(impuls->eimic == 0.0); @@ -304,7 +304,7 @@ TEST_CASE("crew: a road vehicle left by its driver gets the brake the driver sto REQUIRE(bus->LocalBrakePosA == 0.0); bus->CabActivisation(); - crew::secure(bus.mover(), bus.mover()); + crew::secure(bus.physics(), bus.physics()); CHECK(bus->LocalBrakePosA == 1.0); CHECK(bus->MainCtrlPos == bus->MainCtrlNoPowerPos()); diff --git a/tests/unit/test_definition.cpp b/tests/unit/test_definition.cpp index 2f87906ae..4178da19d 100644 --- a/tests/unit/test_definition.cpp +++ b/tests/unit/test_definition.cpp @@ -59,7 +59,7 @@ TEST_CASE("definition: lines the loader skips or trims: comments, a hash anywher } crlf += c; } - TMoverParameters wagon(0.0, "wagon", "test", 0); + physics::Vehicle wagon(0.0, "wagon", "test", 0); REQUIRE(wagon.LoadFIZ_Text(crlf)); CHECK(wagon.Mass == doctest::Approx(42200.0)); CHECK(wagon.Vmax == doctest::Approx(120.0)); diff --git a/tests/unit/test_derail_motion.cpp b/tests/unit/test_derail_motion.cpp index 2256ea455..57f7f47c5 100644 --- a/tests/unit/test_derail_motion.cpp +++ b/tests/unit/test_derail_motion.cpp @@ -3,7 +3,7 @@ #include "vehicle.h" #include "vehicle/derailmotion.h" #include "physics/derailment.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "utilities/Globals.h" #include @@ -14,7 +14,7 @@ #include // a vehicle off the rails moving on the ground by itself (physics.derailment new): vehicle/derailmotion.h, and what -// the vehicle of TMoverParameters makes of it +// the vehicle of physics::Vehicle makes of it using test::definition; using test::vehicle; @@ -102,7 +102,7 @@ struct outcome { double lying_at{-1.0}; // the time it came to lie on its side, -1 never }; -// the vehicle slides as TMoverParameters drives it: its speed along the heading falls with the friction of the motion +// the vehicle slides as physics::Vehicle drives it: its speed along the heading falls with the friction of the motion // and the gravity of the grade under it, the distance of each step goes to the motion outcome slide(dm::start const &Start, dm::ground const &Ground, double const Dt = 0.01, dm::vehicle_shape const &Shape = eu07(), double const Seconds = 60.0) { dm::body body; @@ -522,7 +522,7 @@ struct car { double gap{0.0}; // of the coupling behind it }; -// the train of bodies off the track on level ground as TMoverParameters and TDynamicObject drive it: their buffers and +// the train of bodies off the track on level ground as physics::Vehicle and TDynamicObject drive it: their buffers and // couplings a spring of 2 MN/m with its damping, the longitudinal motion of each from the forces of its couplings along // its heading and the friction of its motion; the forces across turn them. Dt the step [s]; till all stop or 30 s std::vector run_train(std::vector> const &Starts, dm::vehicle_shape const &Shape, double const Dt = 0.01) { @@ -838,7 +838,7 @@ TEST_CASE("derail motion: the scatter") { namespace { -// a body off the track and the speed its vehicle goes with along its heading, as TMoverParameters keeps it +// a body off the track and the speed its vehicle goes with along its heading, as physics::Vehicle keeps it struct slider { dm::body body; double speed{0.0}; diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp index 32feec44d..b6cadad19 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -2,13 +2,13 @@ #include "doctest.h" #include "vehicle.h" #include "physics/derailment.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "utilities/Globals.h" #include // a vehicle too fast in a curve with physics.derailment of eu07.ini: the criteria of physics/derailment.h checked by -// TMoverParameters::check_derailment(), and what the vehicle comes to off the rails +// physics::Vehicle::check_derailment(), and what the vehicle comes to off the rails using test::definition; using test::vehicle; diff --git a/tests/unit/test_door_wings.cpp b/tests/unit/test_door_wings.cpp index 9eff62441..b5249a739 100644 --- a/tests/unit/test_door_wings.cpp +++ b/tests/unit/test_door_wings.cpp @@ -5,7 +5,7 @@ #include "utilities/parser.h" // the poses of the animated door wings (eu07/maszyna#512): a wing of the main model and its namesake in the low -// poly interior get the same pose, worked out once from the door position of the mover +// poly interior get the same pose, worked out once from the door position of the physics TEST_CASE("door wings: only the door animations move wings") { CHECK(door_wings::is_wing(0x010)); // TAnim::TypeSet for the doors @@ -79,7 +79,7 @@ TEST_CASE("door wings: the kinds of animation are named as DoorOpenMethod of the // in any letter case CHECK(door_wings::type_from_name("plug") == door_wings::plug_type); CHECK(door_wings::type_from_name("SHIFT") == door_wings::shift_type); - // the same numbers as TMoverParameters::door_data::type + // the same numbers as physics::Vehicle::door_data::type CHECK(door_wings::shift_type == 1); CHECK(door_wings::rotate_type == 2); CHECK(door_wings::fold_type == 3); diff --git a/tests/unit/test_drivingaid.cpp b/tests/unit/test_drivingaid.cpp index 4413384f3..4cdacb0ec 100644 --- a/tests/unit/test_drivingaid.cpp +++ b/tests/unit/test_drivingaid.cpp @@ -27,16 +27,16 @@ constexpr drivingaid::cab_controls jointctrl_cab{false, true}; constexpr drivingaid::cab_controls elf_cab{false, false}; drivingaid::readout read(vehicle &Vehicle, drivingaid::cab_controls const &Cab) { - return drivingaid::compute(drivingaid::from_movers(Vehicle.mover(), Vehicle.mover(), Cab)); + return drivingaid::compute(drivingaid::from_vehicles(Vehicle.physics(), Vehicle.physics(), Cab)); } // what the panel showed before: the throttle and brakes numbers, and the local brake always -drivingaid::readout before(TMoverParameters const &Mover) { +drivingaid::readout before(physics::Vehicle const &Physics) { drivingaid::readout result; - result.throttle_first = Mover.EIMCtrlType > 0 ? std::max(0, static_cast(100.4 * Mover.eimic_real)) : Mover.MainCtrlPos; - result.throttle_second = Mover.EIMCtrlType > 0 ? Mover.MainCtrlPos : Mover.ScndCtrlPos; - result.brake_first = Mover.UniCtrlIntegratedBrakeCtrl ? std::max(0.0, -100.0 * Mover.eimic_real) : Mover.fBrakeCtrlPos; - result.local_brake = Mover.LocalBrakePosA * LocalBrakePosNo; + result.throttle_first = Physics.EIMCtrlType > 0 ? std::max(0, static_cast(100.4 * Physics.eimic_real)) : Physics.MainCtrlPos; + result.throttle_second = Physics.EIMCtrlType > 0 ? Physics.MainCtrlPos : Physics.ScndCtrlPos; + result.brake_first = Physics.UniCtrlIntegratedBrakeCtrl ? std::max(0.0, -100.0 * Physics.eimic_real) : Physics.fBrakeCtrlPos; + result.local_brake = Physics.LocalBrakePosA * LocalBrakePosNo; return result; } @@ -165,7 +165,7 @@ TEST_CASE("driving aid: every real vehicle with a local brake control shows the real->LocalBrakePosA = localbrake; real->eimic_real = eimic; auto const now{read(real, lever_cab)}; - auto const was{before(real.mover())}; + auto const was{before(real.physics())}; CHECK(now.throttle_first == was.throttle_first); CHECK(now.throttle_second == was.throttle_second); CHECK(now.brake_first == doctest::Approx(was.brake_first)); diff --git a/tests/unit/test_dynamic_brake_diesel.cpp b/tests/unit/test_dynamic_brake_diesel.cpp index ddebba682..085d77a9d 100644 --- a/tests/unit/test_dynamic_brake_diesel.cpp +++ b/tests/unit/test_dynamic_brake_diesel.cpp @@ -51,15 +51,15 @@ definition st44_braking() { } // the force of the brakes above at full effort at the speed of the vehicle -double br285_limit(TMoverParameters const &Vehicle) { +double br285_limit(physics::Vehicle const &Vehicle) { return std::min(150000.0, 2000000.0 / std::abs(Vehicle.V)) * std::clamp((Vehicle.Vel - 2.0) / 4.0, 0.0, 1.0); } -double st44_limit(TMoverParameters const &Vehicle) { +double st44_limit(physics::Vehicle const &Vehicle) { return std::min(120000.0, 1200000.0 / std::abs(Vehicle.V)) * std::clamp(Vehicle.Vel / 40.0, 0.0, 1.0); } // the controller of the BR285 down to the given position, a step a time -void controller_to(TMoverParameters &Locomotive, int Position) { +void controller_to(physics::Vehicle &Locomotive, int Position) { while (Locomotive.MainCtrlPos > Position && Locomotive.DecMainCtrl(1)) {} while (Locomotive.MainCtrlPos < Position && Locomotive.IncMainCtrl(1)) {} } @@ -71,7 +71,7 @@ TEST_CASE("diesel-electric dynamic brake: none without its definition") { for (auto const &path : test::real_vehicles()) { CAPTURE(path); test::vehicle vehicle{definition::fiz(path)}; - CHECK(vehicle->DEDynamicBrake.source == TMoverParameters::diesel_electric_dynamic_brake::control::none); + CHECK(vehicle->DEDynamicBrake.source == physics::Vehicle::diesel_electric_dynamic_brake::control::none); } scenario scenario{"dynamic brake/diesel electric/br285 without", motion() + traction() + dynamic_brake()}; scenario.add("br285_v1/br285", 1); @@ -99,7 +99,7 @@ TEST_CASE("diesel-electric dynamic brake: the BR285's controller") { scenario scenario{"dynamic brake/diesel electric/br285", motion() + traction() + brakes() + dynamic_brake()}; scenario.train().add(br285_braking(), 1); auto &locomotive{scenario.cab()}; - REQUIRE(locomotive.DEDynamicBrake.source == TMoverParameters::diesel_electric_dynamic_brake::control::controller); + REQUIRE(locomotive.DEDynamicBrake.source == physics::Vehicle::diesel_electric_dynamic_brake::control::controller); CHECK(locomotive.DEDynamicBrake.max_force == doctest::Approx(150000.0)); CHECK(locomotive.DEDynamicBrake.max_power == doctest::Approx(2000000.0)); REQUIRE(scenario.start_up()); @@ -164,7 +164,7 @@ TEST_CASE("diesel-electric dynamic brake: a resistor brake with its own lever") scenario scenario{"dynamic brake/diesel electric/st44 lever", motion() + traction() + brakes() + dynamic_brake()}; scenario.train().add(st44_braking(), 1); auto &locomotive{scenario.cab()}; - REQUIRE(locomotive.DEDynamicBrake.source == TMoverParameters::diesel_electric_dynamic_brake::control::lever); + REQUIRE(locomotive.DEDynamicBrake.source == physics::Vehicle::diesel_electric_dynamic_brake::control::lever); CHECK(locomotive.SplitEDPneumaticBrake); CHECK(locomotive.DynamicBrakeCtrlPosNo == 8); REQUIRE(scenario.start_up()); diff --git a/tests/unit/test_elf_controller.cpp b/tests/unit/test_elf_controller.cpp index d099c3303..945eee844 100644 --- a/tests/unit/test_elf_controller.cpp +++ b/tests/unit/test_elf_controller.cpp @@ -72,8 +72,8 @@ struct elf { cab().UniversalBrakeButton(0, 0); wait(30.0); } - TMoverParameters &cab() { return unit[0].mover(); } - TMoverParameters &car(std::size_t Index) { return unit[Index].mover(); } + physics::Vehicle &cab() { return unit[0].physics(); } + physics::Vehicle &car(std::size_t Index) { return unit[Index].physics(); } // the driver moves the controller notch by notch, which the cab sends on to the coupled vehicles void set_controller(int Position) { while (cab().MainCtrlPos < Position && cab().IncMainCtrl(1)) { @@ -94,62 +94,62 @@ TEST_CASE("elf controller: without EIMCtrlMainEmergency the positions stay as th elf unit{false}; REQUIRE(unit.ready); REQUIRE(unit.charged); - auto &mover{unit.cab()}; - CHECK_FALSE(mover.EIMCtrlMainEmergency); - CHECK(mover.EIMCtrlEmergencyPositions() == 0); - CHECK(mover.MainCtrlPosNo == 4); - CHECK(mover.MainCtrlNoPowerPos() == 3); - CHECK(mover.MainCtrlPos == 3); + auto &physics{unit.cab()}; + CHECK_FALSE(physics.EIMCtrlMainEmergency); + CHECK(physics.EIMCtrlEmergencyPositions() == 0); + CHECK(physics.MainCtrlPosNo == 4); + CHECK(physics.MainCtrlNoPowerPos() == 3); + CHECK(physics.MainCtrlPos == 3); // the lowest position brakes fully, without emptying the pipe - mover.MainCtrlPos = 0; - CHECK_FALSE(mover.IsMainCtrlEmergencyPos()); + physics.MainCtrlPos = 0; + CHECK_FALSE(physics.IsMainCtrlEmergencyPos()); unit.wait(10.0); - CHECK(mover.eimic == doctest::Approx(-1.0)); - CHECK(mover.PipePress > 4.5); + CHECK(physics.eimic == doctest::Approx(-1.0)); + CHECK(physics.PipePress > 4.5); } TEST_CASE("elf controller: EIMCtrlMainEmergency shifts the positions up by the emergency brake one") { elf unit{true}; REQUIRE(unit.ready); REQUIRE(unit.charged); - auto &mover{unit.cab()}; - CHECK(mover.EIMCtrlMainEmergency); - CHECK(mover.EIMCtrlEmergencyPositions() == 1); - CHECK(mover.MainCtrlPosNo == 5); - CHECK(mover.MainCtrlNoPowerPos() == 4); - CHECK(mover.MainCtrlPos == 4); - CHECK_FALSE(mover.IsMainCtrlEmergencyPos()); + auto &physics{unit.cab()}; + CHECK(physics.EIMCtrlMainEmergency); + CHECK(physics.EIMCtrlEmergencyPositions() == 1); + CHECK(physics.MainCtrlPosNo == 5); + CHECK(physics.MainCtrlNoPowerPos() == 4); + CHECK(physics.MainCtrlPos == 4); + CHECK_FALSE(physics.IsMainCtrlEmergencyPos()); SUBCASE("the neutral position neither drives nor brakes") { unit.wait(5.0); - CHECK(mover.eimic == doctest::Approx(0.0)); + CHECK(physics.eimic == doctest::Approx(0.0)); } SUBCASE("the full braking position, formerly 0, brakes fully without emptying the pipe") { - mover.MainCtrlPos = 1; + physics.MainCtrlPos = 1; unit.wait(10.0); - CHECK(mover.eimic == doctest::Approx(-1.0)); - CHECK(mover.PipePress > 4.5); + CHECK(physics.eimic == doctest::Approx(-1.0)); + CHECK(physics.PipePress > 4.5); } SUBCASE("the braking position, formerly 1, ramps the braking up") { - mover.MainCtrlPos = 2; + physics.MainCtrlPos = 2; unit.wait(1.0); - CHECK(mover.eimic < 0.0); - CHECK(mover.eimic > -1.0); - CHECK(mover.PipePress > 4.5); + CHECK(physics.eimic < 0.0); + CHECK(physics.eimic > -1.0); + CHECK(physics.PipePress > 4.5); } SUBCASE("the emergency brake position brakes fully at once and empties the pipe") { - mover.MainCtrlPos = 0; - CHECK(mover.IsMainCtrlEmergencyPos()); + physics.MainCtrlPos = 0; + CHECK(physics.IsMainCtrlEmergencyPos()); // a single step of the physics unit.unit.step(unit.line); - CHECK(mover.eimic == doctest::Approx(-1.0)); + CHECK(physics.eimic == doctest::Approx(-1.0)); unit.wait(10.0); - CHECK(mover.PipePress < 0.5); - CHECK(mover.BrakePress > 1.0); + CHECK(physics.PipePress < 0.5); + CHECK(physics.BrakePress > 1.0); // out of it the pipe charges again - mover.MainCtrlPos = mover.MainCtrlNoPowerPos(); - CHECK_FALSE(mover.IsMainCtrlEmergencyPos()); + physics.MainCtrlPos = physics.MainCtrlNoPowerPos(); + CHECK_FALSE(physics.IsMainCtrlEmergencyPos()); unit.recharge(); - CHECK(mover.PipePress > 4.5); + CHECK(physics.PipePress > 4.5); } } @@ -171,18 +171,18 @@ TEST_CASE("elf controller: the reverser works at the neutral shifted by EIMCtrlM // the key added to the old files, DirChangeMaxPos=3 in them elf unit{{data::emergency_old_layout}}; REQUIRE(unit.ready); - auto &mover{unit.cab()}; - REQUIRE(mover.MainCtrlPos == mover.MainCtrlNoPowerPos()); - REQUIRE(mover.DirActive == 1); - CHECK(mover.DirectionBackward()); - CHECK(mover.DirActive == 0); - CHECK(mover.DirectionForward()); - CHECK(mover.DirActive == 1); + auto &physics{unit.cab()}; + REQUIRE(physics.MainCtrlPos == physics.MainCtrlNoPowerPos()); + REQUIRE(physics.DirActive == 1); + CHECK(physics.DirectionBackward()); + CHECK(physics.DirActive == 0); + CHECK(physics.DirectionForward()); + CHECK(physics.DirActive == 1); // not in the power position - unit.set_controller(mover.MainCtrlNoPowerPos() + 1); - REQUIRE(mover.MainCtrlPos == 5); - CHECK_FALSE(mover.DirectionBackward()); - CHECK(mover.DirActive == 1); + unit.set_controller(physics.MainCtrlNoPowerPos() + 1); + REQUIRE(physics.MainCtrlPos == 5); + CHECK_FALSE(physics.DirectionBackward()); + CHECK(physics.DirActive == 1); } TEST_CASE("elf controller: the emergency brake position vents the pipe only from the vehicle driven from") { @@ -264,7 +264,7 @@ TEST_CASE("elf controller: EIMCtrlMainEmergency leaves the other controllers alo // the holding brake of the Elf (SBD) lets go only once power has been demanded for SBDReleaseDelay (eu07/maszyna#556): // the release waits the initial delay of the controller (IniCDelay) instead of going at the first percent of the // demand. TDynamicObject::Update() works the holding brake out, its MED isn't in the tests, so they do here what it -// does with it: TMoverParameters::UpdateStopBrakeRelease() of the cab with its demand after every step and, where the +// does with it: physics::Vehicle::UpdateStopBrakeRelease() of the cab with its demand after every step and, where the // brake matters, the brake's share of every car on its cylinders (LocalBrakePosAEIM) namespace { diff --git a/tests/unit/test_engine_start.cpp b/tests/unit/test_engine_start.cpp index a7aeff790..cf9aa4e42 100644 --- a/tests/unit/test_engine_start.cpp +++ b/tests/unit/test_engine_start.cpp @@ -27,7 +27,7 @@ definition sn61(bool const Joint = true) { // pressure built up, and the controller at the first position giving the engines fuel, which a mechanical diesel // starts at: everything but the engines ready to start void prepare(consist &Train) { - auto &cab{Train[0].mover()}; + auto &cab{Train[0].physics()}; cab.BatterySwitch(true); cab.CabActivisation(); cab.OilPumpSwitch(true); @@ -38,7 +38,7 @@ void prepare(consist &Train) { Train.run(20.0); } -bool running(TMoverParameters const &Vehicle) { +bool running(physics::Vehicle const &Vehicle) { return Vehicle.Mains && Vehicle.enrot > 0.5 * Vehicle.diesel.minRevolutions; } @@ -51,7 +51,7 @@ int steps(double const Seconds) { } // the switch of Engine held closed for Seconds, then let go, in steps of the train -void hold(consist &Train, engine_start::remote_switch &Switch, TMoverParameters *Engine, double const Seconds, bool const Closesonrelease = false) { +void hold(consist &Train, engine_start::remote_switch &Switch, physics::Vehicle *Engine, double const Seconds, bool const Closesonrelease = false) { for (auto step = 0; step < steps(Seconds); ++step) { Switch.update(Engine, true, false, dt, Closesonrelease); Train.step({}, dt); @@ -63,8 +63,8 @@ void hold(consist &Train, engine_start::remote_switch &Switch, TMoverParameters TEST_CASE("engine start: the joint start is the default, and JointEngineStart=No keeps the cab's switch to its vehicle") { consist train; - auto const &joint{train.add(sn61(), 1).mover()}; - auto const &separate{train.add(sn61(false)).mover()}; + auto const &joint{train.add(sn61(), 1).physics()}; + auto const &separate{train.add(sn61(false)).physics()}; CHECK(joint.JointEngineStart); CHECK_FALSE(separate.JointEngineStart); CHECK(joint.MainSwitchRange() == range_t::consist); @@ -73,9 +73,9 @@ TEST_CASE("engine start: the joint start is the default, and JointEngineStart=No TEST_CASE("engine start: the vehicles in multiple, counted from the cab's own one, those behind the cab first") { consist train; - auto &first{train.add(sn61(), 1).mover()}; - auto &second{train.add(sn61()).mover()}; - auto &third{train.add(sn61()).mover()}; + auto &first{train.add(sn61(), 1).physics()}; + auto &second{train.add(sn61()).physics()}; + auto &third{train.add(sn61()).physics()}; CHECK(engine_start::engine(first, first, 1) == &first); CHECK(engine_start::engine(first, first, 2) == &second); CHECK(engine_start::engine(first, first, 3) == &third); @@ -96,10 +96,10 @@ TEST_CASE("engine start: the vehicles in multiple, counted from the cab's own on TEST_CASE("engine start: only the vehicles with an engine and under control through the cable count") { consist train; - auto &first{train.add(sn61(), 1).mover()}; + auto &first{train.add(sn61(), 1).physics()}; // a vehicle without an engine between the railcars is passed over - auto &trailer{train.add(definition::fiz("ed72_v1/5bs-ra")).mover()}; - auto &second{train.add(sn61()).mover()}; + auto &trailer{train.add(definition::fiz("ed72_v1/5bs-ra")).physics()}; + auto &second{train.add(sn61()).physics()}; REQUIRE(trailer.Power < 0.01); CHECK(engine_start::engine(first, first, 2) == &second); // the vehicle with the cab doesn't drive itself: its engine is in the vehicle it controls, which isn't counted twice @@ -110,15 +110,15 @@ TEST_CASE("engine start: only the vehicles with an engine and under control thro // coupled without the control cable, the other railcar isn't under the cab's control consist apart; - auto &alone{apart.add(sn61(), 1).mover()}; + auto &alone{apart.add(sn61(), 1).physics()}; apart.add(sn61(), 0, Coupling::coupler | Coupling::brakeHose); CHECK(engine_start::engine(alone, alone, 2) == nullptr); } TEST_CASE("engine start: by default the cab's switch starts and stops the engines of all the vehicles in multiple") { consist train; - auto &first{train.add(sn61(), 1).mover()}; - auto const &second{train.add(sn61()).mover()}; + auto &first{train.add(sn61(), 1).physics()}; + auto const &second{train.add(sn61()).physics()}; prepare(train); REQUIRE_FALSE(first.Mains); REQUIRE_FALSE(second.Mains); @@ -134,9 +134,9 @@ TEST_CASE("engine start: by default the cab's switch starts and stops the engine TEST_CASE("engine start: with JointEngineStart=No each engine has its own switch") { consist train; - auto &first{train.add(sn61(false), 1).mover()}; - auto &second{train.add(sn61(false)).mover()}; - auto &third{train.add(sn61(false)).mover()}; + auto &first{train.add(sn61(false), 1).physics()}; + auto &second{train.add(sn61(false)).physics()}; + auto &third{train.add(sn61(false)).physics()}; prepare(train); // the cab's own switch starts its own engine only first.MainSwitch(true, first.MainSwitchRange()); @@ -177,7 +177,7 @@ TEST_CASE("engine start: with JointEngineStart=No each engine has its own switch TEST_CASE("engine start: the switch of another vehicle is held for the vehicle's delay, with the vehicle ready") { consist train; train.add(sn61(false).set("Cntrl", "IniCDelay", "2.0"), 1); - auto &second{train.add(sn61(false).set("Cntrl", "IniCDelay", "2.0")).mover()}; + auto &second{train.add(sn61(false).set("Cntrl", "IniCDelay", "2.0")).physics()}; REQUIRE(second.InitialCtrlDelay == doctest::Approx(2.0)); engine_start::remote_switch switchb; @@ -207,7 +207,7 @@ TEST_CASE("engine start: the switch of another vehicle is held for the vehicle's TEST_CASE("engine start: a switch closing on release, as an electric locomotive's impulse switch, waits to be let go") { consist train; train.add(sn61(false), 1); - auto &second{train.add(sn61(false).set("Cntrl", "IniCDelay", "1.0")).mover()}; + auto &second{train.add(sn61(false).set("Cntrl", "IniCDelay", "1.0")).physics()}; prepare(train); engine_start::remote_switch switchb; // held past the delay, the circuit stays open while the switch is held @@ -233,8 +233,8 @@ TEST_CASE("engine start: an engine stopping on its own stops the others only whe for (auto const joint : {true, false}) { CAPTURE(joint); consist train; - auto &first{train.add(sn61(joint), 1).mover()}; - auto const &second{train.add(sn61(joint)).mover()}; + auto &first{train.add(sn61(joint), 1).physics()}; + auto const &second{train.add(sn61(joint)).physics()}; prepare(train); engine_start::remote_switch switchb; first.MainSwitch(true, first.MainSwitchRange()); @@ -259,9 +259,9 @@ TEST_CASE("engine start: an engine stopped from its own switch doesn't stop the consist train; // the middle railcar keeps the joint start, as a .fiz without the key does. what a vehicle without the cab relays // goes on away from the cab, so it's the third one that would stop - auto &first{train.add(sn61(false), 1).mover()}; - auto &second{train.add(sn61()).mover()}; - auto &third{train.add(sn61(false)).mover()}; + auto &first{train.add(sn61(false), 1).physics()}; + auto &second{train.add(sn61()).physics()}; + auto &third{train.add(sn61(false)).physics()}; prepare(train); engine_start::remote_switch switchb; engine_start::remote_switch switchc; @@ -284,8 +284,8 @@ TEST_CASE("engine start: an engine stopped from its own switch doesn't stop the TEST_CASE("engine start: the stopped engine of the cab's vehicle doesn't stop the one started from its switch") { consist train; // the cab's railcar keeps the joint start, its engine stopped - auto &first{train.add(sn61(), 1).mover()}; - auto &second{train.add(sn61(false)).mover()}; + auto &first{train.add(sn61(), 1).physics()}; + auto &second{train.add(sn61(false)).physics()}; prepare(train); REQUIRE_FALSE(first.Mains); // mainb_on diff --git a/tests/unit/test_est3al2_relay.cpp b/tests/unit/test_est3al2_relay.cpp index be4adf244..5af02f313 100644 --- a/tests/unit/test_est3al2_relay.cpp +++ b/tests/unit/test_est3al2_relay.cpp @@ -68,7 +68,7 @@ times measure(int const Delay, int const Lever) { if (wagon->BrakeDelayFlag != Delay) { REQUIRE(wagon->BrakeDelaySwitch(Delay)); } - // an empty wagon starts with the lever at empty (TMoverParameters::CheckLocomotiveParameters) + // an empty wagon starts with the lever at empty (physics::Vehicle::CheckLocomotiveParameters) REQUIRE(wagon->LoadFlag == 1); while (wagon->LoadFlag < Lever) { REQUIRE(wagon->IncBrakeMult()); diff --git a/tests/unit/test_fcfuh_default.cpp b/tests/unit/test_fcfuh_default.cpp index f52a7cdd5..bd5120915 100644 --- a/tests/unit/test_fcfuh_default.cpp +++ b/tests/unit/test_fcfuh_default.cpp @@ -19,7 +19,7 @@ using test::vehicle; namespace { -// a figure read from a line the way TMoverParameters::LoadFIZ_EngineInductionMotor() reads fcfu +// a figure read from a line the way physics::Vehicle::LoadFIZ_EngineInductionMotor() reads fcfu double read_fcfu(std::string const &Text) { double fcfu{0.0}; extract_value(fcfu, "fcfu", "fcfu=" + Text, ""); diff --git a/tests/unit/test_feed_pipe.cpp b/tests/unit/test_feed_pipe.cpp index 2164d2784..21ff98e4d 100644 --- a/tests/unit/test_feed_pipe.cpp +++ b/tests/unit/test_feed_pipe.cpp @@ -1,12 +1,12 @@ #include "stdafx.h" #include "doctest.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "physics/brakes.h" #include "consist.h" #include "vehicle.h" -// the air exchange through the main reservoir hoses between the vehicles of a train (TMoverParameters::UpdatePipeCouplers()). +// the air exchange through the main reservoir hoses between the vehicles of a train (physics::Vehicle::UpdatePipeCouplers()). // taken in one explicit step of 0.01 s, a hose carried about 1.5 times the air which evens out the pipes on its ends, // and the vehicles' own main reservoirs fed the pipe in the same step: the pipes of the middle vehicles of a multiple // unit, or of locomotives in multiple traction, kept jumping 0.8 bar to and fro between the steps, with the main @@ -66,18 +66,18 @@ evening_out even_out(Builder Train, int const Count, double const Pressure, doub test::consist train; Train(train, Count); for (std::size_t i = 0; i < train.size(); ++i) { - auto &mover{train[i].mover()}; - REQUIRE(mover.VeselVolume > 0.0); + auto &physics{train[i].physics()}; + REQUIRE(physics.VeselVolume > 0.0); auto const pressure{i == 0 ? Pressure : Pressure - 1.0}; - mover.CompressedVolume = pressure * mover.VeselVolume; - mover.Compressor = pressure; - mover.Pipe2->CreatePress(pressure); - mover.Pipe2->Act(); - mover.ScndPipePress = pressure; + physics.CompressedVolume = pressure * physics.VeselVolume; + physics.Compressor = pressure; + physics.Pipe2->CreatePress(pressure); + physics.Pipe2->Act(); + physics.ScndPipePress = pressure; } evening_out result; - auto const &first{train[0].mover()}; - auto const &last{train[train.size() - 1].mover()}; + auto const &first{train[0].physics()}; + auto const &last{train[train.size() - 1].physics()}; std::vector previous(train.size()); std::vector change(train.size()); for (std::size_t i = 0; i < train.size(); ++i) { @@ -112,14 +112,14 @@ double charging_time(Builder Train, int const Count, double const Pressure, doub Train(train, Count); train[0].hold_main_reservoir(Pressure); for (std::size_t i = 1; i < train.size(); ++i) { - auto &mover{train[i].mover()}; - REQUIRE(mover.VeselVolume == 0.0); - mover.Pipe2->CreatePress(0.0); - mover.Pipe2->Act(); - mover.ScndPipePress = 0.0; + auto &physics{train[i].physics()}; + REQUIRE(physics.VeselVolume == 0.0); + physics.Pipe2->CreatePress(0.0); + physics.Pipe2->Act(); + physics.ScndPipePress = 0.0; } - auto const &first{train[0].mover()}; - auto const &last{train[train.size() - 1].mover()}; + auto const &first{train[0].physics()}; + auto const &last{train[train.size() - 1].physics()}; auto time{0.0}; while ((last.ScndPipePress < 1.0 || std::abs(last.ScndPipePress - first.ScndPipePress) > 0.2) && time < 60.0) { train.step({}, Dt); diff --git a/tests/unit/test_figures.cpp b/tests/unit/test_figures.cpp index c8b575d50..d40bc158b 100644 --- a/tests/unit/test_figures.cpp +++ b/tests/unit/test_figures.cpp @@ -15,24 +15,24 @@ using test::vehicle; TEST_CASE("figures: a run split into parts by the events, each from the last step of the part before") { vehicle eu07{definition::fiz("4e_v1/4e")}; test::figures figures; - auto &mover{eu07.mover()}; - mover.V = 10.0; - mover.PipePress = 5.0; - figures.sample(0.0, mover); + auto &physics{eu07.physics()}; + physics.V = 10.0; + physics.PipePress = 5.0; + figures.sample(0.0, physics); figures.mark("brake"); figures.mark("hard"); for (int i = 1; i <= 10; ++i) { - mover.V = 10.0 - i; - mover.DistCounter += 0.005; - mover.PipePress = 3.5; - mover.BrakePress = 0.4 * i; - figures.sample(i, mover); + physics.V = 10.0 - i; + physics.DistCounter += 0.005; + physics.PipePress = 3.5; + physics.BrakePress = 0.4 * i; + figures.sample(i, physics); } figures.mark("release"); - mover.PipePress = 4.0; - figures.sample(11.0, mover); - mover.PipePress = 5.0; - figures.sample(12.0, mover); + physics.PipePress = 4.0; + figures.sample(11.0, physics); + physics.PipePress = 5.0; + figures.sample(12.0, physics); auto const lines{figures.lines()}; auto const has{[&lines](std::string const &Line) { return std::ranges::find(lines, Line) != lines.end(); }}; diff --git a/tests/unit/test_fiz.cpp b/tests/unit/test_fiz.cpp index f25632dee..3e1b64760 100644 --- a/tests/unit/test_fiz.cpp +++ b/tests/unit/test_fiz.cpp @@ -23,7 +23,7 @@ TEST_CASE("fiz: every real vehicle loads and keeps its parameters") { test::reseed_random(); vehicle real{definition::fiz(path)}; test::trace trace{"fiz/" + path, test::channels::parameters(), 1}; - trace.sample(0.0, real.mover()); + trace.sample(0.0, real.physics()); // what every vehicle has, the rest of its parameters are in the golden trace CHECK(real->Mass > 0.0); CHECK(real->TotalMass >= real->Mass); diff --git a/tests/unit/test_gauge_scale.cpp b/tests/unit/test_gauge_scale.cpp index 04fa645bb..9e59e5114 100644 --- a/tests/unit/test_gauge_scale.cpp +++ b/tests/unit/test_gauge_scale.cpp @@ -84,7 +84,7 @@ TEST_CASE("main ctrl act: the marker of a diesel locomotive with a scaletable: f for (auto const *path : {"st44_v2/m62-1151", "sm42_v1/6d1", "su45_v2/301d"}) { CAPTURE(path); consist train; - auto &locomotive{train.add(definition::fiz(path), 1).mover()}; + auto &locomotive{train.add(definition::fiz(path), 1).physics()}; REQUIRE((locomotive.EngineType == TEngineType::DieselElectric || locomotive.EngineType == TEngineType::DieselEngine)); REQUIRE(locomotive.EIMCtrlType == 0); locomotive.MainCtrlPos = 5; @@ -101,7 +101,7 @@ TEST_CASE("main ctrl act: the marker of a diesel locomotive without a scaletable for (auto const *path : {"st44_v2/m62-1151", "sm42_v1/6d1", "su45_v2/301d"}) { CAPTURE(path); consist train; - auto &locomotive{train.add(definition::fiz(path), 1).mover()}; + auto &locomotive{train.add(definition::fiz(path), 1).physics()}; REQUIRE(locomotive.EIMCtrlType == 0); locomotive.MainCtrlPos = 5; locomotive.ScndCtrlPos = 1; @@ -117,7 +117,7 @@ TEST_CASE("main ctrl act: the marker of an electric locomotive shows its actual for (auto const scaletable : {false, true}) { CAPTURE(scaletable); consist train; - auto &locomotive{train.add(definition::fiz("et22_v3/201e-w"), 1).mover()}; + auto &locomotive{train.add(definition::fiz("et22_v3/201e-w"), 1).physics()}; locomotive.MainCtrlPos = 10; locomotive.MainCtrlActualPos = 3; locomotive.ScndCtrlPos = 2; diff --git a/tests/unit/test_genset.cpp b/tests/unit/test_genset.cpp index be52eab9a..cc9172a53 100644 --- a/tests/unit/test_genset.cpp +++ b/tests/unit/test_genset.cpp @@ -14,7 +14,7 @@ using test::consist; using test::definition; using test::track; using test::vehicle; -using traction_mode = TMoverParameters::traction_mode; +using traction_mode = physics::Vehicle::traction_mode; namespace { @@ -40,7 +40,7 @@ track const no_wire{0.15, 0.0, 0.0}; track const wire{0.15, 0.0, test::catenary_3kv}; // the battery, the cab and a direction, as the driver begins -void wake(TMoverParameters &Cab) { +void wake(physics::Vehicle &Cab) { Cab.BatterySwitch(true); Cab.CabActivisation(); for (int i = 0; i < 3 && Cab.DirActive <= 0; ++i) { @@ -49,7 +49,7 @@ void wake(TMoverParameters &Cab) { } // the vigilance and the cab signalling acknowledged, as test::drive() does once a second -void attend(TMoverParameters &Cab) { +void attend(physics::Vehicle &Cab) { if (Cab.SecuritySystem.is_cabsignal_blinking() && Cab.SecuritySystem.has_separate_acknowledge()) { Cab.SecuritySystem.cabsignal_reset(); } @@ -63,7 +63,7 @@ void run(vehicle &Vehicle, double const Seconds, track const &Track = no_wire) { } // the line breaker closed, which it does only with the controller at zero, and after the relays are reset -void close_line_breaker(TMoverParameters &Cab) { +void close_line_breaker(physics::Vehicle &Cab) { while (Cab.DecMainCtrl(2)) { // down to zero } @@ -75,7 +75,7 @@ void close_line_breaker(TMoverParameters &Cab) { // genset, the genset started, the line breaker closed once it runs, the converter and the compressor, the air, the // brakes released. one round of the driver's actions a second; returns whether the vehicle got ready bool start_on_genset(vehicle &Vehicle, track const &Track = no_wire, double const Seconds = 300.0) { - auto &cab{Vehicle.mover()}; + auto &cab{Vehicle.physics()}; for (auto second = 0; second < Seconds; ++second) { wake(cab); cab.TractionModeSwitch(traction_mode::genset); @@ -103,21 +103,21 @@ bool start_on_genset(vehicle &Vehicle, track const &Track = no_wire, double cons } // the main controller to its full power position -void notch_up(TMoverParameters &Cab) { +void notch_up(physics::Vehicle &Cab) { for (int i = 0; i < 60 && false == Cab.IsMainCtrlMaxPowerPos(); ++i) { Cab.IncMainCtrl(1); } } // the power at the wheels [kW] -double wheel_power(TMoverParameters const &Vehicle) { +double wheel_power(physics::Vehicle const &Vehicle) { return std::abs(Vehicle.Ft * Vehicle.V) / 1000.0; } // one step of 0.01 s, acknowledging the vigilance once a second void step(vehicle &Vehicle, long const Step, track const &Track = no_wire) { if (Step % 100 == 0) { - attend(Vehicle.mover()); + attend(Vehicle.physics()); } Vehicle.step(Track); } @@ -126,7 +126,7 @@ void step(vehicle &Vehicle, long const Step, track const &Track = no_wire) { TEST_CASE("genset: a vehicle without the keys has none and stays on the catenary") { vehicle dragon6{dragon(), 0.0, "plain", 1}; - auto &cab{dragon6.mover()}; + auto &cab{dragon6.physics()}; CHECK(cab.Genset.power == 0.0); CHECK_FALSE(cab.Genset.fitted()); CHECK_FALSE(cab.TractionModeSwitch(traction_mode::genset)); @@ -191,7 +191,7 @@ TEST_CASE("genset: the keys are ignored on other than induction motor vehicles") TEST_CASE("genset: the selector moves only with the line breaker open") { vehicle dragon6{dragon_genset(), 0.0, "test", 1}; - auto &cab{dragon6.mover()}; + auto &cab{dragon6.physics()}; REQUIRE(test::start_up(test::driving(dragon6), wire)); REQUIRE(cab.Mains); CHECK_FALSE(cab.TractionModeSwitch(traction_mode::genset)); @@ -208,7 +208,7 @@ TEST_CASE("genset: the selector moves only with the line breaker open") { TEST_CASE("genset: started, it closes the line breaker without a catenary") { vehicle dragon6{dragon_genset(), 0.0, "test", 1}; - auto &cab{dragon6.mover()}; + auto &cab{dragon6.physics()}; wake(cab); REQUIRE(cab.TractionModeSwitch(traction_mode::genset)); cab.GensetSwitch(true); @@ -240,7 +240,7 @@ TEST_CASE("genset: started, it closes the line breaker without a catenary") { TEST_CASE("genset: on the catenary position the genset feeds nothing") { vehicle dragon6{dragon_genset(), 0.0, "test", 1}; - auto &cab{dragon6.mover()}; + auto &cab{dragon6.physics()}; wake(cab); cab.GensetSwitch(true); run(dragon6, 20.0); @@ -258,7 +258,7 @@ TEST_CASE("genset: on the catenary position the genset feeds nothing") { TEST_CASE("genset: on the genset position the catenary feeds nothing") { vehicle dragon6{dragon_genset(), 0.0, "test", 1}; - auto &cab{dragon6.mover()}; + auto &cab{dragon6.physics()}; wake(cab); REQUIRE(cab.TractionModeSwitch(traction_mode::genset)); // the pantographs up under the wire, the genset stopped: the line breaker never closes @@ -273,7 +273,7 @@ TEST_CASE("genset: on the genset position the catenary feeds nothing") { TEST_CASE("genset: the power at the wheels stays within the genset's") { vehicle dragon6{dragon_genset(), 0.0, "test", 1}; - auto &cab{dragon6.mover()}; + auto &cab{dragon6.physics()}; REQUIRE(start_on_genset(dragon6)); notch_up(cab); auto peak{0.0}; @@ -301,7 +301,7 @@ TEST_CASE("genset: the power at the wheels stays within the genset's") { TEST_CASE("genset: the revolutions follow the demand, so the power builds up") { vehicle dragon6{dragon_genset(), 0.0, "test", 1}; - auto &cab{dragon6.mover()}; + auto &cab{dragon6.physics()}; REQUIRE(start_on_genset(dragon6)); // at idle with nothing asked of it CHECK(cab.Genset.revolutions == doctest::Approx(cab.Genset.revolutions_idle)); @@ -341,11 +341,11 @@ TEST_CASE("genset: running from the catenary is the same with the keys") { }; auto const record = [](values &Values) { return std::vector{ - {"Ft", [&Values](TMoverParameters const &Vehicle) { Values.force.push_back(Vehicle.Ft); return Vehicle.Ft; }}, - {"V", [&Values](TMoverParameters const &Vehicle) { Values.speed.push_back(Vehicle.V); return Vehicle.V; }}, - {"EngineVoltage", [&Values](TMoverParameters const &Vehicle) { Values.voltage.push_back(Vehicle.EngineVoltage); return Vehicle.EngineVoltage; }}, - {"Itot", [&Values](TMoverParameters const &Vehicle) { Values.current.push_back(Vehicle.Itot); return Vehicle.Itot; }}, - {"eimv_pr", [&Values](TMoverParameters const &Vehicle) { Values.demand.push_back(Vehicle.inductionMotor.forceShare); return Vehicle.inductionMotor.forceShare; }}, + {"Ft", [&Values](physics::Vehicle const &Vehicle) { Values.force.push_back(Vehicle.Ft); return Vehicle.Ft; }}, + {"V", [&Values](physics::Vehicle const &Vehicle) { Values.speed.push_back(Vehicle.V); return Vehicle.V; }}, + {"EngineVoltage", [&Values](physics::Vehicle const &Vehicle) { Values.voltage.push_back(Vehicle.EngineVoltage); return Vehicle.EngineVoltage; }}, + {"Itot", [&Values](physics::Vehicle const &Vehicle) { Values.current.push_back(Vehicle.Itot); return Vehicle.Itot; }}, + {"eimv_pr", [&Values](physics::Vehicle const &Vehicle) { Values.demand.push_back(Vehicle.inductionMotor.forceShare); return Vehicle.inductionMotor.forceShare; }}, }; }; auto const drive = [&record](definition const &Definition, values &Values) { @@ -377,7 +377,7 @@ TEST_CASE("genset: running from the catenary is the same with the keys") { TEST_CASE("genset: stopped, it opens the line breaker") { vehicle dragon6{dragon_genset(), 0.0, "test", 1}; - auto &cab{dragon6.mover()}; + auto &cab{dragon6.physics()}; REQUIRE(start_on_genset(dragon6)); REQUIRE(cab.Genset.revolutions == doctest::Approx(cab.Genset.revolutions_idle)); cab.GensetSwitch(false); @@ -404,7 +404,7 @@ TEST_CASE("genset: stopped, it opens the line breaker") { TEST_CASE("genset: automatic start follows the selector") { vehicle dragon6{dragon_genset().set("Cntrl", "GensetStart", "Automatic"), 0.0, "test", 1}; - auto &cab{dragon6.mover()}; + auto &cab{dragon6.physics()}; wake(cab); run(dragon6, 10.0); CHECK_FALSE(cab.Genset.is_cranking); @@ -425,7 +425,7 @@ TEST_CASE("genset: automatic start follows the selector") { TEST_CASE("genset: no battery, no start") { vehicle dragon6{dragon_genset(), 0.0, "test", 1}; - auto &cab{dragon6.mover()}; + auto &cab{dragon6.physics()}; cab.BatterySwitch(false); REQUIRE(cab.TractionModeSwitch(traction_mode::genset)); cab.GensetSwitch(true); @@ -443,7 +443,7 @@ TEST_CASE("genset: no battery, no start") { TEST_CASE("genset: the pantographs' pressure switch leaves the genset's line breaker alone") { SUBCASE("on the genset") { vehicle dragon6{dragon_genset(), 0.0, "test", 1}; - auto &cab{dragon6.mover()}; + auto &cab{dragon6.physics()}; REQUIRE(start_on_genset(dragon6)); cab.PantPressSwitchActive = true; cab.PantPress = 0.0; @@ -452,7 +452,7 @@ TEST_CASE("genset: the pantographs' pressure switch leaves the genset's line bre } SUBCASE("on the pantographs it opens the line breaker, the check the genset is spared") { vehicle dragon6{dragon_genset(), 0.0, "test", 1}; - auto &cab{dragon6.mover()}; + auto &cab{dragon6.physics()}; REQUIRE(test::start_up(test::driving(dragon6), wire)); REQUIRE(cab.Mains); // the pressure switch looks at the voltage through the couplers, not the pantographs' @@ -475,7 +475,7 @@ struct braking { // up to 60 km/h at full power, then braking with the train brake for 20 s, which the E6ACT blends with the // electrodynamic one braking brake_from_60(vehicle &Dragon, track const &Track) { - auto &cab{Dragon.mover()}; + auto &cab{Dragon.physics()}; notch_up(cab); for (auto step_count = 0L; step_count < 60000 && cab.Vel < 60.0; ++step_count) { step(Dragon, step_count, Track); @@ -513,7 +513,7 @@ TEST_CASE("genset: braking electrodynamically on the genset sends nothing back") SUBCASE("on the catenary the same braking feeds the line, the check the genset is spared") { vehicle dragon6{dragon_genset(), 0.0, "test", 1}; REQUIRE(test::start_up(test::driving(dragon6), wire)); - test::release_brakes(dragon6.mover()); + test::release_brakes(dragon6.physics()); run(dragon6, 5.0, wire); auto const braked{brake_from_60(dragon6, wire)}; REQUIRE(braked.electrodynamic); @@ -525,8 +525,8 @@ TEST_CASE("genset: braking electrodynamically on the genset sends nothing back") TEST_CASE("genset: one genset feeds the next car through the high voltage coupling") { // both able to join the control and the high voltage lines: 35 of the E6ACT, + control 4 + high voltage 8 consist train; - auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 1).mover()}; - auto &second{train.add(dragon().set("BuffCoupl", "AllowedFlag", 47)).mover()}; + auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 1).physics()}; + auto &second{train.add(dragon().set("BuffCoupl", "AllowedFlag", 47)).physics()}; REQUIRE(first.Couplers[VehicleEnd::rear].CouplingFlag.HasAny(Coupling::highVoltage)); wake(first); REQUIRE(first.TractionModeSwitch(traction_mode::genset)); @@ -555,8 +555,8 @@ TEST_CASE("genset: the selector command travels along the train") { // two locomotives in multiple: the control line, no permanent coupling auto const coupling{Coupling::coupler | Coupling::brakeHose | Coupling::mainHose | Coupling::control}; consist train; - auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 1).mover()}; - auto &second{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 0, coupling).mover()}; + auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 1).physics()}; + auto &second{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 0, coupling).physics()}; REQUIRE(first.Couplers[VehicleEnd::rear].CouplingFlag.HasAny(Coupling::control)); wake(first); train.run(1.0, no_wire); @@ -577,8 +577,8 @@ TEST_CASE("genset: the selector command travels along the train") { TEST_CASE("genset: a selector command refused with the line breaker closed isn't passed on") { auto const coupling{Coupling::coupler | Coupling::brakeHose | Coupling::mainHose | Coupling::control}; consist train; - auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 1).mover()}; - auto &second{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 0, coupling).mover()}; + auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 1).physics()}; + auto &second{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 0, coupling).physics()}; REQUIRE(test::start_up(test::driving(train), wire)); REQUIRE(first.Mains); // the second one's line breaker opened by itself, the lead's is closed @@ -597,8 +597,8 @@ TEST_CASE("genset: a selector command refused with the line breaker closed isn't TEST_CASE("genset: a lead which starts its genset on its own passes the start switch on") { auto const coupling{Coupling::coupler | Coupling::brakeHose | Coupling::mainHose | Coupling::control}; consist train; - auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47).set("Cntrl", "GensetStart", "Automatic"), 1).mover()}; - auto &second{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 0, coupling).mover()}; + auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47).set("Cntrl", "GensetStart", "Automatic"), 1).physics()}; + auto &second{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 0, coupling).physics()}; wake(first); train.run(1.0, no_wire); // ignored by the lead, so its cab switch doesn't move, but the car behind starts on it @@ -612,7 +612,7 @@ TEST_CASE("genset: a lead which starts its genset on its own passes the start sw TEST_CASE("genset: on the genset the pantographs carry no traction current") { SUBCASE("on the genset") { vehicle dragon6{dragon_genset(), 0.0, "test", 1}; - auto &cab{dragon6.mover()}; + auto &cab{dragon6.physics()}; REQUIRE(start_on_genset(dragon6)); notch_up(cab); run(dragon6, 10.0); @@ -627,7 +627,7 @@ TEST_CASE("genset: on the genset the pantographs carry no traction current") { } SUBCASE("on the catenary the traction current goes through them, the check the genset is spared") { vehicle dragon6{dragon_genset(), 0.0, "test", 1}; - auto &cab{dragon6.mover()}; + auto &cab{dragon6.physics()}; REQUIRE(test::start_up(test::driving(dragon6), wire)); test::release_brakes(cab); run(dragon6, 5.0, wire); @@ -644,7 +644,7 @@ TEST_CASE("genset: on the genset the pantographs carry no traction current") { TEST_CASE("genset: a scenery command reaches the selector") { vehicle dragon6{dragon_genset(), 0.0, "test", 1}; - auto &cab{dragon6.mover()}; + auto &cab{dragon6.physics()}; wake(cab); // as a scenery's PutValues event gives it, one at a time cab.PutCommand("TractionMode", 1, 0, cab.Loc); diff --git a/tests/unit/test_handover.cpp b/tests/unit/test_handover.cpp index 3cecb9b51..263054cf6 100644 --- a/tests/unit/test_handover.cpp +++ b/tests/unit/test_handover.cpp @@ -30,7 +30,7 @@ TEST_CASE("handover: the horn the AI was sounding goes quiet (eu07/maszyna#511)" SUBCASE("both tones") { cab->WarningSignal = 1 | 2; } REQUIRE(cab->WarningSignal != 0); - handover::release_ai_controls(cab.mover(), cab.mover()); + handover::release_ai_controls(cab.physics(), cab.physics()); CHECK(cab->WarningSignal == 0); } @@ -40,7 +40,7 @@ TEST_CASE("handover: sanding the AI started stops") { cab->Sandbox(true); // the way the AI sands, bypassing the sanding button REQUIRE(cab->SandDose); - handover::release_ai_controls(cab.mover(), cab.mover()); + handover::release_ai_controls(cab.physics(), cab.physics()); CHECK_FALSE(cab->SandDose); } @@ -54,7 +54,7 @@ TEST_CASE("handover: sanding the player or the automatic system asked for goes o } REQUIRE(cab->SandDose); - handover::release_ai_controls(cab.mover(), cab.mover()); + handover::release_ai_controls(cab.physics(), cab.physics()); CHECK(cab->SandDose); } @@ -64,7 +64,7 @@ TEST_CASE("handover: the departure signal the AI was giving stops") { cab->signal_departure(true); REQUIRE(cab->DepartureSignal); - handover::release_ai_controls(cab.mover(), cab.mover()); + handover::release_ai_controls(cab.physics(), cab.physics()); CHECK_FALSE(cab->DepartureSignal); } @@ -74,7 +74,7 @@ TEST_CASE("handover: the brake releaser the AI was holding lets go") { cab->BrakeReleaser(1); REQUIRE(cab->Hamulec->Releaser()); - handover::release_ai_controls(cab.mover(), cab.mover()); + handover::release_ai_controls(cab.physics(), cab.physics()); CHECK_FALSE(cab->Hamulec->Releaser()); } @@ -82,7 +82,7 @@ TEST_CASE("handover: the brake releaser the AI was holding lets go") { TEST_CASE("handover: nothing the AI didn't latch changes") { auto cab{cab_vehicle()}; - handover::release_ai_controls(cab.mover(), cab.mover()); + handover::release_ai_controls(cab.physics(), cab.physics()); CHECK(cab->WarningSignal == 0); CHECK_FALSE(cab->SandDose); @@ -95,17 +95,17 @@ TEST_CASE("handover: the light selector moves to the position giving the head li REQUIRE(cab->LightsPos == 1); // untouched selector: lights off SUBCASE("Pc1") { - CHECK(handover::light_selector_position(cab.mover(), NumberOf(VehicleEnd::front), pc1, allheadlights) == 2); + CHECK(handover::light_selector_position(cab.physics(), NumberOf(VehicleEnd::front), pc1, allheadlights) == 2); } SUBCASE("lights off") { - CHECK(handover::light_selector_position(cab.mover(), NumberOf(VehicleEnd::front), 0, allheadlights) == 1); + CHECK(handover::light_selector_position(cab.physics(), NumberOf(VehicleEnd::front), 0, allheadlights) == 1); } SUBCASE("vehicle without the upper headlight, which the AI's Pc1 can't light") { auto const inventory{allheadlights & ~light::headlight_upper}; - CHECK(handover::light_selector_position(cab.mover(), NumberOf(VehicleEnd::front), pc1 & inventory, inventory) == 2); + CHECK(handover::light_selector_position(cab.physics(), NumberOf(VehicleEnd::front), pc1 & inventory, inventory) == 2); } SUBCASE("no position matches: the selector stays") { - CHECK(handover::light_selector_position(cab.mover(), NumberOf(VehicleEnd::front), light::headlight_left, allheadlights) == 1); + CHECK(handover::light_selector_position(cab.physics(), NumberOf(VehicleEnd::front), light::headlight_left, allheadlights) == 1); } } @@ -118,12 +118,12 @@ TEST_CASE("handover: the light selector stays within its table") { std::fill(std::begin(table) + cab->LightsPosNo, std::end(table), 0); } cab->LightsPosNo = 100; - CHECK(handover::light_selector_position(cab.mover(), NumberOf(VehicleEnd::front), pc1, allheadlights) == 2); - CHECK(handover::light_selector_position(cab.mover(), NumberOf(VehicleEnd::front), light::headlight_left, allheadlights) == 1); + CHECK(handover::light_selector_position(cab.physics(), NumberOf(VehicleEnd::front), pc1, allheadlights) == 2); + CHECK(handover::light_selector_position(cab.physics(), NumberOf(VehicleEnd::front), light::headlight_left, allheadlights) == 1); } SUBCASE("table other than the front or rear one: the selector stays") { - CHECK(handover::light_selector_position(cab.mover(), -1, pc1, allheadlights) == 1); - CHECK(handover::light_selector_position(cab.mover(), 2, pc1, allheadlights) == 1); + CHECK(handover::light_selector_position(cab.physics(), -1, pc1, allheadlights) == 1); + CHECK(handover::light_selector_position(cab.physics(), 2, pc1, allheadlights) == 1); } } @@ -131,7 +131,7 @@ TEST_CASE("handover: the light selector already matching the lights stays") { auto cab{cab_vehicle()}; cab->LightsPos = 2; // Pc1 - CHECK(handover::light_selector_position(cab.mover(), NumberOf(VehicleEnd::front), pc1, allheadlights) == 2); + CHECK(handover::light_selector_position(cab.physics(), NumberOf(VehicleEnd::front), pc1, allheadlights) == 2); } TEST_CASE("handover: the headlight dimmer leaves the off position when the head lights are lit") { @@ -141,14 +141,14 @@ TEST_CASE("handover: the headlight dimmer leaves the off position when the head cab->modernDimmerPosition = 2; // off, left there by the player before the AI took over SUBCASE("to the default position") { - CHECK(handover::dimmer_position(cab.mover(), true) == 3); + CHECK(handover::dimmer_position(cab.physics(), true) == 3); } SUBCASE("to the first regular position, when the default one is off as well") { cab->modernDimmerDefaultPosition = 2; - CHECK(handover::dimmer_position(cab.mover(), true) == 3); + CHECK(handover::dimmer_position(cab.physics(), true) == 3); } SUBCASE("unless the head lights are off anyway") { - CHECK(handover::dimmer_position(cab.mover(), false) == 2); + CHECK(handover::dimmer_position(cab.physics(), false) == 2); } } @@ -157,7 +157,7 @@ TEST_CASE("handover: the headlight dimmer in any other position stays") { for (auto const position : {0, 1, 3, 4}) { CAPTURE(position); cab->modernDimmerPosition = position; - CHECK(handover::dimmer_position(cab.mover(), true) == position); + CHECK(handover::dimmer_position(cab.physics(), true) == position); } } @@ -165,5 +165,5 @@ TEST_CASE("handover: a vehicle without the modern dimmer keeps its dimmer state" vehicle wagon{definition::load("wagon")}; REQUIRE_FALSE(wagon->enableModernDimmer); - CHECK(handover::dimmer_position(wagon.mover(), true) == wagon->modernDimmerPosition); + CHECK(handover::dimmer_position(wagon.physics(), true) == wagon->modernDimmerPosition); } diff --git a/tests/unit/test_horn.cpp b/tests/unit/test_horn.cpp index 18e5c5322..7245d4267 100644 --- a/tests/unit/test_horn.cpp +++ b/tests/unit/test_horn.cpp @@ -108,9 +108,9 @@ TEST_CASE("horn: a vehicle without any air, a road vehicle say, sounds its pneum TEST_CASE("horn: a pneumatic horn sounds from the threshold pressure up") { auto vehicle{horn_vehicle(test::definition::load("wagon"))}; - vehicle->Compressor = TMoverParameters::HornMinPressure; + vehicle->Compressor = physics::Vehicle::HornMinPressure; CHECK(vehicle->SoundingHorns(horn::low) == horn::low); - vehicle->Compressor = TMoverParameters::HornMinPressure - 0.01; + vehicle->Compressor = physics::Vehicle::HornMinPressure - 0.01; CHECK(vehicle->SoundingHorns(horn::low) == 0); } diff --git a/tests/unit/test_invariants.cpp b/tests/unit/test_invariants.cpp index 36c511863..3abad65f6 100644 --- a/tests/unit/test_invariants.cpp +++ b/tests/unit/test_invariants.cpp @@ -12,13 +12,13 @@ using test::vehicle; TEST_CASE("invariants: a vehicle in an impossible state, reported once with its time and the last event") { vehicle eu07{definition::fiz("4e_v1/4e")}; test::trace trace{"invariants/self test", test::channels::brakes()}; - trace.sample(0.0, eu07.mover()); + trace.sample(0.0, eu07.physics()); CHECK(trace.violations().empty()); trace.mark("overfilled"); eu07->BrakePress = 50.0; - trace.sample(0.01, eu07.mover()); - trace.sample(0.02, eu07.mover()); + trace.sample(0.01, eu07.physics()); + trace.sample(0.02, eu07.physics()); REQUIRE(trace.violations().size() == 1); auto const &violation{trace.violations().front()}; CHECK(violation.find("brake cylinders") != std::string::npos); @@ -28,7 +28,7 @@ TEST_CASE("invariants: a vehicle in an impossible state, reported once with its eu07->BrakePress = 0.0; eu07->V = std::nan(""); - trace.sample(0.03, eu07.mover()); + trace.sample(0.03, eu07.physics()); CHECK(trace.violations().size() > 1); CHECK(trace.violations()[1].find("every value a number") != std::string::npos); } diff --git a/tests/unit/test_lights_preset_cablight.cpp b/tests/unit/test_lights_preset_cablight.cpp index fe079bfd4..e1dfcc827 100644 --- a/tests/unit/test_lights_preset_cablight.cpp +++ b/tests/unit/test_lights_preset_cablight.cpp @@ -87,7 +87,7 @@ TEST_CASE("lights preset cab light: a stray note after the two columns is not re auto const rowend{text.find('\n', row)}; REQUIRE(rowend != std::string::npos); text.insert(rowend, " / A"); - TMoverParameters wagon(0.0, "wagon", "test", 0); + physics::Vehicle wagon(0.0, "wagon", "test", 0); REQUIRE(wagon.LoadFIZ_Text(text)); REQUIRE(wagon.LightsPosNo == 2); CHECK(wagon.Lights[VehicleEnd::front][1] == 38); diff --git a/tests/unit/test_line_contactors_interlock.cpp b/tests/unit/test_line_contactors_interlock.cpp index 91274ad35..d8c484349 100644 --- a/tests/unit/test_line_contactors_interlock.cpp +++ b/tests/unit/test_line_contactors_interlock.cpp @@ -117,8 +117,8 @@ TEST_CASE("line contactors interlock: a blower starting with the speed needs to namespace { -bool blowers_run(TMoverParameters const &Mover) { - return Mover.MotorBlowers[VehicleEnd::front].is_active && Mover.MotorBlowers[VehicleEnd::rear].is_active; +bool blowers_run(physics::Vehicle const &Physics) { + return Physics.MotorBlowers[VehicleEnd::front].is_active && Physics.MotorBlowers[VehicleEnd::rear].is_active; } // the driver's first power position, held until the line contactors close (their delay, the pressure switch) @@ -153,34 +153,34 @@ TEST_CASE("line contactors interlock: with blowers starting with the speed the v .set("Engine", "MotorBlowersStartVelocity", 5.0) .set("Engine", "MotorBlowersSustainTime", 10.0), 0.0, "test", 1}; - auto &mover{eu07.mover()}; - REQUIRE(mover.LineContactorsInterlock == line_contactors_interlock::motor_blowers); - REQUIRE(mover.MotorBlowers[VehicleEnd::front].min_start_velocity == doctest::Approx(5.0)); - REQUIRE(mover.MotorBlowers[VehicleEnd::rear].sustain_time == doctest::Approx(10.0)); + auto &physics{eu07.physics()}; + REQUIRE(physics.LineContactorsInterlock == line_contactors_interlock::motor_blowers); + REQUIRE(physics.MotorBlowers[VehicleEnd::front].min_start_velocity == doctest::Approx(5.0)); + REQUIRE(physics.MotorBlowers[VehicleEnd::rear].sustain_time == doctest::Approx(10.0)); auto driven{test::driving(eu07)}; REQUIRE(test::start_up(driven, line)); release(driven); // standing, the blowers don't run; the line contactors close all the same and the motors take current REQUIRE(std::abs(eu07.speed()) < 0.1); - REQUIRE_FALSE(blowers_run(mover)); + REQUIRE_FALSE(blowers_run(physics)); CHECK(close_line_contactors(driven)); - CHECK(std::abs(mover.Im) > 0.5); + CHECK(std::abs(physics.Im) > 0.5); // the blowers come on once the vehicle moves for (int i = 0; i < 6; ++i) { - mover.IncMainCtrl(1); + physics.IncMainCtrl(1); test::drive(driven, line, 2.0); } for (int i = 0; i < 60 && eu07.speed() < 10.0; ++i) { test::drive(driven, line, 1.0); } REQUIRE(eu07.speed() >= 10.0); - CHECK(blowers_run(mover)); - CHECK(mover.StLinFlag); + CHECK(blowers_run(physics)); + CHECK(physics.StLinFlag); // a stop longer than the blowers keep running for - while (mover.DecMainCtrl(1)) { + while (physics.DecMainCtrl(1)) { // down to zero } driven.cab.BrakeLevelSet(driven.cab.Handle->GetPos(bh_FB)); @@ -189,22 +189,22 @@ TEST_CASE("line contactors interlock: with blowers starting with the speed the v } REQUIRE(std::abs(eu07.speed()) <= 0.1); test::drive(driven, line, 15.0); - REQUIRE_FALSE(blowers_run(mover)); - REQUIRE_FALSE(mover.StLinFlag); + REQUIRE_FALSE(blowers_run(physics)); + REQUIRE_FALSE(physics.StLinFlag); // and the vehicle starts again release(driven); CHECK(close_line_contactors(driven)); - CHECK(std::abs(mover.Im) > 0.5); + CHECK(std::abs(physics.Im) > 0.5); for (int i = 0; i < 6; ++i) { - mover.IncMainCtrl(1); + physics.IncMainCtrl(1); test::drive(driven, line, 2.0); } for (int i = 0; i < 60 && eu07.speed() < 10.0; ++i) { test::drive(driven, line, 1.0); } CHECK(eu07.speed() >= 10.0); - CHECK(blowers_run(mover)); + CHECK(blowers_run(physics)); } TEST_CASE("line contactors interlock: a blower starting with the speed, switched off on the way, opens the contactors") { @@ -214,31 +214,31 @@ TEST_CASE("line contactors interlock: a blower starting with the speed, switched .set("Engine", "MotorBlowersStartVelocity", 5.0) .set("Engine", "MotorBlowersSustainTime", 10.0), 0.0, "test", 1}; - auto &mover{eu07.mover()}; + auto &physics{eu07.physics()}; auto driven{test::driving(eu07)}; REQUIRE(test::start_up(driven, line)); release(driven); REQUIRE(close_line_contactors(driven)); // the switch of the rear blower: off, the contactors open and stay open, standing as well as later - REQUIRE(mover.MotorBlowersSwitchOff(true, VehicleEnd::rear)); + REQUIRE(physics.MotorBlowersSwitchOff(true, VehicleEnd::rear)); test::drive(driven, line, 2.0); - CHECK_FALSE(mover.StLinFlag); - CHECK(std::abs(mover.Im) < 0.5); - while (mover.DecMainCtrl(1)) { + CHECK_FALSE(physics.StLinFlag); + CHECK(std::abs(physics.Im) < 0.5); + while (physics.DecMainCtrl(1)) { // down to zero } test::drive(driven, line, 2.0); CHECK_FALSE(close_line_contactors(driven)); // back on, the vehicle starts - REQUIRE(mover.MotorBlowersSwitchOff(false, VehicleEnd::rear)); - while (mover.DecMainCtrl(1)) { + REQUIRE(physics.MotorBlowersSwitchOff(false, VehicleEnd::rear)); + while (physics.DecMainCtrl(1)) { // down to zero } test::drive(driven, line, 2.0); CHECK(close_line_contactors(driven)); - CHECK(std::abs(mover.Im) > 0.5); + CHECK(std::abs(physics.Im) > 0.5); } TEST_CASE("line contactors interlock: held by the local converter switch only where they wait for that converter") { @@ -262,8 +262,8 @@ TEST_CASE("line contactors interlock: the ET42 section with its fans switched of et42.add(definition::fiz("et42_v2/112e-b").set("Cntrl", "LineContactorsInterlock", "Converter")); auto driven{test::driving(et42)}; REQUIRE(test::start_up(driven, line)); - auto &front{et42[0].mover()}; - auto &rear{et42[1].mover()}; + auto &front{et42[0].physics()}; + auto &rear{et42[1].physics()}; REQUIRE(front.ConverterFlag); REQUIRE(rear.ConverterFlag); diff --git a/tests/unit/test_linebreaker.cpp b/tests/unit/test_linebreaker.cpp index 9b36b817f..6b132e08e 100644 --- a/tests/unit/test_linebreaker.cpp +++ b/tests/unit/test_linebreaker.cpp @@ -16,7 +16,7 @@ namespace { // the line breaker lever of the EP05 (main_sw), a single two-state lever, the way TTrain works it: the state // the cab keeps of the line breaker follows the vehicle, the breaker closes while the lever is on and can close struct lever { - TMoverParameters &mover; + physics::Vehicle &physics; state breaker{state::open}; // as TTrain::m_linebreakerstate bool on{false}; @@ -27,7 +27,7 @@ struct lever { break; case linebreaker::toggle::open: on = false; - if (breaker == state::closed && mover.MainSwitch(false)) { + if (breaker == state::closed && physics.MainSwitch(false)) { breaker = state::open; } break; @@ -37,14 +37,14 @@ struct lever { } // TTrain::Update() void update() { - if (breaker == state::open && mover.Mains) { + if (breaker == state::open && physics.Mains) { breaker = state::closed; } - if (breaker == state::closed && false == mover.Mains) { + if (breaker == state::closed && false == physics.Mains) { breaker = state::open; } - if (on && breaker == state::open && mover.MainSwitchCheck()) { - breaker = mover.MainSwitch(true) ? state::closed : state::open; + if (on && breaker == state::open && physics.MainSwitchCheck()) { + breaker = physics.MainSwitch(true) ? state::closed : state::open; } } }; @@ -67,7 +67,7 @@ TEST_CASE("line breaker: a press of the toggle closes an open breaker and opens TEST_CASE("line breaker: the EP05's lever goes off with the converter overload relay tripped (eu07/maszyna#394)") { consist train; - auto &ep05{train.add(definition::fiz("ep05_v2/ep05"), 1).mover()}; + auto &ep05{train.add(definition::fiz("ep05_v2/ep05"), 1).physics()}; test::track const line{0.15, 0.0, test::catenary_3kv}; auto const driver{test::driving(train)}; REQUIRE(test::start_up(driver, line)); diff --git a/tests/unit/test_motor_param_bounds.cpp b/tests/unit/test_motor_param_bounds.cpp index 5d44c7331..8226fad46 100644 --- a/tests/unit/test_motor_param_bounds.cpp +++ b/tests/unit/test_motor_param_bounds.cpp @@ -11,7 +11,7 @@ using test::vehicle; // the field shunting step a position of the master controller selects (RList, its sixth column ScndAct) indexes the // motor parameter table, MotorParam, which has MotorParametersArraySize + 1 entries. The loader takes ScndAct from the -// .fiz as it is, so the readers of the table (TMoverParameters::Momentum(), MomentumF(), TController::ESMVelocity()) +// .fiz as it is, so the readers of the table (physics::Vehicle::Momentum(), MomentumF(), TController::ESMVelocity()) // go through motor_param(), which keeps the index inside the table namespace { diff --git a/tests/unit/test_parser.cpp b/tests/unit/test_parser.cpp index ee82aca9a..58f3bb980 100644 --- a/tests/unit/test_parser.cpp +++ b/tests/unit/test_parser.cpp @@ -698,7 +698,7 @@ TEST_CASE("parser: read line by line, a line starting with include is the direct namespace { -// the lines of a file, read the way the vehicle's .fiz is (TMoverParameters::LoadFIZ_Parse): line by line while the +// the lines of a file, read the way the vehicle's .fiz is (physics::Vehicle::LoadFIZ_Parse): line by line while the // parser is ok std::string fiz_lines(cParser &Parser) { std::string joined; diff --git a/tests/unit/test_pullee.cpp b/tests/unit/test_pullee.cpp index dc5235c08..fb276eb97 100644 --- a/tests/unit/test_pullee.cpp +++ b/tests/unit/test_pullee.cpp @@ -11,7 +11,7 @@ using test::definition; using test::vehicle; // the pullee mode ("jazda ciągniona", MaSzyna-EU07/maszyna#64): a vehicle prepared for being hauled dead in a -// train, TMoverParameters::PulleeModeSwitch(). the trains here are an EU07 and the vehicle behind it, coupled with +// train, physics::Vehicle::PulleeModeSwitch(). the trains here are an EU07 and the vehicle behind it, coupled with // the hook and the brake hose alone, as with coupling 3 of a scenery. every test has both sides: what the vehicle // does as it is (unchanged by the mode being there), and what it does prepared for hauling. // pressures in bar, the brake pipe runs at 5.0 @@ -40,7 +40,7 @@ struct hauled_train { }; // no air in the main reservoir and the feed pipe, as after standing dead for some hours -void drain_feed_air(TMoverParameters &Vehicle) { +void drain_feed_air(physics::Vehicle &Vehicle) { Vehicle.Pipe2->CreatePress(0.0); Vehicle.Pipe2->Act(); Vehicle.CompressedVolume = 0.0; @@ -147,9 +147,9 @@ TEST_CASE("pullee: the spring brake of a dead locomotive without air stops the t CAPTURE(pullee); test::reseed_random(); hauled_train train{definition::fiz(path), 60.0, pullee}; - auto const &hauled{train.hauled.mover()}; + auto const &hauled{train.hauled.physics()}; REQUIRE(hauled.SpringBrake.MaxBrakeForce > 0.0); - drain_feed_air(train.hauled.mover()); + drain_feed_air(train.hauled.physics()); train.run(60.0); // no air came from anywhere: the cylinder of the spring brake is empty either way REQUIRE(hauled.SpringBrake.SBP < 0.1); @@ -171,7 +171,7 @@ TEST_CASE("pullee: a dead EU47 starts to drag once its main reservoir has leaked CAPTURE(pullee); test::reseed_random(); hauled_train train{definition::fiz("e186_v2/eu47"), 0.0, pullee}; - auto &hauled{train.hauled.mover()}; + auto &hauled{train.hauled.physics()}; // what the driver of the train does on its inspection, TController::AutoRewident() hauled.DecManualBrakeLevel(ManualBrakePosNo); hauled.SpringBrake.Activate = false; @@ -199,9 +199,9 @@ TEST_CASE("pullee: a vehicle prepared for hauling brakes and releases with the t CAPTURE(feedair); test::reseed_random(); hauled_train train{definition::fiz(path), 60.0, true}; - auto const &hauled{train.hauled.mover()}; + auto const &hauled{train.hauled.physics()}; if (false == feedair) { - drain_feed_air(train.hauled.mover()); + drain_feed_air(train.hauled.physics()); } train.run(30.0); CHECK(hauled.BrakePress < 0.1); @@ -227,10 +227,10 @@ TEST_CASE("pullee: the spring brake of an Impuls prepared for hauling doesn't ca CAPTURE(pullee); test::reseed_random(); hauled_train train{impuls, 60.0, pullee}; - auto const &hauled{train.hauled.mover()}; + auto const &hauled{train.hauled.physics()}; REQUIRE(hauled.InactiveCabFlag == 0); REQUIRE(hauled.SpringBrakeDriveEmergencyVel == doctest::Approx(2.0)); - drain_feed_air(train.hauled.mover()); + drain_feed_air(train.hauled.physics()); train.run(10.0); REQUIRE(hauled.Vel > 2.0); REQUIRE(hauled.SpringBrake.IsActive); @@ -415,8 +415,8 @@ TEST_CASE("pullee: every real vehicle prepared for hauling runs free behind a lo } test::reseed_random(); hauled_train train{definition::fiz(path), 60.0, true}; - auto const &hauled{train.hauled.mover()}; - drain_feed_air(train.hauled.mover()); + auto const &hauled{train.hauled.physics()}; + drain_feed_air(train.hauled.physics()); train.run(60.0); CHECK(hauled.EmergencyValveFlow == 0.0); CHECK(hauled.BrakePress < 0.1); @@ -436,7 +436,7 @@ TEST_CASE("pullee: every real vehicle standing braked releases once prepared for test::reseed_random(); // hand brakes on, spring brakes switched on, cylinders half full, the pipe at 3.5 hauled_train train{definition::fiz(path), 0.0, true}; - auto const &hauled{train.hauled.mover()}; + auto const &hauled{train.hauled.physics()}; CHECK(hauled.ManualBrakePos == 0); CHECK_FALSE(hauled.SpringBrake.Activate); CHECK_FALSE(hauled.Battery); diff --git a/tests/unit/test_queries.cpp b/tests/unit/test_queries.cpp index 490c57be4..871549e9b 100644 --- a/tests/unit/test_queries.cpp +++ b/tests/unit/test_queries.cpp @@ -51,7 +51,7 @@ TEST_CASE("queries: the damage of a vehicle as the driver's panel describes it") TEST_CASE("queries: the ammeters of a vehicle without power show the current of the ones it controls") { vehicle unpowered{definition::fiz("en57_v1/6ba_840")}; vehicle powered{definition::fiz("en57_v1/5bgb")}; - unpowered->Attach(VehicleEnd::rear, VehicleEnd::front, &powered.mover(), Coupling::control, true, false); + unpowered->Attach(VehicleEnd::rear, VehicleEnd::front, &powered.physics(), Coupling::control, true, false); powered->Power = 600.0; powered->Itot = 321.7; unpowered->Power = 0.0; diff --git a/tests/unit/test_smoke.cpp b/tests/unit/test_smoke.cpp index e8c31d87b..7f204927c 100644 --- a/tests/unit/test_smoke.cpp +++ b/tests/unit/test_smoke.cpp @@ -35,12 +35,12 @@ TEST_CASE("smoke: a vehicle taken off the tracks puffs no more (#90)") { vehicle->Im = 400.0; } // on the tracks the engine puffs - REQUIRE(smoke::vehicle_spawn_count(vehicle.mover(), true, source, update) >= 1.f); + REQUIRE(smoke::vehicle_spawn_count(vehicle.physics(), true, source, update) >= 1.f); // gone through a portal, the pending particles are dropped too auto pending{source}; pending.pending = 5.f; - CHECK(smoke::vehicle_spawn_count(vehicle.mover(), false, pending, update) == 0.f); + CHECK(smoke::vehicle_spawn_count(vehicle.physics(), false, pending, update) == 0.f); } TEST_CASE("smoke: a road vehicle back on the road from the pool puffs again") { @@ -48,11 +48,11 @@ TEST_CASE("smoke: a road vehicle back on the road from the pool puffs again") { // waiting in the pool, the count stays at zero update after update auto rate{source}; for (auto i{0}; i < 10; ++i) { - rate.pending = smoke::vehicle_spawn_count(vehicle.mover(), false, rate, update); + rate.pending = smoke::vehicle_spawn_count(vehicle.physics(), false, rate, update); } REQUIRE(rate.pending == 0.f); - CHECK(smoke::vehicle_spawn_count(vehicle.mover(), true, rate, update) >= 1.f); + CHECK(smoke::vehicle_spawn_count(vehicle.physics(), true, rate, update) >= 1.f); } TEST_CASE("smoke: the engine adds to the steady rate of the source") { @@ -61,18 +61,18 @@ TEST_CASE("smoke: the engine adds to the steady rate of the source") { auto const steady{source.rate * update}; // the rate of a source of the scenery vehicle->EnginePower = 0.0; - CHECK(smoke::vehicle_spawn_count(vehicle.mover(), true, source, update) == doctest::Approx(steady)); + CHECK(smoke::vehicle_spawn_count(vehicle.physics(), true, source, update) == doctest::Approx(steady)); vehicle->EnginePower = 400.0; - auto const working{smoke::vehicle_spawn_count(vehicle.mover(), true, source, update)}; + auto const working{smoke::vehicle_spawn_count(vehicle.physics(), true, source, update)}; CHECK(working > steady); // the faster the starting engine turns, the more it puffs vehicle->diesel.spinningUp = true; vehicle->enrot = 100.0; - auto const slow{smoke::vehicle_spawn_count(vehicle.mover(), true, source, update)}; + auto const slow{smoke::vehicle_spawn_count(vehicle.physics(), true, source, update)}; vehicle->enrot = 400.0; - CHECK(smoke::vehicle_spawn_count(vehicle.mover(), true, source, update) > slow); + CHECK(smoke::vehicle_spawn_count(vehicle.physics(), true, source, update) > slow); } TEST_CASE("smoke: the pending particles never outgrow the room of the source") { @@ -82,7 +82,7 @@ TEST_CASE("smoke: the pending particles never outgrow the room of the source") { auto rate{source}; rate.pending = 99.f; - CHECK(smoke::vehicle_spawn_count(vehicle.mover(), true, rate, 10.0) == rate.limit); + CHECK(smoke::vehicle_spawn_count(vehicle.physics(), true, rate, 10.0) == rate.limit); } TEST_CASE("smoke: an engine the starter turns lets out no smoke until it fires (#523)") { @@ -92,10 +92,10 @@ TEST_CASE("smoke: an engine the starter turns lets out no smoke until it fires ( pending.pending = 5.f; vehicle->diesel.firingCountdown = 0.5; - CHECK(smoke::vehicle_spawn_count(vehicle.mover(), true, pending, update) == 0.f); + CHECK(smoke::vehicle_spawn_count(vehicle.physics(), true, pending, update) == 0.f); vehicle->diesel.firingCountdown = 0.0; - CHECK(smoke::vehicle_spawn_count(vehicle.mover(), true, pending, update) >= 1.f); + CHECK(smoke::vehicle_spawn_count(vehicle.physics(), true, pending, update) >= 1.f); } namespace { @@ -123,12 +123,12 @@ TEST_CASE("smoke: a real diesel smokes only once its engine has fired, SmokeDela REQUIRE(start_engine(driven, track)); // the engine started less than a second ago: the starter still turns it CHECK(locomotive->diesel.firingCountdown > 0.5); - CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) == 0.f); + CHECK(smoke::vehicle_spawn_count(locomotive.physics(), true, source, update) == 0.f); // it has fired since test::drive(driven, track, 3.0); CHECK(locomotive->Mains); CHECK(locomotive->diesel.firingCountdown == 0.0); - CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) >= 1.f); + CHECK(smoke::vehicle_spawn_count(locomotive.physics(), true, source, update) >= 1.f); } { // a longer delay from the .fiz @@ -136,9 +136,9 @@ TEST_CASE("smoke: a real diesel smokes only once its engine has fired, SmokeDela auto const driven{test::driving(locomotive)}; REQUIRE(start_engine(driven, track)); test::drive(driven, track, 3.0); - CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) == 0.f); + CHECK(smoke::vehicle_spawn_count(locomotive.physics(), true, source, update) == 0.f); test::drive(driven, track, 3.0); - CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) >= 1.f); + CHECK(smoke::vehicle_spawn_count(locomotive.physics(), true, source, update) >= 1.f); } } } @@ -156,6 +156,6 @@ TEST_CASE("smoke: without SmokeDelay in its .fiz a diesel smokes as soon as the auto const driven{test::driving(locomotive)}; REQUIRE(start_engine(driven, track)); CHECK(locomotive->diesel.firingCountdown == 0.0); - CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) >= 1.f); + CHECK(smoke::vehicle_spawn_count(locomotive.physics(), true, source, update) >= 1.f); } } diff --git a/tests/unit/test_speed_control.cpp b/tests/unit/test_speed_control.cpp index 3f8a9a9ec..b54a6aa9c 100644 --- a/tests/unit/test_speed_control.cpp +++ b/tests/unit/test_speed_control.cpp @@ -32,7 +32,7 @@ constexpr int dg_lower{4}; constexpr int dg_hold{5}; constexpr int dg_raise{6}; -void move_to(TMoverParameters &Vehicle, int const Position) { +void move_to(physics::Vehicle &Vehicle, int const Position) { while (Vehicle.MainCtrlPos < Position && Vehicle.IncMainCtrl(1)) { // all the work is done in the condition } @@ -260,7 +260,7 @@ TEST_CASE("speed control apart: which vehicles' cruise control has a switch of i namespace { // Seconds of the scenario going on, a second at a time, counting the seconds with the field shunted and not -void count_shunting(scenario &Scenario, TMoverParameters const &Vehicle, int const Seconds, int &Shunted, int &Unshunted) { +void count_shunting(scenario &Scenario, physics::Vehicle const &Vehicle, int const Seconds, int &Shunted, int &Unshunted) { for (int second = 0; second < Seconds; ++second) { Scenario.wait(1.0); ++(Vehicle.ScndCtrlPos > 0 ? Shunted : Unshunted); diff --git a/tests/unit/test_timetable.cpp b/tests/unit/test_timetable.cpp index 1066edd29..dff4ec6e4 100644 --- a/tests/unit/test_timetable.cpp +++ b/tests/unit/test_timetable.cpp @@ -2,7 +2,7 @@ #include "doctest.h" #include "vehicle.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "utilities/utilities.h" #include "vehicle/timetableservice.h" #include "world/timetablereader.h" @@ -269,20 +269,20 @@ TEST_CASE("timetable: the AI opens the doors from the cab as the vehicle and the auto const notcentral{flags(no, unset, unset, unset)}; unit->Doors.open_control = control_t::driver; - CHECK(timetable::opens_doors(unit.mover(), {})); - CHECK(timetable::opens_doors(unit.mover(), notcentral)); // the driver's doors open only from the cab + CHECK(timetable::opens_doors(unit.physics(), {})); + CHECK(timetable::opens_doors(unit.physics(), notcentral)); // the driver's doors open only from the cab unit->Doors.open_control = control_t::conductor; - CHECK(timetable::opens_doors(unit.mover(), {})); + CHECK(timetable::opens_doors(unit.physics(), {})); // doors of mixed control are left to the passengers, unless the timetable has the driver open them all unit->Doors.open_control = control_t::mixed; - CHECK_FALSE(timetable::opens_doors(unit.mover(), {})); - CHECK_FALSE(timetable::opens_doors(unit.mover(), notcentral)); - CHECK(timetable::opens_doors(unit.mover(), central)); + CHECK_FALSE(timetable::opens_doors(unit.physics(), {})); + CHECK_FALSE(timetable::opens_doors(unit.physics(), notcentral)); + CHECK(timetable::opens_doors(unit.physics(), central)); // the passengers' own doors and the automatic ones can't be opened from the cab unit->Doors.open_control = control_t::passenger; - CHECK_FALSE(timetable::opens_doors(unit.mover(), central)); + CHECK_FALSE(timetable::opens_doors(unit.physics(), central)); unit->Doors.open_control = control_t::autonomous; - CHECK_FALSE(timetable::opens_doors(unit.mover(), central)); + CHECK_FALSE(timetable::opens_doors(unit.physics(), central)); } TEST_CASE("timetable: the doorsteps, the conductor and the brake test as the timetable says") { diff --git a/tests/unit/test_traction.cpp b/tests/unit/test_traction.cpp index 6a9bb544c..f3f2acefa 100644 --- a/tests/unit/test_traction.cpp +++ b/tests/unit/test_traction.cpp @@ -24,7 +24,7 @@ TEST_CASE("traction: every real powered vehicle started up, driven to full power CAPTURE(path); test::reseed_random(); vehicle real{definition::fiz(path), 0.0, "test", 1}; - if (false == test::is_powered(real.mover())) { + if (false == test::is_powered(real.physics())) { continue; } using namespace test::channels; diff --git a/tests/unit/test_wheelslip.cpp b/tests/unit/test_wheelslip.cpp index 9b39e82c6..842eb31e2 100644 --- a/tests/unit/test_wheelslip.cpp +++ b/tests/unit/test_wheelslip.cpp @@ -36,7 +36,7 @@ braking_result brake_to_stop_then_stand(vehicle &Coach, track const &Braking, tr } // namespace -// the engine doesn't let a stopped, braked vehicle slip (the Vel > 0.1 trap in TMoverParameters::ComputeTotalForce), +// the engine doesn't let a stopped, braked vehicle slip (the Vel > 0.1 trap in physics::Vehicle::ComputeTotalForce), // so a wagon which stopped in a skid should be no different from one which stopped without it. it used to stay // skidding instead, with its brakes capped by the sliding adhesion, and slid or crept away (eu07/maszyna#479) TEST_CASE("wheelslip: a wagon which stopped in a skid holds like one which stopped without it") { diff --git a/tests/unit/vehicle.cpp b/tests/unit/vehicle.cpp index fa9c99746..37bb1aab8 100644 --- a/tests/unit/vehicle.cpp +++ b/tests/unit/vehicle.cpp @@ -125,32 +125,32 @@ std::string definition::text() const { vehicle::vehicle(definition const &Definition, double Velocity, std::string const &Name, int Cab) : m_cab(Cab) { // the same steps as TDynamicObject::Init(), for a vehicle set the usual way round (iDirection 1) auto const typename_{Definition.type_name().empty() ? Name : Definition.type_name()}; - m_mover = std::make_unique(Velocity, typename_, Name, Cab); - if (false == m_mover->LoadFIZ_Text(Definition.text())) { + m_physics = std::make_unique(Velocity, typename_, Name, Cab); + if (false == m_physics->LoadFIZ_Text(Definition.text())) { throw definition_error("the test vehicle definition didn't load"); } - m_mover->AssignLoad("", 0.f); - m_mover->ComputeMass(); + m_physics->AssignLoad("", 0.f); + m_physics->ComputeMass(); auto const driveractive{Velocity != 0.0}; - if (false == m_mover->CheckLocomotiveParameters(driveractive, (Velocity > 0 ? 1 : -1) * Cab)) { + if (false == m_physics->CheckLocomotiveParameters(driveractive, (Velocity > 0 ? 1 : -1) * Cab)) { throw definition_error("parameters mismatch in the test vehicle definition"); } - m_mover->MainCtrlPos = m_mover->MainCtrlNoPowerPos(); - m_mover->LocalBrakePosA = 0.0; + m_physics->MainCtrlPos = m_physics->MainCtrlNoPowerPos(); + m_physics->LocalBrakePosA = 0.0; if (driveractive) { - m_mover->BrakeCtrlPos = static_cast(std::floor(m_mover->Handle->GetPos(Cab == 0 ? bh_NP : bh_RP))); + m_physics->BrakeCtrlPos = static_cast(std::floor(m_physics->Handle->GetPos(Cab == 0 ? bh_NP : bh_RP))); // a driver keeps a vehicle on standby on its independent brake - if (Cab != 0 && m_mover->LocalBrake != TLocalBrake::ManualBrake && Velocity < 1.0) { - m_mover->IncLocalBrakeLevel(LocalBrakePosNo); - if (m_mover->EIMCtrlEmergency) { - m_mover->DecLocalBrakeLevel(1); + if (Cab != 0 && m_physics->LocalBrake != TLocalBrake::ManualBrake && Velocity < 1.0) { + m_physics->IncLocalBrakeLevel(LocalBrakePosNo); + if (m_physics->EIMCtrlEmergency) { + m_physics->DecLocalBrakeLevel(1); } } } else { - m_mover->BrakeCtrlPos = static_cast(std::floor(m_mover->Handle->GetPos(bh_NP))); + m_physics->BrakeCtrlPos = static_cast(std::floor(m_physics->Handle->GetPos(bh_NP))); } - m_mover->BrakeLevelSet(m_mover->BrakeCtrlPos); + m_physics->BrakeLevelSet(m_physics->BrakeCtrlPos); } void vehicle::step(track const &Track, double Dt) { @@ -161,7 +161,7 @@ void vehicle::step(track const &Track, double Dt) { fast_move(Track, Dt, location); } forces(Dt); - move(Track, Dt, location, m_mover->PipePress); + move(Track, Dt, location, m_physics->PipePress); } namespace { @@ -175,7 +175,7 @@ TTrackShape shape_of(track const &Track) { return shape; } -TTrackParam parameters_of(track const &Track, TMoverParameters const &Mover) { +TTrackParam parameters_of(track const &Track, physics::Vehicle const &Physics) { TTrackParam param; param.Width = Track.width; param.friction = Track.friction; @@ -185,7 +185,7 @@ TTrackParam parameters_of(track const &Track, TMoverParameters const &Mover) { param.CategoryFlag = Track.category; } else { - param.CategoryFlag = Mover.CategoryFlag != 0 ? Mover.CategoryFlag : 1; + param.CategoryFlag = Physics.CategoryFlag != 0 ? Physics.CategoryFlag : 1; } return param; } @@ -194,71 +194,71 @@ TTrackParam parameters_of(track const &Track, TMoverParameters const &Mover) { double vehicle::fast_move(track const &Track, double Dt, TLocation const &Location) { // TDynamicObject::FastUpdate(), the iterations of a frame before the last one - auto param{parameters_of(Track, *m_mover)}; + auto param{parameters_of(Track, *m_physics)}; param.DamageFlag = m_trackdamage; - return m_mover->FastComputeMovement(Dt, shape_of(Track), param, Location, TRotation{0.0, 0.0, 0.0}); + return m_physics->FastComputeMovement(Dt, shape_of(Track), param, Location, TRotation{0.0, 0.0, 0.0}); } void vehicle::begin_step() { // the conditions the test keeps if (m_pipepressure >= 0.0) { - m_mover->Pipe->CreatePress(m_pipepressure); + m_physics->Pipe->CreatePress(m_pipepressure); } - if (m_reservoirpressure >= 0.0 && m_mover->VeselVolume > 0.0) { - m_mover->CompressedVolume = m_reservoirpressure * m_mover->VeselVolume; + if (m_reservoirpressure >= 0.0 && m_physics->VeselVolume > 0.0) { + m_physics->CompressedVolume = m_reservoirpressure * m_physics->VeselVolume; } // vehicle_table::update(), before the forces - m_mover->ComputeConstans(); + m_physics->ComputeConstans(); } void vehicle::forces(double Dt) { // TDynamicObject::UpdateForce() - m_mover->ComputeTotalForce(Dt); + m_physics->ComputeTotalForce(Dt); } double vehicle::move(track const &Track, double Dt, TLocation const &Location, double Trainpipe) { auto const shape{shape_of(Track)}; - auto param{parameters_of(Track, *m_mover)}; + auto param{parameters_of(Track, *m_physics)}; param.DamageFlag = m_trackdamage; TRotation const rotation{0.0, 0.0, 0.0}; // what TDynamicObject::Update() does before the movement. a raised pantograph touches the wire at once, // the game animates its rise - auto &mover{*m_mover}; - mover.PantFrontVolt = mover.Pantographs[VehicleEnd::front].is_active ? Track.voltage : 0.0; - mover.PantRearVolt = mover.Pantographs[VehicleEnd::rear].is_active ? Track.voltage : 0.0; + auto &physics{*m_physics}; + physics.PantFrontVolt = physics.Pantographs[VehicleEnd::front].is_active ? Track.voltage : 0.0; + physics.PantRearVolt = physics.Pantographs[VehicleEnd::rear].is_active ? Track.voltage : 0.0; TTractionParam traction; traction.TractionVoltage = - mover.EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? std::max(std::abs(mover.PantRearVolt), std::abs(mover.PantFrontVolt)) : 0.95 * mover.EnginePowerSource.MaxVoltage; + physics.EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? std::max(std::abs(physics.PantRearVolt), std::abs(physics.PantFrontVolt)) : 0.95 * physics.EnginePowerSource.MaxVoltage; traction.TractionFreq = 0; traction.TractionMaxCurrent = 7500; traction.TractionResistivity = 0.3; - mover.PantographVoltage = traction.TractionVoltage; + physics.PantographVoltage = traction.TractionVoltage; if (m_cab != 0) { using enum TEngineType; // the driver's own vehicle, which gets the average pressure of the train's brake pipe - mover.EqvtPipePress = Trainpipe; - if (auto const diesel{mover.EngineType == DieselEngine || mover.EngineType == DieselElectric}; diesel && mover.EIMCtrlType > 0) { - mover.CheckEIMIC(Dt); - if (mover.SpeedCtrl) { - mover.CheckSpeedCtrl(Dt); + physics.EqvtPipePress = Trainpipe; + if (auto const diesel{physics.EngineType == DieselEngine || physics.EngineType == DieselElectric}; diesel && physics.EIMCtrlType > 0) { + physics.CheckEIMIC(Dt); + if (physics.SpeedCtrl) { + physics.CheckSpeedCtrl(Dt); } - mover.eimic_real = std::min(mover.eimic, mover.eimicSpeedCtrl); + physics.eimic_real = std::min(physics.eimic, physics.eimicSpeedCtrl); } - if (mover.EngineType == ElectricInductionMotor) { + if (physics.EngineType == ElectricInductionMotor) { // the share of the electric and pneumatic brake over the train (TDynamicObject's MED) isn't here - mover.CheckEIMIC(Dt); - mover.CheckSpeedCtrl(Dt); - mover.eimic_real = std::min(mover.eimic, mover.eimicSpeedCtrl); + physics.CheckEIMIC(Dt); + physics.CheckSpeedCtrl(Dt); + physics.eimic_real = std::min(physics.eimic, physics.eimicSpeedCtrl); } } // the whole frame's time, of all its iterations auto const frame{Dt * Track.iterations}; - auto const distance{m_mover->ComputeMovement(Dt, frame, shape, param, traction, Location, rotation)}; + auto const distance{m_physics->ComputeMovement(Dt, frame, shape, param, traction, Location, rotation)}; m_time += frame; if (m_trace != nullptr) { - m_trace->sample(m_time, *m_mover); + m_trace->sample(m_time, *m_physics); } return distance; } @@ -271,7 +271,7 @@ void vehicle::run(double Seconds, track const &Track, double Dt) { } } -// the physics reaches the vehicle next to it through TDynamicObject::MoverParameters only (neighbour_data). the +// the physics reaches the vehicle next to it through TDynamicObject::physics only (neighbour_data). the // tests can't make a TDynamicObject, whose constructor and members come with the rest of the engine, so the // neighbour is a zeroed block of its size with just that pointer set: enough for the physics, which reads nothing // else of it, and never used as a whole object @@ -279,9 +279,9 @@ static_assert(alignof(TDynamicObject) <= __STDCPP_DEFAULT_NEW_ALIGNMENT__); namespace { -std::vector make_standin(TMoverParameters &Mover) { +std::vector make_standin(physics::Vehicle &Physics) { std::vector standin(sizeof(TDynamicObject)); // zeroed - reinterpret_cast(standin.data())->MoverParameters = &Mover; // NOSONAR see above + reinterpret_cast(standin.data())->physics = &Physics; // NOSONAR see above return standin; } @@ -292,17 +292,17 @@ TDynamicObject *as_neighbour(std::byte *Standin) { } // namespace pair::pair(vehicle &First, VehicleEnd FirstEnd, vehicle &Second, VehicleEnd SecondEnd, double Gap) { - auto const &first{First.mover()}; - auto const &second{Second.mover()}; + auto const &first{First.physics()}; + auto const &second{Second.physics()}; // the first vehicle in the middle, its FirstEnd towards the second one - m_vehicles[0] = {&First, FirstEnd, 0.0, FirstEnd == VehicleEnd::front ? 1.0 : -1.0, make_standin(First.mover())}; - m_vehicles[1] = {&Second, SecondEnd, 0.5 * first.Dim.L + Gap + 0.5 * second.Dim.L, SecondEnd == VehicleEnd::front ? -1.0 : 1.0, make_standin(Second.mover())}; + m_vehicles[0] = {&First, FirstEnd, 0.0, FirstEnd == VehicleEnd::front ? 1.0 : -1.0, make_standin(First.physics())}; + m_vehicles[1] = {&Second, SecondEnd, 0.5 * first.Dim.L + Gap + 0.5 * second.Dim.L, SecondEnd == VehicleEnd::front ? -1.0 : 1.0, make_standin(Second.physics())}; } pair::~pair() { for (auto const &placed : m_vehicles) { // the vehicles outlive the pair, they mustn't point at its stand-ins - for (auto &neighbour : placed.owner->mover().Neighbours) { + for (auto &neighbour : placed.owner->physics().Neighbours) { neighbour = neighbour_data(); } } @@ -311,19 +311,19 @@ pair::~pair() { void pair::find_neighbours() { // as TDynamicObject::update_neighbours() for (auto const &placed : m_vehicles) { - placed.owner->mover().Loc = TLocation{placed.position, 0.0, 0.0}; + placed.owner->physics().Loc = TLocation{placed.position, 0.0, 0.0}; } for (int i = 0; i < 2; ++i) { auto const &self{m_vehicles[i]}; auto &other{m_vehicles[1 - i]}; // its stand-in is what this one points at - auto &mover{self.owner->mover()}; - auto const &othermover{other.owner->mover()}; - auto &neighbour{mover.Neighbours[self.end]}; + auto &physics{self.owner->physics()}; + auto const &otherPhysics{other.owner->physics()}; + auto &neighbour{physics.Neighbours[self.end]}; neighbour.vehicle = as_neighbour(other.standin.data()); neighbour.vehicle_end = NumberOf(other.end); - neighbour.distance = static_cast(TMoverParameters::CouplerDist(&mover, &othermover) - mover.Couplers[self.end].adapter_length - - othermover.Couplers[other.end].adapter_length); - mover.Neighbours[Opposite(self.end)] = neighbour_data(); + neighbour.distance = static_cast(physics::Vehicle::CouplerDist(&physics, &otherPhysics) - physics.Couplers[self.end].adapter_length - + otherPhysics.Couplers[other.end].adapter_length); + physics.Neighbours[Opposite(self.end)] = neighbour_data(); } } @@ -334,11 +334,11 @@ void pair::step(track const &Track, double Dt) { placed.owner->forces(Dt); } for (auto &placed : m_vehicles) { - auto const &mover{placed.owner->mover()}; - placed.position += placed.heading * placed.owner->move(Track, Dt, TLocation{placed.position, 0.0, 0.0}, mover.PipePress); + auto const &physics{placed.owner->physics()}; + placed.position += placed.heading * placed.owner->move(Track, Dt, TLocation{placed.position, 0.0, 0.0}, physics.PipePress); } // vehicle_table::update_brake_pipes() - TMoverParameters::UpdatePipeCouplers({&m_vehicles[0].owner->mover(), &m_vehicles[1].owner->mover()}, Dt); + physics::Vehicle::UpdatePipeCouplers({&m_vehicles[0].owner->physics(), &m_vehicles[1].owner->physics()}, Dt); } void pair::run(double Seconds, track const &Track, double Dt) { @@ -350,13 +350,13 @@ void pair::run(double Seconds, track const &Track, double Dt) { } double pair::gap() const { - auto const &first{m_vehicles[0].owner->mover()}; - auto const &second{m_vehicles[1].owner->mover()}; + auto const &first{m_vehicles[0].owner->physics()}; + auto const &second{m_vehicles[1].owner->physics()}; return std::abs(m_vehicles[1].position - m_vehicles[0].position) - 0.5 * (first.Dim.L + second.Dim.L); } CouplingSet pair::coupling() const { - return m_vehicles[0].owner->mover().Couplers[m_vehicles[0].end].CouplingFlag; + return m_vehicles[0].owner->physics().Couplers[m_vehicles[0].end].CouplingFlag; } void reseed_random() { diff --git a/tests/unit/vehicle.h b/tests/unit/vehicle.h index f83c50b7e..51362d9c1 100644 --- a/tests/unit/vehicle.h +++ b/tests/unit/vehicle.h @@ -9,7 +9,7 @@ #include -#include "physics/mover.h" +#include "physics/vehicle.h" namespace test { @@ -87,8 +87,8 @@ class vehicle { public: explicit vehicle(definition const &Definition, double Velocity = 0.0, std::string const &Name = "test", int Cab = 0); - TMoverParameters &mover() { return *m_mover; } - TMoverParameters *operator->() { return m_mover.get(); } + physics::Vehicle &physics() { return *m_physics; } + physics::Vehicle *operator->() { return m_physics.get(); } // keeps the brake pipe at the given pressure [bar], as a locomotive coupled to the vehicle would; // a negative value leaves the pipe alone @@ -116,10 +116,10 @@ public: double move(track const &Track, double Dt, TLocation const &Location, double Trainpipe); // vehicle speed in kilometres per hour, negative when moving backwards - double speed() const { return m_mover->V * 3.6; } + double speed() const { return m_physics->V * 3.6; } private: - std::unique_ptr m_mover; + std::unique_ptr m_physics; int m_cab{0}; double m_pipepressure{-1.0}; double m_reservoirpressure{-1.0}; diff --git a/tools/rename/mover_to_physics.py b/tools/rename/mover_to_physics.py new file mode 100644 index 000000000..bc1b8885f --- /dev/null +++ b/tools/rename/mover_to_physics.py @@ -0,0 +1,190 @@ +#!/usr/bin/env python3 +"""Renames the physics of a vehicle from TMoverParameters, "the mover", to physics::Vehicle. + +Run it from the root of the repository, on any branch, before merging a branch made before the rename into one +made after it (or the other way round): it turns the old names of the branch into the new ones, so the merge +doesn't conflict over them. Running it again changes nothing. + + python tools/rename/mover_to_physics.py # rename + python tools/rename/mover_to_physics.py --check # only list what it would change, exit 1 if anything + +What it renames, in the code and in the comments (never inside string literals, whose text the game shows, logs or +looks up): + + physics/mover.h physics/vehicle.h + TMoverParameters physics::Vehicle (the class is in namespace physics) + TDynamicObject::MoverParameters physics + mvOccupied, mvControlled occupied, controlled + mvSecond, mvThird secondUnit, thirdUnit + mvPantographUnit pantographUnit + mover, Mover, movers physics, Physics, vehicles (the locals and the parameters) + m_mover, othermover, ... m_physics, otherPhysics, ... + +The "movers" of the editor, the tracks a slide moves, keep their name (EDITOR_MOVERS below). + +One case is left to the hand: a member function of TDynamicObject whose local `mover` is its own `MoverParameters` +(`auto &mover { *MoverParameters };`) becomes `auto &physics { *physics };`, which the compiler stops at ("cannot be +used before it is initialized"). Drop the line and write `physics->` for `physics.` in the rest of the function. +""" + +import re +import subprocess +import sys +from pathlib import Path + +OLD_HEADER = "physics/mover.h" +NEW_HEADER = "physics/vehicle.h" +EXTENSIONS = (".cpp", ".h", ".hpp", ".inl", ".md", ".txt", ".cmake") +SKIP_PREFIXES = ("ref/", "build/", "tools/rename/") +# where a mover is a track moved by a slide of the editor, not the physics of a vehicle +EDITOR_MOVERS = {"application/editormode.h", "application/editormodeswitchslide.cpp"} + +# in the order they apply: the longer and the special forms first +RENAMES = [ + (r"\bmover\.h\b", "vehicle.h"), + (r"\bTMoverParameters::TMoverParameters\b", "physics::Vehicle::Vehicle"), + (r"\bTMoverParameters::~TMoverParameters\b", "physics::Vehicle::~Vehicle"), + (r"\bclass TMoverParameters;", "namespace physics { class Vehicle; }"), + (r"\bT_MoverParameters\b", "physics::Vehicle"), + (r"\bTMoverParameters\b", "physics::Vehicle"), + (r"\bMoverParameters\b", "physics"), + (r"\bmvOccupied\b", "occupied"), + (r"\bmvControlled\b", "controlled"), + (r"\bmvSecond\b", "secondUnit"), + (r"\bmvThird\b", "thirdUnit"), + (r"\bmvPantographUnit\b", "pantographUnit"), + (r"\bm_mover\b", "m_physics"), + (r"\bothermover\b", "otherPhysics"), + (r"\bcurrentMover\b", "currentPhysics"), + (r"\bfrom_movers\b", "from_vehicles"), + (r"\brenderMoverEventSounds\b", "renderPhysicsEventSounds"), + (r"\bmoverparam\b", "the physics"), + (r"\b_mover__(\d)\b", r"_vehicle__\1"), +] +LOCAL_RENAMES = [ + (r"\bmover's\b", "physics'"), + (r"\bmovers\b", "vehicles"), + (r"\bmover\b", "physics"), + (r"\bMover\b", "Physics"), +] + +# a comment, or a string or a character literal (raw strings included): the comments come first, so an apostrophe in +# one doesn't start a character literal +TOKEN = re.compile(r'//[^\n]*|/\*.*?\*/|R"([^()\\\s]{0,16})\(.*?\)\1"|"(?:\\.|[^"\\\n])*"|\'(?:\\.|[^\'\\\n])*\'', re.S) + + +def tracked_files(): + names = subprocess.run(["git", "ls-files"], capture_output=True, text=True, check=True).stdout.split("\n") + for name in names: + if not name or name.startswith(SKIP_PREFIXES): + continue + if name.endswith(EXTENSIONS) or Path(name).name == "CMakeLists.txt": + yield name + + +def rename_outside_literals(text, renames): + """applies the renames to the code and the comments, not to the string and character literals""" + out = [] + last = 0 + for token in TOKEN.finditer(text): + out.append(apply(text[last:token.start()], renames)) + is_comment = token.group(0).startswith(("//", "/*")) + out.append(apply(token.group(0), renames) if is_comment else token.group(0)) + last = token.end() + out.append(apply(text[last:], renames)) + return "".join(out) + + +def apply(chunk, renames): + for pattern, replacement in renames: + chunk = re.sub(pattern, replacement, chunk) + return chunk + + +def rename_file(name, text): + is_code = name.endswith((".cpp", ".h", ".hpp", ".inl")) + # the header where it is included or listed + text = text.replace('"' + OLD_HEADER + '"', '"' + NEW_HEADER + '"') + text = text.replace(OLD_HEADER, NEW_HEADER) + renames = RENAMES + ([] if name in EDITOR_MOVERS else LOCAL_RENAMES) + if is_code: + text = rename_outside_literals(text, renames) + else: + text = apply(text, renames) + if name == NEW_HEADER: + text = wrap_in_namespace(text) + return text + + +def wrap_in_namespace(text): + """puts the class of the physics of a vehicle into namespace physics, once""" + if "\nnamespace physics\n{\n\nclass Vehicle\n" in text.replace("\r\n", "\n"): + return text + nl = "\r\n" if "\r\n" in text else "\n" + head = "class physics::Vehicle" + nl + "{" + start = text.find(head) + if start < 0: + return text + # the end of the class: the brace that closes the one after its name, the braces of the comments and the literals + # not counted + depth = 0 + end = None + i = start + len(head) - 1 + while i < len(text): + token = TOKEN.match(text, i) + if token is not None: + i = token.end() + continue + if text[i] == "{": + depth += 1 + elif text[i] == "}": + depth -= 1 + if depth == 0: + end = text.index(";", i) + 1 + break + i += 1 + if end is None: + raise SystemExit("the end of class physics::Vehicle not found in " + NEW_HEADER) + body = text[start + len(head):end] + # inside the class it is just Vehicle: the constructor and the destructor + body = re.sub(r"(\n\s*)physics::Vehicle\(", r"\1Vehicle(", body) + body = re.sub(r"(\n\s*)~physics::Vehicle\(", r"\1~Vehicle(", body) + wrapped = "namespace physics" + nl + "{" + nl + nl + "class Vehicle" + nl + "{" + body + nl + nl + "} // namespace physics" + text = text[:start] + wrapped + text[end:] + # the types before the class point at it + forward = "namespace physics" + nl + "{" + nl + "class Vehicle;" + nl + "}" + nl + anchor = "class cParser;" + nl + if forward not in text and anchor in text: + text = text.replace(anchor, anchor + forward, 1) + return text + + +def main(): + check = "--check" in sys.argv + changed = [] + if Path(OLD_HEADER).exists(): + changed.append(OLD_HEADER + " -> " + NEW_HEADER) + if not check: + subprocess.run(["git", "mv", OLD_HEADER, NEW_HEADER], check=True) + for name in tracked_files(): + path = Path(name) + if not path.exists(): + continue + raw = path.read_bytes() + try: + text = raw.decode("utf-8") + except UnicodeDecodeError: + continue + renamed = rename_file(name, text) + if renamed != text: + changed.append(name) + if not check: + path.write_bytes(renamed.encode("utf-8")) + for name in changed: + print(name) + print(f"{len(changed)} file(s) {'to change' if check else 'changed'}") + return 1 if check and changed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/utilities/Classes.h b/utilities/Classes.h index b8c470ec9..1291d8433 100644 --- a/utilities/Classes.h +++ b/utilities/Classes.h @@ -32,7 +32,7 @@ class TTraction; // drut class TTractionPowerSource; // zasilanie drutów class TCamera; class scenario_time; -class TMoverParameters; +namespace physics { class Vehicle; } class ui_layer; class editor_ui; class itemproperties_panel; diff --git a/utilities/Globals.h b/utilities/Globals.h index a98d5e60a..43dfcb9d6 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -147,7 +147,7 @@ struct global_settings { std::string Weather{ "cloudy:" }; // current weather std::string Period{}; // time of the day, based on sun position bool FullPhysics{ true }; // full calculations performed for each simulation step - bool physics_sleepheld{ false }; // vehicles standing still and held by their brakes let their physics sleep, see TMoverParameters::accelerating() + bool physics_sleepheld{ false }; // vehicles standing still and held by their brakes let their physics sleep, see physics::Vehicle::accelerating() bool physics_roadlod{ false }; // road vehicles far from the camera go by one step of the physics in a frame, see vehicle_table::update() float physics_pipewake{ 0.f }; // bar: air flowing along a pipe wakes the physics of a vehicle when it changes its pressure by more than this. 0: any flow does bool performance_multithreading{ true }; // work split over the logical cores of the machine (worker_pool), as many as each job is worth @@ -360,7 +360,7 @@ struct global_settings { enum class track_buckling_mode { off, scenery, automatic }; track_buckling_mode track_buckling = track_buckling_mode::scenery; // the physical model of the couplings (physics/couplerphysics.h): progressive buffers and draw gear with hysteresis, - // the play of the coupling, its yield and breaking; the legacy model of TMoverParameters::CouplerForce() without it. + // the play of the coupling, its yield and breaking; the legacy model of physics::Vehicle::CouplerForce() without it. // it covers the player's train and the trains it closes in on (vehicle_table::update_coupler_physics()), or every // train with coupler_physics_all bool coupler_physics = false; diff --git a/utilities/Timer.h b/utilities/Timer.h index 7976d51d2..3eed6eb15 100644 --- a/utilities/Timer.h +++ b/utilities/Timer.h @@ -88,7 +88,7 @@ private: float m_accumulator { 0.f }; }; -// what resets TMoverParameters::LastSwitchingTime, which keeps the physics of a vehicle on for 5 s: counted over a second, +// what resets physics::Vehicle::LastSwitchingTime, which keeps the physics of a vehicle on for 5 s: counted over a second, // with the vehicle which did it most often, for the debug panel class switching_counter { @@ -98,7 +98,7 @@ public: compressor_off, mains, diesel, - // switch_physics( true ) of a vehicle whose physics was off, by TMoverParameters::wake_cause, in its order + // switch_physics( true ) of a vehicle whose physics was off, by physics::Vehicle::wake_cause, in its order wake, wake_mainpipe, wake_scndpipe, @@ -213,12 +213,12 @@ struct subsystem_stopwatches { unsigned int largestgroup { 0 }; unsigned int maingroups { 0 }; // rail vehicles standing still (below 0.01 km/h) with the physics on, and what keeps it on by the test of - // TMoverParameters::ComputeTotalForce(); a vehicle can have several of these + // physics::Vehicle::ComputeTotalForce(); a vehicle can have several of these struct awake_reasons { unsigned int vehicles { 0 }; unsigned int cab { 0 }; // CabActive unsigned int speed { 0 }; // Vel above 0.0001 km/h - unsigned int acceleration { 0 }; // AccS above 0.0001 m/s2, and not held by the brakes (TMoverParameters::accelerating()) + unsigned int acceleration { 0 }; // AccS above 0.0001 m/s2, and not held by the brakes (physics::Vehicle::accelerating()) unsigned int switching { 0 }; // LastSwitchingTime below 5 s unsigned int multipleunit { 0 }; // EZT, DMU unsigned int neighbour { 0 }; // a neighbour moving or accelerating diff --git a/utilities/motiontelemetry.cpp b/utilities/motiontelemetry.cpp index ed2e9f8fe..e8995d716 100644 --- a/utilities/motiontelemetry.cpp +++ b/utilities/motiontelemetry.cpp @@ -6,7 +6,7 @@ #include "utilities/Timer.h" #include "vehicle/Driver.h" #include "simulation/simulation.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #ifdef _WIN32 #include diff --git a/utilities/translation.cpp b/utilities/translation.cpp index ec695b05b..0d007bbd8 100644 --- a/utilities/translation.cpp +++ b/utilities/translation.cpp @@ -15,7 +15,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/translation.h" #include "utilities/Logs.h" #include "utilities/Globals.h" -#include "physics/mover.h" +#include "physics/vehicle.h" void locale::init() { diff --git a/utilities/uart.cpp b/utilities/uart.cpp index 902c95b5f..df6544776 100644 --- a/utilities/uart.cpp +++ b/utilities/uart.cpp @@ -9,7 +9,7 @@ #include "utilities/utilities.h" #include "simulation/simulationtime.h" #include "application/application.h" -#include "physics/mover.h" +#include "physics/vehicle.h" const char* const uart_baudrates_list[] = { "300", diff --git a/vehicle/Camera.cpp b/vehicle/Camera.cpp index 234483ee4..51b13e87e 100644 --- a/vehicle/Camera.cpp +++ b/vehicle/Camera.cpp @@ -17,7 +17,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "vehicle/Driver.h" #include "vehicle/DynObj.h" -#include "physics/mover.h" +#include "physics/vehicle.h" //--------------------------------------------------------------------------- diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 2cde64ee6..2ac5c89f8 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -244,11 +244,11 @@ public: bool primary() const { return drivingFlags.primary; }; inline - TMoverParameters const *Controlling() const { + physics::Vehicle const *Controlling() const { return mvControlling; } inline - TMoverParameters const *Occupied() const { - return mvOccupied; } + physics::Vehicle const *Occupied() const { + return occupied; } void DirectionInitial(); void DirectionChange(); inline @@ -310,7 +310,7 @@ private: void WaitingSet( double Seconds ); void DirectionForward( bool forward ); void ZeroDirection(); - int OrderDirectionChange( int newdir, TMoverParameters *Vehicle ); + int OrderDirectionChange( int newdir, physics::Vehicle *Vehicle ); void sync_consist_reversers(); void Lights( int head, int rear ); std::string StopReasonText() const; @@ -420,9 +420,9 @@ private: bool Psyche = false; int HelperState = 0; //stan pomocnika maszynisty TDynamicObject *pVehicle = nullptr; // pojazd w którym siedzi sterujący - TMoverParameters *mvControlling = nullptr; // jakim pojazdem steruje (może silnikowym w EZT) - TMoverParameters *mvOccupied = nullptr; // jakim pojazdem hamuje - TMoverParameters *mvPantographUnit = nullptr; //pantograph equipped vehicle in the occupied/controlled set + physics::Vehicle *mvControlling = nullptr; // jakim pojazdem steruje (może silnikowym w EZT) + physics::Vehicle *occupied = nullptr; // jakim pojazdem hamuje + physics::Vehicle *pantographUnit = nullptr; //pantograph equipped vehicle in the occupied/controlled set std::string VehicleName; ByEnd m_lighthints = { -1, -1 }; // suggested light patterns double AccPreferred = 0.0; // preferowane przyspieszenie (wg psychiki kierującego, zmniejszana przy wykryciu kolizji) diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index acf6c0461..e8eddd9d5 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -140,7 +140,7 @@ public: // destructor ~TAnim(); // methods - int TypeSet(int i, TMoverParameters currentMover, int fl = 0); // ustawienie typu + int TypeSet(int i, physics::Vehicle currentPhysics, int fl = 0); // ustawienie typu // members union { @@ -220,7 +220,7 @@ public: std::string asTrack; // nazwa toru początkowego; wywalić? std::string asDestination; // dokąd pojazd ma być kierowany "(stacja):(tor)" glm::dmat4 mMatrix; // macierz przekształcenia do renderowania modeli - TMoverParameters *MoverParameters; // parametry fizyki ruchu oraz przeliczanie + physics::Vehicle *physics; // parametry fizyki ruchu oraz przeliczanie TDynamicObject *NextConnected(); // pojazd podłączony od strony sprzęgu 1 (kabina -1) TDynamicObject *PrevConnected(); // pojazd podłączony od strony sprzęgu 0 (kabina 1) TDynamicObject *NextConnected() const; // pojazd podłączony od strony sprzęgu 1 (kabina -1) @@ -476,21 +476,21 @@ private: sound_source retarder { sound_placement::engine }; void position( glm::vec3 const Location ); - void render( TMoverParameters const &Vehicle, double const Deltatime ); + void render( physics::Vehicle const &Vehicle, double const Deltatime ); private: // the parts of render(), by subsystem - void renderPumpSounds( TMoverParameters const &Vehicle ); - void renderIgnitionSounds( TMoverParameters const &Vehicle ); - void renderEngineSounds( TMoverParameters const &Vehicle, double const Deltatime ); - void renderTurboSound( TMoverParameters const &Vehicle, double const Deltatime ); - void renderClutchSound( TMoverParameters const &Vehicle ); - void renderRetarderSound( TMoverParameters const &Vehicle ); - void renderTractionMotorSounds( TMoverParameters const &Vehicle, double const Deltatime ); - void renderMotorBlowerSounds( TMoverParameters const &Vehicle ); - void renderInverterSound( TMoverParameters const &Vehicle ); - void renderFanSounds( TMoverParameters const &Vehicle ); - void renderRelaySounds( TMoverParameters const &Vehicle ); - void renderTransmissionSound( TMoverParameters const &Vehicle ); + void renderPumpSounds( physics::Vehicle const &Vehicle ); + void renderIgnitionSounds( physics::Vehicle const &Vehicle ); + void renderEngineSounds( physics::Vehicle const &Vehicle, double const Deltatime ); + void renderTurboSound( physics::Vehicle const &Vehicle, double const Deltatime ); + void renderClutchSound( physics::Vehicle const &Vehicle ); + void renderRetarderSound( physics::Vehicle const &Vehicle ); + void renderTractionMotorSounds( physics::Vehicle const &Vehicle, double const Deltatime ); + void renderMotorBlowerSounds( physics::Vehicle const &Vehicle ); + void renderInverterSound( physics::Vehicle const &Vehicle ); + void renderFanSounds( physics::Vehicle const &Vehicle ); + void renderRelaySounds( physics::Vehicle const &Vehicle ); + void renderTransmissionSound( physics::Vehicle const &Vehicle ); }; // single source per door (pair) on the centreline struct doorspeaker_sounds { @@ -861,7 +861,7 @@ private: void renderWheelFlatSound(); void renderCurveSound(); void renderStartJoltSound(); - void renderMoverEventSounds(); + void renderPhysicsEventSounds(); void renderCouplerSounds(); void renderDerailmentSounds(); public: @@ -1142,7 +1142,7 @@ private: std::string m_overlappair; double m_overlapdue { 1.0 }; bool m_overlaplogged { false }; - std::vector m_brakepipes; // the vehicles of update_brake_pipes(), kept for the memory + std::vector m_brakepipes; // the vehicles of update_brake_pipes(), kept for the memory std::vector> m_offtrackterrains; // of off_track_terrain() }; diff --git a/vehicle/Train.h b/vehicle/Train.h index 7ef51c28d..ce5ea2def 100644 --- a/vehicle/Train.h +++ b/vehicle/Train.h @@ -248,7 +248,7 @@ class TTrain { return ggHornButton.SubModel != nullptr && ggHornLowButton.SubModel == nullptr && ggHornHighButton.SubModel == nullptr; } // locates nearest vehicle belonging to the consist TDynamicObject *find_nearest_consist_vehicle(bool freefly, glm::vec3 pos) const; - // mover master controller to specified position + // physics master controller to specified position void set_master_controller( double const Position ); // moves train brake lever to specified position, potentially emits switch sound if conditions are met void set_train_brake( double const Position ); @@ -263,7 +263,7 @@ class TTrain { // helper, common part of pantograh valves state update methods void update_pantograph_valves(); // the Index-th other vehicle in multiple whose engine the cab starts with its own switches (0: mainb_*, 1: mainc_*) - TMoverParameters *remote_engine( std::size_t const Index ) const; + physics::Vehicle *remote_engine( std::size_t const Index ) const; // the switches starting the engines of the other vehicles in multiple, for Deltatime seconds void update_remote_linebreakers( double const Deltatime ); // update function subroutines @@ -592,11 +592,11 @@ class TTrain { // members TDynamicObject *DynamicObject { nullptr }; // przestawia zmiana pojazdu [F5] - TMoverParameters *mvControlled { nullptr }; // człon, w którym sterujemy silnikiem - TMoverParameters *mvOccupied { nullptr }; // człon, w którym sterujemy hamulcem - TMoverParameters *mvSecond { nullptr }; // drugi człon (ET40, ET41, ET42, ukrotnienia) - TMoverParameters *mvThird { nullptr }; // trzeci człon (SN61) - TMoverParameters *mvPantographUnit { nullptr }; // nearest pantograph equipped unit + physics::Vehicle *controlled { nullptr }; // człon, w którym sterujemy silnikiem + physics::Vehicle *occupied { nullptr }; // człon, w którym sterujemy hamulcem + physics::Vehicle *secondUnit { nullptr }; // drugi człon (ET40, ET41, ET42, ukrotnienia) + physics::Vehicle *thirdUnit { nullptr }; // trzeci człon (SN61) + physics::Vehicle *pantographUnit { nullptr }; // nearest pantograph equipped unit // helper variable, to prevent immediate switch between closing and opening line breaker circuit linebreaker::state m_linebreakerstate { linebreaker::state::open }; static const commandhandler_map m_commandhandlers; @@ -1046,10 +1046,10 @@ private: inline auto &RadioChannel() { return Dynamic()->Mechanik->iRadioChannel; } inline TDynamicObject *Dynamic() { return DynamicObject; }; inline TDynamicObject const *Dynamic() const { return DynamicObject; }; - inline TMoverParameters *Controlled() { return mvControlled; }; - inline TMoverParameters const *Controlled() const { return mvControlled; }; - inline TMoverParameters *Occupied() { return mvOccupied; }; - inline TMoverParameters const *Occupied() const { return mvOccupied; }; + inline physics::Vehicle *Controlled() { return controlled; }; + inline physics::Vehicle const *Controlled() const { return controlled; }; + inline physics::Vehicle *Occupied() { return occupied; }; + inline physics::Vehicle const *Occupied() const { return occupied; }; void DynamicSet(TDynamicObject *d); void MoveToVehicle( TDynamicObject *target ); // checks whether specified point is within boundaries of the active cab diff --git a/vehicle/ai/consist.cpp b/vehicle/ai/consist.cpp index b0774eccf..c66e090f8 100644 --- a/vehicle/ai/consist.cpp +++ b/vehicle/ai/consist.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/Driver.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "utilities/Globals.h" #include "utilities/translation.h" #include "utilities/Logs.h" @@ -55,28 +55,28 @@ void TController::Activation() { // jeśli jest ustalony kierunek auto *initialvehicle { pVehicle }; /* - auto const initiallocalbrakelevel { mvOccupied->LocalBrakePosA }; + auto const initiallocalbrakelevel { occupied->LocalBrakePosA }; */ - auto const initialspringbrakestate { mvOccupied->SpringBrake.Activate }; + auto const initialspringbrakestate { occupied->SpringBrake.Activate }; // switch off tempomat SpeedCntrl( 0.0 ); mvControlling->DecScndCtrl( 2 ); // reset controls ZeroSpeed(); ZeroDirection(); - mvOccupied->CabOccupied = mvOccupied->CabActive; // użytkownik moze zmienić CabOccupied wychodząc - mvOccupied->CabDeactivisation(); // tak jest w Train.cpp - if (pVehicle->MoverParameters->Couplers[iDirectionOrder < 0 ? VehicleEnd::rear : VehicleEnd::front].CouplingFlag.HasAll(Coupling::control)) { + occupied->CabOccupied = occupied->CabActive; // użytkownik moze zmienić CabOccupied wychodząc + occupied->CabDeactivisation(); // tak jest w Train.cpp + if (pVehicle->physics->Couplers[iDirectionOrder < 0 ? VehicleEnd::rear : VehicleEnd::front].CouplingFlag.HasAll(Coupling::control)) { ZeroLocalBrake(); if( initialspringbrakestate ) { - mvOccupied->SpringBrakeActivate( false ); + occupied->SpringBrakeActivate( false ); } // odcięcie na zaworze maszynisty, FVel6 po drugiej stronie nie luzuje - mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos(bh_NP) ); // odcięcie na zaworze maszynisty - BrakeLevelSet( mvOccupied->BrakeCtrlPos ); //ustawienie zmiennej GBH + occupied->BrakeLevelSet( occupied->Handle->GetPos(bh_NP) ); // odcięcie na zaworze maszynisty + BrakeLevelSet( occupied->BrakeCtrlPos ); //ustawienie zmiennej GBH } // przejście AI na drugą stronę EN57, ET41 itp. - // TODO: clean this up, there's lot of redundancy with TMoverParameters::ChangeCab() and TTrain::MoveToVehicle() + // TODO: clean this up, there's lot of redundancy with physics::Vehicle::ChangeCab() and TTrain::MoveToVehicle() { int movedirection { NumberOf( iDirection < 0 ? VehicleEnd::rear : VehicleEnd::front ) }; auto *targetvehicle { pVehicle->FirstFind( movedirection, Coupling::control ) }; @@ -84,7 +84,7 @@ void TController::Activation() auto *targetvehicledriver { targetvehicle->Mechanik }; // zapamiętanie tego, co ewentualnie tam siedzi, żeby w razie dwóch zamienić miejscami // move to the new vehicle targetvehicle->Mechanik = this; // na razie bilokacja - targetvehicle->MoverParameters->SetInternalCommand(VehicleCommand::none, 0, 0); // usunięcie ewentualnie zalegającej komendy (Change_direction?) + targetvehicle->physics->SetInternalCommand(VehicleCommand::none, 0, 0); // usunięcie ewentualnie zalegającej komendy (Change_direction?) if( targetvehicle->DirectionGet() != pVehicle->DirectionGet() ) { // jeśli są przeciwne do siebie to będziemy jechać w drugą stronę względem zasiedzianego pojazdu iDirection = -iDirection; @@ -93,9 +93,9 @@ void TController::Activation() pVehicle->Mechanik = targetvehicledriver; // wsadzamy tego, co ewentualnie był (podwójna trakcja) // NOTE: having caboccupied != 0 (by swapping in the driver from the target vehicle) may lead to dysfunctional brake // TODO: investigate and resolve if necessary - pVehicle->MoverParameters->CabOccupied = targetvehicle->MoverParameters->CabOccupied; + pVehicle->physics->CabOccupied = targetvehicle->physics->CabOccupied; if( pVehicle->Mechanik ) { // not guaranteed, as target vehicle can be empty - pVehicle->Mechanik->BrakeLevelSet( pVehicle->MoverParameters->BrakeCtrlPos ); + pVehicle->Mechanik->BrakeLevelSet( pVehicle->physics->BrakeCtrlPos ); } // finish driver swap pVehicle = targetvehicle; @@ -104,28 +104,28 @@ void TController::Activation() if (pVehicle != initialvehicle) { // jeśli zmieniony został pojazd prowadzony ControllingSet(); // utworzenie połączenia do sterowanego pojazdu (może się zmienić) - silnikowy dla EZT - if( mvOccupied->BrakeCtrlPosNo > 0 + if( occupied->BrakeCtrlPosNo > 0 && ( BrakeSystem == TBrakeSystem::Pneumatic || BrakeSystem == TBrakeSystem::ElectroPneumatic ) ) { - mvOccupied->LimPipePress = mvOccupied->PipePress; - mvOccupied->ActFlowSpeed = 0; + occupied->LimPipePress = occupied->PipePress; + occupied->ActFlowSpeed = 0; } - BrakeLevelSet( mvOccupied->BrakeCtrlPos ); + BrakeLevelSet( occupied->BrakeCtrlPos ); } if( mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->ShuntModeAllow ) { // dla 2Ls150 - przed ustawieniem kierunku - można zmienić tryb pracy mvControlling->CurrentSwitch(OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt) || fMass > 224000.0); // do tego na wzniesieniu może nie dać rady na liniowym } // Ra: to przełączanie poniżej jest tu bez sensu - mvOccupied->CabOccupied = iDirection; // aktywacja kabiny w prowadzonym pojeżdzie (silnikowy może być odwrotnie?) - mvOccupied->CabActivisation(); // uruchomienie kabin w członach + occupied->CabOccupied = iDirection; // aktywacja kabiny w prowadzonym pojeżdzie (silnikowy może być odwrotnie?) + occupied->CabActivisation(); // uruchomienie kabin w członach DirectionForward(true); // nawrotnik do przodu - mvOccupied->SpringBrakeActivate( initialspringbrakestate ); + occupied->SpringBrakeActivate( initialspringbrakestate ); /* // NOTE: this won't restore local brake if the vehicle has integrated local brake control // TBD, TODO: fix or let the ai activate the brake again as part of its standard logic? if (initiallocalbrakelevel > 0.0) // hamowanie tylko jeśli był wcześniej zahamowany (bo możliwe, że jedzie!) - mvOccupied->LocalBrakePosA = initiallocalbrakelevel; // zahamuj jak wcześniej + occupied->LocalBrakePosA = initiallocalbrakelevel; // zahamuj jak wcześniej */ if( pVehicle != initialvehicle ) { auto *train { simulation::Trains.find( initialvehicle->name() ) }; @@ -144,7 +144,7 @@ void TController::AutoRewident() // 1. Zebranie informacji o składzie pociągu, od czoła do końca std::vector consist; for (auto const *d = pVehicles[0]; d != nullptr; d = d->Next()) { - consist.emplace_back(brake_setting::describe(*d->MoverParameters, d == pVehicle)); + consist.emplace_back(brake_setting::describe(*d->physics, d == pVehicle)); } // 2. Określenie typu pociągu i nastaw: by the brake instruction Cw-1 (eu07/maszyna#350), or as the releases before it did. // brakes are cut out (Cw-1 §19.9) only in a train (a bank engine's run included), not in a consist being shunted @@ -152,7 +152,7 @@ void TController::AutoRewident() auto const settings{Global.AIBrakeSettingCw1 ? brake_setting::choose(consist, train) : brake_setting::choose_legacy(consist)}; // and only at a standstill, the train creeping to a stop included: a check on the run (the order changed mid-run, or // the train was just formed by coupling, which the AI does above that speed) leaves them to reinspect_brakes() - auto const standstill{brake_setting::at_standstill(mvOccupied->Vel)}; + auto const standstill{brake_setting::at_standstill(occupied->Vel)}; auto reinspect{false}; // a light engine counts as a passenger train for the braking below auto const passengertrain{brake_setting::passenger(brake_setting::choose_train_setting(consist))}; @@ -164,21 +164,21 @@ void TController::AutoRewident() continue; } // the setting, a brake cut out in a train on G (Cw-1 §19.9) or put back when the train no longer needs it cut out - if (brake_setting::apply(*d->MoverParameters, *setting, standstill)) { + if (brake_setting::apply(*d->physics, *setting, standstill)) { // a brake to cut out, with the train moving: left for the next standstill reinspect = true; } // potentially release manual brake - d->MoverParameters->DecManualBrakeLevel( ManualBrakePosNo ); - d->MoverParameters->SpringBrake.Activate = false; + d->physics->DecManualBrakeLevel( ManualBrakePosNo ); + d->physics->SpringBrake.Activate = false; } BrakeReinspectionPending = reinspect; //ustawianie trybu pracy zadajnika hamulca, wystarczy raz po inicjalizacji AI if( true == AIControllFlag ) { // if a human is in charge leave the brake mode up to them, otherwise do as you like for( int i = 1; i <= 8; i *= 2 ) { - if( ( mvOccupied->BrakeOpModes & i ) > 0 ) { - mvOccupied->BrakeOpModeFlag = i; + if( ( occupied->BrakeOpModes & i ) > 0 ) { + occupied->BrakeOpModeFlag = i; } } } @@ -204,20 +204,20 @@ void TController::AutoRewident() BrakeSystem = consist_brake_system(); // Change the EP fuse state only when AI is in charge, don't fiddle with controls when the user is controlling the vehicle if (AIControllFlag) { - mvOccupied->EpFuseSwitch(BrakeSystem == TBrakeSystem::ElectroPneumatic); + occupied->EpFuseSwitch(BrakeSystem == TBrakeSystem::ElectroPneumatic); } if( OrderCurrentGet() & ( DriverOrder::obeyTrain | DriverOrder::bank ) ) { // 4. Przeliczanie siły hamowania - double const velstep = mvOccupied->Vmax * 0.5 / BrakeAccTableSize; + double const velstep = occupied->Vmax * 0.5 / BrakeAccTableSize; auto *d = pVehicles[0]; // pojazd na czele składu while (d) { // a vehicle with its brake cut out (by the inspector above or for a reason of its own) adds its mass only; // the inspector of the earlier releases counted its brake in - auto const brakes{false == Global.AIBrakeSettingCw1 || false == brake_setting::is_cut_out(*d->MoverParameters)}; + auto const brakes{false == Global.AIBrakeSettingCw1 || false == brake_setting::is_cut_out(*d->physics)}; for( int i = 0; i < BrakeAccTableSize && brakes; ++i ) { - fBrake_a0[ i + 1 ] += d->MoverParameters->BrakeForceR( 0.25, velstep*( 1 + 2 * i ) ); - fBrake_a1[ i + 1 ] += d->MoverParameters->BrakeForceR( 1.00, velstep*( 1 + 2 * i ) ); + fBrake_a0[ i + 1 ] += d->physics->BrakeForceR( 0.25, velstep*( 1 + 2 * i ) ); + fBrake_a1[ i + 1 ] += d->physics->BrakeForceR( 1.00, velstep*( 1 + 2 * i ) ); } d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) } @@ -229,8 +229,8 @@ void TController::AutoRewident() fBrake_a1[i+1] /= 12 * fMass; } - IsPassengerTrain = is_train() && false == is_emu() && false == is_dmu() && (mvOccupied->BrakeDelayFlag & bdelay_G) == 0; - IsCargoTrain = is_train() && (mvOccupied->BrakeDelayFlag & bdelay_G) != 0; + IsPassengerTrain = is_train() && false == is_emu() && false == is_dmu() && (occupied->BrakeDelayFlag & bdelay_G) == 0; + IsCargoTrain = is_train() && (occupied->BrakeDelayFlag & bdelay_G) != 0; IsHeavyCargoTrain = true == IsCargoTrain && fBrake_a0[1] > 0.4 && iVehicles - ControlledEnginesCount > 0 && fMass / iVehicles > 50000; BrakingInitialLevel = IsHeavyCargoTrain ? 1.25 : IsCargoTrain ? 1.25 : 1.00; @@ -278,7 +278,7 @@ void TController::reinspect_brakes() BrakeReinspectionPending = false; return; } - if (brake_setting::at_standstill(mvOccupied->Vel)) { + if (brake_setting::at_standstill(occupied->Vel)) { // standing, the inspector leaves nothing for later: this clears the flag AutoRewident(); } @@ -286,10 +286,10 @@ void TController::reinspect_brakes() int TController::CheckDirection() { - int d = mvOccupied->DirAbsolute; // który sprzęg jest z przodu + int d = occupied->DirAbsolute; // który sprzęg jest z przodu if( !d ) { // jeśli nie ma ustalonego kierunku to jedziemy wg aktualnej kabiny - d = mvOccupied->CabActive; + d = occupied->CabActive; } return d; } @@ -319,13 +319,13 @@ bool TController::CheckVehicles(DriverOrders user) && p->Mechanik != this && p->Mechanik->drivingFlags.primary ) { // ale chodzi o inny pojazd, niż aktualnie sprawdzający // a tamten ma priorytet // TODO: take into account drivers' operating modes, one or more of them might be on banking duty - if (drivingFlags.primary && mvOccupied->DirAbsolute && mvOccupied->BrakeCtrlPos >= -1) + if (drivingFlags.primary && occupied->DirAbsolute && occupied->BrakeCtrlPos >= -1) { // jeśli rządzi i ma kierunek p->Mechanik->primary(false); // dezaktywuje tamtego p->Mechanik->ZeroLocalBrake(); - p->MoverParameters->BrakeLevelSet(p->MoverParameters->Handle->GetPos(bh_NP)); // odcięcie na zaworze maszynisty - p->Mechanik->BrakeLevelSet(p->MoverParameters->BrakeCtrlPos); // ustawienie zmiennej GBH + p->physics->BrakeLevelSet(p->physics->Handle->GetPos(bh_NP)); // odcięcie na zaworze maszynisty + p->Mechanik->BrakeLevelSet(p->physics->BrakeCtrlPos); // ustawienie zmiennej GBH } else { @@ -334,12 +334,12 @@ bool TController::CheckVehicles(DriverOrders user) } ++iVehicles; // jest jeden pojazd więcej pVehicles[VehicleEnd::rear] = p; // zapamiętanie ostatniego - fLength += p->MoverParameters->Dim.L; // dodanie długości pojazdu - fMass += p->MoverParameters->TotalMass; // dodanie masy łącznie z ładunkiem - fVelMax = min_speed( fVelMax, p->MoverParameters->Vmax ); // ustalenie maksymalnej prędkości dla składu + fLength += p->physics->Dim.L; // dodanie długości pojazdu + fMass += p->physics->TotalMass; // dodanie masy łącznie z ładunkiem + fVelMax = min_speed( fVelMax, p->physics->Vmax ); // ustalenie maksymalnej prędkości dla składu // reset oerlikon brakes consist flag as different type was detected - if( p->MoverParameters->BrakeSubsystem != TBrakeSubSystem::ss_ESt - && p->MoverParameters->BrakeSubsystem != TBrakeSubSystem::ss_LSt ) { + if( p->physics->BrakeSubsystem != TBrakeSubSystem::ss_ESt + && p->physics->BrakeSubsystem != TBrakeSubSystem::ss_LSt ) { drivingFlags.oerlikons = false; } p = p->Neighbour(dir); // pojazd podłączony od wskazanej strony @@ -357,7 +357,7 @@ bool TController::CheckVehicles(DriverOrders user) // establish ownership and vehicle order while (p) { - if (p->MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) + if (p->physics->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) { // jeśli pojazd posiada pantograf, to przydzielamy mu maskę, którą będzie informował o jeździe bezprądowej p->iOverheadMask = pantmask; pantmask = pantmask << 1; // przesunięcie bitów, max. 32 pojazdy z pantografami w składzie @@ -369,7 +369,7 @@ bool TController::CheckVehicles(DriverOrders user) } // with the order established the virtual train manager can do their work p = frontvehicle; - ControlledEnginesCount = p->MoverParameters->Power > 1.0 ? 1 : 0; + ControlledEnginesCount = p->physics->Power > 1.0 ? 1 : 0; auto hasheaters { false }; while (p) { @@ -377,16 +377,16 @@ bool TController::CheckVehicles(DriverOrders user) if( false == p->is_connected( pVehicle, Coupling::control ) ) { // NOTE: don't set battery in controllable vehicles, let the user/ai do it explicitly // HACK: wagony muszą mieć baterię załączoną do otwarcia drzwi... - p->MoverParameters->BatterySwitch( true ); + p->physics->BatterySwitch( true ); // enable heating and converter in carriages with can be heated - if( p->MoverParameters->HeatingPower > 0 ) { - p->MoverParameters->HeatingAllow = true; - p->MoverParameters->ConverterSwitch( true, range_t::local ); + if( p->physics->HeatingPower > 0 ) { + p->physics->HeatingAllow = true; + p->physics->ConverterSwitch( true, range_t::local ); hasheaters = true; } } else { - if( p->MoverParameters->Power > 1.0 ) { + if( p->physics->Power > 1.0 ) { ++ControlledEnginesCount; } } @@ -408,9 +408,9 @@ bool TController::CheckVehicles(DriverOrders user) sync_consist_reversers(); } // potentially sync compartment lighting state for the newly connected vehicles - if( mvOccupied->CompartmentLights.start_type == start_t::manual ) { - mvOccupied->CompartmentLightsSwitchOff( mvOccupied->CompartmentLights.is_disabled ); - mvOccupied->CompartmentLightsSwitch( mvOccupied->CompartmentLights.is_enabled ); + if( occupied->CompartmentLights.start_type == start_t::manual ) { + occupied->CompartmentLightsSwitchOff( occupied->CompartmentLights.is_disabled ); + occupied->CompartmentLightsSwitch( occupied->CompartmentLights.is_enabled ); } } @@ -451,7 +451,7 @@ bool TController::CheckVehicles(DriverOrders user) } // HACK: ensure vehicle lights are active from the beginning, if it had pre-activated battery - if( mvOccupied->LightsPosNo > 0 ) { + if( occupied->LightsPosNo > 0 ) { pVehicle->SetLights(); } if( iEngineActive ) { @@ -460,7 +460,7 @@ bool TController::CheckVehicles(DriverOrders user) // custom ai action for disconnect mode: switch off lights on disconnected vehicle(s) if( is_train() && true == OrderCurrentGet().HasAll(DriverOrder::disconnect) && AIControllFlag ) { // światła manewrowe (Tb1) tylko z przodu, aby nie pozostawić odczepionego ze światłem - if (mvOccupied->DirActive >= 0) + if (occupied->DirActive >= 0) { // jak ma kierunek do przodu pVehicles[VehicleEnd::rear]->RaLightsSet(-1, 0); } @@ -511,12 +511,12 @@ void TController::Lights(int head, int rear) void TController::DirectionInitial() { // ustawienie kierunku po wczytaniu trainset (może jechać na wstecznym - mvOccupied->CabActivisationAuto(); // załączenie rozrządu (wirtualne kabiny) - if (mvOccupied->Vel > EU07_AI_NOMOVEMENT) + occupied->CabActivisationAuto(); // załączenie rozrządu (wirtualne kabiny) + if (occupied->Vel > EU07_AI_NOMOVEMENT) { // jeśli na starcie jedzie iDirection = iDirectionOrder = - mvOccupied->V > 0 ? 1 : -1; // początkowa prędkość wymusza kierunek jazdy - DirectionForward(mvOccupied->V * mvOccupied->CabActive >= 0.0); // a dalej ustawienie nawrotnika + occupied->V > 0 ? 1 : -1; // początkowa prędkość wymusza kierunek jazdy + DirectionForward(occupied->V * occupied->CabActive >= 0.0); // a dalej ustawienie nawrotnika } CheckVehicles(); // sprawdzenie świateł oraz skrajnych pojazdów do skanowania }; @@ -530,7 +530,7 @@ void TController::DirectionChange() { } } -int TController::OrderDirectionChange(int newdir, TMoverParameters *Vehicle) +int TController::OrderDirectionChange(int newdir, physics::Vehicle *Vehicle) { // zmiana kierunku jazdy, niezależnie od kabiny int testd = newdir; if (Vehicle->Vel < 0.5) @@ -568,21 +568,21 @@ void TController::DirectionForward(bool forward) if( forward ) { // do przodu w obecnej kabinie - while( mvOccupied->DirActive <= 0 - && mvOccupied->DirectionForward() ) { + while( occupied->DirActive <= 0 + && occupied->DirectionForward() ) { // force scan table update iTableDirection = 0; } } else { // do tyłu w obecnej kabinie - while( mvOccupied->DirActive >= 0 - && mvOccupied->DirectionBackward() ) { + while( occupied->DirActive >= 0 + && occupied->DirectionBackward() ) { // force scan table update iTableDirection = 0; } } - if( mvOccupied->TrainType == train_type::sn61 ) { + if( occupied->TrainType == train_type::sn61 ) { // specjalnie dla SN61 żeby nie zgasł while( mvControlling->RList[mvControlling->MainCtrlPos].Mn == 0 && mvControlling->IncMainCtrl(1) ) { @@ -593,39 +593,39 @@ void TController::DirectionForward(bool forward) void TController::ZeroDirection() { - while( mvOccupied->DirActive > 0 && mvOccupied->DirectionBackward() ) { ; } - while( mvOccupied->DirActive < 0 && mvOccupied->DirectionForward() ) { ; } + while( occupied->DirActive > 0 && occupied->DirectionBackward() ) { ; } + while( occupied->DirActive < 0 && occupied->DirectionForward() ) { ; } } void TController::sync_consist_reversers() { - auto const currentdirection { mvOccupied->DirActive }; - auto const fastforward { is_emu() && mvOccupied->EngineType != TEngineType::ElectricInductionMotor - && mvOccupied->Imin == mvOccupied->IminHi }; + auto const currentdirection { occupied->DirActive }; + auto const fastforward { is_emu() && occupied->EngineType != TEngineType::ElectricInductionMotor + && occupied->Imin == occupied->IminHi }; // move reverser all way in the opposite direction... for( auto idx = 0; idx < 3; ++idx ) { if( currentdirection >= 0 ) { - mvOccupied->DirectionBackward(); + occupied->DirectionBackward(); } else { - mvOccupied->DirectionForward(); + occupied->DirectionForward(); } } // ...then restore original setting - while( mvOccupied->DirActive != currentdirection ) { + while( occupied->DirActive != currentdirection ) { if( false == ( currentdirection >= 0 ? - mvOccupied->DirectionForward() : - mvOccupied->DirectionBackward() ) ) { + occupied->DirectionForward() : + occupied->DirectionBackward() ) ) { // sanity check for potential endless loop break; } } // potentially restore 'fast forward' setting if( currentdirection > 0 && true == fastforward ) { - mvOccupied->DirectionForward(); + occupied->DirectionForward(); } } @@ -665,12 +665,12 @@ void TController::ControllingSet() // a driver of no vehicle has nothing to control return; } - mvOccupied = pVehicle->MoverParameters; // domyślny skrót do obiektu parametrów - BrakeSystem = mvOccupied->BrakeSystem; // domyślny sposób hamowania - mvControlling = pVehicle->FindPowered()->MoverParameters; // poszukiwanie członu sterowanego + occupied = pVehicle->physics; // domyślny skrót do obiektu parametrów + BrakeSystem = occupied->BrakeSystem; // domyślny sposób hamowania + mvControlling = pVehicle->FindPowered()->physics; // poszukiwanie członu sterowanego { auto *lookup { pVehicle->FindPantographCarrier() }; - mvPantographUnit = lookup != nullptr ? lookup->MoverParameters : mvControlling; + pantographUnit = lookup != nullptr ? lookup->physics : mvControlling; } BrakeSystem = consist_brake_system(); }; @@ -680,30 +680,30 @@ TController::determine_consist_state() { // ABu-160305 testowanie gotowości do jazdy // Ra: przeniesione z DynObj, skład użytkownika też jest testowany, żeby mu przekazać, że ma odhamować - if (mvOccupied->CabActive == 0 && mvOccupied->Power24vIsAvailable) + if (occupied->CabActive == 0 && occupied->Power24vIsAvailable) { cue_action( driver_hint::cabactivation ); } - else if (!mvOccupied->AutomaticCabActivation - && ( mvOccupied->CabActive == -mvOccupied->CabOccupied || !mvOccupied->CabMaster || !mvOccupied->Power24vIsAvailable ) ) + else if (!occupied->AutomaticCabActivation + && ( occupied->CabActive == -occupied->CabOccupied || !occupied->CabMaster || !occupied->Power24vIsAvailable ) ) { cue_action( driver_hint::cabdeactivation ); } - int index = double(BrakeAccTableSize) * (mvOccupied->Vel / mvOccupied->Vmax); + int index = double(BrakeAccTableSize) * (occupied->Vel / occupied->Vmax); index = std::min(BrakeAccTableSize, std::max(1, index)); fBrake_a0[0] = fBrake_a0[index]; fBrake_a1[0] = fBrake_a1[index]; if (is_emu() || is_dmu()) { - auto Coeff = std::clamp( mvOccupied->Vel*0.015 , 0.5 , 1.0); + auto Coeff = std::clamp( occupied->Vel*0.015 , 0.5 , 1.0); fAccThreshold = fNominalAccThreshold * Coeff - fBrake_a0[BrakeAccTableSize] * (1.0 - Coeff); } Ready = true; // wstępnie gotowy fReady = 0.0; // założenie, że odhamowany - IsConsistBraked = mvOccupied->BrakeSystem == TBrakeSystem::ElectroPneumatic && false == ForcePNBrake ? mvOccupied->BrakePress > 2.0 : - mvOccupied->PipePress < std::max(3.9, mvOccupied->BrakePressureActual.PipePressureVal) + 0.1; + IsConsistBraked = occupied->BrakeSystem == TBrakeSystem::ElectroPneumatic && false == ForcePNBrake ? occupied->BrakePress > 2.0 : + occupied->PipePress < std::max(3.9, occupied->BrakePressureActual.PipePressureVal) + 0.1; fAccGravity = 0.0; // przyspieszenie wynikające z pochylenia IsAnyCouplerStretched = false; IsAnyDoorOnlyOpen[ VehicleSide::right ] = IsAnyDoorOnlyOpen[ VehicleSide::left ] = false; @@ -722,7 +722,7 @@ TController::determine_consist_state() { auto chargelevel { std::numeric_limits::max() }; // the lowest pipe or auxiliary reservoir pressure of a working brake while (p) { // sprawdzenie odhamowania wszystkich połączonych pojazdów - auto *vehicle { p->MoverParameters }; + auto *vehicle { p->physics }; auto const bp { std::max( 0.0, vehicle->BrakePress - ( vehicle->SpeedCtrlUnit.Parking ? vehicle->MaxBrakePress[ 0 ] * vehicle->StopBrakeDecc : 0.0 ) ) }; momentum += vehicle->TotalMass * vehicle->V * ( p->DirectionGet() == iDirection ? 1 : -1 ); mostapplied = std::max( bp, mostapplied ); @@ -749,9 +749,9 @@ TController::determine_consist_state() { } if( wasready ) { // Ra: odluźnianie przeładowanych lokomotyw, ciągniętych na zimno - prowizorka... - if( bp >= 0.4 && (AIControllFlag || Global.AITrainman && mvOccupied->Vel < EU07_AI_NOMOVEMENT && !is_emu() && !is_dmu()) && BrakeCtrlPosition == gbh_RP // jest pozycja jazdy + if( bp >= 0.4 && (AIControllFlag || Global.AITrainman && occupied->Vel < EU07_AI_NOMOVEMENT && !is_emu() && !is_dmu()) && BrakeCtrlPosition == gbh_RP // jest pozycja jazdy && false == TestFlag(vehicle->Hamulec->GetBrakeStatus(), b_dmg) // brake isn't broken - && vehicle->PipePress - mvOccupied->Handle->GetRP() > -0.1 // jeśli ciśnienie jak dla jazdy + && vehicle->PipePress - occupied->Handle->GetRP() > -0.1 // jeśli ciśnienie jak dla jazdy && vehicle->Hamulec->GetCRP() > vehicle->PipePress + 0.12 ) { // wg UIC określone sztywno na 0.04 // za dużo w zbiorniku // indywidualne luzowanko @@ -778,7 +778,7 @@ TController::determine_consist_state() { || vehicle->Couplers[VehicleEnd::rear].stretch_duration > 0.0; // check door state { - auto const switchsides{ p->DirectionGet() != (iDirection == 0 ? mvOccupied->CabOccupied : iDirection) }; + auto const switchsides{ p->DirectionGet() != (iDirection == 0 ? occupied->CabOccupied : iDirection) }; auto const &rightdoor { vehicle->Doors.instances[ ( switchsides ? VehicleSide::left : VehicleSide::right ) ] }; auto const &leftdoor { vehicle->Doors.instances[ ( switchsides ? VehicleSide::right : VehicleSide::left ) ] }; if( vehicle->Doors.close_control != control_t::autonomous ) { @@ -821,7 +821,7 @@ TController::determine_consist_state() { pVehicle->for_each( Coupling::control, [this, &islocalconverterswitchoff]( TDynamicObject * Vehicle ) { - auto const *vehicle { Vehicle->MoverParameters }; + auto const *vehicle { Vehicle->physics }; islocalconverterswitchoff |= vehicle->LineContactorsHeldByLocalConverterSwitch(); IsAnyConverterOverloadRelayOpen |= vehicle->ConvOvldFlag; IsAnyMotorOverloadRelayOpen |= vehicle->FuseFlag; @@ -840,11 +840,11 @@ TController::determine_consist_state() { fAccGravity /= fMass; { auto absaccs { fAccGravity }; // Ra 2014-03: jesli skład stoi, to działa na niego składowa styczna grawitacji - if( mvOccupied->Vel > EU07_AI_NOMOVEMENT ) { + if( occupied->Vel > EU07_AI_NOMOVEMENT ) { absaccs = 0; auto *d = pVehicles[ VehicleEnd::front ]; // pojazd na czele składu while( d ) { - absaccs += d->MoverParameters->TotalMass * d->MoverParameters->AccS * ( d->DirectionGet() == iDirection ? 1 : -1 ); + absaccs += d->physics->TotalMass * d->physics->AccS * ( d->DirectionGet() == iDirection ? 1 : -1 ); d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) } absaccs *= iDirection >= 0 ? 1 : -1; @@ -873,7 +873,7 @@ TController::determine_consist_state() { // reservoirs refill as the brake releases, and waiting for the last tenths of a bar there only delays the train and // those behind it. // and only the pneumatic brake: multiple units with the electro-pneumatic one start as before - if( mvOccupied->Vel > 1.0 ) { + if( occupied->Vel > 1.0 ) { // the start is made. a shunting engine coupling wagons moves at a walking pace: a higher speed would leave its // every start the first, waiting for each cut of wagons placed cold to charge bBrakeChargeStart = false; @@ -882,7 +882,7 @@ TController::determine_consist_state() { } auto const chargeable { ( BrakeSystem == TBrakeSystem::Pneumatic ) - && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) + && ( occupied->Vel < EU07_AI_NOMOVEMENT ) && ( chargelevel < std::numeric_limits::max() ) }; if( chargeable && ( chargelevel < brake_charge::empty_level ) ) { bBrakeChargeStart = true; @@ -896,22 +896,22 @@ TController::determine_consist_state() { AIControllFlag ? BrakeCtrlPosition > 0.0 : // a human driver's handle, which BrakeCtrlPosition doesn't follow - mvOccupied->fBrakeCtrlPos > mvOccupied->Handle->GetPos( bh_RP ) + 0.2 }; + occupied->fBrakeCtrlPos > occupied->Handle->GetPos( bh_RP ) + 0.2 }; auto const reference { - brake_charge::reference( mvOccupied->PipePress, std::min( mvOccupied->Handle->GetRP(), 5.0 ), trainbrakeapplied ) }; + brake_charge::reference( occupied->PipePress, std::min( occupied->Handle->GetRP(), 5.0 ), trainbrakeapplied ) }; // air to charge with: the engine prepared, the main reservoir above what the pipe charges to, and the driver's // brake valve feeding the pipe at the head of the train. a train still being prepared from cold can't charge, // nor one whose pipe is locked (unlocked by control_releaser()): it waits without that counting as a stall, held // by its brakes as it can't release them either auto const supplied { iEngineActive - && ( std::max( mvControlling->Compressor, mvOccupied->Compressor ) > reference ) - && ( mvOccupied->PipePress >= reference - brake_charge::margin ) }; + && ( std::max( mvControlling->Compressor, occupied->Compressor ) > reference ) + && ( occupied->PipePress >= reference - brake_charge::margin ) }; auto const wasstalled { BrakeCharge.stalled }; IsConsistCharged = brake_charge::charged( BrakeCharge, chargelevel, reference, ElapsedTime, supplied ); if( BrakeCharge.stalled && ( false == wasstalled ) ) { WriteLog( - "AI: " + mvOccupied->Name + " stopped charging its brakes at " + to_string( chargelevel, 2 ) + "AI: " + occupied->Name + " stopped charging its brakes at " + to_string( chargelevel, 2 ) + " bar of " + to_string( reference, 2 ) + ", starting all the same" ); } if( false == IsConsistCharged ) { @@ -930,7 +930,7 @@ TController::determine_consist_state() { } auto const departblocked { AIControllFlag - && mvOccupied->Vel < EU07_AI_NOMOVEMENT + && occupied->Vel < EU07_AI_NOMOVEMENT && VelDesired > 0.0 && ( false == Ready || fReady > 0.4 ) }; if( false == departblocked ) { @@ -945,7 +945,7 @@ TController::determine_consist_state() { while( true == Ready && p != nullptr ) { - auto const *vehicle { p->MoverParameters }; + auto const *vehicle { p->physics }; if( has_diesel_engine() ) { diff --git a/vehicle/ai/controls.cpp b/vehicle/ai/controls.cpp index ac39a106a..37f4c7b1b 100644 --- a/vehicle/ai/controls.cpp +++ b/vehicle/ai/controls.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/Driver.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "utilities/Globals.h" #include "utilities/translation.h" #include "utilities/Logs.h" @@ -59,23 +59,23 @@ TController::increase_train_brake() { d = pVehicles[0]; // pojazd na czele składu while (d) { // przeliczanie dodatkowego potrzebnego spadku ciśnienia - if( ( d->MoverParameters->Hamulec->GetBrakeStatus() & b_dmg ) == 0 ) { - pos_corr -= ( std::min( 5.0, d->MoverParameters->Hamulec->GetCRP() ) - 5.0 ) * d->MoverParameters->TotalMass; + if( ( d->physics->Hamulec->GetBrakeStatus() & b_dmg ) == 0 ) { + pos_corr -= ( std::min( 5.0, d->physics->Hamulec->GetCRP() ) - 5.0 ) * d->physics->TotalMass; } d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) } pos_corr = pos_corr / fMass * 2.5; - if (mvOccupied->BrakeHandle == TBrakeHandle::FV4a) + if (occupied->BrakeHandle == TBrakeHandle::FV4a) { - pos_corr += mvOccupied->Handle->GetCP()*0.2; + pos_corr += occupied->Handle->GetCP()*0.2; } - if( double const deltaAcc = -AccDesired*BrakeAccFactor() - (fBrake_a0[0] + 4.0 * (/*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition - 1 - pos_corr)*fBrake_a1[0]); + if( double const deltaAcc = -AccDesired*BrakeAccFactor() - (fBrake_a0[0] + 4.0 * (/*GBH occupied->BrakeCtrlPosR*/BrakeCtrlPosition - 1 - pos_corr)*fBrake_a1[0]); deltaAcc > brake_increase_margin() ) { - if( /*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition < 0.1 ) { - auto const OK { /*mvOccupied->*/BrakeLevelAdd( BrakingInitialLevel ) }; //GBH + if( /*GBH occupied->BrakeCtrlPosR*/BrakeCtrlPosition < 0.1 ) { + auto const OK { /*occupied->*/BrakeLevelAdd( BrakingInitialLevel ) }; //GBH // HACK: stronger braking to overcome SA134 engine behaviour if( is_dmu() && VelNext == 0.0 @@ -87,27 +87,27 @@ TController::increase_train_brake() { } return OK; } - auto const OK { /*mvOccupied->*/BrakeLevelAdd( BrakingLevelIncrease ) }; //GBH + auto const OK { /*occupied->*/BrakeLevelAdd( BrakingLevelIncrease ) }; //GBH // brake harder if the acceleration is much higher than desired /*if( ( deltaAcc > 2 * fBrake_a1[ 0 ] ) - && ( mvOccupied->BrakeCtrlPosR + BrakingLevelIncrease <= 5.0 ) ) { - mvOccupied->BrakeLevelAdd( BrakingLevelIncrease ); + && ( occupied->BrakeCtrlPosR + BrakingLevelIncrease <= 5.0 ) ) { + occupied->BrakeLevelAdd( BrakingLevelIncrease ); } GBH */ if( deltaAcc > 2 * fBrake_a1[0] && BrakeCtrlPosition + BrakingLevelIncrease <= 5.0 ) { - /*mvOccupied->*/BrakeLevelAdd( BrakingLevelIncrease ); + /*occupied->*/BrakeLevelAdd( BrakingLevelIncrease ); } return OK; } if( BrakeCtrlPosition > 0.0 && AccDesired < 0.0 // only while braking is asked for, not when called for a train slipping back while starting && ( fBrakeHeldTime > ( - mvOccupied->BrakeDelayFlag > bdelay_G ? - mvOccupied->BrakeDelay[ 1 ] : - mvOccupied->BrakeDelay[ 3 ] ) + occupied->BrakeDelayFlag > bdelay_G ? + occupied->BrakeDelay[ 1 ] : + occupied->BrakeDelay[ 3 ] ) // a train falling further behind needs no full fill time to be seen not to get enough || ( ( fShortfall > 0.02 ) - && ( fBrakeHeldTime > brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) ) { + && ( fBrakeHeldTime > brake_response_horizon( occupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) ) { // the table says the present position is enough, but the brake has had its full fill // time since the handle last moved and the train is still not slowing down as asked: // believe the train rather than the table @@ -125,34 +125,34 @@ bool TController::IncBrake() BrakeSystem }; switch( bs ) { case TBrakeSystem::Individual: { - if( mvOccupied->LocalBrake == TLocalBrake::ManualBrake ) { - OK = mvOccupied->IncManualBrakeLevel( 1 + static_cast( std::floor( 0.5 + std::fabs( AccDesired ) ) ) ); + if( occupied->LocalBrake == TLocalBrake::ManualBrake ) { + OK = occupied->IncManualBrakeLevel( 1 + static_cast( std::floor( 0.5 + std::fabs( AccDesired ) ) ) ); } else { - OK = mvOccupied->IncLocalBrakeLevel( std::floor( 1.5 + std::abs( AccDesired ) ) ); + OK = occupied->IncLocalBrakeLevel( std::floor( 1.5 + std::abs( AccDesired ) ) ); } break; } case TBrakeSystem::Pneumatic: { - if (bs != mvOccupied->BrakeSystem) + if (bs != occupied->BrakeSystem) { - while (mvOccupied->BrakeOpModeFlag > bom_PN) + while (occupied->BrakeOpModeFlag > bom_PN) { - mvOccupied->BrakeOpModeFlag >>= 1; + occupied->BrakeOpModeFlag >>= 1; } } // NOTE: can't perform just test whether connected vehicle == nullptr, due to virtual couplers formed with nearby vehicles auto standalone { true }; - if( mvOccupied->TrainType == train_type::et41 - || mvOccupied->TrainType == train_type::et42 ) { + if( occupied->TrainType == train_type::et41 + || occupied->TrainType == train_type::et42 ) { // NOTE: we're doing simplified checks full of presuptions here. // they'll break if someone does strange thing like turning around the second unit - if( mvOccupied->Couplers[VehicleEnd::rear].CouplingFlag & Coupling::permanent - && mvOccupied->Couplers[VehicleEnd::rear].Connected->Couplers[VehicleEnd::rear].Connected != nullptr ) { + if( occupied->Couplers[VehicleEnd::rear].CouplingFlag & Coupling::permanent + && occupied->Couplers[VehicleEnd::rear].Connected->Couplers[VehicleEnd::rear].Connected != nullptr ) { standalone = false; } - if( mvOccupied->Couplers[VehicleEnd::front].CouplingFlag & Coupling::permanent - && mvOccupied->Couplers[VehicleEnd::front].Connected->Couplers[VehicleEnd::front].Connected != nullptr ) { + if( occupied->Couplers[VehicleEnd::front].CouplingFlag & Coupling::permanent + && occupied->Couplers[VehicleEnd::front].Connected->Couplers[VehicleEnd::front].Connected != nullptr ) { standalone = false; } } @@ -161,15 +161,15 @@ bool TController::IncBrake() standalone = false; } else if( OrderCurrentGet().HasAny(DriverOrder::looseShunt) - && mvOccupied->Vel - VelDesired < fVelPlus + fVelMinus ) { + && occupied->Vel - VelDesired < fVelPlus + fVelMinus ) { // try to reduce train brake use in loose shunting mode standalone = true; } else { /* standalone = - ( ( mvOccupied->Couplers[ 0 ].CouplingFlag.Empty() ) - && ( mvOccupied->Couplers[ 1 ].CouplingFlag.Empty() ) ); + ( ( occupied->Couplers[ 0 ].CouplingFlag.Empty() ) + && ( occupied->Couplers[ 1 ].CouplingFlag.Empty() ) ); */ if( pVehicles[ VehicleEnd::front ] != pVehicles[ VehicleEnd::rear ] ) { // more detailed version, will use manual braking also for coupled sets of controlled vehicles @@ -179,10 +179,10 @@ bool TController::IncBrake() // NOTE: we could simplify this by doing only check of the rear coupler, but this can be quite tricky in itself // TODO: add easier ways to access front/rear coupler taking into account vehicle's direction standalone = - (vehicle->MoverParameters->Couplers[VehicleEnd::front].Connected == nullptr || - (vehicle->MoverParameters->Couplers[VehicleEnd::front].CouplingFlag & Coupling::control && vehicle->MoverParameters->Couplers[VehicleEnd::front].Connected->Power > 1)) && - (vehicle->MoverParameters->Couplers[VehicleEnd::rear].Connected == nullptr || - (vehicle->MoverParameters->Couplers[VehicleEnd::rear].CouplingFlag & Coupling::control && vehicle->MoverParameters->Couplers[VehicleEnd::rear].Connected->Power > 1)); + (vehicle->physics->Couplers[VehicleEnd::front].Connected == nullptr || + (vehicle->physics->Couplers[VehicleEnd::front].CouplingFlag & Coupling::control && vehicle->physics->Couplers[VehicleEnd::front].Connected->Power > 1)) && + (vehicle->physics->Couplers[VehicleEnd::rear].Connected == nullptr || + (vehicle->physics->Couplers[VehicleEnd::rear].CouplingFlag & Coupling::control && vehicle->physics->Couplers[VehicleEnd::rear].Connected->Power > 1)); vehicle = vehicle->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) } } @@ -195,14 +195,14 @@ bool TController::IncBrake() OK = IncBrakeEIM(); } else { - OK = mvOccupied->IncLocalBrakeLevel( + OK = occupied->IncLocalBrakeLevel( 1 + static_cast( std::floor( 0.5 + std::fabs( AccDesired ) ) ) ); // hamowanie lokalnym bo luzem jedzie } } else { - if( /*GBH mvOccupied->BrakeCtrlPos*/ BrakeCtrlPosition + 1 == gbh_MAX ) { + if( /*GBH occupied->BrakeCtrlPos*/ BrakeCtrlPosition + 1 == gbh_MAX ) { if (AccDesired < -1.5) // hamowanie nagle - OK = /*mvOccupied->*/BrakeLevelAdd(1.0); //GBH + OK = /*occupied->*/BrakeLevelAdd(1.0); //GBH else OK = false; } @@ -210,48 +210,48 @@ bool TController::IncBrake() OK = increase_train_brake(); } } - if( /*GBH mvOccupied->BrakeCtrlPos*/ - /*GBH mvOccupied->BrakeCtrlPos*/ BrakeCtrlPosition > 0 && mvOccupied->Hamulec->Releaser() ) { - mvOccupied->BrakeReleaser(0); + if( /*GBH occupied->BrakeCtrlPos*/ + /*GBH occupied->BrakeCtrlPos*/ BrakeCtrlPosition > 0 && occupied->Hamulec->Releaser() ) { + occupied->BrakeReleaser(0); } break; } case TBrakeSystem::ElectroPneumatic: { - while( mvOccupied->BrakeOpModeFlag << 1 <= mvOccupied->BrakeOpModes ) { - mvOccupied->BrakeOpModeFlag <<= 1; + while( occupied->BrakeOpModeFlag << 1 <= occupied->BrakeOpModes ) { + occupied->BrakeOpModeFlag <<= 1; } - if( mvOccupied->EngineType == TEngineType::ElectricInductionMotor ) { - if (mvOccupied->BrakeHandle == TBrakeHandle::MHZ_EN57) { - if (mvOccupied->BrakeCtrlPos < mvOccupied->Handle->GetPos(bh_FB)) - OK = mvOccupied->BrakeLevelAdd(1.0); + if( occupied->EngineType == TEngineType::ElectricInductionMotor ) { + if (occupied->BrakeHandle == TBrakeHandle::MHZ_EN57) { + if (occupied->BrakeCtrlPos < occupied->Handle->GetPos(bh_FB)) + OK = occupied->BrakeLevelAdd(1.0); } else { OK = IncBrakeEIM(); } } - else if( mvOccupied->Handle->TimeEP == false ) { - auto const initialbrakeposition { mvOccupied->fBrakeCtrlPos }; - auto const AccMax { std::min( fBrake_a0[ 0 ] + 12 * fBrake_a1[ 0 ], mvOccupied->MED_amax ) }; - mvOccupied->BrakeLevelSet( + else if( occupied->Handle->TimeEP == false ) { + auto const initialbrakeposition { occupied->fBrakeCtrlPos }; + auto const AccMax { std::min( fBrake_a0[ 0 ] + 12 * fBrake_a1[ 0 ], occupied->MED_amax ) }; + occupied->BrakeLevelSet( std::lerp( - mvOccupied->Handle->GetPos( bh_EPR ), - mvOccupied->Handle->GetPos( bh_EPB ), - std::clamp( -AccDesired / AccMax * mvOccupied->AIHintLocalBrakeAccFactor, 0.0, 1.0 ) ) ); - OK = mvOccupied->fBrakeCtrlPos != initialbrakeposition; + occupied->Handle->GetPos( bh_EPR ), + occupied->Handle->GetPos( bh_EPB ), + std::clamp( -AccDesired / AccMax * occupied->AIHintLocalBrakeAccFactor, 0.0, 1.0 ) ) ); + OK = occupied->fBrakeCtrlPos != initialbrakeposition; } - else if( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_EPB ) ) { - mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_EPB ) ); - if( mvOccupied->Handle->GetPos( bh_EPR ) - mvOccupied->Handle->GetPos( bh_EPN ) < 0.1 ) - mvOccupied->SwitchEPBrake( 1 ); // to nie chce działać + else if( occupied->fBrakeCtrlPos != occupied->Handle->GetPos( bh_EPB ) ) { + occupied->BrakeLevelSet( occupied->Handle->GetPos( bh_EPB ) ); + if( occupied->Handle->GetPos( bh_EPR ) - occupied->Handle->GetPos( bh_EPN ) < 0.1 ) + occupied->SwitchEPBrake( 1 ); // to nie chce działać OK = true; } - else if( ( mvOccupied->Handle->GetPos( bh_EPR ) - mvOccupied->Handle->GetPos( bh_EPN ) < 0.1 ) - && ( mvOccupied->EpForce <= 0.0 ) - && ( mvOccupied->EPBrakeControlPowered() ) ) { + else if( ( occupied->Handle->GetPos( bh_EPR ) - occupied->Handle->GetPos( bh_EPN ) < 0.1 ) + && ( occupied->EpForce <= 0.0 ) + && ( occupied->EPBrakeControlPowered() ) ) { // the handle already in the EP brake position, but the EP brake dropped out with the control's // supply (e.g. the EP fuse off in the running brake test): switch it on again - mvOccupied->SwitchEPBrake( 1 ); - OK = ( mvOccupied->EpForce > 0.0 ); + occupied->SwitchEPBrake( 1 ); + OK = ( occupied->EpForce > 0.0 ); } else OK = false; @@ -265,44 +265,44 @@ bool TController::IncBrake() bool TController::IncBrakeEIM() { // zwiększenie hamowania bool OK = false; - switch (mvOccupied->EIMCtrlType) + switch (occupied->EIMCtrlType) { case 0: { - if( mvOccupied->MED_amax != 9.81 ) { - auto const maxpos{mvOccupied->EIMCtrlEmergency ? 0.9 : 1.0 }; + if( occupied->MED_amax != 9.81 ) { + auto const maxpos{occupied->EIMCtrlEmergency ? 0.9 : 1.0 }; auto const brakelimit{ -2.2 * AccDesired / fMedAmax - 1.0}; //additional limit when hinted is too low - auto const brakehinted{ -1.0 * mvOccupied->AIHintLocalBrakeAccFactor * AccDesired / fMedAmax }; //preffered by AI + auto const brakehinted{ -1.0 * occupied->AIHintLocalBrakeAccFactor * AccDesired / fMedAmax }; //preffered by AI auto const brakeposition{ maxpos * std::clamp(std::max(brakelimit, brakehinted), 0.0, 1.0)}; - OK = brakeposition != mvOccupied->LocalBrakePosA; - mvOccupied->LocalBrakePosA = brakeposition; + OK = brakeposition != occupied->LocalBrakePosA; + occupied->LocalBrakePosA = brakeposition; } else { - OK = mvOccupied->IncLocalBrakeLevel( 1 ); + OK = occupied->IncLocalBrakeLevel( 1 ); } break; } case 1: { - OK = mvOccupied->MainCtrlPos > 0; + OK = occupied->MainCtrlPos > 0; if( OK ) - mvOccupied->MainCtrlPos = 0; + occupied->MainCtrlPos = 0; break; } case 2: { // the braking position, above the emergency brake one where the controller has it - auto const brakepos{1 + mvOccupied->EIMCtrlEmergencyPositions()}; - OK = mvOccupied->MainCtrlPos > brakepos; + auto const brakepos{1 + occupied->EIMCtrlEmergencyPositions()}; + OK = occupied->MainCtrlPos > brakepos; if( OK ) - mvOccupied->MainCtrlPos = brakepos; + occupied->MainCtrlPos = brakepos; break; } case 3: { - if( mvOccupied->UniCtrlIntegratedLocalBrakeCtrl ) { - OK = mvOccupied->MainCtrlPos > 0; + if( occupied->UniCtrlIntegratedLocalBrakeCtrl ) { + OK = occupied->MainCtrlPos > 0; if( OK ) - mvOccupied->MainCtrlPos = 0; + occupied->MainCtrlPos = 0; } else { - OK = mvOccupied->IncLocalBrakeLevel( 1 ); + OK = occupied->IncLocalBrakeLevel( 1 ); } break; } @@ -324,7 +324,7 @@ bool TController::DecBrake() { switch( bs ) { case TBrakeSystem::Individual: { auto const positionchange { 1 + std::floor( 0.5 + std::abs( AccDesired ) ) }; - OK = mvOccupied->LocalBrake == TLocalBrake::ManualBrake ? mvOccupied->DecManualBrakeLevel(positionchange) : mvOccupied->DecLocalBrakeLevel(positionchange); + OK = occupied->LocalBrake == TLocalBrake::ManualBrake ? occupied->DecManualBrakeLevel(positionchange) : occupied->DecLocalBrakeLevel(positionchange); break; } case TBrakeSystem::Pneumatic: { @@ -347,72 +347,72 @@ bool TController::DecBrake() { break; } if( brake_charge::holds_application( - bBrakeChargeHold, IsConsistCharged, mvOccupied->Vel < EU07_AI_NOMOVEMENT, BrakeCtrlPosition ) ) { + bBrakeChargeHold, IsConsistCharged, occupied->Vel < EU07_AI_NOMOVEMENT, BrakeCtrlPosition ) ) { // the order to go came while the train still charges: released now, the wagons let go as their // reservoirs fill and the train stands on a locomotive brake that doesn't hold it. the locomotive // brake stays on with it break; } - if (deltaAcc < 0 && /*GBH mvOccupied->BrakeCtrlPosR*/ BrakeCtrlPosition > 0) { - OK = /*mvOccupied->*/ BrakeLevelAdd(-0.25); - // if ((deltaAcc < 5 * fBrake_a1[0]) && (mvOccupied->BrakeCtrlPosR >= 1.2)) - // mvOccupied->BrakeLevelAdd(-1.0); - /* if (mvOccupied->BrakeCtrlPosR < 0.74) GBH */ + if (deltaAcc < 0 && /*GBH occupied->BrakeCtrlPosR*/ BrakeCtrlPosition > 0) { + OK = /*occupied->*/ BrakeLevelAdd(-0.25); + // if ((deltaAcc < 5 * fBrake_a1[0]) && (occupied->BrakeCtrlPosR >= 1.2)) + // occupied->BrakeLevelAdd(-1.0); + /* if (occupied->BrakeCtrlPosR < 0.74) GBH */ if (BrakeCtrlPosition < 0.74) - /*mvOccupied->*/ BrakeLevelSet(gbh_RP); + /*occupied->*/ BrakeLevelSet(gbh_RP); } // standing, the locomotive brake holds the train until its brakes are charged: off before, a train // released on a gradient rolls with no air to brake with. nor through DecBrakeEIM(), which takes it off // as well (the locomotive brake of a vehicle without the integrated handle) auto const holdlocomotive { ( false == IsConsistCharged ) - && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) }; + && ( occupied->Vel < EU07_AI_NOMOVEMENT ) }; if( ( !OK ) && ( false == holdlocomotive ) ) { - OK = mvOccupied->DecLocalBrakeLevel(2); + OK = occupied->DecLocalBrakeLevel(2); } if( ( !OK ) && ( false == holdlocomotive ) ) { OK = DecBrakeEIM(); } /* // NOTE: disabled, duplicate of AI's behaviour in UpdateSituation() - if (mvOccupied->PipePress < 3.0) + if (occupied->PipePress < 3.0) Need_BrakeRelease = true; */ break; } case TBrakeSystem::ElectroPneumatic: { - if( mvOccupied->EngineType == TEngineType::ElectricInductionMotor ) { - if( mvOccupied->BrakeHandle == TBrakeHandle::MHZ_EN57 ) { - if( mvOccupied->BrakeCtrlPos > mvOccupied->Handle->GetPos( bh_RP ) ) { - OK = mvOccupied->BrakeLevelAdd( -1.0 ); + if( occupied->EngineType == TEngineType::ElectricInductionMotor ) { + if( occupied->BrakeHandle == TBrakeHandle::MHZ_EN57 ) { + if( occupied->BrakeCtrlPos > occupied->Handle->GetPos( bh_RP ) ) { + OK = occupied->BrakeLevelAdd( -1.0 ); } } else { OK = DecBrakeEIM(); } } - else if( mvOccupied->Handle->TimeEP == false ) { - auto const initialbrakeposition { mvOccupied->fBrakeCtrlPos }; - auto const AccMax { std::min( fBrake_a0[ 0 ] + 12 * fBrake_a1[ 0 ], mvOccupied->MED_amax ) }; - mvOccupied->BrakeLevelSet( + else if( occupied->Handle->TimeEP == false ) { + auto const initialbrakeposition { occupied->fBrakeCtrlPos }; + auto const AccMax { std::min( fBrake_a0[ 0 ] + 12 * fBrake_a1[ 0 ], occupied->MED_amax ) }; + occupied->BrakeLevelSet( std::lerp( - mvOccupied->Handle->GetPos( bh_EPR ), - mvOccupied->Handle->GetPos( bh_EPB ), - std::clamp( -AccDesired / AccMax * mvOccupied->AIHintLocalBrakeAccFactor, 0.0, 1.0 ) ) ); - OK = mvOccupied->fBrakeCtrlPos != initialbrakeposition; + occupied->Handle->GetPos( bh_EPR ), + occupied->Handle->GetPos( bh_EPB ), + std::clamp( -AccDesired / AccMax * occupied->AIHintLocalBrakeAccFactor, 0.0, 1.0 ) ) ); + OK = occupied->fBrakeCtrlPos != initialbrakeposition; } else { OK = false; - if (mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos(bh_EPR)) { - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_EPR)); + if (occupied->fBrakeCtrlPos != occupied->Handle->GetPos(bh_EPR)) { + occupied->BrakeLevelSet(occupied->Handle->GetPos(bh_EPR)); OK = true; } - if (mvOccupied->Handle->GetPos(bh_EPR) - mvOccupied->Handle->GetPos(bh_EPN) < 0.1) { - OK = OK || mvOccupied->SwitchEPBrake(1); + if (occupied->Handle->GetPos(bh_EPR) - occupied->Handle->GetPos(bh_EPN) < 0.1) { + OK = OK || occupied->SwitchEPBrake(1); } } if( !OK ) { - OK = mvOccupied->DecLocalBrakeLevel( 2 ); + OK = occupied->DecLocalBrakeLevel( 2 ); } break; } @@ -425,62 +425,62 @@ bool TController::DecBrake() { void TController::LapBrake() { - if( mvOccupied->Handle->TimeEP ) { - if( mvOccupied->Handle->GetPos( bh_EPR ) - mvOccupied->Handle->GetPos( bh_EPN ) < 0.1 ) { - mvOccupied->SwitchEPBrake( 0 ); + if( occupied->Handle->TimeEP ) { + if( occupied->Handle->GetPos( bh_EPR ) - occupied->Handle->GetPos( bh_EPN ) < 0.1 ) { + occupied->SwitchEPBrake( 0 ); } else { - mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_EPN ) ); + occupied->BrakeLevelSet( occupied->Handle->GetPos( bh_EPN ) ); } } } void TController::ZeroLocalBrake() { - if( mvOccupied->UniCtrlIntegratedLocalBrakeCtrl ) { + if( occupied->UniCtrlIntegratedLocalBrakeCtrl ) { while( DecBrakeEIM() ) { ; } } else { - mvOccupied->DecLocalBrakeLevel( LocalBrakePosNo ); + occupied->DecLocalBrakeLevel( LocalBrakePosNo ); } } bool TController::DecBrakeEIM() { // zmniejszenie siły hamowania bool OK = false; - switch (mvOccupied->EIMCtrlType) + switch (occupied->EIMCtrlType) { case 0: { - if( mvOccupied->MED_amax != 9.81 ) { - auto const desiredacceleration { ( mvOccupied->Vel > EU07_AI_NOMOVEMENT ? AccDesired : std::max( 0.0, AccDesired ) ) }; - auto const brakeposition { std::clamp( -1.0 * mvOccupied->AIHintLocalBrakeAccFactor * desiredacceleration / mvOccupied->MED_amax, 0.0, 1.0 ) }; - OK = brakeposition != mvOccupied->LocalBrakePosA; - mvOccupied->LocalBrakePosA = brakeposition; + if( occupied->MED_amax != 9.81 ) { + auto const desiredacceleration { ( occupied->Vel > EU07_AI_NOMOVEMENT ? AccDesired : std::max( 0.0, AccDesired ) ) }; + auto const brakeposition { std::clamp( -1.0 * occupied->AIHintLocalBrakeAccFactor * desiredacceleration / occupied->MED_amax, 0.0, 1.0 ) }; + OK = brakeposition != occupied->LocalBrakePosA; + occupied->LocalBrakePosA = brakeposition; } else { - OK = mvOccupied->DecLocalBrakeLevel( 1 ); + OK = occupied->DecLocalBrakeLevel( 1 ); } break; } case 1: { - OK = mvOccupied->MainCtrlPos < 2; + OK = occupied->MainCtrlPos < 2; if( OK ) - mvOccupied->MainCtrlPos = 2; + occupied->MainCtrlPos = 2; break; } case 2: { - auto const neutralpos{mvOccupied->MainCtrlNoPowerPos()}; - OK = mvOccupied->MainCtrlPos < neutralpos; + auto const neutralpos{occupied->MainCtrlNoPowerPos()}; + OK = occupied->MainCtrlPos < neutralpos; if( OK ) - mvOccupied->MainCtrlPos = neutralpos; + occupied->MainCtrlPos = neutralpos; break; } case 3: { - OK = mvOccupied->MainCtrlPos < mvOccupied->MainCtrlMaxDirChangePos; + OK = occupied->MainCtrlPos < occupied->MainCtrlMaxDirChangePos; if( OK ) - mvOccupied->MainCtrlPos = mvOccupied->MainCtrlMaxDirChangePos; + occupied->MainCtrlPos = occupied->MainCtrlMaxDirChangePos; break; } } @@ -490,14 +490,14 @@ bool TController::DecBrakeEIM() bool TController::IncSpeed() { // zwiększenie prędkości; zwraca false, jeśli dalej się nie da zwiększać auto OK { false }; - switch (mvOccupied->EngineType) + switch (occupied->EngineType) { case TEngineType::None: // McZapkie-041003: wagon sterowniczy if (mvControlling->MainCtrlPosNo > 0) // jeśli ma czym kręcić drivingFlags.incSpeed = true; // ustawienie flagi jazdy return false; case TEngineType::ElectricSeriesMotor: - if (mvPantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) // jeśli pantografujący + if (pantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) // jeśli pantografujący { if (fOverhead2 >= 0.0) // a jazda bezprądowa ustawiana eventami (albo opuszczenie) return false; // to nici z ruszania @@ -512,7 +512,7 @@ bool TController::IncSpeed() // youBy polecił dodać 2012-09-08 v367 // na pozycji 0 przejdzie, a na pozostałych będzie czekać, aż się załączą liniowe (zgaśnie DelayCtrlFlag) auto const usehighoverloadrelaythreshold{mvControlling->TrainType != train_type::et42 // ET42 uses these variables for different purpose. TODO: fix this - && mvControlling->ImaxHi > mvControlling->ImaxLo && mvOccupied->Vel < (mvControlling->IsMotorOverloadRelayHighThresholdOn() ? 30.0 : 20.0) && + && mvControlling->ImaxHi > mvControlling->ImaxLo && occupied->Vel < (mvControlling->IsMotorOverloadRelayHighThresholdOn() ? 30.0 : 20.0) && iVehicles - ControlledEnginesCount > 0 // && ( std::fabs( mvControlling->Im ) > 0.85 * mvControlling->Imax ) && mvControlling->Imax * mvControlling->EngineVoltage * ControlledEnginesCount / @@ -528,17 +528,17 @@ bool TController::IncSpeed() auto const sufficientacceleration{AbsAccS >= (IsHeavyCargoTrain ? 0.03 : IsCargoTrain ? 0.06 : 0.09)}; auto const seriesmodefieldshunting{mvControlling->ScndCtrlPos > 0 && mvControlling->RList[mvControlling->MainCtrlPos].Bn == 1}; auto const parallelmodefieldshunting{mvControlling->ScndCtrlPos > 0 && mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1}; - auto const minvoltage{(mvPantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? mvPantographUnit->EnginePowerSource.CollectorParameters.MinV : 0.0)}; - auto const maxvoltage{(mvPantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? mvPantographUnit->EnginePowerSource.CollectorParameters.MaxV : 0.0)}; + auto const minvoltage{(pantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? pantographUnit->EnginePowerSource.CollectorParameters.MinV : 0.0)}; + auto const maxvoltage{(pantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? pantographUnit->EnginePowerSource.CollectorParameters.MaxV : 0.0)}; auto const seriesmodevoltage{std::lerp(minvoltage, maxvoltage, IsHeavyCargoTrain ? 0.35 : 0.40)}; auto const useseriesmode = mvControlling->Imax > mvControlling->ImaxLo || true == usehighoverloadrelaythreshold || fVoltage < seriesmodevoltage || (true == sufficientacceleration && true == sufficienttractionforce && - mvOccupied->Vel <= (IsCargoTrain ? 40 : 30) + (seriesmodefieldshunting ? 5 : 0) - (fAccGravity < -0.025 ? 10 : 0)); + occupied->Vel <= (IsCargoTrain ? 40 : 30) + (seriesmodefieldshunting ? 5 : 0) - (fAccGravity < -0.025 ? 10 : 0)); // when not in series mode use the first available parallel mode configuration until 50/60 km/h for passenger/cargo train // (if there's only one parallel mode configuration it'll be used regardless of current speed) auto const usefieldshunting = mvControlling->StLinFlag && mvControlling->RList[mvControlling->MainCtrlPos].R < 0.01 && false == mvControlling->IsScndCtrlLockedByMainCtrl() && (useseriesmode ? mvControlling->RList[mvControlling->MainCtrlPos].Bn == 1 : - true == sufficientacceleration && true == sufficienttractionforce && mvOccupied->Vel <= (IsCargoTrain ? 60 : 50) + (parallelmodefieldshunting ? 5 : 0) ? + true == sufficientacceleration && true == sufficienttractionforce && occupied->Vel <= (IsCargoTrain ? 60 : 50) + (parallelmodefieldshunting ? 5 : 0) ? mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1 : mvControlling->MainCtrlPos == mvControlling->MainCtrlPosNo); @@ -655,7 +655,7 @@ bool TController::IncSpeed() } break; case TEngineType::ElectricInductionMotor: - if( !IsAnyMotorOverloadRelayOpen && (Ready || drivingFlags.press || mvOccupied->ShuntMode) ) { + if( !IsAnyMotorOverloadRelayOpen && (Ready || drivingFlags.press || occupied->ShuntMode) ) { //{(BrakePress<=0.01*MaxBrakePress)} OK = IncSpeedEIM(); if (mvControlling->SpeedCtrl && mvControlling->Mains) @@ -747,7 +747,7 @@ void TController::ZeroSpeed( bool const Enforce ) { bool TController::DecSpeed(bool force) { // zmniejszenie prędkości (ale nie hamowanie) bool OK = false; // domyślnie false, aby wyszło z pętli while - switch (mvOccupied->EngineType) + switch (occupied->EngineType) { case TEngineType::None: // McZapkie-041003: wagon sterowniczy drivingFlags.incSpeed = false; // usunięcie flagi jazdy @@ -908,7 +908,7 @@ void TController::SpeedSet() { if( false == AIControllFlag ) { return; } - switch (mvOccupied->EngineType) + switch (occupied->EngineType) { case TEngineType::None: { // McZapkie-041003: wagon sterowniczy if (mvControlling->MainCtrlPosNo > 0) @@ -930,8 +930,8 @@ void TController::SpeedSet() { if( fActionTime < 0.0 ) { break; } if( false == Ready ) { break; } - if( mvOccupied->DirActive > 0 ) { - mvOccupied->DirectionForward(); //żeby EN57 jechały na drugiej nastawie + if( occupied->DirActive > 0 ) { + occupied->DirectionForward(); //żeby EN57 jechały na drugiej nastawie } if( mvControlling->MainCtrlPos > 0 @@ -1013,7 +1013,7 @@ void TController::SpeedSet() { // else // gdy nie jedzie ambitnie pod górę { // sprawdzenie, czy rozruch wysoki jest potrzebny if( ( mvControlling->Imax > mvControlling->ImaxLo ) - && ( mvOccupied->Vel >= 30.0 ) ) { // jak się rozpędził + && ( occupied->Vel >= 30.0 ) ) { // jak się rozpędził // if (fAccGravity > -0.02) // a i pochylenie mnijsze niż 2‰ mvControlling->CurrentSwitch( false ); // rozruch wysoki wyłącz } @@ -1097,7 +1097,7 @@ void TController::SpeedCntrl(double DesiredSpeed) mvControlling->IncScndCtrl(1); mvControlling->RunCommand(VehicleCommand::speedControl, DesiredSpeed, mvControlling->CabActive); } - else if (mvControlling->ScndCtrlPosNo > 1 && !mvOccupied->SpeedCtrlTypeTime) + else if (mvControlling->ScndCtrlPosNo > 1 && !occupied->SpeedCtrlTypeTime) { int DesiredPos = 1 + mvControlling->ScndCtrlPosNo * ((DesiredSpeed - 1.0) / mvControlling->Vmax); while( mvControlling->ScndCtrlPos > DesiredPos && true == mvControlling->DecScndCtrl(1) ) { ; } // all work is done in the condition loop @@ -1115,47 +1115,47 @@ void TController::SpeedCntrl(double DesiredSpeed) void TController::SetTimeControllers() { // TBD, TODO: rework this method to use hint system and regardless of driver type - if( false == AIControllFlag || 0 == mvOccupied->CabActive ) { return; } + if( false == AIControllFlag || 0 == occupied->CabActive ) { return; } //1. Check the type of Main Brake Handle if( BrakeSystem == TBrakeSystem::Pneumatic || ForcePNBrake ) { - if (mvOccupied->Handle->Time) + if (occupied->Handle->Time) { - auto const pressuredifference { mvOccupied->Handle->GetCP() - ( mvOccupied->HighPipePress - BrakeCtrlPosition * 0.25*mvOccupied->DeltaPipePress ) }; + auto const pressuredifference { occupied->Handle->GetCP() - ( occupied->HighPipePress - BrakeCtrlPosition * 0.25*occupied->DeltaPipePress ) }; if (BrakeCtrlPosition > 0 && pressuredifference > 0.05) - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_FB)); + occupied->BrakeLevelSet(occupied->Handle->GetPos(bh_FB)); else if (BrakeCtrlPosition > 0 && pressuredifference < -0.05) - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_RP)); + occupied->BrakeLevelSet(occupied->Handle->GetPos(bh_RP)); else if (BrakeCtrlPosition == 0) - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_RP)); + occupied->BrakeLevelSet(occupied->Handle->GetPos(bh_RP)); else if (BrakeCtrlPosition == -1) - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_FS)); + occupied->BrakeLevelSet(occupied->Handle->GetPos(bh_FS)); else if (BrakeCtrlPosition == -2) - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_NP)); + occupied->BrakeLevelSet(occupied->Handle->GetPos(bh_NP)); } - if( mvOccupied->BrakeHandle == TBrakeHandle::FV4a ) { - mvOccupied->BrakeLevelSet( BrakeCtrlPosition ); + if( occupied->BrakeHandle == TBrakeHandle::FV4a ) { + occupied->BrakeLevelSet( BrakeCtrlPosition ); } - if( mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K8P - || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_EN57 ) { + if( occupied->BrakeHandle == TBrakeHandle::MHZ_K8P + || occupied->BrakeHandle == TBrakeHandle::MHZ_EN57 ) { if( BrakeCtrlPosition == 0 ) { - mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_RP ) ); + occupied->BrakeLevelSet( occupied->Handle->GetPos( bh_RP ) ); } else if( BrakeCtrlPosition == -1 ) { - mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_FS ) ); + occupied->BrakeLevelSet( occupied->Handle->GetPos( bh_FS ) ); } else if( BrakeCtrlPosition == -2 ) { - mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_NP ) ); + occupied->BrakeLevelSet( occupied->Handle->GetPos( bh_NP ) ); } else if( BrakeCtrlPosition > 4.5 ) { - mvOccupied->BrakeLevelSet( 10 ); + occupied->BrakeLevelSet( 10 ); } else if( BrakeCtrlPosition > 3.70 ) { - mvOccupied->BrakeLevelSet( 9 ); + occupied->BrakeLevelSet( 9 ); } else { - mvOccupied->BrakeLevelSet( round( ( BrakeCtrlPosition * 0.4 - 0.1 ) / 0.15 ) ); + occupied->BrakeLevelSet( round( ( BrakeCtrlPosition * 0.4 - 0.1 ) / 0.15 ) ); } } } @@ -1163,37 +1163,37 @@ void TController::SetTimeControllers() //3. Check the type od EIMCtrlType /* - if (mvOccupied->EIMCtrlType > 0) + if (occupied->EIMCtrlType > 0) { - if (mvOccupied->EIMCtrlType == 1) //traxx + if (occupied->EIMCtrlType == 1) //traxx { - if (mvOccupied->LocalBrakePosA > 0.95) mvOccupied->MainCtrlPos = 0; + if (occupied->LocalBrakePosA > 0.95) occupied->MainCtrlPos = 0; } - else if (mvOccupied->EIMCtrlType == 2) //elf + else if (occupied->EIMCtrlType == 2) //elf { - if (mvOccupied->LocalBrakePosA > 0.95) mvOccupied->MainCtrlPos = 1; + if (occupied->LocalBrakePosA > 0.95) occupied->MainCtrlPos = 1; } } */ - if( mvOccupied->UniCtrlIntegratedLocalBrakeCtrl - && mvOccupied->LocalBrakePosA > 0.95 ) { + if( occupied->UniCtrlIntegratedLocalBrakeCtrl + && occupied->LocalBrakePosA > 0.95 ) { while( IncBrakeEIM() ) { ; } } //4. Check Speed Control System - if (mvOccupied->EngineType == TEngineType::ElectricInductionMotor && mvOccupied->ScndCtrlPosNo > 1 && mvOccupied->SpeedCtrlTypeTime) + if (occupied->EngineType == TEngineType::ElectricInductionMotor && occupied->ScndCtrlPosNo > 1 && occupied->SpeedCtrlTypeTime) { double SpeedCntrlVel = ActualProximityDist > std::max(50.0, fMaxProximityDist) ? VelDesired : min_speed(VelDesired, VelNext); SpeedCntrlVel = 10 * std::floor(SpeedCntrlVel*0.1); - if (mvOccupied->ScndCtrlPosNo == 4) + if (occupied->ScndCtrlPosNo == 4) { - if (mvOccupied->NewSpeed + 0.1 < SpeedCntrlVel) - mvOccupied->ScndCtrlPos = 3; - if (mvOccupied->NewSpeed - 0.1 > SpeedCntrlVel) - mvOccupied->ScndCtrlPos = 1; + if (occupied->NewSpeed + 0.1 < SpeedCntrlVel) + occupied->ScndCtrlPos = 3; + if (occupied->NewSpeed - 0.1 > SpeedCntrlVel) + occupied->ScndCtrlPos = 1; } } //5. Check Main Controller in Dizels @@ -1254,7 +1254,7 @@ void TController::SetTimeControllers() while( mvControlling->MainCtrlPos < DesiredPos ) { mvControlling->IncMainCtrl( 1 ); } } if (BrakeCtrlPosition < 0.1) //jesli nie hamuje - mvOccupied->BrakeLevelSet(mvControlling->UniCtrlList[mvControlling->MainCtrlPos].mode); //zeby nie bruzdzilo machanie zespolonym + occupied->BrakeLevelSet(mvControlling->UniCtrlList[mvControlling->MainCtrlPos].mode); //zeby nie bruzdzilo machanie zespolonym } else //5.2. Analog direct controller @@ -1322,7 +1322,7 @@ void TController::SetTimeControllers() } //6.2. Setting buttons for (int i = 0; i < 3; i++) { - mvOccupied->UniversalBrakeButton(i, UniversalBrakeButtons & mvOccupied->UniversalBrakeButtonFlag[i]); + occupied->UniversalBrakeButton(i, UniversalBrakeButtons & occupied->UniversalBrakeButtonFlag[i]); } }; @@ -1332,38 +1332,38 @@ void TController::CheckTimeControllers() if( false == AIControllFlag || 0 == mvControlling->CabActive ) { return; } //1. Check the type of Main Brake Handle - if( BrakeSystem == TBrakeSystem::ElectroPneumatic && mvOccupied->Handle->TimeEP && !ForcePNBrake ) + if( BrakeSystem == TBrakeSystem::ElectroPneumatic && occupied->Handle->TimeEP && !ForcePNBrake ) { - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_EPN)); + occupied->BrakeLevelSet(occupied->Handle->GetPos(bh_EPN)); } - if( ( BrakeSystem == TBrakeSystem::Pneumatic || ForcePNBrake ) && mvOccupied->Handle->Time ) + if( ( BrakeSystem == TBrakeSystem::Pneumatic || ForcePNBrake ) && occupied->Handle->Time ) { if (BrakeCtrlPosition > 0) - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_MB)); + occupied->BrakeLevelSet(occupied->Handle->GetPos(bh_MB)); else - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_RP)); + occupied->BrakeLevelSet(occupied->Handle->GetPos(bh_RP)); } //2. Check the type of Secondary Brake Handle //3. Check the type od EIMCtrlType - if (mvOccupied->EIMCtrlType > 0) + if (occupied->EIMCtrlType > 0) { - if (mvOccupied->EIMCtrlType == 1) //traxx + if (occupied->EIMCtrlType == 1) //traxx { - if (mvOccupied->MainCtrlPos > 3) mvOccupied->MainCtrlPos = 5; - if (mvOccupied->MainCtrlPos < 3) mvOccupied->MainCtrlPos = 1; + if (occupied->MainCtrlPos > 3) occupied->MainCtrlPos = 5; + if (occupied->MainCtrlPos < 3) occupied->MainCtrlPos = 1; } - else if (mvOccupied->EIMCtrlType == 2) //elf + else if (occupied->EIMCtrlType == 2) //elf { - auto const emergencypositions{mvOccupied->EIMCtrlEmergencyPositions()}; - if (mvOccupied->eimic > 0) mvOccupied->MainCtrlPos = 3 + emergencypositions; - if (mvOccupied->eimic < 0) mvOccupied->MainCtrlPos = 2 + emergencypositions; + auto const emergencypositions{occupied->EIMCtrlEmergencyPositions()}; + if (occupied->eimic > 0) occupied->MainCtrlPos = 3 + emergencypositions; + if (occupied->eimic < 0) occupied->MainCtrlPos = 2 + emergencypositions; } } //4. Check Speed Control System - if (mvOccupied->EngineType == TEngineType::ElectricInductionMotor && mvOccupied->ScndCtrlPosNo > 1 && mvOccupied->SpeedCtrlTypeTime && mvOccupied->ScndCtrlPosNo == 4) + if (occupied->EngineType == TEngineType::ElectricInductionMotor && occupied->ScndCtrlPosNo > 1 && occupied->SpeedCtrlTypeTime && occupied->ScndCtrlPosNo == 4) { - mvOccupied->ScndCtrlPos = 2; + occupied->ScndCtrlPos = 2; } //5. Check Main Controller in Dizels @@ -1384,7 +1384,7 @@ void TController::CheckTimeControllers() while (mvControlling->MainCtrlPos > NeutralPos) mvControlling->DecMainCtrl(1); if (DizelActualPercentage <= DizelPercentage_Speed && mvControlling->MainCtrlPos < NeutralPos) while (mvControlling->MainCtrlPos < NeutralPos) mvControlling->IncMainCtrl(1); - mvOccupied->BrakeLevelSet(mvControlling->UniCtrlList[mvControlling->MainCtrlPos].mode); //zeby nie bruzdzilo machanie zespolonym + occupied->BrakeLevelSet(mvControlling->UniCtrlList[mvControlling->MainCtrlPos].mode); //zeby nie bruzdzilo machanie zespolonym } } }; diff --git a/vehicle/ai/doors.cpp b/vehicle/ai/doors.cpp index 665c6de5f..e751dc938 100644 --- a/vehicle/ai/doors.cpp +++ b/vehicle/ai/doors.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/Driver.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "utilities/Globals.h" #include "utilities/translation.h" #include "utilities/Logs.h" @@ -57,12 +57,12 @@ void TController::Doors( bool const Open, int const Side ) { auto const prawe = 3 - lewe; // doorsteps as the timetable asks, before the doors open (eu07/maszyna#95) if( auto const doorstep { timetable::doorstep( m_stopflags ) }; - doorstep.has_value() && mvOccupied->Doors.step_enabled != *doorstep ) { + doorstep.has_value() && occupied->Doors.step_enabled != *doorstep ) { cue_action( *doorstep ? driver_hint::doorstepon : driver_hint::doorstepoff ); } // grant door control permission if it's not automatic // TBD: stricter requirements? - if( true == pVehicle->MoverParameters->Doors.permit_needed ) { + if( true == pVehicle->physics->Doors.permit_needed ) { if( Side & prawe ) { cue_action( driver_hint::doorrightpermiton ); } @@ -73,7 +73,7 @@ void TController::Doors( bool const Open, int const Side ) { // consist-wide remote signals to open doors doors // NOTE: mixed controls are left up to passengers to open doors by themselves, unless the timetable has // the driver open all the doors - if( true == timetable::opens_doors( *pVehicle->MoverParameters, m_stopflags ) ) { + if( true == timetable::opens_doors( *pVehicle->physics, m_stopflags ) ) { if( Side & prawe ) { cue_action( driver_hint::doorrightopen ); } @@ -92,9 +92,9 @@ void TController::Doors( bool const Open, int const Side ) { return; } - if (mvOccupied->Doors.has_warning && !drivingFlags.departureWarned) + if (occupied->Doors.has_warning && !drivingFlags.departureWarned) { - if (!mvOccupied->DepartureSignal) + if (!occupied->DepartureSignal) { // Not warned yet, not warning yet - start the warning signal. cue_action( driver_hint::departuresignalon ); // załącenie bzyczka @@ -108,8 +108,8 @@ void TController::Doors( bool const Open, int const Side ) { return; } - if( true == doors_open() && (pVehicle->MoverParameters->Doors.close_control == control_t::conductor || pVehicle->MoverParameters->Doors.close_control == control_t::driver || - pVehicle->MoverParameters->Doors.close_control == control_t::mixed) ) { + if( true == doors_open() && (pVehicle->physics->Doors.close_control == control_t::conductor || pVehicle->physics->Doors.close_control == control_t::driver || + pVehicle->physics->Doors.close_control == control_t::mixed) ) { // consist-wide remote signals to close doors cue_action(driver_hint::doorrightclose); cue_action(driver_hint::doorleftclose); @@ -124,15 +124,15 @@ void TController::Doors( bool const Open, int const Side ) { while( vehicle != nullptr ) { // zamykanie drzwi w pojazdach - flaga zezwolenia była by lepsza auto const ismanualdoor { - vehicle->MoverParameters->Doors.auto_velocity == -1.f - && ( vehicle->MoverParameters->Doors.close_control == control_t::passenger - || vehicle->MoverParameters->Doors.close_control == control_t::mixed ) }; + vehicle->physics->Doors.auto_velocity == -1.f + && ( vehicle->physics->Doors.close_control == control_t::passenger + || vehicle->physics->Doors.close_control == control_t::mixed ) }; if( true == ismanualdoor && ( vehicle->LoadExchangeTime() == 0.f - || vehicle->MoverParameters->Vel > EU07_AI_MOVEMENT ) ) { - vehicle->MoverParameters->OperateDoors( VehicleSide::right, false, range_t::local ); - vehicle->MoverParameters->OperateDoors( VehicleSide::left, false, range_t::local ); + || vehicle->physics->Vel > EU07_AI_MOVEMENT ) ) { + vehicle->physics->OperateDoors( VehicleSide::right, false, range_t::local ); + vehicle->physics->OperateDoors( VehicleSide::left, false, range_t::local ); } vehicle = vehicle->Next(); // pojazd podłączony z tyłu (patrząc od czoła) } @@ -179,7 +179,7 @@ TController::control_doors() { if( false == doors_open() ) { return; } // jeżeli jedzie // nie zamykać drzwi przy drganiach, bo zatrzymanie na W4 akceptuje niewielkie prędkości - if( mvOccupied->Vel > EU07_AI_MOVEMENT ) { + if( occupied->Vel > EU07_AI_MOVEMENT ) { Doors( false ); return; } @@ -202,7 +202,7 @@ TController::check_departure() { // automatyczne ruszanie po odstaniu albo spod SBL if( VelSignal == 0.0 && WaitingTime > 0.0 - && mvOccupied->RunningTrack.Velmax != 0.0 ) { + && occupied->RunningTrack.Velmax != 0.0 ) { // jeśli stoi, a upłynął czas oczekiwania i tor ma niezerową prędkość if( OrderCurrentGet() & (DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank) && drivingFlags.stopHere ) { @@ -210,7 +210,7 @@ TController::check_departure() { WaitingTime = -WaitingExpireTime; } else { - if( mvOccupied->CategoryFlag & 1 ) { // jeśli pociąg + if( occupied->CategoryFlag & 1 ) { // jeśli pociąg PrepareDirection(); // zmieni ustawiony kierunek SetVelocity( 20, 20 ); // jak się nastał, to niech jedzie 20km/h WaitingTime = 0.0; @@ -226,7 +226,7 @@ TController::check_departure() { } } } - else if( VelSignal == 0.0 && VelNext > 0.0 && mvOccupied->Vel < 1.0 && (false == iCoupler.Empty() || ( false == drivingFlags.stopHere )) ) { + else if( VelSignal == 0.0 && VelNext > 0.0 && occupied->Vel < 1.0 && (false == iCoupler.Empty() || ( false == drivingFlags.stopHere )) ) { // Ra: tu jest coś nie tak, bo bez tego warunku ruszało w manewrowym !!!! SetVelocity(VelNext, VelNext, stopSem); // omijanie SBL } @@ -274,17 +274,17 @@ void TController::GuardOpenDoor() { if (drivingFlags.guardOpenDoor) { auto *vehicle{ pVehicles[VehicleEnd::front] }; - while (vehicle != nullptr && vehicle->MoverParameters->Doors.range == 0) { + while (vehicle != nullptr && vehicle->physics->Doors.range == 0) { vehicle = vehicle->Next(); } - if (vehicle != nullptr && vehicle->MoverParameters->Doors.range > 0) { + if (vehicle != nullptr && vehicle->physics->Doors.range > 0) { auto const lewe = vehicle->DirectionGet() > 0 ? 1 : 2; auto const prawe = 3 - lewe; if (m_lastexchangeplatforms & lewe) { - vehicle->MoverParameters->OperateDoors(VehicleSide::left, true, range_t::local); + vehicle->physics->OperateDoors(VehicleSide::left, true, range_t::local); } if (m_lastexchangeplatforms & prawe) { - vehicle->MoverParameters->OperateDoors(VehicleSide::right, true, range_t::local); + vehicle->physics->OperateDoors(VehicleSide::right, true, range_t::local); } } else { diff --git a/vehicle/ai/driver.cpp b/vehicle/ai/driver.cpp index 7ad7d61d3..c78c627b2 100644 --- a/vehicle/ai/driver.cpp +++ b/vehicle/ai/driver.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/Driver.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "utilities/Globals.h" #include "utilities/translation.h" #include "utilities/Logs.h" @@ -66,9 +66,9 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, pVehicles[ VehicleEnd::rear ] = nullptr; } ControllingSet(); // utworzenie połączenia do sterowanego pojazdu - if( mvOccupied != nullptr ) { - iDirectionOrder = mvOccupied->CabActive; // 1=do przodu (w kierunku sprzęgu 0) - VehicleName = mvOccupied->Name; + if( occupied != nullptr ) { + iDirectionOrder = occupied->CabActive; // 1=do przodu (w kierunku sprzęgu 0) + VehicleName = occupied->Name; if( is_car() ) { // samochody: na podst. http://www.prawko-kwartnik.info/hamowanie.html // fDriverBraking=0.0065; //mnożone przez (v^2+40*v) [km/h] daje prawie drogę hamowania [m] @@ -89,7 +89,7 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, fAccThreshold = is_emu() ? -0.55 : is_dmu() ? -0.45 : -0.2; /* // HACK: emu with induction motors need to start their braking a bit sooner than the ones with series motors - if( ( mvOccupied->TrainType == train_type::emu ) + if( ( occupied->TrainType == train_type::emu ) && ( mvControlling->EngineType == TEngineType::ElectricInductionMotor ) ) { fAccThreshold += 0.10; } @@ -108,7 +108,7 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, drivingFlags.primary = true; // aktywnie prowadzące pojazd } - if( mvOccupied != nullptr ) { + if( occupied != nullptr ) { SetDriverPsyche(); // na końcu, bo wymaga ustawienia zmiennych } TableClear(); @@ -130,7 +130,7 @@ TController::~TController() TBrakeSystem TController::consist_brake_system() const { - if( mvOccupied->BrakeSystem != TBrakeSystem::ElectroPneumatic ) { return mvOccupied->BrakeSystem; } + if( occupied->BrakeSystem != TBrakeSystem::ElectroPneumatic ) { return occupied->BrakeSystem; } auto isepcapable = true; if( pVehicles[ VehicleEnd::front ] != pVehicles[ VehicleEnd::rear ] ) { @@ -140,10 +140,10 @@ TBrakeSystem TController::consist_brake_system() const { && vehicle != nullptr ) { // NOTE: we could simplify this by doing only check of the rear coupler, but this can be quite tricky in itself // TODO: add easier ways to access front/rear coupler taking into account vehicle's direction - isepcapable = (vehicle->MoverParameters->Couplers[VehicleEnd::front].Connected == nullptr || - (vehicle->MoverParameters->Couplers[VehicleEnd::front].CouplingFlag & Coupling::control && vehicle->MoverParameters->Couplers[VehicleEnd::front].Connected->Power > -1)) && - (vehicle->MoverParameters->Couplers[VehicleEnd::rear].Connected == nullptr || - (vehicle->MoverParameters->Couplers[VehicleEnd::rear].CouplingFlag & Coupling::control && vehicle->MoverParameters->Couplers[VehicleEnd::rear].Connected->Power > -1)); + isepcapable = (vehicle->physics->Couplers[VehicleEnd::front].Connected == nullptr || + (vehicle->physics->Couplers[VehicleEnd::front].CouplingFlag & Coupling::control && vehicle->physics->Couplers[VehicleEnd::front].Connected->Power > -1)) && + (vehicle->physics->Couplers[VehicleEnd::rear].Connected == nullptr || + (vehicle->physics->Couplers[VehicleEnd::rear].CouplingFlag & Coupling::control && vehicle->physics->Couplers[VehicleEnd::rear].Connected->Power > -1)); vehicle = vehicle->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) } } @@ -216,7 +216,7 @@ blackbox::ai_reference TController::ai_reference() const { ai.acceleration = static_cast( AccDesired ); ai.braking_distance = static_cast( fBrakeDist ); ai.timetable_vmax_kmh = ( TrainParams.TTVmax > 0.0 ? static_cast( TrainParams.TTVmax ) : -1.0f ); - ai.track_vmax_kmh = static_cast( mvOccupied->RunningTrack.Velmax ); + ai.track_vmax_kmh = static_cast( occupied->RunningTrack.Velmax ); return ai; } @@ -261,7 +261,7 @@ void TController::SetVelocity(double NewVel, double NewVelNext, TStopReason r) && OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank | DriverOrder::connect | DriverOrder::prepareEngine) // jeśli jedzie w dowolnym trybie && drivingFlags.startHorn // jezeli trąbienie włączone && ( false == drivingFlags.startHornDone && false == drivingFlags.connect ) // jeśli nie zatrąbione i nie jest to moment podłączania składu - && mvOccupied->Vel < 1.0 // jesli stoi (na razie, bo chyba powinien też, gdy hamuje przed semaforem) + && occupied->Vel < 1.0 // jesli stoi (na razie, bo chyba powinien też, gdy hamuje przed semaforem) && ( NewVel >= 1.0 || NewVel < 0.0 ) ) { // o ile prędkość jest znacząca zatrąb po odhamowaniu drivingFlags.startHornNow = true; } @@ -277,12 +277,12 @@ double TController::BrakeAccFactor() const if( fAccThreshold != 0.0 && AccDesired < 0.0 && ( ActualProximityDist > fMinProximityDist - || mvOccupied->Vel > VelDesired + fVelPlus ) ) { - Factor += fBrakeReaction * (/*mvOccupied->BrakeCtrlPosR*/ BrakeCtrlPosition < 0.5 ? 1.5 : 1) * mvOccupied->Vel / ( std::max( 0.0, ActualProximityDist ) + 1 ) * ( ( AccDesired - AbsAccS ) / fAccThreshold ); + || occupied->Vel > VelDesired + fVelPlus ) ) { + Factor += fBrakeReaction * (/*occupied->BrakeCtrlPosR*/ BrakeCtrlPosition < 0.5 ? 1.5 : 1) * occupied->Vel / ( std::max( 0.0, ActualProximityDist ) + 1 ) * ( ( AccDesired - AbsAccS ) / fAccThreshold ); } /* - if (mvOccupied->TrainType == train_type::dmu && mvOccupied->Vel > 40 && VelNext<40) - Factor *= 1 + 0.25 * ( (1600 - VelNext * VelNext) / (mvOccupied->Vel * mvOccupied->Vel) ); + if (occupied->TrainType == train_type::dmu && occupied->Vel > 40 && VelNext<40) + Factor *= 1 + 0.25 * ( (1600 - VelNext * VelNext) / (occupied->Vel * occupied->Vel) ); */ return Factor; } @@ -331,12 +331,12 @@ TController::Update( double const Timedelta ) { // NOTE: this section moved all cars to the edge of their respective roads // it may have some use eventually for collision avoidance, // but when enabled all the time it produces silly effect - if( mvOccupied->Vel > 1.0 ) { + if( occupied->Vel > 1.0 ) { // przy prowadzeniu samochodu trzeba każdą oś odsuwać oddzielnie, inaczej kicha wychodzi - if (mvOccupied->CategoryFlag & 2) // jeśli samochód - // if (fabs(mvOccupied->OffsetTrackH)Dim.W) //Ra: szerokość drogi tu powinna być? - if (!mvOccupied->ChangeOffsetH(-0.01 * mvOccupied->Vel * dt)) // ruch w poprzek drogi - mvOccupied->ChangeOffsetH(0.01 * mvOccupied->Vel * dt); // Ra: co to miało być, to nie wiem + if (occupied->CategoryFlag & 2) // jeśli samochód + // if (fabs(occupied->OffsetTrackH)Dim.W) //Ra: szerokość drogi tu powinna być? + if (!occupied->ChangeOffsetH(-0.01 * occupied->Vel * dt)) // ruch w poprzek drogi + occupied->ChangeOffsetH(0.01 * occupied->Vel * dt); // Ra: co to miało być, to nie wiem } */ update_hints(); @@ -348,7 +348,7 @@ TController::Update( double const Timedelta ) { auto const awarenessrange { std::max( 750.0, - mvOccupied->Vel > EU07_AI_MOVEMENT ? + occupied->Vel > EU07_AI_MOVEMENT ? 400 + fBrakeDist : 30.0 * fDriverDist ) }; // 1500m dla stojących pociągów; if( is_active() ) { @@ -405,7 +405,7 @@ void TController::TakeControl( bool const Aidriver, bool const Forcevehiclecheck pVehicle->DimHeadlights = false; pVehicle->HighBeamLights = false; control_lights(); // reinicjalizacja swiatel - mvOccupied->CabActivisation(true); + occupied->CabActivisation(true); iDirection = 0; // kierunek jazdy trzeba dopiero zgadnąć TableClear(); // ponowne utworzenie tabelki, bo człowiek mógł pojechać niezgodnie z sygnałami if( action() != TAction::actSleep ) { @@ -419,18 +419,18 @@ void TController::TakeControl( bool const Aidriver, bool const Forcevehiclecheck else { // jeśli nic nie robi OrderNext( DriverOrder::prepareEngine ); - if( pVehicle->MoverParameters->iLights[ ( mvOccupied->CabActive < 0 ? + if( pVehicle->physics->iLights[ ( occupied->CabActive < 0 ? VehicleEnd::rear : VehicleEnd::front ) ] & ( light::headlight_left | light::headlight_right | light::headlight_upper ) ) // któreś ze świateł zapalone? { // od wersji 357 oczekujemy podania komend dla AI przez scenerię /* - if( pVehicle->MoverParameters->iLights[ mvOccupied->CabActive < 0 ? VehicleEnd::rear : VehicleEnd::front ] & light::headlight_upper ) // górne światło zapalone + if( pVehicle->physics->iLights[ occupied->CabActive < 0 ? VehicleEnd::rear : VehicleEnd::front ] & light::headlight_upper ) // górne światło zapalone OrderNext( DriverOrder::obeyTrain ); // jazda pociągowa else OrderNext( DriverOrder::shunt ); // jazda manewrowa */ - if( mvOccupied->Vel >= 1.0 ) // jeśli jedzie (dla 0.1 ma stać) + if( occupied->Vel >= 1.0 ) // jeśli jedzie (dla 0.1 ma stać) drivingFlags.stopHere = false; // to ma nie czekać na sygnał, tylko jechać else drivingFlags.stopHere = true; // a jak stoi, to niech czeka @@ -446,7 +446,7 @@ void TController::TakeControl( bool const Aidriver, bool const Forcevehiclecheck auto const aiwasdriving { AIControllFlag == AIdriver }; if( aiwasdriving ) { // the horn, sandbox, departure signal and brake releaser the AI may have latched are momentary for the human driver - handover::release_ai_controls( *mvOccupied, *mvControlling ); + handover::release_ai_controls( *occupied, *mvControlling ); fWarningDuration = 0.0; remove_hint( driver_hint::hornon ); // the AI sets the lights directly, leave the selector in matching position so it doesn't revert them later @@ -532,7 +532,7 @@ void TController::RouteSwitch(int d) if( ( d != 0 ) && ( iRouteWanted != d ) ) { // nowy kierunek iRouteWanted = d; // zapamiętanie - if( mvOccupied->CategoryFlag & 2 ) { + if( occupied->CategoryFlag & 2 ) { // jeśli samochód for( std::size_t i = 0; i < sSpeedTable.size(); ++i ) { // szukanie pierwszego skrzyżowania i resetowanie kierunku na nim @@ -559,14 +559,14 @@ void TController::RouteSwitch(int d) */ std::string TController::OwnerName() const { - return pVehicle ? pVehicle->MoverParameters->Name : "none"; + return pVehicle ? pVehicle->physics->Name : "none"; }; bool TController::is_train() const { - return TestFlag( mvOccupied->CategoryFlag, 1 ); } + return TestFlag( occupied->CategoryFlag, 1 ); } bool TController::is_car() const { - return TestFlag( mvOccupied->CategoryFlag, 2 ); } + return TestFlag( occupied->CategoryFlag, 2 ); } bool TController::is_emu() const { return mvControlling->TrainType == train_type::emu; } @@ -578,7 +578,7 @@ bool TController::has_diesel_engine() const { return mvControlling->EngineType == TEngineType::DieselElectric || mvControlling->EngineType == TEngineType::DieselEngine; } double TController::DirectionalVel() const { - return mvOccupied->Vel * sign( iDirection * mvOccupied->V ); } + return occupied->Vel * sign( iDirection * occupied->V ); } std::vector DrivingFlags::ActiveNames() const { std::vector> const flags { diff --git a/vehicle/ai/engine.cpp b/vehicle/ai/engine.cpp index 7c134e4b5..80e80e6f1 100644 --- a/vehicle/ai/engine.cpp +++ b/vehicle/ai/engine.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/Driver.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "utilities/Globals.h" #include "utilities/translation.h" #include "utilities/Logs.h" @@ -55,7 +55,7 @@ void TController::close_line_breaker() // consist-wide ground relay reset cue_action( driver_hint::maincircuitgroundreset ); cue_action( driver_hint::tractionnmotoroverloadreset ); - if( mvOccupied->EngineType == TEngineType::DieselEngine ) { + if( occupied->EngineType == TEngineType::DieselEngine ) { // specjalnie dla SN61 żeby nie zgasł cue_action( driver_hint::mastercontrollersetidle ); } @@ -65,10 +65,10 @@ void TController::close_line_breaker() bool TController::PrepareEngine() { // odpalanie silnika // HACK: don't immediately activate inert vehicle in case the simulation is about to replace us with human driver - if( mvOccupied->Vel < 1.0 && fActionTime < 0.0 ) { return false; } + if( occupied->Vel < 1.0 && fActionTime < 0.0 ) { return false; } LastReactionTime = 0.0; - ReactionTime = mvOccupied->Vel < 5 ? PrepareTime : EasyReactionTime; // react faster with rolling start + ReactionTime = occupied->Vel < 5 ? PrepareTime : EasyReactionTime; // react faster with rolling start cue_action( driver_hint::batteryon ); cue_action( driver_hint::cabactivation); @@ -99,24 +99,24 @@ bool TController::PrepareEngine() 3.5 ) + 0.1 }; // leeway margin - if( mvPantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector - && mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 0 ) { + if( pantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector + && pantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 0 ) { // if our pantograph unit isn't a pantograph-devoid fallback - if (mvPantographUnit->PantPress < sufficientpantographpressure) { + if (pantographUnit->PantPress < sufficientpantographpressure) { // załączenie małej sprężarki - if( false == mvPantographUnit->PantAutoValve ) { + if( false == pantographUnit->PantAutoValve ) { // odłączenie zbiornika głównego, bo z nim nie da rady napompować cue_action( driver_hint::pantographairsourcesetauxiliary ); } cue_action( driver_hint::pantographcompressoron ); // załączenie sprężarki pantografów - if( mvPantographUnit->PantCompFlag ) { + if( pantographUnit->PantCompFlag ) { cue_action( driver_hint::waitpantographpressuretoolow ); } } else { // jeżeli jest wystarczające ciśnienie w pantografach - if( false == mvPantographUnit->bPantKurek3 - || mvPantographUnit->PantPress <= mvPantographUnit->ScndPipePress ) { // kurek przełączony albo główna już pompuje + if( false == pantographUnit->bPantKurek3 + || pantographUnit->PantPress <= pantographUnit->ScndPipePress ) { // kurek przełączony albo główna już pompuje cue_action( driver_hint::pantographcompressoroff ); // sprężarkę pantografów można już wyłączyć } } @@ -167,43 +167,43 @@ bool TController::PrepareEngine() cue_action( driver_hint::waitpressuretoolow ); } // enable motor blowers - if( mvOccupied->MotorBlowers[ VehicleEnd::front ].speed != 0 ) { + if( occupied->MotorBlowers[ VehicleEnd::front ].speed != 0 ) { cue_action( driver_hint::frontmotorblowerson ); } - if( mvOccupied->MotorBlowers[ VehicleEnd::rear ].speed != 0 ) { + if( occupied->MotorBlowers[ VehicleEnd::rear ].speed != 0 ) { cue_action( driver_hint::rearmotorblowerson ); } } control_field_shunting(); // sync virtual brake state with the 'real' one - if( mvOccupied->BrakeHandle != TBrakeHandle::NoHandle ) { + if( occupied->BrakeHandle != TBrakeHandle::NoHandle ) { std::unordered_map const brakepositions{ - { static_cast( mvOccupied->Handle->GetPos( bh_RP ) ), gbh_RP }, - { static_cast( mvOccupied->Handle->GetPos( bh_NP ) ), gbh_NP }, - { static_cast( mvOccupied->Handle->GetPos( bh_FS ) ), gbh_FS } }; - auto const lookup{ brakepositions.find( static_cast( mvOccupied->fBrakeCtrlPos ) ) }; + { static_cast( occupied->Handle->GetPos( bh_RP ) ), gbh_RP }, + { static_cast( occupied->Handle->GetPos( bh_NP ) ), gbh_NP }, + { static_cast( occupied->Handle->GetPos( bh_FS ) ), gbh_FS } }; + auto const lookup{ brakepositions.find( static_cast( occupied->fBrakeCtrlPos ) ) }; if( lookup != brakepositions.end() ) { BrakeLevelSet( lookup->second ); // GBH } } // set up train brake - if( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) { + if( occupied->Vel < EU07_AI_NOMOVEMENT ) { // standing: the locomotive brake first, then the pipe is filled secure_standing_train(); } - else if( ( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_RP ) ) - && ( ( false == mvOccupied->Handle->Time ) - || ( mvOccupied->Handle->GetCP() < mvOccupied->HighPipePress - 0.05 ) ) ) { + else if( ( occupied->fBrakeCtrlPos != occupied->Handle->GetPos( bh_RP ) ) + && ( ( false == occupied->Handle->Time ) + || ( occupied->Handle->GetCP() < occupied->HighPipePress - 0.05 ) ) ) { cue_action( driver_hint::trainbrakerelease ); } // sync spring brake state across consist cue_action( - mvOccupied->SpringBrake.Activate ? + occupied->SpringBrake.Activate ? driver_hint::springbrakeon : driver_hint::springbrakeoff ); } isready = false == IsAnyConverterOverloadRelayOpen - && mvOccupied->DirActive != 0 + && occupied->DirActive != 0 && false == IsAnyLineBreakerOpen && ( false == IsAnyConverterPresent || true == IsAnyConverterEnabled ) && ( false == IsAnyCompressorPresent || true == IsAnyCompressorEnabled ) @@ -234,18 +234,18 @@ TController::report_power_stall( bool const Poweravailable, double const Pantogr ai_power::state state; state.collector = mvControlling->EnginePowerSource.SourceType == TPowerSource::CurrentCollector; state.power = Poweravailable; - state.standing = mvOccupied->Vel < EU07_AI_NOMOVEMENT; - if( mvPantographUnit->PantPress >= Pantographpressure ) { + state.standing = occupied->Vel < EU07_AI_NOMOVEMENT; + if( pantographUnit->PantPress >= Pantographpressure ) { state.pantographs_up = - mvPantographUnit->Pantographs[ VehicleEnd::front ].is_active - || mvPantographUnit->Pantographs[ VehicleEnd::rear ].is_active; + pantographUnit->Pantographs[ VehicleEnd::front ].is_active + || pantographUnit->Pantographs[ VehicleEnd::rear ].is_active; } // the pantographs of the vehicle carrying them hold the wire they found above them if( auto const *carrier { pVehicle->FindPantographCarrier() }; - carrier != nullptr && carrier->MoverParameters == mvPantographUnit ) { - auto const pantographcount { std::min( carrier->iAnimType[ ANIM_PANTS ], static_cast( carrier->MoverParameters->Pantographs.size() ) ) }; + carrier != nullptr && carrier->physics == pantographUnit ) { + auto const pantographcount { std::min( carrier->iAnimType[ ANIM_PANTS ], static_cast( carrier->physics->Pantographs.size() ) ) }; for( auto index { 0 }; index < pantographcount; ++index ) { - if( true == carrier->MoverParameters->Pantographs[ index ].is_active + if( true == carrier->physics->Pantographs[ index ].is_active && carrier->pants[ index ].fParamPants->hvPowerWire != nullptr ) { state.wire = true; } @@ -261,7 +261,7 @@ TController::report_power_stall( bool const Poweravailable, double const Pantogr // wyłączanie silnika (test wyłączenia, a część wykonawcza tylko jeśli steruje komputer) bool TController::ReleaseEngine() { /* - if( mvOccupied->Vel > 0.01 ) { + if( occupied->Vel > 0.01 ) { VelDesired = 0.0; AccDesired = std::min( AccDesired, -1.25 ); // hamuj solidnie if( true == AIControllFlag ) { @@ -275,7 +275,7 @@ bool TController::ReleaseEngine() { } */ // don't bother with the rest until we're standing still - if( mvOccupied->Vel > EU07_AI_NOMOVEMENT ) { return false; } + if( occupied->Vel > EU07_AI_NOMOVEMENT ) { return false; } LastReactionTime = 0.0; ReactionTime = PrepareTime; @@ -325,8 +325,8 @@ bool TController::ReleaseEngine() { // activate parking brake // TBD: do it earlier? cue_action( driver_hint::springbrakeon ); - if( mvOccupied->LocalBrake == TLocalBrake::ManualBrake - || mvOccupied->MBrake == true ) { + if( occupied->LocalBrake == TLocalBrake::ManualBrake + || occupied->MBrake == true ) { cue_action( driver_hint::manualbrakon ); } // switch off remaining power @@ -335,11 +335,11 @@ bool TController::ReleaseEngine() { } auto const OK { - mvOccupied->DirActive == 0 + occupied->DirActive == 0 // && ( false == IsAnyCompressorEnabled ) // && ( false == IsAnyConverterEnabled ) && false == mvControlling->Mains - && false == mvOccupied->Power24vIsAvailable }; + && false == occupied->Power24vIsAvailable }; if (OK) { // jeśli się zatrzymał @@ -419,16 +419,16 @@ TController::PrepareDirection() { if( iDirection == 0 ) { // jeśli nie ma ustalonego kierunku - if( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) { // ustalenie kierunku, gdy stoi - iDirection = mvOccupied->CabActive; // wg wybranej kabiny + if( occupied->Vel < EU07_AI_NOMOVEMENT ) { // ustalenie kierunku, gdy stoi + iDirection = occupied->CabActive; // wg wybranej kabiny /* if( iDirection == 0 ) { // jeśli nie ma ustalonego kierunku - if( mvOccupied->Couplers[ VehicleEnd::rear ].Connected == nullptr ) { + if( occupied->Couplers[ VehicleEnd::rear ].Connected == nullptr ) { // jeśli z tyłu nie ma nic iDirection = -1; // jazda w kierunku sprzęgu 1 } - if( mvOccupied->Couplers[ VehicleEnd::front ].Connected == nullptr ) { + if( occupied->Couplers[ VehicleEnd::front ].Connected == nullptr ) { // jeśli z przodu nie ma nic iDirection = 1; // jazda w kierunku sprzęgu 0 } @@ -437,7 +437,7 @@ TController::PrepareDirection() { } else { // ustalenie kierunku, gdy jedzie - iDirection = mvOccupied->V >= 0 ? 1 : // jazda w kierunku sprzęgu 0 + iDirection = occupied->V >= 0 ? 1 : // jazda w kierunku sprzęgu 0 -1; // jazda w kierunku sprzęgu 1 } } diff --git a/vehicle/ai/force.cpp b/vehicle/ai/force.cpp index 33db87ede..0914e3af0 100644 --- a/vehicle/ai/force.cpp +++ b/vehicle/ai/force.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/Driver.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "utilities/Globals.h" #include "utilities/translation.h" #include "utilities/Logs.h" @@ -74,8 +74,8 @@ TController::control_tractive_and_braking_force() { control_motor_connectors(); // if the radio-stop was issued don't waste effort trying to fight it - if( true == mvOccupied->RadioStopFlag // radio-stop - && mvOccupied->Vel > EU07_AI_NOMOVEMENT ) { // and still moving + if( true == occupied->RadioStopFlag // radio-stop + && occupied->Vel > EU07_AI_NOMOVEMENT ) { // and still moving cue_action( driver_hint::mastercontrollersetzerospeed ); // just throttle down... return; // ...and don't touch any other controls } @@ -95,7 +95,7 @@ TController::control_tractive_and_braking_force() { control_braking_force(); #if LOGVELOCITY - WriteLog("BrakePos=" + AnsiString(mvOccupied->BrakeCtrlPos) + ", MainCtrl=" + + WriteLog("BrakePos=" + AnsiString(occupied->BrakeCtrlPos) + ", MainCtrl=" + AnsiString(mvControlling->MainCtrlPos)); #endif } @@ -148,7 +148,7 @@ void TController::control_tractive_force() { auto const velocity { DirectionalVel() }; // jeśli przyspieszenie pojazdu jest mniejsze niż żądane oraz... if( AccDesired > EU07_AI_NOACCELERATION // don't add power if not asked for actual speed-up - && (AbsAccS < AccDesired /*- std::min( 0.05, 0.01 * iDriverFailCount )*/ || mvOccupied->SpeedCtrlUnit.IsActive && velocity < mvOccupied->SpeedCtrlUnit.FullPowerVelocity) && + && (AbsAccS < AccDesired /*- std::min( 0.05, 0.01 * iDriverFailCount )*/ || occupied->SpeedCtrlUnit.IsActive && velocity < occupied->SpeedCtrlUnit.FullPowerVelocity) && false == drivingFlags.press && // starting uphill against the releasing brake, the power that holds the train is enough: the brake coming off // speeds the train up, more power only drags the brake and slips the wheels. nor is a notch past that taken @@ -247,7 +247,7 @@ void TController::control_uphill_start() { fUphillTractiveForce = 0.0; for( auto const *vehicle { pVehicles[ VehicleEnd::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { // Ft is signed in the vehicle's own frame, and turned into the direction of travel as AbsAccS is - fUphillTractiveForce += std::max( 0.0, vehicle->MoverParameters->Ft * ( vehicle->DirectionGet() == iDirection ? 1 : -1 ) * ( iDirection >= 0 ? 1 : -1 ) ); + fUphillTractiveForce += std::max( 0.0, vehicle->physics->Ft * ( vehicle->DirectionGet() == iDirection ? 1 : -1 ) * ( iDirection >= 0 ? 1 : -1 ) ); } fUphillHoldingForce = fMass * -fAccGravity; bUphillBrakeTopUp = false; @@ -256,8 +256,8 @@ void TController::control_uphill_start() { if( bUphillBrakeTopUp ) { return; } - if( ( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) - && ( mvOccupied->LocalBrakePosA > 0.0 ) ) { + if( ( occupied->LocalBrake != TLocalBrake::ManualBrake ) + && ( occupied->LocalBrakePosA > 0.0 ) ) { cue_action( driver_hint::independentbrakerelease ); } if( ( velocity > 1.0 ) @@ -287,8 +287,8 @@ bool TController::uphill_brake_top_up() { auto trainbrakeforce { 0.0 }; auto haswagons { false }; for( auto const *vehicle { pVehicles[ VehicleEnd::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { - if( vehicle->MoverParameters->Power < 0.01 ) { - trainbrakeforce += vehicle->MoverParameters->Fb; + if( vehicle->physics->Power < 0.01 ) { + trainbrakeforce += vehicle->physics->Fb; haswagons = true; } } @@ -297,7 +297,7 @@ bool TController::uphill_brake_top_up() { } auto const action { uphill_start::brake_top_up( UphillTopUp, trainbrakeforce, fUphillHoldingForce, BrakeCtrlPosition, fBrakeHeldTime, - mvOccupied->BrakeDelay[ mvOccupied->BrakeDelayFlag > bdelay_G ? 1 : 3 ] ) }; + occupied->BrakeDelay[ occupied->BrakeDelayFlag > bdelay_G ? 1 : 3 ] ) }; if( action == uphill_start::top_up_action::none ) { return false; } @@ -334,7 +334,7 @@ void TController::secure_standing_train() { if( false == bHasRun ) { bBrakeChargeStart = true; } - if( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) { + if( occupied->LocalBrake != TLocalBrake::ManualBrake ) { cue_action( driver_hint::independentbrakeapply ); } if( false == brake_charge::locomotive_brake_holds( locomotive_brake_force(), fMass * fAccGravity ) ) { @@ -356,13 +356,13 @@ void TController::secure_standing_train() { // no other, not on a second section or a locomotive in multiple control either, let alone one hauled dead double TController::locomotive_brake_force() const { - if( ( mvOccupied->LocalBrake == TLocalBrake::ManualBrake ) - || ( mvOccupied->MaxBrakePress[ 0 ] <= 0.0 ) ) { + if( ( occupied->LocalBrake == TLocalBrake::ManualBrake ) + || ( occupied->MaxBrakePress[ 0 ] <= 0.0 ) ) { return 0.0; } return brake_charge::locomotive_brake_force( - mvOccupied->BrakeForceP( mvOccupied->MaxBrakePress[ 0 ], 0.0 ), - mvOccupied->TotalMassxg ); + occupied->BrakeForceP( occupied->MaxBrakePress[ 0 ], 0.0 ), + occupied->TotalMassxg ); } void TController::increase_tractive_force() { @@ -370,7 +370,7 @@ void TController::increase_tractive_force() { if( fActionTime < 0.0 ) { return; } // gdy jest nakaz poczekać z jazdą, to nie ruszać if( IsAnyCouplerStretched ) { return; } // train is already stretched past its limits, don't pull even harder - if( mvOccupied->SpringBrake.Activate ) { + if( occupied->SpringBrake.Activate ) { cue_action( driver_hint::springbrakeoff ); } if( VelDesired > 0.0 // to prevent door shuffle on stop @@ -380,7 +380,7 @@ void TController::increase_tractive_force() { // Doors() call can potentially adjust fActionTime if( fActionTime < 0.0 ) { return; } } - if( true == mvOccupied->DepartureSignal ) { + if( true == occupied->DepartureSignal ) { cue_action( driver_hint::departuresignaloff ); } @@ -427,7 +427,7 @@ TController::uphill_brake_committed( double const Velocity ) const { ( BrakeSystem == TBrakeSystem::Pneumatic ) && ( BrakeCtrlPosition > 0.0 ) && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) - && ( Velocity / 3.6 / -fAccGravity < brake_response_horizon( mvOccupied, BrakeSystem, -1.0, fBrake_a0[ 0 ] ) ) ); + && ( Velocity / 3.6 / -fAccGravity < brake_response_horizon( occupied, BrakeSystem, -1.0, fBrake_a0[ 0 ] ) ) ); } void TController::control_braking_force() { @@ -474,7 +474,7 @@ void TController::control_braking_force() { fAccGravity < 0.025 ? // HACK: when going downhill be more responsive to desired deceleration fAccThreshold : std::max( -0.2, fAccThreshold ) ) }; - auto const AccMax{ std::min(fBrake_a0[0] + 12 * fBrake_a1[0], mvOccupied->MED_amax) }; + auto const AccMax{ std::min(fBrake_a0[0] + 12 * fBrake_a1[0], occupied->MED_amax) }; auto const accmargin = AccMax > 1.1 * AccDesired && fAccGravity < 0.025 ? 0.05 : 0.0; if( ( AccDesired < accthreshold // jeśli hamować - u góry ustawia się hamowanie na fAccThreshold @@ -511,14 +511,14 @@ void TController::control_braking_force() { // TODO: check whether brake delay variable still has any purpose cue_action(driver_hint::brakingforceincrease, // Ra: ten czas należy zmniejszyć, jeśli czas dojazdu do zatrzymania jest mniejszy - (3.0 + 0.5 * ((mvOccupied->BrakeDelayFlag > bdelay_G ? mvOccupied->BrakeDelay[1] : mvOccupied->BrakeDelay[3]) - 3.0)) * 0.5); // Ra: tymczasowo, bo przeżyna S1 + (3.0 + 0.5 * ((occupied->BrakeDelayFlag > bdelay_G ? occupied->BrakeDelay[1] : occupied->BrakeDelay[3]) - 3.0)) * 0.5); // Ra: tymczasowo, bo przeżyna S1 } else if( ( BrakeSystem == TBrakeSystem::Pneumatic ) && ( AccDesired < 0.0 ) && ( BrakeCtrlPosition > 0.0 ) && ( fShortfall > 0.02 ) && ( iShortfallGrowth >= 2 ) - && ( fBrakeHeldTime > brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) { + && ( fBrakeHeldTime > brake_response_horizon( occupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) { // the train has been falling further behind the demand for a while at a handle left alone for longer than // the brake takes to respond: a small step now, while it still is small, rather than the deep one the // margin above would allow only once the train is far behind @@ -533,20 +533,20 @@ void TController::control_braking_force() { && ( AIControllFlag || ( false == brake_charge::release_waits( IsConsistCharged, - mvOccupied->Vel < EU07_AI_NOMOVEMENT, - mvOccupied->fBrakeCtrlPos > mvOccupied->Handle->GetPos( bh_RP ) + 0.2 ) ) ) ) { // the human driver's handle + occupied->Vel < EU07_AI_NOMOVEMENT, + occupied->fBrakeCtrlPos > occupied->Handle->GetPos( bh_RP ) + 0.2 ) ) ) ) { // the human driver's handle // jak hamuje, to nie tykaj kranu za często // yB: luzuje hamulec dopiero przy różnicy opóźnień rzędu 0.2 // przy odłączaniu nie zwalniamy tu hamulca // sanity check to prevent unintended brake release on sharp slopes // TODO: check whether brake delay variable still has any purpose cue_action(driver_hint::brakingforcedecrease, - (mvOccupied->BrakeDelayFlag > bdelay_G ? mvOccupied->BrakeDelay[0] : mvOccupied->BrakeDelay[2]) / 3.0 * 0.5); // Ra: tymczasowo, bo przeżyna S1 + (occupied->BrakeDelayFlag > bdelay_G ? occupied->BrakeDelay[0] : occupied->BrakeDelay[2]) / 3.0 * 0.5); // Ra: tymczasowo, bo przeżyna S1 } // uphill, the locomotive brake acts at once while the train brake of a long train takes many seconds to apply: // put it on as the train comes to a stand, and at once if the train has started to roll back - if( ( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) - && ( mvOccupied->LocalBrakePosA < 1.0 ) + if( ( occupied->LocalBrake != TLocalBrake::ManualBrake ) + && ( occupied->LocalBrakePosA < 1.0 ) && ( ( uphill_stop_hold() && ( std::abs( velocity ) < 3.0 ) // a train that has slowed down short of where it is to stop and is to pull up further does not get it && ( VelDesired <= std::abs( velocity ) + 0.5 ) @@ -556,13 +556,13 @@ void TController::control_braking_force() { } // stop-gap measure to ensure cars actually brake to stop even when above calculactions go awry // instead of releasing the brakes and creeping into obstacle at 1-2 km/h - if( is_car() && VelDesired == 0.0 && velocity > VelDesired && ActualProximityDist <= fMinProximityDist && mvOccupied->LocalBrakePosA < 0.01 ) { + if( is_car() && VelDesired == 0.0 && velocity > VelDesired && ActualProximityDist <= fMinProximityDist && occupied->LocalBrakePosA < 0.01 ) { cue_action(driver_hint::brakingforceincrease); } } // odhamowywanie składu po zatrzymaniu i zabezpieczanie lokomotywy - if( mvOccupied->Vel < EU07_AI_NOMOVEMENT + if( occupied->Vel < EU07_AI_NOMOVEMENT && ( VelDesired == 0.0 || AccDesired <= EU07_AI_NOACCELERATION ) ) { @@ -579,9 +579,9 @@ void TController::control_braking_force() { void TController::apply_independent_brake_only() { - if( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) { - if( false == mvOccupied->ShuntMode // no need for independent brake if autobrake is active - && is_equal(mvOccupied->fBrakeCtrlPos, mvOccupied->Handle->GetPos(bh_RP), 0.2) ) { + if( occupied->LocalBrake != TLocalBrake::ManualBrake ) { + if( false == occupied->ShuntMode // no need for independent brake if autobrake is active + && is_equal(occupied->fBrakeCtrlPos, occupied->Handle->GetPos(bh_RP), 0.2) ) { cue_action( driver_hint::independentbrakeapply ); } else { @@ -592,27 +592,27 @@ void TController::apply_independent_brake_only() { void TController::control_releaser() { // HACK: don't immediately touch releaser in inert vehicle, in case the simulation is about to replace us with human driver - if( mvOccupied->Vel < 1.0 && fActionTime < 0.0 ) { return; } + if( occupied->Vel < 1.0 && fActionTime < 0.0 ) { return; } // TODO: combine all releaser handling in single decision tree instead of having bits all over the place // TODO: replace handle and system conditions with flag indicating releaser presence if( BrakeSystem != TBrakeSystem::Pneumatic ) { return; } auto const hasreleaser { false == (is_dmu() || is_emu()) // TODO: a more refined test than rejecting these types wholesale - && ( mvOccupied->BrakeHandle == TBrakeHandle::FV4a - || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_6P - || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K5P - || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K8P - || mvOccupied->BrakeHandle == TBrakeHandle::M394 ) }; + && ( occupied->BrakeHandle == TBrakeHandle::FV4a + || occupied->BrakeHandle == TBrakeHandle::MHZ_6P + || occupied->BrakeHandle == TBrakeHandle::MHZ_K5P + || occupied->BrakeHandle == TBrakeHandle::MHZ_K8P + || occupied->BrakeHandle == TBrakeHandle::M394 ) }; if( false == hasreleaser ) { return; } brake_releaser::conditions state; state.acceleration_desired = AccDesired; - state.pipe_pressure = mvOccupied->PipePress; - state.cylinder_pressure = mvOccupied->BrakePress; - state.control_pressure = mvOccupied->Hamulec->GetCRP(); - state.velocity = mvOccupied->Vel; + state.pipe_pressure = occupied->PipePress; + state.cylinder_pressure = occupied->BrakePress; + state.control_pressure = occupied->Hamulec->GetCRP(); + state.velocity = occupied->Vel; state.uphill_start = bUphillStart; state.pressing = drivingFlags.press; // stage 3 of uncoupling (UpdateDisconnect), from the direction change until the coupler lets go @@ -624,29 +624,29 @@ void TController::control_releaser() { // a handle which has to be moved to unlock is left where it holds the train with the train brake state.charging_standing = bBrakeChargeStart - && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) - && ( ( mvOccupied->HandleUnlock == -3 ) || ( BrakeCtrlPosition <= 0.0 ) ); + && ( occupied->Vel < EU07_AI_NOMOVEMENT ) + && ( ( occupied->HandleUnlock == -3 ) || ( BrakeCtrlPosition <= 0.0 ) ); auto const wanted { brake_releaser::decide( state ) }; auto const actuate { wanted.actuate }; auto isbrakehandleinrightposition { true }; // some vehicles require brake handle to be moved to specific position to fill up the brake pipe if( wanted.fill_pipe - && mvOccupied->HandleUnlock != -3 ) { + && occupied->HandleUnlock != -3 ) { cue_action( driver_hint::trainbrakesetpipeunlock ); - isbrakehandleinrightposition = ( BrakeCtrlPosition == mvOccupied->HandleUnlock ); + isbrakehandleinrightposition = ( BrakeCtrlPosition == occupied->HandleUnlock ); } if( actuate ) { // some vehicles may require master controller in neutral position cue_action( driver_hint::mastercontrollersetzerospeed ); - if( false == mvOccupied->Hamulec->Releaser() + if( false == occupied->Hamulec->Releaser() && isbrakehandleinrightposition ) { cue_action( driver_hint::releaseron ); } } else { - if( true == mvOccupied->Hamulec->Releaser() ) { + if( true == occupied->Hamulec->Releaser() ) { cue_action( driver_hint::releaseroff ); } } @@ -657,30 +657,30 @@ void TController::control_main_pipe() { // unlocking main pipe if( ( AccDesired > -0.03 // standing to charge before the first start, as in control_releaser() - || ( bBrakeChargeStart && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) ) ) - && true == mvOccupied->LockPipe ) { + || ( bBrakeChargeStart && ( occupied->Vel < EU07_AI_NOMOVEMENT ) ) ) + && true == occupied->LockPipe ) { UniversalBrakeButtons |= TUniversalBrake::ub_UnlockPipe; } - else if (false == mvOccupied->LockPipe ) { + else if (false == occupied->LockPipe ) { UniversalBrakeButtons &= ~TUniversalBrake::ub_UnlockPipe; } // napełnianie uderzeniowe if( BrakeSystem != TBrakeSystem::Pneumatic ) { return; } - if( mvOccupied->BrakeHandle == TBrakeHandle::FV4a - || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_6P - || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K5P - || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K8P - || mvOccupied->BrakeHandle == TBrakeHandle::M394 ) { + if( occupied->BrakeHandle == TBrakeHandle::FV4a + || occupied->BrakeHandle == TBrakeHandle::MHZ_6P + || occupied->BrakeHandle == TBrakeHandle::MHZ_K5P + || occupied->BrakeHandle == TBrakeHandle::MHZ_K8P + || occupied->BrakeHandle == TBrakeHandle::M394 ) { auto const departblocked { is_departure_blocked( DepartBlockedFSDelay ) }; - if( (drivingFlags.oerlikons || true == IsCargoTrain || departblocked) && BrakeCtrlPosition == gbh_RP && AbsAccS < 0.03 && AccDesired > -0.03 && VelDesired - mvOccupied->Vel > 2.0 && fReady > 0.35 && - ( mvOccupied->EqvtPipePress < 4.5 || departblocked ) // don't charge with a risk of overcharging the main pipe - && mvOccupied->Compressor >= 7.5 // don't charge without sufficient pressure in the tank + if( (drivingFlags.oerlikons || true == IsCargoTrain || departblocked) && BrakeCtrlPosition == gbh_RP && AbsAccS < 0.03 && AccDesired > -0.03 && VelDesired - occupied->Vel > 2.0 && fReady > 0.35 && + ( occupied->EqvtPipePress < 4.5 || departblocked ) // don't charge with a risk of overcharging the main pipe + && occupied->Compressor >= 7.5 // don't charge without sufficient pressure in the tank && BrakeChargingCooldown >= 0.0 // don't charge while cooldown is active && (ActualProximityDist > 100.0 // don't charge if we're about to be braking soon - || min_speed(mvOccupied->Vel, VelNext) >= mvOccupied->Vel) ) { + || min_speed(occupied->Vel, VelNext) >= occupied->Vel) ) { BrakeLevelSet(gbh_FS); // don't charge the brakes too often, or we risk overcharging @@ -689,12 +689,12 @@ void TController::control_main_pipe() { update_brake_charging(); - if( ( mvOccupied->Compressor < 5.0 + if( ( occupied->Compressor < 5.0 || ( BrakeCtrlPosition < gbh_RP - && ( mvOccupied->EqvtPipePress > (fReady < 0.25 ? 5.1 : 5.2) || is_brake_charging_done() ) ) ) + && ( occupied->EqvtPipePress > (fReady < 0.25 ? 5.1 : 5.2) || is_brake_charging_done() ) ) ) // the light application a charging train stands on stays, as in DecBrake() && ( false == brake_charge::holds_application( - bBrakeChargeHold, IsConsistCharged, mvOccupied->Vel < EU07_AI_NOMOVEMENT, BrakeCtrlPosition ) ) ) { + bBrakeChargeHold, IsConsistCharged, occupied->Vel < EU07_AI_NOMOVEMENT, BrakeCtrlPosition ) ) ) { cue_action( driver_hint::trainbrakerelease ); } } @@ -712,8 +712,8 @@ void TController::update_brake_charging() { } for( auto const *vehicle { pVehicles[ VehicleEnd::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { auto const isovercharged { - vehicle->MoverParameters != mvOccupied - && vehicle->MoverParameters->PipePress > FSOverchargePipePress }; + vehicle->physics != occupied + && vehicle->physics->PipePress > FSOverchargePipePress }; if( isovercharged ) { BrakeChargingPipeOverchargeStart.try_emplace( vehicle, ElapsedTime ); } @@ -733,7 +733,7 @@ double TController::consist_max_crp() const { auto result { 0.0 }; for( auto const *vehicle { pVehicles[ VehicleEnd::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { - result = std::max( result, vehicle->MoverParameters->Hamulec->GetCRP() ); + result = std::max( result, vehicle->physics->Hamulec->GetCRP() ); } return result; } @@ -744,7 +744,7 @@ bool TController::is_brake_charging_done() const { return false; } return ElapsedTime - BrakeChargingStart > FSMaxTime - || consist_max_crp() > mvOccupied->HighPipePress + FSOverchargeCRP + || consist_max_crp() > occupied->HighPipePress + FSOverchargeCRP || std::ranges::any_of( BrakeChargingPipeOverchargeStart, [this]( auto const &Vehicle ) { return ElapsedTime - Vehicle.second > FSOverchargeTime; } ); @@ -753,7 +753,7 @@ bool TController::is_brake_charging_done() const { void TController::UpdateBrakingHelper() { - if (HelperState > 0 && -AccDesired < fBrake_a0[0] + 2 * fBrake_a1[0] && mvOccupied->Vel > EU07_AI_NOMOVEMENT) { + if (HelperState > 0 && -AccDesired < fBrake_a0[0] + 2 * fBrake_a1[0] && occupied->Vel > EU07_AI_NOMOVEMENT) { HelperState = 0; } diff --git a/vehicle/ai/internal.h b/vehicle/ai/internal.h index 379d139c3..f155cf57d 100644 --- a/vehicle/ai/internal.h +++ b/vehicle/ai/internal.h @@ -17,7 +17,7 @@ http://mozilla.org/MPL/2.0/. #pragma once #include "vehicle/Driver.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "utilities/Globals.h" #include "utilities/translation.h" #include "utilities/Logs.h" @@ -108,7 +108,7 @@ const double EasyReactionTime = 0.5; //[s] przebłyski świadomości dla zwykłe const double PrepareTime = 2.0; //[s] przebłyski świadomości przy odpalaniu -double brake_response_horizon( TMoverParameters const *Vehicle, TBrakeSystem const Brakesystem, double const Acceleration, double const Brakea0 ); +double brake_response_horizon( physics::Vehicle const *Vehicle, TBrakeSystem const Brakesystem, double const Acceleration, double const Brakea0 ); double uphill_stopping_distance( double const Velocity, double const Gravity ); diff --git a/vehicle/ai/obstacles.cpp b/vehicle/ai/obstacles.cpp index 4ddd60df1..28d8cf263 100644 --- a/vehicle/ai/obstacles.cpp +++ b/vehicle/ai/obstacles.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/Driver.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "utilities/Globals.h" #include "utilities/translation.h" #include "utilities/Logs.h" @@ -153,7 +153,7 @@ void TController::SetProximityVelocity( double dist, double vel, glm::dvec3 cons dist-=10.0; }; if (dist<0.0) dist=0.0; - if ((vel<0)?true:dist>0.1*(MoverParameters->Vel*MoverParameters->Vel-vel*vel)+50) + if ((vel<0)?true:dist>0.1*(physics->Vel*physics->Vel-vel*vel)+50) {//jeśli jest dalej od umownej drogi hamowania */ PutCommand( "SetProximityVelocity", dist, vel, pos ); @@ -249,7 +249,7 @@ TCommandType TController::BackwardScan( double const Range ) // ruszać stop trzeba powtarzać, bo inaczej zatrąbi i pojedzie sam #if LOGBACKSCAN if (scandist > fMinProximityDist && - mvOccupied->Vel > EU07_AI_NOMOVEMENT && false == OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt)) + occupied->Vel > EU07_AI_NOMOVEMENT && false == OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt)) { WriteLog(edir); } @@ -268,12 +268,12 @@ TCommandType TController::BackwardScan( double const Range ) // jeśli powyżej było SetVelocity 0 0, to dociągamy pod S1 /* if ((scandist > fMinProximityDist) && - ((mvOccupied->Vel > EU07_AI_NOMOVEMENT) || (scanvel == 0.0))) + ((occupied->Vel > EU07_AI_NOMOVEMENT) || (scanvel == 0.0))) { // jeśli tarcza jest daleko, to: //- jesli pojazd jedzie, to informujemy o zmianie prędkości //- jeśli stoi, to z własnej inicjatywy może podjechać pod zamkniętą tarczę - if (mvOccupied->Vel > EU07_AI_NOMOVEMENT) // tylko jeśli jedzie + if (occupied->Vel > EU07_AI_NOMOVEMENT) // tylko jeśli jedzie { // Mechanik->PutCommand("SetProximityVelocity",scandist,scanvel,sl); #if LOGBACKSCAN // WriteLog(edir+"SetProximityVelocity "+AnsiString(scandist)+" @@ -292,7 +292,7 @@ TCommandType TController::BackwardScan( double const Range ) { // ustawiamy prędkość tylko wtedy, gdy ma ruszyć, albo stanąć albo ma stać pod // tarczą stop trzeba powtarzać, bo inaczej zatrąbi i pojedzie sam if - // ((MoverParameters->Vel==0.0)||(scanvel==0.0)) //jeśli jedzie lub ma stanąć/stać + // ((physics->Vel==0.0)||(scanvel==0.0)) //jeśli jedzie lub ma stanąć/stać { // nie dostanie komendy jeśli jedzie i ma jechać // PutCommand("ShuntVelocity",scanvel,e->Params[9].asMemCell->Value2(),&sl,stopSem); #if LOGBACKSCAN @@ -373,12 +373,12 @@ TController::scan_obstacles( double const Range ) { // HACK: vehicle order in the consist is based on intended travel direction // if our actual travel direction doesn't match that, we should be scanning from the other end of the consist // we cast to int to avoid getting confused by microstutters - auto *frontvehicle { pVehicles[ ( static_cast( mvOccupied->V ) * iDirection >= 0 ? VehicleEnd::front : VehicleEnd::rear ) ] }; + auto *frontvehicle { pVehicles[ ( static_cast( occupied->V ) * iDirection >= 0 ? VehicleEnd::front : VehicleEnd::rear ) ] }; int routescandirection; // for moving vehicle determine heading from velocity; for standing fall back on the set direction - if( std::abs(frontvehicle->MoverParameters->V) > 0.5 ? // ignore potential micro-stutters in oposite direction during "almost stop" - frontvehicle->MoverParameters->V > 0.0 : + if( std::abs(frontvehicle->physics->V) > 0.5 ? // ignore potential micro-stutters in oposite direction during "almost stop" + frontvehicle->physics->V > 0.0 : pVehicle->DirectionGet() == frontvehicle->DirectionGet() ? iDirection >= 0 : iDirection <= 0 ) { // towards coupler 0 routescandirection = NumberOf( VehicleEnd::front ); @@ -388,7 +388,7 @@ TController::scan_obstacles( double const Range ) { routescandirection = NumberOf( VehicleEnd::rear ); } /* - if( pVehicle->MoverParameters->CabOccupied < 0 ) { + if( pVehicle->physics->CabOccupied < 0 ) { // flip the scan direction in the rear cab routescandirection ^= routescandirection; } @@ -405,7 +405,7 @@ TController::scan_obstacles( double const Range ) { if( Obstacle.distance < ( is_car() ? 50 : 100 ) ) { // at short distances (re)calculate range between couplers directly - Obstacle.distance = TMoverParameters::CouplerDist( frontvehicle->MoverParameters, Obstacle.vehicle->MoverParameters ); + Obstacle.distance = physics::Vehicle::CouplerDist( frontvehicle->physics, Obstacle.vehicle->physics ); } } } @@ -446,7 +446,7 @@ TController::check_route_ahead( double const Range ) { break; } case TCommandType::cm_Command: { // komenda z komórki - if( OrderCurrentGet().Without(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank).Empty() && mvOccupied->Vel < 0.1 ) { + if( OrderCurrentGet().Without(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank).Empty() && occupied->Vel < 0.1 ) { // jedzie w dowolnym trybie albo Wait_for_orders // dopiero jak stanie /* diff --git a/vehicle/ai/orders.cpp b/vehicle/ai/orders.cpp index ce905afec..81980c17f 100644 --- a/vehicle/ai/orders.cpp +++ b/vehicle/ai/orders.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/Driver.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "utilities/Globals.h" #include "utilities/translation.h" #include "utilities/Logs.h" @@ -155,7 +155,7 @@ void TController::OrdersClear() void TController::RecognizeCommand() { // odczytuje i wykonuje komendę przekazaną lokomotywie - TCommand *c = &mvOccupied->CommandIn; + TCommand *c = &occupied->CommandIn; PutCommand(c->Text, c->Value1, c->Value2, c->Location, stopComm); c->Command = VehicleCommand::none; c->Argument.clear(); @@ -167,7 +167,7 @@ void TController::PutCommand(std::string NewCommand, double NewValue1, double Ne // zamiana na współrzędne scenerii glm::dvec3 sl { -NewLocation.X, NewLocation.Z, NewLocation.Y }; if (!PutCommand(NewCommand, NewValue1, NewValue2, &sl, reason)) - mvOccupied->PutCommand(NewCommand, NewValue1, NewValue2, NewLocation); + occupied->PutCommand(NewCommand, NewValue1, NewValue2, NewLocation); } bool TController::PutCommand( std::string NewCommand, double NewValue1, double NewValue2, glm::dvec3 const *NewLocation, TStopReason reason ) @@ -176,8 +176,8 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N { // SHP wyzwalane jest przez człon z obsadą, ale obsługiwane przez silnikowy // nie jest to najlepiej zrobione, ale bez symulacji obwodów lepiej nie będzie // Ra 2014-04: jednak przeniosłem do rozrządczego - mvOccupied->PutCommand(NewCommand, NewValue1, NewValue2, mvOccupied->Loc); - mvOccupied->RunInternalCommand(); // rozpoznaj komende bo lokomotywa jej nie rozpoznaje + occupied->PutCommand(NewCommand, NewValue1, NewValue2, occupied->Loc); + occupied->RunInternalCommand(); // rozpoznaj komende bo lokomotywa jej nie rozpoznaje return true; // załatwione } @@ -192,7 +192,7 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N if (NewCommand == "Emergency_brake") // wymuszenie zatrzymania, niezależnie kto prowadzi { // Ra: no nadal nie jest zbyt pięknie // SetVelocity(0, 0, reason); - mvOccupied->PutCommand("Emergency_brake", 1.0, 1.0, mvOccupied->Loc); + occupied->PutCommand("Emergency_brake", 1.0, 1.0, occupied->Loc); return true; // załatwione } @@ -224,14 +224,14 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N if( true == AIControllFlag ) { // simplified door closing procedure, to sync actual door state with the door state flag // NOTE: this may result in visually ugly quick switch between closing and opening the doors, but eh - if( pVehicle->MoverParameters->Doors.close_control == control_t::driver - || pVehicle->MoverParameters->Doors.close_control == control_t::mixed ) { - pVehicle->MoverParameters->OperateDoors( VehicleSide::right, false ); - pVehicle->MoverParameters->OperateDoors( VehicleSide::left, false ); + if( pVehicle->physics->Doors.close_control == control_t::driver + || pVehicle->physics->Doors.close_control == control_t::mixed ) { + pVehicle->physics->OperateDoors( VehicleSide::right, false ); + pVehicle->physics->OperateDoors( VehicleSide::left, false ); } - if( pVehicle->MoverParameters->Doors.permit_needed ) { - pVehicle->MoverParameters->PermitDoors( VehicleSide::right, false ); - pVehicle->MoverParameters->PermitDoors( VehicleSide::left, false ); + if( pVehicle->physics->Doors.permit_needed ) { + pVehicle->physics->PermitDoors( VehicleSide::right, false ); + pVehicle->physics->PermitDoors( VehicleSide::left, false ); } } drivingFlags.doorOpened = false; @@ -301,16 +301,16 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N else if (!iDirectionOrder) {//jeśli nie ma kierunku, trzeba ustalić - if (mvOccupied->V!=0.0) - iDirectionOrder=mvOccupied->V>0?1:-1; + if (occupied->V!=0.0) + iDirectionOrder=occupied->V>0?1:-1; else - iDirectionOrder=mvOccupied->CabOccupied; + iDirectionOrder=occupied->CabOccupied; if (!iDirectionOrder) iDirectionOrder=1; } */ // jeśli wysyłane z Trainset, to wszystko jest już odpowiednio ustawione // if (!NewLocation) //jeśli wysyłane z Trainset - // if (mvOccupied->CabActive*mvOccupied->V*NewValue1<0) //jeśli zadana prędkość niezgodna z + // if (occupied->CabActive*occupied->V*NewValue1<0) //jeśli zadana prędkość niezgodna z // aktualnym kierunkiem jazdy // DirectionForward(false); //jedziemy do tyłu (nawrotnik do tyłu) // CheckVehicles(); //sprawdzenie składu, AI zapali światła @@ -434,7 +434,7 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N OrderNext(o); // to samo robić po zmianie else if (!o) // jeśli wcześniej było czekanie OrderNext(DriverOrder::shunt); // to dalej jazda manewrowa - if (mvOccupied->Vel >= EU07_AI_MOVEMENT) // jeśli jedzie + if (occupied->Vel >= EU07_AI_MOVEMENT) // jeśli jedzie drivingFlags.startHorn = false; // to bez trąbienia po ruszeniu z zatrzymania // Change_direction wykona się samo i następnie przejdzie do kolejnej komendy return true; @@ -505,13 +505,13 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N if( NewValue1 >= 0.0 ) { // jeśli ilość wagonów inna niż wszystkie będzie odczepianie, // ale jeśli wagony są z przodu, to trzeba najpierw zmienić kierunek - if( mvOccupied->Couplers[mvOccupied->DirAbsolute > 0 ? VehicleEnd::rear : VehicleEnd::front].Connected == nullptr // z tyłu nic - && mvOccupied->Couplers[mvOccupied->DirAbsolute > 0 ? VehicleEnd::front : VehicleEnd::rear].Connected != nullptr ) { // a z przodu skład + if( occupied->Couplers[occupied->DirAbsolute > 0 ? VehicleEnd::rear : VehicleEnd::front].Connected == nullptr // z tyłu nic + && occupied->Couplers[occupied->DirAbsolute > 0 ? VehicleEnd::front : VehicleEnd::rear].Connected != nullptr ) { // a z przodu skład iDirectionOrder = -iDirection; // zmiana na ciągnięcie OrderNext( DriverOrder::changeDirection ); // najpierw zmień kierunek (zastąpi Disconnect) OrderPush( DriverOrder::disconnect ); // a odczep już po zmianie kierunku } - else if( mvOccupied->Couplers[ mvOccupied->DirAbsolute > 0 ? VehicleEnd::rear : VehicleEnd::front ].Connected != nullptr ) { // z tyłu coś + else if( occupied->Couplers[ occupied->DirAbsolute > 0 ? VehicleEnd::rear : VehicleEnd::front ].Connected != nullptr ) { // z tyłu coś OrderNext( DriverOrder::disconnect ); // jak ciągnie, to tylko odczep (NewValue1) wagonów } else { @@ -881,14 +881,14 @@ TController::UpdateChangeDirection() { // TODO: rework into driver mode independent routine if( false == OrderCurrentGet().HasAll(DriverOrder::changeDirection) ) { return; } - if( true == AIControllFlag && mvOccupied->Vel < EU07_AI_NOMOVEMENT ) { + if( true == AIControllFlag && occupied->Vel < EU07_AI_NOMOVEMENT ) { // sprobuj zmienic kierunek (może być zmieszane z jeszcze jakąś komendą) // jeśli się zatrzymał, to zmieniamy kierunek jazdy, a nawet kabinę/człon Activation(); // ustawienie zadanego wcześniej kierunku i ewentualne przemieszczenie AI // Change_direction (tylko dla AI) } // shared part of the routine, implement if direction matches what was requested - if( mvOccupied->Vel < EU07_AI_NOMOVEMENT + if( occupied->Vel < EU07_AI_NOMOVEMENT && iDirection == iDirectionOrder ) { // NOTE: we can't be sure there's a visible signal within scan range after direction change // which would normally overwrite the old limit, so we reset signal value manually here @@ -915,14 +915,14 @@ TController::UpdateLooseShunt() { if( autobrakerelease && Obstacle.distance < 1.0 && AccDesired > 0.1 - && mvOccupied->Vel < 1.0 ) { + && occupied->Vel < 1.0 ) { auto *vehicle { Obstacle.vehicle }; auto const direction { ( vehicle->Prev() != nullptr ? VehicleEnd::front : VehicleEnd::rear ) }; while( vehicle != nullptr ) { - if( vehicle->MoverParameters->BrakePress > 0.2 ) { - vehicle->MoverParameters->BrakeLevelSet( 0 ); // hamulec na zero, aby nie hamował - vehicle->MoverParameters->BrakeReleaser( 1 ); // wyluzuj pojazd, aby dało się dopychać + if( vehicle->physics->BrakePress > 0.2 ) { + vehicle->physics->BrakeLevelSet( 0 ); // hamulec na zero, aby nie hamował + vehicle->physics->BrakeReleaser( 1 ); // wyluzuj pojazd, aby dało się dopychać } // NOTE: we trust the consist to be arranged in a valid chain // TBD, TODO: traversal direction validation? @@ -952,7 +952,7 @@ TController::UpdateObeyTrain() { // jeśli nie przez radio tsGuardSignal.owner( pVehicle ); // place virtual conductor some distance away - tsGuardSignal.offset( { pVehicle->MoverParameters->Dim.W * -0.75f, 1.7f, std::min( -20.0, -0.2 * fLength ) } ); + tsGuardSignal.offset( { pVehicle->physics->Dim.W * -0.75f, 1.7f, std::min( -20.0, -0.2 * fLength ) } ); tsGuardSignal.play( sound_flags::exclusive ); // NOTE: we can't rely on is_playing() check as sound playback is based on distance from local camera fActionTime = -5.0; // niech trochę potrzyma @@ -961,7 +961,7 @@ TController::UpdateObeyTrain() { // radio message tsGuardSignal.owner( pVehicle ); /* - tsGuardSignal.offset( { 0.f, 2.f, pVehicle->MoverParameters->Dim.L * 0.4f * ( pVehicle->MoverParameters->CabOccupied < 0 ? -1 : 1 ) } ); + tsGuardSignal.offset( { 0.f, 2.f, pVehicle->physics->Dim.L * 0.4f * ( pVehicle->physics->CabOccupied < 0 ? -1 : 1 ) } ); tsGuardSignal.play( sound_flags::exclusive ); */ simulation::radio_message( &tsGuardSignal, iGuardRadio ); @@ -979,13 +979,13 @@ TController::UpdateConnect() { // sprzęgi sprawdzamy w pierwszej kolejności, bo jak połączony, to koniec auto *vehicle { iCouplingVehicle.value().first }; auto const couplingend { iCouplingVehicle.value().second }; - auto *vehicleparameters { vehicle->MoverParameters }; + auto *vehicleparameters { vehicle->physics }; auto const &neighbour { vehicleparameters->Neighbours[ couplingend ] }; // vehicles which can't share their control get coupled without the control connection (eu07/maszyna#520) auto expectedcoupling { iCoupler }; if( neighbour.vehicle != nullptr ) { auto const neighbourend { neighbour.vehicle_end != 2 ? neighbour.vehicle_end : vehicleparameters->Couplers[ couplingend ].ConnectedNr }; - expectedcoupling = vehicleparameters->CompatibleCoupling( EndOf( couplingend ), *neighbour.vehicle->MoverParameters, EndOf( neighbourend ), iCoupler ); + expectedcoupling = vehicleparameters->CompatibleCoupling( EndOf( couplingend ), *neighbour.vehicle->physics, EndOf( neighbourend ), iCoupler ); } if( vehicleparameters->Couplers[ couplingend ].CouplingFlag != expectedcoupling ) { if( neighbour.vehicle != nullptr && neighbour.distance < 10 ) { @@ -994,7 +994,7 @@ TController::UpdateConnect() { auto const &coupler{vehicleparameters->Couplers[couplingend]}; if (coupler.type() != TCouplerType::Automatic) { - auto const &othercoupler = neighbour.vehicle->MoverParameters->Couplers[(neighbour.vehicle_end != 2 ? neighbour.vehicle_end : coupler.ConnectedNr)]; + auto const &othercoupler = neighbour.vehicle->physics->Couplers[(neighbour.vehicle_end != 2 ? neighbour.vehicle_end : coupler.ConnectedNr)]; if (othercoupler.type() == TCouplerType::Automatic) { coupleriscompatible = false; @@ -1004,7 +1004,7 @@ TController::UpdateConnect() { // próba podczepienia if ((AIControllFlag || Global.AITrainman) && coupleriscompatible && neighbour.distance < 2) { - vehicleparameters->Attach(couplingend, neighbour.vehicle_end, neighbour.vehicle->MoverParameters, iCoupler); + vehicleparameters->Attach(couplingend, neighbour.vehicle_end, neighbour.vehicle->physics, iCoupler); } } } @@ -1039,7 +1039,7 @@ TController::unit_count( int const Threshold ) const { auto const decoupledend{ ( vehicle->DirectionGet() > 0 ? // numer sprzęgu od strony czoła składu VehicleEnd::rear : VehicleEnd::front ) }; - auto const coupling { vehicle->MoverParameters->Couplers[ decoupledend ].CouplingFlag }; + auto const coupling { vehicle->physics->Couplers[ decoupledend ].CouplingFlag }; if( coupling == Coupling::none ) { break; } @@ -1072,12 +1072,12 @@ TController::UpdateDisconnect() { if( drivingFlags.press && iDirection == iDirectionOrder ) { if( iVehicleCount >= 0 ) { // zmieni się po odczepieniu - WriteLog( "Uncoupling [" + mvOccupied->Name + "]: actuating and compressing buffers..." ); + WriteLog( "Uncoupling [" + occupied->Name + "]: actuating and compressing buffers..." ); cue_action( driver_hint::independentbrakerelease ); cue_action( driver_hint::bufferscompress ); } - WriteLog( "Uncoupling [" + mvOccupied->Name + "]: from " + ( mvOccupied->DirAbsolute > 0 ? "front" : "rear" ) ); + WriteLog( "Uncoupling [" + occupied->Name + "]: from " + ( occupied->DirAbsolute > 0 ? "front" : "rear" ) ); auto *decoupledvehicle { pVehicle }; // pojazd do odczepienia, w (pVehicle) siedzi AI int decoupledend; // numer sprzęgu, który sprawdzamy albo odczepiamy auto vehiclecount { iVehicleCount }; // ile wagonów ma zostać @@ -1087,11 +1087,11 @@ TController::UpdateDisconnect() { VehicleEnd::front : VehicleEnd::rear ); // jeżeli sprzęg zablokowany to liczymy człony jako jeden - if( decoupledvehicle->MoverParameters->Couplers[ decoupledend ].CouplingFlag & Coupling::permanent ) { + if( decoupledvehicle->physics->Couplers[ decoupledend ].CouplingFlag & Coupling::permanent ) { ++vehiclecount; } if( decoupledvehicle != pVehicle ) { - decoupledvehicle->MoverParameters->BrakeReleaser( 1 ); // wyluzuj pojazd, aby dało się dopychać + decoupledvehicle->physics->BrakeReleaser( 1 ); // wyluzuj pojazd, aby dało się dopychać } if( vehiclecount ) { // jeśli jeszcze nie koniec decoupledvehicle = decoupledvehicle->Prev(); // kolejny w stronę czoła składu (licząc od tyłu), bo dociskamy @@ -1102,7 +1102,7 @@ TController::UpdateDisconnect() { } while( vehiclecount-- ); if( decoupledvehicle == nullptr ) { // no target, or already just virtual coupling - WriteLog( "Uncoupling [" + mvOccupied->Name + "]: didn't find anything to disconnect" ); + WriteLog( "Uncoupling [" + occupied->Name + "]: didn't find anything to disconnect" ); iVehicleCount = -2; // odczepiono, co było do odczepienia } else { @@ -1110,18 +1110,18 @@ TController::UpdateDisconnect() { decoupledvehicle->Dettach( decoupledend ); } // tylko jeśli odepnie - if( decoupledvehicle->MoverParameters->Couplers[ decoupledend ].CouplingFlag == Coupling::none ) { - WriteLog( "Uncoupling [" + mvOccupied->Name + "]: uncoupled" ); + if( decoupledvehicle->physics->Couplers[ decoupledend ].CouplingFlag == Coupling::none ) { + WriteLog( "Uncoupling [" + occupied->Name + "]: uncoupled" ); iVehicleCount = -2; // update trainset state CheckVehicles( DriverOrder::disconnect ); // potentially remove coupler adapter /* - if( decoupledvehicle->MoverParameters->Couplers[ decoupledend ].has_adapter() ) { + if( decoupledvehicle->physics->Couplers[ decoupledend ].has_adapter() ) { decoupledvehicle->remove_coupler_adapter( decoupledend ); } */ - if( pVehicles[ VehicleEnd::front ]->MoverParameters->Couplers[ decoupledend ].has_adapter() ) { + if( pVehicles[ VehicleEnd::front ]->physics->Couplers[ decoupledend ].has_adapter() ) { cue_action( driver_hint::couplingadapterremove, decoupledend ); } } @@ -1134,16 +1134,16 @@ TController::UpdateDisconnect() { iDirectionBackup = iDirection; } if( false == IsConsistBraked ) { - WriteLog( "Uncoupling [" + mvOccupied->Name + "]: applying consist brakes..." ); + WriteLog( "Uncoupling [" + occupied->Name + "]: applying consist brakes..." ); cue_action( driver_hint::trainbrakeapply ); } // jeśli w miarę został zahamowany (ciśnienie mniejsze niż podane na pozycji 3, zwyle 0.37) else { - WriteLog( "Uncoupling [" + mvOccupied->Name + "]: direction change" ); + WriteLog( "Uncoupling [" + occupied->Name + "]: direction change" ); /* // TODO: test if this block is needed if( BrakeSystem == TBrakeSystem::ElectroPneumatic ) { // wyłączenie EP, gdy wystarczy (może nie być potrzebne, bo na początku jest) - mvOccupied->BrakeLevelSet( 0 ); + occupied->BrakeLevelSet( 0 ); } */ iDirectionOrder = -iDirection; // zmiana kierunku jazdy na przeciwny (dociskanie) @@ -1158,7 +1158,7 @@ TController::UpdateDisconnect() { iDirectionBackup.reset(); } if( iDirection != iDirectionOrder ) { - WriteLog( "Uncoupling [" + mvOccupied->Name + "]: second direction change" ); + WriteLog( "Uncoupling [" + occupied->Name + "]: second direction change" ); cue_action( driver_hint::mastercontrollersetreverserunlock ); cue_action( driver_hint::directionother ); // zmiana kierunku jazdy na właściwy } @@ -1178,7 +1178,7 @@ TController::handle_engine() { if( OrderCurrentGet() == DriverOrder::waitForOrders && false == iEngineActive // && ( false == AIControllFlag ) - && true == mvOccupied->Power24vIsAvailable ) { + && true == occupied->Power24vIsAvailable ) { OrderNext( DriverOrder::prepareEngine ); } // basic engine preparation diff --git a/vehicle/ai/physicslog.cpp b/vehicle/ai/physicslog.cpp index cc32e5738..3497fc827 100644 --- a/vehicle/ai/physicslog.cpp +++ b/vehicle/ai/physicslog.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/Driver.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "utilities/Globals.h" #include "utilities/translation.h" #include "utilities/Logs.h" @@ -65,24 +65,24 @@ std::string TController::physicslog_line() const { std::ostringstream line; line << std::fixed << std::setprecision( 4 ) << ElapsedTime << " " - << fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot) << " " + << fabs(11.31 * occupied->WheelDiameter * occupied->nrot) << " " << mvControlling->AccS << " " - << mvOccupied->Couplers[1].Dist << " " - << mvOccupied->Couplers[1].CForce << " " - << mvOccupied->Ft << " " - << mvOccupied->Ff << " " - << mvOccupied->Fb << " " - << mvOccupied->BrakePress << " " - << mvOccupied->PipePress << " " + << occupied->Couplers[1].Dist << " " + << occupied->Couplers[1].CForce << " " + << occupied->Ft << " " + << occupied->Ff << " " + << occupied->Fb << " " + << occupied->BrakePress << " " + << occupied->PipePress << " " << mvControlling->Im << " " << int(mvControlling->MainCtrlPos) << " " << int(mvControlling->ScndCtrlPos) << " " - << mvOccupied->fBrakeCtrlPos << " " - << mvOccupied->LocalBrakePosA << " " + << occupied->fBrakeCtrlPos << " " + << occupied->LocalBrakePosA << " " << int(mvControlling->DirActive) << " " - << ( mvOccupied->CommandIn.Text.empty() ? "none" : mvOccupied->CommandIn.Text.c_str() ) << " " - << mvOccupied->CommandIn.Value1 << " " - << mvOccupied->CommandIn.Value2 << " " + << ( 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 << " " @@ -90,7 +90,7 @@ std::string TController::physicslog_line() const { << mvControlling->diesel.heat.temperatura1 << " " << mvControlling->diesel.heat.temperatura2 << " " // vehicle speed [km/h], the second column is the wheel speed, which stays at 0 while the wheels are locked in a skid - << mvOccupied->V * 3.6 + << occupied->V * 3.6 << "\r\n"; return line.str(); } @@ -114,12 +114,12 @@ void TController::PhysicsLog() #endif #if LOGPRESS == 1 std::ostringstream line; - line << ElapsedTime << "\t" << fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot) + line << ElapsedTime << "\t" << fabs(11.31 * occupied->WheelDiameter * occupied->nrot) << "\t"; line << mvControlling->AccS << "\t"; - line << mvOccupied->PipePress << "\t" << mvOccupied->CntrlPipePress << "\t" - << mvOccupied->BrakePress << "\t"; - line << mvOccupied->Volume << "\t" << mvOccupied->Hamulec->GetCRP() << "\n"; + line << occupied->PipePress << "\t" << occupied->CntrlPipePress << "\t" + << occupied->BrakePress << "\t"; + line << occupied->Volume << "\t" << occupied->Hamulec->GetCRP() << "\n"; PhysicsLogs.append( VehicleName, line.str() ); #endif }; diff --git a/vehicle/ai/routescan.cpp b/vehicle/ai/routescan.cpp index aaf7f3988..fee849e3a 100644 --- a/vehicle/ai/routescan.cpp +++ b/vehicle/ai/routescan.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/Driver.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "utilities/Globals.h" #include "utilities/translation.h" #include "utilities/Logs.h" @@ -211,7 +211,7 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) fTrackLength -= glm::length( pVehicle->AxlePositionGet() - pVehicle->RearPosition() - + pVehicle->VectorLeft() * pVehicle->MoverParameters->OffsetTrackH ); + + pVehicle->VectorLeft() * pVehicle->physics->OffsetTrackH ); // aktualna odległość ma być ujemna gdyż jesteśmy na końcu składu fCurrentDistance = -fLength - fTrackLength; fTrackLength = pTrack->Length(); //skasowanie zmian w zmiennej żeby poprawnie liczyło w dalszych krokach @@ -297,7 +297,7 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) typeid( *pEvent ) == typeid( road_order ) ? fCurrentDistance + ProjectEventOnTrack( pEvent, pTrack, fLastDir ) : GetDistanceToEvent( pTrack, pEvent, fLastDir, fCurrentDistance ) }; - if (newspeedpoint.Set(pEvent, eventdistance, fLength, OrderCurrentGet(), mvOccupied->Vel < EU07_AI_NOMOVEMENT)) + if (newspeedpoint.Set(pEvent, eventdistance, fLength, OrderCurrentGet(), occupied->Vel < EU07_AI_NOMOVEMENT)) { fDistance = newspeedpoint.fDist; // jeśli sygnał stop, to nie ma potrzeby dalej skanować @@ -498,7 +498,7 @@ void TController::TableCheck(double fDistance) sSpeedTable[i].ResetFlags(); // to nie ma go po co trzymać (odtykacz usunie ze środka) } } - else if (sSpeedTable[i].flags & SpeedPointFlag::event && false == sSpeedTable[i].flags.HasAny(SpeedPointFlag::pointSpeed) && sSpeedTable[i].fDist < (typeid(*sSpeedTable[i].evEvent) == typeid(putvalues_event) ? -fLength : 0) && mvOccupied->CategoryFlag == 2 && + else if (sSpeedTable[i].flags & SpeedPointFlag::event && false == sSpeedTable[i].flags.HasAny(SpeedPointFlag::pointSpeed) && sSpeedTable[i].fDist < (typeid(*sSpeedTable[i].evEvent) == typeid(putvalues_event) ? -fLength : 0) && occupied->CategoryFlag == 2 && sSpeedTable[i].fDist < -0.75) // jeśli event { // jeśli jest z tyłu @@ -566,7 +566,7 @@ void TController::CheckSignalPassed( TSpeedPos const &Point, bool const Passedbe { // not bSeenAhead: found already behind the head, the train stood across it or past it, it didn't pass it if( false == signal_passing::passed_now( Passedbefore, Point.flags.HasAll(SpeedPointFlag::elapsed), Point.bSeenAhead ) - || ( mvOccupied->CategoryFlag & 1 ) == 0 ) { // railway only + || ( occupied->CategoryFlag & 1 ) == 0 ) { // railway only return; } if( is_signal_at_stop( Point ) ) { @@ -580,7 +580,7 @@ void TController::CheckSignalPassed( TSpeedPos const &Point, bool const Passedbe simulation::Blackbox.signal_passed( pVehicles[ VehicleEnd::front ], *Point.evEvent, speedatsignal, Point.evEvent->input_value( 2 ), - mvOccupied->Vel, -Point.fDist, + occupied->Vel, -Point.fDist, passing_flags_of( Point, speedatsignal, false == OrderCurrentGet().HasAny( DriverOrder::shunt | DriverOrder::looseShunt ) ) ); } } @@ -617,7 +617,7 @@ TController::train_proximity_margins( bool const Passengerstop ) const { minproximity += 5.0; maxproximity += 5.0; } - if( mvOccupied->Vel < 0.1 ) { + if( occupied->Vel < 0.1 ) { // jak stanie za daleko, to niech nie dociąga paru metrów maxproximity = std::max( maxproximity, 50.0 ); } diff --git a/vehicle/ai/situation.cpp b/vehicle/ai/situation.cpp index 9ef52112f..9e79e913e 100644 --- a/vehicle/ai/situation.cpp +++ b/vehicle/ai/situation.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/Driver.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "utilities/Globals.h" #include "utilities/translation.h" #include "utilities/Logs.h" @@ -56,14 +56,14 @@ TController::update_timers( double dt ) { WaitingTime += dt; fBrakeTime -= dt; // wpisana wartość jest zmniejszana do 0, gdy ujemna należy zmienić nastawę hamulca fBrakeHeldTime += dt; - if( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_FS ) ) { + if( occupied->fBrakeCtrlPos != occupied->Handle->GetPos( bh_FS ) ) { // brake charging timeout starts after charging ends BrakeChargingCooldown += dt; } fStopTime += dt; // zliczanie czasu postoju, nie ruszy dopóki ujemne fActionTime += dt; // czas używany przy regulacji prędkości i zamykaniu drzwi LastReactionTime += dt; - if( mvOccupied->Vel < 0.05 + if( occupied->Vel < 0.05 && OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank) ) { IdleTime += dt; } @@ -98,7 +98,7 @@ TController::control_wheelslip() { // a start that has slipped once keeps the sand on until the train is under way. with the sand off as soon as the // wheels grip again, the next notch slips again, and a heavy train on poor rails slips, grips and snatches over // and over, and may never get going (#187). a vehicle without sand starts as before - auto const velocity { std::abs( mvOccupied->Vel ) }; + auto const velocity { std::abs( occupied->Vel ) }; if( mvControlling->SlippingWheels && velocity < EU07_AI_SANDEDSTARTVELOCITY && false == mvControlling->IsMainCtrlNoPowerPos() @@ -140,10 +140,10 @@ TController::control_wheelslip() { void TController::control_pantographs() { - if( mvPantographUnit->EnginePowerSource.SourceType != TPowerSource::CurrentCollector ) { return; } + if( pantographUnit->EnginePowerSource.SourceType != TPowerSource::CurrentCollector ) { return; } - if( false == mvPantographUnit->PantAutoValve - && mvOccupied->ScndPipePress > 4.3 ) { + if( false == pantographUnit->PantAutoValve + && occupied->ScndPipePress > 4.3 ) { // gdy główna sprężarka bezpiecznie nabije ciśnienie to można przestawić kurek na zasilanie pantografów z głównej pneumatyki cue_action( driver_hint::pantographairsourcesetmain ); } @@ -160,7 +160,7 @@ TController::control_pantographs() { // or the vehicle isn't shunting auto const shuntpantographsetup { OrderCurrentGet().HasAny( DriverOrder::shunt | DriverOrder::looseShunt ) ? - mvOccupied->AIHintShuntPantstate : + occupied->AIHintShuntPantstate : 0 }; // raise/lower pantographs as needed @@ -169,7 +169,7 @@ TController::control_pantographs() { || is_emu() // special case || mvControlling->TrainType == train_type::et41 }; // special case - if( mvOccupied->Vel > EU07_AI_NOMOVEMENT ) { + if( occupied->Vel > EU07_AI_NOMOVEMENT ) { if( fOverhead2 >= 0.0 || iOverheadZero ) { // jeśli jazda bezprądowa albo z opuszczonym pantografem @@ -178,10 +178,10 @@ TController::control_pantographs() { if( fOverhead2 > 0.0 || iOverheadDown ) { // jazda z opuszczonymi pantografami - if( mvPantographUnit->Pantographs[ VehicleEnd::front ].is_active ) { + if( pantographUnit->Pantographs[ VehicleEnd::front ].is_active ) { cue_action( driver_hint::frontpantographvalveoff ); } - if( mvPantographUnit->Pantographs[ VehicleEnd::rear ].is_active ) { + if( pantographUnit->Pantographs[ VehicleEnd::rear ].is_active ) { cue_action( driver_hint::rearpantographvalveoff ); } } @@ -193,39 +193,39 @@ TController::control_pantographs() { // shunting with the pantograph setup the .fiz suggests for it control_pantographs_setup( shuntpantographsetup ); } - else if( mvOccupied->AIHintPantstate == 0 ) { + else if( occupied->AIHintPantstate == 0 ) { // jazda na tylnym if( iDirection >= 0 && useregularpantographlayout ) { // jak jedzie w kierunku sprzęgu 0 - if( mvPantographUnit->PantRearVolt == 0.0 + if( pantographUnit->PantRearVolt == 0.0 // filter out cases with single _other_ working pantograph so we don't try to raise something we can't - && ( mvPantographUnit->PantographVoltage == 0.0 - || mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 1 ) ) { + && ( pantographUnit->PantographVoltage == 0.0 + || pantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 1 ) ) { cue_action( driver_hint::rearpantographvalveon ); } } else { // jak jedzie w kierunku sprzęgu 0 - if( mvPantographUnit->PantFrontVolt == 0.0 + if( pantographUnit->PantFrontVolt == 0.0 // filter out cases with single _other_ working pantograph so we don't try to raise something we can't - && ( mvPantographUnit->PantographVoltage == 0.0 - || mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 1 ) ) { + && ( pantographUnit->PantographVoltage == 0.0 + || pantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 1 ) ) { cue_action( driver_hint::frontpantographvalveon ); } } - if( mvOccupied->Vel > 5 && mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 1 ) { + if( occupied->Vel > 5 && pantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 1 ) { // opuszczenie przedniego po rozpędzeniu się o ile jest więcej niż jeden if (iDirection >= 0 && useregularpantographlayout) // jak jedzie w kierunku sprzęgu 0 { // poczekać na podniesienie tylnego - if (mvPantographUnit->PantFrontVolt != 0.0 && mvPantographUnit->PantRearVolt != 0.0) + if (pantographUnit->PantFrontVolt != 0.0 && pantographUnit->PantRearVolt != 0.0) { // czy jest napięcie zasilające na tylnym? cue_action(driver_hint::frontpantographvalveoff); // opuszcza od sprzęgu 0 } } else { // poczekać na podniesienie przedniego - if (mvPantographUnit->PantRearVolt != 0.0 && mvPantographUnit->PantFrontVolt != 0.0) + if (pantographUnit->PantRearVolt != 0.0 && pantographUnit->PantFrontVolt != 0.0) { // czy jest napięcie zasilające na przednim? cue_action(driver_hint::rearpantographvalveoff); // opuszcza od sprzęgu 1 } @@ -235,8 +235,8 @@ TController::control_pantographs() { } else { // use suggested pantograph setup - if( mvOccupied->Vel > 5 ) { - auto const pantographsetup{ mvOccupied->AIHintPantstate }; + if( occupied->Vel > 5 ) { + auto const pantographsetup{ occupied->AIHintPantstate }; cue_action( pantographsetup & 1 << 0 ? driver_hint::frontpantographvalveon : driver_hint::frontpantographvalveoff ); cue_action( @@ -253,7 +253,7 @@ TController::control_pantographs() { } } else { - if( !mvOccupied->AIHintPantUpIfIdle || IdleTime <= 45.0 || std::abs(fStopTime) <= 15.0 || mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo <= 1 ) + if( !occupied->AIHintPantUpIfIdle || IdleTime <= 45.0 || std::abs(fStopTime) <= 15.0 || pantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo <= 1 ) { } else @@ -262,14 +262,14 @@ TController::control_pantographs() { if (iDirection >= 0 && useregularpantographlayout) { // jak jedzie w kierunku sprzęgu 0 - if (mvPantographUnit->PantFrontVolt == 0.0) + if (pantographUnit->PantFrontVolt == 0.0) { cue_action(driver_hint::frontpantographvalveon, 5); // discard the hint if speed exceeds 5 km/h } } else { - if (mvPantographUnit->PantRearVolt == 0.0) + if (pantographUnit->PantRearVolt == 0.0) { cue_action(driver_hint::rearpantographvalveon, 5); // discard the hint if speed exceeds 5 km/h } @@ -291,7 +291,7 @@ TController::control_pantographs_setup( int const Setup ) { if( rear ) { cue_action( driver_hint::rearpantographvalveon ); } - if( auto const setuplive { ( front && mvPantographUnit->PantFrontVolt != 0.0 ) || ( rear && mvPantographUnit->PantRearVolt != 0.0 ) }; + if( auto const setuplive { ( front && pantographUnit->PantFrontVolt != 0.0 ) || ( rear && pantographUnit->PantRearVolt != 0.0 ) }; false == setuplive ) { return; } @@ -308,16 +308,16 @@ TController::control_horns( double const Timedelta ) { // horn control if( fWarningDuration > 0.0 ) { // jeśli pozostało coś do wytrąbienia trąbienie trwa nadal - if( mvOccupied->WarningSignal == 0 ) { + if( occupied->WarningSignal == 0 ) { cue_action( driver_hint::hornon, 1 ); // low tone horn by default } } else { - if( mvOccupied->WarningSignal != 0 ) { + if( occupied->WarningSignal != 0 ) { cue_action( driver_hint::hornoff ); // a tu się kończy } } - if( mvOccupied->Vel > EU07_AI_MOVEMENT ) { + if( occupied->Vel > EU07_AI_MOVEMENT ) { // jesli jedzie, można odblokować trąbienie, bo się wtedy nie włączy drivingFlags.startHornDone = false; // zatrąbi dopiero jak następnym razem stanie drivingFlags.startHorn = true; // i trąbić przed następnym ruszeniem @@ -337,37 +337,37 @@ TController::control_horns( double const Timedelta ) { void TController::control_security_system( double const Timedelta ) { - if( mvOccupied->SecuritySystem.is_cabsignal_blinking() && mvOccupied->SecuritySystem.has_separate_acknowledge()) { + if( occupied->SecuritySystem.is_cabsignal_blinking() && occupied->SecuritySystem.has_separate_acknowledge()) { // jak zadziałało SHP if( false == is_emu() - && mvOccupied->DirActive == 0 ) { + && occupied->DirActive == 0 ) { cue_action( driver_hint::directionforward ); } cue_action( driver_hint::shpsystemreset ); // to skasuj if( BrakeCtrlPosition == 0 // TODO: verify whether it's 0 in all vehicle types && AccDesired > 0.0 - && mvOccupied->SecuritySystem.is_braking() ) { + && occupied->SecuritySystem.is_braking() ) { cue_action( driver_hint::trainbrakerelease ); } } - if( mvOccupied->SecuritySystem.is_blinking() ) { + if( occupied->SecuritySystem.is_blinking() ) { // jak zadziałało CA/SHP if( false == is_emu() - && mvOccupied->DirActive == 0 ) { + && occupied->DirActive == 0 ) { cue_action( driver_hint::directionforward ); } cue_action( driver_hint::securitysystemreset ); // to skasuj if( BrakeCtrlPosition == 0 // TODO: verify whether it's 0 in all vehicle types && AccDesired > 0.0 - && mvOccupied->SecuritySystem.is_braking() ) { + && occupied->SecuritySystem.is_braking() ) { cue_action( driver_hint::trainbrakerelease ); } } // basic emergency stop handling, while at it - if( true == mvOccupied->RadioStopFlag // radio-stop - && mvOccupied->Vel < 0.01 // and actual stop - && true == mvOccupied->Radio ) { // and we didn't touch the radio yet + if( true == occupied->RadioStopFlag // radio-stop + && occupied->Vel < 0.01 // and actual stop + && true == occupied->Radio ) { // and we didn't touch the radio yet // turning off the radio should reset the flag, during security system check if( m_radiocontroltime > 5.0 ) { // arbitrary delay between stop and disabling the radio cue_action( driver_hint::radiooff ); @@ -377,17 +377,17 @@ TController::control_security_system( double const Timedelta ) { } } if( iEngineActive - && ( false == mvOccupied->Radio || false == mvOccupied->RadioFuse ) - && false == mvOccupied->RadioStopFlag ) { + && ( false == occupied->Radio || false == occupied->RadioFuse ) + && false == occupied->RadioStopFlag ) { // otherwise if it's safe to do so, turn the radio back on // arbitrary 5 sec delay before switching radio back on m_radiocontroltime = std::min( m_radiocontroltime, 5.0 ); if( m_radiocontroltime < 0.0 ) { // hint at whichever of the two is open, the radio's switch or the cut-off in its power supply - if( false == mvOccupied->RadioFuse ) { + if( false == occupied->RadioFuse ) { cue_action( driver_hint::radiofuseon ); } - if( false == mvOccupied->Radio ) { + if( false == occupied->Radio ) { cue_action( driver_hint::radioon ); } } @@ -449,19 +449,19 @@ TController::control_handles() { void TController::sync_lights_selector() { - if( mvOccupied->LightsPosNo <= 0 ) { return; } + if( occupied->LightsPosNo <= 0 ) { return; } auto const *headvehicle { pVehicles[ VehicleEnd::front ] }; if( headvehicle == nullptr ) { return; } // same choice of the light table as in TDynamicObject::SetLights() - auto const lightstable { ( mvOccupied->CabOccupied * pVehicle->DirectionGet() >= 0 ? VehicleEnd::front : VehicleEnd::rear ) }; + auto const lightstable { ( occupied->CabOccupied * pVehicle->DirectionGet() >= 0 ? VehicleEnd::front : VehicleEnd::rear ) }; // same choice of the lit vehicle end as in TDynamicObject::RaLightsSet() auto const headend { ( headvehicle->iDirection > 0 ? VehicleEnd::front : VehicleEnd::rear ) }; auto const position { handover::light_selector_position( - *mvOccupied, NumberOf( lightstable ), headvehicle->MoverParameters->iLights[ headend ], headvehicle->LightList( headend ) ) }; - if( position == mvOccupied->LightsPos ) { return; } + *occupied, NumberOf( lightstable ), headvehicle->physics->iLights[ headend ], headvehicle->LightList( headend ) ) }; + if( position == occupied->LightsPos ) { return; } - mvOccupied->LightsPos = position; + occupied->LightsPos = position; // visual feedback auto *train { simulation::Trains.find( pVehicle->name() ) }; if( train != nullptr ) { @@ -474,24 +474,24 @@ TController::sync_lights_selector() { void TController::sync_lights_dimmer() { - if( mvOccupied->dimPositions.empty() ) { return; } + if( occupied->dimPositions.empty() ) { return; } auto const *headvehicle { pVehicles[ VehicleEnd::front ] }; auto const headend { ( headvehicle != nullptr && headvehicle->iDirection > 0 ? VehicleEnd::front : VehicleEnd::rear ) }; auto const headlightson { headvehicle != nullptr - && ( headvehicle->MoverParameters->iLights[ headend ] & ( light::headlight_left | light::headlight_right | light::headlight_upper ) ) != 0 }; + && ( headvehicle->physics->iLights[ headend ] & ( light::headlight_left | light::headlight_right | light::headlight_upper ) ) != 0 }; - auto const position { handover::dimmer_position( *mvOccupied, headlightson ) }; - if( position != mvOccupied->modernDimmerPosition ) { - mvOccupied->modernDimmerPosition = position; + auto const position { handover::dimmer_position( *occupied, headlightson ) }; + if( position != occupied->modernDimmerPosition ) { + occupied->modernDimmerPosition = position; // visual feedback auto *train { simulation::Trains.find( pVehicle->name() ) }; if( train != nullptr ) { train->ggModernLightDimSw.PutValue( static_cast( position ) ); } } - if( position < 0 || position >= static_cast( mvOccupied->dimPositions.size() ) ) { return; } // SetLightDimmings() doesn't check the range + if( position < 0 || position >= static_cast( occupied->dimPositions.size() ) ) { return; } // SetLightDimmings() doesn't check the range pVehicle->SetLightDimmings(); } @@ -540,9 +540,9 @@ TController::control_lights() { void TController::control_compartment_lights() { // compartment lights - if( mvOccupied->CompartmentLights.start_type != start_t::manual ) { return; } + if( occupied->CompartmentLights.start_type != start_t::manual ) { return; } - auto const currentlightstate { mvOccupied->CompartmentLights.is_enabled }; + auto const currentlightstate { occupied->CompartmentLights.is_enabled }; auto const lightlevel { Global.fLuminance * ConsistShade }; auto const desiredlightstate{ ( currentlightstate ? @@ -556,7 +556,7 @@ TController::control_compartment_lights() { void TController::UpdateCommand() { - if( mvOccupied->CommandIn.Command != VehicleCommand::none && false == mvOccupied->RunInternalCommand() ) { + if( occupied->CommandIn.Command != VehicleCommand::none && false == occupied->RunInternalCommand() ) { // rozpoznaj komende bo lokomotywa jej nie rozpoznaje RecognizeCommand(); // samo czyta komendę wstawioną do pojazdu? } @@ -566,7 +566,7 @@ void TController::UpdateNextStop() { if( fLastStopExpDist > 0.0 - && mvOccupied->DistCounter > fLastStopExpDist ) { + && occupied->DistCounter > fLastStopExpDist ) { // zaktualizować wyświetlanie rozkładu TrainParams.StationStart = TrainParams.StationIndex; fLastStopExpDist = -1.0; // usunąć licznik @@ -581,21 +581,21 @@ void TController::determine_braking_distance() { // przybliżona droga hamowania // NOTE: we're ensuring some minimal braking distance to reduce ai flipping states between starting and braking - auto const velceil { std::max( 2.0, std::ceil( mvOccupied->Vel ) ) }; + auto const velceil { std::max( 2.0, std::ceil( occupied->Vel ) ) }; fBrakeDist = fDriverBraking * velceil * ( 40.0 + velceil ); if( fMass > 1000000.0 ) { // korekta dla ciężkich, bo przeżynają - da to coś? fBrakeDist *= 2.0; } if( -fAccThreshold > 0.05 - && mvOccupied->CategoryFlag == 1 ) { + && occupied->CategoryFlag == 1 ) { fBrakeDist = velceil * velceil / 25.92 / -fAccThreshold; } - if( mvOccupied->BrakeDelayFlag == bdelay_G ) { + if( occupied->BrakeDelayFlag == bdelay_G ) { // dla nastawienia G koniecznie należy wydłużyć drogę na czas reakcji fBrakeDist += 2 * velceil; } - if( mvOccupied->Vel > 15.0 + if( occupied->Vel > 15.0 && mvControlling->EngineType == TEngineType::ElectricInductionMotor && is_emu() ) { // HACK: make the induction motor powered EMUs start braking slightly earlier @@ -702,8 +702,8 @@ TController::determine_proximity_ranges() { } // samochod (sokista też) else { - fMinProximityDist = std::max( 3.5, mvOccupied->Vel * 0.2 ); - fMaxProximityDist = std::max( 9.5, mvOccupied->Vel * 0.375 ); //[m] + fMinProximityDist = std::max( 3.5, occupied->Vel * 0.2 ); + fMaxProximityDist = std::max( 9.5, occupied->Vel * 0.375 ); //[m] if( Global.FrictionWeatherFactor < 1.f ) { // take into account weather conditions fMinProximityDist += 0.75; @@ -712,7 +712,7 @@ TController::determine_proximity_ranges() { // margines prędkości powodujący załączenie napędu fVelMinus = 2.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania - fVelPlus = std::min( 10.0, mvOccupied->Vel * 0.1 ); + fVelPlus = std::min( 10.0, occupied->Vel * 0.1 ); } break; } diff --git a/vehicle/ai/speed.cpp b/vehicle/ai/speed.cpp index 1e461e3f9..e213ef6d8 100644 --- a/vehicle/ai/speed.cpp +++ b/vehicle/ai/speed.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/Driver.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "utilities/Globals.h" #include "utilities/translation.h" #include "utilities/Logs.h" @@ -62,10 +62,10 @@ TController::braking_distance_multiplier( float const Targetvelocity ) const { if( Targetvelocity < 5.f ) { // HACK: engaged automatic transmission means extra/earlier braking effort is needed for the last leg before full stop if( is_dmu() - && mvOccupied->Vel < 40.0 + && occupied->Vel < 40.0 && Targetvelocity == 0.f ) { auto const multiplier { std::clamp( 1.f + iVehicles * 0.5f, 2.f, 4.f ) }; - return std::lerp(multiplier, 1.f, static_cast(mvOccupied->Vel / 40.0)) * frictionmultiplier; + return std::lerp(multiplier, 1.f, static_cast(occupied->Vel / 40.0)) * frictionmultiplier; } // HACK: cargo trains or trains going downhill with high braking threshold need more distance to come to a full stop if( fBrake_a0[1] > 0.2 @@ -170,7 +170,7 @@ TController::hold_train_coming_to_stand_uphill() { || ( ( BrakeSystem == TBrakeSystem::Pneumatic ) // not for a train that is short of where it is to stop and is to pull up further && ( AccDesired <= 0.0 ) - && ( vel / 3.6 / -fAccGravity <= 0.5 * brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) { + && ( vel / 3.6 / -fAccGravity <= 0.5 * brake_response_horizon( occupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) { // the gradient alone already slows the train down nearly this much; ask for enough on top of it that // the brake is applied for sure, not held back by the margin against small corrections AccDesired = std::min( AccDesired, fAccGravity - std::max( 0.15, fBrake_a0[ 0 ] ) - brake_increase_margin() ); @@ -284,7 +284,7 @@ TController::adjust_desired_speed_for_obstacles() { if( Obstacle.distance < 5000 ) { // mamy coś z przodu // prędkość pojazdu z przodu (zakładając, że jedzie w tę samą stronę!!!) - auto const k { Obstacle.vehicle->MoverParameters->Vel }; + auto const k { Obstacle.vehicle->physics->Vel }; if( k - vel < 5 ) { // porównanie modułów prędkości [km/h] @@ -298,7 +298,7 @@ TController::adjust_desired_speed_for_obstacles() { Obstacle.distance ); if( Obstacle.distance <= ( - mvOccupied->CategoryFlag & 2 ? + occupied->CategoryFlag & 2 ? 100.0 : // cars 250.0 ) ) { // others // regardless of driving mode at close distance take precaution measures: @@ -308,13 +308,13 @@ TController::adjust_desired_speed_for_obstacles() { VelDesired, std::max( k, - mvOccupied->CategoryFlag & 2 ? + occupied->CategoryFlag & 2 ? 40.0 : // cars 20.0 ) ); // others if( vel > VelDesired + fVelPlus ) { // if going too fast force some prompt braking AccPreferred = std::min( - mvOccupied->CategoryFlag & 2 ? -0.65 : // cars + occupied->CategoryFlag & 2 ? -0.65 : // cars -0.30, // others AccPreferred ); } @@ -343,7 +343,7 @@ TController::adjust_desired_speed_for_obstacles() { VelDesired = 0.0; } - if( mvOccupied->CategoryFlag & 1 + if( occupied->CategoryFlag & 1 && OrderCurrentGet() & DriverOrder::obeyTrain ) { // trains which move normally should try to stop at safe margin ActualProximityDist -= fDriverDist; @@ -353,14 +353,14 @@ TController::adjust_desired_speed_for_obstacles() { else { // jeśli oba jadą, to przyhamuj lekko i ogranicz prędkość if( Obstacle.distance < ( - mvOccupied->CategoryFlag & 2 ? + occupied->CategoryFlag & 2 ? fMaxProximityDist + 0.5 * vel : // cars 2.0 * fMaxProximityDist + 2.0 * vel ) ) { //others // jak tamten jedzie wolniej a jest w drodze hamowania AccPreferred = std::min( -0.9, AccPreferred ); VelNext = min_speed( std::round( k ) - 5.0, VelDesired ); if( Obstacle.distance <= ( - mvOccupied->CategoryFlag & 2 ? + occupied->CategoryFlag & 2 ? fMaxProximityDist : // cars 2.0 * fMaxProximityDist ) ) { //others // try to force speed change if obstacle is really close @@ -368,7 +368,7 @@ TController::adjust_desired_speed_for_obstacles() { } } } - ReactionTime = mvOccupied->Vel > EU07_AI_NOMOVEMENT ? 0.1 : // orientuj się, bo jest goraco + ReactionTime = occupied->Vel > EU07_AI_NOMOVEMENT ? 0.1 : // orientuj się, bo jest goraco 2.0; // we're already standing still, so take it easy } else { @@ -395,12 +395,12 @@ TController::adjust_desired_speed_for_limits() { VelDesired, VelSignal ); } - if( mvOccupied->RunningTrack.Velmax >= 0 ) { + if( occupied->RunningTrack.Velmax >= 0 ) { // ograniczenie prędkości z trajektorii ruchu VelDesired = min_speed( VelDesired, - mvOccupied->RunningTrack.Velmax ); // uwaga na ograniczenia szlakowej! + occupied->RunningTrack.Velmax ); // uwaga na ograniczenia szlakowej! } if( VelforDriver >= 0 ) { // tu jest zero przy zmianie kierunku jazdy @@ -414,7 +414,7 @@ TController::adjust_desired_speed_for_limits() { // recalculate potential load exchange duration check_load_exchange(); if( ExchangeTime > 0 - || mvOccupied->Vel > 2.0 ) { // HACK: force timer reset if the load exchange is cancelled due to departure + || occupied->Vel > 2.0 ) { // HACK: force timer reset if the load exchange is cancelled due to departure WaitingSet( ExchangeTime ); } if( fStopTime < 0 ) { @@ -423,7 +423,7 @@ TController::adjust_desired_speed_for_limits() { return; // speed limit can't get any lower } - if( OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank) && drivingFlags.stopHere && mvOccupied->Vel < 0.01 && VelSignalNext == 0.0 ) { + if( OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank) && drivingFlags.stopHere && occupied->Vel < 0.01 && VelSignalNext == 0.0 ) { // w Connect nie, bo moveStopHere odnosi się do stanu po połączeniu // jeśli ma czekać na wolną drogę, stoi a wyjazdu nie ma, to ma stać VelDesired = 0.0; @@ -441,7 +441,7 @@ TController::adjust_desired_speed_for_limits() { // its pneumatic brake takes to apply (while speeding up) or to release (while slowing down), which in G // is tens of seconds; never shorter than the look-ahead the AI has always used double -brake_response_horizon( TMoverParameters const *Vehicle, TBrakeSystem const Brakesystem, double const Acceleration, double const Brakea0 ) { +brake_response_horizon( physics::Vehicle const *Vehicle, TBrakeSystem const Brakesystem, double const Acceleration, double const Brakea0 ) { auto horizon { ( 1.0 - Brakea0 ) * 30.0 / 3.6 }; if( Brakesystem == TBrakeSystem::Pneumatic ) { @@ -477,7 +477,7 @@ TController::adjust_desired_speed_for_braking_curve( double const Vel ) { // allow to coast at reasonably low speed auto const brakingdistance { fBrakeDist * braking_distance_multiplier( VelNext ) }; if( auto const slowdowndistance { ( - mvOccupied->CategoryFlag == 2 ? // cars can stop on a dime, for bigger vehicles we enforce some minimal braking distance + occupied->CategoryFlag == 2 ? // cars can stop on a dime, for bigger vehicles we enforce some minimal braking distance brakingdistance : std::max( false == OrderCurrentGet().HasAny(DriverOrder::connect) ? 100.0 : 25.0, @@ -493,7 +493,7 @@ TController::adjust_desired_speed_for_braking_curve( double const Vel ) { VelNext * braking_distance_multiplier( static_cast( VelNext ) ) ); // both plans of a pneumatic brake are made from the brake table of the consist; with none (in shunting it isn't // worked out) the braking curve is the constant deceleration over the distance left, as before them - braking_curve::brake_table const braketable { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax }; + braking_curve::brake_table const braketable { fBrake_a0, fBrake_a1, BrakeAccTableSize, occupied->Vmax }; // making for a passenger stop only the time the brake takes to fill: the look-ahead the horizon // keeps as its floor was set for the stops at a signal, and a vehicle that brakes with its // independent brake, which leaves the train brake handle where it is, kept braking earlier @@ -506,11 +506,11 @@ TController::adjust_desired_speed_for_braking_curve( double const Vel ) { braking_curve::brake_acting( BrakeCtrlPosition, // IncLocalBrakeLevel() moves the independent brake handle on a vehicle without one too - ( mvOccupied->LocalBrake == TLocalBrake::PneumaticBrake || mvOccupied->LocalBrake == TLocalBrake::HydraulicBrake ) ? - mvOccupied->LocalBrakePosA : + ( occupied->LocalBrake == TLocalBrake::PneumaticBrake || occupied->LocalBrake == TLocalBrake::HydraulicBrake ) ? + occupied->LocalBrakePosA : 0.0 ), - brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ), - brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fillbrakea0 ) }; + brake_response_horizon( occupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ), + brake_response_horizon( occupied, BrakeSystem, 1.0, fillbrakea0 ) }; auto const deceleration { braking_curve::demand( approach, BrakeSystem == TBrakeSystem::Pneumatic ? &braketable : nullptr ) }; AccDesired = std::min( AccDesired, deceleration ); // najpierw hamuje mocniej, potem zluzuje if( Vel <= VelNext ) { @@ -535,7 +535,7 @@ TController::adjust_desired_speed_for_braking_curve( double const Vel ) { void TController::adjust_desired_speed_for_final_approach( double const Vel ) { - if( ( mvOccupied->CategoryFlag & 1 ) == 0 ) { + if( ( occupied->CategoryFlag & 1 ) == 0 ) { // for cars (and others) coast at low speed until we hit min proximity range VelDesired = min_speed( VelDesired, 5.0 ); return; @@ -564,7 +564,7 @@ TController::adjust_desired_speed_for_final_approach( double const Vel ) { // cast iron blocks grip harder as the train comes to a stand braking_curve::shaped_demand( Vel, VelNext, stoppingroom, fAccGravity, - { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax } ) : + { fBrake_a0, fBrake_a1, BrakeAccTableSize, occupied->Vmax } ) : ( VelNext * VelNext - Vel * Vel ) / ( 25.92 * stoppingroom ) ); if( ( fAccGravity < -0.025 ) && ( AccDesired >= fAccGravity - 0.001 ) // no brake needed at all @@ -653,7 +653,7 @@ TController::adjust_desired_speed_for_target_speed( double const Range ) { else { // jeśli daleko jechać nie można if( ActualProximityDist > ( - mvOccupied->CategoryFlag & 2 ? + occupied->CategoryFlag & 2 ? fMinProximityDist : // cars fMaxProximityDist ) ) { // trains and others // ale ma kawałek do sygnalizatora @@ -709,7 +709,7 @@ TController::adjust_desired_speed_for_current_speed() { // look ahead for as long as the brake takes to respond, since that is how long the // present acceleration will last whatever is done with the handle now; a pneumatic // brake applies and releases on its own time scale, which in G is tens of seconds - auto const horizon { brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ) }; + auto const horizon { brake_response_horizon( occupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ) }; auto const speedestimate = vel + 3.6 * horizon * AbsAccS; // already below a lower limit ahead, the train has no business speeding up towards it auto holdlimit { VelDesired }; @@ -763,7 +763,7 @@ TController::adjust_desired_speed_for_current_speed() { } } // HACK: limit acceleration for cargo trains, to reduce probability of breaking couplers on sudden jolts - auto MaxAcc{ 0.5 * mvOccupied->Couplers[(mvOccupied->DirAbsolute >= 0 ? VehicleEnd::rear : VehicleEnd::front)].FmaxC / fMass }; + auto MaxAcc{ 0.5 * occupied->Couplers[(occupied->DirAbsolute >= 0 ? VehicleEnd::rear : VehicleEnd::front)].FmaxC / fMass }; if( iVehicles - ControlledEnginesCount > 0 ) { MaxAcc *= std::clamp( vel * 0.025, 0.2, 1.0 ); } @@ -821,7 +821,7 @@ TController::adjust_desired_speed_for_braking_test() { if( ( DynamicBrakeTest == 0 ) && ( false == timetable::makes_brake_test( TrainParams.run_flags() ) ) ) { return; } // the timetable says there's none (eu07/maszyna#95) if( false == is_train() ) { return; } // not applicable - if( mvOccupied->BrakeHandle == TBrakeHandle::FVel6 ) { return; } // leads to bugs in DecBrake, disable for now + if( occupied->BrakeHandle == TBrakeHandle::FVel6 ) { return; } // leads to bugs in DecBrake, disable for now if( false == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { return; } // not applicable if( false == AIControllFlag ) { return; } // TBD: add notification about braking test and enable it for human driver as well? @@ -851,7 +851,7 @@ TController::adjust_desired_speed_for_braking_test() { VelDesired = DBT_VelocityBrake; if( ElapsedTime - DBT_BrakingTime > 1 ) { ForcePNBrake = true; - mvOccupied->EpFuseSwitch( false ); + occupied->EpFuseSwitch( false ); DynamicBrakeTest = 2; } break; @@ -883,7 +883,7 @@ TController::adjust_desired_speed_for_braking_test() { case 4: { if( Ready ) { if( BrakeSystem == TBrakeSystem::ElectroPneumatic ) { - mvOccupied->EpFuseSwitch( true ); + occupied->EpFuseSwitch( true ); } ForcePNBrake = false; DynamicBrakeTest = 5; diff --git a/vehicle/ai/speedpos.cpp b/vehicle/ai/speedpos.cpp index 0fb3b73b1..f783e4591 100644 --- a/vehicle/ai/speedpos.cpp +++ b/vehicle/ai/speedpos.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/Driver.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "utilities/Globals.h" #include "utilities/translation.h" #include "utilities/Logs.h" diff --git a/vehicle/ai/speedtable.cpp b/vehicle/ai/speedtable.cpp index 12fa2f964..c778c3199 100644 --- a/vehicle/ai/speedtable.cpp +++ b/vehicle/ai/speedtable.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/Driver.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "utilities/Globals.h" #include "utilities/translation.h" #include "utilities/Logs.h" @@ -78,7 +78,7 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN IsAtPassengerStop = false; bStopTargetIsPassengerStop = false; IsScheduledPassengerStopVisible = false; - mvOccupied->SecuritySystem.set_cabsignal_lock(false); + occupied->SecuritySystem.set_cabsignal_lock(false); // te flagi są ustawiane tutaj, w razie potrzeby drivingFlags.trackEnd = false; drivingFlags.switchFound = false; @@ -121,7 +121,7 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN && ( false == point.flags.HasAll(SpeedPointFlag::elapsed) || ispointlimit ) ) { // sygnał lub ograniczenie z przodu (+32=przejechane) // 2014-02: jeśli stoi, a ma do przejechania kawałek, to niech jedzie - if( mvOccupied->Vel < 0.01 + if( occupied->Vel < 0.01 && true == point.flags.HasAll(SpeedPointFlag::enabled | SpeedPointFlag::event | SpeedPointFlag::passengerStop) && false == IsAtPassengerStop ) { // ma podjechać bliżej - czy na pewno w tym miejscu taki warunek? @@ -130,8 +130,8 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN else { // przyspieszenie: ujemne, gdy trzeba hamować if( v >= 0.0 ) { - a = ( v * v - mvOccupied->Vel * mvOccupied->Vel ) / ( 25.92 * d ); - if( mvOccupied->Vel < v + a = ( v * v - occupied->Vel * occupied->Vel ) / ( 25.92 * d ); + if( occupied->Vel < v || v == 0.0 ) { // if we're going slower than the target velocity and there's enough room for safe stop, speed up auto const brakingdistance { 1.2 * fBrakeDist * braking_distance_multiplier( v ) }; @@ -174,7 +174,7 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN // event trzyma tylko jeśli VelNext=0, nawet po przejechaniu (nie powinno dotyczyć samochodów?) a = v > 0.0 ? fAcc : - mvOccupied->Vel < 0.01 ? + occupied->Vel < 0.01 ? 0.0 : // already standing still so no need to bother with brakes -2.0; // ruszanie albo hamowanie } @@ -184,7 +184,7 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN if( railwaytrackend ) { // if the railway track ends here set the velnext accordingly as well // TODO: test this with turntables and such - auto const stopatendacceleration = -1.0 * mvOccupied->Vel * mvOccupied->Vel / ( 25.92 * ( d + point.trTrack->Length() ) ); + auto const stopatendacceleration = -1.0 * occupied->Vel * occupied->Vel / ( 25.92 * ( d + point.trTrack->Length() ) ); if( stopatendacceleration < a ) { a = stopatendacceleration; v = 0.0; @@ -279,7 +279,7 @@ TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fN //analiza spisanych z tabelki ograniczeń i nadpisanie aktualnego // if stopped at a valid passenger stop, hold there - if( true == IsAtPassengerStop && mvOccupied->Vel < 0.01 ) { + if( true == IsAtPassengerStop && occupied->Vel < 0.01 ) { fVelDes = 0.0; } else { @@ -350,7 +350,7 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub pVehicle->asName, TrainParams.TrainName, simulation::Time.data().wHour, simulation::Time.data().wMinute, asNextStop)); // informacja #endif // przy jakim dystansie (stanie licznika) ma przesunąć na następny postój - fLastStopExpDist = mvOccupied->DistCounter + 0.250 + 0.001 * fLength; + fLastStopExpDist = occupied->DistCounter + 0.250 + 0.001 * fLength; TrainParams.UpdateMTable( simulation::Time, asNextStop ); record_station( Point, blackbox::station_kinds::passed ); UpdateDelayFlag(); @@ -427,7 +427,7 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub //jeśli nie widzi następnego sygnału ustawia dotychczasową eSignNext = Point.evEvent; } - if( mvOccupied->Vel > EU07_AI_MOVEMENT ) { + if( occupied->Vel > EU07_AI_MOVEMENT ) { // jeśli jedzie (nie trzeba czekać, aż się drgania wytłumią - drzwi zamykane od 1.0) to będzie zatrzymanie Point.fVelNext = 0; // potentially announce pending stop @@ -517,7 +517,7 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub IsAtPassengerStop = false; record_station( Point, blackbox::station_kinds::ready ); // przy jakim dystansie (stanie licznika) ma przesunąć na następny postój - fLastStopExpDist = mvOccupied->DistCounter + 0.050 + 0.001 * fLength; + fLastStopExpDist = occupied->DistCounter + 0.050 + 0.001 * fLength; TrainParams.StationIndexInc(); // przejście do następnej asNextStop = TrainParams.NextStop(); // pobranie kolejnego miejsca zatrzymania #if LOGSTOPS @@ -619,7 +619,7 @@ bool TController::is_road_velocity_held( TSpeedPos const &Point ) const { return Point.flags.HasAll(SpeedPointFlag::roadSpeed) - && mvOccupied->CategoryFlag != 2 + && occupied->CategoryFlag != 2 && Point.fDist >= -fLength; } @@ -659,7 +659,7 @@ TController::TableUpdateRoadVelocity( TSpeedPos &Point ) { if( Point.fDist >= 0.0 ) { return false; } - if( mvOccupied->CategoryFlag == 2 ) { + if( occupied->CategoryFlag == 2 ) { VelRoad = Point.fVelNext; return false; } @@ -845,8 +845,8 @@ void TController::apply_point_limits( double &Velocity, double &Distance, double // the same as for a point of the speed table ahead auto const v { limit.velocity }; auto const d { limit.distance }; - auto a { ( v * v - mvOccupied->Vel * mvOccupied->Vel ) / ( 25.92 * d ) }; - if( mvOccupied->Vel < v ) { + auto a { ( v * v - occupied->Vel * occupied->Vel ) / ( 25.92 * d ) }; + if( occupied->Vel < v ) { auto const brakingdistance { 1.2 * fBrakeDist * braking_distance_multiplier( v ) }; if( brakingdistance > 0.0 ) { a = std::lerp( a, AccPreferred, std::clamp( ( d - brakingdistance ) / brakingdistance, 0.0, 1.0 ) ); @@ -869,7 +869,7 @@ double TController::point_limit_approach() const { // a point limit holds at its point and not a metre beyond, so the braking curve alone leaves a slow consist // coasting above it (the deceleration asked for is below what makes the driver brake). within the final // approach, and five seconds of the present speed before it, the speed is held down to it already - return fMaxProximityDist + mvOccupied->Vel / 3.6 * 5.0; + return fMaxProximityDist + occupied->Vel / 3.6 * 5.0; } glm::dvec3 TController::travel_direction() const { @@ -943,19 +943,19 @@ TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPo case TCommandType::cm_SecuritySystemMagnet: { // NOTE: magnet induction calculation presumes the driver is located in the front vehicle // TBD, TODO: take into account actual position of controlled/occupied vehicle in the consist, whichever comes first - auto const magnetlocation { pVehicles[ VehicleEnd::front ]->MoverParameters->SecuritySystem.MagnetLocation }; + auto const magnetlocation { pVehicles[ VehicleEnd::front ]->physics->SecuritySystem.MagnetLocation }; auto const magnetrange { 1.0 }; auto const ismagnetpassed { Point.fDist < -( magnetlocation + magnetrange ) }; - if( Point.fDist < -magnetlocation && (mvOccupied->Vel > EU07_AI_NOMOVEMENT || false == ismagnetpassed) ) { + if( Point.fDist < -magnetlocation && (occupied->Vel > EU07_AI_NOMOVEMENT || false == ismagnetpassed) ) { // NOTE: normally we'd activate the magnet once the leading vehicle passes it // but on a fresh scan after direction change it would be detected as long as it's under consist, and meet the (simple) activation condition // thus we're doing a more precise check in such situation (we presume direction change takes place only if the vehicle is standing still) - mvOccupied->SecuritySystem.set_cabsignal_lock(!AIControllFlag); // don't make life difficult for the ai, but a human driver is a fair game + occupied->SecuritySystem.set_cabsignal_lock(!AIControllFlag); // don't make life difficult for the ai, but a human driver is a fair game PutCommand(Point.evEvent->input_text(), Point.evEvent->input_value(1), Point.evEvent->input_value(2), nullptr); } if( ismagnetpassed ) { Point.Clear(); - mvOccupied->SecuritySystem.set_cabsignal_lock(false); + occupied->SecuritySystem.set_cabsignal_lock(false); } return true; } @@ -986,7 +986,7 @@ TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPo if( is_car() && Point.fVelNext != -1.0 && Point.fVelNext < 1.0 - && Point.fDist < -0.5 + std::min(fBrakeDist * 0.2, mvOccupied->Vel * 0.2) ) { + && Point.fDist < -0.5 + std::min(fBrakeDist * 0.2, occupied->Vel * 0.2) ) { Point.Clear(); return true; } @@ -1038,7 +1038,7 @@ TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPo } else if ( Point.flags & SpeedPointFlag::stopOnAutomaticBlock) { // jeśli S1 na SBL - if( mvOccupied->Vel < 2.0 && Point.fDist < fMaxProximityDist && Obstacle.distance > 1000 ) { + if( occupied->Vel < 2.0 && Point.fDist < fMaxProximityDist && Obstacle.distance > 1000 ) { // stanąć nie musi, ale zwolnić przynajmniej // jest w maksymalnym zasięgu to można go pominąć (wziąć drugą prędkosć) // as long as there isn't any obstacle in arbitrary view range diff --git a/vehicle/brakesetting.cpp b/vehicle/brakesetting.cpp index 3b06835f9..42be6738c 100644 --- a/vehicle/brakesetting.cpp +++ b/vehicle/brakesetting.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/brakesetting.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "physics/brakes.h" #include "vehicle/Driver.h" @@ -248,11 +248,11 @@ std::vector choose_legacy(std::vector const &Consist) { return settings; } -bool is_cut_out(TMoverParameters const &Vehicle) { +bool is_cut_out(physics::Vehicle const &Vehicle) { return (Vehicle.Hamulec->GetBrakeStatus() & b_dmg) == b_dmg; } -vehicle describe(TMoverParameters const &Vehicle, bool const Driven) { +vehicle describe(physics::Vehicle const &Vehicle, bool const Driven) { vehicle described; described.delays = Vehicle.BrakeDelays; // a locomotive has Power > 1, though it may be a dead one at the end of the train @@ -264,7 +264,7 @@ vehicle describe(TMoverParameters const &Vehicle, bool const Driven) { return described; } -bool apply(TMoverParameters &Vehicle, int const Setting, bool const Standstill) { +bool apply(physics::Vehicle &Vehicle, int const Setting, bool const Standstill) { auto &brake{*Vehicle.Hamulec}; if (Vehicle.BrakeCutOutByInspector && false == is_cut_out(Vehicle)) { // someone put the brake back in the meantime, it's theirs now diff --git a/vehicle/brakesetting.h b/vehicle/brakesetting.h index 9bb46d9da..d54075110 100644 --- a/vehicle/brakesetting.h +++ b/vehicle/brakesetting.h @@ -13,7 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/driverorders.h" -class TMoverParameters; +namespace physics { class Vehicle; } // the brake setting (G/P/R/Mg) the virtual wagon inspector (TController::AutoRewident) chooses for every // vehicle of a train, by the rules of the brake instruction Cw-1 (Mw56), §18 and §19 (eu07/maszyna#350) @@ -89,11 +89,11 @@ bool at_standstill(double Velocity); std::vector choose_legacy(std::vector const &Consist); // the brake of the vehicle is cut out (b_dmg), whoever did it -bool is_cut_out(TMoverParameters const &Vehicle); +bool is_cut_out(physics::Vehicle const &Vehicle); // what choose() needs to know of the vehicle. a brake the inspector cut out itself doesn't count as // cut out: the inspector decides about it anew -vehicle describe(TMoverParameters const &Vehicle, bool Driven); +vehicle describe(physics::Vehicle const &Vehicle, bool Driven); // the inspector puts the vehicle on Setting, as choose() gives it. cut_out cuts the brake out the way // the scenery's '0' does: b_dmg, which cuts the distributor off the brake pipe (as the cab's cut-out, @@ -105,6 +105,6 @@ vehicle describe(TMoverParameters const &Vehicle, bool Driven); // setting as it is). A brake cut out by anyone else stays cut out. // Returns true when a cut-out was left for later because the train was moving: the inspector has to look // at the train again once it stands (TController::reinspect_brakes() does) -bool apply(TMoverParameters &Vehicle, int Setting, bool Standstill); +bool apply(physics::Vehicle &Vehicle, int Setting, bool Standstill); } // namespace brake_setting diff --git a/vehicle/cab/auxiliarycommands.cpp b/vehicle/cab/auxiliarycommands.cpp index 92685e888..0c9804c6c 100644 --- a/vehicle/cab/auxiliarycommands.cpp +++ b/vehicle/cab/auxiliarycommands.cpp @@ -38,7 +38,7 @@ http://mozilla.org/MPL/2.0/. #include "Console.h" #include "application/application.h" #include "rendering/renderer.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include #include #include @@ -69,7 +69,7 @@ void TTrain::OnCommand_fuelpumptoggle(TTrain *Train, command_data const &Command return; } - if (false == Train->mvControlled->FuelPump.is_enabled) + if (false == Train->controlled->FuelPump.is_enabled) { // turn on OnCommand_fuelpumpenable(Train, Command); @@ -97,13 +97,13 @@ void TTrain::OnCommand_fuelpumpenable(TTrain *Train, command_data const &Command { // visual feedback Train->ggFuelPumpButton.UpdateValue(1.0, Train->dsbSwitch); - Train->mvControlled->FuelPumpSwitch(true); + Train->controlled->FuelPumpSwitch(true); } else if (Command.action == GLFW_RELEASE) { // visual feedback Train->ggFuelPumpButton.UpdateValue(0.0, Train->dsbSwitch); - Train->mvControlled->FuelPumpSwitch(false); + Train->controlled->FuelPumpSwitch(false); } } else @@ -113,8 +113,8 @@ void TTrain::OnCommand_fuelpumpenable(TTrain *Train, command_data const &Command { // visual feedback Train->ggFuelPumpButton.UpdateValue(1.0, Train->dsbSwitch); - Train->mvControlled->FuelPumpSwitch(true); - Train->mvControlled->FuelPumpSwitchOff(false); + Train->controlled->FuelPumpSwitch(true); + Train->controlled->FuelPumpSwitchOff(false); } } } @@ -140,8 +140,8 @@ void TTrain::OnCommand_fuelpumpdisable(TTrain *Train, command_data const &Comman { // visual feedback Train->ggFuelPumpButton.UpdateValue(0.0, Train->dsbSwitch); - Train->mvControlled->FuelPumpSwitch(false); - Train->mvControlled->FuelPumpSwitchOff(true); + Train->controlled->FuelPumpSwitch(false); + Train->controlled->FuelPumpSwitchOff(true); } } } @@ -168,7 +168,7 @@ void TTrain::OnCommand_oilpumptoggle(TTrain *Train, command_data const &Command) return; } - if (false == Train->mvControlled->OilPump.is_enabled) + if (false == Train->controlled->OilPump.is_enabled) { // turn on OnCommand_oilpumpenable(Train, Command); @@ -196,13 +196,13 @@ void TTrain::OnCommand_oilpumpenable(TTrain *Train, command_data const &Command) { // visual feedback Train->ggOilPumpButton.UpdateValue(1.0, Train->dsbSwitch); - Train->mvControlled->OilPumpSwitch(true); + Train->controlled->OilPumpSwitch(true); } else if (Command.action == GLFW_RELEASE) { // visual feedback Train->ggOilPumpButton.UpdateValue(0.0, Train->dsbSwitch); - Train->mvControlled->OilPumpSwitch(false); + Train->controlled->OilPumpSwitch(false); } } else @@ -212,8 +212,8 @@ void TTrain::OnCommand_oilpumpenable(TTrain *Train, command_data const &Command) { // visual feedback Train->ggOilPumpButton.UpdateValue(1.0, Train->dsbSwitch); - Train->mvControlled->OilPumpSwitch(true); - Train->mvControlled->OilPumpSwitchOff(false); + Train->controlled->OilPumpSwitch(true); + Train->controlled->OilPumpSwitchOff(false); } } } @@ -239,8 +239,8 @@ void TTrain::OnCommand_oilpumpdisable(TTrain *Train, command_data const &Command { // visual feedback Train->ggOilPumpButton.UpdateValue(0.0, Train->dsbSwitch); - Train->mvControlled->OilPumpSwitch(false); - Train->mvControlled->OilPumpSwitchOff(true); + Train->controlled->OilPumpSwitch(false); + Train->controlled->OilPumpSwitchOff(true); } } } @@ -252,7 +252,7 @@ void TTrain::OnCommand_oilfuelpumptoggle(TTrain *Train, command_data const &Comm return; } - auto *vehicle{Train->mvControlled}; + auto *vehicle{Train->controlled}; if (Train->ggOilFuelPumpButton.type() == TGaugeType::push) { // impulse switch, as the separate ones: held to start both pumps @@ -283,7 +283,7 @@ void TTrain::OnCommand_tractionmodetoggle(TTrain *Train, command_data const &Com { return; } - if (Train->mvControlled->GensetSelected()) + if (Train->controlled->GensetSelected()) { OnCommand_tractionmodecatenary(Train, Command); } @@ -300,8 +300,8 @@ void TTrain::OnCommand_tractionmodecatenary(TTrain *Train, command_data const &C return; } // refused with the line breaker closed: then the switch doesn't move - Train->mvControlled->TractionModeSwitch(TMoverParameters::traction_mode::catenary, range_t::consist); - if (false == Train->mvControlled->GensetSelected()) + Train->controlled->TractionModeSwitch(physics::Vehicle::traction_mode::catenary, range_t::consist); + if (false == Train->controlled->GensetSelected()) { Train->ggTractionModeSwitch.UpdateValue(0.0, Train->dsbSwitch); } @@ -314,8 +314,8 @@ void TTrain::OnCommand_tractionmodegenset(TTrain *Train, command_data const &Com return; } // refused with the line breaker closed, or without a genset: then the switch doesn't move - Train->mvControlled->TractionModeSwitch(TMoverParameters::traction_mode::genset, range_t::consist); - if (Train->mvControlled->GensetSelected()) + Train->controlled->TractionModeSwitch(physics::Vehicle::traction_mode::genset, range_t::consist); + if (Train->controlled->GensetSelected()) { Train->ggTractionModeSwitch.UpdateValue(1.0, Train->dsbSwitch); } @@ -328,7 +328,7 @@ void TTrain::OnCommand_gensettoggle(TTrain *Train, command_data const &Command) { return; } - if (false == Train->mvControlled->Genset.is_enabled) + if (false == Train->controlled->Genset.is_enabled) { OnCommand_gensetenable(Train, Command); } @@ -345,8 +345,8 @@ void TTrain::OnCommand_gensetenable(TTrain *Train, command_data const &Command) return; } // ignored by a genset which starts on its own: then the switch doesn't move - Train->mvControlled->GensetSwitch(true, range_t::consist); - if (Train->mvControlled->Genset.is_enabled) + Train->controlled->GensetSwitch(true, range_t::consist); + if (Train->controlled->Genset.is_enabled) { Train->ggGensetButton.UpdateValue(1.0, Train->dsbSwitch); } @@ -358,8 +358,8 @@ void TTrain::OnCommand_gensetdisable(TTrain *Train, command_data const &Command) { return; } - Train->mvControlled->GensetSwitch(false, range_t::consist); - if (false == Train->mvControlled->Genset.is_enabled) + Train->controlled->GensetSwitch(false, range_t::consist); + if (false == Train->controlled->Genset.is_enabled) { Train->ggGensetButton.UpdateValue(0.0, Train->dsbSwitch); } @@ -371,7 +371,7 @@ void TTrain::OnCommand_waterheaterbreakertoggle(TTrain *Train, command_data cons if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvControlled->WaterHeater.breaker) + if (false == Train->controlled->WaterHeater.breaker) { // turn on OnCommand_waterheaterbreakerclose(Train, Command); @@ -392,12 +392,12 @@ void TTrain::OnCommand_waterheaterbreakerclose(TTrain *Train, command_data const // visual feedback Train->ggWaterHeaterBreakerButton.UpdateValue(1.0, Train->dsbSwitch); - if (true == Train->mvControlled->WaterHeater.breaker) + if (true == Train->controlled->WaterHeater.breaker) { return; } // already enabled - Train->mvControlled->WaterHeaterBreakerSwitch(true); + Train->controlled->WaterHeaterBreakerSwitch(true); } } @@ -409,12 +409,12 @@ void TTrain::OnCommand_waterheaterbreakeropen(TTrain *Train, command_data const // visual feedback Train->ggWaterHeaterBreakerButton.UpdateValue(0.0, Train->dsbSwitch); - if (false == Train->mvControlled->WaterHeater.breaker) + if (false == Train->controlled->WaterHeater.breaker) { return; } // already enabled - Train->mvControlled->WaterHeaterBreakerSwitch(false); + Train->controlled->WaterHeaterBreakerSwitch(false); } } @@ -424,7 +424,7 @@ void TTrain::OnCommand_waterheatertoggle(TTrain *Train, command_data const &Comm if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvControlled->WaterHeater.is_enabled) + if (false == Train->controlled->WaterHeater.is_enabled) { // turn on OnCommand_waterheaterenable(Train, Command); @@ -445,12 +445,12 @@ void TTrain::OnCommand_waterheaterenable(TTrain *Train, command_data const &Comm // visual feedback Train->ggWaterHeaterButton.UpdateValue(1.0, Train->dsbSwitch); - if (true == Train->mvControlled->WaterHeater.is_enabled) + if (true == Train->controlled->WaterHeater.is_enabled) { return; } // already enabled - Train->mvControlled->WaterHeaterSwitch(true); + Train->controlled->WaterHeaterSwitch(true); } } @@ -462,12 +462,12 @@ void TTrain::OnCommand_waterheaterdisable(TTrain *Train, command_data const &Com // visual feedback Train->ggWaterHeaterButton.UpdateValue(0.0, Train->dsbSwitch); - if (false == Train->mvControlled->WaterHeater.is_enabled) + if (false == Train->controlled->WaterHeater.is_enabled) { return; } // already disabled - Train->mvControlled->WaterHeaterSwitch(false); + Train->controlled->WaterHeaterSwitch(false); } } @@ -477,7 +477,7 @@ void TTrain::OnCommand_waterpumpbreakertoggle(TTrain *Train, command_data const if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvControlled->WaterPump.breaker) + if (false == Train->controlled->WaterPump.breaker) { // turn on OnCommand_waterpumpbreakerclose(Train, Command); @@ -498,12 +498,12 @@ void TTrain::OnCommand_waterpumpbreakerclose(TTrain *Train, command_data const & // visual feedback Train->ggWaterPumpBreakerButton.UpdateValue(1.0, Train->dsbSwitch); - if (true == Train->mvControlled->WaterPump.breaker) + if (true == Train->controlled->WaterPump.breaker) { return; } // already enabled - Train->mvControlled->WaterPumpBreakerSwitch(true); + Train->controlled->WaterPumpBreakerSwitch(true); } } @@ -515,12 +515,12 @@ void TTrain::OnCommand_waterpumpbreakeropen(TTrain *Train, command_data const &C // visual feedback Train->ggWaterPumpBreakerButton.UpdateValue(0.0, Train->dsbSwitch); - if (false == Train->mvControlled->WaterPump.breaker) + if (false == Train->controlled->WaterPump.breaker) { return; } // already enabled - Train->mvControlled->WaterPumpBreakerSwitch(false); + Train->controlled->WaterPumpBreakerSwitch(false); } } @@ -546,7 +546,7 @@ void TTrain::OnCommand_waterpumptoggle(TTrain *Train, command_data const &Comman return; } - if (false == Train->mvControlled->WaterPump.is_enabled) + if (false == Train->controlled->WaterPump.is_enabled) { // turn on OnCommand_waterpumpenable(Train, Command); @@ -574,13 +574,13 @@ void TTrain::OnCommand_waterpumpenable(TTrain *Train, command_data const &Comman { // visual feedback Train->ggWaterPumpButton.UpdateValue(1.0, Train->dsbSwitch); - Train->mvControlled->WaterPumpSwitch(true); + Train->controlled->WaterPumpSwitch(true); } else if (Command.action == GLFW_RELEASE) { // visual feedback Train->ggWaterPumpButton.UpdateValue(0.0, Train->dsbSwitch); - Train->mvControlled->WaterPumpSwitch(false); + Train->controlled->WaterPumpSwitch(false); } } else @@ -590,8 +590,8 @@ void TTrain::OnCommand_waterpumpenable(TTrain *Train, command_data const &Comman { // visual feedback Train->ggWaterPumpButton.UpdateValue(1.0, Train->dsbSwitch); - Train->mvControlled->WaterPumpSwitch(true); - Train->mvControlled->WaterPumpSwitchOff(false); + Train->controlled->WaterPumpSwitch(true); + Train->controlled->WaterPumpSwitchOff(false); } } } @@ -617,8 +617,8 @@ void TTrain::OnCommand_waterpumpdisable(TTrain *Train, command_data const &Comma { // visual feedback Train->ggWaterPumpButton.UpdateValue(0.0, Train->dsbSwitch); - Train->mvControlled->WaterPumpSwitch(false); - Train->mvControlled->WaterPumpSwitchOff(true); + Train->controlled->WaterPumpSwitch(false); + Train->controlled->WaterPumpSwitchOff(true); } } } @@ -629,7 +629,7 @@ void TTrain::OnCommand_watercircuitslinktoggle(TTrain *Train, command_data const if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvControlled->WaterCircuitsLink) + if (false == Train->controlled->WaterCircuitsLink) { // turn on OnCommand_watercircuitslinkenable(Train, Command); @@ -650,12 +650,12 @@ void TTrain::OnCommand_watercircuitslinkenable(TTrain *Train, command_data const // visual feedback Train->ggWaterCircuitsLinkButton.UpdateValue(1.0, Train->dsbSwitch); - if (true == Train->mvControlled->WaterCircuitsLink) + if (true == Train->controlled->WaterCircuitsLink) { return; } // already enabled - Train->mvControlled->WaterCircuitsLinkSwitch(true); + Train->controlled->WaterCircuitsLinkSwitch(true); } } @@ -667,12 +667,12 @@ void TTrain::OnCommand_watercircuitslinkdisable(TTrain *Train, command_data cons // visual feedback Train->ggWaterCircuitsLinkButton.UpdateValue(0.0, Train->dsbSwitch); - if (false == Train->mvControlled->WaterCircuitsLink) + if (false == Train->controlled->WaterCircuitsLink) { return; } // already disabled - Train->mvControlled->WaterCircuitsLinkSwitch(false); + Train->controlled->WaterCircuitsLinkSwitch(false); } } @@ -682,9 +682,9 @@ void TTrain::OnCommand_convertertoggle(TTrain *Train, command_data const &Comman if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const overloadrelayisopen{(Train->Dynamic()->Mechanik != nullptr ? Train->Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : Train->mvOccupied->ConvOvldFlag)}; + auto const overloadrelayisopen{(Train->Dynamic()->Mechanik != nullptr ? Train->Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : Train->occupied->ConvOvldFlag)}; - if (Train->mvOccupied->ConvSwitchType != "impulse" ? Train->ggConverterButton.GetValue() < 0.5 : false == Train->mvOccupied->Power110vIsAvailable && false == overloadrelayisopen) + if (Train->occupied->ConvSwitchType != "impulse" ? Train->ggConverterButton.GetValue() < 0.5 : false == Train->occupied->Power110vIsAvailable && false == overloadrelayisopen) { // turn on OnCommand_converterenable(Train, Command); @@ -698,7 +698,7 @@ void TTrain::OnCommand_convertertoggle(TTrain *Train, command_data const &Comman else if (Command.action == GLFW_RELEASE) { // on button release... - if (Train->mvOccupied->ConvSwitchType == "impulse") + if (Train->occupied->ConvSwitchType == "impulse") { // ...return switches to start position if applicable Train->ggConverterButton.UpdateValue(0.0, Train->dsbSwitch); @@ -717,10 +717,10 @@ void TTrain::OnCommand_converterenable(TTrain *Train, command_data const &Comman // impulse type switch has no effect if there's no power // NOTE: this is most likely setup wrong, but the whole thing is smoke and mirrors anyway - if (Train->mvOccupied->ConvSwitchType != "impulse" || Train->mvControlled->Mains) + if (Train->occupied->ConvSwitchType != "impulse" || Train->controlled->Mains) { // won't start if the line breaker button is still held - Train->mvOccupied->ConverterSwitch(true); + Train->occupied->ConverterSwitch(true); } } else if (Command.action == GLFW_RELEASE) @@ -742,7 +742,7 @@ void TTrain::OnCommand_converterdisable(TTrain *Train, command_data const &Comma Train->ggConverterOffButton.UpdateValue(1.0, Train->dsbSwitch); } - Train->mvOccupied->ConverterSwitch(false); + Train->occupied->ConverterSwitch(false); } else if (Command.action == GLFW_RELEASE) { @@ -754,7 +754,7 @@ void TTrain::OnCommand_converterdisable(TTrain *Train, command_data const &Comma void TTrain::OnCommand_convertertogglelocal(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->ConverterStart == start_t::automatic) + if (Train->occupied->ConverterStart == start_t::automatic) { // let the automatic thing do its automatic thing... return; @@ -767,20 +767,20 @@ void TTrain::OnCommand_convertertogglelocal(TTrain *Train, command_data const &C if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvOccupied->ConverterAllowLocal && Train->ggConverterLocalButton.GetValue() < 0.5) + if (false == Train->occupied->ConverterAllowLocal && Train->ggConverterLocalButton.GetValue() < 0.5) { // turn on // visual feedback Train->ggConverterLocalButton.UpdateValue(1.0, Train->dsbSwitch); // effect - Train->mvOccupied->ConverterAllowLocal = true; + Train->occupied->ConverterAllowLocal = true; /* - if( true == Train->mvControlled->ConverterSwitch( true, range::local ) ) { + if( true == Train->controlled->ConverterSwitch( true, range::local ) ) { // side effects // control the compressor, if it's paired with the converter - if( Train->mvControlled->CompressorPower == 2 ) { + if( Train->controlled->CompressorPower == 2 ) { // hunter-091012: tak jest poprawnie - Train->mvControlled->CompressorSwitch( true, range::local ); + Train->controlled->CompressorSwitch( true, range::local ); } } */ @@ -791,19 +791,19 @@ void TTrain::OnCommand_convertertogglelocal(TTrain *Train, command_data const &C // visual feedback Train->ggConverterLocalButton.UpdateValue(0.0, Train->dsbSwitch); // effect - Train->mvOccupied->ConverterAllowLocal = false; + Train->occupied->ConverterAllowLocal = false; /* - if( true == Train->mvControlled->ConverterSwitch( false, range::local ) ) { + if( true == Train->controlled->ConverterSwitch( false, range::local ) ) { // side effects // control the compressor, if it's paired with the converter - if( Train->mvControlled->CompressorPower == 2 ) { + if( Train->controlled->CompressorPower == 2 ) { // hunter-091012: tak jest poprawnie - Train->mvControlled->CompressorSwitch( false, range::local ); + Train->controlled->CompressorSwitch( false, range::local ); } // if there's no (low voltage) power source left, drop pantographs - if( false == Train->mvControlled->Battery ) { - Train->mvControlled->PantFront( false, range::local ); - Train->mvControlled->PantRear( false, range::local ); + if( false == Train->controlled->Battery ) { + Train->controlled->PantFront( false, range::local ); + Train->controlled->PantRear( false, range::local ); } } */ @@ -828,7 +828,7 @@ void TTrain::OnCommand_converteroverloadrelayreset(TTrain *Train, command_data c // visual feedback Train->ggConverterFuseButton.UpdateValue(1.0, Train->dsbSwitch); - Train->mvControlled->RelayReset(relay_t::primaryconverteroverload); + Train->controlled->RelayReset(relay_t::primaryconverteroverload); } else if (Command.action == GLFW_RELEASE) { @@ -843,7 +843,7 @@ void TTrain::OnCommand_compressortoggle(TTrain *Train, command_data const &Comma if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const compressorisenabled{(Train->Dynamic()->Mechanik ? Train->Dynamic()->Mechanik->IsAnyCompressorEnabled : Train->mvOccupied->CompressorAllow)}; + auto const compressorisenabled{(Train->Dynamic()->Mechanik ? Train->Dynamic()->Mechanik->IsAnyCompressorEnabled : Train->occupied->CompressorAllow)}; if (false == compressorisenabled) { @@ -860,7 +860,7 @@ void TTrain::OnCommand_compressortoggle(TTrain *Train, command_data const &Comma // disabled because we don't have yet support for compressor switch type definition else if( Command.action == GLFW_RELEASE ) { // on button release... - if( Train->mvOccupied->CompSwitchType == "impulse" ) { + if( Train->occupied->CompSwitchType == "impulse" ) { // ...return switches to start position if applicable Train->ggCompressorButton.UpdateValue( 0.0, Train->dsbSwitch ); Train->ggCompressorOffButton.UpdateValue( 0.0, Train->dsbSwitch ); @@ -879,10 +879,10 @@ void TTrain::OnCommand_compressorenable(TTrain *Train, command_data const &Comma // impulse type switch has no effect if there's no power // NOTE: this is most likely setup wrong, but the whole thing is smoke and mirrors anyway - // if( ( Train->mvOccupied->CompSwitchType != "impulse" ) - // || ( Train->mvControlled->Mains ) ) { + // if( ( Train->occupied->CompSwitchType != "impulse" ) + // || ( Train->controlled->Mains ) ) { - Train->mvOccupied->CompressorSwitch(true); + Train->occupied->CompressorSwitch(true); // } } else if (Command.action == GLFW_RELEASE) @@ -895,7 +895,7 @@ void TTrain::OnCommand_compressorenable(TTrain *Train, command_data const &Comma void TTrain::OnCommand_compressordisable(TTrain *Train, command_data const &Command) { - if (Train->mvControlled->CompressorPower >= 2) + if (Train->controlled->CompressorPower >= 2) { return; } @@ -909,7 +909,7 @@ void TTrain::OnCommand_compressordisable(TTrain *Train, command_data const &Comm Train->ggCompressorOffButton.UpdateValue( 1.0, Train->dsbSwitch ); } */ - Train->mvOccupied->CompressorSwitch(false); + Train->occupied->CompressorSwitch(false); } else if (Command.action == GLFW_RELEASE) { @@ -921,7 +921,7 @@ void TTrain::OnCommand_compressordisable(TTrain *Train, command_data const &Comm void TTrain::OnCommand_compressortogglelocal(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->CompressorPower >= 2) + if (Train->occupied->CompressorPower >= 2) { return; } @@ -933,13 +933,13 @@ void TTrain::OnCommand_compressortogglelocal(TTrain *Train, command_data const & if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvOccupied->CompressorAllowLocal) + if (false == Train->occupied->CompressorAllowLocal) { // turn on // visual feedback Train->ggCompressorLocalButton.UpdateValue(1.0, Train->dsbSwitch); // effect - Train->mvOccupied->CompressorAllowLocal = true; + Train->occupied->CompressorAllowLocal = true; } else { @@ -947,7 +947,7 @@ void TTrain::OnCommand_compressortogglelocal(TTrain *Train, command_data const & // visual feedback Train->ggCompressorLocalButton.UpdateValue(0.0, Train->dsbSwitch); // effect - Train->mvOccupied->CompressorAllowLocal = false; + Train->occupied->CompressorAllowLocal = false; } } } @@ -955,7 +955,7 @@ void TTrain::OnCommand_compressortogglelocal(TTrain *Train, command_data const & void TTrain::OnCommand_compressorpresetactivatenext(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->CompressorListPosNo == 0) + if (Train->occupied->CompressorListPosNo == 0) { return; } @@ -967,14 +967,14 @@ void TTrain::OnCommand_compressorpresetactivatenext(TTrain *Train, command_data if (Train->ggCompressorListButton.type() == TGaugeType::push) { // impulse switch - if (Train->mvOccupied->CompressorListPosNo < Train->mvOccupied->CompressorListDefPos + 1) + if (Train->occupied->CompressorListPosNo < Train->occupied->CompressorListDefPos + 1) { return; } - Train->mvOccupied->ChangeCompressorPreset(Command.action == GLFW_PRESS ? Train->mvOccupied->CompressorListDefPos + 1 : Train->mvOccupied->CompressorListDefPos); + Train->occupied->ChangeCompressorPreset(Command.action == GLFW_PRESS ? Train->occupied->CompressorListDefPos + 1 : Train->occupied->CompressorListDefPos); // visual feedback - Train->ggCompressorListButton.UpdateValue(static_cast(Train->mvOccupied->CompressorListPos - 1), Train->dsbSwitch); + Train->ggCompressorListButton.UpdateValue(static_cast(Train->occupied->CompressorListPos - 1), Train->dsbSwitch); } else { @@ -984,12 +984,12 @@ void TTrain::OnCommand_compressorpresetactivatenext(TTrain *Train, command_data return; } - if (Train->mvOccupied->CompressorListPos < Train->mvOccupied->CompressorListPosNo || true == Train->mvOccupied->CompressorListWrap) + if (Train->occupied->CompressorListPos < Train->occupied->CompressorListPosNo || true == Train->occupied->CompressorListWrap) { // active light preset is stored as value in range 1-LigthPosNo - Train->mvOccupied->ChangeCompressorPreset(Train->mvOccupied->CompressorListPos < Train->mvOccupied->CompressorListPosNo ? Train->mvOccupied->CompressorListPos + 1 : 1); // wrap mode + Train->occupied->ChangeCompressorPreset(Train->occupied->CompressorListPos < Train->occupied->CompressorListPosNo ? Train->occupied->CompressorListPos + 1 : 1); // wrap mode // visual feedback - Train->ggCompressorListButton.UpdateValue(static_cast(Train->mvOccupied->CompressorListPos - 1), Train->dsbSwitch); + Train->ggCompressorListButton.UpdateValue(static_cast(Train->occupied->CompressorListPos - 1), Train->dsbSwitch); } } } @@ -997,7 +997,7 @@ void TTrain::OnCommand_compressorpresetactivatenext(TTrain *Train, command_data void TTrain::OnCommand_compressorpresetactivateprevious(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->CompressorListPosNo == 0) + if (Train->occupied->CompressorListPosNo == 0) { return; } @@ -1012,15 +1012,15 @@ void TTrain::OnCommand_compressorpresetactivateprevious(TTrain *Train, command_d return; } - if (Train->mvOccupied->CompressorListPos > 1 || true == Train->mvOccupied->CompressorListWrap) + if (Train->occupied->CompressorListPos > 1 || true == Train->occupied->CompressorListWrap) { // active light preset is stored as value in range 1-LigthPosNo - Train->mvOccupied->ChangeCompressorPreset(Train->mvOccupied->CompressorListPos > 1 ? Train->mvOccupied->CompressorListPos - 1 : Train->mvOccupied->CompressorListPosNo); // wrap mode + Train->occupied->ChangeCompressorPreset(Train->occupied->CompressorListPos > 1 ? Train->occupied->CompressorListPos - 1 : Train->occupied->CompressorListPosNo); // wrap mode // visual feedback if (Train->ggCompressorListButton.SubModel != nullptr) { - Train->ggCompressorListButton.UpdateValue(static_cast(Train->mvOccupied->CompressorListPos - 1), Train->dsbSwitch); + Train->ggCompressorListButton.UpdateValue(static_cast(Train->occupied->CompressorListPos - 1), Train->dsbSwitch); } } } @@ -1028,7 +1028,7 @@ void TTrain::OnCommand_compressorpresetactivateprevious(TTrain *Train, command_d void TTrain::OnCommand_compressorpresetactivatedefault(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->CompressorListPosNo == 0) + if (Train->occupied->CompressorListPosNo == 0) { return; } @@ -1037,12 +1037,12 @@ void TTrain::OnCommand_compressorpresetactivatedefault(TTrain *Train, command_da return; } // one change per key press - Train->mvOccupied->ChangeCompressorPreset(Train->mvOccupied->CompressorListDefPos); + Train->occupied->ChangeCompressorPreset(Train->occupied->CompressorListDefPos); // visual feedback if (Train->ggCompressorListButton.SubModel != nullptr) { - Train->ggCompressorListButton.UpdateValue(static_cast(Train->mvOccupied->CompressorListPos - 1), Train->dsbSwitch); + Train->ggCompressorListButton.UpdateValue(static_cast(Train->occupied->CompressorListPos - 1), Train->dsbSwitch); } } @@ -1068,7 +1068,7 @@ void TTrain::OnCommand_motorblowerstogglefront(TTrain *Train, command_data const return; } - if (false == Train->mvControlled->MotorBlowers[VehicleEnd::front].is_enabled) + if (false == Train->controlled->MotorBlowers[VehicleEnd::front].is_enabled) { // turn on OnCommand_motorblowersenablefront(Train, Command); @@ -1096,13 +1096,13 @@ void TTrain::OnCommand_motorblowersenablefront(TTrain *Train, command_data const { // visual feedback Train->ggMotorBlowersFrontButton.UpdateValue(1.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(true, VehicleEnd::front); + Train->controlled->MotorBlowersSwitch(true, VehicleEnd::front); } else if (Command.action == GLFW_RELEASE) { // visual feedback Train->ggMotorBlowersFrontButton.UpdateValue(0.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(false, VehicleEnd::front); + Train->controlled->MotorBlowersSwitch(false, VehicleEnd::front); } } else @@ -1112,8 +1112,8 @@ void TTrain::OnCommand_motorblowersenablefront(TTrain *Train, command_data const { // visual feedback Train->ggMotorBlowersFrontButton.UpdateValue(1.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(true, VehicleEnd::front); - Train->mvControlled->MotorBlowersSwitchOff(false, VehicleEnd::front); + Train->controlled->MotorBlowersSwitch(true, VehicleEnd::front); + Train->controlled->MotorBlowersSwitchOff(false, VehicleEnd::front); } } } @@ -1139,8 +1139,8 @@ void TTrain::OnCommand_motorblowersdisablefront(TTrain *Train, command_data cons { // visual feedback Train->ggMotorBlowersFrontButton.UpdateValue(0.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(false, VehicleEnd::front); - Train->mvControlled->MotorBlowersSwitchOff(true, VehicleEnd::front); + Train->controlled->MotorBlowersSwitch(false, VehicleEnd::front); + Train->controlled->MotorBlowersSwitchOff(true, VehicleEnd::front); } } } @@ -1167,7 +1167,7 @@ void TTrain::OnCommand_motorblowerstogglerear(TTrain *Train, command_data const return; } - if (false == Train->mvControlled->MotorBlowers[VehicleEnd::rear].is_enabled) + if (false == Train->controlled->MotorBlowers[VehicleEnd::rear].is_enabled) { // turn on OnCommand_motorblowersenablerear(Train, Command); @@ -1195,13 +1195,13 @@ void TTrain::OnCommand_motorblowersenablerear(TTrain *Train, command_data const { // visual feedback Train->ggMotorBlowersRearButton.UpdateValue(1.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(true, VehicleEnd::rear); + Train->controlled->MotorBlowersSwitch(true, VehicleEnd::rear); } else if (Command.action == GLFW_RELEASE) { // visual feedback Train->ggMotorBlowersRearButton.UpdateValue(0.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(false, VehicleEnd::rear); + Train->controlled->MotorBlowersSwitch(false, VehicleEnd::rear); } } else @@ -1211,8 +1211,8 @@ void TTrain::OnCommand_motorblowersenablerear(TTrain *Train, command_data const { // visual feedback Train->ggMotorBlowersRearButton.UpdateValue(1.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(true, VehicleEnd::rear); - Train->mvControlled->MotorBlowersSwitchOff(false, VehicleEnd::rear); + Train->controlled->MotorBlowersSwitch(true, VehicleEnd::rear); + Train->controlled->MotorBlowersSwitchOff(false, VehicleEnd::rear); } } } @@ -1238,8 +1238,8 @@ void TTrain::OnCommand_motorblowersdisablerear(TTrain *Train, command_data const { // visual feedback Train->ggMotorBlowersRearButton.UpdateValue(0.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(false, VehicleEnd::rear); - Train->mvControlled->MotorBlowersSwitchOff(true, VehicleEnd::rear); + Train->controlled->MotorBlowersSwitch(false, VehicleEnd::rear); + Train->controlled->MotorBlowersSwitchOff(true, VehicleEnd::rear); } } } @@ -1259,15 +1259,15 @@ void TTrain::OnCommand_motorblowersdisableall(TTrain *Train, command_data const { // visual feedback Train->ggMotorBlowersAllOffButton.UpdateValue(1.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitchOff(true, VehicleEnd::front); - Train->mvControlled->MotorBlowersSwitchOff(true, VehicleEnd::rear); + Train->controlled->MotorBlowersSwitchOff(true, VehicleEnd::front); + Train->controlled->MotorBlowersSwitchOff(true, VehicleEnd::rear); } else if (Command.action == GLFW_RELEASE) { // visual feedback Train->ggMotorBlowersAllOffButton.UpdateValue(0.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitchOff(false, VehicleEnd::front); - Train->mvControlled->MotorBlowersSwitchOff(false, VehicleEnd::rear); + Train->controlled->MotorBlowersSwitchOff(false, VehicleEnd::front); + Train->controlled->MotorBlowersSwitchOff(false, VehicleEnd::rear); } } else @@ -1279,16 +1279,16 @@ void TTrain::OnCommand_motorblowersdisableall(TTrain *Train, command_data const if (Train->ggMotorBlowersAllOffButton.GetDesiredValue() < 0.5f) { // switch is off, activate - Train->mvControlled->MotorBlowersSwitchOff(true, VehicleEnd::front); - Train->mvControlled->MotorBlowersSwitchOff(true, VehicleEnd::rear); + Train->controlled->MotorBlowersSwitchOff(true, VehicleEnd::front); + Train->controlled->MotorBlowersSwitchOff(true, VehicleEnd::rear); // visual feedback Train->ggMotorBlowersRearButton.UpdateValue(1.f, Train->dsbSwitch); } else { // deactivate - Train->mvControlled->MotorBlowersSwitchOff(false, VehicleEnd::front); - Train->mvControlled->MotorBlowersSwitchOff(false, VehicleEnd::rear); + Train->controlled->MotorBlowersSwitchOff(false, VehicleEnd::front); + Train->controlled->MotorBlowersSwitchOff(false, VehicleEnd::rear); // visual feedback Train->ggMotorBlowersRearButton.UpdateValue(0.f, Train->dsbSwitch); } @@ -1304,5 +1304,5 @@ void TTrain::OnCommand_coolingfanstoggle(TTrain *Train, command_data const &Comm return; } - Train->mvControlled->RVentForceOn = !Train->mvControlled->RVentForceOn; + Train->controlled->RVentForceOn = !Train->controlled->RVentForceOn; } diff --git a/vehicle/cab/brakecommands.cpp b/vehicle/cab/brakecommands.cpp index 6ebf453a2..f0f9cef39 100644 --- a/vehicle/cab/brakecommands.cpp +++ b/vehicle/cab/brakecommands.cpp @@ -38,7 +38,7 @@ http://mozilla.org/MPL/2.0/. #include "Console.h" #include "application/application.h" #include "rendering/renderer.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include #include #include @@ -55,17 +55,17 @@ void TTrain::OnCommand_independentbrakeincrease(TTrain *Train, command_data cons // when SplitEDPneumaticBrake is active the local brake key always operates // the pneumatic local brake directly, never piggy-backing on the joint controller - auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; + auto const splitMode{Train->controlled->SplitEDPneumaticBrake}; auto const useStepped{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; - if (Train->mvOccupied->LocalBrake != TLocalBrake::ManualBrake) + if (Train->occupied->LocalBrake != TLocalBrake::ManualBrake) { - if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->mvOccupied->MainCtrlPos > 0) + if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->occupied->MainCtrlPos > 0) { OnCommand_mastercontrollerdecrease(Train, Command); } else { - Train->mvOccupied->IncLocalBrakeLevel(useStepped ? 1 : static_cast(Global.brake_speed * Command.time_delta * LocalBrakePosNo)); + Train->occupied->IncLocalBrakeLevel(useStepped ? 1 : static_cast(Global.brake_speed * Command.time_delta * LocalBrakePosNo)); if (useStepped) { Train->m_mastercontrollerinuse = true; @@ -81,17 +81,17 @@ void TTrain::OnCommand_independentbrakeincreasefast(TTrain *Train, command_data if (Command.action != GLFW_RELEASE) { - auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; + auto const splitMode{Train->controlled->SplitEDPneumaticBrake}; auto const useJointAnim{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; - if (Train->mvOccupied->LocalBrake != TLocalBrake::ManualBrake) + if (Train->occupied->LocalBrake != TLocalBrake::ManualBrake) { - if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->mvOccupied->MainCtrlPos > 0) + if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->occupied->MainCtrlPos > 0) { OnCommand_mastercontrollerdecreasefast(Train, Command); } else { - Train->mvOccupied->IncLocalBrakeLevel(LocalBrakePosNo); + Train->occupied->IncLocalBrakeLevel(LocalBrakePosNo); if (useJointAnim) { Train->m_mastercontrollerinuse = true; @@ -107,20 +107,20 @@ void TTrain::OnCommand_independentbrakedecrease(TTrain *Train, command_data cons if (Command.action != GLFW_RELEASE) { - auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; + auto const splitMode{Train->controlled->SplitEDPneumaticBrake}; auto const useStepped{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; - if (Train->mvOccupied->LocalBrake != TLocalBrake::ManualBrake + if (Train->occupied->LocalBrake != TLocalBrake::ManualBrake // Ra 1014-06: AI potrafi zahamować pomocniczym mimo jego braku - odhamować jakoś trzeba // TODO: sort AI out so it doesn't do things it doesn't have equipment for - || Train->mvOccupied->LocalBrakePosA > 0) + || Train->occupied->LocalBrakePosA > 0) { - if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->mvOccupied->LocalBrakePosA == 0.0) + if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->occupied->LocalBrakePosA == 0.0) { OnCommand_mastercontrollerincrease(Train, Command); } else { - Train->mvOccupied->DecLocalBrakeLevel(useStepped ? 1 : static_cast(Global.brake_speed * Command.time_delta * LocalBrakePosNo)); + Train->occupied->DecLocalBrakeLevel(useStepped ? 1 : static_cast(Global.brake_speed * Command.time_delta * LocalBrakePosNo)); if (useStepped) { Train->m_mastercontrollerinuse = true; @@ -136,20 +136,20 @@ void TTrain::OnCommand_independentbrakedecreasefast(TTrain *Train, command_data if (Command.action != GLFW_RELEASE) { - auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; + auto const splitMode{Train->controlled->SplitEDPneumaticBrake}; auto const useJointAnim{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; - if (Train->mvOccupied->LocalBrake != TLocalBrake::ManualBrake + if (Train->occupied->LocalBrake != TLocalBrake::ManualBrake // Ra 1014-06: AI potrafi zahamować pomocniczym mimo jego braku - odhamować jakoś trzeba // TODO: sort AI out so it doesn't do things it doesn't have equipment for - || Train->mvOccupied->LocalBrakePosA > 0) + || Train->occupied->LocalBrakePosA > 0) { - if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->mvOccupied->LocalBrakePosA == 0.0) + if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->occupied->LocalBrakePosA == 0.0) { OnCommand_mastercontrollerincreasefast(Train, Command); } else { - Train->mvOccupied->DecLocalBrakeLevel(LocalBrakePosNo); + Train->occupied->DecLocalBrakeLevel(LocalBrakePosNo); if (useJointAnim) { Train->m_mastercontrollerinuse = true; @@ -165,10 +165,10 @@ void TTrain::OnCommand_independentbrakeset(TTrain *Train, command_data const &Co if (Command.action != GLFW_RELEASE) { - Train->mvOccupied->LocalBrakePosA = std::clamp(Command.param1, 0.0, 1.0); + Train->occupied->LocalBrakePosA = std::clamp(Command.param1, 0.0, 1.0); } /* - Train->mvControlled->LocalBrakePos = ( + Train->controlled->LocalBrakePos = ( std::round( interpolate( 0.0, @@ -186,10 +186,10 @@ void TTrain::OnCommand_independentbrakebailoff(TTrain *Train, command_data const { // TODO: check if this set of conditions can be simplified. // it'd be more flexible to have an attribute indicating whether bail off position is supported - if (Train->mvControlled->TrainType != train_type::emu && - (Train->mvControlled->EngineType == TEngineType::ElectricSeriesMotor || Train->mvControlled->EngineType == TEngineType::DieselElectric || - Train->mvControlled->EngineType == TEngineType::ElectricInductionMotor) && - Train->mvOccupied->BrakeCtrlPosNo > 0) + if (Train->controlled->TrainType != train_type::emu && + (Train->controlled->EngineType == TEngineType::ElectricSeriesMotor || Train->controlled->EngineType == TEngineType::DieselElectric || + Train->controlled->EngineType == TEngineType::ElectricInductionMotor) && + Train->occupied->BrakeCtrlPosNo > 0) { if (Command.action == GLFW_PRESS) @@ -198,7 +198,7 @@ void TTrain::OnCommand_independentbrakebailoff(TTrain *Train, command_data const // visual feedback Train->ggReleaserButton.UpdateValue(1.0, Train->dsbSwitch); - Train->mvOccupied->BrakeReleaser(1); + Train->occupied->BrakeReleaser(1); } else if (Command.action == GLFW_RELEASE) { @@ -206,7 +206,7 @@ void TTrain::OnCommand_independentbrakebailoff(TTrain *Train, command_data const // visual feedback Train->ggReleaserButton.UpdateValue(0.0, Train->dsbSwitch); - Train->mvOccupied->BrakeReleaser(0); + Train->occupied->BrakeReleaser(0); } } } @@ -219,12 +219,12 @@ void TTrain::OnCommand_independentbrakebailoff(TTrain *Train, command_data const if (Command.action == GLFW_PRESS) { // press or hold - vehicle->MoverParameters->BrakeReleaser(1); + vehicle->physics->BrakeReleaser(1); } else if (Command.action == GLFW_RELEASE) { // release - vehicle->MoverParameters->BrakeReleaser(0); + vehicle->physics->BrakeReleaser(0); } } } @@ -239,7 +239,7 @@ void TTrain::OnCommand_universalbrakebutton1(TTrain *Train, command_data const & // visual feedback Train->ggUniveralBrakeButton1.UpdateValue(1.0, Train->dsbSwitch); - Train->mvOccupied->UniversalBrakeButton(0, 1); + Train->occupied->UniversalBrakeButton(0, 1); } else if (Command.action == GLFW_RELEASE) { @@ -247,7 +247,7 @@ void TTrain::OnCommand_universalbrakebutton1(TTrain *Train, command_data const & // visual feedback Train->ggUniveralBrakeButton1.UpdateValue(0.0, Train->dsbSwitch); - Train->mvOccupied->UniversalBrakeButton(0, 0); + Train->occupied->UniversalBrakeButton(0, 0); } } @@ -260,7 +260,7 @@ void TTrain::OnCommand_universalbrakebutton2(TTrain *Train, command_data const & // visual feedback Train->ggUniveralBrakeButton2.UpdateValue(1.0, Train->dsbSwitch); - Train->mvOccupied->UniversalBrakeButton(1, 1); + Train->occupied->UniversalBrakeButton(1, 1); } else if (Command.action == GLFW_RELEASE) { @@ -268,7 +268,7 @@ void TTrain::OnCommand_universalbrakebutton2(TTrain *Train, command_data const & // visual feedback Train->ggUniveralBrakeButton2.UpdateValue(0.0, Train->dsbSwitch); - Train->mvOccupied->UniversalBrakeButton(1, 0); + Train->occupied->UniversalBrakeButton(1, 0); } } @@ -281,7 +281,7 @@ void TTrain::OnCommand_universalbrakebutton3(TTrain *Train, command_data const & // visual feedback Train->ggUniveralBrakeButton3.UpdateValue(1.0, Train->dsbSwitch); - Train->mvOccupied->UniversalBrakeButton(2, 1); + Train->occupied->UniversalBrakeButton(2, 1); } else if (Command.action == GLFW_RELEASE) { @@ -289,24 +289,24 @@ void TTrain::OnCommand_universalbrakebutton3(TTrain *Train, command_data const & // visual feedback Train->ggUniveralBrakeButton3.UpdateValue(0.0, Train->dsbSwitch); - Train->mvOccupied->UniversalBrakeButton(2, 0); + Train->occupied->UniversalBrakeButton(2, 0); } } void TTrain::OnCommand_trainbrakeincrease(TTrain *Train, command_data const &Command) { - if (Command.action == GLFW_REPEAT && Train->mvOccupied->BrakeHandle == TBrakeHandle::FV4a) - Train->mvOccupied->BrakeLevelAdd(Global.brake_speed * Command.time_delta * Train->mvOccupied->BrakeCtrlPosNo); - else if (Command.action == GLFW_PRESS && Train->mvOccupied->BrakeHandle != TBrakeHandle::FV4a) - Train->set_train_brake(Train->mvOccupied->fBrakeCtrlPos + Global.fBrakeStep); + if (Command.action == GLFW_REPEAT && Train->occupied->BrakeHandle == TBrakeHandle::FV4a) + Train->occupied->BrakeLevelAdd(Global.brake_speed * Command.time_delta * Train->occupied->BrakeCtrlPosNo); + else if (Command.action == GLFW_PRESS && Train->occupied->BrakeHandle != TBrakeHandle::FV4a) + Train->set_train_brake(Train->occupied->fBrakeCtrlPos + Global.fBrakeStep); } void TTrain::OnCommand_trainbrakedecrease(TTrain *Train, command_data const &Command) { - if (Command.action == GLFW_REPEAT && Train->mvOccupied->BrakeHandle == TBrakeHandle::FV4a) - Train->mvOccupied->BrakeLevelAdd(-Global.brake_speed * Command.time_delta * Train->mvOccupied->BrakeCtrlPosNo); - else if (Command.action == GLFW_PRESS && Train->mvOccupied->BrakeHandle != TBrakeHandle::FV4a) - Train->set_train_brake(Train->mvOccupied->fBrakeCtrlPos - Global.fBrakeStep); + if (Command.action == GLFW_REPEAT && Train->occupied->BrakeHandle == TBrakeHandle::FV4a) + Train->occupied->BrakeLevelAdd(-Global.brake_speed * Command.time_delta * Train->occupied->BrakeCtrlPosNo); + else if (Command.action == GLFW_PRESS && Train->occupied->BrakeHandle != TBrakeHandle::FV4a) + Train->set_train_brake(Train->occupied->fBrakeCtrlPos - Global.fBrakeStep); else if (Command.action == GLFW_RELEASE) { // release @@ -320,7 +320,7 @@ void TTrain::OnCommand_trainbrakeset(TTrain *Train, command_data const &Command) if (Command.action != GLFW_RELEASE) { // press or hold - Train->mvOccupied->BrakeLevelSet(std::lerp(Train->mvOccupied->Handle->GetPos(bh_MIN), Train->mvOccupied->Handle->GetPos(bh_MAX), std::clamp(Command.param1, 0.0, 1.0))); + Train->occupied->BrakeLevelSet(std::lerp(Train->occupied->Handle->GetPos(bh_MIN), Train->occupied->Handle->GetPos(bh_MAX), std::clamp(Command.param1, 0.0, 1.0))); } else { @@ -370,7 +370,7 @@ void TTrain::OnCommand_trainbrakeservice(TTrain *Train, command_data const &Comm if (Command.action == GLFW_PRESS) { - Train->set_train_brake(Train->mvOccupied->BrakeCtrlPosNo / 2 + (Train->mvOccupied->BrakeHandle == TBrakeHandle::FV4a ? 1 : 0)); + Train->set_train_brake(Train->occupied->BrakeCtrlPosNo / 2 + (Train->occupied->BrakeHandle == TBrakeHandle::FV4a ? 1 : 0)); } } @@ -380,7 +380,7 @@ void TTrain::OnCommand_trainbrakefullservice(TTrain *Train, command_data const & if (Command.action == GLFW_PRESS) { - Train->set_train_brake(Train->mvOccupied->BrakeCtrlPosNo - 1); + Train->set_train_brake(Train->occupied->BrakeCtrlPosNo - 1); } } @@ -390,7 +390,7 @@ void TTrain::OnCommand_trainbrakehandleoff(TTrain *Train, command_data const &Co if (Command.action == GLFW_PRESS) { - Train->set_train_brake(Train->mvOccupied->Handle->GetPos(bh_NP)); + Train->set_train_brake(Train->occupied->Handle->GetPos(bh_NP)); } } @@ -400,11 +400,11 @@ void TTrain::OnCommand_trainbrakeemergency(TTrain *Train, command_data const &Co if (Command.action == GLFW_PRESS) { - Train->set_train_brake(Train->mvOccupied->Handle->GetPos(bh_EB)); + Train->set_train_brake(Train->occupied->Handle->GetPos(bh_EB)); /* - if( Train->mvOccupied->BrakeCtrlPosNo <= 0.1 ) { + if( Train->occupied->BrakeCtrlPosNo <= 0.1 ) { // hamulec bezpieczeństwa dla wagonów - Train->mvOccupied->RadioStopFlag = true; + Train->occupied->RadioStopFlag = true; } */ } @@ -416,13 +416,13 @@ void TTrain::OnCommand_trainbrakebasepressureincrease(TTrain *Train, command_dat if (Command.action != GLFW_RELEASE) { - if (Train->mvOccupied->BrakeHandle == TBrakeHandle::FV4a) + if (Train->occupied->BrakeHandle == TBrakeHandle::FV4a) { - Train->mvOccupied->BrakeCtrlPos2 = std::clamp(Train->mvOccupied->BrakeCtrlPos2 - 0.01, -1.5, 2.0); + Train->occupied->BrakeCtrlPos2 = std::clamp(Train->occupied->BrakeCtrlPos2 - 0.01, -1.5, 2.0); } else { - Train->mvOccupied->BrakeLevelAdd(0.01); + Train->occupied->BrakeLevelAdd(0.01); } } } @@ -433,13 +433,13 @@ void TTrain::OnCommand_trainbrakebasepressuredecrease(TTrain *Train, command_dat if (Command.action != GLFW_RELEASE) { - if (Train->mvOccupied->BrakeHandle == TBrakeHandle::FV4a) + if (Train->occupied->BrakeHandle == TBrakeHandle::FV4a) { - Train->mvOccupied->BrakeCtrlPos2 = std::clamp(Train->mvOccupied->BrakeCtrlPos2 + 0.01, -1.5, 2.0); + Train->occupied->BrakeCtrlPos2 = std::clamp(Train->occupied->BrakeCtrlPos2 + 0.01, -1.5, 2.0); } else { - Train->mvOccupied->BrakeLevelAdd(-0.01); + Train->occupied->BrakeLevelAdd(-0.01); } } } @@ -450,7 +450,7 @@ void TTrain::OnCommand_trainbrakebasepressurereset(TTrain *Train, command_data c if (Command.action == GLFW_PRESS) { - Train->mvOccupied->BrakeCtrlPos2 = 0; + Train->occupied->BrakeCtrlPos2 = 0; } } @@ -466,9 +466,9 @@ void TTrain::OnCommand_trainbrakeoperationtoggle(TTrain *Train, command_data con return; } - vehicle->MoverParameters->Hamulec->SetBrakeStatus(vehicle->MoverParameters->Hamulec->GetBrakeStatus() ^ b_dmg); + vehicle->physics->Hamulec->SetBrakeStatus(vehicle->physics->Hamulec->GetBrakeStatus() ^ b_dmg); // the brake is the player's now, the wagon inspector won't put it back on its own - vehicle->MoverParameters->BrakeCutOutByInspector = false; + vehicle->physics->BrakeCutOutByInspector = false; } } @@ -484,10 +484,10 @@ void TTrain::OnCommand_manualbrakeincrease(TTrain *Train, command_data const &Co return; } - if (vehicle->MoverParameters->LocalBrake == TLocalBrake::ManualBrake || vehicle->MoverParameters->MBrake == true) + if (vehicle->physics->LocalBrake == TLocalBrake::ManualBrake || vehicle->physics->MBrake == true) { - vehicle->MoverParameters->IncManualBrakeLevel(1); + vehicle->physics->IncManualBrakeLevel(1); } } } @@ -504,10 +504,10 @@ void TTrain::OnCommand_manualbrakedecrease(TTrain *Train, command_data const &Co return; } - if (vehicle->MoverParameters->LocalBrake == TLocalBrake::ManualBrake || vehicle->MoverParameters->MBrake == true) + if (vehicle->physics->LocalBrake == TLocalBrake::ManualBrake || vehicle->physics->MBrake == true) { - vehicle->MoverParameters->DecManualBrakeLevel(1); + vehicle->physics->DecManualBrakeLevel(1); } } } @@ -518,7 +518,7 @@ void TTrain::OnCommand_alarmchaintoggle(TTrain *Train, command_data const &Comma if (Command.action == GLFW_PRESS) { - if (false == Train->mvOccupied->AlarmChainFlag) + if (false == Train->occupied->AlarmChainFlag) { OnCommand_alarmchainenable(Train, Command); } @@ -535,7 +535,7 @@ void TTrain::OnCommand_alarmchainenable(TTrain *Train, command_data const &Comma { // pull - Train->mvOccupied->AlarmChainSwitch(true); + Train->occupied->AlarmChainSwitch(true); // visual feedback Train->ggAlarmChain.UpdateValue(1.0); } @@ -547,7 +547,7 @@ void TTrain::OnCommand_alarmchaindisable(TTrain *Train, command_data const &Comm { // release - Train->mvOccupied->AlarmChainSwitch(false); + Train->occupied->AlarmChainSwitch(false); // visual feedback Train->ggAlarmChain.UpdateValue(0.0); } @@ -566,7 +566,7 @@ void TTrain::OnCommand_wheelspinbrakeactivate(TTrain *Train, command_data const return; } - if (Train->mvOccupied->BrakeSystem != TBrakeSystem::ElectroPneumatic) + if (Train->occupied->BrakeSystem != TBrakeSystem::ElectroPneumatic) { // standard behaviour if (Command.action == GLFW_PRESS) @@ -590,11 +590,11 @@ void TTrain::OnCommand_wheelspinbrakeactivate(TTrain *Train, command_data const // visual feedback Train->ggAntiSlipButton.UpdateValue(1.0, Train->dsbPneumaticSwitch); - // the EP fuse is the cab car's (Ctrl+Z switches mvOccupied's), checked by SwitchEPBrake with the rest of + // the EP fuse is the cab car's (Ctrl+Z switches occupied's), checked by SwitchEPBrake with the rest of // the control's supply - if (Train->mvOccupied->BrakeHandle == TBrakeHandle::St113) + if (Train->occupied->BrakeHandle == TBrakeHandle::St113) { - Train->mvOccupied->SwitchEPBrake(1); + Train->occupied->SwitchEPBrake(1); } } else if (Command.action == GLFW_RELEASE) @@ -602,7 +602,7 @@ void TTrain::OnCommand_wheelspinbrakeactivate(TTrain *Train, command_data const // visual feedback Train->ggAntiSlipButton.UpdateValue(0.0); - Train->mvOccupied->SwitchEPBrake(0); + Train->occupied->SwitchEPBrake(0); } } } @@ -625,14 +625,14 @@ void TTrain::OnCommand_sandboxactivate(TTrain *Train, command_data const &Comman // visual feedback Train->ggSandButton.UpdateValue(1.0, Train->dsbSwitch); - Train->mvControlled->SandboxManual(true); + Train->controlled->SandboxManual(true); } else if (Command.action == GLFW_RELEASE) { // visual feedback Train->ggSandButton.UpdateValue(0.0); - Train->mvControlled->SandboxManual(false); + Train->controlled->SandboxManual(false); } } @@ -642,7 +642,7 @@ void TTrain::OnCommand_autosandboxtoggle(TTrain *Train, command_data const &Comm if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvOccupied->SandDoseAutoAllow) + if (false == Train->occupied->SandDoseAutoAllow) { // turn on OnCommand_autosandboxactivate(Train, Command); @@ -660,7 +660,7 @@ void TTrain::OnCommand_autosandboxactivate(TTrain *Train, command_data const &Co if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SandboxAutoAllow(true); + Train->occupied->SandboxAutoAllow(true); Train->ggAutoSandButton.UpdateValue(1.0, Train->dsbSwitch); } }; @@ -670,7 +670,7 @@ void TTrain::OnCommand_autosandboxdeactivate(TTrain *Train, command_data const & if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SandboxAutoAllow(false); + Train->occupied->SandboxAutoAllow(false); Train->ggAutoSandButton.UpdateValue(0.0, Train->dsbSwitch); } }; @@ -681,7 +681,7 @@ void TTrain::OnCommand_epbrakecontrolenable(TTrain *Train, command_data const &C // command only works for bistable switch if (Command.action == GLFW_PRESS && istoggle) { - if (Train->mvOccupied->EpFuseSwitch(true)) + if (Train->occupied->EpFuseSwitch(true)) { // audio feedback if (Train->dsbPneumaticSwitch) @@ -699,7 +699,7 @@ void TTrain::OnCommand_epbrakecontroldisable(TTrain *Train, command_data const & // command only works for bistable switch if (Command.action == GLFW_PRESS && istoggle) { - if (Train->mvOccupied->EpFuseSwitch(false)) + if (Train->occupied->EpFuseSwitch(false)) { Train->ggEPFuseButton.UpdateValue(0.0f, Train->dsbSwitch); } @@ -722,11 +722,11 @@ void TTrain::OnCommand_epbrakecontroltoggle(TTrain *Train, command_data const &C if (istoggle) { // switch state - if (false == Train->mvOccupied->EpFuse) + if (false == Train->occupied->EpFuse) { // turn on // audio feedback - if (Train->mvOccupied->EpFuseSwitch(true) && Train->dsbPneumaticSwitch) + if (Train->occupied->EpFuseSwitch(true) && Train->dsbPneumaticSwitch) { Train->dsbPneumaticSwitch->play(); } @@ -734,21 +734,21 @@ void TTrain::OnCommand_epbrakecontroltoggle(TTrain *Train, command_data const &C else { // turn off - Train->mvOccupied->EpFuseSwitch(false); + Train->occupied->EpFuseSwitch(false); } } else if (ispush) { // potentially turn on // audio feedback - if (Train->mvOccupied->EpFuseSwitch(true) && Train->dsbPneumaticSwitch) + if (Train->occupied->EpFuseSwitch(true) && Train->dsbPneumaticSwitch) { Train->dsbPneumaticSwitch->play(); } } // visual feedback Train->ggEPFuseButton.UpdateValue(ispush ? 1.0f : // push or pushtoggle - Train->mvOccupied->EpFuse ? 1.0f : + Train->occupied->EpFuse ? 1.0f : 0.0f, // toggle Train->dsbSwitch); } @@ -763,12 +763,12 @@ void TTrain::OnCommand_trainbrakeoperationmodeincrease(TTrain *Train, command_da { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Command.action == GLFW_PRESS && (Train->mvOccupied->BrakeOpModeFlag << 1 & Train->mvOccupied->BrakeOpModes) != 0) + if (Command.action == GLFW_PRESS && (Train->occupied->BrakeOpModeFlag << 1 & Train->occupied->BrakeOpModes) != 0) { // next mode - Train->mvOccupied->BrakeOpModeFlag <<= 1; + Train->occupied->BrakeOpModeFlag <<= 1; // visual feedback - Train->ggBrakeOperationModeCtrl.UpdateValue(Train->mvOccupied->BrakeOpModeFlag > 0 ? static_cast(std::log2(Train->mvOccupied->BrakeOpModeFlag)) : 0); // audio fallback + Train->ggBrakeOperationModeCtrl.UpdateValue(Train->occupied->BrakeOpModeFlag > 0 ? static_cast(std::log2(Train->occupied->BrakeOpModeFlag)) : 0); // audio fallback } } @@ -776,12 +776,12 @@ void TTrain::OnCommand_trainbrakeoperationmodedecrease(TTrain *Train, command_da { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Command.action == GLFW_PRESS && (Train->mvOccupied->BrakeOpModeFlag >> 1 & Train->mvOccupied->BrakeOpModes) != 0) + if (Command.action == GLFW_PRESS && (Train->occupied->BrakeOpModeFlag >> 1 & Train->occupied->BrakeOpModes) != 0) { // previous mode - Train->mvOccupied->BrakeOpModeFlag >>= 1; + Train->occupied->BrakeOpModeFlag >>= 1; // visual feedback - Train->ggBrakeOperationModeCtrl.UpdateValue(Train->mvOccupied->BrakeOpModeFlag > 0 ? static_cast(std::log2(Train->mvOccupied->BrakeOpModeFlag)) : 0); + Train->ggBrakeOperationModeCtrl.UpdateValue(Train->occupied->BrakeOpModeFlag > 0 ? static_cast(std::log2(Train->occupied->BrakeOpModeFlag)) : 0); } } @@ -797,12 +797,12 @@ void TTrain::OnCommand_brakeactingspeedincrease(TTrain *Train, command_data cons return; } - if ((vehicle->MoverParameters->BrakeDelayFlag & bdelay_M) != 0) + if ((vehicle->physics->BrakeDelayFlag & bdelay_M) != 0) { // can't speed it up any more than this return; } - auto const fasterbrakesetting = vehicle->MoverParameters->BrakeDelayFlag < bdelay_R ? vehicle->MoverParameters->BrakeDelayFlag << 1 : vehicle->MoverParameters->BrakeDelayFlag | bdelay_M; + auto const fasterbrakesetting = vehicle->physics->BrakeDelayFlag < bdelay_R ? vehicle->physics->BrakeDelayFlag << 1 : vehicle->physics->BrakeDelayFlag | bdelay_M; Train->set_train_brake_speed(vehicle, fasterbrakesetting); } @@ -820,12 +820,12 @@ void TTrain::OnCommand_brakeactingspeeddecrease(TTrain *Train, command_data cons return; } - if (vehicle->MoverParameters->BrakeDelayFlag == bdelay_G) + if (vehicle->physics->BrakeDelayFlag == bdelay_G) { // can't slow it down any more than this return; } - auto const slowerbrakesetting = vehicle->MoverParameters->BrakeDelayFlag < bdelay_M ? vehicle->MoverParameters->BrakeDelayFlag >> 1 : vehicle->MoverParameters->BrakeDelayFlag ^ bdelay_M; + auto const slowerbrakesetting = vehicle->physics->BrakeDelayFlag < bdelay_M ? vehicle->physics->BrakeDelayFlag >> 1 : vehicle->physics->BrakeDelayFlag ^ bdelay_M; Train->set_train_brake_speed(vehicle, slowerbrakesetting); } @@ -887,7 +887,7 @@ void TTrain::OnCommand_brakeloadcompensationincrease(TTrain *Train, command_data auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; if (vehicle != nullptr) { - vehicle->MoverParameters->IncBrakeMult(); + vehicle->physics->IncBrakeMult(); } } } @@ -900,7 +900,7 @@ void TTrain::OnCommand_brakeloadcompensationdecrease(TTrain *Train, command_data auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; if (vehicle != nullptr) { - vehicle->MoverParameters->DecBrakeMult(); + vehicle->physics->DecBrakeMult(); } } } @@ -916,7 +916,7 @@ void TTrain::OnCommand_mubrakingindicatortoggle(TTrain *Train, command_data cons } return; } - if (Train->mvControlled->TrainType != train_type::emu) + if (Train->controlled->TrainType != train_type::emu) { // return; @@ -925,17 +925,17 @@ void TTrain::OnCommand_mubrakingindicatortoggle(TTrain *Train, command_data cons if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvControlled->Signalling) + if (false == Train->controlled->Signalling) { // turn on - Train->mvControlled->Signalling = true; + Train->controlled->Signalling = true; // visual feedback Train->ggSignallingButton.UpdateValue(1.0, Train->dsbSwitch); } else { // turn off - Train->mvControlled->Signalling = false; + Train->controlled->Signalling = false; // visual feedback Train->ggSignallingButton.UpdateValue(0.0, Train->dsbSwitch); } diff --git a/vehicle/cab/cab.cpp b/vehicle/cab/cab.cpp index bc5bc11a5..1d3192f30 100644 --- a/vehicle/cab/cab.cpp +++ b/vehicle/cab/cab.cpp @@ -38,7 +38,7 @@ http://mozilla.org/MPL/2.0/. #include "Console.h" #include "application/application.h" #include "rendering/renderer.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include #include #include diff --git a/vehicle/cab/cabcommands.cpp b/vehicle/cab/cabcommands.cpp index 5b505ed85..25ac96377 100644 --- a/vehicle/cab/cabcommands.cpp +++ b/vehicle/cab/cabcommands.cpp @@ -38,7 +38,7 @@ http://mozilla.org/MPL/2.0/. #include "Console.h" #include "application/application.h" #include "rendering/renderer.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include #include #include @@ -51,24 +51,24 @@ void TTrain::OnCommand_wiperswitchincrease(TTrain *Train, command_data const &Co { if (Command.action == GLFW_PRESS) { - Train->mvOccupied->wiperSwitchPos++; - if (Train->mvOccupied->wiperSwitchPos > Train->mvOccupied->WiperListSize - 1) - Train->mvOccupied->wiperSwitchPos = Train->mvOccupied->WiperListSize - 1; + Train->occupied->wiperSwitchPos++; + if (Train->occupied->wiperSwitchPos > Train->occupied->WiperListSize - 1) + Train->occupied->wiperSwitchPos = Train->occupied->WiperListSize - 1; // Visual feedback - Train->ggWiperSw.UpdateValue(static_cast(Train->mvOccupied->wiperSwitchPos), Train->dsbSwitch); + Train->ggWiperSw.UpdateValue(static_cast(Train->occupied->wiperSwitchPos), Train->dsbSwitch); } } void TTrain::OnCommand_wiperswitchdecrease(TTrain *Train, command_data const &Command) { if (Command.action == GLFW_PRESS) { - Train->mvOccupied->wiperSwitchPos--; - if (Train->mvOccupied->wiperSwitchPos < 0) - Train->mvOccupied->wiperSwitchPos = 0; + Train->occupied->wiperSwitchPos--; + if (Train->occupied->wiperSwitchPos < 0) + Train->occupied->wiperSwitchPos = 0; // visual feedback - Train->ggWiperSw.UpdateValue(static_cast(Train->mvOccupied->wiperSwitchPos), Train->dsbSwitch); + Train->ggWiperSw.UpdateValue(static_cast(Train->occupied->wiperSwitchPos), Train->dsbSwitch); } } @@ -80,13 +80,13 @@ void TTrain::OnCommand_reverserincrease(TTrain *Train, command_data const &Comma // HACK: master controller position isn't set in occupied vehicle in E(D)MUs // so we do a manual check in relevant vehicle here - if (false == Train->mvControlled->EIMDirectionChangeAllow()) + if (false == Train->controlled->EIMDirectionChangeAllow()) { return; } // aktualizacja skrajnych pojazdów w składzie - if (Train->mvOccupied->DirectionForward() && Train->mvOccupied->DirActive && Train->DynamicObject->Mechanik) + if (Train->occupied->DirectionForward() && Train->occupied->DirActive && Train->DynamicObject->Mechanik) { Train->DynamicObject->Mechanik->DirectionChange(); @@ -102,13 +102,13 @@ void TTrain::OnCommand_reverserdecrease(TTrain *Train, command_data const &Comma // HACK: master controller position isn't set in occupied vehicle in E(D)MUs // so we do a manual check in relevant vehicle here - if (false == Train->mvControlled->EIMDirectionChangeAllow()) + if (false == Train->controlled->EIMDirectionChangeAllow()) { return; } // aktualizacja skrajnych pojazdów w składzie - if (Train->mvOccupied->DirectionBackward() && Train->mvOccupied->DirActive && Train->DynamicObject->Mechanik) + if (Train->occupied->DirectionBackward() && Train->occupied->DirActive && Train->DynamicObject->Mechanik) { Train->DynamicObject->Mechanik->DirectionChange(); @@ -124,7 +124,7 @@ void TTrain::OnCommand_reverserforwardhigh(TTrain *Train, command_data const &Co // HACK: master controller position isn't set in occupied vehicle in E(D)MUs // so we do a manual check in relevant vehicle here - if (false == Train->mvControlled->EIMDirectionChangeAllow()) + if (false == Train->controlled->EIMDirectionChangeAllow()) { return; } @@ -132,15 +132,15 @@ void TTrain::OnCommand_reverserforwardhigh(TTrain *Train, command_data const &Co // HACK: try to move the reverser one position back, in case it's set to "high forward" OnCommand_reverserdecrease(Train, Command); - if (Train->mvOccupied->DirActive < 1) + if (Train->occupied->DirActive < 1) { - while (Train->mvOccupied->DirActive < 1 && true == Train->mvOccupied->DirectionForward()) + while (Train->occupied->DirActive < 1 && true == Train->occupied->DirectionForward()) { // all work is done in the header } // aktualizacja skrajnych pojazdów w składzie - if (Train->mvOccupied->DirActive == 1 && Train->DynamicObject->Mechanik) + if (Train->occupied->DirActive == 1 && Train->DynamicObject->Mechanik) { Train->DynamicObject->Mechanik->DirectionChange(); @@ -158,7 +158,7 @@ void TTrain::OnCommand_reverserforward(TTrain *Train, command_data const &Comman // HACK: master controller position isn't set in occupied vehicle in E(D)MUs // so we do a manual check in relevant vehicle here - if (false == Train->mvControlled->EIMDirectionChangeAllow()) + if (false == Train->controlled->EIMDirectionChangeAllow()) { return; } @@ -168,15 +168,15 @@ void TTrain::OnCommand_reverserforward(TTrain *Train, command_data const &Comman // visual feedback Train->ggDirForwardButton.UpdateValue(1.0, Train->dsbSwitch); - if (Train->mvOccupied->DirActive == 0) + if (Train->occupied->DirActive == 0) { - while (Train->mvOccupied->DirActive < 1 && true == Train->mvOccupied->DirectionForward()) + while (Train->occupied->DirActive < 1 && true == Train->occupied->DirectionForward()) { // all work is done in the header } // aktualizacja skrajnych pojazdów w składzie - if (Train->mvOccupied->DirActive == 1 && Train->DynamicObject->Mechanik) + if (Train->occupied->DirActive == 1 && Train->DynamicObject->Mechanik) { Train->DynamicObject->Mechanik->DirectionChange(); @@ -199,17 +199,17 @@ void TTrain::OnCommand_reverserneutral(TTrain *Train, command_data const &Comman // HACK: master controller position isn't set in occupied vehicle in E(D)MUs // so we do a manual check in relevant vehicle here - if (false == Train->mvControlled->EIMDirectionChangeAllow()) + if (false == Train->controlled->EIMDirectionChangeAllow()) { return; } // visual feedback Train->ggDirNeutralButton.UpdateValue(1.0, Train->dsbSwitch); - while (Train->mvOccupied->DirActive < 0 && true == Train->mvOccupied->DirectionForward()) + while (Train->occupied->DirActive < 0 && true == Train->occupied->DirectionForward()) { // all work is done in the header } - while (Train->mvOccupied->DirActive > 0 && true == Train->mvOccupied->DirectionBackward()) + while (Train->occupied->DirActive > 0 && true == Train->occupied->DirectionBackward()) { // all work is done in the header } @@ -230,20 +230,20 @@ void TTrain::OnCommand_reverserbackward(TTrain *Train, command_data const &Comma // HACK: master controller position isn't set in occupied vehicle in E(D)MUs // so we do a manual check in relevant vehicle here - if (false == Train->mvControlled->EIMDirectionChangeAllow()) + if (false == Train->controlled->EIMDirectionChangeAllow()) { return; } Train->ggDirBackwardButton.UpdateValue(1.0, Train->dsbSwitch); - if (Train->mvOccupied->DirActive == 0) + if (Train->occupied->DirActive == 0) { - while (Train->mvOccupied->DirActive > -1 && true == Train->mvOccupied->DirectionBackward()) + while (Train->occupied->DirActive > -1 && true == Train->occupied->DirectionBackward()) { // all work is done in the header } // aktualizacja skrajnych pojazdów w składzie - if (Train->mvOccupied->DirActive == -1 && Train->DynamicObject->Mechanik) + if (Train->occupied->DirActive == -1 && Train->DynamicObject->Mechanik) { Train->DynamicObject->Mechanik->DirectionChange(); @@ -265,16 +265,16 @@ void TTrain::OnCommand_alerteracknowledge(TTrain *Train, command_data const &Com // visual feedback Train->ggSecurityResetButton.UpdateValue(1.0, Train->dsbSwitch); - if (Train->mvOccupied->TrainType == train_type::emu || Train->mvOccupied->DirActive != 0) - Train->mvOccupied->SecuritySystem.acknowledge_press(); + if (Train->occupied->TrainType == train_type::emu || Train->occupied->DirActive != 0) + Train->occupied->SecuritySystem.acknowledge_press(); } else if (Command.action == GLFW_RELEASE) { // visual feedback Train->ggSecurityResetButton.UpdateValue(0.0); - if (Train->mvOccupied->TrainType == train_type::emu || Train->mvOccupied->DirActive != 0) - Train->mvOccupied->SecuritySystem.acknowledge_release(); + if (Train->occupied->TrainType == train_type::emu || Train->occupied->DirActive != 0) + Train->occupied->SecuritySystem.acknowledge_release(); } } @@ -283,9 +283,9 @@ void TTrain::OnCommand_cabsignalacknowledge(TTrain *Train, command_data const &C // TODO: visual feedback if (Command.action == GLFW_PRESS) { - if (Train->mvOccupied->SecuritySystem.has_separate_acknowledge()) + if (Train->occupied->SecuritySystem.has_separate_acknowledge()) { - Train->mvOccupied->SecuritySystem.cabsignal_reset(); + Train->occupied->SecuritySystem.cabsignal_reset(); Train->ggSHPResetButton.UpdateValue(1.0, Train->dsbSwitch); } } @@ -300,7 +300,7 @@ void TTrain::OnCommand_batterytoggle(TTrain *Train, command_data const &Command) if (Train->allowBatteryToggle || Command.action != GLFW_REPEAT) { // keep the switch from flipping back and forth if key is held down - if (false == Train->mvOccupied->Power24vIsAvailable) + if (false == Train->occupied->Power24vIsAvailable) { // turn on OnCommand_batteryenable(Train, Command); @@ -315,7 +315,7 @@ void TTrain::OnCommand_batterytoggle(TTrain *Train, command_data const &Command) void TTrain::OnCommand_batteryenable(TTrain *Train, command_data const &Command) { - if (!Train->mvOccupied->isBatteryButtonImpulse) + if (!Train->occupied->isBatteryButtonImpulse) { // regular button behavior if (Command.action == GLFW_PRESS) { @@ -323,10 +323,10 @@ void TTrain::OnCommand_batteryenable(TTrain *Train, command_data const &Command) Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); Train->ggBatteryOnButton.UpdateValue(1.0f, Train->dsbSwitch); - Train->mvOccupied->BatterySwitch(true); + Train->occupied->BatterySwitch(true); Train->allowBatteryToggle = false; // side-effects - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { Train->Dynamic()->SetLights(); } @@ -346,20 +346,20 @@ void TTrain::OnCommand_batteryenable(TTrain *Train, command_data const &Command) { if (Command.action == GLFW_PRESS) { - if (Train->mvOccupied->shouldHoldBatteryButton) + if (Train->occupied->shouldHoldBatteryButton) { // jesli przycisk trzeba przytrzymac Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); Train->ggBatteryOnButton.UpdateValue(1.0f, Train->dsbSwitch); - Train->fBatteryTimer = Train->mvOccupied->BatteryButtonHoldTime; // start timer + Train->fBatteryTimer = Train->occupied->BatteryButtonHoldTime; // start timer } else { // jesli przycisk dziala od razu - Train->mvOccupied->BatterySwitch(true); + Train->occupied->BatterySwitch(true); Train->allowBatteryToggle = false; // side-effects - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { Train->Dynamic()->SetLights(); } @@ -376,18 +376,18 @@ void TTrain::OnCommand_batteryenable(TTrain *Train, command_data const &Command) Train->ggBatteryOnButton.UpdateValue(0.0f, Train->dsbSwitch); Train->fBatteryTimer = -1.f; // Train->allowBatteryToggle = true; - Train->mvOccupied->batterySwAlreadyFired = false; + Train->occupied->batterySwAlreadyFired = false; } - else if (Command.action == GLFW_REPEAT && Train->mvOccupied->shouldHoldBatteryButton) + else if (Command.action == GLFW_REPEAT && Train->occupied->shouldHoldBatteryButton) { // trzymamy przycisk - if (Train->fBatteryTimer <= 0.0 && Train->mvOccupied->Battery == false && !Train->mvOccupied->batterySwAlreadyFired) + if (Train->fBatteryTimer <= 0.0 && Train->occupied->Battery == false && !Train->occupied->batterySwAlreadyFired) { - Train->mvOccupied->BatterySwitch(true); - Train->mvOccupied->batterySwAlreadyFired = true; + Train->occupied->BatterySwitch(true); + Train->occupied->batterySwAlreadyFired = true; // side-effects - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { Train->Dynamic()->SetLights(); } @@ -399,7 +399,7 @@ void TTrain::OnCommand_batteryenable(TTrain *Train, command_data const &Command) void TTrain::OnCommand_batterydisable(TTrain *Train, command_data const &Command) { - if (!Train->mvOccupied->isBatteryButtonImpulse) + if (!Train->occupied->isBatteryButtonImpulse) { // regular button behavior if (Command.action == GLFW_PRESS) { @@ -407,10 +407,10 @@ void TTrain::OnCommand_batterydisable(TTrain *Train, command_data const &Command Train->ggBatteryButton.UpdateValue(0.0f, Train->dsbSwitch); Train->ggBatteryOffButton.UpdateValue(1.0f, Train->dsbSwitch); - Train->mvOccupied->BatterySwitch(false); + Train->occupied->BatterySwitch(false); // side-effects - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { Train->Dynamic()->SetLights(); } @@ -429,21 +429,21 @@ void TTrain::OnCommand_batterydisable(TTrain *Train, command_data const &Command { if (Command.action == GLFW_PRESS) { - if (Train->mvOccupied->shouldHoldBatteryButton) + if (Train->occupied->shouldHoldBatteryButton) { // jesli przycisk trzeba przytrzymac Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); Train->ggBatteryOffButton.UpdateValue(1.0f, Train->dsbSwitch); - Train->fBatteryTimer = Train->mvOccupied->BatteryButtonHoldTime; // start timer + Train->fBatteryTimer = Train->occupied->BatteryButtonHoldTime; // start timer } else { // jesli przycisk dziala od razu - Train->mvOccupied->BatterySwitch(false); + Train->occupied->BatterySwitch(false); Train->allowBatteryToggle = false; // side-effects - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { Train->Dynamic()->SetLights(); } @@ -458,18 +458,18 @@ void TTrain::OnCommand_batterydisable(TTrain *Train, command_data const &Command Train->ggBatteryButton.UpdateValue(0.0f, Train->dsbSwitch); Train->ggBatteryOffButton.UpdateValue(0.0f, Train->dsbSwitch); Train->allowBatteryToggle = true; - Train->mvOccupied->batterySwAlreadyFired = false; + Train->occupied->batterySwAlreadyFired = false; } - else if (Command.action == GLFW_REPEAT && Train->mvOccupied->shouldHoldBatteryButton) + else if (Command.action == GLFW_REPEAT && Train->occupied->shouldHoldBatteryButton) { // trzymamy przycisk - if (Train->fBatteryTimer <= 0.0 && Train->mvOccupied->Battery == true && !Train->mvOccupied->batterySwAlreadyFired) + if (Train->fBatteryTimer <= 0.0 && Train->occupied->Battery == true && !Train->occupied->batterySwAlreadyFired) { - Train->mvOccupied->BatterySwitch(false); - Train->mvOccupied->batterySwAlreadyFired = true; + Train->occupied->BatterySwitch(false); + Train->occupied->batterySwAlreadyFired = true; // side-effects - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { Train->Dynamic()->SetLights(); } @@ -485,7 +485,7 @@ void TTrain::OnCommand_cabactivationtoggle(TTrain *Train, command_data const &Co if (Command.action != GLFW_REPEAT) { // keep the switch from flipping back and forth if key is held down - if (0 == Train->mvOccupied->CabActive) + if (0 == Train->occupied->CabActive) { // turn on OnCommand_cabactivationenable(Train, Command); @@ -509,10 +509,10 @@ void TTrain::OnCommand_cabactivationenable(TTrain *Train, command_data const &Co Train->ggCabActivationButton.UpdateValue(1.0f, Train->dsbSwitch); } - Train->mvOccupied->CabActivisation(); + Train->occupied->CabActivisation(); // side-effects - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { Train->Dynamic()->SetLights(); } @@ -535,8 +535,8 @@ void TTrain::OnCommand_cabactivationdisable(TTrain *Train, command_data const &C Train->ggCabActivationButton.UpdateValue(0.0f, Train->dsbSwitch); } - Train->mvOccupied->CabDeactivisation(); - if (Train->mvOccupied->LightsPosNo > 0 && Train->mvOccupied->InactiveCabFlag & activation::redmarkers) + Train->occupied->CabDeactivisation(); + if (Train->occupied->LightsPosNo > 0 && Train->occupied->InactiveCabFlag & activation::redmarkers) { Train->Dynamic()->SetLights(); } @@ -556,21 +556,21 @@ void TTrain::OnCommand_cabchangeforward(TTrain *Train, command_data const &Comma if (auto const movedirection{1}; false == Train->CabChange(movedirection)) { auto const exitdirection{(movedirection > 0 ? VehicleEnd::front : VehicleEnd::rear)}; - if (Train->mvOccupied->Couplers[exitdirection].CouplingFlag.HasAll(Coupling::gangway)) + if (Train->occupied->Couplers[exitdirection].CouplingFlag.HasAll(Coupling::gangway)) { // przejscie do nastepnego pojazdu auto *targetvehicle = exitdirection == VehicleEnd::front ? Train->DynamicObject->PrevConnected() : Train->DynamicObject->NextConnected(); - targetvehicle->MoverParameters->CabOccupied = Train->mvOccupied->Neighbours[exitdirection].vehicle_end ? -1 : 1; + targetvehicle->physics->CabOccupied = Train->occupied->Neighbours[exitdirection].vehicle_end ? -1 : 1; Train->MoveToVehicle(targetvehicle); } } // HACK: match consist door permit state with the preset in the active cab if (Train->ggDoorPermitPresetButton.SubModel != nullptr) { - Train->mvOccupied->ChangeDoorPermitPreset(0); + Train->occupied->ChangeDoorPermitPreset(0); } // HACK: update lights state - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { Train->DynamicObject->SetLights(); } @@ -586,21 +586,21 @@ void TTrain::OnCommand_cabchangebackward(TTrain *Train, command_data const &Comm { // current vehicle doesn't extend any farther in this direction, check if we there's one connected we can move to auto const exitdirection{(movedirection > 0 ? VehicleEnd::front : VehicleEnd::rear)}; - if (Train->mvOccupied->Couplers[exitdirection].CouplingFlag.HasAll(Coupling::gangway)) + if (Train->occupied->Couplers[exitdirection].CouplingFlag.HasAll(Coupling::gangway)) { // przejscie do nastepnego pojazdu auto *targetvehicle = exitdirection == VehicleEnd::front ? Train->DynamicObject->PrevConnected() : Train->DynamicObject->NextConnected(); - targetvehicle->MoverParameters->CabOccupied = Train->mvOccupied->Neighbours[exitdirection].vehicle_end ? -1 : 1; + targetvehicle->physics->CabOccupied = Train->occupied->Neighbours[exitdirection].vehicle_end ? -1 : 1; Train->MoveToVehicle(targetvehicle); } } // HACK: match consist door permit state with the preset in the active cab if (Train->ggDoorPermitPresetButton.SubModel != nullptr) { - Train->mvOccupied->ChangeDoorPermitPreset(0); + Train->occupied->ChangeDoorPermitPreset(0); } // HACK: update lights state - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { Train->DynamicObject->SetLights(); } @@ -638,13 +638,13 @@ void TTrain::OnCommand_vehicleboost(TTrain *Train, const command_data &Command) auto *vehicle{Train->DynamicObject}; while (vehicle) { - vehicle->MoverParameters->V += vehicle->DirectionGet() * boost; + vehicle->physics->V += vehicle->DirectionGet() * boost; vehicle = vehicle->Next(); // pozostałe też } vehicle = Train->DynamicObject->Prev(); while (vehicle) { - vehicle->MoverParameters->V += vehicle->DirectionGet() * boost; + vehicle->physics->V += vehicle->DirectionGet() * boost; vehicle = vehicle->Prev(); // w drugą stronę też } } diff --git a/vehicle/cab/commandtable.cpp b/vehicle/cab/commandtable.cpp index e0632a5fb..76908fcd5 100644 --- a/vehicle/cab/commandtable.cpp +++ b/vehicle/cab/commandtable.cpp @@ -38,7 +38,7 @@ http://mozilla.org/MPL/2.0/. #include "Console.h" #include "application/application.h" #include "rendering/renderer.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include #include #include diff --git a/vehicle/cab/controllercommands.cpp b/vehicle/cab/controllercommands.cpp index 1d2445a29..06974960a 100644 --- a/vehicle/cab/controllercommands.cpp +++ b/vehicle/cab/controllercommands.cpp @@ -38,7 +38,7 @@ http://mozilla.org/MPL/2.0/. #include "Console.h" #include "application/application.h" #include "rendering/renderer.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include #include #include @@ -87,37 +87,37 @@ void TTrain::OnCommand_jointcontrollerset(TTrain *Train, command_data const &Com if (Command.param1 >= 0.5) { Train->set_master_controller((Command.param1 * 2 - 1) * - (Train->mvControlled->CoupledCtrl ? Train->mvControlled->MainCtrlPosNo + Train->mvControlled->ScndCtrlPosNo : Train->mvControlled->MainCtrlPosNo)); + (Train->controlled->CoupledCtrl ? Train->controlled->MainCtrlPosNo + Train->controlled->ScndCtrlPosNo : Train->controlled->MainCtrlPosNo)); Train->m_mastercontrollerinuse = true; // when SplitEDPneumaticBrake is active the joint controller's negative range // commands the dedicated dynamic-brake lever instead of the local pneumatic brake - if (Train->mvControlled->SplitEDPneumaticBrake) + if (Train->controlled->SplitEDPneumaticBrake) { - Train->mvControlled->DynamicBrakeLevelSet(0.0); + Train->controlled->DynamicBrakeLevelSet(0.0); } else { - Train->mvOccupied->LocalBrakePosA = 0; + Train->occupied->LocalBrakePosA = 0; } } else { auto const negativeRange{std::clamp(1.0 - Command.param1 * 2, 0.0, 1.0)}; - if (Train->mvControlled->SplitEDPneumaticBrake) + if (Train->controlled->SplitEDPneumaticBrake) { // negative range of jointctrl drives only ED braking, local pneumatic brake stays untouched. // snap to DBPN discrete stops so the lever animates step-by-step - auto const stepCount{std::max(1, Train->mvControlled->DynamicBrakeCtrlPosNo)}; + auto const stepCount{std::max(1, Train->controlled->DynamicBrakeCtrlPosNo)}; auto const snapped{std::round(negativeRange * stepCount) / stepCount}; - Train->mvControlled->DynamicBrakeLevelSet(snapped); + Train->controlled->DynamicBrakeLevelSet(snapped); } else { - Train->mvOccupied->LocalBrakePosA = negativeRange; + Train->occupied->LocalBrakePosA = negativeRange; } - if (Train->mvControlled->MainCtrlPowerPos() > 0) + if (Train->controlled->MainCtrlPowerPos() > 0) { - Train->set_master_controller(Train->mvControlled->MainCtrlNoPowerPos()); + Train->set_master_controller(Train->controlled->MainCtrlNoPowerPos()); } } } @@ -135,10 +135,10 @@ void TTrain::OnCommand_mastercontrollerincrease(TTrain *Train, command_data cons if (Command.action != GLFW_RELEASE) { // on press or hold - auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; + auto const splitMode{Train->controlled->SplitEDPneumaticBrake}; // when SplitEDPneumaticBrake is true the joint controller's negative range maps // to the dedicated dynamic-brake lever (DynamicBrakeCtrl) rather than to LocalBrake - auto const negativeRangeActive{splitMode ? Train->mvControlled->DynamicBrakeCtrlPos > 0.0 : Train->mvOccupied->LocalBrakePosA > 0.0}; + auto const negativeRangeActive{splitMode ? Train->controlled->DynamicBrakeCtrlPos > 0.0 : Train->occupied->LocalBrakePosA > 0.0}; if (Train->ggJointCtrl.SubModel != nullptr && negativeRangeActive) { if (splitMode) @@ -153,7 +153,7 @@ void TTrain::OnCommand_mastercontrollerincrease(TTrain *Train, command_data cons } else { - Train->mvControlled->IncMainCtrl(1); + Train->controlled->IncMainCtrl(1); Train->m_mastercontrollerinuse = true; } } @@ -171,8 +171,8 @@ void TTrain::OnCommand_mastercontrollerincreasefast(TTrain *Train, command_data if (Command.action != GLFW_RELEASE) { // on press or hold - auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; - auto const negativeRangeActive{splitMode ? Train->mvControlled->DynamicBrakeCtrlPos > 0.0 : Train->mvOccupied->LocalBrakePosA > 0.0}; + auto const splitMode{Train->controlled->SplitEDPneumaticBrake}; + auto const negativeRangeActive{splitMode ? Train->controlled->DynamicBrakeCtrlPos > 0.0 : Train->occupied->LocalBrakePosA > 0.0}; if (Train->ggJointCtrl.SubModel != nullptr && negativeRangeActive) { if (splitMode) @@ -187,7 +187,7 @@ void TTrain::OnCommand_mastercontrollerincreasefast(TTrain *Train, command_data } else { - Train->mvControlled->IncMainCtrl(Train->mvControlled->MainCtrlPosNo); + Train->controlled->IncMainCtrl(Train->controlled->MainCtrlPosNo); Train->m_mastercontrollerinuse = true; } } @@ -205,8 +205,8 @@ void TTrain::OnCommand_mastercontrollerdecrease(TTrain *Train, command_data cons if (Command.action != GLFW_RELEASE) { // on press or hold - auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; - if (Train->ggJointCtrl.SubModel != nullptr && Train->mvControlled->IsMainCtrlNoPowerPos()) + auto const splitMode{Train->controlled->SplitEDPneumaticBrake}; + if (Train->ggJointCtrl.SubModel != nullptr && Train->controlled->IsMainCtrlNoPowerPos()) { // negative range of jointctrl: ED brake when split, otherwise pneumatic local brake if (splitMode) @@ -221,7 +221,7 @@ void TTrain::OnCommand_mastercontrollerdecrease(TTrain *Train, command_data cons } else { - Train->mvControlled->DecMainCtrl(1); + Train->controlled->DecMainCtrl(1); Train->m_mastercontrollerinuse = true; } } @@ -239,8 +239,8 @@ void TTrain::OnCommand_mastercontrollerdecreasefast(TTrain *Train, command_data if (Command.action != GLFW_RELEASE) { // on press or hold - auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; - if (Train->ggJointCtrl.SubModel != nullptr && Train->mvControlled->IsMainCtrlNoPowerPos()) + auto const splitMode{Train->controlled->SplitEDPneumaticBrake}; + if (Train->ggJointCtrl.SubModel != nullptr && Train->controlled->IsMainCtrlNoPowerPos()) { if (splitMode) { @@ -254,7 +254,7 @@ void TTrain::OnCommand_mastercontrollerdecreasefast(TTrain *Train, command_data } else { - Train->mvControlled->DecMainCtrl(Train->mvControlled->MainCtrlPowerPos()); + Train->controlled->DecMainCtrl(Train->controlled->MainCtrlPowerPos()); Train->m_mastercontrollerinuse = true; } } @@ -288,13 +288,13 @@ void TTrain::OnCommand_DynamicBrakeControllerIncrease(TTrain *Train, command_dat { return; } - if (false == Train->mvControlled->SplitEDPneumaticBrake) + if (false == Train->controlled->SplitEDPneumaticBrake) { return; } // step exactly one stop (1 / DBPN) per command, matching the discrete behaviour of jointctrl - Train->mvControlled->IncDynamicBrakeLevel(1.0f); + Train->controlled->IncDynamicBrakeLevel(1.0f); } void TTrain::OnCommand_DynamicBrakeControllerIncreaseFast(TTrain *Train, command_data const &Command) @@ -303,12 +303,12 @@ void TTrain::OnCommand_DynamicBrakeControllerIncreaseFast(TTrain *Train, command { return; } - if (false == Train->mvControlled->SplitEDPneumaticBrake) + if (false == Train->controlled->SplitEDPneumaticBrake) { return; } - Train->mvControlled->IncDynamicBrakeLevel(static_cast(Train->mvControlled->DynamicBrakeCtrlPosNo)); + Train->controlled->IncDynamicBrakeLevel(static_cast(Train->controlled->DynamicBrakeCtrlPosNo)); } void TTrain::OnCommand_DynamicBrakeControllerDecrease(TTrain *Train, command_data const &Command) @@ -317,13 +317,13 @@ void TTrain::OnCommand_DynamicBrakeControllerDecrease(TTrain *Train, command_dat { return; } - if (false == Train->mvControlled->SplitEDPneumaticBrake) + if (false == Train->controlled->SplitEDPneumaticBrake) { return; } // step exactly one stop (1 / DBPN) per command, matching the discrete behaviour of jointctrl - Train->mvControlled->DecDynamicBrakeLevel(1.0f); + Train->controlled->DecDynamicBrakeLevel(1.0f); } void TTrain::OnCommand_DynamicBrakeControllerDecreaseFast(TTrain *Train, command_data const &Command) @@ -332,12 +332,12 @@ void TTrain::OnCommand_DynamicBrakeControllerDecreaseFast(TTrain *Train, command { return; } - if (false == Train->mvControlled->SplitEDPneumaticBrake) + if (false == Train->controlled->SplitEDPneumaticBrake) { return; } - Train->mvControlled->DecDynamicBrakeLevel(static_cast(Train->mvControlled->DynamicBrakeCtrlPosNo)); + Train->controlled->DecDynamicBrakeLevel(static_cast(Train->controlled->DynamicBrakeCtrlPosNo)); } void TTrain::OnCommand_DynamicBrakeControllerSet(TTrain *Train, command_data const &Command) @@ -346,26 +346,26 @@ void TTrain::OnCommand_DynamicBrakeControllerSet(TTrain *Train, command_data con { return; } - if (false == Train->mvControlled->SplitEDPneumaticBrake) + if (false == Train->controlled->SplitEDPneumaticBrake) { return; } // when input source uses raw 0..1 value, snap to nearest DBPN step auto const target{std::clamp(Command.param1, 0.0, 1.0)}; - auto const stepCount{std::max(1, Train->mvControlled->DynamicBrakeCtrlPosNo)}; + auto const stepCount{std::max(1, Train->controlled->DynamicBrakeCtrlPosNo)}; auto const snapped{std::round(target * stepCount) / stepCount}; - Train->mvControlled->DynamicBrakeLevelSet(snapped); + Train->controlled->DynamicBrakeLevelSet(snapped); } void TTrain::OnCommand_secondcontrollerincrease(TTrain *Train, command_data const &Command) { - if (Train->mvControlled->EngineType == TEngineType::DieselElectric && true == Train->mvControlled->ShuntModeAllow && true == Train->mvControlled->ShuntMode) + if (Train->controlled->EngineType == TEngineType::DieselElectric && true == Train->controlled->ShuntModeAllow && true == Train->controlled->ShuntMode) { if (Command.action != GLFW_RELEASE) { - Train->mvControlled->AnPos = std::clamp(Train->mvControlled->AnPos + 0.025, 0.0, 1.0); + Train->controlled->AnPos = std::clamp(Train->controlled->AnPos + 0.025, 0.0, 1.0); } } else @@ -377,7 +377,7 @@ void TTrain::OnCommand_secondcontrollerincrease(TTrain *Train, command_data cons if (Command.action == GLFW_PRESS) { // activate on press - Train->mvControlled->IncScndCtrl(1); + Train->controlled->IncScndCtrl(1); } } // toggle control type @@ -385,7 +385,7 @@ void TTrain::OnCommand_secondcontrollerincrease(TTrain *Train, command_data cons { if (Command.action != GLFW_RELEASE) { - Train->mvControlled->IncScndCtrl(1); + Train->controlled->IncScndCtrl(1); } } // HACK: potentially animate push or pushtoggle control @@ -396,7 +396,7 @@ void TTrain::OnCommand_secondcontrollerincrease(TTrain *Train, command_data cons Train->ggScndCtrl.UpdateValue(Command.action == GLFW_RELEASE ? neutralposition : activeposition, Train->dsbSwitch); } // potentially animate tempomat button, unless the cruise control has its own - if (Train->ggScndCtrlButton.is_push() && Train->mvControlled->ScndCtrlPos <= 1 && false == Train->mvControlled->IsSpeedCtrlSeparate()) + if (Train->ggScndCtrlButton.is_push() && Train->controlled->ScndCtrlPos <= 1 && false == Train->controlled->IsSpeedCtrlSeparate()) { Train->ggScndCtrlButton.UpdateValue(Command.action == GLFW_RELEASE ? 0.f : 1.f, Train->dsbSwitch); } @@ -409,13 +409,13 @@ void TTrain::OnCommand_secondcontrollerincreasefast(TTrain *Train, command_data if (Command.action != GLFW_RELEASE) { // on press or hold - if (Train->mvControlled->EngineType == TEngineType::DieselElectric && true == Train->mvControlled->ShuntMode) + if (Train->controlled->EngineType == TEngineType::DieselElectric && true == Train->controlled->ShuntMode) { - Train->mvControlled->AnPos = 1.0; + Train->controlled->AnPos = 1.0; } else { - Train->mvControlled->IncScndCtrl(2); + Train->controlled->IncScndCtrl(2); } } } @@ -426,18 +426,18 @@ void TTrain::OnCommand_notchingrelaytoggle(TTrain *Train, command_data const &Co if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvOccupied->AutoRelayFlag) + if (false == Train->occupied->AutoRelayFlag) { // turn on - Train->mvOccupied->AutoRelaySwitch(true); + Train->occupied->AutoRelaySwitch(true); } else { // turn off - Train->mvOccupied->AutoRelaySwitch(false); + Train->occupied->AutoRelaySwitch(false); } // visual feedback - Train->ggAutoRelayButton.UpdateValue(Train->mvOccupied->AutoRelayFlag ? 1.f : 0.f, Train->dsbSwitch); + Train->ggAutoRelayButton.UpdateValue(Train->occupied->AutoRelayFlag ? 1.f : 0.f, Train->dsbSwitch); } } @@ -461,17 +461,17 @@ void TTrain::OnCommand_tempomattoggle(TTrain *Train, command_data const &Command return; } // glfw_press - if (false == Train->mvControlled->IsSpeedCtrlEngaged()) + if (false == Train->controlled->IsSpeedCtrlEngaged()) { // turn on if it's not active - Train->mvControlled->SpeedCtrlSwitch(true); + Train->controlled->SpeedCtrlSwitch(true); // visual feedback Train->ggScndCtrlButton.UpdateValue(1.0, Train->dsbSwitch); } else { // otherwise turn off - Train->mvControlled->SpeedCtrlSwitch(false); + Train->controlled->SpeedCtrlSwitch(false); // visual feedback if (Train->m_controlmapper.contains("tempomatoff_sw:")) { @@ -491,17 +491,17 @@ void TTrain::OnCommand_tempomattoggle(TTrain *Train, command_data const &Command return; } - if (false == Train->mvControlled->IsSpeedCtrlEngaged()) + if (false == Train->controlled->IsSpeedCtrlEngaged()) { // turn on - Train->mvControlled->SpeedCtrlSwitch(true); + Train->controlled->SpeedCtrlSwitch(true); // visual feedback Train->ggScndCtrlButton.UpdateValue(1.0, Train->dsbSwitch); } else { // turn off - Train->mvControlled->SpeedCtrlSwitch(false); + Train->controlled->SpeedCtrlSwitch(false); // visual feedback Train->ggScndCtrlButton.UpdateValue(0.0, Train->dsbSwitch); } @@ -516,13 +516,13 @@ void TTrain::OnCommand_distancecounteractivate(TTrain *Train, command_data const // visual feedback Train->ggDistanceCounterButton.UpdateValue(1.0, Train->dsbSwitch); // activate or start anew - if (Train->mvOccupied->isDoubleClickForMeasureNeeded) + if (Train->occupied->isDoubleClickForMeasureNeeded) { // handler tempomatu dla podwojnego kliku if (Train->trainLenghtMeasureTimer >= 0.f) // jesli zdazylismy w czasie sekundy Train->m_distancecounter = 0.f; // rozpoczynamy pomiar else - Train->trainLenghtMeasureTimer = Train->mvOccupied->DistanceCounterDoublePressPeriod; // odpalamy zegarek od nowa + Train->trainLenghtMeasureTimer = Train->occupied->DistanceCounterDoublePressPeriod; // odpalamy zegarek od nowa } else { @@ -568,11 +568,11 @@ void TTrain::OnCommand_mucurrentindicatorothersourceactivate(TTrain *Train, comm void TTrain::OnCommand_secondcontrollerdecrease(TTrain *Train, command_data const &Command) { - if (Train->mvControlled->EngineType == TEngineType::DieselElectric && true == Train->mvControlled->ShuntMode) + if (Train->controlled->EngineType == TEngineType::DieselElectric && true == Train->controlled->ShuntMode) { if (Command.action != GLFW_RELEASE) { - Train->mvControlled->AnPos = std::clamp(Train->mvControlled->AnPos - 0.025, 0.0, 1.0); + Train->controlled->AnPos = std::clamp(Train->controlled->AnPos - 0.025, 0.0, 1.0); } } else @@ -585,7 +585,7 @@ void TTrain::OnCommand_secondcontrollerdecrease(TTrain *Train, command_data cons if (true == Train->ggScndCtrl.is_toggle() && Command.action == GLFW_PRESS) { // activate on press - Train->mvControlled->DecScndCtrl(1); + Train->controlled->DecScndCtrl(1); } } // toggle control type @@ -593,7 +593,7 @@ void TTrain::OnCommand_secondcontrollerdecrease(TTrain *Train, command_data cons { if (Command.action != GLFW_RELEASE) { - Train->mvControlled->DecScndCtrl(1); + Train->controlled->DecScndCtrl(1); } } // HACK: potentially animate push or pushtoggle control @@ -604,7 +604,7 @@ void TTrain::OnCommand_secondcontrollerdecrease(TTrain *Train, command_data cons Train->ggScndCtrl.UpdateValue(Command.action == GLFW_RELEASE ? neutralposition : activeposition, Train->dsbSwitch); } // potentially animate tempomat button, unless the cruise control has its own - if (Train->ggScndCtrlButton.is_push() && Train->mvControlled->ScndCtrlPos <= 1 && false == Train->mvControlled->IsSpeedCtrlSeparate()) + if (Train->ggScndCtrlButton.is_push() && Train->controlled->ScndCtrlPos <= 1 && false == Train->controlled->IsSpeedCtrlSeparate()) { if (Train->m_controlmapper.contains("tempomatoff_sw:")) { @@ -624,13 +624,13 @@ void TTrain::OnCommand_secondcontrollerdecreasefast(TTrain *Train, command_data if (Command.action != GLFW_RELEASE) { // on press or hold - if (Train->mvControlled->EngineType == TEngineType::DieselElectric && true == Train->mvControlled->ShuntMode) + if (Train->controlled->EngineType == TEngineType::DieselElectric && true == Train->controlled->ShuntMode) { - Train->mvControlled->AnPos = 0.0; + Train->controlled->AnPos = 0.0; } else { - Train->mvControlled->DecScndCtrl(2); + Train->controlled->DecScndCtrl(2); } } } @@ -638,13 +638,13 @@ void TTrain::OnCommand_secondcontrollerdecreasefast(TTrain *Train, command_data void TTrain::OnCommand_secondcontrollerset(TTrain *Train, command_data const &Command) { - auto const targetposition{std::min(static_cast(Command.param1), Train->mvControlled->ScndCtrlPosNo)}; + auto const targetposition{std::min(static_cast(Command.param1), Train->controlled->ScndCtrlPosNo)}; // HACK: potentially animate push or pushtoggle control if (Train->ggScndCtrl.is_push()) { auto const activeposition{Train->ggScndCtrl.is_toggle() ? - (targetposition < Train->mvControlled->ScndCtrlPos ? 0.f : - targetposition > Train->mvControlled->ScndCtrlPos ? 1.f : + (targetposition < Train->controlled->ScndCtrlPos ? 0.f : + targetposition > Train->controlled->ScndCtrlPos ? 1.f : Train->ggScndCtrl.GetDesiredValue()) : // leave the control in its current position if it hits the limit targetposition == 0 ? 0.f : 1.f}; @@ -655,11 +655,11 @@ void TTrain::OnCommand_secondcontrollerset(TTrain *Train, command_data const &Co if (Command.action != GLFW_RELEASE) { // on press or hold - while (targetposition < Train->mvControlled->GetVirtualScndPos() && true == Train->mvControlled->DecScndCtrl(1)) + while (targetposition < Train->controlled->GetVirtualScndPos() && true == Train->controlled->DecScndCtrl(1)) { // all work is done in the header } - while (targetposition > Train->mvControlled->GetVirtualScndPos() && true == Train->mvControlled->IncScndCtrl(1)) + while (targetposition > Train->controlled->GetVirtualScndPos() && true == Train->controlled->IncScndCtrl(1)) { // all work is done in the header } diff --git a/vehicle/cab/couplingcommands.cpp b/vehicle/cab/couplingcommands.cpp index 4013fa0fd..6d4bfe1e9 100644 --- a/vehicle/cab/couplingcommands.cpp +++ b/vehicle/cab/couplingcommands.cpp @@ -38,7 +38,7 @@ http://mozilla.org/MPL/2.0/. #include "Console.h" #include "application/application.h" #include "rendering/renderer.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include #include #include @@ -212,10 +212,10 @@ void TTrain::OnCommand_departureannounce(TTrain *Train, command_data const &Comm if (Command.action == GLFW_PRESS) { // only reacting to press, so the sound can loop uninterrupted - if (false == Train->mvOccupied->DepartureSignal) + if (false == Train->occupied->DepartureSignal) { // turn on - Train->mvOccupied->signal_departure(true); + Train->occupied->signal_departure(true); // visual feedback Train->ggDepartureSignalButton.UpdateValue(1.0, Train->dsbSwitch); } @@ -223,7 +223,7 @@ void TTrain::OnCommand_departureannounce(TTrain *Train, command_data const &Comm else if (Command.action == GLFW_RELEASE) { // turn off - Train->mvOccupied->signal_departure(false); + Train->occupied->signal_departure(false); // visual feedback Train->ggDepartureSignalButton.UpdateValue(0.0, Train->dsbSwitch); } diff --git a/vehicle/cab/doorcommands.cpp b/vehicle/cab/doorcommands.cpp index 6205647c6..f801ad1dd 100644 --- a/vehicle/cab/doorcommands.cpp +++ b/vehicle/cab/doorcommands.cpp @@ -38,7 +38,7 @@ http://mozilla.org/MPL/2.0/. #include "Console.h" #include "application/application.h" #include "rendering/renderer.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include #include #include @@ -62,11 +62,11 @@ void TTrain::OnCommand_doorlocktoggle(TTrain *Train, command_data const &Command if (Command.action == GLFW_PRESS) { // only reacting to press, so the sound can loop uninterrupted - if (false == Train->mvOccupied->Doors.lock_enabled) + if (false == Train->occupied->Doors.lock_enabled) { // turn on // TODO: door lock command to send through consist - Train->mvOccupied->LockDoors(true); + Train->occupied->LockDoors(true); // visual feedback Train->ggDoorSignallingButton.UpdateValue(1.0, Train->dsbSwitch); } @@ -74,7 +74,7 @@ void TTrain::OnCommand_doorlocktoggle(TTrain *Train, command_data const &Command { // turn off // TODO: door lock command to send through consist - Train->mvOccupied->LockDoors(false); + Train->occupied->LockDoors(false); // visual feedback Train->ggDoorSignallingButton.UpdateValue(0.0, Train->dsbSwitch); } @@ -113,7 +113,7 @@ void TTrain::OnCommand_doortoggleleft(TTrain *Train, command_data const &Command if (true == (Train->ggDoorLeftButton.GetDesiredValue() > 0.5 || Train->ggDoorLeftOnButton.GetDesiredValue() > 0.5)) { // open - if (Train->mvOccupied->Doors.has_autowarning && Train->mvOccupied->DepartureSignal) + if (Train->occupied->Doors.has_autowarning && Train->occupied->DepartureSignal) { // complete closing the doors if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorLeftOffButton.SubModel == nullptr) @@ -163,7 +163,7 @@ void TTrain::OnCommand_doorpermitleft(TTrain *Train, command_data const &Command { return; } - if (false == Train->mvOccupied->Doors.permit_presets.empty()) + if (false == Train->occupied->Doors.permit_presets.empty()) { return; } @@ -176,18 +176,18 @@ void TTrain::OnCommand_doorpermitleft(TTrain *Train, command_data const &Command if (Train->ggDoorLeftPermitButton.is_push()) { // impulse switch - Train->mvOccupied->PermitDoors(side); + Train->occupied->PermitDoors(side); // visual feedback Train->ggDoorLeftPermitButton.UpdateValue(1.0, Train->dsbSwitch); // start potential timer for remote door control - Train->m_doorpermittimers[side] = Train->mvOccupied->DoorsOpenWithPermitAfter; + Train->m_doorpermittimers[side] = Train->occupied->DoorsOpenWithPermitAfter; } else { // two-state switch auto const newstate{!(Train->ggDoorLeftPermitButton.GetDesiredValue() > 0.5)}; - Train->mvOccupied->PermitDoors(side, newstate); + Train->occupied->PermitDoors(side, newstate); // visual feedback Train->ggDoorLeftPermitButton.UpdateValue(newstate ? 1.0 : 0.0, Train->dsbSwitch); } @@ -209,7 +209,7 @@ void TTrain::OnCommand_doorpermitright(TTrain *Train, command_data const &Comman { return; } - if (false == Train->mvOccupied->Doors.permit_presets.empty()) + if (false == Train->occupied->Doors.permit_presets.empty()) { return; } @@ -222,18 +222,18 @@ void TTrain::OnCommand_doorpermitright(TTrain *Train, command_data const &Comman if (Train->ggDoorRightPermitButton.type() == TGaugeType::push) { // impulse switch - Train->mvOccupied->PermitDoors(side); + Train->occupied->PermitDoors(side); // visual feedback Train->ggDoorRightPermitButton.UpdateValue(1.0, Train->dsbSwitch); // start potential timer for remote door control - Train->m_doorpermittimers[side] = Train->mvOccupied->DoorsOpenWithPermitAfter; + Train->m_doorpermittimers[side] = Train->occupied->DoorsOpenWithPermitAfter; } else { // two-state switch auto const newstate{!(Train->ggDoorRightPermitButton.GetDesiredValue() > 0.5)}; - Train->mvOccupied->PermitDoors(side, newstate); + Train->occupied->PermitDoors(side, newstate); // visual feedback Train->ggDoorRightPermitButton.UpdateValue(newstate ? 1.0 : 0.0, Train->dsbSwitch); } @@ -254,9 +254,9 @@ void TTrain::OnCommand_doorpermitpresetactivatenext(TTrain *Train, command_data if (Command.action == GLFW_PRESS) { - Train->mvOccupied->ChangeDoorPermitPreset(1); + Train->occupied->ChangeDoorPermitPreset(1); // visual feedback - Train->ggDoorPermitPresetButton.UpdateValue(static_cast(Train->mvOccupied->Doors.permit_preset), Train->dsbSwitch); + Train->ggDoorPermitPresetButton.UpdateValue(static_cast(Train->occupied->Doors.permit_preset), Train->dsbSwitch); } } @@ -266,9 +266,9 @@ void TTrain::OnCommand_doorpermitpresetactivateprevious(TTrain *Train, command_d if (Command.action == GLFW_PRESS) { - Train->mvOccupied->ChangeDoorPermitPreset(-1); + Train->occupied->ChangeDoorPermitPreset(-1); // visual feedback - Train->ggDoorPermitPresetButton.UpdateValue(static_cast(Train->mvOccupied->Doors.permit_preset), Train->dsbSwitch); + Train->ggDoorPermitPresetButton.UpdateValue(static_cast(Train->occupied->Doors.permit_preset), Train->dsbSwitch); } } @@ -276,7 +276,7 @@ void TTrain::OnCommand_dooropenleft(TTrain *Train, command_data const &Command) { - if (auto const remoteopencontrol{Train->mvOccupied->Doors.open_control == control_t::driver || Train->mvOccupied->Doors.open_control == control_t::mixed}; false == remoteopencontrol) + if (auto const remoteopencontrol{Train->occupied->Doors.open_control == control_t::driver || Train->occupied->Doors.open_control == control_t::mixed}; false == remoteopencontrol) { return; } @@ -289,7 +289,7 @@ void TTrain::OnCommand_dooropenleft(TTrain *Train, command_data const &Command) if (Command.action == GLFW_PRESS) { - Train->mvOccupied->OperateDoors(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right, true); + Train->occupied->OperateDoors(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right, true); // visual feedback if (Train->ggDoorLeftOnButton.SubModel != nullptr) { @@ -317,7 +317,7 @@ void TTrain::OnCommand_doorcloseleft(TTrain *Train, command_data const &Command) { - if (auto const remoteclosecontrol{Train->mvOccupied->Doors.close_control == control_t::driver || Train->mvOccupied->Doors.close_control == control_t::mixed}; false == remoteclosecontrol) + if (auto const remoteclosecontrol{Train->occupied->Doors.close_control == control_t::driver || Train->occupied->Doors.close_control == control_t::mixed}; false == remoteclosecontrol) { return; } @@ -331,15 +331,15 @@ void TTrain::OnCommand_doorcloseleft(TTrain *Train, command_data const &Command) if (Command.action == GLFW_PRESS) { - if (Train->mvOccupied->Doors.has_autowarning) + if (Train->occupied->Doors.has_autowarning) { // automatic departure signal delays actual door closing until the button is released - Train->mvOccupied->signal_departure(true); + Train->occupied->signal_departure(true); } else { // TODO: move door opening/closing to the update, so the switch animation doesn't hinge on door working - Train->mvOccupied->OperateDoors(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right, false); + Train->occupied->OperateDoors(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right, false); } // visual feedback if (Train->ggDoorLeftOffButton.SubModel != nullptr) @@ -356,12 +356,12 @@ void TTrain::OnCommand_doorcloseleft(TTrain *Train, command_data const &Command) else if (Command.action == GLFW_RELEASE) { - if (Train->mvOccupied->Doors.has_autowarning) + if (Train->occupied->Doors.has_autowarning) { // automatic departure signal delays actual door closing until the button is released - Train->mvOccupied->signal_departure(false); + Train->occupied->signal_departure(false); // now we can actually close the door - Train->mvOccupied->OperateDoors(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right, false); + Train->occupied->OperateDoors(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right, false); } // visual feedback // dedicated closing buttons are presumed to be impulse switches and return automatically to neutral position @@ -402,7 +402,7 @@ void TTrain::OnCommand_doortoggleright(TTrain *Train, command_data const &Comman if (true == (Train->ggDoorRightButton.GetDesiredValue() > 0.5 || Train->ggDoorRightOnButton.GetDesiredValue() > 0.5)) { // open - if (Train->mvOccupied->Doors.has_autowarning && Train->mvOccupied->DepartureSignal) + if (Train->occupied->Doors.has_autowarning && Train->occupied->DepartureSignal) { // complete closing the doors if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorRightOffButton.SubModel == nullptr) @@ -449,7 +449,7 @@ void TTrain::OnCommand_dooropenright(TTrain *Train, command_data const &Command) { - if (auto const remoteopencontrol{Train->mvOccupied->Doors.open_control == control_t::driver || Train->mvOccupied->Doors.open_control == control_t::mixed}; false == remoteopencontrol) + if (auto const remoteopencontrol{Train->occupied->Doors.open_control == control_t::driver || Train->occupied->Doors.open_control == control_t::mixed}; false == remoteopencontrol) { return; } @@ -463,7 +463,7 @@ void TTrain::OnCommand_dooropenright(TTrain *Train, command_data const &Command) if (Command.action == GLFW_PRESS) { - Train->mvOccupied->OperateDoors(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left, true); + Train->occupied->OperateDoors(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left, true); // visual feedback if (Train->ggDoorRightOnButton.SubModel != nullptr) { @@ -491,7 +491,7 @@ void TTrain::OnCommand_doorcloseright(TTrain *Train, command_data const &Command { - if (auto const remoteclosecontrol{Train->mvOccupied->Doors.close_control == control_t::driver || Train->mvOccupied->Doors.close_control == control_t::mixed}; false == remoteclosecontrol) + if (auto const remoteclosecontrol{Train->occupied->Doors.close_control == control_t::driver || Train->occupied->Doors.close_control == control_t::mixed}; false == remoteclosecontrol) { return; } @@ -505,14 +505,14 @@ void TTrain::OnCommand_doorcloseright(TTrain *Train, command_data const &Command if (Command.action == GLFW_PRESS) { - if (Train->mvOccupied->Doors.has_autowarning) + if (Train->occupied->Doors.has_autowarning) { // automatic departure signal delays actual door closing until the button is released - Train->mvOccupied->signal_departure(true); + Train->occupied->signal_departure(true); } else { - Train->mvOccupied->OperateDoors(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left, false); + Train->occupied->OperateDoors(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left, false); } // visual feedback if (Train->ggDoorRightOffButton.SubModel != nullptr) @@ -529,12 +529,12 @@ void TTrain::OnCommand_doorcloseright(TTrain *Train, command_data const &Command else if (Command.action == GLFW_RELEASE) { - if (Train->mvOccupied->Doors.has_autowarning) + if (Train->occupied->Doors.has_autowarning) { // automatic departure signal delays actual door closing until the button is released - Train->mvOccupied->signal_departure(false); + Train->occupied->signal_departure(false); // now we can actually close the door - Train->mvOccupied->OperateDoors(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left, false); + Train->occupied->OperateDoors(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left, false); } // visual feedback // dedicated closing buttons are presumed to be impulse switches and return automatically to neutral position @@ -547,7 +547,7 @@ void TTrain::OnCommand_dooropenall(TTrain *Train, command_data const &Command) { - if (auto const remoteopencontrol{Train->mvOccupied->Doors.open_control == control_t::driver || Train->mvOccupied->Doors.open_control == control_t::mixed}; false == remoteopencontrol) + if (auto const remoteopencontrol{Train->occupied->Doors.open_control == control_t::driver || Train->occupied->Doors.open_control == control_t::mixed}; false == remoteopencontrol) { return; } @@ -565,8 +565,8 @@ void TTrain::OnCommand_dooropenall(TTrain *Train, command_data const &Command) if (Command.action == GLFW_PRESS) { - Train->mvOccupied->OperateDoors(VehicleSide::right, true); - Train->mvOccupied->OperateDoors(VehicleSide::left, true); + Train->occupied->OperateDoors(VehicleSide::right, true); + Train->occupied->OperateDoors(VehicleSide::left, true); // visual feedback Train->ggDoorAllOnButton.UpdateValue(1.0, Train->dsbSwitch); } @@ -581,7 +581,7 @@ void TTrain::OnCommand_doorcloseall(TTrain *Train, command_data const &Command) { - if (auto const remoteclosecontrol{Train->mvOccupied->Doors.close_control == control_t::driver || Train->mvOccupied->Doors.close_control == control_t::mixed}; false == remoteclosecontrol) + if (auto const remoteclosecontrol{Train->occupied->Doors.close_control == control_t::driver || Train->occupied->Doors.close_control == control_t::mixed}; false == remoteclosecontrol) { return; } @@ -599,15 +599,15 @@ void TTrain::OnCommand_doorcloseall(TTrain *Train, command_data const &Command) if (Command.action == GLFW_PRESS) { - if (Train->mvOccupied->Doors.has_autowarning) + if (Train->occupied->Doors.has_autowarning) { - Train->mvOccupied->signal_departure(true); + Train->occupied->signal_departure(true); } if (Train->ggDoorAllOffButton.type() != TGaugeType::push_delayed) { // delays the action until the button is released - Train->mvOccupied->OperateDoors(VehicleSide::right, false); - Train->mvOccupied->OperateDoors(VehicleSide::left, false); + Train->occupied->OperateDoors(VehicleSide::right, false); + Train->occupied->OperateDoors(VehicleSide::left, false); } // visual feedback Train->ggDoorLeftButton.UpdateValue(0.0, Train->dsbSwitch); @@ -617,15 +617,15 @@ void TTrain::OnCommand_doorcloseall(TTrain *Train, command_data const &Command) } else if (Command.action == GLFW_RELEASE) { - if (Train->mvOccupied->Doors.has_autowarning) + if (Train->occupied->Doors.has_autowarning) { - Train->mvOccupied->signal_departure(false); + Train->occupied->signal_departure(false); } if (Train->ggDoorAllOffButton.type() == TGaugeType::push_delayed) { // now we can actually close the door - Train->mvOccupied->OperateDoors(VehicleSide::right, false); - Train->mvOccupied->OperateDoors(VehicleSide::left, false); + Train->occupied->OperateDoors(VehicleSide::right, false); + Train->occupied->OperateDoors(VehicleSide::left, false); } // visual feedback if (Train->ggDoorAllOffButton.SubModel) @@ -641,11 +641,11 @@ void TTrain::OnCommand_doorsteptoggle(TTrain *Train, command_data const &Command // effect if (false == Train->ggDoorStepButton.is_delayed()) { - Train->mvOccupied->PermitDoorStep(false == Train->mvOccupied->Doors.step_enabled); + Train->occupied->PermitDoorStep(false == Train->occupied->Doors.step_enabled); } // visual feedback auto const isactive{(Train->ggDoorStepButton.is_push() // always press push button - || Train->mvOccupied->Doors.step_enabled)}; // for toggle buttons indicate item state + || Train->occupied->Doors.step_enabled)}; // for toggle buttons indicate item state Train->ggDoorStepButton.UpdateValue(isactive ? 1 : 0); } else if (Command.action == GLFW_RELEASE) @@ -653,7 +653,7 @@ void TTrain::OnCommand_doorsteptoggle(TTrain *Train, command_data const &Command // effect if (Train->ggDoorStepButton.is_delayed()) { - Train->mvOccupied->PermitDoorStep(false == Train->mvOccupied->Doors.step_enabled); + Train->occupied->PermitDoorStep(false == Train->occupied->Doors.step_enabled); } // visual feedback if (Train->ggDoorStepButton.is_push()) @@ -668,7 +668,7 @@ void TTrain::OnCommand_doormodetoggle(TTrain *Train, command_data const &Command if (Command.action == GLFW_PRESS) { - Train->mvOccupied->ChangeDoorControlMode(false == Train->mvOccupied->Doors.remote_only); + Train->occupied->ChangeDoorControlMode(false == Train->occupied->Doors.remote_only); } } @@ -681,14 +681,14 @@ void TTrain::OnCommand_mirrorstoggle(TTrain *Train, command_data const &Command) } // only reacting to press, so the sound can loop uninterrupted - if (false == Train->mvOccupied->MirrorForbidden) + if (false == Train->occupied->MirrorForbidden) { // turn on - Train->mvOccupied->MirrorForbidden = true; + Train->occupied->MirrorForbidden = true; } else { // turn off - Train->mvOccupied->MirrorForbidden = false; + Train->occupied->MirrorForbidden = false; } } diff --git a/vehicle/cab/equipmentcommands.cpp b/vehicle/cab/equipmentcommands.cpp index fc0128325..4790ab17b 100644 --- a/vehicle/cab/equipmentcommands.cpp +++ b/vehicle/cab/equipmentcommands.cpp @@ -38,7 +38,7 @@ http://mozilla.org/MPL/2.0/. #include "Console.h" #include "application/application.h" #include "rendering/renderer.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include #include #include @@ -62,7 +62,7 @@ void TTrain::OnCommand_heatingtoggle(TTrain *Train, command_data const &Command) if (Command.action == GLFW_PRESS) { // ignore repeats so the switch doesn't flip back and forth if key is held down - if (false == Train->mvControlled->HeatingAllow) + if (false == Train->controlled->HeatingAllow) { // turn on OnCommand_heatingenable(Train, Command); @@ -73,7 +73,7 @@ void TTrain::OnCommand_heatingtoggle(TTrain *Train, command_data const &Command) OnCommand_heatingdisable(Train, Command); } } - else if (Command.action == GLFW_RELEASE && (Train->ggTrainHeatingButton.type() == TGaugeType::push || Train->mvOccupied->HeatingSwitchImpulse)) + else if (Command.action == GLFW_RELEASE && (Train->ggTrainHeatingButton.type() == TGaugeType::push || Train->occupied->HeatingSwitchImpulse)) { // impulse switch // visual feedback @@ -87,11 +87,11 @@ void TTrain::OnCommand_heatingenable(TTrain *Train, command_data const &Command) if (Command.action == GLFW_PRESS) { - Train->mvOccupied->HeatingSwitch(true); + Train->occupied->HeatingSwitch(true); // visual feedback Train->ggTrainHeatingButton.UpdateValue(1.0, Train->dsbSwitch); } - else if (Command.action == GLFW_RELEASE && Train->mvOccupied->HeatingSwitchImpulse) + else if (Command.action == GLFW_RELEASE && Train->occupied->HeatingSwitchImpulse) { // the switch springs back to the middle Train->ggTrainHeatingButton.UpdateValue(0.0, Train->dsbSwitch); @@ -104,10 +104,10 @@ void TTrain::OnCommand_heatingdisable(TTrain *Train, command_data const &Command if (Command.action == GLFW_PRESS) { - Train->mvOccupied->HeatingSwitch(false); + Train->occupied->HeatingSwitch(false); // visual feedback: an impulse switch is pushed the other way, down auto position{0.0}; - if (Train->mvOccupied->HeatingSwitchImpulse) + if (Train->occupied->HeatingSwitchImpulse) { position = -1.0; } @@ -117,7 +117,7 @@ void TTrain::OnCommand_heatingdisable(TTrain *Train, command_data const &Command } Train->ggTrainHeatingButton.UpdateValue(position, Train->dsbSwitch); } - else if (Command.action == GLFW_RELEASE && Train->mvOccupied->HeatingSwitchImpulse) + else if (Command.action == GLFW_RELEASE && Train->occupied->HeatingSwitchImpulse) { Train->ggTrainHeatingButton.UpdateValue(0.0, Train->dsbSwitch); } @@ -209,7 +209,7 @@ void TTrain::OnCommand_springbraketoggle(TTrain *Train, command_data const &Comm if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvOccupied->SpringBrake.Activate) + if (false == Train->occupied->SpringBrake.Activate) { // turn on OnCommand_springbrakeenable(Train, Command); @@ -234,7 +234,7 @@ void TTrain::OnCommand_springbrakeenable(TTrain *Train, command_data const &Comm if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpringBrakeActivate(true); + Train->occupied->SpringBrakeActivate(true); // visual feedback Train->ggSpringBrakeOnButton.UpdateValue(1.0, Train->dsbSwitch); Train->ggSpringBrakeOffButton.UpdateValue(0.0, Train->dsbSwitch); @@ -252,7 +252,7 @@ void TTrain::OnCommand_springbrakedisable(TTrain *Train, command_data const &Com if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpringBrakeActivate(false); + Train->occupied->SpringBrakeActivate(false); // visual feedback Train->ggSpringBrakeOffButton.UpdateValue(1.0, Train->dsbSwitch); Train->ggSpringBrakeOnButton.UpdateValue(0.0, Train->dsbSwitch); @@ -270,7 +270,7 @@ void TTrain::OnCommand_springbrakeshutofftoggle(TTrain *Train, command_data cons if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvOccupied->SpringBrake.ShuttOff) + if (false == Train->occupied->SpringBrake.ShuttOff) { // turn on OnCommand_springbrakeshutoffenable(Train, Command); @@ -288,7 +288,7 @@ void TTrain::OnCommand_springbrakeshutoffenable(TTrain *Train, command_data cons if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpringBrakeShutOff(true); + Train->occupied->SpringBrakeShutOff(true); } }; @@ -297,7 +297,7 @@ void TTrain::OnCommand_springbrakeshutoffdisable(TTrain *Train, command_data con if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpringBrakeShutOff(false); + Train->occupied->SpringBrakeShutOff(false); } }; @@ -311,7 +311,7 @@ void TTrain::OnCommand_springbrakerelease(TTrain *Train, command_data const &Com { return; } - Train->mvOccupied->SpringBrakeRelease(); + Train->occupied->SpringBrakeRelease(); } }; @@ -320,7 +320,7 @@ void TTrain::OnCommand_speedcontrolincrease(TTrain *Train, command_data const &C if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpeedCtrlInc(); + Train->occupied->SpeedCtrlInc(); // visual feedback Train->ggSpeedControlIncreaseButton.UpdateValue(1.0, Train->dsbSwitch); } @@ -337,7 +337,7 @@ void TTrain::OnCommand_speedcontroldecrease(TTrain *Train, command_data const &C if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpeedCtrlDec(); + Train->occupied->SpeedCtrlDec(); // visual feedback Train->ggSpeedControlDecreaseButton.UpdateValue(1.0, Train->dsbSwitch); } @@ -354,7 +354,7 @@ void TTrain::OnCommand_speedcontrolpowerincrease(TTrain *Train, command_data con if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpeedCtrlPowerInc(); + Train->occupied->SpeedCtrlPowerInc(); // visual feedback Train->ggSpeedControlPowerIncreaseButton.UpdateValue(1.0, Train->dsbSwitch); } @@ -371,7 +371,7 @@ void TTrain::OnCommand_speedcontrolpowerdecrease(TTrain *Train, command_data con if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpeedCtrlPowerDec(); + Train->occupied->SpeedCtrlPowerDec(); // visual feedback Train->ggSpeedControlPowerDecreaseButton.UpdateValue(1.0, Train->dsbSwitch); } @@ -391,7 +391,7 @@ void TTrain::OnCommand_speedcontrolbutton(TTrain *Train, command_data const &Com if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpeedCtrlButton(itemindex); + Train->occupied->SpeedCtrlButton(itemindex); // visual feedback Train->ggSpeedCtrlButtons[itemindex].UpdateValue(1.0, Train->dsbSwitch); } @@ -412,21 +412,21 @@ void TTrain::OnCommand_inverterenable(TTrain *Train, command_data const &Command if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; - auto const flag{CouplingSet::FromBits(Train->DynamicObject->MoverParameters->inductionMotor.inverterControlCouplings)}; - TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, flag); + bool kier = Train->DynamicObject->DirectionGet() * Train->occupied->CabOccupied > 0; + auto const flag{CouplingSet::FromBits(Train->DynamicObject->physics->inductionMotor.inverterControlCouplings)}; + TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->occupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, flag); while (p) { - if (p->MoverParameters->inductionMotor.traction.maxPower > 1) + if (p->physics->inductionMotor.traction.maxPower > 1) { - if (itemindex < p->MoverParameters->inductionMotor.inverterCount) + if (itemindex < p->physics->inductionMotor.inverterCount) { - p->MoverParameters->inductionMotor.inverters[itemindex].Activate = true; + p->physics->inductionMotor.inverters[itemindex].Activate = true; break; } else { - itemindex -= p->MoverParameters->inductionMotor.inverterCount; + itemindex -= p->physics->inductionMotor.inverterCount; } } p = kier ? p->Next(flag) : p->Prev(flag); @@ -451,21 +451,21 @@ void TTrain::OnCommand_inverterdisable(TTrain *Train, command_data const &Comman if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; - auto const flag{CouplingSet::FromBits(Train->DynamicObject->MoverParameters->inductionMotor.inverterControlCouplings)}; - TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, flag); + bool kier = Train->DynamicObject->DirectionGet() * Train->occupied->CabOccupied > 0; + auto const flag{CouplingSet::FromBits(Train->DynamicObject->physics->inductionMotor.inverterControlCouplings)}; + TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->occupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, flag); while (p) { - if (p->MoverParameters->inductionMotor.traction.maxPower > 1) + if (p->physics->inductionMotor.traction.maxPower > 1) { - if (itemindex < p->MoverParameters->inductionMotor.inverterCount) + if (itemindex < p->physics->inductionMotor.inverterCount) { - p->MoverParameters->inductionMotor.inverters[itemindex].Activate = false; + p->physics->inductionMotor.inverters[itemindex].Activate = false; break; } else { - itemindex -= p->MoverParameters->inductionMotor.inverterCount; + itemindex -= p->physics->inductionMotor.inverterCount; } } p = kier ? p->Next(flag) : p->Prev(flag); @@ -490,23 +490,23 @@ void TTrain::OnCommand_invertertoggle(TTrain *Train, command_data const &Command if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; - auto const flag{CouplingSet::FromBits(Train->DynamicObject->MoverParameters->inductionMotor.inverterControlCouplings)}; - TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, flag); + bool kier = Train->DynamicObject->DirectionGet() * Train->occupied->CabOccupied > 0; + auto const flag{CouplingSet::FromBits(Train->DynamicObject->physics->inductionMotor.inverterControlCouplings)}; + TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->occupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, flag); while (p) { - if (p->MoverParameters->inductionMotor.traction.maxPower > 1) + if (p->physics->inductionMotor.traction.maxPower > 1) { - if (itemindex < p->MoverParameters->inductionMotor.inverterCount) + if (itemindex < p->physics->inductionMotor.inverterCount) { - p->MoverParameters->inductionMotor.inverters[itemindex].Activate = !p->MoverParameters->inductionMotor.inverters[itemindex].Activate; + p->physics->inductionMotor.inverters[itemindex].Activate = !p->physics->inductionMotor.inverters[itemindex].Activate; // visual feedback - item.UpdateValue(p->MoverParameters->inductionMotor.inverters[itemindex].Activate ? 1.0 : 0.0, Train->dsbSwitch); + item.UpdateValue(p->physics->inductionMotor.inverters[itemindex].Activate ? 1.0 : 0.0, Train->dsbSwitch); break; } else { - itemindex -= p->MoverParameters->inductionMotor.inverterCount; + itemindex -= p->physics->inductionMotor.inverterCount; } } p = kier ? p->Next(flag) : p->Prev(flag); diff --git a/vehicle/cab/internal.h b/vehicle/cab/internal.h index 94bfcda9d..770c556bc 100644 --- a/vehicle/cab/internal.h +++ b/vehicle/cab/internal.h @@ -39,7 +39,7 @@ http://mozilla.org/MPL/2.0/. #include "Console.h" #include "application/application.h" #include "rendering/renderer.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include #include #include diff --git a/vehicle/cab/lightcommands.cpp b/vehicle/cab/lightcommands.cpp index 5089e3f85..b8125cb40 100644 --- a/vehicle/cab/lightcommands.cpp +++ b/vehicle/cab/lightcommands.cpp @@ -38,7 +38,7 @@ http://mozilla.org/MPL/2.0/. #include "Console.h" #include "application/application.h" #include "rendering/renderer.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include #include #include @@ -51,7 +51,7 @@ http://mozilla.org/MPL/2.0/. // the cab light switch (cablight_sw:) is bound to the light state and follows it by itself void TTrain::set_cab_light_from_lights_preset() { - auto const cablight{mvOccupied->LightsPresetCabLight(mvOccupied->LightsPos)}; + auto const cablight{occupied->LightsPresetCabLight(occupied->LightsPos)}; if (false == cablight.has_value()) { return; @@ -83,7 +83,7 @@ void TTrain::set_cab_light_from_lights_preset() void TTrain::OnCommand_lightspresetactivatenext(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->LightsPosNo == 0) + if (Train->occupied->LightsPosNo == 0) { // no preset selector return; @@ -94,11 +94,11 @@ void TTrain::OnCommand_lightspresetactivatenext(TTrain *Train, command_data cons return; } - if (Train->mvOccupied->LightsPos < Train->mvOccupied->LightsPosNo || true == Train->mvOccupied->LightsWrap) + if (Train->occupied->LightsPos < Train->occupied->LightsPosNo || true == Train->occupied->LightsWrap) { // active light preset is stored as value in range 1-LigthPosNo - auto const restartcycle{Train->mvOccupied->LightsPos >= Train->mvOccupied->LightsPosNo}; - Train->mvOccupied->LightsPos = false == restartcycle ? Train->mvOccupied->LightsPos + 1 : 1; // wrap mode + auto const restartcycle{Train->occupied->LightsPos >= Train->occupied->LightsPosNo}; + Train->occupied->LightsPos = false == restartcycle ? Train->occupied->LightsPos + 1 : 1; // wrap mode Train->Dynamic()->SetLights(); Train->set_cab_light_from_lights_preset(); @@ -107,13 +107,13 @@ void TTrain::OnCommand_lightspresetactivatenext(TTrain *Train, command_data cons { if (false == restartcycle) { - Train->ggLightsButton.UpdateValue(static_cast(Train->mvOccupied->LightsPos - 1), Train->dsbSwitch); + Train->ggLightsButton.UpdateValue(static_cast(Train->occupied->LightsPos - 1), Train->dsbSwitch); } else { // past the last position to the first one: a knob turning all the way round turns on rather than // back across all the positions, and the position reached sounds (eu07/maszyna#464) - Train->ggLightsButton.UpdateValueWrapped(static_cast(Train->mvOccupied->LightsPos - 1), true, Train->mvOccupied->LightsPosNo, Train->dsbSwitch); + Train->ggLightsButton.UpdateValueWrapped(static_cast(Train->occupied->LightsPos - 1), true, Train->occupied->LightsPosNo, Train->dsbSwitch); } } } @@ -122,7 +122,7 @@ void TTrain::OnCommand_lightspresetactivatenext(TTrain *Train, command_data cons void TTrain::OnCommand_lightspresetactivateprevious(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->LightsPosNo == 0) + if (Train->occupied->LightsPosNo == 0) { // no preset selector return; @@ -133,11 +133,11 @@ void TTrain::OnCommand_lightspresetactivateprevious(TTrain *Train, command_data return; } - if (Train->mvOccupied->LightsPos > 1 || true == Train->mvOccupied->LightsWrap) + if (Train->occupied->LightsPos > 1 || true == Train->occupied->LightsWrap) { // active light preset is stored as value in range 1-LigthPosNo - auto const restartcycle{Train->mvOccupied->LightsPos <= 1}; - Train->mvOccupied->LightsPos = false == restartcycle ? Train->mvOccupied->LightsPos - 1 : Train->mvOccupied->LightsPosNo; // wrap mode + auto const restartcycle{Train->occupied->LightsPos <= 1}; + Train->occupied->LightsPos = false == restartcycle ? Train->occupied->LightsPos - 1 : Train->occupied->LightsPosNo; // wrap mode Train->Dynamic()->SetLights(); Train->set_cab_light_from_lights_preset(); @@ -146,12 +146,12 @@ void TTrain::OnCommand_lightspresetactivateprevious(TTrain *Train, command_data { if (false == restartcycle) { - Train->ggLightsButton.UpdateValue(static_cast(Train->mvOccupied->LightsPos - 1), Train->dsbSwitch); + Train->ggLightsButton.UpdateValue(static_cast(Train->occupied->LightsPos - 1), Train->dsbSwitch); } else { // back past the first position to the last one, the same way (eu07/maszyna#464) - Train->ggLightsButton.UpdateValueWrapped(static_cast(Train->mvOccupied->LightsPos - 1), false, Train->mvOccupied->LightsPosNo, Train->dsbSwitch); + Train->ggLightsButton.UpdateValueWrapped(static_cast(Train->occupied->LightsPos - 1), false, Train->occupied->LightsPosNo, Train->dsbSwitch); } } } @@ -168,7 +168,7 @@ void TTrain::OnCommand_headlighttoggleleft(TTrain *Train, command_data const &Co if (Train->ggLeftEndLightButton.SubModel != nullptr || Train->ggLeftLightButton.SubModel == nullptr) { - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0) + if ((Train->occupied->iLights[vehicleend] & light::headlight_left) == 0) { // turn on OnCommand_headlightenableleft(Train, Command); @@ -180,13 +180,13 @@ void TTrain::OnCommand_headlighttoggleleft(TTrain *Train, command_data const &Co } } else { // if the light is controlled by 3-way switch, handle both headlight and redmarker - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0 && - (Train->mvOccupied->iLights[vehicleend] & light::redmarker_left) == 0) + if ((Train->occupied->iLights[vehicleend] & light::headlight_left) == 0 && + (Train->occupied->iLights[vehicleend] & light::redmarker_left) == 0) { // turn on OnCommand_headlightenableleft(Train, Command); } - else if (Train->mvOccupied->iLights[vehicleend] & light::headlight_left) + else if (Train->occupied->iLights[vehicleend] & light::headlight_left) { // switch to red OnCommand_redmarkerenableleft(Train, Command); @@ -203,16 +203,16 @@ void TTrain::OnCommand_headlighttoggleleft(TTrain *Train, command_data const &Co void TTrain::OnCommand_lightsset(TTrain *Train, command_data const &Command) { // set custom item in Lights inventory - Train->mvOccupied->Lights[VehicleEnd::front][17] = static_cast(Command.param1); - Train->mvOccupied->Lights[VehicleEnd::rear][17] = static_cast(Command.param2); - Train->mvOccupied->LightsPos = 18; // nasza custom pozycja + Train->occupied->Lights[VehicleEnd::front][17] = static_cast(Command.param1); + Train->occupied->Lights[VehicleEnd::rear][17] = static_cast(Command.param2); + Train->occupied->LightsPos = 18; // nasza custom pozycja Train->Dynamic()->SetLights(); } void TTrain::OnCommand_headlightenableleft(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { // lights are controlled by preset selector return; @@ -225,14 +225,14 @@ void TTrain::OnCommand_headlightenableleft(TTrain *Train, command_data const &Co // implementation auto const vehicleend{Train->cab_to_end()}; - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0) + if ((Train->occupied->iLights[vehicleend] & light::headlight_left) == 0) { - Train->mvOccupied->iLights[vehicleend] ^= light::headlight_left; + Train->occupied->iLights[vehicleend] ^= light::headlight_left; } // if the light is controlled by 3-way switch, disable marker light if (Train->ggLeftEndLightButton.SubModel == nullptr) { - Train->mvOccupied->iLights[vehicleend] &= ~light::redmarker_left; + Train->occupied->iLights[vehicleend] &= ~light::redmarker_left; } } } @@ -240,7 +240,7 @@ void TTrain::OnCommand_headlightenableleft(TTrain *Train, command_data const &Co void TTrain::OnCommand_headlightdisableleft(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { // lights are controlled by preset selector return; @@ -251,12 +251,12 @@ void TTrain::OnCommand_headlightdisableleft(TTrain *Train, command_data const &C // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleend{Train->cab_to_end()}; - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0) + if ((Train->occupied->iLights[vehicleend] & light::headlight_left) == 0) { return; } // already disabled - Train->mvOccupied->iLights[vehicleend] ^= light::headlight_left; + Train->occupied->iLights[vehicleend] ^= light::headlight_left; // visual feedback Train->ggLeftLightButton.UpdateValue(0.0, Train->dsbSwitch); } @@ -273,7 +273,7 @@ void TTrain::OnCommand_headlighttoggleright(TTrain *Train, command_data const &C if (Train->ggRightEndLightButton.SubModel != nullptr || Train->ggRightLightButton.SubModel == nullptr) { - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_right) == 0) + if ((Train->occupied->iLights[vehicleend] & light::headlight_right) == 0) { // turn on OnCommand_headlightenableright(Train, Command); @@ -285,13 +285,13 @@ void TTrain::OnCommand_headlighttoggleright(TTrain *Train, command_data const &C } } else { // if the light is controlled by 3-way switch, handle both headlight and redmarker - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_right) == 0 && - (Train->mvOccupied->iLights[vehicleend] & light::redmarker_right) == 0) + if ((Train->occupied->iLights[vehicleend] & light::headlight_right) == 0 && + (Train->occupied->iLights[vehicleend] & light::redmarker_right) == 0) { // turn on OnCommand_headlightenableright(Train, Command); } - else if (Train->mvOccupied->iLights[vehicleend] & light::headlight_right) + else if (Train->occupied->iLights[vehicleend] & light::headlight_right) { // switch to red OnCommand_redmarkerenableright(Train, Command); @@ -308,7 +308,7 @@ void TTrain::OnCommand_headlighttoggleright(TTrain *Train, command_data const &C void TTrain::OnCommand_headlightenableright(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { // lights are controlled by preset selector return; @@ -321,14 +321,14 @@ void TTrain::OnCommand_headlightenableright(TTrain *Train, command_data const &C // implementation auto const vehicleend{Train->cab_to_end()}; - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_right) == 0) + if ((Train->occupied->iLights[vehicleend] & light::headlight_right) == 0) { - Train->mvOccupied->iLights[vehicleend] ^= light::headlight_right; + Train->occupied->iLights[vehicleend] ^= light::headlight_right; } // if the light is controlled by 3-way switch, disable marker light if (Train->ggRightEndLightButton.SubModel == nullptr) { - Train->mvOccupied->iLights[vehicleend] &= ~light::redmarker_right; + Train->occupied->iLights[vehicleend] &= ~light::redmarker_right; } } } @@ -336,7 +336,7 @@ void TTrain::OnCommand_headlightenableright(TTrain *Train, command_data const &C void TTrain::OnCommand_headlightdisableright(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { // lights are controlled by preset selector return; @@ -347,12 +347,12 @@ void TTrain::OnCommand_headlightdisableright(TTrain *Train, command_data const & // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleend{Train->cab_to_end()}; - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_right) == 0) + if ((Train->occupied->iLights[vehicleend] & light::headlight_right) == 0) { return; } // already disabled - Train->mvOccupied->iLights[vehicleend] ^= light::headlight_right; + Train->occupied->iLights[vehicleend] ^= light::headlight_right; // visual feedback Train->ggRightLightButton.UpdateValue(0.0, Train->dsbSwitch); } @@ -366,7 +366,7 @@ void TTrain::OnCommand_headlighttoggleupper(TTrain *Train, command_data const &C if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_upper) == 0) + if ((Train->occupied->iLights[vehicleend] & light::headlight_upper) == 0) { // turn on OnCommand_headlightenableupper(Train, Command); @@ -382,7 +382,7 @@ void TTrain::OnCommand_headlighttoggleupper(TTrain *Train, command_data const &C void TTrain::OnCommand_headlightenableupper(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { // lights are controlled by preset selector return; @@ -393,12 +393,12 @@ void TTrain::OnCommand_headlightenableupper(TTrain *Train, command_data const &C // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleend{Train->cab_to_end()}; - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_upper) != 0) + if ((Train->occupied->iLights[vehicleend] & light::headlight_upper) != 0) { return; } // already enabled - Train->mvOccupied->iLights[vehicleend] ^= light::headlight_upper; + Train->occupied->iLights[vehicleend] ^= light::headlight_upper; // visual feedback Train->ggUpperLightButton.UpdateValue(1.0, Train->dsbSwitch); } @@ -407,7 +407,7 @@ void TTrain::OnCommand_headlightenableupper(TTrain *Train, command_data const &C void TTrain::OnCommand_headlightdisableupper(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { // lights are controlled by preset selector return; @@ -418,12 +418,12 @@ void TTrain::OnCommand_headlightdisableupper(TTrain *Train, command_data const & // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleend{Train->cab_to_end()}; - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_upper) == 0) + if ((Train->occupied->iLights[vehicleend] & light::headlight_upper) == 0) { return; } // already disabled - Train->mvOccupied->iLights[vehicleend] ^= light::headlight_upper; + Train->occupied->iLights[vehicleend] ^= light::headlight_upper; // visual feedback Train->ggUpperLightButton.UpdateValue(0.0, Train->dsbSwitch); } @@ -437,7 +437,7 @@ void TTrain::OnCommand_redmarkertoggleleft(TTrain *Train, command_data const &Co // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleend{Train->cab_to_end()}; - if ((Train->mvOccupied->iLights[vehicleend] & light::redmarker_left) == 0) + if ((Train->occupied->iLights[vehicleend] & light::redmarker_left) == 0) { // turn on OnCommand_redmarkerenableleft(Train, Command); @@ -453,7 +453,7 @@ void TTrain::OnCommand_redmarkertoggleleft(TTrain *Train, command_data const &Co void TTrain::OnCommand_redmarkerenableleft(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { // lights are controlled by preset selector return; @@ -464,12 +464,12 @@ void TTrain::OnCommand_redmarkerenableleft(TTrain *Train, command_data const &Co // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleend{Train->cab_to_end()}; - if ((Train->mvOccupied->iLights[vehicleend] & light::redmarker_left) != 0) + if ((Train->occupied->iLights[vehicleend] & light::redmarker_left) != 0) { return; } // already enabled - Train->mvOccupied->iLights[vehicleend] ^= light::redmarker_left; + Train->occupied->iLights[vehicleend] ^= light::redmarker_left; // visual feedback if (Train->ggLeftEndLightButton.SubModel != nullptr) { @@ -481,7 +481,7 @@ void TTrain::OnCommand_redmarkerenableleft(TTrain *Train, command_data const &Co // this is crude, but for now will do Train->ggLeftLightButton.UpdateValue(-1.0, Train->dsbSwitch); // if the light is controlled by 3-way switch, disable the headlight - Train->mvOccupied->iLights[vehicleend] &= ~light::headlight_left; + Train->occupied->iLights[vehicleend] &= ~light::headlight_left; } } } @@ -489,7 +489,7 @@ void TTrain::OnCommand_redmarkerenableleft(TTrain *Train, command_data const &Co void TTrain::OnCommand_redmarkerdisableleft(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { // lights are controlled by preset selector return; @@ -500,12 +500,12 @@ void TTrain::OnCommand_redmarkerdisableleft(TTrain *Train, command_data const &C // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleend{Train->cab_to_end()}; - if ((Train->mvOccupied->iLights[vehicleend] & light::redmarker_left) == 0) + if ((Train->occupied->iLights[vehicleend] & light::redmarker_left) == 0) { return; } // already disabled - Train->mvOccupied->iLights[vehicleend] ^= light::redmarker_left; + Train->occupied->iLights[vehicleend] ^= light::redmarker_left; // visual feedback if (Train->ggLeftEndLightButton.SubModel != nullptr) { @@ -528,7 +528,7 @@ void TTrain::OnCommand_redmarkertoggleright(TTrain *Train, command_data const &C // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleend{Train->cab_to_end()}; - if ((Train->mvOccupied->iLights[vehicleend] & light::redmarker_right) == 0) + if ((Train->occupied->iLights[vehicleend] & light::redmarker_right) == 0) { // turn on OnCommand_redmarkerenableright(Train, Command); @@ -544,7 +544,7 @@ void TTrain::OnCommand_redmarkertoggleright(TTrain *Train, command_data const &C void TTrain::OnCommand_redmarkerenableright(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { // lights are controlled by preset selector return; @@ -555,12 +555,12 @@ void TTrain::OnCommand_redmarkerenableright(TTrain *Train, command_data const &C // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleend{Train->cab_to_end()}; - if ((Train->mvOccupied->iLights[vehicleend] & light::redmarker_right) != 0) + if ((Train->occupied->iLights[vehicleend] & light::redmarker_right) != 0) { return; } // already enabled - Train->mvOccupied->iLights[vehicleend] ^= light::redmarker_right; + Train->occupied->iLights[vehicleend] ^= light::redmarker_right; // visual feedback if (Train->ggRightEndLightButton.SubModel != nullptr) { @@ -572,7 +572,7 @@ void TTrain::OnCommand_redmarkerenableright(TTrain *Train, command_data const &C // this is crude, but for now will do Train->ggRightLightButton.UpdateValue(-1.0, Train->dsbSwitch); // if the light is controlled by 3-way switch, disable the headlight - Train->mvOccupied->iLights[vehicleend] &= ~light::headlight_right; + Train->occupied->iLights[vehicleend] &= ~light::headlight_right; } } } @@ -580,7 +580,7 @@ void TTrain::OnCommand_redmarkerenableright(TTrain *Train, command_data const &C void TTrain::OnCommand_redmarkerdisableright(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { // lights are controlled by preset selector return; @@ -591,12 +591,12 @@ void TTrain::OnCommand_redmarkerdisableright(TTrain *Train, command_data const & // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleend{Train->cab_to_end()}; - if ((Train->mvOccupied->iLights[vehicleend] & light::redmarker_right) == 0) + if ((Train->occupied->iLights[vehicleend] & light::redmarker_right) == 0) { return; } // already disabled - Train->mvOccupied->iLights[vehicleend] ^= light::redmarker_right; + Train->occupied->iLights[vehicleend] ^= light::redmarker_right; // visual feedback if (Train->ggRightEndLightButton.SubModel != nullptr) { @@ -614,7 +614,7 @@ void TTrain::OnCommand_redmarkerdisableright(TTrain *Train, command_data const & void TTrain::OnCommand_headlighttogglerearleft(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { // lights are controlled by preset selector return; @@ -625,7 +625,7 @@ void TTrain::OnCommand_headlighttogglerearleft(TTrain *Train, command_data const // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; // only reacting to press, so the switch doesn't flip back and forth if key is held down - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_right) == 0) + if ((Train->occupied->iLights[vehicleotherend] & light::headlight_right) == 0) { OnCommand_headlightenablerearleft(Train, Command); } @@ -638,7 +638,7 @@ void TTrain::OnCommand_headlighttogglerearleft(TTrain *Train, command_data const void TTrain::OnCommand_headlightenablerearleft(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { // lights are controlled by preset selector return; @@ -648,10 +648,10 @@ void TTrain::OnCommand_headlightenablerearleft(TTrain *Train, command_data const { auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; // already enabled - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_right) == 0) + if ((Train->occupied->iLights[vehicleotherend] & light::headlight_right) == 0) { // turn on - Train->mvOccupied->iLights[vehicleotherend] ^= light::headlight_right; + Train->occupied->iLights[vehicleotherend] ^= light::headlight_right; // visual feedback Train->ggRearLeftLightButton.UpdateValue(1.0, Train->dsbSwitch); } @@ -660,7 +660,7 @@ void TTrain::OnCommand_headlightenablerearleft(TTrain *Train, command_data const void TTrain::OnCommand_headlightdisablerearleft(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { // lights are controlled by preset selector return; @@ -669,13 +669,13 @@ void TTrain::OnCommand_headlightdisablerearleft(TTrain *Train, command_data cons { auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; // already disabled - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_right) == 0) + if ((Train->occupied->iLights[vehicleotherend] & light::headlight_right) == 0) { return; } // turn off - Train->mvOccupied->iLights[vehicleotherend] ^= light::headlight_right; + Train->occupied->iLights[vehicleotherend] ^= light::headlight_right; // visual feedback Train->ggRearLeftLightButton.UpdateValue(0.0, Train->dsbSwitch); } @@ -688,7 +688,7 @@ void TTrain::OnCommand_headlighttogglerearright(TTrain *Train, command_data cons // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; // only reacting to press, so the switch doesn't flip back and forth if key is held down - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_left) == 0) + if ((Train->occupied->iLights[vehicleotherend] & light::headlight_left) == 0) { OnCommand_headlightenablerearright(Train, Command); } @@ -701,7 +701,7 @@ void TTrain::OnCommand_headlighttogglerearright(TTrain *Train, command_data cons void TTrain::OnCommand_headlightenablerearright(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { // lights are controlled by preset selector return; @@ -712,10 +712,10 @@ void TTrain::OnCommand_headlightenablerearright(TTrain *Train, command_data cons // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_left) == 0) + if ((Train->occupied->iLights[vehicleotherend] & light::headlight_left) == 0) { // turn on - Train->mvOccupied->iLights[vehicleotherend] ^= light::headlight_left; + Train->occupied->iLights[vehicleotherend] ^= light::headlight_left; // visual feedback Train->ggRearRightLightButton.UpdateValue(1.0, Train->dsbSwitch); } @@ -724,7 +724,7 @@ void TTrain::OnCommand_headlightenablerearright(TTrain *Train, command_data cons void TTrain::OnCommand_headlightdisablerearright(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { // lights are controlled by preset selector return; @@ -735,13 +735,13 @@ void TTrain::OnCommand_headlightdisablerearright(TTrain *Train, command_data con // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; // already disabled - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_left) == 0) + if ((Train->occupied->iLights[vehicleotherend] & light::headlight_left) == 0) { return; } // turn off - Train->mvOccupied->iLights[vehicleotherend] ^= light::headlight_left; + Train->occupied->iLights[vehicleotherend] ^= light::headlight_left; // visual feedback Train->ggRearRightLightButton.UpdateValue(0.0, Train->dsbSwitch); } @@ -750,7 +750,7 @@ void TTrain::OnCommand_headlightdisablerearright(TTrain *Train, command_data con void TTrain::OnCommand_headlighttogglerearupper(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { // lights are controlled by preset selector return; @@ -760,7 +760,7 @@ void TTrain::OnCommand_headlighttogglerearupper(TTrain *Train, command_data cons { // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_upper) == 0) + if ((Train->occupied->iLights[vehicleotherend] & light::headlight_upper) == 0) { OnCommand_headlightenablerearupper(Train, Command); } @@ -774,7 +774,7 @@ void TTrain::OnCommand_headlighttogglerearupper(TTrain *Train, command_data cons void TTrain::OnCommand_headlightenablerearupper(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { // lights are controlled by preset selector return; @@ -784,10 +784,10 @@ void TTrain::OnCommand_headlightenablerearupper(TTrain *Train, command_data cons { // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_upper) == 0) + if ((Train->occupied->iLights[vehicleotherend] & light::headlight_upper) == 0) { // turn on - Train->mvOccupied->iLights[vehicleotherend] ^= light::headlight_upper; + Train->occupied->iLights[vehicleotherend] ^= light::headlight_upper; // visual feedback Train->ggRearUpperLightButton.UpdateValue(1.0, Train->dsbSwitch); } @@ -797,7 +797,7 @@ void TTrain::OnCommand_headlightenablerearupper(TTrain *Train, command_data cons void TTrain::OnCommand_headlightdisablerearupper(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { // lights are controlled by preset selector return; @@ -808,13 +808,13 @@ void TTrain::OnCommand_headlightdisablerearupper(TTrain *Train, command_data con // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; // already disabled? - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_upper) == 0) + if ((Train->occupied->iLights[vehicleotherend] & light::headlight_upper) == 0) { return; } // turn off - Train->mvOccupied->iLights[vehicleotherend] ^= light::headlight_upper; + Train->occupied->iLights[vehicleotherend] ^= light::headlight_upper; // visual feedback Train->ggRearUpperLightButton.UpdateValue(0.0, Train->dsbSwitch); } @@ -822,14 +822,14 @@ void TTrain::OnCommand_headlightdisablerearupper(TTrain *Train, command_data con void TTrain::OnCommand_modernlightdimmerincrease(TTrain *Train, command_data const &Command) { - if (!Train->mvOccupied->enableModernDimmer) + if (!Train->occupied->enableModernDimmer) return; // if modern dimmer is disabled, skip entire command if (Command.action == GLFW_PRESS) { // update modern dimmer state - if (false == Train->mvOccupied->stepDimmerPosition(1)) + if (false == Train->occupied->stepDimmerPosition(1)) return; // już na maksimum i nie można cyklicznie - auto const dimPos = Train->mvOccupied->modernDimmerPosition; + auto const dimPos = Train->occupied->modernDimmerPosition; // update lightning // Train->Dynamic()->SetLights(); Train->Dynamic()->SetLightDimmings(); @@ -841,14 +841,14 @@ void TTrain::OnCommand_modernlightdimmerincrease(TTrain *Train, command_data con } void TTrain::OnCommand_modernlightdimmerdecrease(TTrain *Train, command_data const &Command) { - if (!Train->mvOccupied->enableModernDimmer) + if (!Train->occupied->enableModernDimmer) return; // jeśli dimmer jest wyłączony, olewamy if (Command.action == GLFW_PRESS) { - if (false == Train->mvOccupied->stepDimmerPosition(-1)) + if (false == Train->occupied->stepDimmerPosition(-1)) return; // już na minimum i nie można cyklicznie - auto const dimPos = Train->mvOccupied->modernDimmerPosition; + auto const dimPos = Train->occupied->modernDimmerPosition; // Train->Dynamic()->SetLights(); Train->Dynamic()->SetLightDimmings(); @@ -865,7 +865,7 @@ void TTrain::OnCommand_redmarkertogglerearleft(TTrain *Train, command_data const // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; // only reacting to press, so the switch doesn't flip back and forth if key is held down - if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_right) == 0) + if ((Train->occupied->iLights[vehicleotherend] & light::redmarker_right) == 0) { OnCommand_redmarkerenablerearleft(Train, Command); } @@ -879,7 +879,7 @@ void TTrain::OnCommand_redmarkertogglerearleft(TTrain *Train, command_data const void TTrain::OnCommand_redmarkerenablerearleft(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { // lights are controlled by preset selector return; @@ -889,10 +889,10 @@ void TTrain::OnCommand_redmarkerenablerearleft(TTrain *Train, command_data const { // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; - if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_right) == 0) + if ((Train->occupied->iLights[vehicleotherend] & light::redmarker_right) == 0) { // turn on - Train->mvOccupied->iLights[vehicleotherend] ^= light::redmarker_right; + Train->occupied->iLights[vehicleotherend] ^= light::redmarker_right; // visual feedback Train->ggRearLeftEndLightButton.UpdateValue(1.0, Train->dsbSwitch); } @@ -902,7 +902,7 @@ void TTrain::OnCommand_redmarkerenablerearleft(TTrain *Train, command_data const void TTrain::OnCommand_redmarkerdisablerearleft(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { // lights are controlled by preset selector return; @@ -912,12 +912,12 @@ void TTrain::OnCommand_redmarkerdisablerearleft(TTrain *Train, command_data cons { // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; - if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_right) == 0) + if ((Train->occupied->iLights[vehicleotherend] & light::redmarker_right) == 0) { return; } // turn off - Train->mvOccupied->iLights[vehicleotherend] ^= light::redmarker_right; + Train->occupied->iLights[vehicleotherend] ^= light::redmarker_right; // visual feedback Train->ggRearLeftEndLightButton.UpdateValue(0.0, Train->dsbSwitch); } @@ -926,7 +926,7 @@ void TTrain::OnCommand_redmarkerdisablerearleft(TTrain *Train, command_data cons void TTrain::OnCommand_redmarkertogglerearright(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { // lights are controlled by preset selector return; @@ -937,7 +937,7 @@ void TTrain::OnCommand_redmarkertogglerearright(TTrain *Train, command_data cons // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; // only reacting to press, so the switch doesn't flip back and forth if key is held down - if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_left) == 0) + if ((Train->occupied->iLights[vehicleotherend] & light::redmarker_left) == 0) { OnCommand_redmarkerenablerearright(Train, Command); } @@ -951,7 +951,7 @@ void TTrain::OnCommand_redmarkertogglerearright(TTrain *Train, command_data cons void TTrain::OnCommand_redmarkerenablerearright(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { // lights are controlled by preset selector return; @@ -961,10 +961,10 @@ void TTrain::OnCommand_redmarkerenablerearright(TTrain *Train, command_data cons { // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; - if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_left) == 0) + if ((Train->occupied->iLights[vehicleotherend] & light::redmarker_left) == 0) { // turn on - Train->mvOccupied->iLights[vehicleotherend] ^= light::redmarker_left; + Train->occupied->iLights[vehicleotherend] ^= light::redmarker_left; // visual feedback Train->ggRearRightEndLightButton.UpdateValue(1.0, Train->dsbSwitch); } @@ -974,7 +974,7 @@ void TTrain::OnCommand_redmarkerenablerearright(TTrain *Train, command_data cons void TTrain::OnCommand_redmarkerdisablerearright(TTrain *Train, command_data const &Command) { - if (Train->mvOccupied->LightsPosNo > 0) + if (Train->occupied->LightsPosNo > 0) { // lights are controlled by preset selector return; @@ -984,12 +984,12 @@ void TTrain::OnCommand_redmarkerdisablerearright(TTrain *Train, command_data con { // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; - if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_left) == 0) + if ((Train->occupied->iLights[vehicleotherend] & light::redmarker_left) == 0) { return; } // turn off - Train->mvOccupied->iLights[vehicleotherend] ^= light::redmarker_left; + Train->occupied->iLights[vehicleotherend] ^= light::redmarker_left; // visual feedback Train->ggRearRightEndLightButton.UpdateValue(0.0, Train->dsbSwitch); } @@ -1014,10 +1014,10 @@ void TTrain::OnCommand_redmarkerstoggle(TTrain * /*Train*/, command_data const & auto const lightset{light::redmarker_left | light::redmarker_right}; - vehicle->MoverParameters->iLights[CouplNr] = - false == TestFlag(vehicle->MoverParameters->iLights[CouplNr], lightset) ? - vehicle->MoverParameters->iLights[CouplNr] |= lightset : // turn signals on - vehicle->MoverParameters->iLights[CouplNr] ^= lightset; // turn signals off + vehicle->physics->iLights[CouplNr] = + false == TestFlag(vehicle->physics->iLights[CouplNr], lightset) ? + vehicle->physics->iLights[CouplNr] |= lightset : // turn signals on + vehicle->physics->iLights[CouplNr] ^= lightset; // turn signals off } } @@ -1039,21 +1039,21 @@ void TTrain::OnCommand_endsignalstoggle(TTrain * /*Train*/, command_data const & auto const lightset{light::rearendsignals}; - vehicle->MoverParameters->iLights[CouplNr] = - false == TestFlag(vehicle->MoverParameters->iLights[CouplNr], lightset) ? - vehicle->MoverParameters->iLights[CouplNr] |= lightset : // turn signals on - vehicle->MoverParameters->iLights[CouplNr] ^= lightset; // turn signals off + vehicle->physics->iLights[CouplNr] = + false == TestFlag(vehicle->physics->iLights[CouplNr], lightset) ? + vehicle->physics->iLights[CouplNr] |= lightset : // turn signals on + vehicle->physics->iLights[CouplNr] ^= lightset; // turn signals off } } void TTrain::OnCommand_headlightsdimtoggle(TTrain *Train, command_data const &Command) { - if (Train->DynamicObject->MoverParameters->enableModernDimmer) + if (Train->DynamicObject->physics->enableModernDimmer) return; if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Train->DynamicObject->MoverParameters->modernDimmerPosition == 0) + if (Train->DynamicObject->physics->modernDimmerPosition == 0) { // turn on OnCommand_headlightsdimenable(Train, Command); @@ -1069,7 +1069,7 @@ void TTrain::OnCommand_headlightsdimtoggle(TTrain *Train, command_data const &Co void TTrain::OnCommand_headlightsdimenable(TTrain *Train, command_data const &Command) { - if (Train->DynamicObject->MoverParameters->enableModernDimmer) + if (Train->DynamicObject->physics->enableModernDimmer) return; if (Command.action == GLFW_PRESS) { @@ -1089,7 +1089,7 @@ void TTrain::OnCommand_headlightsdimenable(TTrain *Train, command_data const &Co Train->DynamicObject->DimHeadlights = true; */ - Train->DynamicObject->MoverParameters->modernDimmerPosition = Train->DynamicObject->MoverParameters->clampDimmerPosition(1); // ustawiamy modern dimmer na flage przyciemnienia + Train->DynamicObject->physics->modernDimmerPosition = Train->DynamicObject->physics->clampDimmerPosition(1); // ustawiamy modern dimmer na flage przyciemnienia Train->DynamicObject->SetLightDimmings(); } } @@ -1097,7 +1097,7 @@ void TTrain::OnCommand_headlightsdimenable(TTrain *Train, command_data const &Co void TTrain::OnCommand_headlightsdimdisable(TTrain *Train, command_data const &Command) { - if (Train->DynamicObject->MoverParameters->enableModernDimmer) // nie wiem dlaczego to tak dziala ze jest odwrocona logika + if (Train->DynamicObject->physics->enableModernDimmer) // nie wiem dlaczego to tak dziala ze jest odwrocona logika return; if (Command.action == GLFW_PRESS) { @@ -1115,7 +1115,7 @@ void TTrain::OnCommand_headlightsdimdisable(TTrain *Train, command_data const &C Train->DynamicObject->DimHeadlights = false; */ - Train->DynamicObject->MoverParameters->modernDimmerPosition = 0; // ustawiamy modern dimmer na flage rozjasnienia + Train->DynamicObject->physics->modernDimmerPosition = 0; // ustawiamy modern dimmer na flage rozjasnienia Train->DynamicObject->SetLightDimmings(); } } @@ -1297,7 +1297,7 @@ void TTrain::OnCommand_compartmentlightstoggle(TTrain *Train, command_data const } // keep the switch from flipping back and forth if key is held down - if (false == Train->mvOccupied->CompartmentLights.is_active && false == Train->mvOccupied->CompartmentLights.is_enabled) + if (false == Train->occupied->CompartmentLights.is_active && false == Train->occupied->CompartmentLights.is_enabled) { // turn on OnCommand_compartmentlightsenable(Train, Command); @@ -1314,12 +1314,12 @@ void TTrain::OnCommand_compartmentlightsenable(TTrain *Train, command_data const if (Command.action == GLFW_PRESS) { - Train->mvOccupied->CompartmentLightsSwitch(true); + Train->occupied->CompartmentLightsSwitch(true); // withdraw the off request, unless a push type control in the cab withdraws it when released if (compartment_lights_switch::withdraws_other_request(Train->m_controlmapper.contains("compartmentlights_sw:"), Train->ggCompartmentLightsButton.is_toggle(), Train->m_controlmapper.contains("compartmentlightsoff_sw:"))) { - Train->mvOccupied->CompartmentLightsSwitchOff(false); + Train->occupied->CompartmentLightsSwitchOff(false); } // visual feedback if (Train->m_controlmapper.contains("compartmentlights_sw:")) @@ -1336,13 +1336,13 @@ void TTrain::OnCommand_compartmentlightsenable(TTrain *Train, command_data const if (Train->m_controlmapper.contains("compartmentlights_sw:") && Train->ggCompartmentLightsButton.type() == TGaugeType::push) { // return the switch to neutral position - Train->mvOccupied->CompartmentLightsSwitch(false); - Train->mvOccupied->CompartmentLightsSwitchOff(false); + Train->occupied->CompartmentLightsSwitch(false); + Train->occupied->CompartmentLightsSwitchOff(false); Train->ggCompartmentLightsButton.UpdateValue(0.5f); } if (Train->m_controlmapper.contains("compartmentlightson_sw:")) { - Train->mvOccupied->CompartmentLightsSwitch(false); + Train->occupied->CompartmentLightsSwitch(false); Train->ggCompartmentLightsOnButton.UpdateValue(0.0f, Train->dsbSwitch); } } @@ -1353,12 +1353,12 @@ void TTrain::OnCommand_compartmentlightsdisable(TTrain *Train, command_data cons if (Command.action == GLFW_PRESS) { - Train->mvOccupied->CompartmentLightsSwitchOff(true); + Train->occupied->CompartmentLightsSwitchOff(true); // withdraw the on request, unless a push type control in the cab withdraws it when released if (compartment_lights_switch::withdraws_other_request(Train->m_controlmapper.contains("compartmentlights_sw:"), Train->ggCompartmentLightsButton.is_toggle(), Train->m_controlmapper.contains("compartmentlightson_sw:"))) { - Train->mvOccupied->CompartmentLightsSwitch(false); + Train->occupied->CompartmentLightsSwitch(false); } // visual feedback if (Train->m_controlmapper.contains("compartmentlights_sw:")) @@ -1375,13 +1375,13 @@ void TTrain::OnCommand_compartmentlightsdisable(TTrain *Train, command_data cons if (Train->m_controlmapper.contains("compartmentlights_sw:") && Train->ggCompartmentLightsButton.type() == TGaugeType::push) { // return the switch to neutral position - Train->mvOccupied->CompartmentLightsSwitch(false); - Train->mvOccupied->CompartmentLightsSwitchOff(false); + Train->occupied->CompartmentLightsSwitch(false); + Train->occupied->CompartmentLightsSwitchOff(false); Train->ggCompartmentLightsButton.UpdateValue(0.5f); } if (Train->m_controlmapper.contains("compartmentlightsoff_sw:")) { - Train->mvOccupied->CompartmentLightsSwitchOff(false); + Train->occupied->CompartmentLightsSwitchOff(false); Train->ggCompartmentLightsOffButton.UpdateValue(0.0f, Train->dsbSwitch); } } diff --git a/vehicle/cab/pantographcommands.cpp b/vehicle/cab/pantographcommands.cpp index 2bf0f0d46..24a043416 100644 --- a/vehicle/cab/pantographcommands.cpp +++ b/vehicle/cab/pantographcommands.cpp @@ -38,7 +38,7 @@ http://mozilla.org/MPL/2.0/. #include "Console.h" #include "application/application.h" #include "rendering/renderer.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include #include #include @@ -59,7 +59,7 @@ void TTrain::OnCommand_pantographtogglefront(TTrain *Train, command_data const & if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const &pantograph{Train->mvPantographUnit->Pantographs[VehicleEnd::front]}; + auto const &pantograph{Train->pantographUnit->Pantographs[VehicleEnd::front]}; auto const state{pantograph.valve.is_enabled || pantograph.is_active}; // fallback for impulse switches if (state) { @@ -73,10 +73,10 @@ void TTrain::OnCommand_pantographtogglefront(TTrain *Train, command_data const & else if (Command.action == GLFW_RELEASE) { // impulse switches return automatically to neutral position - if (Train->mvOccupied->PantSwitchType == "impulse") + if (Train->occupied->PantSwitchType == "impulse") { auto const ismanual{Train->iCabn == 0}; - Train->mvOccupied->OperatePantographValve(VehicleEnd::front, operation_t::none, ismanual ? range_t::local : range_t::consist); + Train->occupied->OperatePantographValve(VehicleEnd::front, operation_t::none, ismanual ? range_t::local : range_t::consist); } } } @@ -93,7 +93,7 @@ void TTrain::OnCommand_pantographtogglerear(TTrain *Train, command_data const &C if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const &pantograph{Train->mvPantographUnit->Pantographs[VehicleEnd::rear]}; + auto const &pantograph{Train->pantographUnit->Pantographs[VehicleEnd::rear]}; auto const state{pantograph.valve.is_enabled || pantograph.is_active}; // fallback for impulse switches if (state) { @@ -107,10 +107,10 @@ void TTrain::OnCommand_pantographtogglerear(TTrain *Train, command_data const &C else if (Command.action == GLFW_RELEASE) { // impulse switches return automatically to neutral position - if (Train->mvOccupied->PantSwitchType == "impulse") + if (Train->occupied->PantSwitchType == "impulse") { auto const ismanual{Train->iCabn == 0}; - Train->mvOccupied->OperatePantographValve(VehicleEnd::rear, operation_t::none, ismanual ? range_t::local : range_t::consist); + Train->occupied->OperatePantographValve(VehicleEnd::rear, operation_t::none, ismanual ? range_t::local : range_t::consist); } } } @@ -134,7 +134,7 @@ void TTrain::OnCommand_pantographraisefront(TTrain *Train, command_data const &C // only reacting to press, so the switch doesn't flip back and forth if key is held down // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers auto const ismanual{Train->iCabn == 0}; - Train->mvOccupied->OperatePantographValve(VehicleEnd::front, Train->mvOccupied->PantSwitchType == "impulse" ? operation_t::enable_on : operation_t::enable, + Train->occupied->OperatePantographValve(VehicleEnd::front, Train->occupied->PantSwitchType == "impulse" ? operation_t::enable_on : operation_t::enable, ismanual ? range_t::local : range_t::consist); } else if (Command.action == GLFW_RELEASE) @@ -163,7 +163,7 @@ void TTrain::OnCommand_pantographraiserear(TTrain *Train, command_data const &Co // only reacting to press, so the switch doesn't flip back and forth if key is held down // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers auto const ismanual{Train->iCabn == 0}; - Train->mvOccupied->OperatePantographValve(VehicleEnd::rear, Train->mvOccupied->PantSwitchType == "impulse" ? operation_t::enable_on : operation_t::enable, + Train->occupied->OperatePantographValve(VehicleEnd::rear, Train->occupied->PantSwitchType == "impulse" ? operation_t::enable_on : operation_t::enable, ismanual ? range_t::local : range_t::consist); } else if (Command.action == GLFW_RELEASE) @@ -182,7 +182,7 @@ void TTrain::OnCommand_pantographlowerfront(TTrain *Train, command_data const &C return; } // prevent operation without submodel outside of engine compartment - if (Train->iCabn != 0 && false == Train->m_controlmapper.contains(Train->mvOccupied->PantSwitchType == "impulse" ? "pantfrontoff_sw:" : "pantfront_sw:")) + if (Train->iCabn != 0 && false == Train->m_controlmapper.contains(Train->occupied->PantSwitchType == "impulse" ? "pantfrontoff_sw:" : "pantfront_sw:")) { return; } @@ -192,7 +192,7 @@ void TTrain::OnCommand_pantographlowerfront(TTrain *Train, command_data const &C // only reacting to press, so the switch doesn't flip back and forth if key is held down // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers auto const ismanual{Train->iCabn == 0}; - Train->mvOccupied->OperatePantographValve(VehicleEnd::front, Train->mvOccupied->PantSwitchType == "impulse" ? operation_t::disable_on : operation_t::disable, + Train->occupied->OperatePantographValve(VehicleEnd::front, Train->occupied->PantSwitchType == "impulse" ? operation_t::disable_on : operation_t::disable, ismanual ? range_t::local : range_t::consist); } else if (Command.action == GLFW_RELEASE) @@ -211,7 +211,7 @@ void TTrain::OnCommand_pantographlowerrear(TTrain *Train, command_data const &Co return; } - if (Train->iCabn != 0 && false == Train->m_controlmapper.contains(Train->mvOccupied->PantSwitchType == "impulse" ? "pantrearoff_sw:" : "pantrear_sw:")) + if (Train->iCabn != 0 && false == Train->m_controlmapper.contains(Train->occupied->PantSwitchType == "impulse" ? "pantrearoff_sw:" : "pantrear_sw:")) { return; } @@ -221,7 +221,7 @@ void TTrain::OnCommand_pantographlowerrear(TTrain *Train, command_data const &Co // only reacting to press, so the switch doesn't flip back and forth if key is held down // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers auto const ismanual{Train->iCabn == 0}; - Train->mvOccupied->OperatePantographValve(VehicleEnd::rear, Train->mvOccupied->PantSwitchType == "impulse" ? operation_t::disable_on : operation_t::disable, + Train->occupied->OperatePantographValve(VehicleEnd::rear, Train->occupied->PantSwitchType == "impulse" ? operation_t::disable_on : operation_t::disable, ismanual ? range_t::local : range_t::consist); } else if (Command.action == GLFW_RELEASE) @@ -254,15 +254,15 @@ void TTrain::OnCommand_pantographlowerall(TTrain *Train, command_data const &Com // two-state switch, only cares about press events if (Command.action == GLFW_PRESS) { - Train->mvPantographUnit->DropAllPantographs(false == Train->mvPantographUnit->PantAllDown); + Train->pantographUnit->DropAllPantographs(false == Train->pantographUnit->PantAllDown); // visual feedback - Train->ggPantAllDownButton.UpdateValue(Train->mvPantographUnit->PantAllDown ? 1.0 : 0.0, Train->dsbSwitch); + Train->ggPantAllDownButton.UpdateValue(Train->pantographUnit->PantAllDown ? 1.0 : 0.0, Train->dsbSwitch); } } else { // impulse switch - Train->mvControlled->DropAllPantographs(Command.action == GLFW_PRESS); + Train->controlled->DropAllPantographs(Command.action == GLFW_PRESS); // visual feedback Train->ggPantAllDownButton.UpdateValue(Command.action == GLFW_PRESS ? 1.0 : 0.0, Train->dsbSwitch); } @@ -315,7 +315,7 @@ void TTrain::OnCommand_pantographtoggleselected(TTrain *Train, command_data cons Train->change_pantograph_selection(-1); // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const state{Train->mvPantographUnit->PantsValve.is_enabled || Train->mvPantographUnit->PantsValve.is_active}; // fallback for impulse switches + auto const state{Train->pantographUnit->PantsValve.is_enabled || Train->pantographUnit->PantsValve.is_active}; // fallback for impulse switches if (state) { OnCommand_pantographlowerselected(Train, Command); @@ -333,13 +333,13 @@ void TTrain::OnCommand_pantographtoggleselected(TTrain *Train, command_data cons // two buttons setup if (Train->ggPantSelectedButton.type() != TGaugeType::toggle) { - Train->mvOccupied->OperatePantographsValve(operation_t::enable_off); + Train->occupied->OperatePantographsValve(operation_t::enable_off); // visual feedback Train->ggPantSelectedButton.UpdateValue(0.0, Train->dsbSwitch); } if (Train->ggPantSelectedDownButton.type() != TGaugeType::toggle) { - Train->mvOccupied->OperatePantographsValve(operation_t::disable_off); + Train->occupied->OperatePantographsValve(operation_t::disable_off); // visual feedback Train->ggPantSelectedDownButton.UpdateValue(0.0, Train->dsbSwitch); } @@ -350,7 +350,7 @@ void TTrain::OnCommand_pantographtoggleselected(TTrain *Train, command_data cons { // special case, just one impulse switch controlling both states // with neutral position mid-way - Train->mvOccupied->OperatePantographsValve(operation_t::none); + Train->occupied->OperatePantographsValve(operation_t::none); // visual feedback Train->ggPantSelectedButton.UpdateValue(0.5, Train->dsbSwitch); } @@ -369,7 +369,7 @@ void TTrain::OnCommand_pantographraiseselected(TTrain *Train, command_data const if (Command.action == GLFW_PRESS) { // raise selected - Train->mvOccupied->OperatePantographsValve(Train->ggPantSelectedButton.type() != TGaugeType::toggle ? operation_t::enable_on : operation_t::enable); + Train->occupied->OperatePantographsValve(Train->ggPantSelectedButton.type() != TGaugeType::toggle ? operation_t::enable_on : operation_t::enable); // visual feedback Train->ggPantSelectedButton.UpdateValue(1.0, Train->dsbSwitch); } @@ -391,7 +391,7 @@ void TTrain::OnCommand_pantographlowerselected(TTrain *Train, command_data const if (Command.action == GLFW_PRESS) { // lower selected - Train->mvOccupied->OperatePantographsValve(Train->ggPantSelectedDownButton.type() != TGaugeType::toggle ? operation_t::disable_on : operation_t::disable); + Train->occupied->OperatePantographsValve(Train->ggPantSelectedDownButton.type() != TGaugeType::toggle ? operation_t::disable_on : operation_t::disable); // visual feedback if (Train->m_controlmapper.contains("pantselectedoff_sw:")) { @@ -415,23 +415,23 @@ void TTrain::update_pantograph_valves() { using enum operation_t; - auto const &presets{mvOccupied->PantsPreset.first}; - auto const &selection{mvOccupied->PantsPreset.second[cab_to_end()]}; + auto const &presets{occupied->PantsPreset.first}; + auto const &selection{occupied->PantsPreset.second[cab_to_end()]}; auto const preset{presets[selection] - '0'}; auto const swapends{cab_to_end() != VehicleEnd::front}; // check desired states for both pantographs; value: whether the pantograph should be raised auto const frontstate{preset & (swapends ? 2 : 1)}; auto const rearstate{preset & (swapends ? 1 : 2)}; - mvOccupied->OperatePantographValve(VehicleEnd::front, frontstate ? enable : disable); - mvOccupied->OperatePantographValve(VehicleEnd::rear, rearstate ? enable : disable); + occupied->OperatePantographValve(VehicleEnd::front, frontstate ? enable : disable); + occupied->OperatePantographValve(VehicleEnd::rear, rearstate ? enable : disable); } void TTrain::change_pantograph_selection(int const Change) { - auto const &presets{mvOccupied->PantsPreset.first}; - auto &selection{mvOccupied->PantsPreset.second[cab_to_end()]}; + auto const &presets{occupied->PantsPreset.first}; + auto &selection{occupied->PantsPreset.second[cab_to_end()]}; auto const initialstate{selection}; selection = std::clamp(selection + Change, 0, std::max(static_cast(presets.size() - 1), 0)); @@ -500,8 +500,8 @@ void TTrain::OnCommand_pantographvalvesoff(TTrain *Train, command_data const &Co if (Command.action == GLFW_PRESS) { // implement action - Train->mvOccupied->OperatePantographValve(VehicleEnd::front, operation_t::disable); - Train->mvOccupied->OperatePantographValve(VehicleEnd::rear, operation_t::disable); + Train->occupied->OperatePantographValve(VehicleEnd::front, operation_t::disable); + Train->occupied->OperatePantographValve(VehicleEnd::rear, operation_t::disable); // visual feedback if (hasSeparateSwitches) Train->ggPantValvesOff.UpdateValue(1.0, Train->dsbSwitch); @@ -525,7 +525,7 @@ void TTrain::OnCommand_pantographcompressorvalvetoggle(TTrain *Train, command_da if (Command.action == GLFW_PRESS) { // only react to press - if (Train->mvControlled->bPantKurek3 == false) + if (Train->controlled->bPantKurek3 == false) { // connect pantographs with primary tank OnCommand_pantographcompressorvalveenable(Train, Command); @@ -542,7 +542,7 @@ void TTrain::OnCommand_pantographcompressorvalveenable(TTrain *Train, command_da { - if (auto const valveispresent{Train->ggPantCompressorValve.SubModel != nullptr || (Train->mvOccupied == Train->mvPantographUnit && Train->iCabn == 0)}; false == valveispresent) + if (auto const valveispresent{Train->ggPantCompressorValve.SubModel != nullptr || (Train->occupied == Train->pantographUnit && Train->iCabn == 0)}; false == valveispresent) { // tylko w maszynowym, unless actual device is present return; @@ -552,7 +552,7 @@ void TTrain::OnCommand_pantographcompressorvalveenable(TTrain *Train, command_da { // only react to press // connect pantographs with primary tank - Train->mvControlled->bPantKurek3 = true; + Train->controlled->bPantKurek3 = true; // visual feedback: Train->ggPantCompressorValve.UpdateValue(0.0); } @@ -562,7 +562,7 @@ void TTrain::OnCommand_pantographcompressorvalvedisable(TTrain *Train, command_d { - if (auto const valveispresent{Train->ggPantCompressorValve.SubModel != nullptr || (Train->mvOccupied == Train->mvPantographUnit && Train->iCabn == 0)}; false == valveispresent) + if (auto const valveispresent{Train->ggPantCompressorValve.SubModel != nullptr || (Train->occupied == Train->pantographUnit && Train->iCabn == 0)}; false == valveispresent) { // tylko w maszynowym, unless actual device is present return; @@ -572,7 +572,7 @@ void TTrain::OnCommand_pantographcompressorvalvedisable(TTrain *Train, command_d { // only react to press // connect pantograps with pantograph compressor - Train->mvControlled->bPantKurek3 = false; + Train->controlled->bPantKurek3 = false; // visual feedback: Train->ggPantCompressorValve.UpdateValue(1.0); } @@ -582,7 +582,7 @@ void TTrain::OnCommand_pantographcompressoractivate(TTrain *Train, command_data { // tylko w maszynowym, unless actual device is present - if (auto const switchispresent{Train->m_controlmapper.contains("pantcompressor_sw:") || (Train->mvOccupied == Train->mvPantographUnit && Train->iCabn == 0)}; false == switchispresent) + if (auto const switchispresent{Train->m_controlmapper.contains("pantcompressor_sw:") || (Train->occupied == Train->pantographUnit && Train->iCabn == 0)}; false == switchispresent) { return; } @@ -590,10 +590,10 @@ void TTrain::OnCommand_pantographcompressoractivate(TTrain *Train, command_data if (Command.action != GLFW_RELEASE) { // press or hold to activate - if (Train->mvPantographUnit->PantPress < 4.8 && true == Train->mvPantographUnit->Power24vIsAvailable) + if (Train->pantographUnit->PantPress < 4.8 && true == Train->pantographUnit->Power24vIsAvailable) { // needs live power source and low enough pressure to work - Train->mvPantographUnit->PantCompFlag = true; + Train->pantographUnit->PantCompFlag = true; } // visual feedback Train->ggPantCompressorButton.UpdateValue(1.0); @@ -601,7 +601,7 @@ void TTrain::OnCommand_pantographcompressoractivate(TTrain *Train, command_data else { // release to disable - Train->mvPantographUnit->PantCompFlag = false; + Train->pantographUnit->PantCompFlag = false; // visual feedback Train->ggPantCompressorButton.UpdateValue(0.0); } diff --git a/vehicle/cab/powercommands.cpp b/vehicle/cab/powercommands.cpp index d9f9576d1..dc4dc14ff 100644 --- a/vehicle/cab/powercommands.cpp +++ b/vehicle/cab/powercommands.cpp @@ -38,7 +38,7 @@ http://mozilla.org/MPL/2.0/. #include "Console.h" #include "application/application.h" #include "rendering/renderer.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include #include #include @@ -131,7 +131,7 @@ void TTrain::OnCommand_linebreakeropen(TTrain *Train, command_data const &Comman { Train->ggMainButton.UpdateValue(0.0, Train->dsbSwitch); } - else if (Train->ggMainOnButton.SubModel != nullptr && false == Train->mvControlled->MainCircuitOpensWithStarterOnly()) + else if (Train->ggMainOnButton.SubModel != nullptr && false == Train->controlled->MainCircuitOpensWithStarterOnly()) { // NOTE: legacy behaviour, for vehicles equipped only with impulse close switch // it doesn't make any real sense to animate this one, but some people can't get over how there's no visual reaction to their keypress @@ -147,10 +147,10 @@ void TTrain::OnCommand_linebreakeropen(TTrain *Train, command_data const &Comman return; } // already in the desired state - if (true == Train->mvControlled->MainSwitch(false, Train->mvControlled->MainSwitchRange())) + if (true == Train->controlled->MainSwitch(false, Train->controlled->MainSwitchRange())) { Train->m_linebreakerstate = linebreaker::state::open; - if (Train->mvControlled->MainSwitchRange() != range_t::local) + if (Train->controlled->MainSwitchRange() != range_t::local) { // the engines of the vehicles in multiple stopped along: their two-state switches go off too, left on // they'd start them again after the delay @@ -232,10 +232,10 @@ void TTrain::OnCommand_linebreakerclose(TTrain *Train, command_data const &Comma // we don't need to start the diesel twice, but the other types (with impulse switch setup) still need to be launched // NOTE: this behaviour should depend on MainOnButton presence and type_delayed // TODO: change it when/if vehicle definition files get their proper switch types - if (Train->m_linebreakerstate == linebreaker::state::closing && Train->mvControlled->EngineType == TEngineType::ElectricSeriesMotor) + if (Train->m_linebreakerstate == linebreaker::state::closing && Train->controlled->EngineType == TEngineType::ElectricSeriesMotor) { // try to finalize state change of the line breaker, set the state based on the outcome - Train->m_linebreakerstate = Train->mvControlled->MainSwitch(true, Train->mvControlled->MainSwitchRange()) ? linebreaker::state::closed : linebreaker::state::open; + Train->m_linebreakerstate = Train->controlled->MainSwitch(true, Train->controlled->MainSwitchRange()) ? linebreaker::state::closed : linebreaker::state::open; } // on button release reset the closing timer Train->fMainRelayTimer = 0.0f; @@ -272,9 +272,9 @@ void release_remote_linebreaker(TTrain::remote_linebreaker &Controls, std::optio } // namespace -TMoverParameters *TTrain::remote_engine(std::size_t const Index) const +physics::Vehicle *TTrain::remote_engine(std::size_t const Index) const { - return engine_start::engine(*mvOccupied, *mvControlled, static_cast(Index) + 2); + return engine_start::engine(*occupied, *controlled, static_cast(Index) + 2); } void TTrain::OnCommand_linebreakertoggleremote(TTrain *Train, command_data const &Command) @@ -403,13 +403,13 @@ void TTrain::OnCommand_motorconnectorsopen(TTrain *Train, command_data const &Co if (Command.action == GLFW_PRESS) { // button works while it's held down but we can ignore repeats - if (false == Train->mvControlled->StLinSwitchOff) + if (false == Train->controlled->StLinSwitchOff) { // open the connectors // visual feedback Train->ggStLinOffButton.UpdateValue(1.0, Train->dsbSwitch); - Train->mvControlled->StLinSwitchOff = true; + Train->controlled->StLinSwitchOff = true; Train->set_paired_open_motor_connectors_button(true); } else @@ -421,13 +421,13 @@ void TTrain::OnCommand_motorconnectorsopen(TTrain *Train, command_data const &Co else if (Command.action == GLFW_RELEASE) { // button released - if (Train->mvControlled->StLinSwitchType != "toggle") + if (Train->controlled->StLinSwitchType != "toggle") { // default button type (impulse) ceases its work on button release // visual feedback Train->ggStLinOffButton.UpdateValue(0.0, Train->dsbSwitch); - Train->mvControlled->StLinSwitchOff = false; + Train->controlled->StLinSwitchOff = false; Train->set_paired_open_motor_connectors_button(false); } } @@ -448,19 +448,19 @@ void TTrain::OnCommand_motorconnectorsclose(TTrain *Train, command_data const &C if (Command.action == GLFW_PRESS) { - if (Train->mvControlled->StLinSwitchType == "toggle") + if (Train->controlled->StLinSwitchType == "toggle") { // default type of button (impulse) has only one effect on press, but the toggle type can toggle the state // visual feedback Train->ggStLinOffButton.UpdateValue(0.0, Train->dsbSwitch); } - if (false == Train->mvControlled->StLinSwitchOff) + if (false == Train->controlled->StLinSwitchOff) { return; } // already closed - Train->mvControlled->StLinSwitchOff = false; + Train->controlled->StLinSwitchOff = false; Train->set_paired_open_motor_connectors_button(false); } } @@ -468,7 +468,7 @@ void TTrain::OnCommand_motorconnectorsclose(TTrain *Train, command_data const &C void TTrain::OnCommand_motordisconnect(TTrain *Train, command_data const &Command) { - if (Train->mvControlled->TrainType == train_type::emu ? Train->mvControlled != Train->mvOccupied : Train->iCabn != 0) + if (Train->controlled->TrainType == train_type::emu ? Train->controlled != Train->occupied : Train->iCabn != 0) { // tylko w maszynowym return; @@ -476,7 +476,7 @@ void TTrain::OnCommand_motordisconnect(TTrain *Train, command_data const &Comman if (Command.action == GLFW_PRESS) { - Train->mvControlled->CutOffEngine(); + Train->controlled->CutOffEngine(); } } @@ -485,7 +485,7 @@ void TTrain::OnCommand_motoroverloadrelaythresholdtoggle(TTrain *Train, command_ if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (true == Train->mvControlled->ShuntModeAllow ? false == Train->mvControlled->ShuntMode : false == Train->mvControlled->MotorOverloadRelayHighThreshold) + if (true == Train->controlled->ShuntModeAllow ? false == Train->controlled->ShuntMode : false == Train->controlled->MotorOverloadRelayHighThreshold) { // turn on OnCommand_motoroverloadrelaythresholdsethigh(Train, Command); @@ -504,9 +504,9 @@ void TTrain::OnCommand_motoroverloadrelaythresholdsetlow(TTrain *Train, command_ if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvControlled->CurrentSwitch(false); + Train->controlled->CurrentSwitch(false); // visual feedback - Train->ggMaxCurrentCtrl.UpdateValue(Train->mvControlled->MotorOverloadRelayHighThreshold ? 1 : 0, Train->dsbSwitch); + Train->ggMaxCurrentCtrl.UpdateValue(Train->controlled->MotorOverloadRelayHighThreshold ? 1 : 0, Train->dsbSwitch); } } @@ -516,9 +516,9 @@ void TTrain::OnCommand_motoroverloadrelaythresholdsethigh(TTrain *Train, command if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvControlled->CurrentSwitch(true); + Train->controlled->CurrentSwitch(true); // visual feedback - Train->ggMaxCurrentCtrl.UpdateValue(Train->mvControlled->MotorOverloadRelayHighThreshold ? 1 : 0, Train->dsbSwitch); + Train->ggMaxCurrentCtrl.UpdateValue(Train->controlled->MotorOverloadRelayHighThreshold ? 1 : 0, Train->dsbSwitch); } } @@ -539,7 +539,7 @@ void TTrain::OnCommand_motoroverloadrelayreset(TTrain *Train, command_data const // visual feedback Train->ggFuseButton.UpdateValue(1.0, Train->dsbSwitch); - Train->mvControlled->FuseOn(); + Train->controlled->FuseOn(); } else if (Command.action == GLFW_RELEASE) { @@ -557,7 +557,7 @@ void TTrain::OnCommand_universalrelayreset(TTrain *Train, command_data const &Co // NOTE: relay reset switches are impulse-only if (Command.action == GLFW_PRESS) { - Train->mvOccupied->UniversalResetButton(itemindex); + Train->occupied->UniversalResetButton(itemindex); // visual feedback item.UpdateValue(1.0); } diff --git a/vehicle/cab/screens.cpp b/vehicle/cab/screens.cpp index c30b1b283..e5b2a37f3 100644 --- a/vehicle/cab/screens.cpp +++ b/vehicle/cab/screens.cpp @@ -38,7 +38,7 @@ http://mozilla.org/MPL/2.0/. #include "Console.h" #include "application/application.h" #include "rendering/renderer.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include #include #include diff --git a/vehicle/cab/setup.cpp b/vehicle/cab/setup.cpp index d1bac2763..699222956 100644 --- a/vehicle/cab/setup.cpp +++ b/vehicle/cab/setup.cpp @@ -38,7 +38,7 @@ http://mozilla.org/MPL/2.0/. #include "Console.h" #include "application/application.h" #include "rendering/renderer.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include #include #include @@ -75,10 +75,10 @@ bool TTrain::LoadMMediaFile(std::string const &asFileName) {"localbrakesound2:", {rsSBHissU, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, {"brakesound:", {rsBrake, internal, -1, single, sound_parameters::amplitude | sound_parameters::frequency, 100.0}}, {"fadesound:", {rsFadeSound, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"runningnoise:", {rsRunningNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, mvOccupied->Vmax}}, - {"resonancenoise:", {rsResonanceNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, mvOccupied->Vmax}}, - {"windsound:", {rsWindSound, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, mvOccupied->Vmax}}, - {"huntingnoise:", {rsHuntingNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, mvOccupied->Vmax}}, + {"runningnoise:", {rsRunningNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, occupied->Vmax}}, + {"resonancenoise:", {rsResonanceNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, occupied->Vmax}}, + {"windsound:", {rsWindSound, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, occupied->Vmax}}, + {"huntingnoise:", {rsHuntingNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, occupied->Vmax}}, {"rainsound:", {m_rainsound, internal, -1, single, 0, 100.0}}, }; for (auto &[soundname, soundsource] : internalsounds) @@ -143,23 +143,23 @@ bool TTrain::LoadMMediaFile(std::string const &asFileName) } if (rsBrake) { - rsBrake->m_frequencyfactor /= static_cast(1 + mvOccupied->Vmax); + rsBrake->m_frequencyfactor /= static_cast(1 + occupied->Vmax); } if (rsResonanceNoise) { - rsResonanceNoise->m_frequencyfactor /= static_cast(1 + mvOccupied->Vmax); + rsResonanceNoise->m_frequencyfactor /= static_cast(1 + occupied->Vmax); } if (rsWindSound) { - rsWindSound->m_frequencyfactor /= static_cast(1 + mvOccupied->Vmax); + rsWindSound->m_frequencyfactor /= static_cast(1 + occupied->Vmax); } if (rsRunningNoise) { - rsRunningNoise->m_frequencyfactor /= static_cast(1 + mvOccupied->Vmax); + rsRunningNoise->m_frequencyfactor /= static_cast(1 + occupied->Vmax); } if (rsHuntingNoise) { - rsHuntingNoise->m_frequencyfactor /= static_cast(1 + mvOccupied->Vmax); + rsHuntingNoise->m_frequencyfactor /= static_cast(1 + occupied->Vmax); } } std::vector>> sounds = { @@ -552,7 +552,7 @@ bool TTrain::InitializeCab(int NewCabNo, std::string const &asFileName) DynamicObject->mdKabina->Init(); // obrócenie modelu oraz optymalizacja, również zapisanie binarnego // the vehicle has a cab, a player is in it: the odometer store keeps the vehicle also when its type has no // driver's brake valve (eu07/maszyna#72) - DynamicObject->MoverParameters->Odometer.shown = true; + DynamicObject->physics->Odometer.shown = true; } set_cab_controls(NewCabNo < 0 ? 2 : NewCabNo); @@ -573,7 +573,7 @@ glm::dvec3 TTrain::MirrorPosition(bool lewe) auto const shiftdirection{(lewe ? -1 : 1) * (iCabn == 2 ? 1 : -1)}; return DynamicObject->mMatrix * - glm::dvec4(mvOccupied->Dim.W * (0.5 * shiftdirection) + 0.2 * shiftdirection, 1.5 + Cabine[iCabn].CabPos1.y, std::lerp(Cabine[iCabn].CabPos1.z, Cabine[iCabn].CabPos2.z, 0.5), 1.0); + glm::dvec4(occupied->Dim.W * (0.5 * shiftdirection) + 0.2 * shiftdirection, 1.5 + Cabine[iCabn].CabPos1.y, std::lerp(Cabine[iCabn].CabPos1.z, Cabine[iCabn].CabPos2.z, 0.5), 1.0); }; // clears state of all cabin controls @@ -587,11 +587,11 @@ void TTrain::clear_cab_controls() btLampkaNadmSil.Clear(4); btLampkaStyczn.Clear(5); btLampkaPoslizg.Clear(6); - btLampkaNadmPrzetw.Clear(mvControlled->TrainType == train_type::emu ? -1 : 7); // EN57 nie ma tej lampki - btLampkaPrzetwOff.Clear(mvControlled->TrainType == train_type::emu ? 7 : -1); // za to ma tę + btLampkaNadmPrzetw.Clear(controlled->TrainType == train_type::emu ? -1 : 7); // EN57 nie ma tej lampki + btLampkaPrzetwOff.Clear(controlled->TrainType == train_type::emu ? 7 : -1); // za to ma tę btLampkaNadmSpr.Clear(8); btLampkaNadmWent.Clear(9); - btLampkaWysRozr.Clear(mvControlled->TrainType == train_type::et22 ? -1 : 10); // ET22 nie ma tej lampki + btLampkaWysRozr.Clear(controlled->TrainType == train_type::et22 ? -1 : 10); // ET22 nie ma tej lampki btLampkaOgrzewanieSkladu.Clear(11); // overheat indicator lamps btLampkaOilOverheat.Clear(-1); @@ -888,9 +888,9 @@ void TTrain::set_cab_controls(int const Cab) { // switches // battery - ggBatteryButton.PutValue(ggBatteryButton.type() == TGaugeType::push ? 0.5f : mvOccupied->Power24vIsAvailable ? 1.f : 0.f); + ggBatteryButton.PutValue(ggBatteryButton.type() == TGaugeType::push ? 0.5f : occupied->Power24vIsAvailable ? 1.f : 0.f); // activation - ggCabActivationButton.PutValue(ggCabActivationButton.type() == TGaugeType::push ? 0.5f : mvOccupied->IsCabMaster() ? 1.f : 0.f); + ggCabActivationButton.PutValue(ggCabActivationButton.type() == TGaugeType::push ? 0.5f : occupied->IsCabMaster() ? 1.f : 0.f); // line breaker if (ggMainButton.SubModel != nullptr) { // instead of single main button there can be on/off pair @@ -915,8 +915,8 @@ void TTrain::set_cab_controls(int const Cab) if (ggModernLightDimSw.SubModel != nullptr) { - mvOccupied->modernDimmerPosition = mvOccupied->modernDimmerDefaultPosition; - ggModernLightDimSw.PutValue(static_cast(mvOccupied->modernDimmerDefaultPosition)); + occupied->modernDimmerPosition = occupied->modernDimmerDefaultPosition; + ggModernLightDimSw.PutValue(static_cast(occupied->modernDimmerDefaultPosition)); } // Init separate buttons @@ -930,35 +930,35 @@ void TTrain::set_cab_controls(int const Cab) } // motor connectors - ggStLinOffButton.PutValue(mvControlled->StLinSwitchOff ? 1.f : 0.f); + ggStLinOffButton.PutValue(controlled->StLinSwitchOff ? 1.f : 0.f); // radio ggRadioChannelSelector.PutValue(static_cast((Dynamic()->Mechanik ? Dynamic()->Mechanik->iRadioChannel : 1) - 1)); // pantographs /* - if( mvOccupied->PantSwitchType != "impulse" ) { + if( occupied->PantSwitchType != "impulse" ) { if( ggPantFrontButton.SubModel ) { ggPantFrontButton.PutValue( - ( mvControlled->Pantographs[VehicleEnd::front].valve.is_enabled ? + ( controlled->Pantographs[VehicleEnd::front].valve.is_enabled ? 1.f : 0.f ) ); } if( ggPantFrontButtonOff.SubModel ) { ggPantFrontButtonOff.PutValue( - ( mvControlled->Pantographs[VehicleEnd::front].valve.is_disabled ? + ( controlled->Pantographs[VehicleEnd::front].valve.is_disabled ? 1.f : 0.f ) ); } } - if( mvOccupied->PantSwitchType != "impulse" ) { + if( occupied->PantSwitchType != "impulse" ) { if( ggPantRearButton.SubModel ) { ggPantRearButton.PutValue( - ( mvControlled->Pantographs[VehicleEnd::rear].valve.is_enabled ? + ( controlled->Pantographs[VehicleEnd::rear].valve.is_enabled ? 1.f : 0.f ) ); } if( ggPantRearButtonOff.SubModel ) { ggPantRearButtonOff.PutValue( - ( mvControlled->Pantographs[VehicleEnd::rear].valve.is_disabled ? + ( controlled->Pantographs[VehicleEnd::rear].valve.is_disabled ? 1.f : 0.f ) ); } @@ -967,7 +967,7 @@ void TTrain::set_cab_controls(int const Cab) // front/end pantograph selection is relative to occupied cab if (ggPantSelectedButton.type() == TGaugeType::toggle) { - ggPantSelectedButton.PutValue(mvPantographUnit->PantsValve.is_enabled ? 1.f : 0.f); + ggPantSelectedButton.PutValue(pantographUnit->PantsValve.is_enabled ? 1.f : 0.f); } else { @@ -979,47 +979,47 @@ void TTrain::set_cab_controls(int const Cab) } if (ggPantSelectedDownButton.type() == TGaugeType::toggle) { - ggPantSelectedDownButton.PutValue(mvPantographUnit->PantsValve.is_disabled ? 1.f : 0.f); + ggPantSelectedDownButton.PutValue(pantographUnit->PantsValve.is_disabled ? 1.f : 0.f); } ggPantValvesButton.PutValue(0.5f); // auxiliary compressor - ggPantCompressorValve.PutValue(mvControlled->bPantKurek3 ? 0.f : // default setting is pantographs connected with primary tank + ggPantCompressorValve.PutValue(controlled->bPantKurek3 ? 0.f : // default setting is pantographs connected with primary tank 1.f); - ggPantCompressorButton.PutValue(mvPantographUnit->PantCompFlag ? 1.f : 0.f); + ggPantCompressorButton.PutValue(pantographUnit->PantCompFlag ? 1.f : 0.f); // converter - if (mvOccupied->ConvSwitchType != "impulse") + if (occupied->ConvSwitchType != "impulse") { - ggConverterButton.PutValue(mvOccupied->ConverterAllow ? 1.f : 0.f); + ggConverterButton.PutValue(occupied->ConverterAllow ? 1.f : 0.f); } - ggConverterLocalButton.PutValue(mvOccupied->ConverterAllowLocal ? 1.f : 0.f); + ggConverterLocalButton.PutValue(occupied->ConverterAllowLocal ? 1.f : 0.f); // compressor - ggCompressorButton.PutValue(mvControlled->CompressorAllow ? 1.f : 0.f); - ggCompressorLocalButton.PutValue(mvControlled->CompressorAllowLocal ? 1.f : 0.f); - ggCompressorListButton.PutValue(static_cast(mvOccupied->CompressorListPos - 1)); + ggCompressorButton.PutValue(controlled->CompressorAllow ? 1.f : 0.f); + ggCompressorLocalButton.PutValue(controlled->CompressorAllowLocal ? 1.f : 0.f); + ggCompressorListButton.PutValue(static_cast(occupied->CompressorListPos - 1)); // motor overload relay threshold / shunt mode - ggMaxCurrentCtrl.PutValue(true == mvControlled->ShuntModeAllow ? (true == mvControlled->ShuntMode ? 1.f : 0.f) : mvControlled->MotorOverloadRelayHighThreshold ? 1.f : 0.f); + ggMaxCurrentCtrl.PutValue(true == controlled->ShuntModeAllow ? (true == controlled->ShuntMode ? 1.f : 0.f) : controlled->MotorOverloadRelayHighThreshold ? 1.f : 0.f); // automatic relays (AutoRelay) - ggAutoRelayButton.PutValue(mvOccupied->AutoRelayFlag ? 1.f : 0.f); + ggAutoRelayButton.PutValue(occupied->AutoRelayFlag ? 1.f : 0.f); // lights - ggLightsButton.PutValue(static_cast(mvOccupied->LightsPos - 1)); + ggLightsButton.PutValue(static_cast(occupied->LightsPos - 1)); auto const vehicleend{cab_to_end(Cab)}; - if ((mvOccupied->iLights[vehicleend] & light::headlight_left) != 0) + if ((occupied->iLights[vehicleend] & light::headlight_left) != 0) { ggLeftLightButton.PutValue(1.f); } - if ((mvOccupied->iLights[vehicleend] & light::headlight_right) != 0) + if ((occupied->iLights[vehicleend] & light::headlight_right) != 0) { ggRightLightButton.PutValue(1.f); } - if ((mvOccupied->iLights[vehicleend] & light::headlight_upper) != 0) + if ((occupied->iLights[vehicleend] & light::headlight_upper) != 0) { ggUpperLightButton.PutValue(1.f); } - if ((mvOccupied->iLights[vehicleend] & light::redmarker_left) != 0) + if ((occupied->iLights[vehicleend] & light::redmarker_left) != 0) { if (ggLeftEndLightButton.SubModel != nullptr) { @@ -1030,7 +1030,7 @@ void TTrain::set_cab_controls(int const Cab) ggLeftLightButton.PutValue(-1.f); } } - if ((mvOccupied->iLights[vehicleend] & light::redmarker_right) != 0) + if ((occupied->iLights[vehicleend] & light::redmarker_right) != 0) { if (ggRightEndLightButton.SubModel != nullptr) { @@ -1041,9 +1041,9 @@ void TTrain::set_cab_controls(int const Cab) ggRightLightButton.PutValue(-1.f); } } - if (1 == DynamicObject->MoverParameters->modernDimmerPosition) + if (1 == DynamicObject->physics->modernDimmerPosition) { - ggDimHeadlightsButton.PutValue(static_cast(DynamicObject->MoverParameters->modernDimmerPosition)); + ggDimHeadlightsButton.PutValue(static_cast(DynamicObject->physics->modernDimmerPosition)); } // cab lights if (true == Cabine[Cab].bLightDim) @@ -1051,7 +1051,7 @@ void TTrain::set_cab_controls(int const Cab) ggCabLightDimButton.PutValue(1.f); } // compartment lights - ggCompartmentLightsButton.PutValue(ggCompartmentLightsButton.type() == TGaugeType::push ? 0.5f : mvOccupied->CompartmentLights.is_enabled ? 1.f : 0.f); + ggCompartmentLightsButton.PutValue(ggCompartmentLightsButton.type() == TGaugeType::push ? 0.5f : occupied->CompartmentLights.is_enabled ? 1.f : 0.f); // instrument lights ggInstrumentLightButton.PutValue(InstrumentLightActive ? 1.f : 0.f); ggDashboardLightButton.PutValue(DashboardLightActive ? 1.f : 0.f); @@ -1059,100 +1059,100 @@ void TTrain::set_cab_controls(int const Cab) // doors permits if (false == ggDoorLeftPermitButton.is_push()) { - ggDoorLeftPermitButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right].open_permit ? 1.f : 0.f); + ggDoorLeftPermitButton.PutValue(occupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right].open_permit ? 1.f : 0.f); } if (false == ggDoorRightPermitButton.is_push()) { - ggDoorRightPermitButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left].open_permit ? 1.f : 0.f); + ggDoorRightPermitButton.PutValue(occupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left].open_permit ? 1.f : 0.f); } - ggDoorPermitPresetButton.PutValue(static_cast(mvOccupied->Doors.permit_preset)); + ggDoorPermitPresetButton.PutValue(static_cast(occupied->Doors.permit_preset)); // door controls - ggDoorLeftButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right].is_closed ? 0.f : 1.f); - ggDoorRightButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left].is_closed ? 0.f : 1.f); + ggDoorLeftButton.PutValue(occupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right].is_closed ? 0.f : 1.f); + ggDoorRightButton.PutValue(occupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left].is_closed ? 0.f : 1.f); // door lock - ggDoorSignallingButton.PutValue(mvOccupied->Doors.lock_enabled ? 1.f : 0.f); + ggDoorSignallingButton.PutValue(occupied->Doors.lock_enabled ? 1.f : 0.f); // door step if (false == ggDoorStepButton.is_push()) { - ggDoorStepButton.PutValue(mvOccupied->Doors.step_enabled ? 1.f : 0.f); + ggDoorStepButton.PutValue(occupied->Doors.step_enabled ? 1.f : 0.f); } // heating - if (false == ggTrainHeatingButton.is_push() && false == mvOccupied->HeatingSwitchImpulse) + if (false == ggTrainHeatingButton.is_push() && false == occupied->HeatingSwitchImpulse) { - ggTrainHeatingButton.PutValue(mvControlled->Heating ? 1.f : 0.f); + ggTrainHeatingButton.PutValue(controlled->Heating ? 1.f : 0.f); } // brake acting time if (ggBrakeProfileCtrl.SubModel != nullptr) { - ggBrakeProfileCtrl.PutValue((mvOccupied->BrakeDelayFlag & bdelay_R) != 0 ? 2.f : static_cast(mvOccupied->BrakeDelayFlag - 1)); + ggBrakeProfileCtrl.PutValue((occupied->BrakeDelayFlag & bdelay_R) != 0 ? 2.f : static_cast(occupied->BrakeDelayFlag - 1)); } if (ggBrakeProfileG.SubModel != nullptr) { - ggBrakeProfileG.PutValue(mvOccupied->BrakeDelayFlag == bdelay_G ? 1.f : 0.f); + ggBrakeProfileG.PutValue(occupied->BrakeDelayFlag == bdelay_G ? 1.f : 0.f); } if (ggBrakeProfileR.SubModel != nullptr) { - ggBrakeProfileR.PutValue((mvOccupied->BrakeDelayFlag & bdelay_R) != 0 ? 1.f : 0.f); + ggBrakeProfileR.PutValue((occupied->BrakeDelayFlag & bdelay_R) != 0 ? 1.f : 0.f); } if (ggWiperSw.SubModel != nullptr) { - ggWiperSw.PutValue(static_cast(mvOccupied->wiperSwitchPos)); + ggWiperSw.PutValue(static_cast(occupied->wiperSwitchPos)); } if (ggBrakeOperationModeCtrl.SubModel != nullptr) { - ggBrakeOperationModeCtrl.PutValue(mvOccupied->BrakeOpModeFlag > 0 ? static_cast(std::log2(mvOccupied->BrakeOpModeFlag)) : 0); + ggBrakeOperationModeCtrl.PutValue(occupied->BrakeOpModeFlag > 0 ? static_cast(std::log2(occupied->BrakeOpModeFlag)) : 0); } // alarm chain - ggAlarmChain.PutValue(mvControlled->AlarmChainFlag ? 1.f : 0.f); + ggAlarmChain.PutValue(controlled->AlarmChainFlag ? 1.f : 0.f); // brake signalling - ggSignallingButton.PutValue(mvControlled->Signalling ? 1.f : 0.f); + ggSignallingButton.PutValue(controlled->Signalling ? 1.f : 0.f); // multiple-unit current indicator source ggNextCurrentButton.PutValue(ShowNextCurrent ? 1.f : 0.f); // water pump - ggWaterPumpBreakerButton.PutValue(mvControlled->WaterPump.breaker ? 1.f : 0.f); + ggWaterPumpBreakerButton.PutValue(controlled->WaterPump.breaker ? 1.f : 0.f); if (ggWaterPumpButton.type() != TGaugeType::push) { - ggWaterPumpButton.PutValue(mvControlled->WaterPump.is_enabled ? 1.f : 0.f); + ggWaterPumpButton.PutValue(controlled->WaterPump.is_enabled ? 1.f : 0.f); } // water heater - ggWaterHeaterBreakerButton.PutValue(mvControlled->WaterHeater.breaker ? 1.f : 0.f); - ggWaterHeaterButton.PutValue(mvControlled->WaterHeater.is_enabled ? 1.f : 0.f); - ggWaterCircuitsLinkButton.PutValue(mvControlled->WaterCircuitsLink ? 1.f : 0.f); + ggWaterHeaterBreakerButton.PutValue(controlled->WaterHeater.breaker ? 1.f : 0.f); + ggWaterHeaterButton.PutValue(controlled->WaterHeater.is_enabled ? 1.f : 0.f); + ggWaterCircuitsLinkButton.PutValue(controlled->WaterCircuitsLink ? 1.f : 0.f); // fuel pump if (ggFuelPumpButton.type() != TGaugeType::push) { - ggFuelPumpButton.PutValue(mvControlled->FuelPump.is_enabled ? 1.f : 0.f); + ggFuelPumpButton.PutValue(controlled->FuelPump.is_enabled ? 1.f : 0.f); } // oil pump if (ggOilPumpButton.type() != TGaugeType::push) { - ggOilPumpButton.PutValue(mvControlled->OilPump.is_enabled ? 1.f : 0.f); + ggOilPumpButton.PutValue(controlled->OilPump.is_enabled ? 1.f : 0.f); } // joint oil and fuel pump if (ggOilFuelPumpButton.type() != TGaugeType::push) { - ggOilFuelPumpButton.PutValue(mvControlled->OilFuelPumpsEnabled() ? 1.f : 0.f); + ggOilFuelPumpButton.PutValue(controlled->OilFuelPumpsEnabled() ? 1.f : 0.f); } // traction selector and genset of a dual-mode vehicle - ggTractionModeSwitch.PutValue(mvControlled->GensetSelected() ? 1.f : 0.f); + ggTractionModeSwitch.PutValue(controlled->GensetSelected() ? 1.f : 0.f); if (ggGensetButton.type() != TGaugeType::push) { - ggGensetButton.PutValue(mvControlled->Genset.is_enabled ? 1.f : 0.f); + ggGensetButton.PutValue(controlled->Genset.is_enabled ? 1.f : 0.f); } // traction motor fans if (ggMotorBlowersFrontButton.type() != TGaugeType::push) { - ggMotorBlowersFrontButton.PutValue(mvControlled->MotorBlowers[VehicleEnd::front].is_enabled ? 1.f : 0.f); + ggMotorBlowersFrontButton.PutValue(controlled->MotorBlowers[VehicleEnd::front].is_enabled ? 1.f : 0.f); } if (ggMotorBlowersRearButton.type() != TGaugeType::push) { - ggMotorBlowersRearButton.PutValue(mvControlled->MotorBlowers[VehicleEnd::rear].is_enabled ? 1.f : 0.f); + ggMotorBlowersRearButton.PutValue(controlled->MotorBlowers[VehicleEnd::rear].is_enabled ? 1.f : 0.f); } if (ggMotorBlowersAllOffButton.type() != TGaugeType::push) { - ggMotorBlowersAllOffButton.PutValue(mvControlled->MotorBlowers[VehicleEnd::front].is_disabled || mvControlled->MotorBlowers[VehicleEnd::rear].is_disabled ? 1.f : 0.f); + ggMotorBlowersAllOffButton.PutValue(controlled->MotorBlowers[VehicleEnd::front].is_disabled || controlled->MotorBlowers[VehicleEnd::rear].is_disabled ? 1.f : 0.f); } // second controller if (ggScndCtrl.is_push()) @@ -1163,38 +1163,38 @@ void TTrain::set_cab_controls(int const Cab) // tempomat if (false == ggScndCtrlButton.is_push()) { - ggScndCtrlButton.PutValue(mvControlled->IsSpeedCtrlEngaged() ? 1.f : 0.f); + ggScndCtrlButton.PutValue(controlled->IsSpeedCtrlEngaged() ? 1.f : 0.f); } // sandbox if (ggAutoSandButton.type() != TGaugeType::push) { - ggAutoSandButton.PutValue(mvControlled->SandDoseAutoAllow ? 1.f : 0.f); + ggAutoSandButton.PutValue(controlled->SandDoseAutoAllow ? 1.f : 0.f); } // radio ggRadioVolumeSelector.PutValue(m_radiovolume); // finding each inverter - not so optimal, but action ins performed only during changing cabin - bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; - auto const flag{CouplingSet::FromBits(DynamicObject->MoverParameters->inductionMotor.inverterControlCouplings)}; + bool kier = DynamicObject->DirectionGet() * occupied->CabOccupied > 0; + auto const flag{CouplingSet::FromBits(DynamicObject->physics->inductionMotor.inverterControlCouplings)}; int itemstart = 0; for ([[maybe_unused]] auto const &item : ggInverterToggleButtons) // for each button { int itemindex = itemstart; itemstart++; - TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, flag); + TDynamicObject *p = DynamicObject->GetFirstDynamic(occupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, flag); while (p) { - if (p->MoverParameters->inductionMotor.traction.maxPower > 1) + if (p->physics->inductionMotor.traction.maxPower > 1) { - if (itemindex < p->MoverParameters->inductionMotor.inverterCount) + if (itemindex < p->physics->inductionMotor.inverterCount) { // visual feedback - ggInverterToggleButtons[itemstart - 1].PutValue(p->MoverParameters->inductionMotor.inverters[itemindex].Activate ? 1.0 : 0.0); + ggInverterToggleButtons[itemstart - 1].PutValue(p->physics->inductionMotor.inverters[itemindex].Activate ? 1.0 : 0.0); break; } else { - itemindex -= p->MoverParameters->inductionMotor.inverterCount; + itemindex -= p->physics->inductionMotor.inverterCount; } } p = kier ? p->Next(flag) : p->Prev(flag); @@ -1338,11 +1338,11 @@ bool TTrain::initialize_button(cParser &Parser, std::string const &Label, int co {"i-doorpermit_left:", &m_doorspermitleft}, {"i-doorpermit_right:", &m_doorspermitright}, {"i-doorpermit_any:", &m_doorpermits}, - {"i-doorstep:", &mvOccupied->Doors.step_enabled}, - {"i-mainpipelock:", &mvOccupied->LockPipe}, - {"i-battery:", &mvOccupied->Power24vIsAvailable}, + {"i-doorstep:", &occupied->Doors.step_enabled}, + {"i-mainpipelock:", &occupied->LockPipe}, + {"i-battery:", &occupied->Power24vIsAvailable}, {"i-cablight:", &Cabine[iCabn].bLight}, - {"i-compartmentlights:", &mvOccupied->CompartmentLights.is_active}, + {"i-compartmentlights:", &occupied->CompartmentLights.is_active}, }; { auto lookup = autolights.find(Label); @@ -1613,26 +1613,26 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con // TODO: move viable gauges here // TODO: convert dedicated gauges to auto-allocated ones, replace dedicated references in command handlers to mapper lookups std::unordered_map> const stategauges = { - {"tempomat_sw:", {ggScndCtrlButton, &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"tempomatoff_sw:", {ggScndCtrlOffButton, &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedinc_bt:", {ggSpeedControlIncreaseButton, &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speeddec_bt:", {ggSpeedControlDecreaseButton, &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedctrlpowerinc_bt:", {ggSpeedControlPowerIncreaseButton, &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedctrlpowerdec_bt:", {ggSpeedControlPowerDecreaseButton, &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton0:", {ggSpeedCtrlButtons[0], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton1:", {ggSpeedCtrlButtons[1], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton2:", {ggSpeedCtrlButtons[2], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton3:", {ggSpeedCtrlButtons[3], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton4:", {ggSpeedCtrlButtons[4], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton5:", {ggSpeedCtrlButtons[5], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton6:", {ggSpeedCtrlButtons[6], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton7:", {ggSpeedCtrlButtons[7], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton8:", {ggSpeedCtrlButtons[8], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton9:", {ggSpeedCtrlButtons[9], &mvOccupied->SpeedCtrlUnit.IsActive}}, + {"tempomat_sw:", {ggScndCtrlButton, &occupied->SpeedCtrlUnit.IsActive}}, + {"tempomatoff_sw:", {ggScndCtrlOffButton, &occupied->SpeedCtrlUnit.IsActive}}, + {"speedinc_bt:", {ggSpeedControlIncreaseButton, &occupied->SpeedCtrlUnit.IsActive}}, + {"speeddec_bt:", {ggSpeedControlDecreaseButton, &occupied->SpeedCtrlUnit.IsActive}}, + {"speedctrlpowerinc_bt:", {ggSpeedControlPowerIncreaseButton, &occupied->SpeedCtrlUnit.IsActive}}, + {"speedctrlpowerdec_bt:", {ggSpeedControlPowerDecreaseButton, &occupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton0:", {ggSpeedCtrlButtons[0], &occupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton1:", {ggSpeedCtrlButtons[1], &occupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton2:", {ggSpeedCtrlButtons[2], &occupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton3:", {ggSpeedCtrlButtons[3], &occupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton4:", {ggSpeedCtrlButtons[4], &occupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton5:", {ggSpeedCtrlButtons[5], &occupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton6:", {ggSpeedCtrlButtons[6], &occupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton7:", {ggSpeedCtrlButtons[7], &occupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton8:", {ggSpeedCtrlButtons[8], &occupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton9:", {ggSpeedCtrlButtons[9], &occupied->SpeedCtrlUnit.IsActive}}, {"doorleftpermit_sw:", {ggDoorLeftPermitButton, &m_doorspermitleft}}, {"doorrightpermit_sw:", {ggDoorRightPermitButton, &m_doorspermitright}}, {"dooralloff_sw:", {ggDoorAllOffButton, &m_doors}}, - {"doorstep_sw:", {ggDoorStepButton, &mvOccupied->Doors.step_enabled}}, + {"doorstep_sw:", {ggDoorStepButton, &occupied->Doors.step_enabled}}, {"dirforward_bt:", {ggDirForwardButton, &m_dirforward}}, {"dirneutral_bt:", {ggDirNeutralButton, &m_dirneutral}}, {"dirbackward_bt:", {ggDirBackwardButton, &m_dirbackward}}, @@ -1650,19 +1650,19 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con } // TODO: move viable dedicated gauges to the automatic array std::unordered_map const autoboolgauges = { - {"doormode_sw:", &mvOccupied->Doors.remote_only}, - {"coolingfans_sw:", &mvControlled->RVentForceOn}, - {"pantfront_sw:", &mvPantographUnit->Pantographs[VehicleEnd::front].valve.is_enabled}, - {"pantrear_sw:", &mvPantographUnit->Pantographs[VehicleEnd::rear].valve.is_enabled}, - {"pantfrontoff_sw:", &mvPantographUnit->Pantographs[VehicleEnd::front].valve.is_disabled}, - {"pantrearoff_sw:", &mvPantographUnit->Pantographs[VehicleEnd::rear].valve.is_disabled}, - {"radio_sw:", &mvOccupied->Radio}, - {"radiofuse_sw:", &mvOccupied->RadioFuse}, + {"doormode_sw:", &occupied->Doors.remote_only}, + {"coolingfans_sw:", &controlled->RVentForceOn}, + {"pantfront_sw:", &pantographUnit->Pantographs[VehicleEnd::front].valve.is_enabled}, + {"pantrear_sw:", &pantographUnit->Pantographs[VehicleEnd::rear].valve.is_enabled}, + {"pantfrontoff_sw:", &pantographUnit->Pantographs[VehicleEnd::front].valve.is_disabled}, + {"pantrearoff_sw:", &pantographUnit->Pantographs[VehicleEnd::rear].valve.is_disabled}, + {"radio_sw:", &occupied->Radio}, + {"radiofuse_sw:", &occupied->RadioFuse}, {"cablight_sw:", &Cabine[iCabn].bLight}, - {"springbraketoggle_bt:", &mvOccupied->SpringBrake.Activate}, + {"springbraketoggle_bt:", &occupied->SpringBrake.Activate}, {"couplingdisconnect_sw:", &m_couplingdisconnect}, {"couplingdisconnectback_sw:", &m_couplingdisconnectback}, - {"mirrors_sw:", &mvOccupied->MirrorForbidden}, + {"mirrors_sw:", &occupied->MirrorForbidden}, }; { auto lookup = autoboolgauges.find(Label); @@ -1677,8 +1677,8 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con } // TODO: move viable dedicated gauges to the automatic array std::unordered_map const autointgauges = { - {"manualbrake:", &mvOccupied->ManualBrakePos}, - {"pantselect_sw:", &mvOccupied->PantsPreset.second[cab_to_end()]}, + {"manualbrake:", &occupied->ManualBrakePos}, + {"pantselect_sw:", &occupied->PantsPreset.second[cab_to_end()]}, }; { auto lookup = autointgauges.find(Label); @@ -1817,21 +1817,21 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con // Ra 2014-08: przeniesione do TCab auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&mvOccupied->BrakePress); + gauge.AssignDouble(&occupied->BrakePress); } else if (Label == "pipepress:" || Label == "pipepressb:") { // manometr przewodu hamulcowego auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&mvOccupied->PipePress); + gauge.AssignDouble(&occupied->PipePress); } else if (Label == "scndpress:") { // manometr przewodu hamulcowego auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&mvOccupied->ScndPipePress); + gauge.AssignDouble(&occupied->ScndPipePress); } else if (Label == "limpipepress:") { @@ -1845,63 +1845,63 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con // manometr zbiornika kontrolnego/rorzďż˝du auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&mvPantographUnit->PantPress); + gauge.AssignDouble(&pantographUnit->PantPress); } else if (Label == "springbrakepress:") { // manometr cylindra hamulca sprężynowego auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&mvOccupied->SpringBrake.SBP); + gauge.AssignDouble(&occupied->SpringBrake.SBP); } else if (Label == "epctrlvalue:") { // wskazowka sterowania sila hamulca ep auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&mvOccupied->EpForce); + gauge.AssignDouble(&occupied->EpForce); } else if (Label == "compressor:" || Label == "compressorb:") { // manometr sprezarki/zbiornika glownego auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&mvOccupied->Compressor); + gauge.AssignDouble(&occupied->Compressor); } else if (Label == "oilpress:") { // oil pressure auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(&mvControlled->OilPump.pressure); + gauge.AssignFloat(&controlled->OilPump.pressure); } else if (Label == "oiltemp:") { // oil temperature auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(&mvControlled->diesel.heat.To); + gauge.AssignFloat(&controlled->diesel.heat.To); } else if (Label == "water1temp:") { // main circuit water temperature auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(&mvControlled->diesel.heat.temperatura1); + gauge.AssignFloat(&controlled->diesel.heat.temperatura1); } else if (Label == "water2temp:") { // auxiliary circuit water temperature auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(&mvControlled->diesel.heat.temperatura2); + gauge.AssignFloat(&controlled->diesel.heat.temperatura2); } else if (Label == "pantpress:") { // pantograph tank pressure auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&mvPantographUnit->PantPress); + gauge.AssignDouble(&pantographUnit->PantPress); } // yB - dla drugiej sekcji else if (Label == "hvbcurrent1:") @@ -1982,7 +1982,7 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con // np. ciśnienie sterownika sprzęgła auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject); - gauge.AssignDouble(&mvControlled->diesel.clutchPressure); + gauge.AssignDouble(&controlled->diesel.clutchPressure); } // ggEngageRatio.Load(Parser,DynamicObject->mdKabina); else if (Label == "maingearstatus:") { @@ -2001,35 +2001,35 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con // the counter shows the odometer of the vehicle, kept between the sessions (eu07/maszyna#72). its offset // was the state it started each session with, now it is that only for a vehicle with no known state if (auto const seed{odometer::counter_seed(gauge.offset(), gauge.scale())}; seed.has_value()) - mvControlled->Odometer.seed(*seed); + controlled->Odometer.seed(*seed); gauge.offset(0.f); - gauge.AssignDouble(&mvControlled->Odometer.km); + gauge.AssignDouble(&controlled->Odometer.km); // the vehicle the counter counts for is one the odometer store keeps, also in the sessions the counter seeds // nothing (its state is a saved one by then) and when it's the motor car of the unit the cab is in - mvControlled->Odometer.shown = true; + controlled->Odometer.shown = true; } else if (Label == "shuntmodepower:") { // shunt mode power slider auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject); - gauge.AssignDouble(&mvControlled->AnPos); + gauge.AssignDouble(&controlled->AnPos); m_controlmapper.insert(gauge, "shuntmodepower:"); } else if (Label == "heatingvoltage:") { - if (mvControlled->HeatingPowerSource.SourceType == TPowerSource::Generator) + if (controlled->HeatingPowerSource.SourceType == TPowerSource::Generator) { auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject); - gauge.AssignDouble(&mvControlled->HeatingPowerSource.EngineGenerator.voltage); + gauge.AssignDouble(&controlled->HeatingPowerSource.EngineGenerator.voltage); } } else if (Label == "heatingcurrent:") { auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject); - gauge.AssignDouble(&mvControlled->TotalCurrent); + gauge.AssignDouble(&controlled->TotalCurrent); } else { diff --git a/vehicle/cab/signalcommands.cpp b/vehicle/cab/signalcommands.cpp index 200781dbe..bc3c6183c 100644 --- a/vehicle/cab/signalcommands.cpp +++ b/vehicle/cab/signalcommands.cpp @@ -38,7 +38,7 @@ http://mozilla.org/MPL/2.0/. #include "Console.h" #include "application/application.h" #include "rendering/renderer.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include #include #include @@ -62,10 +62,10 @@ void TTrain::OnCommand_hornlowactivate(TTrain *Train, command_data const &Comman if (Command.action == GLFW_PRESS) { // only need to react to press, sound will continue until stopped - if (false == TestFlag(Train->mvOccupied->WarningSignal, horn::low)) + if (false == TestFlag(Train->occupied->WarningSignal, horn::low)) { // turn on - Train->mvOccupied->WarningSignal = horn::pressed(Train->mvOccupied->WarningSignal, horn::low, Train->has_single_horn_lever()); + Train->occupied->WarningSignal = horn::pressed(Train->occupied->WarningSignal, horn::low, Train->has_single_horn_lever()); // visual feedback Train->ggHornButton.UpdateValue(-1.0); Train->ggHornLowButton.UpdateValue(1.0); @@ -74,9 +74,9 @@ void TTrain::OnCommand_hornlowactivate(TTrain *Train, command_data const &Comman else if (Command.action == GLFW_RELEASE) { // turn off - Train->mvOccupied->WarningSignal = horn::released(Train->mvOccupied->WarningSignal, horn::low); + Train->occupied->WarningSignal = horn::released(Train->occupied->WarningSignal, horn::low); // visual feedback - if (false == (Train->has_single_horn_lever() && TestFlag(Train->mvOccupied->WarningSignal, horn::high))) + if (false == (Train->has_single_horn_lever() && TestFlag(Train->occupied->WarningSignal, horn::high))) { // leave the single lever alone if it was moved to the other tone in the meantime Train->ggHornButton.UpdateValue(0.0); @@ -100,10 +100,10 @@ void TTrain::OnCommand_hornhighactivate(TTrain *Train, command_data const &Comma if (Command.action == GLFW_PRESS) { // only need to react to press, sound will continue until stopped - if (false == TestFlag(Train->mvOccupied->WarningSignal, horn::high)) + if (false == TestFlag(Train->occupied->WarningSignal, horn::high)) { // turn on - Train->mvOccupied->WarningSignal = horn::pressed(Train->mvOccupied->WarningSignal, horn::high, Train->has_single_horn_lever()); + Train->occupied->WarningSignal = horn::pressed(Train->occupied->WarningSignal, horn::high, Train->has_single_horn_lever()); // visual feedback Train->ggHornButton.UpdateValue(1.0); Train->ggHornHighButton.UpdateValue(1.0); @@ -112,9 +112,9 @@ void TTrain::OnCommand_hornhighactivate(TTrain *Train, command_data const &Comma else if (Command.action == GLFW_RELEASE) { // turn off - Train->mvOccupied->WarningSignal = horn::released(Train->mvOccupied->WarningSignal, horn::high); + Train->occupied->WarningSignal = horn::released(Train->occupied->WarningSignal, horn::high); // visual feedback - if (false == (Train->has_single_horn_lever() && TestFlag(Train->mvOccupied->WarningSignal, horn::low))) + if (false == (Train->has_single_horn_lever() && TestFlag(Train->occupied->WarningSignal, horn::low))) { // leave the single lever alone if it was moved to the other tone in the meantime Train->ggHornButton.UpdateValue(0.0); @@ -138,10 +138,10 @@ void TTrain::OnCommand_whistleactivate(TTrain *Train, command_data const &Comman if (Command.action == GLFW_PRESS) { // only need to react to press, sound will continue until stopped - if (false == TestFlag(Train->mvOccupied->WarningSignal, 4)) + if (false == TestFlag(Train->occupied->WarningSignal, 4)) { // turn on - Train->mvOccupied->WarningSignal |= 4; + Train->occupied->WarningSignal |= 4; // visual feedback Train->ggWhistleButton.UpdateValue(1.0); } @@ -149,7 +149,7 @@ void TTrain::OnCommand_whistleactivate(TTrain *Train, command_data const &Comman else if (Command.action == GLFW_RELEASE) { // turn off - Train->mvOccupied->WarningSignal &= ~4; + Train->occupied->WarningSignal &= ~4; // visual feedback Train->ggWhistleButton.UpdateValue(0.0); } @@ -165,14 +165,14 @@ void TTrain::OnCommand_radiotoggle(TTrain *Train, command_data const &Command) // NOTE: works without the switch in the 3d model too, to allow system reset after receiving radio-stop signal // only reacting to press, so the sound can loop uninterrupted // NOTE: flips the state directly rather than through radioenable/radiodisable, so it doesn't move the radioon_sw:/radiooff_sw: buttons - Train->mvOccupied->Radio = (false == Train->mvOccupied->Radio); + Train->occupied->Radio = (false == Train->occupied->Radio); } void TTrain::OnCommand_radioenable(TTrain *Train, command_data const &Command) { if (Command.action == GLFW_PRESS) { - Train->mvOccupied->Radio = true; + Train->occupied->Radio = true; // visual feedback if (Train->m_controlmapper.contains("radioon_sw:")) { @@ -192,7 +192,7 @@ void TTrain::OnCommand_radiodisable(TTrain *Train, command_data const &Command) { if (Command.action == GLFW_PRESS) { - Train->mvOccupied->Radio = false; + Train->occupied->Radio = false; // visual feedback if (Train->m_controlmapper.contains("radiooff_sw:")) { @@ -219,14 +219,14 @@ void TTrain::OnCommand_radiofusetoggle(TTrain *Train, command_data const &Comman // NOTE: flips the state directly rather than through radiofuseenable/radiofusedisable, so it doesn't move the // radiofuseon_sw:/radiofuseoff_sw: buttons - Train->mvOccupied->RadioFuse = (false == Train->mvOccupied->RadioFuse); + Train->occupied->RadioFuse = (false == Train->occupied->RadioFuse); } void TTrain::OnCommand_radiofuseenable(TTrain *Train, command_data const &Command) { if (Command.action == GLFW_PRESS) { - Train->mvOccupied->RadioFuse = true; + Train->occupied->RadioFuse = true; // visual feedback if (Train->m_controlmapper.contains("radiofuseon_sw:")) { @@ -246,7 +246,7 @@ void TTrain::OnCommand_radiofusedisable(TTrain *Train, command_data const &Comma { if (Command.action == GLFW_PRESS) { - Train->mvOccupied->RadioFuse = false; + Train->occupied->RadioFuse = false; // visual feedback if (Train->m_controlmapper.contains("radiofuseoff_sw:")) { @@ -268,7 +268,7 @@ void TTrain::OnCommand_radiochannelincrease(TTrain *Train, command_data const &C if (Command.action == GLFW_PRESS) { // the channel buttons of a radio switched off or without power do nothing - if (Train->mvOccupied->RadioPowered()) + if (Train->occupied->RadioPowered()) { command_data newCommand = Command; newCommand.param1 = Train->RadioChannel() + 1; @@ -289,7 +289,7 @@ void TTrain::OnCommand_radiochanneldecrease(TTrain *Train, command_data const &C if (Command.action == GLFW_PRESS) { - if (Train->mvOccupied->RadioPowered()) + if (Train->occupied->RadioPowered()) { command_data newCommand = Command; newCommand.param1 = Train->RadioChannel() - 1; @@ -320,7 +320,7 @@ void TTrain::OnCommand_radiostopsend(TTrain *Train, command_data const &Command) if (Command.action == GLFW_PRESS) { - if (Train->mvOccupied->RadioPowered()) + if (Train->occupied->RadioPowered()) { simulation::Region->RadioStop(Train->Dynamic()->GetPosition()); } @@ -338,7 +338,7 @@ void TTrain::OnCommand_radiostopenable(TTrain *Train, command_data const &Comman { if (Command.action == GLFW_PRESS && Train->ggRadioStop.GetValue() == 0) { - if (Train->mvOccupied->RadioPowered()) + if (Train->occupied->RadioPowered()) { simulation::Region->RadioStop(Train->Dynamic()->GetPosition()); } @@ -361,7 +361,7 @@ void TTrain::OnCommand_radiostoptest(TTrain *Train, command_data const &Command) if (Command.action == GLFW_PRESS) { - if (Train->RadioChannel() == 10 && Train->mvOccupied->RadioPowered()) + if (Train->RadioChannel() == 10 && Train->occupied->RadioPowered()) { Train->Dynamic()->RadioStop(); } @@ -379,7 +379,7 @@ void TTrain::OnCommand_radiocall1send(TTrain *Train, command_data const &Command { if (Command.action == GLFW_PRESS) { - if (Train->RadioChannel() != 10 && Train->mvOccupied->RadioPowered()) + if (Train->RadioChannel() != 10 && Train->occupied->RadioPowered()) { simulation::Events.queue_receivers(radio_message::call1, Train->Dynamic()->GetPosition()); } @@ -398,7 +398,7 @@ void TTrain::OnCommand_radiocall3send(TTrain *Train, command_data const &Command if (Command.action == GLFW_PRESS) { - if (Train->RadioChannel() != 10 && Train->mvOccupied->RadioPowered()) + if (Train->RadioChannel() != 10 && Train->occupied->RadioPowered()) { simulation::Events.queue_receivers(radio_message::call3, Train->Dynamic()->GetPosition()); } @@ -418,7 +418,7 @@ void TTrain::OnCommand_radiovolumeincrease(TTrain *Train, command_data const &Co if (Command.action == GLFW_PRESS) { // so do the volume buttons - if (Train->mvOccupied->RadioPowered()) + if (Train->occupied->RadioPowered()) { command_data newCommand = Command; newCommand.param1 = Train->m_radiovolume + 0.125; @@ -438,7 +438,7 @@ void TTrain::OnCommand_radiovolumedecrease(TTrain *Train, command_data const &Co if (Command.action == GLFW_PRESS) { - if (Train->mvOccupied->RadioPowered()) + if (Train->occupied->RadioPowered()) { command_data newCommand = Command; newCommand.param1 = Train->m_radiovolume - 0.125; diff --git a/vehicle/cab/sounds.cpp b/vehicle/cab/sounds.cpp index 01a40da0a..e189027e2 100644 --- a/vehicle/cab/sounds.cpp +++ b/vehicle/cab/sounds.cpp @@ -38,7 +38,7 @@ http://mozilla.org/MPL/2.0/. #include "Console.h" #include "application/application.h" #include "rendering/renderer.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include #include #include @@ -57,14 +57,14 @@ void TTrain::update_sounds(double const Deltatime) if (m_lastlocalbrakepressure != -1.f) { // calculate rate of pressure drop in local brake cylinder, once it's been initialized - auto const brakepressuredifference{mvOccupied->LocBrakePress - m_lastlocalbrakepressure}; + auto const brakepressuredifference{occupied->LocBrakePress - m_lastlocalbrakepressure}; m_localbrakepressurechange = static_cast(std::lerp(m_localbrakepressurechange, 10 * (brakepressuredifference / Deltatime), 0.1f)); } - m_lastlocalbrakepressure = static_cast(mvOccupied->LocBrakePress); + m_lastlocalbrakepressure = static_cast(occupied->LocBrakePress); // local brake, release if (rsSBHiss) { - if (m_localbrakepressurechange < -0.05f && mvOccupied->LocBrakePress > mvOccupied->BrakePress - 0.05) + if (m_localbrakepressurechange < -0.05f && occupied->LocBrakePress > occupied->BrakePress - 0.05) { rsSBHiss->gain(static_cast(std::clamp(rsSBHiss->m_amplitudeoffset + rsSBHiss->m_amplitudefactor * -m_localbrakepressurechange * 0.05, 0.0, 1.5))); rsSBHiss->play(sound_flags::exclusive | sound_flags::looping); @@ -102,12 +102,12 @@ void TTrain::update_sounds(double const Deltatime) // McZapkie-280302 - syczenie // TODO: softer volume reduction than plain abrupt stop, perhaps as reusable wrapper? - if (mvOccupied->BrakeHandle == TBrakeHandle::FV4a || mvOccupied->BrakeHandle == TBrakeHandle::FVel6) + if (occupied->BrakeHandle == TBrakeHandle::FV4a || occupied->BrakeHandle == TBrakeHandle::FVel6) { // upuszczanie z PG if (rsHiss) { - fPPress = std::lerp(fPPress, static_cast(mvOccupied->Handle->GetSound(s_fv4a_b)), 0.05f); + fPPress = std::lerp(fPPress, static_cast(occupied->Handle->GetSound(s_fv4a_b)), 0.05f); volume = fPPress > 0 ? rsHiss->m_amplitudefactor * fPPress * 0.25 + rsHiss->m_amplitudeoffset : 0; if (volume * brakevolumescale > 0.05) { @@ -122,7 +122,7 @@ void TTrain::update_sounds(double const Deltatime) // napelnianie PG if (rsHissU) { - fNPress = std::lerp(fNPress, static_cast(mvOccupied->Handle->GetSound(s_fv4a_u)), 0.25f); + fNPress = std::lerp(fNPress, static_cast(occupied->Handle->GetSound(s_fv4a_u)), 0.25f); volume = fNPress > 0 ? rsHissU->m_amplitudefactor * fNPress + rsHissU->m_amplitudeoffset : 0; if (volume * brakevolumescale > 0.05) { @@ -137,7 +137,7 @@ void TTrain::update_sounds(double const Deltatime) // upuszczanie przy naglym if (rsHissE) { - volume = mvOccupied->Handle->GetSound(s_fv4a_e) * rsHissE->m_amplitudefactor + rsHissE->m_amplitudeoffset; + volume = occupied->Handle->GetSound(s_fv4a_e) * rsHissE->m_amplitudefactor + rsHissE->m_amplitudeoffset; if (volume * brakevolumescale > 0.05) { rsHissE->gain(static_cast(volume * brakevolumescale)); @@ -151,7 +151,7 @@ void TTrain::update_sounds(double const Deltatime) // upuszczanie sterujacego fala if (rsHissX) { - volume = mvOccupied->Handle->GetSound(s_fv4a_x) * rsHissX->m_amplitudefactor + rsHissX->m_amplitudeoffset; + volume = occupied->Handle->GetSound(s_fv4a_x) * rsHissX->m_amplitudefactor + rsHissX->m_amplitudeoffset; if (volume * brakevolumescale > 0.05) { rsHissX->gain(static_cast(volume * brakevolumescale)); @@ -165,7 +165,7 @@ void TTrain::update_sounds(double const Deltatime) // upuszczanie z czasowego if (rsHissT) { - volume = mvOccupied->Handle->GetSound(s_fv4a_t) * rsHissT->m_amplitudefactor + +rsHissT->m_amplitudeoffset; + volume = occupied->Handle->GetSound(s_fv4a_t) * rsHissT->m_amplitudefactor + +rsHissT->m_amplitudeoffset; if (volume * brakevolumescale > 0.05) { rsHissT->gain(static_cast(volume * brakevolumescale)); @@ -183,7 +183,7 @@ void TTrain::update_sounds(double const Deltatime) // upuszczanie z PG if (rsHiss) { - fPPress = static_cast((4.0f * fPPress + std::max(0.0, mvOccupied->dpMainValve)) / (4.0f + 1.0f)); + fPPress = static_cast((4.0f * fPPress + std::max(0.0, occupied->dpMainValve)) / (4.0f + 1.0f)); volume = fPPress > 0.0f ? 2.0 * rsHiss->m_amplitudefactor * fPPress + rsHiss->m_amplitudeoffset : 0.0; if (volume > 0.05) { @@ -198,7 +198,7 @@ void TTrain::update_sounds(double const Deltatime) // napelnianie PG if (rsHissU) { - fNPress = static_cast((4.0f * fNPress + std::min(0.0, mvOccupied->dpMainValve)) / (4.0f + 1.0f)); + fNPress = static_cast((4.0f * fNPress + std::min(0.0, occupied->dpMainValve)) / (4.0f + 1.0f)); volume = fNPress < 0.0f ? -1.0 * rsHissU->m_amplitudefactor * fNPress + rsHissU->m_amplitudeoffset : 0.0; if (volume > 0.01) { @@ -215,14 +215,14 @@ void TTrain::update_sounds(double const Deltatime) // brakes if (rsBrake) { - if (mvOccupied->UnitBrakeForce > 10.0 && mvOccupied->Vel > 0.05) + if (occupied->UnitBrakeForce > 10.0 && occupied->Vel > 0.05) { auto const brakeforceratio{ - std::clamp(mvOccupied->UnitBrakeForce / std::max(1.0, mvOccupied->BrakeForceR(1.0, mvOccupied->Vel) / (mvOccupied->NAxles * std::max(1, mvOccupied->NBpA))), 0.0, 1.0)}; + std::clamp(occupied->UnitBrakeForce / std::max(1.0, occupied->BrakeForceR(1.0, occupied->Vel) / (occupied->NAxles * std::max(1, occupied->NBpA))), 0.0, 1.0)}; // HACK: in external view mute the sound rather than stop it, in case there's an opening bookend it'd (re)play on sound restart after returning inside - volume = FreeFlyModeFlag ? 0.0 : rsBrake->m_amplitudeoffset + std::sqrt(brakeforceratio * std::lerp(0.4, 1.0, mvOccupied->Vel / (1 + mvOccupied->Vmax))) * rsBrake->m_amplitudefactor; - rsBrake->pitch(static_cast(rsBrake->m_frequencyoffset + mvOccupied->Vel * rsBrake->m_frequencyfactor)); + volume = FreeFlyModeFlag ? 0.0 : rsBrake->m_amplitudeoffset + std::sqrt(brakeforceratio * std::lerp(0.4, 1.0, occupied->Vel / (1 + occupied->Vmax))) * rsBrake->m_amplitudefactor; + rsBrake->pitch(static_cast(rsBrake->m_frequencyoffset + occupied->Vel * rsBrake->m_frequencyfactor)); rsBrake->gain(static_cast(volume)); rsBrake->play(sound_flags::exclusive | sound_flags::looping); } @@ -242,7 +242,7 @@ void TTrain::update_sounds(double const Deltatime) if (dsbSlipAlarm) { // alarm przy poslizgu dla 181/182 - BOMBARDIER - if (mvControlled->SlippingWheels && DynamicObject->GetVelocity() > 1.0) + if (controlled->SlippingWheels && DynamicObject->GetVelocity() > 1.0) { dsbSlipAlarm->play(sound_flags::exclusive | sound_flags::looping); } @@ -296,7 +296,7 @@ void TTrain::update_sounds(double const Deltatime) update_sounds_runningnoise(*rsHuntingNoise); // modify calculated sound volume by hunting amount auto const huntingamount = std::lerp( - 0.0, 1.0, std::clamp((mvOccupied->Vel - DynamicObject->HuntingShake.fadein_begin) / (DynamicObject->HuntingShake.fadein_end - DynamicObject->HuntingShake.fadein_begin), 0.0, 1.0)); + 0.0, 1.0, std::clamp((occupied->Vel - DynamicObject->HuntingShake.fadein_begin) / (DynamicObject->HuntingShake.fadein_end - DynamicObject->HuntingShake.fadein_begin), 0.0, 1.0)); rsHuntingNoise->gain(static_cast(rsHuntingNoise->gain() * huntingamount)); } @@ -340,11 +340,11 @@ void TTrain::update_sounds(double const Deltatime) } // power-reliant sounds - if (mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable) + if (occupied->Power24vIsAvailable || occupied->Power110vIsAvailable) { // buzzer shp - if (mvOccupied->SecuritySystem.is_cabsignal_beeping()) + if (occupied->SecuritySystem.is_cabsignal_beeping()) { if (dsbBuzzerShp && false == dsbBuzzerShp->is_playing()) { @@ -363,7 +363,7 @@ void TTrain::update_sounds(double const Deltatime) // McZapkie-141102: SHP i czuwak, TODO: sygnalizacja kabinowa // hunter-091012: rozdzielenie alarmow - if (mvOccupied->SecuritySystem.is_beeping()) + if (occupied->SecuritySystem.is_beeping()) { if (dsbBuzzer && false == dsbBuzzer->is_playing()) { @@ -429,11 +429,11 @@ void TTrain::update_sounds(double const Deltatime) void TTrain::update_sounds_resonancenoise(sound_source &Sound) const { // frequency calculation - auto const normalizer{mvOccupied->Vmax * 0.01f}; - auto const soundfrequency{Sound.m_frequencyoffset + Sound.m_frequencyfactor * mvOccupied->Vel * normalizer}; + auto const normalizer{occupied->Vmax * 0.01f}; + auto const soundfrequency{Sound.m_frequencyoffset + Sound.m_frequencyfactor * occupied->Vel * normalizer}; // volume calculation - auto volume = Sound.m_amplitudeoffset + Sound.m_amplitudefactor * std::lerp(mvOccupied->Vel / (1 + mvOccupied->Vmax), 1.0, 0.5); // scale base volume between 0.5-1.0 + auto volume = Sound.m_amplitudeoffset + Sound.m_amplitudefactor * std::lerp(occupied->Vel / (1 + occupied->Vmax), 1.0, 0.5); // scale base volume between 0.5-1.0 if (volume > 0.05) { @@ -448,16 +448,16 @@ void TTrain::update_sounds_resonancenoise(sound_source &Sound) const void TTrain::update_sounds_runningnoise(sound_source &Sound) { // frequency calculation - auto const normalizer{(true == Sound.is_combined() ? mvOccupied->Vmax * 0.01f : 1.f)}; - auto const soundfrequency{Sound.m_frequencyoffset + Sound.m_frequencyfactor * mvOccupied->Vel * normalizer}; + auto const normalizer{(true == Sound.is_combined() ? occupied->Vmax * 0.01f : 1.f)}; + auto const soundfrequency{Sound.m_frequencyoffset + Sound.m_frequencyfactor * occupied->Vel * normalizer}; // volume calculation - auto volume = Sound.m_amplitudeoffset + Sound.m_amplitudefactor * std::lerp(mvOccupied->Vel / (1 + mvOccupied->Vmax), 1.0, + auto volume = Sound.m_amplitudeoffset + Sound.m_amplitudefactor * std::lerp(occupied->Vel / (1 + occupied->Vmax), 1.0, 0.5); // scale base volume between 0.5-1.0 - if (std::abs(mvOccupied->nrot) > 0.01) + if (std::abs(occupied->nrot) > 0.01) { // hamulce wzmagaja halas - auto const brakeforceratio{(std::clamp(mvOccupied->UnitBrakeForce / std::max(1.0, mvOccupied->BrakeForceR(1.0, mvOccupied->Vel) / (mvOccupied->NAxles * std::max(1, mvOccupied->NBpA))), 0.0, 1.0))}; + auto const brakeforceratio{(std::clamp(occupied->UnitBrakeForce / std::max(1.0, occupied->BrakeForceR(1.0, occupied->Vel) / (occupied->NAxles * std::max(1, occupied->NBpA))), 0.0, 1.0))}; volume *= 1 + 0.125 * brakeforceratio; } @@ -467,7 +467,7 @@ void TTrain::update_sounds_runningnoise(sound_source &Sound) // for single sample sounds muffle the playback at low speeds if (false == Sound.is_combined()) { - volume *= std::lerp(0.0, 1.0, std::clamp(mvOccupied->Vel / 25.0, 0.0, 1.0)); + volume *= std::lerp(0.0, 1.0, std::clamp(occupied->Vel / 25.0, 0.0, 1.0)); } if (volume > 0.05) @@ -490,7 +490,7 @@ void TTrain::update_sounds_radio() std::erase_if(m_radiomessages, [](auto const &source) { return false == source.second->is_playing(); }); } // adjust audibility of remaining messages based on current radio conditions - auto const radioenabled{mvOccupied->RadioPowered()}; + auto const radioenabled{occupied->RadioPowered()}; for (auto const &[messagechannel, messagesound] : m_radiomessages) { auto const volume{true == radioenabled && Dynamic()->Mechanik != nullptr && messagechannel == RadioChannel() ? m_radiovolume : 0.0}; @@ -500,7 +500,7 @@ void TTrain::update_sounds_radio() // radiostop if (m_radiostop) { - if (true == radioenabled && true == mvOccupied->RadioStopFlag) + if (true == radioenabled && true == occupied->RadioStopFlag) { m_radiostop->play(sound_flags::exclusive | sound_flags::looping); radio_message_played |= true; diff --git a/vehicle/cab/train.cpp b/vehicle/cab/train.cpp index 757be2871..32f5610ae 100644 --- a/vehicle/cab/train.cpp +++ b/vehicle/cab/train.cpp @@ -38,7 +38,7 @@ http://mozilla.org/MPL/2.0/. #include "Console.h" #include "application/application.h" #include "rendering/renderer.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include #include #include @@ -103,7 +103,7 @@ bool TTrain::Init(TDynamicObject *NewDynamicObject, bool e3d) ErrorLog( "Bad config: can't take control of inactive vehicle \"" + NewDynamicObject->asName + "\"" ); return false; */ - auto const activecab{(NewDynamicObject->MoverParameters->CabOccupied > 0 ? "1" : NewDynamicObject->MoverParameters->CabOccupied < 0 ? "2" : "p")}; + auto const activecab{(NewDynamicObject->physics->CabOccupied > 0 ? "1" : NewDynamicObject->physics->CabOccupied < 0 ? "2" : "p")}; NewDynamicObject->create_controller(activecab, NewDynamicObject->ctOwner != nullptr); } @@ -115,14 +115,14 @@ bool TTrain::Init(TDynamicObject *NewDynamicObject, bool e3d) fMainRelayTimer = 0; // Hunter, do k...y nędzy, ustawiaj wartości początkowe zmiennych! - iCabn = mvOccupied->CabOccupied > 0 ? 1 : mvOccupied->CabOccupied < 0 ? 2 : 0; + iCabn = occupied->CabOccupied > 0 ? 1 : occupied->CabOccupied < 0 ? 2 : 0; { Global.CurrentMaxTextureSize = Global.iMaxCabTextureSize; - auto const filename{mvOccupied->TypeName + ".mmd"}; + auto const filename{occupied->TypeName + ".mmd"}; LoadMMediaFile(filename); - InitializeCab(mvOccupied->CabOccupied, filename); + InitializeCab(occupied->CabOccupied, filename); Global.CurrentMaxTextureSize = Global.iMaxTextureSize; @@ -135,15 +135,15 @@ bool TTrain::Init(TDynamicObject *NewDynamicObject, bool e3d) // Ra: taka proteza - przesłanie kierunku do członów connected /* - if (mvControlled->DirActive > 0) + if (controlled->DirActive > 0) { // było do przodu - mvControlled->DirectionBackward(); - mvControlled->DirectionForward(); + controlled->DirectionBackward(); + controlled->DirectionForward(); } - else if (mvControlled->DirActive < 0) + else if (controlled->DirActive < 0) { - mvControlled->DirectionForward(); - mvControlled->DirectionBackward(); + controlled->DirectionForward(); + controlled->DirectionBackward(); } */ if (false == DynamicObject->Mechanik->AIControllFlag) @@ -157,7 +157,7 @@ bool TTrain::Init(TDynamicObject *NewDynamicObject, bool e3d) std::shared_ptr TTrain::GetTrainState(dictionary_source const &Extraparameters) { - if (mvOccupied == nullptr || mvControlled == nullptr) + if (occupied == nullptr || controlled == nullptr) { return nullptr; } @@ -169,22 +169,22 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const } dict->insert("name", DynamicObject->asName); - dict->insert("cab", mvOccupied->CabOccupied); - dict->insert("cabactive", mvOccupied->CabActive); - dict->insert("master", mvOccupied->CabMaster); + dict->insert("cab", occupied->CabOccupied); + dict->insert("cabactive", occupied->CabActive); + dict->insert("master", occupied->CabMaster); // basic systems state data - dict->insert("battery", mvOccupied->Power24vIsAvailable); - dict->insert("linebreaker", mvControlled->Mains); - dict->insert("main_init", mvControlled->MainsInitTimeCountdown < mvControlled->MainsInitTime && mvControlled->MainsInitTimeCountdown > 0.0); - dict->insert("main_ready", false == mvControlled->Mains && fHVoltage > 0.0 && mvControlled->MainsInitTimeCountdown <= 0.0); - dict->insert("converter", mvOccupied->Power110vIsAvailable); - dict->insert("converter_overload", mvControlled->ConvOvldFlag); - dict->insert("compress", mvControlled->CompressorFlag); - dict->insert("pant_compressor", mvPantographUnit->PantCompFlag); - dict->insert("lights_front", mvOccupied->iLights[VehicleEnd::front]); - dict->insert("lights_rear", mvOccupied->iLights[VehicleEnd::rear]); - dict->insert("off_from_dimmer", mvOccupied->currentDimPosition().isOff); - dict->insert("lights_compartments", mvOccupied->CompartmentLights.is_active || mvOccupied->CompartmentLights.is_disabled); + dict->insert("battery", occupied->Power24vIsAvailable); + dict->insert("linebreaker", controlled->Mains); + dict->insert("main_init", controlled->MainsInitTimeCountdown < controlled->MainsInitTime && controlled->MainsInitTimeCountdown > 0.0); + dict->insert("main_ready", false == controlled->Mains && fHVoltage > 0.0 && controlled->MainsInitTimeCountdown <= 0.0); + dict->insert("converter", occupied->Power110vIsAvailable); + dict->insert("converter_overload", controlled->ConvOvldFlag); + dict->insert("compress", controlled->CompressorFlag); + dict->insert("pant_compressor", pantographUnit->PantCompFlag); + dict->insert("lights_front", occupied->iLights[VehicleEnd::front]); + dict->insert("lights_rear", occupied->iLights[VehicleEnd::rear]); + dict->insert("off_from_dimmer", occupied->currentDimPosition().isOff); + dict->insert("lights_compartments", occupied->CompartmentLights.is_active || occupied->CompartmentLights.is_disabled); if (Dynamic()->Mechanik) { auto const *controller{Dynamic()->Mechanik}; @@ -194,55 +194,55 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const auto const *rearvehicle{controller->Vehicle(traindirection >= 0 ? VehicleEnd::rear : VehicleEnd::front)}; auto const frontvehicledirection{(frontvehicle->DirectionGet() == controller->Vehicle()->DirectionGet() ? 1 : -1)}; auto const rearvehicledirection{(rearvehicle->DirectionGet() == controller->Vehicle()->DirectionGet() ? 1 : -1)}; - auto const fronttrainlights{frontvehicle->MoverParameters->iLights[frontvehicledirection * cabmodifier >= 0 ? VehicleEnd::front : VehicleEnd::rear]}; - auto const reartrainlights{rearvehicle->MoverParameters->iLights[rearvehicledirection * cabmodifier >= 0 ? VehicleEnd::rear : VehicleEnd::front]}; + auto const fronttrainlights{frontvehicle->physics->iLights[frontvehicledirection * cabmodifier >= 0 ? VehicleEnd::front : VehicleEnd::rear]}; + auto const reartrainlights{rearvehicle->physics->iLights[rearvehicledirection * cabmodifier >= 0 ? VehicleEnd::rear : VehicleEnd::front]}; dict->insert("lights_train_front", fronttrainlights); dict->insert("lights_train_rear", reartrainlights); } else { // fallback, in the unlikely case we lose the controller - dict->insert("lights_train_front", mvOccupied->iLights[VehicleEnd::front]); - dict->insert("lights_train_rear", mvOccupied->iLights[VehicleEnd::rear]); + dict->insert("lights_train_front", occupied->iLights[VehicleEnd::front]); + dict->insert("lights_train_rear", occupied->iLights[VehicleEnd::rear]); } // reverser - dict->insert("direction", mvOccupied->DirActive); + dict->insert("direction", occupied->DirActive); // throttle - dict->insert("mainctrl_pos", mvControlled->MainCtrlPos); - dict->insert("mainctrl_pos_count", mvControlled->MainCtrlPosNo); - dict->insert("main_ctrl_actual_pos", mvControlled->MainCtrlActualPos); - dict->insert("scndctrl_pos", mvControlled->ScndCtrlPos); - dict->insert("dynamicbrake_pos", mvControlled->DynamicBrakeCtrlPos); - dict->insert("scnd_ctrl_actual_pos", mvControlled->ScndCtrlActualPos); - dict->insert("brakectrl_pos", mvControlled->fBrakeCtrlPos); - dict->insert("localbrake_pos", mvControlled->LocalBrakePosA); - dict->insert("new_speed", mvOccupied->NewSpeed); - dict->insert("speedctrl", mvOccupied->SpeedCtrlValue); - dict->insert("speedctrlpower", mvOccupied->SpeedCtrlUnit.DesiredPower); - dict->insert("speedctrlactive", mvOccupied->SpeedCtrlUnit.IsActive); - dict->insert("speedctrlstandby", mvOccupied->SpeedCtrlUnit.Standby); + dict->insert("mainctrl_pos", controlled->MainCtrlPos); + dict->insert("mainctrl_pos_count", controlled->MainCtrlPosNo); + dict->insert("main_ctrl_actual_pos", controlled->MainCtrlActualPos); + dict->insert("scndctrl_pos", controlled->ScndCtrlPos); + dict->insert("dynamicbrake_pos", controlled->DynamicBrakeCtrlPos); + dict->insert("scnd_ctrl_actual_pos", controlled->ScndCtrlActualPos); + dict->insert("brakectrl_pos", controlled->fBrakeCtrlPos); + dict->insert("localbrake_pos", controlled->LocalBrakePosA); + dict->insert("new_speed", occupied->NewSpeed); + dict->insert("speedctrl", occupied->SpeedCtrlValue); + dict->insert("speedctrlpower", occupied->SpeedCtrlUnit.DesiredPower); + dict->insert("speedctrlactive", occupied->SpeedCtrlUnit.IsActive); + dict->insert("speedctrlstandby", occupied->SpeedCtrlUnit.Standby); // brakes - dict->insert("manual_brake", mvOccupied->ManualBrakePos > 0); - bool const bEP = mvControlled->LocHandle->GetCP() > 0.2 || fEIMParams[0][5] > 0.01; + dict->insert("manual_brake", occupied->ManualBrakePos > 0); + bool const bEP = controlled->LocHandle->GetCP() > 0.2 || fEIMParams[0][5] > 0.01; dict->insert("dir_brake", bEP); bool bPN{false}; - auto const &brakevalve{*mvOccupied->Hamulec}; + auto const &brakevalve{*occupied->Hamulec}; if (auto const &brakevalvetype{typeid(brakevalve)}; brakevalvetype == typeid(TLSt) || brakevalvetype == typeid(TEStED)) { - TBrake *temp_ham = mvOccupied->Hamulec.get(); + TBrake *temp_ham = occupied->Hamulec.get(); bPN = static_cast(temp_ham)->GetEDBCP() > 0.2; } dict->insert("indir_brake", bPN); - dict->insert("emergency_brake", mvOccupied->AlarmChainFlag); - dict->insert("brake_delay_flag", mvOccupied->BrakeDelayFlag); - dict->insert("brake_op_mode_flag", mvOccupied->BrakeOpModeFlag); - dict->insert("pipelock", mvOccupied->LockPipe); + dict->insert("emergency_brake", occupied->AlarmChainFlag); + dict->insert("brake_delay_flag", occupied->BrakeDelayFlag); + dict->insert("brake_op_mode_flag", occupied->BrakeOpModeFlag); + dict->insert("pipelock", occupied->LockPipe); // other controls - dict->insert("ca", mvOccupied->SecuritySystem.is_vigilance_blinking()); - dict->insert("shp", mvOccupied->SecuritySystem.is_cabsignal_blinking()); + dict->insert("ca", occupied->SecuritySystem.is_vigilance_blinking()); + dict->insert("shp", occupied->SecuritySystem.is_cabsignal_blinking()); dict->insert("distance_counter", m_distancecounter); - dict->insert("pantpress", std::abs(mvPantographUnit->PantPress)); + dict->insert("pantpress", std::abs(pantographUnit->PantPress)); dict->insert("universal3", InstrumentLightActive); for (auto idx = 0; idx < ggUniversals.size(); idx++) { @@ -251,29 +251,29 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("universal" + std::to_string(idx), ggUniversals[idx].GetValue() > 0.5); } } - dict->insert("radio", mvOccupied->Radio); - dict->insert("radio_fuse", mvOccupied->RadioFuse); + dict->insert("radio", occupied->Radio); + dict->insert("radio_fuse", occupied->RadioFuse); dict->insert("radio_channel", RadioChannel()); dict->insert("radio_volume", m_radiovolume); - dict->insert("door_lock", mvOccupied->Doors.lock_enabled); - dict->insert("door_step", mvOccupied->Doors.step_enabled); - dict->insert("door_permit_left", mvOccupied->Doors.instances[VehicleSide::left].open_permit); - dict->insert("door_permit_right", mvOccupied->Doors.instances[VehicleSide::right].open_permit); + dict->insert("door_lock", occupied->Doors.lock_enabled); + dict->insert("door_step", occupied->Doors.step_enabled); + dict->insert("door_permit_left", occupied->Doors.instances[VehicleSide::left].open_permit); + dict->insert("door_permit_right", occupied->Doors.instances[VehicleSide::right].open_permit); // movement data - dict->insert("velocity", std::abs(mvOccupied->Vel)); - dict->insert("tractionforce", std::abs(mvOccupied->Ft)); - dict->insert("slipping_wheels", mvOccupied->SlippingWheels); - dict->insert("sanding", mvOccupied->SandDose); - dict->insert("odometer", mvOccupied->DistCounter); // distance run in the session, km - dict->insert("odometer_total", mvOccupied->Odometer.km); // the vehicle's odometer, kept between the sessions + dict->insert("velocity", std::abs(occupied->Vel)); + dict->insert("tractionforce", std::abs(occupied->Ft)); + dict->insert("slipping_wheels", occupied->SlippingWheels); + dict->insert("sanding", occupied->SandDose); + dict->insert("odometer", occupied->DistCounter); // distance run in the session, km + dict->insert("odometer_total", occupied->Odometer.km); // the vehicle's odometer, kept between the sessions // electric current data - dict->insert("traction_voltage", std::abs(mvPantographUnit->PantographVoltage)); - dict->insert("voltage", std::abs(mvControlled->EngineVoltage)); - dict->insert("im", std::abs(mvControlled->Im)); - dict->insert("fuse", mvControlled->FuseFlag); - dict->insert("epfuse", mvOccupied->EpFuse); - dict->insert("power_drawn", mvOccupied->EnergyMeter.first); - dict->insert("power_returned", mvOccupied->EnergyMeter.second); + dict->insert("traction_voltage", std::abs(pantographUnit->PantographVoltage)); + dict->insert("voltage", std::abs(controlled->EngineVoltage)); + dict->insert("im", std::abs(controlled->Im)); + dict->insert("fuse", controlled->FuseFlag); + dict->insert("epfuse", occupied->EpFuse); + dict->insert("power_drawn", occupied->EnergyMeter.first); + dict->insert("power_returned", occupied->EnergyMeter.second); // induction motor state data std::array const TXTT{"fd", "fdt", "fdb", "pd", "pdt", "pdb", "itothv", "1", "2", "3"}; @@ -314,20 +314,20 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("compressors_" + idx + "_car_no", std::get<2>(bCompressors[i])); } - bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; - TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); + bool kier = DynamicObject->DirectionGet() * occupied->CabOccupied > 0; + TDynamicObject *p = DynamicObject->GetFirstDynamic(occupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); int in = 0; while (p && in < 8) { - if (p->MoverParameters->inductionMotor.traction.maxPower > 1) + if (p->physics->inductionMotor.traction.maxPower > 1) { in++; - dict->insert("eimp_c" + std::to_string(in) + "_invno", p->MoverParameters->inductionMotor.inverterCount); - for (int j = 0; j < p->MoverParameters->inductionMotor.inverterCount; j++) + dict->insert("eimp_c" + std::to_string(in) + "_invno", p->physics->inductionMotor.inverterCount); + for (int j = 0; j < p->physics->inductionMotor.inverterCount; j++) { - dict->insert("eimp_c" + std::to_string(in) + "_inv" + std::to_string(j + 1) + "_act", p->MoverParameters->inductionMotor.inverters[j].IsActive); - dict->insert("eimp_c" + std::to_string(in) + "_inv" + std::to_string(j + 1) + "_error", p->MoverParameters->inductionMotor.inverters[j].Error); - dict->insert("eimp_c" + std::to_string(in) + "_inv" + std::to_string(j + 1) + "_allow", p->MoverParameters->inductionMotor.inverters[j].Activate); + dict->insert("eimp_c" + std::to_string(in) + "_inv" + std::to_string(j + 1) + "_act", p->physics->inductionMotor.inverters[j].IsActive); + dict->insert("eimp_c" + std::to_string(in) + "_inv" + std::to_string(j + 1) + "_error", p->physics->inductionMotor.inverters[j].Error); + dict->insert("eimp_c" + std::to_string(in) + "_inv" + std::to_string(j + 1) + "_allow", p->physics->inductionMotor.inverters[j].Activate); } } p = kier ? p->Next(Coupling::control) : p->Prev(Coupling::control); @@ -408,30 +408,30 @@ TTrain::state_t TTrain::get_state() const static_cast(iCabn), btHaslerBrakes.GetValue(), btHaslerCurrent.GetValue(), - mvOccupied->SecuritySystem.is_beeping(), + occupied->SecuritySystem.is_beeping(), btLampkaHVoltageB.GetValue(), fTachoVelocity, - static_cast(mvOccupied->Compressor), - static_cast(mvOccupied->PipePress), - static_cast(mvOccupied->BrakePress), - static_cast(mvPantographUnit->PantPress), + static_cast(occupied->Compressor), + static_cast(occupied->PipePress), + static_cast(occupied->BrakePress), + static_cast(pantographUnit->PantPress), fHVoltage, - {fHCurrent[mvControlled->TrainType == train_type::emu ? 0 : 1], fHCurrent[2], fHCurrent[3]}, + {fHCurrent[controlled->TrainType == train_type::emu ? 0 : 1], fHCurrent[2], fHCurrent[3]}, ggLVoltage.GetValue(), - mvOccupied->DistCounter, + occupied->DistCounter, static_cast(RadioChannel()), btLampkaSpringBrakeActive.GetValue(), btLampkaNapNastHam.GetValue(), - mvOccupied->DirActive > 0, - mvOccupied->DirActive < 0, - mvOccupied->Doors.instances[mvOccupied->CabOccupied < 0 ? VehicleSide::right : VehicleSide::left].open_permit, - mvOccupied->Doors.instances[mvOccupied->CabOccupied < 0 ? VehicleSide::right : VehicleSide::left].is_open, - mvOccupied->Doors.instances[mvOccupied->CabOccupied < 0 ? VehicleSide::left : VehicleSide::right].open_permit, - mvOccupied->Doors.instances[mvOccupied->CabOccupied < 0 ? VehicleSide::left : VehicleSide::right].is_open, - mvOccupied->Doors.step_enabled, - mvOccupied->Power24vIsAvailable, + occupied->DirActive > 0, + occupied->DirActive < 0, + occupied->Doors.instances[occupied->CabOccupied < 0 ? VehicleSide::right : VehicleSide::left].open_permit, + occupied->Doors.instances[occupied->CabOccupied < 0 ? VehicleSide::right : VehicleSide::left].is_open, + occupied->Doors.instances[occupied->CabOccupied < 0 ? VehicleSide::left : VehicleSide::right].open_permit, + occupied->Doors.instances[occupied->CabOccupied < 0 ? VehicleSide::left : VehicleSide::right].is_open, + occupied->Doors.step_enabled, + occupied->Power24vIsAvailable, 0, - mvOccupied->LockPipe, + occupied->LockPipe, btLampkaRadioMessage.GetValue(), }; } @@ -439,21 +439,21 @@ TTrain::state_t TTrain::get_state() const bool TTrain::is_eztoer() const { - return mvControlled->TrainType == train_type::emu && mvOccupied->BrakeSubsystem == TBrakeSubSystem::ss_ESt && mvControlled->Power24vIsAvailable == true && mvControlled->EpFuse == true && - mvControlled->DirActive != 0; // od yB + return controlled->TrainType == train_type::emu && occupied->BrakeSubsystem == TBrakeSubSystem::ss_ESt && controlled->Power24vIsAvailable == true && controlled->EpFuse == true && + controlled->DirActive != 0; // od yB } -// mover master controller to specified position +// physics master controller to specified position void TTrain::set_master_controller(double const Position) { - auto positionchange{std::min(static_cast(Position), mvControlled->CoupledCtrl ? mvControlled->MainCtrlPosNo + mvControlled->ScndCtrlPosNo : mvControlled->MainCtrlPosNo) - - (mvControlled->CoupledCtrl ? mvControlled->MainCtrlPos + mvControlled->ScndCtrlPos : mvControlled->MainCtrlPos)}; - while (positionchange < 0 && true == mvControlled->DecMainCtrl(1)) + auto positionchange{std::min(static_cast(Position), controlled->CoupledCtrl ? controlled->MainCtrlPosNo + controlled->ScndCtrlPosNo : controlled->MainCtrlPosNo) - + (controlled->CoupledCtrl ? controlled->MainCtrlPos + controlled->ScndCtrlPos : controlled->MainCtrlPos)}; + while (positionchange < 0 && true == controlled->DecMainCtrl(1)) { ++positionchange; } - while (positionchange > 0 && true == mvControlled->IncMainCtrl(1)) + while (positionchange > 0 && true == controlled->IncMainCtrl(1)) { --positionchange; } @@ -463,16 +463,16 @@ void TTrain::set_master_controller(double const Position) void TTrain::set_train_brake(double const Position) { - auto const originalbrakeposition{static_cast(100.0 * mvOccupied->fBrakeCtrlPos)}; - mvOccupied->BrakeLevelSet(Position); + auto const originalbrakeposition{static_cast(100.0 * occupied->fBrakeCtrlPos)}; + occupied->BrakeLevelSet(Position); - if (static_cast(100.0 * mvOccupied->fBrakeCtrlPos) == originalbrakeposition) + if (static_cast(100.0 * occupied->fBrakeCtrlPos) == originalbrakeposition) { return; } // sound feedback if the lever movement activates one of the switches - if (true == is_eztoer() && false == ((originalbrakeposition / 100 == 0 || originalbrakeposition / 100 >= 5) && (mvOccupied->BrakeCtrlPos == 0 || mvOccupied->BrakeCtrlPos >= 5)) && dsbPneumaticSwitch) + if (true == is_eztoer() && false == ((originalbrakeposition / 100 == 0 || originalbrakeposition / 100 >= 5) && (occupied->BrakeCtrlPos == 0 || occupied->BrakeCtrlPos >= 5)) && dsbPneumaticSwitch) { dsbPneumaticSwitch->play(); } @@ -482,8 +482,8 @@ void TTrain::zero_charging_train_brake() { using enum TBrakeHandle; - if (mvOccupied->BrakeCtrlPos == -1 && DynamicObject->Controller != AIdriver && Global.iFeedbackMode < 3 && - (mvOccupied->BrakeHandle == FVel6 || mvOccupied->BrakeHandle == MHZ_EN57 || mvOccupied->BrakeHandle == MHZ_K8P)) + if (occupied->BrakeCtrlPos == -1 && DynamicObject->Controller != AIdriver && Global.iFeedbackMode < 3 && + (occupied->BrakeHandle == FVel6 || occupied->BrakeHandle == MHZ_EN57 || occupied->BrakeHandle == MHZ_K8P)) { // Odskakiwanie hamulce EP set_train_brake(0); @@ -495,19 +495,19 @@ void TTrain::set_train_brake_speed(TDynamicObject *Vehicle, int const Speed) // visual feedback // TODO: add setting indicator to vehicle class, for external lever/indicator - if (true == Vehicle->MoverParameters->BrakeDelaySwitch(Speed) && Vehicle == DynamicObject) + if (true == Vehicle->physics->BrakeDelaySwitch(Speed) && Vehicle == DynamicObject) { if (ggBrakeProfileCtrl.SubModel != nullptr) { - ggBrakeProfileCtrl.UpdateValue((mvOccupied->BrakeDelayFlag & bdelay_R) != 0 ? 2.0 : static_cast(mvOccupied->BrakeDelayFlag - 1), dsbSwitch); + ggBrakeProfileCtrl.UpdateValue((occupied->BrakeDelayFlag & bdelay_R) != 0 ? 2.0 : static_cast(occupied->BrakeDelayFlag - 1), dsbSwitch); } if (ggBrakeProfileG.SubModel != nullptr) { - ggBrakeProfileG.UpdateValue(mvOccupied->BrakeDelayFlag == bdelay_G ? 1.0 : 0.0, dsbSwitch); + ggBrakeProfileG.UpdateValue(occupied->BrakeDelayFlag == bdelay_G ? 1.0 : 0.0, dsbSwitch); } if (ggBrakeProfileR.SubModel != nullptr) { - ggBrakeProfileR.UpdateValue((mvOccupied->BrakeDelayFlag & bdelay_R) != 0 ? 1.0 : 0.0, dsbSwitch); + ggBrakeProfileR.UpdateValue((occupied->BrakeDelayFlag & bdelay_R) != 0 ? 1.0 : 0.0, dsbSwitch); } } } @@ -515,17 +515,17 @@ void TTrain::set_train_brake_speed(TDynamicObject *Vehicle, int const Speed) void TTrain::set_paired_open_motor_connectors_button(bool const State) { - if (mvControlled->TrainType == train_type::et41 || mvControlled->TrainType == train_type::et42) + if (controlled->TrainType == train_type::et41 || controlled->TrainType == train_type::et42) { // crude implementation of the button affecting entire unit for multi-unit engines // TODO: rework it into part of standard command propagation system - if (mvControlled->Couplers[VehicleEnd::front].Connected != nullptr && true == mvControlled->Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::permanent)) + if (controlled->Couplers[VehicleEnd::front].Connected != nullptr && true == controlled->Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::permanent)) { - mvControlled->Couplers[VehicleEnd::front].Connected->StLinSwitchOff = State; + controlled->Couplers[VehicleEnd::front].Connected->StLinSwitchOff = State; } - if (mvControlled->Couplers[VehicleEnd::rear].Connected != nullptr && true == mvControlled->Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::permanent)) + if (controlled->Couplers[VehicleEnd::rear].Connected != nullptr && true == controlled->Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::permanent)) { - mvControlled->Couplers[VehicleEnd::rear].Connected->StLinSwitchOff = State; + controlled->Couplers[VehicleEnd::rear].Connected->StLinSwitchOff = State; } } } @@ -551,18 +551,18 @@ void TTrain::UpdateCab() // Ra: przesiadka, jeśli AI zmieniło kabinę (a człon?)... if (DynamicObject->Mechanik // może nie być? && DynamicObject->Mechanik->AIControllFlag && iCabn != ( // numer kabiny (-1: kabina B) - mvOccupied->CabOccupied == -1 ? 2 : mvOccupied->CabOccupied)) + occupied->CabOccupied == -1 ? 2 : occupied->CabOccupied)) { - InitializeCab(mvOccupied->CabOccupied, mvOccupied->TypeName + ".mmd"); + InitializeCab(occupied->CabOccupied, occupied->TypeName + ".mmd"); } - iCabn = mvOccupied->CabOccupied == -1 ? 2 : mvOccupied->CabOccupied; + iCabn = occupied->CabOccupied == -1 ? 2 : occupied->CabOccupied; } void TTrain::add_distance(double const Distance) { - auto const meterenabled{m_distancecounter >= 0 && (mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable)}; + auto const meterenabled{m_distancecounter >= 0 && (occupied->Power24vIsAvailable || occupied->Power110vIsAvailable)}; if (true == meterenabled) { @@ -580,22 +580,22 @@ bool TTrain::CabChange(int iDirection) { // jeśli prowadzi AI albo jest w innym członie // jak AI prowadzi, to nie można mu mieszać - if (std::abs(mvOccupied->CabOccupied + iDirection) > 1) + if (std::abs(occupied->CabOccupied + iDirection) > 1) return false; // ewentualna zmiana pojazdu - mvOccupied->CabOccupied += iDirection; + occupied->CabOccupied += iDirection; } else { // jeśli pojazd prowadzony ręcznie albo wcale (wagon) - mvOccupied->CabDeactivisationAuto(); - if (mvOccupied->ChangeCab(iDirection) && InitializeCab(mvOccupied->CabOccupied, mvOccupied->TypeName + ".mmd")) + occupied->CabDeactivisationAuto(); + if (occupied->ChangeCab(iDirection) && InitializeCab(occupied->CabOccupied, occupied->TypeName + ".mmd")) { // zmiana kabiny w ramach tego samego pojazdu - mvOccupied->CabActivisationAuto(); // załączenie rozrządu (wirtualne kabiny) + occupied->CabActivisationAuto(); // załączenie rozrządu (wirtualne kabiny) DynamicObject->Mechanik->DirectionChange(); return true; // udało się zmienić kabinę } // aktywizacja poprzedniej, bo jeszcze nie wiadomo, czy jakiś pojazd jest - mvOccupied->CabActivisationAuto(); + occupied->CabActivisationAuto(); } return false; // ewentualna zmiana pojazdu } @@ -616,36 +616,36 @@ void TTrain::DynamicSet(TDynamicObject *d) // jeździć dobrze // również hamowanie wykonuje się zaworem w członie, a nie w silnikowym... DynamicObject = d; // jedyne miejsce zmiany - mvControlled = d ? DynamicObject->MoverParameters : nullptr; // albo silnikowy w EZT - mvOccupied = mvControlled; + controlled = d ? DynamicObject->physics : nullptr; // albo silnikowy w EZT + occupied = controlled; if (DynamicObject == nullptr) { return; } - mvControlled = DynamicObject->FindPowered()->MoverParameters; - mvSecond = nullptr; // gdyby się nic nie znalazło - if (mvOccupied->Power > 1.0) // dwuczłonowe lub ukrotnienia, żeby nie szukać każdorazowo + controlled = DynamicObject->FindPowered()->physics; + secondUnit = nullptr; // gdyby się nic nie znalazło + if (occupied->Power > 1.0) // dwuczłonowe lub ukrotnienia, żeby nie szukać każdorazowo { - if (mvOccupied->Couplers[1].Connected != nullptr && mvOccupied->Couplers[1].AllowedFlag.HasAny(Coupling::control)) + if (occupied->Couplers[1].Connected != nullptr && occupied->Couplers[1].AllowedFlag.HasAny(Coupling::control)) { // gdy jest człon od sprzęgu 1, a sprzęg łączony // warsztatowo (powiedzmy) - if (mvOccupied->Couplers[1].Connected->Power > 1.0) // ten drugi ma moc - mvSecond = mvOccupied->Couplers[1].Connected; // wskaźnik na drugiego + if (occupied->Couplers[1].Connected->Power > 1.0) // ten drugi ma moc + secondUnit = occupied->Couplers[1].Connected; // wskaźnik na drugiego } - else if (mvOccupied->Couplers[0].Connected != nullptr && mvOccupied->Couplers[0].AllowedFlag.HasAny(Coupling::control)) + else if (occupied->Couplers[0].Connected != nullptr && occupied->Couplers[0].AllowedFlag.HasAny(Coupling::control)) { // gdy jest człon od sprzęgu 0, a sprzęg łączony // warsztatowo (powiedzmy) - if (mvOccupied->Couplers[0].Connected->Power > 1.0) // ale ten drugi ma moc - mvSecond = mvOccupied->Couplers[0].Connected; // wskaźnik na drugiego + if (occupied->Couplers[0].Connected->Power > 1.0) // ale ten drugi ma moc + secondUnit = occupied->Couplers[0].Connected; // wskaźnik na drugiego } } // cache nearest unit equipped with pantographs { auto *lookup{DynamicObject->FindPantographCarrier()}; // HACK: set pointer to existing vehicle to avoid error checking all over the place - mvPantographUnit = lookup != nullptr ? lookup->MoverParameters : mvControlled; + pantographUnit = lookup != nullptr ? lookup->physics : controlled; } }; @@ -813,7 +813,7 @@ void TTrain::radio_message(sound_source *Message, int const Channel) m_radiomessages.emplace_back(Channel, std::make_shared(m_radiosound)); // assign sound to the template and play it auto &message = *m_radiomessages.back().second.get(); - auto const radioenabled{mvOccupied->RadioPowered()}; + auto const radioenabled{occupied->RadioPowered()}; auto const volume{true == radioenabled && Dynamic()->Mechanik != nullptr && Channel == RadioChannel() ? 1.0 : 0.0}; message.copy_sounds(*Message).gain(static_cast(volume)).play(); } diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index 538fc968b..3409f383e 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -38,7 +38,7 @@ http://mozilla.org/MPL/2.0/. #include "Console.h" #include "application/application.h" #include "rendering/renderer.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include #include #include @@ -65,7 +65,7 @@ bool TTrain::Update(double const Deltatime) updateUnitStates(); updateFeedbackGauges(); updateConverterOverload(Deltatime); - auto const lowvoltagepower{mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable}; + auto const lowvoltagepower{occupied->Power24vIsAvailable || occupied->Power110vIsAvailable}; updateSecondUnitGauges(); updateClock(); @@ -74,12 +74,12 @@ bool TTrain::Update(double const Deltatime) /* if (ggZbS.SubModel) { - ggZbS.UpdateValue(mvOccupied->Handle->GetCP()); + ggZbS.UpdateValue(occupied->Handle->GetCP()); ggZbS.Update(); } */ // replacement for the above. TODO: move it to a more suitable place - m_brakehandlecp = mvOccupied->Handle->GetCP(); + m_brakehandlecp = occupied->Handle->GetCP(); updateEngineGauges(); updateBasicLamps(); @@ -103,15 +103,15 @@ bool TTrain::Update(double const Deltatime) updateAuxiliaryButtons(lowvoltagepower); // wyprowadzenie sygnałów dla haslera na PoKeys (zaznaczanie na taśmie) - btHaslerBrakes.Turn(mvOccupied->BrakePress > 0.4); // ciśnienie w cylindrach - btHaslerCurrent.Turn(mvOccupied->Im != 0.0); // prąd na silnikach + btHaslerBrakes.Turn(occupied->BrakePress > 0.4); // ciśnienie w cylindrach + btHaslerCurrent.Turn(occupied->Im != 0.0); // prąd na silnikach updateCabLightLevels(); // anti slip system activation, maintained while the control button is down - if (mvOccupied->BrakeSystem != TBrakeSystem::ElectroPneumatic && ggAntiSlipButton.GetDesiredValue() > 0.95) + if (occupied->BrakeSystem != TBrakeSystem::ElectroPneumatic && ggAntiSlipButton.GetDesiredValue() > 0.95) { - mvControlled->AntiSlippingBrake(); + controlled->AntiSlippingBrake(); } // screens @@ -122,13 +122,13 @@ bool TTrain::Update(double const Deltatime) } // update direction relay - if (prevBatState != mvOccupied->Power24vIsAvailable) + if (prevBatState != occupied->Power24vIsAvailable) SetupDirectionRelays(); - if (prevDirection != mvOccupied->DirActive) + if (prevDirection != occupied->DirActive) UpdateDirectionRelays(); - prevBatState = mvOccupied->Power24vIsAvailable; - prevDirection = mvOccupied->DirActive; + prevBatState = occupied->Power24vIsAvailable; + prevDirection = occupied->DirActive; // sounds update_sounds(Deltatime); @@ -140,12 +140,12 @@ bool TTrain::Update(double const Deltatime) void TTrain::updateLineBreakerState(double const Deltatime) { // line breaker: - if (m_linebreakerstate == linebreaker::state::open && true == mvControlled->Mains) + if (m_linebreakerstate == linebreaker::state::open && true == controlled->Mains) { // crude way to sync state of the linebreaker with ai-issued commands m_linebreakerstate = linebreaker::state::closed; } - if (m_linebreakerstate == linebreaker::state::closed && false == (mvControlled->Mains || mvControlled->diesel.startupRequested)) + if (m_linebreakerstate == linebreaker::state::closed && false == (controlled->Mains || controlled->diesel.startupRequested)) { // crude way to catch cases where the main was knocked out // because the state of the line breaker isn't changed to match, we need to do it here manually @@ -153,7 +153,7 @@ void TTrain::updateLineBreakerState(double const Deltatime) } if (is_hold_coil_lever(ggMainOffButton) && hold_coil_lever::cuts_off(ggMainOffButton.GetDesiredValue())) { - if (true == mvControlled->Mains) + if (true == controlled->Mains) { // the line breaker was closed with the hold coil lever off, by the AI or through the control cable: // put the lever back on to match, like the line breaker state above @@ -171,7 +171,7 @@ void TTrain::updateLineBreakerState(double const Deltatime) ggIgnitionKey.GetDesiredValue() > 0.95) { // HACK: fallback // keep track of period the line breaker button is held down, to determine when/if circuit closes - if (mvControlled->MainSwitchCheck()) + if (controlled->MainSwitchCheck()) { fMainRelayTimer += static_cast(Deltatime); } @@ -186,7 +186,7 @@ void TTrain::updateLineBreakerState(double const Deltatime) // if the button disconnecting the line breaker is down prevent the timer from accumulating fMainRelayTimer = 0.0f; } - if (m_linebreakerstate == linebreaker::state::open && fMainRelayTimer > mvControlled->InitialCtrlDelay) + if (m_linebreakerstate == linebreaker::state::open && fMainRelayTimer > controlled->InitialCtrlDelay) { // wlaczanie WSa z opoznieniem // mark the line breaker as ready to close; for electric series vehicles with impulse switch the setup is completed on button release @@ -194,10 +194,10 @@ void TTrain::updateLineBreakerState(double const Deltatime) } // for diesels and/or vehicles with toggle switch setup we complete the engine start here // TODO: make it a test for main_on_bt of type push_delayed instead - if (m_linebreakerstate == linebreaker::state::closing && (ggMainOnButton.SubModel == nullptr || mvControlled->EngineType != TEngineType::ElectricSeriesMotor)) + if (m_linebreakerstate == linebreaker::state::closing && (ggMainOnButton.SubModel == nullptr || controlled->EngineType != TEngineType::ElectricSeriesMotor)) { // try to finalize state change of the line breaker, set the state based on the outcome - m_linebreakerstate = mvControlled->MainSwitch(true, mvControlled->MainSwitchRange()) ? linebreaker::state::closed : linebreaker::state::open; + m_linebreakerstate = controlled->MainSwitch(true, controlled->MainSwitchRange()) ? linebreaker::state::closed : linebreaker::state::open; } } @@ -215,7 +215,7 @@ void TTrain::updateTimers(double const Deltatime) doorpermittimer -= static_cast(Deltatime); if (doorpermittimer < 0.f) { - mvOccupied->OperateDoors(static_cast(idx), true); + occupied->OperateDoors(static_cast(idx), true); } } @@ -244,18 +244,18 @@ void TTrain::updateDoorAndDirectionStates() { m_doors = DynamicObject->Mechanik->IsAnyDoorOpen[VehicleSide::right] || DynamicObject->Mechanik->IsAnyDoorOpen[VehicleSide::left]; m_doorpermits = DynamicObject->Mechanik->IsAnyDoorPermitActive[VehicleSide::right] || DynamicObject->Mechanik->IsAnyDoorPermitActive[VehicleSide::left]; - m_doorspermitleft = mvOccupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right].open_permit && - (simulation::Time.data().wSecond % 2 < 1 || mvOccupied->DoorsPermitLightBlinking < 1 || - mvOccupied->DoorsPermitLightBlinking < 2 && DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right] || - (mvOccupied->DoorsPermitLightBlinking < 3 && DynamicObject->Mechanik->IsAnyDoorOnlyOpen[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right])); - m_doorspermitright = mvOccupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left].open_permit && - (simulation::Time.data().wSecond % 2 < 1 || mvOccupied->DoorsPermitLightBlinking < 1 || - mvOccupied->DoorsPermitLightBlinking < 2 && DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left] || - (mvOccupied->DoorsPermitLightBlinking < 3 && DynamicObject->Mechanik->IsAnyDoorOnlyOpen[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left])); + m_doorspermitleft = occupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right].open_permit && + (simulation::Time.data().wSecond % 2 < 1 || occupied->DoorsPermitLightBlinking < 1 || + occupied->DoorsPermitLightBlinking < 2 && DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right] || + (occupied->DoorsPermitLightBlinking < 3 && DynamicObject->Mechanik->IsAnyDoorOnlyOpen[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right])); + m_doorspermitright = occupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left].open_permit && + (simulation::Time.data().wSecond % 2 < 1 || occupied->DoorsPermitLightBlinking < 1 || + occupied->DoorsPermitLightBlinking < 2 && DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left] || + (occupied->DoorsPermitLightBlinking < 3 && DynamicObject->Mechanik->IsAnyDoorOnlyOpen[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left])); } - m_dirforward = mvControlled->DirActive > 0; - m_dirneutral = mvControlled->DirActive == 0; - m_dirbackward = mvControlled->DirActive < 0; + m_dirforward = controlled->DirActive > 0; + m_dirneutral = controlled->DirActive == 0; + m_dirbackward = controlled->DirActive < 0; } // passes the user commands received by the vehicle to their handlers @@ -276,7 +276,7 @@ void TTrain::processReceivedCommands() // debug data if (commanddata.action == GLFW_PRESS) { - WriteLog(mvOccupied->Name + " received command: [" + simulation::Commands_descriptions[static_cast(commanddata.command)].name + "]"); + WriteLog(occupied->Name + " received command: [" + simulation::Commands_descriptions[static_cast(commanddata.command)].name + "]"); } // pass the command to the assigned handler lookup->second(this, commanddata); @@ -288,7 +288,7 @@ void TTrain::processReceivedCommands() void TTrain::returnMasterController(double const Deltatime) { // nie blokujemy AI - if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag && (mvOccupied->TrainType == train_type::et40 || mvOccupied->TrainType == train_type::ep05 || mvOccupied->HasCamshaft)) + if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag && (occupied->TrainType == train_type::et40 || occupied->TrainType == train_type::ep05 || occupied->HasCamshaft)) { // dla ET40 i EU05 automatyczne cofanie nastawnika - i tak nie będzie to działać dobrze... // TODO: use deltatime to stabilize speed @@ -304,14 +304,14 @@ void TTrain::returnMasterController(double const Deltatime) if (m_mastercontrollerreturndelay < 0.f) { m_mastercontrollerreturndelay = EU07_CONTROLLER_BASERETURNDELAY; - if (mvOccupied->MainCtrlPos > mvOccupied->MainCtrlActualPos) + if (occupied->MainCtrlPos > occupied->MainCtrlActualPos) { - mvOccupied->DecMainCtrl(1); + occupied->DecMainCtrl(1); } - else if (mvOccupied->MainCtrlPos < mvOccupied->MainCtrlActualPos) + else if (occupied->MainCtrlPos < occupied->MainCtrlActualPos) { // Ra 15-01: a to nie miało być tylko cofanie? - mvOccupied->IncMainCtrl(1); + occupied->IncMainCtrl(1); } } } @@ -324,12 +324,12 @@ void TTrain::updateTachometer(double const Deltatime) // McZapkie: predkosc wyswietlana na tachometrze brana jest z obrotow kol auto const maxtacho{3.0}; - double maxSpeed = mvControlled->Vmax * 1.05; // zachowanie starej logiki jak nie ma definicji max tarczki - if (mvOccupied->maxTachoSpeed != 0) + double maxSpeed = controlled->Vmax * 1.05; // zachowanie starej logiki jak nie ma definicji max tarczki + if (occupied->maxTachoSpeed != 0) { - maxSpeed = mvOccupied->maxTachoSpeed; + maxSpeed = occupied->maxTachoSpeed; } - fTachoVelocity = static_cast(std::min(std::abs(11.31 * mvControlled->WheelDiameter * mvControlled->nrot), maxSpeed)); + fTachoVelocity = static_cast(std::min(std::abs(11.31 * controlled->WheelDiameter * controlled->nrot), maxSpeed)); { // skacze osobna zmienna float ff = simulation::Time.data().wSecond; // skacze co sekunde - pol sekundy // pomiar, pol sekundy ustawienie @@ -359,24 +359,24 @@ void TTrain::updateTachometer(double const Deltatime) void TTrain::updateVoltagesAndCurrents() { // Ra 2014-09: napięcia i prądy muszą być ustalone najpierw, bo wysyłane są ewentualnie na PoKeys - if (mvControlled->EngineType != TEngineType::DieselElectric && mvControlled->EngineType != TEngineType::ElectricInductionMotor) + if (controlled->EngineType != TEngineType::DieselElectric && controlled->EngineType != TEngineType::ElectricInductionMotor) { // Ra 2014-09: czy taki rozdzia? ma sens? - fHVoltage = static_cast(std::max(mvControlled->PantographVoltage, - mvControlled->GetTrainsetHighVoltage())); // Winger czy to nie jest zle? + fHVoltage = static_cast(std::max(controlled->PantographVoltage, + controlled->GetTrainsetHighVoltage())); // Winger czy to nie jest zle? } - // *mvControlled->Mains); + // *controlled->Mains); else { - fHVoltage = static_cast(mvControlled->EngineVoltage); + fHVoltage = static_cast(controlled->EngineVoltage); } if (ShowNextCurrent) { // jeśli pokazywać drugi człon - if (mvSecond) + if (secondUnit) { // o ile jest ten drugi - fHCurrent[0] = static_cast(mvSecond->ShowCurrent(0) * 1.05); - fHCurrent[1] = static_cast(mvSecond->ShowCurrent(1) * 1.05); - fHCurrent[2] = static_cast(mvSecond->ShowCurrent(2) * 1.05); - fHCurrent[3] = static_cast(mvSecond->ShowCurrent(3) * 1.05); + fHCurrent[0] = static_cast(secondUnit->ShowCurrent(0) * 1.05); + fHCurrent[1] = static_cast(secondUnit->ShowCurrent(1) * 1.05); + fHCurrent[2] = static_cast(secondUnit->ShowCurrent(2) * 1.05); + fHCurrent[3] = static_cast(secondUnit->ShowCurrent(3) * 1.05); } else { @@ -388,10 +388,10 @@ void TTrain::updateVoltagesAndCurrents() } else { // normalne pokazywanie - fHCurrent[0] = static_cast(mvControlled->ShowCurrent(0)); - fHCurrent[1] = static_cast(mvControlled->ShowCurrent(1)); - fHCurrent[2] = static_cast(mvControlled->ShowCurrent(2)); - fHCurrent[3] = static_cast(mvControlled->ShowCurrent(3)); + fHCurrent[0] = static_cast(controlled->ShowCurrent(0)); + fHCurrent[1] = static_cast(controlled->ShowCurrent(1)); + fHCurrent[2] = static_cast(controlled->ShowCurrent(2)); + fHCurrent[3] = static_cast(controlled->ShowCurrent(3)); } } @@ -419,8 +419,8 @@ void TTrain::resetUnitStates() // reads the states of the vehicles and the units in multiple, from the cab along the control coupling void TTrain::updateUnitStates() { - bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; - TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); + bool kier = DynamicObject->DirectionGet() * occupied->CabOccupied > 0; + TDynamicObject *p = DynamicObject->GetFirstDynamic(occupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); int in = 0; fEIMParams[0][6] = 0; iCarNo = 0; @@ -432,85 +432,85 @@ void TTrain::updateUnitStates() { if (p) { - fPress[i][0] = static_cast(p->MoverParameters->BrakePress); - fPress[i][1] = static_cast(p->MoverParameters->PipePress); - fPress[i][2] = static_cast(p->MoverParameters->ScndPipePress); - fPress[i][3] = static_cast(p->MoverParameters->CntrlPipePress); - fPress[i][4] = static_cast(p->MoverParameters->Hamulec->GetBRP()); - fPress[i][5] = static_cast((p->MoverParameters->TotalMass - p->MoverParameters->Mred) * 0.001); - fPress[i][6] = static_cast(p->MoverParameters->SpringBrake.SBP); - bBrakes[i][0] = p->MoverParameters->SpringBrake.IsActive; - bBrakes[i][1] = p->MoverParameters->SpringBrake.ShuttOff; - bDoors[i][1] = p->MoverParameters->Doors.instances[VehicleSide::left].position > 0.f; - bDoors[i][2] = p->MoverParameters->Doors.instances[VehicleSide::right].position > 0.f; - bDoors[i][3] = p->MoverParameters->Doors.instances[VehicleSide::left].step_position > 0.f; - bDoors[i][4] = p->MoverParameters->Doors.instances[VehicleSide::right].step_position > 0.f; + fPress[i][0] = static_cast(p->physics->BrakePress); + fPress[i][1] = static_cast(p->physics->PipePress); + fPress[i][2] = static_cast(p->physics->ScndPipePress); + fPress[i][3] = static_cast(p->physics->CntrlPipePress); + fPress[i][4] = static_cast(p->physics->Hamulec->GetBRP()); + fPress[i][5] = static_cast((p->physics->TotalMass - p->physics->Mred) * 0.001); + fPress[i][6] = static_cast(p->physics->SpringBrake.SBP); + bBrakes[i][0] = p->physics->SpringBrake.IsActive; + bBrakes[i][1] = p->physics->SpringBrake.ShuttOff; + bDoors[i][1] = p->physics->Doors.instances[VehicleSide::left].position > 0.f; + bDoors[i][2] = p->physics->Doors.instances[VehicleSide::right].position > 0.f; + bDoors[i][3] = p->physics->Doors.instances[VehicleSide::left].step_position > 0.f; + bDoors[i][4] = p->physics->Doors.instances[VehicleSide::right].step_position > 0.f; bDoors[i][0] = bDoors[i][1] || bDoors[i][2]; iDoorNo[i] = p->iAnimType[ANIM_DOORS]; iUnits[i] = iUnitNo; - cCode[i] = p->MoverParameters->TypeName[p->MoverParameters->TypeName.length() - 1]; + cCode[i] = p->physics->TypeName[p->physics->TypeName.length() - 1]; asCarName[i] = p->name(); - if (p->MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector && iUnitNo <= 8) + if (p->physics->EnginePowerSource.SourceType == TPowerSource::CurrentCollector && iUnitNo <= 8) { - bPants[iUnitNo - 1][VehicleEnd::front] = bPants[iUnitNo - 1][VehicleEnd::front] || p->MoverParameters->Pantographs[VehicleEnd::front].is_active; - bPants[iUnitNo - 1][VehicleEnd::rear] = bPants[iUnitNo - 1][VehicleEnd::rear] || p->MoverParameters->Pantographs[VehicleEnd::rear].is_active; + bPants[iUnitNo - 1][VehicleEnd::front] = bPants[iUnitNo - 1][VehicleEnd::front] || p->physics->Pantographs[VehicleEnd::front].is_active; + bPants[iUnitNo - 1][VehicleEnd::rear] = bPants[iUnitNo - 1][VehicleEnd::rear] || p->physics->Pantographs[VehicleEnd::rear].is_active; } // TBD, TODO: clean up compressor data arrangement? if (iUnitNo <= 8) { - bComp[iUnitNo - 1][0] = bComp[iUnitNo - 1][0] || p->MoverParameters->CompressorAllow || p->MoverParameters->CompressorStart == start_t::automatic; + bComp[iUnitNo - 1][0] = bComp[iUnitNo - 1][0] || p->physics->CompressorAllow || p->physics->CompressorStart == start_t::automatic; } - if (p->MoverParameters->CompressorSpeed > 0.00001) + if (p->physics->CompressorSpeed > 0.00001) { if (iUnitNo <= 8) { - bComp[iUnitNo - 1][1] = bComp[iUnitNo - 1][1] || p->MoverParameters->CompressorFlag; + bComp[iUnitNo - 1][1] = bComp[iUnitNo - 1][1] || p->physics->CompressorFlag; } - bCompressors.emplace_back(p->MoverParameters->CompressorAllow || p->MoverParameters->CompressorStart == start_t::automatic, p->MoverParameters->CompressorFlag, i); + bCompressors.emplace_back(p->physics->CompressorAllow || p->physics->CompressorStart == start_t::automatic, p->physics->CompressorFlag, i); } - bSlip[i] = p->MoverParameters->SlippingWheels; - if (in < 8 && p->MoverParameters->inductionMotor.traction.maxPower > 1) + bSlip[i] = p->physics->SlippingWheels; + if (in < 8 && p->physics->inductionMotor.traction.maxPower > 1) { - fEIMParams[1 + in][0] = static_cast(p->MoverParameters->inductionMotor.state.maxForce); + fEIMParams[1 + in][0] = static_cast(p->physics->inductionMotor.state.maxForce); fEIMParams[1 + in][1] = std::max(fEIMParams[1 + in][0], 0.f); fEIMParams[1 + in][2] = -std::min(fEIMParams[1 + in][0], 0.f); - fEIMParams[1 + in][3] = static_cast(p->MoverParameters->inductionMotor.state.maxForce / std::max(p->MoverParameters->inductionMotor.state.fullForce, 1.)); + fEIMParams[1 + in][3] = static_cast(p->physics->inductionMotor.state.maxForce / std::max(p->physics->inductionMotor.state.fullForce, 1.)); fEIMParams[1 + in][4] = std::max(fEIMParams[1 + in][3], 0.f); fEIMParams[1 + in][5] = -std::min(fEIMParams[1 + in][3], 0.f); - fEIMParams[1 + in][6] = static_cast(p->MoverParameters->inductionMotor.state.fieldCurrent); - fEIMParams[1 + in][7] = static_cast(p->MoverParameters->inductionMotor.state.voltage); - fEIMParams[1 + in][8] = static_cast(p->MoverParameters->Itot); // p->MoverParameters->inductionMotor.state.lineCurrent; - fEIMParams[1 + in][9] = static_cast(p->MoverParameters->EngineVoltage); + fEIMParams[1 + in][6] = static_cast(p->physics->inductionMotor.state.fieldCurrent); + fEIMParams[1 + in][7] = static_cast(p->physics->inductionMotor.state.voltage); + fEIMParams[1 + in][8] = static_cast(p->physics->Itot); // p->physics->inductionMotor.state.lineCurrent; + fEIMParams[1 + in][9] = static_cast(p->physics->EngineVoltage); fEIMParams[0][6] += fEIMParams[1 + in][8]; - bMains[in] = p->MoverParameters->Mains; - fCntVol[in] = static_cast(p->MoverParameters->BatteryVoltage); - bFuse[in] = p->MoverParameters->FuseFlag; - bBatt[in] = p->MoverParameters->Battery; - bConv[in] = p->MoverParameters->ConverterFlag; - bHeat[in] = p->MoverParameters->Heating; - // bComp[in][2] = (p->MoverParameters->CompressorAllow || (p->MoverParameters->CompressorStart == start_t::automatic)); - // bComp[in][3] = (p->MoverParameters->CompressorFlag); + bMains[in] = p->physics->Mains; + fCntVol[in] = static_cast(p->physics->BatteryVoltage); + bFuse[in] = p->physics->FuseFlag; + bBatt[in] = p->physics->Battery; + bConv[in] = p->physics->ConverterFlag; + bHeat[in] = p->physics->Heating; + // bComp[in][2] = (p->physics->CompressorAllow || (p->physics->CompressorStart == start_t::automatic)); + // bComp[in][3] = (p->physics->CompressorFlag); in++; iPowerNo = in; } - if (in < 8 && (p->MoverParameters->EngineType == TEngineType::DieselEngine || p->MoverParameters->EngineType == TEngineType::DieselElectric)) + if (in < 8 && (p->physics->EngineType == TEngineType::DieselEngine || p->physics->EngineType == TEngineType::DieselElectric)) { - fDieselParams[1 + in][0] = static_cast(p->MoverParameters->enrot * 60); - fDieselParams[1 + in][1] = static_cast(p->MoverParameters->nrot); - fDieselParams[1 + in][2] = static_cast(p->MoverParameters->RList[p->MoverParameters->MainCtrlPos].R); - fDieselParams[1 + in][3] = static_cast(p->MoverParameters->diesel.fill); - fDieselParams[1 + in][4] = static_cast(p->MoverParameters->RList[p->MoverParameters->MainCtrlPos].Mn); - fDieselParams[1 + in][5] = static_cast(p->MoverParameters->diesel.clutchPressure); - fDieselParams[1 + in][6] = p->MoverParameters->diesel.heat.Twy; - fDieselParams[1 + in][7] = p->MoverParameters->OilPump.pressure; - fDieselParams[1 + in][8] = p->MoverParameters->diesel.heat.Ts; - fDieselParams[1 + in][9] = static_cast(p->MoverParameters->retarder.fill); - bMains[in] = p->MoverParameters->Mains; - fCntVol[in] = static_cast(p->MoverParameters->BatteryVoltage); - bFuse[in] = p->MoverParameters->FuseFlag; - bBatt[in] = p->MoverParameters->Battery; - bConv[in] = p->MoverParameters->ConverterFlag; - bHeat[in] = p->MoverParameters->Heating; + fDieselParams[1 + in][0] = static_cast(p->physics->enrot * 60); + fDieselParams[1 + in][1] = static_cast(p->physics->nrot); + fDieselParams[1 + in][2] = static_cast(p->physics->RList[p->physics->MainCtrlPos].R); + fDieselParams[1 + in][3] = static_cast(p->physics->diesel.fill); + fDieselParams[1 + in][4] = static_cast(p->physics->RList[p->physics->MainCtrlPos].Mn); + fDieselParams[1 + in][5] = static_cast(p->physics->diesel.clutchPressure); + fDieselParams[1 + in][6] = p->physics->diesel.heat.Twy; + fDieselParams[1 + in][7] = p->physics->OilPump.pressure; + fDieselParams[1 + in][8] = p->physics->diesel.heat.Ts; + fDieselParams[1 + in][9] = static_cast(p->physics->retarder.fill); + bMains[in] = p->physics->Mains; + fCntVol[in] = static_cast(p->physics->BatteryVoltage); + bFuse[in] = p->physics->FuseFlag; + bBatt[in] = p->physics->Battery; + bConv[in] = p->physics->ConverterFlag; + bHeat[in] = p->physics->Heating; in++; iPowerNo = in; } @@ -548,16 +548,16 @@ void TTrain::updateUnitStates() // sets the induction motor values of the whole train and clears the slots of the units after the first in ones void TTrain::completeUnitStates(int const in) { - // if (mvControlled == mvOccupied) - // fEIMParams[0][3] = mvControlled->inductionMotor.state.forceDemand; // procent zadany + // if (controlled == occupied) + // fEIMParams[0][3] = controlled->inductionMotor.state.forceDemand; // procent zadany // else // fEIMParams[0][3] = - // mvControlled->inductionMotor.state.forceDemand - mvOccupied->LocalBrakeRatio(); // procent zadany - fEIMParams[0][3] = static_cast(mvOccupied->eimic_real); + // controlled->inductionMotor.state.forceDemand - occupied->LocalBrakeRatio(); // procent zadany + fEIMParams[0][3] = static_cast(occupied->eimic_real); fEIMParams[0][4] = std::max(fEIMParams[0][3], 0.f); fEIMParams[0][5] = -std::min(fEIMParams[0][3], 0.f); - fEIMParams[0][1] = static_cast(fEIMParams[0][4] * mvControlled->inductionMotor.state.fullForce); - fEIMParams[0][2] = static_cast(fEIMParams[0][5] * mvControlled->inductionMotor.state.fullForce); + fEIMParams[0][1] = static_cast(fEIMParams[0][4] * controlled->inductionMotor.state.fullForce); + fEIMParams[0][2] = static_cast(fEIMParams[0][5] * controlled->inductionMotor.state.fullForce); fEIMParams[0][0] = fEIMParams[0][1] - fEIMParams[0][2]; fEIMParams[0][7] = 0; fEIMParams[0][8] = 0; @@ -581,17 +581,17 @@ void TTrain::updateFeedbackGauges() const { // wykonywać tylko gdy wyprowadzone na pulpit // Ra: sterowanie miernikiem: zbiornik główny - Console::ValueSet(0, mvOccupied->Compressor); + Console::ValueSet(0, occupied->Compressor); // Ra: sterowanie miernikiem: przewód główny - Console::ValueSet(1, mvOccupied->PipePress); + Console::ValueSet(1, occupied->PipePress); // Ra: sterowanie miernikiem: cylinder hamulcowy - Console::ValueSet(2, mvOccupied->BrakePress); + Console::ValueSet(2, occupied->BrakePress); // woltomierz wysokiego napięcia Console::ValueSet(3, fHVoltage); // Ra: sterowanie miernikiem: drugi amperomierz Console::ValueSet(4, fHCurrent[2]); // pierwszy amperomierz; dla EZT prąd całkowity - Console::ValueSet(5, fHCurrent[mvControlled->TrainType == train_type::emu ? 0 : 1]); + Console::ValueSet(5, fHCurrent[controlled->TrainType == train_type::emu ? 0 : 1]); // Ra: prędkość na pin 43 - wyjście analogowe (to nie jest PWM); skakanie zapewnia mechanika napędu Console::ValueSet(6, fTachoVelocity); } @@ -604,23 +604,23 @@ void TTrain::updateConverterOverload(double const Deltatime) //------------------ // hunter-261211: nadmiarowy przetwornicy i ogrzewania // Ra 15-01: to musi stąd wylecieć - zależności nie mogą być w kabinie - if (mvControlled->ConverterFlag == true) + if (controlled->ConverterFlag == true) { fConverterTimer += static_cast(Deltatime); - if (mvControlled->CompressorFlag == true && mvControlled->CompressorPower == 1 && (mvControlled->EngineType == TEngineType::ElectricSeriesMotor || mvControlled->TrainType == train_type::emu) && + if (controlled->CompressorFlag == true && controlled->CompressorPower == 1 && (controlled->EngineType == TEngineType::ElectricSeriesMotor || controlled->TrainType == train_type::emu) && DynamicObject->Controller == Humandriver // hunter-110212: poprawka dla EZT && DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag) { // hunter-091012: poprawka (zmiana warunku z CompressorPower /rozne od 0/ na /rowne 1/) if (fConverterTimer < fConverterPrzekaznik) { - mvControlled->ConvOvldFlag = true; - if (mvControlled->TrainType != train_type::emu) - mvControlled->MainSwitch(false, mvControlled->TrainType == train_type::emu ? range_t::unit : range_t::local); + controlled->ConvOvldFlag = true; + if (controlled->TrainType != train_type::emu) + controlled->MainSwitch(false, controlled->TrainType == train_type::emu ? range_t::unit : range_t::local); } else if (fConverterTimer >= fConverterPrzekaznik) { // changed switch from always true to take into account state of the compressor switch - mvControlled->CompressorSwitch(mvControlled->CompressorAllow); + controlled->CompressorSwitch(controlled->CompressorAllow); } } } @@ -635,40 +635,40 @@ void TTrain::updateSecondUnitGauges() // youBy - prad w drugim czlonie: galaz lub calosc { TDynamicObject const *tmp{nullptr}; - if (DynamicObject->NextConnected() && mvControlled->Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::control) && mvOccupied->CabOccupied == 1) + if (DynamicObject->NextConnected() && controlled->Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::control) && occupied->CabOccupied == 1) tmp = DynamicObject->NextConnected(); - if (DynamicObject->PrevConnected() && mvControlled->Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::control) && mvOccupied->CabOccupied == -1) + if (DynamicObject->PrevConnected() && controlled->Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::control) && occupied->CabOccupied == -1) tmp = DynamicObject->PrevConnected(); - if (tmp && tmp->MoverParameters->Power > 0) + if (tmp && tmp->physics->Power > 0) { if (ggI1B.SubModel) { - ggI1B.UpdateValue(static_cast(tmp->MoverParameters->ShowCurrent(1))); + ggI1B.UpdateValue(static_cast(tmp->physics->ShowCurrent(1))); ggI1B.Update(); } if (ggI2B.SubModel) { - ggI2B.UpdateValue(static_cast(tmp->MoverParameters->ShowCurrent(2))); + ggI2B.UpdateValue(static_cast(tmp->physics->ShowCurrent(2))); ggI2B.Update(); } if (ggI3B.SubModel) { - ggI3B.UpdateValue(static_cast(tmp->MoverParameters->ShowCurrent(3))); + ggI3B.UpdateValue(static_cast(tmp->physics->ShowCurrent(3))); ggI3B.Update(); } if (ggItotalB.SubModel) { - ggItotalB.UpdateValue(static_cast(tmp->MoverParameters->ShowCurrent(0))); + ggItotalB.UpdateValue(static_cast(tmp->physics->ShowCurrent(0))); ggItotalB.Update(); } if (ggWater1TempB.SubModel) { - ggWater1TempB.UpdateValue(tmp->MoverParameters->diesel.heat.temperatura1); + ggWater1TempB.UpdateValue(tmp->physics->diesel.heat.temperatura1); ggWater1TempB.Update(); } if (ggOilPressB.SubModel) { - ggOilPressB.UpdateValue(tmp->MoverParameters->OilPump.pressure); + ggOilPressB.UpdateValue(tmp->physics->OilPump.pressure); ggOilPressB.Update(); } } @@ -696,21 +696,21 @@ void TTrain::updateEngineGauges() // youBy - napiecie na silnikach if (ggEngineVoltage.SubModel) { - if (mvControlled->DynamicBrakeFlag) + if (controlled->DynamicBrakeFlag) { - ggEngineVoltage.UpdateValue(static_cast(std::abs(mvControlled->Im * 5))); + ggEngineVoltage.UpdateValue(static_cast(std::abs(controlled->Im * 5))); } else { int x; - if (mvControlled->TrainType == train_type::et42 && mvControlled->Imax == mvControlled->ImaxHi) + if (controlled->TrainType == train_type::et42 && controlled->Imax == controlled->ImaxHi) x = 1; else x = 2; - if (mvControlled->RList[mvControlled->MainCtrlActualPos].Mn > 0 && std::abs(mvControlled->Im) > 0) + if (controlled->RList[controlled->MainCtrlActualPos].Mn > 0 && std::abs(controlled->Im) > 0) { - ggEngineVoltage.UpdateValue(static_cast(x * (std::abs(mvControlled->EngineVoltage) - mvControlled->RList[mvControlled->MainCtrlActualPos].R * std::abs(mvControlled->Im)) / - mvControlled->RList[mvControlled->MainCtrlActualPos].Mn)); + ggEngineVoltage.UpdateValue(static_cast(x * (std::abs(controlled->EngineVoltage) - controlled->RList[controlled->MainCtrlActualPos].R * std::abs(controlled->Im)) / + controlled->RList[controlled->MainCtrlActualPos].Mn)); } else { @@ -725,32 +725,32 @@ void TTrain::updateEngineGauges() { // NOTE: since we don't have functional converter object, we're faking it here by simple check whether converter is on // TODO: implement object-based circuits and power systems model so we can have this working more properly - ggLVoltage.UpdateValue(static_cast(std::max(mvOccupied->Power110vIsAvailable ? mvOccupied->NominalBatteryVoltage : 0.0, mvOccupied->Power24vIsAvailable ? mvOccupied->BatteryVoltage : 0.0))); + ggLVoltage.UpdateValue(static_cast(std::max(occupied->Power110vIsAvailable ? occupied->NominalBatteryVoltage : 0.0, occupied->Power24vIsAvailable ? occupied->BatteryVoltage : 0.0))); ggLVoltage.Update(); } - if (mvControlled->EngineType == TEngineType::DieselElectric) + if (controlled->EngineType == TEngineType::DieselElectric) { // ustawienie zmiennych dla silnika spalinowego - fEngine[1] = static_cast(mvControlled->ShowEngineRotation(1)); - fEngine[2] = static_cast(mvControlled->ShowEngineRotation(2)); + fEngine[1] = static_cast(controlled->ShowEngineRotation(1)); + fEngine[2] = static_cast(controlled->ShowEngineRotation(2)); } - else if (mvControlled->EngineType == TEngineType::DieselEngine) + else if (controlled->EngineType == TEngineType::DieselEngine) { // albo dla innego spalinowego - fEngine[1] = static_cast(mvControlled->ShowEngineRotation(1)); - fEngine[2] = static_cast(mvControlled->ShowEngineRotation(2)); - fEngine[3] = static_cast(mvControlled->ShowEngineRotation(3)); + fEngine[1] = static_cast(controlled->ShowEngineRotation(1)); + fEngine[2] = static_cast(controlled->ShowEngineRotation(2)); + fEngine[3] = static_cast(controlled->ShowEngineRotation(3)); if (ggMainGearStatus.SubModel) { - if (mvControlled->Mains) - ggMainGearStatus.UpdateValue(static_cast(1.1 - std::abs(mvControlled->diesel.automaticGearShift))); + if (controlled->Mains) + ggMainGearStatus.UpdateValue(static_cast(1.1 - std::abs(controlled->diesel.automaticGearShift))); else ggMainGearStatus.UpdateValue(0.0); ggMainGearStatus.Update(); } if (ggIgnitionKey.SubModel && ggIgnitionKey.GetDesiredValue() == 0.0) { - ggIgnitionKey.UpdateValue(mvControlled->Mains || mvControlled->diesel.startupRequested || fMainRelayTimer > 0.f || + ggIgnitionKey.UpdateValue(controlled->Mains || controlled->diesel.startupRequested || fMainRelayTimer > 0.f || (ggMainButton.SubModel != nullptr && ggMainButton.GetDesiredValue() > 0.95) || (ggMainOnButton.SubModel != nullptr && ggMainOnButton.GetDesiredValue() > 0.95)); } @@ -761,12 +761,12 @@ void TTrain::updateEngineGauges() // sets the lamps of the wheel slip, the compressors, the dynamic brake permit and the active cab void TTrain::updateBasicLamps() { - if (mvControlled->SlippingWheels) + if (controlled->SlippingWheels) { // Ra 2014-12: lokomotywy 181/182 dostają SlippingWheels po zahamowaniu powyżej 2.85 bara i buczały - double veldiff = (DynamicObject->GetVelocity() - fTachoVelocity) / mvControlled->Vmax; + double veldiff = (DynamicObject->GetVelocity() - fTachoVelocity) / controlled->Vmax; // 1% Vmax rezerwy, żeby 181/182 nie buczały po zahamowaniu, ale to proteza - if (veldiff < -0.01 && std::abs(mvControlled->Im) > 10.0) + if (veldiff < -0.01 && std::abs(controlled->Im) > 10.0) { btLampkaPoslizg.Turn(true); } @@ -777,19 +777,19 @@ void TTrain::updateBasicLamps() } // Lampka pracujacej sprezacki - if (mvControlled->CompressorFlag || mvOccupied->CompressorFlag) + if (controlled->CompressorFlag || occupied->CompressorFlag) btCompressors.Turn(true); else btCompressors.Turn(false); // Lampka zezwolenia na hamowanie ED - if (mvControlled->EpFuse) + if (controlled->EpFuse) btEDenabled.Turn(true); else btEDenabled.Turn(false); // Lampka aktywowanej kabiny - if (mvControlled->CabActive != 0) + if (controlled->CabActive != 0) { btCabActived.Turn(true); } @@ -798,7 +798,7 @@ void TTrain::updateBasicLamps() btCabActived.Turn(false); } - if (mvControlled->Battery && mvControlled->CabActive != 0) + if (controlled->Battery && controlled->CabActive != 0) btAKLVents.Turn(true); else btAKLVents.Turn(false); @@ -808,7 +808,7 @@ void TTrain::updateBasicLamps() void TTrain::updateCircuitLamps(double const Deltatime) { // McZapkie-141102: SHP i czuwak, TODO: sygnalizacja kabinowa - if (mvOccupied->SecuritySystem.is_vigilance_blinking()) + if (occupied->SecuritySystem.is_vigilance_blinking()) { if (fBlinkTimer > fCzuwakBlink) fBlinkTimer = -fCzuwakBlink; @@ -823,59 +823,59 @@ void TTrain::updateCircuitLamps(double const Deltatime) btLampkaCzuwaka.Turn(false); } - btLampkaSHP.Turn(mvOccupied->SecuritySystem.is_cabsignal_blinking()); + btLampkaSHP.Turn(occupied->SecuritySystem.is_cabsignal_blinking()); btLampkaCzuwakaSHP.Turn(btLampkaSHP.GetValue() || btLampkaCzuwaka.GetValue()); - btLampkaWylSzybki.Turn(m_linebreakerstate == linebreaker::state::closing || mvControlled->Mains); - btLampkaWylSzybkiOff.Turn(m_linebreakerstate != linebreaker::state::closing && !mvControlled->Mains); - btLampkaMainBreakerReady.Turn(mvControlled->MainsInitTimeCountdown <= 0.0 && m_linebreakerstate != linebreaker::state::closing && !mvControlled->Mains); - btLampkaMainBreakerBlinkingIfReady.Turn(m_linebreakerstate == linebreaker::state::closing || mvControlled->Mains || mvControlled->MainsInitTimeCountdown < 0.0 && simulation::Time.data().wMilliseconds > 500); + btLampkaWylSzybki.Turn(m_linebreakerstate == linebreaker::state::closing || controlled->Mains); + btLampkaWylSzybkiOff.Turn(m_linebreakerstate != linebreaker::state::closing && !controlled->Mains); + btLampkaMainBreakerReady.Turn(controlled->MainsInitTimeCountdown <= 0.0 && m_linebreakerstate != linebreaker::state::closing && !controlled->Mains); + btLampkaMainBreakerBlinkingIfReady.Turn(m_linebreakerstate == linebreaker::state::closing || controlled->Mains || controlled->MainsInitTimeCountdown < 0.0 && simulation::Time.data().wMilliseconds > 500); - btLampkaPrzetw.Turn(mvOccupied->Power110vIsAvailable); - btLampkaPrzetwOff.Turn(!mvOccupied->Power110vIsAvailable); - btLampkaPrzetwAOff.Turn(!mvControlled->ConverterFlag); - btLampkaNadmPrzetw.Turn(Dynamic()->Mechanik ? Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : mvControlled->ConvOvldFlag); + btLampkaPrzetw.Turn(occupied->Power110vIsAvailable); + btLampkaPrzetwOff.Turn(!occupied->Power110vIsAvailable); + btLampkaPrzetwAOff.Turn(!controlled->ConverterFlag); + btLampkaNadmPrzetw.Turn(Dynamic()->Mechanik ? Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : controlled->ConvOvldFlag); - btLampkaOpory.Turn(mvControlled->StLinFlag && mvControlled->ResistorsFlagCheck()); - btLampkaBezoporowa.Turn(mvControlled->ResistorsFlagCheck() || mvControlled->MainCtrlActualPos == 0); // do EU04 - btLampkaStyczn.Turn(mvControlled->LineContactorsLampLit()); // mozna prowadzic rozruch - btLampkaPrzekRozn.Turn(!mvControlled->GroundRelay && mvControlled->MainCircuitLampsEnabled()); // relay is off and needs a reset - btLampkaNadmSil.Turn(mvControlled->FuseFlagCheck() && mvControlled->MainCircuitLampsEnabled()); // relay is off and needs a reset - btLampkaUkrotnienie.Turn(mvControlled->Couplers[mvControlled->CabOccupied == 1 ? VehicleEnd::rear : VehicleEnd::front].CouplingFlag.HasAll(Coupling::control)); - btLampkaHamPosp.Turn(TestFlag(mvOccupied->Hamulec->GetBrakeStatus(), 1)); // lampka drugiego stopnia hamowania + btLampkaOpory.Turn(controlled->StLinFlag && controlled->ResistorsFlagCheck()); + btLampkaBezoporowa.Turn(controlled->ResistorsFlagCheck() || controlled->MainCtrlActualPos == 0); // do EU04 + btLampkaStyczn.Turn(controlled->LineContactorsLampLit()); // mozna prowadzic rozruch + btLampkaPrzekRozn.Turn(!controlled->GroundRelay && controlled->MainCircuitLampsEnabled()); // relay is off and needs a reset + btLampkaNadmSil.Turn(controlled->FuseFlagCheck() && controlled->MainCircuitLampsEnabled()); // relay is off and needs a reset + btLampkaUkrotnienie.Turn(controlled->Couplers[controlled->CabOccupied == 1 ? VehicleEnd::rear : VehicleEnd::front].CouplingFlag.HasAll(Coupling::control)); + btLampkaHamPosp.Turn(TestFlag(occupied->Hamulec->GetBrakeStatus(), 1)); // lampka drugiego stopnia hamowania // TODO: youBy wyciągnąć flagę wysokiego stopnia - btLampkaNadmWent.Turn(mvControlled->RventRot < 5.0 && mvControlled->ResistorsFlagCheck()); // hunter-121211: lampka zanikowo-pradowego wentylatorow - btLampkaWysRozr.Turn(mvControlled->Imax >= mvControlled->ImaxHi); + btLampkaNadmWent.Turn(controlled->RventRot < 5.0 && controlled->ResistorsFlagCheck()); // hunter-121211: lampka zanikowo-pradowego wentylatorow + btLampkaWysRozr.Turn(controlled->Imax >= controlled->ImaxHi); - btLampkaNapNastHam.Turn(mvControlled->DirActive != 0); // napiecie na nastawniku hamulcowym - btLampkaSprezarka.Turn(mvControlled->CompressorFlag); // mutopsitka dziala - btLampkaSprezarkaOff.Turn(!mvControlled->CompressorFlag); - btLampkaFuelPumpOff.Turn(!mvControlled->FuelPump.is_active); - btLampkaOilPump.Turn(mvControlled->OilPump.is_active); // pre-lubrication pump, goes off once the engine is started + btLampkaNapNastHam.Turn(controlled->DirActive != 0); // napiecie na nastawniku hamulcowym + btLampkaSprezarka.Turn(controlled->CompressorFlag); // mutopsitka dziala + btLampkaSprezarkaOff.Turn(!controlled->CompressorFlag); + btLampkaFuelPumpOff.Turn(!controlled->FuelPump.is_active); + btLampkaOilPump.Turn(controlled->OilPump.is_active); // pre-lubrication pump, goes off once the engine is started // boczniki // Ra: w SU45 boczniki wchodzą na ScndCtrlPos, a nie na ScndCtrlActualPos // - pokićkał ktoś? - int scp = mvControlled->RList[mvControlled->MainCtrlPos].ScndAct; + int scp = controlled->RList[controlled->MainCtrlPos].ScndAct; scp = scp == 255 ? 0 : scp; // Ra: whatta hella is this? - btLampkaBoczniki.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlActualPos > 0 || scp > 0); - btLampkaBocznik1.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlPos > 0 || mvControlled->ScndCtrlActualPos > 0 || scp > 0); - btLampkaBocznik2.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlPos > 1 || mvControlled->ScndCtrlActualPos > 1 || scp > 1); - btLampkaBocznik3.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlPos > 2 || mvControlled->ScndCtrlActualPos > 2 || scp > 2); - btLampkaBocznik4.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlPos > 3 || mvControlled->ScndCtrlActualPos > 3 || scp > 3); + btLampkaBoczniki.Turn(!controlled->DelayCtrlFlag && controlled->ScndCtrlActualPos > 0 || scp > 0); + btLampkaBocznik1.Turn(!controlled->DelayCtrlFlag && controlled->ScndCtrlPos > 0 || controlled->ScndCtrlActualPos > 0 || scp > 0); + btLampkaBocznik2.Turn(!controlled->DelayCtrlFlag && controlled->ScndCtrlPos > 1 || controlled->ScndCtrlActualPos > 1 || scp > 1); + btLampkaBocznik3.Turn(!controlled->DelayCtrlFlag && controlled->ScndCtrlPos > 2 || controlled->ScndCtrlActualPos > 2 || scp > 2); + btLampkaBocznik4.Turn(!controlled->DelayCtrlFlag && controlled->ScndCtrlPos > 3 || controlled->ScndCtrlActualPos > 3 || scp > 3); // biegi dla motoraka - btLampkaGear1.Turn(mvControlled->ScndCtrlActualPos == 1 && mvControlled->diesel.clutchState > 0); // bieg 1 - btLampkaGear2.Turn(mvControlled->ScndCtrlActualPos == 2 && mvControlled->diesel.clutchState > 0); // bieg 2 - btLampkaHydroLockup.Turn(mvControlled->torqueConverter.lockedUp); // zblokowanie skrzyni z silnikiem + btLampkaGear1.Turn(controlled->ScndCtrlActualPos == 1 && controlled->diesel.clutchState > 0); // bieg 1 + btLampkaGear2.Turn(controlled->ScndCtrlActualPos == 2 && controlled->diesel.clutchState > 0); // bieg 2 + btLampkaHydroLockup.Turn(controlled->torqueConverter.lockedUp); // zblokowanie skrzyni z silnikiem - if (mvControlled->Signalling == true) + if (controlled->Signalling == true) { - if (mvOccupied->BrakePress >= 1.45f) + if (occupied->BrakePress >= 1.45f) { btLampkaHamowanie1zes.Turn(true); } - if (mvControlled->BrakePress < 0.75f) + if (controlled->BrakePress < 0.75f) { btLampkaHamowanie1zes.Turn(false); } @@ -889,38 +889,38 @@ void TTrain::updateCircuitLamps(double const Deltatime) // sets the lamps of the braking, the radio, the doors, the direction, the lights and the overheating, with the low voltage on void TTrain::updateTrainLamps() { - switch (mvControlled->TrainType) + switch (controlled->TrainType) { // zależnie od typu lokomotywy case train_type::emu: { - btLampkaHamienie.Turn(mvControlled->BrakePress >= 0.2 && mvControlled->Signalling); + btLampkaHamienie.Turn(controlled->BrakePress >= 0.2 && controlled->Signalling); break; } case train_type::et41: { // odhamowanie drugiego członu - if (mvSecond) + if (secondUnit) { // bo może komuś przyjść do głowy jeżdżenie jednym członem - btLampkaHamienie.Turn(mvSecond->BrakePress < 0.4); + btLampkaHamienie.Turn(secondUnit->BrakePress < 0.4); } break; } default: { - btLampkaHamienie.Turn(mvOccupied->BrakePress >= 0.1 || mvControlled->DynamicBrakeFlag); - btLampkaBrakingOff.Turn(mvOccupied->BrakePress < 0.1 && !mvControlled->DynamicBrakeFlag); + btLampkaHamienie.Turn(occupied->BrakePress >= 0.1 || controlled->DynamicBrakeFlag); + btLampkaBrakingOff.Turn(occupied->BrakePress < 0.1 && !controlled->DynamicBrakeFlag); break; } } // KURS90 - btLampkaMaxSila.Turn(abs(mvControlled->Im) >= 350); - btLampkaPrzekrMaxSila.Turn(abs(mvControlled->Im) >= 450); - btLampkaRadio.Turn(mvOccupied->Radio && mvOccupied->RadioFuse); + btLampkaMaxSila.Turn(abs(controlled->Im) >= 350); + btLampkaPrzekrMaxSila.Turn(abs(controlled->Im) >= 450); + btLampkaRadio.Turn(occupied->Radio && occupied->RadioFuse); btLampkaRadioMessage.Turn(radio_message_played); - btLampkaRadioStop.Turn(mvOccupied->Radio && mvOccupied->RadioFuse && mvOccupied->RadioStopFlag); - btLampkaHamulecReczny.Turn(mvOccupied->ManualBrakePos > 0); + btLampkaRadioStop.Turn(occupied->Radio && occupied->RadioFuse && occupied->RadioStopFlag); + btLampkaHamulecReczny.Turn(occupied->ManualBrakePos > 0); // NBMX wrzesien 2003 - drzwi oraz sygnał odjazdu if (DynamicObject->Mechanik != nullptr) { @@ -932,20 +932,20 @@ void TTrain::updateTrainLamps() // with DoorClosureSignal in the definition of the cab's vehicle, the door closure signalling (SOD) of the whole // consist: lit with all doors closed and locked, blinking with them closed but released, dark with a door open. // without it, the lock of the vehicle's own doors, as before - btLampkaBlokadaDrzwi.Turn(mvOccupied->door_closure_lamp_lit(DynamicObject->Mechanik->DoorClosure, simulation::Time.data().wSecond % 2 < 1)); + btLampkaBlokadaDrzwi.Turn(occupied->door_closure_lamp_lit(DynamicObject->Mechanik->DoorClosure, simulation::Time.data().wSecond % 2 < 1)); } else { - btLampkaBlokadaDrzwi.Turn(mvOccupied->Doors.is_locked); + btLampkaBlokadaDrzwi.Turn(occupied->Doors.is_locked); } - btLampkaDoorLockOff.Turn(false == mvOccupied->Doors.lock_enabled); - btLampkaDepartureSignal.Turn(mvControlled->DepartureSignal); - btLampkaNapNastHam.Turn(mvControlled->DirActive != 0 && mvOccupied->EpFuse); // napiecie na nastawniku hamulcowym + btLampkaDoorLockOff.Turn(false == occupied->Doors.lock_enabled); + btLampkaDepartureSignal.Turn(controlled->DepartureSignal); + btLampkaNapNastHam.Turn(controlled->DirActive != 0 && occupied->EpFuse); // napiecie na nastawniku hamulcowym // Wylaczanie lampek kierunku gdy jedziemy // Feature uruchamiany z fiz z sekcji Ctrl. wpisem HideDirStatusWhenMoving=Yes (domyslnie No) - if (mvOccupied->HideDirStatusWhenMoving && // Czy ta funkcja jest w ogole wlaczona - mvOccupied->Vel > mvOccupied->HideDirStatusSpeed) // Uzaleznienie od predkosci + if (occupied->HideDirStatusWhenMoving && // Czy ta funkcja jest w ogole wlaczona + occupied->Vel > occupied->HideDirStatusSpeed) // Uzaleznienie od predkosci { btLampkaForward.Turn(false); btLampkaBackward.Turn(false); @@ -953,40 +953,40 @@ void TTrain::updateTrainLamps() } else { - btLampkaForward.Turn(mvControlled->DirActive > 0); // jazda do przodu - btLampkaBackward.Turn(mvControlled->DirActive < 0); // jazda do tyłu - btLampkaNeutral.Turn(mvControlled->DirActive == 0); // kierunek neutral + btLampkaForward.Turn(controlled->DirActive > 0); // jazda do przodu + btLampkaBackward.Turn(controlled->DirActive < 0); // jazda do tyłu + btLampkaNeutral.Turn(controlled->DirActive == 0); // kierunek neutral } - btLampkaED.Turn(mvControlled->DynamicBrakeFlag); // hamulec ED - btLampkaBrakeProfileG.Turn(TestFlag(mvOccupied->BrakeDelayFlag, bdelay_G)); - btLampkaBrakeProfileP.Turn(TestFlag(mvOccupied->BrakeDelayFlag, bdelay_P)); - btLampkaBrakeProfileR.Turn(TestFlag(mvOccupied->BrakeDelayFlag, bdelay_R)); - btLampkaSpringBrakeActive.Turn(mvOccupied->SpringBrake.IsActive); - btLampkaSpringBrakeInactive.Turn(!mvOccupied->SpringBrake.IsActive); + btLampkaED.Turn(controlled->DynamicBrakeFlag); // hamulec ED + btLampkaBrakeProfileG.Turn(TestFlag(occupied->BrakeDelayFlag, bdelay_G)); + btLampkaBrakeProfileP.Turn(TestFlag(occupied->BrakeDelayFlag, bdelay_P)); + btLampkaBrakeProfileR.Turn(TestFlag(occupied->BrakeDelayFlag, bdelay_R)); + btLampkaSpringBrakeActive.Turn(occupied->SpringBrake.IsActive); + btLampkaSpringBrakeInactive.Turn(!occupied->SpringBrake.IsActive); // light indicators // NOTE: sides are hardcoded to deal with setups where single cab is equipped with all indicators - btLampkaUpperLight.Turn((mvOccupied->iLights[VehicleEnd::front] & light::headlight_upper) != 0); - btLampkaLeftLight.Turn((mvOccupied->iLights[VehicleEnd::front] & light::headlight_left) != 0); - btLampkaRightLight.Turn((mvOccupied->iLights[VehicleEnd::front] & light::headlight_right) != 0); - btLampkaLeftEndLight.Turn((mvOccupied->iLights[VehicleEnd::front] & light::redmarker_left) != 0); - btLampkaRightEndLight.Turn((mvOccupied->iLights[VehicleEnd::front] & light::redmarker_right) != 0); - btLampkaRearUpperLight.Turn((mvOccupied->iLights[VehicleEnd::rear] & light::headlight_upper) != 0); - btLampkaRearLeftLight.Turn((mvOccupied->iLights[VehicleEnd::rear] & light::headlight_left) != 0); - btLampkaRearRightLight.Turn((mvOccupied->iLights[VehicleEnd::rear] & light::headlight_right) != 0); - btLampkaRearLeftEndLight.Turn((mvOccupied->iLights[VehicleEnd::rear] & light::redmarker_left) != 0); - btLampkaRearRightEndLight.Turn((mvOccupied->iLights[VehicleEnd::rear] & light::redmarker_right) != 0); + btLampkaUpperLight.Turn((occupied->iLights[VehicleEnd::front] & light::headlight_upper) != 0); + btLampkaLeftLight.Turn((occupied->iLights[VehicleEnd::front] & light::headlight_left) != 0); + btLampkaRightLight.Turn((occupied->iLights[VehicleEnd::front] & light::headlight_right) != 0); + btLampkaLeftEndLight.Turn((occupied->iLights[VehicleEnd::front] & light::redmarker_left) != 0); + btLampkaRightEndLight.Turn((occupied->iLights[VehicleEnd::front] & light::redmarker_right) != 0); + btLampkaRearUpperLight.Turn((occupied->iLights[VehicleEnd::rear] & light::headlight_upper) != 0); + btLampkaRearLeftLight.Turn((occupied->iLights[VehicleEnd::rear] & light::headlight_left) != 0); + btLampkaRearRightLight.Turn((occupied->iLights[VehicleEnd::rear] & light::headlight_right) != 0); + btLampkaRearLeftEndLight.Turn((occupied->iLights[VehicleEnd::rear] & light::redmarker_left) != 0); + btLampkaRearRightEndLight.Turn((occupied->iLights[VehicleEnd::rear] & light::redmarker_right) != 0); // others - btLampkaMalfunction.Turn(mvControlled->diesel.heat.PA); + btLampkaMalfunction.Turn(controlled->diesel.heat.PA); // overheat indicator lamps - btLampkaOilOverheat.Turn(mvControlled->diesel.heat.oil.is_hot); - btLampkaWaterOverheat.Turn(mvControlled->diesel.heat.water.is_hot); - btLampkaWaterAuxOverheat.Turn(mvControlled->diesel.heat.water_aux.is_hot); - btLampkaEngineOverheat.Turn(mvControlled->diesel.heat.engine_is_hot); - btLampkaMotorBlowers.Turn(mvControlled->MotorBlowers[VehicleEnd::front].is_active && mvControlled->MotorBlowers[VehicleEnd::rear].is_active); - btLampkaCoolingFans.Turn(mvControlled->RventRot > 1.0); - btLampkaLouvresClosed.Turn(mvControlled->LouvresClosed()); - btLampkaTempomat.Turn(mvOccupied->SpeedCtrlUnit.IsActive); + btLampkaOilOverheat.Turn(controlled->diesel.heat.oil.is_hot); + btLampkaWaterOverheat.Turn(controlled->diesel.heat.water.is_hot); + btLampkaWaterAuxOverheat.Turn(controlled->diesel.heat.water_aux.is_hot); + btLampkaEngineOverheat.Turn(controlled->diesel.heat.engine_is_hot); + btLampkaMotorBlowers.Turn(controlled->MotorBlowers[VehicleEnd::front].is_active && controlled->MotorBlowers[VehicleEnd::rear].is_active); + btLampkaCoolingFans.Turn(controlled->RventRot > 1.0); + btLampkaLouvresClosed.Turn(controlled->LouvresClosed()); + btLampkaTempomat.Turn(occupied->SpeedCtrlUnit.IsActive); btLampkaDistanceCounter.Turn(m_distancecounter >= 0.f); // universal devices state indicators for (auto idx = 0; idx < btUniversals.size(); ++idx) @@ -1089,11 +1089,11 @@ void TTrain::turnOffLamps() void TTrain::updateSecondUnitLamps(bool const lowvoltagepower) { { // yB - wskazniki drugiego czlonu - TDynamicObject const *tmp{nullptr}; //=mvControlled->mvSecond; //Ra 2014-07: trzeba to jeszcze wyjąć z kabiny... + TDynamicObject const *tmp{nullptr}; //=controlled->secondUnit; //Ra 2014-07: trzeba to jeszcze wyjąć z kabiny... // Ra 2014-07: no nie ma potrzeby szukać tego w każdej klatce - if (mvControlled->Couplers[1].CouplingFlag.HasAll(Coupling::control) && mvOccupied->CabOccupied > 0) + if (controlled->Couplers[1].CouplingFlag.HasAll(Coupling::control) && occupied->CabOccupied > 0) tmp = DynamicObject->NextConnected(); - if (mvControlled->Couplers[0].CouplingFlag.HasAll(Coupling::control) && mvOccupied->CabOccupied < 0) + if (controlled->Couplers[0].CouplingFlag.HasAll(Coupling::control) && occupied->CabOccupied < 0) tmp = DynamicObject->PrevConnected(); if (tmp) @@ -1101,39 +1101,39 @@ void TTrain::updateSecondUnitLamps(bool const lowvoltagepower) if (lowvoltagepower) { - auto const *mover{tmp->MoverParameters}; + auto const *physics{tmp->physics}; - btLampkaWylSzybkiB.Turn(mover->Mains); - btLampkaWylSzybkiBOff.Turn(false == mover->Mains - /*&& ( mover->MainsInitTimeCountdown <= 0.0 )*/ + btLampkaWylSzybkiB.Turn(physics->Mains); + btLampkaWylSzybkiBOff.Turn(false == physics->Mains + /*&& ( physics->MainsInitTimeCountdown <= 0.0 )*/ /*&& ( fHVoltage != 0.0 )*/); - btLampkaOporyB.Turn(mover->ResistorsFlagCheck()); - btLampkaBezoporowaB.Turn(true == mover->ResistorsFlagCheck() || mover->MainCtrlActualPos == 0); // do EU04 + btLampkaOporyB.Turn(physics->ResistorsFlagCheck()); + btLampkaBezoporowaB.Turn(true == physics->ResistorsFlagCheck() || physics->MainCtrlActualPos == 0); // do EU04 - btLampkaStycznB.Turn(mover->LineContactorsLampLit()); // mozna prowadzic rozruch + btLampkaStycznB.Turn(physics->LineContactorsLampLit()); // mozna prowadzic rozruch // hunter-271211: sygnalizacja poslizgu w pierwszym pojezdzie, gdy wystapi w drugim - if (mover->SlippingWheels) + if (physics->SlippingWheels) { // Ra 2014-12: lokomotywy 181/182 dostają SlippingWheels po zahamowaniu powyżej 2.85 bara i buczały - auto const veldiff{(DynamicObject->GetVelocity() - fTachoVelocity) / mvControlled->Vmax}; + auto const veldiff{(DynamicObject->GetVelocity() - fTachoVelocity) / controlled->Vmax}; if (veldiff < -0.01) { // 1% Vmax rezerwy, żeby 181/182 nie buczały po zahamowaniu, ale to proteza - auto const lightstate{std::abs(mover->Im) > 10.0}; + auto const lightstate{std::abs(physics->Im) > 10.0}; btLampkaPoslizg.Turn(btLampkaPoslizg.GetValue() || lightstate); } } - btLampkaSprezarkaB.Turn(mover->CompressorFlag); // mutopsitka dziala - btLampkaSprezarkaBOff.Turn(false == mover->CompressorFlag); - if (mvControlled->Signalling == true) + btLampkaSprezarkaB.Turn(physics->CompressorFlag); // mutopsitka dziala + btLampkaSprezarkaBOff.Turn(false == physics->CompressorFlag); + if (controlled->Signalling == true) { - if (mover->BrakePress >= 1.45f) + if (physics->BrakePress >= 1.45f) { btLampkaHamowanie2zes.Turn(true); } - if (mover->BrakePress < 0.75f) + if (physics->BrakePress < 0.75f) { btLampkaHamowanie2zes.Turn(false); } @@ -1142,15 +1142,15 @@ void TTrain::updateSecondUnitLamps(bool const lowvoltagepower) { btLampkaHamowanie2zes.Turn(false); } - btLampkaNadmPrzetwB.Turn(mover->ConvOvldFlag); // nadmiarowy przetwornicy? - btLampkaPrzetwB.Turn(mover->ConverterFlag); // zalaczenie przetwornicy - btLampkaPrzetwBOff.Turn(false == mover->ConverterFlag); - btLampkaHVoltageB.Turn(mover->NoVoltRelay && mover->OvervoltageRelay); - btLampkaMalfunctionB.Turn(mover->diesel.heat.PA); + btLampkaNadmPrzetwB.Turn(physics->ConvOvldFlag); // nadmiarowy przetwornicy? + btLampkaPrzetwB.Turn(physics->ConverterFlag); // zalaczenie przetwornicy + btLampkaPrzetwBOff.Turn(false == physics->ConverterFlag); + btLampkaHVoltageB.Turn(physics->NoVoltRelay && physics->OvervoltageRelay); + btLampkaMalfunctionB.Turn(physics->diesel.heat.PA); // motor fuse indicator turns on if the fuse was blown in any unit under control - if (mover->Mains) + if (physics->Mains) { - btLampkaNadmSil.Turn(btLampkaNadmSil.GetValue() || mover->FuseFlagCheck()); + btLampkaNadmSil.Turn(btLampkaNadmSil.GetValue() || physics->FuseFlagCheck()); } } else // wylaczone @@ -1181,21 +1181,21 @@ void TTrain::updateMasterControllers(bool const lowvoltagepower) { // joint master controller moves forward to adjust power and backward to adjust brakes auto const brakerangemultiplier{/* NOTE: scaling disabled as it was conflicting with associating sounds with control positions - ( mvControlled->CoupledCtrl ? - mvControlled->MainCtrlPosNo + mvControlled->ScndCtrlPosNo : - mvControlled->MainCtrlPosNo ) + ( controlled->CoupledCtrl ? + controlled->MainCtrlPosNo + controlled->ScndCtrlPosNo : + controlled->MainCtrlPosNo ) / static_cast(LocalBrakePosNo) */ 1}; // when SplitEDPneumaticBrake is active the negative range of the joint controller // represents the dedicated dynamic-brake lever (DBPN steps), not the pneumatic local brake - auto const negativePart{mvControlled->SplitEDPneumaticBrake ? - (mvControlled->DynamicBrakeCtrlPos > 0.0 ? mvControlled->DynamicBrakeCtrlPos * mvControlled->DynamicBrakeCtrlPosNo * -1 * brakerangemultiplier : 0.0) : - mvOccupied->LocalBrakePosA > 0.0 ? mvOccupied->LocalBrakePosA * LocalBrakePosNo * -1 * brakerangemultiplier : + auto const negativePart{controlled->SplitEDPneumaticBrake ? + (controlled->DynamicBrakeCtrlPos > 0.0 ? controlled->DynamicBrakeCtrlPos * controlled->DynamicBrakeCtrlPosNo * -1 * brakerangemultiplier : 0.0) : + occupied->LocalBrakePosA > 0.0 ? occupied->LocalBrakePosA * LocalBrakePosNo * -1 * brakerangemultiplier : 0.0}; ggJointCtrl.UpdateValue(negativePart < 0.0 ? static_cast(negativePart) : - mvControlled->CoupledCtrl ? static_cast(double(mvControlled->MainCtrlPos + mvControlled->ScndCtrlPos)) : - static_cast(double(mvControlled->MainCtrlPos)), + controlled->CoupledCtrl ? static_cast(double(controlled->MainCtrlPos + controlled->ScndCtrlPos)) : + static_cast(double(controlled->MainCtrlPos)), dsbNastawnikJazdy); ggJointCtrl.Update(); } @@ -1207,24 +1207,24 @@ void TTrain::updateMasterControllers(bool const lowvoltagepower) && Global.iFeedbackMode == 4 && Global.fCalibrateIn[2][1] != 0.0) { - set_master_controller(Console::AnalogCalibrateGet(2) * mvOccupied->MainCtrlPosNo); - mvOccupied->eimic_analog = Console::AnalogCalibrateGet(2); + set_master_controller(Console::AnalogCalibrateGet(2) * occupied->MainCtrlPosNo); + occupied->eimic_analog = Console::AnalogCalibrateGet(2); } #endif - if (mvControlled->CoupledCtrl) + if (controlled->CoupledCtrl) { - ggMainCtrl.UpdateValue(static_cast(double(mvControlled->MainCtrlPos + mvControlled->ScndCtrlPos)), dsbNastawnikJazdy); + ggMainCtrl.UpdateValue(static_cast(double(controlled->MainCtrlPos + controlled->ScndCtrlPos)), dsbNastawnikJazdy); } else { - ggMainCtrl.UpdateValue(static_cast(double(mvControlled->MainCtrlPos)), dsbNastawnikJazdy); + ggMainCtrl.UpdateValue(static_cast(double(controlled->MainCtrlPos)), dsbNastawnikJazdy); } ggMainCtrl.Update(); } if (ggMainCtrlAct.SubModel != nullptr) { - ggMainCtrlAct.UpdateValue(main_ctrl_act::position(*mvControlled, ggMainCtrlAct.has_scaletable())); + ggMainCtrlAct.UpdateValue(main_ctrl_act::position(*controlled, ggMainCtrlAct.has_scaletable())); ggMainCtrlAct.Update(); } if (ggScndCtrl.SubModel != nullptr) @@ -1232,7 +1232,7 @@ void TTrain::updateMasterControllers(bool const lowvoltagepower) // Ra: od byte odejmowane boolean i konwertowane potem na double? if (false == ggScndCtrl.is_push()) { - ggScndCtrl.UpdateValue(static_cast(double(mvControlled->ScndCtrlPos - (mvControlled->TrainType == train_type::et42 && mvControlled->DynamicBrakeFlag))), dsbNastawnikBocz); + ggScndCtrl.UpdateValue(static_cast(double(controlled->ScndCtrlPos - (controlled->TrainType == train_type::et42 && controlled->DynamicBrakeFlag))), dsbNastawnikBocz); } ggScndCtrl.Update(); } @@ -1240,7 +1240,7 @@ void TTrain::updateMasterControllers(bool const lowvoltagepower) { if (ggScndCtrlButton.is_toggle()) { - ggScndCtrlButton.UpdateValue(mvControlled->IsSpeedCtrlEngaged() ? 1.f : 0.f, dsbSwitch); + ggScndCtrlButton.UpdateValue(controlled->IsSpeedCtrlEngaged() ? 1.f : 0.f, dsbSwitch); } ggScndCtrlButton.Update(lowvoltagepower); } @@ -1254,13 +1254,13 @@ void TTrain::updateMasterControllers(bool const lowvoltagepower) } if (ggDirKey.SubModel != nullptr) { - if (mvControlled->TrainType != train_type::emu) + if (controlled->TrainType != train_type::emu) { - ggDirKey.UpdateValue(static_cast(double(mvControlled->DirActive)), dsbReverserKey); + ggDirKey.UpdateValue(static_cast(double(controlled->DirActive)), dsbReverserKey); } else { - ggDirKey.UpdateValue(static_cast(double(mvControlled->DirActive) + double(mvControlled->Imin == mvControlled->IminHi)), dsbReverserKey); + ggDirKey.UpdateValue(static_cast(double(controlled->DirActive) + double(controlled->Imin == controlled->IminHi)), dsbReverserKey); } ggDirKey.Update(); } @@ -1276,37 +1276,37 @@ void TTrain::updateBrakeControllers() false && Global.fCalibrateIn[0][1] != 0.0) // nie blokujemy AI { // Ra: nie najlepsze miejsce, ale na początek gdzieś to dać trzeba // Firleju: dlatego kasujemy i zastepujemy funkcją w Console - if (mvOccupied->BrakeHandle == TBrakeHandle::FV4a) + if (occupied->BrakeHandle == TBrakeHandle::FV4a) { double b = Console::AnalogCalibrateGet(0); b = b * 8.0 - 2.0; - b = safe_clamp(b, -2.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic + b = safe_clamp(b, -2.0, (double)occupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia - mvOccupied->BrakeLevelSet(b); + occupied->BrakeLevelSet(b); } - else if (mvOccupied->BrakeHandle == TBrakeHandle::FVel6) // może można usunąć ograniczenie do FV4a i FVel6? + else if (occupied->BrakeHandle == TBrakeHandle::FVel6) // może można usunąć ograniczenie do FV4a i FVel6? { double b = Console::AnalogCalibrateGet(0); b = b * 7.0 - 1.0; - b = safe_clamp(b, -1.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic + b = safe_clamp(b, -1.0, (double)occupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia - mvOccupied->BrakeLevelSet(b); + occupied->BrakeLevelSet(b); } else { double b = Console::AnalogCalibrateGet(0); - b = b * (mvOccupied->Handle->GetPos(bh_MAX) - mvOccupied->Handle->GetPos(bh_MIN)) + mvOccupied->Handle->GetPos(bh_MIN); - b = safe_clamp(b, mvOccupied->Handle->GetPos(bh_MIN), mvOccupied->Handle->GetPos(bh_MAX)); // przycięcie zmiennej do granic + b = b * (occupied->Handle->GetPos(bh_MAX) - occupied->Handle->GetPos(bh_MIN)) + occupied->Handle->GetPos(bh_MIN); + b = safe_clamp(b, occupied->Handle->GetPos(bh_MIN), occupied->Handle->GetPos(bh_MAX)); // przycięcie zmiennej do granic ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia - mvOccupied->BrakeLevelSet(b); + occupied->BrakeLevelSet(b); } } else #endif { // else //standardowa prodedura z kranem powiązanym z klawiaturą - // ggBrakeCtrl.UpdateValue(double(mvOccupied->BrakeCtrlPos)); - ggBrakeCtrl.UpdateValue(static_cast(mvOccupied->fBrakeCtrlPos)); + // ggBrakeCtrl.UpdateValue(double(occupied->BrakeCtrlPos)); + ggBrakeCtrl.UpdateValue(static_cast(occupied->fBrakeCtrlPos)); ggBrakeCtrl.Update(); } } @@ -1315,19 +1315,19 @@ void TTrain::updateBrakeControllers() { #ifdef _WIN32 if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag // nie blokujemy AI - && mvOccupied->BrakeLocHandle == TBrakeHandle::FD1 && Global.iFeedbackMode == 4 && Global.fCalibrateIn[0][1] != 0.0) + && occupied->BrakeLocHandle == TBrakeHandle::FD1 && Global.iFeedbackMode == 4 && Global.fCalibrateIn[0][1] != 0.0) { // Ra: nie najlepsze miejsce, ale na początek gdzieś to dać trzeba // Firleju: dlatego kasujemy i zastepujemy funkcją w Console auto const b = std::clamp(Console::AnalogCalibrateGet(1), 0.f, 1.f); - mvOccupied->LocalBrakePosA = b; + occupied->LocalBrakePosA = b; ggLocalBrake.UpdateValue(b * LocalBrakePosNo); } else #endif { // standardowa prodedura z kranem powiązanym z klawiaturą - ggLocalBrake.UpdateValue(static_cast(mvOccupied->LocalBrakePosA * LocalBrakePosNo)); + ggLocalBrake.UpdateValue(static_cast(occupied->LocalBrakePosA * LocalBrakePosNo)); } ggLocalBrake.Update(); } @@ -1345,9 +1345,9 @@ void TTrain::updateCabSwitches(bool const lowvoltagepower) ggBrakeProfileR.Update(); ggBrakeOperationModeCtrl.Update(); ggWiperSw.Update(); - ggMaxCurrentCtrl.UpdateValue(true == mvControlled->ShuntModeAllow ? (true == mvControlled->ShuntMode ? 1.f : 0.f) : mvControlled->MotorOverloadRelayHighThreshold ? 1.f : 0.f); + ggMaxCurrentCtrl.UpdateValue(true == controlled->ShuntModeAllow ? (true == controlled->ShuntMode ? 1.f : 0.f) : controlled->MotorOverloadRelayHighThreshold ? 1.f : 0.f); ggMaxCurrentCtrl.Update(); - ggAutoRelayButton.UpdateValue(mvOccupied->AutoRelayFlag ? 1.f : 0.f); + ggAutoRelayButton.UpdateValue(occupied->AutoRelayFlag ? 1.f : 0.f); ggAutoRelayButton.Update(); // NBMX wrzesien 2003 - drzwi ggDoorLeftPermitButton.Update(lowvoltagepower); @@ -1374,7 +1374,7 @@ void TTrain::updateHeatingAndInstrumentLights() { //--------- // hunter-080812: poprawka na ogrzewanie w elektrykach - usuniete uzaleznienie od przetwornicy - if (mvControlled->Heating == true && mvControlled->ConvOvldFlag == false) + if (controlled->Heating == true && controlled->ConvOvldFlag == false) btLampkaOgrzewanieSkladu.Turn(true); else btLampkaOgrzewanieSkladu.Turn(false); @@ -1382,14 +1382,14 @@ void TTrain::updateHeatingAndInstrumentLights() //---------- // lights - auto const lightpower{(InstrumentLightType == 0 ? mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable : - InstrumentLightType == 1 ? mvControlled->Mains : - InstrumentLightType == 2 ? mvOccupied->Power110vIsAvailable : - InstrumentLightType == 3 ? mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable : - InstrumentLightType == 4 ? mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable : + auto const lightpower{(InstrumentLightType == 0 ? occupied->Power24vIsAvailable || occupied->Power110vIsAvailable : + InstrumentLightType == 1 ? controlled->Mains : + InstrumentLightType == 2 ? occupied->Power110vIsAvailable : + InstrumentLightType == 3 ? occupied->Power24vIsAvailable || occupied->Power110vIsAvailable : + InstrumentLightType == 4 ? occupied->Power24vIsAvailable || occupied->Power110vIsAvailable : false)}; InstrumentLightActive = InstrumentLightType == 3 ? true : // TODO: link the light state with the state of the master key - InstrumentLightType == 4 ? mvOccupied->iLights[VehicleEnd::front] != 0 || mvOccupied->iLights[VehicleEnd::rear] != 0 : + InstrumentLightType == 4 ? occupied->iLights[VehicleEnd::front] != 0 || occupied->iLights[VehicleEnd::rear] != 0 : InstrumentLightActive; btInstrumentLight.Turn(InstrumentLightActive && lightpower); btDashboardLight.Turn(DashboardLightActive && lightpower); @@ -1478,14 +1478,14 @@ void TTrain::updateAuxiliaryButtons(bool const lowvoltagepower) //------------ // the converter switches follow the vehicle when something else flips them (the AI driver, the other cab, // the pressure switch of an EMU), not only when the cab is entered (set_cab_controls()) - if (ggConverterButton.SubModel != nullptr && mvOccupied->ConvSwitchType != "impulse" && mvOccupied->ConverterStart == start_t::manual) + if (ggConverterButton.SubModel != nullptr && occupied->ConvSwitchType != "impulse" && occupied->ConverterStart == start_t::manual) { - ggConverterButton.UpdateValue(mvOccupied->ConverterAllow ? 1.f : 0.f, dsbSwitch); + ggConverterButton.UpdateValue(occupied->ConverterAllow ? 1.f : 0.f, dsbSwitch); } ggConverterButton.Update(); if (ggConverterLocalButton.SubModel != nullptr) { - ggConverterLocalButton.UpdateValue(mvOccupied->ConverterAllowLocal ? 1.f : 0.f, dsbSwitch); + ggConverterLocalButton.UpdateValue(occupied->ConverterAllowLocal ? 1.f : 0.f, dsbSwitch); } ggConverterLocalButton.Update(); ggConverterOffButton.Update(); @@ -1543,7 +1543,7 @@ void TTrain::updateAuxiliaryButtons(bool const lowvoltagepower) ggBatteryOffButton.Update(); if (ggCabActivationButton.SubModel != nullptr && ggCabActivationButton.type() != TGaugeType::push) { - ggCabActivationButton.UpdateValue(mvOccupied->IsCabMaster() ? 1.0 : 0.0); + ggCabActivationButton.UpdateValue(occupied->IsCabMaster() ? 1.0 : 0.0); } ggCabActivationButton.Update(); @@ -1574,7 +1574,7 @@ void TTrain::updateCabLightLevels() for (auto &cab : Cabine) { - auto const cablightlevel = (cab.bLight == false ? 0.f : cab.bLightDim == true ? 0.4f : 1.f) * (mvOccupied->Power110vIsAvailable ? 1.f : 0.5f); + auto const cablightlevel = (cab.bLight == false ? 0.f : cab.bLightDim == true ? 0.4f : 1.f) * (occupied->Power110vIsAvailable ? 1.f : 0.5f); if (cab.LightLevel != cablightlevel) { @@ -1593,23 +1593,23 @@ void TTrain::updateCabLightLevels() void TTrain::UpdateDirectionRelays() { - if (mvOccupied->DirActive < 0 && mvOccupied->Power24vIsAvailable) // wstecz + if (occupied->DirActive < 0 && occupied->Power24vIsAvailable) // wstecz Dynamic()->sDirectionRelayR.play(); - if (mvOccupied->DirActive == 0 && mvOccupied->Power24vIsAvailable) // neutral + if (occupied->DirActive == 0 && occupied->Power24vIsAvailable) // neutral Dynamic()->sDirectionRelayN.play(); - if (mvOccupied->DirActive > 0 && mvOccupied->Power24vIsAvailable) // przod + if (occupied->DirActive > 0 && occupied->Power24vIsAvailable) // przod Dynamic()->sDirectionRelayD.play(); } void TTrain::SetupDirectionRelays() { - if (mvOccupied->Power24vIsAvailable) + if (occupied->Power24vIsAvailable) { - if (mvOccupied->DirActive < 0 && mvOccupied->Power24vIsAvailable) // wstecz + if (occupied->DirActive < 0 && occupied->Power24vIsAvailable) // wstecz Dynamic()->sDirectionRelayR.play(); - if (mvOccupied->DirActive > 0 && mvOccupied->Power24vIsAvailable) // przod + if (occupied->DirActive > 0 && occupied->Power24vIsAvailable) // przod Dynamic()->sDirectionRelayD.play(); } - else if (mvOccupied->DirActive != 0) // neutral + else if (occupied->DirActive != 0) // neutral Dynamic()->sDirectionRelayN.play(); } diff --git a/vehicle/crew.cpp b/vehicle/crew.cpp index e375a0c0f..2484ca9f7 100644 --- a/vehicle/crew.cpp +++ b/vehicle/crew.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/crew.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/handover.h" namespace crew { @@ -23,7 +23,7 @@ char lower_ascii(char const Character) { } // the controllers of the vehicle to the positions giving no power, and the vehicles it controls told so -void cut_power(TMoverParameters &Vehicle) { +void cut_power(physics::Vehicle &Vehicle) { Vehicle.MainCtrlPos = Vehicle.MainCtrlNoPowerPos(); Vehicle.ScndCtrlPos = 0; // what the integrated handle and the cruise control asked for last stays in force until somebody drives @@ -110,7 +110,7 @@ std::string_view describe(action const Action) { } } -void secure(TMoverParameters &Occupied, TMoverParameters &Controlling) { +void secure(physics::Vehicle &Occupied, physics::Vehicle &Controlling) { handover::release_ai_controls(Occupied, Controlling); cut_power(Controlling); if (&Occupied != &Controlling) { diff --git a/vehicle/crew.h b/vehicle/crew.h index f2ab938f1..d7c7fb325 100644 --- a/vehicle/crew.h +++ b/vehicle/crew.h @@ -12,7 +12,7 @@ http://mozilla.org/MPL/2.0/. #include #include -class TMoverParameters; +namespace physics { class Vehicle; } // a driver put in a vehicle, or taken off it, while the scenario runs (eu07/maszyna#510): the command of a // putvalues event @@ -76,7 +76,7 @@ std::string_view describe(action Action); // hands over to a user, see handover.h), the power is off, the driver's brake valve is in the emergency position, // so a train on the move stops and stays braked, and the cab is neither active nor occupied. the engine, the // pantographs and the lights stay as they were. Occupied is the vehicle of the driver, Controlling the one whose -// motors it drove (the AI's mvOccupied and mvControlling; the same one in a locomotive) -void secure(TMoverParameters &Occupied, TMoverParameters &Controlling); +// motors it drove (the AI's occupied and mvControlling; the same one in a locomotive) +void secure(physics::Vehicle &Occupied, physics::Vehicle &Controlling); } // namespace crew diff --git a/vehicle/crewchange.cpp b/vehicle/crewchange.cpp index 06d72ab12..e509ea7cf 100644 --- a/vehicle/crewchange.cpp +++ b/vehicle/crewchange.cpp @@ -16,13 +16,13 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/DynObj.h" #include "vehicle/Train.h" #include "vehicle/handover.h" -#include "physics/mover.h" +#include "physics/vehicle.h" namespace crew { namespace { -// TMoverParameters::CategoryFlag of the rail vehicles +// physics::Vehicle::CategoryFlag of the rail vehicles constexpr int rail_category{1}; // more vehicles than a consist has, for a walk along one whose couplers form a loop constexpr int consist_walk_limit{300}; @@ -57,7 +57,7 @@ vehicle_state state_of(TDynamicObject &Vehicle) { vehicle_state state; // a rail vehicle has a cab when it has the driver's brake valve. the others (cars, boats) have no such valve // to tell by, and each of them is driven from its own seat - state.has_cab = Vehicle.MoverParameters->HasDriverCab() || Vehicle.MoverParameters->CategoryFlag != rail_category; + state.has_cab = Vehicle.physics->HasDriverCab() || Vehicle.physics->CategoryFlag != rail_category; state.has_driver = Vehicle.Mechanik != nullptr; state.driver_is_ai = state.has_driver && Vehicle.Mechanik->AIControllFlag; // a cab of the game is bound to the vehicle: the user's own, or another user's in a network game. the cab @@ -70,7 +70,7 @@ vehicle_state state_of(TDynamicObject &Vehicle) { // an AI driver for the vehicle, as the scenery gives one to a vehicle of its own outside a trainset: in charge of // the consist, with no timetable, waiting for orders when the vehicle stands and driving on when it rolls void add_driver(TDynamicObject &Vehicle, int const Cab) { - Vehicle.MoverParameters->CabOccupied = Cab; + Vehicle.physics->CabOccupied = Cab; Vehicle.Controller = AIdriver; Vehicle.create_controller(Cab > 0 ? "1" : "2", false); } @@ -78,12 +78,12 @@ void add_driver(TDynamicObject &Vehicle, int const Cab) { // takes the AI driver off. nothing but the vehicle and the vehicles the driver is in charge of points at a driver // (the panels, the events, the network and the black box read it from a vehicle each time), so these are cleared // and the driver deleted. the vehicles in its charge are looked for among all vehicles, not along the couplers: -// a coupler broken under force or in a collision (TMoverParameters::damage_coupler()) parts the train and leaves +// a coupler broken under force or in a collision (physics::Vehicle::damage_coupler()) parts the train and leaves // the vehicles parted from it in the driver's charge, as uncoupling (TDynamicObject::Dettach()) doesn't void remove_driver(TDynamicObject &Vehicle) { auto *driver{Vehicle.Mechanik}; - auto &occupied{*Vehicle.MoverParameters}; - auto &controlling{*Vehicle.FindPowered()->MoverParameters}; + auto &occupied{*Vehicle.physics}; + auto &controlling{*Vehicle.FindPowered()->physics}; if (driver->primary()) { // the train this driver was in charge of stops and stays braked secure(occupied, controlling); diff --git a/vehicle/derailmotion.h b/vehicle/derailmotion.h index 4e7163ae8..20c89747f 100644 --- a/vehicle/derailmotion.h +++ b/vehicle/derailmotion.h @@ -22,7 +22,7 @@ http://mozilla.org/MPL/2.0/. // a rail vehicle off the rails (physics.derailment new, see physics/derailment.h for when it derails): from then on // it doesn't follow the track any more, it moves on the ground by itself until the friction stops it. // -// along: the longitudinal motion stays with the physics of the vehicle (TMoverParameters), which brakes it with the +// along: the longitudinal motion stays with the physics of the vehicle (physics::Vehicle), which brakes it with the // friction() of this one, takes the grade() under it and passes the forces of the couplings on; each step gives // the distance travelled along the heading of the vehicle // the heading: the way it travels; the one the vehicle had when it derailed, turned out of the curve by the sideways @@ -382,7 +382,7 @@ public: double yaw_rate() const { return m_yawrate; } // how many times the heading was turned about, the body having turned more than a right angle off the way it // goes: the heading stays within a right angle of the front of the body, so the speed along the heading (of - // TMoverParameters, of its couplers at its ends) goes with the body; the speed changes its sign with each + // physics::Vehicle, of its couplers at its ends) goes with the body; the speed changes its sign with each int reversals() const { return m_reversals; } cause reason() const { return m_reason; } // the vehicle the motion was begun with diff --git a/vehicle/doorwings.h b/vehicle/doorwings.h index db05b03fc..4c9304445 100644 --- a/vehicle/doorwings.h +++ b/vehicle/doorwings.h @@ -20,11 +20,11 @@ http://mozilla.org/MPL/2.0/. #include -// the poses of the animated door wings of a vehicle, for the door position of the mover. a wing is posed alike +// the poses of the animated door wings of a vehicle, for the door position of the physics. a wing is posed alike // in the main model and, when the low poly interior has a submodel of the same name, in the interior as well namespace door_wings { -// the kinds of wing animation, numbered as DoorOpenMethod of the .fiz (TMoverParameters::door_data::type) +// the kinds of wing animation, numbered as DoorOpenMethod of the .fiz (physics::Vehicle::door_data::type) inline constexpr int shift_type{1}; inline constexpr int rotate_type{2}; inline constexpr int fold_type{3}; diff --git a/vehicle/drivingaid.cpp b/vehicle/drivingaid.cpp index a7d4f2af2..49f0e8ef9 100644 --- a/vehicle/drivingaid.cpp +++ b/vehicle/drivingaid.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/drivingaid.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "physics/brakes.h" #include @@ -59,7 +59,7 @@ readout compute(input const &Input) { return result; } -input from_movers(TMoverParameters const &Vehicle, TMoverParameters const &Controlling, cab_controls const &Cab) { +input from_vehicles(physics::Vehicle const &Vehicle, physics::Vehicle const &Controlling, cab_controls const &Cab) { input result; result.eim = Vehicle.EngineType == TEngineType::ElectricInductionMotor || Vehicle.EIMCtrlType > 0; result.eimctrltype = Vehicle.EIMCtrlType; diff --git a/vehicle/drivingaid.h b/vehicle/drivingaid.h index 8cec257da..71b44f773 100644 --- a/vehicle/drivingaid.h +++ b/vehicle/drivingaid.h @@ -11,7 +11,7 @@ http://mozilla.org/MPL/2.0/. #include -class TMoverParameters; +namespace physics { class Vehicle; } // what the driving aid panel shows of the controls and of the braking: the numbers of its throttle and // brakes lines, worked out from the vehicle state (eu07/maszyna#558, eu07/maszyna#555) @@ -63,6 +63,6 @@ readout compute(input const &Input); // the state the panel reads: Vehicle is the one the driver sits in, Controlling the one whose controllers // the driver moves (TController::Controlling()) -input from_movers(TMoverParameters const &Vehicle, TMoverParameters const &Controlling, cab_controls const &Cab); +input from_vehicles(physics::Vehicle const &Vehicle, physics::Vehicle const &Controlling, cab_controls const &Cab); } // namespace drivingaid diff --git a/vehicle/dynamic/animations.cpp b/vehicle/dynamic/animations.cpp index f726ee58d..7dfc25bc3 100644 --- a/vehicle/dynamic/animations.cpp +++ b/vehicle/dynamic/animations.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/DynObj.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/lightsprogrammer.h" #include "simulation/simulation.h" #include "simulation/blackboxrecorder.h" @@ -141,7 +141,7 @@ void TAnimPant::DSAx() common_pantograph_settings(); }; //--------------------------------------------------------------------------- -int TAnim::TypeSet(int i, TMoverParameters currentMover, int fl) +int TAnim::TypeSet(int i, physics::Vehicle currentPhysics, int fl) { // ustawienie typu animacji i zależnej od niego ilości animowanych submodeli fMaxDist = -1.0; // normalnie nie pokazywać switch (i) @@ -170,7 +170,7 @@ int TAnim::TypeSet(int i, TMoverParameters currentMover, int fl) case 5: // 5-pantograf - 5 submodeli iFlags = 0x055; fParamPants = new TAnimPant(); - switch (currentMover.EnginePowerSource.CollectorParameters.PantographType) { + switch (currentPhysics.EnginePowerSource.CollectorParameters.PantographType) { case TPantType::AKP_4E: fParamPants->AKP_4E(); break; @@ -279,7 +279,7 @@ void TDynamicObject::SetPneumatic(bool front, bool red) x = 3; break; // mamy prawy skos, dać prawe skosy case 3: // wszystkie cztery na prosto - if (MoverParameters->Couplers[front ? VehicleEnd::front : VehicleEnd::rear].Render) + if (physics->Couplers[front ? VehicleEnd::front : VehicleEnd::rear].Render) x = 1; else x = 4; @@ -351,9 +351,9 @@ namespace // the position of the door the animated wing belongs to: its shift or angle from closed -float door_position( TMoverParameters const &Mover, TAnim const *Animation ) { +float door_position( physics::Vehicle const &Physics, TAnim const *Animation ) { - return Mover.Doors.instances[ ( + return Physics.Doors.instances[ ( door_wings::on_right_side( Animation->iNumber ) ? VehicleSide::right : VehicleSide::left ) ].position; @@ -388,7 +388,7 @@ void TDynamicObject::UpdateDoorTranslate(TAnim *pAnim) { if( pAnim->smAnimated == nullptr ) { return; } - auto const shift { door_wings::slide( door_position( *MoverParameters, pAnim ) ) }; + auto const shift { door_wings::slide( door_position( *physics, pAnim ) ) }; for( auto *wing : wing_parts( pAnim ) ) { if( wing != nullptr ) { wing->SetTranslate( shift ); @@ -401,7 +401,7 @@ void TDynamicObject::UpdateDoorRotate(TAnim *pAnim) { if( pAnim->smAnimated == nullptr ) { return; } - auto const angle { door_position( *MoverParameters, pAnim ) }; + auto const angle { door_position( *physics, pAnim ) }; for( auto *wing : wing_parts( pAnim ) ) { if( wing != nullptr ) { wing->SetRotate( float3( 1, 0, 0 ), angle ); @@ -414,7 +414,7 @@ void TDynamicObject::UpdateDoorFold(TAnim *pAnim) { if( pAnim->smAnimated == nullptr ) { return; } - auto const angles { door_wings::fold( door_position( *MoverParameters, pAnim ) ) }; + auto const angles { door_wings::fold( door_position( *physics, pAnim ) ) }; for( auto *wing : wing_parts( pAnim ) ) { fold_wing( wing, angles ); } @@ -425,7 +425,7 @@ void TDynamicObject::UpdateDoorPlug(TAnim *pAnim) { if( pAnim->smAnimated == nullptr ) { return; } - auto const shift { door_wings::plug( door_position( *MoverParameters, pAnim ), MoverParameters->Doors.range_out ) }; + auto const shift { door_wings::plug( door_position( *physics, pAnim ), physics->Doors.range_out ) }; for( auto *wing : wing_parts( pAnim ) ) { if( wing != nullptr ) { wing->SetTranslate( shift ); @@ -438,7 +438,7 @@ void TDynamicObject::UpdateDoorWing( TAnim *pAnim, door_wings::wing_spec const & if( pAnim->smAnimated == nullptr ) { return; } - auto const position { door_wings::wing_position( door_position( *MoverParameters, pAnim ), MoverParameters->Doors.range, Spec.range ) }; + auto const position { door_wings::wing_position( door_position( *physics, pAnim ), physics->Doors.range, Spec.range ) }; for( auto *wing : wing_parts( pAnim ) ) { if( wing == nullptr ) { continue; } switch( Spec.type ) { @@ -471,7 +471,7 @@ void TDynamicObject::bind_door_animation( TAnim &Animation ) { Animation.yUpdate = [ this, spec = *spec ]( TAnim *pAnim ) { UpdateDoorWing( pAnim, spec ); }; return; } - switch( MoverParameters->Doors.type ) { // od razu zapinamy potrzebny typ animacji + switch( physics->Doors.type ) { // od razu zapinamy potrzebny typ animacji case 1: Animation.yUpdate = std::bind( &TDynamicObject::UpdateDoorTranslate, this, std::placeholders::_1 ); break; @@ -512,14 +512,14 @@ void TDynamicObject::UpdatePlatformTranslate( TAnim *pAnim ) { if( pAnim->smAnimated == nullptr ) { return; } - auto const &door { MoverParameters->Doors.instances[ ( + auto const &door { physics->Doors.instances[ ( ( pAnim->iNumber & 1 ) == 0 ? VehicleSide::right : VehicleSide::left ) ] }; pAnim->smAnimated->SetTranslate( glm::vec3{ - std::lerp( 0.f, MoverParameters->Doors.step_range, door.step_position ), + std::lerp( 0.f, physics->Doors.step_range, door.step_position ), 0.0, 0.0 } ); } @@ -529,14 +529,14 @@ void TDynamicObject::UpdatePlatformRotate( TAnim *pAnim ) { if( pAnim->smAnimated == nullptr ) { return; } - auto const &door { MoverParameters->Doors.instances[ ( + auto const &door { physics->Doors.instances[ ( ( pAnim->iNumber & 1 ) == 0 ? VehicleSide::right : VehicleSide::left ) ] }; pAnim->smAnimated->SetRotate( float3( 0, 1, 0 ), - std::lerp( 0.f, MoverParameters->Doors.step_range, door.step_position ) ); + std::lerp( 0.f, physics->Doors.step_range, door.step_position ) ); } // mirror animation, rotate @@ -546,18 +546,18 @@ void TDynamicObject::UpdateMirror( TAnim *pAnim ) { // only animate the mirror if it's located on the same end of the vehicle as the active cab auto const isactive { ( - MoverParameters->CabOccupied > 0 ? ( EndOf( pAnim->iNumber >> 4 ) == VehicleEnd::front ? 1.0 : 0.0 ) : - MoverParameters->CabOccupied < 0 ? ( EndOf( pAnim->iNumber >> 4 ) == VehicleEnd::rear ? 1.0 : 0.0 ) : + physics->CabOccupied > 0 ? ( EndOf( pAnim->iNumber >> 4 ) == VehicleEnd::front ? 1.0 : 0.0 ) : + physics->CabOccupied < 0 ? ( EndOf( pAnim->iNumber >> 4 ) == VehicleEnd::rear ? 1.0 : 0.0 ) : 0.0 ) }; if( pAnim->iNumber & 1 ) pAnim->smAnimated->SetRotate( float3( 0, 1, 0 ), - std::lerp( 0.0, MoverParameters->MirrorMaxShift, dMirrorMoveR * isactive ) ); + std::lerp( 0.0, physics->MirrorMaxShift, dMirrorMoveR * isactive ) ); else pAnim->smAnimated->SetRotate( float3( 0, 1, 0 ), - std::lerp( 0.0, MoverParameters->MirrorMaxShift, dMirrorMoveL * isactive ) ); + std::lerp( 0.0, physics->MirrorMaxShift, dMirrorMoveL * isactive ) ); } // wipers @@ -568,7 +568,7 @@ void TDynamicObject::UpdateWiper(TAnim* pAnim) int i = pAnim->iNumber; // odwaramy animacje dla parzystych indexow - const double rotateAngle = (i + 1) % 2 == 0 ? -MoverParameters->WiperAngle : MoverParameters->WiperAngle; + const double rotateAngle = (i + 1) % 2 == 0 ? -physics->WiperAngle : physics->WiperAngle; if (pAnim->smElement[0]) // ramie 1 pAnim->smElement[0]->SetRotate(float3(0, 1, 0), smoothInterpolate(0.0, rotateAngle, dWiperPos[i])); diff --git a/vehicle/dynamic/consist.cpp b/vehicle/dynamic/consist.cpp index 2a53e7d2b..aa417f1c6 100644 --- a/vehicle/dynamic/consist.cpp +++ b/vehicle/dynamic/consist.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/DynObj.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/lightsprogrammer.h" #include "simulation/simulation.h" #include "simulation/blackboxrecorder.h" @@ -68,7 +68,7 @@ TDynamicObject * TDynamicObject::FirstFind(int &coupler_nr, CouplingSet const cf { if (!temp) return nullptr; // Ra: zabezpieczenie przed ewentaulnymi błędami sprzęgów - if (false == temp->MoverParameters->Couplers[coupler_nr].CouplingFlag.HasAll(cf)) + if (false == temp->physics->Couplers[coupler_nr].CouplingFlag.HasAll(cf)) return temp; // nic nie ma już dalej podłączone sprzęgiem cf if (EndOf(coupler_nr) == VehicleEnd::front) { // jeżeli szukamy od sprzęgu 0 @@ -109,9 +109,9 @@ float TDynamicObject::GetEPP() { if (!temp) break; // Ra: zabezpieczenie przed ewentaulnymi błędami sprzęgów - eq += temp->MoverParameters->PipePress * temp->MoverParameters->Dim.L; - am += temp->MoverParameters->Dim.L; - if ((temp->MoverParameters->Couplers[coupler_nr].CouplingFlag & Coupling::brakeHose) != Coupling::brakeHose) + eq += temp->physics->PipePress * temp->physics->Dim.L; + am += temp->physics->Dim.L; + if ((temp->physics->Couplers[coupler_nr].CouplingFlag & Coupling::brakeHose) != Coupling::brakeHose) break; // nic nie ma już dalej podłączone if (coupler_nr == 0) { // jeżeli szukamy od sprzęgu 0 @@ -143,9 +143,9 @@ float TDynamicObject::GetEPP() { if (!temp) break; // Ra: zabezpieczenie przed ewentaulnymi błędami sprzęgów - eq += temp->MoverParameters->PipePress * temp->MoverParameters->Dim.L; - am += temp->MoverParameters->Dim.L; - if ((temp->MoverParameters->Couplers[coupler_nr].CouplingFlag & Coupling::brakeHose) != Coupling::brakeHose) + eq += temp->physics->PipePress * temp->physics->Dim.L; + am += temp->physics->Dim.L; + if ((temp->physics->Couplers[coupler_nr].CouplingFlag & Coupling::brakeHose) != Coupling::brakeHose) break; // nic nie ma już dalej podłączone if (coupler_nr == 0) { // jeżeli szukamy od sprzęgu 0 @@ -170,8 +170,8 @@ float TDynamicObject::GetEPP() break; // jeśli jednak z tyłu nic nie ma } } - eq -= MoverParameters->PipePress * MoverParameters->Dim.L; - am -= MoverParameters->Dim.L; + eq -= physics->PipePress * physics->Dim.L; + am -= physics->Dim.L; return eq / am; }; @@ -209,13 +209,13 @@ int TDynamicObject::DirectionSet(int d) // wskaźnik na poprzedni, nawet wirtualny TDynamicObject * TDynamicObject::PrevAny() const { - return MoverParameters->Neighbours[ iDirection ^ 1 ].vehicle; + return physics->Neighbours[ iDirection ^ 1 ].vehicle; } TDynamicObject * TDynamicObject::Prev(CouplingSet const couplings) const { - return MoverParameters->Couplers[iDirection ^ 1].CouplingFlag.HasAny(couplings) ? MoverParameters->Neighbours[iDirection ^ 1].vehicle : nullptr;// gdy sprzęg wirtualny, to jakby nic nie było + return physics->Couplers[iDirection ^ 1].CouplingFlag.HasAny(couplings) ? physics->Neighbours[iDirection ^ 1].vehicle : nullptr;// gdy sprzęg wirtualny, to jakby nic nie było } TDynamicObject * TDynamicObject::Next(CouplingSet const couplings) const { - return MoverParameters->Couplers[iDirection].CouplingFlag.HasAny(couplings) ? MoverParameters->Neighbours[iDirection].vehicle : nullptr;// gdy sprzęg wirtualny, to jakby nic nie było + return physics->Couplers[iDirection].CouplingFlag.HasAny(couplings) ? physics->Neighbours[iDirection].vehicle : nullptr;// gdy sprzęg wirtualny, to jakby nic nie było } // checks whether there's unbroken connection of specified type to specified vehicle @@ -253,11 +253,11 @@ TDynamicObject * TDynamicObject::Neighbour(int &dir) { auto *neighbour { ( - MoverParameters->Couplers[ dir ].CouplingFlag != Coupling::none ? - MoverParameters->Neighbours[ dir ].vehicle : + physics->Couplers[ dir ].CouplingFlag != Coupling::none ? + physics->Neighbours[ dir ].vehicle : nullptr ) }; // nowa wartość - dir = 1 - MoverParameters->Neighbours[ dir ].vehicle_end; + dir = 1 - physics->Neighbours[ dir ].vehicle_end; return neighbour; }; @@ -268,22 +268,22 @@ TDynamicObject::update_neighbours() { for (auto const end : VehicleEnds) { - auto &neighbour { MoverParameters->Neighbours[ end ] }; - auto const &coupler { MoverParameters->Couplers[ end ] }; + auto &neighbour { physics->Neighbours[ end ] }; + auto const &coupler { physics->Couplers[ end ] }; if( coupler.Connected != nullptr && neighbour.vehicle != nullptr ) { // physical connection with another vehicle locks down collision source on this end // neighbour.vehicle = coupler.Connected; // neighbour.vehicle_end = coupler.ConnectedNr; - neighbour.distance = TMoverParameters::CouplerDist( MoverParameters, coupler.Connected ); - if( MoverParameters->OffTrack.active() || neighbour.vehicle->MoverParameters->OffTrack.active() ) { + neighbour.distance = physics::Vehicle::CouplerDist( physics, coupler.Connected ); + if( physics->OffTrack.active() || neighbour.vehicle->physics->OffTrack.active() ) { // physics.derailment new: off the track the bodies turn against each other, the ends meet where they are // (the distance between the middles less the half lengths would press the buffers of a bent pair) neighbour.distance = off_track_gap( end ); } // take into account potential adapters attached to the couplers - auto const &othercoupler { neighbour.vehicle->MoverParameters->Couplers[ neighbour.vehicle_end ] }; + auto const &othercoupler { neighbour.vehicle->physics->Couplers[ neighbour.vehicle_end ] }; neighbour.distance -= coupler.adapter_length; neighbour.distance -= othercoupler.adapter_length; } @@ -292,7 +292,7 @@ TDynamicObject::update_neighbours() { // NOTE: we perform a new scan on each update to ensure we always locate the nearest potential source neighbour = neighbour_data(); // 10m ~= 140 km/h at 4 fps + safety margin, potential distance between outer axles of involved vehicles - auto const scanrange { std::max( 10.0, std::abs( MoverParameters->V ) ) + 40.0 }; + auto const scanrange { std::max( 10.0, std::abs( physics->V ) ) + 40.0 }; // physics.derailment new: a vehicle off the track beside the other one doesn't run into it, the scan goes on // past it to the vehicles beyond auto const lookup { find_vehicle( NumberOf( end ), scanrange, true ) }; @@ -304,15 +304,15 @@ TDynamicObject::update_neighbours() { neighbour.distance = std::get( lookup ); if( neighbour.vehicle - && neighbour.distance < (neighbour.vehicle->MoverParameters->CategoryFlag == 2 ? 50 : 100) ) { + && neighbour.distance < (neighbour.vehicle->physics->CategoryFlag == 2 ? 50 : 100) ) { // at short distances (re)calculate range between couplers directly - neighbour.distance = TMoverParameters::CouplerDist( MoverParameters, neighbour.vehicle->MoverParameters ); - if( MoverParameters->OffTrack.active() || neighbour.vehicle->MoverParameters->OffTrack.active() ) { + neighbour.distance = physics::Vehicle::CouplerDist( physics, neighbour.vehicle->physics ); + if( physics->OffTrack.active() || neighbour.vehicle->physics->OffTrack.active() ) { // physics.derailment new: the ends where they are, as for a coupled pair neighbour.distance = off_track_gap( end ); } // take into account potential adapters attached to the couplers - auto const &othercoupler { neighbour.vehicle->MoverParameters->Couplers[ neighbour.vehicle_end ] }; + auto const &othercoupler { neighbour.vehicle->physics->Couplers[ neighbour.vehicle_end ] }; neighbour.distance -= coupler.adapter_length; neighbour.distance -= othercoupler.adapter_length; } @@ -325,7 +325,7 @@ TDynamicObject::in_line_with( TDynamicObject const &Other ) const { // the middle of the other one off the axis of this one, and this one off the axis of the other one, by less than // the half widths of both: their ends can meet - auto const reach { 0.5 * ( MoverParameters->Dim.W + Other.MoverParameters->Dim.W ) }; + auto const reach { 0.5 * ( physics->Dim.W + Other.physics->Dim.W ) }; auto const apart { Other.vPosition - vPosition }; return std::abs( glm::dot( apart, vLeft ) ) < reach && std::abs( glm::dot( apart, Other.vLeft ) ) < reach; } @@ -400,8 +400,8 @@ TDynamicObject::find_vehicle( int const Direction, double const Distance, bool c if( foundobject == nullptr ) { return {}; } /* - auto const *vehicle { MoverParameters }; - auto const *foundvehicle { foundobject->MoverParameters }; + auto const *vehicle { physics }; + auto const *foundvehicle { foundobject->physics }; if( ( false == TestFlag( track->iCategoryFlag, 1 ) ) && ( distance > 50.0 ) ) { // Ra: jeśli dwa samochody się mijają na odcinku przed zawrotką, to odległość między nimi nie może być liczona w linii prostej! @@ -411,7 +411,7 @@ TDynamicObject::find_vehicle( int const Direction, double const Distance, bool c else if( distance < 100.0 ) { // at short distances start to calculate range between couplers directly // odległość do najbliższego pojazdu w linii prostej - distance = TMoverParameters::CouplerDist( vehicle, foundvehicle ); + distance = physics::Vehicle::CouplerDist( vehicle, foundvehicle ); } */ return { foundobject, foundcoupler, distance, true }; @@ -428,7 +428,7 @@ TDynamicObject * TDynamicObject::FindPowered() // problematyczna może być kwestia wybranej kabiny (w silnikowym...) // jeśli silnikowy będzie zapięty odwrotnie (tzn. -1), to i tak powinno jeździć dobrze // również hamowanie wykonuje się zaworem w członie, a nie w silnikowym... - auto const coupling { MoverParameters->is_multiple_unit() ? + auto const coupling { physics->is_multiple_unit() ? Coupling::permanent : Coupling::control }; @@ -436,7 +436,7 @@ TDynamicObject * TDynamicObject::FindPowered() find_vehicle( coupling, []( TDynamicObject * vehicle ) { - return vehicle->MoverParameters->Power > 1.0; } ) }; + return vehicle->physics->Power > 1.0; } ) }; return lookup != nullptr ? lookup : this; // always return valid vehicle for backward compatibility } @@ -452,7 +452,7 @@ TDynamicObject::FindPantographCarrier() { find_vehicle( coupling, []( TDynamicObject * vehicle ) { - return vehicle->MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector && vehicle->MoverParameters->EnginePowerSource.CollectorParameters.CollectorsNo > 0; } ); + return vehicle->physics->EnginePowerSource.SourceType == TPowerSource::CurrentCollector && vehicle->physics->EnginePowerSource.CollectorParameters.CollectorsNo > 0; } ); if( result != nullptr ) { return result; } @@ -471,7 +471,7 @@ void TDynamicObject::ParamSet(int what, int into) // dla 8 różnych if (what & 1) // na razie mamy lewe oraz prawe, czyli używamy maskę 1=lewe, // 2=prawe, 3=wszystkie - if( MoverParameters->Doors.instances[VehicleSide::left].is_open ) + if( physics->Doors.instances[VehicleSide::left].is_open ) { // są otwarte if (!into) // jeśli zamykanie { @@ -486,7 +486,7 @@ void TDynamicObject::ParamSet(int what, int into) } } if (what & 2) // prawe działają niezależnie od lewych - if( MoverParameters->Doors.instances[VehicleSide::right].is_open ) + if( physics->Doors.instances[VehicleSide::right].is_open ) { // są otwarte if (!into) // jeśli zamykanie { @@ -512,17 +512,17 @@ int TDynamicObject::RouteWish(TTrack *tr) }; // the vehicles coupled at the ends, and the ends of theirs facing this one -TDynamicObject *TDynamicObject::NextConnected() { return MoverParameters->Neighbours[ VehicleEnd::rear ].vehicle; } -TDynamicObject *TDynamicObject::PrevConnected() { return MoverParameters->Neighbours[ VehicleEnd::front ].vehicle; } -TDynamicObject *TDynamicObject::NextConnected() const { return MoverParameters->Neighbours[ VehicleEnd::rear ].vehicle; } -TDynamicObject *TDynamicObject::PrevConnected() const { return MoverParameters->Neighbours[ VehicleEnd::front ].vehicle; } -int TDynamicObject::NextConnectedNo() const { return MoverParameters->Neighbours[ VehicleEnd::rear ].vehicle_end; } -int TDynamicObject::PrevConnectedNo() const { return MoverParameters->Neighbours[ VehicleEnd::front ].vehicle_end; } +TDynamicObject *TDynamicObject::NextConnected() { return physics->Neighbours[ VehicleEnd::rear ].vehicle; } +TDynamicObject *TDynamicObject::PrevConnected() { return physics->Neighbours[ VehicleEnd::front ].vehicle; } +TDynamicObject *TDynamicObject::NextConnected() const { return physics->Neighbours[ VehicleEnd::rear ].vehicle; } +TDynamicObject *TDynamicObject::PrevConnected() const { return physics->Neighbours[ VehicleEnd::front ].vehicle; } +int TDynamicObject::NextConnectedNo() const { return physics->Neighbours[ VehicleEnd::rear ].vehicle_end; } +int TDynamicObject::PrevConnectedNo() const { return physics->Neighbours[ VehicleEnd::front ].vehicle_end; } -void TDynamicObject::SetdMoveLen( double dMoveLen ) { MoverParameters->dMoveLen = dMoveLen; } -void TDynamicObject::ResetdMoveLen() { MoverParameters->dMoveLen = 0; } -double TDynamicObject::GetdMoveLen() { return MoverParameters->dMoveLen; } +void TDynamicObject::SetdMoveLen( double dMoveLen ) { physics->dMoveLen = dMoveLen; } +void TDynamicObject::ResetdMoveLen() { physics->dMoveLen = 0; } +double TDynamicObject::GetdMoveLen() { return physics->dMoveLen; } -double TDynamicObject::GetVelocity() const { return MoverParameters->Vel; } -double TDynamicObject::GetLength() const { return MoverParameters->Dim.L; } -double TDynamicObject::GetWidth() const { return MoverParameters->Dim.W; } +double TDynamicObject::GetVelocity() const { return physics->Vel; } +double TDynamicObject::GetLength() const { return physics->Dim.L; } +double TDynamicObject::GetWidth() const { return physics->Dim.W; } diff --git a/vehicle/dynamic/couplers.cpp b/vehicle/dynamic/couplers.cpp index 90ab27a1b..911aee242 100644 --- a/vehicle/dynamic/couplers.cpp +++ b/vehicle/dynamic/couplers.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/DynObj.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/lightsprogrammer.h" #include "simulation/simulation.h" #include "simulation/blackboxrecorder.h" @@ -63,10 +63,10 @@ int TDynamicObject::DettachStatus(int dir) // rzeczywistych od strony (dir): // 0=przód,1=tył // Ra: dziwne, że ta funkcja nie jest używana - if( MoverParameters->Couplers[ dir ].CouplingFlag == Coupling::none ) { + if( physics->Couplers[ dir ].CouplingFlag == Coupling::none ) { return 0; // jeśli nic nie podłączone, to jest OK } - return MoverParameters->DettachStatus(dir); // czy jest w odpowiedniej odległości? + return physics->DettachStatus(dir); // czy jest w odpowiedniej odległości? } int TDynamicObject::Dettach(int dir) @@ -89,11 +89,11 @@ int TDynamicObject::Dettach(int dir) d = d->Next(); // i w drugą stronę } } - if( MoverParameters->Couplers[ dir ].CouplingFlag ) { + if( physics->Couplers[ dir ].CouplingFlag ) { // odczepianie, o ile coś podłączone - MoverParameters->Dettach( dir ); + physics->Dettach( dir ); /* - if( true == MoverParameters->Dettach( dir ) ) { + if( true == physics->Dettach( dir ) ) { auto *othervehicle { dir ? NextConnected : PrevConnected }; auto const othercoupler { dir ? NextConnectedNo() : PrevConnectedNo() }; ( othercoupler ? othervehicle->NextConnected : othervehicle->PrevConnected ) = nullptr; @@ -102,19 +102,19 @@ int TDynamicObject::Dettach(int dir) */ } // sprzęg po rozłączaniu (czego się nie da odpiąć - return MoverParameters->Couplers[dir].CouplingFlag.Bits(); + return physics->Couplers[dir].CouplingFlag.Bits(); } void TDynamicObject::couple( VehicleEnd const Side ) { - auto const &neighbour { MoverParameters->Neighbours[ Side ] }; + auto const &neighbour { physics->Neighbours[ Side ] }; if( neighbour.vehicle == nullptr ) { return; } - auto const &coupler { MoverParameters->Couplers[ Side ] }; + auto const &coupler { physics->Couplers[ Side ] }; auto *othervehicle { neighbour.vehicle }; - auto *othervehicleparams{ othervehicle->MoverParameters }; + auto *othervehicleparams{ othervehicle->physics }; auto const &othercoupler { othervehicleparams->Couplers[ neighbour.vehicle_end ] }; if( coupler.CouplingFlag == Coupling::none ) { @@ -122,7 +122,7 @@ TDynamicObject::couple( VehicleEnd const Side ) { if( ( coupler.AllowedFlag & othercoupler.AllowedFlag & Coupling::coupler ) == Coupling::coupler ) { - if( MoverParameters->Attach( + if( physics->Attach( Side, neighbour.FacingEnd(), othervehicleparams, Coupling::coupler ) ) { @@ -134,12 +134,12 @@ TDynamicObject::couple( VehicleEnd const Side ) { } } } - if( false == MoverParameters->Couplers[ Side ].CouplingFlag.HasAll(Coupling::brakeHose) ) { + if( false == physics->Couplers[ Side ].CouplingFlag.HasAll(Coupling::brakeHose) ) { // pneumatyka if( ( coupler.AllowedFlag & othercoupler.AllowedFlag & Coupling::brakeHose ) == Coupling::brakeHose ) { - if( MoverParameters->Attach( + if( physics->Attach( Side, neighbour.FacingEnd(), othervehicleparams, coupler.CouplingFlag | Coupling::brakeHose ) ) { @@ -150,12 +150,12 @@ TDynamicObject::couple( VehicleEnd const Side ) { } } } - if( false == MoverParameters->Couplers[ Side ].CouplingFlag.HasAll(Coupling::mainHose) ) { + if( false == physics->Couplers[ Side ].CouplingFlag.HasAll(Coupling::mainHose) ) { // zasilajacy if( ( coupler.AllowedFlag & othercoupler.AllowedFlag & Coupling::mainHose ) == Coupling::mainHose ) { - if( MoverParameters->Attach( + if( physics->Attach( Side, neighbour.FacingEnd(), othervehicleparams, coupler.CouplingFlag | Coupling::mainHose ) ) { @@ -166,12 +166,12 @@ TDynamicObject::couple( VehicleEnd const Side ) { } } } - if( false == MoverParameters->Couplers[ Side ].CouplingFlag.HasAll(Coupling::control) ) { + if( false == physics->Couplers[ Side ].CouplingFlag.HasAll(Coupling::control) ) { // ukrotnionko if( (coupler.AllowedFlag & othercoupler.AllowedFlag & Coupling::control) == Coupling::control && coupler.control_type == othercoupler.control_type - && MoverParameters->CompatibleCoupling( Side, *othervehicleparams, neighbour.FacingEnd(), coupler.CouplingFlag | Coupling::control ).HasAny( Coupling::control ) ) { - if( MoverParameters->Attach( + && physics->CompatibleCoupling( Side, *othervehicleparams, neighbour.FacingEnd(), coupler.CouplingFlag | Coupling::control ).HasAny( Coupling::control ) ) { + if( physics->Attach( Side, neighbour.FacingEnd(), othervehicleparams, coupler.CouplingFlag | Coupling::control ) ) { @@ -180,12 +180,12 @@ TDynamicObject::couple( VehicleEnd const Side ) { } } } - if( false == MoverParameters->Couplers[ Side ].CouplingFlag.HasAll(Coupling::gangway) ) { + if( false == physics->Couplers[ Side ].CouplingFlag.HasAll(Coupling::gangway) ) { // mostek if( ( coupler.AllowedFlag & othercoupler.AllowedFlag & Coupling::gangway ) == Coupling::gangway ) { - if( MoverParameters->Attach( + if( physics->Attach( Side, neighbour.FacingEnd(), othervehicleparams, coupler.CouplingFlag | Coupling::gangway ) ) { @@ -194,12 +194,12 @@ TDynamicObject::couple( VehicleEnd const Side ) { } } } - if( false == MoverParameters->Couplers[ Side ].CouplingFlag.HasAll(Coupling::heating) ) { + if( false == physics->Couplers[ Side ].CouplingFlag.HasAll(Coupling::heating) ) { // heating if( ( coupler.AllowedFlag & othercoupler.AllowedFlag & Coupling::heating ) == Coupling::heating ) { - if( MoverParameters->Attach( + if( physics->Attach( Side, neighbour.FacingEnd(), othervehicleparams, coupler.CouplingFlag | Coupling::heating ) ) { @@ -215,9 +215,9 @@ int TDynamicObject::uncouple( VehicleEnd const Side ) { if( DettachStatus( NumberOf( Side ) ) >= 0 - || true == MoverParameters->Couplers[Side].CouplingFlag.HasAll(Coupling::permanent) ) { + || true == physics->Couplers[Side].CouplingFlag.HasAll(Coupling::permanent) ) { // can't uncouple, return existing coupling state - return MoverParameters->Couplers[ Side ].CouplingFlag.Bits(); + return physics->Couplers[ Side ].CouplingFlag.Bits(); } // jeżeli sprzęg niezablokowany, jest co odczepić i się da auto const couplingflag { Dettach( NumberOf( Side ) ) }; @@ -227,12 +227,12 @@ TDynamicObject::uncouple( VehicleEnd const Side ) { bool TDynamicObject::attach_coupler_adapter( VehicleEnd const Side, bool const Enforce ) { - auto &coupler { MoverParameters->Couplers[ Side ] }; + auto &coupler { physics->Couplers[ Side ] }; // sanity check(s) if( coupler.type() == TCouplerType::Automatic ) { return false; } - auto const *neighbour { MoverParameters->Neighbours[ Side ].vehicle }; + auto const *neighbour { physics->Neighbours[ Side ].vehicle }; if( neighbour == nullptr - || MoverParameters->Neighbours[Side].distance > 25.0 ) { + || physics->Neighbours[Side].distance > 25.0 ) { // can only acquire the adapter from a nearby enough vehicle return false; } @@ -245,7 +245,7 @@ TDynamicObject::attach_coupler_adapter( VehicleEnd const Side, bool const Enforc // explicit coupler adapter definition overrides default parameters adapterdata = neighbour->m_coupleradapter; } - if( MoverParameters->Neighbours[Side].distance - adapterdata.position.x < 0.5 + if( physics->Neighbours[Side].distance - adapterdata.position.x < 0.5 && false == Enforce ) { // arbitrary amount of free room required to install the adapter // NOTE: this also covers cases with established physical connection @@ -265,7 +265,7 @@ TDynamicObject::attach_coupler_adapter( VehicleEnd const Side, bool const Enforc bool TDynamicObject::remove_coupler_adapter( VehicleEnd const Side ) { - auto &coupler{ MoverParameters->Couplers[ Side ] }; + auto &coupler{ physics->Couplers[ Side ] }; if( coupler.adapter_type == TCouplerType::NoCoupler ) { return false; } // TODO: sanity check(s) @@ -289,15 +289,15 @@ void TDynamicObject::AttachNext(TDynamicObject *Object, int iType) auto const vehicleend { iDirection }; auto const othervehicleend { Object->iDirection ^ 1 }; - MoverParameters->Attach( vehicleend, othervehicleend, Object->MoverParameters, CouplingSet::FromBits( iType ), true, false ); + physics->Attach( vehicleend, othervehicleend, Object->physics, CouplingSet::FromBits( iType ), true, false ); // update neighbour data for both affected vehicles update_neighbours(); Object->update_neighbours(); // potentially attach automatic coupler adapter to allow the connection // HACK: we're doing it after establishin actual connection, as the method needs valid neighbour data - auto &coupler { MoverParameters->Couplers[ vehicleend ] }; - auto &othercoupler { Object->MoverParameters->Couplers[ ( othervehicleend != 2 ? othervehicleend : coupler.ConnectedNr ) ] }; + auto &coupler { physics->Couplers[ vehicleend ] }; + auto &othercoupler { Object->physics->Couplers[ ( othervehicleend != 2 ? othervehicleend : coupler.ConnectedNr ) ] }; if( coupler.type() != othercoupler.type() ) { if( othercoupler.type() == TCouplerType::Automatic ) { @@ -317,11 +317,11 @@ void TDynamicObject::AttachNext(TDynamicObject *Object, int iType) Object->update_neighbours(); } // potentially adjust vehicle position to avoid collision at the simulation start - if( MoverParameters->Neighbours[ vehicleend ].distance > -0.001 ) { return; } + if( physics->Neighbours[ vehicleend ].distance > -0.001 ) { return; } - Object->Move( MoverParameters->Neighbours[ vehicleend ].distance * Object->DirectionGet() ); + Object->Move( physics->Neighbours[ vehicleend ].distance * Object->DirectionGet() ); // HACK: manually update vehicle position as it's used by neighbour distance update we do next - Object->MoverParameters->Loc = { + Object->physics->Loc = { -Object->vPosition.x, Object->vPosition.z, Object->vPosition.y }; diff --git a/vehicle/dynamic/destinations.cpp b/vehicle/dynamic/destinations.cpp index 0bad55974..e8ca19457 100644 --- a/vehicle/dynamic/destinations.cpp +++ b/vehicle/dynamic/destinations.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/DynObj.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/lightsprogrammer.h" #include "simulation/simulation.h" #include "simulation/blackboxrecorder.h" @@ -106,7 +106,7 @@ void TDynamicObject::update_destinations() { if( DestinationSign.sign == nullptr ) { return; } - auto const lowvoltagepower { ( MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable ) }; + auto const lowvoltagepower { ( physics->Power24vIsAvailable || physics->Power110vIsAvailable ) }; DestinationSign.sign->fLight = DestinationSign.has_light && lowvoltagepower ? 2.0 : -1.0; @@ -184,8 +184,8 @@ std::string TDynamicObject::destination_request( std::string const &Script, std: if( Mechanik != nullptr ) { return Mechanik->TrainName(); } return "none"; } }; // shouldn't get here but, eh auto const instance { [this, &Instancing]() -> std::string { - if( Instancing == "name" ) { return MoverParameters->Name; } - if( Instancing == "type" ) { return MoverParameters->TypeName; } + if( Instancing == "name" ) { return physics->Name; } + if( Instancing == "type" ) { return physics->TypeName; } return "none"; } }; std::string signrequest { @@ -195,8 +195,8 @@ std::string TDynamicObject::destination_request( std::string const &Script, std: // timetable include + "$timetable=" + ( ctOwner == nullptr ? - MoverParameters->Name : // leading vehicle, can point to it directly - ctOwner->Vehicle()->MoverParameters->Name ) // owned vehicle, safer to point to owner as carriages can have identical names + physics->Name : // leading vehicle, can point to it directly + ctOwner->Vehicle()->physics->Name ) // owned vehicle, safer to point to owner as carriages can have identical names // basic instancing string // NOTE: underscore doesn't have any magic meaning for the time being, it's just less likely to conflict with regular dictionary keys + "&_id1=" + trainname() }; @@ -303,7 +303,7 @@ material_handle TDynamicObject::DestinationFind( std::string Destination ) { Destination = Bezogonkow( Destination ); // do szukania pliku obcinamy ogonki // now see if we can find any version of the texture std::vector const destinations { - Destination + '@' + MoverParameters->TypeName, + Destination + '@' + physics->TypeName, Destination }; for( auto const &destination : destinations ) { diff --git a/vehicle/dynamic/internal.h b/vehicle/dynamic/internal.h index 52ae88dec..27b6e80ae 100644 --- a/vehicle/dynamic/internal.h +++ b/vehicle/dynamic/internal.h @@ -17,7 +17,7 @@ http://mozilla.org/MPL/2.0/. #pragma once #include "vehicle/DynObj.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/lightsprogrammer.h" #include "simulation/simulation.h" #include "simulation/blackboxrecorder.h" diff --git a/vehicle/dynamic/lifecycle.cpp b/vehicle/dynamic/lifecycle.cpp index e63aa4c0e..aee2653d1 100644 --- a/vehicle/dynamic/lifecycle.cpp +++ b/vehicle/dynamic/lifecycle.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/DynObj.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/lightsprogrammer.h" #include "simulation/simulation.h" #include "simulation/blackboxrecorder.h" @@ -80,7 +80,7 @@ TDynamicObject::TDynamicObject() { vFront = vWorldFront; vLeft = vWorldLeft; iNumAxles = 0; - MoverParameters = nullptr; + physics = nullptr; Mechanik = nullptr; MechInside = false; // McZapkie-270202 @@ -144,7 +144,7 @@ TDynamicObject::TDynamicObject() { TDynamicObject::~TDynamicObject() { SafeDelete( Mechanik ); - SafeDelete( MoverParameters ); + SafeDelete( physics ); SafeDeleteArray( pAnimated ); // lista animowanych submodeli } @@ -155,11 +155,11 @@ void TDynamicObject::place_on_track(TTrack *Track, double fDist, bool Reversed) axle.distance = ( Reversed ? -axle.offset : - axle.offset + MoverParameters->Dim.L ) + fDist; + axle.offset + physics->Dim.L ) + fDist; } double fAxleDistHalf = fAxleDist * 0.5; // przesuwanie pojazdu tak, aby jego początek był we wskazanym miejcu - fDist -= 0.5 * MoverParameters->Dim.L; // dodajemy pół długości pojazdu, bo ustawiamy jego środek (zliczanie na minus) + fDist -= 0.5 * physics->Dim.L; // dodajemy pół długości pojazdu, bo ustawiamy jego środek (zliczanie na minus) switch (iNumAxles) { // Ra: pojazdy wstawiane są na tor początkowy, a potem przesuwane case 2: // ustawianie osi na torze @@ -172,8 +172,8 @@ void TDynamicObject::place_on_track(TTrack *Track, double fDist, bool Reversed) break; } // the stretches the criteria of derailment held over were on the track the vehicle left (consistteleport) - MoverParameters->derailment_monitor.reset(); - MoverParameters->derailment_distance = 0.0; + physics->derailment_monitor.reset(); + physics->derailment_distance = 0.0; // potrzebne do wyliczenia aktualnej pozycji; nie może być zero, bo nie przeliczy pozycji // teraz jeszcze trzeba przypisać pojazdy do nowego toru, bo przesuwanie początkowe osi nie // zrobiło tego @@ -239,11 +239,11 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" } */ // utworzenie parametrów fizyki - MoverParameters = new TMoverParameters(iDirection ? fVel : -fVel, Type_Name, asName, Cab); + physics = new physics::Vehicle(iDirection ? fVel : -fVel, Type_Name, asName, Cab); // the vehicle carries on with the odometer state of its earlier sessions (eu07/maszyna#72) - MoverParameters->Odometer = odometer::starting_state( odometer::states(), asName, asBaseDir ); + physics->Odometer = odometer::starting_state( odometer::states(), asName, asBaseDir ); // McZapkie: TypeName musi byc nazwą CHK/MMD pojazdu - if (!MoverParameters->LoadFIZ(asBaseDir)) + if (!physics->LoadFIZ(asBaseDir)) { // jak wczytanie CHK się nie uda, to błąd if (ConversionError == 666) ErrorLog( "Bad vehicle: failed to locate definition file \"" + BaseDir + "/" + Type_Name + ".fiz" + "\"" ); @@ -253,11 +253,11 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" return 0.0; // zerowa długość to brak pojazdu } // load the cargo now that we know whether the vehicle will allow it - MoverParameters->AssignLoad( LoadType, Load ); - MoverParameters->ComputeMass(); + physics->AssignLoad( LoadType, Load ); + physics->ComputeMass(); bool driveractive = fVel != 0.0; // jeśli prędkość niezerowa, to aktywujemy ruch - if (!MoverParameters->CheckLocomotiveParameters( + if (!physics->CheckLocomotiveParameters( driveractive, (fVel > 0 ? 1 : -1) * Cab * (iDirection ? 1 : -1))) // jak jedzie lub obsadzony to gotowy do drogi @@ -266,38 +266,38 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" return 0.0; // zerowa długość to brak pojazdu } // controller position - MoverParameters->MainCtrlPos = MoverParameters->MainCtrlNoPowerPos(); + physics->MainCtrlPos = physics->MainCtrlNoPowerPos(); // ustawienie pozycji hamulca - MoverParameters->LocalBrakePosA = 0.0; + physics->LocalBrakePosA = 0.0; if (driveractive) { if (Cab == 0) - MoverParameters->BrakeCtrlPos = - static_cast( std::floor(MoverParameters->Handle->GetPos(bh_NP)) ); + physics->BrakeCtrlPos = + static_cast( std::floor(physics->Handle->GetPos(bh_NP)) ); else - MoverParameters->BrakeCtrlPos = static_cast( std::floor(MoverParameters->Handle->GetPos(bh_RP)) ); + physics->BrakeCtrlPos = static_cast( std::floor(physics->Handle->GetPos(bh_RP)) ); // engage independent brake if applicable, if the vehicle is to be on standby // NOTE: with more than one driver in the consist this is likely to go awery, since all but one will be sent to sleep // TBD, TODO: have the virtual helper release independent brakes during consist check? if( DriverType != "" ) { - if( MoverParameters->LocalBrake != TLocalBrake::ManualBrake ) { + if( physics->LocalBrake != TLocalBrake::ManualBrake ) { if( fVel < 1.0 ) { - MoverParameters->IncLocalBrakeLevel( LocalBrakePosNo ); - if ( MoverParameters->EIMCtrlEmergency ) { - MoverParameters->DecLocalBrakeLevel(1); + physics->IncLocalBrakeLevel( LocalBrakePosNo ); + if ( physics->EIMCtrlEmergency ) { + physics->DecLocalBrakeLevel(1); } } } } } else - MoverParameters->BrakeCtrlPos = - static_cast( std::floor(MoverParameters->Handle->GetPos(bh_NP)) ); + physics->BrakeCtrlPos = + static_cast( std::floor(physics->Handle->GetPos(bh_NP)) ); // poprawienie hamulca po ewentualnym przestawieniu przez Pascal // TODO: check if needed, we're not in Pascal anymore, Toto - MoverParameters->BrakeLevelSet(MoverParameters->BrakeCtrlPos); + physics->BrakeLevelSet(physics->BrakeCtrlPos); // dodatkowe parametry yB MoreParams += "."; // wykonuje o jedną iterację za mało, więc trzeba mu dodać @@ -316,105 +316,105 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" WriteLog("Wpis hamulca: " + ActPar); if ( contains( ActPar, 'G') ) { - MoverParameters->BrakeDelaySwitch(bdelay_G); + physics->BrakeDelaySwitch(bdelay_G); } if( contains( ActPar, 'P' ) ) { - MoverParameters->BrakeDelaySwitch(bdelay_P); + physics->BrakeDelaySwitch(bdelay_P); } if( contains( ActPar, 'R' ) ) { - MoverParameters->BrakeDelaySwitch(bdelay_R); + physics->BrakeDelaySwitch(bdelay_R); } if( contains( ActPar, 'M' ) ) { - MoverParameters->BrakeDelaySwitch(bdelay_R); - MoverParameters->BrakeDelaySwitch(bdelay_R + bdelay_M); + physics->BrakeDelaySwitch(bdelay_R); + physics->BrakeDelaySwitch(bdelay_R + bdelay_M); } // wylaczanie hamulca if ( contains( ActPar, "<>") ) // wylaczanie na probe hamowania naglego { - MoverParameters->Hamulec->SetBrakeStatus( MoverParameters->Hamulec->GetBrakeStatus() | b_dmg ); // wylacz + physics->Hamulec->SetBrakeStatus( physics->Hamulec->GetBrakeStatus() | b_dmg ); // wylacz } if ( contains( ActPar, '0' ) ) // wylaczanie na sztywno { - MoverParameters->Hamulec->ForceEmptiness(); - MoverParameters->Hamulec->SetBrakeStatus( MoverParameters->Hamulec->GetBrakeStatus() | b_dmg ); // wylacz + physics->Hamulec->ForceEmptiness(); + physics->Hamulec->SetBrakeStatus( physics->Hamulec->GetBrakeStatus() | b_dmg ); // wylacz } if ( contains( ActPar, 'E' ) ) // oprozniony { - MoverParameters->Hamulec->ForceEmptiness(); - MoverParameters->Pipe->CreatePress(0); - MoverParameters->Pipe2->CreatePress(0); + physics->Hamulec->ForceEmptiness(); + physics->Pipe->CreatePress(0); + physics->Pipe2->CreatePress(0); } if ( contains( ActPar, 'Q' ) ) // oprozniony { - MoverParameters->Hamulec->ForceEmptiness(); - MoverParameters->Pipe->CreatePress(0.0); - MoverParameters->PipePress = 0.0; - MoverParameters->Pipe2->CreatePress(0.0); - MoverParameters->ScndPipePress = 0.0; - MoverParameters->PantVolume = 0.1; - MoverParameters->PantPress = 0.0; - MoverParameters->CompressedVolume = 0.0; + physics->Hamulec->ForceEmptiness(); + physics->Pipe->CreatePress(0.0); + physics->PipePress = 0.0; + physics->Pipe2->CreatePress(0.0); + physics->ScndPipePress = 0.0; + physics->PantVolume = 0.1; + physics->PantPress = 0.0; + physics->CompressedVolume = 0.0; } if ( contains( ActPar, '1' ) ) // wylaczanie 10% { if (Random(10) < 1) // losowanie 1/10 { - MoverParameters->Hamulec->ForceEmptiness(); - MoverParameters->Hamulec->SetBrakeStatus( MoverParameters->Hamulec->GetBrakeStatus() | b_dmg ); // wylacz + physics->Hamulec->ForceEmptiness(); + physics->Hamulec->SetBrakeStatus( physics->Hamulec->GetBrakeStatus() | b_dmg ); // wylacz } } if ( contains( ActPar, 'X') ) // agonalny wylaczanie 20%, usrednienie przekladni { if (Random(100) < 20) // losowanie 20/100 { - MoverParameters->Hamulec->ForceEmptiness(); - MoverParameters->Hamulec->SetBrakeStatus( MoverParameters->Hamulec->GetBrakeStatus() | b_dmg ); // wylacz + physics->Hamulec->ForceEmptiness(); + physics->Hamulec->SetBrakeStatus( physics->Hamulec->GetBrakeStatus() | b_dmg ); // wylacz } - if (MoverParameters->BrakeCylMult[2] * MoverParameters->BrakeCylMult[1] > + if (physics->BrakeCylMult[2] * physics->BrakeCylMult[1] > 0.01) // jesli jest nastawiacz mechaniczny PL { float rnd = Random(100); if (rnd < 20) // losowanie 20/100 usrednienie { - MoverParameters->BrakeCylMult[2] = MoverParameters->BrakeCylMult[1] = - (MoverParameters->BrakeCylMult[2] + MoverParameters->BrakeCylMult[1]) / + physics->BrakeCylMult[2] = physics->BrakeCylMult[1] = + (physics->BrakeCylMult[2] + physics->BrakeCylMult[1]) / 2; } else if (rnd < 70) // losowanie 70/100-20/100 oslabienie { - MoverParameters->BrakeCylMult[1] = MoverParameters->BrakeCylMult[1] * 0.50; - MoverParameters->BrakeCylMult[2] = MoverParameters->BrakeCylMult[2] * 0.75; + physics->BrakeCylMult[1] = physics->BrakeCylMult[1] * 0.50; + physics->BrakeCylMult[2] = physics->BrakeCylMult[2] * 0.75; } else if (rnd < 80) // losowanie 80/100-70/100 tylko prozny { - MoverParameters->BrakeCylMult[2] = MoverParameters->BrakeCylMult[1]; + physics->BrakeCylMult[2] = physics->BrakeCylMult[1]; } else // tylko ladowny { - MoverParameters->BrakeCylMult[1] = MoverParameters->BrakeCylMult[2]; + physics->BrakeCylMult[1] = physics->BrakeCylMult[2]; } } } // nastawianie ladunku if ( contains( ActPar, 'T' ) ) // prozny { - MoverParameters->DecBrakeMult(); - MoverParameters->DecBrakeMult(); + physics->DecBrakeMult(); + physics->DecBrakeMult(); } // dwa razy w dol if ( contains( ActPar, 'H' ) ) // ladowny I (dla P-Ł dalej prozny) { - MoverParameters->IncBrakeMult(); - MoverParameters->IncBrakeMult(); - MoverParameters->DecBrakeMult(); + physics->IncBrakeMult(); + physics->IncBrakeMult(); + physics->DecBrakeMult(); } // dwa razy w gore i obniz if ( contains( ActPar, 'F' ) ) // ladowny II { - MoverParameters->IncBrakeMult(); - MoverParameters->IncBrakeMult(); + physics->IncBrakeMult(); + physics->IncBrakeMult(); } // dwa razy w gore if ( contains( ActPar, 'N' ) ) // parametr neutralny { @@ -461,7 +461,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" auto const indexstart { 1 }; auto const indexend { ActPar.find_first_not_of( "1234567890", indexstart ) }; auto const huntingchance { std::atoi( ActPar.substr( indexstart, indexend ).c_str() ) }; - MoverParameters->TruckHunting = Random(0, 100) < huntingchance; + physics->TruckHunting = Random(0, 100) < huntingchance; ActPar.erase( 0, indexend ); break; } @@ -473,7 +473,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" } } if( Random( 0, 100 ) <= flatchance ) { - MoverParameters->WheelFlat += fixedflatsize + Random( 0, randomflatsize ); + physics->WheelFlat += fixedflatsize + Random( 0, randomflatsize ); } } // wheel else if( ActPar.size() >= 2 @@ -500,7 +500,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" } if( true == setambient ) { // TODO: pull ambient temperature from environment data - MoverParameters->dizel_HeatSet( Global.AirTemperature ); + physics->dizel_HeatSet( Global.AirTemperature ); } } // temperature else if( ActPar.size() >= 2 @@ -512,7 +512,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" { auto const indexstart { 0 }; auto const indexend { ActPar.find_first_not_of( "1234567890", indexstart ) }; - MoverParameters->MaxLoad = std::atoi( ActPar.substr( indexstart, indexend ).c_str() ); + physics->MaxLoad = std::atoi( ActPar.substr( indexstart, indexend ).c_str() ); ActPar.erase( 0, indexend ); } while( false == ActPar.empty() ) { @@ -534,32 +534,32 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" if( hauled ) { // once the vehicle has its starting state: the hand brake and the spring brake of a standing one let go, battery off - MoverParameters->PulleeModeSwitch( true ); + physics->PulleeModeSwitch( true ); } - if (MoverParameters->CategoryFlag & 2) // jeśli samochód + if (physics->CategoryFlag & 2) // jeśli samochód { // ustawianie samochodow na poboczu albo na środku drogi if( Track->fTrackWidth < 3.5 // jeśli droga wąska || Track->m_road != nullptr ) // a lane of a road node is one-way, the vehicle keeps to its middle - MoverParameters->OffsetTrackH = 0.0; // to stawiamy na środku, niezależnie od stanu + physics->OffsetTrackH = 0.0; // to stawiamy na środku, niezależnie od stanu // ruchu else if( driveractive ) {// od 3.5m do 8.0m jedzie po środku pasa, dla // szerszych w odległości // 1.5m - auto const lanefreespace = 0.5 * Track->fTrackWidth - MoverParameters->Dim.W; - MoverParameters->OffsetTrackH = lanefreespace > 1.5 ? - -0.5 * MoverParameters->Dim.W - 0.75 : // wide road, keep near centre with safe margin + auto const lanefreespace = 0.5 * Track->fTrackWidth - physics->Dim.W; + physics->OffsetTrackH = lanefreespace > 1.5 ? + -0.5 * physics->Dim.W - 0.75 : // wide road, keep near centre with safe margin lanefreespace > 0.1 ? -0.25 * Track->fTrackWidth : // narrow fit, stay on the middle - -0.5 * MoverParameters->Dim.W - 0.075; // too narrow, just keep some minimal clearance + -0.5 * physics->Dim.W - 0.075; // too narrow, just keep some minimal clearance } else // jak stoi, to kołem na poboczu i pobieramy szerokość razem z // poboczem, ale nie z // chodnikiem - MoverParameters->OffsetTrackH = - -0.5 * (Track->WidthTotal() - MoverParameters->Dim.W) + 0.05; + physics->OffsetTrackH = + -0.5 * (Track->WidthTotal() - physics->Dim.W) + 0.05; iHornWarning = 0; // nie będzie trąbienia po podaniu zezwolenia na jazdę - if (fDist < 0.0) //-0.5*MoverParameters->Dim.L) //jeśli jest przesunięcie do tyłu + if (fDist < 0.0) //-0.5*physics->Dim.L) //jeśli jest przesunięcie do tyłu if (!Track->CurrentPrev()) // a nie ma tam odcinka i trzeba by coś // wygenerować fDist = -fDist; // to traktujemy, jakby przesunięcie było w drugą stronę @@ -574,7 +574,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" // McZapkie-250202 /* - iAxles = std::min( MoverParameters->NAxles, MaxAxles ); // ilość osi + iAxles = std::min( physics->NAxles, MaxAxles ); // ilość osi */ // wczytywanie z pliku nazwatypu.mmd, w tym model erase_extension( asReplacableSkin ); @@ -653,10 +653,10 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" btMechanik1.Init( "mechanik1", mdLowPolyInt, false); btMechanik2.Init( "mechanik2", mdLowPolyInt, false); - if( MoverParameters->diesel.heat.water.config.shutters ) { + if( physics->diesel.heat.water.config.shutters ) { btShutters1.Init( "shutters1", mdModel, false ); } - if( MoverParameters->diesel.heat.water_aux.config.shutters ) { + if( physics->diesel.heat.water_aux.config.shutters ) { btShutters2.Init( "shutters2", mdModel, false ); } TurnOff(); // resetowanie zmiennych submodeli @@ -680,7 +680,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" // passenger car compartments std::vector nameprefixes = { "corridor", "korytarz", "compartment", "przedzial" }; for( auto const &nameprefix : nameprefixes ) { - init_sections( mdLowPolyInt, nameprefix, MoverParameters->CompartmentLights.start_type == start_t::manual ); + init_sections( mdLowPolyInt, nameprefix, physics->CompartmentLights.start_type == start_t::manual ); } // the inside of the door wings, if the interior has them init_interior_doors(); @@ -717,7 +717,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" ( Reversed ? -axle.offset : axle.offset ) - - 0.5 * MoverParameters->Dim.L + - 0.5 * physics->Dim.L + fDist, Track->fSoundDistance ); } @@ -725,17 +725,17 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" // McZapkie-250202 end. Track->AddDynamicObject(this); // wstawiamy do toru na pozycję 0, a potem przesuniemy // McZapkie: zmieniono na ilosc osi brane z chk - // iNumAxles=(MoverParameters->NAxles>3 ? 4 : 2 ); + // iNumAxles=(physics->NAxles>3 ? 4 : 2 ); initial_track = MyTrack; iNumAxles = 2; // McZapkie-090402: odleglosc miedzy czopami skretu lub osiami fAxleDist = safe_clamp( - std::max( MoverParameters->BDist, MoverParameters->ADist ), + std::max( physics->BDist, physics->ADist ), 0.2, //żeby się dało wektory policzyć - MoverParameters->Dim.L - 0.2 ); // nie mogą być za daleko bo będzie "walenie w mur" + physics->Dim.L - 0.2 ); // nie mogą być za daleko bo będzie "walenie w mur" double fAxleDistHalf = fAxleDist * 0.5; // przesuwanie pojazdu tak, aby jego początek był we wskazanym miejcu - fDist -= 0.5 * MoverParameters->Dim.L; // dodajemy pół długości pojazdu, bo ustawiamy jego środek (zliczanie na minus) + fDist -= 0.5 * physics->Dim.L; // dodajemy pół długości pojazdu, bo ustawiamy jego środek (zliczanie na minus) switch (iNumAxles) { // Ra: pojazdy wstawiane są na tor początkowy, a potem przesuwane case 2: // ustawianie osi na torze @@ -746,13 +746,13 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" break; case 4: Axle0.Init(Track, this, iDirection ? 1 : -1); - Axle0.Move((iDirection ? fDist : -fDist) + (fAxleDistHalf + MoverParameters->ADist * 0.5), false); + Axle0.Move((iDirection ? fDist : -fDist) + (fAxleDistHalf + physics->ADist * 0.5), false); Axle1.Init(Track, this, iDirection ? 1 : -1); - Axle1.Move((iDirection ? fDist : -fDist) - (fAxleDistHalf + MoverParameters->ADist * 0.5), false); + Axle1.Move((iDirection ? fDist : -fDist) - (fAxleDistHalf + physics->ADist * 0.5), false); // Axle2.Init(Track,this,iDirection?1:-1); - // Axle2.Move((iDirection?fDist:-fDist)-(fAxleDistHalf-MoverParameters->ADist*0.5),false); + // Axle2.Move((iDirection?fDist:-fDist)-(fAxleDistHalf-physics->ADist*0.5),false); // Axle3.Init(Track,this,iDirection?1:-1); - // Axle3.Move((iDirection?fDist:-fDist)+(fAxleDistHalf-MoverParameters->ADist*0.5),false); + // Axle3.Move((iDirection?fDist:-fDist)+(fAxleDistHalf-physics->ADist*0.5),false); break; } // potrzebne do wyliczenia aktualnej pozycji; nie może być zero, bo nie przeliczy pozycji @@ -761,7 +761,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" Move( 0.0001 ); ABuCheckMyTrack(); // zmiana toru na ten, co oś Axle0 (oś z przodu) // Ra: ustawienie pozycji do obliczania sprzęgów - MoverParameters->Loc = { + physics->Loc = { -vPosition.x, vPosition.z, vPosition.y }; // normalnie przesuwa ComputeMovement() w Update() @@ -785,12 +785,12 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" } // ABu: zainicjowanie zmiennej, zeby nic sie nie ruszylo w pierwszej klatce, // potem juz liczona prawidlowa wartosc masy - MoverParameters->ComputeConstans(); + physics->ComputeConstans(); // wektor podłogi dla wagonów, przesuwa ładunek - vFloor = glm::dvec3(0, 0, MoverParameters->Floor); + vFloor = glm::dvec3(0, 0, physics->Floor); // długość większa od zera oznacza OK; 2mm docisku? - return MoverParameters->Dim.L; + return physics->Dim.L; } int @@ -876,7 +876,7 @@ TDynamicObject::create_controller( std::string const Type, bool const Trainset ) // tryb pociągowy z ustaloną prędkością (względem sprzęgów) Mechanik->PutCommand( "Timetable:", - MoverParameters->V * 3.6 * ( iDirection ? -1.0 : 1.0 ), + physics->V * 3.6 * ( iDirection ? -1.0 : 1.0 ), 0, nullptr ); } diff --git a/vehicle/dynamic/lights.cpp b/vehicle/dynamic/lights.cpp index 0da7ae5b7..11ea04fc8 100644 --- a/vehicle/dynamic/lights.cpp +++ b/vehicle/dynamic/lights.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/DynObj.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/lightsprogrammer.h" #include "simulation/simulation.h" #include "simulation/blackboxrecorder.h" @@ -59,22 +59,22 @@ http://mozilla.org/MPL/2.0/. void TDynamicObject::SetLights() { - auto const isfrontcaboccupied { MoverParameters->CabOccupied * DirectionGet() >= 0 }; - int const automaticmarkers { MoverParameters->CabActive == 0 && MoverParameters->InactiveCabFlag & activation::redmarkers + auto const isfrontcaboccupied { physics->CabOccupied * DirectionGet() >= 0 }; + int const automaticmarkers { physics->CabActive == 0 && physics->InactiveCabFlag & activation::redmarkers ? light::redmarker_left + light::redmarker_right : 0 }; - auto const lightpos { MoverParameters->LightsPos - 1 }; + auto const lightpos { physics->LightsPos - 1 }; ByEnd const cablights { - automaticmarkers > 0 ? automaticmarkers : MoverParameters->Lights[ VehicleEnd::front ][ lightpos ], - automaticmarkers > 0 ? automaticmarkers : MoverParameters->Lights[ VehicleEnd::rear ][ lightpos ] }; + automaticmarkers > 0 ? automaticmarkers : physics->Lights[ VehicleEnd::front ][ lightpos ], + automaticmarkers > 0 ? automaticmarkers : physics->Lights[ VehicleEnd::rear ][ lightpos ] }; // the custom position keeps the lights lit at coupled ends as well - auto const ignorecouplings { MoverParameters->LightsPos == 18 }; - auto *vehicle { GetFirstDynamic( MoverParameters->CabOccupied >= 0 ? VehicleEnd::front : VehicleEnd::rear, Coupling::control ) }; + auto const ignorecouplings { physics->LightsPos == 18 }; + auto *vehicle { GetFirstDynamic( physics->CabOccupied >= 0 ? VehicleEnd::front : VehicleEnd::rear, Coupling::control ) }; while( vehicle != nullptr ) { // set lights on given side if there's no coupling with another vehicle, turn them off otherwise auto const iscoupled { [ vehicle, ignorecouplings ]( VehicleEnd const Side ) { return false == ignorecouplings - && vehicle->MoverParameters->Couplers[ Side ].CouplingFlag.HasAny(Coupling::coupler) - && vehicle->MoverParameters->Neighbours[ Side ].vehicle != nullptr; } }; + && vehicle->physics->Couplers[ Side ].CouplingFlag.HasAny(Coupling::coupler) + && vehicle->physics->Neighbours[ Side ].vehicle != nullptr; } }; auto const lights { lights_programmer::vehicle_lights( cablights, isfrontcaboccupied, vehicle->iDirection, { iscoupled( VehicleEnd::front ), iscoupled( VehicleEnd::rear ) } ) }; vehicle->RaLightsSet( lights.head, lights.rear ); @@ -86,14 +86,14 @@ void TDynamicObject::RaLightsSet(int head, int rear) { // zapalenie świateł z przodu i z // tyłu, zależne od kierunku // pojazdu - if (!MoverParameters) + if (!physics) return; // może tego nie być na początku if (rear == ( light::redmarker_left | light::redmarker_right | light::rearendsignals ) ) { // jeśli koniec pociągu, to trzeba ustalić, czy // jest tam czynna lokomotywa // EN57 może nie mieć końcówek od środka członu - if (MoverParameters->Power > 1.0) // jeśli ma moc napędową - if (!MoverParameters->DirActive) // jeśli nie ma ustawionego kierunku + if (physics->Power > 1.0) // jeśli ma moc napędową + if (!physics->DirActive) // jeśli nie ma ustawionego kierunku { // jeśli ma zarówno światła jak i końcówki, ustalić, czy jest w stanie aktywnym // np. lokomotywa na zimno będzie mieć końcówki a nie światła rear = light::rearendsignals; // tablice blaszane @@ -114,12 +114,12 @@ void TDynamicObject::RaLightsSet(int head, int rear) // w zależności od kierunku pojazdu w składzie if( head >= 0 ) { auto const vehicleend { iDirection > 0 ? VehicleEnd::front : VehicleEnd::rear }; - MoverParameters->iLights[ vehicleend ] = head & iInventory[vehicleend]; - bool tLeft = MoverParameters->iLights[vehicleend] & (light::auxiliary_left | light::headlight_left); // roboczo czy jakiekolwiek swiatlo z lewej jest zapalone - bool tRight = MoverParameters->iLights[vehicleend] & (light::auxiliary_right | light::headlight_right); // a tu z prawej + physics->iLights[ vehicleend ] = head & iInventory[vehicleend]; + bool tLeft = physics->iLights[vehicleend] & (light::auxiliary_left | light::headlight_left); // roboczo czy jakiekolwiek swiatlo z lewej jest zapalone + bool tRight = physics->iLights[vehicleend] & (light::auxiliary_right | light::headlight_right); // a tu z prawej if (Controller == Humandriver) { - auto const dps{MoverParameters->currentDimPosition()}; + auto const dps{physics->currentDimPosition()}; // domyślnie HighBeamLights = false; @@ -128,17 +128,17 @@ void TDynamicObject::RaLightsSet(int head, int rear) // obsługa OFF if (dps.isOff) { - //MoverParameters->iLights[vehicleend] &= 0 | light::rearendsignals; // zostawiamy tylko tabliczki jesli sa + //physics->iLights[vehicleend] &= 0 | light::rearendsignals; // zostawiamy tylko tabliczki jesli sa HighBeamLights = false; DimHeadlights = false; // the headlights at the end of the active cab: A at the front, B at the rear - if( auto const cabend { CabEnd( MoverParameters->CabActive ) }; cabend.has_value() ) { + if( auto const cabend { CabEnd( physics->CabActive ) }; cabend.has_value() ) { ( *cabend == VehicleEnd::front ? HeadlightsAoff : HeadlightsBoff ) = true; } } else { - if( auto const cabend { CabEnd( MoverParameters->CabActive ) }; cabend.has_value() ) { + if( auto const cabend { CabEnd( physics->CabActive ) }; cabend.has_value() ) { ( *cabend == VehicleEnd::front ? HeadlightsAoff : HeadlightsBoff ) = false; } } @@ -156,7 +156,7 @@ void TDynamicObject::RaLightsSet(int head, int rear) } if( rear >= 0 ) { auto const vehicleend{ iDirection > 0 ? VehicleEnd::rear : VehicleEnd::front }; - MoverParameters->iLights[ vehicleend ] = rear & iInventory[vehicleend]; + physics->iLights[ vehicleend ] = rear & iInventory[vehicleend]; } }; @@ -166,7 +166,7 @@ void TDynamicObject::SetLightDimmings() if (Controller == Humandriver) { - auto const dps{MoverParameters->currentDimPosition()}; + auto const dps{physics->currentDimPosition()}; // domyślnie HighBeamLights = false; @@ -175,7 +175,7 @@ void TDynamicObject::SetLightDimmings() // obsługa OFF if (dps.isOff) { - // MoverParameters->iLights[vehicleend] &= 0 | light::rearendsignals; // zostawiamy tylko tabliczki jesli sa + // physics->iLights[vehicleend] &= 0 | light::rearendsignals; // zostawiamy tylko tabliczki jesli sa HighBeamLights = false; DimHeadlights = false; switch (vehicleend) @@ -227,7 +227,7 @@ bool TDynamicObject::has_signal_pc1_on() const { auto const pattern { equippedlights & ( light::headlight_left | light::headlight_right | light::headlight_upper ) }; auto const patternfallback { equippedlights & ( light::auxiliary_left | light::auxiliary_right | light::headlight_upper ) }; auto const hasauxiliarylights { ( equippedlights & ( light::auxiliary_left | light::auxiliary_right ) ) != 0 }; - auto const activelights { MoverParameters->iLights[ vehicleend ] }; + auto const activelights { physics->iLights[ vehicleend ] }; return (pattern != 0 && activelights == pattern) || (hasauxiliarylights && activelights == patternfallback) || (pattern == 0 && patternfallback == 0 && activelights == light::rearendsignals); // pc4 @@ -240,7 +240,7 @@ bool TDynamicObject::has_signal_pc2_on() const { auto const pattern { equippedlights & ( light::redmarker_left | light::headlight_right | light::headlight_upper ) }; auto const patternfallback { equippedlights & ( light::redmarker_left | light::auxiliary_right | light::headlight_upper ) }; auto const hasauxiliarylights { ( equippedlights & ( light::auxiliary_left | light::auxiliary_right ) ) != 0 }; - auto const activelights { MoverParameters->iLights[ vehicleend ] }; + auto const activelights { physics->iLights[ vehicleend ] }; return activelights == pattern || (hasauxiliarylights && activelights == patternfallback); } @@ -251,7 +251,7 @@ bool TDynamicObject::has_signal_pc5_on() const { auto const equippedlights { iInventory[ vehicleend ] }; auto const pattern { equippedlights & ( light::redmarker_left | light::redmarker_right ) }; auto const patternfallback { equippedlights & light::rearendsignals }; - auto const activelights { MoverParameters->iLights[ vehicleend ] }; + auto const activelights { physics->iLights[ vehicleend ] }; return (pattern != 0 && activelights == pattern) || (patternfallback != 0 && activelights == patternfallback); } @@ -261,7 +261,7 @@ bool TDynamicObject::has_signal_on( VehicleEnd const Side, int const Pattern ) c auto const vehicleend { iDirection > 0 ? Side : 1 - Side }; auto const pattern { iInventory[ vehicleend ] & Pattern }; - return ( MoverParameters->iLights[ vehicleend ] == pattern ); + return ( physics->iLights[ vehicleend ] == pattern ); */ - return MoverParameters->iLights[Side] == (Pattern & iInventory[Side]); + return physics->iLights[Side] == (Pattern & iInventory[Side]); } diff --git a/vehicle/dynamic/load.cpp b/vehicle/dynamic/load.cpp index 42c9e7913..026761d23 100644 --- a/vehicle/dynamic/load.cpp +++ b/vehicle/dynamic/load.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/DynObj.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/lightsprogrammer.h" #include "simulation/simulation.h" #include "simulation/blackboxrecorder.h" @@ -61,16 +61,16 @@ http://mozilla.org/MPL/2.0/. // initiates load change by specified amounts, with a platform on specified side void TDynamicObject::LoadExchange( int const Disembark, int const Embark, int const Platforms ) { /* - if( ( MoverParameters->Doors.open_control == control_t::passenger ) - || ( MoverParameters->Doors.open_control == control_t::mixed ) ) { + if( ( physics->Doors.open_control == control_t::passenger ) + || ( physics->Doors.open_control == control_t::mixed ) ) { // jeśli jedzie do tyłu, to drzwi otwiera odwrotnie auto const lewe = ( DirectionGet() > 0 ) ? 1 : 2; auto const prawe = 3 - lewe; if( Platform & lewe ) { - MoverParameters->OperateDoors( VehicleSide::left, true, range_t::local ); + physics->OperateDoors( VehicleSide::left, true, range_t::local ); } if( Platform & prawe ) { - MoverParameters->OperateDoors( VehicleSide::right, true, range_t::local ); + physics->OperateDoors( VehicleSide::right, true, range_t::local ); } } */ @@ -93,7 +93,7 @@ float TDynamicObject::LoadExchangeTime() const { if( m_exchange.unload_count < 0.01 && m_exchange.load_count < 0.01 ) { return 0.f; } - auto const baseexchangetime { m_exchange.unload_count / MoverParameters->UnLoadSpeed + m_exchange.load_count / MoverParameters->LoadSpeed }; + auto const baseexchangetime { m_exchange.unload_count / physics->UnLoadSpeed + m_exchange.load_count / physics->LoadSpeed }; auto const nominalexchangespeedfactor { ( m_exchange.platforms == 3 ? 2.f : 1.f ) }; auto const actualexchangespeedfactor { LoadExchangeSpeed() }; @@ -108,10 +108,10 @@ float TDynamicObject::LoadExchangeSpeed() const { auto const lewe { DirectionGet() > 0 ? 1 : 2 }; auto const prawe { 3 - lewe }; if( m_exchange.platforms & lewe ) { - exchangespeedfactor += MoverParameters->Doors.instances[VehicleSide::left].is_open ? 1.f : 0.f; + exchangespeedfactor += physics->Doors.instances[VehicleSide::left].is_open ? 1.f : 0.f; } if( m_exchange.platforms & prawe ) { - exchangespeedfactor += MoverParameters->Doors.instances[VehicleSide::right].is_open ? 1.f : 0.f; + exchangespeedfactor += physics->Doors.instances[VehicleSide::right].is_open ? 1.f : 0.f; } return exchangespeedfactor; @@ -125,7 +125,7 @@ void TDynamicObject::update_exchange( double const Deltatime ) { if( m_exchange.unload_count < 0.01 && m_exchange.load_count < 0.01 ) { return; } - if( MoverParameters->Vel < 2.0 ) { + if( physics->Vel < 2.0 ) { auto const exchangespeed { LoadExchangeSpeed() }; @@ -134,14 +134,14 @@ void TDynamicObject::update_exchange( double const Deltatime ) { auto const lewe { DirectionGet() > 0 ? 1 : 2 }; auto const prawe { 3 - lewe }; if( m_exchange.platforms & lewe - && false == (MoverParameters->Doors.instances[VehicleSide::left].is_open || MoverParameters->Doors.instances[VehicleSide::left].is_opening) ) { + && false == (physics->Doors.instances[VehicleSide::left].is_open || physics->Doors.instances[VehicleSide::left].is_opening) ) { // try to open left door - MoverParameters->OperateDoors( VehicleSide::left, true, range_t::local ); + physics->OperateDoors( VehicleSide::left, true, range_t::local ); } if( m_exchange.platforms & prawe - && false == (MoverParameters->Doors.instances[VehicleSide::right].is_open || MoverParameters->Doors.instances[VehicleSide::right].is_opening) ) { + && false == (physics->Doors.instances[VehicleSide::right].is_open || physics->Doors.instances[VehicleSide::right].is_opening) ) { // try to open right door - MoverParameters->OperateDoors( VehicleSide::right, true, range_t::local ); + physics->OperateDoors( VehicleSide::right, true, range_t::local ); } } @@ -152,33 +152,33 @@ void TDynamicObject::update_exchange( double const Deltatime ) { && m_exchange.time >= 1.0 ) { m_exchange.time -= 1.0; - auto const exchangesize = std::min( m_exchange.unload_count, MoverParameters->UnLoadSpeed * exchangespeed ); + auto const exchangesize = std::min( m_exchange.unload_count, physics->UnLoadSpeed * exchangespeed ); m_exchange.unload_count -= exchangesize; - MoverParameters->LoadStatus = 1; - MoverParameters->LoadAmount = std::max( 0.f, MoverParameters->LoadAmount - exchangesize ); - MoverParameters->ComputeMass(); + physics->LoadStatus = 1; + physics->LoadAmount = std::max( 0.f, physics->LoadAmount - exchangesize ); + physics->ComputeMass(); update_load_visibility(); } if( m_exchange.unload_count < 0.01 ) { // finish any potential unloading operation before adding new load // don't load more than can fit - m_exchange.load_count = std::min( m_exchange.load_count, MoverParameters->MaxLoad - MoverParameters->LoadAmount ); + m_exchange.load_count = std::min( m_exchange.load_count, physics->MaxLoad - physics->LoadAmount ); while( m_exchange.load_count > 0.01 && m_exchange.time >= 1.0 ) { m_exchange.time -= 1.0; - auto const exchangesize = std::min( m_exchange.load_count, MoverParameters->LoadSpeed * exchangespeed ); + auto const exchangesize = std::min( m_exchange.load_count, physics->LoadSpeed * exchangespeed ); m_exchange.load_count -= exchangesize; - MoverParameters->LoadStatus = 2; - MoverParameters->LoadAmount = std::min( MoverParameters->MaxLoad, MoverParameters->LoadAmount + exchangesize ); // std::max not strictly needed but, eh - MoverParameters->ComputeMass(); + physics->LoadStatus = 2; + physics->LoadAmount = std::min( physics->MaxLoad, physics->LoadAmount + exchangesize ); // std::max not strictly needed but, eh + physics->ComputeMass(); update_load_visibility(); } } } } - if( MoverParameters->Vel > 2.0 ) { + if( physics->Vel > 2.0 ) { // if the vehicle moves too fast cancel the exchange m_exchange.unload_count = 0; m_exchange.load_count = 0; @@ -187,37 +187,37 @@ void TDynamicObject::update_exchange( double const Deltatime ) { if( m_exchange.unload_count < 0.01 && m_exchange.load_count < 0.01 ) { - MoverParameters->LoadStatus = 4; + physics->LoadStatus = 4; // if the exchange is completed (or canceled) close the door, if applicable - if( MoverParameters->Doors.close_control == control_t::passenger - || MoverParameters->Doors.close_control == control_t::mixed ) { + if( physics->Doors.close_control == control_t::passenger + || physics->Doors.close_control == control_t::mixed ) { - if( MoverParameters->Vel > 2.0 + if( physics->Vel > 2.0 || Random() < ( // remotely controlled door are more likely to be left open - MoverParameters->Doors.close_control == control_t::passenger ? 0.75 : 0.50) ) { + physics->Doors.close_control == control_t::passenger ? 0.75 : 0.50) ) { - MoverParameters->OperateDoors( VehicleSide::left, false, range_t::local ); - MoverParameters->OperateDoors( VehicleSide::right, false, range_t::local ); + physics->OperateDoors( VehicleSide::left, false, range_t::local ); + physics->OperateDoors( VehicleSide::right, false, range_t::local ); } } // if the vehicle was emptied potentially switch load visualization model - if( MoverParameters->LoadAmount == 0 ) { - MoverParameters->AssignLoad( "" ); + if( physics->LoadAmount == 0 ) { + physics->AssignLoad( "" ); } } } void TDynamicObject::LoadUpdate() { - MoverParameters->LoadStatus &= 1 | 2; // po zakończeniu będzie równe zero + physics->LoadStatus &= 1 | 2; // po zakończeniu będzie równe zero // przeładowanie modelu ładunku - if( MoverParameters->LoadTypeChange ) { + if( physics->LoadTypeChange ) { // whether we succeed or not don't try more than once - MoverParameters->LoadTypeChange = false; + physics->LoadTypeChange = false; // bieżąca ścieżka do tekstur to dynamic/... Global.asCurrentTexturePath = asBaseDir; - mdLoad = LoadMMediaFile_mdload( MoverParameters->LoadType.name ); + mdLoad = LoadMMediaFile_mdload( physics->LoadType.name ); // TODO: discern from vehicle component which merely uses vehicle directory and has no animations, so it can be initialized outright // and actual vehicles which get their initialization after their animations are set up if( mdLoad != nullptr ) { @@ -247,7 +247,7 @@ TDynamicObject::update_load_sections() { SectionLoadOrder.push_back( §ion ); } // HACK: disable automatic self-illumination threshold, at least until 3d model update - if( MoverParameters->CompartmentLights.start_type == start_t::manual ) { + if( physics->CompartmentLights.start_type == start_t::manual ) { section.load->SetSelfIllum( 2.0f, true, false ); } } @@ -264,9 +264,9 @@ TDynamicObject::update_load_visibility() { // each entry in load order sequence matches a single chunk of the section it points to // the length of load order sequence matches total number of load chunks auto const loadpercentage { ( - MoverParameters->MaxLoad == 0.f ? + physics->MaxLoad == 0.f ? 0.0 : - MoverParameters->LoadAmount / MoverParameters->MaxLoad ) }; + physics->LoadAmount / physics->MaxLoad ) }; auto visiblechunkcount { ( SectionLoadOrder.empty() ? 0 : @@ -281,14 +281,14 @@ TDynamicObject::update_load_visibility() { void TDynamicObject::update_load_offset() { - if( MoverParameters->LoadType.offset_min == 0.f ) { return; } + if( physics->LoadType.offset_min == 0.f ) { return; } auto const loadpercentage { ( - MoverParameters->MaxLoad == 0.f ? + physics->MaxLoad == 0.f ? 0.0 : - 100.0 * MoverParameters->LoadAmount / MoverParameters->MaxLoad ) }; + 100.0 * physics->LoadAmount / physics->MaxLoad ) }; - LoadOffset = std::lerp( MoverParameters->LoadType.offset_min, 0.f, safe_clamp( 0.0, 1.0, loadpercentage * 0.01 ) ); + LoadOffset = std::lerp( physics->LoadType.offset_min, 0.f, safe_clamp( 0.0, 1.0, loadpercentage * 0.01 ) ); } void diff --git a/vehicle/dynamic/mmd.cpp b/vehicle/dynamic/mmd.cpp index b851379cd..ba952baaa 100644 --- a/vehicle/dynamic/mmd.cpp +++ b/vehicle/dynamic/mmd.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/DynObj.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/lightsprogrammer.h" #include "simulation/simulation.h" #include "simulation/blackboxrecorder.h" @@ -92,7 +92,7 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co // preliminary check whether the file exists cParser parser( TypeName + ".mmd", cParser::buffer_FILE, asBaseDir ); if( false == parser.ok() ) { - ErrorLog( "Failed to load appearance data for vehicle " + MoverParameters->Name ); + ErrorLog( "Failed to load appearance data for vehicle " + physics->Name ); return; } } @@ -173,13 +173,13 @@ void TDynamicObject::loadModelsSection( cParser &parser, std::string &token, std } while( token != "" && token != "endmodels" ); - if( false == MoverParameters->LoadAttributes.empty() ) { + if( false == physics->LoadAttributes.empty() ) { // Ra: tu wczytywanie modelu ładunku jest w porządku // bieżąca ścieżka do tekstur to dynamic/... Global.asCurrentTexturePath = asBaseDir; - mdLoad = LoadMMediaFile_mdload( MoverParameters->LoadType.name ); + mdLoad = LoadMMediaFile_mdload( physics->LoadType.name ); // z powrotem defaultowa sciezka do tekstur Global.asCurrentTexturePath = std::string( paths::textures ); @@ -239,7 +239,7 @@ bool TDynamicObject::loadModelsGeneralKeyword( cParser &parser, std::string &tok if (iAnimType[ANIM_WIPERS]) wipers = &pAnimations[k]; pAnimations[k].iShift = sm; // przesunięcie do przydzielenia wskaźnika - sm += pAnimations[k++].TypeSet(j, *MoverParameters); // ustawienie typu animacji i zliczanie tablicowanych submodeli + sm += pAnimations[k++].TypeSet(j, *physics); // ustawienie typu animacji i zliczanie tablicowanych submodeli } if (sm) // o ile są bardziej złożone animacje { @@ -341,7 +341,7 @@ bool TDynamicObject::loadModelsWheelKeyword( cParser &parser, std::string &token { //++iAnimatedAxles; pAnimations[i].smAnimated->WillBeAnimated(); // wyłączenie optymalizacji transformu pAnimations[i].yUpdate = std::bind( &TDynamicObject::UpdateAxle, this, std::placeholders::_1 ); - pAnimations[i].fMaxDist = Global.fDistanceFactor * MoverParameters->WheelDiameter * 200; + pAnimations[i].fMaxDist = Global.fDistanceFactor * physics->WheelDiameter * 200; pAnimations[i].fMaxDist *= pAnimations[i].fMaxDist; } } @@ -352,11 +352,11 @@ bool TDynamicObject::loadModelsWheelKeyword( cParser &parser, std::string &token j = 1; k = 0; m = 0; // numer osi; kolejny znak; ile osi danego typu; która średnica - if (MoverParameters->WheelDiameterL != MoverParameters->WheelDiameter || - MoverParameters->WheelDiameterT != MoverParameters->WheelDiameter) + if (physics->WheelDiameterL != physics->WheelDiameter || + physics->WheelDiameterT != physics->WheelDiameter) { // obsługa różnych średnic, o ile występują while (i < iAnimType[ANIM_WHEELS] && - j <= MoverParameters->AxleArangement.length()) + j <= physics->AxleArangement.length()) { // wersja ze wskaźnikami jest bardziej elastyczna na nietypowe układy if (k >= 'A' && k <= 'J') // 10 chyba maksimum? { @@ -370,7 +370,7 @@ bool TDynamicObject::loadModelsWheelKeyword( cParser &parser, std::string &token --k; // następna będzie albo taka sama, albo bierzemy kolejny znak } else - k = MoverParameters->AxleArangement[j++]; // pobranie kolejnego znaku + k = physics->AxleArangement[j++]; // pobranie kolejnego znaku } } } @@ -626,12 +626,12 @@ bool TDynamicObject::loadModelsPantographUpperKeyword( cParser &parser, std::str // pants[i].fParamPants->vPos.y=panty-panth-pants[i].fParamPants->PantWys; //np. 4.429-0.097=4.332=~4.335 if( pantograph.vPos.y == 0.0 ) { // crude fallback, place the pantograph(s) atop of the vehicle-sized box - pantograph.vPos.y = MoverParameters->Dim.H - pantograph.fHeight - pantograph.PantWys; + pantograph.vPos.y = physics->Dim.H - pantograph.fHeight - pantograph.PantWys; } // pants[i].fParamPants->vPos.z=0; //niezerowe dla pantografów asymetrycznych pantograph.PantTraction = pantograph.PantWys; // połowa szerokości ślizgu; jest w "Power: CSW=" - pantograph.fWidth = 0.5 * MoverParameters->EnginePowerSource.CollectorParameters.CSW; + pantograph.fWidth = 0.5 * physics->EnginePowerSource.CollectorParameters.CSW; // create sound emitters for the pantograph m_pantographsounds.emplace_back(); @@ -685,7 +685,7 @@ bool TDynamicObject::loadModelsLinkageKeyword( cParser &parser, std::string &tok panth=Parser->GetNextSymbol().ToDouble(); //długoś korbowodu (k) */ - MoverParameters->EnginePowerSource.PowerType = + physics->EnginePowerSource.PowerType = TPowerType::SteamPower; // Ra: po chamsku, ale z CHK nie działa } @@ -799,9 +799,9 @@ bool TDynamicObject::loadModelsDoorKeyword( cParser &parser, std::string &token, // the keys left out keep the values of the .fiz. the wing still follows the door of its side door_wings::wing_spec spec { 0, - MoverParameters->Doors.type, - MoverParameters->Doors.range, - MoverParameters->Doors.range_out }; + physics->Doors.type, + physics->Doors.range, + physics->Doors.range_out }; auto error { door_wings::read_spec( parser, spec ) }; if( error.empty() && ( spec.number < 1 || spec.number > iAnimType[ ANIM_DOORS ] ) ) { @@ -835,7 +835,7 @@ bool TDynamicObject::loadModelsDoorKeyword( cParser &parser, std::string &token, if (pAnimations[i + j].smAnimated) { //++iAnimatedDoors; pAnimations[i + j].smAnimated->WillBeAnimated(); // wyłączenie optymalizacji transformu - switch( MoverParameters->Doors.step_type ) + switch( physics->Doors.step_type ) { // od razu zapinamy potrzebny typ animacji case 1: // shift pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdatePlatformTranslate, this, std::placeholders::_1 ); @@ -1002,14 +1002,14 @@ bool TDynamicObject::loadSoundsEngineKeyword( cParser &parser, std::string &toke } else if( token == "engine:" - && MoverParameters->Power > 0 ) { + && physics->Power > 0 ) { // plik z dzwiekiem silnika, mnozniki i ofsety amp. i czest. m_powertrainsounds.engine.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); m_powertrainsounds.engine.owner( this ); - auto const amplitudedivisor = static_cast( MoverParameters->EngineType == TEngineType::DieselEngine ? 1 : - MoverParameters->EngineType == TEngineType::DieselElectric ? 1 : - MoverParameters->nmax * 60 + MoverParameters->Power * 3 ); + auto const amplitudedivisor = static_cast( physics->EngineType == TEngineType::DieselEngine ? 1 : + physics->EngineType == TEngineType::DieselElectric ? 1 : + physics->nmax * 60 + physics->Power * 3 ); m_powertrainsounds.engine.m_amplitudefactor /= amplitudedivisor; } else if (token == "fakeengine:") { @@ -1051,11 +1051,11 @@ bool TDynamicObject::loadSoundsEngineKeyword( cParser &parser, std::string &toke // the sounds of the traction motors, their blowers, the inverter, the fans and the transmission in the sounds: section; false when the token is none of them bool TDynamicObject::loadSoundsMotorKeyword( cParser &parser, std::string_view token ) { - if( token == "tractionmotor:" && MoverParameters->Power > 0 ) { + if( token == "tractionmotor:" && physics->Power > 0 ) { // plik z dzwiekiem silnika, mnozniki i ofsety amp. i czest. sound_source motortemplate { sound_placement::external }; motortemplate.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); - auto const amplitudedivisor { static_cast( MoverParameters->nmax * 60 + MoverParameters->Power * 3 ) }; + auto const amplitudedivisor { static_cast( physics->nmax * 60 + physics->Power * 3 ) }; motortemplate.m_amplitudefactor /= amplitudedivisor; motortemplate.owner( this ); @@ -1079,7 +1079,7 @@ bool TDynamicObject::loadSoundsMotorKeyword( cParser &parser, std::string_view t } } - else if( token == "tractionacmotor:" && MoverParameters->Power > 0 ) { + else if( token == "tractionacmotor:" && physics->Power > 0 ) { // plik z dzwiekiem silnika, mnozniki i ofsety amp. i czest. sound_source motortemplate { sound_placement::external }; motortemplate.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); @@ -1112,9 +1112,9 @@ bool TDynamicObject::loadSoundsMotorKeyword( cParser &parser, std::string_view t blowertemplate.owner( this ); auto const amplitudedivisor { static_cast( - MoverParameters->MotorBlowers[ VehicleEnd::front ].speed > 0 ? MoverParameters->MotorBlowers[ VehicleEnd::front ].speed * MoverParameters->nmax * 60 + MoverParameters->Power * 3 : + physics->MotorBlowers[ VehicleEnd::front ].speed > 0 ? physics->MotorBlowers[ VehicleEnd::front ].speed * physics->nmax * 60 + physics->Power * 3 : blowertemplate.has_bookends() ? 1 : // NOTE: for motorblowers with fixed speed if the sound has defined bookends we skip revolutions-based part of frequency/volume adjustments - MoverParameters->MotorBlowers[ VehicleEnd::front ].speed * -1 ) }; + physics->MotorBlowers[ VehicleEnd::front ].speed * -1 ) }; blowertemplate.m_amplitudefactor /= amplitudedivisor; blowertemplate.m_frequencyfactor /= amplitudedivisor; @@ -1147,8 +1147,8 @@ bool TDynamicObject::loadSoundsMotorKeyword( cParser &parser, std::string_view t m_powertrainsounds.rsWentylator.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); m_powertrainsounds.rsWentylator.owner( this ); - m_powertrainsounds.rsWentylator.m_amplitudefactor /= MoverParameters->RVentnmax; - m_powertrainsounds.rsWentylator.m_frequencyfactor /= MoverParameters->RVentnmax; + m_powertrainsounds.rsWentylator.m_amplitudefactor /= physics->RVentnmax; + m_powertrainsounds.rsWentylator.m_frequencyfactor /= physics->RVentnmax; } else if( token == "radiatorfan1:" ) { @@ -1189,7 +1189,7 @@ bool TDynamicObject::loadSoundsBrakeKeyword( cParser &parser, std::string_view t rsBrake.deserialize( parser, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency ); rsBrake.owner( this ); // NOTE: can't pre-calculate amplitude normalization based on max brake force, as this varies depending on vehicle speed - rsBrake.m_frequencyfactor /= 1 + MoverParameters->Vmax; + rsBrake.m_frequencyfactor /= 1 + physics->Vmax; } else if( token == "brake:" ) { @@ -1494,13 +1494,13 @@ bool TDynamicObject::loadSoundsDoorKeyword( cParser &parser, std::string_view to // the sounds of the load exchange, the sanders, the releaser and the running noise in the sounds: section; false when the token is none of them bool TDynamicObject::loadSoundsOtherKeyword( cParser &parser, std::string_view token ) { if( token == "unloading:" ) { - m_exchangesounds.unloading.range( MoverParameters->Dim.L * 0.5f * -1 ); + m_exchangesounds.unloading.range( physics->Dim.L * 0.5f * -1 ); m_exchangesounds.unloading.deserialize( parser, sound_type::single ); m_exchangesounds.unloading.owner( this ); } else if( token == "loading:" ) { - m_exchangesounds.loading.range( MoverParameters->Dim.L * 0.5f * -1 ); + m_exchangesounds.loading.range( physics->Dim.L * 0.5f * -1 ); m_exchangesounds.loading.deserialize( parser, sound_type::single ); m_exchangesounds.loading.owner( this ); } @@ -1519,11 +1519,11 @@ bool TDynamicObject::loadSoundsOtherKeyword( cParser &parser, std::string_view t else if( token == "outernoise:" ) { // szum podczas jazdy: sound_source noisetemplate{ sound_placement::external, EU07_SOUND_RUNNINGNOISECUTOFFRANGE }; - noisetemplate.deserialize( parser, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency, MoverParameters->Vmax ); + noisetemplate.deserialize( parser, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency, physics->Vmax ); noisetemplate.owner( this ); - noisetemplate.m_amplitudefactor /= 1 + MoverParameters->Vmax; - noisetemplate.m_frequencyfactor /= 1 + MoverParameters->Vmax; + noisetemplate.m_amplitudefactor /= 1 + physics->Vmax; + noisetemplate.m_frequencyfactor /= 1 + physics->Vmax; #ifdef EU07_SOUND_BOGIESOUNDS if( true == m_bogiesounds.empty() ) { // fallback for cases without specified noise locations, convert sound template to a single sound source @@ -1655,7 +1655,7 @@ void TDynamicObject::loadLocationsSection( cParser &parser, std::string &token ) if( sides == "both" || sides == "left" ) { // left... - auto const location { glm::vec3 { MoverParameters->Dim.W * 0.5f, MoverParameters->Dim.H * 0.5f, offset } }; + auto const location { glm::vec3 { physics->Dim.W * 0.5f, physics->Dim.H * 0.5f, offset } }; door.placement = VehicleSide::left; door.rsDoorClose.offset( location ); door.rsDoorOpen.offset( location ); @@ -1669,7 +1669,7 @@ void TDynamicObject::loadLocationsSection( cParser &parser, std::string &token ) if( sides == "both" || sides == "right" ) { // ...and right - auto const location { glm::vec3 { MoverParameters->Dim.W * -0.5f, 2.f, offset } }; + auto const location { glm::vec3 { physics->Dim.W * -0.5f, 2.f, offset } }; door.placement = VehicleSide::right; door.rsDoorClose.offset( location ); door.rsDoorOpen.offset( location ); @@ -1697,8 +1697,8 @@ void TDynamicObject::loadLocationsSection( cParser &parser, std::string &token ) mirror.end = offset >= 0.f ? VehicleEnd::front : VehicleEnd::rear; for( auto const mirrorside : { VehicleSide::left, VehicleSide::right } ) { auto const location { glm::vec3 { - MoverParameters->Dim.W * ( mirrorside == VehicleSide::left ? 0.5f : -0.5f ), - MoverParameters->Dim.H * 0.5f, + physics->Dim.W * ( mirrorside == VehicleSide::left ? 0.5f : -0.5f ), + physics->Dim.H * 0.5f, offset } }; mirror.placement = mirrorside; mirror.unfold.offset( location ); @@ -1796,7 +1796,7 @@ bool TDynamicObject::loadInternalDataDeviceKeyword( cParser &parser, std::string m_powertrainsounds.rsEngageSlippery.deserialize( parser, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency ); m_powertrainsounds.rsEngageSlippery.owner( this ); - m_powertrainsounds.rsEngageSlippery.m_frequencyfactor /= 1 + MoverParameters->nmax; + m_powertrainsounds.rsEngageSlippery.m_frequencyfactor /= 1 + physics->nmax; } // dzwieki wycieraczkuf @@ -1869,7 +1869,7 @@ bool TDynamicObject::loadInternalDataDeviceKeyword( cParser &parser, std::string rsSlippery.deserialize( parser, sound_type::single, sound_parameters::amplitude ); rsSlippery.owner( this ); - rsSlippery.m_amplitudefactor /= 1 + MoverParameters->Vmax; + rsSlippery.m_amplitudefactor /= 1 + physics->Vmax; } else { return false; @@ -2175,10 +2175,10 @@ void TDynamicObject::finishLoadingMMediaFile( std::string const &asFileName, std // assigns the default samples to the sound emitters the .mmd file left out void TDynamicObject::assignDefaultMMediaSounds() { // assign default samples to sound emitters which weren't included in the config file - if( TestFlag( MoverParameters->CategoryFlag, 1 ) ) { + if( TestFlag( physics->CategoryFlag, 1 ) ) { // rail vehicles: // engine - if( MoverParameters->Power > 0 ) { + if( physics->Power > 0 ) { if( true == m_powertrainsounds.dsbWejscie_na_bezoporow.empty() ) { // hunter-111211: domyslne, gdy brak m_powertrainsounds.dsbWejscie_na_bezoporow.deserialize( "wejscie_na_bezoporow", sound_type::single ); @@ -2246,7 +2246,7 @@ void TDynamicObject::initMMediaModels() { void TDynamicObject::positionMMediaSoundEmitters() { // position sound emitters which weren't defined in the config file // engine sounds, centre of the vehicle - auto const enginelocation { glm::vec3 {0.f, MoverParameters->Dim.H * 0.5f, 0.f } }; + auto const enginelocation { glm::vec3 {0.f, physics->Dim.H * 0.5f, 0.f } }; m_powertrainsounds.position( enginelocation ); // other engine compartment sounds auto const nullvector { glm::vec3() }; @@ -2280,7 +2280,7 @@ void TDynamicObject::positionMMediaSoundEmitters() { dooranimationfirstindex += iAnimType[ i ]; } // couplers - auto const frontcoupleroffset { glm::vec3{ 0.f, 1.f, MoverParameters->Dim.L * 0.5f } }; + auto const frontcoupleroffset { glm::vec3{ 0.f, 1.f, physics->Dim.L * 0.5f } }; m_couplersounds[ VehicleEnd::front ].attach_coupler.offset( frontcoupleroffset ); m_couplersounds[ VehicleEnd::front ].attach_brakehose.offset( frontcoupleroffset ); m_couplersounds[ VehicleEnd::front ].attach_mainhose.offset( frontcoupleroffset ); @@ -2299,7 +2299,7 @@ void TDynamicObject::positionMMediaSoundEmitters() { m_couplersounds[ VehicleEnd::front ].dsbBufferClamp_loud.offset( frontcoupleroffset ); m_couplersounds[ VehicleEnd::front ].dsbAdapterAttach.offset( frontcoupleroffset ); m_couplersounds[ VehicleEnd::front ].dsbAdapterRemove.offset( frontcoupleroffset ); - auto const rearcoupleroffset { glm::vec3{ 0.f, 1.f, MoverParameters->Dim.L * -0.5f } }; + auto const rearcoupleroffset { glm::vec3{ 0.f, 1.f, physics->Dim.L * -0.5f } }; m_couplersounds[ VehicleEnd::rear ].attach_coupler.offset( rearcoupleroffset ); m_couplersounds[ VehicleEnd::rear ].attach_brakehose.offset( rearcoupleroffset ); m_couplersounds[ VehicleEnd::rear ].attach_mainhose.offset( rearcoupleroffset ); @@ -2338,7 +2338,7 @@ TDynamicObject::LoadMMediaFile_mdload( std::string const &Name ) const { // try first specialized version of the load model, vehiclename_loadname if ( loadmodel == nullptr ) { - auto const specializedloadfilename { asBaseDir + MoverParameters->TypeName + "_" + loadname }; + auto const specializedloadfilename { asBaseDir + physics->TypeName + "_" + loadname }; loadmodel = TModelsManager::GetModel( specializedloadfilename, true, false ); } // try generic version of the load model next, loadname diff --git a/vehicle/dynamic/movement.cpp b/vehicle/dynamic/movement.cpp index 77bcfbfff..3fd4687cc 100644 --- a/vehicle/dynamic/movement.cpp +++ b/vehicle/dynamic/movement.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/DynObj.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/lightsprogrammer.h" #include "simulation/simulation.h" #include "simulation/blackboxrecorder.h" @@ -60,12 +60,12 @@ http://mozilla.org/MPL/2.0/. void TDynamicObject::FastMove(double fDistance) { - MoverParameters->dMoveLen = MoverParameters->dMoveLen + fDistance; + physics->dMoveLen = physics->dMoveLen + fDistance; } void TDynamicObject::Move(double fDistance) { - if( MoverParameters->OffTrack.active() ) { + if( physics->OffTrack.active() ) { // physics.derailment new: off the track it goes on the ground move_off_track( fDistance ); return; @@ -88,9 +88,9 @@ void TDynamicObject::move_axles(double fDistance) if (Axle0.GetTrack() == Axle1.GetTrack()) // przed przesunięciem { // powiązanie pojazdu z osią można zmienić tylko wtedy, gdy skrajne osie są // na tym samym torze - if (MoverParameters->Vel > + if (physics->Vel > 2) //|[km/h]| nie ma sensu zmiana osi, jesli pojazd drga na postoju - iAxleFirst = MoverParameters->V >= 0.0 ? + iAxleFirst = physics->V >= 0.0 ? 1 : 0; //[m/s] ?1:0 - aktywna druga oś w kierunku jazdy // aktualnie eventy aktywuje druga oś, żeby AI nie wyłączało sobie semafora @@ -146,15 +146,15 @@ void TDynamicObject::place_by_axles() } mMatrix = BasisChange(vLeft, vUp, vFront); // to też można by od razu policzyć, ale potrzebne jest do wyświetlania // przesuwanie jest jednak rzadziej niż renderowanie mMatrix = glm::inverse(mMatrix); // wyliczenie macierzy dla pojazdu (potrzebna tylko do wyświetlania?) - // if (MoverParameters->CategoryFlag&2) + // if (physics->CategoryFlag&2) { // przesunięcia są używane po wyrzuceniu pociągu z toru - vPosition.x += MoverParameters->OffsetTrackH * vLeft.x; // dodanie przesunięcia w bok - vPosition.z += MoverParameters->OffsetTrackH * vLeft.z; // vLeft jest wektorem poprzecznym + vPosition.x += physics->OffsetTrackH * vLeft.x; // dodanie przesunięcia w bok + vPosition.z += physics->OffsetTrackH * vLeft.z; // vLeft jest wektorem poprzecznym // if () na przechyłce będzie dodatkowo zmiana wysokości samochodu - vPosition.y += MoverParameters->OffsetTrackV; // te offsety są liczone przez moverparam + vPosition.y += physics->OffsetTrackV; // te offsety są liczone przez the physics } // obliczanie pozycji sprzęgów do liczenia zderzeń - auto dir = 0.5 * MoverParameters->Dim.L * vFront; // wektor sprzęgu + auto dir = 0.5 * physics->Dim.L * vFront; // wektor sprzęgu vCoulpler[VehicleEnd::front] = vPosition + dir; // współrzędne sprzęgu na początku vCoulpler[VehicleEnd::rear] = vPosition - dir; // współrzędne sprzęgu na końcu // bCameraNear= @@ -232,7 +232,7 @@ bool TDynamicObject::UpdateForce(double dt) return false; if( dt > 0 ) { // wywalenie WS zależy od ustawienia kierunku - MoverParameters->ComputeTotalForce( dt ); + physics->ComputeTotalForce( dt ); } return true; } @@ -261,7 +261,7 @@ bool TDynamicObject::FastUpdate(double dt) if (dt == 0.0) return true; // Ra: pauza double dDOMoveLen; - if (!MoverParameters->PhysicActivation) + if (!physics->PhysicActivation) return true; // McZapkie: wylaczanie fizyki gdy nie potrzeba if (!bEnabled) @@ -279,7 +279,7 @@ bool TDynamicObject::FastUpdate(double dt) modelRot.z }; // McZapkie: parametry powinny byc pobierane z toru // ts.R=MyTrack->fRadius; - // ts.Len= std::max(MoverParameters->BDist,MoverParameters->ADist); + // ts.Len= std::max(physics->BDist,physics->ADist); // ts.dHtrack=Axle1.pPosition.y-Axle0.pPosition.y; // ts.dHrail=((Axle1.GetRoll())+(Axle0.GetRoll()))*0.5f; // tp.Width=MyTrack->fTrackWidth; @@ -288,12 +288,12 @@ bool TDynamicObject::FastUpdate(double dt) // tp.CategoryFlag= MyTrack->iCategoryFlag&15; // tp.DamageFlag=MyTrack->iDamageFlag; // tp.QualityFlag=MyTrack->iQualityFlag; - dDOMoveLen = MoverParameters->FastComputeMovement(dt, ts, tp, l, r); // ,ts,tp,tmpTraction); + dDOMoveLen = physics->FastComputeMovement(dt, ts, tp, l, r); // ,ts,tp,tmpTraction); // Move(dDOMoveLen); // ResetdMoveLen(); FastMove(dDOMoveLen); - if( MoverParameters->LoadStatus ) { + if( physics->LoadStatus ) { LoadUpdate(); // zmiana modelu ładunku } update_exchange( dt ); @@ -314,8 +314,8 @@ double TDynamicObject::radius() const { glm::vec3 diagonal( - static_cast( MoverParameters->Dim.L ), - static_cast( MoverParameters->Dim.H ), - static_cast( MoverParameters->Dim.W ) ); + static_cast( physics->Dim.L ), + static_cast( physics->Dim.H ), + static_cast( physics->Dim.W ) ); return glm::length( diagonal ) * 0.5f; } diff --git a/vehicle/dynamic/neighbours.cpp b/vehicle/dynamic/neighbours.cpp index cc43d8e56..dc24a84a5 100644 --- a/vehicle/dynamic/neighbours.cpp +++ b/vehicle/dynamic/neighbours.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/DynObj.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/lightsprogrammer.h" #include "simulation/simulation.h" #include "simulation/blackboxrecorder.h" @@ -165,7 +165,7 @@ void TDynamicObject::ABuBogies() { // Obracanie wozkow na zakretach. Na razie // uwzględnia tylko zakręty, // bez zadnych gorek i innych przeszkod. - if( smBogie[ 0 ] != nullptr && smBogie[ 1 ] != nullptr && MoverParameters->OffTrack.active() ) { + if( smBogie[ 0 ] != nullptr && smBogie[ 1 ] != nullptr && physics->OffTrack.active() ) { // off the track the bogies stay straight under the body, they don't follow the track any more bogieRot[ 0 ] = glm::vec3 { 0.f }; bogieRot[ 1 ] = glm::vec3 { 0.f }; @@ -252,12 +252,12 @@ TDynamicObject::ABuFindObject( int &Foundcoupler, double &Distance, TTrack const if( dynamic == this ) { continue; } // szukający się nie liczy // physics.derailment new: one of the two off the track beside the other one, they don't meet - if( InLine && ( MoverParameters->OffTrack.active() || dynamic->MoverParameters->OffTrack.active() ) && false == in_line_with( *dynamic ) ) { + if( InLine && ( physics->OffTrack.active() || dynamic->physics->OffTrack.active() ) && false == in_line_with( *dynamic ) ) { continue; } /* - if( ( ( dynamic == PrevConnected ) && ( MoverParameters->Couplers[ TMoverParameters::side::front ].CouplingFlag != Coupling::none ) ) - || ( ( dynamic == NextConnected ) && ( MoverParameters->Couplers[ TMoverParameters::side::rear ].CouplingFlag != Coupling::none ) ) ){ + if( ( ( dynamic == PrevConnected ) && ( physics->Couplers[ physics::Vehicle::side::front ].CouplingFlag != Coupling::none ) ) + || ( ( dynamic == NextConnected ) && ( physics->Couplers[ physics::Vehicle::side::rear ].CouplingFlag != Coupling::none ) ) ){ // stop-gap check to prevent 'detection' of attached vehicles // which seems to be a side-effect of inaccurate location calculation in 'simple' mode? // TODO: investigate actual cause @@ -293,12 +293,12 @@ TDynamicObject::ABuFindObject( int &Foundcoupler, double &Distance, TTrack const double relativeoffset; // wzajemna odległość poprzeczna if( Foundcoupler != Mycoupler ) { // facing the same direction - relativeoffset = std::abs( MoverParameters->OffsetTrackH - dynamic->MoverParameters->OffsetTrackH ); + relativeoffset = std::abs( physics->OffsetTrackH - dynamic->physics->OffsetTrackH ); } else { - relativeoffset = std::abs( MoverParameters->OffsetTrackH + dynamic->MoverParameters->OffsetTrackH ); + relativeoffset = std::abs( physics->OffsetTrackH + dynamic->physics->OffsetTrackH ); } - if( relativeoffset + relativeoffset > MoverParameters->Dim.W + dynamic->MoverParameters->Dim.W ) { + if( relativeoffset + relativeoffset > physics->Dim.W + dynamic->physics->Dim.W ) { // odległość większa od połowy sumy szerokości - kolizji nie będzie continue; } diff --git a/vehicle/dynamic/offtrack.cpp b/vehicle/dynamic/offtrack.cpp index c1dab3d46..40bb90392 100644 --- a/vehicle/dynamic/offtrack.cpp +++ b/vehicle/dynamic/offtrack.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/DynObj.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/lightsprogrammer.h" #include "simulation/simulation.h" #include "simulation/blackboxrecorder.h" @@ -150,19 +150,19 @@ glm::dvec3 level_left_of( glm::dvec3 const &Front ) { // and the buffers of the side it rolled to miss those of an upright one derail_motion::end_point end_point_of( TDynamicObject const &Vehicle, VehicleEnd const End ) { auto const facing { End == VehicleEnd::front ? 1.0 : -1.0 }; - auto const &motion { Vehicle.MoverParameters->OffTrack }; + auto const &motion { Vehicle.physics->OffTrack }; glm::dvec3 const front { Vehicle.VectorFront().x, 0.0, Vehicle.VectorFront().z }; auto const length { glm::length( front ) }; auto const axis { length > 1e-6 ? front / length : glm::dvec3 { 0.0, 0.0, 1.0 } }; auto const middle { motion.active() ? motion.base() : Vehicle.GetPosition() }; return derail_motion::end_point { - middle + glm::dvec3 { 0.0, derail_motion::buffer_height, 0.0 } + axis * ( facing * 0.5 * Vehicle.MoverParameters->Dim.L ), + middle + glm::dvec3 { 0.0, derail_motion::buffer_height, 0.0 } + axis * ( facing * 0.5 * Vehicle.physics->Dim.L ), axis * facing, motion.active() ? motion.tipping() : 0.0 }; } // the push of the buffers on the end of the vehicle [N], negative the pull of its coupling -double compression_of( TMoverParameters const &Vehicle, VehicleEnd const End ) { +double compression_of( physics::Vehicle const &Vehicle, VehicleEnd const End ) { return ( End == VehicleEnd::front ? -1.0 : 1.0 ) * Vehicle.Couplers[ End ].CForce; } @@ -185,16 +185,16 @@ std::string_view side_name( int const Side ) { double TDynamicObject::off_track_gap( VehicleEnd const End ) const { - auto const *neighbour { MoverParameters->Neighbours[ End ].vehicle }; + auto const *neighbour { physics->Neighbours[ End ].vehicle }; if( neighbour == nullptr ) { return 0.0; } - return derail_motion::meet( end_point_of( *this, End ), end_point_of( *neighbour, MoverParameters->Neighbours[ End ].FacingEnd() ) ).gap; + return derail_motion::meet( end_point_of( *this, End ), end_point_of( *neighbour, physics->Neighbours[ End ].FacingEnd() ) ).gap; } double TDynamicObject::off_track_offset() const { - if( false == MoverParameters->OffTrack.active() ) { + if( false == physics->OffTrack.active() ) { return 0.0; } auto const middle { 0.5 * ( Axle0.pPosition + Axle1.pPosition ) }; @@ -228,7 +228,7 @@ int TDynamicObject::outward_side() const { // buckle bends the line the other way more than the curve does (the criteria of derailment, physics/derailment.h) if( auto const design { std::sin( Axle1.vAngles.z - Axle0.vAngles.z ) }; std::abs( design ) >= 1e-4 ) { auto const outside { design > 0.0 ? -1 : 1 }; - return MoverParameters->DerailAcceleration < 0.0 ? -outside : outside; + return physics->DerailAcceleration < 0.0 ? -outside : outside; } // a straight track: the path under the vehicle as it is, a buckle on it, turns from the rear axle to the front one auto const front { Axle0.PathDirection() }; @@ -244,22 +244,21 @@ int TDynamicObject::outward_side() const { void TDynamicObject::gather_off_track_terrain() { - auto const &mover { *MoverParameters }; - auto const &position { mover.OffTrack.active() ? mover.OffTrack.current().position : vPosition }; + auto const &position { physics->OffTrack.active() ? physics->OffTrack.current().position : vPosition }; // as far as it may slide, and some - auto const slide { derail_motion::stopping_distance( mover.V, derailment::off_rails_friction ).value_or( 0.0 ) }; - auto const reach { std::min( slide + mover.Dim.L + 50.0, 600.0 ) }; + auto const slide { derail_motion::stopping_distance( physics->V, derailment::off_rails_friction ).value_or( 0.0 ) }; + auto const reach { std::min( slide + physics->Dim.L + 50.0, 600.0 ) }; m_offtrackgathered = m_offtracktotal; m_offtrackcropped = false; // the terrain of another vehicle, where it covers the way this one goes: around it and around where it stops going // straight on, by its length and the margin the terrain is gathered again at glm::dvec3 heading { vFront.x, 0.0, vFront.z }; - if( mover.OffTrack.active() ) { - heading = mover.OffTrack.heading(); + if( physics->OffTrack.active() ) { + heading = physics->OffTrack.heading(); } auto const length { glm::length( heading ) }; - auto const stop { length > 1e-6 ? position + heading * ( std::copysign( std::max( reach - mover.Dim.L - 50.0, 0.0 ), mover.V ) / length ) : position }; - auto const margin { mover.Dim.L + 30.0 }; + auto const stop { length > 1e-6 ? position + heading * ( std::copysign( std::max( reach - physics->Dim.L - 50.0, 0.0 ), physics->V ) / length ) : position }; + auto const margin { physics->Dim.L + 30.0 }; if( auto shared { simulation::Vehicles.off_track_terrain( glm::dvec2 { std::min( position.x, stop.x ) - margin, std::min( position.z, stop.z ) - margin }, glm::dvec2 { std::max( position.x, stop.x ) + margin, std::max( position.z, stop.z ) + margin } ) }; @@ -284,7 +283,7 @@ void TDynamicObject::gather_off_track_terrain() { return std::max( std::abs( middle.x - position.x ), std::abs( middle.z - position.z ) ); }; return distance( Left ) < distance( Right ); } ); triangles.resize( off_track_triangles ); - ErrorLog( std::format( "derailment: warning: {} found more than {} triangles of terrain around it, took the nearest", MoverParameters->Name, off_track_triangles ) ); + ErrorLog( std::format( "derailment: warning: {} found more than {} triangles of terrain around it, took the nearest", physics->Name, off_track_triangles ) ); } if( triangles.empty() ) { // a scenery without terrain: level with the top of the ballast @@ -300,7 +299,7 @@ void TDynamicObject::gather_off_track_terrain() { m_offtracksite.terrain( m_offtrackterrain.get() ); auto const took { seconds_since( started ) }; if( took > off_track_slow ) { - ErrorLog( std::format( "derailment: warning: gathering the terrain of {:.0f} m around {} took {:.0f} ms ({} triangles)", reach, MoverParameters->Name, took * 1000.0, triangles.size() ) ); + ErrorLog( std::format( "derailment: warning: gathering the terrain of {:.0f} m around {} took {:.0f} ms ({} triangles)", reach, physics->Name, took * 1000.0, triangles.size() ) ); } } @@ -311,8 +310,8 @@ void TDynamicObject::crop_off_track_terrain() { } m_offtrackcropped = true; // the ground under it, and as far around as it gathers the terrain anew once it moves again - auto const &position { MoverParameters->OffTrack.current().position }; - auto const reach { 0.5 * MoverParameters->Dim.L + 40.0 }; + auto const &position { physics->OffTrack.current().position }; + auto const reach { 0.5 * physics->Dim.L + 40.0 }; m_offtrackmin = glm::dvec2 { position.x - reach, position.z - reach }; m_offtrackmax = glm::dvec2 { position.x + reach, position.z + reach }; m_offtrackterrain = std::make_shared( m_offtrackterrain->cropped( m_offtrackmin, m_offtrackmax ) ); @@ -321,40 +320,39 @@ void TDynamicObject::crop_off_track_terrain() { void TDynamicObject::begin_off_track() { - auto &mover { *MoverParameters }; derail_motion::vehicle_shape shape; - shape.length = mover.Dim.L; - shape.width = mover.Dim.W > 0.5 ? mover.Dim.W : 3.0; + shape.length = physics->Dim.L; + shape.width = physics->Dim.W > 0.5 ? physics->Dim.W : 3.0; // a height up to 2 m in the definition is the height of the floor, the older meaning of the key - shape.height = mover.Dim.H > 2.0 ? mover.Dim.H : 4.0; - shape.centre_of_gravity = mover.centre_of_gravity(); - shape.contact_spacing = derailment::contact_spacing( mover.TrackW ); + shape.height = physics->Dim.H > 2.0 ? physics->Dim.H : 4.0; + shape.centre_of_gravity = physics->centre_of_gravity(); + shape.contact_spacing = derailment::contact_spacing( physics->TrackW ); shape.base = std::max( static_cast( fAxleDist ), 1.0 ); - shape.mass = mover.TotalMass; + shape.mass = physics->TotalMass; derail_motion::start start; start.position = vPosition; start.front = vFront; start.line = track_front(); - start.speed = mover.V; - start.reason = mover.DerailCause; - start.outward = ( mover.DerailSide != 0 ? mover.DerailSide : outward_side() ); - start.acceleration = mover.DerailAcceleration; + start.speed = physics->V; + start.reason = physics->DerailCause; + start.outward = ( physics->DerailSide != 0 ? physics->DerailSide : outward_side() ); + start.acceleration = physics->DerailAcceleration; // the terrain as far as it may slide, and some m_offtracktotal = 0.0; gather_off_track_terrain(); m_offtracksite = derail_motion::site { m_offtrackterrain.get(), track_bed() }; // each vehicle its own way of going off, from the seed of the run (the same seed, the same way) - auto const scatter { derail_motion::draw_scatter( derail_motion::seed_of( Global.random_seed, mover.Name ) ) }; - mover.OffTrack.begin( start, shape, m_offtracksite, scatter ); + auto const scatter { derail_motion::draw_scatter( derail_motion::seed_of( Global.random_seed, physics->Name ) ) }; + physics->OffTrack.begin( start, shape, m_offtracksite, scatter ); m_pulledoff = {}; m_offtracklogdue = 0.0; m_offtrackslowdue = 0.0; m_offtrackaxles = 0.0; - m_offtrackfrom = mover.OffTrack.current().position; + m_offtrackfrom = physics->OffTrack.current().position; - auto const heading { mover.OffTrack.heading() }; + auto const heading { physics->OffTrack.heading() }; auto const front { glm::dvec3 { vFront.x, 0.0, vFront.z } }; auto const turn { std::asin( std::clamp( glm::dot( heading, level_left_of( glm::normalize( front ) ) ), -1.0, 1.0 ) ) }; std::string terrain { "no terrain, level ground" }; @@ -363,18 +361,18 @@ void TDynamicObject::begin_off_track() { } WriteLog( std::format( "derailment: {} leaves the track at {:.0f} km/h on track {}, heading turned {:.1f} deg to the {}, the outside of the curve to the {}; {} around it", - mover.Name, std::abs( mover.V ) * 3.6, MyTrack != nullptr ? MyTrack->name() : std::string { "(none)" }, + physics->Name, std::abs( physics->V ) * 3.6, MyTrack != nullptr ? MyTrack->name() : std::string { "(none)" }, std::abs( glm::degrees( turn ) ), side_name( turn >= 0.0 ? 1 : -1 ), side_name( start.outward ), terrain ) ); WriteLog( std::format( "derailment: {} scattered by {:+.2f} deg of departure, {:+.2f} deg of yaw at {:+.3f} rad/s, the friction under its ends x{:.2f} / x{:.2f}{}", - mover.Name, glm::degrees( scatter.departure ), glm::degrees( scatter.yaw ), scatter.yaw_rate, scatter.friction_front, scatter.friction_rear, + physics->Name, glm::degrees( scatter.departure ), glm::degrees( scatter.yaw ), scatter.yaw_rate, scatter.friction_front, scatter.friction_rear, scatter.dig_in >= 0.0 ? std::format( ", its leading end digs in after {:.2f} s, x{:.2f} for {:.2f} s", scatter.dig_in, scatter.dig_in_friction, scatter.dig_in_time ) : std::string {} ) ); } void TDynamicObject::move_off_track( double const Distance ) { auto const started { off_track_clock::now() }; - auto &motion { MoverParameters->OffTrack }; + auto &motion { physics->OffTrack }; auto const time { std::exchange( m_offtracktime, 0.0 ) }; m_offtracktotal += time; // near the edge of the terrain gathered, the terrain further on; not more than once a second, whatever happens @@ -390,19 +388,19 @@ void TDynamicObject::move_off_track( double const Distance ) { // the buffers and the couplings of its ends push and pull it, at an angle to it where the vehicle coupled there is std::array ends {}; for (auto const end : VehicleEnds) { - auto const *neighbour { MoverParameters->Neighbours[ end ].vehicle }; - auto const compression { compression_of( *MoverParameters, end ) }; + auto const *neighbour { physics->Neighbours[ end ].vehicle }; + auto const compression { compression_of( *physics, end ) }; if( neighbour == nullptr || compression == 0.0 ) { continue; } ends[ NumberOf( end ) ] = derail_motion::force_on( - derail_motion::meet( end_point_of( *this, end ), end_point_of( *neighbour, MoverParameters->Neighbours[ end ].FacingEnd() ) ), compression ); + derail_motion::meet( end_point_of( *this, end ), end_point_of( *neighbour, physics->Neighbours[ end ].FacingEnd() ) ), compression ); } auto const reversals { motion.reversals() }; - motion.step( time, Distance, MoverParameters->V, m_offtracksite, ends ); + motion.step( time, Distance, physics->V, m_offtracksite, ends ); if( ( motion.reversals() - reversals ) % 2 != 0 ) { // the body turned about against the way it goes: the vehicle goes rear first, its speed the other way along it - MoverParameters->V = -MoverParameters->V; + physics->V = -physics->V; } auto const &pose { motion.current() }; // the axles go along the track as far as the vehicle went along it, for the track nearest to it: the vehicles on it @@ -426,20 +424,20 @@ void TDynamicObject::move_off_track( double const Distance ) { m_offtrackslowdue -= time; if( took > off_track_slow && m_offtrackslowdue <= 0.0 ) { m_offtrackslowdue = 1.0; - ErrorLog( std::format( "derailment: warning: moving {} off the track took {:.0f} ms in a frame of {:.3f} s", MoverParameters->Name, took * 1000.0, time ) ); + ErrorLog( std::format( "derailment: warning: moving {} off the track took {:.0f} ms in a frame of {:.3f} s", physics->Name, took * 1000.0, time ) ); } } void TDynamicObject::place_off_track() { - auto const &pose { MoverParameters->OffTrack.current() }; + auto const &pose { physics->OffTrack.current() }; vPosition = pose.position; vFront = pose.front; vLeft = pose.left; vUp = pose.up; modelRot.z = std::atan2( -vFront.x, vFront.z ); mMatrix = glm::inverse( BasisChange( vLeft, vUp, vFront ) ); - auto const half { 0.5 * MoverParameters->Dim.L * vFront }; + auto const half { 0.5 * physics->Dim.L * vFront }; vCoulpler[ VehicleEnd::front ] = vPosition + half; vCoulpler[ VehicleEnd::rear ] = vPosition - half; m_offtrackplaced = true; @@ -448,15 +446,15 @@ void TDynamicObject::place_off_track() { void TDynamicObject::pull_neighbours( double const Distance ) { for (auto const end : VehicleEnds) { - auto const &coupler { MoverParameters->Couplers[ end ] }; - auto *neighbour { MoverParameters->Neighbours[ end ].vehicle }; - if( coupler.CouplingFlag == Coupling::none || neighbour == nullptr || neighbour->MoverParameters->OffTrack.active() - || neighbour->MoverParameters->DamageFlag.HasAll(VehicleDamage::derailed) ) { + auto const &coupler { physics->Couplers[ end ] }; + auto *neighbour { physics->Neighbours[ end ].vehicle }; + if( coupler.CouplingFlag == Coupling::none || neighbour == nullptr || neighbour->physics->OffTrack.active() + || neighbour->physics->DamageFlag.HasAll(VehicleDamage::derailed) ) { m_pulledoff[ end ].reset(); continue; } - auto &other { *neighbour->MoverParameters }; - auto const otherend { MoverParameters->Neighbours[ end ].FacingEnd() }; + auto &other { *neighbour->physics }; + auto const otherend { physics->Neighbours[ end ].FacingEnd() }; glm::dvec3 const otherfront { neighbour->vFront.x, 0.0, neighbour->vFront.z }; if( glm::length( otherfront ) < 1e-6 ) { continue; @@ -479,14 +477,14 @@ void TDynamicObject::pull_neighbours( double const Distance ) { other.pull_off( side, mass > 0.0 ? std::abs( across ) / mass : 0.0, - std::format( "Y/Q {:.2f} from the {} of {} at {:.0f} deg, {:.0f} kN", ratio, compression > 0.0 ? "buffers" : "coupling", MoverParameters->Name, glm::degrees( angle ), magnitude / 1000.0 ) ); + std::format( "Y/Q {:.2f} from the {} of {} at {:.0f} deg, {:.0f} kN", ratio, compression > 0.0 ? "buffers" : "coupling", physics->Name, glm::degrees( angle ), magnitude / 1000.0 ) ); m_pulledoff[ end ].reset(); } } void TDynamicObject::update_off_track( double const Deltatime ) { - auto const &motion { MoverParameters->OffTrack }; + auto const &motion { physics->OffTrack }; if( false == motion.active() || m_offtracklogdue < 0.0 ) { // on the track, or came to rest and told so return; @@ -499,6 +497,6 @@ void TDynamicObject::update_off_track( double const Deltatime ) { m_offtracklogdue = ( resting ? -1.0 : 1.0 ); WriteLog( std::format( "derailment: {} {} {:.1f} m from where it left the rails, {:.1f} m from the axis of the track, at {:.1f} km/h, sliding sideways at {:.1f} m/s, tipped {:.0f} deg, roll {:.0f} deg, yaw {:+.1f} deg turning at {:+.1f} deg/s{}", - MoverParameters->Name, resting ? "came to rest" : "off the track", motion.travelled(), off_track_offset(), std::abs( MoverParameters->V ) * 3.6, motion.sideways(), + physics->Name, resting ? "came to rest" : "off the track", motion.travelled(), off_track_offset(), std::abs( physics->V ) * 3.6, motion.sideways(), glm::degrees( motion.tipping() ), glm::degrees( motion.roll() ), glm::degrees( motion.yaw() ), glm::degrees( motion.yaw_rate() ), motion.lying() ? ", lying on its side" : "" ) ); } diff --git a/vehicle/dynamic/sounds.cpp b/vehicle/dynamic/sounds.cpp index 62684280f..e4ee66811 100644 --- a/vehicle/dynamic/sounds.cpp +++ b/vehicle/dynamic/sounds.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/DynObj.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/lightsprogrammer.h" #include "simulation/simulation.h" #include "simulation/blackboxrecorder.h" @@ -65,21 +65,21 @@ void TDynamicObject::RenderSounds() { if( Global.iPause != 0 ) { return; } if( m_startjoltplayed - && ( std::abs(MoverParameters->AccSVBased) < 0.01 + && ( std::abs(physics->AccSVBased) < 0.01 || GetVelocity() < 0.01 ) ) { // if the vehicle comes to a stop set the movement jolt to play when it starts moving again m_startjoltplayed = false; } auto const dt{ Timer::GetDeltaRenderTime() }; - m_powertrainsounds.render( *MoverParameters, dt ); + m_powertrainsounds.render( *physics, dt ); renderAuxiliarySounds(); // brake system and braking sounds: // brake cylinder piston - auto const brakepressureratio { std::max( 0.0, MoverParameters->BrakePress ) / std::max( 1.0, MoverParameters->MaxBrakePress[ 3 ] ) }; + auto const brakepressureratio { std::max( 0.0, physics->BrakePress ) / std::max( 1.0, physics->MaxBrakePress[ 3 ] ) }; renderBrakeCylinderSounds( brakepressureratio ); renderEpBrakeSounds( dt ); renderEmergencyBrakeSound(); @@ -100,11 +100,11 @@ void TDynamicObject::RenderSounds() { renderStartJoltSound(); // McZapkie! - to wazne - SoundFlag wystawiane jest przez moje moduly gdy zachodza pewne wydarzenia komentowane dzwiekiem. - renderMoverEventSounds(); + renderPhysicsEventSounds(); renderCouplerSounds(); - MoverParameters->SoundFlag = 0; - // McZapkie! - koniec obslugi dzwiekow z mover.pas + physics->SoundFlag = 0; + // McZapkie! - koniec obslugi dzwiekow z physics.pas renderDerailmentSounds(); } @@ -115,12 +115,12 @@ void TDynamicObject::renderAuxiliarySounds() { auto frequency{ 1.0 }; // NBMX dzwiek przetwornicy - if( MoverParameters->ConverterFlag ) { - if( MoverParameters->EngineType == TEngineType::ElectricSeriesMotor ) { - auto const voltage { std::max( MoverParameters->GetTrainsetHighVoltage(), MoverParameters->PantographVoltage ) }; + if( physics->ConverterFlag ) { + if( physics->EngineType == TEngineType::ElectricSeriesMotor ) { + auto const voltage { std::max( physics->GetTrainsetHighVoltage(), physics->PantographVoltage ) }; if( voltage > 0.0 ) { // NOTE: we do sound modulation here to avoid sudden jump on voltage loss - frequency = voltage / (MoverParameters->NominalVoltage * MoverParameters->RList[MoverParameters->RlistSize].Mn); + frequency = voltage / (physics->NominalVoltage * physics->RList[physics->RlistSize].Mn); frequency *= sConverter.m_frequencyfactor + sConverter.m_frequencyoffset; sConverter.pitch( std::clamp( frequency, 0.75, 1.25 ) ); // arbitrary limits ) } @@ -137,7 +137,7 @@ void TDynamicObject::renderAuxiliarySounds() { // Odtworzenie dzwieku wentylatora rezystora hamowania - if (MoverParameters->BRVentilators) + if (physics->BRVentilators) { sBRVent.play(sound_flags::exclusive | sound_flags::looping); } @@ -150,16 +150,16 @@ void TDynamicObject::renderAuxiliarySounds() { - if( MoverParameters->CompressorSpeed > 0.0 ) { + if( physics->CompressorSpeed > 0.0 ) { // McZapkie! - dzwiek compressor.wav tylko gdy dziala sprezarka - if( MoverParameters->CompressorFlag ) { + if( physics->CompressorFlag ) { // for compressor coupled with the diesel engine sound pitch is driven by engine revolutions - if( MoverParameters->CompressorPower == 3 ) { + if( physics->CompressorPower == 3 ) { // presume the compressor sound is recorded for idle revolutions // increase the pitch according to increase of engine revolutions auto const enginefactor { std::clamp( // try to keep the sound pitch in semi-reasonable range - MoverParameters->EngineMaxRPM() / MoverParameters->EngineIdleRPM() * MoverParameters->EngineRPMRatio(), + physics->EngineMaxRPM() / physics->EngineIdleRPM() * physics->EngineRPMRatio(), 0.5, 2.5 ) }; sCompressor.pitch( enginefactor ); sCompressorIdle.pitch( enginefactor ); @@ -170,7 +170,7 @@ void TDynamicObject::renderAuxiliarySounds() { } else { // enhanced sound path, with dedicated sound for idling compressor - if( MoverParameters->CompressorGovernorLock ) { + if( physics->CompressorGovernorLock ) { sCompressor.stop(); sCompressorIdle.play( sound_flags::exclusive | sound_flags::looping ); } @@ -187,7 +187,7 @@ void TDynamicObject::renderAuxiliarySounds() { } // Winger 160404 - dzwiek malej sprezarki - if( MoverParameters->PantCompFlag ) { + if( physics->PantCompFlag ) { sSmallCompressor.play( sound_flags::exclusive | sound_flags::looping ); } else { @@ -196,13 +196,13 @@ void TDynamicObject::renderAuxiliarySounds() { // heater sound { - auto const isdieselenginepowered { MoverParameters->EngineType == TEngineType::DieselElectric || MoverParameters->EngineType == TEngineType::DieselEngine }; - if( true == MoverParameters->Heating + auto const isdieselenginepowered { physics->EngineType == TEngineType::DieselElectric || physics->EngineType == TEngineType::DieselEngine }; + if( true == physics->Heating && ( false == isdieselenginepowered - || std::abs(MoverParameters->enrot) > 0.01 ) ) { + || std::abs(physics->enrot) > 0.01 ) ) { sHeater .pitch( true == sHeater.is_combined() ? - std::abs( MoverParameters->enrot ) * 60.f * 0.01f : + std::abs( physics->enrot ) * 60.f * 0.01f : 1.f ) .play( sound_flags::exclusive | sound_flags::looping ); } @@ -212,7 +212,7 @@ void TDynamicObject::renderAuxiliarySounds() { } // battery sound - if( MoverParameters->Battery ) { + if( physics->Battery ) { m_batterysound.play( sound_flags::exclusive | sound_flags::looping ); } else { @@ -233,7 +233,7 @@ void TDynamicObject::renderBrakeCylinderSounds( double const brakepressureratio } // actual sound playback auto const quantizedratio { static_cast( 15 * brakepressureratio ) }; - auto const lastbrakepressureratio { std::max( 0.f, m_lastbrakepressure ) / std::max( 1.0, MoverParameters->MaxBrakePress[ 3 ] ) }; + auto const lastbrakepressureratio { std::max( 0.f, m_lastbrakepressure ) / std::max( 1.0, physics->MaxBrakePress[ 3 ] ) }; auto const quantizedratiochange { quantizedratio - static_cast( 15 * lastbrakepressureratio ) }; if( quantizedratiochange > 0 ) { m_brakecylinderpistonadvance @@ -257,10 +257,10 @@ void TDynamicObject::renderBrakeCylinderSounds( double const brakepressureratio void TDynamicObject::renderEpBrakeSounds( double const dt ) { // epbrake - epcompact - if (MoverParameters->BrakeSystem == TBrakeSystem::ElectroPneumatic && MoverParameters->LocHandle) { - auto const epbrakepressureratio{ std::min( std::max( 0.0, MoverParameters->LocHandle->GetCP() ) / std::max( 1.0, MoverParameters->MaxBrakePress[0] ), + if (physics->BrakeSystem == TBrakeSystem::ElectroPneumatic && physics->LocHandle) { + auto const epbrakepressureratio{ std::min( std::max( 0.0, physics->LocHandle->GetCP() ) / std::max( 1.0, physics->MaxBrakePress[0] ), m_epbrakepressurechangedectimer > -1.0f ? - std::max( MoverParameters->LocalBrakePosAEIM, MoverParameters->Hamulec->GetEDBCP() / MoverParameters->MaxBrakePress[3]) : + std::max( physics->LocalBrakePosAEIM, physics->Hamulec->GetEDBCP() / physics->MaxBrakePress[3]) : 1.0 ) }; if ( m_lastepbrakepressure != -1.f ) { // HACK: potentially reset playback of opening bookend sounds @@ -274,7 +274,7 @@ void TDynamicObject::renderEpBrakeSounds( double const dt ) { m_epbrakepressurechangedectimer += dt; // actual sound playback auto const epquantizedratio{ static_cast( 50 * epbrakepressureratio) }; - auto const lastepbrakepressureratio { std::max( 0.f, m_lastepbrakepressure ) / std::max( 1.0, MoverParameters->MaxBrakePress[0] ) }; + auto const lastepbrakepressureratio { std::max( 0.f, m_lastepbrakepressure ) / std::max( 1.0, physics->MaxBrakePress[0] ) }; auto const epquantizedratiochange { epquantizedratio - static_cast( 50 * lastepbrakepressureratio ) }; if ( epquantizedratiochange > 0 && m_epbrakepressurechangeinctimer > 0.05f) { m_epbrakepressureincrease @@ -295,8 +295,8 @@ void TDynamicObject::renderEpBrakeSounds( double const dt ) { } } if ( m_epbrakepressurechangeinctimer == 0 || m_epbrakepressurechangedectimer == 0 ) - m_lastepbrakepressure = std::min( MoverParameters->LocHandle->GetCP(), - MoverParameters->LocalBrakePosAEIM * std::max( 1.0, MoverParameters->MaxBrakePress[0] ) ); + m_lastepbrakepressure = std::min( physics->LocHandle->GetCP(), + physics->LocalBrakePosAEIM * std::max( 1.0, physics->MaxBrakePress[0] ) ); } } @@ -304,17 +304,17 @@ void TDynamicObject::renderEpBrakeSounds( double const dt ) { void TDynamicObject::renderEmergencyBrakeSound() { // emergency brake - if( MoverParameters->EmergencyValveFlow > 0.025 ) { + if( physics->EmergencyValveFlow > 0.025 ) { // smooth out air flow rate - m_emergencybrakeflow = m_emergencybrakeflow == 0.0 ? MoverParameters->EmergencyValveFlow : std::lerp(m_emergencybrakeflow, MoverParameters->EmergencyValveFlow, 0.1); + m_emergencybrakeflow = m_emergencybrakeflow == 0.0 ? physics->EmergencyValveFlow : std::lerp(m_emergencybrakeflow, physics->EmergencyValveFlow, 0.1); // scale volume based on the flow rate and on the pressure in the main pipe - auto const flowpressure { std::clamp( m_emergencybrakeflow, 0.0, 1.0 ) + std::clamp( 0.1 * MoverParameters->PipePress, 0.0, 0.5 ) }; + auto const flowpressure { std::clamp( m_emergencybrakeflow, 0.0, 1.0 ) + std::clamp( 0.1 * physics->PipePress, 0.0, 0.5 ) }; m_emergencybrake .pitch( m_emergencybrake.m_frequencyoffset + 1.0 * m_emergencybrake.m_frequencyfactor ) .gain( m_emergencybrake.m_amplitudeoffset + std::clamp( flowpressure, 0.0, 1.0 ) * m_emergencybrake.m_amplitudefactor ) .play( sound_flags::exclusive | sound_flags::looping ); } - else if( MoverParameters->EmergencyValveFlow < 0.015 ) { + else if( physics->EmergencyValveFlow < 0.015 ) { m_emergencybrakeflow = 0.0; m_emergencybrake.stop(); } @@ -328,10 +328,10 @@ void TDynamicObject::renderAirReleaseSounds( double const dt, double const brake // air release if( m_lastbrakepressure != -1.f ) { // calculate rate of pressure drop in brake cylinder, once it's been initialized - auto const brakepressuredifference{ m_lastbrakepressure - MoverParameters->BrakePress }; + auto const brakepressuredifference{ m_lastbrakepressure - physics->BrakePress }; m_brakepressurechange = std::lerp( m_brakepressurechange, brakepressuredifference / dt, 0.05f ); } - m_lastbrakepressure = MoverParameters->BrakePress; + m_lastbrakepressure = physics->BrakePress; // ensure some basic level of volume and scale it up depending on pressure in the cylinder; scale this by the air release rate volume = rsUnbrake.m_amplitudefactor * m_brakepressurechange * ( 0.25 + 0.75 * brakepressureratio ); if( m_brakepressurechange > 0.05 && brakepressureratio > 0.05 ) { @@ -349,11 +349,11 @@ void TDynamicObject::renderAirReleaseSounds( double const dt, double const brake } // Dzwiek odluzniacza - if( MoverParameters->Hamulec->Releaser() ) { + if( physics->Hamulec->Releaser() ) { sReleaser .gain( std::clamp( - MoverParameters->BrakePress * 1.25, // arbitrary multiplier + physics->BrakePress * 1.25, // arbitrary multiplier 0., 1. ) ) .play( sound_flags::exclusive | sound_flags::looping ); } @@ -366,12 +366,12 @@ void TDynamicObject::renderAirReleaseSounds( double const dt, double const brake void TDynamicObject::renderSlipAndSandSounds() { // slipping wheels - if( MoverParameters->SlippingWheels ) { + if( physics->SlippingWheels ) { - if( MoverParameters->UnitBrakeForce > 100.0 + if( physics->UnitBrakeForce > 100.0 && GetVelocity() > 1.0 ) { - auto const velocitydifference{ GetVelocity() / MoverParameters->Vmax }; + auto const velocitydifference{ GetVelocity() / physics->Vmax }; rsSlippery .gain( rsSlippery.m_amplitudeoffset + rsSlippery.m_amplitudefactor * velocitydifference ) .play( sound_flags::exclusive | sound_flags::looping ); @@ -382,7 +382,7 @@ void TDynamicObject::renderSlipAndSandSounds() { } // Dzwiek piasecznicy - if( MoverParameters->SandDose ) { + if( physics->SandDose ) { sSand.play( sound_flags::exclusive | sound_flags::looping ); } else { @@ -397,17 +397,17 @@ double TDynamicObject::renderBrakeFrictionSounds( double const dt ) { // brakes auto brakeforceratio{ 0.0 }; - if( //( false == mvOccupied->SlippingWheels ) && - MoverParameters->UnitBrakeForce > 10.0 - && MoverParameters->Vel > 0.05 ) { + if( //( false == occupied->SlippingWheels ) && + physics->UnitBrakeForce > 10.0 + && physics->Vel > 0.05 ) { brakeforceratio = std::clamp( - MoverParameters->UnitBrakeForce / std::max( 1.0, MoverParameters->BrakeForceR( 1.0, MoverParameters->Vel ) / ( MoverParameters->NAxles * std::max( 1, MoverParameters->NBpA ) ) ), + physics->UnitBrakeForce / std::max( 1.0, physics->BrakeForceR( 1.0, physics->Vel ) / ( physics->NAxles * std::max( 1, physics->NBpA ) ) ), 0.0, 1.0 ); rsBrake - .pitch( rsBrake.m_frequencyoffset + MoverParameters->Vel * rsBrake.m_frequencyfactor ) - .gain( rsBrake.m_amplitudeoffset + std::sqrt( brakeforceratio * std::lerp( 0.4, 1.0, MoverParameters->Vel / (1 + MoverParameters->Vmax) ) ) * rsBrake.m_amplitudefactor ) + .pitch( rsBrake.m_frequencyoffset + physics->Vel * rsBrake.m_frequencyfactor ) + .gain( rsBrake.m_amplitudeoffset + std::sqrt( brakeforceratio * std::lerp( 0.4, 1.0, physics->Vel / (1 + physics->Vmax) ) ) * rsBrake.m_amplitudefactor ) .play( sound_flags::exclusive | sound_flags::looping ); } else { @@ -416,20 +416,20 @@ double TDynamicObject::renderBrakeFrictionSounds( double const dt ) { // yB: przyspieszacz (moze zadziala, ale dzwiek juz jest) if( true == bBrakeAcc ) { - if( true == TestFlag( MoverParameters->Hamulec->GetSoundFlag(), sf_Acc ) ) { + if( true == TestFlag( physics->Hamulec->GetSoundFlag(), sf_Acc ) ) { sBrakeAcc.play( sound_flags::exclusive ); } } // McZapkie-280302 - pisk mocno zacisnietych hamulcow - if( MoverParameters->Vel > 2.5 ) { + if( physics->Vel > 2.5 ) { volume = rsPisk.m_amplitudeoffset + std::lerp( -1.0, 1.0, brakeforceratio ) * rsPisk.m_amplitudefactor; if( volume > 0.075 ) { rsPisk .pitch( true == rsPisk.is_combined() ? - MoverParameters->Vel * 0.01f : + physics->Vel * 0.01f : rsPisk.m_frequencyoffset + rsPisk.m_frequencyfactor * 1.f ) .gain( volume ) .play( sound_flags::exclusive | sound_flags::looping ); @@ -451,8 +451,8 @@ double TDynamicObject::renderBrakeFrictionSounds( double const dt ) { void TDynamicObject::renderSpringBrakeSounds() { // spring brake - if( m_springbrakesounds.state != MoverParameters->SpringBrake.Activate ) { - m_springbrakesounds.state = MoverParameters->SpringBrake.Activate; + if( m_springbrakesounds.state != physics->SpringBrake.Activate ) { + m_springbrakesounds.state = physics->SpringBrake.Activate; if( m_springbrakesounds.state ) { m_springbrakesounds.activate.play( sound_flags::exclusive ); m_springbrakesounds.release.stop(); @@ -468,13 +468,13 @@ void TDynamicObject::renderSpringBrakeSounds() { void TDynamicObject::renderLoadExchangeSounds() { // load exchange - if( MoverParameters->LoadStatus & 1 ) { + if( physics->LoadStatus & 1 ) { m_exchangesounds.unloading.play( sound_flags::exclusive ); } else { m_exchangesounds.unloading.stop(); } - if( MoverParameters->LoadStatus & 2 ) { + if( physics->LoadStatus & 2 ) { m_exchangesounds.loading.play( sound_flags::exclusive ); } else { @@ -486,16 +486,16 @@ void TDynamicObject::renderLoadExchangeSounds() { void TDynamicObject::renderDepartureSignalSounds() { // NBMX sygnal odjazdu - if( MoverParameters->Doors.has_warning ) { - auto const lowvoltagepower { MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable }; + if( physics->Doors.has_warning ) { + auto const lowvoltagepower { physics->Power24vIsAvailable || physics->Power110vIsAvailable }; for( auto &doorspeaker : m_doorspeakers ) { // TBD, TODO: per-location door state triggers? - if( MoverParameters->DepartureSignal + if( physics->DepartureSignal && lowvoltagepower /* - || ( ( MoverParameters->DoorCloseCtrl = control::autonomous ) - && ( ( ( false == MoverParameters->DoorLeftOpened ) && ( dDoorMoveL > 0.0 ) ) - || ( ( false == MoverParameters->DoorRightOpened ) && ( dDoorMoveR > 0.0 ) ) ) ) + || ( ( physics->DoorCloseCtrl = control::autonomous ) + && ( ( ( false == physics->DoorLeftOpened ) && ( dDoorMoveL > 0.0 ) ) + || ( ( false == physics->DoorRightOpened ) && ( dDoorMoveR > 0.0 ) ) ) ) */ ) { // for the autonomous doors play the warning automatically whenever a door is closing @@ -514,7 +514,7 @@ void TDynamicObject::renderAnnouncementSounds() { // announcements { - auto const lowvoltagepower { MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable }; + auto const lowvoltagepower { physics->Power24vIsAvailable || physics->Power110vIsAvailable }; if( lowvoltagepower ) { // system is powered up, can play queued announcements if( false == m_pasystem.announcement_queue.empty() @@ -522,7 +522,7 @@ void TDynamicObject::renderAnnouncementSounds() { // pull first sound from the queue m_pasystem.announcement = m_pasystem.announcement_queue.front(); m_pasystem.announcement.owner( this ); - m_pasystem.announcement.range( 0.5 * MoverParameters->Dim.L * -1 ); + m_pasystem.announcement.range( 0.5 * physics->Dim.L * -1 ); if( m_pasystem.soundproofing ) { if( !m_pasystem.announcement.soundproofing() ) { m_pasystem.announcement.soundproofing() = m_pasystem.soundproofing; @@ -546,12 +546,12 @@ void TDynamicObject::renderDoorSounds() { auto const &sides { VehicleSides }; for( auto const side : sides ) { - auto const &door { MoverParameters->Doors.instances[ side ] }; + auto const &door { physics->Doors.instances[ side ] }; if( true == door.is_opening ) { // door sounds if( false == door.step_unfolding // no wait if no doorstep - || MoverParameters->Doors.step_type == 2 ) { // no wait for rotating doorstep + || physics->Doors.step_type == 2 ) { // no wait for rotating doorstep if( door.position < 0.5f ) { // safety measure, to keep slightly too short sounds from repeating for( auto &doorsounds : m_doorsounds ) { if( doorsounds.placement == side ) { @@ -597,7 +597,7 @@ void TDynamicObject::renderDoorSounds() { } } // door locks - if( MoverParameters->Doors.is_locked != m_doorlocks ) { + if( physics->Doors.is_locked != m_doorlocks ) { // toggle state of the locks... m_doorlocks = !m_doorlocks; // ...and play relevant sounds @@ -619,11 +619,11 @@ void TDynamicObject::renderHornSounds() { { // for moving vehicle combine regular horn activation flag with emergency brake horn activation flag, if the brake is active; // the horns without the air or the voltage they need stay silent - auto const warningsignal { MoverParameters->SoundingHorns( - ( MoverParameters->Vel > 0.5 && MoverParameters->AlarmChainFlag ? - MoverParameters->EmergencyBrakeWarningSignal : + auto const warningsignal { physics->SoundingHorns( + ( physics->Vel > 0.5 && physics->AlarmChainFlag ? + physics->EmergencyBrakeWarningSignal : 0 ) - | MoverParameters->WarningSignal ) }; + | physics->WarningSignal ) }; if( TestFlag( warningsignal, 1 ) ) { sHorn1.play( sound_flags::exclusive | sound_flags::looping ); @@ -672,16 +672,16 @@ void TDynamicObject::renderRunningNoise( double const brakeforceratio ) { // frequency calculation auto const normalizer { ( true == bogiesound.is_combined() ? - MoverParameters->Vmax * 0.01f : + physics->Vmax * 0.01f : 1.f ) }; frequency = bogiesound.m_frequencyoffset - + bogiesound.m_frequencyfactor * MoverParameters->Vel * normalizer; + + bogiesound.m_frequencyfactor * physics->Vel * normalizer; // volume calculation volume = bogiesound.m_amplitudeoffset - + bogiesound.m_amplitudefactor * MoverParameters->Vel; + + bogiesound.m_amplitudefactor * physics->Vel; if( brakeforceratio > 0.0 ) { // hamulce wzmagaja halas volume *= 1 + 0.125 * brakeforceratio; @@ -700,7 +700,7 @@ void TDynamicObject::renderRunningNoise( double const brakeforceratio ) { std::lerp( 0.0, 1.0, std::clamp( - MoverParameters->Vel / 40.0, + physics->Vel / 40.0, 0.0, 1.0 ) ); } switch( MyTrack->eEnvironment ) { @@ -760,13 +760,13 @@ void TDynamicObject::renderRunningNoise( double const brakeforceratio ) { void TDynamicObject::renderWheelFlatSound() { // flat spot sound - if( MoverParameters->CategoryFlag == 1 ) { + if( physics->CategoryFlag == 1 ) { // trains only if( GetVelocity() > 1.0 - && MoverParameters->WheelFlat > 5.0 ) { + && physics->WheelFlat > 5.0 ) { m_wheelflat - .pitch( m_wheelflat.m_frequencyoffset + std::abs( MoverParameters->nrot ) * m_wheelflat.m_frequencyfactor ) - .gain( m_wheelflat.m_amplitudeoffset + m_wheelflat.m_amplitudefactor * ( ( 1.0 + MoverParameters->Vel / MoverParameters->Vmax + std::clamp( MoverParameters->WheelFlat / 60.0, 0.0, 1.0 ) ) / 3.0 ) ) + .pitch( m_wheelflat.m_frequencyoffset + std::abs( physics->nrot ) * m_wheelflat.m_frequencyfactor ) + .gain( m_wheelflat.m_amplitudeoffset + m_wheelflat.m_amplitudefactor * ( ( 1.0 + physics->Vel / physics->Vmax + std::clamp( physics->WheelFlat / 60.0, 0.0, 1.0 ) ) / 3.0 ) ) .play( sound_flags::exclusive | sound_flags::looping ); } else { @@ -781,16 +781,16 @@ void TDynamicObject::renderCurveSound() { auto volume{ 0.0 }; // youBy: dzwiek ostrych lukow i ciasnych zwrotek - if( MoverParameters->Vel > 5.0 + if( physics->Vel > 5.0 && ts.R * ts.R > 1.0 && std::abs(ts.R) < 15000.0 ) { // scale volume with curve radius and vehicle speed volume = - std::abs( MoverParameters->AccN ) // * MoverParameters->AccN + std::abs( physics->AccN ) // * physics->AccN * std::lerp( 0.5, 1.0, std::clamp( - MoverParameters->Vel / 40.0, + physics->Vel / 40.0, 0.0, 1.0 ) ) * ( MyTrack->eType == tt_Switch && std::abs(ts.R) < 1500.0 ? 100.0 : 1.0 ); } @@ -801,7 +801,7 @@ void TDynamicObject::renderCurveSound() { rscurve .pitch( true == rscurve.is_combined() ? - MoverParameters->Vel * 0.01f : + physics->Vel * 0.01f : rscurve.m_frequencyoffset + rscurve.m_frequencyfactor * 1.f ) .gain( 2.5 * volume ) .play( sound_flags::exclusive | sound_flags::looping ); @@ -817,7 +817,7 @@ void TDynamicObject::renderStartJoltSound() { // movement start jolt if( false == m_startjoltplayed ) { auto const velocity { GetVelocity() }; - if( ( MoverParameters->V > 0.0 ? MoverParameters->AccSVBased > 0.1 : MoverParameters->AccSVBased < 0.1 ) + if( ( physics->V > 0.0 ? physics->AccSVBased > 0.1 : physics->AccSVBased < 0.1 ) && velocity > 1.0 && velocity < 15.0 ) { m_startjolt.play( sound_flags::exclusive ); @@ -826,20 +826,20 @@ void TDynamicObject::renderStartJoltSound() { } } -// the sounds of the pneumatic relay and of the door permit, set in the sound flags of the mover -void TDynamicObject::renderMoverEventSounds() { +// the sounds of the pneumatic relay and of the door permit, set in the sound flags of the physics +void TDynamicObject::renderPhysicsEventSounds() { // pneumatic relay - if( TestFlag( MoverParameters->SoundFlag, sound::pneumatic ) ) { + if( TestFlag( physics->SoundFlag, sound::pneumatic ) ) { dsbPneumaticRelay .gain( - true == TestFlag( MoverParameters->SoundFlag, sound::loud ) ? + true == TestFlag( physics->SoundFlag, sound::loud ) ? 1.0f : 0.8f ) .play(); } // door permit - if( TestFlag( MoverParameters->SoundFlag, sound::doorpermit ) ) { + if( TestFlag( physics->SoundFlag, sound::doorpermit ) ) { // NOTE: current implementation doesn't discern between permit for left/right side, // which may be undesired in weird setups with doors only on one side // TBD, TODO: rework into dedicated sound event flag for each door location instance? @@ -856,7 +856,7 @@ void TDynamicObject::renderCouplerSounds() { int couplerindex { 0 }; for( auto &couplersounds : m_couplersounds ) { - auto &coupler { MoverParameters->Couplers[ couplerindex ] }; + auto &coupler { physics->Couplers[ couplerindex ] }; if( coupler.sounds == sound::none ) { ++couplerindex; @@ -972,7 +972,7 @@ void TDynamicObject::renderDerailmentSounds() { // physics.derailment new: off the track the vehicle scrapes along the ground until it stops, or until it is put back // on the rails (rerail()) while still sliding - if( MoverParameters->OffTrack.active() && false == MoverParameters->OffTrack.at_rest() ) { + if( physics->OffTrack.active() && false == physics->OffTrack.at_rest() ) { if( false == rsDerailment.is_playing() ) { rsDerailment.play( sound_flags::exclusive | sound_flags::looping ); } @@ -983,13 +983,13 @@ void TDynamicObject::renderDerailmentSounds() { } // special events - if( MoverParameters->EventFlag ) { + if( physics->EventFlag ) { // McZapkie: w razie wykolejenia - if( true == MoverParameters->DamageFlag.HasAll(VehicleDamage::derailed) ) { + if( true == physics->DamageFlag.HasAll(VehicleDamage::derailed) ) { rsDerailment.play( sound_flags::exclusive ); } - MoverParameters->EventFlag = false; + physics->EventFlag = false; } } @@ -997,8 +997,8 @@ void TDynamicObject::play_mirror_sounds( VehicleSide const Side, mirror_moves::e if( Event == mirror_moves::event::none ) { return; } // as UpdateMirror(), only the mirrors of the occupied cab move - if( MoverParameters->CabOccupied == 0 ) { return; } - auto const cabend { MoverParameters->CabOccupied > 0 ? VehicleEnd::front : VehicleEnd::rear }; + if( physics->CabOccupied == 0 ) { return; } + auto const cabend { physics->CabOccupied > 0 ? VehicleEnd::front : VehicleEnd::rear }; for( auto &mirror : m_mirrorsounds ) { if( mirror.placement != Side || mirror.end != cabend ) { continue; } auto &sound { Event == mirror_moves::event::unfolding ? mirror.unfold : mirror.fold }; @@ -1026,7 +1026,7 @@ TDynamicObject::powertrain_sounds::position( glm::vec3 const Location ) { } void -TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, double const Deltatime ) { +TDynamicObject::powertrain_sounds::render( physics::Vehicle const &Vehicle, double const Deltatime ) { if( Vehicle.Power == 0 ) { return; } @@ -1046,7 +1046,7 @@ TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, doub // the sounds of the oil, fuel and water pumps and of the water heater void -TDynamicObject::powertrain_sounds::renderPumpSounds( TMoverParameters const &Vehicle ) { +TDynamicObject::powertrain_sounds::renderPumpSounds( physics::Vehicle const &Vehicle ) { // oil pump if( true == Vehicle.OilPump.is_active ) { @@ -1092,7 +1092,7 @@ TDynamicObject::powertrain_sounds::renderPumpSounds( TMoverParameters const &Veh // the sounds of the engine and the main circuit being switched on or off void -TDynamicObject::powertrain_sounds::renderIgnitionSounds( TMoverParameters const &Vehicle ) { +TDynamicObject::powertrain_sounds::renderIgnitionSounds( physics::Vehicle const &Vehicle ) { // engine sounds // ignition @@ -1130,7 +1130,7 @@ TDynamicObject::powertrain_sounds::renderIgnitionSounds( TMoverParameters const // the sounds of the running engine, of its revving and of the fake engine, and the smoothed engine volume void -TDynamicObject::powertrain_sounds::renderEngineSounds( TMoverParameters const &Vehicle, double const Deltatime ) { +TDynamicObject::powertrain_sounds::renderEngineSounds( physics::Vehicle const &Vehicle, double const Deltatime ) { double frequency { 1.0 }; double volume { 0.0 }; @@ -1258,7 +1258,7 @@ TDynamicObject::powertrain_sounds::renderEngineSounds( TMoverParameters const &V // the sound of the turbocharger void -TDynamicObject::powertrain_sounds::renderTurboSound( TMoverParameters const &Vehicle, double const Deltatime ) { +TDynamicObject::powertrain_sounds::renderTurboSound( physics::Vehicle const &Vehicle, double const Deltatime ) { double volume { 0.0 }; @@ -1293,7 +1293,7 @@ TDynamicObject::powertrain_sounds::renderTurboSound( TMoverParameters const &Veh // the sound of the slipping clutch void -TDynamicObject::powertrain_sounds::renderClutchSound( TMoverParameters const &Vehicle ) { +TDynamicObject::powertrain_sounds::renderClutchSound( physics::Vehicle const &Vehicle ) { double frequency { 1.0 }; double volume { 0.0 }; @@ -1304,7 +1304,7 @@ TDynamicObject::powertrain_sounds::renderClutchSound( TMoverParameters const &Ve volume = rsEngageSlippery.m_amplitudeoffset + rsEngageSlippery.m_amplitudefactor * Vehicle.diesel.clutchPressure; } else { - frequency = 1.f; // rsEngageSlippery.FA+0.7*rsEngageSlippery.FM*(fabs(mvControlled->enrot)+mvControlled->nmax); + frequency = 1.f; // rsEngageSlippery.FA+0.7*rsEngageSlippery.FM*(fabs(controlled->enrot)+controlled->nmax); volume = Vehicle.diesel.clutchPressure > 0.2 ? rsEngageSlippery.m_amplitudeoffset + 0.2 * rsEngageSlippery.m_amplitudefactor * (Vehicle.enrot / Vehicle.nmax) : 0.f; } @@ -1320,7 +1320,7 @@ TDynamicObject::powertrain_sounds::renderClutchSound( TMoverParameters const &Ve // the sound of the retarder void -TDynamicObject::powertrain_sounds::renderRetarderSound( TMoverParameters const &Vehicle ) { +TDynamicObject::powertrain_sounds::renderRetarderSound( physics::Vehicle const &Vehicle ) { if (Vehicle.retarder.present) { float speed = std::abs(Vehicle.retarder.revolutions); @@ -1340,7 +1340,7 @@ TDynamicObject::powertrain_sounds::renderRetarderSound( TMoverParameters const & // the sounds of the traction motors, the generic ones and the inverter-specific ones void -TDynamicObject::powertrain_sounds::renderTractionMotorSounds( TMoverParameters const &Vehicle, double const Deltatime ) { +TDynamicObject::powertrain_sounds::renderTractionMotorSounds( physics::Vehicle const &Vehicle, double const Deltatime ) { double frequency { 1.0 }; double volume { 0.0 }; @@ -1461,7 +1461,7 @@ TDynamicObject::powertrain_sounds::renderTractionMotorSounds( TMoverParameters c // the sounds of the motor blowers, each matched with the blower at its end of the vehicle void -TDynamicObject::powertrain_sounds::renderMotorBlowerSounds( TMoverParameters const &Vehicle ) { +TDynamicObject::powertrain_sounds::renderMotorBlowerSounds( physics::Vehicle const &Vehicle ) { // motor blowers if( false == motorblowers.empty() ) { @@ -1489,7 +1489,7 @@ TDynamicObject::powertrain_sounds::renderMotorBlowerSounds( TMoverParameters con // the sound of the inverter void -TDynamicObject::powertrain_sounds::renderInverterSound( TMoverParameters const &Vehicle ) { +TDynamicObject::powertrain_sounds::renderInverterSound( physics::Vehicle const &Vehicle ) { double volume { 0.0 }; @@ -1512,7 +1512,7 @@ TDynamicObject::powertrain_sounds::renderInverterSound( TMoverParameters const & // the sounds of the ventilator and of the radiator fans void -TDynamicObject::powertrain_sounds::renderFanSounds( TMoverParameters const &Vehicle ) { +TDynamicObject::powertrain_sounds::renderFanSounds( physics::Vehicle const &Vehicle ) { // ventillator sounds if( Vehicle.RventRot > 0.1 ) { @@ -1558,7 +1558,7 @@ TDynamicObject::powertrain_sounds::renderFanSounds( TMoverParameters const &Vehi // the sounds of the relays, set in the sound flags of the vehicle void -TDynamicObject::powertrain_sounds::renderRelaySounds( TMoverParameters const &Vehicle ) { +TDynamicObject::powertrain_sounds::renderRelaySounds( physics::Vehicle const &Vehicle ) { // relay sounds auto const soundflags { Vehicle.SoundFlag }; @@ -1608,7 +1608,7 @@ TDynamicObject::powertrain_sounds::renderRelaySounds( TMoverParameters const &Ve // the sound of the transmission void -TDynamicObject::powertrain_sounds::renderTransmissionSound( TMoverParameters const &Vehicle ) { +TDynamicObject::powertrain_sounds::renderTransmissionSound( physics::Vehicle const &Vehicle ) { if( Vehicle.Vel > 0.1 ) { transmission diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index ec942b9a7..7a3dee1b7 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/DynObj.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/lightsprogrammer.h" #include "simulation/simulation.h" #include "simulation/blackboxrecorder.h" @@ -83,7 +83,7 @@ bool TDynamicObject::Update(double dt, double dt1) vehicle->m_offtrackupdatedue -= frame; if( took > off_track_slow && vehicle->m_offtrackupdatedue <= 0.0 ) { vehicle->m_offtrackupdatedue = 1.0; - ErrorLog( std::format( "derailment: warning: the update of {} off the track took {:.0f} ms in a frame of {:.3f} s", vehicle->MoverParameters->Name, took * 1000.0, frame ) ); + ErrorLog( std::format( "derailment: warning: the update of {} off the track took {:.0f} ms in a frame of {:.3f} s", vehicle->physics->Name, took * 1000.0, frame ) ); } } private: @@ -91,17 +91,17 @@ bool TDynamicObject::Update(double dt, double dt1) double frame; off_track_clock::time_point started {}; }; - off_track_watch const watch { MoverParameters->OffTrack.active() ? this : nullptr, dt1 }; - if( m_offtrackterrain != nullptr && false == MoverParameters->OffTrack.active() ) { + off_track_watch const watch { physics->OffTrack.active() ? this : nullptr, dt1 }; + if( m_offtrackterrain != nullptr && false == physics->OffTrack.active() ) { // physics.derailment new: back on the rails (rerail()), the terrain it slid over is let go m_offtrackterrain.reset(); m_offtracksite.terrain( nullptr ); } - if (!MoverParameters->PhysicActivation && + if (!physics->PhysicActivation && !MechInside) { // to drugie, bo będąc w maszynowym blokuje się fizyka // physics.derailment new: a vehicle off the track stopped along its heading still settles: it slides down a // slope, falls over, or comes to rest after the step its physics stopped in - if( MoverParameters->OffTrack.active() && false == MoverParameters->OffTrack.at_rest() && bEnabled ) { + if( physics->OffTrack.active() && false == physics->OffTrack.at_rest() && bEnabled ) { m_offtracktime = dt1; Move( 0.0 ); update_off_track( dt1 ); @@ -139,20 +139,20 @@ bool TDynamicObject::Update(double dt, double dt1) updateAxleClatter( dDOMoveLen ); // fragment z EXE Kursa - /* if (MoverParameters->TrainType==train_type::et42) + /* if (physics->TrainType==train_type::et42) { - if ((MoverParameters->DynamicBrakeType=dbrake_switch) && - ((MoverParameters->BrakePress > - 0.2) || ( MoverParameters->PipePress < 0.36 ))) + if ((physics->DynamicBrakeType=dbrake_switch) && + ((physics->BrakePress > + 0.2) || ( physics->PipePress < 0.36 ))) { - MoverParameters->StLinFlag=true; + physics->StLinFlag=true; } else - if ((MoverParameters->DynamicBrakeType=dbrake_switch) && - (MoverParameters->BrakePress < + if ((physics->DynamicBrakeType=dbrake_switch) && + (physics->BrakePress < 0.1)) { - MoverParameters->StLinFlag=false; + physics->StLinFlag=false; } } */ @@ -164,19 +164,19 @@ bool TDynamicObject::Update(double dt, double 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 - if( ctOwner != nullptr ? SectionLightsActive != MoverParameters->CompartmentLights.is_active : - Mechanik != nullptr ? SectionLightsActive != MoverParameters->CompartmentLights.is_active : + if( ctOwner != nullptr ? SectionLightsActive != physics->CompartmentLights.is_active : + Mechanik != nullptr ? SectionLightsActive != physics->CompartmentLights.is_active : SectionLightsActive ) { // without controller switch the lights off toggle_lights(); } - if (MoverParameters->InactiveCabPantsCheck) + if (physics->InactiveCabPantsCheck) { pants_up(); - MoverParameters->InactiveCabPantsCheck = false; + physics->InactiveCabPantsCheck = false; } - if( MoverParameters->LoadStatus ) { + if( physics->LoadStatus ) { LoadUpdate(); // zmiana modelu ładunku } update_exchange( dt ); @@ -202,7 +202,7 @@ void TDynamicObject::updateTrackParameters() if( ts.R != 0.0 ) { // sin(0) results in division by zero - ts.R = -0.5 * MoverParameters->BDist / sin( ts.R * 0.5 ); + ts.R = -0.5 * physics->BDist / sin( ts.R * 0.5 ); } } } @@ -211,7 +211,7 @@ void TDynamicObject::updateTrackParameters() // ts.R=ComputeRadius(Axle1.pPosition,Axle2.pPosition,Axle3.pPosition,Axle0.pPosition); // Ra: składową pochylenia wzdłużnego mamy policzoną w jednostkowym wektorze // vFront - ts.Len = 1.0; // std::max(MoverParameters->BDist,MoverParameters->ADist); + ts.Len = 1.0; // std::max(physics->BDist,physics->ADist); ts.dHtrack = -vFront.y; // Axle1.pPosition.y-Axle0.pPosition.y; //wektor // między skrajnymi osiami // (!!!odwrotny) @@ -220,7 +220,7 @@ void TDynamicObject::updateTrackParameters() ts.uneven_curvature = glm::dot( 0.5 * ( Axle0.UnevenBend() + Axle1.UnevenBend() ), vLeft ); ts.uneven_cross = MyTrack->uneven_underway().cross; // a buckle of the track under the body: the mean of the curvatures at the outer axles, each over the wheelbase of its bogie - ts.buckle_curvature = 0.5 * ( Axle0.BuckleCurvature( MoverParameters->ADist ) + Axle1.BuckleCurvature( MoverParameters->ADist ) ); + ts.buckle_curvature = 0.5 * ( Axle0.BuckleCurvature( physics->ADist ) + Axle1.BuckleCurvature( physics->ADist ) ); // TTrackParam tp; tp.Width = MyTrack->fTrackWidth; // McZapkie-250202 @@ -235,19 +235,19 @@ void TDynamicObject::updateTrackParameters() void TDynamicObject::updateCouplingState() { // couplers - if( MoverParameters->Couplers[0].CouplingFlag != Coupling::none - && MoverParameters->Couplers[1].CouplingFlag != Coupling::none ) { - MoverParameters->InsideConsist = true; + if( physics->Couplers[0].CouplingFlag != Coupling::none + && physics->Couplers[1].CouplingFlag != Coupling::none ) { + physics->InsideConsist = true; } else { - MoverParameters->InsideConsist = false; + physics->InsideConsist = false; } - if( TestFlag( MoverParameters->AIFlag, sound::attachcoupler ) ) { + if( TestFlag( physics->AIFlag, sound::attachcoupler ) ) { auto *driver{ ctOwner ? ctOwner : Mechanik }; if( driver != nullptr ) { driver->CheckVehicles( DriverOrder::connect ); } - ClearFlag( MoverParameters->AIFlag, sound::attachcoupler ); + ClearFlag( physics->AIFlag, sound::attachcoupler ); } } @@ -255,9 +255,9 @@ void TDynamicObject::updateCouplingState() void TDynamicObject::updateTractionVoltage( double const dt1 ) { // napiecie sieci trakcyjnej - if (MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) { // dla EZT tylko silnikowy + if (physics->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) { // dla EZT tylko silnikowy - tmpTraction.TractionVoltage = std::max( std::abs( MoverParameters->PantRearVolt ), std::abs( MoverParameters->PantFrontVolt ) ); + tmpTraction.TractionVoltage = std::max( std::abs( physics->PantRearVolt ), std::abs( physics->PantFrontVolt ) ); // jeśli brak zasilania dłużej niż 0.2 sekundy (25km/h pod izolatorem daje 0.15s) // Ra 2F1H: prowizorka, trzeba przechować napięcie, żeby nie wywalało WS pod izolatorem if( tmpTraction.TractionVoltage > 0.0) { @@ -266,20 +266,20 @@ void TDynamicObject::updateTractionVoltage( double const dt1 ) else { NoVoltTime += dt1; if( NoVoltTime <= 0.2 ) { - tmpTraction.TractionVoltage = MoverParameters->PantographVoltage; + tmpTraction.TractionVoltage = physics->PantographVoltage; } else { // jeśli jedzie - if( MoverParameters->Vel > 0.5 ) { + if( physics->Vel > 0.5 ) { // Ra 2014-07: doraźna blokada logowania zimnych lokomotyw - zrobić to trzeba inaczej - if( MoverParameters->Pantographs[VehicleEnd::front].is_active - || MoverParameters->Pantographs[VehicleEnd::rear].is_active ) { - if( MoverParameters->Mains // Ra 15-01: logować tylko, jeśli WS załączony - && MoverParameters->GetTrainsetHighVoltage() < 0.1f // yB 16-03: i nie jest to asynchron zasilany z daleka - && false == MoverParameters->GensetSelected() ) { // nor a dual-mode vehicle running on its genset + if( physics->Pantographs[VehicleEnd::front].is_active + || physics->Pantographs[VehicleEnd::rear].is_active ) { + if( physics->Mains // Ra 15-01: logować tylko, jeśli WS załączony + && physics->GetTrainsetHighVoltage() < 0.1f // yB 16-03: i nie jest to asynchron zasilany z daleka + && false == physics->GensetSelected() ) { // nor a dual-mode vehicle running on its genset // Ra 15-01: bezwzględne współrzędne pantografu nie są dostępne więc lepiej się tego nie zaloguje ErrorLog( - "Bad traction: " + MoverParameters->Name + "Bad traction: " + physics->Name + " lost power for " + to_string( NoVoltTime, 2 ) + " sec. at " + to_string(vPosition) ); } @@ -289,33 +289,33 @@ void TDynamicObject::updateTractionVoltage( double const dt1 ) } } else { - tmpTraction.TractionVoltage = 0.95 * MoverParameters->EnginePowerSource.MaxVoltage; + tmpTraction.TractionVoltage = 0.95 * physics->EnginePowerSource.MaxVoltage; } tmpTraction.TractionFreq = 0; tmpTraction.TractionMaxCurrent = 7500; // Ra: chyba za dużo? powinno wywalać przy 1500 tmpTraction.TractionResistivity = 0.3; - MoverParameters->PantographVoltage = tmpTraction.TractionVoltage; + physics->PantographVoltage = tmpTraction.TractionVoltage; } // the driver of the vehicle: the integrated controller, the brakes blended over a consist with induction motors, the AI void TDynamicObject::updateDriver( double const dt1 ) { if( Mechanik->primary() ) { - MoverParameters->EqvtPipePress = GetEPP(); // srednie cisnienie w PG + physics->EqvtPipePress = GetEPP(); // srednie cisnienie w PG } if (Mechanik->primary() && - (MoverParameters->EngineType == TEngineType::DieselEngine || - MoverParameters->EngineType == TEngineType::DieselElectric) - && MoverParameters->EIMCtrlType > 0) { - MoverParameters->CheckEIMIC(dt1); - if (MoverParameters->SpeedCtrl) - MoverParameters->CheckSpeedCtrl(dt1); - MoverParameters->eimic_real = std::min(MoverParameters->eimic,MoverParameters->eimicSpeedCtrl); - MoverParameters->SendCtrlToNext(VehicleCommand::integratedController, MoverParameters->eimic_real, MoverParameters->CabActive); + (physics->EngineType == TEngineType::DieselEngine || + physics->EngineType == TEngineType::DieselElectric) + && physics->EIMCtrlType > 0) { + physics->CheckEIMIC(dt1); + if (physics->SpeedCtrl) + physics->CheckSpeedCtrl(dt1); + physics->eimic_real = std::min(physics->eimic,physics->eimicSpeedCtrl); + physics->SendCtrlToNext(VehicleCommand::integratedController, physics->eimic_real, physics->CabActive); } if( Mechanik->primary() - && MoverParameters->EngineType == TEngineType::ElectricInductionMotor ) { + && physics->EngineType == TEngineType::ElectricInductionMotor ) { // jesli glowny i z asynchronami, to niech steruje hamulcem i napedem lacznie dla calego pociagu/ezt distributeInductionBraking( dt1 ); } @@ -351,7 +351,7 @@ struct TDynamicObject::InductionBrakeState { void TDynamicObject::distributeInductionBraking( double const dt1 ) { InductionBrakeState state; - state.kier = DirectionGet() * MoverParameters->CabOccupied > 0; + state.kier = DirectionGet() * physics->CabOccupied > 0; setInductionControl( state, dt1 ); sumConsistBrakeForces( state ); computeBrakeDeceleration( state ); @@ -369,23 +369,23 @@ void TDynamicObject::distributeInductionBraking( double const dt1 ) void TDynamicObject::setInductionControl( InductionBrakeState &state, double const dt1 ) { // 0a. ustal aktualna nastawe zadania sily napedowej i hamowania - if( MoverParameters->Power < 1 + if( physics->Power < 1 && ctOwner != nullptr ) { - MoverParameters->MainCtrlPos = ctOwner->Controlling()->MainCtrlPos*MoverParameters->MainCtrlPosNo / std::max(1, ctOwner->Controlling()->MainCtrlPosNo); - MoverParameters->SpeedCtrlValue = ctOwner->Controlling()->SpeedCtrlValue; - MoverParameters->SpeedCtrlUnit.IsActive = ctOwner->Controlling()->SpeedCtrlUnit.IsActive; + physics->MainCtrlPos = ctOwner->Controlling()->MainCtrlPos*physics->MainCtrlPosNo / std::max(1, ctOwner->Controlling()->MainCtrlPosNo); + physics->SpeedCtrlValue = ctOwner->Controlling()->SpeedCtrlValue; + physics->SpeedCtrlUnit.IsActive = ctOwner->Controlling()->SpeedCtrlUnit.IsActive; } - MoverParameters->CheckEIMIC(dt1); - MoverParameters->CheckSpeedCtrl(dt1); + physics->CheckEIMIC(dt1); + physics->CheckSpeedCtrl(dt1); - state.eimic = std::min(MoverParameters->eimic, MoverParameters->eimicSpeedCtrl); - MoverParameters->eimic_real = state.eimic; + state.eimic = std::min(physics->eimic, physics->eimicSpeedCtrl); + physics->eimic_real = state.eimic; // Elf: full braking at once in the lowest position, and in the emergency brake position below it - if (MoverParameters->EIMCtrlType == 2 && MoverParameters->MainCtrlPos <= MoverParameters->EIMCtrlEmergencyPositions()) + if (physics->EIMCtrlType == 2 && physics->MainCtrlPos <= physics->EIMCtrlEmergencyPositions()) state.eimic = -1.0; - MoverParameters->SendCtrlToNext(VehicleCommand::integratedController, std::max(0., state.eimic), MoverParameters->CabActive); + physics->SendCtrlToNext(VehicleCommand::integratedController, std::max(0., state.eimic), physics->CabActive); state.LBR = std::max(-state.eimic, 0.); - state.eim_lb = Mechanik->AIControllFlag || !MoverParameters->LocHandleTimeTraxx ? 0 : MoverParameters->eim_localbrake; + state.eim_lb = Mechanik->AIControllFlag || !physics->LocHandleTimeTraxx ? 0 : physics->eim_localbrake; } // steps 1-2 of the blending: the masses and the most braking forces, pneumatic and ED, summed over the consist @@ -401,39 +401,39 @@ void TDynamicObject::sumConsistBrakeForces( InductionBrakeState &state ) // 2. ustal mozliwa do realizacji sile hamowania ED // - w szczegolnosci powinien brac pod uwage rozne sily hamowania - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; + for (TDynamicObject *p = GetFirstDynamic(physics->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; state.kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) { ++state.np; state.masamax += - p->MoverParameters->MBPM - + ( p->MoverParameters->MBPM > 1.0 ? + p->physics->MBPM + + ( p->physics->MBPM > 1.0 ? 0.0 : - p->MoverParameters->Mass ) - + p->MoverParameters->Mred; - auto const Nmax = ((p->MoverParameters->P2FTrans * p->MoverParameters->MaxBrakePress[0] - - p->MoverParameters->BrakeCylSpring) * - p->MoverParameters->BrakeCylMult[0] - - p->MoverParameters->BrakeSlckAdj) * - p->MoverParameters->BrakeCylNo * p->MoverParameters->BrakeRigEff; - state.FmaxPN += Nmax * p->MoverParameters->Hamulec->GetFC( - Nmax / (p->MoverParameters->NAxles * p->MoverParameters->NBpA), - p->MoverParameters->MED_Vref) * + p->physics->Mass ) + + p->physics->Mred; + auto const Nmax = ((p->physics->P2FTrans * p->physics->MaxBrakePress[0] - + p->physics->BrakeCylSpring) * + p->physics->BrakeCylMult[0] - + p->physics->BrakeSlckAdj) * + p->physics->BrakeCylNo * p->physics->BrakeRigEff; + state.FmaxPN += Nmax * p->physics->Hamulec->GetFC( + Nmax / (p->physics->NAxles * p->physics->NBpA), + p->physics->MED_Vref) * 1000; // sila hamowania pn - state.FmaxED += p->MoverParameters->Mains && p->MoverParameters->DirActive != 0 && p->MoverParameters->inductionMotor.inverterRatio == 1.0 && - p->MoverParameters->inductionMotor.braking.maxForce * p->MoverParameters->NPoweredAxles > 0 ? - p->MoverParameters->inductionMotor.braking.maxForce * 1000 : + state.FmaxED += p->physics->Mains && p->physics->DirActive != 0 && p->physics->inductionMotor.inverterRatio == 1.0 && + p->physics->inductionMotor.braking.maxForce * p->physics->NPoweredAxles > 0 ? + p->physics->inductionMotor.braking.maxForce * 1000 : 0; // chwilowy max ED -> do rozdzialu sil - FED -= std::min(p->MoverParameters->inductionMotor.state.maxForce, 0.0) * + FED -= std::min(p->physics->inductionMotor.state.maxForce, 0.0) * 1000; // chwilowy max ED -> do rozdzialu sil - state.FfulED = std::min(p->MoverParameters->inductionMotor.state.fullForce, 0.0) * + state.FfulED = std::min(p->physics->inductionMotor.state.fullForce, 0.0) * 1000; // chwilowy max ED -> do rozdzialu sil - state.FrED -= std::min(p->MoverParameters->inductionMotor.state.maxForce, 0.0) * + state.FrED -= std::min(p->physics->inductionMotor.state.maxForce, 0.0) * 1000; // chwilowo realizowane ED -> do pneumatyki - Frj += std::max(p->MoverParameters->inductionMotor.state.maxForce, 0.0) * + Frj += std::max(p->physics->inductionMotor.state.maxForce, 0.0) * 1000;// chwilowo realizowany napęd -> do utrzymującego - state.masa += p->MoverParameters->TotalMass; - state.osie += p->MoverParameters->NAxles; + state.masa += p->physics->TotalMass; + state.osie += p->physics->NAxles; } } @@ -441,11 +441,11 @@ void TDynamicObject::sumConsistBrakeForces( InductionBrakeState &state ) void TDynamicObject::computeBrakeDeceleration( InductionBrakeState &state ) { double RapidMult = 1.0; - if ((MoverParameters->BrakeDelays & bdelay_P + bdelay_R) == bdelay_P + bdelay_R - && MoverParameters->BrakeDelayFlag & bdelay_P) - RapidMult = MoverParameters->RapidMult; + if ((physics->BrakeDelays & bdelay_P + bdelay_R) == bdelay_P + bdelay_R + && physics->BrakeDelayFlag & bdelay_P) + RapidMult = physics->RapidMult; - state.amax = RapidMult * std::min(state.FmaxPN / state.masamax, MoverParameters->MED_amax); + state.amax = RapidMult * std::min(state.FmaxPN / state.masamax, physics->MED_amax); Mechanik->fMedAmax = state.amax; } @@ -454,26 +454,26 @@ void TDynamicObject::computeBrakeDeceleration( InductionBrakeState &state ) void TDynamicObject::updateShuntMode( InductionBrakeState &state ) { state.doorisopen = - false == MoverParameters->Doors.instances[VehicleSide::left].is_closed - || false == MoverParameters->Doors.instances[VehicleSide::right].is_closed - || ( MoverParameters->Doors.permit_needed - && ( MoverParameters->Doors.instances[ VehicleSide::left ].open_permit - || MoverParameters->Doors.instances[ VehicleSide::right ].open_permit ) ); - state.doorisopen &= !(MoverParameters->ReleaseParkingBySpringBrakeWhenDoorIsOpen && MoverParameters->SpringBrake.IsActive); + false == physics->Doors.instances[VehicleSide::left].is_closed + || false == physics->Doors.instances[VehicleSide::right].is_closed + || ( physics->Doors.permit_needed + && ( physics->Doors.instances[ VehicleSide::left ].open_permit + || physics->Doors.instances[ VehicleSide::right ].open_permit ) ); + state.doorisopen &= !(physics->ReleaseParkingBySpringBrakeWhenDoorIsOpen && physics->SpringBrake.IsActive); - if (MoverParameters->Vel < 0.5 && (state.eimic < 0 || state.doorisopen || MoverParameters->Hamulec->GetEDBCP())) + if (physics->Vel < 0.5 && (state.eimic < 0 || state.doorisopen || physics->Hamulec->GetEDBCP())) { - MoverParameters->ShuntMode = true; + physics->ShuntMode = true; } - if (MoverParameters->ShuntMode) + if (physics->ShuntMode) { - MoverParameters->ShuntModeAllow = false == state.doorisopen && + physics->ShuntModeAllow = false == state.doorisopen && state.LBR < 0.01; } - if( MoverParameters->Vel > 1 && false == state.doorisopen ) + if( physics->Vel > 1 && false == state.doorisopen ) { - MoverParameters->ShuntMode = false; - MoverParameters->ShuntModeAllow = MoverParameters->BrakePress > 0.2 && + physics->ShuntMode = false; + physics->ShuntModeAllow = physics->BrakePress > 0.2 && state.LBR < 0.01; } } @@ -481,21 +481,21 @@ void TDynamicObject::updateShuntMode( InductionBrakeState &state ) void TDynamicObject::computeBrakeDemand( InductionBrakeState &state, double const dt1 ) { state.Fzad = state.amax * state.LBR * state.masa; - if ((MoverParameters->BrakeCtrlPos == MoverParameters->Handle->GetPos(bh_EB) - && MoverParameters->inductionMotor.braking.cylinderPressureGain < 0.001) || - MoverParameters->EmergencyValveFlow > 0) + if ((physics->BrakeCtrlPos == physics->Handle->GetPos(bh_EB) + && physics->inductionMotor.braking.cylinderPressureGain < 0.001) || + physics->EmergencyValveFlow > 0) state.Fzad = state.amax * state.masa; //pętla bezpieczeństwa - pełne służbowe - if (MoverParameters->ScndS && - MoverParameters->Vel > MoverParameters->inductionMotor.braking.fullSpeed && state.FmaxED > 0) + if (physics->ScndS && + physics->Vel > physics->inductionMotor.braking.fullSpeed && state.FmaxED > 0) { state.Fzad = std::min(state.LBR * state.FmaxED, state.FfulED); } // the holding brake lets go once power has been demanded for its delay (SBDReleaseDelay, none by default) - auto const holdingbrakereleased { MoverParameters->UpdateStopBrakeRelease( state.eimic, dt1 ) }; - if (MoverParameters->ShuntMode && false == holdingbrakereleased || state.doorisopen /*|| - (MoverParameters->V * MoverParameters->DirAbsolute < -0.2)*/) + auto const holdingbrakereleased { physics->UpdateStopBrakeRelease( state.eimic, dt1 ) }; + if (physics->ShuntMode && false == holdingbrakereleased || state.doorisopen /*|| + (physics->V * physics->DirAbsolute < -0.2)*/) { - auto const sbd { ( MoverParameters->SpringBrake.IsActive && MoverParameters->ReleaseParkingBySpringBrake ? 0.0 : MoverParameters->StopBrakeDecc ) }; + auto const sbd { ( physics->SpringBrake.IsActive && physics->ReleaseParkingBySpringBrake ? 0.0 : physics->StopBrakeDecc ) }; state.Fzad = std::max( state.Fzad, sbd * state.masa ); } } @@ -503,10 +503,10 @@ void TDynamicObject::computeBrakeDemand( InductionBrakeState &state, double cons // the log of the braking of the consist opened, once it brakes while moving void TDynamicObject::openMedLog( InductionBrakeState const &state ) { - if (state.Fzad > 1 && !MEDLogFile.is_open() && MoverParameters->Vel > 1) + if (state.Fzad > 1 && !MEDLogFile.is_open() && physics->Vel > 1) { MEDLogFile.open( - "MEDLOGS/" + MoverParameters->Name + "_" + std::to_string( ++MEDLogCount ) + ".csv", + "MEDLOGS/" + physics->Name + "_" + std::to_string( ++MEDLogCount ) + ".csv", std::ios::in | std::ios::out | std::ios::trunc ); MEDLogFile << "t\tVel\tMasa\tOsie\tFmaxPN\tFmaxED\tFfulED\tFrED\tFzad\tFzadED\tFzadPN"; for(int k=1;k<=state.np;k++) @@ -524,23 +524,23 @@ void TDynamicObject::openMedLog( InductionBrakeState const &state ) void TDynamicObject::computeElectrodynamicDemand( InductionBrakeState &state, double const dt1 ) { state.FzadED = 0.0; - if( state.LBR > MoverParameters->MED_MinBrakeReqED - && ( MoverParameters->BrakeHandle == TBrakeHandle::MHZ_EN57 ? - (MoverParameters->BrakeOpModeFlag & bom_MED) != 0 : - MoverParameters->EpFuse ) ) { + if( state.LBR > physics->MED_MinBrakeReqED + && ( physics->BrakeHandle == TBrakeHandle::MHZ_EN57 ? + (physics->BrakeOpModeFlag & bom_MED) != 0 : + physics->EpFuse ) ) { state.FzadED = std::min( state.Fzad, state.FmaxED ); } /*/ELF - wdrazanie ED po powrocie na utrzymanie hamowania - do usuniecia - if (MoverParameters->EIMCtrlType == 2 && MoverParameters->MainCtrlPos < 2 && MoverParameters->eimic > -0.999) + if (physics->EIMCtrlType == 2 && physics->MainCtrlPos < 2 && physics->eimic > -0.999) { FzadED = std::min(FzadED, MED_oldFED); } //*/ //opoznienie wdrazania ED if (state.FzadED > MED_oldFED) { - if (MoverParameters->MED_ED_DelayTimer <= 0) { - MoverParameters->MED_ED_DelayTimer += dt1; - if (MoverParameters->MED_ED_DelayTimer > 0) { + if (physics->MED_ED_DelayTimer <= 0) { + physics->MED_ED_DelayTimer += dt1; + if (physics->MED_ED_DelayTimer > 0) { } else { @@ -550,13 +550,13 @@ void TDynamicObject::computeElectrodynamicDemand( InductionBrakeState &state, do else { state.FzadED = std::min(state.FzadED, MED_oldFED); - MoverParameters->MED_ED_DelayTimer = state.FrED > 0 ? -MoverParameters->MED_ED_Delay2 : -MoverParameters->MED_ED_Delay1; + physics->MED_ED_DelayTimer = state.FrED > 0 ? -physics->MED_ED_Delay2 : -physics->MED_ED_Delay1; } } - if (MoverParameters->BrakeCtrlPos == MoverParameters->Handle->GetPos(bh_EB) - && MoverParameters->inductionMotor.braking.cylinderPressureGain < 0.001) + if (physics->BrakeCtrlPos == physics->Handle->GetPos(bh_EB) + && physics->inductionMotor.braking.cylinderPressureGain < 0.001) state.FzadED = 0; //pętla bezpieczeństwa - bez ED - state.FzadPN = state.Fzad - state.FrED * MoverParameters->MED_FrED_factor; + state.FzadPN = state.Fzad - state.FrED * physics->MED_FrED_factor; } // steps 3-6 of the blending: the ED and the pneumatic braking forces set to the vehicles of the consist void TDynamicObject::distributeBrakeForces( InductionBrakeState &state, double const dt1 ) @@ -577,49 +577,49 @@ void TDynamicObject::distributeBrakeForces( InductionBrakeState &state, double c // 6. ustaw pojazdom sile hamowania ep // - proporcjonalnie do masy, do liczby osi, rowne cisnienia - jak // bedzie, tak bedzie dobrze - float Fpoj = 0; // MoverParameters->CabOccupied < 0 + float Fpoj = 0; // physics->CabOccupied < 0 ////ALGORYTM 2 - KAZDEMU PO ROWNO, ale nie wiecej niz eped * masa // 1. najpierw daj kazdemu tyle samo int i = 0; - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; + for (TDynamicObject *p = GetFirstDynamic(physics->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; p = state.kier == true ? p->Next(Coupling::control) : p->Prev(Coupling::control) ) { - auto const Nmax = ((p->MoverParameters->P2FTrans * p->MoverParameters->MaxBrakePress[0] - - p->MoverParameters->BrakeCylSpring) * - p->MoverParameters->BrakeCylMult[0] - - p->MoverParameters->BrakeSlckAdj) * - p->MoverParameters->BrakeCylNo * p->MoverParameters->BrakeRigEff; + auto const Nmax = ((p->physics->P2FTrans * p->physics->MaxBrakePress[0] - + p->physics->BrakeCylSpring) * + p->physics->BrakeCylMult[0] - + p->physics->BrakeSlckAdj) * + p->physics->BrakeCylNo * p->physics->BrakeRigEff; FmaxEP[i] = Nmax * - p->MoverParameters->Hamulec->GetFC( - Nmax / (p->MoverParameters->NAxles * p->MoverParameters->NBpA), - p->MoverParameters->MED_Vref) * + p->physics->Hamulec->GetFC( + Nmax / (p->physics->NAxles * p->physics->NBpA), + p->physics->MED_Vref) * 1000; // sila hamowania pn PrzekrF[i] = false; FzED[i] = state.FmaxED > 0 ? state.FzadED / state.FmaxED : 0; - p->MoverParameters->AnPos = - MoverParameters->ScndS ? state.LBR : FzED[i]; - FzEP[ i ] = static_cast( state.FzadPN * p->MoverParameters->NAxles ) / static_cast( state.osie ); + p->physics->AnPos = + physics->ScndS ? state.LBR : FzED[i]; + FzEP[ i ] = static_cast( state.FzadPN * p->physics->NAxles ) / static_cast( state.osie ); ++i; - p->MoverParameters->ShuntMode = MoverParameters->ShuntMode; - p->MoverParameters->ShuntModeAllow = MoverParameters->ShuntModeAllow; + p->physics->ShuntMode = physics->ShuntMode; + p->physics->ShuntModeAllow = physics->ShuntModeAllow; } while (test) { test = false; i = 0; float przek = 0; - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; + for (TDynamicObject *p = GetFirstDynamic(physics->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; p = state.kier == true ? p->Next(Coupling::control) : p->Prev(Coupling::control) ) { if (FzEP[i] > 0.01 && - FzEP[i] > p->MoverParameters->TotalMass * p->MoverParameters->inductionMotor.braking.maxEpDeceleration + std::min(p->MoverParameters->inductionMotor.state.maxForce, 0.) * 1000 && + FzEP[i] > p->physics->TotalMass * p->physics->inductionMotor.braking.maxEpDeceleration + std::min(p->physics->inductionMotor.state.maxForce, 0.) * 1000 && !PrzekrF[i]) { - float przek1 = -std::min(p->MoverParameters->inductionMotor.state.maxForce, 0.) * 1000 + + float przek1 = -std::min(p->physics->inductionMotor.state.maxForce, 0.) * 1000 + FzEP[i] - - p->MoverParameters->TotalMass * - p->MoverParameters->inductionMotor.braking.maxEpDeceleration * 0.999; + p->physics->TotalMass * + p->physics->inductionMotor.braking.maxEpDeceleration * 0.999; PrzekrF[i] = true; test = true; state.nPrzekrF++; @@ -633,7 +633,7 @@ void TDynamicObject::distributeBrakeForces( InductionBrakeState &state, double c } i = 0; przek = przek / (state.np - state.nPrzekrF); - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; + for (TDynamicObject *p = GetFirstDynamic(physics->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; true == state.kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) { if (!PrzekrF[i]) @@ -644,42 +644,42 @@ void TDynamicObject::distributeBrakeForces( InductionBrakeState &state, double c } } i = 0; - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; + for (TDynamicObject *p = GetFirstDynamic(physics->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; true == state.kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) { - float Nmax = ((p->MoverParameters->P2FTrans * p->MoverParameters->MaxBrakePress[0] - - p->MoverParameters->BrakeCylSpring) * - p->MoverParameters->BrakeCylMult[0] - - p->MoverParameters->BrakeSlckAdj) * - p->MoverParameters->BrakeCylNo * p->MoverParameters->BrakeRigEff; + float Nmax = ((p->physics->P2FTrans * p->physics->MaxBrakePress[0] - + p->physics->BrakeCylSpring) * + p->physics->BrakeCylMult[0] - + p->physics->BrakeSlckAdj) * + p->physics->BrakeCylNo * p->physics->BrakeRigEff; if (state.FrED > 0.1) - p->MoverParameters->MED_EPVC_CurrentTime = 0; + p->physics->MED_EPVC_CurrentTime = 0; else - p->MoverParameters->MED_EPVC_CurrentTime += dt1; - bool EPVC = p->MoverParameters->MED_EPVC && (p->MoverParameters->MED_EPVC_Time < 0 || p->MoverParameters->MED_EPVC_CurrentTime < p->MoverParameters->MED_EPVC_Time); - float VelC = EPVC ? safe_clamp(p->MoverParameters->Vel, p->MoverParameters->MED_Vmin, p->MoverParameters->MED_Vmax) : p->MoverParameters->MED_Vref;//korekcja EP po prędkości + p->physics->MED_EPVC_CurrentTime += dt1; + bool EPVC = p->physics->MED_EPVC && (p->physics->MED_EPVC_Time < 0 || p->physics->MED_EPVC_CurrentTime < p->physics->MED_EPVC_Time); + float VelC = EPVC ? safe_clamp(p->physics->Vel, p->physics->MED_Vmin, p->physics->MED_Vmax) : p->physics->MED_Vref;//korekcja EP po prędkości float FmaxPoj = Nmax * - p->MoverParameters->Hamulec->GetFC( - Nmax / (p->MoverParameters->NAxles * p->MoverParameters->NBpA), VelC) * + p->physics->Hamulec->GetFC( + Nmax / (p->physics->NAxles * p->physics->NBpA), VelC) * 1000; // sila hamowania pn - p->MoverParameters->LocalBrakePosAEIM = FzEP[i] / FmaxPoj; - if (p->MoverParameters->LocalBrakePosAEIM>0.009) - if (p->MoverParameters->P2FTrans * p->MoverParameters->BrakeCylMult[0] * - p->MoverParameters->MaxBrakePress[0] != 0) + p->physics->LocalBrakePosAEIM = FzEP[i] / FmaxPoj; + if (p->physics->LocalBrakePosAEIM>0.009) + if (p->physics->P2FTrans * p->physics->BrakeCylMult[0] * + p->physics->MaxBrakePress[0] != 0) { - float x = (p->MoverParameters->BrakeSlckAdj / p->MoverParameters->BrakeCylMult[0] + - p->MoverParameters->BrakeCylSpring) / (p->MoverParameters->P2FTrans * - p->MoverParameters->MaxBrakePress[0]); - p->MoverParameters->LocalBrakePosAEIM = x + (1 - x) * p->MoverParameters->LocalBrakePosAEIM; + float x = (p->physics->BrakeSlckAdj / p->physics->BrakeCylMult[0] + + p->physics->BrakeCylSpring) / (p->physics->P2FTrans * + p->physics->MaxBrakePress[0]); + p->physics->LocalBrakePosAEIM = x + (1 - x) * p->physics->LocalBrakePosAEIM; } else - p->MoverParameters->LocalBrakePosAEIM = p->MoverParameters->LocalBrakePosAEIM; + p->physics->LocalBrakePosAEIM = p->physics->LocalBrakePosAEIM; else - p->MoverParameters->LocalBrakePosAEIM = 0; - if (p->MoverParameters->LocHandleTimeTraxx) + p->physics->LocalBrakePosAEIM = 0; + if (p->physics->LocHandleTimeTraxx) { - p->MoverParameters->eim_localbrake = state.eim_lb; - p->MoverParameters->LocalBrakePosAEIM = std::max(p->MoverParameters->LocalBrakePosAEIM, state.eim_lb); + p->physics->eim_localbrake = state.eim_lb; + p->physics->LocalBrakePosAEIM = std::max(p->physics->LocalBrakePosAEIM, state.eim_lb); } ++i; } @@ -699,12 +699,12 @@ void TDynamicObject::recordMedState( InductionBrakeState const &state, double co if (MEDLogFile.is_open()) { - MEDLogFile << MEDLogTime << "\t" << MoverParameters->Vel << "\t" << state.masa*0.001 << "\t" << state.osie << "\t" << state.FmaxPN*0.001 << "\t" << state.FmaxED*0.001 << "\t" + MEDLogFile << MEDLogTime << "\t" << physics->Vel << "\t" << state.masa*0.001 << "\t" << state.osie << "\t" << state.FmaxPN*0.001 << "\t" << state.FmaxED*0.001 << "\t" << state.FfulED*0.001 << "\t" << state.FrED*0.001 << "\t" << state.Fzad*0.001 << "\t" << state.FzadED*0.001 << "\t" << state.FzadPN*0.001; - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; + for (TDynamicObject *p = GetFirstDynamic(physics->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; true == state.kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) { - MEDLogFile << "\t" << p->MoverParameters->BrakePress; + MEDLogFile << "\t" << p->physics->BrakePress; } MEDLogFile << "\n"; if (floor(MEDLogTime + dt1) > floor(MEDLogTime)) @@ -713,7 +713,7 @@ void TDynamicObject::recordMedState( InductionBrakeState const &state, double co } MEDLogTime += dt1; - if (MoverParameters->Vel < 0.1 || MoverParameters->MainCtrlPowerPos() > 0) + if (physics->Vel < 0.1 || physics->MainCtrlPowerPos() > 0) { MEDLogInactiveTime += dt1; } @@ -734,25 +734,25 @@ void TDynamicObject::recordMedState( InductionBrakeState const &state, double co void TDynamicObject::switchOffMainsWithoutBattery() { // fragment "z EXE Kursa" - if( MoverParameters->Mains ) { // nie wchodzić w funkcję bez potrzeby - if( false == (MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable) + if( physics->Mains ) { // nie wchodzić w funkcję bez potrzeby + if( false == (physics->Power24vIsAvailable || physics->Power110vIsAvailable) /* // NOTE: disabled on account of multi-unit setups, where the unmanned unit wouldn't be affected && ( Controller == Humandriver ) */ - && MoverParameters->EngineType != TEngineType::DieselEngine - && MoverParameters->EngineType != TEngineType::WheelsDriven ) { // jeśli bateria wyłączona, a nie diesel ani drezyna reczna - if( MoverParameters->MainSwitch( false, MoverParameters->TrainType == train_type::emu ? range_t::unit : range_t::local ) ) { + && physics->EngineType != TEngineType::DieselEngine + && physics->EngineType != TEngineType::WheelsDriven ) { // jeśli bateria wyłączona, a nie diesel ani drezyna reczna + if( physics->MainSwitch( false, physics->TrainType == train_type::emu ? range_t::unit : range_t::local ) ) { // wyłączyć zasilanie // NOTE: we turn off entire EMU, but only the affected unit for other multi-unit consists - MoverParameters->EventFlag = true; + physics->EventFlag = true; // drop pantographs // NOTE: this isn't universal behaviour // TODO: have this dependant on .fiz-driven flag // NOTE: moved to pantspeed calculation part a little later in the function. all remarks and todo still apply /* - MoverParameters->PantFront( false, ( MoverParameters->TrainType == train_type::emu ? range::unit : range::local ) ); - MoverParameters->PantRear( false, ( MoverParameters->TrainType == train_type::emu ? range::unit : range::local ) ); + physics->PantFront( false, ( physics->TrainType == train_type::emu ? range::unit : range::local ) ); + physics->PantRear( false, ( physics->TrainType == train_type::emu ? range::unit : range::local ) ); */ } } @@ -774,7 +774,7 @@ double TDynamicObject::moveByPhysics( double const dt, double const dt1 ) 0.0, modelRot.z }; // McZapkie-260202 - dMoveLen przyda sie przy stukocie kol - double const dDOMoveLen = GetdMoveLen() + MoverParameters->ComputeMovement(dt, dt1, ts, tp, tmpTraction, l, r); + double const dDOMoveLen = GetdMoveLen() + physics->ComputeMovement(dt, dt1, ts, tp, tmpTraction, l, r); if( Mechanik ) { // dodanie aktualnego przemieszczenia Mechanik->MoveDistanceAdd( dDOMoveLen ); @@ -782,11 +782,11 @@ double TDynamicObject::moveByPhysics( double const dt, double const dt1 ) if( simulation::Train != nullptr && simulation::Train->Dynamic() == this ) { // update distance meter in user-controlled cab - // TBD: place the meter on mover logic level? + // TBD: place the meter on physics logic level? simulation::Train->add_distance( dDOMoveLen ); } // physics.derailment new: derailed, the vehicle leaves the track and goes on the ground - if( MoverParameters->leaves_track() ) { + if( physics->leaves_track() ) { begin_off_track(); } m_offtracktime = dt1; @@ -815,7 +815,7 @@ void TDynamicObject::updateAxleClatter( double const dDOMoveLen ) dRailLength = MyTrack->fSoundDistance; } if( dRailLength > 0.0 ) { - if( MoverParameters->Vel > 0 ) { + if( physics->Vel > 0 ) { // TODO: track quality and/or environment factors as separate subroutine auto volume = std::lerp( @@ -844,9 +844,9 @@ void TDynamicObject::updateAxleClatter( double const dDOMoveLen ) ctOwner->Vehicle()->DirectionGet() == DirectionGet() ? 1 : -1 ) }; for( auto &axle : m_axlesounds ) { if( axle_passed_joint( axle, dDOMoveLen, directioninconsist ) - && MoverParameters->Vel > 0.1 ) { + && physics->Vel > 0.1 ) { // NOTE: for combined clatter sound we supply 1/100th of actual value, as the sound module converts does the opposite, converting received (typically) 0-1 values to 0-100 range - auto const frequency = true == axle.clatter.is_combined() ? MoverParameters->Vel * 0.01 : 1.0; + auto const frequency = true == axle.clatter.is_combined() ? physics->Vel * 0.01 : 1.0; axle.clatter .pitch( frequency ) .gain( volume ) @@ -867,37 +867,37 @@ void TDynamicObject::applyJointJolt( int const axleindex ) { // crude bump simulation, drop down on even axles, move back up on // the odd ones - // MoverParameters->AccVert += (MoverParameters->Vel*0.1f) * + // physics->AccVert += (physics->Vel*0.1f) * // the arguments keep the order they had up to 26.05.1, 0 in place of the value and the figure in place of the // upper limit, so they work out as the old clamp worked them out up to 26.05.1: the headroom is // Vmax - (Vel + 0.32 Vmax) whatever its sign, and the bump is capped from above only - double const headroom = safe_clamp( 0.0, MoverParameters->Vmax, MoverParameters->Vmax - ( MoverParameters->Vel + MoverParameters->Vmax * 0.32f ) ); + double const headroom = safe_clamp( 0.0, physics->Vmax, physics->Vmax - ( physics->Vel + physics->Vmax * 0.32f ) ); double const jolt = headroom * .05f * ( MyTrack->iDamageFlag * 0.25f ); if (MyTrack->eType == tt_Normal) { - MoverParameters->AccVert += safe_clamp( 0.0, 4.0, jolt ); + physics->AccVert += safe_clamp( 0.0, 4.0, jolt ); } else if (MyTrack->eType == tt_Switch) { double const accHorizontal = safe_clamp( 0.0, 1.0, jolt ) * ((axleindex % 2) != 0 ? 1 : -1); - MoverParameters->AccS += accHorizontal; - MoverParameters->AccN += accHorizontal; - MoverParameters->AccVert += safe_clamp( 0.0, 2.0, jolt ); + physics->AccS += accHorizontal; + physics->AccN += accHorizontal; + physics->AccVert += safe_clamp( 0.0, 2.0, jolt ); } } // the wheels turned by the distance the vehicle went void TDynamicObject::updateWheelAngles( double const dt1 ) { - if (MoverParameters->Vel != 0) + if (physics->Vel != 0) { // McZapkie-050402: krecenie kolami: glm::dvec3 old_wheels = glm::dvec3(dWheelAngle[0], dWheelAngle[1], dWheelAngle[2]); - dWheelAngle[0] += 114.59155902616464175359630962821 * MoverParameters->V * dt1 / - MoverParameters->WheelDiameterL; // przednie toczne - dWheelAngle[1] += MoverParameters->nrot * dt1 * 360.0; // napędne - dWheelAngle[2] += 114.59155902616464175359630962821 * MoverParameters->V * dt1 / - MoverParameters->WheelDiameterT; // tylne toczne + dWheelAngle[0] += 114.59155902616464175359630962821 * physics->V * dt1 / + physics->WheelDiameterL; // przednie toczne + dWheelAngle[1] += physics->nrot * dt1 * 360.0; // napędne + dWheelAngle[2] += 114.59155902616464175359630962821 * physics->V * dt1 / + physics->WheelDiameterT; // tylne toczne m_future_wheels_angle = (glm::dvec3(dWheelAngle[0], dWheelAngle[1], dWheelAngle[2]) - old_wheels) / dt1 * Timer::GetDeltaRenderTime(); @@ -915,8 +915,8 @@ void TDynamicObject::updateCurrentCollectors( double const dt1 ) { // przeliczanie kątów dla pantografów // prąd pobierany przez pojazd z sieci: trakcyjny (on the genset of a dual-mode vehicle none) i TotalCurrent // TotalCurrent to bedzie prad nietrakcyjny (niezwiazany z napedem) - double fCurrent = MoverParameters->CatenaryCurrent(); - // fCurrent+=fabs(MoverParameters->Voltage)*1e-6; //prąd płynący przez woltomierz, rozładowuje kondensator orgromowy 4µF + double fCurrent = physics->CatenaryCurrent(); + // fCurrent+=fabs(physics->Voltage)*1e-6; //prąd płynący przez woltomierz, rozładowuje kondensator orgromowy 4µF /* double fPantCurrent = fCurrent; // normalnie cały prąd przez jeden pantograf if (iAnimType[ANIM_PANTS] > 1) { // a jeśli są dwa pantografy //Ra 1014-11: proteza, trzeba zrobić sensowniej @@ -938,7 +938,7 @@ void TDynamicObject::updateCurrentCollectors( double const dt1 ) } else { if( pantograph->hvPowerWire != nullptr - && true == MoverParameters->Pantographs[PantographEnd( idx )].is_active + && true == physics->Pantographs[PantographEnd( idx )].is_active && pantograph->PantTraction - pantograph->PantWys < 0.01 ) { // tolerancja niedolegania ++activepantographs; } @@ -952,8 +952,8 @@ void TDynamicObject::updateCurrentCollectors( double const dt1 ) } // koniec pętli po pantografach playPantographDropSounds(); } - else if (MoverParameters->EnginePowerSource.SourceType == TPowerSource::InternalSource) - if (MoverParameters->EnginePowerSource.PowerType == TPowerType::SteamPower) + else if (physics->EnginePowerSource.SourceType == TPowerSource::InternalSource) + if (physics->EnginePowerSource.PowerType == TPowerType::SteamPower) // if (smPatykird1[0]) { // Ra: animacja rozrządu parowozu, na razie nieoptymalizowane /* //Ra: tymczasowo wyłączone ze względu na porządkowanie animacji @@ -1035,10 +1035,10 @@ void TDynamicObject::updateCurrentCollectors( double const dt1 ) */ } - if (MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector - && MoverParameters->EnginePowerSource.CollectorParameters.FakePower) { - MoverParameters->PantRearVolt = 0.95 * MoverParameters->EnginePowerSource.MaxVoltage; - MoverParameters->PantFrontVolt = 0.95 * MoverParameters->EnginePowerSource.MaxVoltage; + if (physics->EnginePowerSource.SourceType == TPowerSource::CurrentCollector + && physics->EnginePowerSource.CollectorParameters.FakePower) { + physics->PantRearVolt = 0.95 * physics->EnginePowerSource.MaxVoltage; + physics->PantFrontVolt = 0.95 * physics->EnginePowerSource.MaxVoltage; } } @@ -1059,9 +1059,9 @@ void TDynamicObject::updatePantograph( int const i, double const fPantCurrent, d if (p->fAngleU > M_PI) p->fAngleU = M_PI; if (i & 1) // zgłoszono, że po połamaniu potrafi zostać zasilanie - MoverParameters->PantRearVolt = 0.0; + physics->PantRearVolt = 0.0; else - MoverParameters->PantFrontVolt = 0.0; + physics->PantFrontVolt = 0.0; return; // reszta wtedy nie jest wykonywana } PantDiff = p->PantTraction - p->PantWys; // docelowy-aktualny @@ -1078,30 +1078,30 @@ void TDynamicObject::updatePantographVoltage( int const i, TAnimPant const *p, d if (Global.bLiveTraction == false && p->hvPowerWire == nullptr ) { // jeśli nie ma drutu, może pooszukiwać - MoverParameters->PantFrontVolt = + physics->PantFrontVolt = p->PantWys >= 1.2 ? - 0.95 * MoverParameters->EnginePowerSource.MaxVoltage : + 0.95 * physics->EnginePowerSource.MaxVoltage : 0.0; } - else if( true == MoverParameters->Pantographs[VehicleEnd::front].is_active + else if( true == physics->Pantographs[VehicleEnd::front].is_active && PantDiff < 0.01 ) // tolerancja niedolegania { if (p->hvPowerWire) { - auto const lastvoltage { MoverParameters->PantFrontVolt }; + auto const lastvoltage { physics->PantFrontVolt }; // TODO: wyliczyć trzeba prąd przypadający na pantograf i wstawić do GetVoltage() if( lastvoltage == 0.0 ) { // HACK: retrieve the wire voltage for calculations down the road without blowing up the supply - MoverParameters->PantFrontVolt = p->hvPowerWire->VoltageGet( MoverParameters->PantographVoltage, 0.0 ); + physics->PantFrontVolt = p->hvPowerWire->VoltageGet( physics->PantographVoltage, 0.0 ); } else { - MoverParameters->PantFrontVolt = p->hvPowerWire->VoltageGet( MoverParameters->PantographVoltage, fPantCurrent ); - if( MoverParameters->PantFrontVolt > 0.0 ) { + physics->PantFrontVolt = p->hvPowerWire->VoltageGet( physics->PantographVoltage, fPantCurrent ); + if( physics->PantFrontVolt > 0.0 ) { fCurrent -= fPantCurrent; // taki prąd płynie przez powyższy pantograf (unless it doesn't) } } - // TODO: refactor reaction to voltage change to mover as sound event for specific pantograph + // TODO: refactor reaction to voltage change to physics as sound event for specific pantograph if( lastvoltage == 0.0 - && MoverParameters->PantFrontVolt > 0.0 ) { + && physics->PantFrontVolt > 0.0 ) { for( auto &pantograph : m_pantographsounds ) { if( pantograph.sPantUp.offset().z > 0 ) { // limit to pantographs located in the front half of the vehicle @@ -1111,40 +1111,40 @@ void TDynamicObject::updatePantographVoltage( int const i, TAnimPant const *p, d } } else - MoverParameters->PantFrontVolt = 0.0; + physics->PantFrontVolt = 0.0; } else - MoverParameters->PantFrontVolt = 0.0; - ( fPantCurrent > 0.0 ? MoverParameters->EnergyMeter.first : MoverParameters->EnergyMeter.second ) += MoverParameters->PantFrontVolt * fPantCurrent * dt1 / 3600000.0; + physics->PantFrontVolt = 0.0; + ( fPantCurrent > 0.0 ? physics->EnergyMeter.first : physics->EnergyMeter.second ) += physics->PantFrontVolt * fPantCurrent * dt1 / 3600000.0; break; case 1: if( false == Global.bLiveTraction && nullptr == p->hvPowerWire ) { // jeśli nie ma drutu, może pooszukiwać - MoverParameters->PantRearVolt = + physics->PantRearVolt = p->PantWys >= 1.2 ? - 0.95 * MoverParameters->EnginePowerSource.MaxVoltage : + 0.95 * physics->EnginePowerSource.MaxVoltage : 0.0; } - else if ( true == MoverParameters->Pantographs[VehicleEnd::rear].is_active + else if ( true == physics->Pantographs[VehicleEnd::rear].is_active && PantDiff < 0.01 ) { if (p->hvPowerWire) { - auto const lastvoltage { MoverParameters->PantRearVolt }; + auto const lastvoltage { physics->PantRearVolt }; // TODO: wyliczyć trzeba prąd przypadający na pantograf i wstawić do GetVoltage() if( lastvoltage == 0.0 ) { // HACK: retrieve the wire voltage for calculations down the road without blowing up the supply - MoverParameters->PantRearVolt = p->hvPowerWire->VoltageGet( MoverParameters->PantographVoltage, 0.0 ); + physics->PantRearVolt = p->hvPowerWire->VoltageGet( physics->PantographVoltage, 0.0 ); } else { - MoverParameters->PantRearVolt = p->hvPowerWire->VoltageGet( MoverParameters->PantographVoltage, fPantCurrent ); - if( MoverParameters->PantRearVolt > 0.0 ) { + physics->PantRearVolt = p->hvPowerWire->VoltageGet( physics->PantographVoltage, fPantCurrent ); + if( physics->PantRearVolt > 0.0 ) { fCurrent -= fPantCurrent; // taki prąd płynie przez powyższy pantograf (unless it doesn't) } } - // TODO: refactor reaction to voltage change to mover as sound event for specific pantograph + // TODO: refactor reaction to voltage change to physics as sound event for specific pantograph if( lastvoltage == 0.0 - && MoverParameters->PantRearVolt > 0.0 ) { + && physics->PantRearVolt > 0.0 ) { for( auto &pantograph : m_pantographsounds ) { if( pantograph.sPantUp.offset().z < 0 ) { // limit to pantographs located in the rear half of the vehicle @@ -1154,13 +1154,13 @@ void TDynamicObject::updatePantographVoltage( int const i, TAnimPant const *p, d } } else - MoverParameters->PantRearVolt = 0.0; + physics->PantRearVolt = 0.0; } else { // Global.iPause ^= 2; - MoverParameters->PantRearVolt = 0.0; + physics->PantRearVolt = 0.0; } - ( fPantCurrent > 0.0 ? MoverParameters->EnergyMeter.first : MoverParameters->EnergyMeter.second ) += MoverParameters->PantRearVolt * fPantCurrent * dt1 / 3600000.0; + ( fPantCurrent > 0.0 ? physics->EnergyMeter.first : physics->EnergyMeter.second ) += physics->PantRearVolt * fPantCurrent * dt1 / 3600000.0; break; } // pozostałe na razie nie obsługiwane } @@ -1169,24 +1169,24 @@ void TDynamicObject::updatePantographVoltage( int const i, TAnimPant const *p, d void TDynamicObject::updatePantographMotion( int const i, TAnimPant *p, double const PantDiff, double const dt1 ) { double k; // tymczasowy kąt - if( MoverParameters->PantPress > ( - MoverParameters->TrainType == train_type::emu ? + if( physics->PantPress > ( + physics->TrainType == train_type::emu ? 2.45 : // Ra 2013-12: Niebugocław mówi, że w EZT podnoszą się przy 2.5 3.45 ) ) { // z EXE Kursa // Ra: wysokość zależy od ciśnienia !!! - pantspeedfactor = 0.015 * MoverParameters->PantPress * dt1; + pantspeedfactor = 0.015 * physics->PantPress * dt1; } else { pantspeedfactor = 0.0; } - if( false == ( MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable ) ) { + if( false == ( physics->Power24vIsAvailable || physics->Power110vIsAvailable ) ) { pantspeedfactor = 0.0; } pantspeedfactor = std::max( 0.0, pantspeedfactor ); k = p->fAngleL; if( pantspeedfactor > 0.0 - && MoverParameters->Pantographs[i].is_active )// jeśli ma być podniesiony + && physics->Pantographs[i].is_active )// jeśli ma być podniesiony { if (PantDiff > 0.001) // jeśli nie dolega do drutu { // jeśli poprzednia wysokość jest mniejsza niż pożądana, zwiększyć kąt dolnego @@ -1234,9 +1234,9 @@ void TDynamicObject::updatePantographMotion( int const i, TAnimPant *p, double c // the sound of the pantographs dropping, at the end whose pantograph went down void TDynamicObject::playPantographDropSounds() { - // TBD, TODO: generate sound event during mover update instead? - if( MoverParameters->Pantographs[VehicleEnd::front].sound_event != MoverParameters->Pantographs[ VehicleEnd::front ].is_active ) { - if( MoverParameters->Pantographs[ VehicleEnd::front ].is_active ) { + // TBD, TODO: generate sound event during physics update instead? + if( physics->Pantographs[VehicleEnd::front].sound_event != physics->Pantographs[ VehicleEnd::front ].is_active ) { + if( physics->Pantographs[ VehicleEnd::front ].is_active ) { // pantograph moving up // TBD: add a sound? } @@ -1249,10 +1249,10 @@ void TDynamicObject::playPantographDropSounds() } } } - MoverParameters->Pantographs[ VehicleEnd::front ].sound_event = MoverParameters->Pantographs[ VehicleEnd::front ].is_active; + physics->Pantographs[ VehicleEnd::front ].sound_event = physics->Pantographs[ VehicleEnd::front ].is_active; } - if( MoverParameters->Pantographs[ VehicleEnd::rear ].sound_event != MoverParameters->Pantographs[ VehicleEnd::rear ].is_active ) { - if( MoverParameters->Pantographs[ VehicleEnd::rear ].is_active ) { + if( physics->Pantographs[ VehicleEnd::rear ].sound_event != physics->Pantographs[ VehicleEnd::rear ].is_active ) { + if( physics->Pantographs[ VehicleEnd::rear ].is_active ) { // pantograph moving up // TBD: add a sound? } @@ -1265,7 +1265,7 @@ void TDynamicObject::playPantographDropSounds() } } } - MoverParameters->Pantographs[ VehicleEnd::rear ].sound_event = MoverParameters->Pantographs[ VehicleEnd::rear ].is_active; + physics->Pantographs[ VehicleEnd::rear ].sound_event = physics->Pantographs[ VehicleEnd::rear ].is_active; } } @@ -1278,22 +1278,22 @@ void TDynamicObject::updateWipers( double const dt1 ) for (int i = 0; i < dWiperPos.size(); i++) // iteracja po kazdej wycieraczce { bool wipersActive; - auto const bytesum = MoverParameters->WiperList[MoverParameters->wiperSwitchPos].byteSum; + auto const bytesum = physics->WiperList[physics->wiperSwitchPos].byteSum; // rozroznienie kabinowe - if (MoverParameters->CabActive == 1) + if (physics->CabActive == 1) { - wipersActive = (bytesum & 1 << i) != 0 && MoverParameters->Battery; + wipersActive = (bytesum & 1 << i) != 0 && physics->Battery; } - else if (MoverParameters->CabActive == -1) + else if (physics->CabActive == -1) { // odwroconie indexow wycieraczek - wipersActive = (bytesum & 1 << dWiperPos.size() - 1 - i) != 0 && MoverParameters->Battery; + wipersActive = (bytesum & 1 << dWiperPos.size() - 1 - i) != 0 && physics->Battery; } else { wipersActive = false; } - auto const currentWiperParams = MoverParameters->WiperList[workingSwitchPos[i]]; + auto const currentWiperParams = physics->WiperList[workingSwitchPos[i]]; wiperOutTimer[i] += dt1; // aktualizujemy zegarek wiperParkTimer[i] += dt1; // aktualizujemy zegarek @@ -1340,7 +1340,7 @@ void TDynamicObject::updateWipers( double const dt1 ) sWiperToParkPlayed = false; wiperOutTimer[i] = 0.0; wiperDirection[i] = false; - workingSwitchPos[i] = MoverParameters->wiperSwitchPos; // update configuration + workingSwitchPos[i] = physics->wiperSwitchPos; // update configuration } } @@ -1355,9 +1355,9 @@ void TDynamicObject::updateMirrors( double const dt1 ) // mirrors auto const mirrorleft { dMirrorMoveL }; auto const mirrorright { dMirrorMoveR }; - if( MoverParameters->Vel > MoverParameters->MirrorVelClose - || MoverParameters->CabActive == 0 && activation::mirrors - || MoverParameters->MirrorForbidden ) { + if( physics->Vel > physics->MirrorVelClose + || physics->CabActive == 0 && activation::mirrors + || physics->MirrorForbidden ) { // automatically fold mirrors when above velocity threshold if( dMirrorMoveL > 0.0 ) { dMirrorMoveL = std::max( @@ -1373,13 +1373,13 @@ void TDynamicObject::updateMirrors( double const dt1 ) else { // unfold mirror on the side with open doors, if not moving too fast if( dMirrorMoveL < 1.0 - && true == MoverParameters->Doors.instances[VehicleSide::left].open_permit ) { + && true == physics->Doors.instances[VehicleSide::left].open_permit ) { dMirrorMoveL = std::min( 1.0, dMirrorMoveL + 1.0 * dt1 ); } if( dMirrorMoveR < 1.0 - && true == MoverParameters->Doors.instances[VehicleSide::right].open_permit ) { + && true == physics->Doors.instances[VehicleSide::right].open_permit ) { dMirrorMoveR = std::min( 1.0, dMirrorMoveR + 1.0 * dt1 ); @@ -1394,7 +1394,7 @@ void TDynamicObject::pants_up() TDynamicObject *d = this; bool isAnyPantUp = false; while (d) { - for (auto &item : d->MoverParameters->Pantographs) + for (auto &item : d->physics->Pantographs) { isAnyPantUp |= item.is_active; } @@ -1402,7 +1402,7 @@ void TDynamicObject::pants_up() } d = Prev(Coupling::control); while (d) { - for (auto &item : d->MoverParameters->Pantographs) + for (auto &item : d->physics->Pantographs) { isAnyPantUp |= item.is_active; } @@ -1412,14 +1412,14 @@ void TDynamicObject::pants_up() { d = this; while (d) { - d->MoverParameters->OperatePantographValve(VehicleEnd::front, operation_t::enable, range_t::local); - d->MoverParameters->OperatePantographValve(VehicleEnd::rear, operation_t::enable, range_t::local); + d->physics->OperatePantographValve(VehicleEnd::front, operation_t::enable, range_t::local); + d->physics->OperatePantographValve(VehicleEnd::rear, operation_t::enable, range_t::local); d = d->Next(Coupling::control); // pozostałe też } d = Prev(Coupling::control); while (d) { - d->MoverParameters->OperatePantographValve(VehicleEnd::front, operation_t::enable, range_t::local); - d->MoverParameters->OperatePantographValve(VehicleEnd::rear, operation_t::enable, range_t::local); + d->physics->OperatePantographValve(VehicleEnd::front, operation_t::enable, range_t::local); + d->physics->OperatePantographValve(VehicleEnd::rear, operation_t::enable, range_t::local); d = d->Prev(Coupling::control); // w drugą stronę też } } @@ -1482,9 +1482,9 @@ void TDynamicObject::RadioStop() { // zatrzymanie pojazdu if( Mechanik ) { // o ile ktoś go prowadzi - if( MoverParameters->SecuritySystem.radiostop_available() - && MoverParameters->Radio - && MoverParameters->RadioFuse ) { + if( physics->SecuritySystem.radiostop_available() + && physics->Radio + && physics->RadioFuse ) { // jeśli pojazd ma RadioStop i jest on aktywny // HACK cast until math types unification glm::dvec3 pos = static_cast(vPosition); @@ -1503,8 +1503,8 @@ void TDynamicObject::Damage(char flag) { if (flag & 1) //różnicówka nie robi nic { - MoverParameters->MainSwitch(false); - MoverParameters->FuseOff(); + physics->MainSwitch(false); + physics->FuseOff(); } else { @@ -1512,20 +1512,20 @@ void TDynamicObject::Damage(char flag) if (flag & 2) //usterka sterowania { - MoverParameters->StLinFlag = false; - if (MoverParameters->InitialCtrlDelay<100000000) - MoverParameters->InitialCtrlDelay += 100000001; + physics->StLinFlag = false; + if (physics->InitialCtrlDelay<100000000) + physics->InitialCtrlDelay += 100000001; } else { - if (MoverParameters->InitialCtrlDelay>100000000) - MoverParameters->InitialCtrlDelay -= 100000001; + if (physics->InitialCtrlDelay>100000000) + physics->InitialCtrlDelay -= 100000001; } if (flag & 4) //blokada przetwornicy { - if( MoverParameters->ConverterStart != start_t::disabled ) { - MoverParameters->ConvOvldFlag = true; + if( physics->ConverterStart != start_t::disabled ) { + physics->ConvOvldFlag = true; } } else @@ -1534,32 +1534,32 @@ void TDynamicObject::Damage(char flag) if (flag & 8) //blokada sprezarki { - if (MoverParameters->MinCompressor>0) - MoverParameters->MinCompressor -= 100000001; - if (MoverParameters->MaxCompressor>0) - MoverParameters->MaxCompressor -= 100000001; + if (physics->MinCompressor>0) + physics->MinCompressor -= 100000001; + if (physics->MaxCompressor>0) + physics->MaxCompressor -= 100000001; } else { - if (MoverParameters->MinCompressor<0) - MoverParameters->MinCompressor += 100000001; - if (MoverParameters->MaxCompressor<0) - MoverParameters->MaxCompressor += 100000001; + if (physics->MinCompressor<0) + physics->MinCompressor += 100000001; + if (physics->MaxCompressor<0) + physics->MaxCompressor += 100000001; } if (flag & 16) //blokada wału { - if (MoverParameters->CtrlDelay<100000000) - MoverParameters->CtrlDelay += 100000001; - if (MoverParameters->CtrlDownDelay<100000000) - MoverParameters->CtrlDownDelay += 100000001; + if (physics->CtrlDelay<100000000) + physics->CtrlDelay += 100000001; + if (physics->CtrlDownDelay<100000000) + physics->CtrlDownDelay += 100000001; } else { - if (MoverParameters->CtrlDelay>100000000) - MoverParameters->CtrlDelay -= 100000001; - if (MoverParameters->CtrlDownDelay>100000000) - MoverParameters->CtrlDownDelay -= 100000001; + if (physics->CtrlDelay>100000000) + physics->CtrlDelay -= 100000001; + if (physics->CtrlDownDelay>100000000) + physics->CtrlDownDelay -= 100000001; } if (flag & 32) //hamowanie nagŁe @@ -1569,7 +1569,7 @@ void TDynamicObject::Damage(char flag) { } - MoverParameters->EngDmgFlag = flag; + physics->EngDmgFlag = flag; }; void TDynamicObject::OverheadTrack(float o) diff --git a/vehicle/dynamic/vehicletable.cpp b/vehicle/dynamic/vehicletable.cpp index 689ef28c4..8a49d822f 100644 --- a/vehicle/dynamic/vehicletable.cpp +++ b/vehicle/dynamic/vehicletable.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/DynObj.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/lightsprogrammer.h" #include "simulation/simulation.h" #include "simulation/blackboxrecorder.h" @@ -77,16 +77,16 @@ coupled_train( TDynamicObject *Vehicle ) { auto side { direction }; // a train of more vehicles than are on the tracks would be one coupled into a ring while( train.size() < 10000 ) { - auto const &mover { *vehicle->MoverParameters }; - auto *next { mover.Neighbours[ side ].vehicle }; + auto const &physics { *vehicle->physics }; + auto *next { physics.Neighbours[ side ].vehicle }; if( next == nullptr - || false == mover.Couplers[ side ].CouplingFlag.HasAny(Coupling::coupler) + || false == physics.Couplers[ side ].CouplingFlag.HasAny(Coupling::coupler) || std::ranges::find( train, next ) != train.end() ) { break; } train.emplace_back( next ); // onwards from the end of the next vehicle away from this one - side = EndOf( 1 - mover.Neighbours[ side ].vehicle_end ); + side = EndOf( 1 - physics.Neighbours[ side ].vehicle_end ); vehicle = next; } } @@ -100,10 +100,10 @@ trains_closing_in( std::vector const &Train ) { std::vector trains; for( auto *vehicle : Train ) { for (auto const side : VehicleEnds) { - auto const &mover { *vehicle->MoverParameters }; - auto const &neighbour { mover.Neighbours[ side ] }; + auto const &physics { *vehicle->physics }; + auto const &neighbour { physics.Neighbours[ side ] }; if( neighbour.vehicle == nullptr - || mover.Couplers[ side ].CouplingFlag.HasAny(Coupling::coupler) + || physics.Couplers[ side ].CouplingFlag.HasAny(Coupling::coupler) || neighbour.distance > coupler_physics_reach || std::ranges::find( Train, neighbour.vehicle ) != Train.end() ) { continue; @@ -147,10 +147,10 @@ vehicle_table::update_coupler_physics() const { std::unordered_set checked; for( auto *vehicle : m_items ) { if( covered.contains( vehicle ) ) { - vehicle->MoverParameters->CouplerPhysics = true; + vehicle->physics->CouplerPhysics = true; continue; } - if( false == vehicle->MoverParameters->CouplerPhysics + if( false == vehicle->physics->CouplerPhysics || checked.contains( vehicle ) ) { continue; } @@ -159,7 +159,7 @@ vehicle_table::update_coupler_physics() const { checked.insert( other.begin(), other.end() ); if( false == trains_within( other, train, coupler_physics_release ) ) { for( auto *othervehicle : other ) { - othervehicle->MoverParameters->CouplerPhysics = false; + othervehicle->physics->CouplerPhysics = false; } } } @@ -199,28 +199,28 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { auto const camera { Global.pCamera.Pos }; for( std::size_t index = 0; index < m_items.size(); ++index ) { auto const *vehicle { m_items[ index ] }; - auto const road { ( vehicle->MoverParameters->CategoryFlag & 2 ) != 0 }; + 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 == vehicle->bEnabled ) { continue; } ++counts.kind[ kinds[ index ] ]; - auto const *mover { vehicle->MoverParameters }; - if( mover->Vel < 0.01 ) { + auto const *physics { vehicle->physics }; + if( physics->Vel < 0.01 ) { ++counts.standing[ kinds[ index ] ]; - if( ( false == road ) && mover->PhysicActivation ) { - // the test of TMoverParameters::ComputeTotalForce(), part by part + if( ( false == road ) && physics->PhysicActivation ) { + // the test of physics::Vehicle::ComputeTotalForce(), part by part auto const moving = []( neighbour_data const &Neighbour ) { return ( Neighbour.vehicle != nullptr ) - && ( ( Neighbour.vehicle->MoverParameters->Vel > 0.0001 ) || Neighbour.vehicle->MoverParameters->accelerating() ); }; + && ( ( Neighbour.vehicle->physics->Vel > 0.0001 ) || Neighbour.vehicle->physics->accelerating() ); }; auto &awake { counts.awake }; ++awake.vehicles; - if( mover->CabActive != 0 ) { ++awake.cab; } - if( mover->Vel > 0.0001 ) { ++awake.speed; } - if( mover->accelerating() ) { ++awake.acceleration; } - if( mover->LastSwitchingTime < 5 ) { ++awake.switching; } - if( mover->is_multiple_unit() ) { ++awake.multipleunit; } - if( moving( mover->Neighbours[ VehicleEnd::front ] ) || moving( mover->Neighbours[ VehicleEnd::rear ] ) ) { ++awake.neighbour; } + if( physics->CabActive != 0 ) { ++awake.cab; } + if( physics->Vel > 0.0001 ) { ++awake.speed; } + if( physics->accelerating() ) { ++awake.acceleration; } + if( physics->LastSwitchingTime < 5 ) { ++awake.switching; } + if( physics->is_multiple_unit() ) { ++awake.multipleunit; } + if( moving( physics->Neighbours[ VehicleEnd::front ] ) || moving( physics->Neighbours[ VehicleEnd::rear ] ) ) { ++awake.neighbour; } } } } @@ -234,19 +234,19 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { for( auto const *vehicle : m_items ) { if( false == vehicle->bEnabled ) { continue; } ++counts.enabled; - if( vehicle->MoverParameters->CategoryFlag & 2 ) { ++counts.road; } + if( vehicle->physics->CategoryFlag & 2 ) { ++counts.road; } if( ( vehicle->Mechanik != nullptr ) && vehicle->Mechanik->AIControllFlag ) { ++counts.ai; } - if( vehicle->MoverParameters->PhysicActivation || vehicle->MechInside ) { ++counts.active; } + if( vehicle->physics->PhysicActivation || vehicle->MechInside ) { ++counts.active; } } Timer::subsystem.vehicles_prepare.start(); for( auto *vehicle : m_items ) { if( false == vehicle->bEnabled ) { continue; } // Ra: zmienić warunek na sprawdzanie pantografów w jednej zmiennej: czy pantografy i czy podniesione - if( vehicle->MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector ) { + if( vehicle->physics->EnginePowerSource.SourceType == TPowerSource::CurrentCollector ) { update_traction( vehicle ); } - vehicle->MoverParameters->ComputeConstans(); + vehicle->physics->ComputeConstans(); vehicle->update_neighbours(); } update_coupler_physics(); @@ -261,7 +261,7 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { std::size_t work { 0 }; for( std::size_t index = 0; index < m_items.size(); ++index ) { auto const *vehicle { m_items[ index ] }; - if( vehicle->MoverParameters->PhysicActivation || vehicle->MechInside ) { + if( vehicle->physics->PhysicActivation || vehicle->MechInside ) { work += ( coarse[ index ] != 0 ? 1 : static_cast( std::max( Iterationcount, 1 ) ) ); } } @@ -351,10 +351,10 @@ namespace // the body of the vehicle as it stands, for the contacts: off the track by its motion, on the track upright on it derail_motion::footprint footprint_of( TDynamicObject const &Vehicle ) { - auto const &mover { *Vehicle.MoverParameters }; + auto const &physics { *Vehicle.physics }; derail_motion::pose pose; - if( mover.OffTrack.active() ) { - pose = mover.OffTrack.current(); + if( physics.OffTrack.active() ) { + pose = physics.OffTrack.current(); } else { pose.position = Vehicle.GetPosition(); @@ -362,24 +362,24 @@ derail_motion::footprint footprint_of( TDynamicObject const &Vehicle ) { pose.left = Vehicle.VectorLeft(); pose.up = Vehicle.VectorUp(); } - auto const &shape { mover.OffTrack.shape() }; + auto const &shape { physics.OffTrack.shape() }; return derail_motion::footprint_of( - pose, mover.Dim.L, - mover.OffTrack.active() ? shape.width : ( mover.Dim.W > 0.5 ? mover.Dim.W : 3.0 ), - mover.OffTrack.active() ? shape.height : ( mover.Dim.H > 2.0 ? mover.Dim.H : 4.0 ) ); + pose, physics.Dim.L, + physics.OffTrack.active() ? shape.width : ( physics.Dim.W > 0.5 ? physics.Dim.W : 3.0 ), + physics.OffTrack.active() ? shape.height : ( physics.Dim.H > 2.0 ? physics.Dim.H : 4.0 ) ); } // the vehicle as a body in a contact derail_motion::contact_body contact_body_of( TDynamicObject const &Vehicle ) { - auto const &mover { *Vehicle.MoverParameters }; + auto const &physics { *Vehicle.physics }; derail_motion::contact_body body; - body.mass = mover.TotalMass; - if( mover.OffTrack.active() ) { - body.base = mover.OffTrack.base(); - body.velocity = mover.OffTrack.velocity(); - body.yaw_rate = mover.OffTrack.yaw_rate(); - body.gyration = mover.OffTrack.gyration(); + body.mass = physics.TotalMass; + if( physics.OffTrack.active() ) { + body.base = physics.OffTrack.base(); + body.velocity = physics.OffTrack.velocity(); + body.yaw_rate = physics.OffTrack.yaw_rate(); + body.gyration = physics.OffTrack.gyration(); } else { // on the rails it goes along them only @@ -388,7 +388,7 @@ derail_motion::contact_body contact_body_of( TDynamicObject const &Vehicle ) { body.guided = true; body.guide = length > 1e-6 ? front / length : glm::dvec3 { 0.0, 0.0, 1.0 }; body.base = Vehicle.GetPosition(); - body.velocity = body.guide * mover.V; + body.velocity = body.guide * physics.V; } return body; } @@ -396,13 +396,13 @@ derail_motion::contact_body contact_body_of( TDynamicObject const &Vehicle ) { // how the two came to overlap, for the log std::string_view overlap_kind( TDynamicObject const &First, TDynamicObject const &Second ) { - auto const offtrack { First.MoverParameters->OffTrack.active() && Second.MoverParameters->OffTrack.active() }; + auto const offtrack { First.physics->OffTrack.active() && Second.physics->OffTrack.active() }; for (auto const end : VehicleEnds) { - if( First.MoverParameters->Couplers[ end ].Connected == Second.MoverParameters - && First.MoverParameters->Couplers[ end ].CouplingFlag != Coupling::none ) { + if( First.physics->Couplers[ end ].Connected == Second.physics + && First.physics->Couplers[ end ].CouplingFlag != Coupling::none ) { return offtrack ? "coupled, both off the track" : "coupled, one on the rails"; } - if( First.MoverParameters->Neighbours[ end ].vehicle == &Second ) { + if( First.physics->Neighbours[ end ].vehicle == &Second ) { return offtrack ? "neighbours, both off the track" : "neighbours, one on the rails"; } } @@ -420,7 +420,7 @@ vehicle_table::update_off_track_contacts( double const Deltatime ) { // by their places in the table: the order the pairs are taken in is the same in every run std::vector offtrack; for( std::size_t index = 0; index < m_items.size(); ++index ) { - if( m_items[ index ]->bEnabled && m_items[ index ]->MoverParameters->OffTrack.active() ) { + if( m_items[ index ]->bEnabled && m_items[ index ]->physics->OffTrack.active() ) { offtrack.push_back( index ); } } @@ -433,7 +433,7 @@ vehicle_table::update_off_track_contacts( double const Deltatime ) { auto resting { true }; for( auto const place : offtrack ) { auto *vehicle { m_items[ place ] }; - resting = resting && vehicle->MoverParameters->OffTrack.at_rest(); + resting = resting && vehicle->physics->OffTrack.at_rest(); auto const print { footprint_of( *vehicle ) }; auto const reach { std::hypot( print.half_length, print.half_width ) }; for( std::size_t otherplace = 0; otherplace < m_items.size(); ++otherplace ) { @@ -442,13 +442,13 @@ vehicle_table::update_off_track_contacts( double const Deltatime ) { continue; } // each pair of two off the track once - auto const otheroff { other->MoverParameters->OffTrack.active() }; + auto const otheroff { other->physics->OffTrack.active() }; if( otheroff && otherplace < place ) { continue; } // the bounding circles first auto const apart { other->GetPosition() - vehicle->GetPosition() }; - auto const otherreach { 0.5 * other->MoverParameters->Dim.L + std::max( other->MoverParameters->Dim.W, other->MoverParameters->Dim.H ) }; + auto const otherreach { 0.5 * other->physics->Dim.L + std::max( other->physics->Dim.W, other->physics->Dim.H ) }; if( glm::length( glm::dvec3 { apart.x, 0.0, apart.z } ) > reach + otherreach + 1.0 ) { continue; } @@ -459,19 +459,19 @@ vehicle_table::update_off_track_contacts( double const Deltatime ) { } if( hit->depth > deepest ) { deepest = hit->depth; - deepestpair = std::format( "{} and {}, {}", vehicle->MoverParameters->Name, other->MoverParameters->Name, overlap_kind( *vehicle, *other ) ); + deepestpair = std::format( "{} and {}, {}", vehicle->physics->Name, other->physics->Name, overlap_kind( *vehicle, *other ) ); } auto const body { contact_body_of( *vehicle ) }; auto const otherbody { contact_body_of( *other ) }; auto const impulse { derail_motion::contact_impulse( *hit, body, otherbody ) }; // the one off the track: kicked, and moved out of the other one (half of the way when both are off it) auto const [ velocity, yawrate ] { derail_motion::impulse_change( body, -impulse, hit->point ) }; - auto &motion { vehicle->MoverParameters->OffTrack }; + auto &motion { vehicle->physics->OffTrack }; auto const share { otheroff ? 0.5 : 1.0 }; auto const correction { derail_motion::contact_correction * std::max( 0.0, hit->depth - derail_motion::contact_slop ) }; if( glm::length( impulse ) > 0.0 ) { motion.kick( velocity, yawrate ); - vehicle->MoverParameters->V = motion.speed(); + vehicle->physics->V = motion.speed(); } if( correction > 0.0 ) { motion.nudge( -hit->normal * ( share * correction ) ); @@ -479,10 +479,10 @@ vehicle_table::update_off_track_contacts( double const Deltatime ) { } if( otheroff ) { auto const [ othervelocity, otheryawrate ] { derail_motion::impulse_change( otherbody, impulse, hit->point ) }; - auto &othermotion { other->MoverParameters->OffTrack }; + auto &othermotion { other->physics->OffTrack }; if( glm::length( impulse ) > 0.0 ) { othermotion.kick( othervelocity, otheryawrate ); - other->MoverParameters->V = othermotion.speed(); + other->physics->V = othermotion.speed(); } if( correction > 0.0 ) { othermotion.nudge( hit->normal * ( share * correction ) ); @@ -491,23 +491,23 @@ vehicle_table::update_off_track_contacts( double const Deltatime ) { continue; } // one on the rails: along them into its speed, across them on its wheels, as a coupling pulls them off - auto &othermover { *other->MoverParameters }; - othermover.V += glm::dot( impulse, otherbody.guide ) / std::max( othermover.TotalMass, 1.0 ); - if( othermover.DamageFlag.HasAll(VehicleDamage::derailed) ) { + auto &otherPhysics { *other->physics }; + otherPhysics.V += glm::dot( impulse, otherbody.guide ) / std::max( otherPhysics.TotalMass, 1.0 ); + if( otherPhysics.DamageFlag.HasAll(VehicleDamage::derailed) ) { continue; } glm::dvec3 const otherleft { otherbody.guide.z, 0.0, -otherbody.guide.x }; auto const across { glm::dot( impulse, otherleft ) / Deltatime }; - auto const mass { othermover.TotalMass - othermover.Mred }; - auto const ratio { derail_motion::pull_ratio( std::abs( across ), 0.5 * std::numbers::pi, mass, othermover.NAxles ) }; + auto const mass { otherPhysics.TotalMass - otherPhysics.Mred }; + auto const ratio { derail_motion::pull_ratio( std::abs( across ), 0.5 * std::numbers::pi, mass, otherPhysics.NAxles ) }; // held over the window of the climbing as the bodies slide along each other, or a hit three times as hard // at once: the wheels jump the rail auto const sliding { glm::length( derail_motion::velocity_at( body, hit->point ) - otherbody.velocity ) * Deltatime }; if( other->m_struck.update( ratio >= derailment::climbing_limit, sliding ) || ratio >= 3.0 * derailment::climbing_limit ) { - othermover.pull_off( + otherPhysics.pull_off( across >= 0.0 ? 1 : -1, mass > 0.0 ? std::abs( across ) / mass : 0.0, - std::format( "Y/Q {:.2f} from {} running into it, {:.0f} kN across", ratio, vehicle->MoverParameters->Name, std::abs( across ) / 1000.0 ) ); + std::format( "Y/Q {:.2f} from {} running into it, {:.0f} kN across", ratio, vehicle->physics->Name, std::abs( across ) / 1000.0 ) ); other->m_struck.reset(); } } @@ -562,12 +562,12 @@ vehicle_table::update_brake_pipes( double const Deltatime ) { m_brakepipes.clear(); for( auto *vehicle : m_items ) { - if( ( true == vehicle->MoverParameters->PipeCouplersPending ) - || ( true == vehicle->MoverParameters->ScndPipeCouplersPending ) ) { - m_brakepipes.push_back( vehicle->MoverParameters ); + if( ( true == vehicle->physics->PipeCouplersPending ) + || ( true == vehicle->physics->ScndPipeCouplersPending ) ) { + m_brakepipes.push_back( vehicle->physics ); } } - TMoverParameters::UpdatePipeCouplers( m_brakepipes, Deltatime ); + physics::Vehicle::UpdatePipeCouplers( m_brakepipes, Deltatime ); } // records the odometer states of the vehicles and saves them for the next sessions (eu07/maszyna#72) @@ -577,8 +577,8 @@ vehicle_table::save_odometers() { m_odometersavetimer = 0.0; auto &odometers { odometer::states() }; for( auto const *vehicle : m_items ) { - if( vehicle->MoverParameters != nullptr ) { - odometer::record( odometers, vehicle->name(), vehicle->MoverParameters->HasDriverCab(), vehicle->MoverParameters->Odometer ); + if( vehicle->physics != nullptr ) { + odometer::record( odometers, vehicle->name(), vehicle->physics->HasDriverCab(), vehicle->physics->Odometer ); } } odometer::save(); @@ -608,11 +608,11 @@ vehicle_table::update_steps_parallel( double const Deltatime, int const Iteratio } return Index; }; for( std::size_t index = 0; index < itemcount; ++index ) { - auto const *mover { m_items[ index ]->MoverParameters }; + auto const *physics { m_items[ index ]->physics }; for (auto const end : VehicleEnds) { - auto const *neighbour { mover->Neighbours[ end ].vehicle }; - if( ( mover->Couplers[ end ].Connected != nullptr ) - && ( ( neighbour == nullptr ) || ( neighbour->MoverParameters != mover->Couplers[ end ].Connected ) ) ) { + auto const *neighbour { physics->Neighbours[ end ].vehicle }; + if( ( physics->Couplers[ end ].Connected != nullptr ) + && ( ( neighbour == nullptr ) || ( neighbour->physics != physics->Couplers[ end ].Connected ) ) ) { return false; } if( neighbour == nullptr ) { continue; } @@ -650,7 +650,7 @@ vehicle_table::update_steps_parallel( double const Deltatime, int const Iteratio std::begin( m_groups[ group ] ), std::end( m_groups[ group ] ), [ this ]( std::uint32_t const Index ) { auto const *vehicle { m_items[ Index ] }; - return ( vehicle->MoverParameters->LoadStatus != 0 ) || ( vehicle->LoadExchangeTime() > 0.f ); } ) }; + return ( vehicle->physics->LoadStatus != 0 ) || ( vehicle->LoadExchangeTime() > 0.f ); } ) }; ( loading ? m_maingroups : m_threadgroups ).push_back( static_cast( group ) ); } std::sort( @@ -677,7 +677,7 @@ vehicle_table::update_steps_parallel( double const Deltatime, int const Iteratio set_thread_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; + std::vector pipes; if( Iterationcount > 1 ) { // ABu: ponizsze wykonujemy tylko jesli wiecej niz jedna iteracja for( int iteration = 0; iteration < Iterationcount - 1; ++iteration ) { @@ -689,12 +689,12 @@ vehicle_table::update_steps_parallel( double const Deltatime, int const Iteratio } pipes.clear(); for( auto const index : members ) { - auto *mover { m_items[ index ]->MoverParameters }; - if( mover->PipeCouplersPending || mover->ScndPipeCouplersPending ) { - pipes.push_back( mover ); + auto *physics { m_items[ index ]->physics }; + if( physics->PipeCouplersPending || physics->ScndPipeCouplersPending ) { + pipes.push_back( physics ); } } - TMoverParameters::UpdatePipeCouplers( pipes, Deltatime ); + physics::Vehicle::UpdatePipeCouplers( pipes, Deltatime ); } } for( auto const index : members ) { @@ -724,7 +724,7 @@ vehicle_table::update_traction( TDynamicObject *Vehicle ) { for( int pantographindex = 0; pantographindex < Vehicle->iAnimType[ ANIM_PANTS ]; ++pantographindex ) { // pętla po pantografach auto *pantograph { Vehicle->pants[ pantographindex ].fParamPants }; - if( true == Vehicle->MoverParameters->Pantographs[ pantographindex ].is_active ) { + if( true == Vehicle->physics->Pantographs[ pantographindex ].is_active ) { // jeśli pantograf podniesiony auto const pant0 { position + vLeft * pantograph->vPos.z + vUp * pantograph->vPos.y + vFront * pantograph->vPos.x }; if( pantograph->hvPowerWire != nullptr ) { @@ -859,8 +859,8 @@ vehicle_table::erase_disabled() { else { // the distance the vehicle ran goes in the odometer store now, it doesn't depend on the vehicle being // kept on the list until the next save (eu07/maszyna#72) - if( vehicle->MoverParameters != nullptr ) { - odometer::record( odometer::states(), vehicle->name(), vehicle->MoverParameters->HasDriverCab(), vehicle->MoverParameters->Odometer ); + if( vehicle->physics != nullptr ) { + odometer::record( odometer::states(), vehicle->name(), vehicle->physics->HasDriverCab(), vehicle->physics->Odometer ); } if( vehicle->MyTrack != nullptr && true == vehicle->MyTrack->RemoveDynamicObject(vehicle) ) { diff --git a/vehicle/dynamic/visual.cpp b/vehicle/dynamic/visual.cpp index 5d7e83562..60a1c5c4b 100644 --- a/vehicle/dynamic/visual.cpp +++ b/vehicle/dynamic/visual.cpp @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/DynObj.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/lightsprogrammer.h" #include "simulation/simulation.h" #include "simulation/blackboxrecorder.h" @@ -126,8 +126,8 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) // display _xon if connected with another vehicle and not the coupling owner // display _xon if not connected, but equipped with coupling adapter // display _off if not connected, not equipped with coupling adapter or if _xon model is missing - if( MoverParameters->Couplers[ VehicleEnd::front ].CouplingFlag.HasAll(Coupling::coupler) ) { - if( MoverParameters->Couplers[ VehicleEnd::front ].Render ) { + if( physics->Couplers[ VehicleEnd::front ].CouplingFlag.HasAll(Coupling::coupler) ) { + if( physics->Couplers[ VehicleEnd::front ].Render ) { btCoupler1.TurnOn(); } else { @@ -136,13 +136,13 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) btnOn = true; } else { - if( true == MoverParameters->Couplers[ VehicleEnd::front ].has_adapter() ) { + if( true == physics->Couplers[ VehicleEnd::front ].has_adapter() ) { btCoupler1.TurnxOnWithOffAsFallback(); btnOn = true; } } - if( MoverParameters->Couplers[ VehicleEnd::rear ].CouplingFlag.HasAll(Coupling::coupler) ) { - if( MoverParameters->Couplers[ VehicleEnd::rear ].Render ) { + if( physics->Couplers[ VehicleEnd::rear ].CouplingFlag.HasAll(Coupling::coupler) ) { + if( physics->Couplers[ VehicleEnd::rear ].Render ) { btCoupler2.TurnOn(); } else { @@ -151,7 +151,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) btnOn = true; } else { - if( true == MoverParameters->Couplers[ VehicleEnd::rear ].has_adapter() ) { + if( true == physics->Couplers[ VehicleEnd::rear ].has_adapter() ) { btCoupler2.TurnxOnWithOffAsFallback(); btnOn = true; } @@ -168,7 +168,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) SetPneumatic(true, true); // ktore z nich nalezy SetPneumatic(false, true); // wyswietlic w tej klatce - if (MoverParameters->Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::brakeHose)) + if (physics->Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::brakeHose)) { switch (cp1) { @@ -188,7 +188,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) btnOn = true; } - if (MoverParameters->Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::brakeHose)) + if (physics->Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::brakeHose)) { switch (cp2) { @@ -209,7 +209,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } // przewody zasilajace, j.w. (yB) - if (MoverParameters->Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::mainHose)) + if (physics->Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::mainHose)) { switch (sp1) { @@ -229,7 +229,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) btnOn = true; } - if (MoverParameters->Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::mainHose)) + if (physics->Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::mainHose)) { switch (sp2) { @@ -254,18 +254,18 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) { // przewody powietrzne j.w., ABu: decyzja czy rysowac tylko na podstawie // 'render' - if (MoverParameters->Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::brakeHose)) + if (physics->Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::brakeHose)) { - if (MoverParameters->Couplers[VehicleEnd::front].Render) + if (physics->Couplers[VehicleEnd::front].Render) btCPneumatic1.TurnOn(); else btCPneumatic1r.TurnOn(); btnOn = true; } - if (MoverParameters->Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::brakeHose)) + if (physics->Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::brakeHose)) { - if (MoverParameters->Couplers[VehicleEnd::rear].Render) + if (physics->Couplers[VehicleEnd::rear].Render) btCPneumatic2.TurnOn(); else btCPneumatic2r.TurnOn(); @@ -275,18 +275,18 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) // przewody powietrzne j.w., ABu: decyzja czy rysowac tylko na podstawie // 'render' // //yB - zasilajace - if (MoverParameters->Couplers[0].CouplingFlag.HasAll(Coupling::mainHose)) + if (physics->Couplers[0].CouplingFlag.HasAll(Coupling::mainHose)) { - if (MoverParameters->Couplers[0].Render) + if (physics->Couplers[0].Render) btPneumatic1.TurnOn(); else btPneumatic1r.TurnOn(); btnOn = true; } - if (MoverParameters->Couplers[1].CouplingFlag.HasAll(Coupling::mainHose)) + if (physics->Couplers[1].CouplingFlag.HasAll(Coupling::mainHose)) { - if (MoverParameters->Couplers[1].Render) + if (physics->Couplers[1].Render) btPneumatic2.TurnOn(); else btPneumatic2r.TurnOn(); @@ -298,13 +298,13 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) // uginanie zderzakow for (int i = 0; i < 2; ++i) { - if( MoverParameters->Couplers[ i ].has_adapter() ) { + if( physics->Couplers[ i ].has_adapter() ) { // HACK: if there's coupler adapter on this side, we presume there's additional distance put between vehicles // which prevents buffers from clashing against each other (or the other vehicle doesn't have buffers to begin with) continue; } - auto const dist { safe_clamp( MoverParameters->Couplers[ i ].Dist / 2.0, -MoverParameters->Couplers[ i ].DmaxB, 0.0 ) }; + auto const dist { safe_clamp( physics->Couplers[ i ].Dist / 2.0, -physics->Couplers[ i ].DmaxB, 0.0 ) }; if( dist >= 0.0 ) { continue; } @@ -320,64 +320,64 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) // Winger 160204 - podnoszenie pantografow // przewody sterowania ukrotnionego - if (MoverParameters->Couplers[0].CouplingFlag.HasAll(Coupling::control)) + if (physics->Couplers[0].CouplingFlag.HasAll(Coupling::control)) { btCCtrl1.Turn( true ); btnOn = true; } // else btCCtrl1.TurnOff(); - if (MoverParameters->Couplers[1].CouplingFlag.HasAll(Coupling::control)) + if (physics->Couplers[1].CouplingFlag.HasAll(Coupling::control)) { btCCtrl2.Turn( true ); btnOn = true; } // else btCCtrl2.TurnOff(); // McZapkie-181103: mostki przejsciowe - if (MoverParameters->Couplers[0].CouplingFlag.HasAll(Coupling::gangway)) + if (physics->Couplers[0].CouplingFlag.HasAll(Coupling::gangway)) { btCPass1.Turn( true ); btnOn = true; } // else btCPass1.TurnOff(); - if (MoverParameters->Couplers[1].CouplingFlag.HasAll(Coupling::gangway)) + if (physics->Couplers[1].CouplingFlag.HasAll(Coupling::gangway)) { btCPass2.Turn( true ); btnOn = true; } // else btCPass2.TurnOff(); - if (MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable) + if (physics->Power24vIsAvailable || physics->Power110vIsAvailable) { // sygnaly konca pociagu if (m_endsignals1.Active()) { - if (TestFlag(MoverParameters->iLights[VehicleEnd::front], light::redmarker_left | light::redmarker_right ) ) { + if (TestFlag(physics->iLights[VehicleEnd::front], light::redmarker_left | light::redmarker_right ) ) { m_endsignals1.Turn( true ); btnOn = true; } } else { - if (TestFlag(MoverParameters->iLights[VehicleEnd::front], light::redmarker_left) && !HeadlightsAoff) + if (TestFlag(physics->iLights[VehicleEnd::front], light::redmarker_left) && !HeadlightsAoff) { m_endsignal13.Turn( true ); btnOn = true; } - if (TestFlag(MoverParameters->iLights[VehicleEnd::front], light::redmarker_right) && !HeadlightsAoff) + if (TestFlag(physics->iLights[VehicleEnd::front], light::redmarker_right) && !HeadlightsAoff) { m_endsignal12.Turn( true ); btnOn = true; } } if (m_endsignals2.Active()) { - if (TestFlag(MoverParameters->iLights[VehicleEnd::rear], light::redmarker_left | light::redmarker_right ) ) { + if (TestFlag(physics->iLights[VehicleEnd::rear], light::redmarker_left | light::redmarker_right ) ) { m_endsignals2.Turn( true ); btnOn = true; } } else { - if (TestFlag(MoverParameters->iLights[VehicleEnd::rear], light::redmarker_left) && !HeadlightsBoff) + if (TestFlag(physics->iLights[VehicleEnd::rear], light::redmarker_left) && !HeadlightsBoff) { m_endsignal23.Turn( true ); btnOn = true; } - if (TestFlag(MoverParameters->iLights[VehicleEnd::rear], light::redmarker_right) && !HeadlightsBoff) + if (TestFlag(physics->iLights[VehicleEnd::rear], light::redmarker_right) && !HeadlightsBoff) { m_endsignal22.Turn( true ); btnOn = true; @@ -385,12 +385,12 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } } // tablice blaszane: - if (TestFlag(MoverParameters->iLights[VehicleEnd::front], light::rearendsignals)) { + if (TestFlag(physics->iLights[VehicleEnd::front], light::rearendsignals)) { m_endtab1.Turn( true ); btnOn = true; } // else btEndSignalsTab1.TurnOff(); - if (TestFlag(MoverParameters->iLights[VehicleEnd::rear], light::rearendsignals)) { + if (TestFlag(physics->iLights[VehicleEnd::rear], light::rearendsignals)) { m_endtab2.Turn( true ); btnOn = true; } @@ -402,17 +402,17 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) for (int i = 0; i < 4; ++i) if (smWahacze[i]) smWahacze[i]->SetRotate(float3(1, 0, 0), - fWahaczeAmp * cos(MoverParameters->eAngle)); + fWahaczeAmp * cos(physics->eAngle)); // cooling shutters // NOTE: shutters display _on state when they're closed, _off otherwise - if( true == MoverParameters->diesel.heat.water.config.shutters - && false == MoverParameters->diesel.heat.zaluzje1 ) { + if( true == physics->diesel.heat.water.config.shutters + && false == physics->diesel.heat.zaluzje1 ) { btShutters1.Turn( true ); btnOn = true; } - if( true == MoverParameters->diesel.heat.water_aux.config.shutters - && false == MoverParameters->diesel.heat.zaluzje2 ) { + if( true == physics->diesel.heat.water_aux.config.shutters + && false == physics->diesel.heat.zaluzje2 ) { btShutters2.Turn( true ); btnOn = true; } @@ -424,21 +424,21 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) && Mechanik != nullptr && Mechanik->action() != TAction::actSleep ) { // rysowanie figurki mechanika - btMechanik1.Turn(MoverParameters->CabOccupied > 0); - btMechanik2.Turn( MoverParameters->CabOccupied < 0 ); - if( MoverParameters->CabOccupied != 0 ) { + btMechanik1.Turn(physics->CabOccupied > 0); + btMechanik2.Turn( physics->CabOccupied < 0 ); + if( physics->CabOccupied != 0 ) { btnOn = true; } } } // vehicle within 400m - if( MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable ) + if( physics->Power24vIsAvailable || physics->Power110vIsAvailable ) { // sygnały czoła pociagu //Ra: wyświetlamy bez // ograniczeń odległości, by były widoczne z // daleka - if (TestFlag(MoverParameters->iLights[VehicleEnd::front], light::headlight_left) + if (TestFlag(physics->iLights[VehicleEnd::front], light::headlight_left) && !HeadlightsAoff && !HighBeamLights) { if( DimHeadlights ) { @@ -449,7 +449,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } btnOn = true; } - if (TestFlag(MoverParameters->iLights[VehicleEnd::front], light::headlight_upper) + if (TestFlag(physics->iLights[VehicleEnd::front], light::headlight_upper) && !HeadlightsAoff) { if( DimHeadlights ) { @@ -460,7 +460,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } btnOn = true; } - if (TestFlag(MoverParameters->iLights[VehicleEnd::front], light::headlight_right) + if (TestFlag(physics->iLights[VehicleEnd::front], light::headlight_right) && !HeadlightsAoff && !HighBeamLights) { if( DimHeadlights ) { @@ -472,7 +472,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) btnOn = true; } // else btHeadSignals13.TurnOff(); - if (TestFlag(MoverParameters->iLights[VehicleEnd::rear], light::headlight_left) + if (TestFlag(physics->iLights[VehicleEnd::rear], light::headlight_left) && !HeadlightsBoff && !HighBeamLights) { if( DimHeadlights ) { @@ -483,7 +483,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } btnOn = true; } - if (TestFlag(MoverParameters->iLights[VehicleEnd::rear], light::headlight_upper) + if (TestFlag(physics->iLights[VehicleEnd::rear], light::headlight_upper) && !HeadlightsBoff) { if( DimHeadlights ) { @@ -494,7 +494,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } btnOn = true; } - if (TestFlag(MoverParameters->iLights[VehicleEnd::rear], light::headlight_right) + if (TestFlag(physics->iLights[VehicleEnd::rear], light::headlight_right) && !HeadlightsBoff && !HighBeamLights) { if( DimHeadlights ) { @@ -506,7 +506,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) btnOn = true; } // auxiliary lights - if (TestFlag(MoverParameters->iLights[VehicleEnd::front], light::auxiliary_left) && !HeadlightsAoff) + if (TestFlag(physics->iLights[VehicleEnd::front], light::auxiliary_left) && !HeadlightsAoff) { if( DimHeadlights ) { m_headsignal13.TurnxOnWithOnAsFallback(); @@ -516,7 +516,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } btnOn = true; } - if (TestFlag(MoverParameters->iLights[VehicleEnd::front], light::auxiliary_right) && !HeadlightsAoff) + if (TestFlag(physics->iLights[VehicleEnd::front], light::auxiliary_right) && !HeadlightsAoff) { if( DimHeadlights ) { m_headsignal12.TurnxOnWithOnAsFallback(); @@ -526,7 +526,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } btnOn = true; } - if (TestFlag(MoverParameters->iLights[VehicleEnd::rear], light::auxiliary_left) && !HeadlightsBoff) + if (TestFlag(physics->iLights[VehicleEnd::rear], light::auxiliary_left) && !HeadlightsBoff) { if( DimHeadlights ) { m_headsignal23.TurnxOnWithOnAsFallback(); @@ -536,7 +536,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } btnOn = true; } - if (TestFlag(MoverParameters->iLights[VehicleEnd::rear], light::auxiliary_right) && !HeadlightsBoff) + if (TestFlag(physics->iLights[VehicleEnd::rear], light::auxiliary_right) && !HeadlightsBoff) { if( DimHeadlights ) { m_headsignal22.TurnxOnWithOnAsFallback(); @@ -548,26 +548,26 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } // logika dlugich - if (TestFlag(MoverParameters->iLights[VehicleEnd::front], light::headlight_left) + if (TestFlag(physics->iLights[VehicleEnd::front], light::headlight_left) && !HeadlightsAoff && HighBeamLights) m_highbeam13.TurnxOnWithOnAsFallback(); else m_highbeam13.TurnOff(); - if (TestFlag(MoverParameters->iLights[VehicleEnd::front], light::headlight_right) + if (TestFlag(physics->iLights[VehicleEnd::front], light::headlight_right) && !HeadlightsAoff && HighBeamLights) m_highbeam12.TurnxOnWithOnAsFallback(); else m_highbeam12.TurnOff(); // i to samo od dupy strony - if (TestFlag(MoverParameters->iLights[VehicleEnd::rear], light::headlight_left) + if (TestFlag(physics->iLights[VehicleEnd::rear], light::headlight_left) && !HeadlightsBoff && HighBeamLights) m_highbeam23.TurnxOnWithOnAsFallback(); else m_highbeam23.TurnOff(); - if (TestFlag(MoverParameters->iLights[VehicleEnd::rear], light::headlight_right) + if (TestFlag(physics->iLights[VehicleEnd::rear], light::headlight_right) && !HeadlightsBoff && HighBeamLights) m_highbeam22.TurnxOnWithOnAsFallback(); else @@ -583,7 +583,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) cabsection &= sectionname.size() >= 4 && sectionname.starts_with("cab"); } // TODO: add cablight devices - auto const sectionlightlevel { section.light_level * ( cabsection ? 1.0f : MoverParameters->CompartmentLights.intensity ) }; + auto const sectionlightlevel { section.light_level * ( cabsection ? 1.0f : physics->CompartmentLights.intensity ) }; sectionlightcolor = glm::vec4( sectionlightlevel == 0.f || Global.fLuminance > section.compartment->fLight ? glm::vec3(240.f / 255.f) : // TBD: save and restore initial submodel diffuse instead of enforcing one? @@ -642,35 +642,35 @@ TDynamicObject::update_shake( double const Timedelta ) { if( Global.iSlowMotion == 0 ) { // musi być pełna prędkość glm::dvec3 shakevector; - if( MoverParameters->EngineType == TEngineType::DieselElectric - || MoverParameters->EngineType == TEngineType::DieselEngine ) { - if( std::abs( MoverParameters->enrot ) > 0.0 ) { + if( physics->EngineType == TEngineType::DieselElectric + || physics->EngineType == TEngineType::DieselEngine ) { + if( std::abs( physics->enrot ) > 0.0 ) { // engine vibration shakevector.x += - std::sin(MoverParameters->eAngle * 4.0) * Timedelta * + std::sin(physics->eAngle * 4.0) * Timedelta * EngineShake.scale // fade in with rpm above threshold * std::clamp( - ( MoverParameters->enrot - EngineShake.fadein_offset ) * EngineShake.fadein_factor, + ( physics->enrot - EngineShake.fadein_offset ) * EngineShake.fadein_factor, 0.0, 1.0 ) // fade out with rpm above threshold * std::lerp( 1.0, 0.0, std::clamp( - ( MoverParameters->enrot - EngineShake.fadeout_offset ) * EngineShake.fadeout_factor, + ( physics->enrot - EngineShake.fadeout_offset ) * EngineShake.fadeout_factor, 0.0, 1.0 ) ); } } if( HuntingShake.fadein_begin > 0.f - && true == MoverParameters->TruckHunting ) { + && true == physics->TruckHunting ) { // hunting oscillation - HuntingAngle = clamp_circular( HuntingAngle + 4.0 * HuntingShake.frequency * Timedelta * MoverParameters->Vel, 360.0 ); + HuntingAngle = clamp_circular( HuntingAngle + 4.0 * HuntingShake.frequency * Timedelta * physics->Vel, 360.0 ); auto const huntingamount = std::lerp( 0.0, 1.0, std::clamp( - ( MoverParameters->Vel - HuntingShake.fadein_begin ) / ( HuntingShake.fadein_end - HuntingShake.fadein_begin ), + ( physics->Vel - HuntingShake.fadein_begin ) / ( HuntingShake.fadein_end - HuntingShake.fadein_begin ), 0.0, 1.0 ) ); shakevector.x += std::sin(glm::radians(HuntingAngle)) * Timedelta * HuntingShake.scale @@ -687,11 +687,11 @@ TDynamicObject::update_shake( double const Timedelta ) { if( iVel > 0.5 ) { // acceleration-driven base shake shakevector += glm::dvec3( - replaced.sway ? 0.0 : -MoverParameters->AccN * Timedelta * 5.0 * Global.ShakingMultiplierRL, // highlight side sway - -MoverParameters->AccVert * Timedelta * Global.ShakingMultiplierUD, - -MoverParameters->AccSVBased * Timedelta * 1.5 * Global.ShakingMultiplierBF); // accent acceleration/deceleration + replaced.sway ? 0.0 : -physics->AccN * Timedelta * 5.0 * Global.ShakingMultiplierRL, // highlight side sway + -physics->AccVert * Timedelta * Global.ShakingMultiplierUD, + -physics->AccSVBased * Timedelta * 1.5 * Global.ShakingMultiplierBF); // accent acceleration/deceleration // unevenness of the track under the outer axles - auto const ride { 0.5 * ( Axle0.UnevenBend() + Axle1.UnevenBend() ) * ( MoverParameters->V * MoverParameters->V ) }; + auto const ride { 0.5 * ( Axle0.UnevenBend() + Axle1.UnevenBend() ) * ( physics->V * physics->V ) }; shakevector += glm::dvec3( -glm::dot( ride, vLeft ) * Timedelta * 5.0 * Global.ShakingMultiplierRL, -ride.y * Timedelta * Global.ShakingMultiplierUD, diff --git a/vehicle/enginestart.cpp b/vehicle/enginestart.cpp index df29fae07..c221119f4 100644 --- a/vehicle/enginestart.cpp +++ b/vehicle/enginestart.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/enginestart.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "utilities/utilities.h" namespace engine_start { @@ -18,13 +18,13 @@ namespace engine_start { namespace { // whether the vehicle has an engine the cab can start, the same test the tachometers of the vehicles in multiple make -bool has_engine(TMoverParameters const &Vehicle) { +bool has_engine(physics::Vehicle const &Vehicle) { return Vehicle.Power > 0.01; } // walks from Start through its coupler Side along the control cable, and returns the Number-th vehicle with an engine // other than Skipped it meets; Number is lowered by the ones it met when it doesn't get that far -TMoverParameters *find_along(TMoverParameters const &Start, int const Side, TMoverParameters const &Skipped, int &Number) { +physics::Vehicle *find_along(physics::Vehicle const &Start, int const Side, physics::Vehicle const &Skipped, int &Number) { auto const *vehicle{&Start}; auto side{Side}; // a train can't loop back on itself, the limit only guards against a broken chain of couplers @@ -49,7 +49,7 @@ TMoverParameters *find_along(TMoverParameters const &Start, int const Side, TMov } // namespace -TMoverParameters *engine(TMoverParameters const &Occupied, TMoverParameters &Controlled, int Number) { +physics::Vehicle *engine(physics::Vehicle const &Occupied, physics::Vehicle &Controlled, int Number) { if (Number < 1) { return nullptr; } @@ -66,7 +66,7 @@ TMoverParameters *engine(TMoverParameters const &Occupied, TMoverParameters &Con return find_along(Occupied, 1 - behind, Controlled, others); } -void remote_switch::update(TMoverParameters *Engine, bool const Closeheld, bool const Openheld, double const Deltatime, bool const Closesonrelease) { +void remote_switch::update(physics::Vehicle *Engine, bool const Closeheld, bool const Openheld, double const Deltatime, bool const Closesonrelease) { if (Engine != m_engine) { // another vehicle under the switch, after a change in the train m_engine = Engine; @@ -98,11 +98,11 @@ void remote_switch::update(TMoverParameters *Engine, bool const Closeheld, bool } } -bool remote_switch::open(TMoverParameters &Engine) { +bool remote_switch::open(physics::Vehicle &Engine) { return Engine.MainSwitch(false, range_t::local); } -bool remote_switch::is_running(TMoverParameters const &Engine) { +bool remote_switch::is_running(physics::Vehicle const &Engine) { return Engine.Mains || Engine.diesel.startupRequested; } diff --git a/vehicle/enginestart.h b/vehicle/enginestart.h index 77b6a2d93..b2696ba46 100644 --- a/vehicle/enginestart.h +++ b/vehicle/enginestart.h @@ -9,20 +9,20 @@ http://mozilla.org/MPL/2.0/. #pragma once -class TMoverParameters; +namespace physics { class Vehicle; } // starting the engines (closing the line breakers) of the vehicles in multiple from the cab (eu07/maszyna#80). in // vehicles like the ST43, the SP32 or the SN61 every engine of the train has its own switches in the cab: main_* work -// the vehicle the cab controls (TTrain::mvControlled: the cab's own vehicle, on an EMU its motor car), mainb_* the +// the vehicle the cab controls (TTrain::controlled: the cab's own vehicle, on an EMU its motor car), mainb_* the // second one and mainc_* the third one under its control. Engine:JointEngineStart=No in the .fiz of the controlled // vehicle (on an EMU the motor car's, not the one of the car with the cab) keeps main_* to that vehicle alone -// (TMoverParameters::MainSwitchRange()); by default it works all of them, as before. +// (physics::Vehicle::MainSwitchRange()); by default it works all of them, as before. namespace engine_start { // the Number-th vehicle with an engine under the cab's control: 1 is Controlled, the cab's own; then the others // connected through the control cable, those behind the cab of Occupied first, the nearest first, then those in front // of it. nullptr when there are fewer of them -TMoverParameters *engine(TMoverParameters const &Occupied, TMoverParameters &Controlled, int Number); +physics::Vehicle *engine(physics::Vehicle const &Occupied, physics::Vehicle &Controlled, int Number); // the switch starting the engine of another vehicle in multiple. like the cab's own switch, it has to be held closed // for the vehicle's InitialCtrlDelay, with the vehicle ready for it, before the engine starts (the line breaker closes) @@ -31,14 +31,14 @@ public: // one step of Deltatime seconds of the switch of Engine, with the switch held closed (Closeheld) or open (Openheld). // with Closesonrelease, the line breaker closes when the switch is let go after the delay, as the impulse switch // of an electric locomotive with series motors does - void update(TMoverParameters *Engine, bool Closeheld, bool Openheld, double Deltatime, bool Closesonrelease); + void update(physics::Vehicle *Engine, bool Closeheld, bool Openheld, double Deltatime, bool Closesonrelease); // opens the line breaker / stops the engine of Engine, the vehicle alone; returns whether it was running - static bool open(TMoverParameters &Engine); + static bool open(physics::Vehicle &Engine); // whether the line breaker of Engine is closed or its engine starting or running - static bool is_running(TMoverParameters const &Engine); + static bool is_running(physics::Vehicle const &Engine); private: - TMoverParameters const *m_engine{nullptr}; // the vehicle the switch worked the last step + physics::Vehicle const *m_engine{nullptr}; // the vehicle the switch worked the last step double m_heldtime{0.0}; // how long the switch is held closed with the vehicle ready to start bool m_ready{false}; // held long enough, the line breaker closes now or when the switch is let go }; diff --git a/vehicle/handover.cpp b/vehicle/handover.cpp index 878afdf3d..73996d12e 100644 --- a/vehicle/handover.cpp +++ b/vehicle/handover.cpp @@ -10,11 +10,11 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/handover.h" -#include "physics/mover.h" +#include "physics/vehicle.h" namespace handover { -void release_ai_controls(TMoverParameters &Occupied, TMoverParameters &Controlling) { +void release_ai_controls(physics::Vehicle &Occupied, physics::Vehicle &Controlling) { // the AI's hornoff action touches the horn only while the AI drives Occupied.WarningSignal = 0; // the AI drives the sandbox directly, bypassing the manual and automatic sanding states @@ -29,7 +29,7 @@ void release_ai_controls(TMoverParameters &Occupied, TMoverParameters &Controlli } } -int light_selector_position(TMoverParameters const &Occupied, int const Lightstable, int const Headlights, int const Inventory) { +int light_selector_position(physics::Vehicle const &Occupied, int const Lightstable, int const Headlights, int const Inventory) { // the selector size comes from the vehicle definition, the table holds a fixed number of positions auto const positioncount{std::min(Occupied.LightsPosNo, static_cast(std::size(Occupied.Lights[0])))}; if (positioncount <= 0 || Lightstable < 0 || Lightstable >= static_cast(std::size(Occupied.Lights))) { @@ -48,7 +48,7 @@ int light_selector_position(TMoverParameters const &Occupied, int const Lightsta return Occupied.LightsPos; } -int dimmer_position(TMoverParameters const &Occupied, bool const Headlightson) { +int dimmer_position(physics::Vehicle const &Occupied, bool const Headlightson) { auto const &positions{Occupied.dimPositions}; auto const current{Occupied.modernDimmerPosition}; auto const count{static_cast(positions.size())}; diff --git a/vehicle/handover.h b/vehicle/handover.h index 32ed57d0a..f02edca68 100644 --- a/vehicle/handover.h +++ b/vehicle/handover.h @@ -9,7 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once -class TMoverParameters; +namespace physics { class Vehicle; } // what changes about a vehicle when the AI hands it over to the human driver. the AI operates some // controls directly, bypassing the cab controls a human uses, and only the AI ever releases them; @@ -18,16 +18,16 @@ namespace handover { // releases what the AI latches, but which is held only while pressed for the human driver: // the horn, the sandbox, the departure signal and the brake releaser -void release_ai_controls(TMoverParameters &Occupied, TMoverParameters &Controlling); +void release_ai_controls(physics::Vehicle &Occupied, physics::Vehicle &Controlling); // position of the light preset selector [1..LightsPosNo] for the human driver: the current one when it // gives the head lights the AI has set, else the first one which does, else the current one. // Lightstable is the end of the selector's table in use, Inventory the lights the head end has -int light_selector_position(TMoverParameters const &Occupied, int Lightstable, int Headlights, int Inventory); +int light_selector_position(physics::Vehicle const &Occupied, int Lightstable, int Headlights, int Inventory); // position of the headlight dimmer for the human driver: the current one, unless it's the off position // which would hide the head lights the AI has lit. then the default one, else the first regular one, // else any other than off -int dimmer_position(TMoverParameters const &Occupied, bool Headlightson); +int dimmer_position(physics::Vehicle const &Occupied, bool Headlightson); } // namespace handover diff --git a/vehicle/lightsprogrammer.h b/vehicle/lightsprogrammer.h index bf9728b1e..6e0cd7bbb 100644 --- a/vehicle/lightsprogrammer.h +++ b/vehicle/lightsprogrammer.h @@ -11,7 +11,7 @@ http://mozilla.org/MPL/2.0/. #include -#include "physics/mover.h" +#include "physics/vehicle.h" // the lights the light preset selector (programmer) of the occupied cab gives one vehicle of the consist namespace lights_programmer { diff --git a/vehicle/linebreaker.h b/vehicle/linebreaker.h index e87312dd1..cfcf76003 100644 --- a/vehicle/linebreaker.h +++ b/vehicle/linebreaker.h @@ -12,7 +12,7 @@ http://mozilla.org/MPL/2.0/. // the line breaker (main switch, WS) controls of the cab namespace linebreaker { -// the state the cab keeps of the line breaker, besides the vehicle's own (TMoverParameters::Mains) +// the state the cab keeps of the line breaker, besides the vehicle's own (physics::Vehicle::Mains) enum class state : int { open, closed, diff --git a/vehicle/mainctrlact.h b/vehicle/mainctrlact.h index eb594473e..15b943de1 100644 --- a/vehicle/mainctrlact.h +++ b/vehicle/mainctrlact.h @@ -9,7 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once -#include "physics/mover.h" +#include "physics/vehicle.h" // the position the controller position marker of the cab (mainctrlact:) shows namespace main_ctrl_act { @@ -17,14 +17,14 @@ namespace main_ctrl_act { // the diesel engines work the controller position straight away, they have no camshaft or relays of their own that // would follow it, and nothing sets their MainCtrlActualPos; only with a controller of the EIM kind (EIMCtrlType) // it is kept up to date (CheckEIMIC). so their marker shows the position of the controller (MaSzyna-EU07/maszyna#74) -inline bool follows_controller(TMoverParameters const &Vehicle) { +inline bool follows_controller(physics::Vehicle const &Vehicle) { return (Vehicle.EngineType == TEngineType::DieselEngine || Vehicle.EngineType == TEngineType::DieselElectric) && Vehicle.EIMCtrlType == 0; } // Scaletable: the cab's gauge has a scaletable:. only such a marker follows the controller; the cabs that define // mainctrlact: without one (the ST43 so far) keep their marker still, as before, instead of moving it on a scale // nobody has checked -inline float position(TMoverParameters const &Vehicle, bool const Scaletable) { +inline float position(physics::Vehicle const &Vehicle, bool const Scaletable) { auto const controller{Scaletable && follows_controller(Vehicle)}; auto const main{controller ? Vehicle.MainCtrlPos : Vehicle.MainCtrlActualPos}; auto const scnd{controller ? Vehicle.ScndCtrlPos : Vehicle.ScndCtrlActualPos}; diff --git a/vehicle/odometer.h b/vehicle/odometer.h index 958a15f60..4fe369764 100644 --- a/vehicle/odometer.h +++ b/vehicle/odometer.h @@ -105,7 +105,7 @@ private: // the vehicle is one the store keeps: one with a driver's cab, which can show its odometer on the cab's counter or a // python screen. that's -// - a vehicle whose type has a cab (Drivercab, TMoverParameters::HasDriverCab(): it has the driver's brake valve). that +// - a vehicle whose type has a cab (Drivercab, physics::Vehicle::HasDriverCab(): it has the driver's brake valve). that // includes the locomotives and units the AI runs before a player's cab loads them, their made up states stay // replaceable by the cab's counter // - a vehicle whose cab showed the odometer in this session (reading::shown): the cab was loaded for a player, or a diff --git a/vehicle/odometerreading.h b/vehicle/odometerreading.h index 286b2da5a..e5d0e7b00 100644 --- a/vehicle/odometerreading.h +++ b/vehicle/odometerreading.h @@ -9,7 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once -// the odometer of a vehicle (eu07/maszyna#72), the part the vehicle physics (TMoverParameters::Odometer) keeps: plain +// the odometer of a vehicle (eu07/maszyna#72), the part the vehicle physics (physics::Vehicle::Odometer) keeps: plain // data, without the store and its files, which are in vehicle/odometer.h namespace odometer { diff --git a/vehicle/pulleemode.h b/vehicle/pulleemode.h index f01ed5768..e1b7a73ed 100644 --- a/vehicle/pulleemode.h +++ b/vehicle/pulleemode.h @@ -13,7 +13,7 @@ http://mozilla.org/MPL/2.0/. #include // the pullee mode ("jazda ciągniona", MaSzyna-EU07/maszyna#64): a vehicle prepared for being hauled dead in a train, -// TMoverParameters::PulleeModeSwitch(). a scenery asks for it with the parameter H among the ones written after the +// physics::Vehicle::PulleeModeSwitch(). a scenery asks for it with the parameter H among the ones written after the // coupling of the vehicle, split by dots: "3.H", or with others, "3.BG.H" // node -1 0 EU160-001 dynamic pkp/vectron_v1 1293-107 wariant_7w 0 nobody 3.H 0 enddynamic namespace pullee_mode { diff --git a/vehicle/smoke.cpp b/vehicle/smoke.cpp index b12c4d3ca..b0805374d 100644 --- a/vehicle/smoke.cpp +++ b/vehicle/smoke.cpp @@ -10,37 +10,37 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/smoke.h" -#include "physics/mover.h" +#include "physics/vehicle.h" namespace smoke { namespace { // how hard the engine works, scaling the spawn rate of the source -double engine_load(TMoverParameters const &Mover) { - if (Mover.diesel.spinningUp) { +double engine_load(physics::Vehicle const &Physics) { + if (Physics.diesel.spinningUp) { // starting up, it puffs harder the faster it turns - return ((Mover.enrot / 4) * 0.01); + return ((Physics.enrot / 4) * 0.01); } - auto const rpmrise{(Mover.DElist[Mover.MainCtrlPosNo].RPM - Mover.enrot) / 60}; - if (Mover.DirAbsolute == 0 || Mover.Im == 0) { + auto const rpmrise{(Physics.DElist[Physics.MainCtrlPosNo].RPM - Physics.enrot) / 60}; + if (Physics.DirAbsolute == 0 || Physics.Im == 0) { // idling: speeding up to the revolutions of the master controller - return ((rpmrise * 0.02) * (Mover.EnginePower * 0.005)); + return ((rpmrise * 0.02) * (Physics.EnginePower * 0.005)); } // under load: the more current the traction motors draw, the more smoke - return ((rpmrise * (std::sqrt(Mover.Im) * 0.01) * 0.02) * (Mover.EnginePower * 0.005)); + return ((rpmrise * (std::sqrt(Physics.Im) * 0.01) * 0.02) * (Physics.EnginePower * 0.005)); } } // namespace -float vehicle_spawn_count(TMoverParameters const &Mover, bool const Ontracks, spawn_rate const &Rate, double const Timedelta) { - if (false == Ontracks || Mover.diesel.firingCountdown > 0.0) { +float vehicle_spawn_count(physics::Vehicle const &Physics, bool const Ontracks, spawn_rate const &Rate, double const Timedelta) { + if (false == Ontracks || Physics.diesel.firingCountdown > 0.0) { return 0.f; } // the steady rate of the source, the way a source of the scenery spawns... auto const steady{std::min(static_cast(Rate.pending + (Rate.rate * Timedelta * Rate.fidelity)), Rate.limit)}; // ...and on top of it the share of the engine - return std::min(static_cast(steady + (Rate.rate * Timedelta * Rate.fidelity * engine_load(Mover))), Rate.limit); + return std::min(static_cast(steady + (Rate.rate * Timedelta * Rate.fidelity * engine_load(Physics))), Rate.limit); } } // namespace smoke diff --git a/vehicle/smoke.h b/vehicle/smoke.h index e3c3adec5..0391c70ff 100644 --- a/vehicle/smoke.h +++ b/vehicle/smoke.h @@ -9,7 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once -class TMoverParameters; +namespace physics { class Vehicle; } // the smoke of a vehicle's engine, let out by the smoke sources of its model (rendering/particles.h) namespace smoke { @@ -25,7 +25,7 @@ struct spawn_rate { // number of particles the smoke source of a vehicle has to spawn after Timedelta seconds: the steady rate of the // source, plus a share which grows with the work of its engine. a vehicle taken off the tracks (Ontracks false: gone through a portal, or waiting in the pool of the road // traffic) puffs no more, the particles it already let out fade away as usual -// an engine the starter turns but which hasn't fired yet (TMoverParameters::diesel.firingCountdown) lets out no smoke either -float vehicle_spawn_count(TMoverParameters const &Mover, bool Ontracks, spawn_rate const &Rate, double Timedelta); +// an engine the starter turns but which hasn't fired yet (physics::Vehicle::diesel.firingCountdown) lets out no smoke either +float vehicle_spawn_count(physics::Vehicle const &Physics, bool Ontracks, spawn_rate const &Rate, double Timedelta); } // namespace smoke diff --git a/vehicle/timetableservice.cpp b/vehicle/timetableservice.cpp index cca7a5e17..eac25815b 100644 --- a/vehicle/timetableservice.cpp +++ b/vehicle/timetableservice.cpp @@ -10,11 +10,11 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/timetableservice.h" -#include "physics/mover.h" +#include "physics/vehicle.h" namespace timetable { -bool opens_doors(TMoverParameters const &Vehicle, service_flags const &Flags) { +bool opens_doors(physics::Vehicle const &Vehicle, service_flags const &Flags) { switch (Vehicle.Doors.open_control) { case control_t::conductor: case control_t::driver: diff --git a/vehicle/timetableservice.h b/vehicle/timetableservice.h index b5c72adf7..b1c32576f 100644 --- a/vehicle/timetableservice.h +++ b/vehicle/timetableservice.h @@ -13,7 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "world/timetableflags.h" -class TMoverParameters; +namespace physics { class Vehicle; } // what the AI driver does at a stop and on the way, as the service flags of the timetable ask (eu07/maszyna#95). with // no flags each answer is the one the AI gave before the flags @@ -22,7 +22,7 @@ namespace timetable { // whether the driver opens the doors of the consist from the cab at a stop, Vehicle being the one he drives: the doors // the conductor or the driver opens, and with the central door opening also the ones of mixed control, which are // otherwise left to the passengers -bool opens_doors(TMoverParameters const &Vehicle, service_flags const &Flags); +bool opens_doors(physics::Vehicle const &Vehicle, service_flags const &Flags); // the state the driver sets the doorsteps to before he opens the doors at a stop, none when he leaves them as they are std::optional doorstep(service_flags const &Flags); diff --git a/widgets/trainingcard.cpp b/widgets/trainingcard.cpp index 31434237f..d5a464e92 100644 --- a/widgets/trainingcard.cpp +++ b/widgets/trainingcard.cpp @@ -2,7 +2,7 @@ #include "widgets/trainingcard.h" #include "simulation/simulation.h" #include "utilities/utilities.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include "vehicle/DynObj.h" #ifdef __linux__ @@ -179,7 +179,7 @@ void trainingcard_panel::render_contents() { state.store(2); if (simulation::Trains.sequence().size() > 0) - distance = static_cast(simulation::Trains.sequence()[0]->Dynamic()->MoverParameters->DistCounter); + distance = static_cast(simulation::Trains.sequence()[0]->Dynamic()->physics->DistCounter); if (save_thread.joinable()) save_thread.join(); diff --git a/widgets/vehicleparams.cpp b/widgets/vehicleparams.cpp index 86966de40..dd439cfbb 100644 --- a/widgets/vehicleparams.cpp +++ b/widgets/vehicleparams.cpp @@ -4,7 +4,7 @@ #include "application/driveruipanels.h" #include "vehicle/Driver.h" #include "vehicle/Train.h" -#include "physics/mover.h" +#include "physics/vehicle.h" ui::vehicleparams_panel::vehicleparams_panel(const std::string &vehicle) : ui_panel(std::string(STR("Vehicle parameters")) + ": " + vehicle, false), m_vehicle_name(vehicle) { @@ -47,7 +47,7 @@ void ui::vehicleparams_panel::draw_infobutton(const char *str, ImVec2 pos, const ImGui::PopStyleColor(4); } -void ui::vehicleparams_panel::draw_mini(const TMoverParameters &mover) +void ui::vehicleparams_panel::draw_mini(const physics::Vehicle &physics) { if (vehicle_mini == null_handle) return; @@ -63,34 +63,34 @@ void ui::vehicleparams_panel::draw_mini(const TMoverParameters &mover) { ImGui::Image((ImTextureID)(intptr_t)(tex.get_id()), ImVec2(x, y), ImVec2(0, 1), ImVec2(1, 0)); - if (mover.Pantographs[VehicleEnd::rear].is_active) + if (physics.Pantographs[VehicleEnd::rear].is_active) draw_infobutton("╨╨╨", ImVec2(126, 10)); - if (mover.Pantographs[VehicleEnd::front].is_active) + if (physics.Pantographs[VehicleEnd::front].is_active) draw_infobutton("╨╨╨", ImVec2(290, 10)); - if (mover.Battery) + if (physics.Battery) draw_infobutton(STR_C("bat."), ImVec2(120, 55)); - if (mover.Mains) + if (physics.Mains) draw_infobutton(STR_C("main.")); - if (mover.ConverterFlag) + if (physics.ConverterFlag) draw_infobutton(STR_C("conv.")); - if (mover.CompressorFlag) + if (physics.CompressorFlag) draw_infobutton(STR_C("comp.")); - if (mover.WarningSignal) + if (physics.WarningSignal) draw_infobutton(STR_C("horn"), ImVec2(361, 11)); - if (mover.iLights[VehicleEnd::front] & light::redmarker_left) + if (physics.iLights[VehicleEnd::front] & light::redmarker_left) draw_infobutton("o", ImVec2(490, 71), ImVec4(1.0f, 0.0f, 0.0f, 1.0f)); - else if (mover.iLights[VehicleEnd::front] & light::headlight_left) + else if (physics.iLights[VehicleEnd::front] & light::headlight_left) draw_infobutton("O", ImVec2(490, 71), ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); - if (mover.iLights[VehicleEnd::front] & light::redmarker_right) + if (physics.iLights[VehicleEnd::front] & light::redmarker_right) draw_infobutton("o", ImVec2(443, 71), ImVec4(1.0f, 0.0f, 0.0f, 1.0f)); - else if (mover.iLights[VehicleEnd::front] & light::headlight_right) + else if (physics.iLights[VehicleEnd::front] & light::headlight_right) draw_infobutton("O", ImVec2(443, 71), ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); - if (mover.iLights[VehicleEnd::front] & light::headlight_upper) + if (physics.iLights[VehicleEnd::front] & light::headlight_upper) draw_infobutton("O", ImVec2(467, 18), ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); } ImGui::EndChild(); @@ -138,28 +138,28 @@ void ui::vehicleparams_panel::render_contents() } TDynamicObject &vehicle = *vehicle_ptr; - TMoverParameters &mover = *vehicle.MoverParameters; + physics::Vehicle &physics = *vehicle.physics; std::vector lines; std::array buffer; - auto const isdieselenginepowered{(mover.EngineType == TEngineType::DieselElectric) || (mover.EngineType == TEngineType::DieselEngine)}; - auto const isdieselinshuntmode{mover.ShuntMode && mover.EngineType == TEngineType::DieselElectric}; + auto const isdieselenginepowered{(physics.EngineType == TEngineType::DieselElectric) || (physics.EngineType == TEngineType::DieselEngine)}; + auto const isdieselinshuntmode{physics.ShuntMode && physics.EngineType == TEngineType::DieselElectric}; std::snprintf(buffer.data(), buffer.size(), STR_C("Devices: %c%c%c%c%c%c%c%c%c%c%c%c%c%c%s%s\nPower transfers: %.0f@%.0f%s%s%s%.0f@%.0f"), // devices - (mover.Battery ? 'B' : '.'), (mover.Mains ? 'M' : '.'), (mover.FuseFlag ? '!' : '.'), (mover.Pantographs[VehicleEnd::rear].is_active ? (mover.PantRearVolt > 0.0 ? 'O' : 'o') : '.'), - (mover.Pantographs[VehicleEnd::front].is_active ? (mover.PantFrontVolt > 0.0 ? 'P' : 'p') : '.'), (mover.PantPressLockActive ? '!' : (mover.PantPressSwitchActive ? '*' : '.')), - (mover.WaterPump.is_active ? 'W' : (false == mover.WaterPump.breaker ? '-' : (mover.WaterPump.is_enabled ? 'w' : '.'))), - (true == mover.WaterHeater.is_damaged ? '!' : (mover.WaterHeater.is_active ? 'H' : (false == mover.WaterHeater.breaker ? '-' : (mover.WaterHeater.is_enabled ? 'h' : '.')))), - (mover.FuelPump.is_active ? 'F' : (mover.FuelPump.is_enabled ? 'f' : '.')), (mover.OilPump.is_active ? 'O' : (mover.OilPump.is_enabled ? 'o' : '.')), - (false == mover.ConverterAllowLocal ? '-' : (mover.ConverterAllow ? (mover.ConverterFlag ? 'X' : 'x') : '.')), (mover.ConvOvldFlag ? '!' : '.'), - (mover.CompressorFlag ? 'C' : (false == mover.CompressorAllowLocal ? '-' : ((mover.CompressorAllow || mover.CompressorStart == start_t::automatic) ? 'c' : '.'))), - (mover.CompressorGovernorLock ? '!' : '.'), "", std::string(isdieselenginepowered ? STR(" oil pressure: ") + to_string(mover.OilPump.pressure, 2) : "").c_str(), + (physics.Battery ? 'B' : '.'), (physics.Mains ? 'M' : '.'), (physics.FuseFlag ? '!' : '.'), (physics.Pantographs[VehicleEnd::rear].is_active ? (physics.PantRearVolt > 0.0 ? 'O' : 'o') : '.'), + (physics.Pantographs[VehicleEnd::front].is_active ? (physics.PantFrontVolt > 0.0 ? 'P' : 'p') : '.'), (physics.PantPressLockActive ? '!' : (physics.PantPressSwitchActive ? '*' : '.')), + (physics.WaterPump.is_active ? 'W' : (false == physics.WaterPump.breaker ? '-' : (physics.WaterPump.is_enabled ? 'w' : '.'))), + (true == physics.WaterHeater.is_damaged ? '!' : (physics.WaterHeater.is_active ? 'H' : (false == physics.WaterHeater.breaker ? '-' : (physics.WaterHeater.is_enabled ? 'h' : '.')))), + (physics.FuelPump.is_active ? 'F' : (physics.FuelPump.is_enabled ? 'f' : '.')), (physics.OilPump.is_active ? 'O' : (physics.OilPump.is_enabled ? 'o' : '.')), + (false == physics.ConverterAllowLocal ? '-' : (physics.ConverterAllow ? (physics.ConverterFlag ? 'X' : 'x') : '.')), (physics.ConvOvldFlag ? '!' : '.'), + (physics.CompressorFlag ? 'C' : (false == physics.CompressorAllowLocal ? '-' : ((physics.CompressorAllow || physics.CompressorStart == start_t::automatic) ? 'c' : '.'))), + (physics.CompressorGovernorLock ? '!' : '.'), "", std::string(isdieselenginepowered ? STR(" oil pressure: ") + to_string(physics.OilPump.pressure, 2) : "").c_str(), // power transfers - mover.Couplers[VehicleEnd::front].power_high.voltage, mover.Couplers[VehicleEnd::front].power_high.current, std::string(mover.Couplers[VehicleEnd::front].power_high.is_local ? "" : "-").c_str(), - std::string(vehicle.DirectionGet() ? ":<<:" : ":>>:").c_str(), std::string(mover.Couplers[VehicleEnd::rear].power_high.is_local ? "" : "-").c_str(), - mover.Couplers[VehicleEnd::rear].power_high.voltage, mover.Couplers[VehicleEnd::rear].power_high.current); + physics.Couplers[VehicleEnd::front].power_high.voltage, physics.Couplers[VehicleEnd::front].power_high.current, std::string(physics.Couplers[VehicleEnd::front].power_high.is_local ? "" : "-").c_str(), + std::string(vehicle.DirectionGet() ? ":<<:" : ":>>:").c_str(), std::string(physics.Couplers[VehicleEnd::rear].power_high.is_local ? "" : "-").c_str(), + physics.Couplers[VehicleEnd::rear].power_high.voltage, physics.Couplers[VehicleEnd::rear].power_high.current); ImGui::TextUnformatted(buffer.data()); @@ -167,20 +167,20 @@ void ui::vehicleparams_panel::render_contents() STR_C("Controllers:\n master: %d(%d), secondary: %s\nEngine output: %.1f, current: %.0f\nRevolutions:\n engine: %.0f, motors: %.0f\n engine fans: %.0f, motor fans: %.0f+%.0f, " "cooling fans: %.0f+%.0f"), // controllers - mover.MainCtrlPos, mover.MainCtrlActualPos, - std::string(isdieselinshuntmode ? to_string(mover.AnPos, 2) + STR(" (shunt mode)") : std::to_string(mover.ScndCtrlPos) + "(" + std::to_string(mover.ScndCtrlActualPos) + ")").c_str(), + physics.MainCtrlPos, physics.MainCtrlActualPos, + std::string(isdieselinshuntmode ? to_string(physics.AnPos, 2) + STR(" (shunt mode)") : std::to_string(physics.ScndCtrlPos) + "(" + std::to_string(physics.ScndCtrlActualPos) + ")").c_str(), // engine - mover.EnginePower, std::abs(mover.TrainType == train_type::emu ? mover.ShowCurrent(0) : mover.Im), + physics.EnginePower, std::abs(physics.TrainType == train_type::emu ? physics.ShowCurrent(0) : physics.Im), // revolutions - std::abs(mover.enrot) * 60, std::abs(mover.nrot) * mover.Transmision.Ratio * 60, mover.RventRot * 60, std::abs(mover.MotorBlowers[VehicleEnd::front].revolutions), - std::abs(mover.MotorBlowers[VehicleEnd::rear].revolutions), mover.diesel.heat.rpmw, mover.diesel.heat.rpmw2); + std::abs(physics.enrot) * 60, std::abs(physics.nrot) * physics.Transmision.Ratio * 60, physics.RventRot * 60, std::abs(physics.MotorBlowers[VehicleEnd::front].revolutions), + std::abs(physics.MotorBlowers[VehicleEnd::rear].revolutions), physics.diesel.heat.rpmw, physics.diesel.heat.rpmw2); ImGui::TextUnformatted(buffer.data()); if (isdieselenginepowered) { - std::snprintf(buffer.data(), buffer.size(), STR_C("\nTemperatures:\n engine: %.2f, oil: %.2f, water: %.2f%c%.2f"), mover.diesel.heat.Ts, mover.diesel.heat.To, mover.diesel.heat.temperatura1, - (mover.WaterCircuitsLink ? '-' : '|'), mover.diesel.heat.temperatura2); + std::snprintf(buffer.data(), buffer.size(), STR_C("\nTemperatures:\n engine: %.2f, oil: %.2f, water: %.2f%c%.2f"), physics.diesel.heat.Ts, physics.diesel.heat.To, physics.diesel.heat.temperatura1, + (physics.WaterCircuitsLink ? '-' : '|'), physics.diesel.heat.temperatura2); ImGui::TextUnformatted(buffer.data()); } @@ -190,7 +190,7 @@ void ui::vehicleparams_panel::render_contents() for (auto const &delay : delays) { - if ((mover.BrakeDelayFlag & delay.first) == delay.first) + if ((physics.BrakeDelayFlag & delay.first) == delay.first) { brakedelay += delay.second; } @@ -201,19 +201,19 @@ void ui::vehicleparams_panel::render_contents() STR_C("Brakes:\n train: %.2f, independent: %.2f, mode: %d, delay: %s, load flag: %d\nBrake cylinder pressures:\n train: %.2f, independent: %.2f, status: 0x%.2x\nPipe pressures:\n " "brake: %.2f (hat: %.2f), main: %.2f, control: %.2f\nTank pressures:\n auxiliary: %.2f, main: %.2f, control: %.2f"), // brakes - mover.fBrakeCtrlPos, mover.LocalBrakePosA, mover.BrakeOpModeFlag, brakedelay.c_str(), mover.LoadFlag, + physics.fBrakeCtrlPos, physics.LocalBrakePosA, physics.BrakeOpModeFlag, brakedelay.c_str(), physics.LoadFlag, // cylinders - mover.BrakePress, mover.LocBrakePress, mover.Hamulec->GetBrakeStatus(), + physics.BrakePress, physics.LocBrakePress, physics.Hamulec->GetBrakeStatus(), // pipes - mover.PipePress, mover.BrakeCtrlPos2, mover.ScndPipePress, mover.CntrlPipePress, + physics.PipePress, physics.BrakeCtrlPos2, physics.ScndPipePress, physics.CntrlPipePress, // tanks - mover.Hamulec->GetBRP(), mover.Compressor, mover.Hamulec->GetCRP()); + physics.Hamulec->GetBRP(), physics.Compressor, physics.Hamulec->GetCRP()); ImGui::TextUnformatted(buffer.data()); - if (mover.EnginePowerSource.SourceType == TPowerSource::CurrentCollector) + if (physics.EnginePowerSource.SourceType == TPowerSource::CurrentCollector) { - std::snprintf(buffer.data(), buffer.size(), STR_C(" pantograph: %.2f%cMT"), mover.PantPress, (mover.bPantKurek3 ? '-' : '|')); + std::snprintf(buffer.data(), buffer.size(), STR_C(" pantograph: %.2f%cMT"), physics.PantPress, (physics.bPantKurek3 ? '-' : '|')); ImGui::TextUnformatted(buffer.data()); } @@ -221,16 +221,16 @@ void ui::vehicleparams_panel::render_contents() STR_C("Forces:\n tractive: %.1f, brake: %.1f, friction: %.2f%s\nAcceleration:\n tangential: %.2f, normal: %.2f (path radius: %s)\nVelocity: %.2f, distance traveled: %.2f\nPosition: " "[%.2f, %.2f, %.2f]"), // forces - mover.Ft * 0.001f * - (mover.CabActive ? mover.CabActive : + physics.Ft * 0.001f * + (physics.CabActive ? physics.CabActive : vehicle.ctOwner ? vehicle.ctOwner->Controlling()->CabActive : 1) + 0.001f, - mover.Fb * 0.001f, mover.Adhesive(mover.RunningTrack.friction), (mover.SlippingWheels ? " (!)" : ""), + physics.Fb * 0.001f, physics.Adhesive(physics.RunningTrack.friction), (physics.SlippingWheels ? " (!)" : ""), // acceleration - mover.AccSVBased, mover.AccN + 0.001f, std::string(std::abs(mover.RunningShape.R) > 10000.0 ? "~0" : to_string(mover.RunningShape.R, 0)).c_str(), + physics.AccSVBased, physics.AccN + 0.001f, std::string(std::abs(physics.RunningShape.R) > 10000.0 ? "~0" : to_string(physics.RunningShape.R, 0)).c_str(), // velocity - vehicle.GetVelocity(), mover.DistCounter, + vehicle.GetVelocity(), physics.DistCounter, // position vehicle.GetPosition().x, vehicle.GetPosition().y, vehicle.GetPosition().z); @@ -249,8 +249,8 @@ void ui::vehicleparams_panel::render_contents() while (vehicle_iter) { - TrainsetPowerMeter.first += vehicle_iter->MoverParameters->EnergyMeter.first; - TrainsetPowerMeter.second += vehicle_iter->MoverParameters->EnergyMeter.second; + TrainsetPowerMeter.first += vehicle_iter->physics->EnergyMeter.first; + TrainsetPowerMeter.second += vehicle_iter->physics->EnergyMeter.second; vehicle_iter = vehicle_iter->Prev(); } @@ -262,7 +262,7 @@ void ui::vehicleparams_panel::render_contents() ImGui::TextUnformatted(buffer.data()); } - draw_mini(mover); + draw_mini(physics); if (ImGui::Button(STR_C("Radiostop"))) m_relay.post(user_command::radiostopsend, 0.0, 0.0, GLFW_PRESS, 0, vehicle_ptr->GetPosition()); @@ -293,7 +293,7 @@ void ui::vehicleparams_panel::render_contents() if (ImGui::IsItemDeactivated()) m_relay.post(user_command::consistreleaser, 0.0, 0.0, GLFW_RELEASE, 0, glm::vec3(0.0f), &vehicle_ptr->name()); - if (vehicle_ptr->MoverParameters->V < 0.01) + if (vehicle_ptr->physics->V < 0.01) { if (ImGui::Button(STR_C("Move +500m"))) m_relay.post(user_command::dynamicmove, 500.0, 0.0, GLFW_PRESS, 0, glm::vec3(0.0f), &vehicle_ptr->name()); diff --git a/widgets/vehicleparams.h b/widgets/vehicleparams.h index 787e1e819..d8eb0910e 100644 --- a/widgets/vehicleparams.h +++ b/widgets/vehicleparams.h @@ -14,7 +14,7 @@ class vehicleparams_panel : public ui_panel texture_handle vehicle_mini; void draw_infobutton(const char *str, ImVec2 pos = ImVec2(-1.0f, -1.0f), const ImVec4 color = ImVec4(1.0f, 1.0f, 0.0f, 1.0f)); - void draw_mini(const TMoverParameters &mover); + void draw_mini(const physics::Vehicle &physics); public: vehicleparams_panel(const std::string &vehicle); diff --git a/world/Event.cpp b/world/Event.cpp index acd53908c..d76749dc6 100644 --- a/world/Event.cpp +++ b/world/Event.cpp @@ -34,7 +34,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "utilities/Logs.h" #include "widgets/map_objects.h" -#include "physics/mover.h" +#include "physics/vehicle.h" void basic_event::event_conditions::bind( basic_event::node_sequence *Nodes ) { @@ -722,7 +722,7 @@ putvalues_event::run_() { else { // przekazanie do pojazdu WriteLog( " Vehicle: [" + m_activator->name() +"]" ); - m_activator->MoverParameters->PutCommand( + m_activator->physics->PutCommand( m_input.data_text, m_input.data_value_1, m_input.data_value_2, @@ -1042,30 +1042,30 @@ whois_event::run_() { -1.0 ) }; targetcell->UpdateValues( - m_activator->MoverParameters->TypeName, // typ pojazdu + m_activator->physics->TypeName, // typ pojazdu consistbrakelevel, collisiondistance, m_input.flags & ( flags::text | flags::value1 | flags::value2 ) ); WriteLog( "Type: WhoIs (" + std::to_string( m_input.flags ) + ") - " - + "[type: " + m_activator->MoverParameters->TypeName + "], " + + "[type: " + m_activator->physics->TypeName + "], " + "[consist brake level: " + to_string( consistbrakelevel, 2 ) + "], " + "[obstacle distance: " + to_string( collisiondistance, 2 ) + " m]" ); } else { // jeśli parametry ładunku targetcell->UpdateValues( - m_activator->MoverParameters->LoadType.name, // nazwa ładunku - m_activator->MoverParameters->LoadAmount, // aktualna ilość - m_activator->MoverParameters->MaxLoad, // maksymalna ilość + m_activator->physics->LoadType.name, // nazwa ładunku + m_activator->physics->LoadAmount, // aktualna ilość + m_activator->physics->MaxLoad, // maksymalna ilość m_input.flags & ( flags::text | flags::value1 | flags::value2 ) ); WriteLog( "Type: WhoIs (" + std::to_string( m_input.flags ) + ") - " - + "[load type: " + m_activator->MoverParameters->LoadType.name + "], " - + "[current load: " + to_string( m_activator->MoverParameters->LoadAmount, 2 ) + "], " - + "[max load: " + to_string( m_activator->MoverParameters->MaxLoad, 2 ) + "]" ); + + "[load type: " + m_activator->physics->LoadType.name + "], " + + "[current load: " + to_string( m_activator->physics->LoadAmount, 2 ) + "], " + + "[max load: " + to_string( m_activator->physics->MaxLoad, 2 ) + "]" ); } } // +8 @@ -1073,14 +1073,14 @@ whois_event::run_() { targetcell->UpdateValues( m_activator->asDestination, // adres docelowy m_activator->DirectionGet(), // kierunek pojazdu względem czoła składu (1=zgodny,-1=przeciwny) - m_activator->MoverParameters->Power, // moc pojazdu silnikowego: 0 dla wagonu + m_activator->physics->Power, // moc pojazdu silnikowego: 0 dla wagonu m_input.flags & ( flags::text | flags::value1 | flags::value2 ) ); WriteLog( "Type: WhoIs (" + std::to_string( m_input.flags ) + ") - " + "[destination: " + m_activator->asDestination + "], " + "[direction: " + std::to_string( m_activator->DirectionGet() ) + "], " - + "[engine power: " + to_string( m_activator->MoverParameters->Power, 2 ) + "]" ); + + "[engine power: " + to_string( m_activator->physics->Power, 2 ) + "]" ); } // +0 else { diff --git a/world/Road.cpp b/world/Road.cpp index 58b5fd575..39396b87f 100644 --- a/world/Road.cpp +++ b/world/Road.cpp @@ -20,7 +20,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/parser.h" #include "utilities/utilities.h" -#include "physics/mover.h" +#include "physics/vehicle.h" namespace { @@ -3161,8 +3161,8 @@ void junction_node::update(double const Deltatime) if (first != nullptr) { gate.distance = nearest; - gate.speed = std::abs(first->MoverParameters->V); - gate.halflength = 0.5 * first->MoverParameters->Dim.L; + gate.speed = std::abs(first->physics->V); + gate.halflength = 0.5 * first->physics->Dim.L; gate.taken = ways_of(gate, first); gate.active = gate.distance < std::max(gate_zone, gate.speed * gate_gap) + gate.halflength; } diff --git a/world/RoadPoint.cpp b/world/RoadPoint.cpp index 15ae891ad..f3e8b89ba 100644 --- a/world/RoadPoint.cpp +++ b/world/RoadPoint.cpp @@ -26,7 +26,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/parser.h" #include "utilities/utilities.h" -#include "physics/mover.h" +#include "physics/vehicle.h" namespace { @@ -860,7 +860,7 @@ void roadpoint_node::prepare() } pooled_vehicle entry; entry.vehicle = vehicle; - entry.velocity = vehicle->MoverParameters->V; + entry.velocity = vehicle->physics->V; m_pool.emplace_back(entry); // ...which is taken off the road right away, the way the vehicles leaving the scenery are, to wait for its turn if (vehicle->MyTrack != nullptr) @@ -998,7 +998,7 @@ void roadpoint_node::update_spawn(double const Deltatime) entry.standing = 0.0; continue; } - auto const speed{vehicle->MoverParameters->V}; + auto const speed{vehicle->physics->V}; // forward is the way it went when it was put on the road auto const backwards{speed * entry.velocity < 0.0 && std::abs(speed) > reverse_speed}; if (std::abs(speed) > stuck_speed || simulation::Roadpoints.holds(*vehicle)) @@ -1061,9 +1061,9 @@ void roadpoint_node::update_spawn(double const Deltatime) auto *vehicle{entry.vehicle}; // it comes back the way it was made: whole, at speed, with the driver told to drive on vehicle->bEnabled = true; - vehicle->MoverParameters->repair_damage(); - vehicle->MoverParameters->V = entry.velocity; - vehicle->place_on_track(m_lanes.front(), m_offset + 0.5 * vehicle->MoverParameters->Dim.L, false); + vehicle->physics->repair_damage(); + vehicle->physics->V = entry.velocity; + vehicle->place_on_track(m_lanes.front(), m_offset + 0.5 * vehicle->physics->Dim.L, false); if (vehicle->Mechanik != nullptr) { // the same order a vehicle put in the scenery gets; it has the driver forget the road they knew @@ -1079,7 +1079,7 @@ void roadpoint_node::update_despawn() { for (auto *vehicle : lane->Dynamics) { - if (vehicle == nullptr || false == vehicle->bEnabled || vehicle->MoverParameters->CategoryFlag != 2) + if (vehicle == nullptr || false == vehicle->bEnabled || vehicle->physics->CategoryFlag != 2) { continue; } @@ -1088,7 +1088,7 @@ void roadpoint_node::update_despawn() // not the one the user sits in continue; } - if (planar_distance(vehicle->GetPosition(), m_state.position) > m_state.radius + 0.5 * vehicle->MoverParameters->Dim.L) + if (planar_distance(vehicle->GetPosition(), m_state.position) > m_state.radius + 0.5 * vehicle->physics->Dim.L) { continue; } diff --git a/world/Track.cpp b/world/Track.cpp index 6e2824756..06aa6ce00 100644 --- a/world/Track.cpp +++ b/world/Track.cpp @@ -31,7 +31,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "utilities/Logs.h" #include "rendering/renderer.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include @@ -2344,7 +2344,7 @@ void trail_switch( TTrack &Track, int const i, TDynamicObject const *o ) { Track.Switch(i); // jeśli się tu nie przełączy, to każdy pojazd powtórzy event rozrprucia if( Track.SwitchExtension->m_movablenose && o != nullptr ) { // the wheels can't push the nose of the frog over, the vehicle runs off the rails at it - o->MoverParameters->Derail( TRAILED_SWITCH ); + o->physics->Derail( TRAILED_SWITCH ); } } diff --git a/world/TrackBuckle.cpp b/world/TrackBuckle.cpp index f0328d8d1..7dabf4c0b 100644 --- a/world/TrackBuckle.cpp +++ b/world/TrackBuckle.cpp @@ -15,7 +15,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Globals.h" #include "utilities/Logs.h" #include "vehicle/DynObj.h" -#include "physics/mover.h" +#include "physics/vehicle.h" #include @@ -214,8 +214,8 @@ void TTrack::buckle_pass_enter( TDynamicObject const &Dynamic ) { return; } ++m_buckle_passes; - auto const *mover { Dynamic.MoverParameters }; - auto const train { mover != nullptr && track_buckle::stirs( std::abs( mover->Vel ), mover->BrakePress > 0.5 ) }; + auto const *physics { Dynamic.physics }; + auto const train { physics != nullptr && track_buckle::stirs( std::abs( physics->Vel ), physics->BrakePress > 0.5 ) }; auto const rise { rail_temperature_now() - m_cwr.neutral }; auto const draw { track_buckle::draw( buckle_key(), Global.random_seed, track_buckle::pass, m_buckle_passes ) }; m_buckle_armed = ( track_buckle::decide( rise, buckle_limits(), train, draw ) != track_buckle::verdict::none ); diff --git a/world/TrkFoll.cpp b/world/TrkFoll.cpp index 6477f9763..8013af966 100644 --- a/world/TrkFoll.cpp +++ b/world/TrkFoll.cpp @@ -21,7 +21,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/DynObj.h" #include "vehicle/Driver.h" #include "utilities/Logs.h" -#include "physics/mover.h" +#include "physics/vehicle.h" namespace { @@ -127,7 +127,7 @@ TTrack * TTrackFollower::SetCurrentTrack(TTrack *pTrack, int end) pCurrentTrack = pTrack; pCurrentSegment = pCurrentTrack != nullptr ? pCurrentTrack->CurrentSegment() : nullptr; if (!pCurrentTrack) - Error(Owner->MoverParameters->Name + " at NULL track"); + Error(Owner->physics->Name + " at NULL track"); return pCurrentTrack; }; @@ -345,7 +345,7 @@ bool TTrackFollower::Move(double fDistance, bool bPrimary) { // gdy zostaje na tym samym torze (przesuwanie już nie zmienia toru) if (bPrimary) { // tylko gdy początkowe ustawienie, dodajemy eventy stania do kolejki - if (Owner->MoverParameters->CabOccupied != 0) { + if (Owner->physics->CabOccupied != 0) { pCurrentTrack->QueueEvents( pCurrentTrack->m_events1, Owner, -1.0 ); pCurrentTrack->QueueEvents( pCurrentTrack->m_events2, Owner, -1.0 ); diff --git a/world/station.cpp b/world/station.cpp index 8ac77db30..40c343118 100644 --- a/world/station.cpp +++ b/world/station.cpp @@ -13,7 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/utilities.h" #include "vehicle/DynObj.h" #include "world/mtable.h" -#include "physics/mover.h" +#include "physics/vehicle.h" namespace simulation { @@ -43,7 +43,7 @@ basic_station::update_load( TDynamicObject *First, Mtable::TTrainParameters &Sch auto *vehicle { First }; while( vehicle != nullptr ) { - auto ¶meters { *vehicle->MoverParameters }; + auto ¶meters { *vehicle->physics }; if( parameters.Doors.range == 0.f ) { goto next; } From 2753994bf62f86435b6b201509f474d5b93902be Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 00:28:52 +0100 Subject: [PATCH 028/123] refactor(physics): the blending, the holding brake and the spring brake in physics::Braking The first part of the braking of physics::Vehicle becomes a component of its own, brakes (physics/components/braking.h), with the fields named in English: blending (BrakeBlending) the MED_* of the Blending section and their timers: maxSpeed, minSpeed, referenceSpeed, maxDeceleration, epCorrection(Time, Timer), loadCorrection, minEdDemand, edForceFactor, edFirstDelay, edNextDelay, edDelayTimer emuDynamic (EmuDynamicBrake) the DCEMUED_*: checkedCoupler, epMaxSpeed, epMinCurrent, epDelay holding (HoldingBrake) StopBrakeDecc, StopBrakeReleaseDelay, the timer: deceleration, releaseDelay, releaseTimer spring (SpringBrake) the nested spring_brake (SBP is pressure, ShuttOff shutOff, MultiTractionCoupler controlCouplings ...) and the ReleaseParkingBySpringBrake*, SpringBrakeCutsOffDrive, SpringBrakeDriveEmergencyVel of the vehicle Each field says in its comment the key of the .fiz it comes from; the keys, the golden channel names and the texts are as they were. The struct is Braking, not BrakeSystem, the name of the kind of the train brake the vehicle already has. Kept as it was, to look at: the spring brake reads valveOffArea from the key ValveOnArea and valveOnArea from ValveOffArea. No change in behaviour: 1149/1149 tests, golden traces exact against staging 62f7a29b. --- application/driverhints.cpp | 4 +- application/driveruipanels.cpp | 2 +- physics/components/body.cpp | 12 ++-- physics/components/braking.h | 99 ++++++++++++++++++++++++++++++ physics/components/cab.cpp | 2 +- physics/components/commands.cpp | 6 +- physics/components/controllers.cpp | 4 +- physics/components/fizsections.cpp | 74 +++++++++++----------- physics/components/pneumatics.cpp | 54 ++++++++-------- physics/components/setup.cpp | 10 +-- physics/vehicle.h | 62 ++----------------- simulation/blackboxrecorder.cpp | 2 +- tests/unit/drive.cpp | 2 +- tests/unit/golden.cpp | 2 +- tests/unit/test_cab.cpp | 6 +- tests/unit/test_commands.cpp | 2 +- tests/unit/test_elf_controller.cpp | 16 ++--- tests/unit/test_pullee.cpp | 18 +++--- vehicle/ai/consist.cpp | 6 +- vehicle/ai/controls.cpp | 10 +-- vehicle/ai/engine.cpp | 2 +- vehicle/ai/force.cpp | 4 +- vehicle/cab/equipmentcommands.cpp | 4 +- vehicle/cab/setup.cpp | 4 +- vehicle/cab/update.cpp | 10 +-- vehicle/dynamic/sounds.cpp | 4 +- vehicle/dynamic/update.cpp | 30 ++++----- 27 files changed, 249 insertions(+), 202 deletions(-) create mode 100644 physics/components/braking.h diff --git a/application/driverhints.cpp b/application/driverhints.cpp index 721636949..76203813e 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -467,7 +467,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this]( float const /*Parameter*/ ) { - return occupied->SpringBrake.Activate == true; } ); + return occupied->brakes.spring.activate == true; } ); break; } case driver_hint::springbrakeoff: { @@ -478,7 +478,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this]( float const /*Parameter*/ ) { - return occupied->SpringBrake.Activate == false; } ); + return occupied->brakes.spring.activate == false; } ); break; } // manual brake diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index f811d8df0..bb86961f8 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -930,7 +930,7 @@ debug_panel::update_section_vehicle( std::vector &Output ) { physics.LocalBrakePosA, physics.LocalBrakePosAEIM, static_cast(physics.ManualBrakePos) / static_cast(ManualBrakePosNo), - physics.SpringBrake.Activate ? 1.f : 0.f, + physics.brakes.spring.activate ? 1.f : 0.f, // cylinders physics.BrakePress, physics.LocBrakePress, diff --git a/physics/components/body.cpp b/physics/components/body.cpp index f3da81add..d969b7d9b 100644 --- a/physics/components/body.cpp +++ b/physics/components/body.cpp @@ -501,11 +501,11 @@ void physics::Vehicle::compute_movement_(double const Deltatime) UpdateBatteryVoltage(Deltatime); UpdateScndPipePressure(Deltatime); // druga rurka, youBy - if ((DCEMUED_CC & 1) != 0 && Couplers[VehicleEnd::front].CouplingFlag.HasAny(Coupling::control)) + if ((brakes.emuDynamic.checkedCoupler & 1) != 0 && Couplers[VehicleEnd::front].CouplingFlag.HasAny(Coupling::control)) { DynamicBrakeEMUStatus &= Couplers[VehicleEnd::front].Connected->DynamicBrakeEMUStatus; } - if ((DCEMUED_CC & 2) != 0 && Couplers[VehicleEnd::rear].CouplingFlag.HasAny(Coupling::control)) + if ((brakes.emuDynamic.checkedCoupler & 2) != 0 && Couplers[VehicleEnd::rear].CouplingFlag.HasAny(Coupling::control)) { DynamicBrakeEMUStatus &= Couplers[VehicleEnd::rear].Connected->DynamicBrakeEMUStatus; } @@ -1019,8 +1019,8 @@ double physics::Vehicle::BrakeForce(TTrackParam const & /*Track*/) } // the spring brake of a vehicle prepared for hauling (PulleeMode) is released by hand: no force, whatever its cylinder has - if (SpringBrake.IsReady && false == PulleeMode) - K += std::max(0.0, SpringBrake.MinForcePressure - SpringBrake.Cylinder->P()) * SpringBrake.MaxBrakeForce; + if (brakes.spring.isReady && false == PulleeMode) + K += std::max(0.0, brakes.spring.minForcePressure - brakes.spring.cylinder->P()) * brakes.spring.maxForce; u = (BrakePress * P2FTrans - BrakeCylSpring) * BrakeCylMult[0] - BrakeSlckAdj; if (u * BrakeRigEff > Ntotal) // histereza na nacisku klockow @@ -1273,7 +1273,7 @@ bool physics::Vehicle::brakes_changed_asleep() const if (PhysicActivation) return false; constexpr double pressure_change{0.05}; // [bar] - return std::abs(BrakePress - sleep_brakes.cylinder) > pressure_change || std::abs(SpringBrake.SBP - sleep_brakes.spring) > pressure_change || + return std::abs(BrakePress - sleep_brakes.cylinder) > pressure_change || std::abs(brakes.spring.pressure - sleep_brakes.spring) > pressure_change || ManualBrakePos != sleep_brakes.manual || std::abs(LocalBrakePosA - sleep_brakes.local) > 0.01; } @@ -1296,7 +1296,7 @@ bool physics::Vehicle::switch_physics(bool const State, wake_cause const Cause) else { // what the brake force of the last step came from, which it keeps while asleep (brakes_changed_asleep()) - sleep_brakes = {BrakePress, SpringBrake.SBP, ManualBrakePos, LocalBrakePosA}; + sleep_brakes = {BrakePress, brakes.spring.pressure, ManualBrakePos, LocalBrakePosA}; } return true; diff --git a/physics/components/braking.h b/physics/components/braking.h new file mode 100644 index 000000000..c78bb262c --- /dev/null +++ b/physics/components/braking.h @@ -0,0 +1,99 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +// the braking of a vehicle beside its air brake valves: the blending of the brakes of a unit, the holding brake, the +// spring brake. Held by physics::Vehicle as brakes + +#pragma once + +#include + +class TReservoir; + +namespace physics +{ + +// the blending of the electro-pneumatic and the electrodynamic brake of a unit (MED, the Blending section of the .fiz) +struct BrakeBlending +{ + double maxSpeed = 0; // MED_Vmax: the top speed the momentary force of the EP brake is computed for [km/h] + double minSpeed = 0; // MED_Vmin: the lowest speed the momentary force of the EP brake is computed for [km/h] + double referenceSpeed = 0; // MED_Vref: the speed the available force of the EP brake is computed for [km/h] + double maxDeceleration{9.81}; // MED_amax: the most deceleration of the service braking [m/s2] + bool epCorrection = false; // MED_EPVC: the force of the EP brake corrected while the ED brake is unavailable + double epCorrectionTime = 7; // MED_EPVC_Time: how long that correction lasts [s] + bool loadCorrection = false; // MED_Ncor: the braking force corrected by the load on the axles + double minEdDemand = 0; // MED_MinBrakeReqED: below this demand only the EP brake brakes, the ED brake stays off + double edForceFactor = 1; // MED_FrEDFactor: the factor of the force of the ED brake, to correct the blending + double edFirstDelay = 0; // MED_FirstDelayED: the delay of the ED brake coming in, the first time [s] + double edNextDelay = 0; // MED_ScndDelayED: the delay of the ED brake growing, the times after [s] + // the state + double epCorrectionTimer = 0; // how long the force of the EP brake has been corrected [s] + double edDelayTimer = 0; // the count of the delay of the ED brake [s] +}; + +// the electrodynamic brake of a DC unit and the EP brake beside it (the DCEMUED section of the .fiz) +struct EmuDynamicBrake +{ + int checkedCoupler{0}; // CouplerCheck: the coupler the ED brake of the unit is checked on + double epMaxSpeed{0.0}; // EP_max_Vel: the top speed the EP brake works at with the ED brake of the unit on (trailers) + double epMinCurrent{0.0}; // EP_min_Im: the current the EP brake stops working at with the ED brake of the car on (motor cars) + double epDelay{0.0}; // EP_delay: the delay of the EP brake coming in while the ED brake brakes +}; + +// the holding brake of a unit with the MED: it holds the unit standing, and lets go once power is demanded +struct HoldingBrake +{ + double deceleration = 0.0; // SBD: the deceleration it holds the unit with [m/s2] + // SBDReleaseDelay: it lets go only once power has been demanded for this long [s]; 0 lets it go at the first demand + double releaseDelay = 0.0; + double releaseTimer = 0.0; // how long power has been demanded without a break [s] +}; + +// the spring brake: the spring of its cylinder brakes when the air leaves it (the SpringBrake section of the .fiz) +struct SpringBrake +{ + std::shared_ptr cylinder; + // the inputs + bool activate{false}; // switched on or off in service: the main valve or switch + bool shutOff{true}; // shut off for a fault: the valve in the pneumatic container + bool release{false}; // the emergency release rod + // the outputs + bool isReady{false}; // ready to brake: the cylinder armed, the spring tensioned + bool isActive{false}; // braking + double pressure{0.0}; // the pressure in the cylinder + // the configuration + bool pneumaticConnection{false}; // connected to the cylinders of the air brake + double maxSetPressure{0.0}; // MaxSP: the most pressure for the brake switched off + double resetPressure{0.0}; // ResetP: the pressure that arms the cylinder + double minForcePressure{0.1}; // MinFP: the least pressure of no force + double maxForce{0.0}; // MBF: the most force of the spring on the brake shoes or pads + double pressureOn{-2.0}; // PressOn: the pressure the brake turns on at + double pressureOff{-1.0}; // PressOff: the pressure the brake turns off at + double valveOffArea{0.0}; // the area of the filling valve (read from the key ValveOnArea) + double valveOnArea{0.0}; // the area of the dumping valve (read from the key ValveOffArea) + double valvePneumaticArea{0.0}; // ValvePNBArea: the area of the bypass to the cylinders of the air brake + int controlCouplings{127}; // MTC: the couplings the command needs to pass on, the number of the couplings of the .fiz + // of the vehicle with it + bool releasesParking{false}; // ReleaseParkingBySpringBrake + bool releasesParkingWithDoorOpen{false}; // ReleaseParkingBySpringBrakeWhenDoorIsOpen + bool cutsOffDrive{true}; // SpringBrakeCutsOffDrive + double driveEmergencySpeed{-1}; // SpringBrakeDriveEmergencyVel +}; + +// the braking of a vehicle beside its air brake valves +struct Braking +{ + BrakeBlending blending; + EmuDynamicBrake emuDynamic; + HoldingBrake holding; + SpringBrake spring; +}; + +} // namespace physics diff --git a/physics/components/cab.cpp b/physics/components/cab.cpp index 0ac0324ce..af1d27849 100644 --- a/physics/components/cab.cpp +++ b/physics/components/cab.cpp @@ -202,7 +202,7 @@ bool physics::Vehicle::PulleeModeSwitch(bool const State) if (PulleeMode) { DecManualBrakeLevel(ManualBrakePosNo); - SpringBrake.Activate = false; + brakes.spring.activate = false; SecuritySystem.set_enabled(false); Battery = false; } diff --git a/physics/components/commands.cpp b/physics/components/commands.cpp index 22d1b8558..676180b84 100644 --- a/physics/components/commands.cpp +++ b/physics/components/commands.cpp @@ -275,9 +275,9 @@ bool physics::Vehicle::RunBrakeCommand(VehicleCommand const Command, double CVal if (CValue1 < 0.001) DynamicBrakeEMUStatus = true; double temp1 = CValue1; - if (DCEMUED_EP_max_Vel > 0.001 && Vel > DCEMUED_EP_max_Vel && DynamicBrakeEMUStatus) + if (brakes.emuDynamic.epMaxSpeed > 0.001 && Vel > brakes.emuDynamic.epMaxSpeed && DynamicBrakeEMUStatus) temp1 = 0; - if (DCEMUED_EP_min_Im > 0.001 && abs(Im) > DCEMUED_EP_min_Im && DynamicBrakeEMUStatus) + if (brakes.emuDynamic.epMinCurrent > 0.001 && abs(Im) > brakes.emuDynamic.epMinCurrent && DynamicBrakeEMUStatus) temp1 = 0; Hamulec->SetEPS(temp1); TUHEX_StageActual = static_cast(CValue1); @@ -327,7 +327,7 @@ bool physics::Vehicle::RunBrakeEquipmentCommand(VehicleCommand const Command, do { if (Power24vIsAvailable || Power110vIsAvailable) { - SpringBrake.Activate = CValue1 > 0; + brakes.spring.activate = CValue1 > 0; OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } else diff --git a/physics/components/controllers.cpp b/physics/components/controllers.cpp index 902eecc4b..3a2a61e0e 100644 --- a/physics/components/controllers.cpp +++ b/physics/components/controllers.cpp @@ -1212,8 +1212,8 @@ void physics::Vehicle::EIMICTraxxLocalBrake(double dt) // the value limited by the power, the spring brake, the pipe lock, the direction and the doors' permits void physics::Vehicle::EIMICLimit() { - auto const eimicpowerenabled{(MainCircuitPowered() || Power == 0.0) && (!SpringBrake.IsActive || !SpringBrakeCutsOffDrive) && !LockPipe && DirAbsolute != 0}; - auto const eimicdoorenabled{(SpringBrake.IsActive && ReleaseParkingBySpringBrakeWhenDoorIsOpen)}; + auto const eimicpowerenabled{(MainCircuitPowered() || Power == 0.0) && (!brakes.spring.isActive || !brakes.spring.cutsOffDrive) && !LockPipe && DirAbsolute != 0}; + auto const eimicdoorenabled{(brakes.spring.isActive && brakes.spring.releasesParkingWithDoorOpen)}; double eimic_max = 0.0; if (Doors.instances[VehicleSide::left].open_permit == false && Doors.instances[VehicleSide::right].open_permit == false) { diff --git a/physics/components/fizsections.cpp b/physics/components/fizsections.cpp index a58837090..e4331ef32 100644 --- a/physics/components/fizsections.cpp +++ b/physics/components/fizsections.cpp @@ -883,12 +883,12 @@ void physics::Vehicle::LoadFIZ_CntrlControllers(std::string const &line) extract_value(AutomaticCabActivation, "AutomaticCabActivation", line, ""); extract_value(InactiveCabFlag, "InactiveCabFlag", line, ""); - extract_value(StopBrakeDecc, "SBD", line, ""); - extract_value(StopBrakeReleaseDelay, "SBDReleaseDelay", line, ""); // the holding brake waits for the power demand this long, s - extract_value(ReleaseParkingBySpringBrake, "ReleaseParkingBySpringBrake", line, ""); - extract_value(ReleaseParkingBySpringBrakeWhenDoorIsOpen, "ReleaseParkingBySpringBrakeWhenDoorIsOpen", line, ""); - extract_value(SpringBrakeCutsOffDrive, "SpringBrakeCutsOffDrive", line, ""); - extract_value(SpringBrakeDriveEmergencyVel, "SpringBrakeDriveEmergencyVel", line, ""); + extract_value(brakes.holding.deceleration, "SBD", line, ""); + extract_value(brakes.holding.releaseDelay, "SBDReleaseDelay", line, ""); // the holding brake waits for the power demand this long, s + extract_value(brakes.spring.releasesParking, "ReleaseParkingBySpringBrake", line, ""); + extract_value(brakes.spring.releasesParkingWithDoorOpen, "ReleaseParkingBySpringBrakeWhenDoorIsOpen", line, ""); + extract_value(brakes.spring.cutsOffDrive, "SpringBrakeCutsOffDrive", line, ""); + extract_value(brakes.spring.driveEmergencySpeed, "SpringBrakeDriveEmergencyVel", line, ""); extract_value(HideDirStatusWhenMoving, "HideDirStatusWhenMoving", line, ""); extract_value(HideDirStatusSpeed, "HideDirStatusSpeed", line, ""); @@ -1020,25 +1020,25 @@ void physics::Vehicle::LoadFIZ_CntrlStarts(std::string const &line) void physics::Vehicle::LoadFIZ_Blending(std::string const &line) { - extract_value(MED_Vmax, "MED_Vmax", line, std::to_string(Vmax)); - extract_value(MED_Vmin, "MED_Vmin", line, "0"); - extract_value(MED_Vref, "MED_Vref", line, std::to_string(Vmax)); - extract_value(MED_amax, "MED_amax", line, "9.81"); - extract_value(MED_EPVC, "MED_EPVC", line, ""); - extract_value(MED_Ncor, "MED_Ncor", line, ""); - extract_value(MED_MinBrakeReqED, "MED_MinBrakeReqED", line, ""); - extract_value(MED_FrED_factor, "MED_FrEDFactor", line, ""); - extract_value(MED_ED_Delay1, "MED_FirstDelayED", line, ""); - extract_value(MED_ED_Delay2, "MED_ScndDelayED", line, ""); + extract_value(brakes.blending.maxSpeed, "MED_Vmax", line, std::to_string(Vmax)); + extract_value(brakes.blending.minSpeed, "MED_Vmin", line, "0"); + extract_value(brakes.blending.referenceSpeed, "MED_Vref", line, std::to_string(Vmax)); + extract_value(brakes.blending.maxDeceleration, "MED_amax", line, "9.81"); + extract_value(brakes.blending.epCorrection, "MED_EPVC", line, ""); + extract_value(brakes.blending.loadCorrection, "MED_Ncor", line, ""); + extract_value(brakes.blending.minEdDemand, "MED_MinBrakeReqED", line, ""); + extract_value(brakes.blending.edForceFactor, "MED_FrEDFactor", line, ""); + extract_value(brakes.blending.edFirstDelay, "MED_FirstDelayED", line, ""); + extract_value(brakes.blending.edNextDelay, "MED_ScndDelayED", line, ""); } void physics::Vehicle::LoadFIZ_DCEMUED(std::string const &line) { - extract_value(DCEMUED_CC, "CouplerCheck", line, "0"); - extract_value(DCEMUED_EP_max_Vel, "EP_max_Vel", line, "0"); - extract_value(DCEMUED_EP_min_Im, "EP_min_Im", line, "0"); - extract_value(DCEMUED_EP_delay, "EP_delay", line, "0"); + extract_value(brakes.emuDynamic.checkedCoupler, "CouplerCheck", line, "0"); + extract_value(brakes.emuDynamic.epMaxSpeed, "EP_max_Vel", line, "0"); + extract_value(brakes.emuDynamic.epMinCurrent, "EP_min_Im", line, "0"); + extract_value(brakes.emuDynamic.epDelay, "EP_delay", line, "0"); } void physics::Vehicle::LoadFIZ_SpringBrake(std::string const &line) @@ -1046,23 +1046,23 @@ void physics::Vehicle::LoadFIZ_SpringBrake(std::string const &line) double vol{1.0}; extract_value(vol, "Volume", line, "1"); - if (!SpringBrake.Cylinder) - SpringBrake.Cylinder = std::make_shared(); - SpringBrake.Cylinder->CreateCap(vol); - extract_value(SpringBrake.MaxBrakeForce, "MBF", line, ""); - extract_value(SpringBrake.MaxSetPressure, "MaxSP", line, ""); - extract_value(SpringBrake.ResetPressure, "ResetP", line, ""); - extract_value(SpringBrake.MinForcePressure, "MinFP", line, ""); - extract_value(SpringBrake.PressureOff, "PressOff", line, ""); - extract_value(SpringBrake.PressureOn, "PressOn", line, ""); - extract_value(SpringBrake.ValveOffArea, "ValveOnArea", line, ""); - extract_value(SpringBrake.ValveOnArea, "ValveOffArea", line, ""); - extract_value(SpringBrake.ValvePNBrakeArea, "ValvePNBArea", line, ""); - SpringBrake.PNBrakeConnection = SpringBrake.ValvePNBrakeArea > 0; - extract_value(SpringBrake.MultiTractionCoupler, "MTC", line, ""); - SpringBrake.ShuttOff = false; - SpringBrake.Activate = false; - SpringBrake.IsReady = true; + if (!brakes.spring.cylinder) + brakes.spring.cylinder = std::make_shared(); + brakes.spring.cylinder->CreateCap(vol); + extract_value(brakes.spring.maxForce, "MBF", line, ""); + extract_value(brakes.spring.maxSetPressure, "MaxSP", line, ""); + extract_value(brakes.spring.resetPressure, "ResetP", line, ""); + extract_value(brakes.spring.minForcePressure, "MinFP", line, ""); + extract_value(brakes.spring.pressureOff, "PressOff", line, ""); + extract_value(brakes.spring.pressureOn, "PressOn", line, ""); + extract_value(brakes.spring.valveOffArea, "ValveOnArea", line, ""); + extract_value(brakes.spring.valveOnArea, "ValveOffArea", line, ""); + extract_value(brakes.spring.valvePneumaticArea, "ValvePNBArea", line, ""); + brakes.spring.pneumaticConnection = brakes.spring.valvePneumaticArea > 0; + extract_value(brakes.spring.controlCouplings, "MTC", line, ""); + brakes.spring.shutOff = false; + brakes.spring.activate = false; + brakes.spring.isReady = true; } void physics::Vehicle::LoadFIZ_Light(std::string const &line) diff --git a/physics/components/pneumatics.cpp b/physics/components/pneumatics.cpp index 4ba3c0276..84d5eb838 100644 --- a/physics/components/pneumatics.cpp +++ b/physics/components/pneumatics.cpp @@ -248,11 +248,11 @@ bool physics::Vehicle::SpringBrakeActivate(bool State) { if (Power24vIsAvailable || Power110vIsAvailable) { - SendCtrlToNext(VehicleCommand::springBrakeActivate, int(State), CabActive, CouplingSet::FromBits(SpringBrake.MultiTractionCoupler)); + SendCtrlToNext(VehicleCommand::springBrakeActivate, int(State), CabActive, CouplingSet::FromBits(brakes.spring.controlCouplings)); - if (SpringBrake.Activate != State) + if (brakes.spring.activate != State) { - SpringBrake.Activate = State; + brakes.spring.activate = State; wake_for_brake(); return true; } @@ -266,9 +266,9 @@ bool physics::Vehicle::SpringBrakeActivate(bool State) // ************************************************************************************************* bool physics::Vehicle::SpringBrakeShutOff(bool State) { - if (SpringBrake.ShuttOff != State) + if (brakes.spring.shutOff != State) { - SpringBrake.ShuttOff = State; + brakes.spring.shutOff = State; return true; } else @@ -281,9 +281,9 @@ bool physics::Vehicle::SpringBrakeShutOff(bool State) // ************************************************************************************************* bool physics::Vehicle::SpringBrakeRelease() { - if (SpringBrake.IsReady && SpringBrake.Cylinder->P() < SpringBrake.MinForcePressure) + if (brakes.spring.isReady && brakes.spring.cylinder->P() < brakes.spring.minForcePressure) { - SpringBrake.IsReady = false; + brakes.spring.isReady = false; wake_for_brake(); return true; } @@ -988,7 +988,7 @@ void physics::Vehicle::UpdateLocalBrakeValve(double dt) } if (SpeedCtrlUnit.Parking) { - lbpa = std::max(lbpa, StopBrakeDecc); + lbpa = std::max(lbpa, brakes.holding.deceleration); } dpLocalValve = LocHandle->GetPF(PulleeMode ? 0.0 : std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); } @@ -1097,7 +1097,7 @@ void physics::Vehicle::UpdateEmergencyValve(double dt) // a vehicle prepared for hauling (PulleeMode) vents it for nothing of its own, only for the alarm chain, // which a train parting sets too auto const ownemergency{RadioStopFlag || (EIMCtrlEmergency && LocalBrakePosA >= 1.0) || (IsMainCtrlEmergencyPos() && IsCabMaster()) || SecuritySystem.is_braking() || - (SpringBrakeDriveEmergencyVel >= 0 && Vel > SpringBrakeDriveEmergencyVel && SpringBrake.IsActive) || + (brakes.spring.driveEmergencySpeed >= 0 && Vel > brakes.spring.driveEmergencySpeed && brakes.spring.isActive) || (0 == CabActive && (InactiveCabFlag & activation::emergencybrake) != 0)}; if (AlarmChainFlag || (ownemergency && false == PulleeMode)) { @@ -1229,9 +1229,9 @@ void physics::Vehicle::UpdateEPBrake() DynamicBrakeEMUStatus = EpForce > 0.001 ? Power110vIsAvailable : true; double temp1 = EpForce; - if (DCEMUED_EP_max_Vel > 0.001 && Vel > DCEMUED_EP_max_Vel && DynamicBrakeEMUStatus) + if (brakes.emuDynamic.epMaxSpeed > 0.001 && Vel > brakes.emuDynamic.epMaxSpeed && DynamicBrakeEMUStatus) temp1 = 0; - if (DCEMUED_EP_min_Im > 0.001 && abs(Im) > DCEMUED_EP_min_Im && DynamicBrakeEMUStatus) + if (brakes.emuDynamic.epMinCurrent > 0.001 && abs(Im) > brakes.emuDynamic.epMinCurrent && DynamicBrakeEMUStatus) temp1 = 0; Hamulec->SetEPS(temp1); TUHEX_StageActual = static_cast(EpForce); @@ -1283,28 +1283,28 @@ void physics::Vehicle::UpdateScndPipePressure(double dt) // ************************************************************************************************* void physics::Vehicle::UpdateSpringBrake(double /*dt*/) { - double BP = SpringBrake.PNBrakeConnection ? BrakePress : 0; - double MSP = SpringBrake.ShuttOff ? 0 : SpringBrake.MaxSetPressure; - if (!SpringBrake.Activate) + double BP = brakes.spring.pneumaticConnection ? BrakePress : 0; + double MSP = brakes.spring.shutOff ? 0 : brakes.spring.maxSetPressure; + if (!brakes.spring.activate) { double desired_press = std::min(std::max(MSP, BP), Pipe2->P()); - double dv = PF(desired_press, SpringBrake.SBP, SpringBrake.ValveOffArea); - SpringBrake.Cylinder->Flow(-dv); + double dv = PF(desired_press, brakes.spring.pressure, brakes.spring.valveOffArea); + brakes.spring.cylinder->Flow(-dv); Pipe2->Flow(std::max(dv, 0.0)); } else { - double dv = PF(BP, SpringBrake.SBP, SpringBrake.ValveOnArea); - SpringBrake.Cylinder->Flow(-dv); + double dv = PF(BP, brakes.spring.pressure, brakes.spring.valveOnArea); + brakes.spring.cylinder->Flow(-dv); } - if (SpringBrake.SBP > SpringBrake.ResetPressure) - SpringBrake.IsReady = true; + if (brakes.spring.pressure > brakes.spring.resetPressure) + brakes.spring.isReady = true; - SpringBrake.IsActive = SpringBrake.SBP < (SpringBrake.IsActive ? SpringBrake.PressureOff : SpringBrake.PressureOn); + brakes.spring.isActive = brakes.spring.pressure < (brakes.spring.isActive ? brakes.spring.pressureOff : brakes.spring.pressureOn); - SpringBrake.Release = false; - SpringBrake.Cylinder->Act(); - SpringBrake.SBP = SpringBrake.Cylinder->P(); + brakes.spring.release = false; + brakes.spring.cylinder->Act(); + brakes.spring.pressure = brakes.spring.cylinder->P(); } namespace { @@ -1611,11 +1611,11 @@ bool physics::Vehicle::UpdateStopBrakeRelease(double const Demand, double const { if (Demand <= 0.0) { - StopBrakeReleaseTimer = 0.0; + brakes.holding.releaseTimer = 0.0; return false; } // the step the demand rises above 0 is time 0 of it, so without the delay the brake lets go at once, as it always did - auto const released{StopBrakeReleaseTimer >= StopBrakeReleaseDelay}; - StopBrakeReleaseTimer += Dt; + auto const released{brakes.holding.releaseTimer >= brakes.holding.releaseDelay}; + brakes.holding.releaseTimer += Dt; return released; } diff --git a/physics/components/setup.cpp b/physics/components/setup.cpp index f5c8944bd..1ad40b41c 100644 --- a/physics/components/setup.cpp +++ b/physics/components/setup.cpp @@ -396,10 +396,10 @@ void physics::Vehicle::CreateBrakePipes() Pipe2 = std::make_shared(); // zabezpieczenie, bo sie PG wywala... :( Pipe->CreateCap((std::max(Dim.L, 14.0) + 0.5) * Spg * 1); // dlugosc x przekroj x odejscia i takie tam Pipe2->CreateCap((std::max(Dim.L, 14.0) + 0.5) * Spg * 1); - if (!SpringBrake.Cylinder) + if (!brakes.spring.cylinder) { - SpringBrake.Cylinder = std::make_shared(); - SpringBrake.Cylinder->CreateCap(1); + brakes.spring.cylinder = std::make_shared(); + brakes.spring.cylinder->CreateCap(1); } } @@ -464,8 +464,8 @@ void physics::Vehicle::SetBraked() { IncManualBrakeLevel(ManualBrakePosNo); } - if (SpringBrake.MaxBrakeForce > 0.0) + if (brakes.spring.maxForce > 0.0) { - SpringBrake.Activate = true; + brakes.spring.activate = true; } } diff --git a/physics/vehicle.h b/physics/vehicle.h index 1b2f5c8d8..7d9e5b8a1 100644 --- a/physics/vehicle.h +++ b/physics/vehicle.h @@ -24,6 +24,7 @@ http://mozilla.org/MPL/2.0/. #include "physics/vehicletypes.h" #include "physics/components/dieselengine.h" #include "physics/components/inductionmotor.h" +#include "physics/components/braking.h" class TractionDrive; @@ -813,31 +814,6 @@ class Vehicle bool is_damaged{false}; // device is damaged }; - struct spring_brake - { - std::shared_ptr Cylinder; - bool Activate{false}; // Input: switching brake on/off in exploitation - main valve/switch - bool ShuttOff{true}; // Input: shutting brake off during failure - valve in pneumatic container - bool Release{false}; // Input: emergency releasing rod - - bool IsReady{false}; // Output: readyness to braking - cylinder is armed, spring is tentioned - bool IsActive{false}; // Output: brake is working - double SBP{0.0}; // Output: pressure in spring brake cylinder - - bool PNBrakeConnection{false}; // Conf: connection to pneumatic brake cylinders - double MaxSetPressure{0.0}; // Conf: Maximal pressure for switched off brake - double ResetPressure{0.0}; // Conf: Pressure for arming brake cylinder - double MinForcePressure{0.1}; // Conf: Minimal pressure for zero force - double MaxBrakeForce{0.0}; // Conf: Maximal tension for brake pads/shoes - double PressureOn{-2.0}; // Conf: Pressure changing ActiveFlag to "On" - double PressureOff{-1.0}; // Conf: Pressure changing ActiveFlag to "Off" - double ValveOffArea{0.0}; // Conf: Area of filling valve - double ValveOnArea{0.0}; // Conf: Area of dumping valve - double ValvePNBrakeArea{0.0}; // Conf: Area of bypass to brake cylinders - - int MultiTractionCoupler{127}; // Conf: Coupling flag necessary for transmitting the command - }; - public: std::string chkPath; bool reload_FIZ(); @@ -915,7 +891,7 @@ class Vehicle std::shared_ptr LocHandle; std::shared_ptr Pipe; std::shared_ptr Pipe2; - spring_brake SpringBrake; + Braking brakes; // the blending, the holding brake, the spring brake (physics/components/braking.h) TLocalBrake LocalBrake = TLocalBrake::NoBrake; /*rodzaj hamulca indywidualnego*/ TBrakePressureTable BrakePressureTable; /*wyszczegolnienie cisnien w rurze*/ @@ -1004,15 +980,6 @@ class Vehicle int ScndInMain{0}; /*zaleznosc bocznika od nastawnika*/ bool MBrake = false; /*Czy jest hamulec reczny*/ double maxTachoSpeed = {0.0}; // maksymalna predkosc na tarczce predkosciomierza analogowego - double StopBrakeDecc = 0.0; - // the holding brake (StopBrakeDecc) of a unit with the MED lets go only once power has been demanded for this long (SBDReleaseDelay, s); - // 0 lets it go at the first demand - double StopBrakeReleaseDelay = 0.0; - double StopBrakeReleaseTimer = 0.0; // how long power has been demanded without a break, s - bool ReleaseParkingBySpringBrake{false}; - bool ReleaseParkingBySpringBrakeWhenDoorIsOpen{false}; - bool SpringBrakeCutsOffDrive{true}; - double SpringBrakeDriveEmergencyVel{-1}; bool HideDirStatusWhenMoving{false}; // Czy gasic lampki kierunku powyzej predkosci zdefiniowanej przez HideDirStatusSpeed int HideDirStatusSpeed{1}; // Predkosc od ktorej lampki kierunku sa wylaczane bool isDoubleClickForMeasureNeeded = {false}; // czy rozpoczecie pomiaru odleglosci odbywa sie po podwojnym wcisnienciu przycisku? @@ -1163,23 +1130,6 @@ class Vehicle int Imaxrpc = 0; // Maksymalny prad rezystora hamowania chlodzonego pasywnie int BRVto = 0; // Czas jaki wentylatory jeszcze dodatkowo schladzaja rezystor double BRVtimer = 0; // Timer dla podtrzymania wentylatora - /* -dla pojazdów z blendingiem EP/ED (MED) */ - double MED_Vmax = 0; // predkosc maksymalna dla obliczen chwilowej sily hamowania EP w MED - double MED_Vmin = 0; // predkosc minimalna dla obliczen chwilowej sily hamowania EP w MED - double MED_Vref = 0; // predkosc referencyjna dla obliczen dostepnej sily hamowania EP w MED - double MED_amax{9.81}; // maksymalne opoznienie hamowania sluzbowego MED - bool MED_EPVC = false; // czy korekcja sily hamowania EP, gdy nie ma dostepnego ED - double MED_EPVC_Time = 7; // czas korekcji sily hamowania EP, gdy nie ma dostepnego ED - bool MED_Ncor = false; // czy korekcja sily hamowania z uwzglednieniem nacisku - double MED_MinBrakeReqED = 0; // minimalne zadanie sily hamowania uruchamiajace ED - ponizej tylko EP - double MED_FrED_factor = 1; // mnoznik sily hamowania ED do korekty blendingu - double MED_ED_Delay1 = 0; // opoznienie wdrazania hamowania ED (pierwszy raz) - double MED_ED_Delay2 = 0; // opoznienie zwiekszania sily hamowania ED (kolejne razy) - - int DCEMUED_CC{0}; // na którym sprzęgu sprawdzać działanie ED - double DCEMUED_EP_max_Vel{0.0}; // maksymalna prędkość, przy której działa EP przy włączonym ED w jednostce (dla tocznych) - double DCEMUED_EP_min_Im{0.0}; // minimalny prąd, przy którym EP nie działa przy włączonym ED w członie (dla silnikowych) - double DCEMUED_EP_delay{0.0}; // opóźnienie włączenia hamulca EP przy hamowaniu ED - zwłoka wstępna /*-dla wagonow*/ struct load_attributes @@ -1495,8 +1445,6 @@ class Vehicle double eimicSpeedCtrl = 1; /*pozycja sugerowana przez tempomat*/ double eimicSpeedCtrlIntegral = 0; /*calkowany blad ustawienia predkosci*/ double NewSpeed = 0; /*nowa predkosc do zadania*/ - double MED_EPVC_CurrentTime = 0; /*aktualny czas licznika czasu korekcji siły EP*/ - double MED_ED_DelayTimer = 0; /*aktualny czas licznika opoznienia hamowania ED*/ /*-zmienne dla drezyny*/ double PulseForce = 0.0; /*przylozona sila*/ @@ -1538,7 +1486,7 @@ class Vehicle struct { double cylinder{0.0}; // BrakePress - double spring{0.0}; // SpringBrake.SBP + double spring{0.0}; // brakes.spring.pressure int manual{0}; // ManualBrakePos double local{0.0}; // LocalBrakePosA } sleep_brakes; @@ -2152,8 +2100,8 @@ class Vehicle void UniversalControllerTrainBrake(); void EIMICTraxxLocalBrake(double dt); void EIMICLimit(); - // whether the holding brake (StopBrakeDecc) lets go at the power demand (eimic, above 0 when power is demanded) of this step of - // Dt seconds: once the demand has stayed above 0 for StopBrakeReleaseDelay. a demand of 0 or less starts the count again + // whether the holding brake (brakes.holding) lets go at the power demand (eimic, above 0 when power is demanded) of this step of + // Dt seconds: once the demand has stayed above 0 for brakes.holding.releaseDelay. a demand of 0 or less starts the count again bool UpdateStopBrakeRelease(double Demand, double Dt); void CheckSpeedCtrl(double dt); void SpeedCtrlRegulator(double dt, double accfactor); diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index 9f8a44378..c948f9e43 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -79,7 +79,7 @@ std::uint32_t devices_of(physics::Vehicle const &Occupied, physics::Vehicle cons on(Controlling.FuseFlag, device::overload_relay) | on(Controlling.SandDose, device::sanding) | on(Occupied.WarningSignal != 0, device::horn) | on(false == Occupied.Doors.instances[VehicleSide::left].is_closed, device::doors_left) | on(false == Occupied.Doors.instances[VehicleSide::right].is_closed, device::doors_right) | on(Occupied.Radio, device::radio) | - on(Controlling.Heating, device::heating) | on(Occupied.SpringBrake.IsActive, device::spring_brake) | on(Controlling.ShuntMode, device::shunt_mode) | + on(Controlling.Heating, device::heating) | on(Occupied.brakes.spring.isActive, device::spring_brake) | on(Controlling.ShuntMode, device::shunt_mode) | // the doors as the cab works them: the permits, the departure signal, the steps and the lock on(Occupied.DepartureSignal, device::departure_signal) | on(Occupied.Doors.instances[VehicleSide::left].open_permit, device::door_permit_left) | on(Occupied.Doors.instances[VehicleSide::right].open_permit, device::door_permit_right) | on(Occupied.Doors.step_enabled, device::door_step) | diff --git a/tests/unit/drive.cpp b/tests/unit/drive.cpp index ea60924f5..3f1227269 100644 --- a/tests/unit/drive.cpp +++ b/tests/unit/drive.cpp @@ -76,7 +76,7 @@ void release_brakes(physics::Vehicle &Cab) { for (auto const &thiscoupler : vehicle->Couplers) { if (thiscoupler.Connected != nullptr && thiscoupler.CouplingFlag != Coupling::none && std::ranges::find(train, thiscoupler.Connected) == train.end()) { thiscoupler.Connected->DecManualBrakeLevel(ManualBrakePosNo); - thiscoupler.Connected->SpringBrake.Activate = false; + thiscoupler.Connected->brakes.spring.activate = false; train.push_back(thiscoupler.Connected); pending.push_back(thiscoupler.Connected); } diff --git a/tests/unit/golden.cpp b/tests/unit/golden.cpp index aff0890f7..f66631b8a 100644 --- a/tests/unit/golden.cpp +++ b/tests/unit/golden.cpp @@ -182,7 +182,7 @@ std::vector parameters() { {"ScndCtrlPosNo", [](auto const &M) { return M.ScndCtrlPosNo; }}, {"LightsPosNo", [](auto const &M) { return M.LightsPosNo; }}, {"MBrake", [](auto const &M) { return M.MBrake ? 1.0 : 0.0; }}, - {"StopBrakeDecc", [](auto const &M) { return M.StopBrakeDecc; }}, + {"StopBrakeDecc", [](auto const &M) { return M.brakes.holding.deceleration; }}, {"BrakeDelays", [](auto const &M) { return M.BrakeDelays; }}, {"BrakeOpModes", [](auto const &M) { return M.BrakeOpModes; }}, {"Imin", [](auto const &M) { return M.Imin; }}, diff --git a/tests/unit/test_cab.cpp b/tests/unit/test_cab.cpp index 14c5e163d..c42d9d9f4 100644 --- a/tests/unit/test_cab.cpp +++ b/tests/unit/test_cab.cpp @@ -130,10 +130,10 @@ TEST_CASE("cab: the spring brake shut off and released by hand, the ep brake's f scenario.act("spring brake on"); railbus.SpringBrakeActivate(true); scenario.wait(10.0); - CHECK(railbus.SpringBrake.IsActive); + CHECK(railbus.brakes.spring.isActive); // released by hand only with its cylinder empty of the air holding it off - auto const pressure{railbus.SpringBrake.Cylinder->P()}; - CHECK(railbus.SpringBrakeRelease() == (pressure < railbus.SpringBrake.MinForcePressure)); + auto const pressure{railbus.brakes.spring.cylinder->P()}; + CHECK(railbus.SpringBrakeRelease() == (pressure < railbus.brakes.spring.minForcePressure)); scenario.act("shut off"); CHECK(railbus.SpringBrakeShutOff(true)); CHECK_FALSE(railbus.SpringBrakeShutOff(true)); diff --git a/tests/unit/test_commands.cpp b/tests/unit/test_commands.cpp index ac84c075e..a61ffd2b2 100644 --- a/tests/unit/test_commands.cpp +++ b/tests/unit/test_commands.cpp @@ -73,7 +73,7 @@ std::vector state() { {"LoadStatus", [](auto const &M) { return M.LoadStatus; }}, {"SpeedCtrlValue", [](auto const &M) { return M.SpeedCtrlValue; }}, {"SpeedCtrlParking", [](auto const &M) { return flag(M.SpeedCtrlUnit.Parking); }}, - {"SpringBrakeActivate", [](auto const &M) { return flag(M.SpringBrake.Activate); }}, + {"SpringBrakeActivate", [](auto const &M) { return flag(M.brakes.spring.activate); }}, }; for (auto const end : VehicleEnds) { auto const name{std::string{end == VehicleEnd::front ? "Front" : "Rear"}}; diff --git a/tests/unit/test_elf_controller.cpp b/tests/unit/test_elf_controller.cpp index 945eee844..49805c30c 100644 --- a/tests/unit/test_elf_controller.cpp +++ b/tests/unit/test_elf_controller.cpp @@ -288,7 +288,7 @@ template double release_time(elf &Unit, double Seconds, Action return -1.0; } -// the holding brake of TDynamicObject::Update() at standstill: StopBrakeDecc times the mass of the train, shared out +// the holding brake of TDynamicObject::Update() at standstill: brakes.holding.deceleration (SBD) times the mass of the train, shared out // by the axles, each car's share made a position of its brake valve (LocalBrakePosAEIM) as there. at standstill the // electric brake makes no part of it void hold(elf &Unit, bool Hold) { @@ -298,11 +298,11 @@ void hold(elf &Unit, bool Hold) { mass += Unit.car(i).TotalMass; axles += Unit.car(i).NAxles; } - auto const force{Unit.cab().StopBrakeDecc * mass}; + auto const force{Unit.cab().brakes.holding.deceleration * mass}; for (std::size_t i = 0; i < Unit.unit.size(); ++i) { auto &car{Unit.car(i)}; auto const nmax{((car.P2FTrans * car.MaxBrakePress[0] - car.BrakeCylSpring) * car.BrakeCylMult[0] - car.BrakeSlckAdj) * car.BrakeCylNo * car.BrakeRigEff}; - auto const fmax{nmax * car.Hamulec->GetFC(nmax / (car.NAxles * car.NBpA), car.MED_Vref) * 1000}; + auto const fmax{nmax * car.Hamulec->GetFC(nmax / (car.NAxles * car.NBpA), car.brakes.blending.referenceSpeed) * 1000}; auto position{Hold ? force * car.NAxles / axles / fmax : 0.0}; if (position > 0.009) { auto const slack{(car.BrakeSlckAdj / car.BrakeCylMult[0] + car.BrakeCylSpring) / (car.P2FTrans * car.MaxBrakePress[0])}; @@ -366,8 +366,8 @@ void flick(elf &Unit, double Time) { TEST_CASE("elf holding brake: without SBDReleaseDelay it lets go at the first demand, as it always did") { vehicle car{definition::fiz("elf_v1/21we-a")}; - CHECK(car->StopBrakeDecc == doctest::Approx(0.6)); - CHECK(car->StopBrakeReleaseDelay == 0.0); + CHECK(car->brakes.holding.deceleration == doctest::Approx(0.6)); + CHECK(car->brakes.holding.releaseDelay == 0.0); CHECK_FALSE(car->UpdateStopBrakeRelease(0.0, step_time)); CHECK_FALSE(car->UpdateStopBrakeRelease(-0.5, step_time)); CHECK(car->UpdateStopBrakeRelease(0.001, step_time)); @@ -378,7 +378,7 @@ TEST_CASE("elf holding brake: without SBDReleaseDelay it lets go at the first de TEST_CASE("elf holding brake: SBDReleaseDelay holds it for that long of a demand") { vehicle car{definition::fiz("elf_v1/21we-a").set("Cntrl", "SBDReleaseDelay", 1.0)}; - REQUIRE(car->StopBrakeReleaseDelay == doctest::Approx(1.0)); + REQUIRE(car->brakes.holding.releaseDelay == doctest::Approx(1.0)); // the demand rises above 0 in the step of time 0 long held{0}; while (held < 500 && false == car->UpdateStopBrakeRelease(0.01, step_time)) { @@ -387,7 +387,7 @@ TEST_CASE("elf holding brake: SBDReleaseDelay holds it for that long of a demand CHECK(held * step_time == doctest::Approx(1.0).epsilon(0.015)); // it holds again once there's no demand, and waits the whole delay again for the next one CHECK_FALSE(car->UpdateStopBrakeRelease(0.0, step_time)); - CHECK(car->StopBrakeReleaseTimer == 0.0); + CHECK(car->brakes.holding.releaseTimer == 0.0); CHECK_FALSE(car->UpdateStopBrakeRelease(0.01, step_time)); } @@ -528,7 +528,7 @@ TEST_CASE("elf holding brake: the force of the motors at 1% against the holding unit.unit.step(unit.line); unit.set_controller(3); unit.wait(5.0); - auto const holding{cab.StopBrakeDecc * mass}; + auto const holding{cab.brakes.holding.deceleration * mass}; MESSAGE("mass " << mass << " kg, holding " << holding << " N, cars with motors " << powered << ", demand " << cab.eimic_real << ", cab car Ft " << cab.Ft << " N, Fful " << cab.inductionMotor.state.fullForce << " kN, speed " << cab.Vel << " km/h after 5 s"); CHECK(cab.eimic_real == doctest::Approx(0.01).epsilon(0.02)); diff --git a/tests/unit/test_pullee.cpp b/tests/unit/test_pullee.cpp index fb276eb97..525673eca 100644 --- a/tests/unit/test_pullee.cpp +++ b/tests/unit/test_pullee.cpp @@ -148,11 +148,11 @@ TEST_CASE("pullee: the spring brake of a dead locomotive without air stops the t test::reseed_random(); hauled_train train{definition::fiz(path), 60.0, pullee}; auto const &hauled{train.hauled.physics()}; - REQUIRE(hauled.SpringBrake.MaxBrakeForce > 0.0); + REQUIRE(hauled.brakes.spring.maxForce > 0.0); drain_feed_air(train.hauled.physics()); train.run(60.0); // no air came from anywhere: the cylinder of the spring brake is empty either way - REQUIRE(hauled.SpringBrake.SBP < 0.1); + REQUIRE(hauled.brakes.spring.pressure < 0.1); if (pullee) { CHECK(hauled.Fb < 1.0); CHECK(train.hauled.speed() > 45.0); @@ -174,13 +174,13 @@ TEST_CASE("pullee: a dead EU47 starts to drag once its main reservoir has leaked auto &hauled{train.hauled.physics()}; // what the driver of the train does on its inspection, TController::AutoRewident() hauled.DecManualBrakeLevel(ManualBrakePosNo); - hauled.SpringBrake.Activate = false; + hauled.brakes.spring.activate = false; train.run(180.0); // charged and released: nothing holds it yet CHECK(hauled.BrakePress < 0.1); CHECK(hauled.Fb < 1.0); train.run(1020.0); // 20 minutes since the start - CHECK(hauled.ScndPipePress < hauled.SpringBrake.MinForcePressure); + CHECK(hauled.ScndPipePress < hauled.brakes.spring.minForcePressure); if (pullee) { CHECK(hauled.Fb < 1.0); } @@ -229,11 +229,11 @@ TEST_CASE("pullee: the spring brake of an Impuls prepared for hauling doesn't ca hauled_train train{impuls, 60.0, pullee}; auto const &hauled{train.hauled.physics()}; REQUIRE(hauled.InactiveCabFlag == 0); - REQUIRE(hauled.SpringBrakeDriveEmergencyVel == doctest::Approx(2.0)); + REQUIRE(hauled.brakes.spring.driveEmergencySpeed == doctest::Approx(2.0)); drain_feed_air(train.hauled.physics()); train.run(10.0); REQUIRE(hauled.Vel > 2.0); - REQUIRE(hauled.SpringBrake.IsActive); + REQUIRE(hauled.brakes.spring.isActive); if (pullee) { CHECK(hauled.EmergencyValveFlow == 0.0); CHECK(hauled.BrakePress < 0.1); @@ -319,11 +319,11 @@ TEST_CASE("pullee: the local brake of a vehicle prepared for hauling stays relea TEST_CASE("pullee: entering the mode lets go of the hand brake and the spring brake switch, and switches the battery off") { SUBCASE("a locomotive standing braked, its spring brake switched on") { vehicle vectron{definition::fiz("vectron_v1/wariant_7w")}; - REQUIRE(vectron->SpringBrake.Activate); + REQUIRE(vectron->brakes.spring.activate); REQUIRE_FALSE(vectron->PulleeMode); CHECK(vectron->PulleeModeSwitch(true)); CHECK(vectron->PulleeMode); - CHECK_FALSE(vectron->SpringBrake.Activate); + CHECK_FALSE(vectron->brakes.spring.activate); // already in it CHECK_FALSE(vectron->PulleeModeSwitch(true)); } @@ -438,7 +438,7 @@ TEST_CASE("pullee: every real vehicle standing braked releases once prepared for hauled_train train{definition::fiz(path), 0.0, true}; auto const &hauled{train.hauled.physics()}; CHECK(hauled.ManualBrakePos == 0); - CHECK_FALSE(hauled.SpringBrake.Activate); + CHECK_FALSE(hauled.brakes.spring.activate); CHECK_FALSE(hauled.Battery); train.run(180.0); CHECK(hauled.EmergencyValveFlow == 0.0); diff --git a/vehicle/ai/consist.cpp b/vehicle/ai/consist.cpp index c66e090f8..cb0472388 100644 --- a/vehicle/ai/consist.cpp +++ b/vehicle/ai/consist.cpp @@ -57,7 +57,7 @@ void TController::Activation() /* auto const initiallocalbrakelevel { occupied->LocalBrakePosA }; */ - auto const initialspringbrakestate { occupied->SpringBrake.Activate }; + auto const initialspringbrakestate { occupied->brakes.spring.activate }; // switch off tempomat SpeedCntrl( 0.0 ); mvControlling->DecScndCtrl( 2 ); @@ -170,7 +170,7 @@ void TController::AutoRewident() } // potentially release manual brake d->physics->DecManualBrakeLevel( ManualBrakePosNo ); - d->physics->SpringBrake.Activate = false; + d->physics->brakes.spring.activate = false; } BrakeReinspectionPending = reinspect; //ustawianie trybu pracy zadajnika hamulca, wystarczy raz po inicjalizacji AI @@ -723,7 +723,7 @@ TController::determine_consist_state() { while (p) { // sprawdzenie odhamowania wszystkich połączonych pojazdów auto *vehicle { p->physics }; - auto const bp { std::max( 0.0, vehicle->BrakePress - ( vehicle->SpeedCtrlUnit.Parking ? vehicle->MaxBrakePress[ 0 ] * vehicle->StopBrakeDecc : 0.0 ) ) }; + auto const bp { std::max( 0.0, vehicle->BrakePress - ( vehicle->SpeedCtrlUnit.Parking ? vehicle->MaxBrakePress[ 0 ] * vehicle->brakes.holding.deceleration : 0.0 ) ) }; momentum += vehicle->TotalMass * vehicle->V * ( p->DirectionGet() == iDirection ? 1 : -1 ); mostapplied = std::max( bp, mostapplied ); if( ( vehicle->BrakeSystem != TBrakeSystem::Individual ) diff --git a/vehicle/ai/controls.cpp b/vehicle/ai/controls.cpp index 37f4c7b1b..42d8fb2d6 100644 --- a/vehicle/ai/controls.cpp +++ b/vehicle/ai/controls.cpp @@ -231,7 +231,7 @@ bool TController::IncBrake() } else if( occupied->Handle->TimeEP == false ) { auto const initialbrakeposition { occupied->fBrakeCtrlPos }; - auto const AccMax { std::min( fBrake_a0[ 0 ] + 12 * fBrake_a1[ 0 ], occupied->MED_amax ) }; + auto const AccMax { std::min( fBrake_a0[ 0 ] + 12 * fBrake_a1[ 0 ], occupied->brakes.blending.maxDeceleration ) }; occupied->BrakeLevelSet( std::lerp( occupied->Handle->GetPos( bh_EPR ), @@ -268,7 +268,7 @@ bool TController::IncBrakeEIM() switch (occupied->EIMCtrlType) { case 0: { - if( occupied->MED_amax != 9.81 ) { + if( occupied->brakes.blending.maxDeceleration != 9.81 ) { auto const maxpos{occupied->EIMCtrlEmergency ? 0.9 : 1.0 }; auto const brakelimit{ -2.2 * AccDesired / fMedAmax - 1.0}; //additional limit when hinted is too low auto const brakehinted{ -1.0 * occupied->AIHintLocalBrakeAccFactor * AccDesired / fMedAmax }; //preffered by AI @@ -393,7 +393,7 @@ bool TController::DecBrake() { } else if( occupied->Handle->TimeEP == false ) { auto const initialbrakeposition { occupied->fBrakeCtrlPos }; - auto const AccMax { std::min( fBrake_a0[ 0 ] + 12 * fBrake_a1[ 0 ], occupied->MED_amax ) }; + auto const AccMax { std::min( fBrake_a0[ 0 ] + 12 * fBrake_a1[ 0 ], occupied->brakes.blending.maxDeceleration ) }; occupied->BrakeLevelSet( std::lerp( occupied->Handle->GetPos( bh_EPR ), @@ -453,9 +453,9 @@ bool TController::DecBrakeEIM() switch (occupied->EIMCtrlType) { case 0: { - if( occupied->MED_amax != 9.81 ) { + if( occupied->brakes.blending.maxDeceleration != 9.81 ) { auto const desiredacceleration { ( occupied->Vel > EU07_AI_NOMOVEMENT ? AccDesired : std::max( 0.0, AccDesired ) ) }; - auto const brakeposition { std::clamp( -1.0 * occupied->AIHintLocalBrakeAccFactor * desiredacceleration / occupied->MED_amax, 0.0, 1.0 ) }; + auto const brakeposition { std::clamp( -1.0 * occupied->AIHintLocalBrakeAccFactor * desiredacceleration / occupied->brakes.blending.maxDeceleration, 0.0, 1.0 ) }; OK = brakeposition != occupied->LocalBrakePosA; occupied->LocalBrakePosA = brakeposition; } diff --git a/vehicle/ai/engine.cpp b/vehicle/ai/engine.cpp index 80e80e6f1..bab5c1044 100644 --- a/vehicle/ai/engine.cpp +++ b/vehicle/ai/engine.cpp @@ -198,7 +198,7 @@ bool TController::PrepareEngine() } // sync spring brake state across consist cue_action( - occupied->SpringBrake.Activate ? + occupied->brakes.spring.activate ? driver_hint::springbrakeon : driver_hint::springbrakeoff ); } diff --git a/vehicle/ai/force.cpp b/vehicle/ai/force.cpp index 0914e3af0..e68ef676a 100644 --- a/vehicle/ai/force.cpp +++ b/vehicle/ai/force.cpp @@ -370,7 +370,7 @@ void TController::increase_tractive_force() { if( fActionTime < 0.0 ) { return; } // gdy jest nakaz poczekać z jazdą, to nie ruszać if( IsAnyCouplerStretched ) { return; } // train is already stretched past its limits, don't pull even harder - if( occupied->SpringBrake.Activate ) { + if( occupied->brakes.spring.activate ) { cue_action( driver_hint::springbrakeoff ); } if( VelDesired > 0.0 // to prevent door shuffle on stop @@ -474,7 +474,7 @@ void TController::control_braking_force() { fAccGravity < 0.025 ? // HACK: when going downhill be more responsive to desired deceleration fAccThreshold : std::max( -0.2, fAccThreshold ) ) }; - auto const AccMax{ std::min(fBrake_a0[0] + 12 * fBrake_a1[0], occupied->MED_amax) }; + auto const AccMax{ std::min(fBrake_a0[0] + 12 * fBrake_a1[0], occupied->brakes.blending.maxDeceleration) }; auto const accmargin = AccMax > 1.1 * AccDesired && fAccGravity < 0.025 ? 0.05 : 0.0; if( ( AccDesired < accthreshold // jeśli hamować - u góry ustawia się hamowanie na fAccThreshold diff --git a/vehicle/cab/equipmentcommands.cpp b/vehicle/cab/equipmentcommands.cpp index 4790ab17b..efe5eef28 100644 --- a/vehicle/cab/equipmentcommands.cpp +++ b/vehicle/cab/equipmentcommands.cpp @@ -209,7 +209,7 @@ void TTrain::OnCommand_springbraketoggle(TTrain *Train, command_data const &Comm if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->occupied->SpringBrake.Activate) + if (false == Train->occupied->brakes.spring.activate) { // turn on OnCommand_springbrakeenable(Train, Command); @@ -270,7 +270,7 @@ void TTrain::OnCommand_springbrakeshutofftoggle(TTrain *Train, command_data cons if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->occupied->SpringBrake.ShuttOff) + if (false == Train->occupied->brakes.spring.shutOff) { // turn on OnCommand_springbrakeshutoffenable(Train, Command); diff --git a/vehicle/cab/setup.cpp b/vehicle/cab/setup.cpp index 699222956..9658e1872 100644 --- a/vehicle/cab/setup.cpp +++ b/vehicle/cab/setup.cpp @@ -1659,7 +1659,7 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con {"radio_sw:", &occupied->Radio}, {"radiofuse_sw:", &occupied->RadioFuse}, {"cablight_sw:", &Cabine[iCabn].bLight}, - {"springbraketoggle_bt:", &occupied->SpringBrake.Activate}, + {"springbraketoggle_bt:", &occupied->brakes.spring.activate}, {"couplingdisconnect_sw:", &m_couplingdisconnect}, {"couplingdisconnectback_sw:", &m_couplingdisconnectback}, {"mirrors_sw:", &occupied->MirrorForbidden}, @@ -1852,7 +1852,7 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con // manometr cylindra hamulca sprężynowego auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&occupied->SpringBrake.SBP); + gauge.AssignDouble(&occupied->brakes.spring.pressure); } else if (Label == "epctrlvalue:") { diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index 3409f383e..6ec84fb91 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -438,9 +438,9 @@ void TTrain::updateUnitStates() fPress[i][3] = static_cast(p->physics->CntrlPipePress); fPress[i][4] = static_cast(p->physics->Hamulec->GetBRP()); fPress[i][5] = static_cast((p->physics->TotalMass - p->physics->Mred) * 0.001); - fPress[i][6] = static_cast(p->physics->SpringBrake.SBP); - bBrakes[i][0] = p->physics->SpringBrake.IsActive; - bBrakes[i][1] = p->physics->SpringBrake.ShuttOff; + fPress[i][6] = static_cast(p->physics->brakes.spring.pressure); + bBrakes[i][0] = p->physics->brakes.spring.isActive; + bBrakes[i][1] = p->physics->brakes.spring.shutOff; bDoors[i][1] = p->physics->Doors.instances[VehicleSide::left].position > 0.f; bDoors[i][2] = p->physics->Doors.instances[VehicleSide::right].position > 0.f; bDoors[i][3] = p->physics->Doors.instances[VehicleSide::left].step_position > 0.f; @@ -962,8 +962,8 @@ void TTrain::updateTrainLamps() btLampkaBrakeProfileG.Turn(TestFlag(occupied->BrakeDelayFlag, bdelay_G)); btLampkaBrakeProfileP.Turn(TestFlag(occupied->BrakeDelayFlag, bdelay_P)); btLampkaBrakeProfileR.Turn(TestFlag(occupied->BrakeDelayFlag, bdelay_R)); - btLampkaSpringBrakeActive.Turn(occupied->SpringBrake.IsActive); - btLampkaSpringBrakeInactive.Turn(!occupied->SpringBrake.IsActive); + btLampkaSpringBrakeActive.Turn(occupied->brakes.spring.isActive); + btLampkaSpringBrakeInactive.Turn(!occupied->brakes.spring.isActive); // light indicators // NOTE: sides are hardcoded to deal with setups where single cab is equipped with all indicators btLampkaUpperLight.Turn((occupied->iLights[VehicleEnd::front] & light::headlight_upper) != 0); diff --git a/vehicle/dynamic/sounds.cpp b/vehicle/dynamic/sounds.cpp index e4ee66811..8e5c30067 100644 --- a/vehicle/dynamic/sounds.cpp +++ b/vehicle/dynamic/sounds.cpp @@ -451,8 +451,8 @@ double TDynamicObject::renderBrakeFrictionSounds( double const dt ) { void TDynamicObject::renderSpringBrakeSounds() { // spring brake - if( m_springbrakesounds.state != physics->SpringBrake.Activate ) { - m_springbrakesounds.state = physics->SpringBrake.Activate; + if( m_springbrakesounds.state != physics->brakes.spring.activate ) { + m_springbrakesounds.state = physics->brakes.spring.activate; if( m_springbrakesounds.state ) { m_springbrakesounds.activate.play( sound_flags::exclusive ); m_springbrakesounds.release.stop(); diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index 7a3dee1b7..d433fc649 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -418,7 +418,7 @@ void TDynamicObject::sumConsistBrakeForces( InductionBrakeState &state ) p->physics->BrakeCylNo * p->physics->BrakeRigEff; state.FmaxPN += Nmax * p->physics->Hamulec->GetFC( Nmax / (p->physics->NAxles * p->physics->NBpA), - p->physics->MED_Vref) * + p->physics->brakes.blending.referenceSpeed) * 1000; // sila hamowania pn state.FmaxED += p->physics->Mains && p->physics->DirActive != 0 && p->physics->inductionMotor.inverterRatio == 1.0 && p->physics->inductionMotor.braking.maxForce * p->physics->NPoweredAxles > 0 ? @@ -445,7 +445,7 @@ void TDynamicObject::computeBrakeDeceleration( InductionBrakeState &state ) && physics->BrakeDelayFlag & bdelay_P) RapidMult = physics->RapidMult; - state.amax = RapidMult * std::min(state.FmaxPN / state.masamax, physics->MED_amax); + state.amax = RapidMult * std::min(state.FmaxPN / state.masamax, physics->brakes.blending.maxDeceleration); Mechanik->fMedAmax = state.amax; } @@ -459,7 +459,7 @@ void TDynamicObject::updateShuntMode( InductionBrakeState &state ) || ( physics->Doors.permit_needed && ( physics->Doors.instances[ VehicleSide::left ].open_permit || physics->Doors.instances[ VehicleSide::right ].open_permit ) ); - state.doorisopen &= !(physics->ReleaseParkingBySpringBrakeWhenDoorIsOpen && physics->SpringBrake.IsActive); + state.doorisopen &= !(physics->brakes.spring.releasesParkingWithDoorOpen && physics->brakes.spring.isActive); if (physics->Vel < 0.5 && (state.eimic < 0 || state.doorisopen || physics->Hamulec->GetEDBCP())) { @@ -495,7 +495,7 @@ void TDynamicObject::computeBrakeDemand( InductionBrakeState &state, double cons if (physics->ShuntMode && false == holdingbrakereleased || state.doorisopen /*|| (physics->V * physics->DirAbsolute < -0.2)*/) { - auto const sbd { ( physics->SpringBrake.IsActive && physics->ReleaseParkingBySpringBrake ? 0.0 : physics->StopBrakeDecc ) }; + auto const sbd { ( physics->brakes.spring.isActive && physics->brakes.spring.releasesParking ? 0.0 : physics->brakes.holding.deceleration ) }; state.Fzad = std::max( state.Fzad, sbd * state.masa ); } } @@ -524,7 +524,7 @@ void TDynamicObject::openMedLog( InductionBrakeState const &state ) void TDynamicObject::computeElectrodynamicDemand( InductionBrakeState &state, double const dt1 ) { state.FzadED = 0.0; - if( state.LBR > physics->MED_MinBrakeReqED + if( state.LBR > physics->brakes.blending.minEdDemand && ( physics->BrakeHandle == TBrakeHandle::MHZ_EN57 ? (physics->BrakeOpModeFlag & bom_MED) != 0 : physics->EpFuse ) ) { @@ -538,9 +538,9 @@ void TDynamicObject::computeElectrodynamicDemand( InductionBrakeState &state, do //opoznienie wdrazania ED if (state.FzadED > MED_oldFED) { - if (physics->MED_ED_DelayTimer <= 0) { - physics->MED_ED_DelayTimer += dt1; - if (physics->MED_ED_DelayTimer > 0) { + if (physics->brakes.blending.edDelayTimer <= 0) { + physics->brakes.blending.edDelayTimer += dt1; + if (physics->brakes.blending.edDelayTimer > 0) { } else { @@ -550,13 +550,13 @@ void TDynamicObject::computeElectrodynamicDemand( InductionBrakeState &state, do else { state.FzadED = std::min(state.FzadED, MED_oldFED); - physics->MED_ED_DelayTimer = state.FrED > 0 ? -physics->MED_ED_Delay2 : -physics->MED_ED_Delay1; + physics->brakes.blending.edDelayTimer = state.FrED > 0 ? -physics->brakes.blending.edNextDelay : -physics->brakes.blending.edFirstDelay; } } if (physics->BrakeCtrlPos == physics->Handle->GetPos(bh_EB) && physics->inductionMotor.braking.cylinderPressureGain < 0.001) state.FzadED = 0; //pętla bezpieczeństwa - bez ED - state.FzadPN = state.Fzad - state.FrED * physics->MED_FrED_factor; + state.FzadPN = state.Fzad - state.FrED * physics->brakes.blending.edForceFactor; } // steps 3-6 of the blending: the ED and the pneumatic braking forces set to the vehicles of the consist void TDynamicObject::distributeBrakeForces( InductionBrakeState &state, double const dt1 ) @@ -592,7 +592,7 @@ void TDynamicObject::distributeBrakeForces( InductionBrakeState &state, double c FmaxEP[i] = Nmax * p->physics->Hamulec->GetFC( Nmax / (p->physics->NAxles * p->physics->NBpA), - p->physics->MED_Vref) * + p->physics->brakes.blending.referenceSpeed) * 1000; // sila hamowania pn PrzekrF[i] = false; @@ -653,11 +653,11 @@ void TDynamicObject::distributeBrakeForces( InductionBrakeState &state, double c p->physics->BrakeSlckAdj) * p->physics->BrakeCylNo * p->physics->BrakeRigEff; if (state.FrED > 0.1) - p->physics->MED_EPVC_CurrentTime = 0; + p->physics->brakes.blending.epCorrectionTimer = 0; else - p->physics->MED_EPVC_CurrentTime += dt1; - bool EPVC = p->physics->MED_EPVC && (p->physics->MED_EPVC_Time < 0 || p->physics->MED_EPVC_CurrentTime < p->physics->MED_EPVC_Time); - float VelC = EPVC ? safe_clamp(p->physics->Vel, p->physics->MED_Vmin, p->physics->MED_Vmax) : p->physics->MED_Vref;//korekcja EP po prędkości + p->physics->brakes.blending.epCorrectionTimer += dt1; + bool EPVC = p->physics->brakes.blending.epCorrection && (p->physics->brakes.blending.epCorrectionTime < 0 || p->physics->brakes.blending.epCorrectionTimer < p->physics->brakes.blending.epCorrectionTime); + float VelC = EPVC ? safe_clamp(p->physics->Vel, p->physics->brakes.blending.minSpeed, p->physics->brakes.blending.maxSpeed) : p->physics->brakes.blending.referenceSpeed;//korekcja EP po prędkości float FmaxPoj = Nmax * p->physics->Hamulec->GetFC( Nmax / (p->physics->NAxles * p->physics->NBpA), VelC) * From 309926bb055f1da2098750d8566ac177a70c37bd Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 01:18:26 +0100 Subject: [PATCH 029/123] refactor(physics): the air supply and the pipes along the train as components The air of physics::Vehicle becomes components of their own, with the fields named in English (physics/components/airsupply.h): air (AirSupply) the compressor and the main reservoir: compressor (AirCompressor) MinCompressor, MaxCompressor and those of each cab, CabDependentCompressor, CompressorSpeed, CompressorPower, CompressorStartDelay, CompressorTankValve, CompressorStart, the CompressorList programmer and its switch, and the state: CompressorFlag running, CompressorAllow(Local) allow(Local), CompressorGovernorLock, CompressorPowerTime VeselVolume mainReservoirVolume Compressor mainReservoirPressure CompressedVolume compressedVolume AirLeakRate leakRate brakePipe, mainPipe the two pipes along the train, of one type, (TrainPipe) TrainPipe: reservoir, pressure, couplersPending (Pipe, PipePress, PipeCouplersPending and Pipe2, ScndPipePress, ScndPipeCouplersPending before) CompressorPower, a number 0 to 5, is the enum CompressorSupply (mainCircuit, converterManual, converter, engine, frontUnitConverter, rearUnitConverter), read from the same words of the .fiz. The CompressorList table is a std::array of the same ints. The exchange of air through the hoses (pneumatics.cpp) takes the pipe as one TrainPipe of the vehicle instead of three member pointers. No change in behaviour: 1149/1149 tests, golden traces exact against staging 62f7a29b. --- application/driverhints.cpp | 2 +- application/driveruipanels.cpp | 16 +- input/messaging.cpp | 8 +- physics/components/airsupply.h | 84 +++++ physics/components/body.cpp | 22 +- physics/components/cab.cpp | 8 +- physics/components/commands.cpp | 2 +- physics/components/controllers.cpp | 4 +- physics/components/drive.cpp | 2 +- physics/components/electrics.cpp | 6 +- physics/components/fizparser.cpp | 2 +- physics/components/fizsections.cpp | 61 ++-- physics/components/pneumatics.cpp | 318 +++++++++--------- physics/components/setup.cpp | 46 +-- physics/components/traction.cpp | 2 +- physics/vehicle.h | 40 +-- simulation/blackboxrecorder.cpp | 8 +- simulation/simulation.cpp | 2 +- tests/unit/COVERAGE.md | 2 +- tests/unit/consist.cpp | 2 +- tests/unit/drive.cpp | 6 +- tests/unit/figures.cpp | 2 +- tests/unit/golden.cpp | 18 +- tests/unit/invariants.cpp | 16 +- tests/unit/test_brake_handles.cpp | 18 +- tests/unit/test_brake_pipe.cpp | 10 +- tests/unit/test_brakes.cpp | 12 +- tests/unit/test_cab.cpp | 8 +- tests/unit/test_camshaft.cpp | 2 +- tests/unit/test_commands.cpp | 8 +- tests/unit/test_compressor.cpp | 68 ++-- tests/unit/test_controls.cpp | 16 +- tests/unit/test_crew.cpp | 4 +- tests/unit/test_definition.cpp | 36 +- tests/unit/test_dynamic_brake_diesel.cpp | 2 +- tests/unit/test_elf_controller.cpp | 26 +- tests/unit/test_feed_pipe.cpp | 32 +- tests/unit/test_figures.cpp | 8 +- tests/unit/test_genset.cpp | 2 +- tests/unit/test_horn.cpp | 24 +- tests/unit/test_line_contactors.cpp | 2 +- tests/unit/test_line_contactors_interlock.cpp | 12 +- tests/unit/test_mains_before_pantographs.cpp | 24 +- tests/unit/test_pressure_switch.cpp | 18 +- tests/unit/test_pullee.cpp | 28 +- tests/unit/vehicle.cpp | 10 +- vehicle/ai/consist.cpp | 24 +- vehicle/ai/engine.cpp | 6 +- vehicle/ai/force.cpp | 8 +- vehicle/ai/physicslog.cpp | 4 +- vehicle/ai/situation.cpp | 2 +- vehicle/cab/auxiliarycommands.cpp | 40 +-- vehicle/cab/setup.cpp | 12 +- vehicle/cab/train.cpp | 10 +- vehicle/cab/update.cpp | 30 +- vehicle/dynamic/consist.cpp | 6 +- vehicle/dynamic/lifecycle.cpp | 14 +- vehicle/dynamic/sounds.cpp | 10 +- vehicle/dynamic/update.cpp | 16 +- vehicle/dynamic/vehicletable.cpp | 6 +- widgets/vehicleparams.cpp | 10 +- 61 files changed, 649 insertions(+), 598 deletions(-) create mode 100644 physics/components/airsupply.h diff --git a/application/driverhints.cpp b/application/driverhints.cpp index 76203813e..34a0b5c2b 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -752,7 +752,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return mvControlling->ScndPipePress > 4.5 || mvControlling->VeselVolume == 0.0; } ); + return mvControlling->mainPipe.pressure > 4.5 || mvControlling->air.mainReservoirVolume == 0.0; } ); break; } case driver_hint::waitpantographpressuretoolow: { diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index bb86961f8..c4840d80d 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -150,7 +150,7 @@ drivingaid_panel::update() { m_buffer.data(), m_buffer.size(), STR_C(" Pressure: %.2f kPa (train pipe: %.2f kPa)"), physics->BrakePress * 100, - physics->PipePress * 100 ); + physics->brakePipe.pressure * 100 ); expandedtext = m_buffer.data(); } if( readout.ed_percent ) { @@ -849,11 +849,11 @@ debug_panel::update_section_vehicle( std::vector &Output ) { physics.ConverterAllow ? 'x' : '.', physics.ConvOvldFlag ? '!' : '.', - physics.CompressorFlag ? 'C' : - false == physics.CompressorAllowLocal ? '-' : - physics.CompressorAllow || (physics.CompressorStart == start_t::automatic && physics.CompressorSpeed > 0.0) ? 'c' : + physics.air.compressor.running ? 'C' : + false == physics.air.compressor.allowLocal ? '-' : + physics.air.compressor.allow || (physics.air.compressor.start == start_t::automatic && physics.air.compressor.speed > 0.0) ? 'c' : '.', - physics.CompressorGovernorLock ? '!' : '.', + physics.air.compressor.governorLock ? '!' : '.', physics.StLinSwitchOff ? '-' : physics.ControlPressureSwitch ? '!' : physics.StLinFlag ? '+' : @@ -936,13 +936,13 @@ debug_panel::update_section_vehicle( std::vector &Output ) { physics.LocBrakePress, physics.Hamulec->GetBrakeStatus(), // pipes - physics.PipePress, + physics.brakePipe.pressure, physics.BrakeCtrlPos2, - physics.ScndPipePress, + physics.mainPipe.pressure, physics.CntrlPipePress, // tanks physics.Hamulec->GetBRP(), - physics.Compressor, + physics.air.mainReservoirPressure, physics.Hamulec->GetCRP() ); textline = m_buffer.data(); diff --git a/input/messaging.cpp b/input/messaging.cpp index 4c17eedf1..f50fde423 100644 --- a/input/messaging.cpp +++ b/input/messaging.cpp @@ -284,10 +284,10 @@ WyslijNamiary([[maybe_unused]] TDynamicObject const *Vehicle) r.fPar[9] = Vehicle->physics->AccN; // przyspieszenie Y //na razie nie r.fPar[10] = Vehicle->physics->AccVert; // przyspieszenie Z r.fPar[11] = Vehicle->physics->DistCounter; // przejechana odległość w km - r.fPar[12] = Vehicle->physics->PipePress; // ciśnienie w PG - r.fPar[13] = Vehicle->physics->ScndPipePress; // ciśnienie w PZ + r.fPar[12] = Vehicle->physics->brakePipe.pressure; // ciśnienie w PG + r.fPar[13] = Vehicle->physics->mainPipe.pressure; // ciśnienie w PZ r.fPar[14] = Vehicle->physics->BrakePress; // ciśnienie w CH - r.fPar[15] = Vehicle->physics->Compressor; // ciśnienie w ZG + r.fPar[15] = Vehicle->physics->air.mainReservoirPressure; // ciśnienie w ZG r.fPar[16] = Vehicle->physics->Itot; // Prąd całkowity r.iPar[17] = Vehicle->physics->MainCtrlPos; // Pozycja NJ r.iPar[18] = Vehicle->physics->ScndCtrlPos; // Pozycja NB @@ -296,7 +296,7 @@ WyslijNamiary([[maybe_unused]] TDynamicObject const *Vehicle) r.iPar[21] = Vehicle->physics->ScndCtrlActualPos; // Pozycja bocznikowania r.iPar[22] = Vehicle->physics->ResistorsFlag * 1 + Vehicle->physics->ConverterFlag * 2 - + Vehicle->physics->CompressorFlag * 4 + + Vehicle->physics->air.compressor.running * 4 + Vehicle->physics->Mains * 8 #ifdef EU07_USEOLDDOORCODE + Vehicle->physics->DoorLeftOpened * 16 diff --git a/physics/components/airsupply.h b/physics/components/airsupply.h new file mode 100644 index 000000000..d81fc3e29 --- /dev/null +++ b/physics/components/airsupply.h @@ -0,0 +1,84 @@ +/* +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 supply of compressed air of a vehicle: the compressor and the main reservoir, held by physics::Vehicle as air; and +// the pipes along the train, held by it as brakePipe and mainPipe + +#pragma once + +#include +#include + +#include "physics/vehicletypes.h" + +class TReservoir; + +namespace physics +{ + +// a pipe along the train, coupled by the hoses between the vehicles: the brake pipe, the main reservoir pipe +struct TrainPipe +{ + std::shared_ptr reservoir; + double pressure = 0.0; + bool couplersPending{false}; // the pipe stepped, its exchange of air through the hoses is yet to come (UpdatePipeCouplers()) +}; + +// where the compressor gets its power from (CompressorPower of the .fiz), in the order of the numbers it had before +enum class CompressorSupply +{ + mainCircuit, // Main + converterManual, // the default: from the converter, switched by hand + converter, // Converter: from the converter, always + engine, // Engine: driven by the diesel engine + frontUnitConverter, // Coupler1: from the converter of the unit in front (a motor car of an EMU) + rearUnitConverter, // Coupler2: from the converter of the unit behind +}; + +// the compressor of the main reservoir +struct AirCompressor +{ + // the definition (the Brake section of the .fiz) + double minPressure = 0.0; // MinCP: it starts below this pressure of the main reservoir + double maxPressure = 0.0; // MaxCP: it stops above this pressure + double minPressureCabA = 0.0; // the pressures of each cab, where they differ (MinCP_B, MaxCP_B given) + double maxPressureCabA = 0.0; + double minPressureCabB = 0.0; // MinCP_B + double maxPressureCabB = 0.0; // MaxCP_B + bool cabDependent = false; // the pressures follow the occupied cab + double speed = 0.0; // CompressorSpeed: how fast it fills the main reservoir + CompressorSupply supply{CompressorSupply::converterManual}; // CompressorPower + double startDelay{0.0}; // CompressorStartDelay: how long it waits after getting its power before it can start, after the engine starts say [s] + bool tankValve{false}; // CompressorTankValve: the pressure over the top is let out of its tank at once + start_t start{start_t::manual}; // CompressorStart: whether it is started by hand, or another way + // the programmer of the compressors of a unit (the CompressorList section), indexed by the cl_* rows + std::array, 4> list{}; + int listPositions = 0; // Size: the positions of its switch + int listDefaultPosition = 1; // Default + bool listWraps = false; // Wrap + // the state + bool running = false; // it runs + bool allow = false; // it may start + bool allowLocal{true}; // the switch of the vehicle itself; most have none, so it allows + bool governorLock{false}; // the governor switched it off at the cut-out pressure + double powerTime{0.0}; // how long it has had its power [s] + int listPosition = 0; // the position of the switch of the programmer +}; + +// the supply of compressed air +struct AirSupply +{ + AirCompressor compressor; + double mainReservoirVolume = 0.0; // Vv: the volume of the main reservoir + double mainReservoirPressure = 0.0; // the pressure in the main reservoir + double compressedVolume = 0.0; // the compressed air in the supply + double leakRate{0.01}; // AirLeakRate: the base rate of the air leaking from the components of the brakes (0.001 = 1 l/s) +}; + +} // namespace physics diff --git a/physics/components/body.cpp b/physics/components/body.cpp index d969b7d9b..310925e34 100644 --- a/physics/components/body.cpp +++ b/physics/components/body.cpp @@ -91,13 +91,13 @@ physics::Vehicle::Vehicle(double VelInitial, std::string const &TypeNameInit, st for (int k = 0; k < 17; ++k) cablights[k] = 0; - for (auto &compressorrow : CompressorList) + for (auto &compressorrow : air.compressor.list) for (int k = 1; k < 9; ++k) compressorrow[k] = 0; - CompressorList[0][0] = 0.0; - CompressorList[1][0] = 1.0; - CompressorList[2][0] = 1.0; - CompressorList[3][0] = 1.0; + air.compressor.list[0][0] = 0.0; + air.compressor.list[1][0] = 1.0; + air.compressor.list[2][0] = 1.0; + air.compressor.list[3][0] = 1.0; for (int b = -1; b <= MainBrakeMaxPos; ++b) { @@ -474,14 +474,14 @@ void physics::Vehicle::compute_movement_(double const Deltatime) MotorBlowersCheck(Deltatime); // uklady hamulcowe: ConverterCheck(Deltatime); - if (VeselVolume > 0) - Compressor = CompressedVolume / VeselVolume; + if (air.mainReservoirVolume > 0) + air.mainReservoirPressure = air.compressedVolume / air.mainReservoirVolume; else { - Compressor = 0; - CompressorFlag = false; + air.mainReservoirPressure = 0; + air.compressor.running = false; } - if (VeselVolume > 0.0) + if (air.mainReservoirVolume > 0.0) { // sprężarka musi mieć jakąś niezerową wydajność żeby rozważać jej załączenie i pracę CompressorCheck(Deltatime); @@ -842,7 +842,7 @@ void physics::Vehicle::ComputeTotalForce(double dt) double old_nrot = abs(nrot); nrot = v2n(); // przeliczenie prędkości liniowej na obrotową - if (true == TestFlag(BrakeMethod, bp_MHS) && PipePress < 3.0 // ustawione na sztywno na 3 bar + if (true == TestFlag(BrakeMethod, bp_MHS) && brakePipe.pressure < 3.0 // ustawione na sztywno na 3 bar && Vel > 45 && true == TestFlag(BrakeDelayFlag, bdelay_M)) { // doliczenie hamowania hamulcem szynowym diff --git a/physics/components/cab.cpp b/physics/components/cab.cpp index af1d27849..c8f0addf1 100644 --- a/physics/components/cab.cpp +++ b/physics/components/cab.cpp @@ -57,7 +57,7 @@ bool physics::Vehicle::ChangeCab(int direction) if (BrakeCtrlPosNo > 0 && (BrakeSystem == TBrakeSystem::Pneumatic || BrakeSystem == TBrakeSystem::ElectroPneumatic)) { BrakeLevelSet(Handle->GetPos(bh_NP)); - LimPipePress = PipePress; + LimPipePress = brakePipe.pressure; ActFlowSpeed = 0; } else @@ -76,14 +76,14 @@ int physics::Vehicle::SoundingHorns(int const Signal) const { return Power24vIsAvailable || Power110vIsAvailable; } - if (VeselVolume > 0.0) + if (air.mainReservoirVolume > 0.0) { - return Compressor >= HornMinPressure; + return air.mainReservoirPressure >= HornMinPressure; } // a vehicle without a main reservoir of its own takes the air from the main pipe, a vehicle without either // (a road vehicle, say) has no air to check auto const mainpipe{(Couplers[VehicleEnd::front].AllowedFlag | Couplers[VehicleEnd::rear].AllowedFlag).HasAny(Coupling::mainHose)}; - return false == mainpipe || ScndPipePress >= HornMinPressure; + return false == mainpipe || mainPipe.pressure >= HornMinPressure; }}; auto horns{0}; if (supplied(HornSupply)) diff --git a/physics/components/commands.cpp b/physics/components/commands.cpp index 676180b84..7f94808d4 100644 --- a/physics/components/commands.cpp +++ b/physics/components/commands.cpp @@ -392,7 +392,7 @@ bool physics::Vehicle::RunAuxiliariesCommand(VehicleCommand const Command, doubl } else if (Command == VehicleCommand::compressorPreset) { - CompressorListPos = safe_clamp(static_cast(CValue1), 0, CompressorListPosNo); + air.compressor.listPosition = safe_clamp(static_cast(CValue1), 0, air.compressor.listPositions); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } else diff --git a/physics/components/controllers.cpp b/physics/components/controllers.cpp index 3a2a61e0e..f8d7315fc 100644 --- a/physics/components/controllers.cpp +++ b/physics/components/controllers.cpp @@ -894,7 +894,7 @@ bool physics::Vehicle::MotorConnectorsCheck() // hunter-111211: wylacznik cisnieniowy // (on some vehicles it watches the brake pipe alone) - ControlPressureSwitch = HasControlPressureSwitch && ((PressureSwitchBrakeCylinder && BrakePress > 2.0) || PipePress < 3.6); + ControlPressureSwitch = HasControlPressureSwitch && ((PressureSwitchBrakeCylinder && BrakePress > 2.0) || brakePipe.pressure < 3.6); if (true == ControlPressureSwitch) { @@ -1253,7 +1253,7 @@ void physics::Vehicle::CheckSpeedCtrl(double dt) { SpeedCtrlUnit.Standby = false; } - if (!SpeedCtrlUnit.BrakeIntervention && (Hamulec->GetEDBCP() > 0.4 || PipePress < HighPipePress - 0.2)) + if (!SpeedCtrlUnit.BrakeIntervention && (Hamulec->GetEDBCP() > 0.4 || brakePipe.pressure < HighPipePress - 0.2)) SpeedCtrlUnit.Standby = true; if (EIMCtrlType >= 3 && UniCtrlList[MainCtrlPos].SpeedUp <= 0) { diff --git a/physics/components/drive.cpp b/physics/components/drive.cpp index 537bba01d..c1f64738e 100644 --- a/physics/components/drive.cpp +++ b/physics/components/drive.cpp @@ -384,7 +384,7 @@ public: { ++vehicle.MainCtrlPos; } - vehicle.CompressorAllow = vehicle.MainCtrlPowerPos() > 0; + vehicle.air.compressor.allow = vehicle.MainCtrlPowerPos() > 0; return true; } bool DecreaseMainController(physics::Vehicle &vehicle, int const speed) const override diff --git a/physics/components/electrics.cpp b/physics/components/electrics.cpp index ebab2cbf0..d533a1c7d 100644 --- a/physics/components/electrics.cpp +++ b/physics/components/electrics.cpp @@ -50,12 +50,12 @@ void physics::Vehicle::UpdatePantVolume(double dt) // Ra 2014-07: kurek trójdrogowy łączy spr.pom. z pantografami i wyłącznikiem ciśnieniowym WS // Ra 2014-07: zbiornika rozrządu nie pompuje się tu, tylko pantografy; potem można zamknąć // WS i odpalić resztę - if (PantAutoValve ? PantPress < ScndPipePress : bPantKurek3) // kurek zamyka połączenie z ZG + if (PantAutoValve ? PantPress < mainPipe.pressure : bPantKurek3) // kurek zamyka połączenie z ZG { // zbiornik pantografu połączony ze zbiornikiem głównym - małą sprężarką się tego nie napompuje // Ra 2013-12: Niebugocław mówi, że w EZT nie ma potrzeby odcinać kurkiem - PantPress = ScndPipePress; + PantPress = mainPipe.pressure; // ograniczenie ciśnienia do MaxPress (tylko w pantografach!) - PantPress = safe_clamp(ScndPipePress, 0.0, EnginePowerSource.CollectorParameters.MaxPress); + PantPress = safe_clamp(mainPipe.pressure, 0.0, EnginePowerSource.CollectorParameters.MaxPress); PantVolume = (PantPress + 1.0) * 0.1; // objętość, na wypadek odcięcia kurkiem } else diff --git a/physics/components/fizparser.cpp b/physics/components/fizparser.cpp index 5d7f3fc63..6b688fa68 100644 --- a/physics/components/fizparser.cpp +++ b/physics/components/fizparser.cpp @@ -546,7 +546,7 @@ bool physics::Vehicle::readCompressorList(std::string const &Input) return false; } // NOTE: content of slot [x][0] is hardcoded elsewhere - parser >> CompressorList[0][idx + 1] >> CompressorList[1][idx + 1] >> CompressorList[2][idx + 1] >> CompressorList[3][idx + 1]; + parser >> air.compressor.list[0][idx + 1] >> air.compressor.list[1][idx + 1] >> air.compressor.list[2][idx + 1] >> air.compressor.list[3][idx + 1]; return true; } diff --git a/physics/components/fizsections.cpp b/physics/components/fizsections.cpp index e4331ef32..882086abb 100644 --- a/physics/components/fizsections.cpp +++ b/physics/components/fizsections.cpp @@ -291,16 +291,16 @@ void physics::Vehicle::LoadFIZ_Brake(std::string const &line) extract_value(LowPipePress, "LoPP", line, ""); DeltaPipePress = HighPipePress - LowPipePress; - extract_value(VeselVolume, "Vv", line, ""); + extract_value(air.mainReservoirVolume, "Vv", line, ""); /* if( VeselVolume == 0.0 ) { VeselVolume = 0.01; } */ - extract_value(MinCompressor, "MinCP", line, ""); - extract_value(MaxCompressor, "MaxCP", line, ""); - extract_value(MinCompressor_cabB, "MinCP_B", line, ""); - extract_value(MaxCompressor_cabB, "MaxCP_B", line, ""); - extract_value(CompressorTankValve, "CompressorTankValve", line, ""); - extract_value(CompressorSpeed, "CompressorSpeed", line, ""); + extract_value(air.compressor.minPressure, "MinCP", line, ""); + extract_value(air.compressor.maxPressure, "MaxCP", line, ""); + extract_value(air.compressor.minPressureCabB, "MinCP_B", line, ""); + extract_value(air.compressor.maxPressureCabB, "MaxCP_B", line, ""); + extract_value(air.compressor.tankValve, "CompressorTankValve", line, ""); + extract_value(air.compressor.speed, "CompressorSpeed", line, ""); extract_value(EmergencyValveOff, "MinEVP", line, ""); extract_value(EmergencyValveOn, "MaxEVP", line, ""); extract_value(EmergencyValveArea, "EVArea", line, ""); @@ -312,44 +312,45 @@ void physics::Vehicle::LoadFIZ_Brake(std::string const &line) extract_value(HandleUnlock, "HandlePipeUnlockPos", line, "-3"); extract_value(EmergencyCutsOffHandle, "EmergencyCutsOffHandle", line, ""); { - std::map> compressorpowers{ - {"Main", 0}, - // 1: default, powered by converter, with manual state control - {"Converter", 2}, - {"Engine", 3}, // equivalent of 0, TODO: separate 'main' and 'engine' in the code - {"Coupler1", 4}, // włączana w silnikowym EZT z przodu - {"Coupler2", 5} // włączana w silnikowym EZT z tyłu + using enum CompressorSupply; + std::map> compressorpowers{ + {"Main", mainCircuit}, + // the default: powered by the converter, switched by hand + {"Converter", converter}, + {"Engine", engine}, // equivalent of Main, TODO: separate 'main' and 'engine' in the code + {"Coupler1", frontUnitConverter}, // włączana w silnikowym EZT z przodu + {"Coupler2", rearUnitConverter} // włączana w silnikowym EZT z tyłu }; auto lookup = compressorpowers.find(extract_value("CompressorPower", line)); - CompressorPower = lookup != compressorpowers.end() ? lookup->second : 1; + air.compressor.supply = lookup != compressorpowers.end() ? lookup->second : converterManual; } - extract_value(CompressorStartDelay, "CompressorStartDelay", line, ""); + extract_value(air.compressor.startDelay, "CompressorStartDelay", line, ""); - if (true == extract_value(AirLeakRate, "AirLeakRate", line, "")) + if (true == extract_value(air.leakRate, "AirLeakRate", line, "")) { // the parameter is provided in form of a multiplier, where 1.0 means the default rate of 0.01 - AirLeakRate *= 0.01; + air.leakRate *= 0.01; } extract_value(ReleaserEnabledOnlyAtNoPowerPos, "ReleaserPowerPosLock", line, EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric ? "yes" : "no"); - if (MinCompressor_cabB > 0.0) + if (air.compressor.minPressureCabB > 0.0) { - MinCompressor_cabA = MinCompressor; - CabDependentCompressor = true; + air.compressor.minPressureCabA = air.compressor.minPressure; + air.compressor.cabDependent = true; } else { - MinCompressor_cabB = MinCompressor; + air.compressor.minPressureCabB = air.compressor.minPressure; } - if (MaxCompressor_cabB > 0.0) + if (air.compressor.maxPressureCabB > 0.0) { - MaxCompressor_cabA = MaxCompressor; - CabDependentCompressor = true; + air.compressor.maxPressureCabA = air.compressor.maxPressure; + air.compressor.cabDependent = true; } else { - MaxCompressor_cabB = MaxCompressor; + air.compressor.maxPressureCabB = air.compressor.maxPressure; } } @@ -932,7 +933,7 @@ void physics::Vehicle::LoadFIZ_CntrlStarts(std::string const &line) // compressor { auto lookup = starts.find(extract_value("CompressorStart", line)); - CompressorStart = lookup != starts.end() ? lookup->second : manual; + air.compressor.start = lookup != starts.end() ? lookup->second : manual; } // pantograph compressor { @@ -1667,9 +1668,9 @@ void physics::Vehicle::LoadFIZ_LightsList(std::string const &Input) void physics::Vehicle::LoadFIZ_CompressorList(std::string const &Input) { - extract_value(CompressorListPosNo, "Size", Input, ""); - extract_value(CompressorListWrap, "Wrap", Input, ""); - extract_value(CompressorListDefPos, "Default", Input, ""); + extract_value(air.compressor.listPositions, "Size", Input, ""); + extract_value(air.compressor.listWraps, "Wrap", Input, ""); + extract_value(air.compressor.listDefaultPosition, "Default", Input, ""); } void physics::Vehicle::LoadFIZ_PowerParamsDecode(TPowerParameters &Powerparameters, std::string const &Prefix, std::string const &Line) diff --git a/physics/components/pneumatics.cpp b/physics/components/pneumatics.cpp index 84d5eb838..ba186f1dc 100644 --- a/physics/components/pneumatics.cpp +++ b/physics/components/pneumatics.cpp @@ -189,7 +189,7 @@ double physics::Vehicle::RealPipeRatio(void) const double rpp; if (DeltaPipePress > 0) - rpp = (CntrlPipePress - PipePress) / DeltaPipePress; + rpp = (CntrlPipePress - brakePipe.pressure) / DeltaPipePress; else rpp = 0; return rpp; @@ -206,10 +206,10 @@ double physics::Vehicle::PipeRatio(void) const if (DeltaPipePress > 0) if (false) // SPKS!! no to jak nie wchodzimy to po co branch? { - if (3.0 * PipePress > HighPipePress + LowPipePress + LowPipePress) - pr = (HighPipePress - std::min(HighPipePress, PipePress)) / (DeltaPipePress * 4.0 / 3.0); + if (3.0 * brakePipe.pressure > HighPipePress + LowPipePress + LowPipePress) + pr = (HighPipePress - std::min(HighPipePress, brakePipe.pressure)) / (DeltaPipePress * 4.0 / 3.0); else - pr = (HighPipePress - 1.0 / 3.0 * DeltaPipePress - std::max(LowPipePress, PipePress)) / (DeltaPipePress * 2.0 / 3.0); + pr = (HighPipePress - 1.0 / 3.0 * DeltaPipePress - std::max(LowPipePress, brakePipe.pressure)) / (DeltaPipePress * 2.0 / 3.0); // if (not TestFlag(BrakeStatus, b_Ractive)) // and(BrakeMethod and 1 = 0) and TestFlag(BrakeDelays, bdelay_R) and (Power < 1) and // (BrakeCtrlPos < 1) then pr : = std::min(0.5, pr); @@ -217,7 +217,7 @@ double physics::Vehicle::PipeRatio(void) const // then pr : = pr * 1.333; // dziwny rapid wywalamy } else - pr = (HighPipePress - std::max(LowPipePress, std::min(HighPipePress, PipePress))) / DeltaPipePress; + pr = (HighPipePress - std::max(LowPipePress, std::min(HighPipePress, brakePipe.pressure))) / DeltaPipePress; else pr = 0; return pr; @@ -308,17 +308,17 @@ bool physics::Vehicle::AntiSlippingButton(void) bool physics::Vehicle::CompressorSwitch(bool State, range_t const Notify) { - if (CompressorStart != start_t::manual) + if (air.compressor.start != start_t::manual) { // only pay attention if the compressor can be controlled manually return false; } - auto const initialstate{CompressorAllow}; + auto const initialstate{air.compressor.allow}; - if (VeselVolume > 0.0 && CompressorSpeed > 0.0) + if (air.mainReservoirVolume > 0.0 && air.compressor.speed > 0.0) { - CompressorAllow = State; + air.compressor.allow = State; } if (Notify != range_t::local) @@ -326,22 +326,22 @@ bool physics::Vehicle::CompressorSwitch(bool State, range_t const Notify) SendCtrlToNext(VehicleCommand::compressorSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } - return CompressorAllow != initialstate; + return air.compressor.allow != initialstate; } bool physics::Vehicle::ChangeCompressorPreset(int const State, range_t const Notify) { - auto const initialstate{CompressorListPos}; + auto const initialstate{air.compressor.listPosition}; - CompressorListPos = safe_clamp(State, 0, CompressorListPosNo); + air.compressor.listPosition = safe_clamp(State, 0, air.compressor.listPositions); if (Notify != range_t::local) { SendCtrlToNext(VehicleCommand::compressorPreset, State, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } - return CompressorListPos != initialstate; + return air.compressor.listPosition != initialstate; } // ************************************************************************************************* @@ -360,7 +360,7 @@ bool physics::Vehicle::IncBrakeLevelOld(void) // youBy: EP po nowemu IBLO = true; if (BrakePressureActual.PipePressureVal < 0 && BrakePressureTable[BrakeCtrlPos - 1].PipePressureVal > 0) - LimPipePress = PipePress; + LimPipePress = brakePipe.pressure; } else { @@ -727,7 +727,7 @@ void physics::Vehicle::UpdateBrakePressure(double dt) dpLocalValve = 0; dpBrake = 0; - Hamulec->ForceLeak(dt * AirLeakRate * 0.25); // fake air leaks from brake system reservoirs + Hamulec->ForceLeak(dt * air.leakRate * 0.25); // fake air leaks from brake system reservoirs auto const brakepress{BrakePress}; BrakePress = Hamulec->GetBCP(); @@ -748,59 +748,59 @@ void physics::Vehicle::UpdateBrakePressure(double dt) void physics::Vehicle::CompressorCheck(double dt) { - if (CompressorSpeed == 0.0) + if (air.compressor.speed == 0.0) { - CompressorAllow = false; + air.compressor.allow = false; return; } - if (CabDependentCompressor) + if (air.compressor.cabDependent) { if (CabActive > 0) { - MinCompressor = MinCompressor_cabA; - MaxCompressor = MaxCompressor_cabA; + air.compressor.minPressure = air.compressor.minPressureCabA; + air.compressor.maxPressure = air.compressor.maxPressureCabA; } if (CabActive < 0) { - MinCompressor = MinCompressor_cabB; - MaxCompressor = MaxCompressor_cabB; + air.compressor.minPressure = air.compressor.minPressureCabB; + air.compressor.maxPressure = air.compressor.maxPressureCabB; } } // EmergencyValve - EmergencyValveOpen = Compressor > (EmergencyValveOpen ? EmergencyValveOff : EmergencyValveOn); + EmergencyValveOpen = air.mainReservoirPressure > (EmergencyValveOpen ? EmergencyValveOff : EmergencyValveOn); if (EmergencyValveOpen) { - auto dV = static_cast(PF(0, Compressor, EmergencyValveArea) * dt); - CompressedVolume -= dV; + auto dV = static_cast(PF(0, air.mainReservoirPressure, EmergencyValveArea) * dt); + air.compressedVolume -= dV; } - CompressedVolume = std::max(0.0, CompressedVolume - dt * AirLeakRate * 0.1); // nieszczelności: 0.001=1l/s + air.compressedVolume = std::max(0.0, air.compressedVolume - dt * air.leakRate * 0.1); // nieszczelności: 0.001=1l/s - Compressor = CompressedVolume / VeselVolume; + air.mainReservoirPressure = air.compressedVolume / air.mainReservoirVolume; // assorted operational logic - auto const MaxCompressorF{CompressorList[TCompressorList::cl_MaxFactor][CompressorListPos] * MaxCompressor}; - auto const MinCompressorF{CompressorList[TCompressorList::cl_MinFactor][CompressorListPos] * MinCompressor}; - auto const CompressorSpeedF{CompressorList[TCompressorList::cl_SpeedFactor][CompressorListPos] * CompressorSpeed}; + auto const MaxCompressorF{air.compressor.list[TCompressorList::cl_MaxFactor][air.compressor.listPosition] * air.compressor.maxPressure}; + auto const MinCompressorF{air.compressor.list[TCompressorList::cl_MinFactor][air.compressor.listPosition] * air.compressor.minPressure}; + auto const CompressorSpeedF{air.compressor.list[TCompressorList::cl_SpeedFactor][air.compressor.listPosition] * air.compressor.speed}; // checking the impact on the compressor allowance - if (auto const AllowFactor{CompressorList[TCompressorList::cl_Allow][CompressorListPos]}; AllowFactor > 0.5) + if (auto const AllowFactor{air.compressor.list[TCompressorList::cl_Allow][air.compressor.listPosition]}; AllowFactor > 0.5) { - CompressorAllow = AllowFactor > 1.5; + air.compressor.allow = AllowFactor > 1.5; } - switch (CompressorPower) + switch (air.compressor.supply) { - case 2: + case CompressorSupply::converter: { - CompressorAllow = ConverterAllow; + air.compressor.allow = ConverterAllow; break; } - case 3: + case CompressorSupply::engine: { // HACK: make sure compressor coupled with diesel engine is always ready for work - CompressorStart = start_t::automatic; + air.compressor.start = start_t::automatic; break; } default: @@ -810,61 +810,61 @@ void physics::Vehicle::CompressorCheck(double dt) } // the main circuit, also for a compressor driven by the engine, otherwise the low voltage - auto const compressorpower{CompressorPower == 0 || CompressorPower == 3 ? MainCircuitPowered() : Power110vIsAvailable}; - CompressorPowerTime = compressorpower ? CompressorPowerTime + dt : 0.0; - auto const compressorready{compressorpower && CompressorPowerTime >= CompressorStartDelay}; + auto const compressorpower{air.compressor.supply == CompressorSupply::mainCircuit || air.compressor.supply == CompressorSupply::engine ? MainCircuitPowered() : Power110vIsAvailable}; + air.compressor.powerTime = compressorpower ? air.compressor.powerTime + dt : 0.0; + auto const compressorready{compressorpower && air.compressor.powerTime >= air.compressor.startDelay}; // TBD: split CompressorAllow into separate enable/disable flags, inherit compressor from basic_device - auto const compressorenable{CompressorAllowLocal && (CompressorStart == start_t::automatic || CompressorAllow)}; + auto const compressorenable{air.compressor.allowLocal && (air.compressor.start == start_t::automatic || air.compressor.allow)}; auto const compressordisable{false == compressorenable}; - auto const pressureistoolow{Compressor < MinCompressorF}; - auto const pressureistoohigh{Compressor > MaxCompressorF}; + auto const pressureistoolow{air.mainReservoirPressure < MinCompressorF}; + auto const pressureistoohigh{air.mainReservoirPressure > MaxCompressorF}; // TBD, TODO: break the lock with no low voltage power? auto const governorlockispresent{MaxCompressorF - MinCompressorF > 0.0001}; - CompressorGovernorLock = governorlockispresent && false == pressureistoolow // unlock if pressure drops below minimal threshold - && (pressureistoohigh || CompressorGovernorLock); // lock if pressure goes above maximum threshold + air.compressor.governorLock = governorlockispresent && false == pressureistoolow // unlock if pressure drops below minimal threshold + && (pressureistoohigh || air.compressor.governorLock); // lock if pressure goes above maximum threshold // for these multi-unit engines compressors turn off whenever any of them was affected by the governor // NOTE: this is crude implementation, limited only to adjacent vehicles // TODO: re-implement when a more elegant/flexible system is in place auto const coupledgovernorlock{ - (Couplers[VehicleEnd::rear].Connected != nullptr && true == Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::permanent) && Couplers[VehicleEnd::rear].Connected->CompressorGovernorLock) || - (Couplers[VehicleEnd::front].Connected != nullptr && true == Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::permanent) && Couplers[VehicleEnd::front].Connected->CompressorGovernorLock)}; - auto const governorlock{CompressorGovernorLock || coupledgovernorlock}; + (Couplers[VehicleEnd::rear].Connected != nullptr && true == Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::permanent) && Couplers[VehicleEnd::rear].Connected->air.compressor.governorLock) || + (Couplers[VehicleEnd::front].Connected != nullptr && true == Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::permanent) && Couplers[VehicleEnd::front].Connected->air.compressor.governorLock)}; + auto const governorlock{air.compressor.governorLock || coupledgovernorlock}; - auto const compressorflag{CompressorFlag}; - CompressorFlag = - compressorready && false == compressordisable && (false == governorlock || CompressorPower == 3) && (CompressorFlag || (compressorenable && LastSwitchingTime > CtrlDelay)); + auto const compressorflag{air.compressor.running}; + air.compressor.running = + compressorready && false == compressordisable && (false == governorlock || air.compressor.supply == CompressorSupply::engine) && (air.compressor.running || (compressorenable && LastSwitchingTime > CtrlDelay)); - if (CompressorFlag && CompressorFlag != compressorflag) + if (air.compressor.running && air.compressor.running != compressorflag) { // jeśli została załączona to trzeba ograniczyć ponowne włączenie LastSwitchingTime = 0; } - if (CompressorFlag != compressorflag) + if (air.compressor.running != compressorflag) { - Timer::subsystem.switching.note(CompressorFlag ? Timer::switching_counter::compressor_on : Timer::switching_counter::compressor_off, this, &TypeName, &Name); + Timer::subsystem.switching.note(air.compressor.running ? Timer::switching_counter::compressor_on : Timer::switching_counter::compressor_off, this, &TypeName, &Name); } - if (false == CompressorFlag) + if (false == air.compressor.running) { return; } // working compressor adds air to the air reservoir - if (CompressorPower == 3) + if (air.compressor.supply == CompressorSupply::engine) { // the compressor is coupled with the diesel engine, engine revolutions affect the output - CompressedVolume += - CompressorSpeedF * (2.0 * MaxCompressorF - Compressor) / MaxCompressorF * EngineRPMRatio() * dt * (CompressorGovernorLock ? 0.0 : 1.0); // with the lock active air is vented out + air.compressedVolume += + CompressorSpeedF * (2.0 * MaxCompressorF - air.mainReservoirPressure) / MaxCompressorF * EngineRPMRatio() * dt * (air.compressor.governorLock ? 0.0 : 1.0); // with the lock active air is vented out } else { // the compressor is a stand-alone device, working at steady pace - CompressedVolume += CompressorSpeedF * (2.0 * MaxCompressorF - Compressor) / MaxCompressorF * dt; + air.compressedVolume += CompressorSpeedF * (2.0 * MaxCompressorF - air.mainReservoirPressure) / MaxCompressorF * dt; } - if (pressureistoohigh && (false == governorlockispresent || CompressorPower == 3)) + if (pressureistoohigh && (false == governorlockispresent || air.compressor.supply == CompressorSupply::engine)) { // vent some air out if there's no governor lock to stop the compressor from exceeding acceptable pressure level SetFlag(SoundFlag, sound::relay | sound::loud); @@ -873,14 +873,14 @@ void physics::Vehicle::CompressorCheck(double dt) { ventedfraction = 0.80; // arbitrary amount } - else if (CompressorTankValve) + else if (air.compressor.tankValve) { ventedfraction = MinCompressorF / MaxCompressorF; // drop to mincompressor level } - CompressedVolume *= ventedfraction; - if (false == governorlockispresent || CompressorTankValve) + air.compressedVolume *= ventedfraction; + if (false == governorlockispresent || air.compressor.tankValve) { - CompressorGovernorLock = false; + air.compressor.governorLock = false; } } @@ -893,10 +893,10 @@ void physics::Vehicle::CompressorCheck(double dt) // ************************************************************************************************* void physics::Vehicle::UpdatePipePressure(double dt) { - if (PipePress > 1.0) + if (brakePipe.pressure > 1.0) { - Pipe->Flow(-PipePress*AirLeakRate * dt); - Pipe->Act(); + brakePipe.reservoir->Flow(-brakePipe.pressure*air.leakRate * dt); + brakePipe.reservoir->Act(); } // double dV; @@ -904,7 +904,7 @@ void physics::Vehicle::UpdatePipePressure(double dt) double temp; // int b; - PipePress = Pipe->P(); + brakePipe.pressure = brakePipe.reservoir->P(); // PPP:=PipePress; dpMainValve = 0; @@ -919,8 +919,8 @@ void physics::Vehicle::UpdatePipePressure(double dt) UpdateEmergencyValve(dt); // 0.2*Spg - Pipe->Flow(-dpMainValve); - Pipe->Flow(-PipePress * 0.001 * dt); + brakePipe.reservoir->Flow(-dpMainValve); + brakePipe.reservoir->Flow(-brakePipe.pressure * 0.001 * dt); // if Heating then // Pipe.Flow(PF(PipePress, 0, d2A(7)) * dt); // if ConverterFlag then @@ -943,15 +943,15 @@ void physics::Vehicle::UpdatePipePressure(double dt) SwitchEPBrake(0); } - Pipe->Act(); - PipePress = Pipe->P(); + brakePipe.reservoir->Act(); + brakePipe.pressure = brakePipe.reservoir->P(); if ((Hamulec->GetBrakeStatus() & b_dmg) == b_dmg) // jesli hamulec wyłączony temp = 0.0; // odetnij else temp = 1.0; // połącz - Pipe->Flow(temp * Hamulec->GetPF(temp * PipePress, dt, Vel)); + brakePipe.reservoir->Flow(temp * Hamulec->GetPF(temp * brakePipe.pressure, dt, Vel)); // the air the brake hoses carry to and from the neighbours comes once all vehicles have stepped, UpdatePipeCouplers() - PipeCouplersPending = true; + brakePipe.couplersPending = true; if (ASBType == 128) Hamulec->ASB(int(SlippingWheels && Vel > 1) * (1 + 2 * int(nrot_eps < -0.01))); @@ -959,20 +959,20 @@ void physics::Vehicle::UpdatePipePressure(double dt) dpPipe = 0; // yB: jednokrokowe liczenie tego wszystkiego - Pipe->Act(); - PipePress = Pipe->P(); + brakePipe.reservoir->Act(); + brakePipe.pressure = brakePipe.reservoir->P(); dpMainValve = dpMainValve / (100.0 * dt); // normalizacja po czasie do syczenia; - if (PipePress < -1.0) + if (brakePipe.pressure < -1.0) { - PipePress = -1.0; - Pipe->CreatePress(-1.0); - Pipe->Act(); + brakePipe.pressure = -1.0; + brakePipe.reservoir->CreatePress(-1.0); + brakePipe.reservoir->Act(); } - if (CompressedVolume < 0.0) - CompressedVolume = 0.0; + if (air.compressedVolume < 0.0) + air.compressedVolume = 0.0; } // the flow of the local brake valve, by the handle, the TRAXX's timed one, the integrated controller or the parking @@ -990,7 +990,7 @@ void physics::Vehicle::UpdateLocalBrakeValve(double dt) { lbpa = std::max(lbpa, brakes.holding.deceleration); } - dpLocalValve = LocHandle->GetPF(PulleeMode ? 0.0 : std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); + dpLocalValve = LocHandle->GetPF(PulleeMode ? 0.0 : std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), mainPipe.pressure, dt, 0); } else { @@ -1011,7 +1011,7 @@ void physics::Vehicle::UpdateLocalBrakeValve(double dt) { lbpa = 0.0; } - dpLocalValve = LocHandle->GetPF(PulleeMode ? 0.0 : std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); + dpLocalValve = LocHandle->GetPF(PulleeMode ? 0.0 : std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), mainPipe.pressure, dt, 0); } } @@ -1031,43 +1031,43 @@ void physics::Vehicle::UpdateMainValve(double dt) if (BrakeOpModeFlag < bom_EP || Handle->GetPos(bh_EB) - 0.5 < BrakeCtrlPosR || (BrakeHandle != TBrakeHandle::MHZ_EN57 && BrakeHandle != TBrakeHandle::MHZ_K8P)) { - dpMainValve = Handle->GetPF(MainValveHandlePosition(), PipePress, temp, dt, EqvtPipePress); + dpMainValve = Handle->GetPF(MainValveHandlePosition(), brakePipe.pressure, temp, dt, EqvtPipePress); } else { - dpMainValve = Handle->GetPF(0, PipePress, temp, dt, EqvtPipePress); + dpMainValve = Handle->GetPF(0, brakePipe.pressure, temp, dt, EqvtPipePress); } } else if (BrakeCtrlPos == Handle->GetPos(bh_EB)) { - dpMainValve = Handle->GetPF(BrakeCtrlPosR, PipePress, temp, dt, EqvtPipePress); + dpMainValve = Handle->GetPF(BrakeCtrlPosR, brakePipe.pressure, temp, dt, EqvtPipePress); } if (dpMainValve < 0) // && (PipePressureVal > 0.01) //50 { - if (Compressor > ScndPipePress) + if (air.mainReservoirPressure > mainPipe.pressure) { - CompressedVolume = CompressedVolume + dpMainValve / 1500.0; - Pipe2->Flow(dpMainValve / 3.0); + air.compressedVolume = air.compressedVolume + dpMainValve / 1500.0; + mainPipe.reservoir->Flow(dpMainValve / 3.0); } else - Pipe2->Flow(dpMainValve); + mainPipe.reservoir->Flow(dpMainValve); } } // the pressure the driver's handle is fed from: the main pipe's, or the brake pipe's own with the pipe locked double physics::Vehicle::MainValveSupply() { - LockPipe = PipePress < (LockPipe ? LockPipeOff : LockPipeOn); + LockPipe = brakePipe.pressure < (LockPipe ? LockPipeOff : LockPipeOn); bool lock_new = (LockPipe && !UnlockPipe && BrakeCtrlPosR > HandleUnlock) || (EmergencyCutsOffHandle && EmergencyValveFlow > 0); // new simple codition based on .fiz bool lock_old = BrakeHandle == TBrakeHandle::FV4a // old complex condition based on assumptions - && PipePress < 2.75 && (Hamulec->GetStatus() & b_rls) == 0 && BrakeSubsystem == TBrakeSubSystem::ss_LSt && TrainType != train_type::emu && !UnlockPipe; + && brakePipe.pressure < 2.75 && (Hamulec->GetStatus() & b_rls) == 0 && BrakeSubsystem == TBrakeSubSystem::ss_LSt && TrainType != train_type::emu && !UnlockPipe; if (lock_old || lock_new) { - return PipePress + 0.00001; + return brakePipe.pressure + 0.00001; } - return ScndPipePress; + return mainPipe.pressure; } // the position the driver's handle works at: its own, or the one the speed control's brake intervention sets @@ -1101,7 +1101,7 @@ void physics::Vehicle::UpdateEmergencyValve(double dt) (0 == CabActive && (InactiveCabFlag & activation::emergencybrake) != 0)}; if (AlarmChainFlag || (ownemergency && false == PulleeMode)) { - EmergencyValveFlow = PF(0, PipePress, 0.15) * dt; + EmergencyValveFlow = PF(0, brakePipe.pressure, 0.15) * dt; } dpMainValve += EmergencyValveFlow; } @@ -1246,34 +1246,34 @@ void physics::Vehicle::UpdateEPBrake() // ************************************************************************************************* void physics::Vehicle::UpdateScndPipePressure(double dt) { - if (ScndPipePress > 1.0) + if (mainPipe.pressure > 1.0) { - Pipe2->Flow(-ScndPipePress*AirLeakRate * dt); - Pipe2->Act(); + mainPipe.reservoir->Flow(-mainPipe.pressure*air.leakRate * dt); + mainPipe.reservoir->Act(); } const double Spz = 0.5067; UpdateSpringBrake(dt); - Pipe2->Flow(Hamulec->GetHPFlow(ScndPipePress, dt)); + mainPipe.reservoir->Flow(Hamulec->GetHPFlow(mainPipe.pressure, dt)); // NOTE: condition disabled to allow the air flow from the main hose to the main tank as well - if (/* ( ( Compressor > ScndPipePress ) && ( */ VeselVolume > 0.0 /* ) ) || ( TrainType == train_type::emu ) || ( TrainType == train_type::dmu ) */) + if (/* ( ( Compressor > ScndPipePress ) && ( */ air.mainReservoirVolume > 0.0 /* ) ) || ( TrainType == train_type::emu ) || ( TrainType == train_type::dmu ) */) { - double const dV = PF(Compressor, ScndPipePress, Spz) * dt; - CompressedVolume += dV / 1000.0; - Pipe2->Flow(-dV); + double const dV = PF(air.mainReservoirPressure, mainPipe.pressure, Spz) * dt; + air.compressedVolume += dV / 1000.0; + mainPipe.reservoir->Flow(-dV); } // the air the main reservoir hoses carry to and from the neighbours comes once all vehicles have stepped, UpdatePipeCouplers() - ScndPipeCouplersPending = true; - Pipe2->Act(); - ScndPipePress = Pipe2->P(); + mainPipe.couplersPending = true; + mainPipe.reservoir->Act(); + mainPipe.pressure = mainPipe.reservoir->P(); - if (ScndPipePress < -1) + if (mainPipe.pressure < -1) { - ScndPipePress = -1; - Pipe2->CreatePress(-1); - Pipe2->Act(); + mainPipe.pressure = -1; + mainPipe.reservoir->CreatePress(-1); + mainPipe.reservoir->Act(); } } @@ -1287,10 +1287,10 @@ void physics::Vehicle::UpdateSpringBrake(double /*dt*/) double MSP = brakes.spring.shutOff ? 0 : brakes.spring.maxSetPressure; if (!brakes.spring.activate) { - double desired_press = std::min(std::max(MSP, BP), Pipe2->P()); + double desired_press = std::min(std::max(MSP, BP), mainPipe.reservoir->P()); double dv = PF(desired_press, brakes.spring.pressure, brakes.spring.valveOffArea); brakes.spring.cylinder->Flow(-dv); - Pipe2->Flow(std::max(dv, 0.0)); + mainPipe.reservoir->Flow(std::max(dv, 0.0)); } else { @@ -1314,23 +1314,23 @@ namespace // Global.physics_pipewake only a flow which leaves its pressure, with what has flown in while it slept, that much away from the // pressure of the vehicle the air comes from, or which has changed it by that much since it fell asleep: a pressure followed in // small steps would never reach the valves of a vehicle asleep otherwise -bool pipe_wakes(double const Flow, double const Pressure, TReservoir const &Pipe) +bool pipe_wakes(double const Flow, double const Pressure, TReservoir const &Reservoir) { if (Flow * Flow <= 0.00000000000001) return false; return (Global.physics_pipewake <= 0.f) - || (std::abs(Pressure - Pipe.P_pending()) > Global.physics_pipewake) - || (std::abs(Pipe.P_pending() - Pipe.P_applied()) > Global.physics_pipewake); + || (std::abs(Pressure - Reservoir.P_pending()) > Global.physics_pipewake) + || (std::abs(Reservoir.P_pending() - Reservoir.P_applied()) > Global.physics_pipewake); } // the pressure in the pipe of a coupled vehicle the flow to it goes by. the pressure the vehicle keeps is the one of its last step: // with Global.physics_pipewake one asleep can take air for a long time without waking, and the flow, going by that pressure, would // carry on past the pressure of the vehicle it comes from. so of one asleep, the pressure with what has flown in since -double neighbour_pipe_pressure(physics::Vehicle const &Neighbour, double const Pressure, TReservoir const &Pipe) +double neighbour_pipe_pressure(physics::Vehicle const &Neighbour, double const Pressure, TReservoir const &Reservoir) { if ((Global.physics_pipewake <= 0.f) || Neighbour.PhysicActivation) return Pressure; - return Pipe.P_pending(); + return Reservoir.P_pending(); } } // namespace @@ -1352,18 +1352,18 @@ double physics::Vehicle::GetDVc(double dt) if (Couplers[0].Connected != nullptr && Couplers[0].CouplingFlag.HasAll(Coupling::brakeHose)) { //*0.85 c = Couplers[0].Connected; // skrot //0.08 //e/D * L/D = e/D^2 * L - dv1 = 0.5 * dt * PF(PipePress, neighbour_pipe_pressure(*c, c->PipePress, *c->Pipe), Spg / (1.0 + 0.015 / Spg * Dim.L)); - c->Pipe->Flow(-dv1); - if (pipe_wakes(dv1, PipePress, *c->Pipe)) + dv1 = 0.5 * dt * PF(brakePipe.pressure, neighbour_pipe_pressure(*c, c->brakePipe.pressure, *c->brakePipe.reservoir), Spg / (1.0 + 0.015 / Spg * Dim.L)); + c->brakePipe.reservoir->Flow(-dv1); + if (pipe_wakes(dv1, brakePipe.pressure, *c->brakePipe.reservoir)) c->switch_physics(true, wake_cause::mainpipe); } // sprzeg 2 if (Couplers[1].Connected != nullptr && Couplers[1].CouplingFlag.HasAll(Coupling::brakeHose)) { c = Couplers[1].Connected; // skrot - dv2 = 0.5 * dt * PF(PipePress, neighbour_pipe_pressure(*c, c->PipePress, *c->Pipe), Spg / (1.0 + 0.015 / Spg * Dim.L)); - c->Pipe->Flow(-dv2); - if (pipe_wakes(dv2, PipePress, *c->Pipe)) + dv2 = 0.5 * dt * PF(brakePipe.pressure, neighbour_pipe_pressure(*c, c->brakePipe.pressure, *c->brakePipe.reservoir), Spg / (1.0 + 0.015 / Spg * Dim.L)); + c->brakePipe.reservoir->Flow(-dv2); + if (pipe_wakes(dv2, brakePipe.pressure, *c->brakePipe.reservoir)) c->switch_physics(true, wake_cause::mainpipe); } // if ((Couplers[1].Connected != NULL) && (Couplers[0].Connected != NULL)) @@ -1395,25 +1395,25 @@ double physics::Vehicle::GetScndDVc(double dt) if (Couplers[0].Connected != nullptr && Couplers[0].CouplingFlag.HasAll(Coupling::mainHose)) { c = Couplers[0].Connected; // skrot - dv1 = 0.5 * dt * PF(ScndPipePress, neighbour_pipe_pressure(*c, c->ScndPipePress, *c->Pipe2), Spz * 0.75); - c->Pipe2->Flow(-dv1); - if (pipe_wakes(dv1, ScndPipePress, *c->Pipe2)) + dv1 = 0.5 * dt * PF(mainPipe.pressure, neighbour_pipe_pressure(*c, c->mainPipe.pressure, *c->mainPipe.reservoir), Spz * 0.75); + c->mainPipe.reservoir->Flow(-dv1); + if (pipe_wakes(dv1, mainPipe.pressure, *c->mainPipe.reservoir)) c->switch_physics(true, wake_cause::scndpipe); } // sprzeg 2 if (Couplers[1].Connected != nullptr && Couplers[1].CouplingFlag.HasAll(Coupling::mainHose)) { c = Couplers[1].Connected; // skrot - dv2 = 0.5 * dt * PF(ScndPipePress, neighbour_pipe_pressure(*c, c->ScndPipePress, *c->Pipe2), Spz * 0.75); - c->Pipe2->Flow(-dv2); - if (pipe_wakes(dv2, ScndPipePress, *c->Pipe2)) + dv2 = 0.5 * dt * PF(mainPipe.pressure, neighbour_pipe_pressure(*c, c->mainPipe.pressure, *c->mainPipe.reservoir), Spz * 0.75); + c->mainPipe.reservoir->Flow(-dv2); + if (pipe_wakes(dv2, mainPipe.pressure, *c->mainPipe.reservoir)) c->switch_physics(true, wake_cause::scndpipe); } if (Couplers[1].Connected != nullptr && Couplers[0].Connected != nullptr && Couplers[0].CouplingFlag.HasAll(Coupling::mainHose) && Couplers[1].CouplingFlag.HasAll(Coupling::mainHose)) { - double const dV = 0.00025 * dt * PF(Couplers[0].Connected->ScndPipePress, Couplers[1].Connected->ScndPipePress, Spz * 0.25); - Couplers[0].Connected->Pipe2->Flow(+dV); - Couplers[1].Connected->Pipe2->Flow(-dV); + double const dV = 0.00025 * dt * PF(Couplers[0].Connected->mainPipe.pressure, Couplers[1].Connected->mainPipe.pressure, Spz * 0.25); + Couplers[0].Connected->mainPipe.reservoir->Flow(+dV); + Couplers[1].Connected->mainPipe.reservoir->Flow(-dV); } return dv1 + dv2; } @@ -1424,46 +1424,40 @@ namespace // a pipe along the train, whose air the hoses between the vehicles carry (physics::Vehicle::UpdatePipeCouplers()) struct train_pipe { - std::shared_ptr physics::Vehicle::*reservoir; - double physics::Vehicle::*pressure; - bool physics::Vehicle::*pending; // the vehicle stepped the pipe, the exchange through its hoses is yet to come + physics::TrainPipe physics::Vehicle::*pipe; // the reservoir, the pressure and whether the exchange through the hoses is yet to come CouplingSet hose; // the coupling of the pipe's hose double (physics::Vehicle::*exchange)(double); // the air the hoses carry in a step, the neighbours' share sent to them double (*area)(physics::Vehicle const &); // the cross-section of the hose, as the exchange takes it }; // the brake pipe, GetDVc() -train_pipe const brake_pipe{&physics::Vehicle::Pipe, - &physics::Vehicle::PipePress, - &physics::Vehicle::PipeCouplersPending, +train_pipe const brake_pipe{&physics::Vehicle::brakePipe, Coupling::brakeHose, &physics::Vehicle::GetDVc, [](physics::Vehicle const &Vehicle) { return Vehicle.Spg / (1.0 + 0.015 / Vehicle.Spg * Vehicle.Dim.L); }}; // the main reservoir pipe, GetScndDVc() -train_pipe const main_reservoir_pipe{&physics::Vehicle::Pipe2, - &physics::Vehicle::ScndPipePress, - &physics::Vehicle::ScndPipeCouplersPending, +train_pipe const main_reservoir_pipe{&physics::Vehicle::mainPipe, Coupling::mainHose, &physics::Vehicle::GetScndDVc, [](physics::Vehicle const &) { return 0.5067 * 0.75; }}; // the number of sub-steps of dt the air exchange through the hoses of the vehicle's pipe needs: in one, the air a // hose carries stays below what evens out the pipes on its ends -int hose_substeps(physics::Vehicle const &Vehicle, train_pipe const &Pipe, double const dt) +int hose_substeps(physics::Vehicle const &Vehicle, train_pipe const &trainPipe, double const dt) { auto substeps{1}; - auto const area{Pipe.area(Vehicle)}; - auto const capacity{(Vehicle.*Pipe.reservoir)->GetCap()}; + auto const area{trainPipe.area(Vehicle)}; + auto const capacity{(Vehicle.*trainPipe.pipe).reservoir->GetCap()}; for (auto const &hose : Vehicle.Couplers) { - if (hose.Connected == nullptr || false == hose.CouplingFlag.HasAll(Pipe.hose)) + if (hose.Connected == nullptr || false == hose.CouplingFlag.HasAll(trainPipe.hose)) { continue; } auto const &other{*hose.Connected}; - auto const othercapacity{(other.*Pipe.reservoir)->GetCap()}; + auto const othercapacity{(other.*trainPipe.pipe).reservoir->GetCap()}; // the flow per bar of the difference, at small differences, where it's the largest - auto const pressure{std::max(Vehicle.*Pipe.pressure, other.*Pipe.pressure)}; + auto const pressure{std::max((Vehicle.*trainPipe.pipe).pressure, (other.*trainPipe.pipe).pressure)}; auto const conductance{std::abs(PF(pressure, pressure - 0.01, area)) / 0.01}; auto const equalising{capacity * othercapacity / (capacity + othercapacity)}; substeps = std::max(substeps, static_cast(std::ceil(dt * conductance / equalising))); @@ -1474,7 +1468,7 @@ int hose_substeps(physics::Vehicle const &Vehicle, train_pipe const &Pipe, doubl // the vehicles of the list which stepped the pipe, each with the number of the train it is in: the ones joined by the hoses // of the pipe, directly, numbered in the order of their first vehicle in the list. a vehicle which didn't step the pipe // (its physics sleeps) takes the air sent to it without passing it on, so it ends a train -std::vector hose_trains(std::vector const &Vehicles, train_pipe const &Pipe) +std::vector hose_trains(std::vector const &Vehicles, train_pipe const &trainPipe) { auto constexpr none{std::numeric_limits::max()}; std::vector trains(Vehicles.size(), none); @@ -1483,7 +1477,7 @@ std::vector hose_trains(std::vector const &Vehi byaddress.reserve(Vehicles.size()); for (std::size_t index = 0; index < Vehicles.size(); ++index) { - if (Vehicles[index]->*Pipe.pending) + if ((Vehicles[index]->*trainPipe.pipe).couplersPending) { byaddress.emplace_back(Vehicles[index], index); } @@ -1497,7 +1491,7 @@ std::vector hose_trains(std::vector const &Vehi std::vector stack; for (std::size_t first = 0; first < Vehicles.size(); ++first) { - if (false == Vehicles[first]->*Pipe.pending || trains[first] != none) + if (false == (Vehicles[first]->*trainPipe.pipe).couplersPending || trains[first] != none) { continue; } @@ -1509,7 +1503,7 @@ std::vector hose_trains(std::vector const &Vehi stack.pop_back(); for (auto const &hose : vehicle.Couplers) { - if (hose.Connected == nullptr || false == hose.CouplingFlag.HasAll(Pipe.hose)) + if (hose.Connected == nullptr || false == hose.CouplingFlag.HasAll(trainPipe.hose)) { continue; } @@ -1530,13 +1524,13 @@ std::vector hose_trains(std::vector const &Vehi // 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 &Pipe, double const dt) +void exchange_through_hoses(std::vector const &Vehicles, train_pipe const &trainPipe, double const dt) { - auto const trains{hose_trains(Vehicles, Pipe)}; + auto const trains{hose_trains(Vehicles, trainPipe)}; std::vector substeps; for (std::size_t index = 0; index < Vehicles.size(); ++index) { - if (false == Vehicles[index]->*Pipe.pending) + if (false == (Vehicles[index]->*trainPipe.pipe).couplersPending) { continue; } @@ -1544,7 +1538,7 @@ void exchange_through_hoses(std::vector const &Vehicles, tra { substeps.resize(trains[index] + 1, 1); } - substeps[trains[index]] = std::max(substeps[trains[index]], hose_substeps(*Vehicles[index], Pipe, dt)); + substeps[trains[index]] = std::max(substeps[trains[index]], hose_substeps(*Vehicles[index], trainPipe, dt)); } for (std::size_t train = 0; train < substeps.size(); ++train) { @@ -1553,23 +1547,23 @@ void exchange_through_hoses(std::vector const &Vehicles, tra { for (std::size_t index = 0; index < Vehicles.size(); ++index) { - if (false == Vehicles[index]->*Pipe.pending || trains[index] != train) + if (false == (Vehicles[index]->*trainPipe.pipe).couplersPending || trains[index] != train) { continue; } auto *vehicle{Vehicles[index]}; - auto &pipe{*(vehicle->*Pipe.reservoir)}; + auto &pipe{*(vehicle->*trainPipe.pipe).reservoir}; pipe.Act(); // what the neighbours have sent in the meantime - vehicle->*Pipe.pressure = pipe.P(); - pipe.Flow((vehicle->*Pipe.exchange)(substep)); + (vehicle->*trainPipe.pipe).pressure = pipe.P(); + pipe.Flow((vehicle->*trainPipe.exchange)(substep)); pipe.Act(); - vehicle->*Pipe.pressure = pipe.P(); + (vehicle->*trainPipe.pipe).pressure = pipe.P(); } } } for (auto *vehicle : Vehicles) { - vehicle->*Pipe.pending = false; + (vehicle->*trainPipe.pipe).couplersPending = false; } } diff --git a/physics/components/setup.cpp b/physics/components/setup.cpp index 1ad40b41c..cbd4e4b98 100644 --- a/physics/components/setup.cpp +++ b/physics/components/setup.cpp @@ -49,9 +49,9 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) Sand = SandCapacity; // NOTE: for diesel-powered vehicles we automatically convert legacy "main" power source to more accurate "engine" - if (CompressorPower == 0 && (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric)) + if (air.compressor.supply == CompressorSupply::mainCircuit && (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric)) { - CompressorPower = 3; + air.compressor.supply = CompressorSupply::engine; } // for these engine types secondary controller positions index MotorParam table @@ -96,8 +96,8 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) // set default wiper switch position wiperSwitchPos = WiperDefaultPos; - if (CompressorListPosNo > 0) - CompressorListPos = CompressorListDefPos; + if (air.compressor.listPositions > 0) + air.compressor.listPosition = air.compressor.listDefaultPosition; // the genset of a dual-mode vehicle is a second source of the traction circuit of an induction motor vehicle if (Genset.fitted() && (EngineType != TEngineType::ElectricInductionMotor || EnginePowerSource.SourceType != TPowerSource::CurrentCollector)) @@ -134,14 +134,14 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) if (BrakeLocHandle == TBrakeHandle::Knorr) LocalBrakePosA = 0.5; - Pipe->CreatePress(PipePress); - Pipe2->CreatePress(ScndPipePress); - Pipe->Act(); - Pipe2->Act(); + brakePipe.reservoir->CreatePress(brakePipe.pressure); + mainPipe.reservoir->CreatePress(mainPipe.pressure); + brakePipe.reservoir->Act(); + mainPipe.reservoir->Act(); - EqvtPipePress = PipePress; + EqvtPipePress = brakePipe.pressure; - Handle->Init(PipePress); + Handle->Init(brakePipe.pressure); ComputeConstans(); @@ -188,7 +188,7 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) BrakeDelay[b] = BrakeDelay[b] * (2.5 + Random(0.0, 0.2)) / 3.0; } - Hamulec->Init(PipePress, HighPipePress, LowPipePress, BrakePress, BrakeDelayFlag); + Hamulec->Init(brakePipe.pressure, HighPipePress, LowPipePress, BrakePress, BrakeDelayFlag); /* ScndPipePress = Compressor; */ @@ -392,10 +392,10 @@ void physics::Vehicle::CreateBrakePipes() Spg = 0.507; // WriteLog("SPG = " + FloatToStr(Spg)); - Pipe = std::make_shared(); - Pipe2 = std::make_shared(); // zabezpieczenie, bo sie PG wywala... :( - Pipe->CreateCap((std::max(Dim.L, 14.0) + 0.5) * Spg * 1); // dlugosc x przekroj x odejscia i takie tam - Pipe2->CreateCap((std::max(Dim.L, 14.0) + 0.5) * Spg * 1); + brakePipe.reservoir = std::make_shared(); + mainPipe.reservoir = std::make_shared(); // zabezpieczenie, bo sie PG wywala... :( + brakePipe.reservoir->CreateCap((std::max(Dim.L, 14.0) + 0.5) * Spg * 1); // dlugosc x przekroj x odejscia i takie tam + mainPipe.reservoir->CreateCap((std::max(Dim.L, 14.0) + 0.5) * Spg * 1); if (!brakes.spring.cylinder) { brakes.spring.cylinder = std::make_shared(); @@ -406,9 +406,9 @@ void physics::Vehicle::CreateBrakePipes() // the pressure of the main pipe at the start: the main reservoir's, or HosePressure fed through a main hose, or none double physics::Vehicle::InitialScndPipePress(double const HosePressure) const { - if (VeselVolume > 0.0) + if (air.mainReservoirVolume > 0.0) { - return CompressedVolume / VeselVolume; + return air.compressedVolume / air.mainReservoirVolume; } if (Couplers[VehicleEnd::front].AllowedFlag.HasAny(Coupling::mainHose) || Couplers[VehicleEnd::rear].AllowedFlag.HasAny(Coupling::mainHose)) { @@ -421,9 +421,9 @@ double physics::Vehicle::InitialScndPipePress(double const HosePressure) const void physics::Vehicle::SetReadyToDepart() { WriteLog("Ready to depart"); - CompressedVolume = VeselVolume * MinCompressor * 9.8 / 10.0; - ScndPipePress = InitialScndPipePress(5.0); - PipePress = CntrlPipePress; + air.compressedVolume = air.mainReservoirVolume * air.compressor.minPressure * 9.8 / 10.0; + mainPipe.pressure = InitialScndPipePress(5.0); + brakePipe.pressure = CntrlPipePress; BrakePress = 0.0; LocalBrakePosA = 0.0; if (CabActive == 0) @@ -449,12 +449,12 @@ void physics::Vehicle::SetBraked() { WriteLog("Braked"); Volume = BrakeVVolume * MaxBrakePress[3]; - CompressedVolume = VeselVolume * MinCompressor * 0.55; + air.compressedVolume = air.mainReservoirVolume * air.compressor.minPressure * 0.55; /* ScndPipePress = 5.1; */ - ScndPipePress = InitialScndPipePress(5.1); - PipePress = LowPipePress; + mainPipe.pressure = InitialScndPipePress(5.1); + brakePipe.pressure = LowPipePress; PipeBrakePress = MaxBrakePress[3] * 0.5; BrakePress = MaxBrakePress[3] * 0.5; LocalBrakePosA = 0.0; diff --git a/physics/components/traction.cpp b/physics/components/traction.cpp index 62b45c2c2..f0e33a702 100644 --- a/physics/components/traction.cpp +++ b/physics/components/traction.cpp @@ -113,7 +113,7 @@ double physics::Vehicle::Current(double n, double U) } // writepaslog("MotorCurrent ", FloatToStr(MotorCurrent)); - if (DynamicBrakeType == dbrake_switch && (BrakePress > 2.0 || PipePress < 3.6)) + if (DynamicBrakeType == dbrake_switch && (BrakePress > 2.0 || brakePipe.pressure < 3.6)) { Im = 0; // Im:=0; diff --git a/physics/vehicle.h b/physics/vehicle.h index 7d9e5b8a1..0510ce0d3 100644 --- a/physics/vehicle.h +++ b/physics/vehicle.h @@ -25,6 +25,7 @@ http://mozilla.org/MPL/2.0/. #include "physics/components/dieselengine.h" #include "physics/components/inductionmotor.h" #include "physics/components/braking.h" +#include "physics/components/airsupply.h" class TractionDrive; @@ -889,8 +890,9 @@ class Vehicle std::shared_ptr Hamulec; std::shared_ptr Handle; std::shared_ptr LocHandle; - std::shared_ptr Pipe; - std::shared_ptr Pipe2; + TrainPipe brakePipe; // the brake pipe along the train + TrainPipe mainPipe; // the main reservoir pipe along the train + AirSupply air; // the compressor and the main reservoir (physics/components/airsupply.h) Braking brakes; // the blending, the holding brake, the spring brake (physics/components/braking.h) TLocalBrake LocalBrake = TLocalBrake::NoBrake; /*rodzaj hamulca indywidualnego*/ @@ -923,7 +925,6 @@ class Vehicle double CntrlPipePress = 0.0; // ciśnienie z zbiorniku sterującym double BrakeVolume = 0.0; double BrakeVVolume = 0.0; - double VeselVolume = 0.0; /*pojemnosc powietrza w ukladzie hamulcowym, w ukladzie glownej sprezarki [m^3] */ int BrakeCylNo = 0; /*ilosc cylindrow ham.*/ double BrakeCylRadius = 0.0; @@ -939,15 +940,6 @@ class Vehicle int BrakeValveSize = 0; std::string BrakeValveParams; double Spg = 0.0; - double MinCompressor = 0.0; - double MaxCompressor = 0.0; - double MinCompressor_cabA = 0.0; - double MaxCompressor_cabA = 0.0; - double MinCompressor_cabB = 0.0; - double MaxCompressor_cabB = 0.0; - bool CabDependentCompressor = false; - double CompressorSpeed = 0.0; - int CompressorList[4][9]; // pozycje świateł, przód - tył, 1 .. 16 double EmergencyValveOn = 0.0; double EmergencyValveOff = 0.0; bool EmergencyValveOpen = false; @@ -956,12 +948,8 @@ class Vehicle double LockPipeOff = -1.0; double HandleUnlock = -3.0; bool EmergencyCutsOffHandle = false; - int CompressorListPosNo = 0; - int CompressorListDefPos = 1; - bool CompressorListWrap = false; /*cisnienie wlaczania, zalaczania sprezarki, wydajnosc sprezarki*/ TBrakeDelayTable BrakeDelay; /*opoznienie hamowania/odhamowania t/o*/ - double AirLeakRate{0.01}; // base rate of air leak from brake system components ( 0.001 = 1 l/sec ) int BrakeCtrlPosNo = 0; /*ilosc pozycji hamulca*/ /*nastawniki:*/ int MainCtrlPosNo = 0; /*ilosc pozycji nastawnika*/ @@ -1088,7 +1076,6 @@ class Vehicle double RVentSpeed{0.5}; // rozpedzanie sie wentylatora obr/s^2} double RVentMinI{50.0}; // przy jakim pradzie sie wylaczaja} bool RVentForceOn{false}; // forced activation switch - int CompressorPower = 1; // 0: main circuit, 1: z przetwornicy, reczne, 2: w przetwornicy, stale, 3: diesel engine, 4: converter of unit in front, 5: converter of unit behind int SmallCompressorPower = 0; /*Winger ZROBIC*/ bool Trafo = false; /*pojazd wyposażony w transformator*/ @@ -1232,28 +1219,14 @@ class Vehicle double dpLocalValve = 0.0; double EmergencyValveFlow = 0.0; // air flow through alerter valve during last simulation step /*! przyrosty cisnienia w kroku czasowym*/ - double ScndPipePress = 0.0; /*cisnienie w przewodzie zasilajacym*/ - bool ScndPipeCouplersPending{false}; // the main reservoir pipe stepped, its air exchange through the hoses is yet to come (UpdatePipeCouplers()) double BrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych*/ double BrakePressRate = 0.0; // how fast BrakePress changes, averaged over about a second [bar/s], see accelerating() double LocBrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych z pomocniczego*/ double PipeBrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych z przewodu*/ - double PipePress = 0.0; /*!o cisnienie w przewodzie glownym*/ - bool PipeCouplersPending{false}; // the brake pipe stepped, its air exchange through the hoses is yet to come (UpdatePipeCouplers()) double EqvtPipePress = 0.0; /*!o cisnienie w przewodzie glownym skladu*/ double Volume = 0.0; /*objetosc spr. powietrza w zbiorniku hamulca*/ - double CompressedVolume = 0.0; /*objetosc spr. powietrza w ukl. zasilania*/ double PantVolume = 0.48; /*objetosc spr. powietrza w ukl. pantografu*/ // aby podniesione pantografy opadły w krótkim czasie przy wyłączonej sprężarce - double Compressor = 0.0; /*! cisnienie w ukladzie zasilajacym*/ - bool CompressorFlag = false; /*!o czy wlaczona sprezarka*/ bool PantCompFlag = false; /*!o czy wlaczona sprezarka pantografow*/ - bool CompressorAllow = false; /*! zezwolenie na uruchomienie sprezarki NBMX*/ - bool CompressorAllowLocal{true}; // local device state override (most units don't have this fitted so it's set to true not to intefere) - bool CompressorGovernorLock{false}; // indicates whether compressor pressure switch was activated due to reaching cut-out pressure - double CompressorStartDelay{0.0}; // time [s] the compressor waits after getting its power before it can start, after the engine starts say - double CompressorPowerTime{0.0}; // time [s] since the compressor got its power - bool CompressorTankValve{false}; // indicates excessive pressure is vented from compressor tank directly and instantly - start_t CompressorStart{start_t::manual}; // whether the compressor is started manually, or another way start_t PantographCompressorStart{start_t::manual}; basic_valve PantsValve; ByEnd Pantographs; @@ -1359,7 +1332,6 @@ class Vehicle int MainCtrlPos = 0; /*polozenie glownego nastawnika*/ int ScndCtrlPos = 0; /*polozenie dodatkowego nastawnika*/ int LightsPos = 0; /*polozenie przelacznika wielopozycyjnego swiatel*/ - int CompressorListPos = 0; /*polozenie przelacznika wielopozycyjnego sprezarek*/ int DirActive = 0; // czy lok. jest wlaczona i w ktorym kierunku: względem wybranej kabiny: -1 - do tylu, +1 - do przodu, 0 - wylaczona int DirAbsolute = 0; // zadany kierunek jazdy względem sprzęgów (1=w strone 0,-1=w stronę 1) int MainCtrlMaxDirChangePos{0}; // can't change reverser state with master controller set above this position @@ -1927,7 +1899,7 @@ class Vehicle // (EmergencyBrakeMainOffPressure) while the master controller is on a power position bool EmergencyBrakeHoldsMainOff() const { - return EmergencyBrakeMainOffPressure > 0.0 && PipePress < EmergencyBrakeMainOffPressure && false == IsMainCtrlNoPowerPos(); + return EmergencyBrakeMainOffPressure > 0.0 && brakePipe.pressure < EmergencyBrakeMainOffPressure && false == IsMainCtrlNoPowerPos(); } // whether the lamp of the open line contactors is lit. on the electric locomotives it tells the start can be made, so // it goes out with the start cut off; on the diesel-electric ones (the SU45 and SU46 family) it just tells the @@ -1949,7 +1921,7 @@ class Vehicle // whether the pneumatic louvres of the motor fans are still closed, the main reservoir short of the pressure that opens them bool LouvresClosed() const { - return Compressor < LouvresOpenPressure; + return air.mainReservoirPressure < LouvresOpenPressure; } // whether the devices the line contactors are interlocked with (LineContactorsInterlock) let them close bool LineContactorsInterlockReleased() const; diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index c948f9e43..a65181405 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -75,7 +75,7 @@ std::uint32_t devices_of(physics::Vehicle const &Occupied, physics::Vehicle cons auto const on{[](bool const State, std::uint32_t const Bit) { return State ? Bit : 0u; }}; return on(Occupied.Battery || Controlling.Battery, device::battery) | on(Controlling.Mains, device::main_breaker) | on(Controlling.Pantographs[VehicleEnd::front].is_active, device::pantograph_front) | on(Controlling.Pantographs[VehicleEnd::rear].is_active, device::pantograph_rear) | - on(Controlling.ConverterFlag, device::converter) | on(Controlling.CompressorFlag, device::compressor) | on(Controlling.StLinFlag, device::line_contactors) | + on(Controlling.ConverterFlag, device::converter) | on(Controlling.air.compressor.running, device::compressor) | on(Controlling.StLinFlag, device::line_contactors) | on(Controlling.FuseFlag, device::overload_relay) | on(Controlling.SandDose, device::sanding) | on(Occupied.WarningSignal != 0, device::horn) | on(false == Occupied.Doors.instances[VehicleSide::left].is_closed, device::doors_left) | on(false == Occupied.Doors.instances[VehicleSide::right].is_closed, device::doors_right) | on(Occupied.Radio, device::radio) | @@ -453,12 +453,12 @@ void blackbox_recorder::write_cab() { sample.train_brake = static_cast(occupied->fBrakeCtrlPos); sample.local_brake = static_cast(occupied->LocalBrakePosA); sample.brake_cylinder = static_cast(occupied->BrakePress); - sample.brake_pipe = static_cast(occupied->PipePress); + sample.brake_pipe = static_cast(occupied->brakePipe.pressure); sample.motor_current = static_cast(controlling->Im); if (owner != nullptr && owner->is_active()) sample.ai = owner->ai_reference(); sample.devices = devices_of(*occupied, *controlling); - sample.main_reservoir = static_cast(controlling->Compressor); + sample.main_reservoir = static_cast(controlling->air.mainReservoirPressure); sample.voltage = static_cast(controlling->EngineVoltage); sample.engine_rpm = static_cast(std::abs(controlling->enrot) * 60.0); // the lights at the ends of the train: of the vehicles at its ends, at their ends turned away from the rest @@ -478,7 +478,7 @@ void blackbox_recorder::write_cab() { // the const one: with no driver the first channel sample.radio_channel = static_cast(std::clamp(std::as_const(*train).RadioChannel(), 0, 255)); sample.driver_valve = occupied->Handle != nullptr ? static_cast(occupied->Handle->GetCP()) : 0.0f; - sample.feed_pipe = static_cast(occupied->ScndPipePress); + sample.feed_pipe = static_cast(occupied->mainPipe.pressure); sample.oil_pressure = controlling->OilPump.pressure; sample.water_temperature = controlling->diesel.heat.Twy; sample.oil_temperature = controlling->diesel.heat.To; diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp index 82ae73792..2ff95b8f3 100644 --- a/simulation/simulation.cpp +++ b/simulation/simulation.cpp @@ -467,7 +467,7 @@ void state_manager::process_commands() { if (commanddata.command == user_command::fillcompressor) { TDynamicObject *vehicle = simulation::Vehicles.find(commanddata.payload); - vehicle->physics->CompressedVolume = 8.0f * vehicle->physics->VeselVolume; + vehicle->physics->air.compressedVolume = 8.0f * vehicle->physics->air.mainReservoirVolume; } if (commanddata.command == user_command::dynamicmove) { diff --git a/tests/unit/COVERAGE.md b/tests/unit/COVERAGE.md index 9757288a3..2d9774239 100644 --- a/tests/unit/COVERAGE.md +++ b/tests/unit/COVERAGE.md @@ -165,7 +165,7 @@ The tests record the behaviour as it is. The following points may deserve a look - **`Random(10) - Random(10)` (`physics.cpp`, the noise of the control pipe pressure `CntrlPipePress`):** the order the two calls were evaluated in isn't specified. MSVC Release, MSVC Debug and GCC gave different traces, a control pipe pressure mirrored around 5 bar, which failed 32 tests on the Linux CI. Fixed: the draws are sequenced in the order of MSVC Release, which the golden traces were recorded with. - **`TCommand::Location` isn't initialised** in a new vehicle. The game always sets it through `PutCommand()`, but a test calling `RunCommand()` directly got different results run to run. -- **`CompressorList` is `int[4][9]`** (`vehicle.h`), though its factors are fractions: 0.9 is read as 0. No game vehicle has the list yet. +- **The `CompressorList` table (`air.compressor.list`) holds `int`s** (`physics/components/airsupply.h`), though its factors are fractions: 0.9 is read as 0. No game vehicle has the list yet. - **A train whose pipe leaks under 2.75 bar before its start-up can't be released:** - Where this happens: an FV4a handle and an LSt valve, for example 4 minutes standing with wagons, waiting for a hot engine. - The cause: the pipe gets cut off the main reservoir (`lock_old` in `UpdatePipePressure`). The AI presses its unlock button only for the lock set by `LPOn` and `LPOff` (`control_main_pipe`). diff --git a/tests/unit/consist.cpp b/tests/unit/consist.cpp index 0d6dbb5bf..04338f4c4 100644 --- a/tests/unit/consist.cpp +++ b/tests/unit/consist.cpp @@ -84,7 +84,7 @@ void consist::step(track const &Track, double Dt) { auto pipe{0.0}; auto length{0.0}; for (auto const &vehicle : m_vehicles) { - pipe += vehicle->physics().PipePress * vehicle->physics().Dim.L; + pipe += vehicle->physics().brakePipe.pressure * vehicle->physics().Dim.L; length += vehicle->physics().Dim.L; } pipe /= length; diff --git a/tests/unit/drive.cpp b/tests/unit/drive.cpp index 3f1227269..2470d561a 100644 --- a/tests/unit/drive.cpp +++ b/tests/unit/drive.cpp @@ -86,7 +86,7 @@ void release_brakes(physics::Vehicle &Cab) { bool is_ready(driven const &Driven) { auto const &physics{Driven.controlling}; - auto const air{physics.VeselVolume <= 0.0 || physics.ScndPipePress >= 4.5}; + auto const air{physics.air.mainReservoirVolume <= 0.0 || physics.mainPipe.pressure >= 4.5}; // the converter feeds the 110 V circuits (the electrodynamic brake's control among them); the AI switches // it on once the line breaker is closed, so a train already charged with air isn't ready before it runs auto const converter{physics.ConverterStart != start_t::manual || physics.ConverterFlag}; @@ -114,7 +114,7 @@ void raise_pantographs(driven const &Driven) { } pantographs.PantCompFlag = true; } - else if (false == pantographs.bPantKurek3 || pantographs.PantPress <= pantographs.ScndPipePress) { + else if (false == pantographs.bPantKurek3 || pantographs.PantPress <= pantographs.mainPipe.pressure) { pantographs.PantCompFlag = false; } Driven.cab.OperatePantographsValve(operation_t::enable); @@ -210,7 +210,7 @@ void drive_cycle(driven Driven, track const &Track, trace &Trace) { auto &cab{Driven.cab}; auto &controlling{Driven.controlling}; if (false == start_up(Driven, Track, 300.0, &Trace)) { - MESSAGE("didn't get ready: Mains " << controlling.Mains << ", main reservoir " << controlling.ScndPipePress); + MESSAGE("didn't get ready: Mains " << controlling.Mains << ", main reservoir " << controlling.mainPipe.pressure); } Trace.mark("release brakes"); release_brakes(cab); diff --git a/tests/unit/figures.cpp b/tests/unit/figures.cpp index 949a53061..4472bfa86 100644 --- a/tests/unit/figures.cpp +++ b/tests/unit/figures.cpp @@ -62,7 +62,7 @@ constexpr double pipe_back{4.9}; void figures::sample(double Time, physics::Vehicle const &Vehicle) { auto &part{m_parts.back()}; auto const speed{Vehicle.V * 3.6}; - auto const pipe{Vehicle.PipePress}; + auto const pipe{Vehicle.brakePipe.pressure}; if (false == part.sampled) { part.sampled = true; // from the last step of the part before, so the parts add up to the run diff --git a/tests/unit/golden.cpp b/tests/unit/golden.cpp index f66631b8a..26e6ea254 100644 --- a/tests/unit/golden.cpp +++ b/tests/unit/golden.cpp @@ -75,7 +75,7 @@ std::vector traction() { std::vector brakes() { return { {"BrakeCtrlPos", [](auto const &M) { return M.BrakeCtrlPos; }}, - {"PipePress", [](auto const &M) { return M.PipePress; }}, + {"PipePress", [](auto const &M) { return M.brakePipe.pressure; }}, {"BrakePress", [](auto const &M) { return M.BrakePress; }}, {"LocBrakePress", [](auto const &M) { return M.LocBrakePress; }}, {"BRP", [](auto const &M) { return M.Hamulec->GetBRP(); }}, @@ -86,9 +86,9 @@ std::vector brakes() { std::vector air() { return { - {"Compressor", [](auto const &M) { return M.Compressor; }}, - {"CompressorFlag", [](auto const &M) { return M.CompressorFlag ? 1.0 : 0.0; }}, - {"ScndPipePress", [](auto const &M) { return M.ScndPipePress; }}, + {"Compressor", [](auto const &M) { return M.air.mainReservoirPressure; }}, + {"CompressorFlag", [](auto const &M) { return M.air.compressor.running ? 1.0 : 0.0; }}, + {"ScndPipePress", [](auto const &M) { return M.mainPipe.pressure; }}, }; } @@ -162,7 +162,7 @@ std::vector parameters() { {"CntrlPipePress", [](auto const &M) { return M.CntrlPipePress; }}, {"BrakeVolume", [](auto const &M) { return M.BrakeVolume; }}, {"BrakeVVolume", [](auto const &M) { return M.BrakeVVolume; }}, - {"VeselVolume", [](auto const &M) { return M.VeselVolume; }}, + {"VeselVolume", [](auto const &M) { return M.air.mainReservoirVolume; }}, {"BrakeCylNo", [](auto const &M) { return M.BrakeCylNo; }}, {"BrakeCylRadius", [](auto const &M) { return M.BrakeCylRadius; }}, {"BrakeCylDist", [](auto const &M) { return M.BrakeCylDist; }}, @@ -172,11 +172,11 @@ std::vector parameters() { {"RapidMult", [](auto const &M) { return M.RapidMult; }}, {"RapidVel", [](auto const &M) { return M.RapidVel; }}, {"BrakeValveSize", [](auto const &M) { return M.BrakeValveSize; }}, - {"MinCompressor", [](auto const &M) { return M.MinCompressor; }}, - {"MaxCompressor", [](auto const &M) { return M.MaxCompressor; }}, - {"CompressorSpeed", [](auto const &M) { return M.CompressorSpeed; }}, + {"MinCompressor", [](auto const &M) { return M.air.compressor.minPressure; }}, + {"MaxCompressor", [](auto const &M) { return M.air.compressor.maxPressure; }}, + {"CompressorSpeed", [](auto const &M) { return M.air.compressor.speed; }}, {"EmergencyValveOn", [](auto const &M) { return M.EmergencyValveOn; }}, - {"AirLeakRate", [](auto const &M) { return M.AirLeakRate; }}, + {"AirLeakRate", [](auto const &M) { return M.air.leakRate; }}, {"BrakeCtrlPosNo", [](auto const &M) { return M.BrakeCtrlPosNo; }}, {"MainCtrlPosNo", [](auto const &M) { return M.MainCtrlPosNo; }}, {"ScndCtrlPosNo", [](auto const &M) { return M.ScndCtrlPosNo; }}, diff --git a/tests/unit/invariants.cpp b/tests/unit/invariants.cpp index d2e938d94..bbaeefce4 100644 --- a/tests/unit/invariants.cpp +++ b/tests/unit/invariants.cpp @@ -42,13 +42,13 @@ std::vector const &invariants() { {"every value a number", [](auto const &M, double, auto const *) { std::initializer_list const values{M.V, M.AccS, M.Ft, M.Fb, M.Im, M.Itot, M.EngineVoltage, - M.enrot, M.PipePress, M.BrakePress, M.LocBrakePress, M.ScndPipePress, M.Compressor, M.BatteryVoltage}; + M.enrot, M.brakePipe.pressure, M.BrakePress, M.LocBrakePress, M.mainPipe.pressure, M.air.mainReservoirPressure, M.BatteryVoltage}; return std::ranges::all_of(values, [](double const Value) { return std::isfinite(Value); }); }, [](auto const &M) { return values({{"V", M.V}, {"AccS", M.AccS}, {"Ft", M.Ft}, {"Fb", M.Fb}, {"Im", M.Im}, {"Itot", M.Itot}, {"EngineVoltage", M.EngineVoltage}, - {"enrot", M.enrot}, {"PipePress", M.PipePress}, {"BrakePress", M.BrakePress}, {"LocBrakePress", M.LocBrakePress}, - {"ScndPipePress", M.ScndPipePress}, {"Compressor", M.Compressor}, {"BatteryVoltage", M.BatteryVoltage}}); + {"enrot", M.enrot}, {"PipePress", M.brakePipe.pressure}, {"BrakePress", M.BrakePress}, {"LocBrakePress", M.LocBrakePress}, + {"ScndPipePress", M.mainPipe.pressure}, {"Compressor", M.air.mainReservoirPressure}, {"BatteryVoltage", M.BatteryVoltage}}); }}, {"brake cylinders between empty and the vehicle's highest pressure", [](auto const &M, double, auto const *) { @@ -61,14 +61,14 @@ std::vector const &invariants() { [](auto const &M, double, auto const *) { // all the air comes from the main reservoirs, which the game sets up to 10 bar, some (the Impuls) to 12; // the driver's valve in its filling position joins the brake pipe to them - auto const highest{1.01 * std::max(10.0, M.MaxCompressor) + pressure_margin}; - std::initializer_list const pressures{M.PipePress, M.ScndPipePress, M.Compressor}; + auto const highest{1.01 * std::max(10.0, M.air.compressor.maxPressure) + pressure_margin}; + std::initializer_list const pressures{M.brakePipe.pressure, M.mainPipe.pressure, M.air.mainReservoirPressure}; return std::ranges::all_of(pressures, [highest](double const Press) { return Press >= -pressure_margin && Press <= highest; }); }, - [](auto const &M) { return values({{"PipePress", M.PipePress}, {"ScndPipePress", M.ScndPipePress}, {"Compressor", M.Compressor}}); }}, + [](auto const &M) { return values({{"PipePress", M.brakePipe.pressure}, {"ScndPipePress", M.mainPipe.pressure}, {"Compressor", M.air.mainReservoirPressure}}); }}, {"main reservoir no higher than the compressor's governor", - [](auto const &M, double, auto const *) { return M.MaxCompressor <= 0.0 || M.Compressor <= 1.01 * M.MaxCompressor + pressure_margin; }, - [](auto const &M) { return values({{"Compressor", M.Compressor}, {"MaxCompressor", M.MaxCompressor}}); }}, + [](auto const &M, double, auto const *) { return M.air.compressor.maxPressure <= 0.0 || M.air.mainReservoirPressure <= 1.01 * M.air.compressor.maxPressure + pressure_margin; }, + [](auto const &M) { return values({{"Compressor", M.air.mainReservoirPressure}, {"MaxCompressor", M.air.compressor.maxPressure}}); }}, {"no motor current with the line breaker open", [](auto const &M, double, auto const *) { return M.Mains || false == electric(M) || std::abs(M.Im) < 1.0; }, [](auto const &M) { return values({{"Mains", M.Mains}, {"Im", M.Im}, {"Itot", M.Itot}}); }}, diff --git a/tests/unit/test_brake_handles.cpp b/tests/unit/test_brake_handles.cpp index f86942e4f..1cceda3c0 100644 --- a/tests/unit/test_brake_handles.cpp +++ b/tests/unit/test_brake_handles.cpp @@ -35,7 +35,7 @@ void hold(vehicle &Vehicle, test::trace &Trace, std::string const &Event, double // every position of the driver's handle, recorded in the trace void every_position(vehicle &Vehicle, test::trace &Trace) { - Vehicle.hold_main_reservoir(std::max(Vehicle->MaxCompressor, 8.0)); + Vehicle.hold_main_reservoir(std::max(Vehicle->air.compressor.maxPressure, 8.0)); REQUIRE(Vehicle->Handle != nullptr); auto &handle{*Vehicle->Handle}; Vehicle.record(Trace); @@ -102,7 +102,7 @@ TEST_CASE("brake handles: the local brake handle of every real vehicle") { if (false == has_handle(real)) { continue; } - real.hold_main_reservoir(std::max(real->MaxCompressor, 8.0)); + real.hold_main_reservoir(std::max(real->air.compressor.maxPressure, 8.0)); test::trace trace{"local brake/" + path, handle_channels(), 100}; real.record(trace); REQUIRE(real->Handle != nullptr); @@ -133,22 +133,22 @@ TEST_CASE("brake handles: the overload and the high pressure buttons of the MHZ vehicle real{definition, 0.0, "test", 1}; real->BatterySwitch(true); real->CabActivisation(); - real.hold_main_reservoir(std::max(real->MaxCompressor, 8.0)); + real.hold_main_reservoir(std::max(real->air.compressor.maxPressure, 8.0)); test::trace trace{"brake handles/buttons/" + name, handle_channels(), 100}; real.record(trace); REQUIRE(real->Handle != nullptr); auto &handle{*real->Handle}; driven_at(real, trace, "running", handle.GetPos(bh_RP), 60.0); - auto const running{real->PipePress}; + auto const running{real->brakePipe.pressure}; handle.SetUniversalFlag(TUniversalBrake::ub_Overload); driven_at(real, trace, "overload button", handle.GetPos(bh_RP), 30.0); handle.SetUniversalFlag(0); - auto const overloaded{real->PipePress}; + auto const overloaded{real->brakePipe.pressure}; driven_at(real, trace, "overload decaying", handle.GetPos(bh_RP), 240.0); - auto const decayed{real->PipePress}; + auto const decayed{real->brakePipe.pressure}; handle.SetUniversalFlag(TUniversalBrake::ub_HighPressure); driven_at(real, trace, "high pressure button, filling stroke", handle.GetPos(bh_FS), 10.0); - auto const filled{real->PipePress}; + auto const filled{real->brakePipe.pressure}; handle.SetUniversalFlag(0); driven_at(real, trace, "running", handle.GetPos(bh_RP), 120.0); CHECK(running == doctest::Approx(5.0).epsilon(0.01)); @@ -283,10 +283,10 @@ std::vector st113_run() { vehicle real{definition::fiz("en57_v1/6bai")}; REQUIRE(real->BrakeHandle == TBrakeHandle::St113); REQUIRE(real->Handle != nullptr); - real.hold_main_reservoir(std::max(real->MaxCompressor, 8.0)); + real.hold_main_reservoir(std::max(real->air.compressor.maxPressure, 8.0)); auto &handle{*real->Handle}; std::vector samples; - auto const sample{[&] { samples.push_back({handle.GetCP(), real->PipePress, real->BrakePress, handle.GetEP()}); }}; + auto const sample{[&] { samples.push_back({handle.GetCP(), real->brakePipe.pressure, real->BrakePress, handle.GetEP()}); }}; auto const hold{[&](double Position, std::initializer_list Seconds) { real->BrakeLevelSet(Position); for (auto const seconds : Seconds) { diff --git a/tests/unit/test_brake_pipe.cpp b/tests/unit/test_brake_pipe.cpp index e7f9a3dd7..17a6a498f 100644 --- a/tests/unit/test_brake_pipe.cpp +++ b/tests/unit/test_brake_pipe.cpp @@ -42,10 +42,10 @@ void passenger_train(test::consist &Train, int const Cars) { // at Pressure [bar], the physics stepping by Dt double application_time(test::consist &Train, double const Pressure, double const Dt) { auto &last{Train[Train.size() - 1]}; - auto const start{last->PipePress}; + auto const start{last->brakePipe.pressure}; Train[0].hold_brake_pipe(Pressure); auto time{0.0}; - while (last->PipePress > start - 0.5 && time < 60.0) { + while (last->brakePipe.pressure > start - 0.5 && time < 60.0) { Train.step({}, Dt); time += Dt; } @@ -72,8 +72,8 @@ TEST_CASE("brake pipe: the distributors of a standing freight train see the pres CAPTURE(i); auto &wagon{train[i].physics()}; // the distributor's valve chamber follows the pressure the distributor works with: the pipe's own - CHECK(std::abs(wagon.Hamulec->GetVRP() - wagon.PipePress) < 0.005); - CHECK(wagon.PipePress > 4.9); + CHECK(std::abs(wagon.Hamulec->GetVRP() - wagon.brakePipe.pressure) < 0.005); + CHECK(wagon.brakePipe.pressure > 4.9); // released, as the AI wants every vehicle before it starts (TController::CheckVehicles()) CHECK((wagon.Hamulec->GetBrakeStatus() & (b_on | b_hld)) == 0); CHECK(wagon.BrakePress < 0.1); @@ -106,7 +106,7 @@ TEST_CASE("brake pipe: a passenger train, whose exchange was stable in one step, for (std::size_t i = 1; i < train.size(); ++i) { CAPTURE(i); auto &car{train[i].physics()}; - CHECK(std::abs(car.Hamulec->GetVRP() - car.PipePress) < 0.005); + CHECK(std::abs(car.Hamulec->GetVRP() - car.brakePipe.pressure) < 0.005); CHECK((car.Hamulec->GetBrakeStatus() & (b_on | b_hld)) == 0); CHECK(car.BrakePress < 0.1); } diff --git a/tests/unit/test_brakes.cpp b/tests/unit/test_brakes.cpp index cb83e2f0e..51e50cd19 100644 --- a/tests/unit/test_brakes.cpp +++ b/tests/unit/test_brakes.cpp @@ -110,18 +110,18 @@ TEST_CASE("brakes: a dead EN57 hauled with the brake hose alone charges from the auto &car{train[i].physics()}; REQUIRE(car.BrakeValve == TBrakeValve::EP2); car.Hamulec->ForceEmptiness(); - car.Pipe->CreatePress(0.0); - car.Pipe->Act(); - car.Pipe2->CreatePress(0.0); - car.Pipe2->Act(); - car.CompressedVolume = 0.0; + car.brakePipe.reservoir->CreatePress(0.0); + car.brakePipe.reservoir->Act(); + car.mainPipe.reservoir->CreatePress(0.0); + car.mainPipe.reservoir->Act(); + car.air.compressedVolume = 0.0; } locomotive.hold_brake_pipe(5.0); train.run(900.0); for (std::size_t i = 1; i < train.size(); ++i) { CAPTURE(i); auto &car{train[i].physics()}; - REQUIRE(car.ScndPipePress < 0.1); // no main reservoir pipe + REQUIRE(car.mainPipe.pressure < 0.1); // no main reservoir pipe CHECK(car.Hamulec->GetBRP() > 4.8); CHECK(car.Hamulec->GetCRP() > 4.8); CHECK(car.BrakePress < 0.1); diff --git a/tests/unit/test_cab.cpp b/tests/unit/test_cab.cpp index c42d9d9f4..4aceb5836 100644 --- a/tests/unit/test_cab.cpp +++ b/tests/unit/test_cab.cpp @@ -223,7 +223,7 @@ TEST_CASE("cab: the lamps and the buzzer of the security system left unattended" CHECK(blinked); CHECK(beeped); CHECK_FALSE(security.is_cabsignal_beeping()); - CHECK(eu07.PipePress < 1.0); + CHECK(eu07.brakePipe.pressure < 1.0); CHECK(security.radiostop_available()); scenario.check(); } @@ -269,7 +269,7 @@ TEST_CASE("cab: the SM42's vigilance device switched off in the shunt mode, wher } CHECK(sm42.Vel > 1.0); CHECK_FALSE(blinked); - CHECK(sm42.PipePress > 3.5); + CHECK(sm42.brakePipe.pressure > 3.5); scenario.act("shunt mode off"); scenario.notch_back(0); REQUIRE(sm42.CurrentSwitch(false)); @@ -293,7 +293,7 @@ TEST_CASE("cab: the vigilance device of the SM42 kept in the shunt mode, by defa scenario.act("unattended in shunt mode"); CHECK(unattended(scenario, 120)); CHECK(sm42.ShuntMode); - CHECK(sm42.PipePress < 1.0); + CHECK(sm42.brakePipe.pressure < 1.0); scenario.check(); } @@ -324,7 +324,7 @@ TEST_CASE("cab: the SM42's vigilance alarm on, not cleared by switching into the CHECK(security.is_vigilance_blinking()); CHECK(security.is_beeping()); CHECK(security.is_braking()); - CHECK(sm42.PipePress < 1.0); + CHECK(sm42.brakePipe.pressure < 1.0); scenario.act("acknowledged"); sm42.SecuritySystemReset(); scenario.train().run(1.0, scenario.line()); diff --git a/tests/unit/test_camshaft.cpp b/tests/unit/test_camshaft.cpp index 959c81d37..31f255f69 100644 --- a/tests/unit/test_camshaft.cpp +++ b/tests/unit/test_camshaft.cpp @@ -71,7 +71,7 @@ void running(physics::Vehicle &Locomotive, int const Direction, int const Positi Locomotive.CabActive = 1; Locomotive.DirActive = Direction; Locomotive.Mains = true; - Locomotive.PipePress = 5.0; // bar, the pressure switch lets the line contactors close + Locomotive.brakePipe.pressure = 5.0; // bar, the pressure switch lets the line contactors close Locomotive.BrakePress = 0.0; Locomotive.StLinFlag = true; Locomotive.MainCtrlActualPos = Position; diff --git a/tests/unit/test_commands.cpp b/tests/unit/test_commands.cpp index a61ffd2b2..5f3718959 100644 --- a/tests/unit/test_commands.cpp +++ b/tests/unit/test_commands.cpp @@ -55,8 +55,8 @@ std::vector state() { {"AutoRelayFlag", [](auto const &M) { return flag(M.AutoRelayFlag); }}, {"ConverterAllow", [](auto const &M) { return flag(M.ConverterAllow); }}, {"Battery", [](auto const &M) { return flag(M.Battery); }}, - {"CompressorAllow", [](auto const &M) { return flag(M.CompressorAllow); }}, - {"CompressorListPos", [](auto const &M) { return M.CompressorListPos; }}, + {"CompressorAllow", [](auto const &M) { return flag(M.air.compressor.allow); }}, + {"CompressorListPos", [](auto const &M) { return M.air.compressor.listPosition; }}, {"DoorLock", [](auto const &M) { return flag(M.Doors.lock_enabled); }}, {"DoorStep", [](auto const &M) { return flag(M.Doors.step_enabled); }}, {"DoorRemoteOnly", [](auto const &M) { return flag(M.Doors.remote_only); }}, @@ -413,8 +413,8 @@ TEST_CASE("commands: every switch of the cab, worked on a pair standing under th {"PantPress", [](auto const &M) { return M.PantPress; }}, {"GroundRelay", [](auto const &M) { return flag(M.GroundRelay); }}, {"ConverterFlag", [](auto const &M) { return flag(M.ConverterFlag); }}, - {"CompressorFlag", [](auto const &M) { return flag(M.CompressorFlag); }}, - {"Compressor", [](auto const &M) { return M.Compressor; }}, + {"CompressorFlag", [](auto const &M) { return flag(M.air.compressor.running); }}, + {"Compressor", [](auto const &M) { return M.air.mainReservoirPressure; }}, {"MainCtrlActualPos", [](auto const &M) { return M.MainCtrlActualPos; }}, {"Itot", [](auto const &M) { return M.Itot; }}, {"FuseFlag", [](auto const &M) { return flag(M.FuseFlag); }}, diff --git a/tests/unit/test_compressor.cpp b/tests/unit/test_compressor.cpp index 4f55ce0b8..033bd4775 100644 --- a/tests/unit/test_compressor.cpp +++ b/tests/unit/test_compressor.cpp @@ -26,7 +26,7 @@ vehicle compressor_vehicle(double const Delay, std::string const &Power = "Main" definition.set("Brake", "CompressorStartDelay", Delay); } vehicle vehicle{definition}; - vehicle->CompressedVolume = 0.0; + vehicle->air.compressedVolume = 0.0; vehicle->LastSwitchingTime = 10.0; // nothing was switched lately return vehicle; } @@ -45,11 +45,11 @@ void run_compressor(vehicle &Vehicle, double const Seconds) { TEST_CASE("compressor: without a start delay the compressor starts with its power") { auto vehicle{compressor_vehicle(0.0)}; run_compressor(vehicle, 1.0); - REQUIRE_FALSE(vehicle->CompressorFlag); // no power, no compressor + REQUIRE_FALSE(vehicle->air.compressor.running); // no power, no compressor vehicle->Mains = true; run_compressor(vehicle, step); - CHECK(vehicle->CompressorFlag); + CHECK(vehicle->air.compressor.running); } TEST_CASE("compressor: the compressor starts the delay after getting its power") { @@ -57,94 +57,94 @@ TEST_CASE("compressor: the compressor starts the delay after getting its power") vehicle->Mains = true; run_compressor(vehicle, 4.9); - CHECK_FALSE(vehicle->CompressorFlag); - CHECK(vehicle->Compressor == doctest::Approx(0.0)); + CHECK_FALSE(vehicle->air.compressor.running); + CHECK(vehicle->air.mainReservoirPressure == doctest::Approx(0.0)); run_compressor(vehicle, 0.2); - CHECK(vehicle->CompressorFlag); + CHECK(vehicle->air.compressor.running); run_compressor(vehicle, 10.0); - CHECK(vehicle->Compressor > 0.0); // and fills the reservoir + CHECK(vehicle->air.mainReservoirPressure > 0.0); // and fills the reservoir } TEST_CASE("compressor: the delay starts over once the power is gone") { auto vehicle{compressor_vehicle(5.0)}; vehicle->Mains = true; run_compressor(vehicle, 10.0); - REQUIRE(vehicle->CompressorFlag); + REQUIRE(vehicle->air.compressor.running); vehicle->Mains = false; // the engine stopped run_compressor(vehicle, 1.0); - CHECK_FALSE(vehicle->CompressorFlag); + CHECK_FALSE(vehicle->air.compressor.running); vehicle->Mains = true; // and started again run_compressor(vehicle, 4.9); - CHECK_FALSE(vehicle->CompressorFlag); + CHECK_FALSE(vehicle->air.compressor.running); run_compressor(vehicle, 0.2); - CHECK(vehicle->CompressorFlag); + CHECK(vehicle->air.compressor.running); } TEST_CASE("compressor: a compressor fed from the low voltage waits from the low voltage coming on") { auto vehicle{compressor_vehicle(5.0, "")}; // the default supply: the converter, the 110 V vehicle->Mains = true; // which alone doesn't feed it run_compressor(vehicle, 10.0); - REQUIRE_FALSE(vehicle->CompressorFlag); + REQUIRE_FALSE(vehicle->air.compressor.running); vehicle->Power110vIsAvailable = true; run_compressor(vehicle, 4.9); - CHECK_FALSE(vehicle->CompressorFlag); + CHECK_FALSE(vehicle->air.compressor.running); run_compressor(vehicle, 0.2); - CHECK(vehicle->CompressorFlag); + CHECK(vehicle->air.compressor.running); } TEST_CASE("compressor: the pressure switch stops the compressor above the cut-out pressure") { auto vehicle{compressor_vehicle(0.0)}; vehicle->Mains = true; - vehicle->CompressedVolume = 8.5; // over MaxCP, in the reservoir of 1 m3 + vehicle->air.compressedVolume = 8.5; // over MaxCP, in the reservoir of 1 m3 run_compressor(vehicle, step); - CHECK(vehicle->CompressorGovernorLock); - CHECK_FALSE(vehicle->CompressorFlag); + CHECK(vehicle->air.compressor.governorLock); + CHECK_FALSE(vehicle->air.compressor.running); } TEST_CASE("compressor: without a pressure switch the air over the cut-out pressure is vented") { auto vehicle{compressor_vehicle(0.0, "Main", 8.0)}; // MinCP the same as MaxCP: no pressure switch vehicle->Mains = true; - vehicle->CompressedVolume = 8.5; + vehicle->air.compressedVolume = 8.5; run_compressor(vehicle, step); - REQUIRE(vehicle->CompressorFlag); // nothing stops it - CHECK(vehicle->CompressedVolume < 8.5 * 0.81); // a fifth of the air let out + REQUIRE(vehicle->air.compressor.running); // nothing stops it + CHECK(vehicle->air.compressedVolume < 8.5 * 0.81); // a fifth of the air let out } TEST_CASE("compressor: an engine stopped before the delay passed counts the whole delay again") { auto vehicle{compressor_vehicle(30.0)}; vehicle->Mains = true; // engine started run_compressor(vehicle, 20.0); - REQUIRE_FALSE(vehicle->CompressorFlag); + REQUIRE_FALSE(vehicle->air.compressor.running); vehicle->Mains = false; // engine stopped, 10 s short of the delay run_compressor(vehicle, 1.0); vehicle->Mains = true; run_compressor(vehicle, 15.0); // 36 s since the first start, but only 15 s since this one - CHECK_FALSE(vehicle->CompressorFlag); + CHECK_FALSE(vehicle->air.compressor.running); run_compressor(vehicle, 15.1); - CHECK(vehicle->CompressorFlag); + CHECK(vehicle->air.compressor.running); } TEST_CASE("compressor: the start delay holds back a compressor switched on by hand too") { auto vehicle{compressor_vehicle(30.0)}; - vehicle->CompressorStart = start_t::manual; - vehicle->CompressorAllow = true; // switch in the cabinet on before the engine start + vehicle->air.compressor.start = start_t::manual; + vehicle->air.compressor.allow = true; // switch in the cabinet on before the engine start vehicle->Mains = true; run_compressor(vehicle, 29.9); - CHECK_FALSE(vehicle->CompressorFlag); + CHECK_FALSE(vehicle->air.compressor.running); run_compressor(vehicle, 0.2); - CHECK(vehicle->CompressorFlag); + CHECK(vehicle->air.compressor.running); } TEST_CASE("compressor: the start delay is read from the brake section") { auto const delay{[](std::string const &Section) { - return vehicle{definition::load("wagon").set(Section, "CompressorStartDelay", 30)}->CompressorStartDelay; + return vehicle{definition::load("wagon").set(Section, "CompressorStartDelay", 30)}->air.compressor.startDelay; }}; CHECK(delay("Brake") == doctest::Approx(30.0)); CHECK(delay("Cntrl") == doctest::Approx(0.0)); // the key isn't taken from the control section @@ -174,7 +174,7 @@ definition generator_vehicle(double const ConverterDelay, double const Compresso TEST_CASE("compressor: fed from the converter it waits for the converter start delay") { vehicle loco{generator_vehicle(30.0, 0.0)}; - REQUIRE(loco->CompressorPower == 2); + REQUIRE(loco->air.compressor.supply == physics::CompressorSupply::converter); REQUIRE(loco->ConverterStartDelay == doctest::Approx(30.0)); loco.run(1.0); // engine off @@ -183,23 +183,23 @@ TEST_CASE("compressor: fed from the converter it waits for the converter start d loco->Mains = true; // engine started loco.run(25.0); CHECK_FALSE(loco->Power110vIsAvailable); - CHECK_FALSE(loco->CompressorFlag); + CHECK_FALSE(loco->air.compressor.running); loco.run(10.0); CHECK(loco->Power110vIsAvailable); - CHECK(loco->CompressorFlag); + CHECK(loco->air.compressor.running); } TEST_CASE("compressor: fed from the converter the start delay counts from the converter voltage") { vehicle loco{generator_vehicle(20.0, 10.0)}; - REQUIRE(loco->CompressorStartDelay == doctest::Approx(10.0)); + REQUIRE(loco->air.compressor.startDelay == doctest::Approx(10.0)); loco.run(1.0); // engine off loco->Mains = true; // engine started loco.run(25.0); REQUIRE(loco->Power110vIsAvailable); // the converter is up - CHECK_FALSE(loco->CompressorFlag); // but the compressor waits for its own delay as well + CHECK_FALSE(loco->air.compressor.running); // but the compressor waits for its own delay as well loco.run(10.0); - CHECK(loco->CompressorFlag); + CHECK(loco->air.compressor.running); } diff --git a/tests/unit/test_controls.cpp b/tests/unit/test_controls.cpp index c2f7bb9d5..6549146c0 100644 --- a/tests/unit/test_controls.cpp +++ b/tests/unit/test_controls.cpp @@ -301,16 +301,16 @@ TEST_CASE("controls: emergency stops by the alarm chain and the radio-stop") { scenario.wait(40.0); // the pipe emptied, the whole train braked to a stop CHECK(stopped(scenario)); - CHECK(cab.PipePress < 0.5); + CHECK(cab.brakePipe.pressure < 0.5); CHECK(scenario.vehicle(2).BrakePress > 1.0); scenario.act("alarm chain reset"); scenario.vehicle(1).AlarmChainSwitch(false); scenario.wait(10.0); // the FV4a handle stays cut off the emptied pipe of an LSt locomotive (lock_old in UpdatePipePressure) // until the releaser is held - CHECK(cab.PipePress < 0.5); + CHECK(cab.brakePipe.pressure < 0.5); recharge(scenario); - CHECK(cab.PipePress > 4.5); + CHECK(cab.brakePipe.pressure > 4.5); scenario.get_going(); notch_up(scenario, 20, 1.0); scenario.wait(20.0); @@ -320,12 +320,12 @@ TEST_CASE("controls: emergency stops by the alarm chain and the radio-stop") { cab.RadiostopSwitch(true); scenario.wait(40.0); CHECK(stopped(scenario)); - CHECK(cab.PipePress < 0.5); + CHECK(cab.brakePipe.pressure < 0.5); scenario.act("radio-stop reset"); cab.RadiostopSwitch(false); scenario.wait(10.0); recharge(scenario); - CHECK(cab.PipePress > 4.5); + CHECK(cab.brakePipe.pressure > 4.5); scenario.check(); } @@ -353,7 +353,7 @@ TEST_CASE("controls: releasers and the universal brake buttons") { CHECK(cab.BrakePress < 0.5); CHECK(coach.BrakePress < coachbraked - 1.0); CHECK(wagon.BrakePress < wagonbraked - 0.5); - CHECK(cab.PipePress < 4.0); // the pipe stays where the service application left it + CHECK(cab.brakePipe.pressure < 4.0); // the pipe stays where the service application left it wagonbraked = wagon.BrakePress; scenario.act("releaser of the wagon"); wagon.BrakeReleaser(1); @@ -370,7 +370,7 @@ TEST_CASE("controls: releasers and the universal brake buttons") { scenario.act("running"); cab.BrakeLevelSet(cab.Handle->GetPos(bh_RP)); scenario.wait(60.0); - CHECK(cab.PipePress > 4.8); + CHECK(cab.brakePipe.pressure > 4.8); CHECK(released(scenario)); scenario.check(); } @@ -403,7 +403,7 @@ TEST_CASE("controls: the ep brake of electric units") { if (i == 3) { // the ep brake works the cylinders of every car by wire, the pipe stays charged (by the first // application the EW58's pipe is still charging after the start-up) - CHECK(cab.PipePress > 4.8); + CHECK(cab.brakePipe.pressure > 4.8); CHECK(cab.BrakePress > 1.0); CHECK(last.BrakePress > 1.0); } diff --git a/tests/unit/test_crew.cpp b/tests/unit/test_crew.cpp index 3c1b17664..5caaf9fd0 100644 --- a/tests/unit/test_crew.cpp +++ b/tests/unit/test_crew.cpp @@ -208,7 +208,7 @@ TEST_CASE("crew: a locomotive under power left by its driver stops and stays bra auto const stoppedafter{seconds_to_stop(train, 120.0)}; CAPTURE(stoppedafter); CHECK(std::abs(train[0].speed()) <= 0.01); - CHECK(eu07.PipePress < 1.0); // vented by the emergency position + CHECK(eu07.brakePipe.pressure < 1.0); // vented by the emergency position CHECK(eu07.BrakePress > 2.0); // it keeps standing, also on a slope, with the engine as the driver left it train.run(120.0, track{0.15, 0.02, test::catenary_3kv}); @@ -252,7 +252,7 @@ TEST_CASE("crew: a train left by its driver is braked through the whole of it") CAPTURE(stoppedafter); CHECK(std::abs(train[0].speed()) <= 0.01); CHECK(std::abs(train[2].speed()) <= 0.01); - CHECK(last.PipePress < 1.0); + CHECK(last.brakePipe.pressure < 1.0); CHECK(last.BrakePress > 1.0); } diff --git a/tests/unit/test_definition.cpp b/tests/unit/test_definition.cpp index 4178da19d..2c62ce241 100644 --- a/tests/unit/test_definition.cpp +++ b/tests/unit/test_definition.cpp @@ -76,32 +76,32 @@ TEST_CASE("definition: a compressor list, whose positions allow the compressor a .set("CompressorList", "Default", 1) .set("CompressorList", "rows", {{2, 2, 1, 1}, {1, 1, 1, 1}, {2, 1, 0.9, 0.9}})}; vehicle real{eu07, 0.0, "test", 1}; - CHECK(real->CompressorListPosNo == 3); - CHECK(real->CompressorList[3][3] == 0); + CHECK(real->air.compressor.listPositions == 3); + CHECK(real->air.compressor.list[3][3] == 0); auto driven{test::driving(real)}; test::track const line{0.15, 0.0, test::catenary_3kv}; REQUIRE(test::start_up(driven, line)); - CHECK(real->CompressorListPos == 1); + CHECK(real->air.compressor.listPosition == 1); test::drive(driven, line, 60.0); - CHECK(real->CompressorAllow); - CHECK(real->Compressor <= real->MaxCompressor + 0.05); - CHECK(real->Compressor >= real->MinCompressor - 0.05); + CHECK(real->air.compressor.allow); + CHECK(real->air.mainReservoirPressure <= real->air.compressor.maxPressure + 0.05); + CHECK(real->air.mainReservoirPressure >= real->air.compressor.minPressure - 0.05); // the second position doesn't let it run CHECK(real->ChangeCompressorPreset(2)); test::drive(driven, line, 2.0); - CHECK_FALSE(real->CompressorAllow); - CHECK_FALSE(real->CompressorFlag); + CHECK_FALSE(real->air.compressor.allow); + CHECK_FALSE(real->air.compressor.running); // the third lets it, under limits of nothing: with no span between them for the governor, the reservoir over // the upper limit gets vented while the compressor runs on CHECK(real->ChangeCompressorPreset(3)); - auto const full{real->Compressor}; + auto const full{real->air.mainReservoirPressure}; test::drive(driven, line, 10.0); - CHECK(real->CompressorAllow); - CHECK(real->CompressorFlag); - CHECK(real->Compressor < full - 1.0); + CHECK(real->air.compressor.allow); + CHECK(real->air.compressor.running); + CHECK(real->air.mainReservoirPressure < full - 1.0); // no further than the last position CHECK_FALSE(real->ChangeCompressorPreset(5)); - CHECK(real->CompressorListPos == 3); + CHECK(real->air.compressor.listPosition == 3); } TEST_CASE("definition: the compressor's limits set apart for the rear cab") { @@ -113,11 +113,11 @@ TEST_CASE("definition: the compressor's limits set apart for the rear cab") { test::track const line{0.15, 0.0, test::catenary_3kv}; REQUIRE(test::start_up(driven, line)); test::drive(driven, line, 120.0); - CHECK(real->CabDependentCompressor); - CHECK(real->MaxCompressor == doctest::Approx(cab > 0 ? 8.7 : 6.0)); - CHECK(real->MinCompressor == doctest::Approx(cab > 0 ? 7.0 : 5.0)); - CHECK(real->Compressor <= real->MaxCompressor + 0.05); - CHECK(real->Compressor >= real->MinCompressor - 0.05); + CHECK(real->air.compressor.cabDependent); + CHECK(real->air.compressor.maxPressure == doctest::Approx(cab > 0 ? 8.7 : 6.0)); + CHECK(real->air.compressor.minPressure == doctest::Approx(cab > 0 ? 7.0 : 5.0)); + CHECK(real->air.mainReservoirPressure <= real->air.compressor.maxPressure + 0.05); + CHECK(real->air.mainReservoirPressure >= real->air.compressor.minPressure - 0.05); } } diff --git a/tests/unit/test_dynamic_brake_diesel.cpp b/tests/unit/test_dynamic_brake_diesel.cpp index 085d77a9d..1d1e317b1 100644 --- a/tests/unit/test_dynamic_brake_diesel.cpp +++ b/tests/unit/test_dynamic_brake_diesel.cpp @@ -227,7 +227,7 @@ TEST_CASE("diesel-electric dynamic brake: blended with the locomotive's air brak scenario.wait(6.0); REQUIRE(locomotive.Vel > 15.0); CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); - CHECK(locomotive.PipePress < 4.6); + CHECK(locomotive.brakePipe.pressure < 4.6); CHECK((locomotive.BrakePress < 0.2) == blending); scenario.check(); } diff --git a/tests/unit/test_elf_controller.cpp b/tests/unit/test_elf_controller.cpp index 49805c30c..47a62d5a8 100644 --- a/tests/unit/test_elf_controller.cpp +++ b/tests/unit/test_elf_controller.cpp @@ -61,7 +61,7 @@ struct elf { } test::release_brakes(cab()); recharge(); - charged = cab().PipePress > 4.5; + charged = cab().brakePipe.pressure > 4.5; } // the pipe charged again after an emergency stop: the Elf locks its emptied pipe off the brake handle (LPOn, // LPOff) until the unlock button (UBB1, the first universal brake button) is held, the handle at running @@ -105,7 +105,7 @@ TEST_CASE("elf controller: without EIMCtrlMainEmergency the positions stay as th CHECK_FALSE(physics.IsMainCtrlEmergencyPos()); unit.wait(10.0); CHECK(physics.eimic == doctest::Approx(-1.0)); - CHECK(physics.PipePress > 4.5); + CHECK(physics.brakePipe.pressure > 4.5); } TEST_CASE("elf controller: EIMCtrlMainEmergency shifts the positions up by the emergency brake one") { @@ -127,14 +127,14 @@ TEST_CASE("elf controller: EIMCtrlMainEmergency shifts the positions up by the e physics.MainCtrlPos = 1; unit.wait(10.0); CHECK(physics.eimic == doctest::Approx(-1.0)); - CHECK(physics.PipePress > 4.5); + CHECK(physics.brakePipe.pressure > 4.5); } SUBCASE("the braking position, formerly 1, ramps the braking up") { physics.MainCtrlPos = 2; unit.wait(1.0); CHECK(physics.eimic < 0.0); CHECK(physics.eimic > -1.0); - CHECK(physics.PipePress > 4.5); + CHECK(physics.brakePipe.pressure > 4.5); } SUBCASE("the emergency brake position brakes fully at once and empties the pipe") { physics.MainCtrlPos = 0; @@ -143,13 +143,13 @@ TEST_CASE("elf controller: EIMCtrlMainEmergency shifts the positions up by the e unit.unit.step(unit.line); CHECK(physics.eimic == doctest::Approx(-1.0)); unit.wait(10.0); - CHECK(physics.PipePress < 0.5); + CHECK(physics.brakePipe.pressure < 0.5); CHECK(physics.BrakePress > 1.0); // out of it the pipe charges again physics.MainCtrlPos = physics.MainCtrlNoPowerPos(); CHECK_FALSE(physics.IsMainCtrlEmergencyPos()); unit.recharge(); - CHECK(physics.PipePress > 4.5); + CHECK(physics.brakePipe.pressure > 4.5); } } @@ -195,8 +195,8 @@ TEST_CASE("elf controller: the emergency brake position vents the pipe only from CHECK(rear.IsMainCtrlEmergencyPos()); CHECK_FALSE(rear.IsCabMaster()); unit.wait(10.0); - CHECK(unit.cab().PipePress > 4.5); - CHECK(rear.PipePress > 4.5); + CHECK(unit.cab().brakePipe.pressure > 4.5); + CHECK(rear.brakePipe.pressure > 4.5); } TEST_CASE("elf controller: an Elf with the emergency brake position leading one without it") { @@ -217,15 +217,15 @@ TEST_CASE("elf controller: an Elf with the emergency brake position leading one unit.set_controller(1); CHECK(other.MainCtrlPos == 0); unit.wait(10.0); - CHECK(lead.PipePress > 4.5); + CHECK(lead.brakePipe.pressure > 4.5); } SUBCASE("the emergency brake: the other one at its full braking, the pipe vented by the lead") { unit.set_controller(0); REQUIRE(lead.IsMainCtrlEmergencyPos()); CHECK(other.MainCtrlPos == 0); unit.wait(10.0); - CHECK(lead.PipePress < 0.5); - CHECK(other.PipePress < 0.5); + CHECK(lead.brakePipe.pressure < 0.5); + CHECK(other.brakePipe.pressure < 0.5); } } @@ -247,8 +247,8 @@ TEST_CASE("elf controller: an Elf without the emergency brake position leading o CHECK(other.MainCtrlPos == 1); CHECK_FALSE(other.IsMainCtrlEmergencyPos()); unit.wait(10.0); - CHECK(lead.PipePress > 4.5); - CHECK(other.PipePress > 4.5); + CHECK(lead.brakePipe.pressure > 4.5); + CHECK(other.brakePipe.pressure > 4.5); } } diff --git a/tests/unit/test_feed_pipe.cpp b/tests/unit/test_feed_pipe.cpp index 21ff98e4d..a7eba7c0c 100644 --- a/tests/unit/test_feed_pipe.cpp +++ b/tests/unit/test_feed_pipe.cpp @@ -48,7 +48,7 @@ double off_pressure(test::consist &Train, double const Pressure, double const Se for (int step = 0; step < steps; ++step) { Train.step({}, Dt); for (std::size_t i = 0; i < Train.size(); ++i) { - off = std::max(off, std::abs(Train[i]->ScndPipePress - Pressure)); + off = std::max(off, std::abs(Train[i]->mainPipe.pressure - Pressure)); } } return off; @@ -67,13 +67,13 @@ evening_out even_out(Builder Train, int const Count, double const Pressure, doub Train(train, Count); for (std::size_t i = 0; i < train.size(); ++i) { auto &physics{train[i].physics()}; - REQUIRE(physics.VeselVolume > 0.0); + REQUIRE(physics.air.mainReservoirVolume > 0.0); auto const pressure{i == 0 ? Pressure : Pressure - 1.0}; - physics.CompressedVolume = pressure * physics.VeselVolume; - physics.Compressor = pressure; - physics.Pipe2->CreatePress(pressure); - physics.Pipe2->Act(); - physics.ScndPipePress = pressure; + physics.air.compressedVolume = pressure * physics.air.mainReservoirVolume; + physics.air.mainReservoirPressure = pressure; + physics.mainPipe.reservoir->CreatePress(pressure); + physics.mainPipe.reservoir->Act(); + physics.mainPipe.pressure = pressure; } evening_out result; auto const &first{train[0].physics()}; @@ -81,22 +81,22 @@ evening_out even_out(Builder Train, int const Count, double const Pressure, doub std::vector previous(train.size()); std::vector change(train.size()); for (std::size_t i = 0; i < train.size(); ++i) { - previous[i] = train[i]->ScndPipePress; + previous[i] = train[i]->mainPipe.pressure; } auto time{0.0}; while (time < 60.0) { train.step({}, Dt); time += Dt; for (std::size_t i = 0; i < train.size(); ++i) { - auto const step{train[i]->ScndPipePress - previous[i]}; + auto const step{train[i]->mainPipe.pressure - previous[i]}; if (step * change[i] < 0.0) { // turned back result.zigzag = std::max(result.zigzag, std::min(std::abs(step), std::abs(change[i]))); } change[i] = step; - previous[i] = train[i]->ScndPipePress; + previous[i] = train[i]->mainPipe.pressure; } - if (std::abs(first.Compressor - last.Compressor) < 0.05) { + if (std::abs(first.air.mainReservoirPressure - last.air.mainReservoirPressure) < 0.05) { result.time = time; break; } @@ -113,15 +113,15 @@ double charging_time(Builder Train, int const Count, double const Pressure, doub train[0].hold_main_reservoir(Pressure); for (std::size_t i = 1; i < train.size(); ++i) { auto &physics{train[i].physics()}; - REQUIRE(physics.VeselVolume == 0.0); - physics.Pipe2->CreatePress(0.0); - physics.Pipe2->Act(); - physics.ScndPipePress = 0.0; + REQUIRE(physics.air.mainReservoirVolume == 0.0); + physics.mainPipe.reservoir->CreatePress(0.0); + physics.mainPipe.reservoir->Act(); + physics.mainPipe.pressure = 0.0; } auto const &first{train[0].physics()}; auto const &last{train[train.size() - 1].physics()}; auto time{0.0}; - while ((last.ScndPipePress < 1.0 || std::abs(last.ScndPipePress - first.ScndPipePress) > 0.2) && time < 60.0) { + while ((last.mainPipe.pressure < 1.0 || std::abs(last.mainPipe.pressure - first.mainPipe.pressure) > 0.2) && time < 60.0) { train.step({}, Dt); time += Dt; } diff --git a/tests/unit/test_figures.cpp b/tests/unit/test_figures.cpp index d40bc158b..bf8c004f1 100644 --- a/tests/unit/test_figures.cpp +++ b/tests/unit/test_figures.cpp @@ -17,21 +17,21 @@ TEST_CASE("figures: a run split into parts by the events, each from the last ste test::figures figures; auto &physics{eu07.physics()}; physics.V = 10.0; - physics.PipePress = 5.0; + physics.brakePipe.pressure = 5.0; figures.sample(0.0, physics); figures.mark("brake"); figures.mark("hard"); for (int i = 1; i <= 10; ++i) { physics.V = 10.0 - i; physics.DistCounter += 0.005; - physics.PipePress = 3.5; + physics.brakePipe.pressure = 3.5; physics.BrakePress = 0.4 * i; figures.sample(i, physics); } figures.mark("release"); - physics.PipePress = 4.0; + physics.brakePipe.pressure = 4.0; figures.sample(11.0, physics); - physics.PipePress = 5.0; + physics.brakePipe.pressure = 5.0; figures.sample(12.0, physics); auto const lines{figures.lines()}; diff --git a/tests/unit/test_genset.cpp b/tests/unit/test_genset.cpp index cc9172a53..7d4250d28 100644 --- a/tests/unit/test_genset.cpp +++ b/tests/unit/test_genset.cpp @@ -90,7 +90,7 @@ bool start_on_genset(vehicle &Vehicle, track const &Track = no_wire, double cons cab.CompressorSwitch(true); } run(Vehicle, 1.0, Track); - if (cab.Mains && cab.ConverterFlag && cab.ScndPipePress >= 4.5) { + if (cab.Mains && cab.ConverterFlag && cab.mainPipe.pressure >= 4.5) { // and the brakes let go test::release_brakes(cab); for (auto wait = 0; wait < 120 && cab.BrakePress > 0.05; ++wait) { diff --git a/tests/unit/test_horn.cpp b/tests/unit/test_horn.cpp index 7245d4267..cd2e68df3 100644 --- a/tests/unit/test_horn.cpp +++ b/tests/unit/test_horn.cpp @@ -57,19 +57,19 @@ TEST_CASE("horn: a pneumatic horn sounds on the air of the main reservoir only") auto vehicle{horn_vehicle(test::definition::load("wagon"))}; REQUIRE(vehicle->HornSupply == horn_supply::air); // the default - vehicle->Compressor = 6.5; + vehicle->air.mainReservoirPressure = 6.5; CHECK(vehicle->SoundingHorns(allhorns) == allhorns); - vehicle->Compressor = 0.0; // the reservoir is empty + vehicle->air.mainReservoirPressure = 0.0; // the reservoir is empty CHECK(vehicle->SoundingHorns(allhorns) == 0); } TEST_CASE("horn: a vehicle without a main reservoir takes the horn air from the main pipe") { test::vehicle vehicle{test::definition::load("wagon")}; - REQUIRE(vehicle->VeselVolume == 0.0); + REQUIRE(vehicle->air.mainReservoirVolume == 0.0); - vehicle->ScndPipePress = 5.0; + vehicle->mainPipe.pressure = 5.0; CHECK(vehicle->SoundingHorns(horn::low) == horn::low); - vehicle->ScndPipePress = 0.0; + vehicle->mainPipe.pressure = 0.0; CHECK(vehicle->SoundingHorns(horn::low) == 0); } @@ -78,7 +78,7 @@ TEST_CASE("horn: an electric horn sounds on the low voltage, whatever the air") REQUIRE(vehicle->HornSupply == horn_supply::electric); REQUIRE(vehicle->Horn3Supply == horn_supply::electric); // the third horn follows the others unless told otherwise - vehicle->Compressor = 0.0; + vehicle->air.mainReservoirPressure = 0.0; vehicle->Power24vIsAvailable = true; CHECK(vehicle->SoundingHorns(allhorns) == allhorns); vehicle->Power24vIsAvailable = false; @@ -90,10 +90,10 @@ TEST_CASE("horn: the third horn can have a supply of its own, an electric horn o REQUIRE(vehicle->HornSupply == horn_supply::air); REQUIRE(vehicle->Horn3Supply == horn_supply::electric); - vehicle->Compressor = 0.0; + vehicle->air.mainReservoirPressure = 0.0; vehicle->Power24vIsAvailable = true; CHECK(vehicle->SoundingHorns(allhorns) == 4); - vehicle->Compressor = 6.5; + vehicle->air.mainReservoirPressure = 6.5; vehicle->Power24vIsAvailable = false; CHECK(vehicle->SoundingHorns(allhorns) == (horn::low | horn::high)); } @@ -101,16 +101,16 @@ TEST_CASE("horn: the third horn can have a supply of its own, an electric horn o TEST_CASE("horn: a vehicle without any air, a road vehicle say, sounds its pneumatic horn as before") { // no main reservoir and no main pipe connection at either end test::vehicle vehicle{test::definition::load("wagon").set("BuffCoupl", "AllowedFlag", 3)}; - REQUIRE(vehicle->VeselVolume == 0.0); - vehicle->ScndPipePress = 0.0; + REQUIRE(vehicle->air.mainReservoirVolume == 0.0); + vehicle->mainPipe.pressure = 0.0; CHECK(vehicle->SoundingHorns(allhorns) == allhorns); } TEST_CASE("horn: a pneumatic horn sounds from the threshold pressure up") { auto vehicle{horn_vehicle(test::definition::load("wagon"))}; - vehicle->Compressor = physics::Vehicle::HornMinPressure; + vehicle->air.mainReservoirPressure = physics::Vehicle::HornMinPressure; CHECK(vehicle->SoundingHorns(horn::low) == horn::low); - vehicle->Compressor = physics::Vehicle::HornMinPressure - 0.01; + vehicle->air.mainReservoirPressure = physics::Vehicle::HornMinPressure - 0.01; CHECK(vehicle->SoundingHorns(horn::low) == 0); } diff --git a/tests/unit/test_line_contactors.cpp b/tests/unit/test_line_contactors.cpp index fd7e24f08..6e2944d49 100644 --- a/tests/unit/test_line_contactors.cpp +++ b/tests/unit/test_line_contactors.cpp @@ -10,7 +10,7 @@ namespace { test::vehicle locomotive(bool const Pressureswitch) { test::vehicle vehicle{test::definition::load("wagon").set("Engine", "PressureSwitch", Pressureswitch)}; vehicle->StLinFlag = false; // the line contactors open - vehicle->PipePress = 5.0; + vehicle->brakePipe.pressure = 5.0; return vehicle; } diff --git a/tests/unit/test_line_contactors_interlock.cpp b/tests/unit/test_line_contactors_interlock.cpp index d8c484349..4a2ed9c5e 100644 --- a/tests/unit/test_line_contactors_interlock.cpp +++ b/tests/unit/test_line_contactors_interlock.cpp @@ -24,7 +24,7 @@ vehicle ready(std::string_view const Interlock) { vehicle locomotive{loaded}; locomotive->Mains = true; locomotive->DirActive = 1; - locomotive->PipePress = 5.0; + locomotive->brakePipe.pressure = 5.0; locomotive->BrakePress = 0.0; return locomotive; } @@ -133,7 +133,7 @@ bool close_line_contactors(test::driven const &Driven) { // the brakes released and the cylinders empty enough for the pressure switch to let the vehicle start void release(test::driven const &Driven) { test::release_brakes(Driven.cab); - for (int i = 0; i < 90 && (Driven.controlling.BrakePress > 0.1 || Driven.controlling.PipePress < 4.8); ++i) { + for (int i = 0; i < 90 && (Driven.controlling.BrakePress > 0.1 || Driven.controlling.brakePipe.pressure < 4.8); ++i) { test::drive(Driven, line, 1.0); } } @@ -302,14 +302,14 @@ TEST_CASE("line contactors interlock: the ET42 section with its fans switched of TEST_CASE("louvres: closed until the main reservoir reaches the pressure that opens them") { vehicle et22{definition::fiz("et22_v3/201e-w")}; CHECK(et22->LouvresOpenPressure == doctest::Approx(5.0)); // by default - et22->Compressor = 4.9; + et22->air.mainReservoirPressure = 4.9; CHECK(et22->LouvresClosed()); - et22->Compressor = 5.0; + et22->air.mainReservoirPressure = 5.0; CHECK_FALSE(et22->LouvresClosed()); vehicle given{definition::fiz("et22_v3/201e-w").set("Cntrl", "LouvresOpenPressure", 4.0)}; - given->Compressor = 4.5; + given->air.mainReservoirPressure = 4.5; CHECK_FALSE(given->LouvresClosed()); - given->Compressor = 3.9; + given->air.mainReservoirPressure = 3.9; CHECK(given->LouvresClosed()); } diff --git a/tests/unit/test_mains_before_pantographs.cpp b/tests/unit/test_mains_before_pantographs.cpp index efab5a572..3506966ad 100644 --- a/tests/unit/test_mains_before_pantographs.cpp +++ b/tests/unit/test_mains_before_pantographs.cpp @@ -57,9 +57,9 @@ void switch_auxiliaries_on(test::vehicle &Loco) { // what the main reservoir gains over the given time [bar]; the compressor of the locomotive adds some 0.07 bar a second double reservoir_gain(test::vehicle &Loco, double const Seconds, test::track const &Track) { - auto const before{Loco->CompressedVolume}; + auto const before{Loco->air.compressedVolume}; Loco.run(Seconds, Track); - return (Loco->CompressedVolume - before) / Loco->VeselVolume; + return (Loco->air.compressedVolume - before) / Loco->air.mainReservoirVolume; } // the locomotive started up the way the driver does it, the brakes released, then the master controller taken to the @@ -168,7 +168,7 @@ TEST_CASE("mains before pantographs: with the flag the converter and the compres REQUIRE(loco->PantographVoltage == 0.0); switch_auxiliaries_on(loco); REQUIRE(loco->ConverterAllow); - REQUIRE(loco->CompressorAllow); + REQUIRE(loco->air.compressor.allow); // the line breaker closed on the battery, the pantographs down: there's nothing to run them on CHECK(reservoir_gain(loco, 20.0, line) < 0.01); @@ -176,7 +176,7 @@ TEST_CASE("mains before pantographs: with the flag the converter and the compres CHECK_FALSE(loco->MainCircuitPowered()); CHECK_FALSE(loco->ConverterFlag); CHECK_FALSE(loco->Power110vIsAvailable); - CHECK_FALSE(loco->CompressorFlag); + CHECK_FALSE(loco->air.compressor.running); // the pantograph up: the converter starts, and the compressor on its 110 V raise_pantograph(loco); @@ -185,7 +185,7 @@ TEST_CASE("mains before pantographs: with the flag the converter and the compres CHECK(loco->MainCircuitPowered()); CHECK(loco->ConverterFlag); CHECK(loco->Power110vIsAvailable); - CHECK(loco->CompressorFlag); + CHECK(loco->air.compressor.running); // the voltage gone they stop, behind the line breaker which stays closed auto const *track{&line}; @@ -209,14 +209,14 @@ TEST_CASE("mains before pantographs: with the flag the converter and the compres CHECK_FALSE(loco->MainCircuitPowered()); CHECK_FALSE(loco->ConverterFlag); CHECK_FALSE(loco->Power110vIsAvailable); - CHECK_FALSE(loco->CompressorFlag); + CHECK_FALSE(loco->air.compressor.running); } TEST_CASE("mains before pantographs: with the flag whatever else the main circuit feeds waits for the traction voltage too") { // a compressor on the main circuit rather than the converter's 110 V, the motor blowers, the blowers of the starting // resistors, the heating test::vehicle loco{ep05(true).set("Brake", "CompressorPower", "Main"), 0.0, "test", 1}; - REQUIRE(loco->CompressorPower == 0); + REQUIRE(loco->air.compressor.supply == physics::CompressorSupply::mainCircuit); REQUIRE(loco->HeatingPowerSource.SourceType == TPowerSource::Main); prepare(loco); close_line_breaker(loco); @@ -228,7 +228,7 @@ TEST_CASE("mains before pantographs: with the flag whatever else the main circui loco.hold_main_reservoir(-1.0); CHECK(reservoir_gain(loco, 10.0, line) < 0.01); - CHECK_FALSE(loco->CompressorFlag); + CHECK_FALSE(loco->air.compressor.running); CHECK_FALSE(loco->MotorBlowers[VehicleEnd::front].is_active); CHECK(loco->RventRot == 0.0); CHECK_FALSE(loco->Heating); @@ -238,7 +238,7 @@ TEST_CASE("mains before pantographs: with the flag whatever else the main circui REQUIRE(loco->PantographVoltage == doctest::Approx(weak.voltage)); CHECK(reservoir_gain(loco, 10.0, weak) < 0.01); CHECK(loco->Mains); - CHECK_FALSE(loco->CompressorFlag); + CHECK_FALSE(loco->air.compressor.running); CHECK_FALSE(loco->MotorBlowers[VehicleEnd::front].is_active); CHECK(loco->RventRot == 0.0); CHECK_FALSE(loco->Heating); @@ -247,7 +247,7 @@ TEST_CASE("mains before pantographs: with the flag whatever else the main circui raise_pantograph(loco); REQUIRE(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); CHECK(reservoir_gain(loco, 10.0, line) > 0.1); - CHECK(loco->CompressorFlag); + CHECK(loco->air.compressor.running); CHECK(loco->MotorBlowers[VehicleEnd::front].is_active); CHECK(loco->RventRot > 0.0); CHECK(loco->Heating); @@ -265,14 +265,14 @@ TEST_CASE("mains before pantographs: without the flag the converter and the comp CHECK(loco->MainCircuitPowered()); CHECK(loco->ConverterFlag); CHECK(loco->Power110vIsAvailable); - CHECK(loco->CompressorFlag); + CHECK(loco->air.compressor.running); // too low a voltage opens the line breaker, and they stop with it loco.run(5.0, weak); CHECK_FALSE(loco->Mains); CHECK_FALSE(loco->MainCircuitPowered()); CHECK_FALSE(loco->ConverterFlag); CHECK_FALSE(loco->Power110vIsAvailable); - CHECK_FALSE(loco->CompressorFlag); + CHECK_FALSE(loco->air.compressor.running); } // the undervoltage trip was also what cut the traction motors off when the voltage went: the line contactors open diff --git a/tests/unit/test_pressure_switch.cpp b/tests/unit/test_pressure_switch.cpp index bb548ecb4..cc3d48aca 100644 --- a/tests/unit/test_pressure_switch.cpp +++ b/tests/unit/test_pressure_switch.cpp @@ -74,13 +74,13 @@ void apply_independent_brake(test::vehicle &Loco, test::driven const &Driven) { Loco->IncLocalBrakeLevel(LocalBrakePosNo); test::drive(Driven, line, 20.0); REQUIRE(Loco->BrakePress == doctest::Approx(3.8).epsilon(0.03)); - REQUIRE(Loco->PipePress > 4.8); + REQUIRE(Loco->brakePipe.pressure > 4.8); } void emergency_application(test::vehicle &Loco, test::driven const &Driven) { Loco->BrakeLevelSet(Loco->Handle->GetPos(bh_EB)); test::drive(Driven, line, 10.0); - REQUIRE(Loco->PipePress < 1.0); + REQUIRE(Loco->brakePipe.pressure < 1.0); } } // namespace @@ -138,8 +138,8 @@ TEST_CASE("pressure switch: without its brake cylinder half the brake pipe still SUBCASE("a service application") { loco->BrakeLevelSet(loco->Handle->GetPos(bh_FB)); test::drive(driven, line, 15.0); - REQUIRE(loco->PipePress < 3.6); - REQUIRE(loco->PipePress > 3.0); + REQUIRE(loco->brakePipe.pressure < 3.6); + REQUIRE(loco->brakePipe.pressure > 3.0); } SUBCASE("an emergency application") { emergency_application(loco, driven); @@ -164,7 +164,7 @@ TEST_CASE("pressure switch: an emergency application with the master controller loco->AlarmChainSwitch(true); } test::drive(driven, line, 10.0); - REQUIRE(loco->PipePress < emergency_pressure); + REQUIRE(loco->brakePipe.pressure < emergency_pressure); REQUIRE(loco->MainCtrlPos == 5); CHECK_FALSE(loco->Mains); CHECK_FALSE(loco->Pantographs[VehicleEnd::front].is_active); @@ -210,10 +210,10 @@ TEST_CASE("pressure switch: a service application with the master controller on // the last service position of the FV4a, 2.8 bar in the pipe loco->BrakeLevelSet(5.0); - auto lowest{loco->PipePress}; + auto lowest{loco->brakePipe.pressure}; for (int second = 0; second < 60; ++second) { test::drive(driven, line, 1.0); - lowest = std::min(lowest, loco->PipePress); + lowest = std::min(lowest, loco->brakePipe.pressure); } MESSAGE("the lowest brake pipe pressure of the service application: " << lowest << " bar"); REQUIRE(lowest < 3.0); @@ -273,7 +273,7 @@ TEST_CASE("pressure switch: after the emergency application the driver's start-u CHECK(loco->Mains); CHECK(loco->Pantographs[VehicleEnd::rear].is_active); CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); - REQUIRE(loco->PipePress < emergency_pressure); + REQUIRE(loco->brakePipe.pressure < emergency_pressure); // and it stays so test::drive(driven, line, 30.0); CHECK(loco->Mains); @@ -283,7 +283,7 @@ TEST_CASE("pressure switch: after the emergency application the driver's start-u // the pressure switch lets the start be made test::release_brakes(driven.cab); for (int i = 0; i < 180 && loco->ControlPressureSwitch; ++i) { - loco->BrakeReleaser(loco->PipePress < 3.0 ? 1 : 0); + loco->BrakeReleaser(loco->brakePipe.pressure < 3.0 ? 1 : 0); test::drive(driven, line, 1.0); } loco->BrakeReleaser(0); diff --git a/tests/unit/test_pullee.cpp b/tests/unit/test_pullee.cpp index 525673eca..e9917747a 100644 --- a/tests/unit/test_pullee.cpp +++ b/tests/unit/test_pullee.cpp @@ -41,9 +41,9 @@ struct hauled_train { // no air in the main reservoir and the feed pipe, as after standing dead for some hours void drain_feed_air(physics::Vehicle &Vehicle) { - Vehicle.Pipe2->CreatePress(0.0); - Vehicle.Pipe2->Act(); - Vehicle.CompressedVolume = 0.0; + Vehicle.mainPipe.reservoir->CreatePress(0.0); + Vehicle.mainPipe.reservoir->Act(); + Vehicle.air.compressedVolume = 0.0; } // whether the real vehicle can go in a train at all: the road vehicles can't, nor can the draisine, which has no coupler @@ -79,7 +79,7 @@ TEST_CASE("pullee: a dead Vectron vents the brake pipe of the train hauling it, REQUIRE_FALSE(train.hauled->PulleeMode); train.run(120.0); CHECK(train.hauled->EmergencyValveFlow > 0.0); - CHECK(train.locomotive->PipePress < 4.95); // the pipe sags although the locomotive keeps feeding it + CHECK(train.locomotive->brakePipe.pressure < 4.95); // the pipe sags although the locomotive keeps feeding it CHECK(train.hauled->BrakePress > 0.4); CHECK(train.hauled.speed() < 30.0); } @@ -87,7 +87,7 @@ TEST_CASE("pullee: a dead Vectron vents the brake pipe of the train hauling it, hauled_train train{vectron, 60.0, true}; train.run(120.0); CHECK(train.hauled->EmergencyValveFlow == 0.0); - CHECK(train.locomotive->PipePress > 4.99); + CHECK(train.locomotive->brakePipe.pressure > 4.99); CHECK(train.hauled->BrakePress < 0.1); CHECK(train.hauled->Fb < 1.0); CHECK(train.hauled.speed() > 40.0); // running resistance alone @@ -115,13 +115,13 @@ TEST_CASE("pullee: an EU07 with a driver can't release the brakes of a dead Vect if (false == pullee) { // the Vectron has emptied the brake pipe, and both locomotives stand on an emergency application CHECK(hauled->Battery); - CHECK(locomotive->PipePress < 1.0); + CHECK(locomotive->brakePipe.pressure < 1.0); CHECK(locomotive->BrakePress > 3.0); CHECK(hauled->BrakePress > 3.0); continue; } CHECK_FALSE(hauled->Battery); - CHECK(locomotive->PipePress > 4.9); + CHECK(locomotive->brakePipe.pressure > 4.9); CHECK(locomotive->BrakePress < 0.1); CHECK(hauled->BrakePress < 0.1); // the driver notches up watching the ammeter @@ -180,7 +180,7 @@ TEST_CASE("pullee: a dead EU47 starts to drag once its main reservoir has leaked CHECK(hauled.BrakePress < 0.1); CHECK(hauled.Fb < 1.0); train.run(1020.0); // 20 minutes since the start - CHECK(hauled.ScndPipePress < hauled.brakes.spring.minForcePressure); + CHECK(hauled.mainPipe.pressure < hauled.brakes.spring.minForcePressure); if (pullee) { CHECK(hauled.Fb < 1.0); } @@ -262,17 +262,17 @@ TEST_CASE("pullee: the brake valves in the cab of a vehicle prepared for hauling driven->DecLocalBrakeLevel(LocalBrakePosNo); driven.run(20.0); REQUIRE(driven->BrakePress < 0.1); - auto const charged{driven->PipePress}; + auto const charged{driven->brakePipe.pressure}; // full service braking with the driver's valve driven->BrakeLevelSet(driven->Handle->GetPos(bh_FB)); driven.run(10.0); if (pullee) { CHECK(driven->dpMainValve == 0.0); - CHECK(driven->PipePress > charged - 0.1); + CHECK(driven->brakePipe.pressure > charged - 0.1); CHECK(driven->BrakePress < 0.1); } else { - CHECK(driven->PipePress < charged - 0.5); + CHECK(driven->brakePipe.pressure < charged - 0.5); CHECK(driven->BrakePress > 1.0); } // and the emergency position @@ -280,10 +280,10 @@ TEST_CASE("pullee: the brake valves in the cab of a vehicle prepared for hauling driven.run(10.0); if (pullee) { CHECK(driven->dpMainValve == 0.0); - CHECK(driven->PipePress > charged - 0.1); + CHECK(driven->brakePipe.pressure > charged - 0.1); } else { - CHECK(driven->PipePress < 1.0); + CHECK(driven->brakePipe.pressure < 1.0); } } } @@ -421,7 +421,7 @@ TEST_CASE("pullee: every real vehicle prepared for hauling runs free behind a lo CHECK(hauled.EmergencyValveFlow == 0.0); CHECK(hauled.BrakePress < 0.1); CHECK(hauled.Fb < 1.0); - CHECK(train.locomotive->PipePress > 4.99); + CHECK(train.locomotive->brakePipe.pressure > 4.99); CHECK(train.hauled.speed() > 40.0); } } diff --git a/tests/unit/vehicle.cpp b/tests/unit/vehicle.cpp index 37bb1aab8..0f5fa9c21 100644 --- a/tests/unit/vehicle.cpp +++ b/tests/unit/vehicle.cpp @@ -161,7 +161,7 @@ void vehicle::step(track const &Track, double Dt) { fast_move(Track, Dt, location); } forces(Dt); - move(Track, Dt, location, m_physics->PipePress); + move(Track, Dt, location, m_physics->brakePipe.pressure); } namespace { @@ -202,10 +202,10 @@ double vehicle::fast_move(track const &Track, double Dt, TLocation const &Locati void vehicle::begin_step() { // the conditions the test keeps if (m_pipepressure >= 0.0) { - m_physics->Pipe->CreatePress(m_pipepressure); + m_physics->brakePipe.reservoir->CreatePress(m_pipepressure); } - if (m_reservoirpressure >= 0.0 && m_physics->VeselVolume > 0.0) { - m_physics->CompressedVolume = m_reservoirpressure * m_physics->VeselVolume; + if (m_reservoirpressure >= 0.0 && m_physics->air.mainReservoirVolume > 0.0) { + m_physics->air.compressedVolume = m_reservoirpressure * m_physics->air.mainReservoirVolume; } // vehicle_table::update(), before the forces m_physics->ComputeConstans(); @@ -335,7 +335,7 @@ void pair::step(track const &Track, double Dt) { } for (auto &placed : m_vehicles) { auto const &physics{placed.owner->physics()}; - placed.position += placed.heading * placed.owner->move(Track, Dt, TLocation{placed.position, 0.0, 0.0}, physics.PipePress); + placed.position += placed.heading * placed.owner->move(Track, Dt, TLocation{placed.position, 0.0, 0.0}, physics.brakePipe.pressure); } // vehicle_table::update_brake_pipes() physics::Vehicle::UpdatePipeCouplers({&m_vehicles[0].owner->physics(), &m_vehicles[1].owner->physics()}, Dt); diff --git a/vehicle/ai/consist.cpp b/vehicle/ai/consist.cpp index cb0472388..28c700cb5 100644 --- a/vehicle/ai/consist.cpp +++ b/vehicle/ai/consist.cpp @@ -107,7 +107,7 @@ void TController::Activation() if( occupied->BrakeCtrlPosNo > 0 && ( BrakeSystem == TBrakeSystem::Pneumatic || BrakeSystem == TBrakeSystem::ElectroPneumatic ) ) { - occupied->LimPipePress = occupied->PipePress; + occupied->LimPipePress = occupied->brakePipe.pressure; occupied->ActFlowSpeed = 0; } BrakeLevelSet( occupied->BrakeCtrlPos ); @@ -703,7 +703,7 @@ TController::determine_consist_state() { Ready = true; // wstępnie gotowy fReady = 0.0; // założenie, że odhamowany IsConsistBraked = occupied->BrakeSystem == TBrakeSystem::ElectroPneumatic && false == ForcePNBrake ? occupied->BrakePress > 2.0 : - occupied->PipePress < std::max(3.9, occupied->BrakePressureActual.PipePressureVal) + 0.1; + occupied->brakePipe.pressure < std::max(3.9, occupied->BrakePressureActual.PipePressureVal) + 0.1; fAccGravity = 0.0; // przyspieszenie wynikające z pochylenia IsAnyCouplerStretched = false; IsAnyDoorOnlyOpen[ VehicleSide::right ] = IsAnyDoorOnlyOpen[ VehicleSide::left ] = false; @@ -729,7 +729,7 @@ TController::determine_consist_state() { if( ( vehicle->BrakeSystem != TBrakeSystem::Individual ) && ( vehicle->MaxBrakePress[ 3 ] > 0.0 ) && ( false == TestFlag( vehicle->Hamulec->GetBrakeStatus(), b_dmg ) ) ) { // a brake cut out doesn't count - chargelevel = std::min( { chargelevel, vehicle->PipePress, vehicle->Hamulec->GetBRP() } ); + chargelevel = std::min( { chargelevel, vehicle->brakePipe.pressure, vehicle->Hamulec->GetBRP() } ); } auto const wasready { Ready }; if( released || Ready ) { @@ -751,14 +751,14 @@ TController::determine_consist_state() { // Ra: odluźnianie przeładowanych lokomotyw, ciągniętych na zimno - prowizorka... if( bp >= 0.4 && (AIControllFlag || Global.AITrainman && occupied->Vel < EU07_AI_NOMOVEMENT && !is_emu() && !is_dmu()) && BrakeCtrlPosition == gbh_RP // jest pozycja jazdy && false == TestFlag(vehicle->Hamulec->GetBrakeStatus(), b_dmg) // brake isn't broken - && vehicle->PipePress - occupied->Handle->GetRP() > -0.1 // jeśli ciśnienie jak dla jazdy - && vehicle->Hamulec->GetCRP() > vehicle->PipePress + 0.12 ) { // wg UIC określone sztywno na 0.04 + && vehicle->brakePipe.pressure - occupied->Handle->GetRP() > -0.1 // jeśli ciśnienie jak dla jazdy + && vehicle->Hamulec->GetCRP() > vehicle->brakePipe.pressure + 0.12 ) { // wg UIC określone sztywno na 0.04 // za dużo w zbiorniku // indywidualne luzowanko vehicle->BrakeReleaser(1); } if (bp < 0.1 && (AIControllFlag || Global.AITrainman) && false == TestFlag(vehicle->Hamulec->GetBrakeStatus(), b_dmg) // brake isn't broken - && vehicle->Hamulec->GetCRP() < vehicle->PipePress - 0.1) { + && vehicle->Hamulec->GetCRP() < vehicle->brakePipe.pressure - 0.1) { // już nie jest za dużo w zbiorniku // koniec indywidualnego luzowanka vehicle->BrakeReleaser(0); @@ -826,9 +826,9 @@ TController::determine_consist_state() { IsAnyConverterOverloadRelayOpen |= vehicle->ConvOvldFlag; IsAnyMotorOverloadRelayOpen |= vehicle->FuseFlag; IsAnyGroundRelayOpen |= !vehicle->GroundRelay; - IsAnyCompressorPresent |= vehicle->CompressorSpeed > 0.0; - IsAnyCompressorEnabled |= vehicle->CompressorSpeed > 0.0 ? (vehicle->CompressorAllow || vehicle->CompressorStart == start_t::automatic) && vehicle->CompressorAllowLocal : false; - IsAnyCompressorExplicitlyEnabled |= vehicle->CompressorSpeed > 0.0 ? vehicle->CompressorAllow && vehicle->CompressorAllowLocal : false; + IsAnyCompressorPresent |= vehicle->air.compressor.speed > 0.0; + IsAnyCompressorEnabled |= vehicle->air.compressor.speed > 0.0 ? (vehicle->air.compressor.allow || vehicle->air.compressor.start == start_t::automatic) && vehicle->air.compressor.allowLocal : false; + IsAnyCompressorExplicitlyEnabled |= vehicle->air.compressor.speed > 0.0 ? vehicle->air.compressor.allow && vehicle->air.compressor.allowLocal : false; IsAnyConverterPresent |= vehicle->ConverterStart != start_t::disabled; IsAnyConverterEnabled |= ( vehicle->ConverterAllow || vehicle->ConverterStart == start_t::automatic ) && vehicle->ConverterAllowLocal; IsAnyConverterExplicitlyEnabled |= vehicle->ConverterAllow && vehicle->ConverterAllowLocal; @@ -898,15 +898,15 @@ TController::determine_consist_state() { // a human driver's handle, which BrakeCtrlPosition doesn't follow occupied->fBrakeCtrlPos > occupied->Handle->GetPos( bh_RP ) + 0.2 }; auto const reference { - brake_charge::reference( occupied->PipePress, std::min( occupied->Handle->GetRP(), 5.0 ), trainbrakeapplied ) }; + brake_charge::reference( occupied->brakePipe.pressure, std::min( occupied->Handle->GetRP(), 5.0 ), trainbrakeapplied ) }; // air to charge with: the engine prepared, the main reservoir above what the pipe charges to, and the driver's // brake valve feeding the pipe at the head of the train. a train still being prepared from cold can't charge, // nor one whose pipe is locked (unlocked by control_releaser()): it waits without that counting as a stall, held // by its brakes as it can't release them either auto const supplied { iEngineActive - && ( std::max( mvControlling->Compressor, occupied->Compressor ) > reference ) - && ( occupied->PipePress >= reference - brake_charge::margin ) }; + && ( std::max( mvControlling->air.mainReservoirPressure, occupied->air.mainReservoirPressure ) > reference ) + && ( occupied->brakePipe.pressure >= reference - brake_charge::margin ) }; auto const wasstalled { BrakeCharge.stalled }; IsConsistCharged = brake_charge::charged( BrakeCharge, chargelevel, reference, ElapsedTime, supplied ); if( BrakeCharge.stalled && ( false == wasstalled ) ) { diff --git a/vehicle/ai/engine.cpp b/vehicle/ai/engine.cpp index bab5c1044..7f8d27c72 100644 --- a/vehicle/ai/engine.cpp +++ b/vehicle/ai/engine.cpp @@ -116,7 +116,7 @@ bool TController::PrepareEngine() else { // jeżeli jest wystarczające ciśnienie w pantografach if( false == pantographUnit->bPantKurek3 - || pantographUnit->PantPress <= pantographUnit->ScndPipePress ) { // kurek przełączony albo główna już pompuje + || pantographUnit->PantPress <= pantographUnit->mainPipe.pressure ) { // kurek przełączony albo główna już pompuje cue_action( driver_hint::pantographcompressoroff ); // sprężarkę pantografów można już wyłączyć } } @@ -163,7 +163,7 @@ bool TController::PrepareEngine() if( IsAnyCompressorPresent && IsAnyConverterEnabled ) { cue_action( driver_hint::compressoron ); } - if( mvControlling->ScndPipePress < 4.5 && mvControlling->VeselVolume > 0.0 ) { + if( mvControlling->mainPipe.pressure < 4.5 && mvControlling->air.mainReservoirVolume > 0.0 ) { cue_action( driver_hint::waitpressuretoolow ); } // enable motor blowers @@ -207,7 +207,7 @@ bool TController::PrepareEngine() && false == IsAnyLineBreakerOpen && ( false == IsAnyConverterPresent || true == IsAnyConverterEnabled ) && ( false == IsAnyCompressorPresent || true == IsAnyCompressorEnabled ) - && ( mvControlling->ScndPipePress > 4.5 || mvControlling->VeselVolume == 0.0 ); + && ( mvControlling->mainPipe.pressure > 4.5 || mvControlling->air.mainReservoirVolume == 0.0 ); } if( true == isready ) { diff --git a/vehicle/ai/force.cpp b/vehicle/ai/force.cpp index e68ef676a..ca37e43c7 100644 --- a/vehicle/ai/force.cpp +++ b/vehicle/ai/force.cpp @@ -609,7 +609,7 @@ void TController::control_releaser() { brake_releaser::conditions state; state.acceleration_desired = AccDesired; - state.pipe_pressure = occupied->PipePress; + state.pipe_pressure = occupied->brakePipe.pressure; state.cylinder_pressure = occupied->BrakePress; state.control_pressure = occupied->Hamulec->GetCRP(); state.velocity = occupied->Vel; @@ -677,7 +677,7 @@ void TController::control_main_pipe() { auto const departblocked { is_departure_blocked( DepartBlockedFSDelay ) }; if( (drivingFlags.oerlikons || true == IsCargoTrain || departblocked) && BrakeCtrlPosition == gbh_RP && AbsAccS < 0.03 && AccDesired > -0.03 && VelDesired - occupied->Vel > 2.0 && fReady > 0.35 && ( occupied->EqvtPipePress < 4.5 || departblocked ) // don't charge with a risk of overcharging the main pipe - && occupied->Compressor >= 7.5 // don't charge without sufficient pressure in the tank + && occupied->air.mainReservoirPressure >= 7.5 // don't charge without sufficient pressure in the tank && BrakeChargingCooldown >= 0.0 // don't charge while cooldown is active && (ActualProximityDist > 100.0 // don't charge if we're about to be braking soon || min_speed(occupied->Vel, VelNext) >= occupied->Vel) ) { @@ -689,7 +689,7 @@ void TController::control_main_pipe() { update_brake_charging(); - if( ( occupied->Compressor < 5.0 + if( ( occupied->air.mainReservoirPressure < 5.0 || ( BrakeCtrlPosition < gbh_RP && ( occupied->EqvtPipePress > (fReady < 0.25 ? 5.1 : 5.2) || is_brake_charging_done() ) ) ) // the light application a charging train stands on stays, as in DecBrake() @@ -713,7 +713,7 @@ void TController::update_brake_charging() { for( auto const *vehicle { pVehicles[ VehicleEnd::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { auto const isovercharged { vehicle->physics != occupied - && vehicle->physics->PipePress > FSOverchargePipePress }; + && vehicle->physics->brakePipe.pressure > FSOverchargePipePress }; if( isovercharged ) { BrakeChargingPipeOverchargeStart.try_emplace( vehicle, ElapsedTime ); } diff --git a/vehicle/ai/physicslog.cpp b/vehicle/ai/physicslog.cpp index 3497fc827..ea40569c9 100644 --- a/vehicle/ai/physicslog.cpp +++ b/vehicle/ai/physicslog.cpp @@ -73,7 +73,7 @@ std::string TController::physicslog_line() const { << occupied->Ff << " " << occupied->Fb << " " << occupied->BrakePress << " " - << occupied->PipePress << " " + << occupied->brakePipe.pressure << " " << mvControlling->Im << " " << int(mvControlling->MainCtrlPos) << " " << int(mvControlling->ScndCtrlPos) << " " @@ -117,7 +117,7 @@ void TController::PhysicsLog() line << ElapsedTime << "\t" << fabs(11.31 * occupied->WheelDiameter * occupied->nrot) << "\t"; line << mvControlling->AccS << "\t"; - line << occupied->PipePress << "\t" << occupied->CntrlPipePress << "\t" + line << occupied->brakePipe.pressure << "\t" << occupied->CntrlPipePress << "\t" << occupied->BrakePress << "\t"; line << occupied->Volume << "\t" << occupied->Hamulec->GetCRP() << "\n"; PhysicsLogs.append( VehicleName, line.str() ); diff --git a/vehicle/ai/situation.cpp b/vehicle/ai/situation.cpp index 9e79e913e..e07736b8e 100644 --- a/vehicle/ai/situation.cpp +++ b/vehicle/ai/situation.cpp @@ -143,7 +143,7 @@ TController::control_pantographs() { if( pantographUnit->EnginePowerSource.SourceType != TPowerSource::CurrentCollector ) { return; } if( false == pantographUnit->PantAutoValve - && occupied->ScndPipePress > 4.3 ) { + && occupied->mainPipe.pressure > 4.3 ) { // gdy główna sprężarka bezpiecznie nabije ciśnienie to można przestawić kurek na zasilanie pantografów z głównej pneumatyki cue_action( driver_hint::pantographairsourcesetmain ); } diff --git a/vehicle/cab/auxiliarycommands.cpp b/vehicle/cab/auxiliarycommands.cpp index 0c9804c6c..dac2aea49 100644 --- a/vehicle/cab/auxiliarycommands.cpp +++ b/vehicle/cab/auxiliarycommands.cpp @@ -843,7 +843,7 @@ void TTrain::OnCommand_compressortoggle(TTrain *Train, command_data const &Comma if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const compressorisenabled{(Train->Dynamic()->Mechanik ? Train->Dynamic()->Mechanik->IsAnyCompressorEnabled : Train->occupied->CompressorAllow)}; + auto const compressorisenabled{(Train->Dynamic()->Mechanik ? Train->Dynamic()->Mechanik->IsAnyCompressorEnabled : Train->occupied->air.compressor.allow)}; if (false == compressorisenabled) { @@ -895,7 +895,7 @@ void TTrain::OnCommand_compressorenable(TTrain *Train, command_data const &Comma void TTrain::OnCommand_compressordisable(TTrain *Train, command_data const &Command) { - if (Train->controlled->CompressorPower >= 2) + if (Train->controlled->air.compressor.supply >= physics::CompressorSupply::converter) { return; } @@ -921,7 +921,7 @@ void TTrain::OnCommand_compressordisable(TTrain *Train, command_data const &Comm void TTrain::OnCommand_compressortogglelocal(TTrain *Train, command_data const &Command) { - if (Train->occupied->CompressorPower >= 2) + if (Train->occupied->air.compressor.supply >= physics::CompressorSupply::converter) { return; } @@ -933,13 +933,13 @@ void TTrain::OnCommand_compressortogglelocal(TTrain *Train, command_data const & if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->occupied->CompressorAllowLocal) + if (false == Train->occupied->air.compressor.allowLocal) { // turn on // visual feedback Train->ggCompressorLocalButton.UpdateValue(1.0, Train->dsbSwitch); // effect - Train->occupied->CompressorAllowLocal = true; + Train->occupied->air.compressor.allowLocal = true; } else { @@ -947,7 +947,7 @@ void TTrain::OnCommand_compressortogglelocal(TTrain *Train, command_data const & // visual feedback Train->ggCompressorLocalButton.UpdateValue(0.0, Train->dsbSwitch); // effect - Train->occupied->CompressorAllowLocal = false; + Train->occupied->air.compressor.allowLocal = false; } } } @@ -955,7 +955,7 @@ void TTrain::OnCommand_compressortogglelocal(TTrain *Train, command_data const & void TTrain::OnCommand_compressorpresetactivatenext(TTrain *Train, command_data const &Command) { - if (Train->occupied->CompressorListPosNo == 0) + if (Train->occupied->air.compressor.listPositions == 0) { return; } @@ -967,14 +967,14 @@ void TTrain::OnCommand_compressorpresetactivatenext(TTrain *Train, command_data if (Train->ggCompressorListButton.type() == TGaugeType::push) { // impulse switch - if (Train->occupied->CompressorListPosNo < Train->occupied->CompressorListDefPos + 1) + if (Train->occupied->air.compressor.listPositions < Train->occupied->air.compressor.listDefaultPosition + 1) { return; } - Train->occupied->ChangeCompressorPreset(Command.action == GLFW_PRESS ? Train->occupied->CompressorListDefPos + 1 : Train->occupied->CompressorListDefPos); + Train->occupied->ChangeCompressorPreset(Command.action == GLFW_PRESS ? Train->occupied->air.compressor.listDefaultPosition + 1 : Train->occupied->air.compressor.listDefaultPosition); // visual feedback - Train->ggCompressorListButton.UpdateValue(static_cast(Train->occupied->CompressorListPos - 1), Train->dsbSwitch); + Train->ggCompressorListButton.UpdateValue(static_cast(Train->occupied->air.compressor.listPosition - 1), Train->dsbSwitch); } else { @@ -984,12 +984,12 @@ void TTrain::OnCommand_compressorpresetactivatenext(TTrain *Train, command_data return; } - if (Train->occupied->CompressorListPos < Train->occupied->CompressorListPosNo || true == Train->occupied->CompressorListWrap) + if (Train->occupied->air.compressor.listPosition < Train->occupied->air.compressor.listPositions || true == Train->occupied->air.compressor.listWraps) { // active light preset is stored as value in range 1-LigthPosNo - Train->occupied->ChangeCompressorPreset(Train->occupied->CompressorListPos < Train->occupied->CompressorListPosNo ? Train->occupied->CompressorListPos + 1 : 1); // wrap mode + Train->occupied->ChangeCompressorPreset(Train->occupied->air.compressor.listPosition < Train->occupied->air.compressor.listPositions ? Train->occupied->air.compressor.listPosition + 1 : 1); // wrap mode // visual feedback - Train->ggCompressorListButton.UpdateValue(static_cast(Train->occupied->CompressorListPos - 1), Train->dsbSwitch); + Train->ggCompressorListButton.UpdateValue(static_cast(Train->occupied->air.compressor.listPosition - 1), Train->dsbSwitch); } } } @@ -997,7 +997,7 @@ void TTrain::OnCommand_compressorpresetactivatenext(TTrain *Train, command_data void TTrain::OnCommand_compressorpresetactivateprevious(TTrain *Train, command_data const &Command) { - if (Train->occupied->CompressorListPosNo == 0) + if (Train->occupied->air.compressor.listPositions == 0) { return; } @@ -1012,15 +1012,15 @@ void TTrain::OnCommand_compressorpresetactivateprevious(TTrain *Train, command_d return; } - if (Train->occupied->CompressorListPos > 1 || true == Train->occupied->CompressorListWrap) + if (Train->occupied->air.compressor.listPosition > 1 || true == Train->occupied->air.compressor.listWraps) { // active light preset is stored as value in range 1-LigthPosNo - Train->occupied->ChangeCompressorPreset(Train->occupied->CompressorListPos > 1 ? Train->occupied->CompressorListPos - 1 : Train->occupied->CompressorListPosNo); // wrap mode + Train->occupied->ChangeCompressorPreset(Train->occupied->air.compressor.listPosition > 1 ? Train->occupied->air.compressor.listPosition - 1 : Train->occupied->air.compressor.listPositions); // wrap mode // visual feedback if (Train->ggCompressorListButton.SubModel != nullptr) { - Train->ggCompressorListButton.UpdateValue(static_cast(Train->occupied->CompressorListPos - 1), Train->dsbSwitch); + Train->ggCompressorListButton.UpdateValue(static_cast(Train->occupied->air.compressor.listPosition - 1), Train->dsbSwitch); } } } @@ -1028,7 +1028,7 @@ void TTrain::OnCommand_compressorpresetactivateprevious(TTrain *Train, command_d void TTrain::OnCommand_compressorpresetactivatedefault(TTrain *Train, command_data const &Command) { - if (Train->occupied->CompressorListPosNo == 0) + if (Train->occupied->air.compressor.listPositions == 0) { return; } @@ -1037,12 +1037,12 @@ void TTrain::OnCommand_compressorpresetactivatedefault(TTrain *Train, command_da return; } // one change per key press - Train->occupied->ChangeCompressorPreset(Train->occupied->CompressorListDefPos); + Train->occupied->ChangeCompressorPreset(Train->occupied->air.compressor.listDefaultPosition); // visual feedback if (Train->ggCompressorListButton.SubModel != nullptr) { - Train->ggCompressorListButton.UpdateValue(static_cast(Train->occupied->CompressorListPos - 1), Train->dsbSwitch); + Train->ggCompressorListButton.UpdateValue(static_cast(Train->occupied->air.compressor.listPosition - 1), Train->dsbSwitch); } } diff --git a/vehicle/cab/setup.cpp b/vehicle/cab/setup.cpp index 9658e1872..f7f99df23 100644 --- a/vehicle/cab/setup.cpp +++ b/vehicle/cab/setup.cpp @@ -995,9 +995,9 @@ void TTrain::set_cab_controls(int const Cab) } ggConverterLocalButton.PutValue(occupied->ConverterAllowLocal ? 1.f : 0.f); // compressor - ggCompressorButton.PutValue(controlled->CompressorAllow ? 1.f : 0.f); - ggCompressorLocalButton.PutValue(controlled->CompressorAllowLocal ? 1.f : 0.f); - ggCompressorListButton.PutValue(static_cast(occupied->CompressorListPos - 1)); + ggCompressorButton.PutValue(controlled->air.compressor.allow ? 1.f : 0.f); + ggCompressorLocalButton.PutValue(controlled->air.compressor.allowLocal ? 1.f : 0.f); + ggCompressorListButton.PutValue(static_cast(occupied->air.compressor.listPosition - 1)); // motor overload relay threshold / shunt mode ggMaxCurrentCtrl.PutValue(true == controlled->ShuntModeAllow ? (true == controlled->ShuntMode ? 1.f : 0.f) : controlled->MotorOverloadRelayHighThreshold ? 1.f : 0.f); // automatic relays (AutoRelay) @@ -1824,14 +1824,14 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con // manometr przewodu hamulcowego auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&occupied->PipePress); + gauge.AssignDouble(&occupied->brakePipe.pressure); } else if (Label == "scndpress:") { // manometr przewodu hamulcowego auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&occupied->ScndPipePress); + gauge.AssignDouble(&occupied->mainPipe.pressure); } else if (Label == "limpipepress:") { @@ -1866,7 +1866,7 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con // manometr sprezarki/zbiornika glownego auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&occupied->Compressor); + gauge.AssignDouble(&occupied->air.mainReservoirPressure); } else if (Label == "oilpress:") { diff --git a/vehicle/cab/train.cpp b/vehicle/cab/train.cpp index 32f5610ae..742117642 100644 --- a/vehicle/cab/train.cpp +++ b/vehicle/cab/train.cpp @@ -179,7 +179,7 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("main_ready", false == controlled->Mains && fHVoltage > 0.0 && controlled->MainsInitTimeCountdown <= 0.0); dict->insert("converter", occupied->Power110vIsAvailable); dict->insert("converter_overload", controlled->ConvOvldFlag); - dict->insert("compress", controlled->CompressorFlag); + dict->insert("compress", controlled->air.compressor.running); dict->insert("pant_compressor", pantographUnit->PantCompFlag); dict->insert("lights_front", occupied->iLights[VehicleEnd::front]); dict->insert("lights_rear", occupied->iLights[VehicleEnd::rear]); @@ -411,8 +411,8 @@ TTrain::state_t TTrain::get_state() const occupied->SecuritySystem.is_beeping(), btLampkaHVoltageB.GetValue(), fTachoVelocity, - static_cast(occupied->Compressor), - static_cast(occupied->PipePress), + static_cast(occupied->air.mainReservoirPressure), + static_cast(occupied->brakePipe.pressure), static_cast(occupied->BrakePress), static_cast(pantographUnit->PantPress), fHVoltage, @@ -677,7 +677,7 @@ void TTrain::MoveToVehicle(TDynamicObject *target) if (Dynamic()->Mechanik) Dynamic()->Mechanik->MoveTo(target); - target_train->Occupied()->LimPipePress = target_train->Occupied()->PipePress; + target_train->Occupied()->LimPipePress = target_train->Occupied()->brakePipe.pressure; target_train->Occupied()->CabActivisationAuto(true); // załączenie rozrządu (wirtualne kabiny) target_train->Dynamic()->MechInside = true; if (target_train->Dynamic()->Mechanik) @@ -748,7 +748,7 @@ void TTrain::MoveToVehicle(TDynamicObject *target) Dynamic()->Controller = Humandriver; } - Occupied()->LimPipePress = Occupied()->PipePress; + Occupied()->LimPipePress = Occupied()->brakePipe.pressure; Occupied()->CabActivisationAuto(true); // załączenie rozrządu (wirtualne kabiny) } else diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index 6ec84fb91..81399d8c6 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -433,8 +433,8 @@ void TTrain::updateUnitStates() if (p) { fPress[i][0] = static_cast(p->physics->BrakePress); - fPress[i][1] = static_cast(p->physics->PipePress); - fPress[i][2] = static_cast(p->physics->ScndPipePress); + fPress[i][1] = static_cast(p->physics->brakePipe.pressure); + fPress[i][2] = static_cast(p->physics->mainPipe.pressure); fPress[i][3] = static_cast(p->physics->CntrlPipePress); fPress[i][4] = static_cast(p->physics->Hamulec->GetBRP()); fPress[i][5] = static_cast((p->physics->TotalMass - p->physics->Mred) * 0.001); @@ -458,15 +458,15 @@ void TTrain::updateUnitStates() // TBD, TODO: clean up compressor data arrangement? if (iUnitNo <= 8) { - bComp[iUnitNo - 1][0] = bComp[iUnitNo - 1][0] || p->physics->CompressorAllow || p->physics->CompressorStart == start_t::automatic; + bComp[iUnitNo - 1][0] = bComp[iUnitNo - 1][0] || p->physics->air.compressor.allow || p->physics->air.compressor.start == start_t::automatic; } - if (p->physics->CompressorSpeed > 0.00001) + if (p->physics->air.compressor.speed > 0.00001) { if (iUnitNo <= 8) { - bComp[iUnitNo - 1][1] = bComp[iUnitNo - 1][1] || p->physics->CompressorFlag; + bComp[iUnitNo - 1][1] = bComp[iUnitNo - 1][1] || p->physics->air.compressor.running; } - bCompressors.emplace_back(p->physics->CompressorAllow || p->physics->CompressorStart == start_t::automatic, p->physics->CompressorFlag, i); + bCompressors.emplace_back(p->physics->air.compressor.allow || p->physics->air.compressor.start == start_t::automatic, p->physics->air.compressor.running, i); } bSlip[i] = p->physics->SlippingWheels; if (in < 8 && p->physics->inductionMotor.traction.maxPower > 1) @@ -581,9 +581,9 @@ void TTrain::updateFeedbackGauges() const { // wykonywać tylko gdy wyprowadzone na pulpit // Ra: sterowanie miernikiem: zbiornik główny - Console::ValueSet(0, occupied->Compressor); + Console::ValueSet(0, occupied->air.mainReservoirPressure); // Ra: sterowanie miernikiem: przewód główny - Console::ValueSet(1, occupied->PipePress); + Console::ValueSet(1, occupied->brakePipe.pressure); // Ra: sterowanie miernikiem: cylinder hamulcowy Console::ValueSet(2, occupied->BrakePress); // woltomierz wysokiego napięcia @@ -607,7 +607,7 @@ void TTrain::updateConverterOverload(double const Deltatime) if (controlled->ConverterFlag == true) { fConverterTimer += static_cast(Deltatime); - if (controlled->CompressorFlag == true && controlled->CompressorPower == 1 && (controlled->EngineType == TEngineType::ElectricSeriesMotor || controlled->TrainType == train_type::emu) && + if (controlled->air.compressor.running == true && controlled->air.compressor.supply == physics::CompressorSupply::converterManual && (controlled->EngineType == TEngineType::ElectricSeriesMotor || controlled->TrainType == train_type::emu) && DynamicObject->Controller == Humandriver // hunter-110212: poprawka dla EZT && DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag) { // hunter-091012: poprawka (zmiana warunku z CompressorPower /rozne od 0/ na /rowne 1/) @@ -620,7 +620,7 @@ void TTrain::updateConverterOverload(double const Deltatime) else if (fConverterTimer >= fConverterPrzekaznik) { // changed switch from always true to take into account state of the compressor switch - controlled->CompressorSwitch(controlled->CompressorAllow); + controlled->CompressorSwitch(controlled->air.compressor.allow); } } } @@ -777,7 +777,7 @@ void TTrain::updateBasicLamps() } // Lampka pracujacej sprezacki - if (controlled->CompressorFlag || occupied->CompressorFlag) + if (controlled->air.compressor.running || occupied->air.compressor.running) btCompressors.Turn(true); else btCompressors.Turn(false); @@ -848,8 +848,8 @@ void TTrain::updateCircuitLamps(double const Deltatime) btLampkaWysRozr.Turn(controlled->Imax >= controlled->ImaxHi); btLampkaNapNastHam.Turn(controlled->DirActive != 0); // napiecie na nastawniku hamulcowym - btLampkaSprezarka.Turn(controlled->CompressorFlag); // mutopsitka dziala - btLampkaSprezarkaOff.Turn(!controlled->CompressorFlag); + btLampkaSprezarka.Turn(controlled->air.compressor.running); // mutopsitka dziala + btLampkaSprezarkaOff.Turn(!controlled->air.compressor.running); btLampkaFuelPumpOff.Turn(!controlled->FuelPump.is_active); btLampkaOilPump.Turn(controlled->OilPump.is_active); // pre-lubrication pump, goes off once the engine is started @@ -1125,8 +1125,8 @@ void TTrain::updateSecondUnitLamps(bool const lowvoltagepower) } } - btLampkaSprezarkaB.Turn(physics->CompressorFlag); // mutopsitka dziala - btLampkaSprezarkaBOff.Turn(false == physics->CompressorFlag); + btLampkaSprezarkaB.Turn(physics->air.compressor.running); // mutopsitka dziala + btLampkaSprezarkaBOff.Turn(false == physics->air.compressor.running); if (controlled->Signalling == true) { if (physics->BrakePress >= 1.45f) diff --git a/vehicle/dynamic/consist.cpp b/vehicle/dynamic/consist.cpp index aa417f1c6..22d3c1a92 100644 --- a/vehicle/dynamic/consist.cpp +++ b/vehicle/dynamic/consist.cpp @@ -109,7 +109,7 @@ float TDynamicObject::GetEPP() { if (!temp) break; // Ra: zabezpieczenie przed ewentaulnymi błędami sprzęgów - eq += temp->physics->PipePress * temp->physics->Dim.L; + eq += temp->physics->brakePipe.pressure * temp->physics->Dim.L; am += temp->physics->Dim.L; if ((temp->physics->Couplers[coupler_nr].CouplingFlag & Coupling::brakeHose) != Coupling::brakeHose) break; // nic nie ma już dalej podłączone @@ -143,7 +143,7 @@ float TDynamicObject::GetEPP() { if (!temp) break; // Ra: zabezpieczenie przed ewentaulnymi błędami sprzęgów - eq += temp->physics->PipePress * temp->physics->Dim.L; + eq += temp->physics->brakePipe.pressure * temp->physics->Dim.L; am += temp->physics->Dim.L; if ((temp->physics->Couplers[coupler_nr].CouplingFlag & Coupling::brakeHose) != Coupling::brakeHose) break; // nic nie ma już dalej podłączone @@ -170,7 +170,7 @@ float TDynamicObject::GetEPP() break; // jeśli jednak z tyłu nic nie ma } } - eq -= physics->PipePress * physics->Dim.L; + eq -= physics->brakePipe.pressure * physics->Dim.L; am -= physics->Dim.L; return eq / am; }; diff --git a/vehicle/dynamic/lifecycle.cpp b/vehicle/dynamic/lifecycle.cpp index aee2653d1..9fe33bed3 100644 --- a/vehicle/dynamic/lifecycle.cpp +++ b/vehicle/dynamic/lifecycle.cpp @@ -344,19 +344,19 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" if ( contains( ActPar, 'E' ) ) // oprozniony { physics->Hamulec->ForceEmptiness(); - physics->Pipe->CreatePress(0); - physics->Pipe2->CreatePress(0); + physics->brakePipe.reservoir->CreatePress(0); + physics->mainPipe.reservoir->CreatePress(0); } if ( contains( ActPar, 'Q' ) ) // oprozniony { physics->Hamulec->ForceEmptiness(); - physics->Pipe->CreatePress(0.0); - physics->PipePress = 0.0; - physics->Pipe2->CreatePress(0.0); - physics->ScndPipePress = 0.0; + physics->brakePipe.reservoir->CreatePress(0.0); + physics->brakePipe.pressure = 0.0; + physics->mainPipe.reservoir->CreatePress(0.0); + physics->mainPipe.pressure = 0.0; physics->PantVolume = 0.1; physics->PantPress = 0.0; - physics->CompressedVolume = 0.0; + physics->air.compressedVolume = 0.0; } if ( contains( ActPar, '1' ) ) // wylaczanie 10% diff --git a/vehicle/dynamic/sounds.cpp b/vehicle/dynamic/sounds.cpp index 8e5c30067..37c6963e1 100644 --- a/vehicle/dynamic/sounds.cpp +++ b/vehicle/dynamic/sounds.cpp @@ -150,11 +150,11 @@ void TDynamicObject::renderAuxiliarySounds() { - if( physics->CompressorSpeed > 0.0 ) { + if( physics->air.compressor.speed > 0.0 ) { // McZapkie! - dzwiek compressor.wav tylko gdy dziala sprezarka - if( physics->CompressorFlag ) { + if( physics->air.compressor.running ) { // for compressor coupled with the diesel engine sound pitch is driven by engine revolutions - if( physics->CompressorPower == 3 ) { + if( physics->air.compressor.supply == physics::CompressorSupply::engine ) { // presume the compressor sound is recorded for idle revolutions // increase the pitch according to increase of engine revolutions auto const enginefactor { @@ -170,7 +170,7 @@ void TDynamicObject::renderAuxiliarySounds() { } else { // enhanced sound path, with dedicated sound for idling compressor - if( physics->CompressorGovernorLock ) { + if( physics->air.compressor.governorLock ) { sCompressor.stop(); sCompressorIdle.play( sound_flags::exclusive | sound_flags::looping ); } @@ -308,7 +308,7 @@ void TDynamicObject::renderEmergencyBrakeSound() { // smooth out air flow rate m_emergencybrakeflow = m_emergencybrakeflow == 0.0 ? physics->EmergencyValveFlow : std::lerp(m_emergencybrakeflow, physics->EmergencyValveFlow, 0.1); // scale volume based on the flow rate and on the pressure in the main pipe - auto const flowpressure { std::clamp( m_emergencybrakeflow, 0.0, 1.0 ) + std::clamp( 0.1 * physics->PipePress, 0.0, 0.5 ) }; + auto const flowpressure { std::clamp( m_emergencybrakeflow, 0.0, 1.0 ) + std::clamp( 0.1 * physics->brakePipe.pressure, 0.0, 0.5 ) }; m_emergencybrake .pitch( m_emergencybrake.m_frequencyoffset + 1.0 * m_emergencybrake.m_frequencyfactor ) .gain( m_emergencybrake.m_amplitudeoffset + std::clamp( flowpressure, 0.0, 1.0 ) * m_emergencybrake.m_amplitudefactor ) diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index d433fc649..8d0465bfa 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -1534,17 +1534,17 @@ void TDynamicObject::Damage(char flag) if (flag & 8) //blokada sprezarki { - if (physics->MinCompressor>0) - physics->MinCompressor -= 100000001; - if (physics->MaxCompressor>0) - physics->MaxCompressor -= 100000001; + if (physics->air.compressor.minPressure>0) + physics->air.compressor.minPressure -= 100000001; + if (physics->air.compressor.maxPressure>0) + physics->air.compressor.maxPressure -= 100000001; } else { - if (physics->MinCompressor<0) - physics->MinCompressor += 100000001; - if (physics->MaxCompressor<0) - physics->MaxCompressor += 100000001; + if (physics->air.compressor.minPressure<0) + physics->air.compressor.minPressure += 100000001; + if (physics->air.compressor.maxPressure<0) + physics->air.compressor.maxPressure += 100000001; } if (flag & 16) //blokada wału diff --git a/vehicle/dynamic/vehicletable.cpp b/vehicle/dynamic/vehicletable.cpp index 8a49d822f..6fb994068 100644 --- a/vehicle/dynamic/vehicletable.cpp +++ b/vehicle/dynamic/vehicletable.cpp @@ -562,8 +562,8 @@ vehicle_table::update_brake_pipes( double const Deltatime ) { m_brakepipes.clear(); for( auto *vehicle : m_items ) { - if( ( true == vehicle->physics->PipeCouplersPending ) - || ( true == vehicle->physics->ScndPipeCouplersPending ) ) { + if( ( true == vehicle->physics->brakePipe.couplersPending ) + || ( true == vehicle->physics->mainPipe.couplersPending ) ) { m_brakepipes.push_back( vehicle->physics ); } } @@ -690,7 +690,7 @@ vehicle_table::update_steps_parallel( double const Deltatime, int const Iteratio pipes.clear(); for( auto const index : members ) { auto *physics { m_items[ index ]->physics }; - if( physics->PipeCouplersPending || physics->ScndPipeCouplersPending ) { + if( physics->brakePipe.couplersPending || physics->mainPipe.couplersPending ) { pipes.push_back( physics ); } } diff --git a/widgets/vehicleparams.cpp b/widgets/vehicleparams.cpp index dd439cfbb..b4dfc2b6b 100644 --- a/widgets/vehicleparams.cpp +++ b/widgets/vehicleparams.cpp @@ -74,7 +74,7 @@ void ui::vehicleparams_panel::draw_mini(const physics::Vehicle &physics) draw_infobutton(STR_C("main.")); if (physics.ConverterFlag) draw_infobutton(STR_C("conv.")); - if (physics.CompressorFlag) + if (physics.air.compressor.running) draw_infobutton(STR_C("comp.")); if (physics.WarningSignal) @@ -154,8 +154,8 @@ void ui::vehicleparams_panel::render_contents() (true == physics.WaterHeater.is_damaged ? '!' : (physics.WaterHeater.is_active ? 'H' : (false == physics.WaterHeater.breaker ? '-' : (physics.WaterHeater.is_enabled ? 'h' : '.')))), (physics.FuelPump.is_active ? 'F' : (physics.FuelPump.is_enabled ? 'f' : '.')), (physics.OilPump.is_active ? 'O' : (physics.OilPump.is_enabled ? 'o' : '.')), (false == physics.ConverterAllowLocal ? '-' : (physics.ConverterAllow ? (physics.ConverterFlag ? 'X' : 'x') : '.')), (physics.ConvOvldFlag ? '!' : '.'), - (physics.CompressorFlag ? 'C' : (false == physics.CompressorAllowLocal ? '-' : ((physics.CompressorAllow || physics.CompressorStart == start_t::automatic) ? 'c' : '.'))), - (physics.CompressorGovernorLock ? '!' : '.'), "", std::string(isdieselenginepowered ? STR(" oil pressure: ") + to_string(physics.OilPump.pressure, 2) : "").c_str(), + (physics.air.compressor.running ? 'C' : (false == physics.air.compressor.allowLocal ? '-' : ((physics.air.compressor.allow || physics.air.compressor.start == start_t::automatic) ? 'c' : '.'))), + (physics.air.compressor.governorLock ? '!' : '.'), "", std::string(isdieselenginepowered ? STR(" oil pressure: ") + to_string(physics.OilPump.pressure, 2) : "").c_str(), // power transfers physics.Couplers[VehicleEnd::front].power_high.voltage, physics.Couplers[VehicleEnd::front].power_high.current, std::string(physics.Couplers[VehicleEnd::front].power_high.is_local ? "" : "-").c_str(), std::string(vehicle.DirectionGet() ? ":<<:" : ":>>:").c_str(), std::string(physics.Couplers[VehicleEnd::rear].power_high.is_local ? "" : "-").c_str(), @@ -205,9 +205,9 @@ void ui::vehicleparams_panel::render_contents() // cylinders physics.BrakePress, physics.LocBrakePress, physics.Hamulec->GetBrakeStatus(), // pipes - physics.PipePress, physics.BrakeCtrlPos2, physics.ScndPipePress, physics.CntrlPipePress, + physics.brakePipe.pressure, physics.BrakeCtrlPos2, physics.mainPipe.pressure, physics.CntrlPipePress, // tanks - physics.Hamulec->GetBRP(), physics.Compressor, physics.Hamulec->GetCRP()); + physics.Hamulec->GetBRP(), physics.air.mainReservoirPressure, physics.Hamulec->GetCRP()); ImGui::TextUnformatted(buffer.data()); From 16568d56952c466a0097ddae5818e3e650c643a0 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 01:48:33 +0100 Subject: [PATCH 030/123] refactor(physics): the brake valves, cylinders, pressures and positions in physics::Braking The rest of the braking of physics::Vehicle moves into brakes, with English names (physics/components/braking.h): the valves Hamulec distributor, Handle driverValve, LocHandle independentValve the definition BrakeSystem kind, BrakeSubsystem subsystem, BrakeValve / BrakeValveSize / BrakeValveParams distributorType / Size / Parameters, BrakeHandle / BrakeLocHandle driverValveType / independentValveType, the Handle_* driverValveSettings, LocalBrake localKind, MaxBrakePress maxCylinderPressure, LoadFlag loadSetting, P2FTrans pressureToForce, NBpA blocksPerAxle, High/Low/DeltaPipePress pipeHigh/LowPressure / pipePressureRange, CntrlPipePress controlReservoirPressure, Spg pipeSection, RapidMult / RapidVel rapidRatio / rapidSpeed, BrakeDelay delays, BrakeCtrlPosNo handlePositions, ... cylinders BrakeCylNo / Radius / Dist / Mult / Spring, BrakeSlckAdj, BrakeRigEff: count, radius, stroke, leverRatio, springForce, slackAdjusterForce, riggingEfficiency emergencyValve EmergencyValveOn / Off / Open / Area / Flow pipeLock LockPipeOn / Off, HandleUnlock, LockPipe, UnlockPipe the state BrakePress cylinderPressure, LocBrakePress independentCylinderPressure, EqvtPipePress equivalentPipePressure, Volume reservoirAir, dpBrake / dpPipe / dpMainValve / dpLocalValve brakeFlow / pipeFlow / driverValveFlow / independentValveFlow, BrakeCtrlPos(R, 2) handlePosition(Real), handleCapPosition, fBrakeCtrlPos handlePositionSmooth, LocalBrakePosA(EIM) independentPosition (Eim), BrakeStatus status, AlarmChainFlag alarmChain, BrakeDelayFlag / BrakeDelays delaySetting / availableDelays, BrakeOpModeFlag / BrakeOpModes operatingMode / availableOperatingModes, UnitBrakeForce unitForce, ... Renamed in the files of the vehicle itself, and elsewhere only where reached through -> or .: the driver keeps its own BrakeSystem, the editor its Handle, the radio its Volume, and the brake valve classes (brakes.*, oerlikonest.*) their fields of the same names. The C arrays (MaxBrakePress, BrakeCylMult, the universal buttons) are std::arrays of the same values; the bits of status, delaySetting and operatingMode stay ints for now. No change in behaviour: 1149/1149 tests, golden traces exact against staging 62f7a29b. --- application/driverhints.cpp | 30 +- application/driveruipanels.cpp | 32 +- input/drivermouseinput.cpp | 6 +- input/messaging.cpp | 2 +- physics/components/body.cpp | 96 ++--- physics/components/braking.h | 129 ++++++- physics/components/cab.cpp | 8 +- physics/components/collisions.cpp | 12 +- physics/components/commands.cpp | 8 +- physics/components/controllers.cpp | 28 +- physics/components/diesel.cpp | 2 +- physics/components/electrics.cpp | 2 +- physics/components/fizparser.cpp | 28 +- physics/components/fizsections.cpp | 156 ++++---- physics/components/pneumatics.cpp | 338 +++++++++--------- physics/components/securitysystem.cpp | 2 +- physics/components/setup.cpp | 184 +++++----- physics/components/traction.cpp | 40 +-- physics/vehicle.h | 98 +---- simulation/blackboxrecorder.cpp | 22 +- simulation/simulation.cpp | 4 +- tests/unit/drive.cpp | 6 +- tests/unit/figures.cpp | 4 +- tests/unit/golden.cpp | 94 ++--- tests/unit/invariants.cpp | 14 +- tests/unit/test_6dg_power_steps.cpp | 4 +- tests/unit/test_brake_cycle.cpp | 22 +- tests/unit/test_brake_handles.cpp | 46 +-- tests/unit/test_brake_pipe.cpp | 18 +- tests/unit/test_brake_setting.cpp | 96 ++--- tests/unit/test_brakes.cpp | 40 +-- tests/unit/test_cab.cpp | 8 +- tests/unit/test_camshaft.cpp | 2 +- tests/unit/test_cntrl.cpp | 6 +- tests/unit/test_commands.cpp | 4 +- tests/unit/test_controls.cpp | 66 ++-- tests/unit/test_coupler_physics.cpp | 8 +- tests/unit/test_couplers_trains.cpp | 4 +- tests/unit/test_crew.cpp | 22 +- tests/unit/test_definition.cpp | 6 +- tests/unit/test_derailment_vehicle.cpp | 2 +- tests/unit/test_diesel.cpp | 4 +- tests/unit/test_drivingaid.cpp | 14 +- tests/unit/test_dynamic_brake_diesel.cpp | 8 +- tests/unit/test_elf_controller.cpp | 14 +- tests/unit/test_est3al2_relay.cpp | 16 +- tests/unit/test_figures.cpp | 2 +- tests/unit/test_fiz.cpp | 2 +- tests/unit/test_genset.cpp | 6 +- tests/unit/test_handover.cpp | 6 +- tests/unit/test_invariants.cpp | 4 +- tests/unit/test_line_contactors.cpp | 12 +- tests/unit/test_line_contactors_interlock.cpp | 6 +- tests/unit/test_pressure_switch.cpp | 10 +- tests/unit/test_pullee.cpp | 70 ++-- tests/unit/test_speed_control.cpp | 4 +- tests/unit/test_traction.cpp | 10 +- tests/unit/vehicle.cpp | 12 +- vehicle/ai/consist.cpp | 62 ++-- vehicle/ai/controls.cpp | 126 +++---- vehicle/ai/driver.cpp | 2 +- vehicle/ai/engine.cpp | 20 +- vehicle/ai/force.cpp | 78 ++-- vehicle/ai/orders.cpp | 2 +- vehicle/ai/physicslog.cpp | 12 +- vehicle/ai/situation.cpp | 4 +- vehicle/ai/speed.cpp | 10 +- vehicle/brakesetting.cpp | 18 +- vehicle/cab/brakecommands.cpp | 90 ++--- vehicle/cab/controllercommands.cpp | 8 +- vehicle/cab/setup.cpp | 16 +- vehicle/cab/sounds.cpp | 28 +- vehicle/cab/train.cpp | 50 +-- vehicle/cab/update.cpp | 62 ++-- vehicle/crew.cpp | 6 +- vehicle/drivingaid.cpp | 4 +- vehicle/dynamic/lifecycle.cpp | 48 +-- vehicle/dynamic/sounds.cpp | 40 +-- vehicle/dynamic/update.cpp | 96 ++--- vehicle/handover.cpp | 2 +- widgets/vehicleparams.cpp | 10 +- world/TrackBuckle.cpp | 2 +- 82 files changed, 1363 insertions(+), 1332 deletions(-) diff --git a/application/driverhints.cpp b/application/driverhints.cpp index 34a0b5c2b..e41b12a39 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -490,7 +490,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this]( float const /*Parameter*/ ) { - return occupied->LocalBrake != TLocalBrake::ManualBrake || occupied->MBrake == false || occupied->ManualBrakePos == ManualBrakePosNo; } ); + return occupied->brakes.localKind != TLocalBrake::ManualBrake || occupied->brakes.hasHandBrake == false || occupied->brakes.handBrakePosition == ManualBrakePosNo; } ); break; } case driver_hint::manualbrakoff: { @@ -501,7 +501,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this]( float const /*Parameter*/ ) { - return occupied->LocalBrake != TLocalBrake::ManualBrake || occupied->MBrake == false || occupied->ManualBrakePos == 0; } ); + return occupied->brakes.localKind != TLocalBrake::ManualBrake || occupied->brakes.hasHandBrake == false || occupied->brakes.handBrakePosition == 0; } ); break; } // master controller @@ -796,8 +796,8 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // driver_hint_brakingforcesetzero // driver_hint_brakingforcelap case driver_hint::trainbrakesetpipeunlock: { - if (AIControllFlag && occupied->HandleUnlock != -3) { - while( BrakeCtrlPosition >= occupied->HandleUnlock + if (AIControllFlag && occupied->brakes.pipeLock.unlockHandlePosition != -3) { + while( BrakeCtrlPosition >= occupied->brakes.pipeLock.unlockHandlePosition && BrakeLevelAdd(-1) ) { // all work is done in the header } @@ -806,7 +806,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return occupied->HandleUnlock == -3 || BrakeCtrlPosition == occupied->HandleUnlock; } ); + return occupied->brakes.pipeLock.unlockHandlePosition == -3 || BrakeCtrlPosition == occupied->brakes.pipeLock.unlockHandlePosition; } ); break; } case driver_hint::trainbrakerelease: { @@ -818,7 +818,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return is_equal(occupied->fBrakeCtrlPos, occupied->Handle->GetPos(bh_RP), 0.2) || (occupied->Handle->Time && occupied->Handle->GetCP() > occupied->HighPipePress - 0.05); } ); + return is_equal(occupied->brakes.handlePositionSmooth, occupied->brakes.driverValve->GetPos(bh_RP), 0.2) || (occupied->brakes.driverValve->Time && occupied->brakes.driverValve->GetCP() > occupied->brakes.pipeHighPressure - 0.05); } ); // return ( BrakeCtrlPosition == gbh_RP ); } ); break; } @@ -826,7 +826,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) if( AIControllFlag ) { // za radą yB ustawiamy pozycję 3 kranu (ruszanie kranem w innych miejscach powino zostać wyłączone) if( BrakeSystem == TBrakeSystem::ElectroPneumatic && false == ForcePNBrake ) { - occupied->BrakeLevelSet( occupied->Handle->GetPos( bh_EPB ) ); + occupied->BrakeLevelSet( occupied->brakes.driverValve->GetPos( bh_EPB ) ); } else { BrakeCtrlPosition = 3; @@ -867,7 +867,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const Parameter) { - return std::abs(mvControlling->Fb) > Parameter || is_equal(occupied->fBrakeCtrlPos, occupied->Handle->GetPos(bh_EB), 0.2); }, + return std::abs(mvControlling->Fb) > Parameter || is_equal(occupied->brakes.handlePositionSmooth, occupied->brakes.driverValve->GetPos(bh_EB), 0.2); }, static_cast(std::max( 0.0, std::max( @@ -885,7 +885,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return Ready && fReady < 0.4 && is_equal(occupied->fBrakeCtrlPos, occupied->Handle->GetPos(bh_RP), 0.2); } ); + return Ready && fReady < 0.4 && is_equal(occupied->brakes.handlePositionSmooth, occupied->brakes.driverValve->GetPos(bh_RP), 0.2); } ); break; } case driver_hint::brakingforcelap: { @@ -899,7 +899,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // independent brake case driver_hint::independentbrakeapply: { - if (AIControllFlag && occupied->LocalBrakePosA < 1.0) { + if (AIControllFlag && occupied->brakes.independentPosition < 1.0) { occupied->IncLocalBrakeLevel( LocalBrakePosNo ); if (occupied->EIMCtrlEmergency) { occupied->DecLocalBrakeLevel(1); @@ -909,7 +909,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const Parameter) { - return occupied->LocalBrakePosA >= Parameter; }, + return occupied->brakes.independentPosition >= Parameter; }, ( LocalBrakePosNo - ( occupied->EIMCtrlEmergency ? 1 : 0 ) ) / LocalBrakePosNo ); break; } @@ -921,7 +921,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return occupied->LocalBrakePosA < 0.05; } ); + return occupied->brakes.independentPosition < 0.05; } ); break; } // reverser @@ -1001,7 +1001,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return mvControlling->ASBType != 1 || (mvControlling->Hamulec->GetBrakeStatus() & b_asb) != 0 || mvControlling->SlippingWheels == false; } ); + return mvControlling->brakes.antiSlipType != 1 || (mvControlling->brakes.distributor->GetBrakeStatus() & b_asb) != 0 || mvControlling->SlippingWheels == false; } ); break; } // horns @@ -1358,7 +1358,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return true == occupied->Hamulec->Releaser(); } ); + return true == occupied->brakes.distributor->Releaser(); } ); break; } case driver_hint::releaseroff: { @@ -1369,7 +1369,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return false == occupied->Hamulec->Releaser(); } ); + return false == occupied->brakes.distributor->Releaser(); } ); break; } diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index c4840d80d..7c956f019 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -149,7 +149,7 @@ drivingaid_panel::update() { std::snprintf ( m_buffer.data(), m_buffer.size(), STR_C(" Pressure: %.2f kPa (train pipe: %.2f kPa)"), - physics->BrakePress * 100, + physics->brakes.cylinderPressure * 100, physics->brakePipe.pressure * 100 ); expandedtext = m_buffer.data(); } @@ -861,7 +861,7 @@ debug_panel::update_section_vehicle( std::vector &Output ) { physics.Heating ? 'H' : physics.HeatingAllow ? 'h' : '.', - physics.Hamulec->Releaser() ? '^' : '.', + physics.brakes.distributor->Releaser() ? '^' : '.', std::string( m_input.mechanik ? STR(" R") + ( physics.Radio && physics.RadioFuse ? std::to_string( m_input.mechanik->iRadioChannel ) : "-" ) : "" ).c_str(), std::string( isdieselenginepowered ? STR(" oil pressure: ") + to_string( physics.OilPump.pressure, 2 ) : "" ).c_str(), // power transfers @@ -923,27 +923,27 @@ debug_panel::update_section_vehicle( std::vector &Output ) { m_buffer.data(), m_buffer.size(), STR_C("Brakes:\n train: %.2f (mode: %d, delay: %s, load flag: %d)\n independent: %.2f (%.2f), manual: %.2f, spring: %.2f\nBrake cylinder pressures:\n train: %.2f, independent: %.2f, status: 0x%.2x\nPipe pressures:\n brake: %.2f (hat: %.2f), main: %.2f, control: %.2f\nTank pressures:\n auxiliary: %.2f, main: %.2f, control: %.2f"), // brakes - physics.fBrakeCtrlPos, - physics.BrakeOpModeFlag, + physics.brakes.handlePositionSmooth, + physics.brakes.operatingMode, update_vehicle_brake().c_str(), - physics.LoadFlag, - physics.LocalBrakePosA, - physics.LocalBrakePosAEIM, - static_cast(physics.ManualBrakePos) / static_cast(ManualBrakePosNo), + physics.brakes.loadSetting, + physics.brakes.independentPosition, + physics.brakes.independentPositionEim, + static_cast(physics.brakes.handBrakePosition) / static_cast(ManualBrakePosNo), physics.brakes.spring.activate ? 1.f : 0.f, // cylinders - physics.BrakePress, - physics.LocBrakePress, - physics.Hamulec->GetBrakeStatus(), + physics.brakes.cylinderPressure, + physics.brakes.independentCylinderPressure, + physics.brakes.distributor->GetBrakeStatus(), // pipes physics.brakePipe.pressure, - physics.BrakeCtrlPos2, + physics.brakes.handleCapPosition, physics.mainPipe.pressure, - physics.CntrlPipePress, + physics.brakes.controlReservoirPressure, // tanks - physics.Hamulec->GetBRP(), + physics.brakes.distributor->GetBRP(), physics.air.mainReservoirPressure, - physics.Hamulec->GetCRP() ); + physics.brakes.distributor->GetCRP() ); textline = m_buffer.data(); @@ -1074,7 +1074,7 @@ debug_panel::update_vehicle_brake() const { { bdelay_M, "+Mg" } }; for( auto const &[delayflag, delayname] : delays ) { - if( ( physics.BrakeDelayFlag & delayflag ) == delayflag ) { + if( ( physics.brakes.delaySetting & delayflag ) == delayflag ) { brakedelay += delayname; } } diff --git a/input/drivermouseinput.cpp b/input/drivermouseinput.cpp index 087365c77..a2b3cc614 100644 --- a/input/drivermouseinput.cpp +++ b/input/drivermouseinput.cpp @@ -73,7 +73,7 @@ mouse_slider::bind( user_command const &Command ) { + 0.5 * ( vehicle->CoupledCtrl ? vehicle->MainCtrlPos + vehicle->ScndCtrlPos : vehicle->MainCtrlPos ) / powerrange - - 0.5 * occupied->LocalBrakePosA; + - 0.5 * occupied->brakes.independentPosition; m_analogue = true; m_invertrange = false; break; @@ -94,14 +94,14 @@ mouse_slider::bind( user_command const &Command ) { } case user_command::trainbrakeset: { m_valuerange = 1.0; - m_value = ( vehicle->fBrakeCtrlPos - vehicle->Handle->GetPos( bh_MIN ) ) / ( vehicle->Handle->GetPos( bh_MAX ) - vehicle->Handle->GetPos( bh_MIN ) ); + m_value = ( vehicle->brakes.handlePositionSmooth - vehicle->brakes.driverValve->GetPos( bh_MIN ) ) / ( vehicle->brakes.driverValve->GetPos( bh_MAX ) - vehicle->brakes.driverValve->GetPos( bh_MIN ) ); m_analogue = true; m_invertrange = true; break; } case user_command::independentbrakeset: { m_valuerange = 1.0; - m_value = vehicle->LocalBrakePosA; + m_value = vehicle->brakes.independentPosition; m_analogue = true; m_invertrange = true; break; diff --git a/input/messaging.cpp b/input/messaging.cpp index f50fde423..f39f20962 100644 --- a/input/messaging.cpp +++ b/input/messaging.cpp @@ -286,7 +286,7 @@ WyslijNamiary([[maybe_unused]] TDynamicObject const *Vehicle) r.fPar[11] = Vehicle->physics->DistCounter; // przejechana odległość w km r.fPar[12] = Vehicle->physics->brakePipe.pressure; // ciśnienie w PG r.fPar[13] = Vehicle->physics->mainPipe.pressure; // ciśnienie w PZ - r.fPar[14] = Vehicle->physics->BrakePress; // ciśnienie w CH + r.fPar[14] = Vehicle->physics->brakes.cylinderPressure; // ciśnienie w CH r.fPar[15] = Vehicle->physics->air.mainReservoirPressure; // ciśnienie w ZG r.fPar[16] = Vehicle->physics->Itot; // Prąd całkowity r.iPar[17] = Vehicle->physics->MainCtrlPos; // Pozycja NJ diff --git a/physics/components/body.cpp b/physics/components/body.cpp index 310925e34..9e84a8da9 100644 --- a/physics/components/body.cpp +++ b/physics/components/body.cpp @@ -101,17 +101,17 @@ physics::Vehicle::Vehicle(double VelInitial, std::string const &TypeNameInit, st for (int b = -1; b <= MainBrakeMaxPos; ++b) { - BrakePressureTable[b].PipePressureVal = 0.0; - BrakePressureTable[b].BrakePressureVal = 0.0; - BrakePressureTable[b].FlowSpeedVal = 0.0; + brakes.pressureTable[b].PipePressureVal = 0.0; + brakes.pressureTable[b].BrakePressureVal = 0.0; + brakes.pressureTable[b].FlowSpeedVal = 0.0; } // with BrakePressureTable[-2] do {pozycja odciecia} { - BrakePressureTable[-2].PipePressureVal = -1.0; - BrakePressureTable[-2].BrakePressureVal = -1.0; - BrakePressureTable[-2].FlowSpeedVal = 0.0; + brakes.pressureTable[-2].PipePressureVal = -1.0; + brakes.pressureTable[-2].BrakePressureVal = -1.0; + brakes.pressureTable[-2].FlowSpeedVal = 0.0; } - for (auto &delay : BrakeDelay) + for (auto &delay : brakes.delays) { delay = 0.0; } @@ -126,7 +126,7 @@ physics::Vehicle::Vehicle(double VelInitial, std::string const &TypeNameInit, st Couplers[b].DmaxC = 0.1; Couplers[b].FmaxC = 1000.0; } - for (auto &cylindermult : BrakeCylMult) + for (auto &cylindermult : brakes.cylinders.leverRatio) { cylindermult = 0.0; } @@ -143,7 +143,7 @@ physics::Vehicle::Vehicle(double VelInitial, std::string const &TypeNameInit, st couplerentry.CheckCollision = false; } - for (auto &brakepress : MaxBrakePress) + for (auto &brakepress : brakes.maxCylinderPressure) { brakepress = 0.0; } @@ -510,12 +510,12 @@ void physics::Vehicle::compute_movement_(double const Deltatime) DynamicBrakeEMUStatus &= Couplers[VehicleEnd::rear].Connected->DynamicBrakeEMUStatus; } - if (BrakeSlippingTimer > 0.8 && ASBType != 128) + if (brakes.antiSlipTimer > 0.8 && brakes.antiSlipType != 128) { // ASBSpeed=0.8 // hamulec antypoślizgowy - wyłączanie - Hamulec->ASB(0); + brakes.distributor->ASB(0); } - BrakeSlippingTimer += Deltatime; + brakes.antiSlipTimer += Deltatime; // automatic doors update_doors(Deltatime); @@ -842,11 +842,11 @@ void physics::Vehicle::ComputeTotalForce(double dt) double old_nrot = abs(nrot); nrot = v2n(); // przeliczenie prędkości liniowej na obrotową - if (true == TestFlag(BrakeMethod, bp_MHS) && brakePipe.pressure < 3.0 // ustawione na sztywno na 3 bar - && Vel > 45 && true == TestFlag(BrakeDelayFlag, bdelay_M)) + if (true == TestFlag(brakes.method, bp_MHS) && brakePipe.pressure < 3.0 // ustawione na sztywno na 3 bar + && Vel > 45 && true == TestFlag(brakes.delaySetting, bdelay_M)) { // doliczenie hamowania hamulcem szynowym - FStand += TrackBrakeForce; + FStand += brakes.trackBrakeForce; } // w charakterystykach jest wartość siły hamowania zamiast nacisku @@ -949,24 +949,24 @@ void physics::Vehicle::ComputeTotalForce(double dt) double physics::Vehicle::BrakeForceR(double ratio, double velocity) const { double press = 0; - ratio = Hamulec->GetBrakeRatio(ratio); - if (MBPM > 2) + ratio = brakes.distributor->GetBrakeRatio(ratio); + if (brakes.maxPressureMass > 2) { - press = MaxBrakePress[1] + (MaxBrakePress[3] - MaxBrakePress[1]) * std::min(1.0, (TotalMass - Mass) / (MBPM - Mass)); + press = brakes.maxCylinderPressure[1] + (brakes.maxCylinderPressure[3] - brakes.maxCylinderPressure[1]) * std::min(1.0, (TotalMass - Mass) / (brakes.maxPressureMass - Mass)); } else { - if (MaxBrakePress[1] > 0.1) + if (brakes.maxCylinderPressure[1] > 0.1) { - press = MaxBrakePress[LoadFlag]; + press = brakes.maxCylinderPressure[brakes.loadSetting]; } else { - press = MaxBrakePress[3]; + press = brakes.maxCylinderPressure[3]; if (DynamicBrakeType == dbrake_automatic) ratio = ratio + (1.5 - ratio) * std::min(1.0, Vel * 0.02); - if (BrakeDelayFlag & bdelay_R && BrakeMethod % 128 != bp_Cosid && BrakeMethod % 128 != bp_D1 && BrakeMethod % 128 != bp_D2 && Power < 1) - ratio *= Hamulec->GetRapidRatio(velocity); + if (brakes.delaySetting & bdelay_R && brakes.method % 128 != bp_Cosid && brakes.method % 128 != bp_D1 && brakes.method % 128 != bp_D2 && Power < 1) + ratio *= brakes.distributor->GetRapidRatio(velocity); if (TrainType == train_type::dmu && velocity < 30.0) { ratio -= 0.3; @@ -979,9 +979,9 @@ double physics::Vehicle::BrakeForceR(double ratio, double velocity) const double physics::Vehicle::BrakeForceP(double press, double velocity) const { double BFP = 0; - double K = ((press * P2FTrans - BrakeCylSpring) * BrakeCylMult[0] - BrakeSlckAdj) * BrakeRigEff; - K *= static_cast(BrakeCylNo) / (NAxles * std::max(1, NBpA)); - BFP = Hamulec->GetFC(velocity, K) * K * (NAxles * std::max(1, NBpA)) * 1000; + double K = ((press * brakes.pressureToForce - brakes.cylinders.springForce) * brakes.cylinders.leverRatio[0] - brakes.cylinders.slackAdjusterForce) * brakes.cylinders.riggingEfficiency; + K *= static_cast(brakes.cylinders.count) / (NAxles * std::max(1, brakes.blocksPerAxle)); + BFP = brakes.distributor->GetFC(velocity, K) * K * (NAxles * std::max(1, brakes.blocksPerAxle)) * 1000; return BFP; } @@ -995,16 +995,16 @@ double physics::Vehicle::BrakeForce(TTrackParam const & /*Track*/) double K{0}; double brakeforce{0}; - switch (LocalBrake) + switch (brakes.localKind) { case TLocalBrake::ManualBrake: { - K = MaxBrakeForce * ManualBrakeRatio(); + K = brakes.maxForce * ManualBrakeRatio(); break; } case TLocalBrake::HydraulicBrake: { - K = MaxBrakeForce * LocalBrakeRatio(); + K = brakes.maxForce * LocalBrakeRatio(); break; } default: @@ -1013,45 +1013,45 @@ double physics::Vehicle::BrakeForce(TTrackParam const & /*Track*/) } } - if (MBrake == true) + if (brakes.hasHandBrake == true) { - K = MaxBrakeForce * ManualBrakeRatio(); + K = brakes.maxForce * ManualBrakeRatio(); } // the spring brake of a vehicle prepared for hauling (PulleeMode) is released by hand: no force, whatever its cylinder has if (brakes.spring.isReady && false == PulleeMode) K += std::max(0.0, brakes.spring.minForcePressure - brakes.spring.cylinder->P()) * brakes.spring.maxForce; - u = (BrakePress * P2FTrans - BrakeCylSpring) * BrakeCylMult[0] - BrakeSlckAdj; - if (u * BrakeRigEff > Ntotal) // histereza na nacisku klockow - Ntotal = u * BrakeRigEff; + u = (brakes.cylinderPressure * brakes.pressureToForce - brakes.cylinders.springForce) * brakes.cylinders.leverRatio[0] - brakes.cylinders.slackAdjusterForce; + if (u * brakes.cylinders.riggingEfficiency > Ntotal) // histereza na nacisku klockow + Ntotal = u * brakes.cylinders.riggingEfficiency; else { - u = (BrakePress * P2FTrans - BrakeCylSpring) * BrakeCylMult[0] - BrakeSlckAdj; - if (u * (2.0 - BrakeRigEff) < Ntotal) // histereza na nacisku klockow - Ntotal = u * (2.0 - BrakeRigEff); + u = (brakes.cylinderPressure * brakes.pressureToForce - brakes.cylinders.springForce) * brakes.cylinders.leverRatio[0] - brakes.cylinders.slackAdjusterForce; + if (u * (2.0 - brakes.cylinders.riggingEfficiency) < Ntotal) // histereza na nacisku klockow + Ntotal = u * (2.0 - brakes.cylinders.riggingEfficiency); } auto const NBrakeAxles{NAxles}; - if (NBrakeAxles * NBpA > 0) + if (NBrakeAxles * brakes.blocksPerAxle > 0) { if (Ntotal > 0) // nie luz K += Ntotal; // w kN - K *= static_cast(BrakeCylNo) / (NBrakeAxles * static_cast(NBpA)); // w kN na os + K *= static_cast(brakes.cylinders.count) / (NBrakeAxles * static_cast(brakes.blocksPerAxle)); // w kN na os } - if (BrakeSystem == TBrakeSystem::Pneumatic || BrakeSystem == TBrakeSystem::ElectroPneumatic) + if (brakes.kind == TBrakeSystem::Pneumatic || brakes.kind == TBrakeSystem::ElectroPneumatic) { - u = Hamulec->GetFC(Vel, K); - UnitBrakeForce = u * K * 1000.0; // sila na jeden klocek w N + u = brakes.distributor->GetFC(Vel, K); + brakes.unitForce = u * K * 1000.0; // sila na jeden klocek w N } else - UnitBrakeForce = K * 1000.0; + brakes.unitForce = K * 1000.0; // if (LocalBrake=ManualBrake)or(MBrake=true)) and (BrakePress<0.3) then // Fb:=UnitBrakeForce*NBpA {ham. reczny dziala na jedna os} // else //yB: to nie do konca ma sens, ponieważ ręczny w wagonie działa na jeden cylinder // hamulcowy/wózek, dlatego potrzebne są oddzielnie liczone osie - brakeforce = UnitBrakeForce * NBrakeAxles * std::max(1, NBpA); + brakeforce = brakes.unitForce * NBrakeAxles * std::max(1, brakes.blocksPerAxle); // u:=((BrakePress*P2FTrans)-BrakeCylSpring*BrakeCylMult[BCMFlag]/BrakeCylNo-0.83*BrakeSlckAdj/(BrakeCylNo))*BrakeCylNo; // { end; } @@ -1247,7 +1247,7 @@ bool physics::Vehicle::accelerating() const // brake cylinders still fill or release isn't held yet: asleep, it would keep the brake force (and the pressure the AI waits on // to set off) it had when it fell asleep. 0.05 bar/s is less than a distributor moves the cylinder when it applies or releases, and // more than the leaks take - auto const held{Global.physics_sleepheld && Vel <= 0.0001 && std::abs(FStand) > std::abs(FTrain) && BrakePressRate <= 0.05}; + auto const held{Global.physics_sleepheld && Vel <= 0.0001 && std::abs(FStand) > std::abs(FTrain) && brakes.cylinderPressureRate <= 0.05}; return false == held; } @@ -1273,8 +1273,8 @@ bool physics::Vehicle::brakes_changed_asleep() const if (PhysicActivation) return false; constexpr double pressure_change{0.05}; // [bar] - return std::abs(BrakePress - sleep_brakes.cylinder) > pressure_change || std::abs(brakes.spring.pressure - sleep_brakes.spring) > pressure_change || - ManualBrakePos != sleep_brakes.manual || std::abs(LocalBrakePosA - sleep_brakes.local) > 0.01; + return std::abs(brakes.cylinderPressure - sleep_brakes.cylinder) > pressure_change || std::abs(brakes.spring.pressure - sleep_brakes.spring) > pressure_change || + brakes.handBrakePosition != sleep_brakes.manual || std::abs(brakes.independentPosition - sleep_brakes.local) > 0.01; } // ************************************************************************************************* @@ -1296,7 +1296,7 @@ bool physics::Vehicle::switch_physics(bool const State, wake_cause const Cause) else { // what the brake force of the last step came from, which it keeps while asleep (brakes_changed_asleep()) - sleep_brakes = {BrakePress, brakes.spring.pressure, ManualBrakePos, LocalBrakePosA}; + sleep_brakes = {brakes.cylinderPressure, brakes.spring.pressure, brakes.handBrakePosition, brakes.independentPosition}; } return true; diff --git a/physics/components/braking.h b/physics/components/braking.h index c78bb262c..43865134c 100644 --- a/physics/components/braking.h +++ b/physics/components/braking.h @@ -7,14 +7,20 @@ obtain one at http://mozilla.org/MPL/2.0/. */ -// the braking of a vehicle beside its air brake valves: the blending of the brakes of a unit, the holding brake, the -// spring brake. Held by physics::Vehicle as brakes +// the braking of a vehicle: its brake valves and cylinders, the handles of the driver, the blending of the brakes of a +// unit, the holding brake, the spring brake. Held by physics::Vehicle as brakes #pragma once +#include #include +#include + +#include "physics/vehicletypes.h" class TReservoir; +class TBrake; +class TDriverHandle; namespace physics { @@ -88,8 +94,127 @@ struct SpringBrake }; // the braking of a vehicle beside its air brake valves +// the settings of the driver's brake valve (the Handle_* keys of the .fiz) +struct DriverValveSettings +{ + bool automaticOverload = false; // the overcharge is let in automatically at the filling position + bool manualOverload = false; // the overcharge is let in by a button + double genericParameter1 = 0.0; + double genericParameter2 = 0.0; + double overloadMaxPressure = 1.0; // the most the overcharge raises the pressure + double overloadPressureDecrease = 0.002; // how fast the pressure of the overcharge falls +}; + +// the brake cylinders of a vehicle and their rigging +struct BrakeCylinders +{ + int count = 0; + double radius = 0.0; + double stroke = 0.0; + std::array leverRatio{}; // the ratio of the brake rigging, by the load setting + double springForce = 0.0; // the sum of the forces of the return springs [kN] + double slackAdjusterForce = 0.0; // the resistance of the slack adjuster [kN] + double riggingEfficiency = 0.0; // the efficiency of the lever rigging +}; + +// the emergency valve, which lets the air out of the main reservoir above its pressure +struct EmergencyValve +{ + double onPressure = 0.0; // MaxEVP: it opens above this pressure of the main reservoir + double offPressure = 0.0; // MinEVP: it closes again below this one + bool open = false; + double area = 0.0; // EVArea + double flow = 0.0; // the air through it in the last step +}; + +// the lock of the brake pipe in an emergency application +struct PipeLock +{ + double onPressure = -1.0; // LPOn + double offPressure = -1.0; // LPOff + double unlockHandlePosition = -3.0; // HandlePipeUnlockPos: the position of the driver's valve that unlocks it + bool locked = false; + bool unlockPressed = false; // the button that unlocks it pressed +}; + +// the braking of a vehicle struct Braking { + // the valves + std::shared_ptr distributor; // the brake valve of the vehicle with its reservoirs and cylinders + std::shared_ptr driverValve; // the driver's brake valve of the train brake + std::shared_ptr independentValve; // the driver's valve of the independent brake + + // the definition + TBrakeSystem kind = TBrakeSystem::Individual; // the kind of the train brake + TBrakeSubSystem subsystem = TBrakeSubSystem::ss_None; + TBrakeValve distributorType = TBrakeValve::NoValve; + int distributorSize = 0; + std::string distributorParameters; + TBrakeHandle driverValveType = TBrakeHandle::NoHandle; + TBrakeHandle independentValveType = TBrakeHandle::NoHandle; + bool independentTraxx = false; // the independent brake of the Traxx kind + DriverValveSettings driverValveSettings; + TLocalBrake localKind = TLocalBrake::NoBrake; // the kind of the individual brake + TBrakePressureTable pressureTable; // the pressures in the pipe of the positions of the driver's valve + TBrakePressure actualPressure; // their values weighted for the present position of the valve + int antiSlipType = 0; // 0: no anti-slip brake, 1: by hand, 2: automatic + std::array universalButtonActions{}; // what the universal brake buttons do + std::array universalButtonPressed{}; // the universal brake buttons pressed + double maxForce = 0.0; // the most force of the brake + std::array maxCylinderPressure{}; // by the load setting: auxiliary, empty, medium, loaded, anti-slip + int loadSetting = 0; // the index of maxCylinderPressure the brake takes + double pressureToForce = 0.0; // P2FTrans + double trackBrakeForce = 0.0; // the force of the track brake + int method = 0; // the friction material and its flags (bp_*) + int blocksPerAxle = 0; // NBpA: 0, 1, 2 or 4 + double maxPressureMass = 1.0; // MBPM: the mass of the highest pressure + double pipeHighPressure = 0.0; // the highest working pressure of the brake pipe + double pipeLowPressure = 0.0; // the lowest one + double pipePressureRange = 0.0; // the difference between them + double controlReservoirPressure = 0.0; // the pressure in the control reservoir + double cylinderVolume = 0.0; // the volume of the brake cylinders + double valveVolume = 0.0; // BVV + BrakeCylinders cylinders; + double rapidRatio = 1.0; // the ratio of the rapid brake + double rapidSpeed = 55.0; // the speed the rapid brake switches at + double pipeSection = 0.0; // Spg: the cross-section of the brake pipe + EmergencyValve emergencyValve; + PipeLock pipeLock; + bool emergencyCutsOffDriverValve = false; // EmergencyCutsOffHandle + TBrakeDelayTable delays; // the delays of applying and releasing + int handlePositions = 0; // the positions of the driver's valve + bool hasHandBrake = false; + + // the state + double cylinderPressure = 0.0; // the pressure in the brake cylinders + double cylinderPressureRate = 0.0; // how fast it changes, averaged over about a second [bar/s], see accelerating() + double independentCylinderPressure = 0.0; // the pressure in the cylinders from the independent brake + double pipeCylinderPressure = 0.0; // the pressure in the cylinders from the brake pipe + double equivalentPipePressure = 0.0; // the pressure of the brake pipe of the consist + double pipeLimiterPressure = 0.0; // the pressure the stabiliser holds + double reservoirAir = 0.0; // the compressed air in the brake reservoir + double brakeFlow = 0.0; // the air of the step: into the cylinders, + double pipeFlow = 0.0; // of the brake pipe, + double driverValveFlow = 0.0; // through the driver's valve, + double independentValveFlow = 0.0; // through the valve of the independent brake + int handlePosition = -2; // the position of the driver's valve + double handlePositionReal = 0.0; // the same, continuous, of the FV4a + double handleCapPosition = 0.0; // the cap of the FV4a + double handlePositionSmooth = -2.0; // the continuous position of the driver's valve + double independentPosition = 0.0; // the position of the independent brake + double independentPositionEim = 0.0; // the position of the EP independent brake of the asynchronous EMUs + int handBrakePosition = 0; + int status = 0; // the bits b_* (b_off 0, b_on, b_dmg, b_rls, b_asb, b_ep ...) + bool alarmChain = false; // the manual emergency brake + int delaySetting = 0; // the delay set (bdelay_*) + int availableDelays = 0; // the delays it can be set to + bool cutOutByInspector = false; + int operatingMode = 0; // the mode set (bom_*: PS/PN/EP/MED 1/2/4/8) + int availableOperatingModes = 0; + double unitForce = 0.0; // the braking force of one braked element + double antiSlipTimer = 0.0; // to switch the anti-slip brake off + BrakeBlending blending; EmuDynamicBrake emuDynamic; HoldingBrake holding; diff --git a/physics/components/cab.cpp b/physics/components/cab.cpp index c8f0addf1..09716282c 100644 --- a/physics/components/cab.cpp +++ b/physics/components/cab.cpp @@ -54,14 +54,14 @@ bool physics::Vehicle::ChangeCab(int direction) if (std::abs(CabOccupied + direction) < 2) { CabOccupied = CabOccupied + direction; - if (BrakeCtrlPosNo > 0 && (BrakeSystem == TBrakeSystem::Pneumatic || BrakeSystem == TBrakeSystem::ElectroPneumatic)) + if (brakes.handlePositions > 0 && (brakes.kind == TBrakeSystem::Pneumatic || brakes.kind == TBrakeSystem::ElectroPneumatic)) { - BrakeLevelSet(Handle->GetPos(bh_NP)); - LimPipePress = brakePipe.pressure; + BrakeLevelSet(brakes.driverValve->GetPos(bh_NP)); + brakes.pipeLimiterPressure = brakePipe.pressure; ActFlowSpeed = 0; } else - BrakeLevelSet(Handle->GetPos(bh_NP)); + BrakeLevelSet(brakes.driverValve->GetPos(bh_NP)); MainCtrlPos = MainCtrlNoPowerPos(); ScndCtrlPos = 0; return true; diff --git a/physics/components/collisions.cpp b/physics/components/collisions.cpp index eeb711535..55e93944b 100644 --- a/physics/components/collisions.cpp +++ b/physics/components/collisions.cpp @@ -59,7 +59,7 @@ void tear_brake_hoses(physics::Vehicle &Vehicle) { if (std::any_of(std::begin(Vehicle.Couplers), std::end(Vehicle.Couplers), [](auto const &Coupler) { return Coupler.CouplingFlag.HasAll(Coupling::brakeHose); })) { - Vehicle.AlarmChainFlag = true; + Vehicle.brakes.alarmChain = true; } } @@ -205,7 +205,7 @@ void physics::Vehicle::damage_coupler(VehicleEnd const End) if (hosetorn) { // hamowanie nagle - zerwanie przewodow hamulcowych - AlarmChainFlag = true; + brakes.alarmChain = true; } thiscoupler.CouplingFlag = {}; @@ -222,7 +222,7 @@ void physics::Vehicle::damage_coupler(VehicleEnd const End) if (hosetorn && coupler_physics_at(End)) { // the brake pipe of the other part of the train vents through the torn hose as well - thiscoupler.Connected->AlarmChainFlag = true; + thiscoupler.Connected->brakes.alarmChain = true; } } @@ -512,7 +512,7 @@ bool physics::Vehicle::crush_hit(VehicleEnd const End, double const dt) damage_coupler(End); if (hose) { - othervehicle->AlarmChainFlag = true; + othervehicle->brakes.alarmChain = true; } } else if (thiscoupler.CouplingFlag == Coupling::none) @@ -647,7 +647,7 @@ void repair(physics::Vehicle &Vehicle, TCoupling &Coupler) } Vehicle.DamageFlag.Clear(VehicleDamage::coupling); // either vehicle of the pair may have been braking through the torn hose - Vehicle.AlarmChainFlag = false; + Vehicle.brakes.alarmChain = false; } } // namespace @@ -790,7 +790,7 @@ void physics::Vehicle::repair_damage() DamageFlag = {}; EngDmgFlag = 0; WheelFlat = 0.0; - AlarmChainFlag = false; + brakes.alarmChain = false; // the crushed ends rebuilt for (auto &coupler : Couplers) { diff --git a/physics/components/commands.cpp b/physics/components/commands.cpp index 7f94808d4..51b577a2b 100644 --- a/physics/components/commands.cpp +++ b/physics/components/commands.cpp @@ -279,13 +279,13 @@ bool physics::Vehicle::RunBrakeCommand(VehicleCommand const Command, double CVal temp1 = 0; if (brakes.emuDynamic.epMinCurrent > 0.001 && abs(Im) > brakes.emuDynamic.epMinCurrent && DynamicBrakeEMUStatus) temp1 = 0; - Hamulec->SetEPS(temp1); + brakes.distributor->SetEPS(temp1); TUHEX_StageActual = static_cast(CValue1); TUHEX_Active = TUHEX_StageActual > 0; if (CValue1 < 0.001) DynamicBrakeEMUStatus = true; // fBrakeCtrlPos:=BrakeCtrlPos; //to powinnno być w jednym miejscu, aktualnie w C++!!! - BrakePressureActual = BrakePressureTable[BrakeCtrlPos]; + brakes.actualPressure = brakes.pressureTable[brakes.handlePosition]; OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } // youby - odluzniacz hamulcow, przyda sie else if (Command == VehicleCommand::brakeReleaser) @@ -312,9 +312,9 @@ bool physics::Vehicle::RunBrakeEquipmentCommand(VehicleCommand const Command, do { if (Command == VehicleCommand::brakeDelay) { - if (auto const brakesetting = static_cast(std::floor(CValue1)); true == Hamulec->SetBDF(brakesetting)) + if (auto const brakesetting = static_cast(std::floor(CValue1)); true == brakes.distributor->SetBDF(brakesetting)) { - BrakeDelayFlag = brakesetting; + brakes.delaySetting = brakesetting; OK = true; } else diff --git a/physics/components/controllers.cpp b/physics/components/controllers.cpp index f8d7315fc..d68f39594 100644 --- a/physics/components/controllers.cpp +++ b/physics/components/controllers.cpp @@ -894,7 +894,7 @@ bool physics::Vehicle::MotorConnectorsCheck() // hunter-111211: wylacznik cisnieniowy // (on some vehicles it watches the brake pipe alone) - ControlPressureSwitch = HasControlPressureSwitch && ((PressureSwitchBrakeCylinder && BrakePress > 2.0) || brakePipe.pressure < 3.6); + ControlPressureSwitch = HasControlPressureSwitch && ((PressureSwitchBrakeCylinder && brakes.cylinderPressure > 2.0) || brakePipe.pressure < 3.6); if (true == ControlPressureSwitch) { @@ -1025,7 +1025,7 @@ void physics::Vehicle::CheckEIMIC(double dt) EIMICFromUniversalController(dt, brakeDemand); break; } - if (LocHandleTimeTraxx) + if (brakes.independentTraxx) { EIMICTraxxLocalBrake(dt); } @@ -1041,7 +1041,7 @@ void physics::Vehicle::EIMICFromController(double const brakeDemand, double cons { if (eimic > 0.001) eimic = std::max(0.002, eimic * (double)MainCtrlPosNo / ((double)MainCtrlPosNo - offset) - offset / ((double)MainCtrlPosNo - offset)); - if (eimic < -0.001 && BrakeHandle != TBrakeHandle::MHZ_EN57) + if (eimic < -0.001 && brakes.driverValveType != TBrakeHandle::MHZ_EN57) eimic = std::min(-0.002, eimic * (double)LocalBrakePosNo / ((double)LocalBrakePosNo - multiplier) + offset / ((double)LocalBrakePosNo - multiplier)); } if (eimic > 0.001 && SpeedCtrlUnit.IsActive) @@ -1154,7 +1154,7 @@ void physics::Vehicle::EIMICFromUniversalController(double dt, double const brak LastRelayTime = 0; MainCtrlActualPos = MainCtrlPos; } - if (Hamulec->GetEDBCP() > 0.3 && eimic < 0 && !UniCtrlIntegratedLocalBrakeCtrl) // when braking with pneumatic brake + if (brakes.distributor->GetEDBCP() > 0.3 && eimic < 0 && !UniCtrlIntegratedLocalBrakeCtrl) // when braking with pneumatic brake eimic = 0; // shut off retarder if (UniCtrlIntegratedBrakeCtrl == false && UniCtrlIntegratedLocalBrakeCtrl == false) { @@ -1168,17 +1168,17 @@ void physics::Vehicle::EIMICFromUniversalController(double dt, double const brak // controller, at a brake handle moved alone, to the nearest position of the handle's void physics::Vehicle::UniversalControllerTrainBrake() { - if (UniCtrlList[MainCtrlPos].mode != BrakeCtrlPos && MainCtrlActualPos == MainCtrlPos) // there was no move of controller, but brake only + if (UniCtrlList[MainCtrlPos].mode != brakes.handlePosition && MainCtrlActualPos == MainCtrlPos) // there was no move of controller, but brake only { - if (BrakeCtrlPos < UniCtrlList[MainCtrlPosNo].mode) + if (brakes.handlePosition < UniCtrlList[MainCtrlPosNo].mode) BrakeLevelSet(UniCtrlList[MainCtrlPosNo].mode); // bottom clamping - if (BrakeCtrlPos > UniCtrlList[0].mode) + if (brakes.handlePosition > UniCtrlList[0].mode) BrakeLevelSet(UniCtrlList[0].mode); // top clamping if (IsCabMaster()) { - while (BrakeCtrlPos > UniCtrlList[MainCtrlPos].mode) + while (brakes.handlePosition > UniCtrlList[MainCtrlPos].mode) DecMainCtrl(1); // find nearest position - while (BrakeCtrlPos < UniCtrlList[MainCtrlPos].mode) + while (brakes.handlePosition < UniCtrlList[MainCtrlPos].mode) IncMainCtrl(1); // find nearest position } } @@ -1197,11 +1197,11 @@ void physics::Vehicle::EIMICTraxxLocalBrake(double dt) if (LocalBrakeRatio() > 0.6) // pozycja 2, zahamowywanie { eim_localbrake += dt * 0.17; - eim_localbrake = std::max(eim_localbrake, BrakePress / MaxBrakePress[0]); + eim_localbrake = std::max(eim_localbrake, brakes.cylinderPressure / brakes.maxCylinderPressure[0]); } else // pozycja 1, utrzymanie cisnienia { - if (eim_localbrake < Hamulec->GetEDBCP() / MaxBrakePress[0]) + if (eim_localbrake < brakes.distributor->GetEDBCP() / brakes.maxCylinderPressure[0]) eim_localbrake = 0; } eim_localbrake = std::clamp(eim_localbrake, 0.0, 1.0); @@ -1212,7 +1212,7 @@ void physics::Vehicle::EIMICTraxxLocalBrake(double dt) // the value limited by the power, the spring brake, the pipe lock, the direction and the doors' permits void physics::Vehicle::EIMICLimit() { - auto const eimicpowerenabled{(MainCircuitPowered() || Power == 0.0) && (!brakes.spring.isActive || !brakes.spring.cutsOffDrive) && !LockPipe && DirAbsolute != 0}; + auto const eimicpowerenabled{(MainCircuitPowered() || Power == 0.0) && (!brakes.spring.isActive || !brakes.spring.cutsOffDrive) && !brakes.pipeLock.locked && DirAbsolute != 0}; auto const eimicdoorenabled{(brakes.spring.isActive && brakes.spring.releasesParkingWithDoorOpen)}; double eimic_max = 0.0; if (Doors.instances[VehicleSide::left].open_permit == false && Doors.instances[VehicleSide::right].open_permit == false) @@ -1253,7 +1253,7 @@ void physics::Vehicle::CheckSpeedCtrl(double dt) { SpeedCtrlUnit.Standby = false; } - if (!SpeedCtrlUnit.BrakeIntervention && (Hamulec->GetEDBCP() > 0.4 || brakePipe.pressure < HighPipePress - 0.2)) + if (!SpeedCtrlUnit.BrakeIntervention && (brakes.distributor->GetEDBCP() > 0.4 || brakePipe.pressure < brakes.pipeHighPressure - 0.2)) SpeedCtrlUnit.Standby = true; if (EIMCtrlType >= 3 && UniCtrlList[MainCtrlPos].SpeedUp <= 0) { @@ -1284,7 +1284,7 @@ void physics::Vehicle::CheckSpeedCtrl(double dt) else eimicSpeedCtrl = std::clamp(0.5 * (SpeedCtrlValue * 2 - Vel), -1.0, 1.0); } - if ((SpeedCtrlAutoTurnOffFlag & 2) == 2 && Hamulec->GetEDBCP() > 0.25) + if ((SpeedCtrlAutoTurnOffFlag & 2) == 2 && brakes.distributor->GetEDBCP() > 0.25) { SpeedCtrlSwitch(false); SpeedCtrlUnit.IsActive = false; diff --git a/physics/components/diesel.cpp b/physics/components/diesel.cpp index 034a11793..c80ecd863 100644 --- a/physics/components/diesel.cpp +++ b/physics/components/diesel.cpp @@ -622,7 +622,7 @@ void physics::Vehicle::update_dieselelectric_dynamic_brake(double const dt) if (brake.blending) { // the train brake of the locomotive lets off by the share of the dynamic brake's force (LSt, EStED) - Hamulec->SetED(brake.max_force > 0.0 ? brake.force / brake.max_force : 0.0); + brakes.distributor->SetED(brake.max_force > 0.0 ? brake.force / brake.max_force : 0.0); } } diff --git a/physics/components/electrics.cpp b/physics/components/electrics.cpp index d533a1c7d..c33e2e0c8 100644 --- a/physics/components/electrics.cpp +++ b/physics/components/electrics.cpp @@ -76,7 +76,7 @@ void physics::Vehicle::UpdatePantVolume(double dt) } else { // a tu coś dla SM42 i SM31, aby pokazywać na manometrze - PantPress = CntrlPipePress; + PantPress = brakes.controlReservoirPressure; } }; diff --git a/physics/components/fizparser.cpp b/physics/components/fizparser.cpp index 6b688fa68..ca86e3de5 100644 --- a/physics/components/fizparser.cpp +++ b/physics/components/fizparser.cpp @@ -231,18 +231,18 @@ bool physics::Vehicle::readBPT(std::string const &line) std::string braketype; int idx = 0; parser >> idx; - parser >> BrakePressureTable[idx].PipePressureVal >> BrakePressureTable[idx].BrakePressureVal >> BrakePressureTable[idx].FlowSpeedVal >> braketype; + parser >> brakes.pressureTable[idx].PipePressureVal >> brakes.pressureTable[idx].BrakePressureVal >> brakes.pressureTable[idx].FlowSpeedVal >> braketype; if (braketype == "Pneumatic") { - BrakePressureTable[idx].BrakeType = TBrakeSystem::Pneumatic; + brakes.pressureTable[idx].BrakeType = TBrakeSystem::Pneumatic; } else if (braketype == "ElectroPneumatic") { - BrakePressureTable[idx].BrakeType = TBrakeSystem::ElectroPneumatic; + brakes.pressureTable[idx].BrakeType = TBrakeSystem::ElectroPneumatic; } else { - BrakePressureTable[idx].BrakeType = TBrakeSystem::Individual; + brakes.pressureTable[idx].BrakeType = TBrakeSystem::Individual; } return true; @@ -587,12 +587,12 @@ void physics::Vehicle::BrakeValveDecode(std::string const &Valve) {"CV1", CV1}, {"CV1_R", CV1_R}}; auto lookup = valvetypes.find(Valve); - BrakeValve = lookup != valvetypes.end() ? lookup->second : Other; + brakes.distributorType = lookup != valvetypes.end() ? lookup->second : Other; - if (BrakeValve == Other && contains(Valve, "ESt")) + if (brakes.distributorType == Other && contains(Valve, "ESt")) { - BrakeValve = ESt3; + brakes.distributorType = ESt3; } } @@ -602,33 +602,33 @@ void physics::Vehicle::BrakeValveDecode(std::string const &Valve) void physics::Vehicle::BrakeSubsystemDecode() { using enum TBrakeSubSystem; - BrakeSubsystem = ss_None; - switch (BrakeValve) + brakes.subsystem = ss_None; + switch (brakes.distributorType) { using enum TBrakeValve; case W: case W_Lu_L: case W_Lu_VI: case W_Lu_XR: - BrakeSubsystem = ss_W; + brakes.subsystem = ss_W; break; case ESt3: case ESt3AL2: case ESt4: case EP2: case EP1: - BrakeSubsystem = ss_ESt; + brakes.subsystem = ss_ESt; break; case KE: - BrakeSubsystem = ss_KE; + brakes.subsystem = ss_KE; break; case CV1: case CV1_L_TR: - BrakeSubsystem = ss_Dako; + brakes.subsystem = ss_Dako; break; case LSt: case EStED: - BrakeSubsystem = ss_LSt; + brakes.subsystem = ss_LSt; break; default: break; diff --git a/physics/components/fizsections.cpp b/physics/components/fizsections.cpp index 882086abb..8eff86951 100644 --- a/physics/components/fizsections.cpp +++ b/physics/components/fizsections.cpp @@ -209,87 +209,87 @@ void physics::Vehicle::LoadFIZ_Wheels(std::string const &line) void physics::Vehicle::LoadFIZ_Brake(std::string const &line) { - extract_value(BrakeValveParams, "BrakeValve", line, ""); - BrakeValveDecode(BrakeValveParams); + extract_value(brakes.distributorParameters, "BrakeValve", line, ""); + BrakeValveDecode(brakes.distributorParameters); BrakeSubsystemDecode(); - extract_value(NBpA, "NBpA", line, ""); - extract_value(MaxBrakeForce, "MBF", line, ""); - extract_value(BrakeValveSize, "Size", line, ""); - extract_value(TrackBrakeForce, "TBF", line, ""); - TrackBrakeForce *= 1000.0; + extract_value(brakes.blocksPerAxle, "NBpA", line, ""); + extract_value(brakes.maxForce, "MBF", line, ""); + extract_value(brakes.distributorSize, "Size", line, ""); + extract_value(brakes.trackBrakeForce, "TBF", line, ""); + brakes.trackBrakeForce *= 1000.0; - extract_value(MaxBrakePress[3], "MaxBP", line, ""); - if (MaxBrakePress[3] > 0.0) + extract_value(brakes.maxCylinderPressure[3], "MaxBP", line, ""); + if (brakes.maxCylinderPressure[3] > 0.0) { - extract_value(BrakeCylNo, "BCN", line, ""); - if (BrakeCylNo > 0) + extract_value(brakes.cylinders.count, "BCN", line, ""); + if (brakes.cylinders.count > 0) { - extract_value(MaxBrakePress[0], "MaxLBP", line, ""); - if (MaxBrakePress[0] < 0.01) + extract_value(brakes.maxCylinderPressure[0], "MaxLBP", line, ""); + if (brakes.maxCylinderPressure[0] < 0.01) { - MaxBrakePress[0] = MaxBrakePress[3]; + brakes.maxCylinderPressure[0] = brakes.maxCylinderPressure[3]; } - extract_value(MaxBrakePress[1], "TareMaxBP", line, ""); - extract_value(MaxBrakePress[2], "MedMaxBP", line, ""); - extract_value(MaxBrakePress[4], "MaxASBP", line, ""); - if (MaxBrakePress[4] < 0.01) + extract_value(brakes.maxCylinderPressure[1], "TareMaxBP", line, ""); + extract_value(brakes.maxCylinderPressure[2], "MedMaxBP", line, ""); + extract_value(brakes.maxCylinderPressure[4], "MaxASBP", line, ""); + if (brakes.maxCylinderPressure[4] < 0.01) { - MaxBrakePress[4] = 0.0; + brakes.maxCylinderPressure[4] = 0.0; } - extract_value(BrakeCylRadius, "BCR", line, ""); - extract_value(BrakeCylDist, "BCD", line, ""); - extract_value(BrakeCylSpring, "BCS", line, ""); - extract_value(BrakeSlckAdj, "BSA", line, ""); - extract_value(BrakeRigEff, "BRE", line, "1"); + extract_value(brakes.cylinders.radius, "BCR", line, ""); + extract_value(brakes.cylinders.stroke, "BCD", line, ""); + extract_value(brakes.cylinders.springForce, "BCS", line, ""); + extract_value(brakes.cylinders.slackAdjusterForce, "BSA", line, ""); + extract_value(brakes.cylinders.riggingEfficiency, "BRE", line, "1"); - extract_value(BrakeCylMult[0], "BCM", line, ""); - extract_value(BrakeCylMult[1], "BCMlo", line, ""); - extract_value(BrakeCylMult[2], "BCMHi", line, ""); + extract_value(brakes.cylinders.leverRatio[0], "BCM", line, ""); + extract_value(brakes.cylinders.leverRatio[1], "BCMlo", line, ""); + extract_value(brakes.cylinders.leverRatio[2], "BCMHi", line, ""); - P2FTrans = 100 * M_PI * std::pow(BrakeCylRadius, 2); // w kN/bar + brakes.pressureToForce = 100 * M_PI * std::pow(brakes.cylinders.radius, 2); // w kN/bar - if (BrakeCylMult[1] > 0.0 || MaxBrakePress[1] > 0.0) + if (brakes.cylinders.leverRatio[1] > 0.0 || brakes.maxCylinderPressure[1] > 0.0) { - LoadFlag = 1; + brakes.loadSetting = 1; } else { - LoadFlag = 0; + brakes.loadSetting = 0; } - BrakeVolume = M_PI * std::pow(BrakeCylRadius, 2) * BrakeCylDist * BrakeCylNo; - extract_value(BrakeVVolume, "BVV", line, ""); + brakes.cylinderVolume = M_PI * std::pow(brakes.cylinders.radius, 2) * brakes.cylinders.stroke * brakes.cylinders.count; + extract_value(brakes.valveVolume, "BVV", line, ""); { std::map> brakemethods{{"P10-Bg", bp_P10Bg}, {"P10-Bgu", bp_P10Bgu}, {"FR513", bp_FR513}, {"FR510", bp_FR510}, {"Cosid", bp_Cosid}, {"P10yBg", bp_P10yBg}, {"P10yBgu", bp_P10yBgu}, {"Disk1", bp_D1}, {"Disk1+Mg", bp_D1 + bp_MHS}, {"Disk2", bp_D2}}; auto lookup = brakemethods.find(extract_value("BM", line)); - BrakeMethod = lookup != brakemethods.end() ? lookup->second : 0; + brakes.method = lookup != brakemethods.end() ? lookup->second : 0; } - extract_value(RapidMult, "RM", line, "1"); - extract_value(RapidVel, "RV", line, "55"); + extract_value(brakes.rapidRatio, "RM", line, "1"); + extract_value(brakes.rapidSpeed, "RV", line, "55"); } } else { // maxbrakepress[3] == 0 or less - P2FTrans = 0; + brakes.pressureToForce = 0; } // Ra 2014-07: trochę niedokładności // the draws are sequenced: the order of the operands of '-' is unspecified, and GCC and MSVC draw them the other way round auto const firstdraw{Random(10)}; - CntrlPipePress = 5 + 0.001 * (Random(10) - firstdraw); - extract_value(CntrlPipePress, "HiPP", line, ""); - HighPipePress = CntrlPipePress; - LowPipePress = std::min(HighPipePress, 3.5); - extract_value(LowPipePress, "LoPP", line, ""); - DeltaPipePress = HighPipePress - LowPipePress; + brakes.controlReservoirPressure = 5 + 0.001 * (Random(10) - firstdraw); + extract_value(brakes.controlReservoirPressure, "HiPP", line, ""); + brakes.pipeHighPressure = brakes.controlReservoirPressure; + brakes.pipeLowPressure = std::min(brakes.pipeHighPressure, 3.5); + extract_value(brakes.pipeLowPressure, "LoPP", line, ""); + brakes.pipePressureRange = brakes.pipeHighPressure - brakes.pipeLowPressure; extract_value(air.mainReservoirVolume, "Vv", line, ""); /* @@ -301,16 +301,16 @@ void physics::Vehicle::LoadFIZ_Brake(std::string const &line) extract_value(air.compressor.maxPressureCabB, "MaxCP_B", line, ""); extract_value(air.compressor.tankValve, "CompressorTankValve", line, ""); extract_value(air.compressor.speed, "CompressorSpeed", line, ""); - extract_value(EmergencyValveOff, "MinEVP", line, ""); - extract_value(EmergencyValveOn, "MaxEVP", line, ""); - extract_value(EmergencyValveArea, "EVArea", line, ""); - extract_value(UniversalBrakeButtonFlag[0], "UBB1", line, ""); - extract_value(UniversalBrakeButtonFlag[1], "UBB2", line, ""); - extract_value(UniversalBrakeButtonFlag[2], "UBB3", line, ""); - extract_value(LockPipeOn, "LPOn", line, "-1"); - extract_value(LockPipeOff, "LPOff", line, "-1"); - extract_value(HandleUnlock, "HandlePipeUnlockPos", line, "-3"); - extract_value(EmergencyCutsOffHandle, "EmergencyCutsOffHandle", line, ""); + extract_value(brakes.emergencyValve.offPressure, "MinEVP", line, ""); + extract_value(brakes.emergencyValve.onPressure, "MaxEVP", line, ""); + extract_value(brakes.emergencyValve.area, "EVArea", line, ""); + extract_value(brakes.universalButtonActions[0], "UBB1", line, ""); + extract_value(brakes.universalButtonActions[1], "UBB2", line, ""); + extract_value(brakes.universalButtonActions[2], "UBB3", line, ""); + extract_value(brakes.pipeLock.onPressure, "LPOn", line, "-1"); + extract_value(brakes.pipeLock.offPressure, "LPOff", line, "-1"); + extract_value(brakes.pipeLock.unlockHandlePosition, "HandlePipeUnlockPos", line, "-3"); + extract_value(brakes.emergencyCutsOffDriverValve, "EmergencyCutsOffHandle", line, ""); { using enum CompressorSupply; std::map> compressorpowers{ @@ -691,9 +691,9 @@ void physics::Vehicle::LoadFIZ_CntrlBrakes(std::string const &line) using enum TBrakeSystem; std::map> brakesystems{{"Pneumatic", Pneumatic}, {"ElectroPneumatic", ElectroPneumatic}}; auto lookup = brakesystems.find(extract_value("BrakeSystem", line)); - BrakeSystem = lookup != brakesystems.end() ? lookup->second : Individual; + brakes.kind = lookup != brakesystems.end() ? lookup->second : Individual; } - if (BrakeSystem != TBrakeSystem::Individual) + if (brakes.kind != TBrakeSystem::Individual) { LoadFIZ_CntrlTrainBrake(line); } // brakesystem != individual @@ -703,10 +703,10 @@ void physics::Vehicle::LoadFIZ_CntrlBrakes(std::string const &line) using enum TLocalBrake; std::map> localbrakes{{"ManualBrake", ManualBrake}, {"PneumaticBrake", PneumaticBrake}, {"HydraulicBrake", HydraulicBrake}}; auto lookup = localbrakes.find(extract_value("LocalBrake", line)); - LocalBrake = lookup != localbrakes.end() ? lookup->second : NoBrake; + brakes.localKind = lookup != localbrakes.end() ? lookup->second : NoBrake; } // mbrake - extract_value(MBrake, "ManualBrake", line, ""); + extract_value(brakes.hasHandBrake, "ManualBrake", line, ""); } // Cntrl.: of a vehicle with a train brake, its positions, delays, modes, handles, load weighing and anti-slip brake @@ -714,11 +714,11 @@ void physics::Vehicle::LoadFIZ_CntrlTrainBrake(std::string const &line) { using enum TBrakeHandle; - extract_value(BrakeCtrlPosNo, "BCPN", line, ""); + extract_value(brakes.handlePositions, "BCPN", line, ""); for (int idx = 0; idx < 4; ++idx) { - extract_value(BrakeDelay[idx], std::format("BDelay{}", idx + 1), line, ""); + extract_value(brakes.delays[idx], std::format("BDelay{}", idx + 1), line, ""); } // brakedelays, brakedelayflag { @@ -734,15 +734,15 @@ void physics::Vehicle::LoadFIZ_CntrlTrainBrake(std::string const &line) std::string brakedelay; extract_value(brakedelay, "BrakeDelays", line, ""); auto lookup = brakedelays.find(brakedelay); - BrakeDelays = lookup != brakedelays.end() ? lookup->second : 0; + brakes.availableDelays = lookup != brakedelays.end() ? lookup->second : 0; lookup = brakedelayflags.find(brakedelay); - BrakeDelayFlag = lookup != brakedelayflags.end() ? lookup->second : 0; + brakes.delaySetting = lookup != brakedelayflags.end() ? lookup->second : 0; } // brakeopmode { std::map> brakeopmodes{{"PN", bom_PS + bom_PN}, {"PNEP", bom_PS + bom_PN + bom_EP}, {"PNEPMED", bom_PS + bom_PN + bom_EP + bom_MED}}; auto lookup = brakeopmodes.find(extract_value("BrakeOpModes", line)); - BrakeOpModes = lookup != brakeopmodes.end() ? lookup->second : 0; + brakes.availableOperatingModes = lookup != brakeopmodes.end() ? lookup->second : 0; } // brakehandle { @@ -751,26 +751,26 @@ void physics::Vehicle::LoadFIZ_CntrlTrainBrake(std::string const &line) {"MHZ_K8P", MHZ_K8P}, {"MHZ_6P", MHZ_6P}, {"M394", M394}, {"Knorr", Knorr}, {"Westinghouse", West}, {"FVel6", FVel6}, {"FVE408", FVE408}, {"St113", St113}}; auto lookup = brakehandles.find(extract_value("BrakeHandle", line)); - BrakeHandle = lookup != brakehandles.end() ? lookup->second : NoHandle; + brakes.driverValveType = lookup != brakehandles.end() ? lookup->second : NoHandle; } - extract_value(Handle_AutomaticOverload, "HAO", line, ""); - extract_value(Handle_ManualOverload, "HMO", line, ""); - extract_value(Handle_GenericDoubleParameter1, "HGDP1", line, ""); - extract_value(Handle_GenericDoubleParameter2, "HGDP2", line, ""); - extract_value(Handle_OverloadMaxPressure, "OMP", line, ""); - extract_value(Handle_OverloadPressureDecrease, "OPD", line, ""); + extract_value(brakes.driverValveSettings.automaticOverload, "HAO", line, ""); + extract_value(brakes.driverValveSettings.manualOverload, "HMO", line, ""); + extract_value(brakes.driverValveSettings.genericParameter1, "HGDP1", line, ""); + extract_value(brakes.driverValveSettings.genericParameter2, "HGDP2", line, ""); + extract_value(brakes.driverValveSettings.overloadMaxPressure, "OMP", line, ""); + extract_value(brakes.driverValveSettings.overloadPressureDecrease, "OPD", line, ""); // brakelochandle { std::map> locbrakehandles{{"FD1", FD1}, {"Knorr", Knorr}, {"Westinghouse", West}}; auto lookup = locbrakehandles.find(extract_value("LocBrakeHandle", line)); - BrakeLocHandle = lookup != locbrakehandles.end() ? lookup->second : NoHandle; + brakes.independentValveType = lookup != locbrakehandles.end() ? lookup->second : NoHandle; } // mbpm - if (true == extract_value(MBPM, "MaxBPMass", line, "")) + if (true == extract_value(brakes.maxPressureMass, "MaxBPMass", line, "")) { // NOTE: only convert the value from tons to kilograms if the entry is present in the config file - MBPM *= 1000.0; + brakes.maxPressureMass *= 1000.0; } // asbtype @@ -782,15 +782,15 @@ void physics::Vehicle::LoadFIZ_CntrlAntiSlipBrake(std::string_view const asb) { if (asb == "yes") { - ASBType = 128; + brakes.antiSlipType = 128; } - else if (BrakeCtrlPosNo > 0 && asb == "manual") + else if (brakes.handlePositions > 0 && asb == "manual") { - ASBType = 1; + brakes.antiSlipType = 1; } - else if (BrakeCtrlPosNo > 0 && asb == "automatic") + else if (brakes.handlePositions > 0 && asb == "automatic") { - ASBType = 2; + brakes.antiSlipType = 2; } } @@ -855,7 +855,7 @@ void physics::Vehicle::LoadFIZ_CntrlControllers(std::string const &line) extract_value(HasCamshaft, "Camshaft", line, ""); extract_value(EIMCtrlType, "EIMCtrlType", line, ""); EIMCtrlType = std::clamp(EIMCtrlType, 0, 3); - extract_value(LocHandleTimeTraxx, "LocalBrakeTraxx", line, ""); + extract_value(brakes.independentTraxx, "LocalBrakeTraxx", line, ""); extract_value(EIMCtrlAdditionalZeros, "EIMCtrlAddZeros", line, ""); extract_value(EIMCtrlEmergency, "EIMCtrlEmergency", line, ""); // Elf (EIMCtrlType 2): an emergency brake position below the controller's position 0, which shifts the other positions up by one diff --git a/physics/components/pneumatics.cpp b/physics/components/pneumatics.cpp index ba186f1dc..37b421f57 100644 --- a/physics/components/pneumatics.cpp +++ b/physics/components/pneumatics.cpp @@ -35,24 +35,24 @@ http://mozilla.org/MPL/2.0/. void physics::Vehicle::BrakeLevelSet(double b) { // ustawienie pozycji hamulca na wartość (b) w zakresie od -2 do BrakeCtrlPosNo // jedyny dopuszczalny sposób przestawienia hamulca zasadniczego - if (fBrakeCtrlPos == b) + if (brakes.handlePositionSmooth == b) return; // nie przeliczać, jak nie ma zmiany - fBrakeCtrlPos = b; - if (fBrakeCtrlPos < Handle->GetPos(bh_MIN)) - fBrakeCtrlPos = Handle->GetPos(bh_MIN); // odcięcie - else if (fBrakeCtrlPos > Handle->GetPos(bh_MAX)) - fBrakeCtrlPos = Handle->GetPos(bh_MAX); + brakes.handlePositionSmooth = b; + if (brakes.handlePositionSmooth < brakes.driverValve->GetPos(bh_MIN)) + brakes.handlePositionSmooth = brakes.driverValve->GetPos(bh_MIN); // odcięcie + else if (brakes.handlePositionSmooth > brakes.driverValve->GetPos(bh_MAX)) + brakes.handlePositionSmooth = brakes.driverValve->GetPos(bh_MAX); // TODO: verify whether BrakeCtrlPosR and fBrakeCtrlPos can be rolled into single variable - BrakeCtrlPosR = fBrakeCtrlPos; - auto x = static_cast(std::floor(fBrakeCtrlPos)); // jeśli odwołujemy się do BrakeCtrlPos w pośrednich, to musi być + brakes.handlePositionReal = brakes.handlePositionSmooth; + auto x = static_cast(std::floor(brakes.handlePositionSmooth)); // jeśli odwołujemy się do BrakeCtrlPos w pośrednich, to musi być // obcięte a nie zaokrągone - while (x > BrakeCtrlPos && BrakeCtrlPos < BrakeCtrlPosNo) // jeśli zwiększyło się o 1 + while (x > brakes.handlePosition && brakes.handlePosition < brakes.handlePositions) // jeśli zwiększyło się o 1 if (!IncBrakeLevelOld()) // physics::Vehicle:: break; // wyjście awaryjne - while (x < BrakeCtrlPos && BrakeCtrlPos >= -1) // jeśli zmniejszyło się o 1 + while (x < brakes.handlePosition && brakes.handlePosition >= -1) // jeśli zmniejszyło się o 1 if (!DecBrakeLevelOld()) // physics::Vehicle:: break; - BrakePressureActual = BrakePressureTable[BrakeCtrlPos]; // skopiowanie pozycji + brakes.actualPressure = brakes.pressureTable[brakes.handlePosition]; // skopiowanie pozycji /* //youBy: obawiam sie, ze tutaj to nie dziala :P //Ra 2014-03: było tak zrobione, że działało - po każdej zmianie pozycji była wywoływana ta @@ -76,8 +76,8 @@ void physics::Vehicle::BrakeLevelSet(double b) bool physics::Vehicle::BrakeLevelAdd(double b) { // dodanie wartości (b) do pozycji hamulca (w tym ujemnej) // zwraca false, gdy po dodaniu było by poza zakresem - BrakeLevelSet(fBrakeCtrlPos + b); - return b > 0.0 ? fBrakeCtrlPos < BrakeCtrlPosNo : BrakeCtrlPos > -1.0; // true, jeśli można kontynuować + BrakeLevelSet(brakes.handlePositionSmooth + b); + return b > 0.0 ? brakes.handlePositionSmooth < brakes.handlePositions : brakes.handlePosition > -1.0; // true, jeśli można kontynuować }; bool physics::Vehicle::IncBrakeLevel() @@ -136,15 +136,15 @@ ZN //masa double physics::Vehicle::LocalBrakeRatio(void) const { double LBR; - if (BrakeHandle == TBrakeHandle::MHZ_EN57) - if (BrakeOpModeFlag >= bom_EP) - LBR = Handle->GetEP(BrakeCtrlPosR); + if (brakes.driverValveType == TBrakeHandle::MHZ_EN57) + if (brakes.operatingMode >= bom_EP) + LBR = brakes.driverValve->GetEP(brakes.handlePositionReal); else LBR = 0; else { if (LocalBrakePosNo > 0) - LBR = LocalBrakePosA; + LBR = brakes.independentPosition; else LBR = 0; } @@ -162,7 +162,7 @@ double physics::Vehicle::ManualBrakeRatio(void) const double MBR; if (ManualBrakePosNo > 0) - MBR = (double)ManualBrakePos / ManualBrakePosNo; + MBR = (double)brakes.handBrakePosition / ManualBrakePosNo; else MBR = 0; return MBR; @@ -174,8 +174,8 @@ double physics::Vehicle::ManualBrakeRatio(void) const // ***************************************************************************** double physics::Vehicle::BrakeVP(void) const { - if (BrakeVVolume > 0) - return Volume / (10.0 * BrakeVVolume); + if (brakes.valveVolume > 0) + return brakes.reservoirAir / (10.0 * brakes.valveVolume); else return 0; } @@ -188,8 +188,8 @@ double physics::Vehicle::RealPipeRatio(void) const { double rpp; - if (DeltaPipePress > 0) - rpp = (CntrlPipePress - brakePipe.pressure) / DeltaPipePress; + if (brakes.pipePressureRange > 0) + rpp = (brakes.controlReservoirPressure - brakePipe.pressure) / brakes.pipePressureRange; else rpp = 0; return rpp; @@ -203,13 +203,13 @@ double physics::Vehicle::PipeRatio(void) const { double pr; - if (DeltaPipePress > 0) + if (brakes.pipePressureRange > 0) if (false) // SPKS!! no to jak nie wchodzimy to po co branch? { - if (3.0 * brakePipe.pressure > HighPipePress + LowPipePress + LowPipePress) - pr = (HighPipePress - std::min(HighPipePress, brakePipe.pressure)) / (DeltaPipePress * 4.0 / 3.0); + if (3.0 * brakePipe.pressure > brakes.pipeHighPressure + brakes.pipeLowPressure + brakes.pipeLowPressure) + pr = (brakes.pipeHighPressure - std::min(brakes.pipeHighPressure, brakePipe.pressure)) / (brakes.pipePressureRange * 4.0 / 3.0); else - pr = (HighPipePress - 1.0 / 3.0 * DeltaPipePress - std::max(LowPipePress, brakePipe.pressure)) / (DeltaPipePress * 2.0 / 3.0); + pr = (brakes.pipeHighPressure - 1.0 / 3.0 * brakes.pipePressureRange - std::max(brakes.pipeLowPressure, brakePipe.pressure)) / (brakes.pipePressureRange * 2.0 / 3.0); // if (not TestFlag(BrakeStatus, b_Ractive)) // and(BrakeMethod and 1 = 0) and TestFlag(BrakeDelays, bdelay_R) and (Power < 1) and // (BrakeCtrlPos < 1) then pr : = std::min(0.5, pr); @@ -217,7 +217,7 @@ double physics::Vehicle::PipeRatio(void) const // then pr : = pr * 1.333; // dziwny rapid wywalamy } else - pr = (HighPipePress - std::max(LowPipePress, std::min(HighPipePress, brakePipe.pressure))) / DeltaPipePress; + pr = (brakes.pipeHighPressure - std::max(brakes.pipeLowPressure, std::min(brakes.pipeHighPressure, brakePipe.pressure))) / brakes.pipePressureRange; else pr = 0; return pr; @@ -352,15 +352,15 @@ bool physics::Vehicle::IncBrakeLevelOld(void) { bool IBLO = false; - if (BrakeCtrlPosNo > 0) + if (brakes.handlePositions > 0) { - if (BrakeCtrlPos < BrakeCtrlPosNo) + if (brakes.handlePosition < brakes.handlePositions) { - ++BrakeCtrlPos; + ++brakes.handlePosition; // youBy: EP po nowemu IBLO = true; - if (BrakePressureActual.PipePressureVal < 0 && BrakePressureTable[BrakeCtrlPos - 1].PipePressureVal > 0) - LimPipePress = brakePipe.pressure; + if (brakes.actualPressure.PipePressureVal < 0 && brakes.pressureTable[brakes.handlePosition - 1].PipePressureVal > 0) + brakes.pipeLimiterPressure = brakePipe.pressure; } else { @@ -379,11 +379,11 @@ bool physics::Vehicle::DecBrakeLevelOld(void) { bool DBLO = false; - if (BrakeCtrlPosNo > 0) + if (brakes.handlePositions > 0) { - if (BrakeCtrlPos > (BrakeHandle == TBrakeHandle::FV4a ? -2 : -1)) + if (brakes.handlePosition > (brakes.driverValveType == TBrakeHandle::FV4a ? -2 : -1)) { - --BrakeCtrlPos; + --brakes.handlePosition; // youBy: EP po nowemu DBLO = true; // if ((BrakePressureTable[BrakeCtrlPos].PipePressureVal<0.0) && @@ -404,9 +404,9 @@ bool physics::Vehicle::DecBrakeLevelOld(void) bool physics::Vehicle::IncLocalBrakeLevel(float const CtrlSpeed) { bool IBL; - if (LocalBrakePosA < 1.0 /*and (BrakeCtrlPos<1)*/) + if (brakes.independentPosition < 1.0 /*and (BrakeCtrlPos<1)*/) { - LocalBrakePosA = std::min(1.0, LocalBrakePosA + CtrlSpeed / LocalBrakePosNo); + brakes.independentPosition = std::min(1.0, brakes.independentPosition + CtrlSpeed / LocalBrakePosNo); wake_for_brake(); IBL = true; } @@ -423,9 +423,9 @@ bool physics::Vehicle::IncLocalBrakeLevel(float const CtrlSpeed) bool physics::Vehicle::DecLocalBrakeLevel(float const CtrlSpeed) { bool DBL; - if (LocalBrakePosA > 0) + if (brakes.independentPosition > 0) { - LocalBrakePosA = std::max(0.0, LocalBrakePosA - CtrlSpeed / LocalBrakePosNo); + brakes.independentPosition = std::max(0.0, brakes.independentPosition - CtrlSpeed / LocalBrakePosNo); wake_for_brake(); DBL = true; } @@ -442,11 +442,11 @@ bool physics::Vehicle::DecLocalBrakeLevel(float const CtrlSpeed) bool physics::Vehicle::IncManualBrakeLevel(int CtrlSpeed) { bool IMBL; - if (ManualBrakePos < ManualBrakePosNo) /*and (BrakeCtrlPos<1)*/ + if (brakes.handBrakePosition < ManualBrakePosNo) /*and (BrakeCtrlPos<1)*/ { - while (ManualBrakePos < ManualBrakePosNo && CtrlSpeed > 0) + while (brakes.handBrakePosition < ManualBrakePosNo && CtrlSpeed > 0) { - ManualBrakePos++; + brakes.handBrakePosition++; CtrlSpeed--; } wake_for_brake(); @@ -465,11 +465,11 @@ bool physics::Vehicle::IncManualBrakeLevel(int CtrlSpeed) bool physics::Vehicle::DecManualBrakeLevel(int CtrlSpeed) { bool DMBL; - if (ManualBrakePos > 0) + if (brakes.handBrakePosition > 0) { - while (CtrlSpeed > 0 && ManualBrakePos > 0) + while (CtrlSpeed > 0 && brakes.handBrakePosition > 0) { - ManualBrakePos--; + brakes.handBrakePosition--; CtrlSpeed--; } wake_for_brake(); @@ -483,10 +483,10 @@ bool physics::Vehicle::DecManualBrakeLevel(int CtrlSpeed) bool physics::Vehicle::AlarmChainSwitch(bool const State) { - if (AlarmChainFlag != State) + if (brakes.alarmChain != State) { // simple routine for the time being - AlarmChainFlag = State; + brakes.alarmChain = State; return true; } return false; @@ -499,11 +499,11 @@ bool physics::Vehicle::AlarmChainSwitch(bool const State) bool physics::Vehicle::AntiSlippingBrake(void) { bool ASB = false; // Ra: przeniesione z końca - if (ASBType == 1) + if (brakes.antiSlipType == 1) { ASB = true; // SPKS!! - Hamulec->ASB(1); - BrakeSlippingTimer = 0; + brakes.distributor->ASB(1); + brakes.antiSlipTimer = 0; } return ASB; } @@ -520,12 +520,12 @@ bool physics::Vehicle::BrakeReleaser(int state) // additional limitations imposed by pressure switch if (false == ControlPressureSwitch || false == ReleaserEnabledOnlyAtNoPowerPos || true == IsMainCtrlNoPowerPos()) { - Hamulec->Releaser(state); + brakes.distributor->Releaser(state); } } else { - Hamulec->Releaser(state); + brakes.distributor->Releaser(state); } if (CabActive != 0) // rekurencyjne wysłanie do następnego OK = SendCtrlToNext(VehicleCommand::brakeReleaser, state, CabActive); @@ -539,23 +539,23 @@ bool physics::Vehicle::BrakeReleaser(int state) bool physics::Vehicle::UniversalBrakeButton(int button, int state) { bool OK = true; // false tylko jeśli nie uda się wysłać, GF 20161124 - UniversalBrakeButtonActive[button] = state > 0; + brakes.universalButtonPressed[button] = state > 0; int flag = 0; if (Power24vIsAvailable || Power110vIsAvailable) { for (int i = 0; i < 3; i++) { - flag = flag | (UniversalBrakeButtonActive[i] ? UniversalBrakeButtonFlag[i] : 0); + flag = flag | (brakes.universalButtonPressed[i] ? brakes.universalButtonActions[i] : 0); } } - Hamulec->SetUniversalFlag(flag); - Handle->SetUniversalFlag(flag); - LocHandle->SetUniversalFlag(flag); - UnlockPipe = (flag & TUniversalBrake::ub_UnlockPipe) > 0; + brakes.distributor->SetUniversalFlag(flag); + brakes.driverValve->SetUniversalFlag(flag); + brakes.independentValve->SetUniversalFlag(flag); + brakes.pipeLock.unlockPressed = (flag & TUniversalBrake::ub_UnlockPipe) > 0; // if the releaser can be activated by switch - if (TestFlag(UniversalBrakeButtonFlag[0] & UniversalBrakeButtonFlag[1] & UniversalBrakeButtonFlag[2], TUniversalBrake::ub_Release)) + if (TestFlag(brakes.universalButtonActions[0] & brakes.universalButtonActions[1] & brakes.universalButtonActions[2], TUniversalBrake::ub_Release)) { BrakeReleaser(TestFlag(flag, TUniversalBrake::ub_Release) ? 1 : 0); } @@ -571,14 +571,14 @@ bool physics::Vehicle::SwitchEPBrake(int state) bool OK; OK = false; - if (BrakeHandle == TBrakeHandle::St113 && CabOccupied != 0) + if (brakes.driverValveType == TBrakeHandle::St113 && CabOccupied != 0) { // the handle works the EP contactors pneumatically, their supply is cut as the Oerlikon handle's is if (state > 0 && EPBrakeControlPowered()) - EpForce = Handle->GetEP(); // TODO: przetlumaczyc + EpForce = brakes.driverValve->GetEP(); // TODO: przetlumaczyc else EpForce = 0; - Hamulec->SetEPS(EpForce); + brakes.distributor->SetEPS(EpForce); SendCtrlToNext(VehicleCommand::brake, EpForce, CabActive); } // OK:=SetFlag(BrakeStatus,((2*State-1)*b_epused)); @@ -600,7 +600,7 @@ bool physics::Vehicle::IncBrakePress(double &brake, double PressLimit, double dp bool IBP; // if (DynamicBrakeType<>dbrake_switch) and (DynamicBrakeType<>dbrake_none) and // ((BrakePress>2.0) or (PipePress<3.7{(LowPipePress+0.5)})) then - if (DynamicBrakeType != dbrake_switch && DynamicBrakeType != dbrake_none && BrakePress > 2.0 && TrainType != train_type::emu) // yB radzi nie sprawdzać ciśnienia w przewodzie + if (DynamicBrakeType != dbrake_switch && DynamicBrakeType != dbrake_none && brakes.cylinderPressure > 2.0 && TrainType != train_type::emu) // yB radzi nie sprawdzać ciśnienia w przewodzie // hunter-301211: dla EN57 silnikow nie odlaczamy { DynamicBrakeFlag = true; // uruchamianie hamulca ED albo odlaczanie silnikow @@ -640,7 +640,7 @@ bool physics::Vehicle::DecBrakePress(double &brake, double PressLimit, double dp } // if ((DynamicBrakeType != dbrake_switch) && ((BrakePress < 0.1) && (PipePress > 0.45 // /*(LowPipePress+0.06)*/ ))) - if (DynamicBrakeType != dbrake_switch && BrakePress < 0.1) // yB radzi nie sprawdzać ciśnienia w przewodzie + if (DynamicBrakeType != dbrake_switch && brakes.cylinderPressure < 0.1) // yB radzi nie sprawdzać ciśnienia w przewodzie DynamicBrakeFlag = false; // wylaczanie hamulca ED i/albo zalaczanie silnikow return DBP; @@ -653,14 +653,14 @@ bool physics::Vehicle::DecBrakePress(double &brake, double PressLimit, double dp bool physics::Vehicle::BrakeDelaySwitch(int BDS) { bool rBDS; - if (Hamulec->SetBDF(BDS)) + if (brakes.distributor->SetBDF(BDS)) { - BrakeDelayFlag = BDS; + brakes.delaySetting = BDS; rBDS = true; - Hamulec->SetBrakeStatus(Hamulec->GetBrakeStatus() & ~64); + brakes.distributor->SetBrakeStatus(brakes.distributor->GetBrakeStatus() & ~64); // kopowanie nastawy hamulca do kolejnego czlonu - do przemyślenia if (CabActive != 0) - SendCtrlToNext(VehicleCommand::brakeDelay, BrakeDelayFlag, CabActive); + SendCtrlToNext(VehicleCommand::brakeDelay, brakes.delaySetting, CabActive); } else rBDS = false; @@ -676,15 +676,15 @@ bool physics::Vehicle::IncBrakeMult(void) { bool IBM; - if (LoadFlag > 0 && MBPM < 2 && LoadFlag < 3) + if (brakes.loadSetting > 0 && brakes.maxPressureMass < 2 && brakes.loadSetting < 3) { - if (MaxBrakePress[2] > 0 && LoadFlag == 1) - LoadFlag = 2; + if (brakes.maxCylinderPressure[2] > 0 && brakes.loadSetting == 1) + brakes.loadSetting = 2; else - LoadFlag = 3; + brakes.loadSetting = 3; IBM = true; - if (BrakeCylMult[2] > 0) - BrakeCylMult[0] = BrakeCylMult[2]; + if (brakes.cylinders.leverRatio[2] > 0) + brakes.cylinders.leverRatio[0] = brakes.cylinders.leverRatio[2]; } else IBM = false; @@ -699,15 +699,15 @@ bool physics::Vehicle::IncBrakeMult(void) bool physics::Vehicle::DecBrakeMult(void) { bool DBM; - if (LoadFlag > 1 && MBPM < 2) + if (brakes.loadSetting > 1 && brakes.maxPressureMass < 2) { - if (MaxBrakePress[2] > 0 && LoadFlag == 3) - LoadFlag = 2; + if (brakes.maxCylinderPressure[2] > 0 && brakes.loadSetting == 3) + brakes.loadSetting = 2; else - LoadFlag = 1; + brakes.loadSetting = 1; DBM = true; - if (BrakeCylMult[1] > 0) - BrakeCylMult[0] = BrakeCylMult[1]; + if (brakes.cylinders.leverRatio[1] > 0) + brakes.cylinders.leverRatio[0] = brakes.cylinders.leverRatio[1]; } else DBM = false; @@ -724,21 +724,21 @@ void physics::Vehicle::UpdateBrakePressure(double dt) // const double LBDelay = 5.0; // stala czasowa hamulca // double Rate, Speed, dp, sm; - dpLocalValve = 0; - dpBrake = 0; + brakes.independentValveFlow = 0; + brakes.brakeFlow = 0; - Hamulec->ForceLeak(dt * air.leakRate * 0.25); // fake air leaks from brake system reservoirs + brakes.distributor->ForceLeak(dt * air.leakRate * 0.25); // fake air leaks from brake system reservoirs - auto const brakepress{BrakePress}; - BrakePress = Hamulec->GetBCP(); + auto const brakepress{brakes.cylinderPressure}; + brakes.cylinderPressure = brakes.distributor->GetBCP(); if (dt > 0.0) { // averaged over about a second: the valves move the cylinder in pulses, quicker than that within a single step - auto const rate{std::abs(BrakePress - brakepress) / dt}; - BrakePressRate += (rate - BrakePressRate) * std::min(1.0, dt / 1.0); + auto const rate{std::abs(brakes.cylinderPressure - brakepress) / dt}; + brakes.cylinderPressureRate += (rate - brakes.cylinderPressureRate) * std::min(1.0, dt / 1.0); } // BrakePress:=(Hamulec as TEst4).ImplsRes.pa; - Volume = Hamulec->GetBRP(); + brakes.reservoirAir = brakes.distributor->GetBRP(); } // ************************************************************************************************* @@ -769,10 +769,10 @@ void physics::Vehicle::CompressorCheck(double dt) } // EmergencyValve - EmergencyValveOpen = air.mainReservoirPressure > (EmergencyValveOpen ? EmergencyValveOff : EmergencyValveOn); - if (EmergencyValveOpen) + brakes.emergencyValve.open = air.mainReservoirPressure > (brakes.emergencyValve.open ? brakes.emergencyValve.offPressure : brakes.emergencyValve.onPressure); + if (brakes.emergencyValve.open) { - auto dV = static_cast(PF(0, air.mainReservoirPressure, EmergencyValveArea) * dt); + auto dV = static_cast(PF(0, air.mainReservoirPressure, brakes.emergencyValve.area) * dt); air.compressedVolume -= dV; } @@ -907,9 +907,9 @@ void physics::Vehicle::UpdatePipePressure(double dt) brakePipe.pressure = brakePipe.reservoir->P(); // PPP:=PipePress; - dpMainValve = 0; + brakes.driverValveFlow = 0; - if (BrakeCtrlPosNo > 1) + if (brakes.handlePositions > 1) { UpdateLocalBrakeValve(dt); @@ -919,25 +919,25 @@ void physics::Vehicle::UpdatePipePressure(double dt) UpdateEmergencyValve(dt); // 0.2*Spg - brakePipe.reservoir->Flow(-dpMainValve); + brakePipe.reservoir->Flow(-brakes.driverValveFlow); brakePipe.reservoir->Flow(-brakePipe.pressure * 0.001 * dt); // if Heating then // Pipe.Flow(PF(PipePress, 0, d2A(7)) * dt); // if ConverterFlag then // Pipe.Flow(PF(PipePress, 0, d2A(12)) * dt); - dpMainValve = dpMainValve / (Dim.L * Spg * 20); + brakes.driverValveFlow = brakes.driverValveFlow / (Dim.L * brakes.pipeSection * 20); - CntrlPipePress = Hamulec->GetVRP(); // ciśnienie komory wstępnej rozdzielacza + brakes.controlReservoirPressure = brakes.distributor->GetVRP(); // ciśnienie komory wstępnej rozdzielacza // if (Hamulec is typeid(TWest)) return 0; UpdateDistributorSettings(); - if ((BrakeHandle == TBrakeHandle::FVel6 || BrakeHandle == TBrakeHandle::FVE408) && CabOccupied != 0) + if ((brakes.driverValveType == TBrakeHandle::FVel6 || brakes.driverValveType == TBrakeHandle::FVE408) && CabOccupied != 0) { UpdateEPBrake(); } - else if (BrakeHandle == TBrakeHandle::St113 && CabOccupied != 0 && std::abs(EpForce) > 0.001 && !EPBrakeControlPowered()) + else if (brakes.driverValveType == TBrakeHandle::St113 && CabOccupied != 0 && std::abs(EpForce) > 0.001 && !EPBrakeControlPowered()) { // the EP brake switched on with the button drops out with the control's supply SwitchEPBrake(0); @@ -945,24 +945,24 @@ void physics::Vehicle::UpdatePipePressure(double dt) brakePipe.reservoir->Act(); brakePipe.pressure = brakePipe.reservoir->P(); - if ((Hamulec->GetBrakeStatus() & b_dmg) == b_dmg) // jesli hamulec wyłączony + if ((brakes.distributor->GetBrakeStatus() & b_dmg) == b_dmg) // jesli hamulec wyłączony temp = 0.0; // odetnij else temp = 1.0; // połącz - brakePipe.reservoir->Flow(temp * Hamulec->GetPF(temp * brakePipe.pressure, dt, Vel)); + brakePipe.reservoir->Flow(temp * brakes.distributor->GetPF(temp * brakePipe.pressure, dt, Vel)); // the air the brake hoses carry to and from the neighbours comes once all vehicles have stepped, UpdatePipeCouplers() brakePipe.couplersPending = true; - if (ASBType == 128) - Hamulec->ASB(int(SlippingWheels && Vel > 1) * (1 + 2 * int(nrot_eps < -0.01))); + if (brakes.antiSlipType == 128) + brakes.distributor->ASB(int(SlippingWheels && Vel > 1) * (1 + 2 * int(nrot_eps < -0.01))); - dpPipe = 0; + brakes.pipeFlow = 0; // yB: jednokrokowe liczenie tego wszystkiego brakePipe.reservoir->Act(); brakePipe.pressure = brakePipe.reservoir->P(); - dpMainValve = dpMainValve / (100.0 * dt); // normalizacja po czasie do syczenia; + brakes.driverValveFlow = brakes.driverValveFlow / (100.0 * dt); // normalizacja po czasie do syczenia; if (brakePipe.pressure < -1.0) { @@ -981,7 +981,7 @@ void physics::Vehicle::UpdateLocalBrakeValve(double dt) // the local brake of a vehicle prepared for hauling (PulleeMode) is held released, whatever asks for it if (EngineType != TEngineType::ElectricInductionMotor) { - double lbpa = LocHandleTimeTraxx ? eim_localbrake : LocalBrakePosA; + double lbpa = brakes.independentTraxx ? eim_localbrake : brakes.independentPosition; if (EIMCtrlType > 0 && UniCtrlIntegratedLocalBrakeCtrl) { lbpa = std::max(0.0, -eimic_real); @@ -990,7 +990,7 @@ void physics::Vehicle::UpdateLocalBrakeValve(double dt) { lbpa = std::max(lbpa, brakes.holding.deceleration); } - dpLocalValve = LocHandle->GetPF(PulleeMode ? 0.0 : std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), mainPipe.pressure, dt, 0); + brakes.independentValveFlow = brakes.independentValve->GetPF(PulleeMode ? 0.0 : std::max(lbpa, brakes.independentPositionEim), brakes.distributor->GetBCP(), mainPipe.pressure, dt, 0); } else { @@ -999,19 +999,19 @@ void physics::Vehicle::UpdateLocalBrakeValve(double dt) // lever should apply pneumatic pressure on the locomotive directly, bypassing MED. // LocHandleTimeTraxx also bypasses MED, but has 3 positions (brake-hold-unbrake). double lbpa; - if (LocHandleTimeTraxx) + if (brakes.independentTraxx) { lbpa = eim_localbrake; } else if (SplitEDPneumaticBrake) // When LocHandleTimeTraxx and SplitEDPneumaticBrake are both active, lbpa is taken from LocHandleTimeTraxx, which is the desired behavior. { - lbpa = LocalBrakePosA; + lbpa = brakes.independentPosition; } else { lbpa = 0.0; } - dpLocalValve = LocHandle->GetPF(PulleeMode ? 0.0 : std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), mainPipe.pressure, dt, 0); + brakes.independentValveFlow = brakes.independentValve->GetPF(PulleeMode ? 0.0 : std::max(lbpa, brakes.independentPositionEim), brakes.distributor->GetBCP(), mainPipe.pressure, dt, 0); } } @@ -1019,49 +1019,49 @@ void physics::Vehicle::UpdateLocalBrakeValve(double dt) void physics::Vehicle::UpdateMainValve(double dt) { auto const temp{MainValveSupply()}; - Handle->SetReductor(BrakeCtrlPos2); + brakes.driverValve->SetReductor(brakes.handleCapPosition); if (PulleeMode) { // the driver's valve of a vehicle prepared for hauling is cut out, whatever its handle shows - dpMainValve = 0; + brakes.driverValveFlow = 0; } - else if ((BrakeOpModes & bom_PS) == 0 || (CabOccupied != 0 && BrakeOpModeFlag != bom_PS)) + else if ((brakes.availableOperatingModes & bom_PS) == 0 || (CabOccupied != 0 && brakes.operatingMode != bom_PS)) { - if (BrakeOpModeFlag < bom_EP || Handle->GetPos(bh_EB) - 0.5 < BrakeCtrlPosR || (BrakeHandle != TBrakeHandle::MHZ_EN57 && BrakeHandle != TBrakeHandle::MHZ_K8P)) + if (brakes.operatingMode < bom_EP || brakes.driverValve->GetPos(bh_EB) - 0.5 < brakes.handlePositionReal || (brakes.driverValveType != TBrakeHandle::MHZ_EN57 && brakes.driverValveType != TBrakeHandle::MHZ_K8P)) { - dpMainValve = Handle->GetPF(MainValveHandlePosition(), brakePipe.pressure, temp, dt, EqvtPipePress); + brakes.driverValveFlow = brakes.driverValve->GetPF(MainValveHandlePosition(), brakePipe.pressure, temp, dt, brakes.equivalentPipePressure); } else { - dpMainValve = Handle->GetPF(0, brakePipe.pressure, temp, dt, EqvtPipePress); + brakes.driverValveFlow = brakes.driverValve->GetPF(0, brakePipe.pressure, temp, dt, brakes.equivalentPipePressure); } } - else if (BrakeCtrlPos == Handle->GetPos(bh_EB)) + else if (brakes.handlePosition == brakes.driverValve->GetPos(bh_EB)) { - dpMainValve = Handle->GetPF(BrakeCtrlPosR, brakePipe.pressure, temp, dt, EqvtPipePress); + brakes.driverValveFlow = brakes.driverValve->GetPF(brakes.handlePositionReal, brakePipe.pressure, temp, dt, brakes.equivalentPipePressure); } - if (dpMainValve < 0) // && (PipePressureVal > 0.01) //50 + if (brakes.driverValveFlow < 0) // && (PipePressureVal > 0.01) //50 { if (air.mainReservoirPressure > mainPipe.pressure) { - air.compressedVolume = air.compressedVolume + dpMainValve / 1500.0; - mainPipe.reservoir->Flow(dpMainValve / 3.0); + air.compressedVolume = air.compressedVolume + brakes.driverValveFlow / 1500.0; + mainPipe.reservoir->Flow(brakes.driverValveFlow / 3.0); } else - mainPipe.reservoir->Flow(dpMainValve); + mainPipe.reservoir->Flow(brakes.driverValveFlow); } } // the pressure the driver's handle is fed from: the main pipe's, or the brake pipe's own with the pipe locked double physics::Vehicle::MainValveSupply() { - LockPipe = brakePipe.pressure < (LockPipe ? LockPipeOff : LockPipeOn); - bool lock_new = (LockPipe && !UnlockPipe && BrakeCtrlPosR > HandleUnlock) || (EmergencyCutsOffHandle && EmergencyValveFlow > 0); // new simple codition based on .fiz - bool lock_old = BrakeHandle == TBrakeHandle::FV4a // old complex condition based on assumptions - && brakePipe.pressure < 2.75 && (Hamulec->GetStatus() & b_rls) == 0 && BrakeSubsystem == TBrakeSubSystem::ss_LSt && TrainType != train_type::emu && !UnlockPipe; + brakes.pipeLock.locked = brakePipe.pressure < (brakes.pipeLock.locked ? brakes.pipeLock.offPressure : brakes.pipeLock.onPressure); + bool lock_new = (brakes.pipeLock.locked && !brakes.pipeLock.unlockPressed && brakes.handlePositionReal > brakes.pipeLock.unlockHandlePosition) || (brakes.emergencyCutsOffDriverValve && brakes.emergencyValve.flow > 0); // new simple codition based on .fiz + bool lock_old = brakes.driverValveType == TBrakeHandle::FV4a // old complex condition based on assumptions + && brakePipe.pressure < 2.75 && (brakes.distributor->GetStatus() & b_rls) == 0 && brakes.subsystem == TBrakeSubSystem::ss_LSt && TrainType != train_type::emu && !brakes.pipeLock.unlockPressed; if (lock_old || lock_new) { @@ -1073,14 +1073,14 @@ double physics::Vehicle::MainValveSupply() // the position the driver's handle works at: its own, or the one the speed control's brake intervention sets double physics::Vehicle::MainValveHandlePosition() const { - double pos = BrakeCtrlPosR; - if (SpeedCtrlUnit.IsActive && SpeedCtrlUnit.BrakeIntervention && !SpeedCtrlUnit.Standby && BrakeCtrlPos != Handle->GetPos(bh_EB)) + double pos = brakes.handlePositionReal; + if (SpeedCtrlUnit.IsActive && SpeedCtrlUnit.BrakeIntervention && !SpeedCtrlUnit.Standby && brakes.handlePosition != brakes.driverValve->GetPos(bh_EB)) { - pos = Handle->GetPos(bh_NP); + pos = brakes.driverValve->GetPos(bh_NP); if (SpeedCtrlUnit.BrakeInterventionBraking) - pos = Handle->GetPos(bh_FB); + pos = brakes.driverValve->GetPos(bh_FB); if (SpeedCtrlUnit.BrakeInterventionUnbraking) - pos = Handle->GetPos(bh_RP); + pos = brakes.driverValve->GetPos(bh_RP); } return pos; } @@ -1088,7 +1088,7 @@ double physics::Vehicle::MainValveHandlePosition() const void physics::Vehicle::UpdateEmergencyValve(double dt) { // ulepszony hamulec bezp. - EmergencyValveFlow = 0.0; + brakes.emergencyValve.flow = 0.0; // EngDmgFlag 32 (load destroyed) used to trigger this too; dropped, it has nothing to do with @@ -1096,39 +1096,39 @@ void physics::Vehicle::UpdateEmergencyValve(double dt) // vents the pipe only from the vehicle driven from, whatever the controllers of the others show. // a vehicle prepared for hauling (PulleeMode) vents it for nothing of its own, only for the alarm chain, // which a train parting sets too - auto const ownemergency{RadioStopFlag || (EIMCtrlEmergency && LocalBrakePosA >= 1.0) || (IsMainCtrlEmergencyPos() && IsCabMaster()) || SecuritySystem.is_braking() || + auto const ownemergency{RadioStopFlag || (EIMCtrlEmergency && brakes.independentPosition >= 1.0) || (IsMainCtrlEmergencyPos() && IsCabMaster()) || SecuritySystem.is_braking() || (brakes.spring.driveEmergencySpeed >= 0 && Vel > brakes.spring.driveEmergencySpeed && brakes.spring.isActive) || (0 == CabActive && (InactiveCabFlag & activation::emergencybrake) != 0)}; - if (AlarmChainFlag || (ownemergency && false == PulleeMode)) + if (brakes.alarmChain || (ownemergency && false == PulleeMode)) { - EmergencyValveFlow = PF(0, brakePipe.pressure, 0.15) * dt; + brakes.emergencyValve.flow = PF(0, brakePipe.pressure, 0.15) * dt; } - dpMainValve += EmergencyValveFlow; + brakes.driverValveFlow += brakes.emergencyValve.flow; } // what the distributor valve gets of the local brake and the load, by its kind void physics::Vehicle::UpdateDistributorSettings() { - switch (BrakeValve) + switch (brakes.distributorType) { case TBrakeValve::K: case TBrakeValve::W: { - if (BrakeLocHandle != TBrakeHandle::NoHandle) + if (brakes.independentValveType != TBrakeHandle::NoHandle) { - LocBrakePress = LocHandle->GetCP(); + brakes.independentCylinderPressure = brakes.independentValve->GetCP(); //(Hamulec as TWest).SetLBP(LocBrakePress); - Hamulec->SetLBP(LocBrakePress); + brakes.distributor->SetLBP(brakes.independentCylinderPressure); } - if (MBPM < 2) + if (brakes.maxPressureMass < 2) //(Hamulec as TWest).PLC(MaxBrakePress[LoadFlag]) - Hamulec->PLC(MaxBrakePress[LoadFlag]); + brakes.distributor->PLC(brakes.maxCylinderPressure[brakes.loadSetting]); else //(Hamulec as TWest).PLC(TotalMass); - Hamulec->PLC(TotalMass - Mred); + brakes.distributor->PLC(TotalMass - Mred); break; } @@ -1136,13 +1136,13 @@ void physics::Vehicle::UpdateDistributorSettings() case TBrakeValve::EStED: { - LocBrakePress = LocHandle->GetCP(); + brakes.independentCylinderPressure = brakes.independentValve->GetCP(); auto const et41or42 = [](train_type const Type) { return Type == train_type::et41 || Type == train_type::et42; }; for (auto const &couplerentry : Couplers) // nie podoba mi się to rozwiązanie, chyba trzeba // dodać jakiś wpis do fizyki na to if (et41or42(TrainType) && couplerentry.Connected != nullptr && et41or42(couplerentry.Connected->TrainType) && couplerentry.CouplingFlag.HasAll(Coupling::control | Coupling::mainHose)) - LocBrakePress = std::max(couplerentry.Connected->LocHandle->GetCP(), LocBrakePress); + brakes.independentCylinderPressure = std::max(couplerentry.Connected->brakes.independentValve->GetCP(), brakes.independentCylinderPressure); // if ((DynamicBrakeFlag) && (EngineType == ElectricInductionMotor)) //{ @@ -1153,29 +1153,29 @@ void physics::Vehicle::UpdateDistributorSettings() // } //(Hamulec as TLSt).SetLBP(LocBrakePress); - Hamulec->SetLBP(LocBrakePress); - if (BrakeValve == TBrakeValve::EStED) + brakes.distributor->SetLBP(brakes.independentCylinderPressure); + if (brakes.distributorType == TBrakeValve::EStED) { - if (MBPM < 2) - Hamulec->PLC(MaxBrakePress[LoadFlag]); + if (brakes.maxPressureMass < 2) + brakes.distributor->PLC(brakes.maxCylinderPressure[brakes.loadSetting]); else - Hamulec->PLC(TotalMass - Mred); + brakes.distributor->PLC(TotalMass - Mred); } break; } case TBrakeValve::CV1_L_TR: { - LocBrakePress = LocHandle->GetCP(); + brakes.independentCylinderPressure = brakes.independentValve->GetCP(); //(Hamulec as TCV1L_TR).SetLBP(LocBrakePress); - Hamulec->SetLBP(LocBrakePress); + brakes.distributor->SetLBP(brakes.independentCylinderPressure); break; } case TBrakeValve::EP2: case TBrakeValve::EP1: { - Hamulec->PLC(TotalMass - Mred); + brakes.distributor->PLC(TotalMass - Mred); break; } case TBrakeValve::ESt3AL2: @@ -1183,28 +1183,28 @@ void physics::Vehicle::UpdateDistributorSettings() case TBrakeValve::ESt4: case TBrakeValve::ESt3: { - if (MBPM < 2) + if (brakes.maxPressureMass < 2) //(Hamulec as TNESt3).PLC(MaxBrakePress[LoadFlag]) - Hamulec->PLC(MaxBrakePress[LoadFlag]); + brakes.distributor->PLC(brakes.maxCylinderPressure[brakes.loadSetting]); else //(Hamulec as TNESt3).PLC(TotalMass); - Hamulec->PLC(TotalMass - Mred); - LocBrakePress = LocHandle->GetCP(); + brakes.distributor->PLC(TotalMass - Mred); + brakes.independentCylinderPressure = brakes.independentValve->GetCP(); //(Hamulec as TNESt3).SetLBP(LocBrakePress); - Hamulec->SetLBP(LocBrakePress); + brakes.distributor->SetLBP(brakes.independentCylinderPressure); break; } case TBrakeValve::KE: { - LocBrakePress = LocHandle->GetCP(); + brakes.independentCylinderPressure = brakes.independentValve->GetCP(); //(Hamulec as TKE).SetLBP(LocBrakePress); - Hamulec->SetLBP(LocBrakePress); - if (MBPM < 2) + brakes.distributor->SetLBP(brakes.independentCylinderPressure); + if (brakes.maxPressureMass < 2) //(Hamulec as TKE).PLC(MaxBrakePress[LoadFlag]) - Hamulec->PLC(MaxBrakePress[LoadFlag]); + brakes.distributor->PLC(brakes.maxCylinderPressure[brakes.loadSetting]); else //(Hamulec as TKE).PLC(TotalMass); - Hamulec->PLC(TotalMass - Mred); + brakes.distributor->PLC(TotalMass - Mred); break; } default: @@ -1222,7 +1222,7 @@ void physics::Vehicle::UpdateEPBrake() { if (EPBrakeControlPowered()) // tu powinien byc jeszcze bezpiecznik EP i baterie - // temp = (Handle as TFVel6).GetCP - EpForce = Handle->GetEP(); + EpForce = brakes.driverValve->GetEP(); else EpForce = 0.0; @@ -1233,7 +1233,7 @@ void physics::Vehicle::UpdateEPBrake() temp1 = 0; if (brakes.emuDynamic.epMinCurrent > 0.001 && abs(Im) > brakes.emuDynamic.epMinCurrent && DynamicBrakeEMUStatus) temp1 = 0; - Hamulec->SetEPS(temp1); + brakes.distributor->SetEPS(temp1); TUHEX_StageActual = static_cast(EpForce); TUHEX_Active = TUHEX_StageActual > 0; // Ra 2014-11: na tym się wysypuje, ale nie wiem, w jakich warunkach @@ -1256,7 +1256,7 @@ void physics::Vehicle::UpdateScndPipePressure(double dt) UpdateSpringBrake(dt); - mainPipe.reservoir->Flow(Hamulec->GetHPFlow(mainPipe.pressure, dt)); + mainPipe.reservoir->Flow(brakes.distributor->GetHPFlow(mainPipe.pressure, dt)); // NOTE: condition disabled to allow the air flow from the main hose to the main tank as well if (/* ( ( Compressor > ScndPipePress ) && ( */ air.mainReservoirVolume > 0.0 /* ) ) || ( TrainType == train_type::emu ) || ( TrainType == train_type::dmu ) */) { @@ -1283,7 +1283,7 @@ void physics::Vehicle::UpdateScndPipePressure(double dt) // ************************************************************************************************* void physics::Vehicle::UpdateSpringBrake(double /*dt*/) { - double BP = brakes.spring.pneumaticConnection ? BrakePress : 0; + double BP = brakes.spring.pneumaticConnection ? brakes.cylinderPressure : 0; double MSP = brakes.spring.shutOff ? 0 : brakes.spring.maxSetPressure; if (!brakes.spring.activate) { @@ -1352,7 +1352,7 @@ double physics::Vehicle::GetDVc(double dt) if (Couplers[0].Connected != nullptr && Couplers[0].CouplingFlag.HasAll(Coupling::brakeHose)) { //*0.85 c = Couplers[0].Connected; // skrot //0.08 //e/D * L/D = e/D^2 * L - dv1 = 0.5 * dt * PF(brakePipe.pressure, neighbour_pipe_pressure(*c, c->brakePipe.pressure, *c->brakePipe.reservoir), Spg / (1.0 + 0.015 / Spg * Dim.L)); + dv1 = 0.5 * dt * PF(brakePipe.pressure, neighbour_pipe_pressure(*c, c->brakePipe.pressure, *c->brakePipe.reservoir), brakes.pipeSection / (1.0 + 0.015 / brakes.pipeSection * Dim.L)); c->brakePipe.reservoir->Flow(-dv1); if (pipe_wakes(dv1, brakePipe.pressure, *c->brakePipe.reservoir)) c->switch_physics(true, wake_cause::mainpipe); @@ -1361,7 +1361,7 @@ double physics::Vehicle::GetDVc(double dt) if (Couplers[1].Connected != nullptr && Couplers[1].CouplingFlag.HasAll(Coupling::brakeHose)) { c = Couplers[1].Connected; // skrot - dv2 = 0.5 * dt * PF(brakePipe.pressure, neighbour_pipe_pressure(*c, c->brakePipe.pressure, *c->brakePipe.reservoir), Spg / (1.0 + 0.015 / Spg * Dim.L)); + dv2 = 0.5 * dt * PF(brakePipe.pressure, neighbour_pipe_pressure(*c, c->brakePipe.pressure, *c->brakePipe.reservoir), brakes.pipeSection / (1.0 + 0.015 / brakes.pipeSection * Dim.L)); c->brakePipe.reservoir->Flow(-dv2); if (pipe_wakes(dv2, brakePipe.pressure, *c->brakePipe.reservoir)) c->switch_physics(true, wake_cause::mainpipe); @@ -1434,7 +1434,7 @@ struct train_pipe train_pipe const brake_pipe{&physics::Vehicle::brakePipe, Coupling::brakeHose, &physics::Vehicle::GetDVc, - [](physics::Vehicle const &Vehicle) { return Vehicle.Spg / (1.0 + 0.015 / Vehicle.Spg * Vehicle.Dim.L); }}; + [](physics::Vehicle const &Vehicle) { return Vehicle.brakes.pipeSection / (1.0 + 0.015 / Vehicle.brakes.pipeSection * Vehicle.Dim.L); }}; // the main reservoir pipe, GetScndDVc() train_pipe const main_reservoir_pipe{&physics::Vehicle::mainPipe, Coupling::mainHose, diff --git a/physics/components/securitysystem.cpp b/physics/components/securitysystem.cpp index ed943661c..7eef7086b 100644 --- a/physics/components/securitysystem.cpp +++ b/physics/components/securitysystem.cpp @@ -266,7 +266,7 @@ void physics::Vehicle::SecuritySystemCheck(double dt) bool physics::Vehicle::RadiostopSwitch(bool Switch) { bool EBS; - if (BrakeSystem != TBrakeSystem::Individual && BrakeCtrlPosNo > 0) + if (brakes.kind != TBrakeSystem::Individual && brakes.handlePositions > 0) { if (true == Switch && false == RadioStopFlag) diff --git a/physics/components/setup.cpp b/physics/components/setup.cpp index cbd4e4b98..9d2ee49db 100644 --- a/physics/components/setup.cpp +++ b/physics/components/setup.cpp @@ -71,16 +71,16 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) // WriteLogSS("aa ok", BoolToYN(OK)); } - if (BrakeSystem == TBrakeSystem::Individual && BrakeSubsystem != TBrakeSubSystem::ss_None) + if (brakes.kind == TBrakeSystem::Individual && brakes.subsystem != TBrakeSubSystem::ss_None) OK = false; //! - if (BrakeVVolume == 0 && MaxBrakePress[3] > 0 && BrakeSystem != TBrakeSystem::Individual) + if (brakes.valveVolume == 0 && brakes.maxCylinderPressure[3] > 0 && brakes.kind != TBrakeSystem::Individual) { - BrakeVVolume = MaxBrakePress[3] / (5.0 - MaxBrakePress[3]) * (BrakeCylRadius * BrakeCylRadius * BrakeCylDist * BrakeCylNo * M_PI) * 1000; + brakes.valveVolume = brakes.maxCylinderPressure[3] / (5.0 - brakes.maxCylinderPressure[3]) * (brakes.cylinders.radius * brakes.cylinders.radius * brakes.cylinders.stroke * brakes.cylinders.count * M_PI) * 1000; } - if (BrakeVVolume == 0.0) + if (brakes.valveVolume == 0.0) { - BrakeVVolume = 0.01; + brakes.valveVolume = 0.01; } // WriteLog("BVV = " + FloatToStr(BrakeVVolume)); @@ -129,23 +129,23 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) } ActFlowSpeed = 0.0; - BrakeCtrlPosR = BrakeCtrlPos; + brakes.handlePositionReal = brakes.handlePosition; - if (BrakeLocHandle == TBrakeHandle::Knorr) - LocalBrakePosA = 0.5; + if (brakes.independentValveType == TBrakeHandle::Knorr) + brakes.independentPosition = 0.5; brakePipe.reservoir->CreatePress(brakePipe.pressure); mainPipe.reservoir->CreatePress(mainPipe.pressure); brakePipe.reservoir->Act(); mainPipe.reservoir->Act(); - EqvtPipePress = brakePipe.pressure; + brakes.equivalentPipePressure = brakePipe.pressure; - Handle->Init(brakePipe.pressure); + brakes.driverValve->Init(brakePipe.pressure); ComputeConstans(); - if (LoadFlag > 0) + if (brakes.loadSetting > 0) { if (LoadAmount < MaxLoad * 0.45) @@ -165,30 +165,30 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) } // taki mini automat - powinno byc ladnie dobrze :) - BrakeDelayFlag = bdelay_P; - if (TestFlag(BrakeDelays, bdelay_G) && !TestFlag(BrakeDelays, bdelay_R)) - BrakeDelayFlag = bdelay_G; - if (TestFlag(BrakeDelays, bdelay_R) && !TestFlag(BrakeDelays, bdelay_G)) - BrakeDelayFlag = bdelay_R; + brakes.delaySetting = bdelay_P; + if (TestFlag(brakes.availableDelays, bdelay_G) && !TestFlag(brakes.availableDelays, bdelay_R)) + brakes.delaySetting = bdelay_G; + if (TestFlag(brakes.availableDelays, bdelay_R) && !TestFlag(brakes.availableDelays, bdelay_G)) + brakes.delaySetting = bdelay_R; /* // disabled, as test mode is used in specific situations and not really a default if (BrakeOpModes & bom_PS) BrakeOpModeFlag = bom_PS; else */ - BrakeOpModeFlag = bom_PN; + brakes.operatingMode = bom_PN; // yB: jesli pojazdy nie maja zadeklarowanych czasow, to wsadz z przepisow +-16,(6)% std::array const DefBrakeTable{15, 4, 25, 25, 13, 3, 12, 2}; for (int b = 1; b < 4; b++) { - if (BrakeDelay[b] == 0) - BrakeDelay[b] = DefBrakeTable[b]; - BrakeDelay[b] = BrakeDelay[b] * (2.5 + Random(0.0, 0.2)) / 3.0; + if (brakes.delays[b] == 0) + brakes.delays[b] = DefBrakeTable[b]; + brakes.delays[b] = brakes.delays[b] * (2.5 + Random(0.0, 0.2)) / 3.0; } - Hamulec->Init(brakePipe.pressure, HighPipePress, LowPipePress, BrakePress, BrakeDelayFlag); + brakes.distributor->Init(brakePipe.pressure, brakes.pipeHighPressure, brakes.pipeLowPressure, brakes.cylinderPressure, brakes.delaySetting); /* ScndPipePress = Compressor; */ @@ -221,28 +221,28 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) // the distributor valve of the vehicle's kind void physics::Vehicle::CreateBrakeValve() { - switch (BrakeValve) + switch (brakes.distributorType) { case TBrakeValve::W: case TBrakeValve::K: { WriteLog("XBT W, K"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - if (MBPM < 2) // jesli przystawka wazaca - Hamulec->SetLP(0, MaxBrakePress[3], 0); + brakes.distributor = std::make_shared(brakes.maxCylinderPressure[3], brakes.cylinders.radius, brakes.cylinders.stroke, brakes.valveVolume, brakes.cylinders.count, brakes.availableDelays, brakes.method, NAxles, brakes.blocksPerAxle); + if (brakes.maxPressureMass < 2) // jesli przystawka wazaca + brakes.distributor->SetLP(0, brakes.maxCylinderPressure[3], 0); else - Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]); + brakes.distributor->SetLP(Mass, brakes.maxPressureMass, brakes.maxCylinderPressure[1]); break; } case TBrakeValve::KE: { WriteLog("XBT WKE"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - Hamulec->SetRM(RapidMult); - if (MBPM < 2) // jesli przystawka wazaca - Hamulec->SetLP(0, MaxBrakePress[3], 0); + brakes.distributor = std::make_shared(brakes.maxCylinderPressure[3], brakes.cylinders.radius, brakes.cylinders.stroke, brakes.valveVolume, brakes.cylinders.count, brakes.availableDelays, brakes.method, NAxles, brakes.blocksPerAxle); + brakes.distributor->SetRM(brakes.rapidRatio); + if (brakes.maxPressureMass < 2) // jesli przystawka wazaca + brakes.distributor->SetLP(0, brakes.maxCylinderPressure[3], 0); else - Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]); + brakes.distributor->SetLP(Mass, brakes.maxPressureMass, brakes.maxCylinderPressure[1]); break; } case TBrakeValve::NESt3: @@ -251,151 +251,151 @@ void physics::Vehicle::CreateBrakeValve() case TBrakeValve::ESt4: { WriteLog("XBT NESt3, ESt3, ESt3AL2, ESt4"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - static_cast(Hamulec.get())->SetSize(BrakeValveSize, BrakeValveParams); - if (MBPM < 2) // jesli przystawka wazaca - Hamulec->SetLP(0, MaxBrakePress[3], 0); + brakes.distributor = std::make_shared(brakes.maxCylinderPressure[3], brakes.cylinders.radius, brakes.cylinders.stroke, brakes.valveVolume, brakes.cylinders.count, brakes.availableDelays, brakes.method, NAxles, brakes.blocksPerAxle); + static_cast(brakes.distributor.get())->SetSize(brakes.distributorSize, brakes.distributorParameters); + if (brakes.maxPressureMass < 2) // jesli przystawka wazaca + brakes.distributor->SetLP(0, brakes.maxCylinderPressure[3], 0); else - Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]); + brakes.distributor->SetLP(Mass, brakes.maxPressureMass, brakes.maxCylinderPressure[1]); break; } case TBrakeValve::LSt: { WriteLog("XBT LSt"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - Hamulec->SetRM(RapidMult); + brakes.distributor = std::make_shared(brakes.maxCylinderPressure[3], brakes.cylinders.radius, brakes.cylinders.stroke, brakes.valveVolume, brakes.cylinders.count, brakes.availableDelays, brakes.method, NAxles, brakes.blocksPerAxle); + brakes.distributor->SetRM(brakes.rapidRatio); break; } case TBrakeValve::EStED: { WriteLog("XBT EStED"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - Hamulec->SetRM(RapidMult); - if (MBPM < 2) + brakes.distributor = std::make_shared(brakes.maxCylinderPressure[3], brakes.cylinders.radius, brakes.cylinders.stroke, brakes.valveVolume, brakes.cylinders.count, brakes.availableDelays, brakes.method, NAxles, brakes.blocksPerAxle); + brakes.distributor->SetRM(brakes.rapidRatio); + if (brakes.maxPressureMass < 2) { // jesli przystawka wazaca - Hamulec->SetLP(0, MaxBrakePress[3], 0); + brakes.distributor->SetLP(0, brakes.maxCylinderPressure[3], 0); } else { - Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]); + brakes.distributor->SetLP(Mass, brakes.maxPressureMass, brakes.maxCylinderPressure[1]); } break; } case TBrakeValve::EP2: { WriteLog("XBT EP2"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]); + brakes.distributor = std::make_shared(brakes.maxCylinderPressure[3], brakes.cylinders.radius, brakes.cylinders.stroke, brakes.valveVolume, brakes.cylinders.count, brakes.availableDelays, brakes.method, NAxles, brakes.blocksPerAxle); + brakes.distributor->SetLP(Mass, brakes.maxPressureMass, brakes.maxCylinderPressure[1]); break; } case TBrakeValve::EP1: { WriteLog("XBT EP1"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]); - Hamulec->SetRM(RapidMult); + brakes.distributor = std::make_shared(brakes.maxCylinderPressure[3], brakes.cylinders.radius, brakes.cylinders.stroke, brakes.valveVolume, brakes.cylinders.count, brakes.availableDelays, brakes.method, NAxles, brakes.blocksPerAxle); + brakes.distributor->SetLP(Mass, brakes.maxPressureMass, brakes.maxCylinderPressure[1]); + brakes.distributor->SetRM(brakes.rapidRatio); break; } case TBrakeValve::CV1: { WriteLog("XBT CV1"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); + brakes.distributor = std::make_shared(brakes.maxCylinderPressure[3], brakes.cylinders.radius, brakes.cylinders.stroke, brakes.valveVolume, brakes.cylinders.count, brakes.availableDelays, brakes.method, NAxles, brakes.blocksPerAxle); break; } case TBrakeValve::CV1_L_TR: { WriteLog("XBT CV1_L_T"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); + brakes.distributor = std::make_shared(brakes.maxCylinderPressure[3], brakes.cylinders.radius, brakes.cylinders.stroke, brakes.valveVolume, brakes.cylinders.count, brakes.availableDelays, brakes.method, NAxles, brakes.blocksPerAxle); break; } default: - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); + brakes.distributor = std::make_shared(brakes.maxCylinderPressure[3], brakes.cylinders.radius, brakes.cylinders.stroke, brakes.valveVolume, brakes.cylinders.count, brakes.availableDelays, brakes.method, NAxles, brakes.blocksPerAxle); } - Hamulec->SetASBP(MaxBrakePress[4]); - Hamulec->SetRV(RapidVel); + brakes.distributor->SetASBP(brakes.maxCylinderPressure[4]); + brakes.distributor->SetRV(brakes.rapidSpeed); } // the driver's handle and the local brake handle of the vehicle's kinds void physics::Vehicle::CreateBrakeHandles() { - switch (BrakeHandle) + switch (brakes.driverValveType) { using enum TBrakeHandle; case FV4a: - Handle = std::make_shared(); + brakes.driverValve = std::make_shared(); break; case MHZ_EN57: case MHZ_K8P: - Handle = std::make_shared(); + brakes.driverValve = std::make_shared(); break; case FVel6: - Handle = std::make_shared(); + brakes.driverValve = std::make_shared(); break; case FVE408: - Handle = std::make_shared(); + brakes.driverValve = std::make_shared(); break; case testH: - Handle = std::make_shared(); + brakes.driverValve = std::make_shared(); break; case M394: - Handle = std::make_shared(); + brakes.driverValve = std::make_shared(); break; case Knorr: - Handle = std::make_shared(); + brakes.driverValve = std::make_shared(); break; case St113: - Handle = std::make_shared(); + brakes.driverValve = std::make_shared(); break; case MHZ_K5P: - Handle = std::make_shared(); + brakes.driverValve = std::make_shared(); break; case MHZ_6P: - Handle = std::make_shared(); + brakes.driverValve = std::make_shared(); break; default: - Handle = std::make_shared(); + brakes.driverValve = std::make_shared(); } - Handle->SetParams(Handle_AutomaticOverload, Handle_ManualOverload, Handle_GenericDoubleParameter1, Handle_GenericDoubleParameter2, Handle_OverloadMaxPressure, Handle_OverloadPressureDecrease); + brakes.driverValve->SetParams(brakes.driverValveSettings.automaticOverload, brakes.driverValveSettings.manualOverload, brakes.driverValveSettings.genericParameter1, brakes.driverValveSettings.genericParameter2, brakes.driverValveSettings.overloadMaxPressure, brakes.driverValveSettings.overloadPressureDecrease); - switch (BrakeLocHandle) + switch (brakes.independentValveType) { case TBrakeHandle::FD1: { - LocHandle = std::make_shared(); - LocHandle->Init(MaxBrakePress[0]); + brakes.independentValve = std::make_shared(); + brakes.independentValve->Init(brakes.maxCylinderPressure[0]); if (TrainType == train_type::emu) { - dynamic_cast(LocHandle.get())->SetSpeed(3.5); + dynamic_cast(brakes.independentValve.get())->SetSpeed(3.5); } break; } case TBrakeHandle::Knorr: { - LocHandle = std::make_shared(); - LocHandle->Init(MaxBrakePress[0]); + brakes.independentValve = std::make_shared(); + brakes.independentValve->Init(brakes.maxCylinderPressure[0]); break; } default: - LocHandle = std::make_shared(); + brakes.independentValve = std::make_shared(); } } // the brake pipe, the main pipe and the spring brake's cylinder void physics::Vehicle::CreateBrakePipes() { - if (true == TestFlag(BrakeDelays, bdelay_G) && (false == TestFlag(BrakeDelays, bdelay_R) || Power > 1.0)) // ustalanie srednicy przewodu glownego (lokomotywa lub napędowy - Spg = 0.792; + if (true == TestFlag(brakes.availableDelays, bdelay_G) && (false == TestFlag(brakes.availableDelays, bdelay_R) || Power > 1.0)) // ustalanie srednicy przewodu glownego (lokomotywa lub napędowy + brakes.pipeSection = 0.792; else - Spg = 0.507; + brakes.pipeSection = 0.507; // WriteLog("SPG = " + FloatToStr(Spg)); brakePipe.reservoir = std::make_shared(); mainPipe.reservoir = std::make_shared(); // zabezpieczenie, bo sie PG wywala... :( - brakePipe.reservoir->CreateCap((std::max(Dim.L, 14.0) + 0.5) * Spg * 1); // dlugosc x przekroj x odejscia i takie tam - mainPipe.reservoir->CreateCap((std::max(Dim.L, 14.0) + 0.5) * Spg * 1); + brakePipe.reservoir->CreateCap((std::max(Dim.L, 14.0) + 0.5) * brakes.pipeSection * 1); // dlugosc x przekroj x odejscia i takie tam + mainPipe.reservoir->CreateCap((std::max(Dim.L, 14.0) + 0.5) * brakes.pipeSection * 1); if (!brakes.spring.cylinder) { brakes.spring.cylinder = std::make_shared(); @@ -423,13 +423,13 @@ void physics::Vehicle::SetReadyToDepart() WriteLog("Ready to depart"); air.compressedVolume = air.mainReservoirVolume * air.compressor.minPressure * 9.8 / 10.0; mainPipe.pressure = InitialScndPipePress(5.0); - brakePipe.pressure = CntrlPipePress; - BrakePress = 0.0; - LocalBrakePosA = 0.0; + brakePipe.pressure = brakes.controlReservoirPressure; + brakes.cylinderPressure = 0.0; + brakes.independentPosition = 0.0; if (CabActive == 0) - BrakeCtrlPos = static_cast(Handle->GetPos(bh_NP)); + brakes.handlePosition = static_cast(brakes.driverValve->GetPos(bh_NP)); else - BrakeCtrlPos = static_cast(Handle->GetPos(bh_RP)); + brakes.handlePosition = static_cast(brakes.driverValve->GetPos(bh_RP)); /* // NOTE: disabled and left up to the driver, if there's any MainSwitch( false ); @@ -439,7 +439,7 @@ void physics::Vehicle::SetReadyToDepart() */ DirActive = 0; // Dir; //nastawnik kierunkowy - musi być ustawiane osobno! DirAbsolute = DirActive * CabActive; // kierunek jazdy względem sprzęgów - LimPipePress = CntrlPipePress; + brakes.pipeLimiterPressure = brakes.controlReservoirPressure; Battery = BatteryStart != start_t::disabled; } @@ -448,19 +448,19 @@ void physics::Vehicle::SetReadyToDepart() void physics::Vehicle::SetBraked() { WriteLog("Braked"); - Volume = BrakeVVolume * MaxBrakePress[3]; + brakes.reservoirAir = brakes.valveVolume * brakes.maxCylinderPressure[3]; air.compressedVolume = air.mainReservoirVolume * air.compressor.minPressure * 0.55; /* ScndPipePress = 5.1; */ mainPipe.pressure = InitialScndPipePress(5.1); - brakePipe.pressure = LowPipePress; - PipeBrakePress = MaxBrakePress[3] * 0.5; - BrakePress = MaxBrakePress[3] * 0.5; - LocalBrakePosA = 0.0; - BrakeCtrlPos = static_cast(Handle->GetPos(bh_NP)); - LimPipePress = LowPipePress; - if (LocalBrake == TLocalBrake::ManualBrake || MBrake == true) + brakePipe.pressure = brakes.pipeLowPressure; + brakes.pipeCylinderPressure = brakes.maxCylinderPressure[3] * 0.5; + brakes.cylinderPressure = brakes.maxCylinderPressure[3] * 0.5; + brakes.independentPosition = 0.0; + brakes.handlePosition = static_cast(brakes.driverValve->GetPos(bh_NP)); + brakes.pipeLimiterPressure = brakes.pipeLowPressure; + if (brakes.localKind == TLocalBrake::ManualBrake || brakes.hasHandBrake == true) { IncManualBrakeLevel(ManualBrakePosNo); } diff --git a/physics/components/traction.cpp b/physics/components/traction.cpp index f0e33a702..ffbb6fae5 100644 --- a/physics/components/traction.cpp +++ b/physics/components/traction.cpp @@ -113,7 +113,7 @@ double physics::Vehicle::Current(double n, double U) } // writepaslog("MotorCurrent ", FloatToStr(MotorCurrent)); - if (DynamicBrakeType == dbrake_switch && (BrakePress > 2.0 || brakePipe.pressure < 3.6)) + if (DynamicBrakeType == dbrake_switch && (brakes.cylinderPressure > 2.0 || brakePipe.pressure < 3.6)) { Im = 0; // Im:=0; @@ -135,9 +135,9 @@ void physics::Vehicle::UpdateSeriesMotorDynamicBrakeFlag() // i dzialanie hamulca ED w EP09 if (DynamicBrakeType == dbrake_automatic && TrainType != train_type::emu) { - if ((Hamulec->GetEDBCP() < 0.25 && Vadd < 1) || BrakePress > 2.1) + if ((brakes.distributor->GetEDBCP() < 0.25 && Vadd < 1) || brakes.cylinderPressure > 2.1) DynamicBrakeFlag = false; - else if (BrakePress > 0.25 && Hamulec->GetEDBCP() > 0.25) + else if (brakes.cylinderPressure > 0.25 && brakes.distributor->GetEDBCP() > 0.25) DynamicBrakeFlag = true; DynamicBrakeFlag = DynamicBrakeFlag && Power110vIsAvailable; } @@ -153,12 +153,12 @@ void physics::Vehicle::UpdateSeriesMotorDynamicBrakeFlag() // if (BrakeSubsystem == ss_LSt) // zrobiona funkcja virtualna if (DynamicBrakeFlag) { - Hamulec->SetED(abs(Im / 350)); // hamulec ED na EP09 dziala az do zatrzymania lokomotywy + brakes.distributor->SetED(abs(Im / 350)); // hamulec ED na EP09 dziala az do zatrzymania lokomotywy //- WriteLog("A"); } else { - Hamulec->SetED(0); + brakes.distributor->SetED(0); //- WriteLog("B"); } } @@ -774,7 +774,7 @@ void physics::Vehicle::SeriesMotorDynamicBrake(double dt) break; } } - if (Vadd + abs(Im) > TUHEX_Sum + TUHEX_Diff || Hamulec->GetEDBCP() < 0.25 || TUHEX_ResChange || (TUHEX_StageActual == 0 && TUHEX_Stages > 0)) + if (Vadd + abs(Im) > TUHEX_Sum + TUHEX_Diff || brakes.distributor->GetEDBCP() < 0.25 || TUHEX_ResChange || (TUHEX_StageActual == 0 && TUHEX_Stages > 0)) { Vadd -= 500.0 * dt; if (Vadd < TUHEX_MinIw) @@ -1144,7 +1144,7 @@ void physics::Vehicle::SpeedControlByTime(double dt) void physics::Vehicle::InductionMotorBrakeBlending(double const ActiveInverters, double &PosRatio, double &tmp) { InductionMotorDynamicBrakeFlag(); - auto const edBCP{Hamulec->GetEDBCP() * inductionMotor.braking.cylinderPressureGain}; // stala napedu + auto const edBCP{brakes.distributor->GetEDBCP() * inductionMotor.braking.cylinderPressureGain}; // stala napedu if (DynamicBrakeFlag) { PosRatio = InductionMotorBrakeRatio(ActiveInverters, edBCP); @@ -1163,7 +1163,7 @@ void physics::Vehicle::InductionMotorBrakeBlending(double const ActiveInverters, PosRatio = std::min(PosRatio, std::max(-1, 0.5 * (ScndCtrlActualPos * 2 - Vel))); */ // PosRatio = 1.0 * (PosRatio * 0 + 1) * PosRatio; // 1 * 1 * PosRatio = PosRatio - Hamulec->SetED(0); + brakes.distributor->SetED(0); // (Hamulec as TLSt).SetLBP(LocBrakePress); tmp = 4; // szybkie malenie, powolne wzrastanie } @@ -1173,8 +1173,8 @@ void physics::Vehicle::InductionMotorBrakeBlending(double const ActiveInverters, // brake or its own controller; off without them void physics::Vehicle::InductionMotorDynamicBrakeFlag() { - double const edBCP = Hamulec->GetEDBCP(); - auto const localbrakeactive{CabOccupied != 0 && LocHandle->GetCP() > 0.25}; + double const edBCP = brakes.distributor->GetEDBCP(); + auto const localbrakeactive{CabOccupied != 0 && brakes.independentValve->GetCP() > 0.25}; // gdy SplitEDPneumaticBrake jest aktywne, hamulec pomocniczy (LocalBrake) NIE wymusza // zalaczenia hamulca elektrodynamicznego - ED jest sterowany wlasnym nastawnikiem auto const dynbrakectrlactive{SplitEDPneumaticBrake && DynamicBrakeRatio() > 0.01 && DynamicBrakeAvailable()}; @@ -1185,9 +1185,9 @@ void physics::Vehicle::InductionMotorDynamicBrakeFlag() DynamicBrakeFlag = true; } else if ((edBCP < 0.25 && false == localbrakeforED && false == dynbrakectrlactive && AnPos < 0.01) || - (edBCP < 0.25 && ShuntModeAllow && false == dynbrakectrlactive && LocalBrakePosA < 0.01)) + (edBCP < 0.25 && ShuntModeAllow && false == dynbrakectrlactive && brakes.independentPosition < 0.01)) DynamicBrakeFlag = false; - else if (BrakePress > 0.25 && edBCP > 0.25 || localbrakeforED || AnPos > 0.02 || dynbrakectrlactive) + else if (brakes.cylinderPressure > 0.25 && edBCP > 0.25 || localbrakeforED || AnPos > 0.02 || dynbrakectrlactive) DynamicBrakeFlag = true; } @@ -1199,7 +1199,7 @@ double physics::Vehicle::InductionMotorBrakeRatio(double const ActiveInverters, // ustalanie współczynnika blendingu do luzowania hamulca PN if (inductionMotor.state.maxForce * Sign(V) * DirAbsolute < -1) { - PosRatio = -Sign(V) * DirAbsolute * inductionMotor.state.force / (inductionMotor.braking.maxForce * std::max(edBCP, std::max(0.01, Hamulec->GetEDBCP())) / MaxBrakePress[0]); + PosRatio = -Sign(V) * DirAbsolute * inductionMotor.state.force / (inductionMotor.braking.maxForce * std::max(edBCP, std::max(0.01, brakes.distributor->GetEDBCP())) / brakes.maxCylinderPressure[0]); PosRatio = std::clamp(PosRatio, 0.0, 1.0); } else @@ -1209,9 +1209,9 @@ double physics::Vehicle::InductionMotorBrakeRatio(double const ActiveInverters, PosRatio = static_cast(Round(20.0 * PosRatio)) / 20.0; // stopniowanie PN/ED if (PosRatio < 19.5 / 20.0) PosRatio *= 0.9; - Hamulec->SetED(std::max(0.0, std::min(PosRatio, 1.0))); // ustalenie stopnia zmniejszenia ciśnienia + brakes.distributor->SetED(std::max(0.0, std::min(PosRatio, 1.0))); // ustalenie stopnia zmniejszenia ciśnienia // ustalanie siły hamowania ED - if (Hamulec->GetEDBCP() > 0.25 && inductionMotor.braking.cylinderPressureGain < 0.001 || ActiveInverters < inductionMotor.inverterCount) // jeśli PN wyłącza ED + if (brakes.distributor->GetEDBCP() > 0.25 && inductionMotor.braking.cylinderPressureGain < 0.001 || ActiveInverters < inductionMotor.inverterCount) // jeśli PN wyłącza ED { PosRatio = 0; inductionMotor.state.forceDemand = 0; @@ -1225,13 +1225,13 @@ double physics::Vehicle::InductionMotorBrakeRatio(double const ActiveInverters, // w trybie split LocalBrake nie zaleca ED; uzywany jest DynamicBrakeCtrl // oraz zwykle zapotrzebowanie z hamulca zespolonego (edBCP) double const edLeverDemand = DynamicBrakeRatio(); - PosRatio = -std::max(std::max(edLeverDemand, std::min(edBCP / MaxBrakePress[0], 1.0)), AnPos) * vhRamp; - inductionMotor.state.forceDemand = -std::min(1.0, std::max(edLeverDemand, edBCP / MaxBrakePress[0])); + PosRatio = -std::max(std::max(edLeverDemand, std::min(edBCP / brakes.maxCylinderPressure[0], 1.0)), AnPos) * vhRamp; + inductionMotor.state.forceDemand = -std::min(1.0, std::max(edLeverDemand, edBCP / brakes.maxCylinderPressure[0])); } else { - PosRatio = -std::max(std::min(edBCP * 1.0 / MaxBrakePress[0], 1.0), AnPos) * vhRamp; - inductionMotor.state.forceDemand = -std::min(1.0, std::max(LocalBrakeRatio(), edBCP / MaxBrakePress[0])); + PosRatio = -std::max(std::min(edBCP * 1.0 / brakes.maxCylinderPressure[0], 1.0), AnPos) * vhRamp; + inductionMotor.state.forceDemand = -std::min(1.0, std::max(LocalBrakeRatio(), edBCP / brakes.maxCylinderPressure[0])); } } return PosRatio; @@ -1385,7 +1385,7 @@ void physics::Vehicle::InductionMotorOff() { inductionMotor.state = {}; } - Hamulec->SetED(0.0); + brakes.distributor->SetED(0.0); inductionMotor.inverterFrequency = 0.0; //(Hamulec as TLSt).SetLBP(LocBrakePress); } diff --git a/physics/vehicle.h b/physics/vehicle.h index 0510ce0d3..b1016e644 100644 --- a/physics/vehicle.h +++ b/physics/vehicle.h @@ -873,84 +873,22 @@ class Vehicle int BearingType = 1; /*lozyska: 0 - slizgowe, 1 - toczne*/ double ADist = 0.0; double BDist = 0.0; /*odlegosc osi oraz czopow skretu*/ - /*hamulce:*/ - int NBpA = 0; /*ilosc el. ciernych na os: 0 1 2 lub 4*/ int SandCapacity = 0; /*zasobnik piasku [kg]*/ - TBrakeSystem BrakeSystem = TBrakeSystem::Individual; /*rodzaj hamulca zespolonego*/ - TBrakeSubSystem BrakeSubsystem = TBrakeSubSystem::ss_None; - TBrakeValve BrakeValve = TBrakeValve::NoValve; - TBrakeHandle BrakeHandle = TBrakeHandle::NoHandle; - TBrakeHandle BrakeLocHandle = TBrakeHandle::NoHandle; - bool LocHandleTimeTraxx = false; /*hamulec dodatkowy typu traxx*/ - double MBPM = 1.0; /*masa najwiekszego cisnienia*/ int wiperSwitchPos = 0; // pozycja przelacznika wycieraczek double WiperAngle = {45.0}; // kat pracy wycieraczek - std::shared_ptr Hamulec; - std::shared_ptr Handle; - std::shared_ptr LocHandle; TrainPipe brakePipe; // the brake pipe along the train TrainPipe mainPipe; // the main reservoir pipe along the train AirSupply air; // the compressor and the main reservoir (physics/components/airsupply.h) Braking brakes; // the blending, the holding brake, the spring brake (physics/components/braking.h) - TLocalBrake LocalBrake = TLocalBrake::NoBrake; /*rodzaj hamulca indywidualnego*/ - TBrakePressureTable BrakePressureTable; /*wyszczegolnienie cisnien w rurze*/ - TBrakePressure BrakePressureActual; // wartości ważone dla aktualnej pozycji kranu - int ASBType = 0; /*0: brak hamulca przeciwposlizgowego, 1: reczny, 2: automat*/ - int UniversalBrakeButtonFlag[3] = {0, 0, 0}; /* mozliwe działania przycisków hamulcowych */ int UniversalResetButtonFlag[3] = {0, 0, 0}; // customizable reset buttons assignments int TurboTest = 0; bool batterySwAlreadyFired = false; // czy przycisk baterii juz zostal wcisniety bool isBatteryButtonImpulse = false; // czy przelacznik baterii traktowac jako pojedynczy przycisk bool shouldHoldBatteryButton = false; // czy nalezy przytrzymac przycisk baterii aby wlaczyc/wylaczyc baterie float BatteryButtonHoldTime = 1.f; // minimalny czas przytrzymania przycisku baterii - double MaxBrakeForce = 0.0; /*maksymalna sila nacisku hamulca*/ - double MaxBrakePress[5]; // pomocniczy, proz, sred, lad, pp - double P2FTrans = 0.0; - double TrackBrakeForce = 0.0; /*sila nacisku hamulca szynowego*/ - int BrakeMethod = 0; /*flaga rodzaju hamulca*/ - bool Handle_AutomaticOverload = false; // automatyczna asymilacja na pozycji napelniania - bool Handle_ManualOverload = false; // reczna asymilacja na guzik - double Handle_GenericDoubleParameter1 = 0.0; - double Handle_GenericDoubleParameter2 = 0.0; - double Handle_OverloadMaxPressure = 1.0; // maksymalne zwiekszenie cisnienia przy asymilacji - double Handle_OverloadPressureDecrease = 0.002; // predkosc spadku cisnienia przy asymilacji - /*max. cisnienie w cyl. ham., stala proporcjonalnosci p-K*/ - double HighPipePress = 0.0; - double LowPipePress = 0.0; - double DeltaPipePress = 0.0; - /*max. i min. robocze cisnienie w przewodzie glownym oraz roznica miedzy nimi*/ - double CntrlPipePress = 0.0; // ciśnienie z zbiorniku sterującym - double BrakeVolume = 0.0; - double BrakeVVolume = 0.0; - /*pojemnosc powietrza w ukladzie hamulcowym, w ukladzie glownej sprezarki [m^3] */ - int BrakeCylNo = 0; /*ilosc cylindrow ham.*/ - double BrakeCylRadius = 0.0; - double BrakeCylDist = 0.0; - double BrakeCylMult[3]; - int LoadFlag = 0; - /*promien cylindra, skok cylindra, przekladnia hamulcowa*/ - double BrakeCylSpring = 0.0; /*suma nacisku sprezyn powrotnych, kN*/ - double BrakeSlckAdj = 0.0; /*opor nastawiacza skoku tloka, kN*/ - double BrakeRigEff = 0.0; /*sprawnosc przekladni dzwigniowej*/ - double RapidMult = 1.0; /*przelozenie rapidu*/ - double RapidVel = 55.0; /*szybkosc przelaczania rapidu*/ - int BrakeValveSize = 0; - std::string BrakeValveParams; - double Spg = 0.0; - double EmergencyValveOn = 0.0; - double EmergencyValveOff = 0.0; - bool EmergencyValveOpen = false; - double EmergencyValveArea = 0.0; - double LockPipeOn = -1.0; - double LockPipeOff = -1.0; - double HandleUnlock = -3.0; - bool EmergencyCutsOffHandle = false; - /*cisnienie wlaczania, zalaczania sprezarki, wydajnosc sprezarki*/ - TBrakeDelayTable BrakeDelay; /*opoznienie hamowania/odhamowania t/o*/ - int BrakeCtrlPosNo = 0; /*ilosc pozycji hamulca*/ /*nastawniki:*/ int MainCtrlPosNo = 0; /*ilosc pozycji nastawnika*/ int ScndCtrlPosNo = 0; @@ -966,7 +904,6 @@ class Vehicle return positions; }()}; int ScndInMain{0}; /*zaleznosc bocznika od nastawnika*/ - bool MBrake = false; /*Czy jest hamulec reczny*/ double maxTachoSpeed = {0.0}; // maksymalna predkosc na tarczce predkosciomierza analogowego bool HideDirStatusWhenMoving{false}; // Czy gasic lampki kierunku powyzej predkosci zdefiniowanej przez HideDirStatusSpeed int HideDirStatusSpeed{1}; // Predkosc od ktorej lampki kierunku sa wylaczane @@ -1204,7 +1141,6 @@ class Vehicle double FTrain = 0.0; double FStand = 0.0; /*! sila pociagowa i oporow ruchu*/ double FTotal = 0.0; /*! calkowita sila dzialajaca na pojazd*/ - double UnitBrakeForce = 0.0; /*!s siła hamowania przypadająca na jeden element*/ double Ntotal = 0.0; /*!s siła nacisku klockow*/ bool SlippingWheels = false; bool SandDose = false; /*! poslizg kol, sypanie piasku*/ @@ -1212,19 +1148,7 @@ class Vehicle bool SandDoseAuto = false; /*piaskowanie automatyczne*/ bool SandDoseAutoAllow = true; /*zezwolenie na automatyczne piaskowanie*/ double Sand = 0.0; /*ilosc piasku*/ - double BrakeSlippingTimer = 0.0; /*pomocnicza zmienna do wylaczania przeciwposlizgu*/ - double dpBrake = 0.0; - double dpPipe = 0.0; - double dpMainValve = 0.0; - double dpLocalValve = 0.0; - double EmergencyValveFlow = 0.0; // air flow through alerter valve during last simulation step /*! przyrosty cisnienia w kroku czasowym*/ - double BrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych*/ - double BrakePressRate = 0.0; // how fast BrakePress changes, averaged over about a second [bar/s], see accelerating() - double LocBrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych z pomocniczego*/ - double PipeBrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych z przewodu*/ - double EqvtPipePress = 0.0; /*!o cisnienie w przewodzie glownym skladu*/ - double Volume = 0.0; /*objetosc spr. powietrza w zbiorniku hamulca*/ double PantVolume = 0.48; /*objetosc spr. powietrza w ukl. pantografu*/ // aby podniesione pantografy opadły w krótkim czasie przy wyłączonej sprężarce bool PantCompFlag = false; /*!o czy wlaczona sprezarka pantografow*/ start_t PantographCompressorStart{start_t::manual}; @@ -1258,35 +1182,18 @@ class Vehicle float DoorsOpenWithPermitAfter{-1.f}; // remote open if permit button is held for specified time. NOTE: separate from door data as its cab control thing int DoorsPermitLightBlinking{0}; // when the doors permit signal light is blinking - int BrakeCtrlPos = -2; /*nastawa hamulca zespolonego*/ - double BrakeCtrlPosR = 0.0; /*nastawa hamulca zespolonego - plynna dla FV4a*/ - double BrakeCtrlPos2 = 0.0; /*nastawa hamulca zespolonego - kapturek dla FV4a*/ - int ManualBrakePos = 0; /*nastawa hamulca recznego*/ - double LocalBrakePosA = 0.0; /*nastawa hamulca pomocniczego*/ - double LocalBrakePosAEIM = 0.0; /*pozycja hamulca pomocniczego ep dla asynchronicznych ezt*/ double DynamicBrakeCtrlPos = 0.0; /*nastawa nastawnika hamulca elektrodynamicznego (0..1) - aktywne tylko gdy SplitEDPneumaticBrake*/ - bool UniversalBrakeButtonActive[3] = {false, false, false}; /* brake button pressed */ /* - int BrakeStatus = b_off; //0 - odham, 1 - ham., 2 - uszk., 4 - odluzniacz, 8 - antyposlizg, 16 - uzyte EP, 32 - pozycja R, 64 - powrot z R */ - bool AlarmChainFlag = false; // manual emergency brake bool RadioStopFlag = false; /*hamowanie nagle*/ - bool LockPipe = false; /*locking brake pipe in emergency state*/ - bool UnlockPipe = false; /*unlockig brake pipe button pressed*/ - int BrakeDelayFlag = 0; /*nastawa opoznienia ham. osob/towar/posp/exp 0/1/2/4*/ - int BrakeDelays = 0; /*nastawy mozliwe do uzyskania*/ // the AI wagon inspector cut the brake out (b_dmg) and puts it back when the train no longer needs it // cut out (brake_setting::apply). Anyone else cutting it out or putting it back takes it over - bool BrakeCutOutByInspector = false; - int BrakeOpModeFlag = 0; /*nastawa trybu pracy PS/PN/EP/MED 1/2/4/8*/ - int BrakeOpModes = 0; /*nastawy mozliwe do uzyskania*/ bool DynamicBrakeFlag = false; /*czy wlaczony hamulec elektrodymiczny*/ bool DynamicBrakeEMUStatus = true; /*czy hamulec ED dziala w ezt*/ int TUHEX_StageActual = 0; /*aktualny stopien tuhexa*/ bool TUHEX_ResChange = false; /*czy zmiana rezystancji hamowania ED - odwzbudzanie*/ bool TUHEX_Active = false; /*czy hamowanie ED wywołane z zewnątrz*/ // NapUdWsp: integer; - double LimPipePress = 0.0; /*stabilizator cisnienia*/ double ActFlowSpeed = 0.0; /*szybkosc stabilizatora*/ DamageSet DamageFlag; // the damage of the vehicle @@ -1469,7 +1376,6 @@ class Vehicle double FrictConst2d = 0.0; double TotalMassxg = 0.0; /*TotalMass*g*/ - double fBrakeCtrlPos = -2.0; // płynna nastawa hamulca zespolonego bool bPantKurek3 = true; // kurek trójdrogowy (pantografu): true=połączenie z ZG, false=połączenie z małą sprężarką // domyślnie zbiornik pantografu połączony jest ze zbiornikiem głównym bool PantAutoValve{false}; // type of installed pantograph compressor valve int iProblem = 0; // flagi problemów z taborem, aby AI nie musiało porównywać; 0=może jechać @@ -1893,7 +1799,7 @@ class Vehicle // the pressure switch, when fitted, cuts the start off and puts them out, otherwise they go out once the brakes are applied bool MainCircuitLampsEnabled() const { - return false == ControlPressureSwitch && (HasControlPressureSwitch || BrakePress < 1.0); + return false == ControlPressureSwitch && (HasControlPressureSwitch || brakes.cylinderPressure < 1.0); } // whether an emergency brake application holds the line breaker open: the brake pipe below the pressure taken for one // (EmergencyBrakeMainOffPressure) while the master controller is on a power position @@ -1936,7 +1842,7 @@ class Vehicle // car, as the EN57 s car does). it's the vehicle type's, unlike the cab the scenario puts a driver in bool HasDriverCab() const { - return BrakeHandle != TBrakeHandle::NoHandle; + return brakes.driverValveType != TBrakeHandle::NoHandle; } // whether the cab command opening the main circuit opens it where the only cab switch of the circuit is the button // closing it: on a diesel that's the starter button, and the command is the one way to stop an engine whose fuel pump diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index a65181405..e7821ddb6 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -84,7 +84,7 @@ std::uint32_t devices_of(physics::Vehicle const &Occupied, physics::Vehicle cons on(Occupied.DepartureSignal, device::departure_signal) | on(Occupied.Doors.instances[VehicleSide::left].open_permit, device::door_permit_left) | on(Occupied.Doors.instances[VehicleSide::right].open_permit, device::door_permit_right) | on(Occupied.Doors.step_enabled, device::door_step) | on(Occupied.Doors.lock_enabled, device::door_lock) | on(Occupied.Doors.is_locked, device::doors_locked) | - on(Occupied.Hamulec != nullptr && Occupied.Hamulec->Releaser(), device::brake_releaser) | on(Controlling.FuelPump.is_active, device::fuel_pump) | + on(Occupied.brakes.distributor != nullptr && Occupied.brakes.distributor->Releaser(), device::brake_releaser) | on(Controlling.FuelPump.is_active, device::fuel_pump) | on(Controlling.OilPump.is_active, device::oil_pump) | on(Controlling.MotorBlowers[VehicleEnd::front].is_active || Controlling.MotorBlowers[VehicleEnd::rear].is_active, device::motor_blowers) | on(Controlling.diesel.heat.engine_is_hot, device::engine_hot) | on(Controlling.SpeedCtrl && Controlling.SpeedCtrlUnit.IsActive, device::speed_control); @@ -446,13 +446,13 @@ void blackbox_recorder::write_cab() { sample.flags = (FreeFlyModeFlag ? 0 : blackbox::cab_flags::in_cab) | (owner != nullptr && owner->is_active() ? blackbox::cab_flags::ai_valid : 0) | (controlling->SecuritySystem.is_blinking() ? blackbox::cab_flags::alerter_blinking : 0) | (controlling->SecuritySystem.is_beeping() ? blackbox::cab_flags::alerter_beeping : 0) | (controlling->SlippingWheels ? blackbox::cab_flags::wheel_slip : 0) | - (occupied->RadioStopFlag ? blackbox::cab_flags::radio_stop : 0) | (occupied->AlarmChainFlag ? blackbox::cab_flags::alarm_chain : 0); + (occupied->RadioStopFlag ? blackbox::cab_flags::radio_stop : 0) | (occupied->brakes.alarmChain ? blackbox::cab_flags::alarm_chain : 0); sample.main_controller = static_cast(controlling->MainCtrlPos); sample.scnd_controller = static_cast(controlling->ScndCtrlPos); sample.reverser = static_cast(controlling->DirActive); - sample.train_brake = static_cast(occupied->fBrakeCtrlPos); - sample.local_brake = static_cast(occupied->LocalBrakePosA); - sample.brake_cylinder = static_cast(occupied->BrakePress); + sample.train_brake = static_cast(occupied->brakes.handlePositionSmooth); + sample.local_brake = static_cast(occupied->brakes.independentPosition); + sample.brake_cylinder = static_cast(occupied->brakes.cylinderPressure); sample.brake_pipe = static_cast(occupied->brakePipe.pressure); sample.motor_current = static_cast(controlling->Im); if (owner != nullptr && owner->is_active()) @@ -474,10 +474,10 @@ void blackbox_recorder::write_cab() { sample.cab = static_cast(occupied->CabOccupied); // what drives the train, the setting of the brakes, the radio, the engine's oil and temperatures sample.engine = engine_of(*controlling); - sample.brake_delay = static_cast(occupied->BrakeDelayFlag); + sample.brake_delay = static_cast(occupied->brakes.delaySetting); // the const one: with no driver the first channel sample.radio_channel = static_cast(std::clamp(std::as_const(*train).RadioChannel(), 0, 255)); - sample.driver_valve = occupied->Handle != nullptr ? static_cast(occupied->Handle->GetCP()) : 0.0f; + sample.driver_valve = occupied->brakes.driverValve != nullptr ? static_cast(occupied->brakes.driverValve->GetCP()) : 0.0f; sample.feed_pipe = static_cast(occupied->mainPipe.pressure); sample.oil_pressure = controlling->OilPump.pressure; sample.water_temperature = controlling->diesel.heat.Twy; @@ -485,17 +485,17 @@ void blackbox_recorder::write_cab() { sample.engine_temperature = controlling->diesel.heat.Ts; sample.speed_control_kmh = controlling->SpeedCtrl ? static_cast(controlling->SpeedCtrlUnit.DesiredVelocity) : 0.0f; sample.engine_power = static_cast(controlling->EnginePower); - sample.hand_brake = static_cast(std::clamp(occupied->ManualBrakePos, -128, 127)); - sample.brake_mode = static_cast(occupied->BrakeOpModeFlag); + sample.hand_brake = static_cast(std::clamp(occupied->brakes.handBrakePosition, -128, 127)); + sample.brake_mode = static_cast(occupied->brakes.operatingMode); sample.horn = static_cast(occupied->WarningSignal); sample.integrated_controller = static_cast(controlling->eimic); sample.clutch = static_cast(controlling->diesel.clutchState); sample.converter_fill = static_cast(controlling->torqueConverter.fill); // the brakes of the whole train: the highest of its cylinders, from the head to the tail - auto brakes{occupied->BrakePress}; + auto brakes{occupied->brakes.cylinderPressure}; for (auto const *each{owner != nullptr ? owner->Vehicle(VehicleEnd::front) : nullptr}; each != nullptr; each = each->Next()) if (each->physics != nullptr) - brakes = std::max(brakes, each->physics->BrakePress); + brakes = std::max(brakes, each->physics->brakes.cylinderPressure); sample.consist_brake_cylinder = static_cast(brakes); m_writer->cab(sample); } diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp index 2ff95b8f3..626f6752c 100644 --- a/simulation/simulation.cpp +++ b/simulation/simulation.cpp @@ -244,13 +244,13 @@ void state_manager::process_commands() { TDynamicObject *vehicle = found_vehicle; while (vehicle) { - vehicle->physics->Hamulec->Releaser(commanddata.action != GLFW_RELEASE ? 1 : 0); + vehicle->physics->brakes.distributor->Releaser(commanddata.action != GLFW_RELEASE ? 1 : 0); vehicle = vehicle->Next(); } vehicle = found_vehicle; while (vehicle) { - vehicle->physics->Hamulec->Releaser(commanddata.action != GLFW_RELEASE ? 1 : 0); + vehicle->physics->brakes.distributor->Releaser(commanddata.action != GLFW_RELEASE ? 1 : 0); vehicle = vehicle->Prev(); } } diff --git a/tests/unit/drive.cpp b/tests/unit/drive.cpp index 2470d561a..08868a7a1 100644 --- a/tests/unit/drive.cpp +++ b/tests/unit/drive.cpp @@ -63,7 +63,7 @@ void drive(driven Driven, track const &Track, double Seconds) { } void release_brakes(physics::Vehicle &Cab) { - Cab.BrakeLevelSet(Cab.Handle->GetPos(bh_RP)); + Cab.BrakeLevelSet(Cab.brakes.driverValve->GetPos(bh_RP)); Cab.DecLocalBrakeLevel(LocalBrakePosNo); Cab.DecManualBrakeLevel(ManualBrakePosNo); Cab.SpringBrakeActivate(false); @@ -248,10 +248,10 @@ void drive_cycle(driven Driven, track const &Track, trace &Trace) { drive(Driven, Track, 10.0); Trace.mark("brake"); - cab.BrakeLevelSet(cab.Handle->GetPos(bh_FB)); + cab.BrakeLevelSet(cab.brakes.driverValve->GetPos(bh_FB)); drive(Driven, Track, 60.0); Trace.mark("release"); - cab.BrakeLevelSet(cab.Handle->GetPos(bh_RP)); + cab.BrakeLevelSet(cab.brakes.driverValve->GetPos(bh_RP)); drive(Driven, Track, 20.0); } diff --git a/tests/unit/figures.cpp b/tests/unit/figures.cpp index 4472bfa86..7e9fd110e 100644 --- a/tests/unit/figures.cpp +++ b/tests/unit/figures.cpp @@ -86,7 +86,7 @@ void figures::sample(double Time, physics::Vehicle const &Vehicle) { if (part.pipe_back < 0.0 && part.pipe_lowest < pipe_drop && pipe >= pipe_back) { part.pipe_back = Time - part.start; } - part.cylinders_peak = std::max(part.cylinders_peak, Vehicle.BrakePress); + part.cylinders_peak = std::max(part.cylinders_peak, Vehicle.brakes.cylinderPressure); part.current_peak = std::max(part.current_peak, std::abs(Vehicle.Im)); part.force_peak = std::max(part.force_peak, std::abs(Vehicle.Ft) / 1000.0); @@ -96,7 +96,7 @@ void figures::sample(double Time, physics::Vehicle const &Vehicle) { // which figures the vehicle has, over the whole run, so each part has the same ones m_moved |= std::abs(speed) >= 0.05; m_piped |= pipe >= 0.1; - m_braked |= Vehicle.BrakePress >= 0.005; + m_braked |= Vehicle.brakes.cylinderPressure >= 0.005; m_current |= std::abs(Vehicle.Im) >= 0.5; m_force |= std::abs(Vehicle.Ft) >= 50.0; } diff --git a/tests/unit/golden.cpp b/tests/unit/golden.cpp index 26e6ea254..a011fb0a5 100644 --- a/tests/unit/golden.cpp +++ b/tests/unit/golden.cpp @@ -74,13 +74,13 @@ std::vector traction() { std::vector brakes() { return { - {"BrakeCtrlPos", [](auto const &M) { return M.BrakeCtrlPos; }}, + {"BrakeCtrlPos", [](auto const &M) { return M.brakes.handlePosition; }}, {"PipePress", [](auto const &M) { return M.brakePipe.pressure; }}, - {"BrakePress", [](auto const &M) { return M.BrakePress; }}, - {"LocBrakePress", [](auto const &M) { return M.LocBrakePress; }}, - {"BRP", [](auto const &M) { return M.Hamulec->GetBRP(); }}, - {"VRP", [](auto const &M) { return M.Hamulec->GetVRP(); }}, - {"CRP", [](auto const &M) { return M.Hamulec->GetCRP(); }}, + {"BrakePress", [](auto const &M) { return M.brakes.cylinderPressure; }}, + {"LocBrakePress", [](auto const &M) { return M.brakes.independentCylinderPressure; }}, + {"BRP", [](auto const &M) { return M.brakes.distributor->GetBRP(); }}, + {"VRP", [](auto const &M) { return M.brakes.distributor->GetVRP(); }}, + {"CRP", [](auto const &M) { return M.brakes.distributor->GetCRP(); }}, }; } @@ -94,16 +94,16 @@ std::vector air() { std::vector handles() { std::vector result{ - {"BrakeCtrlPosR", [](auto const &M) { return M.BrakeCtrlPosR; }}, - {"dpMainValve", [](auto const &M) { return M.dpMainValve; }}, - {"HandleCP", [](auto const &M) { return M.Handle->GetCP(); }}, - {"HandleRP", [](auto const &M) { return M.Handle->GetRP(); }}, - {"HandleEP", [](auto const &M) { return M.Handle->GetEP(); }}, - {"LocalBrakePosA", [](auto const &M) { return M.LocalBrakePosA; }}, - {"dpLocalValve", [](auto const &M) { return M.dpLocalValve; }}, + {"BrakeCtrlPosR", [](auto const &M) { return M.brakes.handlePositionReal; }}, + {"dpMainValve", [](auto const &M) { return M.brakes.driverValveFlow; }}, + {"HandleCP", [](auto const &M) { return M.brakes.driverValve->GetCP(); }}, + {"HandleRP", [](auto const &M) { return M.brakes.driverValve->GetRP(); }}, + {"HandleEP", [](auto const &M) { return M.brakes.driverValve->GetEP(); }}, + {"LocalBrakePosA", [](auto const &M) { return M.brakes.independentPosition; }}, + {"dpLocalValve", [](auto const &M) { return M.brakes.independentValveFlow; }}, }; for (int i = 0; i < 5; ++i) { - result.emplace_back(std::format("HandleSound{}", i), [i](auto const &M) { return M.Handle->GetSound(i); }); + result.emplace_back(std::format("HandleSound{}", i), [i](auto const &M) { return M.brakes.driverValve->GetSound(i); }); } return result; } @@ -145,57 +145,57 @@ std::vector parameters() { {"BearingType", [](auto const &M) { return M.BearingType; }}, {"ADist", [](auto const &M) { return M.ADist; }}, {"BDist", [](auto const &M) { return M.BDist; }}, - {"NBpA", [](auto const &M) { return M.NBpA; }}, + {"NBpA", [](auto const &M) { return M.brakes.blocksPerAxle; }}, {"SandCapacity", [](auto const &M) { return M.SandCapacity; }}, - {"BrakeSystem", [](auto const &M) { return static_cast(M.BrakeSystem); }}, - {"BrakeValve", [](auto const &M) { return static_cast(M.BrakeValve); }}, - {"BrakeHandle", [](auto const &M) { return static_cast(M.BrakeHandle); }}, - {"BrakeLocHandle", [](auto const &M) { return static_cast(M.BrakeLocHandle); }}, - {"LocalBrake", [](auto const &M) { return static_cast(M.LocalBrake); }}, - {"ASBType", [](auto const &M) { return M.ASBType; }}, - {"MaxBrakeForce", [](auto const &M) { return M.MaxBrakeForce; }}, - {"P2FTrans", [](auto const &M) { return M.P2FTrans; }}, - {"BrakeMethod", [](auto const &M) { return M.BrakeMethod; }}, - {"HighPipePress", [](auto const &M) { return M.HighPipePress; }}, - {"LowPipePress", [](auto const &M) { return M.LowPipePress; }}, - {"DeltaPipePress", [](auto const &M) { return M.DeltaPipePress; }}, - {"CntrlPipePress", [](auto const &M) { return M.CntrlPipePress; }}, - {"BrakeVolume", [](auto const &M) { return M.BrakeVolume; }}, - {"BrakeVVolume", [](auto const &M) { return M.BrakeVVolume; }}, + {"BrakeSystem", [](auto const &M) { return static_cast(M.brakes.kind); }}, + {"BrakeValve", [](auto const &M) { return static_cast(M.brakes.distributorType); }}, + {"BrakeHandle", [](auto const &M) { return static_cast(M.brakes.driverValveType); }}, + {"BrakeLocHandle", [](auto const &M) { return static_cast(M.brakes.independentValveType); }}, + {"LocalBrake", [](auto const &M) { return static_cast(M.brakes.localKind); }}, + {"ASBType", [](auto const &M) { return M.brakes.antiSlipType; }}, + {"MaxBrakeForce", [](auto const &M) { return M.brakes.maxForce; }}, + {"P2FTrans", [](auto const &M) { return M.brakes.pressureToForce; }}, + {"BrakeMethod", [](auto const &M) { return M.brakes.method; }}, + {"HighPipePress", [](auto const &M) { return M.brakes.pipeHighPressure; }}, + {"LowPipePress", [](auto const &M) { return M.brakes.pipeLowPressure; }}, + {"DeltaPipePress", [](auto const &M) { return M.brakes.pipePressureRange; }}, + {"CntrlPipePress", [](auto const &M) { return M.brakes.controlReservoirPressure; }}, + {"BrakeVolume", [](auto const &M) { return M.brakes.cylinderVolume; }}, + {"BrakeVVolume", [](auto const &M) { return M.brakes.valveVolume; }}, {"VeselVolume", [](auto const &M) { return M.air.mainReservoirVolume; }}, - {"BrakeCylNo", [](auto const &M) { return M.BrakeCylNo; }}, - {"BrakeCylRadius", [](auto const &M) { return M.BrakeCylRadius; }}, - {"BrakeCylDist", [](auto const &M) { return M.BrakeCylDist; }}, - {"BrakeCylSpring", [](auto const &M) { return M.BrakeCylSpring; }}, - {"BrakeSlckAdj", [](auto const &M) { return M.BrakeSlckAdj; }}, - {"BrakeRigEff", [](auto const &M) { return M.BrakeRigEff; }}, - {"RapidMult", [](auto const &M) { return M.RapidMult; }}, - {"RapidVel", [](auto const &M) { return M.RapidVel; }}, - {"BrakeValveSize", [](auto const &M) { return M.BrakeValveSize; }}, + {"BrakeCylNo", [](auto const &M) { return M.brakes.cylinders.count; }}, + {"BrakeCylRadius", [](auto const &M) { return M.brakes.cylinders.radius; }}, + {"BrakeCylDist", [](auto const &M) { return M.brakes.cylinders.stroke; }}, + {"BrakeCylSpring", [](auto const &M) { return M.brakes.cylinders.springForce; }}, + {"BrakeSlckAdj", [](auto const &M) { return M.brakes.cylinders.slackAdjusterForce; }}, + {"BrakeRigEff", [](auto const &M) { return M.brakes.cylinders.riggingEfficiency; }}, + {"RapidMult", [](auto const &M) { return M.brakes.rapidRatio; }}, + {"RapidVel", [](auto const &M) { return M.brakes.rapidSpeed; }}, + {"BrakeValveSize", [](auto const &M) { return M.brakes.distributorSize; }}, {"MinCompressor", [](auto const &M) { return M.air.compressor.minPressure; }}, {"MaxCompressor", [](auto const &M) { return M.air.compressor.maxPressure; }}, {"CompressorSpeed", [](auto const &M) { return M.air.compressor.speed; }}, - {"EmergencyValveOn", [](auto const &M) { return M.EmergencyValveOn; }}, + {"EmergencyValveOn", [](auto const &M) { return M.brakes.emergencyValve.onPressure; }}, {"AirLeakRate", [](auto const &M) { return M.air.leakRate; }}, - {"BrakeCtrlPosNo", [](auto const &M) { return M.BrakeCtrlPosNo; }}, + {"BrakeCtrlPosNo", [](auto const &M) { return M.brakes.handlePositions; }}, {"MainCtrlPosNo", [](auto const &M) { return M.MainCtrlPosNo; }}, {"ScndCtrlPosNo", [](auto const &M) { return M.ScndCtrlPosNo; }}, {"LightsPosNo", [](auto const &M) { return M.LightsPosNo; }}, - {"MBrake", [](auto const &M) { return M.MBrake ? 1.0 : 0.0; }}, + {"MBrake", [](auto const &M) { return M.brakes.hasHandBrake ? 1.0 : 0.0; }}, {"StopBrakeDecc", [](auto const &M) { return M.brakes.holding.deceleration; }}, - {"BrakeDelays", [](auto const &M) { return M.BrakeDelays; }}, - {"BrakeOpModes", [](auto const &M) { return M.BrakeOpModes; }}, + {"BrakeDelays", [](auto const &M) { return M.brakes.availableDelays; }}, + {"BrakeOpModes", [](auto const &M) { return M.brakes.availableOperatingModes; }}, {"Imin", [](auto const &M) { return M.Imin; }}, {"Imax", [](auto const &M) { return M.Imax; }}, {"EIMCtrlType", [](auto const &M) { return M.EIMCtrlType; }}, - {"Volume", [](auto const &M) { return M.Volume; }}, + {"Volume", [](auto const &M) { return M.brakes.reservoirAir; }}, {"PantVolume", [](auto const &M) { return M.PantVolume; }}, }; for (int i = 0; i < 5; ++i) { - result.emplace_back(std::format("MaxBrakePress{}", i), [i](auto const &M) { return M.MaxBrakePress[i]; }); + result.emplace_back(std::format("MaxBrakePress{}", i), [i](auto const &M) { return M.brakes.maxCylinderPressure[i]; }); } for (int i = 0; i < 3; ++i) { - result.emplace_back(std::format("BrakeCylMult{}", i), [i](auto const &M) { return M.BrakeCylMult[i]; }); + result.emplace_back(std::format("BrakeCylMult{}", i), [i](auto const &M) { return M.brakes.cylinders.leverRatio[i]; }); } return result; } diff --git a/tests/unit/invariants.cpp b/tests/unit/invariants.cpp index bbaeefce4..ed3458f88 100644 --- a/tests/unit/invariants.cpp +++ b/tests/unit/invariants.cpp @@ -24,7 +24,7 @@ bool electric(physics::Vehicle const &M) { double max_brake_press(physics::Vehicle const &M) { auto result{0.0}; - for (auto const press : M.MaxBrakePress) { + for (auto const press : M.brakes.maxCylinderPressure) { result = std::max(result, press); } return result; @@ -42,21 +42,21 @@ std::vector const &invariants() { {"every value a number", [](auto const &M, double, auto const *) { std::initializer_list const values{M.V, M.AccS, M.Ft, M.Fb, M.Im, M.Itot, M.EngineVoltage, - M.enrot, M.brakePipe.pressure, M.BrakePress, M.LocBrakePress, M.mainPipe.pressure, M.air.mainReservoirPressure, M.BatteryVoltage}; + M.enrot, M.brakePipe.pressure, M.brakes.cylinderPressure, M.brakes.independentCylinderPressure, M.mainPipe.pressure, M.air.mainReservoirPressure, M.BatteryVoltage}; return std::ranges::all_of(values, [](double const Value) { return std::isfinite(Value); }); }, [](auto const &M) { return values({{"V", M.V}, {"AccS", M.AccS}, {"Ft", M.Ft}, {"Fb", M.Fb}, {"Im", M.Im}, {"Itot", M.Itot}, {"EngineVoltage", M.EngineVoltage}, - {"enrot", M.enrot}, {"PipePress", M.brakePipe.pressure}, {"BrakePress", M.BrakePress}, {"LocBrakePress", M.LocBrakePress}, + {"enrot", M.enrot}, {"PipePress", M.brakePipe.pressure}, {"BrakePress", M.brakes.cylinderPressure}, {"LocBrakePress", M.brakes.independentCylinderPressure}, {"ScndPipePress", M.mainPipe.pressure}, {"Compressor", M.air.mainReservoirPressure}, {"BatteryVoltage", M.BatteryVoltage}}); }}, {"brake cylinders between empty and the vehicle's highest pressure", [](auto const &M, double, auto const *) { // a step overshoots the setting a little: the EU07's LSt fills its cylinders to 4.0 bar of its 3.8 auto const limit{1.1 * max_brake_press(M) + pressure_margin}; - return M.BrakePress >= -pressure_margin && M.BrakePress <= limit && M.LocBrakePress >= -pressure_margin && M.LocBrakePress <= limit; + return M.brakes.cylinderPressure >= -pressure_margin && M.brakes.cylinderPressure <= limit && M.brakes.independentCylinderPressure >= -pressure_margin && M.brakes.independentCylinderPressure <= limit; }, - [](auto const &M) { return values({{"BrakePress", M.BrakePress}, {"LocBrakePress", M.LocBrakePress}, {"max(MaxBrakePress)", max_brake_press(M)}}); }}, + [](auto const &M) { return values({{"BrakePress", M.brakes.cylinderPressure}, {"LocBrakePress", M.brakes.independentCylinderPressure}, {"max(MaxBrakePress)", max_brake_press(M)}}); }}, {"pipes between empty and the highest governor setting", [](auto const &M, double, auto const *) { // all the air comes from the main reservoirs, which the game sets up to 10 bar, some (the Impuls) to 12; @@ -115,8 +115,8 @@ std::vector const &invariants() { }, [](auto const &M) { return values({{"V", M.V}, {"AccS", M.AccS}}); }}, {"hand brake applied, the wheels braked on the move", - [](auto const &M, double, auto const *) { return false == M.MBrake || M.ManualBrakePos == 0 || std::abs(M.V) < 0.5 || std::abs(M.Fb) > 0.0; }, - [](auto const &M) { return values({{"ManualBrakePos", M.ManualBrakePos}, {"V", M.V}, {"Fb", M.Fb}}); }}, + [](auto const &M, double, auto const *) { return false == M.brakes.hasHandBrake || M.brakes.handBrakePosition == 0 || std::abs(M.V) < 0.5 || std::abs(M.Fb) > 0.0; }, + [](auto const &M) { return values({{"ManualBrakePos", M.brakes.handBrakePosition}, {"V", M.V}, {"Fb", M.Fb}}); }}, }; return rules; } diff --git a/tests/unit/test_6dg_power_steps.cpp b/tests/unit/test_6dg_power_steps.cpp index d8444d7e5..e2f834ac8 100644 --- a/tests/unit/test_6dg_power_steps.cpp +++ b/tests/unit/test_6dg_power_steps.cpp @@ -52,10 +52,10 @@ void get_ready(vehicle &Loco, test::track const &Track) { REQUIRE(Loco->DirActive > 0); // the brake pipe was charged during the start-up: the brakes release slowly (about a minute), and the pressure // switch keeps the line contactors open while the brake cylinders hold over 2 bar - for (int second = 0; second < 180 && Loco->BrakePress > 0.1; ++second) { + for (int second = 0; second < 180 && Loco->brakes.cylinderPressure > 0.1; ++second) { test::drive(driven, Track, 1.0); } - REQUIRE(Loco->BrakePress <= 0.1); + REQUIRE(Loco->brakes.cylinderPressure <= 0.1); // the line contactors close on the first position past the ones with no power, as the driver passes it move_to(Loco, lower); test::drive(driven, Track, 1.0); diff --git a/tests/unit/test_brake_cycle.cpp b/tests/unit/test_brake_cycle.cpp index 9598879d8..71db7a97d 100644 --- a/tests/unit/test_brake_cycle.cpp +++ b/tests/unit/test_brake_cycle.cpp @@ -39,7 +39,7 @@ std::map> run_cycle(vehicle &Vehicle, test::tra Trace.mark(stage.name); Vehicle.hold_brake_pipe(stage.pipe); Vehicle.run(stage.seconds); - cylinders[stage.name] = Vehicle->BrakePress; + cylinders[stage.name] = Vehicle->brakes.cylinderPressure; } return cylinders; } @@ -79,7 +79,7 @@ TEST_CASE("brake cycle: every brake delay setting of the real vehicles") { test::reseed_random(); vehicle probe{definition::fiz(path)}; for (auto const delay : {bdelay_G, bdelay_P, bdelay_R, bdelay_R + bdelay_M, bdelay_G + bdelay_M}) { - if ((probe->BrakeDelays & delay) != delay || delay == probe->BrakeDelayFlag) { + if ((probe->brakes.availableDelays & delay) != delay || delay == probe->brakes.delaySetting) { continue; } CAPTURE(delay); @@ -93,7 +93,7 @@ TEST_CASE("brake cycle: every brake delay setting of the real vehicles") { trace.mark(stage.name); real.hold_brake_pipe(stage.pipe); real.run(stage.seconds); - cylinders[stage.name] = real->BrakePress; + cylinders[stage.name] = real->brakes.cylinderPressure; } // every setting brakes in half a minute and releases in a minute CHECK(cylinders["full service"] > 1.0); @@ -136,7 +136,7 @@ TEST_CASE("brake cycle: the rapid setting at speed, the anti-slip brake and the vehicle real{definition::fiz(path), 160.0}; real->DecManualBrakeLevel(ManualBrakePosNo); real->BrakeDelaySwitch(delay); // false when already set - REQUIRE(real->BrakeDelayFlag == delay); + REQUIRE(real->brakes.delaySetting == delay); using test::channels::operator+; test::trace trace{std::string{"brake cycle/at speed/"} + name, test::channels::motion() + test::channels::brakes(), 100}; real.record(trace); @@ -147,20 +147,20 @@ TEST_CASE("brake cycle: the rapid setting at speed, the anti-slip brake and the real.hold_brake_pipe(3.5); real.run(10.0); CHECK(real->Vel > 100.0); - CHECK(real->BrakePress == doctest::Approx(service).epsilon(0.01)); + CHECK(real->brakes.cylinderPressure == doctest::Approx(service).epsilon(0.01)); trace.mark("anti-slip"); - real->Hamulec->ASB(3); + real->brakes.distributor->ASB(3); real.run(2.0); - real->Hamulec->ASB(0); + real->brakes.distributor->ASB(0); real.run(3.0); trace.mark("releaser button"); - real->Hamulec->SetUniversalFlag(TUniversalBrake::ub_Release); + real->brakes.distributor->SetUniversalFlag(TUniversalBrake::ub_Release); real.run(3.0); - real->Hamulec->SetUniversalFlag(0); - CHECK((real->BrakePress < 1.0) == releases); + real->brakes.distributor->SetUniversalFlag(0); + CHECK((real->brakes.cylinderPressure < 1.0) == releases); // released for good, the pipe still at full service real.run(40.0); - CHECK((real->BrakePress < 0.1) == releases); + CHECK((real->brakes.cylinderPressure < 0.1) == releases); trace.check(); } } diff --git a/tests/unit/test_brake_handles.cpp b/tests/unit/test_brake_handles.cpp index 1cceda3c0..12d91adec 100644 --- a/tests/unit/test_brake_handles.cpp +++ b/tests/unit/test_brake_handles.cpp @@ -24,7 +24,7 @@ std::vector handle_channels() { // the vehicles with a driver's brake handle bool has_handle(vehicle &Vehicle) { - return Vehicle->BrakeCtrlPosNo > 1; + return Vehicle->brakes.handlePositions > 1; } void hold(vehicle &Vehicle, test::trace &Trace, std::string const &Event, double Position, double Seconds) { @@ -36,8 +36,8 @@ void hold(vehicle &Vehicle, test::trace &Trace, std::string const &Event, double // every position of the driver's handle, recorded in the trace void every_position(vehicle &Vehicle, test::trace &Trace) { Vehicle.hold_main_reservoir(std::max(Vehicle->air.compressor.maxPressure, 8.0)); - REQUIRE(Vehicle->Handle != nullptr); - auto &handle{*Vehicle->Handle}; + REQUIRE(Vehicle->brakes.driverValve != nullptr); + auto &handle{*Vehicle->brakes.driverValve}; Vehicle.record(Trace); hold(Vehicle, Trace, "running", handle.GetPos(bh_RP), 90.0); @@ -105,13 +105,13 @@ TEST_CASE("brake handles: the local brake handle of every real vehicle") { real.hold_main_reservoir(std::max(real->air.compressor.maxPressure, 8.0)); test::trace trace{"local brake/" + path, handle_channels(), 100}; real.record(trace); - REQUIRE(real->Handle != nullptr); - real->BrakeLevelSet(real->Handle->GetPos(bh_RP)); + REQUIRE(real->brakes.driverValve != nullptr); + real->BrakeLevelSet(real->brakes.driverValve->GetPos(bh_RP)); trace.mark("charge"); real.run(60.0); for (auto const position : {0.25, 0.5, 1.0, 0.5, 0.0}) { trace.mark(std::format("local {:f}", position)); - real->LocalBrakePosA = position; + real->brakes.independentPosition = position; real.run(15.0); } trace.check(); @@ -136,8 +136,8 @@ TEST_CASE("brake handles: the overload and the high pressure buttons of the MHZ real.hold_main_reservoir(std::max(real->air.compressor.maxPressure, 8.0)); test::trace trace{"brake handles/buttons/" + name, handle_channels(), 100}; real.record(trace); - REQUIRE(real->Handle != nullptr); - auto &handle{*real->Handle}; + REQUIRE(real->brakes.driverValve != nullptr); + auto &handle{*real->brakes.driverValve}; driven_at(real, trace, "running", handle.GetPos(bh_RP), 60.0); auto const running{real->brakePipe.pressure}; handle.SetUniversalFlag(TUniversalBrake::ub_Overload); @@ -171,12 +171,12 @@ void ready_knorr_ep(test::consist &Unit) { Unit.add(definition::fiz("en57_v1/6bai"), 1); Unit.add(definition::fiz("en57_v1/5bgb")); auto &cab{Unit[0]}; - REQUIRE(cab->BrakeHandle == TBrakeHandle::St113); - REQUIRE(cab->Handle != nullptr); + REQUIRE(cab->brakes.driverValveType == TBrakeHandle::St113); + REQUIRE(cab->brakes.driverValve != nullptr); cab->BatterySwitch(true); cab->CabActivisation(); cab.hold_brake_pipe(5.0); - cab->BrakeLevelSet(cab->Handle->GetPos(bh_RP)); + cab->BrakeLevelSet(cab->brakes.driverValve->GetPos(bh_RP)); Unit.run(60.0); } @@ -187,7 +187,7 @@ double ep_brake(test::consist &Unit, double Position, double Seconds) { Unit.run(0.1); cab->SwitchEPBrake(1); Unit.run(Seconds); - return cab->BrakePress; + return cab->brakes.cylinderPressure; } // the EP force the St113 handle of the cab car gives in the given position @@ -195,7 +195,7 @@ double ep_at(test::consist &Unit, double Position) { auto &cab{Unit[0]}; cab->BrakeLevelSet(Position); Unit.run(0.1); - return cab->Handle->GetEP(); + return cab->brakes.driverValve->GetEP(); } } // namespace @@ -204,13 +204,13 @@ TEST_CASE("brake handles: the positions of the Knorr St113 EP brake") { test::consist unit; ready_knorr_ep(unit); auto &cab{unit[0]}; - REQUIRE(cab->Handle != nullptr); - auto &handle{*cab->Handle}; + REQUIRE(cab->brakes.driverValve != nullptr); + auto &handle{*cab->brakes.driverValve}; // the keys: Num 6 running, Num 8 the first position on, Num 5 the middle of the handle CHECK(handle.GetPos(bh_RP) == doctest::Approx(0.0)); CHECK(ep_at(unit, 0.0) == doctest::Approx(-1.0)); // EP release CHECK(ep_at(unit, 1.0) == doctest::Approx(1.0)); // EP brake - CHECK(ep_at(unit, cab->BrakeCtrlPosNo / 2) == doctest::Approx(0.0)); // lap, Num 5 + CHECK(ep_at(unit, cab->brakes.handlePositions / 2) == doctest::Approx(0.0)); // lap, Num 5 CHECK(ep_at(unit, handle.GetPos(bh_FB)) == doctest::Approx(0.0)); CHECK(ep_at(unit, handle.GetPos(bh_EPR)) == doctest::Approx(-1.0)); CHECK(ep_at(unit, handle.GetPos(bh_EPB)) == doctest::Approx(1.0)); @@ -254,10 +254,10 @@ TEST_CASE("brake handles: the Knorr St113 EP brake needs the control of the cab cab->DirectionBackward(); unit.run(0.1); CHECK(cab->EpForce == doctest::Approx(0.0)); - auto const held{cab->BrakePress}; + auto const held{cab->brakes.cylinderPressure}; unit.run(5.0); - CHECK(cab->BrakePress < held + 0.05); - CHECK(cab->BrakePress > 0.2); + CHECK(cab->brakes.cylinderPressure < held + 0.05); + CHECK(cab->brakes.cylinderPressure > 0.2); // and doesn't release either, until the control is powered again CHECK(ep_brake(unit, 0.0, 5.0) > 0.2); cab->SwitchEPBrake(0); @@ -281,12 +281,12 @@ struct st113_sample { std::vector st113_run() { test::reseed_random(); vehicle real{definition::fiz("en57_v1/6bai")}; - REQUIRE(real->BrakeHandle == TBrakeHandle::St113); - REQUIRE(real->Handle != nullptr); + REQUIRE(real->brakes.driverValveType == TBrakeHandle::St113); + REQUIRE(real->brakes.driverValve != nullptr); real.hold_main_reservoir(std::max(real->air.compressor.maxPressure, 8.0)); - auto &handle{*real->Handle}; + auto &handle{*real->brakes.driverValve}; std::vector samples; - auto const sample{[&] { samples.push_back({handle.GetCP(), real->brakePipe.pressure, real->BrakePress, handle.GetEP()}); }}; + auto const sample{[&] { samples.push_back({handle.GetCP(), real->brakePipe.pressure, real->brakes.cylinderPressure, handle.GetEP()}); }}; auto const hold{[&](double Position, std::initializer_list Seconds) { real->BrakeLevelSet(Position); for (auto const seconds : Seconds) { diff --git a/tests/unit/test_brake_pipe.cpp b/tests/unit/test_brake_pipe.cpp index 17a6a498f..6e7019afa 100644 --- a/tests/unit/test_brake_pipe.cpp +++ b/tests/unit/test_brake_pipe.cpp @@ -22,8 +22,8 @@ void freight_train(test::consist &Train, int const Wagons) { for (int i = 0; i < Wagons; ++i) { auto &wagon{Train.add(definition::fiz("3wl_v2/3wl"))}; wagon->BrakeDelaySwitch(bdelay_G); - REQUIRE(wagon->BrakeValve == TBrakeValve::ESt3); - REQUIRE(wagon->Spg == doctest::Approx(0.792)); // the pipe of a freight wagon + REQUIRE(wagon->brakes.distributorType == TBrakeValve::ESt3); + REQUIRE(wagon->brakes.pipeSection == doctest::Approx(0.792)); // the pipe of a freight wagon } Train[0].hold_brake_pipe(5.0); // the locomotive's driver's valve in the running position } @@ -33,7 +33,7 @@ void passenger_train(test::consist &Train, int const Cars) { Train.add(definition::fiz("st44_v2/m62-1151")); for (int i = 0; i < Cars; ++i) { auto &car{Train.add(definition::fiz("11xa_v2/93a"))}; - REQUIRE(car->Spg == doctest::Approx(0.507)); // the pipe of a passenger car + REQUIRE(car->brakes.pipeSection == doctest::Approx(0.507)); // the pipe of a passenger car } Train[0].hold_brake_pipe(5.0); } @@ -72,11 +72,11 @@ TEST_CASE("brake pipe: the distributors of a standing freight train see the pres CAPTURE(i); auto &wagon{train[i].physics()}; // the distributor's valve chamber follows the pressure the distributor works with: the pipe's own - CHECK(std::abs(wagon.Hamulec->GetVRP() - wagon.brakePipe.pressure) < 0.005); + CHECK(std::abs(wagon.brakes.distributor->GetVRP() - wagon.brakePipe.pressure) < 0.005); CHECK(wagon.brakePipe.pressure > 4.9); // released, as the AI wants every vehicle before it starts (TController::CheckVehicles()) - CHECK((wagon.Hamulec->GetBrakeStatus() & (b_on | b_hld)) == 0); - CHECK(wagon.BrakePress < 0.1); + CHECK((wagon.brakes.distributor->GetBrakeStatus() & (b_on | b_hld)) == 0); + CHECK(wagon.brakes.cylinderPressure < 0.1); } // the exchange between the 14 m wagons takes 3 sub-steps of a step of 0.01 s CHECK(train[1]->PipeCouplersSubsteps(0.01) == 3); @@ -106,9 +106,9 @@ TEST_CASE("brake pipe: a passenger train, whose exchange was stable in one step, for (std::size_t i = 1; i < train.size(); ++i) { CAPTURE(i); auto &car{train[i].physics()}; - CHECK(std::abs(car.Hamulec->GetVRP() - car.brakePipe.pressure) < 0.005); - CHECK((car.Hamulec->GetBrakeStatus() & (b_on | b_hld)) == 0); - CHECK(car.BrakePress < 0.1); + CHECK(std::abs(car.brakes.distributor->GetVRP() - car.brakePipe.pressure) < 0.005); + CHECK((car.brakes.distributor->GetBrakeStatus() & (b_on | b_hld)) == 0); + CHECK(car.brakes.cylinderPressure < 0.1); } auto const converged{application_time(passenger_train, 10, 3.5, 0.001)}; auto const usual{application_time(passenger_train, 10, 3.5, 0.01)}; diff --git a/tests/unit/test_brake_setting.cpp b/tests/unit/test_brake_setting.cpp index a8d5fb0af..b4f7cb26c 100644 --- a/tests/unit/test_brake_setting.cpp +++ b/tests/unit/test_brake_setting.cpp @@ -247,68 +247,68 @@ bool inspection_pending(std::vector const &Vehicles, bool const TEST_CASE("brake setting: the inspector cuts the brake out in a train on G and puts it back in a train on P") { test::vehicle car{passenger_car_definition()}; charge_and_apply(car); - REQUIRE(car->BrakePress > 1.0); + REQUIRE(car->brakes.cylinderPressure > 1.0); // made up into a heavy train on G: the brake is cut out and released REQUIRE(inspect_heavy_train(car) == brake_setting::cut_out); CHECK(brake_setting::is_cut_out(car.physics())); - CHECK(car->BrakeCutOutByInspector); + CHECK(car->brakes.cutOutByInspector); car.run(30.0); - CHECK(car->BrakePress < 0.1); + CHECK(car->brakes.cylinderPressure < 0.1); // and it stays off whatever the brake pipe does car.hold_brake_pipe(5.0); car.run(60.0); car.hold_brake_pipe(3.5); car.run(20.0); - CHECK(car->BrakePress < 0.1); + CHECK(car->brakes.cylinderPressure < 0.1); car.hold_brake_pipe(0.0); car.run(20.0); - CHECK(car->BrakePress < 0.1); + CHECK(car->brakes.cylinderPressure < 0.1); // to the inspector looking at the train again it's a car like any other, and the train needs it cut out still CHECK(false == brake_setting::describe(car.physics(), false).cut_out); REQUIRE(inspect_heavy_train(car) == brake_setting::cut_out); - CHECK(car->BrakeCutOutByInspector); + CHECK(car->brakes.cutOutByInspector); // made up into a light train: the brake is back on P, charges and brakes again CHECK(inspect_light_train(car) == P); CHECK(false == brake_setting::is_cut_out(car.physics())); - CHECK(false == car->BrakeCutOutByInspector); - CHECK(car->BrakeDelayFlag == P); + CHECK(false == car->brakes.cutOutByInspector); + CHECK(car->brakes.delaySetting == P); // the reservoirs emptied when it was cut out take some five minutes to charge from the brake pipe car.hold_brake_pipe(5.0); car.run(300.0); - CHECK(car->Hamulec->GetBRP() > 4.9); + CHECK(car->brakes.distributor->GetBRP() > 4.9); charge_and_apply(car); - CHECK(car->BrakePress > 1.0); + CHECK(car->brakes.cylinderPressure > 1.0); } TEST_CASE("brake setting: the inspector never puts back a brake cut out for another reason") { test::vehicle car{passenger_car_definition()}; charge_and_apply(car); // cut out the way the scenery's '0' does it - car->Hamulec->ForceEmptiness(); - car->Hamulec->SetBrakeStatus(car->Hamulec->GetBrakeStatus() | b_dmg); + car->brakes.distributor->ForceEmptiness(); + car->brakes.distributor->SetBrakeStatus(car->brakes.distributor->GetBrakeStatus() | b_dmg); CHECK(brake_setting::describe(car.physics(), false).cut_out); // a train on G wants it cut out anyway: it isn't the inspector's to put back CHECK(inspect_heavy_train(car) == brake_setting::cut_out); - CHECK(false == car->BrakeCutOutByInspector); + CHECK(false == car->brakes.cutOutByInspector); // a train on P would want it working: it stays cut out CHECK(inspect_light_train(car) == P); CHECK(brake_setting::is_cut_out(car.physics())); charge_and_apply(car); - CHECK(car->BrakePress < 0.1); + CHECK(car->brakes.cylinderPressure < 0.1); // a brake the inspector cut out, which someone else puts back and cuts out again, is theirs from then on test::vehicle other{passenger_car_definition()}; REQUIRE(inspect_heavy_train(other) == brake_setting::cut_out); - other->Hamulec->SetBrakeStatus(other->Hamulec->GetBrakeStatus() & ~b_dmg); + other->brakes.distributor->SetBrakeStatus(other->brakes.distributor->GetBrakeStatus() & ~b_dmg); CHECK(inspect_heavy_train(other) == brake_setting::cut_out); // the inspector cuts it out again, and it's its own again - CHECK(other->BrakeCutOutByInspector); - other->Hamulec->SetBrakeStatus(other->Hamulec->GetBrakeStatus() & ~b_dmg); + CHECK(other->brakes.cutOutByInspector); + other->brakes.distributor->SetBrakeStatus(other->brakes.distributor->GetBrakeStatus() & ~b_dmg); CHECK(inspect_light_train(other) == P); - CHECK(false == other->BrakeCutOutByInspector); - other->Hamulec->SetBrakeStatus(other->Hamulec->GetBrakeStatus() | b_dmg); + CHECK(false == other->brakes.cutOutByInspector); + other->brakes.distributor->SetBrakeStatus(other->brakes.distributor->GetBrakeStatus() | b_dmg); CHECK(inspect_light_train(other) == P); CHECK(brake_setting::is_cut_out(other.physics())); } @@ -319,23 +319,23 @@ TEST_CASE("brake setting: shunting puts back a brake the inspector cut out, and // shunted in a heavy consist: nothing is cut out, the car is on P and brakes CHECK(inspect_heavy_train(car, shunting) == P); CHECK(false == brake_setting::is_cut_out(car.physics())); - CHECK(car->BrakeDelayFlag == P); - CHECK(car->BrakePress > 1.0); + CHECK(car->brakes.delaySetting == P); + CHECK(car->brakes.cylinderPressure > 1.0); // cut out when the consist became a train, then shunted again (e.g. left in a yard): the brake is back REQUIRE(inspect_heavy_train(car) == brake_setting::cut_out); - REQUIRE(car->BrakeCutOutByInspector); + REQUIRE(car->brakes.cutOutByInspector); CHECK(inspect_heavy_train(car, shunting) == P); CHECK(false == brake_setting::is_cut_out(car.physics())); - CHECK(false == car->BrakeCutOutByInspector); + CHECK(false == car->brakes.cutOutByInspector); car.hold_brake_pipe(5.0); car.run(300.0); charge_and_apply(car); - CHECK(car->BrakePress > 1.0); + CHECK(car->brakes.cylinderPressure > 1.0); // a brake cut out for a reason of its own stays cut out in shunting too test::vehicle other{passenger_car_definition()}; - other->Hamulec->SetBrakeStatus(other->Hamulec->GetBrakeStatus() | b_dmg); + other->brakes.distributor->SetBrakeStatus(other->brakes.distributor->GetBrakeStatus() | b_dmg); CHECK(inspect_heavy_train(other, shunting) == P); CHECK(brake_setting::is_cut_out(other.physics())); } @@ -343,25 +343,25 @@ TEST_CASE("brake setting: shunting puts back a brake the inspector cut out, and TEST_CASE("brake setting: the inspector doesn't cut a brake out on the run, it waits for a standstill") { test::vehicle car{passenger_car_definition()}; charge_and_apply(car); - REQUIRE(car->BrakePress > 1.0); + REQUIRE(car->brakes.cylinderPressure > 1.0); // the train checked on the run (the order changed mid-run): the car keeps its brake and its setting - auto const setting{car->BrakeDelayFlag}; + auto const setting{car->brakes.delaySetting}; CHECK(inspect_heavy_train(car, as_train, moving) == brake_setting::cut_out); CHECK(false == brake_setting::is_cut_out(car.physics())); - CHECK(false == car->BrakeCutOutByInspector); - CHECK(car->BrakeDelayFlag == setting); + CHECK(false == car->brakes.cutOutByInspector); + CHECK(car->brakes.delaySetting == setting); car.run(5.0); - CHECK(car->BrakePress > 1.0); + CHECK(car->brakes.cylinderPressure > 1.0); // the next check, standing, cuts it out CHECK(inspect_heavy_train(car) == brake_setting::cut_out); CHECK(brake_setting::is_cut_out(car.physics())); - CHECK(car->BrakeCutOutByInspector); + CHECK(car->brakes.cutOutByInspector); // a brake cut out already stays cut out on the run, and one put back on the run is back CHECK(inspect_heavy_train(car, as_train, moving) == brake_setting::cut_out); - CHECK(car->BrakeCutOutByInspector); + CHECK(car->brakes.cutOutByInspector); CHECK(inspect_heavy_train(car, shunting, moving) == P); CHECK(false == brake_setting::is_cut_out(car.physics())); - CHECK(false == car->BrakeCutOutByInspector); + CHECK(false == car->brakes.cutOutByInspector); } TEST_CASE("brake setting: a cut-out skipped on the run is reported, and done at the next inspection standing") { @@ -374,23 +374,23 @@ TEST_CASE("brake setting: a cut-out skipped on the run is reported, and done at for (auto *vehicle : vehicles) { charge_and_apply(*vehicle); } - auto const setting{first->BrakeDelayFlag}; + auto const setting{first->brakes.delaySetting}; // moving: nothing is cut out, and the inspector tells it has to come back CHECK(inspection_pending(vehicles, as_train, brake_setting::at_standstill(3.0))); for (auto *vehicle : vehicles) { CHECK(false == brake_setting::is_cut_out(vehicle->physics())); - CHECK(false == vehicle->physics().BrakeCutOutByInspector); + CHECK(false == vehicle->physics().brakes.cutOutByInspector); } - CHECK(first->BrakeDelayFlag == setting); - CHECK(wagon->BrakeDelayFlag == G); + CHECK(first->brakes.delaySetting == setting); + CHECK(wagon->brakes.delaySetting == G); // still moving: still pending CHECK(inspection_pending(vehicles, as_train, moving)); // the train stands (its brake pipe charging after the coupling): the cars get cut out, nothing is left CHECK(false == inspection_pending(vehicles, as_train, brake_setting::at_standstill(0.0))); CHECK(brake_setting::is_cut_out(first.physics())); - CHECK(first->BrakeCutOutByInspector); + CHECK(first->brakes.cutOutByInspector); CHECK(brake_setting::is_cut_out(second.physics())); - CHECK(second->BrakeCutOutByInspector); + CHECK(second->brakes.cutOutByInspector); CHECK(false == brake_setting::is_cut_out(wagon.physics())); // and nothing is pending when the train moves off CHECK(false == inspection_pending(vehicles, as_train, moving)); @@ -401,19 +401,19 @@ TEST_CASE("brake setting: an inspection on the run with nothing to cut out leave // a wagon with G in a heavy train on G test::vehicle wagon{test::definition::load("wagon").set("Cntrl", "BrakeDelays", "GP")}; CHECK(false == inspection_pending({&wagon}, as_train, moving)); - CHECK(wagon->BrakeDelayFlag == G); + CHECK(wagon->brakes.delaySetting == G); // a car without G in a consist being shunted: it keeps its brake, on P test::vehicle car{passenger_car_definition()}; CHECK(false == inspection_pending({&car}, shunting, moving)); CHECK(false == brake_setting::is_cut_out(car.physics())); // a car whose brake is cut out already, for a reason of its own or by the inspector test::vehicle damaged{passenger_car_definition()}; - damaged->Hamulec->SetBrakeStatus(damaged->Hamulec->GetBrakeStatus() | b_dmg); + damaged->brakes.distributor->SetBrakeStatus(damaged->brakes.distributor->GetBrakeStatus() | b_dmg); CHECK(false == inspection_pending({&damaged}, as_train, moving)); - CHECK(false == damaged->BrakeCutOutByInspector); + CHECK(false == damaged->brakes.cutOutByInspector); test::vehicle done{passenger_car_definition()}; REQUIRE(false == inspection_pending({&done}, as_train, standstill)); - REQUIRE(done->BrakeCutOutByInspector); + REQUIRE(done->brakes.cutOutByInspector); CHECK(false == inspection_pending({&done}, as_train, moving)); // a brake put back on the run (the train became a consist being shunted) leaves nothing either CHECK(false == inspection_pending({&done}, shunting, moving)); @@ -444,15 +444,15 @@ TEST_CASE("brake setting: a train creeping to a stop counts as standing, one on charge_and_apply(creeping); CHECK(inspect_heavy_train(creeping, as_train, brake_setting::at_standstill(0.9)) == brake_setting::cut_out); CHECK(brake_setting::is_cut_out(creeping.physics())); - CHECK(creeping->BrakeCutOutByInspector); + CHECK(creeping->brakes.cutOutByInspector); // checked at 30 km/h: the car keeps its brake test::vehicle running{passenger_car_definition()}; charge_and_apply(running); CHECK(inspect_heavy_train(running, as_train, brake_setting::at_standstill(30.0)) == brake_setting::cut_out); CHECK(false == brake_setting::is_cut_out(running.physics())); - CHECK(false == running->BrakeCutOutByInspector); + CHECK(false == running->brakes.cutOutByInspector); running.run(5.0); - CHECK(running->BrakePress > 1.0); + CHECK(running->brakes.cylinderPressure > 1.0); } TEST_CASE("brake setting: a bank engine's run counts as a train, shunting doesn't") { @@ -506,13 +506,13 @@ TEST_CASE("brake setting: R+Mg brakes as hard as R at speed, the rapid stage of test::vehicle real{definition, 160.0}; real->DecManualBrakeLevel(ManualBrakePosNo); real->BrakeDelaySwitch(Setting); // false when already set - REQUIRE(real->BrakeDelayFlag == Setting); + REQUIRE(real->brakes.delaySetting == Setting); real.hold_brake_pipe(5.0); real.run(60.0); real.hold_brake_pipe(3.5); real.run(10.0); REQUIRE(real->Vel > 100.0); - return real->BrakePress; + return real->brakes.cylinderPressure; }; auto const rapid{service(R)}; CHECK(service(R | M) == doctest::Approx(rapid).epsilon(0.01)); diff --git a/tests/unit/test_brakes.cpp b/tests/unit/test_brakes.cpp index 51e50cd19..43ebdd098 100644 --- a/tests/unit/test_brakes.cpp +++ b/tests/unit/test_brakes.cpp @@ -17,16 +17,16 @@ TEST_CASE("brakes: KE wagon applies up to its tare limit on a service applicatio wagon.hold_brake_pipe(5.0); wagon.run(60.0); - CHECK(wagon->BrakePress < 0.1); - CHECK(wagon->Hamulec->GetBRP() > 4.5); // auxiliary reservoir charged + CHECK(wagon->brakes.cylinderPressure < 0.1); + CHECK(wagon->brakes.distributor->GetBRP() > 4.5); // auxiliary reservoir charged wagon.hold_brake_pipe(3.5); wagon.run(10.0); - CHECK(wagon->BrakePress == doctest::Approx(2.3).epsilon(0.05)); + CHECK(wagon->brakes.cylinderPressure == doctest::Approx(2.3).epsilon(0.05)); wagon.hold_brake_pipe(5.0); wagon.run(60.0); - CHECK(wagon->BrakePress < 0.1); + CHECK(wagon->brakes.cylinderPressure < 0.1); } TEST_CASE("brakes: a deeper brake pipe reduction brakes harder") { @@ -36,7 +36,7 @@ TEST_CASE("brakes: a deeper brake pipe reduction brakes harder") { wagon.run(60.0); wagon.hold_brake_pipe(Pipe); wagon.run(20.0); - return wagon->BrakePress; + return wagon->brakes.cylinderPressure; }; auto const light{applied(4.6)}; auto const medium{applied(4.2)}; @@ -55,14 +55,14 @@ TEST_CASE("brakes: every implemented distributor valve charges, applies and rele vehicle wagon{definition::load("wagon").set("Brake", "BrakeValve", valve).set("Brake", "Size", 16)}; wagon.hold_brake_pipe(5.0); wagon.run(90.0); - CHECK(wagon->BrakePress < 0.1); + CHECK(wagon->brakes.cylinderPressure < 0.1); wagon.hold_brake_pipe(3.5); wagon.run(20.0); - CHECK(wagon->BrakePress > 1.0); - CHECK(wagon->BrakePress <= 3.8 + 0.1); // MaxBP + CHECK(wagon->brakes.cylinderPressure > 1.0); + CHECK(wagon->brakes.cylinderPressure <= 3.8 + 0.1); // MaxBP wagon.hold_brake_pipe(5.0); wagon.run(90.0); - CHECK(wagon->BrakePress < 0.1); + CHECK(wagon->brakes.cylinderPressure < 0.1); } } @@ -108,8 +108,8 @@ TEST_CASE("brakes: a dead EN57 hauled with the brake hose alone charges from the // a unit standing dead: no air anywhere, nothing in its main reservoir pipe for (std::size_t i = 1; i < train.size(); ++i) { auto &car{train[i].physics()}; - REQUIRE(car.BrakeValve == TBrakeValve::EP2); - car.Hamulec->ForceEmptiness(); + REQUIRE(car.brakes.distributorType == TBrakeValve::EP2); + car.brakes.distributor->ForceEmptiness(); car.brakePipe.reservoir->CreatePress(0.0); car.brakePipe.reservoir->Act(); car.mainPipe.reservoir->CreatePress(0.0); @@ -122,22 +122,22 @@ TEST_CASE("brakes: a dead EN57 hauled with the brake hose alone charges from the CAPTURE(i); auto &car{train[i].physics()}; REQUIRE(car.mainPipe.pressure < 0.1); // no main reservoir pipe - CHECK(car.Hamulec->GetBRP() > 4.8); - CHECK(car.Hamulec->GetCRP() > 4.8); - CHECK(car.BrakePress < 0.1); + CHECK(car.brakes.distributor->GetBRP() > 4.8); + CHECK(car.brakes.distributor->GetCRP() > 4.8); + CHECK(car.brakes.cylinderPressure < 0.1); } // a full service application brakes the unit, and it releases again locomotive.hold_brake_pipe(3.5); train.run(20.0); for (std::size_t i = 1; i < train.size(); ++i) { CAPTURE(i); - CHECK(train[i]->BrakePress > 2.0); + CHECK(train[i]->brakes.cylinderPressure > 2.0); } locomotive.hold_brake_pipe(5.0); train.run(60.0); for (std::size_t i = 1; i < train.size(); ++i) { CAPTURE(i); - CHECK(train[i]->BrakePress < 0.1); + CHECK(train[i]->brakes.cylinderPressure < 0.1); } } @@ -165,7 +165,7 @@ TEST_CASE("brakes: a wagon standing braked on a gradient sleeps while the brakes wagon->DecManualBrakeLevel(ManualBrakePosNo); wagon.hold_brake_pipe(3.5); wagon.run(30.0, slope); - REQUIRE(wagon->BrakePress > 1.0); + REQUIRE(wagon->brakes.cylinderPressure > 1.0); CHECK(std::abs(wagon.speed()) < 0.01); CHECK_FALSE(wagon->PhysicActivation); @@ -184,7 +184,7 @@ TEST_CASE("brakes: a wagon standing braked on a gradient sleeps while the brakes // released, it wakes, the force of the brakes is gone and it rolls down the gradient wagon.hold_brake_pipe(5.0); wagon.run(60.0, slope); - CHECK(wagon->BrakePress < 0.1); + CHECK(wagon->brakes.cylinderPressure < 0.1); CHECK(wagon->Fb < 1.0); CHECK(std::abs(wagon.speed()) > 1.0); CHECK(wagon->PhysicActivation); @@ -197,10 +197,10 @@ TEST_CASE("brakes: a wagon held by its hand brake on a gradient wakes and rolls slope.gradient = 0.01; vehicle wagon{definition::load("wagon")}; // made standing, it has the hand brake on (SetBraked()) - REQUIRE(wagon->ManualBrakePos == ManualBrakePosNo); + REQUIRE(wagon->brakes.handBrakePosition == ManualBrakePosNo); wagon.hold_brake_pipe(5.0); wagon.run(90.0, slope); - REQUIRE(wagon->BrakePress < 0.1); + REQUIRE(wagon->brakes.cylinderPressure < 0.1); CHECK(std::abs(wagon.speed()) < 0.01); CHECK_FALSE(wagon->PhysicActivation); diff --git a/tests/unit/test_cab.cpp b/tests/unit/test_cab.cpp index 4aceb5836..b76911c5e 100644 --- a/tests/unit/test_cab.cpp +++ b/tests/unit/test_cab.cpp @@ -103,7 +103,7 @@ TEST_CASE("cab: the controller of the electrodynamic brake apart from the local scenario.wait(10.0); CHECK(eu47.DynamicBrakeFlag); CHECK(eu47.Im < -50.0); - CHECK(eu47.BrakePress < 0.1); + CHECK(eu47.brakes.cylinderPressure < 0.1); scenario.act("dynamic brake full"); CHECK(eu47.DynamicBrakeLevelSet(2.0)); CHECK(eu47.DynamicBrakeRatio() == doctest::Approx(1.0)); @@ -118,7 +118,7 @@ TEST_CASE("cab: the controller of the electrodynamic brake apart from the local scenario.act("local brake"); eu47.IncLocalBrakeLevel(LocalBrakePosNo); scenario.wait(5.0); - CHECK(eu47.BrakePress > 1.0); + CHECK(eu47.brakes.cylinderPressure > 1.0); scenario.check(); } @@ -148,9 +148,9 @@ TEST_CASE("cab: the spring brake shut off and released by hand, the ep brake's f CHECK(railbus.EpFuseSwitch(true)); // the train brake handle stepped as the AI does, false at its ends scenario.act("handle stepped"); - railbus.BrakeLevelSet(railbus.Handle->GetPos(bh_RP)); + railbus.BrakeLevelSet(railbus.brakes.driverValve->GetPos(bh_RP)); CHECK(railbus.BrakeLevelAdd(1.0)); - CHECK(railbus.BrakeCtrlPos == static_cast(railbus.Handle->GetPos(bh_RP)) + 1); + CHECK(railbus.brakes.handlePosition == static_cast(railbus.brakes.driverValve->GetPos(bh_RP)) + 1); CHECK(railbus.BrakeLevelAdd(-1.0)); CHECK_FALSE(railbus.BrakeLevelAdd(-10.0)); CHECK_FALSE(railbus.BrakeLevelAdd(100.0)); diff --git a/tests/unit/test_camshaft.cpp b/tests/unit/test_camshaft.cpp index 31f255f69..236c80f14 100644 --- a/tests/unit/test_camshaft.cpp +++ b/tests/unit/test_camshaft.cpp @@ -72,7 +72,7 @@ void running(physics::Vehicle &Locomotive, int const Direction, int const Positi Locomotive.DirActive = Direction; Locomotive.Mains = true; Locomotive.brakePipe.pressure = 5.0; // bar, the pressure switch lets the line contactors close - Locomotive.BrakePress = 0.0; + Locomotive.brakes.cylinderPressure = 0.0; Locomotive.StLinFlag = true; Locomotive.MainCtrlActualPos = Position; Locomotive.MainCtrlPos = Controller; diff --git a/tests/unit/test_cntrl.cpp b/tests/unit/test_cntrl.cpp index 425a2b07a..4df03f31d 100644 --- a/tests/unit/test_cntrl.cpp +++ b/tests/unit/test_cntrl.cpp @@ -9,13 +9,13 @@ using test::vehicle; TEST_CASE("cntrl: the brake delays of the settings come from BDelay1 to BDelay4") { vehicle wagon{definition::load("wagon").set("Cntrl", "BDelay1", 10.0).set("Cntrl", "BDelay2", 20.0).set("Cntrl", "BDelay3", 30.0).set("Cntrl", "BDelay4", 40.0)}; - CHECK(wagon->BrakeDelay[0] == doctest::Approx(10.0)); + CHECK(wagon->brakes.delays[0] == doctest::Approx(10.0)); // the vehicle varies the others a little, by 0.83 to 0.9 (CheckLocomotiveParameters()) for (auto setting{1}; setting < 4; ++setting) { CAPTURE(setting); auto const given{10.0 * (setting + 1)}; - CHECK(wagon->BrakeDelay[setting] >= 0.83 * given); - CHECK(wagon->BrakeDelay[setting] <= 0.9 * given); + CHECK(wagon->brakes.delays[setting] >= 0.83 * given); + CHECK(wagon->brakes.delays[setting] <= 0.9 * given); } } diff --git a/tests/unit/test_commands.cpp b/tests/unit/test_commands.cpp index 5f3718959..702e81ae1 100644 --- a/tests/unit/test_commands.cpp +++ b/tests/unit/test_commands.cpp @@ -33,7 +33,7 @@ std::vector state() { {"TUHEX_StageActual", [](auto const &M) { return M.TUHEX_StageActual; }}, {"TUHEX_Active", [](auto const &M) { return flag(M.TUHEX_Active); }}, {"DynamicBrakeEMUStatus", [](auto const &M) { return flag(M.DynamicBrakeEMUStatus); }}, - {"BrakeReleaser", [](auto const &M) { return flag(M.Hamulec->Releaser()); }}, + {"BrakeReleaser", [](auto const &M) { return flag(M.brakes.distributor->Releaser()); }}, {"WaterPumpBreaker", [](auto const &M) { return flag(M.WaterPump.breaker); }}, {"WaterPumpEnabled", [](auto const &M) { return flag(M.WaterPump.is_enabled); }}, {"WaterPumpDisabled", [](auto const &M) { return flag(M.WaterPump.is_disabled); }}, @@ -66,7 +66,7 @@ std::vector state() { {"Imin", [](auto const &M) { return M.Imin; }}, {"DamageFlag", [](auto const &M) { return M.DamageFlag.Bits(); }}, {"RadioStop", [](auto const &M) { return flag(M.RadioStopFlag); }}, - {"BrakeDelayFlag", [](auto const &M) { return M.BrakeDelayFlag; }}, + {"BrakeDelayFlag", [](auto const &M) { return M.brakes.delaySetting; }}, {"SandDose", [](auto const &M) { return flag(M.SandDose); }}, {"CabSignal", [](auto const &M) { return flag(M.SecuritySystem.is_cabsignal_blinking()); }}, {"LoadAmount", [](auto const &M) { return M.LoadAmount; }}, diff --git a/tests/unit/test_controls.cpp b/tests/unit/test_controls.cpp index 6549146c0..203624d5a 100644 --- a/tests/unit/test_controls.cpp +++ b/tests/unit/test_controls.cpp @@ -33,9 +33,9 @@ void notch_down(scenario &Scenario) { void brake_to_stop(scenario &Scenario, double Seconds = 60.0) { Scenario.act("brake to stop"); - Scenario.cab().BrakeLevelSet(Scenario.cab().Handle->GetPos(bh_FB)); + Scenario.cab().BrakeLevelSet(Scenario.cab().brakes.driverValve->GetPos(bh_FB)); Scenario.wait(Seconds); - Scenario.cab().BrakeLevelSet(Scenario.cab().Handle->GetPos(bh_RP)); + Scenario.cab().BrakeLevelSet(Scenario.cab().brakes.driverValve->GetPos(bh_RP)); Scenario.wait(20.0); } @@ -43,7 +43,7 @@ void brake_to_stop(scenario &Scenario, double Seconds = 60.0) { void recharge(scenario &Scenario) { auto &cab{Scenario.cab()}; Scenario.act("releaser held, the pipe charged"); - cab.BrakeLevelSet(cab.Handle->GetPos(bh_RP)); + cab.BrakeLevelSet(cab.brakes.driverValve->GetPos(bh_RP)); cab.BrakeReleaser(1); Scenario.wait(30.0); cab.BrakeReleaser(0); @@ -62,7 +62,7 @@ bool stopped(scenario &Scenario) { // the brake cylinders of every vehicle of the train under the pressure given bool released(scenario &Scenario, double Pressure = 0.1) { for (std::size_t i = 0; i < Scenario.train().size(); ++i) { - if (Scenario.vehicle(i).BrakePress > Pressure) { + if (Scenario.vehicle(i).brakes.cylinderPressure > Pressure) { return false; } } @@ -302,7 +302,7 @@ TEST_CASE("controls: emergency stops by the alarm chain and the radio-stop") { // the pipe emptied, the whole train braked to a stop CHECK(stopped(scenario)); CHECK(cab.brakePipe.pressure < 0.5); - CHECK(scenario.vehicle(2).BrakePress > 1.0); + CHECK(scenario.vehicle(2).brakes.cylinderPressure > 1.0); scenario.act("alarm chain reset"); scenario.vehicle(1).AlarmChainSwitch(false); scenario.wait(10.0); @@ -337,29 +337,29 @@ TEST_CASE("controls: releasers and the universal brake buttons") { auto &cab{scenario.cab()}; auto &wagon{scenario.vehicle(2)}; scenario.act("service brake"); - cab.BrakeLevelSet(cab.Handle->GetPos(bh_FB)); + cab.BrakeLevelSet(cab.brakes.driverValve->GetPos(bh_FB)); scenario.wait(20.0); - CHECK(cab.BrakePress > 1.0); - CHECK(wagon.BrakePress > 1.0); - cab.BrakeLevelSet(cab.Handle->GetPos(bh_NP)); + CHECK(cab.brakes.cylinderPressure > 1.0); + CHECK(wagon.brakes.cylinderPressure > 1.0); + cab.BrakeLevelSet(cab.brakes.driverValve->GetPos(bh_NP)); auto &coach{scenario.vehicle(1)}; // the releaser of the cab is passed along the whole train, a wagon's works on the wagon alone - auto const coachbraked{coach.BrakePress}; - auto wagonbraked{wagon.BrakePress}; + auto const coachbraked{coach.brakes.cylinderPressure}; + auto wagonbraked{wagon.brakes.cylinderPressure}; scenario.act("releaser of the locomotive"); cab.BrakeReleaser(1); scenario.wait(10.0); cab.BrakeReleaser(0); - CHECK(cab.BrakePress < 0.5); - CHECK(coach.BrakePress < coachbraked - 1.0); - CHECK(wagon.BrakePress < wagonbraked - 0.5); + CHECK(cab.brakes.cylinderPressure < 0.5); + CHECK(coach.brakes.cylinderPressure < coachbraked - 1.0); + CHECK(wagon.brakes.cylinderPressure < wagonbraked - 0.5); CHECK(cab.brakePipe.pressure < 4.0); // the pipe stays where the service application left it - wagonbraked = wagon.BrakePress; + wagonbraked = wagon.brakes.cylinderPressure; scenario.act("releaser of the wagon"); wagon.BrakeReleaser(1); scenario.wait(10.0); wagon.BrakeReleaser(0); - CHECK(wagon.BrakePress < wagonbraked - 0.5); + CHECK(wagon.brakes.cylinderPressure < wagonbraked - 0.5); for (int button = 0; button < 3; ++button) { scenario.act(std::format("universal button {}", button)); cab.UniversalBrakeButton(button, 1); @@ -368,7 +368,7 @@ TEST_CASE("controls: releasers and the universal brake buttons") { scenario.wait(5.0); } scenario.act("running"); - cab.BrakeLevelSet(cab.Handle->GetPos(bh_RP)); + cab.BrakeLevelSet(cab.brakes.driverValve->GetPos(bh_RP)); scenario.wait(60.0); CHECK(cab.brakePipe.pressure > 4.8); CHECK(released(scenario)); @@ -395,7 +395,7 @@ TEST_CASE("controls: the ep brake of electric units") { for (std::size_t i = 0; i < positions.size(); ++i) { CAPTURE(positions[i]); scenario.act(std::format("handle {}", positions[i])); - cab.BrakeLevelSet(cab.Handle->GetPos(positions[i])); + cab.BrakeLevelSet(cab.brakes.driverValve->GetPos(positions[i])); scenario.wait(15.0); if (i == 2) { CHECK(released(scenario)); @@ -404,8 +404,8 @@ TEST_CASE("controls: the ep brake of electric units") { // the ep brake works the cylinders of every car by wire, the pipe stays charged (by the first // application the EW58's pipe is still charging after the start-up) CHECK(cab.brakePipe.pressure > 4.8); - CHECK(cab.BrakePress > 1.0); - CHECK(last.BrakePress > 1.0); + CHECK(cab.brakes.cylinderPressure > 1.0); + CHECK(last.brakes.cylinderPressure > 1.0); } } // the EW58 releases at the running position, the ED72 holds the ep application there, and with the ep @@ -437,7 +437,7 @@ TEST_CASE("controls: the electrodynamic brake of locomotives having one") { cab.DynamicBrakeSwitch(true); scenario.wait(5.0); scenario.act("brake"); - cab.BrakeLevelSet(cab.Handle->GetPos(bh_FB)); + cab.BrakeLevelSet(cab.brakes.driverValve->GetPos(bh_FB)); scenario.wait(40.0); CHECK(cab.Vel < speed); scenario.act("dynamic brake off"); @@ -554,20 +554,20 @@ TEST_CASE("controls: the automatic electrodynamic brake of the EP09, in service auto &ep09{scenario.cab()}; REQUIRE(ep09.Power110vIsAvailable); scenario.act(std::string{"brake "} + name); - ep09.BrakeLevelSet(ep09.Handle->GetPos(bh_MB) + steps); + ep09.BrakeLevelSet(ep09.brakes.driverValve->GetPos(bh_MB) + steps); scenario.wait(10.0); CHECK(ep09.DynamicBrakeFlag); CHECK(ep09.Im < -100.0); - CHECK(ep09.BrakePress < 0.25 * ep09.Hamulec->GetEDBCP()); + CHECK(ep09.brakes.cylinderPressure < 0.25 * ep09.brakes.distributor->GetEDBCP()); scenario.wait(110.0); // stopped, held by the air alone. the flag of the electrodynamic brake stays on while the cylinders hold // less than 2.1 bar, though the motors give nothing; a stronger application drops it before the stop CHECK(ep09.Vel == doctest::Approx(0.0)); CHECK(ep09.Im == doctest::Approx(0.0)); - CHECK(ep09.DynamicBrakeFlag == (ep09.BrakePress <= 2.1)); - CHECK(ep09.BrakePress == doctest::Approx(ep09.Hamulec->GetEDBCP()).epsilon(0.05)); + CHECK(ep09.DynamicBrakeFlag == (ep09.brakes.cylinderPressure <= 2.1)); + CHECK(ep09.brakes.cylinderPressure == doctest::Approx(ep09.brakes.distributor->GetEDBCP()).epsilon(0.05)); scenario.act("release"); - ep09.BrakeLevelSet(ep09.Handle->GetPos(bh_RP)); + ep09.BrakeLevelSet(ep09.brakes.driverValve->GetPos(bh_RP)); scenario.wait(30.0); scenario.check(); } @@ -600,17 +600,17 @@ TEST_CASE("controls: the automatic electrodynamic brake under ep and service bra cab.BrakeLevelSet(Position); scenario.wait(Seconds); }}; - brake("ep brake", cab.Handle->GetPos(bh_EPB), 15.0); + brake("ep brake", cab.brakes.driverValve->GetPos(bh_EPB), 15.0); CHECK(cab.DynamicBrakeFlag == epelectric); CHECK((cab.Im < -100.0) == epelectric); - brake("ep hold", cab.Handle->GetPos(bh_EPN), 5.0); - brake("first step", cab.Handle->GetPos(bh_MB), 20.0); - brake("deeper", cab.Handle->GetPos(bh_MB) + 1.0, 15.0); + brake("ep hold", cab.brakes.driverValve->GetPos(bh_EPN), 5.0); + brake("first step", cab.brakes.driverValve->GetPos(bh_MB), 20.0); + brake("deeper", cab.brakes.driverValve->GetPos(bh_MB) + 1.0, 15.0); // the pipe alone doesn't bring the EW58's motors in CHECK((cab.Im < -50.0) != epelectric); - brake("release", cab.Handle->GetPos(bh_RP), 20.0); - brake("full service", cab.Handle->GetPos(bh_FB), 40.0); - brake("release", cab.Handle->GetPos(bh_RP), 20.0); + brake("release", cab.brakes.driverValve->GetPos(bh_RP), 20.0); + brake("full service", cab.brakes.driverValve->GetPos(bh_FB), 40.0); + brake("release", cab.brakes.driverValve->GetPos(bh_RP), 20.0); scenario.check(); } } diff --git a/tests/unit/test_coupler_physics.cpp b/tests/unit/test_coupler_physics.cpp index 534104473..753bc4213 100644 --- a/tests/unit/test_coupler_physics.cpp +++ b/tests/unit/test_coupler_physics.cpp @@ -402,8 +402,8 @@ TEST_CASE("coupler physics: a jerk on a coupling with play breaks it, the brake CHECK_FALSE(pair.coupled()); CHECK((coupler_damaged(rear) || coupler_damaged(front))); // both parts of the train brake, their pipe vented through the torn hoses - CHECK(rear->AlarmChainFlag); - CHECK(front->AlarmChainFlag); + CHECK(rear->brakes.alarmChain); + CHECK(front->brakes.alarmChain); // the front wagon runs away from the rear one CHECK(front.speed() > rear.speed() + 5.0); CHECK(pair.gap() > 0.3); @@ -492,12 +492,12 @@ TEST_CASE("couplers: a broken coupler is repaired alone, with the one of the veh CHECK(third->Couplers[VehicleEnd::front].broken); // the second wagon keeps its damage, and its emergency braking, while a coupler of it is broken CHECK(second->DamageFlag.HasAll(VehicleDamage::coupling)); - CHECK(second->AlarmChainFlag); + CHECK(second->brakes.alarmChain); CHECK(third->repair_coupler(VehicleEnd::front)); CHECK_FALSE(second->Couplers[VehicleEnd::rear].broken); CHECK_FALSE(second->DamageFlag.HasAll(VehicleDamage::coupling)); - CHECK_FALSE(second->AlarmChainFlag); + CHECK_FALSE(second->brakes.alarmChain); // repaired, not coupled: the vehicles are coupled again as usual CHECK(second->Couplers[VehicleEnd::rear].CouplingFlag == Coupling::none); CHECK(second->Attach(VehicleEnd::rear, VehicleEnd::front, &third.physics(), Coupling::coupler, true, false)); diff --git a/tests/unit/test_couplers_trains.cpp b/tests/unit/test_couplers_trains.cpp index 6eed2c6ac..a98feb802 100644 --- a/tests/unit/test_couplers_trains.cpp +++ b/tests/unit/test_couplers_trains.cpp @@ -146,13 +146,13 @@ TEST_CASE("couplers: a coupler broken, with its brake hose torn off") { REQUIRE(locomotive.Couplers[VehicleEnd::rear].Connected == &wagon); locomotive.damage_coupler(VehicleEnd::rear); CHECK(locomotive.DamageFlag.HasAll(VehicleDamage::coupling)); - CHECK(locomotive.AlarmChainFlag); + CHECK(locomotive.brakes.alarmChain); CHECK(locomotive.Couplers[VehicleEnd::rear].CouplingFlag == Coupling::none); CHECK(wagon.Couplers[VehicleEnd::front].CouplingFlag == Coupling::none); // the front coupler of the wagon, broken on its own: no hose to tear wagon.damage_coupler(VehicleEnd::front); CHECK(wagon.DamageFlag.HasAll(VehicleDamage::coupling)); - CHECK_FALSE(wagon.AlarmChainFlag); + CHECK_FALSE(wagon.brakes.alarmChain); // articulated couplers don't break consist articulated; auto &unit{articulated.add(definition::fiz("impuls_v1/31we-a_pr")).physics()}; diff --git a/tests/unit/test_crew.cpp b/tests/unit/test_crew.cpp index 5caaf9fd0..b0d0e1659 100644 --- a/tests/unit/test_crew.cpp +++ b/tests/unit/test_crew.cpp @@ -200,7 +200,7 @@ TEST_CASE("crew: a locomotive under power left by its driver stops and stays bra CHECK(eu07.MainCtrlPos == eu07.MainCtrlNoPowerPos()); CHECK(eu07.ScndCtrlPos == 0); - CHECK(eu07.BrakeCtrlPos == static_cast(eu07.Handle->GetPos(bh_EB))); + CHECK(eu07.brakes.handlePosition == static_cast(eu07.brakes.driverValve->GetPos(bh_EB))); CHECK(eu07.CabActive == 0); CHECK(eu07.CabOccupied == 0); CHECK_FALSE(eu07.CabMaster); @@ -209,7 +209,7 @@ TEST_CASE("crew: a locomotive under power left by its driver stops and stays bra CAPTURE(stoppedafter); CHECK(std::abs(train[0].speed()) <= 0.01); CHECK(eu07.brakePipe.pressure < 1.0); // vented by the emergency position - CHECK(eu07.BrakePress > 2.0); + CHECK(eu07.brakes.cylinderPressure > 2.0); // it keeps standing, also on a slope, with the engine as the driver left it train.run(120.0, track{0.15, 0.02, test::catenary_3kv}); CHECK(std::abs(train[0].speed()) <= 0.01); @@ -244,7 +244,7 @@ TEST_CASE("crew: a train left by its driver is braked through the whole of it") auto &eu07{train[0].physics()}; auto &last{train[2].physics()}; REQUIRE(train[0].speed() > 15.0); - REQUIRE(last.BrakePress < 0.1); + REQUIRE(last.brakes.cylinderPressure < 0.1); crew::secure(eu07, eu07); @@ -253,7 +253,7 @@ TEST_CASE("crew: a train left by its driver is braked through the whole of it") CHECK(std::abs(train[0].speed()) <= 0.01); CHECK(std::abs(train[2].speed()) <= 0.01); CHECK(last.brakePipe.pressure < 1.0); - CHECK(last.BrakePress > 1.0); + CHECK(last.brakes.cylinderPressure > 1.0); } TEST_CASE("crew: a standing locomotive left by its driver is braked too") { @@ -265,16 +265,16 @@ TEST_CASE("crew: a standing locomotive left by its driver is braked too") { test::release_brakes(driver.cab); auto &eu07{train[0].physics()}; // the cylinders of a locomotive started up cold take their time to empty - for (int i = 0; i < 180 && eu07.BrakePress >= 0.1; ++i) { + for (int i = 0; i < 180 && eu07.brakes.cylinderPressure >= 0.1; ++i) { test::drive(driver, line, 1.0); } - REQUIRE(eu07.BrakePress < 0.1); + REQUIRE(eu07.brakes.cylinderPressure < 0.1); crew::secure(eu07, eu07); // on a slope it would roll away with the brakes off train.run(120.0, track{0.15, 0.02, test::catenary_3kv}); - CHECK(eu07.BrakePress > 2.0); + CHECK(eu07.brakes.cylinderPressure > 2.0); CHECK(std::abs(train[0].speed()) <= 0.01); } @@ -293,20 +293,20 @@ TEST_CASE("crew: the power an integrated handle asked for goes when the driver l CHECK(impuls->MainCtrlPos == impuls->MainCtrlNoPowerPos()); CHECK(impuls->eimic == 0.0); CHECK(impuls->eimic_real == 0.0); - CHECK(impuls->BrakeCtrlPos == static_cast(impuls->Handle->GetPos(bh_EB))); + CHECK(impuls->brakes.handlePosition == static_cast(impuls->brakes.driverValve->GetPos(bh_EB))); CHECK(impuls->CabOccupied == 0); } TEST_CASE("crew: a road vehicle left by its driver gets the brake the driver stops it with") { test::reseed_random(); vehicle bus{definition::fiz("road/man/nl293"), 40.0, "bus", 1}; - REQUIRE(bus->BrakeSystem == TBrakeSystem::Individual); - REQUIRE(bus->LocalBrakePosA == 0.0); + REQUIRE(bus->brakes.kind == TBrakeSystem::Individual); + REQUIRE(bus->brakes.independentPosition == 0.0); bus->CabActivisation(); crew::secure(bus.physics(), bus.physics()); - CHECK(bus->LocalBrakePosA == 1.0); + CHECK(bus->brakes.independentPosition == 1.0); CHECK(bus->MainCtrlPos == bus->MainCtrlNoPowerPos()); bus.run(60.0, track{0.6, 0.0, 0.0, 2}); CHECK(std::abs(bus.speed()) <= 0.01); diff --git a/tests/unit/test_definition.cpp b/tests/unit/test_definition.cpp index 2c62ce241..bed2aba2f 100644 --- a/tests/unit/test_definition.cpp +++ b/tests/unit/test_definition.cpp @@ -14,8 +14,8 @@ TEST_CASE("definition: the wagon from data/wagon.json loads with its values") { CHECK(wagon->Dim.L == doctest::Approx(26.8)); CHECK(wagon->WheelDiameter == doctest::Approx(0.96)); CHECK(wagon->NAxles == 4); - CHECK(wagon->MaxBrakePress[3] == doctest::Approx(3.8)); - CHECK(wagon->BrakeSystem == TBrakeSystem::Pneumatic); + CHECK(wagon->brakes.maxCylinderPressure[3] == doctest::Approx(3.8)); + CHECK(wagon->brakes.kind == TBrakeSystem::Pneumatic); } TEST_CASE("definition: keys set by the test reach the vehicle") { @@ -63,7 +63,7 @@ TEST_CASE("definition: lines the loader skips or trims: comments, a hash anywher REQUIRE(wagon.LoadFIZ_Text(crlf)); CHECK(wagon.Mass == doctest::Approx(42200.0)); CHECK(wagon.Vmax == doctest::Approx(120.0)); - CHECK(wagon.MaxBrakePress[3] == doctest::Approx(3.8)); + CHECK(wagon.brakes.maxCylinderPressure[3] == doctest::Approx(3.8)); } TEST_CASE("definition: a compressor list, whose positions allow the compressor and scale its speed and limits") { diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp index b6cadad19..606d1c83f 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -141,7 +141,7 @@ TEST_CASE("derailment: the brake hoses tear") { eu07vehicle.step(curve); } REQUIRE(eu07vehicle->Derailed == dr::outcome::overturned); - CHECK(eu07vehicle->AlarmChainFlag); + CHECK(eu07vehicle->brakes.alarmChain); } TEST_CASE("derailment: a stopped derailed vehicle stays put on a gradient") { diff --git a/tests/unit/test_diesel.cpp b/tests/unit/test_diesel.cpp index 847633ec0..b2713b620 100644 --- a/tests/unit/test_diesel.cpp +++ b/tests/unit/test_diesel.cpp @@ -111,7 +111,7 @@ TEST_CASE("diesel: the 214M railbus's torque converter, gears and retarder") { CHECK(railbus.eimic_real == doctest::Approx(eimic)); CHECK((railbus.retarder.fill > 0.99) == retarder); CHECK((railbus.retarder.torque > 1000.0) == retarder); - CHECK((railbus.BrakePress > 2.0) == air); + CHECK((railbus.brakes.cylinderPressure > 2.0) == air); } scenario.act("position 0"); railbus.DecMainCtrl(1); @@ -161,7 +161,7 @@ TEST_CASE("diesel: the 214M railbus's speed control, up to the speed of a button // the retarder does it at this speed, the air isn't needed CHECK(railbus.eimic_real == doctest::Approx(-1.0)); CHECK(railbus.retarder.fill == doctest::Approx(1.0)); - CHECK(railbus.BrakePress < 0.1); + CHECK(railbus.brakes.cylinderPressure < 0.1); CHECK_FALSE(railbus.SpeedCtrlUnit.BrakeInterventionBraking); scenario.wait(60.0); CHECK(railbus.Vel == doctest::Approx(40.0).epsilon(0.05)); diff --git a/tests/unit/test_drivingaid.cpp b/tests/unit/test_drivingaid.cpp index 4cdacb0ec..a8ef7ffa0 100644 --- a/tests/unit/test_drivingaid.cpp +++ b/tests/unit/test_drivingaid.cpp @@ -35,8 +35,8 @@ drivingaid::readout before(physics::Vehicle const &Physics) { drivingaid::readout result; result.throttle_first = Physics.EIMCtrlType > 0 ? std::max(0, static_cast(100.4 * Physics.eimic_real)) : Physics.MainCtrlPos; result.throttle_second = Physics.EIMCtrlType > 0 ? Physics.MainCtrlPos : Physics.ScndCtrlPos; - result.brake_first = Physics.UniCtrlIntegratedBrakeCtrl ? std::max(0.0, -100.0 * Physics.eimic_real) : Physics.fBrakeCtrlPos; - result.local_brake = Physics.LocalBrakePosA * LocalBrakePosNo; + result.brake_first = Physics.UniCtrlIntegratedBrakeCtrl ? std::max(0.0, -100.0 * Physics.eimic_real) : Physics.brakes.handlePositionSmooth; + result.local_brake = Physics.brakes.independentPosition * LocalBrakePosNo; return result; } @@ -68,7 +68,7 @@ TEST_CASE("driving aid: the Vectron's ED lever shows as a negative throttle step REQUIRE(braking.ed_percent.has_value()); CHECK(*braking.ed_percent == 40); // the train brake handle and the local brake, as before - CHECK(braking.brake_first == doctest::Approx(vectron->fBrakeCtrlPos)); + CHECK(braking.brake_first == doctest::Approx(vectron->brakes.handlePositionSmooth)); CHECK(braking.show_local_brake); CHECK(braking.local_brake == doctest::Approx(0.0)); @@ -99,7 +99,7 @@ TEST_CASE("driving aid: the Elf leaves out the local brake it has no control of, vehicle elf{definition::fiz("elf_v1/21we-a"), 60.0 /* km/h */, "elf", 1}; REQUIRE(elf->EIMCtrlType == 2); // the definition has a local brake (LocalBrake=PneumaticBrake, LocBrakeHandle=FD1), the cab no control of it - REQUIRE(elf->LocalBrake == TLocalBrake::PneumaticBrake); + REQUIRE(elf->brakes.localKind == TLocalBrake::PneumaticBrake); auto const idle{read(elf, elf_cab)}; CHECK_FALSE(idle.show_local_brake); @@ -117,7 +117,7 @@ TEST_CASE("driving aid: the Elf leaves out the local brake it has no control of, CHECK_FALSE(braking.show_local_brake); // applied after all (the AI, or the keys), it shows - elf->LocalBrakePosA = 0.3; + elf->brakes.independentPosition = 0.3; auto const applied{read(elf, elf_cab)}; CHECK(applied.show_local_brake); CHECK(applied.local_brake == doctest::Approx(3.0)); @@ -126,7 +126,7 @@ TEST_CASE("driving aid: the Elf leaves out the local brake it has no control of, TEST_CASE("driving aid: a vehicle without an EIM controller shows what it did") { vehicle eu07{definition::fiz("4e_v1/4e"), 60.0 /* km/h */, "eu07", 1}; eu07->MainCtrlPos = 5; - eu07->LocalBrakePosA = 0.2; + eu07->brakes.independentPosition = 0.2; auto const readout{read(eu07, lever_cab)}; CHECK(readout.throttle_first == 5); CHECK(readout.throttle_second == eu07->ScndCtrlPos); @@ -162,7 +162,7 @@ TEST_CASE("driving aid: every real vehicle with a local brake control shows the vehicle real{definition::fiz(path), 40.0 /* km/h */, "real", 1}; for (auto const &[mainctrl, localbrake, eimic] : {std::tuple{0, 0.0, 0.0}, std::tuple{1, 0.4, -0.25}, std::tuple{1, 0.0, 0.6}}) { real->MainCtrlPos = std::min(mainctrl, real->MainCtrlPosNo); - real->LocalBrakePosA = localbrake; + real->brakes.independentPosition = localbrake; real->eimic_real = eimic; auto const now{read(real, lever_cab)}; auto const was{before(real.physics())}; diff --git a/tests/unit/test_dynamic_brake_diesel.cpp b/tests/unit/test_dynamic_brake_diesel.cpp index 1d1e317b1..165343583 100644 --- a/tests/unit/test_dynamic_brake_diesel.cpp +++ b/tests/unit/test_dynamic_brake_diesel.cpp @@ -117,7 +117,7 @@ TEST_CASE("diesel-electric dynamic brake: the BR285's controller") { CHECK(-locomotive.Ft == doctest::Approx(br285_limit(locomotive)).epsilon(0.01)); CHECK(locomotive.Im > 0.0); CHECK(locomotive.EngineVoltage == doctest::Approx(0.0)); - CHECK(locomotive.BrakePress < 0.1); + CHECK(locomotive.brakes.cylinderPressure < 0.1); scenario.act("EB- to half"); controller_to(locomotive, 2); @@ -223,12 +223,12 @@ TEST_CASE("diesel-electric dynamic brake: blended with the locomotive's air brak scenario.notch_back(0); scenario.act("dynamic and train brake"); locomotive.DynamicBrakeLevelSet(1.0); - locomotive.BrakeLevelSet(locomotive.Handle->GetPos(bh_FB)); + locomotive.BrakeLevelSet(locomotive.brakes.driverValve->GetPos(bh_FB)); scenario.wait(6.0); REQUIRE(locomotive.Vel > 15.0); CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); CHECK(locomotive.brakePipe.pressure < 4.6); - CHECK((locomotive.BrakePress < 0.2) == blending); + CHECK((locomotive.brakes.cylinderPressure < 0.2) == blending); scenario.check(); } } @@ -252,7 +252,7 @@ TEST_CASE("diesel-electric dynamic brake: without a fade it brings the vehicle t for (int i = 0; i < 120 && locomotive.V != 0.0; ++i) { scenario.wait(1.0); } - CHECK(locomotive.BrakePress < 0.1); + CHECK(locomotive.brakes.cylinderPressure < 0.1); // at rest, and staying there: no speed either way, no force for (int i = 0; i < 5; ++i) { scenario.wait(1.0); diff --git a/tests/unit/test_elf_controller.cpp b/tests/unit/test_elf_controller.cpp index 47a62d5a8..c2d3847aa 100644 --- a/tests/unit/test_elf_controller.cpp +++ b/tests/unit/test_elf_controller.cpp @@ -66,7 +66,7 @@ struct elf { // the pipe charged again after an emergency stop: the Elf locks its emptied pipe off the brake handle (LPOn, // LPOff) until the unlock button (UBB1, the first universal brake button) is held, the handle at running void recharge() { - cab().BrakeLevelSet(cab().Handle->GetPos(bh_RP)); + cab().BrakeLevelSet(cab().brakes.driverValve->GetPos(bh_RP)); cab().UniversalBrakeButton(0, 1); wait(30.0); cab().UniversalBrakeButton(0, 0); @@ -144,7 +144,7 @@ TEST_CASE("elf controller: EIMCtrlMainEmergency shifts the positions up by the e CHECK(physics.eimic == doctest::Approx(-1.0)); unit.wait(10.0); CHECK(physics.brakePipe.pressure < 0.5); - CHECK(physics.BrakePress > 1.0); + CHECK(physics.brakes.cylinderPressure > 1.0); // out of it the pipe charges again physics.MainCtrlPos = physics.MainCtrlNoPowerPos(); CHECK_FALSE(physics.IsMainCtrlEmergencyPos()); @@ -301,17 +301,17 @@ void hold(elf &Unit, bool Hold) { auto const force{Unit.cab().brakes.holding.deceleration * mass}; for (std::size_t i = 0; i < Unit.unit.size(); ++i) { auto &car{Unit.car(i)}; - auto const nmax{((car.P2FTrans * car.MaxBrakePress[0] - car.BrakeCylSpring) * car.BrakeCylMult[0] - car.BrakeSlckAdj) * car.BrakeCylNo * car.BrakeRigEff}; - auto const fmax{nmax * car.Hamulec->GetFC(nmax / (car.NAxles * car.NBpA), car.brakes.blending.referenceSpeed) * 1000}; + auto const nmax{((car.brakes.pressureToForce * car.brakes.maxCylinderPressure[0] - car.brakes.cylinders.springForce) * car.brakes.cylinders.leverRatio[0] - car.brakes.cylinders.slackAdjusterForce) * car.brakes.cylinders.count * car.brakes.cylinders.riggingEfficiency}; + auto const fmax{nmax * car.brakes.distributor->GetFC(nmax / (car.NAxles * car.brakes.blocksPerAxle), car.brakes.blending.referenceSpeed) * 1000}; auto position{Hold ? force * car.NAxles / axles / fmax : 0.0}; if (position > 0.009) { - auto const slack{(car.BrakeSlckAdj / car.BrakeCylMult[0] + car.BrakeCylSpring) / (car.P2FTrans * car.MaxBrakePress[0])}; + auto const slack{(car.brakes.cylinders.slackAdjusterForce / car.brakes.cylinders.leverRatio[0] + car.brakes.cylinders.springForce) / (car.brakes.pressureToForce * car.brakes.maxCylinderPressure[0])}; position = slack + (1 - slack) * position; } else { position = 0.0; } - car.LocalBrakePosAEIM = position; + car.brakes.independentPositionEim = position; } } @@ -332,7 +332,7 @@ template start start_off(elf &Unit, double Seconds, Action Act hold(Unit, true); Unit.wait(10.0); start result; - result.pressure = cab.BrakePress; + result.pressure = cab.brakes.cylinderPressure; auto shuntmode{true}; auto const steps{std::lround(Seconds / step_time)}; for (long i = 0; i < steps && result.running < 0.0; ++i) { diff --git a/tests/unit/test_est3al2_relay.cpp b/tests/unit/test_est3al2_relay.cpp index 5af02f313..6d3e60e85 100644 --- a/tests/unit/test_est3al2_relay.cpp +++ b/tests/unit/test_est3al2_relay.cpp @@ -64,28 +64,28 @@ struct times { times measure(int const Delay, int const Lever) { test::reseed_random(); vehicle wagon{fas_413s()}; - REQUIRE(wagon->BrakeValve == TBrakeValve::ESt3AL2); - if (wagon->BrakeDelayFlag != Delay) { + REQUIRE(wagon->brakes.distributorType == TBrakeValve::ESt3AL2); + if (wagon->brakes.delaySetting != Delay) { REQUIRE(wagon->BrakeDelaySwitch(Delay)); } // an empty wagon starts with the lever at empty (physics::Vehicle::CheckLocomotiveParameters) - REQUIRE(wagon->LoadFlag == 1); - while (wagon->LoadFlag < Lever) { + REQUIRE(wagon->brakes.loadSetting == 1); + while (wagon->brakes.loadSetting < Lever) { REQUIRE(wagon->IncBrakeMult()); } - REQUIRE(wagon->LoadFlag == Lever); + REQUIRE(wagon->brakes.loadSetting == Lever); times result{}; wagon.hold_brake_pipe(5.0); wagon.run(180.0); - result.charged = wagon->BrakePress; + result.charged = wagon->brakes.cylinderPressure; double constexpr step{0.01}; std::vector cylinder; wagon.hold_brake_pipe(0.0); for (int i = 0; i < 6000; ++i) { wagon.step(); - cylinder.push_back(wagon->BrakePress); + cylinder.push_back(wagon->brakes.cylinderPressure); } result.applied = cylinder.back(); result.fill = -1.0; @@ -100,7 +100,7 @@ times measure(int const Delay, int const Lever) { result.release = -1.0; for (int i = 0; i < 18000; ++i) { wagon.step(); - if (wagon->BrakePress <= 0.4) { + if (wagon->brakes.cylinderPressure <= 0.4) { result.release = static_cast(i + 1) * step; break; } diff --git a/tests/unit/test_figures.cpp b/tests/unit/test_figures.cpp index bf8c004f1..718d722f7 100644 --- a/tests/unit/test_figures.cpp +++ b/tests/unit/test_figures.cpp @@ -25,7 +25,7 @@ TEST_CASE("figures: a run split into parts by the events, each from the last ste physics.V = 10.0 - i; physics.DistCounter += 0.005; physics.brakePipe.pressure = 3.5; - physics.BrakePress = 0.4 * i; + physics.brakes.cylinderPressure = 0.4 * i; figures.sample(i, physics); } figures.mark("release"); diff --git a/tests/unit/test_fiz.cpp b/tests/unit/test_fiz.cpp index 3e1b64760..54f7a1ac9 100644 --- a/tests/unit/test_fiz.cpp +++ b/tests/unit/test_fiz.cpp @@ -40,7 +40,7 @@ TEST_CASE("fiz: changes made by a test reach the vehicle") { CHECK(vehicle{eu07}->Mass == doctest::Approx(80000.0)); CHECK(vehicle{definition{eu07}.set("Param", "M", 90000)}->Mass == doctest::Approx(90000.0)); // a key the file doesn't have is added to its section - CHECK(vehicle{definition{eu07}.set("Brake", "MaxBP", 3.5)}->MaxBrakePress[3] == doctest::Approx(3.5)); + CHECK(vehicle{definition{eu07}.set("Brake", "MaxBP", 3.5)}->brakes.maxCylinderPressure[3] == doctest::Approx(3.5)); // removing a key brings its default back CHECK(vehicle{definition{eu07}.remove("Param", "Vmax")}->Vmax != doctest::Approx(125.0)); } diff --git a/tests/unit/test_genset.cpp b/tests/unit/test_genset.cpp index 7d4250d28..d0beab879 100644 --- a/tests/unit/test_genset.cpp +++ b/tests/unit/test_genset.cpp @@ -93,10 +93,10 @@ bool start_on_genset(vehicle &Vehicle, track const &Track = no_wire, double cons if (cab.Mains && cab.ConverterFlag && cab.mainPipe.pressure >= 4.5) { // and the brakes let go test::release_brakes(cab); - for (auto wait = 0; wait < 120 && cab.BrakePress > 0.05; ++wait) { + for (auto wait = 0; wait < 120 && cab.brakes.cylinderPressure > 0.05; ++wait) { run(Vehicle, 1.0, Track); } - return cab.BrakePress <= 0.05; + return cab.brakes.cylinderPressure <= 0.05; } } return false; @@ -486,7 +486,7 @@ braking brake_from_60(vehicle &Dragon, track const &Track) { } run(Dragon, 2.0, Track); cab.DynamicBrakeSwitch(true); - cab.BrakeLevelSet(cab.Handle->GetPos(bh_FB)); + cab.BrakeLevelSet(cab.brakes.driverValve->GetPos(bh_FB)); braking result; auto const speed{cab.Vel}; for (auto step_count = 0L; step_count < 2000; ++step_count) { diff --git a/tests/unit/test_handover.cpp b/tests/unit/test_handover.cpp index 263054cf6..03dc4d8c2 100644 --- a/tests/unit/test_handover.cpp +++ b/tests/unit/test_handover.cpp @@ -72,11 +72,11 @@ TEST_CASE("handover: the departure signal the AI was giving stops") { TEST_CASE("handover: the brake releaser the AI was holding lets go") { auto cab{cab_vehicle()}; cab->BrakeReleaser(1); - REQUIRE(cab->Hamulec->Releaser()); + REQUIRE(cab->brakes.distributor->Releaser()); handover::release_ai_controls(cab.physics(), cab.physics()); - CHECK_FALSE(cab->Hamulec->Releaser()); + CHECK_FALSE(cab->brakes.distributor->Releaser()); } TEST_CASE("handover: nothing the AI didn't latch changes") { @@ -87,7 +87,7 @@ TEST_CASE("handover: nothing the AI didn't latch changes") { CHECK(cab->WarningSignal == 0); CHECK_FALSE(cab->SandDose); CHECK_FALSE(cab->DepartureSignal); - CHECK_FALSE(cab->Hamulec->Releaser()); + CHECK_FALSE(cab->brakes.distributor->Releaser()); } TEST_CASE("handover: the light selector moves to the position giving the head lights the AI has set") { diff --git a/tests/unit/test_invariants.cpp b/tests/unit/test_invariants.cpp index 3abad65f6..94f32e0ab 100644 --- a/tests/unit/test_invariants.cpp +++ b/tests/unit/test_invariants.cpp @@ -16,7 +16,7 @@ TEST_CASE("invariants: a vehicle in an impossible state, reported once with its CHECK(trace.violations().empty()); trace.mark("overfilled"); - eu07->BrakePress = 50.0; + eu07->brakes.cylinderPressure = 50.0; trace.sample(0.01, eu07.physics()); trace.sample(0.02, eu07.physics()); REQUIRE(trace.violations().size() == 1); @@ -26,7 +26,7 @@ TEST_CASE("invariants: a vehicle in an impossible state, reported once with its CHECK(violation.find("after \"overfilled\"") != std::string::npos); CHECK(violation.find("BrakePress=50") != std::string::npos); - eu07->BrakePress = 0.0; + eu07->brakes.cylinderPressure = 0.0; eu07->V = std::nan(""); trace.sample(0.03, eu07.physics()); CHECK(trace.violations().size() > 1); diff --git a/tests/unit/test_line_contactors.cpp b/tests/unit/test_line_contactors.cpp index 6e2944d49..749cf8644 100644 --- a/tests/unit/test_line_contactors.cpp +++ b/tests/unit/test_line_contactors.cpp @@ -20,12 +20,12 @@ TEST_CASE("line contactors: with a pressure switch the lamp goes out with the st auto vehicle{locomotive(true)}; REQUIRE(vehicle->HasControlPressureSwitch); - vehicle->BrakePress = 1.5; // braked, the start can still be made + vehicle->brakes.cylinderPressure = 1.5; // braked, the start can still be made vehicle->MotorConnectorsCheck(); // updates the pressure switch REQUIRE_FALSE(vehicle->ControlPressureSwitch); CHECK(vehicle->LineContactorsLampLit()); - vehicle->BrakePress = 2.5; // the pressure switch cuts the start off + vehicle->brakes.cylinderPressure = 2.5; // the pressure switch cuts the start off vehicle->MotorConnectorsCheck(); REQUIRE(vehicle->ControlPressureSwitch); CHECK_FALSE(vehicle->LineContactorsLampLit()); @@ -33,10 +33,10 @@ TEST_CASE("line contactors: with a pressure switch the lamp goes out with the st TEST_CASE("line contactors: without a pressure switch the lamp goes out with the brakes applied, as before") { auto vehicle{locomotive(false)}; - vehicle->BrakePress = 0.5; + vehicle->brakes.cylinderPressure = 0.5; vehicle->MotorConnectorsCheck(); CHECK(vehicle->LineContactorsLampLit()); - vehicle->BrakePress = 1.5; + vehicle->brakes.cylinderPressure = 1.5; vehicle->MotorConnectorsCheck(); CHECK_FALSE(vehicle->LineContactorsLampLit()); } @@ -50,10 +50,10 @@ TEST_CASE("line contactors: closed contactors put the lamp out") { TEST_CASE("line contactors: the ground relay and overload lamps follow the same rule") { // all the lamps of the main circuit go out together, with the pressure switch where it's fitted auto vehicle{locomotive(true)}; - vehicle->BrakePress = 1.5; + vehicle->brakes.cylinderPressure = 1.5; vehicle->MotorConnectorsCheck(); CHECK(vehicle->MainCircuitLampsEnabled()); - vehicle->BrakePress = 2.5; + vehicle->brakes.cylinderPressure = 2.5; vehicle->MotorConnectorsCheck(); CHECK_FALSE(vehicle->MainCircuitLampsEnabled()); } diff --git a/tests/unit/test_line_contactors_interlock.cpp b/tests/unit/test_line_contactors_interlock.cpp index 4a2ed9c5e..f7f6d69a9 100644 --- a/tests/unit/test_line_contactors_interlock.cpp +++ b/tests/unit/test_line_contactors_interlock.cpp @@ -25,7 +25,7 @@ vehicle ready(std::string_view const Interlock) { locomotive->Mains = true; locomotive->DirActive = 1; locomotive->brakePipe.pressure = 5.0; - locomotive->BrakePress = 0.0; + locomotive->brakes.cylinderPressure = 0.0; return locomotive; } @@ -133,7 +133,7 @@ bool close_line_contactors(test::driven const &Driven) { // the brakes released and the cylinders empty enough for the pressure switch to let the vehicle start void release(test::driven const &Driven) { test::release_brakes(Driven.cab); - for (int i = 0; i < 90 && (Driven.controlling.BrakePress > 0.1 || Driven.controlling.brakePipe.pressure < 4.8); ++i) { + for (int i = 0; i < 90 && (Driven.controlling.brakes.cylinderPressure > 0.1 || Driven.controlling.brakePipe.pressure < 4.8); ++i) { test::drive(Driven, line, 1.0); } } @@ -183,7 +183,7 @@ TEST_CASE("line contactors interlock: with blowers starting with the speed the v while (physics.DecMainCtrl(1)) { // down to zero } - driven.cab.BrakeLevelSet(driven.cab.Handle->GetPos(bh_FB)); + driven.cab.BrakeLevelSet(driven.cab.brakes.driverValve->GetPos(bh_FB)); for (int i = 0; i < 120 && std::abs(eu07.speed()) > 0.1; ++i) { test::drive(driven, line, 1.0); } diff --git a/tests/unit/test_pressure_switch.cpp b/tests/unit/test_pressure_switch.cpp index cc3d48aca..5f787cee3 100644 --- a/tests/unit/test_pressure_switch.cpp +++ b/tests/unit/test_pressure_switch.cpp @@ -73,12 +73,12 @@ void get_under_power(test::vehicle &Loco, test::driven const &Driven, int const void apply_independent_brake(test::vehicle &Loco, test::driven const &Driven) { Loco->IncLocalBrakeLevel(LocalBrakePosNo); test::drive(Driven, line, 20.0); - REQUIRE(Loco->BrakePress == doctest::Approx(3.8).epsilon(0.03)); + REQUIRE(Loco->brakes.cylinderPressure == doctest::Approx(3.8).epsilon(0.03)); REQUIRE(Loco->brakePipe.pressure > 4.8); } void emergency_application(test::vehicle &Loco, test::driven const &Driven) { - Loco->BrakeLevelSet(Loco->Handle->GetPos(bh_EB)); + Loco->BrakeLevelSet(Loco->brakes.driverValve->GetPos(bh_EB)); test::drive(Driven, line, 10.0); REQUIRE(Loco->brakePipe.pressure < 1.0); } @@ -126,7 +126,7 @@ TEST_CASE("pressure switch: without its brake cylinder half the EP05 takes curre CHECK(loco->StLinFlag); CHECK(loco->MainCtrlActualPos == 3); CHECK(std::abs(loco->Im) > 100.0); - CHECK(loco->BrakePress == doctest::Approx(3.8).epsilon(0.03)); + CHECK(loco->brakes.cylinderPressure == doctest::Approx(3.8).epsilon(0.03)); MESSAGE("current with 3.8 bar in the brake cylinders, position 3: " << std::abs(loco->Im) << " A"); } @@ -136,7 +136,7 @@ TEST_CASE("pressure switch: without its brake cylinder half the brake pipe still get_under_power(loco, driven, 5); SUBCASE("a service application") { - loco->BrakeLevelSet(loco->Handle->GetPos(bh_FB)); + loco->BrakeLevelSet(loco->brakes.driverValve->GetPos(bh_FB)); test::drive(driven, line, 15.0); REQUIRE(loco->brakePipe.pressure < 3.6); REQUIRE(loco->brakePipe.pressure > 3.0); @@ -158,7 +158,7 @@ TEST_CASE("pressure switch: an emergency application with the master controller get_under_power(loco, driven, 5); SUBCASE("made with the brake handle") { - loco->BrakeLevelSet(loco->Handle->GetPos(bh_EB)); + loco->BrakeLevelSet(loco->brakes.driverValve->GetPos(bh_EB)); } SUBCASE("made with the emergency brake of the train") { loco->AlarmChainSwitch(true); diff --git a/tests/unit/test_pullee.cpp b/tests/unit/test_pullee.cpp index e9917747a..3591e6e95 100644 --- a/tests/unit/test_pullee.cpp +++ b/tests/unit/test_pullee.cpp @@ -78,17 +78,17 @@ TEST_CASE("pullee: a dead Vectron vents the brake pipe of the train hauling it, REQUIRE((train.hauled->InactiveCabFlag & activation::emergencybrake) != 0); REQUIRE_FALSE(train.hauled->PulleeMode); train.run(120.0); - CHECK(train.hauled->EmergencyValveFlow > 0.0); + CHECK(train.hauled->brakes.emergencyValve.flow > 0.0); CHECK(train.locomotive->brakePipe.pressure < 4.95); // the pipe sags although the locomotive keeps feeding it - CHECK(train.hauled->BrakePress > 0.4); + CHECK(train.hauled->brakes.cylinderPressure > 0.4); CHECK(train.hauled.speed() < 30.0); } SUBCASE("prepared for hauling") { hauled_train train{vectron, 60.0, true}; train.run(120.0); - CHECK(train.hauled->EmergencyValveFlow == 0.0); + CHECK(train.hauled->brakes.emergencyValve.flow == 0.0); CHECK(train.locomotive->brakePipe.pressure > 4.99); - CHECK(train.hauled->BrakePress < 0.1); + CHECK(train.hauled->brakes.cylinderPressure < 0.1); CHECK(train.hauled->Fb < 1.0); CHECK(train.hauled.speed() > 40.0); // running resistance alone } @@ -116,14 +116,14 @@ TEST_CASE("pullee: an EU07 with a driver can't release the brakes of a dead Vect // the Vectron has emptied the brake pipe, and both locomotives stand on an emergency application CHECK(hauled->Battery); CHECK(locomotive->brakePipe.pressure < 1.0); - CHECK(locomotive->BrakePress > 3.0); - CHECK(hauled->BrakePress > 3.0); + CHECK(locomotive->brakes.cylinderPressure > 3.0); + CHECK(hauled->brakes.cylinderPressure > 3.0); continue; } CHECK_FALSE(hauled->Battery); CHECK(locomotive->brakePipe.pressure > 4.9); - CHECK(locomotive->BrakePress < 0.1); - CHECK(hauled->BrakePress < 0.1); + CHECK(locomotive->brakes.cylinderPressure < 0.1); + CHECK(hauled->brakes.cylinderPressure < 0.1); // the driver notches up watching the ammeter for (int i = 0; i < 3 && driven.cab.DirActive <= 0; ++i) { driven.cab.DirectionForward(); @@ -177,7 +177,7 @@ TEST_CASE("pullee: a dead EU47 starts to drag once its main reservoir has leaked hauled.brakes.spring.activate = false; train.run(180.0); // charged and released: nothing holds it yet - CHECK(hauled.BrakePress < 0.1); + CHECK(hauled.brakes.cylinderPressure < 0.1); CHECK(hauled.Fb < 1.0); train.run(1020.0); // 20 minutes since the start CHECK(hauled.mainPipe.pressure < hauled.brakes.spring.minForcePressure); @@ -204,17 +204,17 @@ TEST_CASE("pullee: a vehicle prepared for hauling brakes and releases with the t drain_feed_air(train.hauled.physics()); } train.run(30.0); - CHECK(hauled.BrakePress < 0.1); + CHECK(hauled.brakes.cylinderPressure < 0.1); // a full service application train.locomotive.hold_brake_pipe(3.5); train.run(20.0); - CHECK(hauled.BrakePress > 2.0); + CHECK(hauled.brakes.cylinderPressure > 2.0); CHECK(hauled.Fb > 30000.0); train.locomotive.hold_brake_pipe(5.0); train.run(90.0); - CHECK(hauled.BrakePress < 0.1); + CHECK(hauled.brakes.cylinderPressure < 0.1); CHECK(hauled.Fb < 1.0); - CHECK(hauled.EmergencyValveFlow == 0.0); + CHECK(hauled.brakes.emergencyValve.flow == 0.0); } } } @@ -235,11 +235,11 @@ TEST_CASE("pullee: the spring brake of an Impuls prepared for hauling doesn't ca REQUIRE(hauled.Vel > 2.0); REQUIRE(hauled.brakes.spring.isActive); if (pullee) { - CHECK(hauled.EmergencyValveFlow == 0.0); - CHECK(hauled.BrakePress < 0.1); + CHECK(hauled.brakes.emergencyValve.flow == 0.0); + CHECK(hauled.brakes.cylinderPressure < 0.1); } else { - CHECK(hauled.EmergencyValveFlow > 0.0); + CHECK(hauled.brakes.emergencyValve.flow > 0.0); } } } @@ -261,25 +261,25 @@ TEST_CASE("pullee: the brake valves in the cab of a vehicle prepared for hauling // the local brake a driver keeps a standing vehicle on is let go driven->DecLocalBrakeLevel(LocalBrakePosNo); driven.run(20.0); - REQUIRE(driven->BrakePress < 0.1); + REQUIRE(driven->brakes.cylinderPressure < 0.1); auto const charged{driven->brakePipe.pressure}; // full service braking with the driver's valve - driven->BrakeLevelSet(driven->Handle->GetPos(bh_FB)); + driven->BrakeLevelSet(driven->brakes.driverValve->GetPos(bh_FB)); driven.run(10.0); if (pullee) { - CHECK(driven->dpMainValve == 0.0); + CHECK(driven->brakes.driverValveFlow == 0.0); CHECK(driven->brakePipe.pressure > charged - 0.1); - CHECK(driven->BrakePress < 0.1); + CHECK(driven->brakes.cylinderPressure < 0.1); } else { CHECK(driven->brakePipe.pressure < charged - 0.5); - CHECK(driven->BrakePress > 1.0); + CHECK(driven->brakes.cylinderPressure > 1.0); } // and the emergency position - driven->BrakeLevelSet(driven->Handle->GetPos(bh_EB)); + driven->BrakeLevelSet(driven->brakes.driverValve->GetPos(bh_EB)); driven.run(10.0); if (pullee) { - CHECK(driven->dpMainValve == 0.0); + CHECK(driven->brakes.driverValveFlow == 0.0); CHECK(driven->brakePipe.pressure > charged - 0.1); } else { @@ -304,13 +304,13 @@ TEST_CASE("pullee: the local brake of a vehicle prepared for hauling stays relea // applied with the lever, as on a vehicle left on standby, and asked for by the brake computer of a unit // (what the MED of TDynamicObject writes; the lever of a Vectron does nothing without it) driven->IncLocalBrakeLevel(LocalBrakePosNo); - driven->LocalBrakePosAEIM = 1.0; + driven->brakes.independentPositionEim = 1.0; driven.run(20.0); if (pullee) { - CHECK(driven->BrakePress < 0.1); + CHECK(driven->brakes.cylinderPressure < 0.1); } else { - CHECK(driven->BrakePress > 1.0); + CHECK(driven->brakes.cylinderPressure > 1.0); } } } @@ -329,9 +329,9 @@ TEST_CASE("pullee: entering the mode lets go of the hand brake and the spring br } SUBCASE("a unit standing with its hand brake on") { vehicle en57{definition::fiz("en57_v1/5bgb")}; - REQUIRE(en57->ManualBrakePos > 0); + REQUIRE(en57->brakes.handBrakePosition > 0); CHECK(en57->PulleeModeSwitch(true)); - CHECK(en57->ManualBrakePos == 0); + CHECK(en57->brakes.handBrakePosition == 0); } SUBCASE("a locomotive ready to depart, its battery on") { vehicle vectron{definition::fiz("vectron_v1/wariant_7w"), 0.1}; @@ -352,7 +352,7 @@ TEST_CASE("pullee: the battery and the cabs of a vehicle prepared for hauling st vectron.run(5.0); // the vigilance device and the cab signalling of a cab never activated stay out of it CHECK_FALSE(vectron->SecuritySystem.is_braking()); - CHECK(vectron->EmergencyValveFlow == 0.0); + CHECK(vectron->brakes.emergencyValve.flow == 0.0); REQUIRE(vectron->PulleeModeSwitch(false)); CHECK_FALSE(vectron->PulleeMode); @@ -378,7 +378,7 @@ TEST_CASE("pullee: a cab activated on a dead battery calls the emergency brake, CHECK(vectron->CabActivisation() == (false == pullee)); vectron.run(0.5); CHECK(vectron->SecuritySystem.is_braking() == (false == pullee)); - CHECK((vectron->EmergencyValveFlow > 0.0) == (false == pullee)); + CHECK((vectron->brakes.emergencyValve.flow > 0.0) == (false == pullee)); } } @@ -418,8 +418,8 @@ TEST_CASE("pullee: every real vehicle prepared for hauling runs free behind a lo auto const &hauled{train.hauled.physics()}; drain_feed_air(train.hauled.physics()); train.run(60.0); - CHECK(hauled.EmergencyValveFlow == 0.0); - CHECK(hauled.BrakePress < 0.1); + CHECK(hauled.brakes.emergencyValve.flow == 0.0); + CHECK(hauled.brakes.cylinderPressure < 0.1); CHECK(hauled.Fb < 1.0); CHECK(train.locomotive->brakePipe.pressure > 4.99); CHECK(train.hauled.speed() > 40.0); @@ -437,12 +437,12 @@ TEST_CASE("pullee: every real vehicle standing braked releases once prepared for // hand brakes on, spring brakes switched on, cylinders half full, the pipe at 3.5 hauled_train train{definition::fiz(path), 0.0, true}; auto const &hauled{train.hauled.physics()}; - CHECK(hauled.ManualBrakePos == 0); + CHECK(hauled.brakes.handBrakePosition == 0); CHECK_FALSE(hauled.brakes.spring.activate); CHECK_FALSE(hauled.Battery); train.run(180.0); - CHECK(hauled.EmergencyValveFlow == 0.0); - CHECK(hauled.BrakePress < 0.1); + CHECK(hauled.brakes.emergencyValve.flow == 0.0); + CHECK(hauled.brakes.cylinderPressure < 0.1); // the cylinders of a few are still letting out the last of their air (6Dg, SM42, 810: 15-72 N) CHECK(hauled.Fb < 500.0); } diff --git a/tests/unit/test_speed_control.cpp b/tests/unit/test_speed_control.cpp index b54a6aa9c..09647c188 100644 --- a/tests/unit/test_speed_control.cpp +++ b/tests/unit/test_speed_control.cpp @@ -49,10 +49,10 @@ void get_6dg_going(scenario &Scenario) { REQUIRE(Scenario.start_up()); Scenario.get_going(); move_to(loco, dg_no_power); - for (int second = 0; second < 180 && loco.BrakePress > 0.1; ++second) { + for (int second = 0; second < 180 && loco.brakes.cylinderPressure > 0.1; ++second) { Scenario.wait(1.0); } - REQUIRE(loco.BrakePress <= 0.1); + REQUIRE(loco.brakes.cylinderPressure <= 0.1); move_to(loco, dg_lower); Scenario.wait(1.0); move_to(loco, dg_hold); diff --git a/tests/unit/test_traction.cpp b/tests/unit/test_traction.cpp index f3f2acefa..8ae1d1f9f 100644 --- a/tests/unit/test_traction.cpp +++ b/tests/unit/test_traction.cpp @@ -51,7 +51,7 @@ using namespace test::channels; void stop(scenario &Scenario) { Scenario.notch_back(0); Scenario.act("brake"); - Scenario.cab().BrakeLevelSet(Scenario.cab().Handle->GetPos(bh_FB)); + Scenario.cab().BrakeLevelSet(Scenario.cab().brakes.driverValve->GetPos(bh_FB)); Scenario.wait(60.0); } @@ -187,7 +187,7 @@ TEST_CASE("traction: the stages of the EW58's electrodynamic brake, set by the p CHECK(ew58.Im < 0.0); } scenario.act("release"); - ew58.BrakeLevelSet(ew58.Handle->GetPos(bh_RP)); + ew58.BrakeLevelSet(ew58.brakes.driverValve->GetPos(bh_RP)); scenario.wait(10.0); CHECK(ew58.TUHEX_StageActual == 0); scenario.check(); @@ -242,7 +242,7 @@ TEST_CASE("traction: the induction motor drive's speed control, its electrodynam scenario.wait(5.0); CHECK(eu47.DynamicBrakeFlag); CHECK(eu47.Im == doctest::Approx(0.0)); - CHECK(eu47.BrakePress > 2.0); + CHECK(eu47.brakes.cylinderPressure > 2.0); scenario.act("local brake off"); eu47.DecLocalBrakeLevel(LocalBrakePosNo); scenario.wait(10.0); @@ -252,12 +252,12 @@ TEST_CASE("traction: the induction motor drive's speed control, its electrodynam CAPTURE(voltage); scenario.line().voltage = voltage; scenario.act(std::format("service brake at {} V", static_cast(voltage))); - eu47.BrakeLevelSet(eu47.Handle->GetPos(bh_FB)); + eu47.BrakeLevelSet(eu47.brakes.driverValve->GetPos(bh_FB)); scenario.wait(6.0); CHECK(eu47.DynamicBrakeFlag); CHECK(eu47.Im < -100.0); CHECK((eu47.Vadd > 1.0) == (voltage > eu47.EnginePowerSource.CollectorParameters.MaxV)); - eu47.BrakeLevelSet(eu47.Handle->GetPos(bh_RP)); + eu47.BrakeLevelSet(eu47.brakes.driverValve->GetPos(bh_RP)); scenario.wait(6.0); } scenario.line().voltage = test::catenary_3kv; diff --git a/tests/unit/vehicle.cpp b/tests/unit/vehicle.cpp index 0f5fa9c21..0c36df05f 100644 --- a/tests/unit/vehicle.cpp +++ b/tests/unit/vehicle.cpp @@ -136,11 +136,11 @@ vehicle::vehicle(definition const &Definition, double Velocity, std::string cons throw definition_error("parameters mismatch in the test vehicle definition"); } m_physics->MainCtrlPos = m_physics->MainCtrlNoPowerPos(); - m_physics->LocalBrakePosA = 0.0; + m_physics->brakes.independentPosition = 0.0; if (driveractive) { - m_physics->BrakeCtrlPos = static_cast(std::floor(m_physics->Handle->GetPos(Cab == 0 ? bh_NP : bh_RP))); + m_physics->brakes.handlePosition = static_cast(std::floor(m_physics->brakes.driverValve->GetPos(Cab == 0 ? bh_NP : bh_RP))); // a driver keeps a vehicle on standby on its independent brake - if (Cab != 0 && m_physics->LocalBrake != TLocalBrake::ManualBrake && Velocity < 1.0) { + if (Cab != 0 && m_physics->brakes.localKind != TLocalBrake::ManualBrake && Velocity < 1.0) { m_physics->IncLocalBrakeLevel(LocalBrakePosNo); if (m_physics->EIMCtrlEmergency) { m_physics->DecLocalBrakeLevel(1); @@ -148,9 +148,9 @@ vehicle::vehicle(definition const &Definition, double Velocity, std::string cons } } else { - m_physics->BrakeCtrlPos = static_cast(std::floor(m_physics->Handle->GetPos(bh_NP))); + m_physics->brakes.handlePosition = static_cast(std::floor(m_physics->brakes.driverValve->GetPos(bh_NP))); } - m_physics->BrakeLevelSet(m_physics->BrakeCtrlPos); + m_physics->BrakeLevelSet(m_physics->brakes.handlePosition); } void vehicle::step(track const &Track, double Dt) { @@ -237,7 +237,7 @@ double vehicle::move(track const &Track, double Dt, TLocation const &Location, d if (m_cab != 0) { using enum TEngineType; // the driver's own vehicle, which gets the average pressure of the train's brake pipe - physics.EqvtPipePress = Trainpipe; + physics.brakes.equivalentPipePressure = Trainpipe; if (auto const diesel{physics.EngineType == DieselEngine || physics.EngineType == DieselElectric}; diesel && physics.EIMCtrlType > 0) { physics.CheckEIMIC(Dt); if (physics.SpeedCtrl) { diff --git a/vehicle/ai/consist.cpp b/vehicle/ai/consist.cpp index 28c700cb5..ed08ac78d 100644 --- a/vehicle/ai/consist.cpp +++ b/vehicle/ai/consist.cpp @@ -72,8 +72,8 @@ void TController::Activation() occupied->SpringBrakeActivate( false ); } // odcięcie na zaworze maszynisty, FVel6 po drugiej stronie nie luzuje - occupied->BrakeLevelSet( occupied->Handle->GetPos(bh_NP) ); // odcięcie na zaworze maszynisty - BrakeLevelSet( occupied->BrakeCtrlPos ); //ustawienie zmiennej GBH + occupied->BrakeLevelSet( occupied->brakes.driverValve->GetPos(bh_NP) ); // odcięcie na zaworze maszynisty + BrakeLevelSet( occupied->brakes.handlePosition ); //ustawienie zmiennej GBH } // przejście AI na drugą stronę EN57, ET41 itp. // TODO: clean this up, there's lot of redundancy with physics::Vehicle::ChangeCab() and TTrain::MoveToVehicle() @@ -95,7 +95,7 @@ void TController::Activation() // TODO: investigate and resolve if necessary pVehicle->physics->CabOccupied = targetvehicle->physics->CabOccupied; if( pVehicle->Mechanik ) { // not guaranteed, as target vehicle can be empty - pVehicle->Mechanik->BrakeLevelSet( pVehicle->physics->BrakeCtrlPos ); + pVehicle->Mechanik->BrakeLevelSet( pVehicle->physics->brakes.handlePosition ); } // finish driver swap pVehicle = targetvehicle; @@ -104,13 +104,13 @@ void TController::Activation() if (pVehicle != initialvehicle) { // jeśli zmieniony został pojazd prowadzony ControllingSet(); // utworzenie połączenia do sterowanego pojazdu (może się zmienić) - silnikowy dla EZT - if( occupied->BrakeCtrlPosNo > 0 + if( occupied->brakes.handlePositions > 0 && ( BrakeSystem == TBrakeSystem::Pneumatic || BrakeSystem == TBrakeSystem::ElectroPneumatic ) ) { - occupied->LimPipePress = occupied->brakePipe.pressure; + occupied->brakes.pipeLimiterPressure = occupied->brakePipe.pressure; occupied->ActFlowSpeed = 0; } - BrakeLevelSet( occupied->BrakeCtrlPos ); + BrakeLevelSet( occupied->brakes.handlePosition ); } if( mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->ShuntModeAllow ) { // dla 2Ls150 - przed ustawieniem kierunku - można zmienić tryb pracy @@ -177,8 +177,8 @@ void TController::AutoRewident() if( true == AIControllFlag ) { // if a human is in charge leave the brake mode up to them, otherwise do as you like for( int i = 1; i <= 8; i *= 2 ) { - if( ( occupied->BrakeOpModes & i ) > 0 ) { - occupied->BrakeOpModeFlag = i; + if( ( occupied->brakes.availableOperatingModes & i ) > 0 ) { + occupied->brakes.operatingMode = i; } } } @@ -229,8 +229,8 @@ void TController::AutoRewident() fBrake_a1[i+1] /= 12 * fMass; } - IsPassengerTrain = is_train() && false == is_emu() && false == is_dmu() && (occupied->BrakeDelayFlag & bdelay_G) == 0; - IsCargoTrain = is_train() && (occupied->BrakeDelayFlag & bdelay_G) != 0; + IsPassengerTrain = is_train() && false == is_emu() && false == is_dmu() && (occupied->brakes.delaySetting & bdelay_G) == 0; + IsCargoTrain = is_train() && (occupied->brakes.delaySetting & bdelay_G) != 0; IsHeavyCargoTrain = true == IsCargoTrain && fBrake_a0[1] > 0.4 && iVehicles - ControlledEnginesCount > 0 && fMass / iVehicles > 50000; BrakingInitialLevel = IsHeavyCargoTrain ? 1.25 : IsCargoTrain ? 1.25 : 1.00; @@ -319,13 +319,13 @@ bool TController::CheckVehicles(DriverOrders user) && p->Mechanik != this && p->Mechanik->drivingFlags.primary ) { // ale chodzi o inny pojazd, niż aktualnie sprawdzający // a tamten ma priorytet // TODO: take into account drivers' operating modes, one or more of them might be on banking duty - if (drivingFlags.primary && occupied->DirAbsolute && occupied->BrakeCtrlPos >= -1) + if (drivingFlags.primary && occupied->DirAbsolute && occupied->brakes.handlePosition >= -1) { // jeśli rządzi i ma kierunek p->Mechanik->primary(false); // dezaktywuje tamtego p->Mechanik->ZeroLocalBrake(); - p->physics->BrakeLevelSet(p->physics->Handle->GetPos(bh_NP)); // odcięcie na zaworze maszynisty - p->Mechanik->BrakeLevelSet(p->physics->BrakeCtrlPos); // ustawienie zmiennej GBH + p->physics->BrakeLevelSet(p->physics->brakes.driverValve->GetPos(bh_NP)); // odcięcie na zaworze maszynisty + p->Mechanik->BrakeLevelSet(p->physics->brakes.handlePosition); // ustawienie zmiennej GBH } else { @@ -338,8 +338,8 @@ bool TController::CheckVehicles(DriverOrders user) fMass += p->physics->TotalMass; // dodanie masy łącznie z ładunkiem fVelMax = min_speed( fVelMax, p->physics->Vmax ); // ustalenie maksymalnej prędkości dla składu // reset oerlikon brakes consist flag as different type was detected - if( p->physics->BrakeSubsystem != TBrakeSubSystem::ss_ESt - && p->physics->BrakeSubsystem != TBrakeSubSystem::ss_LSt ) { + if( p->physics->brakes.subsystem != TBrakeSubSystem::ss_ESt + && p->physics->brakes.subsystem != TBrakeSubSystem::ss_LSt ) { drivingFlags.oerlikons = false; } p = p->Neighbour(dir); // pojazd podłączony od wskazanej strony @@ -666,7 +666,7 @@ void TController::ControllingSet() return; } occupied = pVehicle->physics; // domyślny skrót do obiektu parametrów - BrakeSystem = occupied->BrakeSystem; // domyślny sposób hamowania + BrakeSystem = occupied->brakes.kind; // domyślny sposób hamowania mvControlling = pVehicle->FindPowered()->physics; // poszukiwanie członu sterowanego { auto *lookup { pVehicle->FindPantographCarrier() }; @@ -702,8 +702,8 @@ TController::determine_consist_state() { Ready = true; // wstępnie gotowy fReady = 0.0; // założenie, że odhamowany - IsConsistBraked = occupied->BrakeSystem == TBrakeSystem::ElectroPneumatic && false == ForcePNBrake ? occupied->BrakePress > 2.0 : - occupied->brakePipe.pressure < std::max(3.9, occupied->BrakePressureActual.PipePressureVal) + 0.1; + IsConsistBraked = occupied->brakes.kind == TBrakeSystem::ElectroPneumatic && false == ForcePNBrake ? occupied->brakes.cylinderPressure > 2.0 : + occupied->brakePipe.pressure < std::max(3.9, occupied->brakes.actualPressure.PipePressureVal) + 0.1; fAccGravity = 0.0; // przyspieszenie wynikające z pochylenia IsAnyCouplerStretched = false; IsAnyDoorOnlyOpen[ VehicleSide::right ] = IsAnyDoorOnlyOpen[ VehicleSide::left ] = false; @@ -723,18 +723,18 @@ TController::determine_consist_state() { while (p) { // sprawdzenie odhamowania wszystkich połączonych pojazdów auto *vehicle { p->physics }; - auto const bp { std::max( 0.0, vehicle->BrakePress - ( vehicle->SpeedCtrlUnit.Parking ? vehicle->MaxBrakePress[ 0 ] * vehicle->brakes.holding.deceleration : 0.0 ) ) }; + auto const bp { std::max( 0.0, vehicle->brakes.cylinderPressure - ( vehicle->SpeedCtrlUnit.Parking ? vehicle->brakes.maxCylinderPressure[ 0 ] * vehicle->brakes.holding.deceleration : 0.0 ) ) }; momentum += vehicle->TotalMass * vehicle->V * ( p->DirectionGet() == iDirection ? 1 : -1 ); mostapplied = std::max( bp, mostapplied ); - if( ( vehicle->BrakeSystem != TBrakeSystem::Individual ) - && ( vehicle->MaxBrakePress[ 3 ] > 0.0 ) - && ( false == TestFlag( vehicle->Hamulec->GetBrakeStatus(), b_dmg ) ) ) { // a brake cut out doesn't count - chargelevel = std::min( { chargelevel, vehicle->brakePipe.pressure, vehicle->Hamulec->GetBRP() } ); + if( ( vehicle->brakes.kind != TBrakeSystem::Individual ) + && ( vehicle->brakes.maxCylinderPressure[ 3 ] > 0.0 ) + && ( false == TestFlag( vehicle->brakes.distributor->GetBrakeStatus(), b_dmg ) ) ) { // a brake cut out doesn't count + chargelevel = std::min( { chargelevel, vehicle->brakePipe.pressure, vehicle->brakes.distributor->GetBRP() } ); } auto const wasready { Ready }; if( released || Ready ) { // bo jak coś nie odhamowane, to dalej nie ma co sprawdzać - auto const isbraking { TestFlagAny( vehicle->Hamulec->GetBrakeStatus(), b_hld | b_on ) }; + auto const isbraking { TestFlagAny( vehicle->brakes.distributor->GetBrakeStatus(), b_hld | b_on ) }; if( vehicle->Vel < 1.0 ? isbraking || bp > 0.4 : // ensure the brakes are sufficiently released when starting to move // once in motion a brake down to 0.4 bar counts as released (UIC), even if its distributor @@ -750,15 +750,15 @@ TController::determine_consist_state() { if( wasready ) { // Ra: odluźnianie przeładowanych lokomotyw, ciągniętych na zimno - prowizorka... if( bp >= 0.4 && (AIControllFlag || Global.AITrainman && occupied->Vel < EU07_AI_NOMOVEMENT && !is_emu() && !is_dmu()) && BrakeCtrlPosition == gbh_RP // jest pozycja jazdy - && false == TestFlag(vehicle->Hamulec->GetBrakeStatus(), b_dmg) // brake isn't broken - && vehicle->brakePipe.pressure - occupied->Handle->GetRP() > -0.1 // jeśli ciśnienie jak dla jazdy - && vehicle->Hamulec->GetCRP() > vehicle->brakePipe.pressure + 0.12 ) { // wg UIC określone sztywno na 0.04 + && false == TestFlag(vehicle->brakes.distributor->GetBrakeStatus(), b_dmg) // brake isn't broken + && vehicle->brakePipe.pressure - occupied->brakes.driverValve->GetRP() > -0.1 // jeśli ciśnienie jak dla jazdy + && vehicle->brakes.distributor->GetCRP() > vehicle->brakePipe.pressure + 0.12 ) { // wg UIC określone sztywno na 0.04 // za dużo w zbiorniku // indywidualne luzowanko vehicle->BrakeReleaser(1); } - if (bp < 0.1 && (AIControllFlag || Global.AITrainman) && false == TestFlag(vehicle->Hamulec->GetBrakeStatus(), b_dmg) // brake isn't broken - && vehicle->Hamulec->GetCRP() < vehicle->brakePipe.pressure - 0.1) { + if (bp < 0.1 && (AIControllFlag || Global.AITrainman) && false == TestFlag(vehicle->brakes.distributor->GetBrakeStatus(), b_dmg) // brake isn't broken + && vehicle->brakes.distributor->GetCRP() < vehicle->brakePipe.pressure - 0.1) { // już nie jest za dużo w zbiorniku // koniec indywidualnego luzowanka vehicle->BrakeReleaser(0); @@ -896,9 +896,9 @@ TController::determine_consist_state() { AIControllFlag ? BrakeCtrlPosition > 0.0 : // a human driver's handle, which BrakeCtrlPosition doesn't follow - occupied->fBrakeCtrlPos > occupied->Handle->GetPos( bh_RP ) + 0.2 }; + occupied->brakes.handlePositionSmooth > occupied->brakes.driverValve->GetPos( bh_RP ) + 0.2 }; auto const reference { - brake_charge::reference( occupied->brakePipe.pressure, std::min( occupied->Handle->GetRP(), 5.0 ), trainbrakeapplied ) }; + brake_charge::reference( occupied->brakePipe.pressure, std::min( occupied->brakes.driverValve->GetRP(), 5.0 ), trainbrakeapplied ) }; // air to charge with: the engine prepared, the main reservoir above what the pipe charges to, and the driver's // brake valve feeding the pipe at the head of the train. a train still being prepared from cold can't charge, // nor one whose pipe is locked (unlocked by control_releaser()): it waits without that counting as a stall, held diff --git a/vehicle/ai/controls.cpp b/vehicle/ai/controls.cpp index 42d8fb2d6..d488e2c53 100644 --- a/vehicle/ai/controls.cpp +++ b/vehicle/ai/controls.cpp @@ -59,16 +59,16 @@ TController::increase_train_brake() { d = pVehicles[0]; // pojazd na czele składu while (d) { // przeliczanie dodatkowego potrzebnego spadku ciśnienia - if( ( d->physics->Hamulec->GetBrakeStatus() & b_dmg ) == 0 ) { - pos_corr -= ( std::min( 5.0, d->physics->Hamulec->GetCRP() ) - 5.0 ) * d->physics->TotalMass; + if( ( d->physics->brakes.distributor->GetBrakeStatus() & b_dmg ) == 0 ) { + pos_corr -= ( std::min( 5.0, d->physics->brakes.distributor->GetCRP() ) - 5.0 ) * d->physics->TotalMass; } d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) } pos_corr = pos_corr / fMass * 2.5; - if (occupied->BrakeHandle == TBrakeHandle::FV4a) + if (occupied->brakes.driverValveType == TBrakeHandle::FV4a) { - pos_corr += occupied->Handle->GetCP()*0.2; + pos_corr += occupied->brakes.driverValve->GetCP()*0.2; } if( double const deltaAcc = -AccDesired*BrakeAccFactor() - (fBrake_a0[0] + 4.0 * (/*GBH occupied->BrakeCtrlPosR*/BrakeCtrlPosition - 1 - pos_corr)*fBrake_a1[0]); @@ -102,9 +102,9 @@ TController::increase_train_brake() { if( BrakeCtrlPosition > 0.0 && AccDesired < 0.0 // only while braking is asked for, not when called for a train slipping back while starting && ( fBrakeHeldTime > ( - occupied->BrakeDelayFlag > bdelay_G ? - occupied->BrakeDelay[ 1 ] : - occupied->BrakeDelay[ 3 ] ) + occupied->brakes.delaySetting > bdelay_G ? + occupied->brakes.delays[ 1 ] : + occupied->brakes.delays[ 3 ] ) // a train falling further behind needs no full fill time to be seen not to get enough || ( ( fShortfall > 0.02 ) && ( fBrakeHeldTime > brake_response_horizon( occupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) ) { @@ -125,7 +125,7 @@ bool TController::IncBrake() BrakeSystem }; switch( bs ) { case TBrakeSystem::Individual: { - if( occupied->LocalBrake == TLocalBrake::ManualBrake ) { + if( occupied->brakes.localKind == TLocalBrake::ManualBrake ) { OK = occupied->IncManualBrakeLevel( 1 + static_cast( std::floor( 0.5 + std::fabs( AccDesired ) ) ) ); } else { @@ -134,11 +134,11 @@ bool TController::IncBrake() break; } case TBrakeSystem::Pneumatic: { - if (bs != occupied->BrakeSystem) + if (bs != occupied->brakes.kind) { - while (occupied->BrakeOpModeFlag > bom_PN) + while (occupied->brakes.operatingMode > bom_PN) { - occupied->BrakeOpModeFlag >>= 1; + occupied->brakes.operatingMode >>= 1; } } // NOTE: can't perform just test whether connected vehicle == nullptr, due to virtual couplers formed with nearby vehicles @@ -211,41 +211,41 @@ bool TController::IncBrake() } } if( /*GBH occupied->BrakeCtrlPos*/ - /*GBH occupied->BrakeCtrlPos*/ BrakeCtrlPosition > 0 && occupied->Hamulec->Releaser() ) { + /*GBH occupied->BrakeCtrlPos*/ BrakeCtrlPosition > 0 && occupied->brakes.distributor->Releaser() ) { occupied->BrakeReleaser(0); } break; } case TBrakeSystem::ElectroPneumatic: { - while( occupied->BrakeOpModeFlag << 1 <= occupied->BrakeOpModes ) { - occupied->BrakeOpModeFlag <<= 1; + while( occupied->brakes.operatingMode << 1 <= occupied->brakes.availableOperatingModes ) { + occupied->brakes.operatingMode <<= 1; } if( occupied->EngineType == TEngineType::ElectricInductionMotor ) { - if (occupied->BrakeHandle == TBrakeHandle::MHZ_EN57) { - if (occupied->BrakeCtrlPos < occupied->Handle->GetPos(bh_FB)) + if (occupied->brakes.driverValveType == TBrakeHandle::MHZ_EN57) { + if (occupied->brakes.handlePosition < occupied->brakes.driverValve->GetPos(bh_FB)) OK = occupied->BrakeLevelAdd(1.0); } else { OK = IncBrakeEIM(); } } - else if( occupied->Handle->TimeEP == false ) { - auto const initialbrakeposition { occupied->fBrakeCtrlPos }; + else if( occupied->brakes.driverValve->TimeEP == false ) { + auto const initialbrakeposition { occupied->brakes.handlePositionSmooth }; auto const AccMax { std::min( fBrake_a0[ 0 ] + 12 * fBrake_a1[ 0 ], occupied->brakes.blending.maxDeceleration ) }; occupied->BrakeLevelSet( std::lerp( - occupied->Handle->GetPos( bh_EPR ), - occupied->Handle->GetPos( bh_EPB ), + occupied->brakes.driverValve->GetPos( bh_EPR ), + occupied->brakes.driverValve->GetPos( bh_EPB ), std::clamp( -AccDesired / AccMax * occupied->AIHintLocalBrakeAccFactor, 0.0, 1.0 ) ) ); - OK = occupied->fBrakeCtrlPos != initialbrakeposition; + OK = occupied->brakes.handlePositionSmooth != initialbrakeposition; } - else if( occupied->fBrakeCtrlPos != occupied->Handle->GetPos( bh_EPB ) ) { - occupied->BrakeLevelSet( occupied->Handle->GetPos( bh_EPB ) ); - if( occupied->Handle->GetPos( bh_EPR ) - occupied->Handle->GetPos( bh_EPN ) < 0.1 ) + else if( occupied->brakes.handlePositionSmooth != occupied->brakes.driverValve->GetPos( bh_EPB ) ) { + occupied->BrakeLevelSet( occupied->brakes.driverValve->GetPos( bh_EPB ) ); + if( occupied->brakes.driverValve->GetPos( bh_EPR ) - occupied->brakes.driverValve->GetPos( bh_EPN ) < 0.1 ) occupied->SwitchEPBrake( 1 ); // to nie chce działać OK = true; } - else if( ( occupied->Handle->GetPos( bh_EPR ) - occupied->Handle->GetPos( bh_EPN ) < 0.1 ) + else if( ( occupied->brakes.driverValve->GetPos( bh_EPR ) - occupied->brakes.driverValve->GetPos( bh_EPN ) < 0.1 ) && ( occupied->EpForce <= 0.0 ) && ( occupied->EPBrakeControlPowered() ) ) { // the handle already in the EP brake position, but the EP brake dropped out with the control's @@ -273,8 +273,8 @@ bool TController::IncBrakeEIM() auto const brakelimit{ -2.2 * AccDesired / fMedAmax - 1.0}; //additional limit when hinted is too low auto const brakehinted{ -1.0 * occupied->AIHintLocalBrakeAccFactor * AccDesired / fMedAmax }; //preffered by AI auto const brakeposition{ maxpos * std::clamp(std::max(brakelimit, brakehinted), 0.0, 1.0)}; - OK = brakeposition != occupied->LocalBrakePosA; - occupied->LocalBrakePosA = brakeposition; + OK = brakeposition != occupied->brakes.independentPosition; + occupied->brakes.independentPosition = brakeposition; } else { OK = occupied->IncLocalBrakeLevel( 1 ); @@ -324,7 +324,7 @@ bool TController::DecBrake() { switch( bs ) { case TBrakeSystem::Individual: { auto const positionchange { 1 + std::floor( 0.5 + std::abs( AccDesired ) ) }; - OK = occupied->LocalBrake == TLocalBrake::ManualBrake ? occupied->DecManualBrakeLevel(positionchange) : occupied->DecLocalBrakeLevel(positionchange); + OK = occupied->brakes.localKind == TLocalBrake::ManualBrake ? occupied->DecManualBrakeLevel(positionchange) : occupied->DecLocalBrakeLevel(positionchange); break; } case TBrakeSystem::Pneumatic: { @@ -382,8 +382,8 @@ bool TController::DecBrake() { } case TBrakeSystem::ElectroPneumatic: { if( occupied->EngineType == TEngineType::ElectricInductionMotor ) { - if( occupied->BrakeHandle == TBrakeHandle::MHZ_EN57 ) { - if( occupied->BrakeCtrlPos > occupied->Handle->GetPos( bh_RP ) ) { + if( occupied->brakes.driverValveType == TBrakeHandle::MHZ_EN57 ) { + if( occupied->brakes.handlePosition > occupied->brakes.driverValve->GetPos( bh_RP ) ) { OK = occupied->BrakeLevelAdd( -1.0 ); } } @@ -391,23 +391,23 @@ bool TController::DecBrake() { OK = DecBrakeEIM(); } } - else if( occupied->Handle->TimeEP == false ) { - auto const initialbrakeposition { occupied->fBrakeCtrlPos }; + else if( occupied->brakes.driverValve->TimeEP == false ) { + auto const initialbrakeposition { occupied->brakes.handlePositionSmooth }; auto const AccMax { std::min( fBrake_a0[ 0 ] + 12 * fBrake_a1[ 0 ], occupied->brakes.blending.maxDeceleration ) }; occupied->BrakeLevelSet( std::lerp( - occupied->Handle->GetPos( bh_EPR ), - occupied->Handle->GetPos( bh_EPB ), + occupied->brakes.driverValve->GetPos( bh_EPR ), + occupied->brakes.driverValve->GetPos( bh_EPB ), std::clamp( -AccDesired / AccMax * occupied->AIHintLocalBrakeAccFactor, 0.0, 1.0 ) ) ); - OK = occupied->fBrakeCtrlPos != initialbrakeposition; + OK = occupied->brakes.handlePositionSmooth != initialbrakeposition; } else { OK = false; - if (occupied->fBrakeCtrlPos != occupied->Handle->GetPos(bh_EPR)) { - occupied->BrakeLevelSet(occupied->Handle->GetPos(bh_EPR)); + if (occupied->brakes.handlePositionSmooth != occupied->brakes.driverValve->GetPos(bh_EPR)) { + occupied->BrakeLevelSet(occupied->brakes.driverValve->GetPos(bh_EPR)); OK = true; } - if (occupied->Handle->GetPos(bh_EPR) - occupied->Handle->GetPos(bh_EPN) < 0.1) { + if (occupied->brakes.driverValve->GetPos(bh_EPR) - occupied->brakes.driverValve->GetPos(bh_EPN) < 0.1) { OK = OK || occupied->SwitchEPBrake(1); } } @@ -425,12 +425,12 @@ bool TController::DecBrake() { void TController::LapBrake() { - if( occupied->Handle->TimeEP ) { - if( occupied->Handle->GetPos( bh_EPR ) - occupied->Handle->GetPos( bh_EPN ) < 0.1 ) { + if( occupied->brakes.driverValve->TimeEP ) { + if( occupied->brakes.driverValve->GetPos( bh_EPR ) - occupied->brakes.driverValve->GetPos( bh_EPN ) < 0.1 ) { occupied->SwitchEPBrake( 0 ); } else { - occupied->BrakeLevelSet( occupied->Handle->GetPos( bh_EPN ) ); + occupied->BrakeLevelSet( occupied->brakes.driverValve->GetPos( bh_EPN ) ); } } } @@ -456,8 +456,8 @@ bool TController::DecBrakeEIM() if( occupied->brakes.blending.maxDeceleration != 9.81 ) { auto const desiredacceleration { ( occupied->Vel > EU07_AI_NOMOVEMENT ? AccDesired : std::max( 0.0, AccDesired ) ) }; auto const brakeposition { std::clamp( -1.0 * occupied->AIHintLocalBrakeAccFactor * desiredacceleration / occupied->brakes.blending.maxDeceleration, 0.0, 1.0 ) }; - OK = brakeposition != occupied->LocalBrakePosA; - occupied->LocalBrakePosA = brakeposition; + OK = brakeposition != occupied->brakes.independentPosition; + occupied->brakes.independentPosition = brakeposition; } else { OK = occupied->DecLocalBrakeLevel( 1 ); @@ -1120,33 +1120,33 @@ void TController::SetTimeControllers() //1. Check the type of Main Brake Handle if( BrakeSystem == TBrakeSystem::Pneumatic || ForcePNBrake ) { - if (occupied->Handle->Time) + if (occupied->brakes.driverValve->Time) { - auto const pressuredifference { occupied->Handle->GetCP() - ( occupied->HighPipePress - BrakeCtrlPosition * 0.25*occupied->DeltaPipePress ) }; + auto const pressuredifference { occupied->brakes.driverValve->GetCP() - ( occupied->brakes.pipeHighPressure - BrakeCtrlPosition * 0.25*occupied->brakes.pipePressureRange ) }; if (BrakeCtrlPosition > 0 && pressuredifference > 0.05) - occupied->BrakeLevelSet(occupied->Handle->GetPos(bh_FB)); + occupied->BrakeLevelSet(occupied->brakes.driverValve->GetPos(bh_FB)); else if (BrakeCtrlPosition > 0 && pressuredifference < -0.05) - occupied->BrakeLevelSet(occupied->Handle->GetPos(bh_RP)); + occupied->BrakeLevelSet(occupied->brakes.driverValve->GetPos(bh_RP)); else if (BrakeCtrlPosition == 0) - occupied->BrakeLevelSet(occupied->Handle->GetPos(bh_RP)); + occupied->BrakeLevelSet(occupied->brakes.driverValve->GetPos(bh_RP)); else if (BrakeCtrlPosition == -1) - occupied->BrakeLevelSet(occupied->Handle->GetPos(bh_FS)); + occupied->BrakeLevelSet(occupied->brakes.driverValve->GetPos(bh_FS)); else if (BrakeCtrlPosition == -2) - occupied->BrakeLevelSet(occupied->Handle->GetPos(bh_NP)); + occupied->BrakeLevelSet(occupied->brakes.driverValve->GetPos(bh_NP)); } - if( occupied->BrakeHandle == TBrakeHandle::FV4a ) { + if( occupied->brakes.driverValveType == TBrakeHandle::FV4a ) { occupied->BrakeLevelSet( BrakeCtrlPosition ); } - if( occupied->BrakeHandle == TBrakeHandle::MHZ_K8P - || occupied->BrakeHandle == TBrakeHandle::MHZ_EN57 ) { + if( occupied->brakes.driverValveType == TBrakeHandle::MHZ_K8P + || occupied->brakes.driverValveType == TBrakeHandle::MHZ_EN57 ) { if( BrakeCtrlPosition == 0 ) { - occupied->BrakeLevelSet( occupied->Handle->GetPos( bh_RP ) ); + occupied->BrakeLevelSet( occupied->brakes.driverValve->GetPos( bh_RP ) ); } else if( BrakeCtrlPosition == -1 ) { - occupied->BrakeLevelSet( occupied->Handle->GetPos( bh_FS ) ); + occupied->BrakeLevelSet( occupied->brakes.driverValve->GetPos( bh_FS ) ); } else if( BrakeCtrlPosition == -2 ) { - occupied->BrakeLevelSet( occupied->Handle->GetPos( bh_NP ) ); + occupied->BrakeLevelSet( occupied->brakes.driverValve->GetPos( bh_NP ) ); } else if( BrakeCtrlPosition > 4.5 ) { occupied->BrakeLevelSet( 10 ); @@ -1176,7 +1176,7 @@ void TController::SetTimeControllers() } */ if( occupied->UniCtrlIntegratedLocalBrakeCtrl - && occupied->LocalBrakePosA > 0.95 ) { + && occupied->brakes.independentPosition > 0.95 ) { while( IncBrakeEIM() ) { ; } } @@ -1322,7 +1322,7 @@ void TController::SetTimeControllers() } //6.2. Setting buttons for (int i = 0; i < 3; i++) { - occupied->UniversalBrakeButton(i, UniversalBrakeButtons & occupied->UniversalBrakeButtonFlag[i]); + occupied->UniversalBrakeButton(i, UniversalBrakeButtons & occupied->brakes.universalButtonActions[i]); } }; @@ -1332,16 +1332,16 @@ void TController::CheckTimeControllers() if( false == AIControllFlag || 0 == mvControlling->CabActive ) { return; } //1. Check the type of Main Brake Handle - if( BrakeSystem == TBrakeSystem::ElectroPneumatic && occupied->Handle->TimeEP && !ForcePNBrake ) + if( BrakeSystem == TBrakeSystem::ElectroPneumatic && occupied->brakes.driverValve->TimeEP && !ForcePNBrake ) { - occupied->BrakeLevelSet(occupied->Handle->GetPos(bh_EPN)); + occupied->BrakeLevelSet(occupied->brakes.driverValve->GetPos(bh_EPN)); } - if( ( BrakeSystem == TBrakeSystem::Pneumatic || ForcePNBrake ) && occupied->Handle->Time ) + if( ( BrakeSystem == TBrakeSystem::Pneumatic || ForcePNBrake ) && occupied->brakes.driverValve->Time ) { if (BrakeCtrlPosition > 0) - occupied->BrakeLevelSet(occupied->Handle->GetPos(bh_MB)); + occupied->BrakeLevelSet(occupied->brakes.driverValve->GetPos(bh_MB)); else - occupied->BrakeLevelSet(occupied->Handle->GetPos(bh_RP)); + occupied->BrakeLevelSet(occupied->brakes.driverValve->GetPos(bh_RP)); } //2. Check the type of Secondary Brake Handle diff --git a/vehicle/ai/driver.cpp b/vehicle/ai/driver.cpp index c78c627b2..abd9f279e 100644 --- a/vehicle/ai/driver.cpp +++ b/vehicle/ai/driver.cpp @@ -130,7 +130,7 @@ TController::~TController() TBrakeSystem TController::consist_brake_system() const { - if( occupied->BrakeSystem != TBrakeSystem::ElectroPneumatic ) { return occupied->BrakeSystem; } + if( occupied->brakes.kind != TBrakeSystem::ElectroPneumatic ) { return occupied->brakes.kind; } auto isepcapable = true; if( pVehicles[ VehicleEnd::front ] != pVehicles[ VehicleEnd::rear ] ) { diff --git a/vehicle/ai/engine.cpp b/vehicle/ai/engine.cpp index 7f8d27c72..af3e9b1a1 100644 --- a/vehicle/ai/engine.cpp +++ b/vehicle/ai/engine.cpp @@ -176,12 +176,12 @@ bool TController::PrepareEngine() } control_field_shunting(); // sync virtual brake state with the 'real' one - if( occupied->BrakeHandle != TBrakeHandle::NoHandle ) { + if( occupied->brakes.driverValveType != TBrakeHandle::NoHandle ) { std::unordered_map const brakepositions{ - { static_cast( occupied->Handle->GetPos( bh_RP ) ), gbh_RP }, - { static_cast( occupied->Handle->GetPos( bh_NP ) ), gbh_NP }, - { static_cast( occupied->Handle->GetPos( bh_FS ) ), gbh_FS } }; - auto const lookup{ brakepositions.find( static_cast( occupied->fBrakeCtrlPos ) ) }; + { static_cast( occupied->brakes.driverValve->GetPos( bh_RP ) ), gbh_RP }, + { static_cast( occupied->brakes.driverValve->GetPos( bh_NP ) ), gbh_NP }, + { static_cast( occupied->brakes.driverValve->GetPos( bh_FS ) ), gbh_FS } }; + auto const lookup{ brakepositions.find( static_cast( occupied->brakes.handlePositionSmooth ) ) }; if( lookup != brakepositions.end() ) { BrakeLevelSet( lookup->second ); // GBH } @@ -191,9 +191,9 @@ bool TController::PrepareEngine() // standing: the locomotive brake first, then the pipe is filled secure_standing_train(); } - else if( ( occupied->fBrakeCtrlPos != occupied->Handle->GetPos( bh_RP ) ) - && ( ( false == occupied->Handle->Time ) - || ( occupied->Handle->GetCP() < occupied->HighPipePress - 0.05 ) ) ) { + else if( ( occupied->brakes.handlePositionSmooth != occupied->brakes.driverValve->GetPos( bh_RP ) ) + && ( ( false == occupied->brakes.driverValve->Time ) + || ( occupied->brakes.driverValve->GetCP() < occupied->brakes.pipeHighPressure - 0.05 ) ) ) { cue_action( driver_hint::trainbrakerelease ); } // sync spring brake state across consist @@ -325,8 +325,8 @@ bool TController::ReleaseEngine() { // activate parking brake // TBD: do it earlier? cue_action( driver_hint::springbrakeon ); - if( occupied->LocalBrake == TLocalBrake::ManualBrake - || occupied->MBrake == true ) { + if( occupied->brakes.localKind == TLocalBrake::ManualBrake + || occupied->brakes.hasHandBrake == true ) { cue_action( driver_hint::manualbrakon ); } // switch off remaining power diff --git a/vehicle/ai/force.cpp b/vehicle/ai/force.cpp index ca37e43c7..315085c4a 100644 --- a/vehicle/ai/force.cpp +++ b/vehicle/ai/force.cpp @@ -95,7 +95,7 @@ TController::control_tractive_and_braking_force() { control_braking_force(); #if LOGVELOCITY - WriteLog("BrakePos=" + AnsiString(occupied->BrakeCtrlPos) + ", MainCtrl=" + + WriteLog("BrakePos=" + AnsiString(occupied->brakes.handlePosition) + ", MainCtrl=" + AnsiString(mvControlling->MainCtrlPos)); #endif } @@ -256,8 +256,8 @@ void TController::control_uphill_start() { if( bUphillBrakeTopUp ) { return; } - if( ( occupied->LocalBrake != TLocalBrake::ManualBrake ) - && ( occupied->LocalBrakePosA > 0.0 ) ) { + if( ( occupied->brakes.localKind != TLocalBrake::ManualBrake ) + && ( occupied->brakes.independentPosition > 0.0 ) ) { cue_action( driver_hint::independentbrakerelease ); } if( ( velocity > 1.0 ) @@ -297,7 +297,7 @@ bool TController::uphill_brake_top_up() { } auto const action { uphill_start::brake_top_up( UphillTopUp, trainbrakeforce, fUphillHoldingForce, BrakeCtrlPosition, fBrakeHeldTime, - occupied->BrakeDelay[ occupied->BrakeDelayFlag > bdelay_G ? 1 : 3 ] ) }; + occupied->brakes.delays[ occupied->brakes.delaySetting > bdelay_G ? 1 : 3 ] ) }; if( action == uphill_start::top_up_action::none ) { return false; } @@ -334,7 +334,7 @@ void TController::secure_standing_train() { if( false == bHasRun ) { bBrakeChargeStart = true; } - if( occupied->LocalBrake != TLocalBrake::ManualBrake ) { + if( occupied->brakes.localKind != TLocalBrake::ManualBrake ) { cue_action( driver_hint::independentbrakeapply ); } if( false == brake_charge::locomotive_brake_holds( locomotive_brake_force(), fMass * fAccGravity ) ) { @@ -356,12 +356,12 @@ void TController::secure_standing_train() { // no other, not on a second section or a locomotive in multiple control either, let alone one hauled dead double TController::locomotive_brake_force() const { - if( ( occupied->LocalBrake == TLocalBrake::ManualBrake ) - || ( occupied->MaxBrakePress[ 0 ] <= 0.0 ) ) { + if( ( occupied->brakes.localKind == TLocalBrake::ManualBrake ) + || ( occupied->brakes.maxCylinderPressure[ 0 ] <= 0.0 ) ) { return 0.0; } return brake_charge::locomotive_brake_force( - occupied->BrakeForceP( occupied->MaxBrakePress[ 0 ], 0.0 ), + occupied->BrakeForceP( occupied->brakes.maxCylinderPressure[ 0 ], 0.0 ), occupied->TotalMassxg ); } @@ -511,7 +511,7 @@ void TController::control_braking_force() { // TODO: check whether brake delay variable still has any purpose cue_action(driver_hint::brakingforceincrease, // Ra: ten czas należy zmniejszyć, jeśli czas dojazdu do zatrzymania jest mniejszy - (3.0 + 0.5 * ((occupied->BrakeDelayFlag > bdelay_G ? occupied->BrakeDelay[1] : occupied->BrakeDelay[3]) - 3.0)) * 0.5); // Ra: tymczasowo, bo przeżyna S1 + (3.0 + 0.5 * ((occupied->brakes.delaySetting > bdelay_G ? occupied->brakes.delays[1] : occupied->brakes.delays[3]) - 3.0)) * 0.5); // Ra: tymczasowo, bo przeżyna S1 } else if( ( BrakeSystem == TBrakeSystem::Pneumatic ) && ( AccDesired < 0.0 ) @@ -534,19 +534,19 @@ void TController::control_braking_force() { || ( false == brake_charge::release_waits( IsConsistCharged, occupied->Vel < EU07_AI_NOMOVEMENT, - occupied->fBrakeCtrlPos > occupied->Handle->GetPos( bh_RP ) + 0.2 ) ) ) ) { // the human driver's handle + occupied->brakes.handlePositionSmooth > occupied->brakes.driverValve->GetPos( bh_RP ) + 0.2 ) ) ) ) { // the human driver's handle // jak hamuje, to nie tykaj kranu za często // yB: luzuje hamulec dopiero przy różnicy opóźnień rzędu 0.2 // przy odłączaniu nie zwalniamy tu hamulca // sanity check to prevent unintended brake release on sharp slopes // TODO: check whether brake delay variable still has any purpose cue_action(driver_hint::brakingforcedecrease, - (occupied->BrakeDelayFlag > bdelay_G ? occupied->BrakeDelay[0] : occupied->BrakeDelay[2]) / 3.0 * 0.5); // Ra: tymczasowo, bo przeżyna S1 + (occupied->brakes.delaySetting > bdelay_G ? occupied->brakes.delays[0] : occupied->brakes.delays[2]) / 3.0 * 0.5); // Ra: tymczasowo, bo przeżyna S1 } // uphill, the locomotive brake acts at once while the train brake of a long train takes many seconds to apply: // put it on as the train comes to a stand, and at once if the train has started to roll back - if( ( occupied->LocalBrake != TLocalBrake::ManualBrake ) - && ( occupied->LocalBrakePosA < 1.0 ) + if( ( occupied->brakes.localKind != TLocalBrake::ManualBrake ) + && ( occupied->brakes.independentPosition < 1.0 ) && ( ( uphill_stop_hold() && ( std::abs( velocity ) < 3.0 ) // a train that has slowed down short of where it is to stop and is to pull up further does not get it && ( VelDesired <= std::abs( velocity ) + 0.5 ) @@ -556,7 +556,7 @@ void TController::control_braking_force() { } // stop-gap measure to ensure cars actually brake to stop even when above calculactions go awry // instead of releasing the brakes and creeping into obstacle at 1-2 km/h - if( is_car() && VelDesired == 0.0 && velocity > VelDesired && ActualProximityDist <= fMinProximityDist && occupied->LocalBrakePosA < 0.01 ) { + if( is_car() && VelDesired == 0.0 && velocity > VelDesired && ActualProximityDist <= fMinProximityDist && occupied->brakes.independentPosition < 0.01 ) { cue_action(driver_hint::brakingforceincrease); } } @@ -579,9 +579,9 @@ void TController::control_braking_force() { void TController::apply_independent_brake_only() { - if( occupied->LocalBrake != TLocalBrake::ManualBrake ) { + if( occupied->brakes.localKind != TLocalBrake::ManualBrake ) { if( false == occupied->ShuntMode // no need for independent brake if autobrake is active - && is_equal(occupied->fBrakeCtrlPos, occupied->Handle->GetPos(bh_RP), 0.2) ) { + && is_equal(occupied->brakes.handlePositionSmooth, occupied->brakes.driverValve->GetPos(bh_RP), 0.2) ) { cue_action( driver_hint::independentbrakeapply ); } else { @@ -599,19 +599,19 @@ void TController::control_releaser() { auto const hasreleaser { false == (is_dmu() || is_emu()) // TODO: a more refined test than rejecting these types wholesale - && ( occupied->BrakeHandle == TBrakeHandle::FV4a - || occupied->BrakeHandle == TBrakeHandle::MHZ_6P - || occupied->BrakeHandle == TBrakeHandle::MHZ_K5P - || occupied->BrakeHandle == TBrakeHandle::MHZ_K8P - || occupied->BrakeHandle == TBrakeHandle::M394 ) }; + && ( occupied->brakes.driverValveType == TBrakeHandle::FV4a + || occupied->brakes.driverValveType == TBrakeHandle::MHZ_6P + || occupied->brakes.driverValveType == TBrakeHandle::MHZ_K5P + || occupied->brakes.driverValveType == TBrakeHandle::MHZ_K8P + || occupied->brakes.driverValveType == TBrakeHandle::M394 ) }; if( false == hasreleaser ) { return; } brake_releaser::conditions state; state.acceleration_desired = AccDesired; state.pipe_pressure = occupied->brakePipe.pressure; - state.cylinder_pressure = occupied->BrakePress; - state.control_pressure = occupied->Hamulec->GetCRP(); + state.cylinder_pressure = occupied->brakes.cylinderPressure; + state.control_pressure = occupied->brakes.distributor->GetCRP(); state.velocity = occupied->Vel; state.uphill_start = bUphillStart; state.pressing = drivingFlags.press; @@ -625,28 +625,28 @@ void TController::control_releaser() { state.charging_standing = bBrakeChargeStart && ( occupied->Vel < EU07_AI_NOMOVEMENT ) - && ( ( occupied->HandleUnlock == -3 ) || ( BrakeCtrlPosition <= 0.0 ) ); + && ( ( occupied->brakes.pipeLock.unlockHandlePosition == -3 ) || ( BrakeCtrlPosition <= 0.0 ) ); auto const wanted { brake_releaser::decide( state ) }; auto const actuate { wanted.actuate }; auto isbrakehandleinrightposition { true }; // some vehicles require brake handle to be moved to specific position to fill up the brake pipe if( wanted.fill_pipe - && occupied->HandleUnlock != -3 ) { + && occupied->brakes.pipeLock.unlockHandlePosition != -3 ) { cue_action( driver_hint::trainbrakesetpipeunlock ); - isbrakehandleinrightposition = ( BrakeCtrlPosition == occupied->HandleUnlock ); + isbrakehandleinrightposition = ( BrakeCtrlPosition == occupied->brakes.pipeLock.unlockHandlePosition ); } if( actuate ) { // some vehicles may require master controller in neutral position cue_action( driver_hint::mastercontrollersetzerospeed ); - if( false == occupied->Hamulec->Releaser() + if( false == occupied->brakes.distributor->Releaser() && isbrakehandleinrightposition ) { cue_action( driver_hint::releaseron ); } } else { - if( true == occupied->Hamulec->Releaser() ) { + if( true == occupied->brakes.distributor->Releaser() ) { cue_action( driver_hint::releaseroff ); } } @@ -658,25 +658,25 @@ void TController::control_main_pipe() { if( ( AccDesired > -0.03 // standing to charge before the first start, as in control_releaser() || ( bBrakeChargeStart && ( occupied->Vel < EU07_AI_NOMOVEMENT ) ) ) - && true == occupied->LockPipe ) { + && true == occupied->brakes.pipeLock.locked ) { UniversalBrakeButtons |= TUniversalBrake::ub_UnlockPipe; } - else if (false == occupied->LockPipe ) { + else if (false == occupied->brakes.pipeLock.locked ) { UniversalBrakeButtons &= ~TUniversalBrake::ub_UnlockPipe; } // napełnianie uderzeniowe if( BrakeSystem != TBrakeSystem::Pneumatic ) { return; } - if( occupied->BrakeHandle == TBrakeHandle::FV4a - || occupied->BrakeHandle == TBrakeHandle::MHZ_6P - || occupied->BrakeHandle == TBrakeHandle::MHZ_K5P - || occupied->BrakeHandle == TBrakeHandle::MHZ_K8P - || occupied->BrakeHandle == TBrakeHandle::M394 ) { + if( occupied->brakes.driverValveType == TBrakeHandle::FV4a + || occupied->brakes.driverValveType == TBrakeHandle::MHZ_6P + || occupied->brakes.driverValveType == TBrakeHandle::MHZ_K5P + || occupied->brakes.driverValveType == TBrakeHandle::MHZ_K8P + || occupied->brakes.driverValveType == TBrakeHandle::M394 ) { auto const departblocked { is_departure_blocked( DepartBlockedFSDelay ) }; if( (drivingFlags.oerlikons || true == IsCargoTrain || departblocked) && BrakeCtrlPosition == gbh_RP && AbsAccS < 0.03 && AccDesired > -0.03 && VelDesired - occupied->Vel > 2.0 && fReady > 0.35 && - ( occupied->EqvtPipePress < 4.5 || departblocked ) // don't charge with a risk of overcharging the main pipe + ( occupied->brakes.equivalentPipePressure < 4.5 || departblocked ) // don't charge with a risk of overcharging the main pipe && occupied->air.mainReservoirPressure >= 7.5 // don't charge without sufficient pressure in the tank && BrakeChargingCooldown >= 0.0 // don't charge while cooldown is active && (ActualProximityDist > 100.0 // don't charge if we're about to be braking soon @@ -691,7 +691,7 @@ void TController::control_main_pipe() { if( ( occupied->air.mainReservoirPressure < 5.0 || ( BrakeCtrlPosition < gbh_RP - && ( occupied->EqvtPipePress > (fReady < 0.25 ? 5.1 : 5.2) || is_brake_charging_done() ) ) ) + && ( occupied->brakes.equivalentPipePressure > (fReady < 0.25 ? 5.1 : 5.2) || is_brake_charging_done() ) ) ) // the light application a charging train stands on stays, as in DecBrake() && ( false == brake_charge::holds_application( bBrakeChargeHold, IsConsistCharged, occupied->Vel < EU07_AI_NOMOVEMENT, BrakeCtrlPosition ) ) ) { @@ -733,7 +733,7 @@ double TController::consist_max_crp() const { auto result { 0.0 }; for( auto const *vehicle { pVehicles[ VehicleEnd::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { - result = std::max( result, vehicle->physics->Hamulec->GetCRP() ); + result = std::max( result, vehicle->physics->brakes.distributor->GetCRP() ); } return result; } @@ -744,7 +744,7 @@ bool TController::is_brake_charging_done() const { return false; } return ElapsedTime - BrakeChargingStart > FSMaxTime - || consist_max_crp() > occupied->HighPipePress + FSOverchargeCRP + || consist_max_crp() > occupied->brakes.pipeHighPressure + FSOverchargeCRP || std::ranges::any_of( BrakeChargingPipeOverchargeStart, [this]( auto const &Vehicle ) { return ElapsedTime - Vehicle.second > FSOverchargeTime; } ); diff --git a/vehicle/ai/orders.cpp b/vehicle/ai/orders.cpp index 81980c17f..c50cca135 100644 --- a/vehicle/ai/orders.cpp +++ b/vehicle/ai/orders.cpp @@ -920,7 +920,7 @@ TController::UpdateLooseShunt() { auto *vehicle { Obstacle.vehicle }; auto const direction { ( vehicle->Prev() != nullptr ? VehicleEnd::front : VehicleEnd::rear ) }; while( vehicle != nullptr ) { - if( vehicle->physics->BrakePress > 0.2 ) { + if( vehicle->physics->brakes.cylinderPressure > 0.2 ) { vehicle->physics->BrakeLevelSet( 0 ); // hamulec na zero, aby nie hamował vehicle->physics->BrakeReleaser( 1 ); // wyluzuj pojazd, aby dało się dopychać } diff --git a/vehicle/ai/physicslog.cpp b/vehicle/ai/physicslog.cpp index ea40569c9..820c90e9a 100644 --- a/vehicle/ai/physicslog.cpp +++ b/vehicle/ai/physicslog.cpp @@ -72,13 +72,13 @@ std::string TController::physicslog_line() const { << occupied->Ft << " " << occupied->Ff << " " << occupied->Fb << " " - << occupied->BrakePress << " " + << occupied->brakes.cylinderPressure << " " << occupied->brakePipe.pressure << " " << mvControlling->Im << " " << int(mvControlling->MainCtrlPos) << " " << int(mvControlling->ScndCtrlPos) << " " - << occupied->fBrakeCtrlPos << " " - << occupied->LocalBrakePosA << " " + << occupied->brakes.handlePositionSmooth << " " + << occupied->brakes.independentPosition << " " << int(mvControlling->DirActive) << " " << ( occupied->CommandIn.Text.empty() ? "none" : occupied->CommandIn.Text.c_str() ) << " " << occupied->CommandIn.Value1 << " " @@ -117,9 +117,9 @@ void TController::PhysicsLog() line << ElapsedTime << "\t" << fabs(11.31 * occupied->WheelDiameter * occupied->nrot) << "\t"; line << mvControlling->AccS << "\t"; - line << occupied->brakePipe.pressure << "\t" << occupied->CntrlPipePress << "\t" - << occupied->BrakePress << "\t"; - line << occupied->Volume << "\t" << occupied->Hamulec->GetCRP() << "\n"; + line << occupied->brakePipe.pressure << "\t" << occupied->brakes.controlReservoirPressure << "\t" + << occupied->brakes.cylinderPressure << "\t"; + line << occupied->brakes.reservoirAir << "\t" << occupied->brakes.distributor->GetCRP() << "\n"; PhysicsLogs.append( VehicleName, line.str() ); #endif }; diff --git a/vehicle/ai/situation.cpp b/vehicle/ai/situation.cpp index e07736b8e..9ccb515d6 100644 --- a/vehicle/ai/situation.cpp +++ b/vehicle/ai/situation.cpp @@ -56,7 +56,7 @@ TController::update_timers( double dt ) { WaitingTime += dt; fBrakeTime -= dt; // wpisana wartość jest zmniejszana do 0, gdy ujemna należy zmienić nastawę hamulca fBrakeHeldTime += dt; - if( occupied->fBrakeCtrlPos != occupied->Handle->GetPos( bh_FS ) ) { + if( occupied->brakes.handlePositionSmooth != occupied->brakes.driverValve->GetPos( bh_FS ) ) { // brake charging timeout starts after charging ends BrakeChargingCooldown += dt; } @@ -591,7 +591,7 @@ TController::determine_braking_distance() { && occupied->CategoryFlag == 1 ) { fBrakeDist = velceil * velceil / 25.92 / -fAccThreshold; } - if( occupied->BrakeDelayFlag == bdelay_G ) { + if( occupied->brakes.delaySetting == bdelay_G ) { // dla nastawienia G koniecznie należy wydłużyć drogę na czas reakcji fBrakeDist += 2 * velceil; } diff --git a/vehicle/ai/speed.cpp b/vehicle/ai/speed.cpp index e213ef6d8..864f67341 100644 --- a/vehicle/ai/speed.cpp +++ b/vehicle/ai/speed.cpp @@ -446,9 +446,9 @@ brake_response_horizon( physics::Vehicle const *Vehicle, TBrakeSystem const Brak auto horizon { ( 1.0 - Brakea0 ) * 30.0 / 3.6 }; if( Brakesystem == TBrakeSystem::Pneumatic ) { // BrakeDelay holds the release and the application time in G, then the same two in P - auto const delays { Vehicle->BrakeDelayFlag > bdelay_G ? 0 : 2 }; + auto const delays { Vehicle->brakes.delaySetting > bdelay_G ? 0 : 2 }; auto const isrelease { Acceleration < 0.0 }; - horizon = std::max( horizon, 0.5 * Vehicle->BrakeDelay[ delays + ( isrelease ? 0 : 1 ) ] ); + horizon = std::max( horizon, 0.5 * Vehicle->brakes.delays[ delays + ( isrelease ? 0 : 1 ) ] ); } return horizon; } @@ -506,8 +506,8 @@ TController::adjust_desired_speed_for_braking_curve( double const Vel ) { braking_curve::brake_acting( BrakeCtrlPosition, // IncLocalBrakeLevel() moves the independent brake handle on a vehicle without one too - ( occupied->LocalBrake == TLocalBrake::PneumaticBrake || occupied->LocalBrake == TLocalBrake::HydraulicBrake ) ? - occupied->LocalBrakePosA : + ( occupied->brakes.localKind == TLocalBrake::PneumaticBrake || occupied->brakes.localKind == TLocalBrake::HydraulicBrake ) ? + occupied->brakes.independentPosition : 0.0 ), brake_response_horizon( occupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ), brake_response_horizon( occupied, BrakeSystem, 1.0, fillbrakea0 ) }; @@ -821,7 +821,7 @@ TController::adjust_desired_speed_for_braking_test() { if( ( DynamicBrakeTest == 0 ) && ( false == timetable::makes_brake_test( TrainParams.run_flags() ) ) ) { return; } // the timetable says there's none (eu07/maszyna#95) if( false == is_train() ) { return; } // not applicable - if( occupied->BrakeHandle == TBrakeHandle::FVel6 ) { return; } // leads to bugs in DecBrake, disable for now + if( occupied->brakes.driverValveType == TBrakeHandle::FVel6 ) { return; } // leads to bugs in DecBrake, disable for now if( false == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { return; } // not applicable if( false == AIControllFlag ) { return; } // TBD: add notification about braking test and enable it for human driver as well? diff --git a/vehicle/brakesetting.cpp b/vehicle/brakesetting.cpp index 42be6738c..6c5517cfd 100644 --- a/vehicle/brakesetting.cpp +++ b/vehicle/brakesetting.cpp @@ -249,26 +249,26 @@ std::vector choose_legacy(std::vector const &Consist) { } bool is_cut_out(physics::Vehicle const &Vehicle) { - return (Vehicle.Hamulec->GetBrakeStatus() & b_dmg) == b_dmg; + return (Vehicle.brakes.distributor->GetBrakeStatus() & b_dmg) == b_dmg; } vehicle describe(physics::Vehicle const &Vehicle, bool const Driven) { vehicle described; - described.delays = Vehicle.BrakeDelays; + described.delays = Vehicle.brakes.availableDelays; // a locomotive has Power > 1, though it may be a dead one at the end of the train described.powered = Vehicle.Power >= 1.0; described.length = Vehicle.Dim.L; described.mass = Vehicle.TotalMass; - described.cut_out = is_cut_out(Vehicle) && false == Vehicle.BrakeCutOutByInspector; + described.cut_out = is_cut_out(Vehicle) && false == Vehicle.brakes.cutOutByInspector; described.driven = Driven; return described; } bool apply(physics::Vehicle &Vehicle, int const Setting, bool const Standstill) { - auto &brake{*Vehicle.Hamulec}; - if (Vehicle.BrakeCutOutByInspector && false == is_cut_out(Vehicle)) { + auto &brake{*Vehicle.brakes.distributor}; + if (Vehicle.brakes.cutOutByInspector && false == is_cut_out(Vehicle)) { // someone put the brake back in the meantime, it's theirs now - Vehicle.BrakeCutOutByInspector = false; + Vehicle.brakes.cutOutByInspector = false; } if (Setting == cut_out) { if (is_cut_out(Vehicle)) { @@ -284,13 +284,13 @@ bool apply(physics::Vehicle &Vehicle, int const Setting, bool const Standstill) // distributor, cut off the brake pipe, has no air left to brake with and lets the cylinders go brake.ForceEmptiness(); brake.SetBrakeStatus(brake.GetBrakeStatus() | b_dmg); - Vehicle.BrakeCutOutByInspector = true; + Vehicle.brakes.cutOutByInspector = true; return false; } - if (Vehicle.BrakeCutOutByInspector) { + if (Vehicle.brakes.cutOutByInspector) { // open the cut-out cock: the distributor charges from the brake pipe again brake.SetBrakeStatus(brake.GetBrakeStatus() & ~b_dmg); - Vehicle.BrakeCutOutByInspector = false; + Vehicle.brakes.cutOutByInspector = false; } if (Setting != 0) { Vehicle.BrakeDelaySwitch(Setting); diff --git a/vehicle/cab/brakecommands.cpp b/vehicle/cab/brakecommands.cpp index f0f9cef39..087ee602c 100644 --- a/vehicle/cab/brakecommands.cpp +++ b/vehicle/cab/brakecommands.cpp @@ -57,7 +57,7 @@ void TTrain::OnCommand_independentbrakeincrease(TTrain *Train, command_data cons // the pneumatic local brake directly, never piggy-backing on the joint controller auto const splitMode{Train->controlled->SplitEDPneumaticBrake}; auto const useStepped{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; - if (Train->occupied->LocalBrake != TLocalBrake::ManualBrake) + if (Train->occupied->brakes.localKind != TLocalBrake::ManualBrake) { if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->occupied->MainCtrlPos > 0) { @@ -83,7 +83,7 @@ void TTrain::OnCommand_independentbrakeincreasefast(TTrain *Train, command_data auto const splitMode{Train->controlled->SplitEDPneumaticBrake}; auto const useJointAnim{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; - if (Train->occupied->LocalBrake != TLocalBrake::ManualBrake) + if (Train->occupied->brakes.localKind != TLocalBrake::ManualBrake) { if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->occupied->MainCtrlPos > 0) { @@ -109,12 +109,12 @@ void TTrain::OnCommand_independentbrakedecrease(TTrain *Train, command_data cons auto const splitMode{Train->controlled->SplitEDPneumaticBrake}; auto const useStepped{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; - if (Train->occupied->LocalBrake != TLocalBrake::ManualBrake + if (Train->occupied->brakes.localKind != TLocalBrake::ManualBrake // Ra 1014-06: AI potrafi zahamować pomocniczym mimo jego braku - odhamować jakoś trzeba // TODO: sort AI out so it doesn't do things it doesn't have equipment for - || Train->occupied->LocalBrakePosA > 0) + || Train->occupied->brakes.independentPosition > 0) { - if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->occupied->LocalBrakePosA == 0.0) + if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->occupied->brakes.independentPosition == 0.0) { OnCommand_mastercontrollerincrease(Train, Command); } @@ -138,12 +138,12 @@ void TTrain::OnCommand_independentbrakedecreasefast(TTrain *Train, command_data auto const splitMode{Train->controlled->SplitEDPneumaticBrake}; auto const useJointAnim{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; - if (Train->occupied->LocalBrake != TLocalBrake::ManualBrake + if (Train->occupied->brakes.localKind != TLocalBrake::ManualBrake // Ra 1014-06: AI potrafi zahamować pomocniczym mimo jego braku - odhamować jakoś trzeba // TODO: sort AI out so it doesn't do things it doesn't have equipment for - || Train->occupied->LocalBrakePosA > 0) + || Train->occupied->brakes.independentPosition > 0) { - if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->occupied->LocalBrakePosA == 0.0) + if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->occupied->brakes.independentPosition == 0.0) { OnCommand_mastercontrollerincreasefast(Train, Command); } @@ -165,7 +165,7 @@ void TTrain::OnCommand_independentbrakeset(TTrain *Train, command_data const &Co if (Command.action != GLFW_RELEASE) { - Train->occupied->LocalBrakePosA = std::clamp(Command.param1, 0.0, 1.0); + Train->occupied->brakes.independentPosition = std::clamp(Command.param1, 0.0, 1.0); } /* Train->controlled->LocalBrakePos = ( @@ -189,7 +189,7 @@ void TTrain::OnCommand_independentbrakebailoff(TTrain *Train, command_data const if (Train->controlled->TrainType != train_type::emu && (Train->controlled->EngineType == TEngineType::ElectricSeriesMotor || Train->controlled->EngineType == TEngineType::DieselElectric || Train->controlled->EngineType == TEngineType::ElectricInductionMotor) && - Train->occupied->BrakeCtrlPosNo > 0) + Train->occupied->brakes.handlePositions > 0) { if (Command.action == GLFW_PRESS) @@ -295,18 +295,18 @@ void TTrain::OnCommand_universalbrakebutton3(TTrain *Train, command_data const & void TTrain::OnCommand_trainbrakeincrease(TTrain *Train, command_data const &Command) { - if (Command.action == GLFW_REPEAT && Train->occupied->BrakeHandle == TBrakeHandle::FV4a) - Train->occupied->BrakeLevelAdd(Global.brake_speed * Command.time_delta * Train->occupied->BrakeCtrlPosNo); - else if (Command.action == GLFW_PRESS && Train->occupied->BrakeHandle != TBrakeHandle::FV4a) - Train->set_train_brake(Train->occupied->fBrakeCtrlPos + Global.fBrakeStep); + if (Command.action == GLFW_REPEAT && Train->occupied->brakes.driverValveType == TBrakeHandle::FV4a) + Train->occupied->BrakeLevelAdd(Global.brake_speed * Command.time_delta * Train->occupied->brakes.handlePositions); + else if (Command.action == GLFW_PRESS && Train->occupied->brakes.driverValveType != TBrakeHandle::FV4a) + Train->set_train_brake(Train->occupied->brakes.handlePositionSmooth + Global.fBrakeStep); } void TTrain::OnCommand_trainbrakedecrease(TTrain *Train, command_data const &Command) { - if (Command.action == GLFW_REPEAT && Train->occupied->BrakeHandle == TBrakeHandle::FV4a) - Train->occupied->BrakeLevelAdd(-Global.brake_speed * Command.time_delta * Train->occupied->BrakeCtrlPosNo); - else if (Command.action == GLFW_PRESS && Train->occupied->BrakeHandle != TBrakeHandle::FV4a) - Train->set_train_brake(Train->occupied->fBrakeCtrlPos - Global.fBrakeStep); + if (Command.action == GLFW_REPEAT && Train->occupied->brakes.driverValveType == TBrakeHandle::FV4a) + Train->occupied->BrakeLevelAdd(-Global.brake_speed * Command.time_delta * Train->occupied->brakes.handlePositions); + else if (Command.action == GLFW_PRESS && Train->occupied->brakes.driverValveType != TBrakeHandle::FV4a) + Train->set_train_brake(Train->occupied->brakes.handlePositionSmooth - Global.fBrakeStep); else if (Command.action == GLFW_RELEASE) { // release @@ -320,7 +320,7 @@ void TTrain::OnCommand_trainbrakeset(TTrain *Train, command_data const &Command) if (Command.action != GLFW_RELEASE) { // press or hold - Train->occupied->BrakeLevelSet(std::lerp(Train->occupied->Handle->GetPos(bh_MIN), Train->occupied->Handle->GetPos(bh_MAX), std::clamp(Command.param1, 0.0, 1.0))); + Train->occupied->BrakeLevelSet(std::lerp(Train->occupied->brakes.driverValve->GetPos(bh_MIN), Train->occupied->brakes.driverValve->GetPos(bh_MAX), std::clamp(Command.param1, 0.0, 1.0))); } else { @@ -370,7 +370,7 @@ void TTrain::OnCommand_trainbrakeservice(TTrain *Train, command_data const &Comm if (Command.action == GLFW_PRESS) { - Train->set_train_brake(Train->occupied->BrakeCtrlPosNo / 2 + (Train->occupied->BrakeHandle == TBrakeHandle::FV4a ? 1 : 0)); + Train->set_train_brake(Train->occupied->brakes.handlePositions / 2 + (Train->occupied->brakes.driverValveType == TBrakeHandle::FV4a ? 1 : 0)); } } @@ -380,7 +380,7 @@ void TTrain::OnCommand_trainbrakefullservice(TTrain *Train, command_data const & if (Command.action == GLFW_PRESS) { - Train->set_train_brake(Train->occupied->BrakeCtrlPosNo - 1); + Train->set_train_brake(Train->occupied->brakes.handlePositions - 1); } } @@ -390,7 +390,7 @@ void TTrain::OnCommand_trainbrakehandleoff(TTrain *Train, command_data const &Co if (Command.action == GLFW_PRESS) { - Train->set_train_brake(Train->occupied->Handle->GetPos(bh_NP)); + Train->set_train_brake(Train->occupied->brakes.driverValve->GetPos(bh_NP)); } } @@ -400,7 +400,7 @@ void TTrain::OnCommand_trainbrakeemergency(TTrain *Train, command_data const &Co if (Command.action == GLFW_PRESS) { - Train->set_train_brake(Train->occupied->Handle->GetPos(bh_EB)); + Train->set_train_brake(Train->occupied->brakes.driverValve->GetPos(bh_EB)); /* if( Train->occupied->BrakeCtrlPosNo <= 0.1 ) { // hamulec bezpieczeństwa dla wagonów @@ -416,9 +416,9 @@ void TTrain::OnCommand_trainbrakebasepressureincrease(TTrain *Train, command_dat if (Command.action != GLFW_RELEASE) { - if (Train->occupied->BrakeHandle == TBrakeHandle::FV4a) + if (Train->occupied->brakes.driverValveType == TBrakeHandle::FV4a) { - Train->occupied->BrakeCtrlPos2 = std::clamp(Train->occupied->BrakeCtrlPos2 - 0.01, -1.5, 2.0); + Train->occupied->brakes.handleCapPosition = std::clamp(Train->occupied->brakes.handleCapPosition - 0.01, -1.5, 2.0); } else { @@ -433,9 +433,9 @@ void TTrain::OnCommand_trainbrakebasepressuredecrease(TTrain *Train, command_dat if (Command.action != GLFW_RELEASE) { - if (Train->occupied->BrakeHandle == TBrakeHandle::FV4a) + if (Train->occupied->brakes.driverValveType == TBrakeHandle::FV4a) { - Train->occupied->BrakeCtrlPos2 = std::clamp(Train->occupied->BrakeCtrlPos2 + 0.01, -1.5, 2.0); + Train->occupied->brakes.handleCapPosition = std::clamp(Train->occupied->brakes.handleCapPosition + 0.01, -1.5, 2.0); } else { @@ -450,7 +450,7 @@ void TTrain::OnCommand_trainbrakebasepressurereset(TTrain *Train, command_data c if (Command.action == GLFW_PRESS) { - Train->occupied->BrakeCtrlPos2 = 0; + Train->occupied->brakes.handleCapPosition = 0; } } @@ -466,9 +466,9 @@ void TTrain::OnCommand_trainbrakeoperationtoggle(TTrain *Train, command_data con return; } - vehicle->physics->Hamulec->SetBrakeStatus(vehicle->physics->Hamulec->GetBrakeStatus() ^ b_dmg); + vehicle->physics->brakes.distributor->SetBrakeStatus(vehicle->physics->brakes.distributor->GetBrakeStatus() ^ b_dmg); // the brake is the player's now, the wagon inspector won't put it back on its own - vehicle->physics->BrakeCutOutByInspector = false; + vehicle->physics->brakes.cutOutByInspector = false; } } @@ -484,7 +484,7 @@ void TTrain::OnCommand_manualbrakeincrease(TTrain *Train, command_data const &Co return; } - if (vehicle->physics->LocalBrake == TLocalBrake::ManualBrake || vehicle->physics->MBrake == true) + if (vehicle->physics->brakes.localKind == TLocalBrake::ManualBrake || vehicle->physics->brakes.hasHandBrake == true) { vehicle->physics->IncManualBrakeLevel(1); @@ -504,7 +504,7 @@ void TTrain::OnCommand_manualbrakedecrease(TTrain *Train, command_data const &Co return; } - if (vehicle->physics->LocalBrake == TLocalBrake::ManualBrake || vehicle->physics->MBrake == true) + if (vehicle->physics->brakes.localKind == TLocalBrake::ManualBrake || vehicle->physics->brakes.hasHandBrake == true) { vehicle->physics->DecManualBrakeLevel(1); @@ -518,7 +518,7 @@ void TTrain::OnCommand_alarmchaintoggle(TTrain *Train, command_data const &Comma if (Command.action == GLFW_PRESS) { - if (false == Train->occupied->AlarmChainFlag) + if (false == Train->occupied->brakes.alarmChain) { OnCommand_alarmchainenable(Train, Command); } @@ -566,7 +566,7 @@ void TTrain::OnCommand_wheelspinbrakeactivate(TTrain *Train, command_data const return; } - if (Train->occupied->BrakeSystem != TBrakeSystem::ElectroPneumatic) + if (Train->occupied->brakes.kind != TBrakeSystem::ElectroPneumatic) { // standard behaviour if (Command.action == GLFW_PRESS) @@ -592,7 +592,7 @@ void TTrain::OnCommand_wheelspinbrakeactivate(TTrain *Train, command_data const // the EP fuse is the cab car's (Ctrl+Z switches occupied's), checked by SwitchEPBrake with the rest of // the control's supply - if (Train->occupied->BrakeHandle == TBrakeHandle::St113) + if (Train->occupied->brakes.driverValveType == TBrakeHandle::St113) { Train->occupied->SwitchEPBrake(1); } @@ -763,12 +763,12 @@ void TTrain::OnCommand_trainbrakeoperationmodeincrease(TTrain *Train, command_da { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Command.action == GLFW_PRESS && (Train->occupied->BrakeOpModeFlag << 1 & Train->occupied->BrakeOpModes) != 0) + if (Command.action == GLFW_PRESS && (Train->occupied->brakes.operatingMode << 1 & Train->occupied->brakes.availableOperatingModes) != 0) { // next mode - Train->occupied->BrakeOpModeFlag <<= 1; + Train->occupied->brakes.operatingMode <<= 1; // visual feedback - Train->ggBrakeOperationModeCtrl.UpdateValue(Train->occupied->BrakeOpModeFlag > 0 ? static_cast(std::log2(Train->occupied->BrakeOpModeFlag)) : 0); // audio fallback + Train->ggBrakeOperationModeCtrl.UpdateValue(Train->occupied->brakes.operatingMode > 0 ? static_cast(std::log2(Train->occupied->brakes.operatingMode)) : 0); // audio fallback } } @@ -776,12 +776,12 @@ void TTrain::OnCommand_trainbrakeoperationmodedecrease(TTrain *Train, command_da { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Command.action == GLFW_PRESS && (Train->occupied->BrakeOpModeFlag >> 1 & Train->occupied->BrakeOpModes) != 0) + if (Command.action == GLFW_PRESS && (Train->occupied->brakes.operatingMode >> 1 & Train->occupied->brakes.availableOperatingModes) != 0) { // previous mode - Train->occupied->BrakeOpModeFlag >>= 1; + Train->occupied->brakes.operatingMode >>= 1; // visual feedback - Train->ggBrakeOperationModeCtrl.UpdateValue(Train->occupied->BrakeOpModeFlag > 0 ? static_cast(std::log2(Train->occupied->BrakeOpModeFlag)) : 0); + Train->ggBrakeOperationModeCtrl.UpdateValue(Train->occupied->brakes.operatingMode > 0 ? static_cast(std::log2(Train->occupied->brakes.operatingMode)) : 0); } } @@ -797,12 +797,12 @@ void TTrain::OnCommand_brakeactingspeedincrease(TTrain *Train, command_data cons return; } - if ((vehicle->physics->BrakeDelayFlag & bdelay_M) != 0) + if ((vehicle->physics->brakes.delaySetting & bdelay_M) != 0) { // can't speed it up any more than this return; } - auto const fasterbrakesetting = vehicle->physics->BrakeDelayFlag < bdelay_R ? vehicle->physics->BrakeDelayFlag << 1 : vehicle->physics->BrakeDelayFlag | bdelay_M; + auto const fasterbrakesetting = vehicle->physics->brakes.delaySetting < bdelay_R ? vehicle->physics->brakes.delaySetting << 1 : vehicle->physics->brakes.delaySetting | bdelay_M; Train->set_train_brake_speed(vehicle, fasterbrakesetting); } @@ -820,12 +820,12 @@ void TTrain::OnCommand_brakeactingspeeddecrease(TTrain *Train, command_data cons return; } - if (vehicle->physics->BrakeDelayFlag == bdelay_G) + if (vehicle->physics->brakes.delaySetting == bdelay_G) { // can't slow it down any more than this return; } - auto const slowerbrakesetting = vehicle->physics->BrakeDelayFlag < bdelay_M ? vehicle->physics->BrakeDelayFlag >> 1 : vehicle->physics->BrakeDelayFlag ^ bdelay_M; + auto const slowerbrakesetting = vehicle->physics->brakes.delaySetting < bdelay_M ? vehicle->physics->brakes.delaySetting >> 1 : vehicle->physics->brakes.delaySetting ^ bdelay_M; Train->set_train_brake_speed(vehicle, slowerbrakesetting); } diff --git a/vehicle/cab/controllercommands.cpp b/vehicle/cab/controllercommands.cpp index 06974960a..8028e5e6f 100644 --- a/vehicle/cab/controllercommands.cpp +++ b/vehicle/cab/controllercommands.cpp @@ -97,7 +97,7 @@ void TTrain::OnCommand_jointcontrollerset(TTrain *Train, command_data const &Com } else { - Train->occupied->LocalBrakePosA = 0; + Train->occupied->brakes.independentPosition = 0; } } else @@ -113,7 +113,7 @@ void TTrain::OnCommand_jointcontrollerset(TTrain *Train, command_data const &Com } else { - Train->occupied->LocalBrakePosA = negativeRange; + Train->occupied->brakes.independentPosition = negativeRange; } if (Train->controlled->MainCtrlPowerPos() > 0) { @@ -138,7 +138,7 @@ void TTrain::OnCommand_mastercontrollerincrease(TTrain *Train, command_data cons auto const splitMode{Train->controlled->SplitEDPneumaticBrake}; // when SplitEDPneumaticBrake is true the joint controller's negative range maps // to the dedicated dynamic-brake lever (DynamicBrakeCtrl) rather than to LocalBrake - auto const negativeRangeActive{splitMode ? Train->controlled->DynamicBrakeCtrlPos > 0.0 : Train->occupied->LocalBrakePosA > 0.0}; + auto const negativeRangeActive{splitMode ? Train->controlled->DynamicBrakeCtrlPos > 0.0 : Train->occupied->brakes.independentPosition > 0.0}; if (Train->ggJointCtrl.SubModel != nullptr && negativeRangeActive) { if (splitMode) @@ -172,7 +172,7 @@ void TTrain::OnCommand_mastercontrollerincreasefast(TTrain *Train, command_data { // on press or hold auto const splitMode{Train->controlled->SplitEDPneumaticBrake}; - auto const negativeRangeActive{splitMode ? Train->controlled->DynamicBrakeCtrlPos > 0.0 : Train->occupied->LocalBrakePosA > 0.0}; + auto const negativeRangeActive{splitMode ? Train->controlled->DynamicBrakeCtrlPos > 0.0 : Train->occupied->brakes.independentPosition > 0.0}; if (Train->ggJointCtrl.SubModel != nullptr && negativeRangeActive) { if (splitMode) diff --git a/vehicle/cab/setup.cpp b/vehicle/cab/setup.cpp index f7f99df23..53bf093ca 100644 --- a/vehicle/cab/setup.cpp +++ b/vehicle/cab/setup.cpp @@ -1084,15 +1084,15 @@ void TTrain::set_cab_controls(int const Cab) // brake acting time if (ggBrakeProfileCtrl.SubModel != nullptr) { - ggBrakeProfileCtrl.PutValue((occupied->BrakeDelayFlag & bdelay_R) != 0 ? 2.f : static_cast(occupied->BrakeDelayFlag - 1)); + ggBrakeProfileCtrl.PutValue((occupied->brakes.delaySetting & bdelay_R) != 0 ? 2.f : static_cast(occupied->brakes.delaySetting - 1)); } if (ggBrakeProfileG.SubModel != nullptr) { - ggBrakeProfileG.PutValue(occupied->BrakeDelayFlag == bdelay_G ? 1.f : 0.f); + ggBrakeProfileG.PutValue(occupied->brakes.delaySetting == bdelay_G ? 1.f : 0.f); } if (ggBrakeProfileR.SubModel != nullptr) { - ggBrakeProfileR.PutValue((occupied->BrakeDelayFlag & bdelay_R) != 0 ? 1.f : 0.f); + ggBrakeProfileR.PutValue((occupied->brakes.delaySetting & bdelay_R) != 0 ? 1.f : 0.f); } if (ggWiperSw.SubModel != nullptr) @@ -1102,10 +1102,10 @@ void TTrain::set_cab_controls(int const Cab) if (ggBrakeOperationModeCtrl.SubModel != nullptr) { - ggBrakeOperationModeCtrl.PutValue(occupied->BrakeOpModeFlag > 0 ? static_cast(std::log2(occupied->BrakeOpModeFlag)) : 0); + ggBrakeOperationModeCtrl.PutValue(occupied->brakes.operatingMode > 0 ? static_cast(std::log2(occupied->brakes.operatingMode)) : 0); } // alarm chain - ggAlarmChain.PutValue(controlled->AlarmChainFlag ? 1.f : 0.f); + ggAlarmChain.PutValue(controlled->brakes.alarmChain ? 1.f : 0.f); // brake signalling ggSignallingButton.PutValue(controlled->Signalling ? 1.f : 0.f); // multiple-unit current indicator source @@ -1339,7 +1339,7 @@ bool TTrain::initialize_button(cParser &Parser, std::string const &Label, int co {"i-doorpermit_right:", &m_doorspermitright}, {"i-doorpermit_any:", &m_doorpermits}, {"i-doorstep:", &occupied->Doors.step_enabled}, - {"i-mainpipelock:", &occupied->LockPipe}, + {"i-mainpipelock:", &occupied->brakes.pipeLock.locked}, {"i-battery:", &occupied->Power24vIsAvailable}, {"i-cablight:", &Cabine[iCabn].bLight}, {"i-compartmentlights:", &occupied->CompartmentLights.is_active}, @@ -1677,7 +1677,7 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con } // TODO: move viable dedicated gauges to the automatic array std::unordered_map const autointgauges = { - {"manualbrake:", &occupied->ManualBrakePos}, + {"manualbrake:", &occupied->brakes.handBrakePosition}, {"pantselect_sw:", &occupied->PantsPreset.second[cab_to_end()]}, }; { @@ -1817,7 +1817,7 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con // Ra 2014-08: przeniesione do TCab auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&occupied->BrakePress); + gauge.AssignDouble(&occupied->brakes.cylinderPressure); } else if (Label == "pipepress:" || Label == "pipepressb:") { diff --git a/vehicle/cab/sounds.cpp b/vehicle/cab/sounds.cpp index e189027e2..23dd29647 100644 --- a/vehicle/cab/sounds.cpp +++ b/vehicle/cab/sounds.cpp @@ -57,14 +57,14 @@ void TTrain::update_sounds(double const Deltatime) if (m_lastlocalbrakepressure != -1.f) { // calculate rate of pressure drop in local brake cylinder, once it's been initialized - auto const brakepressuredifference{occupied->LocBrakePress - m_lastlocalbrakepressure}; + auto const brakepressuredifference{occupied->brakes.independentCylinderPressure - m_lastlocalbrakepressure}; m_localbrakepressurechange = static_cast(std::lerp(m_localbrakepressurechange, 10 * (brakepressuredifference / Deltatime), 0.1f)); } - m_lastlocalbrakepressure = static_cast(occupied->LocBrakePress); + m_lastlocalbrakepressure = static_cast(occupied->brakes.independentCylinderPressure); // local brake, release if (rsSBHiss) { - if (m_localbrakepressurechange < -0.05f && occupied->LocBrakePress > occupied->BrakePress - 0.05) + if (m_localbrakepressurechange < -0.05f && occupied->brakes.independentCylinderPressure > occupied->brakes.cylinderPressure - 0.05) { rsSBHiss->gain(static_cast(std::clamp(rsSBHiss->m_amplitudeoffset + rsSBHiss->m_amplitudefactor * -m_localbrakepressurechange * 0.05, 0.0, 1.5))); rsSBHiss->play(sound_flags::exclusive | sound_flags::looping); @@ -102,12 +102,12 @@ void TTrain::update_sounds(double const Deltatime) // McZapkie-280302 - syczenie // TODO: softer volume reduction than plain abrupt stop, perhaps as reusable wrapper? - if (occupied->BrakeHandle == TBrakeHandle::FV4a || occupied->BrakeHandle == TBrakeHandle::FVel6) + if (occupied->brakes.driverValveType == TBrakeHandle::FV4a || occupied->brakes.driverValveType == TBrakeHandle::FVel6) { // upuszczanie z PG if (rsHiss) { - fPPress = std::lerp(fPPress, static_cast(occupied->Handle->GetSound(s_fv4a_b)), 0.05f); + fPPress = std::lerp(fPPress, static_cast(occupied->brakes.driverValve->GetSound(s_fv4a_b)), 0.05f); volume = fPPress > 0 ? rsHiss->m_amplitudefactor * fPPress * 0.25 + rsHiss->m_amplitudeoffset : 0; if (volume * brakevolumescale > 0.05) { @@ -122,7 +122,7 @@ void TTrain::update_sounds(double const Deltatime) // napelnianie PG if (rsHissU) { - fNPress = std::lerp(fNPress, static_cast(occupied->Handle->GetSound(s_fv4a_u)), 0.25f); + fNPress = std::lerp(fNPress, static_cast(occupied->brakes.driverValve->GetSound(s_fv4a_u)), 0.25f); volume = fNPress > 0 ? rsHissU->m_amplitudefactor * fNPress + rsHissU->m_amplitudeoffset : 0; if (volume * brakevolumescale > 0.05) { @@ -137,7 +137,7 @@ void TTrain::update_sounds(double const Deltatime) // upuszczanie przy naglym if (rsHissE) { - volume = occupied->Handle->GetSound(s_fv4a_e) * rsHissE->m_amplitudefactor + rsHissE->m_amplitudeoffset; + volume = occupied->brakes.driverValve->GetSound(s_fv4a_e) * rsHissE->m_amplitudefactor + rsHissE->m_amplitudeoffset; if (volume * brakevolumescale > 0.05) { rsHissE->gain(static_cast(volume * brakevolumescale)); @@ -151,7 +151,7 @@ void TTrain::update_sounds(double const Deltatime) // upuszczanie sterujacego fala if (rsHissX) { - volume = occupied->Handle->GetSound(s_fv4a_x) * rsHissX->m_amplitudefactor + rsHissX->m_amplitudeoffset; + volume = occupied->brakes.driverValve->GetSound(s_fv4a_x) * rsHissX->m_amplitudefactor + rsHissX->m_amplitudeoffset; if (volume * brakevolumescale > 0.05) { rsHissX->gain(static_cast(volume * brakevolumescale)); @@ -165,7 +165,7 @@ void TTrain::update_sounds(double const Deltatime) // upuszczanie z czasowego if (rsHissT) { - volume = occupied->Handle->GetSound(s_fv4a_t) * rsHissT->m_amplitudefactor + +rsHissT->m_amplitudeoffset; + volume = occupied->brakes.driverValve->GetSound(s_fv4a_t) * rsHissT->m_amplitudefactor + +rsHissT->m_amplitudeoffset; if (volume * brakevolumescale > 0.05) { rsHissT->gain(static_cast(volume * brakevolumescale)); @@ -183,7 +183,7 @@ void TTrain::update_sounds(double const Deltatime) // upuszczanie z PG if (rsHiss) { - fPPress = static_cast((4.0f * fPPress + std::max(0.0, occupied->dpMainValve)) / (4.0f + 1.0f)); + fPPress = static_cast((4.0f * fPPress + std::max(0.0, occupied->brakes.driverValveFlow)) / (4.0f + 1.0f)); volume = fPPress > 0.0f ? 2.0 * rsHiss->m_amplitudefactor * fPPress + rsHiss->m_amplitudeoffset : 0.0; if (volume > 0.05) { @@ -198,7 +198,7 @@ void TTrain::update_sounds(double const Deltatime) // napelnianie PG if (rsHissU) { - fNPress = static_cast((4.0f * fNPress + std::min(0.0, occupied->dpMainValve)) / (4.0f + 1.0f)); + fNPress = static_cast((4.0f * fNPress + std::min(0.0, occupied->brakes.driverValveFlow)) / (4.0f + 1.0f)); volume = fNPress < 0.0f ? -1.0 * rsHissU->m_amplitudefactor * fNPress + rsHissU->m_amplitudeoffset : 0.0; if (volume > 0.01) { @@ -215,11 +215,11 @@ void TTrain::update_sounds(double const Deltatime) // brakes if (rsBrake) { - if (occupied->UnitBrakeForce > 10.0 && occupied->Vel > 0.05) + if (occupied->brakes.unitForce > 10.0 && occupied->Vel > 0.05) { auto const brakeforceratio{ - std::clamp(occupied->UnitBrakeForce / std::max(1.0, occupied->BrakeForceR(1.0, occupied->Vel) / (occupied->NAxles * std::max(1, occupied->NBpA))), 0.0, 1.0)}; + std::clamp(occupied->brakes.unitForce / std::max(1.0, occupied->BrakeForceR(1.0, occupied->Vel) / (occupied->NAxles * std::max(1, occupied->brakes.blocksPerAxle))), 0.0, 1.0)}; // HACK: in external view mute the sound rather than stop it, in case there's an opening bookend it'd (re)play on sound restart after returning inside volume = FreeFlyModeFlag ? 0.0 : rsBrake->m_amplitudeoffset + std::sqrt(brakeforceratio * std::lerp(0.4, 1.0, occupied->Vel / (1 + occupied->Vmax))) * rsBrake->m_amplitudefactor; rsBrake->pitch(static_cast(rsBrake->m_frequencyoffset + occupied->Vel * rsBrake->m_frequencyfactor)); @@ -457,7 +457,7 @@ void TTrain::update_sounds_runningnoise(sound_source &Sound) if (std::abs(occupied->nrot) > 0.01) { // hamulce wzmagaja halas - auto const brakeforceratio{(std::clamp(occupied->UnitBrakeForce / std::max(1.0, occupied->BrakeForceR(1.0, occupied->Vel) / (occupied->NAxles * std::max(1, occupied->NBpA))), 0.0, 1.0))}; + auto const brakeforceratio{(std::clamp(occupied->brakes.unitForce / std::max(1.0, occupied->BrakeForceR(1.0, occupied->Vel) / (occupied->NAxles * std::max(1, occupied->brakes.blocksPerAxle))), 0.0, 1.0))}; volume *= 1 + 0.125 * brakeforceratio; } diff --git a/vehicle/cab/train.cpp b/vehicle/cab/train.cpp index 742117642..a805f7a06 100644 --- a/vehicle/cab/train.cpp +++ b/vehicle/cab/train.cpp @@ -214,30 +214,30 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("scndctrl_pos", controlled->ScndCtrlPos); dict->insert("dynamicbrake_pos", controlled->DynamicBrakeCtrlPos); dict->insert("scnd_ctrl_actual_pos", controlled->ScndCtrlActualPos); - dict->insert("brakectrl_pos", controlled->fBrakeCtrlPos); - dict->insert("localbrake_pos", controlled->LocalBrakePosA); + dict->insert("brakectrl_pos", controlled->brakes.handlePositionSmooth); + dict->insert("localbrake_pos", controlled->brakes.independentPosition); dict->insert("new_speed", occupied->NewSpeed); dict->insert("speedctrl", occupied->SpeedCtrlValue); dict->insert("speedctrlpower", occupied->SpeedCtrlUnit.DesiredPower); dict->insert("speedctrlactive", occupied->SpeedCtrlUnit.IsActive); dict->insert("speedctrlstandby", occupied->SpeedCtrlUnit.Standby); // brakes - dict->insert("manual_brake", occupied->ManualBrakePos > 0); - bool const bEP = controlled->LocHandle->GetCP() > 0.2 || fEIMParams[0][5] > 0.01; + dict->insert("manual_brake", occupied->brakes.handBrakePosition > 0); + bool const bEP = controlled->brakes.independentValve->GetCP() > 0.2 || fEIMParams[0][5] > 0.01; dict->insert("dir_brake", bEP); bool bPN{false}; - auto const &brakevalve{*occupied->Hamulec}; + auto const &brakevalve{*occupied->brakes.distributor}; if (auto const &brakevalvetype{typeid(brakevalve)}; brakevalvetype == typeid(TLSt) || brakevalvetype == typeid(TEStED)) { - TBrake *temp_ham = occupied->Hamulec.get(); + TBrake *temp_ham = occupied->brakes.distributor.get(); bPN = static_cast(temp_ham)->GetEDBCP() > 0.2; } dict->insert("indir_brake", bPN); - dict->insert("emergency_brake", occupied->AlarmChainFlag); - dict->insert("brake_delay_flag", occupied->BrakeDelayFlag); - dict->insert("brake_op_mode_flag", occupied->BrakeOpModeFlag); - dict->insert("pipelock", occupied->LockPipe); + dict->insert("emergency_brake", occupied->brakes.alarmChain); + dict->insert("brake_delay_flag", occupied->brakes.delaySetting); + dict->insert("brake_op_mode_flag", occupied->brakes.operatingMode); + dict->insert("pipelock", occupied->brakes.pipeLock.locked); // other controls dict->insert("ca", occupied->SecuritySystem.is_vigilance_blinking()); dict->insert("shp", occupied->SecuritySystem.is_cabsignal_blinking()); @@ -413,7 +413,7 @@ TTrain::state_t TTrain::get_state() const fTachoVelocity, static_cast(occupied->air.mainReservoirPressure), static_cast(occupied->brakePipe.pressure), - static_cast(occupied->BrakePress), + static_cast(occupied->brakes.cylinderPressure), static_cast(pantographUnit->PantPress), fHVoltage, {fHCurrent[controlled->TrainType == train_type::emu ? 0 : 1], fHCurrent[2], fHCurrent[3]}, @@ -431,7 +431,7 @@ TTrain::state_t TTrain::get_state() const occupied->Doors.step_enabled, occupied->Power24vIsAvailable, 0, - occupied->LockPipe, + occupied->brakes.pipeLock.locked, btLampkaRadioMessage.GetValue(), }; } @@ -439,7 +439,7 @@ TTrain::state_t TTrain::get_state() const bool TTrain::is_eztoer() const { - return controlled->TrainType == train_type::emu && occupied->BrakeSubsystem == TBrakeSubSystem::ss_ESt && controlled->Power24vIsAvailable == true && controlled->EpFuse == true && + return controlled->TrainType == train_type::emu && occupied->brakes.subsystem == TBrakeSubSystem::ss_ESt && controlled->Power24vIsAvailable == true && controlled->EpFuse == true && controlled->DirActive != 0; // od yB } @@ -463,16 +463,16 @@ void TTrain::set_master_controller(double const Position) void TTrain::set_train_brake(double const Position) { - auto const originalbrakeposition{static_cast(100.0 * occupied->fBrakeCtrlPos)}; + auto const originalbrakeposition{static_cast(100.0 * occupied->brakes.handlePositionSmooth)}; occupied->BrakeLevelSet(Position); - if (static_cast(100.0 * occupied->fBrakeCtrlPos) == originalbrakeposition) + if (static_cast(100.0 * occupied->brakes.handlePositionSmooth) == originalbrakeposition) { return; } // sound feedback if the lever movement activates one of the switches - if (true == is_eztoer() && false == ((originalbrakeposition / 100 == 0 || originalbrakeposition / 100 >= 5) && (occupied->BrakeCtrlPos == 0 || occupied->BrakeCtrlPos >= 5)) && dsbPneumaticSwitch) + if (true == is_eztoer() && false == ((originalbrakeposition / 100 == 0 || originalbrakeposition / 100 >= 5) && (occupied->brakes.handlePosition == 0 || occupied->brakes.handlePosition >= 5)) && dsbPneumaticSwitch) { dsbPneumaticSwitch->play(); } @@ -482,8 +482,8 @@ void TTrain::zero_charging_train_brake() { using enum TBrakeHandle; - if (occupied->BrakeCtrlPos == -1 && DynamicObject->Controller != AIdriver && Global.iFeedbackMode < 3 && - (occupied->BrakeHandle == FVel6 || occupied->BrakeHandle == MHZ_EN57 || occupied->BrakeHandle == MHZ_K8P)) + if (occupied->brakes.handlePosition == -1 && DynamicObject->Controller != AIdriver && Global.iFeedbackMode < 3 && + (occupied->brakes.driverValveType == FVel6 || occupied->brakes.driverValveType == MHZ_EN57 || occupied->brakes.driverValveType == MHZ_K8P)) { // Odskakiwanie hamulce EP set_train_brake(0); @@ -499,15 +499,15 @@ void TTrain::set_train_brake_speed(TDynamicObject *Vehicle, int const Speed) { if (ggBrakeProfileCtrl.SubModel != nullptr) { - ggBrakeProfileCtrl.UpdateValue((occupied->BrakeDelayFlag & bdelay_R) != 0 ? 2.0 : static_cast(occupied->BrakeDelayFlag - 1), dsbSwitch); + ggBrakeProfileCtrl.UpdateValue((occupied->brakes.delaySetting & bdelay_R) != 0 ? 2.0 : static_cast(occupied->brakes.delaySetting - 1), dsbSwitch); } if (ggBrakeProfileG.SubModel != nullptr) { - ggBrakeProfileG.UpdateValue(occupied->BrakeDelayFlag == bdelay_G ? 1.0 : 0.0, dsbSwitch); + ggBrakeProfileG.UpdateValue(occupied->brakes.delaySetting == bdelay_G ? 1.0 : 0.0, dsbSwitch); } if (ggBrakeProfileR.SubModel != nullptr) { - ggBrakeProfileR.UpdateValue((occupied->BrakeDelayFlag & bdelay_R) != 0 ? 1.0 : 0.0, dsbSwitch); + ggBrakeProfileR.UpdateValue((occupied->brakes.delaySetting & bdelay_R) != 0 ? 1.0 : 0.0, dsbSwitch); } } } @@ -665,7 +665,7 @@ void TTrain::MoveToVehicle(TDynamicObject *target) // jeśli prowadzi AI, to mu nie robimy dywersji! Occupied()->CabDeactivisation(); Occupied()->CabOccupied = 0; - Occupied()->BrakeLevelSet(Occupied()->Handle->GetPos(bh_NP)); // rozwala sterowanie hamulcem GF 04-2016 + Occupied()->BrakeLevelSet(Occupied()->brakes.driverValve->GetPos(bh_NP)); // rozwala sterowanie hamulcem GF 04-2016 Occupied()->MainCtrlPos = Occupied()->MainCtrlNoPowerPos(); Occupied()->ScndCtrlPos = 0; Dynamic()->MechInside = false; @@ -677,7 +677,7 @@ void TTrain::MoveToVehicle(TDynamicObject *target) if (Dynamic()->Mechanik) Dynamic()->Mechanik->MoveTo(target); - target_train->Occupied()->LimPipePress = target_train->Occupied()->brakePipe.pressure; + target_train->Occupied()->brakes.pipeLimiterPressure = target_train->Occupied()->brakePipe.pressure; target_train->Occupied()->CabActivisationAuto(true); // załączenie rozrządu (wirtualne kabiny) target_train->Dynamic()->MechInside = true; if (target_train->Dynamic()->Mechanik) @@ -723,7 +723,7 @@ void TTrain::MoveToVehicle(TDynamicObject *target) Occupied()->CabDeactivisation(); Occupied()->CabOccupied = 0; - Occupied()->BrakeLevelSet(Occupied()->Handle->GetPos(bh_NP)); // rozwala sterowanie hamulcem GF 04-2016 + Occupied()->BrakeLevelSet(Occupied()->brakes.driverValve->GetPos(bh_NP)); // rozwala sterowanie hamulcem GF 04-2016 Occupied()->MainCtrlPos = Occupied()->MainCtrlNoPowerPos(); Occupied()->ScndCtrlPos = 0; Dynamic()->MechInside = false; @@ -748,7 +748,7 @@ void TTrain::MoveToVehicle(TDynamicObject *target) Dynamic()->Controller = Humandriver; } - Occupied()->LimPipePress = Occupied()->brakePipe.pressure; + Occupied()->brakes.pipeLimiterPressure = Occupied()->brakePipe.pressure; Occupied()->CabActivisationAuto(true); // załączenie rozrządu (wirtualne kabiny) } else diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index 81399d8c6..5427dc0b5 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -79,7 +79,7 @@ bool TTrain::Update(double const Deltatime) } */ // replacement for the above. TODO: move it to a more suitable place - m_brakehandlecp = occupied->Handle->GetCP(); + m_brakehandlecp = occupied->brakes.driverValve->GetCP(); updateEngineGauges(); updateBasicLamps(); @@ -103,13 +103,13 @@ bool TTrain::Update(double const Deltatime) updateAuxiliaryButtons(lowvoltagepower); // wyprowadzenie sygnałów dla haslera na PoKeys (zaznaczanie na taśmie) - btHaslerBrakes.Turn(occupied->BrakePress > 0.4); // ciśnienie w cylindrach + btHaslerBrakes.Turn(occupied->brakes.cylinderPressure > 0.4); // ciśnienie w cylindrach btHaslerCurrent.Turn(occupied->Im != 0.0); // prąd na silnikach updateCabLightLevels(); // anti slip system activation, maintained while the control button is down - if (occupied->BrakeSystem != TBrakeSystem::ElectroPneumatic && ggAntiSlipButton.GetDesiredValue() > 0.95) + if (occupied->brakes.kind != TBrakeSystem::ElectroPneumatic && ggAntiSlipButton.GetDesiredValue() > 0.95) { controlled->AntiSlippingBrake(); } @@ -432,11 +432,11 @@ void TTrain::updateUnitStates() { if (p) { - fPress[i][0] = static_cast(p->physics->BrakePress); + fPress[i][0] = static_cast(p->physics->brakes.cylinderPressure); fPress[i][1] = static_cast(p->physics->brakePipe.pressure); fPress[i][2] = static_cast(p->physics->mainPipe.pressure); - fPress[i][3] = static_cast(p->physics->CntrlPipePress); - fPress[i][4] = static_cast(p->physics->Hamulec->GetBRP()); + fPress[i][3] = static_cast(p->physics->brakes.controlReservoirPressure); + fPress[i][4] = static_cast(p->physics->brakes.distributor->GetBRP()); fPress[i][5] = static_cast((p->physics->TotalMass - p->physics->Mred) * 0.001); fPress[i][6] = static_cast(p->physics->brakes.spring.pressure); bBrakes[i][0] = p->physics->brakes.spring.isActive; @@ -585,7 +585,7 @@ void TTrain::updateFeedbackGauges() const // Ra: sterowanie miernikiem: przewód główny Console::ValueSet(1, occupied->brakePipe.pressure); // Ra: sterowanie miernikiem: cylinder hamulcowy - Console::ValueSet(2, occupied->BrakePress); + Console::ValueSet(2, occupied->brakes.cylinderPressure); // woltomierz wysokiego napięcia Console::ValueSet(3, fHVoltage); // Ra: sterowanie miernikiem: drugi amperomierz @@ -842,7 +842,7 @@ void TTrain::updateCircuitLamps(double const Deltatime) btLampkaPrzekRozn.Turn(!controlled->GroundRelay && controlled->MainCircuitLampsEnabled()); // relay is off and needs a reset btLampkaNadmSil.Turn(controlled->FuseFlagCheck() && controlled->MainCircuitLampsEnabled()); // relay is off and needs a reset btLampkaUkrotnienie.Turn(controlled->Couplers[controlled->CabOccupied == 1 ? VehicleEnd::rear : VehicleEnd::front].CouplingFlag.HasAll(Coupling::control)); - btLampkaHamPosp.Turn(TestFlag(occupied->Hamulec->GetBrakeStatus(), 1)); // lampka drugiego stopnia hamowania + btLampkaHamPosp.Turn(TestFlag(occupied->brakes.distributor->GetBrakeStatus(), 1)); // lampka drugiego stopnia hamowania // TODO: youBy wyciągnąć flagę wysokiego stopnia btLampkaNadmWent.Turn(controlled->RventRot < 5.0 && controlled->ResistorsFlagCheck()); // hunter-121211: lampka zanikowo-pradowego wentylatorow btLampkaWysRozr.Turn(controlled->Imax >= controlled->ImaxHi); @@ -871,11 +871,11 @@ void TTrain::updateCircuitLamps(double const Deltatime) if (controlled->Signalling == true) { - if (occupied->BrakePress >= 1.45f) + if (occupied->brakes.cylinderPressure >= 1.45f) { btLampkaHamowanie1zes.Turn(true); } - if (controlled->BrakePress < 0.75f) + if (controlled->brakes.cylinderPressure < 0.75f) { btLampkaHamowanie1zes.Turn(false); } @@ -894,7 +894,7 @@ void TTrain::updateTrainLamps() // zależnie od typu lokomotywy case train_type::emu: { - btLampkaHamienie.Turn(controlled->BrakePress >= 0.2 && controlled->Signalling); + btLampkaHamienie.Turn(controlled->brakes.cylinderPressure >= 0.2 && controlled->Signalling); break; } case train_type::et41: @@ -903,14 +903,14 @@ void TTrain::updateTrainLamps() if (secondUnit) { // bo może komuś przyjść do głowy jeżdżenie jednym członem - btLampkaHamienie.Turn(secondUnit->BrakePress < 0.4); + btLampkaHamienie.Turn(secondUnit->brakes.cylinderPressure < 0.4); } break; } default: { - btLampkaHamienie.Turn(occupied->BrakePress >= 0.1 || controlled->DynamicBrakeFlag); - btLampkaBrakingOff.Turn(occupied->BrakePress < 0.1 && !controlled->DynamicBrakeFlag); + btLampkaHamienie.Turn(occupied->brakes.cylinderPressure >= 0.1 || controlled->DynamicBrakeFlag); + btLampkaBrakingOff.Turn(occupied->brakes.cylinderPressure < 0.1 && !controlled->DynamicBrakeFlag); break; } } @@ -920,7 +920,7 @@ void TTrain::updateTrainLamps() btLampkaRadio.Turn(occupied->Radio && occupied->RadioFuse); btLampkaRadioMessage.Turn(radio_message_played); btLampkaRadioStop.Turn(occupied->Radio && occupied->RadioFuse && occupied->RadioStopFlag); - btLampkaHamulecReczny.Turn(occupied->ManualBrakePos > 0); + btLampkaHamulecReczny.Turn(occupied->brakes.handBrakePosition > 0); // NBMX wrzesien 2003 - drzwi oraz sygnał odjazdu if (DynamicObject->Mechanik != nullptr) { @@ -959,9 +959,9 @@ void TTrain::updateTrainLamps() } btLampkaED.Turn(controlled->DynamicBrakeFlag); // hamulec ED - btLampkaBrakeProfileG.Turn(TestFlag(occupied->BrakeDelayFlag, bdelay_G)); - btLampkaBrakeProfileP.Turn(TestFlag(occupied->BrakeDelayFlag, bdelay_P)); - btLampkaBrakeProfileR.Turn(TestFlag(occupied->BrakeDelayFlag, bdelay_R)); + btLampkaBrakeProfileG.Turn(TestFlag(occupied->brakes.delaySetting, bdelay_G)); + btLampkaBrakeProfileP.Turn(TestFlag(occupied->brakes.delaySetting, bdelay_P)); + btLampkaBrakeProfileR.Turn(TestFlag(occupied->brakes.delaySetting, bdelay_R)); btLampkaSpringBrakeActive.Turn(occupied->brakes.spring.isActive); btLampkaSpringBrakeInactive.Turn(!occupied->brakes.spring.isActive); // light indicators @@ -1129,11 +1129,11 @@ void TTrain::updateSecondUnitLamps(bool const lowvoltagepower) btLampkaSprezarkaBOff.Turn(false == physics->air.compressor.running); if (controlled->Signalling == true) { - if (physics->BrakePress >= 1.45f) + if (physics->brakes.cylinderPressure >= 1.45f) { btLampkaHamowanie2zes.Turn(true); } - if (physics->BrakePress < 0.75f) + if (physics->brakes.cylinderPressure < 0.75f) { btLampkaHamowanie2zes.Turn(false); } @@ -1191,7 +1191,7 @@ void TTrain::updateMasterControllers(bool const lowvoltagepower) // represents the dedicated dynamic-brake lever (DBPN steps), not the pneumatic local brake auto const negativePart{controlled->SplitEDPneumaticBrake ? (controlled->DynamicBrakeCtrlPos > 0.0 ? controlled->DynamicBrakeCtrlPos * controlled->DynamicBrakeCtrlPosNo * -1 * brakerangemultiplier : 0.0) : - occupied->LocalBrakePosA > 0.0 ? occupied->LocalBrakePosA * LocalBrakePosNo * -1 * brakerangemultiplier : + occupied->brakes.independentPosition > 0.0 ? occupied->brakes.independentPosition * LocalBrakePosNo * -1 * brakerangemultiplier : 0.0}; ggJointCtrl.UpdateValue(negativePart < 0.0 ? static_cast(negativePart) : controlled->CoupledCtrl ? static_cast(double(controlled->MainCtrlPos + controlled->ScndCtrlPos)) : @@ -1276,27 +1276,27 @@ void TTrain::updateBrakeControllers() false && Global.fCalibrateIn[0][1] != 0.0) // nie blokujemy AI { // Ra: nie najlepsze miejsce, ale na początek gdzieś to dać trzeba // Firleju: dlatego kasujemy i zastepujemy funkcją w Console - if (occupied->BrakeHandle == TBrakeHandle::FV4a) + if (occupied->brakes.driverValveType == TBrakeHandle::FV4a) { double b = Console::AnalogCalibrateGet(0); b = b * 8.0 - 2.0; - b = safe_clamp(b, -2.0, (double)occupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic + b = safe_clamp(b, -2.0, (double)occupied->brakes.handlePositions); // przycięcie zmiennej do granic ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia occupied->BrakeLevelSet(b); } - else if (occupied->BrakeHandle == TBrakeHandle::FVel6) // może można usunąć ograniczenie do FV4a i FVel6? + else if (occupied->brakes.driverValveType == TBrakeHandle::FVel6) // może można usunąć ograniczenie do FV4a i FVel6? { double b = Console::AnalogCalibrateGet(0); b = b * 7.0 - 1.0; - b = safe_clamp(b, -1.0, (double)occupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic + b = safe_clamp(b, -1.0, (double)occupied->brakes.handlePositions); // przycięcie zmiennej do granic ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia occupied->BrakeLevelSet(b); } else { double b = Console::AnalogCalibrateGet(0); - b = b * (occupied->Handle->GetPos(bh_MAX) - occupied->Handle->GetPos(bh_MIN)) + occupied->Handle->GetPos(bh_MIN); - b = safe_clamp(b, occupied->Handle->GetPos(bh_MIN), occupied->Handle->GetPos(bh_MAX)); // przycięcie zmiennej do granic + b = b * (occupied->brakes.driverValve->GetPos(bh_MAX) - occupied->brakes.driverValve->GetPos(bh_MIN)) + occupied->brakes.driverValve->GetPos(bh_MIN); + b = safe_clamp(b, occupied->brakes.driverValve->GetPos(bh_MIN), occupied->brakes.driverValve->GetPos(bh_MAX)); // przycięcie zmiennej do granic ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia occupied->BrakeLevelSet(b); } @@ -1306,7 +1306,7 @@ void TTrain::updateBrakeControllers() { // else //standardowa prodedura z kranem powiązanym z klawiaturą // ggBrakeCtrl.UpdateValue(double(occupied->BrakeCtrlPos)); - ggBrakeCtrl.UpdateValue(static_cast(occupied->fBrakeCtrlPos)); + ggBrakeCtrl.UpdateValue(static_cast(occupied->brakes.handlePositionSmooth)); ggBrakeCtrl.Update(); } } @@ -1315,19 +1315,19 @@ void TTrain::updateBrakeControllers() { #ifdef _WIN32 if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag // nie blokujemy AI - && occupied->BrakeLocHandle == TBrakeHandle::FD1 && Global.iFeedbackMode == 4 && Global.fCalibrateIn[0][1] != 0.0) + && occupied->brakes.independentValveType == TBrakeHandle::FD1 && Global.iFeedbackMode == 4 && Global.fCalibrateIn[0][1] != 0.0) { // Ra: nie najlepsze miejsce, ale na początek gdzieś to dać trzeba // Firleju: dlatego kasujemy i zastepujemy funkcją w Console auto const b = std::clamp(Console::AnalogCalibrateGet(1), 0.f, 1.f); - occupied->LocalBrakePosA = b; + occupied->brakes.independentPosition = b; ggLocalBrake.UpdateValue(b * LocalBrakePosNo); } else #endif { // standardowa prodedura z kranem powiązanym z klawiaturą - ggLocalBrake.UpdateValue(static_cast(occupied->LocalBrakePosA * LocalBrakePosNo)); + ggLocalBrake.UpdateValue(static_cast(occupied->brakes.independentPosition * LocalBrakePosNo)); } ggLocalBrake.Update(); } diff --git a/vehicle/crew.cpp b/vehicle/crew.cpp index 2484ca9f7..5897dd5cb 100644 --- a/vehicle/crew.cpp +++ b/vehicle/crew.cpp @@ -117,10 +117,10 @@ void secure(physics::Vehicle &Occupied, physics::Vehicle &Controlling) { cut_power(Occupied); } // the emergency position vents the brake pipe whatever the brake mode, and with nobody in the cab too - Occupied.BrakeLevelSet(Occupied.Handle->GetPos(bh_EB)); + Occupied.BrakeLevelSet(Occupied.brakes.driverValve->GetPos(bh_EB)); // a vehicle with no train brake (a car, a draisine) gets the brake its driver stops it with, in full - if (Occupied.BrakeSystem == TBrakeSystem::Individual) { - if (Occupied.LocalBrake == TLocalBrake::ManualBrake) { + if (Occupied.brakes.kind == TBrakeSystem::Individual) { + if (Occupied.brakes.localKind == TLocalBrake::ManualBrake) { Occupied.IncManualBrakeLevel(ManualBrakePosNo); } else { diff --git a/vehicle/drivingaid.cpp b/vehicle/drivingaid.cpp index 49f0e8ef9..1638c4ddd 100644 --- a/vehicle/drivingaid.cpp +++ b/vehicle/drivingaid.cpp @@ -70,8 +70,8 @@ input from_vehicles(physics::Vehicle const &Vehicle, physics::Vehicle const &Con result.dynamicbrakeposno = Controlling.DynamicBrakeCtrlPosNo; result.mainctrlpos = Controlling.MainCtrlPos; result.scndctrlpos = Controlling.ScndCtrlPos; - result.brakectrlpos = Vehicle.fBrakeCtrlPos; - result.localbrakepos = Vehicle.LocalBrakePosA; + result.brakectrlpos = Vehicle.brakes.handlePositionSmooth; + result.localbrakepos = Vehicle.brakes.independentPosition; result.cab = Cab; return result; } diff --git a/vehicle/dynamic/lifecycle.cpp b/vehicle/dynamic/lifecycle.cpp index 9fe33bed3..8fbf1592e 100644 --- a/vehicle/dynamic/lifecycle.cpp +++ b/vehicle/dynamic/lifecycle.cpp @@ -268,20 +268,20 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" // controller position physics->MainCtrlPos = physics->MainCtrlNoPowerPos(); // ustawienie pozycji hamulca - physics->LocalBrakePosA = 0.0; + physics->brakes.independentPosition = 0.0; if (driveractive) { if (Cab == 0) - physics->BrakeCtrlPos = - static_cast( std::floor(physics->Handle->GetPos(bh_NP)) ); + physics->brakes.handlePosition = + static_cast( std::floor(physics->brakes.driverValve->GetPos(bh_NP)) ); else - physics->BrakeCtrlPos = static_cast( std::floor(physics->Handle->GetPos(bh_RP)) ); + physics->brakes.handlePosition = static_cast( std::floor(physics->brakes.driverValve->GetPos(bh_RP)) ); // engage independent brake if applicable, if the vehicle is to be on standby // NOTE: with more than one driver in the consist this is likely to go awery, since all but one will be sent to sleep // TBD, TODO: have the virtual helper release independent brakes during consist check? if( DriverType != "" ) { - if( physics->LocalBrake != TLocalBrake::ManualBrake ) { + if( physics->brakes.localKind != TLocalBrake::ManualBrake ) { if( fVel < 1.0 ) { physics->IncLocalBrakeLevel( LocalBrakePosNo ); if ( physics->EIMCtrlEmergency ) { @@ -292,12 +292,12 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" } } else - physics->BrakeCtrlPos = - static_cast( std::floor(physics->Handle->GetPos(bh_NP)) ); + physics->brakes.handlePosition = + static_cast( std::floor(physics->brakes.driverValve->GetPos(bh_NP)) ); // poprawienie hamulca po ewentualnym przestawieniu przez Pascal // TODO: check if needed, we're not in Pascal anymore, Toto - physics->BrakeLevelSet(physics->BrakeCtrlPos); + physics->BrakeLevelSet(physics->brakes.handlePosition); // dodatkowe parametry yB MoreParams += "."; // wykonuje o jedną iterację za mało, więc trzeba mu dodać @@ -334,22 +334,22 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" // wylaczanie hamulca if ( contains( ActPar, "<>") ) // wylaczanie na probe hamowania naglego { - physics->Hamulec->SetBrakeStatus( physics->Hamulec->GetBrakeStatus() | b_dmg ); // wylacz + physics->brakes.distributor->SetBrakeStatus( physics->brakes.distributor->GetBrakeStatus() | b_dmg ); // wylacz } if ( contains( ActPar, '0' ) ) // wylaczanie na sztywno { - physics->Hamulec->ForceEmptiness(); - physics->Hamulec->SetBrakeStatus( physics->Hamulec->GetBrakeStatus() | b_dmg ); // wylacz + physics->brakes.distributor->ForceEmptiness(); + physics->brakes.distributor->SetBrakeStatus( physics->brakes.distributor->GetBrakeStatus() | b_dmg ); // wylacz } if ( contains( ActPar, 'E' ) ) // oprozniony { - physics->Hamulec->ForceEmptiness(); + physics->brakes.distributor->ForceEmptiness(); physics->brakePipe.reservoir->CreatePress(0); physics->mainPipe.reservoir->CreatePress(0); } if ( contains( ActPar, 'Q' ) ) // oprozniony { - physics->Hamulec->ForceEmptiness(); + physics->brakes.distributor->ForceEmptiness(); physics->brakePipe.reservoir->CreatePress(0.0); physics->brakePipe.pressure = 0.0; physics->mainPipe.reservoir->CreatePress(0.0); @@ -363,39 +363,39 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" { if (Random(10) < 1) // losowanie 1/10 { - physics->Hamulec->ForceEmptiness(); - physics->Hamulec->SetBrakeStatus( physics->Hamulec->GetBrakeStatus() | b_dmg ); // wylacz + physics->brakes.distributor->ForceEmptiness(); + physics->brakes.distributor->SetBrakeStatus( physics->brakes.distributor->GetBrakeStatus() | b_dmg ); // wylacz } } if ( contains( ActPar, 'X') ) // agonalny wylaczanie 20%, usrednienie przekladni { if (Random(100) < 20) // losowanie 20/100 { - physics->Hamulec->ForceEmptiness(); - physics->Hamulec->SetBrakeStatus( physics->Hamulec->GetBrakeStatus() | b_dmg ); // wylacz + physics->brakes.distributor->ForceEmptiness(); + physics->brakes.distributor->SetBrakeStatus( physics->brakes.distributor->GetBrakeStatus() | b_dmg ); // wylacz } - if (physics->BrakeCylMult[2] * physics->BrakeCylMult[1] > + if (physics->brakes.cylinders.leverRatio[2] * physics->brakes.cylinders.leverRatio[1] > 0.01) // jesli jest nastawiacz mechaniczny PL { float rnd = Random(100); if (rnd < 20) // losowanie 20/100 usrednienie { - physics->BrakeCylMult[2] = physics->BrakeCylMult[1] = - (physics->BrakeCylMult[2] + physics->BrakeCylMult[1]) / + physics->brakes.cylinders.leverRatio[2] = physics->brakes.cylinders.leverRatio[1] = + (physics->brakes.cylinders.leverRatio[2] + physics->brakes.cylinders.leverRatio[1]) / 2; } else if (rnd < 70) // losowanie 70/100-20/100 oslabienie { - physics->BrakeCylMult[1] = physics->BrakeCylMult[1] * 0.50; - physics->BrakeCylMult[2] = physics->BrakeCylMult[2] * 0.75; + physics->brakes.cylinders.leverRatio[1] = physics->brakes.cylinders.leverRatio[1] * 0.50; + physics->brakes.cylinders.leverRatio[2] = physics->brakes.cylinders.leverRatio[2] * 0.75; } else if (rnd < 80) // losowanie 80/100-70/100 tylko prozny { - physics->BrakeCylMult[2] = physics->BrakeCylMult[1]; + physics->brakes.cylinders.leverRatio[2] = physics->brakes.cylinders.leverRatio[1]; } else // tylko ladowny { - physics->BrakeCylMult[1] = physics->BrakeCylMult[2]; + physics->brakes.cylinders.leverRatio[1] = physics->brakes.cylinders.leverRatio[2]; } } } diff --git a/vehicle/dynamic/sounds.cpp b/vehicle/dynamic/sounds.cpp index 37c6963e1..a99610a14 100644 --- a/vehicle/dynamic/sounds.cpp +++ b/vehicle/dynamic/sounds.cpp @@ -79,7 +79,7 @@ void TDynamicObject::RenderSounds() { // brake system and braking sounds: // brake cylinder piston - auto const brakepressureratio { std::max( 0.0, physics->BrakePress ) / std::max( 1.0, physics->MaxBrakePress[ 3 ] ) }; + auto const brakepressureratio { std::max( 0.0, physics->brakes.cylinderPressure ) / std::max( 1.0, physics->brakes.maxCylinderPressure[ 3 ] ) }; renderBrakeCylinderSounds( brakepressureratio ); renderEpBrakeSounds( dt ); renderEmergencyBrakeSound(); @@ -233,7 +233,7 @@ void TDynamicObject::renderBrakeCylinderSounds( double const brakepressureratio } // actual sound playback auto const quantizedratio { static_cast( 15 * brakepressureratio ) }; - auto const lastbrakepressureratio { std::max( 0.f, m_lastbrakepressure ) / std::max( 1.0, physics->MaxBrakePress[ 3 ] ) }; + auto const lastbrakepressureratio { std::max( 0.f, m_lastbrakepressure ) / std::max( 1.0, physics->brakes.maxCylinderPressure[ 3 ] ) }; auto const quantizedratiochange { quantizedratio - static_cast( 15 * lastbrakepressureratio ) }; if( quantizedratiochange > 0 ) { m_brakecylinderpistonadvance @@ -257,10 +257,10 @@ void TDynamicObject::renderBrakeCylinderSounds( double const brakepressureratio void TDynamicObject::renderEpBrakeSounds( double const dt ) { // epbrake - epcompact - if (physics->BrakeSystem == TBrakeSystem::ElectroPneumatic && physics->LocHandle) { - auto const epbrakepressureratio{ std::min( std::max( 0.0, physics->LocHandle->GetCP() ) / std::max( 1.0, physics->MaxBrakePress[0] ), + if (physics->brakes.kind == TBrakeSystem::ElectroPneumatic && physics->brakes.independentValve) { + auto const epbrakepressureratio{ std::min( std::max( 0.0, physics->brakes.independentValve->GetCP() ) / std::max( 1.0, physics->brakes.maxCylinderPressure[0] ), m_epbrakepressurechangedectimer > -1.0f ? - std::max( physics->LocalBrakePosAEIM, physics->Hamulec->GetEDBCP() / physics->MaxBrakePress[3]) : + std::max( physics->brakes.independentPositionEim, physics->brakes.distributor->GetEDBCP() / physics->brakes.maxCylinderPressure[3]) : 1.0 ) }; if ( m_lastepbrakepressure != -1.f ) { // HACK: potentially reset playback of opening bookend sounds @@ -274,7 +274,7 @@ void TDynamicObject::renderEpBrakeSounds( double const dt ) { m_epbrakepressurechangedectimer += dt; // actual sound playback auto const epquantizedratio{ static_cast( 50 * epbrakepressureratio) }; - auto const lastepbrakepressureratio { std::max( 0.f, m_lastepbrakepressure ) / std::max( 1.0, physics->MaxBrakePress[0] ) }; + auto const lastepbrakepressureratio { std::max( 0.f, m_lastepbrakepressure ) / std::max( 1.0, physics->brakes.maxCylinderPressure[0] ) }; auto const epquantizedratiochange { epquantizedratio - static_cast( 50 * lastepbrakepressureratio ) }; if ( epquantizedratiochange > 0 && m_epbrakepressurechangeinctimer > 0.05f) { m_epbrakepressureincrease @@ -295,8 +295,8 @@ void TDynamicObject::renderEpBrakeSounds( double const dt ) { } } if ( m_epbrakepressurechangeinctimer == 0 || m_epbrakepressurechangedectimer == 0 ) - m_lastepbrakepressure = std::min( physics->LocHandle->GetCP(), - physics->LocalBrakePosAEIM * std::max( 1.0, physics->MaxBrakePress[0] ) ); + m_lastepbrakepressure = std::min( physics->brakes.independentValve->GetCP(), + physics->brakes.independentPositionEim * std::max( 1.0, physics->brakes.maxCylinderPressure[0] ) ); } } @@ -304,9 +304,9 @@ void TDynamicObject::renderEpBrakeSounds( double const dt ) { void TDynamicObject::renderEmergencyBrakeSound() { // emergency brake - if( physics->EmergencyValveFlow > 0.025 ) { + if( physics->brakes.emergencyValve.flow > 0.025 ) { // smooth out air flow rate - m_emergencybrakeflow = m_emergencybrakeflow == 0.0 ? physics->EmergencyValveFlow : std::lerp(m_emergencybrakeflow, physics->EmergencyValveFlow, 0.1); + m_emergencybrakeflow = m_emergencybrakeflow == 0.0 ? physics->brakes.emergencyValve.flow : std::lerp(m_emergencybrakeflow, physics->brakes.emergencyValve.flow, 0.1); // scale volume based on the flow rate and on the pressure in the main pipe auto const flowpressure { std::clamp( m_emergencybrakeflow, 0.0, 1.0 ) + std::clamp( 0.1 * physics->brakePipe.pressure, 0.0, 0.5 ) }; m_emergencybrake @@ -314,7 +314,7 @@ void TDynamicObject::renderEmergencyBrakeSound() { .gain( m_emergencybrake.m_amplitudeoffset + std::clamp( flowpressure, 0.0, 1.0 ) * m_emergencybrake.m_amplitudefactor ) .play( sound_flags::exclusive | sound_flags::looping ); } - else if( physics->EmergencyValveFlow < 0.015 ) { + else if( physics->brakes.emergencyValve.flow < 0.015 ) { m_emergencybrakeflow = 0.0; m_emergencybrake.stop(); } @@ -328,10 +328,10 @@ void TDynamicObject::renderAirReleaseSounds( double const dt, double const brake // air release if( m_lastbrakepressure != -1.f ) { // calculate rate of pressure drop in brake cylinder, once it's been initialized - auto const brakepressuredifference{ m_lastbrakepressure - physics->BrakePress }; + auto const brakepressuredifference{ m_lastbrakepressure - physics->brakes.cylinderPressure }; m_brakepressurechange = std::lerp( m_brakepressurechange, brakepressuredifference / dt, 0.05f ); } - m_lastbrakepressure = physics->BrakePress; + m_lastbrakepressure = physics->brakes.cylinderPressure; // ensure some basic level of volume and scale it up depending on pressure in the cylinder; scale this by the air release rate volume = rsUnbrake.m_amplitudefactor * m_brakepressurechange * ( 0.25 + 0.75 * brakepressureratio ); if( m_brakepressurechange > 0.05 && brakepressureratio > 0.05 ) { @@ -349,11 +349,11 @@ void TDynamicObject::renderAirReleaseSounds( double const dt, double const brake } // Dzwiek odluzniacza - if( physics->Hamulec->Releaser() ) { + if( physics->brakes.distributor->Releaser() ) { sReleaser .gain( std::clamp( - physics->BrakePress * 1.25, // arbitrary multiplier + physics->brakes.cylinderPressure * 1.25, // arbitrary multiplier 0., 1. ) ) .play( sound_flags::exclusive | sound_flags::looping ); } @@ -368,7 +368,7 @@ void TDynamicObject::renderSlipAndSandSounds() { // slipping wheels if( physics->SlippingWheels ) { - if( physics->UnitBrakeForce > 100.0 + if( physics->brakes.unitForce > 100.0 && GetVelocity() > 1.0 ) { auto const velocitydifference{ GetVelocity() / physics->Vmax }; @@ -398,12 +398,12 @@ double TDynamicObject::renderBrakeFrictionSounds( double const dt ) { // brakes auto brakeforceratio{ 0.0 }; if( //( false == occupied->SlippingWheels ) && - physics->UnitBrakeForce > 10.0 + physics->brakes.unitForce > 10.0 && physics->Vel > 0.05 ) { brakeforceratio = std::clamp( - physics->UnitBrakeForce / std::max( 1.0, physics->BrakeForceR( 1.0, physics->Vel ) / ( physics->NAxles * std::max( 1, physics->NBpA ) ) ), + physics->brakes.unitForce / std::max( 1.0, physics->BrakeForceR( 1.0, physics->Vel ) / ( physics->NAxles * std::max( 1, physics->brakes.blocksPerAxle ) ) ), 0.0, 1.0 ); rsBrake .pitch( rsBrake.m_frequencyoffset + physics->Vel * rsBrake.m_frequencyfactor ) @@ -416,7 +416,7 @@ double TDynamicObject::renderBrakeFrictionSounds( double const dt ) { // yB: przyspieszacz (moze zadziala, ale dzwiek juz jest) if( true == bBrakeAcc ) { - if( true == TestFlag( physics->Hamulec->GetSoundFlag(), sf_Acc ) ) { + if( true == TestFlag( physics->brakes.distributor->GetSoundFlag(), sf_Acc ) ) { sBrakeAcc.play( sound_flags::exclusive ); } } @@ -620,7 +620,7 @@ void TDynamicObject::renderHornSounds() { // for moving vehicle combine regular horn activation flag with emergency brake horn activation flag, if the brake is active; // the horns without the air or the voltage they need stay silent auto const warningsignal { physics->SoundingHorns( - ( physics->Vel > 0.5 && physics->AlarmChainFlag ? + ( physics->Vel > 0.5 && physics->brakes.alarmChain ? physics->EmergencyBrakeWarningSignal : 0 ) | physics->WarningSignal ) }; diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index 8d0465bfa..8a74d47f5 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -302,7 +302,7 @@ void TDynamicObject::updateTractionVoltage( double const dt1 ) void TDynamicObject::updateDriver( double const dt1 ) { if( Mechanik->primary() ) { - physics->EqvtPipePress = GetEPP(); // srednie cisnienie w PG + physics->brakes.equivalentPipePressure = GetEPP(); // srednie cisnienie w PG } if (Mechanik->primary() && (physics->EngineType == TEngineType::DieselEngine || @@ -385,7 +385,7 @@ void TDynamicObject::setInductionControl( InductionBrakeState &state, double con state.eimic = -1.0; physics->SendCtrlToNext(VehicleCommand::integratedController, std::max(0., state.eimic), physics->CabActive); state.LBR = std::max(-state.eimic, 0.); - state.eim_lb = Mechanik->AIControllFlag || !physics->LocHandleTimeTraxx ? 0 : physics->eim_localbrake; + state.eim_lb = Mechanik->AIControllFlag || !physics->brakes.independentTraxx ? 0 : physics->eim_localbrake; } // steps 1-2 of the blending: the masses and the most braking forces, pneumatic and ED, summed over the consist @@ -406,18 +406,18 @@ void TDynamicObject::sumConsistBrakeForces( InductionBrakeState &state ) { ++state.np; state.masamax += - p->physics->MBPM - + ( p->physics->MBPM > 1.0 ? + p->physics->brakes.maxPressureMass + + ( p->physics->brakes.maxPressureMass > 1.0 ? 0.0 : p->physics->Mass ) + p->physics->Mred; - auto const Nmax = ((p->physics->P2FTrans * p->physics->MaxBrakePress[0] - - p->physics->BrakeCylSpring) * - p->physics->BrakeCylMult[0] - - p->physics->BrakeSlckAdj) * - p->physics->BrakeCylNo * p->physics->BrakeRigEff; - state.FmaxPN += Nmax * p->physics->Hamulec->GetFC( - Nmax / (p->physics->NAxles * p->physics->NBpA), + auto const Nmax = ((p->physics->brakes.pressureToForce * p->physics->brakes.maxCylinderPressure[0] - + p->physics->brakes.cylinders.springForce) * + p->physics->brakes.cylinders.leverRatio[0] - + p->physics->brakes.cylinders.slackAdjusterForce) * + p->physics->brakes.cylinders.count * p->physics->brakes.cylinders.riggingEfficiency; + state.FmaxPN += Nmax * p->physics->brakes.distributor->GetFC( + Nmax / (p->physics->NAxles * p->physics->brakes.blocksPerAxle), p->physics->brakes.blending.referenceSpeed) * 1000; // sila hamowania pn state.FmaxED += p->physics->Mains && p->physics->DirActive != 0 && p->physics->inductionMotor.inverterRatio == 1.0 && @@ -441,9 +441,9 @@ void TDynamicObject::sumConsistBrakeForces( InductionBrakeState &state ) void TDynamicObject::computeBrakeDeceleration( InductionBrakeState &state ) { double RapidMult = 1.0; - if ((physics->BrakeDelays & bdelay_P + bdelay_R) == bdelay_P + bdelay_R - && physics->BrakeDelayFlag & bdelay_P) - RapidMult = physics->RapidMult; + if ((physics->brakes.availableDelays & bdelay_P + bdelay_R) == bdelay_P + bdelay_R + && physics->brakes.delaySetting & bdelay_P) + RapidMult = physics->brakes.rapidRatio; state.amax = RapidMult * std::min(state.FmaxPN / state.masamax, physics->brakes.blending.maxDeceleration); @@ -461,7 +461,7 @@ void TDynamicObject::updateShuntMode( InductionBrakeState &state ) || physics->Doors.instances[ VehicleSide::right ].open_permit ) ); state.doorisopen &= !(physics->brakes.spring.releasesParkingWithDoorOpen && physics->brakes.spring.isActive); - if (physics->Vel < 0.5 && (state.eimic < 0 || state.doorisopen || physics->Hamulec->GetEDBCP())) + if (physics->Vel < 0.5 && (state.eimic < 0 || state.doorisopen || physics->brakes.distributor->GetEDBCP())) { physics->ShuntMode = true; } @@ -473,7 +473,7 @@ void TDynamicObject::updateShuntMode( InductionBrakeState &state ) if( physics->Vel > 1 && false == state.doorisopen ) { physics->ShuntMode = false; - physics->ShuntModeAllow = physics->BrakePress > 0.2 && + physics->ShuntModeAllow = physics->brakes.cylinderPressure > 0.2 && state.LBR < 0.01; } } @@ -481,9 +481,9 @@ void TDynamicObject::updateShuntMode( InductionBrakeState &state ) void TDynamicObject::computeBrakeDemand( InductionBrakeState &state, double const dt1 ) { state.Fzad = state.amax * state.LBR * state.masa; - if ((physics->BrakeCtrlPos == physics->Handle->GetPos(bh_EB) + if ((physics->brakes.handlePosition == physics->brakes.driverValve->GetPos(bh_EB) && physics->inductionMotor.braking.cylinderPressureGain < 0.001) || - physics->EmergencyValveFlow > 0) + physics->brakes.emergencyValve.flow > 0) state.Fzad = state.amax * state.masa; //pętla bezpieczeństwa - pełne służbowe if (physics->ScndS && physics->Vel > physics->inductionMotor.braking.fullSpeed && state.FmaxED > 0) @@ -525,8 +525,8 @@ void TDynamicObject::computeElectrodynamicDemand( InductionBrakeState &state, do { state.FzadED = 0.0; if( state.LBR > physics->brakes.blending.minEdDemand - && ( physics->BrakeHandle == TBrakeHandle::MHZ_EN57 ? - (physics->BrakeOpModeFlag & bom_MED) != 0 : + && ( physics->brakes.driverValveType == TBrakeHandle::MHZ_EN57 ? + (physics->brakes.operatingMode & bom_MED) != 0 : physics->EpFuse ) ) { state.FzadED = std::min( state.Fzad, state.FmaxED ); } @@ -553,7 +553,7 @@ void TDynamicObject::computeElectrodynamicDemand( InductionBrakeState &state, do physics->brakes.blending.edDelayTimer = state.FrED > 0 ? -physics->brakes.blending.edNextDelay : -physics->brakes.blending.edFirstDelay; } } - if (physics->BrakeCtrlPos == physics->Handle->GetPos(bh_EB) + if (physics->brakes.handlePosition == physics->brakes.driverValve->GetPos(bh_EB) && physics->inductionMotor.braking.cylinderPressureGain < 0.001) state.FzadED = 0; //pętla bezpieczeństwa - bez ED state.FzadPN = state.Fzad - state.FrED * physics->brakes.blending.edForceFactor; @@ -584,14 +584,14 @@ void TDynamicObject::distributeBrakeForces( InductionBrakeState &state, double c for (TDynamicObject *p = GetFirstDynamic(physics->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; p = state.kier == true ? p->Next(Coupling::control) : p->Prev(Coupling::control) ) { - auto const Nmax = ((p->physics->P2FTrans * p->physics->MaxBrakePress[0] - - p->physics->BrakeCylSpring) * - p->physics->BrakeCylMult[0] - - p->physics->BrakeSlckAdj) * - p->physics->BrakeCylNo * p->physics->BrakeRigEff; + auto const Nmax = ((p->physics->brakes.pressureToForce * p->physics->brakes.maxCylinderPressure[0] - + p->physics->brakes.cylinders.springForce) * + p->physics->brakes.cylinders.leverRatio[0] - + p->physics->brakes.cylinders.slackAdjusterForce) * + p->physics->brakes.cylinders.count * p->physics->brakes.cylinders.riggingEfficiency; FmaxEP[i] = Nmax * - p->physics->Hamulec->GetFC( - Nmax / (p->physics->NAxles * p->physics->NBpA), + p->physics->brakes.distributor->GetFC( + Nmax / (p->physics->NAxles * p->physics->brakes.blocksPerAxle), p->physics->brakes.blending.referenceSpeed) * 1000; // sila hamowania pn @@ -647,11 +647,11 @@ void TDynamicObject::distributeBrakeForces( InductionBrakeState &state, double c for (TDynamicObject *p = GetFirstDynamic(physics->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; true == state.kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) { - float Nmax = ((p->physics->P2FTrans * p->physics->MaxBrakePress[0] - - p->physics->BrakeCylSpring) * - p->physics->BrakeCylMult[0] - - p->physics->BrakeSlckAdj) * - p->physics->BrakeCylNo * p->physics->BrakeRigEff; + float Nmax = ((p->physics->brakes.pressureToForce * p->physics->brakes.maxCylinderPressure[0] - + p->physics->brakes.cylinders.springForce) * + p->physics->brakes.cylinders.leverRatio[0] - + p->physics->brakes.cylinders.slackAdjusterForce) * + p->physics->brakes.cylinders.count * p->physics->brakes.cylinders.riggingEfficiency; if (state.FrED > 0.1) p->physics->brakes.blending.epCorrectionTimer = 0; else @@ -659,27 +659,27 @@ void TDynamicObject::distributeBrakeForces( InductionBrakeState &state, double c bool EPVC = p->physics->brakes.blending.epCorrection && (p->physics->brakes.blending.epCorrectionTime < 0 || p->physics->brakes.blending.epCorrectionTimer < p->physics->brakes.blending.epCorrectionTime); float VelC = EPVC ? safe_clamp(p->physics->Vel, p->physics->brakes.blending.minSpeed, p->physics->brakes.blending.maxSpeed) : p->physics->brakes.blending.referenceSpeed;//korekcja EP po prędkości float FmaxPoj = Nmax * - p->physics->Hamulec->GetFC( - Nmax / (p->physics->NAxles * p->physics->NBpA), VelC) * + p->physics->brakes.distributor->GetFC( + Nmax / (p->physics->NAxles * p->physics->brakes.blocksPerAxle), VelC) * 1000; // sila hamowania pn - p->physics->LocalBrakePosAEIM = FzEP[i] / FmaxPoj; - if (p->physics->LocalBrakePosAEIM>0.009) - if (p->physics->P2FTrans * p->physics->BrakeCylMult[0] * - p->physics->MaxBrakePress[0] != 0) + p->physics->brakes.independentPositionEim = FzEP[i] / FmaxPoj; + if (p->physics->brakes.independentPositionEim>0.009) + if (p->physics->brakes.pressureToForce * p->physics->brakes.cylinders.leverRatio[0] * + p->physics->brakes.maxCylinderPressure[0] != 0) { - float x = (p->physics->BrakeSlckAdj / p->physics->BrakeCylMult[0] + - p->physics->BrakeCylSpring) / (p->physics->P2FTrans * - p->physics->MaxBrakePress[0]); - p->physics->LocalBrakePosAEIM = x + (1 - x) * p->physics->LocalBrakePosAEIM; + float x = (p->physics->brakes.cylinders.slackAdjusterForce / p->physics->brakes.cylinders.leverRatio[0] + + p->physics->brakes.cylinders.springForce) / (p->physics->brakes.pressureToForce * + p->physics->brakes.maxCylinderPressure[0]); + p->physics->brakes.independentPositionEim = x + (1 - x) * p->physics->brakes.independentPositionEim; } else - p->physics->LocalBrakePosAEIM = p->physics->LocalBrakePosAEIM; + p->physics->brakes.independentPositionEim = p->physics->brakes.independentPositionEim; else - p->physics->LocalBrakePosAEIM = 0; - if (p->physics->LocHandleTimeTraxx) + p->physics->brakes.independentPositionEim = 0; + if (p->physics->brakes.independentTraxx) { p->physics->eim_localbrake = state.eim_lb; - p->physics->LocalBrakePosAEIM = std::max(p->physics->LocalBrakePosAEIM, state.eim_lb); + p->physics->brakes.independentPositionEim = std::max(p->physics->brakes.independentPositionEim, state.eim_lb); } ++i; } @@ -704,7 +704,7 @@ void TDynamicObject::recordMedState( InductionBrakeState const &state, double co for (TDynamicObject *p = GetFirstDynamic(physics->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; true == state.kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) { - MEDLogFile << "\t" << p->physics->BrakePress; + MEDLogFile << "\t" << p->physics->brakes.cylinderPressure; } MEDLogFile << "\n"; if (floor(MEDLogTime + dt1) > floor(MEDLogTime)) diff --git a/vehicle/handover.cpp b/vehicle/handover.cpp index 73996d12e..6a2a75dce 100644 --- a/vehicle/handover.cpp +++ b/vehicle/handover.cpp @@ -24,7 +24,7 @@ void release_ai_controls(physics::Vehicle &Occupied, physics::Vehicle &Controlli if (Occupied.DepartureSignal) { Occupied.signal_departure(false); } - if (Occupied.Hamulec->Releaser()) { + if (Occupied.brakes.distributor->Releaser()) { Occupied.BrakeReleaser(0); } } diff --git a/widgets/vehicleparams.cpp b/widgets/vehicleparams.cpp index b4dfc2b6b..b53f23f01 100644 --- a/widgets/vehicleparams.cpp +++ b/widgets/vehicleparams.cpp @@ -190,7 +190,7 @@ void ui::vehicleparams_panel::render_contents() for (auto const &delay : delays) { - if ((physics.BrakeDelayFlag & delay.first) == delay.first) + if ((physics.brakes.delaySetting & delay.first) == delay.first) { brakedelay += delay.second; } @@ -201,13 +201,13 @@ void ui::vehicleparams_panel::render_contents() STR_C("Brakes:\n train: %.2f, independent: %.2f, mode: %d, delay: %s, load flag: %d\nBrake cylinder pressures:\n train: %.2f, independent: %.2f, status: 0x%.2x\nPipe pressures:\n " "brake: %.2f (hat: %.2f), main: %.2f, control: %.2f\nTank pressures:\n auxiliary: %.2f, main: %.2f, control: %.2f"), // brakes - physics.fBrakeCtrlPos, physics.LocalBrakePosA, physics.BrakeOpModeFlag, brakedelay.c_str(), physics.LoadFlag, + physics.brakes.handlePositionSmooth, physics.brakes.independentPosition, physics.brakes.operatingMode, brakedelay.c_str(), physics.brakes.loadSetting, // cylinders - physics.BrakePress, physics.LocBrakePress, physics.Hamulec->GetBrakeStatus(), + physics.brakes.cylinderPressure, physics.brakes.independentCylinderPressure, physics.brakes.distributor->GetBrakeStatus(), // pipes - physics.brakePipe.pressure, physics.BrakeCtrlPos2, physics.mainPipe.pressure, physics.CntrlPipePress, + physics.brakePipe.pressure, physics.brakes.handleCapPosition, physics.mainPipe.pressure, physics.brakes.controlReservoirPressure, // tanks - physics.Hamulec->GetBRP(), physics.air.mainReservoirPressure, physics.Hamulec->GetCRP()); + physics.brakes.distributor->GetBRP(), physics.air.mainReservoirPressure, physics.brakes.distributor->GetCRP()); ImGui::TextUnformatted(buffer.data()); diff --git a/world/TrackBuckle.cpp b/world/TrackBuckle.cpp index 7dabf4c0b..a3d056db8 100644 --- a/world/TrackBuckle.cpp +++ b/world/TrackBuckle.cpp @@ -215,7 +215,7 @@ void TTrack::buckle_pass_enter( TDynamicObject const &Dynamic ) { } ++m_buckle_passes; auto const *physics { Dynamic.physics }; - auto const train { physics != nullptr && track_buckle::stirs( std::abs( physics->Vel ), physics->BrakePress > 0.5 ) }; + auto const train { physics != nullptr && track_buckle::stirs( std::abs( physics->Vel ), physics->brakes.cylinderPressure > 0.5 ) }; auto const rise { rail_temperature_now() - m_cwr.neutral }; auto const draw { track_buckle::draw( buckle_key(), Global.random_seed, track_buckle::pass, m_buckle_passes ) }; m_buckle_armed = ( track_buckle::decide( rise, buckle_limits(), train, draw ) != track_buckle::verdict::none ); From 5e56a915151b377577bd27afc41dd6a6995f3c45 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 02:13:17 +0100 Subject: [PATCH 031/123] refactor(physics): the devices out of physics::Vehicle, the pantographs as components The types of the devices nested in physics::Vehicle (basic_device, the pumps, the fans, basic_valve, basic_pantograph, basic_door, door_data, water_heater, genset_device) move out of it into physics/components/devices.h, namespace physics, so the components of the vehicle can hold them. The pantographs and their air become components, with English names (physics/components/pantographs.h): Pantographs pantographs (ByEnd) pantographCircuit PantFrontVolt / PantRearVolt frontVoltage / rearVoltage, PantographVoltage supplyVoltage, PantAllDown allDown, PantSwitchType switchType, PantsPreset presets pantographAir PantVolume volume, PantPress pressure, PantCompFlag compressorRunning, PantographCompressorStart compressorStart, SmallCompressorPower compressorPower, PantsValve valve, bPantKurek3 connectedToMainReservoir, PantAutoValve autoValve, PantPressSwitchActive / PantPressLockActive pressureSwitchActive / pressureLockActive No string literal changed (checked over all the changed files). No change in behaviour: 1149/1149 tests, golden traces exact against staging 62f7a29b. --- application/driverhints.cpp | 28 +-- application/driveruipanels.cpp | 18 +- input/messaging.cpp | 2 +- physics/components/devices.h | 220 ++++++++++++++++++ physics/components/drive.cpp | 2 +- physics/components/electrics.cpp | 76 +++---- physics/components/fizsections.cpp | 18 +- physics/components/pantographs.h | 50 +++++ physics/vehicle.h | 222 +------------------ simulation/blackboxrecorder.cpp | 2 +- tests/unit/drive.cpp | 14 +- tests/unit/golden.cpp | 2 +- tests/unit/test_auxiliaries.cpp | 34 +-- tests/unit/test_commands.cpp | 16 +- tests/unit/test_door_wings.cpp | 2 +- tests/unit/test_genset.cpp | 18 +- tests/unit/test_loads.cpp | 4 +- tests/unit/test_mains_before_pantographs.cpp | 44 ++-- tests/unit/test_pressure_switch.cpp | 40 ++-- tests/unit/vehicle.cpp | 8 +- vehicle/ai/engine.cpp | 22 +- vehicle/ai/situation.cpp | 26 +-- vehicle/cab/pantographcommands.cpp | 46 ++-- vehicle/cab/setup.cpp | 22 +- vehicle/cab/train.cpp | 8 +- vehicle/cab/update.cpp | 6 +- vehicle/doorwings.h | 2 +- vehicle/dynamic/lifecycle.cpp | 4 +- vehicle/dynamic/sounds.cpp | 4 +- vehicle/dynamic/update.cpp | 82 +++---- vehicle/dynamic/vehicletable.cpp | 2 +- widgets/vehicleparams.cpp | 10 +- 32 files changed, 556 insertions(+), 498 deletions(-) create mode 100644 physics/components/devices.h create mode 100644 physics/components/pantographs.h diff --git a/application/driverhints.cpp b/application/driverhints.cpp index e41b12a39..ecd311e9e 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -224,46 +224,46 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // pantographs case driver_hint::pantographairsourcesetmain: { if( AIControllFlag ) { - pantographUnit->bPantKurek3 = true; + pantographUnit->pantographAir.connectedToMainReservoir = true; } remove_hint( driver_hint::pantographairsourcesetauxiliary ); hint( Action, [this](float const /*Parameter*/) { - return pantographUnit->bPantKurek3 == true; } ); + return pantographUnit->pantographAir.connectedToMainReservoir == true; } ); break; } case driver_hint::pantographairsourcesetauxiliary: { if( AIControllFlag ) { - pantographUnit->bPantKurek3 = false; + pantographUnit->pantographAir.connectedToMainReservoir = false; } remove_hint( driver_hint::pantographcompressoron ); hint( Action, [this](float const /*Parameter*/) { - return pantographUnit->bPantKurek3 == false; } ); + return pantographUnit->pantographAir.connectedToMainReservoir == false; } ); break; } case driver_hint::pantographcompressoron: { if( AIControllFlag ) { - pantographUnit->PantCompFlag = true; + pantographUnit->pantographAir.compressorRunning = true; } remove_hint( driver_hint::pantographcompressoroff ); hint( Action, [this](float const /*Parameter*/) { - return pantographUnit->PantCompFlag == true; } ); + return pantographUnit->pantographAir.compressorRunning == true; } ); break; } case driver_hint::pantographcompressoroff: { if( AIControllFlag ) { - pantographUnit->PantCompFlag = false; + pantographUnit->pantographAir.compressorRunning = false; } remove_hint( driver_hint::pantographcompressoron ); hint( Action, [this](float const /*Parameter*/) { - return pantographUnit->PantCompFlag == false; } ); + return pantographUnit->pantographAir.compressorRunning == false; } ); break; } case driver_hint::pantographsvalveon: { @@ -274,7 +274,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return pantographUnit->PantsValve.is_active == true; } ); + return pantographUnit->pantographAir.valve.is_active == true; } ); break; } case driver_hint::frontpantographvalveon: { @@ -285,7 +285,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [ this ]( float const Parameter ) { - return pantographUnit->Pantographs[VehicleEnd::front].valve.is_active == true || (Parameter > 0 && occupied->Vel > Parameter); }, + return pantographUnit->pantographs[VehicleEnd::front].valve.is_active == true || (Parameter > 0 && occupied->Vel > Parameter); }, Actionparameter ); break; } @@ -297,7 +297,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return pantographUnit->Pantographs[VehicleEnd::front].valve.is_active == false; } ); + return pantographUnit->pantographs[VehicleEnd::front].valve.is_active == false; } ); break; } case driver_hint::rearpantographvalveon: { @@ -308,7 +308,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [ this ]( float const Parameter ) { - return pantographUnit->Pantographs[VehicleEnd::rear].valve.is_active == true || (Parameter > 0 && occupied->Vel > Parameter); }, + return pantographUnit->pantographs[VehicleEnd::rear].valve.is_active == true || (Parameter > 0 && occupied->Vel > Parameter); }, Actionparameter ); break; } @@ -320,7 +320,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return pantographUnit->Pantographs[VehicleEnd::rear].valve.is_active == false; } ); + return pantographUnit->pantographs[VehicleEnd::rear].valve.is_active == false; } ); break; } // converter @@ -760,7 +760,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return pantographUnit->PantPress >= (is_emu() ? (pantographUnit->PantPressLockActive ? 4.6 : 2.6) : 4.2); } ); + return pantographUnit->pantographAir.pressure >= (is_emu() ? (pantographUnit->pantographAir.pressureLockActive ? 4.6 : 2.6) : 4.2); } ); break; } case driver_hint::waitbrakecharge: { diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 7c956f019..21cfa1030 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -817,15 +817,15 @@ debug_panel::update_section_vehicle( std::vector &Output ) { STR_C("Devices: %c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%s%s\nPower transfers: %.0f@%.0f%s[%.0f]%s%.0f@%.0f :: %.0f@%.0f%s[%.0f]%s%.0f@%.0f"), // devices physics.Battery ? 'B' : '.', - physics.PantsValve.is_active ? '+' : '.', - physics.Pantographs[VehicleEnd::rear].valve.is_active ? 'O' : - physics.Pantographs[VehicleEnd::rear].valve.is_enabled ? 'o' : + physics.pantographAir.valve.is_active ? '+' : '.', + physics.pantographs[VehicleEnd::rear].valve.is_active ? 'O' : + physics.pantographs[VehicleEnd::rear].valve.is_enabled ? 'o' : '.', - physics.Pantographs[VehicleEnd::front].valve.is_active ? 'P' : - physics.Pantographs[VehicleEnd::front].valve.is_enabled ? 'p' : + physics.pantographs[VehicleEnd::front].valve.is_active ? 'P' : + physics.pantographs[VehicleEnd::front].valve.is_enabled ? 'p' : '.', - physics.PantPressLockActive ? '!' : - physics.PantPressSwitchActive ? '*' : + physics.pantographAir.pressureLockActive ? '!' : + physics.pantographAir.pressureSwitchActive ? '*' : '.', physics.WaterPump.is_active ? 'W' : false == physics.WaterPump.breaker ? '-' : @@ -951,8 +951,8 @@ debug_panel::update_section_vehicle( std::vector &Output ) { std::snprintf( m_buffer.data(), m_buffer.size(), STR_C(" pantograph: %.2f%cMT"), - physics.PantPress, - physics.bPantKurek3 ? '-' : '|' ); + physics.pantographAir.pressure, + physics.pantographAir.connectedToMainReservoir ? '-' : '|' ); textline += m_buffer.data(); } diff --git a/input/messaging.cpp b/input/messaging.cpp index f39f20962..c7950c737 100644 --- a/input/messaging.cpp +++ b/input/messaging.cpp @@ -329,7 +329,7 @@ WyslijNamiary([[maybe_unused]] TDynamicObject const *Vehicle) Vehicle->physics->ShowCurrent(p + 1); // amperomierze kolejnych grup // WriteLog("zapisalem prady"); r.iPar[30] = Vehicle->physics->WarningSignal; // trabienie - r.fPar[31] = Vehicle->physics->PantographVoltage; // napiecie WN + r.fPar[31] = Vehicle->physics->pantographCircuit.supplyVoltage; // napiecie WN // WriteLog("Parametry gotowe"); i <<= 2; // ilość bajtów r.cString[i] = char(j); // na końcu nazwa, żeby jakoś zidentyfikować diff --git a/physics/components/devices.h b/physics/components/devices.h new file mode 100644 index 000000000..4b225a27e --- /dev/null +++ b/physics/components/devices.h @@ -0,0 +1,220 @@ +/* +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 devices of a vehicle: pumps, fans, valves, pantographs, doors, the genset (nested in physics::Vehicle before) + +#pragma once + +#include +#include + +#include "physics/vehicletypes.h" + +namespace physics +{ + +/* TODO: implement + // communication cable, exchanging control signals with adjacent vehicle + struct jumper_cable { + // types + using flag_pair = std::pair; + // members + // booleans + // std::array flags {}; + // boolean pairs, exchanged data is swapped when connected to a matching end (front to front or back to back) + // TBD, TODO: convert to regular bool array for efficiency once it's working? + std::array flag_pairs {}; + // integers + // std::array values {}; + }; +*/ +// basic approximation of a generic device +// TBD: inheritance or composition? +struct basic_device +{ + // config + start_t start_type{start_t::manual}; + // ld inputs + bool is_enabled{false}; // device is allowed/requested to operate + bool is_disabled{false}; // device is requested to stop + // TODO: add remaining inputs; start conditions and potential breakers + // ld outputs + bool is_active{false}; // device is working +}; + +struct basic_light : public basic_device +{ + // config + float dimming{1.0f}; // light strength multiplier + // ld outputs + float intensity{0.0f}; // current light strength +}; + +struct cooling_fan : public basic_device +{ + // config + float speed{0.f}; // cooling fan rpm; either fraction of parent rpm, or absolute value if negative + float sustain_time{0.f}; // time of sustaining work of cooling fans after stop + float min_start_velocity{-1.f}; // minimal velocity of vehicle, when cooling fans activate + // ld outputs + float revolutions{0.f}; // current fan rpm + float stop_timer{0.f}; // current time, when shut off condition is active +}; + +// basic approximation of a fuel pump +struct fuel_pump : public basic_device +{ + // TODO: fuel consumption, optional automatic engine start after activation +}; + +// basic approximation of an oil pump +struct oil_pump : public basic_device +{ + // config + float pressure_minimum{0.f}; // lowest acceptable working pressure + float pressure_maximum{0.65f}; // oil pressure at maximum engine revolutions + // ld inputs + float resource_amount{1.f}; // amount of affected resource, compared to nominal value + // internal data + float pressure_target{0.f}; + // ld outputs + float pressure{0.f}; // current pressure +}; + +// the diesel generator set of a dual-mode vehicle: a second source of the traction circuit, next to the +// pantographs (eu07/maszyna#536). none unless the .fiz gives GensetPower +struct genset_device : public basic_device +{ + // config (Power: Genset*), revolutions in rev/s, the .fiz gives rpm + double power{0.0}; // GensetPower, electric output at full revolutions [kW]; 0 = no genset + double voltage_nominal{0.0}; // GensetVoltage, regulated DC voltage from the idle revolutions up [V] + double revolutions_idle{0.0}; // GensetIdleRPM + double revolutions_max{0.0}; // GensetMaxRPM + double start_time{8.0}; // GensetStartTime, from the start request to running at idle [s] + double spinup_time{3.0}; // GensetSpinUpTime, time constant of the revolutions [s] + double traction_share{1.0}; // GensetPmaxRatio, part of the power the traction may take + // state + double timer{0.0}; // of the start [s] + bool is_cranking{false}; + // ld outputs + double revolutions{0.0}; // [rev/s] + double voltage{0.0}; // [V] + bool fitted() const { return power > 0.0; } + // the power the genset gives at its present revolutions [kW] + double available_power() const { return revolutions_max > 0.0 ? power * std::clamp(revolutions / revolutions_max, 0.0, 1.0) : 0.0; } +}; +// basic approximation of a water pump +struct water_pump : public basic_device +{ + // ld inputs + // TODO: move to breaker list in the basic device once implemented + bool breaker{false}; // device is allowed to operate +}; + +// basic approximation of a solenoid valve +struct basic_valve : basic_device +{ + // config + bool solenoid{true}; // requires electric power to operate + bool spring{true}; // spring return or double acting actuator +}; + +// basic approximation of a pantograph +struct basic_pantograph +{ + // ld inputs + basic_valve valve; // associated pneumatic valve + // ld outputs + bool is_active{false}; // device is working + bool sound_event{false}; // indicates last state which generated sound event + double voltage{0.0}; +}; + +// basic approximation of doors +struct basic_door +{ + // config + // ld inputs + bool open_permit{false}; // door can be opened + bool local_open{false}; // local attempt to open the door + bool local_close{false}; // local attempt to close the door + bool remote_open{false}; // received remote signal to open the door + bool remote_close{false}; // received remote signal to close the door + // internal data + float auto_timer{-1.f}; // delay between activation of open state and closing state for automatic doors + float close_delay{0.f}; // delay between activation of closing state and actual closing + float open_delay{0.f}; // delay between activation of opening state and actual opening + float position{0.f}; // current shift of the door from the closed position + float step_position{0.f}; // current shift of the movable step from the retracted position + // ld outputs + bool is_closed{true}; // the door is fully closed + bool is_door_closed{true}; // the door is fully closed, step doesn't matter + bool is_closing{false}; // the door is currently closing + bool is_opening{false}; // the door is currently opening + bool is_open{false}; // the door is fully open + bool step_folding{false}; // the doorstep is currently closing + bool step_unfolding{false}; // the doorstep is currently opening +}; + +struct door_data +{ + // config + control_t open_control{control_t::passenger}; + float open_rate{1.f}; + float open_delay{0.f}; + control_t close_control{control_t::passenger}; + float close_rate{1.f}; + float close_delay{0.f}; + int type{2}; + float range{0.f}; // extent of primary move/rotation + float range_out{0.f}; // extent of shift outward, applicable for plug doors + int step_type{2}; + float step_rate{0.5f}; + float step_range{0.f}; + bool has_lock{false}; + bool has_warning{false}; + bool has_autowarning{false}; + float auto_duration{-1.f}; // automatic door closure delay period + float auto_velocity{-1.f}; // automatic door closure velocity threshold + bool auto_include_remote{false}; // automatic door closure applies also to remote control + bool permit_needed{false}; + bool closure_signal{false}; // the door closure lamp (SOD) of the cab signals the doors of the whole consist in three states + std::vector permit_presets; // permit presets selectable with preset switch + float voltage{0.f}; // power type required for door movement + // ld inputs + bool lock_enabled{true}; + bool step_enabled{true}; + bool remote_only{false}; // door ignores local control signals + // internal data + int permit_preset{-1}; // curent position of preset selection switch + // vehicle parts + BySide instances; // door on the right and left side of the vehicle + // ld outputs + bool is_locked{false}; + double doorLockSpeed = 10.0; // predkosc przy ktorej wyzwalana jest blokada drzwi +}; + +struct water_heater +{ + // config + struct heater_config_t + { + float temp_min{-1}; // lowest accepted temperature + float temp_max{-1}; // highest accepted temperature + }; + heater_config_t config; + // ld inputs + bool breaker{false}; // device is allowed to operate + bool is_enabled{false}; // device is requested to operate + // ld outputs + bool is_active{false}; // device is working + bool is_damaged{false}; // device is damaged +}; + +} // namespace physics diff --git a/physics/components/drive.cpp b/physics/components/drive.cpp index c1f64738e..b58e97963 100644 --- a/physics/components/drive.cpp +++ b/physics/components/drive.cpp @@ -259,7 +259,7 @@ public: void CheckVoltageRelays(physics::Vehicle &vehicle) const override { // update the state of voltage relays - auto const voltage{std::max(vehicle.GetTrainsetHighVoltage(), vehicle.PantographVoltage)}; + auto const voltage{std::max(vehicle.GetTrainsetHighVoltage(), vehicle.pantographCircuit.supplyVoltage)}; // where the line breaker holds without voltage (closed ahead of the pantographs) the undervoltage relay opens the // line contactors instead, see MotorConnectorsCheck(). it picks up again only with the master controller back // where a start begins, as the line breaker it stands in for wouldn't close on a running position either: at diff --git a/physics/components/electrics.cpp b/physics/components/electrics.cpp index c33e2e0c8..7e050f4f1 100644 --- a/physics/components/electrics.cpp +++ b/physics/components/electrics.cpp @@ -37,11 +37,11 @@ void physics::Vehicle::UpdatePantVolume(double dt) // check the pantograph compressor while at it // TODO: move the check to a separate method // automatic start if the pressure is too low - PantCompFlag |= PantPress < 4.2 && true == (Pantographs[VehicleEnd::front].is_active | Pantographs[VehicleEnd::rear].is_active) // TODO: any_pantograph_is_active method - && (PantographCompressorStart == start_t::automatic || PantographCompressorStart == start_t::manualwithautofallback); + pantographAir.compressorRunning |= pantographAir.pressure < 4.2 && true == (pantographs[VehicleEnd::front].is_active | pantographs[VehicleEnd::rear].is_active) // TODO: any_pantograph_is_active method + && (pantographAir.compressorStart == start_t::automatic || pantographAir.compressorStart == start_t::manualwithautofallback); auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; - PantCompFlag &= lowvoltagepower; + pantographAir.compressorRunning &= lowvoltagepower; if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector // tylko jeśli pantografujący && EnginePowerSource.CollectorParameters.CollectorsNo > 0) @@ -50,33 +50,33 @@ void physics::Vehicle::UpdatePantVolume(double dt) // Ra 2014-07: kurek trójdrogowy łączy spr.pom. z pantografami i wyłącznikiem ciśnieniowym WS // Ra 2014-07: zbiornika rozrządu nie pompuje się tu, tylko pantografy; potem można zamknąć // WS i odpalić resztę - if (PantAutoValve ? PantPress < mainPipe.pressure : bPantKurek3) // kurek zamyka połączenie z ZG + if (pantographAir.autoValve ? pantographAir.pressure < mainPipe.pressure : pantographAir.connectedToMainReservoir) // kurek zamyka połączenie z ZG { // zbiornik pantografu połączony ze zbiornikiem głównym - małą sprężarką się tego nie napompuje // Ra 2013-12: Niebugocław mówi, że w EZT nie ma potrzeby odcinać kurkiem - PantPress = mainPipe.pressure; + pantographAir.pressure = mainPipe.pressure; // ograniczenie ciśnienia do MaxPress (tylko w pantografach!) - PantPress = safe_clamp(mainPipe.pressure, 0.0, EnginePowerSource.CollectorParameters.MaxPress); - PantVolume = (PantPress + 1.0) * 0.1; // objętość, na wypadek odcięcia kurkiem + pantographAir.pressure = safe_clamp(mainPipe.pressure, 0.0, EnginePowerSource.CollectorParameters.MaxPress); + pantographAir.volume = (pantographAir.pressure + 1.0) * 0.1; // objętość, na wypadek odcięcia kurkiem } else { // zbiornik główny odcięty, można pompować pantografy - if (PantCompFlag) + if (pantographAir.compressorRunning) { // włączona mała sprężarka - PantVolume += dt + pantographAir.volume += dt // Ra 2013-12: Niebugocław mówi, że w EZT nabija 1.5 raz wolniej niż jak było 0.005 - * (TrainType == train_type::emu ? 0.003 : 0.005) / std::max(1.0, PantPress) * (0.45 - (0.1 / PantVolume / 10 - 0.1)) / 0.45; + * (TrainType == train_type::emu ? 0.003 : 0.005) / std::max(1.0, pantographAir.pressure) * (0.45 - (0.1 / pantographAir.volume / 10 - 0.1)) / 0.45; } - PantPress = safe_clamp(10.0 * PantVolume - 1.0, 0.0, EnginePowerSource.CollectorParameters.MaxPress); // tu by się przydała objętość zbiornika + pantographAir.pressure = safe_clamp(10.0 * pantographAir.volume - 1.0, 0.0, EnginePowerSource.CollectorParameters.MaxPress); // tu by się przydała objętość zbiornika } - if (!PantCompFlag && PantVolume > 0.1) - PantVolume -= dt * 0.0003 * std::max(1.0, PantPress * 0.5); // nieszczelności: 0.0003=0.3l/s + if (!pantographAir.compressorRunning && pantographAir.volume > 0.1) + pantographAir.volume -= dt * 0.0003 * std::max(1.0, pantographAir.pressure * 0.5); // nieszczelności: 0.0003=0.3l/s PantPressureSwitchCheck(); } else { // a tu coś dla SM42 i SM31, aby pokazywać na manometrze - PantPress = brakes.controlReservoirPressure; + pantographAir.pressure = brakes.controlReservoirPressure; } }; @@ -84,31 +84,31 @@ void physics::Vehicle::UpdatePantVolume(double dt) // primed again over 4.6 bar, where the pantographs' compressor stops at 4.8 void physics::Vehicle::PantPressureSwitchCheck() { - if (PantPress < EnginePowerSource.CollectorParameters.MinPress) + if (pantographAir.pressure < EnginePowerSource.CollectorParameters.MinPress) { // 3.5 wg http://www.transportszynowy.pl/eu06-07pneumat.php - if (true == PantPressSwitchActive) + if (true == pantographAir.pressureSwitchActive) { PantPressureSwitchTrip(); } } - else if (PantPress >= 4.6) + else if (pantographAir.pressure >= 4.6) { // NOTE: we require active low power source to prime the pressure switch // this is a work-around for potential isssues caused by the switch activating on otherwise idle vehicles, but should check whether it's accurate if (true == Power24vIsAvailable || true == Power110vIsAvailable) { // prime the pressure switch - PantPressSwitchActive = true; + pantographAir.pressureSwitchActive = true; // turn off the subsystems lock - PantPressLockActive = false; + pantographAir.pressureLockActive = false; } - if (PantPress >= 4.8) + if (pantographAir.pressure >= 4.8) { // Winger - automatyczne wylaczanie malej sprezarki // TODO: governor lock, disables usage until pressure drop below 3.8 (should really make compressor object we could reuse) - PantCompFlag = false; + pantographAir.compressorRunning = false; } } } @@ -132,12 +132,12 @@ void physics::Vehicle::PantPressureSwitchTrip() { // specialized variant for EMU -- pwr system disables converter and heating, // and prevents their activation until pressure switch is set again - PantPressLockActive = true; + pantographAir.pressureLockActive = true; // TODO: separate 'heating allowed' from actual heating flag, so we can disable it here without messing up heating toggle ConverterSwitch(false, range_t::unit); } // mark the pressure switch as spent - PantPressSwitchActive = false; + pantographAir.pressureSwitchActive = false; } void physics::Vehicle::UpdateBatteryVoltage(double dt) @@ -223,7 +223,7 @@ double physics::Vehicle::BatteryDrainLow(double dt, bool const converteractive) double sn3; double sn4; double sn5; - if (PantCompFlag) + if (pantographAir.compressorRunning) sn1 = dt * 0.0046; else sn1 = 0; @@ -276,7 +276,7 @@ void physics::Vehicle::MainsCheck(double const Deltatime) { case TPowerSource::CurrentCollector: { - localvoltage = std::max(localvoltage, PantographVoltage); + localvoltage = std::max(localvoltage, pantographCircuit.supplyVoltage); break; } case TPowerSource::Accumulator: @@ -405,7 +405,7 @@ double physics::Vehicle::LocalPowerVoltage(Coupling const kind) } case TPowerSource::CurrentCollector: { - localvoltage = PantographVoltage; + localvoltage = pantographCircuit.supplyVoltage; break; } case TPowerSource::Main: @@ -620,7 +620,7 @@ void physics::Vehicle::ConverterCheck(double const Timestep) } if (ConverterAllow && ConverterAllowLocal && false == ConvOvldFlag && - false == PantPressLockActive + false == pantographAir.pressureLockActive // HACK: allow carriages to operate converter without (missing) fuse prerequisite && (Power > 1.0 ? MainCircuitPowered() : GetTrainsetHighVoltage() > 0.0)) { @@ -694,7 +694,7 @@ void physics::Vehicle::HeatingCheck(double const /*Timestep*/) } case TPowerSource::CurrentCollector: { - voltage = PantographVoltage; + voltage = pantographCircuit.supplyVoltage; break; } case TPowerSource::PowerCable: @@ -730,12 +730,12 @@ void physics::Vehicle::PantographsCheck(double const /*Timestep*/) using enum start_t; { - auto const &valve{PantsValve}; + auto const &valve{pantographAir.valve}; auto const lowvoltagepower{valve.solenoid ? Power24vIsAvailable || Power110vIsAvailable : true}; auto const autostart{valve.start_type == automatic || valve.start_type == manualwithautofallback}; auto const manualcontrol{valve.start_type == manual || valve.start_type == manualwithautofallback}; - PantsValve.is_active = (valve.spring ? lowvoltagepower : true) // spring actuator needs power to maintain non-default state + pantographAir.valve.is_active = (valve.spring ? lowvoltagepower : true) // spring actuator needs power to maintain non-default state && (manualcontrol && lowvoltagepower ? false == valve.is_disabled : true) // needs power to change state && (valve.is_active || (autostart ? lowvoltagepower : !autostart ? lowvoltagepower && valve.is_enabled : @@ -743,7 +743,7 @@ void physics::Vehicle::PantographsCheck(double const /*Timestep*/) } size_t pant_id = 0; - for (auto &pantograph : Pantographs) + for (auto &pantograph : pantographs) { auto &valve{pantograph.valve}; @@ -753,13 +753,13 @@ void physics::Vehicle::PantographsCheck(double const /*Timestep*/) valve.is_active = (valve.spring ? lowvoltagepower : true) // spring actuator needs power to maintain non-default state && (manualcontrol && lowvoltagepower ? false == valve.is_disabled : true) // needs power to change state, without it just pass through - && (manualcontrol && lowvoltagepower ? false == PantAllDown : true) && + && (manualcontrol && lowvoltagepower ? false == pantographCircuit.allDown : true) && (Mains || false == PantographsRequireMains) // fed through the closed line breaker, where it comes first && (valve.is_active || (manualcontrol && lowvoltagepower && valve.is_enabled) || (autostart && lowvoltagepower)); // shouldn't ever get this far but, eh auto const pantographexists{EnginePowerSource.SourceType == TPowerSource::CurrentCollector && EnginePowerSource.CollectorParameters.PhysicalLayout & 1 << pant_id}; - pantograph.is_active = valve.is_active && PantsValve.is_active && pantographexists; + pantograph.is_active = valve.is_active && pantographAir.valve.is_active && pantographexists; pant_id++; } @@ -1069,7 +1069,7 @@ bool physics::Vehicle::GensetSwitch(bool const State, range_t const Notify) // genset of a dual-mode vehicle double physics::Vehicle::TractionSourceVoltage() const { - return GensetSelected() ? Genset.voltage : PantographVoltage; + return GensetSelected() ? Genset.voltage : pantographCircuit.supplyVoltage; } // the voltage the traction circuit gets: from the vehicle's own source, or through the train's high voltage line @@ -1137,7 +1137,7 @@ bool physics::Vehicle::OperatePantographsValve(operation_t const State, range_t if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector && EnginePowerSource.CollectorParameters.CollectorsNo > 0) { - auto &valve{PantsValve}; + auto &valve{pantographAir.valve}; switch (State) { @@ -1197,7 +1197,7 @@ bool physics::Vehicle::OperatePantographValve(VehicleEnd const End, operation_t if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector && EnginePowerSource.CollectorParameters.CollectorsNo > 0) { - auto &valve{Pantographs[End].valve}; + auto &valve{pantographs[End].valve}; switch (State) { @@ -1258,9 +1258,9 @@ bool physics::Vehicle::OperatePantographValve(VehicleEnd const End, operation_t bool physics::Vehicle::DropAllPantographs(bool const State, range_t const Notify) { - auto const initialstate{PantAllDown}; + auto const initialstate{pantographCircuit.allDown}; - PantAllDown = State; + pantographCircuit.allDown = State; if (Notify != range_t::local) { diff --git a/physics/components/fizsections.cpp b/physics/components/fizsections.cpp index 8eff86951..35d561f23 100644 --- a/physics/components/fizsections.cpp +++ b/physics/components/fizsections.cpp @@ -938,16 +938,16 @@ void physics::Vehicle::LoadFIZ_CntrlStarts(std::string const &line) // pantograph compressor { auto lookup = starts.find(extract_value("PantCompressorStart", line)); - PantographCompressorStart = lookup != starts.end() ? lookup->second : manual; + pantographAir.compressorStart = lookup != starts.end() ? lookup->second : manual; } // pantograph compressor valve - PantAutoValve = TrainType == train_type::emu; // legacy code behaviour, automatic valve was initially installed in all EMUs - extract_value(PantAutoValve, "PantAutoValve", line, ""); + pantographAir.autoValve = TrainType == train_type::emu; // legacy code behaviour, automatic valve was initially installed in all EMUs + extract_value(pantographAir.autoValve, "PantAutoValve", line, ""); // pantographs valve { auto lookup = starts.find(extract_value("PantEPValveStart", line)); - PantsValve.start_type = lookup != starts.end() ? lookup->second : automatic; // legacy code behaviour, there was no pantographs valve - extract_value(PantsValve.spring, "PantEPValveSpring", line, ""); + pantographAir.valve.start_type = lookup != starts.end() ? lookup->second : automatic; // legacy code behaviour, there was no pantographs valve + extract_value(pantographAir.valve.spring, "PantEPValveSpring", line, ""); } // pantograph valve configuration { @@ -957,7 +957,7 @@ void physics::Vehicle::LoadFIZ_CntrlStarts(std::string const &line) extract_value(valvespring, "PantValveSpring", line, ""); auto valvesolenoid{true}; extract_value(valvesolenoid, "PantValveSolenoid", line, ""); - for (auto &pantograph : Pantographs) + for (auto &pantograph : pantographs) { pantograph.valve.spring = valvespring; pantograph.valve.solenoid = valvesolenoid; @@ -1468,12 +1468,12 @@ void physics::Vehicle::LoadFIZ_EngineDieselShared(std::string const &Input) void physics::Vehicle::LoadFIZ_Switches(std::string const &Input) { - extract_value(PantSwitchType, "Pantograph", Input, ""); + extract_value(pantographCircuit.switchType, "Pantograph", Input, ""); extract_value(ConvSwitchType, "Converter", Input, ""); extract_value(StLinSwitchType, "MotorConnectors", Input, ""); HeatingSwitchImpulse = ToLower(extract_value("TrainHeating", Input)) == "impulse"; // because people can't make up their minds whether it's "impulse" or "Impulse"... - PantSwitchType = ToLower(PantSwitchType); + pantographCircuit.switchType = ToLower(pantographCircuit.switchType); ConvSwitchType = ToLower(ConvSwitchType); StLinSwitchType = ToLower(StLinSwitchType); // universal reset buttons assignments @@ -1483,7 +1483,7 @@ void physics::Vehicle::LoadFIZ_Switches(std::string const &Input) extract_value(enableModernDimmer, "ModernDimmer", Input, ""); // pantograph presets { - auto &presets{PantsPreset.first}; + auto &presets{pantographCircuit.presets.first}; extract_value(presets, "PantographPresets", Input, "0|1|3|2"); std::erase(presets, '|'); } diff --git a/physics/components/pantographs.h b/physics/components/pantographs.h new file mode 100644 index 000000000..e4ee98505 --- /dev/null +++ b/physics/components/pantographs.h @@ -0,0 +1,50 @@ +/* +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 circuit and the air of the pantographs of a vehicle, held by physics::Vehicle as pantographCircuit and +// pantographAir beside its pantographs + +#pragma once + +#include +#include + +#include "physics/components/devices.h" + +namespace physics +{ + +// the circuit of the pantographs: their voltages, the kind of their switches, the presets of the cabs +struct PantographCircuit +{ + double frontVoltage = 0.0; // the voltage at the front pantograph + double rearVoltage = 0.0; // the voltage at the rear one + double supplyVoltage{0.0}; // the voltage supplied to the pantographs + bool allDown{false}; // the switch that lowers all of them + std::string switchType; // PantSwitchType: the kind of the switches of the cab + // the presets of the pantographs: the setups they can be switched to as chars, and the one selected in each cab + std::pair> presets{"0132", {0, 0}}; +}; + +// the air of the pantographs: their reservoir, the small compressor that fills it, the valves +struct PantographAir +{ + double volume = 0.48; // so that the raised pantographs drop soon with the compressor off + double pressure = 0.0; // in the reservoirs of the pantographs + bool compressorRunning = false; // the small compressor + start_t compressorStart{start_t::manual}; // PantCompressorStart + int compressorPower = 0; // SmallCompressorPower + basic_valve valve; + bool connectedToMainReservoir = true; // the three-way cock: to the main reservoir, or to the small compressor + bool autoValve{false}; // the kind of the valve of the small compressor fitted + bool pressureSwitchActive{false}; // the pressure switch, primed at the pressure set in the air of the pantographs + bool pressureLockActive{false}; // fires when the pressure switch trips by the pressure dropping below its level +}; + +} // namespace physics diff --git a/physics/vehicle.h b/physics/vehicle.h index b1016e644..183e55b9e 100644 --- a/physics/vehicle.h +++ b/physics/vehicle.h @@ -26,6 +26,8 @@ http://mozilla.org/MPL/2.0/. #include "physics/components/inductionmotor.h" #include "physics/components/braking.h" #include "physics/components/airsupply.h" +#include "physics/components/devices.h" +#include "physics/components/pantographs.h" class TractionDrive; @@ -615,206 +617,6 @@ namespace physics class Vehicle { // Ra: wrapper na kod pascalowy, przejmujący jego funkcje Q: 20160824 - juz nie wrapper a klasa bazowa :) - private: - // types - /* TODO: implement - // communication cable, exchanging control signals with adjacent vehicle - struct jumper_cable { - // types - using flag_pair = std::pair; - // members - // booleans - // std::array flags {}; - // boolean pairs, exchanged data is swapped when connected to a matching end (front to front or back to back) - // TBD, TODO: convert to regular bool array for efficiency once it's working? - std::array flag_pairs {}; - // integers - // std::array values {}; - }; - */ - // basic approximation of a generic device - // TBD: inheritance or composition? - struct basic_device - { - // config - start_t start_type{start_t::manual}; - // ld inputs - bool is_enabled{false}; // device is allowed/requested to operate - bool is_disabled{false}; // device is requested to stop - // TODO: add remaining inputs; start conditions and potential breakers - // ld outputs - bool is_active{false}; // device is working - }; - - struct basic_light : public basic_device - { - // config - float dimming{1.0f}; // light strength multiplier - // ld outputs - float intensity{0.0f}; // current light strength - }; - - struct cooling_fan : public basic_device - { - // config - float speed{0.f}; // cooling fan rpm; either fraction of parent rpm, or absolute value if negative - float sustain_time{0.f}; // time of sustaining work of cooling fans after stop - float min_start_velocity{-1.f}; // minimal velocity of vehicle, when cooling fans activate - // ld outputs - float revolutions{0.f}; // current fan rpm - float stop_timer{0.f}; // current time, when shut off condition is active - }; - - // basic approximation of a fuel pump - struct fuel_pump : public basic_device - { - // TODO: fuel consumption, optional automatic engine start after activation - }; - - // basic approximation of an oil pump - struct oil_pump : public basic_device - { - // config - float pressure_minimum{0.f}; // lowest acceptable working pressure - float pressure_maximum{0.65f}; // oil pressure at maximum engine revolutions - // ld inputs - float resource_amount{1.f}; // amount of affected resource, compared to nominal value - // internal data - float pressure_target{0.f}; - // ld outputs - float pressure{0.f}; // current pressure - }; - - // the diesel generator set of a dual-mode vehicle: a second source of the traction circuit, next to the - // pantographs (eu07/maszyna#536). none unless the .fiz gives GensetPower - struct genset_device : public basic_device - { - // config (Power: Genset*), revolutions in rev/s, the .fiz gives rpm - double power{0.0}; // GensetPower, electric output at full revolutions [kW]; 0 = no genset - double voltage_nominal{0.0}; // GensetVoltage, regulated DC voltage from the idle revolutions up [V] - double revolutions_idle{0.0}; // GensetIdleRPM - double revolutions_max{0.0}; // GensetMaxRPM - double start_time{8.0}; // GensetStartTime, from the start request to running at idle [s] - double spinup_time{3.0}; // GensetSpinUpTime, time constant of the revolutions [s] - double traction_share{1.0}; // GensetPmaxRatio, part of the power the traction may take - // state - double timer{0.0}; // of the start [s] - bool is_cranking{false}; - // ld outputs - double revolutions{0.0}; // [rev/s] - double voltage{0.0}; // [V] - bool fitted() const { return power > 0.0; } - // the power the genset gives at its present revolutions [kW] - double available_power() const { return revolutions_max > 0.0 ? power * std::clamp(revolutions / revolutions_max, 0.0, 1.0) : 0.0; } - }; - // basic approximation of a water pump - struct water_pump : public basic_device - { - // ld inputs - // TODO: move to breaker list in the basic device once implemented - bool breaker{false}; // device is allowed to operate - }; - - // basic approximation of a solenoid valve - struct basic_valve : basic_device - { - // config - bool solenoid{true}; // requires electric power to operate - bool spring{true}; // spring return or double acting actuator - }; - - // basic approximation of a pantograph - struct basic_pantograph - { - // ld inputs - basic_valve valve; // associated pneumatic valve - // ld outputs - bool is_active{false}; // device is working - bool sound_event{false}; // indicates last state which generated sound event - double voltage{0.0}; - }; - - // basic approximation of doors - struct basic_door - { - // config - // ld inputs - bool open_permit{false}; // door can be opened - bool local_open{false}; // local attempt to open the door - bool local_close{false}; // local attempt to close the door - bool remote_open{false}; // received remote signal to open the door - bool remote_close{false}; // received remote signal to close the door - // internal data - float auto_timer{-1.f}; // delay between activation of open state and closing state for automatic doors - float close_delay{0.f}; // delay between activation of closing state and actual closing - float open_delay{0.f}; // delay between activation of opening state and actual opening - float position{0.f}; // current shift of the door from the closed position - float step_position{0.f}; // current shift of the movable step from the retracted position - // ld outputs - bool is_closed{true}; // the door is fully closed - bool is_door_closed{true}; // the door is fully closed, step doesn't matter - bool is_closing{false}; // the door is currently closing - bool is_opening{false}; // the door is currently opening - bool is_open{false}; // the door is fully open - bool step_folding{false}; // the doorstep is currently closing - bool step_unfolding{false}; // the doorstep is currently opening - }; - - struct door_data - { - // config - control_t open_control{control_t::passenger}; - float open_rate{1.f}; - float open_delay{0.f}; - control_t close_control{control_t::passenger}; - float close_rate{1.f}; - float close_delay{0.f}; - int type{2}; - float range{0.f}; // extent of primary move/rotation - float range_out{0.f}; // extent of shift outward, applicable for plug doors - int step_type{2}; - float step_rate{0.5f}; - float step_range{0.f}; - bool has_lock{false}; - bool has_warning{false}; - bool has_autowarning{false}; - float auto_duration{-1.f}; // automatic door closure delay period - float auto_velocity{-1.f}; // automatic door closure velocity threshold - bool auto_include_remote{false}; // automatic door closure applies also to remote control - bool permit_needed{false}; - bool closure_signal{false}; // the door closure lamp (SOD) of the cab signals the doors of the whole consist in three states - std::vector permit_presets; // permit presets selectable with preset switch - float voltage{0.f}; // power type required for door movement - // ld inputs - bool lock_enabled{true}; - bool step_enabled{true}; - bool remote_only{false}; // door ignores local control signals - // internal data - int permit_preset{-1}; // curent position of preset selection switch - // vehicle parts - BySide instances; // door on the right and left side of the vehicle - // ld outputs - bool is_locked{false}; - double doorLockSpeed = 10.0; // predkosc przy ktorej wyzwalana jest blokada drzwi - }; - - struct water_heater - { - // config - struct heater_config_t - { - float temp_min{-1}; // lowest accepted temperature - float temp_max{-1}; // highest accepted temperature - }; - heater_config_t config; - // ld inputs - bool breaker{false}; // device is allowed to operate - bool is_enabled{false}; // device is requested to operate - // ld outputs - bool is_active{false}; // device is working - bool is_damaged{false}; // device is damaged - }; - public: std::string chkPath; bool reload_FIZ(); @@ -878,6 +680,9 @@ class Vehicle int wiperSwitchPos = 0; // pozycja przelacznika wycieraczek double WiperAngle = {45.0}; // kat pracy wycieraczek + ByEnd pantographs; + PantographCircuit pantographCircuit; // their voltages, switches, presets (physics/components/pantographs.h) + PantographAir pantographAir; // their reservoir, the small compressor, the valves TrainPipe brakePipe; // the brake pipe along the train TrainPipe mainPipe; // the main reservoir pipe along the train AirSupply air; // the compressor and the main reservoir (physics/components/airsupply.h) @@ -925,7 +730,6 @@ class Vehicle // 5% steps of the 6Dg), one at once when moved to a raising or lowering position, then one each time its SpeedUp / SpeedDown // covers a step; 0 (the default) changes it continuously double UniCtrlValStep{0.0}; - std::pair> PantsPreset{"0132", {0, 0}}; // pantograph preset switches; .first holds possible setups as chars, .second holds currently selected preset in each cab /*-sekcja parametrow dla lokomotywy elektrycznej*/ TSchemeTable RList; /*lista rezystorow rozruchowych i polaczen silnikow, dla dizla: napelnienia*/ @@ -1013,7 +817,6 @@ class Vehicle double RVentSpeed{0.5}; // rozpedzanie sie wentylatora obr/s^2} double RVentMinI{50.0}; // przy jakim pradzie sie wylaczaja} bool RVentForceOn{false}; // forced activation switch - int SmallCompressorPower = 0; /*Winger ZROBIC*/ bool Trafo = false; /*pojazd wyposażony w transformator*/ // the diesel engine, its torque converter and its retarder (physics/components/dieselengine.h) @@ -1149,14 +952,6 @@ class Vehicle bool SandDoseAutoAllow = true; /*zezwolenie na automatyczne piaskowanie*/ double Sand = 0.0; /*ilosc piasku*/ /*! przyrosty cisnienia w kroku czasowym*/ - double PantVolume = 0.48; /*objetosc spr. powietrza w ukl. pantografu*/ // aby podniesione pantografy opadły w krótkim czasie przy wyłączonej sprężarce - bool PantCompFlag = false; /*!o czy wlaczona sprezarka pantografow*/ - start_t PantographCompressorStart{start_t::manual}; - basic_valve PantsValve; - ByEnd Pantographs; - bool PantAllDown{false}; - double PantFrontVolt = 0.0; // pantograf pod napieciem? 'Winger 160404 - double PantRearVolt = 0.0; // TODO converter parameters, for when we start cleaning up physics parameters start_t ConverterStart{start_t::manual}; // whether converter is started manually, or by other means float ConverterStartDelay{0.0f}; // delay (in seconds) before the converter is started, once its activation conditions are met @@ -1297,10 +1092,6 @@ class Vehicle double LouvresOpenPressure{5.0}; // main reservoir pressure [bar] at which the pneumatic louvres of the motor fans open (ET22) bool ResistorsFlag = false; /*!o jazda rezystorowa*/ double RventRot = 0.0; /*!s obroty wentylatorow rozruchowych*/ - double PantographVoltage{0.0}; // voltage supplied to pantographs - double PantPress = 0.0; /*Cisnienie w zbiornikach pantografow*/ - bool PantPressSwitchActive{false}; // state of the pantograph pressure switch. gets primed at defined pressure level in pantograph air system - bool PantPressLockActive{false}; // pwr system state flag. fires when pressure switch activates by pantograph pressure dropping below defined level // switches off if the power level drops below threshold, which opens the line breaker; with PantographsRequireMains // it opens the line contactors instead, and switches back on only with the master controller at zero or the first position bool NoVoltRelay{true}; @@ -1349,7 +1140,6 @@ class Vehicle double DoorRightOpenTimer{-1.0}; // right door closing timer for automatic door type #endif // TODO: move these switch types where they belong, cabin definition - std::string PantSwitchType; std::string ConvSwitchType; bool HeatingSwitchImpulse{false}; // the train heating switch springs back to its middle position std::string StLinSwitchType; @@ -1376,8 +1166,6 @@ class Vehicle double FrictConst2d = 0.0; double TotalMassxg = 0.0; /*TotalMass*g*/ - bool bPantKurek3 = true; // kurek trójdrogowy (pantografu): true=połączenie z ZG, false=połączenie z małą sprężarką // domyślnie zbiornik pantografu połączony jest ze zbiornikiem głównym - bool PantAutoValve{false}; // type of installed pantograph compressor valve int iProblem = 0; // flagi problemów z taborem, aby AI nie musiało porównywać; 0=może jechać ByEnd iLights; // bity zapalonych świateł tutaj, żeby dało się liczyć pobór prądu diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index e7821ddb6..3d95510c5 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -74,7 +74,7 @@ std::uint32_t devices_of(physics::Vehicle const &Occupied, physics::Vehicle cons namespace device = blackbox::cab_devices; auto const on{[](bool const State, std::uint32_t const Bit) { return State ? Bit : 0u; }}; return on(Occupied.Battery || Controlling.Battery, device::battery) | on(Controlling.Mains, device::main_breaker) | - on(Controlling.Pantographs[VehicleEnd::front].is_active, device::pantograph_front) | on(Controlling.Pantographs[VehicleEnd::rear].is_active, device::pantograph_rear) | + on(Controlling.pantographs[VehicleEnd::front].is_active, device::pantograph_front) | on(Controlling.pantographs[VehicleEnd::rear].is_active, device::pantograph_rear) | on(Controlling.ConverterFlag, device::converter) | on(Controlling.air.compressor.running, device::compressor) | on(Controlling.StLinFlag, device::line_contactors) | on(Controlling.FuseFlag, device::overload_relay) | on(Controlling.SandDose, device::sanding) | on(Occupied.WarningSignal != 0, device::horn) | on(false == Occupied.Doors.instances[VehicleSide::left].is_closed, device::doors_left) | diff --git a/tests/unit/drive.cpp b/tests/unit/drive.cpp index 08868a7a1..de9736557 100644 --- a/tests/unit/drive.cpp +++ b/tests/unit/drive.cpp @@ -108,14 +108,14 @@ void prepare_diesel(driven const &Driven) { // the pantographs' own air topped up by their compressor, and the pantographs raised void raise_pantographs(driven const &Driven) { auto &pantographs{Driven.pantographs}; - if (auto const enough{(pantographs.TrainType == train_type::emu ? 2.5 : 3.5) + 0.1}; pantographs.PantPress < enough) { - if (false == pantographs.PantAutoValve) { - pantographs.bPantKurek3 = false; // the pantographs on their own air + if (auto const enough{(pantographs.TrainType == train_type::emu ? 2.5 : 3.5) + 0.1}; pantographs.pantographAir.pressure < enough) { + if (false == pantographs.pantographAir.autoValve) { + pantographs.pantographAir.connectedToMainReservoir = false; // the pantographs on their own air } - pantographs.PantCompFlag = true; + pantographs.pantographAir.compressorRunning = true; } - else if (false == pantographs.bPantKurek3 || pantographs.PantPress <= pantographs.mainPipe.pressure) { - pantographs.PantCompFlag = false; + else if (false == pantographs.pantographAir.connectedToMainReservoir || pantographs.pantographAir.pressure <= pantographs.mainPipe.pressure) { + pantographs.pantographAir.compressorRunning = false; } Driven.cab.OperatePantographsValve(operation_t::enable); Driven.cab.OperatePantographValve(VehicleEnd::rear, operation_t::enable); @@ -184,7 +184,7 @@ bool start_up(driven Driven, track const &Track, double Seconds, trace *Trace) { if (collector) { raise_pantographs(Driven); } - if (false == collector || std::max(controlling.GetTrainsetHighVoltage(), controlling.PantographVoltage) > controlling.EnginePowerSource.CollectorParameters.MinV) { + if (false == collector || std::max(controlling.GetTrainsetHighVoltage(), controlling.pantographCircuit.supplyVoltage) > controlling.EnginePowerSource.CollectorParameters.MinV) { // a direction first, as in TController::PrepareDirection(): the relays reset only with one set for (int i = 0; i < 3 && cab.DirActive <= 0; ++i) { cab.DirectionForward(); diff --git a/tests/unit/golden.cpp b/tests/unit/golden.cpp index a011fb0a5..d668592c0 100644 --- a/tests/unit/golden.cpp +++ b/tests/unit/golden.cpp @@ -189,7 +189,7 @@ std::vector parameters() { {"Imax", [](auto const &M) { return M.Imax; }}, {"EIMCtrlType", [](auto const &M) { return M.EIMCtrlType; }}, {"Volume", [](auto const &M) { return M.brakes.reservoirAir; }}, - {"PantVolume", [](auto const &M) { return M.PantVolume; }}, + {"PantVolume", [](auto const &M) { return M.pantographAir.volume; }}, }; for (int i = 0; i < 5; ++i) { result.emplace_back(std::format("MaxBrakePress{}", i), [i](auto const &M) { return M.brakes.maxCylinderPressure[i]; }); diff --git a/tests/unit/test_auxiliaries.cpp b/tests/unit/test_auxiliaries.cpp index 4da5c1f51..66702750b 100644 --- a/tests/unit/test_auxiliaries.cpp +++ b/tests/unit/test_auxiliaries.cpp @@ -18,11 +18,11 @@ std::vector auxiliaries() { {"Battery", [](auto const &M) { return M.Battery ? 1.0 : 0.0; }}, {"ConverterFlag", [](auto const &M) { return M.ConverterFlag ? 1.0 : 0.0; }}, {"Power110vIsAvailable", [](auto const &M) { return M.Power110vIsAvailable ? 1.0 : 0.0; }}, - {"PantPress", [](auto const &M) { return M.PantPress; }}, - {"PantVolume", [](auto const &M) { return M.PantVolume; }}, - {"PantCompFlag", [](auto const &M) { return M.PantCompFlag ? 1.0 : 0.0; }}, - {"PantPressSwitchActive", [](auto const &M) { return M.PantPressSwitchActive ? 1.0 : 0.0; }}, - {"PantPressLockActive", [](auto const &M) { return M.PantPressLockActive ? 1.0 : 0.0; }}, + {"PantPress", [](auto const &M) { return M.pantographAir.pressure; }}, + {"PantVolume", [](auto const &M) { return M.pantographAir.volume; }}, + {"PantCompFlag", [](auto const &M) { return M.pantographAir.compressorRunning ? 1.0 : 0.0; }}, + {"PantPressSwitchActive", [](auto const &M) { return M.pantographAir.pressureSwitchActive ? 1.0 : 0.0; }}, + {"PantPressLockActive", [](auto const &M) { return M.pantographAir.pressureLockActive ? 1.0 : 0.0; }}, }; } @@ -40,7 +40,7 @@ TEST_CASE("auxiliaries: the battery drained by the lights and the pantographs' c eu07.ConverterSwitch(false); eu07.iLights[VehicleEnd::front] = 1 | 2 | 4; eu07.iLights[VehicleEnd::rear] = 16; - eu07.PantCompFlag = true; + eu07.pantographAir.compressorRunning = true; scenario.wait(30.0); CHECK(eu07.BatteryVoltage < 0.83 * eu07.NominalBatteryVoltage); CHECK(eu07.Mains); @@ -90,23 +90,23 @@ TEST_CASE("auxiliaries: the pantographs on their own tank, leaking until the pre auto &eu07{scenario.cab()}; // started up on the small compressor, the tank gets joined to the main reservoir, which primes the switch scenario.act("tank joined to the main reservoir"); - eu07.bPantKurek3 = true; + eu07.pantographAir.connectedToMainReservoir = true; scenario.wait(30.0); - REQUIRE(eu07.PantPressSwitchActive); + REQUIRE(eu07.pantographAir.pressureSwitchActive); scenario.act("tank cut off the main reservoir"); - eu07.bPantKurek3 = false; - eu07.PantCompFlag = false; + eu07.pantographAir.connectedToMainReservoir = false; + eu07.pantographAir.compressorRunning = false; scenario.wait(600.0); - CHECK(eu07.PantPress < eu07.EnginePowerSource.CollectorParameters.MinPress); - CHECK_FALSE(eu07.PantPressSwitchActive); + CHECK(eu07.pantographAir.pressure < eu07.EnginePowerSource.CollectorParameters.MinPress); + CHECK_FALSE(eu07.pantographAir.pressureSwitchActive); CHECK_FALSE(eu07.Mains); scenario.act("small compressor on"); - eu07.PantCompFlag = true; - for (int i = 0; i < 60 && eu07.PantCompFlag; ++i) { + eu07.pantographAir.compressorRunning = true; + for (int i = 0; i < 60 && eu07.pantographAir.compressorRunning; ++i) { scenario.wait(10.0); } - CHECK_FALSE(eu07.PantCompFlag); - CHECK(eu07.PantPress >= 4.6); // stopped at 4.8, leaking since - CHECK(eu07.PantPressSwitchActive); + CHECK_FALSE(eu07.pantographAir.compressorRunning); + CHECK(eu07.pantographAir.pressure >= 4.6); // stopped at 4.8, leaking since + CHECK(eu07.pantographAir.pressureSwitchActive); scenario.check(); } diff --git a/tests/unit/test_commands.cpp b/tests/unit/test_commands.cpp index 702e81ae1..859f73336 100644 --- a/tests/unit/test_commands.cpp +++ b/tests/unit/test_commands.cpp @@ -61,7 +61,7 @@ std::vector state() { {"DoorStep", [](auto const &M) { return flag(M.Doors.step_enabled); }}, {"DoorRemoteOnly", [](auto const &M) { return flag(M.Doors.remote_only); }}, {"DepartureSignal", [](auto const &M) { return flag(M.DepartureSignal); }}, - {"PantsValve", [](auto const &M) { return flag(M.PantsValve.is_enabled) + 2 * flag(M.PantsValve.is_disabled); }}, + {"PantsValve", [](auto const &M) { return flag(M.pantographAir.valve.is_enabled) + 2 * flag(M.pantographAir.valve.is_disabled); }}, {"MaxCurrentHigh", [](auto const &M) { return flag(M.MotorOverloadRelayHighThreshold); }}, {"Imin", [](auto const &M) { return M.Imin; }}, {"DamageFlag", [](auto const &M) { return M.DamageFlag.Bits(); }}, @@ -79,7 +79,7 @@ std::vector state() { auto const name{std::string{end == VehicleEnd::front ? "Front" : "Rear"}}; result.emplace_back("MotorBlowers" + name + "Enabled", [end](auto const &M) { return flag(M.MotorBlowers[end].is_enabled); }); result.emplace_back("MotorBlowers" + name + "Disabled", [end](auto const &M) { return flag(M.MotorBlowers[end].is_disabled); }); - result.emplace_back("Pant" + name + "Valve", [end](auto const &M) { return flag(M.Pantographs[end].valve.is_enabled) + 2 * flag(M.Pantographs[end].valve.is_disabled); }); + result.emplace_back("Pant" + name + "Valve", [end](auto const &M) { return flag(M.pantographs[end].valve.is_enabled) + 2 * flag(M.pantographs[end].valve.is_disabled); }); } for (auto const side : VehicleSides) { auto const name{std::string{side == VehicleSide::right ? "Right" : "Left"}}; @@ -408,9 +408,9 @@ TEST_CASE("commands: every switch of the cab, worked on a pair standing under th auto done{false}; auto channels{state()}; channels.insert(channels.end(), { - {"PantFrontActive", [](auto const &M) { return flag(M.Pantographs[VehicleEnd::front].is_active); }}, - {"PantRearActive", [](auto const &M) { return flag(M.Pantographs[VehicleEnd::rear].is_active); }}, - {"PantPress", [](auto const &M) { return M.PantPress; }}, + {"PantFrontActive", [](auto const &M) { return flag(M.pantographs[VehicleEnd::front].is_active); }}, + {"PantRearActive", [](auto const &M) { return flag(M.pantographs[VehicleEnd::rear].is_active); }}, + {"PantPress", [](auto const &M) { return M.pantographAir.pressure; }}, {"GroundRelay", [](auto const &M) { return flag(M.GroundRelay); }}, {"ConverterFlag", [](auto const &M) { return flag(M.ConverterFlag); }}, {"CompressorFlag", [](auto const &M) { return flag(M.air.compressor.running); }}, @@ -480,9 +480,9 @@ TEST_CASE("commands: travel along the train, turned round for a vehicle facing b } SUBCASE("a pantograph valve: the vehicles past one coupled by its control cable take the other pantograph") { consist.head->OperatePantographValve(VehicleEnd::front, operation_t::enable, range_t::consist); - CHECK(consist.head->Pantographs[VehicleEnd::front].valve.is_enabled); - CHECK(consist.middle->Pantographs[VehicleEnd::front].valve.is_enabled); - CHECK(consist.last->Pantographs[VehicleEnd::rear].valve.is_enabled); + CHECK(consist.head->pantographs[VehicleEnd::front].valve.is_enabled); + CHECK(consist.middle->pantographs[VehicleEnd::front].valve.is_enabled); + CHECK(consist.last->pantographs[VehicleEnd::rear].valve.is_enabled); } SUBCASE("sent backwards, it goes no further than the sender: nothing is coupled at its front") { consist.head->RunCommand(VehicleCommand::doorLock, 0, -1, Coupling::control); diff --git a/tests/unit/test_door_wings.cpp b/tests/unit/test_door_wings.cpp index b5249a739..12eae8193 100644 --- a/tests/unit/test_door_wings.cpp +++ b/tests/unit/test_door_wings.cpp @@ -79,7 +79,7 @@ TEST_CASE("door wings: the kinds of animation are named as DoorOpenMethod of the // in any letter case CHECK(door_wings::type_from_name("plug") == door_wings::plug_type); CHECK(door_wings::type_from_name("SHIFT") == door_wings::shift_type); - // the same numbers as physics::Vehicle::door_data::type + // the same numbers as physics::door_data::type CHECK(door_wings::shift_type == 1); CHECK(door_wings::rotate_type == 2); CHECK(door_wings::fold_type == 3); diff --git a/tests/unit/test_genset.cpp b/tests/unit/test_genset.cpp index d0beab879..b552ed158 100644 --- a/tests/unit/test_genset.cpp +++ b/tests/unit/test_genset.cpp @@ -133,8 +133,8 @@ TEST_CASE("genset: a vehicle without the keys has none and stays on the catenary CHECK(cab.TractionMode == traction_mode::catenary); CHECK_FALSE(cab.GensetSelected()); REQUIRE(test::start_up(test::driving(dragon6), wire)); - CHECK(cab.PantographVoltage > 2900.0); - CHECK(cab.TractionSupplyVoltage() == std::max(cab.GetTrainsetHighVoltage(), cab.PantographVoltage)); + CHECK(cab.pantographCircuit.supplyVoltage > 2900.0); + CHECK(cab.TractionSupplyVoltage() == std::max(cab.GetTrainsetHighVoltage(), cab.pantographCircuit.supplyVoltage)); CHECK(cab.TractionSupplyMinVoltage() == cab.EnginePowerSource.CollectorParameters.MinV); CHECK(cab.GensetTractionPowerLimit() == std::numeric_limits::max()); // a start request does nothing without a genset @@ -230,7 +230,7 @@ TEST_CASE("genset: started, it closes the line breaker without a catenary") { run(dragon6, 1.0); } REQUIRE(cab.Mains); - CHECK(cab.PantographVoltage == 0.0); + CHECK(cab.pantographCircuit.supplyVoltage == 0.0); dragon6.step(no_wire); CHECK(cab.EngineVoltage == 3000.0); CHECK(cab.MainCircuitPowered()); @@ -263,7 +263,7 @@ TEST_CASE("genset: on the genset position the catenary feeds nothing") { REQUIRE(cab.TractionModeSwitch(traction_mode::genset)); // the pantographs up under the wire, the genset stopped: the line breaker never closes CHECK_FALSE(test::start_up(test::driving(dragon6), wire, 120.0)); - REQUIRE(cab.PantographVoltage > 2900.0); + REQUIRE(cab.pantographCircuit.supplyVoltage > 2900.0); CHECK_FALSE(cab.Mains); CHECK_FALSE(cab.MainSwitchCheck()); dragon6.step(wire); @@ -445,8 +445,8 @@ TEST_CASE("genset: the pantographs' pressure switch leaves the genset's line bre vehicle dragon6{dragon_genset(), 0.0, "test", 1}; auto &cab{dragon6.physics()}; REQUIRE(start_on_genset(dragon6)); - cab.PantPressSwitchActive = true; - cab.PantPress = 0.0; + cab.pantographAir.pressureSwitchActive = true; + cab.pantographAir.pressure = 0.0; cab.PantPressureSwitchCheck(); CHECK(cab.Mains); } @@ -456,8 +456,8 @@ TEST_CASE("genset: the pantographs' pressure switch leaves the genset's line bre REQUIRE(test::start_up(test::driving(dragon6), wire)); REQUIRE(cab.Mains); // the pressure switch looks at the voltage through the couplers, not the pantographs' - cab.PantPressSwitchActive = true; - cab.PantPress = 0.0; + cab.pantographAir.pressureSwitchActive = true; + cab.pantographAir.pressure = 0.0; cab.PantPressureSwitchCheck(); CHECK_FALSE(cab.Mains); } @@ -536,7 +536,7 @@ TEST_CASE("genset: one genset feeds the next car through the high voltage coupli train.run(10.0, no_wire); REQUIRE(first.Genset.is_active); CHECK(second.GetTrainsetHighVoltage() > 2900.0); - CHECK(second.PantographVoltage == 0.0); + CHECK(second.pantographCircuit.supplyVoltage == 0.0); // the second one, on its catenary position with the pantographs down, takes it as the catenary's second.BatterySwitch(true); train.run(10.0, no_wire); diff --git a/tests/unit/test_loads.cpp b/tests/unit/test_loads.cpp index 9440cd450..228ea5f5b 100644 --- a/tests/unit/test_loads.cpp +++ b/tests/unit/test_loads.cpp @@ -23,8 +23,8 @@ TEST_CASE("loads: the pantographs of an electric vehicle set up by the amount of vehicle et42{definition::fiz("et42_v2/112e-a")}; CHECK(et42->AssignLoad("pantstate", static_cast(amount))); CHECK(et42->DoubleTr == ((amount & 4) != 0 ? -1 : 1)); - CHECK(et42->Pantographs[VehicleEnd::front].valve.is_enabled == frontraised); - CHECK(et42->Pantographs[VehicleEnd::rear].valve.is_enabled == rearraised); + CHECK(et42->pantographs[VehicleEnd::front].valve.is_enabled == frontraised); + CHECK(et42->pantographs[VehicleEnd::rear].valve.is_enabled == rearraised); // the load itself stays as it was CHECK(et42->LoadAmount == doctest::Approx(0.0)); } diff --git a/tests/unit/test_mains_before_pantographs.cpp b/tests/unit/test_mains_before_pantographs.cpp index 3506966ad..374a8709a 100644 --- a/tests/unit/test_mains_before_pantographs.cpp +++ b/tests/unit/test_mains_before_pantographs.cpp @@ -26,7 +26,7 @@ test::definition ep05(bool const Mainsfirst) { // battery and cab on, direction set and the relays reset, the pantographs on the main reservoir's air void prepare(test::vehicle &Loco) { Loco.hold_main_reservoir(6.0); - Loco->bPantKurek3 = true; + Loco->pantographAir.connectedToMainReservoir = true; Loco->BatterySwitch(true); Loco->CabActivisation(); for (int i = 0; i < 3 && Loco->DirActive <= 0; ++i) { @@ -93,14 +93,14 @@ TEST_CASE("mains before pantographs: without the flag the line breaker needs the close_line_breaker(loco); CHECK_FALSE(loco->Mains); raise_pantograph(loco); - CHECK(loco->Pantographs[VehicleEnd::rear].is_active); - CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); + CHECK(loco->pantographs[VehicleEnd::rear].is_active); + CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); close_line_breaker(loco); CHECK(loco->Mains); // the pantographs stay up with the line breaker open, and the line breaker opens without voltage loco->MainSwitch(false); loco.run(2.0, line); - CHECK(loco->Pantographs[VehicleEnd::rear].is_active); + CHECK(loco->pantographs[VehicleEnd::rear].is_active); close_line_breaker(loco); REQUIRE(loco->Mains); loco->OperatePantographValve(VehicleEnd::rear, operation_t::disable); @@ -114,28 +114,28 @@ TEST_CASE("mains before pantographs: with the flag the pantographs rise only thr prepare(loco); // the pantographs stay down while the line breaker is open raise_pantograph(loco); - CHECK_FALSE(loco->Pantographs[VehicleEnd::rear].is_active); - CHECK(loco->PantographVoltage == 0.0); + CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); + CHECK(loco->pantographCircuit.supplyVoltage == 0.0); // the line breaker closes without voltage, and the pantograph rises through it close_line_breaker(loco); CHECK(loco->Mains); raise_pantograph(loco); - CHECK(loco->Pantographs[VehicleEnd::rear].is_active); - CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); + CHECK(loco->pantographs[VehicleEnd::rear].is_active); + CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); CHECK(loco->Mains); // opening the line breaker drops the pantograph, which stays down until the line breaker closes again loco->MainSwitch(false); loco.run(2.0, line); CHECK_FALSE(loco->Mains); - CHECK_FALSE(loco->Pantographs[VehicleEnd::rear].is_active); - CHECK(loco->PantographVoltage == 0.0); + CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); + CHECK(loco->pantographCircuit.supplyVoltage == 0.0); // a pantograph lowered under the closed line breaker leaves it closed close_line_breaker(loco); raise_pantograph(loco); - REQUIRE(loco->Pantographs[VehicleEnd::rear].is_active); + REQUIRE(loco->pantographs[VehicleEnd::rear].is_active); loco->OperatePantographValve(VehicleEnd::rear, operation_t::disable); loco.run(5.0, line); - CHECK_FALSE(loco->Pantographs[VehicleEnd::rear].is_active); + CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); CHECK(loco->Mains); } @@ -153,7 +153,7 @@ TEST_CASE("mains before pantographs: with the flag the driver's start-up gets th auto driven{test::driving(loco)}; REQUIRE(test::start_up(driven, line)); CHECK(loco->Mains); - CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); + CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); CHECK(test::is_ready(driven)); } @@ -165,7 +165,7 @@ TEST_CASE("mains before pantographs: with the flag the converter and the compres prepare(loco); close_line_breaker(loco); REQUIRE(loco->Mains); - REQUIRE(loco->PantographVoltage == 0.0); + REQUIRE(loco->pantographCircuit.supplyVoltage == 0.0); switch_auxiliaries_on(loco); REQUIRE(loco->ConverterAllow); REQUIRE(loco->air.compressor.allow); @@ -180,7 +180,7 @@ TEST_CASE("mains before pantographs: with the flag the converter and the compres // the pantograph up: the converter starts, and the compressor on its 110 V raise_pantograph(loco); - REQUIRE(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); + REQUIRE(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); CHECK(reservoir_gain(loco, 10.0, line) > 0.1); CHECK(loco->MainCircuitPowered()); CHECK(loco->ConverterFlag); @@ -192,17 +192,17 @@ TEST_CASE("mains before pantographs: with the flag the converter and the compres SUBCASE("the pantograph lowered again") { loco->OperatePantographValve(VehicleEnd::rear, operation_t::disable); loco.run(5.0, line); - REQUIRE_FALSE(loco->Pantographs[VehicleEnd::rear].is_active); + REQUIRE_FALSE(loco->pantographs[VehicleEnd::rear].is_active); } SUBCASE("no voltage in the catenary") { track = &dead; loco.run(5.0, dead); - REQUIRE(loco->Pantographs[VehicleEnd::rear].is_active); + REQUIRE(loco->pantographs[VehicleEnd::rear].is_active); } SUBCASE("the voltage in the catenary below the one the locomotive works on") { track = &weak; loco.run(5.0, weak); - REQUIRE(loco->PantographVoltage == doctest::Approx(weak.voltage)); + REQUIRE(loco->pantographCircuit.supplyVoltage == doctest::Approx(weak.voltage)); } CHECK(reservoir_gain(loco, 10.0, *track) < 0.01); CHECK(loco->Mains); @@ -235,7 +235,7 @@ TEST_CASE("mains before pantographs: with the flag whatever else the main circui SUBCASE("nor do they run on a voltage below the one the locomotive works on") { raise_pantograph(loco, weak); - REQUIRE(loco->PantographVoltage == doctest::Approx(weak.voltage)); + REQUIRE(loco->pantographCircuit.supplyVoltage == doctest::Approx(weak.voltage)); CHECK(reservoir_gain(loco, 10.0, weak) < 0.01); CHECK(loco->Mains); CHECK_FALSE(loco->air.compressor.running); @@ -245,7 +245,7 @@ TEST_CASE("mains before pantographs: with the flag whatever else the main circui } SUBCASE("with the voltage they do") { raise_pantograph(loco); - REQUIRE(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); + REQUIRE(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); CHECK(reservoir_gain(loco, 10.0, line) > 0.1); CHECK(loco->air.compressor.running); CHECK(loco->MotorBlowers[VehicleEnd::front].is_active); @@ -288,7 +288,7 @@ TEST_CASE("mains before pantographs: with the flag the line contactors open when // the voltage goes: the line breaker holds, the pantograph stays up, the motors are cut off test::drive(driven, dead, 3.0); CHECK(loco->Mains); - CHECK(loco->Pantographs[VehicleEnd::rear].is_active); + CHECK(loco->pantographs[VehicleEnd::rear].is_active); CHECK_FALSE(loco->NoVoltRelay); CHECK_FALSE(loco->StLinFlag); CHECK(loco->Im == 0.0); @@ -296,7 +296,7 @@ TEST_CASE("mains before pantographs: with the flag the line contactors open when // the voltage back, with the master controller still where it was: the camshaft went down to zero and stays // there, the motors still cut off; the converter is back on its own test::drive(driven, line, 10.0); - REQUIRE(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); + REQUIRE(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); REQUIRE(loco->MainCtrlPos == 5); CHECK(loco->Mains); CHECK(loco->ConverterFlag); diff --git a/tests/unit/test_pressure_switch.cpp b/tests/unit/test_pressure_switch.cpp index 5f787cee3..75304f5ae 100644 --- a/tests/unit/test_pressure_switch.cpp +++ b/tests/unit/test_pressure_switch.cpp @@ -50,7 +50,7 @@ void get_ready(test::vehicle &Loco, test::driven const &Driven) { } REQUIRE_FALSE(Loco->ControlPressureSwitch); REQUIRE(Loco->Mains); - REQUIRE(Loco->Pantographs[VehicleEnd::rear].is_active); + REQUIRE(Loco->pantographs[VehicleEnd::rear].is_active); } // the master controller taken to the given position a notch a second @@ -109,7 +109,7 @@ TEST_CASE("pressure switch: with the brake cylinders at 3.8 bar the EP05 takes n CHECK_FALSE(loco->StLinFlag); CHECK(loco->Im == 0.0); CHECK(loco->Mains); - CHECK(loco->Pantographs[VehicleEnd::rear].is_active); + CHECK(loco->pantographs[VehicleEnd::rear].is_active); } TEST_CASE("pressure switch: without its brake cylinder half the EP05 takes current with the brake cylinders at 3.8 bar") { @@ -149,7 +149,7 @@ TEST_CASE("pressure switch: without its brake cylinder half the brake pipe still CHECK(loco->Im == 0.0); // nothing else lets go without the other key CHECK(loco->Mains); - CHECK(loco->Pantographs[VehicleEnd::rear].is_active); + CHECK(loco->pantographs[VehicleEnd::rear].is_active); } TEST_CASE("pressure switch: an emergency application with the master controller on a power position opens the line breaker and drops the pantographs") { @@ -167,9 +167,9 @@ TEST_CASE("pressure switch: an emergency application with the master controller REQUIRE(loco->brakePipe.pressure < emergency_pressure); REQUIRE(loco->MainCtrlPos == 5); CHECK_FALSE(loco->Mains); - CHECK_FALSE(loco->Pantographs[VehicleEnd::front].is_active); - CHECK_FALSE(loco->Pantographs[VehicleEnd::rear].is_active); - CHECK(loco->PantographVoltage == 0.0); + CHECK_FALSE(loco->pantographs[VehicleEnd::front].is_active); + CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); + CHECK(loco->pantographCircuit.supplyVoltage == 0.0); CHECK_FALSE(loco->StLinFlag); CHECK(loco->Im == 0.0); @@ -177,7 +177,7 @@ TEST_CASE("pressure switch: an emergency application with the master controller loco->MainSwitch(true); test::drive(driven, line, 2.0); CHECK_FALSE(loco->Mains); - CHECK_FALSE(loco->Pantographs[VehicleEnd::rear].is_active); + CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); } TEST_CASE("pressure switch: an emergency application with the master controller at zero leaves the line breaker and the pantographs alone") { @@ -192,15 +192,15 @@ TEST_CASE("pressure switch: an emergency application with the master controller emergency_application(loco, driven); CHECK(loco->Mains); - CHECK(loco->Pantographs[VehicleEnd::rear].is_active); - CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); + CHECK(loco->pantographs[VehicleEnd::rear].is_active); + CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); CHECK(loco->Im == 0.0); // and the master controller moved with the pipe empty is the same as the application made with it moved loco->IncMainCtrl(1); test::drive(driven, line, 2.0); CHECK_FALSE(loco->Mains); - CHECK_FALSE(loco->Pantographs[VehicleEnd::rear].is_active); + CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); } TEST_CASE("pressure switch: a service application with the master controller on a power position doesn't open the line breaker") { @@ -219,7 +219,7 @@ TEST_CASE("pressure switch: a service application with the master controller on REQUIRE(lowest < 3.0); CHECK(lowest > emergency_pressure); CHECK(loco->Mains); - CHECK(loco->Pantographs[VehicleEnd::rear].is_active); + CHECK(loco->pantographs[VehicleEnd::rear].is_active); // the pressure switch has cut the motors off CHECK_FALSE(loco->StLinFlag); CHECK(loco->Im == 0.0); @@ -233,8 +233,8 @@ TEST_CASE("pressure switch: without the key an emergency application leaves the emergency_application(loco, driven); REQUIRE(loco->MainCtrlPos == 5); CHECK(loco->Mains); - CHECK(loco->Pantographs[VehicleEnd::rear].is_active); - CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); + CHECK(loco->pantographs[VehicleEnd::rear].is_active); + CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); // the pressure switch cuts the motors off CHECK(loco->ControlPressureSwitch); CHECK_FALSE(loco->StLinFlag); @@ -249,8 +249,8 @@ TEST_CASE("pressure switch: where the pantographs don't hang on the line breaker emergency_application(loco, driven); CHECK_FALSE(loco->Mains); - CHECK(loco->Pantographs[VehicleEnd::rear].is_active); - CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); + CHECK(loco->pantographs[VehicleEnd::rear].is_active); + CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); CHECK_FALSE(loco->StLinFlag); CHECK(loco->Im == 0.0); } @@ -264,20 +264,20 @@ TEST_CASE("pressure switch: after the emergency application the driver's start-u get_under_power(loco, driven, 5); emergency_application(loco, driven); REQUIRE_FALSE(loco->Mains); - REQUIRE_FALSE(loco->Pantographs[VehicleEnd::rear].is_active); - REQUIRE(loco->Pantographs[VehicleEnd::rear].valve.is_enabled); + REQUIRE_FALSE(loco->pantographs[VehicleEnd::rear].is_active); + REQUIRE(loco->pantographs[VehicleEnd::rear].valve.is_enabled); // with the brake pipe still empty REQUIRE(test::start_up(driven, line, 60.0)); CHECK(loco->MainCtrlPos == 0); CHECK(loco->Mains); - CHECK(loco->Pantographs[VehicleEnd::rear].is_active); - CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); + CHECK(loco->pantographs[VehicleEnd::rear].is_active); + CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); REQUIRE(loco->brakePipe.pressure < emergency_pressure); // and it stays so test::drive(driven, line, 30.0); CHECK(loco->Mains); - CHECK(loco->Pantographs[VehicleEnd::rear].is_active); + CHECK(loco->pantographs[VehicleEnd::rear].is_active); // the brakes released (the AI fills an emptied pipe with the releaser held, TController::control_releaser()), // the pressure switch lets the start be made diff --git a/tests/unit/vehicle.cpp b/tests/unit/vehicle.cpp index 0c36df05f..4e98ed74f 100644 --- a/tests/unit/vehicle.cpp +++ b/tests/unit/vehicle.cpp @@ -225,15 +225,15 @@ double vehicle::move(track const &Track, double Dt, TLocation const &Location, d // what TDynamicObject::Update() does before the movement. a raised pantograph touches the wire at once, // the game animates its rise auto &physics{*m_physics}; - physics.PantFrontVolt = physics.Pantographs[VehicleEnd::front].is_active ? Track.voltage : 0.0; - physics.PantRearVolt = physics.Pantographs[VehicleEnd::rear].is_active ? Track.voltage : 0.0; + physics.pantographCircuit.frontVoltage = physics.pantographs[VehicleEnd::front].is_active ? Track.voltage : 0.0; + physics.pantographCircuit.rearVoltage = physics.pantographs[VehicleEnd::rear].is_active ? Track.voltage : 0.0; TTractionParam traction; traction.TractionVoltage = - physics.EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? std::max(std::abs(physics.PantRearVolt), std::abs(physics.PantFrontVolt)) : 0.95 * physics.EnginePowerSource.MaxVoltage; + physics.EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? std::max(std::abs(physics.pantographCircuit.rearVoltage), std::abs(physics.pantographCircuit.frontVoltage)) : 0.95 * physics.EnginePowerSource.MaxVoltage; traction.TractionFreq = 0; traction.TractionMaxCurrent = 7500; traction.TractionResistivity = 0.3; - physics.PantographVoltage = traction.TractionVoltage; + physics.pantographCircuit.supplyVoltage = traction.TractionVoltage; if (m_cab != 0) { using enum TEngineType; // the driver's own vehicle, which gets the average pressure of the train's brake pipe diff --git a/vehicle/ai/engine.cpp b/vehicle/ai/engine.cpp index af3e9b1a1..5aedc3b66 100644 --- a/vehicle/ai/engine.cpp +++ b/vehicle/ai/engine.cpp @@ -102,21 +102,21 @@ bool TController::PrepareEngine() if( pantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector && pantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 0 ) { // if our pantograph unit isn't a pantograph-devoid fallback - if (pantographUnit->PantPress < sufficientpantographpressure) { + if (pantographUnit->pantographAir.pressure < sufficientpantographpressure) { // załączenie małej sprężarki - if( false == pantographUnit->PantAutoValve ) { + if( false == pantographUnit->pantographAir.autoValve ) { // odłączenie zbiornika głównego, bo z nim nie da rady napompować cue_action( driver_hint::pantographairsourcesetauxiliary ); } cue_action( driver_hint::pantographcompressoron ); // załączenie sprężarki pantografów - if( pantographUnit->PantCompFlag ) { + if( pantographUnit->pantographAir.compressorRunning ) { cue_action( driver_hint::waitpantographpressuretoolow ); } } else { // jeżeli jest wystarczające ciśnienie w pantografach - if( false == pantographUnit->bPantKurek3 - || pantographUnit->PantPress <= pantographUnit->mainPipe.pressure ) { // kurek przełączony albo główna już pompuje + if( false == pantographUnit->pantographAir.connectedToMainReservoir + || pantographUnit->pantographAir.pressure <= pantographUnit->mainPipe.pressure ) { // kurek przełączony albo główna już pompuje cue_action( driver_hint::pantographcompressoroff ); // sprężarkę pantografów można już wyłączyć } } @@ -130,7 +130,7 @@ bool TController::PrepareEngine() auto const ispoweravailable = mvControlling->EnginePowerSource.SourceType != TPowerSource::CurrentCollector - || std::max(mvControlling->GetTrainsetHighVoltage(), mvControlling->PantographVoltage) > mvControlling->EnginePowerSource.CollectorParameters.MinV; + || std::max(mvControlling->GetTrainsetHighVoltage(), mvControlling->pantographCircuit.supplyVoltage) > mvControlling->EnginePowerSource.CollectorParameters.MinV; // standing with the pantographs up and no voltage, nothing the driver does starts the vehicle. it says so, and keeps // trying: towed back under the wire, or with the power switched on, the vehicle gets prepared after all report_power_stall( ispoweravailable, sufficientpantographpressure ); @@ -235,17 +235,17 @@ TController::report_power_stall( bool const Poweravailable, double const Pantogr state.collector = mvControlling->EnginePowerSource.SourceType == TPowerSource::CurrentCollector; state.power = Poweravailable; state.standing = occupied->Vel < EU07_AI_NOMOVEMENT; - if( pantographUnit->PantPress >= Pantographpressure ) { + if( pantographUnit->pantographAir.pressure >= Pantographpressure ) { state.pantographs_up = - pantographUnit->Pantographs[ VehicleEnd::front ].is_active - || pantographUnit->Pantographs[ VehicleEnd::rear ].is_active; + pantographUnit->pantographs[ VehicleEnd::front ].is_active + || pantographUnit->pantographs[ VehicleEnd::rear ].is_active; } // the pantographs of the vehicle carrying them hold the wire they found above them if( auto const *carrier { pVehicle->FindPantographCarrier() }; carrier != nullptr && carrier->physics == pantographUnit ) { - auto const pantographcount { std::min( carrier->iAnimType[ ANIM_PANTS ], static_cast( carrier->physics->Pantographs.size() ) ) }; + auto const pantographcount { std::min( carrier->iAnimType[ ANIM_PANTS ], static_cast( carrier->physics->pantographs.size() ) ) }; for( auto index { 0 }; index < pantographcount; ++index ) { - if( true == carrier->physics->Pantographs[ index ].is_active + if( true == carrier->physics->pantographs[ index ].is_active && carrier->pants[ index ].fParamPants->hvPowerWire != nullptr ) { state.wire = true; } diff --git a/vehicle/ai/situation.cpp b/vehicle/ai/situation.cpp index 9ccb515d6..84b7de29e 100644 --- a/vehicle/ai/situation.cpp +++ b/vehicle/ai/situation.cpp @@ -142,14 +142,14 @@ TController::control_pantographs() { if( pantographUnit->EnginePowerSource.SourceType != TPowerSource::CurrentCollector ) { return; } - if( false == pantographUnit->PantAutoValve + if( false == pantographUnit->pantographAir.autoValve && occupied->mainPipe.pressure > 4.3 ) { // gdy główna sprężarka bezpiecznie nabije ciśnienie to można przestawić kurek na zasilanie pantografów z głównej pneumatyki cue_action( driver_hint::pantographairsourcesetmain ); } // uśrednione napięcie sieci: przy spadku poniżej wartości minimalnej opóźnić rozruch o losowy czas - fVoltage = 0.5 * (fVoltage + std::max( mvControlling->GetTrainsetHighVoltage(), mvControlling->PantographVoltage ) ); + fVoltage = 0.5 * (fVoltage + std::max( mvControlling->GetTrainsetHighVoltage(), mvControlling->pantographCircuit.supplyVoltage ) ); if( fVoltage < mvControlling->EnginePowerSource.CollectorParameters.MinV && fActionTime >= PrepareTime ) { // gdy rozłączenie WS z powodu niskiego napięcia // jeśli czas oczekiwania nie został ustawiony, losowy czas oczekiwania przed ponownym załączeniem jazdy @@ -178,10 +178,10 @@ TController::control_pantographs() { if( fOverhead2 > 0.0 || iOverheadDown ) { // jazda z opuszczonymi pantografami - if( pantographUnit->Pantographs[ VehicleEnd::front ].is_active ) { + if( pantographUnit->pantographs[ VehicleEnd::front ].is_active ) { cue_action( driver_hint::frontpantographvalveoff ); } - if( pantographUnit->Pantographs[ VehicleEnd::rear ].is_active ) { + if( pantographUnit->pantographs[ VehicleEnd::rear ].is_active ) { cue_action( driver_hint::rearpantographvalveoff ); } } @@ -197,18 +197,18 @@ TController::control_pantographs() { // jazda na tylnym if( iDirection >= 0 && useregularpantographlayout ) { // jak jedzie w kierunku sprzęgu 0 - if( pantographUnit->PantRearVolt == 0.0 + if( pantographUnit->pantographCircuit.rearVoltage == 0.0 // filter out cases with single _other_ working pantograph so we don't try to raise something we can't - && ( pantographUnit->PantographVoltage == 0.0 + && ( pantographUnit->pantographCircuit.supplyVoltage == 0.0 || pantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 1 ) ) { cue_action( driver_hint::rearpantographvalveon ); } } else { // jak jedzie w kierunku sprzęgu 0 - if( pantographUnit->PantFrontVolt == 0.0 + if( pantographUnit->pantographCircuit.frontVoltage == 0.0 // filter out cases with single _other_ working pantograph so we don't try to raise something we can't - && ( pantographUnit->PantographVoltage == 0.0 + && ( pantographUnit->pantographCircuit.supplyVoltage == 0.0 || pantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 1 ) ) { cue_action( driver_hint::frontpantographvalveon ); } @@ -218,14 +218,14 @@ TController::control_pantographs() { // opuszczenie przedniego po rozpędzeniu się o ile jest więcej niż jeden if (iDirection >= 0 && useregularpantographlayout) // jak jedzie w kierunku sprzęgu 0 { // poczekać na podniesienie tylnego - if (pantographUnit->PantFrontVolt != 0.0 && pantographUnit->PantRearVolt != 0.0) + if (pantographUnit->pantographCircuit.frontVoltage != 0.0 && pantographUnit->pantographCircuit.rearVoltage != 0.0) { // czy jest napięcie zasilające na tylnym? cue_action(driver_hint::frontpantographvalveoff); // opuszcza od sprzęgu 0 } } else { // poczekać na podniesienie przedniego - if (pantographUnit->PantRearVolt != 0.0 && pantographUnit->PantFrontVolt != 0.0) + if (pantographUnit->pantographCircuit.rearVoltage != 0.0 && pantographUnit->pantographCircuit.frontVoltage != 0.0) { // czy jest napięcie zasilające na przednim? cue_action(driver_hint::rearpantographvalveoff); // opuszcza od sprzęgu 1 } @@ -262,14 +262,14 @@ TController::control_pantographs() { if (iDirection >= 0 && useregularpantographlayout) { // jak jedzie w kierunku sprzęgu 0 - if (pantographUnit->PantFrontVolt == 0.0) + if (pantographUnit->pantographCircuit.frontVoltage == 0.0) { cue_action(driver_hint::frontpantographvalveon, 5); // discard the hint if speed exceeds 5 km/h } } else { - if (pantographUnit->PantRearVolt == 0.0) + if (pantographUnit->pantographCircuit.rearVoltage == 0.0) { cue_action(driver_hint::rearpantographvalveon, 5); // discard the hint if speed exceeds 5 km/h } @@ -291,7 +291,7 @@ TController::control_pantographs_setup( int const Setup ) { if( rear ) { cue_action( driver_hint::rearpantographvalveon ); } - if( auto const setuplive { ( front && pantographUnit->PantFrontVolt != 0.0 ) || ( rear && pantographUnit->PantRearVolt != 0.0 ) }; + if( auto const setuplive { ( front && pantographUnit->pantographCircuit.frontVoltage != 0.0 ) || ( rear && pantographUnit->pantographCircuit.rearVoltage != 0.0 ) }; false == setuplive ) { return; } diff --git a/vehicle/cab/pantographcommands.cpp b/vehicle/cab/pantographcommands.cpp index 24a043416..c83599f97 100644 --- a/vehicle/cab/pantographcommands.cpp +++ b/vehicle/cab/pantographcommands.cpp @@ -59,7 +59,7 @@ void TTrain::OnCommand_pantographtogglefront(TTrain *Train, command_data const & if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const &pantograph{Train->pantographUnit->Pantographs[VehicleEnd::front]}; + auto const &pantograph{Train->pantographUnit->pantographs[VehicleEnd::front]}; auto const state{pantograph.valve.is_enabled || pantograph.is_active}; // fallback for impulse switches if (state) { @@ -73,7 +73,7 @@ void TTrain::OnCommand_pantographtogglefront(TTrain *Train, command_data const & else if (Command.action == GLFW_RELEASE) { // impulse switches return automatically to neutral position - if (Train->occupied->PantSwitchType == "impulse") + if (Train->occupied->pantographCircuit.switchType == "impulse") { auto const ismanual{Train->iCabn == 0}; Train->occupied->OperatePantographValve(VehicleEnd::front, operation_t::none, ismanual ? range_t::local : range_t::consist); @@ -93,7 +93,7 @@ void TTrain::OnCommand_pantographtogglerear(TTrain *Train, command_data const &C if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const &pantograph{Train->pantographUnit->Pantographs[VehicleEnd::rear]}; + auto const &pantograph{Train->pantographUnit->pantographs[VehicleEnd::rear]}; auto const state{pantograph.valve.is_enabled || pantograph.is_active}; // fallback for impulse switches if (state) { @@ -107,7 +107,7 @@ void TTrain::OnCommand_pantographtogglerear(TTrain *Train, command_data const &C else if (Command.action == GLFW_RELEASE) { // impulse switches return automatically to neutral position - if (Train->occupied->PantSwitchType == "impulse") + if (Train->occupied->pantographCircuit.switchType == "impulse") { auto const ismanual{Train->iCabn == 0}; Train->occupied->OperatePantographValve(VehicleEnd::rear, operation_t::none, ismanual ? range_t::local : range_t::consist); @@ -134,7 +134,7 @@ void TTrain::OnCommand_pantographraisefront(TTrain *Train, command_data const &C // only reacting to press, so the switch doesn't flip back and forth if key is held down // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers auto const ismanual{Train->iCabn == 0}; - Train->occupied->OperatePantographValve(VehicleEnd::front, Train->occupied->PantSwitchType == "impulse" ? operation_t::enable_on : operation_t::enable, + Train->occupied->OperatePantographValve(VehicleEnd::front, Train->occupied->pantographCircuit.switchType == "impulse" ? operation_t::enable_on : operation_t::enable, ismanual ? range_t::local : range_t::consist); } else if (Command.action == GLFW_RELEASE) @@ -163,7 +163,7 @@ void TTrain::OnCommand_pantographraiserear(TTrain *Train, command_data const &Co // only reacting to press, so the switch doesn't flip back and forth if key is held down // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers auto const ismanual{Train->iCabn == 0}; - Train->occupied->OperatePantographValve(VehicleEnd::rear, Train->occupied->PantSwitchType == "impulse" ? operation_t::enable_on : operation_t::enable, + Train->occupied->OperatePantographValve(VehicleEnd::rear, Train->occupied->pantographCircuit.switchType == "impulse" ? operation_t::enable_on : operation_t::enable, ismanual ? range_t::local : range_t::consist); } else if (Command.action == GLFW_RELEASE) @@ -182,7 +182,7 @@ void TTrain::OnCommand_pantographlowerfront(TTrain *Train, command_data const &C return; } // prevent operation without submodel outside of engine compartment - if (Train->iCabn != 0 && false == Train->m_controlmapper.contains(Train->occupied->PantSwitchType == "impulse" ? "pantfrontoff_sw:" : "pantfront_sw:")) + if (Train->iCabn != 0 && false == Train->m_controlmapper.contains(Train->occupied->pantographCircuit.switchType == "impulse" ? "pantfrontoff_sw:" : "pantfront_sw:")) { return; } @@ -192,7 +192,7 @@ void TTrain::OnCommand_pantographlowerfront(TTrain *Train, command_data const &C // only reacting to press, so the switch doesn't flip back and forth if key is held down // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers auto const ismanual{Train->iCabn == 0}; - Train->occupied->OperatePantographValve(VehicleEnd::front, Train->occupied->PantSwitchType == "impulse" ? operation_t::disable_on : operation_t::disable, + Train->occupied->OperatePantographValve(VehicleEnd::front, Train->occupied->pantographCircuit.switchType == "impulse" ? operation_t::disable_on : operation_t::disable, ismanual ? range_t::local : range_t::consist); } else if (Command.action == GLFW_RELEASE) @@ -211,7 +211,7 @@ void TTrain::OnCommand_pantographlowerrear(TTrain *Train, command_data const &Co return; } - if (Train->iCabn != 0 && false == Train->m_controlmapper.contains(Train->occupied->PantSwitchType == "impulse" ? "pantrearoff_sw:" : "pantrear_sw:")) + if (Train->iCabn != 0 && false == Train->m_controlmapper.contains(Train->occupied->pantographCircuit.switchType == "impulse" ? "pantrearoff_sw:" : "pantrear_sw:")) { return; } @@ -221,7 +221,7 @@ void TTrain::OnCommand_pantographlowerrear(TTrain *Train, command_data const &Co // only reacting to press, so the switch doesn't flip back and forth if key is held down // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers auto const ismanual{Train->iCabn == 0}; - Train->occupied->OperatePantographValve(VehicleEnd::rear, Train->occupied->PantSwitchType == "impulse" ? operation_t::disable_on : operation_t::disable, + Train->occupied->OperatePantographValve(VehicleEnd::rear, Train->occupied->pantographCircuit.switchType == "impulse" ? operation_t::disable_on : operation_t::disable, ismanual ? range_t::local : range_t::consist); } else if (Command.action == GLFW_RELEASE) @@ -254,9 +254,9 @@ void TTrain::OnCommand_pantographlowerall(TTrain *Train, command_data const &Com // two-state switch, only cares about press events if (Command.action == GLFW_PRESS) { - Train->pantographUnit->DropAllPantographs(false == Train->pantographUnit->PantAllDown); + Train->pantographUnit->DropAllPantographs(false == Train->pantographUnit->pantographCircuit.allDown); // visual feedback - Train->ggPantAllDownButton.UpdateValue(Train->pantographUnit->PantAllDown ? 1.0 : 0.0, Train->dsbSwitch); + Train->ggPantAllDownButton.UpdateValue(Train->pantographUnit->pantographCircuit.allDown ? 1.0 : 0.0, Train->dsbSwitch); } } else @@ -315,7 +315,7 @@ void TTrain::OnCommand_pantographtoggleselected(TTrain *Train, command_data cons Train->change_pantograph_selection(-1); // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const state{Train->pantographUnit->PantsValve.is_enabled || Train->pantographUnit->PantsValve.is_active}; // fallback for impulse switches + auto const state{Train->pantographUnit->pantographAir.valve.is_enabled || Train->pantographUnit->pantographAir.valve.is_active}; // fallback for impulse switches if (state) { OnCommand_pantographlowerselected(Train, Command); @@ -415,8 +415,8 @@ void TTrain::update_pantograph_valves() { using enum operation_t; - auto const &presets{occupied->PantsPreset.first}; - auto const &selection{occupied->PantsPreset.second[cab_to_end()]}; + auto const &presets{occupied->pantographCircuit.presets.first}; + auto const &selection{occupied->pantographCircuit.presets.second[cab_to_end()]}; auto const preset{presets[selection] - '0'}; auto const swapends{cab_to_end() != VehicleEnd::front}; @@ -430,8 +430,8 @@ void TTrain::update_pantograph_valves() void TTrain::change_pantograph_selection(int const Change) { - auto const &presets{occupied->PantsPreset.first}; - auto &selection{occupied->PantsPreset.second[cab_to_end()]}; + auto const &presets{occupied->pantographCircuit.presets.first}; + auto &selection{occupied->pantographCircuit.presets.second[cab_to_end()]}; auto const initialstate{selection}; selection = std::clamp(selection + Change, 0, std::max(static_cast(presets.size() - 1), 0)); @@ -525,7 +525,7 @@ void TTrain::OnCommand_pantographcompressorvalvetoggle(TTrain *Train, command_da if (Command.action == GLFW_PRESS) { // only react to press - if (Train->controlled->bPantKurek3 == false) + if (Train->controlled->pantographAir.connectedToMainReservoir == false) { // connect pantographs with primary tank OnCommand_pantographcompressorvalveenable(Train, Command); @@ -552,7 +552,7 @@ void TTrain::OnCommand_pantographcompressorvalveenable(TTrain *Train, command_da { // only react to press // connect pantographs with primary tank - Train->controlled->bPantKurek3 = true; + Train->controlled->pantographAir.connectedToMainReservoir = true; // visual feedback: Train->ggPantCompressorValve.UpdateValue(0.0); } @@ -572,7 +572,7 @@ void TTrain::OnCommand_pantographcompressorvalvedisable(TTrain *Train, command_d { // only react to press // connect pantograps with pantograph compressor - Train->controlled->bPantKurek3 = false; + Train->controlled->pantographAir.connectedToMainReservoir = false; // visual feedback: Train->ggPantCompressorValve.UpdateValue(1.0); } @@ -590,10 +590,10 @@ void TTrain::OnCommand_pantographcompressoractivate(TTrain *Train, command_data if (Command.action != GLFW_RELEASE) { // press or hold to activate - if (Train->pantographUnit->PantPress < 4.8 && true == Train->pantographUnit->Power24vIsAvailable) + if (Train->pantographUnit->pantographAir.pressure < 4.8 && true == Train->pantographUnit->Power24vIsAvailable) { // needs live power source and low enough pressure to work - Train->pantographUnit->PantCompFlag = true; + Train->pantographUnit->pantographAir.compressorRunning = true; } // visual feedback Train->ggPantCompressorButton.UpdateValue(1.0); @@ -601,7 +601,7 @@ void TTrain::OnCommand_pantographcompressoractivate(TTrain *Train, command_data else { // release to disable - Train->pantographUnit->PantCompFlag = false; + Train->pantographUnit->pantographAir.compressorRunning = false; // visual feedback Train->ggPantCompressorButton.UpdateValue(0.0); } diff --git a/vehicle/cab/setup.cpp b/vehicle/cab/setup.cpp index 53bf093ca..116d2b8dc 100644 --- a/vehicle/cab/setup.cpp +++ b/vehicle/cab/setup.cpp @@ -967,7 +967,7 @@ void TTrain::set_cab_controls(int const Cab) // front/end pantograph selection is relative to occupied cab if (ggPantSelectedButton.type() == TGaugeType::toggle) { - ggPantSelectedButton.PutValue(pantographUnit->PantsValve.is_enabled ? 1.f : 0.f); + ggPantSelectedButton.PutValue(pantographUnit->pantographAir.valve.is_enabled ? 1.f : 0.f); } else { @@ -979,15 +979,15 @@ void TTrain::set_cab_controls(int const Cab) } if (ggPantSelectedDownButton.type() == TGaugeType::toggle) { - ggPantSelectedDownButton.PutValue(pantographUnit->PantsValve.is_disabled ? 1.f : 0.f); + ggPantSelectedDownButton.PutValue(pantographUnit->pantographAir.valve.is_disabled ? 1.f : 0.f); } ggPantValvesButton.PutValue(0.5f); // auxiliary compressor - ggPantCompressorValve.PutValue(controlled->bPantKurek3 ? 0.f : // default setting is pantographs connected with primary tank + ggPantCompressorValve.PutValue(controlled->pantographAir.connectedToMainReservoir ? 0.f : // default setting is pantographs connected with primary tank 1.f); - ggPantCompressorButton.PutValue(pantographUnit->PantCompFlag ? 1.f : 0.f); + ggPantCompressorButton.PutValue(pantographUnit->pantographAir.compressorRunning ? 1.f : 0.f); // converter if (occupied->ConvSwitchType != "impulse") { @@ -1652,10 +1652,10 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con std::unordered_map const autoboolgauges = { {"doormode_sw:", &occupied->Doors.remote_only}, {"coolingfans_sw:", &controlled->RVentForceOn}, - {"pantfront_sw:", &pantographUnit->Pantographs[VehicleEnd::front].valve.is_enabled}, - {"pantrear_sw:", &pantographUnit->Pantographs[VehicleEnd::rear].valve.is_enabled}, - {"pantfrontoff_sw:", &pantographUnit->Pantographs[VehicleEnd::front].valve.is_disabled}, - {"pantrearoff_sw:", &pantographUnit->Pantographs[VehicleEnd::rear].valve.is_disabled}, + {"pantfront_sw:", &pantographUnit->pantographs[VehicleEnd::front].valve.is_enabled}, + {"pantrear_sw:", &pantographUnit->pantographs[VehicleEnd::rear].valve.is_enabled}, + {"pantfrontoff_sw:", &pantographUnit->pantographs[VehicleEnd::front].valve.is_disabled}, + {"pantrearoff_sw:", &pantographUnit->pantographs[VehicleEnd::rear].valve.is_disabled}, {"radio_sw:", &occupied->Radio}, {"radiofuse_sw:", &occupied->RadioFuse}, {"cablight_sw:", &Cabine[iCabn].bLight}, @@ -1678,7 +1678,7 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con // TODO: move viable dedicated gauges to the automatic array std::unordered_map const autointgauges = { {"manualbrake:", &occupied->brakes.handBrakePosition}, - {"pantselect_sw:", &occupied->PantsPreset.second[cab_to_end()]}, + {"pantselect_sw:", &occupied->pantographCircuit.presets.second[cab_to_end()]}, }; { auto lookup = autointgauges.find(Label); @@ -1845,7 +1845,7 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con // manometr zbiornika kontrolnego/rorzďż˝du auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&pantographUnit->PantPress); + gauge.AssignDouble(&pantographUnit->pantographAir.pressure); } else if (Label == "springbrakepress:") { @@ -1901,7 +1901,7 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con // pantograph tank pressure auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&pantographUnit->PantPress); + gauge.AssignDouble(&pantographUnit->pantographAir.pressure); } // yB - dla drugiej sekcji else if (Label == "hvbcurrent1:") diff --git a/vehicle/cab/train.cpp b/vehicle/cab/train.cpp index a805f7a06..2a54c74f7 100644 --- a/vehicle/cab/train.cpp +++ b/vehicle/cab/train.cpp @@ -180,7 +180,7 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("converter", occupied->Power110vIsAvailable); dict->insert("converter_overload", controlled->ConvOvldFlag); dict->insert("compress", controlled->air.compressor.running); - dict->insert("pant_compressor", pantographUnit->PantCompFlag); + dict->insert("pant_compressor", pantographUnit->pantographAir.compressorRunning); dict->insert("lights_front", occupied->iLights[VehicleEnd::front]); dict->insert("lights_rear", occupied->iLights[VehicleEnd::rear]); dict->insert("off_from_dimmer", occupied->currentDimPosition().isOff); @@ -242,7 +242,7 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("ca", occupied->SecuritySystem.is_vigilance_blinking()); dict->insert("shp", occupied->SecuritySystem.is_cabsignal_blinking()); dict->insert("distance_counter", m_distancecounter); - dict->insert("pantpress", std::abs(pantographUnit->PantPress)); + dict->insert("pantpress", std::abs(pantographUnit->pantographAir.pressure)); dict->insert("universal3", InstrumentLightActive); for (auto idx = 0; idx < ggUniversals.size(); idx++) { @@ -267,7 +267,7 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("odometer", occupied->DistCounter); // distance run in the session, km dict->insert("odometer_total", occupied->Odometer.km); // the vehicle's odometer, kept between the sessions // electric current data - dict->insert("traction_voltage", std::abs(pantographUnit->PantographVoltage)); + dict->insert("traction_voltage", std::abs(pantographUnit->pantographCircuit.supplyVoltage)); dict->insert("voltage", std::abs(controlled->EngineVoltage)); dict->insert("im", std::abs(controlled->Im)); dict->insert("fuse", controlled->FuseFlag); @@ -414,7 +414,7 @@ TTrain::state_t TTrain::get_state() const static_cast(occupied->air.mainReservoirPressure), static_cast(occupied->brakePipe.pressure), static_cast(occupied->brakes.cylinderPressure), - static_cast(pantographUnit->PantPress), + static_cast(pantographUnit->pantographAir.pressure), fHVoltage, {fHCurrent[controlled->TrainType == train_type::emu ? 0 : 1], fHCurrent[2], fHCurrent[3]}, ggLVoltage.GetValue(), diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index 5427dc0b5..0594899ee 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -361,7 +361,7 @@ void TTrain::updateVoltagesAndCurrents() // Ra 2014-09: napięcia i prądy muszą być ustalone najpierw, bo wysyłane są ewentualnie na PoKeys if (controlled->EngineType != TEngineType::DieselElectric && controlled->EngineType != TEngineType::ElectricInductionMotor) { // Ra 2014-09: czy taki rozdzia? ma sens? - fHVoltage = static_cast(std::max(controlled->PantographVoltage, + fHVoltage = static_cast(std::max(controlled->pantographCircuit.supplyVoltage, controlled->GetTrainsetHighVoltage())); // Winger czy to nie jest zle? } // *controlled->Mains); @@ -452,8 +452,8 @@ void TTrain::updateUnitStates() asCarName[i] = p->name(); if (p->physics->EnginePowerSource.SourceType == TPowerSource::CurrentCollector && iUnitNo <= 8) { - bPants[iUnitNo - 1][VehicleEnd::front] = bPants[iUnitNo - 1][VehicleEnd::front] || p->physics->Pantographs[VehicleEnd::front].is_active; - bPants[iUnitNo - 1][VehicleEnd::rear] = bPants[iUnitNo - 1][VehicleEnd::rear] || p->physics->Pantographs[VehicleEnd::rear].is_active; + bPants[iUnitNo - 1][VehicleEnd::front] = bPants[iUnitNo - 1][VehicleEnd::front] || p->physics->pantographs[VehicleEnd::front].is_active; + bPants[iUnitNo - 1][VehicleEnd::rear] = bPants[iUnitNo - 1][VehicleEnd::rear] || p->physics->pantographs[VehicleEnd::rear].is_active; } // TBD, TODO: clean up compressor data arrangement? if (iUnitNo <= 8) diff --git a/vehicle/doorwings.h b/vehicle/doorwings.h index 4c9304445..259c85575 100644 --- a/vehicle/doorwings.h +++ b/vehicle/doorwings.h @@ -24,7 +24,7 @@ http://mozilla.org/MPL/2.0/. // in the main model and, when the low poly interior has a submodel of the same name, in the interior as well namespace door_wings { -// the kinds of wing animation, numbered as DoorOpenMethod of the .fiz (physics::Vehicle::door_data::type) +// the kinds of wing animation, numbered as DoorOpenMethod of the .fiz (physics::door_data::type) inline constexpr int shift_type{1}; inline constexpr int rotate_type{2}; inline constexpr int fold_type{3}; diff --git a/vehicle/dynamic/lifecycle.cpp b/vehicle/dynamic/lifecycle.cpp index 8fbf1592e..ddd6816e5 100644 --- a/vehicle/dynamic/lifecycle.cpp +++ b/vehicle/dynamic/lifecycle.cpp @@ -354,8 +354,8 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" physics->brakePipe.pressure = 0.0; physics->mainPipe.reservoir->CreatePress(0.0); physics->mainPipe.pressure = 0.0; - physics->PantVolume = 0.1; - physics->PantPress = 0.0; + physics->pantographAir.volume = 0.1; + physics->pantographAir.pressure = 0.0; physics->air.compressedVolume = 0.0; } diff --git a/vehicle/dynamic/sounds.cpp b/vehicle/dynamic/sounds.cpp index a99610a14..d83e3afca 100644 --- a/vehicle/dynamic/sounds.cpp +++ b/vehicle/dynamic/sounds.cpp @@ -117,7 +117,7 @@ void TDynamicObject::renderAuxiliarySounds() { // NBMX dzwiek przetwornicy if( physics->ConverterFlag ) { if( physics->EngineType == TEngineType::ElectricSeriesMotor ) { - auto const voltage { std::max( physics->GetTrainsetHighVoltage(), physics->PantographVoltage ) }; + auto const voltage { std::max( physics->GetTrainsetHighVoltage(), physics->pantographCircuit.supplyVoltage ) }; if( voltage > 0.0 ) { // NOTE: we do sound modulation here to avoid sudden jump on voltage loss frequency = voltage / (physics->NominalVoltage * physics->RList[physics->RlistSize].Mn); @@ -187,7 +187,7 @@ void TDynamicObject::renderAuxiliarySounds() { } // Winger 160404 - dzwiek malej sprezarki - if( physics->PantCompFlag ) { + if( physics->pantographAir.compressorRunning ) { sSmallCompressor.play( sound_flags::exclusive | sound_flags::looping ); } else { diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index 8a74d47f5..2ec42d52c 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -257,7 +257,7 @@ void TDynamicObject::updateTractionVoltage( double const dt1 ) // napiecie sieci trakcyjnej if (physics->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) { // dla EZT tylko silnikowy - tmpTraction.TractionVoltage = std::max( std::abs( physics->PantRearVolt ), std::abs( physics->PantFrontVolt ) ); + tmpTraction.TractionVoltage = std::max( std::abs( physics->pantographCircuit.rearVoltage ), std::abs( physics->pantographCircuit.frontVoltage ) ); // jeśli brak zasilania dłużej niż 0.2 sekundy (25km/h pod izolatorem daje 0.15s) // Ra 2F1H: prowizorka, trzeba przechować napięcie, żeby nie wywalało WS pod izolatorem if( tmpTraction.TractionVoltage > 0.0) { @@ -266,14 +266,14 @@ void TDynamicObject::updateTractionVoltage( double const dt1 ) else { NoVoltTime += dt1; if( NoVoltTime <= 0.2 ) { - tmpTraction.TractionVoltage = physics->PantographVoltage; + tmpTraction.TractionVoltage = physics->pantographCircuit.supplyVoltage; } else { // jeśli jedzie if( physics->Vel > 0.5 ) { // Ra 2014-07: doraźna blokada logowania zimnych lokomotyw - zrobić to trzeba inaczej - if( physics->Pantographs[VehicleEnd::front].is_active - || physics->Pantographs[VehicleEnd::rear].is_active ) { + if( physics->pantographs[VehicleEnd::front].is_active + || physics->pantographs[VehicleEnd::rear].is_active ) { if( physics->Mains // Ra 15-01: logować tylko, jeśli WS załączony && physics->GetTrainsetHighVoltage() < 0.1f // yB 16-03: i nie jest to asynchron zasilany z daleka && false == physics->GensetSelected() ) { // nor a dual-mode vehicle running on its genset @@ -295,7 +295,7 @@ void TDynamicObject::updateTractionVoltage( double const dt1 ) tmpTraction.TractionMaxCurrent = 7500; // Ra: chyba za dużo? powinno wywalać przy 1500 tmpTraction.TractionResistivity = 0.3; - physics->PantographVoltage = tmpTraction.TractionVoltage; + physics->pantographCircuit.supplyVoltage = tmpTraction.TractionVoltage; } // the driver of the vehicle: the integrated controller, the brakes blended over a consist with induction motors, the AI @@ -938,7 +938,7 @@ void TDynamicObject::updateCurrentCollectors( double const dt1 ) } else { if( pantograph->hvPowerWire != nullptr - && true == physics->Pantographs[PantographEnd( idx )].is_active + && true == physics->pantographs[PantographEnd( idx )].is_active && pantograph->PantTraction - pantograph->PantWys < 0.01 ) { // tolerancja niedolegania ++activepantographs; } @@ -1037,8 +1037,8 @@ void TDynamicObject::updateCurrentCollectors( double const dt1 ) if (physics->EnginePowerSource.SourceType == TPowerSource::CurrentCollector && physics->EnginePowerSource.CollectorParameters.FakePower) { - physics->PantRearVolt = 0.95 * physics->EnginePowerSource.MaxVoltage; - physics->PantFrontVolt = 0.95 * physics->EnginePowerSource.MaxVoltage; + physics->pantographCircuit.rearVoltage = 0.95 * physics->EnginePowerSource.MaxVoltage; + physics->pantographCircuit.frontVoltage = 0.95 * physics->EnginePowerSource.MaxVoltage; } } @@ -1059,9 +1059,9 @@ void TDynamicObject::updatePantograph( int const i, double const fPantCurrent, d if (p->fAngleU > M_PI) p->fAngleU = M_PI; if (i & 1) // zgłoszono, że po połamaniu potrafi zostać zasilanie - physics->PantRearVolt = 0.0; + physics->pantographCircuit.rearVoltage = 0.0; else - physics->PantFrontVolt = 0.0; + physics->pantographCircuit.frontVoltage = 0.0; return; // reszta wtedy nie jest wykonywana } PantDiff = p->PantTraction - p->PantWys; // docelowy-aktualny @@ -1078,30 +1078,30 @@ void TDynamicObject::updatePantographVoltage( int const i, TAnimPant const *p, d if (Global.bLiveTraction == false && p->hvPowerWire == nullptr ) { // jeśli nie ma drutu, może pooszukiwać - physics->PantFrontVolt = + physics->pantographCircuit.frontVoltage = p->PantWys >= 1.2 ? 0.95 * physics->EnginePowerSource.MaxVoltage : 0.0; } - else if( true == physics->Pantographs[VehicleEnd::front].is_active + else if( true == physics->pantographs[VehicleEnd::front].is_active && PantDiff < 0.01 ) // tolerancja niedolegania { if (p->hvPowerWire) { - auto const lastvoltage { physics->PantFrontVolt }; + auto const lastvoltage { physics->pantographCircuit.frontVoltage }; // TODO: wyliczyć trzeba prąd przypadający na pantograf i wstawić do GetVoltage() if( lastvoltage == 0.0 ) { // HACK: retrieve the wire voltage for calculations down the road without blowing up the supply - physics->PantFrontVolt = p->hvPowerWire->VoltageGet( physics->PantographVoltage, 0.0 ); + physics->pantographCircuit.frontVoltage = p->hvPowerWire->VoltageGet( physics->pantographCircuit.supplyVoltage, 0.0 ); } else { - physics->PantFrontVolt = p->hvPowerWire->VoltageGet( physics->PantographVoltage, fPantCurrent ); - if( physics->PantFrontVolt > 0.0 ) { + physics->pantographCircuit.frontVoltage = p->hvPowerWire->VoltageGet( physics->pantographCircuit.supplyVoltage, fPantCurrent ); + if( physics->pantographCircuit.frontVoltage > 0.0 ) { fCurrent -= fPantCurrent; // taki prąd płynie przez powyższy pantograf (unless it doesn't) } } // TODO: refactor reaction to voltage change to physics as sound event for specific pantograph if( lastvoltage == 0.0 - && physics->PantFrontVolt > 0.0 ) { + && physics->pantographCircuit.frontVoltage > 0.0 ) { for( auto &pantograph : m_pantographsounds ) { if( pantograph.sPantUp.offset().z > 0 ) { // limit to pantographs located in the front half of the vehicle @@ -1111,40 +1111,40 @@ void TDynamicObject::updatePantographVoltage( int const i, TAnimPant const *p, d } } else - physics->PantFrontVolt = 0.0; + physics->pantographCircuit.frontVoltage = 0.0; } else - physics->PantFrontVolt = 0.0; - ( fPantCurrent > 0.0 ? physics->EnergyMeter.first : physics->EnergyMeter.second ) += physics->PantFrontVolt * fPantCurrent * dt1 / 3600000.0; + physics->pantographCircuit.frontVoltage = 0.0; + ( fPantCurrent > 0.0 ? physics->EnergyMeter.first : physics->EnergyMeter.second ) += physics->pantographCircuit.frontVoltage * fPantCurrent * dt1 / 3600000.0; break; case 1: if( false == Global.bLiveTraction && nullptr == p->hvPowerWire ) { // jeśli nie ma drutu, może pooszukiwać - physics->PantRearVolt = + physics->pantographCircuit.rearVoltage = p->PantWys >= 1.2 ? 0.95 * physics->EnginePowerSource.MaxVoltage : 0.0; } - else if ( true == physics->Pantographs[VehicleEnd::rear].is_active + else if ( true == physics->pantographs[VehicleEnd::rear].is_active && PantDiff < 0.01 ) { if (p->hvPowerWire) { - auto const lastvoltage { physics->PantRearVolt }; + auto const lastvoltage { physics->pantographCircuit.rearVoltage }; // TODO: wyliczyć trzeba prąd przypadający na pantograf i wstawić do GetVoltage() if( lastvoltage == 0.0 ) { // HACK: retrieve the wire voltage for calculations down the road without blowing up the supply - physics->PantRearVolt = p->hvPowerWire->VoltageGet( physics->PantographVoltage, 0.0 ); + physics->pantographCircuit.rearVoltage = p->hvPowerWire->VoltageGet( physics->pantographCircuit.supplyVoltage, 0.0 ); } else { - physics->PantRearVolt = p->hvPowerWire->VoltageGet( physics->PantographVoltage, fPantCurrent ); - if( physics->PantRearVolt > 0.0 ) { + physics->pantographCircuit.rearVoltage = p->hvPowerWire->VoltageGet( physics->pantographCircuit.supplyVoltage, fPantCurrent ); + if( physics->pantographCircuit.rearVoltage > 0.0 ) { fCurrent -= fPantCurrent; // taki prąd płynie przez powyższy pantograf (unless it doesn't) } } // TODO: refactor reaction to voltage change to physics as sound event for specific pantograph if( lastvoltage == 0.0 - && physics->PantRearVolt > 0.0 ) { + && physics->pantographCircuit.rearVoltage > 0.0 ) { for( auto &pantograph : m_pantographsounds ) { if( pantograph.sPantUp.offset().z < 0 ) { // limit to pantographs located in the rear half of the vehicle @@ -1154,13 +1154,13 @@ void TDynamicObject::updatePantographVoltage( int const i, TAnimPant const *p, d } } else - physics->PantRearVolt = 0.0; + physics->pantographCircuit.rearVoltage = 0.0; } else { // Global.iPause ^= 2; - physics->PantRearVolt = 0.0; + physics->pantographCircuit.rearVoltage = 0.0; } - ( fPantCurrent > 0.0 ? physics->EnergyMeter.first : physics->EnergyMeter.second ) += physics->PantRearVolt * fPantCurrent * dt1 / 3600000.0; + ( fPantCurrent > 0.0 ? physics->EnergyMeter.first : physics->EnergyMeter.second ) += physics->pantographCircuit.rearVoltage * fPantCurrent * dt1 / 3600000.0; break; } // pozostałe na razie nie obsługiwane } @@ -1169,13 +1169,13 @@ void TDynamicObject::updatePantographVoltage( int const i, TAnimPant const *p, d void TDynamicObject::updatePantographMotion( int const i, TAnimPant *p, double const PantDiff, double const dt1 ) { double k; // tymczasowy kąt - if( physics->PantPress > ( + if( physics->pantographAir.pressure > ( physics->TrainType == train_type::emu ? 2.45 : // Ra 2013-12: Niebugocław mówi, że w EZT podnoszą się przy 2.5 3.45 ) ) { // z EXE Kursa // Ra: wysokość zależy od ciśnienia !!! - pantspeedfactor = 0.015 * physics->PantPress * dt1; + pantspeedfactor = 0.015 * physics->pantographAir.pressure * dt1; } else { pantspeedfactor = 0.0; @@ -1186,7 +1186,7 @@ void TDynamicObject::updatePantographMotion( int const i, TAnimPant *p, double c pantspeedfactor = std::max( 0.0, pantspeedfactor ); k = p->fAngleL; if( pantspeedfactor > 0.0 - && physics->Pantographs[i].is_active )// jeśli ma być podniesiony + && physics->pantographs[i].is_active )// jeśli ma być podniesiony { if (PantDiff > 0.001) // jeśli nie dolega do drutu { // jeśli poprzednia wysokość jest mniejsza niż pożądana, zwiększyć kąt dolnego @@ -1235,8 +1235,8 @@ void TDynamicObject::updatePantographMotion( int const i, TAnimPant *p, double c void TDynamicObject::playPantographDropSounds() { // TBD, TODO: generate sound event during physics update instead? - if( physics->Pantographs[VehicleEnd::front].sound_event != physics->Pantographs[ VehicleEnd::front ].is_active ) { - if( physics->Pantographs[ VehicleEnd::front ].is_active ) { + if( physics->pantographs[VehicleEnd::front].sound_event != physics->pantographs[ VehicleEnd::front ].is_active ) { + if( physics->pantographs[ VehicleEnd::front ].is_active ) { // pantograph moving up // TBD: add a sound? } @@ -1249,10 +1249,10 @@ void TDynamicObject::playPantographDropSounds() } } } - physics->Pantographs[ VehicleEnd::front ].sound_event = physics->Pantographs[ VehicleEnd::front ].is_active; + physics->pantographs[ VehicleEnd::front ].sound_event = physics->pantographs[ VehicleEnd::front ].is_active; } - if( physics->Pantographs[ VehicleEnd::rear ].sound_event != physics->Pantographs[ VehicleEnd::rear ].is_active ) { - if( physics->Pantographs[ VehicleEnd::rear ].is_active ) { + if( physics->pantographs[ VehicleEnd::rear ].sound_event != physics->pantographs[ VehicleEnd::rear ].is_active ) { + if( physics->pantographs[ VehicleEnd::rear ].is_active ) { // pantograph moving up // TBD: add a sound? } @@ -1265,7 +1265,7 @@ void TDynamicObject::playPantographDropSounds() } } } - physics->Pantographs[ VehicleEnd::rear ].sound_event = physics->Pantographs[ VehicleEnd::rear ].is_active; + physics->pantographs[ VehicleEnd::rear ].sound_event = physics->pantographs[ VehicleEnd::rear ].is_active; } } @@ -1394,7 +1394,7 @@ void TDynamicObject::pants_up() TDynamicObject *d = this; bool isAnyPantUp = false; while (d) { - for (auto &item : d->physics->Pantographs) + for (auto &item : d->physics->pantographs) { isAnyPantUp |= item.is_active; } @@ -1402,7 +1402,7 @@ void TDynamicObject::pants_up() } d = Prev(Coupling::control); while (d) { - for (auto &item : d->physics->Pantographs) + for (auto &item : d->physics->pantographs) { isAnyPantUp |= item.is_active; } diff --git a/vehicle/dynamic/vehicletable.cpp b/vehicle/dynamic/vehicletable.cpp index 6fb994068..447579c9d 100644 --- a/vehicle/dynamic/vehicletable.cpp +++ b/vehicle/dynamic/vehicletable.cpp @@ -724,7 +724,7 @@ vehicle_table::update_traction( TDynamicObject *Vehicle ) { for( int pantographindex = 0; pantographindex < Vehicle->iAnimType[ ANIM_PANTS ]; ++pantographindex ) { // pętla po pantografach auto *pantograph { Vehicle->pants[ pantographindex ].fParamPants }; - if( true == Vehicle->physics->Pantographs[ pantographindex ].is_active ) { + if( true == Vehicle->physics->pantographs[ pantographindex ].is_active ) { // jeśli pantograf podniesiony auto const pant0 { position + vLeft * pantograph->vPos.z + vUp * pantograph->vPos.y + vFront * pantograph->vPos.x }; if( pantograph->hvPowerWire != nullptr ) { diff --git a/widgets/vehicleparams.cpp b/widgets/vehicleparams.cpp index b53f23f01..edc3568b7 100644 --- a/widgets/vehicleparams.cpp +++ b/widgets/vehicleparams.cpp @@ -63,9 +63,9 @@ void ui::vehicleparams_panel::draw_mini(const physics::Vehicle &physics) { ImGui::Image((ImTextureID)(intptr_t)(tex.get_id()), ImVec2(x, y), ImVec2(0, 1), ImVec2(1, 0)); - if (physics.Pantographs[VehicleEnd::rear].is_active) + if (physics.pantographs[VehicleEnd::rear].is_active) draw_infobutton("╨╨╨", ImVec2(126, 10)); - if (physics.Pantographs[VehicleEnd::front].is_active) + if (physics.pantographs[VehicleEnd::front].is_active) draw_infobutton("╨╨╨", ImVec2(290, 10)); if (physics.Battery) @@ -148,8 +148,8 @@ void ui::vehicleparams_panel::render_contents() std::snprintf(buffer.data(), buffer.size(), STR_C("Devices: %c%c%c%c%c%c%c%c%c%c%c%c%c%c%s%s\nPower transfers: %.0f@%.0f%s%s%s%.0f@%.0f"), // devices - (physics.Battery ? 'B' : '.'), (physics.Mains ? 'M' : '.'), (physics.FuseFlag ? '!' : '.'), (physics.Pantographs[VehicleEnd::rear].is_active ? (physics.PantRearVolt > 0.0 ? 'O' : 'o') : '.'), - (physics.Pantographs[VehicleEnd::front].is_active ? (physics.PantFrontVolt > 0.0 ? 'P' : 'p') : '.'), (physics.PantPressLockActive ? '!' : (physics.PantPressSwitchActive ? '*' : '.')), + (physics.Battery ? 'B' : '.'), (physics.Mains ? 'M' : '.'), (physics.FuseFlag ? '!' : '.'), (physics.pantographs[VehicleEnd::rear].is_active ? (physics.pantographCircuit.rearVoltage > 0.0 ? 'O' : 'o') : '.'), + (physics.pantographs[VehicleEnd::front].is_active ? (physics.pantographCircuit.frontVoltage > 0.0 ? 'P' : 'p') : '.'), (physics.pantographAir.pressureLockActive ? '!' : (physics.pantographAir.pressureSwitchActive ? '*' : '.')), (physics.WaterPump.is_active ? 'W' : (false == physics.WaterPump.breaker ? '-' : (physics.WaterPump.is_enabled ? 'w' : '.'))), (true == physics.WaterHeater.is_damaged ? '!' : (physics.WaterHeater.is_active ? 'H' : (false == physics.WaterHeater.breaker ? '-' : (physics.WaterHeater.is_enabled ? 'h' : '.')))), (physics.FuelPump.is_active ? 'F' : (physics.FuelPump.is_enabled ? 'f' : '.')), (physics.OilPump.is_active ? 'O' : (physics.OilPump.is_enabled ? 'o' : '.')), @@ -213,7 +213,7 @@ void ui::vehicleparams_panel::render_contents() if (physics.EnginePowerSource.SourceType == TPowerSource::CurrentCollector) { - std::snprintf(buffer.data(), buffer.size(), STR_C(" pantograph: %.2f%cMT"), physics.PantPress, (physics.bPantKurek3 ? '-' : '|')); + std::snprintf(buffer.data(), buffer.size(), STR_C(" pantograph: %.2f%cMT"), physics.pantographAir.pressure, (physics.pantographAir.connectedToMainReservoir ? '-' : '|')); ImGui::TextUnformatted(buffer.data()); } From 1bea2800103c8095746f00639f1ddf68bd4ecac8 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 02:50:50 +0100 Subject: [PATCH 032/123] refactor(physics): the line breaker, the line contactors, the relays and the converter as components The main circuit of physics::Vehicle becomes components, with English names (physics/components/maincircuit.h): lineBreaker (LineBreaker) Mains closed, MainsInitTime(Countdown) initTime / initCountdown, MainsStart start, JointEngineStart jointStart, PantographsRequireMains pantographsRequireIt, LineBreakerClosesOnlyAtNoPowerPos closesOnlyAtNoPower, EmergencyBrakeMainOffPressure emergencyOffPressure lineContactors (LineContactors) StLinFlag closed, StLinSwitchOff forcedOpen, StLinSwitchType switchType, LineContactorsInterlock interlock, LastRelayTime lastSwitchTime protection (ProtectionRelays) NoVoltRelay noVoltage, OvervoltageRelay overvoltage, GroundRelay(Start) ground(Start), ControlPressureSwitch pressureSwitch, HasControlPressureSwitch hasPressureSwitch, PressureSwitchBrakeCylinder pressureSwitchWatchesCylinders converter (PowerConverter) the Converter* fields: start, startDelay(Timer), allow(Local), running, overloadRelayStart, overloadRelayOffWithLineBreaker; ConvOvldFlag overloaded, ConvSwitchType switchType The long comments of the fields went with them into the header. Where the loading of the .fiz has using enum start_t, the member is this->converter: the enumerator start_t::converter would hide it there. No string literal changed (checked over all the changed files). No change in behaviour: 1149/1149 tests, golden traces exact against staging 62f7a29b. --- application/driverhints.cpp | 10 +-- application/driveruipanels.cpp | 16 ++-- input/messaging.cpp | 4 +- physics/components/commands.cpp | 16 ++-- physics/components/controllers.cpp | 80 ++++++++--------- physics/components/diesel.cpp | 60 ++++++------- physics/components/drive.cpp | 28 +++--- physics/components/electrics.cpp | 90 +++++++++---------- physics/components/fizsections.cpp | 36 ++++---- physics/components/maincircuit.h | 88 ++++++++++++++++++ physics/components/pneumatics.cpp | 4 +- physics/components/traction.cpp | 22 ++--- physics/vehicle.h | 64 +++---------- simulation/blackboxrecorder.cpp | 4 +- tests/unit/drive.cpp | 10 +-- tests/unit/golden.cpp | 2 +- tests/unit/invariants.cpp | 8 +- tests/unit/scenario.cpp | 4 +- tests/unit/test_6dg_power_steps.cpp | 4 +- tests/unit/test_auxiliaries.cpp | 8 +- tests/unit/test_camshaft.cpp | 10 +-- tests/unit/test_cntrl.cpp | 12 +-- tests/unit/test_collisions.cpp | 4 +- tests/unit/test_commands.cpp | 10 +-- tests/unit/test_compressor.cpp | 30 +++---- tests/unit/test_crew.cpp | 6 +- tests/unit/test_derailment_vehicle.cpp | 2 +- tests/unit/test_engine_shutdown.cpp | 10 +-- tests/unit/test_engine_start.cpp | 34 +++---- tests/unit/test_field_shunting.cpp | 4 +- tests/unit/test_genset.cpp | 46 +++++----- tests/unit/test_line_contactors.cpp | 32 +++---- tests/unit/test_line_contactors_interlock.cpp | 60 ++++++------- tests/unit/test_linebreaker.cpp | 22 ++--- tests/unit/test_mains_before_pantographs.cpp | 86 +++++++++--------- tests/unit/test_oil_pump.cpp | 4 +- tests/unit/test_pressure_switch.cpp | 76 ++++++++-------- tests/unit/test_smoke.cpp | 6 +- tests/unit/test_speed_control.cpp | 10 +-- tests/unit/test_traction.cpp | 8 +- vehicle/ai/consist.cpp | 14 +-- vehicle/ai/controls.cpp | 18 ++-- vehicle/ai/engine.cpp | 6 +- vehicle/ai/situation.cpp | 4 +- vehicle/cab/auxiliarycommands.cpp | 16 ++-- vehicle/cab/powercommands.cpp | 14 +-- vehicle/cab/setup.cpp | 8 +- vehicle/cab/train.cpp | 12 +-- vehicle/cab/update.cpp | 62 ++++++------- vehicle/dynamic/sounds.cpp | 12 +-- vehicle/dynamic/update.cpp | 12 +-- vehicle/enginestart.cpp | 2 +- widgets/vehicleparams.cpp | 8 +- 53 files changed, 632 insertions(+), 586 deletions(-) create mode 100644 physics/components/maincircuit.h diff --git a/application/driverhints.cpp b/application/driverhints.cpp index ecd311e9e..661f4d33d 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -181,7 +181,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) Action, [this](float const /*Parameter*/) { auto const &device { occupied->OilPump }; - return device.start_type != start_t::manual || device.is_enabled == true || device.is_active == true || occupied->Mains; } ); + return device.start_type != start_t::manual || device.is_enabled == true || device.is_active == true || occupied->lineBreaker.closed; } ); break; } case driver_hint::oilpumpoff: { @@ -334,7 +334,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) []( TDynamicObject * Vehicle ) { auto *vehicle { Vehicle->physics }; if( vehicle->LineContactorsHeldByLocalConverterSwitch() ) { - vehicle->ConverterAllowLocal = true; } } ); + vehicle->converter.allowLocal = true; } } ); } remove_hint( driver_hint::converteroff ); hint( @@ -362,7 +362,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return occupied->ConverterOverloadRelayStart != start_t::manual || occupied->ConvOvldFlag == false; } ); + return occupied->converter.overloadRelayStart != start_t::manual || occupied->converter.overloaded == false; } ); break; } case driver_hint::maincircuitgroundreset: { @@ -372,7 +372,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return occupied->GroundRelayStart != start_t::manual || occupied->GroundRelay == true; } ); + return occupied->protection.groundStart != start_t::manual || occupied->protection.ground == true; } ); break; } case driver_hint::tractionnmotoroverloadreset: { @@ -406,7 +406,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) Action, [this](float const /*Parameter*/) { // TBD, TODO: replace with consist-wide flag set true if any line breaker is closed? - return mvControlling->Mains == false; } ); + return mvControlling->lineBreaker.closed == false; } ); break; } // compressor diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 21cfa1030..8ec1a9997 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -842,21 +842,21 @@ debug_panel::update_section_vehicle( std::vector &Output ) { physics.OilPump.is_active ? 'O' : physics.OilPump.is_enabled ? 'o' : '.', - physics.Mains ? 'M' : '.', + physics.lineBreaker.closed ? 'M' : '.', physics.FuseFlag ? '!' : '.', - physics.ConverterFlag ? 'X' : - false == physics.ConverterAllowLocal ? '-' : - physics.ConverterAllow ? 'x' : + physics.converter.running ? 'X' : + false == physics.converter.allowLocal ? '-' : + physics.converter.allow ? 'x' : '.', - physics.ConvOvldFlag ? '!' : '.', + physics.converter.overloaded ? '!' : '.', physics.air.compressor.running ? 'C' : false == physics.air.compressor.allowLocal ? '-' : physics.air.compressor.allow || (physics.air.compressor.start == start_t::automatic && physics.air.compressor.speed > 0.0) ? 'c' : '.', physics.air.compressor.governorLock ? '!' : '.', - physics.StLinSwitchOff ? '-' : - physics.ControlPressureSwitch ? '!' : - physics.StLinFlag ? '+' : + physics.lineContactors.forcedOpen ? '-' : + physics.protection.pressureSwitch ? '!' : + physics.lineContactors.closed ? '+' : '.', physics.Heating ? 'H' : physics.HeatingAllow ? 'h' : diff --git a/input/messaging.cpp b/input/messaging.cpp index c7950c737..283bd15e8 100644 --- a/input/messaging.cpp +++ b/input/messaging.cpp @@ -295,9 +295,9 @@ WyslijNamiary([[maybe_unused]] TDynamicObject const *Vehicle) r.iPar[20] = Vehicle->physics->ScndCtrlActualPos; // Pozycja bocznikowania r.iPar[21] = Vehicle->physics->ScndCtrlActualPos; // Pozycja bocznikowania r.iPar[22] = Vehicle->physics->ResistorsFlag * 1 - + Vehicle->physics->ConverterFlag * 2 + + Vehicle->physics->converter.running * 2 + Vehicle->physics->air.compressor.running * 4 - + Vehicle->physics->Mains * 8 + + Vehicle->physics->lineBreaker.closed * 8 #ifdef EU07_USEOLDDOORCODE + Vehicle->physics->DoorLeftOpened * 16 + Vehicle->physics->DoorRightOpened * 32 diff --git a/physics/components/commands.cpp b/physics/components/commands.cpp index 51b577a2b..42c0885da 100644 --- a/physics/components/commands.cpp +++ b/physics/components/commands.cpp @@ -144,11 +144,11 @@ bool physics::Vehicle::RunControllerCommand(VehicleCommand const Command, double MainCtrlPos = position; if (DelayCtrlFlag) { - if (LastRelayTime >= InitialCtrlDelay && MainCtrlPos == 1) - LastRelayTime = 0; + if (lineContactors.lastSwitchTime >= InitialCtrlDelay && MainCtrlPos == 1) + lineContactors.lastSwitchTime = 0; } - else if (LastRelayTime > CtrlDelay) - LastRelayTime = 0; + else if (lineContactors.lastSwitchTime > CtrlDelay) + lineContactors.lastSwitchTime = 0; } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } @@ -157,8 +157,8 @@ bool physics::Vehicle::RunControllerCommand(VehicleCommand const Command, double if (ScndCtrlPosNo >= floor(CValue1)) { ScndCtrlPos = static_cast(floor(CValue1)); - if (LastRelayTime > CtrlDelay) - LastRelayTime = 0; + if (lineContactors.lastSwitchTime > CtrlDelay) + lineContactors.lastSwitchTime = 0; } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } @@ -364,9 +364,9 @@ bool physics::Vehicle::RunAuxiliariesCommand(VehicleCommand const Command, doubl } else if (Command == VehicleCommand::converterSwitch) /*NBMX*/ { - if (ConverterStart == start_t::manual) + if (converter.start == start_t::manual) { - ConverterAllow = CValue1 > 0.0; + converter.allow = CValue1 > 0.0; } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } diff --git a/physics/components/controllers.cpp b/physics/components/controllers.cpp index d68f39594..ea780ab4e 100644 --- a/physics/components/controllers.cpp +++ b/physics/components/controllers.cpp @@ -97,11 +97,11 @@ bool physics::Vehicle::IncMainCtrl(int CtrlSpeed) { if (DelayCtrlFlag) { - if (LastRelayTime >= InitialCtrlDelay && MainCtrlPos == 1) - LastRelayTime = 0; + if (lineContactors.lastSwitchTime >= InitialCtrlDelay && MainCtrlPos == 1) + lineContactors.lastSwitchTime = 0; } - else if (LastRelayTime > CtrlDelay) - LastRelayTime = 0; + else if (lineContactors.lastSwitchTime > CtrlDelay) + lineContactors.lastSwitchTime = 0; } return OK; } @@ -226,11 +226,11 @@ bool physics::Vehicle::DecMainCtrl(int CtrlSpeed) { if (DelayCtrlFlag) { - if (LastRelayTime >= InitialCtrlDelay) - LastRelayTime = 0; + if (lineContactors.lastSwitchTime >= InitialCtrlDelay) + lineContactors.lastSwitchTime = 0; } - else if (LastRelayTime > CtrlDownDelay) - LastRelayTime = 0; + else if (lineContactors.lastSwitchTime > CtrlDownDelay) + lineContactors.lastSwitchTime = 0; } return OK; } @@ -363,7 +363,7 @@ bool physics::Vehicle::IncScndCtrl(int CtrlSpeed) // TBD, TODO: refactor this validation as part of relay check routine (currently in tractionforce() // TBD, TODO: diesel electric engine utilize scndctrlactualpos like the other types? if (EngineType == TEngineType::DieselElectric && - (IsMainCtrlNoPowerPos() || fieldshunting::diesel_electric(AutoRelayType, FieldShuntSwitch, AutoRelayFlag) != fieldshunting::control::manual || ShuntMode || false == Mains)) + (IsMainCtrlNoPowerPos() || fieldshunting::diesel_electric(AutoRelayType, FieldShuntSwitch, AutoRelayFlag) != fieldshunting::control::manual || ShuntMode || false == lineBreaker.closed)) { OK = false; } @@ -392,8 +392,8 @@ bool physics::Vehicle::IncScndCtrl(int CtrlSpeed) OK = false; // if OK then LastRelayTime:=0; // hunter-101012: poprawka - if (OK && LastRelayTime > CtrlDelay) - LastRelayTime = 0; + if (OK && lineContactors.lastSwitchTime > CtrlDelay) + lineContactors.lastSwitchTime = 0; if (OK && EngineType == TEngineType::ElectricInductionMotor && ScndCtrlPosNo == 1 && MainCtrlPos > 0) { @@ -454,8 +454,8 @@ bool physics::Vehicle::DecScndCtrl(int CtrlSpeed) OK = false; // if OK then LastRelayTime:=0; // hunter-101012: poprawka - if (OK && LastRelayTime > CtrlDownDelay) - LastRelayTime = 0; + if (OK && lineContactors.lastSwitchTime > CtrlDownDelay) + lineContactors.lastSwitchTime = 0; if (OK && EngineType == TEngineType::ElectricInductionMotor && ScndCtrlPosNo == 1) { @@ -549,7 +549,7 @@ bool physics::Vehicle::AutoRelayCheck(void) // yBARC - rozlaczenie stycznikow liniowych if (motorconnectorsoff || (HasCamshaft ? IsMainCtrlActualNoPowerPos() : IsMainCtrlNoPowerPos())) { - StLinFlag = false; + lineContactors.closed = false; if (false == DynamicBrakeFlag) { Im = 0; @@ -569,7 +569,7 @@ bool physics::Vehicle::AutoRelayCheck(void) // przejście dalej przez danie nastawnika na dalszą pozycję - tak to do // tej pory działało i na tym się opiera fizyka ET22-2k { - if (StLinFlag) + if (lineContactors.closed) { if (RList[MainCtrlActualPos].R == 0 && (ScndCtrlActualPos > 0 || ScndCtrlPos > 0) && (!CoupledCtrl || RList[MainCtrlActualPos].Relay == MainCtrlPos)) { // zmieniaj scndctrlactualpos @@ -585,7 +585,7 @@ bool physics::Vehicle::AutoRelayCheck(void) OK = AutoRelayLineContactorsStep(motorconnectorsoff); } if (OK) - LastRelayTime = 0; + lineContactors.lastSwitchTime = 0; return OK; } @@ -598,7 +598,7 @@ bool physics::Vehicle::AutoRelayShuntStep(bool const ARFASI2) // scnd bez samoczynnego rozruchu if (ScndCtrlActualPos < ScndCtrlPos) { - if (LastRelayTime > CtrlDelay && ARFASI2) + if (lineContactors.lastSwitchTime > CtrlDelay && ARFASI2) { ++ScndCtrlActualPos; SetFlag(SoundFlag, sound::shuntfield); @@ -607,7 +607,7 @@ bool physics::Vehicle::AutoRelayShuntStep(bool const ARFASI2) } else if (ScndCtrlActualPos > ScndCtrlPos) { - if (LastRelayTime > CtrlDownDelay && TrainType != train_type::emu) + if (lineContactors.lastSwitchTime > CtrlDownDelay && TrainType != train_type::emu) { --ScndCtrlActualPos; SetFlag(SoundFlag, sound::shuntfield); @@ -640,7 +640,7 @@ bool physics::Vehicle::AutoRelayMainStep(bool const ARFASI) } else if (RList[MainCtrlActualPos].R > 0 && ScndCtrlActualPos > 0) { - if (LastRelayTime > CtrlDownDelay) + if (lineContactors.lastSwitchTime > CtrlDownDelay) { --ScndCtrlActualPos; // boczniki nie dzialaja na poz. oporowych SetFlag(SoundFlag, sound::shuntfield); @@ -681,7 +681,7 @@ bool physics::Vehicle::AutoRelayMainUp(bool const ARFASI) OK = true; } } - else if (LastRelayTime > CtrlDelay && ARFASI) + else if (lineContactors.lastSwitchTime > CtrlDelay && ARFASI) { OK = AutoRelayMainNotchUp(); } @@ -704,7 +704,7 @@ bool physics::Vehicle::AutoRelayMainNotchUp() DelayCtrlFlag = true; // tryb przejscia OK = true; } - else if (LastRelayTime > 4 * CtrlDelay) // przejscie + else if (lineContactors.lastSwitchTime > 4 * CtrlDelay) // przejscie { DelayCtrlFlag = false; @@ -753,7 +753,7 @@ bool physics::Vehicle::AutoRelayMainDown() SetFlag(SoundFlag, sound::parallel); } } - else if (LastRelayTime > CtrlDownDelay) + else if (lineContactors.lastSwitchTime > CtrlDownDelay) { if (TrainType != train_type::emu) // tutaj powinien być tryb sterowania wałem { @@ -779,9 +779,9 @@ bool physics::Vehicle::AutoRelayLineContactorsStep(bool const motorconnectorsoff { DelayCtrlFlag = true; - if (LastRelayTime >= InitialCtrlDelay) + if (lineContactors.lastSwitchTime >= InitialCtrlDelay) { - StLinFlag = true; + lineContactors.closed = true; MainCtrlActualPos = 1; DelayCtrlFlag = false; SetFlag(SoundFlag, sound::relay | sound::loud); @@ -793,7 +793,7 @@ bool physics::Vehicle::AutoRelayLineContactorsStep(bool const motorconnectorsoff DelayCtrlFlag = false; } - if (false == StLinFlag && (MainCtrlActualPos > 0 || ScndCtrlActualPos > 0)) + if (false == lineContactors.closed && (MainCtrlActualPos > 0 || ScndCtrlActualPos > 0)) { OK |= CamshaftRunDown(); } @@ -813,7 +813,7 @@ bool physics::Vehicle::CamshaftRunDown() { OK = CamshaftRunDownEMU(); } - else if (LastRelayTime > CtrlDownDelay) // wal kulakowy dwukierunkowy + else if (lineContactors.lastSwitchTime > CtrlDownDelay) // wal kulakowy dwukierunkowy { if (ScndCtrlActualPos > 0) { @@ -830,7 +830,7 @@ bool physics::Vehicle::CamshaftRunDown() else if (HasCamshaft) { // wal kulakowy dwukierunkowy - if (LastRelayTime > CtrlDownDelay) + if (lineContactors.lastSwitchTime > CtrlDownDelay) { if (MainCtrlActualPos > 0) { @@ -863,7 +863,7 @@ bool physics::Vehicle::CamshaftRunDownEMU() else { - if (LastRelayTime > CtrlDownDelay) + if (lineContactors.lastSwitchTime > CtrlDownDelay) { if (MainCtrlActualPos < RlistSize) @@ -894,29 +894,29 @@ bool physics::Vehicle::MotorConnectorsCheck() // hunter-111211: wylacznik cisnieniowy // (on some vehicles it watches the brake pipe alone) - ControlPressureSwitch = HasControlPressureSwitch && ((PressureSwitchBrakeCylinder && brakes.cylinderPressure > 2.0) || brakePipe.pressure < 3.6); + protection.pressureSwitch = protection.hasPressureSwitch && ((protection.pressureSwitchWatchesCylinders && brakes.cylinderPressure > 2.0) || brakePipe.pressure < 3.6); - if (true == ControlPressureSwitch) + if (true == protection.pressureSwitch) { return false; } // a line breaker closed ahead of the pantographs holds without voltage; what cuts the motors off there is its // undervoltage relay, which elsewhere opens the line breaker - auto const undervoltage{PantographsRequireMains && false == NoVoltRelay}; + auto const undervoltage{lineBreaker.pantographsRequireIt && false == protection.noVoltage}; - auto const connectorsoff{false == Mains || undervoltage || true == FuseFlag || true == StLinSwitchOff || DirActive == 0}; + auto const connectorsoff{false == lineBreaker.closed || undervoltage || true == FuseFlag || true == lineContactors.forcedOpen || DirActive == 0}; return false == connectorsoff && LineContactorsInterlockReleased(); } bool physics::Vehicle::LineContactorsInterlockReleased() const { - switch (LineContactorsInterlock) + switch (lineContactors.interlock) { case line_contactors_interlock::converter: // the converter of this very vehicle, not the 110 V of the trainset: a section with its fans off doesn't start - return ConverterFlag; + return converter.running; case line_contactors_interlock::motor_blowers: return std::ranges::all_of(MotorBlowers, [this](auto const &Blower) { if (Blower.min_start_velocity < 0) @@ -1092,7 +1092,7 @@ void physics::Vehicle::EIMICFromFourPositions(double dt) // hamowanie nagle: pelne hamowanie od razu, przewod glowny oproznia UpdatePipePressure() eimic = -1.0; } - else if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) + else if (MainCtrlActualPos != MainCtrlPos || lineContactors.lastSwitchTime > InitialCtrlDelay) { double delta = MainCtrlActualPos == MainCtrlPos ? dt * CtrlDelay : 0.01; // the positions below are those of the controller without the emergency brake position @@ -1120,10 +1120,10 @@ void physics::Vehicle::EIMICFromFourPositions(double dt) } } if (MainCtrlActualPos == MainCtrlPos) - LastRelayTime += dt; + lineContactors.lastSwitchTime += dt; else { - LastRelayTime = 0; + lineContactors.lastSwitchTime = 0; MainCtrlActualPos = MainCtrlPos; } } @@ -1136,7 +1136,7 @@ void physics::Vehicle::EIMICFromUniversalController(double dt, double const brak UniversalControllerTrainBrake(); } - if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) + if (MainCtrlActualPos != MainCtrlPos || lineContactors.lastSwitchTime > InitialCtrlDelay) { auto const &position{UniCtrlList[MainCtrlPos]}; double ramped{eimic}; @@ -1148,10 +1148,10 @@ void physics::Vehicle::EIMICFromUniversalController(double dt, double const brak eimic = UniCtrlValStep > 0.0 ? stepped_uc_value(eimic, ramped, position, UniCtrlValStep, MainCtrlActualPos != MainCtrlPos, eimic_step_progress) : ramped; } if (MainCtrlActualPos == MainCtrlPos) - LastRelayTime += dt; + lineContactors.lastSwitchTime += dt; else { - LastRelayTime = 0; + lineContactors.lastSwitchTime = 0; MainCtrlActualPos = MainCtrlPos; } if (brakes.distributor->GetEDBCP() > 0.3 && eimic < 0 && !UniCtrlIntegratedLocalBrakeCtrl) // when braking with pneumatic brake diff --git a/physics/components/diesel.cpp b/physics/components/diesel.cpp index c80ecd863..9ed1ad4ff 100644 --- a/physics/components/diesel.cpp +++ b/physics/components/diesel.cpp @@ -76,8 +76,8 @@ void physics::Vehicle::FuelPumpCheck(double const /*Timestep*/) FuelPump.is_active = true == (Power24vIsAvailable || Power110vIsAvailable) && false == FuelPump.is_disabled && (FuelPump.is_active || (FuelPump.start_type == manual ? FuelPump.is_enabled : - FuelPump.start_type == automatic ? diesel.startupRequested || Mains : - FuelPump.start_type == manualwithautofallback ? FuelPump.is_enabled || diesel.startupRequested || Mains : + FuelPump.start_type == automatic ? diesel.startupRequested || lineBreaker.closed : + FuelPump.start_type == manualwithautofallback ? FuelPump.is_enabled || diesel.startupRequested || lineBreaker.closed : false)); // shouldn't ever get this far but, eh } @@ -85,7 +85,7 @@ void physics::Vehicle::FuelPumpCheck(double const /*Timestep*/) void physics::Vehicle::OilPumpCheck(double const Timestep) { - OilPump.is_active = true == (Power24vIsAvailable || Power110vIsAvailable) && false == Mains && false == OilPump.is_disabled && + OilPump.is_active = true == (Power24vIsAvailable || Power110vIsAvailable) && false == lineBreaker.closed && false == OilPump.is_disabled && (OilPump.is_active || (OilPump.start_type == start_t::manual ? OilPump.is_enabled : OilPump.start_type == start_t::automatic ? diesel.startupRequested : OilPump.start_type == start_t::manualwithautofallback ? OilPump.is_enabled || diesel.startupRequested : @@ -339,7 +339,7 @@ double physics::Vehicle::DieselElectricTargetRevolutions() if (EIMCtrlType > 0) // sterowanie cyfrowe tmp = (DElist[0].RPM + (DElist[MainCtrlPosNo].RPM - DElist[0].RPM) * std::max(0.0, eimic_real)) / 60.0; else - tmp = DElist[ControlPressureSwitch ? MainCtrlNoPowerPos() : MainCtrlPos].RPM / 60.0; + tmp = DElist[protection.pressureSwitch ? MainCtrlNoPowerPos() : MainCtrlPos].RPM / 60.0; if (true == HeatingAllow && HeatingPower > 0 && EngineHeatingRPM > 0) { @@ -399,7 +399,7 @@ void physics::Vehicle::DieselElectricTractionForce(double tmp) PosRatio = currentgenpower / DElist[MainCtrlPosNo].GenPower; // stosunek mocy teraz do mocy max // NOTE: Mains in this context is working diesel engine - if (true == StLinFlag) + if (true == lineContactors.closed) Ft = DieselElectricForce(tmpV, power, PosRatio, tmp); else Ft = 0; // jak nastawnik na zero, to sila tez zero @@ -433,7 +433,7 @@ void physics::Vehicle::DieselElectricTractionForce(double tmp) // przekazniki bocznikowania, kazdy inny dla kazdej pozycji if (auto const fieldshuntingcontrol{fieldshunting::diesel_electric(AutoRelayType, FieldShuntSwitch, AutoRelayFlag)}; - false == StLinFlag || ShuntMode || fieldshuntingcontrol == fieldshunting::control::off) + false == lineContactors.closed || ShuntMode || fieldshuntingcontrol == fieldshunting::control::off) { ScndCtrlPos = 0; } @@ -448,7 +448,7 @@ void physics::Vehicle::DieselElectricTractionForce(double tmp) // tmp, the power the generator gives void physics::Vehicle::DieselElectricShuntForce(double const tmpV, double &tmp) { - if (true == StLinFlag) + if (true == lineContactors.closed) { EngineVoltage = SST[MainCtrlPos].Umax * AnPos + SST[MainCtrlPos].Umin * (1.0 - AnPos); // NOTE: very crude way to approximate power generated at current rpm instead of instant top output @@ -472,7 +472,7 @@ double physics::Vehicle::DieselElectricDigitalForce(double const tmpV, double &t tempImax = DElist[MainCtrlPosNo].Imax * eimic_positive; tempUmax = DElist[MainCtrlPosNo].Umax * std::min(eimic_positive, rpmratio); auto const tempPmax = DElist[MainCtrlPosNo].GenPower * std::min(eimic_positive, rpmratio); - if (true == StLinFlag) + if (true == lineContactors.closed) Ft = DieselElectricForce(tmpV, tempPmax, eimic_positive, tempPmax); else Ft = 0; // jak nastawnik na zero, to sila tez zero @@ -539,7 +539,7 @@ void physics::Vehicle::DieselElectricGenerator(double const tmp, double const te if (EngineVoltage > tempUmax || Im == 0) { // gdy wychodzi za duze napiecie albo przy biegu jalowym (jest cos takiego?) - EngineVoltage = tempUmax * (ConverterFlag ? 1 : 0); + EngineVoltage = tempUmax * (converter.running ? 1 : 0); } EnginePower = EngineVoltage * Im / 1000.0; @@ -609,7 +609,7 @@ void physics::Vehicle::update_dieselelectric_dynamic_brake(double const dt) { auto &brake{DEDynamicBrake}; auto const nopower{brake.source == diesel_electric_dynamic_brake::control::controller ? eimic_real <= 0.0 : IsMainCtrlNoPowerPos()}; - if (Mains && DirActive != 0 && false == FuseFlag && false == SlippingWheels && nopower) + if (lineBreaker.closed && DirActive != 0 && false == FuseFlag && false == SlippingWheels && nopower) { brake.level += std::clamp(dieselelectric_dynamic_brake_demand() - brake.level, -brake.rate * dt, brake.rate * dt); } @@ -705,12 +705,12 @@ bool physics::Vehicle::dizel_AutoGearCheck(void) auto const VelDown{(motor_param(ScndCtrlActualPos).fi0 != 0.0 && eimic_real <= 0.0 ? motor_param(ScndCtrlActualPos).fi0 : motor_param(ScndCtrlActualPos).fi)}; - if (motor_param(ScndCtrlActualPos).AutoSwitch && Mains) + if (motor_param(ScndCtrlActualPos).AutoSwitch && lineBreaker.closed) { OK = dizel_GearShiftCheck(VelUp, VelDown); } - if (Mains) + if (lineBreaker.closed) { dizel_ClutchCheck(); } @@ -892,7 +892,7 @@ bool physics::Vehicle::dizel_Update(double dt) OilPumpCheck(dt); FuelPumpCheck(dt); // the engine being started fires once the starter has turned it a while; one stopped meanwhile starts over - diesel.firingCountdown = (Mains ? std::max(0.0, diesel.firingCountdown - dt) : 0.0); + diesel.firingCountdown = (lineBreaker.closed ? std::max(0.0, diesel.firingCountdown - dt) : 0.0); if (true == diesel.startupRequested && true == dizel_StartupCheck()) { @@ -907,7 +907,7 @@ bool physics::Vehicle::dizel_Update(double dt) // TODO: split engine and main circuit state indicator in two separate flags LastSwitchingTime = 0; Timer::subsystem.switching.note(Timer::switching_counter::diesel, this, &TypeName, &Name); - Mains = true; + lineBreaker.closed = true; diesel.spinningUp = true; diesel.firingCountdown = diesel.smokeDelay; enrot = std::max(enrot, @@ -915,9 +915,9 @@ bool physics::Vehicle::dizel_Update(double dt) EngineType == TEngineType::DieselEngine ? diesel.minRevolutions : DElist[0].RPM / 60.0)); } - diesel.spinningUp = diesel.spinningUp && Mains && enrot < 0.95 * (EngineType == TEngineType::DieselEngine ? diesel.minRevolutions : DElist[0].RPM / 60.0); + diesel.spinningUp = diesel.spinningUp && lineBreaker.closed && enrot < 0.95 * (EngineType == TEngineType::DieselEngine ? diesel.minRevolutions : DElist[0].RPM / 60.0); - if (true == Mains && false == FuelPump.is_active) + if (true == lineBreaker.closed && false == FuelPump.is_active) { // knock out the engine if the fuel pump isn't feeding it // TBD, TODO: grace period before the engine is starved for fuel and knocked out @@ -948,7 +948,7 @@ double physics::Vehicle::dizel_fillcheck(int mcp, double dt) { auto realfill{0.0}; - if (true == Mains && MainCtrlPosNo > 0 && true == FuelPump.is_active) + if (true == lineBreaker.closed && MainCtrlPosNo > 0 && true == FuelPump.is_active) { if (true == diesel.ignitionRequested && LastSwitchingTime >= 0.9 * InitialCtrlDelay) @@ -1184,7 +1184,7 @@ double physics::Vehicle::dizel_Momentum(double Fill, double n, double dt) // an engine stalling stops those started together with it, once. one already stopped, from its own switch or // another vehicle's, or not started at all, has nothing to stop: it stays quiet, rather than stop every frame // the engines started on their own or from the separate switches (eu07/maszyna#80) - if (true == Mains) + if (true == lineBreaker.closed) { MainSwitch(false, MainSwitchRange()); } @@ -1203,22 +1203,22 @@ void physics::Vehicle::hydro_TCFillCheck(double dt) { // napelnianie przetwornika bool IsPower = EIMCtrlType > 0 ? eimic_real > 0.005 : MainCtrlPowerPos() > 0; - if (IsPower && Mains && enrot > diesel.minRevolutions * 0.9) + if (IsPower && lineBreaker.closed && enrot > diesel.minRevolutions * 0.9) torqueConverter.fill += torqueConverter.fillRateIncrease * dt; // oproznianie przetwornika - if ((!IsPower && Vel < diesel.converterReleaseVelocity) || !Mains || enrot < diesel.minRevolutions * 0.8) + if ((!IsPower && Vel < diesel.converterReleaseVelocity) || !lineBreaker.closed || enrot < diesel.minRevolutions * 0.8) torqueConverter.fill -= torqueConverter.fillRateDecrease * dt; // obcinanie zakresu torqueConverter.fill = std::clamp(torqueConverter.fill, 0.0, 1.0); // blokowanie sprzegla blokującego - if (Vel > torqueConverter.lockupSpeed && Mains && enrot > 0.9 * diesel.minRevolutions && IsPower) + if (Vel > torqueConverter.lockupSpeed && lineBreaker.closed && enrot > 0.9 * diesel.minRevolutions && IsPower) { torqueConverter.lockedUp = true; torqueConverter.lockupRate += torqueConverter.fillRateIncrease * dt; } // luzowanie sprzegla blokujacego - if (Vel < (IsPower ? torqueConverter.lockupSpeed : torqueConverter.unlockSpeed) || !Mains || enrot < 0.8 * diesel.minRevolutions) + if (Vel < (IsPower ? torqueConverter.lockupSpeed : torqueConverter.unlockSpeed) || !lineBreaker.closed || enrot < 0.8 * diesel.minRevolutions) { torqueConverter.lockedUp = false; torqueConverter.lockupRate -= torqueConverter.fillRateDecrease * dt; @@ -1266,7 +1266,7 @@ void physics::Vehicle::hydro_TCTorque() double physics::Vehicle::dizel_MomentumRetarder(double n, double dt) { - double RetarderRequest = Mains ? std::max(0.0, -eimic_real) : 0; + double RetarderRequest = lineBreaker.closed ? std::max(0.0, -eimic_real) : 0; if (retarder.withIndividual) RetarderRequest = LocalBrakeRatio(); if (Vel < retarder.minVelocity) @@ -1344,8 +1344,8 @@ void physics::Vehicle::dizel_Heat(double const dt) diesel.heat.Te = Global.AirTemperature; - auto const engineon{(Mains ? 1 : 0)}; - auto const engineoff{(Mains ? 0 : 1)}; + auto const engineon{(lineBreaker.closed ? 1 : 0)}; + auto const engineoff{(lineBreaker.closed ? 0 : 1)}; auto const rpm{enrot * 60}; // TODO: calculate this once and cache for further use, instead of doing it repeatedly all over the place auto const revolutionsfactor{EngineRPMRatio()}; @@ -1355,11 +1355,11 @@ void physics::Vehicle::dizel_Heat(double const dt) auto const gw2 = engineon * std::lerp(gwmin2, gwmax2, revolutionsfactor) + waterpump * 1000 + engineoff * 200; auto const gwO = std::lerp(gwmin, gwmax, revolutionsfactor); - diesel.heat.water.is_cold = diesel.heat.water.config.temp_min > 0 && diesel.heat.temperatura1 < diesel.heat.water.config.temp_min - (Mains ? 5 : 0); + diesel.heat.water.is_cold = diesel.heat.water.config.temp_min > 0 && diesel.heat.temperatura1 < diesel.heat.water.config.temp_min - (lineBreaker.closed ? 5 : 0); diesel.heat.water.is_hot = diesel.heat.water.config.temp_max > 0 && diesel.heat.temperatura1 > diesel.heat.water.config.temp_max - (diesel.heat.water.is_hot ? 8 : 0); - diesel.heat.water_aux.is_cold = diesel.heat.water_aux.config.temp_min > 0 && diesel.heat.temperatura2 < diesel.heat.water_aux.config.temp_min - (Mains ? 5 : 0); + diesel.heat.water_aux.is_cold = diesel.heat.water_aux.config.temp_min > 0 && diesel.heat.temperatura2 < diesel.heat.water_aux.config.temp_min - (lineBreaker.closed ? 5 : 0); diesel.heat.water_aux.is_hot = diesel.heat.water_aux.config.temp_max > 0 && diesel.heat.temperatura2 > diesel.heat.water_aux.config.temp_max - (diesel.heat.water_aux.is_hot ? 8 : 0); - diesel.heat.oil.is_cold = diesel.heat.oil.config.temp_min > 0 && diesel.heat.To < diesel.heat.oil.config.temp_min - (Mains ? 5 : 0); + diesel.heat.oil.is_cold = diesel.heat.oil.config.temp_min > 0 && diesel.heat.To < diesel.heat.oil.config.temp_min - (lineBreaker.closed ? 5 : 0); diesel.heat.oil.is_hot = diesel.heat.oil.config.temp_max > 0 && diesel.heat.To > diesel.heat.oil.config.temp_max - (diesel.heat.oil.is_hot ? 8 : 0); // engine overheat check diesel.heat.engine_is_hot = diesel.heat.engine_max_temp > 0 && diesel.heat.Ts > diesel.heat.engine_max_temp - (diesel.heat.engine_is_hot ? 8 : 0); @@ -1400,7 +1400,7 @@ void physics::Vehicle::dizel_Heat(double const dt) { // auxiliary water circuit setup diesel.heat.water_aux.is_warm = true == diesel.heat.cooling || - (true == Mains && BatteryVoltage > 0.75 * NominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ + (true == lineBreaker.closed && BatteryVoltage > 0.75 * NominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ && diesel.heat.water_aux.config.temp_cooling > 0 && diesel.heat.temperatura2 > diesel.heat.water_aux.config.temp_cooling - (diesel.heat.water_aux.is_warm ? 8 : 0)); auto const PTC2{(diesel.heat.water_aux.is_warm /*or PTC2p*/ ? 1 : 0)}; diesel.heat.rpmwz2 = static_cast(PTC2 * (diesel.heat.fan_speed >= 0 ? rpm * diesel.heat.fan_speed : diesel.heat.fan_speed * -1)); @@ -1423,7 +1423,7 @@ void physics::Vehicle::dizel_Heat(double const dt) diesel.heat.water.is_flowing = diesel.heat.water.config.temp_flow < 0 || diesel.heat.temperatura1 > diesel.heat.water.config.temp_flow - (diesel.heat.water.is_flowing ? 5 : 0); auto const obieg{(diesel.heat.water.is_flowing ? 1 : 0)}; diesel.heat.water.is_warm = - true == diesel.heat.cooling || (true == Mains && BatteryVoltage > 0.75 * NominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ + true == diesel.heat.cooling || (true == lineBreaker.closed && BatteryVoltage > 0.75 * NominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ && diesel.heat.water.config.temp_cooling > 0 && diesel.heat.temperatura1 > diesel.heat.water.config.temp_cooling - (diesel.heat.water.is_warm ? 8 : 0)); auto const PTC1{(diesel.heat.water.is_warm /*or PTC1p*/ ? 1 : 0)}; diesel.heat.rpmwz = static_cast(PTC1 * (diesel.heat.fan_speed >= 0 ? rpm * diesel.heat.fan_speed : diesel.heat.fan_speed * -1)); diff --git a/physics/components/drive.cpp b/physics/components/drive.cpp index b58e97963..938b66069 100644 --- a/physics/components/drive.cpp +++ b/physics/components/drive.cpp @@ -109,7 +109,7 @@ namespace void updateRadiatorFans(physics::Vehicle &vehicle, double const dt) { auto &heat{vehicle.diesel.heat}; - if (true == vehicle.Mains) + if (true == vehicle.lineBreaker.closed) { heat.rpmw += static_cast(std::clamp(heat.rpmwz - heat.rpmw, -100.f, 50.f) * dt); heat.rpmw2 += static_cast(std::clamp(heat.rpmwz2 - heat.rpmw2, -100.f, 50.f) * dt); @@ -125,7 +125,7 @@ void updateRadiatorFans(physics::Vehicle &vehicle, double const dt) // else it needs the voltage of the source bool linePowerAvailable(physics::Vehicle const &vehicle) { - return vehicle.PantographsRequireMains ? vehicle.Power24vIsAvailable || vehicle.Power110vIsAvailable : vehicle.EnginePowerSourceVoltage() > 0.5 * vehicle.EnginePowerSource.MaxVoltage; + return vehicle.lineBreaker.pantographsRequireIt ? vehicle.Power24vIsAvailable || vehicle.Power110vIsAvailable : vehicle.EnginePowerSourceVoltage() > 0.5 * vehicle.EnginePowerSource.MaxVoltage; } // a notch of the master controller of the drives without steps of their own (no engine, Dumb, diesel-electric, @@ -265,13 +265,13 @@ public: // where a start begins, as the line breaker it stands in for wouldn't close on a running position either: at // zero, or at the first position, which is the first resistance step, where the line contactors close on any // start, and where the AI waits for them rather than going back to zero - auto const novoltrelaypicksup{false == vehicle.PantographsRequireMains || vehicle.NoVoltRelay || vehicle.MainCtrlPowerPos() <= 1}; + auto const novoltrelaypicksup{false == vehicle.lineBreaker.pantographsRequireIt || vehicle.protection.noVoltage || vehicle.MainCtrlPowerPos() <= 1}; auto const &source{vehicle.EnginePowerSource}; - vehicle.NoVoltRelay = source.SourceType != TPowerSource::CurrentCollector || (voltage >= source.CollectorParameters.MinV && novoltrelaypicksup); - vehicle.OvervoltageRelay = source.SourceType != TPowerSource::CurrentCollector || voltage <= source.CollectorParameters.MaxV || false == source.CollectorParameters.OVP; + vehicle.protection.noVoltage = source.SourceType != TPowerSource::CurrentCollector || (voltage >= source.CollectorParameters.MinV && novoltrelaypicksup); + vehicle.protection.overvoltage = source.SourceType != TPowerSource::CurrentCollector || voltage <= source.CollectorParameters.MaxV || false == source.CollectorParameters.OVP; // wywalanie szybkiego z powodu niewłaściwego napięcia // (a line breaker closed ahead of the pantographs holds without voltage) - vehicle.EventFlag |= true == vehicle.Mains && ((false == vehicle.NoVoltRelay && false == vehicle.PantographsRequireMains) || false == vehicle.OvervoltageRelay) && + vehicle.EventFlag |= true == vehicle.lineBreaker.closed && ((false == vehicle.protection.noVoltage && false == vehicle.lineBreaker.pantographsRequireIt) || false == vehicle.protection.overvoltage) && vehicle.MainSwitch(false, vehicle.TrainType == train_type::emu ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide } bool UpdateEngine(physics::Vehicle &vehicle, double /*dt*/) const override @@ -281,10 +281,10 @@ public: } void UpdateEngineVoltage(physics::Vehicle &vehicle, double const dt) const override { - vehicle.LastRelayTime += dt; + vehicle.lineContactors.lastSwitchTime += dt; // potem ulepszyc! pantogtrafy! // Ra 2014-03: uwzględnienie kierunku jazdy w napięciu na silnikach, a powinien być zdefiniowany nawrotnik - vehicle.EngineVoltage = vehicle.Mains ? vehicle.EnginePowerSourceVoltage() : 0.0; + vehicle.EngineVoltage = vehicle.lineBreaker.closed ? vehicle.EnginePowerSourceVoltage() : 0.0; if (vehicle.CabActive == 0) { vehicle.EngineVoltage *= vehicle.DirActive; @@ -334,7 +334,7 @@ public: // nie wchodzić w funkcję bez potrzeby // (a line breaker closed ahead of the pantographs holds without voltage) // (the source by the traction selector of a dual-mode vehicle: the pantographs or the genset) - if (vehicle.Mains && ((vehicle.TractionSupplyVoltage() < vehicle.TractionSupplyMinVoltage() && false == vehicle.PantographsRequireMains) || + if (vehicle.lineBreaker.closed && ((vehicle.TractionSupplyVoltage() < vehicle.TractionSupplyMinVoltage() && false == vehicle.lineBreaker.pantographsRequireIt) || vehicle.TractionSupplyVoltage() > vehicle.EnginePowerSource.CollectorParameters.MaxV + 200)) { vehicle.MainSwitch(false, vehicle.TrainType == train_type::emu ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide @@ -457,7 +457,7 @@ public: double UpdateEngineRevolutions(physics::Vehicle &vehicle, double const dt, double & /*transmission*/, double & /*moment*/) const override { double target{0.0}; - if (true == vehicle.Mains && true == vehicle.FuelPump.is_active) + if (true == vehicle.lineBreaker.closed && true == vehicle.FuelPump.is_active) { target = vehicle.DieselElectricTargetRevolutions(); } @@ -494,7 +494,7 @@ public: void UpdateVentilators(physics::Vehicle &vehicle, double const dt) const override { // NOTE: for this type RventRot is the speed of motor blowers; we also update radiator fans while at it - if (true == vehicle.Mains) + if (true == vehicle.lineBreaker.closed) { // TBD, TODO: currently ignores RVentType, fix this? vehicle.RventRot += std::clamp(vehicle.enrot - vehicle.RventRot, -100.0, 50.0) * dt; @@ -528,9 +528,9 @@ public: void CheckVoltageRelays(physics::Vehicle &vehicle) const override { // TODO: move this to the auto relay check when the electric engine code paths are unified - vehicle.StLinFlag |= vehicle.Mains && false == vehicle.StLinFlag && vehicle.MainCtrlPowerPos() == 1; - vehicle.StLinFlag &= vehicle.MotorConnectorsCheck(); - vehicle.StLinFlag &= vehicle.MainCtrlPowerPos() > 0; + vehicle.lineContactors.closed |= vehicle.lineBreaker.closed && false == vehicle.lineContactors.closed && vehicle.MainCtrlPowerPos() == 1; + vehicle.lineContactors.closed &= vehicle.MotorConnectorsCheck(); + vehicle.lineContactors.closed &= vehicle.MainCtrlPowerPos() > 0; } bool UpdateEngine(physics::Vehicle &vehicle, double const dt) const override { diff --git a/physics/components/electrics.cpp b/physics/components/electrics.cpp index 7e050f4f1..20e734075 100644 --- a/physics/components/electrics.cpp +++ b/physics/components/electrics.cpp @@ -149,7 +149,7 @@ void physics::Vehicle::UpdateBatteryVoltage(double dt) // HACK: allow to draw power also from adjacent converter, applicable for EMUs // TODO: expand power cables system to include low voltage power transfers // HACK: emulate low voltage generator powered directly by the diesel engine - auto const converteractive{Power110vIsAvailable || (EngineType == DieselElectric && true == Mains) || (EngineType == DieselEngine && true == Mains)}; + auto const converteractive{Power110vIsAvailable || (EngineType == DieselElectric && true == lineBreaker.closed) || (EngineType == DieselEngine && true == lineBreaker.closed)}; BatteryVoltage -= BatteryDrain(dt, converteractive); if (NominalBatteryVoltage / BatteryVoltage > 1.57 && MainSwitch(false) && EngineType != DieselEngine && EngineType != WheelsDriven) @@ -200,7 +200,7 @@ double physics::Vehicle::BatteryDrainCharged(double dt, bool const converteracti sn2 = -(dt * 2.0); // szybki wzrost do 110V else sn2 = 0; - if (Mains) + if (lineBreaker.closed) sn3 = dt * 0.05; else sn3 = 0; @@ -231,7 +231,7 @@ double physics::Vehicle::BatteryDrainLow(double dt, bool const converteractive) sn2 = -(dt * 50); // szybki wzrost do 110V else sn2 = 0; - if (Mains) + if (lineBreaker.closed) sn3 = dt * 0.001; else sn3 = 0; @@ -295,21 +295,21 @@ void physics::Vehicle::MainsCheck(double const Deltatime) localvoltage = Genset.voltage; } // a line breaker closed ahead of the pantographs gets ready on the low voltage circuits - auto const maincircuitpowersupply{std::abs(localvoltage) > 0.1 || GetTrainsetHighVoltage() > 0.1 || (PantographsRequireMains && (Power24vIsAvailable || Power110vIsAvailable))}; + auto const maincircuitpowersupply{std::abs(localvoltage) > 0.1 || GetTrainsetHighVoltage() > 0.1 || (lineBreaker.pantographsRequireIt && (Power24vIsAvailable || Power110vIsAvailable))}; if (true == maincircuitpowersupply) { // all is well - if (MainsInitTimeCountdown >= 0.0) + if (lineBreaker.initCountdown >= 0.0) { // NOTE: we ensure main circuit readiness meets condition MainsInitTimeCountdown < 0 // this allows for simpler rejection of cases where MainsInitTime == 0 - MainsInitTimeCountdown -= Deltatime; + lineBreaker.initCountdown -= Deltatime; } else { // optional automatic circuit start - if (MainsStart != start_t::manual && false == (Mains || diesel.startupRequested)) + if (lineBreaker.start != start_t::manual && false == (lineBreaker.closed || diesel.startupRequested)) { MainSwitch(true); } @@ -318,11 +318,11 @@ void physics::Vehicle::MainsCheck(double const Deltatime) else { // no power supply - MainsInitTimeCountdown = MainsInitTime; + lineBreaker.initCountdown = lineBreaker.initTime; } // an emergency brake application made under power opens the line breaker, where the vehicle has such an interlock - if (Mains && EmergencyBrakeHoldsMainOff()) + if (lineBreaker.closed && EmergencyBrakeHoldsMainOff()) { MainSwitch(false, TrainType == train_type::emu ? range_t::unit : range_t::local); } @@ -335,12 +335,12 @@ void physics::Vehicle::LowVoltagePowerCheck(double const /*Deltatime*/) if (EngineType == TEngineType::ElectricSeriesMotor) { - GroundRelay &= lowvoltagepower; - if (GroundRelayStart != start_t::manual) + protection.ground &= lowvoltagepower; + if (protection.groundStart != start_t::manual) { // NOTE: we're ignoring intricaties of battery and converter types as they're unlikely to be used // TODO: generic check method which takes these into account - GroundRelay |= lowvoltagepower; + protection.ground |= lowvoltagepower; } } } @@ -431,7 +431,7 @@ double physics::Vehicle::LocalPowerVoltage(Coupling const kind) case Coupling::power110v: { - if (ConverterFlag) + if (converter.running) { localvoltage = NominalBatteryVoltage; } @@ -591,27 +591,27 @@ void physics::Vehicle::PowerCouplersCurrent(Coupling const kind, bool const loca void physics::Vehicle::ConverterCheck(double const Timestep) { // TODO: move other converter checks here, to have it all in one place for potential device object - if (ConverterStart != start_t::disabled && ConverterOverloadRelayOffWhenMainIsOff) + if (converter.start != start_t::disabled && converter.overloadRelayOffWithLineBreaker) { - ConvOvldFlag |= !Mains && Power24vIsAvailable; + converter.overloaded |= !lineBreaker.closed && Power24vIsAvailable; } - switch (ConverterStart) + switch (converter.start) { case start_t::disabled: { - ConverterAllow = false; + converter.allow = false; // NOTE: if there's no converter in vehicle we can end the check here return; } case start_t::automatic: { - ConverterAllow = Mains; + converter.allow = lineBreaker.closed; break; } case start_t::direction: { - ConverterAllow = DirActive != 0; + converter.allow = DirActive != 0; } default: { @@ -619,31 +619,31 @@ void physics::Vehicle::ConverterCheck(double const Timestep) } } - if (ConverterAllow && ConverterAllowLocal && false == ConvOvldFlag && + if (converter.allow && converter.allowLocal && false == converter.overloaded && false == pantographAir.pressureLockActive // HACK: allow carriages to operate converter without (missing) fuse prerequisite && (Power > 1.0 ? MainCircuitPowered() : GetTrainsetHighVoltage() > 0.0)) { // delay timer can be optionally configured, and is set anew whenever converter goes off - if (ConverterStartDelayTimer <= 0.0) + if (converter.startDelayTimer <= 0.0) { - ConverterFlag = true; + converter.running = true; } else { - ConverterStartDelayTimer -= Timestep; + converter.startDelayTimer -= Timestep; } } else { - ConverterFlag = false; - ConverterStartDelayTimer = static_cast(ConverterStartDelay); + converter.running = false; + converter.startDelayTimer = static_cast(converter.startDelay); } - if (ConverterOverloadRelayStart == start_t::converter && false == (ConverterAllow && ConverterAllowLocal) && false == TestFlag(EngDmgFlag, 4)) + if (converter.overloadRelayStart == start_t::converter && false == (converter.allow && converter.allowLocal) && false == TestFlag(EngDmgFlag, 4)) { // reset converter overload relay if the converter was switched off, unless it's damaged - ConvOvldFlag = false; + converter.overloaded = false; } }; @@ -754,7 +754,7 @@ void physics::Vehicle::PantographsCheck(double const /*Timestep*/) valve.is_active = (valve.spring ? lowvoltagepower : true) // spring actuator needs power to maintain non-default state && (manualcontrol && lowvoltagepower ? false == valve.is_disabled : true) // needs power to change state, without it just pass through && (manualcontrol && lowvoltagepower ? false == pantographCircuit.allDown : true) && - (Mains || false == PantographsRequireMains) // fed through the closed line breaker, where it comes first + (lineBreaker.closed || false == lineBreaker.pantographsRequireIt) // fed through the closed line breaker, where it comes first && (valve.is_active || (manualcontrol && lowvoltagepower && valve.is_enabled) || (autostart && lowvoltagepower)); // shouldn't ever get this far but, eh auto const pantographexists{EnginePowerSource.SourceType == TPowerSource::CurrentCollector && EnginePowerSource.CollectorParameters.PhysicalLayout & 1 << pant_id}; @@ -805,7 +805,7 @@ void physics::Vehicle::GensetCheck(double const Deltatime) } else { - auto const demand{GensetSelected() && Mains ? std::clamp(inductionMotor.forceShare, 0.0, 1.0) : 0.0}; + auto const demand{GensetSelected() && lineBreaker.closed ? std::clamp(inductionMotor.forceShare, 0.0, 1.0) : 0.0}; auto const target{genset.is_active ? genset.revolutions_idle + (genset.revolutions_max - genset.revolutions_idle) * demand : 0.0}; genset.revolutions += (target - genset.revolutions) * std::min(1.0, Deltatime / genset.spinup_time); if (genset.revolutions < 0.001) @@ -920,7 +920,7 @@ bool physics::Vehicle::CompartmentLightsSwitchOff(bool State, range_t const Noti bool physics::Vehicle::MainSwitch(bool const State, range_t const Notify) { - bool const initialstate{Mains || diesel.startupRequested}; + bool const initialstate{lineBreaker.closed || diesel.startupRequested}; MainSwitch_(State); @@ -931,19 +931,19 @@ bool physics::Vehicle::MainSwitch(bool const State, range_t const Notify) SendCtrlToNext(VehicleCommand::mainSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } - return (Mains || diesel.startupRequested) != initialstate; + return (lineBreaker.closed || diesel.startupRequested) != initialstate; } void physics::Vehicle::MainSwitch_(bool const State) { - if (Mains == State || MainCtrlPosNo == 0) + if (lineBreaker.closed == State || MainCtrlPosNo == 0) { // nothing to do return; } - bool const initialstate{Mains}; + bool const initialstate{lineBreaker.closed}; if (false == State || true == MainSwitchCheck()) { @@ -959,18 +959,18 @@ void physics::Vehicle::MainSwitch_(bool const State) else { // additional check, as vehicles without pantographs won't fail relay checks earlier - Mains = true; + lineBreaker.closed = true; } } else { - Mains = false; + lineBreaker.closed = false; // potentially knock out the pumps if their switch doesn't force them on WaterPump.is_active &= WaterPump.is_enabled; FuelPump.is_active &= FuelPump.is_enabled; } - if (Mains != initialstate) + if (lineBreaker.closed != initialstate) { LastSwitchingTime = 0; Timer::subsystem.switching.note(Timer::switching_counter::mains, this, &TypeName, &Name); @@ -991,11 +991,11 @@ bool physics::Vehicle::MainSwitchCheck() const powerisavailable = Genset.is_active && Genset.voltage >= TractionSupplyMinVoltage(); } - return powerisavailable && (ScndCtrlPos == 0 || EngineType == ElectricInductionMotor) && MainsInitTimeCountdown <= 0.0 && - (ConvOvldFlag == false || ConverterOverloadRelayOffWhenMainIsOff) && true == GroundRelay && (true == NoVoltRelay || PantographsRequireMains) && true == OvervoltageRelay && + return powerisavailable && (ScndCtrlPos == 0 || EngineType == ElectricInductionMotor) && lineBreaker.initCountdown <= 0.0 && + (converter.overloaded == false || converter.overloadRelayOffWithLineBreaker) && true == protection.ground && (true == protection.noVoltage || lineBreaker.pantographsRequireIt) && true == protection.overvoltage && LastSwitchingTime > CtrlDelay && (HasCamshaft ? IsMainCtrlActualNoPowerPos() : - LineBreakerClosesOnlyAtNoPowerPos ? IsMainCtrlNoPowerPos() : + lineBreaker.closesOnlyAtNoPower ? IsMainCtrlNoPowerPos() : true) && false == DamageFlag.HasAll(VehicleDamage::derailed) && false == TestFlag(EngDmgFlag, 1) && false == EmergencyBrakeHoldsMainOff(); } @@ -1007,11 +1007,11 @@ bool physics::Vehicle::MainSwitchCheck() const bool physics::Vehicle::ConverterSwitch(bool State, range_t const Notify) { - auto const initialstate{ConverterAllow}; + auto const initialstate{converter.allow}; - if (ConverterStart == start_t::manual) + if (converter.start == start_t::manual) { - ConverterAllow = State; + converter.allow = State; } if (Notify != range_t::local) @@ -1019,7 +1019,7 @@ bool physics::Vehicle::ConverterSwitch(bool State, range_t const Notify) SendCtrlToNext(VehicleCommand::converterSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } - return ConverterAllow != initialstate; + return converter.allow != initialstate; } bool physics::Vehicle::HeatingSwitch(bool const State, range_t const Notify) @@ -1116,11 +1116,11 @@ double physics::Vehicle::EnginePowerSourceVoltage() const // blowers, the traction motors bool physics::Vehicle::MainCircuitPowered() const { - if (false == Mains) + if (false == lineBreaker.closed) { return false; } - if (false == PantographsRequireMains || EnginePowerSource.SourceType != TPowerSource::CurrentCollector) + if (false == lineBreaker.pantographsRequireIt || EnginePowerSource.SourceType != TPowerSource::CurrentCollector) { // the closed line breaker says it all: the undervoltage trip opens it without traction voltage, and an engine // which runs is its own supply diff --git a/physics/components/fizsections.cpp b/physics/components/fizsections.cpp index 35d561f23..ea183719c 100644 --- a/physics/components/fizsections.cpp +++ b/physics/components/fizsections.cpp @@ -909,15 +909,15 @@ void physics::Vehicle::LoadFIZ_CntrlStarts(std::string const &line) {"Battery", battery}, {"Converter", converter}, {"Direction", direction}}; // main circuit - extract_value(MainsInitTime, "MainInitTime", line, ""); + extract_value(lineBreaker.initTime, "MainInitTime", line, ""); { auto lookup = starts.find(extract_value("MainStart", line)); - MainsStart = lookup != starts.end() ? lookup->second : manual; + lineBreaker.start = lookup != starts.end() ? lookup->second : manual; } - extract_value(PantographsRequireMains, "PantRequiresMain", line, ""); + extract_value(lineBreaker.pantographsRequireIt, "PantRequiresMain", line, ""); // the brake pipe pressure of an emergency brake application, which opens the line breaker under power - extract_value(EmergencyBrakeMainOffPressure, "EmergencyBrakeMainOff", line, ""); - EmergencyBrakeMainOffPressure = std::max(0.0, EmergencyBrakeMainOffPressure); + extract_value(lineBreaker.emergencyOffPressure, "EmergencyBrakeMainOff", line, ""); + lineBreaker.emergencyOffPressure = std::max(0.0, lineBreaker.emergencyOffPressure); // battery { auto lookup = starts.find(extract_value("BatteryStart", line)); @@ -926,10 +926,10 @@ void physics::Vehicle::LoadFIZ_CntrlStarts(std::string const &line) // converter { auto lookup = starts.find(extract_value("ConverterStart", line)); - ConverterStart = lookup != starts.end() ? lookup->second : manual; + this->converter.start = lookup != starts.end() ? lookup->second : manual; } - extract_value(ConverterStartDelay, "ConverterStartDelay", line, ""); - extract_value(ConverterOverloadRelayOffWhenMainIsOff, "ConverterOverloadWhenMainIsOff", line, TrainType == train_type::emu ? "yes" : "no"); + extract_value(this->converter.startDelay, "ConverterStartDelay", line, ""); + extract_value(this->converter.overloadRelayOffWithLineBreaker, "ConverterOverloadWhenMainIsOff", line, TrainType == train_type::emu ? "yes" : "no"); // compressor { auto lookup = starts.find(extract_value("CompressorStart", line)); @@ -995,7 +995,7 @@ void physics::Vehicle::LoadFIZ_CntrlStarts(std::string const &line) std::map> const interlocks{{"Converter", line_contactors_interlock::converter}, {"MotorBlowers", line_contactors_interlock::motor_blowers}}; auto lookup = interlocks.find(extract_value("LineContactorsInterlock", line)); - LineContactorsInterlock = lookup != interlocks.end() ? lookup->second : line_contactors_interlock::none; + lineContactors.interlock = lookup != interlocks.end() ? lookup->second : line_contactors_interlock::none; } extract_value(LouvresOpenPressure, "LouvresOpenPressure", line, ""); // compartment lights @@ -1007,14 +1007,14 @@ void physics::Vehicle::LoadFIZ_CntrlStarts(std::string const &line) { auto lookup = starts.find(extract_value("GroundRelayStart", line)); auto const defaultstart{TrainType == train_type::emu ? automatic : manual}; - GroundRelayStart = lookup != starts.end() ? lookup->second : defaultstart; + protection.groundStart = lookup != starts.end() ? lookup->second : defaultstart; } // converter overload relay { auto lookup = starts.find(extract_value("ConverterOverloadRelayStart", line)); // the relay of a multiple unit activates when the converter is switched off auto const defaultstart{TrainType == train_type::emu ? converter : manual}; - ConverterOverloadRelayStart = lookup != starts.end() ? lookup->second : defaultstart; + this->converter.overloadRelayStart = lookup != starts.end() ? lookup->second : defaultstart; } } @@ -1183,7 +1183,7 @@ void physics::Vehicle::LoadFIZ_Engine(std::string const &Input) { EngineType = LoadFIZ_EngineDecode(extract_value("EngineType", Input)); - extract_value(JointEngineStart, "JointEngineStart", Input, ""); + extract_value(lineBreaker.jointStart, "JointEngineStart", Input, ""); if (std::string transmission = extract_value("Trans", Input); false == transmission.empty()) { @@ -1262,9 +1262,9 @@ void physics::Vehicle::LoadFIZ_Engine(std::string const &Input) extract_value(MotorBlowers[VehicleEnd::front].min_start_velocity, "MotorBlowersStartVelocity", Input, ""); MotorBlowers[VehicleEnd::rear] = MotorBlowers[VehicleEnd::front]; // pressure switch - extract_value(HasControlPressureSwitch, "PressureSwitch", Input, TrainType != train_type::emu ? "yes" : "no"); + extract_value(protection.hasPressureSwitch, "PressureSwitch", Input, TrainType != train_type::emu ? "yes" : "no"); // its brake cylinder half; the brake pipe one stays - extract_value(PressureSwitchBrakeCylinder, "PressureSwitchBrakeCylinder", Input, ""); + extract_value(protection.pressureSwitchWatchesCylinders, "PressureSwitchBrakeCylinder", Input, ""); } // Engine: of a diesel engine, its revolutions, gears, hydraulic transmission and retarder @@ -1469,13 +1469,13 @@ void physics::Vehicle::LoadFIZ_Switches(std::string const &Input) { extract_value(pantographCircuit.switchType, "Pantograph", Input, ""); - extract_value(ConvSwitchType, "Converter", Input, ""); - extract_value(StLinSwitchType, "MotorConnectors", Input, ""); + extract_value(converter.switchType, "Converter", Input, ""); + extract_value(lineContactors.switchType, "MotorConnectors", Input, ""); HeatingSwitchImpulse = ToLower(extract_value("TrainHeating", Input)) == "impulse"; // because people can't make up their minds whether it's "impulse" or "Impulse"... pantographCircuit.switchType = ToLower(pantographCircuit.switchType); - ConvSwitchType = ToLower(ConvSwitchType); - StLinSwitchType = ToLower(StLinSwitchType); + converter.switchType = ToLower(converter.switchType); + lineContactors.switchType = ToLower(lineContactors.switchType); // universal reset buttons assignments extract_value(UniversalResetButtonFlag[0], "RelayResetButton1", Input, ""); extract_value(UniversalResetButtonFlag[1], "RelayResetButton2", Input, ""); diff --git a/physics/components/maincircuit.h b/physics/components/maincircuit.h new file mode 100644 index 000000000..3970b2835 --- /dev/null +++ b/physics/components/maincircuit.h @@ -0,0 +1,88 @@ +/* +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 main circuit of a vehicle: the line breaker, the line contactors, the protective relays, the converter. Held by +// physics::Vehicle as lineBreaker, lineContactors, protection and converter + +#pragma once + +#include + +#include "physics/vehicletypes.h" + +namespace physics +{ + +// the line breaker (the main switch) of the vehicle +struct LineBreaker +{ + bool closed = false; + double initTime{0.0}; // how long the main circuit initialises after it gets its power, before the breaker can close [s] + double initCountdown{0.0}; // how long it still initialises [s] + start_t start{start_t::manual}; + // Engine:JointEngineStart: the line breaker / engine start switch of the cab works the vehicles in multiple too; when it + // doesn't, the cab has separate switches for them (mainb_*, mainc_*) + bool jointStart{true}; + // Cntrl.PantRequiresMain: the line breaker closes without traction voltage and holds without it, and the pantographs + // rise and stay up only while it's closed (EU05, EP05, ČD 181 family); off, the pantographs come first and the line + // breaker needs their voltage. what the main circuit feeds still needs the voltage (MainCircuitPowered()), and without + // it the undervoltage relay opens the line contactors (protection.noVoltage) + bool pantographsRequireIt{false}; + bool closesOnlyAtNoPower{false}; // it closes only with the master controller at a position of no power + // Cntrl.EmergencyBrakeMainOff: the brake pipe pressure [bar] taken for an emergency brake application: below it, with + // the master controller on a power position, the line breaker opens and doesn't close again. where the pantographs + // stay up only through the closed line breaker (pantographsRequireIt) they drop with it (EP05). 0: an emergency + // application leaves the line breaker alone + double emergencyOffPressure{0.0}; +}; + +// the line contactors of the traction motors +struct LineContactors +{ + bool closed = false; + bool forcedOpen{false}; // the button that forces them open + std::string switchType; // StLinSwitchType: the kind of the switch of the cab + line_contactors_interlock interlock{line_contactors_interlock::none}; // what else they need to close + double lastSwitchTime = 0.0; // the time since they last switched [s] +}; + +// the protective relays and the pressure switch of the main circuit +struct ProtectionRelays +{ + // the undervoltage relay: it switches off if the voltage drops below its threshold, which opens the line breaker; with + // lineBreaker.pantographsRequireIt it opens the line contactors instead, and switches back on only with the master + // controller at zero or the first position + bool noVoltage{true}; + bool overvoltage{true}; // the overvoltage relay, which opens above the voltage it's set to + bool ground{true}; // the ground relay, which opens to protect against damage from earths + start_t groundStart{start_t::manual}; // how the ground relay is reset + bool pressureSwitch{false}; // tripped while the brake pipe and/or the brake cylinders aren't at their working pressures + bool hasPressureSwitch{true}; + // Engine:PressureSwitchBrakeCylinder: the pressure switch watches the brake cylinders (it cuts the start off above 2 bar + // there) as well as the brake pipe (below 3.6 bar). off, it's left with the brake pipe alone, and the vehicle takes + // current whatever the pressure in its brake cylinders (EP05) + bool pressureSwitchWatchesCylinders{true}; +}; + +// the converter of the vehicle +struct PowerConverter +{ + start_t start{start_t::manual}; // whether it is started by hand, or another way + float startDelay{0.0f}; // the delay before it starts, once its conditions are met [s] + double startDelayTimer{0.0}; // how long its conditions have been met + bool allow = false; // it may run + bool allowLocal{true}; // the switch of the vehicle itself; most have none, so it allows + bool running = false; + start_t overloadRelayStart{start_t::manual}; // whether its overload relay is reset by a button of its own + bool overloadRelayOffWithLineBreaker{false}; // ConverterOverloadRelayOffWhenMainIsOff + bool overloaded = false; // the overload relay of the converter and the heating tripped + std::string switchType; // ConvSwitchType: the kind of the switch of the cab. TODO: the kinds of the switches belong to the cab definition +}; + +} // namespace physics diff --git a/physics/components/pneumatics.cpp b/physics/components/pneumatics.cpp index 37b421f57..c1e9fcd8a 100644 --- a/physics/components/pneumatics.cpp +++ b/physics/components/pneumatics.cpp @@ -518,7 +518,7 @@ bool physics::Vehicle::BrakeReleaser(int state) if (state != 0) { // additional limitations imposed by pressure switch - if (false == ControlPressureSwitch || false == ReleaserEnabledOnlyAtNoPowerPos || true == IsMainCtrlNoPowerPos()) + if (false == protection.pressureSwitch || false == ReleaserEnabledOnlyAtNoPowerPos || true == IsMainCtrlNoPowerPos()) { brakes.distributor->Releaser(state); } @@ -794,7 +794,7 @@ void physics::Vehicle::CompressorCheck(double dt) { case CompressorSupply::converter: { - air.compressor.allow = ConverterAllow; + air.compressor.allow = converter.allow; break; } case CompressorSupply::engine: diff --git a/physics/components/traction.cpp b/physics/components/traction.cpp index ffbb6fae5..acddd1fa8 100644 --- a/physics/components/traction.cpp +++ b/physics/components/traction.cpp @@ -97,12 +97,12 @@ double physics::Vehicle::Current(double n, double U) } } - if (DynamicBrakeFlag && !FuseFlag && DynamicBrakeType == dbrake_automatic && Power110vIsAvailable && Mains) // hamowanie EP09 //TUHEX + if (DynamicBrakeFlag && !FuseFlag && DynamicBrakeType == dbrake_automatic && Power110vIsAvailable && lineBreaker.closed) // hamowanie EP09 //TUHEX { // TODO: zrobic bardziej uniwersalne nie tylko dla EP09 MotorCurrent = -std::max(motor_param(0).fi * (Vadd / (Vadd + motor_param(0).Isat) - motor_param(0).fi0), 0.) * n * 2.0 / DynamicBrakeRes; } - else if (RList[MainCtrlActualPos].Bn == 0 || false == StLinFlag) + else if (RList[MainCtrlActualPos].Bn == 0 || false == lineContactors.closed) { // wylaczone MotorCurrent = 0; @@ -447,7 +447,7 @@ bool physics::Vehicle::TractionModeSwitch(traction_mode const Mode, range_t cons { auto const initialstate{TractionMode}; // refused with the line breaker closed, and then not passed on either, so the train stays on one source - auto const accepted{false == Mains}; + auto const accepted{false == lineBreaker.closed}; if (Genset.fitted() && accepted) { @@ -668,7 +668,7 @@ void physics::Vehicle::VoltageRelaysCheck() void physics::Vehicle::DumbTractionForce(double const PosRatio) { - if (Mains && CabActive != 0) + if (lineBreaker.closed && CabActive != 0) { if (Vel > 0.1) { @@ -1461,12 +1461,12 @@ bool physics::Vehicle::RelayReset(int const Relays, range_t const Notify) bool reset{false}; if (TestFlag(Relays, relay_t::maincircuitground) && (EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric) && - (GroundRelayStart == start_t::manual || GroundRelayStart == start_t::manualwithautofallback) && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0 && DirActive != 0 && + (protection.groundStart == start_t::manual || protection.groundStart == start_t::manualwithautofallback) && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0 && DirActive != 0 && !TestFlag(EngDmgFlag, 1)) { // NOTE: true means the relay is operational - reset |= !GroundRelay && lowvoltagepower; - GroundRelay |= lowvoltagepower; + reset |= !protection.ground && lowvoltagepower; + protection.ground |= lowvoltagepower; } if (TestFlag(Relays, relay_t::tractionnmotoroverload) && (EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric) && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0 && DirActive != 0 && @@ -1479,15 +1479,15 @@ bool physics::Vehicle::RelayReset(int const Relays, range_t const Notify) FuseFlag &= !lowvoltagepower; } - if (TestFlag(Relays, relay_t::primaryconverteroverload) && ConverterOverloadRelayStart == start_t::manual + if (TestFlag(Relays, relay_t::primaryconverteroverload) && converter.overloadRelayStart == start_t::manual // && ( false == Mains ) - && false == ConverterAllow) + && false == converter.allow) { // NOTE: false means the relay is operational // TODO: cleanup, flip the FuseFlag code to match other relays // TODO: check whether the power is required, TBD, TODO: make it configurable? - reset |= ConvOvldFlag && lowvoltagepower; - ConvOvldFlag &= !lowvoltagepower; + reset |= converter.overloaded && lowvoltagepower; + converter.overloaded &= !lowvoltagepower; } if (reset) diff --git a/physics/vehicle.h b/physics/vehicle.h index 183e55b9e..45436c2ac 100644 --- a/physics/vehicle.h +++ b/physics/vehicle.h @@ -28,6 +28,7 @@ http://mozilla.org/MPL/2.0/. #include "physics/components/airsupply.h" #include "physics/components/devices.h" #include "physics/components/pantographs.h" +#include "physics/components/maincircuit.h" class TractionDrive; @@ -680,6 +681,10 @@ class Vehicle int wiperSwitchPos = 0; // pozycja przelacznika wycieraczek double WiperAngle = {45.0}; // kat pracy wycieraczek + LineBreaker lineBreaker; // the main circuit (physics/components/maincircuit.h) + LineContactors lineContactors; + ProtectionRelays protection; + PowerConverter converter; ByEnd pantographs; PantographCircuit pantographCircuit; // their voltages, switches, presets (physics/components/pantographs.h) PantographAir pantographAir; // their reservoir, the small compressor, the valves @@ -952,16 +957,7 @@ class Vehicle bool SandDoseAutoAllow = true; /*zezwolenie na automatyczne piaskowanie*/ double Sand = 0.0; /*ilosc piasku*/ /*! przyrosty cisnienia w kroku czasowym*/ - // TODO converter parameters, for when we start cleaning up physics parameters - start_t ConverterStart{start_t::manual}; // whether converter is started manually, or by other means - float ConverterStartDelay{0.0f}; // delay (in seconds) before the converter is started, once its activation conditions are met - double ConverterStartDelayTimer{0.0}; // helper, for tracking whether converter start delay passed - bool ConverterAllow = false; /*zezwolenie na prace przetwornicy NBMX*/ - bool ConverterAllowLocal{true}; // local device state override (most units don't have this fitted so it's set to true not to intefere) - bool ConverterFlag = false; /*! czy wlaczona przetwornica NBMX*/ bool BRVentilators = false; /* Czy rezystor hamowania pracuje */ - start_t ConverterOverloadRelayStart{start_t::manual}; // whether overload relay reset responds to dedicated button - bool ConverterOverloadRelayOffWhenMainIsOff{false}; fuel_pump FuelPump; oil_pump OilPump; genset_device Genset; // of a dual-mode vehicle, fitted() only with GensetPower @@ -1006,30 +1002,6 @@ class Vehicle double OffsetTrackV = 0.0; /*przesuniecie poz. i pion. w/m osi toru*/ /*-zmienne dla lokomotyw*/ - bool Mains = false; /*polozenie glownego wylacznika*/ - double MainsInitTime{0.0}; // config, initialization time (in seconds) of the main circuit after it receives power, before it can be closed - double MainsInitTimeCountdown{0.0}; // current state of main circuit initialization, remaining time (in seconds) until it's ready - start_t MainsStart{start_t::manual}; - // config, Engine:JointEngineStart. whether the cab's line breaker / engine start switch works the vehicles in multiple - // too; when it doesn't, the cab has separate switches for them (mainb_*, mainc_*) - bool JointEngineStart{true}; - // config, .fiz Cntrl.PantRequiresMain: the line breaker closes without traction voltage and holds without it, and the - // pantographs rise and stay up only while it's closed (EU05, EP05, ČD 181 family); off, the pantographs come first and the line - // breaker needs their voltage. what the main circuit feeds still needs the voltage (MainCircuitPowered()), and without - // it the undervoltage relay opens the line contactors (NoVoltRelay) - bool PantographsRequireMains{false}; - bool LineBreakerClosesOnlyAtNoPowerPos{false}; - bool ControlPressureSwitch{false}; // activates if the main pipe and/or brake cylinder pressure aren't within operational levels - bool HasControlPressureSwitch{true}; - // config, .fiz Engine:PressureSwitchBrakeCylinder. whether the pressure switch watches the brake cylinders (it cuts the - // start off above 2 bar there) as well as the brake pipe (below 3.6 bar). off, it's left with the brake pipe alone, - // and the vehicle takes current whatever the pressure in its brake cylinders (EP05) - bool PressureSwitchBrakeCylinder{true}; - // config, .fiz Cntrl.EmergencyBrakeMainOff. the brake pipe pressure [bar] taken for an emergency brake application: - // below it, with the master controller on a power position, the line breaker opens and doesn't close again. where - // the pantographs stay up only through the closed line breaker (PantographsRequireMains) they drop with it (EP05). - // 0: an emergency application leaves the line breaker alone - double EmergencyBrakeMainOffPressure{0.0}; bool ReleaserEnabledOnlyAtNoPowerPos{false}; int MainCtrlPos = 0; /*polozenie glownego nastawnika*/ int ScndCtrlPos = 0; /*polozenie dodatkowego nastawnika*/ @@ -1080,22 +1052,11 @@ class Vehicle int MainCtrlActualPos = 0; /*wskaznik RList*/ int ScndCtrlActualPos = 0; /*wskaznik MotorParam*/ bool DelayCtrlFlag = false; // czy czekanie na 1. pozycji na załączenie? - double LastRelayTime = 0.0; /*czas ostatniego przelaczania stycznikow*/ bool AutoRelayFlag = false; /*mozna zmieniac jesli AutoRelayType=2*/ bool FuseFlag = false; /*!o bezpiecznik nadmiarowy*/ - bool ConvOvldFlag = false; /*! nadmiarowy przetwornicy i ogrzewania*/ - bool GroundRelay{true}; // switches off to protect against damage from earths - start_t GroundRelayStart{start_t::manual}; // relay activation method - bool StLinFlag = false; /*!o styczniki liniowe*/ - bool StLinSwitchOff{false}; // state of the button forcing motor connectors open - line_contactors_interlock LineContactorsInterlock{line_contactors_interlock::none}; // what else the line contactors need to close double LouvresOpenPressure{5.0}; // main reservoir pressure [bar] at which the pneumatic louvres of the motor fans open (ET22) bool ResistorsFlag = false; /*!o jazda rezystorowa*/ double RventRot = 0.0; /*!s obroty wentylatorow rozruchowych*/ - // switches off if the power level drops below threshold, which opens the line breaker; with PantographsRequireMains - // it opens the line contactors instead, and switches back on only with the master controller at zero or the first position - bool NoVoltRelay{true}; - bool OvervoltageRelay{true}; // switches off if the power level goes above threshold bool s_CAtestebrake = false; // hunter-091012: zmienna dla testu ca std::array, 4> PowerCircuits; // 24v, 110v, 3x400v and 3000v power circuits, voltage from local sources and current draw pairs @@ -1139,10 +1100,7 @@ class Vehicle bool DoorRightOpened = false; double DoorRightOpenTimer{-1.0}; // right door closing timer for automatic door type #endif - // TODO: move these switch types where they belong, cabin definition - std::string ConvSwitchType; bool HeatingSwitchImpulse{false}; // the train heating switch springs back to its middle position - std::string StLinSwitchType; bool Heating = false; // ogrzewanie 'Winger 020304 bool HeatingAllow{false}; // heating switch // TODO: wrap heating in a basic device @@ -1587,13 +1545,13 @@ class Vehicle // the pressure switch, when fitted, cuts the start off and puts them out, otherwise they go out once the brakes are applied bool MainCircuitLampsEnabled() const { - return false == ControlPressureSwitch && (HasControlPressureSwitch || brakes.cylinderPressure < 1.0); + return false == protection.pressureSwitch && (protection.hasPressureSwitch || brakes.cylinderPressure < 1.0); } // whether an emergency brake application holds the line breaker open: the brake pipe below the pressure taken for one // (EmergencyBrakeMainOffPressure) while the master controller is on a power position bool EmergencyBrakeHoldsMainOff() const { - return EmergencyBrakeMainOffPressure > 0.0 && brakePipe.pressure < EmergencyBrakeMainOffPressure && false == IsMainCtrlNoPowerPos(); + return lineBreaker.emergencyOffPressure > 0.0 && brakePipe.pressure < lineBreaker.emergencyOffPressure && false == IsMainCtrlNoPowerPos(); } // whether the lamp of the open line contactors is lit. on the electric locomotives it tells the start can be made, so // it goes out with the start cut off; on the diesel-electric ones (the SU45 and SU46 family) it just tells the @@ -1602,15 +1560,15 @@ class Vehicle { if (EngineType == TEngineType::DieselElectric) { - return false == StLinFlag; + return false == lineContactors.closed; } - return false == StLinFlag && MainCircuitLampsEnabled(); + return false == lineContactors.closed && MainCircuitLampsEnabled(); } // the vehicles the line breaker / engine start switch of this vehicle works, and its engine stopping on its own // stops: the whole consist, or with JointEngineStart=No this vehicle alone (eu07/maszyna#80) range_t MainSwitchRange() const { - return JointEngineStart ? range_t::consist : range_t::local; + return lineBreaker.jointStart ? range_t::consist : range_t::local; } // whether the pneumatic louvres of the motor fans are still closed, the main reservoir short of the pressure that opens them bool LouvresClosed() const @@ -1623,7 +1581,7 @@ class Vehicle // the AI driver doesn't leave it so: the converters of the other vehicles running, it would wait for the contactors forever bool LineContactorsHeldByLocalConverterSwitch() const { - return LineContactorsInterlock == line_contactors_interlock::converter && false == ConverterAllowLocal; + return lineContactors.interlock == line_contactors_interlock::converter && false == converter.allowLocal; } // whether the vehicle has a driver's cab: it has the driver's brake valve (BrakeHandle in the Cntrl. section of the // .fiz), which the wagons and most cars of the units without a cab don't (a few copy the Cntrl. section of the cab diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index 3d95510c5..fe22a6964 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -73,9 +73,9 @@ blackbox::driver driver_of(TDynamicObject const &Vehicle) { std::uint32_t devices_of(physics::Vehicle const &Occupied, physics::Vehicle const &Controlling) { namespace device = blackbox::cab_devices; auto const on{[](bool const State, std::uint32_t const Bit) { return State ? Bit : 0u; }}; - return on(Occupied.Battery || Controlling.Battery, device::battery) | on(Controlling.Mains, device::main_breaker) | + return on(Occupied.Battery || Controlling.Battery, device::battery) | on(Controlling.lineBreaker.closed, device::main_breaker) | on(Controlling.pantographs[VehicleEnd::front].is_active, device::pantograph_front) | on(Controlling.pantographs[VehicleEnd::rear].is_active, device::pantograph_rear) | - on(Controlling.ConverterFlag, device::converter) | on(Controlling.air.compressor.running, device::compressor) | on(Controlling.StLinFlag, device::line_contactors) | + on(Controlling.converter.running, device::converter) | on(Controlling.air.compressor.running, device::compressor) | on(Controlling.lineContactors.closed, device::line_contactors) | on(Controlling.FuseFlag, device::overload_relay) | on(Controlling.SandDose, device::sanding) | on(Occupied.WarningSignal != 0, device::horn) | on(false == Occupied.Doors.instances[VehicleSide::left].is_closed, device::doors_left) | on(false == Occupied.Doors.instances[VehicleSide::right].is_closed, device::doors_right) | on(Occupied.Radio, device::radio) | diff --git a/tests/unit/drive.cpp b/tests/unit/drive.cpp index de9736557..74fcfb9d7 100644 --- a/tests/unit/drive.cpp +++ b/tests/unit/drive.cpp @@ -89,8 +89,8 @@ bool is_ready(driven const &Driven) { auto const air{physics.air.mainReservoirVolume <= 0.0 || physics.mainPipe.pressure >= 4.5}; // the converter feeds the 110 V circuits (the electrodynamic brake's control among them); the AI switches // it on once the line breaker is closed, so a train already charged with air isn't ready before it runs - auto const converter{physics.ConverterStart != start_t::manual || physics.ConverterFlag}; - return physics.Mains && air && converter; + auto const converter{physics.converter.start != start_t::manual || physics.converter.running}; + return physics.lineBreaker.closed && air && converter; } namespace { @@ -174,7 +174,7 @@ bool start_up(driven Driven, track const &Track, double Seconds, trace *Trace) { if (diesel) { prepare_diesel(Driven); } - if (controlling.PantographsRequireMains && false == controlling.Mains) { + if (controlling.lineBreaker.pantographsRequireIt && false == controlling.lineBreaker.closed) { // the pantographs rise only through the closed line breaker, which closes without their voltage for (int i = 0; i < 3 && cab.DirActive <= 0; ++i) { cab.DirectionForward(); @@ -189,7 +189,7 @@ bool start_up(driven Driven, track const &Track, double Seconds, trace *Trace) { for (int i = 0; i < 3 && cab.DirActive <= 0; ++i) { cab.DirectionForward(); } - if (false == controlling.Mains) { + if (false == controlling.lineBreaker.closed) { close_line_breaker(Driven); } else { @@ -210,7 +210,7 @@ void drive_cycle(driven Driven, track const &Track, trace &Trace) { auto &cab{Driven.cab}; auto &controlling{Driven.controlling}; if (false == start_up(Driven, Track, 300.0, &Trace)) { - MESSAGE("didn't get ready: Mains " << controlling.Mains << ", main reservoir " << controlling.mainPipe.pressure); + MESSAGE("didn't get ready: Mains " << controlling.lineBreaker.closed << ", main reservoir " << controlling.mainPipe.pressure); } Trace.mark("release brakes"); release_brakes(cab); diff --git a/tests/unit/golden.cpp b/tests/unit/golden.cpp index d668592c0..36d6010bc 100644 --- a/tests/unit/golden.cpp +++ b/tests/unit/golden.cpp @@ -55,7 +55,7 @@ std::vector motion() { std::vector traction() { return { - {"Mains", [](auto const &M) { return M.Mains ? 1.0 : 0.0; }}, + {"Mains", [](auto const &M) { return M.lineBreaker.closed ? 1.0 : 0.0; }}, {"DirActive", [](auto const &M) { return M.DirActive; }}, {"MainCtrlPos", [](auto const &M) { return M.MainCtrlPos; }}, {"MainCtrlActualPos", [](auto const &M) { return M.MainCtrlActualPos; }}, diff --git a/tests/unit/invariants.cpp b/tests/unit/invariants.cpp index ed3458f88..c0141c5ca 100644 --- a/tests/unit/invariants.cpp +++ b/tests/unit/invariants.cpp @@ -70,15 +70,15 @@ std::vector const &invariants() { [](auto const &M, double, auto const *) { return M.air.compressor.maxPressure <= 0.0 || M.air.mainReservoirPressure <= 1.01 * M.air.compressor.maxPressure + pressure_margin; }, [](auto const &M) { return values({{"Compressor", M.air.mainReservoirPressure}, {"MaxCompressor", M.air.compressor.maxPressure}}); }}, {"no motor current with the line breaker open", - [](auto const &M, double, auto const *) { return M.Mains || false == electric(M) || std::abs(M.Im) < 1.0; }, - [](auto const &M) { return values({{"Mains", M.Mains}, {"Im", M.Im}, {"Itot", M.Itot}}); }}, + [](auto const &M, double, auto const *) { return M.lineBreaker.closed || false == electric(M) || std::abs(M.Im) < 1.0; }, + [](auto const &M) { return values({{"Mains", M.lineBreaker.closed}, {"Im", M.Im}, {"Itot", M.Itot}}); }}, {"no motor current with the line contactors open, but for the dynamic brake", [](auto const &M, double, auto const *) { // the dynamic brake closes its own circuit of the motors and the resistors - return M.StLinFlag || M.DynamicBrakeFlag || M.EngineType != TEngineType::ElectricSeriesMotor || std::abs(M.Im) < 1.0; + return M.lineContactors.closed || M.DynamicBrakeFlag || M.EngineType != TEngineType::ElectricSeriesMotor || std::abs(M.Im) < 1.0; }, [](auto const &M) { - return values({{"StLinFlag", M.StLinFlag}, {"DynamicBrakeFlag", M.DynamicBrakeFlag}, {"Im", M.Im}, {"MainCtrlActualPos", M.MainCtrlActualPos}}); + return values({{"StLinFlag", M.lineContactors.closed}, {"DynamicBrakeFlag", M.DynamicBrakeFlag}, {"Im", M.Im}, {"MainCtrlActualPos", M.MainCtrlActualPos}}); }}, {"no tractive force without power", [](auto const &M, double, auto const *) { return M.Power >= 0.01 || std::abs(M.Ft) < 1.0; }, diff --git a/tests/unit/scenario.cpp b/tests/unit/scenario.cpp index b26300a35..ecda46e3e 100644 --- a/tests/unit/scenario.cpp +++ b/tests/unit/scenario.cpp @@ -11,7 +11,7 @@ namespace { // switch is on when the controller leaves zero doesn't close its line contactors until the controller is back at zero bool start_cut_off(consist &Train) { for (std::size_t i = 0; i < Train.size(); ++i) { - if (Train[i].physics().ControlPressureSwitch) { + if (Train[i].physics().protection.pressureSwitch) { return true; } } @@ -74,7 +74,7 @@ void scenario::full_power(double Seconds) { wait(1.0); } controlling.IncMainCtrl(1); - for (int i = 0; i < 90 && false == controlling.StLinFlag; ++i) { + for (int i = 0; i < 90 && false == controlling.lineContactors.closed; ++i) { wait(1.0); } for (int i = 0; i < 60 && false == controlling.IsMainCtrlMaxPowerPos(); ++i) { diff --git a/tests/unit/test_6dg_power_steps.cpp b/tests/unit/test_6dg_power_steps.cpp index e2f834ac8..ed3f3c7fa 100644 --- a/tests/unit/test_6dg_power_steps.cpp +++ b/tests/unit/test_6dg_power_steps.cpp @@ -61,8 +61,8 @@ void get_ready(vehicle &Loco, test::track const &Track) { test::drive(driven, Track, 1.0); move_to(Loco, hold); test::drive(driven, Track, 5.0); - REQUIRE(Loco->Mains); // the engine running - REQUIRE(Loco->StLinFlag); // the line contactors closed + REQUIRE(Loco->lineBreaker.closed); // the engine running + REQUIRE(Loco->lineContactors.closed); // the line contactors closed REQUIRE(false == Loco->SpeedCtrlUnit.IsActive); // the demand of the controller drives, not the speed control REQUIRE(Loco->eimic == doctest::Approx(0.0)); } diff --git a/tests/unit/test_auxiliaries.cpp b/tests/unit/test_auxiliaries.cpp index 66702750b..de33f2ffb 100644 --- a/tests/unit/test_auxiliaries.cpp +++ b/tests/unit/test_auxiliaries.cpp @@ -16,7 +16,7 @@ std::vector auxiliaries() { return { {"BatteryVoltage", [](auto const &M) { return M.BatteryVoltage; }}, {"Battery", [](auto const &M) { return M.Battery ? 1.0 : 0.0; }}, - {"ConverterFlag", [](auto const &M) { return M.ConverterFlag ? 1.0 : 0.0; }}, + {"ConverterFlag", [](auto const &M) { return M.converter.running ? 1.0 : 0.0; }}, {"Power110vIsAvailable", [](auto const &M) { return M.Power110vIsAvailable ? 1.0 : 0.0; }}, {"PantPress", [](auto const &M) { return M.pantographAir.pressure; }}, {"PantVolume", [](auto const &M) { return M.pantographAir.volume; }}, @@ -43,10 +43,10 @@ TEST_CASE("auxiliaries: the battery drained by the lights and the pantographs' c eu07.pantographAir.compressorRunning = true; scenario.wait(30.0); CHECK(eu07.BatteryVoltage < 0.83 * eu07.NominalBatteryVoltage); - CHECK(eu07.Mains); + CHECK(eu07.lineBreaker.closed); scenario.wait(5000.0); CHECK(eu07.BatteryVoltage < eu07.NominalBatteryVoltage / 1.57); - CHECK_FALSE(eu07.Mains); + CHECK_FALSE(eu07.lineBreaker.closed); scenario.act("start up again"); CHECK_FALSE(scenario.start_up()); CHECK(eu07.BatteryVoltage < eu07.NominalBatteryVoltage / 1.57); @@ -99,7 +99,7 @@ TEST_CASE("auxiliaries: the pantographs on their own tank, leaking until the pre scenario.wait(600.0); CHECK(eu07.pantographAir.pressure < eu07.EnginePowerSource.CollectorParameters.MinPress); CHECK_FALSE(eu07.pantographAir.pressureSwitchActive); - CHECK_FALSE(eu07.Mains); + CHECK_FALSE(eu07.lineBreaker.closed); scenario.act("small compressor on"); eu07.pantographAir.compressorRunning = true; for (int i = 0; i < 60 && eu07.pantographAir.compressorRunning; ++i) { diff --git a/tests/unit/test_camshaft.cpp b/tests/unit/test_camshaft.cpp index 236c80f14..11b2784d6 100644 --- a/tests/unit/test_camshaft.cpp +++ b/tests/unit/test_camshaft.cpp @@ -70,20 +70,20 @@ definition skoda() { void running(physics::Vehicle &Locomotive, int const Direction, int const Position, int const Controller) { Locomotive.CabActive = 1; Locomotive.DirActive = Direction; - Locomotive.Mains = true; + Locomotive.lineBreaker.closed = true; Locomotive.brakePipe.pressure = 5.0; // bar, the pressure switch lets the line contactors close Locomotive.brakes.cylinderPressure = 0.0; - Locomotive.StLinFlag = true; + Locomotive.lineContactors.closed = true; Locomotive.MainCtrlActualPos = Position; Locomotive.MainCtrlPos = Controller; - Locomotive.LastRelayTime = 10.0; + Locomotive.lineContactors.lastSwitchTime = 10.0; } // steps the camshaft as the physics does, each step once the delay since the previous one passed; returns where it // ended up int run_camshaft(physics::Vehicle &Locomotive, int const Steps) { for (int step = 0; step < Steps; ++step) { - Locomotive.LastRelayTime = 10.0; + Locomotive.lineContactors.lastSwitchTime = 10.0; Locomotive.AutoRelayCheck(); } return Locomotive.MainCtrlActualPos; @@ -108,7 +108,7 @@ TEST_CASE("camshaft: running backwards, the camshaft goes back down from the las running(physics, -1, 22, 0); run_camshaft(physics, 30); CHECK(physics.MainCtrlActualPos == 0); - CHECK_FALSE(physics.StLinFlag); // the motors don't pull any more + CHECK_FALSE(physics.lineContactors.closed); // the motors don't pull any more } } diff --git a/tests/unit/test_cntrl.cpp b/tests/unit/test_cntrl.cpp index 4df03f31d..eb99d05b0 100644 --- a/tests/unit/test_cntrl.cpp +++ b/tests/unit/test_cntrl.cpp @@ -23,18 +23,18 @@ TEST_CASE("cntrl: the relays of a multiple unit start on their own, of other veh SUBCASE("multiple unit") { vehicle unit{definition::load("wagon").set("Param", "Type", "ezt")}; REQUIRE(unit->TrainType == train_type::emu); - CHECK(unit->GroundRelayStart == start_t::automatic); - CHECK(unit->ConverterOverloadRelayStart == start_t::converter); // activates when the converter is switched off + CHECK(unit->protection.groundStart == start_t::automatic); + CHECK(unit->converter.overloadRelayStart == start_t::converter); // activates when the converter is switched off } SUBCASE("other vehicle") { vehicle wagon{definition::load("wagon")}; - CHECK(wagon->GroundRelayStart == start_t::manual); - CHECK(wagon->ConverterOverloadRelayStart == start_t::manual); + CHECK(wagon->protection.groundStart == start_t::manual); + CHECK(wagon->converter.overloadRelayStart == start_t::manual); } SUBCASE("given in the definition") { vehicle unit{definition::load("wagon").set("Param", "Type", "ezt").set("Cntrl", "GroundRelayStart", "Manual").set("Cntrl", "ConverterOverloadRelayStart", "Automatic")}; - CHECK(unit->GroundRelayStart == start_t::manual); - CHECK(unit->ConverterOverloadRelayStart == start_t::automatic); + CHECK(unit->protection.groundStart == start_t::manual); + CHECK(unit->converter.overloadRelayStart == start_t::automatic); } } diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index 24dc4d545..108cf87e2 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -596,7 +596,7 @@ TEST_CASE("collisions: a locomotive at its starting effort against a braked trai }; // the line contactors close at the first position, once their delay and the pressure switch let them locomotive->IncMainCtrl(1); - for (int i = 0; i < 90 && false == locomotive->StLinFlag; ++i) { + for (int i = 0; i < 90 && false == locomotive->lineContactors.closed; ++i) { test::drive(driver, line, 1.0); } for (int i = 0; i < 60 && false == locomotive->IsMainCtrlMaxPowerPos(); ++i) { @@ -1248,7 +1248,7 @@ TEST_CASE("collisions: a locomotive pushing a standing braked train at full powe }; // the line contactors close at the first position, once their delay and the pressure switch let them locomotive->IncMainCtrl(1); - for (int i = 0; i < 90 && false == locomotive->StLinFlag; ++i) { + for (int i = 0; i < 90 && false == locomotive->lineContactors.closed; ++i) { test::drive(driver, line, 1.0); } for (int i = 0; i < 60 && false == locomotive->IsMainCtrlMaxPowerPos(); ++i) { diff --git a/tests/unit/test_commands.cpp b/tests/unit/test_commands.cpp index 859f73336..0fc6ea4c5 100644 --- a/tests/unit/test_commands.cpp +++ b/tests/unit/test_commands.cpp @@ -28,7 +28,7 @@ std::vector state() { std::vector result{ {"MainCtrlPos", [](auto const &M) { return M.MainCtrlPos; }}, {"ScndCtrlPos", [](auto const &M) { return M.ScndCtrlPos; }}, - {"LastRelayTime", [](auto const &M) { return M.LastRelayTime; }}, + {"LastRelayTime", [](auto const &M) { return M.lineContactors.lastSwitchTime; }}, {"eimic_real", [](auto const &M) { return M.eimic_real; }}, {"TUHEX_StageActual", [](auto const &M) { return M.TUHEX_StageActual; }}, {"TUHEX_Active", [](auto const &M) { return flag(M.TUHEX_Active); }}, @@ -46,14 +46,14 @@ std::vector state() { {"OilPumpDisabled", [](auto const &M) { return flag(M.OilPump.is_disabled); }}, {"CompartmentLightsEnabled", [](auto const &M) { return flag(M.CompartmentLights.is_enabled); }}, {"CompartmentLightsDisabled", [](auto const &M) { return flag(M.CompartmentLights.is_disabled); }}, - {"MainSwitch", [](auto const &M) { return flag(M.Mains); }}, + {"MainSwitch", [](auto const &M) { return flag(M.lineBreaker.closed); }}, {"Heating", [](auto const &M) { return flag(M.Heating); }}, {"DirActive", [](auto const &M) { return M.DirActive; }}, {"DirAbsolute", [](auto const &M) { return M.DirAbsolute; }}, {"CabActive", [](auto const &M) { return M.CabActive; }}, {"CabMaster", [](auto const &M) { return flag(M.CabMaster); }}, {"AutoRelayFlag", [](auto const &M) { return flag(M.AutoRelayFlag); }}, - {"ConverterAllow", [](auto const &M) { return flag(M.ConverterAllow); }}, + {"ConverterAllow", [](auto const &M) { return flag(M.converter.allow); }}, {"Battery", [](auto const &M) { return flag(M.Battery); }}, {"CompressorAllow", [](auto const &M) { return flag(M.air.compressor.allow); }}, {"CompressorListPos", [](auto const &M) { return M.air.compressor.listPosition; }}, @@ -411,8 +411,8 @@ TEST_CASE("commands: every switch of the cab, worked on a pair standing under th {"PantFrontActive", [](auto const &M) { return flag(M.pantographs[VehicleEnd::front].is_active); }}, {"PantRearActive", [](auto const &M) { return flag(M.pantographs[VehicleEnd::rear].is_active); }}, {"PantPress", [](auto const &M) { return M.pantographAir.pressure; }}, - {"GroundRelay", [](auto const &M) { return flag(M.GroundRelay); }}, - {"ConverterFlag", [](auto const &M) { return flag(M.ConverterFlag); }}, + {"GroundRelay", [](auto const &M) { return flag(M.protection.ground); }}, + {"ConverterFlag", [](auto const &M) { return flag(M.converter.running); }}, {"CompressorFlag", [](auto const &M) { return flag(M.air.compressor.running); }}, {"Compressor", [](auto const &M) { return M.air.mainReservoirPressure; }}, {"MainCtrlActualPos", [](auto const &M) { return M.MainCtrlActualPos; }}, diff --git a/tests/unit/test_compressor.cpp b/tests/unit/test_compressor.cpp index 033bd4775..e65935672 100644 --- a/tests/unit/test_compressor.cpp +++ b/tests/unit/test_compressor.cpp @@ -47,14 +47,14 @@ TEST_CASE("compressor: without a start delay the compressor starts with its powe run_compressor(vehicle, 1.0); REQUIRE_FALSE(vehicle->air.compressor.running); // no power, no compressor - vehicle->Mains = true; + vehicle->lineBreaker.closed = true; run_compressor(vehicle, step); CHECK(vehicle->air.compressor.running); } TEST_CASE("compressor: the compressor starts the delay after getting its power") { auto vehicle{compressor_vehicle(5.0)}; - vehicle->Mains = true; + vehicle->lineBreaker.closed = true; run_compressor(vehicle, 4.9); CHECK_FALSE(vehicle->air.compressor.running); @@ -68,15 +68,15 @@ TEST_CASE("compressor: the compressor starts the delay after getting its power") TEST_CASE("compressor: the delay starts over once the power is gone") { auto vehicle{compressor_vehicle(5.0)}; - vehicle->Mains = true; + vehicle->lineBreaker.closed = true; run_compressor(vehicle, 10.0); REQUIRE(vehicle->air.compressor.running); - vehicle->Mains = false; // the engine stopped + vehicle->lineBreaker.closed = false; // the engine stopped run_compressor(vehicle, 1.0); CHECK_FALSE(vehicle->air.compressor.running); - vehicle->Mains = true; // and started again + vehicle->lineBreaker.closed = true; // and started again run_compressor(vehicle, 4.9); CHECK_FALSE(vehicle->air.compressor.running); run_compressor(vehicle, 0.2); @@ -85,7 +85,7 @@ TEST_CASE("compressor: the delay starts over once the power is gone") { TEST_CASE("compressor: a compressor fed from the low voltage waits from the low voltage coming on") { auto vehicle{compressor_vehicle(5.0, "")}; // the default supply: the converter, the 110 V - vehicle->Mains = true; // which alone doesn't feed it + vehicle->lineBreaker.closed = true; // which alone doesn't feed it run_compressor(vehicle, 10.0); REQUIRE_FALSE(vehicle->air.compressor.running); @@ -98,7 +98,7 @@ TEST_CASE("compressor: a compressor fed from the low voltage waits from the low TEST_CASE("compressor: the pressure switch stops the compressor above the cut-out pressure") { auto vehicle{compressor_vehicle(0.0)}; - vehicle->Mains = true; + vehicle->lineBreaker.closed = true; vehicle->air.compressedVolume = 8.5; // over MaxCP, in the reservoir of 1 m3 run_compressor(vehicle, step); CHECK(vehicle->air.compressor.governorLock); @@ -107,7 +107,7 @@ TEST_CASE("compressor: the pressure switch stops the compressor above the cut-ou TEST_CASE("compressor: without a pressure switch the air over the cut-out pressure is vented") { auto vehicle{compressor_vehicle(0.0, "Main", 8.0)}; // MinCP the same as MaxCP: no pressure switch - vehicle->Mains = true; + vehicle->lineBreaker.closed = true; vehicle->air.compressedVolume = 8.5; run_compressor(vehicle, step); REQUIRE(vehicle->air.compressor.running); // nothing stops it @@ -116,13 +116,13 @@ TEST_CASE("compressor: without a pressure switch the air over the cut-out pressu TEST_CASE("compressor: an engine stopped before the delay passed counts the whole delay again") { auto vehicle{compressor_vehicle(30.0)}; - vehicle->Mains = true; // engine started + vehicle->lineBreaker.closed = true; // engine started run_compressor(vehicle, 20.0); REQUIRE_FALSE(vehicle->air.compressor.running); - vehicle->Mains = false; // engine stopped, 10 s short of the delay + vehicle->lineBreaker.closed = false; // engine stopped, 10 s short of the delay run_compressor(vehicle, 1.0); - vehicle->Mains = true; + vehicle->lineBreaker.closed = true; run_compressor(vehicle, 15.0); // 36 s since the first start, but only 15 s since this one CHECK_FALSE(vehicle->air.compressor.running); @@ -134,7 +134,7 @@ TEST_CASE("compressor: the start delay holds back a compressor switched on by ha auto vehicle{compressor_vehicle(30.0)}; vehicle->air.compressor.start = start_t::manual; vehicle->air.compressor.allow = true; // switch in the cabinet on before the engine start - vehicle->Mains = true; + vehicle->lineBreaker.closed = true; run_compressor(vehicle, 29.9); CHECK_FALSE(vehicle->air.compressor.running); @@ -175,12 +175,12 @@ definition generator_vehicle(double const ConverterDelay, double const Compresso TEST_CASE("compressor: fed from the converter it waits for the converter start delay") { vehicle loco{generator_vehicle(30.0, 0.0)}; REQUIRE(loco->air.compressor.supply == physics::CompressorSupply::converter); - REQUIRE(loco->ConverterStartDelay == doctest::Approx(30.0)); + REQUIRE(loco->converter.startDelay == doctest::Approx(30.0)); loco.run(1.0); // engine off CHECK_FALSE(loco->Power110vIsAvailable); - loco->Mains = true; // engine started + loco->lineBreaker.closed = true; // engine started loco.run(25.0); CHECK_FALSE(loco->Power110vIsAvailable); CHECK_FALSE(loco->air.compressor.running); @@ -195,7 +195,7 @@ TEST_CASE("compressor: fed from the converter the start delay counts from the co REQUIRE(loco->air.compressor.startDelay == doctest::Approx(10.0)); loco.run(1.0); // engine off - loco->Mains = true; // engine started + loco->lineBreaker.closed = true; // engine started loco.run(25.0); REQUIRE(loco->Power110vIsAvailable); // the converter is up CHECK_FALSE(loco->air.compressor.running); // but the compressor waits for its own delay as well diff --git a/tests/unit/test_crew.cpp b/tests/unit/test_crew.cpp index b0d0e1659..a850194fd 100644 --- a/tests/unit/test_crew.cpp +++ b/tests/unit/test_crew.cpp @@ -31,7 +31,7 @@ void get_under_way(consist &Train, int const Position, double const Seconds) { } test::drive(driver, line, 20.0); driver.controlling.IncMainCtrl(1); - for (int i = 0; i < 90 && false == driver.controlling.StLinFlag; ++i) { + for (int i = 0; i < 90 && false == driver.controlling.lineContactors.closed; ++i) { test::drive(driver, line, 1.0); } for (int i = 0; i < 60 && driver.controlling.MainCtrlPos < Position; ++i) { @@ -194,7 +194,7 @@ TEST_CASE("crew: a locomotive under power left by its driver stops and stays bra auto &eu07{train[0].physics()}; REQUIRE(train[0].speed() > 20.0); REQUIRE(eu07.MainCtrlPos > 0); - REQUIRE(eu07.Mains); + REQUIRE(eu07.lineBreaker.closed); crew::secure(eu07, eu07); @@ -213,7 +213,7 @@ TEST_CASE("crew: a locomotive under power left by its driver stops and stays bra // it keeps standing, also on a slope, with the engine as the driver left it train.run(120.0, track{0.15, 0.02, test::catenary_3kv}); CHECK(std::abs(train[0].speed()) <= 0.01); - CHECK(eu07.Mains); + CHECK(eu07.lineBreaker.closed); CHECK(eu07.Im == doctest::Approx(0.0)); } diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp index 606d1c83f..786d16f1b 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -59,7 +59,7 @@ TEST_CASE("derailment: a vehicle too fast in a curve") { } REQUIRE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); CHECK(eu07vehicle->Derailed == dr::outcome::overturned); - CHECK_FALSE(eu07vehicle->Mains); + CHECK_FALSE(eu07vehicle->lineBreaker.closed); // not stopped dead as the legacy model has it: it slows down at half of g on the 80 of its 96 t auto const start{eu07vehicle->V}; CHECK(start > 0.95 * (critical + 5.0) * kmh); diff --git a/tests/unit/test_engine_shutdown.cpp b/tests/unit/test_engine_shutdown.cpp index e9629c4ed..a3cab4002 100644 --- a/tests/unit/test_engine_shutdown.cpp +++ b/tests/unit/test_engine_shutdown.cpp @@ -27,7 +27,7 @@ TEST_CASE("engine shutdown: the shunter starts with the starter button") { auto shunter{running_shunter()}; REQUIRE(shunter->EngineType == TEngineType::DieselEngine); REQUIRE(shunter->FuelPump.start_type == start_t::automatic); - CHECK(shunter->Mains); + CHECK(shunter->lineBreaker.closed); CHECK(shunter->FuelPump.is_active); CHECK(shunter->enrot > 0.9 * shunter->diesel.minRevolutions); } @@ -36,11 +36,11 @@ TEST_CASE("engine shutdown: neither the fuel pump switch nor the battery switch auto shunter{running_shunter()}; shunter->FuelPumpSwitchOff(true, range_t::local); // the pump started automatically ignores its switch shunter.run(10.0); - CHECK(shunter->Mains); + CHECK(shunter->lineBreaker.closed); shunter->BatterySwitch(false); shunter.run(10.0); CHECK(shunter->Power110vIsAvailable); // the converter run by the engine keeps feeding the fuel pump - CHECK(shunter->Mains); + CHECK(shunter->lineBreaker.closed); CHECK(shunter->enrot > 0.9 * shunter->diesel.minRevolutions); } @@ -49,7 +49,7 @@ TEST_CASE("engine shutdown: the command opening the main circuit stops the engin REQUIRE(shunter->MainCircuitOpensWithStarterOnly()); // the cab passes the command on with only the starter button CHECK(shunter->MainSwitch(false)); shunter.run(20.0); - CHECK_FALSE(shunter->Mains); + CHECK_FALSE(shunter->lineBreaker.closed); CHECK_FALSE(shunter->FuelPump.is_active); CHECK(shunter->enrot == 0.0); } @@ -61,7 +61,7 @@ TEST_CASE("engine shutdown: the engine starts again after it was stopped") { REQUIRE(shunter->enrot == 0.0); shunter->MainSwitch(true); shunter.run(15.0); - CHECK(shunter->Mains); + CHECK(shunter->lineBreaker.closed); CHECK(shunter->enrot > 0.9 * shunter->diesel.minRevolutions); } diff --git a/tests/unit/test_engine_start.cpp b/tests/unit/test_engine_start.cpp index cf9aa4e42..c45019b71 100644 --- a/tests/unit/test_engine_start.cpp +++ b/tests/unit/test_engine_start.cpp @@ -39,7 +39,7 @@ void prepare(consist &Train) { } bool running(physics::Vehicle const &Vehicle) { - return Vehicle.Mains && Vehicle.enrot > 0.5 * Vehicle.diesel.minRevolutions; + return Vehicle.lineBreaker.closed && Vehicle.enrot > 0.5 * Vehicle.diesel.minRevolutions; } // the time step of the train in the loops below @@ -65,8 +65,8 @@ TEST_CASE("engine start: the joint start is the default, and JointEngineStart=No consist train; auto const &joint{train.add(sn61(), 1).physics()}; auto const &separate{train.add(sn61(false)).physics()}; - CHECK(joint.JointEngineStart); - CHECK_FALSE(separate.JointEngineStart); + CHECK(joint.lineBreaker.jointStart); + CHECK_FALSE(separate.lineBreaker.jointStart); CHECK(joint.MainSwitchRange() == range_t::consist); CHECK(separate.MainSwitchRange() == range_t::local); } @@ -120,16 +120,16 @@ TEST_CASE("engine start: by default the cab's switch starts and stops the engine auto &first{train.add(sn61(), 1).physics()}; auto const &second{train.add(sn61()).physics()}; prepare(train); - REQUIRE_FALSE(first.Mains); - REQUIRE_FALSE(second.Mains); + REQUIRE_FALSE(first.lineBreaker.closed); + REQUIRE_FALSE(second.lineBreaker.closed); first.MainSwitch(true, first.MainSwitchRange()); train.run(15.0); CHECK(running(first)); CHECK(running(second)); first.MainSwitch(false, first.MainSwitchRange()); train.run(5.0); - CHECK_FALSE(first.Mains); - CHECK_FALSE(second.Mains); + CHECK_FALSE(first.lineBreaker.closed); + CHECK_FALSE(second.lineBreaker.closed); } TEST_CASE("engine start: with JointEngineStart=No each engine has its own switch") { @@ -142,8 +142,8 @@ TEST_CASE("engine start: with JointEngineStart=No each engine has its own switch first.MainSwitch(true, first.MainSwitchRange()); train.run(15.0); REQUIRE(running(first)); - CHECK_FALSE(second.Mains); - CHECK_FALSE(third.Mains); + CHECK_FALSE(second.lineBreaker.closed); + CHECK_FALSE(third.lineBreaker.closed); // the second one's switch, mainb_*, starts the second engine engine_start::remote_switch switchb; @@ -155,7 +155,7 @@ TEST_CASE("engine start: with JointEngineStart=No each engine has its own switch hold(train, switchb, engineb, 2.0); // past the SN61's delay of 1.5 s train.run(15.0); CHECK(running(second)); - CHECK_FALSE(third.Mains); + CHECK_FALSE(third.lineBreaker.closed); // and the third one's, mainc_*, the third hold(train, switchc, enginec, 2.0); train.run(15.0); @@ -164,12 +164,12 @@ TEST_CASE("engine start: with JointEngineStart=No each engine has its own switch // the switches open their own vehicles' circuits only CHECK(engine_start::remote_switch::open(second)); train.run(5.0); - CHECK_FALSE(second.Mains); + CHECK_FALSE(second.lineBreaker.closed); CHECK(running(first)); CHECK(running(third)); first.MainSwitch(false, first.MainSwitchRange()); train.run(5.0); - CHECK_FALSE(first.Mains); + CHECK_FALSE(first.lineBreaker.closed); CHECK(running(third)); CHECK_FALSE(engine_start::remote_switch::open(second)); // already stopped } @@ -184,7 +184,7 @@ TEST_CASE("engine start: the switch of another vehicle is held for the vehicle's // without the battery the switch does nothing, however long it's held hold(train, switchb, &second, 5.0); train.run(5.0); - CHECK_FALSE(second.Mains); + CHECK_FALSE(second.lineBreaker.closed); CHECK_FALSE(second.diesel.startupRequested); prepare(train); @@ -245,7 +245,7 @@ TEST_CASE("engine start: an engine stopping on its own stops the others only whe // the first one's fuel cut off, its engine stops first.FuelPump.is_disabled = true; train.run(15.0); - CHECK_FALSE(first.Mains); + CHECK_FALSE(first.lineBreaker.closed); CHECK(first.enrot == 0.0); // started on their own, the others keep running CHECK(running(second) == (false == joint)); @@ -275,7 +275,7 @@ TEST_CASE("engine start: an engine stopped from its own switch doesn't stop the // mainb_off CHECK(engine_start::remote_switch::open(second)); train.run(30.0); - CHECK_FALSE(second.Mains); + CHECK_FALSE(second.lineBreaker.closed); CHECK(second.enrot == 0.0); CHECK(running(first)); CHECK(running(third)); @@ -287,12 +287,12 @@ TEST_CASE("engine start: the stopped engine of the cab's vehicle doesn't stop th auto &first{train.add(sn61(), 1).physics()}; auto &second{train.add(sn61(false)).physics()}; prepare(train); - REQUIRE_FALSE(first.Mains); + REQUIRE_FALSE(first.lineBreaker.closed); // mainb_on engine_start::remote_switch switchb; hold(train, switchb, engine_start::engine(first, first, 2), 2.0); train.run(15.0); CHECK(running(second)); - CHECK_FALSE(first.Mains); + CHECK_FALSE(first.lineBreaker.closed); CHECK(first.enrot == 0.0); } diff --git a/tests/unit/test_field_shunting.cpp b/tests/unit/test_field_shunting.cpp index e61783b0e..e1c2c9b8f 100644 --- a/tests/unit/test_field_shunting.cpp +++ b/tests/unit/test_field_shunting.cpp @@ -55,7 +55,7 @@ TEST_CASE("field shunting: the SU45 with its switch, off at full power and switc scenario.get_going(); scenario.full_power(120.0); CHECK(su45.IsMainCtrlMaxPowerPos()); - CHECK(su45.StLinFlag); + CHECK(su45.lineContactors.closed); CHECK(su45.ScndCtrlPos == 0); CHECK_FALSE(su45.IncScndCtrl(1)); scenario.wait(1.0); @@ -87,7 +87,7 @@ TEST_CASE("field shunting: a diesel-electric with AutoRelay=Optional alone shunt scenario.get_going(); scenario.full_power(120.0); CHECK(su45.IsMainCtrlMaxPowerPos()); - CHECK(su45.StLinFlag); + CHECK(su45.lineContactors.closed); // over 50 km/h: the relays don't shunt, the driver does CHECK(su45.Vel > 50.0); CHECK(su45.ScndCtrlPos == 0); diff --git a/tests/unit/test_genset.cpp b/tests/unit/test_genset.cpp index b552ed158..595abff6e 100644 --- a/tests/unit/test_genset.cpp +++ b/tests/unit/test_genset.cpp @@ -80,7 +80,7 @@ bool start_on_genset(vehicle &Vehicle, track const &Track = no_wire, double cons wake(cab); cab.TractionModeSwitch(traction_mode::genset); cab.GensetSwitch(true); - if (false == cab.Mains) { + if (false == cab.lineBreaker.closed) { if (cab.MainSwitchCheck()) { close_line_breaker(cab); } @@ -90,7 +90,7 @@ bool start_on_genset(vehicle &Vehicle, track const &Track = no_wire, double cons cab.CompressorSwitch(true); } run(Vehicle, 1.0, Track); - if (cab.Mains && cab.ConverterFlag && cab.mainPipe.pressure >= 4.5) { + if (cab.lineBreaker.closed && cab.converter.running && cab.mainPipe.pressure >= 4.5) { // and the brakes let go test::release_brakes(cab); for (auto wait = 0; wait < 120 && cab.brakes.cylinderPressure > 0.05; ++wait) { @@ -193,13 +193,13 @@ TEST_CASE("genset: the selector moves only with the line breaker open") { vehicle dragon6{dragon_genset(), 0.0, "test", 1}; auto &cab{dragon6.physics()}; REQUIRE(test::start_up(test::driving(dragon6), wire)); - REQUIRE(cab.Mains); + REQUIRE(cab.lineBreaker.closed); CHECK_FALSE(cab.TractionModeSwitch(traction_mode::genset)); CHECK(cab.TractionMode == traction_mode::catenary); run(dragon6, 2.0, wire); - CHECK(cab.Mains); + CHECK(cab.lineBreaker.closed); cab.MainSwitch(false); - REQUIRE_FALSE(cab.Mains); + REQUIRE_FALSE(cab.lineBreaker.closed); CHECK(cab.TractionModeSwitch(traction_mode::genset)); CHECK(cab.GensetSelected()); CHECK(cab.TractionModeSwitch(traction_mode::catenary)); @@ -223,19 +223,19 @@ TEST_CASE("genset: started, it closes the line breaker without a catenary") { CHECK(cab.Genset.revolutions == cab.Genset.revolutions_idle); CHECK(cab.Genset.voltage == 3000.0); // the line breaker gets ready MainInitTime after the voltage came - for (auto second = 0; second < 10 && false == cab.Mains; ++second) { + for (auto second = 0; second < 10 && false == cab.lineBreaker.closed; ++second) { if (cab.MainSwitchCheck()) { close_line_breaker(cab); } run(dragon6, 1.0); } - REQUIRE(cab.Mains); + REQUIRE(cab.lineBreaker.closed); CHECK(cab.pantographCircuit.supplyVoltage == 0.0); dragon6.step(no_wire); CHECK(cab.EngineVoltage == 3000.0); CHECK(cab.MainCircuitPowered()); run(dragon6, 5.0); - CHECK(cab.Mains); + CHECK(cab.lineBreaker.closed); } TEST_CASE("genset: on the catenary position the genset feeds nothing") { @@ -248,7 +248,7 @@ TEST_CASE("genset: on the catenary position the genset feeds nothing") { CHECK(cab.TractionMode == traction_mode::catenary); CHECK_FALSE(cab.MainSwitchCheck()); close_line_breaker(cab); - CHECK_FALSE(cab.Mains); + CHECK_FALSE(cab.lineBreaker.closed); dragon6.step(no_wire); CHECK(cab.EngineVoltage == 0.0); CHECK(cab.TractionSupplyVoltage() == 0.0); @@ -264,7 +264,7 @@ TEST_CASE("genset: on the genset position the catenary feeds nothing") { // the pantographs up under the wire, the genset stopped: the line breaker never closes CHECK_FALSE(test::start_up(test::driving(dragon6), wire, 120.0)); REQUIRE(cab.pantographCircuit.supplyVoltage > 2900.0); - CHECK_FALSE(cab.Mains); + CHECK_FALSE(cab.lineBreaker.closed); CHECK_FALSE(cab.MainSwitchCheck()); dragon6.step(wire); CHECK(cab.EngineVoltage == 0.0); @@ -280,7 +280,7 @@ TEST_CASE("genset: the power at the wheels stays within the genset's") { auto revolutions{0.0}; auto over{0L}; auto step_count{0L}; - for (; step_count < 60000 && cab.Vel < 80.0 && cab.Mains; ++step_count) { + for (; step_count < 60000 && cab.Vel < 80.0 && cab.lineBreaker.closed; ++step_count) { step(dragon6, step_count); auto const power{wheel_power(cab)}; peak = std::max(peak, power); @@ -291,7 +291,7 @@ TEST_CASE("genset: the power at the wheels stays within the genset's") { } CAPTURE(step_count); CAPTURE(peak); - CHECK(cab.Mains); + CHECK(cab.lineBreaker.closed); CHECK(cab.Vel >= 80.0); CHECK(over == 0); CHECK(peak <= genset_traction_power * 1.02); @@ -382,13 +382,13 @@ TEST_CASE("genset: stopped, it opens the line breaker") { REQUIRE(cab.Genset.revolutions == doctest::Approx(cab.Genset.revolutions_idle)); cab.GensetSwitch(false); auto step_count{0L}; - for (; step_count < 1000 && cab.Mains; ++step_count) { + for (; step_count < 1000 && cab.lineBreaker.closed; ++step_count) { step(dragon6, step_count); } // coasting down from idle, the voltage falls to half, the undervoltage limit, in spinup_time * ln 2 auto const seconds{step_count * 0.01}; CAPTURE(seconds); - CHECK_FALSE(cab.Mains); + CHECK_FALSE(cab.lineBreaker.closed); CHECK(seconds == doctest::Approx(3.0 * std::log(2.0)).epsilon(0.05)); CHECK_FALSE(cab.Genset.is_active); // and it doesn't close again @@ -396,7 +396,7 @@ TEST_CASE("genset: stopped, it opens the line breaker") { close_line_breaker(cab); run(dragon6, 1.0); } - CHECK_FALSE(cab.Mains); + CHECK_FALSE(cab.lineBreaker.closed); // coasting down to a stop, with the time constant spinup_time CHECK(cab.Genset.revolutions < 0.01 * cab.Genset.revolutions_idle); CHECK(cab.Genset.voltage < 0.01 * cab.Genset.voltage_nominal); @@ -448,18 +448,18 @@ TEST_CASE("genset: the pantographs' pressure switch leaves the genset's line bre cab.pantographAir.pressureSwitchActive = true; cab.pantographAir.pressure = 0.0; cab.PantPressureSwitchCheck(); - CHECK(cab.Mains); + CHECK(cab.lineBreaker.closed); } SUBCASE("on the pantographs it opens the line breaker, the check the genset is spared") { vehicle dragon6{dragon_genset(), 0.0, "test", 1}; auto &cab{dragon6.physics()}; REQUIRE(test::start_up(test::driving(dragon6), wire)); - REQUIRE(cab.Mains); + REQUIRE(cab.lineBreaker.closed); // the pressure switch looks at the voltage through the couplers, not the pantographs' cab.pantographAir.pressureSwitchActive = true; cab.pantographAir.pressure = 0.0; cab.PantPressureSwitchCheck(); - CHECK_FALSE(cab.Mains); + CHECK_FALSE(cab.lineBreaker.closed); } } @@ -508,7 +508,7 @@ TEST_CASE("genset: braking electrodynamically on the genset sends nothing back") REQUIRE(braked.electrodynamic); CHECK(braked.lowest_current >= -1e-6); CHECK(braked.speed_lost > 5.0); - CHECK(dragon6->Mains); + CHECK(dragon6->lineBreaker.closed); } SUBCASE("on the catenary the same braking feeds the line, the check the genset is spared") { vehicle dragon6{dragon_genset(), 0.0, "test", 1}; @@ -543,12 +543,12 @@ TEST_CASE("genset: one genset feeds the next car through the high voltage coupli second.RelayReset(relay_t::maincircuitground | relay_t::tractionnmotoroverload | relay_t::primaryconverteroverload, range_t::local); CHECK(second.MainSwitchCheck()); second.MainSwitch(true, range_t::local); - CHECK(second.Mains); + CHECK(second.lineBreaker.closed); // stopped, the genset takes the voltage away first.GensetSwitch(false); train.run(30.0, no_wire); CHECK(second.GetTrainsetHighVoltage() < 1.0); - CHECK_FALSE(second.Mains); + CHECK_FALSE(second.lineBreaker.closed); } TEST_CASE("genset: the selector command travels along the train") { @@ -580,10 +580,10 @@ TEST_CASE("genset: a selector command refused with the line breaker closed isn't auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 1).physics()}; auto &second{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 0, coupling).physics()}; REQUIRE(test::start_up(test::driving(train), wire)); - REQUIRE(first.Mains); + REQUIRE(first.lineBreaker.closed); // the second one's line breaker opened by itself, the lead's is closed second.MainSwitch(false, range_t::local); - REQUIRE_FALSE(second.Mains); + REQUIRE_FALSE(second.lineBreaker.closed); CHECK_FALSE(first.TractionModeSwitch(traction_mode::genset, range_t::consist)); CHECK_FALSE(first.GensetSelected()); CHECK_FALSE(second.GensetSelected()); diff --git a/tests/unit/test_line_contactors.cpp b/tests/unit/test_line_contactors.cpp index 749cf8644..90f3ff2a1 100644 --- a/tests/unit/test_line_contactors.cpp +++ b/tests/unit/test_line_contactors.cpp @@ -9,7 +9,7 @@ namespace { test::vehicle locomotive(bool const Pressureswitch) { test::vehicle vehicle{test::definition::load("wagon").set("Engine", "PressureSwitch", Pressureswitch)}; - vehicle->StLinFlag = false; // the line contactors open + vehicle->lineContactors.closed = false; // the line contactors open vehicle->brakePipe.pressure = 5.0; return vehicle; } @@ -18,16 +18,16 @@ test::vehicle locomotive(bool const Pressureswitch) { TEST_CASE("line contactors: with a pressure switch the lamp goes out with the start cut off") { auto vehicle{locomotive(true)}; - REQUIRE(vehicle->HasControlPressureSwitch); + REQUIRE(vehicle->protection.hasPressureSwitch); vehicle->brakes.cylinderPressure = 1.5; // braked, the start can still be made vehicle->MotorConnectorsCheck(); // updates the pressure switch - REQUIRE_FALSE(vehicle->ControlPressureSwitch); + REQUIRE_FALSE(vehicle->protection.pressureSwitch); CHECK(vehicle->LineContactorsLampLit()); vehicle->brakes.cylinderPressure = 2.5; // the pressure switch cuts the start off vehicle->MotorConnectorsCheck(); - REQUIRE(vehicle->ControlPressureSwitch); + REQUIRE(vehicle->protection.pressureSwitch); CHECK_FALSE(vehicle->LineContactorsLampLit()); } @@ -43,7 +43,7 @@ TEST_CASE("line contactors: without a pressure switch the lamp goes out with the TEST_CASE("line contactors: closed contactors put the lamp out") { auto vehicle{locomotive(true)}; - vehicle->StLinFlag = true; + vehicle->lineContactors.closed = true; CHECK_FALSE(vehicle->LineContactorsLampLit()); } @@ -85,19 +85,19 @@ test::vehicle diesel_electric() { TEST_CASE("line contactors: on a diesel-electric the lamp is lit at 0 and goes out on a power position") { auto vehicle{diesel_electric()}; REQUIRE(vehicle->EngineType == TEngineType::DieselElectric); - REQUIRE(vehicle->Mains); - REQUIRE_FALSE(vehicle->ControlPressureSwitch); - CHECK_FALSE(vehicle->StLinFlag); + REQUIRE(vehicle->lineBreaker.closed); + REQUIRE_FALSE(vehicle->protection.pressureSwitch); + CHECK_FALSE(vehicle->lineContactors.closed); CHECK(vehicle->LineContactorsLampLit()); vehicle->IncMainCtrl(1); vehicle.run(3.0); - CHECK(vehicle->StLinFlag); + CHECK(vehicle->lineContactors.closed); CHECK_FALSE(vehicle->LineContactorsLampLit()); vehicle->DecMainCtrl(1); vehicle.run(3.0); - CHECK_FALSE(vehicle->StLinFlag); + CHECK_FALSE(vehicle->lineContactors.closed); CHECK(vehicle->LineContactorsLampLit()); } @@ -107,12 +107,12 @@ TEST_CASE("line contactors: on a diesel-electric the lamp lights with the contac vehicle.run(1.0); vehicle->IncMainCtrl(1); vehicle.run(2.0); - REQUIRE(vehicle->StLinFlag); + REQUIRE(vehicle->lineContactors.closed); vehicle.hold_brake_pipe(2.5); // bar, below the 3.6 bar of the pressure switch vehicle.run(10.0); - REQUIRE(vehicle->ControlPressureSwitch); - CHECK_FALSE(vehicle->StLinFlag); + REQUIRE(vehicle->protection.pressureSwitch); + CHECK_FALSE(vehicle->lineContactors.closed); CHECK(vehicle->LineContactorsLampLit()); // it went out here CHECK_FALSE(vehicle->MainCircuitLampsEnabled()); // the ground relay and overload lamps still go out with the start cut off @@ -120,11 +120,11 @@ TEST_CASE("line contactors: on a diesel-electric the lamp lights with the contac // they close again only on the first one vehicle.hold_brake_pipe(5.0); vehicle.run(60.0); - REQUIRE_FALSE(vehicle->ControlPressureSwitch); - CHECK_FALSE(vehicle->StLinFlag); + REQUIRE_FALSE(vehicle->protection.pressureSwitch); + CHECK_FALSE(vehicle->lineContactors.closed); CHECK(vehicle->LineContactorsLampLit()); vehicle->DecMainCtrl(1); vehicle.run(3.0); - CHECK(vehicle->StLinFlag); + CHECK(vehicle->lineContactors.closed); CHECK_FALSE(vehicle->LineContactorsLampLit()); } diff --git a/tests/unit/test_line_contactors_interlock.cpp b/tests/unit/test_line_contactors_interlock.cpp index f7f6d69a9..24e025f09 100644 --- a/tests/unit/test_line_contactors_interlock.cpp +++ b/tests/unit/test_line_contactors_interlock.cpp @@ -22,7 +22,7 @@ vehicle ready(std::string_view const Interlock) { loaded.set("Cntrl", "LineContactorsInterlock", std::string{Interlock}); } vehicle locomotive{loaded}; - locomotive->Mains = true; + locomotive->lineBreaker.closed = true; locomotive->DirActive = 1; locomotive->brakePipe.pressure = 5.0; locomotive->brakes.cylinderPressure = 0.0; @@ -34,15 +34,15 @@ test::track const line{0.15, 0.0, test::catenary_3kv}; } // namespace TEST_CASE("line contactors interlock: read from the Cntrl. section, none by default") { - CHECK(ready("")->LineContactorsInterlock == line_contactors_interlock::none); - CHECK(ready("Converter")->LineContactorsInterlock == line_contactors_interlock::converter); - CHECK(ready("MotorBlowers")->LineContactorsInterlock == line_contactors_interlock::motor_blowers); - CHECK(ready("Something")->LineContactorsInterlock == line_contactors_interlock::none); + CHECK(ready("")->lineContactors.interlock == line_contactors_interlock::none); + CHECK(ready("Converter")->lineContactors.interlock == line_contactors_interlock::converter); + CHECK(ready("MotorBlowers")->lineContactors.interlock == line_contactors_interlock::motor_blowers); + CHECK(ready("Something")->lineContactors.interlock == line_contactors_interlock::none); } TEST_CASE("line contactors interlock: without one the converter and the blowers don't matter, as before") { auto locomotive{ready("")}; - locomotive->ConverterFlag = false; + locomotive->converter.running = false; for (auto &blower : locomotive->MotorBlowers) { blower.is_active = false; } @@ -51,12 +51,12 @@ TEST_CASE("line contactors interlock: without one the converter and the blowers TEST_CASE("line contactors interlock: on the converter, they close only with the vehicle's own converter running") { auto locomotive{ready("Converter")}; - locomotive->ConverterFlag = false; + locomotive->converter.running = false; locomotive->Power110vIsAvailable = true; // the 110 V from the other section doesn't run this one's fans CHECK_FALSE(locomotive->MotorConnectorsCheck()); - locomotive->ConverterFlag = true; + locomotive->converter.running = true; CHECK(locomotive->MotorConnectorsCheck()); - locomotive->Mains = false; // the other conditions still hold + locomotive->lineBreaker.closed = false; // the other conditions still hold CHECK_FALSE(locomotive->MotorConnectorsCheck()); } @@ -124,10 +124,10 @@ bool blowers_run(physics::Vehicle const &Physics) { // the driver's first power position, held until the line contactors close (their delay, the pressure switch) bool close_line_contactors(test::driven const &Driven) { Driven.controlling.IncMainCtrl(1); - for (int i = 0; i < 30 && false == Driven.controlling.StLinFlag; ++i) { + for (int i = 0; i < 30 && false == Driven.controlling.lineContactors.closed; ++i) { test::drive(Driven, line, 1.0); } - return Driven.controlling.StLinFlag; + return Driven.controlling.lineContactors.closed; } // the brakes released and the cylinders empty enough for the pressure switch to let the vehicle start @@ -154,7 +154,7 @@ TEST_CASE("line contactors interlock: with blowers starting with the speed the v .set("Engine", "MotorBlowersSustainTime", 10.0), 0.0, "test", 1}; auto &physics{eu07.physics()}; - REQUIRE(physics.LineContactorsInterlock == line_contactors_interlock::motor_blowers); + REQUIRE(physics.lineContactors.interlock == line_contactors_interlock::motor_blowers); REQUIRE(physics.MotorBlowers[VehicleEnd::front].min_start_velocity == doctest::Approx(5.0)); REQUIRE(physics.MotorBlowers[VehicleEnd::rear].sustain_time == doctest::Approx(10.0)); auto driven{test::driving(eu07)}; @@ -177,7 +177,7 @@ TEST_CASE("line contactors interlock: with blowers starting with the speed the v } REQUIRE(eu07.speed() >= 10.0); CHECK(blowers_run(physics)); - CHECK(physics.StLinFlag); + CHECK(physics.lineContactors.closed); // a stop longer than the blowers keep running for while (physics.DecMainCtrl(1)) { @@ -190,7 +190,7 @@ TEST_CASE("line contactors interlock: with blowers starting with the speed the v REQUIRE(std::abs(eu07.speed()) <= 0.1); test::drive(driven, line, 15.0); REQUIRE_FALSE(blowers_run(physics)); - REQUIRE_FALSE(physics.StLinFlag); + REQUIRE_FALSE(physics.lineContactors.closed); // and the vehicle starts again release(driven); @@ -223,7 +223,7 @@ TEST_CASE("line contactors interlock: a blower starting with the speed, switched // the switch of the rear blower: off, the contactors open and stay open, standing as well as later REQUIRE(physics.MotorBlowersSwitchOff(true, VehicleEnd::rear)); test::drive(driven, line, 2.0); - CHECK_FALSE(physics.StLinFlag); + CHECK_FALSE(physics.lineContactors.closed); CHECK(std::abs(physics.Im) < 0.5); while (physics.DecMainCtrl(1)) { // down to zero @@ -245,13 +245,13 @@ TEST_CASE("line contactors interlock: held by the local converter switch only wh // what the AI driver looks at to switch the converter of a section back on (TController, the converteron hint) auto interlocked{ready("Converter")}; CHECK_FALSE(interlocked->LineContactorsHeldByLocalConverterSwitch()); - interlocked->ConverterAllowLocal = false; + interlocked->converter.allowLocal = false; CHECK(interlocked->LineContactorsHeldByLocalConverterSwitch()); for (auto const *other : {"", "MotorBlowers"}) { CAPTURE(other); auto locomotive{ready(other)}; - locomotive->ConverterAllowLocal = false; + locomotive->converter.allowLocal = false; CHECK_FALSE(locomotive->LineContactorsHeldByLocalConverterSwitch()); } } @@ -264,13 +264,13 @@ TEST_CASE("line contactors interlock: the ET42 section with its fans switched of REQUIRE(test::start_up(driven, line)); auto &front{et42[0].physics()}; auto &rear{et42[1].physics()}; - REQUIRE(front.ConverterFlag); - REQUIRE(rear.ConverterFlag); + REQUIRE(front.converter.running); + REQUIRE(rear.converter.running); // the fans of the rear section switched off with its own switch, the 110 V of the front one still reaches it - rear.ConverterAllowLocal = false; + rear.converter.allowLocal = false; test::drive(driven, line, 2.0); - REQUIRE_FALSE(rear.ConverterFlag); + REQUIRE_FALSE(rear.converter.running); CHECK(rear.Power110vIsAvailable); test::release_brakes(driven.cab); @@ -280,23 +280,23 @@ TEST_CASE("line contactors interlock: the ET42 section with its fans switched of test::drive(driven, line, 20.0); driven.controlling.IncMainCtrl(1); // as the AI does, it waits at the first position for the contactors (their delay, the pressure switch) - for (int i = 0; i < 90 && false == front.StLinFlag; ++i) { + for (int i = 0; i < 90 && false == front.lineContactors.closed; ++i) { test::drive(driven, line, 1.0); } - CHECK(front.StLinFlag); - CHECK_FALSE(rear.StLinFlag); + CHECK(front.lineContactors.closed); + CHECK_FALSE(rear.lineContactors.closed); // the fans back on, the section starts too - rear.ConverterAllowLocal = true; + rear.converter.allowLocal = true; test::drive(driven, line, 10.0); - REQUIRE(rear.ConverterFlag); - CHECK(rear.StLinFlag); + REQUIRE(rear.converter.running); + CHECK(rear.lineContactors.closed); // and the fans switched off on the way open its line contactors again - rear.ConverterAllowLocal = false; + rear.converter.allowLocal = false; test::drive(driven, line, 2.0); - CHECK_FALSE(rear.StLinFlag); - CHECK(front.StLinFlag); + CHECK_FALSE(rear.lineContactors.closed); + CHECK(front.lineContactors.closed); } TEST_CASE("louvres: closed until the main reservoir reaches the pressure that opens them") { diff --git a/tests/unit/test_linebreaker.cpp b/tests/unit/test_linebreaker.cpp index 6b132e08e..d0a678c7d 100644 --- a/tests/unit/test_linebreaker.cpp +++ b/tests/unit/test_linebreaker.cpp @@ -37,10 +37,10 @@ struct lever { } // TTrain::Update() void update() { - if (breaker == state::open && physics.Mains) { + if (breaker == state::open && physics.lineBreaker.closed) { breaker = state::closed; } - if (breaker == state::closed && false == physics.Mains) { + if (breaker == state::closed && false == physics.lineBreaker.closed) { breaker = state::open; } if (on && breaker == state::open && physics.MainSwitchCheck()) { @@ -71,16 +71,16 @@ TEST_CASE("line breaker: the EP05's lever goes off with the converter overload r test::track const line{0.15, 0.0, test::catenary_3kv}; auto const driver{test::driving(train)}; REQUIRE(test::start_up(driver, line)); - REQUIRE(ep05.Mains); - REQUIRE(ep05.ConverterFlag); + REQUIRE(ep05.lineBreaker.closed); + REQUIRE(ep05.converter.running); lever ws{ep05, state::closed, true}; // the converter overload relay knocks the line breaker out, as the cab does it when the converter is // switched on together with the compressor; the lever stays on - ep05.ConvOvldFlag = true; + ep05.converter.overloaded = true; ep05.MainSwitch(false, range_t::local); ws.update(); - REQUIRE_FALSE(ep05.Mains); + REQUIRE_FALSE(ep05.lineBreaker.closed); REQUIRE(ws.breaker == state::open); CHECK(ws.on); // with the relay tripped the breaker doesn't close @@ -93,7 +93,7 @@ TEST_CASE("line breaker: the EP05's lever goes off with the converter overload r ws.press(); CHECK(ws.on); ws.update(); - CHECK_FALSE(ep05.Mains); + CHECK_FALSE(ep05.lineBreaker.closed); ws.press(); CHECK_FALSE(ws.on); @@ -101,15 +101,15 @@ TEST_CASE("line breaker: the EP05's lever goes off with the converter overload r ep05.ConverterSwitch(false, range_t::local); test::drive(driver, line, 1.0); CHECK(ep05.RelayReset(relay_t::primaryconverteroverload, range_t::local)); - CHECK_FALSE(ep05.ConvOvldFlag); + CHECK_FALSE(ep05.converter.overloaded); ws.update(); - CHECK_FALSE(ep05.Mains); // the lever is off + CHECK_FALSE(ep05.lineBreaker.closed); // the lever is off ws.press(); ws.update(); - CHECK(ep05.Mains); + CHECK(ep05.lineBreaker.closed); CHECK(ws.breaker == state::closed); // and the next press opens it ws.press(); CHECK_FALSE(ws.on); - CHECK_FALSE(ep05.Mains); + CHECK_FALSE(ep05.lineBreaker.closed); } diff --git a/tests/unit/test_mains_before_pantographs.cpp b/tests/unit/test_mains_before_pantographs.cpp index 374a8709a..7fd62fa35 100644 --- a/tests/unit/test_mains_before_pantographs.cpp +++ b/tests/unit/test_mains_before_pantographs.cpp @@ -69,7 +69,7 @@ void get_under_power(test::vehicle &Loco, test::driven const &Driven, int const test::release_brakes(Driven.cab); test::drive(Driven, line, 20.0); // until the pressure switch lets the line contactors close - for (int i = 0; i < 120 && Loco->ControlPressureSwitch; ++i) { + for (int i = 0; i < 120 && Loco->protection.pressureSwitch; ++i) { test::drive(Driven, line, 1.0); } for (int i = 0; i < Position; ++i) { @@ -80,7 +80,7 @@ void get_under_power(test::vehicle &Loco, test::driven const &Driven, int const REQUIRE(Loco->MainCtrlPos == Position); REQUIRE(Loco->MainCtrlActualPos == Position); REQUIRE(Loco->RList[Position].R > 0.0); // a resistance position - REQUIRE(Loco->StLinFlag); + REQUIRE(Loco->lineContactors.closed); REQUIRE(std::abs(Loco->Im) > 10.0); } @@ -88,29 +88,29 @@ void get_under_power(test::vehicle &Loco, test::driven const &Driven, int const TEST_CASE("mains before pantographs: without the flag the line breaker needs the pantographs' voltage, as before") { test::vehicle loco{ep05(false), 0.0, "test", 1}; - REQUIRE_FALSE(loco->PantographsRequireMains); + REQUIRE_FALSE(loco->lineBreaker.pantographsRequireIt); prepare(loco); close_line_breaker(loco); - CHECK_FALSE(loco->Mains); + CHECK_FALSE(loco->lineBreaker.closed); raise_pantograph(loco); CHECK(loco->pantographs[VehicleEnd::rear].is_active); CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); close_line_breaker(loco); - CHECK(loco->Mains); + CHECK(loco->lineBreaker.closed); // the pantographs stay up with the line breaker open, and the line breaker opens without voltage loco->MainSwitch(false); loco.run(2.0, line); CHECK(loco->pantographs[VehicleEnd::rear].is_active); close_line_breaker(loco); - REQUIRE(loco->Mains); + REQUIRE(loco->lineBreaker.closed); loco->OperatePantographValve(VehicleEnd::rear, operation_t::disable); loco.run(2.0, line); - CHECK_FALSE(loco->Mains); + CHECK_FALSE(loco->lineBreaker.closed); } TEST_CASE("mains before pantographs: with the flag the pantographs rise only through the closed line breaker") { test::vehicle loco{ep05(true), 0.0, "test", 1}; - REQUIRE(loco->PantographsRequireMains); + REQUIRE(loco->lineBreaker.pantographsRequireIt); prepare(loco); // the pantographs stay down while the line breaker is open raise_pantograph(loco); @@ -118,15 +118,15 @@ TEST_CASE("mains before pantographs: with the flag the pantographs rise only thr CHECK(loco->pantographCircuit.supplyVoltage == 0.0); // the line breaker closes without voltage, and the pantograph rises through it close_line_breaker(loco); - CHECK(loco->Mains); + CHECK(loco->lineBreaker.closed); raise_pantograph(loco); CHECK(loco->pantographs[VehicleEnd::rear].is_active); CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); - CHECK(loco->Mains); + CHECK(loco->lineBreaker.closed); // opening the line breaker drops the pantograph, which stays down until the line breaker closes again loco->MainSwitch(false); loco.run(2.0, line); - CHECK_FALSE(loco->Mains); + CHECK_FALSE(loco->lineBreaker.closed); CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); CHECK(loco->pantographCircuit.supplyVoltage == 0.0); // a pantograph lowered under the closed line breaker leaves it closed @@ -136,7 +136,7 @@ TEST_CASE("mains before pantographs: with the flag the pantographs rise only thr loco->OperatePantographValve(VehicleEnd::rear, operation_t::disable); loco.run(5.0, line); CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); - CHECK(loco->Mains); + CHECK(loco->lineBreaker.closed); } TEST_CASE("mains before pantographs: with the flag the line breaker still needs the battery") { @@ -144,7 +144,7 @@ TEST_CASE("mains before pantographs: with the flag the line breaker still needs loco.hold_main_reservoir(6.0); loco.run(2.0, line); close_line_breaker(loco); - CHECK_FALSE(loco->Mains); + CHECK_FALSE(loco->lineBreaker.closed); } TEST_CASE("mains before pantographs: with the flag the driver's start-up gets the locomotive ready") { @@ -152,7 +152,7 @@ TEST_CASE("mains before pantographs: with the flag the driver's start-up gets th test::vehicle loco{ep05(true), 0.0, "test", 1}; auto driven{test::driving(loco)}; REQUIRE(test::start_up(driven, line)); - CHECK(loco->Mains); + CHECK(loco->lineBreaker.closed); CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); CHECK(test::is_ready(driven)); } @@ -164,17 +164,17 @@ TEST_CASE("mains before pantographs: with the flag the converter and the compres test::vehicle loco{ep05(true), 0.0, "test", 1}; prepare(loco); close_line_breaker(loco); - REQUIRE(loco->Mains); + REQUIRE(loco->lineBreaker.closed); REQUIRE(loco->pantographCircuit.supplyVoltage == 0.0); switch_auxiliaries_on(loco); - REQUIRE(loco->ConverterAllow); + REQUIRE(loco->converter.allow); REQUIRE(loco->air.compressor.allow); // the line breaker closed on the battery, the pantographs down: there's nothing to run them on CHECK(reservoir_gain(loco, 20.0, line) < 0.01); - CHECK(loco->Mains); + CHECK(loco->lineBreaker.closed); CHECK_FALSE(loco->MainCircuitPowered()); - CHECK_FALSE(loco->ConverterFlag); + CHECK_FALSE(loco->converter.running); CHECK_FALSE(loco->Power110vIsAvailable); CHECK_FALSE(loco->air.compressor.running); @@ -183,7 +183,7 @@ TEST_CASE("mains before pantographs: with the flag the converter and the compres REQUIRE(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); CHECK(reservoir_gain(loco, 10.0, line) > 0.1); CHECK(loco->MainCircuitPowered()); - CHECK(loco->ConverterFlag); + CHECK(loco->converter.running); CHECK(loco->Power110vIsAvailable); CHECK(loco->air.compressor.running); @@ -205,9 +205,9 @@ TEST_CASE("mains before pantographs: with the flag the converter and the compres REQUIRE(loco->pantographCircuit.supplyVoltage == doctest::Approx(weak.voltage)); } CHECK(reservoir_gain(loco, 10.0, *track) < 0.01); - CHECK(loco->Mains); + CHECK(loco->lineBreaker.closed); CHECK_FALSE(loco->MainCircuitPowered()); - CHECK_FALSE(loco->ConverterFlag); + CHECK_FALSE(loco->converter.running); CHECK_FALSE(loco->Power110vIsAvailable); CHECK_FALSE(loco->air.compressor.running); } @@ -220,7 +220,7 @@ TEST_CASE("mains before pantographs: with the flag whatever else the main circui REQUIRE(loco->HeatingPowerSource.SourceType == TPowerSource::Main); prepare(loco); close_line_breaker(loco); - REQUIRE(loco->Mains); + REQUIRE(loco->lineBreaker.closed); loco->CompressorSwitch(true); loco->MotorBlowersSwitch(true, VehicleEnd::front); loco->RVentForceOn = true; @@ -237,7 +237,7 @@ TEST_CASE("mains before pantographs: with the flag whatever else the main circui raise_pantograph(loco, weak); REQUIRE(loco->pantographCircuit.supplyVoltage == doctest::Approx(weak.voltage)); CHECK(reservoir_gain(loco, 10.0, weak) < 0.01); - CHECK(loco->Mains); + CHECK(loco->lineBreaker.closed); CHECK_FALSE(loco->air.compressor.running); CHECK_FALSE(loco->MotorBlowers[VehicleEnd::front].is_active); CHECK(loco->RventRot == 0.0); @@ -259,18 +259,18 @@ TEST_CASE("mains before pantographs: without the flag the converter and the comp prepare(loco); raise_pantograph(loco); close_line_breaker(loco); - REQUIRE(loco->Mains); + REQUIRE(loco->lineBreaker.closed); switch_auxiliaries_on(loco); CHECK(reservoir_gain(loco, 10.0, line) > 0.1); CHECK(loco->MainCircuitPowered()); - CHECK(loco->ConverterFlag); + CHECK(loco->converter.running); CHECK(loco->Power110vIsAvailable); CHECK(loco->air.compressor.running); // too low a voltage opens the line breaker, and they stop with it loco.run(5.0, weak); - CHECK_FALSE(loco->Mains); + CHECK_FALSE(loco->lineBreaker.closed); CHECK_FALSE(loco->MainCircuitPowered()); - CHECK_FALSE(loco->ConverterFlag); + CHECK_FALSE(loco->converter.running); CHECK_FALSE(loco->Power110vIsAvailable); CHECK_FALSE(loco->air.compressor.running); } @@ -287,10 +287,10 @@ TEST_CASE("mains before pantographs: with the flag the line contactors open when // the voltage goes: the line breaker holds, the pantograph stays up, the motors are cut off test::drive(driven, dead, 3.0); - CHECK(loco->Mains); + CHECK(loco->lineBreaker.closed); CHECK(loco->pantographs[VehicleEnd::rear].is_active); - CHECK_FALSE(loco->NoVoltRelay); - CHECK_FALSE(loco->StLinFlag); + CHECK_FALSE(loco->protection.noVoltage); + CHECK_FALSE(loco->lineContactors.closed); CHECK(loco->Im == 0.0); // the voltage back, with the master controller still where it was: the camshaft went down to zero and stays @@ -298,10 +298,10 @@ TEST_CASE("mains before pantographs: with the flag the line contactors open when test::drive(driven, line, 10.0); REQUIRE(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); REQUIRE(loco->MainCtrlPos == 5); - CHECK(loco->Mains); - CHECK(loco->ConverterFlag); - CHECK_FALSE(loco->NoVoltRelay); - CHECK_FALSE(loco->StLinFlag); + CHECK(loco->lineBreaker.closed); + CHECK(loco->converter.running); + CHECK_FALSE(loco->protection.noVoltage); + CHECK_FALSE(loco->lineContactors.closed); CHECK(loco->MainCtrlActualPos == 0); CHECK(loco->Im == 0.0); @@ -311,13 +311,13 @@ TEST_CASE("mains before pantographs: with the flag the line contactors open when } REQUIRE(loco->MainCtrlPos == 0); test::drive(driven, line, 1.0); - CHECK(loco->NoVoltRelay); - CHECK_FALSE(loco->StLinFlag); + CHECK(loco->protection.noVoltage); + CHECK_FALSE(loco->lineContactors.closed); for (int i = 0; i < 3; ++i) { loco->IncMainCtrl(1); test::drive(driven, line, 2.0); } - CHECK(loco->StLinFlag); + CHECK(loco->lineContactors.closed); CHECK(loco->MainCtrlActualPos == 3); CHECK(std::abs(loco->Im) > 10.0); } @@ -327,8 +327,8 @@ TEST_CASE("mains before pantographs: with the flag the line contactors open when } REQUIRE(loco->MainCtrlPos == 1); test::drive(driven, line, 2.0); - CHECK(loco->NoVoltRelay); - CHECK(loco->StLinFlag); + CHECK(loco->protection.noVoltage); + CHECK(loco->lineContactors.closed); CHECK(loco->MainCtrlActualPos == 1); } } @@ -339,13 +339,13 @@ TEST_CASE("mains before pantographs: without the flag the line breaker opens whe get_under_power(loco, driven, 5); test::drive(driven, dead, 3.0); - CHECK_FALSE(loco->Mains); - CHECK_FALSE(loco->StLinFlag); + CHECK_FALSE(loco->lineBreaker.closed); + CHECK_FALSE(loco->lineContactors.closed); CHECK(loco->Im == 0.0); // and stays open with the voltage back test::drive(driven, line, 10.0); - CHECK_FALSE(loco->Mains); - CHECK_FALSE(loco->StLinFlag); + CHECK_FALSE(loco->lineBreaker.closed); + CHECK_FALSE(loco->lineContactors.closed); CHECK(loco->MainCtrlActualPos == 0); CHECK(loco->Im == 0.0); } diff --git a/tests/unit/test_oil_pump.cpp b/tests/unit/test_oil_pump.cpp index aaac2e871..130145b29 100644 --- a/tests/unit/test_oil_pump.cpp +++ b/tests/unit/test_oil_pump.cpp @@ -21,7 +21,7 @@ TEST_CASE("oil pump: the pre-lubrication pump works before the engine start and loco->OilPumpCheck(0.01); CHECK(loco->OilPump.is_active); - loco->Mains = true; // engine started + loco->lineBreaker.closed = true; // engine started loco->OilPumpCheck(0.01); CHECK_FALSE(loco->OilPump.is_active); } @@ -39,7 +39,7 @@ TEST_CASE("oil pump: the pump started with the engine start procedure stops once loco->OilPumpCheck(0.01); CHECK(loco->OilPump.is_active); - loco->Mains = true; + loco->lineBreaker.closed = true; loco->OilPumpCheck(0.01); CHECK_FALSE(loco->OilPump.is_active); } diff --git a/tests/unit/test_pressure_switch.cpp b/tests/unit/test_pressure_switch.cpp index 75304f5ae..8645b5165 100644 --- a/tests/unit/test_pressure_switch.cpp +++ b/tests/unit/test_pressure_switch.cpp @@ -45,11 +45,11 @@ void get_ready(test::vehicle &Loco, test::driven const &Driven) { REQUIRE(test::start_up(Driven, line)); test::release_brakes(Driven.cab); test::drive(Driven, line, 20.0); - for (int i = 0; i < 120 && Loco->ControlPressureSwitch; ++i) { + for (int i = 0; i < 120 && Loco->protection.pressureSwitch; ++i) { test::drive(Driven, line, 1.0); } - REQUIRE_FALSE(Loco->ControlPressureSwitch); - REQUIRE(Loco->Mains); + REQUIRE_FALSE(Loco->protection.pressureSwitch); + REQUIRE(Loco->lineBreaker.closed); REQUIRE(Loco->pantographs[VehicleEnd::rear].is_active); } @@ -65,7 +65,7 @@ void notch_up(test::vehicle &Loco, test::driven const &Driven, int const Positio void get_under_power(test::vehicle &Loco, test::driven const &Driven, int const Position) { get_ready(Loco, Driven); notch_up(Loco, Driven, Position); - REQUIRE(Loco->StLinFlag); + REQUIRE(Loco->lineContactors.closed); REQUIRE(std::abs(Loco->Im) > 10.0); } @@ -87,14 +87,14 @@ void emergency_application(test::vehicle &Loco, test::driven const &Driven) { TEST_CASE("pressure switch: the keys are off by default") { test::vehicle loco{ep05({}), 0.0, "test", 1}; - CHECK(loco->HasControlPressureSwitch); - CHECK(loco->PressureSwitchBrakeCylinder); - CHECK(loco->EmergencyBrakeMainOffPressure == 0.0); + CHECK(loco->protection.hasPressureSwitch); + CHECK(loco->protection.pressureSwitchWatchesCylinders); + CHECK(loco->lineBreaker.emergencyOffPressure == 0.0); test::vehicle changed{ep05({.brakecylinder = false, .mainoff = true}), 0.0, "test", 1}; - CHECK(changed->HasControlPressureSwitch); - CHECK_FALSE(changed->PressureSwitchBrakeCylinder); - CHECK(changed->EmergencyBrakeMainOffPressure == doctest::Approx(emergency_pressure)); + CHECK(changed->protection.hasPressureSwitch); + CHECK_FALSE(changed->protection.pressureSwitchWatchesCylinders); + CHECK(changed->lineBreaker.emergencyOffPressure == doctest::Approx(emergency_pressure)); } TEST_CASE("pressure switch: with the brake cylinders at 3.8 bar the EP05 takes no current, as before") { @@ -102,13 +102,13 @@ TEST_CASE("pressure switch: with the brake cylinders at 3.8 bar the EP05 takes n auto driven{test::driving(loco)}; get_ready(loco, driven); apply_independent_brake(loco, driven); - CHECK(loco->ControlPressureSwitch); + CHECK(loco->protection.pressureSwitch); CHECK_FALSE(loco->MainCircuitLampsEnabled()); notch_up(loco, driven, 3); - CHECK_FALSE(loco->StLinFlag); + CHECK_FALSE(loco->lineContactors.closed); CHECK(loco->Im == 0.0); - CHECK(loco->Mains); + CHECK(loco->lineBreaker.closed); CHECK(loco->pantographs[VehicleEnd::rear].is_active); } @@ -117,13 +117,13 @@ TEST_CASE("pressure switch: without its brake cylinder half the EP05 takes curre auto driven{test::driving(loco)}; get_ready(loco, driven); apply_independent_brake(loco, driven); - CHECK_FALSE(loco->ControlPressureSwitch); + CHECK_FALSE(loco->protection.pressureSwitch); // the lamps of the main circuit tell the start can be made CHECK(loco->MainCircuitLampsEnabled()); CHECK(loco->LineContactorsLampLit()); notch_up(loco, driven, 3); - CHECK(loco->StLinFlag); + CHECK(loco->lineContactors.closed); CHECK(loco->MainCtrlActualPos == 3); CHECK(std::abs(loco->Im) > 100.0); CHECK(loco->brakes.cylinderPressure == doctest::Approx(3.8).epsilon(0.03)); @@ -144,11 +144,11 @@ TEST_CASE("pressure switch: without its brake cylinder half the brake pipe still SUBCASE("an emergency application") { emergency_application(loco, driven); } - CHECK(loco->ControlPressureSwitch); - CHECK_FALSE(loco->StLinFlag); + CHECK(loco->protection.pressureSwitch); + CHECK_FALSE(loco->lineContactors.closed); CHECK(loco->Im == 0.0); // nothing else lets go without the other key - CHECK(loco->Mains); + CHECK(loco->lineBreaker.closed); CHECK(loco->pantographs[VehicleEnd::rear].is_active); } @@ -166,17 +166,17 @@ TEST_CASE("pressure switch: an emergency application with the master controller test::drive(driven, line, 10.0); REQUIRE(loco->brakePipe.pressure < emergency_pressure); REQUIRE(loco->MainCtrlPos == 5); - CHECK_FALSE(loco->Mains); + CHECK_FALSE(loco->lineBreaker.closed); CHECK_FALSE(loco->pantographs[VehicleEnd::front].is_active); CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); CHECK(loco->pantographCircuit.supplyVoltage == 0.0); - CHECK_FALSE(loco->StLinFlag); + CHECK_FALSE(loco->lineContactors.closed); CHECK(loco->Im == 0.0); // the line breaker doesn't close again while the master controller is where it was loco->MainSwitch(true); test::drive(driven, line, 2.0); - CHECK_FALSE(loco->Mains); + CHECK_FALSE(loco->lineBreaker.closed); CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); } @@ -191,7 +191,7 @@ TEST_CASE("pressure switch: an emergency application with the master controller REQUIRE(loco->MainCtrlPos == 0); emergency_application(loco, driven); - CHECK(loco->Mains); + CHECK(loco->lineBreaker.closed); CHECK(loco->pantographs[VehicleEnd::rear].is_active); CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); CHECK(loco->Im == 0.0); @@ -199,7 +199,7 @@ TEST_CASE("pressure switch: an emergency application with the master controller // and the master controller moved with the pipe empty is the same as the application made with it moved loco->IncMainCtrl(1); test::drive(driven, line, 2.0); - CHECK_FALSE(loco->Mains); + CHECK_FALSE(loco->lineBreaker.closed); CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); } @@ -218,10 +218,10 @@ TEST_CASE("pressure switch: a service application with the master controller on MESSAGE("the lowest brake pipe pressure of the service application: " << lowest << " bar"); REQUIRE(lowest < 3.0); CHECK(lowest > emergency_pressure); - CHECK(loco->Mains); + CHECK(loco->lineBreaker.closed); CHECK(loco->pantographs[VehicleEnd::rear].is_active); // the pressure switch has cut the motors off - CHECK_FALSE(loco->StLinFlag); + CHECK_FALSE(loco->lineContactors.closed); CHECK(loco->Im == 0.0); } @@ -232,26 +232,26 @@ TEST_CASE("pressure switch: without the key an emergency application leaves the emergency_application(loco, driven); REQUIRE(loco->MainCtrlPos == 5); - CHECK(loco->Mains); + CHECK(loco->lineBreaker.closed); CHECK(loco->pantographs[VehicleEnd::rear].is_active); CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); // the pressure switch cuts the motors off - CHECK(loco->ControlPressureSwitch); - CHECK_FALSE(loco->StLinFlag); + CHECK(loco->protection.pressureSwitch); + CHECK_FALSE(loco->lineContactors.closed); CHECK(loco->Im == 0.0); } TEST_CASE("pressure switch: where the pantographs don't hang on the line breaker the emergency application opens only the line breaker") { test::vehicle loco{ep05({.brakecylinder = false, .mainoff = true, .mainsfirst = false}), 0.0, "test", 1}; - REQUIRE_FALSE(loco->PantographsRequireMains); + REQUIRE_FALSE(loco->lineBreaker.pantographsRequireIt); auto driven{test::driving(loco)}; get_under_power(loco, driven, 5); emergency_application(loco, driven); - CHECK_FALSE(loco->Mains); + CHECK_FALSE(loco->lineBreaker.closed); CHECK(loco->pantographs[VehicleEnd::rear].is_active); CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); - CHECK_FALSE(loco->StLinFlag); + CHECK_FALSE(loco->lineContactors.closed); CHECK(loco->Im == 0.0); } @@ -263,33 +263,33 @@ TEST_CASE("pressure switch: after the emergency application the driver's start-u auto driven{test::driving(loco)}; get_under_power(loco, driven, 5); emergency_application(loco, driven); - REQUIRE_FALSE(loco->Mains); + REQUIRE_FALSE(loco->lineBreaker.closed); REQUIRE_FALSE(loco->pantographs[VehicleEnd::rear].is_active); REQUIRE(loco->pantographs[VehicleEnd::rear].valve.is_enabled); // with the brake pipe still empty REQUIRE(test::start_up(driven, line, 60.0)); CHECK(loco->MainCtrlPos == 0); - CHECK(loco->Mains); + CHECK(loco->lineBreaker.closed); CHECK(loco->pantographs[VehicleEnd::rear].is_active); CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); REQUIRE(loco->brakePipe.pressure < emergency_pressure); // and it stays so test::drive(driven, line, 30.0); - CHECK(loco->Mains); + CHECK(loco->lineBreaker.closed); CHECK(loco->pantographs[VehicleEnd::rear].is_active); // the brakes released (the AI fills an emptied pipe with the releaser held, TController::control_releaser()), // the pressure switch lets the start be made test::release_brakes(driven.cab); - for (int i = 0; i < 180 && loco->ControlPressureSwitch; ++i) { + for (int i = 0; i < 180 && loco->protection.pressureSwitch; ++i) { loco->BrakeReleaser(loco->brakePipe.pressure < 3.0 ? 1 : 0); test::drive(driven, line, 1.0); } loco->BrakeReleaser(0); - REQUIRE_FALSE(loco->ControlPressureSwitch); + REQUIRE_FALSE(loco->protection.pressureSwitch); notch_up(loco, driven, 3); - CHECK(loco->Mains); - CHECK(loco->StLinFlag); + CHECK(loco->lineBreaker.closed); + CHECK(loco->lineContactors.closed); CHECK(std::abs(loco->Im) > 10.0); } diff --git a/tests/unit/test_smoke.cpp b/tests/unit/test_smoke.cpp index 7f204927c..5ee3a75f3 100644 --- a/tests/unit/test_smoke.cpp +++ b/tests/unit/test_smoke.cpp @@ -102,10 +102,10 @@ namespace { // the locomotive's engine started the way the AI starts it, a second at a time, until it runs (Mains) bool start_engine(test::driven const &Driven, test::track const &Track) { - for (int second = 0; second < 120 && false == Driven.controlling.Mains; ++second) { + for (int second = 0; second < 120 && false == Driven.controlling.lineBreaker.closed; ++second) { test::start_up(Driven, Track, 1.0); } - return Driven.controlling.Mains; + return Driven.controlling.lineBreaker.closed; } } // namespace @@ -126,7 +126,7 @@ TEST_CASE("smoke: a real diesel smokes only once its engine has fired, SmokeDela CHECK(smoke::vehicle_spawn_count(locomotive.physics(), true, source, update) == 0.f); // it has fired since test::drive(driven, track, 3.0); - CHECK(locomotive->Mains); + CHECK(locomotive->lineBreaker.closed); CHECK(locomotive->diesel.firingCountdown == 0.0); CHECK(smoke::vehicle_spawn_count(locomotive.physics(), true, source, update) >= 1.f); } diff --git a/tests/unit/test_speed_control.cpp b/tests/unit/test_speed_control.cpp index 09647c188..41047924b 100644 --- a/tests/unit/test_speed_control.cpp +++ b/tests/unit/test_speed_control.cpp @@ -57,7 +57,7 @@ void get_6dg_going(scenario &Scenario) { Scenario.wait(1.0); move_to(loco, dg_hold); Scenario.wait(5.0); - REQUIRE(loco.StLinFlag); + REQUIRE(loco.lineContactors.closed); } } // namespace @@ -309,7 +309,7 @@ TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the CHECK(higher == doctest::Approx(held + 10.0).epsilon(0.1)); count_shunting(scenario, loco, 60, shunted, unshunted); CHECK(loco.Vel == doctest::Approx(higher).epsilon(0.03)); - CHECK(loco.StLinFlag); + CHECK(loco.lineContactors.closed); CHECK(shunted > 0); CHECK(unshunted > 0); CHECK_FALSE(loco.IncScndCtrl(1)); // still not the driver's @@ -321,13 +321,13 @@ TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the // it brakes down with the air (BrakeIntervention), which opens the line contactors (the pressure switch), and // they close again only through the first power position of the controller, as without the cruise control CHECK(loco.Vel < 35.0); - CHECK_FALSE(loco.StLinFlag); + CHECK_FALSE(loco.lineContactors.closed); scenario.act("controller to the first power position and back up"); move_to(loco, dg_lower); scenario.wait(2.0); move_to(loco, dg_raise); scenario.wait(60.0); - CHECK(loco.StLinFlag); + CHECK(loco.lineContactors.closed); CHECK(loco.Vel == doctest::Approx(30.0).epsilon(0.05)); CHECK(loco.ScndCtrlPos == 0); // out at this speed @@ -356,7 +356,7 @@ TEST_CASE("speed control apart: the ST45's cruise control on its own switch, wit CHECK(loco.SpeedCtrlValue == doctest::Approx(60.0)); scenario.wait(90.0); CHECK(loco.Vel == doctest::Approx(60.0).epsilon(0.03)); - CHECK(loco.StLinFlag); + CHECK(loco.lineContactors.closed); scenario.act("step up, power down"); loco.SpeedCtrlInc(); CHECK(loco.SpeedCtrlValue == doctest::Approx(65.0)); diff --git a/tests/unit/test_traction.cpp b/tests/unit/test_traction.cpp index 8ae1d1f9f..5fd81fd95 100644 --- a/tests/unit/test_traction.cpp +++ b/tests/unit/test_traction.cpp @@ -33,7 +33,7 @@ TEST_CASE("traction: every real powered vehicle started up, driven to full power test::drive_cycle(test::driving(real), test::track{0.15, 0.0, test::catenary_3kv}, trace); // every vehicle getting its line breaker closed runs off and is braked to a stop. the SM31 and the TEM2 // barely move (COVERAGE.md); the cars of a unit taking their power from another car don't start alone - if (real->Mains) { + if (real->lineBreaker.closed) { auto const crawls{path == "sm31_v1/411d" || path == "tem2_v2/tem2a"}; CHECK((real->DistCounter > 0.2 /* km */) != crawls); // but the road vehicle, which a minute of full service only slows down @@ -72,11 +72,11 @@ TEST_CASE("traction: the line breaker opened by the catenary lost, and by too hi scenario.get_going(); auto &controlling{scenario.driver().controlling}; scenario.full_power(10.0); - REQUIRE(controlling.Mains); + REQUIRE(controlling.lineBreaker.closed); scenario.act("catenary lost"); scenario.line().voltage = 0.0; scenario.wait(5.0); - CHECK_FALSE(controlling.Mains); + CHECK_FALSE(controlling.lineBreaker.closed); CHECK(controlling.Im == doctest::Approx(0.0)); scenario.act("catenary back"); scenario.line().voltage = test::catenary_3kv; @@ -86,7 +86,7 @@ TEST_CASE("traction: the line breaker opened by the catenary lost, and by too hi scenario.act("overvoltage"); scenario.line().voltage = controlling.EnginePowerSource.CollectorParameters.MaxV + 300.0; scenario.wait(5.0); - CHECK(controlling.Mains == (controlling.EngineType == TEngineType::ElectricSeriesMotor && false == controlling.EnginePowerSource.CollectorParameters.OVP)); + CHECK(controlling.lineBreaker.closed == (controlling.EngineType == TEngineType::ElectricSeriesMotor && false == controlling.EnginePowerSource.CollectorParameters.OVP)); scenario.line().voltage = test::catenary_3kv; stop(scenario); scenario.check(); diff --git a/vehicle/ai/consist.cpp b/vehicle/ai/consist.cpp index ed08ac78d..30176ce2f 100644 --- a/vehicle/ai/consist.cpp +++ b/vehicle/ai/consist.cpp @@ -823,17 +823,17 @@ TController::determine_consist_state() { [this, &islocalconverterswitchoff]( TDynamicObject * Vehicle ) { auto const *vehicle { Vehicle->physics }; islocalconverterswitchoff |= vehicle->LineContactorsHeldByLocalConverterSwitch(); - IsAnyConverterOverloadRelayOpen |= vehicle->ConvOvldFlag; + IsAnyConverterOverloadRelayOpen |= vehicle->converter.overloaded; IsAnyMotorOverloadRelayOpen |= vehicle->FuseFlag; - IsAnyGroundRelayOpen |= !vehicle->GroundRelay; + IsAnyGroundRelayOpen |= !vehicle->protection.ground; IsAnyCompressorPresent |= vehicle->air.compressor.speed > 0.0; IsAnyCompressorEnabled |= vehicle->air.compressor.speed > 0.0 ? (vehicle->air.compressor.allow || vehicle->air.compressor.start == start_t::automatic) && vehicle->air.compressor.allowLocal : false; IsAnyCompressorExplicitlyEnabled |= vehicle->air.compressor.speed > 0.0 ? vehicle->air.compressor.allow && vehicle->air.compressor.allowLocal : false; - IsAnyConverterPresent |= vehicle->ConverterStart != start_t::disabled; - IsAnyConverterEnabled |= ( vehicle->ConverterAllow || vehicle->ConverterStart == start_t::automatic ) && vehicle->ConverterAllowLocal; - IsAnyConverterExplicitlyEnabled |= vehicle->ConverterAllow && vehicle->ConverterAllowLocal; + IsAnyConverterPresent |= vehicle->converter.start != start_t::disabled; + IsAnyConverterEnabled |= ( vehicle->converter.allow || vehicle->converter.start == start_t::automatic ) && vehicle->converter.allowLocal; + IsAnyConverterExplicitlyEnabled |= vehicle->converter.allow && vehicle->converter.allowLocal; if( vehicle->Power > 0.01 ) { - IsAnyLineBreakerOpen |= !vehicle->Mains; } } ); + IsAnyLineBreakerOpen |= !vehicle->lineBreaker.closed; } } ); // siłę generują pojazdy na pochyleniu ale działa ona całość składu, więc a=F/m fAccGravity *= iDirection >= 0 ? 1 : -1; @@ -950,7 +950,7 @@ TController::determine_consist_state() { if( has_diesel_engine() ) { Ready = vehicle->Vel > EU07_AI_MOVEMENT // already moving - || false == vehicle->Mains // deadweight vehicle + || false == vehicle->lineBreaker.closed // deadweight vehicle || vehicle->enrot > 0.8 * (vehicle->EngineType == TEngineType::DieselEngine ? vehicle->diesel.minRevolutions : vehicle->DElist[0].RPM / 60.0); } p = p->Next(); // pojazd podłączony z tyłu (patrząc od czoła) diff --git a/vehicle/ai/controls.cpp b/vehicle/ai/controls.cpp index d488e2c53..c2cc203c2 100644 --- a/vehicle/ai/controls.cpp +++ b/vehicle/ai/controls.cpp @@ -508,7 +508,7 @@ bool TController::IncSpeed() if( mvControlling->EnginePowerSource.SourceType == TPowerSource::Accumulator ) { fVoltage = mvControlling->BatteryVoltage; } - if (!IsAnyMotorOverloadRelayOpen && !mvControlling->ControlPressureSwitch && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->StLinFlag) && (Ready || drivingFlags.press)) { + if (!IsAnyMotorOverloadRelayOpen && !mvControlling->protection.pressureSwitch && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->lineContactors.closed) && (Ready || drivingFlags.press)) { // youBy polecił dodać 2012-09-08 v367 // na pozycji 0 przejdzie, a na pozostałych będzie czekać, aż się załączą liniowe (zgaśnie DelayCtrlFlag) auto const usehighoverloadrelaythreshold{mvControlling->TrainType != train_type::et42 // ET42 uses these variables for different purpose. TODO: fix this @@ -536,7 +536,7 @@ bool TController::IncSpeed() occupied->Vel <= (IsCargoTrain ? 40 : 30) + (seriesmodefieldshunting ? 5 : 0) - (fAccGravity < -0.025 ? 10 : 0)); // when not in series mode use the first available parallel mode configuration until 50/60 km/h for passenger/cargo train // (if there's only one parallel mode configuration it'll be used regardless of current speed) - auto const usefieldshunting = mvControlling->StLinFlag && mvControlling->RList[mvControlling->MainCtrlPos].R < 0.01 && false == mvControlling->IsScndCtrlLockedByMainCtrl() && + auto const usefieldshunting = mvControlling->lineContactors.closed && mvControlling->RList[mvControlling->MainCtrlPos].R < 0.01 && false == mvControlling->IsScndCtrlLockedByMainCtrl() && (useseriesmode ? mvControlling->RList[mvControlling->MainCtrlPos].Bn == 1 : true == sufficientacceleration && true == sufficienttractionforce && occupied->Vel <= (IsCargoTrain ? 60 : 50) + (parallelmodefieldshunting ? 5 : 0) ? mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1 : @@ -607,7 +607,7 @@ bool TController::IncSpeed() OK = sufficientpowermargin && false == mvControlling->DelayCtrlFlag ? mvControlling->IncMainCtrl(1) : true; // czekaj na 1 pozycji, zanim się nie włączą liniowe - if (true == mvControlling->StLinFlag) + if (true == mvControlling->lineContactors.closed) { drivingFlags.incSpeed = true; } @@ -643,7 +643,7 @@ bool TController::IncSpeed() } break; case TEngineType::DieselElectric: - if (!IsAnyMotorOverloadRelayOpen && !mvControlling->ControlPressureSwitch && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->StLinFlag) && (Ready || drivingFlags.press)) { + if (!IsAnyMotorOverloadRelayOpen && !mvControlling->protection.pressureSwitch && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->lineContactors.closed) && (Ready || drivingFlags.press)) { // youBy polecił dodać 2012-09-08 v367 // na pozycji 0 przejdzie, a na pozostałych będzie czekać, aż się załączą liniowe (zgaśnie DelayCtrlFlag) //{(BrakePress<=0.01*MaxBrakePress)} @@ -658,7 +658,7 @@ bool TController::IncSpeed() if( !IsAnyMotorOverloadRelayOpen && (Ready || drivingFlags.press || occupied->ShuntMode) ) { //{(BrakePress<=0.01*MaxBrakePress)} OK = IncSpeedEIM(); - if (mvControlling->SpeedCtrl && mvControlling->Mains) + if (mvControlling->SpeedCtrl && mvControlling->lineBreaker.closed) { // cruise control auto const couplinginprogress{true == drivingFlags.connect && true == OrderCurrentGet().HasAll(DriverOrder::connect)}; @@ -689,7 +689,7 @@ bool TController::IncSpeed() { // dla 2Ls150 można zmienić tryb pracy, jeśli jest w liniowym i nie daje rady (wymaga zerowania kierunku) // mvControlling->ShuntMode=(OrderList[OrderPos]&Shunt)||(fMass>224000.0); } - if (mvControlling->SpeedCtrl && mvControlling->Mains) {// cruise control + if (mvControlling->SpeedCtrl && mvControlling->lineBreaker.closed) {// cruise control auto const couplinginprogress { true == drivingFlags.connect && true == OrderCurrentGet().HasAll(DriverOrder::connect) }; auto const SpeedCntrlVel { ( ActualProximityDist > std::max(50.0, fMaxProximityDist) || couplinginprogress ? @@ -725,7 +725,7 @@ bool TController::IncSpeed() } } // TODO: move this check to a more suitable place, or scrap it - if( false == mvControlling->Mains ) { + if( false == mvControlling->lineBreaker.closed ) { SpeedCntrl(0.0); mvControlling->DecScndCtrl( 2 ); cue_action( driver_hint::linebreakerclose ); @@ -935,7 +935,7 @@ void TController::SpeedSet() { } if( mvControlling->MainCtrlPos > 0 - && false == mvControlling->StLinFlag ) { + && false == mvControlling->lineContactors.closed ) { // jak niby jedzie, ale ma rozłączone liniowe to na zero i czekać na przewalenie kułakowego mvControlling->DecMainCtrl( 2 ); } @@ -1278,7 +1278,7 @@ void TController::SetTimeControllers() } } // 5.5 universal control for diesel electric vehicles - if (mvControlling->EngineType == TEngineType::DieselElectric && mvControlling->EIMCtrlType == 3 && AccDesired >= 0.0 && mvControlling->StLinFlag) + if (mvControlling->EngineType == TEngineType::DieselElectric && mvControlling->EIMCtrlType == 3 && AccDesired >= 0.0 && mvControlling->lineContactors.closed) { // NOTE: partial implementation for speedinc/dec // TBD, TODO: implement fully? diff --git a/vehicle/ai/engine.cpp b/vehicle/ai/engine.cpp index 5aedc3b66..33884cac8 100644 --- a/vehicle/ai/engine.cpp +++ b/vehicle/ai/engine.cpp @@ -86,7 +86,7 @@ bool TController::PrepareEngine() } } - if( mvControlling->PantographsRequireMains + if( mvControlling->lineBreaker.pantographsRequireIt && IsAnyLineBreakerOpen ) { // the pantographs rise only through the closed line breaker, which closes without their voltage PrepareDirection(); @@ -307,7 +307,7 @@ bool TController::ReleaseEngine() { cue_action( driver_hint::frontpantographvalveoff ); cue_action( driver_hint::rearpantographvalveoff ); - if( false == mvControlling->Mains ) { + if( false == mvControlling->lineBreaker.closed ) { // finish vehicle shutdown if( has_diesel_engine() ) { // heating/cooling subsystem @@ -338,7 +338,7 @@ bool TController::ReleaseEngine() { occupied->DirActive == 0 // && ( false == IsAnyCompressorEnabled ) // && ( false == IsAnyConverterEnabled ) - && false == mvControlling->Mains + && false == mvControlling->lineBreaker.closed && false == occupied->Power24vIsAvailable }; if (OK) { diff --git a/vehicle/ai/situation.cpp b/vehicle/ai/situation.cpp index 84b7de29e..a6c7fbd78 100644 --- a/vehicle/ai/situation.cpp +++ b/vehicle/ai/situation.cpp @@ -403,7 +403,7 @@ TController::control_handles() { switch( mvControlling->EngineType ) { case TEngineType::ElectricSeriesMotor: { // styczniki liniowe rozłączone yBARC - if( false == mvControlling->StLinFlag + if( false == mvControlling->lineContactors.closed && false == mvControlling->DelayCtrlFlag && mvControlling->MainCtrlPowerPos() > 1 ) { cue_action( driver_hint::mastercontrollersetzerospeed ); @@ -427,7 +427,7 @@ TController::control_handles() { } case TEngineType::DieselElectric: { // styczniki liniowe rozłączone yBARC - if( false == mvControlling->StLinFlag + if( false == mvControlling->lineContactors.closed && false == mvControlling->DelayCtrlFlag && mvControlling->MainCtrlPowerPos() > 1 ) { cue_action( driver_hint::mastercontrollersetzerospeed ); diff --git a/vehicle/cab/auxiliarycommands.cpp b/vehicle/cab/auxiliarycommands.cpp index dac2aea49..cb7540cc8 100644 --- a/vehicle/cab/auxiliarycommands.cpp +++ b/vehicle/cab/auxiliarycommands.cpp @@ -682,9 +682,9 @@ void TTrain::OnCommand_convertertoggle(TTrain *Train, command_data const &Comman if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const overloadrelayisopen{(Train->Dynamic()->Mechanik != nullptr ? Train->Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : Train->occupied->ConvOvldFlag)}; + auto const overloadrelayisopen{(Train->Dynamic()->Mechanik != nullptr ? Train->Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : Train->occupied->converter.overloaded)}; - if (Train->occupied->ConvSwitchType != "impulse" ? Train->ggConverterButton.GetValue() < 0.5 : false == Train->occupied->Power110vIsAvailable && false == overloadrelayisopen) + if (Train->occupied->converter.switchType != "impulse" ? Train->ggConverterButton.GetValue() < 0.5 : false == Train->occupied->Power110vIsAvailable && false == overloadrelayisopen) { // turn on OnCommand_converterenable(Train, Command); @@ -698,7 +698,7 @@ void TTrain::OnCommand_convertertoggle(TTrain *Train, command_data const &Comman else if (Command.action == GLFW_RELEASE) { // on button release... - if (Train->occupied->ConvSwitchType == "impulse") + if (Train->occupied->converter.switchType == "impulse") { // ...return switches to start position if applicable Train->ggConverterButton.UpdateValue(0.0, Train->dsbSwitch); @@ -717,7 +717,7 @@ void TTrain::OnCommand_converterenable(TTrain *Train, command_data const &Comman // impulse type switch has no effect if there's no power // NOTE: this is most likely setup wrong, but the whole thing is smoke and mirrors anyway - if (Train->occupied->ConvSwitchType != "impulse" || Train->controlled->Mains) + if (Train->occupied->converter.switchType != "impulse" || Train->controlled->lineBreaker.closed) { // won't start if the line breaker button is still held Train->occupied->ConverterSwitch(true); @@ -754,7 +754,7 @@ void TTrain::OnCommand_converterdisable(TTrain *Train, command_data const &Comma void TTrain::OnCommand_convertertogglelocal(TTrain *Train, command_data const &Command) { - if (Train->occupied->ConverterStart == start_t::automatic) + if (Train->occupied->converter.start == start_t::automatic) { // let the automatic thing do its automatic thing... return; @@ -767,13 +767,13 @@ void TTrain::OnCommand_convertertogglelocal(TTrain *Train, command_data const &C if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->occupied->ConverterAllowLocal && Train->ggConverterLocalButton.GetValue() < 0.5) + if (false == Train->occupied->converter.allowLocal && Train->ggConverterLocalButton.GetValue() < 0.5) { // turn on // visual feedback Train->ggConverterLocalButton.UpdateValue(1.0, Train->dsbSwitch); // effect - Train->occupied->ConverterAllowLocal = true; + Train->occupied->converter.allowLocal = true; /* if( true == Train->controlled->ConverterSwitch( true, range::local ) ) { // side effects @@ -791,7 +791,7 @@ void TTrain::OnCommand_convertertogglelocal(TTrain *Train, command_data const &C // visual feedback Train->ggConverterLocalButton.UpdateValue(0.0, Train->dsbSwitch); // effect - Train->occupied->ConverterAllowLocal = false; + Train->occupied->converter.allowLocal = false; /* if( true == Train->controlled->ConverterSwitch( false, range::local ) ) { // side effects diff --git a/vehicle/cab/powercommands.cpp b/vehicle/cab/powercommands.cpp index dc4dc14ff..6d15e634d 100644 --- a/vehicle/cab/powercommands.cpp +++ b/vehicle/cab/powercommands.cpp @@ -403,13 +403,13 @@ void TTrain::OnCommand_motorconnectorsopen(TTrain *Train, command_data const &Co if (Command.action == GLFW_PRESS) { // button works while it's held down but we can ignore repeats - if (false == Train->controlled->StLinSwitchOff) + if (false == Train->controlled->lineContactors.forcedOpen) { // open the connectors // visual feedback Train->ggStLinOffButton.UpdateValue(1.0, Train->dsbSwitch); - Train->controlled->StLinSwitchOff = true; + Train->controlled->lineContactors.forcedOpen = true; Train->set_paired_open_motor_connectors_button(true); } else @@ -421,13 +421,13 @@ void TTrain::OnCommand_motorconnectorsopen(TTrain *Train, command_data const &Co else if (Command.action == GLFW_RELEASE) { // button released - if (Train->controlled->StLinSwitchType != "toggle") + if (Train->controlled->lineContactors.switchType != "toggle") { // default button type (impulse) ceases its work on button release // visual feedback Train->ggStLinOffButton.UpdateValue(0.0, Train->dsbSwitch); - Train->controlled->StLinSwitchOff = false; + Train->controlled->lineContactors.forcedOpen = false; Train->set_paired_open_motor_connectors_button(false); } } @@ -448,19 +448,19 @@ void TTrain::OnCommand_motorconnectorsclose(TTrain *Train, command_data const &C if (Command.action == GLFW_PRESS) { - if (Train->controlled->StLinSwitchType == "toggle") + if (Train->controlled->lineContactors.switchType == "toggle") { // default type of button (impulse) has only one effect on press, but the toggle type can toggle the state // visual feedback Train->ggStLinOffButton.UpdateValue(0.0, Train->dsbSwitch); } - if (false == Train->controlled->StLinSwitchOff) + if (false == Train->controlled->lineContactors.forcedOpen) { return; } // already closed - Train->controlled->StLinSwitchOff = false; + Train->controlled->lineContactors.forcedOpen = false; Train->set_paired_open_motor_connectors_button(false); } } diff --git a/vehicle/cab/setup.cpp b/vehicle/cab/setup.cpp index 116d2b8dc..118a6ff30 100644 --- a/vehicle/cab/setup.cpp +++ b/vehicle/cab/setup.cpp @@ -930,7 +930,7 @@ void TTrain::set_cab_controls(int const Cab) } // motor connectors - ggStLinOffButton.PutValue(controlled->StLinSwitchOff ? 1.f : 0.f); + ggStLinOffButton.PutValue(controlled->lineContactors.forcedOpen ? 1.f : 0.f); // radio ggRadioChannelSelector.PutValue(static_cast((Dynamic()->Mechanik ? Dynamic()->Mechanik->iRadioChannel : 1) - 1)); // pantographs @@ -989,11 +989,11 @@ void TTrain::set_cab_controls(int const Cab) 1.f); ggPantCompressorButton.PutValue(pantographUnit->pantographAir.compressorRunning ? 1.f : 0.f); // converter - if (occupied->ConvSwitchType != "impulse") + if (occupied->converter.switchType != "impulse") { - ggConverterButton.PutValue(occupied->ConverterAllow ? 1.f : 0.f); + ggConverterButton.PutValue(occupied->converter.allow ? 1.f : 0.f); } - ggConverterLocalButton.PutValue(occupied->ConverterAllowLocal ? 1.f : 0.f); + ggConverterLocalButton.PutValue(occupied->converter.allowLocal ? 1.f : 0.f); // compressor ggCompressorButton.PutValue(controlled->air.compressor.allow ? 1.f : 0.f); ggCompressorLocalButton.PutValue(controlled->air.compressor.allowLocal ? 1.f : 0.f); diff --git a/vehicle/cab/train.cpp b/vehicle/cab/train.cpp index 2a54c74f7..d0c889eb2 100644 --- a/vehicle/cab/train.cpp +++ b/vehicle/cab/train.cpp @@ -174,11 +174,11 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("master", occupied->CabMaster); // basic systems state data dict->insert("battery", occupied->Power24vIsAvailable); - dict->insert("linebreaker", controlled->Mains); - dict->insert("main_init", controlled->MainsInitTimeCountdown < controlled->MainsInitTime && controlled->MainsInitTimeCountdown > 0.0); - dict->insert("main_ready", false == controlled->Mains && fHVoltage > 0.0 && controlled->MainsInitTimeCountdown <= 0.0); + dict->insert("linebreaker", controlled->lineBreaker.closed); + dict->insert("main_init", controlled->lineBreaker.initCountdown < controlled->lineBreaker.initTime && controlled->lineBreaker.initCountdown > 0.0); + dict->insert("main_ready", false == controlled->lineBreaker.closed && fHVoltage > 0.0 && controlled->lineBreaker.initCountdown <= 0.0); dict->insert("converter", occupied->Power110vIsAvailable); - dict->insert("converter_overload", controlled->ConvOvldFlag); + dict->insert("converter_overload", controlled->converter.overloaded); dict->insert("compress", controlled->air.compressor.running); dict->insert("pant_compressor", pantographUnit->pantographAir.compressorRunning); dict->insert("lights_front", occupied->iLights[VehicleEnd::front]); @@ -521,11 +521,11 @@ void TTrain::set_paired_open_motor_connectors_button(bool const State) // TODO: rework it into part of standard command propagation system if (controlled->Couplers[VehicleEnd::front].Connected != nullptr && true == controlled->Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::permanent)) { - controlled->Couplers[VehicleEnd::front].Connected->StLinSwitchOff = State; + controlled->Couplers[VehicleEnd::front].Connected->lineContactors.forcedOpen = State; } if (controlled->Couplers[VehicleEnd::rear].Connected != nullptr && true == controlled->Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::permanent)) { - controlled->Couplers[VehicleEnd::rear].Connected->StLinSwitchOff = State; + controlled->Couplers[VehicleEnd::rear].Connected->lineContactors.forcedOpen = State; } } } diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index 0594899ee..32a0fab22 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -140,12 +140,12 @@ bool TTrain::Update(double const Deltatime) void TTrain::updateLineBreakerState(double const Deltatime) { // line breaker: - if (m_linebreakerstate == linebreaker::state::open && true == controlled->Mains) + if (m_linebreakerstate == linebreaker::state::open && true == controlled->lineBreaker.closed) { // crude way to sync state of the linebreaker with ai-issued commands m_linebreakerstate = linebreaker::state::closed; } - if (m_linebreakerstate == linebreaker::state::closed && false == (controlled->Mains || controlled->diesel.startupRequested)) + if (m_linebreakerstate == linebreaker::state::closed && false == (controlled->lineBreaker.closed || controlled->diesel.startupRequested)) { // crude way to catch cases where the main was knocked out // because the state of the line breaker isn't changed to match, we need to do it here manually @@ -153,7 +153,7 @@ void TTrain::updateLineBreakerState(double const Deltatime) } if (is_hold_coil_lever(ggMainOffButton) && hold_coil_lever::cuts_off(ggMainOffButton.GetDesiredValue())) { - if (true == controlled->Mains) + if (true == controlled->lineBreaker.closed) { // the line breaker was closed with the hold coil lever off, by the AI or through the control cable: // put the lever back on to match, like the line breaker state above @@ -482,11 +482,11 @@ void TTrain::updateUnitStates() fEIMParams[1 + in][8] = static_cast(p->physics->Itot); // p->physics->inductionMotor.state.lineCurrent; fEIMParams[1 + in][9] = static_cast(p->physics->EngineVoltage); fEIMParams[0][6] += fEIMParams[1 + in][8]; - bMains[in] = p->physics->Mains; + bMains[in] = p->physics->lineBreaker.closed; fCntVol[in] = static_cast(p->physics->BatteryVoltage); bFuse[in] = p->physics->FuseFlag; bBatt[in] = p->physics->Battery; - bConv[in] = p->physics->ConverterFlag; + bConv[in] = p->physics->converter.running; bHeat[in] = p->physics->Heating; // bComp[in][2] = (p->physics->CompressorAllow || (p->physics->CompressorStart == start_t::automatic)); // bComp[in][3] = (p->physics->CompressorFlag); @@ -505,11 +505,11 @@ void TTrain::updateUnitStates() fDieselParams[1 + in][7] = p->physics->OilPump.pressure; fDieselParams[1 + in][8] = p->physics->diesel.heat.Ts; fDieselParams[1 + in][9] = static_cast(p->physics->retarder.fill); - bMains[in] = p->physics->Mains; + bMains[in] = p->physics->lineBreaker.closed; fCntVol[in] = static_cast(p->physics->BatteryVoltage); bFuse[in] = p->physics->FuseFlag; bBatt[in] = p->physics->Battery; - bConv[in] = p->physics->ConverterFlag; + bConv[in] = p->physics->converter.running; bHeat[in] = p->physics->Heating; in++; iPowerNo = in; @@ -604,7 +604,7 @@ void TTrain::updateConverterOverload(double const Deltatime) //------------------ // hunter-261211: nadmiarowy przetwornicy i ogrzewania // Ra 15-01: to musi stąd wylecieć - zależności nie mogą być w kabinie - if (controlled->ConverterFlag == true) + if (controlled->converter.running == true) { fConverterTimer += static_cast(Deltatime); if (controlled->air.compressor.running == true && controlled->air.compressor.supply == physics::CompressorSupply::converterManual && (controlled->EngineType == TEngineType::ElectricSeriesMotor || controlled->TrainType == train_type::emu) && @@ -613,7 +613,7 @@ void TTrain::updateConverterOverload(double const Deltatime) { // hunter-091012: poprawka (zmiana warunku z CompressorPower /rozne od 0/ na /rowne 1/) if (fConverterTimer < fConverterPrzekaznik) { - controlled->ConvOvldFlag = true; + controlled->converter.overloaded = true; if (controlled->TrainType != train_type::emu) controlled->MainSwitch(false, controlled->TrainType == train_type::emu ? range_t::unit : range_t::local); } @@ -742,7 +742,7 @@ void TTrain::updateEngineGauges() fEngine[3] = static_cast(controlled->ShowEngineRotation(3)); if (ggMainGearStatus.SubModel) { - if (controlled->Mains) + if (controlled->lineBreaker.closed) ggMainGearStatus.UpdateValue(static_cast(1.1 - std::abs(controlled->diesel.automaticGearShift))); else ggMainGearStatus.UpdateValue(0.0); @@ -750,7 +750,7 @@ void TTrain::updateEngineGauges() } if (ggIgnitionKey.SubModel && ggIgnitionKey.GetDesiredValue() == 0.0) { - ggIgnitionKey.UpdateValue(controlled->Mains || controlled->diesel.startupRequested || fMainRelayTimer > 0.f || + ggIgnitionKey.UpdateValue(controlled->lineBreaker.closed || controlled->diesel.startupRequested || fMainRelayTimer > 0.f || (ggMainButton.SubModel != nullptr && ggMainButton.GetDesiredValue() > 0.95) || (ggMainOnButton.SubModel != nullptr && ggMainOnButton.GetDesiredValue() > 0.95)); } @@ -826,20 +826,20 @@ void TTrain::updateCircuitLamps(double const Deltatime) btLampkaSHP.Turn(occupied->SecuritySystem.is_cabsignal_blinking()); btLampkaCzuwakaSHP.Turn(btLampkaSHP.GetValue() || btLampkaCzuwaka.GetValue()); - btLampkaWylSzybki.Turn(m_linebreakerstate == linebreaker::state::closing || controlled->Mains); - btLampkaWylSzybkiOff.Turn(m_linebreakerstate != linebreaker::state::closing && !controlled->Mains); - btLampkaMainBreakerReady.Turn(controlled->MainsInitTimeCountdown <= 0.0 && m_linebreakerstate != linebreaker::state::closing && !controlled->Mains); - btLampkaMainBreakerBlinkingIfReady.Turn(m_linebreakerstate == linebreaker::state::closing || controlled->Mains || controlled->MainsInitTimeCountdown < 0.0 && simulation::Time.data().wMilliseconds > 500); + btLampkaWylSzybki.Turn(m_linebreakerstate == linebreaker::state::closing || controlled->lineBreaker.closed); + btLampkaWylSzybkiOff.Turn(m_linebreakerstate != linebreaker::state::closing && !controlled->lineBreaker.closed); + btLampkaMainBreakerReady.Turn(controlled->lineBreaker.initCountdown <= 0.0 && m_linebreakerstate != linebreaker::state::closing && !controlled->lineBreaker.closed); + btLampkaMainBreakerBlinkingIfReady.Turn(m_linebreakerstate == linebreaker::state::closing || controlled->lineBreaker.closed || controlled->lineBreaker.initCountdown < 0.0 && simulation::Time.data().wMilliseconds > 500); btLampkaPrzetw.Turn(occupied->Power110vIsAvailable); btLampkaPrzetwOff.Turn(!occupied->Power110vIsAvailable); - btLampkaPrzetwAOff.Turn(!controlled->ConverterFlag); - btLampkaNadmPrzetw.Turn(Dynamic()->Mechanik ? Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : controlled->ConvOvldFlag); + btLampkaPrzetwAOff.Turn(!controlled->converter.running); + btLampkaNadmPrzetw.Turn(Dynamic()->Mechanik ? Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : controlled->converter.overloaded); - btLampkaOpory.Turn(controlled->StLinFlag && controlled->ResistorsFlagCheck()); + btLampkaOpory.Turn(controlled->lineContactors.closed && controlled->ResistorsFlagCheck()); btLampkaBezoporowa.Turn(controlled->ResistorsFlagCheck() || controlled->MainCtrlActualPos == 0); // do EU04 btLampkaStyczn.Turn(controlled->LineContactorsLampLit()); // mozna prowadzic rozruch - btLampkaPrzekRozn.Turn(!controlled->GroundRelay && controlled->MainCircuitLampsEnabled()); // relay is off and needs a reset + btLampkaPrzekRozn.Turn(!controlled->protection.ground && controlled->MainCircuitLampsEnabled()); // relay is off and needs a reset btLampkaNadmSil.Turn(controlled->FuseFlagCheck() && controlled->MainCircuitLampsEnabled()); // relay is off and needs a reset btLampkaUkrotnienie.Turn(controlled->Couplers[controlled->CabOccupied == 1 ? VehicleEnd::rear : VehicleEnd::front].CouplingFlag.HasAll(Coupling::control)); btLampkaHamPosp.Turn(TestFlag(occupied->brakes.distributor->GetBrakeStatus(), 1)); // lampka drugiego stopnia hamowania @@ -1103,8 +1103,8 @@ void TTrain::updateSecondUnitLamps(bool const lowvoltagepower) auto const *physics{tmp->physics}; - btLampkaWylSzybkiB.Turn(physics->Mains); - btLampkaWylSzybkiBOff.Turn(false == physics->Mains + btLampkaWylSzybkiB.Turn(physics->lineBreaker.closed); + btLampkaWylSzybkiBOff.Turn(false == physics->lineBreaker.closed /*&& ( physics->MainsInitTimeCountdown <= 0.0 )*/ /*&& ( fHVoltage != 0.0 )*/); @@ -1142,13 +1142,13 @@ void TTrain::updateSecondUnitLamps(bool const lowvoltagepower) { btLampkaHamowanie2zes.Turn(false); } - btLampkaNadmPrzetwB.Turn(physics->ConvOvldFlag); // nadmiarowy przetwornicy? - btLampkaPrzetwB.Turn(physics->ConverterFlag); // zalaczenie przetwornicy - btLampkaPrzetwBOff.Turn(false == physics->ConverterFlag); - btLampkaHVoltageB.Turn(physics->NoVoltRelay && physics->OvervoltageRelay); + btLampkaNadmPrzetwB.Turn(physics->converter.overloaded); // nadmiarowy przetwornicy? + btLampkaPrzetwB.Turn(physics->converter.running); // zalaczenie przetwornicy + btLampkaPrzetwBOff.Turn(false == physics->converter.running); + btLampkaHVoltageB.Turn(physics->protection.noVoltage && physics->protection.overvoltage); btLampkaMalfunctionB.Turn(physics->diesel.heat.PA); // motor fuse indicator turns on if the fuse was blown in any unit under control - if (physics->Mains) + if (physics->lineBreaker.closed) { btLampkaNadmSil.Turn(btLampkaNadmSil.GetValue() || physics->FuseFlagCheck()); } @@ -1374,7 +1374,7 @@ void TTrain::updateHeatingAndInstrumentLights() { //--------- // hunter-080812: poprawka na ogrzewanie w elektrykach - usuniete uzaleznienie od przetwornicy - if (controlled->Heating == true && controlled->ConvOvldFlag == false) + if (controlled->Heating == true && controlled->converter.overloaded == false) btLampkaOgrzewanieSkladu.Turn(true); else btLampkaOgrzewanieSkladu.Turn(false); @@ -1383,7 +1383,7 @@ void TTrain::updateHeatingAndInstrumentLights() // lights auto const lightpower{(InstrumentLightType == 0 ? occupied->Power24vIsAvailable || occupied->Power110vIsAvailable : - InstrumentLightType == 1 ? controlled->Mains : + InstrumentLightType == 1 ? controlled->lineBreaker.closed : InstrumentLightType == 2 ? occupied->Power110vIsAvailable : InstrumentLightType == 3 ? occupied->Power24vIsAvailable || occupied->Power110vIsAvailable : InstrumentLightType == 4 ? occupied->Power24vIsAvailable || occupied->Power110vIsAvailable : @@ -1478,14 +1478,14 @@ void TTrain::updateAuxiliaryButtons(bool const lowvoltagepower) //------------ // the converter switches follow the vehicle when something else flips them (the AI driver, the other cab, // the pressure switch of an EMU), not only when the cab is entered (set_cab_controls()) - if (ggConverterButton.SubModel != nullptr && occupied->ConvSwitchType != "impulse" && occupied->ConverterStart == start_t::manual) + if (ggConverterButton.SubModel != nullptr && occupied->converter.switchType != "impulse" && occupied->converter.start == start_t::manual) { - ggConverterButton.UpdateValue(occupied->ConverterAllow ? 1.f : 0.f, dsbSwitch); + ggConverterButton.UpdateValue(occupied->converter.allow ? 1.f : 0.f, dsbSwitch); } ggConverterButton.Update(); if (ggConverterLocalButton.SubModel != nullptr) { - ggConverterLocalButton.UpdateValue(occupied->ConverterAllowLocal ? 1.f : 0.f, dsbSwitch); + ggConverterLocalButton.UpdateValue(occupied->converter.allowLocal ? 1.f : 0.f, dsbSwitch); } ggConverterLocalButton.Update(); ggConverterOffButton.Update(); diff --git a/vehicle/dynamic/sounds.cpp b/vehicle/dynamic/sounds.cpp index d83e3afca..144d8e776 100644 --- a/vehicle/dynamic/sounds.cpp +++ b/vehicle/dynamic/sounds.cpp @@ -115,7 +115,7 @@ void TDynamicObject::renderAuxiliarySounds() { auto frequency{ 1.0 }; // NBMX dzwiek przetwornicy - if( physics->ConverterFlag ) { + if( physics->converter.running ) { if( physics->EngineType == TEngineType::ElectricSeriesMotor ) { auto const voltage { std::max( physics->GetTrainsetHighVoltage(), physics->pantographCircuit.supplyVoltage ) }; if( voltage > 0.0 ) { @@ -1096,9 +1096,9 @@ TDynamicObject::powertrain_sounds::renderIgnitionSounds( physics::Vehicle const // engine sounds // ignition - if( engine_state_last != Vehicle.Mains ) { + if( engine_state_last != Vehicle.lineBreaker.closed ) { - if( true == Vehicle.Mains ) { + if( true == Vehicle.lineBreaker.closed ) { // TODO: separate engine and main circuit // engine activation engine_shutdown.stop(); @@ -1124,7 +1124,7 @@ TDynamicObject::powertrain_sounds::renderIgnitionSounds( physics::Vehicle const .gain( linebreaker_open.m_amplitudeoffset + linebreaker_open.m_amplitudefactor * 1.f ) .play(); } - engine_state_last = Vehicle.Mains; + engine_state_last = Vehicle.lineBreaker.closed; } } @@ -1136,7 +1136,7 @@ TDynamicObject::powertrain_sounds::renderEngineSounds( physics::Vehicle const &V double volume { 0.0 }; // main engine sound - if( true == Vehicle.Mains ) { + if( true == Vehicle.lineBreaker.closed ) { if( std::abs(Vehicle.enrot) > 0.01 // McZapkie-280503: zeby dla dumb dzialal silnik na jalowych obrotach @@ -1238,7 +1238,7 @@ TDynamicObject::powertrain_sounds::renderEngineSounds( physics::Vehicle const &V } } - if (Vehicle.Mains) { + if (Vehicle.lineBreaker.closed) { float power = std::clamp(Vehicle.inductionMotor.forceShare, 0.0, 1.0); fake_engine diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index 2ec42d52c..6e929c902 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -274,7 +274,7 @@ void TDynamicObject::updateTractionVoltage( double const dt1 ) // Ra 2014-07: doraźna blokada logowania zimnych lokomotyw - zrobić to trzeba inaczej if( physics->pantographs[VehicleEnd::front].is_active || physics->pantographs[VehicleEnd::rear].is_active ) { - if( physics->Mains // Ra 15-01: logować tylko, jeśli WS załączony + if( physics->lineBreaker.closed // Ra 15-01: logować tylko, jeśli WS załączony && physics->GetTrainsetHighVoltage() < 0.1f // yB 16-03: i nie jest to asynchron zasilany z daleka && false == physics->GensetSelected() ) { // nor a dual-mode vehicle running on its genset // Ra 15-01: bezwzględne współrzędne pantografu nie są dostępne więc lepiej się tego nie zaloguje @@ -420,7 +420,7 @@ void TDynamicObject::sumConsistBrakeForces( InductionBrakeState &state ) Nmax / (p->physics->NAxles * p->physics->brakes.blocksPerAxle), p->physics->brakes.blending.referenceSpeed) * 1000; // sila hamowania pn - state.FmaxED += p->physics->Mains && p->physics->DirActive != 0 && p->physics->inductionMotor.inverterRatio == 1.0 && + state.FmaxED += p->physics->lineBreaker.closed && p->physics->DirActive != 0 && p->physics->inductionMotor.inverterRatio == 1.0 && p->physics->inductionMotor.braking.maxForce * p->physics->NPoweredAxles > 0 ? p->physics->inductionMotor.braking.maxForce * 1000 : 0; // chwilowy max ED -> do rozdzialu sil @@ -734,7 +734,7 @@ void TDynamicObject::recordMedState( InductionBrakeState const &state, double co void TDynamicObject::switchOffMainsWithoutBattery() { // fragment "z EXE Kursa" - if( physics->Mains ) { // nie wchodzić w funkcję bez potrzeby + if( physics->lineBreaker.closed ) { // nie wchodzić w funkcję bez potrzeby if( false == (physics->Power24vIsAvailable || physics->Power110vIsAvailable) /* // NOTE: disabled on account of multi-unit setups, where the unmanned unit wouldn't be affected @@ -1512,7 +1512,7 @@ void TDynamicObject::Damage(char flag) if (flag & 2) //usterka sterowania { - physics->StLinFlag = false; + physics->lineContactors.closed = false; if (physics->InitialCtrlDelay<100000000) physics->InitialCtrlDelay += 100000001; } @@ -1524,8 +1524,8 @@ void TDynamicObject::Damage(char flag) if (flag & 4) //blokada przetwornicy { - if( physics->ConverterStart != start_t::disabled ) { - physics->ConvOvldFlag = true; + if( physics->converter.start != start_t::disabled ) { + physics->converter.overloaded = true; } } else diff --git a/vehicle/enginestart.cpp b/vehicle/enginestart.cpp index c221119f4..ebac38066 100644 --- a/vehicle/enginestart.cpp +++ b/vehicle/enginestart.cpp @@ -103,7 +103,7 @@ bool remote_switch::open(physics::Vehicle &Engine) { } bool remote_switch::is_running(physics::Vehicle const &Engine) { - return Engine.Mains || Engine.diesel.startupRequested; + return Engine.lineBreaker.closed || Engine.diesel.startupRequested; } } // namespace engine_start diff --git a/widgets/vehicleparams.cpp b/widgets/vehicleparams.cpp index edc3568b7..321cee7de 100644 --- a/widgets/vehicleparams.cpp +++ b/widgets/vehicleparams.cpp @@ -70,9 +70,9 @@ void ui::vehicleparams_panel::draw_mini(const physics::Vehicle &physics) if (physics.Battery) draw_infobutton(STR_C("bat."), ImVec2(120, 55)); - if (physics.Mains) + if (physics.lineBreaker.closed) draw_infobutton(STR_C("main.")); - if (physics.ConverterFlag) + if (physics.converter.running) draw_infobutton(STR_C("conv.")); if (physics.air.compressor.running) draw_infobutton(STR_C("comp.")); @@ -148,12 +148,12 @@ void ui::vehicleparams_panel::render_contents() std::snprintf(buffer.data(), buffer.size(), STR_C("Devices: %c%c%c%c%c%c%c%c%c%c%c%c%c%c%s%s\nPower transfers: %.0f@%.0f%s%s%s%.0f@%.0f"), // devices - (physics.Battery ? 'B' : '.'), (physics.Mains ? 'M' : '.'), (physics.FuseFlag ? '!' : '.'), (physics.pantographs[VehicleEnd::rear].is_active ? (physics.pantographCircuit.rearVoltage > 0.0 ? 'O' : 'o') : '.'), + (physics.Battery ? 'B' : '.'), (physics.lineBreaker.closed ? 'M' : '.'), (physics.FuseFlag ? '!' : '.'), (physics.pantographs[VehicleEnd::rear].is_active ? (physics.pantographCircuit.rearVoltage > 0.0 ? 'O' : 'o') : '.'), (physics.pantographs[VehicleEnd::front].is_active ? (physics.pantographCircuit.frontVoltage > 0.0 ? 'P' : 'p') : '.'), (physics.pantographAir.pressureLockActive ? '!' : (physics.pantographAir.pressureSwitchActive ? '*' : '.')), (physics.WaterPump.is_active ? 'W' : (false == physics.WaterPump.breaker ? '-' : (physics.WaterPump.is_enabled ? 'w' : '.'))), (true == physics.WaterHeater.is_damaged ? '!' : (physics.WaterHeater.is_active ? 'H' : (false == physics.WaterHeater.breaker ? '-' : (physics.WaterHeater.is_enabled ? 'h' : '.')))), (physics.FuelPump.is_active ? 'F' : (physics.FuelPump.is_enabled ? 'f' : '.')), (physics.OilPump.is_active ? 'O' : (physics.OilPump.is_enabled ? 'o' : '.')), - (false == physics.ConverterAllowLocal ? '-' : (physics.ConverterAllow ? (physics.ConverterFlag ? 'X' : 'x') : '.')), (physics.ConvOvldFlag ? '!' : '.'), + (false == physics.converter.allowLocal ? '-' : (physics.converter.allow ? (physics.converter.running ? 'X' : 'x') : '.')), (physics.converter.overloaded ? '!' : '.'), (physics.air.compressor.running ? 'C' : (false == physics.air.compressor.allowLocal ? '-' : ((physics.air.compressor.allow || physics.air.compressor.start == start_t::automatic) ? 'c' : '.'))), (physics.air.compressor.governorLock ? '!' : '.'), "", std::string(isdieselenginepowered ? STR(" oil pressure: ") + to_string(physics.OilPump.pressure, 2) : "").c_str(), // power transfers From 89258eb72cefff55f49f1262103f82a0ea5a26e5 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 03:15:56 +0100 Subject: [PATCH 033/123] refactor(physics): the low voltage, the train heating and the electrodynamic brake as components The rest of the electrics of physics::Vehicle beside the traction motors becomes components, with English names: lowVoltage (LowVoltageSupply, Battery batteryOn, BatteryVoltage, physics/components/lowvoltage.h) NominalBatteryVoltage, BatteryStart, Power110vIsAvailable / Power24vIsAvailable / Power24vVoltage power110vAvailable / power24vAvailable / power24vVoltage, the battery button of the cab: batteryButtonFired, batteryButtonImpulse, batteryButtonHeld, batteryButtonHoldTime trainHeating (TrainHeating) Heating on, HeatingAllow allow, HeatingSwitchImpulse switchImpulse, HeatingPower power, EngineHeatingRPM engineRpm brakes.electrodynamic the DynamicBrake* fields: type, ammeters, (ElectrodynamicBrake, controllerPositions, controllerPosition, physics/components/braking.h) resistance(1, 2), on, emuWorking; SplitEDPneumaticBrake splitFromPneumatic; the fans of the braking resistor (BRVentilators, BRVto, BRVtimer, Imaxrpc): resistorFansRunning, resistorFansSustain, resistorFansTimer, resistorPassiveMaxCurrent The diesel-electric dynamic brake (DEDynamicBrake) and the currents of the traction circuit (Im, Itot, EngineVoltage ...) stay for the traction stage. No string literal changed (checked over all the changed files). No change in behaviour: 1149/1149 tests, golden traces exact against staging 62f7a29b. --- application/driverhints.cpp | 10 +- application/driveruipanels.cpp | 6 +- physics/components/body.cpp | 24 ++-- physics/components/braking.h | 22 ++++ physics/components/cab.cpp | 4 +- physics/components/collisions.cpp | 2 +- physics/components/commands.cpp | 16 +-- physics/components/controllers.cpp | 16 +-- physics/components/diesel.cpp | 24 ++-- physics/components/doors.cpp | 6 +- physics/components/drive.cpp | 8 +- physics/components/electrics.cpp | 92 +++++++-------- physics/components/fizsections.cpp | 44 +++---- physics/components/lowvoltage.h | 46 ++++++++ physics/components/pneumatics.cpp | 26 ++--- physics/components/securitysystem.cpp | 4 +- physics/components/setup.cpp | 8 +- physics/components/traction.cpp | 110 +++++++++--------- physics/vehicle.h | 39 +------ rendering/lightarray.cpp | 4 +- simulation/blackboxrecorder.cpp | 4 +- tests/unit/golden.cpp | 6 +- tests/unit/invariants.cpp | 12 +- tests/unit/test_auxiliaries.cpp | 22 ++-- tests/unit/test_cab.cpp | 8 +- tests/unit/test_commands.cpp | 6 +- tests/unit/test_compartment_lights.cpp | 20 ++-- tests/unit/test_compartment_lights_switch.cpp | 2 +- tests/unit/test_compressor.cpp | 10 +- tests/unit/test_controls.cpp | 16 +-- tests/unit/test_drivingaid.cpp | 6 +- tests/unit/test_dynamic_brake_diesel.cpp | 22 ++-- tests/unit/test_engine_shutdown.cpp | 2 +- tests/unit/test_genset.cpp | 2 +- tests/unit/test_horn.cpp | 10 +- tests/unit/test_line_contactors_interlock.cpp | 12 +- tests/unit/test_mains_before_pantographs.cpp | 16 +-- tests/unit/test_oil_pump.cpp | 8 +- tests/unit/test_pullee.cpp | 20 ++-- tests/unit/test_radio.cpp | 14 +-- tests/unit/test_switches.cpp | 4 +- tests/unit/test_traction.cpp | 6 +- vehicle/ai/consist.cpp | 10 +- vehicle/ai/controls.cpp | 2 +- vehicle/ai/engine.cpp | 2 +- vehicle/ai/orders.cpp | 2 +- vehicle/cab/auxiliarycommands.cpp | 2 +- vehicle/cab/brakecommands.cpp | 8 +- vehicle/cab/cabcommands.cpp | 30 ++--- vehicle/cab/controllercommands.cpp | 34 +++--- vehicle/cab/equipmentcommands.cpp | 10 +- vehicle/cab/pantographcommands.cpp | 2 +- vehicle/cab/setup.cpp | 8 +- vehicle/cab/sounds.cpp | 2 +- vehicle/cab/train.cpp | 12 +- vehicle/cab/update.cpp | 64 +++++----- vehicle/drivingaid.cpp | 6 +- vehicle/dynamic/destinations.cpp | 2 +- vehicle/dynamic/sounds.cpp | 12 +- vehicle/dynamic/update.cpp | 8 +- vehicle/dynamic/visual.cpp | 4 +- widgets/vehicleparams.cpp | 4 +- 62 files changed, 501 insertions(+), 462 deletions(-) create mode 100644 physics/components/lowvoltage.h diff --git a/application/driverhints.cpp b/application/driverhints.cpp index 661f4d33d..d59431dc6 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -89,7 +89,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return occupied->BatteryStart != start_t::manual || occupied->Power24vIsAvailable == true; } ); + return occupied->lowVoltage.batteryStart != start_t::manual || occupied->lowVoltage.power24vAvailable == true; } ); break; } case driver_hint::batteryoff: { @@ -100,12 +100,12 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return occupied->BatteryStart != start_t::manual || occupied->Power24vIsAvailable == false; } ); + return occupied->lowVoltage.batteryStart != start_t::manual || occupied->lowVoltage.power24vAvailable == false; } ); break; } // battery case driver_hint::cabactivation: { - if (AIControllFlag && occupied->Power24vIsAvailable) { + if (AIControllFlag && occupied->lowVoltage.power24vAvailable) { occupied->CabActivisation(); CheckVehicles(); } @@ -1218,7 +1218,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return occupied->HeatingAllow == true; } ); + return occupied->trainHeating.allow == true; } ); break; } case driver_hint::consistheatingoff: { @@ -1229,7 +1229,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return occupied->HeatingAllow == false; } ); + return occupied->trainHeating.allow == false; } ); break; } diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 8ec1a9997..15ff54b1a 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -816,7 +816,7 @@ debug_panel::update_section_vehicle( std::vector &Output ) { m_buffer.data(), m_buffer.size(), STR_C("Devices: %c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%s%s\nPower transfers: %.0f@%.0f%s[%.0f]%s%.0f@%.0f :: %.0f@%.0f%s[%.0f]%s%.0f@%.0f"), // devices - physics.Battery ? 'B' : '.', + physics.lowVoltage.batteryOn ? 'B' : '.', physics.pantographAir.valve.is_active ? '+' : '.', physics.pantographs[VehicleEnd::rear].valve.is_active ? 'O' : physics.pantographs[VehicleEnd::rear].valve.is_enabled ? 'o' : @@ -858,8 +858,8 @@ debug_panel::update_section_vehicle( std::vector &Output ) { physics.protection.pressureSwitch ? '!' : physics.lineContactors.closed ? '+' : '.', - physics.Heating ? 'H' : - physics.HeatingAllow ? 'h' : + physics.trainHeating.on ? 'H' : + physics.trainHeating.allow ? 'h' : '.', physics.brakes.distributor->Releaser() ? '^' : '.', std::string( m_input.mechanik ? STR(" R") + ( physics.Radio && physics.RadioFuse ? std::to_string( m_input.mechanik->iRadioChannel ) : "-" ) : "" ).c_str(), diff --git a/physics/components/body.cpp b/physics/components/body.cpp index 9e84a8da9..30d19d59c 100644 --- a/physics/components/body.cpp +++ b/physics/components/body.cpp @@ -440,16 +440,16 @@ void physics::Vehicle::compute_movement_(double const Deltatime) // Prad oddawany na rezystor // Wlacz wentylator jesli prad rekuperacji przekroczy maksymalny dla pasywnego chlodzenia rezystora - if (double Irh = abs(inductionMotor.state.electricalPower) - abs(inductionMotor.state.lineCurrent); Irh > Imaxrpc && inductionMotor.state.lineCurrent < 0) + if (double Irh = abs(inductionMotor.state.electricalPower) - abs(inductionMotor.state.lineCurrent); Irh > brakes.electrodynamic.resistorPassiveMaxCurrent && inductionMotor.state.lineCurrent < 0) { - BRVtimer = 0; - BRVentilators = true; + brakes.electrodynamic.resistorFansTimer = 0; + brakes.electrodynamic.resistorFansRunning = true; } else { - BRVtimer += Deltatime; - if (BRVtimer > BRVto) - BRVentilators = false; + brakes.electrodynamic.resistorFansTimer += Deltatime; + if (brakes.electrodynamic.resistorFansTimer > brakes.electrodynamic.resistorFansSustain) + brakes.electrodynamic.resistorFansRunning = false; } // the master controller set directly, not through IncMainCtrl()/DecMainCtrl() (AI, consist): the locked shunt follows it as well @@ -503,11 +503,11 @@ void physics::Vehicle::compute_movement_(double const Deltatime) if ((brakes.emuDynamic.checkedCoupler & 1) != 0 && Couplers[VehicleEnd::front].CouplingFlag.HasAny(Coupling::control)) { - DynamicBrakeEMUStatus &= Couplers[VehicleEnd::front].Connected->DynamicBrakeEMUStatus; + brakes.electrodynamic.emuWorking &= Couplers[VehicleEnd::front].Connected->brakes.electrodynamic.emuWorking; } if ((brakes.emuDynamic.checkedCoupler & 2) != 0 && Couplers[VehicleEnd::rear].CouplingFlag.HasAny(Coupling::control)) { - DynamicBrakeEMUStatus &= Couplers[VehicleEnd::rear].Connected->DynamicBrakeEMUStatus; + brakes.electrodynamic.emuWorking &= Couplers[VehicleEnd::rear].Connected->brakes.electrodynamic.emuWorking; } if (brakes.antiSlipTimer > 0.8 && brakes.antiSlipType != 128) @@ -525,9 +525,9 @@ void physics::Vehicle::compute_movement_(double const Deltatime) PowerCouplersCheck(Deltatime, Coupling::power110v); PowerCouplersCheck(Deltatime, Coupling::power24v); - Power24vVoltage = std::max(PowerCircuits[0].first, GetTrainsetVoltage(Coupling::power24v)); - Power24vIsAvailable = Power24vVoltage > 0; - Power110vIsAvailable = PowerCircuits[1].first > 0 || GetTrainsetVoltage(Coupling::power110v) > 0; + lowVoltage.power24vVoltage = std::max(PowerCircuits[0].first, GetTrainsetVoltage(Coupling::power24v)); + lowVoltage.power24vAvailable = lowVoltage.power24vVoltage > 0; + lowVoltage.power110vAvailable = PowerCircuits[1].first > 0 || GetTrainsetVoltage(Coupling::power110v) > 0; } // ************************************************************************************************* @@ -963,7 +963,7 @@ double physics::Vehicle::BrakeForceR(double ratio, double velocity) const else { press = brakes.maxCylinderPressure[3]; - if (DynamicBrakeType == dbrake_automatic) + if (brakes.electrodynamic.type == dbrake_automatic) ratio = ratio + (1.5 - ratio) * std::min(1.0, Vel * 0.02); if (brakes.delaySetting & bdelay_R && brakes.method % 128 != bp_Cosid && brakes.method % 128 != bp_D1 && brakes.method % 128 != bp_D2 && Power < 1) ratio *= brakes.distributor->GetRapidRatio(velocity); diff --git a/physics/components/braking.h b/physics/components/braking.h index 43865134c..817403f9c 100644 --- a/physics/components/braking.h +++ b/physics/components/braking.h @@ -94,6 +94,25 @@ struct SpringBrake }; // the braking of a vehicle beside its air brake valves +// the electrodynamic brake of the traction motors and its resistors +struct ElectrodynamicBrake +{ + int type = 0; // dbrake_* + int ammeters = 2; // the ammeters it shows on + bool splitFromPneumatic = false; // its controller is apart from the one of the independent air brake + int controllerPositions = 10; // DBPN: the positions of its controller + double controllerPosition = 0.0; // the position of its controller, 0..1, with splitFromPneumatic only + double resistance = 5.8; // of the braking resistors + double resistance1 = 5.8; // of the first mode + double resistance2 = 5.8; // of the second mode + bool on = false; // braking + bool emuWorking = true; // it works, in a multiple unit + bool resistorFansRunning = false; // the fans of the braking resistor + int resistorFansSustain = 0; // how long the fans still cool the resistor after it stops [s] + double resistorFansTimer = 0; // the timer of that + int resistorPassiveMaxCurrent = 0; // the most current of the resistor cooled passively +}; + // the settings of the driver's brake valve (the Handle_* keys of the .fiz) struct DriverValveSettings { @@ -209,12 +228,15 @@ struct Braking bool alarmChain = false; // the manual emergency brake int delaySetting = 0; // the delay set (bdelay_*) int availableDelays = 0; // the delays it can be set to + // the AI wagon inspector cut the brake out (b_dmg) and puts it back when the train no longer needs it cut out + // (brake_setting::apply). Anyone else cutting it out or putting it back takes it over bool cutOutByInspector = false; int operatingMode = 0; // the mode set (bom_*: PS/PN/EP/MED 1/2/4/8) int availableOperatingModes = 0; double unitForce = 0.0; // the braking force of one braked element double antiSlipTimer = 0.0; // to switch the anti-slip brake off + ElectrodynamicBrake electrodynamic; BrakeBlending blending; EmuDynamicBrake emuDynamic; HoldingBrake holding; diff --git a/physics/components/cab.cpp b/physics/components/cab.cpp index 09716282c..cf9e52321 100644 --- a/physics/components/cab.cpp +++ b/physics/components/cab.cpp @@ -74,7 +74,7 @@ int physics::Vehicle::SoundingHorns(int const Signal) const auto const supplied{[this](horn_supply const Supply) { if (Supply == horn_supply::electric) { - return Power24vIsAvailable || Power110vIsAvailable; + return lowVoltage.power24vAvailable || lowVoltage.power110vAvailable; } if (air.mainReservoirVolume > 0.0) { @@ -204,7 +204,7 @@ bool physics::Vehicle::PulleeModeSwitch(bool const State) DecManualBrakeLevel(ManualBrakePosNo); brakes.spring.activate = false; SecuritySystem.set_enabled(false); - Battery = false; + lowVoltage.batteryOn = false; } return true; } diff --git a/physics/components/collisions.cpp b/physics/components/collisions.cpp index 55e93944b..347100559 100644 --- a/physics/components/collisions.cpp +++ b/physics/components/collisions.cpp @@ -238,7 +238,7 @@ collision::vehicle_kind physics::Vehicle::collision_kind() const auto const unit{is_multiple_unit()}; auto const passengers{std::any_of(LoadAttributes.begin(), LoadAttributes.end(), [](auto const &Load) { return ToLower(Load.name).starts_with("passenger"); })}; // a coach heats its compartments; the crash zone is a matter of each end (crush_of()) - return collision::kind_of(powered, unit || passengers || (false == powered && HeatingPower > 0.0), false); + return collision::kind_of(powered, unit || passengers || (false == powered && trainHeating.power > 0.0), false); } collision::crush_curve physics::Vehicle::crush_curve_at(VehicleEnd const End) const diff --git a/physics/components/commands.cpp b/physics/components/commands.cpp index 42c0885da..a5d6f6a2d 100644 --- a/physics/components/commands.cpp +++ b/physics/components/commands.cpp @@ -273,17 +273,17 @@ bool physics::Vehicle::RunBrakeCommand(VehicleCommand const Command, double CVal if (Command == VehicleCommand::brake) // youBy - jak sie EP hamuje, to trza sygnal wyslac... { if (CValue1 < 0.001) - DynamicBrakeEMUStatus = true; + brakes.electrodynamic.emuWorking = true; double temp1 = CValue1; - if (brakes.emuDynamic.epMaxSpeed > 0.001 && Vel > brakes.emuDynamic.epMaxSpeed && DynamicBrakeEMUStatus) + if (brakes.emuDynamic.epMaxSpeed > 0.001 && Vel > brakes.emuDynamic.epMaxSpeed && brakes.electrodynamic.emuWorking) temp1 = 0; - if (brakes.emuDynamic.epMinCurrent > 0.001 && abs(Im) > brakes.emuDynamic.epMinCurrent && DynamicBrakeEMUStatus) + if (brakes.emuDynamic.epMinCurrent > 0.001 && abs(Im) > brakes.emuDynamic.epMinCurrent && brakes.electrodynamic.emuWorking) temp1 = 0; brakes.distributor->SetEPS(temp1); TUHEX_StageActual = static_cast(CValue1); TUHEX_Active = TUHEX_StageActual > 0; if (CValue1 < 0.001) - DynamicBrakeEMUStatus = true; + brakes.electrodynamic.emuWorking = true; // fBrakeCtrlPos:=BrakeCtrlPos; //to powinnno być w jednym miejscu, aktualnie w C++!!! brakes.actualPressure = brakes.pressureTable[brakes.handlePosition]; OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); @@ -325,7 +325,7 @@ bool physics::Vehicle::RunBrakeEquipmentCommand(VehicleCommand const Command, do } else if (Command == VehicleCommand::springBrakeActivate) { - if (Power24vIsAvailable || Power110vIsAvailable) + if (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable) { brakes.spring.activate = CValue1 > 0; OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); @@ -373,9 +373,9 @@ bool physics::Vehicle::RunAuxiliariesCommand(VehicleCommand const Command, doubl else if (Command == VehicleCommand::batterySwitch) /*NBMX*/ { // the battery of a vehicle prepared for hauling (PulleeMode) stays off - if (BatteryStart == start_t::manual && (false == PulleeMode || CValue1 <= 0.0)) + if (lowVoltage.batteryStart == start_t::manual && (false == PulleeMode || CValue1 <= 0.0)) { - Battery = CValue1 > 0.0; + lowVoltage.batteryOn = CValue1 > 0.0; } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } @@ -693,7 +693,7 @@ void physics::Vehicle::DoorRemoteCommand(bool const Open, double const CValue1, { using enum control_t; if (auto const doorcontrol{Open ? Doors.open_control : Doors.close_control}; - (doorcontrol != conductor && doorcontrol != driver && doorcontrol != mixed) || (false == Power24vIsAvailable && false == Power110vIsAvailable)) + (doorcontrol != conductor && doorcontrol != driver && doorcontrol != mixed) || (false == lowVoltage.power24vAvailable && false == lowVoltage.power110vAvailable)) { return; } diff --git a/physics/components/controllers.cpp b/physics/components/controllers.cpp index ea780ab4e..d88cdc6c8 100644 --- a/physics/components/controllers.cpp +++ b/physics/components/controllers.cpp @@ -167,7 +167,7 @@ bool physics::Vehicle::IncMainCtrlSeriesMotor(int const CtrlSpeed) //} } - if (TrainType == train_type::et42 && true == DynamicBrakeFlag && MainCtrlPos > 20) + if (TrainType == train_type::et42 && true == brakes.electrodynamic.on && MainCtrlPos > 20) { MainCtrlPos = 20; OK = false; @@ -350,11 +350,11 @@ bool physics::Vehicle::IncScndCtrl(int CtrlSpeed) { bool OK = false; - if (DynamicBrakeFlag && TrainType == train_type::et42 && CabActive != 0 && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0) + if (brakes.electrodynamic.on && TrainType == train_type::et42 && CabActive != 0 && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0) { OK = DynamicBrakeSwitch(false); } - else if (ScndCtrlPosNo > 0 && CabActive != 0 && !(TrainType == train_type::et42 && (Imax == ImaxHi || (DynamicBrakeFlag && MainCtrlPowerPos() > 0)))) + else if (ScndCtrlPosNo > 0 && CabActive != 0 && !(TrainType == train_type::et42 && (Imax == ImaxHi || (brakes.electrodynamic.on && MainCtrlPowerPos() > 0)))) { // if (RList[MainCtrlPos].R=0) and (MainCtrlPos>0) and (ScndCtrlPos0 OK = DynamicBrakeSwitch(true); @@ -498,7 +498,7 @@ void physics::Vehicle::ScndCtrlResistiveLockCheck() int physics::Vehicle::GetVirtualScndPos() const { - if (TrainType == train_type::et42 && DynamicBrakeFlag && !ScndCtrlPos) + if (TrainType == train_type::et42 && brakes.electrodynamic.on && !ScndCtrlPos) return -1; return ScndCtrlPos; } @@ -550,7 +550,7 @@ bool physics::Vehicle::AutoRelayCheck(void) if (motorconnectorsoff || (HasCamshaft ? IsMainCtrlActualNoPowerPos() : IsMainCtrlNoPowerPos())) { lineContactors.closed = false; - if (false == DynamicBrakeFlag) + if (false == brakes.electrodynamic.on) { Im = 0; Itot = 0; @@ -999,8 +999,8 @@ void physics::Vehicle::CheckEIMIC(double dt) // Dodatkowo zapotrzebowanie ED jest ograniczone przez strefe Vh0..Vh1: powyzej Vh1 - pelny ED, // pomiedzy Vh1 a Vh0 - liniowe zanikanie, ponizej Vh0 - zerowe (brak hamowania pneumatycznego // jako uzupelnienia, poniewaz LocalBrake jest oddzielny i operuje wylacznie pneumatyka). - double brakeDemand = SplitEDPneumaticBrake ? DynamicBrakeRatio() : LocalBrakeRatio(); - if (SplitEDPneumaticBrake) + double brakeDemand = brakes.electrodynamic.splitFromPneumatic ? DynamicBrakeRatio() : LocalBrakeRatio(); + if (brakes.electrodynamic.splitFromPneumatic) { double const vh0 = inductionMotor.braking.offSpeed; double const vh1 = inductionMotor.braking.fullSpeed; diff --git a/physics/components/diesel.cpp b/physics/components/diesel.cpp index 9ed1ad4ff..d7e7ecc85 100644 --- a/physics/components/diesel.cpp +++ b/physics/components/diesel.cpp @@ -50,7 +50,7 @@ double physics::Vehicle::EngineMaxRPM() const void physics::Vehicle::WaterPumpCheck(double const /*Timestep*/) { // NOTE: breaker override with start type is sm42 specific hack, replace with ability to define the presence of the breaker - WaterPump.is_active = true == (Power24vIsAvailable || Power110vIsAvailable) && true == WaterPump.breaker && false == WaterPump.is_disabled && + WaterPump.is_active = true == (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable) && true == WaterPump.breaker && false == WaterPump.is_disabled && (true == WaterPump.is_active || true == WaterPump.is_enabled || WaterPump.start_type == start_t::battery); } @@ -58,7 +58,7 @@ void physics::Vehicle::WaterPumpCheck(double const /*Timestep*/) void physics::Vehicle::WaterHeaterCheck(double const /*Timestep*/) { - WaterHeater.is_active = false == WaterHeater.is_damaged && true == (Power24vIsAvailable || Power110vIsAvailable) && true == WaterHeater.is_enabled && true == WaterHeater.breaker && + WaterHeater.is_active = false == WaterHeater.is_damaged && true == (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable) && true == WaterHeater.is_enabled && true == WaterHeater.breaker && (WaterHeater.is_active || WaterHeater.config.temp_min < 0 || diesel.heat.temperatura1 < WaterHeater.config.temp_min); WaterHeater.is_damaged = true == WaterHeater.is_damaged || (true == WaterHeater.is_active && false == WaterPump.is_active); @@ -74,7 +74,7 @@ void physics::Vehicle::FuelPumpCheck(double const /*Timestep*/) { using enum start_t; - FuelPump.is_active = true == (Power24vIsAvailable || Power110vIsAvailable) && false == FuelPump.is_disabled && + FuelPump.is_active = true == (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable) && false == FuelPump.is_disabled && (FuelPump.is_active || (FuelPump.start_type == manual ? FuelPump.is_enabled : FuelPump.start_type == automatic ? diesel.startupRequested || lineBreaker.closed : FuelPump.start_type == manualwithautofallback ? FuelPump.is_enabled || diesel.startupRequested || lineBreaker.closed : @@ -85,7 +85,7 @@ void physics::Vehicle::FuelPumpCheck(double const /*Timestep*/) void physics::Vehicle::OilPumpCheck(double const Timestep) { - OilPump.is_active = true == (Power24vIsAvailable || Power110vIsAvailable) && false == lineBreaker.closed && false == OilPump.is_disabled && + OilPump.is_active = true == (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable) && false == lineBreaker.closed && false == OilPump.is_disabled && (OilPump.is_active || (OilPump.start_type == start_t::manual ? OilPump.is_enabled : OilPump.start_type == start_t::automatic ? diesel.startupRequested : OilPump.start_type == start_t::manualwithautofallback ? OilPump.is_enabled || diesel.startupRequested : @@ -341,10 +341,10 @@ double physics::Vehicle::DieselElectricTargetRevolutions() else tmp = DElist[protection.pressureSwitch ? MainCtrlNoPowerPos() : MainCtrlPos].RPM / 60.0; - if (true == HeatingAllow && HeatingPower > 0 && EngineHeatingRPM > 0) + if (true == trainHeating.allow && trainHeating.power > 0 && trainHeating.engineRpm > 0) { // bump engine revolutions up if needed, when heating is on - tmp = std::max(tmp, std::min(EngineMaxRPM(), EngineHeatingRPM) / 60.0); + tmp = std::max(tmp, std::min(EngineMaxRPM(), trainHeating.engineRpm) / 60.0); } // NOTE: fake diesel.fill calculation for the sake of smoke emitter which uses this parameter to determine smoke opacity diesel.fill = std::clamp(0.2 + 0.35 * (tmp - enrot) + 0.5 * (std::abs(Im) / DElist[MainCtrlPosNo].Imax), 0.05, 1.0); @@ -385,9 +385,9 @@ void physics::Vehicle::DieselElectricTractionForce(double tmp) auto power = Power; tempImax = DElist[MainCtrlPos].Imax; tempUmax = DElist[MainCtrlPos].Umax; - if (true == Heating) + if (true == trainHeating.on) { - power -= HeatingPower; + power -= trainHeating.power; } power = std::max(power, 0.0); // NOTE: very crude way to approximate power generated at current rpm instead of instant top output @@ -618,7 +618,7 @@ void physics::Vehicle::update_dieselelectric_dynamic_brake(double const dt) brake.level = 0.0; } brake.force = brake.level * dieselelectric_dynamic_brake_limit(); - DynamicBrakeFlag = brake.force > 0.0; + brakes.electrodynamic.on = brake.force > 0.0; if (brake.blending) { // the train brake of the locomotive lets off by the share of the dynamic brake's force (LSt, EStED) @@ -1373,7 +1373,7 @@ void physics::Vehicle::dizel_Heat(double const dt) // engine heat transfers auto const Ge{engineon * (0.21 * diesel.heat.powerfactor * EnginePower + 12) / 3600}; // TODO: replace fixed heating power cost with more accurate calculation - auto const obciazenie{engineon * (diesel.heat.powerfactor * EnginePower / 950 + (Heating ? HeatingPower : 0) + 70)}; + auto const obciazenie{engineon * (diesel.heat.powerfactor * EnginePower / 950 + (trainHeating.on ? trainHeating.power : 0) + 70)}; auto const Qd{qs * Ge - obciazenie}; // silnik oddaje czesc ciepla do wody chlodzacej, a takze pewna niewielka czesc do otoczenia, modyfikowane przez okienko auto const Qs{(Qd - diesel.heat.kfs * (diesel.heat.Ts - diesel.heat.Tsr) - diesel.heat.kfe * /* ( 0.3 + 0.7 * ( diesel.heat.okienko ? 1 : 0 ) ) * */ (diesel.heat.Ts - diesel.heat.Te))}; @@ -1400,7 +1400,7 @@ void physics::Vehicle::dizel_Heat(double const dt) { // auxiliary water circuit setup diesel.heat.water_aux.is_warm = true == diesel.heat.cooling || - (true == lineBreaker.closed && BatteryVoltage > 0.75 * NominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ + (true == lineBreaker.closed && lowVoltage.batteryVoltage > 0.75 * lowVoltage.nominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ && diesel.heat.water_aux.config.temp_cooling > 0 && diesel.heat.temperatura2 > diesel.heat.water_aux.config.temp_cooling - (diesel.heat.water_aux.is_warm ? 8 : 0)); auto const PTC2{(diesel.heat.water_aux.is_warm /*or PTC2p*/ ? 1 : 0)}; diesel.heat.rpmwz2 = static_cast(PTC2 * (diesel.heat.fan_speed >= 0 ? rpm * diesel.heat.fan_speed : diesel.heat.fan_speed * -1)); @@ -1423,7 +1423,7 @@ void physics::Vehicle::dizel_Heat(double const dt) diesel.heat.water.is_flowing = diesel.heat.water.config.temp_flow < 0 || diesel.heat.temperatura1 > diesel.heat.water.config.temp_flow - (diesel.heat.water.is_flowing ? 5 : 0); auto const obieg{(diesel.heat.water.is_flowing ? 1 : 0)}; diesel.heat.water.is_warm = - true == diesel.heat.cooling || (true == lineBreaker.closed && BatteryVoltage > 0.75 * NominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ + true == diesel.heat.cooling || (true == lineBreaker.closed && lowVoltage.batteryVoltage > 0.75 * lowVoltage.nominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ && diesel.heat.water.config.temp_cooling > 0 && diesel.heat.temperatura1 > diesel.heat.water.config.temp_cooling - (diesel.heat.water.is_warm ? 8 : 0)); auto const PTC1{(diesel.heat.water.is_warm /*or PTC1p*/ ? 1 : 0)}; diesel.heat.rpmwz = static_cast(PTC1 * (diesel.heat.fan_speed >= 0 ? rpm * diesel.heat.fan_speed : diesel.heat.fan_speed * -1)); diff --git a/physics/components/doors.cpp b/physics/components/doors.cpp index 2e90c2a88..613d33da4 100644 --- a/physics/components/doors.cpp +++ b/physics/components/doors.cpp @@ -281,7 +281,7 @@ bool physics::Vehicle::OperateDoors(VehicleSide const Door, bool const State, ra else { // remote door operation signals require power to propagate - if (Power24vIsAvailable || Power110vIsAvailable) + if (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable) { door.remote_open = State; door.remote_close = false == State; @@ -486,9 +486,9 @@ bool physics::Vehicle::doors_powered() const } if (Doors.voltage == 24) { - return Power24vIsAvailable || Power110vIsAvailable; + return lowVoltage.power24vAvailable || lowVoltage.power110vAvailable; } - return Doors.voltage == 110 && Power110vIsAvailable; + return Doors.voltage == 110 && lowVoltage.power110vAvailable; } // whether the unfolded step folds: without the permission to stay out, or with the door closing, once it's about to diff --git a/physics/components/drive.cpp b/physics/components/drive.cpp index 938b66069..648c6cac4 100644 --- a/physics/components/drive.cpp +++ b/physics/components/drive.cpp @@ -125,7 +125,7 @@ void updateRadiatorFans(physics::Vehicle &vehicle, double const dt) // else it needs the voltage of the source bool linePowerAvailable(physics::Vehicle const &vehicle) { - return vehicle.lineBreaker.pantographsRequireIt ? vehicle.Power24vIsAvailable || vehicle.Power110vIsAvailable : vehicle.EnginePowerSourceVoltage() > 0.5 * vehicle.EnginePowerSource.MaxVoltage; + return vehicle.lineBreaker.pantographsRequireIt ? vehicle.lowVoltage.power24vAvailable || vehicle.lowVoltage.power110vAvailable : vehicle.EnginePowerSourceVoltage() > 0.5 * vehicle.EnginePowerSource.MaxVoltage; } // a notch of the master controller of the drives without steps of their own (no engine, Dumb, diesel-electric, @@ -199,7 +199,7 @@ public: } bool MainsPowerAvailable(physics::Vehicle const &vehicle) const override { - return vehicle.Power24vIsAvailable; + return vehicle.lowVoltage.power24vAvailable; } bool IncreaseMainController(physics::Vehicle &vehicle, int const speed) const override { @@ -421,7 +421,7 @@ public: } bool MainsPowerAvailable(physics::Vehicle const &vehicle) const override { - return vehicle.Power24vIsAvailable; + return vehicle.lowVoltage.power24vAvailable; } bool UpdateEngine(physics::Vehicle &vehicle, double const dt) const override { @@ -523,7 +523,7 @@ public: } bool MainsPowerAvailable(physics::Vehicle const &vehicle) const override { - return vehicle.Power24vIsAvailable; + return vehicle.lowVoltage.power24vAvailable; } void CheckVoltageRelays(physics::Vehicle &vehicle) const override { diff --git a/physics/components/electrics.cpp b/physics/components/electrics.cpp index 20e734075..178bcab4f 100644 --- a/physics/components/electrics.cpp +++ b/physics/components/electrics.cpp @@ -40,7 +40,7 @@ void physics::Vehicle::UpdatePantVolume(double dt) pantographAir.compressorRunning |= pantographAir.pressure < 4.2 && true == (pantographs[VehicleEnd::front].is_active | pantographs[VehicleEnd::rear].is_active) // TODO: any_pantograph_is_active method && (pantographAir.compressorStart == start_t::automatic || pantographAir.compressorStart == start_t::manualwithautofallback); - auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; + auto const lowvoltagepower{lowVoltage.power24vAvailable || lowVoltage.power110vAvailable}; pantographAir.compressorRunning &= lowvoltagepower; if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector // tylko jeśli pantografujący @@ -96,7 +96,7 @@ void physics::Vehicle::PantPressureSwitchCheck() { // NOTE: we require active low power source to prime the pressure switch // this is a work-around for potential isssues caused by the switch activating on otherwise idle vehicles, but should check whether it's accurate - if (true == Power24vIsAvailable || true == Power110vIsAvailable) + if (true == lowVoltage.power24vAvailable || true == lowVoltage.power110vAvailable) { // prime the pressure switch pantographAir.pressureSwitchActive = true; @@ -143,41 +143,41 @@ void physics::Vehicle::PantPressureSwitchTrip() void physics::Vehicle::UpdateBatteryVoltage(double dt) { // przeliczenie obciążenia baterii using enum TEngineType; - if (BatteryVoltage > 0 && EngineType != DieselEngine && EngineType != WheelsDriven && NominalBatteryVoltage > 0) + if (lowVoltage.batteryVoltage > 0 && EngineType != DieselEngine && EngineType != WheelsDriven && lowVoltage.nominalBatteryVoltage > 0) { // HACK: allow to draw power also from adjacent converter, applicable for EMUs // TODO: expand power cables system to include low voltage power transfers // HACK: emulate low voltage generator powered directly by the diesel engine - auto const converteractive{Power110vIsAvailable || (EngineType == DieselElectric && true == lineBreaker.closed) || (EngineType == DieselEngine && true == lineBreaker.closed)}; + auto const converteractive{lowVoltage.power110vAvailable || (EngineType == DieselElectric && true == lineBreaker.closed) || (EngineType == DieselEngine && true == lineBreaker.closed)}; - BatteryVoltage -= BatteryDrain(dt, converteractive); - if (NominalBatteryVoltage / BatteryVoltage > 1.57 && MainSwitch(false) && EngineType != DieselEngine && EngineType != WheelsDriven) + lowVoltage.batteryVoltage -= BatteryDrain(dt, converteractive); + if (lowVoltage.nominalBatteryVoltage / lowVoltage.batteryVoltage > 1.57 && MainSwitch(false) && EngineType != DieselEngine && EngineType != WheelsDriven) EventFlag = true; // wywalanie szybkiego z powodu zbyt niskiego napiecia - if (BatteryVoltage > NominalBatteryVoltage) - BatteryVoltage = NominalBatteryVoltage; // wstrzymanie ładowania pow. 110V - if (BatteryVoltage < 0.01) - BatteryVoltage = 0.01; + if (lowVoltage.batteryVoltage > lowVoltage.nominalBatteryVoltage) + lowVoltage.batteryVoltage = lowVoltage.nominalBatteryVoltage; // wstrzymanie ładowania pow. 110V + if (lowVoltage.batteryVoltage < 0.01) + lowVoltage.batteryVoltage = 0.01; } else { // TODO: check and implement proper way to handle this for diesel engines - BatteryVoltage = NominalBatteryVoltage; + lowVoltage.batteryVoltage = lowVoltage.nominalBatteryVoltage; } }; // the drop of the battery's voltage in dt, by what draws from it, or its rise by the converter charging it double physics::Vehicle::BatteryDrain(double dt, bool const converteractive) const { - if (NominalBatteryVoltage / BatteryVoltage < 1.22 && Battery) + if (lowVoltage.nominalBatteryVoltage / lowVoltage.batteryVoltage < 1.22 && lowVoltage.batteryOn) { // 110V return BatteryDrainCharged(dt, converteractive); } - if (NominalBatteryVoltage / BatteryVoltage >= 1.22 && Battery) + if (lowVoltage.nominalBatteryVoltage / lowVoltage.batteryVoltage >= 1.22 && lowVoltage.batteryOn) { // 90V return BatteryDrainLow(dt, converteractive); } - if (!Battery) + if (!lowVoltage.batteryOn) { return BatteryDrainSwitchedOff(dt); } @@ -254,7 +254,7 @@ double physics::Vehicle::BatteryDrainSwitchedOff(double dt) const double sn3; double sn4; double sn5; - if (NominalBatteryVoltage / BatteryVoltage < 1.22) + if (lowVoltage.nominalBatteryVoltage / lowVoltage.batteryVoltage < 1.22) sn1 = dt * 50; else sn1 = 0; @@ -281,7 +281,7 @@ void physics::Vehicle::MainsCheck(double const Deltatime) } case TPowerSource::Accumulator: { - localvoltage = std::max(localvoltage, Power24vVoltage); + localvoltage = std::max(localvoltage, lowVoltage.power24vVoltage); break; } default: @@ -295,7 +295,7 @@ void physics::Vehicle::MainsCheck(double const Deltatime) localvoltage = Genset.voltage; } // a line breaker closed ahead of the pantographs gets ready on the low voltage circuits - auto const maincircuitpowersupply{std::abs(localvoltage) > 0.1 || GetTrainsetHighVoltage() > 0.1 || (lineBreaker.pantographsRequireIt && (Power24vIsAvailable || Power110vIsAvailable))}; + auto const maincircuitpowersupply{std::abs(localvoltage) > 0.1 || GetTrainsetHighVoltage() > 0.1 || (lineBreaker.pantographsRequireIt && (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable))}; if (true == maincircuitpowersupply) { @@ -331,7 +331,7 @@ void physics::Vehicle::MainsCheck(double const Deltatime) void physics::Vehicle::LowVoltagePowerCheck(double const /*Deltatime*/) { - auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; + auto const lowvoltagepower{lowVoltage.power24vAvailable || lowVoltage.power110vAvailable}; if (EngineType == TEngineType::ElectricSeriesMotor) { @@ -394,7 +394,7 @@ double physics::Vehicle::LocalPowerVoltage(Coupling const kind) case Coupling::highVoltage: { // heating power sources - if (Heating) + if (trainHeating.on) { switch (HeatingPowerSource.SourceType) { @@ -433,7 +433,7 @@ double physics::Vehicle::LocalPowerVoltage(Coupling const kind) { if (converter.running) { - localvoltage = NominalBatteryVoltage; + localvoltage = lowVoltage.nominalBatteryVoltage; } // TBD, TODO: reduce by current draw? PowerCircuits[1].first = localvoltage; @@ -442,9 +442,9 @@ double physics::Vehicle::LocalPowerVoltage(Coupling const kind) case Coupling::power24v: { - if (Battery) + if (lowVoltage.batteryOn) { - localvoltage = BatteryVoltage; + localvoltage = lowVoltage.batteryVoltage; } // TBD, TODO: reduce by current draw? PowerCircuits[0].first = localvoltage; @@ -487,7 +487,7 @@ void physics::Vehicle::PowerCouplersVoltage(Coupling const kind, double const ab auto const oppositeheatingcoupling{oppositecoupler.CouplingFlag.HasAny(Coupling::heating)}; oppositecouplingispresent = oppositehighvoltagecoupling || oppositeheatingcoupling; - localpowerexportisenabled = oppositehighvoltagecoupling || (oppositeheatingcoupling && localpowersource && Heating); + localpowerexportisenabled = oppositehighvoltagecoupling || (oppositeheatingcoupling && localpowersource && trainHeating.on); break; } @@ -593,7 +593,7 @@ void physics::Vehicle::ConverterCheck(double const Timestep) // TODO: move other converter checks here, to have it all in one place for potential device object if (converter.start != start_t::disabled && converter.overloadRelayOffWithLineBreaker) { - converter.overloaded |= !lineBreaker.closed && Power24vIsAvailable; + converter.overloaded |= !lineBreaker.closed && lowVoltage.power24vAvailable; } switch (converter.start) @@ -663,7 +663,7 @@ void physics::Vehicle::HeatingCheck(double const /*Timestep*/) generator.revolutions = *generator.engine_revolutions; auto const absrevolutions{std::abs(generator.revolutions)}; - generator.voltage = (false == HeatingAllow ? 0.0 : + generator.voltage = (false == trainHeating.allow ? 0.0 : // TODO: add support for desired voltage selector absrevolutions < generator.revolutions_min ? generator.voltage_min * absrevolutions / generator.revolutions_min : @@ -675,9 +675,9 @@ void physics::Vehicle::HeatingCheck(double const /*Timestep*/) } // quick check first to avoid unnecessary calls... - if (false == HeatingAllow) + if (false == trainHeating.allow) { - Heating = false; + trainHeating.on = false; return; } // ...detailed check if we're still here @@ -717,11 +717,11 @@ void physics::Vehicle::HeatingCheck(double const /*Timestep*/) } } - Heating = voltage > heatingpowerthreshold; + trainHeating.on = voltage > heatingpowerthreshold; - if (Heating) + if (trainHeating.on) { - TotalCurrent += 1000 * HeatingPower / voltage; // heater power cost presumably specified in kilowatts + TotalCurrent += 1000 * trainHeating.power / voltage; // heater power cost presumably specified in kilowatts } } @@ -731,7 +731,7 @@ void physics::Vehicle::PantographsCheck(double const /*Timestep*/) { auto const &valve{pantographAir.valve}; - auto const lowvoltagepower{valve.solenoid ? Power24vIsAvailable || Power110vIsAvailable : true}; + auto const lowvoltagepower{valve.solenoid ? lowVoltage.power24vAvailable || lowVoltage.power110vAvailable : true}; auto const autostart{valve.start_type == automatic || valve.start_type == manualwithautofallback}; auto const manualcontrol{valve.start_type == manual || valve.start_type == manualwithautofallback}; @@ -747,7 +747,7 @@ void physics::Vehicle::PantographsCheck(double const /*Timestep*/) { auto &valve{pantograph.valve}; - auto const lowvoltagepower{valve.solenoid ? Power24vIsAvailable || Power110vIsAvailable : true}; + auto const lowvoltagepower{valve.solenoid ? lowVoltage.power24vAvailable || lowVoltage.power110vAvailable : true}; auto const autostart{valve.start_type == automatic || valve.start_type == manualwithautofallback}; auto const manualcontrol{valve.start_type == manual || valve.start_type == manualwithautofallback}; @@ -775,7 +775,7 @@ void physics::Vehicle::GensetCheck(double const Deltatime) } auto &genset{Genset}; auto const wasactive{genset.is_active}; - auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; + auto const lowvoltagepower{lowVoltage.power24vAvailable || lowVoltage.power110vAvailable}; auto const requested{lowvoltagepower && false == genset.is_disabled && (genset.start_type == start_t::automatic ? GensetSelected() : genset.is_enabled)}; if (false == requested) { @@ -829,13 +829,13 @@ void physics::Vehicle::LightsCheck(double const /*Timestep*/) light.is_active = // TODO: bind properly power source when ld is in place - (Power24vIsAvailable || Power110vIsAvailable) // power source + (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable) // power source && false == light.is_disabled && (true == light.is_active || (light.start_type == start_t::manual ? light.is_enabled : true)); light.intensity = (light.is_active ? 1.0f : 0.0f) // TODO: bind properly power source when ld is in place - * (Power110vIsAvailable ? 1.0f : - Power24vIsAvailable ? 0.5f : + * (lowVoltage.power110vAvailable ? 1.0f : + lowVoltage.power24vAvailable ? 0.5f : 0.0f) * light.dimming; } @@ -852,12 +852,12 @@ bool physics::Vehicle::BatterySwitch(bool State, range_t const Notify) // the battery of a vehicle prepared for hauling stays off return false; } - auto const initialstate{Battery}; + auto const initialstate{lowVoltage.batteryOn}; // Ra: ukrotnienie załączania baterii jest jakąś fikcją... - if (BatteryStart == start_t::manual) + if (lowVoltage.batteryStart == start_t::manual) { - Battery = State; + lowVoltage.batteryOn = State; } // switching batteries does not require activation @@ -867,7 +867,7 @@ bool physics::Vehicle::BatterySwitch(bool State, range_t const Notify) SendCtrlToNext(VehicleCommand::batterySwitch, State ? 1 : 0, -1, Notify == unit ? Coupling::control | Coupling::permanent : Coupling::control); } - return Battery != initialstate; + return lowVoltage.batteryOn != initialstate; } bool physics::Vehicle::CompartmentLightsSwitch(bool State, range_t const Notify) @@ -1025,7 +1025,7 @@ bool physics::Vehicle::ConverterSwitch(bool State, range_t const Notify) bool physics::Vehicle::HeatingSwitch(bool const State, range_t const Notify) { - bool const initialstate{HeatingAllow}; + bool const initialstate{trainHeating.allow}; HeatingSwitch_(State); @@ -1036,14 +1036,14 @@ bool physics::Vehicle::HeatingSwitch(bool const State, range_t const Notify) SendCtrlToNext(VehicleCommand::heatingSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } - return HeatingAllow != initialstate; + return trainHeating.allow != initialstate; } void physics::Vehicle::HeatingSwitch_(bool const State) { // TBD, TODO: activation dependencies? - HeatingAllow = State; + trainHeating.allow = State; } // the start request of the genset of a dual-mode vehicle; one which starts on its own ignores it, but passes it on to @@ -1100,7 +1100,7 @@ double physics::Vehicle::CatenaryCurrent() const { return HeatingPowerSource.SourceType == TPowerSource::CurrentCollector ? TotalCurrent : 0.0; } - return (DynamicBrakeFlag && ResistorsFlag ? 0 : std::abs(Itot) * IsVehicleEIMBrakingFactor()) + TotalCurrent; + return (brakes.electrodynamic.on && ResistorsFlag ? 0 : std::abs(Itot) * IsVehicleEIMBrakingFactor()) + TotalCurrent; } // returns voltage of defined main engine power source @@ -1108,7 +1108,7 @@ double physics::Vehicle::EnginePowerSourceVoltage() const { return EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? TractionSupplyVoltage() : - EnginePowerSource.SourceType == TPowerSource::Accumulator ? Power24vVoltage : + EnginePowerSource.SourceType == TPowerSource::Accumulator ? lowVoltage.power24vVoltage : 0.0; } @@ -1304,7 +1304,7 @@ double physics::Vehicle::GetTrainsetVoltage(CouplingSet const couplings) const double physics::Vehicle::GetTrainsetHighVoltage() const { - return std::max(GetTrainsetVoltage(Coupling::highVoltage), HeatingAllow ? GetTrainsetVoltage(Coupling::heating) : 0.0); + return std::max(GetTrainsetVoltage(Coupling::highVoltage), trainHeating.allow ? GetTrainsetVoltage(Coupling::heating) : 0.0); } int physics::Vehicle::clampDimmerPosition(int const Position) const diff --git a/physics/components/fizsections.cpp b/physics/components/fizsections.cpp index ea183719c..d32c1bda1 100644 --- a/physics/components/fizsections.cpp +++ b/physics/components/fizsections.cpp @@ -62,7 +62,7 @@ void physics::Vehicle::LoadFIZ_Param(std::string const &line) extract_value(Vmax, "Vmax", line, "0"); extract_value(Power, "PWR", line, "0"); extract_value(SandCapacity, "SandCap", line, "0"); - extract_value(HeatingPower, "HeatingP", line, "0"); + extract_value(trainHeating.power, "HeatingP", line, "0"); extract_value(LightPower, "LightP", line, "0"); { @@ -814,20 +814,20 @@ void physics::Vehicle::LoadFIZ_CntrlControllers(std::string const &line) { std::map> dynamicbrakes{{"Passive", dbrake_passive}, {"Switch", dbrake_switch}, {"Reversal", dbrake_reversal}, {"Automatic", dbrake_automatic}}; auto lookup = dynamicbrakes.find(extract_value("DynamicBrake", line)); - DynamicBrakeType = lookup != dynamicbrakes.end() ? lookup->second : dbrake_none; - extract_value(DynamicBrakeAmpmeters, "DBAM", line, ""); + brakes.electrodynamic.type = lookup != dynamicbrakes.end() ? lookup->second : dbrake_none; + extract_value(brakes.electrodynamic.ammeters, "DBAM", line, ""); } // split ED/pneumatic brake control: when true the local brake operates only on the // pneumatic locomotive cylinder while electrodynamic braking is commanded by a // separate "dynamicbrakectrl" lever (or the negative range of jointctrl). - extract_value(SplitEDPneumaticBrake, "SplitEDPneumaticBrake", line, ""); + extract_value(brakes.electrodynamic.splitFromPneumatic, "SplitEDPneumaticBrake", line, ""); // number of stepped positions for the dedicated ED brake controller (default 10) - DynamicBrakeCtrlPosNo = 10; - extract_value(DynamicBrakeCtrlPosNo, "DBPN", line, ""); - if (DynamicBrakeCtrlPosNo < 1) + brakes.electrodynamic.controllerPositions = 10; + extract_value(brakes.electrodynamic.controllerPositions, "DBPN", line, ""); + if (brakes.electrodynamic.controllerPositions < 1) { - DynamicBrakeCtrlPosNo = 10; + brakes.electrodynamic.controllerPositions = 10; } extract_value(MainCtrlPosNo, "MCPN", line, ""); @@ -896,9 +896,9 @@ void physics::Vehicle::LoadFIZ_CntrlControllers(std::string const &line) extract_value(isDoubleClickForMeasureNeeded, "DCMB", line, ""); extract_value(DistanceCounterDoublePressPeriod, "DCDPP", line, ""); - extract_value(isBatteryButtonImpulse, "IBTB", line, ""); - extract_value(shouldHoldBatteryButton, "SBBBH", line, ""); - extract_value(BatteryButtonHoldTime, "BBHT", line, ""); + extract_value(lowVoltage.batteryButtonImpulse, "IBTB", line, ""); + extract_value(lowVoltage.batteryButtonHeld, "SBBBH", line, ""); + extract_value(lowVoltage.batteryButtonHoldTime, "BBHT", line, ""); } // Cntrl.: how the devices start (MainStart, BatteryStart, ...) and their relays @@ -921,7 +921,7 @@ void physics::Vehicle::LoadFIZ_CntrlStarts(std::string const &line) // battery { auto lookup = starts.find(extract_value("BatteryStart", line)); - BatteryStart = lookup != starts.end() ? lookup->second : manual; + lowVoltage.batteryStart = lookup != starts.end() ? lookup->second : manual; } // converter { @@ -1076,8 +1076,8 @@ void physics::Vehicle::LoadFIZ_Light(std::string const &line) LoadFIZ_PowerParamsDecode(AlterLightPowerSource, "AlterL", line); extract_value(NominalVoltage, "Volt", line, ""); - extract_value(BatteryVoltage, "LMaxVoltage", line, ""); - NominalBatteryVoltage = static_cast(BatteryVoltage); + extract_value(lowVoltage.batteryVoltage, "LMaxVoltage", line, ""); + lowVoltage.nominalBatteryVoltage = static_cast(lowVoltage.batteryVoltage); } void physics::Vehicle::LoadFIZ_Clima(std::string const &line) @@ -1368,7 +1368,7 @@ void physics::Vehicle::LoadFIZ_EngineDieselElectric(std::string const &Input) ImaxHi = 2; ImaxLo = 1; } - extract_value(EngineHeatingRPM, "HeatingRPM", Input, ""); + extract_value(trainHeating.engineRpm, "HeatingRPM", Input, ""); extract_value(diesel.shaftInertia, "AIM", Input, "1.25"); extract_value(diesel.revolutionsDecreaseRate, "RPMDecRate", Input, ""); LoadFIZ_DieselElectricDynamicBrake(Input); @@ -1410,8 +1410,8 @@ void physics::Vehicle::LoadFIZ_EngineInductionMotor(std::string const &Input) extract_value(inductionMotor.logForce, "eimclf", Input, ""); extract_value(inductionMotor.inverterCount, "InvNo", Input, ""); extract_value(inductionMotor.inverterControlCouplings, "InvCtrCplFlag", Input, ""); - extract_value(Imaxrpc, "Imaxrpc", Input, ""); - extract_value(BRVto, "BRVto", Input, ""); + extract_value(brakes.electrodynamic.resistorPassiveMaxCurrent, "Imaxrpc", Input, ""); + extract_value(brakes.electrodynamic.resistorFansSustain, "BRVto", Input, ""); extract_value(Flat, "Flat", Input, ""); if (inductionMotor.traction.maxPower > 0 && Power > 0 && inductionMotor.inverterCount == 0) @@ -1471,7 +1471,7 @@ void physics::Vehicle::LoadFIZ_Switches(std::string const &Input) extract_value(pantographCircuit.switchType, "Pantograph", Input, ""); extract_value(converter.switchType, "Converter", Input, ""); extract_value(lineContactors.switchType, "MotorConnectors", Input, ""); - HeatingSwitchImpulse = ToLower(extract_value("TrainHeating", Input)) == "impulse"; + trainHeating.switchImpulse = ToLower(extract_value("TrainHeating", Input)) == "impulse"; // because people can't make up their minds whether it's "impulse" or "Impulse"... pantographCircuit.switchType = ToLower(pantographCircuit.switchType); converter.switchType = ToLower(converter.switchType); @@ -1565,9 +1565,9 @@ void physics::Vehicle::LoadFIZ_RList(std::string const &Input) } extract_value(RVentMinI, "RVentMinI", Input, ""); extract_value(RVentSpeed, "RVentSpeed", Input, ""); - extract_value(DynamicBrakeRes, "DynBrakeRes", Input, ""); - extract_value(DynamicBrakeRes1, "DynBrakeRes1", Input, ""); - extract_value(DynamicBrakeRes2, "DynBrakeRes2", Input, ""); + extract_value(brakes.electrodynamic.resistance, "DynBrakeRes", Input, ""); + extract_value(brakes.electrodynamic.resistance1, "DynBrakeRes1", Input, ""); + extract_value(brakes.electrodynamic.resistance2, "DynBrakeRes2", Input, ""); } // the dynamic brake of a diesel-electric vehicle, from its Engine section: none without EDBrake @@ -1595,7 +1595,7 @@ void physics::Vehicle::LoadFIZ_DieselElectricDynamicBrake(std::string const &Inp if (brake.source == lever) { // the lever of its own, which the commands of the dynamic brake controller move - SplitEDPneumaticBrake = true; + brakes.electrodynamic.splitFromPneumatic = true; } } diff --git a/physics/components/lowvoltage.h b/physics/components/lowvoltage.h new file mode 100644 index 000000000..5127e3455 --- /dev/null +++ b/physics/components/lowvoltage.h @@ -0,0 +1,46 @@ +/* +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 low voltage supply and the train heating of a vehicle, held by physics::Vehicle as lowVoltage and trainHeating + +#pragma once + +#include "physics/vehicletypes.h" + +namespace physics +{ + +// the battery and the low voltage circuits +struct LowVoltageSupply +{ + bool batteryOn = false; // the battery switched on + double batteryVoltage = 0.0; + float nominalBatteryVoltage = 0.f; + start_t batteryStart = start_t::manual; + bool power110vAvailable = false; // the 110 V circuit has power, as the last step found it + bool power24vAvailable = false; // the 24 V circuit has power, as the last step found it + double power24vVoltage{0.0}; // the voltage of the battery circuit, as the last step found it + // the battery switch of the cab + bool batteryButtonFired = false; // the button already pressed + bool batteryButtonImpulse = false; // the switch works as a single button + bool batteryButtonHeld = false; // the button has to be held to switch the battery on or off + float batteryButtonHoldTime = 1.f; // how long it has to be held [s] +}; + +// the heating of the train fed by the vehicle +struct TrainHeating +{ + bool on = false; + bool allow{false}; // the heating switch. TODO: wrap the heating in a basic device + bool switchImpulse{false}; // the switch springs back to its middle position + double power = 0.0; + double engineRpm{0.0}; // the revolutions of the engine guaranteed with the heating on +}; + +} // namespace physics diff --git a/physics/components/pneumatics.cpp b/physics/components/pneumatics.cpp index c1e9fcd8a..62cd30bb3 100644 --- a/physics/components/pneumatics.cpp +++ b/physics/components/pneumatics.cpp @@ -246,7 +246,7 @@ bool physics::Vehicle::EpFuseSwitch(bool State) // ************************************************************************************************* bool physics::Vehicle::SpringBrakeActivate(bool State) { - if (Power24vIsAvailable || Power110vIsAvailable) + if (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable) { SendCtrlToNext(VehicleCommand::springBrakeActivate, int(State), CabActive, CouplingSet::FromBits(brakes.spring.controlCouplings)); @@ -541,7 +541,7 @@ bool physics::Vehicle::UniversalBrakeButton(int button, int state) bool OK = true; // false tylko jeśli nie uda się wysłać, GF 20161124 brakes.universalButtonPressed[button] = state > 0; int flag = 0; - if (Power24vIsAvailable || Power110vIsAvailable) + if (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable) { for (int i = 0; i < 3; i++) { @@ -588,7 +588,7 @@ bool physics::Vehicle::SwitchEPBrake(int state) bool physics::Vehicle::EPBrakeControlPowered() const { - return Power24vIsAvailable && DirActive != 0 && EpFuse; + return lowVoltage.power24vAvailable && DirActive != 0 && EpFuse; } // ************************************************************************************************* @@ -600,11 +600,11 @@ bool physics::Vehicle::IncBrakePress(double &brake, double PressLimit, double dp bool IBP; // if (DynamicBrakeType<>dbrake_switch) and (DynamicBrakeType<>dbrake_none) and // ((BrakePress>2.0) or (PipePress<3.7{(LowPipePress+0.5)})) then - if (DynamicBrakeType != dbrake_switch && DynamicBrakeType != dbrake_none && brakes.cylinderPressure > 2.0 && TrainType != train_type::emu) // yB radzi nie sprawdzać ciśnienia w przewodzie + if (brakes.electrodynamic.type != dbrake_switch && brakes.electrodynamic.type != dbrake_none && brakes.cylinderPressure > 2.0 && TrainType != train_type::emu) // yB radzi nie sprawdzać ciśnienia w przewodzie // hunter-301211: dla EN57 silnikow nie odlaczamy { - DynamicBrakeFlag = true; // uruchamianie hamulca ED albo odlaczanie silnikow - if (DynamicBrakeType == dbrake_automatic && abs(Im) > 60) // nie napelniaj wiecej, jak na EP09 + brakes.electrodynamic.on = true; // uruchamianie hamulca ED albo odlaczanie silnikow + if (brakes.electrodynamic.type == dbrake_automatic && abs(Im) > 60) // nie napelniaj wiecej, jak na EP09 dp = 0.0; } if (brake + dp < PressLimit) @@ -640,8 +640,8 @@ bool physics::Vehicle::DecBrakePress(double &brake, double PressLimit, double dp } // if ((DynamicBrakeType != dbrake_switch) && ((BrakePress < 0.1) && (PipePress > 0.45 // /*(LowPipePress+0.06)*/ ))) - if (DynamicBrakeType != dbrake_switch && brakes.cylinderPressure < 0.1) // yB radzi nie sprawdzać ciśnienia w przewodzie - DynamicBrakeFlag = false; // wylaczanie hamulca ED i/albo zalaczanie silnikow + if (brakes.electrodynamic.type != dbrake_switch && brakes.cylinderPressure < 0.1) // yB radzi nie sprawdzać ciśnienia w przewodzie + brakes.electrodynamic.on = false; // wylaczanie hamulca ED i/albo zalaczanie silnikow return DBP; } @@ -810,7 +810,7 @@ void physics::Vehicle::CompressorCheck(double dt) } // the main circuit, also for a compressor driven by the engine, otherwise the low voltage - auto const compressorpower{air.compressor.supply == CompressorSupply::mainCircuit || air.compressor.supply == CompressorSupply::engine ? MainCircuitPowered() : Power110vIsAvailable}; + auto const compressorpower{air.compressor.supply == CompressorSupply::mainCircuit || air.compressor.supply == CompressorSupply::engine ? MainCircuitPowered() : lowVoltage.power110vAvailable}; air.compressor.powerTime = compressorpower ? air.compressor.powerTime + dt : 0.0; auto const compressorready{compressorpower && air.compressor.powerTime >= air.compressor.startDelay}; // TBD: split CompressorAllow into separate enable/disable flags, inherit compressor from basic_device @@ -1003,7 +1003,7 @@ void physics::Vehicle::UpdateLocalBrakeValve(double dt) { lbpa = eim_localbrake; } - else if (SplitEDPneumaticBrake) // When LocHandleTimeTraxx and SplitEDPneumaticBrake are both active, lbpa is taken from LocHandleTimeTraxx, which is the desired behavior. + else if (brakes.electrodynamic.splitFromPneumatic) // When LocHandleTimeTraxx and SplitEDPneumaticBrake are both active, lbpa is taken from LocHandleTimeTraxx, which is the desired behavior. { lbpa = brakes.independentPosition; } @@ -1226,12 +1226,12 @@ void physics::Vehicle::UpdateEPBrake() else EpForce = 0.0; - DynamicBrakeEMUStatus = EpForce > 0.001 ? Power110vIsAvailable : true; + brakes.electrodynamic.emuWorking = EpForce > 0.001 ? lowVoltage.power110vAvailable : true; double temp1 = EpForce; - if (brakes.emuDynamic.epMaxSpeed > 0.001 && Vel > brakes.emuDynamic.epMaxSpeed && DynamicBrakeEMUStatus) + if (brakes.emuDynamic.epMaxSpeed > 0.001 && Vel > brakes.emuDynamic.epMaxSpeed && brakes.electrodynamic.emuWorking) temp1 = 0; - if (brakes.emuDynamic.epMinCurrent > 0.001 && abs(Im) > brakes.emuDynamic.epMinCurrent && DynamicBrakeEMUStatus) + if (brakes.emuDynamic.epMinCurrent > 0.001 && abs(Im) > brakes.emuDynamic.epMinCurrent && brakes.electrodynamic.emuWorking) temp1 = 0; brakes.distributor->SetEPS(temp1); TUHEX_StageActual = static_cast(EpForce); diff --git a/physics/components/securitysystem.cpp b/physics/components/securitysystem.cpp index 7eef7086b..5d1fdf2e6 100644 --- a/physics/components/securitysystem.cpp +++ b/physics/components/securitysystem.cpp @@ -248,12 +248,12 @@ void physics::Vehicle::SecuritySystemReset(void) // zbijanie czuwaka/SHP // ************************************************************************************************* void physics::Vehicle::SecuritySystemCheck(double dt) { - bool isPower = Power24vIsAvailable || Power110vIsAvailable; + bool isPower = lowVoltage.power24vAvailable || lowVoltage.power110vAvailable; // the shunt mode of the SM42 switches its vigilance device (CA) off, on the vehicles with AwareOffInShuntMode=Yes (eu07/maszyna#457) SecuritySystem.set_shunt_mode(ShuntMode); SecuritySystem.update(dt, Vel, isPower, CabActive); - if (!Battery || !Radio || !RadioFuse) + if (!lowVoltage.batteryOn || !Radio || !RadioFuse) { // wyłączenie baterii deaktywuje sprzęt RadiostopSwitch(false); } diff --git a/physics/components/setup.cpp b/physics/components/setup.cpp index 9d2ee49db..128047d35 100644 --- a/physics/components/setup.cpp +++ b/physics/components/setup.cpp @@ -41,9 +41,9 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) AutoRelayFlag = AutoRelayType == 1; - if (NominalBatteryVoltage == 0.0) + if (lowVoltage.nominalBatteryVoltage == 0.0) { - BatteryStart = start_t::disabled; + lowVoltage.batteryStart = start_t::disabled; } Sand = SandCapacity; @@ -111,7 +111,7 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) { HeatingPowerSource.SourceType = TPowerSource::Main; } - if (HeatingPowerSource.SourceType == TPowerSource::NotDefined && HeatingPower > 0) + if (HeatingPowerSource.SourceType == TPowerSource::NotDefined && trainHeating.power > 0) { HeatingPowerSource.SourceType = TPowerSource::PowerCable; HeatingPowerSource.PowerType = TPowerType::ElectricPower; @@ -441,7 +441,7 @@ void physics::Vehicle::SetReadyToDepart() DirAbsolute = DirActive * CabActive; // kierunek jazdy względem sprzęgów brakes.pipeLimiterPressure = brakes.controlReservoirPressure; - Battery = BatteryStart != start_t::disabled; + lowVoltage.batteryOn = lowVoltage.batteryStart != start_t::disabled; } // the air and the brakes of a vehicle standing braked diff --git a/physics/components/traction.cpp b/physics/components/traction.cpp index acddd1fa8..cf25d9509 100644 --- a/physics/components/traction.cpp +++ b/physics/components/traction.cpp @@ -74,7 +74,7 @@ double physics::Vehicle::Current(double n, double U) UpdateSeriesMotorDynamicBrakeFlag(); ResistorsFlag = RList[MainCtrlActualPos].R > 0.01; // and (!DelayCtrlFlag) - ResistorsFlag = ResistorsFlag || (DynamicBrakeFlag == true && DynamicBrakeType == dbrake_automatic); + ResistorsFlag = ResistorsFlag || (brakes.electrodynamic.on == true && brakes.electrodynamic.type == dbrake_automatic); if (TrainType == train_type::et22 && DelayCtrlFlag && MainCtrlActualPos > 1) Bn = 1.0 - 1.0 / RList[MainCtrlActualPos].Bn; @@ -97,10 +97,10 @@ double physics::Vehicle::Current(double n, double U) } } - if (DynamicBrakeFlag && !FuseFlag && DynamicBrakeType == dbrake_automatic && Power110vIsAvailable && lineBreaker.closed) // hamowanie EP09 //TUHEX + if (brakes.electrodynamic.on && !FuseFlag && brakes.electrodynamic.type == dbrake_automatic && lowVoltage.power110vAvailable && lineBreaker.closed) // hamowanie EP09 //TUHEX { // TODO: zrobic bardziej uniwersalne nie tylko dla EP09 - MotorCurrent = -std::max(motor_param(0).fi * (Vadd / (Vadd + motor_param(0).Isat) - motor_param(0).fi0), 0.) * n * 2.0 / DynamicBrakeRes; + MotorCurrent = -std::max(motor_param(0).fi * (Vadd / (Vadd + motor_param(0).Isat) - motor_param(0).fi0), 0.) * n * 2.0 / brakes.electrodynamic.resistance; } else if (RList[MainCtrlActualPos].Bn == 0 || false == lineContactors.closed) { @@ -113,7 +113,7 @@ double physics::Vehicle::Current(double n, double U) } // writepaslog("MotorCurrent ", FloatToStr(MotorCurrent)); - if (DynamicBrakeType == dbrake_switch && (brakes.cylinderPressure > 2.0 || brakePipe.pressure < 3.6)) + if (brakes.electrodynamic.type == dbrake_switch && (brakes.cylinderPressure > 2.0 || brakePipe.pressure < 3.6)) { Im = 0; // Im:=0; @@ -133,17 +133,17 @@ double physics::Vehicle::Current(double n, double U) void physics::Vehicle::UpdateSeriesMotorDynamicBrakeFlag() { // i dzialanie hamulca ED w EP09 - if (DynamicBrakeType == dbrake_automatic && TrainType != train_type::emu) + if (brakes.electrodynamic.type == dbrake_automatic && TrainType != train_type::emu) { if ((brakes.distributor->GetEDBCP() < 0.25 && Vadd < 1) || brakes.cylinderPressure > 2.1) - DynamicBrakeFlag = false; + brakes.electrodynamic.on = false; else if (brakes.cylinderPressure > 0.25 && brakes.distributor->GetEDBCP() > 0.25) - DynamicBrakeFlag = true; - DynamicBrakeFlag = DynamicBrakeFlag && Power110vIsAvailable; + brakes.electrodynamic.on = true; + brakes.electrodynamic.on = brakes.electrodynamic.on && lowVoltage.power110vAvailable; } - if (DynamicBrakeType == dbrake_automatic && TrainType == train_type::emu) + if (brakes.electrodynamic.type == dbrake_automatic && TrainType == train_type::emu) { - DynamicBrakeFlag = Power110vIsAvailable && (TUHEX_Active || Vadd > TUHEX_MinIw) && DynamicBrakeEMUStatus; + brakes.electrodynamic.on = lowVoltage.power110vAvailable && (TUHEX_Active || Vadd > TUHEX_MinIw) && brakes.electrodynamic.emuWorking; } // wylacznik cisnieniowy yBARC - to jest chyba niepotrzebne tutaj Q: no to usuwam... @@ -151,7 +151,7 @@ void physics::Vehicle::UpdateSeriesMotorDynamicBrakeFlag() // BrakeSubsystem = ss_LSt; // if (BrakeSubsystem == ss_LSt) WriteLog("LSt"); // if (BrakeSubsystem == ss_LSt) // zrobiona funkcja virtualna - if (DynamicBrakeFlag) + if (brakes.electrodynamic.on) { brakes.distributor->SetED(abs(Im / 350)); // hamulec ED na EP09 dziala az do zatrzymania lokomotywy //- WriteLog("A"); @@ -180,7 +180,7 @@ double physics::Vehicle::SeriesMotorCurrent(double const n, double const U, doub Rz = Mn * WindingRes + R; - if (DynamicBrakeFlag) // hamowanie + if (brakes.electrodynamic.on) // hamowanie { // if DynamicBrakeType<>dbrake_automatic then // MotorCurrent:=-fi*n/Rz {hamowanie silnikiem na oporach rozruchowych} @@ -191,7 +191,7 @@ double physics::Vehicle::SeriesMotorCurrent(double const n, double const U, doub MotorCurrent:=(U-Isf*Rz-Mn*fi*n+SQRT(Delta))/(2*Rz) end*/ // only the ET42's switched brake brakes on the starting resistors, otherwise the current is cut off (0) - if (DynamicBrakeType == dbrake_switch && TrainType == train_type::et42) + if (brakes.electrodynamic.type == dbrake_switch && TrainType == train_type::et42) { // z Megapacka Rz = WindingRes + R; MotorCurrent = -motor_param(SP).fi * n / Rz; //{hamowanie silnikiem na oporach rozruchowych} @@ -381,9 +381,9 @@ bool physics::Vehicle::MotorBlowerPowerIsAvailable(cooling_fan const &Blower) co switch (Blower.start_type) { case start_t::battery: - return Power24vIsAvailable; + return lowVoltage.power24vAvailable; case start_t::converter: - return Power110vIsAvailable; + return lowVoltage.power110vAvailable; default: return MainCircuitPowered(); } @@ -468,13 +468,13 @@ bool physics::Vehicle::TractionModeSwitch(traction_mode const Mode, range_t cons // ************************************************************************************************* bool physics::Vehicle::IncDynamicBrakeLevel(float const CtrlSpeed) { - if (false == SplitEDPneumaticBrake) + if (false == brakes.electrodynamic.splitFromPneumatic) return false; - if (DynamicBrakeCtrlPosNo < 1) + if (brakes.electrodynamic.controllerPositions < 1) return false; - if (DynamicBrakeCtrlPos < 1.0) + if (brakes.electrodynamic.controllerPosition < 1.0) { - DynamicBrakeCtrlPos = std::min(1.0, DynamicBrakeCtrlPos + (double)CtrlSpeed / (double)DynamicBrakeCtrlPosNo); + brakes.electrodynamic.controllerPosition = std::min(1.0, brakes.electrodynamic.controllerPosition + (double)CtrlSpeed / (double)brakes.electrodynamic.controllerPositions); return true; } return false; @@ -485,13 +485,13 @@ bool physics::Vehicle::IncDynamicBrakeLevel(float const CtrlSpeed) // ************************************************************************************************* bool physics::Vehicle::DecDynamicBrakeLevel(float const CtrlSpeed) { - if (false == SplitEDPneumaticBrake) + if (false == brakes.electrodynamic.splitFromPneumatic) return false; - if (DynamicBrakeCtrlPosNo < 1) + if (brakes.electrodynamic.controllerPositions < 1) return false; - if (DynamicBrakeCtrlPos > 0.0) + if (brakes.electrodynamic.controllerPosition > 0.0) { - DynamicBrakeCtrlPos = std::max(0.0, DynamicBrakeCtrlPos - (double)CtrlSpeed / (double)DynamicBrakeCtrlPosNo); + brakes.electrodynamic.controllerPosition = std::max(0.0, brakes.electrodynamic.controllerPosition - (double)CtrlSpeed / (double)brakes.electrodynamic.controllerPositions); return true; } return false; @@ -502,9 +502,9 @@ bool physics::Vehicle::DecDynamicBrakeLevel(float const CtrlSpeed) // ************************************************************************************************* bool physics::Vehicle::DynamicBrakeLevelSet(double Position) { - if (false == SplitEDPneumaticBrake) + if (false == brakes.electrodynamic.splitFromPneumatic) return false; - DynamicBrakeCtrlPos = std::clamp(Position, 0.0, 1.0); + brakes.electrodynamic.controllerPosition = std::clamp(Position, 0.0, 1.0); return true; } @@ -514,9 +514,9 @@ bool physics::Vehicle::DynamicBrakeLevelSet(double Position) // ************************************************************************************************* double physics::Vehicle::DynamicBrakeRatio(void) const { - if (false == SplitEDPneumaticBrake) + if (false == brakes.electrodynamic.splitFromPneumatic) return 0.0; - return std::clamp(DynamicBrakeCtrlPos, 0.0, 1.0); + return std::clamp(brakes.electrodynamic.controllerPosition, 0.0, 1.0); } // ************************************************************************************************* @@ -542,14 +542,14 @@ bool physics::Vehicle::DynamicBrakeSwitch(bool Switch) { bool DBS; - if (DynamicBrakeType == dbrake_switch && IsMainCtrlNoPowerPos()) + if (brakes.electrodynamic.type == dbrake_switch && IsMainCtrlNoPowerPos()) { - DynamicBrakeFlag = Switch; + brakes.electrodynamic.on = Switch; DBS = true; for (auto &thiscoupler : Couplers) // with Couplers[b] do if (thiscoupler.CouplingFlag.HasAll(Coupling::control)) - thiscoupler.Connected->DynamicBrakeFlag = Switch; + thiscoupler.Connected->brakes.electrodynamic.on = Switch; // end; // if (DynamicBrakeType=dbrake_passive) and (TrainType=train_type::et42) then // begin @@ -632,7 +632,7 @@ void physics::Vehicle::UpdateResistorBlowers(double dt) RventRot += (RVentnmax * std::min(1.0, motorcurrent / NPoweredAxles / RVentMinI) * motorcurrent / ImaxLo - RventRot) * RVentSpeed * dt; } - else if (DynamicBrakeType == dbrake_automatic && true == DynamicBrakeFlag) + else if (brakes.electrodynamic.type == dbrake_automatic && true == brakes.electrodynamic.on) { RventRot += (RVentnmax * motorcurrent / ImaxLo - RventRot) * RVentSpeed * dt; } @@ -712,10 +712,10 @@ void physics::Vehicle::SeriesMotorTractionForce(double dt) { if (Imax == ImaxHi) EngineVoltage = EngineVoltage * 2; - if (DynamicBrakeFlag && abs(Im) > 300) // przeiesione do physics.cpp + if (brakes.electrodynamic.on && abs(Im) > 300) // przeiesione do physics.cpp FuseOff(); } - if (DynamicBrakeType == dbrake_automatic && DynamicBrakeFlag) + if (brakes.electrodynamic.type == dbrake_automatic && brakes.electrodynamic.on) { SeriesMotorDynamicBrake(dt); } @@ -730,7 +730,7 @@ void physics::Vehicle::SeriesMotorTractionForce(double dt) if (Vhyp > CtrlDelay / 2) // jesli czas oddzialywania przekroczony FuseOff(); // wywalanie bezpiecznika z powodu przetezenia silnikow - if ((DynamicBrakeType == dbrake_automatic || DynamicBrakeType == dbrake_switch) && DynamicBrakeFlag) + if ((brakes.electrodynamic.type == dbrake_automatic || brakes.electrodynamic.type == dbrake_switch) && brakes.electrodynamic.on) Itot = Im * 2; // 2x2 silniki w EP09 else if (TrainType == train_type::emu && Imin == IminLo && ScndS) // yBARC - boczniki na szeregu poprawnie Itot = Im; @@ -752,24 +752,24 @@ void physics::Vehicle::SeriesMotorDynamicBrake(double dt) { case 1: TUHEX_Sum = TUHEX_Sum1; - DynamicBrakeRes = DynamicBrakeRes1; + brakes.electrodynamic.resistance = brakes.electrodynamic.resistance1; break; case 2: TUHEX_Sum = TUHEX_Sum2; - DynamicBrakeRes = DynamicBrakeRes1; + brakes.electrodynamic.resistance = brakes.electrodynamic.resistance1; break; case 3: TUHEX_Sum = TUHEX_Sum3; - if (Vadd > 0.99 * TUHEX_MaxIw && DynamicBrakeRes == DynamicBrakeRes1) + if (Vadd > 0.99 * TUHEX_MaxIw && brakes.electrodynamic.resistance == brakes.electrodynamic.resistance1) TUHEX_ResChange = true; if (TUHEX_ResChange && Vadd < 0.5 * TUHEX_MaxIw) { TUHEX_ResChange = false; - DynamicBrakeRes = DynamicBrakeRes2; + brakes.electrodynamic.resistance = brakes.electrodynamic.resistance2; } break; default: - DynamicBrakeRes = DynamicBrakeRes1; + brakes.electrodynamic.resistance = brakes.electrodynamic.resistance1; TUHEX_Sum = 0; break; } @@ -780,10 +780,10 @@ void physics::Vehicle::SeriesMotorDynamicBrake(double dt) if (Vadd < TUHEX_MinIw) { Vadd = 0; - DynamicBrakeFlag = false; + brakes.electrodynamic.on = false; } } - else if (DynamicBrakeFlag && Vadd + abs(Im) < TUHEX_Sum - TUHEX_Diff) + else if (brakes.electrodynamic.on && Vadd + abs(Im) < TUHEX_Sum - TUHEX_Diff) { Vadd += 70.0 * dt; Vadd = std::min(std::max(Vadd, TUHEX_MinIw), TUHEX_MaxIw); @@ -1145,7 +1145,7 @@ void physics::Vehicle::InductionMotorBrakeBlending(double const ActiveInverters, { InductionMotorDynamicBrakeFlag(); auto const edBCP{brakes.distributor->GetEDBCP() * inductionMotor.braking.cylinderPressureGain}; // stala napedu - if (DynamicBrakeFlag) + if (brakes.electrodynamic.on) { PosRatio = InductionMotorBrakeRatio(ActiveInverters, edBCP); tmp = 5; @@ -1177,18 +1177,18 @@ void physics::Vehicle::InductionMotorDynamicBrakeFlag() auto const localbrakeactive{CabOccupied != 0 && brakes.independentValve->GetCP() > 0.25}; // gdy SplitEDPneumaticBrake jest aktywne, hamulec pomocniczy (LocalBrake) NIE wymusza // zalaczenia hamulca elektrodynamicznego - ED jest sterowany wlasnym nastawnikiem - auto const dynbrakectrlactive{SplitEDPneumaticBrake && DynamicBrakeRatio() > 0.01 && DynamicBrakeAvailable()}; - auto const localbrakeforED{SplitEDPneumaticBrake ? false : localbrakeactive}; + auto const dynbrakectrlactive{brakes.electrodynamic.splitFromPneumatic && DynamicBrakeRatio() > 0.01 && DynamicBrakeAvailable()}; + auto const localbrakeforED{brakes.electrodynamic.splitFromPneumatic ? false : localbrakeactive}; if (false == Doors.instances[VehicleSide::left].is_closed || false == Doors.instances[VehicleSide::right].is_closed || (Doors.permit_needed && (Doors.instances[VehicleSide::left].open_permit || Doors.instances[VehicleSide::right].open_permit))) { - DynamicBrakeFlag = true; + brakes.electrodynamic.on = true; } else if ((edBCP < 0.25 && false == localbrakeforED && false == dynbrakectrlactive && AnPos < 0.01) || (edBCP < 0.25 && ShuntModeAllow && false == dynbrakectrlactive && brakes.independentPosition < 0.01)) - DynamicBrakeFlag = false; + brakes.electrodynamic.on = false; else if (brakes.cylinderPressure > 0.25 && edBCP > 0.25 || localbrakeforED || AnPos > 0.02 || dynbrakectrlactive) - DynamicBrakeFlag = true; + brakes.electrodynamic.on = true; } // the share of the electrodynamic brake (negative), and the distributor told how much of the air to let out; none @@ -1220,7 +1220,7 @@ double physics::Vehicle::InductionMotorBrakeRatio(double const ActiveInverters, { // strefa wylaczenia ED (Vh0..Vh1) - mnoznik 0..1 zaleznie od predkosci double const vhRamp = std::max(0.0, std::min(1.0, (Vel - inductionMotor.braking.offSpeed) / (inductionMotor.braking.fullSpeed - inductionMotor.braking.offSpeed))); - if (SplitEDPneumaticBrake) + if (brakes.electrodynamic.splitFromPneumatic) { // w trybie split LocalBrake nie zaleca ED; uzywany jest DynamicBrakeCtrl // oraz zwykle zapotrzebowanie z hamulca zespolonego (edBCP) @@ -1241,12 +1241,12 @@ double physics::Vehicle::InductionMotorBrakeRatio(double const ActiveInverters, void physics::Vehicle::InductionMotorDrive(double dt) { double tmp; - if (DynamicBrakeFlag) + if (brakes.electrodynamic.on) tmp = inductionMotor.converter.brakingLinkVoltage; else tmp = inductionMotor.converter.maxLinkVoltage; - auto f_cfu{DynamicBrakeFlag ? inductionMotor.converter.brakingVoltsPerHertz : inductionMotor.converter.voltsPerHertz}; + auto f_cfu{brakes.electrodynamic.on ? inductionMotor.converter.brakingVoltsPerHertz : inductionMotor.converter.voltsPerHertz}; inductionMotor.state.linkVoltage = std::min(EngineVoltage - inductionMotor.converter.voltageDrop, tmp); inductionMotor.state.criticalFrequency = inductionMotor.state.linkVoltage / f_cfu; @@ -1347,7 +1347,7 @@ void physics::Vehicle::InductionMotorForceLimits() void physics::Vehicle::UpdateInverterFrequency() { auto const tmpV{std::abs(inductionMotor.state.supplyFrequency)}; - auto const useFFEDList = FFEDListSize > 0 && DynamicBrakeFlag; + auto const useFFEDList = FFEDListSize > 0 && brakes.electrodynamic.on; auto const list = useFFEDList ? FFEDlist : FFlist; if (auto const listSize = useFFEDList ? FFEDListSize : FFListSize; listSize > 0 && std::abs(inductionMotor.state.fieldCurrent) > 1.0 && tmpV > 0.0001) @@ -1437,7 +1437,7 @@ void physics::Vehicle::FuseOff(void) bool physics::Vehicle::UniversalResetButton(int const Button, range_t const Notify) { - if (auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; false == lowvoltagepower) + if (auto const lowvoltagepower{lowVoltage.power24vAvailable || lowVoltage.power110vAvailable}; false == lowvoltagepower) { return false; } @@ -1457,7 +1457,7 @@ bool physics::Vehicle::UniversalResetButton(int const Button, range_t const Noti bool physics::Vehicle::RelayReset(int const Relays, range_t const Notify) { - auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; + auto const lowvoltagepower{lowVoltage.power24vAvailable || lowVoltage.power110vAvailable}; bool reset{false}; if (TestFlag(Relays, relay_t::maincircuitground) && (EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric) && @@ -1651,8 +1651,8 @@ double physics::Vehicle::ShowCurrentP(int AmpN) const Grupowy = DelayCtrlFlag && TrainType == train_type::et22; // przerzucanie walu grupowego w ET22; Bn = RList[MainCtrlActualPos].Bn; // ile równoległych gałęzi silników - if (DynamicBrakeType == dbrake_automatic && DynamicBrakeFlag) - Bn = DynamicBrakeAmpmeters; + if (brakes.electrodynamic.type == dbrake_automatic && brakes.electrodynamic.on) + Bn = brakes.electrodynamic.ammeters; if (Power > 0.01) { if (AmpN > 0) // podać prąd w gałęzi diff --git a/physics/vehicle.h b/physics/vehicle.h index 45436c2ac..f10c8a038 100644 --- a/physics/vehicle.h +++ b/physics/vehicle.h @@ -29,6 +29,7 @@ http://mozilla.org/MPL/2.0/. #include "physics/components/devices.h" #include "physics/components/pantographs.h" #include "physics/components/maincircuit.h" +#include "physics/components/lowvoltage.h" class TractionDrive; @@ -645,12 +646,7 @@ class Vehicle double Power = 0.0; /*max. predkosc kontrukcyjna, masa wlasna, moc*/ double Mred = 0.0; /*Ra: zredukowane masy wirujące; potrzebne do obliczeń hamowania*/ double TotalMass = 0.0; /*wyliczane przez ComputeMass*/ - double HeatingPower = 0.0; - double EngineHeatingRPM{0.0}; // guaranteed engine revolutions with heating enabled double LightPower = 0.0; /*moc pobierana na ogrzewanie/oswietlenie*/ - double BatteryVoltage = 0.0; /*Winger - baterie w elektrykach*/ - bool Battery = false; /*Czy sa zalaczone baterie*/ - start_t BatteryStart = start_t::manual; bool EpFuse = true; /*Czy jest wlaczony hamulec EP*/ double EpForce = 0.0; /*Poziom zadanej sily EP*/ bool Signalling = false; /*Czy jest zalaczona sygnalizacja hamowania ostatniego wagonu*/ @@ -658,7 +654,6 @@ class Vehicle // the cut-off in the radio's power supply: a fuse in the cabinet, a lever on the desk or the switch on the radio's power // supply (eu07/maszyna#438). Closed unless the driver opens it, so vehicles without such a switch work as before bool RadioFuse = true; - float NominalBatteryVoltage = 0.f; /*Winger - baterie w elektrykach*/ TDimension Dim; /*wymiary*/ double Cx = 0.0; /*wsp. op. aerodyn.*/ float Floor = 0.96f; // poziom podłogi dla ładunków @@ -681,6 +676,8 @@ class Vehicle int wiperSwitchPos = 0; // pozycja przelacznika wycieraczek double WiperAngle = {45.0}; // kat pracy wycieraczek + LowVoltageSupply lowVoltage; // the battery and the low voltage circuits (physics/components/lowvoltage.h) + TrainHeating trainHeating; LineBreaker lineBreaker; // the main circuit (physics/components/maincircuit.h) LineContactors lineContactors; ProtectionRelays protection; @@ -695,10 +692,6 @@ class Vehicle int UniversalResetButtonFlag[3] = {0, 0, 0}; // customizable reset buttons assignments int TurboTest = 0; - bool batterySwAlreadyFired = false; // czy przycisk baterii juz zostal wcisniety - bool isBatteryButtonImpulse = false; // czy przelacznik baterii traktowac jako pojedynczy przycisk - bool shouldHoldBatteryButton = false; // czy nalezy przytrzymac przycisk baterii aby wlaczyc/wylaczyc baterie - float BatteryButtonHoldTime = 1.f; // minimalny czas przytrzymania przycisku baterii /*nastawniki:*/ int MainCtrlPosNo = 0; /*ilosc pozycji nastawnika*/ int ScndCtrlPosNo = 0; @@ -777,10 +770,6 @@ class Vehicle bool FieldShuntSwitch = false; bool CoupledCtrl = false; /*czy mainctrl i scndctrl sa sprzezone*/ bool HasCamshaft{false}; - int DynamicBrakeType = 0; /*patrz dbrake_**/ - int DynamicBrakeAmpmeters = 2; /*liczba amperomierzy przy hamowaniu ED*/ - bool SplitEDPneumaticBrake = false; /*czy hamulec ED i pneumatyczny pomocniczy są rozdzielone na osobne nastawniki*/ - int DynamicBrakeCtrlPosNo = 10; /*ilosc pozycji nastawnika hamulca ED (DBPN, domyslnie 10)*/ // the dynamic brake of a diesel-electric vehicle (Engine: EDBrake=...): the traction motors brake into resistors while // the engine runs, with the force of the definition rather than from a circuit, as the drive of these vehicles is // computed from the generator's power. no definition, no dynamic brake (MaSzyna-EU07/maszyna#82) @@ -804,9 +793,6 @@ class Vehicle double force{0.0}; // [N] the braking force, against the motion }; diesel_electric_dynamic_brake DEDynamicBrake; - double DynamicBrakeRes = 5.8; /*rezystancja oporników przy hamowaniu ED*/ - double DynamicBrakeRes1 = 5.8; /*rezystancja oporników przy hamowaniu ED - 1 tryb*/ - double DynamicBrakeRes2 = 5.8; /*rezystancja oporników przy hamowaniu ED - 2 tryb*/ double TUHEX_Sum = 750; /*nastawa sterownika hamowania ED - aktualna*/ double TUHEX_Diff = 10; /*histereza działania sterownika hamowania ED*/ double TUHEX_MinIw = 60; /*minimalny prąd wzbudzenia przy hamowaniu ED - wynika z chk silnika*/ @@ -859,9 +845,6 @@ class Vehicle /*- dla lokomotyw z silnikami indukcyjnymi -*/ // the drive of induction motors (physics/components/inductionmotor.h) InductionMotor inductionMotor; - int Imaxrpc = 0; // Maksymalny prad rezystora hamowania chlodzonego pasywnie - int BRVto = 0; // Czas jaki wentylatory jeszcze dodatkowo schladzaja rezystor - double BRVtimer = 0; // Timer dla podtrzymania wentylatora /*-dla wagonow*/ struct load_attributes @@ -915,9 +898,6 @@ class Vehicle // (vehicle_table::update_coupler_physics()); with couplerphysics all in eu07.ini every vehicle is covered bool CouplerPhysics{false}; ByEnd Neighbours; // potential collision sources - bool Power110vIsAvailable = false; // cached availability of 110v power - bool Power24vIsAvailable = false; // cached availability of 110v power - double Power24vVoltage{0.0}; // cached battery voltage bool EventFlag = false; /*!o true jesli cos nietypowego sie wydarzy*/ int SoundFlag = 0; /*!o patrz stale sound_ */ int AIFlag{0}; // HACK: events of interest for consist owner @@ -957,7 +937,6 @@ class Vehicle bool SandDoseAutoAllow = true; /*zezwolenie na automatyczne piaskowanie*/ double Sand = 0.0; /*ilosc piasku*/ /*! przyrosty cisnienia w kroku czasowym*/ - bool BRVentilators = false; /* Czy rezystor hamowania pracuje */ fuel_pump FuelPump; oil_pump OilPump; genset_device Genset; // of a dual-mode vehicle, fitted() only with GensetPower @@ -973,14 +952,9 @@ class Vehicle float DoorsOpenWithPermitAfter{-1.f}; // remote open if permit button is held for specified time. NOTE: separate from door data as its cab control thing int DoorsPermitLightBlinking{0}; // when the doors permit signal light is blinking - double DynamicBrakeCtrlPos = 0.0; /*nastawa nastawnika hamulca elektrodynamicznego (0..1) - aktywne tylko gdy SplitEDPneumaticBrake*/ /* */ bool RadioStopFlag = false; /*hamowanie nagle*/ - // the AI wagon inspector cut the brake out (b_dmg) and puts it back when the train no longer needs it - // cut out (brake_setting::apply). Anyone else cutting it out or putting it back takes it over - bool DynamicBrakeFlag = false; /*czy wlaczony hamulec elektrodymiczny*/ - bool DynamicBrakeEMUStatus = true; /*czy hamulec ED dziala w ezt*/ int TUHEX_StageActual = 0; /*aktualny stopien tuhexa*/ bool TUHEX_ResChange = false; /*czy zmiana rezystancji hamowania ED - odwzbudzanie*/ bool TUHEX_Active = false; /*czy hamowanie ED wywołane z zewnątrz*/ @@ -1100,10 +1074,7 @@ class Vehicle bool DoorRightOpened = false; double DoorRightOpenTimer{-1.0}; // right door closing timer for automatic door type #endif - bool HeatingSwitchImpulse{false}; // the train heating switch springs back to its middle position - bool Heating = false; // ogrzewanie 'Winger 020304 - bool HeatingAllow{false}; // heating switch // TODO: wrap heating in a basic device int DoubleTr = 1; // trakcja ukrotniona - przedni pojazd 'Winger 160304 basic_light CompartmentLights; @@ -1265,7 +1236,7 @@ class Vehicle bool EIMDirectionChangeAllow(void) const; inline double IsVehicleEIMBrakingFactor() const { - return DynamicBrakeFlag && ResistorsFlag ? 0.0 : inductionMotor.state.lineCurrent < 0 ? -1.0 : 1.0; + return brakes.electrodynamic.on && ResistorsFlag ? 0.0 : inductionMotor.state.lineCurrent < 0 ? -1.0 : 1.0; } void BrakeLevelSet(double b); bool BrakeLevelAdd(double b); @@ -1607,7 +1578,7 @@ class Vehicle // whether the radio is switched on, its power supply isn't cut off and it has the low voltage to work bool RadioPowered() const { - return Radio && RadioFuse && (Power24vIsAvailable || Power110vIsAvailable); + return Radio && RadioFuse && (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable); } /*obrot kol uwzgledniajacy poslizg*/ double ComputeRotatingWheel(double WForce, double dt, double n) const; diff --git a/rendering/lightarray.cpp b/rendering/lightarray.cpp index 8e9b561ff..33c5415f4 100644 --- a/rendering/lightarray.cpp +++ b/rendering/lightarray.cpp @@ -52,8 +52,8 @@ light_array::update() { light.direction.z = -light.direction.z; } // determine intensity of this light set - if( ( true == light.owner->physics->Power24vIsAvailable ) - || ( true == light.owner->physics->Power110vIsAvailable ) ) { + if( ( true == light.owner->physics->lowVoltage.power24vAvailable ) + || ( true == light.owner->physics->lowVoltage.power110vAvailable ) ) { // with power on, the intensity depends on the state of activated switches // first we cross-check the list of enabled lights with the lights installed in the vehicle... auto const lights { light.owner->physics->iLights[ light.index ] & light.owner->LightList( static_cast( light.index ) ) }; diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index fe22a6964..7af23b625 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -73,13 +73,13 @@ blackbox::driver driver_of(TDynamicObject const &Vehicle) { std::uint32_t devices_of(physics::Vehicle const &Occupied, physics::Vehicle const &Controlling) { namespace device = blackbox::cab_devices; auto const on{[](bool const State, std::uint32_t const Bit) { return State ? Bit : 0u; }}; - return on(Occupied.Battery || Controlling.Battery, device::battery) | on(Controlling.lineBreaker.closed, device::main_breaker) | + return on(Occupied.lowVoltage.batteryOn || Controlling.lowVoltage.batteryOn, device::battery) | on(Controlling.lineBreaker.closed, device::main_breaker) | on(Controlling.pantographs[VehicleEnd::front].is_active, device::pantograph_front) | on(Controlling.pantographs[VehicleEnd::rear].is_active, device::pantograph_rear) | on(Controlling.converter.running, device::converter) | on(Controlling.air.compressor.running, device::compressor) | on(Controlling.lineContactors.closed, device::line_contactors) | on(Controlling.FuseFlag, device::overload_relay) | on(Controlling.SandDose, device::sanding) | on(Occupied.WarningSignal != 0, device::horn) | on(false == Occupied.Doors.instances[VehicleSide::left].is_closed, device::doors_left) | on(false == Occupied.Doors.instances[VehicleSide::right].is_closed, device::doors_right) | on(Occupied.Radio, device::radio) | - on(Controlling.Heating, device::heating) | on(Occupied.brakes.spring.isActive, device::spring_brake) | on(Controlling.ShuntMode, device::shunt_mode) | + on(Controlling.trainHeating.on, device::heating) | on(Occupied.brakes.spring.isActive, device::spring_brake) | on(Controlling.ShuntMode, device::shunt_mode) | // the doors as the cab works them: the permits, the departure signal, the steps and the lock on(Occupied.DepartureSignal, device::departure_signal) | on(Occupied.Doors.instances[VehicleSide::left].open_permit, device::door_permit_left) | on(Occupied.Doors.instances[VehicleSide::right].open_permit, device::door_permit_right) | on(Occupied.Doors.step_enabled, device::door_step) | diff --git a/tests/unit/golden.cpp b/tests/unit/golden.cpp index 36d6010bc..e1769511c 100644 --- a/tests/unit/golden.cpp +++ b/tests/unit/golden.cpp @@ -68,7 +68,7 @@ std::vector traction() { {"enrot", [](auto const &M) { return M.enrot; }}, {"dizel_fill", [](auto const &M) { return M.diesel.fill; }}, {"eimv_pr", [](auto const &M) { return M.inductionMotor.forceShare; }}, - {"DynamicBrakeFlag", [](auto const &M) { return M.DynamicBrakeFlag ? 1.0 : 0.0; }}, + {"DynamicBrakeFlag", [](auto const &M) { return M.brakes.electrodynamic.on ? 1.0 : 0.0; }}, }; } @@ -133,9 +133,9 @@ std::vector parameters() { {"TotalMass", [](auto const &M) { return M.TotalMass; }}, {"Mred", [](auto const &M) { return M.Mred; }}, {"Power", [](auto const &M) { return M.Power; }}, - {"HeatingPower", [](auto const &M) { return M.HeatingPower; }}, + {"HeatingPower", [](auto const &M) { return M.trainHeating.power; }}, {"LightPower", [](auto const &M) { return M.LightPower; }}, - {"BatteryVoltage", [](auto const &M) { return M.BatteryVoltage; }}, + {"BatteryVoltage", [](auto const &M) { return M.lowVoltage.batteryVoltage; }}, {"Cx", [](auto const &M) { return M.Cx; }}, {"WheelDiameter", [](auto const &M) { return M.WheelDiameter; }}, {"TrackW", [](auto const &M) { return M.TrackW; }}, diff --git a/tests/unit/invariants.cpp b/tests/unit/invariants.cpp index c0141c5ca..1942c476a 100644 --- a/tests/unit/invariants.cpp +++ b/tests/unit/invariants.cpp @@ -42,13 +42,13 @@ std::vector const &invariants() { {"every value a number", [](auto const &M, double, auto const *) { std::initializer_list const values{M.V, M.AccS, M.Ft, M.Fb, M.Im, M.Itot, M.EngineVoltage, - M.enrot, M.brakePipe.pressure, M.brakes.cylinderPressure, M.brakes.independentCylinderPressure, M.mainPipe.pressure, M.air.mainReservoirPressure, M.BatteryVoltage}; + M.enrot, M.brakePipe.pressure, M.brakes.cylinderPressure, M.brakes.independentCylinderPressure, M.mainPipe.pressure, M.air.mainReservoirPressure, M.lowVoltage.batteryVoltage}; return std::ranges::all_of(values, [](double const Value) { return std::isfinite(Value); }); }, [](auto const &M) { return values({{"V", M.V}, {"AccS", M.AccS}, {"Ft", M.Ft}, {"Fb", M.Fb}, {"Im", M.Im}, {"Itot", M.Itot}, {"EngineVoltage", M.EngineVoltage}, {"enrot", M.enrot}, {"PipePress", M.brakePipe.pressure}, {"BrakePress", M.brakes.cylinderPressure}, {"LocBrakePress", M.brakes.independentCylinderPressure}, - {"ScndPipePress", M.mainPipe.pressure}, {"Compressor", M.air.mainReservoirPressure}, {"BatteryVoltage", M.BatteryVoltage}}); + {"ScndPipePress", M.mainPipe.pressure}, {"Compressor", M.air.mainReservoirPressure}, {"BatteryVoltage", M.lowVoltage.batteryVoltage}}); }}, {"brake cylinders between empty and the vehicle's highest pressure", [](auto const &M, double, auto const *) { @@ -75,10 +75,10 @@ std::vector const &invariants() { {"no motor current with the line contactors open, but for the dynamic brake", [](auto const &M, double, auto const *) { // the dynamic brake closes its own circuit of the motors and the resistors - return M.lineContactors.closed || M.DynamicBrakeFlag || M.EngineType != TEngineType::ElectricSeriesMotor || std::abs(M.Im) < 1.0; + return M.lineContactors.closed || M.brakes.electrodynamic.on || M.EngineType != TEngineType::ElectricSeriesMotor || std::abs(M.Im) < 1.0; }, [](auto const &M) { - return values({{"StLinFlag", M.lineContactors.closed}, {"DynamicBrakeFlag", M.DynamicBrakeFlag}, {"Im", M.Im}, {"MainCtrlActualPos", M.MainCtrlActualPos}}); + return values({{"StLinFlag", M.lineContactors.closed}, {"DynamicBrakeFlag", M.brakes.electrodynamic.on}, {"Im", M.Im}, {"MainCtrlActualPos", M.MainCtrlActualPos}}); }}, {"no tractive force without power", [](auto const &M, double, auto const *) { return M.Power >= 0.01 || std::abs(M.Ft) < 1.0; }, @@ -93,8 +93,8 @@ std::vector const &invariants() { }, [](auto const &M) { return values({{"enrot", M.enrot}, {"dizel_nmax", M.diesel.maxRevolutions}}); }}, {"battery no higher than its nominal voltage", - [](auto const &M, double, auto const *) { return M.NominalBatteryVoltage <= 0.0 || M.BatteryVoltage <= 1.05 * M.NominalBatteryVoltage; }, - [](auto const &M) { return values({{"BatteryVoltage", M.BatteryVoltage}, {"NominalBatteryVoltage", M.NominalBatteryVoltage}}); }}, + [](auto const &M, double, auto const *) { return M.lowVoltage.nominalBatteryVoltage <= 0.0 || M.lowVoltage.batteryVoltage <= 1.05 * M.lowVoltage.nominalBatteryVoltage; }, + [](auto const &M) { return values({{"BatteryVoltage", M.lowVoltage.batteryVoltage}, {"NominalBatteryVoltage", M.lowVoltage.nominalBatteryVoltage}}); }}, {"distance counted as the speed runs", [](auto const &M, double Time, auto const *Before) { if (Before == nullptr) { diff --git a/tests/unit/test_auxiliaries.cpp b/tests/unit/test_auxiliaries.cpp index de33f2ffb..6334179c8 100644 --- a/tests/unit/test_auxiliaries.cpp +++ b/tests/unit/test_auxiliaries.cpp @@ -14,10 +14,10 @@ namespace { std::vector auxiliaries() { return { - {"BatteryVoltage", [](auto const &M) { return M.BatteryVoltage; }}, - {"Battery", [](auto const &M) { return M.Battery ? 1.0 : 0.0; }}, + {"BatteryVoltage", [](auto const &M) { return M.lowVoltage.batteryVoltage; }}, + {"Battery", [](auto const &M) { return M.lowVoltage.batteryOn ? 1.0 : 0.0; }}, {"ConverterFlag", [](auto const &M) { return M.converter.running ? 1.0 : 0.0; }}, - {"Power110vIsAvailable", [](auto const &M) { return M.Power110vIsAvailable ? 1.0 : 0.0; }}, + {"Power110vIsAvailable", [](auto const &M) { return M.lowVoltage.power110vAvailable ? 1.0 : 0.0; }}, {"PantPress", [](auto const &M) { return M.pantographAir.pressure; }}, {"PantVolume", [](auto const &M) { return M.pantographAir.volume; }}, {"PantCompFlag", [](auto const &M) { return M.pantographAir.compressorRunning ? 1.0 : 0.0; }}, @@ -35,21 +35,21 @@ TEST_CASE("auxiliaries: the battery drained by the lights and the pantographs' c scenario.add("4e_v1/4e", 1); REQUIRE(scenario.start_up()); auto &eu07{scenario.cab()}; - REQUIRE(eu07.BatteryVoltage == doctest::Approx(eu07.NominalBatteryVoltage)); + REQUIRE(eu07.lowVoltage.batteryVoltage == doctest::Approx(eu07.lowVoltage.nominalBatteryVoltage)); scenario.act("converter off, lights on, small compressor on"); eu07.ConverterSwitch(false); eu07.iLights[VehicleEnd::front] = 1 | 2 | 4; eu07.iLights[VehicleEnd::rear] = 16; eu07.pantographAir.compressorRunning = true; scenario.wait(30.0); - CHECK(eu07.BatteryVoltage < 0.83 * eu07.NominalBatteryVoltage); + CHECK(eu07.lowVoltage.batteryVoltage < 0.83 * eu07.lowVoltage.nominalBatteryVoltage); CHECK(eu07.lineBreaker.closed); scenario.wait(5000.0); - CHECK(eu07.BatteryVoltage < eu07.NominalBatteryVoltage / 1.57); + CHECK(eu07.lowVoltage.batteryVoltage < eu07.lowVoltage.nominalBatteryVoltage / 1.57); CHECK_FALSE(eu07.lineBreaker.closed); scenario.act("start up again"); CHECK_FALSE(scenario.start_up()); - CHECK(eu07.BatteryVoltage < eu07.NominalBatteryVoltage / 1.57); + CHECK(eu07.lowVoltage.batteryVoltage < eu07.lowVoltage.nominalBatteryVoltage / 1.57); scenario.check(); } @@ -61,20 +61,20 @@ TEST_CASE("auxiliaries: the battery switched off, and charged by the converter") scenario.act("converter off"); eu07.ConverterSwitch(false); scenario.wait(10.0); - auto const discharged{eu07.BatteryVoltage}; - CHECK(discharged < 0.83 * eu07.NominalBatteryVoltage); + auto const discharged{eu07.lowVoltage.batteryVoltage}; + CHECK(discharged < 0.83 * eu07.lowVoltage.nominalBatteryVoltage); // the converter charges it back at once scenario.act("converter on"); eu07.ConverterSwitch(true); scenario.wait(10.0); - CHECK(eu07.BatteryVoltage == doctest::Approx(eu07.NominalBatteryVoltage)); + CHECK(eu07.lowVoltage.batteryVoltage == doctest::Approx(eu07.lowVoltage.nominalBatteryVoltage)); // switched off, the battery falls to 90 V at once, then holds scenario.act("battery off"); eu07.MainSwitch(false); eu07.ConverterSwitch(false); eu07.BatterySwitch(false); scenario.wait(10.0); - CHECK(eu07.BatteryVoltage == doctest::Approx(discharged).epsilon(0.01)); + CHECK(eu07.lowVoltage.batteryVoltage == doctest::Approx(discharged).epsilon(0.01)); scenario.check(); } diff --git a/tests/unit/test_cab.cpp b/tests/unit/test_cab.cpp index b76911c5e..2cbb7096d 100644 --- a/tests/unit/test_cab.cpp +++ b/tests/unit/test_cab.cpp @@ -68,7 +68,7 @@ TEST_CASE("cab: the engine's idle speed, and the ET42's second controller shown vehicle et42{definition::fiz("et42_v2/112e-a")}; CHECK(et42->GetVirtualScndPos() == 0); - et42->DynamicBrakeFlag = true; + et42->brakes.electrodynamic.on = true; CHECK(et42->GetVirtualScndPos() == -1); et42->ScndCtrlPos = 1; CHECK(et42->GetVirtualScndPos() == 1); @@ -91,9 +91,9 @@ TEST_CASE("cab: the controller of the electrodynamic brake apart from the local CHECK_FALSE(eu47.IncDynamicBrakeLevel(1.f)); CHECK(eu47.DynamicBrakeRatio() == doctest::Approx(0.0)); - scenario.train()[0].physics().SplitEDPneumaticBrake = true; + scenario.train()[0].physics().brakes.electrodynamic.splitFromPneumatic = true; REQUIRE(scenario.start_up()); - REQUIRE(eu47.DynamicBrakeCtrlPosNo == 10); + REQUIRE(eu47.brakes.electrodynamic.controllerPositions == 10); CHECK(eu47.DynamicBrakeAvailable()); scenario.act("dynamic brake up"); for (int i = 0; i < 5; ++i) { @@ -101,7 +101,7 @@ TEST_CASE("cab: the controller of the electrodynamic brake apart from the local } CHECK(eu47.DynamicBrakeRatio() == doctest::Approx(0.5)); scenario.wait(10.0); - CHECK(eu47.DynamicBrakeFlag); + CHECK(eu47.brakes.electrodynamic.on); CHECK(eu47.Im < -50.0); CHECK(eu47.brakes.cylinderPressure < 0.1); scenario.act("dynamic brake full"); diff --git a/tests/unit/test_commands.cpp b/tests/unit/test_commands.cpp index 0fc6ea4c5..58ad83fa3 100644 --- a/tests/unit/test_commands.cpp +++ b/tests/unit/test_commands.cpp @@ -32,7 +32,7 @@ std::vector state() { {"eimic_real", [](auto const &M) { return M.eimic_real; }}, {"TUHEX_StageActual", [](auto const &M) { return M.TUHEX_StageActual; }}, {"TUHEX_Active", [](auto const &M) { return flag(M.TUHEX_Active); }}, - {"DynamicBrakeEMUStatus", [](auto const &M) { return flag(M.DynamicBrakeEMUStatus); }}, + {"DynamicBrakeEMUStatus", [](auto const &M) { return flag(M.brakes.electrodynamic.emuWorking); }}, {"BrakeReleaser", [](auto const &M) { return flag(M.brakes.distributor->Releaser()); }}, {"WaterPumpBreaker", [](auto const &M) { return flag(M.WaterPump.breaker); }}, {"WaterPumpEnabled", [](auto const &M) { return flag(M.WaterPump.is_enabled); }}, @@ -47,14 +47,14 @@ std::vector state() { {"CompartmentLightsEnabled", [](auto const &M) { return flag(M.CompartmentLights.is_enabled); }}, {"CompartmentLightsDisabled", [](auto const &M) { return flag(M.CompartmentLights.is_disabled); }}, {"MainSwitch", [](auto const &M) { return flag(M.lineBreaker.closed); }}, - {"Heating", [](auto const &M) { return flag(M.Heating); }}, + {"Heating", [](auto const &M) { return flag(M.trainHeating.on); }}, {"DirActive", [](auto const &M) { return M.DirActive; }}, {"DirAbsolute", [](auto const &M) { return M.DirAbsolute; }}, {"CabActive", [](auto const &M) { return M.CabActive; }}, {"CabMaster", [](auto const &M) { return flag(M.CabMaster); }}, {"AutoRelayFlag", [](auto const &M) { return flag(M.AutoRelayFlag); }}, {"ConverterAllow", [](auto const &M) { return flag(M.converter.allow); }}, - {"Battery", [](auto const &M) { return flag(M.Battery); }}, + {"Battery", [](auto const &M) { return flag(M.lowVoltage.batteryOn); }}, {"CompressorAllow", [](auto const &M) { return flag(M.air.compressor.allow); }}, {"CompressorListPos", [](auto const &M) { return M.air.compressor.listPosition; }}, {"DoorLock", [](auto const &M) { return flag(M.Doors.lock_enabled); }}, diff --git a/tests/unit/test_compartment_lights.cpp b/tests/unit/test_compartment_lights.cpp index bff60e440..917618544 100644 --- a/tests/unit/test_compartment_lights.cpp +++ b/tests/unit/test_compartment_lights.cpp @@ -20,32 +20,32 @@ void lights_check(vehicle &Car) { TEST_CASE("compartment lights: the lights need low voltage power and the switch") { vehicle car{definition::fiz("elf_v1/21we-a")}; REQUIRE(car->CompartmentLights.start_type == start_t::manual); - car->Power24vIsAvailable = false; - car->Power110vIsAvailable = false; + car->lowVoltage.power24vAvailable = false; + car->lowVoltage.power110vAvailable = false; car->CompartmentLightsSwitch(true, range_t::local); // switch on, no power lights_check(car); CHECK_FALSE(car->CompartmentLights.is_active); - car->Power110vIsAvailable = true; // converter on + car->lowVoltage.power110vAvailable = true; // converter on lights_check(car); CHECK(car->CompartmentLights.is_active); CHECK(car->CompartmentLights.intensity == doctest::Approx(1.0)); - car->Power110vIsAvailable = false; // battery only: the lights stay on, dimmed - car->Power24vIsAvailable = true; + car->lowVoltage.power110vAvailable = false; // battery only: the lights stay on, dimmed + car->lowVoltage.power24vAvailable = true; lights_check(car); CHECK(car->CompartmentLights.is_active); CHECK(car->CompartmentLights.intensity == doctest::Approx(0.5)); - car->Power24vIsAvailable = false; // no power at all + car->lowVoltage.power24vAvailable = false; // no power at all lights_check(car); CHECK_FALSE(car->CompartmentLights.is_active); } TEST_CASE("compartment lights: the off switch turns the lights off, the on switch back on") { vehicle car{definition::fiz("elf_v1/21we-a")}; - car->Power110vIsAvailable = true; + car->lowVoltage.power110vAvailable = true; lights_check(car); CHECK_FALSE(car->CompartmentLights.is_active); // manual start: off until switched on @@ -68,13 +68,13 @@ TEST_CASE("compartment lights: the off switch turns the lights off, the on switc TEST_CASE("compartment lights: lights started automatically come on with the power alone") { vehicle car{definition::fiz("elf_v1/21we-a").set("Cntrl", "CompartmentLightsStart", "Automatic")}; REQUIRE(car->CompartmentLights.start_type == start_t::automatic); - car->Power24vIsAvailable = false; - car->Power110vIsAvailable = false; + car->lowVoltage.power24vAvailable = false; + car->lowVoltage.power110vAvailable = false; lights_check(car); CHECK_FALSE(car->CompartmentLights.is_active); - car->Power110vIsAvailable = true; + car->lowVoltage.power110vAvailable = true; lights_check(car); CHECK(car->CompartmentLights.is_active); } diff --git a/tests/unit/test_compartment_lights_switch.cpp b/tests/unit/test_compartment_lights_switch.cpp index b9ba78398..8bc096c5d 100644 --- a/tests/unit/test_compartment_lights_switch.cpp +++ b/tests/unit/test_compartment_lights_switch.cpp @@ -117,7 +117,7 @@ void toggle(vehicle &Car, cab_controls const &Cab) { // the Elf (21WE-a), its compartment lights started by hand, with the converter running void power_up(vehicle &Car) { REQUIRE(Car->CompartmentLights.start_type == start_t::manual); - Car->Power110vIsAvailable = true; + Car->lowVoltage.power110vAvailable = true; lights_check(Car); REQUIRE_FALSE(Car->CompartmentLights.is_active); } diff --git a/tests/unit/test_compressor.cpp b/tests/unit/test_compressor.cpp index e65935672..13e667ceb 100644 --- a/tests/unit/test_compressor.cpp +++ b/tests/unit/test_compressor.cpp @@ -89,7 +89,7 @@ TEST_CASE("compressor: a compressor fed from the low voltage waits from the low run_compressor(vehicle, 10.0); REQUIRE_FALSE(vehicle->air.compressor.running); - vehicle->Power110vIsAvailable = true; + vehicle->lowVoltage.power110vAvailable = true; run_compressor(vehicle, 4.9); CHECK_FALSE(vehicle->air.compressor.running); run_compressor(vehicle, 0.2); @@ -178,15 +178,15 @@ TEST_CASE("compressor: fed from the converter it waits for the converter start d REQUIRE(loco->converter.startDelay == doctest::Approx(30.0)); loco.run(1.0); // engine off - CHECK_FALSE(loco->Power110vIsAvailable); + CHECK_FALSE(loco->lowVoltage.power110vAvailable); loco->lineBreaker.closed = true; // engine started loco.run(25.0); - CHECK_FALSE(loco->Power110vIsAvailable); + CHECK_FALSE(loco->lowVoltage.power110vAvailable); CHECK_FALSE(loco->air.compressor.running); loco.run(10.0); - CHECK(loco->Power110vIsAvailable); + CHECK(loco->lowVoltage.power110vAvailable); CHECK(loco->air.compressor.running); } @@ -197,7 +197,7 @@ TEST_CASE("compressor: fed from the converter the start delay counts from the co loco.run(1.0); // engine off loco->lineBreaker.closed = true; // engine started loco.run(25.0); - REQUIRE(loco->Power110vIsAvailable); // the converter is up + REQUIRE(loco->lowVoltage.power110vAvailable); // the converter is up CHECK_FALSE(loco->air.compressor.running); // but the compressor waits for its own delay as well loco.run(10.0); diff --git a/tests/unit/test_controls.cpp b/tests/unit/test_controls.cpp index 203624d5a..a7f73561d 100644 --- a/tests/unit/test_controls.cpp +++ b/tests/unit/test_controls.cpp @@ -456,13 +456,13 @@ TEST_CASE("controls: train heating from the locomotive") { scenario.act("heating on"); cab.HeatingSwitch(true); scenario.wait(30.0); - CHECK(cab.Heating); - CHECK(scenario.vehicle(2).Heating); + CHECK(cab.trainHeating.on); + CHECK(scenario.vehicle(2).trainHeating.on); scenario.act("heating off"); cab.HeatingSwitch(false); scenario.wait(10.0); - CHECK_FALSE(cab.Heating); - CHECK_FALSE(scenario.vehicle(2).Heating); + CHECK_FALSE(cab.trainHeating.on); + CHECK_FALSE(scenario.vehicle(2).trainHeating.on); scenario.check(); } @@ -552,11 +552,11 @@ TEST_CASE("controls: the automatic electrodynamic brake of the EP09, in service scenario.add("bdhpumn_v3/bdhpumn", 0, test::consist::full_coupling, 120.0); REQUIRE(scenario.start_up()); auto &ep09{scenario.cab()}; - REQUIRE(ep09.Power110vIsAvailable); + REQUIRE(ep09.lowVoltage.power110vAvailable); scenario.act(std::string{"brake "} + name); ep09.BrakeLevelSet(ep09.brakes.driverValve->GetPos(bh_MB) + steps); scenario.wait(10.0); - CHECK(ep09.DynamicBrakeFlag); + CHECK(ep09.brakes.electrodynamic.on); CHECK(ep09.Im < -100.0); CHECK(ep09.brakes.cylinderPressure < 0.25 * ep09.brakes.distributor->GetEDBCP()); scenario.wait(110.0); @@ -564,7 +564,7 @@ TEST_CASE("controls: the automatic electrodynamic brake of the EP09, in service // less than 2.1 bar, though the motors give nothing; a stronger application drops it before the stop CHECK(ep09.Vel == doctest::Approx(0.0)); CHECK(ep09.Im == doctest::Approx(0.0)); - CHECK(ep09.DynamicBrakeFlag == (ep09.brakes.cylinderPressure <= 2.1)); + CHECK(ep09.brakes.electrodynamic.on == (ep09.brakes.cylinderPressure <= 2.1)); CHECK(ep09.brakes.cylinderPressure == doctest::Approx(ep09.brakes.distributor->GetEDBCP()).epsilon(0.05)); scenario.act("release"); ep09.BrakeLevelSet(ep09.brakes.driverValve->GetPos(bh_RP)); @@ -601,7 +601,7 @@ TEST_CASE("controls: the automatic electrodynamic brake under ep and service bra scenario.wait(Seconds); }}; brake("ep brake", cab.brakes.driverValve->GetPos(bh_EPB), 15.0); - CHECK(cab.DynamicBrakeFlag == epelectric); + CHECK(cab.brakes.electrodynamic.on == epelectric); CHECK((cab.Im < -100.0) == epelectric); brake("ep hold", cab.brakes.driverValve->GetPos(bh_EPN), 5.0); brake("first step", cab.brakes.driverValve->GetPos(bh_MB), 20.0); diff --git a/tests/unit/test_drivingaid.cpp b/tests/unit/test_drivingaid.cpp index a8ef7ffa0..9a4cbdea9 100644 --- a/tests/unit/test_drivingaid.cpp +++ b/tests/unit/test_drivingaid.cpp @@ -46,8 +46,8 @@ test::track const line{0.15, 0.0, test::catenary_3kv}; TEST_CASE("driving aid: the Vectron's ED lever shows as a negative throttle step, and its ED braking") { vehicle vectron{definition::fiz("vectron_v1/wariant_7w"), 80.0 /* km/h */, "vectron", 1}; - REQUIRE(vectron->SplitEDPneumaticBrake); - REQUIRE(vectron->DynamicBrakeCtrlPosNo == 15); + REQUIRE(vectron->brakes.electrodynamic.splitFromPneumatic); + REQUIRE(vectron->brakes.electrodynamic.controllerPositions == 15); REQUIRE(vectron->EIMCtrlType == 0); // lever at zero: the master controller, as before, and no ED braking @@ -79,7 +79,7 @@ TEST_CASE("driving aid: the Vectron's ED lever shows as a negative throttle step TEST_CASE("driving aid: the Traxx's ED braking from its master controller") { vehicle traxx{definition::fiz("e186_v2/eu47"), 80.0 /* km/h */, "traxx", 1}; REQUIRE(traxx->EIMCtrlType == 1); - REQUIRE_FALSE(traxx->SplitEDPneumaticBrake); + REQUIRE_FALSE(traxx->brakes.electrodynamic.splitFromPneumatic); CHECK_FALSE(read(traxx, lever_cab).ed_percent.has_value()); // B+: the braking demand ramps towards full diff --git a/tests/unit/test_dynamic_brake_diesel.cpp b/tests/unit/test_dynamic_brake_diesel.cpp index 165343583..a5ed0ece1 100644 --- a/tests/unit/test_dynamic_brake_diesel.cpp +++ b/tests/unit/test_dynamic_brake_diesel.cpp @@ -22,9 +22,9 @@ std::vector dynamic_brake() { return { {"EDLevel", [](auto const &M) { return M.DEDynamicBrake.level; }}, {"EDForce", [](auto const &M) { return M.DEDynamicBrake.force; }}, - {"DynamicBrakeFlag", [](auto const &M) { return M.DynamicBrakeFlag ? 1.0 : 0.0; }}, + {"DynamicBrakeFlag", [](auto const &M) { return M.brakes.electrodynamic.on ? 1.0 : 0.0; }}, {"eimic_real", [](auto const &M) { return M.eimic_real; }}, - {"DynamicBrakeCtrlPos", [](auto const &M) { return M.DynamicBrakeCtrlPos; }}, + {"DynamicBrakeCtrlPos", [](auto const &M) { return M.brakes.electrodynamic.controllerPosition; }}, }; } @@ -86,7 +86,7 @@ TEST_CASE("diesel-electric dynamic brake: none without its definition") { scenario.wait(15.0); CHECK(locomotive.eimic_real == doctest::Approx(-1.0)); CHECK(locomotive.Ft == doctest::Approx(0.0)); - CHECK_FALSE(locomotive.DynamicBrakeFlag); + CHECK_FALSE(locomotive.brakes.electrodynamic.on); // coasting: braking with the power of the resistors above, it would lose more than 30 km/h CHECK(locomotive.Vel > speed - 12.0); scenario.check(); @@ -112,7 +112,7 @@ TEST_CASE("diesel-electric dynamic brake: the BR285's controller") { scenario.wait(10.0); CHECK(locomotive.eimic_real == doctest::Approx(-1.0)); CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); - CHECK(locomotive.DynamicBrakeFlag); + CHECK(locomotive.brakes.electrodynamic.on); REQUIRE(locomotive.Vel > 6.0); CHECK(-locomotive.Ft == doctest::Approx(br285_limit(locomotive)).epsilon(0.01)); CHECK(locomotive.Im > 0.0); @@ -151,7 +151,7 @@ TEST_CASE("diesel-electric dynamic brake: the BR285's controller") { scenario.wait(1.0); } CHECK(locomotive.Ft == doctest::Approx(0.0)); - CHECK_FALSE(locomotive.DynamicBrakeFlag); + CHECK_FALSE(locomotive.brakes.electrodynamic.on); // it doesn't hold the train: the air brake does CHECK(locomotive.Vel > 0.1); scenario.check(); @@ -165,8 +165,8 @@ TEST_CASE("diesel-electric dynamic brake: a resistor brake with its own lever") scenario.train().add(st44_braking(), 1); auto &locomotive{scenario.cab()}; REQUIRE(locomotive.DEDynamicBrake.source == physics::Vehicle::diesel_electric_dynamic_brake::control::lever); - CHECK(locomotive.SplitEDPneumaticBrake); - CHECK(locomotive.DynamicBrakeCtrlPosNo == 8); + CHECK(locomotive.brakes.electrodynamic.splitFromPneumatic); + CHECK(locomotive.brakes.electrodynamic.controllerPositions == 8); REQUIRE(scenario.start_up()); scenario.get_going(); scenario.full_power(90.0); @@ -178,19 +178,19 @@ TEST_CASE("diesel-electric dynamic brake: a resistor brake with its own lever") // the master controller at a power position keeps it off CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(0.0)); CHECK(locomotive.Ft > 0.0); - CHECK_FALSE(locomotive.DynamicBrakeFlag); + CHECK_FALSE(locomotive.brakes.electrodynamic.on); scenario.act("power off"); scenario.notch_back(0); scenario.wait(4.0); CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); - CHECK(locomotive.DynamicBrakeFlag); + CHECK(locomotive.brakes.electrodynamic.on); CHECK(-locomotive.Ft == doctest::Approx(st44_limit(locomotive)).epsilon(0.01)); CHECK(locomotive.ShowCurrent(0) > 0.0); scenario.act("half the lever"); locomotive.DecDynamicBrakeLevel(4.0f); - CHECK(locomotive.DynamicBrakeCtrlPos == doctest::Approx(0.5)); + CHECK(locomotive.brakes.electrodynamic.controllerPosition == doctest::Approx(0.5)); for (int i = 0; i < 300 && locomotive.Vel > 20.0; ++i) { scenario.wait(1.0); } @@ -204,7 +204,7 @@ TEST_CASE("diesel-electric dynamic brake: a resistor brake with its own lever") scenario.wait(1.0); CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(0.0)); CHECK(locomotive.Ft == doctest::Approx(0.0)); - CHECK_FALSE(locomotive.DynamicBrakeFlag); + CHECK_FALSE(locomotive.brakes.electrodynamic.on); scenario.check(); } diff --git a/tests/unit/test_engine_shutdown.cpp b/tests/unit/test_engine_shutdown.cpp index a3cab4002..4e54206ed 100644 --- a/tests/unit/test_engine_shutdown.cpp +++ b/tests/unit/test_engine_shutdown.cpp @@ -39,7 +39,7 @@ TEST_CASE("engine shutdown: neither the fuel pump switch nor the battery switch CHECK(shunter->lineBreaker.closed); shunter->BatterySwitch(false); shunter.run(10.0); - CHECK(shunter->Power110vIsAvailable); // the converter run by the engine keeps feeding the fuel pump + CHECK(shunter->lowVoltage.power110vAvailable); // the converter run by the engine keeps feeding the fuel pump CHECK(shunter->lineBreaker.closed); CHECK(shunter->enrot > 0.9 * shunter->diesel.minRevolutions); } diff --git a/tests/unit/test_genset.cpp b/tests/unit/test_genset.cpp index 595abff6e..b51264712 100644 --- a/tests/unit/test_genset.cpp +++ b/tests/unit/test_genset.cpp @@ -430,7 +430,7 @@ TEST_CASE("genset: no battery, no start") { REQUIRE(cab.TractionModeSwitch(traction_mode::genset)); cab.GensetSwitch(true); run(dragon6, 20.0); - CHECK_FALSE(cab.Power24vIsAvailable); + CHECK_FALSE(cab.lowVoltage.power24vAvailable); CHECK_FALSE(cab.Genset.is_cranking); CHECK_FALSE(cab.Genset.is_active); CHECK(cab.Genset.revolutions == 0.0); diff --git a/tests/unit/test_horn.cpp b/tests/unit/test_horn.cpp index cd2e68df3..e606f4105 100644 --- a/tests/unit/test_horn.cpp +++ b/tests/unit/test_horn.cpp @@ -79,9 +79,9 @@ TEST_CASE("horn: an electric horn sounds on the low voltage, whatever the air") REQUIRE(vehicle->Horn3Supply == horn_supply::electric); // the third horn follows the others unless told otherwise vehicle->air.mainReservoirPressure = 0.0; - vehicle->Power24vIsAvailable = true; + vehicle->lowVoltage.power24vAvailable = true; CHECK(vehicle->SoundingHorns(allhorns) == allhorns); - vehicle->Power24vIsAvailable = false; + vehicle->lowVoltage.power24vAvailable = false; CHECK(vehicle->SoundingHorns(allhorns) == 0); } @@ -91,10 +91,10 @@ TEST_CASE("horn: the third horn can have a supply of its own, an electric horn o REQUIRE(vehicle->Horn3Supply == horn_supply::electric); vehicle->air.mainReservoirPressure = 0.0; - vehicle->Power24vIsAvailable = true; + vehicle->lowVoltage.power24vAvailable = true; CHECK(vehicle->SoundingHorns(allhorns) == 4); vehicle->air.mainReservoirPressure = 6.5; - vehicle->Power24vIsAvailable = false; + vehicle->lowVoltage.power24vAvailable = false; CHECK(vehicle->SoundingHorns(allhorns) == (horn::low | horn::high)); } @@ -116,6 +116,6 @@ TEST_CASE("horn: a pneumatic horn sounds from the threshold pressure up") { TEST_CASE("horn: an electric horn sounds on 110 V too") { auto vehicle{horn_vehicle(test::definition::load("wagon").set("Cntrl", "HornType", "Electric"))}; - vehicle->Power110vIsAvailable = true; + vehicle->lowVoltage.power110vAvailable = true; CHECK(vehicle->SoundingHorns(horn::high) == horn::high); } diff --git a/tests/unit/test_line_contactors_interlock.cpp b/tests/unit/test_line_contactors_interlock.cpp index 24e025f09..eb92812e2 100644 --- a/tests/unit/test_line_contactors_interlock.cpp +++ b/tests/unit/test_line_contactors_interlock.cpp @@ -52,7 +52,7 @@ TEST_CASE("line contactors interlock: without one the converter and the blowers TEST_CASE("line contactors interlock: on the converter, they close only with the vehicle's own converter running") { auto locomotive{ready("Converter")}; locomotive->converter.running = false; - locomotive->Power110vIsAvailable = true; // the 110 V from the other section doesn't run this one's fans + locomotive->lowVoltage.power110vAvailable = true; // the 110 V from the other section doesn't run this one's fans CHECK_FALSE(locomotive->MotorConnectorsCheck()); locomotive->converter.running = true; CHECK(locomotive->MotorConnectorsCheck()); @@ -95,16 +95,16 @@ TEST_CASE("line contactors interlock: a blower starting with the speed needs to SUBCASE("off the converter, it needs the 110 V") { rear.start_type = start_t::converter; rear.is_enabled = false; // nothing for the driver to switch on - locomotive->Power110vIsAvailable = false; + locomotive->lowVoltage.power110vAvailable = false; CHECK_FALSE(locomotive->MotorConnectorsCheck()); - locomotive->Power110vIsAvailable = true; + locomotive->lowVoltage.power110vAvailable = true; CHECK(locomotive->MotorConnectorsCheck()); } SUBCASE("off the battery, it needs the 24 V") { rear.start_type = start_t::battery; - locomotive->Power24vIsAvailable = false; + locomotive->lowVoltage.power24vAvailable = false; CHECK_FALSE(locomotive->MotorConnectorsCheck()); - locomotive->Power24vIsAvailable = true; + locomotive->lowVoltage.power24vAvailable = true; CHECK(locomotive->MotorConnectorsCheck()); } SUBCASE("one without a start velocity still has to run") { @@ -271,7 +271,7 @@ TEST_CASE("line contactors interlock: the ET42 section with its fans switched of rear.converter.allowLocal = false; test::drive(driven, line, 2.0); REQUIRE_FALSE(rear.converter.running); - CHECK(rear.Power110vIsAvailable); + CHECK(rear.lowVoltage.power110vAvailable); test::release_brakes(driven.cab); for (int i = 0; i < 3 && driven.cab.DirActive <= 0; ++i) { diff --git a/tests/unit/test_mains_before_pantographs.cpp b/tests/unit/test_mains_before_pantographs.cpp index 7fd62fa35..11d8b889a 100644 --- a/tests/unit/test_mains_before_pantographs.cpp +++ b/tests/unit/test_mains_before_pantographs.cpp @@ -175,7 +175,7 @@ TEST_CASE("mains before pantographs: with the flag the converter and the compres CHECK(loco->lineBreaker.closed); CHECK_FALSE(loco->MainCircuitPowered()); CHECK_FALSE(loco->converter.running); - CHECK_FALSE(loco->Power110vIsAvailable); + CHECK_FALSE(loco->lowVoltage.power110vAvailable); CHECK_FALSE(loco->air.compressor.running); // the pantograph up: the converter starts, and the compressor on its 110 V @@ -184,7 +184,7 @@ TEST_CASE("mains before pantographs: with the flag the converter and the compres CHECK(reservoir_gain(loco, 10.0, line) > 0.1); CHECK(loco->MainCircuitPowered()); CHECK(loco->converter.running); - CHECK(loco->Power110vIsAvailable); + CHECK(loco->lowVoltage.power110vAvailable); CHECK(loco->air.compressor.running); // the voltage gone they stop, behind the line breaker which stays closed @@ -208,7 +208,7 @@ TEST_CASE("mains before pantographs: with the flag the converter and the compres CHECK(loco->lineBreaker.closed); CHECK_FALSE(loco->MainCircuitPowered()); CHECK_FALSE(loco->converter.running); - CHECK_FALSE(loco->Power110vIsAvailable); + CHECK_FALSE(loco->lowVoltage.power110vAvailable); CHECK_FALSE(loco->air.compressor.running); } @@ -231,7 +231,7 @@ TEST_CASE("mains before pantographs: with the flag whatever else the main circui CHECK_FALSE(loco->air.compressor.running); CHECK_FALSE(loco->MotorBlowers[VehicleEnd::front].is_active); CHECK(loco->RventRot == 0.0); - CHECK_FALSE(loco->Heating); + CHECK_FALSE(loco->trainHeating.on); SUBCASE("nor do they run on a voltage below the one the locomotive works on") { raise_pantograph(loco, weak); @@ -241,7 +241,7 @@ TEST_CASE("mains before pantographs: with the flag whatever else the main circui CHECK_FALSE(loco->air.compressor.running); CHECK_FALSE(loco->MotorBlowers[VehicleEnd::front].is_active); CHECK(loco->RventRot == 0.0); - CHECK_FALSE(loco->Heating); + CHECK_FALSE(loco->trainHeating.on); } SUBCASE("with the voltage they do") { raise_pantograph(loco); @@ -250,7 +250,7 @@ TEST_CASE("mains before pantographs: with the flag whatever else the main circui CHECK(loco->air.compressor.running); CHECK(loco->MotorBlowers[VehicleEnd::front].is_active); CHECK(loco->RventRot > 0.0); - CHECK(loco->Heating); + CHECK(loco->trainHeating.on); } } @@ -264,14 +264,14 @@ TEST_CASE("mains before pantographs: without the flag the converter and the comp CHECK(reservoir_gain(loco, 10.0, line) > 0.1); CHECK(loco->MainCircuitPowered()); CHECK(loco->converter.running); - CHECK(loco->Power110vIsAvailable); + CHECK(loco->lowVoltage.power110vAvailable); CHECK(loco->air.compressor.running); // too low a voltage opens the line breaker, and they stop with it loco.run(5.0, weak); CHECK_FALSE(loco->lineBreaker.closed); CHECK_FALSE(loco->MainCircuitPowered()); CHECK_FALSE(loco->converter.running); - CHECK_FALSE(loco->Power110vIsAvailable); + CHECK_FALSE(loco->lowVoltage.power110vAvailable); CHECK_FALSE(loco->air.compressor.running); } diff --git a/tests/unit/test_oil_pump.cpp b/tests/unit/test_oil_pump.cpp index 130145b29..7d7acb902 100644 --- a/tests/unit/test_oil_pump.cpp +++ b/tests/unit/test_oil_pump.cpp @@ -12,7 +12,7 @@ using test::vehicle; TEST_CASE("oil pump: the pre-lubrication pump works before the engine start and stops once the engine runs") { vehicle loco{definition::load("cab_vehicle").set("Cntrl", "OilStart", "Manual")}; REQUIRE(loco->OilPump.start_type == start_t::manual); - loco->Power24vIsAvailable = true; // battery on + loco->lowVoltage.power24vAvailable = true; // battery on loco->OilPumpCheck(0.01); CHECK_FALSE(loco->OilPump.is_active); // not switched on yet @@ -29,7 +29,7 @@ TEST_CASE("oil pump: the pre-lubrication pump works before the engine start and TEST_CASE("oil pump: the pump started with the engine start procedure stops once the engine runs") { vehicle loco{definition::load("cab_vehicle").set("Cntrl", "OilStart", "Automatic")}; REQUIRE(loco->OilPump.start_type == start_t::automatic); - loco->Power24vIsAvailable = true; + loco->lowVoltage.power24vAvailable = true; loco->diesel.startupRequested = true; // starter button pressed loco->OilPumpCheck(0.01); @@ -46,8 +46,8 @@ TEST_CASE("oil pump: the pump started with the engine start procedure stops once TEST_CASE("oil pump: without power the pump and its lamp stay off") { vehicle loco{definition::load("cab_vehicle")}; - loco->Power24vIsAvailable = false; - loco->Power110vIsAvailable = false; + loco->lowVoltage.power24vAvailable = false; + loco->lowVoltage.power110vAvailable = false; loco->OilPump.is_enabled = true; loco->OilPumpCheck(0.01); diff --git a/tests/unit/test_pullee.cpp b/tests/unit/test_pullee.cpp index 3591e6e95..62f620270 100644 --- a/tests/unit/test_pullee.cpp +++ b/tests/unit/test_pullee.cpp @@ -114,13 +114,13 @@ TEST_CASE("pullee: an EU07 with a driver can't release the brakes of a dead Vect test::drive(driven, track, 60.0); if (false == pullee) { // the Vectron has emptied the brake pipe, and both locomotives stand on an emergency application - CHECK(hauled->Battery); + CHECK(hauled->lowVoltage.batteryOn); CHECK(locomotive->brakePipe.pressure < 1.0); CHECK(locomotive->brakes.cylinderPressure > 3.0); CHECK(hauled->brakes.cylinderPressure > 3.0); continue; } - CHECK_FALSE(hauled->Battery); + CHECK_FALSE(hauled->lowVoltage.batteryOn); CHECK(locomotive->brakePipe.pressure > 4.9); CHECK(locomotive->brakes.cylinderPressure < 0.1); CHECK(hauled->brakes.cylinderPressure < 0.1); @@ -335,9 +335,9 @@ TEST_CASE("pullee: entering the mode lets go of the hand brake and the spring br } SUBCASE("a locomotive ready to depart, its battery on") { vehicle vectron{definition::fiz("vectron_v1/wariant_7w"), 0.1}; - REQUIRE(vectron->Battery); + REQUIRE(vectron->lowVoltage.batteryOn); CHECK(vectron->PulleeModeSwitch(true)); - CHECK_FALSE(vectron->Battery); + CHECK_FALSE(vectron->lowVoltage.batteryOn); } } @@ -345,7 +345,7 @@ TEST_CASE("pullee: the battery and the cabs of a vehicle prepared for hauling st vehicle vectron{definition::fiz("vectron_v1/wariant_7w"), 0.0, "test", 1}; REQUIRE(vectron->PulleeModeSwitch(true)); CHECK_FALSE(vectron->BatterySwitch(true)); - CHECK_FALSE(vectron->Battery); + CHECK_FALSE(vectron->lowVoltage.batteryOn); CHECK_FALSE(vectron->CabActivisation()); CHECK_FALSE(vectron->CabActivisation(true)); CHECK(vectron->CabActive == 0); @@ -357,7 +357,7 @@ TEST_CASE("pullee: the battery and the cabs of a vehicle prepared for hauling st REQUIRE(vectron->PulleeModeSwitch(false)); CHECK_FALSE(vectron->PulleeMode); CHECK(vectron->BatterySwitch(true)); - CHECK(vectron->Battery); + CHECK(vectron->lowVoltage.batteryOn); CHECK(vectron->CabActivisation()); CHECK(vectron->CabActive == 1); // a vehicle driven from isn't one to haul @@ -394,14 +394,14 @@ TEST_CASE("pullee: the battery and cab commands of the train's driver pass a veh if (pullee) { REQUIRE(hauled->PulleeModeSwitch(true)); } - REQUIRE_FALSE(hauled->Battery); + REQUIRE_FALSE(hauled->lowVoltage.batteryOn); locomotive->BatterySwitch(true); locomotive->CabActivisation(); train.run(2.0); - CHECK(hauled->Battery == (false == pullee)); + CHECK(hauled->lowVoltage.batteryOn == (false == pullee)); CHECK(hauled->CabActive == (pullee ? 0 : 1)); // the vehicle behind it gets them either way - CHECK(last->Battery); + CHECK(last->lowVoltage.batteryOn); CHECK(last->CabActive == 1); } } @@ -439,7 +439,7 @@ TEST_CASE("pullee: every real vehicle standing braked releases once prepared for auto const &hauled{train.hauled.physics()}; CHECK(hauled.brakes.handBrakePosition == 0); CHECK_FALSE(hauled.brakes.spring.activate); - CHECK_FALSE(hauled.Battery); + CHECK_FALSE(hauled.lowVoltage.batteryOn); train.run(180.0); CHECK(hauled.brakes.emergencyValve.flow == 0.0); CHECK(hauled.brakes.cylinderPressure < 0.1); diff --git a/tests/unit/test_radio.cpp b/tests/unit/test_radio.cpp index b65cc2ced..abe4ef9f8 100644 --- a/tests/unit/test_radio.cpp +++ b/tests/unit/test_radio.cpp @@ -8,8 +8,8 @@ TEST_CASE("radio: a radio switched on with the low voltage works") { test::vehicle vehicle{test::definition::load("wagon")}; vehicle->Radio = true; - SUBCASE("24 V") { vehicle->Power24vIsAvailable = true; } - SUBCASE("110 V") { vehicle->Power110vIsAvailable = true; } + SUBCASE("24 V") { vehicle->lowVoltage.power24vAvailable = true; } + SUBCASE("110 V") { vehicle->lowVoltage.power110vAvailable = true; } CHECK(vehicle->RadioPowered()); } @@ -17,12 +17,12 @@ TEST_CASE("radio: a radio switched off or without the low voltage doesn't") { test::vehicle vehicle{test::definition::load("wagon")}; SUBCASE("switched off") { vehicle->Radio = false; - vehicle->Power24vIsAvailable = true; + vehicle->lowVoltage.power24vAvailable = true; } SUBCASE("batteries off") { vehicle->Radio = true; - vehicle->Power24vIsAvailable = false; - vehicle->Power110vIsAvailable = false; + vehicle->lowVoltage.power24vAvailable = false; + vehicle->lowVoltage.power110vAvailable = false; } CHECK_FALSE(vehicle->RadioPowered()); } @@ -38,7 +38,7 @@ TEST_CASE("radio: the radio fuse is closed by default") { TEST_CASE("radio: an opened radio fuse cuts the radio off") { test::vehicle vehicle{test::definition::load("wagon")}; vehicle->Radio = true; - vehicle->Power24vIsAvailable = true; + vehicle->lowVoltage.power24vAvailable = true; vehicle->RadioFuse = false; CHECK_FALSE(vehicle->RadioPowered()); vehicle->RadioFuse = true; @@ -47,7 +47,7 @@ TEST_CASE("radio: an opened radio fuse cuts the radio off") { TEST_CASE("radio: opening the radio fuse at a standstill resets the radio-stop, as switching the radio off does") { test::vehicle loco{test::definition::fiz("4e_v1/4e")}; - loco->Battery = true; + loco->lowVoltage.batteryOn = true; loco->Radio = true; REQUIRE(loco->RadiostopSwitch(true)); loco->SecuritySystemCheck(0.1); diff --git a/tests/unit/test_switches.cpp b/tests/unit/test_switches.cpp index 72b1e47ce..f2ca6de17 100644 --- a/tests/unit/test_switches.cpp +++ b/tests/unit/test_switches.cpp @@ -7,10 +7,10 @@ TEST_CASE("switches: the train heating switch can spring back (MaSzyna-EU07/maszyna#85)") { SUBCASE("impulse") { test::vehicle vehicle{test::definition::load("cab_vehicle").set("Switches", "TrainHeating", "Impulse")}; - CHECK(vehicle->HeatingSwitchImpulse); // whichever the case it's written in + CHECK(vehicle->trainHeating.switchImpulse); // whichever the case it's written in } SUBCASE("a plain switch by default") { test::vehicle vehicle{test::definition::load("cab_vehicle")}; - CHECK_FALSE(vehicle->HeatingSwitchImpulse); + CHECK_FALSE(vehicle->trainHeating.switchImpulse); } } diff --git a/tests/unit/test_traction.cpp b/tests/unit/test_traction.cpp index 5fd81fd95..4b27a94a6 100644 --- a/tests/unit/test_traction.cpp +++ b/tests/unit/test_traction.cpp @@ -183,7 +183,7 @@ TEST_CASE("traction: the stages of the EW58's electrodynamic brake, set by the p ew58.BrakeLevelSet(position); scenario.wait(6.0); CHECK(ew58.TUHEX_StageActual == stage); - CHECK(ew58.DynamicBrakeFlag); + CHECK(ew58.brakes.electrodynamic.on); CHECK(ew58.Im < 0.0); } scenario.act("release"); @@ -240,7 +240,7 @@ TEST_CASE("traction: the induction motor drive's speed control, its electrodynam scenario.act("local brake"); eu47.IncLocalBrakeLevel(LocalBrakePosNo); scenario.wait(5.0); - CHECK(eu47.DynamicBrakeFlag); + CHECK(eu47.brakes.electrodynamic.on); CHECK(eu47.Im == doctest::Approx(0.0)); CHECK(eu47.brakes.cylinderPressure > 2.0); scenario.act("local brake off"); @@ -254,7 +254,7 @@ TEST_CASE("traction: the induction motor drive's speed control, its electrodynam scenario.act(std::format("service brake at {} V", static_cast(voltage))); eu47.BrakeLevelSet(eu47.brakes.driverValve->GetPos(bh_FB)); scenario.wait(6.0); - CHECK(eu47.DynamicBrakeFlag); + CHECK(eu47.brakes.electrodynamic.on); CHECK(eu47.Im < -100.0); CHECK((eu47.Vadd > 1.0) == (voltage > eu47.EnginePowerSource.CollectorParameters.MaxV)); eu47.BrakeLevelSet(eu47.brakes.driverValve->GetPos(bh_RP)); diff --git a/vehicle/ai/consist.cpp b/vehicle/ai/consist.cpp index 30176ce2f..64e2d1a6a 100644 --- a/vehicle/ai/consist.cpp +++ b/vehicle/ai/consist.cpp @@ -379,8 +379,8 @@ bool TController::CheckVehicles(DriverOrders user) // HACK: wagony muszą mieć baterię załączoną do otwarcia drzwi... p->physics->BatterySwitch( true ); // enable heating and converter in carriages with can be heated - if( p->physics->HeatingPower > 0 ) { - p->physics->HeatingAllow = true; + if( p->physics->trainHeating.power > 0 ) { + p->physics->trainHeating.allow = true; p->physics->ConverterSwitch( true, range_t::local ); hasheaters = true; } @@ -485,7 +485,7 @@ bool TController::CheckVehicles(DriverOrders user) false == isheatingcouplingactive ? false : ispassengertrain ? hasheaters : false) }; - if( mvControlling->HeatingAllow != isheatingneeded ) { + if( mvControlling->trainHeating.allow != isheatingneeded ) { cue_action( isheatingneeded ? driver_hint::consistheatingon : @@ -680,12 +680,12 @@ TController::determine_consist_state() { // ABu-160305 testowanie gotowości do jazdy // Ra: przeniesione z DynObj, skład użytkownika też jest testowany, żeby mu przekazać, że ma odhamować - if (occupied->CabActive == 0 && occupied->Power24vIsAvailable) + if (occupied->CabActive == 0 && occupied->lowVoltage.power24vAvailable) { cue_action( driver_hint::cabactivation ); } else if (!occupied->AutomaticCabActivation - && ( occupied->CabActive == -occupied->CabOccupied || !occupied->CabMaster || !occupied->Power24vIsAvailable ) ) + && ( occupied->CabActive == -occupied->CabOccupied || !occupied->CabMaster || !occupied->lowVoltage.power24vAvailable ) ) { cue_action( driver_hint::cabdeactivation ); } diff --git a/vehicle/ai/controls.cpp b/vehicle/ai/controls.cpp index c2cc203c2..0d5552e7c 100644 --- a/vehicle/ai/controls.cpp +++ b/vehicle/ai/controls.cpp @@ -506,7 +506,7 @@ bool TController::IncSpeed() } // TODO: move all fVoltage assignments to a single, more generic place if( mvControlling->EnginePowerSource.SourceType == TPowerSource::Accumulator ) { - fVoltage = mvControlling->BatteryVoltage; + fVoltage = mvControlling->lowVoltage.batteryVoltage; } if (!IsAnyMotorOverloadRelayOpen && !mvControlling->protection.pressureSwitch && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->lineContactors.closed) && (Ready || drivingFlags.press)) { // youBy polecił dodać 2012-09-08 v367 diff --git a/vehicle/ai/engine.cpp b/vehicle/ai/engine.cpp index 33884cac8..661a3d7a8 100644 --- a/vehicle/ai/engine.cpp +++ b/vehicle/ai/engine.cpp @@ -339,7 +339,7 @@ bool TController::ReleaseEngine() { // && ( false == IsAnyCompressorEnabled ) // && ( false == IsAnyConverterEnabled ) && false == mvControlling->lineBreaker.closed - && false == occupied->Power24vIsAvailable }; + && false == occupied->lowVoltage.power24vAvailable }; if (OK) { // jeśli się zatrzymał diff --git a/vehicle/ai/orders.cpp b/vehicle/ai/orders.cpp index c50cca135..954c56dfc 100644 --- a/vehicle/ai/orders.cpp +++ b/vehicle/ai/orders.cpp @@ -1178,7 +1178,7 @@ TController::handle_engine() { if( OrderCurrentGet() == DriverOrder::waitForOrders && false == iEngineActive // && ( false == AIControllFlag ) - && true == occupied->Power24vIsAvailable ) { + && true == occupied->lowVoltage.power24vAvailable ) { OrderNext( DriverOrder::prepareEngine ); } // basic engine preparation diff --git a/vehicle/cab/auxiliarycommands.cpp b/vehicle/cab/auxiliarycommands.cpp index cb7540cc8..9bd043955 100644 --- a/vehicle/cab/auxiliarycommands.cpp +++ b/vehicle/cab/auxiliarycommands.cpp @@ -684,7 +684,7 @@ void TTrain::OnCommand_convertertoggle(TTrain *Train, command_data const &Comman // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const overloadrelayisopen{(Train->Dynamic()->Mechanik != nullptr ? Train->Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : Train->occupied->converter.overloaded)}; - if (Train->occupied->converter.switchType != "impulse" ? Train->ggConverterButton.GetValue() < 0.5 : false == Train->occupied->Power110vIsAvailable && false == overloadrelayisopen) + if (Train->occupied->converter.switchType != "impulse" ? Train->ggConverterButton.GetValue() < 0.5 : false == Train->occupied->lowVoltage.power110vAvailable && false == overloadrelayisopen) { // turn on OnCommand_converterenable(Train, Command); diff --git a/vehicle/cab/brakecommands.cpp b/vehicle/cab/brakecommands.cpp index 087ee602c..2e60ad77f 100644 --- a/vehicle/cab/brakecommands.cpp +++ b/vehicle/cab/brakecommands.cpp @@ -55,7 +55,7 @@ void TTrain::OnCommand_independentbrakeincrease(TTrain *Train, command_data cons // when SplitEDPneumaticBrake is active the local brake key always operates // the pneumatic local brake directly, never piggy-backing on the joint controller - auto const splitMode{Train->controlled->SplitEDPneumaticBrake}; + auto const splitMode{Train->controlled->brakes.electrodynamic.splitFromPneumatic}; auto const useStepped{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; if (Train->occupied->brakes.localKind != TLocalBrake::ManualBrake) { @@ -81,7 +81,7 @@ void TTrain::OnCommand_independentbrakeincreasefast(TTrain *Train, command_data if (Command.action != GLFW_RELEASE) { - auto const splitMode{Train->controlled->SplitEDPneumaticBrake}; + auto const splitMode{Train->controlled->brakes.electrodynamic.splitFromPneumatic}; auto const useJointAnim{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; if (Train->occupied->brakes.localKind != TLocalBrake::ManualBrake) { @@ -107,7 +107,7 @@ void TTrain::OnCommand_independentbrakedecrease(TTrain *Train, command_data cons if (Command.action != GLFW_RELEASE) { - auto const splitMode{Train->controlled->SplitEDPneumaticBrake}; + auto const splitMode{Train->controlled->brakes.electrodynamic.splitFromPneumatic}; auto const useStepped{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; if (Train->occupied->brakes.localKind != TLocalBrake::ManualBrake // Ra 1014-06: AI potrafi zahamować pomocniczym mimo jego braku - odhamować jakoś trzeba @@ -136,7 +136,7 @@ void TTrain::OnCommand_independentbrakedecreasefast(TTrain *Train, command_data if (Command.action != GLFW_RELEASE) { - auto const splitMode{Train->controlled->SplitEDPneumaticBrake}; + auto const splitMode{Train->controlled->brakes.electrodynamic.splitFromPneumatic}; auto const useJointAnim{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; if (Train->occupied->brakes.localKind != TLocalBrake::ManualBrake // Ra 1014-06: AI potrafi zahamować pomocniczym mimo jego braku - odhamować jakoś trzeba diff --git a/vehicle/cab/cabcommands.cpp b/vehicle/cab/cabcommands.cpp index 25ac96377..30f020482 100644 --- a/vehicle/cab/cabcommands.cpp +++ b/vehicle/cab/cabcommands.cpp @@ -300,7 +300,7 @@ void TTrain::OnCommand_batterytoggle(TTrain *Train, command_data const &Command) if (Train->allowBatteryToggle || Command.action != GLFW_REPEAT) { // keep the switch from flipping back and forth if key is held down - if (false == Train->occupied->Power24vIsAvailable) + if (false == Train->occupied->lowVoltage.power24vAvailable) { // turn on OnCommand_batteryenable(Train, Command); @@ -315,7 +315,7 @@ void TTrain::OnCommand_batterytoggle(TTrain *Train, command_data const &Command) void TTrain::OnCommand_batteryenable(TTrain *Train, command_data const &Command) { - if (!Train->occupied->isBatteryButtonImpulse) + if (!Train->occupied->lowVoltage.batteryButtonImpulse) { // regular button behavior if (Command.action == GLFW_PRESS) { @@ -346,12 +346,12 @@ void TTrain::OnCommand_batteryenable(TTrain *Train, command_data const &Command) { if (Command.action == GLFW_PRESS) { - if (Train->occupied->shouldHoldBatteryButton) + if (Train->occupied->lowVoltage.batteryButtonHeld) { // jesli przycisk trzeba przytrzymac Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); Train->ggBatteryOnButton.UpdateValue(1.0f, Train->dsbSwitch); - Train->fBatteryTimer = Train->occupied->BatteryButtonHoldTime; // start timer + Train->fBatteryTimer = Train->occupied->lowVoltage.batteryButtonHoldTime; // start timer } else { @@ -376,15 +376,15 @@ void TTrain::OnCommand_batteryenable(TTrain *Train, command_data const &Command) Train->ggBatteryOnButton.UpdateValue(0.0f, Train->dsbSwitch); Train->fBatteryTimer = -1.f; // Train->allowBatteryToggle = true; - Train->occupied->batterySwAlreadyFired = false; + Train->occupied->lowVoltage.batteryButtonFired = false; } - else if (Command.action == GLFW_REPEAT && Train->occupied->shouldHoldBatteryButton) + else if (Command.action == GLFW_REPEAT && Train->occupied->lowVoltage.batteryButtonHeld) { // trzymamy przycisk - if (Train->fBatteryTimer <= 0.0 && Train->occupied->Battery == false && !Train->occupied->batterySwAlreadyFired) + if (Train->fBatteryTimer <= 0.0 && Train->occupied->lowVoltage.batteryOn == false && !Train->occupied->lowVoltage.batteryButtonFired) { Train->occupied->BatterySwitch(true); - Train->occupied->batterySwAlreadyFired = true; + Train->occupied->lowVoltage.batteryButtonFired = true; // side-effects if (Train->occupied->LightsPosNo > 0) @@ -399,7 +399,7 @@ void TTrain::OnCommand_batteryenable(TTrain *Train, command_data const &Command) void TTrain::OnCommand_batterydisable(TTrain *Train, command_data const &Command) { - if (!Train->occupied->isBatteryButtonImpulse) + if (!Train->occupied->lowVoltage.batteryButtonImpulse) { // regular button behavior if (Command.action == GLFW_PRESS) { @@ -429,12 +429,12 @@ void TTrain::OnCommand_batterydisable(TTrain *Train, command_data const &Command { if (Command.action == GLFW_PRESS) { - if (Train->occupied->shouldHoldBatteryButton) + if (Train->occupied->lowVoltage.batteryButtonHeld) { // jesli przycisk trzeba przytrzymac Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); Train->ggBatteryOffButton.UpdateValue(1.0f, Train->dsbSwitch); - Train->fBatteryTimer = Train->occupied->BatteryButtonHoldTime; // start timer + Train->fBatteryTimer = Train->occupied->lowVoltage.batteryButtonHoldTime; // start timer } else { @@ -458,15 +458,15 @@ void TTrain::OnCommand_batterydisable(TTrain *Train, command_data const &Command Train->ggBatteryButton.UpdateValue(0.0f, Train->dsbSwitch); Train->ggBatteryOffButton.UpdateValue(0.0f, Train->dsbSwitch); Train->allowBatteryToggle = true; - Train->occupied->batterySwAlreadyFired = false; + Train->occupied->lowVoltage.batteryButtonFired = false; } - else if (Command.action == GLFW_REPEAT && Train->occupied->shouldHoldBatteryButton) + else if (Command.action == GLFW_REPEAT && Train->occupied->lowVoltage.batteryButtonHeld) { // trzymamy przycisk - if (Train->fBatteryTimer <= 0.0 && Train->occupied->Battery == true && !Train->occupied->batterySwAlreadyFired) + if (Train->fBatteryTimer <= 0.0 && Train->occupied->lowVoltage.batteryOn == true && !Train->occupied->lowVoltage.batteryButtonFired) { Train->occupied->BatterySwitch(false); - Train->occupied->batterySwAlreadyFired = true; + Train->occupied->lowVoltage.batteryButtonFired = true; // side-effects if (Train->occupied->LightsPosNo > 0) diff --git a/vehicle/cab/controllercommands.cpp b/vehicle/cab/controllercommands.cpp index 8028e5e6f..3126ee91c 100644 --- a/vehicle/cab/controllercommands.cpp +++ b/vehicle/cab/controllercommands.cpp @@ -91,7 +91,7 @@ void TTrain::OnCommand_jointcontrollerset(TTrain *Train, command_data const &Com Train->m_mastercontrollerinuse = true; // when SplitEDPneumaticBrake is active the joint controller's negative range // commands the dedicated dynamic-brake lever instead of the local pneumatic brake - if (Train->controlled->SplitEDPneumaticBrake) + if (Train->controlled->brakes.electrodynamic.splitFromPneumatic) { Train->controlled->DynamicBrakeLevelSet(0.0); } @@ -103,11 +103,11 @@ void TTrain::OnCommand_jointcontrollerset(TTrain *Train, command_data const &Com else { auto const negativeRange{std::clamp(1.0 - Command.param1 * 2, 0.0, 1.0)}; - if (Train->controlled->SplitEDPneumaticBrake) + if (Train->controlled->brakes.electrodynamic.splitFromPneumatic) { // negative range of jointctrl drives only ED braking, local pneumatic brake stays untouched. // snap to DBPN discrete stops so the lever animates step-by-step - auto const stepCount{std::max(1, Train->controlled->DynamicBrakeCtrlPosNo)}; + auto const stepCount{std::max(1, Train->controlled->brakes.electrodynamic.controllerPositions)}; auto const snapped{std::round(negativeRange * stepCount) / stepCount}; Train->controlled->DynamicBrakeLevelSet(snapped); } @@ -135,10 +135,10 @@ void TTrain::OnCommand_mastercontrollerincrease(TTrain *Train, command_data cons if (Command.action != GLFW_RELEASE) { // on press or hold - auto const splitMode{Train->controlled->SplitEDPneumaticBrake}; + auto const splitMode{Train->controlled->brakes.electrodynamic.splitFromPneumatic}; // when SplitEDPneumaticBrake is true the joint controller's negative range maps // to the dedicated dynamic-brake lever (DynamicBrakeCtrl) rather than to LocalBrake - auto const negativeRangeActive{splitMode ? Train->controlled->DynamicBrakeCtrlPos > 0.0 : Train->occupied->brakes.independentPosition > 0.0}; + auto const negativeRangeActive{splitMode ? Train->controlled->brakes.electrodynamic.controllerPosition > 0.0 : Train->occupied->brakes.independentPosition > 0.0}; if (Train->ggJointCtrl.SubModel != nullptr && negativeRangeActive) { if (splitMode) @@ -171,8 +171,8 @@ void TTrain::OnCommand_mastercontrollerincreasefast(TTrain *Train, command_data if (Command.action != GLFW_RELEASE) { // on press or hold - auto const splitMode{Train->controlled->SplitEDPneumaticBrake}; - auto const negativeRangeActive{splitMode ? Train->controlled->DynamicBrakeCtrlPos > 0.0 : Train->occupied->brakes.independentPosition > 0.0}; + auto const splitMode{Train->controlled->brakes.electrodynamic.splitFromPneumatic}; + auto const negativeRangeActive{splitMode ? Train->controlled->brakes.electrodynamic.controllerPosition > 0.0 : Train->occupied->brakes.independentPosition > 0.0}; if (Train->ggJointCtrl.SubModel != nullptr && negativeRangeActive) { if (splitMode) @@ -205,7 +205,7 @@ void TTrain::OnCommand_mastercontrollerdecrease(TTrain *Train, command_data cons if (Command.action != GLFW_RELEASE) { // on press or hold - auto const splitMode{Train->controlled->SplitEDPneumaticBrake}; + auto const splitMode{Train->controlled->brakes.electrodynamic.splitFromPneumatic}; if (Train->ggJointCtrl.SubModel != nullptr && Train->controlled->IsMainCtrlNoPowerPos()) { // negative range of jointctrl: ED brake when split, otherwise pneumatic local brake @@ -239,7 +239,7 @@ void TTrain::OnCommand_mastercontrollerdecreasefast(TTrain *Train, command_data if (Command.action != GLFW_RELEASE) { // on press or hold - auto const splitMode{Train->controlled->SplitEDPneumaticBrake}; + auto const splitMode{Train->controlled->brakes.electrodynamic.splitFromPneumatic}; if (Train->ggJointCtrl.SubModel != nullptr && Train->controlled->IsMainCtrlNoPowerPos()) { if (splitMode) @@ -288,7 +288,7 @@ void TTrain::OnCommand_DynamicBrakeControllerIncrease(TTrain *Train, command_dat { return; } - if (false == Train->controlled->SplitEDPneumaticBrake) + if (false == Train->controlled->brakes.electrodynamic.splitFromPneumatic) { return; } @@ -303,12 +303,12 @@ void TTrain::OnCommand_DynamicBrakeControllerIncreaseFast(TTrain *Train, command { return; } - if (false == Train->controlled->SplitEDPneumaticBrake) + if (false == Train->controlled->brakes.electrodynamic.splitFromPneumatic) { return; } - Train->controlled->IncDynamicBrakeLevel(static_cast(Train->controlled->DynamicBrakeCtrlPosNo)); + Train->controlled->IncDynamicBrakeLevel(static_cast(Train->controlled->brakes.electrodynamic.controllerPositions)); } void TTrain::OnCommand_DynamicBrakeControllerDecrease(TTrain *Train, command_data const &Command) @@ -317,7 +317,7 @@ void TTrain::OnCommand_DynamicBrakeControllerDecrease(TTrain *Train, command_dat { return; } - if (false == Train->controlled->SplitEDPneumaticBrake) + if (false == Train->controlled->brakes.electrodynamic.splitFromPneumatic) { return; } @@ -332,12 +332,12 @@ void TTrain::OnCommand_DynamicBrakeControllerDecreaseFast(TTrain *Train, command { return; } - if (false == Train->controlled->SplitEDPneumaticBrake) + if (false == Train->controlled->brakes.electrodynamic.splitFromPneumatic) { return; } - Train->controlled->DecDynamicBrakeLevel(static_cast(Train->controlled->DynamicBrakeCtrlPosNo)); + Train->controlled->DecDynamicBrakeLevel(static_cast(Train->controlled->brakes.electrodynamic.controllerPositions)); } void TTrain::OnCommand_DynamicBrakeControllerSet(TTrain *Train, command_data const &Command) @@ -346,14 +346,14 @@ void TTrain::OnCommand_DynamicBrakeControllerSet(TTrain *Train, command_data con { return; } - if (false == Train->controlled->SplitEDPneumaticBrake) + if (false == Train->controlled->brakes.electrodynamic.splitFromPneumatic) { return; } // when input source uses raw 0..1 value, snap to nearest DBPN step auto const target{std::clamp(Command.param1, 0.0, 1.0)}; - auto const stepCount{std::max(1, Train->controlled->DynamicBrakeCtrlPosNo)}; + auto const stepCount{std::max(1, Train->controlled->brakes.electrodynamic.controllerPositions)}; auto const snapped{std::round(target * stepCount) / stepCount}; Train->controlled->DynamicBrakeLevelSet(snapped); } diff --git a/vehicle/cab/equipmentcommands.cpp b/vehicle/cab/equipmentcommands.cpp index efe5eef28..398836221 100644 --- a/vehicle/cab/equipmentcommands.cpp +++ b/vehicle/cab/equipmentcommands.cpp @@ -62,7 +62,7 @@ void TTrain::OnCommand_heatingtoggle(TTrain *Train, command_data const &Command) if (Command.action == GLFW_PRESS) { // ignore repeats so the switch doesn't flip back and forth if key is held down - if (false == Train->controlled->HeatingAllow) + if (false == Train->controlled->trainHeating.allow) { // turn on OnCommand_heatingenable(Train, Command); @@ -73,7 +73,7 @@ void TTrain::OnCommand_heatingtoggle(TTrain *Train, command_data const &Command) OnCommand_heatingdisable(Train, Command); } } - else if (Command.action == GLFW_RELEASE && (Train->ggTrainHeatingButton.type() == TGaugeType::push || Train->occupied->HeatingSwitchImpulse)) + else if (Command.action == GLFW_RELEASE && (Train->ggTrainHeatingButton.type() == TGaugeType::push || Train->occupied->trainHeating.switchImpulse)) { // impulse switch // visual feedback @@ -91,7 +91,7 @@ void TTrain::OnCommand_heatingenable(TTrain *Train, command_data const &Command) // visual feedback Train->ggTrainHeatingButton.UpdateValue(1.0, Train->dsbSwitch); } - else if (Command.action == GLFW_RELEASE && Train->occupied->HeatingSwitchImpulse) + else if (Command.action == GLFW_RELEASE && Train->occupied->trainHeating.switchImpulse) { // the switch springs back to the middle Train->ggTrainHeatingButton.UpdateValue(0.0, Train->dsbSwitch); @@ -107,7 +107,7 @@ void TTrain::OnCommand_heatingdisable(TTrain *Train, command_data const &Command Train->occupied->HeatingSwitch(false); // visual feedback: an impulse switch is pushed the other way, down auto position{0.0}; - if (Train->occupied->HeatingSwitchImpulse) + if (Train->occupied->trainHeating.switchImpulse) { position = -1.0; } @@ -117,7 +117,7 @@ void TTrain::OnCommand_heatingdisable(TTrain *Train, command_data const &Command } Train->ggTrainHeatingButton.UpdateValue(position, Train->dsbSwitch); } - else if (Command.action == GLFW_RELEASE && Train->occupied->HeatingSwitchImpulse) + else if (Command.action == GLFW_RELEASE && Train->occupied->trainHeating.switchImpulse) { Train->ggTrainHeatingButton.UpdateValue(0.0, Train->dsbSwitch); } diff --git a/vehicle/cab/pantographcommands.cpp b/vehicle/cab/pantographcommands.cpp index c83599f97..a1806c9d6 100644 --- a/vehicle/cab/pantographcommands.cpp +++ b/vehicle/cab/pantographcommands.cpp @@ -590,7 +590,7 @@ void TTrain::OnCommand_pantographcompressoractivate(TTrain *Train, command_data if (Command.action != GLFW_RELEASE) { // press or hold to activate - if (Train->pantographUnit->pantographAir.pressure < 4.8 && true == Train->pantographUnit->Power24vIsAvailable) + if (Train->pantographUnit->pantographAir.pressure < 4.8 && true == Train->pantographUnit->lowVoltage.power24vAvailable) { // needs live power source and low enough pressure to work Train->pantographUnit->pantographAir.compressorRunning = true; diff --git a/vehicle/cab/setup.cpp b/vehicle/cab/setup.cpp index 118a6ff30..fe23cc0fe 100644 --- a/vehicle/cab/setup.cpp +++ b/vehicle/cab/setup.cpp @@ -888,7 +888,7 @@ void TTrain::set_cab_controls(int const Cab) { // switches // battery - ggBatteryButton.PutValue(ggBatteryButton.type() == TGaugeType::push ? 0.5f : occupied->Power24vIsAvailable ? 1.f : 0.f); + ggBatteryButton.PutValue(ggBatteryButton.type() == TGaugeType::push ? 0.5f : occupied->lowVoltage.power24vAvailable ? 1.f : 0.f); // activation ggCabActivationButton.PutValue(ggCabActivationButton.type() == TGaugeType::push ? 0.5f : occupied->IsCabMaster() ? 1.f : 0.f); // line breaker @@ -1077,9 +1077,9 @@ void TTrain::set_cab_controls(int const Cab) ggDoorStepButton.PutValue(occupied->Doors.step_enabled ? 1.f : 0.f); } // heating - if (false == ggTrainHeatingButton.is_push() && false == occupied->HeatingSwitchImpulse) + if (false == ggTrainHeatingButton.is_push() && false == occupied->trainHeating.switchImpulse) { - ggTrainHeatingButton.PutValue(controlled->Heating ? 1.f : 0.f); + ggTrainHeatingButton.PutValue(controlled->trainHeating.on ? 1.f : 0.f); } // brake acting time if (ggBrakeProfileCtrl.SubModel != nullptr) @@ -1340,7 +1340,7 @@ bool TTrain::initialize_button(cParser &Parser, std::string const &Label, int co {"i-doorpermit_any:", &m_doorpermits}, {"i-doorstep:", &occupied->Doors.step_enabled}, {"i-mainpipelock:", &occupied->brakes.pipeLock.locked}, - {"i-battery:", &occupied->Power24vIsAvailable}, + {"i-battery:", &occupied->lowVoltage.power24vAvailable}, {"i-cablight:", &Cabine[iCabn].bLight}, {"i-compartmentlights:", &occupied->CompartmentLights.is_active}, }; diff --git a/vehicle/cab/sounds.cpp b/vehicle/cab/sounds.cpp index 23dd29647..ebf928565 100644 --- a/vehicle/cab/sounds.cpp +++ b/vehicle/cab/sounds.cpp @@ -340,7 +340,7 @@ void TTrain::update_sounds(double const Deltatime) } // power-reliant sounds - if (occupied->Power24vIsAvailable || occupied->Power110vIsAvailable) + if (occupied->lowVoltage.power24vAvailable || occupied->lowVoltage.power110vAvailable) { // buzzer shp diff --git a/vehicle/cab/train.cpp b/vehicle/cab/train.cpp index d0c889eb2..0c6ae06b9 100644 --- a/vehicle/cab/train.cpp +++ b/vehicle/cab/train.cpp @@ -173,11 +173,11 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("cabactive", occupied->CabActive); dict->insert("master", occupied->CabMaster); // basic systems state data - dict->insert("battery", occupied->Power24vIsAvailable); + dict->insert("battery", occupied->lowVoltage.power24vAvailable); dict->insert("linebreaker", controlled->lineBreaker.closed); dict->insert("main_init", controlled->lineBreaker.initCountdown < controlled->lineBreaker.initTime && controlled->lineBreaker.initCountdown > 0.0); dict->insert("main_ready", false == controlled->lineBreaker.closed && fHVoltage > 0.0 && controlled->lineBreaker.initCountdown <= 0.0); - dict->insert("converter", occupied->Power110vIsAvailable); + dict->insert("converter", occupied->lowVoltage.power110vAvailable); dict->insert("converter_overload", controlled->converter.overloaded); dict->insert("compress", controlled->air.compressor.running); dict->insert("pant_compressor", pantographUnit->pantographAir.compressorRunning); @@ -212,7 +212,7 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("mainctrl_pos_count", controlled->MainCtrlPosNo); dict->insert("main_ctrl_actual_pos", controlled->MainCtrlActualPos); dict->insert("scndctrl_pos", controlled->ScndCtrlPos); - dict->insert("dynamicbrake_pos", controlled->DynamicBrakeCtrlPos); + dict->insert("dynamicbrake_pos", controlled->brakes.electrodynamic.controllerPosition); dict->insert("scnd_ctrl_actual_pos", controlled->ScndCtrlActualPos); dict->insert("brakectrl_pos", controlled->brakes.handlePositionSmooth); dict->insert("localbrake_pos", controlled->brakes.independentPosition); @@ -429,7 +429,7 @@ TTrain::state_t TTrain::get_state() const occupied->Doors.instances[occupied->CabOccupied < 0 ? VehicleSide::left : VehicleSide::right].open_permit, occupied->Doors.instances[occupied->CabOccupied < 0 ? VehicleSide::left : VehicleSide::right].is_open, occupied->Doors.step_enabled, - occupied->Power24vIsAvailable, + occupied->lowVoltage.power24vAvailable, 0, occupied->brakes.pipeLock.locked, btLampkaRadioMessage.GetValue(), @@ -439,7 +439,7 @@ TTrain::state_t TTrain::get_state() const bool TTrain::is_eztoer() const { - return controlled->TrainType == train_type::emu && occupied->brakes.subsystem == TBrakeSubSystem::ss_ESt && controlled->Power24vIsAvailable == true && controlled->EpFuse == true && + return controlled->TrainType == train_type::emu && occupied->brakes.subsystem == TBrakeSubSystem::ss_ESt && controlled->lowVoltage.power24vAvailable == true && controlled->EpFuse == true && controlled->DirActive != 0; // od yB } @@ -562,7 +562,7 @@ void TTrain::UpdateCab() void TTrain::add_distance(double const Distance) { - auto const meterenabled{m_distancecounter >= 0 && (occupied->Power24vIsAvailable || occupied->Power110vIsAvailable)}; + auto const meterenabled{m_distancecounter >= 0 && (occupied->lowVoltage.power24vAvailable || occupied->lowVoltage.power110vAvailable)}; if (true == meterenabled) { diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index 32a0fab22..cf33a899a 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -65,7 +65,7 @@ bool TTrain::Update(double const Deltatime) updateUnitStates(); updateFeedbackGauges(); updateConverterOverload(Deltatime); - auto const lowvoltagepower{occupied->Power24vIsAvailable || occupied->Power110vIsAvailable}; + auto const lowvoltagepower{occupied->lowVoltage.power24vAvailable || occupied->lowVoltage.power110vAvailable}; updateSecondUnitGauges(); updateClock(); @@ -122,12 +122,12 @@ bool TTrain::Update(double const Deltatime) } // update direction relay - if (prevBatState != occupied->Power24vIsAvailable) + if (prevBatState != occupied->lowVoltage.power24vAvailable) SetupDirectionRelays(); if (prevDirection != occupied->DirActive) UpdateDirectionRelays(); - prevBatState = occupied->Power24vIsAvailable; + prevBatState = occupied->lowVoltage.power24vAvailable; prevDirection = occupied->DirActive; // sounds @@ -483,11 +483,11 @@ void TTrain::updateUnitStates() fEIMParams[1 + in][9] = static_cast(p->physics->EngineVoltage); fEIMParams[0][6] += fEIMParams[1 + in][8]; bMains[in] = p->physics->lineBreaker.closed; - fCntVol[in] = static_cast(p->physics->BatteryVoltage); + fCntVol[in] = static_cast(p->physics->lowVoltage.batteryVoltage); bFuse[in] = p->physics->FuseFlag; - bBatt[in] = p->physics->Battery; + bBatt[in] = p->physics->lowVoltage.batteryOn; bConv[in] = p->physics->converter.running; - bHeat[in] = p->physics->Heating; + bHeat[in] = p->physics->trainHeating.on; // bComp[in][2] = (p->physics->CompressorAllow || (p->physics->CompressorStart == start_t::automatic)); // bComp[in][3] = (p->physics->CompressorFlag); in++; @@ -506,11 +506,11 @@ void TTrain::updateUnitStates() fDieselParams[1 + in][8] = p->physics->diesel.heat.Ts; fDieselParams[1 + in][9] = static_cast(p->physics->retarder.fill); bMains[in] = p->physics->lineBreaker.closed; - fCntVol[in] = static_cast(p->physics->BatteryVoltage); + fCntVol[in] = static_cast(p->physics->lowVoltage.batteryVoltage); bFuse[in] = p->physics->FuseFlag; - bBatt[in] = p->physics->Battery; + bBatt[in] = p->physics->lowVoltage.batteryOn; bConv[in] = p->physics->converter.running; - bHeat[in] = p->physics->Heating; + bHeat[in] = p->physics->trainHeating.on; in++; iPowerNo = in; } @@ -696,7 +696,7 @@ void TTrain::updateEngineGauges() // youBy - napiecie na silnikach if (ggEngineVoltage.SubModel) { - if (controlled->DynamicBrakeFlag) + if (controlled->brakes.electrodynamic.on) { ggEngineVoltage.UpdateValue(static_cast(std::abs(controlled->Im * 5))); } @@ -725,7 +725,7 @@ void TTrain::updateEngineGauges() { // NOTE: since we don't have functional converter object, we're faking it here by simple check whether converter is on // TODO: implement object-based circuits and power systems model so we can have this working more properly - ggLVoltage.UpdateValue(static_cast(std::max(occupied->Power110vIsAvailable ? occupied->NominalBatteryVoltage : 0.0, occupied->Power24vIsAvailable ? occupied->BatteryVoltage : 0.0))); + ggLVoltage.UpdateValue(static_cast(std::max(occupied->lowVoltage.power110vAvailable ? occupied->lowVoltage.nominalBatteryVoltage : 0.0, occupied->lowVoltage.power24vAvailable ? occupied->lowVoltage.batteryVoltage : 0.0))); ggLVoltage.Update(); } @@ -798,7 +798,7 @@ void TTrain::updateBasicLamps() btCabActived.Turn(false); } - if (controlled->Battery && controlled->CabActive != 0) + if (controlled->lowVoltage.batteryOn && controlled->CabActive != 0) btAKLVents.Turn(true); else btAKLVents.Turn(false); @@ -831,8 +831,8 @@ void TTrain::updateCircuitLamps(double const Deltatime) btLampkaMainBreakerReady.Turn(controlled->lineBreaker.initCountdown <= 0.0 && m_linebreakerstate != linebreaker::state::closing && !controlled->lineBreaker.closed); btLampkaMainBreakerBlinkingIfReady.Turn(m_linebreakerstate == linebreaker::state::closing || controlled->lineBreaker.closed || controlled->lineBreaker.initCountdown < 0.0 && simulation::Time.data().wMilliseconds > 500); - btLampkaPrzetw.Turn(occupied->Power110vIsAvailable); - btLampkaPrzetwOff.Turn(!occupied->Power110vIsAvailable); + btLampkaPrzetw.Turn(occupied->lowVoltage.power110vAvailable); + btLampkaPrzetwOff.Turn(!occupied->lowVoltage.power110vAvailable); btLampkaPrzetwAOff.Turn(!controlled->converter.running); btLampkaNadmPrzetw.Turn(Dynamic()->Mechanik ? Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : controlled->converter.overloaded); @@ -909,8 +909,8 @@ void TTrain::updateTrainLamps() } default: { - btLampkaHamienie.Turn(occupied->brakes.cylinderPressure >= 0.1 || controlled->DynamicBrakeFlag); - btLampkaBrakingOff.Turn(occupied->brakes.cylinderPressure < 0.1 && !controlled->DynamicBrakeFlag); + btLampkaHamienie.Turn(occupied->brakes.cylinderPressure >= 0.1 || controlled->brakes.electrodynamic.on); + btLampkaBrakingOff.Turn(occupied->brakes.cylinderPressure < 0.1 && !controlled->brakes.electrodynamic.on); break; } } @@ -958,7 +958,7 @@ void TTrain::updateTrainLamps() btLampkaNeutral.Turn(controlled->DirActive == 0); // kierunek neutral } - btLampkaED.Turn(controlled->DynamicBrakeFlag); // hamulec ED + btLampkaED.Turn(controlled->brakes.electrodynamic.on); // hamulec ED btLampkaBrakeProfileG.Turn(TestFlag(occupied->brakes.delaySetting, bdelay_G)); btLampkaBrakeProfileP.Turn(TestFlag(occupied->brakes.delaySetting, bdelay_P)); btLampkaBrakeProfileR.Turn(TestFlag(occupied->brakes.delaySetting, bdelay_R)); @@ -1189,8 +1189,8 @@ void TTrain::updateMasterControllers(bool const lowvoltagepower) 1}; // when SplitEDPneumaticBrake is active the negative range of the joint controller // represents the dedicated dynamic-brake lever (DBPN steps), not the pneumatic local brake - auto const negativePart{controlled->SplitEDPneumaticBrake ? - (controlled->DynamicBrakeCtrlPos > 0.0 ? controlled->DynamicBrakeCtrlPos * controlled->DynamicBrakeCtrlPosNo * -1 * brakerangemultiplier : 0.0) : + auto const negativePart{controlled->brakes.electrodynamic.splitFromPneumatic ? + (controlled->brakes.electrodynamic.controllerPosition > 0.0 ? controlled->brakes.electrodynamic.controllerPosition * controlled->brakes.electrodynamic.controllerPositions * -1 * brakerangemultiplier : 0.0) : occupied->brakes.independentPosition > 0.0 ? occupied->brakes.independentPosition * LocalBrakePosNo * -1 * brakerangemultiplier : 0.0}; ggJointCtrl.UpdateValue(negativePart < 0.0 ? static_cast(negativePart) : @@ -1232,7 +1232,7 @@ void TTrain::updateMasterControllers(bool const lowvoltagepower) // Ra: od byte odejmowane boolean i konwertowane potem na double? if (false == ggScndCtrl.is_push()) { - ggScndCtrl.UpdateValue(static_cast(double(controlled->ScndCtrlPos - (controlled->TrainType == train_type::et42 && controlled->DynamicBrakeFlag))), dsbNastawnikBocz); + ggScndCtrl.UpdateValue(static_cast(double(controlled->ScndCtrlPos - (controlled->TrainType == train_type::et42 && controlled->brakes.electrodynamic.on))), dsbNastawnikBocz); } ggScndCtrl.Update(); } @@ -1374,7 +1374,7 @@ void TTrain::updateHeatingAndInstrumentLights() { //--------- // hunter-080812: poprawka na ogrzewanie w elektrykach - usuniete uzaleznienie od przetwornicy - if (controlled->Heating == true && controlled->converter.overloaded == false) + if (controlled->trainHeating.on == true && controlled->converter.overloaded == false) btLampkaOgrzewanieSkladu.Turn(true); else btLampkaOgrzewanieSkladu.Turn(false); @@ -1382,11 +1382,11 @@ void TTrain::updateHeatingAndInstrumentLights() //---------- // lights - auto const lightpower{(InstrumentLightType == 0 ? occupied->Power24vIsAvailable || occupied->Power110vIsAvailable : + auto const lightpower{(InstrumentLightType == 0 ? occupied->lowVoltage.power24vAvailable || occupied->lowVoltage.power110vAvailable : InstrumentLightType == 1 ? controlled->lineBreaker.closed : - InstrumentLightType == 2 ? occupied->Power110vIsAvailable : - InstrumentLightType == 3 ? occupied->Power24vIsAvailable || occupied->Power110vIsAvailable : - InstrumentLightType == 4 ? occupied->Power24vIsAvailable || occupied->Power110vIsAvailable : + InstrumentLightType == 2 ? occupied->lowVoltage.power110vAvailable : + InstrumentLightType == 3 ? occupied->lowVoltage.power24vAvailable || occupied->lowVoltage.power110vAvailable : + InstrumentLightType == 4 ? occupied->lowVoltage.power24vAvailable || occupied->lowVoltage.power110vAvailable : false)}; InstrumentLightActive = InstrumentLightType == 3 ? true : // TODO: link the light state with the state of the master key InstrumentLightType == 4 ? occupied->iLights[VehicleEnd::front] != 0 || occupied->iLights[VehicleEnd::rear] != 0 : @@ -1574,7 +1574,7 @@ void TTrain::updateCabLightLevels() for (auto &cab : Cabine) { - auto const cablightlevel = (cab.bLight == false ? 0.f : cab.bLightDim == true ? 0.4f : 1.f) * (occupied->Power110vIsAvailable ? 1.f : 0.5f); + auto const cablightlevel = (cab.bLight == false ? 0.f : cab.bLightDim == true ? 0.4f : 1.f) * (occupied->lowVoltage.power110vAvailable ? 1.f : 0.5f); if (cab.LightLevel != cablightlevel) { @@ -1593,21 +1593,21 @@ void TTrain::updateCabLightLevels() void TTrain::UpdateDirectionRelays() { - if (occupied->DirActive < 0 && occupied->Power24vIsAvailable) // wstecz + if (occupied->DirActive < 0 && occupied->lowVoltage.power24vAvailable) // wstecz Dynamic()->sDirectionRelayR.play(); - if (occupied->DirActive == 0 && occupied->Power24vIsAvailable) // neutral + if (occupied->DirActive == 0 && occupied->lowVoltage.power24vAvailable) // neutral Dynamic()->sDirectionRelayN.play(); - if (occupied->DirActive > 0 && occupied->Power24vIsAvailable) // przod + if (occupied->DirActive > 0 && occupied->lowVoltage.power24vAvailable) // przod Dynamic()->sDirectionRelayD.play(); } void TTrain::SetupDirectionRelays() { - if (occupied->Power24vIsAvailable) + if (occupied->lowVoltage.power24vAvailable) { - if (occupied->DirActive < 0 && occupied->Power24vIsAvailable) // wstecz + if (occupied->DirActive < 0 && occupied->lowVoltage.power24vAvailable) // wstecz Dynamic()->sDirectionRelayR.play(); - if (occupied->DirActive > 0 && occupied->Power24vIsAvailable) // przod + if (occupied->DirActive > 0 && occupied->lowVoltage.power24vAvailable) // przod Dynamic()->sDirectionRelayD.play(); } else if (occupied->DirActive != 0) // neutral diff --git a/vehicle/drivingaid.cpp b/vehicle/drivingaid.cpp index 1638c4ddd..9b67d967d 100644 --- a/vehicle/drivingaid.cpp +++ b/vehicle/drivingaid.cpp @@ -63,11 +63,11 @@ input from_vehicles(physics::Vehicle const &Vehicle, physics::Vehicle const &Con input result; result.eim = Vehicle.EngineType == TEngineType::ElectricInductionMotor || Vehicle.EIMCtrlType > 0; result.eimctrltype = Vehicle.EIMCtrlType; - result.splited = Controlling.SplitEDPneumaticBrake; + result.splited = Controlling.brakes.electrodynamic.splitFromPneumatic; result.integratedbrake = Vehicle.UniCtrlIntegratedBrakeCtrl; result.eimic_real = Vehicle.eimic_real; - result.dynamicbrakepos = Controlling.DynamicBrakeCtrlPos; - result.dynamicbrakeposno = Controlling.DynamicBrakeCtrlPosNo; + result.dynamicbrakepos = Controlling.brakes.electrodynamic.controllerPosition; + result.dynamicbrakeposno = Controlling.brakes.electrodynamic.controllerPositions; result.mainctrlpos = Controlling.MainCtrlPos; result.scndctrlpos = Controlling.ScndCtrlPos; result.brakectrlpos = Vehicle.brakes.handlePositionSmooth; diff --git a/vehicle/dynamic/destinations.cpp b/vehicle/dynamic/destinations.cpp index e8ca19457..6311c8799 100644 --- a/vehicle/dynamic/destinations.cpp +++ b/vehicle/dynamic/destinations.cpp @@ -106,7 +106,7 @@ void TDynamicObject::update_destinations() { if( DestinationSign.sign == nullptr ) { return; } - auto const lowvoltagepower { ( physics->Power24vIsAvailable || physics->Power110vIsAvailable ) }; + auto const lowvoltagepower { ( physics->lowVoltage.power24vAvailable || physics->lowVoltage.power110vAvailable ) }; DestinationSign.sign->fLight = DestinationSign.has_light && lowvoltagepower ? 2.0 : -1.0; diff --git a/vehicle/dynamic/sounds.cpp b/vehicle/dynamic/sounds.cpp index 144d8e776..b9f948111 100644 --- a/vehicle/dynamic/sounds.cpp +++ b/vehicle/dynamic/sounds.cpp @@ -137,7 +137,7 @@ void TDynamicObject::renderAuxiliarySounds() { // Odtworzenie dzwieku wentylatora rezystora hamowania - if (physics->BRVentilators) + if (physics->brakes.electrodynamic.resistorFansRunning) { sBRVent.play(sound_flags::exclusive | sound_flags::looping); } @@ -197,7 +197,7 @@ void TDynamicObject::renderAuxiliarySounds() { // heater sound { auto const isdieselenginepowered { physics->EngineType == TEngineType::DieselElectric || physics->EngineType == TEngineType::DieselEngine }; - if( true == physics->Heating + if( true == physics->trainHeating.on && ( false == isdieselenginepowered || std::abs(physics->enrot) > 0.01 ) ) { sHeater @@ -212,7 +212,7 @@ void TDynamicObject::renderAuxiliarySounds() { } // battery sound - if( physics->Battery ) { + if( physics->lowVoltage.batteryOn ) { m_batterysound.play( sound_flags::exclusive | sound_flags::looping ); } else { @@ -487,7 +487,7 @@ void TDynamicObject::renderDepartureSignalSounds() { // NBMX sygnal odjazdu if( physics->Doors.has_warning ) { - auto const lowvoltagepower { physics->Power24vIsAvailable || physics->Power110vIsAvailable }; + auto const lowvoltagepower { physics->lowVoltage.power24vAvailable || physics->lowVoltage.power110vAvailable }; for( auto &doorspeaker : m_doorspeakers ) { // TBD, TODO: per-location door state triggers? if( physics->DepartureSignal @@ -514,7 +514,7 @@ void TDynamicObject::renderAnnouncementSounds() { // announcements { - auto const lowvoltagepower { physics->Power24vIsAvailable || physics->Power110vIsAvailable }; + auto const lowvoltagepower { physics->lowVoltage.power24vAvailable || physics->lowVoltage.power110vAvailable }; if( lowvoltagepower ) { // system is powered up, can play queued announcements if( false == m_pasystem.announcement_queue.empty() @@ -1398,7 +1398,7 @@ TDynamicObject::powertrain_sounds::renderTractionMotorSounds( physics::Vehicle c } } - if( Vehicle.DynamicBrakeFlag + if( Vehicle.brakes.electrodynamic.on && Vehicle.EnginePower > 0.1 ) { // Szociu - 29012012 - jeżeli uruchomiony jest hamulec elektrodynamiczny, odtwarzany jest dźwięk silnika volume += 0.8; diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index 6e929c902..6d41fb379 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -735,7 +735,7 @@ void TDynamicObject::switchOffMainsWithoutBattery() { // fragment "z EXE Kursa" if( physics->lineBreaker.closed ) { // nie wchodzić w funkcję bez potrzeby - if( false == (physics->Power24vIsAvailable || physics->Power110vIsAvailable) + if( false == (physics->lowVoltage.power24vAvailable || physics->lowVoltage.power110vAvailable) /* // NOTE: disabled on account of multi-unit setups, where the unmanned unit wouldn't be affected && ( Controller == Humandriver ) @@ -1180,7 +1180,7 @@ void TDynamicObject::updatePantographMotion( int const i, TAnimPant *p, double c else { pantspeedfactor = 0.0; } - if( false == ( physics->Power24vIsAvailable || physics->Power110vIsAvailable ) ) { + if( false == ( physics->lowVoltage.power24vAvailable || physics->lowVoltage.power110vAvailable ) ) { pantspeedfactor = 0.0; } pantspeedfactor = std::max( 0.0, pantspeedfactor ); @@ -1282,12 +1282,12 @@ void TDynamicObject::updateWipers( double const dt1 ) // rozroznienie kabinowe if (physics->CabActive == 1) { - wipersActive = (bytesum & 1 << i) != 0 && physics->Battery; + wipersActive = (bytesum & 1 << i) != 0 && physics->lowVoltage.batteryOn; } else if (physics->CabActive == -1) { // odwroconie indexow wycieraczek - wipersActive = (bytesum & 1 << dWiperPos.size() - 1 - i) != 0 && physics->Battery; + wipersActive = (bytesum & 1 << dWiperPos.size() - 1 - i) != 0 && physics->lowVoltage.batteryOn; } else { wipersActive = false; diff --git a/vehicle/dynamic/visual.cpp b/vehicle/dynamic/visual.cpp index 60a1c5c4b..75dc89a72 100644 --- a/vehicle/dynamic/visual.cpp +++ b/vehicle/dynamic/visual.cpp @@ -345,7 +345,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) btnOn = true; } // else btCPass2.TurnOff(); - if (physics->Power24vIsAvailable || physics->Power110vIsAvailable) + if (physics->lowVoltage.power24vAvailable || physics->lowVoltage.power110vAvailable) { // sygnaly konca pociagu if (m_endsignals1.Active()) { if (TestFlag(physics->iLights[VehicleEnd::front], light::redmarker_left | light::redmarker_right ) ) { @@ -433,7 +433,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } // vehicle within 400m - if( physics->Power24vIsAvailable || physics->Power110vIsAvailable ) + if( physics->lowVoltage.power24vAvailable || physics->lowVoltage.power110vAvailable ) { // sygnały czoła pociagu //Ra: wyświetlamy bez // ograniczeń odległości, by były widoczne z // daleka diff --git a/widgets/vehicleparams.cpp b/widgets/vehicleparams.cpp index 321cee7de..6bb8274b9 100644 --- a/widgets/vehicleparams.cpp +++ b/widgets/vehicleparams.cpp @@ -68,7 +68,7 @@ void ui::vehicleparams_panel::draw_mini(const physics::Vehicle &physics) if (physics.pantographs[VehicleEnd::front].is_active) draw_infobutton("╨╨╨", ImVec2(290, 10)); - if (physics.Battery) + if (physics.lowVoltage.batteryOn) draw_infobutton(STR_C("bat."), ImVec2(120, 55)); if (physics.lineBreaker.closed) draw_infobutton(STR_C("main.")); @@ -148,7 +148,7 @@ void ui::vehicleparams_panel::render_contents() std::snprintf(buffer.data(), buffer.size(), STR_C("Devices: %c%c%c%c%c%c%c%c%c%c%c%c%c%c%s%s\nPower transfers: %.0f@%.0f%s%s%s%.0f@%.0f"), // devices - (physics.Battery ? 'B' : '.'), (physics.lineBreaker.closed ? 'M' : '.'), (physics.FuseFlag ? '!' : '.'), (physics.pantographs[VehicleEnd::rear].is_active ? (physics.pantographCircuit.rearVoltage > 0.0 ? 'O' : 'o') : '.'), + (physics.lowVoltage.batteryOn ? 'B' : '.'), (physics.lineBreaker.closed ? 'M' : '.'), (physics.FuseFlag ? '!' : '.'), (physics.pantographs[VehicleEnd::rear].is_active ? (physics.pantographCircuit.rearVoltage > 0.0 ? 'O' : 'o') : '.'), (physics.pantographs[VehicleEnd::front].is_active ? (physics.pantographCircuit.frontVoltage > 0.0 ? 'P' : 'p') : '.'), (physics.pantographAir.pressureLockActive ? '!' : (physics.pantographAir.pressureSwitchActive ? '*' : '.')), (physics.WaterPump.is_active ? 'W' : (false == physics.WaterPump.breaker ? '-' : (physics.WaterPump.is_enabled ? 'w' : '.'))), (true == physics.WaterHeater.is_damaged ? '!' : (physics.WaterHeater.is_active ? 'H' : (false == physics.WaterHeater.breaker ? '-' : (physics.WaterHeater.is_enabled ? 'h' : '.')))), From 6aca6bc4f65f72a9ef60ccc53f8e8dd423c8f03a Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 04:13:17 +0100 Subject: [PATCH 034/123] fix(review): an empty Load= no longer throws, and the stale notes of the review of #531 From the review of #531: - Load= and UnLoad= without the name of a load threw std::out_of_range as soon as ParseVehicleCommand() read them: extract_value() reads past the end of the text when nothing but spaces follows the =. Before this branch the same exception came later, in the RunCommand() of a vehicle standing at the ramp. ParseVehicleCommand() gives an empty name now, which loads and unloads nothing (AssignLoad("") and LoadingDone() with no name, as for an empty vehicle). extract_value() itself is left as it was: it has hundreds of callers and test_utilities.cpp records its exception at the end of the text. New checks in test_vehicle_command.cpp. - compression_at() is an inline function of physics/components/internal.h, as square() is, rather than a global function of external linkage defined in collisions.cpp; its body is the same - the comment of train_type::sn61 says what the AI does for it (the master controller up to a position with torque after setting the direction) rather than that nothing handles it - tests/unit/COVERAGE.md names the files as they are now (physics/components/, vehicle/dynamic/lifecycle.cpp) instead of physics/physics.cpp, a name the renaming script left there The naming of AGENTS.md, which the review asked about, stays as it is. --- physics/components/collisions.cpp | 6 ------ physics/components/internal.h | 8 +++++++- physics/vehiclecommand.cpp | 15 +++++++++++++-- physics/vehicletypes.h | 2 +- tests/unit/COVERAGE.md | 10 +++++----- tests/unit/test_vehicle_command.cpp | 8 ++++++++ 6 files changed, 34 insertions(+), 15 deletions(-) diff --git a/physics/components/collisions.cpp b/physics/components/collisions.cpp index 347100559..e46bae097 100644 --- a/physics/components/collisions.cpp +++ b/physics/components/collisions.cpp @@ -304,12 +304,6 @@ char const *kind_name(collision::vehicle_kind const Kind) } } // namespace - -// the force pressing the end in, of the coupling or of the buffers touching [N]: forwards at the front pulls -double compression_at(TCoupling const &Coupler, VehicleEnd const End) -{ - return std::max(0.0, (End == VehicleEnd::front ? -1.0 : 1.0) * Coupler.CForce); -} namespace { diff --git a/physics/components/internal.h b/physics/components/internal.h index 4cdcbe668..b469abbc5 100644 --- a/physics/components/internal.h +++ b/physics/components/internal.h @@ -11,6 +11,8 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include + #include "physics/vehicle.h" const double CouplerTune = 0.1; // skalowanie tlumiennosci @@ -27,7 +29,11 @@ int DirF(VehicleEnd CouplerN); double TableInterpolation(std::map &Map, double Parameter); -double compression_at(TCoupling const &Coupler, VehicleEnd const End); +// the force pressing the end in, of the coupling or of the buffers touching [N]: forwards at the front pulls +inline double compression_at(TCoupling const &Coupler, VehicleEnd const End) +{ + return std::max(0.0, (End == VehicleEnd::front ? -1.0 : 1.0) * Coupler.CForce); +} bool issection(std::string_view Name, std::string_view Input); diff --git a/physics/vehiclecommand.cpp b/physics/vehiclecommand.cpp index 9b8e6fc72..c07b0546f 100644 --- a/physics/vehiclecommand.cpp +++ b/physics/vehiclecommand.cpp @@ -84,6 +84,17 @@ constexpr std::array, 59> commandNam {unknown, ""}, }}; +// the name of the load after Load= or UnLoad= (key) at the start of the text, empty when nothing follows the = but +// spaces: extract_value() would throw there, reading past the end of the text +std::string loadName(std::string_view const key, std::string_view const text) +{ + if (text.find_first_not_of(' ', key.size() + 1) == std::string_view::npos) + { + return {}; + } + return extract_value(std::string{key}, std::string{text}); +} + } // namespace ParsedVehicleCommand ParseVehicleCommand(std::string const &Text) @@ -95,11 +106,11 @@ ParsedVehicleCommand ParseVehicleCommand(std::string const &Text) // Load= and UnLoad= begin the text, the name of the load follows if (Text.starts_with("Load=")) { - return {load, extract_value("Load", Text)}; + return {load, loadName("Load", Text)}; } if (Text.starts_with("UnLoad=")) { - return {unload, extract_value("UnLoad", Text)}; + return {unload, loadName("UnLoad", Text)}; } auto const named{std::ranges::find(commandNames, std::string_view{Text}, &std::pair::second)}; if (named == commandNames.end() || named->first == load || named->first == unload) diff --git a/physics/vehicletypes.h b/physics/vehicletypes.h index 7c1c01572..79ecd2ea5 100644 --- a/physics/vehicletypes.h +++ b/physics/vehicletypes.h @@ -499,7 +499,7 @@ enum class train_type et42, /// EP05 locomotive. ep05, - /// SN61 railcar: the type is read, but nothing handles it on its own. + /// SN61 railcar: the physics has nothing of its own for it; the AI, after setting the direction, moves the master controller up to a position with engine torque so the engine doesn't stall (TController::DirectionForward()). sn61, /// Pseudo-diesel (an electric drivetrain with the input model of a diesel). pseudodiesel, diff --git a/tests/unit/COVERAGE.md b/tests/unit/COVERAGE.md index 2d9774239..74eacedcd 100644 --- a/tests/unit/COVERAGE.md +++ b/tests/unit/COVERAGE.md @@ -1,6 +1,6 @@ # Coverage of the simulation core by the unit tests -These tests characterise the physics of the vehicles (`physics/physics.cpp`, `brakes.cpp`, `oerlikonest.cpp`, `friction.cpp`). They exist to show that refactors of those files, such as splitting `TractionForce` or `RunCommand`, leave the behaviour as it was. This page lists: +These tests characterise the physics of the vehicles (`physics/components/*.cpp`, once `Mover.cpp`; `physics/brakes.cpp`, `oerlikonest.cpp`, `friction.cpp`). They exist to show that refactors of those files, such as splitting `TractionForce` or `RunCommand`, leave the behaviour as it was. This page lists: - what the tests reach; - what nothing in the game ever runs; @@ -14,7 +14,7 @@ Coverage was measured on Windows with MSVC's SanitizerCoverage (`/fsanitize-cove | File | Blocks run, at the start | Now | |---|---|---| -| `physics.cpp` | 8.9% | 80.7% (3323 of 4118) | +| `Mover.cpp` (now `physics/components/*.cpp`) | 8.9% | 80.7% (3323 of 4118) | | `brakes.cpp` | 30% | 76.3% (649 of 851) | | `oerlikonest.cpp` | 58% | 87.4% (118 of 135) | | `friction.cpp` | 9% | 90.9% (10 of 11) | @@ -35,7 +35,7 @@ Nothing creates these objects or calls these functions anywhere in the game, whi - **Base implementations always overridden:** `TFricMat::GetFC` (every material, the default P10 too, has its own) and `TPrzekladnik::Update` (every relay has its own). - **Functions without callers:** - In `brakes.cpp`: `PF_old`, `TBrake::GetBCF`, `TDriverHandle::OvrldButton`, `TReservoir::pa` and `TBrakeCyl::pa`. - - In `physics.cpp`: `BrakeVP`, `PipeRatio`, `RealPipeRatio`, `IncBrakeLevel`, `DecBrakeLevel`, `IncBrakePress`, `DecBrakePress` and `MainCtrlActualPowerPos`. (`GetExternalCommand` was removed.) + - In `physics/components/pneumatics.cpp`: `BrakeVP`, `PipeRatio`, `RealPipeRatio`, `IncBrakeLevel`, `DecBrakeLevel`, `IncBrakePress` and `DecBrakePress`; in `physics/components/controllers.cpp`: `MainCtrlActualPowerPos`. (`GetExternalCommand` was removed.) - **Inverter failures** of the induction motor drives (`inverter::Failure_Drive`, `Failure_Const`, `Activate`): nothing ever sets them. The cab only shows them. The branches reading them in `TractionForce` can't be reached. ## Code only data no game vehicle has would run @@ -60,7 +60,7 @@ Where it was worth it, a test fits the missing parameter to a real vehicle or bu These are run by the game, by vehicles it has or by the cab, the AI or the scenery, but no test reaches them yet. Most of them are the far sides of conditions inside functions the tests do run. - **Entry points from outside the core:** - - `TBrake::ForceEmptiness` and its overrides: a scenario's vehicle set up with empty brakes (`DynObj.cpp`). + - `TBrake::ForceEmptiness` and its overrides: a scenario's vehicle set up with empty brakes (`vehicle/dynamic/lifecycle.cpp`). - `TBrake::GetSoundFlag`: the sounds of the brakes. - `LoadFIZ` and `reload_FIZ`: the file loading around `LoadFIZ_Text`, which the tests call directly. - `TSecuritySystem::set_cabsignal_lock`. @@ -163,7 +163,7 @@ The tests are written for the first two columns, and for what the game doesn't c The tests record the behaviour as it is. The following points may deserve a look by someone who knows how the real vehicles behave. -- **`Random(10) - Random(10)` (`physics.cpp`, the noise of the control pipe pressure `CntrlPipePress`):** the order the two calls were evaluated in isn't specified. MSVC Release, MSVC Debug and GCC gave different traces, a control pipe pressure mirrored around 5 bar, which failed 32 tests on the Linux CI. Fixed: the draws are sequenced in the order of MSVC Release, which the golden traces were recorded with. +- **`Random(10) - Random(10)` (`physics/components/fizsections.cpp`, the noise of the control pipe pressure `brakes.controlReservoirPressure`, `CntrlPipePress` before):** the order the two calls were evaluated in isn't specified. MSVC Release, MSVC Debug and GCC gave different traces, a control pipe pressure mirrored around 5 bar, which failed 32 tests on the Linux CI. Fixed: the draws are sequenced in the order of MSVC Release, which the golden traces were recorded with. - **`TCommand::Location` isn't initialised** in a new vehicle. The game always sets it through `PutCommand()`, but a test calling `RunCommand()` directly got different results run to run. - **The `CompressorList` table (`air.compressor.list`) holds `int`s** (`physics/components/airsupply.h`), though its factors are fractions: 0.9 is read as 0. No game vehicle has the list yet. - **A train whose pipe leaks under 2.75 bar before its start-up can't be released:** diff --git a/tests/unit/test_vehicle_command.cpp b/tests/unit/test_vehicle_command.cpp index 737d66431..84701e416 100644 --- a/tests/unit/test_vehicle_command.cpp +++ b/tests/unit/test_vehicle_command.cpp @@ -37,6 +37,14 @@ TEST_CASE("vehicle commands: the empty text, an unknown one, the load") { CHECK(unload.command == VehicleCommand::unload); CHECK(unload.argument == "passengers"); + // a load without a name is a load of no name, not an exception: the vehicle loads nothing for it + auto const noname{ParseVehicleCommand("Load=")}; + CHECK(noname.command == VehicleCommand::load); + CHECK(noname.argument.empty()); + CHECK(ParseVehicleCommand("UnLoad= ").argument.empty()); + // a space after the = is skipped, as extract_value() does + CHECK(ParseVehicleCommand("Load= Coal").argument == "Coal"); + CHECK(VehicleCommandName(VehicleCommand::none).empty()); CHECK(VehicleCommandName(VehicleCommand::unknown).empty()); CHECK(VehicleCommandName(VehicleCommand::integratedController) == "EIMIC"); From 5d3b3bc09503da8b8283514f71896da8cef7224b Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 08:27:14 +0100 Subject: [PATCH 035/123] fix(debug): the couplings in the coupler line of the debug panel as a number, not the set The coupler line of the debug panel passed the CouplingSet itself to snprintf under %d. A class object through varargs is undefined behaviour (SonarCloud S2275, a blocker on #531); it now passes CouplingFlag.Bits(), the same number the line showed before. --- application/driveruipanels.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 15ff54b1a..3e3ce61f0 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -1054,7 +1054,7 @@ debug_panel::update_vehicle_coupler( VehicleEnd const Side ) { controltype.c_str(), connected->name().c_str(), adapterstatus.c_str(), - physics.Couplers[ Side ].CouplingFlag, + physics.Couplers[ Side ].CouplingFlag.Bits(), physics.Neighbours[ Side ].distance ); return { m_buffer.data() }; From dc7bd0efe6e5dd9d14695f047dbb709d47b31828 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 08:36:15 +0100 Subject: [PATCH 036/123] fix(vehicle): the headlight dimmer by the active cab, the pantograph by its end SetLightDimmings(), which the dimmer commands of the cab and the AI's hints call, picked the headlights to put out by iDirection, while RaLightsSet() picks them by the active cab (CabEnd(CabActive)) since the mover became physics::Vehicle. From cab -1 with iDirection > 0 the dimmer put out A and RaLightsSet() B, so both ends went dark. Both now use the end of the active cab: cab 1 the A headlights, cab -1 the B ones, and none without an active cab. This changes behaviour against staging, where RaLightsSet() compared CabActive with the end numbers (0 put out A, 1 put out B, -1 nothing) and SetLightDimmings() went by iDirection. updatePantographMotion() read pantographs[i] by the animation index, past the two ends for a model with more than two pantograph animations (an old fault, staging DynObj.cpp). It reads pantographs[PantographEnd(i)] now, as the voltage and the count of raised pantographs already do. --- vehicle/dynamic/lights.cpp | 27 ++++++--------------------- vehicle/dynamic/update.cpp | 2 +- 2 files changed, 7 insertions(+), 22 deletions(-) diff --git a/vehicle/dynamic/lights.cpp b/vehicle/dynamic/lights.cpp index 11ea04fc8..663469aa9 100644 --- a/vehicle/dynamic/lights.cpp +++ b/vehicle/dynamic/lights.cpp @@ -162,7 +162,6 @@ void TDynamicObject::RaLightsSet(int head, int rear) void TDynamicObject::SetLightDimmings() { - auto const vehicleend{iDirection > 0 ? VehicleEnd::front : VehicleEnd::rear}; if (Controller == Humandriver) { @@ -172,36 +171,22 @@ void TDynamicObject::SetLightDimmings() HighBeamLights = false; DimHeadlights = false; - // obsługa OFF + // obsługa OFF: the headlights at the end of the active cab, as RaLightsSet() picks them: A at the front, B at the + // rear, none without an active cab if (dps.isOff) { - // physics->iLights[vehicleend] &= 0 | light::rearendsignals; // zostawiamy tylko tabliczki jesli sa HighBeamLights = false; DimHeadlights = false; - switch (vehicleend) + if (auto const cabend{CabEnd(physics->CabActive)}; cabend.has_value()) { - case VehicleEnd::front: - HeadlightsAoff = true; - break; - case VehicleEnd::rear: - HeadlightsBoff = true; - break; - default: - break; + (*cabend == VehicleEnd::front ? HeadlightsAoff : HeadlightsBoff) = true; } } else { - switch (vehicleend) + if (auto const cabend{CabEnd(physics->CabActive)}; cabend.has_value()) { - case VehicleEnd::front: - HeadlightsAoff = false; - break; - case VehicleEnd::rear: - HeadlightsBoff = false; - break; - default: - break; + (*cabend == VehicleEnd::front ? HeadlightsAoff : HeadlightsBoff) = false; } } diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index 6d41fb379..4c70f7979 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -1186,7 +1186,7 @@ void TDynamicObject::updatePantographMotion( int const i, TAnimPant *p, double c pantspeedfactor = std::max( 0.0, pantspeedfactor ); k = p->fAngleL; if( pantspeedfactor > 0.0 - && physics->pantographs[i].is_active )// jeśli ma być podniesiony + && physics->pantographs[PantographEnd( i )].is_active )// jeśli ma być podniesiony { if (PantDiff > 0.001) // jeśli nie dolega do drutu { // jeśli poprzednia wysokość jest mniejsza niż pożądana, zwiększyć kąt dolnego From 12c5bb35e712fa2a778a6826d951568f03600a01 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 08:36:30 +0100 Subject: [PATCH 037/123] refactor(vehicle): the helpers of the split files out of the global namespace The split of Driver.cpp, DynObj.cpp and Train.cpp took five helpers out of their anonymous namespaces. outside() is used in offtrack.cpp alone and goes back into its anonymous namespace. The four shared by the parts of a class go into a namespace of its module: vehicle_ai (brake_response_horizon, uphill_stopping_distance), vehicle_dynamic (seconds_since) and vehicle_cab (is_hold_coil_lever). The rename of mover to physics also hit comments where the word meant something else: "prime mover" and "move the master controller" are back. --- physics/components/fizsections.cpp | 2 +- physics/vehicle.h | 4 ++-- vehicle/Train.h | 2 +- vehicle/ai/controls.cpp | 2 +- vehicle/ai/force.cpp | 6 +++--- vehicle/ai/internal.h | 5 +++++ vehicle/ai/speed.cpp | 16 ++++++++-------- vehicle/cab/internal.h | 6 ++++++ vehicle/cab/powercommands.cpp | 8 ++++---- vehicle/cab/train.cpp | 2 +- vehicle/cab/update.cpp | 2 +- vehicle/dynamic/internal.h | 7 +++++-- vehicle/dynamic/offtrack.cpp | 10 +++++----- vehicle/dynamic/update.cpp | 2 +- vehicle/dynamic/vehicletable.cpp | 2 +- 15 files changed, 45 insertions(+), 31 deletions(-) diff --git a/physics/components/fizsections.cpp b/physics/components/fizsections.cpp index d32c1bda1..f75fb011f 100644 --- a/physics/components/fizsections.cpp +++ b/physics/components/fizsections.cpp @@ -1694,7 +1694,7 @@ void physics::Vehicle::LoadFIZ_PowerParamsDecode(TPowerParameters &Powerparamete } case TPowerSource::Generator: { - // prime physics for the generator + // prime mover for the generator auto &generatorparameters{Powerparameters.EngineGenerator}; if (auto const enginetype{LoadFIZ_EngineDecode(extract_value(Prefix + "GeneratorEngine", Line))}; enginetype == TEngineType::Main) diff --git a/physics/vehicle.h b/physics/vehicle.h index f10c8a038..d106a243c 100644 --- a/physics/vehicle.h +++ b/physics/vehicle.h @@ -212,8 +212,8 @@ enum class TPowerSource struct engine_generator { // ld inputs - /// Pointer to the prime-physics revolutions [rev/s]. - double *engine_revolutions; // revs per second of the prime physics + /// Pointer to the prime-mover revolutions [rev/s]. + double *engine_revolutions; // revs per second of the prime mover // config /// Minimum working rev rate [rev/s]. double revolutions_min; // min working revolutions rate, in revs per second diff --git a/vehicle/Train.h b/vehicle/Train.h index ce5ea2def..078a06064 100644 --- a/vehicle/Train.h +++ b/vehicle/Train.h @@ -248,7 +248,7 @@ class TTrain { return ggHornButton.SubModel != nullptr && ggHornLowButton.SubModel == nullptr && ggHornHighButton.SubModel == nullptr; } // locates nearest vehicle belonging to the consist TDynamicObject *find_nearest_consist_vehicle(bool freefly, glm::vec3 pos) const; - // physics master controller to specified position + // move the master controller to specified position void set_master_controller( double const Position ); // moves train brake lever to specified position, potentially emits switch sound if conditions are met void set_train_brake( double const Position ); diff --git a/vehicle/ai/controls.cpp b/vehicle/ai/controls.cpp index 0d5552e7c..37e7d314e 100644 --- a/vehicle/ai/controls.cpp +++ b/vehicle/ai/controls.cpp @@ -107,7 +107,7 @@ TController::increase_train_brake() { occupied->brakes.delays[ 3 ] ) // a train falling further behind needs no full fill time to be seen not to get enough || ( ( fShortfall > 0.02 ) - && ( fBrakeHeldTime > brake_response_horizon( occupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) ) { + && ( fBrakeHeldTime > vehicle_ai::brake_response_horizon( occupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) ) { // the table says the present position is enough, but the brake has had its full fill // time since the handle last moved and the train is still not slowing down as asked: // believe the train rather than the table diff --git a/vehicle/ai/force.cpp b/vehicle/ai/force.cpp index e97905230..69967d99e 100644 --- a/vehicle/ai/force.cpp +++ b/vehicle/ai/force.cpp @@ -421,7 +421,7 @@ TController::uphill_brake_committed( double const Velocity ) const { ( BrakeSystem == TBrakeSystem::Pneumatic ) && ( BrakeCtrlPosition > 0.0 ) && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) - && ( Velocity / 3.6 / -fAccGravity < brake_response_horizon( occupied, BrakeSystem, -1.0, fBrake_a0[ 0 ] ) ) ); + && ( Velocity / 3.6 / -fAccGravity < vehicle_ai::brake_response_horizon( occupied, BrakeSystem, -1.0, fBrake_a0[ 0 ] ) ) ); } void TController::control_braking_force() { @@ -512,7 +512,7 @@ void TController::control_braking_force() { && ( BrakeCtrlPosition > 0.0 ) && ( fShortfall > 0.02 ) && ( iShortfallGrowth >= 2 ) - && ( fBrakeHeldTime > brake_response_horizon( occupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) { + && ( fBrakeHeldTime > vehicle_ai::brake_response_horizon( occupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) { // the train has been falling further behind the demand for a while at a handle left alone for longer than // the brake takes to respond: a small step now, while it still is small, rather than the deep one the // margin above would allow only once the train is far behind @@ -544,7 +544,7 @@ void TController::control_braking_force() { && ( ( uphill_stop_hold() && ( std::abs( velocity ) < 3.0 ) // a train that has slowed down short of where it is to stop and is to pull up further does not get it && ( VelDesired <= std::abs( velocity ) + 0.5 ) - && ( ActualProximityDist - uphill_stopping_distance( std::abs( velocity ), fAccGravity ) <= stopping_margin() ) ) + && ( ActualProximityDist - vehicle_ai::uphill_stopping_distance( std::abs( velocity ), fAccGravity ) <= stopping_margin() ) ) || ( ( BrakeSystem == TBrakeSystem::Pneumatic ) && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) && ( velocity < -0.1 ) && ( AccDesired <= 0.0 ) ) ) ) { cue_action( driver_hint::independentbrakeapply ); } diff --git a/vehicle/ai/internal.h b/vehicle/ai/internal.h index f155cf57d..adda3a7ea 100644 --- a/vehicle/ai/internal.h +++ b/vehicle/ai/internal.h @@ -108,8 +108,13 @@ const double EasyReactionTime = 0.5; //[s] przebłyski świadomości dla zwykłe const double PrepareTime = 2.0; //[s] przebłyski świadomości przy odpalaniu +// what the split parts of TController share, kept out of the global namespace +namespace vehicle_ai { + double brake_response_horizon( physics::Vehicle const *Vehicle, TBrakeSystem const Brakesystem, double const Acceleration, double const Brakea0 ); double uphill_stopping_distance( double const Velocity, double const Gravity ); +} // namespace vehicle_ai + diff --git a/vehicle/ai/speed.cpp b/vehicle/ai/speed.cpp index 864f67341..55b8db7f0 100644 --- a/vehicle/ai/speed.cpp +++ b/vehicle/ai/speed.cpp @@ -170,7 +170,7 @@ TController::hold_train_coming_to_stand_uphill() { || ( ( BrakeSystem == TBrakeSystem::Pneumatic ) // not for a train that is short of where it is to stop and is to pull up further && ( AccDesired <= 0.0 ) - && ( vel / 3.6 / -fAccGravity <= 0.5 * brake_response_horizon( occupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) { + && ( vel / 3.6 / -fAccGravity <= 0.5 * vehicle_ai::brake_response_horizon( occupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) { // the gradient alone already slows the train down nearly this much; ask for enough on top of it that // the brake is applied for sure, not held back by the margin against small corrections AccDesired = std::min( AccDesired, fAccGravity - std::max( 0.15, fBrake_a0[ 0 ] ) - brake_increase_margin() ); @@ -441,7 +441,7 @@ TController::adjust_desired_speed_for_limits() { // its pneumatic brake takes to apply (while speeding up) or to release (while slowing down), which in G // is tens of seconds; never shorter than the look-ahead the AI has always used double -brake_response_horizon( physics::Vehicle const *Vehicle, TBrakeSystem const Brakesystem, double const Acceleration, double const Brakea0 ) { +vehicle_ai::brake_response_horizon( physics::Vehicle const *Vehicle, TBrakeSystem const Brakesystem, double const Acceleration, double const Brakea0 ) { auto horizon { ( 1.0 - Brakea0 ) * 30.0 / 3.6 }; if( Brakesystem == TBrakeSystem::Pneumatic ) { @@ -455,7 +455,7 @@ brake_response_horizon( physics::Vehicle const *Vehicle, TBrakeSystem const Brak // distance [m] in which the gradient alone, with no brake and no power, brings a train rolling uphill at Velocity [km/h] to a stand double -uphill_stopping_distance( double const Velocity, double const Gravity ) { +vehicle_ai::uphill_stopping_distance( double const Velocity, double const Gravity ) { return ( Velocity / 3.6 ) * ( Velocity / 3.6 ) / ( 2.0 * std::max( 0.01, -Gravity ) ); } @@ -509,8 +509,8 @@ TController::adjust_desired_speed_for_braking_curve( double const Vel ) { ( occupied->brakes.localKind == TLocalBrake::PneumaticBrake || occupied->brakes.localKind == TLocalBrake::HydraulicBrake ) ? occupied->brakes.independentPosition : 0.0 ), - brake_response_horizon( occupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ), - brake_response_horizon( occupied, BrakeSystem, 1.0, fillbrakea0 ) }; + vehicle_ai::brake_response_horizon( occupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ), + vehicle_ai::brake_response_horizon( occupied, BrakeSystem, 1.0, fillbrakea0 ) }; auto const deceleration { braking_curve::demand( approach, BrakeSystem == TBrakeSystem::Pneumatic ? &braketable : nullptr ) }; AccDesired = std::min( AccDesired, deceleration ); // najpierw hamuje mocniej, potem zluzuje if( Vel <= VelNext ) { @@ -523,7 +523,7 @@ TController::adjust_desired_speed_for_braking_curve( double const Vel ) { else if( ( fAccGravity < -0.025 ) && ( OrderCurrentGet().HasAny(DriverOrder::obeyTrain) ) && ( false == uphill_brake_committed( Vel ) ) - && ( ActualProximityDist - uphill_stopping_distance( Vel, fAccGravity ) > brakingpointoffset ) ) { + && ( ActualProximityDist - vehicle_ai::uphill_stopping_distance( Vel, fAccGravity ) > brakingpointoffset ) ) { // uphill the gradient alone slows the train down more than it is asked to; // keep it rolling at the present speed until that changes AccDesired = std::min( 0.0, AccPreferred ); @@ -569,7 +569,7 @@ TController::adjust_desired_speed_for_final_approach( double const Vel ) { if( ( fAccGravity < -0.025 ) && ( AccDesired >= fAccGravity - 0.001 ) // no brake needed at all && ( false == uphill_brake_committed( Vel ) ) - && ( ActualProximityDist - uphill_stopping_distance( Vel, fAccGravity ) > stopping_margin() ) ) { + && ( ActualProximityDist - vehicle_ai::uphill_stopping_distance( Vel, fAccGravity ) > stopping_margin() ) ) { // uphill the gradient alone would bring the train to a stand short of the // middle of the stopping window; keep it rolling at the present speed until that changes, // but no faster than the gradient alone can take off by the middle of the window @@ -709,7 +709,7 @@ TController::adjust_desired_speed_for_current_speed() { // look ahead for as long as the brake takes to respond, since that is how long the // present acceleration will last whatever is done with the handle now; a pneumatic // brake applies and releases on its own time scale, which in G is tens of seconds - auto const horizon { brake_response_horizon( occupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ) }; + auto const horizon { vehicle_ai::brake_response_horizon( occupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ) }; auto const speedestimate = vel + 3.6 * horizon * AbsAccS; // already below a lower limit ahead, the train has no business speeding up towards it auto holdlimit { VelDesired }; diff --git a/vehicle/cab/internal.h b/vehicle/cab/internal.h index 770c556bc..cc4bc2f2c 100644 --- a/vehicle/cab/internal.h +++ b/vehicle/cab/internal.h @@ -57,5 +57,11 @@ extern user_command command; auto const EU07_CONTROLLER_BASERETURNDELAY{0.5f}; +// what the split parts of TTrain share, kept out of the global namespace +namespace vehicle_cab +{ + bool is_hold_coil_lever(TGauge const &Button); +} // namespace vehicle_cab + diff --git a/vehicle/cab/powercommands.cpp b/vehicle/cab/powercommands.cpp index 6d15e634d..f9d17ecf7 100644 --- a/vehicle/cab/powercommands.cpp +++ b/vehicle/cab/powercommands.cpp @@ -48,7 +48,7 @@ http://mozilla.org/MPL/2.0/. // whether the cab's main_off_bt is the bistable lever of the line breaker's hold coil (eu07/maszyna#364) -bool is_hold_coil_lever(TGauge const &Button) +bool vehicle_cab::is_hold_coil_lever(TGauge const &Button) { return Button.SubModel != nullptr && hold_coil_lever::is_bistable(Button.type_declared(), Button.type() == TGaugeType::toggle); } @@ -66,7 +66,7 @@ void TTrain::OnCommand_linebreakertoggle(TTrain *Train, command_data const &Comm { case linebreaker::toggle::close: // ...to close the circuit - if (is_hold_coil_lever(Train->ggMainOffButton) && hold_coil_lever::cuts_off(Train->ggMainOffButton.GetDesiredValue())) + if (vehicle_cab::is_hold_coil_lever(Train->ggMainOffButton) && hold_coil_lever::cuts_off(Train->ggMainOffButton.GetDesiredValue())) { // the one key works both controls: the hold coil lever goes back on first, or the line breaker couldn't close Train->ggMainOffButton.UpdateValue(0.0, Train->dsbSwitch); @@ -112,7 +112,7 @@ void TTrain::OnCommand_linebreakeropen(TTrain *Train, command_data const &Comman if (Command.action == GLFW_PRESS) { // visual feedback - if (is_hold_coil_lever(Train->ggMainOffButton)) + if (vehicle_cab::is_hold_coil_lever(Train->ggMainOffButton)) { // the bistable lever goes over to its other position and stays there auto const position{hold_coil_lever::operated(Train->ggMainOffButton.GetDesiredValue())}; @@ -173,7 +173,7 @@ void TTrain::OnCommand_linebreakeropen(TTrain *Train, command_data const &Comman { Train->ggMainOnButton.UpdateValue(0.0, Train->dsbSwitch); } - if (Train->ggMainOffButton.SubModel != nullptr && false == is_hold_coil_lever(Train->ggMainOffButton)) + if (Train->ggMainOffButton.SubModel != nullptr && false == vehicle_cab::is_hold_coil_lever(Train->ggMainOffButton)) { // (the bistable hold coil lever stays where it was put) Train->ggMainOffButton.UpdateValue(0.0, Train->dsbSwitch); diff --git a/vehicle/cab/train.cpp b/vehicle/cab/train.cpp index 0c6ae06b9..99987edb7 100644 --- a/vehicle/cab/train.cpp +++ b/vehicle/cab/train.cpp @@ -443,7 +443,7 @@ bool TTrain::is_eztoer() const controlled->DirActive != 0; // od yB } -// physics master controller to specified position +// move the master controller to specified position void TTrain::set_master_controller(double const Position) { diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index cf33a899a..8a56054b5 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -151,7 +151,7 @@ void TTrain::updateLineBreakerState(double const Deltatime) // because the state of the line breaker isn't changed to match, we need to do it here manually m_linebreakerstate = linebreaker::state::open; } - if (is_hold_coil_lever(ggMainOffButton) && hold_coil_lever::cuts_off(ggMainOffButton.GetDesiredValue())) + if (vehicle_cab::is_hold_coil_lever(ggMainOffButton) && hold_coil_lever::cuts_off(ggMainOffButton.GetDesiredValue())) { if (true == controlled->lineBreaker.closed) { diff --git a/vehicle/dynamic/internal.h b/vehicle/dynamic/internal.h index 27b6e80ae..99eb1e40c 100644 --- a/vehicle/dynamic/internal.h +++ b/vehicle/dynamic/internal.h @@ -67,8 +67,6 @@ http://mozilla.org/MPL/2.0/. TSubModel * GetSubmodelFromName( TModel3d * const Model, std::string const Name ); -bool outside( glm::dvec3 const &Centre, double const Radius, glm::dvec2 const &Min, glm::dvec2 const &Max ); - // the time spent off the track in a frame which makes it worth a warning [s] constexpr double off_track_slow { 0.02 }; @@ -76,5 +74,10 @@ constexpr double off_track_slow { 0.02 }; using off_track_clock = std::chrono::steady_clock; +// what the split parts of TDynamicObject share, kept out of the global namespace +namespace vehicle_dynamic { + double seconds_since( off_track_clock::time_point const Start ); +} // namespace vehicle_dynamic + diff --git a/vehicle/dynamic/offtrack.cpp b/vehicle/dynamic/offtrack.cpp index 40bb90392..e12ccb0c2 100644 --- a/vehicle/dynamic/offtrack.cpp +++ b/vehicle/dynamic/offtrack.cpp @@ -63,11 +63,11 @@ namespace using ground_triangles = std::vector; -} // namespace - bool outside( glm::dvec3 const &Centre, double const Radius, glm::dvec2 const &Min, glm::dvec2 const &Max ) { return Centre.x + Radius < Min.x || Centre.x - Radius > Max.x || Centre.z + Radius < Min.y || Centre.z - Radius > Max.y; } + +} // namespace namespace { @@ -168,7 +168,7 @@ double compression_of( physics::Vehicle const &Vehicle, VehicleEnd const End ) { } // namespace -double seconds_since( off_track_clock::time_point const Start ) { +double vehicle_dynamic::seconds_since( off_track_clock::time_point const Start ) { return std::chrono::duration( off_track_clock::now() - Start ).count(); } namespace @@ -297,7 +297,7 @@ void TDynamicObject::gather_off_track_terrain() { } } m_offtracksite.terrain( m_offtrackterrain.get() ); - auto const took { seconds_since( started ) }; + auto const took { vehicle_dynamic::seconds_since( started ) }; if( took > off_track_slow ) { ErrorLog( std::format( "derailment: warning: gathering the terrain of {:.0f} m around {} took {:.0f} ms ({} triangles)", reach, physics->Name, took * 1000.0, triangles.size() ) ); } @@ -420,7 +420,7 @@ void TDynamicObject::move_off_track( double const Distance ) { pull_neighbours( Distance ); // what it cost: a frame of the vehicle off the track should take well under a millisecond - auto const took { seconds_since( started ) }; + auto const took { vehicle_dynamic::seconds_since( started ) }; m_offtrackslowdue -= time; if( took > off_track_slow && m_offtrackslowdue <= 0.0 ) { m_offtrackslowdue = 1.0; diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index 4c70f7979..b59ab45aa 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -79,7 +79,7 @@ bool TDynamicObject::Update(double dt, double dt1) if( vehicle == nullptr ) { return; } - auto const took { seconds_since( started ) }; + auto const took { vehicle_dynamic::seconds_since( started ) }; vehicle->m_offtrackupdatedue -= frame; if( took > off_track_slow && vehicle->m_offtrackupdatedue <= 0.0 ) { vehicle->m_offtrackupdatedue = 1.0; diff --git a/vehicle/dynamic/vehicletable.cpp b/vehicle/dynamic/vehicletable.cpp index 447579c9d..1b2ffe229 100644 --- a/vehicle/dynamic/vehicletable.cpp +++ b/vehicle/dynamic/vehicletable.cpp @@ -530,7 +530,7 @@ vehicle_table::update_off_track_contacts( double const Deltatime ) { if( false == resting ) { m_overlaplogged = false; } - auto const took { seconds_since( started ) }; + auto const took { vehicle_dynamic::seconds_since( started ) }; if( took > off_track_slow ) { ErrorLog( std::format( "derailment: warning: the contacts of {} vehicles off the track took {:.0f} ms", offtrack.size(), took * 1000.0 ) ); } From a9d9c74a706980e52c8042f7972a4d2ee64494a9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 1 Nov 2026 19:12:41 +0100 Subject: [PATCH 038/123] Keep the wiper timers of the windscreen when the camera leaves the cab The moments the blades were at the ends of their sweep (wiper_timer_out / wiper_timer_return, the drops on the glass come back from then) were set to -1000 whenever the camera wasn't in an active cab, so the glass came back fully wet on the return to the cab, and stayed so until the blades reached the end of their sweep again. They now follow the train driven while the camera is outside it (or the vehicle of the camera, as before, when it's in an active cab) and are kept; they're forgotten only when another vehicle is followed. Both renderers (OpenGL 4.6 and Vulkan). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- rendering/opengl46/opengl46renderer.cpp | 19 +++++++++++++++---- rendering/opengl46/opengl46renderer.h | 2 ++ rendering/vulkan14/vulkan14frame.cpp | 19 +++++++++++++++---- rendering/vulkan14/vulkan14renderer.h | 2 ++ 4 files changed, 34 insertions(+), 8 deletions(-) diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index e1b65aa44..49276a47f 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -1685,13 +1685,26 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) air -= owner->VectorFront() * owner->physics->V; scene_ubs.rain_wind = glm::vec4{glm::vec3{air}, 0.f}; } - if (TDynamicObject const *owner = Global.pCamera.m_owner; owner && !!owner->physics->CabActive) + // the wipers of the vehicle the camera is in, or of the train driven when the camera is outside it: the moments the blades + // were at the ends of their sweep (the drops on the glass come back from then) are kept while the camera is away, so the glass + // looks as the blades left it when it's back in the cab. they're forgotten only for another vehicle + TDynamicObject const *owner = Global.pCamera.m_owner; + if ((owner == nullptr) || (owner->MoverParameters->CabActive == 0)) + owner = (simulation::Train != nullptr) ? simulation::Train->Dynamic() : nullptr; + if (owner != m_wipervehicle) { + m_wipervehicle = owner; + scene_ubs.wiper_timer_out = glm::vec4{-1000.}; + scene_ubs.wiper_timer_return = glm::vec4{-1000.}; + } + if (owner != nullptr) + { + auto const cabactive{owner->MoverParameters->CabActive != 0 ? owner->MoverParameters->CabActive : 1}; for (int i = 0; i < 4; ++i) { if (i < owner->dWiperPos.size()) { - int index = owner->physics->CabActive > 0 ? i : static_cast(owner->dWiperPos.size() - 1) - i; + int index = cabactive > 0 ? i : static_cast(owner->dWiperPos.size() - 1) - i; scene_ubs.wiper_pos[i] = owner->dWiperPos[index]; if (owner->dWiperPos[index] > 0. && owner->wiperDirection[index]) { @@ -1717,8 +1730,6 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) else { scene_ubs.wiper_pos = glm::vec4{0.}; - scene_ubs.wiper_timer_out = glm::vec4{-1000.}; - scene_ubs.wiper_timer_return = glm::vec4{-1000.}; } } // the reflections: the ground below the horizon of the environment map, and the screen space ones set up for the colour diff --git a/rendering/opengl46/opengl46renderer.h b/rendering/opengl46/opengl46renderer.h index 5f5ec776a..691bea6bb 100644 --- a/rendering/opengl46/opengl46renderer.h +++ b/rendering/opengl46/opengl46renderer.h @@ -864,6 +864,8 @@ class opengl46_renderer : public gfx_renderer, public gfx::scene_walk { // persistently mapped with Global.gfx_bufferstreaming std::unique_ptr m_instancestream; gl::scene_ubs scene_ubs; + // the vehicle whose wipers the timers of the blades in scene_ubs (wiper_timer_out / wiper_timer_return) follow + TDynamicObject const *m_wipervehicle{nullptr}; gl::light_data light_data; std::unordered_map> m_shaders; diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index 1b802f3d5..28493bac9 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -1566,13 +1566,26 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) air -= owner->VectorFront() * owner->physics->V; scene_ubs.rain_wind = glm::vec4{glm::vec3{air}, 0.f}; } - if (TDynamicObject const *owner = Global.pCamera.m_owner; owner && !!owner->physics->CabActive) + // the wipers of the vehicle the camera is in, or of the train driven when the camera is outside it: the moments the blades + // were at the ends of their sweep (the drops on the glass come back from then) are kept while the camera is away, so the glass + // looks as the blades left it when it's back in the cab. they're forgotten only for another vehicle + TDynamicObject const *owner = Global.pCamera.m_owner; + if ((owner == nullptr) || (owner->MoverParameters->CabActive == 0)) + owner = (simulation::Train != nullptr) ? simulation::Train->Dynamic() : nullptr; + if (owner != m_wipervehicle) { + m_wipervehicle = owner; + scene_ubs.wiper_timer_out = glm::vec4{-1000.}; + scene_ubs.wiper_timer_return = glm::vec4{-1000.}; + } + if (owner != nullptr) + { + auto const cabactive{owner->MoverParameters->CabActive != 0 ? owner->MoverParameters->CabActive : 1}; for (int i = 0; i < 4; ++i) { if (i < owner->dWiperPos.size()) { - int index = owner->physics->CabActive > 0 ? i : static_cast(owner->dWiperPos.size() - 1) - i; + int index = cabactive > 0 ? i : static_cast(owner->dWiperPos.size() - 1) - i; scene_ubs.wiper_pos[i] = owner->dWiperPos[index]; if (owner->dWiperPos[index] > 0. && owner->wiperDirection[index]) { @@ -1598,8 +1611,6 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) else { scene_ubs.wiper_pos = glm::vec4{0.}; - scene_ubs.wiper_timer_out = glm::vec4{-1000.}; - scene_ubs.wiper_timer_return = glm::vec4{-1000.}; } } // the stages after D: no contact shadows, no cascades fitted to the depth, no shadow maps of headlights diff --git a/rendering/vulkan14/vulkan14renderer.h b/rendering/vulkan14/vulkan14renderer.h index 7184e7ba5..e8160c2bc 100644 --- a/rendering/vulkan14/vulkan14renderer.h +++ b/rendering/vulkan14/vulkan14renderer.h @@ -559,6 +559,8 @@ class vulkan14_renderer : public gfx_renderer, public gfx::scene_walk glm::vec3 m_fogcolor{0.f}; glm::vec4 m_shadowcolor{colors::shadow}; gl::scene_ubs scene_ubs{}; + // the vehicle whose wipers the timers of the blades in scene_ubs (wiper_timer_out / wiper_timer_return) follow + TDynamicObject const *m_wipervehicle{nullptr}; gl::light_data light_data{}; std::uint32_t m_lightcount{1}; // lights written to light_data // the copies of the light buffer in the ring of the frame since the lights were last written, by the header and the sun From d3920cdd3f30fa8250a20930a8271e4e3a00ce37 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 1 Nov 2026 19:25:29 +0100 Subject: [PATCH 039/123] Add the windscreen bugs shader (mat_bugs_windscreen) for OpenGL 4.6 and Vulkan 1.4 The spring / summer dirt of the windscreen, ported from the OpenGL 3.3 shader: insects splat on the glass one by one until it's fully dirty after an hour of simulation time, the wipers wipe them off where they sweep, a ring of blur around every splat. The .mat blocks of the seasons name it (szyby.mat of the cab), and it was missing from both renderers ("cannot read shader"). The syntax of the 4.6 renderers (locations, bindings, #pragma texture / param, the tuning values as constants), the blur ring through the velocity target as the haze of rain_windscreen, the colour written straight as rain_windscreen writes the glass, and no lighting where the glass is clear. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_bugs_windscreen.frag | 477 ++++++++++++++++++++++++ shaders/vk14/mat_bugs_windscreen.frag | 482 +++++++++++++++++++++++++ 2 files changed, 959 insertions(+) create mode 100644 shaders/ogl46/mat_bugs_windscreen.frag create mode 100644 shaders/vk14/mat_bugs_windscreen.frag diff --git a/shaders/ogl46/mat_bugs_windscreen.frag b/shaders/ogl46/mat_bugs_windscreen.frag new file mode 100644 index 000000000..ff0128c8e --- /dev/null +++ b/shaders/ogl46/mat_bugs_windscreen.frag @@ -0,0 +1,477 @@ +#version 460 core +#define STAGE_FRAGMENT 1 +// Windscreen bugs (spring / summer) - v3 (OpenGL 4.6 / Vulkan 1.4 port of the OpenGL 3.3 v2) +// v3: the syntax of the 4.6 renderers (explicit locations and bindings, #pragma texture / param, the settings as constants); +// the tuning values are constants (a uniform can't have a default any more); the blur ring goes to the post-processing +// through the velocity target as the haze of rain_windscreen does (postfx_taa.frag / postfx_motionblur.frag with +// rain_windscreen_haze.glsl); the colour is written straight (not premultiplied), as rain_windscreen of the 4.6 renderers +// writes the glass; the gloss of the glass from legacy_gloss(); no lighting where the glass is clear (no bug, clear texture) +// v2: cells without a bug are skipped before the wiper mask is read (the mask used to be read for all +// 18 cells of both layers on every pixel); the fine specks are procedural (no texture reads, only the +// pixel's own cell); optional vertical bias of the dirt; quick splat instead of a 2 s growth; +// now and then a really big bug and rarely a huge one (own coarse grids, never cut off by the 3x3 search); +// smaller blur ring, scaled by the size of the bug on screen. +// +// Insects splat on the glass one by one and the glass gets dirtier until it is +// fully dirty after `bugs_fill_time` seconds of simulation time (default 3600 = 1 h). +// No sliding, no rain: every bug is placed once (hash of its grid cell) and just +// appears at its own random moment. Wipers (wipermask) wipe the bugs off in the area they +// sweep; the glass there then gets dirty again, with new bugs, over the next bugs_fill_time. +// +// .mat (shader name WITHOUT the "mat_" prefix, the engine adds it). +// The sampler is called "raindropsatlas" on purpose, exactly like in rain_windscreen: +// the engine collects ALL texture_* lines of a .mat and checks them against the final +// shader, so a key that only one of the two shaders knows ends in "unknown texture binding". +// With one shared key, a season / weather block just overrides the file: +// +// texture_diffuse: dynamic/pkp/vectron_v1/cab/szyby +// texture_wipermask: dynamic/pkp/vectron_v1/cab/szyby_wipermask +// shader: rain_windscreen +// texture_raindropsatlas: textures/fx/raindrops-atlas +// texture_normalmap: textures/fx/raindrops_normalmap +// param_raindrop_grid_size: 150 +// +// spring: { +// shader: bugs_windscreen +// texture_raindropsatlas: textures/fx/bugs-atlas <- 2x2 atlas (blender_bugs_atlas.py), colour + alpha +// texture_normalmap: textures/fx/bugs_normalmap <- same layout: rg = normal xy, b = height, a = mask +// param_raindrop_grid_size: 60 <- cells across the glass UV, see below +// } +// summer: { +// shader: bugs_windscreen +// texture_raindropsatlas: textures/fx/bugs-atlas +// texture_normalmap: textures/fx/bugs_normalmap +// param_raindrop_grid_size: 60 +// } +// +// rain: { <- rain weather beats the season (priority 2 > 1) +// shader: rain_windscreen +// texture_raindropsatlas: textures/fx/raindrops-atlas +// texture_normalmap: textures/fx/raindrops_normalmap +// param_raindrop_grid_size: 150 +// } +// +// NOTE: the wipers' memory of when the glass was last wiped lives only in the engine's +// wiper timers, and the renderer resets them to -1000 whenever the camera is not in +// a cab (F4 ...). The shader cannot recover what is gone, so after returning to the cab the +// parts of the glass the blades cover are dirty as if never wiped (capped by `bugs_unknown_level`) until they are +// wiped again. A one-line engine fix would keep the memory, see the note in the chat. +// +// One cell is about one bug, so a grid of ~40-80 gives bugs of a few cm on a ~1.5 m +// windscreen (150, as used for rain drops, would make them tiny). + +layout(location = 0) in vec3 f_normal; +layout(location = 2) in vec2 f_coord; +layout(location = 3) in vec4 f_pos; +#include "common.glsl" + +layout(location = 0) out vec4 out_color; +layout(location = 1) out vec4 out_motion; + +#pragma texture(diffuse, 0, sRGB_A) +#pragma texture(raindropsatlas, 1, sRGB_A) +#pragma texture(wipermask, 2, sRGB_A) +#pragma texture(normalmap, 3, RGBA) // splats: rg = normal xy, b = height, a = mask; same 2x2 layout as raindropsatlas (linear) +#pragma param(color, 0, 0, 4, diffuse) +#pragma param(diffuse, 1, 0, 1, diffuse) +#pragma param(specular, 1, 1, 1, specular) +#pragma param(reflection, 1, 2, 1, zero) +#pragma param(glossiness, 1, 3, 1, glossiness) +#pragma param(raindrop_grid_size, 2, 0, 1, one) + +#include "light_common.glsl" +#include "apply_fog.glsl" +#include "tonemapping.glsl" +#include "random.glsl" + +layout(binding = 0) uniform sampler2D diffuse; +layout(binding = 1) uniform sampler2D raindropsatlas; +layout(binding = 2) uniform sampler2D wipermask; +layout(binding = 3) uniform sampler2D normalmap; + +// --- Tuning ----------------------------------------------------------------- +const float bugs_fill_time = 3600.0; // seconds of simulation time until the glass is fully dirty +const float bugs_start_time = 0.0; // simulation time at which the glass was clean +const float bugs_density = 0.15; // fraction of grid cells that end up with a big bug (0..1) +const float specks_density = 0.12; // same for the layer of tiny specks (0 = off) +const float bugs_opacity = 1.0; // overall opacity of the dirt +const float bugs_uv_aspect = 1.0; // glass width / height in the world if the UV is stretched (e.g. 2.0 for a 1.4 x 0.7 m pane) +const float bugs_unknown_level = 1.0; // upper limit of the dirt where the wiper memory was lost: 1 = grows like everywhere else, 0.3 = never more than 30%, 0 = stays clean until a blade passes +const float bugs_wiper_clean = 1.0; // 1 = wipers wipe the bugs off (uses wipermask), 0 = wipers ignore them +const float bugs_gloss = 0.45; // shininess of the wet splats (sun / headlight glints on the bumps), 0 = matt +const float bugs_bump = 1.0; // strength of the 3D relief from the normal map, 0 = flat +const float bugs_halo_blur = 0.45; // blur of the scene in a ring around every bug (0 = off, 1 = full); done in the post-processing (rain_windscreen_haze.glsl) +const float bugs_halo_size = 1.15; // ring radius = bug half-size * this (1 = only under the splat, max 1.6) +const float bugs_halo_px = 60.0; // a bug this many pixels wide on screen gets the full blur, smaller ones less (the blur radius is fixed in pixels) +const float bugs_vertical = 0.0; // -1..1: more dirt at the bottom (<0) or at the top (>0) of the pane, 0 = even +const float bugs_giant_density = 0.015; // share of the coarse cells that end up with a really big bug (0 = off) +const float bugs_giant_scale = 4.0; // how much bigger the big ones are (the coarse grid is this many times coarser) +const float bugs_huge_density = 0.02; // share of the very coarse cells with a huge bug: about one per pane when fully dirty (0 = off) +const float bugs_huge_scale = 9.0; // how much bigger the huge ones are than the normal bugs +const float specks_size = 0.30; // size of the fine specks, in speck cells (0.1 .. 0.45) +const float specks_opacity = 0.55; // how much a speck covers the glass + +const float BUG_SIZE_MIN = 0.6; // bug size in grid cells (keep max <= 1.2, the search covers 3x3 cells) +const float BUG_SIZE_MAX = 1.2; +const float BUG_FADE_TIME = 0.15; // seconds a splat takes to appear (a quick splat) +const float SPECK_SCALE = 2.5; // speck grid = raindrop_grid_size * this +const float WS_ENC = 64.0; // must match rain_windscreen_haze.glsl + +// Match the way rain_windscreen draws the glass itself (colour premultiplied by +// alpha, then alpha-blended), so the pane looks identical in summer and in rain. +// Set to 1 to see the shader's clock (`time`) as red digits on the glass, see bugs_start_time. +#ifndef BUGS_DEBUG_TIME +#define BUGS_DEBUG_TIME 0 +#endif + +#ifndef BUGS_MATCH_RAIN_GLASS +#define BUGS_MATCH_RAIN_GLASS 0 // 4.6: rain_windscreen writes the glass straight, not premultiplied +#endif + +vec2 tileOffset(float choice) +{ + if (choice < 0.25) return vec2(0.0, 0.0); + else if (choice < 0.5) return vec2(0.5, 0.0); + else if (choice < 0.75) return vec2(0.0, 0.5); + return vec2(0.5, 0.5); +} + +// Simulation time at which a wiper blade last swept over `co`. +// WIPER_NONE no blade covers this spot (it can never be wiped) +// WIPER_UNKNOWN a blade covers it, but the engine has lost its memory: while the camera is +// outside the cab (F4 ...) the renderer resets the stroke timers to -1000 +// Same blade/stroke logic as GetMixFactor in rain_windscreen: wipermask channel i is the +// area of blade i, its value says when during the stroke the blade reaches that spot, and +// wiper_pos is 0..1 on the way out and 1..2 on the way back. The timers hold the moment +// each stroke started, which is good enough (a stroke takes about a second). +const float WIPER_NONE = -1.0e9; +const float WIPER_UNKNOWN = -2.0e9; + +float lastCleanTime(vec2 co) +{ + vec4 m = textureLod(wipermask, co, 0.0); + float best = WIPER_NONE; + bool unknown = false; + for (int i = 0; i < 4; ++i) + { + if (m[i] <= 0.001) + continue; + float pos = wiper_pos[i]; + bool isOut = pos <= 1.0; + float phase = isOut ? pos : 2.0 - pos; + float maskVal = isOut ? m[i] : 1.0 - m[i]; + bool passed = maskVal <= phase; // blade is already past this spot + float sideV = isOut ? (passed ? 0.0 : 1.0) : (passed ? 1.0 : 0.0); + float t = mix(wiper_timer_out[i], wiper_timer_return[i], sideV); + if (!(t <= time)) // garbage or NaN: ignore + continue; + if (t < -500.0) // the -1000 "memory lost" marker + { + unknown = true; + continue; + } + best = max(best, t); + } + if (best > WIPER_NONE) + return best; + return unknown ? WIPER_UNKNOWN : WIPER_NONE; +} + +// Fine specks: tiny dried drops of bug juice. Procedural (a soft irregular blob with a darker rim), +// one per speck cell and always inside it, so only the pixel's own cell is checked: no texture reads +// apart from the wiper state of this pixel, which main() passes in. +void speckLayer(float gridSize, float density, float tcPix, vec2 aspect, float pixelUV, + inout vec3 accRGB, inout float accA, inout vec3 accN, inout float accNA) +{ + vec2 g = f_coord * gridSize; + vec2 cell = floor(g); + float tBase, prog; + if (tcPix < -1.5e9) + { + tBase = -1000.0; + prog = min(max(time - bugs_start_time, 0.0) / max(bugs_fill_time, 1.0), bugs_unknown_level); + } + else + { + tBase = max(bugs_start_time, tcPix); + prog = max(time - tBase, 0.0) / max(bugs_fill_time, 1.0); + } + if (prog <= 0.0) + return; + uint pseed = Hash(uvec3(uvec2(ivec2(floor(cell / 8.0))), 107u)); + float patchMul = mix(0.4, 1.6, RandF(pseed)); + float vertMul = clamp(1.0 + bugs_vertical * ((cell.y + 0.5) / gridSize - 0.5) * 2.0, 0.0, 2.0); + uint seed = Hash(uvec3(uvec2(ivec2(cell)), 7u ^ floatBitsToUint(tBase))); + if (RandF(seed) > density * patchMul * vertMul) + return; + float appearAt = RandF(seed); + if (prog < appearAt) + return; + float r = clamp(specks_size, 0.05, 0.45) * mix(0.5, 1.0, RandF(seed)); + vec2 c = vec2(r) + vec2(RandF(seed), RandF(seed)) * max(1.0 - 2.0 * r, 0.0); + float ang = RandF(seed) * 6.2831853; + float el = mix(0.6, 1.0, RandF(seed)); + vec2 p = (g - cell - c) / r; + p = vec2(cos(ang) * p.x + sin(ang) * p.y, (-sin(ang) * p.x + cos(ang) * p.y) / el); + // irregular outline: a few lobes + float th = atan(p.y, p.x); + float lob = 1.0 + 0.18 * sin(3.0 * th + RandF(seed) * 6.28) + 0.10 * sin(5.0 * th + RandF(seed) * 6.28); + float d = length(p) / lob; + if (d >= 1.0) + return; + float edgeW = clamp(pixelUV * gridSize / r * 1.5, 0.05, 0.6); // ~1.5 px soft edge + float m = 1.0 - smoothstep(1.0 - edgeW, 1.0, d); + float a = m * specks_opacity * bugs_opacity * (0.6 + 0.4 * smoothstep(0.5, 0.95, d)); // the dried rim covers more + vec3 col = vec3(0.42, 0.34, 0.16) * mix(0.8, 1.15, RandF(seed)) * mix(1.0, 0.75, smoothstep(0.6, 0.95, d)); + vec3 nT = normalize(vec3(p / max(lob, 0.5) * 0.25 * bugs_bump, 1.0)); + accRGB = col * a + accRGB * (1.0 - a); + accN = nT * a + accN * (1.0 - a); + accA = a + accA * (1.0 - a); + accNA = accA; +} + +// Adds one layer of bugs to the premultiplied accumulators (accRGB, accA). +void bugLayer(float gridSize, float density, uint layerSeed, + float pixelUV, vec2 aspect, float haloStrength, float opacityMul, float lightMix, + inout vec3 accRGB, inout float accA, inout float smear, + inout vec3 accN, inout float accNA) +{ + vec2 cell = floor(f_coord * gridSize); + float fadeSpan = BUG_FADE_TIME / max(bugs_fill_time, 1.0); + + for (int oy = -1; oy <= 1; oy++) { + for (int ox = -1; ox <= 1; ox++) { + + vec2 ncell = cell + vec2(float(ox), float(oy)); + + // Dirt is patchy: big areas get more bugs than others; optional bias towards the top / bottom + uint pseed = Hash(uvec3(uvec2(ivec2(floor(ncell / 8.0))), layerSeed + 100u)); + float patchMul = mix(0.4, 1.6, RandF(pseed)); + float vy = (ncell.y + 0.5) / gridSize; // 0 = bottom of the UV, 1 = top + float vertMul = clamp(1.0 + bugs_vertical * (vy - 0.5) * 2.0, 0.0, 2.0); + float pCell = clamp(density * patchMul * vertMul, 0.0, 1.0); + + // 1st test, fixed per cell (cheap, no texture): can this cell hold a bug at all? + // Cells that fail it are skipped before the wiper mask is read. + float pMax = min(2.0 * pCell, 1.0); + uint cseed = Hash(uvec3(uvec2(ivec2(ncell)), layerSeed + 31u)); + if (RandF(cseed) > pMax) + continue; + + // When the wipers last swept over this cell. Whatever hit the glass before that + // moment is gone; the cell then gets a brand new set of bugs (the seed depends on + // that moment) that again take bugs_fill_time to build up. + float tc = (bugs_wiper_clean > 0.5) ? lastCleanTime((ncell + 0.5) / gridSize) : WIPER_NONE; + + float tBase; + float prog; + if (tc < -1.5e9) + { + // The engine forgot when the wipers last swept here (the camera was outside the + // cab). We cannot know how dirty the glass was, so show a fixed, non-growing level + // until a blade passes and gives us a real clean time again. + tBase = -1000.0; + prog = min(max(time - bugs_start_time, 0.0) / max(bugs_fill_time, 1.0), bugs_unknown_level); + } + else + { + tBase = max(bugs_start_time, tc); + prog = max(time - tBase, 0.0) / max(bugs_fill_time, 1.0); + } + if (prog <= 0.0) + continue; + + uint seed = Hash(uvec3(uvec2(ivec2(ncell)), layerSeed ^ floatBitsToUint(tBase))); + + // 2nd test, new after every wipe: together with the 1st one the cell holds a bug with + // probability pCell, and a wiped cell gets a new set of bugs + float present = RandF(seed); + if (present * pMax > pCell) + continue; + + // Moment (0..1 of the fill time) when this bug hits the glass + float appearAt = RandF(seed); + if (prog < appearAt) + continue; + float appear = smoothstep(appearAt, appearAt + fadeSpan, prog); + + float jx = RandF(seed); + float jy = RandF(seed); + vec2 center = (ncell + vec2(jx, jy)) / gridSize; + + float size = mix(BUG_SIZE_MIN, BUG_SIZE_MAX, RandF(seed)) / gridSize * mix(0.7, 1.0, appear); + float ang = RandF(seed) * 6.2831853; + float flipX = (RandF(seed) < 0.5) ? -1.0 : 1.0; + float choice = RandF(seed); + float tone = mix(0.8, 1.15, RandF(seed)); + + vec2 d = (f_coord - center) * aspect; + + // Blur ring around the splat (greasy smear): strongest next to the bug, fading out + // (the post pass blurs with a fixed radius in pixels, so a bug that is small on screen gets less of it) + float haloR = size * 0.5 * clamp(bugs_halo_size, 1.0, 1.6); + float dist = length(d); + if (dist < haloR) + { + float pxScale = clamp(size / max(pixelUV, 1e-6) / max(bugs_halo_px, 1.0), 0.15, 1.0); + smear = max(smear, (1.0 - smoothstep(0.5 * haloR, haloR, dist)) * haloStrength * appear * pxScale); + } + + float c = cos(ang); + float s = sin(ang); + vec2 r = vec2(c * d.x + s * d.y, -s * d.x + c * d.y); + r.x *= flipX; + + vec2 local = r / size + 0.5; + if (any(lessThan(local, vec2(0.0))) || any(greaterThan(local, vec2(1.0)))) + continue; + + // mip level from the on-screen size of the bug (derivatives are not + // allowed inside this non-uniform branch, so pixelUV comes from main) + float lod = clamp(log2(max(pixelUV / size * 0.5 * float(textureSize(raindropsatlas, 0).x), 1.0)), 0.0, 4.0); + vec4 t = textureLod(raindropsatlas, tileOffset(choice) + local * 0.5, lod); + + // fine specks: fainter and lighter than the big bugs (the splat bodies are nearly black) + t.rgb = mix(t.rgb, vec3(0.42, 0.34, 0.16), lightMix); + float a = clamp(t.a * appear * bugs_opacity * opacityMul, 0.0, 1.0); + + // relief: tangent-space normal of the splat -> glass UV frame (undo the mirror, then the rotation) + vec4 nm = textureLod(normalmap, tileOffset(choice) + local * 0.5, lod); + vec2 nxy = (nm.rg * 2.0 - 1.0) * bugs_bump * appear; // a splat that is still settling is flatter + nxy.x *= flipX; + vec2 nuv = vec2(c * nxy.x - s * nxy.y, s * nxy.x + c * nxy.y); + vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); + + // "over" compositing in premultiplied form + accRGB = t.rgb * tone * a + accRGB * (1.0 - a); + accN = nT * a + accN * (1.0 - a); + accA = a + accA * (1.0 - a); + accNA = accA; + } + } +} + +void main() +{ + // Derivatives first, in uniform control flow (no discard before them). + vec3 Ngl = normalize(f_normal); + vec3 dp1 = dFdx(f_pos.xyz); + vec3 dp2 = dFdy(f_pos.xyz); + vec2 duv1 = dFdx(f_coord); + vec2 duv2 = dFdy(f_coord); + vec3 dp2perp = cross(dp2, Ngl); + vec3 dp1perp = cross(Ngl, dp1); + vec3 Tgl = dp2perp * duv1.x + dp1perp * duv2.x; // tangent frame of the glass (T along u, B along v) + vec3 Bgl = dp2perp * duv1.y + dp1perp * duv2.y; + float invmax = inversesqrt(max(max(dot(Tgl, Tgl), dot(Bgl, Bgl)), 1e-20)); + Tgl *= invmax; + Bgl *= invmax; + + vec4 tex_color = texture(diffuse, f_coord); + // No discard on a (nearly) clear glass texture: clean glass between patches of faint dirt would + // otherwise be "bald" - no bugs, no halo. + + float gridSize = max(ceil(param[2].x), 1.0); + float pixelUV = max(length(dFdx(f_coord)), length(dFdy(f_coord))); // uniform control flow here + vec2 aspect = (bugs_uv_aspect >= 1.0) ? vec2(bugs_uv_aspect, 1.0) : vec2(1.0, 1.0 / max(bugs_uv_aspect, 0.01)); + + // 0 = never dirty yet; the real per-cell progress is computed in bugLayer (wipers reset it) + float progress = clamp((time - bugs_start_time) / max(bugs_fill_time, 1.0), 0.0, 1.0); + + vec3 bugRGB = vec3(0.0); // premultiplied + float bugA = 0.0; + float smear = 0.0; // blur ring around the bugs + vec3 bugN = vec3(0.0); // normals of the splats, premultiplied like the colour + float bugNA = 0.0; + if (progress > 0.0) + { + // fine specks underneath (procedural, one wiper read for the pixel), big bugs on top + if (specks_density > 0.0) + { + float tcPix = (bugs_wiper_clean > 0.5) ? lastCleanTime(f_coord) : WIPER_NONE; + speckLayer(gridSize * SPECK_SCALE, specks_density, tcPix, aspect, pixelUV, bugRGB, bugA, bugN, bugNA); + } + bugLayer(gridSize, bugs_density, 3u, pixelUV, aspect, 1.0, 1.0, 0.0, bugRGB, bugA, smear, bugN, bugNA); + // now and then a really big one, on top (its own coarse grid: same 3x3 search, bigger cells) + if (bugs_giant_density > 0.0) + bugLayer(gridSize / max(bugs_giant_scale, 1.0), bugs_giant_density, 11u, pixelUV, aspect, 1.0, 1.0, 0.0, + bugRGB, bugA, smear, bugN, bugNA); + // and rarely a huge one (about one per pane when it is fully dirty) + if (bugs_huge_density > 0.0) + bugLayer(gridSize / max(bugs_huge_scale, 1.0), bugs_huge_density, 13u, pixelUV, aspect, 1.0, 1.0, 0.0, + bugRGB, bugA, smear, bugN, bugNA); + } + + // Bugs over the glass (premultiplied "over") + float glassA = tex_color.a * alpha_mult; + float finalA = bugA + glassA * (1.0 - bugA); + vec3 premult = bugRGB + tex_color.rgb * glassA * (1.0 - bugA); + vec3 albedo = premult / max(finalA, 1e-4); + + // Reflections / specular belong to the glass only, not to the bugs + float glassShare = glassA * (1.0 - bugA) / max(finalA, 1e-4); + + vec3 fragcolor = ambient; + // Relief of the splats: tilt the glass normal by the splat's slope (the tilt direction is physical, + // so it does not matter which way the mesh normal points); flat where there is no bug. + vec3 bugDir = bugN + vec3(0.0, 0.0, 1.0) * (1.0 - bugNA); + vec3 fragnormal = Ngl; + if (bugNA > 0.001) + fragnormal = normalize(Ngl * max(bugDir.z, 0.05) + Tgl * bugDir.x + Bgl * bugDir.y); + float reflectivity = param[1].z * glassShare; + float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5 * glassShare + + bugs_gloss * bugA; // wet splats catch the sun and the headlights + legacy_gloss(); + + // Lit by sun, ambient and headlights like everything else (bugs glow in oncoming beams) + // most of the glass is clear (no bug, a clear glass texture): the lighting of the 4.6 renderers (the clusters of lamps, the + // shadows, the reflections) is skipped there, it would be multiplied by an alpha of ~0 + if (finalA > 0.002) + fragcolor = apply_lights(fragcolor, fragnormal, albedo, reflectivity, specularity, shadow_tone); + vec3 lit = apply_fog(fragcolor); + +#if BUGS_MATCH_RAIN_GLASS + vec4 color = vec4(lit * finalA, finalA); +#else + vec4 color = vec4(lit, finalA); +#endif + + out_color = POSTFX_ENABLED ? color : tonemap(color); + +#if BUGS_DEBUG_TIME + // Calibration: paints floor(time) as 8 red digits across the glass (the shader's own clock, in seconds). + // Read the number right after the scenario has loaded and put it into bugs_start_time. + { + const int SEG[10] = int[10](63, 6, 91, 79, 102, 109, 125, 7, 127, 111); + float dx = (f_coord.x - 0.10) / 0.10; + float dy = (f_coord.y - 0.42) / 0.08; + int idx = int(floor(dx)); + if (idx >= 0 && idx < 8 && dy >= 0.0 && dy <= 2.0) + { + float tt = floor(max(time, 0.0)); + float div = pow(10.0, float(7 - idx)); + int dig = int(mod(floor(tt / div), 10.0)); + vec2 q = vec2(fract(dx) / 0.8, dy); + int m = SEG[dig]; + bool on = false; + if ((m & 1) != 0 && q.y > 1.86 && q.x > 0.1 && q.x < 0.9) on = true; // a + if ((m & 2) != 0 && q.x > 0.86 && q.x < 1.0 && q.y > 1.0 && q.y < 1.9) on = true; // b + if ((m & 4) != 0 && q.x > 0.86 && q.x < 1.0 && q.y > 0.1 && q.y < 1.0) on = true; // c + if ((m & 8) != 0 && q.y < 0.14 && q.x > 0.1 && q.x < 0.9) on = true; // d + if ((m & 16) != 0 && q.x < 0.14 && q.y > 0.1 && q.y < 1.0) on = true; // e + if ((m & 32) != 0 && q.x < 0.14 && q.y > 1.0 && q.y < 1.9) on = true; // f + if ((m & 64) != 0 && q.y > 0.93 && q.y < 1.07 && q.x > 0.1 && q.x < 0.9) on = true; // g + if (on) + out_color = vec4(1.0, 0.05, 0.05, 1.0); + } + } +#endif + + if (MOTIONBLUR_ENABLED) + { + // alpha 0 = blending keeps the scene's own motion vectors + // the bug itself stays sharp (1 - bugA); no blur over opaque parts of the pane (1 - glassA) + float blurMask = clamp(smear * bugs_halo_blur * (1.0 - bugA) * (1.0 - smoothstep(0.5, 0.95, glassA)), 0.0, 1.0); + out_motion = (blurMask >= 0.01) ? vec4(WS_ENC * blurMask, 0.0, 0.0, 1.0) : vec4(0.0); + } +} diff --git a/shaders/vk14/mat_bugs_windscreen.frag b/shaders/vk14/mat_bugs_windscreen.frag new file mode 100644 index 000000000..261acefe4 --- /dev/null +++ b/shaders/vk14/mat_bugs_windscreen.frag @@ -0,0 +1,482 @@ +#version 460 core +#define STAGE_FRAGMENT 1 +#include "common.glsl" +// Windscreen bugs (spring / summer) - v3 (OpenGL 4.6 / Vulkan 1.4 port of the OpenGL 3.3 v2) +// v3: the syntax of the 4.6 renderers (explicit locations and bindings, #pragma texture / param, the settings as constants); +// the tuning values are constants (a uniform can't have a default any more); the blur ring goes to the post-processing +// through the velocity target as the haze of rain_windscreen does (postfx_taa.frag / postfx_motionblur.frag with +// rain_windscreen_haze.glsl); the colour is written straight (not premultiplied), as rain_windscreen of the 4.6 renderers +// writes the glass; the gloss of the glass from legacy_gloss(); no lighting where the glass is clear (no bug, clear texture) +// v2: cells without a bug are skipped before the wiper mask is read (the mask used to be read for all +// 18 cells of both layers on every pixel); the fine specks are procedural (no texture reads, only the +// pixel's own cell); optional vertical bias of the dirt; quick splat instead of a 2 s growth; +// now and then a really big bug and rarely a huge one (own coarse grids, never cut off by the 3x3 search); +// smaller blur ring, scaled by the size of the bug on screen. +// +// Insects splat on the glass one by one and the glass gets dirtier until it is +// fully dirty after `bugs_fill_time` seconds of simulation time (default 3600 = 1 h). +// No sliding, no rain: every bug is placed once (hash of its grid cell) and just +// appears at its own random moment. Wipers (wipermask) wipe the bugs off in the area they +// sweep; the glass there then gets dirty again, with new bugs, over the next bugs_fill_time. +// +// .mat (shader name WITHOUT the "mat_" prefix, the engine adds it). +// The sampler is called "raindropsatlas" on purpose, exactly like in rain_windscreen: +// the engine collects ALL texture_* lines of a .mat and checks them against the final +// shader, so a key that only one of the two shaders knows ends in "unknown texture binding". +// With one shared key, a season / weather block just overrides the file: +// +// texture_diffuse: dynamic/pkp/vectron_v1/cab/szyby +// texture_wipermask: dynamic/pkp/vectron_v1/cab/szyby_wipermask +// shader: rain_windscreen +// texture_raindropsatlas: textures/fx/raindrops-atlas +// texture_normalmap: textures/fx/raindrops_normalmap +// param_raindrop_grid_size: 150 +// +// spring: { +// shader: bugs_windscreen +// texture_raindropsatlas: textures/fx/bugs-atlas <- 2x2 atlas (blender_bugs_atlas.py), colour + alpha +// texture_normalmap: textures/fx/bugs_normalmap <- same layout: rg = normal xy, b = height, a = mask +// param_raindrop_grid_size: 60 <- cells across the glass UV, see below +// } +// summer: { +// shader: bugs_windscreen +// texture_raindropsatlas: textures/fx/bugs-atlas +// texture_normalmap: textures/fx/bugs_normalmap +// param_raindrop_grid_size: 60 +// } +// +// rain: { <- rain weather beats the season (priority 2 > 1) +// shader: rain_windscreen +// texture_raindropsatlas: textures/fx/raindrops-atlas +// texture_normalmap: textures/fx/raindrops_normalmap +// param_raindrop_grid_size: 150 +// } +// +// NOTE: the wipers' memory of when the glass was last wiped lives only in the engine's +// wiper timers, and the renderer resets them to -1000 whenever the camera is not in +// a cab (F4 ...). The shader cannot recover what is gone, so after returning to the cab the +// parts of the glass the blades cover are dirty as if never wiped (capped by `bugs_unknown_level`) until they are +// wiped again. A one-line engine fix would keep the memory, see the note in the chat. +// +// One cell is about one bug, so a grid of ~40-80 gives bugs of a few cm on a ~1.5 m +// windscreen (150, as used for rain drops, would make them tiny). + +layout(location = 0) in vec3 f_normal; +layout(location = 2) in vec2 f_coord; +layout(location = 3) in vec4 f_pos; + +layout(location = 0) out vec4 out_color; +#ifdef NO_MOTION_OUTPUT +// a pass without the velocity target: the writes go nowhere +vec4 out_motion; +#else +layout(location = 1) out vec4 out_motion; +#endif + +#pragma texture(diffuse, 0, sRGB_A) +#pragma texture(raindropsatlas, 1, sRGB_A) +#pragma texture(wipermask, 2, sRGB_A) +#pragma texture(normalmap, 3, RGBA) // splats: rg = normal xy, b = height, a = mask; same 2x2 layout as raindropsatlas (linear) +#pragma param(color, 0, 0, 4, diffuse) +#pragma param(diffuse, 1, 0, 1, diffuse) +#pragma param(specular, 1, 1, 1, specular) +#pragma param(reflection, 1, 2, 1, zero) +#pragma param(glossiness, 1, 3, 1, glossiness) +#pragma param(raindrop_grid_size, 2, 0, 1, one) + +#include "light_common.glsl" +#include "apply_fog.glsl" +#include "tonemapping.glsl" +#include "random.glsl" + +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 0) uniform sampler2D diffuse; +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 1) uniform sampler2D raindropsatlas; +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 2) uniform sampler2D wipermask; +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 3) uniform sampler2D normalmap; + +// --- Tuning ----------------------------------------------------------------- +const float bugs_fill_time = 3600.0; // seconds of simulation time until the glass is fully dirty +const float bugs_start_time = 0.0; // simulation time at which the glass was clean +const float bugs_density = 0.15; // fraction of grid cells that end up with a big bug (0..1) +const float specks_density = 0.12; // same for the layer of tiny specks (0 = off) +const float bugs_opacity = 1.0; // overall opacity of the dirt +const float bugs_uv_aspect = 1.0; // glass width / height in the world if the UV is stretched (e.g. 2.0 for a 1.4 x 0.7 m pane) +const float bugs_unknown_level = 1.0; // upper limit of the dirt where the wiper memory was lost: 1 = grows like everywhere else, 0.3 = never more than 30%, 0 = stays clean until a blade passes +const float bugs_wiper_clean = 1.0; // 1 = wipers wipe the bugs off (uses wipermask), 0 = wipers ignore them +const float bugs_gloss = 0.45; // shininess of the wet splats (sun / headlight glints on the bumps), 0 = matt +const float bugs_bump = 1.0; // strength of the 3D relief from the normal map, 0 = flat +const float bugs_halo_blur = 0.45; // blur of the scene in a ring around every bug (0 = off, 1 = full); done in the post-processing (rain_windscreen_haze.glsl) +const float bugs_halo_size = 1.15; // ring radius = bug half-size * this (1 = only under the splat, max 1.6) +const float bugs_halo_px = 60.0; // a bug this many pixels wide on screen gets the full blur, smaller ones less (the blur radius is fixed in pixels) +const float bugs_vertical = 0.0; // -1..1: more dirt at the bottom (<0) or at the top (>0) of the pane, 0 = even +const float bugs_giant_density = 0.015; // share of the coarse cells that end up with a really big bug (0 = off) +const float bugs_giant_scale = 4.0; // how much bigger the big ones are (the coarse grid is this many times coarser) +const float bugs_huge_density = 0.02; // share of the very coarse cells with a huge bug: about one per pane when fully dirty (0 = off) +const float bugs_huge_scale = 9.0; // how much bigger the huge ones are than the normal bugs +const float specks_size = 0.30; // size of the fine specks, in speck cells (0.1 .. 0.45) +const float specks_opacity = 0.55; // how much a speck covers the glass + +const float BUG_SIZE_MIN = 0.6; // bug size in grid cells (keep max <= 1.2, the search covers 3x3 cells) +const float BUG_SIZE_MAX = 1.2; +const float BUG_FADE_TIME = 0.15; // seconds a splat takes to appear (a quick splat) +const float SPECK_SCALE = 2.5; // speck grid = raindrop_grid_size * this +const float WS_ENC = 64.0; // must match rain_windscreen_haze.glsl + +// Match the way rain_windscreen draws the glass itself (colour premultiplied by +// alpha, then alpha-blended), so the pane looks identical in summer and in rain. +// Set to 1 to see the shader's clock (`time`) as red digits on the glass, see bugs_start_time. +#ifndef BUGS_DEBUG_TIME +#define BUGS_DEBUG_TIME 0 +#endif + +#ifndef BUGS_MATCH_RAIN_GLASS +#define BUGS_MATCH_RAIN_GLASS 0 // 4.6: rain_windscreen writes the glass straight, not premultiplied +#endif + +vec2 tileOffset(float choice) +{ + if (choice < 0.25) return vec2(0.0, 0.0); + else if (choice < 0.5) return vec2(0.5, 0.0); + else if (choice < 0.75) return vec2(0.0, 0.5); + return vec2(0.5, 0.5); +} + +// Simulation time at which a wiper blade last swept over `co`. +// WIPER_NONE no blade covers this spot (it can never be wiped) +// WIPER_UNKNOWN a blade covers it, but the engine has lost its memory: while the camera is +// outside the cab (F4 ...) the renderer resets the stroke timers to -1000 +// Same blade/stroke logic as GetMixFactor in rain_windscreen: wipermask channel i is the +// area of blade i, its value says when during the stroke the blade reaches that spot, and +// wiper_pos is 0..1 on the way out and 1..2 on the way back. The timers hold the moment +// each stroke started, which is good enough (a stroke takes about a second). +const float WIPER_NONE = -1.0e9; +const float WIPER_UNKNOWN = -2.0e9; + +float lastCleanTime(vec2 co) +{ + vec4 m = textureLod(wipermask, co, 0.0); + float best = WIPER_NONE; + bool unknown = false; + for (int i = 0; i < 4; ++i) + { + if (m[i] <= 0.001) + continue; + float pos = wiper_pos[i]; + bool isOut = pos <= 1.0; + float phase = isOut ? pos : 2.0 - pos; + float maskVal = isOut ? m[i] : 1.0 - m[i]; + bool passed = maskVal <= phase; // blade is already past this spot + float sideV = isOut ? (passed ? 0.0 : 1.0) : (passed ? 1.0 : 0.0); + float t = mix(wiper_timer_out[i], wiper_timer_return[i], sideV); + if (!(t <= time)) // garbage or NaN: ignore + continue; + if (t < -500.0) // the -1000 "memory lost" marker + { + unknown = true; + continue; + } + best = max(best, t); + } + if (best > WIPER_NONE) + return best; + return unknown ? WIPER_UNKNOWN : WIPER_NONE; +} + +// Fine specks: tiny dried drops of bug juice. Procedural (a soft irregular blob with a darker rim), +// one per speck cell and always inside it, so only the pixel's own cell is checked: no texture reads +// apart from the wiper state of this pixel, which main() passes in. +void speckLayer(float gridSize, float density, float tcPix, vec2 aspect, float pixelUV, + inout vec3 accRGB, inout float accA, inout vec3 accN, inout float accNA) +{ + vec2 g = f_coord * gridSize; + vec2 cell = floor(g); + float tBase, prog; + if (tcPix < -1.5e9) + { + tBase = -1000.0; + prog = min(max(time - bugs_start_time, 0.0) / max(bugs_fill_time, 1.0), bugs_unknown_level); + } + else + { + tBase = max(bugs_start_time, tcPix); + prog = max(time - tBase, 0.0) / max(bugs_fill_time, 1.0); + } + if (prog <= 0.0) + return; + uint pseed = Hash(uvec3(uvec2(ivec2(floor(cell / 8.0))), 107u)); + float patchMul = mix(0.4, 1.6, RandF(pseed)); + float vertMul = clamp(1.0 + bugs_vertical * ((cell.y + 0.5) / gridSize - 0.5) * 2.0, 0.0, 2.0); + uint seed = Hash(uvec3(uvec2(ivec2(cell)), 7u ^ floatBitsToUint(tBase))); + if (RandF(seed) > density * patchMul * vertMul) + return; + float appearAt = RandF(seed); + if (prog < appearAt) + return; + float r = clamp(specks_size, 0.05, 0.45) * mix(0.5, 1.0, RandF(seed)); + vec2 c = vec2(r) + vec2(RandF(seed), RandF(seed)) * max(1.0 - 2.0 * r, 0.0); + float ang = RandF(seed) * 6.2831853; + float el = mix(0.6, 1.0, RandF(seed)); + vec2 p = (g - cell - c) / r; + p = vec2(cos(ang) * p.x + sin(ang) * p.y, (-sin(ang) * p.x + cos(ang) * p.y) / el); + // irregular outline: a few lobes + float th = atan(p.y, p.x); + float lob = 1.0 + 0.18 * sin(3.0 * th + RandF(seed) * 6.28) + 0.10 * sin(5.0 * th + RandF(seed) * 6.28); + float d = length(p) / lob; + if (d >= 1.0) + return; + float edgeW = clamp(pixelUV * gridSize / r * 1.5, 0.05, 0.6); // ~1.5 px soft edge + float m = 1.0 - smoothstep(1.0 - edgeW, 1.0, d); + float a = m * specks_opacity * bugs_opacity * (0.6 + 0.4 * smoothstep(0.5, 0.95, d)); // the dried rim covers more + vec3 col = vec3(0.42, 0.34, 0.16) * mix(0.8, 1.15, RandF(seed)) * mix(1.0, 0.75, smoothstep(0.6, 0.95, d)); + vec3 nT = normalize(vec3(p / max(lob, 0.5) * 0.25 * bugs_bump, 1.0)); + accRGB = col * a + accRGB * (1.0 - a); + accN = nT * a + accN * (1.0 - a); + accA = a + accA * (1.0 - a); + accNA = accA; +} + +// Adds one layer of bugs to the premultiplied accumulators (accRGB, accA). +void bugLayer(float gridSize, float density, uint layerSeed, + float pixelUV, vec2 aspect, float haloStrength, float opacityMul, float lightMix, + inout vec3 accRGB, inout float accA, inout float smear, + inout vec3 accN, inout float accNA) +{ + vec2 cell = floor(f_coord * gridSize); + float fadeSpan = BUG_FADE_TIME / max(bugs_fill_time, 1.0); + + for (int oy = -1; oy <= 1; oy++) { + for (int ox = -1; ox <= 1; ox++) { + + vec2 ncell = cell + vec2(float(ox), float(oy)); + + // Dirt is patchy: big areas get more bugs than others; optional bias towards the top / bottom + uint pseed = Hash(uvec3(uvec2(ivec2(floor(ncell / 8.0))), layerSeed + 100u)); + float patchMul = mix(0.4, 1.6, RandF(pseed)); + float vy = (ncell.y + 0.5) / gridSize; // 0 = bottom of the UV, 1 = top + float vertMul = clamp(1.0 + bugs_vertical * (vy - 0.5) * 2.0, 0.0, 2.0); + float pCell = clamp(density * patchMul * vertMul, 0.0, 1.0); + + // 1st test, fixed per cell (cheap, no texture): can this cell hold a bug at all? + // Cells that fail it are skipped before the wiper mask is read. + float pMax = min(2.0 * pCell, 1.0); + uint cseed = Hash(uvec3(uvec2(ivec2(ncell)), layerSeed + 31u)); + if (RandF(cseed) > pMax) + continue; + + // When the wipers last swept over this cell. Whatever hit the glass before that + // moment is gone; the cell then gets a brand new set of bugs (the seed depends on + // that moment) that again take bugs_fill_time to build up. + float tc = (bugs_wiper_clean > 0.5) ? lastCleanTime((ncell + 0.5) / gridSize) : WIPER_NONE; + + float tBase; + float prog; + if (tc < -1.5e9) + { + // The engine forgot when the wipers last swept here (the camera was outside the + // cab). We cannot know how dirty the glass was, so show a fixed, non-growing level + // until a blade passes and gives us a real clean time again. + tBase = -1000.0; + prog = min(max(time - bugs_start_time, 0.0) / max(bugs_fill_time, 1.0), bugs_unknown_level); + } + else + { + tBase = max(bugs_start_time, tc); + prog = max(time - tBase, 0.0) / max(bugs_fill_time, 1.0); + } + if (prog <= 0.0) + continue; + + uint seed = Hash(uvec3(uvec2(ivec2(ncell)), layerSeed ^ floatBitsToUint(tBase))); + + // 2nd test, new after every wipe: together with the 1st one the cell holds a bug with + // probability pCell, and a wiped cell gets a new set of bugs + float present = RandF(seed); + if (present * pMax > pCell) + continue; + + // Moment (0..1 of the fill time) when this bug hits the glass + float appearAt = RandF(seed); + if (prog < appearAt) + continue; + float appear = smoothstep(appearAt, appearAt + fadeSpan, prog); + + float jx = RandF(seed); + float jy = RandF(seed); + vec2 center = (ncell + vec2(jx, jy)) / gridSize; + + float size = mix(BUG_SIZE_MIN, BUG_SIZE_MAX, RandF(seed)) / gridSize * mix(0.7, 1.0, appear); + float ang = RandF(seed) * 6.2831853; + float flipX = (RandF(seed) < 0.5) ? -1.0 : 1.0; + float choice = RandF(seed); + float tone = mix(0.8, 1.15, RandF(seed)); + + vec2 d = (f_coord - center) * aspect; + + // Blur ring around the splat (greasy smear): strongest next to the bug, fading out + // (the post pass blurs with a fixed radius in pixels, so a bug that is small on screen gets less of it) + float haloR = size * 0.5 * clamp(bugs_halo_size, 1.0, 1.6); + float dist = length(d); + if (dist < haloR) + { + float pxScale = clamp(size / max(pixelUV, 1e-6) / max(bugs_halo_px, 1.0), 0.15, 1.0); + smear = max(smear, (1.0 - smoothstep(0.5 * haloR, haloR, dist)) * haloStrength * appear * pxScale); + } + + float c = cos(ang); + float s = sin(ang); + vec2 r = vec2(c * d.x + s * d.y, -s * d.x + c * d.y); + r.x *= flipX; + + vec2 local = r / size + 0.5; + if (any(lessThan(local, vec2(0.0))) || any(greaterThan(local, vec2(1.0)))) + continue; + + // mip level from the on-screen size of the bug (derivatives are not + // allowed inside this non-uniform branch, so pixelUV comes from main) + float lod = clamp(log2(max(pixelUV / size * 0.5 * float(textureSize(raindropsatlas, 0).x), 1.0)), 0.0, 4.0); + vec4 t = textureLod(raindropsatlas, tileOffset(choice) + local * 0.5, lod); + + // fine specks: fainter and lighter than the big bugs (the splat bodies are nearly black) + t.rgb = mix(t.rgb, vec3(0.42, 0.34, 0.16), lightMix); + float a = clamp(t.a * appear * bugs_opacity * opacityMul, 0.0, 1.0); + + // relief: tangent-space normal of the splat -> glass UV frame (undo the mirror, then the rotation) + vec4 nm = textureLod(normalmap, tileOffset(choice) + local * 0.5, lod); + vec2 nxy = (nm.rg * 2.0 - 1.0) * bugs_bump * appear; // a splat that is still settling is flatter + nxy.x *= flipX; + vec2 nuv = vec2(c * nxy.x - s * nxy.y, s * nxy.x + c * nxy.y); + vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); + + // "over" compositing in premultiplied form + accRGB = t.rgb * tone * a + accRGB * (1.0 - a); + accN = nT * a + accN * (1.0 - a); + accA = a + accA * (1.0 - a); + accNA = accA; + } + } +} + +void main() +{ + // Derivatives first, in uniform control flow (no discard before them). + vec3 Ngl = normalize(f_normal); + vec3 dp1 = dFdx(f_pos.xyz); + vec3 dp2 = dFdy(f_pos.xyz); + vec2 duv1 = dFdx(f_coord); + vec2 duv2 = dFdy(f_coord); + vec3 dp2perp = cross(dp2, Ngl); + vec3 dp1perp = cross(Ngl, dp1); + vec3 Tgl = dp2perp * duv1.x + dp1perp * duv2.x; // tangent frame of the glass (T along u, B along v) + vec3 Bgl = dp2perp * duv1.y + dp1perp * duv2.y; + float invmax = inversesqrt(max(max(dot(Tgl, Tgl), dot(Bgl, Bgl)), 1e-20)); + Tgl *= invmax; + Bgl *= invmax; + + vec4 tex_color = texture(diffuse, f_coord); + // No discard on a (nearly) clear glass texture: clean glass between patches of faint dirt would + // otherwise be "bald" - no bugs, no halo. + + float gridSize = max(ceil(param[2].x), 1.0); + float pixelUV = max(length(dFdx(f_coord)), length(dFdy(f_coord))); // uniform control flow here + vec2 aspect = (bugs_uv_aspect >= 1.0) ? vec2(bugs_uv_aspect, 1.0) : vec2(1.0, 1.0 / max(bugs_uv_aspect, 0.01)); + + // 0 = never dirty yet; the real per-cell progress is computed in bugLayer (wipers reset it) + float progress = clamp((time - bugs_start_time) / max(bugs_fill_time, 1.0), 0.0, 1.0); + + vec3 bugRGB = vec3(0.0); // premultiplied + float bugA = 0.0; + float smear = 0.0; // blur ring around the bugs + vec3 bugN = vec3(0.0); // normals of the splats, premultiplied like the colour + float bugNA = 0.0; + if (progress > 0.0) + { + // fine specks underneath (procedural, one wiper read for the pixel), big bugs on top + if (specks_density > 0.0) + { + float tcPix = (bugs_wiper_clean > 0.5) ? lastCleanTime(f_coord) : WIPER_NONE; + speckLayer(gridSize * SPECK_SCALE, specks_density, tcPix, aspect, pixelUV, bugRGB, bugA, bugN, bugNA); + } + bugLayer(gridSize, bugs_density, 3u, pixelUV, aspect, 1.0, 1.0, 0.0, bugRGB, bugA, smear, bugN, bugNA); + // now and then a really big one, on top (its own coarse grid: same 3x3 search, bigger cells) + if (bugs_giant_density > 0.0) + bugLayer(gridSize / max(bugs_giant_scale, 1.0), bugs_giant_density, 11u, pixelUV, aspect, 1.0, 1.0, 0.0, + bugRGB, bugA, smear, bugN, bugNA); + // and rarely a huge one (about one per pane when it is fully dirty) + if (bugs_huge_density > 0.0) + bugLayer(gridSize / max(bugs_huge_scale, 1.0), bugs_huge_density, 13u, pixelUV, aspect, 1.0, 1.0, 0.0, + bugRGB, bugA, smear, bugN, bugNA); + } + + // Bugs over the glass (premultiplied "over") + float glassA = tex_color.a * alpha_mult; + float finalA = bugA + glassA * (1.0 - bugA); + vec3 premult = bugRGB + tex_color.rgb * glassA * (1.0 - bugA); + vec3 albedo = premult / max(finalA, 1e-4); + + // Reflections / specular belong to the glass only, not to the bugs + float glassShare = glassA * (1.0 - bugA) / max(finalA, 1e-4); + + vec3 fragcolor = ambient; + // Relief of the splats: tilt the glass normal by the splat's slope (the tilt direction is physical, + // so it does not matter which way the mesh normal points); flat where there is no bug. + vec3 bugDir = bugN + vec3(0.0, 0.0, 1.0) * (1.0 - bugNA); + vec3 fragnormal = Ngl; + if (bugNA > 0.001) + fragnormal = normalize(Ngl * max(bugDir.z, 0.05) + Tgl * bugDir.x + Bgl * bugDir.y); + float reflectivity = param[1].z * glassShare; + float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5 * glassShare + + bugs_gloss * bugA; // wet splats catch the sun and the headlights + legacy_gloss(); + + // Lit by sun, ambient and headlights like everything else (bugs glow in oncoming beams) + // most of the glass is clear (no bug, a clear glass texture): the lighting of the 4.6 renderers (the clusters of lamps, the + // shadows, the reflections) is skipped there, it would be multiplied by an alpha of ~0 + if (finalA > 0.002) + fragcolor = apply_lights(fragcolor, fragnormal, albedo, reflectivity, specularity, shadow_tone); + vec3 lit = apply_fog(fragcolor); + +#if BUGS_MATCH_RAIN_GLASS + vec4 color = vec4(lit * finalA, finalA); +#else + vec4 color = vec4(lit, finalA); +#endif + + out_color = POSTFX_ENABLED ? color : tonemap(color); + +#if BUGS_DEBUG_TIME + // Calibration: paints floor(time) as 8 red digits across the glass (the shader's own clock, in seconds). + // Read the number right after the scenario has loaded and put it into bugs_start_time. + { + const int SEG[10] = int[10](63, 6, 91, 79, 102, 109, 125, 7, 127, 111); + float dx = (f_coord.x - 0.10) / 0.10; + float dy = (f_coord.y - 0.42) / 0.08; + int idx = int(floor(dx)); + if (idx >= 0 && idx < 8 && dy >= 0.0 && dy <= 2.0) + { + float tt = floor(max(time, 0.0)); + float div = pow(10.0, float(7 - idx)); + int dig = int(mod(floor(tt / div), 10.0)); + vec2 q = vec2(fract(dx) / 0.8, dy); + int m = SEG[dig]; + bool on = false; + if ((m & 1) != 0 && q.y > 1.86 && q.x > 0.1 && q.x < 0.9) on = true; // a + if ((m & 2) != 0 && q.x > 0.86 && q.x < 1.0 && q.y > 1.0 && q.y < 1.9) on = true; // b + if ((m & 4) != 0 && q.x > 0.86 && q.x < 1.0 && q.y > 0.1 && q.y < 1.0) on = true; // c + if ((m & 8) != 0 && q.y < 0.14 && q.x > 0.1 && q.x < 0.9) on = true; // d + if ((m & 16) != 0 && q.x < 0.14 && q.y > 0.1 && q.y < 1.0) on = true; // e + if ((m & 32) != 0 && q.x < 0.14 && q.y > 1.0 && q.y < 1.9) on = true; // f + if ((m & 64) != 0 && q.y > 0.93 && q.y < 1.07 && q.x > 0.1 && q.x < 0.9) on = true; // g + if (on) + out_color = vec4(1.0, 0.05, 0.05, 1.0); + } + } +#endif + + if (MOTIONBLUR_ENABLED) + { + // alpha 0 = blending keeps the scene's own motion vectors + // the bug itself stays sharp (1 - bugA); no blur over opaque parts of the pane (1 - glassA) + float blurMask = clamp(smear * bugs_halo_blur * (1.0 - bugA) * (1.0 - smoothstep(0.5, 0.95, glassA)), 0.0, 1.0); + out_motion = (blurMask >= 0.01) ? vec4(WS_ENC * blurMask, 0.0, 0.0, 1.0) : vec4(0.0); + } +} From e2a9d5339d4d1cd6e62dda8a43e3b4e66bf1b64a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 1 Nov 2026 19:35:09 +0100 Subject: [PATCH 040/123] Rain on the windscreen: drops of an atlas, haze and refraction in the post-processing mat_rain_windscreen draws the drops, the micro droplets and the rivulets from an atlas of drops with its normal map (textures/fx/raindrops-atlas and raindrops_normalmap, the 2x2 drops on the left, the rivulet sprites on the right): the drops land, grow and run down, the wipers clear them and they come back, the air at speed drives many small drops with trails (some of them long), the haze over the wet glass grows with the rain fallen since the wiper went over it. The glass asks the post-processing for its haze and for the view bent by its drops in the velocity target (rain_windscreen_haze.glsl); postfx_taa.frag does it every frame with the temporal anti-aliasing (the drops blended with the last frame at the same pixel, so they don't shimmer with its offsets), postfx_motionblur.frag without it. The picture of this frame with the depth of the whole frame, so the cab is never pulled into a drop; the bright lights of the haze kept from smearing (a karis average with the light it loses given back up to a limit), the lights in the drops from the mipmaps of the image of the reflections (OpenGL 4.6). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_rain_windscreen.frag | 2131 +++++++++++------------ shaders/ogl46/postfx_motionblur.frag | 23 +- shaders/ogl46/postfx_taa.frag | 49 + shaders/ogl46/rain_windscreen_haze.glsl | 233 +++ shaders/vk14/mat_rain_windscreen.frag | 2131 +++++++++++------------ shaders/vk14/postfx_motionblur.frag | 25 +- shaders/vk14/postfx_taa.frag | 50 + shaders/vk14/rain_windscreen_haze.glsl | 233 +++ 8 files changed, 2601 insertions(+), 2274 deletions(-) create mode 100644 shaders/ogl46/rain_windscreen_haze.glsl create mode 100644 shaders/vk14/rain_windscreen_haze.glsl diff --git a/shaders/ogl46/mat_rain_windscreen.frag b/shaders/ogl46/mat_rain_windscreen.frag index 91ed0ad96..06a221f89 100644 --- a/shaders/ogl46/mat_rain_windscreen.frag +++ b/shaders/ogl46/mat_rain_windscreen.frag @@ -1,29 +1,44 @@ #version 460 core #define STAGE_FRAGMENT 1 -// Windshield rain and snow -// by @lcddisplay; wiper movement @MichauSto; water on the glass rewritten as a model of drops lying on it +// Windshield rain effects - v3 (rewrite) +// by @lcddisplay; wiper movement @MichauSto; rain v3: drop layers, drop life, rivulets that sweep drops // -// the material: the textures diffuse (the glass) and wipermask (a blade per channel, r g b a: 0 where it doesn't reach, elsewhere -// the place of the blade over its sweep, 0 at rest .. 1 at the far end, at which it goes over the place). raindropsatlas and -// raindrop_grid_size aren't used any more, they stay so the materials which name them still load. rain_scale (1 when not given) -// scales the drops and the flakes. water_slot is given by the renderer (1 + the glass of the simulation, 0 none), not by the -// material. the block of the scene: rain_params (x: how heavy the rain or snow is, z: 1 for snow, w: temperature of the air), -// wiper_pos, wiper_timer_out, wiper_timer_return (the blades of the vehicle of the camera) and rain_wind (the air against it). +// What is on the glass: +// 1. Micro droplets: a dense grid of tiny, static droplets. Procedural (no texture reads): a spherical cap +// per droplet. They make the glass look wet between the bigger drops. +// 2. Drops: one per grid cell (raindrop_grid_size), shape from the 2x2 drop tiles of the atlas +// (normalmap: rg = normal xy, b = height, a = mask). A drop lands (quick pop), sits still for +// drop_life_min..drop_life_max seconds, then makes room for a new one. Drops do NOT slide: all motion is +// done by the rivulets (a sliding drop used to leave its 3x3 neighbourhood and got cut off). +// Sizes are skewed (many medium, few big) and the tiles are randomly mirrored (8 shapes instead of 4). +// Where drops overlap, the higher one wins (no averaged "ghost" normals). +// 3. Rivulets: a drop runs down in stick-slip fashion and leaves a wet trail (4 sprites in the right half +// of the atlas, 256 x 1024: head in the bottom STREAK_HEAD_FRAC, trail above). The head sweeps up every +// drop and droplet on its way: the trail band is clean until the rivulet fades out. +// The trail right above the head is taken from the sprite part that touches the head, then it blends +// into the trail pattern that is fixed to the glass (beads stay where they were left). // -// the glasses of the cab of the train are simulated (gfx::windscreen_water, water_*.comp, water.glsl): the raindrops land as often -// as the rain hits the glass, splashing; the drops lie held by surface tension until gravity and the drag of the air pull them -// harder, then slide in stops and goes, wetting their paths (the next ones follow them into rivulets) and leaving droplets behind; -// the drops which touch flow together; the blades take the water along, gather it into a bead and leave it at the ends of their -// sweep, where it runs down; the flakes stick and melt. here the drops of the simulation are drawn where the fragment is, and the -// wetted paths as a thin film. elsewhere (the windows of other vehicles, a glass the simulation has no room for) the water is made -// up from the time alone: drops landing, growing and sliding along tracks, the blades pushing a ridge and leaving the water at the -// edge of their sweep. +// Shading: the grey atlas (bright rim, dark middle) is read once per pixel, only for the drop that wins the +// pixel (it used to be read for all 9 neighbours). Micro droplets are shaded analytically. // -// the water is a field of soft kernels (metaballs): drops coming close flow together, and a drop is a few kernels, so the drops -// are of many shapes. a drop is a lens holding a sharp picture of the place around it turned over (the image of the last frame -// where the screen holds it, the sky and the ground elsewhere), its edge shows the light of the sky reflected inside it; the lamps -// and the headlights light the water up; the film the blades leave breaks up behind them and the lights seen through it are drawn -// into lines towards their pivot; the wet glass is a little milky +// Refraction / blur (OpenGL 4.6, the renderer with the screen space reflections): the glass reads the image of the last +// frame the renderer keeps for the reflections (ssr_history, with mipmaps) and the depth of the scene (scene_depth): +// - drops act as small lenses: the pixel shows the scene on the opposite side of the drop centre, so every drop holds a +// small, flipped picture (drop_lens); rivulets bend the view by Snell's law from their normal, +// - bright lights near a drop (signals, lamps, headlights) show up in it, +// Works standing still, with the motion blur off and with taa. Needs gfx.ssr (default: medium); without it the drops show +// the sky / ground only, faintly. +// The haze of the wet glass is blurred by the post-processing, from the picture of this frame: the glass writes a request +// into the velocity target (x = 64 * strength, y = 0) and postfx_taa.frag (with gfx.antialiasing taa: every frame) or +// postfx_motionblur.frag (without it: only while something moves) blur the picture there (rain_windscreen_haze.glsl). +// +// Speed: the air against the vehicle (rain_wind) drives the water: at speed a second layer of rivulets runs along its push +// (up a front glass, back along a side window) and sweeps the drops up on its way, the drops are stretched along the push, +// the haze grows. Standing still the rain is as it always was. +// +// OpenGL 4.6 renderer (feat/gl46-migration): headlights and lamps are clustered, calc_headlights takes the +// screen-space derivatives of f_pos, the sun glint follows the cloud shadow. Lamps (cab lamp, scenery) light up +// the drops too (drop_lamp_scatter). layout(location = 0) in vec3 f_normal; layout(location = 2) in vec2 f_coord; @@ -37,1176 +52,1020 @@ layout(location = 1) out vec4 out_motion; #pragma texture(diffuse, 0, sRGB_A) #pragma texture(raindropsatlas, 1, sRGB_A) #pragma texture(wipermask, 2, sRGB_A) +#pragma texture(normalmap, 3, RGBA) // rg = normal xy, b = height, a = mask; 2048 x 1024 (drops left, rivulets right), linear #pragma param(color, 0, 0, 4, diffuse) #pragma param(diffuse, 1, 0, 1, diffuse) #pragma param(specular, 1, 1, 1, specular) #pragma param(reflection, 1, 2, 1, zero) #pragma param(glossiness, 1, 3, 1, glossiness) #pragma param(raindrop_grid_size, 2, 0, 1, one) -#pragma param(rain_scale, 2, 1, 1, one) #include "light_common.glsl" #include "apply_fog.glsl" #include "tonemapping.glsl" -#include "water.glsl" +#include "random.glsl" layout(binding = 0) uniform sampler2D diffuse; layout(binding = 1) uniform sampler2D raindropsatlas; layout(binding = 2) uniform sampler2D wipermask; +layout(binding = 3) uniform sampler2D normalmap; -const float RW_PI = 3.14159265; -// refractive index of water -const float RW_IOR = 1.333; -// the falling particles (particles_precipitation.comp, rendering/common/gpuparticles.cpp): the diameters of the flakes, metres, -// and how fast the rain and the snow fall, m/s -const vec2 RW_SNOW_DIAMETER = vec2(0.004, 0.012); -const float RW_RAIN_FALL = 7.0; -const float RW_SNOW_FALL = 1.1; -// a drop is a lens: it holds a sharp picture of the place around it, turned over through its middle, RW_LENS times as far out -// as the fragment is from the middle (and as much smaller), with this share of the bending of the view by the surface on top -const float RW_LENS = 2.0; -const float RW_LENS_BEND = 0.15; -// the drag of the air going along the glass: the speed at which it equals the weight of a drop, m/s; and the share of the air -// meeting the glass head on which turns up along it. so the water goes up a glass the sooner the more it leans back: on a -// vertical glass at about 250 km/h, leaning 20 degrees at about 130 km/h, 45 degrees at about 80 km/h -const float RW_DRAG_SPEED = 24.0; -const float RW_HEAD_ON = 0.35; -// the water is a field summed from soft kernels (metaballs) and its surface is where the field is RW_SURFACE: drops which come -// close flow together the way surface tension pulls them. a kernel alone reaches the surface at RW_EDGE of its radius -const float RW_SURFACE = 0.25; -const float RW_EDGE = 0.61; +// --- Haze of the wet glass (blur) ------------------------------------------------ +// The haze follows the rain and is wiped away by the wipers, as before (fully blurred from a quarter of the haze on). +const float blur_amount = 1.0; // strength of the haze: 0 = off, 1 = full +// after the wiper the haze grows with the rain fallen on the glass since (intensity x seconds) from nothing up to its full +// strength, which is the intensity of the rain (cloud cover 1.5 -> 0.5). where no wiper reaches it is as always +const float haze_fill = 12.0; // rain to mist the glass up fully: seconds of the heaviest rain (2x as long at 1.5) +const float haze_curve = 1.0; // > 1: slow at first, then more and more +const float haze_speed = 1.0; // at speed the haze grows: x (1 + haze_speed) at full speed (see wind_drag_gain) +const float WS_BEND_ENC = 60.0; // the drop request in the velocity target; must match rain_windscreen_haze.glsl +const float WS_DROP_BIAS = 192.0; +const float WS_ENC = 64.0; // the haze request in the velocity target; must match rain_windscreen_haze.glsl -// the glass at the fragment: the view space steps along it for a step of the coordinates of the glass (metres along the axes -// of the model, see main()), and the size of a pixel on it, metres -vec3 rw_tu; -vec3 rw_tv; -float rw_pixel; +// --- Drops (atlas tiles) ------------------------------------------------------ +const float drop_density = 0.6; // share of grid cells holding a drop at full rain (scaled by rain intensity) +const float drop_size_min = 0.45; // drop size in grid cells +const float drop_size_max = 1.15; +const float drop_size_bias = 1.8; // >1 = more small/medium drops, fewer big ones +const float drop_life_min = 14.0; // seconds a drop sits on the glass +const float drop_life_max = 45.0; +const float drop_appear = 0.18; // seconds of the landing "pop" +const float drop_fade = 1.5; // seconds a drop takes to vanish at the end of its life +const float drop_sag = 0.12; // max vertical stretch of a resting drop (gravity) -// how the water on the glass behaves here, set by main() -float rw_scale; // size of the drops (param rain_scale) -float rw_since; // seconds since a blade last cleaned the place -float rw_period; // seconds between the small drops landing on a place of one -float rw_grow; // seconds the drops need after a wipe to grow big enough to slide -float rw_rate; // how fast the glass gathers the rain against a standing vertical glass in the heaviest rain -float rw_push; // the force on a drop along the glass, in units of its weight -vec2 rw_down; // the way gravity pulls along the glass (coordinates of the glass, unit) -vec2 rw_flow; // the way the air goes along the glass (unit, 0 in still air) +// --- Micro droplets ------------------------------------------------------------- +const float micro_density = 0.45; // share of micro cells holding a droplet at full rain, 0 = off +const float micro_scale = 3.0; // micro grid = raindrop_grid_size * micro_scale +const float micro_size_min = 0.12; // droplet radius in micro cells +const float micro_size_max = 0.40; +const float micro_bulge = 0.80; // slope of the droplet dome at its rim (0..0.95) +const float micro_life = 60.0; // average seconds a droplet lives -// the field of the water: the sum of the kernels, its gradient along the glass (view space) and the sums for the mean radius of -// the drops it is made of -float rw_field = 0.0; -vec3 rw_fgrad = vec3(0.0); -float rw_fsize = 0.0; -float rw_fweight = 0.0; +// --- Look of the drops (grey atlas for drops / rivulets, the same look computed for micro droplets) --------- +const float drop_rim_start = 0.30; // micro droplets: dome slope (1 - nz) where the bright rim starts +const float drop_rim_end = 0.80; // ... and where it is fully bright +const float drop_light_side = 0.25; // micro droplets: brighter on the upper-left side +const float drop_center_alpha = 0.25; // how much the dark middle of a drop covers the scene +const float drop_rim_alpha = 0.85; // how much the bright rim covers the scene +const float drop_shade_alpha = 0.30; // faint alpha over the whole dome (carries the glints) -// the water at the fragment: the thickness of the highest water there (metres), its gradient (view space), the radius of the -// curvature of its surface (metres: how much it bends the view across a pixel) and how much of the pixel it covers -float rw_height = 0.0; -vec3 rw_slope = vec3(0.0); -float rw_curve = 1.0; -float rw_cover = 0.0; -// from the middle of the drop which gives the water to the fragment (view space, metres), 0 for spread water -vec3 rw_offset = vec3(0.0); -// the last time the water a blade pushes went over the fragment, taking the drops lying there with it -float rw_cleared = -1.0e9; +// --- Light on the drops -------------------------------------------------------- +const float drop_ior = 1.33; // refraction index of water +const float drop_refract = 0.5; // rivulets: strength of the picture shift (Snell; 1 = physical) +const float drop_lens = 2.0; // drops: lens field, the drop shows (1 + drop_lens) x its own size, flipped +const float drop_lens_mix = 0.7; // drops: 1 = lens picture, 0 = Snell shift like the rivulets +const float drop_env = 0.6; // reflection of the environment on the dome (0 = off) +const float drop_glint_strength = 5.0; // sun / moon glint brightness +const float drop_glint_sharpness = 40.0; // sun / moon glint size (lower = a wider lobe, so more drops catch it) +const float drop_sheen = 0.3; // wide, soft sun sheen on the domes around the sharp glint +const float drop_headlight_scatter = 3.0; // how much drops light up in headlight beams +const float drop_lamp_scatter = 1.0; // GL 4.6: how much drops light up from lamps (station lamps, signals), 0 = off +const float drop_light_near = 4.0; // lights nearer than this (metres; the own vehicle) don't light the drops, full from 2x +const float drop_light_max = 3.0; +const float drop_dark_lum = 0.25; // average brightness of the screen (scene units) below which the drops darken with it // the most the lamps and headlights add to a drop (scene units, before tonemapping) -uvec4 rw_pcg4d(uvec4 v) +// --- Rivulets (drops that run down and leave a wet trail) --------------------------------- +// Sizes are in "drop cells" (1 cell = 1 / raindrop_grid_size of the glass UV). +const float streak_density = 1.00; // share of cells carrying a rivulet (scaled by the rain intensity), 0 = off +const float streak_cell = 6.0; // width of a rivulet cell in drop cells +const float streak_run = 20.0; // height of a rivulet cell in drop cells = the longest run of one rivulet +const float streak_head = 1.7; // mean width of the drop head, in drop cells (randomised 0.75x .. 1.25x) +const float streak_period = 40.0; // seconds a rivulet lives (it runs for ~90% of that and then fades out), average +const float streak_wiggle = 0.35; // how far the path swings sideways, in head widths (0 = straight) +const float streak_wiggle_speed = 0.5; // speed of the little waves that flow down the trail +const float streak_flow = 0.15; // ripples flowing down inside the trail (shows in refraction and glints), 0 = off +const float streak_uv_aspect = 1.0; // glass width / height in UV terms (1 = same stretch as the drops) +const float streak_sweep = 1.0; // 1 = the head sweeps up drops on its way (clean band behind it), 0 = off +const float streak_sweep_width = 0.9; // width of the swept band, in head widths +const float streak_link = 1.5; // head widths above the head where the trail is taken from the sprite part + // that touches the head (so the trail always leaves the head cleanly) + +// --- Speed: the air against the vehicle (rain_wind) drives the water on the glass -------------------- +// The force on the water along the glass: its weight (gravity) and the drag of the air going along the glass (and of the +// share of the air meeting it head on which turns up along it), as in the stock shader of the renderer. Standing still +// (or in a light wind) nothing of it shows: the rain lands, grows and runs down as it always did. +const float wind_drag_gain = 4.0; // how strongly the air drives the water (1 = the drag of the stock shader: on a + // vertical front glass the water would go up only at ~250 km/h) +const float wind_streaks = 3.0; // density of the rivulets driven by the air, at full drag (x streak_density) +const float wind_cell_scale = 0.36; // the rivulets of the air: their cells this much narrower ... +const float wind_run_scale = 0.28; // ... and shorter than those of gravity: many small drops with short trails +const float wind_head_scale = 0.55; // their heads this much smaller +const int wind_layers = 4; // layers of them, each with drops of its own (1 .. 4) +const float wind_long_run = 1.6; // the last layer: its trails this much longer than those of gravity (the long ones, a part of all) +const float wind_streak_period = 14.0; // seconds a rivulet driven by the air lives (they run faster than the ones of gravity) +const float drop_wind_stretch = 0.4; // drops are stretched up to this much along the push of the air (0 = off) +const float WS_DRAG_SPEED = 24.0; // speed of the air along the glass at which its drag equals the weight of a drop, m/s +const float WS_HEAD_ON = 0.35; // share of the air meeting the glass head on which turns up along it +const float WS_WIND_STEP = 0.1309; // the direction of the rivulets of the air in steps of 7.5 degrees (no seams on a + // curved glass, where every triangle would turn them a little) + +#ifndef STREAK_FLIP_Y +#define STREAK_FLIP_Y 0 // set to 1 if the rivulets run UP the glass (head on top) +#endif +const float STREAK_TAIL_SCALE = 1.5; // the trail pattern of the sprite is drawn this much longer than native +const float STREAK_HEAD_FRAC = 0.22; // part of the sprite height used by the drop head (= HEAD_FRAC of the atlas generator) + +const float WS_INSIDE = 0.3; // metres beyond the glass nearer than which the image is taken for the inside of the cab + // (in the rain the cab isn't in the depth: the nose of the own vehicle is outside) +const float WS_REFR_MAXPX = 96.0; // largest picture shift of a drop, screen pixels +const float WS_REFR_MIX = 0.85; // 0 = no refraction, 1 = only the refracted picture +const float WS_LIGHT_GAIN = 1.0; // brightness of the lights near a drop shown in it (0 = off) +const float WS_LIGHT_CONTRAST = 3.0; // a light: this many times brighter than the place around it + +const vec3 DROP_LIGHT = vec3(-0.5527, 0.6532, 0.5226); // same light as the atlas generator (upper left) + +// the surroundings in a view space direction where the image doesn't hold them: the environment map above the horizon, +// the ground below it, blurred by Lod (as in the stock mat_rain_windscreen.frag) +vec3 wsSurroundings(vec3 direction, float lod) { - v = v * 1664525u + 1013904223u; - v.x += v.y * v.w; - v.y += v.z * v.x; - v.z += v.x * v.y; - v.w += v.y * v.z; - v ^= v >> 16u; - v.x += v.y * v.w; - v.y += v.z * v.x; - v.z += v.x * v.y; - v.w += v.y * v.z; - return v; + vec3 world = mat3(inv_view) * direction; + vec3 sky = envmap_sample_rough(normalize(vec3(world.x, max(world.y, 0.0), world.z)), clamp(lod / 8.0, 0.0, 1.0)); + float below = smoothstep(-0.03 - 0.05 * lod, 0.25 + 0.05 * lod, -world.y); + if ((below <= 0.0) || (false == ENVMAP_ENABLED)) + return sky; + return mix(sky, reflection_ground(), below); } -// four numbers 0 .. 1 of a cell of a layer -vec4 rw_random(ivec2 cell, uint layer, uint index) +// what is seen through the glass in a view space direction: the image of the last frame where it holds the place, Distance +// away along the direction (0: far), blurred by Lod; Share: how much of it the image gave. Fade: towards the edges of the +// image the surroundings take over. The inside of the cab (near the camera in the depth) is never taken: the surroundings +// stand for it (else the drops would show the dark walls of the cab) +vec3 wsBehind(vec3 direction, float lod, float distance, out float share, bool fade) { - return vec4(rw_pcg4d(uvec4(uvec2(cell), layer, index))) * (1.0 / 4294967296.0); + share = 0.0; + vec3 around = wsSurroundings(direction, lod); + if (ssr_params.x < 1.0) + return around; + vec4 previous = ssr_reprojection * ((distance > 0.0) ? vec4(direction * distance, 1.0) : vec4(direction, 0.0)); + if (previous.w <= 1e-5) + return around; + vec2 coords = (previous.xy / previous.w) * 0.5 + 0.5; + vec2 edges = min(coords, 1.0 - coords); + share = fade ? smoothstep(0.0, 0.04, min(edges.x, edges.y)) : step(-0.02, min(edges.x, edges.y)); + coords = clamp(coords, vec2(0.0), vec2(1.0)); + if (share <= 0.0) + return around; + ivec2 size = textureSize(scene_depth, 0); + float depth = texelFetch(scene_depth, clamp(ivec2(coords * vec2(size)), ivec2(0), size - 1), 0).r; + float near = projection[3][2]; + if ((depth > 0.0) && (near / depth < -f_pos.z + WS_INSIDE)) + { + share = 0.0; + return around; + } + vec3 color = textureLod(ssr_history, coords, clamp(lod, 0.0, ssr_params2.x)).rgb; + if (any(isnan(color)) || any(isinf(color))) + { + share = 0.0; + return around; + } + return mix(around, max(color, vec3(0.0)), share); } -float rw_noise(float x, uint layer) +float wsLum(vec3 c) { - float i = floor(x); - float f = x - i; - float a = rw_random(ivec2(int(i), 0), layer, 7u).x; - float b = rw_random(ivec2(int(i) + 1, 0), layer, 7u).x; - return mix(a, b, f * f * (3.0 - 2.0 * f)); + return dot(c, vec3(0.2126, 0.7152, 0.0722)); } -// value noise 0 .. 1 (x) with its gradient (yz) -vec3 rw_noise2(vec2 p, uint layer) +// bright lights near a drop (signals, lamps, headlights): a drop is a wide-angle lens and picks them up. A light is where a +// fine mip level of the image (~11 px around) is much brighter than a coarse one (~90 px around) +vec3 wsLightGlow(vec3 direction, float distance) { - vec2 i = floor(p); - vec2 f = p - i; - vec2 u = f * f * (3.0 - 2.0 * f); - vec2 du = 6.0 * f * (1.0 - f); - ivec2 c = ivec2(i); - float a = rw_random(c, layer, 8u).x; - float b = rw_random(c + ivec2(1, 0), layer, 8u).x; - float d = rw_random(c + ivec2(0, 1), layer, 8u).x; - float e = rw_random(c + ivec2(1, 1), layer, 8u).x; - float k1 = b - a; - float k2 = d - a; - float k4 = a - b - d + e; - return vec3(a + k1 * u.x + k2 * u.y + k4 * u.x * u.y, du * vec2(k1 + k4 * u.y, k2 + k4 * u.x)); -} - -// P turned by A (radians). every set of drops is laid on its own grid, turned and shifted against the others, so the drops line -// up neither with each other nor along the glass -vec2 rw_turn(vec2 p, float a) -{ - float c = cos(a); - float s = sin(a); - return vec2(c * p.x - s * p.y, s * p.x + c * p.y); -} - -// a gradient given along the coordinates of the glass, view space -vec3 rw_along(vec2 gradient) -{ - return rw_tu * (gradient.x / dot(rw_tu, rw_tu)) + rw_tv * (gradient.y / dot(rw_tv, rw_tv)); -} - -// the gradient along the glass (view space) of a value of the fragments, from how it changes from pixel to pixel; Dpdx, Dpdy: -// the steps of the position, Normal: of the glass -vec3 rw_gradient(float value, vec3 dpdx, vec3 dpdy, vec3 normal) -{ - vec3 r1 = cross(dpdy, normal); - vec3 r2 = cross(normal, dpdx); - float det = dot(dpdx, r1); - float dx = dFdx(value); - float dy = dFdy(value); - return (abs(det) > 1e-14) ? (dx * r1 + dy * r2) / det : vec3(0.0); -} - -// a kernel of the water, Offset (view space) from its centre to the fragment: alone it makes water of the radius Visible, -// Weight 1 .. 0 as it goes. water smaller than a pixel would only flicker, it is left to the haze of the wet glass -void rw_kernel(vec3 offset, float visible, float weight) -{ - if ((weight <= 0.0) || (visible < 0.5 * rw_pixel)) - return; - // a drop a pixel or two across is grain rather than a lens: it fades into the haze of the wet glass - weight *= smoothstep(0.5 * rw_pixel, 2.0 * rw_pixel, visible); - float support = visible / RW_EDGE; - float q = dot(offset, offset) / (support * support); - if (q >= 1.0) - return; - float k = 1.0 - q; - float k3 = weight * k * k * k; - rw_field += k3; - rw_fgrad += offset * (-6.0 * weight * k * k / (support * support)); - rw_fsize += k3 * visible; - rw_fweight += k3; -} - -// a kernel at the Offset in the coordinates of the glass -void rw_blob(vec2 offset, float visible, float weight) -{ - rw_kernel(offset.x * rw_tu + offset.y * rw_tv, visible, weight); -} - -// a drop lying on the glass: a few kernels, sagging down the glass and lopsided as Shape (random 0 .. 1) says -void rw_drop(vec2 offset, float visible, float weight, vec4 shape) -{ - rw_blob(offset, visible, weight); - if (visible < 1.5 * rw_pixel) - return; - vec2 side = vec2(-rw_down.y, rw_down.x); - vec2 sag = (rw_down * (0.2 + 0.35 * shape.x) + side * ((shape.y - 0.5) * 0.7)) * visible; - rw_blob(offset - sag, visible * mix(0.6, 0.85, shape.z), weight); - if (shape.w > 0.4) - { - float angle = shape.w * 40.0; - rw_blob(offset - vec2(cos(angle), sin(angle)) * (0.6 * visible), visible * mix(0.4, 0.6, shape.x), weight); - } -} - -// water spread over the glass (a film, a ridge): its thickness, the gradient of it (view space), the radius of the curvature of -// its surface and how much of the pixel it covers -void rw_sheet(float thickness, vec3 slope, float curve, float cover) -{ - if (cover <= 0.0) - return; - rw_cover = max(rw_cover, cover); - if (thickness > rw_height) - { - rw_height = thickness; - rw_slope = slope; - rw_curve = curve; - rw_offset = vec3(0.0); - } -} - -// the surface of the water of the field: a drop is a cap of a sphere, flat lens of the contact angle Contact (radians) the water -// makes with the glass. how far across a drop the fragment is follows from the field (inverting the kernel), the height and -// the slope of the cap from that: the slope rises slowly from the middle and steeply only close to the edge, where it reaches -// the contact angle; where drops flowed together the field is above that of a drop alone and the water is flat. the edge is -// antialiased by how fast the field changes across a pixel -void rw_settle(float contact) -{ - if (rw_field <= 0.5 * RW_SURFACE) - return; - float gradient = length(rw_fgrad); - float cover = clamp((rw_field - RW_SURFACE) / max(gradient * rw_pixel, 1e-3) + 0.5, 0.0, 1.0); - if (cover <= 0.0) - return; - float mean = rw_fsize / max(rw_fweight, 1e-12); - // 0 in the middle of a drop, 1 at its edge - float across = min(sqrt(max(1.0 - pow(min(rw_field, 1.0), 1.0 / 3.0), 0.0)) / RW_EDGE, 1.0); - float s = sin(contact); - float rs = across * s; - float root = sqrt(max(1.0 - rs * rs, 1e-4)); - float sphere = mean / s; - vec3 slope = (gradient > 1e-9) ? rw_fgrad * ((rs / root) / gradient) : vec3(0.0); - float height = max(sphere * (root - cos(contact)), 0.0); - bool top = height > rw_height; - rw_sheet(height, slope, sphere, cover); - // the field rises towards the middle of the drop - if (top && (gradient > 1e-9)) - rw_offset = rw_fgrad * (-across * mean / gradient); -} - -// the blades. a channel of the mask of the wipers is a blade: 0 where it doesn't reach, elsewhere the place of the blade over its -// sweep (0 at rest .. 1 at the far end) at which it goes over the place. wiper_pos: where the blade is (0 .. 1 on its way out, -// 1 + where it is on its way back), wiper_timer_out / _return: the last time it lay at its start / was at its far end -struct rw_wipe_s -{ - float since; // seconds since a blade last went over the place (large where none reaches) - float ahead; // 0 .. 1, how close in front of a moving blade the place is (the water the blade pushes) - float front; // how far in front of the nearest moving blade the place is, units of the mask (1 where none) - float swept; // 0 .. 1, how much of its way the blade in front did, the water it gathered on the way - float working; // 0 .. 1, the blades went lately -}; - -rw_wipe_s rw_wipe(vec4 mask) -{ - rw_wipe_s wipe = rw_wipe_s(1.0e4, 0.0, 1.0, 0.0, 0.0); - for (int i = 0; i < 4; ++i) - { - float m = mask[i]; - if (m < 0.001) - continue; - float pos = wiper_pos[i]; - bool back = pos > 1.0; - float blade = back ? pos - 1.0 : pos; - float t0 = wiper_timer_out[i]; - float t1 = wiper_timer_return[i]; - // when the blade went over the place last: on this stroke, the blade moving at an even pace from its end, or on the - // stroke before, which took as long as the time between the ends (if the blade lay at its end longer, two seconds) - float pass; - float front; // how far in front of the blade the place is (units of the mask), below 0 behind it - if (back) - { - pass = (m >= blade) ? t1 + (time - t1) * ((1.0 - m) / max(1.0 - blade, 1e-3)) : t0 + m * clamp(t1 - t0, 0.0, 2.0); - front = blade - m; - } - else - { - pass = (m <= blade) ? t0 + (time - t0) * (m / max(blade, 1e-3)) : t1 + (1.0 - m) * clamp(t0 - t1, 0.0, 2.0); - front = m - blade; - } - wipe.since = min(wipe.since, max(time - pass, 0.0)); - float moving = smoothstep(0.0, 0.03, blade) * smoothstep(1.0, 0.97, blade); - float ahead = (front > 0.0) ? (1.0 - smoothstep(0.0, 0.035, front)) * moving : 0.0; - wipe.ahead = max(wipe.ahead, ahead); - if ((front > 0.0) && (moving > 0.5)) - wipe.front = min(wipe.front, front); - wipe.swept = max(wipe.swept, ahead * (back ? 1.0 - blade : blade)); - float working = 1.0 - smoothstep(4.0, 30.0, time - t1); - wipe.working = max(wipe.working, working); - } - return wipe; -} - -// a place of the glass a blade reaches -bool rw_reached(vec2 coords) -{ - return any(greaterThanEqual(textureLod(wipermask, clamp(coords, vec2(0.0), vec2(1.0)), 0.0), vec4(0.001))); -} - -// the edge of the sweep of the blades, where they push the water out to: 0 where a blade reaches, else the share of the places -// around at Reach (metres along the glass) which a blade reaches. found from where the blades reach and not from the values of -// the mask, which may stay at the end of the sweep over a wide part of the glass. Maskstep: the coordinates of the mask for a -// step along the glass -float rw_rim(vec2 coords, float reach, mat2 maskstep) -{ - if (rw_reached(coords)) - return 0.0; - float inside = 0.0; - for (int k = 0; k < 6; ++k) - { - float angle = float(k) * (RW_PI / 3.0); - inside += rw_reached(coords + maskstep * (vec2(cos(angle), sin(angle)) * reach)) ? 1.0 : 0.0; - } - return inside / 6.0; -} - -// whether the edge of the sweep of the blades is within Reach of the place -bool rw_border(vec2 coords, float reach, mat2 maskstep) -{ - bool here = rw_reached(coords); - for (int k = 0; k < 6; ++k) - { - float angle = float(k) * (RW_PI / 3.0); - if (rw_reached(coords + maskstep * (vec2(cos(angle), sin(angle)) * reach)) != here) - return true; - } - return false; -} - -// how far along its way a sliding drop is at the share T of the time it takes: it stops and goes, the more smoothly the harder -// it is pushed -float rw_stickslip(float t, float seed) -{ - t = clamp(t, 0.0, 1.0); - float s = t * 3.0; - float i = floor(s); - float stuck = (i + smoothstep(0.25 + 0.4 * seed, 1.0, s - i)) / 3.0; - return mix(stuck, t, smoothstep(0.8, 2.0, rw_push)); -} - -// the track of the water down a column of the glass (Column: its index, Width: of a column, Y: metres up the way): where it -// is across, metres. the water keeps to the way wetted before, so every drop of a column goes the same way, wavy, with kinks -// where the glass held it -float rw_path(int column, float y, float width, uint layer) -{ - float slow = rw_noise(y / (0.05 * rw_scale) + float(column) * 7.31, layer) - 0.5; - float k = y / (0.008 * rw_scale); - float i = floor(k); - float a = rw_random(ivec2(column, int(i)), layer + 500u, 3u).x; - float b = rw_random(ivec2(column, int(i) + 1), layer + 500u, 3u).x; - float kinks = mix(a, b, smoothstep(0.15, 0.85, k - i)) - 0.5; - return (float(column) + 0.5 + 0.4 * slow + 0.2 * kinks) * width; -} - -// the drops which grew big enough to slide, and the streams they leave: Q the place across and up the way they go (Side, Down: -// those directions in the coordinates of the glass), Share of them going this way. a column of the glass carries the water of -// a track; a drop starts somewhere in a cell of the column now and then, slides down with stops, thinning, and leaves a stream -// which drains into beads and dries -void rw_sliders(vec2 q, vec2 side, vec2 down, uint layer, float share) -{ - float width = 0.04 * rw_scale; - float height = 0.15 * rw_scale; - int column = int(floor(q.x / width)); - int row = int(floor(q.y / height)); - vec4 a = rw_random(ivec2(column, 7), layer, 0u); - if (a.x > share * mix(0.35, 0.9, clamp(rw_rate / 3.0, 0.0, 1.0))) - return; - float speed = clamp(0.035 + 0.06 * (rw_push - 0.4) + 0.3 * max(rw_push - 1.5, 0.0), 0.01, 0.8); - float period = clamp(25.0 / rw_rate, 3.0, 60.0); - float trail = 0.0; - for (int r = 0; r < 3; ++r) - { - ivec2 cell = ivec2(column, row + r); - vec4 b = rw_random(cell, layer, 1u); - float span = period * mix(0.7, 1.3, b.x); - float now = floor(time / span + b.y); - for (int k = 0; k < 2; ++k) - { - float cycle = now - float(k); - float start = (cycle - b.y) * span; - float t = time - start; - // the drop gathered from the drops landed since the last wipe - if ((t < 0.0) || (rw_since - t < rw_grow)) - continue; - vec4 c = rw_random(cell, layer + 1000u, uint(int(cycle) + 1000000)); - float top = (float(cell.y) + 0.8 - 0.6 * c.x) * height; - float travel = mix(0.06, 0.28, c.y) * rw_scale; - float v = speed * mix(0.7, 1.3, c.z); - float gather = 0.6; - float moved = travel * rw_stickslip((t - gather) * v / travel, c.w); - float y = top - moved; - float radius = mix(0.003, 0.0042, c.w) * rw_scale * (1.0 - 0.35 * moved / travel) * mix(0.6, 1.0, smoothstep(0.0, gather, t)); - // at the end of its way what is left of it stays and flows out into the stream - float body = 1.0 - smoothstep(0.0, 1.5, t - gather - travel / v); - if ((body > 0.0) && (abs(q.y - y) < 3.5 * radius)) - { - vec2 o = vec2(q.x - rw_path(column, y, width, layer), q.y - y); - rw_blob(side * o.x - down * o.y, radius, body); - // its rear up the stream: a corner, drawn out into a cusp the faster it goes (the front stays round) - float drawn = clamp(v * 5.0, 0.0, 1.5); - for (int k = 1; k <= 2; ++k) - { - float yt = y + radius * (0.45 + 0.5 * drawn) * float(k); - vec2 ot = vec2(q.x - rw_path(column, yt, width, layer), q.y - yt); - rw_blob(side * ot.x - down * ot.y, radius * ((k == 1) ? 0.7 : 0.42), body); - } - } - if ((moved > 0.0) && (q.y > y) && (q.y < top)) - { - float age = t - gather - (top - q.y) / v; - if ((age >= 0.0) && (age < rw_since)) - { - // fresh, the stream is whole; draining, it breaks into beads, which dry - float beads = rw_noise(q.y / (0.004 * rw_scale), layer + 9u); - float wet = mix(1.15, 0.2 + 1.0 * beads, smoothstep(0.0, 15.0, age)) * (1.0 - smoothstep(30.0, 60.0, age)); - trail = max(trail, wet); - } - } - } - } - if (trail > 0.0) - { - float across = q.x - rw_path(column, q.y, width, layer); - float half_width = mix(0.0005, 0.0011, a.y) * rw_scale * (0.6 + 0.8 * rw_noise(q.y / (0.006 * rw_scale), layer + 11u)); - rw_blob(side * across, half_width, trail); - } -} - -// a drop lying on the glass, as rw_drop() with the directions along the glass given in the view space (Down: the way gravity -// pulls along the glass, Side across it) -void rw_drop_view(vec3 offset, float visible, float weight, vec4 shape, vec3 down, vec3 side) -{ - rw_kernel(offset, visible, weight); - if (visible < 1.5 * rw_pixel) - return; - vec3 sag = (down * (0.2 + 0.35 * shape.x) + side * ((shape.y - 0.5) * 0.7)) * visible; - rw_kernel(offset - sag, visible * mix(0.6, 0.85, shape.z), weight); - if (shape.w > 0.4) - { - float angle = shape.w * 40.0; - rw_kernel(offset - (cos(angle) * side + sin(angle) * down) * (0.6 * visible), visible * mix(0.4, 0.6, shape.x), weight); - } -} - -// the water the simulation keeps on the glass (gfx::windscreen_water, water.glsl), where the material is a glass of the cab of the -// train: the drops listed by the cell of the grid the fragment is in. Slot: of the glass, Uv: the coordinates of the fragment, -// Puv: the view space step along the glass for a step of the uv; Down, Side: along the glass. a sliding drop is drawn out behind -// itself into a cusp, the faster the longer; one lying is lopsided and sags down the glass; a flake of snow is lace, grey and -// clear as it melts (Snowcover, Wet: as the flakes of rw_snow()) -void rw_simulated(uint slot, vec2 uv, mat2x3 puv, vec3 down, vec3 side, inout float snowcover, inout float wet) -{ - uint base = water_grid_base(slot); - uint cell = water_cell(uv); - uint count = min(water_cells[base + cell], uint(WATER_CELL_DROPS)); - for (uint k = 0u; k < count; ++k) - { - uint place = water_cells[base + uint(WATER_GRID * WATER_GRID) + cell * uint(WATER_CELL_DROPS) + k]; - water_drop_s drop = water_drops[slot * uint(WATER_DROPS) + place]; - float volume = drop.place.z; - if (volume <= 0.0) - continue; - vec3 offset = puv * (uv - drop.place.xy); - vec4 shape = vec4(rw_pcg4d(uvec4(place, slot, 41u, 0u))) * (1.0 / 4294967296.0); - if (drop.motion.w < 1.0) - { - // a flake: lobed lace, shrinking, grey and clear as it melts - float m = drop.motion.w; - vec2 flat2 = vec2(dot(offset, side), dot(offset, down)); - float radius = 0.5 * water_flake(volume); - float dist = length(flat2); - if (dist < radius + rw_pixel) - { - float angle = atan(flat2.y, flat2.x); - float lobes = 0.55 + 0.45 * (0.6 * rw_noise(angle * 1.9 + shape.z * 40.0, 13u) + 0.4 * abs(cos(3.0 * angle + shape.w * 6.2831853))); - float rim = radius * lobes * (1.0 - 0.45 * m); - float body = smoothstep(rim + rw_pixel, 0.55 * rim - rw_pixel, dist); - float lace = rw_noise2(flat2 / 0.0007 + shape.zw * 100.0, 14u).x; - float flake = body * mix(0.55, 1.0, lace) * (1.0 - 0.7 * m * m); - snowcover = 1.0 - (1.0 - snowcover) * (1.0 - flake); - wet = max(wet, m * body); - } - continue; - } - float radius = water_radius(volume); - vec3 velocity = puv * drop.motion.xy; - float speed = length(velocity); - if (speed > 0.002) - { - // its rear up the way it came: a corner, drawn out into a cusp the faster it goes (the front stays round) - vec3 way = velocity / speed; - rw_kernel(offset, radius, 1.0); - float drawn = clamp(speed * 5.0, 0.0, 1.5); - for (int t = 1; t <= 2; ++t) - rw_kernel(offset + way * (radius * (0.45 + 0.5 * drawn) * float(t)), radius * ((t == 1) ? 0.7 : 0.42), 1.0); - } - else - { - rw_drop_view(offset, radius, 1.0, shape, down, side); - } - } -} - -// how fresh the wetted paths of the simulation are at a place of the glass (x) and how that changes along u and v (yz): the -// texels of their map filtered by a cubic b-spline over 4 x 4 of them, so the edges of a path are smooth curves and its slopes -// change smoothly (a bilinear filter would leave steps at every texel in the bending of the view) -vec3 rw_trail(uint slot, vec2 uv, float now) -{ - // a path stays wet (and seen) longer than the drops keep to it - float lasting = 25.0; - vec2 p = uv * float(WATER_TRAIL) - 0.5; - vec2 i = floor(p); - vec2 f = p - i; - // the weights of the b-spline and their derivatives, for the texels i - 1 .. i + 2 - vec2 g = 1.0 - f; - vec4 wx = vec4(g.x * g.x * g.x, 3.0 * f.x * f.x * f.x - 6.0 * f.x * f.x + 4.0, -3.0 * f.x * f.x * f.x + 3.0 * f.x * f.x + 3.0 * f.x + 1.0, f.x * f.x * f.x) / 6.0; - vec4 wy = vec4(g.y * g.y * g.y, 3.0 * f.y * f.y * f.y - 6.0 * f.y * f.y + 4.0, -3.0 * f.y * f.y * f.y + 3.0 * f.y * f.y + 3.0 * f.y + 1.0, f.y * f.y * f.y) / 6.0; - vec4 dx = vec4(-g.x * g.x, 3.0 * f.x * f.x - 4.0 * f.x, -3.0 * f.x * f.x + 2.0 * f.x + 1.0, f.x * f.x) * 0.5; - vec4 dy = vec4(-g.y * g.y, 3.0 * f.y * f.y - 4.0 * f.y, -3.0 * f.y * f.y + 2.0 * f.y + 1.0, f.y * f.y) * 0.5; - vec3 result = vec3(0.0); - ivec2 base = ivec2(i) - 1; - for (int y = 0; y < 4; ++y) - { - for (int x = 0; x < 4; ++x) - { - float value = water_wetted(slot, base + ivec2(x, y), now, lasting); - result += value * vec3(wx[x] * wy[y], dx[x] * wy[y], wx[x] * dy[y]); - } - } - result.yz *= float(WATER_TRAIL); - return result; -} - -// the surroundings in a view space direction where the screen doesn't hold them: the environment map above the horizon (the sky -// and the clouds), the ground below it, blurred by Lod -vec3 rw_surroundings(vec3 direction, float lod) -{ - vec3 world = mat3(inv_view) * direction; - vec3 sky = envmap_sample_rough(normalize(vec3(world.x, max(world.y, 0.0), world.z)), clamp(lod / 8.0, 0.0, 1.0)); - // the horizon as blurred as the view is - float below = smoothstep(-0.03 - 0.05 * lod, 0.25 + 0.05 * lod, -world.y); - if ((below <= 0.0) || (false == ENVMAP_ENABLED)) - return sky; - return mix(sky, reflection_ground(), below); -} - -// what is seen through the glass in a view space direction: the image of the last frame (the screen space reflections keep it) -// where it holds the place, Distance away along the direction (0: far), blurred by Lod; Share: how much of it the image gave. -// Fade: towards the edges of the image the surroundings take over (else the edges are stretched) -vec3 rw_behind_edges(vec3 direction, float lod, float distance, out float share, bool fade) -{ - share = 0.0; - vec3 around = rw_surroundings(direction, lod); - if (ssr_params.x < 1.0) - return around; - vec4 previous = ssr_reprojection * ((distance > 0.0) ? vec4(direction * distance, 1.0) : vec4(direction, 0.0)); - if (previous.w <= 1e-5) - return around; - vec2 coords = (previous.xy / previous.w) * 0.5 + 0.5; - vec2 edges = min(coords, 1.0 - coords); - share = fade ? smoothstep(0.0, 0.04, min(edges.x, edges.y)) : step(-0.02, min(edges.x, edges.y)); - coords = clamp(coords, vec2(0.0), vec2(1.0)); - if (share <= 0.0) - return around; - // the view out through the water goes on outside, where the image shows the inside of the cab around the windows the - // surroundings stand for it (else the drops show the dark walls and roof of the cab) - ivec2 size = textureSize(scene_depth, 0); - float depth = texelFetch(scene_depth, clamp(ivec2(coords * vec2(size)), ivec2(0), size - 1), 0).r; - float near = projection[3][2]; - if ((depth > 0.0) && (near / depth < -f_pos.z + 2.5)) - { - share = 0.0; - return around; - } - vec3 color = textureLod(ssr_history, coords, clamp(lod, 0.0, ssr_params2.x)).rgb; - if (any(isnan(color)) || any(isinf(color))) - { - share = 0.0; - return around; - } - return mix(around, max(color, vec3(0.0)), share); -} - -vec3 rw_behind(vec3 direction, float lod, float distance, out float share) -{ - return rw_behind_edges(direction, lod, distance, share, true); + vec4 previous = ssr_reprojection * ((distance > 0.0) ? vec4(direction * distance, 1.0) : vec4(direction, 0.0)); + if (previous.w <= 1e-5) + return vec3(0.0); + vec2 coords = clamp((previous.xy / previous.w) * 0.5 + 0.5, vec2(0.0), vec2(1.0)); + vec3 near = textureLod(ssr_history, coords, min(3.5, ssr_params2.x)).rgb; + vec3 wide = textureLod(ssr_history, coords, min(6.5, ssr_params2.x)).rgb; + if (any(isnan(near)) || any(isinf(near)) || any(isnan(wide)) || any(isinf(wide))) + return vec3(0.0); + vec3 excess = max(near - wide * WS_LIGHT_CONTRAST, vec3(0.0)); + return min(excess, vec3(30.0)) * (2.0 * WS_LIGHT_GAIN); } // a layer Over put over Under, the colours not premultiplied -vec4 rw_over(vec4 over, vec4 under) +vec4 wsOver(vec4 over, vec4 under) { - float alpha = over.a + under.a * (1.0 - over.a); - if (alpha <= 1e-5) - return vec4(0.0); - return vec4((over.rgb * over.a + under.rgb * under.a * (1.0 - over.a)) / alpha, alpha); + float alpha = over.a + under.a * (1.0 - over.a); + if (alpha <= 1e-5) + return vec4(0.0); + return vec4((over.rgb * over.a + under.rgb * under.a * (1.0 - over.a)) / alpha, alpha); +} + +// =========================================================================== +float GetMixFactor(in vec2 co, out float side); + +uvec2 cellKey(vec2 c); + +vec2 tileOffset(float choice) +{ + if (choice < 0.25) return vec2(0.0, 0.0); + else if (choice < 0.5) return vec2(0.5, 0.0); + else if (choice < 0.75) return vec2(0.0, 0.5); + return vec2(0.5, 0.5); +} + +// the 2x2 drop tiles live in the left half of the atlas: a tile is 0.25 wide and 0.5 high in atlas UV +vec2 dropAtlasUV(float choice, vec2 uv) +{ + vec2 off = tileOffset(choice); + return vec2((off.x + uv.x * 0.5) * 0.5, off.y + uv.y * 0.5); +} + +uvec2 cellKey(vec2 c) +{ + return uvec2(ivec2(c) + ivec2(65536)); +} + +// --- one rivulet cell ------------------------------------------------------------ +struct Riv +{ + bool on; + float life; // 0..1 (fade in / out) + float width; // sprite width = head width (glass UV) + float headH; // head height (glass UV) + float topY; // where the trail starts (fixed on the glass) + float bottom; // bottom of the head now + float left; // left edge of the sprite + float flip; + float col; // which of the 4 sprites + float wipe; + float wavK, wavPh, wavSp; +}; + +// the layer of rivulets being worked on: the one of gravity (the rivulets as they always were, coordinates = glass UV with v +// up) or the one of the air (its own cells and seeds, turned so that its rivulets run along the push of the air) +float wsLayerDensity = 1.0; // x rain x streak_density: share of the cells holding a rivulet +float wsLayerPeriod = streak_period; +uint wsLayerSalt = 91u; +float wsLayerHead = 1.0; // x streak_head +float wsLayerCos = 1.0; // the layer is turned by this angle (its "down" is the way its water runs on the glass) +float wsLayerSin = 0.0; + +// glass UV (v up) -> coordinates of the layer, where the rivulets run down (-v) +vec2 wsToLayerDir(vec2 v) +{ + return vec2(wsLayerCos * v.x + wsLayerSin * v.y, -wsLayerSin * v.x + wsLayerCos * v.y); +} +vec2 wsToLayer(vec2 g) +{ + return wsToLayerDir(g - 0.5) + 0.5; +} +vec2 wsFromLayerDir(vec2 v) +{ + return vec2(wsLayerCos * v.x - wsLayerSin * v.y, wsLayerSin * v.x + wsLayerCos * v.y); +} +vec2 wsFromLayer(vec2 p) +{ + return wsFromLayerDir(p - 0.5) + 0.5; +} + +// the layers: 0 gravity, 1 air. WindShare: how much the air drives the water (0 standing still), WindCos / WindSin: the turn +// of the layer of the air +float wsWindShare = 0.0; +float wsWindCos = 1.0; +float wsWindSin = 0.0; +void wsSetLayer(int layer) +{ + if (layer == 0) + { + wsLayerDensity = 1.0 - wsWindShare; + wsLayerPeriod = streak_period; + wsLayerSalt = 91u; + wsLayerHead = 1.0; + wsLayerCos = 1.0; + wsLayerSin = 0.0; + } + else + { + wsLayerDensity = wsWindShare * wind_streaks; + wsLayerPeriod = wind_streak_period; + wsLayerSalt = 91u + 2u * uint(layer); + wsLayerHead = wind_head_scale; + wsLayerCos = wsWindCos; + wsLayerSin = wsWindSin; + } +} + +Riv getRiv(vec2 sCell, float sCW, float sCH, float gridSize) +{ + Riv r; + uint sSeed = Hash(uvec3(cellKey(sCell), wsLayerSalt)); + r.on = (RandF(sSeed) < rain_params.x * streak_density * wsLayerDensity); + float sPeriod = wsLayerPeriod * mix(0.6, 1.6, RandF(sSeed)); + float sPhase = fract(time / sPeriod + RandF(sSeed)); + r.life = smoothstep(0.0, 0.05, sPhase) * (1.0 - smoothstep(0.86, 1.0, sPhase)); + r.width = streak_head * wsLayerHead / gridSize * mix(0.75, 1.25, RandF(sSeed)); + r.headH = r.width * 0.88 * streak_uv_aspect; + float sSpan = max(sCH * mix(0.35, 0.70, RandF(sSeed)), r.headH * 3.0); + // stick-slip: the drop waits, then lurches forward; N waits on the way down + float sSteps = floor(mix(3.0, 8.0, RandF(sSeed))); + float sXs = clamp(sPhase / 0.88, 0.0, 1.0) * sSteps; + float sRun = clamp((floor(sXs) + smoothstep(0.55, 1.0, fract(sXs))) / sSteps, 0.0, 1.0); + r.topY = sCell.y * sCH + sSpan + RandF(sSeed) * max(sCH - sSpan, 0.0); + r.bottom = r.topY - r.headH * 1.2 - sRun * (sSpan - r.headH * 1.2); + const float sMargin = 0.8; + r.left = sCell.x * sCW + sMargin * r.width + RandF(sSeed) * max(sCW - r.width * (1.0 + 2.0 * sMargin), 0.0); + r.flip = (RandF(sSeed) < 0.5) ? 1.0 : 0.0; + r.col = floor(RandF(sSeed) * 4.0); + r.wipe = RandF(sSeed); + r.wavK = 6.2831853 / mix(2.5, 5.0, RandF(sSeed)); + r.wavPh = RandF(sSeed) * 6.2831853; + r.wavSp = streak_wiggle_speed * mix(0.6, 1.4, RandF(sSeed)); + return r; +} + +// sideways offset of the path (in head widths) at distance dW (head widths) down from the start of the trail +float rivWob(Riv r, float dW, out float ramp, out float wobD) +{ + float rampT = clamp(dW / 2.5, 0.0, 1.0); + ramp = rampT * rampT * (3.0 - 2.0 * rampT); + float rampD = 3.0 * rampT * (1.0 - rampT) / 2.5; + float a1 = dW * r.wavK + r.wavPh; + float a2 = dW * r.wavK * 1.7 - time * r.wavSp * 1.0472 + r.wavPh * 2.0; // the wave runs DOWN + float w1 = 0.7 * sin(a1) + 0.3 * sin(a2); + float w1D = 0.7 * cos(a1) * r.wavK + 0.3 * cos(a2) * r.wavK * 1.7; + wobD = -streak_wiggle * (rampD * w1 + ramp * w1D); + return streak_wiggle * ramp * w1; +} + +// how much a drop centred at p (glass UV, v up) with radius rad has been swept up by rivulet r (0..1) +float rivSwept(Riv r, vec2 p, float rad) +{ + if (!r.on || r.life <= 0.001) return 0.0; + if (p.y > r.topY || p.y < r.bottom - rad) return 0.0; + bool inHead = p.y < r.bottom + r.headH; + float dW = (r.topY - (inHead ? r.bottom + 0.5 * r.headH : p.y)) / r.width; + float ramp, wobD; + float wob = rivWob(r, dW, ramp, wobD); + float cx = r.left + (0.5 + wob) * r.width; + float halfW = 0.5 * streak_sweep_width * r.width; + return (1.0 - smoothstep(halfW, halfW + rad, abs(p.x - cx))) * r.life; +} + +// candidate on the glass that wins the pixel (the highest dome) +struct Hit +{ + float score; + float cov; // coverage of the dome (normal map alpha) + float colA; // coverage of the drawn drop (sharper) + vec3 n; // dome normal, tangent space of the glass + vec2 offUV; // pixel - centre (glass UV), for the lens + float radUV; // radius (glass UV) + float isDrop; // 1 = drop / droplet (lens), 0 = rivulet (Snell) + float vis; // life / sweep visibility + vec2 auv; // grey atlas lookup of the winner (drops, rivulets) + vec2 agx, agy; + float atlas; // 1 = shade from the grey atlas, 0 = analytic (micro droplets: shade in colA's place) + float shade; // analytic shade (micro droplets) +}; + +void consider(inout Hit h, float score, float cov, float colA, vec3 n, vec2 offUV, float radUV, float isDrop, + float vis, vec2 auv, vec2 agx, vec2 agy, float atlas, float shade) +{ + if (score > h.score) + { + h.score = score; h.cov = cov; h.colA = colA; h.n = n; + h.offUV = offUV; h.radUV = radUV; h.isDrop = isDrop; + h.vis = vis; h.auv = auv; h.agx = agx; h.agy = agy; h.atlas = atlas; h.shade = shade; + } +} + +// the rivulet R of the layer set (wsSetLayer) at the pixel, at SUVr in the coordinates of the layer; Rd1 / Rd2: their change +// per screen pixel +void drawRivulet(inout Hit hit, Riv r, vec2 sUVr, vec2 rd1, vec2 rd2) +{ + if (!(r.on && r.life > 0.001)) + return; + const float sMargin = 0.8; + float sLen = r.topY - r.bottom; + float sx = (sUVr.x - r.left) / r.width; + float sy = sUVr.y - r.bottom; + if (sx >= -sMargin && sx <= 1.0 + sMargin && sy >= 0.0 && sy <= sLen) + { + bool inHead = sy < r.headH; + float dW = (r.topY - (inHead ? r.bottom + 0.5 * r.headH : sUVr.y)) / r.width; + float ramp, wobD; + float wob = rivWob(r, dW, ramp, wobD); + if (inHead) wobD = 0.0; + float sxw = sx - wob; + if (sxw >= 0.0 && sxw <= 1.0) + { + float sSide; + vec2 sWipeUV = f_coord; + if (inHead) + { + sWipeUV = wsFromLayer(vec2(r.left + 0.5 * r.width, r.bottom + 0.5 * r.headH)); + if (STREAK_FLIP_Y != 0) sWipeUV.y = 1.0 - sWipeUV.y; + } + if (GetMixFactor(sWipeUV, sSide) >= mix(0.5, 1.0, r.wipe)) + { + float sNative = 3.125 * r.width * streak_uv_aspect * STREAK_TAIL_SCALE; + float sxs = mix(sxw, 1.0 - sxw, r.flip); + float su = 0.5 + (r.col + sxs) * 0.125; + vec2 sgx = vec2(0.125 / r.width * rd1.x, 0.0); + vec2 sgy = vec2(0.125 / r.width * rd2.x, 0.0); + vec4 sNm; + vec2 sAuv; + float vtSign = 1.0; + if (inHead) + { + float kv = STREAK_HEAD_FRAC / r.headH; + sgx.y = kv * rd1.y; sgy.y = kv * rd2.y; + sAuv = vec2(su, sy / r.headH * STREAK_HEAD_FRAC); + sNm = textureGrad(normalmap, sAuv, sgx, sgy); + } + else + { + float kv = (1.0 - STREAK_HEAD_FRAC) / sNative; + sgx.y = kv * rd1.y; sgy.y = kv * rd2.y; + // a) trail pattern fixed to the glass, tiled by mirroring (beads stay where they were left) + float dd = max(r.topY - sUVr.y, 0.0) / sNative; + float vt = abs(mod(dd, 2.0) - 1.0); + vtSign = (mod(dd, 2.0) < 1.0) ? 1.0 : -1.0; + // b) right above the head: the sprite part that touches the head + float above = (sy - r.headH) / r.width; // head widths above the head + float link = 1.0 - smoothstep(0.5 * streak_link, streak_link, above); + vec4 nGlass = vec4(0.0); + vec4 nLink = vec4(0.0); + vec2 uvGlass = vec2(su, STREAK_HEAD_FRAC + vt * (1.0 - STREAK_HEAD_FRAC)); + vec2 uvLink = vec2(su, STREAK_HEAD_FRAC + min((sy - r.headH) / sNative, 1.0) * (1.0 - STREAK_HEAD_FRAC)); + if (link < 0.999) + nGlass = textureGrad(normalmap, uvGlass, sgx, sgy); + if (link > 0.001) + nLink = textureGrad(normalmap, uvLink, sgx, sgy); + sAuv = (link > 0.5) ? uvLink : uvGlass; + sNm = mix(nGlass, nLink, link); + vtSign = mix(vtSign, 1.0, link); + } + + float sFade = inHead ? 1.0 : smoothstep(0.0, 1.5, dW); // the start of the trail melts into the glass + float sVis = r.life * sFade; + float sCov = smoothstep(0.1, 0.6, sNm.a) * sVis; + if (sCov > 0.001) + { + vec2 nxy = sNm.rg * 2.0 - 1.0; + if (r.flip > 0.5) nxy.x = -nxy.x; + if (STREAK_FLIP_Y != 0) nxy.y = -nxy.y; + float nz = sqrt(1.0 - clamp(dot(nxy, nxy), 0.0, 1.0)); + vec2 slope = -nxy / max(nz, 0.08); + if (!inHead) + slope.y = slope.y * vtSign / STREAK_TAIL_SCALE - slope.x * wobD + + streak_flow * ramp * sin(dW * 4.8 - time * 4.0); + // the slope of the layer to the one of the glass + if (STREAK_FLIP_Y != 0) slope.y = -slope.y; + slope = wsFromLayerDir(slope); + if (STREAK_FLIP_Y != 0) slope.y = -slope.y; + vec3 n = normalize(vec3(-slope, 1.0)); + float h = sNm.b * r.width * 0.5; + consider(hit, sCov * (h + 1e-5), sCov, 0.0, n, vec2(0.0), r.width * 0.5, 0.0, + sVis, sAuv, sgx, sgy, 1.0, 0.0); + } + } + } + } +} + +// how much of a drop centred at Cg (glass UV, v up) with radius Rad the rivulets of both layers have swept up (0..1 kept) +float wsKept(vec2 cg, float rad, Riv rivP, vec2 sCell, float sCW, float sCH, float gridSize) +{ + wsSetLayer(0); + vec2 rc = floor(cg / vec2(sCW, sCH)); + Riv rv = rivP; + if (rc != sCell) rv = getRiv(rc, sCW, sCH, gridSize); + float kept = 1.0 - streak_sweep * rivSwept(rv, cg, rad); + if (wsWindShare > 0.001) + { + wsSetLayer(1); + vec2 cw = wsToLayer(cg); + vec2 wc = vec2(sCW * wind_cell_scale, sCH * wind_run_scale); + Riv rw = getRiv(floor(cw / wc), wc.x, wc.y, gridSize); + kept *= 1.0 - streak_sweep * rivSwept(rw, cw, rad); + wsSetLayer(0); + } + return kept; +} + +// seconds since a wiper blade last went over Co (texture UV), from the timers of its strokes as GetMixFactor takes them; +// -1 where no wiper reaches +float wsWipeAge(vec2 co) +{ + vec4 movePhase = wiper_pos; + bvec4 is_out = lessThanEqual(movePhase, vec4(1.)); + movePhase = mix(vec4(2.) - movePhase, movePhase, is_out); + vec4 mask = textureLod(wipermask, co, 0.0); + vec4 maskVal = mix(1. - mask, mask, is_out); + vec4 passed = step(maskVal, movePhase); + vec4 sideV = mix(passed, vec4(1.) - passed, is_out); + vec4 ages = vec4(time) - mix(wiper_timer_out, wiper_timer_return, sideV); + float age = -1.0; + for (int i = 0; i < 4; ++i) + if ((mask[i] > 0.001) && ((age < 0.0) || (ages[i] < age))) + age = max(ages[i], 0.0); + return age; } void main() { - vec4 tex_color = texture(diffuse, f_coord); - vec4 mask = texture(wipermask, f_coord); + // ---- screen-space derivatives (before any non-uniform flow) ---- + float uvPerPx = max(length(dFdx(f_coord)), length(dFdy(f_coord))); + vec2 sxy = f_pos.xy / max(-f_pos.z, 1e-3); + float pxPerSlope = 1.0 / max(max(length(dFdx(sxy)), length(dFdy(sxy))), 1e-6); + vec3 Ngl = normalize(f_normal); + vec3 wsView = normalize(f_pos.xyz); // the view through the glass and its change per pixel (for the bent view) + vec3 wsDvx = dFdx(wsView); + vec3 wsDvy = dFdy(wsView); + vec3 dp1 = dFdx(f_pos.xyz); + vec3 dp2 = dFdy(f_pos.xyz); + vec2 duv1 = dFdx(f_coord); + vec2 duv2 = dFdy(f_coord); + vec3 dp2perp = cross(dp2, Ngl); + vec3 dp1perp = cross(Ngl, dp1); + vec3 Tgl = dp2perp * duv1.x + dp1perp * duv2.x; + vec3 Bgl = dp2perp * duv1.y + dp1perp * duv2.y; + float invmax = inversesqrt(max(max(dot(Tgl, Tgl), dot(Bgl, Bgl)), 1e-20)); + Tgl *= invmax; + Bgl *= invmax; + // glass UV offset -> screen pixels (inverse of the UV Jacobian), for the drop lens + mat2 Juv = mat2(duv1, duv2); + float detJ = determinant(Juv); + mat2 Jinv = (abs(detJ) > 1e-20) ? inverse(Juv) : mat2(0.0); - // the coordinates of the glass: metres along the axes of the model, so the water stays where it lies on the glass whatever the - // vehicle and the camera do. the axis of the model nearest to the vertical is up, the glass is projected along the - // horizontal one it faces most (along the vertical one if it lies flat) - mat3 linear = mat3(modelview); - mat3 rot = mat3(normalize(linear[0]), normalize(linear[1]), normalize(linear[2])); - mat3 unrot = transpose(rot); - vec3 local = unrot * (f_pos.xyz - modelview[3].xyz); - vec3 viewnormal = normalize(f_normal); - // the water is on the side away from the camera, the outside of the cab - vec3 outward = (dot(viewnormal, f_pos.xyz) < 0.0) ? -viewnormal : viewnormal; - vec3 normal = unrot * outward; - vec3 up = unrot * (vec3(0.0, 1.0, 0.0) * mat3(inv_view)); - vec3 aup = abs(up); - int iu = (aup.x > aup.y) ? ((aup.x > aup.z) ? 0 : 2) : ((aup.y > aup.z) ? 1 : 2); - int ia = (iu + 1) % 3; - int ib = (iu + 2) % 3; - vec3 axis_up = vec3(0.0); - axis_up[iu] = (up[iu] < 0.0) ? -1.0 : 1.0; - vec3 axis_a = vec3(0.0); - axis_a[ia] = 1.0; - vec3 axis_b = vec3(0.0); - axis_b[ib] = 1.0; - vec3 an = abs(normal); - vec3 axis_u, axis_v, axis_n; - if (an[iu] > max(an[ia], an[ib])) - { - axis_n = axis_up; - axis_u = axis_a; - axis_v = axis_b; - } - else if (an[ia] >= an[ib]) - { - axis_n = axis_a; - axis_u = axis_b; - axis_v = axis_up; - } - else - { - axis_n = axis_b; - axis_u = axis_a; - axis_v = axis_up; - } - vec2 glass = vec2(dot(local, axis_u), dot(local, axis_v)); - float facing = dot(normal, axis_n); - facing = ((facing < 0.0) ? -1.0 : 1.0) * max(abs(facing), 0.35); - // a step of the coordinates is a step along the glass - rw_tu = rot * (axis_u - axis_n * (dot(normal, axis_u) / facing)); - rw_tv = rot * (axis_v - axis_n * (dot(normal, axis_v) / facing)); + vec4 tex_color = texture(diffuse, f_coord); + float glassA = tex_color.a * alpha_mult; - // the derivatives, before anything is discarded: the size of a pixel on the glass and in the view, and how the coordinates of - // the mask follow the ones of the glass - vec3 view = normalize(f_pos.xyz); - vec3 dpdx = dFdx(f_pos.xyz); - vec3 dpdy = dFdy(f_pos.xyz); - rw_pixel = max(max(length(dpdx), length(dpdy)), 1e-6); - float pixelangle = max(max(length(dFdx(view)), length(dFdy(view))), 1e-6); - vec2 gdx = dFdx(glass); - vec2 gdy = dFdy(glass); - mat2 steps = mat2(gdx, gdy); - float det = determinant(steps); - mat2 maskstep = (abs(det) > 1e-14) ? mat2(dFdx(f_coord), dFdy(f_coord)) * inverse(steps) : mat2(0.0); + float gridSize = ceil(param[2].x); + vec2 rainCoord = f_coord; - // the water the simulation keeps, where the material is a glass of the cab of the train (the param water_slot, given by the - // renderer: 1 + the glass): the view space step along the glass for a step of the uv, and how fresh the wetted path the water - // went along is, with how that changes along the glass (before anything is discarded) - int slot = int(param[2].z + 0.5) - 1; - mat2 uvsteps = mat2(dFdx(f_coord), dFdy(f_coord)); - float uvdet = determinant(uvsteps); - bool simulated = (slot >= 0) && (slot < WATER_SLOTS) && (abs(uvdet) > 1e-24); - simulated = simulated && (water_header[clamp(slot, 0, WATER_SLOTS - 1)].x > 0.5); - mat2x3 puv = (abs(uvdet) > 1e-24) ? mat2x3(dpdx, dpdy) * inverse(uvsteps) : mat2x3(0.0); - vec3 trailfield = simulated ? rw_trail(uint(slot), f_coord, water_header[clamp(slot, 0, WATER_SLOTS - 1)].y) : vec3(0.0); - float trail = trailfield.x; - // its gradient along the glass, view space: the uv gradient taken through the steps of the uv along the glass - vec3 trailslope = vec3(0.0); - { - mat2 metric = transpose(puv) * puv; - if (abs(determinant(metric)) > 1e-30) - trailslope = puv * (inverse(metric) * trailfield.yz); - } + float ambLum = clamp(dot(ambient, vec3(0.2126, 0.7152, 0.0722)), 0.0, 1.0); + float dynBright = pow(clamp(ambLum * 6.0, 0.0, 1.0), 0.5); + // GL 4.6: the ambient light isn't a level of 0..1 any more (it is in the units of the scene, the light of the sky added), so + // at night the drops came out as bright as by day. how bright the picture around really is says it: the coarsest level of + // the image of the last frame, the average of the screen + float sceneLum = (ssr_params.x >= 1.0) ? wsLum(textureLod(ssr_history, vec2(0.5), ssr_params2.x).rgb) : 1.0; + float wsNight = smoothstep(0.0, drop_dark_lum, sceneLum); // 0 dark night .. 1 daylight + dynBright *= wsNight; - if (tex_color.a < 0.01) - discard; + // wiper state of this pixel (blur, micro droplets) + float hazeSide; + float wipeVis = GetMixFactor(f_coord, hazeSide); - vec4 layer = vec4(0.0); - float heavy = clamp(rain_params.x, 0.0, 1.0); - bool snow = rain_params.z > 0.5; - if ((heavy > 0.0) || simulated) - { - rw_scale = max(param[2].y, 0.05); + Hit hit; + hit.score = 0.0; hit.cov = 0.0; hit.colA = 0.0; hit.n = vec3(0.0, 0.0, 1.0); + hit.offUV = vec2(0.0); hit.radUV = 1.0; hit.isDrop = 1.0; + hit.vis = 0.0; hit.auv = vec2(0.0); hit.agx = vec2(0.0); hit.agy = vec2(0.0); hit.atlas = 0.0; hit.shade = 0.0; - // what meets the glass. the air against the vehicle (rain_wind) drags the drops along the glass with what of it goes - // along the glass and with the share of what meets it head on which turns up it: the more the glass leans back the more - // of the air goes along it, and the less of their weight pulls the drops down it - vec3 air = unrot * (rain_wind.xyz * mat3(inv_view)); - float fall = snow ? RW_SNOW_FALL : RW_RAIN_FALL; - float hits = max(-dot(air - up * fall, normal), 0.0); - rw_rate = heavy * clamp(0.7 + hits / fall, 0.7, 6.0); - rw_period = clamp((snow ? 10.0 : 5.0) / rw_rate, 0.4, 300.0); - rw_grow = 2.0 * rw_period; - vec3 gravity = -up - normal * dot(-up, normal); - vec3 rise = up - normal * dot(up, normal); - rise = (length(rise) > 0.1) ? normalize(rise) : vec3(0.0); - vec3 flow = air - normal * dot(air, normal) + rise * (max(-dot(air, normal), 0.0) * RW_HEAD_ON); - vec3 push = gravity + flow * (length(flow) / (RW_DRAG_SPEED * RW_DRAG_SPEED)); - vec2 force = vec2(dot(push, axis_u), dot(push, axis_v)); - rw_push = length(force); - vec2 fallway = vec2(dot(gravity, axis_u), dot(gravity, axis_v)); - rw_down = (length(fallway) > 0.1) ? normalize(fallway) : vec2(0.0, -1.0); - vec2 flowway = vec2(dot(flow, axis_u), dot(flow, axis_v)); - rw_flow = (length(flowway) > 1.0) ? normalize(flowway) : vec2(0.0); + // ---- the air against the vehicle on the glass (uniform flow: the derivatives of the glass above) ---- + float flipS = (STREAK_FLIP_Y != 0) ? -1.0 : 1.0; // texture v -> glass v (up) + vec3 wsUp = vec3(0.0, 1.0, 0.0) * mat3(inv_view); // world up, view space + vec3 wsAir = rain_wind.xyz * mat3(inv_view); // the air against the vehicle, view space, m/s + vec3 wsN = (dot(Ngl, f_pos.xyz) < 0.0) ? -Ngl : Ngl; // the outside of the glass + vec3 wsGrav = -wsUp - wsN * dot(-wsUp, wsN); // the weight along the glass + vec3 wsRise = wsUp - wsN * dot(wsUp, wsN); + wsRise = (length(wsRise) > 0.1) ? normalize(wsRise) : vec3(0.0); + vec3 wsFlow = wsAir - wsN * dot(wsAir, wsN) + wsRise * (max(-dot(wsAir, wsN), 0.0) * WS_HEAD_ON); + float wsDrag = dot(wsFlow, wsFlow) / (WS_DRAG_SPEED * WS_DRAG_SPEED) * wind_drag_gain; // in units of the weight + vec3 wsFlowDir = (length(wsFlow) > 1e-3) ? normalize(wsFlow) : vec3(0.0); + vec3 wsPush = wsGrav + wsFlowDir * wsDrag; + // to the glass UV (v up) through the tangent frame of the texture + vec2 gravG = vec2(dot(wsGrav, Tgl), dot(wsGrav, Bgl) * flipS); + vec2 flowG = vec2(dot(wsFlowDir, Tgl), dot(wsFlowDir, Bgl) * flipS); + float wsSpeed = smoothstep(0.3, 1.2, wsDrag); // 0 standing still .. 1 at speed (haze, drops) + wsWindShare = smoothstep(0.5, 1.3, wsDrag); // how much the air drives the rivulets + if (wsWindShare > 0.0) + { + // the rivulets of the air run along the push of the air at twice the weight: the same way at any speed (they don't swing + // round as the train speeds up), up a front glass, back and down a side window + vec2 way = gravG + flowG * 2.0; + if (dot(way, way) > 1e-8) + { + way = normalize(way); + float turn = round(atan(way.x, -way.y) / WS_WIND_STEP) * WS_WIND_STEP; + wsWindCos = cos(turn); + wsWindSin = sin(turn); + } + else + wsWindShare = 0.0; + } + // the push of the air on the drops, texture UV (for stretching them) + vec2 wsPushT = vec2(dot(wsPush, Tgl), dot(wsPush, Bgl)); + wsPushT = (dot(wsPushT, wsPushT) > 1e-10) ? normalize(wsPushT) : vec2(0.0, -1.0); + // the change of the glass UV (v up) per screen pixel, for the rivulets + vec2 wsRd1 = vec2(duv1.x, flipS * duv1.y); + vec2 wsRd2 = vec2(duv2.x, flipS * duv2.y); - rw_wipe_s wipe = rw_wipe(mask); - rw_since = wipe.since; - // the blades went lately (any of them, also where none of them reaches) - float working = 0.0; - for (int i = 0; i < 4; ++i) - working = max(working, 1.0 - smoothstep(4.0, 30.0, time - wiper_timer_return[i])); - // how much of the water the place gathers it has - float gathered = 1.0 - exp(-rw_since / (6.0 * rw_period)); - // the film a blade leaves is drawn into fine streaks along its arcs, each a thin cylindrical lens which draws a light seen - // through it into a line across the streaks, towards the pivot of the blade: the way across the streaks on the screen - vec2 streakway = vec2(0.0); - if ((working > 0.0) && (false == snow) && (abs(det) > 1e-14)) - { - int blade = 0; - for (int i = 1; i < 4; ++i) - blade = (mask[i] > mask[blade]) ? i : blade; - if (mask[blade] >= 0.001) - { - // the mask grows along the arcs; a step of a centimetre, so the steps of its values don't matter - float mu = textureLod(wipermask, f_coord + maskstep * vec2(0.01, 0.0), 0.0)[blade]; - float mv = textureLod(wipermask, f_coord + maskstep * vec2(0.0, 0.01), 0.0)[blade]; - vec2 arc = vec2(mu, mv) - mask[blade]; - vec2 onscreen = inverse(steps) * vec2(-arc.y, arc.x); - if ((length(arc) > 1e-4) && (length(onscreen) > 1e-9)) - streakway = normalize(onscreen); - } - } - vec3 ripple = rw_noise2(glass / (0.006 * rw_scale), 5u); + // ---- rivulet cell of this pixel (also used to sweep the drops) ---- + wsSetLayer(0); + float sCW = streak_cell / gridSize; + float sCH = streak_run / gridSize; + vec2 sUVg = vec2(f_coord.x, (STREAK_FLIP_Y != 0) ? 1.0 - f_coord.y : f_coord.y); // glass UV, v up + vec2 sCell = floor(sUVg / vec2(sCW, sCH)); + Riv rivP = getRiv(sCell, sCW, sCH, gridSize); + bool sweepOn = streak_sweep > 0.0 && streak_density > 0.0 && (wind_streaks > 0.0 || wsWindShare < 1.0); - // the water a blade pushes: a bead in front of it while it moves, as wide as the water it gathered on its way, with a steep - // lumpy front (its edge shows dark, the view can't get out there). the drops the bead reaches flow into it - vec3 lumps = rw_noise2(glass / (0.009 * rw_scale), 7u); - float gatheredwater = snow ? 0.0 : min(gathered * 1.5, 1.0) * (0.35 + 0.65 * min(wipe.swept * 2.5, 1.0)); - float reach = 0.004 + 0.018 * gatheredwater + 0.008 * (ripple.x - 0.5); - float ridge = gatheredwater * smoothstep(0.0, 0.003, wipe.front) * (1.0 - smoothstep(reach - 0.004, reach, wipe.front)); - // the smooth shape from how it changes from pixel to pixel, the lumps on it as they are - float pooledbase = 0.004 * ridge; - float pooled = pooledbase * (0.75 + 0.5 * lumps.x); - vec3 pooledslope = rw_gradient(pooledbase, dpdx, dpdy, outward) * (0.75 + 0.5 * lumps.x) + rw_along(lumps.yz * (0.5 * pooledbase / (0.009 * rw_scale))); - if ((pooled > 0.0) && (false == simulated)) - { - rw_sheet(pooled, pooledslope, 0.03, smoothstep(0.0, 0.1, ridge)); - if (ridge > 0.05) - rw_cleared = time; - } + if (rain_params.x > 0.001) + { + // =================================================================== + // 1. drops from the atlas: this cell and its 8 neighbours + // =================================================================== + vec2 cell = floor(rainCoord * gridSize); + for (int oy = -1; oy <= 1; oy++) + for (int ox = -1; ox <= 1; ox++) + { + vec2 nc = cell + vec2(ox, oy); + uvec2 key = cellKey(nc); + // life cycle of this cell: a new drop every lifeLen seconds + uint s0 = Hash(uvec3(key, 23u)); + float lifeLen = mix(drop_life_min, drop_life_max, RandF(s0)); + float tt = time / lifeLen + RandF(s0); + float epoch = floor(tt); + float ph = tt - epoch; + uint ep = uint(mod(epoch, 65521.0)); + // activation first (cheap), the wiper texture only for live drops + uint s1 = Hash(uvec3(key, ep * 4u + 1u)); + if (RandF(s1) > rain_params.x * drop_density) + continue; + float side; + float mixF = GetMixFactor((nc + 0.5) / gridSize, side); + uint s2 = Hash(uvec3(key, ep * 4u + 2u + uint(side) * 2u)); + if (mixF < RandF(s2)) + continue; - float snowcover = 0.0; - float wet = 0.0; - if (simulated) - { - // the directions along the glass, view space - vec3 upview = vec3(0.0, 1.0, 0.0) * mat3(inv_view); - vec3 downview = -(upview - outward * dot(upview, outward)); - downview = (length(downview) > 0.05) ? normalize(downview) : normalize(cross(outward, normalize(rw_tu))); - vec3 sideview = cross(outward, downview); - rw_simulated(uint(slot), f_coord, puv, downview, sideview, snowcover, wet); - // the paths the water went along lately: a rivulet, a band of water rounded across (a cylinder lens: it holds a picture of - // the place around it turned over across the band, its edges dark as the edges of drops), thicker the fresher. the - // smoothed freshness falls off from the middle of a path to its edges - if (trail > 0.08) - { - float p = clamp((trail - 0.08) / 0.5, 0.0, 1.0); - float thickness = 0.0005 * (1.0 - (1.0 - p) * (1.0 - p)); - vec3 rise = trailslope * (0.0005 * 2.0 * (1.0 - p) / 0.5); - float steep = length(rise); - if (steep > 0.7) - rise *= 0.7 / steep; - bool top = thickness > rw_height; - rw_sheet(thickness, rise, 0.004, smoothstep(0.0, 0.15, p) * 0.95); - // from the middle of the band to the fragment - float across = length(trailslope) / 0.5; - if (top && (across > 1.0)) - rw_offset = -trailslope * ((1.0 - p) / (across * length(trailslope))); - } - } - else if (false == snow) - { - // the drops which grew big enough slide off, with gravity and the air: a set of tracks for each of the directions of the - // push nearest to the one now, each laid along its own way, so none of them moves when the push turns - float sliding = smoothstep(0.25, 0.6, rw_push); - if (sliding > 0.0) - { - float bin = atan(force.y, force.x) / (RW_PI / 6.0); - float lower = floor(bin); - for (int k = 0; k < 2; ++k) - { - float share = ((k == 0) ? 1.0 - (bin - lower) : bin - lower) * sliding; - if (share < 0.02) - continue; - float angle = (lower + float(k)) * (RW_PI / 6.0); - vec2 down = vec2(cos(angle), sin(angle)); - vec2 side = vec2(-down.y, down.x); - rw_sliders(vec2(dot(glass, side), -dot(glass, down)), side, down, uint(int(lower) + k + 64) * 2u + 16u, share); - } - } + vec2 center = (nc + vec2(RandF(s2), RandF(s2))) / gridSize; + float size = mix(drop_size_min, drop_size_max, pow(RandF(s2), drop_size_bias)) / gridSize; + float sag = 1.0 + drop_sag * RandF(s2); + float flipX = (RandF(s2) < 0.5) ? 1.0 : 0.0; + float choice = RandF(s2); + // at speed the air stretches the drop along its push (1 standing still: the drop as it always was) + float stretch = 1.0 + drop_wind_stretch * wsSpeed * RandF(s2); + mat2 shapeM = mat2(1.0, 0.0, 0.0, 1.0 / sag) + * (mat2(1.0) + (1.0 / stretch - 1.0) * outerProduct(wsPushT, wsPushT)); - // the drops as they land, each time somewhere else in its cell, as often as the rain hits the glass: the drops of the - // rain spread on the glass, thrown with a fine splash which runs back into them - // each drop anywhere in its cell, the cell as large as a drop with its splash reaches - float cell = 0.007 * rw_scale; - vec2 laid = rw_turn(glass, 0.61) + vec2(0.31, 0.17); - ivec2 home = ivec2(floor(laid / cell)); - float density = mix(0.08, 0.3, heavy); - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x) - { - ivec2 c = home + ivec2(x, y); - vec4 a = rw_random(c, 1u, 0u); - if (a.x > density) - continue; - vec4 b = rw_random(c, 1u, 1u); - float span = rw_period * mix(0.7, 1.3, a.w); - float cycle = floor(time / span + b.x); - float age = time - (cycle - b.x) * span; - float life = span * mix(0.5, 0.9, b.y); - if ((age > life) || (age > rw_since) || (time - age < rw_cleared)) - continue; - vec4 p = rw_random(c, 2u, uint(cycle)); - vec2 offset = rw_turn(laid - (vec2(c) + p.xy) * cell, -0.61); - float visible = mix(0.0011, 0.0019, b.z) * rw_scale; - // a raindrop hits the glass far above the speed at which it splashes (Weber number in the hundreds and thousands): - // it spreads, throws a spray of droplets which stay on the glass around it, and draws back - float splash = exp(-age / 0.06); - float fade = 1.0 - smoothstep(life - min(0.4, 0.3 * life), life, age); - if (visible * 0.3 > 0.5 * rw_pixel) - { - int spray = 3 + int(p.z * 4.0); - for (int s = 0; s < spray; ++s) - { - vec4 e = rw_random(c, 3u, uint(cycle) * 8u + uint(s)); - vec2 way = normalize(vec2(cos(e.x * 6.2831853), sin(e.x * 6.2831853)) + rw_flow * 0.9); - rw_blob(offset - way * (visible * (1.4 + 1.6 * e.y)), visible * mix(0.18, 0.35, e.z), fade * (0.55 + 0.45 * splash)); - } - } - rw_drop(offset, visible * (1.0 + 0.3 * splash), fade, p.wzyx); - } - } - // the drops the landing ones gathered into, growing until they are big enough to slide (the air blows them off sooner) - cell = 0.011 * rw_scale; - laid = rw_turn(glass, 1.07) + vec2(0.53, 0.29); - home = ivec2(floor(laid / cell)); - density = mix(0.55, 1.0, heavy); - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x) - { - ivec2 c = home + ivec2(x, y); - vec4 a = rw_random(c, 4u, 0u); - if (a.x > density) - continue; - vec4 b = rw_random(c, 4u, 1u); - float span = rw_period * mix(2.5, 4.0, a.w); - float cycle = floor(time / span + b.x); - float age = time - (cycle - b.x) * span; - float life = span * mix(0.75, 0.98, b.y) / (1.0 + 2.0 * max(rw_push - 1.0, 0.0)); - if ((age > life) || (age > rw_since) || (time - age < rw_cleared)) - continue; - vec4 p = rw_random(c, 5u, uint(cycle)); - // the big drops are much alike: they grow as they gather the small ones (the radius in step with the time) up to the - // size at which they slide off (on a vertical glass a footprint of about 9 mm, larger on a glass leaning back, smaller - // in a strong air flow), and go - float slides = min(0.0045 / sqrt(max(rw_push, 0.3)), 0.005); - float visible = slides * mix(0.6, 1.0, b.z) * rw_scale * mix(0.35, 1.0, clamp(age / (0.6 * life), 0.0, 1.0)); - rw_drop(rw_turn(laid - (vec2(c) + p.xy) * cell, -1.07), visible, 1.0 - smoothstep(life - min(0.5, 0.3 * life), life, age), p.zwxy); - } - } + float appearF = drop_appear / lifeLen; + float fadeF = drop_fade / lifeLen; + float vis = smoothstep(0.0, appearF, ph) * (1.0 - smoothstep(1.0 - fadeF, 1.0, ph)); + float sq = size * mix(0.8, 1.0, smoothstep(0.0, 2.0 * appearF, ph)); // spreads out as it lands - // the water the blades push out of their sweep: a broken row of drops flowed together along its edge, just outside it - float leave = working * min(heavy * 1.5, 1.0); - if ((leave > 0.0) && rw_border(f_coord, 0.009 * rw_scale, maskstep)) - { - cell = 0.0065 * rw_scale; - laid = rw_turn(glass, 0.29) + vec2(0.11, 0.43); - home = ivec2(floor(laid / cell)); - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x) - { - ivec2 c = home + ivec2(x, y); - vec4 a = rw_random(c, 20u, 0u); - if (a.x > 0.85) - continue; - // from the fragment to the middle of the drop, along the glass - vec2 centre = rw_turn((vec2(c) + a.yz) * cell - laid, -0.29); - float rim = rw_rim(f_coord + maskstep * centre, 0.004 * rw_scale, maskstep) * leave; - if (rim <= 0.05) - continue; - rw_drop(-centre, mix(0.0016, 0.003, a.w) * rw_scale * mix(0.6, 1.0, rim), smoothstep(0.05, 0.35, rim), rw_random(c, 21u, 0u)); - } - } - } + vec2 diff = rainCoord - center; + vec2 dl = shapeM * diff; + if (max(abs(dl.x), abs(dl.y)) >= sq * 0.5) + continue; - // the streams running down from the water the blades leave at the ends of their sweep: a stream in some of the columns - // along the way down, where up the glass there is such water, as far down as the water had time to run since the blade - // went over the place - if ((working > 0.0) && (length(fallway) > 0.3)) - { - vec2 side = vec2(-rw_down.y, rw_down.x); - float width = 0.035 * rw_scale; - float across = dot(glass, side); - float along = -dot(glass, rw_down); - int column = int(floor(across / width)); - vec4 a = rw_random(ivec2(column, 0), 30u, 0u); - if (a.x < 0.6 * heavy * working) - { - float lateral = across - rw_path(column, along, width, 31u); - float half_width = mix(0.0006, 0.0012, a.z) * rw_scale * (0.6 + 0.8 * rw_noise(along / (0.006 * rw_scale), 32u)); - if (abs(lateral) < 2.0 * half_width + rw_pixel) - { - // up the glass, the first place where the reach of the blades begins or ends - const float reach[6] = float[](0.01, 0.025, 0.05, 0.1, 0.18, 0.3); - bool here = rw_reached(f_coord); - float source = -1.0; - for (int s = 0; s < 6; ++s) - { - if (rw_reached(f_coord + maskstep * (-rw_down * reach[s])) != here) - { - source = reach[s]; - break; - } - } - if ((source > 0.0) && (source < max(rw_since - 0.1, 0.0) * 0.2)) - { - float beads = rw_noise(along / (0.004 * rw_scale), 33u); - float flowing = working * (1.0 - 0.5 * smoothstep(0.15, 0.3, source)); - rw_blob(side * lateral, half_width, flowing * mix(0.6, 1.2, beads)); - } - } - } - } - } - else - { - // the flakes stick where they land and melt into drops: the glass is warmed by the cab, faster in the air above zero - float warm = rain_params.w; - float cell = 0.016 * rw_scale; - vec2 laid = rw_turn(glass, 0.83) + vec2(0.07, 0.61); - ivec2 home = ivec2(floor(laid / cell)); - float density = mix(0.5, 0.9, heavy); - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x) - { - ivec2 c = home + ivec2(x, y); - vec4 a = rw_random(c, 11u, 0u); - if (a.x > density) - continue; - vec4 b = rw_random(c, 11u, 1u); - float span = rw_period * mix(0.7, 1.3, a.w); - float cycle = floor(time / span + b.x); - float age = time - (cycle - b.x) * span; - float life = span * mix(0.6, 0.95, b.y); - if ((age > life) || (age > rw_since)) - continue; - vec4 p = rw_random(c, 12u, uint(cycle)); - vec2 offset = rw_turn(laid - (vec2(c) + p.xy) * cell, -0.83); - float diameter = mix(RW_SNOW_DIAMETER.x, RW_SNOW_DIAMETER.y, b.z) * rw_scale; - float melt = ((warm > 0.5) ? mix(3.0, 10.0, b.w) / (1.0 + 0.25 * warm) : mix(15.0, 45.0, b.w)); - if (age < melt) - { - float m = age / melt; - float dist = length(offset.x * rw_tu + offset.y * rw_tv); - float radius = 0.5 * diameter; - if (dist < radius + rw_pixel) - { - float angle = atan(offset.y, offset.x); - float lobes = 0.55 + 0.45 * (0.6 * rw_noise(angle * 1.9 + p.z * 40.0, 13u) + 0.4 * abs(cos(3.0 * angle + p.w * 6.2831853))); - float rim = radius * lobes * (1.0 - 0.45 * m); - float body = smoothstep(rim + rw_pixel, 0.55 * rim - rw_pixel, dist); - float lace = rw_noise2(glass / (0.0007 * rw_scale) + p.zw * 100.0, 14u).x; - float flake = body * mix(0.55, 1.0, lace) * (1.0 - 0.7 * m * m); - snowcover = 1.0 - (1.0 - snowcover) * (1.0 - flake); - wet = max(wet, m * body); - } - } - else - { - // the water of the flake - rw_drop(offset, 0.0018 * pow(diameter / 0.008, 0.667) * rw_scale, 1.0 - smoothstep(life - min(0.5, 0.3 * life), life, age), p.wzyx); - } - } - } - // the snow the blades push in front of them and leave at the ends of their sweep - float pile = max(wipe.ahead * min(gathered * 2.0, 1.0) * (0.4 + 0.6 * min(wipe.swept * 2.5, 1.0)), rw_rim(f_coord, 0.006 * rw_scale, maskstep) * working * heavy); - float packed = rw_noise2(glass / (0.0015 * rw_scale), 15u).x; - snowcover = max(snowcover, smoothstep(0.15, 0.5, pile * 1.2 + 0.4 * (ripple.x - 0.5)) * mix(0.7, 1.0, packed)); - } - // untreated glass, weathered and a little dirty: flat drops (a rain repellent coating would give beads above 90 degrees) - rw_settle(radians(mix(30.0, 48.0, rw_noise2(glass / (0.005 * rw_scale), 16u).x))); + if (sweepOn) + { + vec2 cg = vec2(center.x, (STREAK_FLIP_Y != 0) ? 1.0 - center.y : center.y); + vis *= wsKept(cg, 0.35 * sq, rivP, sCell, sCW, sCH, gridSize); + } + if (vis <= 0.001) + continue; - // the lamps (of the cab, of the scenery) and the headlights light the water up, from both sides of the glass (worked out - // here, where the fragments of a quad go together) - vec3 lamps = vec3(0.0); - vec3 lampgloss = vec3(0.0); - add_local_lights(outward, lamps, lampgloss); - add_local_lights(-outward, lamps, lampgloss); + vec2 luv = dl / sq + 0.5; + if (flipX > 0.5) luv.x = 1.0 - luv.x; + float atlasTexels = float(textureSize(normalmap, 0).x); + float quadPx = sq / max(uvPerPx, 1e-6); + float nlod = clamp(log2(max(0.25 * atlasTexels / max(quadPx, 1.0), 1.0)), 0.0, 6.0); + vec4 nm = textureLod(normalmap, dropAtlasUV(choice, luv), nlod); + float cov = smoothstep(0.1, 0.6, nm.a) * vis; + if (cov <= 0.001) + continue; + vec2 nxy = nm.rg * 2.0 - 1.0; + if (flipX > 0.5) nxy.x = -nxy.x; + float nz = sqrt(1.0 - clamp(dot(nxy, nxy), 0.0, 1.0)); + vec2 slope = transpose(shapeM) * (-nxy / max(nz, 0.08)); + vec3 n = normalize(vec3(-slope, 1.0)); + // gradients of the tile UV (for the one atlas read after the loop) + vec2 gx = (shapeM * duv1) / sq * vec2(0.25, 0.5); + vec2 gy = (shapeM * duv2) / sq * vec2(0.25, 0.5); + consider(hit, cov * (nm.b * sq * sag + 1e-5), cov, 0.0, n, diff, 0.5 * sq, 1.0, + vis, dropAtlasUV(choice, luv), gx, gy, 1.0, 0.0); + } - // the film just behind a blade, breaking up - float film = snow ? 0.0 : heavy * exp(-rw_since / 0.8) * smoothstep(0.02, 0.08, rw_since); - if (film > 0.01) - { - vec3 fine = rw_noise2(glass / (0.0021 * rw_scale), 6u); - vec2 tilt = fine.yz * (0.004 * film); - rw_sheet(0.00005 * film, rw_along(tilt), 0.3, 0.8 * film); - } + // =================================================================== + // 2. micro droplets: procedural, one per micro cell, fully inside it + // =================================================================== + if (micro_density > 0.0) + { + float mg = gridSize * micro_scale; + vec2 mc = floor(rainCoord * mg); + uvec2 mk = cellKey(mc); + uint m0 = Hash(uvec3(mk, 51u)); + float mLife = micro_life * mix(0.6, 1.6, RandF(m0)); + float mtt = time / mLife + RandF(m0); + float mph = fract(mtt); + uint mep = uint(mod(floor(mtt), 65521.0)); + uint m1 = Hash(uvec3(mk, mep * 4u + 1u)); + if (RandF(m1) < rain_params.x * micro_density) + { + uint m2 = Hash(uvec3(mk, mep * 4u + 2u + uint(hazeSide) * 2u)); + if (wipeVis >= RandF(m2)) + { + float r = mix(micro_size_min, micro_size_max, pow(RandF(m2), 1.5)); + vec2 c = mc + vec2(r) + vec2(RandF(m2), RandF(m2)) * max(1.0 - 2.0 * r, 0.0); + float ell = mix(0.85, 1.15, RandF(m2)); + vec2 p = (rainCoord * mg - c) / r; + p.x *= ell; + float d2 = dot(p, p); + if (d2 < 1.0) + { + float vis = smoothstep(0.0, 0.01, mph) * (1.0 - smoothstep(0.97, 1.0, mph)); + if (sweepOn) + { + vec2 cu = c / mg; + vec2 cg = vec2(cu.x, (STREAK_FLIP_Y != 0) ? 1.0 - cu.y : cu.y); + vis *= wsKept(cg, r / mg, rivP, sCell, sCW, sCH, gridSize); + } + float d = sqrt(d2); + float cov = smoothstep(1.0, 0.8, d) * vis; + if (cov > 0.001) + { + vec2 nxy = p * micro_bulge; + float nz = sqrt(1.0 - clamp(dot(nxy, nxy), 0.0, 1.0)); + vec3 n = normalize(vec3(nxy, nz)); + float h = sqrt(1.0 - d2) * micro_bulge * (r / mg); + float rim = smoothstep(drop_rim_start, drop_rim_end, 1.0 - n.z); + float lt = dot(n, DROP_LIGHT) * drop_light_side * 0.5 + (1.0 - drop_light_side * 0.5); + consider(hit, cov * (h + 1e-6), cov, smoothstep(1.0, 0.9, d) * vis, n, + rainCoord - c / mg, r / mg, 1.0, + vis, vec2(0.0), vec2(0.0), vec2(0.0), 0.0, clamp(rim * lt, 0.0, 1.0)); + } + } + } + } + } - // what the water shows: the view goes through the glass (a plate: only the way from the air into the water counts) and out - // through the surface of the water, bent as much as it is curved. it is the world turned upside down in a drop, and the - // edges of a drop, where the view can't get out (total internal reflection), show the inside of the cab - float background = 0.0; - bool image = ssr_params.x >= 1.0; - if (image) - { - ivec2 size = textureSize(scene_depth, 0); - float depth = texelFetch(scene_depth, clamp(ivec2(gl_FragCoord.xy), ivec2(0), size - 1), 0).r; - if (depth > 0.0) - background = (projection[3][2] / depth) / max(-view.z, 0.05); - } - vec3 inside = ambient * (AMBIENT_SCALE * 0.5); - vec4 water = vec4(0.0); - if (rw_cover > 0.0) - { - vec3 surface = normalize(outward - rw_slope); - vec3 inwater = refract(view, -outward, 1.0 / RW_IOR); - vec3 through = refract(inwater, -surface, RW_IOR); - // what the surface reflects back inside the water: the light which came in at the other side of the drop, from the sky, - // and the inside of the cab. where the view can't get out (the edge of a drop) that is all it shows: a bright edge - vec3 bounced = reflect(inwater, surface); - if (dot(bounced, outward) < 0.0) - bounced = reflect(bounced, outward); - vec3 inner = mix(inside, rw_surroundings(normalize(bounced), 5.0), 0.3); - vec3 color = inner; - if (dot(through, through) > 0.5) - { - float fresnel = 0.02 + 0.98 * pow(1.0 - abs(dot(through, surface)), 5.0); - // the view through the water spreads over this much of the world across a pixel (radians) - float spread = (RW_IOR - 1.0) * rw_pixel / max(rw_curve, 1e-4); - // the picture the drop holds as a lens, and a share of the bending by the surface - vec3 lens = normalize(f_pos.xyz - (1.0 + RW_LENS) * rw_offset) + (through - view) * RW_LENS_BEND; - float lod = mix(log2(1.0 + RW_LENS) - 0.5, log2(max(spread / pixelangle, 1.0)), RW_LENS_BEND); - // a drop a few pixels across would hold a picture of single pixels, a grain: blurred more the smaller it looks - lod += clamp(2.5 - log2(max(rw_curve / rw_pixel, 1.0)), 0.0, 1.5); - float share; - vec3 seen = rw_behind(normalize(lens), lod, background, share); - // the sun through the drop, where the image doesn't hold it: as bright as the drop gathers its light. in heavier rain - // the sun is behind the clouds, its disc is not there to be focused - float sunshare = (1.0 - heavy) * (1.0 - heavy); - if ((lights_count > 0U) && (share < 1.0) && (sunshare > 0.01)) - { - vec3 sun = normalize(-lights[0].dir); - float width = max(spread, 0.03); - float off = acos(clamp(dot(through, sun), -1.0, 1.0)); - if (off < 4.0 * width) - { - float lit = 1.0 - clamp(calc_shadow(), 0.0, 1.0); - vec3 sunlight = lights[0].color * (SUN_DIFFUSE_SCALE * lights[0].intensity * cloud_shadow(mat3(inv_view) * f_pos.xyz)); - // the light of the sun over the spread of the view: a pixel shows pi * irradiance * the share of a steradian - seen += sunlight * (sunshare * lit * (1.0 - share) * exp(-0.5 * off * off / (width * width)) / (2.0 * width * width)); - } - } - color = mix(seen, inner, fresnel); - } - color += lamps * 0.6; - // without the image of the last frame the surroundings stand for what the water bends the view to; nearly flat water - // would show them in place of the scene behind it, so it is left mostly clear - float opaque = image ? 1.0 : mix(0.3, 1.0, smoothstep(0.02, 0.15, 1.0 - dot(through, view))); - water = vec4(color, rw_cover * opaque); - } - // the wet glass where the rain gathers is a little hazy: the tiniest drops spread the light - if (image && (false == snow)) - { - float mist = heavy * gathered * (simulated ? 0.18 : 0.3); - if (mist > 0.01) - { - float share; - vec3 hazy = rw_behind_edges(view, 3.5, background, share, false); - // the tiniest drops spread the light of the sky coming through the glass - hazy = mix(hazy, rw_surroundings(outward, 7.0), 0.1); - layer = vec4(hazy, mist * max(share, 0.5)); - } - } - layer = rw_over(water, layer); - // the lights seen through the streaks of the film the blades leave, drawn into lines towards their pivot - if (image && (length(streakway) > 0.5)) - { - vec4 previous = ssr_reprojection * ((background > 0.0) ? vec4(view * background, 1.0) : vec4(view, 0.0)); - if (previous.w > 1e-5) - { - vec2 coords = (previous.xy / previous.w) * 0.5 + 0.5; - vec2 texel = 1.0 / vec2(textureSize(ssr_history, 0)); - ivec2 size = textureSize(scene_depth, 0); - float near = projection[3][2]; - // a light: much brighter than the place around it (the bright sky is not) - vec3 around = textureLod(ssr_history, clamp(coords, vec2(0.0), vec2(1.0)), 6.0).rgb; - float threshold = max(1.0, 3.0 * max(around.r, max(around.g, around.b))); - vec3 glare = vec3(0.0); - float total = 0.0; - for (int k = -8; k <= 8; ++k) - { - if (k == 0) - continue; - float w = 1.0 - abs(float(k)) / 9.0; - total += w; - vec2 tap = coords + streakway * texel * (float(k) * 5.0); - if (any(lessThan(tap, vec2(0.0))) || any(greaterThan(tap, vec2(1.0)))) - continue; - // only what is outside: the lamps of the cab are not behind the glass - float depth = texelFetch(scene_depth, clamp(ivec2(tap * vec2(size)), ivec2(0), size - 1), 0).r; - if ((depth > 0.0) && (near / depth < -f_pos.z + 2.5)) - continue; - vec3 c = textureLod(ssr_history, tap, 1.5).rgb; - if (any(isnan(c)) || any(isinf(c))) - continue; - glare += max(c - vec3(threshold), vec3(0.0)) * w; - } - glare *= 0.6 * heavy * working / total; - if (any(greaterThan(glare, vec3(1e-4)))) - { - // the scene itself under the water carries the light added (it changes nothing seen) - vec3 scene = textureLod(ssr_history, clamp(coords, vec2(0.0), vec2(1.0)), 0.0).rgb; - layer = rw_over(layer, vec4(max(scene, vec3(0.0)), 0.2)); - layer.rgb += glare / layer.a; - } - } - } - if (snowcover > 0.0) - { - // the flakes are lit through from the outside, by the sky and the sun, and from the inside of the cab; melting they turn - // grey and clear - vec3 outside = rw_surroundings(outward, 6.0); - if (lights_count > 0U) - { - vec3 sun = normalize(-lights[0].dir); - outside += lights[0].color * (SUN_DIFFUSE_SCALE * lights[0].intensity * max(dot(outward, sun), 0.0) * (1.0 - clamp(calc_shadow(), 0.0, 1.0))); - } - vec3 flake = mix(vec3(0.92), vec3(0.62, 0.66, 0.7), wet); - vec3 color = flake * (outside * (0.35 * (1.0 - 0.5 * wet)) + ambient * (AMBIENT_SCALE * 0.7)); - layer = rw_over(vec4(color, snowcover * mix(0.97, 0.6, wet)), layer); - } - } - out_color = layer; + // =================================================================== + // 3. rivulets of this pixel's cells: the layer of gravity and, at speed, the one of the air + // =================================================================== + wsSetLayer(0); + drawRivulet(hit, rivP, sUVg, wsRd1, wsRd2); + if (wsWindShare > 0.001) + { + for (int wl = 1; wl <= wind_layers; ++wl) + { + vec2 wc = vec2(sCW * wind_cell_scale, sCH * ((wl == wind_layers) && (wl > 1) ? wind_long_run : wind_run_scale)); + wsSetLayer(wl); + // every further layer: its cells shifted aside, drops of its own + vec2 sUVw = wsToLayer(sUVg) + fract(vec2(0.5, 0.618) * float(wl - 1)) * wc; + Riv rivW = getRiv(floor(sUVw / wc), wc.x, wc.y, gridSize); + drawRivulet(hit, rivW, sUVw, wsToLayerDir(wsRd1), wsToLayerDir(wsRd2)); + } + wsSetLayer(0); + } + } - { // Overlay windshield texture with alpha - vec3 fragcolor = ambient; - vec3 fragnormal = normalize(f_normal); - float reflectivity = param[1].z; - float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5; - legacy_gloss(); + // ----------------------------------------------------------------------- + // Shading of the winning dome + // ----------------------------------------------------------------------- + float coverA = clamp(hit.cov, 0.0, 1.0); + vec3 dropLayer = vec3(0.0); + float alphaOut = 0.0; + vec3 dropGlint = vec3(0.0); + vec2 lensBend = vec2(0.0); + float lensK = 0.0; // drops: how much the lens shrinks the picture + float lensRadPx = 1.0e4; // drops: radius on screen, pixels + if (coverA > 0.001) + { + vec3 Nt = hit.n; + // look of the drop: grey atlas (bright rim, dark middle) for drops and rivulets, analytic for droplets + vec3 rgb; + float colA; + if (hit.atlas > 0.5) + { + vec4 at = textureGrad(raindropsatlas, hit.auv, hit.agx, hit.agy); + rgb = at.rgb; + colA = smoothstep(0.3, 0.9, at.a) * hit.vis; + } + else + { + rgb = vec3(hit.shade); + colA = hit.colA; + } + float a = colA * mix(drop_center_alpha, drop_rim_alpha, smoothstep(0.1, 0.3, length(rgb))); + dropLayer = rgb * dynBright * a; + alphaOut = clamp(a, 0.0, 1.0); - fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); - vec4 color = vec4(fragcolor, tex_color.a * alpha_mult); + // refraction: Snell for rivulets (and as a fallback), lens picture for drops + vec3 I = normalize(f_pos.xyz); + vec3 No = (dot(Ngl, I) > 0.0) ? Ngl : -Ngl; + vec3 Nd = normalize(Tgl * Nt.x + Bgl * Nt.y + No * Nt.z); + vec3 R = refract(I, -Nd, drop_ior); + if (dot(R, R) < 1e-4) + R = refract(I, -Nd, 1.0 + 0.5 * (drop_ior - 1.0)); + vec2 dSlope = vec2(0.0); + if (dot(R, R) > 1e-4 && R.z < -0.05) + dSlope = R.xy / (-R.z) - I.xy / (-I.z); + vec2 snellBend = clamp(-(dSlope * pxPerSlope * drop_refract) / WS_REFR_MAXPX, vec2(-1.0), vec2(1.0)); + lensBend = snellBend; + if (hit.isDrop > 0.5 && drop_lens_mix > 0.0) + { + vec2 offPx = Jinv * hit.offUV; // pixel - drop centre, in screen pixels + float radPx = hit.radUV / max(uvPerPx, 1e-6); + float k = clamp(min(drop_lens, 0.95 * WS_REFR_MAXPX / max(radPx, 1.0) - 1.0), 0.0, drop_lens); + vec2 lb = clamp((1.0 + k) * offPx / WS_REFR_MAXPX, vec2(-1.0), vec2(1.0)); + lensBend = mix(snellBend, lb, drop_lens_mix); + lensK = k; + lensRadPx = radPx; + } - out_color.xyz = apply_fog(mix(out_color.xyz, color.xyz, color.a)); - out_color.a = mix(out_color.a, 1., color.a); - } - if (false == POSTFX_ENABLED) - { - out_color = tonemap(out_color); - } + vec3 Rd = (dot(R, R) > 1e-4) ? normalize(R) : I; + vec3 glint = vec3(0.0); + if (lights_count > 0U) + { + float cosS = max(dot(Rd, normalize(-lights[0].dir)), 0.0); + float lobe = pow(cosS, drop_glint_sharpness) * drop_glint_strength + + pow(cosS, 0.2 * drop_glint_sharpness) * drop_sheen; + // the shadow (shadow map + GL 4.6 contact shadow ray) only where the sun shows in the drop at all + if (lobe > 1e-4) + { + float shadowSun = 0.0; + if (shadow_tone < 1.0) + shadowSun = (1.0 - shadow_tone) * clamp(calc_shadow(), 0.0, 1.0); + // GL 4.6: the clouds hold the sun back where their shadow falls (as in apply_lights) + float cloudSun = cloud_shadow(mat3(inv_view) * f_pos.xyz); + glint += lights[0].color * lights[0].intensity * lobe * (1.0 - shadowSun) * cloudSun * wsNight; + } + } + // GL 4.6: headlights and lamps come from the light cluster of the fragment (lights_clustered), or are the + // first lights_count - 1 headlights otherwise. calc_headlights takes the screen-space change of f_pos + // (worked out at the top of main, in uniform flow). The drop scatters light from both sides of the glass, + // so the glass normal is turned towards the light. + // only the lights outside the glass and a few metres away light the drops up (signals, lamps of the station, the + // headlights of other trains): the lamps and the headlights of the own vehicle, a metre or two from the glass, would + // make every drop glow white + vec3 lamps = vec3(0.0); + if (lights_clustered != 0U) + { + cluster_range_s range = cluster_ranges[fragment_cluster()]; + for (uint i = 0U; i < range.count; i++) + { + light_s lt = lights[cluster_light_indices[range.offset + i]]; + vec3 toL = lt.pos - f_pos.xyz; + float away = smoothstep(0.0, 0.2, dot(toL, wsN) / max(length(toL), 1e-4)) + * smoothstep(drop_light_near, 2.0 * drop_light_near, length(toL)); + if (away <= 0.0) + continue; + vec3 nl = (dot(Ngl, toL) > 0.0) ? Ngl : -Ngl; + if (lt.type == LIGHT_HEADLIGHTS) + lamps += lt.color * calc_headlights(lt, nl, dp1, dp2).x * lt.intensity * drop_headlight_scatter * away; + else if (drop_lamp_scatter > 0.0) + lamps += lt.color * calc_local_light(lt, nl).x * lt.intensity * drop_lamp_scatter * away; + } + } + else + { + for (uint i = 1U; i < lights_count; i++) + { + light_s lt = lights[i]; + vec3 toL = lt.pos - f_pos.xyz; + float away = smoothstep(0.0, 0.2, dot(toL, wsN) / max(length(toL), 1e-4)) + * smoothstep(drop_light_near, 2.0 * drop_light_near, length(toL)); + if (away <= 0.0) + continue; + vec3 nl = (dot(Ngl, toL) > 0.0) ? Ngl : -Ngl; + lamps += lt.color * calc_headlights(lt, nl, dp1, dp2).x * lt.intensity * drop_headlight_scatter * away; + } + } + glint += min(lamps, vec3(drop_light_max)); + // reflection of the surroundings on the dome: straight from the environment map. (It used to go through a + // second apply_lights, which in GL 4.6 also runs the shadow map, the contact shadows and the whole light + // cluster again for every drop pixel; the sun and the lamps are done above already.) + if (drop_env > 0.0) + { + vec3 Nv = -Nd; // dome normal towards the viewer + float NoV = clamp(dot(Nv, -I), 0.0, 1.0); + glint += envmap_color_lod(Nv, 0.8) * EnvBRDFApprox(vec3(0.04), 0.1, NoV) * drop_env * wsNight; + } + dropGlint = glint; + if (!POSTFX_ENABLED) + dropGlint = min(dropGlint, vec3(1.0)); // this path is not tonemapped + } - if (MOTIONBLUR_ENABLED) - { - out_motion = vec4(0.0); - } + // ----------------------------------------------------------------------- + // What is seen through the wet glass: the image of the last frame, blurred by the haze, bent by the drops + // ----------------------------------------------------------------------- + // the haze after the wiper: grows with the rain fallen since, up to the intensity of the rain (as it always was where no wiper reaches) + float wipeAge = wsWipeAge(f_coord); + float hazeBack = (wipeAge < 0.0) ? 1.0 + : min(wipeVis, pow(clamp(wipeAge * rain_params.x / haze_fill, 0.0, 1.0), haze_curve)); + float hazeWeight = min(rain_params.x * hazeBack * (1.0 + haze_speed * wsSpeed), 1.0) * (1.0 - max(alphaOut, coverA)); + float glassClear = 1.0 - smoothstep(0.5, 0.95, glassA); + bool image = ssr_params.x >= 1.0; + float background = 0.0; // distance to the scene behind, along the view (0: far / not known) + if (image) + { + ivec2 size = textureSize(scene_depth, 0); + float depth = texelFetch(scene_depth, clamp(ivec2(gl_FragCoord.xy), ivec2(0), size - 1), 0).r; + if (depth > 0.0) + background = (projection[3][2] / depth) / max(-wsView.z, 0.05); + } + vec4 under = vec4(0.0); // the blurred view under the drops (not premultiplied) + vec4 bent = vec4(0.0); // the view bent by the drops, laid over everything (as the old postfx did) + + // the haze is blurred by the post-processing (postfx_taa.frag / postfx_motionblur.frag, rain_windscreen_haze.glsl): the + // picture of this frame can't be read here, and one of the last frame laid over it only shows a milky ghost of the scene + float blurAmt = clamp(hazeWeight * blur_amount, 0.0, 1.0); + + // the drops: the view bent (the picture shift worked out above), and the lights near them. with the motion vectors the + // post-processing bends the picture of this frame (postfx_taa.frag / postfx_motionblur.frag, rain_windscreen_haze.glsl): it has + // the depth of the cab and never pulls the dashboard or the roof into a drop. the image of the last frame is only the fallback + float refrA = smoothstep(0.05, 0.35, coverA) * glassClear * step(glassA, 0.5); + if ((false == MOTIONBLUR_ENABLED) && (refrA > 0.001)) + { + vec2 shiftPx = -lensBend * WS_REFR_MAXPX; // where the drop looks, screen pixels + vec3 dir = normalize(wsView + shiftPx.x * wsDvx + shiftPx.y * wsDvy); + // a drop shows a minified picture: read it from a coarser level (no grain); tiny drops a little blurrier still + float lod = clamp(log2(1.0 + lensK * drop_lens_mix) - 0.5, 0.0, 3.0) + + clamp(2.5 - log2(max(lensRadPx, 1.0)), 0.0, 1.5); + float share; + vec3 seen = wsBehind(dir, lod, background, share, true); + if (image && (WS_LIGHT_GAIN > 0.0)) + seen += wsLightGlow(wsView, background); + // without the image the surroundings stand in: only faintly, they aren't the scene behind + bent = vec4(seen, refrA * WS_REFR_MIX * (image ? 1.0 : 0.3)); + } + + // the drop shading over it + float shadeA = coverA * drop_shade_alpha; + float outA = alphaOut + shadeA * (1.0 - alphaOut); + vec4 drops = vec4(dropLayer, outA); + drops.rgb += dropGlint * coverA / max(outA, 0.05); // the blend multiplies by alpha once more + out_color = wsOver(drops, under); + + { // windshield texture over the rain + vec3 fragcolor = ambient; + // where the glass texture is clear, its lighting is multiplied by ~0 below: skip apply_lights there + if (glassA > 0.002) + { + vec3 fragnormal = normalize(f_normal); + float reflectivity = param[1].z; + float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5; + legacy_gloss(); + fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); + } + vec4 color = vec4(fragcolor, glassA); + out_color.xyz = apply_fog(mix(out_color.xyz, color.xyz, color.a)); + out_color.a = mix(out_color.a, 1., color.a); + } + // the picture in the drops goes over the drop shading and the glass, as the old postfx replaced the pixel with it: the dark + // middle of the atlas only shows through faintly, the rim and the glints a little more + out_color = wsOver(bent, out_color); + if (!POSTFX_ENABLED) + out_color = tonemap(out_color); + + // the velocity target: on the drops the picture shift (x, y = WS_DROP_BIAS + WS_BEND_ENC * bend), on the hazy glass the request + // for the haze (x = WS_ENC * strength, y = 0); elsewhere the velocity of the scene behind the glass stays as it is (alpha 0) + if (MOTIONBLUR_ENABLED) + { + vec4 req = vec4(0.0); + bool drop = (coverA > 0.05 || alphaOut > 0.05) && (glassA < 0.5); + float blurMask = blurAmt * glassClear; + if (drop) + { + vec2 bend = lensBend * smoothstep(0.05, 0.35, coverA); + req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); + } + else if (blurMask >= 0.01) + req = vec4(WS_ENC * blurMask, 0.0, 0.0, 1.0); + out_motion = req; + } +} + +float GetMixFactor(in vec2 co, out float side) { + vec4 movePhase = wiper_pos; + bvec4 is_out = lessThanEqual(movePhase, vec4(1.)); + movePhase = mix(vec4(2.) - movePhase, movePhase, is_out); + + vec4 mask = textureLod(wipermask, co, 0.0); // called from non-uniform flow: no implicit derivatives + + vec4 areaMask = step(.001, mask); + + vec4 maskVal = mix(1. - mask, mask, is_out); + vec4 wipeWidth = smoothstep(1., .9, movePhase) * .25; + vec4 cleaned = smoothstep(movePhase - wipeWidth, movePhase, maskVal) * areaMask; + vec4 side_v = step(maskVal, movePhase); + cleaned *= side_v; + side_v = mix(side_v, vec4(1.) - side_v, is_out); + + // "regeneration", raindrops gradually returning after wiper pass: + vec4 regenPhase = clamp((vec4(time) - mix(wiper_timer_out, wiper_timer_return, side_v) - vec4(.2)) / vec4(rain_params.y), vec4(0.), vec4(1.)); + + side_v = mix(vec4(0.), vec4(1.) - side_v, areaMask); + + vec4 factor_v = mix(vec4(1.), regenPhase * (vec4(1.) - cleaned), areaMask); + + side = 0.; + float out_factor = 1.; + bool have_side = false; + // out_factor: the blade that clears the cell the most wins. side: which wiper stroke the drops of this + // cell belong to (part of their random seed, so it must not depend on out_factor). + for (int i = 0; i < 4; ++i) + { + out_factor = min(out_factor, factor_v[i]); + if (!have_side && areaMask[i] > 0.) + { + side = side_v[i]; + have_side = true; + } + } + return out_factor; } diff --git a/shaders/ogl46/postfx_motionblur.frag b/shaders/ogl46/postfx_motionblur.frag index e28953ebb..41e080ce6 100644 --- a/shaders/ogl46/postfx_motionblur.frag +++ b/shaders/ogl46/postfx_motionblur.frag @@ -13,13 +13,34 @@ layout(binding = 1) uniform sampler2D velocity_tex; layout(binding = 2) uniform sampler2D depth_tex; #include "common.glsl" +#include "rain_windscreen_haze.glsl" void main() { + // the hazy wet windscreen (mat_rain_windscreen.frag): blurred here without the taa, left as it is when the taa blurred it + vec2 rawv = texture(velocity_tex, f_coords).xy; + if (wsIsDrop(rawv)) + { + vec4 picture = texture(color_tex, f_coords); + out_color = vec4((picture.a > 0.5 * (1.0 + WS_HAZED)) ? picture.rgb + : wsDropRefraction(color_tex, velocity_tex, depth_tex, f_coords, rawv), 1.0); + return; + } + float blurAmt = wsBlur(rawv); + if (blurAmt > 0.0) + { + vec4 picture = texture(color_tex, f_coords); + out_color = vec4((picture.a > 0.5 * (1.0 + WS_HAZED)) ? picture.rgb : wsHaze(color_tex, velocity_tex, f_coords, blurAmt), 1.0); + return; + } + float ori_depth = texture(depth_tex, f_coords).x; vec2 texelSize = 1.0 / vec2(textureSize(color_tex, 0)); - vec2 velocity = texture(velocity_tex, f_coords).xy * param[0].x; + vec2 velocity = rawv * param[0].x; + // edge pixels of the windscreen can carry a fraction of a blur request: never use that as motion + if (any(greaterThan(abs(rawv), vec2(WS_FLOOR * WS_ENC)))) + velocity = vec2(0.0); float speed = length(velocity / texelSize); int nSamples = clamp(int(speed), 1, 32); diff --git a/shaders/ogl46/postfx_taa.frag b/shaders/ogl46/postfx_taa.frag index 294325e71..a4e9566d4 100644 --- a/shaders/ogl46/postfx_taa.frag +++ b/shaders/ogl46/postfx_taa.frag @@ -22,4 +22,53 @@ layout(binding = 3) uniform sampler2D history_tex; #define TAA_HISTORY_VALID (param[0].x > 0.5) #define TAA_REPROJECTION future #define TAA_NEAR param[0].y +#include "rain_windscreen_haze.glsl" + +// the resolve of the taa under another name: main() below gives the hazy windscreen its blur first +#define main taa_resolve_main #include "taa_resolve.glsl" +#undef main + +// the drops and the haze are made from the frame alone (the history of the taa would smear them over the frames): drawn with the +// offsets of the taa they shimmer from frame to frame. they stay where they are on the screen, so the result of the last frame at +// the same pixel is blended in: fully while the view stands still, half while it moves, kept near this frame's result (no ghosts +// of a wiper or of drops gone) +const float WS_TEMPORAL_SHARE = 0.2; // the share of this frame while the view stands still +const float WS_TEMPORAL_MOVING = 0.5; // ... and while it moves +const float WS_TEMPORAL_RANGE = 0.12; // the last frame kept within this of this frame (colours squeezed into 0..1) + +vec3 wsStabilize(vec3 current, ivec2 pixel) +{ + if (false == TAA_HISTORY_VALID) + return current; + vec4 last = texelFetch(history_tex, pixel, 0); + if (any(isnan(last)) || (last.a < 0.5 * (1.0 + WS_HAZED))) // not a drop or haze pixel in the last frame + return current; + vec2 size = vec2(textureSize(color_tex, 0)); + float depth = texelFetch(depth_tex, pixel, 0).r; + vec4 world = TAA_REPROJECTION * vec4(f_coords * 2.0 - 1.0, depth, 1.0); + bool still = (world.w > 0.0) && (length((world.xy / world.w * 0.5 + 0.5 - f_coords) * size) < 0.5); + vec3 c = taa_compress(current); + vec3 h = clamp(taa_compress(taa_clean(last.rgb)), c - WS_TEMPORAL_RANGE, c + WS_TEMPORAL_RANGE); + return taa_decompress(clamp(mix(h, c, still ? WS_TEMPORAL_SHARE : WS_TEMPORAL_MOVING), vec3(0.0), vec3(1.0 - 1.0 / TAA_HALF_MAX))); +} + +void main() +{ + // the hazy wet windscreen (mat_rain_windscreen.frag): the picture of this frame blurred over the hazy glass, without the + // history (else it would blur on frame after frame); marked for the motion blur after + ivec2 pixel = ivec2(f_coords * vec2(textureSize(velocity_tex, 0))); + vec2 raw = texelFetch(velocity_tex, pixel, 0).xy; + if (wsIsDrop(raw)) + { + out_color = vec4(wsStabilize(taa_clean(wsDropRefraction(color_tex, velocity_tex, depth_tex, f_coords, raw)), pixel), WS_HAZED); + return; + } + float blurAmt = wsBlur(raw); + if (blurAmt > 0.0) + { + out_color = vec4(wsStabilize(taa_clean(wsHaze(color_tex, velocity_tex, f_coords, blurAmt)), pixel), WS_HAZED); + return; + } + taa_resolve_main(); +} diff --git a/shaders/ogl46/rain_windscreen_haze.glsl b/shaders/ogl46/rain_windscreen_haze.glsl new file mode 100644 index 000000000..6dd9a4cde --- /dev/null +++ b/shaders/ogl46/rain_windscreen_haze.glsl @@ -0,0 +1,233 @@ +// the haze of the wet windscreen (mat_rain_windscreen.frag), drawn by the post-processing: the glass asks for it in the velocity +// target (x = WS_ENC * strength, y = 0, see mat_rain_windscreen.frag), and the picture there is blurred over the hazy glass only. +// postfx_taa.frag does it with the temporal anti-aliasing (every frame, also standing still), postfx_motionblur.frag without it +// (it runs only while something moves). the picture blurred by the taa is marked in its alpha (WS_HAZED), so the motion blur +// after it leaves it as it is. +// +// real motion vectors are tiny (<< 0.25 per frame), so the large values can only come from the windscreen +#ifndef RAIN_WINDSCREEN_HAZE_GLSL +#define RAIN_WINDSCREEN_HAZE_GLSL + +const float WS_ENC = 64.0; // must match mat_rain_windscreen.frag +const float WS_FLOOR = 0.004; // = 0.256 in raw velocity units: everything below is real motion +const float WS_HAZED = 2.0; // alpha of the picture the taa already blurred + +// blur of hazy glass +const float WS_RADIUS = 0.014; // max blur radius, fraction of screen height +const int WS_TAPS = 16; +const float WS_HAZE_LIGHT_CAP = 12.0; // the most a light adds to the haze around it (brightness, scene units) + +// strength of the blur request, 0 for pixels that are not blur pixels +float wsBlur(vec2 raw) +{ + if (raw.x > 100.0 || raw.y > 100.0) // a blended edge with something else: not a blur pixel + return 0.0; + float m = clamp(raw.x / WS_ENC, 0.0, 1.0); + return clamp((m - WS_FLOOR) / (1.0 - WS_FLOOR), 0.0, 1.0); +} + +// a colour of the picture made safe: a very bright light can be an infinity in the half float image (and a broken pixel a nan); +// in an average that gave nan for the whole result, which the taa turns black: black dotted blobs around the lights +vec3 wsSafe(vec3 c) +{ + return any(isnan(c)) ? vec3(0.0) : clamp(c, vec3(0.0), vec3(65000.0)); +} + +vec3 wsFetch(sampler2D tex, vec2 uv) +{ + return wsSafe(textureLod(tex, uv, 0.0).rgb); +} + +// the weight of a colour in an average that a single very bright pixel must not take over +float wsKaris(vec3 c) +{ + return 1.0 / (1.0 + dot(c, vec3(0.2126, 0.7152, 0.0722))); +} + +// the picture at Uv blurred over the hazy glass, for a request of BlurAmt (> 0) +vec3 wsHaze(sampler2D colortex, sampler2D velocitytex, vec2 uv, float blurAmt) +{ + vec2 texelSize = 1.0 / vec2(textureSize(colortex, 0)); + float aspect = texelSize.x / texelSize.y; // height / width + vec3 sharp = wsFetch(colortex, uv); + + float radius = WS_RADIUS * blurAmt; + + // interleaved gradient noise rotates the disc per pixel -> no banding + float rot = 6.2831853 * fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715)))); + + float wsum = wsKaris(sharp); + vec3 sum = sharp * wsum; + float psum_w = 1.0; // the plain average beside it + vec3 psum = sharp; + + for (int i = 0; i < WS_TAPS; ++i) + { + float r = sqrt((float(i) + 0.5) / float(WS_TAPS)); + float a = float(i) * 2.3999632 + rot; // golden angle + vec2 o = vec2(cos(a), sin(a)) * r * radius; + o.x *= aspect; + + vec2 tap = uv + o; + + // take only hazy-glass pixels (not the cab frame, not clear glass, not drops) + // weighed by 1 / (1 + brightness) (karis average): an ordinary picture blurs the same, but a very bright light + // (a lamp close by, headlights) is not smeared over the whole disc at full strength, which the bloom then turned + // into a large flat blob shaped like a clover + float w = step(0.01, wsBlur(textureLod(velocitytex, tap, 0.0).xy)); + vec3 c = wsFetch(colortex, tap); + psum += c * w; + psum_w += w; + w *= wsKaris(c); + sum += c * w; + wsum += w; + } + + // the karis average alone almost wipes small bright lights out of the haze (signals at night went faint): the light the + // plain average has above it comes back, up to WS_HAZE_LIGHT_CAP, so a light stays a soft glow of its colour and only a + // very bright one (a lamp close by) isn't smeared at full strength + vec3 blurred = sum / wsum; + vec3 extra = max(psum / psum_w - blurred, vec3(0.0)); + float extraL = dot(extra, vec3(0.2126, 0.7152, 0.0722)); + blurred += extra * min(1.0, WS_HAZE_LIGHT_CAP / max(extraL, 1e-4)); + return mix(sharp, blurred, min(blurAmt * 4.0, 1.0)); +} + +// --------------------------------------------------------------------------------------------------------------------------- +// refraction in the drops: the glass sends the picture shift of the drop (x, y = WS_DROP_BIAS + WS_BEND_ENC * bend, bend -1..1 +// = WS_REFR_MAXPX pixels), and the picture of this frame is bent here. the depth of the whole frame (with the cab) is known here, +// so the dashboard, the frame and the roof of the cab are never pulled into a drop (the image of the last frame used by the +// glass shader can't tell them apart: white drops at night at the edges and under the wipers) +// --------------------------------------------------------------------------------------------------------------------------- +const float WS_BEND_ENC = 60.0; // must match mat_rain_windscreen.frag +const float WS_DROP_BIAS = 192.0; // must match mat_rain_windscreen.frag +const float WS_REFR_MAXPX = 96.0; // must match mat_rain_windscreen.frag +const float WS_REFR_MIX = 0.85; // 0 = no refraction, 1 = only the refracted picture +const float WS_LENS_AA = 0.75; // above this spread of the picture between neighbouring pixels, a 4x4 footprint is averaged + +// the lights in the drops: a drop is a wide-angle lens and lights up near a bright light (signals, lamps, headlights). taken from +// the mipmaps of the image the screen reflections keep (ssr_history: the last frame, or this one in the motion blur), so the glow +// is smooth: point samples of the full image caught a headlight of one pixel only at fixed offsets and drew it as grids of dots +const float WS_LIGHT_GAIN = 1.0; // brightness of the lights in the drops (0 = off) +const float WS_LIGHT_CAP = 8.0; // the most the glow adds to a drop (brightness, scene units) +const float WS_LIGHT_MIN_LUM = 1.0; // a light: the fine level at least this bright (scene units) above the place around it ... +const float WS_LIGHT_CONTRAST = 3.0; // ... and this many times brighter than it +const float WS_LIGHT_FINE = 3.5; // mip levels: the drop's own neighbourhood (~11 px), a wider one (~32 px), the place around +const float WS_LIGHT_MID = 5.0; +const float WS_LIGHT_WIDE = 7.0; +const float WS_LIGHT_MID_SHARE = 0.5; // how much the lights a little further away count + +// the vulkan renderer gives the post-processing only its own images (LAYOUT_POST): no history of the reflections, no glow there +#ifndef LAYOUT_POST +layout(binding = SSR_HISTORY_TEX) uniform sampler2D ws_light_history; +#endif + +// reverse z, infinite far: depth = znear / distance. a sample is "the cab" when it is much nearer than the centre and closer than ~5 m +const float WS_NEAR_RATIO = 1.6; +const float WS_NEAR_DEPTH = 0.02; + +bool wsSameLayer(float d, float d0) +{ + return d <= max(d0 * WS_NEAR_RATIO, WS_NEAR_DEPTH); +} + +float wsLum(vec3 c) +{ + return dot(c, vec3(0.2126, 0.7152, 0.0722)); +} + +// a drop pixel (drop, rivulet): both values in 132..252 +bool wsIsDrop(vec2 raw) +{ + return raw.x > 120.0 && raw.y > 120.0; +} + +vec2 wsBend(vec2 raw) +{ + return clamp((raw - WS_DROP_BIAS) / WS_BEND_ENC, -1.0, 1.0); +} + +#ifndef LAYOUT_POST +vec3 wsLightExcess(vec2 uv, float lod, vec3 wide) +{ + vec3 c = wsSafe(textureLod(ws_light_history, uv, min(lod, ssr_params2.x)).rgb); + vec3 excess = max(c - wide * WS_LIGHT_CONTRAST, vec3(0.0)); + return excess * smoothstep(0.5 * WS_LIGHT_MIN_LUM, WS_LIGHT_MIN_LUM, wsLum(excess)); +} + +vec3 wsLightGlow(vec2 uv) +{ + if ((ssr_params.x < 1.0) || (textureSize(ws_light_history, 0).x < 16)) + return vec3(0.0); + vec3 wide = wsSafe(textureLod(ws_light_history, uv, min(WS_LIGHT_WIDE, ssr_params2.x)).rgb); + vec3 glow = wsLightExcess(uv, WS_LIGHT_FINE, wide) + WS_LIGHT_MID_SHARE * wsLightExcess(uv, WS_LIGHT_MID, wide); + glow *= WS_LIGHT_GAIN; + // a light close by is kept to the brightness of one light + return glow * min(1.0, WS_LIGHT_CAP / max(wsLum(glow), 1e-4)); +} +#else +vec3 wsLightGlow(vec2 uv) +{ + return vec3(0.0); +} +#endif + +// the picture at Uv seen through the drop, for a drop pixel with the request Raw +vec3 wsDropRefraction(sampler2D colortex, sampler2D velocitytex, sampler2D depthtex, vec2 uv, vec2 raw) +{ + vec2 texelSize = 1.0 / vec2(textureSize(colortex, 0)); + float aspect = texelSize.x / texelSize.y; // height / width + vec3 center = wsFetch(colortex, uv); + + vec2 bend = wsBend(raw); + vec2 uv2 = uv - bend * WS_REFR_MAXPX * texelSize; + + // the spread of the picture between neighbouring pixels (the jacobian of the shift): a drop shows a minified, flipped copy + // of the scene, single samples would alias into a hatch there + vec2 rx = textureLod(velocitytex, uv + vec2(texelSize.x, 0.0), 0.0).xy; + vec2 ry = textureLod(velocitytex, uv + vec2(0.0, texelSize.y), 0.0).xy; + vec2 jx = (wsIsDrop(rx) ? wsBend(rx) - bend : vec2(0.0)) * WS_REFR_MAXPX; + vec2 jy = (wsIsDrop(ry) ? wsBend(ry) - bend : vec2(0.0)) * WS_REFR_MAXPX; + float lens = length(jx) + length(jy); + + // never pull in what is much nearer than the scene behind the glass (the cab) + vec3 refr = center; + float d0 = textureLod(depthtex, uv, 0.0).x; + float d1 = textureLod(depthtex, uv2, 0.0).x; + if (wsSameLayer(d1, d0)) + { + if (lens < WS_LENS_AA) + { + refr = wsFetch(colortex, uv2); + } + else + { + vec2 fx = clamp(vec2(1.0, 0.0) - jx, vec2(-10.0), vec2(10.0)); + vec2 fy = clamp(vec2(0.0, 1.0) - jy, vec2(-10.0), vec2(10.0)); + vec3 acc = vec3(0.0); + float wacc = 0.0; + for (int j = 0; j < 4; ++j) + { + for (int i = 0; i < 4; ++i) + { + vec2 t = (vec2(float(i), float(j)) + 0.5) / 4.0 - 0.5; + vec3 c = wsFetch(colortex, uv2 + (fx * t.x + fy * t.y) * texelSize); + float w = wsKaris(c); + acc += c * w; + wacc += w; + } + } + refr = acc / wacc; + } + } + + vec3 outc = mix(center, refr, WS_REFR_MIX); + // the glow only in the drops themselves, strongest in their middle, where the lens bends most: the water film and the + // rivulets between them (no bend) would show it as flat squares around the headlights of an oncoming train + float glowW = smoothstep(0.03, 0.2, length(bend)); + if ((WS_LIGHT_GAIN > 0.0) && (glowW > 0.0)) + outc += wsLightGlow(uv) * glowW; + return outc; +} + +#endif diff --git a/shaders/vk14/mat_rain_windscreen.frag b/shaders/vk14/mat_rain_windscreen.frag index 4cc783f2a..fa76bc95e 100644 --- a/shaders/vk14/mat_rain_windscreen.frag +++ b/shaders/vk14/mat_rain_windscreen.frag @@ -1,30 +1,45 @@ #version 460 core #define STAGE_FRAGMENT 1 #include "common.glsl" -// Windshield rain and snow -// by @lcddisplay; wiper movement @MichauSto; water on the glass rewritten as a model of drops lying on it +// Windshield rain effects - v3 (rewrite) +// by @lcddisplay; wiper movement @MichauSto; rain v3: drop layers, drop life, rivulets that sweep drops // -// the material: the textures diffuse (the glass) and wipermask (a blade per channel, r g b a: 0 where it doesn't reach, elsewhere -// the place of the blade over its sweep, 0 at rest .. 1 at the far end, at which it goes over the place). raindropsatlas and -// raindrop_grid_size aren't used any more, they stay so the materials which name them still load. rain_scale (1 when not given) -// scales the drops and the flakes. water_slot is given by the renderer (1 + the glass of the simulation, 0 none), not by the -// material. the block of the scene: rain_params (x: how heavy the rain or snow is, z: 1 for snow, w: temperature of the air), -// wiper_pos, wiper_timer_out, wiper_timer_return (the blades of the vehicle of the camera) and rain_wind (the air against it). +// What is on the glass: +// 1. Micro droplets: a dense grid of tiny, static droplets. Procedural (no texture reads): a spherical cap +// per droplet. They make the glass look wet between the bigger drops. +// 2. Drops: one per grid cell (raindrop_grid_size), shape from the 2x2 drop tiles of the atlas +// (normalmap: rg = normal xy, b = height, a = mask). A drop lands (quick pop), sits still for +// drop_life_min..drop_life_max seconds, then makes room for a new one. Drops do NOT slide: all motion is +// done by the rivulets (a sliding drop used to leave its 3x3 neighbourhood and got cut off). +// Sizes are skewed (many medium, few big) and the tiles are randomly mirrored (8 shapes instead of 4). +// Where drops overlap, the higher one wins (no averaged "ghost" normals). +// 3. Rivulets: a drop runs down in stick-slip fashion and leaves a wet trail (4 sprites in the right half +// of the atlas, 256 x 1024: head in the bottom STREAK_HEAD_FRAC, trail above). The head sweeps up every +// drop and droplet on its way: the trail band is clean until the rivulet fades out. +// The trail right above the head is taken from the sprite part that touches the head, then it blends +// into the trail pattern that is fixed to the glass (beads stay where they were left). // -// the glasses of the cab of the train are simulated (gfx::windscreen_water, water_*.comp, water.glsl): the raindrops land as often -// as the rain hits the glass, splashing; the drops lie held by surface tension until gravity and the drag of the air pull them -// harder, then slide in stops and goes, wetting their paths (the next ones follow them into rivulets) and leaving droplets behind; -// the drops which touch flow together; the blades take the water along, gather it into a bead and leave it at the ends of their -// sweep, where it runs down; the flakes stick and melt. here the drops of the simulation are drawn where the fragment is, and the -// wetted paths as a thin film. elsewhere (the windows of other vehicles, a glass the simulation has no room for) the water is made -// up from the time alone: drops landing, growing and sliding along tracks, the blades pushing a ridge and leaving the water at the -// edge of their sweep. +// Shading: the grey atlas (bright rim, dark middle) is read once per pixel, only for the drop that wins the +// pixel (it used to be read for all 9 neighbours). Micro droplets are shaded analytically. // -// the water is a field of soft kernels (metaballs): drops coming close flow together, and a drop is a few kernels, so the drops -// are of many shapes. a drop is a lens holding a sharp picture of the place around it turned over (the image of the last frame -// where the screen holds it, the sky and the ground elsewhere), its edge shows the light of the sky reflected inside it; the lamps -// and the headlights light the water up; the film the blades leave breaks up behind them and the lights seen through it are drawn -// into lines towards their pivot; the wet glass is a little milky +// Refraction / blur (OpenGL 4.6, the renderer with the screen space reflections): the glass reads the image of the last +// frame the renderer keeps for the reflections (ssr_history, with mipmaps) and the depth of the scene (scene_depth): +// - drops act as small lenses: the pixel shows the scene on the opposite side of the drop centre, so every drop holds a +// small, flipped picture (drop_lens); rivulets bend the view by Snell's law from their normal, +// - bright lights near a drop (signals, lamps, headlights) show up in it, +// Works standing still, with the motion blur off and with taa. Needs gfx.ssr (default: medium); without it the drops show +// the sky / ground only, faintly. +// The haze of the wet glass is blurred by the post-processing, from the picture of this frame: the glass writes a request +// into the velocity target (x = 64 * strength, y = 0) and postfx_taa.frag (with gfx.antialiasing taa: every frame) or +// postfx_motionblur.frag (without it: only while something moves) blur the picture there (rain_windscreen_haze.glsl). +// +// Speed: the air against the vehicle (rain_wind) drives the water: at speed a second layer of rivulets runs along its push +// (up a front glass, back along a side window) and sweeps the drops up on its way, the drops are stretched along the push, +// the haze grows. Standing still the rain is as it always was. +// +// OpenGL 4.6 renderer (feat/gl46-migration): headlights and lamps are clustered, calc_headlights takes the +// screen-space derivatives of f_pos, the sun glint follows the cloud shadow. Lamps (cab lamp, scenery) light up +// the drops too (drop_lamp_scatter). layout(location = 0) in vec3 f_normal; layout(location = 2) in vec2 f_coord; @@ -42,1176 +57,1020 @@ layout(location = 1) out vec4 out_motion; #pragma texture(diffuse, 0, sRGB_A) #pragma texture(raindropsatlas, 1, sRGB_A) #pragma texture(wipermask, 2, sRGB_A) +#pragma texture(normalmap, 3, RGBA) // rg = normal xy, b = height, a = mask; 2048 x 1024 (drops left, rivulets right), linear #pragma param(color, 0, 0, 4, diffuse) #pragma param(diffuse, 1, 0, 1, diffuse) #pragma param(specular, 1, 1, 1, specular) #pragma param(reflection, 1, 2, 1, zero) #pragma param(glossiness, 1, 3, 1, glossiness) #pragma param(raindrop_grid_size, 2, 0, 1, one) -#pragma param(rain_scale, 2, 1, 1, one) #include "light_common.glsl" #include "apply_fog.glsl" #include "tonemapping.glsl" -#include "water.glsl" +#include "random.glsl" layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 0) uniform sampler2D diffuse; layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 1) uniform sampler2D raindropsatlas; layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 2) uniform sampler2D wipermask; +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 3) uniform sampler2D normalmap; -const float RW_PI = 3.14159265; -// refractive index of water -const float RW_IOR = 1.333; -// the falling particles (particles_precipitation.comp, rendering/common/gpuparticles.cpp): the diameters of the flakes, metres, -// and how fast the rain and the snow fall, m/s -const vec2 RW_SNOW_DIAMETER = vec2(0.004, 0.012); -const float RW_RAIN_FALL = 7.0; -const float RW_SNOW_FALL = 1.1; -// a drop is a lens: it holds a sharp picture of the place around it, turned over through its middle, RW_LENS times as far out -// as the fragment is from the middle (and as much smaller), with this share of the bending of the view by the surface on top -const float RW_LENS = 2.0; -const float RW_LENS_BEND = 0.15; -// the drag of the air going along the glass: the speed at which it equals the weight of a drop, m/s; and the share of the air -// meeting the glass head on which turns up along it. so the water goes up a glass the sooner the more it leans back: on a -// vertical glass at about 250 km/h, leaning 20 degrees at about 130 km/h, 45 degrees at about 80 km/h -const float RW_DRAG_SPEED = 24.0; -const float RW_HEAD_ON = 0.35; -// the water is a field summed from soft kernels (metaballs) and its surface is where the field is RW_SURFACE: drops which come -// close flow together the way surface tension pulls them. a kernel alone reaches the surface at RW_EDGE of its radius -const float RW_SURFACE = 0.25; -const float RW_EDGE = 0.61; +// --- Haze of the wet glass (blur) ------------------------------------------------ +// The haze follows the rain and is wiped away by the wipers, as before (fully blurred from a quarter of the haze on). +const float blur_amount = 1.0; // strength of the haze: 0 = off, 1 = full +// after the wiper the haze grows with the rain fallen on the glass since (intensity x seconds) from nothing up to its full +// strength, which is the intensity of the rain (cloud cover 1.5 -> 0.5). where no wiper reaches it is as always +const float haze_fill = 12.0; // rain to mist the glass up fully: seconds of the heaviest rain (2x as long at 1.5) +const float haze_curve = 1.0; // > 1: slow at first, then more and more +const float haze_speed = 1.0; // at speed the haze grows: x (1 + haze_speed) at full speed (see wind_drag_gain) +const float WS_BEND_ENC = 60.0; // the drop request in the velocity target; must match rain_windscreen_haze.glsl +const float WS_DROP_BIAS = 192.0; +const float WS_ENC = 64.0; // the haze request in the velocity target; must match rain_windscreen_haze.glsl -// the glass at the fragment: the view space steps along it for a step of the coordinates of the glass (metres along the axes -// of the model, see main()), and the size of a pixel on it, metres -vec3 rw_tu; -vec3 rw_tv; -float rw_pixel; +// --- Drops (atlas tiles) ------------------------------------------------------ +const float drop_density = 0.6; // share of grid cells holding a drop at full rain (scaled by rain intensity) +const float drop_size_min = 0.45; // drop size in grid cells +const float drop_size_max = 1.15; +const float drop_size_bias = 1.8; // >1 = more small/medium drops, fewer big ones +const float drop_life_min = 14.0; // seconds a drop sits on the glass +const float drop_life_max = 45.0; +const float drop_appear = 0.18; // seconds of the landing "pop" +const float drop_fade = 1.5; // seconds a drop takes to vanish at the end of its life +const float drop_sag = 0.12; // max vertical stretch of a resting drop (gravity) -// how the water on the glass behaves here, set by main() -float rw_scale; // size of the drops (param rain_scale) -float rw_since; // seconds since a blade last cleaned the place -float rw_period; // seconds between the small drops landing on a place of one -float rw_grow; // seconds the drops need after a wipe to grow big enough to slide -float rw_rate; // how fast the glass gathers the rain against a standing vertical glass in the heaviest rain -float rw_push; // the force on a drop along the glass, in units of its weight -vec2 rw_down; // the way gravity pulls along the glass (coordinates of the glass, unit) -vec2 rw_flow; // the way the air goes along the glass (unit, 0 in still air) +// --- Micro droplets ------------------------------------------------------------- +const float micro_density = 0.45; // share of micro cells holding a droplet at full rain, 0 = off +const float micro_scale = 3.0; // micro grid = raindrop_grid_size * micro_scale +const float micro_size_min = 0.12; // droplet radius in micro cells +const float micro_size_max = 0.40; +const float micro_bulge = 0.80; // slope of the droplet dome at its rim (0..0.95) +const float micro_life = 60.0; // average seconds a droplet lives -// the field of the water: the sum of the kernels, its gradient along the glass (view space) and the sums for the mean radius of -// the drops it is made of -float rw_field = 0.0; -vec3 rw_fgrad = vec3(0.0); -float rw_fsize = 0.0; -float rw_fweight = 0.0; +// --- Look of the drops (grey atlas for drops / rivulets, the same look computed for micro droplets) --------- +const float drop_rim_start = 0.30; // micro droplets: dome slope (1 - nz) where the bright rim starts +const float drop_rim_end = 0.80; // ... and where it is fully bright +const float drop_light_side = 0.25; // micro droplets: brighter on the upper-left side +const float drop_center_alpha = 0.25; // how much the dark middle of a drop covers the scene +const float drop_rim_alpha = 0.85; // how much the bright rim covers the scene +const float drop_shade_alpha = 0.30; // faint alpha over the whole dome (carries the glints) -// the water at the fragment: the thickness of the highest water there (metres), its gradient (view space), the radius of the -// curvature of its surface (metres: how much it bends the view across a pixel) and how much of the pixel it covers -float rw_height = 0.0; -vec3 rw_slope = vec3(0.0); -float rw_curve = 1.0; -float rw_cover = 0.0; -// from the middle of the drop which gives the water to the fragment (view space, metres), 0 for spread water -vec3 rw_offset = vec3(0.0); -// the last time the water a blade pushes went over the fragment, taking the drops lying there with it -float rw_cleared = -1.0e9; +// --- Light on the drops -------------------------------------------------------- +const float drop_ior = 1.33; // refraction index of water +const float drop_refract = 0.5; // rivulets: strength of the picture shift (Snell; 1 = physical) +const float drop_lens = 2.0; // drops: lens field, the drop shows (1 + drop_lens) x its own size, flipped +const float drop_lens_mix = 0.7; // drops: 1 = lens picture, 0 = Snell shift like the rivulets +const float drop_env = 0.6; // reflection of the environment on the dome (0 = off) +const float drop_glint_strength = 5.0; // sun / moon glint brightness +const float drop_glint_sharpness = 40.0; // sun / moon glint size (lower = a wider lobe, so more drops catch it) +const float drop_sheen = 0.3; // wide, soft sun sheen on the domes around the sharp glint +const float drop_headlight_scatter = 3.0; // how much drops light up in headlight beams +const float drop_lamp_scatter = 1.0; // GL 4.6: how much drops light up from lamps (station lamps, signals), 0 = off +const float drop_light_near = 4.0; // lights nearer than this (metres; the own vehicle) don't light the drops, full from 2x +const float drop_light_max = 3.0; +const float drop_dark_lum = 0.25; // average brightness of the screen (scene units) below which the drops darken with it // the most the lamps and headlights add to a drop (scene units, before tonemapping) -uvec4 rw_pcg4d(uvec4 v) +// --- Rivulets (drops that run down and leave a wet trail) --------------------------------- +// Sizes are in "drop cells" (1 cell = 1 / raindrop_grid_size of the glass UV). +const float streak_density = 1.00; // share of cells carrying a rivulet (scaled by the rain intensity), 0 = off +const float streak_cell = 6.0; // width of a rivulet cell in drop cells +const float streak_run = 20.0; // height of a rivulet cell in drop cells = the longest run of one rivulet +const float streak_head = 1.7; // mean width of the drop head, in drop cells (randomised 0.75x .. 1.25x) +const float streak_period = 40.0; // seconds a rivulet lives (it runs for ~90% of that and then fades out), average +const float streak_wiggle = 0.35; // how far the path swings sideways, in head widths (0 = straight) +const float streak_wiggle_speed = 0.5; // speed of the little waves that flow down the trail +const float streak_flow = 0.15; // ripples flowing down inside the trail (shows in refraction and glints), 0 = off +const float streak_uv_aspect = 1.0; // glass width / height in UV terms (1 = same stretch as the drops) +const float streak_sweep = 1.0; // 1 = the head sweeps up drops on its way (clean band behind it), 0 = off +const float streak_sweep_width = 0.9; // width of the swept band, in head widths +const float streak_link = 1.5; // head widths above the head where the trail is taken from the sprite part + // that touches the head (so the trail always leaves the head cleanly) + +// --- Speed: the air against the vehicle (rain_wind) drives the water on the glass -------------------- +// The force on the water along the glass: its weight (gravity) and the drag of the air going along the glass (and of the +// share of the air meeting it head on which turns up along it), as in the stock shader of the renderer. Standing still +// (or in a light wind) nothing of it shows: the rain lands, grows and runs down as it always did. +const float wind_drag_gain = 4.0; // how strongly the air drives the water (1 = the drag of the stock shader: on a + // vertical front glass the water would go up only at ~250 km/h) +const float wind_streaks = 3.0; // density of the rivulets driven by the air, at full drag (x streak_density) +const float wind_cell_scale = 0.36; // the rivulets of the air: their cells this much narrower ... +const float wind_run_scale = 0.28; // ... and shorter than those of gravity: many small drops with short trails +const float wind_head_scale = 0.55; // their heads this much smaller +const int wind_layers = 4; // layers of them, each with drops of its own (1 .. 4) +const float wind_long_run = 1.6; // the last layer: its trails this much longer than those of gravity (the long ones, a part of all) +const float wind_streak_period = 14.0; // seconds a rivulet driven by the air lives (they run faster than the ones of gravity) +const float drop_wind_stretch = 0.4; // drops are stretched up to this much along the push of the air (0 = off) +const float WS_DRAG_SPEED = 24.0; // speed of the air along the glass at which its drag equals the weight of a drop, m/s +const float WS_HEAD_ON = 0.35; // share of the air meeting the glass head on which turns up along it +const float WS_WIND_STEP = 0.1309; // the direction of the rivulets of the air in steps of 7.5 degrees (no seams on a + // curved glass, where every triangle would turn them a little) + +#ifndef STREAK_FLIP_Y +#define STREAK_FLIP_Y 0 // set to 1 if the rivulets run UP the glass (head on top) +#endif +const float STREAK_TAIL_SCALE = 1.5; // the trail pattern of the sprite is drawn this much longer than native +const float STREAK_HEAD_FRAC = 0.22; // part of the sprite height used by the drop head (= HEAD_FRAC of the atlas generator) + +const float WS_INSIDE = 0.3; // metres beyond the glass nearer than which the image is taken for the inside of the cab + // (in the rain the cab isn't in the depth: the nose of the own vehicle is outside) +const float WS_REFR_MAXPX = 96.0; // largest picture shift of a drop, screen pixels +const float WS_REFR_MIX = 0.85; // 0 = no refraction, 1 = only the refracted picture +const float WS_LIGHT_GAIN = 1.0; // brightness of the lights near a drop shown in it (0 = off) +const float WS_LIGHT_CONTRAST = 3.0; // a light: this many times brighter than the place around it + +const vec3 DROP_LIGHT = vec3(-0.5527, 0.6532, 0.5226); // same light as the atlas generator (upper left) + +// the surroundings in a view space direction where the image doesn't hold them: the environment map above the horizon, +// the ground below it, blurred by Lod (as in the stock mat_rain_windscreen.frag) +vec3 wsSurroundings(vec3 direction, float lod) { - v = v * 1664525u + 1013904223u; - v.x += v.y * v.w; - v.y += v.z * v.x; - v.z += v.x * v.y; - v.w += v.y * v.z; - v ^= v >> 16u; - v.x += v.y * v.w; - v.y += v.z * v.x; - v.z += v.x * v.y; - v.w += v.y * v.z; - return v; + vec3 world = mat3(inv_view) * direction; + vec3 sky = envmap_sample_rough(normalize(vec3(world.x, max(world.y, 0.0), world.z)), clamp(lod / 8.0, 0.0, 1.0)); + float below = smoothstep(-0.03 - 0.05 * lod, 0.25 + 0.05 * lod, -world.y); + if ((below <= 0.0) || (false == ENVMAP_ENABLED)) + return sky; + return mix(sky, reflection_ground(), below); } -// four numbers 0 .. 1 of a cell of a layer -vec4 rw_random(ivec2 cell, uint layer, uint index) +// what is seen through the glass in a view space direction: the image of the last frame where it holds the place, Distance +// away along the direction (0: far), blurred by Lod; Share: how much of it the image gave. Fade: towards the edges of the +// image the surroundings take over. The inside of the cab (near the camera in the depth) is never taken: the surroundings +// stand for it (else the drops would show the dark walls of the cab) +vec3 wsBehind(vec3 direction, float lod, float distance, out float share, bool fade) { - return vec4(rw_pcg4d(uvec4(uvec2(cell), layer, index))) * (1.0 / 4294967296.0); + share = 0.0; + vec3 around = wsSurroundings(direction, lod); + if (ssr_params.x < 1.0) + return around; + vec4 previous = ssr_reprojection * ((distance > 0.0) ? vec4(direction * distance, 1.0) : vec4(direction, 0.0)); + if (previous.w <= 1e-5) + return around; + vec2 coords = (previous.xy / previous.w) * 0.5 + 0.5; + vec2 edges = min(coords, 1.0 - coords); + share = fade ? smoothstep(0.0, 0.04, min(edges.x, edges.y)) : step(-0.02, min(edges.x, edges.y)); + coords = clamp(coords, vec2(0.0), vec2(1.0)); + if (share <= 0.0) + return around; + ivec2 size = textureSize(scene_depth, 0); + float depth = texelFetch(scene_depth, clamp(ivec2(coords * vec2(size)), ivec2(0), size - 1), 0).r; + float near = projection[3][2]; + if ((depth > 0.0) && (near / depth < -f_pos.z + WS_INSIDE)) + { + share = 0.0; + return around; + } + vec3 color = textureLod(ssr_history, coords, clamp(lod, 0.0, ssr_params2.x)).rgb; + if (any(isnan(color)) || any(isinf(color))) + { + share = 0.0; + return around; + } + return mix(around, max(color, vec3(0.0)), share); } -float rw_noise(float x, uint layer) +float wsLum(vec3 c) { - float i = floor(x); - float f = x - i; - float a = rw_random(ivec2(int(i), 0), layer, 7u).x; - float b = rw_random(ivec2(int(i) + 1, 0), layer, 7u).x; - return mix(a, b, f * f * (3.0 - 2.0 * f)); + return dot(c, vec3(0.2126, 0.7152, 0.0722)); } -// value noise 0 .. 1 (x) with its gradient (yz) -vec3 rw_noise2(vec2 p, uint layer) +// bright lights near a drop (signals, lamps, headlights): a drop is a wide-angle lens and picks them up. A light is where a +// fine mip level of the image (~11 px around) is much brighter than a coarse one (~90 px around) +vec3 wsLightGlow(vec3 direction, float distance) { - vec2 i = floor(p); - vec2 f = p - i; - vec2 u = f * f * (3.0 - 2.0 * f); - vec2 du = 6.0 * f * (1.0 - f); - ivec2 c = ivec2(i); - float a = rw_random(c, layer, 8u).x; - float b = rw_random(c + ivec2(1, 0), layer, 8u).x; - float d = rw_random(c + ivec2(0, 1), layer, 8u).x; - float e = rw_random(c + ivec2(1, 1), layer, 8u).x; - float k1 = b - a; - float k2 = d - a; - float k4 = a - b - d + e; - return vec3(a + k1 * u.x + k2 * u.y + k4 * u.x * u.y, du * vec2(k1 + k4 * u.y, k2 + k4 * u.x)); -} - -// P turned by A (radians). every set of drops is laid on its own grid, turned and shifted against the others, so the drops line -// up neither with each other nor along the glass -vec2 rw_turn(vec2 p, float a) -{ - float c = cos(a); - float s = sin(a); - return vec2(c * p.x - s * p.y, s * p.x + c * p.y); -} - -// a gradient given along the coordinates of the glass, view space -vec3 rw_along(vec2 gradient) -{ - return rw_tu * (gradient.x / dot(rw_tu, rw_tu)) + rw_tv * (gradient.y / dot(rw_tv, rw_tv)); -} - -// the gradient along the glass (view space) of a value of the fragments, from how it changes from pixel to pixel; Dpdx, Dpdy: -// the steps of the position, Normal: of the glass -vec3 rw_gradient(float value, vec3 dpdx, vec3 dpdy, vec3 normal) -{ - vec3 r1 = cross(dpdy, normal); - vec3 r2 = cross(normal, dpdx); - float det = dot(dpdx, r1); - float dx = dFdx(value); - float dy = dFdy(value); - return (abs(det) > 1e-14) ? (dx * r1 + dy * r2) / det : vec3(0.0); -} - -// a kernel of the water, Offset (view space) from its centre to the fragment: alone it makes water of the radius Visible, -// Weight 1 .. 0 as it goes. water smaller than a pixel would only flicker, it is left to the haze of the wet glass -void rw_kernel(vec3 offset, float visible, float weight) -{ - if ((weight <= 0.0) || (visible < 0.5 * rw_pixel)) - return; - // a drop a pixel or two across is grain rather than a lens: it fades into the haze of the wet glass - weight *= smoothstep(0.5 * rw_pixel, 2.0 * rw_pixel, visible); - float support = visible / RW_EDGE; - float q = dot(offset, offset) / (support * support); - if (q >= 1.0) - return; - float k = 1.0 - q; - float k3 = weight * k * k * k; - rw_field += k3; - rw_fgrad += offset * (-6.0 * weight * k * k / (support * support)); - rw_fsize += k3 * visible; - rw_fweight += k3; -} - -// a kernel at the Offset in the coordinates of the glass -void rw_blob(vec2 offset, float visible, float weight) -{ - rw_kernel(offset.x * rw_tu + offset.y * rw_tv, visible, weight); -} - -// a drop lying on the glass: a few kernels, sagging down the glass and lopsided as Shape (random 0 .. 1) says -void rw_drop(vec2 offset, float visible, float weight, vec4 shape) -{ - rw_blob(offset, visible, weight); - if (visible < 1.5 * rw_pixel) - return; - vec2 side = vec2(-rw_down.y, rw_down.x); - vec2 sag = (rw_down * (0.2 + 0.35 * shape.x) + side * ((shape.y - 0.5) * 0.7)) * visible; - rw_blob(offset - sag, visible * mix(0.6, 0.85, shape.z), weight); - if (shape.w > 0.4) - { - float angle = shape.w * 40.0; - rw_blob(offset - vec2(cos(angle), sin(angle)) * (0.6 * visible), visible * mix(0.4, 0.6, shape.x), weight); - } -} - -// water spread over the glass (a film, a ridge): its thickness, the gradient of it (view space), the radius of the curvature of -// its surface and how much of the pixel it covers -void rw_sheet(float thickness, vec3 slope, float curve, float cover) -{ - if (cover <= 0.0) - return; - rw_cover = max(rw_cover, cover); - if (thickness > rw_height) - { - rw_height = thickness; - rw_slope = slope; - rw_curve = curve; - rw_offset = vec3(0.0); - } -} - -// the surface of the water of the field: a drop is a cap of a sphere, flat lens of the contact angle Contact (radians) the water -// makes with the glass. how far across a drop the fragment is follows from the field (inverting the kernel), the height and -// the slope of the cap from that: the slope rises slowly from the middle and steeply only close to the edge, where it reaches -// the contact angle; where drops flowed together the field is above that of a drop alone and the water is flat. the edge is -// antialiased by how fast the field changes across a pixel -void rw_settle(float contact) -{ - if (rw_field <= 0.5 * RW_SURFACE) - return; - float gradient = length(rw_fgrad); - float cover = clamp((rw_field - RW_SURFACE) / max(gradient * rw_pixel, 1e-3) + 0.5, 0.0, 1.0); - if (cover <= 0.0) - return; - float mean = rw_fsize / max(rw_fweight, 1e-12); - // 0 in the middle of a drop, 1 at its edge - float across = min(sqrt(max(1.0 - pow(min(rw_field, 1.0), 1.0 / 3.0), 0.0)) / RW_EDGE, 1.0); - float s = sin(contact); - float rs = across * s; - float root = sqrt(max(1.0 - rs * rs, 1e-4)); - float sphere = mean / s; - vec3 slope = (gradient > 1e-9) ? rw_fgrad * ((rs / root) / gradient) : vec3(0.0); - float height = max(sphere * (root - cos(contact)), 0.0); - bool top = height > rw_height; - rw_sheet(height, slope, sphere, cover); - // the field rises towards the middle of the drop - if (top && (gradient > 1e-9)) - rw_offset = rw_fgrad * (-across * mean / gradient); -} - -// the blades. a channel of the mask of the wipers is a blade: 0 where it doesn't reach, elsewhere the place of the blade over its -// sweep (0 at rest .. 1 at the far end) at which it goes over the place. wiper_pos: where the blade is (0 .. 1 on its way out, -// 1 + where it is on its way back), wiper_timer_out / _return: the last time it lay at its start / was at its far end -struct rw_wipe_s -{ - float since; // seconds since a blade last went over the place (large where none reaches) - float ahead; // 0 .. 1, how close in front of a moving blade the place is (the water the blade pushes) - float front; // how far in front of the nearest moving blade the place is, units of the mask (1 where none) - float swept; // 0 .. 1, how much of its way the blade in front did, the water it gathered on the way - float working; // 0 .. 1, the blades went lately -}; - -rw_wipe_s rw_wipe(vec4 mask) -{ - rw_wipe_s wipe = rw_wipe_s(1.0e4, 0.0, 1.0, 0.0, 0.0); - for (int i = 0; i < 4; ++i) - { - float m = mask[i]; - if (m < 0.001) - continue; - float pos = wiper_pos[i]; - bool back = pos > 1.0; - float blade = back ? pos - 1.0 : pos; - float t0 = wiper_timer_out[i]; - float t1 = wiper_timer_return[i]; - // when the blade went over the place last: on this stroke, the blade moving at an even pace from its end, or on the - // stroke before, which took as long as the time between the ends (if the blade lay at its end longer, two seconds) - float pass; - float front; // how far in front of the blade the place is (units of the mask), below 0 behind it - if (back) - { - pass = (m >= blade) ? t1 + (time - t1) * ((1.0 - m) / max(1.0 - blade, 1e-3)) : t0 + m * clamp(t1 - t0, 0.0, 2.0); - front = blade - m; - } - else - { - pass = (m <= blade) ? t0 + (time - t0) * (m / max(blade, 1e-3)) : t1 + (1.0 - m) * clamp(t0 - t1, 0.0, 2.0); - front = m - blade; - } - wipe.since = min(wipe.since, max(time - pass, 0.0)); - float moving = smoothstep(0.0, 0.03, blade) * smoothstep(1.0, 0.97, blade); - float ahead = (front > 0.0) ? (1.0 - smoothstep(0.0, 0.035, front)) * moving : 0.0; - wipe.ahead = max(wipe.ahead, ahead); - if ((front > 0.0) && (moving > 0.5)) - wipe.front = min(wipe.front, front); - wipe.swept = max(wipe.swept, ahead * (back ? 1.0 - blade : blade)); - float working = 1.0 - smoothstep(4.0, 30.0, time - t1); - wipe.working = max(wipe.working, working); - } - return wipe; -} - -// a place of the glass a blade reaches -bool rw_reached(vec2 coords) -{ - return any(greaterThanEqual(textureLod(wipermask, clamp(coords, vec2(0.0), vec2(1.0)), 0.0), vec4(0.001))); -} - -// the edge of the sweep of the blades, where they push the water out to: 0 where a blade reaches, else the share of the places -// around at Reach (metres along the glass) which a blade reaches. found from where the blades reach and not from the values of -// the mask, which may stay at the end of the sweep over a wide part of the glass. Maskstep: the coordinates of the mask for a -// step along the glass -float rw_rim(vec2 coords, float reach, mat2 maskstep) -{ - if (rw_reached(coords)) - return 0.0; - float inside = 0.0; - for (int k = 0; k < 6; ++k) - { - float angle = float(k) * (RW_PI / 3.0); - inside += rw_reached(coords + maskstep * (vec2(cos(angle), sin(angle)) * reach)) ? 1.0 : 0.0; - } - return inside / 6.0; -} - -// whether the edge of the sweep of the blades is within Reach of the place -bool rw_border(vec2 coords, float reach, mat2 maskstep) -{ - bool here = rw_reached(coords); - for (int k = 0; k < 6; ++k) - { - float angle = float(k) * (RW_PI / 3.0); - if (rw_reached(coords + maskstep * (vec2(cos(angle), sin(angle)) * reach)) != here) - return true; - } - return false; -} - -// how far along its way a sliding drop is at the share T of the time it takes: it stops and goes, the more smoothly the harder -// it is pushed -float rw_stickslip(float t, float seed) -{ - t = clamp(t, 0.0, 1.0); - float s = t * 3.0; - float i = floor(s); - float stuck = (i + smoothstep(0.25 + 0.4 * seed, 1.0, s - i)) / 3.0; - return mix(stuck, t, smoothstep(0.8, 2.0, rw_push)); -} - -// the track of the water down a column of the glass (Column: its index, Width: of a column, Y: metres up the way): where it -// is across, metres. the water keeps to the way wetted before, so every drop of a column goes the same way, wavy, with kinks -// where the glass held it -float rw_path(int column, float y, float width, uint layer) -{ - float slow = rw_noise(y / (0.05 * rw_scale) + float(column) * 7.31, layer) - 0.5; - float k = y / (0.008 * rw_scale); - float i = floor(k); - float a = rw_random(ivec2(column, int(i)), layer + 500u, 3u).x; - float b = rw_random(ivec2(column, int(i) + 1), layer + 500u, 3u).x; - float kinks = mix(a, b, smoothstep(0.15, 0.85, k - i)) - 0.5; - return (float(column) + 0.5 + 0.4 * slow + 0.2 * kinks) * width; -} - -// the drops which grew big enough to slide, and the streams they leave: Q the place across and up the way they go (Side, Down: -// those directions in the coordinates of the glass), Share of them going this way. a column of the glass carries the water of -// a track; a drop starts somewhere in a cell of the column now and then, slides down with stops, thinning, and leaves a stream -// which drains into beads and dries -void rw_sliders(vec2 q, vec2 side, vec2 down, uint layer, float share) -{ - float width = 0.04 * rw_scale; - float height = 0.15 * rw_scale; - int column = int(floor(q.x / width)); - int row = int(floor(q.y / height)); - vec4 a = rw_random(ivec2(column, 7), layer, 0u); - if (a.x > share * mix(0.35, 0.9, clamp(rw_rate / 3.0, 0.0, 1.0))) - return; - float speed = clamp(0.035 + 0.06 * (rw_push - 0.4) + 0.3 * max(rw_push - 1.5, 0.0), 0.01, 0.8); - float period = clamp(25.0 / rw_rate, 3.0, 60.0); - float trail = 0.0; - for (int r = 0; r < 3; ++r) - { - ivec2 cell = ivec2(column, row + r); - vec4 b = rw_random(cell, layer, 1u); - float span = period * mix(0.7, 1.3, b.x); - float now = floor(time / span + b.y); - for (int k = 0; k < 2; ++k) - { - float cycle = now - float(k); - float start = (cycle - b.y) * span; - float t = time - start; - // the drop gathered from the drops landed since the last wipe - if ((t < 0.0) || (rw_since - t < rw_grow)) - continue; - vec4 c = rw_random(cell, layer + 1000u, uint(int(cycle) + 1000000)); - float top = (float(cell.y) + 0.8 - 0.6 * c.x) * height; - float travel = mix(0.06, 0.28, c.y) * rw_scale; - float v = speed * mix(0.7, 1.3, c.z); - float gather = 0.6; - float moved = travel * rw_stickslip((t - gather) * v / travel, c.w); - float y = top - moved; - float radius = mix(0.003, 0.0042, c.w) * rw_scale * (1.0 - 0.35 * moved / travel) * mix(0.6, 1.0, smoothstep(0.0, gather, t)); - // at the end of its way what is left of it stays and flows out into the stream - float body = 1.0 - smoothstep(0.0, 1.5, t - gather - travel / v); - if ((body > 0.0) && (abs(q.y - y) < 3.5 * radius)) - { - vec2 o = vec2(q.x - rw_path(column, y, width, layer), q.y - y); - rw_blob(side * o.x - down * o.y, radius, body); - // its rear up the stream: a corner, drawn out into a cusp the faster it goes (the front stays round) - float drawn = clamp(v * 5.0, 0.0, 1.5); - for (int k = 1; k <= 2; ++k) - { - float yt = y + radius * (0.45 + 0.5 * drawn) * float(k); - vec2 ot = vec2(q.x - rw_path(column, yt, width, layer), q.y - yt); - rw_blob(side * ot.x - down * ot.y, radius * ((k == 1) ? 0.7 : 0.42), body); - } - } - if ((moved > 0.0) && (q.y > y) && (q.y < top)) - { - float age = t - gather - (top - q.y) / v; - if ((age >= 0.0) && (age < rw_since)) - { - // fresh, the stream is whole; draining, it breaks into beads, which dry - float beads = rw_noise(q.y / (0.004 * rw_scale), layer + 9u); - float wet = mix(1.15, 0.2 + 1.0 * beads, smoothstep(0.0, 15.0, age)) * (1.0 - smoothstep(30.0, 60.0, age)); - trail = max(trail, wet); - } - } - } - } - if (trail > 0.0) - { - float across = q.x - rw_path(column, q.y, width, layer); - float half_width = mix(0.0005, 0.0011, a.y) * rw_scale * (0.6 + 0.8 * rw_noise(q.y / (0.006 * rw_scale), layer + 11u)); - rw_blob(side * across, half_width, trail); - } -} - -// a drop lying on the glass, as rw_drop() with the directions along the glass given in the view space (Down: the way gravity -// pulls along the glass, Side across it) -void rw_drop_view(vec3 offset, float visible, float weight, vec4 shape, vec3 down, vec3 side) -{ - rw_kernel(offset, visible, weight); - if (visible < 1.5 * rw_pixel) - return; - vec3 sag = (down * (0.2 + 0.35 * shape.x) + side * ((shape.y - 0.5) * 0.7)) * visible; - rw_kernel(offset - sag, visible * mix(0.6, 0.85, shape.z), weight); - if (shape.w > 0.4) - { - float angle = shape.w * 40.0; - rw_kernel(offset - (cos(angle) * side + sin(angle) * down) * (0.6 * visible), visible * mix(0.4, 0.6, shape.x), weight); - } -} - -// the water the simulation keeps on the glass (gfx::windscreen_water, water.glsl), where the material is a glass of the cab of the -// train: the drops listed by the cell of the grid the fragment is in. Slot: of the glass, Uv: the coordinates of the fragment, -// Puv: the view space step along the glass for a step of the uv; Down, Side: along the glass. a sliding drop is drawn out behind -// itself into a cusp, the faster the longer; one lying is lopsided and sags down the glass; a flake of snow is lace, grey and -// clear as it melts (Snowcover, Wet: as the flakes of rw_snow()) -void rw_simulated(uint slot, vec2 uv, mat2x3 puv, vec3 down, vec3 side, inout float snowcover, inout float wet) -{ - uint base = water_grid_base(slot); - uint cell = water_cell(uv); - uint count = min(water_cells[base + cell], uint(WATER_CELL_DROPS)); - for (uint k = 0u; k < count; ++k) - { - uint place = water_cells[base + uint(WATER_GRID * WATER_GRID) + cell * uint(WATER_CELL_DROPS) + k]; - water_drop_s drop = water_drops[slot * uint(WATER_DROPS) + place]; - float volume = drop.place.z; - if (volume <= 0.0) - continue; - vec3 offset = puv * (uv - drop.place.xy); - vec4 shape = vec4(rw_pcg4d(uvec4(place, slot, 41u, 0u))) * (1.0 / 4294967296.0); - if (drop.motion.w < 1.0) - { - // a flake: lobed lace, shrinking, grey and clear as it melts - float m = drop.motion.w; - vec2 flat2 = vec2(dot(offset, side), dot(offset, down)); - float radius = 0.5 * water_flake(volume); - float dist = length(flat2); - if (dist < radius + rw_pixel) - { - float angle = atan(flat2.y, flat2.x); - float lobes = 0.55 + 0.45 * (0.6 * rw_noise(angle * 1.9 + shape.z * 40.0, 13u) + 0.4 * abs(cos(3.0 * angle + shape.w * 6.2831853))); - float rim = radius * lobes * (1.0 - 0.45 * m); - float body = smoothstep(rim + rw_pixel, 0.55 * rim - rw_pixel, dist); - float lace = rw_noise2(flat2 / 0.0007 + shape.zw * 100.0, 14u).x; - float flake = body * mix(0.55, 1.0, lace) * (1.0 - 0.7 * m * m); - snowcover = 1.0 - (1.0 - snowcover) * (1.0 - flake); - wet = max(wet, m * body); - } - continue; - } - float radius = water_radius(volume); - vec3 velocity = puv * drop.motion.xy; - float speed = length(velocity); - if (speed > 0.002) - { - // its rear up the way it came: a corner, drawn out into a cusp the faster it goes (the front stays round) - vec3 way = velocity / speed; - rw_kernel(offset, radius, 1.0); - float drawn = clamp(speed * 5.0, 0.0, 1.5); - for (int t = 1; t <= 2; ++t) - rw_kernel(offset + way * (radius * (0.45 + 0.5 * drawn) * float(t)), radius * ((t == 1) ? 0.7 : 0.42), 1.0); - } - else - { - rw_drop_view(offset, radius, 1.0, shape, down, side); - } - } -} - -// how fresh the wetted paths of the simulation are at a place of the glass (x) and how that changes along u and v (yz): the -// texels of their map filtered by a cubic b-spline over 4 x 4 of them, so the edges of a path are smooth curves and its slopes -// change smoothly (a bilinear filter would leave steps at every texel in the bending of the view) -vec3 rw_trail(uint slot, vec2 uv, float now) -{ - // a path stays wet (and seen) longer than the drops keep to it - float lasting = 25.0; - vec2 p = uv * float(WATER_TRAIL) - 0.5; - vec2 i = floor(p); - vec2 f = p - i; - // the weights of the b-spline and their derivatives, for the texels i - 1 .. i + 2 - vec2 g = 1.0 - f; - vec4 wx = vec4(g.x * g.x * g.x, 3.0 * f.x * f.x * f.x - 6.0 * f.x * f.x + 4.0, -3.0 * f.x * f.x * f.x + 3.0 * f.x * f.x + 3.0 * f.x + 1.0, f.x * f.x * f.x) / 6.0; - vec4 wy = vec4(g.y * g.y * g.y, 3.0 * f.y * f.y * f.y - 6.0 * f.y * f.y + 4.0, -3.0 * f.y * f.y * f.y + 3.0 * f.y * f.y + 3.0 * f.y + 1.0, f.y * f.y * f.y) / 6.0; - vec4 dx = vec4(-g.x * g.x, 3.0 * f.x * f.x - 4.0 * f.x, -3.0 * f.x * f.x + 2.0 * f.x + 1.0, f.x * f.x) * 0.5; - vec4 dy = vec4(-g.y * g.y, 3.0 * f.y * f.y - 4.0 * f.y, -3.0 * f.y * f.y + 2.0 * f.y + 1.0, f.y * f.y) * 0.5; - vec3 result = vec3(0.0); - ivec2 base = ivec2(i) - 1; - for (int y = 0; y < 4; ++y) - { - for (int x = 0; x < 4; ++x) - { - float value = water_wetted(slot, base + ivec2(x, y), now, lasting); - result += value * vec3(wx[x] * wy[y], dx[x] * wy[y], wx[x] * dy[y]); - } - } - result.yz *= float(WATER_TRAIL); - return result; -} - -// the surroundings in a view space direction where the screen doesn't hold them: the environment map above the horizon (the sky -// and the clouds), the ground below it, blurred by Lod -vec3 rw_surroundings(vec3 direction, float lod) -{ - vec3 world = mat3(inv_view) * direction; - vec3 sky = envmap_sample_rough(normalize(vec3(world.x, max(world.y, 0.0), world.z)), clamp(lod / 8.0, 0.0, 1.0)); - // the horizon as blurred as the view is - float below = smoothstep(-0.03 - 0.05 * lod, 0.25 + 0.05 * lod, -world.y); - if ((below <= 0.0) || (false == ENVMAP_ENABLED)) - return sky; - return mix(sky, reflection_ground(), below); -} - -// what is seen through the glass in a view space direction: the image of the last frame (the screen space reflections keep it) -// where it holds the place, Distance away along the direction (0: far), blurred by Lod; Share: how much of it the image gave. -// Fade: towards the edges of the image the surroundings take over (else the edges are stretched) -vec3 rw_behind_edges(vec3 direction, float lod, float distance, out float share, bool fade) -{ - share = 0.0; - vec3 around = rw_surroundings(direction, lod); - if (ssr_params.x < 1.0) - return around; - vec4 previous = ssr_reprojection * ((distance > 0.0) ? vec4(direction * distance, 1.0) : vec4(direction, 0.0)); - if (previous.w <= 1e-5) - return around; - vec2 coords = (previous.xy / previous.w) * 0.5 + 0.5; - vec2 edges = min(coords, 1.0 - coords); - share = fade ? smoothstep(0.0, 0.04, min(edges.x, edges.y)) : step(-0.02, min(edges.x, edges.y)); - coords = clamp(coords, vec2(0.0), vec2(1.0)); - if (share <= 0.0) - return around; - // the view out through the water goes on outside, where the image shows the inside of the cab around the windows the - // surroundings stand for it (else the drops show the dark walls and roof of the cab) - ivec2 size = textureSize(scene_depth, 0); - float depth = texelFetch(scene_depth, clamp(ivec2(coords * vec2(size)), ivec2(0), size - 1), 0).r; - float near = projection[3][2]; - if ((depth > 0.0) && (near / depth < -f_pos.z + 2.5)) - { - share = 0.0; - return around; - } - vec3 color = textureLod(ssr_history, coords, clamp(lod, 0.0, ssr_params2.x)).rgb; - if (any(isnan(color)) || any(isinf(color))) - { - share = 0.0; - return around; - } - return mix(around, max(color, vec3(0.0)), share); -} - -vec3 rw_behind(vec3 direction, float lod, float distance, out float share) -{ - return rw_behind_edges(direction, lod, distance, share, true); + vec4 previous = ssr_reprojection * ((distance > 0.0) ? vec4(direction * distance, 1.0) : vec4(direction, 0.0)); + if (previous.w <= 1e-5) + return vec3(0.0); + vec2 coords = clamp((previous.xy / previous.w) * 0.5 + 0.5, vec2(0.0), vec2(1.0)); + vec3 near = textureLod(ssr_history, coords, min(3.5, ssr_params2.x)).rgb; + vec3 wide = textureLod(ssr_history, coords, min(6.5, ssr_params2.x)).rgb; + if (any(isnan(near)) || any(isinf(near)) || any(isnan(wide)) || any(isinf(wide))) + return vec3(0.0); + vec3 excess = max(near - wide * WS_LIGHT_CONTRAST, vec3(0.0)); + return min(excess, vec3(30.0)) * (2.0 * WS_LIGHT_GAIN); } // a layer Over put over Under, the colours not premultiplied -vec4 rw_over(vec4 over, vec4 under) +vec4 wsOver(vec4 over, vec4 under) { - float alpha = over.a + under.a * (1.0 - over.a); - if (alpha <= 1e-5) - return vec4(0.0); - return vec4((over.rgb * over.a + under.rgb * under.a * (1.0 - over.a)) / alpha, alpha); + float alpha = over.a + under.a * (1.0 - over.a); + if (alpha <= 1e-5) + return vec4(0.0); + return vec4((over.rgb * over.a + under.rgb * under.a * (1.0 - over.a)) / alpha, alpha); +} + +// =========================================================================== +float GetMixFactor(in vec2 co, out float side); + +uvec2 cellKey(vec2 c); + +vec2 tileOffset(float choice) +{ + if (choice < 0.25) return vec2(0.0, 0.0); + else if (choice < 0.5) return vec2(0.5, 0.0); + else if (choice < 0.75) return vec2(0.0, 0.5); + return vec2(0.5, 0.5); +} + +// the 2x2 drop tiles live in the left half of the atlas: a tile is 0.25 wide and 0.5 high in atlas UV +vec2 dropAtlasUV(float choice, vec2 uv) +{ + vec2 off = tileOffset(choice); + return vec2((off.x + uv.x * 0.5) * 0.5, off.y + uv.y * 0.5); +} + +uvec2 cellKey(vec2 c) +{ + return uvec2(ivec2(c) + ivec2(65536)); +} + +// --- one rivulet cell ------------------------------------------------------------ +struct Riv +{ + bool on; + float life; // 0..1 (fade in / out) + float width; // sprite width = head width (glass UV) + float headH; // head height (glass UV) + float topY; // where the trail starts (fixed on the glass) + float bottom; // bottom of the head now + float left; // left edge of the sprite + float flip; + float col; // which of the 4 sprites + float wipe; + float wavK, wavPh, wavSp; +}; + +// the layer of rivulets being worked on: the one of gravity (the rivulets as they always were, coordinates = glass UV with v +// up) or the one of the air (its own cells and seeds, turned so that its rivulets run along the push of the air) +float wsLayerDensity = 1.0; // x rain x streak_density: share of the cells holding a rivulet +float wsLayerPeriod = streak_period; +uint wsLayerSalt = 91u; +float wsLayerHead = 1.0; // x streak_head +float wsLayerCos = 1.0; // the layer is turned by this angle (its "down" is the way its water runs on the glass) +float wsLayerSin = 0.0; + +// glass UV (v up) -> coordinates of the layer, where the rivulets run down (-v) +vec2 wsToLayerDir(vec2 v) +{ + return vec2(wsLayerCos * v.x + wsLayerSin * v.y, -wsLayerSin * v.x + wsLayerCos * v.y); +} +vec2 wsToLayer(vec2 g) +{ + return wsToLayerDir(g - 0.5) + 0.5; +} +vec2 wsFromLayerDir(vec2 v) +{ + return vec2(wsLayerCos * v.x - wsLayerSin * v.y, wsLayerSin * v.x + wsLayerCos * v.y); +} +vec2 wsFromLayer(vec2 p) +{ + return wsFromLayerDir(p - 0.5) + 0.5; +} + +// the layers: 0 gravity, 1 air. WindShare: how much the air drives the water (0 standing still), WindCos / WindSin: the turn +// of the layer of the air +float wsWindShare = 0.0; +float wsWindCos = 1.0; +float wsWindSin = 0.0; +void wsSetLayer(int layer) +{ + if (layer == 0) + { + wsLayerDensity = 1.0 - wsWindShare; + wsLayerPeriod = streak_period; + wsLayerSalt = 91u; + wsLayerHead = 1.0; + wsLayerCos = 1.0; + wsLayerSin = 0.0; + } + else + { + wsLayerDensity = wsWindShare * wind_streaks; + wsLayerPeriod = wind_streak_period; + wsLayerSalt = 91u + 2u * uint(layer); + wsLayerHead = wind_head_scale; + wsLayerCos = wsWindCos; + wsLayerSin = wsWindSin; + } +} + +Riv getRiv(vec2 sCell, float sCW, float sCH, float gridSize) +{ + Riv r; + uint sSeed = Hash(uvec3(cellKey(sCell), wsLayerSalt)); + r.on = (RandF(sSeed) < rain_params.x * streak_density * wsLayerDensity); + float sPeriod = wsLayerPeriod * mix(0.6, 1.6, RandF(sSeed)); + float sPhase = fract(time / sPeriod + RandF(sSeed)); + r.life = smoothstep(0.0, 0.05, sPhase) * (1.0 - smoothstep(0.86, 1.0, sPhase)); + r.width = streak_head * wsLayerHead / gridSize * mix(0.75, 1.25, RandF(sSeed)); + r.headH = r.width * 0.88 * streak_uv_aspect; + float sSpan = max(sCH * mix(0.35, 0.70, RandF(sSeed)), r.headH * 3.0); + // stick-slip: the drop waits, then lurches forward; N waits on the way down + float sSteps = floor(mix(3.0, 8.0, RandF(sSeed))); + float sXs = clamp(sPhase / 0.88, 0.0, 1.0) * sSteps; + float sRun = clamp((floor(sXs) + smoothstep(0.55, 1.0, fract(sXs))) / sSteps, 0.0, 1.0); + r.topY = sCell.y * sCH + sSpan + RandF(sSeed) * max(sCH - sSpan, 0.0); + r.bottom = r.topY - r.headH * 1.2 - sRun * (sSpan - r.headH * 1.2); + const float sMargin = 0.8; + r.left = sCell.x * sCW + sMargin * r.width + RandF(sSeed) * max(sCW - r.width * (1.0 + 2.0 * sMargin), 0.0); + r.flip = (RandF(sSeed) < 0.5) ? 1.0 : 0.0; + r.col = floor(RandF(sSeed) * 4.0); + r.wipe = RandF(sSeed); + r.wavK = 6.2831853 / mix(2.5, 5.0, RandF(sSeed)); + r.wavPh = RandF(sSeed) * 6.2831853; + r.wavSp = streak_wiggle_speed * mix(0.6, 1.4, RandF(sSeed)); + return r; +} + +// sideways offset of the path (in head widths) at distance dW (head widths) down from the start of the trail +float rivWob(Riv r, float dW, out float ramp, out float wobD) +{ + float rampT = clamp(dW / 2.5, 0.0, 1.0); + ramp = rampT * rampT * (3.0 - 2.0 * rampT); + float rampD = 3.0 * rampT * (1.0 - rampT) / 2.5; + float a1 = dW * r.wavK + r.wavPh; + float a2 = dW * r.wavK * 1.7 - time * r.wavSp * 1.0472 + r.wavPh * 2.0; // the wave runs DOWN + float w1 = 0.7 * sin(a1) + 0.3 * sin(a2); + float w1D = 0.7 * cos(a1) * r.wavK + 0.3 * cos(a2) * r.wavK * 1.7; + wobD = -streak_wiggle * (rampD * w1 + ramp * w1D); + return streak_wiggle * ramp * w1; +} + +// how much a drop centred at p (glass UV, v up) with radius rad has been swept up by rivulet r (0..1) +float rivSwept(Riv r, vec2 p, float rad) +{ + if (!r.on || r.life <= 0.001) return 0.0; + if (p.y > r.topY || p.y < r.bottom - rad) return 0.0; + bool inHead = p.y < r.bottom + r.headH; + float dW = (r.topY - (inHead ? r.bottom + 0.5 * r.headH : p.y)) / r.width; + float ramp, wobD; + float wob = rivWob(r, dW, ramp, wobD); + float cx = r.left + (0.5 + wob) * r.width; + float halfW = 0.5 * streak_sweep_width * r.width; + return (1.0 - smoothstep(halfW, halfW + rad, abs(p.x - cx))) * r.life; +} + +// candidate on the glass that wins the pixel (the highest dome) +struct Hit +{ + float score; + float cov; // coverage of the dome (normal map alpha) + float colA; // coverage of the drawn drop (sharper) + vec3 n; // dome normal, tangent space of the glass + vec2 offUV; // pixel - centre (glass UV), for the lens + float radUV; // radius (glass UV) + float isDrop; // 1 = drop / droplet (lens), 0 = rivulet (Snell) + float vis; // life / sweep visibility + vec2 auv; // grey atlas lookup of the winner (drops, rivulets) + vec2 agx, agy; + float atlas; // 1 = shade from the grey atlas, 0 = analytic (micro droplets: shade in colA's place) + float shade; // analytic shade (micro droplets) +}; + +void consider(inout Hit h, float score, float cov, float colA, vec3 n, vec2 offUV, float radUV, float isDrop, + float vis, vec2 auv, vec2 agx, vec2 agy, float atlas, float shade) +{ + if (score > h.score) + { + h.score = score; h.cov = cov; h.colA = colA; h.n = n; + h.offUV = offUV; h.radUV = radUV; h.isDrop = isDrop; + h.vis = vis; h.auv = auv; h.agx = agx; h.agy = agy; h.atlas = atlas; h.shade = shade; + } +} + +// the rivulet R of the layer set (wsSetLayer) at the pixel, at SUVr in the coordinates of the layer; Rd1 / Rd2: their change +// per screen pixel +void drawRivulet(inout Hit hit, Riv r, vec2 sUVr, vec2 rd1, vec2 rd2) +{ + if (!(r.on && r.life > 0.001)) + return; + const float sMargin = 0.8; + float sLen = r.topY - r.bottom; + float sx = (sUVr.x - r.left) / r.width; + float sy = sUVr.y - r.bottom; + if (sx >= -sMargin && sx <= 1.0 + sMargin && sy >= 0.0 && sy <= sLen) + { + bool inHead = sy < r.headH; + float dW = (r.topY - (inHead ? r.bottom + 0.5 * r.headH : sUVr.y)) / r.width; + float ramp, wobD; + float wob = rivWob(r, dW, ramp, wobD); + if (inHead) wobD = 0.0; + float sxw = sx - wob; + if (sxw >= 0.0 && sxw <= 1.0) + { + float sSide; + vec2 sWipeUV = f_coord; + if (inHead) + { + sWipeUV = wsFromLayer(vec2(r.left + 0.5 * r.width, r.bottom + 0.5 * r.headH)); + if (STREAK_FLIP_Y != 0) sWipeUV.y = 1.0 - sWipeUV.y; + } + if (GetMixFactor(sWipeUV, sSide) >= mix(0.5, 1.0, r.wipe)) + { + float sNative = 3.125 * r.width * streak_uv_aspect * STREAK_TAIL_SCALE; + float sxs = mix(sxw, 1.0 - sxw, r.flip); + float su = 0.5 + (r.col + sxs) * 0.125; + vec2 sgx = vec2(0.125 / r.width * rd1.x, 0.0); + vec2 sgy = vec2(0.125 / r.width * rd2.x, 0.0); + vec4 sNm; + vec2 sAuv; + float vtSign = 1.0; + if (inHead) + { + float kv = STREAK_HEAD_FRAC / r.headH; + sgx.y = kv * rd1.y; sgy.y = kv * rd2.y; + sAuv = vec2(su, sy / r.headH * STREAK_HEAD_FRAC); + sNm = textureGrad(normalmap, sAuv, sgx, sgy); + } + else + { + float kv = (1.0 - STREAK_HEAD_FRAC) / sNative; + sgx.y = kv * rd1.y; sgy.y = kv * rd2.y; + // a) trail pattern fixed to the glass, tiled by mirroring (beads stay where they were left) + float dd = max(r.topY - sUVr.y, 0.0) / sNative; + float vt = abs(mod(dd, 2.0) - 1.0); + vtSign = (mod(dd, 2.0) < 1.0) ? 1.0 : -1.0; + // b) right above the head: the sprite part that touches the head + float above = (sy - r.headH) / r.width; // head widths above the head + float link = 1.0 - smoothstep(0.5 * streak_link, streak_link, above); + vec4 nGlass = vec4(0.0); + vec4 nLink = vec4(0.0); + vec2 uvGlass = vec2(su, STREAK_HEAD_FRAC + vt * (1.0 - STREAK_HEAD_FRAC)); + vec2 uvLink = vec2(su, STREAK_HEAD_FRAC + min((sy - r.headH) / sNative, 1.0) * (1.0 - STREAK_HEAD_FRAC)); + if (link < 0.999) + nGlass = textureGrad(normalmap, uvGlass, sgx, sgy); + if (link > 0.001) + nLink = textureGrad(normalmap, uvLink, sgx, sgy); + sAuv = (link > 0.5) ? uvLink : uvGlass; + sNm = mix(nGlass, nLink, link); + vtSign = mix(vtSign, 1.0, link); + } + + float sFade = inHead ? 1.0 : smoothstep(0.0, 1.5, dW); // the start of the trail melts into the glass + float sVis = r.life * sFade; + float sCov = smoothstep(0.1, 0.6, sNm.a) * sVis; + if (sCov > 0.001) + { + vec2 nxy = sNm.rg * 2.0 - 1.0; + if (r.flip > 0.5) nxy.x = -nxy.x; + if (STREAK_FLIP_Y != 0) nxy.y = -nxy.y; + float nz = sqrt(1.0 - clamp(dot(nxy, nxy), 0.0, 1.0)); + vec2 slope = -nxy / max(nz, 0.08); + if (!inHead) + slope.y = slope.y * vtSign / STREAK_TAIL_SCALE - slope.x * wobD + + streak_flow * ramp * sin(dW * 4.8 - time * 4.0); + // the slope of the layer to the one of the glass + if (STREAK_FLIP_Y != 0) slope.y = -slope.y; + slope = wsFromLayerDir(slope); + if (STREAK_FLIP_Y != 0) slope.y = -slope.y; + vec3 n = normalize(vec3(-slope, 1.0)); + float h = sNm.b * r.width * 0.5; + consider(hit, sCov * (h + 1e-5), sCov, 0.0, n, vec2(0.0), r.width * 0.5, 0.0, + sVis, sAuv, sgx, sgy, 1.0, 0.0); + } + } + } + } +} + +// how much of a drop centred at Cg (glass UV, v up) with radius Rad the rivulets of both layers have swept up (0..1 kept) +float wsKept(vec2 cg, float rad, Riv rivP, vec2 sCell, float sCW, float sCH, float gridSize) +{ + wsSetLayer(0); + vec2 rc = floor(cg / vec2(sCW, sCH)); + Riv rv = rivP; + if (rc != sCell) rv = getRiv(rc, sCW, sCH, gridSize); + float kept = 1.0 - streak_sweep * rivSwept(rv, cg, rad); + if (wsWindShare > 0.001) + { + wsSetLayer(1); + vec2 cw = wsToLayer(cg); + vec2 wc = vec2(sCW * wind_cell_scale, sCH * wind_run_scale); + Riv rw = getRiv(floor(cw / wc), wc.x, wc.y, gridSize); + kept *= 1.0 - streak_sweep * rivSwept(rw, cw, rad); + wsSetLayer(0); + } + return kept; +} + +// seconds since a wiper blade last went over Co (texture UV), from the timers of its strokes as GetMixFactor takes them; +// -1 where no wiper reaches +float wsWipeAge(vec2 co) +{ + vec4 movePhase = wiper_pos; + bvec4 is_out = lessThanEqual(movePhase, vec4(1.)); + movePhase = mix(vec4(2.) - movePhase, movePhase, is_out); + vec4 mask = textureLod(wipermask, co, 0.0); + vec4 maskVal = mix(1. - mask, mask, is_out); + vec4 passed = step(maskVal, movePhase); + vec4 sideV = mix(passed, vec4(1.) - passed, is_out); + vec4 ages = vec4(time) - mix(wiper_timer_out, wiper_timer_return, sideV); + float age = -1.0; + for (int i = 0; i < 4; ++i) + if ((mask[i] > 0.001) && ((age < 0.0) || (ages[i] < age))) + age = max(ages[i], 0.0); + return age; } void main() { - vec4 tex_color = texture(diffuse, f_coord); - vec4 mask = texture(wipermask, f_coord); + // ---- screen-space derivatives (before any non-uniform flow) ---- + float uvPerPx = max(length(dFdx(f_coord)), length(dFdy(f_coord))); + vec2 sxy = f_pos.xy / max(-f_pos.z, 1e-3); + float pxPerSlope = 1.0 / max(max(length(dFdx(sxy)), length(dFdy(sxy))), 1e-6); + vec3 Ngl = normalize(f_normal); + vec3 wsView = normalize(f_pos.xyz); // the view through the glass and its change per pixel (for the bent view) + vec3 wsDvx = dFdx(wsView); + vec3 wsDvy = dFdy(wsView); + vec3 dp1 = dFdx(f_pos.xyz); + vec3 dp2 = dFdy(f_pos.xyz); + vec2 duv1 = dFdx(f_coord); + vec2 duv2 = dFdy(f_coord); + vec3 dp2perp = cross(dp2, Ngl); + vec3 dp1perp = cross(Ngl, dp1); + vec3 Tgl = dp2perp * duv1.x + dp1perp * duv2.x; + vec3 Bgl = dp2perp * duv1.y + dp1perp * duv2.y; + float invmax = inversesqrt(max(max(dot(Tgl, Tgl), dot(Bgl, Bgl)), 1e-20)); + Tgl *= invmax; + Bgl *= invmax; + // glass UV offset -> screen pixels (inverse of the UV Jacobian), for the drop lens + mat2 Juv = mat2(duv1, duv2); + float detJ = determinant(Juv); + mat2 Jinv = (abs(detJ) > 1e-20) ? inverse(Juv) : mat2(0.0); - // the coordinates of the glass: metres along the axes of the model, so the water stays where it lies on the glass whatever the - // vehicle and the camera do. the axis of the model nearest to the vertical is up, the glass is projected along the - // horizontal one it faces most (along the vertical one if it lies flat) - mat3 linear = mat3(modelview); - mat3 rot = mat3(normalize(linear[0]), normalize(linear[1]), normalize(linear[2])); - mat3 unrot = transpose(rot); - vec3 local = unrot * (f_pos.xyz - modelview[3].xyz); - vec3 viewnormal = normalize(f_normal); - // the water is on the side away from the camera, the outside of the cab - vec3 outward = (dot(viewnormal, f_pos.xyz) < 0.0) ? -viewnormal : viewnormal; - vec3 normal = unrot * outward; - vec3 up = unrot * (vec3(0.0, 1.0, 0.0) * mat3(inv_view)); - vec3 aup = abs(up); - int iu = (aup.x > aup.y) ? ((aup.x > aup.z) ? 0 : 2) : ((aup.y > aup.z) ? 1 : 2); - int ia = (iu + 1) % 3; - int ib = (iu + 2) % 3; - vec3 axis_up = vec3(0.0); - axis_up[iu] = (up[iu] < 0.0) ? -1.0 : 1.0; - vec3 axis_a = vec3(0.0); - axis_a[ia] = 1.0; - vec3 axis_b = vec3(0.0); - axis_b[ib] = 1.0; - vec3 an = abs(normal); - vec3 axis_u, axis_v, axis_n; - if (an[iu] > max(an[ia], an[ib])) - { - axis_n = axis_up; - axis_u = axis_a; - axis_v = axis_b; - } - else if (an[ia] >= an[ib]) - { - axis_n = axis_a; - axis_u = axis_b; - axis_v = axis_up; - } - else - { - axis_n = axis_b; - axis_u = axis_a; - axis_v = axis_up; - } - vec2 glass = vec2(dot(local, axis_u), dot(local, axis_v)); - float facing = dot(normal, axis_n); - facing = ((facing < 0.0) ? -1.0 : 1.0) * max(abs(facing), 0.35); - // a step of the coordinates is a step along the glass - rw_tu = rot * (axis_u - axis_n * (dot(normal, axis_u) / facing)); - rw_tv = rot * (axis_v - axis_n * (dot(normal, axis_v) / facing)); + vec4 tex_color = texture(diffuse, f_coord); + float glassA = tex_color.a * alpha_mult; - // the derivatives, before anything is discarded: the size of a pixel on the glass and in the view, and how the coordinates of - // the mask follow the ones of the glass - vec3 view = normalize(f_pos.xyz); - vec3 dpdx = dFdx(f_pos.xyz); - vec3 dpdy = dFdy(f_pos.xyz); - rw_pixel = max(max(length(dpdx), length(dpdy)), 1e-6); - float pixelangle = max(max(length(dFdx(view)), length(dFdy(view))), 1e-6); - vec2 gdx = dFdx(glass); - vec2 gdy = dFdy(glass); - mat2 steps = mat2(gdx, gdy); - float det = determinant(steps); - mat2 maskstep = (abs(det) > 1e-14) ? mat2(dFdx(f_coord), dFdy(f_coord)) * inverse(steps) : mat2(0.0); + float gridSize = ceil(param[2].x); + vec2 rainCoord = f_coord; - // the water the simulation keeps, where the material is a glass of the cab of the train (the param water_slot, given by the - // renderer: 1 + the glass): the view space step along the glass for a step of the uv, and how fresh the wetted path the water - // went along is, with how that changes along the glass (before anything is discarded) - int slot = int(param[2].z + 0.5) - 1; - mat2 uvsteps = mat2(dFdx(f_coord), dFdy(f_coord)); - float uvdet = determinant(uvsteps); - bool simulated = (slot >= 0) && (slot < WATER_SLOTS) && (abs(uvdet) > 1e-24); - simulated = simulated && (water_header[clamp(slot, 0, WATER_SLOTS - 1)].x > 0.5); - mat2x3 puv = (abs(uvdet) > 1e-24) ? mat2x3(dpdx, dpdy) * inverse(uvsteps) : mat2x3(0.0); - vec3 trailfield = simulated ? rw_trail(uint(slot), f_coord, water_header[clamp(slot, 0, WATER_SLOTS - 1)].y) : vec3(0.0); - float trail = trailfield.x; - // its gradient along the glass, view space: the uv gradient taken through the steps of the uv along the glass - vec3 trailslope = vec3(0.0); - { - mat2 metric = transpose(puv) * puv; - if (abs(determinant(metric)) > 1e-30) - trailslope = puv * (inverse(metric) * trailfield.yz); - } + float ambLum = clamp(dot(ambient, vec3(0.2126, 0.7152, 0.0722)), 0.0, 1.0); + float dynBright = pow(clamp(ambLum * 6.0, 0.0, 1.0), 0.5); + // GL 4.6: the ambient light isn't a level of 0..1 any more (it is in the units of the scene, the light of the sky added), so + // at night the drops came out as bright as by day. how bright the picture around really is says it: the coarsest level of + // the image of the last frame, the average of the screen + float sceneLum = (ssr_params.x >= 1.0) ? wsLum(textureLod(ssr_history, vec2(0.5), ssr_params2.x).rgb) : 1.0; + float wsNight = smoothstep(0.0, drop_dark_lum, sceneLum); // 0 dark night .. 1 daylight + dynBright *= wsNight; - if (tex_color.a < 0.01) - discard; + // wiper state of this pixel (blur, micro droplets) + float hazeSide; + float wipeVis = GetMixFactor(f_coord, hazeSide); - vec4 layer = vec4(0.0); - float heavy = clamp(rain_params.x, 0.0, 1.0); - bool snow = rain_params.z > 0.5; - if ((heavy > 0.0) || simulated) - { - rw_scale = max(param[2].y, 0.05); + Hit hit; + hit.score = 0.0; hit.cov = 0.0; hit.colA = 0.0; hit.n = vec3(0.0, 0.0, 1.0); + hit.offUV = vec2(0.0); hit.radUV = 1.0; hit.isDrop = 1.0; + hit.vis = 0.0; hit.auv = vec2(0.0); hit.agx = vec2(0.0); hit.agy = vec2(0.0); hit.atlas = 0.0; hit.shade = 0.0; - // what meets the glass. the air against the vehicle (rain_wind) drags the drops along the glass with what of it goes - // along the glass and with the share of what meets it head on which turns up it: the more the glass leans back the more - // of the air goes along it, and the less of their weight pulls the drops down it - vec3 air = unrot * (rain_wind.xyz * mat3(inv_view)); - float fall = snow ? RW_SNOW_FALL : RW_RAIN_FALL; - float hits = max(-dot(air - up * fall, normal), 0.0); - rw_rate = heavy * clamp(0.7 + hits / fall, 0.7, 6.0); - rw_period = clamp((snow ? 10.0 : 5.0) / rw_rate, 0.4, 300.0); - rw_grow = 2.0 * rw_period; - vec3 gravity = -up - normal * dot(-up, normal); - vec3 rise = up - normal * dot(up, normal); - rise = (length(rise) > 0.1) ? normalize(rise) : vec3(0.0); - vec3 flow = air - normal * dot(air, normal) + rise * (max(-dot(air, normal), 0.0) * RW_HEAD_ON); - vec3 push = gravity + flow * (length(flow) / (RW_DRAG_SPEED * RW_DRAG_SPEED)); - vec2 force = vec2(dot(push, axis_u), dot(push, axis_v)); - rw_push = length(force); - vec2 fallway = vec2(dot(gravity, axis_u), dot(gravity, axis_v)); - rw_down = (length(fallway) > 0.1) ? normalize(fallway) : vec2(0.0, -1.0); - vec2 flowway = vec2(dot(flow, axis_u), dot(flow, axis_v)); - rw_flow = (length(flowway) > 1.0) ? normalize(flowway) : vec2(0.0); + // ---- the air against the vehicle on the glass (uniform flow: the derivatives of the glass above) ---- + float flipS = (STREAK_FLIP_Y != 0) ? -1.0 : 1.0; // texture v -> glass v (up) + vec3 wsUp = vec3(0.0, 1.0, 0.0) * mat3(inv_view); // world up, view space + vec3 wsAir = rain_wind.xyz * mat3(inv_view); // the air against the vehicle, view space, m/s + vec3 wsN = (dot(Ngl, f_pos.xyz) < 0.0) ? -Ngl : Ngl; // the outside of the glass + vec3 wsGrav = -wsUp - wsN * dot(-wsUp, wsN); // the weight along the glass + vec3 wsRise = wsUp - wsN * dot(wsUp, wsN); + wsRise = (length(wsRise) > 0.1) ? normalize(wsRise) : vec3(0.0); + vec3 wsFlow = wsAir - wsN * dot(wsAir, wsN) + wsRise * (max(-dot(wsAir, wsN), 0.0) * WS_HEAD_ON); + float wsDrag = dot(wsFlow, wsFlow) / (WS_DRAG_SPEED * WS_DRAG_SPEED) * wind_drag_gain; // in units of the weight + vec3 wsFlowDir = (length(wsFlow) > 1e-3) ? normalize(wsFlow) : vec3(0.0); + vec3 wsPush = wsGrav + wsFlowDir * wsDrag; + // to the glass UV (v up) through the tangent frame of the texture + vec2 gravG = vec2(dot(wsGrav, Tgl), dot(wsGrav, Bgl) * flipS); + vec2 flowG = vec2(dot(wsFlowDir, Tgl), dot(wsFlowDir, Bgl) * flipS); + float wsSpeed = smoothstep(0.3, 1.2, wsDrag); // 0 standing still .. 1 at speed (haze, drops) + wsWindShare = smoothstep(0.5, 1.3, wsDrag); // how much the air drives the rivulets + if (wsWindShare > 0.0) + { + // the rivulets of the air run along the push of the air at twice the weight: the same way at any speed (they don't swing + // round as the train speeds up), up a front glass, back and down a side window + vec2 way = gravG + flowG * 2.0; + if (dot(way, way) > 1e-8) + { + way = normalize(way); + float turn = round(atan(way.x, -way.y) / WS_WIND_STEP) * WS_WIND_STEP; + wsWindCos = cos(turn); + wsWindSin = sin(turn); + } + else + wsWindShare = 0.0; + } + // the push of the air on the drops, texture UV (for stretching them) + vec2 wsPushT = vec2(dot(wsPush, Tgl), dot(wsPush, Bgl)); + wsPushT = (dot(wsPushT, wsPushT) > 1e-10) ? normalize(wsPushT) : vec2(0.0, -1.0); + // the change of the glass UV (v up) per screen pixel, for the rivulets + vec2 wsRd1 = vec2(duv1.x, flipS * duv1.y); + vec2 wsRd2 = vec2(duv2.x, flipS * duv2.y); - rw_wipe_s wipe = rw_wipe(mask); - rw_since = wipe.since; - // the blades went lately (any of them, also where none of them reaches) - float working = 0.0; - for (int i = 0; i < 4; ++i) - working = max(working, 1.0 - smoothstep(4.0, 30.0, time - wiper_timer_return[i])); - // how much of the water the place gathers it has - float gathered = 1.0 - exp(-rw_since / (6.0 * rw_period)); - // the film a blade leaves is drawn into fine streaks along its arcs, each a thin cylindrical lens which draws a light seen - // through it into a line across the streaks, towards the pivot of the blade: the way across the streaks on the screen - vec2 streakway = vec2(0.0); - if ((working > 0.0) && (false == snow) && (abs(det) > 1e-14)) - { - int blade = 0; - for (int i = 1; i < 4; ++i) - blade = (mask[i] > mask[blade]) ? i : blade; - if (mask[blade] >= 0.001) - { - // the mask grows along the arcs; a step of a centimetre, so the steps of its values don't matter - float mu = textureLod(wipermask, f_coord + maskstep * vec2(0.01, 0.0), 0.0)[blade]; - float mv = textureLod(wipermask, f_coord + maskstep * vec2(0.0, 0.01), 0.0)[blade]; - vec2 arc = vec2(mu, mv) - mask[blade]; - vec2 onscreen = inverse(steps) * vec2(-arc.y, arc.x); - if ((length(arc) > 1e-4) && (length(onscreen) > 1e-9)) - streakway = normalize(onscreen); - } - } - vec3 ripple = rw_noise2(glass / (0.006 * rw_scale), 5u); + // ---- rivulet cell of this pixel (also used to sweep the drops) ---- + wsSetLayer(0); + float sCW = streak_cell / gridSize; + float sCH = streak_run / gridSize; + vec2 sUVg = vec2(f_coord.x, (STREAK_FLIP_Y != 0) ? 1.0 - f_coord.y : f_coord.y); // glass UV, v up + vec2 sCell = floor(sUVg / vec2(sCW, sCH)); + Riv rivP = getRiv(sCell, sCW, sCH, gridSize); + bool sweepOn = streak_sweep > 0.0 && streak_density > 0.0 && (wind_streaks > 0.0 || wsWindShare < 1.0); - // the water a blade pushes: a bead in front of it while it moves, as wide as the water it gathered on its way, with a steep - // lumpy front (its edge shows dark, the view can't get out there). the drops the bead reaches flow into it - vec3 lumps = rw_noise2(glass / (0.009 * rw_scale), 7u); - float gatheredwater = snow ? 0.0 : min(gathered * 1.5, 1.0) * (0.35 + 0.65 * min(wipe.swept * 2.5, 1.0)); - float reach = 0.004 + 0.018 * gatheredwater + 0.008 * (ripple.x - 0.5); - float ridge = gatheredwater * smoothstep(0.0, 0.003, wipe.front) * (1.0 - smoothstep(reach - 0.004, reach, wipe.front)); - // the smooth shape from how it changes from pixel to pixel, the lumps on it as they are - float pooledbase = 0.004 * ridge; - float pooled = pooledbase * (0.75 + 0.5 * lumps.x); - vec3 pooledslope = rw_gradient(pooledbase, dpdx, dpdy, outward) * (0.75 + 0.5 * lumps.x) + rw_along(lumps.yz * (0.5 * pooledbase / (0.009 * rw_scale))); - if ((pooled > 0.0) && (false == simulated)) - { - rw_sheet(pooled, pooledslope, 0.03, smoothstep(0.0, 0.1, ridge)); - if (ridge > 0.05) - rw_cleared = time; - } + if (rain_params.x > 0.001) + { + // =================================================================== + // 1. drops from the atlas: this cell and its 8 neighbours + // =================================================================== + vec2 cell = floor(rainCoord * gridSize); + for (int oy = -1; oy <= 1; oy++) + for (int ox = -1; ox <= 1; ox++) + { + vec2 nc = cell + vec2(ox, oy); + uvec2 key = cellKey(nc); + // life cycle of this cell: a new drop every lifeLen seconds + uint s0 = Hash(uvec3(key, 23u)); + float lifeLen = mix(drop_life_min, drop_life_max, RandF(s0)); + float tt = time / lifeLen + RandF(s0); + float epoch = floor(tt); + float ph = tt - epoch; + uint ep = uint(mod(epoch, 65521.0)); + // activation first (cheap), the wiper texture only for live drops + uint s1 = Hash(uvec3(key, ep * 4u + 1u)); + if (RandF(s1) > rain_params.x * drop_density) + continue; + float side; + float mixF = GetMixFactor((nc + 0.5) / gridSize, side); + uint s2 = Hash(uvec3(key, ep * 4u + 2u + uint(side) * 2u)); + if (mixF < RandF(s2)) + continue; - float snowcover = 0.0; - float wet = 0.0; - if (simulated) - { - // the directions along the glass, view space - vec3 upview = vec3(0.0, 1.0, 0.0) * mat3(inv_view); - vec3 downview = -(upview - outward * dot(upview, outward)); - downview = (length(downview) > 0.05) ? normalize(downview) : normalize(cross(outward, normalize(rw_tu))); - vec3 sideview = cross(outward, downview); - rw_simulated(uint(slot), f_coord, puv, downview, sideview, snowcover, wet); - // the paths the water went along lately: a rivulet, a band of water rounded across (a cylinder lens: it holds a picture of - // the place around it turned over across the band, its edges dark as the edges of drops), thicker the fresher. the - // smoothed freshness falls off from the middle of a path to its edges - if (trail > 0.08) - { - float p = clamp((trail - 0.08) / 0.5, 0.0, 1.0); - float thickness = 0.0005 * (1.0 - (1.0 - p) * (1.0 - p)); - vec3 rise = trailslope * (0.0005 * 2.0 * (1.0 - p) / 0.5); - float steep = length(rise); - if (steep > 0.7) - rise *= 0.7 / steep; - bool top = thickness > rw_height; - rw_sheet(thickness, rise, 0.004, smoothstep(0.0, 0.15, p) * 0.95); - // from the middle of the band to the fragment - float across = length(trailslope) / 0.5; - if (top && (across > 1.0)) - rw_offset = -trailslope * ((1.0 - p) / (across * length(trailslope))); - } - } - else if (false == snow) - { - // the drops which grew big enough slide off, with gravity and the air: a set of tracks for each of the directions of the - // push nearest to the one now, each laid along its own way, so none of them moves when the push turns - float sliding = smoothstep(0.25, 0.6, rw_push); - if (sliding > 0.0) - { - float bin = atan(force.y, force.x) / (RW_PI / 6.0); - float lower = floor(bin); - for (int k = 0; k < 2; ++k) - { - float share = ((k == 0) ? 1.0 - (bin - lower) : bin - lower) * sliding; - if (share < 0.02) - continue; - float angle = (lower + float(k)) * (RW_PI / 6.0); - vec2 down = vec2(cos(angle), sin(angle)); - vec2 side = vec2(-down.y, down.x); - rw_sliders(vec2(dot(glass, side), -dot(glass, down)), side, down, uint(int(lower) + k + 64) * 2u + 16u, share); - } - } + vec2 center = (nc + vec2(RandF(s2), RandF(s2))) / gridSize; + float size = mix(drop_size_min, drop_size_max, pow(RandF(s2), drop_size_bias)) / gridSize; + float sag = 1.0 + drop_sag * RandF(s2); + float flipX = (RandF(s2) < 0.5) ? 1.0 : 0.0; + float choice = RandF(s2); + // at speed the air stretches the drop along its push (1 standing still: the drop as it always was) + float stretch = 1.0 + drop_wind_stretch * wsSpeed * RandF(s2); + mat2 shapeM = mat2(1.0, 0.0, 0.0, 1.0 / sag) + * (mat2(1.0) + (1.0 / stretch - 1.0) * outerProduct(wsPushT, wsPushT)); - // the drops as they land, each time somewhere else in its cell, as often as the rain hits the glass: the drops of the - // rain spread on the glass, thrown with a fine splash which runs back into them - // each drop anywhere in its cell, the cell as large as a drop with its splash reaches - float cell = 0.007 * rw_scale; - vec2 laid = rw_turn(glass, 0.61) + vec2(0.31, 0.17); - ivec2 home = ivec2(floor(laid / cell)); - float density = mix(0.08, 0.3, heavy); - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x) - { - ivec2 c = home + ivec2(x, y); - vec4 a = rw_random(c, 1u, 0u); - if (a.x > density) - continue; - vec4 b = rw_random(c, 1u, 1u); - float span = rw_period * mix(0.7, 1.3, a.w); - float cycle = floor(time / span + b.x); - float age = time - (cycle - b.x) * span; - float life = span * mix(0.5, 0.9, b.y); - if ((age > life) || (age > rw_since) || (time - age < rw_cleared)) - continue; - vec4 p = rw_random(c, 2u, uint(cycle)); - vec2 offset = rw_turn(laid - (vec2(c) + p.xy) * cell, -0.61); - float visible = mix(0.0011, 0.0019, b.z) * rw_scale; - // a raindrop hits the glass far above the speed at which it splashes (Weber number in the hundreds and thousands): - // it spreads, throws a spray of droplets which stay on the glass around it, and draws back - float splash = exp(-age / 0.06); - float fade = 1.0 - smoothstep(life - min(0.4, 0.3 * life), life, age); - if (visible * 0.3 > 0.5 * rw_pixel) - { - int spray = 3 + int(p.z * 4.0); - for (int s = 0; s < spray; ++s) - { - vec4 e = rw_random(c, 3u, uint(cycle) * 8u + uint(s)); - vec2 way = normalize(vec2(cos(e.x * 6.2831853), sin(e.x * 6.2831853)) + rw_flow * 0.9); - rw_blob(offset - way * (visible * (1.4 + 1.6 * e.y)), visible * mix(0.18, 0.35, e.z), fade * (0.55 + 0.45 * splash)); - } - } - rw_drop(offset, visible * (1.0 + 0.3 * splash), fade, p.wzyx); - } - } - // the drops the landing ones gathered into, growing until they are big enough to slide (the air blows them off sooner) - cell = 0.011 * rw_scale; - laid = rw_turn(glass, 1.07) + vec2(0.53, 0.29); - home = ivec2(floor(laid / cell)); - density = mix(0.55, 1.0, heavy); - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x) - { - ivec2 c = home + ivec2(x, y); - vec4 a = rw_random(c, 4u, 0u); - if (a.x > density) - continue; - vec4 b = rw_random(c, 4u, 1u); - float span = rw_period * mix(2.5, 4.0, a.w); - float cycle = floor(time / span + b.x); - float age = time - (cycle - b.x) * span; - float life = span * mix(0.75, 0.98, b.y) / (1.0 + 2.0 * max(rw_push - 1.0, 0.0)); - if ((age > life) || (age > rw_since) || (time - age < rw_cleared)) - continue; - vec4 p = rw_random(c, 5u, uint(cycle)); - // the big drops are much alike: they grow as they gather the small ones (the radius in step with the time) up to the - // size at which they slide off (on a vertical glass a footprint of about 9 mm, larger on a glass leaning back, smaller - // in a strong air flow), and go - float slides = min(0.0045 / sqrt(max(rw_push, 0.3)), 0.005); - float visible = slides * mix(0.6, 1.0, b.z) * rw_scale * mix(0.35, 1.0, clamp(age / (0.6 * life), 0.0, 1.0)); - rw_drop(rw_turn(laid - (vec2(c) + p.xy) * cell, -1.07), visible, 1.0 - smoothstep(life - min(0.5, 0.3 * life), life, age), p.zwxy); - } - } + float appearF = drop_appear / lifeLen; + float fadeF = drop_fade / lifeLen; + float vis = smoothstep(0.0, appearF, ph) * (1.0 - smoothstep(1.0 - fadeF, 1.0, ph)); + float sq = size * mix(0.8, 1.0, smoothstep(0.0, 2.0 * appearF, ph)); // spreads out as it lands - // the water the blades push out of their sweep: a broken row of drops flowed together along its edge, just outside it - float leave = working * min(heavy * 1.5, 1.0); - if ((leave > 0.0) && rw_border(f_coord, 0.009 * rw_scale, maskstep)) - { - cell = 0.0065 * rw_scale; - laid = rw_turn(glass, 0.29) + vec2(0.11, 0.43); - home = ivec2(floor(laid / cell)); - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x) - { - ivec2 c = home + ivec2(x, y); - vec4 a = rw_random(c, 20u, 0u); - if (a.x > 0.85) - continue; - // from the fragment to the middle of the drop, along the glass - vec2 centre = rw_turn((vec2(c) + a.yz) * cell - laid, -0.29); - float rim = rw_rim(f_coord + maskstep * centre, 0.004 * rw_scale, maskstep) * leave; - if (rim <= 0.05) - continue; - rw_drop(-centre, mix(0.0016, 0.003, a.w) * rw_scale * mix(0.6, 1.0, rim), smoothstep(0.05, 0.35, rim), rw_random(c, 21u, 0u)); - } - } - } + vec2 diff = rainCoord - center; + vec2 dl = shapeM * diff; + if (max(abs(dl.x), abs(dl.y)) >= sq * 0.5) + continue; - // the streams running down from the water the blades leave at the ends of their sweep: a stream in some of the columns - // along the way down, where up the glass there is such water, as far down as the water had time to run since the blade - // went over the place - if ((working > 0.0) && (length(fallway) > 0.3)) - { - vec2 side = vec2(-rw_down.y, rw_down.x); - float width = 0.035 * rw_scale; - float across = dot(glass, side); - float along = -dot(glass, rw_down); - int column = int(floor(across / width)); - vec4 a = rw_random(ivec2(column, 0), 30u, 0u); - if (a.x < 0.6 * heavy * working) - { - float lateral = across - rw_path(column, along, width, 31u); - float half_width = mix(0.0006, 0.0012, a.z) * rw_scale * (0.6 + 0.8 * rw_noise(along / (0.006 * rw_scale), 32u)); - if (abs(lateral) < 2.0 * half_width + rw_pixel) - { - // up the glass, the first place where the reach of the blades begins or ends - const float reach[6] = float[](0.01, 0.025, 0.05, 0.1, 0.18, 0.3); - bool here = rw_reached(f_coord); - float source = -1.0; - for (int s = 0; s < 6; ++s) - { - if (rw_reached(f_coord + maskstep * (-rw_down * reach[s])) != here) - { - source = reach[s]; - break; - } - } - if ((source > 0.0) && (source < max(rw_since - 0.1, 0.0) * 0.2)) - { - float beads = rw_noise(along / (0.004 * rw_scale), 33u); - float flowing = working * (1.0 - 0.5 * smoothstep(0.15, 0.3, source)); - rw_blob(side * lateral, half_width, flowing * mix(0.6, 1.2, beads)); - } - } - } - } - } - else - { - // the flakes stick where they land and melt into drops: the glass is warmed by the cab, faster in the air above zero - float warm = rain_params.w; - float cell = 0.016 * rw_scale; - vec2 laid = rw_turn(glass, 0.83) + vec2(0.07, 0.61); - ivec2 home = ivec2(floor(laid / cell)); - float density = mix(0.5, 0.9, heavy); - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x) - { - ivec2 c = home + ivec2(x, y); - vec4 a = rw_random(c, 11u, 0u); - if (a.x > density) - continue; - vec4 b = rw_random(c, 11u, 1u); - float span = rw_period * mix(0.7, 1.3, a.w); - float cycle = floor(time / span + b.x); - float age = time - (cycle - b.x) * span; - float life = span * mix(0.6, 0.95, b.y); - if ((age > life) || (age > rw_since)) - continue; - vec4 p = rw_random(c, 12u, uint(cycle)); - vec2 offset = rw_turn(laid - (vec2(c) + p.xy) * cell, -0.83); - float diameter = mix(RW_SNOW_DIAMETER.x, RW_SNOW_DIAMETER.y, b.z) * rw_scale; - float melt = ((warm > 0.5) ? mix(3.0, 10.0, b.w) / (1.0 + 0.25 * warm) : mix(15.0, 45.0, b.w)); - if (age < melt) - { - float m = age / melt; - float dist = length(offset.x * rw_tu + offset.y * rw_tv); - float radius = 0.5 * diameter; - if (dist < radius + rw_pixel) - { - float angle = atan(offset.y, offset.x); - float lobes = 0.55 + 0.45 * (0.6 * rw_noise(angle * 1.9 + p.z * 40.0, 13u) + 0.4 * abs(cos(3.0 * angle + p.w * 6.2831853))); - float rim = radius * lobes * (1.0 - 0.45 * m); - float body = smoothstep(rim + rw_pixel, 0.55 * rim - rw_pixel, dist); - float lace = rw_noise2(glass / (0.0007 * rw_scale) + p.zw * 100.0, 14u).x; - float flake = body * mix(0.55, 1.0, lace) * (1.0 - 0.7 * m * m); - snowcover = 1.0 - (1.0 - snowcover) * (1.0 - flake); - wet = max(wet, m * body); - } - } - else - { - // the water of the flake - rw_drop(offset, 0.0018 * pow(diameter / 0.008, 0.667) * rw_scale, 1.0 - smoothstep(life - min(0.5, 0.3 * life), life, age), p.wzyx); - } - } - } - // the snow the blades push in front of them and leave at the ends of their sweep - float pile = max(wipe.ahead * min(gathered * 2.0, 1.0) * (0.4 + 0.6 * min(wipe.swept * 2.5, 1.0)), rw_rim(f_coord, 0.006 * rw_scale, maskstep) * working * heavy); - float packed = rw_noise2(glass / (0.0015 * rw_scale), 15u).x; - snowcover = max(snowcover, smoothstep(0.15, 0.5, pile * 1.2 + 0.4 * (ripple.x - 0.5)) * mix(0.7, 1.0, packed)); - } - // untreated glass, weathered and a little dirty: flat drops (a rain repellent coating would give beads above 90 degrees) - rw_settle(radians(mix(30.0, 48.0, rw_noise2(glass / (0.005 * rw_scale), 16u).x))); + if (sweepOn) + { + vec2 cg = vec2(center.x, (STREAK_FLIP_Y != 0) ? 1.0 - center.y : center.y); + vis *= wsKept(cg, 0.35 * sq, rivP, sCell, sCW, sCH, gridSize); + } + if (vis <= 0.001) + continue; - // the lamps (of the cab, of the scenery) and the headlights light the water up, from both sides of the glass (worked out - // here, where the fragments of a quad go together) - vec3 lamps = vec3(0.0); - vec3 lampgloss = vec3(0.0); - add_local_lights(outward, lamps, lampgloss); - add_local_lights(-outward, lamps, lampgloss); + vec2 luv = dl / sq + 0.5; + if (flipX > 0.5) luv.x = 1.0 - luv.x; + float atlasTexels = float(textureSize(normalmap, 0).x); + float quadPx = sq / max(uvPerPx, 1e-6); + float nlod = clamp(log2(max(0.25 * atlasTexels / max(quadPx, 1.0), 1.0)), 0.0, 6.0); + vec4 nm = textureLod(normalmap, dropAtlasUV(choice, luv), nlod); + float cov = smoothstep(0.1, 0.6, nm.a) * vis; + if (cov <= 0.001) + continue; + vec2 nxy = nm.rg * 2.0 - 1.0; + if (flipX > 0.5) nxy.x = -nxy.x; + float nz = sqrt(1.0 - clamp(dot(nxy, nxy), 0.0, 1.0)); + vec2 slope = transpose(shapeM) * (-nxy / max(nz, 0.08)); + vec3 n = normalize(vec3(-slope, 1.0)); + // gradients of the tile UV (for the one atlas read after the loop) + vec2 gx = (shapeM * duv1) / sq * vec2(0.25, 0.5); + vec2 gy = (shapeM * duv2) / sq * vec2(0.25, 0.5); + consider(hit, cov * (nm.b * sq * sag + 1e-5), cov, 0.0, n, diff, 0.5 * sq, 1.0, + vis, dropAtlasUV(choice, luv), gx, gy, 1.0, 0.0); + } - // the film just behind a blade, breaking up - float film = snow ? 0.0 : heavy * exp(-rw_since / 0.8) * smoothstep(0.02, 0.08, rw_since); - if (film > 0.01) - { - vec3 fine = rw_noise2(glass / (0.0021 * rw_scale), 6u); - vec2 tilt = fine.yz * (0.004 * film); - rw_sheet(0.00005 * film, rw_along(tilt), 0.3, 0.8 * film); - } + // =================================================================== + // 2. micro droplets: procedural, one per micro cell, fully inside it + // =================================================================== + if (micro_density > 0.0) + { + float mg = gridSize * micro_scale; + vec2 mc = floor(rainCoord * mg); + uvec2 mk = cellKey(mc); + uint m0 = Hash(uvec3(mk, 51u)); + float mLife = micro_life * mix(0.6, 1.6, RandF(m0)); + float mtt = time / mLife + RandF(m0); + float mph = fract(mtt); + uint mep = uint(mod(floor(mtt), 65521.0)); + uint m1 = Hash(uvec3(mk, mep * 4u + 1u)); + if (RandF(m1) < rain_params.x * micro_density) + { + uint m2 = Hash(uvec3(mk, mep * 4u + 2u + uint(hazeSide) * 2u)); + if (wipeVis >= RandF(m2)) + { + float r = mix(micro_size_min, micro_size_max, pow(RandF(m2), 1.5)); + vec2 c = mc + vec2(r) + vec2(RandF(m2), RandF(m2)) * max(1.0 - 2.0 * r, 0.0); + float ell = mix(0.85, 1.15, RandF(m2)); + vec2 p = (rainCoord * mg - c) / r; + p.x *= ell; + float d2 = dot(p, p); + if (d2 < 1.0) + { + float vis = smoothstep(0.0, 0.01, mph) * (1.0 - smoothstep(0.97, 1.0, mph)); + if (sweepOn) + { + vec2 cu = c / mg; + vec2 cg = vec2(cu.x, (STREAK_FLIP_Y != 0) ? 1.0 - cu.y : cu.y); + vis *= wsKept(cg, r / mg, rivP, sCell, sCW, sCH, gridSize); + } + float d = sqrt(d2); + float cov = smoothstep(1.0, 0.8, d) * vis; + if (cov > 0.001) + { + vec2 nxy = p * micro_bulge; + float nz = sqrt(1.0 - clamp(dot(nxy, nxy), 0.0, 1.0)); + vec3 n = normalize(vec3(nxy, nz)); + float h = sqrt(1.0 - d2) * micro_bulge * (r / mg); + float rim = smoothstep(drop_rim_start, drop_rim_end, 1.0 - n.z); + float lt = dot(n, DROP_LIGHT) * drop_light_side * 0.5 + (1.0 - drop_light_side * 0.5); + consider(hit, cov * (h + 1e-6), cov, smoothstep(1.0, 0.9, d) * vis, n, + rainCoord - c / mg, r / mg, 1.0, + vis, vec2(0.0), vec2(0.0), vec2(0.0), 0.0, clamp(rim * lt, 0.0, 1.0)); + } + } + } + } + } - // what the water shows: the view goes through the glass (a plate: only the way from the air into the water counts) and out - // through the surface of the water, bent as much as it is curved. it is the world turned upside down in a drop, and the - // edges of a drop, where the view can't get out (total internal reflection), show the inside of the cab - float background = 0.0; - bool image = ssr_params.x >= 1.0; - if (image) - { - ivec2 size = textureSize(scene_depth, 0); - float depth = texelFetch(scene_depth, clamp(ivec2(gl_FragCoord.xy), ivec2(0), size - 1), 0).r; - if (depth > 0.0) - background = (projection[3][2] / depth) / max(-view.z, 0.05); - } - vec3 inside = ambient * (AMBIENT_SCALE * 0.5); - vec4 water = vec4(0.0); - if (rw_cover > 0.0) - { - vec3 surface = normalize(outward - rw_slope); - vec3 inwater = refract(view, -outward, 1.0 / RW_IOR); - vec3 through = refract(inwater, -surface, RW_IOR); - // what the surface reflects back inside the water: the light which came in at the other side of the drop, from the sky, - // and the inside of the cab. where the view can't get out (the edge of a drop) that is all it shows: a bright edge - vec3 bounced = reflect(inwater, surface); - if (dot(bounced, outward) < 0.0) - bounced = reflect(bounced, outward); - vec3 inner = mix(inside, rw_surroundings(normalize(bounced), 5.0), 0.3); - vec3 color = inner; - if (dot(through, through) > 0.5) - { - float fresnel = 0.02 + 0.98 * pow(1.0 - abs(dot(through, surface)), 5.0); - // the view through the water spreads over this much of the world across a pixel (radians) - float spread = (RW_IOR - 1.0) * rw_pixel / max(rw_curve, 1e-4); - // the picture the drop holds as a lens, and a share of the bending by the surface - vec3 lens = normalize(f_pos.xyz - (1.0 + RW_LENS) * rw_offset) + (through - view) * RW_LENS_BEND; - float lod = mix(log2(1.0 + RW_LENS) - 0.5, log2(max(spread / pixelangle, 1.0)), RW_LENS_BEND); - // a drop a few pixels across would hold a picture of single pixels, a grain: blurred more the smaller it looks - lod += clamp(2.5 - log2(max(rw_curve / rw_pixel, 1.0)), 0.0, 1.5); - float share; - vec3 seen = rw_behind(normalize(lens), lod, background, share); - // the sun through the drop, where the image doesn't hold it: as bright as the drop gathers its light. in heavier rain - // the sun is behind the clouds, its disc is not there to be focused - float sunshare = (1.0 - heavy) * (1.0 - heavy); - if ((lights_count > 0U) && (share < 1.0) && (sunshare > 0.01)) - { - vec3 sun = normalize(-lights[0].dir); - float width = max(spread, 0.03); - float off = acos(clamp(dot(through, sun), -1.0, 1.0)); - if (off < 4.0 * width) - { - float lit = 1.0 - clamp(calc_shadow(), 0.0, 1.0); - vec3 sunlight = lights[0].color * (SUN_DIFFUSE_SCALE * lights[0].intensity * cloud_shadow(mat3(inv_view) * f_pos.xyz)); - // the light of the sun over the spread of the view: a pixel shows pi * irradiance * the share of a steradian - seen += sunlight * (sunshare * lit * (1.0 - share) * exp(-0.5 * off * off / (width * width)) / (2.0 * width * width)); - } - } - color = mix(seen, inner, fresnel); - } - color += lamps * 0.6; - // without the image of the last frame the surroundings stand for what the water bends the view to; nearly flat water - // would show them in place of the scene behind it, so it is left mostly clear - float opaque = image ? 1.0 : mix(0.3, 1.0, smoothstep(0.02, 0.15, 1.0 - dot(through, view))); - water = vec4(color, rw_cover * opaque); - } - // the wet glass where the rain gathers is a little hazy: the tiniest drops spread the light - if (image && (false == snow)) - { - float mist = heavy * gathered * (simulated ? 0.18 : 0.3); - if (mist > 0.01) - { - float share; - vec3 hazy = rw_behind_edges(view, 3.5, background, share, false); - // the tiniest drops spread the light of the sky coming through the glass - hazy = mix(hazy, rw_surroundings(outward, 7.0), 0.1); - layer = vec4(hazy, mist * max(share, 0.5)); - } - } - layer = rw_over(water, layer); - // the lights seen through the streaks of the film the blades leave, drawn into lines towards their pivot - if (image && (length(streakway) > 0.5)) - { - vec4 previous = ssr_reprojection * ((background > 0.0) ? vec4(view * background, 1.0) : vec4(view, 0.0)); - if (previous.w > 1e-5) - { - vec2 coords = (previous.xy / previous.w) * 0.5 + 0.5; - vec2 texel = 1.0 / vec2(textureSize(ssr_history, 0)); - ivec2 size = textureSize(scene_depth, 0); - float near = projection[3][2]; - // a light: much brighter than the place around it (the bright sky is not) - vec3 around = textureLod(ssr_history, clamp(coords, vec2(0.0), vec2(1.0)), 6.0).rgb; - float threshold = max(1.0, 3.0 * max(around.r, max(around.g, around.b))); - vec3 glare = vec3(0.0); - float total = 0.0; - for (int k = -8; k <= 8; ++k) - { - if (k == 0) - continue; - float w = 1.0 - abs(float(k)) / 9.0; - total += w; - vec2 tap = coords + streakway * texel * (float(k) * 5.0); - if (any(lessThan(tap, vec2(0.0))) || any(greaterThan(tap, vec2(1.0)))) - continue; - // only what is outside: the lamps of the cab are not behind the glass - float depth = texelFetch(scene_depth, clamp(ivec2(tap * vec2(size)), ivec2(0), size - 1), 0).r; - if ((depth > 0.0) && (near / depth < -f_pos.z + 2.5)) - continue; - vec3 c = textureLod(ssr_history, tap, 1.5).rgb; - if (any(isnan(c)) || any(isinf(c))) - continue; - glare += max(c - vec3(threshold), vec3(0.0)) * w; - } - glare *= 0.6 * heavy * working / total; - if (any(greaterThan(glare, vec3(1e-4)))) - { - // the scene itself under the water carries the light added (it changes nothing seen) - vec3 scene = textureLod(ssr_history, clamp(coords, vec2(0.0), vec2(1.0)), 0.0).rgb; - layer = rw_over(layer, vec4(max(scene, vec3(0.0)), 0.2)); - layer.rgb += glare / layer.a; - } - } - } - if (snowcover > 0.0) - { - // the flakes are lit through from the outside, by the sky and the sun, and from the inside of the cab; melting they turn - // grey and clear - vec3 outside = rw_surroundings(outward, 6.0); - if (lights_count > 0U) - { - vec3 sun = normalize(-lights[0].dir); - outside += lights[0].color * (SUN_DIFFUSE_SCALE * lights[0].intensity * max(dot(outward, sun), 0.0) * (1.0 - clamp(calc_shadow(), 0.0, 1.0))); - } - vec3 flake = mix(vec3(0.92), vec3(0.62, 0.66, 0.7), wet); - vec3 color = flake * (outside * (0.35 * (1.0 - 0.5 * wet)) + ambient * (AMBIENT_SCALE * 0.7)); - layer = rw_over(vec4(color, snowcover * mix(0.97, 0.6, wet)), layer); - } - } - out_color = layer; + // =================================================================== + // 3. rivulets of this pixel's cells: the layer of gravity and, at speed, the one of the air + // =================================================================== + wsSetLayer(0); + drawRivulet(hit, rivP, sUVg, wsRd1, wsRd2); + if (wsWindShare > 0.001) + { + for (int wl = 1; wl <= wind_layers; ++wl) + { + vec2 wc = vec2(sCW * wind_cell_scale, sCH * ((wl == wind_layers) && (wl > 1) ? wind_long_run : wind_run_scale)); + wsSetLayer(wl); + // every further layer: its cells shifted aside, drops of its own + vec2 sUVw = wsToLayer(sUVg) + fract(vec2(0.5, 0.618) * float(wl - 1)) * wc; + Riv rivW = getRiv(floor(sUVw / wc), wc.x, wc.y, gridSize); + drawRivulet(hit, rivW, sUVw, wsToLayerDir(wsRd1), wsToLayerDir(wsRd2)); + } + wsSetLayer(0); + } + } - { // Overlay windshield texture with alpha - vec3 fragcolor = ambient; - vec3 fragnormal = normalize(f_normal); - float reflectivity = param[1].z; - float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5; - legacy_gloss(); + // ----------------------------------------------------------------------- + // Shading of the winning dome + // ----------------------------------------------------------------------- + float coverA = clamp(hit.cov, 0.0, 1.0); + vec3 dropLayer = vec3(0.0); + float alphaOut = 0.0; + vec3 dropGlint = vec3(0.0); + vec2 lensBend = vec2(0.0); + float lensK = 0.0; // drops: how much the lens shrinks the picture + float lensRadPx = 1.0e4; // drops: radius on screen, pixels + if (coverA > 0.001) + { + vec3 Nt = hit.n; + // look of the drop: grey atlas (bright rim, dark middle) for drops and rivulets, analytic for droplets + vec3 rgb; + float colA; + if (hit.atlas > 0.5) + { + vec4 at = textureGrad(raindropsatlas, hit.auv, hit.agx, hit.agy); + rgb = at.rgb; + colA = smoothstep(0.3, 0.9, at.a) * hit.vis; + } + else + { + rgb = vec3(hit.shade); + colA = hit.colA; + } + float a = colA * mix(drop_center_alpha, drop_rim_alpha, smoothstep(0.1, 0.3, length(rgb))); + dropLayer = rgb * dynBright * a; + alphaOut = clamp(a, 0.0, 1.0); - fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); - vec4 color = vec4(fragcolor, tex_color.a * alpha_mult); + // refraction: Snell for rivulets (and as a fallback), lens picture for drops + vec3 I = normalize(f_pos.xyz); + vec3 No = (dot(Ngl, I) > 0.0) ? Ngl : -Ngl; + vec3 Nd = normalize(Tgl * Nt.x + Bgl * Nt.y + No * Nt.z); + vec3 R = refract(I, -Nd, drop_ior); + if (dot(R, R) < 1e-4) + R = refract(I, -Nd, 1.0 + 0.5 * (drop_ior - 1.0)); + vec2 dSlope = vec2(0.0); + if (dot(R, R) > 1e-4 && R.z < -0.05) + dSlope = R.xy / (-R.z) - I.xy / (-I.z); + vec2 snellBend = clamp(-(dSlope * pxPerSlope * drop_refract) / WS_REFR_MAXPX, vec2(-1.0), vec2(1.0)); + lensBend = snellBend; + if (hit.isDrop > 0.5 && drop_lens_mix > 0.0) + { + vec2 offPx = Jinv * hit.offUV; // pixel - drop centre, in screen pixels + float radPx = hit.radUV / max(uvPerPx, 1e-6); + float k = clamp(min(drop_lens, 0.95 * WS_REFR_MAXPX / max(radPx, 1.0) - 1.0), 0.0, drop_lens); + vec2 lb = clamp((1.0 + k) * offPx / WS_REFR_MAXPX, vec2(-1.0), vec2(1.0)); + lensBend = mix(snellBend, lb, drop_lens_mix); + lensK = k; + lensRadPx = radPx; + } - out_color.xyz = apply_fog(mix(out_color.xyz, color.xyz, color.a)); - out_color.a = mix(out_color.a, 1., color.a); - } - if (false == POSTFX_ENABLED) - { - out_color = tonemap(out_color); - } + vec3 Rd = (dot(R, R) > 1e-4) ? normalize(R) : I; + vec3 glint = vec3(0.0); + if (lights_count > 0U) + { + float cosS = max(dot(Rd, normalize(-lights[0].dir)), 0.0); + float lobe = pow(cosS, drop_glint_sharpness) * drop_glint_strength + + pow(cosS, 0.2 * drop_glint_sharpness) * drop_sheen; + // the shadow (shadow map + GL 4.6 contact shadow ray) only where the sun shows in the drop at all + if (lobe > 1e-4) + { + float shadowSun = 0.0; + if (shadow_tone < 1.0) + shadowSun = (1.0 - shadow_tone) * clamp(calc_shadow(), 0.0, 1.0); + // GL 4.6: the clouds hold the sun back where their shadow falls (as in apply_lights) + float cloudSun = cloud_shadow(mat3(inv_view) * f_pos.xyz); + glint += lights[0].color * lights[0].intensity * lobe * (1.0 - shadowSun) * cloudSun * wsNight; + } + } + // GL 4.6: headlights and lamps come from the light cluster of the fragment (lights_clustered), or are the + // first lights_count - 1 headlights otherwise. calc_headlights takes the screen-space change of f_pos + // (worked out at the top of main, in uniform flow). The drop scatters light from both sides of the glass, + // so the glass normal is turned towards the light. + // only the lights outside the glass and a few metres away light the drops up (signals, lamps of the station, the + // headlights of other trains): the lamps and the headlights of the own vehicle, a metre or two from the glass, would + // make every drop glow white + vec3 lamps = vec3(0.0); + if (lights_clustered != 0U) + { + cluster_range_s range = cluster_ranges[fragment_cluster()]; + for (uint i = 0U; i < range.count; i++) + { + light_s lt = lights[cluster_light_indices[range.offset + i]]; + vec3 toL = lt.pos - f_pos.xyz; + float away = smoothstep(0.0, 0.2, dot(toL, wsN) / max(length(toL), 1e-4)) + * smoothstep(drop_light_near, 2.0 * drop_light_near, length(toL)); + if (away <= 0.0) + continue; + vec3 nl = (dot(Ngl, toL) > 0.0) ? Ngl : -Ngl; + if (lt.type == LIGHT_HEADLIGHTS) + lamps += lt.color * calc_headlights(lt, nl, dp1, dp2).x * lt.intensity * drop_headlight_scatter * away; + else if (drop_lamp_scatter > 0.0) + lamps += lt.color * calc_local_light(lt, nl).x * lt.intensity * drop_lamp_scatter * away; + } + } + else + { + for (uint i = 1U; i < lights_count; i++) + { + light_s lt = lights[i]; + vec3 toL = lt.pos - f_pos.xyz; + float away = smoothstep(0.0, 0.2, dot(toL, wsN) / max(length(toL), 1e-4)) + * smoothstep(drop_light_near, 2.0 * drop_light_near, length(toL)); + if (away <= 0.0) + continue; + vec3 nl = (dot(Ngl, toL) > 0.0) ? Ngl : -Ngl; + lamps += lt.color * calc_headlights(lt, nl, dp1, dp2).x * lt.intensity * drop_headlight_scatter * away; + } + } + glint += min(lamps, vec3(drop_light_max)); + // reflection of the surroundings on the dome: straight from the environment map. (It used to go through a + // second apply_lights, which in GL 4.6 also runs the shadow map, the contact shadows and the whole light + // cluster again for every drop pixel; the sun and the lamps are done above already.) + if (drop_env > 0.0) + { + vec3 Nv = -Nd; // dome normal towards the viewer + float NoV = clamp(dot(Nv, -I), 0.0, 1.0); + glint += envmap_color_lod(Nv, 0.8) * EnvBRDFApprox(vec3(0.04), 0.1, NoV) * drop_env * wsNight; + } + dropGlint = glint; + if (!POSTFX_ENABLED) + dropGlint = min(dropGlint, vec3(1.0)); // this path is not tonemapped + } - if (MOTIONBLUR_ENABLED) - { - out_motion = vec4(0.0); - } + // ----------------------------------------------------------------------- + // What is seen through the wet glass: the image of the last frame, blurred by the haze, bent by the drops + // ----------------------------------------------------------------------- + // the haze after the wiper: grows with the rain fallen since, up to the intensity of the rain (as it always was where no wiper reaches) + float wipeAge = wsWipeAge(f_coord); + float hazeBack = (wipeAge < 0.0) ? 1.0 + : min(wipeVis, pow(clamp(wipeAge * rain_params.x / haze_fill, 0.0, 1.0), haze_curve)); + float hazeWeight = min(rain_params.x * hazeBack * (1.0 + haze_speed * wsSpeed), 1.0) * (1.0 - max(alphaOut, coverA)); + float glassClear = 1.0 - smoothstep(0.5, 0.95, glassA); + bool image = ssr_params.x >= 1.0; + float background = 0.0; // distance to the scene behind, along the view (0: far / not known) + if (image) + { + ivec2 size = textureSize(scene_depth, 0); + float depth = texelFetch(scene_depth, clamp(ivec2(gl_FragCoord.xy), ivec2(0), size - 1), 0).r; + if (depth > 0.0) + background = (projection[3][2] / depth) / max(-wsView.z, 0.05); + } + vec4 under = vec4(0.0); // the blurred view under the drops (not premultiplied) + vec4 bent = vec4(0.0); // the view bent by the drops, laid over everything (as the old postfx did) + + // the haze is blurred by the post-processing (postfx_taa.frag / postfx_motionblur.frag, rain_windscreen_haze.glsl): the + // picture of this frame can't be read here, and one of the last frame laid over it only shows a milky ghost of the scene + float blurAmt = clamp(hazeWeight * blur_amount, 0.0, 1.0); + + // the drops: the view bent (the picture shift worked out above), and the lights near them. with the motion vectors the + // post-processing bends the picture of this frame (postfx_taa.frag / postfx_motionblur.frag, rain_windscreen_haze.glsl): it has + // the depth of the cab and never pulls the dashboard or the roof into a drop. the image of the last frame is only the fallback + float refrA = smoothstep(0.05, 0.35, coverA) * glassClear * step(glassA, 0.5); + if ((false == MOTIONBLUR_ENABLED) && (refrA > 0.001)) + { + vec2 shiftPx = -lensBend * WS_REFR_MAXPX; // where the drop looks, screen pixels + vec3 dir = normalize(wsView + shiftPx.x * wsDvx + shiftPx.y * wsDvy); + // a drop shows a minified picture: read it from a coarser level (no grain); tiny drops a little blurrier still + float lod = clamp(log2(1.0 + lensK * drop_lens_mix) - 0.5, 0.0, 3.0) + + clamp(2.5 - log2(max(lensRadPx, 1.0)), 0.0, 1.5); + float share; + vec3 seen = wsBehind(dir, lod, background, share, true); + if (image && (WS_LIGHT_GAIN > 0.0)) + seen += wsLightGlow(wsView, background); + // without the image the surroundings stand in: only faintly, they aren't the scene behind + bent = vec4(seen, refrA * WS_REFR_MIX * (image ? 1.0 : 0.3)); + } + + // the drop shading over it + float shadeA = coverA * drop_shade_alpha; + float outA = alphaOut + shadeA * (1.0 - alphaOut); + vec4 drops = vec4(dropLayer, outA); + drops.rgb += dropGlint * coverA / max(outA, 0.05); // the blend multiplies by alpha once more + out_color = wsOver(drops, under); + + { // windshield texture over the rain + vec3 fragcolor = ambient; + // where the glass texture is clear, its lighting is multiplied by ~0 below: skip apply_lights there + if (glassA > 0.002) + { + vec3 fragnormal = normalize(f_normal); + float reflectivity = param[1].z; + float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5; + legacy_gloss(); + fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); + } + vec4 color = vec4(fragcolor, glassA); + out_color.xyz = apply_fog(mix(out_color.xyz, color.xyz, color.a)); + out_color.a = mix(out_color.a, 1., color.a); + } + // the picture in the drops goes over the drop shading and the glass, as the old postfx replaced the pixel with it: the dark + // middle of the atlas only shows through faintly, the rim and the glints a little more + out_color = wsOver(bent, out_color); + if (!POSTFX_ENABLED) + out_color = tonemap(out_color); + + // the velocity target: on the drops the picture shift (x, y = WS_DROP_BIAS + WS_BEND_ENC * bend), on the hazy glass the request + // for the haze (x = WS_ENC * strength, y = 0); elsewhere the velocity of the scene behind the glass stays as it is (alpha 0) + if (MOTIONBLUR_ENABLED) + { + vec4 req = vec4(0.0); + bool drop = (coverA > 0.05 || alphaOut > 0.05) && (glassA < 0.5); + float blurMask = blurAmt * glassClear; + if (drop) + { + vec2 bend = lensBend * smoothstep(0.05, 0.35, coverA); + req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); + } + else if (blurMask >= 0.01) + req = vec4(WS_ENC * blurMask, 0.0, 0.0, 1.0); + out_motion = req; + } +} + +float GetMixFactor(in vec2 co, out float side) { + vec4 movePhase = wiper_pos; + bvec4 is_out = lessThanEqual(movePhase, vec4(1.)); + movePhase = mix(vec4(2.) - movePhase, movePhase, is_out); + + vec4 mask = textureLod(wipermask, co, 0.0); // called from non-uniform flow: no implicit derivatives + + vec4 areaMask = step(.001, mask); + + vec4 maskVal = mix(1. - mask, mask, is_out); + vec4 wipeWidth = smoothstep(1., .9, movePhase) * .25; + vec4 cleaned = smoothstep(movePhase - wipeWidth, movePhase, maskVal) * areaMask; + vec4 side_v = step(maskVal, movePhase); + cleaned *= side_v; + side_v = mix(side_v, vec4(1.) - side_v, is_out); + + // "regeneration", raindrops gradually returning after wiper pass: + vec4 regenPhase = clamp((vec4(time) - mix(wiper_timer_out, wiper_timer_return, side_v) - vec4(.2)) / vec4(rain_params.y), vec4(0.), vec4(1.)); + + side_v = mix(vec4(0.), vec4(1.) - side_v, areaMask); + + vec4 factor_v = mix(vec4(1.), regenPhase * (vec4(1.) - cleaned), areaMask); + + side = 0.; + float out_factor = 1.; + bool have_side = false; + // out_factor: the blade that clears the cell the most wins. side: which wiper stroke the drops of this + // cell belong to (part of their random seed, so it must not depend on out_factor). + for (int i = 0; i < 4; ++i) + { + out_factor = min(out_factor, factor_v[i]); + if (!have_side && areaMask[i] > 0.) + { + side = side_v[i]; + have_side = true; + } + } + return out_factor; } diff --git a/shaders/vk14/postfx_motionblur.frag b/shaders/vk14/postfx_motionblur.frag index 12d788008..2bc7d938b 100644 --- a/shaders/vk14/postfx_motionblur.frag +++ b/shaders/vk14/postfx_motionblur.frag @@ -16,12 +16,35 @@ layout(set = POST_SET, binding = POST_TEXTURE_FIRST + 1) uniform sampler2D veloc layout(set = POST_SET, binding = POST_TEXTURE_FIRST + 2) uniform sampler2D depth_tex; +#include "rain_windscreen_haze.glsl" + void main() { + // the wet windscreen (mat_rain_windscreen.frag): its drops and haze done here without the taa, left as they are when the taa + // did them (marked in the alpha) + vec2 rawv = texture(velocity_tex, f_coords).xy; + if (wsIsDrop(rawv)) + { + vec4 picture = texture(color_tex, f_coords); + out_color = vec4((picture.a > 0.5 * (1.0 + WS_HAZED)) ? picture.rgb + : wsDropRefraction(color_tex, velocity_tex, depth_tex, f_coords, rawv), 1.0); + return; + } + float blurAmt = wsBlur(rawv); + if (blurAmt > 0.0) + { + vec4 picture = texture(color_tex, f_coords); + out_color = vec4((picture.a > 0.5 * (1.0 + WS_HAZED)) ? picture.rgb : wsHaze(color_tex, velocity_tex, f_coords, blurAmt), 1.0); + return; + } + float ori_depth = texture(depth_tex, f_coords).x; vec2 texelSize = 1.0 / vec2(textureSize(color_tex, 0)); - vec2 velocity = texture(velocity_tex, f_coords).xy * param[0].x; + vec2 velocity = rawv * param[0].x; + // edge pixels of the windscreen can carry a fraction of a request: never use that as motion + if (any(greaterThan(abs(rawv), vec2(WS_FLOOR * WS_ENC)))) + velocity = vec2(0.0); float speed = length(velocity / texelSize); int nSamples = clamp(int(speed), 1, 32); diff --git a/shaders/vk14/postfx_taa.frag b/shaders/vk14/postfx_taa.frag index dd48c0203..6e01a3b25 100644 --- a/shaders/vk14/postfx_taa.frag +++ b/shaders/vk14/postfx_taa.frag @@ -23,4 +23,54 @@ layout(set = POST_SET, binding = POST_TEXTURE_FIRST + 3) uniform sampler2D histo #define TAA_HISTORY_VALID (param[0].x > 0.5) #define TAA_REPROJECTION mat4(param[2], param[3], param[4], param[5]) #define TAA_NEAR param[0].y +#include "rain_windscreen_haze.glsl" + +// the resolve of the taa under another name: main() below gives the wet windscreen (mat_rain_windscreen.frag) its haze and the +// picture in its drops first +#define main taa_resolve_main #include "taa_resolve.glsl" +#undef main + +// the drops and the haze are made from the frame alone (the history of the taa would smear them over the frames): drawn with the +// offsets of the taa they shimmer from frame to frame. they stay where they are on the screen, so the result of the last frame at +// the same pixel is blended in: fully while the view stands still, half while it moves, kept near this frame's result (no ghosts +// of a wiper or of drops gone) +const float WS_TEMPORAL_SHARE = 0.2; // the share of this frame while the view stands still +const float WS_TEMPORAL_MOVING = 0.5; // ... and while it moves +const float WS_TEMPORAL_RANGE = 0.12; // the last frame kept within this of this frame (colours squeezed into 0..1) + +vec3 wsStabilize(vec3 current, ivec2 pixel) +{ + if (false == TAA_HISTORY_VALID) + return current; + vec4 last = texelFetch(history_tex, pixel, 0); + if (any(isnan(last)) || (last.a < 0.5 * (1.0 + WS_HAZED))) // not a drop or haze pixel in the last frame + return current; + vec2 size = vec2(textureSize(color_tex, 0)); + float depth = texelFetch(depth_tex, pixel, 0).r; + vec4 world = TAA_REPROJECTION * vec4(f_coords * 2.0 - 1.0, depth, 1.0); + bool still = (world.w > 0.0) && (length((world.xy / world.w * 0.5 + 0.5 - f_coords) * size) < 0.5); + vec3 c = taa_compress(current); + vec3 h = clamp(taa_compress(taa_clean(last.rgb)), c - WS_TEMPORAL_RANGE, c + WS_TEMPORAL_RANGE); + return taa_decompress(clamp(mix(h, c, still ? WS_TEMPORAL_SHARE : WS_TEMPORAL_MOVING), vec3(0.0), vec3(1.0 - 1.0 / TAA_HALF_MAX))); +} + +void main() +{ + // the drops: the picture of this frame bent by them; the hazy glass: the picture of this frame blurred over it. both without + // the history (else they would smear on frame after frame), marked for the motion blur after + ivec2 pixel = ivec2(f_coords * vec2(textureSize(velocity_tex, 0))); + vec2 raw = texelFetch(velocity_tex, pixel, 0).xy; + if (wsIsDrop(raw)) + { + out_color = vec4(wsStabilize(taa_clean(wsDropRefraction(color_tex, velocity_tex, depth_tex, f_coords, raw)), pixel), WS_HAZED); + return; + } + float blurAmt = wsBlur(raw); + if (blurAmt > 0.0) + { + out_color = vec4(wsStabilize(taa_clean(wsHaze(color_tex, velocity_tex, f_coords, blurAmt)), pixel), WS_HAZED); + return; + } + taa_resolve_main(); +} diff --git a/shaders/vk14/rain_windscreen_haze.glsl b/shaders/vk14/rain_windscreen_haze.glsl new file mode 100644 index 000000000..6dd9a4cde --- /dev/null +++ b/shaders/vk14/rain_windscreen_haze.glsl @@ -0,0 +1,233 @@ +// the haze of the wet windscreen (mat_rain_windscreen.frag), drawn by the post-processing: the glass asks for it in the velocity +// target (x = WS_ENC * strength, y = 0, see mat_rain_windscreen.frag), and the picture there is blurred over the hazy glass only. +// postfx_taa.frag does it with the temporal anti-aliasing (every frame, also standing still), postfx_motionblur.frag without it +// (it runs only while something moves). the picture blurred by the taa is marked in its alpha (WS_HAZED), so the motion blur +// after it leaves it as it is. +// +// real motion vectors are tiny (<< 0.25 per frame), so the large values can only come from the windscreen +#ifndef RAIN_WINDSCREEN_HAZE_GLSL +#define RAIN_WINDSCREEN_HAZE_GLSL + +const float WS_ENC = 64.0; // must match mat_rain_windscreen.frag +const float WS_FLOOR = 0.004; // = 0.256 in raw velocity units: everything below is real motion +const float WS_HAZED = 2.0; // alpha of the picture the taa already blurred + +// blur of hazy glass +const float WS_RADIUS = 0.014; // max blur radius, fraction of screen height +const int WS_TAPS = 16; +const float WS_HAZE_LIGHT_CAP = 12.0; // the most a light adds to the haze around it (brightness, scene units) + +// strength of the blur request, 0 for pixels that are not blur pixels +float wsBlur(vec2 raw) +{ + if (raw.x > 100.0 || raw.y > 100.0) // a blended edge with something else: not a blur pixel + return 0.0; + float m = clamp(raw.x / WS_ENC, 0.0, 1.0); + return clamp((m - WS_FLOOR) / (1.0 - WS_FLOOR), 0.0, 1.0); +} + +// a colour of the picture made safe: a very bright light can be an infinity in the half float image (and a broken pixel a nan); +// in an average that gave nan for the whole result, which the taa turns black: black dotted blobs around the lights +vec3 wsSafe(vec3 c) +{ + return any(isnan(c)) ? vec3(0.0) : clamp(c, vec3(0.0), vec3(65000.0)); +} + +vec3 wsFetch(sampler2D tex, vec2 uv) +{ + return wsSafe(textureLod(tex, uv, 0.0).rgb); +} + +// the weight of a colour in an average that a single very bright pixel must not take over +float wsKaris(vec3 c) +{ + return 1.0 / (1.0 + dot(c, vec3(0.2126, 0.7152, 0.0722))); +} + +// the picture at Uv blurred over the hazy glass, for a request of BlurAmt (> 0) +vec3 wsHaze(sampler2D colortex, sampler2D velocitytex, vec2 uv, float blurAmt) +{ + vec2 texelSize = 1.0 / vec2(textureSize(colortex, 0)); + float aspect = texelSize.x / texelSize.y; // height / width + vec3 sharp = wsFetch(colortex, uv); + + float radius = WS_RADIUS * blurAmt; + + // interleaved gradient noise rotates the disc per pixel -> no banding + float rot = 6.2831853 * fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715)))); + + float wsum = wsKaris(sharp); + vec3 sum = sharp * wsum; + float psum_w = 1.0; // the plain average beside it + vec3 psum = sharp; + + for (int i = 0; i < WS_TAPS; ++i) + { + float r = sqrt((float(i) + 0.5) / float(WS_TAPS)); + float a = float(i) * 2.3999632 + rot; // golden angle + vec2 o = vec2(cos(a), sin(a)) * r * radius; + o.x *= aspect; + + vec2 tap = uv + o; + + // take only hazy-glass pixels (not the cab frame, not clear glass, not drops) + // weighed by 1 / (1 + brightness) (karis average): an ordinary picture blurs the same, but a very bright light + // (a lamp close by, headlights) is not smeared over the whole disc at full strength, which the bloom then turned + // into a large flat blob shaped like a clover + float w = step(0.01, wsBlur(textureLod(velocitytex, tap, 0.0).xy)); + vec3 c = wsFetch(colortex, tap); + psum += c * w; + psum_w += w; + w *= wsKaris(c); + sum += c * w; + wsum += w; + } + + // the karis average alone almost wipes small bright lights out of the haze (signals at night went faint): the light the + // plain average has above it comes back, up to WS_HAZE_LIGHT_CAP, so a light stays a soft glow of its colour and only a + // very bright one (a lamp close by) isn't smeared at full strength + vec3 blurred = sum / wsum; + vec3 extra = max(psum / psum_w - blurred, vec3(0.0)); + float extraL = dot(extra, vec3(0.2126, 0.7152, 0.0722)); + blurred += extra * min(1.0, WS_HAZE_LIGHT_CAP / max(extraL, 1e-4)); + return mix(sharp, blurred, min(blurAmt * 4.0, 1.0)); +} + +// --------------------------------------------------------------------------------------------------------------------------- +// refraction in the drops: the glass sends the picture shift of the drop (x, y = WS_DROP_BIAS + WS_BEND_ENC * bend, bend -1..1 +// = WS_REFR_MAXPX pixels), and the picture of this frame is bent here. the depth of the whole frame (with the cab) is known here, +// so the dashboard, the frame and the roof of the cab are never pulled into a drop (the image of the last frame used by the +// glass shader can't tell them apart: white drops at night at the edges and under the wipers) +// --------------------------------------------------------------------------------------------------------------------------- +const float WS_BEND_ENC = 60.0; // must match mat_rain_windscreen.frag +const float WS_DROP_BIAS = 192.0; // must match mat_rain_windscreen.frag +const float WS_REFR_MAXPX = 96.0; // must match mat_rain_windscreen.frag +const float WS_REFR_MIX = 0.85; // 0 = no refraction, 1 = only the refracted picture +const float WS_LENS_AA = 0.75; // above this spread of the picture between neighbouring pixels, a 4x4 footprint is averaged + +// the lights in the drops: a drop is a wide-angle lens and lights up near a bright light (signals, lamps, headlights). taken from +// the mipmaps of the image the screen reflections keep (ssr_history: the last frame, or this one in the motion blur), so the glow +// is smooth: point samples of the full image caught a headlight of one pixel only at fixed offsets and drew it as grids of dots +const float WS_LIGHT_GAIN = 1.0; // brightness of the lights in the drops (0 = off) +const float WS_LIGHT_CAP = 8.0; // the most the glow adds to a drop (brightness, scene units) +const float WS_LIGHT_MIN_LUM = 1.0; // a light: the fine level at least this bright (scene units) above the place around it ... +const float WS_LIGHT_CONTRAST = 3.0; // ... and this many times brighter than it +const float WS_LIGHT_FINE = 3.5; // mip levels: the drop's own neighbourhood (~11 px), a wider one (~32 px), the place around +const float WS_LIGHT_MID = 5.0; +const float WS_LIGHT_WIDE = 7.0; +const float WS_LIGHT_MID_SHARE = 0.5; // how much the lights a little further away count + +// the vulkan renderer gives the post-processing only its own images (LAYOUT_POST): no history of the reflections, no glow there +#ifndef LAYOUT_POST +layout(binding = SSR_HISTORY_TEX) uniform sampler2D ws_light_history; +#endif + +// reverse z, infinite far: depth = znear / distance. a sample is "the cab" when it is much nearer than the centre and closer than ~5 m +const float WS_NEAR_RATIO = 1.6; +const float WS_NEAR_DEPTH = 0.02; + +bool wsSameLayer(float d, float d0) +{ + return d <= max(d0 * WS_NEAR_RATIO, WS_NEAR_DEPTH); +} + +float wsLum(vec3 c) +{ + return dot(c, vec3(0.2126, 0.7152, 0.0722)); +} + +// a drop pixel (drop, rivulet): both values in 132..252 +bool wsIsDrop(vec2 raw) +{ + return raw.x > 120.0 && raw.y > 120.0; +} + +vec2 wsBend(vec2 raw) +{ + return clamp((raw - WS_DROP_BIAS) / WS_BEND_ENC, -1.0, 1.0); +} + +#ifndef LAYOUT_POST +vec3 wsLightExcess(vec2 uv, float lod, vec3 wide) +{ + vec3 c = wsSafe(textureLod(ws_light_history, uv, min(lod, ssr_params2.x)).rgb); + vec3 excess = max(c - wide * WS_LIGHT_CONTRAST, vec3(0.0)); + return excess * smoothstep(0.5 * WS_LIGHT_MIN_LUM, WS_LIGHT_MIN_LUM, wsLum(excess)); +} + +vec3 wsLightGlow(vec2 uv) +{ + if ((ssr_params.x < 1.0) || (textureSize(ws_light_history, 0).x < 16)) + return vec3(0.0); + vec3 wide = wsSafe(textureLod(ws_light_history, uv, min(WS_LIGHT_WIDE, ssr_params2.x)).rgb); + vec3 glow = wsLightExcess(uv, WS_LIGHT_FINE, wide) + WS_LIGHT_MID_SHARE * wsLightExcess(uv, WS_LIGHT_MID, wide); + glow *= WS_LIGHT_GAIN; + // a light close by is kept to the brightness of one light + return glow * min(1.0, WS_LIGHT_CAP / max(wsLum(glow), 1e-4)); +} +#else +vec3 wsLightGlow(vec2 uv) +{ + return vec3(0.0); +} +#endif + +// the picture at Uv seen through the drop, for a drop pixel with the request Raw +vec3 wsDropRefraction(sampler2D colortex, sampler2D velocitytex, sampler2D depthtex, vec2 uv, vec2 raw) +{ + vec2 texelSize = 1.0 / vec2(textureSize(colortex, 0)); + float aspect = texelSize.x / texelSize.y; // height / width + vec3 center = wsFetch(colortex, uv); + + vec2 bend = wsBend(raw); + vec2 uv2 = uv - bend * WS_REFR_MAXPX * texelSize; + + // the spread of the picture between neighbouring pixels (the jacobian of the shift): a drop shows a minified, flipped copy + // of the scene, single samples would alias into a hatch there + vec2 rx = textureLod(velocitytex, uv + vec2(texelSize.x, 0.0), 0.0).xy; + vec2 ry = textureLod(velocitytex, uv + vec2(0.0, texelSize.y), 0.0).xy; + vec2 jx = (wsIsDrop(rx) ? wsBend(rx) - bend : vec2(0.0)) * WS_REFR_MAXPX; + vec2 jy = (wsIsDrop(ry) ? wsBend(ry) - bend : vec2(0.0)) * WS_REFR_MAXPX; + float lens = length(jx) + length(jy); + + // never pull in what is much nearer than the scene behind the glass (the cab) + vec3 refr = center; + float d0 = textureLod(depthtex, uv, 0.0).x; + float d1 = textureLod(depthtex, uv2, 0.0).x; + if (wsSameLayer(d1, d0)) + { + if (lens < WS_LENS_AA) + { + refr = wsFetch(colortex, uv2); + } + else + { + vec2 fx = clamp(vec2(1.0, 0.0) - jx, vec2(-10.0), vec2(10.0)); + vec2 fy = clamp(vec2(0.0, 1.0) - jy, vec2(-10.0), vec2(10.0)); + vec3 acc = vec3(0.0); + float wacc = 0.0; + for (int j = 0; j < 4; ++j) + { + for (int i = 0; i < 4; ++i) + { + vec2 t = (vec2(float(i), float(j)) + 0.5) / 4.0 - 0.5; + vec3 c = wsFetch(colortex, uv2 + (fx * t.x + fy * t.y) * texelSize); + float w = wsKaris(c); + acc += c * w; + wacc += w; + } + } + refr = acc / wacc; + } + } + + vec3 outc = mix(center, refr, WS_REFR_MIX); + // the glow only in the drops themselves, strongest in their middle, where the lens bends most: the water film and the + // rivulets between them (no bend) would show it as flat squares around the headlights of an oncoming train + float glowW = smoothstep(0.03, 0.2, length(bend)); + if ((WS_LIGHT_GAIN > 0.0) && (glowW > 0.0)) + outc += wsLightGlow(uv) * glowW; + return outc; +} + +#endif From 12d7fbb00e0d300f2459ba461896924286d14b0f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 1 Nov 2026 20:02:25 +0100 Subject: [PATCH 041/123] Windscreen bugs from the insects met: none below 20 km/h, more the faster The engine counts the insects the vehicle of the wipers meets (seconds of driving at 100 km/h: nothing below 20 km/h, then (v - 20) / 80 a second) and gives the count to the shaders in rain_wind.w, with the count of the moments the blades were at the ends of their sweep in two new vec4 at the end of the block of the scene (wiper_bugs_out, wiper_bugs_return, next to the timers). mat_bugs_windscreen grows the dirt from the insects met since the glass was clean instead of from the time, so a vehicle standing still gets no bugs and a fast one gets them sooner (full after an hour at 100 km/h). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- gl/ubo.h | 9 +++- rendering/opengl46/opengl46renderer.cpp | 12 +++++ rendering/opengl46/opengl46renderer.h | 2 + rendering/vulkan14/vulkan14frame.cpp | 12 +++++ rendering/vulkan14/vulkan14renderer.h | 2 + shaders/ogl46/common.glsl | 3 ++ shaders/ogl46/mat_bugs_windscreen.frag | 63 +++++++++++++++++-------- shaders/vk14/common.glsl | 3 ++ shaders/vk14/mat_bugs_windscreen.frag | 63 +++++++++++++++++-------- 9 files changed, 127 insertions(+), 42 deletions(-) diff --git a/gl/ubo.h b/gl/ubo.h index 321e1af61..1d6c4d1ab 100644 --- a/gl/ubo.h +++ b/gl/ubo.h @@ -153,7 +153,8 @@ namespace gl // as realistic (gfx.water.realistic, water_surface.glsl), 0 as before glm::vec4 env_params; // the water on the windscreens (mat_rain_windscreen): xyz the velocity of the air against the vehicle of the camera (the - // share of the wind the particles of the rain drift with, less the velocity of the vehicle), world space, m/s; w unused + // share of the wind the particles of the rain drift with, less the velocity of the vehicle), world space, m/s; w the insects + // the vehicle met so far (mat_bugs_windscreen): seconds of driving at 100 km/h, none below 20 km/h, more the faster glm::vec4 rain_wind; // the ambient occlusion in the light of the surfaces (gfx.postfx.ao.lighting), set only for the colour pass of the main view, // zero elsewhere: x 1 when SCENE_AO_TEX holds the occlusion of the depth in SCENE_DEPTH_TEX, y the power it's raised to @@ -196,9 +197,13 @@ namespace gl glm::vec4 cab_probe_sun_color; glm::vec4 cab_probe_sun_box; glm::vec4 cab_probe_sun_world; + // the insects the vehicle had met (rain_wind.w) when the blades were at the ends of their sweep, as wiper_timer_out and + // wiper_timer_return (mat_bugs_windscreen: what hit the glass since a blade went over it); -1 not known + glm::vec4 wiper_bugs_out; + glm::vec4 wiper_bugs_return; }; - static_assert(sizeof(scene_ubs) == 928 + 80 * MAX_HEADLIGHT_SHADOWS + 96 * MAX_CAB_PROBE_LAMPS, "bad size of ubs"); + static_assert(sizeof(scene_ubs) == 960 + 80 * MAX_HEADLIGHT_SHADOWS + 96 * MAX_CAB_PROBE_LAMPS, "bad size of ubs"); const size_t MAX_PARAMS = 3; diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index 49276a47f..875c4f624 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -1696,7 +1696,15 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) m_wipervehicle = owner; scene_ubs.wiper_timer_out = glm::vec4{-1000.}; scene_ubs.wiper_timer_return = glm::vec4{-1000.}; + scene_ubs.wiper_bugs_out = glm::vec4{-1.}; + scene_ubs.wiper_bugs_return = glm::vec4{-1.}; + m_wiperbugs = 0.0; } + // the insects the vehicle meets (mat_bugs_windscreen): none below 20 km/h, above it the more the faster, counted in seconds of + // driving at 100 km/h + if (owner != nullptr) + m_wiperbugs += Timer::GetDeltaTime() * std::max(std::abs(owner->MoverParameters->V) * 3.6 - 20.0, 0.0) / 80.0; + scene_ubs.rain_wind.w = static_cast(m_wiperbugs); if (owner != nullptr) { auto const cabactive{owner->MoverParameters->CabActive != 0 ? owner->MoverParameters->CabActive : 1}; @@ -1713,10 +1721,12 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) if (owner->dWiperPos[index] < .025) { scene_ubs.wiper_timer_out[i] = scene_ubs.time; + scene_ubs.wiper_bugs_out[i] = static_cast(m_wiperbugs); } if (owner->dWiperPos[index] > .975) { scene_ubs.wiper_timer_return[i] = scene_ubs.time; + scene_ubs.wiper_bugs_return[i] = static_cast(m_wiperbugs); } } else @@ -1724,6 +1734,8 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) scene_ubs.wiper_pos[i] = 0.; scene_ubs.wiper_timer_out[i] = -1000.; scene_ubs.wiper_timer_return[i] = -1000.; + scene_ubs.wiper_bugs_out[i] = -1.; + scene_ubs.wiper_bugs_return[i] = -1.; } } } diff --git a/rendering/opengl46/opengl46renderer.h b/rendering/opengl46/opengl46renderer.h index 691bea6bb..585f6f355 100644 --- a/rendering/opengl46/opengl46renderer.h +++ b/rendering/opengl46/opengl46renderer.h @@ -866,6 +866,8 @@ class opengl46_renderer : public gfx_renderer, public gfx::scene_walk { gl::scene_ubs scene_ubs; // the vehicle whose wipers the timers of the blades in scene_ubs (wiper_timer_out / wiper_timer_return) follow TDynamicObject const *m_wipervehicle{nullptr}; + // the insects that vehicle met so far: seconds of driving at 100 km/h (scene_ubs.rain_wind.w) + double m_wiperbugs{0.0}; gl::light_data light_data; std::unordered_map> m_shaders; diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index 28493bac9..2aa65ea1a 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -1577,7 +1577,15 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) m_wipervehicle = owner; scene_ubs.wiper_timer_out = glm::vec4{-1000.}; scene_ubs.wiper_timer_return = glm::vec4{-1000.}; + scene_ubs.wiper_bugs_out = glm::vec4{-1.}; + scene_ubs.wiper_bugs_return = glm::vec4{-1.}; + m_wiperbugs = 0.0; } + // the insects the vehicle meets (mat_bugs_windscreen): none below 20 km/h, above it the more the faster, counted in seconds of + // driving at 100 km/h + if (owner != nullptr) + m_wiperbugs += Timer::GetDeltaTime() * std::max(std::abs(owner->MoverParameters->V) * 3.6 - 20.0, 0.0) / 80.0; + scene_ubs.rain_wind.w = static_cast(m_wiperbugs); if (owner != nullptr) { auto const cabactive{owner->MoverParameters->CabActive != 0 ? owner->MoverParameters->CabActive : 1}; @@ -1594,10 +1602,12 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) if (owner->dWiperPos[index] < .025) { scene_ubs.wiper_timer_out[i] = scene_ubs.time; + scene_ubs.wiper_bugs_out[i] = static_cast(m_wiperbugs); } if (owner->dWiperPos[index] > .975) { scene_ubs.wiper_timer_return[i] = scene_ubs.time; + scene_ubs.wiper_bugs_return[i] = static_cast(m_wiperbugs); } } else @@ -1605,6 +1615,8 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) scene_ubs.wiper_pos[i] = 0.; scene_ubs.wiper_timer_out[i] = -1000.; scene_ubs.wiper_timer_return[i] = -1000.; + scene_ubs.wiper_bugs_out[i] = -1.; + scene_ubs.wiper_bugs_return[i] = -1.; } } } diff --git a/rendering/vulkan14/vulkan14renderer.h b/rendering/vulkan14/vulkan14renderer.h index e8160c2bc..1ba2dcbde 100644 --- a/rendering/vulkan14/vulkan14renderer.h +++ b/rendering/vulkan14/vulkan14renderer.h @@ -561,6 +561,8 @@ class vulkan14_renderer : public gfx_renderer, public gfx::scene_walk gl::scene_ubs scene_ubs{}; // the vehicle whose wipers the timers of the blades in scene_ubs (wiper_timer_out / wiper_timer_return) follow TDynamicObject const *m_wipervehicle{nullptr}; + // the insects that vehicle met so far: seconds of driving at 100 km/h (scene_ubs.rain_wind.w) + double m_wiperbugs{0.0}; gl::light_data light_data{}; std::uint32_t m_lightcount{1}; // lights written to light_data // the copies of the light buffer in the ring of the frame since the lights were last written, by the header and the sun diff --git a/shaders/ogl46/common.glsl b/shaders/ogl46/common.glsl index 9c0a2ada4..a3762442a 100644 --- a/shaders/ogl46/common.glsl +++ b/shaders/ogl46/common.glsl @@ -368,6 +368,9 @@ layout(std140, binding = SCENE_UBO_BINDING) uniform scene_ubo vec4 cab_probe_sun_color; vec4 cab_probe_sun_box; vec4 cab_probe_sun_world; + // the insects met when the blades were at the ends of their sweep (mat_bugs_windscreen), see gl::scene_ubs + vec4 wiper_bugs_out; + vec4 wiper_bugs_return; }; #ifdef STAGE_VERTEX diff --git a/shaders/ogl46/mat_bugs_windscreen.frag b/shaders/ogl46/mat_bugs_windscreen.frag index ff0128c8e..93f6a4032 100644 --- a/shaders/ogl46/mat_bugs_windscreen.frag +++ b/shaders/ogl46/mat_bugs_windscreen.frag @@ -12,8 +12,10 @@ // now and then a really big bug and rarely a huge one (own coarse grids, never cut off by the 3x3 search); // smaller blur ring, scaled by the size of the bug on screen. // -// Insects splat on the glass one by one and the glass gets dirtier until it is -// fully dirty after `bugs_fill_time` seconds of simulation time (default 3600 = 1 h). +// Insects splat on the glass one by one, only while the vehicle goes faster than 20 km/h and the more the faster, and the glass +// gets dirtier until it is fully dirty after `bugs_fill_time` seconds of driving at 100 km/h (default 3600 = 1 h; at 160 km/h +// about 35 minutes, at 50 km/h 2.7 hours). The engine counts the insects met (rain_wind.w) and keeps the count of the moments +// the blades were at the ends of their sweep (wiper_bugs_out / wiper_bugs_return), next to their times. // No sliding, no rain: every bug is placed once (hash of its grid cell) and just // appears at its own random moment. Wipers (wipermask) wipe the bugs off in the area they // sweep; the glass there then gets dirty again, with new bugs, over the next bugs_fill_time. @@ -90,7 +92,7 @@ layout(binding = 2) uniform sampler2D wipermask; layout(binding = 3) uniform sampler2D normalmap; // --- Tuning ----------------------------------------------------------------- -const float bugs_fill_time = 3600.0; // seconds of simulation time until the glass is fully dirty +const float bugs_fill_time = 3600.0; // seconds of driving at 100 km/h until the glass is fully dirty (none below 20 km/h) const float bugs_start_time = 0.0; // simulation time at which the glass was clean const float bugs_density = 0.15; // fraction of grid cells that end up with a big bug (0..1) const float specks_density = 0.12; // same for the layer of tiny specks (0 = off) @@ -147,10 +149,11 @@ vec2 tileOffset(float choice) const float WIPER_NONE = -1.0e9; const float WIPER_UNKNOWN = -2.0e9; -float lastCleanTime(vec2 co) +float lastCleanTime(vec2 co, out float bugsAt) { vec4 m = textureLod(wipermask, co, 0.0); float best = WIPER_NONE; + bugsAt = 0.0; bool unknown = false; for (int i = 0; i < 4; ++i) { @@ -165,12 +168,17 @@ float lastCleanTime(vec2 co) float t = mix(wiper_timer_out[i], wiper_timer_return[i], sideV); if (!(t <= time)) // garbage or NaN: ignore continue; - if (t < -500.0) // the -1000 "memory lost" marker + float b = mix(wiper_bugs_out[i], wiper_bugs_return[i], sideV); // the insects met at that moment + if ((t < -500.0) || (b < 0.0)) // the -1000 "memory lost" marker { unknown = true; continue; } - best = max(best, t); + if (t > best) + { + best = t; + bugsAt = b; + } } if (best > WIPER_NONE) return best; @@ -180,21 +188,27 @@ float lastCleanTime(vec2 co) // Fine specks: tiny dried drops of bug juice. Procedural (a soft irregular blob with a darker rim), // one per speck cell and always inside it, so only the pixel's own cell is checked: no texture reads // apart from the wiper state of this pixel, which main() passes in. -void speckLayer(float gridSize, float density, float tcPix, vec2 aspect, float pixelUV, +void speckLayer(float gridSize, float density, float tcPix, float bugsPix, vec2 aspect, float pixelUV, inout vec3 accRGB, inout float accA, inout vec3 accN, inout float accNA) { vec2 g = f_coord * gridSize; vec2 cell = floor(g); float tBase, prog; + float met = max(rain_wind.w, 0.0); // the insects met so far if (tcPix < -1.5e9) { tBase = -1000.0; - prog = min(max(time - bugs_start_time, 0.0) / max(bugs_fill_time, 1.0), bugs_unknown_level); + prog = min(met / max(bugs_fill_time, 1.0), bugs_unknown_level); + } + else if (tcPix < -0.5e9) + { + tBase = bugs_start_time; + prog = met / max(bugs_fill_time, 1.0); } else { - tBase = max(bugs_start_time, tcPix); - prog = max(time - tBase, 0.0) / max(bugs_fill_time, 1.0); + tBase = tcPix; + prog = max(met - bugsPix, 0.0) / max(bugs_fill_time, 1.0); } if (prog <= 0.0) return; @@ -261,22 +275,30 @@ void bugLayer(float gridSize, float density, uint layerSeed, // When the wipers last swept over this cell. Whatever hit the glass before that // moment is gone; the cell then gets a brand new set of bugs (the seed depends on // that moment) that again take bugs_fill_time to build up. - float tc = (bugs_wiper_clean > 0.5) ? lastCleanTime((ncell + 0.5) / gridSize) : WIPER_NONE; + float bugsAt = 0.0; + float tc = (bugs_wiper_clean > 0.5) ? lastCleanTime((ncell + 0.5) / gridSize, bugsAt) : WIPER_NONE; + // the insects met since the glass here was clean (they come only above 20 km/h, see the head of the file) + float met = max(rain_wind.w, 0.0); float tBase; float prog; if (tc < -1.5e9) { - // The engine forgot when the wipers last swept here (the camera was outside the - // cab). We cannot know how dirty the glass was, so show a fixed, non-growing level - // until a blade passes and gives us a real clean time again. + // The engine forgot when the wipers last swept here (another vehicle). We cannot know how dirty the glass was, + // so show the level of the glass never wiped, at most bugs_unknown_level, until a blade passes. tBase = -1000.0; - prog = min(max(time - bugs_start_time, 0.0) / max(bugs_fill_time, 1.0), bugs_unknown_level); + prog = min(met / max(bugs_fill_time, 1.0), bugs_unknown_level); + } + else if (tc < -0.5e9) + { + // no blade reaches here: everything met so far + tBase = bugs_start_time; + prog = met / max(bugs_fill_time, 1.0); } else { - tBase = max(bugs_start_time, tc); - prog = max(time - tBase, 0.0) / max(bugs_fill_time, 1.0); + tBase = tc; + prog = max(met - bugsAt, 0.0) / max(bugs_fill_time, 1.0); } if (prog <= 0.0) continue; @@ -376,7 +398,7 @@ void main() vec2 aspect = (bugs_uv_aspect >= 1.0) ? vec2(bugs_uv_aspect, 1.0) : vec2(1.0, 1.0 / max(bugs_uv_aspect, 0.01)); // 0 = never dirty yet; the real per-cell progress is computed in bugLayer (wipers reset it) - float progress = clamp((time - bugs_start_time) / max(bugs_fill_time, 1.0), 0.0, 1.0); + float progress = clamp(max(rain_wind.w, 0.0) / max(bugs_fill_time, 1.0), 0.0, 1.0); vec3 bugRGB = vec3(0.0); // premultiplied float bugA = 0.0; @@ -388,8 +410,9 @@ void main() // fine specks underneath (procedural, one wiper read for the pixel), big bugs on top if (specks_density > 0.0) { - float tcPix = (bugs_wiper_clean > 0.5) ? lastCleanTime(f_coord) : WIPER_NONE; - speckLayer(gridSize * SPECK_SCALE, specks_density, tcPix, aspect, pixelUV, bugRGB, bugA, bugN, bugNA); + float bugsPix = 0.0; + float tcPix = (bugs_wiper_clean > 0.5) ? lastCleanTime(f_coord, bugsPix) : WIPER_NONE; + speckLayer(gridSize * SPECK_SCALE, specks_density, tcPix, bugsPix, aspect, pixelUV, bugRGB, bugA, bugN, bugNA); } bugLayer(gridSize, bugs_density, 3u, pixelUV, aspect, 1.0, 1.0, 0.0, bugRGB, bugA, smear, bugN, bugNA); // now and then a really big one, on top (its own coarse grid: same 3x3 search, bigger cells) diff --git a/shaders/vk14/common.glsl b/shaders/vk14/common.glsl index 3dc8df4b8..7a087f669 100644 --- a/shaders/vk14/common.glsl +++ b/shaders/vk14/common.glsl @@ -330,6 +330,9 @@ layout(std140, set = PASS_SET, binding = SCENE_UBO) uniform scene_ubo vec4 cab_probe_sun_color; vec4 cab_probe_sun_box; vec4 cab_probe_sun_world; + // the insects met when the blades were at the ends of their sweep (mat_bugs_windscreen), see gl::scene_ubs + vec4 wiper_bugs_out; + vec4 wiper_bugs_return; }; #ifndef LAYOUT_COMPUTE diff --git a/shaders/vk14/mat_bugs_windscreen.frag b/shaders/vk14/mat_bugs_windscreen.frag index 261acefe4..8037ddff6 100644 --- a/shaders/vk14/mat_bugs_windscreen.frag +++ b/shaders/vk14/mat_bugs_windscreen.frag @@ -13,8 +13,10 @@ // now and then a really big bug and rarely a huge one (own coarse grids, never cut off by the 3x3 search); // smaller blur ring, scaled by the size of the bug on screen. // -// Insects splat on the glass one by one and the glass gets dirtier until it is -// fully dirty after `bugs_fill_time` seconds of simulation time (default 3600 = 1 h). +// Insects splat on the glass one by one, only while the vehicle goes faster than 20 km/h and the more the faster, and the glass +// gets dirtier until it is fully dirty after `bugs_fill_time` seconds of driving at 100 km/h (default 3600 = 1 h; at 160 km/h +// about 35 minutes, at 50 km/h 2.7 hours). The engine counts the insects met (rain_wind.w) and keeps the count of the moments +// the blades were at the ends of their sweep (wiper_bugs_out / wiper_bugs_return), next to their times. // No sliding, no rain: every bug is placed once (hash of its grid cell) and just // appears at its own random moment. Wipers (wipermask) wipe the bugs off in the area they // sweep; the glass there then gets dirty again, with new bugs, over the next bugs_fill_time. @@ -95,7 +97,7 @@ layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 2) uniform sampler layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 3) uniform sampler2D normalmap; // --- Tuning ----------------------------------------------------------------- -const float bugs_fill_time = 3600.0; // seconds of simulation time until the glass is fully dirty +const float bugs_fill_time = 3600.0; // seconds of driving at 100 km/h until the glass is fully dirty (none below 20 km/h) const float bugs_start_time = 0.0; // simulation time at which the glass was clean const float bugs_density = 0.15; // fraction of grid cells that end up with a big bug (0..1) const float specks_density = 0.12; // same for the layer of tiny specks (0 = off) @@ -152,10 +154,11 @@ vec2 tileOffset(float choice) const float WIPER_NONE = -1.0e9; const float WIPER_UNKNOWN = -2.0e9; -float lastCleanTime(vec2 co) +float lastCleanTime(vec2 co, out float bugsAt) { vec4 m = textureLod(wipermask, co, 0.0); float best = WIPER_NONE; + bugsAt = 0.0; bool unknown = false; for (int i = 0; i < 4; ++i) { @@ -170,12 +173,17 @@ float lastCleanTime(vec2 co) float t = mix(wiper_timer_out[i], wiper_timer_return[i], sideV); if (!(t <= time)) // garbage or NaN: ignore continue; - if (t < -500.0) // the -1000 "memory lost" marker + float b = mix(wiper_bugs_out[i], wiper_bugs_return[i], sideV); // the insects met at that moment + if ((t < -500.0) || (b < 0.0)) // the -1000 "memory lost" marker { unknown = true; continue; } - best = max(best, t); + if (t > best) + { + best = t; + bugsAt = b; + } } if (best > WIPER_NONE) return best; @@ -185,21 +193,27 @@ float lastCleanTime(vec2 co) // Fine specks: tiny dried drops of bug juice. Procedural (a soft irregular blob with a darker rim), // one per speck cell and always inside it, so only the pixel's own cell is checked: no texture reads // apart from the wiper state of this pixel, which main() passes in. -void speckLayer(float gridSize, float density, float tcPix, vec2 aspect, float pixelUV, +void speckLayer(float gridSize, float density, float tcPix, float bugsPix, vec2 aspect, float pixelUV, inout vec3 accRGB, inout float accA, inout vec3 accN, inout float accNA) { vec2 g = f_coord * gridSize; vec2 cell = floor(g); float tBase, prog; + float met = max(rain_wind.w, 0.0); // the insects met so far if (tcPix < -1.5e9) { tBase = -1000.0; - prog = min(max(time - bugs_start_time, 0.0) / max(bugs_fill_time, 1.0), bugs_unknown_level); + prog = min(met / max(bugs_fill_time, 1.0), bugs_unknown_level); + } + else if (tcPix < -0.5e9) + { + tBase = bugs_start_time; + prog = met / max(bugs_fill_time, 1.0); } else { - tBase = max(bugs_start_time, tcPix); - prog = max(time - tBase, 0.0) / max(bugs_fill_time, 1.0); + tBase = tcPix; + prog = max(met - bugsPix, 0.0) / max(bugs_fill_time, 1.0); } if (prog <= 0.0) return; @@ -266,22 +280,30 @@ void bugLayer(float gridSize, float density, uint layerSeed, // When the wipers last swept over this cell. Whatever hit the glass before that // moment is gone; the cell then gets a brand new set of bugs (the seed depends on // that moment) that again take bugs_fill_time to build up. - float tc = (bugs_wiper_clean > 0.5) ? lastCleanTime((ncell + 0.5) / gridSize) : WIPER_NONE; + float bugsAt = 0.0; + float tc = (bugs_wiper_clean > 0.5) ? lastCleanTime((ncell + 0.5) / gridSize, bugsAt) : WIPER_NONE; + // the insects met since the glass here was clean (they come only above 20 km/h, see the head of the file) + float met = max(rain_wind.w, 0.0); float tBase; float prog; if (tc < -1.5e9) { - // The engine forgot when the wipers last swept here (the camera was outside the - // cab). We cannot know how dirty the glass was, so show a fixed, non-growing level - // until a blade passes and gives us a real clean time again. + // The engine forgot when the wipers last swept here (another vehicle). We cannot know how dirty the glass was, + // so show the level of the glass never wiped, at most bugs_unknown_level, until a blade passes. tBase = -1000.0; - prog = min(max(time - bugs_start_time, 0.0) / max(bugs_fill_time, 1.0), bugs_unknown_level); + prog = min(met / max(bugs_fill_time, 1.0), bugs_unknown_level); + } + else if (tc < -0.5e9) + { + // no blade reaches here: everything met so far + tBase = bugs_start_time; + prog = met / max(bugs_fill_time, 1.0); } else { - tBase = max(bugs_start_time, tc); - prog = max(time - tBase, 0.0) / max(bugs_fill_time, 1.0); + tBase = tc; + prog = max(met - bugsAt, 0.0) / max(bugs_fill_time, 1.0); } if (prog <= 0.0) continue; @@ -381,7 +403,7 @@ void main() vec2 aspect = (bugs_uv_aspect >= 1.0) ? vec2(bugs_uv_aspect, 1.0) : vec2(1.0, 1.0 / max(bugs_uv_aspect, 0.01)); // 0 = never dirty yet; the real per-cell progress is computed in bugLayer (wipers reset it) - float progress = clamp((time - bugs_start_time) / max(bugs_fill_time, 1.0), 0.0, 1.0); + float progress = clamp(max(rain_wind.w, 0.0) / max(bugs_fill_time, 1.0), 0.0, 1.0); vec3 bugRGB = vec3(0.0); // premultiplied float bugA = 0.0; @@ -393,8 +415,9 @@ void main() // fine specks underneath (procedural, one wiper read for the pixel), big bugs on top if (specks_density > 0.0) { - float tcPix = (bugs_wiper_clean > 0.5) ? lastCleanTime(f_coord) : WIPER_NONE; - speckLayer(gridSize * SPECK_SCALE, specks_density, tcPix, aspect, pixelUV, bugRGB, bugA, bugN, bugNA); + float bugsPix = 0.0; + float tcPix = (bugs_wiper_clean > 0.5) ? lastCleanTime(f_coord, bugsPix) : WIPER_NONE; + speckLayer(gridSize * SPECK_SCALE, specks_density, tcPix, bugsPix, aspect, pixelUV, bugRGB, bugA, bugN, bugNA); } bugLayer(gridSize, bugs_density, 3u, pixelUV, aspect, 1.0, 1.0, 0.0, bugRGB, bugA, smear, bugN, bugNA); // now and then a really big one, on top (its own coarse grid: same 3x3 search, bigger cells) From 03766899af2a8182a142802b61350ad9cf680234 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 1 Nov 2026 21:15:58 +0100 Subject: [PATCH 042/123] Windscreen post pass in every frame: drops and haze also standing still, with any anti-aliasing The velocity target is always drawn and the motion blur pass always runs; the motion itself is blurred only when the motion blur is on and something moves (by 0 otherwise). The rain and bugs windscreens send their drops and haze through it, so they look the same with MSAA, TAA or none, moving or not. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- rendering/opengl46/opengl46renderer.cpp | 20 ++++++++------------ rendering/vulkan14/vulkan14frame.cpp | 17 ++++++++--------- utilities/Globals.h | 4 +++- 3 files changed, 19 insertions(+), 22 deletions(-) diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index 875c4f624..86c98531b 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -1821,21 +1821,17 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) if (vp.main && !vp.custom_backbuffer) // TODO: update window sizes also for extra viewports target_size = Global.fb_size; - // the camera with no vehicle of its own (freefly, the editor) blurs the world with its own movement, as a vehicle does with - // its (rendering/common/freecameramotion.h) - if (vp.main && (Global.pCamera.m_owner != nullptr)) - m_freecamera.reset(); - auto const freecameramovement{(vp.main && (Global.pCamera.m_owner == nullptr)) ? m_freecamera.next_frame(Global.pCamera.Pos) : glm::vec3{0.f}}; - // the motion blur only when something in the view moves: the vehicle of the camera, the camera with no vehicle of its own, - // or a vehicle drawn in the last frame. - // with nothing moving the velocity is zero everywhere, the blur takes a single sample of each pixel and gives back the - // image it was given, so the velocity target, its resolve and the blur are left out and the picture stays the same. - // a vehicle setting off is blurred from its second frame, when its velocity is still far below a pixel - auto const motionblur{ + // the motion is blurred only when something in the view moves: the vehicle of the camera, or a vehicle drawn in the last + // frame (a vehicle setting off is blurred from its second frame, when its velocity is still far below a pixel). the pass + // itself runs in every frame: the windscreens (mat_rain_windscreen, mat_bugs_windscreen) ask it in the velocity target for + // the picture in their drops and the haze, also standing still, with the motion blur off and with any anti-aliasing (the + // motion is then blurred by 0) + auto const moving{ Global.gfx_postfx_motionblur_enabled && (m_vehiclesmoved || (freecameramovement != glm::vec3{0.f}) || ((Global.pCamera.m_owner != nullptr) && (Global.pCamera.m_owner->get_future_movement() != glm::dvec3{0.0})))}; + auto const motionblur{Global.gfx_motion_vectors() && (vp.main_texv != nullptr)}; if (!Global.gfx_skippipeline) { @@ -2146,7 +2142,7 @@ if (!Global.gfx_skippipeline) { if (taa) gpupart("motion blur"); - model_ubs.param[0].x = m_framerate / (1.0 / Global.gfx_postfx_motionblur_shutter); + model_ubs.param[0].x = moving ? m_framerate / (1.0 / Global.gfx_postfx_motionblur_shutter) : 0.0; model_ubo->update(model_ubs); m_pfx_motionblur->apply({image, vp.main_texv.get(), vp.main_texd.get()}, vp.main2_fb.get()); } diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index 2aa65ea1a..cfac1ecdb 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -393,7 +393,8 @@ bool make_targets(vk14::allocator &Memory, vk14::deletion_queue &Deletions, std: { ok = ok && make(Targets.motion_image, velocity, sampledcolour, VK_SAMPLE_COUNT_1_BIT, "scene velocity"); } - if (motion && Global.gfx_postfx_motionblur_enabled) + // the pass of the motion blur runs in every frame: the windscreens ask it for their drops and haze (see render_post()) + if (motion) { ok = ok && make(Targets.blurred, hdr, sampledcolour, VK_SAMPLE_COUNT_1_BIT, "motion blurred", outputextent); } @@ -1684,12 +1685,7 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) render_ray_scene(vp); } - // the camera with no vehicle of its own (freefly, the editor) blurs the world with its own movement, as a vehicle does with its - // (rendering/common/freecameramotion.h) - if (vp.main && (Global.pCamera.m_owner != nullptr)) - m_freecamera.reset(); - auto const freecameramovement{(vp.main && (Global.pCamera.m_owner == nullptr)) ? m_freecamera.next_frame(Global.pCamera.Pos) : glm::vec3{0.f}}; - // the motion blur only when something in the view moves (see opengl46_renderer::Render_pass()) + // the motion blurred only when something in the view moves (see opengl46_renderer::Render_pass()); the pass runs anyway auto const motionblur{Global.gfx_postfx_motionblur_enabled && targets.motion && (m_vehiclesmoved || (freecameramovement != glm::vec3{0.f}) || ((Global.pCamera.m_owner != nullptr) && (Global.pCamera.m_owner->get_future_movement() != glm::dvec3{0.0})))}; @@ -3813,10 +3809,13 @@ void vulkan14_renderer::render_post(std::size_t const Index, bool const Motionbl store_ssr_history(Index, *hdr); } m_ssrframe = false; - if (Motionblur && targets.blurred) + // the pass of the motion blur in every frame: the windscreens (mat_rain_windscreen, mat_bugs_windscreen) ask it in the velocity + // target for the picture in their drops and the haze, also standing still, with the motion blur off and with any anti-aliasing. + // the motion is blurred only with Motionblur (by 0 otherwise) + if (targets.blurred && targets.motion_image) { vk14::draw_constants constants; - constants.data[0].x = m_framerate / (1.0 / Global.gfx_postfx_motionblur_shutter); + constants.data[0].x = Motionblur ? m_framerate / (1.0 / Global.gfx_postfx_motionblur_shutter) : 0.0; // with the frames generated by dlss each frame drawn is shown for a part of its time: the blur as much shorter (the guide of // the frame generation) if (m_generationinputs && m_viewports[Index].main) diff --git a/utilities/Globals.h b/utilities/Globals.h index f0c1909da..e69a96955 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -488,7 +488,9 @@ struct global_settings { bool gfx_bufferstreaming = true; bool gfx_postfx_motionblur_enabled = true; // the colour pass writes the velocities of the pixels: for the motion blur, the temporal anti-aliasing or dlss - bool gfx_motion_vectors() const { return gfx_postfx_motionblur_enabled || gfx_taa() || gfx_dlss(); } + // the velocity target is always drawn: the windscreens (mat_rain_windscreen, mat_bugs_windscreen) send the post-processing their + // drops and haze through it, whatever the motion blur and the anti-aliasing (not without the pipeline: no post-processing there) + bool gfx_motion_vectors() const { return ( false == gfx_skippipeline ) || gfx_postfx_motionblur_enabled; } float gfx_postfx_motionblur_shutter = 0.01f; GLenum gfx_postfx_motionblur_format = GL_RG16F; GLenum gfx_format_color = GL_RGB16F; From fd3d0811914d96a3e4d38689cbcc8b53e2ded667 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Mon, 2 Nov 2026 10:35:33 +0100 Subject: [PATCH 043/123] OpenGL 4.6: a material can have its own vertex shader, mat_.vert Fetch_Shader() links mat_.vert with the fragment shader of the material when the file is there (people animated by textures, mat_vat.vert), the common vertex.vert otherwise. The multi draw variant takes the same shader with MODEL_DRAWS. The sun shadows of such materials go through the same vertex shader with MATERIAL_SHADOW and (alpha)shadowmap.frag, with the textures and params of the material bound; in the indirect shadow pass they are drawn one by one. The depth prepass leaves them out (Prepass_Class() 0). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GXgG7F4L42c2F9sDSAJbT2 --- rendering/opengl46/opengl46renderer.cpp | 89 ++++++++++++++++++++++--- rendering/opengl46/opengl46renderer.h | 26 ++------ 2 files changed, 86 insertions(+), 29 deletions(-) diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index 86c98531b..110b44ce6 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "rendering/opengl46/opengl46renderer.h" +#include "rendering/common/shadersource.h" #include "utilities/color.h" #include "utilities/Globals.h" #include "utilities/Timer.h" @@ -32,6 +33,7 @@ http://mozilla.org/MPL/2.0/. #include "physics/vehicle.h" #include "vehicle/DynObj.h" #include +#include #include #include @@ -3302,7 +3304,19 @@ std::shared_ptr opengl46_renderer::Fetch_Shader(const std:: if (it == m_shaders.end()) { gl::shader fragment("mat_" + name + ".frag"); - gl::program *program = new gl::program({fragment, *m_vertex_shader.get()}); + gl::program *program{nullptr}; + // a material can move its vertices in a vertex shader of its own, mat_.vert (people animated by textures, + // mat_vat.vert), the others take the common one + if (std::filesystem::exists(gfx::shader_source_dir(gfx::shader_api::opengl46) + "mat_" + name + ".vert")) + { + gl::shader vertex("mat_" + name + ".vert"); + program = new gl::program({fragment, vertex}); + m_ownvertexprograms.insert(program); + } + else + { + program = new gl::program({fragment, *m_vertex_shader.get()}); + } m_shaders.insert({name, std::shared_ptr(program)}); // the variant for the multi draws of the instances, made now rather than when the instances first come into view if ((Global.gfx_gpucull == 1) && Global.gfx_gpucull_multidraw) @@ -3537,6 +3551,24 @@ void opengl46_renderer::Bind_Material_Shadow(material_handle const Material) { auto &material = m_materials.material(Material); + if (false == m_cubeshadows) + { + // a material which moves its vertices itself casts the shadow of where they are: its vertex shader, with the + // textures and the params it reads them by + if (auto *program{Material_Shadow_Program(Material, material.textures[0] != null_handle)}) + { + for (std::size_t unit = 0; unit < gl::MAX_TEXTURES; ++unit) + { + if (material.textures[unit] == null_handle) + break; + m_textures.bind(unit, material.textures[unit]); + } + memcpy(&model_ubs.param[0], &material.params[0], sizeof(model_ubs.param)); + program->bind(); + return; + } + } + if (material.textures[0] != null_handle) { m_textures.bind(0, material.textures[0]); @@ -4100,13 +4132,11 @@ opengl46_renderer::indirect_counts opengl46_renderer::Render_Instances_Indirect_ for( std::size_t index = 0; index < count; ) { auto const &draw { m_indirectdraws[ index ] }; auto const texture { Indirect_Shadow_Texture( draw.material ) }; - if( ( texture != null_handle ) && ( false == m_textures.mark_as_used( texture ).bind( 0 ) ) ) { - // a texture which isn't there (yet) would leave the one bound before to the alpha test; no shadow until it is - ++index; - continue; - } + // the materials with a vertex shader of their own are drawn one by one, with it (Bind_Material_Shadow()) + auto const ownvertex = [ this ]( material_handle const Material ) { + return ( false == m_cubeshadows ) && ( Material_Shadow_Program( Material, Indirect_Shadow_Texture( Material ) != null_handle ) != nullptr ); }; auto *multidrawprogram { - m_indirectmultidraw ? + ( m_indirectmultidraw && ( false == ownvertex( draw.material ) ) ) ? ( m_cubeshadows ? m_localshadows.multidraw_program( texture != null_handle ) : ( texture != null_handle ? m_alpha_shadow_multidraw_shader.get() : m_shadow_multidraw_shader.get() ) ) : @@ -4118,7 +4148,8 @@ opengl46_renderer::indirect_counts opengl46_renderer::Render_Instances_Indirect_ && ( m_indirectdraws[ last ].group == draw.group ) && ( m_indirectdraws[ last ].type == draw.type ) && ( m_indirectcommands[ last ].indexed == m_indirectcommands[ index ].indexed ) - && ( Indirect_Shadow_Texture( m_indirectdraws[ last ].material ) == texture ) ) { + && ( Indirect_Shadow_Texture( m_indirectdraws[ last ].material ) == texture ) + && ( false == ownvertex( m_indirectdraws[ last ].material ) ) ) { ++last; } multidrawprogram->bind(); @@ -4129,8 +4160,10 @@ opengl46_renderer::indirect_counts opengl46_renderer::Render_Instances_Indirect_ index = last; } else { - Bind_Material_Shadow( draw.material ); + // the block of the draw first: Bind_Material_Shadow() puts the params of the material in it, for the materials which + // read them in their vertex shader model_ubs = draw.ubs; + Bind_Material_Shadow( draw.material ); model_ubo->update( model_ubs ); m_geometry.draw_indirect( draw.geometry, m_indirectcull->draw_command_offset( Set, index ) ); ++counts.draws; @@ -4195,7 +4228,14 @@ gl::program *opengl46_renderer::Multidraw_Program( gl::program const *Program ) if( shader.second.get() != Program ) { continue; } try { gl::shader fragment( "mat_" + shader.first + ".frag", "#define MODEL_DRAWS 1\n" ); - variant = std::make_unique( std::vector>{ fragment, *m_vertex_multidraw_shader } ); + if( m_ownvertexprograms.count( Program ) > 0 ) { + // the vertex shader of the material itself, in its variant of the multi draws + gl::shader vertex( "mat_" + shader.first + ".vert", "#define MODEL_DRAWS 1\n" ); + variant = std::make_unique( std::vector>{ fragment, vertex } ); + } + else { + variant = std::make_unique( std::vector>{ fragment, *m_vertex_multidraw_shader } ); + } } catch( gl::shader_exception const &e ) { ErrorLog( "material " + shader.first + " drawn without multi draws: " + std::string( e.what() ) ); @@ -4207,6 +4247,35 @@ gl::program *opengl46_renderer::Multidraw_Program( gl::program const *Program ) return result; } +gl::program *opengl46_renderer::Material_Shadow_Program( material_handle const Material, bool const Alphatest ) +{ + if( Material == null_handle ) { return nullptr; } + auto const &material { m_materials.material( Material ) }; + if( ( false == material.is_good ) || ( material.shader == nullptr ) ) { return nullptr; } + auto const *program { static_cast( material.shader.get() ) }; + if( m_ownvertexprograms.count( program ) == 0 ) { return nullptr; } + auto &programs { m_materialshadowprograms[ Alphatest ? 1 : 0 ] }; + auto const lookup { programs.find( program ) }; + if( lookup != programs.end() ) { return lookup->second.get(); } + + std::unique_ptr shadow; + for( auto const &shader : m_shaders ) { + if( shader.second.get() != program ) { continue; } + try { + gl::shader vertex( "mat_" + shader.first + ".vert", "#define MATERIAL_SHADOW 1\n" ); + gl::shader fragment( Alphatest ? "alphashadowmap.frag" : "shadowmap.frag" ); + shadow = std::make_unique( std::vector>{ vertex, fragment } ); + } + catch( gl::shader_exception const &e ) { + ErrorLog( "material " + shader.first + " casts its shadow in the pose of the model: " + std::string( e.what() ) ); + } + break; + } + auto *result { shadow.get() }; + programs.emplace( program, std::move( shadow ) ); + return result; +} + // depth of the whole opaque scene of the colour pass, before its colour. the same walk as the colour pass makes (the cab drawn // early, then the region), so the same things are seen at the same levels of detail; the programs of the depth prepass draw // them (Bind_Material(), draw()), with the depth a little farther than the surface like the prepass of the instances, so the diff --git a/rendering/opengl46/opengl46renderer.h b/rendering/opengl46/opengl46renderer.h index 585f6f355..f4144bd52 100644 --- a/rendering/opengl46/opengl46renderer.h +++ b/rendering/opengl46/opengl46renderer.h @@ -413,6 +413,10 @@ class opengl46_renderer : public gfx_renderer, public gfx::scene_walk { // the variant of a material program for multi draws (built with MODEL_DRAWS), made the first time it's asked for. // nullptr if there's none (a program not fetched by Fetch_Shader(), or one which didn't compile) gl::program *Multidraw_Program( gl::program const *Program ); + // the program of the sun shadows of a material which moves its vertices in its own vertex shader (mat_.vert, see + // Fetch_Shader()): that shader with MATERIAL_SHADOW and the shadow fragment shader (Alphatest: alphashadowmap.frag). + // nullptr for the materials of the common vertex shader, which the shadow programs draw as they are + gl::program *Material_Shadow_Program( material_handle const Material, bool const Alphatest ); // how the depth prepass treats the material: 0 left out, 1 drawn without alpha test, 2 with the alpha test of the diffuse texture int Prepass_Class( material_handle const Material ); // depth of the whole opaque scene of the colour pass, before its colour (Global.gfx_depthprepass_scene): the colour pass @@ -651,25 +655,9 @@ class opengl46_renderer : public gfx_renderer, public gfx::scene_walk { // programs of the multi draws: the vertex shader of the materials, variants of the material programs, of the depth prepass std::unique_ptr m_vertex_multidraw_shader; std::unordered_map> m_multidrawprograms; - // Prewarm_Shaders(): the programs to draw with, the next one, and a small target of the formats of the colour pass with a - // triangle of no area to draw - struct shader_prewarm - { - bool started{ false }; - std::vector programs; - std::size_t next{ 0 }; - std::size_t water{ 0 }; // programs of the windscreen water made ahead - bool water_done{ false }; - std::unique_ptr color; - std::unique_ptr depth; - std::unique_ptr motion; - std::unique_ptr target; - // one model block for the variants of the multi draws, which read theirs from a storage buffer (MODEL_DRAW_SSBO_BINDING) - std::unique_ptr draws; - gfx::geometrybank_handle bank{}; - gfx::geometry_handle triangle{}; - }; - shader_prewarm m_prewarm; + // the material programs with a vertex shader of their own (mat_.vert), and their programs of the sun shadows + std::unordered_set m_ownvertexprograms; + std::unordered_map> m_materialshadowprograms[ 2 ]; std::unique_ptr m_prepass_multidraw_shader; std::unique_ptr m_prepass_alpha_multidraw_shader; std::unique_ptr m_shadow_multidraw_shader; // and of the sun shadows From f3b70c388625f40bc8a2ecf13984fd45a837919b Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Mon, 2 Nov 2026 15:57:14 +0100 Subject: [PATCH 044/123] OpenGL 4.6: the scene block carries the rotation of the shadow pass's own camera The sun cascades and the headlight shadows draw with the camera of the light, but inv_view stayed the one of the color pass. mat_vat.vert takes the turn of a model in the world from inv_view and the modelview, so in the shadow passes it saw another turn, gave the animation another moment, and the shadows of the animated people and animals lagged behind them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GXgG7F4L42c2F9sDSAJbT2 --- rendering/opengl46/opengl46renderer.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index 110b44ce6..7c41b100c 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -2291,6 +2291,8 @@ if (!Global.gfx_skippipeline) glViewport(0, 0, m_shadowbuffersize, m_shadowbuffersize); auto csmstageboundaries { Shadow_Fixed_Splits() }; + // the rotation of the camera of the view, given back to the scene block after the cascades + auto const colorinvview { scene_ubs.inv_view }; // the cascades fitted to the depth of the view (gfx.shadow.sdsm) go between the distances of its pixels, each map // covering the area of the pixels its cascade takes std::array>, gl::MAX_CASCADES> fitareas; @@ -2318,6 +2320,9 @@ if (!Global.gfx_skippipeline) setup_matrices(); scene_ubs.projection = OpenGLMatrices.data( GL_PROJECTION ); + // the rotation of the camera of this pass (the sun's): the shaders which put the model in the world (mat_vat.vert, the + // moment of the animation of every one of the people from its turn) see the same turn as in the color pass + scene_ubs.inv_view = glm::inverse( glm::mat4{ glm::mat3{ m_renderpass.pass_camera.modelview() } } ); auto const csmstagezfar { (csmstageboundaries[ idx + 1 ]) + ( m_shadowpass.size() - idx ) }; // we can fairly safely add some extra padding in the early stages @@ -2336,6 +2341,8 @@ if (!Global.gfx_skippipeline) } } m_shadow_fb->unbind(); + scene_ubs.inv_view = colorinvview; + scene_ubo->update( scene_ubs ); glDebug("rendermode::shadows end"); @@ -6941,7 +6948,10 @@ void opengl46_renderer::Render_headlight_shadow(std::size_t const Slot, light_ar camera.update_frustum(glm::perspective(fieldofview, 1.f, nearplane, reach)); setup_matrices(); auto const colorprojection{scene_ubs.projection}; + auto const colorinvview{scene_ubs.inv_view}; scene_ubs.projection = projection; + // the rotation of the projector, as the one of the sun in its shadows (see rendermode::shadows) + scene_ubs.inv_view = glm::inverse(glm::mat4{glm::mat3{camera.modelview()}}); scene_ubo->update(scene_ubs); m_localshadows.begin_headlight(Slot, projector, rotation, projection, Light.direction, m_framestamp); @@ -6957,6 +6967,7 @@ void opengl46_renderer::Render_headlight_shadow(std::size_t const Slot, light_ar m_shadowskipvehicle = nullptr; m_localshadows.end_headlight(static_cast(m_renderpass.draw_stats.drawcalls)); scene_ubs.projection = colorprojection; + scene_ubs.inv_view = colorinvview; scene_ubo->update(scene_ubs); m_renderpass = m_colorpass; glPolygonMode(GL_FRONT_AND_BACK, Global.bWireFrame ? GL_LINE : GL_FILL); From 2b415fdb167698b8ceded566b407617480d36953 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Mon, 2 Nov 2026 16:37:48 +0100 Subject: [PATCH 045/123] Textures with the trait r are kept as they are; the scene block carries the place of the camera of the pass A texture named with :r (the frames of the animations baked into textures, mat_vat) is never scaled down to maxtexturesize nor compressed by the driver with compresstex: its texels are data, not a picture. gl::scene_ubs::camera_hi, camera_lo: the place of the camera of the pass in the world, which the models are drawn relative to, split so both parts are exact in floats. Set with inv_view in every pass that has it (the color pass, the faces of the environment map, the sun cascades, the headlight shadows, the previews). mat_vat.vert takes the place of a model in the world from them, so models standing turned the same way still get a moment of the animation of their own, the same in every pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GXgG7F4L42c2F9sDSAJbT2 --- gl/ubo.h | 7 +++++- model/Texture.cpp | 9 ++++++-- rendering/opengl46/opengl46renderer.cpp | 30 ++++++++++++++++++++----- 3 files changed, 38 insertions(+), 8 deletions(-) diff --git a/gl/ubo.h b/gl/ubo.h index 1d6c4d1ab..0c41d9a87 100644 --- a/gl/ubo.h +++ b/gl/ubo.h @@ -201,9 +201,14 @@ namespace gl // wiper_timer_return (mat_bugs_windscreen: what hit the glass since a blade went over it); -1 not known glm::vec4 wiper_bugs_out; glm::vec4 wiper_bugs_return; + // the place of the camera of the pass in the world, which the models are drawn relative to: xyz of camera_hi the place + // rounded down to whole 64 metres, of camera_lo the rest (both exact in floats), w unused. mat_vat.vert puts a model in the + // world with them, inv_view and its modelview (the moment of its animation from its place) + glm::vec4 camera_hi; + glm::vec4 camera_lo; }; - static_assert(sizeof(scene_ubs) == 960 + 80 * MAX_HEADLIGHT_SHADOWS + 96 * MAX_CAB_PROBE_LAMPS, "bad size of ubs"); + static_assert(sizeof(scene_ubs) == 992 + 80 * MAX_HEADLIGHT_SHADOWS + 96 * MAX_CAB_PROBE_LAMPS, "bad size of ubs"); const size_t MAX_PARAMS = 3; diff --git a/model/Texture.cpp b/model/Texture.cpp index efd9e711b..d058ca9b2 100644 --- a/model/Texture.cpp +++ b/model/Texture.cpp @@ -1258,7 +1258,8 @@ texture_source::load_TGA() { } downsize( GL_BGRA ); - if( data_width > Global.CurrentMaxTextureSize || data_height > Global.CurrentMaxTextureSize ) { + if( ( false == contains( traits, 'r' ) ) + && ( data_width > Global.CurrentMaxTextureSize || data_height > Global.CurrentMaxTextureSize ) ) { // for non-square textures there's currently possibility the scaling routine will have to abort // before it gets all work done data_state = resource_state::failed; @@ -1430,7 +1431,7 @@ opengl_texture::create( bool const Static ) { // uncompressed texture data. have the gfx card do the compression as it sees fit ::glTexImage2D( target, 0, - Global.compress_tex ? compressed_format : internal_format, + ( Global.compress_tex && ( false == contains( traits, 'r' ) ) ) ? compressed_format : internal_format, data_width, data_height, 0, data_format, data_type, (GLubyte *)&data[ 0 ] ); } @@ -1683,6 +1684,10 @@ opengl_texture::set_filtering() const void texture_source::downsize( GLuint const Format ) { + if( contains( traits, 'r' ) ) { + // raw data (trait r: the frames of the animations baked into textures, mat_vat): never scaled down + return; + } while( data_width > Global.CurrentMaxTextureSize || data_height > Global.CurrentMaxTextureSize ) { // scale down the base texture, if it's larger than allowed maximum // NOTE: scaling is uniform along both axes, meaning non-square textures can drop below the maximum diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index 7c41b100c..7953056c1 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -35,10 +35,16 @@ http://mozilla.org/MPL/2.0/. #include #include -#include -#include -#include -#include +namespace +{ +// the camera of a pass in the world for the scene block (gl::scene_ubs::camera_hi, camera_lo) +void scene_camera_place(gl::scene_ubs &Ubs, glm::dvec3 const &Place) +{ + auto const high{glm::floor(Place / 64.0) * 64.0}; + Ubs.camera_hi = glm::vec4{glm::vec3{high}, 0.f}; + Ubs.camera_lo = glm::vec4{glm::vec3{Place - high}, 0.f}; +} +} // namespace //#define EU07_DEBUG_OPENGL @@ -1754,6 +1760,7 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) m_skyocclusion.setup_scene(scene_ubs, m_colorpass.pass_camera.position()); scene_ubs.projection = OpenGLMatrices.data(GL_PROJECTION); scene_ubs.inv_view = glm::inverse( glm::mat4{ glm::mat3{ m_colorpass.pass_camera.modelview() } } ); + scene_camera_place( scene_ubs, m_colorpass.pass_camera.position() ); scene_ubo->update(scene_ubs); scene_ubo->bind_uniform(); // the water on the windscreens of the cab: a step of its simulation once a frame, its storage for the glasses of every view @@ -1933,6 +1940,7 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) scene_ubs.projection = OpenGLMatrices.data(GL_PROJECTION); // back to the rotation of the camera after the faces of the environment map, which are drawn with their own scene_ubs.inv_view = glm::inverse(glm::mat4{glm::mat3{m_colorpass.pass_camera.modelview()}}); + scene_camera_place(scene_ubs, m_colorpass.pass_camera.position()); scene_ubo->update(scene_ubs); Render(&simulation::Environment); @@ -2293,6 +2301,8 @@ if (!Global.gfx_skippipeline) auto csmstageboundaries { Shadow_Fixed_Splits() }; // the rotation of the camera of the view, given back to the scene block after the cascades auto const colorinvview { scene_ubs.inv_view }; + auto const colorcamerahi { scene_ubs.camera_hi }; + auto const colorcameralo { scene_ubs.camera_lo }; // the cascades fitted to the depth of the view (gfx.shadow.sdsm) go between the distances of its pixels, each map // covering the area of the pixels its cascade takes std::array>, gl::MAX_CASCADES> fitareas; @@ -2323,6 +2333,7 @@ if (!Global.gfx_skippipeline) // the rotation of the camera of this pass (the sun's): the shaders which put the model in the world (mat_vat.vert, the // moment of the animation of every one of the people from its turn) see the same turn as in the color pass scene_ubs.inv_view = glm::inverse( glm::mat4{ glm::mat3{ m_renderpass.pass_camera.modelview() } } ); + scene_camera_place( scene_ubs, m_renderpass.pass_camera.position() ); auto const csmstagezfar { (csmstageboundaries[ idx + 1 ]) + ( m_shadowpass.size() - idx ) }; // we can fairly safely add some extra padding in the early stages @@ -2342,6 +2353,8 @@ if (!Global.gfx_skippipeline) } m_shadow_fb->unbind(); scene_ubs.inv_view = colorinvview; + scene_ubs.camera_hi = colorcamerahi; + scene_ubs.camera_lo = colorcameralo; scene_ubo->update( scene_ubs ); glDebug("rendermode::shadows end"); @@ -2379,6 +2392,7 @@ if (!Global.gfx_skippipeline) scene_ubs.projection = OpenGLMatrices.data(GL_PROJECTION); // world space directions of the shading of the face (the sky, the directional ambient light) scene_ubs.inv_view = glm::inverse(glm::mat4{glm::mat3{m_renderpass.pass_camera.modelview()}}); + scene_camera_place(scene_ubs, m_renderpass.pass_camera.position()); scene_ubo->update(scene_ubs); Render(&simulation::Environment); // the passes after this one expect the state the opaque scenery left behind (depth writes on, no blending) @@ -6135,6 +6149,7 @@ void opengl46_renderer::Preview_Color(TAnimModel *Instance, float const Squaredi scene_ubs.projection = OpenGLMatrices.data(GL_PROJECTION); scene_ubs.inv_view = glm::inverse(glm::mat4{glm::mat3{View}}); + scene_camera_place(scene_ubs, Eye); scene_ubs.time = 0.f; for (auto idx = 0; idx < m_shadowpass.size(); ++idx) { @@ -6949,9 +6964,12 @@ void opengl46_renderer::Render_headlight_shadow(std::size_t const Slot, light_ar setup_matrices(); auto const colorprojection{scene_ubs.projection}; auto const colorinvview{scene_ubs.inv_view}; + auto const colorcamerahi{scene_ubs.camera_hi}; + auto const colorcameralo{scene_ubs.camera_lo}; scene_ubs.projection = projection; - // the rotation of the projector, as the one of the sun in its shadows (see rendermode::shadows) + // the rotation and the place of the projector, as the ones of the sun in its shadows (see rendermode::shadows) scene_ubs.inv_view = glm::inverse(glm::mat4{glm::mat3{camera.modelview()}}); + scene_camera_place(scene_ubs, camera.position()); scene_ubo->update(scene_ubs); m_localshadows.begin_headlight(Slot, projector, rotation, projection, Light.direction, m_framestamp); @@ -6968,6 +6986,8 @@ void opengl46_renderer::Render_headlight_shadow(std::size_t const Slot, light_ar m_localshadows.end_headlight(static_cast(m_renderpass.draw_stats.drawcalls)); scene_ubs.projection = colorprojection; scene_ubs.inv_view = colorinvview; + scene_ubs.camera_hi = colorcamerahi; + scene_ubs.camera_lo = colorcameralo; scene_ubo->update(scene_ubs); m_renderpass = m_colorpass; glPolygonMode(GL_FRONT_AND_BACK, Global.bWireFrame ? GL_LINE : GL_FILL); From 0df374a5e960f629f86ce0f746e18787abb039dc Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Mon, 2 Nov 2026 19:30:41 +0100 Subject: [PATCH 046/123] Vulkan 1.4: a material can have its own vertex shader, mat_.vert, also in the sun shadows As in the OpenGL 4.6 renderer: Fetch_Shader() takes shaders/vk14/mat_.vert when the file is there (the animals and people animated by textures, mat_vat.vert), vertex.vert otherwise; the multi draw variant is made of the same one. Such a material gets the programs of its sun shadows with it: its vertex shader with MATERIAL_SHADOW and (alpha)shadowmap.frag, drawn with all its textures and its params, also from the gpu culling (the draws of one such material go together). The cube maps of the lamps keep their programs, the depth prepass leaves these materials out (prepass class 0). The scene block carries the rotation and the place of the camera of each sun cascade and headlight map (inv_view, camera_hi, camera_lo, gl::set_camera_place()), and those of the view in the colour pass, so the shaders see a model in the world the same way in every pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GXgG7F4L42c2F9sDSAJbT2 --- gl/ubo.h | 8 +++ rendering/vulkan14/vulkan14context.h | 3 ++ rendering/vulkan14/vulkan14frame.cpp | 14 +++++ rendering/vulkan14/vulkan14indirect.cpp | 31 +++++++---- rendering/vulkan14/vulkan14lamps.cpp | 9 ++++ rendering/vulkan14/vulkan14renderer.h | 2 + rendering/vulkan14/vulkan14scene.cpp | 69 ++++++++++++++++++++++++- 7 files changed, 123 insertions(+), 13 deletions(-) diff --git a/gl/ubo.h b/gl/ubo.h index 0c41d9a87..2f6955107 100644 --- a/gl/ubo.h +++ b/gl/ubo.h @@ -210,6 +210,14 @@ namespace gl static_assert(sizeof(scene_ubs) == 992 + 80 * MAX_HEADLIGHT_SHADOWS + 96 * MAX_CAB_PROBE_LAMPS, "bad size of ubs"); + // the camera of a pass in the world for the scene block (scene_ubs::camera_hi, camera_lo) + inline void set_camera_place(scene_ubs &Ubs, glm::dvec3 const &Place) + { + auto const high{glm::floor(Place / 64.0) * 64.0}; + Ubs.camera_hi = glm::vec4{glm::vec3{high}, 0.f}; + Ubs.camera_lo = glm::vec4{glm::vec3{Place - high}, 0.f}; + } + const size_t MAX_PARAMS = 3; struct model_ubs diff --git a/rendering/vulkan14/vulkan14context.h b/rendering/vulkan14/vulkan14context.h index f3ef48acc..26010523c 100644 --- a/rendering/vulkan14/vulkan14context.h +++ b/rendering/vulkan14/vulkan14context.h @@ -515,6 +515,9 @@ struct scene_state // the depth prepass of the scene (the stage P3): without and with the alpha test, and which of them a program of a material takes std::shared_ptr prepass, prepass_alpha; std::unordered_map prepass_classes; + // the sun shadows of the materials which move their vertices in a vertex shader of their own (mat_.vert, the animals + // and people animated by textures): by the program of the material, without and with the alpha test; made with the program + std::unordered_map, 2>> own_shadows; // the post-processing, by the fragment shader std::unordered_map> post_fragments; std::shared_ptr quad; diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index cfac1ecdb..9e3c05ca0 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -1735,6 +1735,7 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) scene.skyocclusion.setup_scene(scene_ubs, m_colorpass.pass_camera.position()); scene_ubs.projection = OpenGLMatrices.data(GL_PROJECTION); scene_ubs.inv_view = glm::inverse(glm::mat4{glm::mat3{m_colorpass.pass_camera.modelview()}}); + gl::set_camera_place(scene_ubs, m_colorpass.pass_camera.position()); setup_shadow_matrices(); upload_scene_block(); if (clustered) @@ -1770,6 +1771,7 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) walk_blending(true); scene_ubs.projection = OpenGLMatrices.data(GL_PROJECTION); scene_ubs.inv_view = glm::inverse(glm::mat4{glm::mat3{m_colorpass.pass_camera.modelview()}}); + gl::set_camera_place(scene_ubs, m_colorpass.pass_camera.position()); upload_scene_block(); render_environment(&simulation::Environment); @@ -2462,6 +2464,10 @@ void vulkan14_renderer::render_shadows(viewport_config &Viewport) ensure_cull(); } static char const *const parts[] = {"sun shadows 1", "sun shadows 2", "sun shadows 3"}; + // the camera of the view, given back to the scene block after the cascades (walk_cascade() puts the one of each in it) + auto const colorinvview{scene_ubs.inv_view}; + auto const colorcamerahi{scene_ubs.camera_hi}; + auto const colorcameralo{scene_ubs.camera_lo}; for (std::size_t idx = 0; idx < m_shadowpass.size(); ++idx) { ctx.passes.begin_pass(parts[idx], {vk14::use_of(*scene.shadow_map, VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL, depth_stage, depth_access)}); @@ -2485,6 +2491,9 @@ void vulkan14_renderer::render_shadows(viewport_config &Viewport) } ctx.passes.end_pass(); } + scene_ubs.inv_view = colorinvview; + scene_ubs.camera_hi = colorcamerahi; + scene_ubs.camera_lo = colorcameralo; vk14::barriers(commands, {vk14::use_of(*scene.shadow_map, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, sampled_stage, sampled_access)}); } @@ -2509,6 +2518,10 @@ void vulkan14_renderer::walk_cascade(std::size_t const Index) start_draws(scene.shadow_formats, static_cast(scene.shadow_size), static_cast(scene.shadow_size), vk14::scene_state::set_plain, true); m_shadowcascade = static_cast(Index); walk_blending(false); + // the rotation and the place of the camera of the cascade (the sun's): the shaders which put the model in the world (mat_vat.vert, + // the moment of the animation of every one of the animals and people from its place and turn) see the same as in the colour pass + scene_ubs.inv_view = glm::inverse(glm::mat4{glm::mat3{m_renderpass.pass_camera.modelview()}}); + gl::set_camera_place(scene_ubs, m_renderpass.pass_camera.position()); upload_scene_block(); if (m_shadowcolor != colors::white) { @@ -2673,6 +2686,7 @@ void vulkan14_renderer::render_reflection_face(viewport_config &Viewport) walk_blending(true); scene_ubs.projection = OpenGLMatrices.data(GL_PROJECTION); scene_ubs.inv_view = glm::inverse(glm::mat4{glm::mat3{m_renderpass.pass_camera.modelview()}}); + gl::set_camera_place(scene_ubs, m_renderpass.pass_camera.position()); upload_scene_block(); // the sky and the clouds alone: the scenery is reflected by the screen space reflections (gfx.ssr) and the ray tracing, the // environment map gives what they don't find diff --git a/rendering/vulkan14/vulkan14indirect.cpp b/rendering/vulkan14/vulkan14indirect.cpp index c568306fd..c97eec716 100644 --- a/rendering/vulkan14/vulkan14indirect.cpp +++ b/rendering/vulkan14/vulkan14indirect.cpp @@ -630,26 +630,35 @@ vulkan14_renderer::indirect_counts vulkan14_renderer::draw_indirect_shadow(vk14: { auto const &entry{m_indirectdraws[index]}; auto const texture{Indirect_Shadow_Texture(entry.material)}; - auto &program{m_cubeshadows ? (texture != null_handle ? *scene.cube_alpha_shadow : *scene.cube_shadow) : (texture != null_handle ? *scene.alpha_shadow : *scene.shadow)}; - auto pending{false}; - auto *multidraw{m_indirectmultidraw ? multidraw_program(program, pending) : nullptr}; - if (pending) - { - // the shaders of its multi draws are being compiled: the draw is left out till they're there - ++index; - continue; - } + // a material which moves its vertices itself: its own program, with its textures; the draws of it alone go together + auto *own{own_shadow_program(entry.material)}; + auto &program{own != nullptr ? *own : + m_cubeshadows ? (texture != null_handle ? *scene.cube_alpha_shadow : *scene.cube_shadow) : + (texture != null_handle ? *scene.alpha_shadow : *scene.shadow)}; + auto *multidraw{m_indirectmultidraw ? multidraw_program(program) : nullptr}; auto last{index + 1}; if (multidraw != nullptr) { // the draws which follow in the same bank and of the same primitive, with the same texture for the alpha test while ((last < count) && (last - index < longest) && (m_indirectdraws[last].group == entry.group) && (m_indirectdraws[last].type == entry.type) && - (m_indirectcommands[last].indexed == m_indirectcommands[index].indexed) && (Indirect_Shadow_Texture(m_indirectdraws[last].material) == texture)) + (m_indirectcommands[last].indexed == m_indirectcommands[index].indexed) && (Indirect_Shadow_Texture(m_indirectdraws[last].material) == texture) && + (own_shadow_program(m_indirectdraws[last].material) == own) && ((own == nullptr) || (m_indirectdraws[last].material == entry.material))) { ++last; } } - if (texture != null_handle) + if (own != nullptr) + { + auto const &textures{m_materials.material(entry.material).textures}; + for (std::size_t unit = 0; unit < gl::MAX_TEXTURES; ++unit) + { + if (textures[unit] != null_handle) + { + walk_texture(unit, textures[unit]); + } + } + } + else if (texture != null_handle) { walk_texture(0, texture); } diff --git a/rendering/vulkan14/vulkan14lamps.cpp b/rendering/vulkan14/vulkan14lamps.cpp index 9857d5108..69f87d463 100644 --- a/rendering/vulkan14/vulkan14lamps.cpp +++ b/rendering/vulkan14/vulkan14lamps.cpp @@ -369,7 +369,13 @@ void vulkan14_renderer::render_headlight_shadow(std::size_t const Slot, light_ar camera.update_frustum(glm::perspective(fieldofview, 1.f, nearplane, reach)); setup_matrices(); auto const colorprojection{scene_ubs.projection}; + auto const colorinvview{scene_ubs.inv_view}; + auto const colorcamerahi{scene_ubs.camera_hi}; + auto const colorcameralo{scene_ubs.camera_lo}; scene_ubs.projection = projection; + // the rotation and the place of the projector, as the ones of the sun in its shadows (walk_cascade()) + scene_ubs.inv_view = glm::inverse(glm::mat4{glm::mat3{camera.modelview()}}); + gl::set_camera_place(scene_ubs, camera.position()); lamps.begin_headlight(Slot, projector, rotation, projection, Light.direction, m_framestamp); begin_local_shadow_rendering(); // the instances culled on the gpu, each slot with a culling of its own; the occupied cab, within the reach @@ -391,6 +397,9 @@ void vulkan14_renderer::render_headlight_shadow(std::size_t const Slot, light_ar lamps.end_headlight(static_cast(m_renderpass.draw_stats.drawcalls)); } scene_ubs.projection = colorprojection; + scene_ubs.inv_view = colorinvview; + scene_ubs.camera_hi = colorcamerahi; + scene_ubs.camera_lo = colorcameralo; m_renderpass = m_colorpass; } diff --git a/rendering/vulkan14/vulkan14renderer.h b/rendering/vulkan14/vulkan14renderer.h index 1ba2dcbde..4d53a3c43 100644 --- a/rendering/vulkan14/vulkan14renderer.h +++ b/rendering/vulkan14/vulkan14renderer.h @@ -419,6 +419,8 @@ class vulkan14_renderer : public gfx_renderer, public gfx::scene_walk void update_clusters(glm::ivec2 const &Targetsize); // which program of the depth prepass stands for the program of the material: 0 none, 1 without the alpha test, 2 with it int prepass_class(material_handle const Material); + // the program of the sun shadows of a material with a vertex shader of its own (mat_.vert), nullptr for the others + vk14::scene_program *own_shadow_program(material_handle const Material) const; // the depth of the whole opaque scene of the colour pass of the main viewport before its colour, for the contact shadows // (Contactonly: with them alone) or for itself (gfx.depthprepass.scene), and the contact shadows set up to read it void render_scene_depth(std::size_t const Viewport, glm::mat4 const &Future); diff --git a/rendering/vulkan14/vulkan14scene.cpp b/rendering/vulkan14/vulkan14scene.cpp index d6b9e5f76..d640b5335 100644 --- a/rendering/vulkan14/vulkan14scene.cpp +++ b/rendering/vulkan14/vulkan14scene.cpp @@ -1441,10 +1441,14 @@ std::shared_ptr vulkan14_renderer::Fetch_Shader(std::string } // throws gfx::shader_exception, which the materials catch auto program{std::make_shared()}; - program->vertex = m_context->shaders.get("vertex.vert"); + // a material can move its vertices in a vertex shader of its own, mat_.vert (animals and people animated by textures, + // mat_vat.vert), the others take the common one + auto const ownvertex{std::filesystem::exists(gfx::shader_source_dir(gfx::shader_api::vulkan14) + "mat_" + name + ".vert")}; + auto const vertexname{ownvertex ? "mat_" + name + ".vert" : std::string("vertex.vert")}; + program->vertex = m_context->shaders.get(vertexname); program->fragment = m_context->shaders.get("mat_" + name + ".frag"); program->fragment_name = "mat_" + name + ".frag"; - program->vertex_name = "vertex.vert"; + program->vertex_name = vertexname; program->vertices = vk14::vertex_kind::scene; program->name = "mat_" + name; // the directives of the material, of both stages as the opengl program has them @@ -1453,10 +1457,51 @@ std::shared_ptr vulkan14_renderer::Fetch_Shader(std::string program->texture_conf.insert(stage->source.texture_conf.begin(), stage->source.texture_conf.end()); program->param_conf.insert(stage->source.param_conf.begin(), stage->source.param_conf.end()); } + if (ownvertex) + { + // its sun shadows go through the same vertex shader (MATERIAL_SHADOW), so they are cast by where the vertices are + std::array, 2> shadows; + for (auto alpha = 0; alpha < 2; ++alpha) + { + auto shadow{std::make_shared()}; + char const *fragment{alpha ? "alphashadowmap.frag" : "shadowmap.frag"}; + shadow->defines = "#define MATERIAL_SHADOW 1\n"; + shadow->vertex = m_context->shaders.get(vertexname, shadow->defines); + shadow->fragment = m_context->shaders.get(fragment, shadow->defines); + shadow->vertex_name = vertexname; + shadow->fragment_name = fragment; + shadow->vertices = vk14::vertex_kind::scene; + shadow->name = vertexname + " (shadow) + " + fragment; + shadows[alpha] = std::move(shadow); + } + m_context->scene.own_shadows.emplace(program.get(), std::move(shadows)); + } materials.emplace(name, program); return program; } +// the program of the sun shadows of a material with a vertex shader of its own, nullptr for the others (and in the cube maps of +// the lamps, which keep their own programs) +vk14::scene_program *vulkan14_renderer::own_shadow_program(material_handle const Material) const +{ + if ((Material == null_handle) || m_cubeshadows || (false == bool(m_context))) + { + return nullptr; + } + auto const &material{m_materials.material(Material)}; + if ((false == material.is_good) || (material.shader == nullptr)) + { + return nullptr; + } + auto const &shadows{m_context->scene.own_shadows}; + auto const lookup{shadows.find(material.shader.get())}; + if (lookup == shadows.end()) + { + return nullptr; + } + return lookup->second[material.textures[0] != null_handle ? 1 : 0].get(); +} + std::string vulkan14_renderer::Shader_Name(std::shared_ptr const &Program) const { if (m_context) @@ -1660,6 +1705,12 @@ void vulkan14_renderer::walk_material(material_handle const Material, TSubModel void vulkan14_renderer::walk_shadow_material(material_handle const Material) { + // a material which moves its vertices itself reads its params in the vertex shader of its shadow too + auto *own{own_shadow_program(Material)}; + if (own != nullptr) + { + std::memcpy(&model_ubs.param[0], &m_materials.material(Material).params[0], sizeof(model_ubs.param)); + } if (m_indirectrecording) { // the walk of the groups of the gpu culling of a shadow pass only notes the material @@ -1669,6 +1720,20 @@ void vulkan14_renderer::walk_shadow_material(material_handle const Material) } auto &draw{*m_draw}; auto &scene{m_context->scene}; + if (own != nullptr) + { + // its textures (the alpha test and the ones its vertex shader reads) and its program + auto const &textures{m_materials.material(Material).textures}; + for (std::size_t unit = 0; unit < gl::MAX_TEXTURES; ++unit) + { + if (textures[unit] != null_handle) + { + walk_texture(unit, textures[unit]); + } + } + draw.program = own; + return; + } // the cube maps of the lamps with programs of their own (the faces drawn by multiview) if (auto const texture{Indirect_Shadow_Texture(Material)}; texture != null_handle) { From 869df1651e321657be1c8c3037694c416f419620 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 23:09:33 +0100 Subject: [PATCH 047/123] Rain and bugs windscreens: the shaders as tested in the game [skip ci] - mat_rain_windscreen (v49): longer wind rivulets of different widths, no beads gathered by the blades - mat_bugs_windscreen: the scene blurred only under the see-through parts of a bug, no ring around it - rain_windscreen_haze: exact codes of the drops (MSAA averaged edges are neither a drop nor haze), the lights in the drops read in a round footprint and fading away from the light - postfx_taa / postfx_motionblur: the mark of the picture the TAA blurred is negative (below any alpha of the scene; the TAA lock takes 0) - vk14 postfx_dlss_motion: the codes of the windscreens aren't motion Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_bugs_windscreen.frag | 20 ++++---- shaders/ogl46/mat_rain_windscreen.frag | 67 +++++++++++++++++++++---- shaders/ogl46/postfx_motionblur.frag | 4 +- shaders/ogl46/postfx_taa.frag | 2 +- shaders/ogl46/rain_windscreen_haze.glsl | 51 ++++++++++++++++--- shaders/vk14/mat_bugs_windscreen.frag | 20 ++++---- shaders/vk14/mat_rain_windscreen.frag | 67 +++++++++++++++++++++---- shaders/vk14/postfx_dlss_motion.frag | 6 +++ shaders/vk14/postfx_motionblur.frag | 4 +- shaders/vk14/postfx_taa.frag | 2 +- shaders/vk14/rain_windscreen_haze.glsl | 51 ++++++++++++++++--- 11 files changed, 232 insertions(+), 62 deletions(-) diff --git a/shaders/ogl46/mat_bugs_windscreen.frag b/shaders/ogl46/mat_bugs_windscreen.frag index 93f6a4032..081d81c7d 100644 --- a/shaders/ogl46/mat_bugs_windscreen.frag +++ b/shaders/ogl46/mat_bugs_windscreen.frag @@ -102,7 +102,8 @@ const float bugs_unknown_level = 1.0; // upper limit of the dirt where the wipe const float bugs_wiper_clean = 1.0; // 1 = wipers wipe the bugs off (uses wipermask), 0 = wipers ignore them const float bugs_gloss = 0.45; // shininess of the wet splats (sun / headlight glints on the bumps), 0 = matt const float bugs_bump = 1.0; // strength of the 3D relief from the normal map, 0 = flat -const float bugs_halo_blur = 0.45; // blur of the scene in a ring around every bug (0 = off, 1 = full); done in the post-processing (rain_windscreen_haze.glsl) +const float bugs_halo_blur = 0.8; // blur of the scene seen through the see-through parts of a bug (its texture half transparent: wings, + // the thin smear of the splat), none around it (0 = off, 1 = full); done in the post-processing const float bugs_halo_size = 1.15; // ring radius = bug half-size * this (1 = only under the splat, max 1.6) const float bugs_halo_px = 60.0; // a bug this many pixels wide on screen gets the full blur, smaller ones less (the blur radius is fixed in pixels) const float bugs_vertical = 0.0; // -1..1: more dirt at the bottom (<0) or at the top (>0) of the pane, 0 = even @@ -331,13 +332,6 @@ void bugLayer(float gridSize, float density, uint layerSeed, // Blur ring around the splat (greasy smear): strongest next to the bug, fading out // (the post pass blurs with a fixed radius in pixels, so a bug that is small on screen gets less of it) - float haloR = size * 0.5 * clamp(bugs_halo_size, 1.0, 1.6); - float dist = length(d); - if (dist < haloR) - { - float pxScale = clamp(size / max(pixelUV, 1e-6) / max(bugs_halo_px, 1.0), 0.15, 1.0); - smear = max(smear, (1.0 - smoothstep(0.5 * haloR, haloR, dist)) * haloStrength * appear * pxScale); - } float c = cos(ang); float s = sin(ang); @@ -357,6 +351,12 @@ void bugLayer(float gridSize, float density, uint layerSeed, t.rgb = mix(t.rgb, vec3(0.42, 0.34, 0.16), lightMix); float a = clamp(t.a * appear * bugs_opacity * opacityMul, 0.0, 1.0); + // the scene blurred only where the bug is see-through (half transparent), not around it and not where it's opaque + // (the post pass blurs with a fixed radius in pixels, so a bug that is small on screen gets less of it) + float pxScale = clamp(size / max(pixelUV, 1e-6) / max(bugs_halo_px, 1.0), 0.15, 1.0); + float seeThrough = smoothstep(0.03, 0.3, a) * (1.0 - smoothstep(0.75, 0.95, a)); + smear = max(smear, seeThrough * haloStrength * pxScale); + // relief: tangent-space normal of the splat -> glass UV frame (undo the mirror, then the rotation) vec4 nm = textureLod(normalmap, tileOffset(choice) + local * 0.5, lod); vec2 nxy = (nm.rg * 2.0 - 1.0) * bugs_bump * appear; // a splat that is still settling is flatter @@ -493,8 +493,8 @@ void main() if (MOTIONBLUR_ENABLED) { // alpha 0 = blending keeps the scene's own motion vectors - // the bug itself stays sharp (1 - bugA); no blur over opaque parts of the pane (1 - glassA) - float blurMask = clamp(smear * bugs_halo_blur * (1.0 - bugA) * (1.0 - smoothstep(0.5, 0.95, glassA)), 0.0, 1.0); + // only the see-through parts of the bugs (smear); no blur over opaque parts of the pane (1 - glassA) + float blurMask = clamp(smear * bugs_halo_blur * (1.0 - smoothstep(0.5, 0.95, glassA)), 0.0, 1.0); out_motion = (blurMask >= 0.01) ? vec4(WS_ENC * blurMask, 0.0, 0.0, 1.0) : vec4(0.0); } } diff --git a/shaders/ogl46/mat_rain_windscreen.frag b/shaders/ogl46/mat_rain_windscreen.frag index 06a221f89..ec7fdc6a3 100644 --- a/shaders/ogl46/mat_rain_windscreen.frag +++ b/shaders/ogl46/mat_rain_windscreen.frag @@ -146,19 +146,32 @@ const float streak_link = 1.5; // head widths above the head where the tr // (or in a light wind) nothing of it shows: the rain lands, grows and runs down as it always did. const float wind_drag_gain = 4.0; // how strongly the air drives the water (1 = the drag of the stock shader: on a // vertical front glass the water would go up only at ~250 km/h) -const float wind_streaks = 3.0; // density of the rivulets driven by the air, at full drag (x streak_density) -const float wind_cell_scale = 0.36; // the rivulets of the air: their cells this much narrower ... -const float wind_run_scale = 0.28; // ... and shorter than those of gravity: many small drops with short trails -const float wind_head_scale = 0.55; // their heads this much smaller +const float wind_streaks = 1.5; // density of the rivulets driven by the air, at full drag (x streak_density) +const float wind_cell_scale = 0.5; // the rivulets of the air: their cells this much narrower ... +const float wind_run_scale = 1.2; // ... and their runs this long against those of gravity: few drops with long trails +const float wind_head_scale = 0.4; // their heads this much smaller (a small bead at the front of a long trail) const int wind_layers = 4; // layers of them, each with drops of its own (1 .. 4) -const float wind_long_run = 1.6; // the last layer: its trails this much longer than those of gravity (the long ones, a part of all) -const float wind_streak_period = 14.0; // seconds a rivulet driven by the air lives (they run faster than the ones of gravity) +const float wind_long_run = 3.0; // the last layer: its trails this much longer than those of gravity (the long ones, a part of all) +const float wind_streak_period = 18.0; // seconds a rivulet driven by the air lives (they run faster than the ones of gravity) const float drop_wind_stretch = 0.4; // drops are stretched up to this much along the push of the air (0 = off) const float WS_DRAG_SPEED = 24.0; // speed of the air along the glass at which its drag equals the weight of a drop, m/s const float WS_HEAD_ON = 0.35; // share of the air meeting the glass head on which turns up along it const float WS_WIND_STEP = 0.1309; // the direction of the rivulets of the air in steps of 7.5 degrees (no seams on a // curved glass, where every triangle would turn them a little) +// --- The rivulets of the air of different thickness: the width of every one is drawn from this range (x streak_head, x +// wind_head_scale), most of them thin, a few thick (never wider than their cell) ------------------------------------------------- +const float streak_thin = 0.5; // the thinnest +const float streak_thick = 2.0; // the thickest +const float streak_thick_bias = 2.0; // > 1: more thin ones +// --- What the blades leave: they don't take every drop (a few stay where they were), and the water they push lies along the edge +// of their sweep, just outside it, as a row of beads (where the blades went lately) ------------------------------------------------ +const float wiper_miss = 0.05; // share of the drops a blade goes over without taking them +const float wiper_edge_boost = 0.0; // along the edge of the sweep this many times more drops (and droplets) (0 = off) ... +const float wiper_edge_size = 0.65; // ... this much smaller: a row of beads +const float wiper_edge_reach = 4.0; // how wide the row is: the mip level of the mask read (4: ~16 texels of the mask out) +const float wiper_edge_keep = 180.0; // seconds after the last stroke the water at the edge keeps (then it's like the rest of the glass) + #ifndef STREAK_FLIP_Y #define STREAK_FLIP_Y 0 // set to 1 if the rivulets run UP the glass (head on top) #endif @@ -301,6 +314,7 @@ uint wsLayerSalt = 91u; float wsLayerHead = 1.0; // x streak_head float wsLayerCos = 1.0; // the layer is turned by this angle (its "down" is the way its water runs on the glass) float wsLayerSin = 0.0; +bool wsLayerVaried = false; // the widths of its rivulets from streak_thin .. streak_thick (the air) // glass UV (v up) -> coordinates of the layer, where the rivulets run down (-v) vec2 wsToLayerDir(vec2 v) @@ -335,6 +349,7 @@ void wsSetLayer(int layer) wsLayerHead = 1.0; wsLayerCos = 1.0; wsLayerSin = 0.0; + wsLayerVaried = false; } else { @@ -344,6 +359,7 @@ void wsSetLayer(int layer) wsLayerHead = wind_head_scale; wsLayerCos = wsWindCos; wsLayerSin = wsWindSin; + wsLayerVaried = true; } } @@ -355,7 +371,11 @@ Riv getRiv(vec2 sCell, float sCW, float sCH, float gridSize) float sPeriod = wsLayerPeriod * mix(0.6, 1.6, RandF(sSeed)); float sPhase = fract(time / sPeriod + RandF(sSeed)); r.life = smoothstep(0.0, 0.05, sPhase) * (1.0 - smoothstep(0.86, 1.0, sPhase)); - r.width = streak_head * wsLayerHead / gridSize * mix(0.75, 1.25, RandF(sSeed)); + float wr = RandF(sSeed); + r.width = streak_head * wsLayerHead / gridSize + * (wsLayerVaried ? mix(streak_thin, streak_thick, pow(wr, streak_thick_bias)) : mix(0.75, 1.25, wr)); + if (wsLayerVaried) + r.width = min(r.width, sCW / 2.6); // the trail with its swing (sMargin) stays in its cell r.headH = r.width * 0.88 * streak_uv_aspect; float sSpan = max(sCH * mix(0.35, 0.70, RandF(sSeed)), r.headH * 3.0); // stick-slip: the drop waits, then lurches forward; N waits on the way down @@ -565,6 +585,20 @@ float wsWipeAge(vec2 co) return age; } +// how much the place Co (texture UV) lies along the edge of the sweep of the blades, just outside it: 0 .. 1. the mask is 0 there and +// a coarse level of it isn't (the sweep is near). times wsWiperRecent: only where the blades went lately +float wsWiperRecent = 0.0; +float wsWiperEdge(vec2 co) +{ + if ((wiper_edge_boost <= 0.0) || (wsWiperRecent <= 0.0)) + return 0.0; + vec4 m = textureLod(wipermask, co, 0.0); + if (max(max(m.r, m.g), max(m.b, m.a)) > 0.001) + return 0.0; + vec4 c = textureLod(wipermask, co, wiper_edge_reach); + return smoothstep(0.01, 0.12, max(max(c.r, c.g), max(c.b, c.a))) * wsWiperRecent; +} + void main() { // ---- screen-space derivatives (before any non-uniform flow) ---- @@ -609,6 +643,13 @@ void main() // wiper state of this pixel (blur, micro droplets) float hazeSide; float wipeVis = GetMixFactor(f_coord, hazeSide); + // the blades went over the glass lately (the water they pushed still lies along the edge of the sweep) + for (int i = 0; i < 4; ++i) + { + float t = max(wiper_timer_out[i], wiper_timer_return[i]); + if ((t > -500.0) && (t <= time)) + wsWiperRecent = max(wsWiperRecent, 1.0 - smoothstep(0.5 * wiper_edge_keep, wiper_edge_keep, time - t)); + } Hit hit; hit.score = 0.0; hit.cov = 0.0; hit.colA = 0.0; hit.n = vec3(0.0, 0.0, 1.0); @@ -683,16 +724,20 @@ void main() uint ep = uint(mod(epoch, 65521.0)); // activation first (cheap), the wiper texture only for live drops uint s1 = Hash(uvec3(key, ep * 4u + 1u)); - if (RandF(s1) > rain_params.x * drop_density) + float edge = wsWiperEdge((nc + 0.5) / gridSize); + if (RandF(s1) > min(rain_params.x * drop_density * (1.0 + wiper_edge_boost * edge), 0.95)) continue; + // a drop the blades miss: the same drop before and after the stroke, left where it is + bool missed = RandF(s1) < wiper_miss; float side; - float mixF = GetMixFactor((nc + 0.5) / gridSize, side); + float mixF = missed ? 1.0 : GetMixFactor((nc + 0.5) / gridSize, side); + if (missed) side = 0.0; uint s2 = Hash(uvec3(key, ep * 4u + 2u + uint(side) * 2u)); if (mixF < RandF(s2)) continue; vec2 center = (nc + vec2(RandF(s2), RandF(s2))) / gridSize; - float size = mix(drop_size_min, drop_size_max, pow(RandF(s2), drop_size_bias)) / gridSize; + float size = mix(drop_size_min, drop_size_max, pow(RandF(s2), drop_size_bias)) / gridSize * mix(1.0, wiper_edge_size, edge); float sag = 1.0 + drop_sag * RandF(s2); float flipX = (RandF(s2) < 0.5) ? 1.0 : 0.0; float choice = RandF(s2); @@ -754,7 +799,7 @@ void main() float mph = fract(mtt); uint mep = uint(mod(floor(mtt), 65521.0)); uint m1 = Hash(uvec3(mk, mep * 4u + 1u)); - if (RandF(m1) < rain_params.x * micro_density) + if (RandF(m1) < min(rain_params.x * micro_density * (1.0 + wiper_edge_boost * wsWiperEdge((mc + 0.5) / mg)), 0.95)) { uint m2 = Hash(uvec3(mk, mep * 4u + 2u + uint(hazeSide) * 2u)); if (wipeVis >= RandF(m2)) diff --git a/shaders/ogl46/postfx_motionblur.frag b/shaders/ogl46/postfx_motionblur.frag index 41e080ce6..66ce2ed43 100644 --- a/shaders/ogl46/postfx_motionblur.frag +++ b/shaders/ogl46/postfx_motionblur.frag @@ -22,7 +22,7 @@ void main() if (wsIsDrop(rawv)) { vec4 picture = texture(color_tex, f_coords); - out_color = vec4((picture.a > 0.5 * (1.0 + WS_HAZED)) ? picture.rgb + out_color = vec4(wsWasHazed(picture.a) ? picture.rgb : wsDropRefraction(color_tex, velocity_tex, depth_tex, f_coords, rawv), 1.0); return; } @@ -30,7 +30,7 @@ void main() if (blurAmt > 0.0) { vec4 picture = texture(color_tex, f_coords); - out_color = vec4((picture.a > 0.5 * (1.0 + WS_HAZED)) ? picture.rgb : wsHaze(color_tex, velocity_tex, f_coords, blurAmt), 1.0); + out_color = vec4(wsWasHazed(picture.a) ? picture.rgb : wsHaze(color_tex, velocity_tex, f_coords, blurAmt), 1.0); return; } diff --git a/shaders/ogl46/postfx_taa.frag b/shaders/ogl46/postfx_taa.frag index a4e9566d4..c06a03fcb 100644 --- a/shaders/ogl46/postfx_taa.frag +++ b/shaders/ogl46/postfx_taa.frag @@ -42,7 +42,7 @@ vec3 wsStabilize(vec3 current, ivec2 pixel) if (false == TAA_HISTORY_VALID) return current; vec4 last = texelFetch(history_tex, pixel, 0); - if (any(isnan(last)) || (last.a < 0.5 * (1.0 + WS_HAZED))) // not a drop or haze pixel in the last frame + if (any(isnan(last)) || (false == wsWasHazed(last.a))) // not a drop or haze pixel in the last frame return current; vec2 size = vec2(textureSize(color_tex, 0)); float depth = texelFetch(depth_tex, pixel, 0).r; diff --git a/shaders/ogl46/rain_windscreen_haze.glsl b/shaders/ogl46/rain_windscreen_haze.glsl index 6dd9a4cde..73be4b573 100644 --- a/shaders/ogl46/rain_windscreen_haze.glsl +++ b/shaders/ogl46/rain_windscreen_haze.glsl @@ -10,7 +10,15 @@ const float WS_ENC = 64.0; // must match mat_rain_windscreen.frag const float WS_FLOOR = 0.004; // = 0.256 in raw velocity units: everything below is real motion -const float WS_HAZED = 2.0; // alpha of the picture the taa already blurred +const float WS_HAZED = -4.0; // alpha of the picture the taa already blurred: below anything a scene writes (additive + // particles took the alpha of the image above 1.5, and the motion blur then left the haze of a + // bug or of the glass out on some frames: a flicker). negative, so the lock of the taa takes 0 + +// whether the picture was blurred by the taa already (WS_HAZED in its alpha) +bool wsWasHazed(float alpha) +{ + return alpha < -3.0; +} // blur of hazy glass const float WS_RADIUS = 0.014; // max blur radius, fraction of screen height @@ -20,7 +28,10 @@ const float WS_HAZE_LIGHT_CAP = 12.0; // the most a light adds to the haze aro // strength of the blur request, 0 for pixels that are not blur pixels float wsBlur(vec2 raw) { - if (raw.x > 100.0 || raw.y > 100.0) // a blended edge with something else: not a blur pixel + // a blended edge with something else: not a blur pixel. the haze is asked with y = 0; with msaa the samples of a pixel are + // averaged, and the edge of a drop (y half of a drop's) came out as a full haze request: a ring blurred around the drop which + // flickered as the edges moved over the samples + if (raw.x > 100.0 || raw.y > 1.0) return 0.0; float m = clamp(raw.x / WS_ENC, 0.0, 1.0); return clamp((m - WS_FLOOR) / (1.0 - WS_FLOOR), 0.0, 1.0); @@ -139,7 +150,9 @@ float wsLum(vec3 c) // a drop pixel (drop, rivulet): both values in 132..252 bool wsIsDrop(vec2 raw) { - return raw.x > 120.0 && raw.y > 120.0; + // 132 .. 252 exactly: with msaa the edge of a drop averaged with the scene behind (half the values, up to 126) isn't a drop, + // else its decoded bend was nonsense, pulling the picture from far away for a frame (a drop flashing) + return raw.x > 131.5 && raw.y > 131.5; } vec2 wsBend(vec2 raw) @@ -148,19 +161,43 @@ vec2 wsBend(vec2 raw) } #ifndef LAYOUT_POST +// the image of the reflections around Uv as blurred as its mip level Lod, but round: a level of the mipmaps is a grid of squares +// (2^Lod pixels each), and a light read from it alone lit the drops in a square around it. a ring of taps of the finer level +// around the place, weighed as a soft disc, gives the same blur without the squares +vec3 wsHistoryRound(vec2 uv, float lod) +{ + float level = min(lod, ssr_params2.x); + float finer = max(level - 1.0, 0.0); + vec2 pixel = 1.0 / vec2(textureSize(ws_light_history, 0)); + float radius = 0.6 * exp2(level); // pixels of the image + vec3 sum = wsSafe(textureLod(ws_light_history, uv, finer).rgb) * 0.2; + for (int i = 0; i < 8; ++i) + { + float a = (float(i) + 0.5) * 0.7853982; + sum += wsSafe(textureLod(ws_light_history, uv + vec2(cos(a), sin(a)) * radius * pixel, finer).rgb) * 0.06; + sum += wsSafe(textureLod(ws_light_history, uv + vec2(cos(a + 0.3927), sin(a + 0.3927)) * (2.0 * radius) * pixel, finer).rgb) * 0.04; + } + return sum; +} + vec3 wsLightExcess(vec2 uv, float lod, vec3 wide) { - vec3 c = wsSafe(textureLod(ws_light_history, uv, min(lod, ssr_params2.x)).rgb); + vec3 c = wsHistoryRound(uv, lod); vec3 excess = max(c - wide * WS_LIGHT_CONTRAST, vec3(0.0)); - return excess * smoothstep(0.5 * WS_LIGHT_MIN_LUM, WS_LIGHT_MIN_LUM, wsLum(excess)); + // no threshold with an edge: a light dims away from it (the drops right by a lamp the brightest, then less and less); full + // from twice WS_LIGHT_MIN_LUM above the place around, as much as before there + return excess * clamp(wsLum(excess) / (2.0 * WS_LIGHT_MIN_LUM), 0.0, 1.0); } vec3 wsLightGlow(vec2 uv) { if ((ssr_params.x < 1.0) || (textureSize(ws_light_history, 0).x < 16)) return vec3(0.0); - vec3 wide = wsSafe(textureLod(ws_light_history, uv, min(WS_LIGHT_WIDE, ssr_params2.x)).rgb); - vec3 glow = wsLightExcess(uv, WS_LIGHT_FINE, wide) + WS_LIGHT_MID_SHARE * wsLightExcess(uv, WS_LIGHT_MID, wide); + vec3 wide = wsHistoryRound(uv, WS_LIGHT_WIDE); + // the near light in full, the one a little further away fading with it squared: the farther the drop, the less + vec3 mid = wsLightExcess(uv, WS_LIGHT_MID, wide); + float midF = clamp(wsLum(mid) / (2.0 * WS_LIGHT_MIN_LUM), 0.0, 1.0); + vec3 glow = wsLightExcess(uv, WS_LIGHT_FINE, wide) + WS_LIGHT_MID_SHARE * mid * midF; glow *= WS_LIGHT_GAIN; // a light close by is kept to the brightness of one light return glow * min(1.0, WS_LIGHT_CAP / max(wsLum(glow), 1e-4)); diff --git a/shaders/vk14/mat_bugs_windscreen.frag b/shaders/vk14/mat_bugs_windscreen.frag index 8037ddff6..fc0396286 100644 --- a/shaders/vk14/mat_bugs_windscreen.frag +++ b/shaders/vk14/mat_bugs_windscreen.frag @@ -107,7 +107,8 @@ const float bugs_unknown_level = 1.0; // upper limit of the dirt where the wipe const float bugs_wiper_clean = 1.0; // 1 = wipers wipe the bugs off (uses wipermask), 0 = wipers ignore them const float bugs_gloss = 0.45; // shininess of the wet splats (sun / headlight glints on the bumps), 0 = matt const float bugs_bump = 1.0; // strength of the 3D relief from the normal map, 0 = flat -const float bugs_halo_blur = 0.45; // blur of the scene in a ring around every bug (0 = off, 1 = full); done in the post-processing (rain_windscreen_haze.glsl) +const float bugs_halo_blur = 0.8; // blur of the scene seen through the see-through parts of a bug (its texture half transparent: wings, + // the thin smear of the splat), none around it (0 = off, 1 = full); done in the post-processing const float bugs_halo_size = 1.15; // ring radius = bug half-size * this (1 = only under the splat, max 1.6) const float bugs_halo_px = 60.0; // a bug this many pixels wide on screen gets the full blur, smaller ones less (the blur radius is fixed in pixels) const float bugs_vertical = 0.0; // -1..1: more dirt at the bottom (<0) or at the top (>0) of the pane, 0 = even @@ -336,13 +337,6 @@ void bugLayer(float gridSize, float density, uint layerSeed, // Blur ring around the splat (greasy smear): strongest next to the bug, fading out // (the post pass blurs with a fixed radius in pixels, so a bug that is small on screen gets less of it) - float haloR = size * 0.5 * clamp(bugs_halo_size, 1.0, 1.6); - float dist = length(d); - if (dist < haloR) - { - float pxScale = clamp(size / max(pixelUV, 1e-6) / max(bugs_halo_px, 1.0), 0.15, 1.0); - smear = max(smear, (1.0 - smoothstep(0.5 * haloR, haloR, dist)) * haloStrength * appear * pxScale); - } float c = cos(ang); float s = sin(ang); @@ -362,6 +356,12 @@ void bugLayer(float gridSize, float density, uint layerSeed, t.rgb = mix(t.rgb, vec3(0.42, 0.34, 0.16), lightMix); float a = clamp(t.a * appear * bugs_opacity * opacityMul, 0.0, 1.0); + // the scene blurred only where the bug is see-through (half transparent), not around it and not where it's opaque + // (the post pass blurs with a fixed radius in pixels, so a bug that is small on screen gets less of it) + float pxScale = clamp(size / max(pixelUV, 1e-6) / max(bugs_halo_px, 1.0), 0.15, 1.0); + float seeThrough = smoothstep(0.03, 0.3, a) * (1.0 - smoothstep(0.75, 0.95, a)); + smear = max(smear, seeThrough * haloStrength * pxScale); + // relief: tangent-space normal of the splat -> glass UV frame (undo the mirror, then the rotation) vec4 nm = textureLod(normalmap, tileOffset(choice) + local * 0.5, lod); vec2 nxy = (nm.rg * 2.0 - 1.0) * bugs_bump * appear; // a splat that is still settling is flatter @@ -498,8 +498,8 @@ void main() if (MOTIONBLUR_ENABLED) { // alpha 0 = blending keeps the scene's own motion vectors - // the bug itself stays sharp (1 - bugA); no blur over opaque parts of the pane (1 - glassA) - float blurMask = clamp(smear * bugs_halo_blur * (1.0 - bugA) * (1.0 - smoothstep(0.5, 0.95, glassA)), 0.0, 1.0); + // only the see-through parts of the bugs (smear); no blur over opaque parts of the pane (1 - glassA) + float blurMask = clamp(smear * bugs_halo_blur * (1.0 - smoothstep(0.5, 0.95, glassA)), 0.0, 1.0); out_motion = (blurMask >= 0.01) ? vec4(WS_ENC * blurMask, 0.0, 0.0, 1.0) : vec4(0.0); } } diff --git a/shaders/vk14/mat_rain_windscreen.frag b/shaders/vk14/mat_rain_windscreen.frag index fa76bc95e..975fd3eb8 100644 --- a/shaders/vk14/mat_rain_windscreen.frag +++ b/shaders/vk14/mat_rain_windscreen.frag @@ -151,19 +151,32 @@ const float streak_link = 1.5; // head widths above the head where the tr // (or in a light wind) nothing of it shows: the rain lands, grows and runs down as it always did. const float wind_drag_gain = 4.0; // how strongly the air drives the water (1 = the drag of the stock shader: on a // vertical front glass the water would go up only at ~250 km/h) -const float wind_streaks = 3.0; // density of the rivulets driven by the air, at full drag (x streak_density) -const float wind_cell_scale = 0.36; // the rivulets of the air: their cells this much narrower ... -const float wind_run_scale = 0.28; // ... and shorter than those of gravity: many small drops with short trails -const float wind_head_scale = 0.55; // their heads this much smaller +const float wind_streaks = 1.5; // density of the rivulets driven by the air, at full drag (x streak_density) +const float wind_cell_scale = 0.5; // the rivulets of the air: their cells this much narrower ... +const float wind_run_scale = 1.2; // ... and their runs this long against those of gravity: few drops with long trails +const float wind_head_scale = 0.4; // their heads this much smaller (a small bead at the front of a long trail) const int wind_layers = 4; // layers of them, each with drops of its own (1 .. 4) -const float wind_long_run = 1.6; // the last layer: its trails this much longer than those of gravity (the long ones, a part of all) -const float wind_streak_period = 14.0; // seconds a rivulet driven by the air lives (they run faster than the ones of gravity) +const float wind_long_run = 3.0; // the last layer: its trails this much longer than those of gravity (the long ones, a part of all) +const float wind_streak_period = 18.0; // seconds a rivulet driven by the air lives (they run faster than the ones of gravity) const float drop_wind_stretch = 0.4; // drops are stretched up to this much along the push of the air (0 = off) const float WS_DRAG_SPEED = 24.0; // speed of the air along the glass at which its drag equals the weight of a drop, m/s const float WS_HEAD_ON = 0.35; // share of the air meeting the glass head on which turns up along it const float WS_WIND_STEP = 0.1309; // the direction of the rivulets of the air in steps of 7.5 degrees (no seams on a // curved glass, where every triangle would turn them a little) +// --- The rivulets of the air of different thickness: the width of every one is drawn from this range (x streak_head, x +// wind_head_scale), most of them thin, a few thick (never wider than their cell) ------------------------------------------------- +const float streak_thin = 0.5; // the thinnest +const float streak_thick = 2.0; // the thickest +const float streak_thick_bias = 2.0; // > 1: more thin ones +// --- What the blades leave: they don't take every drop (a few stay where they were), and the water they push lies along the edge +// of their sweep, just outside it, as a row of beads (where the blades went lately) ------------------------------------------------ +const float wiper_miss = 0.05; // share of the drops a blade goes over without taking them +const float wiper_edge_boost = 0.0; // along the edge of the sweep this many times more drops (and droplets) (0 = off) ... +const float wiper_edge_size = 0.65; // ... this much smaller: a row of beads +const float wiper_edge_reach = 4.0; // how wide the row is: the mip level of the mask read (4: ~16 texels of the mask out) +const float wiper_edge_keep = 180.0; // seconds after the last stroke the water at the edge keeps (then it's like the rest of the glass) + #ifndef STREAK_FLIP_Y #define STREAK_FLIP_Y 0 // set to 1 if the rivulets run UP the glass (head on top) #endif @@ -306,6 +319,7 @@ uint wsLayerSalt = 91u; float wsLayerHead = 1.0; // x streak_head float wsLayerCos = 1.0; // the layer is turned by this angle (its "down" is the way its water runs on the glass) float wsLayerSin = 0.0; +bool wsLayerVaried = false; // the widths of its rivulets from streak_thin .. streak_thick (the air) // glass UV (v up) -> coordinates of the layer, where the rivulets run down (-v) vec2 wsToLayerDir(vec2 v) @@ -340,6 +354,7 @@ void wsSetLayer(int layer) wsLayerHead = 1.0; wsLayerCos = 1.0; wsLayerSin = 0.0; + wsLayerVaried = false; } else { @@ -349,6 +364,7 @@ void wsSetLayer(int layer) wsLayerHead = wind_head_scale; wsLayerCos = wsWindCos; wsLayerSin = wsWindSin; + wsLayerVaried = true; } } @@ -360,7 +376,11 @@ Riv getRiv(vec2 sCell, float sCW, float sCH, float gridSize) float sPeriod = wsLayerPeriod * mix(0.6, 1.6, RandF(sSeed)); float sPhase = fract(time / sPeriod + RandF(sSeed)); r.life = smoothstep(0.0, 0.05, sPhase) * (1.0 - smoothstep(0.86, 1.0, sPhase)); - r.width = streak_head * wsLayerHead / gridSize * mix(0.75, 1.25, RandF(sSeed)); + float wr = RandF(sSeed); + r.width = streak_head * wsLayerHead / gridSize + * (wsLayerVaried ? mix(streak_thin, streak_thick, pow(wr, streak_thick_bias)) : mix(0.75, 1.25, wr)); + if (wsLayerVaried) + r.width = min(r.width, sCW / 2.6); // the trail with its swing (sMargin) stays in its cell r.headH = r.width * 0.88 * streak_uv_aspect; float sSpan = max(sCH * mix(0.35, 0.70, RandF(sSeed)), r.headH * 3.0); // stick-slip: the drop waits, then lurches forward; N waits on the way down @@ -570,6 +590,20 @@ float wsWipeAge(vec2 co) return age; } +// how much the place Co (texture UV) lies along the edge of the sweep of the blades, just outside it: 0 .. 1. the mask is 0 there and +// a coarse level of it isn't (the sweep is near). times wsWiperRecent: only where the blades went lately +float wsWiperRecent = 0.0; +float wsWiperEdge(vec2 co) +{ + if ((wiper_edge_boost <= 0.0) || (wsWiperRecent <= 0.0)) + return 0.0; + vec4 m = textureLod(wipermask, co, 0.0); + if (max(max(m.r, m.g), max(m.b, m.a)) > 0.001) + return 0.0; + vec4 c = textureLod(wipermask, co, wiper_edge_reach); + return smoothstep(0.01, 0.12, max(max(c.r, c.g), max(c.b, c.a))) * wsWiperRecent; +} + void main() { // ---- screen-space derivatives (before any non-uniform flow) ---- @@ -614,6 +648,13 @@ void main() // wiper state of this pixel (blur, micro droplets) float hazeSide; float wipeVis = GetMixFactor(f_coord, hazeSide); + // the blades went over the glass lately (the water they pushed still lies along the edge of the sweep) + for (int i = 0; i < 4; ++i) + { + float t = max(wiper_timer_out[i], wiper_timer_return[i]); + if ((t > -500.0) && (t <= time)) + wsWiperRecent = max(wsWiperRecent, 1.0 - smoothstep(0.5 * wiper_edge_keep, wiper_edge_keep, time - t)); + } Hit hit; hit.score = 0.0; hit.cov = 0.0; hit.colA = 0.0; hit.n = vec3(0.0, 0.0, 1.0); @@ -688,16 +729,20 @@ void main() uint ep = uint(mod(epoch, 65521.0)); // activation first (cheap), the wiper texture only for live drops uint s1 = Hash(uvec3(key, ep * 4u + 1u)); - if (RandF(s1) > rain_params.x * drop_density) + float edge = wsWiperEdge((nc + 0.5) / gridSize); + if (RandF(s1) > min(rain_params.x * drop_density * (1.0 + wiper_edge_boost * edge), 0.95)) continue; + // a drop the blades miss: the same drop before and after the stroke, left where it is + bool missed = RandF(s1) < wiper_miss; float side; - float mixF = GetMixFactor((nc + 0.5) / gridSize, side); + float mixF = missed ? 1.0 : GetMixFactor((nc + 0.5) / gridSize, side); + if (missed) side = 0.0; uint s2 = Hash(uvec3(key, ep * 4u + 2u + uint(side) * 2u)); if (mixF < RandF(s2)) continue; vec2 center = (nc + vec2(RandF(s2), RandF(s2))) / gridSize; - float size = mix(drop_size_min, drop_size_max, pow(RandF(s2), drop_size_bias)) / gridSize; + float size = mix(drop_size_min, drop_size_max, pow(RandF(s2), drop_size_bias)) / gridSize * mix(1.0, wiper_edge_size, edge); float sag = 1.0 + drop_sag * RandF(s2); float flipX = (RandF(s2) < 0.5) ? 1.0 : 0.0; float choice = RandF(s2); @@ -759,7 +804,7 @@ void main() float mph = fract(mtt); uint mep = uint(mod(floor(mtt), 65521.0)); uint m1 = Hash(uvec3(mk, mep * 4u + 1u)); - if (RandF(m1) < rain_params.x * micro_density) + if (RandF(m1) < min(rain_params.x * micro_density * (1.0 + wiper_edge_boost * wsWiperEdge((mc + 0.5) / mg)), 0.95)) { uint m2 = Hash(uvec3(mk, mep * 4u + 2u + uint(hazeSide) * 2u)); if (wipeVis >= RandF(m2)) diff --git a/shaders/vk14/postfx_dlss_motion.frag b/shaders/vk14/postfx_dlss_motion.frag index dcb91e498..e94ed8d20 100644 --- a/shaders/vk14/postfx_dlss_motion.frag +++ b/shaders/vk14/postfx_dlss_motion.frag @@ -20,6 +20,12 @@ void main() ivec2 pixel = ivec2(gl_FragCoord.xy); vec2 velocity = texelFetch(velocity_tex, pixel, 0).xy; float depth = texelFetch(depth_tex, pixel, 0).r; + // the windscreens (mat_rain_windscreen, mat_bugs_windscreen) send the post-processing their drops and haze as large values + // (real motion is far below a quarter of the screen per frame): no motion for dlss there, the glass goes with the camera + if (any(greaterThan(abs(velocity), vec2(0.25)))) + { + velocity = vec2(0.0); + } if (depth <= 0.0) { vec4 world = mat4(param[2], param[3], param[4], param[5]) * vec4(f_coords * 2.0 - 1.0, depth, 1.0); diff --git a/shaders/vk14/postfx_motionblur.frag b/shaders/vk14/postfx_motionblur.frag index 2bc7d938b..2677cc6c6 100644 --- a/shaders/vk14/postfx_motionblur.frag +++ b/shaders/vk14/postfx_motionblur.frag @@ -26,7 +26,7 @@ void main() if (wsIsDrop(rawv)) { vec4 picture = texture(color_tex, f_coords); - out_color = vec4((picture.a > 0.5 * (1.0 + WS_HAZED)) ? picture.rgb + out_color = vec4(wsWasHazed(picture.a) ? picture.rgb : wsDropRefraction(color_tex, velocity_tex, depth_tex, f_coords, rawv), 1.0); return; } @@ -34,7 +34,7 @@ void main() if (blurAmt > 0.0) { vec4 picture = texture(color_tex, f_coords); - out_color = vec4((picture.a > 0.5 * (1.0 + WS_HAZED)) ? picture.rgb : wsHaze(color_tex, velocity_tex, f_coords, blurAmt), 1.0); + out_color = vec4(wsWasHazed(picture.a) ? picture.rgb : wsHaze(color_tex, velocity_tex, f_coords, blurAmt), 1.0); return; } diff --git a/shaders/vk14/postfx_taa.frag b/shaders/vk14/postfx_taa.frag index 6e01a3b25..281c6b07b 100644 --- a/shaders/vk14/postfx_taa.frag +++ b/shaders/vk14/postfx_taa.frag @@ -44,7 +44,7 @@ vec3 wsStabilize(vec3 current, ivec2 pixel) if (false == TAA_HISTORY_VALID) return current; vec4 last = texelFetch(history_tex, pixel, 0); - if (any(isnan(last)) || (last.a < 0.5 * (1.0 + WS_HAZED))) // not a drop or haze pixel in the last frame + if (any(isnan(last)) || (false == wsWasHazed(last.a))) // not a drop or haze pixel in the last frame return current; vec2 size = vec2(textureSize(color_tex, 0)); float depth = texelFetch(depth_tex, pixel, 0).r; diff --git a/shaders/vk14/rain_windscreen_haze.glsl b/shaders/vk14/rain_windscreen_haze.glsl index 6dd9a4cde..73be4b573 100644 --- a/shaders/vk14/rain_windscreen_haze.glsl +++ b/shaders/vk14/rain_windscreen_haze.glsl @@ -10,7 +10,15 @@ const float WS_ENC = 64.0; // must match mat_rain_windscreen.frag const float WS_FLOOR = 0.004; // = 0.256 in raw velocity units: everything below is real motion -const float WS_HAZED = 2.0; // alpha of the picture the taa already blurred +const float WS_HAZED = -4.0; // alpha of the picture the taa already blurred: below anything a scene writes (additive + // particles took the alpha of the image above 1.5, and the motion blur then left the haze of a + // bug or of the glass out on some frames: a flicker). negative, so the lock of the taa takes 0 + +// whether the picture was blurred by the taa already (WS_HAZED in its alpha) +bool wsWasHazed(float alpha) +{ + return alpha < -3.0; +} // blur of hazy glass const float WS_RADIUS = 0.014; // max blur radius, fraction of screen height @@ -20,7 +28,10 @@ const float WS_HAZE_LIGHT_CAP = 12.0; // the most a light adds to the haze aro // strength of the blur request, 0 for pixels that are not blur pixels float wsBlur(vec2 raw) { - if (raw.x > 100.0 || raw.y > 100.0) // a blended edge with something else: not a blur pixel + // a blended edge with something else: not a blur pixel. the haze is asked with y = 0; with msaa the samples of a pixel are + // averaged, and the edge of a drop (y half of a drop's) came out as a full haze request: a ring blurred around the drop which + // flickered as the edges moved over the samples + if (raw.x > 100.0 || raw.y > 1.0) return 0.0; float m = clamp(raw.x / WS_ENC, 0.0, 1.0); return clamp((m - WS_FLOOR) / (1.0 - WS_FLOOR), 0.0, 1.0); @@ -139,7 +150,9 @@ float wsLum(vec3 c) // a drop pixel (drop, rivulet): both values in 132..252 bool wsIsDrop(vec2 raw) { - return raw.x > 120.0 && raw.y > 120.0; + // 132 .. 252 exactly: with msaa the edge of a drop averaged with the scene behind (half the values, up to 126) isn't a drop, + // else its decoded bend was nonsense, pulling the picture from far away for a frame (a drop flashing) + return raw.x > 131.5 && raw.y > 131.5; } vec2 wsBend(vec2 raw) @@ -148,19 +161,43 @@ vec2 wsBend(vec2 raw) } #ifndef LAYOUT_POST +// the image of the reflections around Uv as blurred as its mip level Lod, but round: a level of the mipmaps is a grid of squares +// (2^Lod pixels each), and a light read from it alone lit the drops in a square around it. a ring of taps of the finer level +// around the place, weighed as a soft disc, gives the same blur without the squares +vec3 wsHistoryRound(vec2 uv, float lod) +{ + float level = min(lod, ssr_params2.x); + float finer = max(level - 1.0, 0.0); + vec2 pixel = 1.0 / vec2(textureSize(ws_light_history, 0)); + float radius = 0.6 * exp2(level); // pixels of the image + vec3 sum = wsSafe(textureLod(ws_light_history, uv, finer).rgb) * 0.2; + for (int i = 0; i < 8; ++i) + { + float a = (float(i) + 0.5) * 0.7853982; + sum += wsSafe(textureLod(ws_light_history, uv + vec2(cos(a), sin(a)) * radius * pixel, finer).rgb) * 0.06; + sum += wsSafe(textureLod(ws_light_history, uv + vec2(cos(a + 0.3927), sin(a + 0.3927)) * (2.0 * radius) * pixel, finer).rgb) * 0.04; + } + return sum; +} + vec3 wsLightExcess(vec2 uv, float lod, vec3 wide) { - vec3 c = wsSafe(textureLod(ws_light_history, uv, min(lod, ssr_params2.x)).rgb); + vec3 c = wsHistoryRound(uv, lod); vec3 excess = max(c - wide * WS_LIGHT_CONTRAST, vec3(0.0)); - return excess * smoothstep(0.5 * WS_LIGHT_MIN_LUM, WS_LIGHT_MIN_LUM, wsLum(excess)); + // no threshold with an edge: a light dims away from it (the drops right by a lamp the brightest, then less and less); full + // from twice WS_LIGHT_MIN_LUM above the place around, as much as before there + return excess * clamp(wsLum(excess) / (2.0 * WS_LIGHT_MIN_LUM), 0.0, 1.0); } vec3 wsLightGlow(vec2 uv) { if ((ssr_params.x < 1.0) || (textureSize(ws_light_history, 0).x < 16)) return vec3(0.0); - vec3 wide = wsSafe(textureLod(ws_light_history, uv, min(WS_LIGHT_WIDE, ssr_params2.x)).rgb); - vec3 glow = wsLightExcess(uv, WS_LIGHT_FINE, wide) + WS_LIGHT_MID_SHARE * wsLightExcess(uv, WS_LIGHT_MID, wide); + vec3 wide = wsHistoryRound(uv, WS_LIGHT_WIDE); + // the near light in full, the one a little further away fading with it squared: the farther the drop, the less + vec3 mid = wsLightExcess(uv, WS_LIGHT_MID, wide); + float midF = clamp(wsLum(mid) / (2.0 * WS_LIGHT_MIN_LUM), 0.0, 1.0); + vec3 glow = wsLightExcess(uv, WS_LIGHT_FINE, wide) + WS_LIGHT_MID_SHARE * mid * midF; glow *= WS_LIGHT_GAIN; // a light close by is kept to the brightness of one light return glow * min(1.0, WS_LIGHT_CAP / max(wsLum(glow), 1e-4)); From 5c3570caddcdf7cd90090f13a41b697a21415091 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 23:18:59 +0100 Subject: [PATCH 048/123] People animated by textures: the shaders (mat_vat) and the scene block with the place of the camera [skip ci] The shaders of the animation baked into textures, as tested in the game: mat_vat.vert / mat_vat.frag for OpenGL 4.6 and Vulkan 1.4, and common.glsl with camera_hi / camera_lo at the end of the scene block, matching gl/ubo.h of this branch. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/common.glsl | 3 + shaders/ogl46/mat_vat.frag | 4 + shaders/ogl46/mat_vat.vert | 195 ++++++++++++++++++++++++++++++++++++ shaders/vk14/common.glsl | 3 + shaders/vk14/mat_vat.frag | 9 ++ shaders/vk14/mat_vat.vert | 196 +++++++++++++++++++++++++++++++++++++ 6 files changed, 410 insertions(+) create mode 100644 shaders/ogl46/mat_vat.frag create mode 100644 shaders/ogl46/mat_vat.vert create mode 100644 shaders/vk14/mat_vat.frag create mode 100644 shaders/vk14/mat_vat.vert diff --git a/shaders/ogl46/common.glsl b/shaders/ogl46/common.glsl index a3762442a..4ba306c3f 100644 --- a/shaders/ogl46/common.glsl +++ b/shaders/ogl46/common.glsl @@ -371,6 +371,9 @@ layout(std140, binding = SCENE_UBO_BINDING) uniform scene_ubo // the insects met when the blades were at the ends of their sweep (mat_bugs_windscreen), see gl::scene_ubs vec4 wiper_bugs_out; vec4 wiper_bugs_return; + // the place of the camera of the pass in the world (whole 64 m, the rest), see gl::scene_ubs + vec4 camera_hi; + vec4 camera_lo; }; #ifdef STAGE_VERTEX diff --git a/shaders/ogl46/mat_vat.frag b/shaders/ogl46/mat_vat.frag new file mode 100644 index 000000000..9081789a5 --- /dev/null +++ b/shaders/ogl46/mat_vat.frag @@ -0,0 +1,4 @@ +#version 460 core +#define STAGE_FRAGMENT 1 +// people animated by textures (mat_vat.vert moves the vertices): drawn as mat_default +#include "mat_default.glsl" diff --git a/shaders/ogl46/mat_vat.vert b/shaders/ogl46/mat_vat.vert new file mode 100644 index 000000000..a06143220 --- /dev/null +++ b/shaders/ogl46/mat_vat.vert @@ -0,0 +1,195 @@ +#version 460 core +#define STAGE_VERTEX 1 +// an animation baked into textures (vertex animation texture, VAT): people walking, standing, waiting. the vertices are moved +// here by the frames of the animation the textures hold, the material is drawn by mat_vat.frag (as mat_default). made by +// vat_bake.py from an animated mesh in blender; the model (t3d) carries in the userdata of every vertex (x) its column of the +// textures. the same shader draws the sun shadows (MATERIAL_SHADOW) and the multi draws (MODEL_DRAWS, opengl46_renderer) +// +// the textures (linear, never compressed or downscaled: at most gfx maxtexturesize, 2048 by default): +// vatpos_hi, vatpos_lo: the position of a vertex in a frame, 16 bits per axis over the box of the animation (rgb: the high and +// the low bytes), the normal in vatnormal (rgb, 0.5 + 0.5 n) +// the frames lie one under another, each in RowsPerFrame rows of Width vertices; the first row of vatpos_hi holds the header, +// the last one the same header with another mark (so the shader sees whether the image came upside down): +// pixel 0: 'V' 'A' 'T' 1 in the first row, 'V' 'A' 'T' 2 in the last +// pixel 1: min x, min y (16 bits each: hi, lo; millimetres + 32768) pixel 2: min z, size x (size: millimetres) +// pixel 3: size y, size z pixel 4: vertices, frames +// pixel 5: rows per frame, frames a second x 100 +// pixel 6: clips (0 or 1: one animation); with more the frames are that many animations of equal length one after another, +// and every one of the models plays one of them, picked as its moment is; then flags: 1 the frames packed one +// right after another (vertex Frame * Vertices + Vertex of the whole image, row by row), else each in its own rows +// the textures go with the trait r (texture_vatpos_hi: name:r), which keeps them as they are (never scaled down nor compressed) +// param vat_speed (1 if not given): how fast the animation plays +layout(location = 0) in vec3 v_vert; +layout(location = 1) in vec3 v_normal; +layout(location = 2) in vec2 v_coord; +layout(location = 3) in vec4 v_tangent; +layout(location = 4) in vec4 v_userdata; + +#include "common.glsl" + +#pragma texture(vatpos_hi, 1, RGBA) +#pragma texture(vatpos_lo, 2, RGBA) +#pragma texture(vatnormal, 3, RGBA) +#pragma param(vat_speed, 2, 0, 1, one) +layout(binding = 1) uniform sampler2D vatpos_hi; +layout(binding = 2) uniform sampler2D vatpos_lo; +layout(binding = 3) uniform sampler2D vatnormal; + +#ifdef MATERIAL_SHADOW +layout(location = 2) out vec2 f_coord; +#else +invariant gl_Position; + +layout(location = 0) out vec3 f_normal; +layout(location = 1) flat out vec3 f_normal_raw; +layout(location = 2) out vec2 f_coord; +layout(location = 3) out vec4 f_pos; +layout(location = 8) out mat3 f_tbn; + +layout(location = 4) out vec4 f_clip_pos; +layout(location = 5) out vec4 f_clip_future_pos; + +layout(location = 6) out vec3 TangentFragPos; +layout(location = 7) out vec4 UserData; +#endif + +// the header: Flipped when the image came upside down +struct vat_header +{ + bool valid; + bool flipped; + int height; + vec3 lower; + vec3 size; + int vertices; + int frames; + int rows; + float fps; + int clips; + bool dense; +}; + +ivec4 vat_bytes(ivec2 texel) +{ + return ivec4(round(texelFetch(vatpos_hi, texel, 0) * 255.0)); +} + +vat_header vat_read_header() +{ + vat_header h; + ivec2 size = textureSize(vatpos_hi, 0); + h.height = size.y; + ivec4 mark = vat_bytes(ivec2(0, 0)); + h.valid = (mark.x == 86) && (mark.y == 65) && (mark.z == 84) && ((mark.w == 1) || (mark.w == 2)); + h.flipped = (mark.w == 2); + int row = 0; + ivec4 p1 = vat_bytes(ivec2(1, row)); + ivec4 p2 = vat_bytes(ivec2(2, row)); + ivec4 p3 = vat_bytes(ivec2(3, row)); + ivec4 p4 = vat_bytes(ivec2(4, row)); + ivec4 p5 = vat_bytes(ivec2(5, row)); + ivec4 p6 = vat_bytes(ivec2(6, row)); + h.lower = (vec3(p1.x * 256 + p1.y, p1.z * 256 + p1.w, p2.x * 256 + p2.y) - 32768.0) * 0.001; + h.size = vec3(p2.z * 256 + p2.w, p3.x * 256 + p3.y, p3.z * 256 + p3.w) * 0.001; + h.vertices = p4.x * 256 + p4.y; + h.frames = max(p4.z * 256 + p4.w, 1); + h.rows = max(p5.x * 256 + p5.y, 1); + h.fps = float(p5.z * 256 + p5.w) * 0.01; + h.clips = clamp(p6.x * 256 + p6.y, 1, h.frames); + h.dense = (p6.z & 1) != 0; + return h; +} + +// the texel of vertex Vertex in frame Frame +ivec2 vat_texel(vat_header h, int vertex, int frame, int width) +{ + int ix = h.dense ? frame * h.vertices + vertex : frame * h.rows * width + vertex; + int row = 1 + ix / width; + if (h.flipped) + row = h.height - 1 - row; + return ivec2(ix % width, row); +} + +vec3 vat_position(vat_header h, ivec2 texel) +{ + vec3 high = round(texelFetch(vatpos_hi, texel, 0).rgb * 255.0); + vec3 low = round(texelFetch(vatpos_lo, texel, 0).rgb * 255.0); + return h.lower + h.size * ((high * 256.0 + low) / 65535.0); +} + +vec3 vat_normal(ivec2 texel) +{ + return texelFetch(vatnormal, texel, 0).rgb * 2.0 - 1.0; +} + +// the place and the normal of the vertex now (the rest pose of the model where the textures don't fit it) +void vat_animate(mat4 mv, out vec3 position, out vec3 normal) +{ + position = v_vert; + normal = v_normal; + vat_header h = vat_read_header(); + int vertex = int(v_userdata.x + 0.5); + if ((false == h.valid) || (vertex < 0) || (vertex >= h.vertices)) + return; + int width = textureSize(vatpos_hi, 0).x; + // every one of the models a moment (and a clip) of its own: from its place in the world, whole metres, and its turn about the + // vertical, whole 2 degrees. the place is the one of the camera of the pass (camera_hi exact, camera_lo the rest) and the model + // relative to it (mv, turned back to the world with inv_view), so it's the same in every pass and with every move of the camera; + // the edges of the cells and of the bins away from the round values models are set at + mat3 world = mat3(inv_view) * mat3(mv); + vec3 rel = camera_lo.xyz + mat3(inv_view) * mv[3].xyz; + ivec3 cell = ivec3(camera_hi.xyz) + ivec3(floor(rel + 0.37)); + float yaw = degrees(atan(world[0].z, world[0].x)); + int bin = int(mod(floor(yaw * 0.5 + 0.315), 180.0)); + uint seed = uint(cell.x) * 73856093u ^ uint(cell.y) * 19349663u ^ uint(cell.z) * 83492791u ^ uint(bin) * 2654435761u; + seed ^= seed >> 16; seed *= 0x7feb352du; seed ^= seed >> 15; seed *= 0x846ca68bu; seed ^= seed >> 16; + float phase = float(seed & 0xffffu) / 65536.0; + float pick = float(seed >> 16) / 65536.0; + int clipframes = max(h.frames / h.clips, 1); + int clip = min(int(pick * float(h.clips)), h.clips - 1); + float t = (time * h.fps * max(param[2].x, 0.0)) + phase * float(clipframes); + float f = mod(t, float(clipframes)); + int f0 = clip * clipframes + int(floor(f)) % clipframes; + int f1 = clip * clipframes + (int(floor(f)) + 1) % clipframes; + float a = fract(f); + ivec2 t0 = vat_texel(h, vertex, f0, width); + ivec2 t1 = vat_texel(h, vertex, f1, width); + position = mix(vat_position(h, t0), vat_position(h, t1), a); + vec3 n = mix(vat_normal(t0), vat_normal(t1), a); + normal = (dot(n, n) > 1e-6) ? normalize(n) : v_normal; +} + +void main() +{ + mat4 mv = effective_modelview(); + vec3 position; + vec3 normal; + vat_animate(mv, position, normal); +#ifdef MATERIAL_SHADOW + gl_Position = (projection * mv) * vec4(position, 1.0); + f_coord = v_coord; +#else + mat3 mvn = effective_modelviewnormal(); + + f_normal = normalize(mvn * normal); + f_normal_raw = normal; + f_coord = v_coord; + f_pos = mv * vec4(position, 1.0); + f_clip_pos = projection * f_pos; + f_clip_future_pos = (projection * future) * f_pos; + + gl_Position = f_clip_pos; + gl_PointSize = param[1].x; + + vec3 N = f_normal; + vec3 T = mvn * v_tangent.xyz; + T = normalize(T - N * dot(N, T)); + vec3 B = cross(N, T) * (v_tangent.w < 0.0 ? -1.0 : 1.0); + f_tbn = mat3(T, B, N); + TangentFragPos = transpose(f_tbn) * f_pos.xyz; + UserData = v_userdata; +#endif +#ifdef MODEL_DRAWS + f_model_draw = uint(gl_DrawID); +#endif +} diff --git a/shaders/vk14/common.glsl b/shaders/vk14/common.glsl index 7a087f669..d29dc677b 100644 --- a/shaders/vk14/common.glsl +++ b/shaders/vk14/common.glsl @@ -333,6 +333,9 @@ layout(std140, set = PASS_SET, binding = SCENE_UBO) uniform scene_ubo // the insects met when the blades were at the ends of their sweep (mat_bugs_windscreen), see gl::scene_ubs vec4 wiper_bugs_out; vec4 wiper_bugs_return; + // the place of the camera of the pass in the world (whole 64 m, the rest), see gl::scene_ubs + vec4 camera_hi; + vec4 camera_lo; }; #ifndef LAYOUT_COMPUTE diff --git a/shaders/vk14/mat_vat.frag b/shaders/vk14/mat_vat.frag new file mode 100644 index 000000000..2ce2b3690 --- /dev/null +++ b/shaders/vk14/mat_vat.frag @@ -0,0 +1,9 @@ +#version 460 core +#define STAGE_FRAGMENT 1 +// animals and people animated by textures (mat_vat.vert moves the vertices): drawn as mat_default. the textures and the param of +// the animation are declared here too, as in the vertex shader +#pragma texture(vatpos_hi, 1, RGBA) +#pragma texture(vatpos_lo, 2, RGBA) +#pragma texture(vatnormal, 3, RGBA) +#pragma param(vat_speed, 2, 0, 1, one) +#include "mat_default.glsl" diff --git a/shaders/vk14/mat_vat.vert b/shaders/vk14/mat_vat.vert new file mode 100644 index 000000000..d830b93c1 --- /dev/null +++ b/shaders/vk14/mat_vat.vert @@ -0,0 +1,196 @@ +#version 460 core +#define STAGE_VERTEX 1 +#include "common.glsl" +// an animation baked into textures (vertex animation texture, VAT): people walking, standing, waiting. the vertices are moved +// here by the frames of the animation the textures hold, the material is drawn by mat_vat.frag (as mat_default). made by +// vat_bake.py from an animated mesh in blender; the model (t3d) carries in the userdata of every vertex (x) its column of the +// textures. the same shader draws the sun shadows (MATERIAL_SHADOW) and the multi draws (MODEL_DRAWS) of vulkan14_renderer: +// the vulkan version of shaders/ogl46/mat_vat.vert, with the bindings of the material set +// +// the textures (linear, never compressed or downscaled: at most gfx maxtexturesize, 2048 by default): +// vatpos_hi, vatpos_lo: the position of a vertex in a frame, 16 bits per axis over the box of the animation (rgb: the high and +// the low bytes), the normal in vatnormal (rgb, 0.5 + 0.5 n) +// the frames lie one under another, each in RowsPerFrame rows of Width vertices; the first row of vatpos_hi holds the header, +// the last one the same header with another mark (so the shader sees whether the image came upside down): +// pixel 0: 'V' 'A' 'T' 1 in the first row, 'V' 'A' 'T' 2 in the last +// pixel 1: min x, min y (16 bits each: hi, lo; millimetres + 32768) pixel 2: min z, size x (size: millimetres) +// pixel 3: size y, size z pixel 4: vertices, frames +// pixel 5: rows per frame, frames a second x 100 +// pixel 6: clips (0 or 1: one animation); with more the frames are that many animations of equal length one after another, +// and every one of the models plays one of them, picked as its moment is; then flags: 1 the frames packed one +// right after another (vertex Frame * Vertices + Vertex of the whole image, row by row), else each in its own rows +// the textures go with the trait r (texture_vatpos_hi: name:r), which keeps them as they are (never scaled down nor compressed) +// param vat_speed (1 if not given): how fast the animation plays +layout(location = 0) in vec3 v_vert; +layout(location = 1) in vec3 v_normal; +layout(location = 2) in vec2 v_coord; +layout(location = 3) in vec4 v_tangent; +layout(location = 4) in vec4 v_userdata; + +#pragma texture(vatpos_hi, 1, RGBA) +#pragma texture(vatpos_lo, 2, RGBA) +#pragma texture(vatnormal, 3, RGBA) +#pragma param(vat_speed, 2, 0, 1, one) +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 1) uniform sampler2D vatpos_hi; +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 2) uniform sampler2D vatpos_lo; +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 3) uniform sampler2D vatnormal; + +#ifdef MATERIAL_SHADOW +layout(location = 2) out vec2 f_coord; +#else +invariant gl_Position; + +layout(location = 0) out vec3 f_normal; +layout(location = 1) flat out vec3 f_normal_raw; +layout(location = 2) out vec2 f_coord; +layout(location = 3) out vec4 f_pos; +layout(location = 8) out mat3 f_tbn; + +layout(location = 4) out vec4 f_clip_pos; +layout(location = 5) out vec4 f_clip_future_pos; + +layout(location = 6) out vec3 TangentFragPos; +layout(location = 7) out vec4 UserData; +#endif + +// the header: Flipped when the image came upside down +struct vat_header +{ + bool valid; + bool flipped; + int height; + vec3 lower; + vec3 size; + int vertices; + int frames; + int rows; + float fps; + int clips; + bool dense; +}; + +ivec4 vat_bytes(ivec2 texel) +{ + return ivec4(round(texelFetch(vatpos_hi, texel, 0) * 255.0)); +} + +vat_header vat_read_header() +{ + vat_header h; + ivec2 size = textureSize(vatpos_hi, 0); + h.height = size.y; + ivec4 mark = vat_bytes(ivec2(0, 0)); + h.valid = (mark.x == 86) && (mark.y == 65) && (mark.z == 84) && ((mark.w == 1) || (mark.w == 2)); + h.flipped = (mark.w == 2); + int row = 0; + ivec4 p1 = vat_bytes(ivec2(1, row)); + ivec4 p2 = vat_bytes(ivec2(2, row)); + ivec4 p3 = vat_bytes(ivec2(3, row)); + ivec4 p4 = vat_bytes(ivec2(4, row)); + ivec4 p5 = vat_bytes(ivec2(5, row)); + ivec4 p6 = vat_bytes(ivec2(6, row)); + h.lower = (vec3(p1.x * 256 + p1.y, p1.z * 256 + p1.w, p2.x * 256 + p2.y) - 32768.0) * 0.001; + h.size = vec3(p2.z * 256 + p2.w, p3.x * 256 + p3.y, p3.z * 256 + p3.w) * 0.001; + h.vertices = p4.x * 256 + p4.y; + h.frames = max(p4.z * 256 + p4.w, 1); + h.rows = max(p5.x * 256 + p5.y, 1); + h.fps = float(p5.z * 256 + p5.w) * 0.01; + h.clips = clamp(p6.x * 256 + p6.y, 1, h.frames); + h.dense = (p6.z & 1) != 0; + return h; +} + +// the texel of vertex Vertex in frame Frame +ivec2 vat_texel(vat_header h, int vertex, int frame, int width) +{ + int ix = h.dense ? frame * h.vertices + vertex : frame * h.rows * width + vertex; + int row = 1 + ix / width; + if (h.flipped) + row = h.height - 1 - row; + return ivec2(ix % width, row); +} + +vec3 vat_position(vat_header h, ivec2 texel) +{ + vec3 high = round(texelFetch(vatpos_hi, texel, 0).rgb * 255.0); + vec3 low = round(texelFetch(vatpos_lo, texel, 0).rgb * 255.0); + return h.lower + h.size * ((high * 256.0 + low) / 65535.0); +} + +vec3 vat_normal(ivec2 texel) +{ + return texelFetch(vatnormal, texel, 0).rgb * 2.0 - 1.0; +} + +// the place and the normal of the vertex now (the rest pose of the model where the textures don't fit it) +void vat_animate(mat4 mv, out vec3 position, out vec3 normal) +{ + position = v_vert; + normal = v_normal; + vat_header h = vat_read_header(); + int vertex = int(v_userdata.x + 0.5); + if ((false == h.valid) || (vertex < 0) || (vertex >= h.vertices)) + return; + int width = textureSize(vatpos_hi, 0).x; + // every one of the models a moment (and a clip) of its own: from its place in the world, whole metres, and its turn about the + // vertical, whole 2 degrees. the place is the one of the camera of the pass (camera_hi exact, camera_lo the rest) and the model + // relative to it (mv, turned back to the world with inv_view), so it's the same in every pass and with every move of the camera; + // the edges of the cells and of the bins away from the round values models are set at + mat3 world = mat3(inv_view) * mat3(mv); + vec3 rel = camera_lo.xyz + mat3(inv_view) * mv[3].xyz; + ivec3 cell = ivec3(camera_hi.xyz) + ivec3(floor(rel + 0.37)); + float yaw = degrees(atan(world[0].z, world[0].x)); + int bin = int(mod(floor(yaw * 0.5 + 0.315), 180.0)); + uint seed = uint(cell.x) * 73856093u ^ uint(cell.y) * 19349663u ^ uint(cell.z) * 83492791u ^ uint(bin) * 2654435761u; + seed ^= seed >> 16; seed *= 0x7feb352du; seed ^= seed >> 15; seed *= 0x846ca68bu; seed ^= seed >> 16; + float phase = float(seed & 0xffffu) / 65536.0; + float pick = float(seed >> 16) / 65536.0; + int clipframes = max(h.frames / h.clips, 1); + int clip = min(int(pick * float(h.clips)), h.clips - 1); + float t = (time * h.fps * max(param[2].x, 0.0)) + phase * float(clipframes); + float f = mod(t, float(clipframes)); + int f0 = clip * clipframes + int(floor(f)) % clipframes; + int f1 = clip * clipframes + (int(floor(f)) + 1) % clipframes; + float a = fract(f); + ivec2 t0 = vat_texel(h, vertex, f0, width); + ivec2 t1 = vat_texel(h, vertex, f1, width); + position = mix(vat_position(h, t0), vat_position(h, t1), a); + vec3 n = mix(vat_normal(t0), vat_normal(t1), a); + normal = (dot(n, n) > 1e-6) ? normalize(n) : v_normal; +} + +void main() +{ + mat4 mv = effective_modelview(); + vec3 position; + vec3 normal; + vat_animate(mv, position, normal); +#ifdef MATERIAL_SHADOW + gl_Position = (projection * mv) * vec4(position, 1.0); + f_coord = v_coord; +#else + mat3 mvn = effective_modelviewnormal(); + + f_normal = normalize(mvn * normal); + f_normal_raw = normal; + f_coord = v_coord; + f_pos = mv * vec4(position, 1.0); + f_clip_pos = projection * f_pos; + f_clip_future_pos = (projection * future) * f_pos; + + gl_Position = f_clip_pos; + gl_PointSize = param[1].x; + + vec3 N = f_normal; + vec3 T = mvn * v_tangent.xyz; + T = normalize(T - N * dot(N, T)); + vec3 B = cross(N, T) * (v_tangent.w < 0.0 ? -1.0 : 1.0); + f_tbn = mat3(T, B, N); + TangentFragPos = transpose(f_tbn) * f_pos.xyz; + UserData = v_userdata; +#endif +#ifdef MODEL_DRAWS + // which block of the multi draw the fragments read (common.glsl) + f_model_draw = MODEL_DRAW; +#endif +} From 339d70a6e6ab2439f0415ade16bdc77a707284e4 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Thu, 5 Nov 2026 22:32:59 +0100 Subject: [PATCH 049/123] Moths fly about the lit lamps of the scenery A part of the lamps of the scenery models which shine downwards (moths.share, picked by the places of the lamps) gets a swarm of moths: an instance of animals/cmy.t3d (animated by textures, shader vat) put at the light point when the lamp first comes within moths.range of the camera. The swarm is shown while its lamp shines (the light points gathered by the local lights in the frame), not in the winter and not below moths.temperature. The swarms are made by the game (basic_node::m_generated): not saved with the scenery, not edited. Settings (eu07.ini): moths yes/no, moths.share 0-1 (0.4), moths.range metres (80), moths.temperature degrees (8). Also in the debug window of the lights. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GXgG7F4L42c2F9sDSAJbT2 --- CMakeLists.txt | 1 + lang/editor_pl.po | 5 ++ rendering/common/locallights.cpp | 11 ++- rendering/common/moths.cpp | 140 +++++++++++++++++++++++++++++++ rendering/common/moths.h | 63 ++++++++++++++ scene/scenelayers.cpp | 8 ++ scene/scenenode.cpp | 2 + scene/scenenode.h | 1 + utilities/Globals.cpp | 8 ++ utilities/Globals.h | 6 ++ 10 files changed, 244 insertions(+), 1 deletion(-) create mode 100644 rendering/common/moths.cpp create mode 100644 rendering/common/moths.h diff --git a/CMakeLists.txt b/CMakeLists.txt index c5973e512..a881961db 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -441,6 +441,7 @@ set(SOURCES "rendering/common/gpuparticles.cpp" "rendering/common/windscreenwater.cpp" "rendering/common/locallights.cpp" +"rendering/common/moths.cpp" "rendering/common/skylight.cpp" "rendering/common/weatherstate.cpp" "rendering/common/exposure.cpp" diff --git a/lang/editor_pl.po b/lang/editor_pl.po index 4e845d709..2abe0652d 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -15904,6 +15904,11 @@ msgstr "Nie udało się zapisać sieci trakcyjnej: jej plik \"%s\" jest plikiem msgid "it's a part of the catenary, which is changed with the Catenary tool (F6)" msgstr "to część sieci trakcyjnej, którą zmienia się narzędziem Sieć trakcyjna (F6)" +# scenery editor: moths at the lamps, made by the game + +msgid "it's made by the game while it runs (the moths at a lamp), not a part of the scenery" +msgstr "to robi sama gra podczas jazdy (ćmy przy lampie), nie jest częścią scenerii" + msgid "A part of the catenary: it's changed with the Catenary tool (F6)" msgstr "Część sieci trakcyjnej: zmienia się ją narzędziem Sieć trakcyjna (F6)" diff --git a/rendering/common/locallights.cpp b/rendering/common/locallights.cpp index 524dbb6e4..4b34098a5 100644 --- a/rendering/common/locallights.cpp +++ b/rendering/common/locallights.cpp @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "rendering/common/locallights.h" +#include "rendering/common/moths.h" #include #include @@ -267,6 +268,9 @@ void gfx::local_lights::gather(glm::dvec3 const &Camera, scene::basic_region &Re }); } + // the moths fly about the lamps of the scenery which shine + Moths.update(m_lights, Camera, Framestamp); + auto const elapsed{std::chrono::duration(std::chrono::steady_clock::now() - start).count()}; m_gathertime = (m_gathertime == 0.0 ? elapsed : m_gathertime * 0.95 + elapsed * 0.05); } @@ -281,6 +285,7 @@ void gfx::local_lights::reset() m_sections.clear(); m_models.clear(); m_scenerycount = m_vehiclecount = m_compartmentcount = m_placed = m_dropped = 0; + Moths.reset(); } void gfx::local_lights::forget(scene::basic_node const *) @@ -738,7 +743,7 @@ std::string gfx::local_lights::info() const { return "local lights: " + std::to_string(m_lights.size()) + " (scenery " + std::to_string(m_scenerycount) + ", vehicles " + std::to_string(m_vehiclecount) + ", compartments " + std::to_string(m_compartmentcount) + ")" + (m_cablampon ? " + cab lights " + std::to_string(m_cablights.size()) : "") + ", placed " + std::to_string(m_placed) + ", over capacity " + std::to_string(m_dropped) + - ", gather " + to_string(m_gathertime, 2) + " ms"; + ", gather " + to_string(m_gathertime, 2) + " ms, moth swarms " + std::to_string(Moths.shown()) + "/" + std::to_string(Moths.count()); } void gfx::local_lights::draw_debug_ui() @@ -752,6 +757,10 @@ void gfx::local_lights::draw_debug_ui() ImGui::SliderFloat("cab lamp brightness", &Global.gfx_lights_cab_intensity, 0.f, 10.f); ImGui::SliderFloat("cab ambient kept", &Global.gfx_lights_cab_bounce, 0.f, 1.f); ImGui::SliderFloat("range, m", &Global.gfx_lights_range, 0.f, 1000.f); + ImGui::Checkbox("moths at the lamps of the scenery", &Global.moths); + ImGui::SliderFloat("moths: part of the lamps", &Global.moths_share, 0.f, 1.f); + ImGui::SliderFloat("moths: range, m", &Global.moths_range, 0.f, 300.f); + ImGui::Text("moth swarms shown %u, made %u", static_cast(Moths.shown()), static_cast(Moths.count())); ImGui::Text("gathered %u: scenery %u, vehicles %u, compartments %u, cab %u", static_cast(m_lights.size()), m_scenerycount, m_vehiclecount, m_compartmentcount, static_cast(m_cablights.size())); ImGui::Text("in the light buffer %u, over capacity %u", m_placed, m_dropped); diff --git a/rendering/common/moths.cpp b/rendering/common/moths.cpp new file mode 100644 index 000000000..16399b6c7 --- /dev/null +++ b/rendering/common/moths.cpp @@ -0,0 +1,140 @@ +/* +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 "rendering/common/moths.h" +#include +#include +#include +#include "utilities/Globals.h" +#include "model/AnimModel.h" +#include "scene/scenenode.h" +#include "scene/scenelayers.h" +#include "simulation/simulation.h" + +namespace +{ + +// the model of a swarm, models/ and the extension left out +char const *const Swarmmodel{"animals/cmy"}; + +// a number 0-1 for the place, the same every time for the same place (whole half metres) +double place_number(glm::dvec3 const &Position) +{ + auto const x{static_cast(std::floor(Position.x * 2.0))}; + auto const y{static_cast(std::floor(Position.y * 2.0))}; + auto const z{static_cast(std::floor(Position.z * 2.0))}; + auto hash{static_cast(x) * 0x9E3779B97F4A7C15ull ^ static_cast(y) * 0xC2B2AE3D27D4EB4Full ^ static_cast(z) * 0x165667B19E3779F9ull}; + hash ^= hash >> 33; + hash *= 0xff51afd7ed558ccdull; + hash ^= hash >> 33; + hash *= 0xc4ceb9fe1a85ec53ull; + hash ^= hash >> 33; + return static_cast(hash >> 11) / static_cast(1ull << 53); +} + +// moths fly in the warm part of the year +bool moths_fly() +{ + return Global.moths && (Global.Season != "winter:") && (Global.AirTemperature >= Global.moths_temperature); +} + +} // namespace + +gfx::moths gfx::Moths; + +void gfx::moths::update(std::vector const &Lights, glm::dvec3 const &Camera, unsigned int const Framestamp) +{ + auto const flying{moths_fly() && (Global.moths_share > 0.f) && (Global.moths_range > 0.f)}; + if (flying) + { + auto const range{static_cast(Global.moths_range)}; + for (auto const &light : Lights) + { + // the lamps of the scenery models, shining downwards (street and platform lamps; not the signals) + if ((light.owner == nullptr) || (light.part == nullptr) || (light.direction.y > -0.5f)) + { + continue; + } + auto const key{std::make_pair(light.owner, light.part)}; + auto lookup{m_lamps.find(key)}; + if ((lookup != m_lamps.end()) && (glm::length(lookup->second.position - light.position) > 0.5)) + { + // another lamp in the place of the one met before (the editor took it away and put a new one) + if (lookup->second.model != nullptr) + { + lookup->second.model->visible(false); + } + lookup = m_lamps.end(); + m_lamps.erase(key); + } + if (lookup == m_lamps.end()) + { + if (glm::length(light.position - Camera) > range) + { + // decided when the lamp comes closer + continue; + } + swarm entry; + entry.position = light.position; + auto chosen{place_number(light.position) < static_cast(Global.moths_share)}; + for (auto const &place : m_places) + { + if (glm::length(place - light.position) < 1.0) + { + // the other light point of the same lamp has a swarm already + chosen = false; + break; + } + } + if (chosen) + { + auto const definition{"node " + std::to_string(static_cast(std::ceil(range))) + " 0 none model 0 0 0 0 " + std::string{Swarmmodel} + ".t3d none endmodel"}; + auto *model{simulation::State.create_model(definition, "none", light.position)}; + if (model != nullptr) + { + // not a part of the scenery: no layer of it, not saved, not edited + scene::Layers.count(model->layer(), scene::layer_item::model, -1); + model->layer(null_handle); + model->m_dirty = false; + model->m_generated = true; + model->visible(false); + ++scene::node_state_version; + entry.model = model; + m_places.emplace_back(light.position); + ++m_count; + } + } + lookup = m_lamps.emplace(key, entry).first; + } + lookup->second.seen = Framestamp; + } + } + // the swarms of the lamps lit in this frame are shown + m_shown = 0; + for (auto &lamp : m_lamps) + { + auto &entry{lamp.second}; + if (entry.model == nullptr) + { + continue; + } + auto const shown{flying && (entry.seen == Framestamp)}; + entry.model->visible(shown); + m_shown += (shown ? 1 : 0); + } +} + +void gfx::moths::reset() +{ + // the instances go with the scenery + m_lamps.clear(); + m_places.clear(); + m_count = m_shown = 0; +} diff --git a/rendering/common/moths.h b/rendering/common/moths.h new file mode 100644 index 000000000..ca2e71643 --- /dev/null +++ b/rendering/common/moths.h @@ -0,0 +1,63 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include +#include "rendering/common/locallights.h" + +class TAnimModel; + +// moths flying about the lit lamps of the scenery. a part of the lamps of the scenery models which shine downwards (Global.moths_share, +// picked by the places of the lamps, so always the same ones) gets a swarm: an instance of the model animals/cmy (animated by textures, +// shader vat: the swarms differ in the moment and the clip of the animation by their places) put in the scenery at the light point. +// the swarm is shown while its lamp shines (the light points the local lights gathered in the frame), in the warm part of the year +// (not in the winter, the air not colder than Global.moths_temperature), to Global.moths_range from the camera. the swarms are made +// when their lamps first come within the range, aren't parts of the scenery (not saved, not edited) and go with it +namespace gfx +{ + +class moths +{ + public: + // after the lights of the frame were gathered: makes the swarms of the lamps which came within the range, shows the swarms of the + // lit lamps and hides the others + void update(std::vector const &Lights, glm::dvec3 const &Camera, unsigned int const Framestamp); + // forgets the swarms: the scenery they were put in is about to be replaced + void reset(); + // swarms made, and shown in the last frame + std::size_t count() const + { + return m_count; + } + std::size_t shown() const + { + return m_shown; + } + + private: + struct swarm + { + glm::dvec3 position{0.0}; // of the light point the swarm was decided for + TAnimModel *model{nullptr}; // nullptr: the lamp has no swarm + unsigned int seen{0}; // the frame the lamp shone last in + }; + // the lamps met: the instance and the submodel of the light point + std::map, swarm> m_lamps; + std::vector m_places; // of the swarms made, so two light points of one lamp don't both get one + std::size_t m_count{0}; + std::size_t m_shown{0}; +}; + +// the swarms of the scenery, kept by the local lights (local_lights::gather(), reset()) +extern moths Moths; + +} // namespace gfx diff --git a/scene/scenelayers.cpp b/scene/scenelayers.cpp index 9e075d063..e729fac7b 100644 --- a/scene/scenelayers.cpp +++ b/scene/scenelayers.cpp @@ -393,6 +393,14 @@ bool node_layers::editable(basic_node const *Node, std::string *Reason) const { return false; } + if (Node->m_generated) + { + if (Reason != nullptr) + { + *Reason = STR_C("it's made by the game while it runs (the moths at a lamp), not a part of the scenery"); + } + return false; + } if (Node->m_catenary) { // moved, copied or deleted by itself it would part from the catenary which keeps it (and is rebuilt from its own file) diff --git a/scene/scenenode.cpp b/scene/scenenode.cpp index afe87cf83..d46413835 100644 --- a/scene/scenenode.cpp +++ b/scene/scenenode.cpp @@ -776,6 +776,8 @@ basic_node::deserialize( std::istream &Input ) { void basic_node::export_as_text( std::ostream &Output ) const { + // what the game made while it runs isn't a part of the scenery + if( m_generated ) { return; } Output // header << "node" diff --git a/scene/scenenode.h b/scene/scenenode.h index d0246adc1..adf21c603 100644 --- a/scene/scenenode.h +++ b/scene/scenenode.h @@ -423,6 +423,7 @@ public: bool m_layerhidden { false }; // the node was visible until the editor hid its scenery layer, or the include which defines it bool m_preview { false }; // the node was made by the editor to show an include it placed or changed, and is replaced when the include changes bool m_catenary { false }; // a part the catenary assembled (world/catenary_scene.cpp): it's changed by the catenary tool, not edited as a node + bool m_generated { false }; // made by the game while it runs (the moths at the lamps, rendering/common/moths.cpp): not edited, not saved scene::layer_handle m_layer { null_handle }; // scenery layer this node belongs to, if any // include of an *.inc template which defines the node; 0 if the node is defined directly by a scenery layer file. // such nodes can't be rewritten one by one on scenery save. set only for scenery opened for editing diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index cb034614b..bd6bf9001 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -2275,6 +2275,10 @@ global_settings::ConfigParse_gfx_sky( cParser &Parser, std::string_view const To else if( Token == "gfx.skyvisibility.tunnels" ) { readswitch( gfx_skyvisibility_tunnels ); } else if( Token == "gfx.tunnelflags" ) { readswitch( gfx_tunnelflags ); } else if( Token == "gfx.lights.range" ) { readvalue( gfx_lights_range, 0.f, 2000.f ); } + else if( Token == "moths" ) { readswitch( moths ); } + else if( Token == "moths.share" ) { readvalue( moths_share, 0.f, 1.f ); } + else if( Token == "moths.range" ) { readvalue( moths_range, 0.f, 500.f ); } + else if( Token == "moths.temperature" ) { readvalue( moths_temperature, -50.f, 50.f ); } else if( Token == "gfx.lights.shadows" ) { // no/low/medium/high, or the number of the level Parser.getTokens( 1 ); @@ -2848,6 +2852,10 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "gfx.skyvisibility.tunnels", gfx_skyvisibility_tunnels ); export_as_text( Output, "gfx.tunnelflags", gfx_tunnelflags ); export_as_text( Output, "gfx.lights.range", gfx_lights_range ); + export_as_text( Output, "moths", moths ); + export_as_text( Output, "moths.share", moths_share ); + export_as_text( Output, "moths.range", moths_range ); + export_as_text( Output, "moths.temperature", moths_temperature ); export_as_text( Output, "gfx.lights.shadows", std::string{ gfx_lights_shadows == 3 ? "high" : gfx_lights_shadows == 2 ? "medium" : gfx_lights_shadows == 1 ? "low" : "no" } ); export_as_text( Output, "gfx.lights.shadows.cab", gfx_lights_shadows_cab ); export_as_text( Output, "gfx.lights.shadows.lamps", gfx_lights_shadows_lamps ); diff --git a/utilities/Globals.h b/utilities/Globals.h index e69a96955..bf9de1472 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -647,6 +647,12 @@ struct global_settings { // the sound and the driver bool gfx_tunnelflags { false }; float gfx_lights_range { 300.f }; // distance from the camera the lights of models and vehicles are taken from, metres + // moths flying about the lit lamps of the scenery (rendering/common/moths.cpp): a swarm (the model animals/cmy, animated by + // textures) at a part of the lamps shining downwards, picked by their places, in the warm months, within the range of the camera + bool moths { true }; + float moths_share { 0.4f }; // part of the lamps with a swarm, 0-1 + float moths_range { 80.f }; // distance from the camera the swarms are shown at, metres + float moths_temperature { 8.f }; // the lowest temperature of the air moths fly at, degrees Celsius // shadows of the lamps (cube shadow maps), 0 none, 1 low, 2 medium, 3 high; see opengl46_local_shadows. for now the lamp of the // occupied cab, its shadows cast by the cab int gfx_lights_shadows { 2 }; From 394e252daf618d85e4e27e411999ed4065dd3323 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 15:54:28 +0100 Subject: [PATCH 050/123] Rain windscreen: the cells of the drops and rivulets worked out once a frame The glass with rain worked out, in every pixel, the hashes and the life cycles of the 9 drop cells around it, of the rivulet cells of its 5 layers and of those the drops are swept by. A compute pass (rain_cells.comp) now does it once a frame for every cell into a buffer (rain_cells.glsl: RAIN_CELLS_SSBO in the pass set of Vulkan 1.4, binding 18 in OpenGL 4.6); the glass only reads it, and asks the wipers only for the drops the pixel lies on. The hashes are the same, so the drops and the rivulets are where they were. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- gl/glsl_common.cpp | 1 + gl/ubo.h | 8 ++ rendering/opengl46/opengl46renderer.cpp | 4 + rendering/opengl46/opengl46water.cpp | 32 +++++ rendering/opengl46/opengl46water.h | 10 +- rendering/vulkan14/vulkan14bindings.h | 5 +- rendering/vulkan14/vulkan14frame.cpp | 2 + rendering/vulkan14/vulkan14scene.cpp | 3 + rendering/vulkan14/vulkan14shaders.cpp | 1 + rendering/vulkan14/vulkan14water.cpp | 52 ++++++++ rendering/vulkan14/vulkan14water.h | 11 ++ shaders/ogl46/common.glsl | 1 + shaders/ogl46/mat_rain_windscreen.frag | 168 ++++++++++-------------- shaders/ogl46/rain_cells.comp | 131 ++++++++++++++++++ shaders/ogl46/rain_cells.glsl | 67 ++++++++++ shaders/vk14/common.glsl | 3 +- shaders/vk14/mat_rain_windscreen.frag | 168 ++++++++++-------------- shaders/vk14/rain_cells.comp | 136 +++++++++++++++++++ shaders/vk14/rain_cells.glsl | 67 ++++++++++ 19 files changed, 674 insertions(+), 196 deletions(-) create mode 100644 shaders/ogl46/rain_cells.comp create mode 100644 shaders/ogl46/rain_cells.glsl create mode 100644 shaders/vk14/rain_cells.comp create mode 100644 shaders/vk14/rain_cells.glsl diff --git a/gl/glsl_common.cpp b/gl/glsl_common.cpp index f6f3df06d..981d7b05e 100644 --- a/gl/glsl_common.cpp +++ b/gl/glsl_common.cpp @@ -53,6 +53,7 @@ void gl::glsl_common_setup() "#define WATER_MAP " + std::to_string(WATER_MAP) + "\n" + "#define WATER_GROUP_SIZE " + std::to_string(WATER_GROUP_SIZE) + "\n" + "#define WATER_SSBO_BINDING " + std::to_string(WATER_SSBO_BINDING) + "\n" + + "#define RAIN_CELLS_SSBO_BINDING " + std::to_string(RAIN_CELLS_SSBO_BINDING) + "\n" + "#define WATER_UBO_BINDING " + std::to_string(WATER_UBO_BINDING) + "\n" + "#define WATER_MASK_TEX " + std::to_string(WATER_MASK_TEX) + "\n" + "#define INSTANCE_COUNTER_HEADER " + std::to_string(INSTANCE_COUNTER_HEADER) + "\n" + diff --git a/gl/ubo.h b/gl/ubo.h index 2f6955107..6be7979ad 100644 --- a/gl/ubo.h +++ b/gl/ubo.h @@ -710,6 +710,14 @@ namespace gl // of the step of the simulation (water_ubs) and the texture unit of the mask of the wipers the map is baked from. the storage // point is used by nothing else, bound with the colour passes const GLuint WATER_SSBO_BINDING = 16; + // the drops and the rivulets of the cells of the glasses with rain (mat_rain_windscreen, rain_cells.comp, rain_cells.glsl): worked + // out once a frame for every cell, so a glass only reads them. RAIN_CELLS_COUNT uvec4, as rain_cells.glsl lays them out + const GLuint RAIN_CELLS_SSBO_BINDING = 18; + const size_t RAIN_DROP_CELLS = 512; + const size_t RAIN_RIV_CELLS = 128; + const size_t RAIN_RIV_LAYERS = 5; + const size_t RAIN_CELLS_COUNT = RAIN_DROP_CELLS * RAIN_DROP_CELLS + RAIN_RIV_LAYERS * RAIN_RIV_CELLS * RAIN_RIV_CELLS; + const size_t RAIN_CELLS_GROUP_SIZE = 64; const GLuint WATER_UBO_BINDING = 6; const size_t WATER_MASK_TEX = MAX_TEXTURES + HELPER_TEXTURES + 13; // the parts of the storage of the water (std430, GLSL water_ssbo), offsets in bytes: the header of every glass (vec4), the diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index 7953056c1..99f2f45a1 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -1765,7 +1765,11 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) scene_ubo->bind_uniform(); // the water on the windscreens of the cab: a step of its simulation once a frame, its storage for the glasses of every view if (vp.main) + { m_windscreenwater.update(Timer::GetDeltaTime()); + // the drops and the rivulets of the glasses with rain, for the time of the block of the scene + m_windscreenwater.update_rain_cells(scene_ubs.time, scene_ubs.rain_params.x); + } m_windscreenwater.bind(); if (Global.bWireFrame) diff --git a/rendering/opengl46/opengl46water.cpp b/rendering/opengl46/opengl46water.cpp index a48b9edfb..bd7ce27d9 100644 --- a/rendering/opengl46/opengl46water.cpp +++ b/rendering/opengl46/opengl46water.cpp @@ -83,6 +83,38 @@ void opengl46_windscreen_water::bind() const { if (m_storage) m_storage->bind_base(); + if (m_raincells) + m_raincells->bind_base(); +} + +void opengl46_windscreen_water::update_rain_cells(float const Time, float const Rain) +{ + if (Rain <= 0.f) + return; + if (false == m_raincelltried) + { + m_raincelltried = true; + try + { + gl::shader shader("rain_cells.comp"); + m_raincellprogram = std::make_unique(std::vector>{shader}); + m_raincells = std::make_unique(static_cast(gl::RAIN_CELLS_COUNT * 16), gl::RAIN_CELLS_SSBO_BINDING); + } + catch (gl::shader_exception const &e) + { + ErrorLog("rain cells: can't use rain_cells.comp, the glasses with rain stay dry: " + std::string(e.what())); + m_raincellprogram.reset(); + } + } + if ((!m_raincellprogram) || (!m_raincells)) + return; + // the glasses of the frame before read the cells, this one writes them + ::glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); + m_raincells->bind_base(); + ::glProgramUniform1f(*m_raincellprogram, 0, Time); + m_raincellprogram->dispatch(static_cast((gl::RAIN_CELLS_COUNT + gl::RAIN_CELLS_GROUP_SIZE - 1) / gl::RAIN_CELLS_GROUP_SIZE)); + ::glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); + gl::program::unbind(); } void opengl46_windscreen_water::gpu_setup(std::size_t const Slot, std::vector const &Axes) diff --git a/rendering/opengl46/opengl46water.h b/rendering/opengl46/opengl46water.h index f609291c9..7e5a20d29 100644 --- a/rendering/opengl46/opengl46water.h +++ b/rendering/opengl46/opengl46water.h @@ -27,10 +27,9 @@ class opengl46_windscreen_water : public gfx::windscreen_water // the storage bound to its point for the glasses drawn next (the bindings are kept by every context of its own) void bind() const; - // the next of the programs of the simulation compiled ahead of its first step (a few seconds each where the driver has none - // of them kept, at the first start of a new version), so the loading screen stays while they're made. false once all are - bool prepare_next(); - static constexpr std::size_t program_count() { return pass::count; } + // the drops and the rivulets of the cells of the glasses with rain (mat_rain_windscreen, rain_cells.comp) worked out for the + // time of the frame (scene_ubs.time), once a frame before the passes; nothing while it doesn't rain + void update_rain_cells(float Time, float Rain); protected: bool gpu_init() override; @@ -56,4 +55,7 @@ class opengl46_windscreen_water : public gfx::windscreen_water std::array, pass::count> m_programs; std::unique_ptr m_storage; std::unique_ptr m_block; + std::unique_ptr m_raincellprogram; + std::unique_ptr m_raincells; + bool m_raincelltried{false}; }; diff --git a/rendering/vulkan14/vulkan14bindings.h b/rendering/vulkan14/vulkan14bindings.h index 0e98ccc88..c671e372f 100644 --- a/rendering/vulkan14/vulkan14bindings.h +++ b/rendering/vulkan14/vulkan14bindings.h @@ -86,7 +86,10 @@ constexpr std::uint32_t SKY_OCCLUSION_HEIGHT_TEX = 31; constexpr std::uint32_t SKY_OCCLUSION_TEX = 32; // the probe of the cab drawn last, a small level of its albedo, which the drawing of the probe reads to tell where the windows are constexpr std::uint32_t CAB_PROBE_MASK_TEX = 33; -constexpr std::uint32_t PASS_BINDING_COUNT = 34; +// the drops and the rivulets of the cells of the glasses with rain (mat_rain_windscreen, rain_cells.comp): worked out once a frame +// for every cell, so a glass only reads them +constexpr std::uint32_t RAIN_CELLS_SSBO = 34; +constexpr std::uint32_t PASS_BINDING_COUNT = 35; // the offsets of the bindings above with dynamic offsets, in the order of the bindings constexpr std::uint32_t PASS_DYNAMIC_OFFSETS = 6; // the textures of a material take the bindings of their units (#pragma texture(name, unit, ...)), 0 .. MAX_TEXTURES - 1 diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index 9e3c05ca0..30c56a2a2 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -1135,6 +1135,8 @@ void vulkan14_renderer::render_scene() auto &scene{ctx.scene}; // the water on the windscreens of the cab: a step of its simulation once a frame, before the passes which draw the glasses scene.water.update(Timer::GetDeltaTime()); + // the drops and the rivulets of the glasses with rain, for the time the block of the scene gets (scene_ubs.time) + scene.water.update_rain_cells(static_cast(Timer::GetTime()), glm::saturate(Global.Overcast - 1.f)); if (scene.targets.size() < m_viewports.size()) { scene.targets.resize(m_viewports.size()); diff --git a/rendering/vulkan14/vulkan14scene.cpp b/rendering/vulkan14/vulkan14scene.cpp index d640b5335..0e221446a 100644 --- a/rendering/vulkan14/vulkan14scene.cpp +++ b/rendering/vulkan14/vulkan14scene.cpp @@ -182,6 +182,7 @@ VkDescriptorType pass_binding_type(std::uint32_t const Binding) case CLUSTER_INDEX_SSBO: case SKY_SSBO: case WATER_SSBO: + case RAIN_CELLS_SSBO: case CAB_PROBE_SSBO: return VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; case ATMOSPHERE_UBO: @@ -1093,6 +1094,7 @@ void vulkan14_renderer::write_pass_sets(vk14::instance_cull *Cull) VkDescriptorBufferInfo const weatherblock{ctx.ring.handle(), 0, offsetof(gl::weather_ubs, fog_horizon)}; VkDescriptorBufferInfo const horizonblock{scene.weather_horizon.handle(), 0, sizeof(glm::vec4) * gl::FOG_HORIZON_SAMPLES}; VkDescriptorBufferInfo const water{scene.water.storage(), 0, VK_WHOLE_SIZE}; + VkDescriptorBufferInfo const raincells{scene.water.rain_cells(), 0, VK_WHOLE_SIZE}; VkDescriptorBufferInfo const cabprobe{scene.cabprobe_bounce.handle(), 0, sizeof(gl::cab_probe_data)}; VkDescriptorImageInfo const headlightsinfo{scene.headlights_sampler, scene.headlights_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}; std::vector writes; @@ -1128,6 +1130,7 @@ void vulkan14_renderer::write_pass_sets(vk14::instance_cull *Cull) write(handle, WEATHER_UBO, &weatherblock, nullptr); write(handle, WEATHER_HORIZON_UBO, &horizonblock, nullptr); write(handle, WATER_SSBO, &water, nullptr); + write(handle, RAIN_CELLS_SSBO, &raincells, nullptr); write(handle, HEADLIGHT_TEX, nullptr, &headlightsinfo); write(handle, SHADOW_TEX, nullptr, image(ctx.sampling.shadow, views[SHADOW_TEX])); write(handle, ENV_TEX, nullptr, image(ctx.sampling.clamp_linear, views[ENV_TEX])); diff --git a/rendering/vulkan14/vulkan14shaders.cpp b/rendering/vulkan14/vulkan14shaders.cpp index b0101f9eb..59b51b1d1 100644 --- a/rendering/vulkan14/vulkan14shaders.cpp +++ b/rendering/vulkan14/vulkan14shaders.cpp @@ -898,6 +898,7 @@ std::string binding_preamble(bool const Raytracing) define("SKY_OCCLUSION_HEIGHT_TEX", SKY_OCCLUSION_HEIGHT_TEX); define("SKY_OCCLUSION_TEX", SKY_OCCLUSION_TEX); define("CAB_PROBE_MASK_TEX", CAB_PROBE_MASK_TEX); + define("RAIN_CELLS_SSBO", RAIN_CELLS_SSBO); define("PASS_BINDING_COUNT", PASS_BINDING_COUNT); define("MATERIAL_TEXTURE_FIRST", MATERIAL_TEXTURE_FIRST); define("CL_CLUSTER_UBO", CL_CLUSTER_UBO); diff --git a/rendering/vulkan14/vulkan14water.cpp b/rendering/vulkan14/vulkan14water.cpp index 4d323b333..5c32c2974 100644 --- a/rendering/vulkan14/vulkan14water.cpp +++ b/rendering/vulkan14/vulkan14water.cpp @@ -49,6 +49,12 @@ bool windscreen_water::init(VkDevice const Device, pipeline_library &Pipelines, m_ring = &Ring; m_alignment = std::max(Alignment, 16); m_host = std::move(Host); + m_raincells = std::make_shared(); + if (false == m_raincells->create(Memory, static_cast(gl::RAIN_CELLS_COUNT * 16), storage_usage, memory_kind::device, "rain cells")) + { + m_raincells.reset(); + return false; + } m_storage = std::make_shared(); m_full = m_storage->create(Memory, static_cast(gl::WATER_STORAGE_SIZE), storage_usage, memory_kind::device, "windscreen water"); if (false == m_full) @@ -75,6 +81,9 @@ void windscreen_water::destroy() { kernel.destroy(m_device); } + m_raincellkernel.destroy(m_device); + m_raincelltried = false; + m_raincells.reset(); m_storage.reset(); m_device = VK_NULL_HANDLE; m_cleared = false; @@ -164,6 +173,49 @@ void windscreen_water::gpu_setup(std::size_t const Slot, std::vector m_deletions->push(m_uploads->current_value(), [staging]() {}); } +void windscreen_water::update_rain_cells(float const Time, float const Rain) +{ + if ((m_device == VK_NULL_HANDLE) || (false == bool(m_raincells)) || (Rain <= 0.f) || (false == bool(m_host.commands))) + { + return; + } + if (false == m_raincelltried) + { + m_raincelltried = true; + try + { + if (false == m_raincellkernel.create(m_device, *m_pipelines, m_shaders->get("rain_cells.comp"), m_passlayout, {}, "rain_cells.comp")) + { + ErrorLog("rain cells: no compute pipeline of rain_cells.comp, the glasses with rain stay dry"); + } + } + catch (gfx::shader_exception const &e) + { + ErrorLog("rain cells: can't use rain_cells.comp: " + std::string(e.what())); + } + } + if (false == bool(m_raincellkernel)) + { + return; + } + auto const commands{m_host.commands()}; + if (commands == nullptr) + { + return; + } + // the glasses of the frames before read the cells, this one writes them + memory_barrier(commands, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, VK_ACCESS_2_SHADER_STORAGE_READ_BIT | VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, + VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT); + struct constants + { + float time; + float pad[3]; + } const data{Time, {0.f, 0.f, 0.f}}; + m_raincellkernel.dispatch(commands, {buffer_descriptor(m_raincells->handle(), 0, VK_WHOLE_SIZE)}, data, + static_cast((gl::RAIN_CELLS_COUNT + gl::RAIN_CELLS_GROUP_SIZE - 1) / gl::RAIN_CELLS_GROUP_SIZE)); + compute_barrier(commands); +} + ring_slice windscreen_water::block(gl::water_ubs const &Block) { auto const slice{m_ring->allocate(sizeof(gl::water_ubs), m_alignment)}; diff --git a/rendering/vulkan14/vulkan14water.h b/rendering/vulkan14/vulkan14water.h index 2b24bbf9d..901e241bd 100644 --- a/rendering/vulkan14/vulkan14water.h +++ b/rendering/vulkan14/vulkan14water.h @@ -50,6 +50,14 @@ class windscreen_water : public gfx::windscreen_water { return m_storage ? m_storage->handle() : VK_NULL_HANDLE; } + // the drops and the rivulets of the cells of the glasses with rain (RAIN_CELLS_SSBO, rain_cells.comp), the pass sets hold it + VkBuffer rain_cells() const + { + return m_raincells ? m_raincells->handle() : VK_NULL_HANDLE; + } + // the cells worked out for the time of the frame (the time of the block of the scene), with the commands of the frame before + // its passes; nothing while it doesn't rain + void update_rain_cells(float Time, float Rain); protected: bool gpu_init() override; @@ -89,6 +97,9 @@ class windscreen_water : public gfx::windscreen_water host m_host; std::array m_kernels; std::shared_ptr m_storage; + std::shared_ptr m_raincells; + compute_kernel m_raincellkernel; + bool m_raincelltried{false}; bool m_full{false}; // the storage is as large as the simulation needs (else a stand-in, the glasses make their water up) bool m_cleared{false}; }; diff --git a/shaders/ogl46/common.glsl b/shaders/ogl46/common.glsl index 4ba306c3f..01bdfab85 100644 --- a/shaders/ogl46/common.glsl +++ b/shaders/ogl46/common.glsl @@ -62,6 +62,7 @@ #define WATER_MAP 256 #define WATER_GROUP_SIZE 64 #define WATER_SSBO_BINDING 16 +#define RAIN_CELLS_SSBO_BINDING 18 #define WATER_UBO_BINDING 6 #define WATER_MASK_TEX 25 #define INSTANCE_COUNTER_HEADER 8 diff --git a/shaders/ogl46/mat_rain_windscreen.frag b/shaders/ogl46/mat_rain_windscreen.frag index ec7fdc6a3..e4e2de711 100644 --- a/shaders/ogl46/mat_rain_windscreen.frag +++ b/shaders/ogl46/mat_rain_windscreen.frag @@ -18,6 +18,10 @@ // The trail right above the head is taken from the sprite part that touches the head, then it blends // into the trail pattern that is fixed to the glass (beads stay where they were left). // +// Speed: the hashes and the life cycles of the cells (which drop a cell holds now, where, how big; where the head of a rivulet is) +// are worked out once a frame for every cell by rain_cells.comp (rain_cells.glsl), not here for the 9 cells around every pixel; +// the wipers are asked only for the drops the pixel lies on. the look is the same. +// // Shading: the grey atlas (bright rim, dark middle) is read once per pixel, only for the drop that wins the // pixel (it used to be read for all 9 neighbours). Micro droplets are shaded analytically. // @@ -64,6 +68,7 @@ layout(location = 1) out vec4 out_motion; #include "apply_fog.glsl" #include "tonemapping.glsl" #include "random.glsl" +#include "rain_cells.glsl" layout(binding = 0) uniform sampler2D diffuse; layout(binding = 1) uniform sampler2D raindropsatlas; @@ -83,14 +88,11 @@ const float WS_DROP_BIAS = 192.0; const float WS_ENC = 64.0; // the haze request in the velocity target; must match rain_windscreen_haze.glsl // --- Drops (atlas tiles) ------------------------------------------------------ +// (how long they live: rain_cells.glsl; the cells of the drops and of the rivulets are worked out once a frame by rain_cells.comp) const float drop_density = 0.6; // share of grid cells holding a drop at full rain (scaled by rain intensity) const float drop_size_min = 0.45; // drop size in grid cells const float drop_size_max = 1.15; const float drop_size_bias = 1.8; // >1 = more small/medium drops, fewer big ones -const float drop_life_min = 14.0; // seconds a drop sits on the glass -const float drop_life_max = 45.0; -const float drop_appear = 0.18; // seconds of the landing "pop" -const float drop_fade = 1.5; // seconds a drop takes to vanish at the end of its life const float drop_sag = 0.12; // max vertical stretch of a resting drop (gravity) // --- Micro droplets ------------------------------------------------------------- @@ -130,7 +132,6 @@ const float streak_density = 1.00; // share of cells carrying a rivulet (scal const float streak_cell = 6.0; // width of a rivulet cell in drop cells const float streak_run = 20.0; // height of a rivulet cell in drop cells = the longest run of one rivulet const float streak_head = 1.7; // mean width of the drop head, in drop cells (randomised 0.75x .. 1.25x) -const float streak_period = 40.0; // seconds a rivulet lives (it runs for ~90% of that and then fades out), average const float streak_wiggle = 0.35; // how far the path swings sideways, in head widths (0 = straight) const float streak_wiggle_speed = 0.5; // speed of the little waves that flow down the trail const float streak_flow = 0.15; // ripples flowing down inside the trail (shows in refraction and glints), 0 = off @@ -152,7 +153,6 @@ const float wind_run_scale = 1.2; // ... and their runs this long against const float wind_head_scale = 0.4; // their heads this much smaller (a small bead at the front of a long trail) const int wind_layers = 4; // layers of them, each with drops of its own (1 .. 4) const float wind_long_run = 3.0; // the last layer: its trails this much longer than those of gravity (the long ones, a part of all) -const float wind_streak_period = 18.0; // seconds a rivulet driven by the air lives (they run faster than the ones of gravity) const float drop_wind_stretch = 0.4; // drops are stretched up to this much along the push of the air (0 = off) const float WS_DRAG_SPEED = 24.0; // speed of the air along the glass at which its drag equals the weight of a drop, m/s const float WS_HEAD_ON = 0.35; // share of the air meeting the glass head on which turns up along it @@ -164,13 +164,7 @@ const float WS_WIND_STEP = 0.1309; // the direction of the rivulets of the const float streak_thin = 0.5; // the thinnest const float streak_thick = 2.0; // the thickest const float streak_thick_bias = 2.0; // > 1: more thin ones -// --- What the blades leave: they don't take every drop (a few stay where they were), and the water they push lies along the edge -// of their sweep, just outside it, as a row of beads (where the blades went lately) ------------------------------------------------ -const float wiper_miss = 0.05; // share of the drops a blade goes over without taking them -const float wiper_edge_boost = 0.0; // along the edge of the sweep this many times more drops (and droplets) (0 = off) ... -const float wiper_edge_size = 0.65; // ... this much smaller: a row of beads -const float wiper_edge_reach = 4.0; // how wide the row is: the mip level of the mask read (4: ~16 texels of the mask out) -const float wiper_edge_keep = 180.0; // seconds after the last stroke the water at the edge keeps (then it's like the rest of the glass) +// --- What the blades leave: they don't take every drop (a few stay where they were): wiper_miss of rain_cells.glsl ----------------- #ifndef STREAK_FLIP_Y #define STREAK_FLIP_Y 0 // set to 1 if the rivulets run UP the glass (head on top) @@ -309,8 +303,7 @@ struct Riv // the layer of rivulets being worked on: the one of gravity (the rivulets as they always were, coordinates = glass UV with v // up) or the one of the air (its own cells and seeds, turned so that its rivulets run along the push of the air) float wsLayerDensity = 1.0; // x rain x streak_density: share of the cells holding a rivulet -float wsLayerPeriod = streak_period; -uint wsLayerSalt = 91u; +int wsLayerIndex = 0; // its cells in rain_cells (0 gravity, 1 .. 4 the air) float wsLayerHead = 1.0; // x streak_head float wsLayerCos = 1.0; // the layer is turned by this angle (its "down" is the way its water runs on the glass) float wsLayerSin = 0.0; @@ -344,8 +337,7 @@ void wsSetLayer(int layer) if (layer == 0) { wsLayerDensity = 1.0 - wsWindShare; - wsLayerPeriod = streak_period; - wsLayerSalt = 91u; + wsLayerIndex = 0; wsLayerHead = 1.0; wsLayerCos = 1.0; wsLayerSin = 0.0; @@ -354,8 +346,7 @@ void wsSetLayer(int layer) else { wsLayerDensity = wsWindShare * wind_streaks; - wsLayerPeriod = wind_streak_period; - wsLayerSalt = 91u + 2u * uint(layer); + wsLayerIndex = layer; wsLayerHead = wind_head_scale; wsLayerCos = wsWindCos; wsLayerSin = wsWindSin; @@ -363,35 +354,33 @@ void wsSetLayer(int layer) } } +// the rivulet of cell SCell of the layer set (wsSetLayer): the randoms and the life of the cell from rain_cells (rain_cells.comp +// worked them out as this did once from the hashes of the cell), the sizes and the places from them Riv getRiv(vec2 sCell, float sCW, float sCH, float gridSize) { Riv r; - uint sSeed = Hash(uvec3(cellKey(sCell), wsLayerSalt)); - r.on = (RandF(sSeed) < rain_params.x * streak_density * wsLayerDensity); - float sPeriod = wsLayerPeriod * mix(0.6, 1.6, RandF(sSeed)); - float sPhase = fract(time / sPeriod + RandF(sSeed)); - r.life = smoothstep(0.0, 0.05, sPhase) * (1.0 - smoothstep(0.86, 1.0, sPhase)); - float wr = RandF(sSeed); + uvec4 d = rain_cells[rain_riv_index(wsLayerIndex, ivec2(sCell))]; + r.on = ((float(d.x & 65535u) + 0.5) * (1.0 / 65536.0) < rain_params.x * streak_density * wsLayerDensity); + r.life = float((d.x >> 16) & 255u) * (1.0 / 255.0); + float wr = rain_byte(d.y, 16u); r.width = streak_head * wsLayerHead / gridSize * (wsLayerVaried ? mix(streak_thin, streak_thick, pow(wr, streak_thick_bias)) : mix(0.75, 1.25, wr)); if (wsLayerVaried) r.width = min(r.width, sCW / 2.6); // the trail with its swing (sMargin) stays in its cell r.headH = r.width * 0.88 * streak_uv_aspect; - float sSpan = max(sCH * mix(0.35, 0.70, RandF(sSeed)), r.headH * 3.0); - // stick-slip: the drop waits, then lurches forward; N waits on the way down - float sSteps = floor(mix(3.0, 8.0, RandF(sSeed))); - float sXs = clamp(sPhase / 0.88, 0.0, 1.0) * sSteps; - float sRun = clamp((floor(sXs) + smoothstep(0.55, 1.0, fract(sXs))) / sSteps, 0.0, 1.0); - r.topY = sCell.y * sCH + sSpan + RandF(sSeed) * max(sCH - sSpan, 0.0); + float sSpan = max(sCH * mix(0.35, 0.70, rain_byte(d.y, 24u)), r.headH * 3.0); + // stick-slip: how far down its run the head is now (rain_cells.comp) + float sRun = float(d.y & 65535u) * (1.0 / 65535.0); + r.topY = sCell.y * sCH + sSpan + rain_byte(d.z, 0u) * max(sCH - sSpan, 0.0); r.bottom = r.topY - r.headH * 1.2 - sRun * (sSpan - r.headH * 1.2); const float sMargin = 0.8; - r.left = sCell.x * sCW + sMargin * r.width + RandF(sSeed) * max(sCW - r.width * (1.0 + 2.0 * sMargin), 0.0); - r.flip = (RandF(sSeed) < 0.5) ? 1.0 : 0.0; - r.col = floor(RandF(sSeed) * 4.0); - r.wipe = RandF(sSeed); - r.wavK = 6.2831853 / mix(2.5, 5.0, RandF(sSeed)); - r.wavPh = RandF(sSeed) * 6.2831853; - r.wavSp = streak_wiggle_speed * mix(0.6, 1.4, RandF(sSeed)); + r.left = sCell.x * sCW + sMargin * r.width + rain_byte(d.z, 8u) * max(sCW - r.width * (1.0 + 2.0 * sMargin), 0.0); + r.flip = (((d.w >> 8) & 1u) != 0u) ? 1.0 : 0.0; + r.col = float((d.w >> 9) & 3u); + r.wipe = rain_byte(d.x, 24u); + r.wavK = 6.2831853 / mix(2.5, 5.0, rain_byte(d.z, 16u)); + r.wavPh = rain_byte(d.z, 24u) * 6.2831853; + r.wavSp = streak_wiggle_speed * mix(0.6, 1.4, rain_byte(d.w, 0u)); return r; } @@ -585,18 +574,20 @@ float wsWipeAge(vec2 co) return age; } -// how much the place Co (texture UV) lies along the edge of the sweep of the blades, just outside it: 0 .. 1. the mask is 0 there and -// a coarse level of it isn't (the sweep is near). times wsWiperRecent: only where the blades went lately -float wsWiperRecent = 0.0; -float wsWiperEdge(vec2 co) +// the drop of a cell for one side of the blades (A, B: its half of the cell in rain_cells): where it lies, how big it is and its +// shape (the sag, the stretch by the air along PushT). true when P lies on it +bool wsDropShape(uint a, uint b, vec2 nc, float gridSize, float spreadF, float speed, vec2 pushT, vec2 p, + out vec2 center, out float sq, out float sag, out mat2 shapeM, out vec2 dl) { - if ((wiper_edge_boost <= 0.0) || (wsWiperRecent <= 0.0)) - return 0.0; - vec4 m = textureLod(wipermask, co, 0.0); - if (max(max(m.r, m.g), max(m.b, m.a)) > 0.001) - return 0.0; - vec4 c = textureLod(wipermask, co, wiper_edge_reach); - return smoothstep(0.01, 0.12, max(max(c.r, c.g), max(c.b, c.a))) * wsWiperRecent; + center = (nc + vec2(rain_byte(a, 8u), rain_byte(a, 16u))) / gridSize; + float size = mix(drop_size_min, drop_size_max, pow(rain_byte(a, 24u), drop_size_bias)) / gridSize; + sag = 1.0 + drop_sag * rain_byte(b, 0u); + // at speed the air stretches the drop along its push (1 standing still: the drop as it always was) + float stretch = 1.0 + drop_wind_stretch * speed * rain_byte(b, 8u); + shapeM = mat2(1.0, 0.0, 0.0, 1.0 / sag) * (mat2(1.0) + (1.0 / stretch - 1.0) * outerProduct(pushT, pushT)); + sq = size * spreadF; // spreads out as it lands + dl = shapeM * (p - center); + return max(abs(dl.x), abs(dl.y)) < sq * 0.5; } void main() @@ -643,13 +634,6 @@ void main() // wiper state of this pixel (blur, micro droplets) float hazeSide; float wipeVis = GetMixFactor(f_coord, hazeSide); - // the blades went over the glass lately (the water they pushed still lies along the edge of the sweep) - for (int i = 0; i < 4; ++i) - { - float t = max(wiper_timer_out[i], wiper_timer_return[i]); - if ((t > -500.0) && (t <= time)) - wsWiperRecent = max(wsWiperRecent, 1.0 - smoothstep(0.5 * wiper_edge_keep, wiper_edge_keep, time - t)); - } Hit hit; hit.score = 0.0; hit.cov = 0.0; hit.colA = 0.0; hit.n = vec3(0.0, 0.0, 1.0); @@ -709,52 +693,46 @@ void main() // =================================================================== // 1. drops from the atlas: this cell and its 8 neighbours // =================================================================== - vec2 cell = floor(rainCoord * gridSize); + vec2 cell = floor(rainCoord * gridSize); + float actMax = min(rain_params.x * drop_density, 0.95); for (int oy = -1; oy <= 1; oy++) for (int ox = -1; ox <= 1; ox++) { - vec2 nc = cell + vec2(ox, oy); - uvec2 key = cellKey(nc); - // life cycle of this cell: a new drop every lifeLen seconds - uint s0 = Hash(uvec3(key, 23u)); - float lifeLen = mix(drop_life_min, drop_life_max, RandF(s0)); - float tt = time / lifeLen + RandF(s0); - float epoch = floor(tt); - float ph = tt - epoch; - uint ep = uint(mod(epoch, 65521.0)); - // activation first (cheap), the wiper texture only for live drops - uint s1 = Hash(uvec3(key, ep * 4u + 1u)); - float edge = wsWiperEdge((nc + 0.5) / gridSize); - if (RandF(s1) > min(rain_params.x * drop_density * (1.0 + wiper_edge_boost * edge), 0.95)) + vec2 nc = cell + vec2(ox, oy); + // the drop of the cell as it is now (rain_cells.comp): none, or the one of either side of the blades + uvec4 d = rain_cells[rain_drop_index(ivec2(nc))]; + if (rain_byte(d.y, 24u) > actMax) continue; + float vis = float(d.w >> 24) * (1.0 / 255.0); + if (vis <= 0.001) + continue; + float spreadF = mix(0.8, 1.0, float((d.y >> 19) & 31u) * (1.0 / 31.0)); // a drop the blades miss: the same drop before and after the stroke, left where it is - bool missed = RandF(s1) < wiper_miss; - float side; + bool missed = ((d.w >> 19) & 1u) != 0u; + vec2 center0, center1, dl0, dl1; + float sq0, sq1, sag0, sag1; + mat2 shape0, shape1; + bool in0 = wsDropShape(d.x, d.y, nc, gridSize, spreadF, wsSpeed, wsPushT, rainCoord, center0, sq0, sag0, shape0, dl0); + bool in1 = (!missed) && wsDropShape(d.z, d.w, nc, gridSize, spreadF, wsSpeed, wsPushT, rainCoord, center1, sq1, sag1, shape1, dl1); + // the wipers asked only for the drops the pixel lies on + if (!(in0 || in1)) + continue; + float side = 0.0; float mixF = missed ? 1.0 : GetMixFactor((nc + 0.5) / gridSize, side); - if (missed) side = 0.0; - uint s2 = Hash(uvec3(key, ep * 4u + 2u + uint(side) * 2u)); - if (mixF < RandF(s2)) + bool back = (side > 0.5); + if (!(back ? in1 : in0)) continue; - - vec2 center = (nc + vec2(RandF(s2), RandF(s2))) / gridSize; - float size = mix(drop_size_min, drop_size_max, pow(RandF(s2), drop_size_bias)) / gridSize * mix(1.0, wiper_edge_size, edge); - float sag = 1.0 + drop_sag * RandF(s2); - float flipX = (RandF(s2) < 0.5) ? 1.0 : 0.0; - float choice = RandF(s2); - // at speed the air stretches the drop along its push (1 standing still: the drop as it always was) - float stretch = 1.0 + drop_wind_stretch * wsSpeed * RandF(s2); - mat2 shapeM = mat2(1.0, 0.0, 0.0, 1.0 / sag) - * (mat2(1.0) + (1.0 / stretch - 1.0) * outerProduct(wsPushT, wsPushT)); - - float appearF = drop_appear / lifeLen; - float fadeF = drop_fade / lifeLen; - float vis = smoothstep(0.0, appearF, ph) * (1.0 - smoothstep(1.0 - fadeF, 1.0, ph)); - float sq = size * mix(0.8, 1.0, smoothstep(0.0, 2.0 * appearF, ph)); // spreads out as it lands - - vec2 diff = rainCoord - center; - vec2 dl = shapeM * diff; - if (max(abs(dl.x), abs(dl.y)) >= sq * 0.5) + if (mixF < rain_byte(back ? d.z : d.x, 0u)) continue; + uint db = back ? d.w : d.y; + vec2 center = back ? center1 : center0; + float sq = back ? sq1 : sq0; + float sag = back ? sag1 : sag0; + mat2 shapeM = back ? shape1 : shape0; + vec2 dl = back ? dl1 : dl0; + float flipX = (((db >> 16) & 1u) != 0u) ? 1.0 : 0.0; + float choice = (float((db >> 17) & 3u) + 0.5) * 0.25; + vec2 diff = rainCoord - center; if (sweepOn) { @@ -799,7 +777,7 @@ void main() float mph = fract(mtt); uint mep = uint(mod(floor(mtt), 65521.0)); uint m1 = Hash(uvec3(mk, mep * 4u + 1u)); - if (RandF(m1) < min(rain_params.x * micro_density * (1.0 + wiper_edge_boost * wsWiperEdge((mc + 0.5) / mg)), 0.95)) + if (RandF(m1) < min(rain_params.x * micro_density, 0.95)) { uint m2 = Hash(uvec3(mk, mep * 4u + 2u + uint(hazeSide) * 2u)); if (wipeVis >= RandF(m2)) diff --git a/shaders/ogl46/rain_cells.comp b/shaders/ogl46/rain_cells.comp new file mode 100644 index 000000000..7cece6a0b --- /dev/null +++ b/shaders/ogl46/rain_cells.comp @@ -0,0 +1,131 @@ +#version 460 core +#define STAGE_COMPUTE 1 +// the cells of the glasses with rain (rain_cells.glsl): the drops and the rivulets of every cell worked out for the time of the +// frame, a thread a cell, before the passes which draw the glasses (mat_rain_windscreen.frag only reads them) + +#include "common.glsl" + +layout(location = 0) uniform float rain_time; // the time of the block of the scene (scene_ubs.time) + +#include "random.glsl" +#include "rain_cells.glsl" + +layout(local_size_x = RAIN_CELLS_GROUP_SIZE) in; + +uvec2 rain_key(ivec2 Cell) +{ + return uvec2(Cell + ivec2(65536)); +} + +// a random kept to 8 bits (rain_byte() takes it back) +uint q8(float Value) +{ + return min(uint(Value * 256.0), 255u); +} + +// a share 0 .. 1 kept to Steps + 1 levels, 0 and 1 exact +uint qn(float Value, float Steps) +{ + return uint(round(clamp(Value, 0.0, 1.0) * Steps)); +} + +// a drop cell: its life now, the activation, and the drop of either side of the blades (the sequence of the randoms is the +// one mat_rain_windscreen.frag had) +uvec4 drop_cell(ivec2 Cell) +{ + uvec2 key = rain_key(Cell); + uint s0 = Hash(uvec3(key, 23u)); + float lifeLen = mix(drop_life_min, drop_life_max, RandF(s0)); + float tt = rain_time / lifeLen + RandF(s0); + float epoch = floor(tt); + float ph = tt - epoch; + uint ep = uint(mod(epoch, 65521.0)); + uint s1 = Hash(uvec3(key, ep * 4u + 1u)); + float landing = RandF(s1); + bool missed = RandF(s1) < wiper_miss; + float appearF = drop_appear / lifeLen; + float fadeF = drop_fade / lifeLen; + float vis = smoothstep(0.0, appearF, ph) * (1.0 - smoothstep(1.0 - fadeF, 1.0, ph)); + float spread = smoothstep(0.0, 2.0 * appearF, ph); + uvec4 result; + for (uint side = 0u; side < 2u; ++side) + { + uint s2 = Hash(uvec3(key, ep * 4u + 2u + side * 2u)); + float thr = RandF(s2); + float cx = RandF(s2); + float cy = RandF(s2); + float size = RandF(s2); + float sag = RandF(s2); + float flip = RandF(s2); + float choice = RandF(s2); + float stretch = RandF(s2); + uint tile = min(uint(choice * 4.0), 3u); + uint a = q8(thr) | (q8(cx) << 8) | (q8(cy) << 16) | (q8(size) << 24); + uint b = q8(sag) | (q8(stretch) << 8) | ((flip < 0.5) ? (1u << 16) : 0u) | (tile << 17); + if (side == 0u) + { + b |= (qn(spread, 31.0) << 19) | (q8(landing) << 24); + result.x = a; + result.y = b; + } + else + { + b |= (missed ? (1u << 19) : 0u) | (qn(vis, 255.0) << 24); + result.z = a; + result.w = b; + } + } + return result; +} + +// a rivulet cell of layer Layer (0 gravity, 1 .. 4 the air), as getRiv of mat_rain_windscreen.frag drew it +uvec4 rivulet_cell(int Layer, ivec2 Cell) +{ + uint salt = 91u + 2u * uint(Layer); + uint sSeed = Hash(uvec3(rain_key(Cell), salt)); + float on = RandF(sSeed); + float sPeriod = ((Layer == 0) ? streak_period : wind_streak_period) * mix(0.6, 1.6, RandF(sSeed)); + float sPhase = fract(rain_time / sPeriod + RandF(sSeed)); + float life = smoothstep(0.0, 0.05, sPhase) * (1.0 - smoothstep(0.86, 1.0, sPhase)); + float wr = RandF(sSeed); + float span = RandF(sSeed); + float sSteps = floor(mix(3.0, 8.0, RandF(sSeed))); + float sXs = clamp(sPhase / 0.88, 0.0, 1.0) * sSteps; + float sRun = clamp((floor(sXs) + smoothstep(0.55, 1.0, fract(sXs))) / sSteps, 0.0, 1.0); + float top = RandF(sSeed); + float left = RandF(sSeed); + float flip = RandF(sSeed); + float col = RandF(sSeed); + float wipe = RandF(sSeed); + float wavK = RandF(sSeed); + float wavPh = RandF(sSeed); + float wavSp = RandF(sSeed); + uvec4 result; + result.x = min(uint(on * 65536.0), 65535u) | (qn(life, 255.0) << 16) | (q8(wipe) << 24); + result.y = qn(sRun, 65535.0) | (q8(wr) << 16) | (q8(span) << 24); + result.z = q8(top) | (q8(left) << 8) | (q8(wavK) << 16) | (q8(wavPh) << 24); + result.w = q8(wavSp) | ((flip < 0.5) ? (1u << 8) : 0u) | (min(uint(col * 4.0), 3u) << 9); + return result; +} + +void main() +{ + uint index = gl_GlobalInvocationID.x; + if (index >= uint(RAIN_CELLS_COUNT)) + return; + if (index < uint(RAIN_RIV_BASE)) + { + ivec2 texel = ivec2(int(index % uint(RAIN_DROP_CELLS)), int(index / uint(RAIN_DROP_CELLS))); + // the last column and row stand for the cells -1 (the neighbours of the first ones) + ivec2 cell = ivec2(texel.x == RAIN_DROP_CELLS - 1 ? -1 : texel.x, texel.y == RAIN_DROP_CELLS - 1 ? -1 : texel.y); + rain_cells[index] = drop_cell(cell); + return; + } + uint rest = index - uint(RAIN_RIV_BASE); + int layer = int(rest / uint(RAIN_RIV_CELLS * RAIN_RIV_CELLS)); + uint place = rest % uint(RAIN_RIV_CELLS * RAIN_RIV_CELLS); + ivec2 texel = ivec2(int(place % uint(RAIN_RIV_CELLS)), int(place / uint(RAIN_RIV_CELLS))); + // the cells -32 .. 95: the upper quarter stands for the cells below 0 + ivec2 cell = ivec2(texel.x >= 96 ? texel.x - RAIN_RIV_CELLS : texel.x, texel.y >= 96 ? texel.y - RAIN_RIV_CELLS : texel.y); + rain_cells[index] = rivulet_cell(layer, cell); +} diff --git a/shaders/ogl46/rain_cells.glsl b/shaders/ogl46/rain_cells.glsl new file mode 100644 index 000000000..97819d724 --- /dev/null +++ b/shaders/ogl46/rain_cells.glsl @@ -0,0 +1,67 @@ +// the cells of the glasses with rain (mat_rain_windscreen.frag): the drops of the grid of drops and the rivulets of the layers of +// rivulets, worked out once a frame for every cell by rain_cells.comp (a thread a cell) instead of in every pixel of a glass for +// its 9 neighbouring cells. a cell holds the random values of its drop or rivulet as they are now (the hashes of the cell and of +// its epoch, the life cycle at the time of the frame); the glass takes the sizes and the places from them with its own settings. +// so the glass looks the same as when it worked them out itself (the hashes are the same; the values are kept to 8 or 16 bits) +// +// a cell is one uvec4. the drops: RAIN_DROP_CELLS x RAIN_DROP_CELLS cells, cell c of the grid in element (c.y & 511) * 512 + +// (c.x & 511), whole for the cells -1 .. 510 (grids up to 510 cells; finer ones repeat their drops every 512 cells): +// x side 0 (the drop of a cell the blades went over on their way out): bits 0-7 the threshold the wipers have to be past for +// it, 8-15 / 16-23 the place in the cell (x, y), 24-31 the random of its size +// y side 0: bits 0-7 the random of its sag, 8-15 of its stretch by the air, 16 mirrored, 17-18 the tile of the atlas, +// 19-23 how far it spread out landing (0 .. 31), 24-31 the random a cell holds a drop by (a drop when below the share) +// z side 1 (the blades on their way back): as x +// w side 1: as y, bit 19 set when the blades miss the drop, bits 24-31 its visibility in its life (0 .. 255) +// the rivulets: RAIN_RIV_LAYERS layers (0 gravity, 1 .. 4 the air) of RAIN_RIV_CELLS x RAIN_RIV_CELLS cells, cell c in element +// RAIN_RIV_BASE + layer * 128 * 128 + (c.y & 127) * 128 + (c.x & 127), whole for the cells -32 .. 95: +// x bits 0-15 the random the cell holds a rivulet by, 16-23 its life (0 .. 255), 24-31 the random of the wipers it stays under +// y bits 0-15 how far down its run the head is (0 .. 65535), 16-23 the random of its width, 24-31 of its span +// z the randoms of its top, its left edge, the length and the phase of its waves (a byte each) +// w bits 0-7 the random of the speed of its waves, 8 mirrored, 9-10 the sprite of the atlas + +#ifndef RAIN_CELLS_GLSL +#define RAIN_CELLS_GLSL + +#define RAIN_DROP_CELLS 512 +#define RAIN_RIV_CELLS 128 +#define RAIN_RIV_LAYERS 5 +#define RAIN_RIV_BASE (RAIN_DROP_CELLS * RAIN_DROP_CELLS) +#define RAIN_CELLS_COUNT (RAIN_RIV_BASE + RAIN_RIV_LAYERS * RAIN_RIV_CELLS * RAIN_RIV_CELLS) +#define RAIN_CELLS_GROUP_SIZE 64 + +#if defined(STAGE_COMPUTE) +layout(std430, binding = RAIN_CELLS_SSBO_BINDING) writeonly buffer rain_cells_ssbo +#else +layout(std430, binding = RAIN_CELLS_SSBO_BINDING) readonly buffer rain_cells_ssbo +#endif +{ + uvec4 rain_cells[]; +}; + +// the life of the drops and of the rivulets (the settings of mat_rain_windscreen.frag which the cells are worked out with) +const float drop_life_min = 14.0; // seconds a drop sits on the glass +const float drop_life_max = 45.0; +const float drop_appear = 0.18; // seconds of the landing "pop" +const float drop_fade = 1.5; // seconds a drop takes to vanish at the end of its life +const float wiper_miss = 0.05; // share of the drops a blade goes over without taking them +const float streak_period = 40.0; // seconds a rivulet lives (it runs for ~90% of that and then fades out), average +const float wind_streak_period = 18.0; // seconds a rivulet driven by the air lives (they run faster than the ones of gravity) + +// a random kept to 8 bits, back to 0 .. 1 (the middle of its step) +float rain_byte(uint Value, uint Shift) +{ + return (float((Value >> Shift) & 255u) + 0.5) * (1.0 / 256.0); +} + +uint rain_drop_index(ivec2 Cell) +{ + return uint(Cell.y & (RAIN_DROP_CELLS - 1)) * uint(RAIN_DROP_CELLS) + uint(Cell.x & (RAIN_DROP_CELLS - 1)); +} + +uint rain_riv_index(int Layer, ivec2 Cell) +{ + return uint(RAIN_RIV_BASE) + uint(Layer) * uint(RAIN_RIV_CELLS * RAIN_RIV_CELLS) + uint(Cell.y & (RAIN_RIV_CELLS - 1)) * uint(RAIN_RIV_CELLS) + + uint(Cell.x & (RAIN_RIV_CELLS - 1)); +} + +#endif diff --git a/shaders/vk14/common.glsl b/shaders/vk14/common.glsl index d29dc677b..b2aa5218b 100644 --- a/shaders/vk14/common.glsl +++ b/shaders/vk14/common.glsl @@ -68,7 +68,8 @@ #define SKY_OCCLUSION_HEIGHT_TEX 31 #define SKY_OCCLUSION_TEX 32 #define CAB_PROBE_MASK_TEX 33 -#define PASS_BINDING_COUNT 34 +#define RAIN_CELLS_SSBO 34 +#define PASS_BINDING_COUNT 35 #define MATERIAL_TEXTURE_FIRST 0 #define CL_CLUSTER_UBO 0 #define CL_AABB_SSBO 1 diff --git a/shaders/vk14/mat_rain_windscreen.frag b/shaders/vk14/mat_rain_windscreen.frag index 975fd3eb8..1c167c9e4 100644 --- a/shaders/vk14/mat_rain_windscreen.frag +++ b/shaders/vk14/mat_rain_windscreen.frag @@ -19,6 +19,10 @@ // The trail right above the head is taken from the sprite part that touches the head, then it blends // into the trail pattern that is fixed to the glass (beads stay where they were left). // +// Speed: the hashes and the life cycles of the cells (which drop a cell holds now, where, how big; where the head of a rivulet is) +// are worked out once a frame for every cell by rain_cells.comp (rain_cells.glsl), not here for the 9 cells around every pixel; +// the wipers are asked only for the drops the pixel lies on. the look is the same. +// // Shading: the grey atlas (bright rim, dark middle) is read once per pixel, only for the drop that wins the // pixel (it used to be read for all 9 neighbours). Micro droplets are shaded analytically. // @@ -69,6 +73,7 @@ layout(location = 1) out vec4 out_motion; #include "apply_fog.glsl" #include "tonemapping.glsl" #include "random.glsl" +#include "rain_cells.glsl" layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 0) uniform sampler2D diffuse; layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 1) uniform sampler2D raindropsatlas; @@ -88,14 +93,11 @@ const float WS_DROP_BIAS = 192.0; const float WS_ENC = 64.0; // the haze request in the velocity target; must match rain_windscreen_haze.glsl // --- Drops (atlas tiles) ------------------------------------------------------ +// (how long they live: rain_cells.glsl; the cells of the drops and of the rivulets are worked out once a frame by rain_cells.comp) const float drop_density = 0.6; // share of grid cells holding a drop at full rain (scaled by rain intensity) const float drop_size_min = 0.45; // drop size in grid cells const float drop_size_max = 1.15; const float drop_size_bias = 1.8; // >1 = more small/medium drops, fewer big ones -const float drop_life_min = 14.0; // seconds a drop sits on the glass -const float drop_life_max = 45.0; -const float drop_appear = 0.18; // seconds of the landing "pop" -const float drop_fade = 1.5; // seconds a drop takes to vanish at the end of its life const float drop_sag = 0.12; // max vertical stretch of a resting drop (gravity) // --- Micro droplets ------------------------------------------------------------- @@ -135,7 +137,6 @@ const float streak_density = 1.00; // share of cells carrying a rivulet (scal const float streak_cell = 6.0; // width of a rivulet cell in drop cells const float streak_run = 20.0; // height of a rivulet cell in drop cells = the longest run of one rivulet const float streak_head = 1.7; // mean width of the drop head, in drop cells (randomised 0.75x .. 1.25x) -const float streak_period = 40.0; // seconds a rivulet lives (it runs for ~90% of that and then fades out), average const float streak_wiggle = 0.35; // how far the path swings sideways, in head widths (0 = straight) const float streak_wiggle_speed = 0.5; // speed of the little waves that flow down the trail const float streak_flow = 0.15; // ripples flowing down inside the trail (shows in refraction and glints), 0 = off @@ -157,7 +158,6 @@ const float wind_run_scale = 1.2; // ... and their runs this long against const float wind_head_scale = 0.4; // their heads this much smaller (a small bead at the front of a long trail) const int wind_layers = 4; // layers of them, each with drops of its own (1 .. 4) const float wind_long_run = 3.0; // the last layer: its trails this much longer than those of gravity (the long ones, a part of all) -const float wind_streak_period = 18.0; // seconds a rivulet driven by the air lives (they run faster than the ones of gravity) const float drop_wind_stretch = 0.4; // drops are stretched up to this much along the push of the air (0 = off) const float WS_DRAG_SPEED = 24.0; // speed of the air along the glass at which its drag equals the weight of a drop, m/s const float WS_HEAD_ON = 0.35; // share of the air meeting the glass head on which turns up along it @@ -169,13 +169,7 @@ const float WS_WIND_STEP = 0.1309; // the direction of the rivulets of the const float streak_thin = 0.5; // the thinnest const float streak_thick = 2.0; // the thickest const float streak_thick_bias = 2.0; // > 1: more thin ones -// --- What the blades leave: they don't take every drop (a few stay where they were), and the water they push lies along the edge -// of their sweep, just outside it, as a row of beads (where the blades went lately) ------------------------------------------------ -const float wiper_miss = 0.05; // share of the drops a blade goes over without taking them -const float wiper_edge_boost = 0.0; // along the edge of the sweep this many times more drops (and droplets) (0 = off) ... -const float wiper_edge_size = 0.65; // ... this much smaller: a row of beads -const float wiper_edge_reach = 4.0; // how wide the row is: the mip level of the mask read (4: ~16 texels of the mask out) -const float wiper_edge_keep = 180.0; // seconds after the last stroke the water at the edge keeps (then it's like the rest of the glass) +// --- What the blades leave: they don't take every drop (a few stay where they were): wiper_miss of rain_cells.glsl ----------------- #ifndef STREAK_FLIP_Y #define STREAK_FLIP_Y 0 // set to 1 if the rivulets run UP the glass (head on top) @@ -314,8 +308,7 @@ struct Riv // the layer of rivulets being worked on: the one of gravity (the rivulets as they always were, coordinates = glass UV with v // up) or the one of the air (its own cells and seeds, turned so that its rivulets run along the push of the air) float wsLayerDensity = 1.0; // x rain x streak_density: share of the cells holding a rivulet -float wsLayerPeriod = streak_period; -uint wsLayerSalt = 91u; +int wsLayerIndex = 0; // its cells in rain_cells (0 gravity, 1 .. 4 the air) float wsLayerHead = 1.0; // x streak_head float wsLayerCos = 1.0; // the layer is turned by this angle (its "down" is the way its water runs on the glass) float wsLayerSin = 0.0; @@ -349,8 +342,7 @@ void wsSetLayer(int layer) if (layer == 0) { wsLayerDensity = 1.0 - wsWindShare; - wsLayerPeriod = streak_period; - wsLayerSalt = 91u; + wsLayerIndex = 0; wsLayerHead = 1.0; wsLayerCos = 1.0; wsLayerSin = 0.0; @@ -359,8 +351,7 @@ void wsSetLayer(int layer) else { wsLayerDensity = wsWindShare * wind_streaks; - wsLayerPeriod = wind_streak_period; - wsLayerSalt = 91u + 2u * uint(layer); + wsLayerIndex = layer; wsLayerHead = wind_head_scale; wsLayerCos = wsWindCos; wsLayerSin = wsWindSin; @@ -368,35 +359,33 @@ void wsSetLayer(int layer) } } +// the rivulet of cell SCell of the layer set (wsSetLayer): the randoms and the life of the cell from rain_cells (rain_cells.comp +// worked them out as this did once from the hashes of the cell), the sizes and the places from them Riv getRiv(vec2 sCell, float sCW, float sCH, float gridSize) { Riv r; - uint sSeed = Hash(uvec3(cellKey(sCell), wsLayerSalt)); - r.on = (RandF(sSeed) < rain_params.x * streak_density * wsLayerDensity); - float sPeriod = wsLayerPeriod * mix(0.6, 1.6, RandF(sSeed)); - float sPhase = fract(time / sPeriod + RandF(sSeed)); - r.life = smoothstep(0.0, 0.05, sPhase) * (1.0 - smoothstep(0.86, 1.0, sPhase)); - float wr = RandF(sSeed); + uvec4 d = rain_cells[rain_riv_index(wsLayerIndex, ivec2(sCell))]; + r.on = ((float(d.x & 65535u) + 0.5) * (1.0 / 65536.0) < rain_params.x * streak_density * wsLayerDensity); + r.life = float((d.x >> 16) & 255u) * (1.0 / 255.0); + float wr = rain_byte(d.y, 16u); r.width = streak_head * wsLayerHead / gridSize * (wsLayerVaried ? mix(streak_thin, streak_thick, pow(wr, streak_thick_bias)) : mix(0.75, 1.25, wr)); if (wsLayerVaried) r.width = min(r.width, sCW / 2.6); // the trail with its swing (sMargin) stays in its cell r.headH = r.width * 0.88 * streak_uv_aspect; - float sSpan = max(sCH * mix(0.35, 0.70, RandF(sSeed)), r.headH * 3.0); - // stick-slip: the drop waits, then lurches forward; N waits on the way down - float sSteps = floor(mix(3.0, 8.0, RandF(sSeed))); - float sXs = clamp(sPhase / 0.88, 0.0, 1.0) * sSteps; - float sRun = clamp((floor(sXs) + smoothstep(0.55, 1.0, fract(sXs))) / sSteps, 0.0, 1.0); - r.topY = sCell.y * sCH + sSpan + RandF(sSeed) * max(sCH - sSpan, 0.0); + float sSpan = max(sCH * mix(0.35, 0.70, rain_byte(d.y, 24u)), r.headH * 3.0); + // stick-slip: how far down its run the head is now (rain_cells.comp) + float sRun = float(d.y & 65535u) * (1.0 / 65535.0); + r.topY = sCell.y * sCH + sSpan + rain_byte(d.z, 0u) * max(sCH - sSpan, 0.0); r.bottom = r.topY - r.headH * 1.2 - sRun * (sSpan - r.headH * 1.2); const float sMargin = 0.8; - r.left = sCell.x * sCW + sMargin * r.width + RandF(sSeed) * max(sCW - r.width * (1.0 + 2.0 * sMargin), 0.0); - r.flip = (RandF(sSeed) < 0.5) ? 1.0 : 0.0; - r.col = floor(RandF(sSeed) * 4.0); - r.wipe = RandF(sSeed); - r.wavK = 6.2831853 / mix(2.5, 5.0, RandF(sSeed)); - r.wavPh = RandF(sSeed) * 6.2831853; - r.wavSp = streak_wiggle_speed * mix(0.6, 1.4, RandF(sSeed)); + r.left = sCell.x * sCW + sMargin * r.width + rain_byte(d.z, 8u) * max(sCW - r.width * (1.0 + 2.0 * sMargin), 0.0); + r.flip = (((d.w >> 8) & 1u) != 0u) ? 1.0 : 0.0; + r.col = float((d.w >> 9) & 3u); + r.wipe = rain_byte(d.x, 24u); + r.wavK = 6.2831853 / mix(2.5, 5.0, rain_byte(d.z, 16u)); + r.wavPh = rain_byte(d.z, 24u) * 6.2831853; + r.wavSp = streak_wiggle_speed * mix(0.6, 1.4, rain_byte(d.w, 0u)); return r; } @@ -590,18 +579,20 @@ float wsWipeAge(vec2 co) return age; } -// how much the place Co (texture UV) lies along the edge of the sweep of the blades, just outside it: 0 .. 1. the mask is 0 there and -// a coarse level of it isn't (the sweep is near). times wsWiperRecent: only where the blades went lately -float wsWiperRecent = 0.0; -float wsWiperEdge(vec2 co) +// the drop of a cell for one side of the blades (A, B: its half of the cell in rain_cells): where it lies, how big it is and its +// shape (the sag, the stretch by the air along PushT). true when P lies on it +bool wsDropShape(uint a, uint b, vec2 nc, float gridSize, float spreadF, float speed, vec2 pushT, vec2 p, + out vec2 center, out float sq, out float sag, out mat2 shapeM, out vec2 dl) { - if ((wiper_edge_boost <= 0.0) || (wsWiperRecent <= 0.0)) - return 0.0; - vec4 m = textureLod(wipermask, co, 0.0); - if (max(max(m.r, m.g), max(m.b, m.a)) > 0.001) - return 0.0; - vec4 c = textureLod(wipermask, co, wiper_edge_reach); - return smoothstep(0.01, 0.12, max(max(c.r, c.g), max(c.b, c.a))) * wsWiperRecent; + center = (nc + vec2(rain_byte(a, 8u), rain_byte(a, 16u))) / gridSize; + float size = mix(drop_size_min, drop_size_max, pow(rain_byte(a, 24u), drop_size_bias)) / gridSize; + sag = 1.0 + drop_sag * rain_byte(b, 0u); + // at speed the air stretches the drop along its push (1 standing still: the drop as it always was) + float stretch = 1.0 + drop_wind_stretch * speed * rain_byte(b, 8u); + shapeM = mat2(1.0, 0.0, 0.0, 1.0 / sag) * (mat2(1.0) + (1.0 / stretch - 1.0) * outerProduct(pushT, pushT)); + sq = size * spreadF; // spreads out as it lands + dl = shapeM * (p - center); + return max(abs(dl.x), abs(dl.y)) < sq * 0.5; } void main() @@ -648,13 +639,6 @@ void main() // wiper state of this pixel (blur, micro droplets) float hazeSide; float wipeVis = GetMixFactor(f_coord, hazeSide); - // the blades went over the glass lately (the water they pushed still lies along the edge of the sweep) - for (int i = 0; i < 4; ++i) - { - float t = max(wiper_timer_out[i], wiper_timer_return[i]); - if ((t > -500.0) && (t <= time)) - wsWiperRecent = max(wsWiperRecent, 1.0 - smoothstep(0.5 * wiper_edge_keep, wiper_edge_keep, time - t)); - } Hit hit; hit.score = 0.0; hit.cov = 0.0; hit.colA = 0.0; hit.n = vec3(0.0, 0.0, 1.0); @@ -714,52 +698,46 @@ void main() // =================================================================== // 1. drops from the atlas: this cell and its 8 neighbours // =================================================================== - vec2 cell = floor(rainCoord * gridSize); + vec2 cell = floor(rainCoord * gridSize); + float actMax = min(rain_params.x * drop_density, 0.95); for (int oy = -1; oy <= 1; oy++) for (int ox = -1; ox <= 1; ox++) { - vec2 nc = cell + vec2(ox, oy); - uvec2 key = cellKey(nc); - // life cycle of this cell: a new drop every lifeLen seconds - uint s0 = Hash(uvec3(key, 23u)); - float lifeLen = mix(drop_life_min, drop_life_max, RandF(s0)); - float tt = time / lifeLen + RandF(s0); - float epoch = floor(tt); - float ph = tt - epoch; - uint ep = uint(mod(epoch, 65521.0)); - // activation first (cheap), the wiper texture only for live drops - uint s1 = Hash(uvec3(key, ep * 4u + 1u)); - float edge = wsWiperEdge((nc + 0.5) / gridSize); - if (RandF(s1) > min(rain_params.x * drop_density * (1.0 + wiper_edge_boost * edge), 0.95)) + vec2 nc = cell + vec2(ox, oy); + // the drop of the cell as it is now (rain_cells.comp): none, or the one of either side of the blades + uvec4 d = rain_cells[rain_drop_index(ivec2(nc))]; + if (rain_byte(d.y, 24u) > actMax) continue; + float vis = float(d.w >> 24) * (1.0 / 255.0); + if (vis <= 0.001) + continue; + float spreadF = mix(0.8, 1.0, float((d.y >> 19) & 31u) * (1.0 / 31.0)); // a drop the blades miss: the same drop before and after the stroke, left where it is - bool missed = RandF(s1) < wiper_miss; - float side; + bool missed = ((d.w >> 19) & 1u) != 0u; + vec2 center0, center1, dl0, dl1; + float sq0, sq1, sag0, sag1; + mat2 shape0, shape1; + bool in0 = wsDropShape(d.x, d.y, nc, gridSize, spreadF, wsSpeed, wsPushT, rainCoord, center0, sq0, sag0, shape0, dl0); + bool in1 = (!missed) && wsDropShape(d.z, d.w, nc, gridSize, spreadF, wsSpeed, wsPushT, rainCoord, center1, sq1, sag1, shape1, dl1); + // the wipers asked only for the drops the pixel lies on + if (!(in0 || in1)) + continue; + float side = 0.0; float mixF = missed ? 1.0 : GetMixFactor((nc + 0.5) / gridSize, side); - if (missed) side = 0.0; - uint s2 = Hash(uvec3(key, ep * 4u + 2u + uint(side) * 2u)); - if (mixF < RandF(s2)) + bool back = (side > 0.5); + if (!(back ? in1 : in0)) continue; - - vec2 center = (nc + vec2(RandF(s2), RandF(s2))) / gridSize; - float size = mix(drop_size_min, drop_size_max, pow(RandF(s2), drop_size_bias)) / gridSize * mix(1.0, wiper_edge_size, edge); - float sag = 1.0 + drop_sag * RandF(s2); - float flipX = (RandF(s2) < 0.5) ? 1.0 : 0.0; - float choice = RandF(s2); - // at speed the air stretches the drop along its push (1 standing still: the drop as it always was) - float stretch = 1.0 + drop_wind_stretch * wsSpeed * RandF(s2); - mat2 shapeM = mat2(1.0, 0.0, 0.0, 1.0 / sag) - * (mat2(1.0) + (1.0 / stretch - 1.0) * outerProduct(wsPushT, wsPushT)); - - float appearF = drop_appear / lifeLen; - float fadeF = drop_fade / lifeLen; - float vis = smoothstep(0.0, appearF, ph) * (1.0 - smoothstep(1.0 - fadeF, 1.0, ph)); - float sq = size * mix(0.8, 1.0, smoothstep(0.0, 2.0 * appearF, ph)); // spreads out as it lands - - vec2 diff = rainCoord - center; - vec2 dl = shapeM * diff; - if (max(abs(dl.x), abs(dl.y)) >= sq * 0.5) + if (mixF < rain_byte(back ? d.z : d.x, 0u)) continue; + uint db = back ? d.w : d.y; + vec2 center = back ? center1 : center0; + float sq = back ? sq1 : sq0; + float sag = back ? sag1 : sag0; + mat2 shapeM = back ? shape1 : shape0; + vec2 dl = back ? dl1 : dl0; + float flipX = (((db >> 16) & 1u) != 0u) ? 1.0 : 0.0; + float choice = (float((db >> 17) & 3u) + 0.5) * 0.25; + vec2 diff = rainCoord - center; if (sweepOn) { @@ -804,7 +782,7 @@ void main() float mph = fract(mtt); uint mep = uint(mod(floor(mtt), 65521.0)); uint m1 = Hash(uvec3(mk, mep * 4u + 1u)); - if (RandF(m1) < min(rain_params.x * micro_density * (1.0 + wiper_edge_boost * wsWiperEdge((mc + 0.5) / mg)), 0.95)) + if (RandF(m1) < min(rain_params.x * micro_density, 0.95)) { uint m2 = Hash(uvec3(mk, mep * 4u + 2u + uint(hazeSide) * 2u)); if (wipeVis >= RandF(m2)) diff --git a/shaders/vk14/rain_cells.comp b/shaders/vk14/rain_cells.comp new file mode 100644 index 000000000..c8ca2af4b --- /dev/null +++ b/shaders/vk14/rain_cells.comp @@ -0,0 +1,136 @@ +#version 460 core +#define STAGE_COMPUTE 1 +// the cells of the glasses with rain (rain_cells.glsl): the drops and the rivulets of every cell worked out for the time of the +// frame, a thread a cell, before the passes which draw the glasses (mat_rain_windscreen.frag only reads them) + +// none of the pass set: the cells pushed with the dispatch (set COMPUTE_SET), the time in the push constants +#define LAYOUT_UI 1 +#include "common.glsl" + +layout(push_constant) uniform kernel_constants +{ + float rain_time; // the time of the block of the scene (scene_ubs.time) +}; + +#include "random.glsl" +#include "rain_cells.glsl" + +layout(local_size_x = RAIN_CELLS_GROUP_SIZE) in; + +uvec2 rain_key(ivec2 Cell) +{ + return uvec2(Cell + ivec2(65536)); +} + +// a random kept to 8 bits (rain_byte() takes it back) +uint q8(float Value) +{ + return min(uint(Value * 256.0), 255u); +} + +// a share 0 .. 1 kept to Steps + 1 levels, 0 and 1 exact +uint qn(float Value, float Steps) +{ + return uint(round(clamp(Value, 0.0, 1.0) * Steps)); +} + +// a drop cell: its life now, the activation, and the drop of either side of the blades (the sequence of the randoms is the +// one mat_rain_windscreen.frag had) +uvec4 drop_cell(ivec2 Cell) +{ + uvec2 key = rain_key(Cell); + uint s0 = Hash(uvec3(key, 23u)); + float lifeLen = mix(drop_life_min, drop_life_max, RandF(s0)); + float tt = rain_time / lifeLen + RandF(s0); + float epoch = floor(tt); + float ph = tt - epoch; + uint ep = uint(mod(epoch, 65521.0)); + uint s1 = Hash(uvec3(key, ep * 4u + 1u)); + float landing = RandF(s1); + bool missed = RandF(s1) < wiper_miss; + float appearF = drop_appear / lifeLen; + float fadeF = drop_fade / lifeLen; + float vis = smoothstep(0.0, appearF, ph) * (1.0 - smoothstep(1.0 - fadeF, 1.0, ph)); + float spread = smoothstep(0.0, 2.0 * appearF, ph); + uvec4 result; + for (uint side = 0u; side < 2u; ++side) + { + uint s2 = Hash(uvec3(key, ep * 4u + 2u + side * 2u)); + float thr = RandF(s2); + float cx = RandF(s2); + float cy = RandF(s2); + float size = RandF(s2); + float sag = RandF(s2); + float flip = RandF(s2); + float choice = RandF(s2); + float stretch = RandF(s2); + uint tile = min(uint(choice * 4.0), 3u); + uint a = q8(thr) | (q8(cx) << 8) | (q8(cy) << 16) | (q8(size) << 24); + uint b = q8(sag) | (q8(stretch) << 8) | ((flip < 0.5) ? (1u << 16) : 0u) | (tile << 17); + if (side == 0u) + { + b |= (qn(spread, 31.0) << 19) | (q8(landing) << 24); + result.x = a; + result.y = b; + } + else + { + b |= (missed ? (1u << 19) : 0u) | (qn(vis, 255.0) << 24); + result.z = a; + result.w = b; + } + } + return result; +} + +// a rivulet cell of layer Layer (0 gravity, 1 .. 4 the air), as getRiv of mat_rain_windscreen.frag drew it +uvec4 rivulet_cell(int Layer, ivec2 Cell) +{ + uint salt = 91u + 2u * uint(Layer); + uint sSeed = Hash(uvec3(rain_key(Cell), salt)); + float on = RandF(sSeed); + float sPeriod = ((Layer == 0) ? streak_period : wind_streak_period) * mix(0.6, 1.6, RandF(sSeed)); + float sPhase = fract(rain_time / sPeriod + RandF(sSeed)); + float life = smoothstep(0.0, 0.05, sPhase) * (1.0 - smoothstep(0.86, 1.0, sPhase)); + float wr = RandF(sSeed); + float span = RandF(sSeed); + float sSteps = floor(mix(3.0, 8.0, RandF(sSeed))); + float sXs = clamp(sPhase / 0.88, 0.0, 1.0) * sSteps; + float sRun = clamp((floor(sXs) + smoothstep(0.55, 1.0, fract(sXs))) / sSteps, 0.0, 1.0); + float top = RandF(sSeed); + float left = RandF(sSeed); + float flip = RandF(sSeed); + float col = RandF(sSeed); + float wipe = RandF(sSeed); + float wavK = RandF(sSeed); + float wavPh = RandF(sSeed); + float wavSp = RandF(sSeed); + uvec4 result; + result.x = min(uint(on * 65536.0), 65535u) | (qn(life, 255.0) << 16) | (q8(wipe) << 24); + result.y = qn(sRun, 65535.0) | (q8(wr) << 16) | (q8(span) << 24); + result.z = q8(top) | (q8(left) << 8) | (q8(wavK) << 16) | (q8(wavPh) << 24); + result.w = q8(wavSp) | ((flip < 0.5) ? (1u << 8) : 0u) | (min(uint(col * 4.0), 3u) << 9); + return result; +} + +void main() +{ + uint index = gl_GlobalInvocationID.x; + if (index >= uint(RAIN_CELLS_COUNT)) + return; + if (index < uint(RAIN_RIV_BASE)) + { + ivec2 texel = ivec2(int(index % uint(RAIN_DROP_CELLS)), int(index / uint(RAIN_DROP_CELLS))); + // the last column and row stand for the cells -1 (the neighbours of the first ones) + ivec2 cell = ivec2(texel.x == RAIN_DROP_CELLS - 1 ? -1 : texel.x, texel.y == RAIN_DROP_CELLS - 1 ? -1 : texel.y); + rain_cells[index] = drop_cell(cell); + return; + } + uint rest = index - uint(RAIN_RIV_BASE); + int layer = int(rest / uint(RAIN_RIV_CELLS * RAIN_RIV_CELLS)); + uint place = rest % uint(RAIN_RIV_CELLS * RAIN_RIV_CELLS); + ivec2 texel = ivec2(int(place % uint(RAIN_RIV_CELLS)), int(place / uint(RAIN_RIV_CELLS))); + // the cells -32 .. 95: the upper quarter stands for the cells below 0 + ivec2 cell = ivec2(texel.x >= 96 ? texel.x - RAIN_RIV_CELLS : texel.x, texel.y >= 96 ? texel.y - RAIN_RIV_CELLS : texel.y); + rain_cells[index] = rivulet_cell(layer, cell); +} diff --git a/shaders/vk14/rain_cells.glsl b/shaders/vk14/rain_cells.glsl new file mode 100644 index 000000000..e61cfe4f6 --- /dev/null +++ b/shaders/vk14/rain_cells.glsl @@ -0,0 +1,67 @@ +// the cells of the glasses with rain (mat_rain_windscreen.frag): the drops of the grid of drops and the rivulets of the layers of +// rivulets, worked out once a frame for every cell by rain_cells.comp (a thread a cell) instead of in every pixel of a glass for +// its 9 neighbouring cells. a cell holds the random values of its drop or rivulet as they are now (the hashes of the cell and of +// its epoch, the life cycle at the time of the frame); the glass takes the sizes and the places from them with its own settings. +// so the glass looks the same as when it worked them out itself (the hashes are the same; the values are kept to 8 or 16 bits) +// +// a cell is one uvec4. the drops: RAIN_DROP_CELLS x RAIN_DROP_CELLS cells, cell c of the grid in element (c.y & 511) * 512 + +// (c.x & 511), whole for the cells -1 .. 510 (grids up to 510 cells; finer ones repeat their drops every 512 cells): +// x side 0 (the drop of a cell the blades went over on their way out): bits 0-7 the threshold the wipers have to be past for +// it, 8-15 / 16-23 the place in the cell (x, y), 24-31 the random of its size +// y side 0: bits 0-7 the random of its sag, 8-15 of its stretch by the air, 16 mirrored, 17-18 the tile of the atlas, +// 19-23 how far it spread out landing (0 .. 31), 24-31 the random a cell holds a drop by (a drop when below the share) +// z side 1 (the blades on their way back): as x +// w side 1: as y, bit 19 set when the blades miss the drop, bits 24-31 its visibility in its life (0 .. 255) +// the rivulets: RAIN_RIV_LAYERS layers (0 gravity, 1 .. 4 the air) of RAIN_RIV_CELLS x RAIN_RIV_CELLS cells, cell c in element +// RAIN_RIV_BASE + layer * 128 * 128 + (c.y & 127) * 128 + (c.x & 127), whole for the cells -32 .. 95: +// x bits 0-15 the random the cell holds a rivulet by, 16-23 its life (0 .. 255), 24-31 the random of the wipers it stays under +// y bits 0-15 how far down its run the head is (0 .. 65535), 16-23 the random of its width, 24-31 of its span +// z the randoms of its top, its left edge, the length and the phase of its waves (a byte each) +// w bits 0-7 the random of the speed of its waves, 8 mirrored, 9-10 the sprite of the atlas + +#ifndef RAIN_CELLS_GLSL +#define RAIN_CELLS_GLSL + +#define RAIN_DROP_CELLS 512 +#define RAIN_RIV_CELLS 128 +#define RAIN_RIV_LAYERS 5 +#define RAIN_RIV_BASE (RAIN_DROP_CELLS * RAIN_DROP_CELLS) +#define RAIN_CELLS_COUNT (RAIN_RIV_BASE + RAIN_RIV_LAYERS * RAIN_RIV_CELLS * RAIN_RIV_CELLS) +#define RAIN_CELLS_GROUP_SIZE 64 + +#if defined(STAGE_COMPUTE) +layout(std430, set = COMPUTE_SET, binding = 0) writeonly buffer rain_cells_ssbo +#else +layout(std430, set = PASS_SET, binding = RAIN_CELLS_SSBO) readonly buffer rain_cells_ssbo +#endif +{ + uvec4 rain_cells[]; +}; + +// the life of the drops and of the rivulets (the settings of mat_rain_windscreen.frag which the cells are worked out with) +const float drop_life_min = 14.0; // seconds a drop sits on the glass +const float drop_life_max = 45.0; +const float drop_appear = 0.18; // seconds of the landing "pop" +const float drop_fade = 1.5; // seconds a drop takes to vanish at the end of its life +const float wiper_miss = 0.05; // share of the drops a blade goes over without taking them +const float streak_period = 40.0; // seconds a rivulet lives (it runs for ~90% of that and then fades out), average +const float wind_streak_period = 18.0; // seconds a rivulet driven by the air lives (they run faster than the ones of gravity) + +// a random kept to 8 bits, back to 0 .. 1 (the middle of its step) +float rain_byte(uint Value, uint Shift) +{ + return (float((Value >> Shift) & 255u) + 0.5) * (1.0 / 256.0); +} + +uint rain_drop_index(ivec2 Cell) +{ + return uint(Cell.y & (RAIN_DROP_CELLS - 1)) * uint(RAIN_DROP_CELLS) + uint(Cell.x & (RAIN_DROP_CELLS - 1)); +} + +uint rain_riv_index(int Layer, ivec2 Cell) +{ + return uint(RAIN_RIV_BASE) + uint(Layer) * uint(RAIN_RIV_CELLS * RAIN_RIV_CELLS) + uint(Cell.y & (RAIN_RIV_CELLS - 1)) * uint(RAIN_RIV_CELLS) + + uint(Cell.x & (RAIN_RIV_CELLS - 1)); +} + +#endif From 0683a468172c389105eaab0a8bbb04ac61b6f828 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 16:58:47 +0100 Subject: [PATCH 051/123] Rain windscreen: a switch to measure what the glass costs (WS_PROFILE, 0 as in the game) [skip ci] Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_rain_windscreen.frag | 20 +++++++++++++++++--- shaders/vk14/mat_rain_windscreen.frag | 20 +++++++++++++++++--- 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/shaders/ogl46/mat_rain_windscreen.frag b/shaders/ogl46/mat_rain_windscreen.frag index e4e2de711..668f21e8a 100644 --- a/shaders/ogl46/mat_rain_windscreen.frag +++ b/shaders/ogl46/mat_rain_windscreen.frag @@ -179,6 +179,13 @@ const float WS_REFR_MIX = 0.85; // 0 = no refraction, 1 = only the refrac const float WS_LIGHT_GAIN = 1.0; // brightness of the lights near a drop shown in it (0 = off) const float WS_LIGHT_CONTRAST = 3.0; // a light: this many times brighter than the place around it +// measuring what costs what (the time of "colour, translucent and cab" with each): 0 everything (as in the game), 1 the drops not lit +// (no sun glint, lamps, reflection), 2 no rivulets (and nothing swept by them), 3 no micro droplets, 4 no drops of the atlas, +// 5 none of the rain (only the glass and the haze) +#ifndef WS_PROFILE +#define WS_PROFILE 0 +#endif + const vec3 DROP_LIGHT = vec3(-0.5527, 0.6532, 0.5226); // same light as the atlas generator (upper left) // the surroundings in a view space direction where the image doesn't hold them: the environment map above the horizon, @@ -686,14 +693,15 @@ void main() vec2 sUVg = vec2(f_coord.x, (STREAK_FLIP_Y != 0) ? 1.0 - f_coord.y : f_coord.y); // glass UV, v up vec2 sCell = floor(sUVg / vec2(sCW, sCH)); Riv rivP = getRiv(sCell, sCW, sCH, gridSize); - bool sweepOn = streak_sweep > 0.0 && streak_density > 0.0 && (wind_streaks > 0.0 || wsWindShare < 1.0); + bool sweepOn = streak_sweep > 0.0 && streak_density > 0.0 && (wind_streaks > 0.0 || wsWindShare < 1.0) && (WS_PROFILE != 2); - if (rain_params.x > 0.001) + if ((rain_params.x > 0.001) && (WS_PROFILE != 5)) { // =================================================================== // 1. drops from the atlas: this cell and its 8 neighbours // =================================================================== vec2 cell = floor(rainCoord * gridSize); +#if WS_PROFILE != 4 float actMax = min(rain_params.x * drop_density, 0.95); for (int oy = -1; oy <= 1; oy++) for (int ox = -1; ox <= 1; ox++) @@ -762,11 +770,12 @@ void main() consider(hit, cov * (nm.b * sq * sag + 1e-5), cov, 0.0, n, diff, 0.5 * sq, 1.0, vis, dropAtlasUV(choice, luv), gx, gy, 1.0, 0.0); } +#endif // =================================================================== // 2. micro droplets: procedural, one per micro cell, fully inside it // =================================================================== - if (micro_density > 0.0) + if ((micro_density > 0.0) && (WS_PROFILE != 3)) { float mg = gridSize * micro_scale; vec2 mc = floor(rainCoord * mg); @@ -819,6 +828,7 @@ void main() // =================================================================== // 3. rivulets of this pixel's cells: the layer of gravity and, at speed, the one of the air // =================================================================== +#if WS_PROFILE != 2 wsSetLayer(0); drawRivulet(hit, rivP, sUVg, wsRd1, wsRd2); if (wsWindShare > 0.001) @@ -834,6 +844,7 @@ void main() } wsSetLayer(0); } +#endif } // ----------------------------------------------------------------------- @@ -958,6 +969,9 @@ void main() float NoV = clamp(dot(Nv, -I), 0.0, 1.0); glint += envmap_color_lod(Nv, 0.8) * EnvBRDFApprox(vec3(0.04), 0.1, NoV) * drop_env * wsNight; } +#if WS_PROFILE == 1 + glint = vec3(0.0); +#endif dropGlint = glint; if (!POSTFX_ENABLED) dropGlint = min(dropGlint, vec3(1.0)); // this path is not tonemapped diff --git a/shaders/vk14/mat_rain_windscreen.frag b/shaders/vk14/mat_rain_windscreen.frag index 1c167c9e4..3ac5ca31a 100644 --- a/shaders/vk14/mat_rain_windscreen.frag +++ b/shaders/vk14/mat_rain_windscreen.frag @@ -184,6 +184,13 @@ const float WS_REFR_MIX = 0.85; // 0 = no refraction, 1 = only the refrac const float WS_LIGHT_GAIN = 1.0; // brightness of the lights near a drop shown in it (0 = off) const float WS_LIGHT_CONTRAST = 3.0; // a light: this many times brighter than the place around it +// measuring what costs what (the time of "colour, translucent and cab" with each): 0 everything (as in the game), 1 the drops not lit +// (no sun glint, lamps, reflection), 2 no rivulets (and nothing swept by them), 3 no micro droplets, 4 no drops of the atlas, +// 5 none of the rain (only the glass and the haze) +#ifndef WS_PROFILE +#define WS_PROFILE 0 +#endif + const vec3 DROP_LIGHT = vec3(-0.5527, 0.6532, 0.5226); // same light as the atlas generator (upper left) // the surroundings in a view space direction where the image doesn't hold them: the environment map above the horizon, @@ -691,14 +698,15 @@ void main() vec2 sUVg = vec2(f_coord.x, (STREAK_FLIP_Y != 0) ? 1.0 - f_coord.y : f_coord.y); // glass UV, v up vec2 sCell = floor(sUVg / vec2(sCW, sCH)); Riv rivP = getRiv(sCell, sCW, sCH, gridSize); - bool sweepOn = streak_sweep > 0.0 && streak_density > 0.0 && (wind_streaks > 0.0 || wsWindShare < 1.0); + bool sweepOn = streak_sweep > 0.0 && streak_density > 0.0 && (wind_streaks > 0.0 || wsWindShare < 1.0) && (WS_PROFILE != 2); - if (rain_params.x > 0.001) + if ((rain_params.x > 0.001) && (WS_PROFILE != 5)) { // =================================================================== // 1. drops from the atlas: this cell and its 8 neighbours // =================================================================== vec2 cell = floor(rainCoord * gridSize); +#if WS_PROFILE != 4 float actMax = min(rain_params.x * drop_density, 0.95); for (int oy = -1; oy <= 1; oy++) for (int ox = -1; ox <= 1; ox++) @@ -767,11 +775,12 @@ void main() consider(hit, cov * (nm.b * sq * sag + 1e-5), cov, 0.0, n, diff, 0.5 * sq, 1.0, vis, dropAtlasUV(choice, luv), gx, gy, 1.0, 0.0); } +#endif // =================================================================== // 2. micro droplets: procedural, one per micro cell, fully inside it // =================================================================== - if (micro_density > 0.0) + if ((micro_density > 0.0) && (WS_PROFILE != 3)) { float mg = gridSize * micro_scale; vec2 mc = floor(rainCoord * mg); @@ -824,6 +833,7 @@ void main() // =================================================================== // 3. rivulets of this pixel's cells: the layer of gravity and, at speed, the one of the air // =================================================================== +#if WS_PROFILE != 2 wsSetLayer(0); drawRivulet(hit, rivP, sUVg, wsRd1, wsRd2); if (wsWindShare > 0.001) @@ -839,6 +849,7 @@ void main() } wsSetLayer(0); } +#endif } // ----------------------------------------------------------------------- @@ -963,6 +974,9 @@ void main() float NoV = clamp(dot(Nv, -I), 0.0, 1.0); glint += envmap_color_lod(Nv, 0.8) * EnvBRDFApprox(vec3(0.04), 0.1, NoV) * drop_env * wsNight; } +#if WS_PROFILE == 1 + glint = vec3(0.0); +#endif dropGlint = glint; if (!POSTFX_ENABLED) dropGlint = min(dropGlint, vec3(1.0)); // this path is not tonemapped From 91d5851ea455674f47ac740118bca59dec2544f7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 17:20:36 +0100 Subject: [PATCH 052/123] Rain windscreen: a glass looks only at the drops which reach the quarter of its cell A second pass of rain_cells.comp writes, for every drop cell, which of the drops of the 9 cells around reach each quarter of it, so a pixel looks at those (usually 1 to 3) instead of all 9. The bias of the drop sizes is applied there too, and the glass keeps fewer values through its loops (the frame of the glass and the lens are worked out after them, the rivulet of the pixel is read again where it is needed), so more pixels run at once. The look is the same. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- gl/ubo.h | 4 +- rendering/opengl46/opengl46water.cpp | 9 ++- rendering/vulkan14/vulkan14water.cpp | 14 +++- shaders/ogl46/mat_rain_windscreen.frag | 108 ++++++++++++++----------- shaders/ogl46/rain_cells.comp | 65 ++++++++++++++- shaders/ogl46/rain_cells.glsl | 23 +++++- shaders/vk14/mat_rain_windscreen.frag | 108 ++++++++++++++----------- shaders/vk14/rain_cells.comp | 67 +++++++++++++-- shaders/vk14/rain_cells.glsl | 23 +++++- 9 files changed, 300 insertions(+), 121 deletions(-) diff --git a/gl/ubo.h b/gl/ubo.h index 6be7979ad..52da98b92 100644 --- a/gl/ubo.h +++ b/gl/ubo.h @@ -716,7 +716,9 @@ namespace gl const size_t RAIN_DROP_CELLS = 512; const size_t RAIN_RIV_CELLS = 128; const size_t RAIN_RIV_LAYERS = 5; - const size_t RAIN_CELLS_COUNT = RAIN_DROP_CELLS * RAIN_DROP_CELLS + RAIN_RIV_LAYERS * RAIN_RIV_CELLS * RAIN_RIV_CELLS; + // the cells (the first pass of rain_cells.comp), then the reach of the drops into the quarters of each drop cell (the second) + const size_t RAIN_MASK_BASE = RAIN_DROP_CELLS * RAIN_DROP_CELLS + RAIN_RIV_LAYERS * RAIN_RIV_CELLS * RAIN_RIV_CELLS; + const size_t RAIN_CELLS_COUNT = RAIN_MASK_BASE + RAIN_DROP_CELLS * RAIN_DROP_CELLS; const size_t RAIN_CELLS_GROUP_SIZE = 64; const GLuint WATER_UBO_BINDING = 6; const size_t WATER_MASK_TEX = MAX_TEXTURES + HELPER_TEXTURES + 13; diff --git a/rendering/opengl46/opengl46water.cpp b/rendering/opengl46/opengl46water.cpp index bd7ce27d9..c8ee70ccd 100644 --- a/rendering/opengl46/opengl46water.cpp +++ b/rendering/opengl46/opengl46water.cpp @@ -111,8 +111,15 @@ void opengl46_windscreen_water::update_rain_cells(float const Time, float const // the glasses of the frame before read the cells, this one writes them ::glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); m_raincells->bind_base(); + auto const groups = [](std::size_t const Count) { return static_cast((Count + gl::RAIN_CELLS_GROUP_SIZE - 1) / gl::RAIN_CELLS_GROUP_SIZE); }; ::glProgramUniform1f(*m_raincellprogram, 0, Time); - m_raincellprogram->dispatch(static_cast((gl::RAIN_CELLS_COUNT + gl::RAIN_CELLS_GROUP_SIZE - 1) / gl::RAIN_CELLS_GROUP_SIZE)); + ::glProgramUniform1f(*m_raincellprogram, 1, Rain); + // the cells, then the reach of the drops into the quarters of each drop cell, which reads them + ::glProgramUniform1i(*m_raincellprogram, 2, 0); + m_raincellprogram->dispatch(groups(gl::RAIN_MASK_BASE)); + ::glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); + ::glProgramUniform1i(*m_raincellprogram, 2, 1); + m_raincellprogram->dispatch(groups(gl::RAIN_CELLS_COUNT - gl::RAIN_MASK_BASE)); ::glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); gl::program::unbind(); } diff --git a/rendering/vulkan14/vulkan14water.cpp b/rendering/vulkan14/vulkan14water.cpp index 5c32c2974..c3aefc748 100644 --- a/rendering/vulkan14/vulkan14water.cpp +++ b/rendering/vulkan14/vulkan14water.cpp @@ -209,10 +209,16 @@ void windscreen_water::update_rain_cells(float const Time, float const Rain) struct constants { float time; - float pad[3]; - } const data{Time, {0.f, 0.f, 0.f}}; - m_raincellkernel.dispatch(commands, {buffer_descriptor(m_raincells->handle(), 0, VK_WHOLE_SIZE)}, data, - static_cast((gl::RAIN_CELLS_COUNT + gl::RAIN_CELLS_GROUP_SIZE - 1) / gl::RAIN_CELLS_GROUP_SIZE)); + float rain; + std::int32_t pass; + float pad; + }; + auto const groups = [](std::size_t const Count) { return static_cast((Count + gl::RAIN_CELLS_GROUP_SIZE - 1) / gl::RAIN_CELLS_GROUP_SIZE); }; + std::vector const descriptors{buffer_descriptor(m_raincells->handle(), 0, VK_WHOLE_SIZE)}; + // the cells, then the reach of the drops into the quarters of each drop cell, which reads them + m_raincellkernel.dispatch(commands, descriptors, constants{Time, Rain, 0, 0.f}, groups(gl::RAIN_MASK_BASE)); + compute_barrier(commands); + m_raincellkernel.dispatch(commands, descriptors, constants{Time, Rain, 1, 0.f}, groups(gl::RAIN_CELLS_COUNT - gl::RAIN_MASK_BASE)); compute_barrier(commands); } diff --git a/shaders/ogl46/mat_rain_windscreen.frag b/shaders/ogl46/mat_rain_windscreen.frag index 668f21e8a..a7bceccc9 100644 --- a/shaders/ogl46/mat_rain_windscreen.frag +++ b/shaders/ogl46/mat_rain_windscreen.frag @@ -89,11 +89,6 @@ const float WS_ENC = 64.0; // the haze request in the velocity // --- Drops (atlas tiles) ------------------------------------------------------ // (how long they live: rain_cells.glsl; the cells of the drops and of the rivulets are worked out once a frame by rain_cells.comp) -const float drop_density = 0.6; // share of grid cells holding a drop at full rain (scaled by rain intensity) -const float drop_size_min = 0.45; // drop size in grid cells -const float drop_size_max = 1.15; -const float drop_size_bias = 1.8; // >1 = more small/medium drops, fewer big ones -const float drop_sag = 0.12; // max vertical stretch of a resting drop (gravity) // --- Micro droplets ------------------------------------------------------------- const float micro_density = 0.45; // share of micro cells holding a droplet at full rain, 0 = off @@ -153,7 +148,6 @@ const float wind_run_scale = 1.2; // ... and their runs this long against const float wind_head_scale = 0.4; // their heads this much smaller (a small bead at the front of a long trail) const int wind_layers = 4; // layers of them, each with drops of its own (1 .. 4) const float wind_long_run = 3.0; // the last layer: its trails this much longer than those of gravity (the long ones, a part of all) -const float drop_wind_stretch = 0.4; // drops are stretched up to this much along the push of the air (0 = off) const float WS_DRAG_SPEED = 24.0; // speed of the air along the glass at which its drag equals the weight of a drop, m/s const float WS_HEAD_ON = 0.35; // share of the air meeting the glass head on which turns up along it const float WS_WIND_STEP = 0.1309; // the direction of the rivulets of the air in steps of 7.5 degrees (no seams on a @@ -543,12 +537,10 @@ void drawRivulet(inout Hit hit, Riv r, vec2 sUVr, vec2 rd1, vec2 rd2) } // how much of a drop centred at Cg (glass UV, v up) with radius Rad the rivulets of both layers have swept up (0..1 kept) -float wsKept(vec2 cg, float rad, Riv rivP, vec2 sCell, float sCW, float sCH, float gridSize) +float wsKept(vec2 cg, float rad, float sCW, float sCH, float gridSize) { wsSetLayer(0); - vec2 rc = floor(cg / vec2(sCW, sCH)); - Riv rv = rivP; - if (rc != sCell) rv = getRiv(rc, sCW, sCH, gridSize); + Riv rv = getRiv(floor(cg / vec2(sCW, sCH)), sCW, sCH, gridSize); float kept = 1.0 - streak_sweep * rivSwept(rv, cg, rad); if (wsWindShare > 0.001) { @@ -581,13 +573,27 @@ float wsWipeAge(vec2 co) return age; } +// the tangent frame of the glass (the directions of u and v on it, view space) from the screen-space change of the place and the uv +void wsGlassFrame(vec3 Ngl, vec2 duv1, vec2 duv2, out vec3 Tgl, out vec3 Bgl) +{ + vec3 dp1 = dFdx(f_pos.xyz); + vec3 dp2 = dFdy(f_pos.xyz); + vec3 dp2perp = cross(dp2, Ngl); + vec3 dp1perp = cross(Ngl, dp1); + Tgl = dp2perp * duv1.x + dp1perp * duv2.x; + Bgl = dp2perp * duv1.y + dp1perp * duv2.y; + float invmax = inversesqrt(max(max(dot(Tgl, Tgl), dot(Bgl, Bgl)), 1e-20)); + Tgl *= invmax; + Bgl *= invmax; +} + // the drop of a cell for one side of the blades (A, B: its half of the cell in rain_cells): where it lies, how big it is and its // shape (the sag, the stretch by the air along PushT). true when P lies on it bool wsDropShape(uint a, uint b, vec2 nc, float gridSize, float spreadF, float speed, vec2 pushT, vec2 p, out vec2 center, out float sq, out float sag, out mat2 shapeM, out vec2 dl) { center = (nc + vec2(rain_byte(a, 8u), rain_byte(a, 16u))) / gridSize; - float size = mix(drop_size_min, drop_size_max, pow(rain_byte(a, 24u), drop_size_bias)) / gridSize; + float size = mix(drop_size_min, drop_size_max, rain_byte(a, 24u)) / gridSize; // the bias of the sizes: rain_cells.comp sag = 1.0 + drop_sag * rain_byte(b, 0u); // at speed the air stretches the drop along its push (1 standing still: the drop as it always was) float stretch = 1.0 + drop_wind_stretch * speed * rain_byte(b, 8u); @@ -600,28 +606,12 @@ bool wsDropShape(uint a, uint b, vec2 nc, float gridSize, float spreadF, float s void main() { // ---- screen-space derivatives (before any non-uniform flow) ---- - float uvPerPx = max(length(dFdx(f_coord)), length(dFdy(f_coord))); - vec2 sxy = f_pos.xy / max(-f_pos.z, 1e-3); - float pxPerSlope = 1.0 / max(max(length(dFdx(sxy)), length(dFdy(sxy))), 1e-6); - vec3 Ngl = normalize(f_normal); - vec3 wsView = normalize(f_pos.xyz); // the view through the glass and its change per pixel (for the bent view) - vec3 wsDvx = dFdx(wsView); - vec3 wsDvy = dFdy(wsView); - vec3 dp1 = dFdx(f_pos.xyz); - vec3 dp2 = dFdy(f_pos.xyz); + // only what the drops, the droplets and the rivulets read is kept through their loops; the frame of the glass, the change of the + // view and the lens are worked out again for the shading after them (fewer registers in the loops: more pixels at once) vec2 duv1 = dFdx(f_coord); vec2 duv2 = dFdy(f_coord); - vec3 dp2perp = cross(dp2, Ngl); - vec3 dp1perp = cross(Ngl, dp1); - vec3 Tgl = dp2perp * duv1.x + dp1perp * duv2.x; - vec3 Bgl = dp2perp * duv1.y + dp1perp * duv2.y; - float invmax = inversesqrt(max(max(dot(Tgl, Tgl), dot(Bgl, Bgl)), 1e-20)); - Tgl *= invmax; - Bgl *= invmax; - // glass UV offset -> screen pixels (inverse of the UV Jacobian), for the drop lens - mat2 Juv = mat2(duv1, duv2); - float detJ = determinant(Juv); - mat2 Jinv = (abs(detJ) > 1e-20) ? inverse(Juv) : mat2(0.0); + float uvPerPx = max(length(duv1), length(duv2)); + vec3 Ngl = normalize(f_normal); vec4 tex_color = texture(diffuse, f_coord); float glassA = tex_color.a * alpha_mult; @@ -647,11 +637,16 @@ void main() hit.offUV = vec2(0.0); hit.radUV = 1.0; hit.isDrop = 1.0; hit.vis = 0.0; hit.auv = vec2(0.0); hit.agx = vec2(0.0); hit.agy = vec2(0.0); hit.atlas = 0.0; hit.shade = 0.0; - // ---- the air against the vehicle on the glass (uniform flow: the derivatives of the glass above) ---- + // ---- the air against the vehicle on the glass (uniform flow: the derivatives of the glass) ---- + vec2 wsPushT; + float wsSpeed; float flipS = (STREAK_FLIP_Y != 0) ? -1.0 : 1.0; // texture v -> glass v (up) + vec3 wsN = (dot(Ngl, f_pos.xyz) < 0.0) ? -Ngl : Ngl; // the outside of the glass + { + vec3 Tgl, Bgl; + wsGlassFrame(Ngl, duv1, duv2, Tgl, Bgl); vec3 wsUp = vec3(0.0, 1.0, 0.0) * mat3(inv_view); // world up, view space vec3 wsAir = rain_wind.xyz * mat3(inv_view); // the air against the vehicle, view space, m/s - vec3 wsN = (dot(Ngl, f_pos.xyz) < 0.0) ? -Ngl : Ngl; // the outside of the glass vec3 wsGrav = -wsUp - wsN * dot(-wsUp, wsN); // the weight along the glass vec3 wsRise = wsUp - wsN * dot(wsUp, wsN); wsRise = (length(wsRise) > 0.1) ? normalize(wsRise) : vec3(0.0); @@ -662,7 +657,7 @@ void main() // to the glass UV (v up) through the tangent frame of the texture vec2 gravG = vec2(dot(wsGrav, Tgl), dot(wsGrav, Bgl) * flipS); vec2 flowG = vec2(dot(wsFlowDir, Tgl), dot(wsFlowDir, Bgl) * flipS); - float wsSpeed = smoothstep(0.3, 1.2, wsDrag); // 0 standing still .. 1 at speed (haze, drops) + wsSpeed = smoothstep(0.3, 1.2, wsDrag); // 0 standing still .. 1 at speed (haze, drops) wsWindShare = smoothstep(0.5, 1.3, wsDrag); // how much the air drives the rivulets if (wsWindShare > 0.0) { @@ -680,8 +675,9 @@ void main() wsWindShare = 0.0; } // the push of the air on the drops, texture UV (for stretching them) - vec2 wsPushT = vec2(dot(wsPush, Tgl), dot(wsPush, Bgl)); + wsPushT = vec2(dot(wsPush, Tgl), dot(wsPush, Bgl)); wsPushT = (dot(wsPushT, wsPushT) > 1e-10) ? normalize(wsPushT) : vec2(0.0, -1.0); + } // the change of the glass UV (v up) per screen pixel, for the rivulets vec2 wsRd1 = vec2(duv1.x, flipS * duv1.y); vec2 wsRd2 = vec2(duv2.x, flipS * duv2.y); @@ -692,7 +688,6 @@ void main() float sCH = streak_run / gridSize; vec2 sUVg = vec2(f_coord.x, (STREAK_FLIP_Y != 0) ? 1.0 - f_coord.y : f_coord.y); // glass UV, v up vec2 sCell = floor(sUVg / vec2(sCW, sCH)); - Riv rivP = getRiv(sCell, sCW, sCH, gridSize); bool sweepOn = streak_sweep > 0.0 && streak_density > 0.0 && (wind_streaks > 0.0 || wsWindShare < 1.0) && (WS_PROFILE != 2); if ((rain_params.x > 0.001) && (WS_PROFILE != 5)) @@ -700,20 +695,20 @@ void main() // =================================================================== // 1. drops from the atlas: this cell and its 8 neighbours // =================================================================== - vec2 cell = floor(rainCoord * gridSize); + vec2 cellF = rainCoord * gridSize; + vec2 cell = floor(cellF); #if WS_PROFILE != 4 - float actMax = min(rain_params.x * drop_density, 0.95); - for (int oy = -1; oy <= 1; oy++) - for (int ox = -1; ox <= 1; ox++) + // the drops of the 9 cells around which reach the quarter of the cell the pixel lies in (worked out by rain_cells.comp, + // with the drops there are now): usually 1 .. 3 of them + uvec2 quarter = uvec2(greaterThanEqual(cellF - cell, vec2(0.5))); + uint reach = rain_cells[rain_mask_index(ivec2(cell))][quarter.y * 2u + quarter.x]; + while (reach != 0u) { - vec2 nc = cell + vec2(ox, oy); - // the drop of the cell as it is now (rain_cells.comp): none, or the one of either side of the blades + int bit = findLSB(reach); + reach &= reach - 1u; + vec2 nc = cell + vec2(float(bit % 3 - 1), float(bit / 3 - 1)); uvec4 d = rain_cells[rain_drop_index(ivec2(nc))]; - if (rain_byte(d.y, 24u) > actMax) - continue; float vis = float(d.w >> 24) * (1.0 / 255.0); - if (vis <= 0.001) - continue; float spreadF = mix(0.8, 1.0, float((d.y >> 19) & 31u) * (1.0 / 31.0)); // a drop the blades miss: the same drop before and after the stroke, left where it is bool missed = ((d.w >> 19) & 1u) != 0u; @@ -745,7 +740,7 @@ void main() if (sweepOn) { vec2 cg = vec2(center.x, (STREAK_FLIP_Y != 0) ? 1.0 - center.y : center.y); - vis *= wsKept(cg, 0.35 * sq, rivP, sCell, sCW, sCH, gridSize); + vis *= wsKept(cg, 0.35 * sq, sCW, sCH, gridSize); } if (vis <= 0.001) continue; @@ -804,7 +799,7 @@ void main() { vec2 cu = c / mg; vec2 cg = vec2(cu.x, (STREAK_FLIP_Y != 0) ? 1.0 - cu.y : cu.y); - vis *= wsKept(cg, r / mg, rivP, sCell, sCW, sCH, gridSize); + vis *= wsKept(cg, r / mg, sCW, sCH, gridSize); } float d = sqrt(d2); float cov = smoothstep(1.0, 0.8, d) * vis; @@ -830,7 +825,7 @@ void main() // =================================================================== #if WS_PROFILE != 2 wsSetLayer(0); - drawRivulet(hit, rivP, sUVg, wsRd1, wsRd2); + drawRivulet(hit, getRiv(sCell, sCW, sCH, gridSize), sUVg, wsRd1, wsRd2); if (wsWindShare > 0.001) { for (int wl = 1; wl <= wind_layers; ++wl) @@ -847,6 +842,21 @@ void main() #endif } + // ---- the frame of the glass, the change of the view and the lens, for the shading (uniform flow again) ---- + vec2 sxy = f_pos.xy / max(-f_pos.z, 1e-3); + float pxPerSlope = 1.0 / max(max(length(dFdx(sxy)), length(dFdy(sxy))), 1e-6); + vec3 wsView = normalize(f_pos.xyz); // the view through the glass and its change per pixel (for the bent view) + vec3 wsDvx = dFdx(wsView); + vec3 wsDvy = dFdy(wsView); + vec3 dp1 = dFdx(f_pos.xyz); + vec3 dp2 = dFdy(f_pos.xyz); + vec3 Tgl, Bgl; + wsGlassFrame(Ngl, duv1, duv2, Tgl, Bgl); + // glass UV offset -> screen pixels (inverse of the UV Jacobian), for the drop lens + mat2 Juv = mat2(duv1, duv2); + float detJ = determinant(Juv); + mat2 Jinv = (abs(detJ) > 1e-20) ? inverse(Juv) : mat2(0.0); + // ----------------------------------------------------------------------- // Shading of the winning dome // ----------------------------------------------------------------------- diff --git a/shaders/ogl46/rain_cells.comp b/shaders/ogl46/rain_cells.comp index 7cece6a0b..6916c3eab 100644 --- a/shaders/ogl46/rain_cells.comp +++ b/shaders/ogl46/rain_cells.comp @@ -1,11 +1,14 @@ #version 460 core #define STAGE_COMPUTE 1 // the cells of the glasses with rain (rain_cells.glsl): the drops and the rivulets of every cell worked out for the time of the -// frame, a thread a cell, before the passes which draw the glasses (mat_rain_windscreen.frag only reads them) +// frame, a thread a cell, before the passes which draw the glasses (mat_rain_windscreen.frag only reads them). two passes: the +// cells (rain_pass 0), then which drops reach the quarters of each drop cell (rain_pass 1, it reads the first) #include "common.glsl" -layout(location = 0) uniform float rain_time; // the time of the block of the scene (scene_ubs.time) +layout(location = 0) uniform float rain_time; // the time of the block of the scene (scene_ubs.time) +layout(location = 1) uniform float rain_amount; // how hard it rains (scene_ubs.rain_params.x) +layout(location = 2) uniform int rain_pass; // 0 the cells, 1 the reach of the drops #include "random.glsl" #include "rain_cells.glsl" @@ -60,7 +63,7 @@ uvec4 drop_cell(ivec2 Cell) float choice = RandF(s2); float stretch = RandF(s2); uint tile = min(uint(choice * 4.0), 3u); - uint a = q8(thr) | (q8(cx) << 8) | (q8(cy) << 16) | (q8(size) << 24); + uint a = q8(thr) | (q8(cx) << 8) | (q8(cy) << 16) | (q8(pow(size, drop_size_bias)) << 24); uint b = q8(sag) | (q8(stretch) << 8) | ((flip < 0.5) ? (1u << 16) : 0u) | (tile << 17); if (side == 0u) { @@ -108,10 +111,64 @@ uvec4 rivulet_cell(int Layer, ivec2 Cell) return result; } +// how far from the centre (in cells) the drop of side half A, B of a cell can reach at most: half its size, the sag, the stretch of the +// air at its strongest, any way it is turned +float drop_reach(uint A, uint B, float Spread) +{ + float half_size = 0.5 * mix(drop_size_min, drop_size_max, rain_byte(A, 24u)) * Spread; + float sag = 1.0 + drop_sag * rain_byte(B, 0u); + float stretch = 1.0 + drop_wind_stretch * rain_byte(B, 8u); + return half_size * sqrt(1.0 + sag * sag) * stretch * 1.01; +} + +// the reach of the drops around a drop cell into its quarters (rain_cells.glsl), from the cells worked out by the first pass +uvec4 drop_masks(ivec2 Cell) +{ + uvec4 result = uvec4(0u); + float most = min(rain_amount * drop_density, 0.95); + for (int dy = -1; dy <= 1; ++dy) + for (int dx = -1; dx <= 1; ++dx) + { + uvec4 d = rain_cells[rain_drop_index(Cell + ivec2(dx, dy))]; + if ((rain_byte(d.y, 24u) > most) || ((d.w >> 24) == 0u)) + continue; + float spread = mix(0.8, 1.0, float((d.y >> 19) & 31u) * (1.0 / 31.0)); + bool missed = ((d.w >> 19) & 1u) != 0u; + uint bit = 1u << uint((dy + 1) * 3 + dx + 1); + for (uint side = 0u; side < 2u; ++side) + { + if ((side == 1u) && missed) + break; + uint a = (side == 0u) ? d.x : d.z; + uint b = (side == 0u) ? d.y : d.w; + vec2 centre = vec2(dx, dy) + vec2(rain_byte(a, 8u), rain_byte(a, 16u)); + float reach = drop_reach(a, b, spread); + for (uint q = 0u; q < 4u; ++q) + { + vec2 low = vec2(float(q & 1u), float(q >> 1)) * 0.5; + vec2 away = max(max(low - centre, centre - (low + 0.5)), vec2(0.0)); + if (dot(away, away) < reach * reach) + result[q] |= bit; + } + } + } + return result; +} + void main() { uint index = gl_GlobalInvocationID.x; - if (index >= uint(RAIN_CELLS_COUNT)) + if (rain_pass == 1) + { + // the second pass: the reach of the drops, a thread a drop cell + if (index >= uint(RAIN_DROP_CELLS * RAIN_DROP_CELLS)) + return; + ivec2 texel = ivec2(int(index % uint(RAIN_DROP_CELLS)), int(index / uint(RAIN_DROP_CELLS))); + ivec2 cell = ivec2(texel.x == RAIN_DROP_CELLS - 1 ? -1 : texel.x, texel.y == RAIN_DROP_CELLS - 1 ? -1 : texel.y); + rain_cells[uint(RAIN_MASK_BASE) + index] = drop_masks(cell); + return; + } + if (index >= uint(RAIN_MASK_BASE)) return; if (index < uint(RAIN_RIV_BASE)) { diff --git a/shaders/ogl46/rain_cells.glsl b/shaders/ogl46/rain_cells.glsl index 97819d724..52e248032 100644 --- a/shaders/ogl46/rain_cells.glsl +++ b/shaders/ogl46/rain_cells.glsl @@ -7,11 +7,14 @@ // a cell is one uvec4. the drops: RAIN_DROP_CELLS x RAIN_DROP_CELLS cells, cell c of the grid in element (c.y & 511) * 512 + // (c.x & 511), whole for the cells -1 .. 510 (grids up to 510 cells; finer ones repeat their drops every 512 cells): // x side 0 (the drop of a cell the blades went over on their way out): bits 0-7 the threshold the wipers have to be past for -// it, 8-15 / 16-23 the place in the cell (x, y), 24-31 the random of its size +// it, 8-15 / 16-23 the place in the cell (x, y), 24-31 its size (0 .. 1 from drop_size_min to drop_size_max) // y side 0: bits 0-7 the random of its sag, 8-15 of its stretch by the air, 16 mirrored, 17-18 the tile of the atlas, // 19-23 how far it spread out landing (0 .. 31), 24-31 the random a cell holds a drop by (a drop when below the share) // z side 1 (the blades on their way back): as x // w side 1: as y, bit 19 set when the blades miss the drop, bits 24-31 its visibility in its life (0 .. 255) +// the reach of the drops: for every drop cell (element RAIN_MASK_BASE + the index of the drop cell) the drops of the 9 cells around +// it (bit (dy + 1) * 3 + dx + 1) which reach into each quarter of it (x the lower left, y the lower right, z the upper left, w the +// upper right), with the drops the cells hold now in the rain there is now (a glass only looks at those) // the rivulets: RAIN_RIV_LAYERS layers (0 gravity, 1 .. 4 the air) of RAIN_RIV_CELLS x RAIN_RIV_CELLS cells, cell c in element // RAIN_RIV_BASE + layer * 128 * 128 + (c.y & 127) * 128 + (c.x & 127), whole for the cells -32 .. 95: // x bits 0-15 the random the cell holds a rivulet by, 16-23 its life (0 .. 255), 24-31 the random of the wipers it stays under @@ -26,11 +29,12 @@ #define RAIN_RIV_CELLS 128 #define RAIN_RIV_LAYERS 5 #define RAIN_RIV_BASE (RAIN_DROP_CELLS * RAIN_DROP_CELLS) -#define RAIN_CELLS_COUNT (RAIN_RIV_BASE + RAIN_RIV_LAYERS * RAIN_RIV_CELLS * RAIN_RIV_CELLS) +#define RAIN_MASK_BASE (RAIN_RIV_BASE + RAIN_RIV_LAYERS * RAIN_RIV_CELLS * RAIN_RIV_CELLS) +#define RAIN_CELLS_COUNT (RAIN_MASK_BASE + RAIN_DROP_CELLS * RAIN_DROP_CELLS) #define RAIN_CELLS_GROUP_SIZE 64 #if defined(STAGE_COMPUTE) -layout(std430, binding = RAIN_CELLS_SSBO_BINDING) writeonly buffer rain_cells_ssbo +layout(std430, binding = RAIN_CELLS_SSBO_BINDING) buffer rain_cells_ssbo #else layout(std430, binding = RAIN_CELLS_SSBO_BINDING) readonly buffer rain_cells_ssbo #endif @@ -38,7 +42,13 @@ layout(std430, binding = RAIN_CELLS_SSBO_BINDING) readonly buffer rain_cells_ssb uvec4 rain_cells[]; }; -// the life of the drops and of the rivulets (the settings of mat_rain_windscreen.frag which the cells are worked out with) +// the drops and the rivulets (the settings of mat_rain_windscreen.frag which the cells are worked out with) +const float drop_density = 0.6; // share of grid cells holding a drop at full rain (scaled by rain intensity) +const float drop_size_min = 0.45; // drop size in grid cells +const float drop_size_max = 1.15; +const float drop_size_bias = 1.8; // >1 = more small/medium drops, fewer big ones +const float drop_sag = 0.12; // max vertical stretch of a resting drop (gravity) +const float drop_wind_stretch = 0.4; // drops are stretched up to this much along the push of the air (0 = off) const float drop_life_min = 14.0; // seconds a drop sits on the glass const float drop_life_max = 45.0; const float drop_appear = 0.18; // seconds of the landing "pop" @@ -58,6 +68,11 @@ uint rain_drop_index(ivec2 Cell) return uint(Cell.y & (RAIN_DROP_CELLS - 1)) * uint(RAIN_DROP_CELLS) + uint(Cell.x & (RAIN_DROP_CELLS - 1)); } +uint rain_mask_index(ivec2 Cell) +{ + return uint(RAIN_MASK_BASE) + rain_drop_index(Cell); +} + uint rain_riv_index(int Layer, ivec2 Cell) { return uint(RAIN_RIV_BASE) + uint(Layer) * uint(RAIN_RIV_CELLS * RAIN_RIV_CELLS) + uint(Cell.y & (RAIN_RIV_CELLS - 1)) * uint(RAIN_RIV_CELLS) diff --git a/shaders/vk14/mat_rain_windscreen.frag b/shaders/vk14/mat_rain_windscreen.frag index 3ac5ca31a..9b8bfb2a8 100644 --- a/shaders/vk14/mat_rain_windscreen.frag +++ b/shaders/vk14/mat_rain_windscreen.frag @@ -94,11 +94,6 @@ const float WS_ENC = 64.0; // the haze request in the velocity // --- Drops (atlas tiles) ------------------------------------------------------ // (how long they live: rain_cells.glsl; the cells of the drops and of the rivulets are worked out once a frame by rain_cells.comp) -const float drop_density = 0.6; // share of grid cells holding a drop at full rain (scaled by rain intensity) -const float drop_size_min = 0.45; // drop size in grid cells -const float drop_size_max = 1.15; -const float drop_size_bias = 1.8; // >1 = more small/medium drops, fewer big ones -const float drop_sag = 0.12; // max vertical stretch of a resting drop (gravity) // --- Micro droplets ------------------------------------------------------------- const float micro_density = 0.45; // share of micro cells holding a droplet at full rain, 0 = off @@ -158,7 +153,6 @@ const float wind_run_scale = 1.2; // ... and their runs this long against const float wind_head_scale = 0.4; // their heads this much smaller (a small bead at the front of a long trail) const int wind_layers = 4; // layers of them, each with drops of its own (1 .. 4) const float wind_long_run = 3.0; // the last layer: its trails this much longer than those of gravity (the long ones, a part of all) -const float drop_wind_stretch = 0.4; // drops are stretched up to this much along the push of the air (0 = off) const float WS_DRAG_SPEED = 24.0; // speed of the air along the glass at which its drag equals the weight of a drop, m/s const float WS_HEAD_ON = 0.35; // share of the air meeting the glass head on which turns up along it const float WS_WIND_STEP = 0.1309; // the direction of the rivulets of the air in steps of 7.5 degrees (no seams on a @@ -548,12 +542,10 @@ void drawRivulet(inout Hit hit, Riv r, vec2 sUVr, vec2 rd1, vec2 rd2) } // how much of a drop centred at Cg (glass UV, v up) with radius Rad the rivulets of both layers have swept up (0..1 kept) -float wsKept(vec2 cg, float rad, Riv rivP, vec2 sCell, float sCW, float sCH, float gridSize) +float wsKept(vec2 cg, float rad, float sCW, float sCH, float gridSize) { wsSetLayer(0); - vec2 rc = floor(cg / vec2(sCW, sCH)); - Riv rv = rivP; - if (rc != sCell) rv = getRiv(rc, sCW, sCH, gridSize); + Riv rv = getRiv(floor(cg / vec2(sCW, sCH)), sCW, sCH, gridSize); float kept = 1.0 - streak_sweep * rivSwept(rv, cg, rad); if (wsWindShare > 0.001) { @@ -586,13 +578,27 @@ float wsWipeAge(vec2 co) return age; } +// the tangent frame of the glass (the directions of u and v on it, view space) from the screen-space change of the place and the uv +void wsGlassFrame(vec3 Ngl, vec2 duv1, vec2 duv2, out vec3 Tgl, out vec3 Bgl) +{ + vec3 dp1 = dFdx(f_pos.xyz); + vec3 dp2 = dFdy(f_pos.xyz); + vec3 dp2perp = cross(dp2, Ngl); + vec3 dp1perp = cross(Ngl, dp1); + Tgl = dp2perp * duv1.x + dp1perp * duv2.x; + Bgl = dp2perp * duv1.y + dp1perp * duv2.y; + float invmax = inversesqrt(max(max(dot(Tgl, Tgl), dot(Bgl, Bgl)), 1e-20)); + Tgl *= invmax; + Bgl *= invmax; +} + // the drop of a cell for one side of the blades (A, B: its half of the cell in rain_cells): where it lies, how big it is and its // shape (the sag, the stretch by the air along PushT). true when P lies on it bool wsDropShape(uint a, uint b, vec2 nc, float gridSize, float spreadF, float speed, vec2 pushT, vec2 p, out vec2 center, out float sq, out float sag, out mat2 shapeM, out vec2 dl) { center = (nc + vec2(rain_byte(a, 8u), rain_byte(a, 16u))) / gridSize; - float size = mix(drop_size_min, drop_size_max, pow(rain_byte(a, 24u), drop_size_bias)) / gridSize; + float size = mix(drop_size_min, drop_size_max, rain_byte(a, 24u)) / gridSize; // the bias of the sizes: rain_cells.comp sag = 1.0 + drop_sag * rain_byte(b, 0u); // at speed the air stretches the drop along its push (1 standing still: the drop as it always was) float stretch = 1.0 + drop_wind_stretch * speed * rain_byte(b, 8u); @@ -605,28 +611,12 @@ bool wsDropShape(uint a, uint b, vec2 nc, float gridSize, float spreadF, float s void main() { // ---- screen-space derivatives (before any non-uniform flow) ---- - float uvPerPx = max(length(dFdx(f_coord)), length(dFdy(f_coord))); - vec2 sxy = f_pos.xy / max(-f_pos.z, 1e-3); - float pxPerSlope = 1.0 / max(max(length(dFdx(sxy)), length(dFdy(sxy))), 1e-6); - vec3 Ngl = normalize(f_normal); - vec3 wsView = normalize(f_pos.xyz); // the view through the glass and its change per pixel (for the bent view) - vec3 wsDvx = dFdx(wsView); - vec3 wsDvy = dFdy(wsView); - vec3 dp1 = dFdx(f_pos.xyz); - vec3 dp2 = dFdy(f_pos.xyz); + // only what the drops, the droplets and the rivulets read is kept through their loops; the frame of the glass, the change of the + // view and the lens are worked out again for the shading after them (fewer registers in the loops: more pixels at once) vec2 duv1 = dFdx(f_coord); vec2 duv2 = dFdy(f_coord); - vec3 dp2perp = cross(dp2, Ngl); - vec3 dp1perp = cross(Ngl, dp1); - vec3 Tgl = dp2perp * duv1.x + dp1perp * duv2.x; - vec3 Bgl = dp2perp * duv1.y + dp1perp * duv2.y; - float invmax = inversesqrt(max(max(dot(Tgl, Tgl), dot(Bgl, Bgl)), 1e-20)); - Tgl *= invmax; - Bgl *= invmax; - // glass UV offset -> screen pixels (inverse of the UV Jacobian), for the drop lens - mat2 Juv = mat2(duv1, duv2); - float detJ = determinant(Juv); - mat2 Jinv = (abs(detJ) > 1e-20) ? inverse(Juv) : mat2(0.0); + float uvPerPx = max(length(duv1), length(duv2)); + vec3 Ngl = normalize(f_normal); vec4 tex_color = texture(diffuse, f_coord); float glassA = tex_color.a * alpha_mult; @@ -652,11 +642,16 @@ void main() hit.offUV = vec2(0.0); hit.radUV = 1.0; hit.isDrop = 1.0; hit.vis = 0.0; hit.auv = vec2(0.0); hit.agx = vec2(0.0); hit.agy = vec2(0.0); hit.atlas = 0.0; hit.shade = 0.0; - // ---- the air against the vehicle on the glass (uniform flow: the derivatives of the glass above) ---- + // ---- the air against the vehicle on the glass (uniform flow: the derivatives of the glass) ---- + vec2 wsPushT; + float wsSpeed; float flipS = (STREAK_FLIP_Y != 0) ? -1.0 : 1.0; // texture v -> glass v (up) + vec3 wsN = (dot(Ngl, f_pos.xyz) < 0.0) ? -Ngl : Ngl; // the outside of the glass + { + vec3 Tgl, Bgl; + wsGlassFrame(Ngl, duv1, duv2, Tgl, Bgl); vec3 wsUp = vec3(0.0, 1.0, 0.0) * mat3(inv_view); // world up, view space vec3 wsAir = rain_wind.xyz * mat3(inv_view); // the air against the vehicle, view space, m/s - vec3 wsN = (dot(Ngl, f_pos.xyz) < 0.0) ? -Ngl : Ngl; // the outside of the glass vec3 wsGrav = -wsUp - wsN * dot(-wsUp, wsN); // the weight along the glass vec3 wsRise = wsUp - wsN * dot(wsUp, wsN); wsRise = (length(wsRise) > 0.1) ? normalize(wsRise) : vec3(0.0); @@ -667,7 +662,7 @@ void main() // to the glass UV (v up) through the tangent frame of the texture vec2 gravG = vec2(dot(wsGrav, Tgl), dot(wsGrav, Bgl) * flipS); vec2 flowG = vec2(dot(wsFlowDir, Tgl), dot(wsFlowDir, Bgl) * flipS); - float wsSpeed = smoothstep(0.3, 1.2, wsDrag); // 0 standing still .. 1 at speed (haze, drops) + wsSpeed = smoothstep(0.3, 1.2, wsDrag); // 0 standing still .. 1 at speed (haze, drops) wsWindShare = smoothstep(0.5, 1.3, wsDrag); // how much the air drives the rivulets if (wsWindShare > 0.0) { @@ -685,8 +680,9 @@ void main() wsWindShare = 0.0; } // the push of the air on the drops, texture UV (for stretching them) - vec2 wsPushT = vec2(dot(wsPush, Tgl), dot(wsPush, Bgl)); + wsPushT = vec2(dot(wsPush, Tgl), dot(wsPush, Bgl)); wsPushT = (dot(wsPushT, wsPushT) > 1e-10) ? normalize(wsPushT) : vec2(0.0, -1.0); + } // the change of the glass UV (v up) per screen pixel, for the rivulets vec2 wsRd1 = vec2(duv1.x, flipS * duv1.y); vec2 wsRd2 = vec2(duv2.x, flipS * duv2.y); @@ -697,7 +693,6 @@ void main() float sCH = streak_run / gridSize; vec2 sUVg = vec2(f_coord.x, (STREAK_FLIP_Y != 0) ? 1.0 - f_coord.y : f_coord.y); // glass UV, v up vec2 sCell = floor(sUVg / vec2(sCW, sCH)); - Riv rivP = getRiv(sCell, sCW, sCH, gridSize); bool sweepOn = streak_sweep > 0.0 && streak_density > 0.0 && (wind_streaks > 0.0 || wsWindShare < 1.0) && (WS_PROFILE != 2); if ((rain_params.x > 0.001) && (WS_PROFILE != 5)) @@ -705,20 +700,20 @@ void main() // =================================================================== // 1. drops from the atlas: this cell and its 8 neighbours // =================================================================== - vec2 cell = floor(rainCoord * gridSize); + vec2 cellF = rainCoord * gridSize; + vec2 cell = floor(cellF); #if WS_PROFILE != 4 - float actMax = min(rain_params.x * drop_density, 0.95); - for (int oy = -1; oy <= 1; oy++) - for (int ox = -1; ox <= 1; ox++) + // the drops of the 9 cells around which reach the quarter of the cell the pixel lies in (worked out by rain_cells.comp, + // with the drops there are now): usually 1 .. 3 of them + uvec2 quarter = uvec2(greaterThanEqual(cellF - cell, vec2(0.5))); + uint reach = rain_cells[rain_mask_index(ivec2(cell))][quarter.y * 2u + quarter.x]; + while (reach != 0u) { - vec2 nc = cell + vec2(ox, oy); - // the drop of the cell as it is now (rain_cells.comp): none, or the one of either side of the blades + int bit = findLSB(reach); + reach &= reach - 1u; + vec2 nc = cell + vec2(float(bit % 3 - 1), float(bit / 3 - 1)); uvec4 d = rain_cells[rain_drop_index(ivec2(nc))]; - if (rain_byte(d.y, 24u) > actMax) - continue; float vis = float(d.w >> 24) * (1.0 / 255.0); - if (vis <= 0.001) - continue; float spreadF = mix(0.8, 1.0, float((d.y >> 19) & 31u) * (1.0 / 31.0)); // a drop the blades miss: the same drop before and after the stroke, left where it is bool missed = ((d.w >> 19) & 1u) != 0u; @@ -750,7 +745,7 @@ void main() if (sweepOn) { vec2 cg = vec2(center.x, (STREAK_FLIP_Y != 0) ? 1.0 - center.y : center.y); - vis *= wsKept(cg, 0.35 * sq, rivP, sCell, sCW, sCH, gridSize); + vis *= wsKept(cg, 0.35 * sq, sCW, sCH, gridSize); } if (vis <= 0.001) continue; @@ -809,7 +804,7 @@ void main() { vec2 cu = c / mg; vec2 cg = vec2(cu.x, (STREAK_FLIP_Y != 0) ? 1.0 - cu.y : cu.y); - vis *= wsKept(cg, r / mg, rivP, sCell, sCW, sCH, gridSize); + vis *= wsKept(cg, r / mg, sCW, sCH, gridSize); } float d = sqrt(d2); float cov = smoothstep(1.0, 0.8, d) * vis; @@ -835,7 +830,7 @@ void main() // =================================================================== #if WS_PROFILE != 2 wsSetLayer(0); - drawRivulet(hit, rivP, sUVg, wsRd1, wsRd2); + drawRivulet(hit, getRiv(sCell, sCW, sCH, gridSize), sUVg, wsRd1, wsRd2); if (wsWindShare > 0.001) { for (int wl = 1; wl <= wind_layers; ++wl) @@ -852,6 +847,21 @@ void main() #endif } + // ---- the frame of the glass, the change of the view and the lens, for the shading (uniform flow again) ---- + vec2 sxy = f_pos.xy / max(-f_pos.z, 1e-3); + float pxPerSlope = 1.0 / max(max(length(dFdx(sxy)), length(dFdy(sxy))), 1e-6); + vec3 wsView = normalize(f_pos.xyz); // the view through the glass and its change per pixel (for the bent view) + vec3 wsDvx = dFdx(wsView); + vec3 wsDvy = dFdy(wsView); + vec3 dp1 = dFdx(f_pos.xyz); + vec3 dp2 = dFdy(f_pos.xyz); + vec3 Tgl, Bgl; + wsGlassFrame(Ngl, duv1, duv2, Tgl, Bgl); + // glass UV offset -> screen pixels (inverse of the UV Jacobian), for the drop lens + mat2 Juv = mat2(duv1, duv2); + float detJ = determinant(Juv); + mat2 Jinv = (abs(detJ) > 1e-20) ? inverse(Juv) : mat2(0.0); + // ----------------------------------------------------------------------- // Shading of the winning dome // ----------------------------------------------------------------------- diff --git a/shaders/vk14/rain_cells.comp b/shaders/vk14/rain_cells.comp index c8ca2af4b..780addf0e 100644 --- a/shaders/vk14/rain_cells.comp +++ b/shaders/vk14/rain_cells.comp @@ -1,15 +1,18 @@ #version 460 core #define STAGE_COMPUTE 1 // the cells of the glasses with rain (rain_cells.glsl): the drops and the rivulets of every cell worked out for the time of the -// frame, a thread a cell, before the passes which draw the glasses (mat_rain_windscreen.frag only reads them) +// frame, a thread a cell, before the passes which draw the glasses (mat_rain_windscreen.frag only reads them). two passes: the +// cells (rain_pass 0), then which drops reach the quarters of each drop cell (rain_pass 1, it reads the first) -// none of the pass set: the cells pushed with the dispatch (set COMPUTE_SET), the time in the push constants +// none of the pass set: the cells pushed with the dispatch (set COMPUTE_SET), the time and the pass in the push constants #define LAYOUT_UI 1 #include "common.glsl" layout(push_constant) uniform kernel_constants { - float rain_time; // the time of the block of the scene (scene_ubs.time) + float rain_time; // the time of the block of the scene (scene_ubs.time) + float rain_amount; // how hard it rains (scene_ubs.rain_params.x) + int rain_pass; // 0 the cells, 1 the reach of the drops }; #include "random.glsl" @@ -65,7 +68,7 @@ uvec4 drop_cell(ivec2 Cell) float choice = RandF(s2); float stretch = RandF(s2); uint tile = min(uint(choice * 4.0), 3u); - uint a = q8(thr) | (q8(cx) << 8) | (q8(cy) << 16) | (q8(size) << 24); + uint a = q8(thr) | (q8(cx) << 8) | (q8(cy) << 16) | (q8(pow(size, drop_size_bias)) << 24); uint b = q8(sag) | (q8(stretch) << 8) | ((flip < 0.5) ? (1u << 16) : 0u) | (tile << 17); if (side == 0u) { @@ -113,10 +116,64 @@ uvec4 rivulet_cell(int Layer, ivec2 Cell) return result; } +// how far from the centre (in cells) the drop of side half A, B of a cell can reach at most: half its size, the sag, the stretch of the +// air at its strongest, any way it is turned +float drop_reach(uint A, uint B, float Spread) +{ + float half_size = 0.5 * mix(drop_size_min, drop_size_max, rain_byte(A, 24u)) * Spread; + float sag = 1.0 + drop_sag * rain_byte(B, 0u); + float stretch = 1.0 + drop_wind_stretch * rain_byte(B, 8u); + return half_size * sqrt(1.0 + sag * sag) * stretch * 1.01; +} + +// the reach of the drops around a drop cell into its quarters (rain_cells.glsl), from the cells worked out by the first pass +uvec4 drop_masks(ivec2 Cell) +{ + uvec4 result = uvec4(0u); + float most = min(rain_amount * drop_density, 0.95); + for (int dy = -1; dy <= 1; ++dy) + for (int dx = -1; dx <= 1; ++dx) + { + uvec4 d = rain_cells[rain_drop_index(Cell + ivec2(dx, dy))]; + if ((rain_byte(d.y, 24u) > most) || ((d.w >> 24) == 0u)) + continue; + float spread = mix(0.8, 1.0, float((d.y >> 19) & 31u) * (1.0 / 31.0)); + bool missed = ((d.w >> 19) & 1u) != 0u; + uint bit = 1u << uint((dy + 1) * 3 + dx + 1); + for (uint side = 0u; side < 2u; ++side) + { + if ((side == 1u) && missed) + break; + uint a = (side == 0u) ? d.x : d.z; + uint b = (side == 0u) ? d.y : d.w; + vec2 centre = vec2(dx, dy) + vec2(rain_byte(a, 8u), rain_byte(a, 16u)); + float reach = drop_reach(a, b, spread); + for (uint q = 0u; q < 4u; ++q) + { + vec2 low = vec2(float(q & 1u), float(q >> 1)) * 0.5; + vec2 away = max(max(low - centre, centre - (low + 0.5)), vec2(0.0)); + if (dot(away, away) < reach * reach) + result[q] |= bit; + } + } + } + return result; +} + void main() { uint index = gl_GlobalInvocationID.x; - if (index >= uint(RAIN_CELLS_COUNT)) + if (rain_pass == 1) + { + // the second pass: the reach of the drops, a thread a drop cell + if (index >= uint(RAIN_DROP_CELLS * RAIN_DROP_CELLS)) + return; + ivec2 texel = ivec2(int(index % uint(RAIN_DROP_CELLS)), int(index / uint(RAIN_DROP_CELLS))); + ivec2 cell = ivec2(texel.x == RAIN_DROP_CELLS - 1 ? -1 : texel.x, texel.y == RAIN_DROP_CELLS - 1 ? -1 : texel.y); + rain_cells[uint(RAIN_MASK_BASE) + index] = drop_masks(cell); + return; + } + if (index >= uint(RAIN_MASK_BASE)) return; if (index < uint(RAIN_RIV_BASE)) { diff --git a/shaders/vk14/rain_cells.glsl b/shaders/vk14/rain_cells.glsl index e61cfe4f6..0629492e2 100644 --- a/shaders/vk14/rain_cells.glsl +++ b/shaders/vk14/rain_cells.glsl @@ -7,11 +7,14 @@ // a cell is one uvec4. the drops: RAIN_DROP_CELLS x RAIN_DROP_CELLS cells, cell c of the grid in element (c.y & 511) * 512 + // (c.x & 511), whole for the cells -1 .. 510 (grids up to 510 cells; finer ones repeat their drops every 512 cells): // x side 0 (the drop of a cell the blades went over on their way out): bits 0-7 the threshold the wipers have to be past for -// it, 8-15 / 16-23 the place in the cell (x, y), 24-31 the random of its size +// it, 8-15 / 16-23 the place in the cell (x, y), 24-31 its size (0 .. 1 from drop_size_min to drop_size_max) // y side 0: bits 0-7 the random of its sag, 8-15 of its stretch by the air, 16 mirrored, 17-18 the tile of the atlas, // 19-23 how far it spread out landing (0 .. 31), 24-31 the random a cell holds a drop by (a drop when below the share) // z side 1 (the blades on their way back): as x // w side 1: as y, bit 19 set when the blades miss the drop, bits 24-31 its visibility in its life (0 .. 255) +// the reach of the drops: for every drop cell (element RAIN_MASK_BASE + the index of the drop cell) the drops of the 9 cells around +// it (bit (dy + 1) * 3 + dx + 1) which reach into each quarter of it (x the lower left, y the lower right, z the upper left, w the +// upper right), with the drops the cells hold now in the rain there is now (a glass only looks at those) // the rivulets: RAIN_RIV_LAYERS layers (0 gravity, 1 .. 4 the air) of RAIN_RIV_CELLS x RAIN_RIV_CELLS cells, cell c in element // RAIN_RIV_BASE + layer * 128 * 128 + (c.y & 127) * 128 + (c.x & 127), whole for the cells -32 .. 95: // x bits 0-15 the random the cell holds a rivulet by, 16-23 its life (0 .. 255), 24-31 the random of the wipers it stays under @@ -26,11 +29,12 @@ #define RAIN_RIV_CELLS 128 #define RAIN_RIV_LAYERS 5 #define RAIN_RIV_BASE (RAIN_DROP_CELLS * RAIN_DROP_CELLS) -#define RAIN_CELLS_COUNT (RAIN_RIV_BASE + RAIN_RIV_LAYERS * RAIN_RIV_CELLS * RAIN_RIV_CELLS) +#define RAIN_MASK_BASE (RAIN_RIV_BASE + RAIN_RIV_LAYERS * RAIN_RIV_CELLS * RAIN_RIV_CELLS) +#define RAIN_CELLS_COUNT (RAIN_MASK_BASE + RAIN_DROP_CELLS * RAIN_DROP_CELLS) #define RAIN_CELLS_GROUP_SIZE 64 #if defined(STAGE_COMPUTE) -layout(std430, set = COMPUTE_SET, binding = 0) writeonly buffer rain_cells_ssbo +layout(std430, set = COMPUTE_SET, binding = 0) buffer rain_cells_ssbo #else layout(std430, set = PASS_SET, binding = RAIN_CELLS_SSBO) readonly buffer rain_cells_ssbo #endif @@ -38,7 +42,13 @@ layout(std430, set = PASS_SET, binding = RAIN_CELLS_SSBO) readonly buffer rain_c uvec4 rain_cells[]; }; -// the life of the drops and of the rivulets (the settings of mat_rain_windscreen.frag which the cells are worked out with) +// the drops and the rivulets (the settings of mat_rain_windscreen.frag which the cells are worked out with) +const float drop_density = 0.6; // share of grid cells holding a drop at full rain (scaled by rain intensity) +const float drop_size_min = 0.45; // drop size in grid cells +const float drop_size_max = 1.15; +const float drop_size_bias = 1.8; // >1 = more small/medium drops, fewer big ones +const float drop_sag = 0.12; // max vertical stretch of a resting drop (gravity) +const float drop_wind_stretch = 0.4; // drops are stretched up to this much along the push of the air (0 = off) const float drop_life_min = 14.0; // seconds a drop sits on the glass const float drop_life_max = 45.0; const float drop_appear = 0.18; // seconds of the landing "pop" @@ -58,6 +68,11 @@ uint rain_drop_index(ivec2 Cell) return uint(Cell.y & (RAIN_DROP_CELLS - 1)) * uint(RAIN_DROP_CELLS) + uint(Cell.x & (RAIN_DROP_CELLS - 1)); } +uint rain_mask_index(ivec2 Cell) +{ + return uint(RAIN_MASK_BASE) + rain_drop_index(Cell); +} + uint rain_riv_index(int Layer, ivec2 Cell) { return uint(RAIN_RIV_BASE) + uint(Layer) * uint(RAIN_RIV_CELLS * RAIN_RIV_CELLS) + uint(Cell.y & (RAIN_RIV_CELLS - 1)) * uint(RAIN_RIV_CELLS) From 77e4abadaeb2435fdba4d19a9102cce52659b3c4 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 18:42:07 +0100 Subject: [PATCH 053/123] Rain: the cab in the depth prepass also in the rain In the rain the cab is drawn after the precipitation (so the rain inside it is hidden), and it was left out of the depth prepass too, so the opaque pass shaded everything behind it. Its depth now goes into the prepass in any weather (Vulkan 1.4, and OpenGL 4.6 without gfx.depthprepass.replay); the colour of the cab is still drawn after the rain, so nothing changes in the picture. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- rendering/opengl46/opengl46renderer.cpp | 5 +++-- rendering/vulkan14/vulkan14frame.cpp | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index 99f2f45a1..3da55b6a7 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -4368,8 +4368,9 @@ void opengl46_renderer::Render_Scene_Depth( glm::mat4 const &Future, bool const m_scenerecordedparts = static_cast( m_scenechunks.size() ); } else { - // the conditions of the cab drawn early by the colour pass - if( ( false == FreeFlyModeFlag ) && ( Global.Overcast <= 1.0f ) && ( Global.render_cab ) ) { + // the cab first, also in the rain: the colour pass draws it after the rain then (the rain inside it hidden), but with its depth + // here nothing the cab hides is shaded by the opaque pass + if( ( false == FreeFlyModeFlag ) && ( Global.render_cab ) ) { model_ubs.future = m_cabfuture; auto const *vehicle { simulation::Train->Dynamic() }; Render_cab( vehicle, vehicle->InteriorLightLevel, false ); diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index 30c56a2a2..26b494e37 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -1991,8 +1991,9 @@ void vulkan14_renderer::render_scene_depth(std::size_t const Index, glm::mat4 co auto const colourstats{m_renderpass.draw_stats}; m_renderpass.draw_stats = {}; walk_blending(false); - // the conditions of the cab drawn early by the colour pass - if ((false == FreeFlyModeFlag) && (Global.Overcast <= 1.0f) && Global.render_cab && simulation::Train) + // the cab first, also in the rain: the colour pass draws it after the rain then (the rain inside it hidden), but with its depth here + // nothing the cab hides is shaded by the opaque pass (in a station seen from the cab: about a third of the time of the opaque pass) + if ((false == FreeFlyModeFlag) && Global.render_cab && simulation::Train) { model_ubs.future = m_cabfuture; auto const *vehicle{simulation::Train->Dynamic()}; From d8f0c46c7f321e676c0ecdbe1fad194699666a4b Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Sun, 8 Nov 2026 22:23:17 +0100 Subject: [PATCH 054/123] Sun shadows of the gpu culling: the replayed walks keep the parameters of the materials A walk kept from an earlier frame (gfx.gpucull.walkcache) gave the draws of the shadows the parameters the pass had at the moment, not those of their materials. mat_vat.vert reads vat_speed from them in the shadow too, so the shadows of the animals and people animated by textures stood still on Vulkan with gfx.gpucull.shadows. The common shadow programs read none of them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GXgG7F4L42c2F9sDSAJbT2 --- rendering/common/scenewalkindirect.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/rendering/common/scenewalkindirect.cpp b/rendering/common/scenewalkindirect.cpp index e65606827..4953e3c8d 100644 --- a/rendering/common/scenewalkindirect.cpp +++ b/rendering/common/scenewalkindirect.cpp @@ -866,9 +866,11 @@ void scene_walk::Replay_Walk(walk_band const &Walk, bool const Shadows) draw.ubs = model_ubs; draw.ubs.modelview = walked.modelview; draw.ubs.modelviewnormal = walked.modelviewnormal; + // the parameters of the material go with the shadows too: a material which moves its vertices in a vertex shader of its own + // reads them there (vat_speed of mat_vat.vert, without which its shadow stands still); the common shadow programs don't + std::memcpy(&draw.ubs.param[0], &walked.param[0], sizeof(draw.ubs.param)); if (false == Shadows) { - std::memcpy(&draw.ubs.param[0], &walked.param[0], sizeof(draw.ubs.param)); draw.ubs.opacity = walked.opacity; draw.ubs.alpha_mult = walked.alpha_mult; } From 8050ea8eb66559337698d5cdf90a5af8a28e32bb Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Tue, 10 Nov 2026 22:44:22 +0100 Subject: [PATCH 055/123] Deer at the tracks: graze ahead of the train, take fright at the horn and bound away A deer is put on the path the player's train goes along (world/deer.cpp), grazing. The horn within deer.hornrange, or the train closer than deer.fleedistance, frightens it: it raises its head, looks at the train and bounds away from the tracks, then grazes where it stopped. The deer go once the train is past them; they aren't parts of the scenery (not saved, not edited). Off unless eu07.ini turns it on: deer (no), deer.interval (2000 m), deer.distance (2000 m), deer.chance (1), deer.hornrange (600 m), deer.fleedistance (150 m). - mat_vat.vert (ogl46, vk14): vat_random -1, the game picks the clip and the moment of an instance by the fraction of ten times its turn about the vertical, so one animation hands over to the next in the very same pose. 0 and 1 work as before. - TAnimModel::draw_alone(): an instance the game moves leaves the groups of its model. - scene_walk::Queue_Model: the record of an instance drawn on its own is made anew when the instance moved. Assets (game data, installed locally in the game folder, not yet in the SVN; without them no deer is made): - models/animals/jelen_je.t3d, jelen_zryw.t3d, jelen_skok.t3d (the deer of jelen_lewo.t3d with the head turned straight, three animations baked by jelen_anim2.py) - textures/animals/jelen_{je,zryw,skok}.mat and their _vatpos_hi, _vatpos_lo, _vatnormal .tga; diffuse animals/sarna_d_1, in winter animals/sarna_f_1 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GXgG7F4L42c2F9sDSAJbT2 --- CMakeLists.txt | 1 + application/drivermode.cpp | 13 +- model/AnimModel.cpp | 9 + model/AnimModel.h | 3 + rendering/common/scenewalkindirect.cpp | 4 +- shaders/ogl46/mat_vat.vert | 18 +- shaders/vk14/mat_vat.vert | 18 +- utilities/Globals.cpp | 12 + utilities/Globals.h | 8 + world/deer.cpp | 502 +++++++++++++++++++++++++ world/deer.h | 86 +++++ 11 files changed, 657 insertions(+), 17 deletions(-) create mode 100644 world/deer.cpp create mode 100644 world/deer.h diff --git a/CMakeLists.txt b/CMakeLists.txt index a881961db..1cb60396c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -187,6 +187,7 @@ set(SOURCES "vehicle/cab/train.cpp" "vehicle/cab/update.cpp" "world/TrkFoll.cpp" +"world/deer.cpp" "vehicle/AirCoupler.cpp" "model/AnimModel.cpp" "vehicle/Button.cpp" diff --git a/application/drivermode.cpp b/application/drivermode.cpp index 3b132cb60..f36656226 100644 --- a/application/drivermode.cpp +++ b/application/drivermode.cpp @@ -27,6 +27,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/DynObj.h" #include "model/Model3d.h" #include "world/Event.h" +#include "world/deer.h" #include "input/messaging.h" #include "utilities/Timer.h" #include "rendering/renderer.h" @@ -347,17 +348,7 @@ bool driver_mode::update() Timer::subsystem.sim_lights.start(); simulation::Lights.update(); Timer::subsystem.sim_lights.stop(); - { - // where the user looks from, for the black box - auto const &camera{DebugCameraFlag ? DebugCamera : Camera}; - auto const mode{DebugCameraFlag ? blackbox::camera_modes::debug : - false == FreeFlyModeFlag ? blackbox::camera_modes::cab : - m_externalview ? blackbox::camera_modes::external : - blackbox::camera_modes::free}; - simulation::Blackbox.camera(blackbox_camera(camera, mode, mode == blackbox::camera_modes::external ? m_externalviewmode : 0), - DebugCameraFlag ? nullptr : camera.m_owner); - } - simulation::Blackbox.update(deltatime); + simulation::Deer.update(deltatime); if (Global.test.enabled && simulation::is_ready) { diff --git a/model/AnimModel.cpp b/model/AnimModel.cpp index 5f538cdd8..42fea67cf 100644 --- a/model/AnimModel.cpp +++ b/model/AnimModel.cpp @@ -571,6 +571,15 @@ void TAnimModel::update_instanceable_flag() { ++s_instanceable_total; } +void TAnimModel::draw_alone() { + + if( m_instanceable ) { + ++s_instanceable_revoked; + m_instanceable = false; + ++scene::node_state_version; + } +} + std::shared_ptr TAnimModel::AddContainer(std::string const &Name) { // dodanie sterowania submodelem dla egzemplarza if (!pModel) diff --git a/model/AnimModel.h b/model/AnimModel.h index 8650165ba..d4e971615 100644 --- a/model/AnimModel.h +++ b/model/AnimModel.h @@ -126,6 +126,9 @@ public: // Angles, Scale: content of the optional blocks of the definition, nullptr for a block which isn't there void Load( std::string const &Name, std::string const &Texture, TAnimModel const *Twin, glm::vec3 const *Angles, glm::vec3 const *Scale, bool const Transition ); std::shared_ptr AddContainer(std::string const &Name); + // the instance drawn on its own from now on, not with the others of its model: one the game moves (the deer at the tracks), + // whose place the renderer takes anew in every frame + void draw_alone(); std::shared_ptr GetContainer(std::string const &Name = ""); void LightSet( int const n, float const v ); void SkinSet( int const Index, material_handle const Material ); diff --git a/rendering/common/scenewalkindirect.cpp b/rendering/common/scenewalkindirect.cpp index 4953e3c8d..661986bec 100644 --- a/rendering/common/scenewalkindirect.cpp +++ b/rendering/common/scenewalkindirect.cpp @@ -283,10 +283,10 @@ bool scene_walk::Queue_Model(TAnimModel *Instance, bool const Inrange) auto &records{m_modelrecords[Instance]}; auto &bucket{records.bucket}; - if ((bucket.recordsversion != m_instancerecordsversion) || (bucket.records.size() != 1)) + if ((bucket.recordsversion != m_instancerecordsversion) || (bucket.records.size() != 1) || (records.area.center != Instance->location())) { // the key, the instance and the record anew: the editor may have given the instance another model or skins, or - // another instance may have taken the place of a deleted one + // another instance may have taken the place of a deleted one, or the game moved it (world/deer.cpp) auto &key{records.key}; key = {}; key.pModel = Instance->Model(); diff --git a/shaders/ogl46/mat_vat.vert b/shaders/ogl46/mat_vat.vert index a06143220..aacf58bdd 100644 --- a/shaders/ogl46/mat_vat.vert +++ b/shaders/ogl46/mat_vat.vert @@ -19,6 +19,9 @@ // right after another (vertex Frame * Vertices + Vertex of the whole image, row by row), else each in its own rows // the textures go with the trait r (texture_vatpos_hi: name:r), which keeps them as they are (never scaled down nor compressed) // param vat_speed (1 if not given): how fast the animation plays +// param vat_random (1 if not given): 1 every model its own moment from its place; 0 the moment of the clock alone, for a model the game +// moves (its place changes the whole time, the moment taken from it would jump); -1 the game picks the clip and the moment, by the +// fraction of ten times the turn of the model about the vertical in degrees: (clip + 0.25 + 0.5 * moment) / clips (world/deer.cpp) layout(location = 0) in vec3 v_vert; layout(location = 1) in vec3 v_normal; layout(location = 2) in vec2 v_coord; @@ -31,6 +34,7 @@ layout(location = 4) in vec4 v_userdata; #pragma texture(vatpos_lo, 2, RGBA) #pragma texture(vatnormal, 3, RGBA) #pragma param(vat_speed, 2, 0, 1, one) +#pragma param(vat_random, 2, 1, 1, one) layout(binding = 1) uniform sampler2D vatpos_hi; layout(binding = 2) uniform sampler2D vatpos_lo; layout(binding = 3) uniform sampler2D vatnormal; @@ -143,8 +147,18 @@ void vat_animate(mat4 mv, out vec3 position, out vec3 normal) int bin = int(mod(floor(yaw * 0.5 + 0.315), 180.0)); uint seed = uint(cell.x) * 73856093u ^ uint(cell.y) * 19349663u ^ uint(cell.z) * 83492791u ^ uint(bin) * 2654435761u; seed ^= seed >> 16; seed *= 0x7feb352du; seed ^= seed >> 15; seed *= 0x846ca68bu; seed ^= seed >> 16; - float phase = float(seed & 0xffffu) / 65536.0; - float pick = float(seed >> 16) / 65536.0; + float random = clamp(param[2].y, 0.0, 1.0); + float phase = random * float(seed & 0xffffu) / 65536.0; + float pick = random * float(seed >> 16) / 65536.0; + if (param[2].y < -0.5) + { + // picked by the game: the fraction of the turn in tenths of a degree (the turn is -yaw), a quarter of a clip's span kept + // clear of its edges + float spin = fract(-yaw * 10.0) * float(h.clips); + float slot = floor(spin); + pick = (slot + 0.5) / float(h.clips); + phase = clamp((spin - slot - 0.25) * 2.0, 0.0, 1.0); + } int clipframes = max(h.frames / h.clips, 1); int clip = min(int(pick * float(h.clips)), h.clips - 1); float t = (time * h.fps * max(param[2].x, 0.0)) + phase * float(clipframes); diff --git a/shaders/vk14/mat_vat.vert b/shaders/vk14/mat_vat.vert index d830b93c1..e3e2fd662 100644 --- a/shaders/vk14/mat_vat.vert +++ b/shaders/vk14/mat_vat.vert @@ -21,6 +21,9 @@ // right after another (vertex Frame * Vertices + Vertex of the whole image, row by row), else each in its own rows // the textures go with the trait r (texture_vatpos_hi: name:r), which keeps them as they are (never scaled down nor compressed) // param vat_speed (1 if not given): how fast the animation plays +// param vat_random (1 if not given): 1 every model its own moment from its place; 0 the moment of the clock alone, for a model the game +// moves (its place changes the whole time, the moment taken from it would jump); -1 the game picks the clip and the moment, by the +// fraction of ten times the turn of the model about the vertical in degrees: (clip + 0.25 + 0.5 * moment) / clips (world/deer.cpp) layout(location = 0) in vec3 v_vert; layout(location = 1) in vec3 v_normal; layout(location = 2) in vec2 v_coord; @@ -31,6 +34,7 @@ layout(location = 4) in vec4 v_userdata; #pragma texture(vatpos_lo, 2, RGBA) #pragma texture(vatnormal, 3, RGBA) #pragma param(vat_speed, 2, 0, 1, one) +#pragma param(vat_random, 2, 1, 1, one) layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 1) uniform sampler2D vatpos_hi; layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 2) uniform sampler2D vatpos_lo; layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 3) uniform sampler2D vatnormal; @@ -143,8 +147,18 @@ void vat_animate(mat4 mv, out vec3 position, out vec3 normal) int bin = int(mod(floor(yaw * 0.5 + 0.315), 180.0)); uint seed = uint(cell.x) * 73856093u ^ uint(cell.y) * 19349663u ^ uint(cell.z) * 83492791u ^ uint(bin) * 2654435761u; seed ^= seed >> 16; seed *= 0x7feb352du; seed ^= seed >> 15; seed *= 0x846ca68bu; seed ^= seed >> 16; - float phase = float(seed & 0xffffu) / 65536.0; - float pick = float(seed >> 16) / 65536.0; + float random = clamp(param[2].y, 0.0, 1.0); + float phase = random * float(seed & 0xffffu) / 65536.0; + float pick = random * float(seed >> 16) / 65536.0; + if (param[2].y < -0.5) + { + // picked by the game: the fraction of the turn in tenths of a degree (the turn is -yaw), a quarter of a clip's span kept + // clear of its edges + float spin = fract(-yaw * 10.0) * float(h.clips); + float slot = floor(spin); + pick = (slot + 0.5) / float(h.clips); + phase = clamp((spin - slot - 0.25) * 2.0, 0.0, 1.0); + } int clipframes = max(h.frames / h.clips, 1); int clip = min(int(pick * float(h.clips)), h.clips - 1); float t = (time * h.fps * max(param[2].x, 0.0)) + phase * float(clipframes); diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index bd6bf9001..10a7ae425 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -2279,6 +2279,12 @@ global_settings::ConfigParse_gfx_sky( cParser &Parser, std::string_view const To else if( Token == "moths.share" ) { readvalue( moths_share, 0.f, 1.f ); } else if( Token == "moths.range" ) { readvalue( moths_range, 0.f, 500.f ); } else if( Token == "moths.temperature" ) { readvalue( moths_temperature, -50.f, 50.f ); } + else if( Token == "deer" ) { readswitch( deer ); } + else if( Token == "deer.interval" ) { readvalue( deer_interval, 0.0f, 100000.0f ); } + else if( Token == "deer.distance" ) { readvalue( deer_distance, 100.0f, 10000.0f ); } + else if( Token == "deer.chance" ) { readvalue( deer_chance, 0.0f, 1.0f ); } + else if( Token == "deer.hornrange" ) { readvalue( deer_hornrange, 0.0f, 5000.0f ); } + else if( Token == "deer.fleedistance" ) { readvalue( deer_fleedistance, 0.0f, 1000.0f ); } else if( Token == "gfx.lights.shadows" ) { // no/low/medium/high, or the number of the level Parser.getTokens( 1 ); @@ -2856,6 +2862,12 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "moths.share", moths_share ); export_as_text( Output, "moths.range", moths_range ); export_as_text( Output, "moths.temperature", moths_temperature ); + export_as_text( Output, "deer", deer ); + export_as_text( Output, "deer.interval", deer_interval ); + export_as_text( Output, "deer.distance", deer_distance ); + export_as_text( Output, "deer.chance", deer_chance ); + export_as_text( Output, "deer.hornrange", deer_hornrange ); + export_as_text( Output, "deer.fleedistance", deer_fleedistance ); export_as_text( Output, "gfx.lights.shadows", std::string{ gfx_lights_shadows == 3 ? "high" : gfx_lights_shadows == 2 ? "medium" : gfx_lights_shadows == 1 ? "low" : "no" } ); export_as_text( Output, "gfx.lights.shadows.cab", gfx_lights_shadows_cab ); export_as_text( Output, "gfx.lights.shadows.lamps", gfx_lights_shadows_lamps ); diff --git a/utilities/Globals.h b/utilities/Globals.h index bf9de1472..5342e7079 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -653,6 +653,14 @@ struct global_settings { float moths_share { 0.4f }; // part of the lamps with a swarm, 0-1 float moths_range { 80.f }; // distance from the camera the swarms are shown at, metres float moths_temperature { 8.f }; // the lowest temperature of the air moths fly at, degrees Celsius + // deer at the tracks (world/deer.cpp): put on the path ahead of the train of the player, grazing, they run away from the horn + // or the train coming close. off unless turned on + bool deer { false }; + float deer_interval { 2000.0f }; // metres the train covers between the deer, 0 none + float deer_distance { 2000.0f }; // metres ahead of the train a deer is put at + float deer_chance { 1.0f }; // of a deer at each interval, 0-1 + float deer_hornrange { 600.0f }; // the horn sends away the deer within this many metres + float deer_fleedistance { 150.0f }; // a deer runs away from the train come this close, metres // shadows of the lamps (cube shadow maps), 0 none, 1 low, 2 medium, 3 high; see opengl46_local_shadows. for now the lamp of the // occupied cab, its shadows cast by the cab int gfx_lights_shadows { 2 }; diff --git a/world/deer.cpp b/world/deer.cpp new file mode 100644 index 000000000..e6c3749be --- /dev/null +++ b/world/deer.cpp @@ -0,0 +1,502 @@ +/* +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 "world/deer.h" +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/utilities.h" +#include "model/AnimModel.h" +#include "scene/scene.h" +#include "scene/scenenode.h" +#include "scene/scenelayers.h" +#include "simulation/simulation.h" +#include "rendering/renderer.h" +#include "vehicle/DynObj.h" +#include "McZapkie/MOVER.h" +#include "world/Track.h" +#include "utilities/Timer.h" + +namespace +{ + +// the animations of the deer (textures of the vertices, shader vat with vat_random -1: the game picks the clip and the moment of every +// instance, see vat_turn()). made by jelen_anim2.py; the numbers below are the ones it bakes with +struct vat_clip +{ + std::string_view model; // models/ and the extension left out + double fps; // frames a second + double frames; // of one clip + int clips; +}; +// grazing, 12 s: the head at the grass, raised about 4.5-9.3 s +constexpr vat_clip Grazing{"animals/jelen_je", 20.0, 240.0, 1}; +// startled: from the moments k * Window of the grazing (clip k) to the alarm, in Startletime; two more frames hold the end +constexpr vat_clip Startle{"animals/jelen_zryw", 30.0, 15.0, 16}; +// the flight from the alarm: looks at the train (clip 0 to the left, 1 to the right), bounds away and stops in the grazing pose of the +// moment Grazeafter, in Flighttime; two more frames hold the end +constexpr vat_clip Flight{"animals/jelen_skok", 30.0, 168.0, 2}; +constexpr double Window{0.75}; +constexpr double Startletime{0.4}; +constexpr double Flighttime{5.5}; +constexpr double Grazeafter{5.6}; +// the way it covers in the flight: the speed rises from 0 to Flightspeed in Flight0-Flight1 and falls back in Flight2-Flight3 +// (smoothstep), as the animation moves its hooves +constexpr double Flightspeed{7.0}; +constexpr double Flight0{0.80}; +constexpr double Flight1{1.20}; +constexpr double Flight2{3.95}; +constexpr double Flight3{4.85}; +// the frame an instance starts from at the moment of the change, a little after the frame proper: never the end of the one before +constexpr double Startframe{0.02}; +// the ground under the way of the deer is looked for up to this much above the place it starts from, metres +constexpr double Groundceiling{3.0}; +// the train past the deer: it came this close, and is this much farther away now, metres +constexpr double Passedclose{300.0}; +constexpr double Passedmargin{200.0}; + +double fraction(double const Value) +{ + return Value - std::floor(Value); +} + +// the integral of smoothstep((T - A) / (B - A)) from minus infinity to T +double ramp_integral(double const T, double const A, double const B) +{ + if (T <= A) + { + return 0.0; + } + if (T >= B) + { + return (B - A) * 0.5 + (T - B); + } + auto const x{(T - A) / (B - A)}; + return (B - A) * (x * x * x - 0.5 * x * x * x * x); +} + +// metres covered in the flight Time seconds after its start +double flight_way(double const Time) +{ + return Flightspeed * (ramp_integral(Time, Flight0, Flight1) - ramp_integral(Time, Flight2, Flight3)); +} + +// the height of the triangle at (X, Z), false when the point isn't in it +bool triangle_height(glm::dvec3 const &A, glm::dvec3 const &B, glm::dvec3 const &C, double const X, double const Z, double &Height) +{ + auto const d{(B.z - C.z) * (A.x - C.x) + (C.x - B.x) * (A.z - C.z)}; + if (std::abs(d) < 1e-9) + { + return false; + } + auto const a{((B.z - C.z) * (X - C.x) + (C.x - B.x) * (Z - C.z)) / d}; + auto const b{((C.z - A.z) * (X - C.x) + (A.x - C.x) * (Z - C.z)) / d}; + auto const c{1.0 - a - b}; + if ((a < 0.0) || (b < 0.0) || (c < 0.0)) + { + return false; + } + Height = a * A.y + b * B.y + c * C.y; + return true; +} + +// what's looked for under a point: its place, the highest ground found so far +struct ground_probe +{ + glm::dvec3 point{0.0}; + double ceiling{0.0}; + bool found{false}; + double height{0.0}; + + void triangle(glm::dvec3 const &A, glm::dvec3 const &B, glm::dvec3 const &C) + { + if (double y{0.0}; triangle_height(A, B, C, point.x, point.z, y) && (y <= ceiling) && ((false == found) || (y > height))) + { + found = true; + height = y; + } + } + + void geometry(gfx::vertex_array const &Vertices, gfx::index_array const &Indices, glm::dvec3 const &Origin) + { + auto const vertex{[&Vertices, &Origin](std::size_t const Index) { return Origin + glm::dvec3{Vertices[Index].position}; }}; + if (Indices.empty()) + { + for (std::size_t index = 0; index + 2 < Vertices.size(); index += 3) + { + triangle(vertex(index), vertex(index + 1), vertex(index + 2)); + } + return; + } + for (std::size_t index = 0; index + 2 < Indices.size(); index += 3) + { + triangle(vertex(Indices[index]), vertex(Indices[index + 1]), vertex(Indices[index + 2])); + } + } + + void shape(scene::shape_node const &Shape) + { + auto const &data{Shape.data()}; + if ((data.area.radius >= 0.f) && (glm::length(glm::dvec2{data.area.center.x - point.x, data.area.center.z - point.z}) > data.area.radius)) + { + return; + } + if (false == data.vertices.empty()) + { + for (std::size_t index = 0; index + 2 < data.vertices.size(); index += 3) + { + triangle(data.vertices[index].position, data.vertices[index + 1].position, data.vertices[index + 2].position); + } + return; + } + // uploaded, the renderer keeps the geometry relative to the origin of the shape + if ((GfxRenderer == nullptr) || ((data.geometry.bank == 0) && (data.geometry.chunk == 0))) + { + return; + } + geometry(GfxRenderer->Vertices(data.geometry), GfxRenderer->Indices(data.geometry), data.origin); + } +}; + +// the height of the ground of the scenery (its shapes: the terrain) under the point, not higher than Ceiling. false where there's +// none: the ground of terrain models, or none loaded +bool ground_height(glm::dvec3 const &Point, double const Ceiling, double &Height) +{ + if (simulation::Region == nullptr) + { + return false; + } + ground_probe probe; + probe.point = Point; + probe.ceiling = Ceiling; + for (auto *section : simulation::Region->sections(Point, 1.f)) + { + for (auto const &shape : section->m_shapes) + { + probe.shape(shape); + } + for (auto const &cell : section->m_cells) + { + if (glm::length(glm::dvec2{cell.m_area.center.x - Point.x, cell.m_area.center.z - Point.z}) > cell.m_area.radius) + { + continue; + } + for (auto const &shape : cell.m_shapesopaque) + { + probe.shape(shape); + } + } + } + Height = probe.height; + return probe.found; +} + +// a place on a path: the point of its axis and the way along it, level, of length 1 +struct path_place +{ + glm::dvec3 position{0.0}; + glm::dvec3 forward{0.0, 0.0, 1.0}; +}; + +// the place Distance from Track at Offset along it, going the way of Direction (1 towards its end, -1 towards its start), through the +// connected paths. false where the paths end earlier (or reach a crossing of roads) +bool path_ahead(TTrack *Track, double Offset, double Direction, double Distance, path_place &Place) +{ + auto *track{Track}; + auto left{Distance}; + // as far as a train could go; a loop of paths ends it as well + for (int step = 0; (step < 10000) && (track != nullptr); ++step) + { + auto const length{track->Length()}; + auto const room{Direction > 0.0 ? length - Offset : Offset}; + if (left > room) + { + left -= room; + track = track->Connected(Direction > 0.0 ? 1 : -1, Direction); + if ((track == nullptr) || (track->eType == tt_Cross)) + { + return false; + } + Offset = (Direction > 0.0 ? 0.0 : track->Length()); + continue; + } + auto const segment{track->CurrentSegment()}; + if (segment == nullptr) + { + return false; + } + auto const at{std::clamp(Offset + Direction * left, 0.0, length)}; + glm::vec3 rotation; + segment->RaPositionGet(at, Place.position, rotation); + // the way of the path from two points about the place + glm::dvec3 behind; + glm::dvec3 ahead; + segment->RaPositionGet(std::clamp(at - 0.5, 0.0, length), behind, rotation); + segment->RaPositionGet(std::clamp(at + 0.5, 0.0, length), ahead, rotation); + auto way{(ahead - behind) * Direction}; + way.y = 0.0; + if (glm::length(way) < 1e-6) + { + return false; + } + Place.forward = glm::normalize(way); + // on the sleepers, below the heads of the rails + Place.position.y -= track->rail_height(); + return true; + } + return false; +} + +// the yaw of an instance whose model looks along -z, to look along Heading, degrees (-180, 180] +double model_yaw(glm::dvec3 const &Heading) +{ + return std::atan2(-Heading.x, -Heading.z) * 180.0 / std::numbers::pi; +} + +// the turn about the vertical (degrees) for an instance looking along Heading, which plays clip Clip of Animation so that it's at +// frame Frame at the time Time. the whole tenths of a degree come from the heading, the fraction of the tenth tells the shader the +// clip and the moment +float vat_turn(glm::dvec3 const &Heading, vat_clip const &Animation, int const Clip, double const Frame, double const Time) +{ + auto const phase{fraction((Frame - Time * Animation.fps) / Animation.frames)}; + auto const spin{(static_cast(Clip) + 0.25 + 0.5 * phase) / static_cast(Animation.clips)}; + return static_cast((std::floor(model_yaw(Heading) * 10.0) + spin) / 10.0); +} + +// a deer put in the scenery, not a part of it. Moving: the game moves it, so it's drawn on its own +TAnimModel *make_deer(vat_clip const &Animation, glm::dvec3 const &Position, float const Turn, bool const Moving) +{ + auto const range{static_cast(std::ceil(Global.deer_distance + 500.0))}; + auto const definition{std::format("node {} 0 none model 0 0 0 0 {}.t3d none endmodel", range, Animation.model)}; + auto *model{simulation::State.create_model(definition, "none", Position)}; + if (model == nullptr) + { + return nullptr; + } + // not a part of the scenery: no layer of it, not saved, not edited + scene::Layers.count(model->layer(), scene::layer_item::model, -1); + model->layer(null_handle); + model->m_dirty = false; + model->m_generated = true; + simulation::Region->erase(model); + model->Angles(glm::vec3{0.f, Turn, 0.f}); + if (Moving) + { + // out of the groups of the instances of its model, which keep their places + model->draw_alone(); + } + simulation::Region->insert(model); + ++scene::node_state_version; + return model; +} + +// the deer moved to another place +void move_deer(TAnimModel &Model, glm::dvec3 const &Position) +{ + if (glm::length(Model.location() - Position) < 1e-4) + { + return; + } + simulation::Region->erase(&Model); + Model.location(Position); + simulation::Region->insert(&Model); +} + +void remove_deer(TAnimModel *Model) +{ + if (Model != nullptr) + { + simulation::State.delete_model(Model); + ++scene::node_state_version; + } +} + +// the deer goes on with another animation, at frame Frame of clip Clip at the time Time; where the model can't be made, as it was +void change_deer(TAnimModel *&Model, glm::dvec3 const &Heading, vat_clip const &Animation, int const Clip, double const Frame, double const Time, bool const Moving) +{ + auto *model{make_deer(Animation, Model->location(), vat_turn(Heading, Animation, Clip, Frame, Time), Moving)}; + if (model == nullptr) + { + return; + } + remove_deer(Model); + Model = model; +} + +} // namespace + +simulation::deer_herd simulation::Deer; + +void simulation::deer_herd::update(double const Deltatime) +{ + if (m_region != simulation::Region) + { + // another scenery: the deer went with the one they were put in + m_deer.clear(); + m_travelled = 0.0; + m_region = simulation::Region; + } + auto const *vehicle{simulation::Train != nullptr ? simulation::Train->Dynamic() : nullptr}; + if ((false == Global.deer) || (vehicle == nullptr) || (simulation::Region == nullptr)) + { + for (auto const &animal : m_deer) + { + remove_deer(animal.model); + } + m_deer.clear(); + m_travelled = 0.0; + return; + } + auto const *mover{vehicle->MoverParameters}; + m_travelled += std::abs(mover->V) * Deltatime; + if ((Global.deer_interval > 0.0) && (m_travelled >= Global.deer_interval)) + { + m_travelled = 0.0; + if (Random(0.0, 1.0) < Global.deer_chance) + { + spawn(*vehicle); + } + } + auto const train{vehicle->GetPosition()}; + auto const horn{(mover->WarningSignal & 7) != 0}; + auto const now{Timer::GetTime()}; + std::erase_if(m_deer, [this, &train, horn, now](deer &Animal) { return tend(Animal, train, horn, now); }); +} + +bool simulation::deer_herd::tend(deer &Animal, glm::dvec3 const &Train, bool const Horn, double const Now) const +{ + auto const distance{glm::length(Animal.model->location() - Train)}; + Animal.closest = std::min(Animal.closest, distance); + if (((Animal.closest < Passedclose) && (distance > Animal.closest + Passedmargin)) || (distance > Global.deer_distance + 1500.0)) + { + // the train is past it, or went another way + remove_deer(Animal.model); + return true; + } + switch (Animal.state) + { + case deer_state::grazing: + if ((Horn && (distance < Global.deer_hornrange)) || (distance < Global.deer_fleedistance)) + { + alarm(Animal, Train, Now); + } + break; + case deer_state::alarmed: + if (Now >= Animal.time) + { + change_deer(Animal.model, Animal.heading, Startle, Animal.clip, Startframe, Animal.time, false); + Animal.state = deer_state::startled; + } + break; + case deer_state::startled: + if (Now >= Animal.time + Startletime) + { + Animal.time += Startletime; + change_deer(Animal.model, Animal.heading, Flight, Animal.look, Startframe, Animal.time, true); + flee(Animal); + } + break; + case deer_state::fleeing: + if (run(Animal, Now)) + { + // grazing again, where it stopped, from the moment of the grazing the flight ends in + Animal.frame = Grazeafter * Grazing.fps + Startframe; + Animal.time += Flighttime; + change_deer(Animal.model, Animal.heading, Grazing, 0, Animal.frame, Animal.time, false); + Animal.state = deer_state::resting; + } + break; + default: + break; + } + return false; +} + +void simulation::deer_herd::spawn(TDynamicObject const &Vehicle) +{ + // the end of the train the way it goes, or the cab occupied when it stands + auto const *mover{Vehicle.MoverParameters}; + auto front{mover->V > 0.1}; + if (std::abs(mover->V) <= 0.1) + { + front = (mover->CabOccupied >= 0); + } + auto const &axle{front ? Vehicle.Axle0 : Vehicle.Axle1}; + auto const direction{front ? axle.GetDirection() : -axle.GetDirection()}; + path_place place; + if (false == path_ahead(axle.GetTrack(), axle.GetTranslation(), direction, Global.deer_distance, place)) + { + return; + } + // across the path, to one side or the other, a little askew + auto const side{Random(0.0, 1.0) < 0.5 ? -1.0 : 1.0}; + auto const askew{Random(-25.0, 25.0) * std::numbers::pi / 180.0}; + glm::dvec3 const across{place.forward.z * side, 0.0, -place.forward.x * side}; + deer animal; + animal.heading = glm::normalize(across * std::cos(askew) + place.forward * std::sin(askew)); + animal.start = place.position; + // grazing from a moment of its own + animal.frame = Random(0.0, Grazing.frames); + animal.time = Timer::GetTime(); + animal.model = make_deer(Grazing, place.position, vat_turn(animal.heading, Grazing, 0, animal.frame, animal.time), false); + if (animal.model == nullptr) + { + return; + } + m_deer.emplace_back(animal); +} + +void simulation::deer_herd::alarm(deer &Animal, glm::dvec3 const &Train, double const Now) const +{ + // it starts from the moment of the grazing nearest ahead whose start it has (every Window seconds) + auto const grazed{fraction((Animal.frame + (Now - Animal.time) * Grazing.fps) / Grazing.frames) * Grazing.frames / Grazing.fps}; + auto const length{Grazing.frames / Grazing.fps}; + auto const windows{static_cast(std::lround(length / Window))}; + auto window{static_cast(std::ceil(grazed / Window - 1e-6))}; + auto wait{static_cast(window) * Window - grazed}; + window %= windows; + Animal.clip = window; + Animal.time = Now + std::max(0.0, wait); + // it looks at the train: to its left or to its right (the left of a heading h is (h.z, 0, -h.x)) + auto const towards{Train - Animal.model->location()}; + Animal.look = ((towards.x * Animal.heading.z - towards.z * Animal.heading.x) > 0.0 ? 0 : 1); + Animal.state = deer_state::alarmed; +} + +void simulation::deer_herd::flee(deer &Animal) const +{ + Animal.state = deer_state::fleeing; + Animal.start = Animal.model->location(); + // the ground along the way it'll run, where there's none found the height of the step before + Animal.ground.front() = Animal.start.y; + auto const length{flight_way(Flighttime)}; + for (std::size_t sample = 1; sample < Groundsamples; ++sample) + { + auto const point{Animal.start + Animal.heading * (length * static_cast(sample) / static_cast(Groundsamples - 1))}; + double height{0.0}; + Animal.ground[sample] = (ground_height(point, Animal.start.y + Groundceiling, height) ? height : Animal.ground[sample - 1]); + } +} + +bool simulation::deer_herd::run(deer &Animal, double const Now) const +{ + auto const elapsed{std::clamp(Now - Animal.time, 0.0, Flighttime)}; + auto const way{flight_way(elapsed)}; + auto const step{way / flight_way(Flighttime) * static_cast(Groundsamples - 1)}; + auto const sample{std::min(static_cast(step), Groundsamples - 2)}; + auto position{Animal.start + Animal.heading * way}; + position.y = std::lerp(Animal.ground[sample], Animal.ground[sample + 1], step - static_cast(sample)); + move_deer(*Animal.model, position); + return (Now - Animal.time >= Flighttime); +} diff --git a/world/deer.h b/world/deer.h new file mode 100644 index 000000000..308fc01b1 --- /dev/null +++ b/world/deer.h @@ -0,0 +1,86 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include + +class TAnimModel; +class TDynamicObject; +namespace scene +{ +class basic_region; +} + +// deer at the tracks (Global.deer, off unless eu07.ini turns it on): every Global.deer_interval metres the train of the player +// covers, a deer is put (with the chance Global.deer_chance) on the path the train goes along, Global.deer_distance metres ahead +// of it, grazing (the model animals/jelen_je, animated by textures). the horn of the train within Global.deer_hornrange of it, or +// the train coming closer than Global.deer_fleedistance, frightens it: it raises its head (animals/jelen_zryw), looks at the train +// and runs away from the tracks in bounds (animals/jelen_skok, moved by the game along with the hooves), and grazes again where it +// stopped. the game picks the clip and the moment of each of the models (shader vat, vat_random -1), so one hands over to the next +// in the very same pose. the deer go once the train is past them. they aren't parts of the scenery (not saved, not edited) +namespace simulation +{ + +class deer_herd +{ + public: + // after the trains moved, Deltatime: the time of the simulation the frame took, seconds + void update(double const Deltatime); + // deer about at the moment + std::size_t count() const + { + return m_deer.size(); + } + + private: + // the ground under the way the deer runs, at equal steps from its start to its end + static constexpr std::size_t Groundsamples{9}; + enum class deer_state + { + grazing, // till it hears the horn or sees the train close + alarmed, // grazing still, till the moment of the grazing its startle starts from (time) + startled, // raises its head (since time) + fleeing, // looks at the train and runs away (since time) + resting // grazes where it stopped, for good + }; + struct deer + { + TAnimModel *model{nullptr}; + glm::dvec3 start{0.0}; // where it stood when it started to run, or stands + glm::dvec3 heading{0.0, 0.0, 1.0}; // where its head points, level, of length 1 + deer_state state{deer_state::grazing}; + double frame{0.0}; // of the grazing at the time time + double time{0.0}; // of the simulation (Timer::GetTime()), seconds; see deer_state + int clip{0}; // of the startle: the moment of the grazing it starts from + int look{0}; // 0 looks at the train to its left, 1 to its right + double closest{1e9}; // the train came this close, metres + std::array ground{}; // heights of the ground along the way it runs + }; + // the train at Train, its horn sounding, at the time Now: the deer takes fright, runs, or goes (true) once the train is past it + bool tend(deer &Animal, glm::dvec3 const &Train, bool const Horn, double const Now) const; + // puts a deer on the path ahead of the train + void spawn(TDynamicObject const &Vehicle); + // the deer took fright: when it starts, where it looks + void alarm(deer &Animal, glm::dvec3 const &Train, double const Now) const; + // the deer starts to run + void flee(deer &Animal) const; + // moves a running deer, true when it stopped + bool run(deer &Animal, double const Now) const; + + std::vector m_deer; + double m_travelled{0.0}; // by the train since the last deer, metres + scene::basic_region const *m_region{nullptr}; // of the scenery the deer were put in +}; + +extern deer_herd Deer; + +} // namespace simulation From dbad19b92a4c69efa38ccfac6f9b84671d3d3872 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 20:25:12 +0100 Subject: [PATCH 056/123] Rain windscreen: the glass fills up to full in any rain, more slowly in a lighter one The game now counts the rain the glass meets (more at speed) and how wet the glass is (scene_ubs.rain_state: it fills with the rain and dries when the rain stops), and the rain fallen when each blade was at the end of its sweep (wiper_rain_out/return). The glass with rain gets as many drops, droplets, rivulets and as much haze as the heaviest rain gives, scaled by how wet it is; where a blade went over it they come back with the rain fallen since. A lighter rain only takes longer: 95% full in 10 s of the heaviest rain standing still, 20 s at cloud cover 1.5, 2.5x as fast at 100 km/h; half dry in 3 minutes standing still. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- gl/ubo.h | 10 +++- rendering/opengl46/opengl46renderer.cpp | 26 +++++++++- rendering/opengl46/opengl46renderer.h | 3 ++ rendering/vulkan14/vulkan14frame.cpp | 26 +++++++++- rendering/vulkan14/vulkan14renderer.h | 3 ++ shaders/ogl46/common.glsl | 5 ++ shaders/ogl46/mat_rain_windscreen.frag | 64 +++++++++++++++---------- shaders/ogl46/rain_cells.comp | 3 +- shaders/vk14/common.glsl | 5 ++ shaders/vk14/mat_rain_windscreen.frag | 64 +++++++++++++++---------- shaders/vk14/rain_cells.comp | 3 +- 11 files changed, 157 insertions(+), 55 deletions(-) diff --git a/gl/ubo.h b/gl/ubo.h index 52da98b92..d2556a4ee 100644 --- a/gl/ubo.h +++ b/gl/ubo.h @@ -206,9 +206,17 @@ namespace gl // world with them, inv_view and its modelview (the moment of its animation from its place) glm::vec4 camera_hi; glm::vec4 camera_lo; + // the rain the glass meets (mat_rain_windscreen): x the rain fallen so far, in seconds of the heaviest rain standing still (more + // at speed: the glass runs into it); y how wet the glass is, 0 dry .. 1 as full of drops as it gets (it fills with the rain, + // dries when it stops); z how fast the glass fills: the share left to fill goes down as exp(-z x the rain fallen); w unused + glm::vec4 rain_state; + // the rain fallen (rain_state.x) when the blades were at the ends of their sweep, as wiper_timer_out and wiper_timer_return + // (the drops come back with the rain fallen since); -1 not known + glm::vec4 wiper_rain_out; + glm::vec4 wiper_rain_return; }; - static_assert(sizeof(scene_ubs) == 992 + 80 * MAX_HEADLIGHT_SHADOWS + 96 * MAX_CAB_PROBE_LAMPS, "bad size of ubs"); + static_assert(sizeof(scene_ubs) == 1040 + 80 * MAX_HEADLIGHT_SHADOWS + 96 * MAX_CAB_PROBE_LAMPS, "bad size of ubs"); // the camera of a pass in the world for the scene block (scene_ubs::camera_hi, camera_lo) inline void set_camera_place(scene_ubs &Ubs, glm::dvec3 const &Place) diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index 3da55b6a7..c4e11b31d 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -1706,6 +1706,8 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) scene_ubs.wiper_timer_return = glm::vec4{-1000.}; scene_ubs.wiper_bugs_out = glm::vec4{-1.}; scene_ubs.wiper_bugs_return = glm::vec4{-1.}; + scene_ubs.wiper_rain_out = glm::vec4{-1.}; + scene_ubs.wiper_rain_return = glm::vec4{-1.}; m_wiperbugs = 0.0; } // the insects the vehicle meets (mat_bugs_windscreen): none below 20 km/h, above it the more the faster, counted in seconds of @@ -1713,6 +1715,23 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) if (owner != nullptr) m_wiperbugs += Timer::GetDeltaTime() * std::max(std::abs(owner->MoverParameters->V) * 3.6 - 20.0, 0.0) / 80.0; scene_ubs.rain_wind.w = static_cast(m_wiperbugs); + // the rain the glass meets (mat_rain_windscreen): counted in seconds of the heaviest rain standing still, more at speed (the + // glass runs into it). the glass fills with it up to as many drops as it gets (a lighter rain only fills it more slowly), and + // dries when it stops (by half in dry_halflife standing still, faster at speed) + { + constexpr double fill_rate{0.3}; // per second of the heaviest rain: 95% full in 10 s (20 s at cloud cover 1.5) + constexpr double fill_speed{1.5}; // at 100 km/h and more the glass meets x (1 + fill_speed) as much rain + constexpr double dry_halflife{180.0}; // seconds standing still + auto const dt{Timer::GetDeltaTime()}; + auto const speed{(owner != nullptr) ? std::min(std::abs(owner->MoverParameters->V) * 3.6 / 100.0, 1.0) : 0.0}; + auto const meet{static_cast(percipitation_intensity) * (1.0 + fill_speed * speed)}; + m_wiperrain += dt * meet; + if (percipitation_intensity > 0.f) + m_glasswet += (1.0 - m_glasswet) * (1.0 - std::exp(-fill_rate * dt * meet)); + else + m_glasswet *= std::exp(-dt * std::log(2.0) / dry_halflife * (1.0 + 2.0 * speed)); + scene_ubs.rain_state = glm::vec4{static_cast(m_wiperrain), static_cast(m_glasswet), static_cast(fill_rate), 0.f}; + } if (owner != nullptr) { auto const cabactive{owner->MoverParameters->CabActive != 0 ? owner->MoverParameters->CabActive : 1}; @@ -1730,11 +1749,13 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) { scene_ubs.wiper_timer_out[i] = scene_ubs.time; scene_ubs.wiper_bugs_out[i] = static_cast(m_wiperbugs); + scene_ubs.wiper_rain_out[i] = static_cast(m_wiperrain); } if (owner->dWiperPos[index] > .975) { scene_ubs.wiper_timer_return[i] = scene_ubs.time; scene_ubs.wiper_bugs_return[i] = static_cast(m_wiperbugs); + scene_ubs.wiper_rain_return[i] = static_cast(m_wiperrain); } } else @@ -1744,6 +1765,8 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) scene_ubs.wiper_timer_return[i] = -1000.; scene_ubs.wiper_bugs_out[i] = -1.; scene_ubs.wiper_bugs_return[i] = -1.; + scene_ubs.wiper_rain_out[i] = -1.; + scene_ubs.wiper_rain_return[i] = -1.; } } } @@ -1768,7 +1791,8 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) { m_windscreenwater.update(Timer::GetDeltaTime()); // the drops and the rivulets of the glasses with rain, for the time of the block of the scene - m_windscreenwater.update_rain_cells(scene_ubs.time, scene_ubs.rain_params.x); + // (the drops a cell may hold: as many as the glass is wet) + m_windscreenwater.update_rain_cells(scene_ubs.time, (scene_ubs.rain_state.y > 0.001f) ? std::min(scene_ubs.rain_state.y + 0.01f, 1.f) : 0.f); } m_windscreenwater.bind(); diff --git a/rendering/opengl46/opengl46renderer.h b/rendering/opengl46/opengl46renderer.h index f4144bd52..5528974b6 100644 --- a/rendering/opengl46/opengl46renderer.h +++ b/rendering/opengl46/opengl46renderer.h @@ -856,6 +856,9 @@ class opengl46_renderer : public gfx_renderer, public gfx::scene_walk { TDynamicObject const *m_wipervehicle{nullptr}; // the insects that vehicle met so far: seconds of driving at 100 km/h (scene_ubs.rain_wind.w) double m_wiperbugs{0.0}; + // the rain the glass met so far and how wet it is (scene_ubs::rain_state) + double m_wiperrain{0.0}; + double m_glasswet{0.0}; gl::light_data light_data; std::unordered_map> m_shaders; diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index 26b494e37..f89beaa62 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -1136,7 +1136,8 @@ void vulkan14_renderer::render_scene() // the water on the windscreens of the cab: a step of its simulation once a frame, before the passes which draw the glasses scene.water.update(Timer::GetDeltaTime()); // the drops and the rivulets of the glasses with rain, for the time the block of the scene gets (scene_ubs.time) - scene.water.update_rain_cells(static_cast(Timer::GetTime()), glm::saturate(Global.Overcast - 1.f)); + // (the drops a cell may hold: as many as the glass is wet, a little more, since it's the wetness of the frame before) + scene.water.update_rain_cells(static_cast(Timer::GetTime()), (m_glasswet > 0.001) ? static_cast(std::min(m_glasswet + 0.01, 1.0)) : 0.f); if (scene.targets.size() < m_viewports.size()) { scene.targets.resize(m_viewports.size()); @@ -1582,6 +1583,8 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) scene_ubs.wiper_timer_return = glm::vec4{-1000.}; scene_ubs.wiper_bugs_out = glm::vec4{-1.}; scene_ubs.wiper_bugs_return = glm::vec4{-1.}; + scene_ubs.wiper_rain_out = glm::vec4{-1.}; + scene_ubs.wiper_rain_return = glm::vec4{-1.}; m_wiperbugs = 0.0; } // the insects the vehicle meets (mat_bugs_windscreen): none below 20 km/h, above it the more the faster, counted in seconds of @@ -1589,6 +1592,23 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) if (owner != nullptr) m_wiperbugs += Timer::GetDeltaTime() * std::max(std::abs(owner->MoverParameters->V) * 3.6 - 20.0, 0.0) / 80.0; scene_ubs.rain_wind.w = static_cast(m_wiperbugs); + // the rain the glass meets (mat_rain_windscreen): counted in seconds of the heaviest rain standing still, more at speed (the + // glass runs into it). the glass fills with it up to as many drops as it gets (a lighter rain only fills it more slowly), and + // dries when it stops (by half in dry_halflife standing still, faster at speed) + { + constexpr double fill_rate{0.3}; // per second of the heaviest rain: 95% full in 10 s (20 s at cloud cover 1.5) + constexpr double fill_speed{1.5}; // at 100 km/h and more the glass meets x (1 + fill_speed) as much rain + constexpr double dry_halflife{180.0}; // seconds standing still + auto const dt{Timer::GetDeltaTime()}; + auto const speed{(owner != nullptr) ? std::min(std::abs(owner->MoverParameters->V) * 3.6 / 100.0, 1.0) : 0.0}; + auto const meet{static_cast(percipitation_intensity) * (1.0 + fill_speed * speed)}; + m_wiperrain += dt * meet; + if (percipitation_intensity > 0.f) + m_glasswet += (1.0 - m_glasswet) * (1.0 - std::exp(-fill_rate * dt * meet)); + else + m_glasswet *= std::exp(-dt * std::log(2.0) / dry_halflife * (1.0 + 2.0 * speed)); + scene_ubs.rain_state = glm::vec4{static_cast(m_wiperrain), static_cast(m_glasswet), static_cast(fill_rate), 0.f}; + } if (owner != nullptr) { auto const cabactive{owner->MoverParameters->CabActive != 0 ? owner->MoverParameters->CabActive : 1}; @@ -1606,11 +1626,13 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) { scene_ubs.wiper_timer_out[i] = scene_ubs.time; scene_ubs.wiper_bugs_out[i] = static_cast(m_wiperbugs); + scene_ubs.wiper_rain_out[i] = static_cast(m_wiperrain); } if (owner->dWiperPos[index] > .975) { scene_ubs.wiper_timer_return[i] = scene_ubs.time; scene_ubs.wiper_bugs_return[i] = static_cast(m_wiperbugs); + scene_ubs.wiper_rain_return[i] = static_cast(m_wiperrain); } } else @@ -1620,6 +1642,8 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) scene_ubs.wiper_timer_return[i] = -1000.; scene_ubs.wiper_bugs_out[i] = -1.; scene_ubs.wiper_bugs_return[i] = -1.; + scene_ubs.wiper_rain_out[i] = -1.; + scene_ubs.wiper_rain_return[i] = -1.; } } } diff --git a/rendering/vulkan14/vulkan14renderer.h b/rendering/vulkan14/vulkan14renderer.h index 4d53a3c43..6539eed87 100644 --- a/rendering/vulkan14/vulkan14renderer.h +++ b/rendering/vulkan14/vulkan14renderer.h @@ -565,6 +565,9 @@ class vulkan14_renderer : public gfx_renderer, public gfx::scene_walk TDynamicObject const *m_wipervehicle{nullptr}; // the insects that vehicle met so far: seconds of driving at 100 km/h (scene_ubs.rain_wind.w) double m_wiperbugs{0.0}; + // the rain the glass met so far and how wet it is (scene_ubs::rain_state) + double m_wiperrain{0.0}; + double m_glasswet{0.0}; gl::light_data light_data{}; std::uint32_t m_lightcount{1}; // lights written to light_data // the copies of the light buffer in the ring of the frame since the lights were last written, by the header and the sun diff --git a/shaders/ogl46/common.glsl b/shaders/ogl46/common.glsl index 01bdfab85..f8cb04883 100644 --- a/shaders/ogl46/common.glsl +++ b/shaders/ogl46/common.glsl @@ -375,6 +375,11 @@ layout(std140, binding = SCENE_UBO_BINDING) uniform scene_ubo // the place of the camera of the pass in the world (whole 64 m, the rest), see gl::scene_ubs vec4 camera_hi; vec4 camera_lo; + // the rain the glass meets: x fallen so far, y how wet the glass is, z how fast it fills (mat_rain_windscreen), see gl::scene_ubs + vec4 rain_state; + // the rain fallen when the blades were at the ends of their sweep, see gl::scene_ubs + vec4 wiper_rain_out; + vec4 wiper_rain_return; }; #ifdef STAGE_VERTEX diff --git a/shaders/ogl46/mat_rain_windscreen.frag b/shaders/ogl46/mat_rain_windscreen.frag index a7bceccc9..9f7012cf4 100644 --- a/shaders/ogl46/mat_rain_windscreen.frag +++ b/shaders/ogl46/mat_rain_windscreen.frag @@ -78,20 +78,26 @@ layout(binding = 3) uniform sampler2D normalmap; // --- Haze of the wet glass (blur) ------------------------------------------------ // The haze follows the rain and is wiped away by the wipers, as before (fully blurred from a quarter of the haze on). const float blur_amount = 1.0; // strength of the haze: 0 = off, 1 = full -// after the wiper the haze grows with the rain fallen on the glass since (intensity x seconds) from nothing up to its full -// strength, which is the intensity of the rain (cloud cover 1.5 -> 0.5). where no wiper reaches it is as always -const float haze_fill = 12.0; // rain to mist the glass up fully: seconds of the heaviest rain (2x as long at 1.5) +// after the wiper the haze grows with the rain fallen on the glass since (intensity x seconds, more at speed) from nothing up to +// its full strength, in any rain (a lighter rain takes longer). where no wiper reaches it is full +const float haze_fill = 12.0; // rain fallen since the blade to mist the glass up fully: seconds of the heaviest + // rain standing still (2x as long at 1.5; the speed counted in by the game) const float haze_curve = 1.0; // > 1: slow at first, then more and more -const float haze_speed = 1.0; // at speed the haze grows: x (1 + haze_speed) at full speed (see wind_drag_gain) const float WS_BEND_ENC = 60.0; // the drop request in the velocity target; must match rain_windscreen_haze.glsl const float WS_DROP_BIAS = 192.0; const float WS_ENC = 64.0; // the haze request in the velocity target; must match rain_windscreen_haze.glsl +// --- How the water gathers on the glass ------------------------------------------------------------------ +// the game counts the rain the glass meets (rain_state, gl::scene_ubs; more at speed) and how wet the glass is (0 dry .. 1 as full +// of drops as it gets): the glass fills up to the full in any rain, a lighter one only takes longer, and dries when the rain stops. +// the times are in the game (fill_rate, fill_speed, dry_halflife in the setup of the scene block). where a blade went over the glass +// the drops come back with the rain fallen since + // --- Drops (atlas tiles) ------------------------------------------------------ // (how long they live: rain_cells.glsl; the cells of the drops and of the rivulets are worked out once a frame by rain_cells.comp) // --- Micro droplets ------------------------------------------------------------- -const float micro_density = 0.45; // share of micro cells holding a droplet at full rain, 0 = off +const float micro_density = 0.45; // share of micro cells holding a droplet on a full glass, 0 = off const float micro_scale = 3.0; // micro grid = raindrop_grid_size * micro_scale const float micro_size_min = 0.12; // droplet radius in micro cells const float micro_size_max = 0.40; @@ -361,7 +367,7 @@ Riv getRiv(vec2 sCell, float sCW, float sCH, float gridSize) { Riv r; uvec4 d = rain_cells[rain_riv_index(wsLayerIndex, ivec2(sCell))]; - r.on = ((float(d.x & 65535u) + 0.5) * (1.0 / 65536.0) < rain_params.x * streak_density * wsLayerDensity); + r.on = ((float(d.x & 65535u) + 0.5) * (1.0 / 65536.0) < streak_density * wsLayerDensity * rain_state.y); // as wet as the glass is r.life = float((d.x >> 16) & 255u) * (1.0 / 255.0); float wr = rain_byte(d.y, 16u); r.width = streak_head * wsLayerHead / gridSize @@ -554,9 +560,8 @@ float wsKept(vec2 cg, float rad, float sCW, float sCH, float gridSize) return kept; } -// seconds since a wiper blade last went over Co (texture UV), from the timers of its strokes as GetMixFactor takes them; -// -1 where no wiper reaches -float wsWipeAge(vec2 co) +// the rain fallen (rain_state.x) since a blade last went over this place (texture UV); -1 where no blade goes or not known +float wsWipeRain(vec2 co) { vec4 movePhase = wiper_pos; bvec4 is_out = lessThanEqual(movePhase, vec4(1.)); @@ -565,12 +570,12 @@ float wsWipeAge(vec2 co) vec4 maskVal = mix(1. - mask, mask, is_out); vec4 passed = step(maskVal, movePhase); vec4 sideV = mix(passed, vec4(1.) - passed, is_out); - vec4 ages = vec4(time) - mix(wiper_timer_out, wiper_timer_return, sideV); - float age = -1.0; + vec4 at = mix(wiper_rain_out, wiper_rain_return, sideV); + float fallen = -1.0; for (int i = 0; i < 4; ++i) - if ((mask[i] > 0.001) && ((age < 0.0) || (ages[i] < age))) - age = max(ages[i], 0.0); - return age; + if ((mask[i] > 0.001) && (at[i] >= 0.0)) + fallen = (fallen < 0.0) ? max(rain_state.x - at[i], 0.0) : min(fallen, max(rain_state.x - at[i], 0.0)); + return fallen; } // the tangent frame of the glass (the directions of u and v on it, view space) from the screen-space change of the place and the uv @@ -628,10 +633,6 @@ void main() float wsNight = smoothstep(0.0, drop_dark_lum, sceneLum); // 0 dark night .. 1 daylight dynBright *= wsNight; - // wiper state of this pixel (blur, micro droplets) - float hazeSide; - float wipeVis = GetMixFactor(f_coord, hazeSide); - Hit hit; hit.score = 0.0; hit.cov = 0.0; hit.colA = 0.0; hit.n = vec3(0.0, 0.0, 1.0); hit.offUV = vec2(0.0); hit.radUV = 1.0; hit.isDrop = 1.0; @@ -678,6 +679,10 @@ void main() wsPushT = vec2(dot(wsPush, Tgl), dot(wsPush, Bgl)); wsPushT = (dot(wsPushT, wsPushT) > 1e-10) ? normalize(wsPushT) : vec2(0.0, -1.0); } + + // the wiper state of this pixel (blur, micro droplets) + float hazeSide; + float wipeVis = GetMixFactor(f_coord, hazeSide); // the change of the glass UV (v up) per screen pixel, for the rivulets vec2 wsRd1 = vec2(duv1.x, flipS * duv1.y); vec2 wsRd2 = vec2(duv2.x, flipS * duv2.y); @@ -690,7 +695,7 @@ void main() vec2 sCell = floor(sUVg / vec2(sCW, sCH)); bool sweepOn = streak_sweep > 0.0 && streak_density > 0.0 && (wind_streaks > 0.0 || wsWindShare < 1.0) && (WS_PROFILE != 2); - if ((rain_params.x > 0.001) && (WS_PROFILE != 5)) + if ((rain_state.y > 0.001) && (WS_PROFILE != 5)) { // =================================================================== // 1. drops from the atlas: this cell and its 8 neighbours @@ -708,6 +713,9 @@ void main() reach &= reach - 1u; vec2 nc = cell + vec2(float(bit % 3 - 1), float(bit / 3 - 1)); uvec4 d = rain_cells[rain_drop_index(ivec2(nc))]; + // as many drops as the glass is wet (the cells were sorted out with a little more) + if (rain_byte(d.y, 24u) > min(rain_state.y * drop_density, 0.95)) + continue; float vis = float(d.w >> 24) * (1.0 / 255.0); float spreadF = mix(0.8, 1.0, float((d.y >> 19) & 31u) * (1.0 / 31.0)); // a drop the blades miss: the same drop before and after the stroke, left where it is @@ -781,7 +789,7 @@ void main() float mph = fract(mtt); uint mep = uint(mod(floor(mtt), 65521.0)); uint m1 = Hash(uvec3(mk, mep * 4u + 1u)); - if (RandF(m1) < min(rain_params.x * micro_density, 0.95)) + if (RandF(m1) < min(micro_density * rain_state.y, 0.95)) { uint m2 = Hash(uvec3(mk, mep * 4u + 2u + uint(hazeSide) * 2u)); if (wipeVis >= RandF(m2)) @@ -991,10 +999,11 @@ void main() // What is seen through the wet glass: the image of the last frame, blurred by the haze, bent by the drops // ----------------------------------------------------------------------- // the haze after the wiper: grows with the rain fallen since, up to the intensity of the rain (as it always was where no wiper reaches) - float wipeAge = wsWipeAge(f_coord); - float hazeBack = (wipeAge < 0.0) ? 1.0 - : min(wipeVis, pow(clamp(wipeAge * rain_params.x / haze_fill, 0.0, 1.0), haze_curve)); - float hazeWeight = min(rain_params.x * hazeBack * (1.0 + haze_speed * wsSpeed), 1.0) * (1.0 - max(alphaOut, coverA)); + float wipeRain = wsWipeRain(f_coord); + float hazeBack = (wipeRain < 0.0) ? rain_state.y + : min(rain_state.y, pow(clamp(wipeRain / haze_fill, 0.0, 1.0), haze_curve)); + // up to the full haze in any rain, as the glass gets wet (a lighter rain only mists it up more slowly), less as it dries + float hazeWeight = hazeBack * (1.0 - max(alphaOut, coverA)); float glassClear = 1.0 - smoothstep(0.5, 0.95, glassA); bool image = ssr_params.x >= 1.0; float background = 0.0; // distance to the scene behind, along the view (0: far / not known) @@ -1094,7 +1103,12 @@ float GetMixFactor(in vec2 co, out float side) { side_v = mix(side_v, vec4(1.) - side_v, is_out); // "regeneration", raindrops gradually returning after wiper pass: - vec4 regenPhase = clamp((vec4(time) - mix(wiper_timer_out, wiper_timer_return, side_v) - vec4(.2)) / vec4(rain_params.y), vec4(0.), vec4(1.)); + // the share of the drops back: the glass fills with the rain fallen since the blade (rain_state), up to as wet as the glass is + // where no blade goes (the drops of a cell are there only up to that share, so the share of those back is the fill over it) + vec4 fallen = vec4(rain_state.x) - mix(wiper_rain_out, wiper_rain_return, side_v); + vec4 known = step(vec4(0.), mix(wiper_rain_out, wiper_rain_return, side_v)); + vec4 filled = mix(vec4(1.), vec4(1.) - exp(-max(fallen, vec4(0.)) * rain_state.z), known); + vec4 regenPhase = clamp(filled / max(rain_state.y, 1e-4), vec4(0.), vec4(1.)); side_v = mix(vec4(0.), vec4(1.) - side_v, areaMask); diff --git a/shaders/ogl46/rain_cells.comp b/shaders/ogl46/rain_cells.comp index 6916c3eab..43ab26a60 100644 --- a/shaders/ogl46/rain_cells.comp +++ b/shaders/ogl46/rain_cells.comp @@ -7,7 +7,7 @@ #include "common.glsl" layout(location = 0) uniform float rain_time; // the time of the block of the scene (scene_ubs.time) -layout(location = 1) uniform float rain_amount; // how hard it rains (scene_ubs.rain_params.x) +layout(location = 1) uniform float rain_amount; // how wet the glass is (scene_ubs.rain_state.y, a little more) layout(location = 2) uniform int rain_pass; // 0 the cells, 1 the reach of the drops #include "random.glsl" @@ -125,6 +125,7 @@ float drop_reach(uint A, uint B, float Spread) uvec4 drop_masks(ivec2 Cell) { uvec4 result = uvec4(0u); + // as many drops as the glass is wet (rain_amount: the wetness of the glass, scene_ubs.rain_state.y) float most = min(rain_amount * drop_density, 0.95); for (int dy = -1; dy <= 1; ++dy) for (int dx = -1; dx <= 1; ++dx) diff --git a/shaders/vk14/common.glsl b/shaders/vk14/common.glsl index b2aa5218b..515b32d50 100644 --- a/shaders/vk14/common.glsl +++ b/shaders/vk14/common.glsl @@ -337,6 +337,11 @@ layout(std140, set = PASS_SET, binding = SCENE_UBO) uniform scene_ubo // the place of the camera of the pass in the world (whole 64 m, the rest), see gl::scene_ubs vec4 camera_hi; vec4 camera_lo; + // the rain the glass meets: x fallen so far, y how wet the glass is, z how fast it fills (mat_rain_windscreen), see gl::scene_ubs + vec4 rain_state; + // the rain fallen when the blades were at the ends of their sweep, see gl::scene_ubs + vec4 wiper_rain_out; + vec4 wiper_rain_return; }; #ifndef LAYOUT_COMPUTE diff --git a/shaders/vk14/mat_rain_windscreen.frag b/shaders/vk14/mat_rain_windscreen.frag index 9b8bfb2a8..cada855a8 100644 --- a/shaders/vk14/mat_rain_windscreen.frag +++ b/shaders/vk14/mat_rain_windscreen.frag @@ -83,20 +83,26 @@ layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 3) uniform sampler // --- Haze of the wet glass (blur) ------------------------------------------------ // The haze follows the rain and is wiped away by the wipers, as before (fully blurred from a quarter of the haze on). const float blur_amount = 1.0; // strength of the haze: 0 = off, 1 = full -// after the wiper the haze grows with the rain fallen on the glass since (intensity x seconds) from nothing up to its full -// strength, which is the intensity of the rain (cloud cover 1.5 -> 0.5). where no wiper reaches it is as always -const float haze_fill = 12.0; // rain to mist the glass up fully: seconds of the heaviest rain (2x as long at 1.5) +// after the wiper the haze grows with the rain fallen on the glass since (intensity x seconds, more at speed) from nothing up to +// its full strength, in any rain (a lighter rain takes longer). where no wiper reaches it is full +const float haze_fill = 12.0; // rain fallen since the blade to mist the glass up fully: seconds of the heaviest + // rain standing still (2x as long at 1.5; the speed counted in by the game) const float haze_curve = 1.0; // > 1: slow at first, then more and more -const float haze_speed = 1.0; // at speed the haze grows: x (1 + haze_speed) at full speed (see wind_drag_gain) const float WS_BEND_ENC = 60.0; // the drop request in the velocity target; must match rain_windscreen_haze.glsl const float WS_DROP_BIAS = 192.0; const float WS_ENC = 64.0; // the haze request in the velocity target; must match rain_windscreen_haze.glsl +// --- How the water gathers on the glass ------------------------------------------------------------------ +// the game counts the rain the glass meets (rain_state, gl::scene_ubs; more at speed) and how wet the glass is (0 dry .. 1 as full +// of drops as it gets): the glass fills up to the full in any rain, a lighter one only takes longer, and dries when the rain stops. +// the times are in the game (fill_rate, fill_speed, dry_halflife in the setup of the scene block). where a blade went over the glass +// the drops come back with the rain fallen since + // --- Drops (atlas tiles) ------------------------------------------------------ // (how long they live: rain_cells.glsl; the cells of the drops and of the rivulets are worked out once a frame by rain_cells.comp) // --- Micro droplets ------------------------------------------------------------- -const float micro_density = 0.45; // share of micro cells holding a droplet at full rain, 0 = off +const float micro_density = 0.45; // share of micro cells holding a droplet on a full glass, 0 = off const float micro_scale = 3.0; // micro grid = raindrop_grid_size * micro_scale const float micro_size_min = 0.12; // droplet radius in micro cells const float micro_size_max = 0.40; @@ -366,7 +372,7 @@ Riv getRiv(vec2 sCell, float sCW, float sCH, float gridSize) { Riv r; uvec4 d = rain_cells[rain_riv_index(wsLayerIndex, ivec2(sCell))]; - r.on = ((float(d.x & 65535u) + 0.5) * (1.0 / 65536.0) < rain_params.x * streak_density * wsLayerDensity); + r.on = ((float(d.x & 65535u) + 0.5) * (1.0 / 65536.0) < streak_density * wsLayerDensity * rain_state.y); // as wet as the glass is r.life = float((d.x >> 16) & 255u) * (1.0 / 255.0); float wr = rain_byte(d.y, 16u); r.width = streak_head * wsLayerHead / gridSize @@ -559,9 +565,8 @@ float wsKept(vec2 cg, float rad, float sCW, float sCH, float gridSize) return kept; } -// seconds since a wiper blade last went over Co (texture UV), from the timers of its strokes as GetMixFactor takes them; -// -1 where no wiper reaches -float wsWipeAge(vec2 co) +// the rain fallen (rain_state.x) since a blade last went over this place (texture UV); -1 where no blade goes or not known +float wsWipeRain(vec2 co) { vec4 movePhase = wiper_pos; bvec4 is_out = lessThanEqual(movePhase, vec4(1.)); @@ -570,12 +575,12 @@ float wsWipeAge(vec2 co) vec4 maskVal = mix(1. - mask, mask, is_out); vec4 passed = step(maskVal, movePhase); vec4 sideV = mix(passed, vec4(1.) - passed, is_out); - vec4 ages = vec4(time) - mix(wiper_timer_out, wiper_timer_return, sideV); - float age = -1.0; + vec4 at = mix(wiper_rain_out, wiper_rain_return, sideV); + float fallen = -1.0; for (int i = 0; i < 4; ++i) - if ((mask[i] > 0.001) && ((age < 0.0) || (ages[i] < age))) - age = max(ages[i], 0.0); - return age; + if ((mask[i] > 0.001) && (at[i] >= 0.0)) + fallen = (fallen < 0.0) ? max(rain_state.x - at[i], 0.0) : min(fallen, max(rain_state.x - at[i], 0.0)); + return fallen; } // the tangent frame of the glass (the directions of u and v on it, view space) from the screen-space change of the place and the uv @@ -633,10 +638,6 @@ void main() float wsNight = smoothstep(0.0, drop_dark_lum, sceneLum); // 0 dark night .. 1 daylight dynBright *= wsNight; - // wiper state of this pixel (blur, micro droplets) - float hazeSide; - float wipeVis = GetMixFactor(f_coord, hazeSide); - Hit hit; hit.score = 0.0; hit.cov = 0.0; hit.colA = 0.0; hit.n = vec3(0.0, 0.0, 1.0); hit.offUV = vec2(0.0); hit.radUV = 1.0; hit.isDrop = 1.0; @@ -683,6 +684,10 @@ void main() wsPushT = vec2(dot(wsPush, Tgl), dot(wsPush, Bgl)); wsPushT = (dot(wsPushT, wsPushT) > 1e-10) ? normalize(wsPushT) : vec2(0.0, -1.0); } + + // the wiper state of this pixel (blur, micro droplets) + float hazeSide; + float wipeVis = GetMixFactor(f_coord, hazeSide); // the change of the glass UV (v up) per screen pixel, for the rivulets vec2 wsRd1 = vec2(duv1.x, flipS * duv1.y); vec2 wsRd2 = vec2(duv2.x, flipS * duv2.y); @@ -695,7 +700,7 @@ void main() vec2 sCell = floor(sUVg / vec2(sCW, sCH)); bool sweepOn = streak_sweep > 0.0 && streak_density > 0.0 && (wind_streaks > 0.0 || wsWindShare < 1.0) && (WS_PROFILE != 2); - if ((rain_params.x > 0.001) && (WS_PROFILE != 5)) + if ((rain_state.y > 0.001) && (WS_PROFILE != 5)) { // =================================================================== // 1. drops from the atlas: this cell and its 8 neighbours @@ -713,6 +718,9 @@ void main() reach &= reach - 1u; vec2 nc = cell + vec2(float(bit % 3 - 1), float(bit / 3 - 1)); uvec4 d = rain_cells[rain_drop_index(ivec2(nc))]; + // as many drops as the glass is wet (the cells were sorted out with a little more) + if (rain_byte(d.y, 24u) > min(rain_state.y * drop_density, 0.95)) + continue; float vis = float(d.w >> 24) * (1.0 / 255.0); float spreadF = mix(0.8, 1.0, float((d.y >> 19) & 31u) * (1.0 / 31.0)); // a drop the blades miss: the same drop before and after the stroke, left where it is @@ -786,7 +794,7 @@ void main() float mph = fract(mtt); uint mep = uint(mod(floor(mtt), 65521.0)); uint m1 = Hash(uvec3(mk, mep * 4u + 1u)); - if (RandF(m1) < min(rain_params.x * micro_density, 0.95)) + if (RandF(m1) < min(micro_density * rain_state.y, 0.95)) { uint m2 = Hash(uvec3(mk, mep * 4u + 2u + uint(hazeSide) * 2u)); if (wipeVis >= RandF(m2)) @@ -996,10 +1004,11 @@ void main() // What is seen through the wet glass: the image of the last frame, blurred by the haze, bent by the drops // ----------------------------------------------------------------------- // the haze after the wiper: grows with the rain fallen since, up to the intensity of the rain (as it always was where no wiper reaches) - float wipeAge = wsWipeAge(f_coord); - float hazeBack = (wipeAge < 0.0) ? 1.0 - : min(wipeVis, pow(clamp(wipeAge * rain_params.x / haze_fill, 0.0, 1.0), haze_curve)); - float hazeWeight = min(rain_params.x * hazeBack * (1.0 + haze_speed * wsSpeed), 1.0) * (1.0 - max(alphaOut, coverA)); + float wipeRain = wsWipeRain(f_coord); + float hazeBack = (wipeRain < 0.0) ? rain_state.y + : min(rain_state.y, pow(clamp(wipeRain / haze_fill, 0.0, 1.0), haze_curve)); + // up to the full haze in any rain, as the glass gets wet (a lighter rain only mists it up more slowly), less as it dries + float hazeWeight = hazeBack * (1.0 - max(alphaOut, coverA)); float glassClear = 1.0 - smoothstep(0.5, 0.95, glassA); bool image = ssr_params.x >= 1.0; float background = 0.0; // distance to the scene behind, along the view (0: far / not known) @@ -1099,7 +1108,12 @@ float GetMixFactor(in vec2 co, out float side) { side_v = mix(side_v, vec4(1.) - side_v, is_out); // "regeneration", raindrops gradually returning after wiper pass: - vec4 regenPhase = clamp((vec4(time) - mix(wiper_timer_out, wiper_timer_return, side_v) - vec4(.2)) / vec4(rain_params.y), vec4(0.), vec4(1.)); + // the share of the drops back: the glass fills with the rain fallen since the blade (rain_state), up to as wet as the glass is + // where no blade goes (the drops of a cell are there only up to that share, so the share of those back is the fill over it) + vec4 fallen = vec4(rain_state.x) - mix(wiper_rain_out, wiper_rain_return, side_v); + vec4 known = step(vec4(0.), mix(wiper_rain_out, wiper_rain_return, side_v)); + vec4 filled = mix(vec4(1.), vec4(1.) - exp(-max(fallen, vec4(0.)) * rain_state.z), known); + vec4 regenPhase = clamp(filled / max(rain_state.y, 1e-4), vec4(0.), vec4(1.)); side_v = mix(vec4(0.), vec4(1.) - side_v, areaMask); diff --git a/shaders/vk14/rain_cells.comp b/shaders/vk14/rain_cells.comp index 780addf0e..9b6848a2b 100644 --- a/shaders/vk14/rain_cells.comp +++ b/shaders/vk14/rain_cells.comp @@ -11,7 +11,7 @@ layout(push_constant) uniform kernel_constants { float rain_time; // the time of the block of the scene (scene_ubs.time) - float rain_amount; // how hard it rains (scene_ubs.rain_params.x) + float rain_amount; // how wet the glass is (scene_ubs.rain_state.y, a little more) int rain_pass; // 0 the cells, 1 the reach of the drops }; @@ -130,6 +130,7 @@ float drop_reach(uint A, uint B, float Spread) uvec4 drop_masks(ivec2 Cell) { uvec4 result = uvec4(0u); + // as many drops as the glass is wet (rain_amount: the wetness of the glass, scene_ubs.rain_state.y) float most = min(rain_amount * drop_density, 0.95); for (int dy = -1; dy <= 1; ++dy) for (int dx = -1; dx <= 1; ++dx) From c71b32297a367428505acb86dd43c65e7bd0352c Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 20:36:11 +0100 Subject: [PATCH 057/123] OpenGL 4.6: the settings from the values the game gives, also where the driver defines GL_SPIRV Some drivers (AMD's) define GL_SPIRV also when they compile the GLSL source, so settings.glsl took the specialization constants, which a source can't have, and no shader compiled ("constant_id: only allowed when generating SPIR-V"). The game always puts the values of the settings before a source it compiles, so those decide. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/settings.glsl | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/shaders/ogl46/settings.glsl b/shaders/ogl46/settings.glsl index 65c441991..cda2ecf39 100644 --- a/shaders/ogl46/settings.glsl +++ b/shaders/ogl46/settings.glsl @@ -4,7 +4,8 @@ #ifndef SETTINGS_GLSL #define SETTINGS_GLSL -#ifdef GL_SPIRV +// (some drivers, AMD's among them, define GL_SPIRV also when they compile the source: the game always puts the values before it) +#if defined(GL_SPIRV) && !defined(SHADOWMAP_ENABLED_VALUE) layout(constant_id = 0) const bool SHADOWMAP_ENABLED = true; layout(constant_id = 1) const bool ENVMAP_ENABLED = true; layout(constant_id = 2) const bool MOTIONBLUR_ENABLED = true; From 2fe11d39a1f3989bb3142794a5f8308aedfc7863 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 13:39:59 +0100 Subject: [PATCH 058/123] Rain windscreen: the rain fallen since a blade went over each place of its sweep The glass took the rain fallen since one of the two moments the blades were at the ends of their sweep, picked by the way the blade was going. After a pass that gave a place the blade had just wiped the rain of the sweep before, until the blade reached the other end: the haze and the drops there jumped back and forth with every sweep (a jump in brightness under the wiper mask, best seen in a light rain). Now the renderers keep, for 64 places along the sweep of each blade (the value of the wiper mask), the rain fallen when the blade last went over them (gl::scene_ubs::wiper_rain_pass, marked for all the places a blade went over since the last frame), and the glass reads the one of its pixel. wiper_rain_out / wiper_rain_return are gone; the timers and the insects keep the ends of the sweep. No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- gl/glsl_common.cpp | 1 + gl/ubo.h | 29 ++++++++++++++++++++----- rendering/opengl46/opengl46renderer.cpp | 15 ++++++++----- rendering/opengl46/opengl46renderer.h | 3 +++ rendering/vulkan14/vulkan14frame.cpp | 15 ++++++++----- rendering/vulkan14/vulkan14renderer.h | 3 +++ shaders/ogl46/common.glsl | 6 ++--- shaders/ogl46/mat_rain_windscreen.frag | 21 ++++++++++-------- shaders/vk14/common.glsl | 6 ++--- shaders/vk14/mat_rain_windscreen.frag | 21 ++++++++++-------- 10 files changed, 79 insertions(+), 41 deletions(-) diff --git a/gl/glsl_common.cpp b/gl/glsl_common.cpp index 981d7b05e..799698e3b 100644 --- a/gl/glsl_common.cpp +++ b/gl/glsl_common.cpp @@ -95,6 +95,7 @@ void gl::glsl_common_setup() "#define HEADLIGHT_SHADOW_TEX " + std::to_string(HEADLIGHT_SHADOW_TEX) + "\n" + "#define MAX_HEADLIGHT_SHADOWS " + std::to_string(MAX_HEADLIGHT_SHADOWS) + "U\n" + "#define MAX_CAB_PROBE_LAMPS " + std::to_string(MAX_CAB_PROBE_LAMPS) + "U\n" + + "#define WIPER_PASS_BUCKETS " + std::to_string(WIPER_PASS_BUCKETS) + "\n" + "#define FOG_VOLUME_TEX " + std::to_string(FOG_VOLUME_TEX) + "\n" + "#define CLOUD_SHADOW_TEX " + std::to_string(CLOUD_SHADOW_TEX) + "\n" + "#define CLOUD_TEX " + std::to_string(CLOUD_TEX) + "\n" + diff --git a/gl/ubo.h b/gl/ubo.h index d2556a4ee..a9a77d32f 100644 --- a/gl/ubo.h +++ b/gl/ubo.h @@ -4,6 +4,7 @@ #include "bindable.h" #include "buffer.h" #include +#include #include #include #include @@ -72,6 +73,9 @@ namespace gl const size_t MAX_HEADLIGHT_SHADOWS = 4; // lights of the occupied cab the probe of the cab is drawn with (gfx::cab_probe, gl::scene_ubs::cab_probe_lamp), at most const size_t MAX_CAB_PROBE_LAMPS = 16; + // the places along the sweep of a blade (dWiperPos 0 .. 1) the rain fallen when it last went over them is kept for + // (gl::scene_ubs::wiper_rain_pass) + const size_t WIPER_PASS_BUCKETS = 64; // weather (opengl46_weather): the fog of the main view (3d, apply_fog.glsl) and the shadows the clouds cast (2d), read by the // shading. bound directly, like the ones above const size_t FOG_VOLUME_TEX = MAX_TEXTURES + HELPER_TEXTURES + 4; @@ -210,13 +214,28 @@ namespace gl // at speed: the glass runs into it); y how wet the glass is, 0 dry .. 1 as full of drops as it gets (it fills with the rain, // dries when it stops); z how fast the glass fills: the share left to fill goes down as exp(-z x the rain fallen); w unused glm::vec4 rain_state; - // the rain fallen (rain_state.x) when the blades were at the ends of their sweep, as wiper_timer_out and wiper_timer_return - // (the drops come back with the rain fallen since); -1 not known - glm::vec4 wiper_rain_out; - glm::vec4 wiper_rain_return; + // the rain fallen (rain_state.x) when a blade last went over a place of its sweep: element b for the places b / 64 .. (b + 1) + // / 64 of dWiperPos (the value of the wiper mask of a pixel), x .. w the blades (as wiper_pos); -1 not known. the drops and the + // haze come back with the rain fallen since. (the moments the blades were at the ends of their sweep, which the pixel took + // the one of by the way the blade went, gave the rain of a whole sweep back to the place a blade had just wiped) + glm::vec4 wiper_rain_pass[WIPER_PASS_BUCKETS]; }; - static_assert(sizeof(scene_ubs) == 1040 + 80 * MAX_HEADLIGHT_SHADOWS + 96 * MAX_CAB_PROBE_LAMPS, "bad size of ubs"); + static_assert(sizeof(scene_ubs) == 1008 + 16 * WIPER_PASS_BUCKETS + 80 * MAX_HEADLIGHT_SHADOWS + 96 * MAX_CAB_PROBE_LAMPS, "bad size of ubs"); + + // the bucket of scene_ubs::wiper_rain_pass a place of a blade (dWiperPos, 0 .. 1) falls in + inline std::size_t wiper_pass_bucket(double const Position) + { + return std::min(static_cast(std::max(Position, 0.0) * static_cast(WIPER_PASS_BUCKETS)), WIPER_PASS_BUCKETS - 1); + } + + // the places blade Wiper went over from From to To (dWiperPos) get the rain fallen Value (-1: not known) + inline void wiper_pass_mark(scene_ubs &Scene, glm::length_t const Wiper, double const From, double const To, float const Value) + { + auto const last{wiper_pass_bucket(std::max(From, To))}; + for (auto bucket{wiper_pass_bucket(std::min(From, To))}; bucket <= last; ++bucket) + Scene.wiper_rain_pass[bucket][Wiper] = Value; + } // the camera of a pass in the world for the scene block (scene_ubs::camera_hi, camera_lo) inline void set_camera_place(scene_ubs &Ubs, glm::dvec3 const &Place) diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index c4e11b31d..ba5b5ec46 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -1706,8 +1706,9 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) scene_ubs.wiper_timer_return = glm::vec4{-1000.}; scene_ubs.wiper_bugs_out = glm::vec4{-1.}; scene_ubs.wiper_bugs_return = glm::vec4{-1.}; - scene_ubs.wiper_rain_out = glm::vec4{-1.}; - scene_ubs.wiper_rain_return = glm::vec4{-1.}; + for (auto &pass : scene_ubs.wiper_rain_pass) + pass = glm::vec4{-1.f}; + m_wiperlastpos.fill(-1.0); m_wiperbugs = 0.0; } // the insects the vehicle meets (mat_bugs_windscreen): none below 20 km/h, above it the more the faster, counted in seconds of @@ -1740,6 +1741,10 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) if (i < owner->dWiperPos.size()) { int index = cabactive > 0 ? i : static_cast(owner->dWiperPos.size() - 1) - i; + // the places of its sweep the blade went over since the last frame get the rain fallen now + auto const position{owner->dWiperPos[index]}; + gl::wiper_pass_mark(scene_ubs, i, (m_wiperlastpos[i] < 0.0) ? position : m_wiperlastpos[i], position, static_cast(m_wiperrain)); + m_wiperlastpos[i] = position; scene_ubs.wiper_pos[i] = owner->dWiperPos[index]; if (owner->dWiperPos[index] > 0. && owner->wiperDirection[index]) { @@ -1749,13 +1754,11 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) { scene_ubs.wiper_timer_out[i] = scene_ubs.time; scene_ubs.wiper_bugs_out[i] = static_cast(m_wiperbugs); - scene_ubs.wiper_rain_out[i] = static_cast(m_wiperrain); } if (owner->dWiperPos[index] > .975) { scene_ubs.wiper_timer_return[i] = scene_ubs.time; scene_ubs.wiper_bugs_return[i] = static_cast(m_wiperbugs); - scene_ubs.wiper_rain_return[i] = static_cast(m_wiperrain); } } else @@ -1765,8 +1768,8 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) scene_ubs.wiper_timer_return[i] = -1000.; scene_ubs.wiper_bugs_out[i] = -1.; scene_ubs.wiper_bugs_return[i] = -1.; - scene_ubs.wiper_rain_out[i] = -1.; - scene_ubs.wiper_rain_return[i] = -1.; + gl::wiper_pass_mark(scene_ubs, i, 0.0, 1.0, -1.f); + m_wiperlastpos[i] = -1.0; } } } diff --git a/rendering/opengl46/opengl46renderer.h b/rendering/opengl46/opengl46renderer.h index 5528974b6..445b936c1 100644 --- a/rendering/opengl46/opengl46renderer.h +++ b/rendering/opengl46/opengl46renderer.h @@ -856,6 +856,9 @@ class opengl46_renderer : public gfx_renderer, public gfx::scene_walk { TDynamicObject const *m_wipervehicle{nullptr}; // the insects that vehicle met so far: seconds of driving at 100 km/h (scene_ubs.rain_wind.w) double m_wiperbugs{0.0}; + // the place of each blade (dWiperPos) the last frame, -1 not known: the places it went over since get the rain fallen + // (gl::wiper_pass_mark) + std::array m_wiperlastpos{-1.0, -1.0, -1.0, -1.0}; // the rain the glass met so far and how wet it is (scene_ubs::rain_state) double m_wiperrain{0.0}; double m_glasswet{0.0}; diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index f89beaa62..a4f31b27e 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -1583,8 +1583,9 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) scene_ubs.wiper_timer_return = glm::vec4{-1000.}; scene_ubs.wiper_bugs_out = glm::vec4{-1.}; scene_ubs.wiper_bugs_return = glm::vec4{-1.}; - scene_ubs.wiper_rain_out = glm::vec4{-1.}; - scene_ubs.wiper_rain_return = glm::vec4{-1.}; + for (auto &pass : scene_ubs.wiper_rain_pass) + pass = glm::vec4{-1.f}; + m_wiperlastpos.fill(-1.0); m_wiperbugs = 0.0; } // the insects the vehicle meets (mat_bugs_windscreen): none below 20 km/h, above it the more the faster, counted in seconds of @@ -1617,6 +1618,10 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) if (i < owner->dWiperPos.size()) { int index = cabactive > 0 ? i : static_cast(owner->dWiperPos.size() - 1) - i; + // the places of its sweep the blade went over since the last frame get the rain fallen now + auto const position{owner->dWiperPos[index]}; + gl::wiper_pass_mark(scene_ubs, i, (m_wiperlastpos[i] < 0.0) ? position : m_wiperlastpos[i], position, static_cast(m_wiperrain)); + m_wiperlastpos[i] = position; scene_ubs.wiper_pos[i] = owner->dWiperPos[index]; if (owner->dWiperPos[index] > 0. && owner->wiperDirection[index]) { @@ -1626,13 +1631,11 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) { scene_ubs.wiper_timer_out[i] = scene_ubs.time; scene_ubs.wiper_bugs_out[i] = static_cast(m_wiperbugs); - scene_ubs.wiper_rain_out[i] = static_cast(m_wiperrain); } if (owner->dWiperPos[index] > .975) { scene_ubs.wiper_timer_return[i] = scene_ubs.time; scene_ubs.wiper_bugs_return[i] = static_cast(m_wiperbugs); - scene_ubs.wiper_rain_return[i] = static_cast(m_wiperrain); } } else @@ -1642,8 +1645,8 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) scene_ubs.wiper_timer_return[i] = -1000.; scene_ubs.wiper_bugs_out[i] = -1.; scene_ubs.wiper_bugs_return[i] = -1.; - scene_ubs.wiper_rain_out[i] = -1.; - scene_ubs.wiper_rain_return[i] = -1.; + gl::wiper_pass_mark(scene_ubs, i, 0.0, 1.0, -1.f); + m_wiperlastpos[i] = -1.0; } } } diff --git a/rendering/vulkan14/vulkan14renderer.h b/rendering/vulkan14/vulkan14renderer.h index 6539eed87..477274efc 100644 --- a/rendering/vulkan14/vulkan14renderer.h +++ b/rendering/vulkan14/vulkan14renderer.h @@ -565,6 +565,9 @@ class vulkan14_renderer : public gfx_renderer, public gfx::scene_walk TDynamicObject const *m_wipervehicle{nullptr}; // the insects that vehicle met so far: seconds of driving at 100 km/h (scene_ubs.rain_wind.w) double m_wiperbugs{0.0}; + // the place of each blade (dWiperPos) the last frame, -1 not known: the places it went over since get the rain fallen + // (gl::wiper_pass_mark) + std::array m_wiperlastpos{-1.0, -1.0, -1.0, -1.0}; // the rain the glass met so far and how wet it is (scene_ubs::rain_state) double m_wiperrain{0.0}; double m_glasswet{0.0}; diff --git a/shaders/ogl46/common.glsl b/shaders/ogl46/common.glsl index f8cb04883..7c1947a9e 100644 --- a/shaders/ogl46/common.glsl +++ b/shaders/ogl46/common.glsl @@ -104,6 +104,7 @@ #define HEADLIGHT_SHADOW_TEX 15 #define MAX_HEADLIGHT_SHADOWS 4U #define MAX_CAB_PROBE_LAMPS 16U +#define WIPER_PASS_BUCKETS 64 #define FOG_VOLUME_TEX 16 #define CLOUD_SHADOW_TEX 17 #define CLOUD_TEX 18 @@ -377,9 +378,8 @@ layout(std140, binding = SCENE_UBO_BINDING) uniform scene_ubo vec4 camera_lo; // the rain the glass meets: x fallen so far, y how wet the glass is, z how fast it fills (mat_rain_windscreen), see gl::scene_ubs vec4 rain_state; - // the rain fallen when the blades were at the ends of their sweep, see gl::scene_ubs - vec4 wiper_rain_out; - vec4 wiper_rain_return; + // the rain fallen when a blade last went over a place of its sweep (the wiper mask / 64), see gl::scene_ubs + vec4 wiper_rain_pass[WIPER_PASS_BUCKETS]; }; #ifdef STAGE_VERTEX diff --git a/shaders/ogl46/mat_rain_windscreen.frag b/shaders/ogl46/mat_rain_windscreen.frag index 9f7012cf4..ca68ca98e 100644 --- a/shaders/ogl46/mat_rain_windscreen.frag +++ b/shaders/ogl46/mat_rain_windscreen.frag @@ -269,6 +269,14 @@ vec4 wsOver(vec4 over, vec4 under) // =========================================================================== float GetMixFactor(in vec2 co, out float side); +// the rain fallen when each blade last went over the place of its sweep given by the wiper mask (-1: not known), see +// gl::scene_ubs::wiper_rain_pass +vec4 wsWipePass(vec4 mask) +{ + ivec4 b = min(ivec4(max(mask, vec4(0.0)) * float(WIPER_PASS_BUCKETS)), ivec4(WIPER_PASS_BUCKETS - 1)); + return vec4(wiper_rain_pass[b.x].x, wiper_rain_pass[b.y].y, wiper_rain_pass[b.z].z, wiper_rain_pass[b.w].w); +} + uvec2 cellKey(vec2 c); vec2 tileOffset(float choice) @@ -563,14 +571,8 @@ float wsKept(vec2 cg, float rad, float sCW, float sCH, float gridSize) // the rain fallen (rain_state.x) since a blade last went over this place (texture UV); -1 where no blade goes or not known float wsWipeRain(vec2 co) { - vec4 movePhase = wiper_pos; - bvec4 is_out = lessThanEqual(movePhase, vec4(1.)); - movePhase = mix(vec4(2.) - movePhase, movePhase, is_out); vec4 mask = textureLod(wipermask, co, 0.0); - vec4 maskVal = mix(1. - mask, mask, is_out); - vec4 passed = step(maskVal, movePhase); - vec4 sideV = mix(passed, vec4(1.) - passed, is_out); - vec4 at = mix(wiper_rain_out, wiper_rain_return, sideV); + vec4 at = wsWipePass(mask); float fallen = -1.0; for (int i = 0; i < 4; ++i) if ((mask[i] > 0.001) && (at[i] >= 0.0)) @@ -1105,8 +1107,9 @@ float GetMixFactor(in vec2 co, out float side) { // "regeneration", raindrops gradually returning after wiper pass: // the share of the drops back: the glass fills with the rain fallen since the blade (rain_state), up to as wet as the glass is // where no blade goes (the drops of a cell are there only up to that share, so the share of those back is the fill over it) - vec4 fallen = vec4(rain_state.x) - mix(wiper_rain_out, wiper_rain_return, side_v); - vec4 known = step(vec4(0.), mix(wiper_rain_out, wiper_rain_return, side_v)); + vec4 at = wsWipePass(mask); + vec4 fallen = vec4(rain_state.x) - at; + vec4 known = step(vec4(0.), at); vec4 filled = mix(vec4(1.), vec4(1.) - exp(-max(fallen, vec4(0.)) * rain_state.z), known); vec4 regenPhase = clamp(filled / max(rain_state.y, 1e-4), vec4(0.), vec4(1.)); diff --git a/shaders/vk14/common.glsl b/shaders/vk14/common.glsl index 515b32d50..180ceb472 100644 --- a/shaders/vk14/common.glsl +++ b/shaders/vk14/common.glsl @@ -100,6 +100,7 @@ #define MAX_PARAMS 3U #define MAX_HEADLIGHT_SHADOWS 4U #define MAX_CAB_PROBE_LAMPS 16U +#define WIPER_PASS_BUCKETS 64 #define CLUSTER_GRID_X 16 #define CLUSTER_GRID_Y 9 #define CLUSTER_GRID_Z 24 @@ -339,9 +340,8 @@ layout(std140, set = PASS_SET, binding = SCENE_UBO) uniform scene_ubo vec4 camera_lo; // the rain the glass meets: x fallen so far, y how wet the glass is, z how fast it fills (mat_rain_windscreen), see gl::scene_ubs vec4 rain_state; - // the rain fallen when the blades were at the ends of their sweep, see gl::scene_ubs - vec4 wiper_rain_out; - vec4 wiper_rain_return; + // the rain fallen when a blade last went over a place of its sweep (the wiper mask / 64), see gl::scene_ubs + vec4 wiper_rain_pass[WIPER_PASS_BUCKETS]; }; #ifndef LAYOUT_COMPUTE diff --git a/shaders/vk14/mat_rain_windscreen.frag b/shaders/vk14/mat_rain_windscreen.frag index cada855a8..89f1c263f 100644 --- a/shaders/vk14/mat_rain_windscreen.frag +++ b/shaders/vk14/mat_rain_windscreen.frag @@ -274,6 +274,14 @@ vec4 wsOver(vec4 over, vec4 under) // =========================================================================== float GetMixFactor(in vec2 co, out float side); +// the rain fallen when each blade last went over the place of its sweep given by the wiper mask (-1: not known), see +// gl::scene_ubs::wiper_rain_pass +vec4 wsWipePass(vec4 mask) +{ + ivec4 b = min(ivec4(max(mask, vec4(0.0)) * float(WIPER_PASS_BUCKETS)), ivec4(WIPER_PASS_BUCKETS - 1)); + return vec4(wiper_rain_pass[b.x].x, wiper_rain_pass[b.y].y, wiper_rain_pass[b.z].z, wiper_rain_pass[b.w].w); +} + uvec2 cellKey(vec2 c); vec2 tileOffset(float choice) @@ -568,14 +576,8 @@ float wsKept(vec2 cg, float rad, float sCW, float sCH, float gridSize) // the rain fallen (rain_state.x) since a blade last went over this place (texture UV); -1 where no blade goes or not known float wsWipeRain(vec2 co) { - vec4 movePhase = wiper_pos; - bvec4 is_out = lessThanEqual(movePhase, vec4(1.)); - movePhase = mix(vec4(2.) - movePhase, movePhase, is_out); vec4 mask = textureLod(wipermask, co, 0.0); - vec4 maskVal = mix(1. - mask, mask, is_out); - vec4 passed = step(maskVal, movePhase); - vec4 sideV = mix(passed, vec4(1.) - passed, is_out); - vec4 at = mix(wiper_rain_out, wiper_rain_return, sideV); + vec4 at = wsWipePass(mask); float fallen = -1.0; for (int i = 0; i < 4; ++i) if ((mask[i] > 0.001) && (at[i] >= 0.0)) @@ -1110,8 +1112,9 @@ float GetMixFactor(in vec2 co, out float side) { // "regeneration", raindrops gradually returning after wiper pass: // the share of the drops back: the glass fills with the rain fallen since the blade (rain_state), up to as wet as the glass is // where no blade goes (the drops of a cell are there only up to that share, so the share of those back is the fill over it) - vec4 fallen = vec4(rain_state.x) - mix(wiper_rain_out, wiper_rain_return, side_v); - vec4 known = step(vec4(0.), mix(wiper_rain_out, wiper_rain_return, side_v)); + vec4 at = wsWipePass(mask); + vec4 fallen = vec4(rain_state.x) - at; + vec4 known = step(vec4(0.), at); vec4 filled = mix(vec4(1.), vec4(1.) - exp(-max(fallen, vec4(0.)) * rain_state.z), known); vec4 regenPhase = clamp(filled / max(rain_state.y, 1e-4), vec4(0.), vec4(1.)); From 87ef243169547b89990dd4421ad21712b7611c1a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 14:29:19 +0100 Subject: [PATCH 059/123] Vulkan: define WIPER_PASS_BUCKETS for the shaders The preamble of the vulkan renderer didn't define it, and with the constants of common.glsl skipped (MASZYNA_CONSTANTS) the shaders didn't compile: the renderer failed to start and fell back to opengl. Now defined by the preamble, and common.glsl defines it when the renderer doesn't (an older exe with these shaders). No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- rendering/vulkan14/vulkan14shaders.cpp | 1 + shaders/ogl46/common.glsl | 7 ++++++- shaders/vk14/common.glsl | 7 ++++++- 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/rendering/vulkan14/vulkan14shaders.cpp b/rendering/vulkan14/vulkan14shaders.cpp index 59b51b1d1..814ac29c3 100644 --- a/rendering/vulkan14/vulkan14shaders.cpp +++ b/rendering/vulkan14/vulkan14shaders.cpp @@ -931,6 +931,7 @@ std::string binding_preamble(bool const Raytracing) define("MAX_PARAMS", static_cast(gl::MAX_PARAMS), "U"); define("MAX_HEADLIGHT_SHADOWS", static_cast(gl::MAX_HEADLIGHT_SHADOWS), "U"); define("MAX_CAB_PROBE_LAMPS", static_cast(gl::MAX_CAB_PROBE_LAMPS), "U"); + define("WIPER_PASS_BUCKETS", static_cast(gl::WIPER_PASS_BUCKETS)); define("CLUSTER_GRID_X", gl::CLUSTER_GRID_X); define("CLUSTER_GRID_Y", gl::CLUSTER_GRID_Y); define("CLUSTER_GRID_Z", gl::CLUSTER_GRID_Z); diff --git a/shaders/ogl46/common.glsl b/shaders/ogl46/common.glsl index 7c1947a9e..f3ac47314 100644 --- a/shaders/ogl46/common.glsl +++ b/shaders/ogl46/common.glsl @@ -104,7 +104,6 @@ #define HEADLIGHT_SHADOW_TEX 15 #define MAX_HEADLIGHT_SHADOWS 4U #define MAX_CAB_PROBE_LAMPS 16U -#define WIPER_PASS_BUCKETS 64 #define FOG_VOLUME_TEX 16 #define CLOUD_SHADOW_TEX 17 #define CLOUD_TEX 18 @@ -131,6 +130,12 @@ #define FOG_VOLUME_BIAS 10.000000 #endif +// the places along the sweep of a blade whose rain is kept (gl::WIPER_PASS_BUCKETS): the renderer defines it, an older one doesn't +#ifndef WIPER_PASS_BUCKETS +#define WIPER_PASS_BUCKETS 64 +#endif + + const uint LIGHT_SPOT = 0U; const uint LIGHT_POINT = 1U; const uint LIGHT_DIR = 2U; diff --git a/shaders/vk14/common.glsl b/shaders/vk14/common.glsl index 180ceb472..dfc741624 100644 --- a/shaders/vk14/common.glsl +++ b/shaders/vk14/common.glsl @@ -100,7 +100,6 @@ #define MAX_PARAMS 3U #define MAX_HEADLIGHT_SHADOWS 4U #define MAX_CAB_PROBE_LAMPS 16U -#define WIPER_PASS_BUCKETS 64 #define CLUSTER_GRID_X 16 #define CLUSTER_GRID_Y 9 #define CLUSTER_GRID_Z 24 @@ -143,6 +142,12 @@ #define CAB_PROBE_SH_GROUP_SIZE 64 #endif +// the places along the sweep of a blade whose rain is kept (gl::WIPER_PASS_BUCKETS): the renderer defines it, an older one doesn't +#ifndef WIPER_PASS_BUCKETS +#define WIPER_PASS_BUCKETS 64 +#endif + + #include "settings.glsl" #if !defined(LAYOUT_UI) && !defined(LAYOUT_COMPUTE) From d0ef4130d09b12f7a560143180bfbaf499bf89a9 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 18:57:29 +0100 Subject: [PATCH 060/123] Windscreens: a third of the drops left by a blade, and the snow glass through the post-processing - rain_cells.glsl: wiper_miss 0.05 -> 0.0167, a blade leaves three times fewer drops where they were - mat_snow_windscreen.frag (the snow glass, made for the game apart from this repository) added, asking the post-processing for its haze and its bent picture through the velocity target as the rain and the insects of this version do (rain_windscreen_haze.glsl) No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_snow_windscreen.frag | 599 ++++++++++++++++++++++++ shaders/ogl46/rain_cells.glsl | 2 +- shaders/vk14/mat_snow_windscreen.frag | 604 +++++++++++++++++++++++++ shaders/vk14/rain_cells.glsl | 2 +- 4 files changed, 1205 insertions(+), 2 deletions(-) create mode 100644 shaders/ogl46/mat_snow_windscreen.frag create mode 100644 shaders/vk14/mat_snow_windscreen.frag diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag new file mode 100644 index 000000000..50496d520 --- /dev/null +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -0,0 +1,599 @@ +#version 460 core +#define STAGE_FRAGMENT 1 +// Windscreen snow: replaces rain_windscreen when it snows - v2 (OpenGL 4.6 / Vulkan 1.4 port of the OpenGL 3.3 v1) +// v2: the syntax of the 4.6 renderers (explicit locations and bindings, #pragma texture / param), the tuning values as constants +// (a uniform can't have a default any more); the blur of the scene and the picture bent by thin snow go to the +// post-processing through the velocity target, as the haze and the drops of rain_windscreen (postfx_taa.frag / +// postfx_motionblur.frag with rain_windscreen_haze.glsl); the colour is written straight +// (not premultiplied) as rain_windscreen of the 4.6 renderers writes the glass; the gloss of the glass from legacy_gloss(); +// no lighting where the glass is clear (no snow, a clear texture). the look and the behaviour of the snow are those of v1. +// +// MaSzyna switches the weather itself (simulationenvironment.cpp): with Overcast > 1 it rains when the air is warmer +// than 1 deg C and it SNOWS at 1 deg C and below, and the .mat block "snow:" is picked. rain_params.x is the +// precipitation intensity (saturate(Overcast - 1)), exactly what rain_windscreen uses for the drops, so the snow +// on the glass follows the snowfall: nothing without snow, and the harder it snows the more the glass gets plastered. +// +// - flakes: every cell of the glass can hold a flake (atlas tiles 0..2: fluffy, wet lump, crumbs). It lands at a random +// moment, stays white for `snow_hold` seconds and then MELTS for `snow_melt` seconds: the snow fades into a water spot +// (tile 3). About `snow_slide_share` of the melting flakes also SLIDE DOWN the glass, stretching into a drip. +// Only the wet, melting spot blurs the scene (water refracts; dry snow does not, see snow_fresh_blur). +// - clumping: flakes land small and GROW as more snow piles onto them. Where flakes land next to each other they run together +// into one bigger patch (a crusty white film), and the more it snows the more flakes land side by side, so the bigger +// the patches get. The patch exists only where flakes really sit close together; when they melt / slide away it breaks +// up and thins out (snow_clump). +// - wipers (wipermask, GetMixFactor) clear all of it; it builds up again after `snow_regen` seconds (faster in heavy snow). +// Nothing depends on the time since the game started. +// +// Atlas / normalmap (blender_snow_atlas.py), 2 x 2 tiles: +// 0 dry fluffy flake 1 wet compact lump 2 crumbs 3 melted spot (water + ice remnants) +// +// .mat: +// +// texture_diffuse: dynamic/pkp/vectron_v1/cab/szyby +// texture_raindropsatlas: textures/fx/raindrops-atlas +// texture_normalmap: textures/fx/raindrops_normalmap +// texture_wipermask: dynamic/pkp/vectron_v1/cab/szyby_wipermask +// shader: rain_windscreen +// param_raindrop_grid_size: 150 +// +// snow: { +// shader: snow_windscreen +// texture_raindropsatlas: textures/fx/snow-atlas +// texture_normalmap: textures/fx/snow_normalmap +// param_raindrop_grid_size: 70 +// } +// +// One cell is about one flake: a grid of ~50-90 gives flakes of ~1-2 cm on a ~1.5 m windscreen. + +layout(location = 0) in vec3 f_normal; +layout(location = 2) in vec2 f_coord; +layout(location = 3) in vec4 f_pos; +layout(location = 4) in vec4 f_clip_pos; +layout(location = 5) in vec4 f_clip_future_pos; +#include "common.glsl" + +layout(location = 0) out vec4 out_color; +layout(location = 1) out vec4 out_motion; + +#pragma texture(diffuse, 0, sRGB_A) +#pragma texture(raindropsatlas, 1, sRGB_A) +#pragma texture(wipermask, 2, sRGB_A) +#pragma texture(normalmap, 3, RGBA) // flakes: rg = normal xy, b = height, a = mask; same 2x2 layout as raindropsatlas (linear) +#pragma param(color, 0, 0, 4, diffuse) +#pragma param(diffuse, 1, 0, 1, diffuse) +#pragma param(specular, 1, 1, 1, specular) +#pragma param(reflection, 1, 2, 1, zero) +#pragma param(glossiness, 1, 3, 1, glossiness) +#pragma param(raindrop_grid_size, 2, 0, 1, one) + +#include "light_common.glsl" +#include "apply_fog.glsl" +#include "tonemapping.glsl" +#include "random.glsl" + +layout(binding = 0) uniform sampler2D diffuse; +layout(binding = 1) uniform sampler2D raindropsatlas; +layout(binding = 2) uniform sampler2D wipermask; +layout(binding = 3) uniform sampler2D normalmap; + +// --- Tuning ----------------------------------------------------------------- +// Intensity = rain_params.x = saturate(Overcast - 1). The slider range 1.00..2.00 (Overcast) maps to intensity 0..1. The share of flake cells is pow(intensity, 0.8) * snow_gain * snow_density, +// so with the defaults every cell carries a flake from Overcast ~ 1.2 and the film closes the glass at about 1.3 (1.1 = light snow, 1.5+ = blizzard). +const float snow_gain = 1.4; // how fast the glass gets covered when the snowfall gets heavier (higher = already plastered in light snow) +const float snow_density = 0.95; // upper limit of the share of cells that carry a big flake +const float snow_small = 0.80; // same for the layer of small flakes (0 = off) +const float snow_pack = 0.90; // opacity of the patches that form where flakes clump together (0 = no patches) +const float snow_clump = 2.60; // how readily neighbouring flakes run together into one patch (higher = patches form sooner and get bigger) +const float snow_clump_share = 0.55; // share of the flakes that run together into patches; the rest stay separate flakes +const float snow_hold = 40.0; // seconds a flake stays white before it starts to melt (longer in heavy snow) +const float snow_melt = 30.0; // seconds the melting takes (snow fades into a water spot) +const float snow_slide_share = 0.40; // share of the melting flakes that run down the glass +const float snow_slide_len = 2.0; // how far a sliding flake runs, in cells (max 2.4) +const float snow_grow_fast = 5.3; // seconds a patch needs to grow from a clump to a big sheet in the heaviest snowfall +const float snow_grow_slow = 46.7; // same in the lightest snowfall (it still gets there, just much later) +const float snow_haze = 1.0; // blur of the scene behind and around the snow patches (frosted glass), 0 = off, 1 = full (radius: windscreen_view.glsl) +const float snow_distort = 2.0; // picture distortion seen through thin snow (refraction by its relief), 0 = off +const float snow_flake_scale = 2.5; // size of the flakes from the atlas relative to one grid cell (2-3 = two to three times bigger than before; the flakes get fewer) +const float snow_regen = 25.0; // seconds until snow is back on a wiped area (in light snowfall) +const float snow_opacity = 1.0; // overall opacity +const float snow_uv_aspect = 1.0; // glass width / height in the world if the UV is stretched +const float snow_bump = 1.0; // strength of the 3D relief from the normal map, 0 = flat +const float snow_gloss = 0.45; // glints of the sun / headlights on the snow, 0 = matt +const float snow_translucency = 0.8; // glow of thin snow when you look towards the sun / a lamp, 0 = off +const float snow_melt_blur = 0.8; // blur of the scene around the water spots of melting flakes (0 = off, 1 = full) +const float snow_fresh_blur = 0.0; // blur around fresh dry flakes: physically there is none, a little (0.1-0.2) fakes light scattering + +#ifndef SNOW_FLIP_Y +#define SNOW_FLIP_Y 0 // set to 1 if sliding flakes run UP the glass (the glass UV then has v growing downwards) +#endif +const float SNOW_SIZE_MIN = 0.70; // flake size in grid cells (keep max <= 1.8, the search covers 3x3 cells) +const float SNOW_SIZE_MAX = 1.50; +const float SNOW_SLIDER_MAX = 1.10; // a flake that slides is smaller than this (it gets stretched on its way down) +const float SNOW_HALO_SCALE = 1.5; // blur ring radius = flake half-size * this +const float SNOW_LAND_TIME = 1.5; // seconds a flake takes to land and settle +const float SNOW_REFR_MAXPX = 96.0; // the largest picture shift of thin snow, screen pixels +const float WS_REFR_MAXPX = 96.0; // the largest picture shift the post-processing makes, screen pixels; must match rain_windscreen_haze.glsl +const float WS_BEND_ENC = 60.0; // the bend request in the velocity target; must match rain_windscreen_haze.glsl +const float WS_DROP_BIAS = 192.0; +const float WS_ENC = 64.0; // the haze request in the velocity target; must match rain_windscreen_haze.glsl +const float SNOW_REFR_MIX = 0.85; // 0 = no refraction, 1 = only the bent picture + +#ifndef SNOW_MATCH_RAIN_GLASS +#define SNOW_MATCH_RAIN_GLASS 0 // 4.6: rain_windscreen writes the glass straight, not premultiplied +#endif + +float snHaze = 0.0; // set by snowFilm: 1 inside / next to a snow patch (drives the frosted-glass blur) +float snWipeSince = 1.0e5; // set by GetMixFactor: seconds since the wiper last cleaned this spot +float GetMixFactor(in vec2 co, out float side); + +const float SNOW_MERGE_R = 2.0; // reach of a flake's 'snow mass' in flake half-sizes (flakes closer than this run together) +const float SNOW_CLUMP_THR = 0.80; // summed mass above which the glass is covered + +float snHash(vec2 p) +{ + return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); +} + +float snNoise(vec2 p) +{ + vec2 i = floor(p); + vec2 f = fract(p); + f = f * f * (3.0 - 2.0 * f); + return mix(mix(snHash(i), snHash(i + vec2(1.0, 0.0)), f.x), + mix(snHash(i + vec2(0.0, 1.0)), snHash(i + vec2(1.0, 1.0)), f.x), f.y); +} + +float snFbm(vec2 p) +{ + float a = 0.5; + float v = 0.0; + for (int i = 0; i < 4; ++i) + { + v += a * snNoise(p); + p = p * 2.07 + vec2(17.3, 9.1); + a *= 0.5; + } + return v / 0.9375; +} + +// One flake in one cell. `age` = seconds since it landed. +void snowFlake(vec2 ncell, uint seed, float age, float gridSize, float pixelUV, vec2 aspect, + float sizeMul, float opacityMul, float hold, float meltT, float slideShare, + inout vec3 accRGB, inout float accA, inout float smear, + inout vec3 accN, inout float accTr, inout float accM) +{ + float mt = clamp((age - hold) / meltT, 0.0, 1.0); // 0 = dry, 1 = melted away + float melt = smoothstep(0.0, 1.0, mt); + float fade = 1.0 - smoothstep(0.75, 1.0, mt); // the water spot dries up at the very end + float land = smoothstep(0.0, 0.3, age); // it lands at once (no ghostly fade-in): it just starts small + + float jx = RandF(seed); + float jy = RandF(seed); + vec2 center = (ncell + vec2(jx, jy)) / gridSize; + + float rs = RandF(seed); + float ang = RandF(seed) * 6.2831853; + float flipX = (RandF(seed) < 0.5) ? -1.0 : 1.0; + float kind = RandF(seed); + float tone = mix(0.94, 1.04, RandF(seed)); + bool slider = RandF(seed) < slideShare; + float slideLen = mix(0.8, 1.0, RandF(seed)) * min(snow_slide_len, 2.4) / gridSize; + bool clumper = RandF(seed) < snow_clump_share; // this flake sticks to its neighbours (else it stays on its own) + float aniso = mix(0.62, 1.0, RandF(seed)); // flakes are never round: random squash after rotation + + float szMax = slider ? SNOW_SLIDER_MAX : SNOW_SIZE_MAX; + float size = mix(SNOW_SIZE_MIN, szMax, rs * rs) / gridSize * sizeMul * mix(0.45, 1.0, smoothstep(0.0, max(hold * 0.25, 1.0), age)) * mix(1.0, 0.85, melt); // grows as snow piles onto it + + // a sliding flake runs down while it melts and stretches into a drip + float slideP = slider ? smoothstep(0.05, 1.0, mt) : 0.0; +#if SNOW_FLIP_Y + center.y += slideLen * slideP * slideP; +#else + center.y -= slideLen * slideP * slideP; +#endif + float stretchY = 1.0 + 0.9 * slideP; + + vec2 d = (f_coord - center) * aspect; + d.y /= stretchY; + + // the 'snow mass' of this flake: neighbouring flakes add up, and where the sum is high they have run into one patch + { + float kr = min(size * 0.5 * SNOW_MERGE_R, 1.0 / gridSize); // (1 cell: the search only covers the 3x3 cells around the pixel) + float m = 1.0 - smoothstep(0.0, kr, length(d)); + if (clumper) + accM += m * m * (3.0 - 2.0 * m) * (1.0 - 0.6 * melt) * snow_clump * land; + } + + // blur only around the water of a melting flake (and, optionally, a little around fresh ones) + float haloR = size * 0.5 * SNOW_HALO_SCALE; + float dist = length(d); + if (dist < haloR) + { + float ring = 1.0 - smoothstep(0.35 * haloR, haloR, dist); + smear = max(smear, ring * land * (melt * snow_melt_blur + (1.0 - melt) * snow_fresh_blur)); + } + + float c = cos(ang); + float s = sin(ang); + vec2 r = vec2(c * d.x + s * d.y, -s * d.x + c * d.y); + r.x *= flipX / aniso; + + vec2 local = r / size + 0.5; + if (any(lessThan(local, vec2(0.0))) || any(greaterThan(local, vec2(1.0)))) + return; + + float lod = clamp(log2(max(pixelUV / size * 0.5 * float(textureSize(raindropsatlas, 0).x), 1.0)), 0.0, 4.0); + + // dry flake (tiles 0..2: fluffy, wet lump, crumbs) and, while melting, its water spot (tile 3) + vec2 off0 = (kind < 0.40) ? vec2(0.0, 0.5) : ((kind < 0.72) ? vec2(0.5, 0.5) : vec2(0.0, 0.0)); + vec2 off3 = vec2(0.5, 0.0); + vec4 t0 = textureLod(raindropsatlas, off0 + local * 0.5, lod); + vec4 n0 = textureLod(normalmap, off0 + local * 0.5, lod); + float a0 = t0.a * (1.0 - melt); + float a3 = 0.0; + vec4 t3 = vec4(0.0); + vec4 n3 = vec4(0.5, 0.5, 0.0, 0.0); + if (melt > 0.001) + { + t3 = textureLod(raindropsatlas, off3 + local * 0.5, lod); + n3 = textureLod(normalmap, off3 + local * 0.5, lod); + a3 = t3.a * smoothstep(0.0, 0.5, melt) * fade; + } + + float aSum = a0 + a3; + float a = clamp(aSum * land * snow_opacity * opacityMul, 0.0, 1.0); + if (a <= 0.0) + return; + vec3 col = (t0.rgb * a0 + t3.rgb * a3) / max(aSum, 1e-4); + vec2 nxy = ((n0.rg * 2.0 - 1.0) * a0 + (n3.rg * 2.0 - 1.0) * a3) / max(aSum, 1e-4); + nxy *= snow_bump * land; + nxy.x *= flipX; + vec2 nuv = vec2(c * nxy.x - s * nxy.y, s * nxy.x + c * nxy.y); + vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); + + // thin snow lets light through: the dry part is translucent, the water spot is not + float tr = (a0 / max(aSum, 1e-4)) * (1.0 - t0.a * 0.55); + + accRGB = col * tone * a + accRGB * (1.0 - a); + accN = nT * a + accN * (1.0 - a); + accTr = tr * a + accTr * (1.0 - a); + accA = a + accA * (1.0 - a); +} + +// Adds one layer of flakes to the premultiplied accumulators. Same scheme as the drops of rain_windscreen: +// the cells around the pixel (a few more above it, for the flakes that slide down), the wipers decide per cell whether it +// is clear, the precipitation intensity decides whether the cell carries a flake right now. +void snowLayer(float gridSize, float density, uint layerSeed, float sizeMul, float opacityMul, float slideShare, int rowsUp, + float pixelUV, vec2 aspect, + inout vec3 accRGB, inout float accA, inout float smear, + inout vec3 accN, inout float accTr, inout float accM) +{ + vec2 cell = floor(f_coord * gridSize); + float heavy = clamp(rain_params.x, 0.0, 1.0); + float hold = snow_hold * (1.0 + 1.5 * heavy); // in heavy snow there is no time to melt + float meltT = max(snow_melt, 1.0); + float life = hold + meltT; + float occupancy = mix(0.70, 0.97, heavy); // share of the time a cell holds a flake + float cycBase = life / occupancy; + float share = clamp(pow(rain_params.x, 0.8) * snow_gain, 0.0, 1.0) * density; + + // flakes slide upwards in UV if SNOW_FLIP_Y: search the rows on the other side +#if SNOW_FLIP_Y + int oyMin = -1 - rowsUp; + int oyMax = 1; +#else + int oyMin = -1; + int oyMax = 1 + rowsUp; +#endif + + for (int oy = oyMin; oy <= oyMax; oy++) { + for (int ox = -1; ox <= 1; ox++) { + + vec2 ncell = cell + vec2(float(ox), float(oy)); + uvec2 ucell = uvec2(ivec2(ncell)); + + float side; + float mixFactor = GetMixFactor((ncell + 0.5) / gridSize, side); + + // timing of this cell: the same in every round + uint tseed = Hash(uvec3(ucell, layerSeed + 31u)); + float cyc = cycBase * (1.0 + mix(0.45, 0.03, heavy) * RandF(tseed)); // in heavy snow the cells hardly ever stand empty + float tOff = RandF(tseed) * cyc; + float patchMul = mix(0.7, 1.3, RandF(tseed)); + float tl = time + tOff; + float rnd = floor(tl / cyc); + float age = tl - rnd * cyc; // seconds since this round's flake landed + if (age > life) + continue; + + // a new flake (position, shape, size) every round; the wiper stroke is part of the seed, as in the rain + uint seed = Hash(uvec3(ucell, layerSeed + uint(side) * 7919u + uint(max(rnd, 0.0)) * 2654435u)); + + if (mixFactor < RandF(seed)) + continue; // wiped / still regrowing + + float activate = RandF(seed); + if (activate > share * patchMul) + continue; + + snowFlake(ncell, seed, age, gridSize, pixelUV, aspect, sizeMul, opacityMul, hold, meltT, slideShare, + accRGB, accA, smear, accN, accTr, accM); + } + } +} + +// Snow patches: a crusty white sheet with the structure of real snow (lumps, grain, thin translucent edges, holes). +// WHERE it grows is decided by the flakes: the 'snow mass' of the flakes that stick together (accM) pushes the sheet up, so a patch starts +// where several flakes landed close to each other, spreads from there in an irregular shape and keeps growing while more flakes land +// next to it; when they melt or slide away it breaks up into holes. It is drawn UNDER the flakes. +// Snow patches built from 'pach pach pach' accretion: every big cell carries a patch that is a heap of 22 small clumps (about flake sized). +// The clumps pop up one after another (the ones near the middle first, so the patch spreads outwards) and each lands at once, as a ragged +// piece that merges with the pieces already there. How fast that goes depends on the snowfall intensity (growT); left alone the pieces +// overlap into a closed sheet. Regions of the glass start at different moments. Returns f > 0 inside the snow (f = depth in sheet cells). +float snowSheetField(float gridSize) +{ + float sg = gridSize * 0.19; + vec2 pg = f_coord * sg; + vec2 cell = floor(pg); + float heavy = clamp(rain_params.x, 0.0, 1.0); + float growT = mix(snow_grow_slow, snow_grow_fast, pow(heavy, 0.5)); + float hold = snow_hold * (1.0 + 1.5 * heavy); + float meltT = max(snow_melt, 1.0); + float life = growT + hold + meltT; + float occupancy = mix(0.80, 0.97, heavy); + float cycBase = life / occupancy; + float share = clamp(heavy * 1.6, 0.0, 1.0) * 0.95 + 0.05 * heavy; // share of the cells that carry a patch (1.0 = none, ~1.6 = nearly all) + + // wiper: pixel precise. The sheet at a pixel is no older than the last wipe of that pixel. + float sidePx; + float mixPx = GetMixFactor(f_coord, sidePx); + float wipeAgePx = snWipeSince; + + float acc = 0.0; // summed clump kernels (metaballs): touching clumps merge, no scalloped circles + for (int oy = -1; oy <= 1; oy++) { + for (int ox = -1; ox <= 1; ox++) { + vec2 ncell = cell + vec2(float(ox), float(oy)); + uvec2 ucell = uvec2(ivec2(ncell)); + + uint tseed = Hash(uvec3(ucell, 211u)); + float cyc = cycBase * (1.0 + mix(0.45, 0.03, heavy) * RandF(tseed)); + float tOff = RandF(tseed) * cyc; + float tl = time + tOff; + float rnd = floor(tl / cyc); + float age = tl - rnd * cyc; + if (age > life) + continue; + + uint seed = Hash(uvec3(ucell, 223u + uint(sidePx) * 7919u + uint(max(rnd, 0.0)) * 2654435u)); + if (RandF(seed) > share) + continue; + + vec2 c = ncell + vec2(0.1 + 0.8 * RandF(seed), 0.1 + 0.8 * RandF(seed)); + vec2 dc = pg - c; + if (dot(dc, dc) > 1.2 * 1.2) + continue; // too far from this patch to be touched by any of its clumps + + age = min(age, wipeAgePx); + float delay = snNoise(c * 0.30 + 3.7) * growT * 0.35; // regions of the glass start at different moments + float ga = max(age - delay, 0.0); + float mt = clamp((age - growT - hold) / meltT, 0.0, 1.0); + float shrink = 1.0 - 1.1 * mt * mt; // melting: the clumps shrink and holes open + + for (int i = 0; i < 22; i++) { + uint bs = Hash(uvec3(seed, uint(i), 977u)); + float rho = RandF(bs); + float an = RandF(bs) * 6.2831853; + float rad = 0.85 * sqrt(rho); + vec2 bp = c + rad * vec2(cos(an), sin(an)); + float rb = mix(0.17, 0.30, RandF(bs)); + float ti = growT * (0.03 + 0.97 * pow(rad / 0.85, 0.9) * mix(0.70, 1.0, RandF(bs))); // inner clumps first + // each clump arrives in three small portions (pop, pop, pop): 45% -> 72% -> 100% of its size, no fading + float dT = growT * 0.10; + float stg = step(ti, ga) + step(ti + dT, ga) + step(ti + 2.0 * dT, ga); // 0..3 + if (stg <= 0.0) + continue; + float rr = rb * shrink * (stg < 1.5 ? 0.45 : (stg < 2.5 ? 0.72 : 1.0)); + float kd = max(1.0 - length(pg - bp) / max(rr * 1.35, 1e-3), 0.0); + acc += kd * kd * (3.0 - 2.0 * kd); + } + } + } + // torn, crumbly edge: fine noise (features about a flake wide) decides where the summed clumps stop, so the outline is irregular + // snow and not a ring of circles + float nz = snFbm(pg * 5.5 + 13.0) * 0.45 + snFbm(pg * 13.0 + 7.0) * 0.35 + snFbm(pg * 31.0 + 3.0) * 0.20 - 0.5; + float best = (acc - 0.50) * 0.20 + nz * 0.30; + best -= (1.0 - smoothstep(0.0, 0.12, mixPx)) * 1.0; // swept (or still regrowing) areas + return best; +} + +void snowFilm(float gridSize, inout vec3 accRGB, inout float accA, inout vec3 accN, inout float accTr) +{ +#if SNOW_FLIP_Y + float dir = -1.0; +#else + float dir = 1.0; +#endif + float sf = snowSheetField(gridSize); + snHaze = max(snHaze, smoothstep(-0.045, 0.0, sf)); // the glass next to a patch is frosted a little as well + float cover = smoothstep(0.0, 0.03, sf); + if (cover <= 0.002) + return; + float thick = smoothstep(0.0, 0.11, sf); // 0 at the thin edge, 1 in the thick middle + vec2 p = f_coord * gridSize * 0.17 + vec2(0.0, dir * time * 0.008); + vec2 q = f_coord * gridSize * 2.6; + float h0 = snFbm(p); + + // lumpy surface: big drifts + fine grain + float f1 = snFbm(q); + float e = 0.06; + float ef = 0.05; + vec2 g = vec2(snFbm(p + vec2(e, 0.0)) - h0, snFbm(p + vec2(0.0, e)) - h0) / e; + vec2 gf = vec2(snFbm(q + vec2(ef, 0.0)) - f1, snFbm(q + vec2(0.0, ef)) - f1) / ef; + vec3 nT = normalize(vec3(-(g * 0.55 + gf * 0.20) * snow_bump, 1.0)); + + vec3 thin = vec3(0.66, 0.72, 0.80); // thin snow is greyish-blue and lets the dark background through + vec3 full = vec3(0.93, 0.95, 0.98); + vec3 col = mix(thin, full, thick) * (0.62 + 0.55 * f1) * (0.88 + 0.22 * snNoise(f_coord * gridSize * 9.0)) * (0.85 + 0.3 * h0); + float a = clamp(cover * mix(0.50, 0.96, thick) * snow_pack * snow_opacity, 0.0, 0.97); + float under = 1.0 - accA; + accRGB = accRGB + col * a * under; + accN = accN + nT * a * under; + accTr = accTr + mix(0.60, 0.30, thick) * a * under; + accA = accA + a * under; +} + +void main() +{ + // Derivatives first, in uniform control flow (no discard before them). + vec3 Ngl = normalize(f_normal); + vec3 dp1 = dFdx(f_pos.xyz); + vec3 dp2 = dFdy(f_pos.xyz); + vec2 duv1 = dFdx(f_coord); + vec2 duv2 = dFdy(f_coord); + vec3 dp2perp = cross(dp2, Ngl); + vec3 dp1perp = cross(Ngl, dp1); + vec3 Tgl = dp2perp * duv1.x + dp1perp * duv2.x; + vec3 Bgl = dp2perp * duv1.y + dp1perp * duv2.y; + float invmax = inversesqrt(max(max(dot(Tgl, Tgl), dot(Bgl, Bgl)), 1e-20)); + Tgl *= invmax; + Bgl *= invmax; + + vec4 tex_color = texture(diffuse, f_coord); // no discard: clean glass between faint dirt must still get snow and blur + + float gridSize = max(ceil(param[2].x), 1.0); + float pixelUV = max(length(dFdx(f_coord)), length(dFdy(f_coord))); + snHaze = 0.0; + vec2 aspect = (snow_uv_aspect >= 1.0) ? vec2(snow_uv_aspect, 1.0) : vec2(1.0, 1.0 / max(snow_uv_aspect, 0.01)); + + vec3 snowRGB = vec3(0.0); // premultiplied + float snowA = 0.0; + float smear = 0.0; + vec3 snowN = vec3(0.0); + float snowTr = 0.0; + if (rain_params.x > 0.0) + { + float mass = 0.0; + if (snow_small > 0.0) + snowLayer(gridSize * 2.4 / snow_flake_scale, snow_small, 17u, 0.9, 0.85, 0.0, 0, pixelUV, aspect, snowRGB, snowA, smear, snowN, snowTr, mass); + snowLayer(gridSize / snow_flake_scale, snow_density, 13u, 1.0, 1.0, snow_slide_share, 4, pixelUV, aspect, snowRGB, snowA, smear, snowN, snowTr, mass); + if (snow_pack > 0.0) + snowFilm(gridSize, snowRGB, snowA, snowN, snowTr); // patches where flakes have run together + } + + float glassA = tex_color.a * alpha_mult; + float finalA = snowA + glassA * (1.0 - snowA); + vec3 premult = snowRGB + tex_color.rgb * glassA * (1.0 - snowA); + vec3 albedo = premult / max(finalA, 1e-4); + float glassShare = glassA * (1.0 - snowA) / max(finalA, 1e-4); + + // relief: tilt the glass normal by the slope of the snow (flat where there is none) + vec3 nDir = snowN + vec3(0.0, 0.0, 1.0) * (1.0 - snowA); + vec3 fragnormal = Ngl; + if (snowA > 0.001) + fragnormal = normalize(Ngl * max(nDir.z, 0.05) + Tgl * nDir.x + Bgl * nDir.y); + + vec3 fragcolor = ambient; + float reflectivity = param[1].z * glassShare; + float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5 * glassShare + snow_gloss * snowA; + legacy_gloss(); + + // most of the glass is clear (no snow, a clear glass texture): the lighting of the 4.6 renderers (the clusters of lamps, the + // shadows, the reflections) is skipped there, it would be multiplied by an alpha of ~0 + if (finalA > 0.002) + fragcolor = apply_lights(fragcolor, fragnormal, albedo, reflectivity, specularity, shadow_tone); + + // thin snow glows when you look towards the sun / a lamp + if (finalA > 0.002 && snowA > 0.001 && snow_translucency > 0.0 && lights_count > 0U) + { + vec3 I = normalize(f_pos.xyz); + float shadowSun = 0.0; + if (shadow_tone < 1.0) + shadowSun = (1.0 - shadow_tone) * clamp(calc_shadow(), 0.0, 1.0); + float towards = max(dot(I, normalize(-lights[0].dir)), 0.0); + float glow = pow(towards, 3.0) * (1.0 - shadowSun); + fragcolor += lights[0].color * lights[0].intensity * glow * snow_translucency * snowTr * albedo * snowA; + } + vec3 lit = apply_fog(fragcolor); + +#if SNOW_MATCH_RAIN_GLASS + vec4 color = vec4(lit * finalA, finalA); +#else + vec4 color = vec4(lit, finalA); +#endif + + out_color = POSTFX_ENABLED ? color : tonemap(color); + + // the scene seen through the snow, drawn by the post-processing (rain_windscreen_haze.glsl), asked for in the velocity target as + // rain_windscreen asks: thin snow bends it (its relief refracts; x, y = WS_DROP_BIAS + WS_BEND_ENC * bend), elsewhere it's blurred in + // and around thin snow and around the melting spots (x = WS_ENC * strength, y = 0); the snow itself stays sharp. alpha 0 elsewhere: + // the blending keeps the motion of the scene behind + if (MOTIONBLUR_ENABLED) + { + float thin = smoothstep(0.04, 0.20, snowA) * (1.0 - smoothstep(0.55, 0.90, snowA)); + vec4 req = vec4(0.0); + if ((snow_distort > 0.0) && (thin > 0.30) && (glassA < 0.5)) + { + vec2 slope = snowN.xy / max(snowA, 1e-3); + vec2 bend = clamp(-slope * snow_distort, vec2(-1.0), vec2(1.0)) * smoothstep(0.30, 0.60, thin) * (SNOW_REFR_MAXPX / WS_REFR_MAXPX); + req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); + } + else + { + float haze = snHaze * snow_haze * (1.0 - smoothstep(0.30, 0.80, snowA)); // frosted glass in and around thin snow + float blurMask = clamp(max(smear * (1.0 - snowA), haze) * (1.0 - smoothstep(0.5, 0.95, glassA)), 0.0, 1.0); + if (blurMask >= 0.01) + req = vec4(WS_ENC * blurMask, 0.0, 0.0, 1.0); + } + out_motion = req; + } +} + +float GetMixFactor(in vec2 co, out float side) { + vec4 movePhase = wiper_pos; + bvec4 is_out = lessThanEqual(movePhase, vec4(1.)); + movePhase = mix(vec4(2.) - movePhase, movePhase, is_out); + + vec4 mask = textureLod(wipermask, co, 0.0); // called from non-uniform flow: no implicit derivatives + + vec4 areaMask = step(.001, mask); + + vec4 maskVal = mix(1. - mask, mask, is_out); + vec4 wipeWidth = smoothstep(1., .9, movePhase) * .25; + vec4 cleaned = smoothstep(movePhase - wipeWidth, movePhase, maskVal) * areaMask; + vec4 side_v = step(maskVal, movePhase); + cleaned *= side_v; + side_v = mix(side_v, vec4(1.) - side_v, is_out); + + // "regeneration", snow gradually returning after a wiper pass (slower than rain, and faster in heavy snowfall): + float regenT = max(mix(snow_regen, snow_regen * 0.6, clamp(rain_params.x, 0.0, 1.0)), 0.5); + vec4 sinceV = vec4(time) - mix(wiper_timer_out, wiper_timer_return, side_v) - vec4(.2); + vec4 regenPhase = clamp(sinceV / vec4(regenT), vec4(0.), vec4(1.)); + + side_v = mix(vec4(0.), vec4(1.) - side_v, areaMask); + + vec4 factor_v = mix(vec4(1.), regenPhase * (vec4(1.) - cleaned), areaMask); + + side = 0.; + float out_factor = 1.; + bool have_side = false; + snWipeSince = 1.0e5; + + // out_factor: the blade that clears the grid cell the most wins (as before). + // side: which wiper stroke the drops of this cell belong to. It is part of the random + // seed of every drop, so it must NOT depend on out_factor. It used to: once the drops had + // fully regrown (out_factor == 1) side fell back to 0 and every drop in the swept area + // jumped to a new position, about one regrow time after each stroke (most visible in + // heavy rain, where regrowth takes ~1 s). + for(int i = 0; i < 4; ++i) + { + out_factor = min(out_factor, factor_v[i]); + if (!have_side && areaMask[i] > 0.) + { + side = side_v[i]; + snWipeSince = max(sinceV[i], 0.0); + have_side = true; + } + } + + return out_factor; +} diff --git a/shaders/ogl46/rain_cells.glsl b/shaders/ogl46/rain_cells.glsl index 52e248032..843aaa496 100644 --- a/shaders/ogl46/rain_cells.glsl +++ b/shaders/ogl46/rain_cells.glsl @@ -53,7 +53,7 @@ const float drop_life_min = 14.0; // seconds a drop sits on the glass const float drop_life_max = 45.0; const float drop_appear = 0.18; // seconds of the landing "pop" const float drop_fade = 1.5; // seconds a drop takes to vanish at the end of its life -const float wiper_miss = 0.05; // share of the drops a blade goes over without taking them +const float wiper_miss = 0.0167; // share of the drops a blade goes over without taking them (a third of the 0.05 it was) const float streak_period = 40.0; // seconds a rivulet lives (it runs for ~90% of that and then fades out), average const float wind_streak_period = 18.0; // seconds a rivulet driven by the air lives (they run faster than the ones of gravity) diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag new file mode 100644 index 000000000..8a81a1ee8 --- /dev/null +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -0,0 +1,604 @@ +#version 460 core +#define STAGE_FRAGMENT 1 +#include "common.glsl" +// Windscreen snow: replaces rain_windscreen when it snows - v2 (OpenGL 4.6 / Vulkan 1.4 port of the OpenGL 3.3 v1) +// v2: the syntax of the 4.6 renderers (explicit locations and bindings, #pragma texture / param), the tuning values as constants +// (a uniform can't have a default any more); the blur of the scene and the picture bent by thin snow go to the +// post-processing through the velocity target, as the haze and the drops of rain_windscreen (postfx_taa.frag / +// postfx_motionblur.frag with rain_windscreen_haze.glsl); the colour is written straight +// (not premultiplied) as rain_windscreen of the 4.6 renderers writes the glass; the gloss of the glass from legacy_gloss(); +// no lighting where the glass is clear (no snow, a clear texture). the look and the behaviour of the snow are those of v1. +// +// MaSzyna switches the weather itself (simulationenvironment.cpp): with Overcast > 1 it rains when the air is warmer +// than 1 deg C and it SNOWS at 1 deg C and below, and the .mat block "snow:" is picked. rain_params.x is the +// precipitation intensity (saturate(Overcast - 1)), exactly what rain_windscreen uses for the drops, so the snow +// on the glass follows the snowfall: nothing without snow, and the harder it snows the more the glass gets plastered. +// +// - flakes: every cell of the glass can hold a flake (atlas tiles 0..2: fluffy, wet lump, crumbs). It lands at a random +// moment, stays white for `snow_hold` seconds and then MELTS for `snow_melt` seconds: the snow fades into a water spot +// (tile 3). About `snow_slide_share` of the melting flakes also SLIDE DOWN the glass, stretching into a drip. +// Only the wet, melting spot blurs the scene (water refracts; dry snow does not, see snow_fresh_blur). +// - clumping: flakes land small and GROW as more snow piles onto them. Where flakes land next to each other they run together +// into one bigger patch (a crusty white film), and the more it snows the more flakes land side by side, so the bigger +// the patches get. The patch exists only where flakes really sit close together; when they melt / slide away it breaks +// up and thins out (snow_clump). +// - wipers (wipermask, GetMixFactor) clear all of it; it builds up again after `snow_regen` seconds (faster in heavy snow). +// Nothing depends on the time since the game started. +// +// Atlas / normalmap (blender_snow_atlas.py), 2 x 2 tiles: +// 0 dry fluffy flake 1 wet compact lump 2 crumbs 3 melted spot (water + ice remnants) +// +// .mat: +// +// texture_diffuse: dynamic/pkp/vectron_v1/cab/szyby +// texture_raindropsatlas: textures/fx/raindrops-atlas +// texture_normalmap: textures/fx/raindrops_normalmap +// texture_wipermask: dynamic/pkp/vectron_v1/cab/szyby_wipermask +// shader: rain_windscreen +// param_raindrop_grid_size: 150 +// +// snow: { +// shader: snow_windscreen +// texture_raindropsatlas: textures/fx/snow-atlas +// texture_normalmap: textures/fx/snow_normalmap +// param_raindrop_grid_size: 70 +// } +// +// One cell is about one flake: a grid of ~50-90 gives flakes of ~1-2 cm on a ~1.5 m windscreen. + +layout(location = 0) in vec3 f_normal; +layout(location = 2) in vec2 f_coord; +layout(location = 3) in vec4 f_pos; +layout(location = 4) in vec4 f_clip_pos; +layout(location = 5) in vec4 f_clip_future_pos; + +layout(location = 0) out vec4 out_color; +#ifdef NO_MOTION_OUTPUT +// a pass without the velocity target: the writes go nowhere +vec4 out_motion; +#else +layout(location = 1) out vec4 out_motion; +#endif + +#pragma texture(diffuse, 0, sRGB_A) +#pragma texture(raindropsatlas, 1, sRGB_A) +#pragma texture(wipermask, 2, sRGB_A) +#pragma texture(normalmap, 3, RGBA) // flakes: rg = normal xy, b = height, a = mask; same 2x2 layout as raindropsatlas (linear) +#pragma param(color, 0, 0, 4, diffuse) +#pragma param(diffuse, 1, 0, 1, diffuse) +#pragma param(specular, 1, 1, 1, specular) +#pragma param(reflection, 1, 2, 1, zero) +#pragma param(glossiness, 1, 3, 1, glossiness) +#pragma param(raindrop_grid_size, 2, 0, 1, one) + +#include "light_common.glsl" +#include "apply_fog.glsl" +#include "tonemapping.glsl" +#include "random.glsl" + +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 0) uniform sampler2D diffuse; +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 1) uniform sampler2D raindropsatlas; +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 2) uniform sampler2D wipermask; +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 3) uniform sampler2D normalmap; + +// --- Tuning ----------------------------------------------------------------- +// Intensity = rain_params.x = saturate(Overcast - 1). The slider range 1.00..2.00 (Overcast) maps to intensity 0..1. The share of flake cells is pow(intensity, 0.8) * snow_gain * snow_density, +// so with the defaults every cell carries a flake from Overcast ~ 1.2 and the film closes the glass at about 1.3 (1.1 = light snow, 1.5+ = blizzard). +const float snow_gain = 1.4; // how fast the glass gets covered when the snowfall gets heavier (higher = already plastered in light snow) +const float snow_density = 0.95; // upper limit of the share of cells that carry a big flake +const float snow_small = 0.80; // same for the layer of small flakes (0 = off) +const float snow_pack = 0.90; // opacity of the patches that form where flakes clump together (0 = no patches) +const float snow_clump = 2.60; // how readily neighbouring flakes run together into one patch (higher = patches form sooner and get bigger) +const float snow_clump_share = 0.55; // share of the flakes that run together into patches; the rest stay separate flakes +const float snow_hold = 40.0; // seconds a flake stays white before it starts to melt (longer in heavy snow) +const float snow_melt = 30.0; // seconds the melting takes (snow fades into a water spot) +const float snow_slide_share = 0.40; // share of the melting flakes that run down the glass +const float snow_slide_len = 2.0; // how far a sliding flake runs, in cells (max 2.4) +const float snow_grow_fast = 5.3; // seconds a patch needs to grow from a clump to a big sheet in the heaviest snowfall +const float snow_grow_slow = 46.7; // same in the lightest snowfall (it still gets there, just much later) +const float snow_haze = 1.0; // blur of the scene behind and around the snow patches (frosted glass), 0 = off, 1 = full (radius: windscreen_view.glsl) +const float snow_distort = 2.0; // picture distortion seen through thin snow (refraction by its relief), 0 = off +const float snow_flake_scale = 2.5; // size of the flakes from the atlas relative to one grid cell (2-3 = two to three times bigger than before; the flakes get fewer) +const float snow_regen = 25.0; // seconds until snow is back on a wiped area (in light snowfall) +const float snow_opacity = 1.0; // overall opacity +const float snow_uv_aspect = 1.0; // glass width / height in the world if the UV is stretched +const float snow_bump = 1.0; // strength of the 3D relief from the normal map, 0 = flat +const float snow_gloss = 0.45; // glints of the sun / headlights on the snow, 0 = matt +const float snow_translucency = 0.8; // glow of thin snow when you look towards the sun / a lamp, 0 = off +const float snow_melt_blur = 0.8; // blur of the scene around the water spots of melting flakes (0 = off, 1 = full) +const float snow_fresh_blur = 0.0; // blur around fresh dry flakes: physically there is none, a little (0.1-0.2) fakes light scattering + +#ifndef SNOW_FLIP_Y +#define SNOW_FLIP_Y 0 // set to 1 if sliding flakes run UP the glass (the glass UV then has v growing downwards) +#endif +const float SNOW_SIZE_MIN = 0.70; // flake size in grid cells (keep max <= 1.8, the search covers 3x3 cells) +const float SNOW_SIZE_MAX = 1.50; +const float SNOW_SLIDER_MAX = 1.10; // a flake that slides is smaller than this (it gets stretched on its way down) +const float SNOW_HALO_SCALE = 1.5; // blur ring radius = flake half-size * this +const float SNOW_LAND_TIME = 1.5; // seconds a flake takes to land and settle +const float SNOW_REFR_MAXPX = 96.0; // the largest picture shift of thin snow, screen pixels +const float WS_REFR_MAXPX = 96.0; // the largest picture shift the post-processing makes, screen pixels; must match rain_windscreen_haze.glsl +const float WS_BEND_ENC = 60.0; // the bend request in the velocity target; must match rain_windscreen_haze.glsl +const float WS_DROP_BIAS = 192.0; +const float WS_ENC = 64.0; // the haze request in the velocity target; must match rain_windscreen_haze.glsl +const float SNOW_REFR_MIX = 0.85; // 0 = no refraction, 1 = only the bent picture + +#ifndef SNOW_MATCH_RAIN_GLASS +#define SNOW_MATCH_RAIN_GLASS 0 // 4.6: rain_windscreen writes the glass straight, not premultiplied +#endif + +float snHaze = 0.0; // set by snowFilm: 1 inside / next to a snow patch (drives the frosted-glass blur) +float snWipeSince = 1.0e5; // set by GetMixFactor: seconds since the wiper last cleaned this spot +float GetMixFactor(in vec2 co, out float side); + +const float SNOW_MERGE_R = 2.0; // reach of a flake's 'snow mass' in flake half-sizes (flakes closer than this run together) +const float SNOW_CLUMP_THR = 0.80; // summed mass above which the glass is covered + +float snHash(vec2 p) +{ + return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); +} + +float snNoise(vec2 p) +{ + vec2 i = floor(p); + vec2 f = fract(p); + f = f * f * (3.0 - 2.0 * f); + return mix(mix(snHash(i), snHash(i + vec2(1.0, 0.0)), f.x), + mix(snHash(i + vec2(0.0, 1.0)), snHash(i + vec2(1.0, 1.0)), f.x), f.y); +} + +float snFbm(vec2 p) +{ + float a = 0.5; + float v = 0.0; + for (int i = 0; i < 4; ++i) + { + v += a * snNoise(p); + p = p * 2.07 + vec2(17.3, 9.1); + a *= 0.5; + } + return v / 0.9375; +} + +// One flake in one cell. `age` = seconds since it landed. +void snowFlake(vec2 ncell, uint seed, float age, float gridSize, float pixelUV, vec2 aspect, + float sizeMul, float opacityMul, float hold, float meltT, float slideShare, + inout vec3 accRGB, inout float accA, inout float smear, + inout vec3 accN, inout float accTr, inout float accM) +{ + float mt = clamp((age - hold) / meltT, 0.0, 1.0); // 0 = dry, 1 = melted away + float melt = smoothstep(0.0, 1.0, mt); + float fade = 1.0 - smoothstep(0.75, 1.0, mt); // the water spot dries up at the very end + float land = smoothstep(0.0, 0.3, age); // it lands at once (no ghostly fade-in): it just starts small + + float jx = RandF(seed); + float jy = RandF(seed); + vec2 center = (ncell + vec2(jx, jy)) / gridSize; + + float rs = RandF(seed); + float ang = RandF(seed) * 6.2831853; + float flipX = (RandF(seed) < 0.5) ? -1.0 : 1.0; + float kind = RandF(seed); + float tone = mix(0.94, 1.04, RandF(seed)); + bool slider = RandF(seed) < slideShare; + float slideLen = mix(0.8, 1.0, RandF(seed)) * min(snow_slide_len, 2.4) / gridSize; + bool clumper = RandF(seed) < snow_clump_share; // this flake sticks to its neighbours (else it stays on its own) + float aniso = mix(0.62, 1.0, RandF(seed)); // flakes are never round: random squash after rotation + + float szMax = slider ? SNOW_SLIDER_MAX : SNOW_SIZE_MAX; + float size = mix(SNOW_SIZE_MIN, szMax, rs * rs) / gridSize * sizeMul * mix(0.45, 1.0, smoothstep(0.0, max(hold * 0.25, 1.0), age)) * mix(1.0, 0.85, melt); // grows as snow piles onto it + + // a sliding flake runs down while it melts and stretches into a drip + float slideP = slider ? smoothstep(0.05, 1.0, mt) : 0.0; +#if SNOW_FLIP_Y + center.y += slideLen * slideP * slideP; +#else + center.y -= slideLen * slideP * slideP; +#endif + float stretchY = 1.0 + 0.9 * slideP; + + vec2 d = (f_coord - center) * aspect; + d.y /= stretchY; + + // the 'snow mass' of this flake: neighbouring flakes add up, and where the sum is high they have run into one patch + { + float kr = min(size * 0.5 * SNOW_MERGE_R, 1.0 / gridSize); // (1 cell: the search only covers the 3x3 cells around the pixel) + float m = 1.0 - smoothstep(0.0, kr, length(d)); + if (clumper) + accM += m * m * (3.0 - 2.0 * m) * (1.0 - 0.6 * melt) * snow_clump * land; + } + + // blur only around the water of a melting flake (and, optionally, a little around fresh ones) + float haloR = size * 0.5 * SNOW_HALO_SCALE; + float dist = length(d); + if (dist < haloR) + { + float ring = 1.0 - smoothstep(0.35 * haloR, haloR, dist); + smear = max(smear, ring * land * (melt * snow_melt_blur + (1.0 - melt) * snow_fresh_blur)); + } + + float c = cos(ang); + float s = sin(ang); + vec2 r = vec2(c * d.x + s * d.y, -s * d.x + c * d.y); + r.x *= flipX / aniso; + + vec2 local = r / size + 0.5; + if (any(lessThan(local, vec2(0.0))) || any(greaterThan(local, vec2(1.0)))) + return; + + float lod = clamp(log2(max(pixelUV / size * 0.5 * float(textureSize(raindropsatlas, 0).x), 1.0)), 0.0, 4.0); + + // dry flake (tiles 0..2: fluffy, wet lump, crumbs) and, while melting, its water spot (tile 3) + vec2 off0 = (kind < 0.40) ? vec2(0.0, 0.5) : ((kind < 0.72) ? vec2(0.5, 0.5) : vec2(0.0, 0.0)); + vec2 off3 = vec2(0.5, 0.0); + vec4 t0 = textureLod(raindropsatlas, off0 + local * 0.5, lod); + vec4 n0 = textureLod(normalmap, off0 + local * 0.5, lod); + float a0 = t0.a * (1.0 - melt); + float a3 = 0.0; + vec4 t3 = vec4(0.0); + vec4 n3 = vec4(0.5, 0.5, 0.0, 0.0); + if (melt > 0.001) + { + t3 = textureLod(raindropsatlas, off3 + local * 0.5, lod); + n3 = textureLod(normalmap, off3 + local * 0.5, lod); + a3 = t3.a * smoothstep(0.0, 0.5, melt) * fade; + } + + float aSum = a0 + a3; + float a = clamp(aSum * land * snow_opacity * opacityMul, 0.0, 1.0); + if (a <= 0.0) + return; + vec3 col = (t0.rgb * a0 + t3.rgb * a3) / max(aSum, 1e-4); + vec2 nxy = ((n0.rg * 2.0 - 1.0) * a0 + (n3.rg * 2.0 - 1.0) * a3) / max(aSum, 1e-4); + nxy *= snow_bump * land; + nxy.x *= flipX; + vec2 nuv = vec2(c * nxy.x - s * nxy.y, s * nxy.x + c * nxy.y); + vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); + + // thin snow lets light through: the dry part is translucent, the water spot is not + float tr = (a0 / max(aSum, 1e-4)) * (1.0 - t0.a * 0.55); + + accRGB = col * tone * a + accRGB * (1.0 - a); + accN = nT * a + accN * (1.0 - a); + accTr = tr * a + accTr * (1.0 - a); + accA = a + accA * (1.0 - a); +} + +// Adds one layer of flakes to the premultiplied accumulators. Same scheme as the drops of rain_windscreen: +// the cells around the pixel (a few more above it, for the flakes that slide down), the wipers decide per cell whether it +// is clear, the precipitation intensity decides whether the cell carries a flake right now. +void snowLayer(float gridSize, float density, uint layerSeed, float sizeMul, float opacityMul, float slideShare, int rowsUp, + float pixelUV, vec2 aspect, + inout vec3 accRGB, inout float accA, inout float smear, + inout vec3 accN, inout float accTr, inout float accM) +{ + vec2 cell = floor(f_coord * gridSize); + float heavy = clamp(rain_params.x, 0.0, 1.0); + float hold = snow_hold * (1.0 + 1.5 * heavy); // in heavy snow there is no time to melt + float meltT = max(snow_melt, 1.0); + float life = hold + meltT; + float occupancy = mix(0.70, 0.97, heavy); // share of the time a cell holds a flake + float cycBase = life / occupancy; + float share = clamp(pow(rain_params.x, 0.8) * snow_gain, 0.0, 1.0) * density; + + // flakes slide upwards in UV if SNOW_FLIP_Y: search the rows on the other side +#if SNOW_FLIP_Y + int oyMin = -1 - rowsUp; + int oyMax = 1; +#else + int oyMin = -1; + int oyMax = 1 + rowsUp; +#endif + + for (int oy = oyMin; oy <= oyMax; oy++) { + for (int ox = -1; ox <= 1; ox++) { + + vec2 ncell = cell + vec2(float(ox), float(oy)); + uvec2 ucell = uvec2(ivec2(ncell)); + + float side; + float mixFactor = GetMixFactor((ncell + 0.5) / gridSize, side); + + // timing of this cell: the same in every round + uint tseed = Hash(uvec3(ucell, layerSeed + 31u)); + float cyc = cycBase * (1.0 + mix(0.45, 0.03, heavy) * RandF(tseed)); // in heavy snow the cells hardly ever stand empty + float tOff = RandF(tseed) * cyc; + float patchMul = mix(0.7, 1.3, RandF(tseed)); + float tl = time + tOff; + float rnd = floor(tl / cyc); + float age = tl - rnd * cyc; // seconds since this round's flake landed + if (age > life) + continue; + + // a new flake (position, shape, size) every round; the wiper stroke is part of the seed, as in the rain + uint seed = Hash(uvec3(ucell, layerSeed + uint(side) * 7919u + uint(max(rnd, 0.0)) * 2654435u)); + + if (mixFactor < RandF(seed)) + continue; // wiped / still regrowing + + float activate = RandF(seed); + if (activate > share * patchMul) + continue; + + snowFlake(ncell, seed, age, gridSize, pixelUV, aspect, sizeMul, opacityMul, hold, meltT, slideShare, + accRGB, accA, smear, accN, accTr, accM); + } + } +} + +// Snow patches: a crusty white sheet with the structure of real snow (lumps, grain, thin translucent edges, holes). +// WHERE it grows is decided by the flakes: the 'snow mass' of the flakes that stick together (accM) pushes the sheet up, so a patch starts +// where several flakes landed close to each other, spreads from there in an irregular shape and keeps growing while more flakes land +// next to it; when they melt or slide away it breaks up into holes. It is drawn UNDER the flakes. +// Snow patches built from 'pach pach pach' accretion: every big cell carries a patch that is a heap of 22 small clumps (about flake sized). +// The clumps pop up one after another (the ones near the middle first, so the patch spreads outwards) and each lands at once, as a ragged +// piece that merges with the pieces already there. How fast that goes depends on the snowfall intensity (growT); left alone the pieces +// overlap into a closed sheet. Regions of the glass start at different moments. Returns f > 0 inside the snow (f = depth in sheet cells). +float snowSheetField(float gridSize) +{ + float sg = gridSize * 0.19; + vec2 pg = f_coord * sg; + vec2 cell = floor(pg); + float heavy = clamp(rain_params.x, 0.0, 1.0); + float growT = mix(snow_grow_slow, snow_grow_fast, pow(heavy, 0.5)); + float hold = snow_hold * (1.0 + 1.5 * heavy); + float meltT = max(snow_melt, 1.0); + float life = growT + hold + meltT; + float occupancy = mix(0.80, 0.97, heavy); + float cycBase = life / occupancy; + float share = clamp(heavy * 1.6, 0.0, 1.0) * 0.95 + 0.05 * heavy; // share of the cells that carry a patch (1.0 = none, ~1.6 = nearly all) + + // wiper: pixel precise. The sheet at a pixel is no older than the last wipe of that pixel. + float sidePx; + float mixPx = GetMixFactor(f_coord, sidePx); + float wipeAgePx = snWipeSince; + + float acc = 0.0; // summed clump kernels (metaballs): touching clumps merge, no scalloped circles + for (int oy = -1; oy <= 1; oy++) { + for (int ox = -1; ox <= 1; ox++) { + vec2 ncell = cell + vec2(float(ox), float(oy)); + uvec2 ucell = uvec2(ivec2(ncell)); + + uint tseed = Hash(uvec3(ucell, 211u)); + float cyc = cycBase * (1.0 + mix(0.45, 0.03, heavy) * RandF(tseed)); + float tOff = RandF(tseed) * cyc; + float tl = time + tOff; + float rnd = floor(tl / cyc); + float age = tl - rnd * cyc; + if (age > life) + continue; + + uint seed = Hash(uvec3(ucell, 223u + uint(sidePx) * 7919u + uint(max(rnd, 0.0)) * 2654435u)); + if (RandF(seed) > share) + continue; + + vec2 c = ncell + vec2(0.1 + 0.8 * RandF(seed), 0.1 + 0.8 * RandF(seed)); + vec2 dc = pg - c; + if (dot(dc, dc) > 1.2 * 1.2) + continue; // too far from this patch to be touched by any of its clumps + + age = min(age, wipeAgePx); + float delay = snNoise(c * 0.30 + 3.7) * growT * 0.35; // regions of the glass start at different moments + float ga = max(age - delay, 0.0); + float mt = clamp((age - growT - hold) / meltT, 0.0, 1.0); + float shrink = 1.0 - 1.1 * mt * mt; // melting: the clumps shrink and holes open + + for (int i = 0; i < 22; i++) { + uint bs = Hash(uvec3(seed, uint(i), 977u)); + float rho = RandF(bs); + float an = RandF(bs) * 6.2831853; + float rad = 0.85 * sqrt(rho); + vec2 bp = c + rad * vec2(cos(an), sin(an)); + float rb = mix(0.17, 0.30, RandF(bs)); + float ti = growT * (0.03 + 0.97 * pow(rad / 0.85, 0.9) * mix(0.70, 1.0, RandF(bs))); // inner clumps first + // each clump arrives in three small portions (pop, pop, pop): 45% -> 72% -> 100% of its size, no fading + float dT = growT * 0.10; + float stg = step(ti, ga) + step(ti + dT, ga) + step(ti + 2.0 * dT, ga); // 0..3 + if (stg <= 0.0) + continue; + float rr = rb * shrink * (stg < 1.5 ? 0.45 : (stg < 2.5 ? 0.72 : 1.0)); + float kd = max(1.0 - length(pg - bp) / max(rr * 1.35, 1e-3), 0.0); + acc += kd * kd * (3.0 - 2.0 * kd); + } + } + } + // torn, crumbly edge: fine noise (features about a flake wide) decides where the summed clumps stop, so the outline is irregular + // snow and not a ring of circles + float nz = snFbm(pg * 5.5 + 13.0) * 0.45 + snFbm(pg * 13.0 + 7.0) * 0.35 + snFbm(pg * 31.0 + 3.0) * 0.20 - 0.5; + float best = (acc - 0.50) * 0.20 + nz * 0.30; + best -= (1.0 - smoothstep(0.0, 0.12, mixPx)) * 1.0; // swept (or still regrowing) areas + return best; +} + +void snowFilm(float gridSize, inout vec3 accRGB, inout float accA, inout vec3 accN, inout float accTr) +{ +#if SNOW_FLIP_Y + float dir = -1.0; +#else + float dir = 1.0; +#endif + float sf = snowSheetField(gridSize); + snHaze = max(snHaze, smoothstep(-0.045, 0.0, sf)); // the glass next to a patch is frosted a little as well + float cover = smoothstep(0.0, 0.03, sf); + if (cover <= 0.002) + return; + float thick = smoothstep(0.0, 0.11, sf); // 0 at the thin edge, 1 in the thick middle + vec2 p = f_coord * gridSize * 0.17 + vec2(0.0, dir * time * 0.008); + vec2 q = f_coord * gridSize * 2.6; + float h0 = snFbm(p); + + // lumpy surface: big drifts + fine grain + float f1 = snFbm(q); + float e = 0.06; + float ef = 0.05; + vec2 g = vec2(snFbm(p + vec2(e, 0.0)) - h0, snFbm(p + vec2(0.0, e)) - h0) / e; + vec2 gf = vec2(snFbm(q + vec2(ef, 0.0)) - f1, snFbm(q + vec2(0.0, ef)) - f1) / ef; + vec3 nT = normalize(vec3(-(g * 0.55 + gf * 0.20) * snow_bump, 1.0)); + + vec3 thin = vec3(0.66, 0.72, 0.80); // thin snow is greyish-blue and lets the dark background through + vec3 full = vec3(0.93, 0.95, 0.98); + vec3 col = mix(thin, full, thick) * (0.62 + 0.55 * f1) * (0.88 + 0.22 * snNoise(f_coord * gridSize * 9.0)) * (0.85 + 0.3 * h0); + float a = clamp(cover * mix(0.50, 0.96, thick) * snow_pack * snow_opacity, 0.0, 0.97); + float under = 1.0 - accA; + accRGB = accRGB + col * a * under; + accN = accN + nT * a * under; + accTr = accTr + mix(0.60, 0.30, thick) * a * under; + accA = accA + a * under; +} + +void main() +{ + // Derivatives first, in uniform control flow (no discard before them). + vec3 Ngl = normalize(f_normal); + vec3 dp1 = dFdx(f_pos.xyz); + vec3 dp2 = dFdy(f_pos.xyz); + vec2 duv1 = dFdx(f_coord); + vec2 duv2 = dFdy(f_coord); + vec3 dp2perp = cross(dp2, Ngl); + vec3 dp1perp = cross(Ngl, dp1); + vec3 Tgl = dp2perp * duv1.x + dp1perp * duv2.x; + vec3 Bgl = dp2perp * duv1.y + dp1perp * duv2.y; + float invmax = inversesqrt(max(max(dot(Tgl, Tgl), dot(Bgl, Bgl)), 1e-20)); + Tgl *= invmax; + Bgl *= invmax; + + vec4 tex_color = texture(diffuse, f_coord); // no discard: clean glass between faint dirt must still get snow and blur + + float gridSize = max(ceil(param[2].x), 1.0); + float pixelUV = max(length(dFdx(f_coord)), length(dFdy(f_coord))); + snHaze = 0.0; + vec2 aspect = (snow_uv_aspect >= 1.0) ? vec2(snow_uv_aspect, 1.0) : vec2(1.0, 1.0 / max(snow_uv_aspect, 0.01)); + + vec3 snowRGB = vec3(0.0); // premultiplied + float snowA = 0.0; + float smear = 0.0; + vec3 snowN = vec3(0.0); + float snowTr = 0.0; + if (rain_params.x > 0.0) + { + float mass = 0.0; + if (snow_small > 0.0) + snowLayer(gridSize * 2.4 / snow_flake_scale, snow_small, 17u, 0.9, 0.85, 0.0, 0, pixelUV, aspect, snowRGB, snowA, smear, snowN, snowTr, mass); + snowLayer(gridSize / snow_flake_scale, snow_density, 13u, 1.0, 1.0, snow_slide_share, 4, pixelUV, aspect, snowRGB, snowA, smear, snowN, snowTr, mass); + if (snow_pack > 0.0) + snowFilm(gridSize, snowRGB, snowA, snowN, snowTr); // patches where flakes have run together + } + + float glassA = tex_color.a * alpha_mult; + float finalA = snowA + glassA * (1.0 - snowA); + vec3 premult = snowRGB + tex_color.rgb * glassA * (1.0 - snowA); + vec3 albedo = premult / max(finalA, 1e-4); + float glassShare = glassA * (1.0 - snowA) / max(finalA, 1e-4); + + // relief: tilt the glass normal by the slope of the snow (flat where there is none) + vec3 nDir = snowN + vec3(0.0, 0.0, 1.0) * (1.0 - snowA); + vec3 fragnormal = Ngl; + if (snowA > 0.001) + fragnormal = normalize(Ngl * max(nDir.z, 0.05) + Tgl * nDir.x + Bgl * nDir.y); + + vec3 fragcolor = ambient; + float reflectivity = param[1].z * glassShare; + float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5 * glassShare + snow_gloss * snowA; + legacy_gloss(); + + // most of the glass is clear (no snow, a clear glass texture): the lighting of the 4.6 renderers (the clusters of lamps, the + // shadows, the reflections) is skipped there, it would be multiplied by an alpha of ~0 + if (finalA > 0.002) + fragcolor = apply_lights(fragcolor, fragnormal, albedo, reflectivity, specularity, shadow_tone); + + // thin snow glows when you look towards the sun / a lamp + if (finalA > 0.002 && snowA > 0.001 && snow_translucency > 0.0 && lights_count > 0U) + { + vec3 I = normalize(f_pos.xyz); + float shadowSun = 0.0; + if (shadow_tone < 1.0) + shadowSun = (1.0 - shadow_tone) * clamp(calc_shadow(), 0.0, 1.0); + float towards = max(dot(I, normalize(-lights[0].dir)), 0.0); + float glow = pow(towards, 3.0) * (1.0 - shadowSun); + fragcolor += lights[0].color * lights[0].intensity * glow * snow_translucency * snowTr * albedo * snowA; + } + vec3 lit = apply_fog(fragcolor); + +#if SNOW_MATCH_RAIN_GLASS + vec4 color = vec4(lit * finalA, finalA); +#else + vec4 color = vec4(lit, finalA); +#endif + + out_color = POSTFX_ENABLED ? color : tonemap(color); + + // the scene seen through the snow, drawn by the post-processing (rain_windscreen_haze.glsl), asked for in the velocity target as + // rain_windscreen asks: thin snow bends it (its relief refracts; x, y = WS_DROP_BIAS + WS_BEND_ENC * bend), elsewhere it's blurred in + // and around thin snow and around the melting spots (x = WS_ENC * strength, y = 0); the snow itself stays sharp. alpha 0 elsewhere: + // the blending keeps the motion of the scene behind + if (MOTIONBLUR_ENABLED) + { + float thin = smoothstep(0.04, 0.20, snowA) * (1.0 - smoothstep(0.55, 0.90, snowA)); + vec4 req = vec4(0.0); + if ((snow_distort > 0.0) && (thin > 0.30) && (glassA < 0.5)) + { + vec2 slope = snowN.xy / max(snowA, 1e-3); + vec2 bend = clamp(-slope * snow_distort, vec2(-1.0), vec2(1.0)) * smoothstep(0.30, 0.60, thin) * (SNOW_REFR_MAXPX / WS_REFR_MAXPX); + req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); + } + else + { + float haze = snHaze * snow_haze * (1.0 - smoothstep(0.30, 0.80, snowA)); // frosted glass in and around thin snow + float blurMask = clamp(max(smear * (1.0 - snowA), haze) * (1.0 - smoothstep(0.5, 0.95, glassA)), 0.0, 1.0); + if (blurMask >= 0.01) + req = vec4(WS_ENC * blurMask, 0.0, 0.0, 1.0); + } + out_motion = req; + } +} + +float GetMixFactor(in vec2 co, out float side) { + vec4 movePhase = wiper_pos; + bvec4 is_out = lessThanEqual(movePhase, vec4(1.)); + movePhase = mix(vec4(2.) - movePhase, movePhase, is_out); + + vec4 mask = textureLod(wipermask, co, 0.0); // called from non-uniform flow: no implicit derivatives + + vec4 areaMask = step(.001, mask); + + vec4 maskVal = mix(1. - mask, mask, is_out); + vec4 wipeWidth = smoothstep(1., .9, movePhase) * .25; + vec4 cleaned = smoothstep(movePhase - wipeWidth, movePhase, maskVal) * areaMask; + vec4 side_v = step(maskVal, movePhase); + cleaned *= side_v; + side_v = mix(side_v, vec4(1.) - side_v, is_out); + + // "regeneration", snow gradually returning after a wiper pass (slower than rain, and faster in heavy snowfall): + float regenT = max(mix(snow_regen, snow_regen * 0.6, clamp(rain_params.x, 0.0, 1.0)), 0.5); + vec4 sinceV = vec4(time) - mix(wiper_timer_out, wiper_timer_return, side_v) - vec4(.2); + vec4 regenPhase = clamp(sinceV / vec4(regenT), vec4(0.), vec4(1.)); + + side_v = mix(vec4(0.), vec4(1.) - side_v, areaMask); + + vec4 factor_v = mix(vec4(1.), regenPhase * (vec4(1.) - cleaned), areaMask); + + side = 0.; + float out_factor = 1.; + bool have_side = false; + snWipeSince = 1.0e5; + + // out_factor: the blade that clears the grid cell the most wins (as before). + // side: which wiper stroke the drops of this cell belong to. It is part of the random + // seed of every drop, so it must NOT depend on out_factor. It used to: once the drops had + // fully regrown (out_factor == 1) side fell back to 0 and every drop in the swept area + // jumped to a new position, about one regrow time after each stroke (most visible in + // heavy rain, where regrowth takes ~1 s). + for(int i = 0; i < 4; ++i) + { + out_factor = min(out_factor, factor_v[i]); + if (!have_side && areaMask[i] > 0.) + { + side = side_v[i]; + snWipeSince = max(sinceV[i], 0.0); + have_side = true; + } + } + + return out_factor; +} diff --git a/shaders/vk14/rain_cells.glsl b/shaders/vk14/rain_cells.glsl index 0629492e2..4d608d571 100644 --- a/shaders/vk14/rain_cells.glsl +++ b/shaders/vk14/rain_cells.glsl @@ -53,7 +53,7 @@ const float drop_life_min = 14.0; // seconds a drop sits on the glass const float drop_life_max = 45.0; const float drop_appear = 0.18; // seconds of the landing "pop" const float drop_fade = 1.5; // seconds a drop takes to vanish at the end of its life -const float wiper_miss = 0.05; // share of the drops a blade goes over without taking them +const float wiper_miss = 0.0167; // share of the drops a blade goes over without taking them (a third of the 0.05 it was) const float streak_period = 40.0; // seconds a rivulet lives (it runs for ~90% of that and then fades out), average const float wind_streak_period = 18.0; // seconds a rivulet driven by the air lives (they run faster than the ones of gravity) From 0531cd2726e685aeee32f9cf23683c5e134eb385 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Tue, 10 Nov 2026 20:40:38 +0100 Subject: [PATCH 061/123] Rain windscreen: fewer drops left by a blade (wiper_miss 0.005) No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/rain_cells.glsl | 2 +- shaders/vk14/rain_cells.glsl | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/shaders/ogl46/rain_cells.glsl b/shaders/ogl46/rain_cells.glsl index 843aaa496..5fa8569dd 100644 --- a/shaders/ogl46/rain_cells.glsl +++ b/shaders/ogl46/rain_cells.glsl @@ -53,7 +53,7 @@ const float drop_life_min = 14.0; // seconds a drop sits on the glass const float drop_life_max = 45.0; const float drop_appear = 0.18; // seconds of the landing "pop" const float drop_fade = 1.5; // seconds a drop takes to vanish at the end of its life -const float wiper_miss = 0.0167; // share of the drops a blade goes over without taking them (a third of the 0.05 it was) +const float wiper_miss = 0.005; // share of the drops a blade goes over without taking them (a tenth of the 0.05 it was) const float streak_period = 40.0; // seconds a rivulet lives (it runs for ~90% of that and then fades out), average const float wind_streak_period = 18.0; // seconds a rivulet driven by the air lives (they run faster than the ones of gravity) diff --git a/shaders/vk14/rain_cells.glsl b/shaders/vk14/rain_cells.glsl index 4d608d571..6a5a69945 100644 --- a/shaders/vk14/rain_cells.glsl +++ b/shaders/vk14/rain_cells.glsl @@ -53,7 +53,7 @@ const float drop_life_min = 14.0; // seconds a drop sits on the glass const float drop_life_max = 45.0; const float drop_appear = 0.18; // seconds of the landing "pop" const float drop_fade = 1.5; // seconds a drop takes to vanish at the end of its life -const float wiper_miss = 0.0167; // share of the drops a blade goes over without taking them (a third of the 0.05 it was) +const float wiper_miss = 0.005; // share of the drops a blade goes over without taking them (a tenth of the 0.05 it was) const float streak_period = 40.0; // seconds a rivulet lives (it runs for ~90% of that and then fades out), average const float wind_streak_period = 18.0; // seconds a rivulet driven by the air lives (they run faster than the ones of gravity) From ba3129275c252c362e213d7efdd2a667bcf2de86 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Tue, 10 Nov 2026 20:51:47 +0100 Subject: [PATCH 062/123] Snow windscreen: the snow of the glass simulated on a map that keeps it A glass of mat_snow_windscreen (the material of the "snow:" block, with a mask of the wipers) gets a slot of the windscreen water storage, as the glasses of the water could, and two maps of its snow (a step reads one, writes the other): the snow, the water, how packed the snow is and the shape of its flakes for each of 256 x 256 texels of its uv. water_snow.comp runs a step a frame, both APIs: - the flakes land as many as come to the glass facing the snow against the cab (and a few from the eddies), the dry ones bouncing off at speed; - the blades take the snow they go over (a little stays, a wet trace) and push it ahead of themselves, leaving it as ridges at the ends of their sweeps; piled snow slips onto its neighbours into a wedge; - the glass is warmer than the air (the cab is heated, less so at speed): above zero the snow melts into water, slush slides down, dry powder is blown along by the air at speed, the water runs and dries. mat_snow_windscreen.frag draws the map: flakes from the atlas where the snow is thin (water spots where it melted), a layer with a torn edge, as opaque as it is thick, grey when wet, its relief from the slopes of the map; the wet glass bends the picture behind through the post-processing. Without the simulation the glass is drawn as before. The glasses are found again when a material of the cab changes its kind (the weather switched its shader). The drop passes run only for glasses of the water. No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- gl/ubo.h | 23 +- rendering/common/windscreenwater.cpp | 56 ++++- rendering/common/windscreenwater.h | 4 + rendering/opengl46/opengl46water.cpp | 34 +-- rendering/opengl46/opengl46water.h | 1 + rendering/vulkan14/vulkan14water.cpp | 33 ++- rendering/vulkan14/vulkan14water.h | 1 + shaders/ogl46/mat_snow_windscreen.frag | 178 +++++++++++++- shaders/ogl46/water.glsl | 39 +++ shaders/ogl46/water_sim.glsl | 5 + shaders/ogl46/water_snow.comp | 316 ++++++++++++++++++++++++ shaders/vk14/mat_snow_windscreen.frag | 178 +++++++++++++- shaders/vk14/water.glsl | 39 +++ shaders/vk14/water_sim.glsl | 5 + shaders/vk14/water_snow.comp | 319 +++++++++++++++++++++++++ 15 files changed, 1193 insertions(+), 38 deletions(-) create mode 100644 shaders/ogl46/water_snow.comp create mode 100644 shaders/vk14/water_snow.comp diff --git a/gl/ubo.h b/gl/ubo.h index a9a77d32f..66a10e2db 100644 --- a/gl/ubo.h +++ b/gl/ubo.h @@ -767,10 +767,15 @@ namespace gl const size_t WATER_CELLS_OFFSET = WATER_EXTRA_OFFSET + 16 * WATER_SLOT_DROPS; const size_t WATER_CELLS_SIZE = 4 * static_cast(WATER_SLOTS) * WATER_GRID * WATER_GRID * (1 + WATER_CELL_DROPS); const size_t WATER_TRAIL_OFFSET = WATER_CELLS_OFFSET + WATER_CELLS_SIZE; - const size_t WATER_STORAGE_SIZE = WATER_TRAIL_OFFSET + 4 * static_cast(WATER_SLOTS) * WATER_TRAIL * WATER_TRAIL; + // the snow on the glasses (water_snow.comp, mat_snow_windscreen.frag): two maps of every glass, WATER_MAP x WATER_MAP texels of + // two uint each (four halves: the snow, mm; the water, mm; how packed the snow is, 0 .. 1; random 0 .. 1, the shape of its + // flakes), a step reads one and writes the other (the header of the glass says which one is the latest) + const size_t WATER_SNOW_OFFSET = WATER_TRAIL_OFFSET + 4 * static_cast(WATER_SLOTS) * WATER_TRAIL * WATER_TRAIL; + const size_t WATER_SNOW_SIZE = 8 * static_cast(WATER_MAP) * WATER_MAP; + const size_t WATER_STORAGE_SIZE = WATER_SNOW_OFFSET + 2 * WATER_SNOW_SIZE * WATER_SLOTS; // the parts of a glass in the storage: its drops and what the passes keep of them, its map (the axes the second part), its - // cells and its paths, its header and its counts, (offset, size) in bytes - inline std::array, 11> water_slot_parts(size_t const Slot) + // cells and its paths, its header and its counts, its two maps of the snow, (offset, size) in bytes + inline std::array, 13> water_slot_parts(size_t const Slot) { auto const drops{static_cast(WATER_DROPS)}; auto const texels{static_cast(WATER_MAP) * WATER_MAP}; @@ -786,7 +791,9 @@ namespace gl {WATER_CELLS_OFFSET + cells * Slot, cells}, {WATER_TRAIL_OFFSET + trail * Slot, trail}, {WATER_HEADER_OFFSET + 16 * Slot, 16}, - {WATER_COUNTS_OFFSET + 16 * Slot, 16}}}; + {WATER_COUNTS_OFFSET + 16 * Slot, 16}, + {WATER_SNOW_OFFSET + WATER_SNOW_SIZE * Slot, WATER_SNOW_SIZE}, + {WATER_SNOW_OFFSET + WATER_SNOW_SIZE * (WATER_SLOTS + Slot), WATER_SNOW_SIZE}}}; } // layout std140: the step of the simulation of the water on the windscreens (GLSL water_ubo), every vector in the space of the @@ -815,8 +822,14 @@ namespace gl // landings tried at the densest place are all taken), z 1 when it's simulated, w the size of its drops (the param // rain_scale of its material) glm::vec4 slots[WATER_SLOTS]; + // the snow (water_snow.comp): x the flakes coming to a square metre of the ground in a second, y how much warmer than the + // air the glass is (the cab heats it), degrees, z the speed of the vehicle, m/s, w the map of the snow the step reads (0, 1) + glm::vec4 snow; + // every glass: 1 when its snow is simulated + glm::vec4 snow_slots; }; - static_assert(sizeof(water_ubs) == 112 + 16 * WATER_SLOTS, "bad size of water_ubs"); + static_assert(WATER_SLOTS == 4, "snow_slots holds a glass in a component"); + static_assert(sizeof(water_ubs) == 144 + 16 * WATER_SLOTS, "bad size of water_ubs"); // layout std430: a bucket of a scene cell queued in the pass (GLSL: instance_cull_job) struct instance_cull_job diff --git a/rendering/common/windscreenwater.cpp b/rendering/common/windscreenwater.cpp index 619b6bf33..5a9dc9995 100644 --- a/rendering/common/windscreenwater.cpp +++ b/rendering/common/windscreenwater.cpp @@ -21,6 +21,8 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Train.h" #include "physics/vehicle.h" +#include + namespace gfx { @@ -39,17 +41,42 @@ double constexpr WIND_SHARE{0.5}; float constexpr LEAST_DROP{0.5f}; // the water a flake of snow brings, mm3 on average (water_spawn.comp: 0.3 .. 2.5) float constexpr FLAKE_WATER{1.4f}; +// how much warmer than the air a glass of the cab is, degrees: the cab is heated (the blowing on the glass isn't simulated), +// less so at speed, when the air cools the glass from the outside (water_snow.comp) +float constexpr GLASS_WARMTH{3.f}; // the most landings tried on a glass in a step std::uint32_t constexpr MOST_TRIES{1024}; // the longest step, seconds: a longer frame slows the water down rather than let it jump double constexpr LONGEST_STEP{0.05}; -// whether the material is a glass: one of mat_rain_windscreen, with a mask of the wipers -bool is_glass(opengl_material const *Material) +// whether the material is a glass of the water: one of mat_rain_windscreen, with a mask of the wipers +bool is_water_glass(opengl_material const *Material) { return (Material != nullptr) && (Material->shader != nullptr) && (Material->shader->texture_conf.count("wipermask") > 0) && (Material->shader->param_conf.count("water_slot") > 0); } +// whether the material is a glass of the snow: one of mat_snow_windscreen, with a mask of the wipers (its param snow_slot is in +// the place of water_slot) +bool is_snow_glass(opengl_material const *Material) +{ + return (Material != nullptr) && (Material->shader != nullptr) && (Material->shader->texture_conf.count("wipermask") > 0) && (Material->shader->param_conf.count("snow_slot") > 0); +} + +// whether the material is a glass, of the water or of the snow +bool is_glass(opengl_material const *Material) +{ + return is_water_glass(Material) || is_snow_glass(Material); +} + +// what a material of the cab with a mask of the wipers is now: 0 no glass, 1 a glass of the water, 2 a glass of the snow (its +// shader goes with the weather) +int glass_kind(opengl_material const *Material) +{ + if (is_snow_glass(Material)) + return 2; + return is_water_glass(Material) ? 1 : 0; +} + // calls Visit for every submodel of the branch, its children and its siblings template void visit_submodels(TSubModel *Submodel, Visit &&Visitor) { @@ -95,6 +122,7 @@ void windscreen_water::release() assign(false); m_glasses = {}; m_glasscount = 0; + m_kinds.clear(); m_vehicle = nullptr; m_cab = nullptr; } @@ -231,6 +259,12 @@ void windscreen_water::build(TModel3d &Cab) } } auto const material{Submodel->m_material}; + if ((material != null_handle) && (material > 0) && (Submodel->eType == GL_TRIANGLES) && std::ranges::none_of(m_kinds, [material](auto const &Kind) { return Kind.first == material; })) + { + // every material with a mask of the wipers, what it is kept: it's a glass of another kind when the weather changes + if (auto const *opengl{m_host.material(material)}; (opengl != nullptr) && (opengl->shader != nullptr) && (opengl->shader->texture_conf.count("wipermask") > 0)) + m_kinds.emplace_back(material, glass_kind(opengl)); + } if ((material != null_handle) && (material > 0) && (Submodel->eType == GL_TRIANGLES) && (std::find(materials.begin(), materials.end(), material) == materials.end()) && is_glass(m_host.material(material))) { materials.push_back(material); @@ -256,6 +290,7 @@ void windscreen_water::build(TModel3d &Cab) glass = windscreen_water::glass{}; glass.material = material; auto const *opengl{m_host.material(material)}; + glass.snow = is_snow_glass(opengl); glass.mask = opengl->textures[opengl->shader->texture_conf.at("wipermask").id]; for (std::size_t texel = 0; texel < texels; ++texel) { @@ -318,7 +353,10 @@ void windscreen_water::update(double const Seconds) } auto const *vehicle{simulation::Train != nullptr ? simulation::Train->Dynamic() : nullptr}; auto *cab{vehicle != nullptr ? vehicle->mdKabina : nullptr}; - if ((vehicle != m_vehicle) || (cab != m_cab)) + // a material of the glasses of another kind: the weather changed, the materials have the shaders of the other weather (the + // snow comes with the shader of the snow and goes with it) + auto const changed{std::ranges::any_of(m_kinds, [this](auto const &Kind) { return glass_kind(m_host.material(Kind.first)) != Kind.second; })}; + if ((vehicle != m_vehicle) || (cab != m_cab) || changed) { // another cab: its glasses dry release(); @@ -410,11 +448,15 @@ void windscreen_water::update(double const Seconds) auto const coming{glm::length(air - up * fall)}; std::uint32_t most{0}; m_tries = 0; + bool anysnow{false}; for (std::size_t slot = 0; slot < m_glasscount; ++slot) { auto &glass{m_glasses[slot]}; auto const *material{m_host.material(glass.material)}; - auto const simulated{glass.baked && is_glass(material)}; + auto const snowed{glass.baked && glass.snow && is_snow_glass(material)}; + block.snow_slots[static_cast(slot)] = (snowed ? 1.f : 0.f); + anysnow = anysnow || snowed; + auto const simulated{glass.baked && (false == glass.snow) && is_water_glass(material)}; glass.landings += static_cast(perground / fall * coming * glass.densest) * seconds; auto const whole{std::floor(glass.landings)}; glass.landings -= whole; @@ -433,8 +475,14 @@ void windscreen_water::update(double const Seconds) m_bladesbefore.x < 0.f ? blades.x : m_bladesbefore.x, m_bladesbefore.y < 0.f ? blades.y : m_bladesbefore.y, m_bladesbefore.z < 0.f ? blades.z : m_bladesbefore.z, m_bladesbefore.w < 0.f ? blades.w : m_bladesbefore.w}; block.rain = glm::vec4{LEAST_DROP, lambda, 1.f, 0.f}; block.counts = glm::uvec4{m_step * 2654435761u, most, 0u, 0u}; + block.snow = glm::vec4{snow ? perground : 0.f, GLASS_WARMTH, static_cast(std::abs(vehicle->MoverParameters->V)), static_cast(m_snowmap)}; m_bladesbefore = blades; gpu_step(block, most); + if (anysnow) + { + // the step wrote the other map of the snow + m_snowmap = 1 - m_snowmap; + } } std::string windscreen_water::info() const diff --git a/rendering/common/windscreenwater.h b/rendering/common/windscreenwater.h index 2c09951ba..6a8ce7c17 100644 --- a/rendering/common/windscreenwater.h +++ b/rendering/common/windscreenwater.h @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include @@ -89,6 +90,7 @@ class windscreen_water float area{0.f}; // metres squared of the glass double landings{0.0}; // the share of a landing left over from the steps before bool baked{false}; + bool snow{false}; // a glass of the snow (mat_snow_windscreen), else of the water }; // the glasses of the model of a cab found and set up @@ -102,12 +104,14 @@ class windscreen_water int m_state{0}; // 0: not set up yet, 1: ready, -1: can't be used TDynamicObject const *m_vehicle{nullptr}; TModel3d const *m_cab{nullptr}; + std::vector> m_kinds; // the materials of the cab with a mask of the wipers, what kind of glass they were std::array m_glasses{}; std::size_t m_glasscount{0}; glm::vec4 m_bladesbefore{-1.f}; double m_time{0.0}; // seconds the simulation runs std::uint32_t m_step{0}; std::uint32_t m_tries{0}; // landings tried in the last step, all glasses + int m_snowmap{0}; // the map of the snow of the glasses the next step reads (0, 1) }; } // namespace gfx diff --git a/rendering/opengl46/opengl46water.cpp b/rendering/opengl46/opengl46water.cpp index c8ee70ccd..d14fa0745 100644 --- a/rendering/opengl46/opengl46water.cpp +++ b/rendering/opengl46/opengl46water.cpp @@ -14,8 +14,6 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include -#include -#include namespace { @@ -59,8 +57,9 @@ bool opengl46_windscreen_water::gpu_init() { try { - // the ones made ahead (prepare_next()) are kept - for (std::size_t i = 0; i < PROGRAM_NAMES.size(); ++i) + std::array const names{"water_trail.comp", "water_spawn.comp", "water_move.comp", "water_clear.comp", "water_grid.comp", + "water_merge.comp", "water_gather.comp", "water_settle.comp", "water_bake.comp", "water_snow.comp"}; + for (std::size_t i = 0; i < names.size(); ++i) { if (m_programs[i]) continue; @@ -172,17 +171,24 @@ void opengl46_windscreen_water::gpu_step(gl::water_ubs const &Block, std::uint32 m_programs[Pass]->dispatch(Groups, slots); ::glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); }; + // the drops only where a glass of the water is (the glasses of the snow have passes of their own) + auto const water{std::ranges::any_of(Block.slots, [](glm::vec4 const &Slot) { return Slot.z > 0.5f; })}; + auto const drop_groups{water ? drops : 0u}; + auto const cell_groups{water ? cells : 0u}; // the wetted paths the blades went over in the step wiped - if (Block.blades != Block.blades_before) + if (water && (Block.blades != Block.blades_before)) run(pass::trail, groups(static_cast(gl::WATER_TRAIL) * gl::WATER_TRAIL)); - run(pass::spawn, groups(Tries)); - run(pass::move, drops); - run(pass::clear, cells); - run(pass::grid, drops); - run(pass::merge, drops); - run(pass::gather, drops); - run(pass::settle, drops); - run(pass::clear, cells); - run(pass::grid, drops); + run(pass::spawn, water ? groups(Tries) : 0u); + run(pass::move, drop_groups); + run(pass::clear, cell_groups); + run(pass::grid, drop_groups); + run(pass::merge, drop_groups); + run(pass::gather, drop_groups); + run(pass::settle, drop_groups); + run(pass::clear, cell_groups); + run(pass::grid, drop_groups); + // the snow of the glasses of the snow, a texel of their maps a thread + if (Block.snow_slots != glm::vec4{0.f}) + run(pass::snow, groups(static_cast(gl::WATER_MAP) * gl::WATER_MAP)); gl::program::unbind(); } diff --git a/rendering/opengl46/opengl46water.h b/rendering/opengl46/opengl46water.h index 7e5a20d29..ce3c92bae 100644 --- a/rendering/opengl46/opengl46water.h +++ b/rendering/opengl46/opengl46water.h @@ -50,6 +50,7 @@ class opengl46_windscreen_water : public gfx::windscreen_water gather, settle, bake, + snow, count }; std::array, pass::count> m_programs; diff --git a/rendering/vulkan14/vulkan14water.cpp b/rendering/vulkan14/vulkan14water.cpp index c3aefc748..1ed3b45a2 100644 --- a/rendering/vulkan14/vulkan14water.cpp +++ b/rendering/vulkan14/vulkan14water.cpp @@ -12,6 +12,8 @@ http://mozilla.org/MPL/2.0/. #include "rendering/vulkan14/vulkan14commands.h" #include "utilities/Logs.h" +#include + #include namespace vk14 @@ -99,7 +101,7 @@ bool windscreen_water::gpu_init() try { std::array const names{"water_trail.comp", "water_spawn.comp", "water_move.comp", "water_clear.comp", "water_grid.comp", - "water_merge.comp", "water_gather.comp", "water_settle.comp", "water_bake.comp"}; + "water_merge.comp", "water_gather.comp", "water_settle.comp", "water_bake.comp", "water_snow.comp"}; for (std::size_t i = 0; i < names.size(); ++i) { if (false == m_kernels[i].create(m_device, *m_pipelines, m_shaders->get(names[i]), m_passlayout, {}, names[i])) @@ -283,20 +285,29 @@ void windscreen_water::gpu_step(gl::water_ubs const &Block, std::uint32_t const }; auto const drops{groups(gl::WATER_DROPS)}; auto const cells{groups(static_cast(gl::WATER_GRID) * gl::WATER_GRID)}; + // the drops only where a glass of the water is (the glasses of the snow have passes of their own) + auto const water{std::ranges::any_of(Block.slots, [](glm::vec4 const &Slot) { return Slot.z > 0.5f; })}; + auto const drop_groups{water ? drops : 0u}; + auto const cell_groups{water ? cells : 0u}; // the wetted paths the blades went over in the step wiped - if (Block.blades != Block.blades_before) + if (water && (Block.blades != Block.blades_before)) { run(pass::trail, groups(static_cast(gl::WATER_TRAIL) * gl::WATER_TRAIL)); } - run(pass::spawn, groups(Tries)); - run(pass::move, drops); - run(pass::clear, cells); - run(pass::grid, drops); - run(pass::merge, drops); - run(pass::gather, drops); - run(pass::settle, drops); - run(pass::clear, cells); - run(pass::grid, drops); + run(pass::spawn, water ? groups(Tries) : 0u); + run(pass::move, drop_groups); + run(pass::clear, cell_groups); + run(pass::grid, drop_groups); + run(pass::merge, drop_groups); + run(pass::gather, drop_groups); + run(pass::settle, drop_groups); + run(pass::clear, cell_groups); + run(pass::grid, drop_groups); + // the snow of the glasses of the snow, a texel of their maps a thread + if (Block.snow_slots != glm::vec4{0.f}) + { + run(pass::snow, groups(static_cast(gl::WATER_MAP) * gl::WATER_MAP)); + } } } // namespace vk14 diff --git a/rendering/vulkan14/vulkan14water.h b/rendering/vulkan14/vulkan14water.h index 901e241bd..dd42cf72a 100644 --- a/rendering/vulkan14/vulkan14water.h +++ b/rendering/vulkan14/vulkan14water.h @@ -78,6 +78,7 @@ class windscreen_water : public gfx::windscreen_water gather, settle, bake, + snow, count }; // the block of the step in the ring of the frame; empty when the ring is full diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index 50496d520..5d4ce8097 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -65,11 +65,14 @@ layout(location = 1) out vec4 out_motion; #pragma param(reflection, 1, 2, 1, zero) #pragma param(glossiness, 1, 3, 1, glossiness) #pragma param(raindrop_grid_size, 2, 0, 1, one) +// snow_slot: 1 + the slot of the glass in the simulation of the snow (the renderer sets it), 0: none +#pragma param(snow_slot, 2, 2, 1, zero) #include "light_common.glsl" #include "apply_fog.glsl" #include "tonemapping.glsl" #include "random.glsl" +#include "water.glsl" layout(binding = 0) uniform sampler2D diffuse; layout(binding = 1) uniform sampler2D raindropsatlas; @@ -442,6 +445,158 @@ void snowFilm(float gridSize, inout vec3 accRGB, inout float accA, inout vec3 ac accA = accA + a * under; } +// --- The snow of the simulation (water_snow.comp): the map of the glass --------------------------------------------------- +// When the renderer simulates the snow of the glass (the param snow_slot holds 1 + its slot), the snow, the water, how packed the +// snow is and the shape of its flakes come from the map of the glass (water.glsl), which keeps them from frame to frame: the flakes +// land and stay where they landed, pile up into a layer, the blades push it into ridges at the ends of their sweeps and leave a wet +// trace, it melts at the warm glass and slush slides down. Here it's only drawn: +// - a texel of the map with a little snow is a flake (atlas tiles 0..2: fluffy when dry, a wet lump when wet or packed, crumbs), +// the more snow the bigger; with mostly water left it's the water spot (tile 3) +// - where the snow is thicker it's a layer: its edge torn by the grain of the snow, as opaque as it's thick (Beer-Lambert), grey +// and translucent when wet (slush), smoother and denser when packed; its relief from the slopes of the snow of the map +// - the water: wet glass bends the picture behind (the post-processing), the thin snow hazes it +// Without the simulation (an older renderer, no compute) the procedural snow below draws the glass as before. +const float snow_map_flake = 1.15; // size of a flake relative to a texel of the map (the snow of a texel) +const float snow_map_layer = 1.0; // mm of snow above which the flakes run together into a layer +const float snow_map_opaque = 1.8; // mm of fresh snow which lets 1/e of the light through (packed: half of it) +const float snow_map_relief = 0.6; // how much the slopes of the snow tilt its surface +const float snow_map_grain = 0.35; // the fine grain of the layer (its relief) +const float snow_map_wet_bend = 0.6; // how strongly a wet glass bends the picture behind it + +int snMapSlot = -1; +uint snMapIndex = 0u; +float snWet = 0.0; // set by snowMapped: the film of water (0 .. 1) +vec2 snWetN = vec2(0.0); // set by snowMapped: the slope of the water, for the bend of the picture + +// the snow of the map at a place of the glass +vec4 snMapAt(vec2 uv) +{ + return water_snow_at(uint(snMapSlot), snMapIndex, uv); +} + +// a flake of the map drawn over the accumulators: Local the place in its sprite (0 .. 1), Tile the corner of its tile in the atlas +void snowMapSprite(vec2 local, vec2 tile, float alpha, float tone, float flip, float c, float s, float lod, + inout vec3 accRGB, inout float accA, inout vec3 accN, inout float accTr) +{ + vec4 t = textureLod(raindropsatlas, tile + local * 0.5, lod); + vec4 n = textureLod(normalmap, tile + local * 0.5, lod); + float a = clamp(t.a * alpha * snow_opacity, 0.0, 1.0); + if (a <= 0.0) + return; + vec2 nxy = (n.rg * 2.0 - 1.0) * snow_bump; + nxy.x *= flip; + vec2 nuv = vec2(c * nxy.x - s * nxy.y, s * nxy.x + c * nxy.y); + vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); + float tr = (1.0 - t.a * 0.55); + accRGB = t.rgb * tone * a + accRGB * (1.0 - a); + accN = nT * a + accN * (1.0 - a); + accTr = tr * a + accTr * (1.0 - a); + accA = a + accA * (1.0 - a); +} + +// the flakes of the texels around the pixel +void snowMapFlakes(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float accA, inout vec3 accN, inout float accTr) +{ + vec2 p = f_coord * float(WATER_MAP); + ivec2 here = ivec2(floor(p)); + for (int oy = -1; oy <= 1; ++oy) + { + for (int ox = -1; ox <= 1; ++ox) + { + ivec2 texel = here + ivec2(ox, oy); + vec4 q = water_snow_texel(uint(snMapSlot), snMapIndex, texel); + float density = mix(0.1, 0.4, q.z); + float wet = q.y / (q.y + q.x * density + 1e-4); + bool spot = (q.x < 0.05) && (q.y > 0.015); // a flake melted into its water + if ((q.x < 0.05) && (false == spot)) + continue; + uint seed = Hash(uvec3(uvec2(texel), uint(q.w * 65535.0) + 7u * uint(snMapSlot))); + vec2 center = vec2(texel) + vec2(0.15 + 0.7 * RandF(seed), 0.15 + 0.7 * RandF(seed)); + float ang = RandF(seed) * 6.2831853; + float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; + float kind = RandF(seed); + float tone = mix(0.94, 1.04, RandF(seed)); + float aniso = mix(0.62, 1.0, RandF(seed)); + // the more snow the texel holds the bigger the flake (a lump of a few flakes) + float size = snow_map_flake * mix(0.6, 1.0, RandF(seed)) * (spot ? mix(0.5, 1.1, smoothstep(0.015, 0.2, q.y)) + : mix(0.7, 1.6, smoothstep(0.05, 2.0, q.x))); + vec2 d = (p - center) * aspect; + float c = cos(ang); + float s = sin(ang); + vec2 r = vec2(c * d.x + s * d.y, -s * d.x + c * d.y); + r.x *= flip / aniso; + vec2 local = r / size + 0.5; + if (any(lessThan(local, vec2(0.0))) || any(greaterThan(local, vec2(1.0)))) + continue; + float sizeUV = size / float(WATER_MAP); + float lod = clamp(log2(max(pixelUV / sizeUV * 0.5 * float(textureSize(raindropsatlas, 0).x), 1.0)), 0.0, 4.0); + vec2 tile; + if (spot) + tile = vec2(0.5, 0.0); + else if ((wet > 0.3) || (q.z > 0.5) || (kind < 0.30)) + tile = vec2(0.5, 0.5); // a wet lump + else if (kind < 0.75) + tile = vec2(0.0, 0.5); // fluffy + else + tile = vec2(0.0, 0.0); // crumbs + float alpha = spot ? smoothstep(0.015, 0.08, q.y) : smoothstep(0.05, 0.25, q.x); + snowMapSprite(local, tile, alpha, tone, flip, c, s, lod, accRGB, accA, accN, accTr); + } + } +} + +// the snow of the map at the pixel: the flakes, the layer of the snow under them, the water, the haze +void snowMapped(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float accA, inout float smear, inout vec3 accN, inout float accTr) +{ + vec4 q = snMapAt(f_coord); + float e = 1.0 / float(WATER_MAP); + vec4 qr = snMapAt(f_coord + vec2(e, 0.0)); + vec4 ql = snMapAt(f_coord - vec2(e, 0.0)); + vec4 qu = snMapAt(f_coord + vec2(0.0, e)); + vec4 qd = snMapAt(f_coord - vec2(0.0, e)); + float around = (q.x + qr.x + ql.x + qu.x + qd.x) * 0.2; + + // the flakes of thin snow and the water spots + snowMapFlakes(aspect, pixelUV, accRGB, accA, accN, accTr); + + // the water: the film bends the picture behind + snWet = smoothstep(0.02, 0.25, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); + snWetN = vec2(qr.y - ql.y, qu.y - qd.y) * 2.0 + (vec2(snNoise(f_coord * 900.0), snNoise(f_coord * 900.0 + 31.0)) - 0.5) * 0.6 * snWet; + smear = max(smear, snWet * snow_melt_blur * 0.6); + // thin snow hazes the picture around it + snHaze = max(snHaze, smoothstep(0.03, 0.6, around)); + + // the layer, where the snow has run together + vec2 gp = f_coord * float(WATER_MAP) * aspect; + float grain = snFbm(gp * 0.9 + 3.0) * 0.55 + snFbm(gp * 2.7 + 11.0) * 0.30 + snFbm(gp * 7.1 + 5.0) * 0.15; + float edge = (q.x - snow_map_layer) / max(snow_map_layer, 1e-3) + (grain - 0.5) * 1.6; + float cover = smoothstep(0.0, 0.35, edge); + if (cover <= 0.002) + return; + float density = mix(0.1, 0.4, q.z); + float wet = q.y / (q.y + q.x * density + 1e-4); + float opaque = snow_map_opaque * mix(1.0, 0.5, q.z); + float thick = 1.0 - exp(-q.x / opaque); + // the relief: the slopes of the snow of the map (ridges, the edges of the swept arcs) and the grain of the fresh snow + vec2 slope = vec2(qr.x - ql.x, qu.x - qd.x) * 0.5 * snow_map_relief; + float f1 = snFbm(gp * 3.3); + float ef = 0.05; + vec2 gf = vec2(snFbm(gp * 3.3 + vec2(ef, 0.0)) - f1, snFbm(gp * 3.3 + vec2(0.0, ef)) - f1) / ef; + vec3 nT = normalize(vec3(-(slope + gf * snow_map_grain * (1.0 - 0.6 * q.z)) * snow_bump, 1.0)); + + vec3 fresh = vec3(0.93, 0.95, 0.98); + vec3 packed = vec3(0.84, 0.87, 0.91); + vec3 slush = vec3(0.60, 0.66, 0.73); + vec3 col = mix(mix(fresh, packed, q.z), slush, smoothstep(0.2, 0.7, wet)); + col *= (0.80 + 0.30 * f1 * (1.0 - 0.5 * q.z)) * (0.92 + 0.12 * grain); + float a = clamp(cover * mix(0.35, 0.97, thick) * mix(1.0, 0.75, smoothstep(0.3, 0.8, wet)) * snow_pack * snow_opacity, 0.0, 0.97); + float under = 1.0 - accA; + accRGB = accRGB + col * a * under; + accN = accN + nT * a * under; + accTr = accTr + mix(0.60, 0.25, thick) * a * under; + accA = accA + a * under; +} + void main() { // Derivatives first, in uniform control flow (no discard before them). @@ -470,7 +625,20 @@ void main() float smear = 0.0; vec3 snowN = vec3(0.0); float snowTr = 0.0; - if (rain_params.x > 0.0) + // the snow of the simulation where the glass has a map of it, else made up as before + snMapSlot = int(param[2].z + 0.5) - 1; + bool mapped = (snMapSlot >= 0) && (snMapSlot < WATER_SLOTS) && water_snow_map(uint(snMapSlot), snMapIndex); + if (mapped) + { + // the texels of the map as they lie on the glass (the uv may be stretched) + ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); + uint axis = (uint(snMapSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; + vec2 span = vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)); + if (min(span.x, span.y) > 1e-6) + aspect = span / max(span.x, span.y); + snowMapped(aspect, pixelUV, snowRGB, snowA, smear, snowN, snowTr); + } + else if (rain_params.x > 0.0) { float mass = 0.0; if (snow_small > 0.0) @@ -531,7 +699,13 @@ void main() { float thin = smoothstep(0.04, 0.20, snowA) * (1.0 - smoothstep(0.55, 0.90, snowA)); vec4 req = vec4(0.0); - if ((snow_distort > 0.0) && (thin > 0.30) && (glassA < 0.5)) + if ((snWet > 0.25) && (snowA < 0.35) && (glassA < 0.5)) + { + // the water on the glass: its film and its spots bend the picture behind + vec2 bend = clamp(-snWetN * snow_map_wet_bend, vec2(-1.0), vec2(1.0)) * smoothstep(0.25, 0.6, snWet); + req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); + } + else if ((snow_distort > 0.0) && (thin > 0.30) && (glassA < 0.5)) { vec2 slope = snowN.xy / max(snowA, 1e-3); vec2 bend = clamp(-slope * snow_distort, vec2(-1.0), vec2(1.0)) * smoothstep(0.30, 0.60, thin) * (SNOW_REFR_MAXPX / WS_REFR_MAXPX); diff --git a/shaders/ogl46/water.glsl b/shaders/ogl46/water.glsl index 6c3dcbfba..f35fbdf75 100644 --- a/shaders/ogl46/water.glsl +++ b/shaders/ogl46/water.glsl @@ -53,6 +53,45 @@ layout(std430, binding = WATER_SSBO_BINDING) readonly buffer water_ssbo uint water_cells[]; }; +// the snow on a glass of the snow (water_snow.comp, mat_snow_windscreen.frag): two maps of WATER_MAP x WATER_MAP texels after the +// wetted paths in water_cells, two uint a texel (halves: x the snow, mm, y the water, mm, z how packed the snow is 0 .. 1, w random +// 0 .. 1, the shape of its flakes); a step reads one and writes the other, the header of the glass says which one is the latest +// (z 1 when there's a map of the snow, w the map) +uint water_snow_base(uint slot, uint map) +{ + return uint(WATER_SLOTS * WATER_GRID * WATER_GRID * (1 + WATER_CELL_DROPS)) + uint(WATER_SLOTS * WATER_TRAIL * WATER_TRAIL) + (map * uint(WATER_SLOTS) + slot) * uint(WATER_MAP * WATER_MAP * 2); +} + +// a texel of a map of the snow, nothing outside the map +vec4 water_snow_texel(uint slot, uint map, ivec2 texel) +{ + if (any(lessThan(texel, ivec2(0))) || any(greaterThanEqual(texel, ivec2(WATER_MAP)))) + return vec4(0.0); + uint index = water_snow_base(slot, map) + 2u * uint(texel.y * WATER_MAP + texel.x); + return vec4(unpackHalf2x16(water_cells[index]), unpackHalf2x16(water_cells[index + 1u])); +} + +// the latest map of the snow of a glass; false when there's none yet +bool water_snow_map(uint slot, out uint map) +{ + vec4 header = water_header[slot]; + map = (header.w > 0.5) ? 1u : 0u; + return header.z > 0.5; +} + +// the latest map of the snow filtered between the texels at a place of the glass +vec4 water_snow_at(uint slot, uint map, vec2 uv) +{ + vec2 p = uv * float(WATER_MAP) - 0.5; + ivec2 i = ivec2(floor(p)); + vec2 f = p - vec2(i); + vec4 a = water_snow_texel(slot, map, i); + vec4 b = water_snow_texel(slot, map, i + ivec2(1, 0)); + vec4 c = water_snow_texel(slot, map, i + ivec2(0, 1)); + vec4 d = water_snow_texel(slot, map, i + ivec2(1, 1)); + return mix(mix(a, b, f.x), mix(c, d, f.x), f.y); +} + // the radius of the footprint of a drop holding Volume mm3 of water, metres: a cap of a sphere meeting the glass at 40 degrees float water_radius(float volume) { diff --git a/shaders/ogl46/water_sim.glsl b/shaders/ogl46/water_sim.glsl index 75919c9e9..d611b6c0e 100644 --- a/shaders/ogl46/water_sim.glsl +++ b/shaders/ogl46/water_sim.glsl @@ -41,6 +41,11 @@ layout(std140, binding = WATER_UBO_BINDING) uniform water_ubo // every glass: x the landings tried in the step, y 1 / the most metres squared a unit of its uv holds, z 1 when it's simulated, // w the size of its drops (rain_scale of its material) vec4 water_slots[WATER_SLOTS]; + // the snow (water_snow.comp): x the flakes coming to a square metre of the ground in a second, y how much warmer than the air + // the glass is, degrees, z the speed of the vehicle, m/s, w the map of the snow the step reads (0, 1) + vec4 water_snow; + // every glass: 1 when its snow is simulated + vec4 water_snow_slots; }; const float WATER_GRAVITY = 9.81; diff --git a/shaders/ogl46/water_snow.comp b/shaders/ogl46/water_snow.comp new file mode 100644 index 000000000..ed0c8e34b --- /dev/null +++ b/shaders/ogl46/water_snow.comp @@ -0,0 +1,316 @@ +#version 460 core +#define STAGE_COMPUTE 1 +// the snow on the windscreens (water_sim.glsl, water.glsl): a step of the snow of the glasses of the snow, a thread per texel of +// the map of a glass, a row of groups per glass. the step reads one map of the snow and writes the other (water_snow.w says which +// one it reads), so a texel sees its neighbours as they were before the step +// +// what a texel holds: the snow, mm (as it lies, fluffy or packed), the water, mm (the melted snow, a film on the glass and soaked +// into the snow), how packed the snow is (0 fresh flakes .. 1 snow pressed by a blade) and a random number, the shape of its +// flakes (mat_snow_windscreen.frag). in a step, in this order: +// - the snow and the water move: wet heavy snow (slush) slides down the glass, dry powder is blown along it by the air at speed, +// the water runs down as a film and is pushed by the air; and snow piled higher than its neighbours by more than it holds slips +// onto them (a ridge left by a blade spreads into a wedge). what goes over the edge of the glass falls off +// - the blades: a blade going over a texel in the step takes its snow (a little stays, and a wet trace of the water), and pushes +// it on in front of itself: the texel just ahead of the line of texels the blade went over gets their snow, packed. at the end +// of its sweep the blade leaves it there, a ridge; pushed past the edge of the glass, it's gone +// - the flakes land: as many as come to the glass facing the snow coming at it against the cab (and a few in the eddies of the +// air where it doesn't face it), each bringing its snow to the texel; the faster the vehicle the more of the dry ones bounce off +// - the snow melts: the glass is warmer than the air (the cab is heated), the less so the faster the vehicle goes; above zero the +// snow melts at the glass into its water, the water dries slowly + +#include "common.glsl" +#include "water_sim.glsl" + +layout(local_size_x = WATER_GROUP_SIZE) in; + +// how dense the snow is: fresh flakes and snow pressed by a blade (the water in a mm of it, mm) +const float SNOW_FRESH = 0.1; +const float SNOW_PACKED = 0.4; +// the snow of a flake, mm3 of water (0.3 .. 2.5 as the flakes of the water passes, water_spawn.comp) +const float SNOW_FLAKE_LEAST = 0.3; +const float SNOW_FLAKE_MOST = 2.5; +// the speed of the snow coming at the glass in the eddies of the air, m/s: a glass not facing the snow gets a little of it +const float SNOW_EDDIES = 0.25; +// the most snow a texel holds, mm, and the step of the snow to a neighbour it holds without slipping onto it, mm +const float SNOW_MOST = 40.0; +const float SNOW_REPOSE = 3.0; +// the share of the snow over the step slipping onto the neighbour in a second +const float SNOW_SLIP = 6.0; +// the share of the snow a blade leaves, of the water, and of the snow it takes which it leaves as a wet trace +const float SNOW_WIPE_MISS = 0.03; +const float SNOW_WIPE_WATER = 0.25; +const float SNOW_WIPE_TRACE = 0.08; +// the longest line of texels a blade goes over in a step, texels +const int SNOW_WIPE_LINE = 12; +// the water the snow melts into at the glass a second for each degree the glass is above zero, mm +const float SNOW_MELT = 0.003; +// the water drying a second, mm +const float SNOW_DRY = 0.0004; +// how fast slush slides down a vertical glass, how fast dry powder goes with the air (a share of the speed of the air along the +// glass), how fast the film of water runs down a vertical glass and goes with the air, m/s +const float SNOW_SLIDE = 0.03; +const float SNOW_BLOW = 0.004; +const float SNOW_RUN = 0.02; +const float SNOW_RUN_AIR = 0.002; + +// the neighbours of a texel +const ivec2 SNOW_AROUND[8] = ivec2[8](ivec2(-1, -1), ivec2(0, -1), ivec2(1, -1), ivec2(-1, 0), ivec2(1, 0), ivec2(-1, 1), ivec2(0, 1), ivec2(1, 1)); + +uint snow_slot; +uint snow_from; +uint snow_axes_base; + +bool snow_on_glass(ivec2 texel) +{ + if (any(lessThan(texel, ivec2(0))) || any(greaterThanEqual(texel, ivec2(WATER_MAP)))) + return false; + return water_axes[(snow_axes_base + uint(texel.y * WATER_MAP + texel.x)) * 2u].w > 0.75; +} + +vec4 snow_get(ivec2 texel) +{ + return snow_on_glass(texel) ? water_snow_texel(snow_slot, snow_from, texel) : vec4(0.0); +} + +float snow_blade(ivec2 texel, int blade) +{ + texel = clamp(texel, ivec2(0), ivec2(WATER_MAP - 1)); + return water_blades[snow_axes_base + uint(texel.y * WATER_MAP + texel.x)][blade]; +} + +// whether the blade went over the texel in the step (it reaches it, and the place of the texel along its sweep is between where +// the blade was and where it is, the place it was at belonging to the step before) +bool snow_crossed(ivec2 texel, int blade) +{ + float before = water_blades_before[blade]; + float now = water_blades_now[blade]; + if ((before < 0.0) || (now < 0.0) || (now == before) || (false == snow_on_glass(texel))) + return false; + float place = snow_blade(texel, blade); + if (place <= 0.001) + return false; + return (now > before) ? ((place > before) && (place <= now)) : ((place < before) && (place >= now)); +} + +// the way the blade goes over the texel, a step of a texel (zero when it can't be told) +ivec2 snow_blade_way(ivec2 texel, int blade) +{ + float here = snow_blade(texel, blade); + float right = snow_blade(texel + ivec2(1, 0), blade); + float left = snow_blade(texel - ivec2(1, 0), blade); + float up = snow_blade(texel + ivec2(0, 1), blade); + float down = snow_blade(texel - ivec2(0, 1), blade); + // one-sided where a neighbour is out of the sweep + right = (right > 0.001) ? right : here; + left = (left > 0.001) ? left : here; + up = (up > 0.001) ? up : here; + down = (down > 0.001) ? down : here; + vec2 gradient = vec2(right - left, up - down); + if (dot(gradient, gradient) < 1e-12) + return ivec2(0); + vec2 way = normalize(gradient) * ((water_blades_now[blade] > water_blades_before[blade]) ? 1.0 : -1.0); + return ivec2(round(way)); +} + +// the frame of the glass at a texel, unfiltered +water_frame_s snow_frame(ivec2 texel) +{ + uint index = snow_axes_base + uint(texel.y * WATER_MAP + texel.x); + vec4 a = water_axes[index * 2u]; + vec4 b = water_axes[index * 2u + 1u]; + water_frame_s frame = water_frame_s(a.xyz, b.xyz, vec3(0.0, 0.0, 1.0), a.w); + vec3 n = cross(a.xyz, b.xyz); + if (dot(n, n) > 1e-24) + frame.normal = normalize(n) * ((b.w < 0.0) ? -1.0 : 1.0); + return frame; +} + +// how the snow (xy) and the water (zw) of a texel move, texels a second +vec4 snow_motion(ivec2 texel, vec4 state) +{ + if ((state.x <= 0.001) && (state.y <= 0.001)) + return vec4(0.0); + water_frame_s frame = snow_frame(texel); + vec3 n = frame.normal; + vec3 down = -water_up.xyz; + vec3 slope = down - n * dot(down, n); + vec3 air = water_air.xyz - n * dot(water_air.xyz, n); + float wind = length(air); + float density = mix(SNOW_FRESH, SNOW_PACKED, state.z); + float wet = state.y / (state.y + state.x * density + 1e-4); + // slush: wet and heavy enough to go; dry powder: loose and thin enough to be blown + float slide = SNOW_SLIDE * smoothstep(0.25, 0.7, wet) * smoothstep(2.0, 8.0, state.x); + float blow = SNOW_BLOW * smoothstep(10.0, 25.0, wind) * (1.0 - state.z) * (1.0 - smoothstep(0.1, 0.3, wet)) * (1.0 - smoothstep(1.0, 4.0, state.x)); + vec3 snow = slope * slide + air * blow; + // the film of water runs where there's enough of it, not the water soaked into the snow + float film = (1.0 - smoothstep(0.5, 3.0, state.x)); + vec3 water = (slope * SNOW_RUN * smoothstep(0.03, 0.15, state.y) + air * SNOW_RUN_AIR * smoothstep(0.03, 0.1, state.y)) * film; + return vec4(water_to_uv(frame, snow), water_to_uv(frame, water)) * float(WATER_MAP); +} + +// the shares of a texel going to its neighbours along x and along y in the step, for a motion in texels a second +vec2 snow_out(vec2 motion, float seconds) +{ + return min(abs(motion) * seconds, vec2(0.45)); +} + +// the snow and the water of the texel after they moved in the step: what leaves it, what comes from its neighbours; the +// packing and the shape go with the snow +vec4 snow_move(ivec2 texel, vec4 state, float seconds) +{ + vec4 motion = snow_motion(texel, state); + vec2 snowout = snow_out(motion.xy, seconds); + vec2 waterout = snow_out(motion.zw, seconds); + float snow = state.x * (1.0 - snowout.x - snowout.y); + float water = state.y * (1.0 - waterout.x - waterout.y); + float packed = state.z * snow; + float slip = min(SNOW_SLIP * seconds, 0.2); + const ivec2 sides[4] = ivec2[4](ivec2(1, 0), ivec2(-1, 0), ivec2(0, 1), ivec2(0, -1)); + for (int k = 0; k < 4; ++k) + { + ivec2 side = sides[k]; + ivec2 other = texel + side; + bool glass = snow_on_glass(other); + vec4 neighbour = glass ? water_snow_texel(snow_slot, snow_from, other) : vec4(0.0); + // slipping onto the neighbour (off the glass: falling off) and from it + float away = slip * max(state.x - neighbour.x - SNOW_REPOSE, 0.0); + snow -= away; + packed -= away * state.z; + if (false == glass) + continue; + float coming = slip * max(neighbour.x - state.x - SNOW_REPOSE, 0.0); + // what the motion of the neighbour brings: it goes this way along the axis of the side + vec4 itsmotion = snow_motion(other, neighbour); + vec2 itssnow = snow_out(itsmotion.xy, seconds); + vec2 itswater = snow_out(itsmotion.zw, seconds); + if (side.x != 0) + { + coming += (itsmotion.x * float(side.x) < 0.0) ? neighbour.x * itssnow.x : 0.0; + water += (itsmotion.z * float(side.x) < 0.0) ? neighbour.y * itswater.x : 0.0; + } + else + { + coming += (itsmotion.y * float(side.y) < 0.0) ? neighbour.x * itssnow.y : 0.0; + water += (itsmotion.w * float(side.y) < 0.0) ? neighbour.y * itswater.y : 0.0; + } + snow += coming; + packed += coming * neighbour.z; + } + snow = max(snow, 0.0); + return vec4(snow, max(water, 0.0), (snow > 1e-4) ? clamp(packed / snow, 0.0, 1.0) : 0.0, state.w); +} + +// the snow and the water of the line of texels the blade went over in the step, ending at a texel (the blade goes on from it to +// the texel ahead), and the packing of the snow (summed for its snow) +vec3 snow_line(ivec2 last, int blade, ivec2 way) +{ + vec3 line = vec3(0.0); + for (int k = 0; k < SNOW_WIPE_LINE; ++k) + { + ivec2 texel = last - way * k; + if (false == snow_crossed(texel, blade)) + break; + vec4 state = water_snow_texel(snow_slot, snow_from, texel); + line += vec3(state.x, state.y, state.x * state.z); + } + return line; +} + +void main() +{ + snow_slot = gl_WorkGroupID.y; + uint place = gl_GlobalInvocationID.x; + if ((water_snow_slots[snow_slot] < 0.5) || (place >= uint(WATER_MAP * WATER_MAP))) + return; + snow_from = (water_snow.w > 0.5) ? 1u : 0u; + uint to = 1u - snow_from; + snow_axes_base = snow_slot * uint(WATER_MAP * WATER_MAP); + if (place == 0u) + water_header[snow_slot].zw = vec2(1.0, float(to)); + ivec2 texel = ivec2(int(place % uint(WATER_MAP)), int(place / uint(WATER_MAP))); + uint index = water_snow_base(snow_slot, to) + 2u * place; + if (false == snow_on_glass(texel)) + { + water_cells[index] = 0u; + water_cells[index + 1u] = 0u; + return; + } + float seconds = water_step.x; + vec4 before = water_snow_texel(snow_slot, snow_from, texel); + vec4 state = snow_move(texel, before, seconds); + + // the blades: taken where they went over, pushed on in front of them + bool crossed = false; + vec3 pushed = vec3(0.0); + for (int blade = 0; blade < 4; ++blade) + { + if (snow_crossed(texel, blade)) + { + crossed = true; + continue; + } + for (int k = 0; k < 8; ++k) + { + ivec2 from = texel + SNOW_AROUND[k]; + if (false == snow_crossed(from, blade)) + continue; + ivec2 way = snow_blade_way(from, blade); + if ((way != ivec2(0)) && (from + way == texel)) + pushed += snow_line(from, blade, way); + } + } + if (crossed) + { + float taken = state.x * (1.0 - SNOW_WIPE_MISS); + state.x -= taken; + state.y = state.y * SNOW_WIPE_WATER + taken * mix(SNOW_FRESH, SNOW_PACKED, state.z) * SNOW_WIPE_TRACE; + } + if (pushed.x + pushed.y > 0.0) + { + float snow = state.x + pushed.x; + // pressed by the blade + state.z = (snow > 1e-4) ? clamp((state.z * state.x + max(pushed.z, pushed.x * 0.85)) / snow, 0.0, 1.0) : state.z; + state.x = snow; + state.y += pushed.y * 0.7; + } + + // the flakes landing + water_frame_s frame = snow_frame(texel); + float area = length(cross(frame.tu, frame.tv)) / float(WATER_MAP * WATER_MAP); // m2 + vec3 coming = water_air.xyz - water_up.xyz * water_air.w; // the snow against the cab, m/s + float facing = max(-dot(coming, frame.normal), 0.0) + SNOW_EDDIES; + float speed = water_snow.z; + float density = mix(SNOW_FRESH, SNOW_PACKED, state.z); + float wet = state.y / (state.y + state.x * density + 1e-4); + // the dry flakes bounce off a fast glass, the ones landing on wet snow or water stay + float sticking = 1.0 - 0.6 * smoothstep(15.0, 35.0, speed) * (1.0 - smoothstep(0.1, 0.4, wet)); + float landings = water_snow.x / max(water_air.w, 0.1) * facing * area * seconds * sticking; + vec4 random = water_random(place, snow_slot, water_counts.x, 0x5e0du); + float count = min(floor(landings) + ((random.x < fract(landings)) ? 1.0 : 0.0), 4.0); + if (count > 0.0) + { + float water = count * mix(SNOW_FLAKE_LEAST, SNOW_FLAKE_MOST, random.y * random.y); // mm3 + float added = water / SNOW_FRESH / max(area * 1e6, 1e-3); // mm of fresh snow over the texel + float snow = state.x + added; + state.z = state.z * state.x / snow; + // a flake on the bare glass has a shape of its own + state.w = (state.x < 0.3) ? random.z : state.w; + state.x = snow; + } + + // the melting at the warm glass and the drying + float glass = water_up.w + water_snow.y / (1.0 + speed / 12.0); + float melted = min(SNOW_MELT * max(glass, 0.0) * seconds, state.x * density); + state.x -= melted / max(density, 1e-3); + state.y = max(state.y + melted - SNOW_DRY * seconds, 0.0); + + state.x = clamp(state.x, 0.0, SNOW_MOST); + state.y = min(state.y, 4.0); + if (state.x < 0.002) + { + state.x = 0.0; + state.z = 0.0; + } + water_cells[index] = packHalf2x16(state.xy); + water_cells[index + 1u] = packHalf2x16(state.zw); +} diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index 8a81a1ee8..b0f14979c 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -70,11 +70,14 @@ layout(location = 1) out vec4 out_motion; #pragma param(reflection, 1, 2, 1, zero) #pragma param(glossiness, 1, 3, 1, glossiness) #pragma param(raindrop_grid_size, 2, 0, 1, one) +// snow_slot: 1 + the slot of the glass in the simulation of the snow (the renderer sets it), 0: none +#pragma param(snow_slot, 2, 2, 1, zero) #include "light_common.glsl" #include "apply_fog.glsl" #include "tonemapping.glsl" #include "random.glsl" +#include "water.glsl" layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 0) uniform sampler2D diffuse; layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 1) uniform sampler2D raindropsatlas; @@ -447,6 +450,158 @@ void snowFilm(float gridSize, inout vec3 accRGB, inout float accA, inout vec3 ac accA = accA + a * under; } +// --- The snow of the simulation (water_snow.comp): the map of the glass --------------------------------------------------- +// When the renderer simulates the snow of the glass (the param snow_slot holds 1 + its slot), the snow, the water, how packed the +// snow is and the shape of its flakes come from the map of the glass (water.glsl), which keeps them from frame to frame: the flakes +// land and stay where they landed, pile up into a layer, the blades push it into ridges at the ends of their sweeps and leave a wet +// trace, it melts at the warm glass and slush slides down. Here it's only drawn: +// - a texel of the map with a little snow is a flake (atlas tiles 0..2: fluffy when dry, a wet lump when wet or packed, crumbs), +// the more snow the bigger; with mostly water left it's the water spot (tile 3) +// - where the snow is thicker it's a layer: its edge torn by the grain of the snow, as opaque as it's thick (Beer-Lambert), grey +// and translucent when wet (slush), smoother and denser when packed; its relief from the slopes of the snow of the map +// - the water: wet glass bends the picture behind (the post-processing), the thin snow hazes it +// Without the simulation (an older renderer, no compute) the procedural snow below draws the glass as before. +const float snow_map_flake = 1.15; // size of a flake relative to a texel of the map (the snow of a texel) +const float snow_map_layer = 1.0; // mm of snow above which the flakes run together into a layer +const float snow_map_opaque = 1.8; // mm of fresh snow which lets 1/e of the light through (packed: half of it) +const float snow_map_relief = 0.6; // how much the slopes of the snow tilt its surface +const float snow_map_grain = 0.35; // the fine grain of the layer (its relief) +const float snow_map_wet_bend = 0.6; // how strongly a wet glass bends the picture behind it + +int snMapSlot = -1; +uint snMapIndex = 0u; +float snWet = 0.0; // set by snowMapped: the film of water (0 .. 1) +vec2 snWetN = vec2(0.0); // set by snowMapped: the slope of the water, for the bend of the picture + +// the snow of the map at a place of the glass +vec4 snMapAt(vec2 uv) +{ + return water_snow_at(uint(snMapSlot), snMapIndex, uv); +} + +// a flake of the map drawn over the accumulators: Local the place in its sprite (0 .. 1), Tile the corner of its tile in the atlas +void snowMapSprite(vec2 local, vec2 tile, float alpha, float tone, float flip, float c, float s, float lod, + inout vec3 accRGB, inout float accA, inout vec3 accN, inout float accTr) +{ + vec4 t = textureLod(raindropsatlas, tile + local * 0.5, lod); + vec4 n = textureLod(normalmap, tile + local * 0.5, lod); + float a = clamp(t.a * alpha * snow_opacity, 0.0, 1.0); + if (a <= 0.0) + return; + vec2 nxy = (n.rg * 2.0 - 1.0) * snow_bump; + nxy.x *= flip; + vec2 nuv = vec2(c * nxy.x - s * nxy.y, s * nxy.x + c * nxy.y); + vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); + float tr = (1.0 - t.a * 0.55); + accRGB = t.rgb * tone * a + accRGB * (1.0 - a); + accN = nT * a + accN * (1.0 - a); + accTr = tr * a + accTr * (1.0 - a); + accA = a + accA * (1.0 - a); +} + +// the flakes of the texels around the pixel +void snowMapFlakes(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float accA, inout vec3 accN, inout float accTr) +{ + vec2 p = f_coord * float(WATER_MAP); + ivec2 here = ivec2(floor(p)); + for (int oy = -1; oy <= 1; ++oy) + { + for (int ox = -1; ox <= 1; ++ox) + { + ivec2 texel = here + ivec2(ox, oy); + vec4 q = water_snow_texel(uint(snMapSlot), snMapIndex, texel); + float density = mix(0.1, 0.4, q.z); + float wet = q.y / (q.y + q.x * density + 1e-4); + bool spot = (q.x < 0.05) && (q.y > 0.015); // a flake melted into its water + if ((q.x < 0.05) && (false == spot)) + continue; + uint seed = Hash(uvec3(uvec2(texel), uint(q.w * 65535.0) + 7u * uint(snMapSlot))); + vec2 center = vec2(texel) + vec2(0.15 + 0.7 * RandF(seed), 0.15 + 0.7 * RandF(seed)); + float ang = RandF(seed) * 6.2831853; + float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; + float kind = RandF(seed); + float tone = mix(0.94, 1.04, RandF(seed)); + float aniso = mix(0.62, 1.0, RandF(seed)); + // the more snow the texel holds the bigger the flake (a lump of a few flakes) + float size = snow_map_flake * mix(0.6, 1.0, RandF(seed)) * (spot ? mix(0.5, 1.1, smoothstep(0.015, 0.2, q.y)) + : mix(0.7, 1.6, smoothstep(0.05, 2.0, q.x))); + vec2 d = (p - center) * aspect; + float c = cos(ang); + float s = sin(ang); + vec2 r = vec2(c * d.x + s * d.y, -s * d.x + c * d.y); + r.x *= flip / aniso; + vec2 local = r / size + 0.5; + if (any(lessThan(local, vec2(0.0))) || any(greaterThan(local, vec2(1.0)))) + continue; + float sizeUV = size / float(WATER_MAP); + float lod = clamp(log2(max(pixelUV / sizeUV * 0.5 * float(textureSize(raindropsatlas, 0).x), 1.0)), 0.0, 4.0); + vec2 tile; + if (spot) + tile = vec2(0.5, 0.0); + else if ((wet > 0.3) || (q.z > 0.5) || (kind < 0.30)) + tile = vec2(0.5, 0.5); // a wet lump + else if (kind < 0.75) + tile = vec2(0.0, 0.5); // fluffy + else + tile = vec2(0.0, 0.0); // crumbs + float alpha = spot ? smoothstep(0.015, 0.08, q.y) : smoothstep(0.05, 0.25, q.x); + snowMapSprite(local, tile, alpha, tone, flip, c, s, lod, accRGB, accA, accN, accTr); + } + } +} + +// the snow of the map at the pixel: the flakes, the layer of the snow under them, the water, the haze +void snowMapped(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float accA, inout float smear, inout vec3 accN, inout float accTr) +{ + vec4 q = snMapAt(f_coord); + float e = 1.0 / float(WATER_MAP); + vec4 qr = snMapAt(f_coord + vec2(e, 0.0)); + vec4 ql = snMapAt(f_coord - vec2(e, 0.0)); + vec4 qu = snMapAt(f_coord + vec2(0.0, e)); + vec4 qd = snMapAt(f_coord - vec2(0.0, e)); + float around = (q.x + qr.x + ql.x + qu.x + qd.x) * 0.2; + + // the flakes of thin snow and the water spots + snowMapFlakes(aspect, pixelUV, accRGB, accA, accN, accTr); + + // the water: the film bends the picture behind + snWet = smoothstep(0.02, 0.25, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); + snWetN = vec2(qr.y - ql.y, qu.y - qd.y) * 2.0 + (vec2(snNoise(f_coord * 900.0), snNoise(f_coord * 900.0 + 31.0)) - 0.5) * 0.6 * snWet; + smear = max(smear, snWet * snow_melt_blur * 0.6); + // thin snow hazes the picture around it + snHaze = max(snHaze, smoothstep(0.03, 0.6, around)); + + // the layer, where the snow has run together + vec2 gp = f_coord * float(WATER_MAP) * aspect; + float grain = snFbm(gp * 0.9 + 3.0) * 0.55 + snFbm(gp * 2.7 + 11.0) * 0.30 + snFbm(gp * 7.1 + 5.0) * 0.15; + float edge = (q.x - snow_map_layer) / max(snow_map_layer, 1e-3) + (grain - 0.5) * 1.6; + float cover = smoothstep(0.0, 0.35, edge); + if (cover <= 0.002) + return; + float density = mix(0.1, 0.4, q.z); + float wet = q.y / (q.y + q.x * density + 1e-4); + float opaque = snow_map_opaque * mix(1.0, 0.5, q.z); + float thick = 1.0 - exp(-q.x / opaque); + // the relief: the slopes of the snow of the map (ridges, the edges of the swept arcs) and the grain of the fresh snow + vec2 slope = vec2(qr.x - ql.x, qu.x - qd.x) * 0.5 * snow_map_relief; + float f1 = snFbm(gp * 3.3); + float ef = 0.05; + vec2 gf = vec2(snFbm(gp * 3.3 + vec2(ef, 0.0)) - f1, snFbm(gp * 3.3 + vec2(0.0, ef)) - f1) / ef; + vec3 nT = normalize(vec3(-(slope + gf * snow_map_grain * (1.0 - 0.6 * q.z)) * snow_bump, 1.0)); + + vec3 fresh = vec3(0.93, 0.95, 0.98); + vec3 packed = vec3(0.84, 0.87, 0.91); + vec3 slush = vec3(0.60, 0.66, 0.73); + vec3 col = mix(mix(fresh, packed, q.z), slush, smoothstep(0.2, 0.7, wet)); + col *= (0.80 + 0.30 * f1 * (1.0 - 0.5 * q.z)) * (0.92 + 0.12 * grain); + float a = clamp(cover * mix(0.35, 0.97, thick) * mix(1.0, 0.75, smoothstep(0.3, 0.8, wet)) * snow_pack * snow_opacity, 0.0, 0.97); + float under = 1.0 - accA; + accRGB = accRGB + col * a * under; + accN = accN + nT * a * under; + accTr = accTr + mix(0.60, 0.25, thick) * a * under; + accA = accA + a * under; +} + void main() { // Derivatives first, in uniform control flow (no discard before them). @@ -475,7 +630,20 @@ void main() float smear = 0.0; vec3 snowN = vec3(0.0); float snowTr = 0.0; - if (rain_params.x > 0.0) + // the snow of the simulation where the glass has a map of it, else made up as before + snMapSlot = int(param[2].z + 0.5) - 1; + bool mapped = (snMapSlot >= 0) && (snMapSlot < WATER_SLOTS) && water_snow_map(uint(snMapSlot), snMapIndex); + if (mapped) + { + // the texels of the map as they lie on the glass (the uv may be stretched) + ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); + uint axis = (uint(snMapSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; + vec2 span = vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)); + if (min(span.x, span.y) > 1e-6) + aspect = span / max(span.x, span.y); + snowMapped(aspect, pixelUV, snowRGB, snowA, smear, snowN, snowTr); + } + else if (rain_params.x > 0.0) { float mass = 0.0; if (snow_small > 0.0) @@ -536,7 +704,13 @@ void main() { float thin = smoothstep(0.04, 0.20, snowA) * (1.0 - smoothstep(0.55, 0.90, snowA)); vec4 req = vec4(0.0); - if ((snow_distort > 0.0) && (thin > 0.30) && (glassA < 0.5)) + if ((snWet > 0.25) && (snowA < 0.35) && (glassA < 0.5)) + { + // the water on the glass: its film and its spots bend the picture behind + vec2 bend = clamp(-snWetN * snow_map_wet_bend, vec2(-1.0), vec2(1.0)) * smoothstep(0.25, 0.6, snWet); + req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); + } + else if ((snow_distort > 0.0) && (thin > 0.30) && (glassA < 0.5)) { vec2 slope = snowN.xy / max(snowA, 1e-3); vec2 bend = clamp(-slope * snow_distort, vec2(-1.0), vec2(1.0)) * smoothstep(0.30, 0.60, thin) * (SNOW_REFR_MAXPX / WS_REFR_MAXPX); diff --git a/shaders/vk14/water.glsl b/shaders/vk14/water.glsl index 41d672d60..ed2b1094d 100644 --- a/shaders/vk14/water.glsl +++ b/shaders/vk14/water.glsl @@ -54,6 +54,45 @@ layout(std430, set = PASS_SET, binding = WATER_SSBO) readonly buffer water_ssbo uint water_cells[]; }; +// the snow on a glass of the snow (water_snow.comp, mat_snow_windscreen.frag): two maps of WATER_MAP x WATER_MAP texels after the +// wetted paths in water_cells, two uint a texel (halves: x the snow, mm, y the water, mm, z how packed the snow is 0 .. 1, w random +// 0 .. 1, the shape of its flakes); a step reads one and writes the other, the header of the glass says which one is the latest +// (z 1 when there's a map of the snow, w the map) +uint water_snow_base(uint slot, uint map) +{ + return uint(WATER_SLOTS * WATER_GRID * WATER_GRID * (1 + WATER_CELL_DROPS)) + uint(WATER_SLOTS * WATER_TRAIL * WATER_TRAIL) + (map * uint(WATER_SLOTS) + slot) * uint(WATER_MAP * WATER_MAP * 2); +} + +// a texel of a map of the snow, nothing outside the map +vec4 water_snow_texel(uint slot, uint map, ivec2 texel) +{ + if (any(lessThan(texel, ivec2(0))) || any(greaterThanEqual(texel, ivec2(WATER_MAP)))) + return vec4(0.0); + uint index = water_snow_base(slot, map) + 2u * uint(texel.y * WATER_MAP + texel.x); + return vec4(unpackHalf2x16(water_cells[index]), unpackHalf2x16(water_cells[index + 1u])); +} + +// the latest map of the snow of a glass; false when there's none yet +bool water_snow_map(uint slot, out uint map) +{ + vec4 header = water_header[slot]; + map = (header.w > 0.5) ? 1u : 0u; + return header.z > 0.5; +} + +// the latest map of the snow filtered between the texels at a place of the glass +vec4 water_snow_at(uint slot, uint map, vec2 uv) +{ + vec2 p = uv * float(WATER_MAP) - 0.5; + ivec2 i = ivec2(floor(p)); + vec2 f = p - vec2(i); + vec4 a = water_snow_texel(slot, map, i); + vec4 b = water_snow_texel(slot, map, i + ivec2(1, 0)); + vec4 c = water_snow_texel(slot, map, i + ivec2(0, 1)); + vec4 d = water_snow_texel(slot, map, i + ivec2(1, 1)); + return mix(mix(a, b, f.x), mix(c, d, f.x), f.y); +} + // the radius of the footprint of a drop holding Volume mm3 of water, metres: a cap of a sphere meeting the glass at 40 degrees float water_radius(float volume) { diff --git a/shaders/vk14/water_sim.glsl b/shaders/vk14/water_sim.glsl index 82710150a..d1794ca64 100644 --- a/shaders/vk14/water_sim.glsl +++ b/shaders/vk14/water_sim.glsl @@ -41,6 +41,11 @@ layout(std140, set = COMPUTE_SET, binding = 1) uniform water_ubo // every glass: x the landings tried in the step, y 1 / the most metres squared a unit of its uv holds, z 1 when it's simulated, // w the size of its drops (rain_scale of its material) vec4 water_slots[WATER_SLOTS]; + // the snow (water_snow.comp): x the flakes coming to a square metre of the ground in a second, y how much warmer than the air + // the glass is, degrees, z the speed of the vehicle, m/s, w the map of the snow the step reads (0, 1) + vec4 water_snow; + // every glass: 1 when its snow is simulated + vec4 water_snow_slots; }; const float WATER_GRAVITY = 9.81; diff --git a/shaders/vk14/water_snow.comp b/shaders/vk14/water_snow.comp new file mode 100644 index 000000000..d241d5fe3 --- /dev/null +++ b/shaders/vk14/water_snow.comp @@ -0,0 +1,319 @@ +#version 460 core +#define STAGE_COMPUTE 1 +// the snow on the windscreens (water_sim.glsl, water.glsl): a step of the snow of the glasses of the snow, a thread per texel of +// the map of a glass, a row of groups per glass. the step reads one map of the snow and writes the other (water_snow.w says which +// one it reads), so a texel sees its neighbours as they were before the step +// +// what a texel holds: the snow, mm (as it lies, fluffy or packed), the water, mm (the melted snow, a film on the glass and soaked +// into the snow), how packed the snow is (0 fresh flakes .. 1 snow pressed by a blade) and a random number, the shape of its +// flakes (mat_snow_windscreen.frag). in a step, in this order: +// - the snow and the water move: wet heavy snow (slush) slides down the glass, dry powder is blown along it by the air at speed, +// the water runs down as a film and is pushed by the air; and snow piled higher than its neighbours by more than it holds slips +// onto them (a ridge left by a blade spreads into a wedge). what goes over the edge of the glass falls off +// - the blades: a blade going over a texel in the step takes its snow (a little stays, and a wet trace of the water), and pushes +// it on in front of itself: the texel just ahead of the line of texels the blade went over gets their snow, packed. at the end +// of its sweep the blade leaves it there, a ridge; pushed past the edge of the glass, it's gone +// - the flakes land: as many as come to the glass facing the snow coming at it against the cab (and a few in the eddies of the +// air where it doesn't face it), each bringing its snow to the texel; the faster the vehicle the more of the dry ones bounce off +// - the snow melts: the glass is warmer than the air (the cab is heated), the less so the faster the vehicle goes; above zero the +// snow melts at the glass into its water, the water dries slowly + +// none of the pass set: everything the kernel reads is pushed with its dispatch (set COMPUTE_SET, water_sim.glsl), so it runs +// before the passes of the frame set theirs up +#define LAYOUT_UI 1 +#include "common.glsl" +#include "water_sim.glsl" + +layout(local_size_x = WATER_GROUP_SIZE) in; + +// how dense the snow is: fresh flakes and snow pressed by a blade (the water in a mm of it, mm) +const float SNOW_FRESH = 0.1; +const float SNOW_PACKED = 0.4; +// the snow of a flake, mm3 of water (0.3 .. 2.5 as the flakes of the water passes, water_spawn.comp) +const float SNOW_FLAKE_LEAST = 0.3; +const float SNOW_FLAKE_MOST = 2.5; +// the speed of the snow coming at the glass in the eddies of the air, m/s: a glass not facing the snow gets a little of it +const float SNOW_EDDIES = 0.25; +// the most snow a texel holds, mm, and the step of the snow to a neighbour it holds without slipping onto it, mm +const float SNOW_MOST = 40.0; +const float SNOW_REPOSE = 3.0; +// the share of the snow over the step slipping onto the neighbour in a second +const float SNOW_SLIP = 6.0; +// the share of the snow a blade leaves, of the water, and of the snow it takes which it leaves as a wet trace +const float SNOW_WIPE_MISS = 0.03; +const float SNOW_WIPE_WATER = 0.25; +const float SNOW_WIPE_TRACE = 0.08; +// the longest line of texels a blade goes over in a step, texels +const int SNOW_WIPE_LINE = 12; +// the water the snow melts into at the glass a second for each degree the glass is above zero, mm +const float SNOW_MELT = 0.003; +// the water drying a second, mm +const float SNOW_DRY = 0.0004; +// how fast slush slides down a vertical glass, how fast dry powder goes with the air (a share of the speed of the air along the +// glass), how fast the film of water runs down a vertical glass and goes with the air, m/s +const float SNOW_SLIDE = 0.03; +const float SNOW_BLOW = 0.004; +const float SNOW_RUN = 0.02; +const float SNOW_RUN_AIR = 0.002; + +// the neighbours of a texel +const ivec2 SNOW_AROUND[8] = ivec2[8](ivec2(-1, -1), ivec2(0, -1), ivec2(1, -1), ivec2(-1, 0), ivec2(1, 0), ivec2(-1, 1), ivec2(0, 1), ivec2(1, 1)); + +uint snow_slot; +uint snow_from; +uint snow_axes_base; + +bool snow_on_glass(ivec2 texel) +{ + if (any(lessThan(texel, ivec2(0))) || any(greaterThanEqual(texel, ivec2(WATER_MAP)))) + return false; + return water_axes[(snow_axes_base + uint(texel.y * WATER_MAP + texel.x)) * 2u].w > 0.75; +} + +vec4 snow_get(ivec2 texel) +{ + return snow_on_glass(texel) ? water_snow_texel(snow_slot, snow_from, texel) : vec4(0.0); +} + +float snow_blade(ivec2 texel, int blade) +{ + texel = clamp(texel, ivec2(0), ivec2(WATER_MAP - 1)); + return water_blades[snow_axes_base + uint(texel.y * WATER_MAP + texel.x)][blade]; +} + +// whether the blade went over the texel in the step (it reaches it, and the place of the texel along its sweep is between where +// the blade was and where it is, the place it was at belonging to the step before) +bool snow_crossed(ivec2 texel, int blade) +{ + float before = water_blades_before[blade]; + float now = water_blades_now[blade]; + if ((before < 0.0) || (now < 0.0) || (now == before) || (false == snow_on_glass(texel))) + return false; + float place = snow_blade(texel, blade); + if (place <= 0.001) + return false; + return (now > before) ? ((place > before) && (place <= now)) : ((place < before) && (place >= now)); +} + +// the way the blade goes over the texel, a step of a texel (zero when it can't be told) +ivec2 snow_blade_way(ivec2 texel, int blade) +{ + float here = snow_blade(texel, blade); + float right = snow_blade(texel + ivec2(1, 0), blade); + float left = snow_blade(texel - ivec2(1, 0), blade); + float up = snow_blade(texel + ivec2(0, 1), blade); + float down = snow_blade(texel - ivec2(0, 1), blade); + // one-sided where a neighbour is out of the sweep + right = (right > 0.001) ? right : here; + left = (left > 0.001) ? left : here; + up = (up > 0.001) ? up : here; + down = (down > 0.001) ? down : here; + vec2 gradient = vec2(right - left, up - down); + if (dot(gradient, gradient) < 1e-12) + return ivec2(0); + vec2 way = normalize(gradient) * ((water_blades_now[blade] > water_blades_before[blade]) ? 1.0 : -1.0); + return ivec2(round(way)); +} + +// the frame of the glass at a texel, unfiltered +water_frame_s snow_frame(ivec2 texel) +{ + uint index = snow_axes_base + uint(texel.y * WATER_MAP + texel.x); + vec4 a = water_axes[index * 2u]; + vec4 b = water_axes[index * 2u + 1u]; + water_frame_s frame = water_frame_s(a.xyz, b.xyz, vec3(0.0, 0.0, 1.0), a.w); + vec3 n = cross(a.xyz, b.xyz); + if (dot(n, n) > 1e-24) + frame.normal = normalize(n) * ((b.w < 0.0) ? -1.0 : 1.0); + return frame; +} + +// how the snow (xy) and the water (zw) of a texel move, texels a second +vec4 snow_motion(ivec2 texel, vec4 state) +{ + if ((state.x <= 0.001) && (state.y <= 0.001)) + return vec4(0.0); + water_frame_s frame = snow_frame(texel); + vec3 n = frame.normal; + vec3 down = -water_up.xyz; + vec3 slope = down - n * dot(down, n); + vec3 air = water_air.xyz - n * dot(water_air.xyz, n); + float wind = length(air); + float density = mix(SNOW_FRESH, SNOW_PACKED, state.z); + float wet = state.y / (state.y + state.x * density + 1e-4); + // slush: wet and heavy enough to go; dry powder: loose and thin enough to be blown + float slide = SNOW_SLIDE * smoothstep(0.25, 0.7, wet) * smoothstep(2.0, 8.0, state.x); + float blow = SNOW_BLOW * smoothstep(10.0, 25.0, wind) * (1.0 - state.z) * (1.0 - smoothstep(0.1, 0.3, wet)) * (1.0 - smoothstep(1.0, 4.0, state.x)); + vec3 snow = slope * slide + air * blow; + // the film of water runs where there's enough of it, not the water soaked into the snow + float film = (1.0 - smoothstep(0.5, 3.0, state.x)); + vec3 water = (slope * SNOW_RUN * smoothstep(0.03, 0.15, state.y) + air * SNOW_RUN_AIR * smoothstep(0.03, 0.1, state.y)) * film; + return vec4(water_to_uv(frame, snow), water_to_uv(frame, water)) * float(WATER_MAP); +} + +// the shares of a texel going to its neighbours along x and along y in the step, for a motion in texels a second +vec2 snow_out(vec2 motion, float seconds) +{ + return min(abs(motion) * seconds, vec2(0.45)); +} + +// the snow and the water of the texel after they moved in the step: what leaves it, what comes from its neighbours; the +// packing and the shape go with the snow +vec4 snow_move(ivec2 texel, vec4 state, float seconds) +{ + vec4 motion = snow_motion(texel, state); + vec2 snowout = snow_out(motion.xy, seconds); + vec2 waterout = snow_out(motion.zw, seconds); + float snow = state.x * (1.0 - snowout.x - snowout.y); + float water = state.y * (1.0 - waterout.x - waterout.y); + float packed = state.z * snow; + float slip = min(SNOW_SLIP * seconds, 0.2); + const ivec2 sides[4] = ivec2[4](ivec2(1, 0), ivec2(-1, 0), ivec2(0, 1), ivec2(0, -1)); + for (int k = 0; k < 4; ++k) + { + ivec2 side = sides[k]; + ivec2 other = texel + side; + bool glass = snow_on_glass(other); + vec4 neighbour = glass ? water_snow_texel(snow_slot, snow_from, other) : vec4(0.0); + // slipping onto the neighbour (off the glass: falling off) and from it + float away = slip * max(state.x - neighbour.x - SNOW_REPOSE, 0.0); + snow -= away; + packed -= away * state.z; + if (false == glass) + continue; + float coming = slip * max(neighbour.x - state.x - SNOW_REPOSE, 0.0); + // what the motion of the neighbour brings: it goes this way along the axis of the side + vec4 itsmotion = snow_motion(other, neighbour); + vec2 itssnow = snow_out(itsmotion.xy, seconds); + vec2 itswater = snow_out(itsmotion.zw, seconds); + if (side.x != 0) + { + coming += (itsmotion.x * float(side.x) < 0.0) ? neighbour.x * itssnow.x : 0.0; + water += (itsmotion.z * float(side.x) < 0.0) ? neighbour.y * itswater.x : 0.0; + } + else + { + coming += (itsmotion.y * float(side.y) < 0.0) ? neighbour.x * itssnow.y : 0.0; + water += (itsmotion.w * float(side.y) < 0.0) ? neighbour.y * itswater.y : 0.0; + } + snow += coming; + packed += coming * neighbour.z; + } + snow = max(snow, 0.0); + return vec4(snow, max(water, 0.0), (snow > 1e-4) ? clamp(packed / snow, 0.0, 1.0) : 0.0, state.w); +} + +// the snow and the water of the line of texels the blade went over in the step, ending at a texel (the blade goes on from it to +// the texel ahead), and the packing of the snow (summed for its snow) +vec3 snow_line(ivec2 last, int blade, ivec2 way) +{ + vec3 line = vec3(0.0); + for (int k = 0; k < SNOW_WIPE_LINE; ++k) + { + ivec2 texel = last - way * k; + if (false == snow_crossed(texel, blade)) + break; + vec4 state = water_snow_texel(snow_slot, snow_from, texel); + line += vec3(state.x, state.y, state.x * state.z); + } + return line; +} + +void main() +{ + snow_slot = gl_WorkGroupID.y; + uint place = gl_GlobalInvocationID.x; + if ((water_snow_slots[snow_slot] < 0.5) || (place >= uint(WATER_MAP * WATER_MAP))) + return; + snow_from = (water_snow.w > 0.5) ? 1u : 0u; + uint to = 1u - snow_from; + snow_axes_base = snow_slot * uint(WATER_MAP * WATER_MAP); + if (place == 0u) + water_header[snow_slot].zw = vec2(1.0, float(to)); + ivec2 texel = ivec2(int(place % uint(WATER_MAP)), int(place / uint(WATER_MAP))); + uint index = water_snow_base(snow_slot, to) + 2u * place; + if (false == snow_on_glass(texel)) + { + water_cells[index] = 0u; + water_cells[index + 1u] = 0u; + return; + } + float seconds = water_step.x; + vec4 before = water_snow_texel(snow_slot, snow_from, texel); + vec4 state = snow_move(texel, before, seconds); + + // the blades: taken where they went over, pushed on in front of them + bool crossed = false; + vec3 pushed = vec3(0.0); + for (int blade = 0; blade < 4; ++blade) + { + if (snow_crossed(texel, blade)) + { + crossed = true; + continue; + } + for (int k = 0; k < 8; ++k) + { + ivec2 from = texel + SNOW_AROUND[k]; + if (false == snow_crossed(from, blade)) + continue; + ivec2 way = snow_blade_way(from, blade); + if ((way != ivec2(0)) && (from + way == texel)) + pushed += snow_line(from, blade, way); + } + } + if (crossed) + { + float taken = state.x * (1.0 - SNOW_WIPE_MISS); + state.x -= taken; + state.y = state.y * SNOW_WIPE_WATER + taken * mix(SNOW_FRESH, SNOW_PACKED, state.z) * SNOW_WIPE_TRACE; + } + if (pushed.x + pushed.y > 0.0) + { + float snow = state.x + pushed.x; + // pressed by the blade + state.z = (snow > 1e-4) ? clamp((state.z * state.x + max(pushed.z, pushed.x * 0.85)) / snow, 0.0, 1.0) : state.z; + state.x = snow; + state.y += pushed.y * 0.7; + } + + // the flakes landing + water_frame_s frame = snow_frame(texel); + float area = length(cross(frame.tu, frame.tv)) / float(WATER_MAP * WATER_MAP); // m2 + vec3 coming = water_air.xyz - water_up.xyz * water_air.w; // the snow against the cab, m/s + float facing = max(-dot(coming, frame.normal), 0.0) + SNOW_EDDIES; + float speed = water_snow.z; + float density = mix(SNOW_FRESH, SNOW_PACKED, state.z); + float wet = state.y / (state.y + state.x * density + 1e-4); + // the dry flakes bounce off a fast glass, the ones landing on wet snow or water stay + float sticking = 1.0 - 0.6 * smoothstep(15.0, 35.0, speed) * (1.0 - smoothstep(0.1, 0.4, wet)); + float landings = water_snow.x / max(water_air.w, 0.1) * facing * area * seconds * sticking; + vec4 random = water_random(place, snow_slot, water_counts.x, 0x5e0du); + float count = min(floor(landings) + ((random.x < fract(landings)) ? 1.0 : 0.0), 4.0); + if (count > 0.0) + { + float water = count * mix(SNOW_FLAKE_LEAST, SNOW_FLAKE_MOST, random.y * random.y); // mm3 + float added = water / SNOW_FRESH / max(area * 1e6, 1e-3); // mm of fresh snow over the texel + float snow = state.x + added; + state.z = state.z * state.x / snow; + // a flake on the bare glass has a shape of its own + state.w = (state.x < 0.3) ? random.z : state.w; + state.x = snow; + } + + // the melting at the warm glass and the drying + float glass = water_up.w + water_snow.y / (1.0 + speed / 12.0); + float melted = min(SNOW_MELT * max(glass, 0.0) * seconds, state.x * density); + state.x -= melted / max(density, 1e-3); + state.y = max(state.y + melted - SNOW_DRY * seconds, 0.0); + + state.x = clamp(state.x, 0.0, SNOW_MOST); + state.y = min(state.y, 4.0); + if (state.x < 0.002) + { + state.x = 0.0; + state.z = 0.0; + } + water_cells[index] = packHalf2x16(state.xy); + water_cells[index + 1u] = packHalf2x16(state.zw); +} From b502311b1e97f55f8815656b24300fa8eb4d8c1c Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Tue, 10 Nov 2026 21:33:23 +0100 Subject: [PATCH 063/123] Snow windscreen: a blade leaves the glass clear, not streaks of the snow it pushes A blade going over the texel holding the snow it pushes left 3% of all of it there, a stripe of snow for every texel of its way; it leaves 3% of the snow up to 0.03 mm now, and a wet trace of at most 0.015 mm. A thin film of water dries and runs off in a few seconds, the water spots are fewer, the haze needs more snow, the packed snow is whiter. No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_snow_windscreen.frag | 15 +++++++++------ shaders/ogl46/water_snow.comp | 22 ++++++++++++++-------- shaders/vk14/mat_snow_windscreen.frag | 15 +++++++++------ shaders/vk14/water_snow.comp | 22 ++++++++++++++-------- 4 files changed, 46 insertions(+), 28 deletions(-) diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index 5d4ce8097..5bc35bb82 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -507,10 +507,13 @@ void snowMapFlakes(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float ac vec4 q = water_snow_texel(uint(snMapSlot), snMapIndex, texel); float density = mix(0.1, 0.4, q.z); float wet = q.y / (q.y + q.x * density + 1e-4); - bool spot = (q.x < 0.05) && (q.y > 0.015); // a flake melted into its water + bool spot = (q.x < 0.05) && (q.y > 0.03); // a flake melted into its water if ((q.x < 0.05) && (false == spot)) continue; uint seed = Hash(uvec3(uvec2(texel), uint(q.w * 65535.0) + 7u * uint(snMapSlot))); + // the water of a texel is a droplet only now and then: the more water the more of them + if (spot && (RandF(seed) > smoothstep(0.03, 0.2, q.y))) + continue; vec2 center = vec2(texel) + vec2(0.15 + 0.7 * RandF(seed), 0.15 + 0.7 * RandF(seed)); float ang = RandF(seed) * 6.2831853; float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; @@ -518,7 +521,7 @@ void snowMapFlakes(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float ac float tone = mix(0.94, 1.04, RandF(seed)); float aniso = mix(0.62, 1.0, RandF(seed)); // the more snow the texel holds the bigger the flake (a lump of a few flakes) - float size = snow_map_flake * mix(0.6, 1.0, RandF(seed)) * (spot ? mix(0.5, 1.1, smoothstep(0.015, 0.2, q.y)) + float size = snow_map_flake * mix(0.6, 1.0, RandF(seed)) * (spot ? mix(0.5, 1.1, smoothstep(0.03, 0.3, q.y)) : mix(0.7, 1.6, smoothstep(0.05, 2.0, q.x))); vec2 d = (p - center) * aspect; float c = cos(ang); @@ -539,7 +542,7 @@ void snowMapFlakes(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float ac tile = vec2(0.0, 0.5); // fluffy else tile = vec2(0.0, 0.0); // crumbs - float alpha = spot ? smoothstep(0.015, 0.08, q.y) : smoothstep(0.05, 0.25, q.x); + float alpha = spot ? smoothstep(0.03, 0.1, q.y) : smoothstep(0.05, 0.25, q.x); snowMapSprite(local, tile, alpha, tone, flip, c, s, lod, accRGB, accA, accN, accTr); } } @@ -560,11 +563,11 @@ void snowMapped(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float accA, snowMapFlakes(aspect, pixelUV, accRGB, accA, accN, accTr); // the water: the film bends the picture behind - snWet = smoothstep(0.02, 0.25, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); + snWet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); snWetN = vec2(qr.y - ql.y, qu.y - qd.y) * 2.0 + (vec2(snNoise(f_coord * 900.0), snNoise(f_coord * 900.0 + 31.0)) - 0.5) * 0.6 * snWet; smear = max(smear, snWet * snow_melt_blur * 0.6); // thin snow hazes the picture around it - snHaze = max(snHaze, smoothstep(0.03, 0.6, around)); + snHaze = max(snHaze, smoothstep(0.15, 1.0, around)); // the layer, where the snow has run together vec2 gp = f_coord * float(WATER_MAP) * aspect; @@ -585,7 +588,7 @@ void snowMapped(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float accA, vec3 nT = normalize(vec3(-(slope + gf * snow_map_grain * (1.0 - 0.6 * q.z)) * snow_bump, 1.0)); vec3 fresh = vec3(0.93, 0.95, 0.98); - vec3 packed = vec3(0.84, 0.87, 0.91); + vec3 packed = vec3(0.89, 0.91, 0.94); vec3 slush = vec3(0.60, 0.66, 0.73); vec3 col = mix(mix(fresh, packed, q.z), slush, smoothstep(0.2, 0.7, wet)); col *= (0.80 + 0.30 * f1 * (1.0 - 0.5 * q.z)) * (0.92 + 0.12 * grain); diff --git a/shaders/ogl46/water_snow.comp b/shaders/ogl46/water_snow.comp index ed0c8e34b..67dfc38d2 100644 --- a/shaders/ogl46/water_snow.comp +++ b/shaders/ogl46/water_snow.comp @@ -36,16 +36,20 @@ const float SNOW_MOST = 40.0; const float SNOW_REPOSE = 3.0; // the share of the snow over the step slipping onto the neighbour in a second const float SNOW_SLIP = 6.0; -// the share of the snow a blade leaves, of the water, and of the snow it takes which it leaves as a wet trace +// the share of the snow a blade leaves (at most SNOW_WIPE_LEFT mm: the snow it pushes along goes with it), of the water, and +// of the water of the snow it takes which it leaves as a wet trace (at most SNOW_WIPE_WET mm) const float SNOW_WIPE_MISS = 0.03; -const float SNOW_WIPE_WATER = 0.25; +const float SNOW_WIPE_LEFT = 0.03; +const float SNOW_WIPE_WATER = 0.1; const float SNOW_WIPE_TRACE = 0.08; +const float SNOW_WIPE_WET = 0.015; // the longest line of texels a blade goes over in a step, texels const int SNOW_WIPE_LINE = 12; // the water the snow melts into at the glass a second for each degree the glass is above zero, mm const float SNOW_MELT = 0.003; -// the water drying a second, mm +// the water drying a second, mm, and the share of a thin film going in a second (it dries and runs off as droplets) const float SNOW_DRY = 0.0004; +const float SNOW_FILM_DRY = 0.15; // how fast slush slides down a vertical glass, how fast dry powder goes with the air (a share of the speed of the air along the // glass), how fast the film of water runs down a vertical glass and goes with the air, m/s const float SNOW_SLIDE = 0.03; @@ -261,9 +265,10 @@ void main() } if (crossed) { - float taken = state.x * (1.0 - SNOW_WIPE_MISS); - state.x -= taken; - state.y = state.y * SNOW_WIPE_WATER + taken * mix(SNOW_FRESH, SNOW_PACKED, state.z) * SNOW_WIPE_TRACE; + float left = min(state.x * SNOW_WIPE_MISS, SNOW_WIPE_LEFT); + float taken = state.x - left; + state.x = left; + state.y = state.y * SNOW_WIPE_WATER + min(taken * mix(SNOW_FRESH, SNOW_PACKED, state.z) * SNOW_WIPE_TRACE, SNOW_WIPE_WET); } if (pushed.x + pushed.y > 0.0) { @@ -271,7 +276,7 @@ void main() // pressed by the blade state.z = (snow > 1e-4) ? clamp((state.z * state.x + max(pushed.z, pushed.x * 0.85)) / snow, 0.0, 1.0) : state.z; state.x = snow; - state.y += pushed.y * 0.7; + state.y += pushed.y * 0.5; } // the flakes landing @@ -302,7 +307,8 @@ void main() float glass = water_up.w + water_snow.y / (1.0 + speed / 12.0); float melted = min(SNOW_MELT * max(glass, 0.0) * seconds, state.x * density); state.x -= melted / max(density, 1e-3); - state.y = max(state.y + melted - SNOW_DRY * seconds, 0.0); + float film = state.y * (1.0 - smoothstep(0.5, 3.0, state.x)); // the water not soaked into the snow + state.y = max(state.y + melted - (SNOW_DRY + SNOW_FILM_DRY * film) * seconds, 0.0); state.x = clamp(state.x, 0.0, SNOW_MOST); state.y = min(state.y, 4.0); diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index b0f14979c..ef3749ce5 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -512,10 +512,13 @@ void snowMapFlakes(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float ac vec4 q = water_snow_texel(uint(snMapSlot), snMapIndex, texel); float density = mix(0.1, 0.4, q.z); float wet = q.y / (q.y + q.x * density + 1e-4); - bool spot = (q.x < 0.05) && (q.y > 0.015); // a flake melted into its water + bool spot = (q.x < 0.05) && (q.y > 0.03); // a flake melted into its water if ((q.x < 0.05) && (false == spot)) continue; uint seed = Hash(uvec3(uvec2(texel), uint(q.w * 65535.0) + 7u * uint(snMapSlot))); + // the water of a texel is a droplet only now and then: the more water the more of them + if (spot && (RandF(seed) > smoothstep(0.03, 0.2, q.y))) + continue; vec2 center = vec2(texel) + vec2(0.15 + 0.7 * RandF(seed), 0.15 + 0.7 * RandF(seed)); float ang = RandF(seed) * 6.2831853; float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; @@ -523,7 +526,7 @@ void snowMapFlakes(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float ac float tone = mix(0.94, 1.04, RandF(seed)); float aniso = mix(0.62, 1.0, RandF(seed)); // the more snow the texel holds the bigger the flake (a lump of a few flakes) - float size = snow_map_flake * mix(0.6, 1.0, RandF(seed)) * (spot ? mix(0.5, 1.1, smoothstep(0.015, 0.2, q.y)) + float size = snow_map_flake * mix(0.6, 1.0, RandF(seed)) * (spot ? mix(0.5, 1.1, smoothstep(0.03, 0.3, q.y)) : mix(0.7, 1.6, smoothstep(0.05, 2.0, q.x))); vec2 d = (p - center) * aspect; float c = cos(ang); @@ -544,7 +547,7 @@ void snowMapFlakes(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float ac tile = vec2(0.0, 0.5); // fluffy else tile = vec2(0.0, 0.0); // crumbs - float alpha = spot ? smoothstep(0.015, 0.08, q.y) : smoothstep(0.05, 0.25, q.x); + float alpha = spot ? smoothstep(0.03, 0.1, q.y) : smoothstep(0.05, 0.25, q.x); snowMapSprite(local, tile, alpha, tone, flip, c, s, lod, accRGB, accA, accN, accTr); } } @@ -565,11 +568,11 @@ void snowMapped(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float accA, snowMapFlakes(aspect, pixelUV, accRGB, accA, accN, accTr); // the water: the film bends the picture behind - snWet = smoothstep(0.02, 0.25, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); + snWet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); snWetN = vec2(qr.y - ql.y, qu.y - qd.y) * 2.0 + (vec2(snNoise(f_coord * 900.0), snNoise(f_coord * 900.0 + 31.0)) - 0.5) * 0.6 * snWet; smear = max(smear, snWet * snow_melt_blur * 0.6); // thin snow hazes the picture around it - snHaze = max(snHaze, smoothstep(0.03, 0.6, around)); + snHaze = max(snHaze, smoothstep(0.15, 1.0, around)); // the layer, where the snow has run together vec2 gp = f_coord * float(WATER_MAP) * aspect; @@ -590,7 +593,7 @@ void snowMapped(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float accA, vec3 nT = normalize(vec3(-(slope + gf * snow_map_grain * (1.0 - 0.6 * q.z)) * snow_bump, 1.0)); vec3 fresh = vec3(0.93, 0.95, 0.98); - vec3 packed = vec3(0.84, 0.87, 0.91); + vec3 packed = vec3(0.89, 0.91, 0.94); vec3 slush = vec3(0.60, 0.66, 0.73); vec3 col = mix(mix(fresh, packed, q.z), slush, smoothstep(0.2, 0.7, wet)); col *= (0.80 + 0.30 * f1 * (1.0 - 0.5 * q.z)) * (0.92 + 0.12 * grain); diff --git a/shaders/vk14/water_snow.comp b/shaders/vk14/water_snow.comp index d241d5fe3..edea8be2a 100644 --- a/shaders/vk14/water_snow.comp +++ b/shaders/vk14/water_snow.comp @@ -39,16 +39,20 @@ const float SNOW_MOST = 40.0; const float SNOW_REPOSE = 3.0; // the share of the snow over the step slipping onto the neighbour in a second const float SNOW_SLIP = 6.0; -// the share of the snow a blade leaves, of the water, and of the snow it takes which it leaves as a wet trace +// the share of the snow a blade leaves (at most SNOW_WIPE_LEFT mm: the snow it pushes along goes with it), of the water, and +// of the water of the snow it takes which it leaves as a wet trace (at most SNOW_WIPE_WET mm) const float SNOW_WIPE_MISS = 0.03; -const float SNOW_WIPE_WATER = 0.25; +const float SNOW_WIPE_LEFT = 0.03; +const float SNOW_WIPE_WATER = 0.1; const float SNOW_WIPE_TRACE = 0.08; +const float SNOW_WIPE_WET = 0.015; // the longest line of texels a blade goes over in a step, texels const int SNOW_WIPE_LINE = 12; // the water the snow melts into at the glass a second for each degree the glass is above zero, mm const float SNOW_MELT = 0.003; -// the water drying a second, mm +// the water drying a second, mm, and the share of a thin film going in a second (it dries and runs off as droplets) const float SNOW_DRY = 0.0004; +const float SNOW_FILM_DRY = 0.15; // how fast slush slides down a vertical glass, how fast dry powder goes with the air (a share of the speed of the air along the // glass), how fast the film of water runs down a vertical glass and goes with the air, m/s const float SNOW_SLIDE = 0.03; @@ -264,9 +268,10 @@ void main() } if (crossed) { - float taken = state.x * (1.0 - SNOW_WIPE_MISS); - state.x -= taken; - state.y = state.y * SNOW_WIPE_WATER + taken * mix(SNOW_FRESH, SNOW_PACKED, state.z) * SNOW_WIPE_TRACE; + float left = min(state.x * SNOW_WIPE_MISS, SNOW_WIPE_LEFT); + float taken = state.x - left; + state.x = left; + state.y = state.y * SNOW_WIPE_WATER + min(taken * mix(SNOW_FRESH, SNOW_PACKED, state.z) * SNOW_WIPE_TRACE, SNOW_WIPE_WET); } if (pushed.x + pushed.y > 0.0) { @@ -274,7 +279,7 @@ void main() // pressed by the blade state.z = (snow > 1e-4) ? clamp((state.z * state.x + max(pushed.z, pushed.x * 0.85)) / snow, 0.0, 1.0) : state.z; state.x = snow; - state.y += pushed.y * 0.7; + state.y += pushed.y * 0.5; } // the flakes landing @@ -305,7 +310,8 @@ void main() float glass = water_up.w + water_snow.y / (1.0 + speed / 12.0); float melted = min(SNOW_MELT * max(glass, 0.0) * seconds, state.x * density); state.x -= melted / max(density, 1e-3); - state.y = max(state.y + melted - SNOW_DRY * seconds, 0.0); + float film = state.y * (1.0 - smoothstep(0.5, 3.0, state.x)); // the water not soaked into the snow + state.y = max(state.y + melted - (SNOW_DRY + SNOW_FILM_DRY * film) * seconds, 0.0); state.x = clamp(state.x, 0.0, SNOW_MOST); state.y = min(state.y, 4.0); From 94ea972bd9a721391f454367ddcd512108ae2252 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Tue, 10 Nov 2026 21:38:19 +0100 Subject: [PATCH 064/123] Snow windscreen: the snow a blade pushes doesn't slip behind it The snow piled in front of a blade slipped onto its lower neighbours, the texels the blade had just wiped among them, so it left a stripe of snow on the wiped glass at every step. Piled snow slips only where no working blade goes over. No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/water_snow.comp | 20 +++++++++++++++++--- shaders/vk14/water_snow.comp | 20 +++++++++++++++++--- 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/shaders/ogl46/water_snow.comp b/shaders/ogl46/water_snow.comp index 67dfc38d2..356260b4d 100644 --- a/shaders/ogl46/water_snow.comp +++ b/shaders/ogl46/water_snow.comp @@ -116,6 +116,18 @@ ivec2 snow_blade_way(ivec2 texel, int blade) return ivec2(round(way)); } +// whether no blade goes over the texel now: the snow piled there may slip onto its neighbours (in a sweep of a working blade +// the snow it pushes would slip behind it, a stripe of snow left on the wiped glass for every step) +bool snow_unswept(ivec2 texel) +{ + for (int blade = 0; blade < 4; ++blade) + { + if ((water_blades_now[blade] >= 0.0) && (water_blades_now[blade] != water_blades_before[blade]) && (snow_blade(texel, blade) > 0.001)) + return false; + } + return true; +} + // the frame of the glass at a texel, unfiltered water_frame_s snow_frame(ivec2 texel) { @@ -168,6 +180,7 @@ vec4 snow_move(ivec2 texel, vec4 state, float seconds) float snow = state.x * (1.0 - snowout.x - snowout.y); float water = state.y * (1.0 - waterout.x - waterout.y); float packed = state.z * snow; + bool unswept = snow_unswept(texel); float slip = min(SNOW_SLIP * seconds, 0.2); const ivec2 sides[4] = ivec2[4](ivec2(1, 0), ivec2(-1, 0), ivec2(0, 1), ivec2(0, -1)); for (int k = 0; k < 4; ++k) @@ -176,13 +189,14 @@ vec4 snow_move(ivec2 texel, vec4 state, float seconds) ivec2 other = texel + side; bool glass = snow_on_glass(other); vec4 neighbour = glass ? water_snow_texel(snow_slot, snow_from, other) : vec4(0.0); - // slipping onto the neighbour (off the glass: falling off) and from it - float away = slip * max(state.x - neighbour.x - SNOW_REPOSE, 0.0); + // slipping onto the neighbour (off the glass: falling off) and from it, where no blade goes over either now + bool slips = unswept && snow_unswept(other); + float away = slips ? slip * max(state.x - neighbour.x - SNOW_REPOSE, 0.0) : 0.0; snow -= away; packed -= away * state.z; if (false == glass) continue; - float coming = slip * max(neighbour.x - state.x - SNOW_REPOSE, 0.0); + float coming = slips ? slip * max(neighbour.x - state.x - SNOW_REPOSE, 0.0) : 0.0; // what the motion of the neighbour brings: it goes this way along the axis of the side vec4 itsmotion = snow_motion(other, neighbour); vec2 itssnow = snow_out(itsmotion.xy, seconds); diff --git a/shaders/vk14/water_snow.comp b/shaders/vk14/water_snow.comp index edea8be2a..769a3e1b6 100644 --- a/shaders/vk14/water_snow.comp +++ b/shaders/vk14/water_snow.comp @@ -119,6 +119,18 @@ ivec2 snow_blade_way(ivec2 texel, int blade) return ivec2(round(way)); } +// whether no blade goes over the texel now: the snow piled there may slip onto its neighbours (in a sweep of a working blade +// the snow it pushes would slip behind it, a stripe of snow left on the wiped glass for every step) +bool snow_unswept(ivec2 texel) +{ + for (int blade = 0; blade < 4; ++blade) + { + if ((water_blades_now[blade] >= 0.0) && (water_blades_now[blade] != water_blades_before[blade]) && (snow_blade(texel, blade) > 0.001)) + return false; + } + return true; +} + // the frame of the glass at a texel, unfiltered water_frame_s snow_frame(ivec2 texel) { @@ -171,6 +183,7 @@ vec4 snow_move(ivec2 texel, vec4 state, float seconds) float snow = state.x * (1.0 - snowout.x - snowout.y); float water = state.y * (1.0 - waterout.x - waterout.y); float packed = state.z * snow; + bool unswept = snow_unswept(texel); float slip = min(SNOW_SLIP * seconds, 0.2); const ivec2 sides[4] = ivec2[4](ivec2(1, 0), ivec2(-1, 0), ivec2(0, 1), ivec2(0, -1)); for (int k = 0; k < 4; ++k) @@ -179,13 +192,14 @@ vec4 snow_move(ivec2 texel, vec4 state, float seconds) ivec2 other = texel + side; bool glass = snow_on_glass(other); vec4 neighbour = glass ? water_snow_texel(snow_slot, snow_from, other) : vec4(0.0); - // slipping onto the neighbour (off the glass: falling off) and from it - float away = slip * max(state.x - neighbour.x - SNOW_REPOSE, 0.0); + // slipping onto the neighbour (off the glass: falling off) and from it, where no blade goes over either now + bool slips = unswept && snow_unswept(other); + float away = slips ? slip * max(state.x - neighbour.x - SNOW_REPOSE, 0.0) : 0.0; snow -= away; packed -= away * state.z; if (false == glass) continue; - float coming = slip * max(neighbour.x - state.x - SNOW_REPOSE, 0.0); + float coming = slips ? slip * max(neighbour.x - state.x - SNOW_REPOSE, 0.0) : 0.0; // what the motion of the neighbour brings: it goes this way along the axis of the side vec4 itsmotion = snow_motion(other, neighbour); vec2 itssnow = snow_out(itsmotion.xy, seconds); From f4ae5b826bed6aaec7d6911f36bdf20af7e30985 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Tue, 10 Nov 2026 21:42:57 +0100 Subject: [PATCH 065/123] Snow windscreen: the snow a blade pushes is counted once A texel ahead of a blade took the lines of every neighbour pointing at it, and the lines overlapped, so the snow pushed along grew at every step and the ends of the sweeps filled with ridges even on a glass with hardly any snow. A texel in the sweep takes only the line behind itself along the way of the blade, one off the sweep the line of one neighbour. No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/water_snow.comp | 16 +++++++++++++++- shaders/vk14/water_snow.comp | 16 +++++++++++++++- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/shaders/ogl46/water_snow.comp b/shaders/ogl46/water_snow.comp index 356260b4d..f7f60b28a 100644 --- a/shaders/ogl46/water_snow.comp +++ b/shaders/ogl46/water_snow.comp @@ -11,7 +11,8 @@ // the water runs down as a film and is pushed by the air; and snow piled higher than its neighbours by more than it holds slips // onto them (a ridge left by a blade spreads into a wedge). what goes over the edge of the glass falls off // - the blades: a blade going over a texel in the step takes its snow (a little stays, and a wet trace of the water), and pushes -// it on in front of itself: the texel just ahead of the line of texels the blade went over gets their snow, packed. at the end +// it on in front of itself: the texel just ahead of the line of texels the blade went over gets their snow, packed (each texel +// to one texel at most: the snow pushed along is never counted twice). at the end // of its sweep the blade leaves it there, a ridge; pushed past the edge of the glass, it's gone // - the flakes land: as many as come to the glass facing the snow coming at it against the cab (and a few in the eddies of the // air where it doesn't face it), each bringing its snow to the texel; the faster the vehicle the more of the dry ones bounce off @@ -267,6 +268,16 @@ void main() crossed = true; continue; } + // every texel the blade went over goes to one texel ahead at most, so the snow it pushes isn't counted twice (it would + // grow at every step): in the sweep the texel takes the line of texels behind itself along the way of the blade, off the + // sweep (the blade pushes the snow out at its edge) the line of one of its neighbours pointing at it + if (snow_blade(texel, blade) > 0.001) + { + ivec2 way = snow_blade_way(texel, blade); + if ((way != ivec2(0)) && snow_crossed(texel - way, blade)) + pushed += snow_line(texel - way, blade, way); + continue; + } for (int k = 0; k < 8; ++k) { ivec2 from = texel + SNOW_AROUND[k]; @@ -274,7 +285,10 @@ void main() continue; ivec2 way = snow_blade_way(from, blade); if ((way != ivec2(0)) && (from + way == texel)) + { pushed += snow_line(from, blade, way); + break; + } } } if (crossed) diff --git a/shaders/vk14/water_snow.comp b/shaders/vk14/water_snow.comp index 769a3e1b6..e4ea47a86 100644 --- a/shaders/vk14/water_snow.comp +++ b/shaders/vk14/water_snow.comp @@ -11,7 +11,8 @@ // the water runs down as a film and is pushed by the air; and snow piled higher than its neighbours by more than it holds slips // onto them (a ridge left by a blade spreads into a wedge). what goes over the edge of the glass falls off // - the blades: a blade going over a texel in the step takes its snow (a little stays, and a wet trace of the water), and pushes -// it on in front of itself: the texel just ahead of the line of texels the blade went over gets their snow, packed. at the end +// it on in front of itself: the texel just ahead of the line of texels the blade went over gets their snow, packed (each texel +// to one texel at most: the snow pushed along is never counted twice). at the end // of its sweep the blade leaves it there, a ridge; pushed past the edge of the glass, it's gone // - the flakes land: as many as come to the glass facing the snow coming at it against the cab (and a few in the eddies of the // air where it doesn't face it), each bringing its snow to the texel; the faster the vehicle the more of the dry ones bounce off @@ -270,6 +271,16 @@ void main() crossed = true; continue; } + // every texel the blade went over goes to one texel ahead at most, so the snow it pushes isn't counted twice (it would + // grow at every step): in the sweep the texel takes the line of texels behind itself along the way of the blade, off the + // sweep (the blade pushes the snow out at its edge) the line of one of its neighbours pointing at it + if (snow_blade(texel, blade) > 0.001) + { + ivec2 way = snow_blade_way(texel, blade); + if ((way != ivec2(0)) && snow_crossed(texel - way, blade)) + pushed += snow_line(texel - way, blade, way); + continue; + } for (int k = 0; k < 8; ++k) { ivec2 from = texel + SNOW_AROUND[k]; @@ -277,7 +288,10 @@ void main() continue; ivec2 way = snow_blade_way(from, blade); if ((way != ivec2(0)) && (from + way == texel)) + { pushed += snow_line(from, blade, way); + break; + } } } if (crossed) From 0d0bea27443a035af377d241da2ca83d37086db2 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Tue, 10 Nov 2026 21:48:28 +0100 Subject: [PATCH 066/123] Snow windscreen: thin flakes let the light through A single flake was drawn nearly opaque and lit only from the cab, a dark speck against the lit snow outside at night. A thin flake is 45% opaque now (full from 2.5 mm of snow) and the picture behind it is blurred, as through ice crystals. No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_snow_windscreen.frag | 7 +++++-- shaders/vk14/mat_snow_windscreen.frag | 7 +++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index 5bc35bb82..0ca45013c 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -462,6 +462,8 @@ const float snow_map_opaque = 1.8; // mm of fresh snow which lets 1/e of t const float snow_map_relief = 0.6; // how much the slopes of the snow tilt its surface const float snow_map_grain = 0.35; // the fine grain of the layer (its relief) const float snow_map_wet_bend = 0.6; // how strongly a wet glass bends the picture behind it +const float snow_map_thin = 0.45; // opacity of a single thin flake (ice crystals let most of the light through: the picture + // behind shows through it, blurred, rather than a dark speck at night) int snMapSlot = -1; uint snMapIndex = 0u; @@ -542,7 +544,7 @@ void snowMapFlakes(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float ac tile = vec2(0.0, 0.5); // fluffy else tile = vec2(0.0, 0.0); // crumbs - float alpha = spot ? smoothstep(0.03, 0.1, q.y) : smoothstep(0.05, 0.25, q.x); + float alpha = spot ? smoothstep(0.03, 0.1, q.y) : smoothstep(0.05, 0.25, q.x) * mix(snow_map_thin, 1.0, smoothstep(0.3, 2.5, q.x)); snowMapSprite(local, tile, alpha, tone, flip, c, s, lod, accRGB, accA, accN, accTr); } } @@ -559,8 +561,9 @@ void snowMapped(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float accA, vec4 qd = snMapAt(f_coord - vec2(0.0, e)); float around = (q.x + qr.x + ql.x + qu.x + qd.x) * 0.2; - // the flakes of thin snow and the water spots + // the flakes of thin snow and the water spots; the picture behind a flake is blurred (it scatters the light going through) snowMapFlakes(aspect, pixelUV, accRGB, accA, accN, accTr); + snHaze = max(snHaze, smoothstep(0.0, 0.3, accA)); // the water: the film bends the picture behind snWet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index ef3749ce5..183193b69 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -467,6 +467,8 @@ const float snow_map_opaque = 1.8; // mm of fresh snow which lets 1/e of t const float snow_map_relief = 0.6; // how much the slopes of the snow tilt its surface const float snow_map_grain = 0.35; // the fine grain of the layer (its relief) const float snow_map_wet_bend = 0.6; // how strongly a wet glass bends the picture behind it +const float snow_map_thin = 0.45; // opacity of a single thin flake (ice crystals let most of the light through: the picture + // behind shows through it, blurred, rather than a dark speck at night) int snMapSlot = -1; uint snMapIndex = 0u; @@ -547,7 +549,7 @@ void snowMapFlakes(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float ac tile = vec2(0.0, 0.5); // fluffy else tile = vec2(0.0, 0.0); // crumbs - float alpha = spot ? smoothstep(0.03, 0.1, q.y) : smoothstep(0.05, 0.25, q.x); + float alpha = spot ? smoothstep(0.03, 0.1, q.y) : smoothstep(0.05, 0.25, q.x) * mix(snow_map_thin, 1.0, smoothstep(0.3, 2.5, q.x)); snowMapSprite(local, tile, alpha, tone, flip, c, s, lod, accRGB, accA, accN, accTr); } } @@ -564,8 +566,9 @@ void snowMapped(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float accA, vec4 qd = snMapAt(f_coord - vec2(0.0, e)); float around = (q.x + qr.x + ql.x + qu.x + qd.x) * 0.2; - // the flakes of thin snow and the water spots + // the flakes of thin snow and the water spots; the picture behind a flake is blurred (it scatters the light going through) snowMapFlakes(aspect, pixelUV, accRGB, accA, accN, accTr); + snHaze = max(snHaze, smoothstep(0.0, 0.3, accA)); // the water: the film bends the picture behind snWet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); From 6ca3339df832353783e69158b09a65ea1d3ae180 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 11:16:56 +0100 Subject: [PATCH 067/123] Deer only where there's flat ground to bound away over A deer is put beside the track only where the way it runs away is all over the terrain of the scenery: ground found under each of the 9 samples of its way, none of them water (a material named water/woda/wody), no farther than 1.2 m below or 0.8 m above the sleepers, rising or falling at most 0.45 m between samples and 1.2 m all along. So no deer on an embankment, in a cutting or by a river. The side it runs to is picked at random first, then the other one; with neither flat, the next deer is looked for 200 m on instead of a whole interval. The ground is sampled when the deer is put there, so the run uses the same heights. Translucent shapes count as ground too, for water drawn translucent. Terrain made of models (e3d tiles) gives no ground, so there are no deer there. No asset changes needed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GXgG7F4L42c2F9sDSAJbT2 --- world/deer.cpp | 131 +++++++++++++++++++++++++++++++++++++++---------- world/deer.h | 4 +- 2 files changed, 108 insertions(+), 27 deletions(-) diff --git a/world/deer.cpp b/world/deer.cpp index e6c3749be..9891d584d 100644 --- a/world/deer.cpp +++ b/world/deer.cpp @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "world/deer.h" #include +#include #include #include #include @@ -60,8 +61,19 @@ constexpr double Flight2{3.95}; constexpr double Flight3{4.85}; // the frame an instance starts from at the moment of the change, a little after the frame proper: never the end of the one before constexpr double Startframe{0.02}; +// the ground under the way of the deer, at equal steps from its start to its end (deer_herd::Groundsamples) +constexpr std::size_t Groundsamples{9}; // the ground under the way of the deer is looked for up to this much above the place it starts from, metres constexpr double Groundceiling{3.0}; +// the way it runs: flat ground found all along it (no slope of an embankment or a cutting, no water). the ground beside the +// track no farther than this below or above the sleepers, metres +constexpr double Waybelow{1.2}; +constexpr double Wayabove{0.8}; +// rising or falling at most this much between the samples of the ground (3 m apart), and this much all along, metres +constexpr double Waystep{0.45}; +constexpr double Wayrange{1.2}; +// where there's no such ground at the place, the next deer is looked for this much farther, metres +constexpr double Retrydistance{200.0}; // the train past the deer: it came this close, and is this much farther away now, metres constexpr double Passedclose{300.0}; constexpr double Passedmargin{200.0}; @@ -111,6 +123,23 @@ bool triangle_height(glm::dvec3 const &A, glm::dvec3 const &B, glm::dvec3 const return true; } +// a shape of water: its material named so (water, woda), or with the shader of water +bool is_water(scene::shape_node const &Shape) +{ + if (GfxRenderer == nullptr) + { + return false; + } + auto const *material{GfxRenderer->Material(Shape.data().material)}; + if (material == nullptr) + { + return false; + } + auto name{material->GetName()}; + std::transform(name.begin(), name.end(), name.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + return (name.find("water") != std::string::npos) || (name.find("woda") != std::string::npos) || (name.find("wody") != std::string::npos); +} + // what's looked for under a point: its place, the highest ground found so far struct ground_probe { @@ -118,6 +147,8 @@ struct ground_probe double ceiling{0.0}; bool found{false}; double height{0.0}; + bool water{false}; // the highest surface found is water + bool shape_water{false}; // of the shape looked through void triangle(glm::dvec3 const &A, glm::dvec3 const &B, glm::dvec3 const &C) { @@ -125,6 +156,7 @@ struct ground_probe { found = true; height = y; + water = shape_water; } } @@ -152,6 +184,7 @@ struct ground_probe { return; } + shape_water = is_water(Shape); if (false == data.vertices.empty()) { for (std::size_t index = 0; index + 2 < data.vertices.size(); index += 3) @@ -169,13 +202,21 @@ struct ground_probe } }; -// the height of the ground of the scenery (its shapes: the terrain) under the point, not higher than Ceiling. false where there's -// none: the ground of terrain models, or none loaded -bool ground_height(glm::dvec3 const &Point, double const Ceiling, double &Height) +// the ground of the scenery (its shapes: the terrain) under a point +struct ground { + bool found{false}; // none: the ground of terrain models, or none loaded + double height{0.0}; + bool water{false}; +}; + +// the ground under the point, not higher than Ceiling +ground ground_at(glm::dvec3 const &Point, double const Ceiling) +{ + ground result; if (simulation::Region == nullptr) { - return false; + return result; } ground_probe probe; probe.point = Point; @@ -196,10 +237,16 @@ bool ground_height(glm::dvec3 const &Point, double const Ceiling, double &Height { probe.shape(shape); } + for (auto const &shape : cell.m_shapestranslucent) + { + probe.shape(shape); + } } } - Height = probe.height; - return probe.found; + result.found = probe.found; + result.height = probe.height; + result.water = probe.water; + return result; } // a place on a path: the point of its axis and the way along it, level, of length 1 @@ -334,6 +381,33 @@ void change_deer(TAnimModel *&Model, glm::dvec3 const &Heading, vat_clip const & Model = model; } +// the way a deer would run away from Start along Heading: true where it's all over flat ground, Ground then the heights of the ground +// at equal steps along it (the first one Start) +bool flat_way(glm::dvec3 const &Start, glm::dvec3 const &Heading, std::array &Ground) +{ + Ground.front() = Start.y; + auto const length{flight_way(Flighttime)}; + auto low{Start.y}; + auto high{Start.y - 1e9}; + for (std::size_t sample = 1; sample < Groundsamples; ++sample) + { + auto const point{Start + Heading * (length * static_cast(sample) / static_cast(Groundsamples - 1))}; + auto const here{ground_at(point, Start.y + Groundceiling)}; + if ((false == here.found) || here.water || (here.height < Start.y - Waybelow) || (here.height > Start.y + Wayabove)) + { + return false; + } + if ((sample > 1) && (std::abs(here.height - Ground[sample - 1]) > Waystep)) + { + return false; + } + Ground[sample] = here.height; + low = (sample == 1 ? here.height : std::min(low, here.height)); + high = std::max(high, here.height); + } + return (high - low <= Wayrange); +} + } // namespace simulation::deer_herd simulation::Deer; @@ -363,9 +437,10 @@ void simulation::deer_herd::update(double const Deltatime) if ((Global.deer_interval > 0.0) && (m_travelled >= Global.deer_interval)) { m_travelled = 0.0; - if (Random(0.0, 1.0) < Global.deer_chance) + if ((Random(0.0, 1.0) < Global.deer_chance) && (false == spawn(*vehicle))) { - spawn(*vehicle); + // no flat ground there: soon again + m_travelled = std::max(0.0, Global.deer_interval - Retrydistance); } } auto const train{vehicle->GetPosition()}; @@ -423,7 +498,7 @@ bool simulation::deer_herd::tend(deer &Animal, glm::dvec3 const &Train, bool con return false; } -void simulation::deer_herd::spawn(TDynamicObject const &Vehicle) +bool simulation::deer_herd::spawn(TDynamicObject const &Vehicle) { // the end of the train the way it goes, or the cab occupied when it stands auto const *mover{Vehicle.MoverParameters}; @@ -437,24 +512,38 @@ void simulation::deer_herd::spawn(TDynamicObject const &Vehicle) path_place place; if (false == path_ahead(axle.GetTrack(), axle.GetTranslation(), direction, Global.deer_distance, place)) { - return; + return false; } - // across the path, to one side or the other, a little askew - auto const side{Random(0.0, 1.0) < 0.5 ? -1.0 : 1.0}; - auto const askew{Random(-25.0, 25.0) * std::numbers::pi / 180.0}; - glm::dvec3 const across{place.forward.z * side, 0.0, -place.forward.x * side}; + // across the path, a little askew, to the side with flat ground to run away over (one picked at random first) deer animal; - animal.heading = glm::normalize(across * std::cos(askew) + place.forward * std::sin(askew)); animal.start = place.position; + auto const askew{Random(-25.0, 25.0) * std::numbers::pi / 180.0}; + auto const first{Random(0.0, 1.0) < 0.5 ? -1.0 : 1.0}; + auto found{false}; + for (auto const side : {first, -first}) + { + glm::dvec3 const across{place.forward.z * side, 0.0, -place.forward.x * side}; + animal.heading = glm::normalize(across * std::cos(askew) + place.forward * std::sin(askew)); + if (flat_way(animal.start, animal.heading, animal.ground)) + { + found = true; + break; + } + } + if (false == found) + { + return false; + } // grazing from a moment of its own animal.frame = Random(0.0, Grazing.frames); animal.time = Timer::GetTime(); animal.model = make_deer(Grazing, place.position, vat_turn(animal.heading, Grazing, 0, animal.frame, animal.time), false); if (animal.model == nullptr) { - return; + return false; } m_deer.emplace_back(animal); + return true; } void simulation::deer_herd::alarm(deer &Animal, glm::dvec3 const &Train, double const Now) const @@ -476,17 +565,9 @@ void simulation::deer_herd::alarm(deer &Animal, glm::dvec3 const &Train, double void simulation::deer_herd::flee(deer &Animal) const { + // the ground along its way was looked at when it was put there Animal.state = deer_state::fleeing; Animal.start = Animal.model->location(); - // the ground along the way it'll run, where there's none found the height of the step before - Animal.ground.front() = Animal.start.y; - auto const length{flight_way(Flighttime)}; - for (std::size_t sample = 1; sample < Groundsamples; ++sample) - { - auto const point{Animal.start + Animal.heading * (length * static_cast(sample) / static_cast(Groundsamples - 1))}; - double height{0.0}; - Animal.ground[sample] = (ground_height(point, Animal.start.y + Groundceiling, height) ? height : Animal.ground[sample - 1]); - } } bool simulation::deer_herd::run(deer &Animal, double const Now) const diff --git a/world/deer.h b/world/deer.h index 308fc01b1..838d809af 100644 --- a/world/deer.h +++ b/world/deer.h @@ -67,8 +67,8 @@ class deer_herd }; // the train at Train, its horn sounding, at the time Now: the deer takes fright, runs, or goes (true) once the train is past it bool tend(deer &Animal, glm::dvec3 const &Train, bool const Horn, double const Now) const; - // puts a deer on the path ahead of the train - void spawn(TDynamicObject const &Vehicle); + // puts a deer on the path ahead of the train, where there's flat ground beside it; false where there's none + bool spawn(TDynamicObject const &Vehicle); // the deer took fright: when it starts, where it looks void alarm(deer &Animal, glm::dvec3 const &Train, double const Now) const; // the deer starts to run From de99a8fc39bb0fd23efd82d052efeeaff8cd17f2 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 12:59:14 +0100 Subject: [PATCH 068/123] Deer: look at the train, only on plain straight track, not by platforms The flight now has 6 clips instead of 2: the head turned 50, 80 or 110 degrees to the left or to the right. The game picks the one nearest to the angle between the heading of the deer and the train. Before, clip 0 didn't turn the head at all and clip 1 always turned it to the left, so the deer looked away from a train on its right. A deer is put only where the way from the train to 100 m past the place is plain track: a switch (or a crossing of roads) on it fails, since the route may change before the train gets there. The track there also turns at most 3 degrees over 50 m before and after the place. No deer within 150 m of an instance of a platform model (a folder named peron..., as peronowe/), nor where the terrain 2.5 or 4 m beside the track rises 0.45 m over the sleepers (a platform made of terrain). Assets: animals/jelen_skok.t3d and its VAT textures (jelen_skok_vatpos_hi, _vatpos_lo, _vatnormal) have to be the ones baked with the 6 clips, in the order 50, 80, 110, -50, -80, -110 degrees (jelen_anim2.py LOOKS). The deer animations are kept local for now, not in the SVN. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GXgG7F4L42c2F9sDSAJbT2 --- world/deer.cpp | 114 ++++++++++++++++++++++++++++++++++++++++++++----- world/deer.h | 5 ++- 2 files changed, 107 insertions(+), 12 deletions(-) diff --git a/world/deer.cpp b/world/deer.cpp index 9891d584d..9a159903c 100644 --- a/world/deer.cpp +++ b/world/deer.cpp @@ -13,12 +13,14 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include #include #include "utilities/Globals.h" #include "utilities/utilities.h" #include "model/AnimModel.h" +#include "model/Model3d.h" #include "scene/scene.h" #include "scene/scenenode.h" #include "scene/scenelayers.h" @@ -45,9 +47,10 @@ struct vat_clip constexpr vat_clip Grazing{"animals/jelen_je", 20.0, 240.0, 1}; // startled: from the moments k * Window of the grazing (clip k) to the alarm, in Startletime; two more frames hold the end constexpr vat_clip Startle{"animals/jelen_zryw", 30.0, 15.0, 16}; -// the flight from the alarm: looks at the train (clip 0 to the left, 1 to the right), bounds away and stops in the grazing pose of the -// moment Grazeafter, in Flighttime; two more frames hold the end -constexpr vat_clip Flight{"animals/jelen_skok", 30.0, 168.0, 2}; +// the flight from the alarm: looks at the train (clip k: the head turned by Looks[k] degrees, to the left when more than 0), bounds +// away and stops in the grazing pose of the moment Grazeafter, in Flighttime; two more frames hold the end +constexpr vat_clip Flight{"animals/jelen_skok", 30.0, 168.0, 6}; +constexpr std::array Looks{50.0, 80.0, 110.0, -50.0, -80.0, -110.0}; constexpr double Window{0.75}; constexpr double Startletime{0.4}; constexpr double Flighttime{5.5}; @@ -74,6 +77,16 @@ constexpr double Waystep{0.45}; constexpr double Wayrange{1.2}; // where there's no such ground at the place, the next deer is looked for this much farther, metres constexpr double Retrydistance{200.0}; +// the track at the place: plain (no switch) from the train to this much past the place, and turning at most Straightturn degrees +// over Straightspan metres before and after it, metres +constexpr double Clearpast{100.0}; +constexpr double Straightspan{50.0}; +constexpr double Straightturn{3.0}; +// no deer this near a platform: an instance of a model of peronowe/ (or another folder named so), metres +constexpr double Platformrange{150.0}; +// nor where the ground beside the track, this far from its axis, rises this much over the sleepers (a platform of the terrain) +constexpr std::array Platformside{2.5, 4.0}; +constexpr double Platformrise{0.45}; // the train past the deer: it came this close, and is this much farther away now, metres constexpr double Passedclose{300.0}; constexpr double Passedmargin{200.0}; @@ -257,7 +270,7 @@ struct path_place }; // the place Distance from Track at Offset along it, going the way of Direction (1 towards its end, -1 towards its start), through the -// connected paths. false where the paths end earlier (or reach a crossing of roads) +// connected paths. false where the paths end earlier, or reach a crossing of roads or a switch bool path_ahead(TTrack *Track, double Offset, double Direction, double Distance, path_place &Place) { auto *track{Track}; @@ -271,8 +284,9 @@ bool path_ahead(TTrack *Track, double Offset, double Direction, double Distance, { left -= room; track = track->Connected(Direction > 0.0 ? 1 : -1, Direction); - if ((track == nullptr) || (track->eType == tt_Cross)) + if ((track == nullptr) || (track->eType != tt_Normal)) { + // the end, a crossing of roads, or a switch: the way may go elsewhere by the time the train gets there return false; } Offset = (Direction > 0.0 ? 0.0 : track->Length()); @@ -305,6 +319,87 @@ bool path_ahead(TTrack *Track, double Offset, double Direction, double Distance, return false; } +// the way ahead of the train to Distance and Clearpast past it plain track, the track there about straight: Place the place +bool plain_way(TTrack *Track, double const Offset, double const Direction, double const Distance, path_place &Place) +{ + if ((Track == nullptr) || (Track->eType != tt_Normal)) + { + return false; + } + path_place before; + path_place past; + if ((false == path_ahead(Track, Offset, Direction, Distance + Clearpast, past)) || + (false == path_ahead(Track, Offset, Direction, Distance - Straightspan, before)) || + (false == path_ahead(Track, Offset, Direction, Distance, Place)) || + (false == path_ahead(Track, Offset, Direction, Distance + Straightspan, past))) + { + return false; + } + auto const limit{std::cos(Straightturn * std::numbers::pi / 180.0)}; + return (glm::dot(before.forward, Place.forward) >= limit) && (glm::dot(Place.forward, past.forward) >= limit); +} + +// a model of a platform: in a folder named peron... (peronowe/) +bool platform_model(TAnimModel const &Instance) +{ + auto const *model{Instance.Model()}; + if (model == nullptr) + { + return false; + } + auto name{model->NameGet()}; + std::transform(name.begin(), name.end(), name.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + std::replace(name.begin(), name.end(), '\\', '/'); + auto const slash{name.rfind('/')}; + return (slash != std::string::npos) && (name.substr(0, slash).find("peron") != std::string::npos); +} + +// a platform about the place: a model of one near it, or the ground beside the track raised to its height +bool near_platform(path_place const &Place) +{ + for (auto *section : simulation::Region->sections(Place.position, static_cast(Platformrange))) + { + for (auto const &cell : section->m_cells) + { + if (glm::length(cell.m_area.center - Place.position) > cell.m_area.radius + Platformrange) + { + continue; + } + auto const nearby{[&Place](TAnimModel const *Instance) { + return (Instance != nullptr) && (glm::length(Instance->location() - Place.position) < Platformrange) && platform_model(*Instance); + }}; + if (std::ranges::any_of(cell.m_instancesopaque, nearby) || std::ranges::any_of(cell.m_instancetranslucent, nearby)) + { + return true; + } + } + } + glm::dvec3 const across{Place.forward.z, 0.0, -Place.forward.x}; + for (auto const side : {-1.0, 1.0}) + { + for (auto const distance : Platformside) + { + auto const here{ground_at(Place.position + across * (side * distance), Place.position.y + Groundceiling)}; + if (here.found && (here.height > Place.position.y + Platformrise)) + { + return true; + } + } + } + return false; +} + +// the clip of the flight which looks the nearest to Towards (from the deer to the train) for a deer looking along Heading +int look_clip(glm::dvec3 const &Heading, glm::dvec3 const &Towards) +{ + // the left of a heading h is (h.z, 0, -h.x) + auto const left{Towards.x * Heading.z - Towards.z * Heading.x}; + auto const ahead{Towards.x * Heading.x + Towards.z * Heading.z}; + auto const angle{std::atan2(left, ahead) * 180.0 / std::numbers::pi}; + auto const nearest{std::ranges::min_element(Looks, {}, [angle](double const Look) { return std::abs(Look - angle); })}; + return static_cast(std::distance(Looks.begin(), nearest)); +} + // the yaw of an instance whose model looks along -z, to look along Heading, degrees (-180, 180] double model_yaw(glm::dvec3 const &Heading) { @@ -439,7 +534,7 @@ void simulation::deer_herd::update(double const Deltatime) m_travelled = 0.0; if ((Random(0.0, 1.0) < Global.deer_chance) && (false == spawn(*vehicle))) { - // no flat ground there: soon again + // no flat ground, a switch or a platform there: soon again m_travelled = std::max(0.0, Global.deer_interval - Retrydistance); } } @@ -510,7 +605,7 @@ bool simulation::deer_herd::spawn(TDynamicObject const &Vehicle) auto const &axle{front ? Vehicle.Axle0 : Vehicle.Axle1}; auto const direction{front ? axle.GetDirection() : -axle.GetDirection()}; path_place place; - if (false == path_ahead(axle.GetTrack(), axle.GetTranslation(), direction, Global.deer_distance, place)) + if ((false == plain_way(axle.GetTrack(), axle.GetTranslation(), direction, Global.deer_distance, place)) || near_platform(place)) { return false; } @@ -557,9 +652,8 @@ void simulation::deer_herd::alarm(deer &Animal, glm::dvec3 const &Train, double window %= windows; Animal.clip = window; Animal.time = Now + std::max(0.0, wait); - // it looks at the train: to its left or to its right (the left of a heading h is (h.z, 0, -h.x)) - auto const towards{Train - Animal.model->location()}; - Animal.look = ((towards.x * Animal.heading.z - towards.z * Animal.heading.x) > 0.0 ? 0 : 1); + // it looks at the train + Animal.look = look_clip(Animal.heading, Train - Animal.model->location()); Animal.state = deer_state::alarmed; } diff --git a/world/deer.h b/world/deer.h index 838d809af..b6581e894 100644 --- a/world/deer.h +++ b/world/deer.h @@ -61,13 +61,14 @@ class deer_herd double frame{0.0}; // of the grazing at the time time double time{0.0}; // of the simulation (Timer::GetTime()), seconds; see deer_state int clip{0}; // of the startle: the moment of the grazing it starts from - int look{0}; // 0 looks at the train to its left, 1 to its right + int look{0}; // the clip of the flight which looks at the train double closest{1e9}; // the train came this close, metres std::array ground{}; // heights of the ground along the way it runs }; // the train at Train, its horn sounding, at the time Now: the deer takes fright, runs, or goes (true) once the train is past it bool tend(deer &Animal, glm::dvec3 const &Train, bool const Horn, double const Now) const; - // puts a deer on the path ahead of the train, where there's flat ground beside it; false where there's none + // puts a deer on the path ahead of the train, where it's plain and straight track with flat ground beside it and no platform near; + // false where there's none bool spawn(TDynamicObject const &Vehicle); // the deer took fright: when it starts, where it looks void alarm(deer &Animal, glm::dvec3 const &Train, double const Now) const; From c476316bbd5cf178cabfc9d9e245b62c43ebbadb Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 13:01:53 +0100 Subject: [PATCH 069/123] Deer: on curved track too, only the switches keep them away The track at the place no longer has to be straight: a curve is fine. Only a switch (or a crossing of roads) from the train to 100 m past the place keeps a deer from being put there. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GXgG7F4L42c2F9sDSAJbT2 --- world/deer.cpp | 18 +++--------------- world/deer.h | 2 +- 2 files changed, 4 insertions(+), 16 deletions(-) diff --git a/world/deer.cpp b/world/deer.cpp index 9a159903c..31cb46548 100644 --- a/world/deer.cpp +++ b/world/deer.cpp @@ -77,11 +77,8 @@ constexpr double Waystep{0.45}; constexpr double Wayrange{1.2}; // where there's no such ground at the place, the next deer is looked for this much farther, metres constexpr double Retrydistance{200.0}; -// the track at the place: plain (no switch) from the train to this much past the place, and turning at most Straightturn degrees -// over Straightspan metres before and after it, metres +// the track at the place: plain (no switch) from the train to this much past the place, metres constexpr double Clearpast{100.0}; -constexpr double Straightspan{50.0}; -constexpr double Straightturn{3.0}; // no deer this near a platform: an instance of a model of peronowe/ (or another folder named so), metres constexpr double Platformrange{150.0}; // nor where the ground beside the track, this far from its axis, rises this much over the sleepers (a platform of the terrain) @@ -319,24 +316,15 @@ bool path_ahead(TTrack *Track, double Offset, double Direction, double Distance, return false; } -// the way ahead of the train to Distance and Clearpast past it plain track, the track there about straight: Place the place +// the way ahead of the train to Distance and Clearpast past it plain track (straight or curved, no switch): Place the place bool plain_way(TTrack *Track, double const Offset, double const Direction, double const Distance, path_place &Place) { if ((Track == nullptr) || (Track->eType != tt_Normal)) { return false; } - path_place before; path_place past; - if ((false == path_ahead(Track, Offset, Direction, Distance + Clearpast, past)) || - (false == path_ahead(Track, Offset, Direction, Distance - Straightspan, before)) || - (false == path_ahead(Track, Offset, Direction, Distance, Place)) || - (false == path_ahead(Track, Offset, Direction, Distance + Straightspan, past))) - { - return false; - } - auto const limit{std::cos(Straightturn * std::numbers::pi / 180.0)}; - return (glm::dot(before.forward, Place.forward) >= limit) && (glm::dot(Place.forward, past.forward) >= limit); + return path_ahead(Track, Offset, Direction, Distance + Clearpast, past) && path_ahead(Track, Offset, Direction, Distance, Place); } // a model of a platform: in a folder named peron... (peronowe/) diff --git a/world/deer.h b/world/deer.h index b6581e894..6f8b24cdc 100644 --- a/world/deer.h +++ b/world/deer.h @@ -67,7 +67,7 @@ class deer_herd }; // the train at Train, its horn sounding, at the time Now: the deer takes fright, runs, or goes (true) once the train is past it bool tend(deer &Animal, glm::dvec3 const &Train, bool const Horn, double const Now) const; - // puts a deer on the path ahead of the train, where it's plain and straight track with flat ground beside it and no platform near; + // puts a deer on the path ahead of the train, where it's plain track (no switch) with flat ground beside it and no platform near; // false where there's none bool spawn(TDynamicObject const &Vehicle); // the deer took fright: when it starts, where it looks From ff023e90477bd9d008fc8fbff5cc3aeee7125f6b Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 13:43:40 +0100 Subject: [PATCH 070/123] Deer: keep away from long platforms too, and log where each is put A platform model is placed by its middle, so a deer by the end of a long one (peronowe/1k96w400m: 200 m from the middle) was farther than the 150 m looked at, and was put there. Now a deer is kept 100 m beyond the reach of the model (its bounding radius), the instances looked through up to 350 m away. Any model with peron in its path counts (peronowe/..., przytorowe/tszopaperon). The log tells where each deer was put ("Deer put at x y z"). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GXgG7F4L42c2F9sDSAJbT2 --- world/deer.cpp | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/world/deer.cpp b/world/deer.cpp index 31cb46548..f8ed59e6b 100644 --- a/world/deer.cpp +++ b/world/deer.cpp @@ -30,6 +30,7 @@ http://mozilla.org/MPL/2.0/. #include "McZapkie/MOVER.h" #include "world/Track.h" #include "utilities/Timer.h" +#include "utilities/Logs.h" namespace { @@ -79,8 +80,10 @@ constexpr double Wayrange{1.2}; constexpr double Retrydistance{200.0}; // the track at the place: plain (no switch) from the train to this much past the place, metres constexpr double Clearpast{100.0}; -// no deer this near a platform: an instance of a model of peronowe/ (or another folder named so), metres -constexpr double Platformrange{150.0}; +// no deer this near a platform (the reach of its model added): an instance of a model with peron in its path (peronowe/...), metres +constexpr double Platformrange{100.0}; +// the platforms are looked for among the instances placed this near, metres (the longest platform model, 400 m, by its middle) +constexpr double Platformsearch{350.0}; // nor where the ground beside the track, this far from its axis, rises this much over the sleepers (a platform of the terrain) constexpr std::array Platformside{2.5, 4.0}; constexpr double Platformrise{0.45}; @@ -327,7 +330,7 @@ bool plain_way(TTrack *Track, double const Offset, double const Direction, doubl return path_ahead(Track, Offset, Direction, Distance + Clearpast, past) && path_ahead(Track, Offset, Direction, Distance, Place); } -// a model of a platform: in a folder named peron... (peronowe/) +// a model of a platform or of what stands on one: peron in the name of its file or of its folder (peronowe/) bool platform_model(TAnimModel const &Instance) { auto const *model{Instance.Model()}; @@ -337,24 +340,24 @@ bool platform_model(TAnimModel const &Instance) } auto name{model->NameGet()}; std::transform(name.begin(), name.end(), name.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); - std::replace(name.begin(), name.end(), '\\', '/'); - auto const slash{name.rfind('/')}; - return (slash != std::string::npos) && (name.substr(0, slash).find("peron") != std::string::npos); + return name.find("peron") != std::string::npos; } // a platform about the place: a model of one near it, or the ground beside the track raised to its height bool near_platform(path_place const &Place) { - for (auto *section : simulation::Region->sections(Place.position, static_cast(Platformrange))) + for (auto *section : simulation::Region->sections(Place.position, static_cast(Platformsearch))) { for (auto const &cell : section->m_cells) { - if (glm::length(cell.m_area.center - Place.position) > cell.m_area.radius + Platformrange) + if (glm::length(cell.m_area.center - Place.position) > cell.m_area.radius + Platformsearch) { continue; } - auto const nearby{[&Place](TAnimModel const *Instance) { - return (Instance != nullptr) && (glm::length(Instance->location() - Place.position) < Platformrange) && platform_model(*Instance); + // a long platform (a model of 400 m) is placed by its middle: the reach of the model counts as well + auto const nearby{[&Place](TAnimModel *Instance) { + return (Instance != nullptr) && (glm::length(Instance->location() - Place.position) < Platformrange + Instance->radius()) && + platform_model(*Instance); }}; if (std::ranges::any_of(cell.m_instancesopaque, nearby) || std::ranges::any_of(cell.m_instancetranslucent, nearby)) { @@ -625,6 +628,7 @@ bool simulation::deer_herd::spawn(TDynamicObject const &Vehicle) { return false; } + WriteLog(std::format("Deer put at {:.1f} {:.1f} {:.1f}", place.position.x, place.position.y, place.position.z)); m_deer.emplace_back(animal); return true; } From 4a4fac1823117941ff862cd36a41cc5cca1cf901 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 14:38:36 +0100 Subject: [PATCH 071/123] Deer: log why a deer wasn't put at a place Every attempt that fails says why in the log: a switch, a crossing of roads or the end of the track ahead; the platform found (its model, or the raised terrain beside the track); or, for each side, why the way to run away isn't flat ground: no ground found, water, ground too low or high, a step, or too much rise and fall. For finding out why no deer appear on a scenery. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GXgG7F4L42c2F9sDSAJbT2 --- world/deer.cpp | 49 +++++++++++++++++++++++++++++++++++++------------ 1 file changed, 37 insertions(+), 12 deletions(-) diff --git a/world/deer.cpp b/world/deer.cpp index f8ed59e6b..75c413160 100644 --- a/world/deer.cpp +++ b/world/deer.cpp @@ -343,8 +343,8 @@ bool platform_model(TAnimModel const &Instance) return name.find("peron") != std::string::npos; } -// a platform about the place: a model of one near it, or the ground beside the track raised to its height -bool near_platform(path_place const &Place) +// a platform about the place: a model of one near it, or the ground beside the track raised to its height. what was found, empty for none +std::string near_platform(path_place const &Place) { for (auto *section : simulation::Region->sections(Place.position, static_cast(Platformsearch))) { @@ -359,9 +359,12 @@ bool near_platform(path_place const &Place) return (Instance != nullptr) && (glm::length(Instance->location() - Place.position) < Platformrange + Instance->radius()) && platform_model(*Instance); }}; - if (std::ranges::any_of(cell.m_instancesopaque, nearby) || std::ranges::any_of(cell.m_instancetranslucent, nearby)) + for (auto const *instances : {&cell.m_instancesopaque, &cell.m_instancetranslucent}) { - return true; + if (auto const found{std::ranges::find_if(*instances, nearby)}; found != instances->end()) + { + return std::format("platform model {}", (*found)->Model()->NameGet()); + } } } } @@ -373,11 +376,11 @@ bool near_platform(path_place const &Place) auto const here{ground_at(Place.position + across * (side * distance), Place.position.y + Groundceiling)}; if (here.found && (here.height > Place.position.y + Platformrise)) { - return true; + return std::format("platform of the terrain {:.2f} m high {:.1f} m aside", here.height - Place.position.y, side * distance); } } } - return false; + return {}; } // the clip of the flight which looks the nearest to Towards (from the deer to the train) for a deer looking along Heading @@ -468,8 +471,8 @@ void change_deer(TAnimModel *&Model, glm::dvec3 const &Heading, vat_clip const & } // the way a deer would run away from Start along Heading: true where it's all over flat ground, Ground then the heights of the ground -// at equal steps along it (the first one Start) -bool flat_way(glm::dvec3 const &Start, glm::dvec3 const &Heading, std::array &Ground) +// at equal steps along it (the first one Start); Reason why not otherwise +bool flat_way(glm::dvec3 const &Start, glm::dvec3 const &Heading, std::array &Ground, std::string &Reason) { Ground.front() = Start.y; auto const length{flight_way(Flighttime)}; @@ -479,19 +482,31 @@ bool flat_way(glm::dvec3 const &Start, glm::dvec3 const &Heading, std::array(sample) / static_cast(Groundsamples - 1))}; auto const here{ground_at(point, Start.y + Groundceiling)}; - if ((false == here.found) || here.water || (here.height < Start.y - Waybelow) || (here.height > Start.y + Wayabove)) + if (false == here.found) { + Reason = std::format("no ground at {:.1f} m", glm::length(point - Start)); + return false; + } + if (here.water || (here.height < Start.y - Waybelow) || (here.height > Start.y + Wayabove)) + { + Reason = std::format("{} at {:.1f} m, {:.2f} m from the sleepers", here.water ? "water" : "ground", glm::length(point - Start), here.height - Start.y); return false; } if ((sample > 1) && (std::abs(here.height - Ground[sample - 1]) > Waystep)) { + Reason = std::format("a step of {:.2f} m at {:.1f} m", here.height - Ground[sample - 1], glm::length(point - Start)); return false; } Ground[sample] = here.height; low = (sample == 1 ? here.height : std::min(low, here.height)); high = std::max(high, here.height); } - return (high - low <= Wayrange); + if (high - low > Wayrange) + { + Reason = std::format("the ground rises and falls {:.2f} m", high - low); + return false; + } + return true; } } // namespace @@ -596,8 +611,14 @@ bool simulation::deer_herd::spawn(TDynamicObject const &Vehicle) auto const &axle{front ? Vehicle.Axle0 : Vehicle.Axle1}; auto const direction{front ? axle.GetDirection() : -axle.GetDirection()}; path_place place; - if ((false == plain_way(axle.GetTrack(), axle.GetTranslation(), direction, Global.deer_distance, place)) || near_platform(place)) + if (false == plain_way(axle.GetTrack(), axle.GetTranslation(), direction, Global.deer_distance, place)) { + WriteLog("Deer not put: a switch, a crossing of roads or the end of the track ahead"); + return false; + } + if (auto const platform{near_platform(place)}; false == platform.empty()) + { + WriteLog(std::format("Deer not put at {:.1f} {:.1f} {:.1f}: {}", place.position.x, place.position.y, place.position.z, platform)); return false; } // across the path, a little askew, to the side with flat ground to run away over (one picked at random first) @@ -606,18 +627,22 @@ bool simulation::deer_herd::spawn(TDynamicObject const &Vehicle) auto const askew{Random(-25.0, 25.0) * std::numbers::pi / 180.0}; auto const first{Random(0.0, 1.0) < 0.5 ? -1.0 : 1.0}; auto found{false}; + std::string reasons; for (auto const side : {first, -first}) { glm::dvec3 const across{place.forward.z * side, 0.0, -place.forward.x * side}; animal.heading = glm::normalize(across * std::cos(askew) + place.forward * std::sin(askew)); - if (flat_way(animal.start, animal.heading, animal.ground)) + std::string reason; + if (flat_way(animal.start, animal.heading, animal.ground, reason)) { found = true; break; } + reasons += (reasons.empty() ? "" : "; ") + reason; } if (false == found) { + WriteLog(std::format("Deer not put at {:.1f} {:.1f} {:.1f}: {}", place.position.x, place.position.y, place.position.z, reasons)); return false; } // grazing from a moment of its own From 5e605e81261e1f17627ecb7c09cf67e3faed42bb Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 15:27:51 +0100 Subject: [PATCH 072/123] Deer: the ground of the heightmap terrain counts On a scenery with heightmap terrain (Tomaszewo: terrain/tomaszewo_hgtmap/) the deer looked for the ground among the shapes of the scenery only, found none beside the track and weren't put anywhere ("no ground at 3.0 m" in the log). Now the height of the heightmap terrain counts as the ground too, and its bodies of water as water. The chunk under the point is read from its pack file when it isn't in memory: the deer are put about 2 km ahead of the camera, where the terrain isn't loaded for drawing yet. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GXgG7F4L42c2F9sDSAJbT2 --- world/deer.cpp | 47 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/world/deer.cpp b/world/deer.cpp index 75c413160..9b7949b3b 100644 --- a/world/deer.cpp +++ b/world/deer.cpp @@ -29,6 +29,8 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/DynObj.h" #include "McZapkie/MOVER.h" #include "world/Track.h" +#include "editor/editorTerrainStreamer.hpp" +#include "scene/heightmapterrain.h" #include "utilities/Timer.h" #include "utilities/Logs.h" @@ -215,7 +217,49 @@ struct ground_probe } }; -// the ground of the scenery (its shapes: the terrain) under a point +// the point (X, Z) within the outline (x, z) +bool inside(std::vector const &Outline, double const X, double const Z) +{ + auto result{false}; + auto const *previous{&Outline.back()}; + for (auto const ¤t : Outline) + { + if (((current.y > Z) != (previous->y > Z)) && (X < (previous->x - current.x) * (Z - current.y) / (previous->y - current.y) + current.x)) + { + result = !result; + } + previous = ¤t; + } + return result; +} + +// the heightmap terrain under the point, and its bodies of water, as the ground. the chunk there is read from its file if it isn't +// in memory yet: the deer are put far ahead of the camera, where the terrain isn't loaded for drawing +void heightmap_ground(glm::dvec3 const &Point, double const Ceiling, ground_probe &Probe) +{ + if ((false == EditorTerrain.active()) || (EditorTerrain.chunk(heightmap::chunk_at(Point.x, Point.z), true) == nullptr)) + { + return; + } + if (double y{0.0}; EditorTerrain.height_at(Point.x, Point.z, y) && (y <= Ceiling) && ((false == Probe.found) || (y > Probe.height))) + { + Probe.found = true; + Probe.height = y; + Probe.water = false; + } + for (auto const &water : EditorTerrain.manifest().water) + { + if ((water.outline.size() >= 3) && (water.level <= Ceiling) && ((false == Probe.found) || (water.level > Probe.height)) && + inside(water.outline, Point.x, Point.z)) + { + Probe.found = true; + Probe.height = water.level; + Probe.water = true; + } + } +} + +// the ground of the scenery (its shapes and the heightmap terrain) under a point struct ground { bool found{false}; // none: the ground of terrain models, or none loaded @@ -256,6 +300,7 @@ ground ground_at(glm::dvec3 const &Point, double const Ceiling) } } } + heightmap_ground(Point, Ceiling, probe); result.found = probe.found; result.height = probe.height; result.water = probe.water; From 5c5cf78c1770d39363914f5351e2f484cf4fcadd Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 19:10:26 +0100 Subject: [PATCH 073/123] Snow windscreen: the snow drawn only with sprites of the atlas The procedural snow (cells with timers, the clumping field, the noise of the layer and its edge, the wiper mask read in the shader) is gone: what lies on the glass comes from the map of the simulation, and it's drawn with sprites of the atlas in two layers, as the drops of the rain and the bugs: - a flake on every texel holding snow (crystals, flakes of a few of them, crumbs; wet lumps; a drop where only the water is left, bending the picture behind), the more snow the bigger; - under them a bigger sprite every three texels where the snow is thicker (clumps, packed snow, slush), overlapping into a cover. A glass without a map (no simulation) has no snow. Uses a new 4 x 4 atlas (2048 x 2048, snieg_atlas_maszyna.py): textures/fx/snow-atlas.tga and textures/fx/snow_normalmap.tga, replacing the 2 x 2 ones of the same names. Without them (a 1024 atlas) the shader takes the four old tiles for the sixteen. To be added to the SVN: the two files. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_snow_windscreen.frag | 856 +++++++------------------ shaders/vk14/mat_snow_windscreen.frag | 854 +++++++----------------- 2 files changed, 459 insertions(+), 1251 deletions(-) diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index 0ca45013c..330a7583a 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -1,70 +1,55 @@ #version 460 core #define STAGE_FRAGMENT 1 -// Windscreen snow: replaces rain_windscreen when it snows - v2 (OpenGL 4.6 / Vulkan 1.4 port of the OpenGL 3.3 v1) -// v2: the syntax of the 4.6 renderers (explicit locations and bindings, #pragma texture / param), the tuning values as constants -// (a uniform can't have a default any more); the blur of the scene and the picture bent by thin snow go to the -// post-processing through the velocity target, as the haze and the drops of rain_windscreen (postfx_taa.frag / -// postfx_motionblur.frag with rain_windscreen_haze.glsl); the colour is written straight -// (not premultiplied) as rain_windscreen of the 4.6 renderers writes the glass; the gloss of the glass from legacy_gloss(); -// no lighting where the glass is clear (no snow, a clear texture). the look and the behaviour of the snow are those of v1. +// Windscreen snow: replaces rain_windscreen when it snows - v3 (OpenGL 4.6 / Vulkan 1.4) // -// MaSzyna switches the weather itself (simulationenvironment.cpp): with Overcast > 1 it rains when the air is warmer -// than 1 deg C and it SNOWS at 1 deg C and below, and the .mat block "snow:" is picked. rain_params.x is the -// precipitation intensity (saturate(Overcast - 1)), exactly what rain_windscreen uses for the drops, so the snow -// on the glass follows the snowfall: nothing without snow, and the harder it snows the more the glass gets plastered. +// MaSzyna switches the weather itself (simulationenvironment.cpp): with Overcast > 1 it SNOWS at 1 deg C and below, and the .mat +// block "snow:" is picked. // -// - flakes: every cell of the glass can hold a flake (atlas tiles 0..2: fluffy, wet lump, crumbs). It lands at a random -// moment, stays white for `snow_hold` seconds and then MELTS for `snow_melt` seconds: the snow fades into a water spot -// (tile 3). About `snow_slide_share` of the melting flakes also SLIDE DOWN the glass, stretching into a drip. -// Only the wet, melting spot blurs the scene (water refracts; dry snow does not, see snow_fresh_blur). -// - clumping: flakes land small and GROW as more snow piles onto them. Where flakes land next to each other they run together -// into one bigger patch (a crusty white film), and the more it snows the more flakes land side by side, so the bigger -// the patches get. The patch exists only where flakes really sit close together; when they melt / slide away it breaks -// up and thins out (snow_clump). -// - wipers (wipermask, GetMixFactor) clear all of it; it builds up again after `snow_regen` seconds (faster in heavy snow). -// Nothing depends on the time since the game started. +// What lies on the glass comes from the simulation (water_snow.comp, water.glsl): the map of the glass keeps the snow, the water, +// how packed the snow is and the shape of its flakes from frame to frame. The flakes land and stay where they landed, pile up, +// the blades push the snow into ridges at the ends of their sweeps and leave a wet trace, it melts at the warm glass, slush slides +// down. The renderer gives the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. // -// Atlas / normalmap (blender_snow_atlas.py), 2 x 2 tiles: -// 0 dry fluffy flake 1 wet compact lump 2 crumbs 3 melted spot (water + ice remnants) +// The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen, two layers of them: +// - the flakes: a sprite on every texel of the map holding snow, the more snow the bigger. Dry: crystals, flakes of a few of +// them, crumbs; wet: lumps; where only the water of a melted flake is left, a drop (it bends the picture behind, as rain does) +// - the layer, under the flakes: a bigger sprite every three texels where the snow is thicker, clumps of flakes, then packed +// snow, overlapping into a whole cover where the snow is thick; grey slush where it's wet +// A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. +// +// Atlas / normalmap (snieg_atlas_maszyna.py), 4 x 4 tiles of 512 x 512 (2048 x 2048): +// 0, 1 star crystals 2 plate 3 needles 4, 5 flakes of a few crystals 6, 7 crumbs +// 8, 9 wet lumps 10, 11 clumps 12, 13 packed snow 14 slush 15 drop +// An older 2 x 2 atlas (1024 x 1024: fluffy flake, wet lump, crumbs, melted spot) still works, its tiles stand in for these. // // .mat: // -// texture_diffuse: dynamic/pkp/vectron_v1/cab/szyby -// texture_raindropsatlas: textures/fx/raindrops-atlas -// texture_normalmap: textures/fx/raindrops_normalmap -// texture_wipermask: dynamic/pkp/vectron_v1/cab/szyby_wipermask -// shader: rain_windscreen -// param_raindrop_grid_size: 150 -// // snow: { // shader: snow_windscreen // texture_raindropsatlas: textures/fx/snow-atlas // texture_normalmap: textures/fx/snow_normalmap -// param_raindrop_grid_size: 70 // } -// -// One cell is about one flake: a grid of ~50-90 gives flakes of ~1-2 cm on a ~1.5 m windscreen. layout(location = 0) in vec3 f_normal; layout(location = 2) in vec2 f_coord; layout(location = 3) in vec4 f_pos; layout(location = 4) in vec4 f_clip_pos; layout(location = 5) in vec4 f_clip_future_pos; -#include "common.glsl" layout(location = 0) out vec4 out_color; layout(location = 1) out vec4 out_motion; +#include "common.glsl" #pragma texture(diffuse, 0, sRGB_A) #pragma texture(raindropsatlas, 1, sRGB_A) -#pragma texture(wipermask, 2, sRGB_A) -#pragma texture(normalmap, 3, RGBA) // flakes: rg = normal xy, b = height, a = mask; same 2x2 layout as raindropsatlas (linear) +#pragma texture(wipermask, 2, sRGB_A) // the renderer bakes it into the map of the glass (the blades); not read here +#pragma texture(normalmap, 3, RGBA) // rg = normal xy, b = height, a = mask; the layout of raindropsatlas (linear) #pragma param(color, 0, 0, 4, diffuse) #pragma param(diffuse, 1, 0, 1, diffuse) #pragma param(specular, 1, 1, 1, specular) #pragma param(reflection, 1, 2, 1, zero) #pragma param(glossiness, 1, 3, 1, glossiness) -#pragma param(raindrop_grid_size, 2, 0, 1, one) +#pragma param(raindrop_grid_size, 2, 0, 1, one) // not used any more (the map of the glass sets the size of the flakes) // snow_slot: 1 + the slot of the glass in the simulation of the snow (the renderer sets it), 0: none #pragma param(snow_slot, 2, 2, 1, zero) @@ -79,425 +64,122 @@ layout(binding = 1) uniform sampler2D raindropsatlas; layout(binding = 2) uniform sampler2D wipermask; layout(binding = 3) uniform sampler2D normalmap; -// --- Tuning ----------------------------------------------------------------- -// Intensity = rain_params.x = saturate(Overcast - 1). The slider range 1.00..2.00 (Overcast) maps to intensity 0..1. The share of flake cells is pow(intensity, 0.8) * snow_gain * snow_density, -// so with the defaults every cell carries a flake from Overcast ~ 1.2 and the film closes the glass at about 1.3 (1.1 = light snow, 1.5+ = blizzard). -const float snow_gain = 1.4; // how fast the glass gets covered when the snowfall gets heavier (higher = already plastered in light snow) -const float snow_density = 0.95; // upper limit of the share of cells that carry a big flake -const float snow_small = 0.80; // same for the layer of small flakes (0 = off) -const float snow_pack = 0.90; // opacity of the patches that form where flakes clump together (0 = no patches) -const float snow_clump = 2.60; // how readily neighbouring flakes run together into one patch (higher = patches form sooner and get bigger) -const float snow_clump_share = 0.55; // share of the flakes that run together into patches; the rest stay separate flakes -const float snow_hold = 40.0; // seconds a flake stays white before it starts to melt (longer in heavy snow) -const float snow_melt = 30.0; // seconds the melting takes (snow fades into a water spot) -const float snow_slide_share = 0.40; // share of the melting flakes that run down the glass -const float snow_slide_len = 2.0; // how far a sliding flake runs, in cells (max 2.4) -const float snow_grow_fast = 5.3; // seconds a patch needs to grow from a clump to a big sheet in the heaviest snowfall -const float snow_grow_slow = 46.7; // same in the lightest snowfall (it still gets there, just much later) -const float snow_haze = 1.0; // blur of the scene behind and around the snow patches (frosted glass), 0 = off, 1 = full (radius: windscreen_view.glsl) -const float snow_distort = 2.0; // picture distortion seen through thin snow (refraction by its relief), 0 = off -const float snow_flake_scale = 2.5; // size of the flakes from the atlas relative to one grid cell (2-3 = two to three times bigger than before; the flakes get fewer) -const float snow_regen = 25.0; // seconds until snow is back on a wiped area (in light snowfall) -const float snow_opacity = 1.0; // overall opacity -const float snow_uv_aspect = 1.0; // glass width / height in the world if the UV is stretched -const float snow_bump = 1.0; // strength of the 3D relief from the normal map, 0 = flat -const float snow_gloss = 0.45; // glints of the sun / headlights on the snow, 0 = matt -const float snow_translucency = 0.8; // glow of thin snow when you look towards the sun / a lamp, 0 = off -const float snow_melt_blur = 0.8; // blur of the scene around the water spots of melting flakes (0 = off, 1 = full) -const float snow_fresh_blur = 0.0; // blur around fresh dry flakes: physically there is none, a little (0.1-0.2) fakes light scattering +// --- tuning ------------------------------------------------------------------------------------------------------------------ +const float snow_flake = 1.2; // size of a flake, texels of the map (grows to 1.6x with the snow of its texel) +const float snow_layer = 0.6; // mm of snow from which the layer starts (clumps), the cover grows to full by 1.5 mm +const float snow_layer_cell = 3.0; // a sprite of the layer every this many texels +const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) +const float snow_thin = 0.45; // opacity of a single thin flake (ice crystals let most of the light through) +const float snow_bump = 1.0; // strength of the relief from the normal map, 0 = flat +const float snow_gloss = 0.45; // glints of the sun / headlights on the snow, 0 = matt +const float snow_translucency = 0.8; // glow of thin snow when you look towards the sun / a lamp, 0 = off +const float snow_haze = 1.0; // blur of the scene behind thin snow (frosted glass), 0 = off +const float snow_drop_bend = 1.0; // how strongly the drops bend the picture behind them +const float snow_wet_blur = 0.6; // blur of the scene behind a wet film -#ifndef SNOW_FLIP_Y -#define SNOW_FLIP_Y 0 // set to 1 if sliding flakes run UP the glass (the glass UV then has v growing downwards) -#endif -const float SNOW_SIZE_MIN = 0.70; // flake size in grid cells (keep max <= 1.8, the search covers 3x3 cells) -const float SNOW_SIZE_MAX = 1.50; -const float SNOW_SLIDER_MAX = 1.10; // a flake that slides is smaller than this (it gets stretched on its way down) -const float SNOW_HALO_SCALE = 1.5; // blur ring radius = flake half-size * this -const float SNOW_LAND_TIME = 1.5; // seconds a flake takes to land and settle -const float SNOW_REFR_MAXPX = 96.0; // the largest picture shift of thin snow, screen pixels -const float WS_REFR_MAXPX = 96.0; // the largest picture shift the post-processing makes, screen pixels; must match rain_windscreen_haze.glsl -const float WS_BEND_ENC = 60.0; // the bend request in the velocity target; must match rain_windscreen_haze.glsl +const float WS_REFR_MAXPX = 96.0; // the largest picture shift the post-processing makes, screen pixels; as rain_windscreen_haze.glsl +const float WS_BEND_ENC = 60.0; // the bend request in the velocity target; as rain_windscreen_haze.glsl const float WS_DROP_BIAS = 192.0; -const float WS_ENC = 64.0; // the haze request in the velocity target; must match rain_windscreen_haze.glsl -const float SNOW_REFR_MIX = 0.85; // 0 = no refraction, 1 = only the bent picture +const float WS_ENC = 64.0; // the haze request in the velocity target; as rain_windscreen_haze.glsl -#ifndef SNOW_MATCH_RAIN_GLASS -#define SNOW_MATCH_RAIN_GLASS 0 // 4.6: rain_windscreen writes the glass straight, not premultiplied -#endif +const float SNOW_FRESH = 0.1; // water in a mm of fresh snow, mm (as water_snow.comp) +const float SNOW_PACKED = 0.4; // and of packed snow -float snHaze = 0.0; // set by snowFilm: 1 inside / next to a snow patch (drives the frosted-glass blur) -float snWipeSince = 1.0e5; // set by GetMixFactor: seconds since the wiper last cleaned this spot -float GetMixFactor(in vec2 co, out float side); +// tiles of the atlas +const int TILE_DROP = 15; -const float SNOW_MERGE_R = 2.0; // reach of a flake's 'snow mass' in flake half-sizes (flakes closer than this run together) -const float SNOW_CLUMP_THR = 0.80; // summed mass above which the glass is covered +int snSlot = 0; +uint snMap = 0u; +bool snBig = true; // a 4 x 4 atlas (else the older 2 x 2) +float snHaze = 0.0; // the picture behind is blurred (thin snow, a wet film) +vec2 snBend = vec2(0.0); // the drops bend the picture behind (their normals, weighted) +float snBendA = 0.0; -float snHash(vec2 p) +struct sprite_acc { - return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); + vec3 rgb; // premultiplied + float a; + vec3 n; // premultiplied, tangent space + float tr; // translucency, premultiplied +}; + +// the corner of a tile in the atlas; an older 2 x 2 atlas stands its four tiles in for the sixteen +vec2 snTile(int tile) +{ + if (snBig) + return vec2(float(tile % 4), float(tile / 4)) * 0.25; + int old = 0; // a fluffy flake + if ((tile == 6) || (tile == 7)) + old = 2; // crumbs + else if ((tile >= 8) && (tile != 10) && (tile != 11) && (tile != TILE_DROP)) + old = 1; // a wet lump + else if (tile == TILE_DROP) + old = 3; // a melted spot + return vec2(float(old % 2), float(old / 2)) * 0.5; } -float snNoise(vec2 p) +float snTileSize() { - vec2 i = floor(p); - vec2 f = fract(p); - f = f * f * (3.0 - 2.0 * f); - return mix(mix(snHash(i), snHash(i + vec2(1.0, 0.0)), f.x), - mix(snHash(i + vec2(0.0, 1.0)), snHash(i + vec2(1.0, 1.0)), f.x), f.y); + return snBig ? 0.25 : 0.5; } -float snFbm(vec2 p) +// a sprite over the accumulator: Local the place in it (0 .. 1), Rot its rotation (cos, sin), Tone its colour +void snSprite(vec2 local, int tile, float alpha, vec3 tone, vec2 rot, float flip, float lod, float bump, inout sprite_acc acc) { - float a = 0.5; - float v = 0.0; - for (int i = 0; i < 4; ++i) - { - v += a * snNoise(p); - p = p * 2.07 + vec2(17.3, 9.1); - a *= 0.5; - } - return v / 0.9375; -} - -// One flake in one cell. `age` = seconds since it landed. -void snowFlake(vec2 ncell, uint seed, float age, float gridSize, float pixelUV, vec2 aspect, - float sizeMul, float opacityMul, float hold, float meltT, float slideShare, - inout vec3 accRGB, inout float accA, inout float smear, - inout vec3 accN, inout float accTr, inout float accM) -{ - float mt = clamp((age - hold) / meltT, 0.0, 1.0); // 0 = dry, 1 = melted away - float melt = smoothstep(0.0, 1.0, mt); - float fade = 1.0 - smoothstep(0.75, 1.0, mt); // the water spot dries up at the very end - float land = smoothstep(0.0, 0.3, age); // it lands at once (no ghostly fade-in): it just starts small - - float jx = RandF(seed); - float jy = RandF(seed); - vec2 center = (ncell + vec2(jx, jy)) / gridSize; - - float rs = RandF(seed); - float ang = RandF(seed) * 6.2831853; - float flipX = (RandF(seed) < 0.5) ? -1.0 : 1.0; - float kind = RandF(seed); - float tone = mix(0.94, 1.04, RandF(seed)); - bool slider = RandF(seed) < slideShare; - float slideLen = mix(0.8, 1.0, RandF(seed)) * min(snow_slide_len, 2.4) / gridSize; - bool clumper = RandF(seed) < snow_clump_share; // this flake sticks to its neighbours (else it stays on its own) - float aniso = mix(0.62, 1.0, RandF(seed)); // flakes are never round: random squash after rotation - - float szMax = slider ? SNOW_SLIDER_MAX : SNOW_SIZE_MAX; - float size = mix(SNOW_SIZE_MIN, szMax, rs * rs) / gridSize * sizeMul * mix(0.45, 1.0, smoothstep(0.0, max(hold * 0.25, 1.0), age)) * mix(1.0, 0.85, melt); // grows as snow piles onto it - - // a sliding flake runs down while it melts and stretches into a drip - float slideP = slider ? smoothstep(0.05, 1.0, mt) : 0.0; -#if SNOW_FLIP_Y - center.y += slideLen * slideP * slideP; -#else - center.y -= slideLen * slideP * slideP; -#endif - float stretchY = 1.0 + 0.9 * slideP; - - vec2 d = (f_coord - center) * aspect; - d.y /= stretchY; - - // the 'snow mass' of this flake: neighbouring flakes add up, and where the sum is high they have run into one patch - { - float kr = min(size * 0.5 * SNOW_MERGE_R, 1.0 / gridSize); // (1 cell: the search only covers the 3x3 cells around the pixel) - float m = 1.0 - smoothstep(0.0, kr, length(d)); - if (clumper) - accM += m * m * (3.0 - 2.0 * m) * (1.0 - 0.6 * melt) * snow_clump * land; - } - - // blur only around the water of a melting flake (and, optionally, a little around fresh ones) - float haloR = size * 0.5 * SNOW_HALO_SCALE; - float dist = length(d); - if (dist < haloR) - { - float ring = 1.0 - smoothstep(0.35 * haloR, haloR, dist); - smear = max(smear, ring * land * (melt * snow_melt_blur + (1.0 - melt) * snow_fresh_blur)); - } - - float c = cos(ang); - float s = sin(ang); - vec2 r = vec2(c * d.x + s * d.y, -s * d.x + c * d.y); - r.x *= flipX / aniso; - - vec2 local = r / size + 0.5; - if (any(lessThan(local, vec2(0.0))) || any(greaterThan(local, vec2(1.0)))) + vec2 uv = snTile(tile) + local * snTileSize(); + vec4 t = textureLod(raindropsatlas, uv, lod); + vec4 n = textureLod(normalmap, uv, lod); + float a = clamp(t.a * alpha, 0.0, 1.0); + if (a <= 0.002) return; - - float lod = clamp(log2(max(pixelUV / size * 0.5 * float(textureSize(raindropsatlas, 0).x), 1.0)), 0.0, 4.0); - - // dry flake (tiles 0..2: fluffy, wet lump, crumbs) and, while melting, its water spot (tile 3) - vec2 off0 = (kind < 0.40) ? vec2(0.0, 0.5) : ((kind < 0.72) ? vec2(0.5, 0.5) : vec2(0.0, 0.0)); - vec2 off3 = vec2(0.5, 0.0); - vec4 t0 = textureLod(raindropsatlas, off0 + local * 0.5, lod); - vec4 n0 = textureLod(normalmap, off0 + local * 0.5, lod); - float a0 = t0.a * (1.0 - melt); - float a3 = 0.0; - vec4 t3 = vec4(0.0); - vec4 n3 = vec4(0.5, 0.5, 0.0, 0.0); - if (melt > 0.001) - { - t3 = textureLod(raindropsatlas, off3 + local * 0.5, lod); - n3 = textureLod(normalmap, off3 + local * 0.5, lod); - a3 = t3.a * smoothstep(0.0, 0.5, melt) * fade; - } - - float aSum = a0 + a3; - float a = clamp(aSum * land * snow_opacity * opacityMul, 0.0, 1.0); - if (a <= 0.0) - return; - vec3 col = (t0.rgb * a0 + t3.rgb * a3) / max(aSum, 1e-4); - vec2 nxy = ((n0.rg * 2.0 - 1.0) * a0 + (n3.rg * 2.0 - 1.0) * a3) / max(aSum, 1e-4); - nxy *= snow_bump * land; - nxy.x *= flipX; - vec2 nuv = vec2(c * nxy.x - s * nxy.y, s * nxy.x + c * nxy.y); - vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); - - // thin snow lets light through: the dry part is translucent, the water spot is not - float tr = (a0 / max(aSum, 1e-4)) * (1.0 - t0.a * 0.55); - - accRGB = col * tone * a + accRGB * (1.0 - a); - accN = nT * a + accN * (1.0 - a); - accTr = tr * a + accTr * (1.0 - a); - accA = a + accA * (1.0 - a); -} - -// Adds one layer of flakes to the premultiplied accumulators. Same scheme as the drops of rain_windscreen: -// the cells around the pixel (a few more above it, for the flakes that slide down), the wipers decide per cell whether it -// is clear, the precipitation intensity decides whether the cell carries a flake right now. -void snowLayer(float gridSize, float density, uint layerSeed, float sizeMul, float opacityMul, float slideShare, int rowsUp, - float pixelUV, vec2 aspect, - inout vec3 accRGB, inout float accA, inout float smear, - inout vec3 accN, inout float accTr, inout float accM) -{ - vec2 cell = floor(f_coord * gridSize); - float heavy = clamp(rain_params.x, 0.0, 1.0); - float hold = snow_hold * (1.0 + 1.5 * heavy); // in heavy snow there is no time to melt - float meltT = max(snow_melt, 1.0); - float life = hold + meltT; - float occupancy = mix(0.70, 0.97, heavy); // share of the time a cell holds a flake - float cycBase = life / occupancy; - float share = clamp(pow(rain_params.x, 0.8) * snow_gain, 0.0, 1.0) * density; - - // flakes slide upwards in UV if SNOW_FLIP_Y: search the rows on the other side -#if SNOW_FLIP_Y - int oyMin = -1 - rowsUp; - int oyMax = 1; -#else - int oyMin = -1; - int oyMax = 1 + rowsUp; -#endif - - for (int oy = oyMin; oy <= oyMax; oy++) { - for (int ox = -1; ox <= 1; ox++) { - - vec2 ncell = cell + vec2(float(ox), float(oy)); - uvec2 ucell = uvec2(ivec2(ncell)); - - float side; - float mixFactor = GetMixFactor((ncell + 0.5) / gridSize, side); - - // timing of this cell: the same in every round - uint tseed = Hash(uvec3(ucell, layerSeed + 31u)); - float cyc = cycBase * (1.0 + mix(0.45, 0.03, heavy) * RandF(tseed)); // in heavy snow the cells hardly ever stand empty - float tOff = RandF(tseed) * cyc; - float patchMul = mix(0.7, 1.3, RandF(tseed)); - float tl = time + tOff; - float rnd = floor(tl / cyc); - float age = tl - rnd * cyc; // seconds since this round's flake landed - if (age > life) - continue; - - // a new flake (position, shape, size) every round; the wiper stroke is part of the seed, as in the rain - uint seed = Hash(uvec3(ucell, layerSeed + uint(side) * 7919u + uint(max(rnd, 0.0)) * 2654435u)); - - if (mixFactor < RandF(seed)) - continue; // wiped / still regrowing - - float activate = RandF(seed); - if (activate > share * patchMul) - continue; - - snowFlake(ncell, seed, age, gridSize, pixelUV, aspect, sizeMul, opacityMul, hold, meltT, slideShare, - accRGB, accA, smear, accN, accTr, accM); - } - } -} - -// Snow patches: a crusty white sheet with the structure of real snow (lumps, grain, thin translucent edges, holes). -// WHERE it grows is decided by the flakes: the 'snow mass' of the flakes that stick together (accM) pushes the sheet up, so a patch starts -// where several flakes landed close to each other, spreads from there in an irregular shape and keeps growing while more flakes land -// next to it; when they melt or slide away it breaks up into holes. It is drawn UNDER the flakes. -// Snow patches built from 'pach pach pach' accretion: every big cell carries a patch that is a heap of 22 small clumps (about flake sized). -// The clumps pop up one after another (the ones near the middle first, so the patch spreads outwards) and each lands at once, as a ragged -// piece that merges with the pieces already there. How fast that goes depends on the snowfall intensity (growT); left alone the pieces -// overlap into a closed sheet. Regions of the glass start at different moments. Returns f > 0 inside the snow (f = depth in sheet cells). -float snowSheetField(float gridSize) -{ - float sg = gridSize * 0.19; - vec2 pg = f_coord * sg; - vec2 cell = floor(pg); - float heavy = clamp(rain_params.x, 0.0, 1.0); - float growT = mix(snow_grow_slow, snow_grow_fast, pow(heavy, 0.5)); - float hold = snow_hold * (1.0 + 1.5 * heavy); - float meltT = max(snow_melt, 1.0); - float life = growT + hold + meltT; - float occupancy = mix(0.80, 0.97, heavy); - float cycBase = life / occupancy; - float share = clamp(heavy * 1.6, 0.0, 1.0) * 0.95 + 0.05 * heavy; // share of the cells that carry a patch (1.0 = none, ~1.6 = nearly all) - - // wiper: pixel precise. The sheet at a pixel is no older than the last wipe of that pixel. - float sidePx; - float mixPx = GetMixFactor(f_coord, sidePx); - float wipeAgePx = snWipeSince; - - float acc = 0.0; // summed clump kernels (metaballs): touching clumps merge, no scalloped circles - for (int oy = -1; oy <= 1; oy++) { - for (int ox = -1; ox <= 1; ox++) { - vec2 ncell = cell + vec2(float(ox), float(oy)); - uvec2 ucell = uvec2(ivec2(ncell)); - - uint tseed = Hash(uvec3(ucell, 211u)); - float cyc = cycBase * (1.0 + mix(0.45, 0.03, heavy) * RandF(tseed)); - float tOff = RandF(tseed) * cyc; - float tl = time + tOff; - float rnd = floor(tl / cyc); - float age = tl - rnd * cyc; - if (age > life) - continue; - - uint seed = Hash(uvec3(ucell, 223u + uint(sidePx) * 7919u + uint(max(rnd, 0.0)) * 2654435u)); - if (RandF(seed) > share) - continue; - - vec2 c = ncell + vec2(0.1 + 0.8 * RandF(seed), 0.1 + 0.8 * RandF(seed)); - vec2 dc = pg - c; - if (dot(dc, dc) > 1.2 * 1.2) - continue; // too far from this patch to be touched by any of its clumps - - age = min(age, wipeAgePx); - float delay = snNoise(c * 0.30 + 3.7) * growT * 0.35; // regions of the glass start at different moments - float ga = max(age - delay, 0.0); - float mt = clamp((age - growT - hold) / meltT, 0.0, 1.0); - float shrink = 1.0 - 1.1 * mt * mt; // melting: the clumps shrink and holes open - - for (int i = 0; i < 22; i++) { - uint bs = Hash(uvec3(seed, uint(i), 977u)); - float rho = RandF(bs); - float an = RandF(bs) * 6.2831853; - float rad = 0.85 * sqrt(rho); - vec2 bp = c + rad * vec2(cos(an), sin(an)); - float rb = mix(0.17, 0.30, RandF(bs)); - float ti = growT * (0.03 + 0.97 * pow(rad / 0.85, 0.9) * mix(0.70, 1.0, RandF(bs))); // inner clumps first - // each clump arrives in three small portions (pop, pop, pop): 45% -> 72% -> 100% of its size, no fading - float dT = growT * 0.10; - float stg = step(ti, ga) + step(ti + dT, ga) + step(ti + 2.0 * dT, ga); // 0..3 - if (stg <= 0.0) - continue; - float rr = rb * shrink * (stg < 1.5 ? 0.45 : (stg < 2.5 ? 0.72 : 1.0)); - float kd = max(1.0 - length(pg - bp) / max(rr * 1.35, 1e-3), 0.0); - acc += kd * kd * (3.0 - 2.0 * kd); - } - } - } - // torn, crumbly edge: fine noise (features about a flake wide) decides where the summed clumps stop, so the outline is irregular - // snow and not a ring of circles - float nz = snFbm(pg * 5.5 + 13.0) * 0.45 + snFbm(pg * 13.0 + 7.0) * 0.35 + snFbm(pg * 31.0 + 3.0) * 0.20 - 0.5; - float best = (acc - 0.50) * 0.20 + nz * 0.30; - best -= (1.0 - smoothstep(0.0, 0.12, mixPx)) * 1.0; // swept (or still regrowing) areas - return best; -} - -void snowFilm(float gridSize, inout vec3 accRGB, inout float accA, inout vec3 accN, inout float accTr) -{ -#if SNOW_FLIP_Y - float dir = -1.0; -#else - float dir = 1.0; -#endif - float sf = snowSheetField(gridSize); - snHaze = max(snHaze, smoothstep(-0.045, 0.0, sf)); // the glass next to a patch is frosted a little as well - float cover = smoothstep(0.0, 0.03, sf); - if (cover <= 0.002) - return; - float thick = smoothstep(0.0, 0.11, sf); // 0 at the thin edge, 1 in the thick middle - vec2 p = f_coord * gridSize * 0.17 + vec2(0.0, dir * time * 0.008); - vec2 q = f_coord * gridSize * 2.6; - float h0 = snFbm(p); - - // lumpy surface: big drifts + fine grain - float f1 = snFbm(q); - float e = 0.06; - float ef = 0.05; - vec2 g = vec2(snFbm(p + vec2(e, 0.0)) - h0, snFbm(p + vec2(0.0, e)) - h0) / e; - vec2 gf = vec2(snFbm(q + vec2(ef, 0.0)) - f1, snFbm(q + vec2(0.0, ef)) - f1) / ef; - vec3 nT = normalize(vec3(-(g * 0.55 + gf * 0.20) * snow_bump, 1.0)); - - vec3 thin = vec3(0.66, 0.72, 0.80); // thin snow is greyish-blue and lets the dark background through - vec3 full = vec3(0.93, 0.95, 0.98); - vec3 col = mix(thin, full, thick) * (0.62 + 0.55 * f1) * (0.88 + 0.22 * snNoise(f_coord * gridSize * 9.0)) * (0.85 + 0.3 * h0); - float a = clamp(cover * mix(0.50, 0.96, thick) * snow_pack * snow_opacity, 0.0, 0.97); - float under = 1.0 - accA; - accRGB = accRGB + col * a * under; - accN = accN + nT * a * under; - accTr = accTr + mix(0.60, 0.30, thick) * a * under; - accA = accA + a * under; -} - -// --- The snow of the simulation (water_snow.comp): the map of the glass --------------------------------------------------- -// When the renderer simulates the snow of the glass (the param snow_slot holds 1 + its slot), the snow, the water, how packed the -// snow is and the shape of its flakes come from the map of the glass (water.glsl), which keeps them from frame to frame: the flakes -// land and stay where they landed, pile up into a layer, the blades push it into ridges at the ends of their sweeps and leave a wet -// trace, it melts at the warm glass and slush slides down. Here it's only drawn: -// - a texel of the map with a little snow is a flake (atlas tiles 0..2: fluffy when dry, a wet lump when wet or packed, crumbs), -// the more snow the bigger; with mostly water left it's the water spot (tile 3) -// - where the snow is thicker it's a layer: its edge torn by the grain of the snow, as opaque as it's thick (Beer-Lambert), grey -// and translucent when wet (slush), smoother and denser when packed; its relief from the slopes of the snow of the map -// - the water: wet glass bends the picture behind (the post-processing), the thin snow hazes it -// Without the simulation (an older renderer, no compute) the procedural snow below draws the glass as before. -const float snow_map_flake = 1.15; // size of a flake relative to a texel of the map (the snow of a texel) -const float snow_map_layer = 1.0; // mm of snow above which the flakes run together into a layer -const float snow_map_opaque = 1.8; // mm of fresh snow which lets 1/e of the light through (packed: half of it) -const float snow_map_relief = 0.6; // how much the slopes of the snow tilt its surface -const float snow_map_grain = 0.35; // the fine grain of the layer (its relief) -const float snow_map_wet_bend = 0.6; // how strongly a wet glass bends the picture behind it -const float snow_map_thin = 0.45; // opacity of a single thin flake (ice crystals let most of the light through: the picture - // behind shows through it, blurred, rather than a dark speck at night) - -int snMapSlot = -1; -uint snMapIndex = 0u; -float snWet = 0.0; // set by snowMapped: the film of water (0 .. 1) -vec2 snWetN = vec2(0.0); // set by snowMapped: the slope of the water, for the bend of the picture - -// the snow of the map at a place of the glass -vec4 snMapAt(vec2 uv) -{ - return water_snow_at(uint(snMapSlot), snMapIndex, uv); -} - -// a flake of the map drawn over the accumulators: Local the place in its sprite (0 .. 1), Tile the corner of its tile in the atlas -void snowMapSprite(vec2 local, vec2 tile, float alpha, float tone, float flip, float c, float s, float lod, - inout vec3 accRGB, inout float accA, inout vec3 accN, inout float accTr) -{ - vec4 t = textureLod(raindropsatlas, tile + local * 0.5, lod); - vec4 n = textureLod(normalmap, tile + local * 0.5, lod); - float a = clamp(t.a * alpha * snow_opacity, 0.0, 1.0); - if (a <= 0.0) - return; - vec2 nxy = (n.rg * 2.0 - 1.0) * snow_bump; + vec2 nxy = (n.rg * 2.0 - 1.0) * snow_bump * bump; nxy.x *= flip; - vec2 nuv = vec2(c * nxy.x - s * nxy.y, s * nxy.x + c * nxy.y); - vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); - float tr = (1.0 - t.a * 0.55); - accRGB = t.rgb * tone * a + accRGB * (1.0 - a); - accN = nT * a + accN * (1.0 - a); - accTr = tr * a + accTr * (1.0 - a); - accA = a + accA * (1.0 - a); + vec2 nuv = vec2(rot.x * nxy.x - rot.y * nxy.y, rot.y * nxy.x + rot.x * nxy.y); + vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); + acc.rgb = t.rgb * tone * a + acc.rgb * (1.0 - a); + acc.n = nT * a + acc.n * (1.0 - a); + acc.tr = (1.0 - t.a * 0.55) * a + acc.tr * (1.0 - a); + acc.a = a + acc.a * (1.0 - a); + if (tile == TILE_DROP) + { + snBend = snBend * (1.0 - a) + nuv * a; + snBendA = snBendA * (1.0 - a) + a; + } } -// the flakes of the texels around the pixel -void snowMapFlakes(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float accA, inout vec3 accN, inout float accTr) +// where in a sprite the pixel is: P the pixel and C the centre of the sprite, in the units of its grid (the size of the sprite +// in them), Aspect the cells as they lie on the glass; false outside the sprite +bool snLocal(vec2 p, vec2 c, float size, vec2 aspect, vec2 rot, float flip, float aniso, out vec2 local) +{ + vec2 d = (p - c) * aspect; + vec2 r = vec2(rot.x * d.x + rot.y * d.y, -rot.y * d.x + rot.x * d.y); + r.x *= flip / aniso; + local = r / size + 0.5; + return all(greaterThanEqual(local, vec2(0.0))) && all(lessThanEqual(local, vec2(1.0))); +} + +float snLod(float pixelUV, float sizeUV) +{ + float tilePx = float(textureSize(raindropsatlas, 0).x) * snTileSize(); + return clamp(log2(max(pixelUV / sizeUV * tilePx, 1.0)), 0.0, 6.0); +} + +// how wet the snow of a state of the map is (0 dry .. 1 slush) +float snWetness(vec4 q) +{ + return q.y / (q.y + q.x * mix(SNOW_FRESH, SNOW_PACKED, q.z) + 1e-4); +} + +// the tone of the snow: grey and darker when wet (slush), a little grey when packed +vec3 snTone(vec4 q, float random) +{ + vec3 tone = vec3(mix(0.94, 1.04, random)); + tone *= mix(vec3(1.0), vec3(0.95, 0.96, 0.98), q.z); + return tone * mix(vec3(1.0), vec3(0.78, 0.83, 0.88), smoothstep(0.3, 0.8, snWetness(q))); +} + +// the flakes: a sprite on every texel holding snow (a drop where only its water is left) +void snFlakes(vec2 aspect, float pixelUV, inout sprite_acc acc) { vec2 p = f_coord * float(WATER_MAP); ivec2 here = ivec2(floor(p)); @@ -506,101 +188,95 @@ void snowMapFlakes(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float ac for (int ox = -1; ox <= 1; ++ox) { ivec2 texel = here + ivec2(ox, oy); - vec4 q = water_snow_texel(uint(snMapSlot), snMapIndex, texel); - float density = mix(0.1, 0.4, q.z); - float wet = q.y / (q.y + q.x * density + 1e-4); - bool spot = (q.x < 0.05) && (q.y > 0.03); // a flake melted into its water - if ((q.x < 0.05) && (false == spot)) + vec4 q = water_snow_texel(uint(snSlot), snMap, texel); + bool drop = (q.x < 0.05) && (q.y > 0.03); + if ((q.x < 0.05) && (false == drop)) continue; - uint seed = Hash(uvec3(uvec2(texel), uint(q.w * 65535.0) + 7u * uint(snMapSlot))); - // the water of a texel is a droplet only now and then: the more water the more of them - if (spot && (RandF(seed) > smoothstep(0.03, 0.2, q.y))) + uint seed = Hash(uvec3(uvec2(texel), uint(q.w * 65535.0) + 7u * uint(snSlot))); + // the water of a texel is a drop only now and then: the more water the more of them + if (drop && (RandF(seed) > smoothstep(0.03, 0.2, q.y))) continue; - vec2 center = vec2(texel) + vec2(0.15 + 0.7 * RandF(seed), 0.15 + 0.7 * RandF(seed)); + vec2 centre = vec2(texel) + 0.2 + 0.6 * vec2(RandF(seed), RandF(seed)); float ang = RandF(seed) * 6.2831853; + vec2 rot = vec2(cos(ang), sin(ang)); float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; float kind = RandF(seed); - float tone = mix(0.94, 1.04, RandF(seed)); - float aniso = mix(0.62, 1.0, RandF(seed)); - // the more snow the texel holds the bigger the flake (a lump of a few flakes) - float size = snow_map_flake * mix(0.6, 1.0, RandF(seed)) * (spot ? mix(0.5, 1.1, smoothstep(0.03, 0.3, q.y)) - : mix(0.7, 1.6, smoothstep(0.05, 2.0, q.x))); - vec2 d = (p - center) * aspect; - float c = cos(ang); - float s = sin(ang); - vec2 r = vec2(c * d.x + s * d.y, -s * d.x + c * d.y); - r.x *= flip / aniso; - vec2 local = r / size + 0.5; - if (any(lessThan(local, vec2(0.0))) || any(greaterThan(local, vec2(1.0)))) + float random = RandF(seed); + float size = snow_flake * mix(0.75, 1.0, RandF(seed)) + * (drop ? mix(0.5, 1.0, smoothstep(0.03, 0.3, q.y)) : mix(0.8, 1.6, smoothstep(0.05, 1.5, q.x))); + vec2 local; + if (false == snLocal(p, centre, size, aspect, rot, flip, 1.0, local)) continue; - float sizeUV = size / float(WATER_MAP); - float lod = clamp(log2(max(pixelUV / sizeUV * 0.5 * float(textureSize(raindropsatlas, 0).x), 1.0)), 0.0, 4.0); - vec2 tile; - if (spot) - tile = vec2(0.5, 0.0); - else if ((wet > 0.3) || (q.z > 0.5) || (kind < 0.30)) - tile = vec2(0.5, 0.5); // a wet lump - else if (kind < 0.75) - tile = vec2(0.0, 0.5); // fluffy + int tile; + float alpha; + if (drop) + { + tile = TILE_DROP; + alpha = smoothstep(0.03, 0.1, q.y); + } else - tile = vec2(0.0, 0.0); // crumbs - float alpha = spot ? smoothstep(0.03, 0.1, q.y) : smoothstep(0.05, 0.25, q.x) * mix(snow_map_thin, 1.0, smoothstep(0.3, 2.5, q.x)); - snowMapSprite(local, tile, alpha, tone, flip, c, s, lod, accRGB, accA, accN, accTr); + { + if (snWetness(q) > 0.35) + tile = 8 + int(kind * 2.0); // wet lumps + else if (kind < 0.25) + tile = int(kind * 8.0); // star crystals (0, 1) + else if (kind < 0.35) + tile = 2; // a plate + else if (kind < 0.45) + tile = 3; // needles + else if (kind < 0.80) + tile = 4 + int((kind - 0.45) / 0.35 * 2.0); // flakes of a few crystals + else + tile = 6 + int((kind - 0.80) / 0.2 * 2.0); // crumbs + tile = min(tile, 9); + alpha = smoothstep(0.05, 0.25, q.x) * mix(snow_thin, 1.0, smoothstep(0.3, 2.5, q.x)); + } + snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / float(WATER_MAP)), 1.0, acc); } } } -// the snow of the map at the pixel: the flakes, the layer of the snow under them, the water, the haze -void snowMapped(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float accA, inout float smear, inout vec3 accN, inout float accTr) +// the layer: a bigger sprite every few texels where the snow is thicker, clumps and then packed snow, overlapping into a cover +void snLayer(vec2 aspect, float pixelUV, inout sprite_acc acc) { - vec4 q = snMapAt(f_coord); - float e = 1.0 / float(WATER_MAP); - vec4 qr = snMapAt(f_coord + vec2(e, 0.0)); - vec4 ql = snMapAt(f_coord - vec2(e, 0.0)); - vec4 qu = snMapAt(f_coord + vec2(0.0, e)); - vec4 qd = snMapAt(f_coord - vec2(0.0, e)); - float around = (q.x + qr.x + ql.x + qu.x + qd.x) * 0.2; - - // the flakes of thin snow and the water spots; the picture behind a flake is blurred (it scatters the light going through) - snowMapFlakes(aspect, pixelUV, accRGB, accA, accN, accTr); - snHaze = max(snHaze, smoothstep(0.0, 0.3, accA)); - - // the water: the film bends the picture behind - snWet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); - snWetN = vec2(qr.y - ql.y, qu.y - qd.y) * 2.0 + (vec2(snNoise(f_coord * 900.0), snNoise(f_coord * 900.0 + 31.0)) - 0.5) * 0.6 * snWet; - smear = max(smear, snWet * snow_melt_blur * 0.6); - // thin snow hazes the picture around it - snHaze = max(snHaze, smoothstep(0.15, 1.0, around)); - - // the layer, where the snow has run together - vec2 gp = f_coord * float(WATER_MAP) * aspect; - float grain = snFbm(gp * 0.9 + 3.0) * 0.55 + snFbm(gp * 2.7 + 11.0) * 0.30 + snFbm(gp * 7.1 + 5.0) * 0.15; - float edge = (q.x - snow_map_layer) / max(snow_map_layer, 1e-3) + (grain - 0.5) * 1.6; - float cover = smoothstep(0.0, 0.35, edge); - if (cover <= 0.002) - return; - float density = mix(0.1, 0.4, q.z); - float wet = q.y / (q.y + q.x * density + 1e-4); - float opaque = snow_map_opaque * mix(1.0, 0.5, q.z); - float thick = 1.0 - exp(-q.x / opaque); - // the relief: the slopes of the snow of the map (ridges, the edges of the swept arcs) and the grain of the fresh snow - vec2 slope = vec2(qr.x - ql.x, qu.x - qd.x) * 0.5 * snow_map_relief; - float f1 = snFbm(gp * 3.3); - float ef = 0.05; - vec2 gf = vec2(snFbm(gp * 3.3 + vec2(ef, 0.0)) - f1, snFbm(gp * 3.3 + vec2(0.0, ef)) - f1) / ef; - vec3 nT = normalize(vec3(-(slope + gf * snow_map_grain * (1.0 - 0.6 * q.z)) * snow_bump, 1.0)); - - vec3 fresh = vec3(0.93, 0.95, 0.98); - vec3 packed = vec3(0.89, 0.91, 0.94); - vec3 slush = vec3(0.60, 0.66, 0.73); - vec3 col = mix(mix(fresh, packed, q.z), slush, smoothstep(0.2, 0.7, wet)); - col *= (0.80 + 0.30 * f1 * (1.0 - 0.5 * q.z)) * (0.92 + 0.12 * grain); - float a = clamp(cover * mix(0.35, 0.97, thick) * mix(1.0, 0.75, smoothstep(0.3, 0.8, wet)) * snow_pack * snow_opacity, 0.0, 0.97); - float under = 1.0 - accA; - accRGB = accRGB + col * a * under; - accN = accN + nT * a * under; - accTr = accTr + mix(0.60, 0.25, thick) * a * under; - accA = accA + a * under; + float cells = float(WATER_MAP) / snow_layer_cell; + vec2 p = f_coord * cells; + ivec2 here = ivec2(floor(p)); + for (int oy = -1; oy <= 1; ++oy) + { + for (int ox = -1; ox <= 1; ++ox) + { + ivec2 cell = here + ivec2(ox, oy); + uint seed = Hash(uvec3(uvec2(cell + 4096), 31u + 7u * uint(snSlot))); + vec2 centre = vec2(cell) + 0.3 + 0.4 * vec2(RandF(seed), RandF(seed)); + vec4 q = water_snow_at(uint(snSlot), snMap, centre / cells); + float present = smoothstep(snow_layer, snow_layer * 2.5, q.x); + if (RandF(seed) >= present) + continue; + float ang = RandF(seed) * 6.2831853; + vec2 rot = vec2(cos(ang), sin(ang)); + float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; + float kind = RandF(seed); + float random = RandF(seed); + float aniso = mix(0.8, 1.0, RandF(seed)); + float size = mix(1.25, 2.0, smoothstep(snow_layer, 4.0, q.x)) * mix(0.85, 1.0, RandF(seed)); + vec2 local; + if (false == snLocal(p, centre, size, aspect, rot, flip, aniso, local)) + continue; + int tile; + if (snWetness(q) > 0.45) + tile = 14; // slush + else if (q.x < 3.0) + tile = 10 + int(kind * 2.0); // clumps + else + tile = 12 + int(kind * 2.0); // packed snow + float thick = 1.0 - exp(-q.x / (snow_opaque * mix(1.0, 0.5, q.z))); + float alpha = mix(0.6, 1.0, thick); + // the ridges of the blades: packed and thick, a stronger relief + float bump = mix(1.0, 1.6, q.z * smoothstep(3.0, 12.0, q.x)); + snSprite(local, min(tile, 14), alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / cells), bump, acc); + } + } } void main() @@ -620,39 +296,32 @@ void main() Bgl *= invmax; vec4 tex_color = texture(diffuse, f_coord); // no discard: clean glass between faint dirt must still get snow and blur + float pixelUV = max(length(duv1), length(duv2)); + snBig = (textureSize(raindropsatlas, 0).x >= 2048); - float gridSize = max(ceil(param[2].x), 1.0); - float pixelUV = max(length(dFdx(f_coord)), length(dFdy(f_coord))); - snHaze = 0.0; - vec2 aspect = (snow_uv_aspect >= 1.0) ? vec2(snow_uv_aspect, 1.0) : vec2(1.0, 1.0 / max(snow_uv_aspect, 0.01)); - - vec3 snowRGB = vec3(0.0); // premultiplied - float snowA = 0.0; - float smear = 0.0; - vec3 snowN = vec3(0.0); - float snowTr = 0.0; - // the snow of the simulation where the glass has a map of it, else made up as before - snMapSlot = int(param[2].z + 0.5) - 1; - bool mapped = (snMapSlot >= 0) && (snMapSlot < WATER_SLOTS) && water_snow_map(uint(snMapSlot), snMapIndex); - if (mapped) + sprite_acc layer = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + sprite_acc flakes = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + float wet = 0.0; + snSlot = int(param[2].z + 0.5) - 1; + if ((snSlot >= 0) && (snSlot < WATER_SLOTS) && water_snow_map(uint(snSlot), snMap)) { // the texels of the map as they lie on the glass (the uv may be stretched) ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); - uint axis = (uint(snMapSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; + uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; vec2 span = vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)); - if (min(span.x, span.y) > 1e-6) - aspect = span / max(span.x, span.y); - snowMapped(aspect, pixelUV, snowRGB, snowA, smear, snowN, snowTr); - } - else if (rain_params.x > 0.0) - { - float mass = 0.0; - if (snow_small > 0.0) - snowLayer(gridSize * 2.4 / snow_flake_scale, snow_small, 17u, 0.9, 0.85, 0.0, 0, pixelUV, aspect, snowRGB, snowA, smear, snowN, snowTr, mass); - snowLayer(gridSize / snow_flake_scale, snow_density, 13u, 1.0, 1.0, snow_slide_share, 4, pixelUV, aspect, snowRGB, snowA, smear, snowN, snowTr, mass); - if (snow_pack > 0.0) - snowFilm(gridSize, snowRGB, snowA, snowN, snowTr); // patches where flakes have run together + vec2 aspect = (min(span.x, span.y) > 1e-6) ? span / max(span.x, span.y) : vec2(1.0); + snLayer(aspect, pixelUV, layer); + snFlakes(aspect, pixelUV, flakes); + vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); + wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); + // the picture behind thin flakes and a wet film is blurred + snHaze = max(smoothstep(0.0, 0.3, flakes.a) * (1.0 - smoothstep(0.5, 0.9, layer.a)), wet * snow_wet_blur); } + // the flakes over the layer + vec3 snowRGB = flakes.rgb + layer.rgb * (1.0 - flakes.a); + float snowA = flakes.a + layer.a * (1.0 - flakes.a); + vec3 snowN = flakes.n + layer.n * (1.0 - flakes.a); + float snowTr = flakes.tr + layer.tr * (1.0 - flakes.a); float glassA = tex_color.a * alpha_mult; float finalA = snowA + glassA * (1.0 - snowA); @@ -660,7 +329,7 @@ void main() vec3 albedo = premult / max(finalA, 1e-4); float glassShare = glassA * (1.0 - snowA) / max(finalA, 1e-4); - // relief: tilt the glass normal by the slope of the snow (flat where there is none) + // relief: tilt the glass normal by the normals of the sprites (flat where there are none) vec3 nDir = snowN + vec3(0.0, 0.0, 1.0) * (1.0 - snowA); vec3 fragnormal = Ngl; if (snowA > 0.001) @@ -671,13 +340,12 @@ void main() float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5 * glassShare + snow_gloss * snowA; legacy_gloss(); - // most of the glass is clear (no snow, a clear glass texture): the lighting of the 4.6 renderers (the clusters of lamps, the - // shadows, the reflections) is skipped there, it would be multiplied by an alpha of ~0 + // most of the glass is clear: the lighting of the 4.6 renderers is skipped there, it would be multiplied by an alpha of ~0 if (finalA > 0.002) fragcolor = apply_lights(fragcolor, fragnormal, albedo, reflectivity, specularity, shadow_tone); // thin snow glows when you look towards the sun / a lamp - if (finalA > 0.002 && snowA > 0.001 && snow_translucency > 0.0 && lights_count > 0U) + if ((finalA > 0.002) && (snowA > 0.001) && (snow_translucency > 0.0) && (lights_count > 0U)) { vec3 I = normalize(f_pos.xyz); float shadowSun = 0.0; @@ -685,95 +353,31 @@ void main() shadowSun = (1.0 - shadow_tone) * clamp(calc_shadow(), 0.0, 1.0); float towards = max(dot(I, normalize(-lights[0].dir)), 0.0); float glow = pow(towards, 3.0) * (1.0 - shadowSun); - fragcolor += lights[0].color * lights[0].intensity * glow * snow_translucency * snowTr * albedo * snowA; + fragcolor += lights[0].color * lights[0].intensity * glow * snow_translucency * (snowTr / max(snowA, 1e-3)) * albedo * snowA; } vec3 lit = apply_fog(fragcolor); - -#if SNOW_MATCH_RAIN_GLASS - vec4 color = vec4(lit * finalA, finalA); -#else - vec4 color = vec4(lit, finalA); -#endif + vec4 color = vec4(lit, finalA); // straight, as rain_windscreen of the 4.6 renderers writes the glass out_color = POSTFX_ENABLED ? color : tonemap(color); // the scene seen through the snow, drawn by the post-processing (rain_windscreen_haze.glsl), asked for in the velocity target as - // rain_windscreen asks: thin snow bends it (its relief refracts; x, y = WS_DROP_BIAS + WS_BEND_ENC * bend), elsewhere it's blurred in - // and around thin snow and around the melting spots (x = WS_ENC * strength, y = 0); the snow itself stays sharp. alpha 0 elsewhere: - // the blending keeps the motion of the scene behind + // rain_windscreen asks: the drops bend it (x, y = WS_DROP_BIAS + WS_BEND_ENC * bend), thin snow and a wet film blur it + // (x = WS_ENC * strength, y = 0); the snow itself stays sharp. alpha 0 elsewhere: the blending keeps the motion of the scene behind if (MOTIONBLUR_ENABLED) { - float thin = smoothstep(0.04, 0.20, snowA) * (1.0 - smoothstep(0.55, 0.90, snowA)); - vec4 req = vec4(0.0); - if ((snWet > 0.25) && (snowA < 0.35) && (glassA < 0.5)) + vec4 req = vec4(0.0); + float clear = 1.0 - smoothstep(0.5, 0.95, glassA); + if ((snBendA > 0.25) && (layer.a < 0.3) && (glassA < 0.5)) { - // the water on the glass: its film and its spots bend the picture behind - vec2 bend = clamp(-snWetN * snow_map_wet_bend, vec2(-1.0), vec2(1.0)) * smoothstep(0.25, 0.6, snWet); - req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); - } - else if ((snow_distort > 0.0) && (thin > 0.30) && (glassA < 0.5)) - { - vec2 slope = snowN.xy / max(snowA, 1e-3); - vec2 bend = clamp(-slope * snow_distort, vec2(-1.0), vec2(1.0)) * smoothstep(0.30, 0.60, thin) * (SNOW_REFR_MAXPX / WS_REFR_MAXPX); + vec2 bend = clamp(-snBend / max(snBendA, 1e-3) * snow_drop_bend, vec2(-1.0), vec2(1.0)) * smoothstep(0.25, 0.6, snBendA); req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); } else { - float haze = snHaze * snow_haze * (1.0 - smoothstep(0.30, 0.80, snowA)); // frosted glass in and around thin snow - float blurMask = clamp(max(smear * (1.0 - snowA), haze) * (1.0 - smoothstep(0.5, 0.95, glassA)), 0.0, 1.0); + float blurMask = clamp(snHaze * snow_haze * (1.0 - smoothstep(0.3, 0.8, snowA)) * clear, 0.0, 1.0); if (blurMask >= 0.01) req = vec4(WS_ENC * blurMask, 0.0, 0.0, 1.0); } out_motion = req; } } - -float GetMixFactor(in vec2 co, out float side) { - vec4 movePhase = wiper_pos; - bvec4 is_out = lessThanEqual(movePhase, vec4(1.)); - movePhase = mix(vec4(2.) - movePhase, movePhase, is_out); - - vec4 mask = textureLod(wipermask, co, 0.0); // called from non-uniform flow: no implicit derivatives - - vec4 areaMask = step(.001, mask); - - vec4 maskVal = mix(1. - mask, mask, is_out); - vec4 wipeWidth = smoothstep(1., .9, movePhase) * .25; - vec4 cleaned = smoothstep(movePhase - wipeWidth, movePhase, maskVal) * areaMask; - vec4 side_v = step(maskVal, movePhase); - cleaned *= side_v; - side_v = mix(side_v, vec4(1.) - side_v, is_out); - - // "regeneration", snow gradually returning after a wiper pass (slower than rain, and faster in heavy snowfall): - float regenT = max(mix(snow_regen, snow_regen * 0.6, clamp(rain_params.x, 0.0, 1.0)), 0.5); - vec4 sinceV = vec4(time) - mix(wiper_timer_out, wiper_timer_return, side_v) - vec4(.2); - vec4 regenPhase = clamp(sinceV / vec4(regenT), vec4(0.), vec4(1.)); - - side_v = mix(vec4(0.), vec4(1.) - side_v, areaMask); - - vec4 factor_v = mix(vec4(1.), regenPhase * (vec4(1.) - cleaned), areaMask); - - side = 0.; - float out_factor = 1.; - bool have_side = false; - snWipeSince = 1.0e5; - - // out_factor: the blade that clears the grid cell the most wins (as before). - // side: which wiper stroke the drops of this cell belong to. It is part of the random - // seed of every drop, so it must NOT depend on out_factor. It used to: once the drops had - // fully regrown (out_factor == 1) side fell back to 0 and every drop in the swept area - // jumped to a new position, about one regrow time after each stroke (most visible in - // heavy rain, where regrowth takes ~1 s). - for(int i = 0; i < 4; ++i) - { - out_factor = min(out_factor, factor_v[i]); - if (!have_side && areaMask[i] > 0.) - { - side = side_v[i]; - snWipeSince = max(sinceV[i], 0.0); - have_side = true; - } - } - - return out_factor; -} diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index 183193b69..34b24de40 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -1,50 +1,35 @@ #version 460 core #define STAGE_FRAGMENT 1 #include "common.glsl" -// Windscreen snow: replaces rain_windscreen when it snows - v2 (OpenGL 4.6 / Vulkan 1.4 port of the OpenGL 3.3 v1) -// v2: the syntax of the 4.6 renderers (explicit locations and bindings, #pragma texture / param), the tuning values as constants -// (a uniform can't have a default any more); the blur of the scene and the picture bent by thin snow go to the -// post-processing through the velocity target, as the haze and the drops of rain_windscreen (postfx_taa.frag / -// postfx_motionblur.frag with rain_windscreen_haze.glsl); the colour is written straight -// (not premultiplied) as rain_windscreen of the 4.6 renderers writes the glass; the gloss of the glass from legacy_gloss(); -// no lighting where the glass is clear (no snow, a clear texture). the look and the behaviour of the snow are those of v1. +// Windscreen snow: replaces rain_windscreen when it snows - v3 (OpenGL 4.6 / Vulkan 1.4) // -// MaSzyna switches the weather itself (simulationenvironment.cpp): with Overcast > 1 it rains when the air is warmer -// than 1 deg C and it SNOWS at 1 deg C and below, and the .mat block "snow:" is picked. rain_params.x is the -// precipitation intensity (saturate(Overcast - 1)), exactly what rain_windscreen uses for the drops, so the snow -// on the glass follows the snowfall: nothing without snow, and the harder it snows the more the glass gets plastered. +// MaSzyna switches the weather itself (simulationenvironment.cpp): with Overcast > 1 it SNOWS at 1 deg C and below, and the .mat +// block "snow:" is picked. // -// - flakes: every cell of the glass can hold a flake (atlas tiles 0..2: fluffy, wet lump, crumbs). It lands at a random -// moment, stays white for `snow_hold` seconds and then MELTS for `snow_melt` seconds: the snow fades into a water spot -// (tile 3). About `snow_slide_share` of the melting flakes also SLIDE DOWN the glass, stretching into a drip. -// Only the wet, melting spot blurs the scene (water refracts; dry snow does not, see snow_fresh_blur). -// - clumping: flakes land small and GROW as more snow piles onto them. Where flakes land next to each other they run together -// into one bigger patch (a crusty white film), and the more it snows the more flakes land side by side, so the bigger -// the patches get. The patch exists only where flakes really sit close together; when they melt / slide away it breaks -// up and thins out (snow_clump). -// - wipers (wipermask, GetMixFactor) clear all of it; it builds up again after `snow_regen` seconds (faster in heavy snow). -// Nothing depends on the time since the game started. +// What lies on the glass comes from the simulation (water_snow.comp, water.glsl): the map of the glass keeps the snow, the water, +// how packed the snow is and the shape of its flakes from frame to frame. The flakes land and stay where they landed, pile up, +// the blades push the snow into ridges at the ends of their sweeps and leave a wet trace, it melts at the warm glass, slush slides +// down. The renderer gives the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. // -// Atlas / normalmap (blender_snow_atlas.py), 2 x 2 tiles: -// 0 dry fluffy flake 1 wet compact lump 2 crumbs 3 melted spot (water + ice remnants) +// The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen, two layers of them: +// - the flakes: a sprite on every texel of the map holding snow, the more snow the bigger. Dry: crystals, flakes of a few of +// them, crumbs; wet: lumps; where only the water of a melted flake is left, a drop (it bends the picture behind, as rain does) +// - the layer, under the flakes: a bigger sprite every three texels where the snow is thicker, clumps of flakes, then packed +// snow, overlapping into a whole cover where the snow is thick; grey slush where it's wet +// A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. +// +// Atlas / normalmap (snieg_atlas_maszyna.py), 4 x 4 tiles of 512 x 512 (2048 x 2048): +// 0, 1 star crystals 2 plate 3 needles 4, 5 flakes of a few crystals 6, 7 crumbs +// 8, 9 wet lumps 10, 11 clumps 12, 13 packed snow 14 slush 15 drop +// An older 2 x 2 atlas (1024 x 1024: fluffy flake, wet lump, crumbs, melted spot) still works, its tiles stand in for these. // // .mat: // -// texture_diffuse: dynamic/pkp/vectron_v1/cab/szyby -// texture_raindropsatlas: textures/fx/raindrops-atlas -// texture_normalmap: textures/fx/raindrops_normalmap -// texture_wipermask: dynamic/pkp/vectron_v1/cab/szyby_wipermask -// shader: rain_windscreen -// param_raindrop_grid_size: 150 -// // snow: { // shader: snow_windscreen // texture_raindropsatlas: textures/fx/snow-atlas // texture_normalmap: textures/fx/snow_normalmap -// param_raindrop_grid_size: 70 // } -// -// One cell is about one flake: a grid of ~50-90 gives flakes of ~1-2 cm on a ~1.5 m windscreen. layout(location = 0) in vec3 f_normal; layout(location = 2) in vec2 f_coord; @@ -62,14 +47,14 @@ layout(location = 1) out vec4 out_motion; #pragma texture(diffuse, 0, sRGB_A) #pragma texture(raindropsatlas, 1, sRGB_A) -#pragma texture(wipermask, 2, sRGB_A) -#pragma texture(normalmap, 3, RGBA) // flakes: rg = normal xy, b = height, a = mask; same 2x2 layout as raindropsatlas (linear) +#pragma texture(wipermask, 2, sRGB_A) // the renderer bakes it into the map of the glass (the blades); not read here +#pragma texture(normalmap, 3, RGBA) // rg = normal xy, b = height, a = mask; the layout of raindropsatlas (linear) #pragma param(color, 0, 0, 4, diffuse) #pragma param(diffuse, 1, 0, 1, diffuse) #pragma param(specular, 1, 1, 1, specular) #pragma param(reflection, 1, 2, 1, zero) #pragma param(glossiness, 1, 3, 1, glossiness) -#pragma param(raindrop_grid_size, 2, 0, 1, one) +#pragma param(raindrop_grid_size, 2, 0, 1, one) // not used any more (the map of the glass sets the size of the flakes) // snow_slot: 1 + the slot of the glass in the simulation of the snow (the renderer sets it), 0: none #pragma param(snow_slot, 2, 2, 1, zero) @@ -84,425 +69,122 @@ layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 1) uniform sampler layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 2) uniform sampler2D wipermask; layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 3) uniform sampler2D normalmap; -// --- Tuning ----------------------------------------------------------------- -// Intensity = rain_params.x = saturate(Overcast - 1). The slider range 1.00..2.00 (Overcast) maps to intensity 0..1. The share of flake cells is pow(intensity, 0.8) * snow_gain * snow_density, -// so with the defaults every cell carries a flake from Overcast ~ 1.2 and the film closes the glass at about 1.3 (1.1 = light snow, 1.5+ = blizzard). -const float snow_gain = 1.4; // how fast the glass gets covered when the snowfall gets heavier (higher = already plastered in light snow) -const float snow_density = 0.95; // upper limit of the share of cells that carry a big flake -const float snow_small = 0.80; // same for the layer of small flakes (0 = off) -const float snow_pack = 0.90; // opacity of the patches that form where flakes clump together (0 = no patches) -const float snow_clump = 2.60; // how readily neighbouring flakes run together into one patch (higher = patches form sooner and get bigger) -const float snow_clump_share = 0.55; // share of the flakes that run together into patches; the rest stay separate flakes -const float snow_hold = 40.0; // seconds a flake stays white before it starts to melt (longer in heavy snow) -const float snow_melt = 30.0; // seconds the melting takes (snow fades into a water spot) -const float snow_slide_share = 0.40; // share of the melting flakes that run down the glass -const float snow_slide_len = 2.0; // how far a sliding flake runs, in cells (max 2.4) -const float snow_grow_fast = 5.3; // seconds a patch needs to grow from a clump to a big sheet in the heaviest snowfall -const float snow_grow_slow = 46.7; // same in the lightest snowfall (it still gets there, just much later) -const float snow_haze = 1.0; // blur of the scene behind and around the snow patches (frosted glass), 0 = off, 1 = full (radius: windscreen_view.glsl) -const float snow_distort = 2.0; // picture distortion seen through thin snow (refraction by its relief), 0 = off -const float snow_flake_scale = 2.5; // size of the flakes from the atlas relative to one grid cell (2-3 = two to three times bigger than before; the flakes get fewer) -const float snow_regen = 25.0; // seconds until snow is back on a wiped area (in light snowfall) -const float snow_opacity = 1.0; // overall opacity -const float snow_uv_aspect = 1.0; // glass width / height in the world if the UV is stretched -const float snow_bump = 1.0; // strength of the 3D relief from the normal map, 0 = flat -const float snow_gloss = 0.45; // glints of the sun / headlights on the snow, 0 = matt -const float snow_translucency = 0.8; // glow of thin snow when you look towards the sun / a lamp, 0 = off -const float snow_melt_blur = 0.8; // blur of the scene around the water spots of melting flakes (0 = off, 1 = full) -const float snow_fresh_blur = 0.0; // blur around fresh dry flakes: physically there is none, a little (0.1-0.2) fakes light scattering +// --- tuning ------------------------------------------------------------------------------------------------------------------ +const float snow_flake = 1.2; // size of a flake, texels of the map (grows to 1.6x with the snow of its texel) +const float snow_layer = 0.6; // mm of snow from which the layer starts (clumps), the cover grows to full by 1.5 mm +const float snow_layer_cell = 3.0; // a sprite of the layer every this many texels +const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) +const float snow_thin = 0.45; // opacity of a single thin flake (ice crystals let most of the light through) +const float snow_bump = 1.0; // strength of the relief from the normal map, 0 = flat +const float snow_gloss = 0.45; // glints of the sun / headlights on the snow, 0 = matt +const float snow_translucency = 0.8; // glow of thin snow when you look towards the sun / a lamp, 0 = off +const float snow_haze = 1.0; // blur of the scene behind thin snow (frosted glass), 0 = off +const float snow_drop_bend = 1.0; // how strongly the drops bend the picture behind them +const float snow_wet_blur = 0.6; // blur of the scene behind a wet film -#ifndef SNOW_FLIP_Y -#define SNOW_FLIP_Y 0 // set to 1 if sliding flakes run UP the glass (the glass UV then has v growing downwards) -#endif -const float SNOW_SIZE_MIN = 0.70; // flake size in grid cells (keep max <= 1.8, the search covers 3x3 cells) -const float SNOW_SIZE_MAX = 1.50; -const float SNOW_SLIDER_MAX = 1.10; // a flake that slides is smaller than this (it gets stretched on its way down) -const float SNOW_HALO_SCALE = 1.5; // blur ring radius = flake half-size * this -const float SNOW_LAND_TIME = 1.5; // seconds a flake takes to land and settle -const float SNOW_REFR_MAXPX = 96.0; // the largest picture shift of thin snow, screen pixels -const float WS_REFR_MAXPX = 96.0; // the largest picture shift the post-processing makes, screen pixels; must match rain_windscreen_haze.glsl -const float WS_BEND_ENC = 60.0; // the bend request in the velocity target; must match rain_windscreen_haze.glsl +const float WS_REFR_MAXPX = 96.0; // the largest picture shift the post-processing makes, screen pixels; as rain_windscreen_haze.glsl +const float WS_BEND_ENC = 60.0; // the bend request in the velocity target; as rain_windscreen_haze.glsl const float WS_DROP_BIAS = 192.0; -const float WS_ENC = 64.0; // the haze request in the velocity target; must match rain_windscreen_haze.glsl -const float SNOW_REFR_MIX = 0.85; // 0 = no refraction, 1 = only the bent picture +const float WS_ENC = 64.0; // the haze request in the velocity target; as rain_windscreen_haze.glsl -#ifndef SNOW_MATCH_RAIN_GLASS -#define SNOW_MATCH_RAIN_GLASS 0 // 4.6: rain_windscreen writes the glass straight, not premultiplied -#endif +const float SNOW_FRESH = 0.1; // water in a mm of fresh snow, mm (as water_snow.comp) +const float SNOW_PACKED = 0.4; // and of packed snow -float snHaze = 0.0; // set by snowFilm: 1 inside / next to a snow patch (drives the frosted-glass blur) -float snWipeSince = 1.0e5; // set by GetMixFactor: seconds since the wiper last cleaned this spot -float GetMixFactor(in vec2 co, out float side); +// tiles of the atlas +const int TILE_DROP = 15; -const float SNOW_MERGE_R = 2.0; // reach of a flake's 'snow mass' in flake half-sizes (flakes closer than this run together) -const float SNOW_CLUMP_THR = 0.80; // summed mass above which the glass is covered +int snSlot = 0; +uint snMap = 0u; +bool snBig = true; // a 4 x 4 atlas (else the older 2 x 2) +float snHaze = 0.0; // the picture behind is blurred (thin snow, a wet film) +vec2 snBend = vec2(0.0); // the drops bend the picture behind (their normals, weighted) +float snBendA = 0.0; -float snHash(vec2 p) +struct sprite_acc { - return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); + vec3 rgb; // premultiplied + float a; + vec3 n; // premultiplied, tangent space + float tr; // translucency, premultiplied +}; + +// the corner of a tile in the atlas; an older 2 x 2 atlas stands its four tiles in for the sixteen +vec2 snTile(int tile) +{ + if (snBig) + return vec2(float(tile % 4), float(tile / 4)) * 0.25; + int old = 0; // a fluffy flake + if ((tile == 6) || (tile == 7)) + old = 2; // crumbs + else if ((tile >= 8) && (tile != 10) && (tile != 11) && (tile != TILE_DROP)) + old = 1; // a wet lump + else if (tile == TILE_DROP) + old = 3; // a melted spot + return vec2(float(old % 2), float(old / 2)) * 0.5; } -float snNoise(vec2 p) +float snTileSize() { - vec2 i = floor(p); - vec2 f = fract(p); - f = f * f * (3.0 - 2.0 * f); - return mix(mix(snHash(i), snHash(i + vec2(1.0, 0.0)), f.x), - mix(snHash(i + vec2(0.0, 1.0)), snHash(i + vec2(1.0, 1.0)), f.x), f.y); + return snBig ? 0.25 : 0.5; } -float snFbm(vec2 p) +// a sprite over the accumulator: Local the place in it (0 .. 1), Rot its rotation (cos, sin), Tone its colour +void snSprite(vec2 local, int tile, float alpha, vec3 tone, vec2 rot, float flip, float lod, float bump, inout sprite_acc acc) { - float a = 0.5; - float v = 0.0; - for (int i = 0; i < 4; ++i) - { - v += a * snNoise(p); - p = p * 2.07 + vec2(17.3, 9.1); - a *= 0.5; - } - return v / 0.9375; -} - -// One flake in one cell. `age` = seconds since it landed. -void snowFlake(vec2 ncell, uint seed, float age, float gridSize, float pixelUV, vec2 aspect, - float sizeMul, float opacityMul, float hold, float meltT, float slideShare, - inout vec3 accRGB, inout float accA, inout float smear, - inout vec3 accN, inout float accTr, inout float accM) -{ - float mt = clamp((age - hold) / meltT, 0.0, 1.0); // 0 = dry, 1 = melted away - float melt = smoothstep(0.0, 1.0, mt); - float fade = 1.0 - smoothstep(0.75, 1.0, mt); // the water spot dries up at the very end - float land = smoothstep(0.0, 0.3, age); // it lands at once (no ghostly fade-in): it just starts small - - float jx = RandF(seed); - float jy = RandF(seed); - vec2 center = (ncell + vec2(jx, jy)) / gridSize; - - float rs = RandF(seed); - float ang = RandF(seed) * 6.2831853; - float flipX = (RandF(seed) < 0.5) ? -1.0 : 1.0; - float kind = RandF(seed); - float tone = mix(0.94, 1.04, RandF(seed)); - bool slider = RandF(seed) < slideShare; - float slideLen = mix(0.8, 1.0, RandF(seed)) * min(snow_slide_len, 2.4) / gridSize; - bool clumper = RandF(seed) < snow_clump_share; // this flake sticks to its neighbours (else it stays on its own) - float aniso = mix(0.62, 1.0, RandF(seed)); // flakes are never round: random squash after rotation - - float szMax = slider ? SNOW_SLIDER_MAX : SNOW_SIZE_MAX; - float size = mix(SNOW_SIZE_MIN, szMax, rs * rs) / gridSize * sizeMul * mix(0.45, 1.0, smoothstep(0.0, max(hold * 0.25, 1.0), age)) * mix(1.0, 0.85, melt); // grows as snow piles onto it - - // a sliding flake runs down while it melts and stretches into a drip - float slideP = slider ? smoothstep(0.05, 1.0, mt) : 0.0; -#if SNOW_FLIP_Y - center.y += slideLen * slideP * slideP; -#else - center.y -= slideLen * slideP * slideP; -#endif - float stretchY = 1.0 + 0.9 * slideP; - - vec2 d = (f_coord - center) * aspect; - d.y /= stretchY; - - // the 'snow mass' of this flake: neighbouring flakes add up, and where the sum is high they have run into one patch - { - float kr = min(size * 0.5 * SNOW_MERGE_R, 1.0 / gridSize); // (1 cell: the search only covers the 3x3 cells around the pixel) - float m = 1.0 - smoothstep(0.0, kr, length(d)); - if (clumper) - accM += m * m * (3.0 - 2.0 * m) * (1.0 - 0.6 * melt) * snow_clump * land; - } - - // blur only around the water of a melting flake (and, optionally, a little around fresh ones) - float haloR = size * 0.5 * SNOW_HALO_SCALE; - float dist = length(d); - if (dist < haloR) - { - float ring = 1.0 - smoothstep(0.35 * haloR, haloR, dist); - smear = max(smear, ring * land * (melt * snow_melt_blur + (1.0 - melt) * snow_fresh_blur)); - } - - float c = cos(ang); - float s = sin(ang); - vec2 r = vec2(c * d.x + s * d.y, -s * d.x + c * d.y); - r.x *= flipX / aniso; - - vec2 local = r / size + 0.5; - if (any(lessThan(local, vec2(0.0))) || any(greaterThan(local, vec2(1.0)))) + vec2 uv = snTile(tile) + local * snTileSize(); + vec4 t = textureLod(raindropsatlas, uv, lod); + vec4 n = textureLod(normalmap, uv, lod); + float a = clamp(t.a * alpha, 0.0, 1.0); + if (a <= 0.002) return; - - float lod = clamp(log2(max(pixelUV / size * 0.5 * float(textureSize(raindropsatlas, 0).x), 1.0)), 0.0, 4.0); - - // dry flake (tiles 0..2: fluffy, wet lump, crumbs) and, while melting, its water spot (tile 3) - vec2 off0 = (kind < 0.40) ? vec2(0.0, 0.5) : ((kind < 0.72) ? vec2(0.5, 0.5) : vec2(0.0, 0.0)); - vec2 off3 = vec2(0.5, 0.0); - vec4 t0 = textureLod(raindropsatlas, off0 + local * 0.5, lod); - vec4 n0 = textureLod(normalmap, off0 + local * 0.5, lod); - float a0 = t0.a * (1.0 - melt); - float a3 = 0.0; - vec4 t3 = vec4(0.0); - vec4 n3 = vec4(0.5, 0.5, 0.0, 0.0); - if (melt > 0.001) - { - t3 = textureLod(raindropsatlas, off3 + local * 0.5, lod); - n3 = textureLod(normalmap, off3 + local * 0.5, lod); - a3 = t3.a * smoothstep(0.0, 0.5, melt) * fade; - } - - float aSum = a0 + a3; - float a = clamp(aSum * land * snow_opacity * opacityMul, 0.0, 1.0); - if (a <= 0.0) - return; - vec3 col = (t0.rgb * a0 + t3.rgb * a3) / max(aSum, 1e-4); - vec2 nxy = ((n0.rg * 2.0 - 1.0) * a0 + (n3.rg * 2.0 - 1.0) * a3) / max(aSum, 1e-4); - nxy *= snow_bump * land; - nxy.x *= flipX; - vec2 nuv = vec2(c * nxy.x - s * nxy.y, s * nxy.x + c * nxy.y); - vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); - - // thin snow lets light through: the dry part is translucent, the water spot is not - float tr = (a0 / max(aSum, 1e-4)) * (1.0 - t0.a * 0.55); - - accRGB = col * tone * a + accRGB * (1.0 - a); - accN = nT * a + accN * (1.0 - a); - accTr = tr * a + accTr * (1.0 - a); - accA = a + accA * (1.0 - a); -} - -// Adds one layer of flakes to the premultiplied accumulators. Same scheme as the drops of rain_windscreen: -// the cells around the pixel (a few more above it, for the flakes that slide down), the wipers decide per cell whether it -// is clear, the precipitation intensity decides whether the cell carries a flake right now. -void snowLayer(float gridSize, float density, uint layerSeed, float sizeMul, float opacityMul, float slideShare, int rowsUp, - float pixelUV, vec2 aspect, - inout vec3 accRGB, inout float accA, inout float smear, - inout vec3 accN, inout float accTr, inout float accM) -{ - vec2 cell = floor(f_coord * gridSize); - float heavy = clamp(rain_params.x, 0.0, 1.0); - float hold = snow_hold * (1.0 + 1.5 * heavy); // in heavy snow there is no time to melt - float meltT = max(snow_melt, 1.0); - float life = hold + meltT; - float occupancy = mix(0.70, 0.97, heavy); // share of the time a cell holds a flake - float cycBase = life / occupancy; - float share = clamp(pow(rain_params.x, 0.8) * snow_gain, 0.0, 1.0) * density; - - // flakes slide upwards in UV if SNOW_FLIP_Y: search the rows on the other side -#if SNOW_FLIP_Y - int oyMin = -1 - rowsUp; - int oyMax = 1; -#else - int oyMin = -1; - int oyMax = 1 + rowsUp; -#endif - - for (int oy = oyMin; oy <= oyMax; oy++) { - for (int ox = -1; ox <= 1; ox++) { - - vec2 ncell = cell + vec2(float(ox), float(oy)); - uvec2 ucell = uvec2(ivec2(ncell)); - - float side; - float mixFactor = GetMixFactor((ncell + 0.5) / gridSize, side); - - // timing of this cell: the same in every round - uint tseed = Hash(uvec3(ucell, layerSeed + 31u)); - float cyc = cycBase * (1.0 + mix(0.45, 0.03, heavy) * RandF(tseed)); // in heavy snow the cells hardly ever stand empty - float tOff = RandF(tseed) * cyc; - float patchMul = mix(0.7, 1.3, RandF(tseed)); - float tl = time + tOff; - float rnd = floor(tl / cyc); - float age = tl - rnd * cyc; // seconds since this round's flake landed - if (age > life) - continue; - - // a new flake (position, shape, size) every round; the wiper stroke is part of the seed, as in the rain - uint seed = Hash(uvec3(ucell, layerSeed + uint(side) * 7919u + uint(max(rnd, 0.0)) * 2654435u)); - - if (mixFactor < RandF(seed)) - continue; // wiped / still regrowing - - float activate = RandF(seed); - if (activate > share * patchMul) - continue; - - snowFlake(ncell, seed, age, gridSize, pixelUV, aspect, sizeMul, opacityMul, hold, meltT, slideShare, - accRGB, accA, smear, accN, accTr, accM); - } - } -} - -// Snow patches: a crusty white sheet with the structure of real snow (lumps, grain, thin translucent edges, holes). -// WHERE it grows is decided by the flakes: the 'snow mass' of the flakes that stick together (accM) pushes the sheet up, so a patch starts -// where several flakes landed close to each other, spreads from there in an irregular shape and keeps growing while more flakes land -// next to it; when they melt or slide away it breaks up into holes. It is drawn UNDER the flakes. -// Snow patches built from 'pach pach pach' accretion: every big cell carries a patch that is a heap of 22 small clumps (about flake sized). -// The clumps pop up one after another (the ones near the middle first, so the patch spreads outwards) and each lands at once, as a ragged -// piece that merges with the pieces already there. How fast that goes depends on the snowfall intensity (growT); left alone the pieces -// overlap into a closed sheet. Regions of the glass start at different moments. Returns f > 0 inside the snow (f = depth in sheet cells). -float snowSheetField(float gridSize) -{ - float sg = gridSize * 0.19; - vec2 pg = f_coord * sg; - vec2 cell = floor(pg); - float heavy = clamp(rain_params.x, 0.0, 1.0); - float growT = mix(snow_grow_slow, snow_grow_fast, pow(heavy, 0.5)); - float hold = snow_hold * (1.0 + 1.5 * heavy); - float meltT = max(snow_melt, 1.0); - float life = growT + hold + meltT; - float occupancy = mix(0.80, 0.97, heavy); - float cycBase = life / occupancy; - float share = clamp(heavy * 1.6, 0.0, 1.0) * 0.95 + 0.05 * heavy; // share of the cells that carry a patch (1.0 = none, ~1.6 = nearly all) - - // wiper: pixel precise. The sheet at a pixel is no older than the last wipe of that pixel. - float sidePx; - float mixPx = GetMixFactor(f_coord, sidePx); - float wipeAgePx = snWipeSince; - - float acc = 0.0; // summed clump kernels (metaballs): touching clumps merge, no scalloped circles - for (int oy = -1; oy <= 1; oy++) { - for (int ox = -1; ox <= 1; ox++) { - vec2 ncell = cell + vec2(float(ox), float(oy)); - uvec2 ucell = uvec2(ivec2(ncell)); - - uint tseed = Hash(uvec3(ucell, 211u)); - float cyc = cycBase * (1.0 + mix(0.45, 0.03, heavy) * RandF(tseed)); - float tOff = RandF(tseed) * cyc; - float tl = time + tOff; - float rnd = floor(tl / cyc); - float age = tl - rnd * cyc; - if (age > life) - continue; - - uint seed = Hash(uvec3(ucell, 223u + uint(sidePx) * 7919u + uint(max(rnd, 0.0)) * 2654435u)); - if (RandF(seed) > share) - continue; - - vec2 c = ncell + vec2(0.1 + 0.8 * RandF(seed), 0.1 + 0.8 * RandF(seed)); - vec2 dc = pg - c; - if (dot(dc, dc) > 1.2 * 1.2) - continue; // too far from this patch to be touched by any of its clumps - - age = min(age, wipeAgePx); - float delay = snNoise(c * 0.30 + 3.7) * growT * 0.35; // regions of the glass start at different moments - float ga = max(age - delay, 0.0); - float mt = clamp((age - growT - hold) / meltT, 0.0, 1.0); - float shrink = 1.0 - 1.1 * mt * mt; // melting: the clumps shrink and holes open - - for (int i = 0; i < 22; i++) { - uint bs = Hash(uvec3(seed, uint(i), 977u)); - float rho = RandF(bs); - float an = RandF(bs) * 6.2831853; - float rad = 0.85 * sqrt(rho); - vec2 bp = c + rad * vec2(cos(an), sin(an)); - float rb = mix(0.17, 0.30, RandF(bs)); - float ti = growT * (0.03 + 0.97 * pow(rad / 0.85, 0.9) * mix(0.70, 1.0, RandF(bs))); // inner clumps first - // each clump arrives in three small portions (pop, pop, pop): 45% -> 72% -> 100% of its size, no fading - float dT = growT * 0.10; - float stg = step(ti, ga) + step(ti + dT, ga) + step(ti + 2.0 * dT, ga); // 0..3 - if (stg <= 0.0) - continue; - float rr = rb * shrink * (stg < 1.5 ? 0.45 : (stg < 2.5 ? 0.72 : 1.0)); - float kd = max(1.0 - length(pg - bp) / max(rr * 1.35, 1e-3), 0.0); - acc += kd * kd * (3.0 - 2.0 * kd); - } - } - } - // torn, crumbly edge: fine noise (features about a flake wide) decides where the summed clumps stop, so the outline is irregular - // snow and not a ring of circles - float nz = snFbm(pg * 5.5 + 13.0) * 0.45 + snFbm(pg * 13.0 + 7.0) * 0.35 + snFbm(pg * 31.0 + 3.0) * 0.20 - 0.5; - float best = (acc - 0.50) * 0.20 + nz * 0.30; - best -= (1.0 - smoothstep(0.0, 0.12, mixPx)) * 1.0; // swept (or still regrowing) areas - return best; -} - -void snowFilm(float gridSize, inout vec3 accRGB, inout float accA, inout vec3 accN, inout float accTr) -{ -#if SNOW_FLIP_Y - float dir = -1.0; -#else - float dir = 1.0; -#endif - float sf = snowSheetField(gridSize); - snHaze = max(snHaze, smoothstep(-0.045, 0.0, sf)); // the glass next to a patch is frosted a little as well - float cover = smoothstep(0.0, 0.03, sf); - if (cover <= 0.002) - return; - float thick = smoothstep(0.0, 0.11, sf); // 0 at the thin edge, 1 in the thick middle - vec2 p = f_coord * gridSize * 0.17 + vec2(0.0, dir * time * 0.008); - vec2 q = f_coord * gridSize * 2.6; - float h0 = snFbm(p); - - // lumpy surface: big drifts + fine grain - float f1 = snFbm(q); - float e = 0.06; - float ef = 0.05; - vec2 g = vec2(snFbm(p + vec2(e, 0.0)) - h0, snFbm(p + vec2(0.0, e)) - h0) / e; - vec2 gf = vec2(snFbm(q + vec2(ef, 0.0)) - f1, snFbm(q + vec2(0.0, ef)) - f1) / ef; - vec3 nT = normalize(vec3(-(g * 0.55 + gf * 0.20) * snow_bump, 1.0)); - - vec3 thin = vec3(0.66, 0.72, 0.80); // thin snow is greyish-blue and lets the dark background through - vec3 full = vec3(0.93, 0.95, 0.98); - vec3 col = mix(thin, full, thick) * (0.62 + 0.55 * f1) * (0.88 + 0.22 * snNoise(f_coord * gridSize * 9.0)) * (0.85 + 0.3 * h0); - float a = clamp(cover * mix(0.50, 0.96, thick) * snow_pack * snow_opacity, 0.0, 0.97); - float under = 1.0 - accA; - accRGB = accRGB + col * a * under; - accN = accN + nT * a * under; - accTr = accTr + mix(0.60, 0.30, thick) * a * under; - accA = accA + a * under; -} - -// --- The snow of the simulation (water_snow.comp): the map of the glass --------------------------------------------------- -// When the renderer simulates the snow of the glass (the param snow_slot holds 1 + its slot), the snow, the water, how packed the -// snow is and the shape of its flakes come from the map of the glass (water.glsl), which keeps them from frame to frame: the flakes -// land and stay where they landed, pile up into a layer, the blades push it into ridges at the ends of their sweeps and leave a wet -// trace, it melts at the warm glass and slush slides down. Here it's only drawn: -// - a texel of the map with a little snow is a flake (atlas tiles 0..2: fluffy when dry, a wet lump when wet or packed, crumbs), -// the more snow the bigger; with mostly water left it's the water spot (tile 3) -// - where the snow is thicker it's a layer: its edge torn by the grain of the snow, as opaque as it's thick (Beer-Lambert), grey -// and translucent when wet (slush), smoother and denser when packed; its relief from the slopes of the snow of the map -// - the water: wet glass bends the picture behind (the post-processing), the thin snow hazes it -// Without the simulation (an older renderer, no compute) the procedural snow below draws the glass as before. -const float snow_map_flake = 1.15; // size of a flake relative to a texel of the map (the snow of a texel) -const float snow_map_layer = 1.0; // mm of snow above which the flakes run together into a layer -const float snow_map_opaque = 1.8; // mm of fresh snow which lets 1/e of the light through (packed: half of it) -const float snow_map_relief = 0.6; // how much the slopes of the snow tilt its surface -const float snow_map_grain = 0.35; // the fine grain of the layer (its relief) -const float snow_map_wet_bend = 0.6; // how strongly a wet glass bends the picture behind it -const float snow_map_thin = 0.45; // opacity of a single thin flake (ice crystals let most of the light through: the picture - // behind shows through it, blurred, rather than a dark speck at night) - -int snMapSlot = -1; -uint snMapIndex = 0u; -float snWet = 0.0; // set by snowMapped: the film of water (0 .. 1) -vec2 snWetN = vec2(0.0); // set by snowMapped: the slope of the water, for the bend of the picture - -// the snow of the map at a place of the glass -vec4 snMapAt(vec2 uv) -{ - return water_snow_at(uint(snMapSlot), snMapIndex, uv); -} - -// a flake of the map drawn over the accumulators: Local the place in its sprite (0 .. 1), Tile the corner of its tile in the atlas -void snowMapSprite(vec2 local, vec2 tile, float alpha, float tone, float flip, float c, float s, float lod, - inout vec3 accRGB, inout float accA, inout vec3 accN, inout float accTr) -{ - vec4 t = textureLod(raindropsatlas, tile + local * 0.5, lod); - vec4 n = textureLod(normalmap, tile + local * 0.5, lod); - float a = clamp(t.a * alpha * snow_opacity, 0.0, 1.0); - if (a <= 0.0) - return; - vec2 nxy = (n.rg * 2.0 - 1.0) * snow_bump; + vec2 nxy = (n.rg * 2.0 - 1.0) * snow_bump * bump; nxy.x *= flip; - vec2 nuv = vec2(c * nxy.x - s * nxy.y, s * nxy.x + c * nxy.y); - vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); - float tr = (1.0 - t.a * 0.55); - accRGB = t.rgb * tone * a + accRGB * (1.0 - a); - accN = nT * a + accN * (1.0 - a); - accTr = tr * a + accTr * (1.0 - a); - accA = a + accA * (1.0 - a); + vec2 nuv = vec2(rot.x * nxy.x - rot.y * nxy.y, rot.y * nxy.x + rot.x * nxy.y); + vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); + acc.rgb = t.rgb * tone * a + acc.rgb * (1.0 - a); + acc.n = nT * a + acc.n * (1.0 - a); + acc.tr = (1.0 - t.a * 0.55) * a + acc.tr * (1.0 - a); + acc.a = a + acc.a * (1.0 - a); + if (tile == TILE_DROP) + { + snBend = snBend * (1.0 - a) + nuv * a; + snBendA = snBendA * (1.0 - a) + a; + } } -// the flakes of the texels around the pixel -void snowMapFlakes(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float accA, inout vec3 accN, inout float accTr) +// where in a sprite the pixel is: P the pixel and C the centre of the sprite, in the units of its grid (the size of the sprite +// in them), Aspect the cells as they lie on the glass; false outside the sprite +bool snLocal(vec2 p, vec2 c, float size, vec2 aspect, vec2 rot, float flip, float aniso, out vec2 local) +{ + vec2 d = (p - c) * aspect; + vec2 r = vec2(rot.x * d.x + rot.y * d.y, -rot.y * d.x + rot.x * d.y); + r.x *= flip / aniso; + local = r / size + 0.5; + return all(greaterThanEqual(local, vec2(0.0))) && all(lessThanEqual(local, vec2(1.0))); +} + +float snLod(float pixelUV, float sizeUV) +{ + float tilePx = float(textureSize(raindropsatlas, 0).x) * snTileSize(); + return clamp(log2(max(pixelUV / sizeUV * tilePx, 1.0)), 0.0, 6.0); +} + +// how wet the snow of a state of the map is (0 dry .. 1 slush) +float snWetness(vec4 q) +{ + return q.y / (q.y + q.x * mix(SNOW_FRESH, SNOW_PACKED, q.z) + 1e-4); +} + +// the tone of the snow: grey and darker when wet (slush), a little grey when packed +vec3 snTone(vec4 q, float random) +{ + vec3 tone = vec3(mix(0.94, 1.04, random)); + tone *= mix(vec3(1.0), vec3(0.95, 0.96, 0.98), q.z); + return tone * mix(vec3(1.0), vec3(0.78, 0.83, 0.88), smoothstep(0.3, 0.8, snWetness(q))); +} + +// the flakes: a sprite on every texel holding snow (a drop where only its water is left) +void snFlakes(vec2 aspect, float pixelUV, inout sprite_acc acc) { vec2 p = f_coord * float(WATER_MAP); ivec2 here = ivec2(floor(p)); @@ -511,101 +193,95 @@ void snowMapFlakes(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float ac for (int ox = -1; ox <= 1; ++ox) { ivec2 texel = here + ivec2(ox, oy); - vec4 q = water_snow_texel(uint(snMapSlot), snMapIndex, texel); - float density = mix(0.1, 0.4, q.z); - float wet = q.y / (q.y + q.x * density + 1e-4); - bool spot = (q.x < 0.05) && (q.y > 0.03); // a flake melted into its water - if ((q.x < 0.05) && (false == spot)) + vec4 q = water_snow_texel(uint(snSlot), snMap, texel); + bool drop = (q.x < 0.05) && (q.y > 0.03); + if ((q.x < 0.05) && (false == drop)) continue; - uint seed = Hash(uvec3(uvec2(texel), uint(q.w * 65535.0) + 7u * uint(snMapSlot))); - // the water of a texel is a droplet only now and then: the more water the more of them - if (spot && (RandF(seed) > smoothstep(0.03, 0.2, q.y))) + uint seed = Hash(uvec3(uvec2(texel), uint(q.w * 65535.0) + 7u * uint(snSlot))); + // the water of a texel is a drop only now and then: the more water the more of them + if (drop && (RandF(seed) > smoothstep(0.03, 0.2, q.y))) continue; - vec2 center = vec2(texel) + vec2(0.15 + 0.7 * RandF(seed), 0.15 + 0.7 * RandF(seed)); + vec2 centre = vec2(texel) + 0.2 + 0.6 * vec2(RandF(seed), RandF(seed)); float ang = RandF(seed) * 6.2831853; + vec2 rot = vec2(cos(ang), sin(ang)); float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; float kind = RandF(seed); - float tone = mix(0.94, 1.04, RandF(seed)); - float aniso = mix(0.62, 1.0, RandF(seed)); - // the more snow the texel holds the bigger the flake (a lump of a few flakes) - float size = snow_map_flake * mix(0.6, 1.0, RandF(seed)) * (spot ? mix(0.5, 1.1, smoothstep(0.03, 0.3, q.y)) - : mix(0.7, 1.6, smoothstep(0.05, 2.0, q.x))); - vec2 d = (p - center) * aspect; - float c = cos(ang); - float s = sin(ang); - vec2 r = vec2(c * d.x + s * d.y, -s * d.x + c * d.y); - r.x *= flip / aniso; - vec2 local = r / size + 0.5; - if (any(lessThan(local, vec2(0.0))) || any(greaterThan(local, vec2(1.0)))) + float random = RandF(seed); + float size = snow_flake * mix(0.75, 1.0, RandF(seed)) + * (drop ? mix(0.5, 1.0, smoothstep(0.03, 0.3, q.y)) : mix(0.8, 1.6, smoothstep(0.05, 1.5, q.x))); + vec2 local; + if (false == snLocal(p, centre, size, aspect, rot, flip, 1.0, local)) continue; - float sizeUV = size / float(WATER_MAP); - float lod = clamp(log2(max(pixelUV / sizeUV * 0.5 * float(textureSize(raindropsatlas, 0).x), 1.0)), 0.0, 4.0); - vec2 tile; - if (spot) - tile = vec2(0.5, 0.0); - else if ((wet > 0.3) || (q.z > 0.5) || (kind < 0.30)) - tile = vec2(0.5, 0.5); // a wet lump - else if (kind < 0.75) - tile = vec2(0.0, 0.5); // fluffy + int tile; + float alpha; + if (drop) + { + tile = TILE_DROP; + alpha = smoothstep(0.03, 0.1, q.y); + } else - tile = vec2(0.0, 0.0); // crumbs - float alpha = spot ? smoothstep(0.03, 0.1, q.y) : smoothstep(0.05, 0.25, q.x) * mix(snow_map_thin, 1.0, smoothstep(0.3, 2.5, q.x)); - snowMapSprite(local, tile, alpha, tone, flip, c, s, lod, accRGB, accA, accN, accTr); + { + if (snWetness(q) > 0.35) + tile = 8 + int(kind * 2.0); // wet lumps + else if (kind < 0.25) + tile = int(kind * 8.0); // star crystals (0, 1) + else if (kind < 0.35) + tile = 2; // a plate + else if (kind < 0.45) + tile = 3; // needles + else if (kind < 0.80) + tile = 4 + int((kind - 0.45) / 0.35 * 2.0); // flakes of a few crystals + else + tile = 6 + int((kind - 0.80) / 0.2 * 2.0); // crumbs + tile = min(tile, 9); + alpha = smoothstep(0.05, 0.25, q.x) * mix(snow_thin, 1.0, smoothstep(0.3, 2.5, q.x)); + } + snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / float(WATER_MAP)), 1.0, acc); } } } -// the snow of the map at the pixel: the flakes, the layer of the snow under them, the water, the haze -void snowMapped(vec2 aspect, float pixelUV, inout vec3 accRGB, inout float accA, inout float smear, inout vec3 accN, inout float accTr) +// the layer: a bigger sprite every few texels where the snow is thicker, clumps and then packed snow, overlapping into a cover +void snLayer(vec2 aspect, float pixelUV, inout sprite_acc acc) { - vec4 q = snMapAt(f_coord); - float e = 1.0 / float(WATER_MAP); - vec4 qr = snMapAt(f_coord + vec2(e, 0.0)); - vec4 ql = snMapAt(f_coord - vec2(e, 0.0)); - vec4 qu = snMapAt(f_coord + vec2(0.0, e)); - vec4 qd = snMapAt(f_coord - vec2(0.0, e)); - float around = (q.x + qr.x + ql.x + qu.x + qd.x) * 0.2; - - // the flakes of thin snow and the water spots; the picture behind a flake is blurred (it scatters the light going through) - snowMapFlakes(aspect, pixelUV, accRGB, accA, accN, accTr); - snHaze = max(snHaze, smoothstep(0.0, 0.3, accA)); - - // the water: the film bends the picture behind - snWet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); - snWetN = vec2(qr.y - ql.y, qu.y - qd.y) * 2.0 + (vec2(snNoise(f_coord * 900.0), snNoise(f_coord * 900.0 + 31.0)) - 0.5) * 0.6 * snWet; - smear = max(smear, snWet * snow_melt_blur * 0.6); - // thin snow hazes the picture around it - snHaze = max(snHaze, smoothstep(0.15, 1.0, around)); - - // the layer, where the snow has run together - vec2 gp = f_coord * float(WATER_MAP) * aspect; - float grain = snFbm(gp * 0.9 + 3.0) * 0.55 + snFbm(gp * 2.7 + 11.0) * 0.30 + snFbm(gp * 7.1 + 5.0) * 0.15; - float edge = (q.x - snow_map_layer) / max(snow_map_layer, 1e-3) + (grain - 0.5) * 1.6; - float cover = smoothstep(0.0, 0.35, edge); - if (cover <= 0.002) - return; - float density = mix(0.1, 0.4, q.z); - float wet = q.y / (q.y + q.x * density + 1e-4); - float opaque = snow_map_opaque * mix(1.0, 0.5, q.z); - float thick = 1.0 - exp(-q.x / opaque); - // the relief: the slopes of the snow of the map (ridges, the edges of the swept arcs) and the grain of the fresh snow - vec2 slope = vec2(qr.x - ql.x, qu.x - qd.x) * 0.5 * snow_map_relief; - float f1 = snFbm(gp * 3.3); - float ef = 0.05; - vec2 gf = vec2(snFbm(gp * 3.3 + vec2(ef, 0.0)) - f1, snFbm(gp * 3.3 + vec2(0.0, ef)) - f1) / ef; - vec3 nT = normalize(vec3(-(slope + gf * snow_map_grain * (1.0 - 0.6 * q.z)) * snow_bump, 1.0)); - - vec3 fresh = vec3(0.93, 0.95, 0.98); - vec3 packed = vec3(0.89, 0.91, 0.94); - vec3 slush = vec3(0.60, 0.66, 0.73); - vec3 col = mix(mix(fresh, packed, q.z), slush, smoothstep(0.2, 0.7, wet)); - col *= (0.80 + 0.30 * f1 * (1.0 - 0.5 * q.z)) * (0.92 + 0.12 * grain); - float a = clamp(cover * mix(0.35, 0.97, thick) * mix(1.0, 0.75, smoothstep(0.3, 0.8, wet)) * snow_pack * snow_opacity, 0.0, 0.97); - float under = 1.0 - accA; - accRGB = accRGB + col * a * under; - accN = accN + nT * a * under; - accTr = accTr + mix(0.60, 0.25, thick) * a * under; - accA = accA + a * under; + float cells = float(WATER_MAP) / snow_layer_cell; + vec2 p = f_coord * cells; + ivec2 here = ivec2(floor(p)); + for (int oy = -1; oy <= 1; ++oy) + { + for (int ox = -1; ox <= 1; ++ox) + { + ivec2 cell = here + ivec2(ox, oy); + uint seed = Hash(uvec3(uvec2(cell + 4096), 31u + 7u * uint(snSlot))); + vec2 centre = vec2(cell) + 0.3 + 0.4 * vec2(RandF(seed), RandF(seed)); + vec4 q = water_snow_at(uint(snSlot), snMap, centre / cells); + float present = smoothstep(snow_layer, snow_layer * 2.5, q.x); + if (RandF(seed) >= present) + continue; + float ang = RandF(seed) * 6.2831853; + vec2 rot = vec2(cos(ang), sin(ang)); + float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; + float kind = RandF(seed); + float random = RandF(seed); + float aniso = mix(0.8, 1.0, RandF(seed)); + float size = mix(1.25, 2.0, smoothstep(snow_layer, 4.0, q.x)) * mix(0.85, 1.0, RandF(seed)); + vec2 local; + if (false == snLocal(p, centre, size, aspect, rot, flip, aniso, local)) + continue; + int tile; + if (snWetness(q) > 0.45) + tile = 14; // slush + else if (q.x < 3.0) + tile = 10 + int(kind * 2.0); // clumps + else + tile = 12 + int(kind * 2.0); // packed snow + float thick = 1.0 - exp(-q.x / (snow_opaque * mix(1.0, 0.5, q.z))); + float alpha = mix(0.6, 1.0, thick); + // the ridges of the blades: packed and thick, a stronger relief + float bump = mix(1.0, 1.6, q.z * smoothstep(3.0, 12.0, q.x)); + snSprite(local, min(tile, 14), alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / cells), bump, acc); + } + } } void main() @@ -625,39 +301,32 @@ void main() Bgl *= invmax; vec4 tex_color = texture(diffuse, f_coord); // no discard: clean glass between faint dirt must still get snow and blur + float pixelUV = max(length(duv1), length(duv2)); + snBig = (textureSize(raindropsatlas, 0).x >= 2048); - float gridSize = max(ceil(param[2].x), 1.0); - float pixelUV = max(length(dFdx(f_coord)), length(dFdy(f_coord))); - snHaze = 0.0; - vec2 aspect = (snow_uv_aspect >= 1.0) ? vec2(snow_uv_aspect, 1.0) : vec2(1.0, 1.0 / max(snow_uv_aspect, 0.01)); - - vec3 snowRGB = vec3(0.0); // premultiplied - float snowA = 0.0; - float smear = 0.0; - vec3 snowN = vec3(0.0); - float snowTr = 0.0; - // the snow of the simulation where the glass has a map of it, else made up as before - snMapSlot = int(param[2].z + 0.5) - 1; - bool mapped = (snMapSlot >= 0) && (snMapSlot < WATER_SLOTS) && water_snow_map(uint(snMapSlot), snMapIndex); - if (mapped) + sprite_acc layer = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + sprite_acc flakes = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + float wet = 0.0; + snSlot = int(param[2].z + 0.5) - 1; + if ((snSlot >= 0) && (snSlot < WATER_SLOTS) && water_snow_map(uint(snSlot), snMap)) { // the texels of the map as they lie on the glass (the uv may be stretched) ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); - uint axis = (uint(snMapSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; + uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; vec2 span = vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)); - if (min(span.x, span.y) > 1e-6) - aspect = span / max(span.x, span.y); - snowMapped(aspect, pixelUV, snowRGB, snowA, smear, snowN, snowTr); - } - else if (rain_params.x > 0.0) - { - float mass = 0.0; - if (snow_small > 0.0) - snowLayer(gridSize * 2.4 / snow_flake_scale, snow_small, 17u, 0.9, 0.85, 0.0, 0, pixelUV, aspect, snowRGB, snowA, smear, snowN, snowTr, mass); - snowLayer(gridSize / snow_flake_scale, snow_density, 13u, 1.0, 1.0, snow_slide_share, 4, pixelUV, aspect, snowRGB, snowA, smear, snowN, snowTr, mass); - if (snow_pack > 0.0) - snowFilm(gridSize, snowRGB, snowA, snowN, snowTr); // patches where flakes have run together + vec2 aspect = (min(span.x, span.y) > 1e-6) ? span / max(span.x, span.y) : vec2(1.0); + snLayer(aspect, pixelUV, layer); + snFlakes(aspect, pixelUV, flakes); + vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); + wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); + // the picture behind thin flakes and a wet film is blurred + snHaze = max(smoothstep(0.0, 0.3, flakes.a) * (1.0 - smoothstep(0.5, 0.9, layer.a)), wet * snow_wet_blur); } + // the flakes over the layer + vec3 snowRGB = flakes.rgb + layer.rgb * (1.0 - flakes.a); + float snowA = flakes.a + layer.a * (1.0 - flakes.a); + vec3 snowN = flakes.n + layer.n * (1.0 - flakes.a); + float snowTr = flakes.tr + layer.tr * (1.0 - flakes.a); float glassA = tex_color.a * alpha_mult; float finalA = snowA + glassA * (1.0 - snowA); @@ -665,7 +334,7 @@ void main() vec3 albedo = premult / max(finalA, 1e-4); float glassShare = glassA * (1.0 - snowA) / max(finalA, 1e-4); - // relief: tilt the glass normal by the slope of the snow (flat where there is none) + // relief: tilt the glass normal by the normals of the sprites (flat where there are none) vec3 nDir = snowN + vec3(0.0, 0.0, 1.0) * (1.0 - snowA); vec3 fragnormal = Ngl; if (snowA > 0.001) @@ -676,13 +345,12 @@ void main() float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5 * glassShare + snow_gloss * snowA; legacy_gloss(); - // most of the glass is clear (no snow, a clear glass texture): the lighting of the 4.6 renderers (the clusters of lamps, the - // shadows, the reflections) is skipped there, it would be multiplied by an alpha of ~0 + // most of the glass is clear: the lighting of the 4.6 renderers is skipped there, it would be multiplied by an alpha of ~0 if (finalA > 0.002) fragcolor = apply_lights(fragcolor, fragnormal, albedo, reflectivity, specularity, shadow_tone); // thin snow glows when you look towards the sun / a lamp - if (finalA > 0.002 && snowA > 0.001 && snow_translucency > 0.0 && lights_count > 0U) + if ((finalA > 0.002) && (snowA > 0.001) && (snow_translucency > 0.0) && (lights_count > 0U)) { vec3 I = normalize(f_pos.xyz); float shadowSun = 0.0; @@ -690,95 +358,31 @@ void main() shadowSun = (1.0 - shadow_tone) * clamp(calc_shadow(), 0.0, 1.0); float towards = max(dot(I, normalize(-lights[0].dir)), 0.0); float glow = pow(towards, 3.0) * (1.0 - shadowSun); - fragcolor += lights[0].color * lights[0].intensity * glow * snow_translucency * snowTr * albedo * snowA; + fragcolor += lights[0].color * lights[0].intensity * glow * snow_translucency * (snowTr / max(snowA, 1e-3)) * albedo * snowA; } vec3 lit = apply_fog(fragcolor); - -#if SNOW_MATCH_RAIN_GLASS - vec4 color = vec4(lit * finalA, finalA); -#else - vec4 color = vec4(lit, finalA); -#endif + vec4 color = vec4(lit, finalA); // straight, as rain_windscreen of the 4.6 renderers writes the glass out_color = POSTFX_ENABLED ? color : tonemap(color); // the scene seen through the snow, drawn by the post-processing (rain_windscreen_haze.glsl), asked for in the velocity target as - // rain_windscreen asks: thin snow bends it (its relief refracts; x, y = WS_DROP_BIAS + WS_BEND_ENC * bend), elsewhere it's blurred in - // and around thin snow and around the melting spots (x = WS_ENC * strength, y = 0); the snow itself stays sharp. alpha 0 elsewhere: - // the blending keeps the motion of the scene behind + // rain_windscreen asks: the drops bend it (x, y = WS_DROP_BIAS + WS_BEND_ENC * bend), thin snow and a wet film blur it + // (x = WS_ENC * strength, y = 0); the snow itself stays sharp. alpha 0 elsewhere: the blending keeps the motion of the scene behind if (MOTIONBLUR_ENABLED) { - float thin = smoothstep(0.04, 0.20, snowA) * (1.0 - smoothstep(0.55, 0.90, snowA)); - vec4 req = vec4(0.0); - if ((snWet > 0.25) && (snowA < 0.35) && (glassA < 0.5)) + vec4 req = vec4(0.0); + float clear = 1.0 - smoothstep(0.5, 0.95, glassA); + if ((snBendA > 0.25) && (layer.a < 0.3) && (glassA < 0.5)) { - // the water on the glass: its film and its spots bend the picture behind - vec2 bend = clamp(-snWetN * snow_map_wet_bend, vec2(-1.0), vec2(1.0)) * smoothstep(0.25, 0.6, snWet); - req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); - } - else if ((snow_distort > 0.0) && (thin > 0.30) && (glassA < 0.5)) - { - vec2 slope = snowN.xy / max(snowA, 1e-3); - vec2 bend = clamp(-slope * snow_distort, vec2(-1.0), vec2(1.0)) * smoothstep(0.30, 0.60, thin) * (SNOW_REFR_MAXPX / WS_REFR_MAXPX); + vec2 bend = clamp(-snBend / max(snBendA, 1e-3) * snow_drop_bend, vec2(-1.0), vec2(1.0)) * smoothstep(0.25, 0.6, snBendA); req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); } else { - float haze = snHaze * snow_haze * (1.0 - smoothstep(0.30, 0.80, snowA)); // frosted glass in and around thin snow - float blurMask = clamp(max(smear * (1.0 - snowA), haze) * (1.0 - smoothstep(0.5, 0.95, glassA)), 0.0, 1.0); + float blurMask = clamp(snHaze * snow_haze * (1.0 - smoothstep(0.3, 0.8, snowA)) * clear, 0.0, 1.0); if (blurMask >= 0.01) req = vec4(WS_ENC * blurMask, 0.0, 0.0, 1.0); } out_motion = req; } } - -float GetMixFactor(in vec2 co, out float side) { - vec4 movePhase = wiper_pos; - bvec4 is_out = lessThanEqual(movePhase, vec4(1.)); - movePhase = mix(vec4(2.) - movePhase, movePhase, is_out); - - vec4 mask = textureLod(wipermask, co, 0.0); // called from non-uniform flow: no implicit derivatives - - vec4 areaMask = step(.001, mask); - - vec4 maskVal = mix(1. - mask, mask, is_out); - vec4 wipeWidth = smoothstep(1., .9, movePhase) * .25; - vec4 cleaned = smoothstep(movePhase - wipeWidth, movePhase, maskVal) * areaMask; - vec4 side_v = step(maskVal, movePhase); - cleaned *= side_v; - side_v = mix(side_v, vec4(1.) - side_v, is_out); - - // "regeneration", snow gradually returning after a wiper pass (slower than rain, and faster in heavy snowfall): - float regenT = max(mix(snow_regen, snow_regen * 0.6, clamp(rain_params.x, 0.0, 1.0)), 0.5); - vec4 sinceV = vec4(time) - mix(wiper_timer_out, wiper_timer_return, side_v) - vec4(.2); - vec4 regenPhase = clamp(sinceV / vec4(regenT), vec4(0.), vec4(1.)); - - side_v = mix(vec4(0.), vec4(1.) - side_v, areaMask); - - vec4 factor_v = mix(vec4(1.), regenPhase * (vec4(1.) - cleaned), areaMask); - - side = 0.; - float out_factor = 1.; - bool have_side = false; - snWipeSince = 1.0e5; - - // out_factor: the blade that clears the grid cell the most wins (as before). - // side: which wiper stroke the drops of this cell belong to. It is part of the random - // seed of every drop, so it must NOT depend on out_factor. It used to: once the drops had - // fully regrown (out_factor == 1) side fell back to 0 and every drop in the swept area - // jumped to a new position, about one regrow time after each stroke (most visible in - // heavy rain, where regrowth takes ~1 s). - for(int i = 0; i < 4; ++i) - { - out_factor = min(out_factor, factor_v[i]); - if (!have_side && areaMask[i] > 0.) - { - side = side_v[i]; - snWipeSince = max(sinceV[i], 0.0); - have_side = true; - } - } - - return out_factor; -} From f0e51a8d84454b732d59dcd9a639ba3bb988ad31 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 19:22:11 +0100 Subject: [PATCH 074/123] Snow windscreen: the blades wipe the snow as the rain, wet snow refracts The blades no longer push the snow along into ridges: they take what they go over (a little stays, a wet trace), as they wipe the rain. Near zero the flakes land wet, half of them water, and the glass is warmer (the given warmth x1.5, cooled less by the speed), so the snow turns into lumps of slush sooner. The wet lumps and the slush of the atlas bend the picture behind them through the post-processing, as the drops do. The atlas (snieg_atlas_maszyna.py) changes its tiles 8, 9 and 14: grey translucent lumps with a frosted core, a darker rim and a dome for the refraction. To be added to the SVN: textures/fx/snow-atlas.tga and textures/fx/snow_normalmap.tga. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_snow_windscreen.frag | 18 +++-- shaders/ogl46/water_snow.comp | 104 ++++--------------------- shaders/vk14/mat_snow_windscreen.frag | 18 +++-- shaders/vk14/water_snow.comp | 104 ++++--------------------- 4 files changed, 52 insertions(+), 192 deletions(-) diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index 330a7583a..138ac5e85 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -7,12 +7,13 @@ // // What lies on the glass comes from the simulation (water_snow.comp, water.glsl): the map of the glass keeps the snow, the water, // how packed the snow is and the shape of its flakes from frame to frame. The flakes land and stay where they landed, pile up, -// the blades push the snow into ridges at the ends of their sweeps and leave a wet trace, it melts at the warm glass, slush slides -// down. The renderer gives the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. +// the blades wipe it as they wipe the rain (a wet trace stays), it melts at the warm glass, slush slides down. The renderer gives +// the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. // // The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen, two layers of them: // - the flakes: a sprite on every texel of the map holding snow, the more snow the bigger. Dry: crystals, flakes of a few of -// them, crumbs; wet: lumps; where only the water of a melted flake is left, a drop (it bends the picture behind, as rain does) +// them, crumbs; wet (near zero, melting): lumps of slush, grey and translucent with a frosted core; where only the water of a +// melted flake is left, a drop. The lumps and the drops bend the picture behind, as the drops of the rain // - the layer, under the flakes: a bigger sprite every three texels where the snow is thicker, clumps of flakes, then packed // snow, overlapping into a whole cover where the snow is thick; grey slush where it's wet // A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. @@ -140,7 +141,8 @@ void snSprite(vec2 local, int tile, float alpha, vec3 tone, vec2 rot, float flip acc.n = nT * a + acc.n * (1.0 - a); acc.tr = (1.0 - t.a * 0.55) * a + acc.tr * (1.0 - a); acc.a = a + acc.a * (1.0 - a); - if (tile == TILE_DROP) + // the drops and the wet lumps bend the picture behind them (water, slush), as the drops of the rain + if ((tile == TILE_DROP) || (tile == 8) || (tile == 9) || (tile == 14)) { snBend = snBend * (1.0 - a) + nuv * a; snBendA = snBendA * (1.0 - a) + a; @@ -216,7 +218,7 @@ void snFlakes(vec2 aspect, float pixelUV, inout sprite_acc acc) } else { - if (snWetness(q) > 0.35) + if (snWetness(q) > 0.25) tile = 8 + int(kind * 2.0); // wet lumps else if (kind < 0.25) tile = int(kind * 8.0); // star crystals (0, 1) @@ -264,7 +266,7 @@ void snLayer(vec2 aspect, float pixelUV, inout sprite_acc acc) if (false == snLocal(p, centre, size, aspect, rot, flip, aniso, local)) continue; int tile; - if (snWetness(q) > 0.45) + if (snWetness(q) > 0.35) tile = 14; // slush else if (q.x < 3.0) tile = 10 + int(kind * 2.0); // clumps @@ -272,7 +274,7 @@ void snLayer(vec2 aspect, float pixelUV, inout sprite_acc acc) tile = 12 + int(kind * 2.0); // packed snow float thick = 1.0 - exp(-q.x / (snow_opaque * mix(1.0, 0.5, q.z))); float alpha = mix(0.6, 1.0, thick); - // the ridges of the blades: packed and thick, a stronger relief + // packed thick snow: a stronger relief float bump = mix(1.0, 1.6, q.z * smoothstep(3.0, 12.0, q.x)); snSprite(local, min(tile, 14), alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / cells), bump, acc); } @@ -367,7 +369,7 @@ void main() { vec4 req = vec4(0.0); float clear = 1.0 - smoothstep(0.5, 0.95, glassA); - if ((snBendA > 0.25) && (layer.a < 0.3) && (glassA < 0.5)) + if ((snBendA > 0.25) && (glassA < 0.5)) { vec2 bend = clamp(-snBend / max(snBendA, 1e-3) * snow_drop_bend, vec2(-1.0), vec2(1.0)) * smoothstep(0.25, 0.6, snBendA); req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); diff --git a/shaders/ogl46/water_snow.comp b/shaders/ogl46/water_snow.comp index f7f60b28a..ce3a3a106 100644 --- a/shaders/ogl46/water_snow.comp +++ b/shaders/ogl46/water_snow.comp @@ -9,13 +9,12 @@ // flakes (mat_snow_windscreen.frag). in a step, in this order: // - the snow and the water move: wet heavy snow (slush) slides down the glass, dry powder is blown along it by the air at speed, // the water runs down as a film and is pushed by the air; and snow piled higher than its neighbours by more than it holds slips -// onto them (a ridge left by a blade spreads into a wedge). what goes over the edge of the glass falls off -// - the blades: a blade going over a texel in the step takes its snow (a little stays, and a wet trace of the water), and pushes -// it on in front of itself: the texel just ahead of the line of texels the blade went over gets their snow, packed (each texel -// to one texel at most: the snow pushed along is never counted twice). at the end -// of its sweep the blade leaves it there, a ridge; pushed past the edge of the glass, it's gone +// onto them. what goes over the edge of the glass falls off +// - the blades wipe, as they wipe the rain: a blade going over a texel in the step takes its snow (a little stays, and a wet +// trace of the water); what it takes is gone // - the flakes land: as many as come to the glass facing the snow coming at it against the cab (and a few in the eddies of the -// air where it doesn't face it), each bringing its snow to the texel; the faster the vehicle the more of the dry ones bounce off +// air where it doesn't face it), each bringing its snow to the texel; the faster the vehicle the more of the dry ones bounce off. +// near zero the flakes are wet: they bring some water with them (wet snow, lumps of slush) // - the snow melts: the glass is warmer than the air (the cab is heated), the less so the faster the vehicle goes; above zero the // snow melts at the glass into its water, the water dries slowly @@ -44,10 +43,12 @@ const float SNOW_WIPE_LEFT = 0.03; const float SNOW_WIPE_WATER = 0.1; const float SNOW_WIPE_TRACE = 0.08; const float SNOW_WIPE_WET = 0.015; -// the longest line of texels a blade goes over in a step, texels -const int SNOW_WIPE_LINE = 12; // the water the snow melts into at the glass a second for each degree the glass is above zero, mm const float SNOW_MELT = 0.003; +// how much warmer than the air the glass is, the share of the warmth given (water_snow.y, the cab heats it) +const float SNOW_WARMTH = 1.5; +// the share of a flake landing near zero already water (wet snow) +const float SNOW_WET_FLAKES = 0.5; // the water drying a second, mm, and the share of a thin film going in a second (it dries and runs off as droplets) const float SNOW_DRY = 0.0004; const float SNOW_FILM_DRY = 0.15; @@ -58,9 +59,6 @@ const float SNOW_BLOW = 0.004; const float SNOW_RUN = 0.02; const float SNOW_RUN_AIR = 0.002; -// the neighbours of a texel -const ivec2 SNOW_AROUND[8] = ivec2[8](ivec2(-1, -1), ivec2(0, -1), ivec2(1, -1), ivec2(-1, 0), ivec2(1, 0), ivec2(-1, 1), ivec2(0, 1), ivec2(1, 1)); - uint snow_slot; uint snow_from; uint snow_axes_base; @@ -97,26 +95,6 @@ bool snow_crossed(ivec2 texel, int blade) return (now > before) ? ((place > before) && (place <= now)) : ((place < before) && (place >= now)); } -// the way the blade goes over the texel, a step of a texel (zero when it can't be told) -ivec2 snow_blade_way(ivec2 texel, int blade) -{ - float here = snow_blade(texel, blade); - float right = snow_blade(texel + ivec2(1, 0), blade); - float left = snow_blade(texel - ivec2(1, 0), blade); - float up = snow_blade(texel + ivec2(0, 1), blade); - float down = snow_blade(texel - ivec2(0, 1), blade); - // one-sided where a neighbour is out of the sweep - right = (right > 0.001) ? right : here; - left = (left > 0.001) ? left : here; - up = (up > 0.001) ? up : here; - down = (down > 0.001) ? down : here; - vec2 gradient = vec2(right - left, up - down); - if (dot(gradient, gradient) < 1e-12) - return ivec2(0); - vec2 way = normalize(gradient) * ((water_blades_now[blade] > water_blades_before[blade]) ? 1.0 : -1.0); - return ivec2(round(way)); -} - // whether no blade goes over the texel now: the snow piled there may slip onto its neighbours (in a sweep of a working blade // the snow it pushes would slip behind it, a stripe of snow left on the wiped glass for every step) bool snow_unswept(ivec2 texel) @@ -219,22 +197,6 @@ vec4 snow_move(ivec2 texel, vec4 state, float seconds) return vec4(snow, max(water, 0.0), (snow > 1e-4) ? clamp(packed / snow, 0.0, 1.0) : 0.0, state.w); } -// the snow and the water of the line of texels the blade went over in the step, ending at a texel (the blade goes on from it to -// the texel ahead), and the packing of the snow (summed for its snow) -vec3 snow_line(ivec2 last, int blade, ivec2 way) -{ - vec3 line = vec3(0.0); - for (int k = 0; k < SNOW_WIPE_LINE; ++k) - { - ivec2 texel = last - way * k; - if (false == snow_crossed(texel, blade)) - break; - vec4 state = water_snow_texel(snow_slot, snow_from, texel); - line += vec3(state.x, state.y, state.x * state.z); - } - return line; -} - void main() { snow_slot = gl_WorkGroupID.y; @@ -258,39 +220,10 @@ void main() vec4 before = water_snow_texel(snow_slot, snow_from, texel); vec4 state = snow_move(texel, before, seconds); - // the blades: taken where they went over, pushed on in front of them + // the blades: they take the snow where they went over bool crossed = false; - vec3 pushed = vec3(0.0); for (int blade = 0; blade < 4; ++blade) - { - if (snow_crossed(texel, blade)) - { - crossed = true; - continue; - } - // every texel the blade went over goes to one texel ahead at most, so the snow it pushes isn't counted twice (it would - // grow at every step): in the sweep the texel takes the line of texels behind itself along the way of the blade, off the - // sweep (the blade pushes the snow out at its edge) the line of one of its neighbours pointing at it - if (snow_blade(texel, blade) > 0.001) - { - ivec2 way = snow_blade_way(texel, blade); - if ((way != ivec2(0)) && snow_crossed(texel - way, blade)) - pushed += snow_line(texel - way, blade, way); - continue; - } - for (int k = 0; k < 8; ++k) - { - ivec2 from = texel + SNOW_AROUND[k]; - if (false == snow_crossed(from, blade)) - continue; - ivec2 way = snow_blade_way(from, blade); - if ((way != ivec2(0)) && (from + way == texel)) - { - pushed += snow_line(from, blade, way); - break; - } - } - } + crossed = crossed || snow_crossed(texel, blade); if (crossed) { float left = min(state.x * SNOW_WIPE_MISS, SNOW_WIPE_LEFT); @@ -298,14 +231,6 @@ void main() state.x = left; state.y = state.y * SNOW_WIPE_WATER + min(taken * mix(SNOW_FRESH, SNOW_PACKED, state.z) * SNOW_WIPE_TRACE, SNOW_WIPE_WET); } - if (pushed.x + pushed.y > 0.0) - { - float snow = state.x + pushed.x; - // pressed by the blade - state.z = (snow > 1e-4) ? clamp((state.z * state.x + max(pushed.z, pushed.x * 0.85)) / snow, 0.0, 1.0) : state.z; - state.x = snow; - state.y += pushed.y * 0.5; - } // the flakes landing water_frame_s frame = snow_frame(texel); @@ -323,7 +248,10 @@ void main() if (count > 0.0) { float water = count * mix(SNOW_FLAKE_LEAST, SNOW_FLAKE_MOST, random.y * random.y); // mm3 - float added = water / SNOW_FRESH / max(area * 1e6, 1e-3); // mm of fresh snow over the texel + // the share of a wet flake already water (near zero) + float melting = SNOW_WET_FLAKES * smoothstep(-4.0, 0.5, water_up.w); + float added = water * (1.0 - melting) / SNOW_FRESH / max(area * 1e6, 1e-3); // mm of fresh snow over the texel + state.y += water * melting / max(area * 1e6, 1e-3); float snow = state.x + added; state.z = state.z * state.x / snow; // a flake on the bare glass has a shape of its own @@ -332,7 +260,7 @@ void main() } // the melting at the warm glass and the drying - float glass = water_up.w + water_snow.y / (1.0 + speed / 12.0); + float glass = water_up.w + water_snow.y * SNOW_WARMTH / (1.0 + speed / 25.0); float melted = min(SNOW_MELT * max(glass, 0.0) * seconds, state.x * density); state.x -= melted / max(density, 1e-3); float film = state.y * (1.0 - smoothstep(0.5, 3.0, state.x)); // the water not soaked into the snow diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index 34b24de40..1a8516b15 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -8,12 +8,13 @@ // // What lies on the glass comes from the simulation (water_snow.comp, water.glsl): the map of the glass keeps the snow, the water, // how packed the snow is and the shape of its flakes from frame to frame. The flakes land and stay where they landed, pile up, -// the blades push the snow into ridges at the ends of their sweeps and leave a wet trace, it melts at the warm glass, slush slides -// down. The renderer gives the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. +// the blades wipe it as they wipe the rain (a wet trace stays), it melts at the warm glass, slush slides down. The renderer gives +// the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. // // The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen, two layers of them: // - the flakes: a sprite on every texel of the map holding snow, the more snow the bigger. Dry: crystals, flakes of a few of -// them, crumbs; wet: lumps; where only the water of a melted flake is left, a drop (it bends the picture behind, as rain does) +// them, crumbs; wet (near zero, melting): lumps of slush, grey and translucent with a frosted core; where only the water of a +// melted flake is left, a drop. The lumps and the drops bend the picture behind, as the drops of the rain // - the layer, under the flakes: a bigger sprite every three texels where the snow is thicker, clumps of flakes, then packed // snow, overlapping into a whole cover where the snow is thick; grey slush where it's wet // A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. @@ -145,7 +146,8 @@ void snSprite(vec2 local, int tile, float alpha, vec3 tone, vec2 rot, float flip acc.n = nT * a + acc.n * (1.0 - a); acc.tr = (1.0 - t.a * 0.55) * a + acc.tr * (1.0 - a); acc.a = a + acc.a * (1.0 - a); - if (tile == TILE_DROP) + // the drops and the wet lumps bend the picture behind them (water, slush), as the drops of the rain + if ((tile == TILE_DROP) || (tile == 8) || (tile == 9) || (tile == 14)) { snBend = snBend * (1.0 - a) + nuv * a; snBendA = snBendA * (1.0 - a) + a; @@ -221,7 +223,7 @@ void snFlakes(vec2 aspect, float pixelUV, inout sprite_acc acc) } else { - if (snWetness(q) > 0.35) + if (snWetness(q) > 0.25) tile = 8 + int(kind * 2.0); // wet lumps else if (kind < 0.25) tile = int(kind * 8.0); // star crystals (0, 1) @@ -269,7 +271,7 @@ void snLayer(vec2 aspect, float pixelUV, inout sprite_acc acc) if (false == snLocal(p, centre, size, aspect, rot, flip, aniso, local)) continue; int tile; - if (snWetness(q) > 0.45) + if (snWetness(q) > 0.35) tile = 14; // slush else if (q.x < 3.0) tile = 10 + int(kind * 2.0); // clumps @@ -277,7 +279,7 @@ void snLayer(vec2 aspect, float pixelUV, inout sprite_acc acc) tile = 12 + int(kind * 2.0); // packed snow float thick = 1.0 - exp(-q.x / (snow_opaque * mix(1.0, 0.5, q.z))); float alpha = mix(0.6, 1.0, thick); - // the ridges of the blades: packed and thick, a stronger relief + // packed thick snow: a stronger relief float bump = mix(1.0, 1.6, q.z * smoothstep(3.0, 12.0, q.x)); snSprite(local, min(tile, 14), alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / cells), bump, acc); } @@ -372,7 +374,7 @@ void main() { vec4 req = vec4(0.0); float clear = 1.0 - smoothstep(0.5, 0.95, glassA); - if ((snBendA > 0.25) && (layer.a < 0.3) && (glassA < 0.5)) + if ((snBendA > 0.25) && (glassA < 0.5)) { vec2 bend = clamp(-snBend / max(snBendA, 1e-3) * snow_drop_bend, vec2(-1.0), vec2(1.0)) * smoothstep(0.25, 0.6, snBendA); req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); diff --git a/shaders/vk14/water_snow.comp b/shaders/vk14/water_snow.comp index e4ea47a86..c69898985 100644 --- a/shaders/vk14/water_snow.comp +++ b/shaders/vk14/water_snow.comp @@ -9,13 +9,12 @@ // flakes (mat_snow_windscreen.frag). in a step, in this order: // - the snow and the water move: wet heavy snow (slush) slides down the glass, dry powder is blown along it by the air at speed, // the water runs down as a film and is pushed by the air; and snow piled higher than its neighbours by more than it holds slips -// onto them (a ridge left by a blade spreads into a wedge). what goes over the edge of the glass falls off -// - the blades: a blade going over a texel in the step takes its snow (a little stays, and a wet trace of the water), and pushes -// it on in front of itself: the texel just ahead of the line of texels the blade went over gets their snow, packed (each texel -// to one texel at most: the snow pushed along is never counted twice). at the end -// of its sweep the blade leaves it there, a ridge; pushed past the edge of the glass, it's gone +// onto them. what goes over the edge of the glass falls off +// - the blades wipe, as they wipe the rain: a blade going over a texel in the step takes its snow (a little stays, and a wet +// trace of the water); what it takes is gone // - the flakes land: as many as come to the glass facing the snow coming at it against the cab (and a few in the eddies of the -// air where it doesn't face it), each bringing its snow to the texel; the faster the vehicle the more of the dry ones bounce off +// air where it doesn't face it), each bringing its snow to the texel; the faster the vehicle the more of the dry ones bounce off. +// near zero the flakes are wet: they bring some water with them (wet snow, lumps of slush) // - the snow melts: the glass is warmer than the air (the cab is heated), the less so the faster the vehicle goes; above zero the // snow melts at the glass into its water, the water dries slowly @@ -47,10 +46,12 @@ const float SNOW_WIPE_LEFT = 0.03; const float SNOW_WIPE_WATER = 0.1; const float SNOW_WIPE_TRACE = 0.08; const float SNOW_WIPE_WET = 0.015; -// the longest line of texels a blade goes over in a step, texels -const int SNOW_WIPE_LINE = 12; // the water the snow melts into at the glass a second for each degree the glass is above zero, mm const float SNOW_MELT = 0.003; +// how much warmer than the air the glass is, the share of the warmth given (water_snow.y, the cab heats it) +const float SNOW_WARMTH = 1.5; +// the share of a flake landing near zero already water (wet snow) +const float SNOW_WET_FLAKES = 0.5; // the water drying a second, mm, and the share of a thin film going in a second (it dries and runs off as droplets) const float SNOW_DRY = 0.0004; const float SNOW_FILM_DRY = 0.15; @@ -61,9 +62,6 @@ const float SNOW_BLOW = 0.004; const float SNOW_RUN = 0.02; const float SNOW_RUN_AIR = 0.002; -// the neighbours of a texel -const ivec2 SNOW_AROUND[8] = ivec2[8](ivec2(-1, -1), ivec2(0, -1), ivec2(1, -1), ivec2(-1, 0), ivec2(1, 0), ivec2(-1, 1), ivec2(0, 1), ivec2(1, 1)); - uint snow_slot; uint snow_from; uint snow_axes_base; @@ -100,26 +98,6 @@ bool snow_crossed(ivec2 texel, int blade) return (now > before) ? ((place > before) && (place <= now)) : ((place < before) && (place >= now)); } -// the way the blade goes over the texel, a step of a texel (zero when it can't be told) -ivec2 snow_blade_way(ivec2 texel, int blade) -{ - float here = snow_blade(texel, blade); - float right = snow_blade(texel + ivec2(1, 0), blade); - float left = snow_blade(texel - ivec2(1, 0), blade); - float up = snow_blade(texel + ivec2(0, 1), blade); - float down = snow_blade(texel - ivec2(0, 1), blade); - // one-sided where a neighbour is out of the sweep - right = (right > 0.001) ? right : here; - left = (left > 0.001) ? left : here; - up = (up > 0.001) ? up : here; - down = (down > 0.001) ? down : here; - vec2 gradient = vec2(right - left, up - down); - if (dot(gradient, gradient) < 1e-12) - return ivec2(0); - vec2 way = normalize(gradient) * ((water_blades_now[blade] > water_blades_before[blade]) ? 1.0 : -1.0); - return ivec2(round(way)); -} - // whether no blade goes over the texel now: the snow piled there may slip onto its neighbours (in a sweep of a working blade // the snow it pushes would slip behind it, a stripe of snow left on the wiped glass for every step) bool snow_unswept(ivec2 texel) @@ -222,22 +200,6 @@ vec4 snow_move(ivec2 texel, vec4 state, float seconds) return vec4(snow, max(water, 0.0), (snow > 1e-4) ? clamp(packed / snow, 0.0, 1.0) : 0.0, state.w); } -// the snow and the water of the line of texels the blade went over in the step, ending at a texel (the blade goes on from it to -// the texel ahead), and the packing of the snow (summed for its snow) -vec3 snow_line(ivec2 last, int blade, ivec2 way) -{ - vec3 line = vec3(0.0); - for (int k = 0; k < SNOW_WIPE_LINE; ++k) - { - ivec2 texel = last - way * k; - if (false == snow_crossed(texel, blade)) - break; - vec4 state = water_snow_texel(snow_slot, snow_from, texel); - line += vec3(state.x, state.y, state.x * state.z); - } - return line; -} - void main() { snow_slot = gl_WorkGroupID.y; @@ -261,39 +223,10 @@ void main() vec4 before = water_snow_texel(snow_slot, snow_from, texel); vec4 state = snow_move(texel, before, seconds); - // the blades: taken where they went over, pushed on in front of them + // the blades: they take the snow where they went over bool crossed = false; - vec3 pushed = vec3(0.0); for (int blade = 0; blade < 4; ++blade) - { - if (snow_crossed(texel, blade)) - { - crossed = true; - continue; - } - // every texel the blade went over goes to one texel ahead at most, so the snow it pushes isn't counted twice (it would - // grow at every step): in the sweep the texel takes the line of texels behind itself along the way of the blade, off the - // sweep (the blade pushes the snow out at its edge) the line of one of its neighbours pointing at it - if (snow_blade(texel, blade) > 0.001) - { - ivec2 way = snow_blade_way(texel, blade); - if ((way != ivec2(0)) && snow_crossed(texel - way, blade)) - pushed += snow_line(texel - way, blade, way); - continue; - } - for (int k = 0; k < 8; ++k) - { - ivec2 from = texel + SNOW_AROUND[k]; - if (false == snow_crossed(from, blade)) - continue; - ivec2 way = snow_blade_way(from, blade); - if ((way != ivec2(0)) && (from + way == texel)) - { - pushed += snow_line(from, blade, way); - break; - } - } - } + crossed = crossed || snow_crossed(texel, blade); if (crossed) { float left = min(state.x * SNOW_WIPE_MISS, SNOW_WIPE_LEFT); @@ -301,14 +234,6 @@ void main() state.x = left; state.y = state.y * SNOW_WIPE_WATER + min(taken * mix(SNOW_FRESH, SNOW_PACKED, state.z) * SNOW_WIPE_TRACE, SNOW_WIPE_WET); } - if (pushed.x + pushed.y > 0.0) - { - float snow = state.x + pushed.x; - // pressed by the blade - state.z = (snow > 1e-4) ? clamp((state.z * state.x + max(pushed.z, pushed.x * 0.85)) / snow, 0.0, 1.0) : state.z; - state.x = snow; - state.y += pushed.y * 0.5; - } // the flakes landing water_frame_s frame = snow_frame(texel); @@ -326,7 +251,10 @@ void main() if (count > 0.0) { float water = count * mix(SNOW_FLAKE_LEAST, SNOW_FLAKE_MOST, random.y * random.y); // mm3 - float added = water / SNOW_FRESH / max(area * 1e6, 1e-3); // mm of fresh snow over the texel + // the share of a wet flake already water (near zero) + float melting = SNOW_WET_FLAKES * smoothstep(-4.0, 0.5, water_up.w); + float added = water * (1.0 - melting) / SNOW_FRESH / max(area * 1e6, 1e-3); // mm of fresh snow over the texel + state.y += water * melting / max(area * 1e6, 1e-3); float snow = state.x + added; state.z = state.z * state.x / snow; // a flake on the bare glass has a shape of its own @@ -335,7 +263,7 @@ void main() } // the melting at the warm glass and the drying - float glass = water_up.w + water_snow.y / (1.0 + speed / 12.0); + float glass = water_up.w + water_snow.y * SNOW_WARMTH / (1.0 + speed / 25.0); float melted = min(SNOW_MELT * max(glass, 0.0) * seconds, state.x * density); state.x -= melted / max(density, 1e-3); float film = state.y * (1.0 - smoothstep(0.5, 3.0, state.x)); // the water not soaked into the snow From 9c2f8572101c4cc2908884154b55724f617e89fe Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 19:38:01 +0100 Subject: [PATCH 075/123] Snow windscreen: lumps in cells as the drops of the rain, not a sprite per texel A sprite on every texel holding snow covered the glass in an even pattern of dots. The snow is drawn now as the rain is: a lump in a cell of four texels at most, the more snow around the likelier and bigger, sizes from a few mm to a few cm (most small, wet ones bigger), clear glass between them until the snow gets thick and packed snow covers it. Single crystals of dry snow show on 12% of the texels holding a little of it, drops of melted flakes on some of those holding only water. The haze stays near the snow. The atlas (snieg_atlas_maszyna.py) gets bigger wet lumps with a bigger frosted core. To be added to the SVN: textures/fx/snow-atlas.tga and textures/fx/snow_normalmap.tga. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_snow_windscreen.frag | 102 ++++++++++++------------- shaders/vk14/mat_snow_windscreen.frag | 102 ++++++++++++------------- 2 files changed, 102 insertions(+), 102 deletions(-) diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index 138ac5e85..532183f4a 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -10,12 +10,12 @@ // the blades wipe it as they wipe the rain (a wet trace stays), it melts at the warm glass, slush slides down. The renderer gives // the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. // -// The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen, two layers of them: -// - the flakes: a sprite on every texel of the map holding snow, the more snow the bigger. Dry: crystals, flakes of a few of -// them, crumbs; wet (near zero, melting): lumps of slush, grey and translucent with a frosted core; where only the water of a -// melted flake is left, a drop. The lumps and the drops bend the picture behind, as the drops of the rain -// - the layer, under the flakes: a bigger sprite every three texels where the snow is thicker, clumps of flakes, then packed -// snow, overlapping into a whole cover where the snow is thick; grey slush where it's wet +// The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen: +// - the lumps: one in a cell of a few texels at most, as the drops of the rain, the more snow around the likelier and bigger, +// from a few mm to a few cm (most of them small), clear glass between them until the snow gets thick, then packed snow +// overlapping into a cover. Wet (near zero, melting): lumps of slush, grey, translucent with a frosted core, bending the +// picture behind; dry: clumps of flakes +// - single crystals of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) // A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. // // Atlas / normalmap (snieg_atlas_maszyna.py), 4 x 4 tiles of 512 x 512 (2048 x 2048): @@ -66,9 +66,11 @@ layout(binding = 2) uniform sampler2D wipermask; layout(binding = 3) uniform sampler2D normalmap; // --- tuning ------------------------------------------------------------------------------------------------------------------ -const float snow_flake = 1.2; // size of a flake, texels of the map (grows to 1.6x with the snow of its texel) -const float snow_layer = 0.6; // mm of snow from which the layer starts (clumps), the cover grows to full by 1.5 mm -const float snow_layer_cell = 3.0; // a sprite of the layer every this many texels +const float snow_flake = 1.4; // size of a single crystal or a drop, texels of the map +const float snow_crystals = 0.12; // share of the texels with a little dry snow showing a single crystal +const float snow_drops = 0.35; // share of the texels with the water of a melted flake showing a drop (more with more water) +const float snow_layer = 0.6; // mm of snow around which a cell surely has a lump (fewer, smaller below) +const float snow_layer_cell = 4.0; // a lump at most every this many texels (~2 cm) const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) const float snow_thin = 0.45; // opacity of a single thin flake (ice crystals let most of the light through) const float snow_bump = 1.0; // strength of the relief from the normal map, 0 = flat @@ -177,10 +179,11 @@ vec3 snTone(vec4 q, float random) { vec3 tone = vec3(mix(0.94, 1.04, random)); tone *= mix(vec3(1.0), vec3(0.95, 0.96, 0.98), q.z); - return tone * mix(vec3(1.0), vec3(0.78, 0.83, 0.88), smoothstep(0.3, 0.8, snWetness(q))); + return tone * mix(vec3(1.0), vec3(0.88, 0.91, 0.94), smoothstep(0.3, 0.8, snWetness(q))); } -// the flakes: a sprite on every texel holding snow (a drop where only its water is left) +// the single crystals and the drops: on a few of the texels holding a little snow a crystal (dry snow) sits by itself between the +// lumps, on a few of those holding only water a drop of a melted flake void snFlakes(vec2 aspect, float pixelUV, inout sprite_acc acc) { vec2 p = f_coord * float(WATER_MAP); @@ -192,11 +195,11 @@ void snFlakes(vec2 aspect, float pixelUV, inout sprite_acc acc) ivec2 texel = here + ivec2(ox, oy); vec4 q = water_snow_texel(uint(snSlot), snMap, texel); bool drop = (q.x < 0.05) && (q.y > 0.03); - if ((q.x < 0.05) && (false == drop)) + bool crystal = (q.x >= 0.05) && (snWetness(q) < 0.25); + if ((false == drop) && (false == crystal)) continue; uint seed = Hash(uvec3(uvec2(texel), uint(q.w * 65535.0) + 7u * uint(snSlot))); - // the water of a texel is a drop only now and then: the more water the more of them - if (drop && (RandF(seed) > smoothstep(0.03, 0.2, q.y))) + if (RandF(seed) > (drop ? snow_drops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) continue; vec2 centre = vec2(texel) + 0.2 + 0.6 * vec2(RandF(seed), RandF(seed)); float ang = RandF(seed) * 6.2831853; @@ -204,41 +207,34 @@ void snFlakes(vec2 aspect, float pixelUV, inout sprite_acc acc) float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; float kind = RandF(seed); float random = RandF(seed); - float size = snow_flake * mix(0.75, 1.0, RandF(seed)) - * (drop ? mix(0.5, 1.0, smoothstep(0.03, 0.3, q.y)) : mix(0.8, 1.6, smoothstep(0.05, 1.5, q.x))); + float size = snow_flake * mix(0.6, 1.0, RandF(seed)) * (drop ? mix(0.7, 1.4, smoothstep(0.03, 0.3, q.y)) : 1.0); vec2 local; if (false == snLocal(p, centre, size, aspect, rot, flip, 1.0, local)) continue; - int tile; - float alpha; - if (drop) + int tile = TILE_DROP; + float alpha = smoothstep(0.03, 0.1, q.y); + if (crystal) { - tile = TILE_DROP; - alpha = smoothstep(0.03, 0.1, q.y); - } - else - { - if (snWetness(q) > 0.25) - tile = 8 + int(kind * 2.0); // wet lumps - else if (kind < 0.25) - tile = int(kind * 8.0); // star crystals (0, 1) - else if (kind < 0.35) + if (kind < 0.35) + tile = int(kind * 5.72); // star crystals (0, 1) + else if (kind < 0.5) tile = 2; // a plate - else if (kind < 0.45) + else if (kind < 0.65) tile = 3; // needles - else if (kind < 0.80) - tile = 4 + int((kind - 0.45) / 0.35 * 2.0); // flakes of a few crystals else - tile = 6 + int((kind - 0.80) / 0.2 * 2.0); // crumbs - tile = min(tile, 9); - alpha = smoothstep(0.05, 0.25, q.x) * mix(snow_thin, 1.0, smoothstep(0.3, 2.5, q.x)); + tile = 4 + int((kind - 0.65) / 0.35 * 2.0); // flakes of a few crystals + tile = min(tile, 5); + alpha = snow_thin; } snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / float(WATER_MAP)), 1.0, acc); } } } -// the layer: a bigger sprite every few texels where the snow is thicker, clumps and then packed snow, overlapping into a cover +// the lumps: one in a cell of a few texels at most, as the drops of the rain: the more snow around it the likelier it's there +// and the bigger, sizes from a few mm to a few cm (most of them small), gaps of clear glass between them until the snow gets +// thick; then packed snow overlapping into a cover. wet: lumps of slush (grey, translucent, bending the picture behind); +// dry: clumps of flakes void snLayer(vec2 aspect, float pixelUV, inout sprite_acc acc) { float cells = float(WATER_MAP) / snow_layer_cell; @@ -250,33 +246,37 @@ void snLayer(vec2 aspect, float pixelUV, inout sprite_acc acc) { ivec2 cell = here + ivec2(ox, oy); uint seed = Hash(uvec3(uvec2(cell + 4096), 31u + 7u * uint(snSlot))); - vec2 centre = vec2(cell) + 0.3 + 0.4 * vec2(RandF(seed), RandF(seed)); + vec2 centre = vec2(cell) + 0.25 + 0.5 * vec2(RandF(seed), RandF(seed)); vec4 q = water_snow_at(uint(snSlot), snMap, centre / cells); - float present = smoothstep(snow_layer, snow_layer * 2.5, q.x); - if (RandF(seed) >= present) + if (RandF(seed) >= smoothstep(snow_layer * 0.1, snow_layer * 2.0, q.x)) continue; float ang = RandF(seed) * 6.2831853; vec2 rot = vec2(cos(ang), sin(ang)); float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; float kind = RandF(seed); float random = RandF(seed); - float aniso = mix(0.8, 1.0, RandF(seed)); - float size = mix(1.25, 2.0, smoothstep(snow_layer, 4.0, q.x)) * mix(0.85, 1.0, RandF(seed)); + float aniso = mix(0.75, 1.0, RandF(seed)); + float cover = smoothstep(2.0, 5.0, q.x); // thick: the lumps grow into a cover + float grow = RandF(seed); + float wet = snWetness(q); + // wet lumps are bigger: the slush of a few flakes runs together + float size = mix(mix(0.5, 1.6, grow * grow) * mix(0.8, 1.3, smoothstep(snow_layer, 2.5, q.x)) * ((wet > 0.2) ? 1.25 : 1.0), + 2.0, cover); vec2 local; if (false == snLocal(p, centre, size, aspect, rot, flip, aniso, local)) continue; int tile; - if (snWetness(q) > 0.35) - tile = 14; // slush - else if (q.x < 3.0) - tile = 10 + int(kind * 2.0); // clumps + if (cover > 0.5) + tile = (wet > 0.35) ? 14 : 12 + int(kind * 2.0); // slush, packed snow + else if (wet > 0.2) + tile = 8 + int(kind * 2.0); // wet lumps + else if (size < 0.7) + tile = 4 + int(kind * 2.0); // flakes of a few crystals else - tile = 12 + int(kind * 2.0); // packed snow + tile = 10 + int(kind * 2.0); // clumps float thick = 1.0 - exp(-q.x / (snow_opaque * mix(1.0, 0.5, q.z))); - float alpha = mix(0.6, 1.0, thick); - // packed thick snow: a stronger relief - float bump = mix(1.0, 1.6, q.z * smoothstep(3.0, 12.0, q.x)); - snSprite(local, min(tile, 14), alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / cells), bump, acc); + float alpha = mix(0.75, 1.0, thick); + snSprite(local, min(tile, 14), alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / cells), 1.0, acc); } } } @@ -317,7 +317,7 @@ void main() vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); // the picture behind thin flakes and a wet film is blurred - snHaze = max(smoothstep(0.0, 0.3, flakes.a) * (1.0 - smoothstep(0.5, 0.9, layer.a)), wet * snow_wet_blur); + snHaze = max(smoothstep(0.0, 0.3, flakes.a + layer.a) * (1.0 - smoothstep(0.5, 0.9, layer.a)) * 0.6, wet * snow_wet_blur); } // the flakes over the layer vec3 snowRGB = flakes.rgb + layer.rgb * (1.0 - flakes.a); diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index 1a8516b15..15b630122 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -11,12 +11,12 @@ // the blades wipe it as they wipe the rain (a wet trace stays), it melts at the warm glass, slush slides down. The renderer gives // the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. // -// The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen, two layers of them: -// - the flakes: a sprite on every texel of the map holding snow, the more snow the bigger. Dry: crystals, flakes of a few of -// them, crumbs; wet (near zero, melting): lumps of slush, grey and translucent with a frosted core; where only the water of a -// melted flake is left, a drop. The lumps and the drops bend the picture behind, as the drops of the rain -// - the layer, under the flakes: a bigger sprite every three texels where the snow is thicker, clumps of flakes, then packed -// snow, overlapping into a whole cover where the snow is thick; grey slush where it's wet +// The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen: +// - the lumps: one in a cell of a few texels at most, as the drops of the rain, the more snow around the likelier and bigger, +// from a few mm to a few cm (most of them small), clear glass between them until the snow gets thick, then packed snow +// overlapping into a cover. Wet (near zero, melting): lumps of slush, grey, translucent with a frosted core, bending the +// picture behind; dry: clumps of flakes +// - single crystals of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) // A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. // // Atlas / normalmap (snieg_atlas_maszyna.py), 4 x 4 tiles of 512 x 512 (2048 x 2048): @@ -71,9 +71,11 @@ layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 2) uniform sampler layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 3) uniform sampler2D normalmap; // --- tuning ------------------------------------------------------------------------------------------------------------------ -const float snow_flake = 1.2; // size of a flake, texels of the map (grows to 1.6x with the snow of its texel) -const float snow_layer = 0.6; // mm of snow from which the layer starts (clumps), the cover grows to full by 1.5 mm -const float snow_layer_cell = 3.0; // a sprite of the layer every this many texels +const float snow_flake = 1.4; // size of a single crystal or a drop, texels of the map +const float snow_crystals = 0.12; // share of the texels with a little dry snow showing a single crystal +const float snow_drops = 0.35; // share of the texels with the water of a melted flake showing a drop (more with more water) +const float snow_layer = 0.6; // mm of snow around which a cell surely has a lump (fewer, smaller below) +const float snow_layer_cell = 4.0; // a lump at most every this many texels (~2 cm) const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) const float snow_thin = 0.45; // opacity of a single thin flake (ice crystals let most of the light through) const float snow_bump = 1.0; // strength of the relief from the normal map, 0 = flat @@ -182,10 +184,11 @@ vec3 snTone(vec4 q, float random) { vec3 tone = vec3(mix(0.94, 1.04, random)); tone *= mix(vec3(1.0), vec3(0.95, 0.96, 0.98), q.z); - return tone * mix(vec3(1.0), vec3(0.78, 0.83, 0.88), smoothstep(0.3, 0.8, snWetness(q))); + return tone * mix(vec3(1.0), vec3(0.88, 0.91, 0.94), smoothstep(0.3, 0.8, snWetness(q))); } -// the flakes: a sprite on every texel holding snow (a drop where only its water is left) +// the single crystals and the drops: on a few of the texels holding a little snow a crystal (dry snow) sits by itself between the +// lumps, on a few of those holding only water a drop of a melted flake void snFlakes(vec2 aspect, float pixelUV, inout sprite_acc acc) { vec2 p = f_coord * float(WATER_MAP); @@ -197,11 +200,11 @@ void snFlakes(vec2 aspect, float pixelUV, inout sprite_acc acc) ivec2 texel = here + ivec2(ox, oy); vec4 q = water_snow_texel(uint(snSlot), snMap, texel); bool drop = (q.x < 0.05) && (q.y > 0.03); - if ((q.x < 0.05) && (false == drop)) + bool crystal = (q.x >= 0.05) && (snWetness(q) < 0.25); + if ((false == drop) && (false == crystal)) continue; uint seed = Hash(uvec3(uvec2(texel), uint(q.w * 65535.0) + 7u * uint(snSlot))); - // the water of a texel is a drop only now and then: the more water the more of them - if (drop && (RandF(seed) > smoothstep(0.03, 0.2, q.y))) + if (RandF(seed) > (drop ? snow_drops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) continue; vec2 centre = vec2(texel) + 0.2 + 0.6 * vec2(RandF(seed), RandF(seed)); float ang = RandF(seed) * 6.2831853; @@ -209,41 +212,34 @@ void snFlakes(vec2 aspect, float pixelUV, inout sprite_acc acc) float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; float kind = RandF(seed); float random = RandF(seed); - float size = snow_flake * mix(0.75, 1.0, RandF(seed)) - * (drop ? mix(0.5, 1.0, smoothstep(0.03, 0.3, q.y)) : mix(0.8, 1.6, smoothstep(0.05, 1.5, q.x))); + float size = snow_flake * mix(0.6, 1.0, RandF(seed)) * (drop ? mix(0.7, 1.4, smoothstep(0.03, 0.3, q.y)) : 1.0); vec2 local; if (false == snLocal(p, centre, size, aspect, rot, flip, 1.0, local)) continue; - int tile; - float alpha; - if (drop) + int tile = TILE_DROP; + float alpha = smoothstep(0.03, 0.1, q.y); + if (crystal) { - tile = TILE_DROP; - alpha = smoothstep(0.03, 0.1, q.y); - } - else - { - if (snWetness(q) > 0.25) - tile = 8 + int(kind * 2.0); // wet lumps - else if (kind < 0.25) - tile = int(kind * 8.0); // star crystals (0, 1) - else if (kind < 0.35) + if (kind < 0.35) + tile = int(kind * 5.72); // star crystals (0, 1) + else if (kind < 0.5) tile = 2; // a plate - else if (kind < 0.45) + else if (kind < 0.65) tile = 3; // needles - else if (kind < 0.80) - tile = 4 + int((kind - 0.45) / 0.35 * 2.0); // flakes of a few crystals else - tile = 6 + int((kind - 0.80) / 0.2 * 2.0); // crumbs - tile = min(tile, 9); - alpha = smoothstep(0.05, 0.25, q.x) * mix(snow_thin, 1.0, smoothstep(0.3, 2.5, q.x)); + tile = 4 + int((kind - 0.65) / 0.35 * 2.0); // flakes of a few crystals + tile = min(tile, 5); + alpha = snow_thin; } snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / float(WATER_MAP)), 1.0, acc); } } } -// the layer: a bigger sprite every few texels where the snow is thicker, clumps and then packed snow, overlapping into a cover +// the lumps: one in a cell of a few texels at most, as the drops of the rain: the more snow around it the likelier it's there +// and the bigger, sizes from a few mm to a few cm (most of them small), gaps of clear glass between them until the snow gets +// thick; then packed snow overlapping into a cover. wet: lumps of slush (grey, translucent, bending the picture behind); +// dry: clumps of flakes void snLayer(vec2 aspect, float pixelUV, inout sprite_acc acc) { float cells = float(WATER_MAP) / snow_layer_cell; @@ -255,33 +251,37 @@ void snLayer(vec2 aspect, float pixelUV, inout sprite_acc acc) { ivec2 cell = here + ivec2(ox, oy); uint seed = Hash(uvec3(uvec2(cell + 4096), 31u + 7u * uint(snSlot))); - vec2 centre = vec2(cell) + 0.3 + 0.4 * vec2(RandF(seed), RandF(seed)); + vec2 centre = vec2(cell) + 0.25 + 0.5 * vec2(RandF(seed), RandF(seed)); vec4 q = water_snow_at(uint(snSlot), snMap, centre / cells); - float present = smoothstep(snow_layer, snow_layer * 2.5, q.x); - if (RandF(seed) >= present) + if (RandF(seed) >= smoothstep(snow_layer * 0.1, snow_layer * 2.0, q.x)) continue; float ang = RandF(seed) * 6.2831853; vec2 rot = vec2(cos(ang), sin(ang)); float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; float kind = RandF(seed); float random = RandF(seed); - float aniso = mix(0.8, 1.0, RandF(seed)); - float size = mix(1.25, 2.0, smoothstep(snow_layer, 4.0, q.x)) * mix(0.85, 1.0, RandF(seed)); + float aniso = mix(0.75, 1.0, RandF(seed)); + float cover = smoothstep(2.0, 5.0, q.x); // thick: the lumps grow into a cover + float grow = RandF(seed); + float wet = snWetness(q); + // wet lumps are bigger: the slush of a few flakes runs together + float size = mix(mix(0.5, 1.6, grow * grow) * mix(0.8, 1.3, smoothstep(snow_layer, 2.5, q.x)) * ((wet > 0.2) ? 1.25 : 1.0), + 2.0, cover); vec2 local; if (false == snLocal(p, centre, size, aspect, rot, flip, aniso, local)) continue; int tile; - if (snWetness(q) > 0.35) - tile = 14; // slush - else if (q.x < 3.0) - tile = 10 + int(kind * 2.0); // clumps + if (cover > 0.5) + tile = (wet > 0.35) ? 14 : 12 + int(kind * 2.0); // slush, packed snow + else if (wet > 0.2) + tile = 8 + int(kind * 2.0); // wet lumps + else if (size < 0.7) + tile = 4 + int(kind * 2.0); // flakes of a few crystals else - tile = 12 + int(kind * 2.0); // packed snow + tile = 10 + int(kind * 2.0); // clumps float thick = 1.0 - exp(-q.x / (snow_opaque * mix(1.0, 0.5, q.z))); - float alpha = mix(0.6, 1.0, thick); - // packed thick snow: a stronger relief - float bump = mix(1.0, 1.6, q.z * smoothstep(3.0, 12.0, q.x)); - snSprite(local, min(tile, 14), alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / cells), bump, acc); + float alpha = mix(0.75, 1.0, thick); + snSprite(local, min(tile, 14), alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / cells), 1.0, acc); } } } @@ -322,7 +322,7 @@ void main() vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); // the picture behind thin flakes and a wet film is blurred - snHaze = max(smoothstep(0.0, 0.3, flakes.a) * (1.0 - smoothstep(0.5, 0.9, layer.a)), wet * snow_wet_blur); + snHaze = max(smoothstep(0.0, 0.3, flakes.a + layer.a) * (1.0 - smoothstep(0.5, 0.9, layer.a)) * 0.6, wet * snow_wet_blur); } // the flakes over the layer vec3 snowRGB = flakes.rgb + layer.rgb * (1.0 - flakes.a); From 2c23d12070a12245a6856ff66f81e3c426745817 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 19:44:34 +0100 Subject: [PATCH 076/123] Snow windscreen: no big star flakes, dry powder bounces off a moving glass The small lumps of dry snow were drawn with the tiles of a few star crystals, a glass covered in big stars at speed. They're crumbs now (a flake breaks up hitting the glass); single crystals are rarer (5% of the texels) and smaller (~5 mm). Dry flakes (below -3 deg C, on dry glass) bounce off a moving glass: 85% of them from 25 m/s, so dry snow builds up slowly at speed; the wet ones stay. No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_snow_windscreen.frag | 10 +++++----- shaders/ogl46/water_snow.comp | 6 ++++-- shaders/vk14/mat_snow_windscreen.frag | 10 +++++----- shaders/vk14/water_snow.comp | 6 ++++-- 4 files changed, 18 insertions(+), 14 deletions(-) diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index 532183f4a..9d27b96d9 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -14,7 +14,7 @@ // - the lumps: one in a cell of a few texels at most, as the drops of the rain, the more snow around the likelier and bigger, // from a few mm to a few cm (most of them small), clear glass between them until the snow gets thick, then packed snow // overlapping into a cover. Wet (near zero, melting): lumps of slush, grey, translucent with a frosted core, bending the -// picture behind; dry: clumps of flakes +// picture behind; dry: crumbs and clumps of the flakes broken on the glass // - single crystals of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) // A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. // @@ -66,8 +66,8 @@ layout(binding = 2) uniform sampler2D wipermask; layout(binding = 3) uniform sampler2D normalmap; // --- tuning ------------------------------------------------------------------------------------------------------------------ -const float snow_flake = 1.4; // size of a single crystal or a drop, texels of the map -const float snow_crystals = 0.12; // share of the texels with a little dry snow showing a single crystal +const float snow_flake = 1.1; // size of a single crystal or a drop, texels of the map (~5 mm) +const float snow_crystals = 0.05; // share of the texels with a little dry snow showing a single crystal const float snow_drops = 0.35; // share of the texels with the water of a melted flake showing a drop (more with more water) const float snow_layer = 0.6; // mm of snow around which a cell surely has a lump (fewer, smaller below) const float snow_layer_cell = 4.0; // a lump at most every this many texels (~2 cm) @@ -270,8 +270,8 @@ void snLayer(vec2 aspect, float pixelUV, inout sprite_acc acc) tile = (wet > 0.35) ? 14 : 12 + int(kind * 2.0); // slush, packed snow else if (wet > 0.2) tile = 8 + int(kind * 2.0); // wet lumps - else if (size < 0.7) - tile = 4 + int(kind * 2.0); // flakes of a few crystals + else if (size < 0.8) + tile = 6 + int(kind * 2.0); // crumbs (a flake breaks up hitting the glass) else tile = 10 + int(kind * 2.0); // clumps float thick = 1.0 - exp(-q.x / (snow_opaque * mix(1.0, 0.5, q.z))); diff --git a/shaders/ogl46/water_snow.comp b/shaders/ogl46/water_snow.comp index ce3a3a106..0599beda4 100644 --- a/shaders/ogl46/water_snow.comp +++ b/shaders/ogl46/water_snow.comp @@ -240,8 +240,10 @@ void main() float speed = water_snow.z; float density = mix(SNOW_FRESH, SNOW_PACKED, state.z); float wet = state.y / (state.y + state.x * density + 1e-4); - // the dry flakes bounce off a fast glass, the ones landing on wet snow or water stay - float sticking = 1.0 - 0.6 * smoothstep(15.0, 35.0, speed) * (1.0 - smoothstep(0.1, 0.4, wet)); + // the dry flakes bounce off a moving glass (powder is blown away), the wet ones (near zero) and those landing on wet snow or + // water stay + float dry = (1.0 - smoothstep(0.1, 0.4, wet)) * (1.0 - smoothstep(-3.0, 0.0, water_up.w)); + float sticking = 1.0 - 0.85 * smoothstep(5.0, 25.0, speed) * dry; float landings = water_snow.x / max(water_air.w, 0.1) * facing * area * seconds * sticking; vec4 random = water_random(place, snow_slot, water_counts.x, 0x5e0du); float count = min(floor(landings) + ((random.x < fract(landings)) ? 1.0 : 0.0), 4.0); diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index 15b630122..6b1ff87d7 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -15,7 +15,7 @@ // - the lumps: one in a cell of a few texels at most, as the drops of the rain, the more snow around the likelier and bigger, // from a few mm to a few cm (most of them small), clear glass between them until the snow gets thick, then packed snow // overlapping into a cover. Wet (near zero, melting): lumps of slush, grey, translucent with a frosted core, bending the -// picture behind; dry: clumps of flakes +// picture behind; dry: crumbs and clumps of the flakes broken on the glass // - single crystals of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) // A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. // @@ -71,8 +71,8 @@ layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 2) uniform sampler layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 3) uniform sampler2D normalmap; // --- tuning ------------------------------------------------------------------------------------------------------------------ -const float snow_flake = 1.4; // size of a single crystal or a drop, texels of the map -const float snow_crystals = 0.12; // share of the texels with a little dry snow showing a single crystal +const float snow_flake = 1.1; // size of a single crystal or a drop, texels of the map (~5 mm) +const float snow_crystals = 0.05; // share of the texels with a little dry snow showing a single crystal const float snow_drops = 0.35; // share of the texels with the water of a melted flake showing a drop (more with more water) const float snow_layer = 0.6; // mm of snow around which a cell surely has a lump (fewer, smaller below) const float snow_layer_cell = 4.0; // a lump at most every this many texels (~2 cm) @@ -275,8 +275,8 @@ void snLayer(vec2 aspect, float pixelUV, inout sprite_acc acc) tile = (wet > 0.35) ? 14 : 12 + int(kind * 2.0); // slush, packed snow else if (wet > 0.2) tile = 8 + int(kind * 2.0); // wet lumps - else if (size < 0.7) - tile = 4 + int(kind * 2.0); // flakes of a few crystals + else if (size < 0.8) + tile = 6 + int(kind * 2.0); // crumbs (a flake breaks up hitting the glass) else tile = 10 + int(kind * 2.0); // clumps float thick = 1.0 - exp(-q.x / (snow_opaque * mix(1.0, 0.5, q.z))); diff --git a/shaders/vk14/water_snow.comp b/shaders/vk14/water_snow.comp index c69898985..dec133365 100644 --- a/shaders/vk14/water_snow.comp +++ b/shaders/vk14/water_snow.comp @@ -243,8 +243,10 @@ void main() float speed = water_snow.z; float density = mix(SNOW_FRESH, SNOW_PACKED, state.z); float wet = state.y / (state.y + state.x * density + 1e-4); - // the dry flakes bounce off a fast glass, the ones landing on wet snow or water stay - float sticking = 1.0 - 0.6 * smoothstep(15.0, 35.0, speed) * (1.0 - smoothstep(0.1, 0.4, wet)); + // the dry flakes bounce off a moving glass (powder is blown away), the wet ones (near zero) and those landing on wet snow or + // water stay + float dry = (1.0 - smoothstep(0.1, 0.4, wet)) * (1.0 - smoothstep(-3.0, 0.0, water_up.w)); + float sticking = 1.0 - 0.85 * smoothstep(5.0, 25.0, speed) * dry; float landings = water_snow.x / max(water_air.w, 0.1) * facing * area * seconds * sticking; vec4 random = water_random(place, snow_slot, water_counts.x, 0x5e0du); float count = min(floor(landings) + ((random.x < fract(landings)) ? 1.0 : 0.0), 4.0); From d8643c42a19a5bed3c444b80fbc5fffb5f33017c Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 19:53:12 +0100 Subject: [PATCH 077/123] Snow windscreen: sizes in metres of the glass, lumps in heaps The sprites were sized in texels of the map, and a glass taking only a part of its uv has big texels: crystals of a few cm (the big stars at speed), lumps in a coarse even grid. The crystals and drops are in cells of 6 mm of the glass now, the lumps in cells of 16 mm, from the size of the glass in the frames of its map. The lumps come in heaps (a random number every four cells, blended): likelier and bigger there, barer glass between; they sit anywhere in their cell. Single crystals are needles, plates, rarely a star. No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_snow_windscreen.frag | 99 +++++++++++++++----------- shaders/vk14/mat_snow_windscreen.frag | 99 +++++++++++++++----------- 2 files changed, 112 insertions(+), 86 deletions(-) diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index 9d27b96d9..ab60f2895 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -66,11 +66,12 @@ layout(binding = 2) uniform sampler2D wipermask; layout(binding = 3) uniform sampler2D normalmap; // --- tuning ------------------------------------------------------------------------------------------------------------------ -const float snow_flake = 1.1; // size of a single crystal or a drop, texels of the map (~5 mm) +const float snow_flake_cell = 0.006; // a single crystal or a drop at most every this many metres of the glass (its size) const float snow_crystals = 0.05; // share of the texels with a little dry snow showing a single crystal const float snow_drops = 0.35; // share of the texels with the water of a melted flake showing a drop (more with more water) const float snow_layer = 0.6; // mm of snow around which a cell surely has a lump (fewer, smaller below) -const float snow_layer_cell = 4.0; // a lump at most every this many texels (~2 cm) +const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) +const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) const float snow_thin = 0.45; // opacity of a single thin flake (ice crystals let most of the light through) const float snow_bump = 1.0; // strength of the relief from the normal map, 0 = flat @@ -182,63 +183,72 @@ vec3 snTone(vec4 q, float random) return tone * mix(vec3(1.0), vec3(0.88, 0.91, 0.94), smoothstep(0.3, 0.8, snWetness(q))); } -// the single crystals and the drops: on a few of the texels holding a little snow a crystal (dry snow) sits by itself between the -// lumps, on a few of those holding only water a drop of a melted flake -void snFlakes(vec2 aspect, float pixelUV, inout sprite_acc acc) +// the single crystals and the drops, in cells of snow_flake_cell metres of the glass: in a few of the cells holding a little dry +// snow a crystal sits by itself between the lumps, in some of those holding only water a drop of a melted flake +void snFlakes(vec2 span, float pixelUV, inout sprite_acc acc) { - vec2 p = f_coord * float(WATER_MAP); + vec2 perUV = span / snow_flake_cell; // cells in a unit of the uv + vec2 p = f_coord * perUV; ivec2 here = ivec2(floor(p)); for (int oy = -1; oy <= 1; ++oy) { for (int ox = -1; ox <= 1; ++ox) { - ivec2 texel = here + ivec2(ox, oy); - vec4 q = water_snow_texel(uint(snSlot), snMap, texel); + ivec2 cell = here + ivec2(ox, oy); + uint seed = Hash(uvec3(uvec2(cell + 8192), 17u + 7u * uint(snSlot))); + vec2 centre = vec2(cell) + 0.15 + 0.7 * vec2(RandF(seed), RandF(seed)); + vec4 q = water_snow_at(uint(snSlot), snMap, centre / perUV); bool drop = (q.x < 0.05) && (q.y > 0.03); bool crystal = (q.x >= 0.05) && (snWetness(q) < 0.25); if ((false == drop) && (false == crystal)) continue; - uint seed = Hash(uvec3(uvec2(texel), uint(q.w * 65535.0) + 7u * uint(snSlot))); if (RandF(seed) > (drop ? snow_drops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) continue; - vec2 centre = vec2(texel) + 0.2 + 0.6 * vec2(RandF(seed), RandF(seed)); float ang = RandF(seed) * 6.2831853; vec2 rot = vec2(cos(ang), sin(ang)); float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; float kind = RandF(seed); float random = RandF(seed); - float size = snow_flake * mix(0.6, 1.0, RandF(seed)) * (drop ? mix(0.7, 1.4, smoothstep(0.03, 0.3, q.y)) : 1.0); + float size = mix(0.6, 1.0, RandF(seed)) * (drop ? mix(0.7, 1.4, smoothstep(0.03, 0.3, q.y)) : 1.0); vec2 local; - if (false == snLocal(p, centre, size, aspect, rot, flip, 1.0, local)) + if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, 1.0, local)) continue; int tile = TILE_DROP; float alpha = smoothstep(0.03, 0.1, q.y); if (crystal) { - if (kind < 0.35) - tile = int(kind * 5.72); // star crystals (0, 1) - else if (kind < 0.5) - tile = 2; // a plate - else if (kind < 0.65) - tile = 3; // needles - else - tile = 4 + int((kind - 0.65) / 0.35 * 2.0); // flakes of a few crystals - tile = min(tile, 5); + tile = (kind < 0.4) ? 3 : ((kind < 0.7) ? 2 : int((kind - 0.7) / 0.3 * 2.0)); // needles, a plate, a star + tile = min(tile, 3); alpha = snow_thin; } - snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / float(WATER_MAP)), 1.0, acc); + snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0, acc); } } } -// the lumps: one in a cell of a few texels at most, as the drops of the rain: the more snow around it the likelier it's there -// and the bigger, sizes from a few mm to a few cm (most of them small), gaps of clear glass between them until the snow gets -// thick; then packed snow overlapping into a cover. wet: lumps of slush (grey, translucent, bending the picture behind); -// dry: clumps of flakes -void snLayer(vec2 aspect, float pixelUV, inout sprite_acc acc) +// how much a cell of the lumps lies in a heap: the snow landing side by side runs together, so the lumps come in heaps with +// barer glass between them; a random number for every few cells, blended between them (the same for every pixel of the cell) +float snHeap(ivec2 cell) { - float cells = float(WATER_MAP) / snow_layer_cell; - vec2 p = f_coord * cells; + vec2 c = (vec2(cell) + 0.5) / snow_heap_cells; + ivec2 i = ivec2(floor(c - 0.5)); + vec2 f = c - 0.5 - vec2(i); + f = f * f * (3.0 - 2.0 * f); + uint s00 = Hash(uvec3(uvec2(i + 8192), 53u)); + uint s10 = Hash(uvec3(uvec2(i + ivec2(1, 0) + 8192), 53u)); + uint s01 = Hash(uvec3(uvec2(i + ivec2(0, 1) + 8192), 53u)); + uint s11 = Hash(uvec3(uvec2(i + ivec2(1, 1) + 8192), 53u)); + return mix(mix(RandF(s00), RandF(s10), f.x), mix(RandF(s01), RandF(s11), f.x), f.y); +} + +// the lumps: one in a cell of snow_lump_cell metres of the glass at most, as the drops of the rain, the more snow around and the +// more the cell lies in a heap the likelier it's there and the bigger, sizes from a few mm to a few cm (most of them small), clear +// glass between the heaps until the snow gets thick; then packed snow overlapping into a cover. wet: lumps of slush (grey, +// translucent, bending the picture behind); dry: crumbs and clumps of the flakes broken on the glass +void snLayer(vec2 span, float pixelUV, inout sprite_acc acc) +{ + vec2 perUV = span / snow_lump_cell; + vec2 p = f_coord * perUV; ivec2 here = ivec2(floor(p)); for (int oy = -1; oy <= 1; ++oy) { @@ -246,9 +256,12 @@ void snLayer(vec2 aspect, float pixelUV, inout sprite_acc acc) { ivec2 cell = here + ivec2(ox, oy); uint seed = Hash(uvec3(uvec2(cell + 4096), 31u + 7u * uint(snSlot))); - vec2 centre = vec2(cell) + 0.25 + 0.5 * vec2(RandF(seed), RandF(seed)); - vec4 q = water_snow_at(uint(snSlot), snMap, centre / cells); - if (RandF(seed) >= smoothstep(snow_layer * 0.1, snow_layer * 2.0, q.x)) + vec2 centre = vec2(cell) + 0.1 + 0.8 * vec2(RandF(seed), RandF(seed)); + vec4 q = water_snow_at(uint(snSlot), snMap, centre / perUV); + float heap = snHeap(cell); + float cover = smoothstep(2.0, 5.0, q.x); // thick: the lumps grow into a cover + float present = smoothstep(snow_layer * 0.1, snow_layer * 2.0, q.x) * mix(0.25, 1.6, heap); + if (RandF(seed) >= max(present, cover)) continue; float ang = RandF(seed) * 6.2831853; vec2 rot = vec2(cos(ang), sin(ang)); @@ -256,14 +269,14 @@ void snLayer(vec2 aspect, float pixelUV, inout sprite_acc acc) float kind = RandF(seed); float random = RandF(seed); float aniso = mix(0.75, 1.0, RandF(seed)); - float cover = smoothstep(2.0, 5.0, q.x); // thick: the lumps grow into a cover float grow = RandF(seed); float wet = snWetness(q); - // wet lumps are bigger: the slush of a few flakes runs together - float size = mix(mix(0.5, 1.6, grow * grow) * mix(0.8, 1.3, smoothstep(snow_layer, 2.5, q.x)) * ((wet > 0.2) ? 1.25 : 1.0), - 2.0, cover); + // wet lumps are bigger (the slush of a few flakes runs together), so are those in a heap + float size = mix(0.5, 1.6, grow * grow) * mix(0.8, 1.3, smoothstep(snow_layer, 2.5, q.x)) * mix(0.75, 1.3, heap) + * ((wet > 0.2) ? 1.2 : 1.0); + size = mix(min(size, 1.9), 2.0, cover); vec2 local; - if (false == snLocal(p, centre, size, aspect, rot, flip, aniso, local)) + if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, aniso, local)) continue; int tile; if (cover > 0.5) @@ -276,7 +289,7 @@ void snLayer(vec2 aspect, float pixelUV, inout sprite_acc acc) tile = 10 + int(kind * 2.0); // clumps float thick = 1.0 - exp(-q.x / (snow_opaque * mix(1.0, 0.5, q.z))); float alpha = mix(0.75, 1.0, thick); - snSprite(local, min(tile, 14), alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / cells), 1.0, acc); + snSprite(local, min(tile, 14), alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0, acc); } } } @@ -307,13 +320,13 @@ void main() snSlot = int(param[2].z + 0.5) - 1; if ((snSlot >= 0) && (snSlot < WATER_SLOTS) && water_snow_map(uint(snSlot), snMap)) { - // the texels of the map as they lie on the glass (the uv may be stretched) + // the size of the glass, metres in a unit of its uv (the sizes of the snow are in metres: the glass may take a part of + // the uv only, or have it stretched) ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; - vec2 span = vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)); - vec2 aspect = (min(span.x, span.y) > 1e-6) ? span / max(span.x, span.y) : vec2(1.0); - snLayer(aspect, pixelUV, layer); - snFlakes(aspect, pixelUV, flakes); + vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); + snLayer(span, pixelUV, layer); + snFlakes(span, pixelUV, flakes); vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); // the picture behind thin flakes and a wet film is blurred diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index 6b1ff87d7..0ffc0c3ef 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -71,11 +71,12 @@ layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 2) uniform sampler layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 3) uniform sampler2D normalmap; // --- tuning ------------------------------------------------------------------------------------------------------------------ -const float snow_flake = 1.1; // size of a single crystal or a drop, texels of the map (~5 mm) +const float snow_flake_cell = 0.006; // a single crystal or a drop at most every this many metres of the glass (its size) const float snow_crystals = 0.05; // share of the texels with a little dry snow showing a single crystal const float snow_drops = 0.35; // share of the texels with the water of a melted flake showing a drop (more with more water) const float snow_layer = 0.6; // mm of snow around which a cell surely has a lump (fewer, smaller below) -const float snow_layer_cell = 4.0; // a lump at most every this many texels (~2 cm) +const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) +const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) const float snow_thin = 0.45; // opacity of a single thin flake (ice crystals let most of the light through) const float snow_bump = 1.0; // strength of the relief from the normal map, 0 = flat @@ -187,63 +188,72 @@ vec3 snTone(vec4 q, float random) return tone * mix(vec3(1.0), vec3(0.88, 0.91, 0.94), smoothstep(0.3, 0.8, snWetness(q))); } -// the single crystals and the drops: on a few of the texels holding a little snow a crystal (dry snow) sits by itself between the -// lumps, on a few of those holding only water a drop of a melted flake -void snFlakes(vec2 aspect, float pixelUV, inout sprite_acc acc) +// the single crystals and the drops, in cells of snow_flake_cell metres of the glass: in a few of the cells holding a little dry +// snow a crystal sits by itself between the lumps, in some of those holding only water a drop of a melted flake +void snFlakes(vec2 span, float pixelUV, inout sprite_acc acc) { - vec2 p = f_coord * float(WATER_MAP); + vec2 perUV = span / snow_flake_cell; // cells in a unit of the uv + vec2 p = f_coord * perUV; ivec2 here = ivec2(floor(p)); for (int oy = -1; oy <= 1; ++oy) { for (int ox = -1; ox <= 1; ++ox) { - ivec2 texel = here + ivec2(ox, oy); - vec4 q = water_snow_texel(uint(snSlot), snMap, texel); + ivec2 cell = here + ivec2(ox, oy); + uint seed = Hash(uvec3(uvec2(cell + 8192), 17u + 7u * uint(snSlot))); + vec2 centre = vec2(cell) + 0.15 + 0.7 * vec2(RandF(seed), RandF(seed)); + vec4 q = water_snow_at(uint(snSlot), snMap, centre / perUV); bool drop = (q.x < 0.05) && (q.y > 0.03); bool crystal = (q.x >= 0.05) && (snWetness(q) < 0.25); if ((false == drop) && (false == crystal)) continue; - uint seed = Hash(uvec3(uvec2(texel), uint(q.w * 65535.0) + 7u * uint(snSlot))); if (RandF(seed) > (drop ? snow_drops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) continue; - vec2 centre = vec2(texel) + 0.2 + 0.6 * vec2(RandF(seed), RandF(seed)); float ang = RandF(seed) * 6.2831853; vec2 rot = vec2(cos(ang), sin(ang)); float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; float kind = RandF(seed); float random = RandF(seed); - float size = snow_flake * mix(0.6, 1.0, RandF(seed)) * (drop ? mix(0.7, 1.4, smoothstep(0.03, 0.3, q.y)) : 1.0); + float size = mix(0.6, 1.0, RandF(seed)) * (drop ? mix(0.7, 1.4, smoothstep(0.03, 0.3, q.y)) : 1.0); vec2 local; - if (false == snLocal(p, centre, size, aspect, rot, flip, 1.0, local)) + if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, 1.0, local)) continue; int tile = TILE_DROP; float alpha = smoothstep(0.03, 0.1, q.y); if (crystal) { - if (kind < 0.35) - tile = int(kind * 5.72); // star crystals (0, 1) - else if (kind < 0.5) - tile = 2; // a plate - else if (kind < 0.65) - tile = 3; // needles - else - tile = 4 + int((kind - 0.65) / 0.35 * 2.0); // flakes of a few crystals - tile = min(tile, 5); + tile = (kind < 0.4) ? 3 : ((kind < 0.7) ? 2 : int((kind - 0.7) / 0.3 * 2.0)); // needles, a plate, a star + tile = min(tile, 3); alpha = snow_thin; } - snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / float(WATER_MAP)), 1.0, acc); + snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0, acc); } } } -// the lumps: one in a cell of a few texels at most, as the drops of the rain: the more snow around it the likelier it's there -// and the bigger, sizes from a few mm to a few cm (most of them small), gaps of clear glass between them until the snow gets -// thick; then packed snow overlapping into a cover. wet: lumps of slush (grey, translucent, bending the picture behind); -// dry: clumps of flakes -void snLayer(vec2 aspect, float pixelUV, inout sprite_acc acc) +// how much a cell of the lumps lies in a heap: the snow landing side by side runs together, so the lumps come in heaps with +// barer glass between them; a random number for every few cells, blended between them (the same for every pixel of the cell) +float snHeap(ivec2 cell) { - float cells = float(WATER_MAP) / snow_layer_cell; - vec2 p = f_coord * cells; + vec2 c = (vec2(cell) + 0.5) / snow_heap_cells; + ivec2 i = ivec2(floor(c - 0.5)); + vec2 f = c - 0.5 - vec2(i); + f = f * f * (3.0 - 2.0 * f); + uint s00 = Hash(uvec3(uvec2(i + 8192), 53u)); + uint s10 = Hash(uvec3(uvec2(i + ivec2(1, 0) + 8192), 53u)); + uint s01 = Hash(uvec3(uvec2(i + ivec2(0, 1) + 8192), 53u)); + uint s11 = Hash(uvec3(uvec2(i + ivec2(1, 1) + 8192), 53u)); + return mix(mix(RandF(s00), RandF(s10), f.x), mix(RandF(s01), RandF(s11), f.x), f.y); +} + +// the lumps: one in a cell of snow_lump_cell metres of the glass at most, as the drops of the rain, the more snow around and the +// more the cell lies in a heap the likelier it's there and the bigger, sizes from a few mm to a few cm (most of them small), clear +// glass between the heaps until the snow gets thick; then packed snow overlapping into a cover. wet: lumps of slush (grey, +// translucent, bending the picture behind); dry: crumbs and clumps of the flakes broken on the glass +void snLayer(vec2 span, float pixelUV, inout sprite_acc acc) +{ + vec2 perUV = span / snow_lump_cell; + vec2 p = f_coord * perUV; ivec2 here = ivec2(floor(p)); for (int oy = -1; oy <= 1; ++oy) { @@ -251,9 +261,12 @@ void snLayer(vec2 aspect, float pixelUV, inout sprite_acc acc) { ivec2 cell = here + ivec2(ox, oy); uint seed = Hash(uvec3(uvec2(cell + 4096), 31u + 7u * uint(snSlot))); - vec2 centre = vec2(cell) + 0.25 + 0.5 * vec2(RandF(seed), RandF(seed)); - vec4 q = water_snow_at(uint(snSlot), snMap, centre / cells); - if (RandF(seed) >= smoothstep(snow_layer * 0.1, snow_layer * 2.0, q.x)) + vec2 centre = vec2(cell) + 0.1 + 0.8 * vec2(RandF(seed), RandF(seed)); + vec4 q = water_snow_at(uint(snSlot), snMap, centre / perUV); + float heap = snHeap(cell); + float cover = smoothstep(2.0, 5.0, q.x); // thick: the lumps grow into a cover + float present = smoothstep(snow_layer * 0.1, snow_layer * 2.0, q.x) * mix(0.25, 1.6, heap); + if (RandF(seed) >= max(present, cover)) continue; float ang = RandF(seed) * 6.2831853; vec2 rot = vec2(cos(ang), sin(ang)); @@ -261,14 +274,14 @@ void snLayer(vec2 aspect, float pixelUV, inout sprite_acc acc) float kind = RandF(seed); float random = RandF(seed); float aniso = mix(0.75, 1.0, RandF(seed)); - float cover = smoothstep(2.0, 5.0, q.x); // thick: the lumps grow into a cover float grow = RandF(seed); float wet = snWetness(q); - // wet lumps are bigger: the slush of a few flakes runs together - float size = mix(mix(0.5, 1.6, grow * grow) * mix(0.8, 1.3, smoothstep(snow_layer, 2.5, q.x)) * ((wet > 0.2) ? 1.25 : 1.0), - 2.0, cover); + // wet lumps are bigger (the slush of a few flakes runs together), so are those in a heap + float size = mix(0.5, 1.6, grow * grow) * mix(0.8, 1.3, smoothstep(snow_layer, 2.5, q.x)) * mix(0.75, 1.3, heap) + * ((wet > 0.2) ? 1.2 : 1.0); + size = mix(min(size, 1.9), 2.0, cover); vec2 local; - if (false == snLocal(p, centre, size, aspect, rot, flip, aniso, local)) + if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, aniso, local)) continue; int tile; if (cover > 0.5) @@ -281,7 +294,7 @@ void snLayer(vec2 aspect, float pixelUV, inout sprite_acc acc) tile = 10 + int(kind * 2.0); // clumps float thick = 1.0 - exp(-q.x / (snow_opaque * mix(1.0, 0.5, q.z))); float alpha = mix(0.75, 1.0, thick); - snSprite(local, min(tile, 14), alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / cells), 1.0, acc); + snSprite(local, min(tile, 14), alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0, acc); } } } @@ -312,13 +325,13 @@ void main() snSlot = int(param[2].z + 0.5) - 1; if ((snSlot >= 0) && (snSlot < WATER_SLOTS) && water_snow_map(uint(snSlot), snMap)) { - // the texels of the map as they lie on the glass (the uv may be stretched) + // the size of the glass, metres in a unit of its uv (the sizes of the snow are in metres: the glass may take a part of + // the uv only, or have it stretched) ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; - vec2 span = vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)); - vec2 aspect = (min(span.x, span.y) > 1e-6) ? span / max(span.x, span.y) : vec2(1.0); - snLayer(aspect, pixelUV, layer); - snFlakes(aspect, pixelUV, flakes); + vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); + snLayer(span, pixelUV, layer); + snFlakes(span, pixelUV, flakes); vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); // the picture behind thin flakes and a wet film is blurred From 7e7ca904c08027df7239b11cf847e80d6329b69d Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 20:03:19 +0100 Subject: [PATCH 078/123] Snow windscreen: icy clumps of grains instead of star crystals, more of them The tiles of star crystals (single and in flakes, also around the clumps) are gone from the atlas: every dry tile is now an icy clump of grains, as the crumbs - a dot, a few grains, small and bigger clumps. Many more of them (35% of the 7 mm cells holding a little dry snow), the lumps cover the glass from 1.2 mm of snow (fully by 3.5 mm), and fewer dry flakes bounce off a moving glass (40% from 25 m/s), so the snow can plaster the glass. The atlas (snieg_atlas_maszyna.py) changes its tiles 0-5 and 10, 11. To be added to the SVN: textures/fx/snow-atlas.tga and textures/fx/snow_normalmap.tga. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_snow_windscreen.frag | 19 +++++++++---------- shaders/ogl46/water_snow.comp | 2 +- shaders/vk14/mat_snow_windscreen.frag | 19 +++++++++---------- shaders/vk14/water_snow.comp | 2 +- 4 files changed, 20 insertions(+), 22 deletions(-) diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index ab60f2895..7bfa2fb5b 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -15,11 +15,11 @@ // from a few mm to a few cm (most of them small), clear glass between them until the snow gets thick, then packed snow // overlapping into a cover. Wet (near zero, melting): lumps of slush, grey, translucent with a frosted core, bending the // picture behind; dry: crumbs and clumps of the flakes broken on the glass -// - single crystals of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) +// - dots and small puffs of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) // A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. // // Atlas / normalmap (snieg_atlas_maszyna.py), 4 x 4 tiles of 512 x 512 (2048 x 2048): -// 0, 1 star crystals 2 plate 3 needles 4, 5 flakes of a few crystals 6, 7 crumbs +// 0 a dot 1 dots 2, 3 small puffs 4, 5 puffs 6, 7 crumbs // 8, 9 wet lumps 10, 11 clumps 12, 13 packed snow 14 slush 15 drop // An older 2 x 2 atlas (1024 x 1024: fluffy flake, wet lump, crumbs, melted spot) still works, its tiles stand in for these. // @@ -66,8 +66,8 @@ layout(binding = 2) uniform sampler2D wipermask; layout(binding = 3) uniform sampler2D normalmap; // --- tuning ------------------------------------------------------------------------------------------------------------------ -const float snow_flake_cell = 0.006; // a single crystal or a drop at most every this many metres of the glass (its size) -const float snow_crystals = 0.05; // share of the texels with a little dry snow showing a single crystal +const float snow_flake_cell = 0.007; // a dot, a small puff or a drop at most every this many metres of the glass (its size) +const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff const float snow_drops = 0.35; // share of the texels with the water of a melted flake showing a drop (more with more water) const float snow_layer = 0.6; // mm of snow around which a cell surely has a lump (fewer, smaller below) const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) @@ -183,8 +183,8 @@ vec3 snTone(vec4 q, float random) return tone * mix(vec3(1.0), vec3(0.88, 0.91, 0.94), smoothstep(0.3, 0.8, snWetness(q))); } -// the single crystals and the drops, in cells of snow_flake_cell metres of the glass: in a few of the cells holding a little dry -// snow a crystal sits by itself between the lumps, in some of those holding only water a drop of a melted flake +// the dots and the drops, in cells of snow_flake_cell metres of the glass: in many of the cells holding a little dry snow a dot +// or a small puff sits between the lumps, in some of those holding only water a drop of a melted flake void snFlakes(vec2 span, float pixelUV, inout sprite_acc acc) { vec2 perUV = span / snow_flake_cell; // cells in a unit of the uv @@ -217,8 +217,7 @@ void snFlakes(vec2 span, float pixelUV, inout sprite_acc acc) float alpha = smoothstep(0.03, 0.1, q.y); if (crystal) { - tile = (kind < 0.4) ? 3 : ((kind < 0.7) ? 2 : int((kind - 0.7) / 0.3 * 2.0)); // needles, a plate, a star - tile = min(tile, 3); + tile = min(int(kind * 4.0), 3); // dots, small puffs alpha = snow_thin; } snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0, acc); @@ -259,7 +258,7 @@ void snLayer(vec2 span, float pixelUV, inout sprite_acc acc) vec2 centre = vec2(cell) + 0.1 + 0.8 * vec2(RandF(seed), RandF(seed)); vec4 q = water_snow_at(uint(snSlot), snMap, centre / perUV); float heap = snHeap(cell); - float cover = smoothstep(2.0, 5.0, q.x); // thick: the lumps grow into a cover + float cover = smoothstep(1.2, 3.5, q.x); // thick: the lumps grow into a cover float present = smoothstep(snow_layer * 0.1, snow_layer * 2.0, q.x) * mix(0.25, 1.6, heap); if (RandF(seed) >= max(present, cover)) continue; @@ -284,7 +283,7 @@ void snLayer(vec2 span, float pixelUV, inout sprite_acc acc) else if (wet > 0.2) tile = 8 + int(kind * 2.0); // wet lumps else if (size < 0.8) - tile = 6 + int(kind * 2.0); // crumbs (a flake breaks up hitting the glass) + tile = 4 + int(kind * 4.0); // puffs, crumbs (a flake breaks up hitting the glass) else tile = 10 + int(kind * 2.0); // clumps float thick = 1.0 - exp(-q.x / (snow_opaque * mix(1.0, 0.5, q.z))); diff --git a/shaders/ogl46/water_snow.comp b/shaders/ogl46/water_snow.comp index 0599beda4..ca93f111a 100644 --- a/shaders/ogl46/water_snow.comp +++ b/shaders/ogl46/water_snow.comp @@ -243,7 +243,7 @@ void main() // the dry flakes bounce off a moving glass (powder is blown away), the wet ones (near zero) and those landing on wet snow or // water stay float dry = (1.0 - smoothstep(0.1, 0.4, wet)) * (1.0 - smoothstep(-3.0, 0.0, water_up.w)); - float sticking = 1.0 - 0.85 * smoothstep(5.0, 25.0, speed) * dry; + float sticking = 1.0 - 0.4 * smoothstep(5.0, 25.0, speed) * dry; float landings = water_snow.x / max(water_air.w, 0.1) * facing * area * seconds * sticking; vec4 random = water_random(place, snow_slot, water_counts.x, 0x5e0du); float count = min(floor(landings) + ((random.x < fract(landings)) ? 1.0 : 0.0), 4.0); diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index 0ffc0c3ef..661bd2062 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -16,11 +16,11 @@ // from a few mm to a few cm (most of them small), clear glass between them until the snow gets thick, then packed snow // overlapping into a cover. Wet (near zero, melting): lumps of slush, grey, translucent with a frosted core, bending the // picture behind; dry: crumbs and clumps of the flakes broken on the glass -// - single crystals of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) +// - dots and small puffs of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) // A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. // // Atlas / normalmap (snieg_atlas_maszyna.py), 4 x 4 tiles of 512 x 512 (2048 x 2048): -// 0, 1 star crystals 2 plate 3 needles 4, 5 flakes of a few crystals 6, 7 crumbs +// 0 a dot 1 dots 2, 3 small puffs 4, 5 puffs 6, 7 crumbs // 8, 9 wet lumps 10, 11 clumps 12, 13 packed snow 14 slush 15 drop // An older 2 x 2 atlas (1024 x 1024: fluffy flake, wet lump, crumbs, melted spot) still works, its tiles stand in for these. // @@ -71,8 +71,8 @@ layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 2) uniform sampler layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 3) uniform sampler2D normalmap; // --- tuning ------------------------------------------------------------------------------------------------------------------ -const float snow_flake_cell = 0.006; // a single crystal or a drop at most every this many metres of the glass (its size) -const float snow_crystals = 0.05; // share of the texels with a little dry snow showing a single crystal +const float snow_flake_cell = 0.007; // a dot, a small puff or a drop at most every this many metres of the glass (its size) +const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff const float snow_drops = 0.35; // share of the texels with the water of a melted flake showing a drop (more with more water) const float snow_layer = 0.6; // mm of snow around which a cell surely has a lump (fewer, smaller below) const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) @@ -188,8 +188,8 @@ vec3 snTone(vec4 q, float random) return tone * mix(vec3(1.0), vec3(0.88, 0.91, 0.94), smoothstep(0.3, 0.8, snWetness(q))); } -// the single crystals and the drops, in cells of snow_flake_cell metres of the glass: in a few of the cells holding a little dry -// snow a crystal sits by itself between the lumps, in some of those holding only water a drop of a melted flake +// the dots and the drops, in cells of snow_flake_cell metres of the glass: in many of the cells holding a little dry snow a dot +// or a small puff sits between the lumps, in some of those holding only water a drop of a melted flake void snFlakes(vec2 span, float pixelUV, inout sprite_acc acc) { vec2 perUV = span / snow_flake_cell; // cells in a unit of the uv @@ -222,8 +222,7 @@ void snFlakes(vec2 span, float pixelUV, inout sprite_acc acc) float alpha = smoothstep(0.03, 0.1, q.y); if (crystal) { - tile = (kind < 0.4) ? 3 : ((kind < 0.7) ? 2 : int((kind - 0.7) / 0.3 * 2.0)); // needles, a plate, a star - tile = min(tile, 3); + tile = min(int(kind * 4.0), 3); // dots, small puffs alpha = snow_thin; } snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0, acc); @@ -264,7 +263,7 @@ void snLayer(vec2 span, float pixelUV, inout sprite_acc acc) vec2 centre = vec2(cell) + 0.1 + 0.8 * vec2(RandF(seed), RandF(seed)); vec4 q = water_snow_at(uint(snSlot), snMap, centre / perUV); float heap = snHeap(cell); - float cover = smoothstep(2.0, 5.0, q.x); // thick: the lumps grow into a cover + float cover = smoothstep(1.2, 3.5, q.x); // thick: the lumps grow into a cover float present = smoothstep(snow_layer * 0.1, snow_layer * 2.0, q.x) * mix(0.25, 1.6, heap); if (RandF(seed) >= max(present, cover)) continue; @@ -289,7 +288,7 @@ void snLayer(vec2 span, float pixelUV, inout sprite_acc acc) else if (wet > 0.2) tile = 8 + int(kind * 2.0); // wet lumps else if (size < 0.8) - tile = 6 + int(kind * 2.0); // crumbs (a flake breaks up hitting the glass) + tile = 4 + int(kind * 4.0); // puffs, crumbs (a flake breaks up hitting the glass) else tile = 10 + int(kind * 2.0); // clumps float thick = 1.0 - exp(-q.x / (snow_opaque * mix(1.0, 0.5, q.z))); diff --git a/shaders/vk14/water_snow.comp b/shaders/vk14/water_snow.comp index dec133365..b3b533628 100644 --- a/shaders/vk14/water_snow.comp +++ b/shaders/vk14/water_snow.comp @@ -246,7 +246,7 @@ void main() // the dry flakes bounce off a moving glass (powder is blown away), the wet ones (near zero) and those landing on wet snow or // water stay float dry = (1.0 - smoothstep(0.1, 0.4, wet)) * (1.0 - smoothstep(-3.0, 0.0, water_up.w)); - float sticking = 1.0 - 0.85 * smoothstep(5.0, 25.0, speed) * dry; + float sticking = 1.0 - 0.4 * smoothstep(5.0, 25.0, speed) * dry; float landings = water_snow.x / max(water_air.w, 0.1) * facing * area * seconds * sticking; vec4 random = water_random(place, snow_slot, water_counts.x, 0x5e0du); float count = min(floor(landings) + ((random.x < fract(landings)) ? 1.0 : 0.0), 4.0); From c5adb1db9b92a77f44dc15fa68896ba1f04b20d9 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 20:06:54 +0100 Subject: [PATCH 079/123] Snow windscreen: the same snow on the wiped glass as around it in frost A blade left a wet trace on any glass, and the snow landing on it there counted as wet: lumps of slush in the sweep, icy clumps around it. The trace is left only on a glass above zero now (none below -1 deg C, full from +1), and the water on a glass below zero freezes into packed snow (0.02 mm a second, from -2 deg C fully). No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/water_snow.comp | 24 +++++++++++++++++++----- shaders/vk14/water_snow.comp | 24 +++++++++++++++++++----- 2 files changed, 38 insertions(+), 10 deletions(-) diff --git a/shaders/ogl46/water_snow.comp b/shaders/ogl46/water_snow.comp index ca93f111a..7cb4f1473 100644 --- a/shaders/ogl46/water_snow.comp +++ b/shaders/ogl46/water_snow.comp @@ -49,6 +49,8 @@ const float SNOW_MELT = 0.003; const float SNOW_WARMTH = 1.5; // the share of a flake landing near zero already water (wet snow) const float SNOW_WET_FLAKES = 0.5; +// the water freezing a second on a glass below zero, mm +const float SNOW_FREEZE = 0.02; // the water drying a second, mm, and the share of a thin film going in a second (it dries and runs off as droplets) const float SNOW_DRY = 0.0004; const float SNOW_FILM_DRY = 0.15; @@ -220,7 +222,12 @@ void main() vec4 before = water_snow_texel(snow_slot, snow_from, texel); vec4 state = snow_move(texel, before, seconds); - // the blades: they take the snow where they went over + // how warm the glass is: warmer than the air (the cab heats it), the less so the faster the vehicle goes + float speed = water_snow.z; + float glass = water_up.w + water_snow.y * SNOW_WARMTH / (1.0 + speed / 25.0); + + // the blades: they take the snow where they went over; a wet trace only on a glass above zero (on a frozen one the blade + // leaves it dry, so the snow landing on the wiped glass is the same dry snow as around) bool crossed = false; for (int blade = 0; blade < 4; ++blade) crossed = crossed || snow_crossed(texel, blade); @@ -229,7 +236,8 @@ void main() float left = min(state.x * SNOW_WIPE_MISS, SNOW_WIPE_LEFT); float taken = state.x - left; state.x = left; - state.y = state.y * SNOW_WIPE_WATER + min(taken * mix(SNOW_FRESH, SNOW_PACKED, state.z) * SNOW_WIPE_TRACE, SNOW_WIPE_WET); + float trace = min(taken * mix(SNOW_FRESH, SNOW_PACKED, state.z) * SNOW_WIPE_TRACE, SNOW_WIPE_WET) * smoothstep(-1.0, 1.0, glass); + state.y = state.y * SNOW_WIPE_WATER + trace; } // the flakes landing @@ -237,7 +245,6 @@ void main() float area = length(cross(frame.tu, frame.tv)) / float(WATER_MAP * WATER_MAP); // m2 vec3 coming = water_air.xyz - water_up.xyz * water_air.w; // the snow against the cab, m/s float facing = max(-dot(coming, frame.normal), 0.0) + SNOW_EDDIES; - float speed = water_snow.z; float density = mix(SNOW_FRESH, SNOW_PACKED, state.z); float wet = state.y / (state.y + state.x * density + 1e-4); // the dry flakes bounce off a moving glass (powder is blown away), the wet ones (near zero) and those landing on wet snow or @@ -261,8 +268,15 @@ void main() state.x = snow; } - // the melting at the warm glass and the drying - float glass = water_up.w + water_snow.y * SNOW_WARMTH / (1.0 + speed / 25.0); + // the melting at the warm glass, the freezing at a frozen one (the water turns to ice, packed snow) and the drying + float frozen = min(state.y, SNOW_FREEZE * smoothstep(0.0, -2.0, glass) * seconds); + if (frozen > 0.0) + { + float ice = frozen / SNOW_PACKED; + state.z = (state.z * state.x + ice) / max(state.x + ice, 1e-4); + state.x += ice; + state.y -= frozen; + } float melted = min(SNOW_MELT * max(glass, 0.0) * seconds, state.x * density); state.x -= melted / max(density, 1e-3); float film = state.y * (1.0 - smoothstep(0.5, 3.0, state.x)); // the water not soaked into the snow diff --git a/shaders/vk14/water_snow.comp b/shaders/vk14/water_snow.comp index b3b533628..36a7125c6 100644 --- a/shaders/vk14/water_snow.comp +++ b/shaders/vk14/water_snow.comp @@ -52,6 +52,8 @@ const float SNOW_MELT = 0.003; const float SNOW_WARMTH = 1.5; // the share of a flake landing near zero already water (wet snow) const float SNOW_WET_FLAKES = 0.5; +// the water freezing a second on a glass below zero, mm +const float SNOW_FREEZE = 0.02; // the water drying a second, mm, and the share of a thin film going in a second (it dries and runs off as droplets) const float SNOW_DRY = 0.0004; const float SNOW_FILM_DRY = 0.15; @@ -223,7 +225,12 @@ void main() vec4 before = water_snow_texel(snow_slot, snow_from, texel); vec4 state = snow_move(texel, before, seconds); - // the blades: they take the snow where they went over + // how warm the glass is: warmer than the air (the cab heats it), the less so the faster the vehicle goes + float speed = water_snow.z; + float glass = water_up.w + water_snow.y * SNOW_WARMTH / (1.0 + speed / 25.0); + + // the blades: they take the snow where they went over; a wet trace only on a glass above zero (on a frozen one the blade + // leaves it dry, so the snow landing on the wiped glass is the same dry snow as around) bool crossed = false; for (int blade = 0; blade < 4; ++blade) crossed = crossed || snow_crossed(texel, blade); @@ -232,7 +239,8 @@ void main() float left = min(state.x * SNOW_WIPE_MISS, SNOW_WIPE_LEFT); float taken = state.x - left; state.x = left; - state.y = state.y * SNOW_WIPE_WATER + min(taken * mix(SNOW_FRESH, SNOW_PACKED, state.z) * SNOW_WIPE_TRACE, SNOW_WIPE_WET); + float trace = min(taken * mix(SNOW_FRESH, SNOW_PACKED, state.z) * SNOW_WIPE_TRACE, SNOW_WIPE_WET) * smoothstep(-1.0, 1.0, glass); + state.y = state.y * SNOW_WIPE_WATER + trace; } // the flakes landing @@ -240,7 +248,6 @@ void main() float area = length(cross(frame.tu, frame.tv)) / float(WATER_MAP * WATER_MAP); // m2 vec3 coming = water_air.xyz - water_up.xyz * water_air.w; // the snow against the cab, m/s float facing = max(-dot(coming, frame.normal), 0.0) + SNOW_EDDIES; - float speed = water_snow.z; float density = mix(SNOW_FRESH, SNOW_PACKED, state.z); float wet = state.y / (state.y + state.x * density + 1e-4); // the dry flakes bounce off a moving glass (powder is blown away), the wet ones (near zero) and those landing on wet snow or @@ -264,8 +271,15 @@ void main() state.x = snow; } - // the melting at the warm glass and the drying - float glass = water_up.w + water_snow.y * SNOW_WARMTH / (1.0 + speed / 25.0); + // the melting at the warm glass, the freezing at a frozen one (the water turns to ice, packed snow) and the drying + float frozen = min(state.y, SNOW_FREEZE * smoothstep(0.0, -2.0, glass) * seconds); + if (frozen > 0.0) + { + float ice = frozen / SNOW_PACKED; + state.z = (state.z * state.x + ice) / max(state.x + ice, 1e-4); + state.x += ice; + state.y -= frozen; + } float melted = min(SNOW_MELT * max(glass, 0.0) * seconds, state.x * density); state.x -= melted / max(density, 1e-3); float film = state.y * (1.0 - smoothstep(0.5, 3.0, state.x)); // the water not soaked into the snow From 0d770365ffcfa1d147075fb857f76ecbb5fc2ce7 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 20:11:55 +0100 Subject: [PATCH 080/123] Snow windscreen: the lumps close into a cover Too much clear glass stayed between the lumps. They're in two grids now, the second shifted by half a cell, so they overlap; a cell surely has a lump from 0.5 mm of snow (fewer below), the lumps are bigger, and they run together into a cover of packed snow from 0.7 mm (full from 2.1 mm), so the glass gets plastered. No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_snow_windscreen.frag | 21 ++++++++++++--------- shaders/vk14/mat_snow_windscreen.frag | 21 ++++++++++++--------- 2 files changed, 24 insertions(+), 18 deletions(-) diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index 7bfa2fb5b..39f61e5f2 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -69,7 +69,8 @@ layout(binding = 3) uniform sampler2D normalmap; const float snow_flake_cell = 0.007; // a dot, a small puff or a drop at most every this many metres of the glass (its size) const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff const float snow_drops = 0.35; // share of the texels with the water of a melted flake showing a drop (more with more water) -const float snow_layer = 0.6; // mm of snow around which a cell surely has a lump (fewer, smaller below) +const float snow_layer = 0.5; // mm of snow around which a cell surely has a lump (fewer, smaller below) +const float snow_cover = 0.7; // mm of snow from which the lumps run together into a cover (full at three times it) const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) @@ -244,22 +245,22 @@ float snHeap(ivec2 cell) // more the cell lies in a heap the likelier it's there and the bigger, sizes from a few mm to a few cm (most of them small), clear // glass between the heaps until the snow gets thick; then packed snow overlapping into a cover. wet: lumps of slush (grey, // translucent, bending the picture behind); dry: crumbs and clumps of the flakes broken on the glass -void snLayer(vec2 span, float pixelUV, inout sprite_acc acc) +void snLayer(vec2 span, float pixelUV, vec2 shift, uint salt, inout sprite_acc acc) { vec2 perUV = span / snow_lump_cell; - vec2 p = f_coord * perUV; + vec2 p = f_coord * perUV + shift; ivec2 here = ivec2(floor(p)); for (int oy = -1; oy <= 1; ++oy) { for (int ox = -1; ox <= 1; ++ox) { ivec2 cell = here + ivec2(ox, oy); - uint seed = Hash(uvec3(uvec2(cell + 4096), 31u + 7u * uint(snSlot))); + uint seed = Hash(uvec3(uvec2(cell + 4096), salt + 7u * uint(snSlot))); vec2 centre = vec2(cell) + 0.1 + 0.8 * vec2(RandF(seed), RandF(seed)); - vec4 q = water_snow_at(uint(snSlot), snMap, centre / perUV); + vec4 q = water_snow_at(uint(snSlot), snMap, (centre - shift) / perUV); float heap = snHeap(cell); - float cover = smoothstep(1.2, 3.5, q.x); // thick: the lumps grow into a cover - float present = smoothstep(snow_layer * 0.1, snow_layer * 2.0, q.x) * mix(0.25, 1.6, heap); + float cover = smoothstep(snow_cover, snow_cover * 3.0, q.x); // thick: the lumps grow into a cover + float present = smoothstep(snow_layer * 0.05, snow_layer, q.x) * mix(0.5, 1.8, heap); if (RandF(seed) >= max(present, cover)) continue; float ang = RandF(seed) * 6.2831853; @@ -271,7 +272,7 @@ void snLayer(vec2 span, float pixelUV, inout sprite_acc acc) float grow = RandF(seed); float wet = snWetness(q); // wet lumps are bigger (the slush of a few flakes runs together), so are those in a heap - float size = mix(0.5, 1.6, grow * grow) * mix(0.8, 1.3, smoothstep(snow_layer, 2.5, q.x)) * mix(0.75, 1.3, heap) + float size = mix(0.6, 1.7, grow * grow) * mix(0.9, 1.4, smoothstep(snow_layer * 0.5, snow_cover, q.x)) * mix(0.8, 1.3, heap) * ((wet > 0.2) ? 1.2 : 1.0); size = mix(min(size, 1.9), 2.0, cover); vec2 local; @@ -324,7 +325,9 @@ void main() ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); - snLayer(span, pixelUV, layer); + // two grids of lumps, the second shifted by half a cell: they overlap, so the snow closes into a cover + snLayer(span, pixelUV, vec2(0.0), 31u, layer); + snLayer(span, pixelUV, vec2(0.5), 77u, layer); snFlakes(span, pixelUV, flakes); vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index 661bd2062..41c50867d 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -74,7 +74,8 @@ layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 3) uniform sampler const float snow_flake_cell = 0.007; // a dot, a small puff or a drop at most every this many metres of the glass (its size) const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff const float snow_drops = 0.35; // share of the texels with the water of a melted flake showing a drop (more with more water) -const float snow_layer = 0.6; // mm of snow around which a cell surely has a lump (fewer, smaller below) +const float snow_layer = 0.5; // mm of snow around which a cell surely has a lump (fewer, smaller below) +const float snow_cover = 0.7; // mm of snow from which the lumps run together into a cover (full at three times it) const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) @@ -249,22 +250,22 @@ float snHeap(ivec2 cell) // more the cell lies in a heap the likelier it's there and the bigger, sizes from a few mm to a few cm (most of them small), clear // glass between the heaps until the snow gets thick; then packed snow overlapping into a cover. wet: lumps of slush (grey, // translucent, bending the picture behind); dry: crumbs and clumps of the flakes broken on the glass -void snLayer(vec2 span, float pixelUV, inout sprite_acc acc) +void snLayer(vec2 span, float pixelUV, vec2 shift, uint salt, inout sprite_acc acc) { vec2 perUV = span / snow_lump_cell; - vec2 p = f_coord * perUV; + vec2 p = f_coord * perUV + shift; ivec2 here = ivec2(floor(p)); for (int oy = -1; oy <= 1; ++oy) { for (int ox = -1; ox <= 1; ++ox) { ivec2 cell = here + ivec2(ox, oy); - uint seed = Hash(uvec3(uvec2(cell + 4096), 31u + 7u * uint(snSlot))); + uint seed = Hash(uvec3(uvec2(cell + 4096), salt + 7u * uint(snSlot))); vec2 centre = vec2(cell) + 0.1 + 0.8 * vec2(RandF(seed), RandF(seed)); - vec4 q = water_snow_at(uint(snSlot), snMap, centre / perUV); + vec4 q = water_snow_at(uint(snSlot), snMap, (centre - shift) / perUV); float heap = snHeap(cell); - float cover = smoothstep(1.2, 3.5, q.x); // thick: the lumps grow into a cover - float present = smoothstep(snow_layer * 0.1, snow_layer * 2.0, q.x) * mix(0.25, 1.6, heap); + float cover = smoothstep(snow_cover, snow_cover * 3.0, q.x); // thick: the lumps grow into a cover + float present = smoothstep(snow_layer * 0.05, snow_layer, q.x) * mix(0.5, 1.8, heap); if (RandF(seed) >= max(present, cover)) continue; float ang = RandF(seed) * 6.2831853; @@ -276,7 +277,7 @@ void snLayer(vec2 span, float pixelUV, inout sprite_acc acc) float grow = RandF(seed); float wet = snWetness(q); // wet lumps are bigger (the slush of a few flakes runs together), so are those in a heap - float size = mix(0.5, 1.6, grow * grow) * mix(0.8, 1.3, smoothstep(snow_layer, 2.5, q.x)) * mix(0.75, 1.3, heap) + float size = mix(0.6, 1.7, grow * grow) * mix(0.9, 1.4, smoothstep(snow_layer * 0.5, snow_cover, q.x)) * mix(0.8, 1.3, heap) * ((wet > 0.2) ? 1.2 : 1.0); size = mix(min(size, 1.9), 2.0, cover); vec2 local; @@ -329,7 +330,9 @@ void main() ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); - snLayer(span, pixelUV, layer); + // two grids of lumps, the second shifted by half a cell: they overlap, so the snow closes into a cover + snLayer(span, pixelUV, vec2(0.0), 31u, layer); + snLayer(span, pixelUV, vec2(0.5), 77u, layer); snFlakes(span, pixelUV, flakes); vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); From 21b3cefaeec51f4f3ce3b3fe16b2174c19725a32 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 20:19:12 +0100 Subject: [PATCH 081/123] Snow windscreen: the snow looks wet, refracts, and plasters the glass All the snow bends the picture behind it now through the post-processing (the icy lumps at 70% of the bend of a drop), not only the drops and the slush; the cover lets 10-30% of the light through and the snow glints more (gloss 0.8), so it looks wet in any frost. The lumps run together into a cover from 0.35 mm of snow (full by about 1 mm), and more snow comes to a glass not facing it (the eddies 0.6 m/s), so a standing cab's glass gets plastered too. No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_snow_windscreen.frag | 24 ++++++++++++------------ shaders/ogl46/water_snow.comp | 2 +- shaders/vk14/mat_snow_windscreen.frag | 24 ++++++++++++------------ shaders/vk14/water_snow.comp | 2 +- 4 files changed, 26 insertions(+), 26 deletions(-) diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index 39f61e5f2..0633b3161 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -69,14 +69,15 @@ layout(binding = 3) uniform sampler2D normalmap; const float snow_flake_cell = 0.007; // a dot, a small puff or a drop at most every this many metres of the glass (its size) const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff const float snow_drops = 0.35; // share of the texels with the water of a melted flake showing a drop (more with more water) -const float snow_layer = 0.5; // mm of snow around which a cell surely has a lump (fewer, smaller below) -const float snow_cover = 0.7; // mm of snow from which the lumps run together into a cover (full at three times it) +const float snow_layer = 0.3; // mm of snow around which a cell surely has a lump (fewer, smaller below) +const float snow_cover = 0.35; // mm of snow from which the lumps run together into a cover (full at three times it) const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) const float snow_thin = 0.45; // opacity of a single thin flake (ice crystals let most of the light through) const float snow_bump = 1.0; // strength of the relief from the normal map, 0 = flat -const float snow_gloss = 0.45; // glints of the sun / headlights on the snow, 0 = matt +const float snow_gloss = 0.8; // glints of the sun / headlights on the wet snow, 0 = matt +const float snow_ice_bend = 0.7; // how strongly the icy snow bends the picture behind it, of the bend of a drop const float snow_translucency = 0.8; // glow of thin snow when you look towards the sun / a lamp, 0 = off const float snow_haze = 1.0; // blur of the scene behind thin snow (frosted glass), 0 = off const float snow_drop_bend = 1.0; // how strongly the drops bend the picture behind them @@ -145,12 +146,11 @@ void snSprite(vec2 local, int tile, float alpha, vec3 tone, vec2 rot, float flip acc.n = nT * a + acc.n * (1.0 - a); acc.tr = (1.0 - t.a * 0.55) * a + acc.tr * (1.0 - a); acc.a = a + acc.a * (1.0 - a); - // the drops and the wet lumps bend the picture behind them (water, slush), as the drops of the rain - if ((tile == TILE_DROP) || (tile == 8) || (tile == 9) || (tile == 14)) - { - snBend = snBend * (1.0 - a) + nuv * a; - snBendA = snBendA * (1.0 - a) + a; - } + // all the snow bends the picture behind it (wet icy snow, slush, drops), as the drops of the rain; the drops and the slush + // the most + float bends = ((tile == TILE_DROP) || (tile == 8) || (tile == 9) || (tile == 14)) ? 1.0 : snow_ice_bend; + snBend = snBend * (1.0 - a) + nuv * bends * a; + snBendA = snBendA * (1.0 - a) + a; } // where in a sprite the pixel is: P the pixel and C the centre of the sprite, in the units of its grid (the size of the sprite @@ -288,7 +288,7 @@ void snLayer(vec2 span, float pixelUV, vec2 shift, uint salt, inout sprite_acc a else tile = 10 + int(kind * 2.0); // clumps float thick = 1.0 - exp(-q.x / (snow_opaque * mix(1.0, 0.5, q.z))); - float alpha = mix(0.75, 1.0, thick); + float alpha = mix(0.7, 0.9, thick); // wet icy snow lets some light (and the bent picture) through snSprite(local, min(tile, 14), alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0, acc); } } @@ -384,9 +384,9 @@ void main() { vec4 req = vec4(0.0); float clear = 1.0 - smoothstep(0.5, 0.95, glassA); - if ((snBendA > 0.25) && (glassA < 0.5)) + if ((snBendA > 0.1) && (glassA < 0.5)) { - vec2 bend = clamp(-snBend / max(snBendA, 1e-3) * snow_drop_bend, vec2(-1.0), vec2(1.0)) * smoothstep(0.25, 0.6, snBendA); + vec2 bend = clamp(-snBend / max(snBendA, 1e-3) * snow_drop_bend, vec2(-1.0), vec2(1.0)) * smoothstep(0.1, 0.4, snBendA); req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); } else diff --git a/shaders/ogl46/water_snow.comp b/shaders/ogl46/water_snow.comp index 7cb4f1473..afd939c77 100644 --- a/shaders/ogl46/water_snow.comp +++ b/shaders/ogl46/water_snow.comp @@ -30,7 +30,7 @@ const float SNOW_PACKED = 0.4; const float SNOW_FLAKE_LEAST = 0.3; const float SNOW_FLAKE_MOST = 2.5; // the speed of the snow coming at the glass in the eddies of the air, m/s: a glass not facing the snow gets a little of it -const float SNOW_EDDIES = 0.25; +const float SNOW_EDDIES = 0.6; // the most snow a texel holds, mm, and the step of the snow to a neighbour it holds without slipping onto it, mm const float SNOW_MOST = 40.0; const float SNOW_REPOSE = 3.0; diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index 41c50867d..7953f6cdc 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -74,14 +74,15 @@ layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 3) uniform sampler const float snow_flake_cell = 0.007; // a dot, a small puff or a drop at most every this many metres of the glass (its size) const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff const float snow_drops = 0.35; // share of the texels with the water of a melted flake showing a drop (more with more water) -const float snow_layer = 0.5; // mm of snow around which a cell surely has a lump (fewer, smaller below) -const float snow_cover = 0.7; // mm of snow from which the lumps run together into a cover (full at three times it) +const float snow_layer = 0.3; // mm of snow around which a cell surely has a lump (fewer, smaller below) +const float snow_cover = 0.35; // mm of snow from which the lumps run together into a cover (full at three times it) const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) const float snow_thin = 0.45; // opacity of a single thin flake (ice crystals let most of the light through) const float snow_bump = 1.0; // strength of the relief from the normal map, 0 = flat -const float snow_gloss = 0.45; // glints of the sun / headlights on the snow, 0 = matt +const float snow_gloss = 0.8; // glints of the sun / headlights on the wet snow, 0 = matt +const float snow_ice_bend = 0.7; // how strongly the icy snow bends the picture behind it, of the bend of a drop const float snow_translucency = 0.8; // glow of thin snow when you look towards the sun / a lamp, 0 = off const float snow_haze = 1.0; // blur of the scene behind thin snow (frosted glass), 0 = off const float snow_drop_bend = 1.0; // how strongly the drops bend the picture behind them @@ -150,12 +151,11 @@ void snSprite(vec2 local, int tile, float alpha, vec3 tone, vec2 rot, float flip acc.n = nT * a + acc.n * (1.0 - a); acc.tr = (1.0 - t.a * 0.55) * a + acc.tr * (1.0 - a); acc.a = a + acc.a * (1.0 - a); - // the drops and the wet lumps bend the picture behind them (water, slush), as the drops of the rain - if ((tile == TILE_DROP) || (tile == 8) || (tile == 9) || (tile == 14)) - { - snBend = snBend * (1.0 - a) + nuv * a; - snBendA = snBendA * (1.0 - a) + a; - } + // all the snow bends the picture behind it (wet icy snow, slush, drops), as the drops of the rain; the drops and the slush + // the most + float bends = ((tile == TILE_DROP) || (tile == 8) || (tile == 9) || (tile == 14)) ? 1.0 : snow_ice_bend; + snBend = snBend * (1.0 - a) + nuv * bends * a; + snBendA = snBendA * (1.0 - a) + a; } // where in a sprite the pixel is: P the pixel and C the centre of the sprite, in the units of its grid (the size of the sprite @@ -293,7 +293,7 @@ void snLayer(vec2 span, float pixelUV, vec2 shift, uint salt, inout sprite_acc a else tile = 10 + int(kind * 2.0); // clumps float thick = 1.0 - exp(-q.x / (snow_opaque * mix(1.0, 0.5, q.z))); - float alpha = mix(0.75, 1.0, thick); + float alpha = mix(0.7, 0.9, thick); // wet icy snow lets some light (and the bent picture) through snSprite(local, min(tile, 14), alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0, acc); } } @@ -389,9 +389,9 @@ void main() { vec4 req = vec4(0.0); float clear = 1.0 - smoothstep(0.5, 0.95, glassA); - if ((snBendA > 0.25) && (glassA < 0.5)) + if ((snBendA > 0.1) && (glassA < 0.5)) { - vec2 bend = clamp(-snBend / max(snBendA, 1e-3) * snow_drop_bend, vec2(-1.0), vec2(1.0)) * smoothstep(0.25, 0.6, snBendA); + vec2 bend = clamp(-snBend / max(snBendA, 1e-3) * snow_drop_bend, vec2(-1.0), vec2(1.0)) * smoothstep(0.1, 0.4, snBendA); req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); } else diff --git a/shaders/vk14/water_snow.comp b/shaders/vk14/water_snow.comp index 36a7125c6..a2f1f8b6c 100644 --- a/shaders/vk14/water_snow.comp +++ b/shaders/vk14/water_snow.comp @@ -33,7 +33,7 @@ const float SNOW_PACKED = 0.4; const float SNOW_FLAKE_LEAST = 0.3; const float SNOW_FLAKE_MOST = 2.5; // the speed of the snow coming at the glass in the eddies of the air, m/s: a glass not facing the snow gets a little of it -const float SNOW_EDDIES = 0.25; +const float SNOW_EDDIES = 0.6; // the most snow a texel holds, mm, and the step of the snow to a neighbour it holds without slipping onto it, mm const float SNOW_MOST = 40.0; const float SNOW_REPOSE = 3.0; From 9c891272a2748e989b2e7845e3a1b0c0c0cd6054 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 20:26:11 +0100 Subject: [PATCH 082/123] Snow windscreen: the snow stays on a moving glass until it's plastered At speed the air blew the thin dry snow along and off the glass as fast as it came, and the glass warmed by the cab melted it near zero, so the glass never got covered. The air blows only the thinnest powder (below 0.2-0.6 mm, a quarter as fast), the glass is as warm as the given warmth (not 1.5x) and the air cools it sooner (/(1 + v/10)), and the lumps close into a cover from 0.25 mm. No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_snow_windscreen.frag | 2 +- shaders/ogl46/water_snow.comp | 8 ++++---- shaders/vk14/mat_snow_windscreen.frag | 2 +- shaders/vk14/water_snow.comp | 8 ++++---- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index 0633b3161..a785f14b9 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -70,7 +70,7 @@ const float snow_flake_cell = 0.007; // a dot, a small puff or a drop at most ev const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff const float snow_drops = 0.35; // share of the texels with the water of a melted flake showing a drop (more with more water) const float snow_layer = 0.3; // mm of snow around which a cell surely has a lump (fewer, smaller below) -const float snow_cover = 0.35; // mm of snow from which the lumps run together into a cover (full at three times it) +const float snow_cover = 0.25; // mm of snow from which the lumps run together into a cover (full at three times it) const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) diff --git a/shaders/ogl46/water_snow.comp b/shaders/ogl46/water_snow.comp index afd939c77..dd3a369c0 100644 --- a/shaders/ogl46/water_snow.comp +++ b/shaders/ogl46/water_snow.comp @@ -46,7 +46,7 @@ const float SNOW_WIPE_WET = 0.015; // the water the snow melts into at the glass a second for each degree the glass is above zero, mm const float SNOW_MELT = 0.003; // how much warmer than the air the glass is, the share of the warmth given (water_snow.y, the cab heats it) -const float SNOW_WARMTH = 1.5; +const float SNOW_WARMTH = 1.0; // the share of a flake landing near zero already water (wet snow) const float SNOW_WET_FLAKES = 0.5; // the water freezing a second on a glass below zero, mm @@ -57,7 +57,7 @@ const float SNOW_FILM_DRY = 0.15; // how fast slush slides down a vertical glass, how fast dry powder goes with the air (a share of the speed of the air along the // glass), how fast the film of water runs down a vertical glass and goes with the air, m/s const float SNOW_SLIDE = 0.03; -const float SNOW_BLOW = 0.004; +const float SNOW_BLOW = 0.001; const float SNOW_RUN = 0.02; const float SNOW_RUN_AIR = 0.002; @@ -137,7 +137,7 @@ vec4 snow_motion(ivec2 texel, vec4 state) float wet = state.y / (state.y + state.x * density + 1e-4); // slush: wet and heavy enough to go; dry powder: loose and thin enough to be blown float slide = SNOW_SLIDE * smoothstep(0.25, 0.7, wet) * smoothstep(2.0, 8.0, state.x); - float blow = SNOW_BLOW * smoothstep(10.0, 25.0, wind) * (1.0 - state.z) * (1.0 - smoothstep(0.1, 0.3, wet)) * (1.0 - smoothstep(1.0, 4.0, state.x)); + float blow = SNOW_BLOW * smoothstep(10.0, 25.0, wind) * (1.0 - state.z) * (1.0 - smoothstep(0.1, 0.3, wet)) * (1.0 - smoothstep(0.2, 0.6, state.x)); vec3 snow = slope * slide + air * blow; // the film of water runs where there's enough of it, not the water soaked into the snow float film = (1.0 - smoothstep(0.5, 3.0, state.x)); @@ -224,7 +224,7 @@ void main() // how warm the glass is: warmer than the air (the cab heats it), the less so the faster the vehicle goes float speed = water_snow.z; - float glass = water_up.w + water_snow.y * SNOW_WARMTH / (1.0 + speed / 25.0); + float glass = water_up.w + water_snow.y * SNOW_WARMTH / (1.0 + speed / 10.0); // the blades: they take the snow where they went over; a wet trace only on a glass above zero (on a frozen one the blade // leaves it dry, so the snow landing on the wiped glass is the same dry snow as around) diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index 7953f6cdc..d7cb09f28 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -75,7 +75,7 @@ const float snow_flake_cell = 0.007; // a dot, a small puff or a drop at most ev const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff const float snow_drops = 0.35; // share of the texels with the water of a melted flake showing a drop (more with more water) const float snow_layer = 0.3; // mm of snow around which a cell surely has a lump (fewer, smaller below) -const float snow_cover = 0.35; // mm of snow from which the lumps run together into a cover (full at three times it) +const float snow_cover = 0.25; // mm of snow from which the lumps run together into a cover (full at three times it) const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) diff --git a/shaders/vk14/water_snow.comp b/shaders/vk14/water_snow.comp index a2f1f8b6c..d972d2052 100644 --- a/shaders/vk14/water_snow.comp +++ b/shaders/vk14/water_snow.comp @@ -49,7 +49,7 @@ const float SNOW_WIPE_WET = 0.015; // the water the snow melts into at the glass a second for each degree the glass is above zero, mm const float SNOW_MELT = 0.003; // how much warmer than the air the glass is, the share of the warmth given (water_snow.y, the cab heats it) -const float SNOW_WARMTH = 1.5; +const float SNOW_WARMTH = 1.0; // the share of a flake landing near zero already water (wet snow) const float SNOW_WET_FLAKES = 0.5; // the water freezing a second on a glass below zero, mm @@ -60,7 +60,7 @@ const float SNOW_FILM_DRY = 0.15; // how fast slush slides down a vertical glass, how fast dry powder goes with the air (a share of the speed of the air along the // glass), how fast the film of water runs down a vertical glass and goes with the air, m/s const float SNOW_SLIDE = 0.03; -const float SNOW_BLOW = 0.004; +const float SNOW_BLOW = 0.001; const float SNOW_RUN = 0.02; const float SNOW_RUN_AIR = 0.002; @@ -140,7 +140,7 @@ vec4 snow_motion(ivec2 texel, vec4 state) float wet = state.y / (state.y + state.x * density + 1e-4); // slush: wet and heavy enough to go; dry powder: loose and thin enough to be blown float slide = SNOW_SLIDE * smoothstep(0.25, 0.7, wet) * smoothstep(2.0, 8.0, state.x); - float blow = SNOW_BLOW * smoothstep(10.0, 25.0, wind) * (1.0 - state.z) * (1.0 - smoothstep(0.1, 0.3, wet)) * (1.0 - smoothstep(1.0, 4.0, state.x)); + float blow = SNOW_BLOW * smoothstep(10.0, 25.0, wind) * (1.0 - state.z) * (1.0 - smoothstep(0.1, 0.3, wet)) * (1.0 - smoothstep(0.2, 0.6, state.x)); vec3 snow = slope * slide + air * blow; // the film of water runs where there's enough of it, not the water soaked into the snow float film = (1.0 - smoothstep(0.5, 3.0, state.x)); @@ -227,7 +227,7 @@ void main() // how warm the glass is: warmer than the air (the cab heats it), the less so the faster the vehicle goes float speed = water_snow.z; - float glass = water_up.w + water_snow.y * SNOW_WARMTH / (1.0 + speed / 25.0); + float glass = water_up.w + water_snow.y * SNOW_WARMTH / (1.0 + speed / 10.0); // the blades: they take the snow where they went over; a wet trace only on a glass above zero (on a frozen one the blade // leaves it dry, so the snow landing on the wiped glass is the same dry snow as around) From 092637afa8c262ee2b39f9e9d38e09fe64ff2cc2 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 20:31:49 +0100 Subject: [PATCH 083/123] Snow windscreen: the snow piles up into an opaque cover The lumps of a cell only changed their tile and size as the snow grew, and the cover stayed translucent (at most 90%), so the glass never closed. A third grid of lumps lies on top of the cover now (it piles up), the cover sprites are bigger (2.4 cells), and from 0.75 mm the cover thickens to opaque at 2.5 mm, bending the picture behind less and less. No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_snow_windscreen.frag | 26 ++++++++++++++++---------- shaders/vk14/mat_snow_windscreen.frag | 26 ++++++++++++++++---------- 2 files changed, 32 insertions(+), 20 deletions(-) diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index a785f14b9..bce56173d 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -70,6 +70,7 @@ const float snow_flake_cell = 0.007; // a dot, a small puff or a drop at most ev const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff const float snow_drops = 0.35; // share of the texels with the water of a melted flake showing a drop (more with more water) const float snow_layer = 0.3; // mm of snow around which a cell surely has a lump (fewer, smaller below) +const float snow_deep = 2.5; // mm of snow from which the cover is opaque (no picture behind it) const float snow_cover = 0.25; // mm of snow from which the lumps run together into a cover (full at three times it) const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) @@ -130,7 +131,7 @@ float snTileSize() } // a sprite over the accumulator: Local the place in it (0 .. 1), Rot its rotation (cos, sin), Tone its colour -void snSprite(vec2 local, int tile, float alpha, vec3 tone, vec2 rot, float flip, float lod, float bump, inout sprite_acc acc) +void snSprite(vec2 local, int tile, float alpha, vec3 tone, vec2 rot, float flip, float lod, float bend, inout sprite_acc acc) { vec2 uv = snTile(tile) + local * snTileSize(); vec4 t = textureLod(raindropsatlas, uv, lod); @@ -138,7 +139,7 @@ void snSprite(vec2 local, int tile, float alpha, vec3 tone, vec2 rot, float flip float a = clamp(t.a * alpha, 0.0, 1.0); if (a <= 0.002) return; - vec2 nxy = (n.rg * 2.0 - 1.0) * snow_bump * bump; + vec2 nxy = (n.rg * 2.0 - 1.0) * snow_bump; nxy.x *= flip; vec2 nuv = vec2(rot.x * nxy.x - rot.y * nxy.y, rot.y * nxy.x + rot.x * nxy.y); vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); @@ -148,7 +149,7 @@ void snSprite(vec2 local, int tile, float alpha, vec3 tone, vec2 rot, float flip acc.a = a + acc.a * (1.0 - a); // all the snow bends the picture behind it (wet icy snow, slush, drops), as the drops of the rain; the drops and the slush // the most - float bends = ((tile == TILE_DROP) || (tile == 8) || (tile == 9) || (tile == 14)) ? 1.0 : snow_ice_bend; + float bends = (((tile == TILE_DROP) || (tile == 8) || (tile == 9) || (tile == 14)) ? 1.0 : snow_ice_bend) * bend; snBend = snBend * (1.0 - a) + nuv * bends * a; snBendA = snBendA * (1.0 - a) + a; } @@ -245,7 +246,7 @@ float snHeap(ivec2 cell) // more the cell lies in a heap the likelier it's there and the bigger, sizes from a few mm to a few cm (most of them small), clear // glass between the heaps until the snow gets thick; then packed snow overlapping into a cover. wet: lumps of slush (grey, // translucent, bending the picture behind); dry: crumbs and clumps of the flakes broken on the glass -void snLayer(vec2 span, float pixelUV, vec2 shift, uint salt, inout sprite_acc acc) +void snLayer(vec2 span, float pixelUV, vec2 shift, uint salt, bool covers, inout sprite_acc acc) { vec2 perUV = span / snow_lump_cell; vec2 p = f_coord * perUV + shift; @@ -259,7 +260,8 @@ void snLayer(vec2 span, float pixelUV, vec2 shift, uint salt, inout sprite_acc a vec2 centre = vec2(cell) + 0.1 + 0.8 * vec2(RandF(seed), RandF(seed)); vec4 q = water_snow_at(uint(snSlot), snMap, (centre - shift) / perUV); float heap = snHeap(cell); - float cover = smoothstep(snow_cover, snow_cover * 3.0, q.x); // thick: the lumps grow into a cover + // thick: the lumps grow into a cover (the grids that make it), the lumps of the last grid lie on it + float cover = covers ? smoothstep(snow_cover, snow_cover * 3.0, q.x) : 0.0; float present = smoothstep(snow_layer * 0.05, snow_layer, q.x) * mix(0.5, 1.8, heap); if (RandF(seed) >= max(present, cover)) continue; @@ -274,7 +276,7 @@ void snLayer(vec2 span, float pixelUV, vec2 shift, uint salt, inout sprite_acc a // wet lumps are bigger (the slush of a few flakes runs together), so are those in a heap float size = mix(0.6, 1.7, grow * grow) * mix(0.9, 1.4, smoothstep(snow_layer * 0.5, snow_cover, q.x)) * mix(0.8, 1.3, heap) * ((wet > 0.2) ? 1.2 : 1.0); - size = mix(min(size, 1.9), 2.0, cover); + size = mix(min(size, 1.9), 2.4, cover); vec2 local; if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, aniso, local)) continue; @@ -288,8 +290,10 @@ void snLayer(vec2 span, float pixelUV, vec2 shift, uint salt, inout sprite_acc a else tile = 10 + int(kind * 2.0); // clumps float thick = 1.0 - exp(-q.x / (snow_opaque * mix(1.0, 0.5, q.z))); - float alpha = mix(0.7, 0.9, thick); // wet icy snow lets some light (and the bent picture) through - snSprite(local, min(tile, 14), alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0, acc); + // thin wet icy snow lets some light (and the bent picture) through, a thick layer none + float deep = smoothstep(snow_cover * 3.0, snow_deep, q.x); + float alpha = mix(mix(0.7, 0.9, thick), 1.0, deep); + snSprite(local, min(tile, 14), alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0 - deep, acc); } } } @@ -326,8 +330,10 @@ void main() uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); // two grids of lumps, the second shifted by half a cell: they overlap, so the snow closes into a cover - snLayer(span, pixelUV, vec2(0.0), 31u, layer); - snLayer(span, pixelUV, vec2(0.5), 77u, layer); + snLayer(span, pixelUV, vec2(0.0), 31u, true, layer); + snLayer(span, pixelUV, vec2(0.5), 77u, true, layer); + // and the lumps lying on the cover: the snow piles up rather than changes + snLayer(span, pixelUV, vec2(0.25, 0.75), 113u, false, layer); snFlakes(span, pixelUV, flakes); vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index d7cb09f28..648eed85f 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -75,6 +75,7 @@ const float snow_flake_cell = 0.007; // a dot, a small puff or a drop at most ev const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff const float snow_drops = 0.35; // share of the texels with the water of a melted flake showing a drop (more with more water) const float snow_layer = 0.3; // mm of snow around which a cell surely has a lump (fewer, smaller below) +const float snow_deep = 2.5; // mm of snow from which the cover is opaque (no picture behind it) const float snow_cover = 0.25; // mm of snow from which the lumps run together into a cover (full at three times it) const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) @@ -135,7 +136,7 @@ float snTileSize() } // a sprite over the accumulator: Local the place in it (0 .. 1), Rot its rotation (cos, sin), Tone its colour -void snSprite(vec2 local, int tile, float alpha, vec3 tone, vec2 rot, float flip, float lod, float bump, inout sprite_acc acc) +void snSprite(vec2 local, int tile, float alpha, vec3 tone, vec2 rot, float flip, float lod, float bend, inout sprite_acc acc) { vec2 uv = snTile(tile) + local * snTileSize(); vec4 t = textureLod(raindropsatlas, uv, lod); @@ -143,7 +144,7 @@ void snSprite(vec2 local, int tile, float alpha, vec3 tone, vec2 rot, float flip float a = clamp(t.a * alpha, 0.0, 1.0); if (a <= 0.002) return; - vec2 nxy = (n.rg * 2.0 - 1.0) * snow_bump * bump; + vec2 nxy = (n.rg * 2.0 - 1.0) * snow_bump; nxy.x *= flip; vec2 nuv = vec2(rot.x * nxy.x - rot.y * nxy.y, rot.y * nxy.x + rot.x * nxy.y); vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); @@ -153,7 +154,7 @@ void snSprite(vec2 local, int tile, float alpha, vec3 tone, vec2 rot, float flip acc.a = a + acc.a * (1.0 - a); // all the snow bends the picture behind it (wet icy snow, slush, drops), as the drops of the rain; the drops and the slush // the most - float bends = ((tile == TILE_DROP) || (tile == 8) || (tile == 9) || (tile == 14)) ? 1.0 : snow_ice_bend; + float bends = (((tile == TILE_DROP) || (tile == 8) || (tile == 9) || (tile == 14)) ? 1.0 : snow_ice_bend) * bend; snBend = snBend * (1.0 - a) + nuv * bends * a; snBendA = snBendA * (1.0 - a) + a; } @@ -250,7 +251,7 @@ float snHeap(ivec2 cell) // more the cell lies in a heap the likelier it's there and the bigger, sizes from a few mm to a few cm (most of them small), clear // glass between the heaps until the snow gets thick; then packed snow overlapping into a cover. wet: lumps of slush (grey, // translucent, bending the picture behind); dry: crumbs and clumps of the flakes broken on the glass -void snLayer(vec2 span, float pixelUV, vec2 shift, uint salt, inout sprite_acc acc) +void snLayer(vec2 span, float pixelUV, vec2 shift, uint salt, bool covers, inout sprite_acc acc) { vec2 perUV = span / snow_lump_cell; vec2 p = f_coord * perUV + shift; @@ -264,7 +265,8 @@ void snLayer(vec2 span, float pixelUV, vec2 shift, uint salt, inout sprite_acc a vec2 centre = vec2(cell) + 0.1 + 0.8 * vec2(RandF(seed), RandF(seed)); vec4 q = water_snow_at(uint(snSlot), snMap, (centre - shift) / perUV); float heap = snHeap(cell); - float cover = smoothstep(snow_cover, snow_cover * 3.0, q.x); // thick: the lumps grow into a cover + // thick: the lumps grow into a cover (the grids that make it), the lumps of the last grid lie on it + float cover = covers ? smoothstep(snow_cover, snow_cover * 3.0, q.x) : 0.0; float present = smoothstep(snow_layer * 0.05, snow_layer, q.x) * mix(0.5, 1.8, heap); if (RandF(seed) >= max(present, cover)) continue; @@ -279,7 +281,7 @@ void snLayer(vec2 span, float pixelUV, vec2 shift, uint salt, inout sprite_acc a // wet lumps are bigger (the slush of a few flakes runs together), so are those in a heap float size = mix(0.6, 1.7, grow * grow) * mix(0.9, 1.4, smoothstep(snow_layer * 0.5, snow_cover, q.x)) * mix(0.8, 1.3, heap) * ((wet > 0.2) ? 1.2 : 1.0); - size = mix(min(size, 1.9), 2.0, cover); + size = mix(min(size, 1.9), 2.4, cover); vec2 local; if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, aniso, local)) continue; @@ -293,8 +295,10 @@ void snLayer(vec2 span, float pixelUV, vec2 shift, uint salt, inout sprite_acc a else tile = 10 + int(kind * 2.0); // clumps float thick = 1.0 - exp(-q.x / (snow_opaque * mix(1.0, 0.5, q.z))); - float alpha = mix(0.7, 0.9, thick); // wet icy snow lets some light (and the bent picture) through - snSprite(local, min(tile, 14), alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0, acc); + // thin wet icy snow lets some light (and the bent picture) through, a thick layer none + float deep = smoothstep(snow_cover * 3.0, snow_deep, q.x); + float alpha = mix(mix(0.7, 0.9, thick), 1.0, deep); + snSprite(local, min(tile, 14), alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0 - deep, acc); } } } @@ -331,8 +335,10 @@ void main() uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); // two grids of lumps, the second shifted by half a cell: they overlap, so the snow closes into a cover - snLayer(span, pixelUV, vec2(0.0), 31u, layer); - snLayer(span, pixelUV, vec2(0.5), 77u, layer); + snLayer(span, pixelUV, vec2(0.0), 31u, true, layer); + snLayer(span, pixelUV, vec2(0.5), 77u, true, layer); + // and the lumps lying on the cover: the snow piles up rather than changes + snLayer(span, pixelUV, vec2(0.25, 0.75), 113u, false, layer); snFlakes(span, pixelUV, flakes); vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); From 12218fc6d7bf623aa043c87115bd39010a22374c Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 20:42:25 +0100 Subject: [PATCH 084/123] Snow windscreen: the map gets all the snowfall, and melts as fast as it can Two reasons the glass never got plastered: - the flakes a second the renderer gives (water_snow.x) are a quarter of the snowfall (the 0.25 of perground, meant to thin out the particles of the drop passes), so the map got a quarter of the snow: a glass not facing the motion (standing, side windows) built up 0.4 mm a minute, 6.5 minutes to opaque. It takes all of it now (x4): 1.5 mm a minute. - the warm glass melted 0.003 mm of water a second for each degree above zero, ~1 kW/m2 a degree, so near zero a standing cab melted the snow 4-5 times as fast as it came. 0.0002 mm (~70 W/m2 a degree) now. No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/water_snow.comp | 10 +++++++--- shaders/vk14/water_snow.comp | 10 +++++++--- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/shaders/ogl46/water_snow.comp b/shaders/ogl46/water_snow.comp index dd3a369c0..251800ed1 100644 --- a/shaders/ogl46/water_snow.comp +++ b/shaders/ogl46/water_snow.comp @@ -43,8 +43,12 @@ const float SNOW_WIPE_LEFT = 0.03; const float SNOW_WIPE_WATER = 0.1; const float SNOW_WIPE_TRACE = 0.08; const float SNOW_WIPE_WET = 0.015; -// the water the snow melts into at the glass a second for each degree the glass is above zero, mm -const float SNOW_MELT = 0.003; +// the water the snow melts into at the glass a second for each degree the glass is above zero, mm (the heat the glass passes on, +// ~70 W/m2 a degree, melts 0.0002 mm of water a second) +const float SNOW_MELT = 0.0002; +// the share of the snowfall the flakes of water_snow.x make (the renderer counts a quarter of them, as for the particles of the +// drop passes): the snow of the map gets all of it +const float SNOW_FALL_SHARE = 4.0; // how much warmer than the air the glass is, the share of the warmth given (water_snow.y, the cab heats it) const float SNOW_WARMTH = 1.0; // the share of a flake landing near zero already water (wet snow) @@ -251,7 +255,7 @@ void main() // water stay float dry = (1.0 - smoothstep(0.1, 0.4, wet)) * (1.0 - smoothstep(-3.0, 0.0, water_up.w)); float sticking = 1.0 - 0.4 * smoothstep(5.0, 25.0, speed) * dry; - float landings = water_snow.x / max(water_air.w, 0.1) * facing * area * seconds * sticking; + float landings = water_snow.x * SNOW_FALL_SHARE / max(water_air.w, 0.1) * facing * area * seconds * sticking; vec4 random = water_random(place, snow_slot, water_counts.x, 0x5e0du); float count = min(floor(landings) + ((random.x < fract(landings)) ? 1.0 : 0.0), 4.0); if (count > 0.0) diff --git a/shaders/vk14/water_snow.comp b/shaders/vk14/water_snow.comp index d972d2052..fcafd5bc5 100644 --- a/shaders/vk14/water_snow.comp +++ b/shaders/vk14/water_snow.comp @@ -46,8 +46,12 @@ const float SNOW_WIPE_LEFT = 0.03; const float SNOW_WIPE_WATER = 0.1; const float SNOW_WIPE_TRACE = 0.08; const float SNOW_WIPE_WET = 0.015; -// the water the snow melts into at the glass a second for each degree the glass is above zero, mm -const float SNOW_MELT = 0.003; +// the water the snow melts into at the glass a second for each degree the glass is above zero, mm (the heat the glass passes on, +// ~70 W/m2 a degree, melts 0.0002 mm of water a second) +const float SNOW_MELT = 0.0002; +// the share of the snowfall the flakes of water_snow.x make (the renderer counts a quarter of them, as for the particles of the +// drop passes): the snow of the map gets all of it +const float SNOW_FALL_SHARE = 4.0; // how much warmer than the air the glass is, the share of the warmth given (water_snow.y, the cab heats it) const float SNOW_WARMTH = 1.0; // the share of a flake landing near zero already water (wet snow) @@ -254,7 +258,7 @@ void main() // water stay float dry = (1.0 - smoothstep(0.1, 0.4, wet)) * (1.0 - smoothstep(-3.0, 0.0, water_up.w)); float sticking = 1.0 - 0.4 * smoothstep(5.0, 25.0, speed) * dry; - float landings = water_snow.x / max(water_air.w, 0.1) * facing * area * seconds * sticking; + float landings = water_snow.x * SNOW_FALL_SHARE / max(water_air.w, 0.1) * facing * area * seconds * sticking; vec4 random = water_random(place, snow_slot, water_counts.x, 0x5e0du); float count = min(floor(landings) + ((random.x < fract(landings)) ? 1.0 : 0.0), 4.0); if (count > 0.0) From 2450612eeb14c657352d2450957a02547fe0f9b7 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 20:54:48 +0100 Subject: [PATCH 085/123] Snow windscreen: wet thick snow closes the glass, flakes stick to snow - The cover of wet snow (wetness above 0.35, near zero, where the flakes land half melted) was drawn with the slush tile, translucent by itself (alpha ~0.4), so a glass covered in any amount of it never closed. The cover is packed snow once it gets thick (from 0.75 mm, opaque at 2.5 mm), greyer when wet by its tone; slush only while it's thin. - The dry flakes bounced off a moving glass also where snow lay already, so the wiped glass (bare, wet from the blade) caught more of them than the snow around it. They bounce off a bare glass only now (below 0.05-0.3 mm of snow); on snow they stick. No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_snow_windscreen.frag | 8 +++++--- shaders/ogl46/water_snow.comp | 3 ++- shaders/vk14/mat_snow_windscreen.frag | 8 +++++--- shaders/vk14/water_snow.comp | 3 ++- 4 files changed, 14 insertions(+), 8 deletions(-) diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index bce56173d..d9624fa3d 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -280,9 +280,13 @@ void snLayer(vec2 span, float pixelUV, vec2 shift, uint salt, bool covers, inout vec2 local; if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, aniso, local)) continue; + // thin wet icy snow lets some light (and the bent picture) through, a thick layer none + float deep = smoothstep(snow_cover * 3.0, snow_deep, q.x); int tile; + // the cover: slush while it's thin and wet; thick snow is packed snow however wet it is (the slush tile is translucent + // by itself, a glass covered with it never closes; the wet one is greyer by its tone) if (cover > 0.5) - tile = (wet > 0.35) ? 14 : 12 + int(kind * 2.0); // slush, packed snow + tile = ((wet > 0.35) && (deep < 0.5)) ? 14 : 12 + int(kind * 2.0); else if (wet > 0.2) tile = 8 + int(kind * 2.0); // wet lumps else if (size < 0.8) @@ -290,8 +294,6 @@ void snLayer(vec2 span, float pixelUV, vec2 shift, uint salt, bool covers, inout else tile = 10 + int(kind * 2.0); // clumps float thick = 1.0 - exp(-q.x / (snow_opaque * mix(1.0, 0.5, q.z))); - // thin wet icy snow lets some light (and the bent picture) through, a thick layer none - float deep = smoothstep(snow_cover * 3.0, snow_deep, q.x); float alpha = mix(mix(0.7, 0.9, thick), 1.0, deep); snSprite(local, min(tile, 14), alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0 - deep, acc); } diff --git a/shaders/ogl46/water_snow.comp b/shaders/ogl46/water_snow.comp index 251800ed1..313d67866 100644 --- a/shaders/ogl46/water_snow.comp +++ b/shaders/ogl46/water_snow.comp @@ -253,7 +253,8 @@ void main() float wet = state.y / (state.y + state.x * density + 1e-4); // the dry flakes bounce off a moving glass (powder is blown away), the wet ones (near zero) and those landing on wet snow or // water stay - float dry = (1.0 - smoothstep(0.1, 0.4, wet)) * (1.0 - smoothstep(-3.0, 0.0, water_up.w)); + // (only on a bare glass: a flake sticks to the snow already there) + float dry = (1.0 - smoothstep(0.1, 0.4, wet)) * (1.0 - smoothstep(-3.0, 0.0, water_up.w)) * (1.0 - smoothstep(0.05, 0.3, state.x)); float sticking = 1.0 - 0.4 * smoothstep(5.0, 25.0, speed) * dry; float landings = water_snow.x * SNOW_FALL_SHARE / max(water_air.w, 0.1) * facing * area * seconds * sticking; vec4 random = water_random(place, snow_slot, water_counts.x, 0x5e0du); diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index 648eed85f..3c72e913f 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -285,9 +285,13 @@ void snLayer(vec2 span, float pixelUV, vec2 shift, uint salt, bool covers, inout vec2 local; if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, aniso, local)) continue; + // thin wet icy snow lets some light (and the bent picture) through, a thick layer none + float deep = smoothstep(snow_cover * 3.0, snow_deep, q.x); int tile; + // the cover: slush while it's thin and wet; thick snow is packed snow however wet it is (the slush tile is translucent + // by itself, a glass covered with it never closes; the wet one is greyer by its tone) if (cover > 0.5) - tile = (wet > 0.35) ? 14 : 12 + int(kind * 2.0); // slush, packed snow + tile = ((wet > 0.35) && (deep < 0.5)) ? 14 : 12 + int(kind * 2.0); else if (wet > 0.2) tile = 8 + int(kind * 2.0); // wet lumps else if (size < 0.8) @@ -295,8 +299,6 @@ void snLayer(vec2 span, float pixelUV, vec2 shift, uint salt, bool covers, inout else tile = 10 + int(kind * 2.0); // clumps float thick = 1.0 - exp(-q.x / (snow_opaque * mix(1.0, 0.5, q.z))); - // thin wet icy snow lets some light (and the bent picture) through, a thick layer none - float deep = smoothstep(snow_cover * 3.0, snow_deep, q.x); float alpha = mix(mix(0.7, 0.9, thick), 1.0, deep); snSprite(local, min(tile, 14), alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0 - deep, acc); } diff --git a/shaders/vk14/water_snow.comp b/shaders/vk14/water_snow.comp index fcafd5bc5..52345a264 100644 --- a/shaders/vk14/water_snow.comp +++ b/shaders/vk14/water_snow.comp @@ -256,7 +256,8 @@ void main() float wet = state.y / (state.y + state.x * density + 1e-4); // the dry flakes bounce off a moving glass (powder is blown away), the wet ones (near zero) and those landing on wet snow or // water stay - float dry = (1.0 - smoothstep(0.1, 0.4, wet)) * (1.0 - smoothstep(-3.0, 0.0, water_up.w)); + // (only on a bare glass: a flake sticks to the snow already there) + float dry = (1.0 - smoothstep(0.1, 0.4, wet)) * (1.0 - smoothstep(-3.0, 0.0, water_up.w)) * (1.0 - smoothstep(0.05, 0.3, state.x)); float sticking = 1.0 - 0.4 * smoothstep(5.0, 25.0, speed) * dry; float landings = water_snow.x * SNOW_FALL_SHARE / max(water_air.w, 0.1) * facing * area * seconds * sticking; vec4 random = water_random(place, snow_slot, water_counts.x, 0x5e0du); From 873937b3a8b680cbc6cf0bd2554f99002316b8d4 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 21:01:37 +0100 Subject: [PATCH 086/123] Snow windscreen: a front glass at speed gets the snow coming at it A front glass at speed built up its snow no faster than a standing one: the flakes come at a glass by the relative wind along its outward normal, and the outward side of the frames of the map (from the middle of the box around the cab model) and the air against the cab (from the matrix of the vehicle and its velocity) don't agree for every cab; with them disagreeing the glass got the snow of the eddies only (1.5 mm a minute), never closed between the lumps. The glass takes the snow coming at it along its normal from either side now (the glass the driver looks through leads); where the sides agree nothing changes. No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/water_snow.comp | 7 ++++++- shaders/vk14/water_snow.comp | 7 ++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/shaders/ogl46/water_snow.comp b/shaders/ogl46/water_snow.comp index 313d67866..7680b570e 100644 --- a/shaders/ogl46/water_snow.comp +++ b/shaders/ogl46/water_snow.comp @@ -248,7 +248,12 @@ void main() water_frame_s frame = snow_frame(texel); float area = length(cross(frame.tu, frame.tv)) / float(WATER_MAP * WATER_MAP); // m2 vec3 coming = water_air.xyz - water_up.xyz * water_air.w; // the snow against the cab, m/s - float facing = max(-dot(coming, frame.normal), 0.0) + SNOW_EDDIES; + // the snow coming at the glass along its normal. the side of the glass the snow comes from isn't told: the outward side of + // the frames of the map (from the middle of the box around the cab model) and the air against the cab (from the matrix of + // the vehicle and its velocity) don't agree for every cab, and with them disagreeing a front glass at speed got the snow of + // the eddies only, plastered no faster than a standing one. the glass the driver looks through leads, so the snow comes at + // it from the outside + float facing = abs(dot(coming, frame.normal)) + SNOW_EDDIES; float density = mix(SNOW_FRESH, SNOW_PACKED, state.z); float wet = state.y / (state.y + state.x * density + 1e-4); // the dry flakes bounce off a moving glass (powder is blown away), the wet ones (near zero) and those landing on wet snow or diff --git a/shaders/vk14/water_snow.comp b/shaders/vk14/water_snow.comp index 52345a264..4a8ee2dcb 100644 --- a/shaders/vk14/water_snow.comp +++ b/shaders/vk14/water_snow.comp @@ -251,7 +251,12 @@ void main() water_frame_s frame = snow_frame(texel); float area = length(cross(frame.tu, frame.tv)) / float(WATER_MAP * WATER_MAP); // m2 vec3 coming = water_air.xyz - water_up.xyz * water_air.w; // the snow against the cab, m/s - float facing = max(-dot(coming, frame.normal), 0.0) + SNOW_EDDIES; + // the snow coming at the glass along its normal. the side of the glass the snow comes from isn't told: the outward side of + // the frames of the map (from the middle of the box around the cab model) and the air against the cab (from the matrix of + // the vehicle and its velocity) don't agree for every cab, and with them disagreeing a front glass at speed got the snow of + // the eddies only, plastered no faster than a standing one. the glass the driver looks through leads, so the snow comes at + // it from the outside + float facing = abs(dot(coming, frame.normal)) + SNOW_EDDIES; float density = mix(SNOW_FRESH, SNOW_PACKED, state.z); float wet = state.y / (state.y + state.x * density + 1e-4); // the dry flakes bounce off a moving glass (powder is blown away), the wet ones (near zero) and those landing on wet snow or From cd7fcd03a26873ba47f735f3850d7029a0313c38 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 21:09:53 +0100 Subject: [PATCH 087/123] Snow windscreen: the refraction doesn't punch holes into the snow The bend request of the snow (all of it since the wet look) makes the post-processing put 85% of the picture from the bent place, up to 96 px away, in place of the pixel, with the snow drawn in it: an opaque pixel of snow took the colour of a gap of the snow elsewhere, so the gaps spread over the cover and it never closed, however much snow lay there. The bend is scaled down by the opacity of the snow now (none from 95%): the snow bends the picture only where it lets the light through. No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_snow_windscreen.frag | 6 +++++- shaders/vk14/mat_snow_windscreen.frag | 6 +++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index d9624fa3d..4c37aad5f 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -394,7 +394,11 @@ void main() float clear = 1.0 - smoothstep(0.5, 0.95, glassA); if ((snBendA > 0.1) && (glassA < 0.5)) { - vec2 bend = clamp(-snBend / max(snBendA, 1e-3) * snow_drop_bend, vec2(-1.0), vec2(1.0)) * smoothstep(0.1, 0.4, snBendA); + // the post-processing puts the picture from the bent place in place of this pixel, snow and all (85% of it): through + // snow it hides, the snow itself would be replaced by the picture from a place up to 96 px away, a gap of the snow + // there showing here, so an opaque cover would never close. bent only as much as the snow lets the light through + float through = 1.0 - smoothstep(0.5, 0.95, snowA); + vec2 bend = clamp(-snBend / max(snBendA, 1e-3) * snow_drop_bend, vec2(-1.0), vec2(1.0)) * smoothstep(0.1, 0.4, snBendA) * through; req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); } else diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index 3c72e913f..259126d9a 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -399,7 +399,11 @@ void main() float clear = 1.0 - smoothstep(0.5, 0.95, glassA); if ((snBendA > 0.1) && (glassA < 0.5)) { - vec2 bend = clamp(-snBend / max(snBendA, 1e-3) * snow_drop_bend, vec2(-1.0), vec2(1.0)) * smoothstep(0.1, 0.4, snBendA); + // the post-processing puts the picture from the bent place in place of this pixel, snow and all (85% of it): through + // snow it hides, the snow itself would be replaced by the picture from a place up to 96 px away, a gap of the snow + // there showing here, so an opaque cover would never close. bent only as much as the snow lets the light through + float through = 1.0 - smoothstep(0.5, 0.95, snowA); + vec2 bend = clamp(-snBend / max(snBendA, 1e-3) * snow_drop_bend, vec2(-1.0), vec2(1.0)) * smoothstep(0.1, 0.4, snBendA) * through; req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); } else From c0589ae696766ea950312df227ef77ed2a1835ea Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 21:25:48 +0100 Subject: [PATCH 088/123] Snow windscreen: lumps that stay, in five grids that pile up A cell of the lumps picked its tile, size and whether it was there at all from the snow of the map every frame: as the snow grew it turned from crumbs to a clump to a lump of packed snow, and the dots came and went with the wetness, so what had landed kept changing and the glass never filled. Each cell has its lump fixed once now (tile, place, turn, size, and the snow it takes); it comes when the snow around reaches that, grows a little, and stays until the snow goes. Five grids, shifted, come one after the other as the snow piles up (dots and crumbs, puffs, clumps, two of packed snow), each on the ones before, closing the glass by 3 mm; sooner in a heap. The dots don't depend on the wetness. No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_snow_windscreen.frag | 89 ++++++++++++-------------- shaders/vk14/mat_snow_windscreen.frag | 89 ++++++++++++-------------- 2 files changed, 82 insertions(+), 96 deletions(-) diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index 4c37aad5f..795401135 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -11,10 +11,10 @@ // the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. // // The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen: -// - the lumps: one in a cell of a few texels at most, as the drops of the rain, the more snow around the likelier and bigger, -// from a few mm to a few cm (most of them small), clear glass between them until the snow gets thick, then packed snow -// overlapping into a cover. Wet (near zero, melting): lumps of slush, grey, translucent with a frosted core, bending the -// picture behind; dry: crumbs and clumps of the flakes broken on the glass +// - the lumps, in five grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, +// size, the snow it takes); it comes when the snow around reaches that and stays as it is until the snow goes. The grids come +// one after the other as the snow piles up (dots and crumbs, puffs, clumps, then two of packed snow), each on the ones before, +// so the snow accumulates rather than changes, and closes the glass by 3 mm. In a heap they come sooner // - dots and small puffs of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) // A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. // @@ -69,9 +69,8 @@ layout(binding = 3) uniform sampler2D normalmap; const float snow_flake_cell = 0.007; // a dot, a small puff or a drop at most every this many metres of the glass (its size) const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff const float snow_drops = 0.35; // share of the texels with the water of a melted flake showing a drop (more with more water) -const float snow_layer = 0.3; // mm of snow around which a cell surely has a lump (fewer, smaller below) const float snow_deep = 2.5; // mm of snow from which the cover is opaque (no picture behind it) -const float snow_cover = 0.25; // mm of snow from which the lumps run together into a cover (full at three times it) +const float snow_cover = 0.25; // the lumps get opaque from three times this many mm of snow const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) @@ -201,7 +200,7 @@ void snFlakes(vec2 span, float pixelUV, inout sprite_acc acc) vec2 centre = vec2(cell) + 0.15 + 0.7 * vec2(RandF(seed), RandF(seed)); vec4 q = water_snow_at(uint(snSlot), snMap, centre / perUV); bool drop = (q.x < 0.05) && (q.y > 0.03); - bool crystal = (q.x >= 0.05) && (snWetness(q) < 0.25); + bool crystal = (q.x >= 0.05); if ((false == drop) && (false == crystal)) continue; if (RandF(seed) > (drop ? snow_drops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) @@ -242,60 +241,52 @@ float snHeap(ivec2 cell) return mix(mix(RandF(s00), RandF(s10), f.x), mix(RandF(s01), RandF(s11), f.x), f.y); } -// the lumps: one in a cell of snow_lump_cell metres of the glass at most, as the drops of the rain, the more snow around and the -// more the cell lies in a heap the likelier it's there and the bigger, sizes from a few mm to a few cm (most of them small), clear -// glass between the heaps until the snow gets thick; then packed snow overlapping into a cover. wet: lumps of slush (grey, -// translucent, bending the picture behind); dry: crumbs and clumps of the flakes broken on the glass -void snLayer(vec2 span, float pixelUV, vec2 shift, uint salt, bool covers, inout sprite_acc acc) +// the lumps, in grids of cells of snow_lump_cell metres of the glass, shifted against each other. every cell of a grid has its +// lump fixed once (its tile, place, turn, size and the snow it takes to be there): the lump comes when the snow of the map around +// it reaches that, grows a little with more snow, and stays as it is until the snow goes (a blade, the melting); it never turns +// into another lump. the grids come one after the other as the snow piles up: dots and crumbs first, then puffs, clumps, and last +// the big lumps of packed snow which close the glass. in a heap (the snow landing side by side runs together) they come sooner +struct lump_grid +{ + vec2 shift; // the grid shifted, cells + uint salt; + vec2 snow; // the snow it takes for a lump of the grid to come, mm: from .. to (random per cell) + vec2 size; // the size of its lumps, cells: from .. to (random per cell) + int tiles; // its tiles: the first one and how many + int count; +}; + +void snLumps(vec2 span, float pixelUV, lump_grid grid, inout sprite_acc acc) { vec2 perUV = span / snow_lump_cell; - vec2 p = f_coord * perUV + shift; + vec2 p = f_coord * perUV + grid.shift; ivec2 here = ivec2(floor(p)); for (int oy = -1; oy <= 1; ++oy) { for (int ox = -1; ox <= 1; ++ox) { ivec2 cell = here + ivec2(ox, oy); - uint seed = Hash(uvec3(uvec2(cell + 4096), salt + 7u * uint(snSlot))); + uint seed = Hash(uvec3(uvec2(cell + 4096), grid.salt + 7u * uint(snSlot))); vec2 centre = vec2(cell) + 0.1 + 0.8 * vec2(RandF(seed), RandF(seed)); - vec4 q = water_snow_at(uint(snSlot), snMap, (centre - shift) / perUV); - float heap = snHeap(cell); - // thick: the lumps grow into a cover (the grids that make it), the lumps of the last grid lie on it - float cover = covers ? smoothstep(snow_cover, snow_cover * 3.0, q.x) : 0.0; - float present = smoothstep(snow_layer * 0.05, snow_layer, q.x) * mix(0.5, 1.8, heap); - if (RandF(seed) >= max(present, cover)) + // the snow it takes, sooner in a heap + float needs = mix(grid.snow.x, grid.snow.y, RandF(seed)) * mix(1.4, 0.6, snHeap(cell)); + vec4 q = water_snow_at(uint(snSlot), snMap, (centre - grid.shift) / perUV); + if (q.x <= needs) continue; float ang = RandF(seed) * 6.2831853; vec2 rot = vec2(cos(ang), sin(ang)); float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; - float kind = RandF(seed); + int tile = grid.tiles + min(int(RandF(seed) * float(grid.count)), grid.count - 1); float random = RandF(seed); - float aniso = mix(0.75, 1.0, RandF(seed)); - float grow = RandF(seed); - float wet = snWetness(q); - // wet lumps are bigger (the slush of a few flakes runs together), so are those in a heap - float size = mix(0.6, 1.7, grow * grow) * mix(0.9, 1.4, smoothstep(snow_layer * 0.5, snow_cover, q.x)) * mix(0.8, 1.3, heap) - * ((wet > 0.2) ? 1.2 : 1.0); - size = mix(min(size, 1.9), 2.4, cover); + float aniso = mix(0.8, 1.0, RandF(seed)); + float size = mix(grid.size.x, grid.size.y, RandF(seed)) * mix(0.85, 1.15, smoothstep(needs, needs * 2.0 + 0.2, q.x)); vec2 local; if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, aniso, local)) continue; - // thin wet icy snow lets some light (and the bent picture) through, a thick layer none + // fading in over the first snow (no flicker on the edge), opaque when thick; the thick snow bends nothing float deep = smoothstep(snow_cover * 3.0, snow_deep, q.x); - int tile; - // the cover: slush while it's thin and wet; thick snow is packed snow however wet it is (the slush tile is translucent - // by itself, a glass covered with it never closes; the wet one is greyer by its tone) - if (cover > 0.5) - tile = ((wet > 0.35) && (deep < 0.5)) ? 14 : 12 + int(kind * 2.0); - else if (wet > 0.2) - tile = 8 + int(kind * 2.0); // wet lumps - else if (size < 0.8) - tile = 4 + int(kind * 4.0); // puffs, crumbs (a flake breaks up hitting the glass) - else - tile = 10 + int(kind * 2.0); // clumps - float thick = 1.0 - exp(-q.x / (snow_opaque * mix(1.0, 0.5, q.z))); - float alpha = mix(mix(0.7, 0.9, thick), 1.0, deep); - snSprite(local, min(tile, 14), alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0 - deep, acc); + float alpha = smoothstep(needs, needs + 0.04, q.x) * mix(0.8, 1.0, deep); + snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0 - deep, acc); } } } @@ -331,11 +322,13 @@ void main() ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); - // two grids of lumps, the second shifted by half a cell: they overlap, so the snow closes into a cover - snLayer(span, pixelUV, vec2(0.0), 31u, true, layer); - snLayer(span, pixelUV, vec2(0.5), 77u, true, layer); - // and the lumps lying on the cover: the snow piles up rather than changes - snLayer(span, pixelUV, vec2(0.25, 0.75), 113u, false, layer); + // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: dots and crumbs, + // puffs and crumbs, clumps, two of packed snow (they close the glass by 3 mm) + snLumps(span, pixelUV, lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(0.6, 1.1), 0, 4), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(0.8, 1.4), 4, 4), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.1, 1.7), 10, 2), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.75, 0.25), 151u, vec2(0.8, 2.0), vec2(1.9, 2.3), 12, 2), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.5, 0.0), 199u, vec2(1.2, 2.5), vec2(1.9, 2.3), 12, 2), layer); snFlakes(span, pixelUV, flakes); vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index 259126d9a..6d747798a 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -12,10 +12,10 @@ // the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. // // The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen: -// - the lumps: one in a cell of a few texels at most, as the drops of the rain, the more snow around the likelier and bigger, -// from a few mm to a few cm (most of them small), clear glass between them until the snow gets thick, then packed snow -// overlapping into a cover. Wet (near zero, melting): lumps of slush, grey, translucent with a frosted core, bending the -// picture behind; dry: crumbs and clumps of the flakes broken on the glass +// - the lumps, in five grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, +// size, the snow it takes); it comes when the snow around reaches that and stays as it is until the snow goes. The grids come +// one after the other as the snow piles up (dots and crumbs, puffs, clumps, then two of packed snow), each on the ones before, +// so the snow accumulates rather than changes, and closes the glass by 3 mm. In a heap they come sooner // - dots and small puffs of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) // A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. // @@ -74,9 +74,8 @@ layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 3) uniform sampler const float snow_flake_cell = 0.007; // a dot, a small puff or a drop at most every this many metres of the glass (its size) const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff const float snow_drops = 0.35; // share of the texels with the water of a melted flake showing a drop (more with more water) -const float snow_layer = 0.3; // mm of snow around which a cell surely has a lump (fewer, smaller below) const float snow_deep = 2.5; // mm of snow from which the cover is opaque (no picture behind it) -const float snow_cover = 0.25; // mm of snow from which the lumps run together into a cover (full at three times it) +const float snow_cover = 0.25; // the lumps get opaque from three times this many mm of snow const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) @@ -206,7 +205,7 @@ void snFlakes(vec2 span, float pixelUV, inout sprite_acc acc) vec2 centre = vec2(cell) + 0.15 + 0.7 * vec2(RandF(seed), RandF(seed)); vec4 q = water_snow_at(uint(snSlot), snMap, centre / perUV); bool drop = (q.x < 0.05) && (q.y > 0.03); - bool crystal = (q.x >= 0.05) && (snWetness(q) < 0.25); + bool crystal = (q.x >= 0.05); if ((false == drop) && (false == crystal)) continue; if (RandF(seed) > (drop ? snow_drops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) @@ -247,60 +246,52 @@ float snHeap(ivec2 cell) return mix(mix(RandF(s00), RandF(s10), f.x), mix(RandF(s01), RandF(s11), f.x), f.y); } -// the lumps: one in a cell of snow_lump_cell metres of the glass at most, as the drops of the rain, the more snow around and the -// more the cell lies in a heap the likelier it's there and the bigger, sizes from a few mm to a few cm (most of them small), clear -// glass between the heaps until the snow gets thick; then packed snow overlapping into a cover. wet: lumps of slush (grey, -// translucent, bending the picture behind); dry: crumbs and clumps of the flakes broken on the glass -void snLayer(vec2 span, float pixelUV, vec2 shift, uint salt, bool covers, inout sprite_acc acc) +// the lumps, in grids of cells of snow_lump_cell metres of the glass, shifted against each other. every cell of a grid has its +// lump fixed once (its tile, place, turn, size and the snow it takes to be there): the lump comes when the snow of the map around +// it reaches that, grows a little with more snow, and stays as it is until the snow goes (a blade, the melting); it never turns +// into another lump. the grids come one after the other as the snow piles up: dots and crumbs first, then puffs, clumps, and last +// the big lumps of packed snow which close the glass. in a heap (the snow landing side by side runs together) they come sooner +struct lump_grid +{ + vec2 shift; // the grid shifted, cells + uint salt; + vec2 snow; // the snow it takes for a lump of the grid to come, mm: from .. to (random per cell) + vec2 size; // the size of its lumps, cells: from .. to (random per cell) + int tiles; // its tiles: the first one and how many + int count; +}; + +void snLumps(vec2 span, float pixelUV, lump_grid grid, inout sprite_acc acc) { vec2 perUV = span / snow_lump_cell; - vec2 p = f_coord * perUV + shift; + vec2 p = f_coord * perUV + grid.shift; ivec2 here = ivec2(floor(p)); for (int oy = -1; oy <= 1; ++oy) { for (int ox = -1; ox <= 1; ++ox) { ivec2 cell = here + ivec2(ox, oy); - uint seed = Hash(uvec3(uvec2(cell + 4096), salt + 7u * uint(snSlot))); + uint seed = Hash(uvec3(uvec2(cell + 4096), grid.salt + 7u * uint(snSlot))); vec2 centre = vec2(cell) + 0.1 + 0.8 * vec2(RandF(seed), RandF(seed)); - vec4 q = water_snow_at(uint(snSlot), snMap, (centre - shift) / perUV); - float heap = snHeap(cell); - // thick: the lumps grow into a cover (the grids that make it), the lumps of the last grid lie on it - float cover = covers ? smoothstep(snow_cover, snow_cover * 3.0, q.x) : 0.0; - float present = smoothstep(snow_layer * 0.05, snow_layer, q.x) * mix(0.5, 1.8, heap); - if (RandF(seed) >= max(present, cover)) + // the snow it takes, sooner in a heap + float needs = mix(grid.snow.x, grid.snow.y, RandF(seed)) * mix(1.4, 0.6, snHeap(cell)); + vec4 q = water_snow_at(uint(snSlot), snMap, (centre - grid.shift) / perUV); + if (q.x <= needs) continue; float ang = RandF(seed) * 6.2831853; vec2 rot = vec2(cos(ang), sin(ang)); float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; - float kind = RandF(seed); + int tile = grid.tiles + min(int(RandF(seed) * float(grid.count)), grid.count - 1); float random = RandF(seed); - float aniso = mix(0.75, 1.0, RandF(seed)); - float grow = RandF(seed); - float wet = snWetness(q); - // wet lumps are bigger (the slush of a few flakes runs together), so are those in a heap - float size = mix(0.6, 1.7, grow * grow) * mix(0.9, 1.4, smoothstep(snow_layer * 0.5, snow_cover, q.x)) * mix(0.8, 1.3, heap) - * ((wet > 0.2) ? 1.2 : 1.0); - size = mix(min(size, 1.9), 2.4, cover); + float aniso = mix(0.8, 1.0, RandF(seed)); + float size = mix(grid.size.x, grid.size.y, RandF(seed)) * mix(0.85, 1.15, smoothstep(needs, needs * 2.0 + 0.2, q.x)); vec2 local; if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, aniso, local)) continue; - // thin wet icy snow lets some light (and the bent picture) through, a thick layer none + // fading in over the first snow (no flicker on the edge), opaque when thick; the thick snow bends nothing float deep = smoothstep(snow_cover * 3.0, snow_deep, q.x); - int tile; - // the cover: slush while it's thin and wet; thick snow is packed snow however wet it is (the slush tile is translucent - // by itself, a glass covered with it never closes; the wet one is greyer by its tone) - if (cover > 0.5) - tile = ((wet > 0.35) && (deep < 0.5)) ? 14 : 12 + int(kind * 2.0); - else if (wet > 0.2) - tile = 8 + int(kind * 2.0); // wet lumps - else if (size < 0.8) - tile = 4 + int(kind * 4.0); // puffs, crumbs (a flake breaks up hitting the glass) - else - tile = 10 + int(kind * 2.0); // clumps - float thick = 1.0 - exp(-q.x / (snow_opaque * mix(1.0, 0.5, q.z))); - float alpha = mix(mix(0.7, 0.9, thick), 1.0, deep); - snSprite(local, min(tile, 14), alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0 - deep, acc); + float alpha = smoothstep(needs, needs + 0.04, q.x) * mix(0.8, 1.0, deep); + snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0 - deep, acc); } } } @@ -336,11 +327,13 @@ void main() ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); - // two grids of lumps, the second shifted by half a cell: they overlap, so the snow closes into a cover - snLayer(span, pixelUV, vec2(0.0), 31u, true, layer); - snLayer(span, pixelUV, vec2(0.5), 77u, true, layer); - // and the lumps lying on the cover: the snow piles up rather than changes - snLayer(span, pixelUV, vec2(0.25, 0.75), 113u, false, layer); + // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: dots and crumbs, + // puffs and crumbs, clumps, two of packed snow (they close the glass by 3 mm) + snLumps(span, pixelUV, lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(0.6, 1.1), 0, 4), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(0.8, 1.4), 4, 4), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.1, 1.7), 10, 2), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.75, 0.25), 151u, vec2(0.8, 2.0), vec2(1.9, 2.3), 12, 2), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.5, 0.0), 199u, vec2(1.2, 2.5), vec2(1.9, 2.3), 12, 2), layer); snFlakes(span, pixelUV, flakes); vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); From 80bafdc7a531c894fbfe03c54f905232f454a8e8 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 21:36:21 +0100 Subject: [PATCH 089/123] Snow windscreen: the icy clumps all the way, packed snow only beneath The grids that close the glass drew the round lumps of packed snow over the icy clumps (tiles 0-7, the look that was liked). Ten grids now: eight of dots, icy clumps and crumbs, more and bigger as the snow piles up, and under them all two of packed snow coming last (2.2-3.4 mm) to fill the gaps between the clumps; the glass closes by about 3 mm still showing the clumps. A grid is skipped where the snow of the pixel is far below what its lumps take. No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_snow_windscreen.frag | 33 +++++++++++++++++--------- shaders/vk14/mat_snow_windscreen.frag | 33 +++++++++++++++++--------- 2 files changed, 44 insertions(+), 22 deletions(-) diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index 795401135..055f0927d 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -11,10 +11,11 @@ // the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. // // The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen: -// - the lumps, in five grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, +// - the lumps, in ten grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, // size, the snow it takes); it comes when the snow around reaches that and stays as it is until the snow goes. The grids come -// one after the other as the snow piles up (dots and crumbs, puffs, clumps, then two of packed snow), each on the ones before, -// so the snow accumulates rather than changes, and closes the glass by 3 mm. In a heap they come sooner +// one after the other as the snow piles up, each on the ones before: dots, icy clumps and crumbs, more and bigger; under them +// two of packed snow coming last, filling the gaps, so the snow accumulates rather than changes and closes the glass by +// about 3 mm. In a heap they come sooner // - dots and small puffs of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) // A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. // @@ -256,8 +257,11 @@ struct lump_grid int count; }; -void snLumps(vec2 span, float pixelUV, lump_grid grid, inout sprite_acc acc) +void snLumps(vec2 span, float pixelUV, float here_snow, lump_grid grid, inout sprite_acc acc) { + // none of the grid near a pixel with much less snow than its lumps take (the most of the work saved on the thin snow) + if (here_snow < grid.snow.x * 0.3) + return; vec2 perUV = span / snow_lump_cell; vec2 p = f_coord * perUV + grid.shift; ivec2 here = ivec2(floor(p)); @@ -322,13 +326,20 @@ void main() ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); - // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: dots and crumbs, - // puffs and crumbs, clumps, two of packed snow (they close the glass by 3 mm) - snLumps(span, pixelUV, lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(0.6, 1.1), 0, 4), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(0.8, 1.4), 4, 4), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.1, 1.7), 10, 2), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.75, 0.25), 151u, vec2(0.8, 2.0), vec2(1.9, 2.3), 12, 2), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.5, 0.0), 199u, vec2(1.2, 2.5), vec2(1.9, 2.3), 12, 2), layer); + // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: under them all two + // of packed snow, coming last (they close the glass by about 3 mm, the gaps between the icy clumps filling), then dots, + // icy clumps and crumbs of more and more and bigger lumps + float here_snow = water_snow_at(uint(snSlot), snMap, f_coord).x; + snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.1, 0.6), 211u, vec2(2.2, 3.2), vec2(2.0, 2.4), 12, 2), layer); + snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.6, 0.1), 223u, vec2(2.6, 3.4), vec2(2.0, 2.4), 12, 2), layer); + snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.0), 31u, vec2(0.02, 0.3), vec2(0.7, 1.2), 0, 4), layer); + snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.5), 77u, vec2(0.1, 0.6), vec2(0.9, 1.5), 4, 4), layer); + snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.25, 0.75), 113u, vec2(0.3, 1.0), vec2(1.0, 1.7), 4, 4), layer); + snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.75, 0.25), 151u, vec2(0.6, 1.5), vec2(1.1, 1.8), 4, 4), layer); + snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.0), vec2(1.6, 2.2), 4, 2), layer); + snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.0, 0.5), 233u, vec2(1.4, 2.6), vec2(1.8, 2.4), 4, 2), layer); + snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.25), 241u, vec2(1.8, 3.0), vec2(1.8, 2.4), 4, 2), layer); + snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.75), 251u, vec2(2.2, 3.2), vec2(1.8, 2.4), 4, 2), layer); snFlakes(span, pixelUV, flakes); vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index 6d747798a..91beefdee 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -12,10 +12,11 @@ // the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. // // The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen: -// - the lumps, in five grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, +// - the lumps, in ten grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, // size, the snow it takes); it comes when the snow around reaches that and stays as it is until the snow goes. The grids come -// one after the other as the snow piles up (dots and crumbs, puffs, clumps, then two of packed snow), each on the ones before, -// so the snow accumulates rather than changes, and closes the glass by 3 mm. In a heap they come sooner +// one after the other as the snow piles up, each on the ones before: dots, icy clumps and crumbs, more and bigger; under them +// two of packed snow coming last, filling the gaps, so the snow accumulates rather than changes and closes the glass by +// about 3 mm. In a heap they come sooner // - dots and small puffs of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) // A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. // @@ -261,8 +262,11 @@ struct lump_grid int count; }; -void snLumps(vec2 span, float pixelUV, lump_grid grid, inout sprite_acc acc) +void snLumps(vec2 span, float pixelUV, float here_snow, lump_grid grid, inout sprite_acc acc) { + // none of the grid near a pixel with much less snow than its lumps take (the most of the work saved on the thin snow) + if (here_snow < grid.snow.x * 0.3) + return; vec2 perUV = span / snow_lump_cell; vec2 p = f_coord * perUV + grid.shift; ivec2 here = ivec2(floor(p)); @@ -327,13 +331,20 @@ void main() ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); - // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: dots and crumbs, - // puffs and crumbs, clumps, two of packed snow (they close the glass by 3 mm) - snLumps(span, pixelUV, lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(0.6, 1.1), 0, 4), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(0.8, 1.4), 4, 4), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.1, 1.7), 10, 2), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.75, 0.25), 151u, vec2(0.8, 2.0), vec2(1.9, 2.3), 12, 2), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.5, 0.0), 199u, vec2(1.2, 2.5), vec2(1.9, 2.3), 12, 2), layer); + // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: under them all two + // of packed snow, coming last (they close the glass by about 3 mm, the gaps between the icy clumps filling), then dots, + // icy clumps and crumbs of more and more and bigger lumps + float here_snow = water_snow_at(uint(snSlot), snMap, f_coord).x; + snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.1, 0.6), 211u, vec2(2.2, 3.2), vec2(2.0, 2.4), 12, 2), layer); + snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.6, 0.1), 223u, vec2(2.6, 3.4), vec2(2.0, 2.4), 12, 2), layer); + snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.0), 31u, vec2(0.02, 0.3), vec2(0.7, 1.2), 0, 4), layer); + snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.5), 77u, vec2(0.1, 0.6), vec2(0.9, 1.5), 4, 4), layer); + snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.25, 0.75), 113u, vec2(0.3, 1.0), vec2(1.0, 1.7), 4, 4), layer); + snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.75, 0.25), 151u, vec2(0.6, 1.5), vec2(1.1, 1.8), 4, 4), layer); + snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.0), vec2(1.6, 2.2), 4, 2), layer); + snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.0, 0.5), 233u, vec2(1.4, 2.6), vec2(1.8, 2.4), 4, 2), layer); + snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.25), 241u, vec2(1.8, 3.0), vec2(1.8, 2.4), 4, 2), layer); + snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.75), 251u, vec2(2.2, 3.2), vec2(1.8, 2.4), 4, 2), layer); snFlakes(span, pixelUV, flakes); vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); From bc33ba3c01ea66123bed7f791888ec6c20963340 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 21:41:52 +0100 Subject: [PATCH 090/123] Snow windscreen: a matte fill under the clumps, no pavement of domes The two grids of packed-snow lumps under the icy clumps showed through as a grey pavement of round domes (their normals shaded each one). They're gone; from 2 mm of snow a flat matte layer of the colour of the packed snow of the atlas (its tile averaged by a coarse mip) fills the gaps under the clumps, closing the glass by 3 mm with the clumps on it. No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_snow_windscreen.frag | 31 ++++++++++++++++++-------- shaders/vk14/mat_snow_windscreen.frag | 31 ++++++++++++++++++-------- 2 files changed, 44 insertions(+), 18 deletions(-) diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index 055f0927d..834ca4850 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -11,11 +11,11 @@ // the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. // // The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen: -// - the lumps, in ten grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, +// - the lumps, in eight grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, // size, the snow it takes); it comes when the snow around reaches that and stays as it is until the snow goes. The grids come // one after the other as the snow piles up, each on the ones before: dots, icy clumps and crumbs, more and bigger; under them -// two of packed snow coming last, filling the gaps, so the snow accumulates rather than changes and closes the glass by -// about 3 mm. In a heap they come sooner +// a matte layer of packed snow fills the gaps from 2 mm, so the snow accumulates rather than changes and closes the glass by +// 3 mm. In a heap they come sooner // - dots and small puffs of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) // A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. // @@ -71,6 +71,7 @@ const float snow_flake_cell = 0.007; // a dot, a small puff or a drop at most ev const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff const float snow_drops = 0.35; // share of the texels with the water of a melted flake showing a drop (more with more water) const float snow_deep = 2.5; // mm of snow from which the cover is opaque (no picture behind it) +const vec2 snow_fill = vec2(2.0, 3.0); // mm of snow over which a matte layer fills the gaps between the clumps const float snow_cover = 0.25; // the lumps get opaque from three times this many mm of snow const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) @@ -326,12 +327,10 @@ void main() ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); - // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: under them all two - // of packed snow, coming last (they close the glass by about 3 mm, the gaps between the icy clumps filling), then dots, - // icy clumps and crumbs of more and more and bigger lumps - float here_snow = water_snow_at(uint(snSlot), snMap, f_coord).x; - snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.1, 0.6), 211u, vec2(2.2, 3.2), vec2(2.0, 2.4), 12, 2), layer); - snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.6, 0.1), 223u, vec2(2.6, 3.4), vec2(2.0, 2.4), 12, 2), layer); + // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: dots, icy clumps and + // crumbs, more and more and bigger lumps + vec4 here = water_snow_at(uint(snSlot), snMap, f_coord); + float here_snow = here.x; snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.0), 31u, vec2(0.02, 0.3), vec2(0.7, 1.2), 0, 4), layer); snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.5), 77u, vec2(0.1, 0.6), vec2(0.9, 1.5), 4, 4), layer); snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.25, 0.75), 113u, vec2(0.3, 1.0), vec2(1.0, 1.7), 4, 4), layer); @@ -340,6 +339,20 @@ void main() snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.0, 0.5), 233u, vec2(1.4, 2.6), vec2(1.8, 2.4), 4, 2), layer); snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.25), 241u, vec2(1.8, 3.0), vec2(1.8, 2.4), 4, 2), layer); snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.75), 251u, vec2(2.2, 3.2), vec2(1.8, 2.4), 4, 2), layer); + // the thick snow under the clumps fills the gaps between them: a matte layer of the colour of the packed snow of the + // atlas (its tile averaged by a coarse mip), flat, so the clumps keep their look (lumps of packed snow drawn there + // made the glass a grey pavement of domes) + float fill = smoothstep(snow_fill.x, snow_fill.y, here_snow); + if (fill > 0.0) + { + vec3 packed = textureLod(raindropsatlas, snTile(12) + 0.5 * snTileSize(), 7.0).rgb; + packed = packed / max(max(packed.r, max(packed.g, packed.b)), 0.5) * 0.92; // the mip is darkened by the empty corners + float under = fill * (1.0 - layer.a); + layer.rgb += packed * snTone(here, 0.5) * under; + layer.n += vec3(0.0, 0.0, 1.0) * under; + layer.tr += 0.3 * under; + layer.a += under; + } snFlakes(span, pixelUV, flakes); vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index 91beefdee..b6c7008cb 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -12,11 +12,11 @@ // the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. // // The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen: -// - the lumps, in ten grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, +// - the lumps, in eight grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, // size, the snow it takes); it comes when the snow around reaches that and stays as it is until the snow goes. The grids come // one after the other as the snow piles up, each on the ones before: dots, icy clumps and crumbs, more and bigger; under them -// two of packed snow coming last, filling the gaps, so the snow accumulates rather than changes and closes the glass by -// about 3 mm. In a heap they come sooner +// a matte layer of packed snow fills the gaps from 2 mm, so the snow accumulates rather than changes and closes the glass by +// 3 mm. In a heap they come sooner // - dots and small puffs of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) // A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. // @@ -76,6 +76,7 @@ const float snow_flake_cell = 0.007; // a dot, a small puff or a drop at most ev const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff const float snow_drops = 0.35; // share of the texels with the water of a melted flake showing a drop (more with more water) const float snow_deep = 2.5; // mm of snow from which the cover is opaque (no picture behind it) +const vec2 snow_fill = vec2(2.0, 3.0); // mm of snow over which a matte layer fills the gaps between the clumps const float snow_cover = 0.25; // the lumps get opaque from three times this many mm of snow const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) @@ -331,12 +332,10 @@ void main() ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); - // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: under them all two - // of packed snow, coming last (they close the glass by about 3 mm, the gaps between the icy clumps filling), then dots, - // icy clumps and crumbs of more and more and bigger lumps - float here_snow = water_snow_at(uint(snSlot), snMap, f_coord).x; - snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.1, 0.6), 211u, vec2(2.2, 3.2), vec2(2.0, 2.4), 12, 2), layer); - snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.6, 0.1), 223u, vec2(2.6, 3.4), vec2(2.0, 2.4), 12, 2), layer); + // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: dots, icy clumps and + // crumbs, more and more and bigger lumps + vec4 here = water_snow_at(uint(snSlot), snMap, f_coord); + float here_snow = here.x; snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.0), 31u, vec2(0.02, 0.3), vec2(0.7, 1.2), 0, 4), layer); snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.5), 77u, vec2(0.1, 0.6), vec2(0.9, 1.5), 4, 4), layer); snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.25, 0.75), 113u, vec2(0.3, 1.0), vec2(1.0, 1.7), 4, 4), layer); @@ -345,6 +344,20 @@ void main() snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.0, 0.5), 233u, vec2(1.4, 2.6), vec2(1.8, 2.4), 4, 2), layer); snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.25), 241u, vec2(1.8, 3.0), vec2(1.8, 2.4), 4, 2), layer); snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.75), 251u, vec2(2.2, 3.2), vec2(1.8, 2.4), 4, 2), layer); + // the thick snow under the clumps fills the gaps between them: a matte layer of the colour of the packed snow of the + // atlas (its tile averaged by a coarse mip), flat, so the clumps keep their look (lumps of packed snow drawn there + // made the glass a grey pavement of domes) + float fill = smoothstep(snow_fill.x, snow_fill.y, here_snow); + if (fill > 0.0) + { + vec3 packed = textureLod(raindropsatlas, snTile(12) + 0.5 * snTileSize(), 7.0).rgb; + packed = packed / max(max(packed.r, max(packed.g, packed.b)), 0.5) * 0.92; // the mip is darkened by the empty corners + float under = fill * (1.0 - layer.a); + layer.rgb += packed * snTone(here, 0.5) * under; + layer.n += vec3(0.0, 0.0, 1.0) * under; + layer.tr += 0.3 * under; + layer.a += under; + } snFlakes(span, pixelUV, flakes); vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); From 6f7e0a0bcf5fb5ed8bedc64fc9eaf720e2264dcc Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 21:45:44 +0100 Subject: [PATCH 091/123] Snow windscreen: back to the five grids of lumps that stay (abc14ed) The look of abc14ed was liked best: the lumps fixed once per cell, five grids piling up (dots and crumbs, puffs, clumps, two of packed snow). The shader is that of abc14ed again; 5fb1173 (ten grids of icy clumps over packed snow) and 4d471f7 (a matte fill instead) are undone. No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_snow_windscreen.frag | 46 ++++++-------------------- shaders/vk14/mat_snow_windscreen.frag | 46 ++++++-------------------- 2 files changed, 22 insertions(+), 70 deletions(-) diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index 834ca4850..795401135 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -11,11 +11,10 @@ // the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. // // The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen: -// - the lumps, in eight grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, +// - the lumps, in five grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, // size, the snow it takes); it comes when the snow around reaches that and stays as it is until the snow goes. The grids come -// one after the other as the snow piles up, each on the ones before: dots, icy clumps and crumbs, more and bigger; under them -// a matte layer of packed snow fills the gaps from 2 mm, so the snow accumulates rather than changes and closes the glass by -// 3 mm. In a heap they come sooner +// one after the other as the snow piles up (dots and crumbs, puffs, clumps, then two of packed snow), each on the ones before, +// so the snow accumulates rather than changes, and closes the glass by 3 mm. In a heap they come sooner // - dots and small puffs of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) // A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. // @@ -71,7 +70,6 @@ const float snow_flake_cell = 0.007; // a dot, a small puff or a drop at most ev const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff const float snow_drops = 0.35; // share of the texels with the water of a melted flake showing a drop (more with more water) const float snow_deep = 2.5; // mm of snow from which the cover is opaque (no picture behind it) -const vec2 snow_fill = vec2(2.0, 3.0); // mm of snow over which a matte layer fills the gaps between the clumps const float snow_cover = 0.25; // the lumps get opaque from three times this many mm of snow const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) @@ -258,11 +256,8 @@ struct lump_grid int count; }; -void snLumps(vec2 span, float pixelUV, float here_snow, lump_grid grid, inout sprite_acc acc) +void snLumps(vec2 span, float pixelUV, lump_grid grid, inout sprite_acc acc) { - // none of the grid near a pixel with much less snow than its lumps take (the most of the work saved on the thin snow) - if (here_snow < grid.snow.x * 0.3) - return; vec2 perUV = span / snow_lump_cell; vec2 p = f_coord * perUV + grid.shift; ivec2 here = ivec2(floor(p)); @@ -327,32 +322,13 @@ void main() ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); - // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: dots, icy clumps and - // crumbs, more and more and bigger lumps - vec4 here = water_snow_at(uint(snSlot), snMap, f_coord); - float here_snow = here.x; - snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.0), 31u, vec2(0.02, 0.3), vec2(0.7, 1.2), 0, 4), layer); - snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.5), 77u, vec2(0.1, 0.6), vec2(0.9, 1.5), 4, 4), layer); - snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.25, 0.75), 113u, vec2(0.3, 1.0), vec2(1.0, 1.7), 4, 4), layer); - snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.75, 0.25), 151u, vec2(0.6, 1.5), vec2(1.1, 1.8), 4, 4), layer); - snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.0), vec2(1.6, 2.2), 4, 2), layer); - snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.0, 0.5), 233u, vec2(1.4, 2.6), vec2(1.8, 2.4), 4, 2), layer); - snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.25), 241u, vec2(1.8, 3.0), vec2(1.8, 2.4), 4, 2), layer); - snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.75), 251u, vec2(2.2, 3.2), vec2(1.8, 2.4), 4, 2), layer); - // the thick snow under the clumps fills the gaps between them: a matte layer of the colour of the packed snow of the - // atlas (its tile averaged by a coarse mip), flat, so the clumps keep their look (lumps of packed snow drawn there - // made the glass a grey pavement of domes) - float fill = smoothstep(snow_fill.x, snow_fill.y, here_snow); - if (fill > 0.0) - { - vec3 packed = textureLod(raindropsatlas, snTile(12) + 0.5 * snTileSize(), 7.0).rgb; - packed = packed / max(max(packed.r, max(packed.g, packed.b)), 0.5) * 0.92; // the mip is darkened by the empty corners - float under = fill * (1.0 - layer.a); - layer.rgb += packed * snTone(here, 0.5) * under; - layer.n += vec3(0.0, 0.0, 1.0) * under; - layer.tr += 0.3 * under; - layer.a += under; - } + // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: dots and crumbs, + // puffs and crumbs, clumps, two of packed snow (they close the glass by 3 mm) + snLumps(span, pixelUV, lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(0.6, 1.1), 0, 4), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(0.8, 1.4), 4, 4), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.1, 1.7), 10, 2), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.75, 0.25), 151u, vec2(0.8, 2.0), vec2(1.9, 2.3), 12, 2), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.5, 0.0), 199u, vec2(1.2, 2.5), vec2(1.9, 2.3), 12, 2), layer); snFlakes(span, pixelUV, flakes); vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index b6c7008cb..6d747798a 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -12,11 +12,10 @@ // the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. // // The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen: -// - the lumps, in eight grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, +// - the lumps, in five grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, // size, the snow it takes); it comes when the snow around reaches that and stays as it is until the snow goes. The grids come -// one after the other as the snow piles up, each on the ones before: dots, icy clumps and crumbs, more and bigger; under them -// a matte layer of packed snow fills the gaps from 2 mm, so the snow accumulates rather than changes and closes the glass by -// 3 mm. In a heap they come sooner +// one after the other as the snow piles up (dots and crumbs, puffs, clumps, then two of packed snow), each on the ones before, +// so the snow accumulates rather than changes, and closes the glass by 3 mm. In a heap they come sooner // - dots and small puffs of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) // A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. // @@ -76,7 +75,6 @@ const float snow_flake_cell = 0.007; // a dot, a small puff or a drop at most ev const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff const float snow_drops = 0.35; // share of the texels with the water of a melted flake showing a drop (more with more water) const float snow_deep = 2.5; // mm of snow from which the cover is opaque (no picture behind it) -const vec2 snow_fill = vec2(2.0, 3.0); // mm of snow over which a matte layer fills the gaps between the clumps const float snow_cover = 0.25; // the lumps get opaque from three times this many mm of snow const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) @@ -263,11 +261,8 @@ struct lump_grid int count; }; -void snLumps(vec2 span, float pixelUV, float here_snow, lump_grid grid, inout sprite_acc acc) +void snLumps(vec2 span, float pixelUV, lump_grid grid, inout sprite_acc acc) { - // none of the grid near a pixel with much less snow than its lumps take (the most of the work saved on the thin snow) - if (here_snow < grid.snow.x * 0.3) - return; vec2 perUV = span / snow_lump_cell; vec2 p = f_coord * perUV + grid.shift; ivec2 here = ivec2(floor(p)); @@ -332,32 +327,13 @@ void main() ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); - // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: dots, icy clumps and - // crumbs, more and more and bigger lumps - vec4 here = water_snow_at(uint(snSlot), snMap, f_coord); - float here_snow = here.x; - snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.0), 31u, vec2(0.02, 0.3), vec2(0.7, 1.2), 0, 4), layer); - snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.5), 77u, vec2(0.1, 0.6), vec2(0.9, 1.5), 4, 4), layer); - snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.25, 0.75), 113u, vec2(0.3, 1.0), vec2(1.0, 1.7), 4, 4), layer); - snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.75, 0.25), 151u, vec2(0.6, 1.5), vec2(1.1, 1.8), 4, 4), layer); - snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.0), vec2(1.6, 2.2), 4, 2), layer); - snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.0, 0.5), 233u, vec2(1.4, 2.6), vec2(1.8, 2.4), 4, 2), layer); - snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.25), 241u, vec2(1.8, 3.0), vec2(1.8, 2.4), 4, 2), layer); - snLumps(span, pixelUV, here_snow, lump_grid(vec2(0.75), 251u, vec2(2.2, 3.2), vec2(1.8, 2.4), 4, 2), layer); - // the thick snow under the clumps fills the gaps between them: a matte layer of the colour of the packed snow of the - // atlas (its tile averaged by a coarse mip), flat, so the clumps keep their look (lumps of packed snow drawn there - // made the glass a grey pavement of domes) - float fill = smoothstep(snow_fill.x, snow_fill.y, here_snow); - if (fill > 0.0) - { - vec3 packed = textureLod(raindropsatlas, snTile(12) + 0.5 * snTileSize(), 7.0).rgb; - packed = packed / max(max(packed.r, max(packed.g, packed.b)), 0.5) * 0.92; // the mip is darkened by the empty corners - float under = fill * (1.0 - layer.a); - layer.rgb += packed * snTone(here, 0.5) * under; - layer.n += vec3(0.0, 0.0, 1.0) * under; - layer.tr += 0.3 * under; - layer.a += under; - } + // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: dots and crumbs, + // puffs and crumbs, clumps, two of packed snow (they close the glass by 3 mm) + snLumps(span, pixelUV, lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(0.6, 1.1), 0, 4), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(0.8, 1.4), 4, 4), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.1, 1.7), 10, 2), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.75, 0.25), 151u, vec2(0.8, 2.0), vec2(1.9, 2.3), 12, 2), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.5, 0.0), 199u, vec2(1.2, 2.5), vec2(1.9, 2.3), 12, 2), layer); snFlakes(span, pixelUV, flakes); vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); From 84b38329e37c376cc01fa1a683f13953417b76b0 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Wed, 11 Nov 2026 21:54:21 +0100 Subject: [PATCH 092/123] Snow windscreen: smaller packed lumps, more fleece, more refraction On the five grids of abc14ed: the lumps of packed snow are smaller (1.2-1.6 cells, 1.9-2.3 before), four grids of them instead of two so they still close the glass (by 2-3 mm); two grids of the small puffs and icy clumps (tiles 2-5, the fleece) instead of one of puffs and crumbs; the icy snow bends the picture as much as a drop, up to 98% opacity (95% before). No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_snow_windscreen.frag | 22 +++++++++++++--------- shaders/vk14/mat_snow_windscreen.frag | 22 +++++++++++++--------- 2 files changed, 26 insertions(+), 18 deletions(-) diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index 795401135..3fe39407a 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -11,10 +11,10 @@ // the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. // // The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen: -// - the lumps, in five grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, +// - the lumps, in eight grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, // size, the snow it takes); it comes when the snow around reaches that and stays as it is until the snow goes. The grids come -// one after the other as the snow piles up (dots and crumbs, puffs, clumps, then two of packed snow), each on the ones before, -// so the snow accumulates rather than changes, and closes the glass by 3 mm. In a heap they come sooner +// one after the other as the snow piles up (dots, two of puffs, clumps, then four of small packed lumps), each on the ones before, +// so the snow accumulates rather than changes, and closes the glass by 2-3 mm. In a heap they come sooner // - dots and small puffs of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) // A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. // @@ -77,7 +77,7 @@ const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the ligh const float snow_thin = 0.45; // opacity of a single thin flake (ice crystals let most of the light through) const float snow_bump = 1.0; // strength of the relief from the normal map, 0 = flat const float snow_gloss = 0.8; // glints of the sun / headlights on the wet snow, 0 = matt -const float snow_ice_bend = 0.7; // how strongly the icy snow bends the picture behind it, of the bend of a drop +const float snow_ice_bend = 1.0; // how strongly the icy snow bends the picture behind it, of the bend of a drop const float snow_translucency = 0.8; // glow of thin snow when you look towards the sun / a lamp, 0 = off const float snow_haze = 1.0; // blur of the scene behind thin snow (frosted glass), 0 = off const float snow_drop_bend = 1.0; // how strongly the drops bend the picture behind them @@ -323,12 +323,16 @@ void main() uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: dots and crumbs, - // puffs and crumbs, clumps, two of packed snow (they close the glass by 3 mm) + // two of small puffs and icy clumps (the fleece), clumps, four of small lumps of packed snow (they close the glass by + // 2-3 mm) snLumps(span, pixelUV, lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(0.6, 1.1), 0, 4), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(0.8, 1.4), 4, 4), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(0.8, 1.4), 2, 4), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.25), 97u, vec2(0.2, 0.9), vec2(0.8, 1.4), 2, 4), layer); snLumps(span, pixelUV, lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.1, 1.7), 10, 2), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.75, 0.25), 151u, vec2(0.8, 2.0), vec2(1.9, 2.3), 12, 2), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.5, 0.0), 199u, vec2(1.2, 2.5), vec2(1.9, 2.3), 12, 2), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.75, 0.25), 151u, vec2(0.8, 2.0), vec2(1.2, 1.6), 12, 2), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.2), vec2(1.2, 1.6), 12, 2), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.0, 0.5), 233u, vec2(1.2, 2.5), vec2(1.2, 1.6), 12, 2), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.75), 251u, vec2(1.4, 2.8), vec2(1.2, 1.6), 12, 2), layer); snFlakes(span, pixelUV, flakes); vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); @@ -390,7 +394,7 @@ void main() // the post-processing puts the picture from the bent place in place of this pixel, snow and all (85% of it): through // snow it hides, the snow itself would be replaced by the picture from a place up to 96 px away, a gap of the snow // there showing here, so an opaque cover would never close. bent only as much as the snow lets the light through - float through = 1.0 - smoothstep(0.5, 0.95, snowA); + float through = 1.0 - smoothstep(0.6, 0.98, snowA); vec2 bend = clamp(-snBend / max(snBendA, 1e-3) * snow_drop_bend, vec2(-1.0), vec2(1.0)) * smoothstep(0.1, 0.4, snBendA) * through; req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); } diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index 6d747798a..55cb89598 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -12,10 +12,10 @@ // the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. // // The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen: -// - the lumps, in five grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, +// - the lumps, in eight grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, // size, the snow it takes); it comes when the snow around reaches that and stays as it is until the snow goes. The grids come -// one after the other as the snow piles up (dots and crumbs, puffs, clumps, then two of packed snow), each on the ones before, -// so the snow accumulates rather than changes, and closes the glass by 3 mm. In a heap they come sooner +// one after the other as the snow piles up (dots, two of puffs, clumps, then four of small packed lumps), each on the ones before, +// so the snow accumulates rather than changes, and closes the glass by 2-3 mm. In a heap they come sooner // - dots and small puffs of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) // A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. // @@ -82,7 +82,7 @@ const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the ligh const float snow_thin = 0.45; // opacity of a single thin flake (ice crystals let most of the light through) const float snow_bump = 1.0; // strength of the relief from the normal map, 0 = flat const float snow_gloss = 0.8; // glints of the sun / headlights on the wet snow, 0 = matt -const float snow_ice_bend = 0.7; // how strongly the icy snow bends the picture behind it, of the bend of a drop +const float snow_ice_bend = 1.0; // how strongly the icy snow bends the picture behind it, of the bend of a drop const float snow_translucency = 0.8; // glow of thin snow when you look towards the sun / a lamp, 0 = off const float snow_haze = 1.0; // blur of the scene behind thin snow (frosted glass), 0 = off const float snow_drop_bend = 1.0; // how strongly the drops bend the picture behind them @@ -328,12 +328,16 @@ void main() uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: dots and crumbs, - // puffs and crumbs, clumps, two of packed snow (they close the glass by 3 mm) + // two of small puffs and icy clumps (the fleece), clumps, four of small lumps of packed snow (they close the glass by + // 2-3 mm) snLumps(span, pixelUV, lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(0.6, 1.1), 0, 4), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(0.8, 1.4), 4, 4), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(0.8, 1.4), 2, 4), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.25), 97u, vec2(0.2, 0.9), vec2(0.8, 1.4), 2, 4), layer); snLumps(span, pixelUV, lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.1, 1.7), 10, 2), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.75, 0.25), 151u, vec2(0.8, 2.0), vec2(1.9, 2.3), 12, 2), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.5, 0.0), 199u, vec2(1.2, 2.5), vec2(1.9, 2.3), 12, 2), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.75, 0.25), 151u, vec2(0.8, 2.0), vec2(1.2, 1.6), 12, 2), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.2), vec2(1.2, 1.6), 12, 2), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.0, 0.5), 233u, vec2(1.2, 2.5), vec2(1.2, 1.6), 12, 2), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.75), 251u, vec2(1.4, 2.8), vec2(1.2, 1.6), 12, 2), layer); snFlakes(span, pixelUV, flakes); vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); @@ -395,7 +399,7 @@ void main() // the post-processing puts the picture from the bent place in place of this pixel, snow and all (85% of it): through // snow it hides, the snow itself would be replaced by the picture from a place up to 96 px away, a gap of the snow // there showing here, so an opaque cover would never close. bent only as much as the snow lets the light through - float through = 1.0 - smoothstep(0.5, 0.95, snowA); + float through = 1.0 - smoothstep(0.6, 0.98, snowA); vec2 bend = clamp(-snBend / max(snBendA, 1e-3) * snow_drop_bend, vec2(-1.0), vec2(1.0)) * smoothstep(0.1, 0.4, snBendA) * through; req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); } From 62a6a3cf40f05f155c10d4e3ea45bc9c3b59bcd3 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Thu, 12 Nov 2026 12:39:16 +0100 Subject: [PATCH 093/123] Snow windscreen: all icy fleece, packed lumps and drops only now and then All the grids of lumps are the icy fleece now (the small puffs and icy clumps of tiles 2-5, the look that was liked), bigger to close the glass (1.2-3.0 cells, the fleece fills about half its tile), eight of them, by 2-3 mm. A lump of packed snow comes in 3% of the cells of one grid, the single crystals between the lumps are small puffs instead of dots, and a drop of a melted flake shows on 5% of the wet texels (35% before). A grid has a share of its cells having a lump at all. No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_snow_windscreen.frag | 34 ++++++++++++++------------ shaders/vk14/mat_snow_windscreen.frag | 34 ++++++++++++++------------ 2 files changed, 36 insertions(+), 32 deletions(-) diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index 3fe39407a..55d531506 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -11,9 +11,9 @@ // the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. // // The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen: -// - the lumps, in eight grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, +// - the lumps, in nine grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, // size, the snow it takes); it comes when the snow around reaches that and stays as it is until the snow goes. The grids come -// one after the other as the snow piles up (dots, two of puffs, clumps, then four of small packed lumps), each on the ones before, +// one after the other as the snow piles up (all of them icy fleece, more and bigger; a lump of packed snow very rarely), each on the ones before, // so the snow accumulates rather than changes, and closes the glass by 2-3 mm. In a heap they come sooner // - dots and small puffs of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) // A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. @@ -68,7 +68,7 @@ layout(binding = 3) uniform sampler2D normalmap; // --- tuning ------------------------------------------------------------------------------------------------------------------ const float snow_flake_cell = 0.007; // a dot, a small puff or a drop at most every this many metres of the glass (its size) const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff -const float snow_drops = 0.35; // share of the texels with the water of a melted flake showing a drop (more with more water) +const float snow_drops = 0.05; // share of the texels with the water of a melted flake showing a drop (more with more water) const float snow_deep = 2.5; // mm of snow from which the cover is opaque (no picture behind it) const float snow_cover = 0.25; // the lumps get opaque from three times this many mm of snow const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) @@ -218,7 +218,7 @@ void snFlakes(vec2 span, float pixelUV, inout sprite_acc acc) float alpha = smoothstep(0.03, 0.1, q.y); if (crystal) { - tile = min(int(kind * 4.0), 3); // dots, small puffs + tile = 2 + min(int(kind * 2.0), 1); // small icy puffs alpha = snow_thin; } snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0, acc); @@ -254,6 +254,7 @@ struct lump_grid vec2 size; // the size of its lumps, cells: from .. to (random per cell) int tiles; // its tiles: the first one and how many int count; + float share; // the share of its cells having a lump at all (1: all of them) }; void snLumps(vec2 span, float pixelUV, lump_grid grid, inout sprite_acc acc) @@ -271,7 +272,7 @@ void snLumps(vec2 span, float pixelUV, lump_grid grid, inout sprite_acc acc) // the snow it takes, sooner in a heap float needs = mix(grid.snow.x, grid.snow.y, RandF(seed)) * mix(1.4, 0.6, snHeap(cell)); vec4 q = water_snow_at(uint(snSlot), snMap, (centre - grid.shift) / perUV); - if (q.x <= needs) + if ((q.x <= needs) || (RandF(seed) >= grid.share)) continue; float ang = RandF(seed) * 6.2831853; vec2 rot = vec2(cos(ang), sin(ang)); @@ -322,17 +323,18 @@ void main() ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); - // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: dots and crumbs, - // two of small puffs and icy clumps (the fleece), clumps, four of small lumps of packed snow (they close the glass by - // 2-3 mm) - snLumps(span, pixelUV, lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(0.6, 1.1), 0, 4), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(0.8, 1.4), 2, 4), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.25), 97u, vec2(0.2, 0.9), vec2(0.8, 1.4), 2, 4), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.1, 1.7), 10, 2), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.75, 0.25), 151u, vec2(0.8, 2.0), vec2(1.2, 1.6), 12, 2), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.2), vec2(1.2, 1.6), 12, 2), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.0, 0.5), 233u, vec2(1.2, 2.5), vec2(1.2, 1.6), 12, 2), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.75), 251u, vec2(1.4, 2.8), vec2(1.2, 1.6), 12, 2), layer); + // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: all of them icy + // fleece (small puffs and icy clumps, tiles 2-5), more and bigger, closing the glass by 2-3 mm + snLumps(span, pixelUV, lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(1.2, 2.0), 2, 4, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(1.4, 2.4), 2, 4, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.25), 97u, vec2(0.2, 0.9), vec2(1.4, 2.4), 2, 4, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.8, 2.8), 4, 2, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.75, 0.25), 151u, vec2(0.7, 1.6), vec2(1.8, 2.8), 4, 2, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.0), vec2(2.0, 3.0), 4, 2, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.0, 0.5), 233u, vec2(1.2, 2.4), vec2(2.0, 3.0), 4, 2, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.75), 251u, vec2(1.4, 2.8), vec2(2.0, 3.0), 4, 2, 1.0), layer); + // now and then a single lump of packed snow + snLumps(span, pixelUV, lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 12, 2, 0.03), layer); snFlakes(span, pixelUV, flakes); vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index 55cb89598..1aed0a3e2 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -12,9 +12,9 @@ // the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. // // The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen: -// - the lumps, in eight grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, +// - the lumps, in nine grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, // size, the snow it takes); it comes when the snow around reaches that and stays as it is until the snow goes. The grids come -// one after the other as the snow piles up (dots, two of puffs, clumps, then four of small packed lumps), each on the ones before, +// one after the other as the snow piles up (all of them icy fleece, more and bigger; a lump of packed snow very rarely), each on the ones before, // so the snow accumulates rather than changes, and closes the glass by 2-3 mm. In a heap they come sooner // - dots and small puffs of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) // A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. @@ -73,7 +73,7 @@ layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 3) uniform sampler // --- tuning ------------------------------------------------------------------------------------------------------------------ const float snow_flake_cell = 0.007; // a dot, a small puff or a drop at most every this many metres of the glass (its size) const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff -const float snow_drops = 0.35; // share of the texels with the water of a melted flake showing a drop (more with more water) +const float snow_drops = 0.05; // share of the texels with the water of a melted flake showing a drop (more with more water) const float snow_deep = 2.5; // mm of snow from which the cover is opaque (no picture behind it) const float snow_cover = 0.25; // the lumps get opaque from three times this many mm of snow const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) @@ -223,7 +223,7 @@ void snFlakes(vec2 span, float pixelUV, inout sprite_acc acc) float alpha = smoothstep(0.03, 0.1, q.y); if (crystal) { - tile = min(int(kind * 4.0), 3); // dots, small puffs + tile = 2 + min(int(kind * 2.0), 1); // small icy puffs alpha = snow_thin; } snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0, acc); @@ -259,6 +259,7 @@ struct lump_grid vec2 size; // the size of its lumps, cells: from .. to (random per cell) int tiles; // its tiles: the first one and how many int count; + float share; // the share of its cells having a lump at all (1: all of them) }; void snLumps(vec2 span, float pixelUV, lump_grid grid, inout sprite_acc acc) @@ -276,7 +277,7 @@ void snLumps(vec2 span, float pixelUV, lump_grid grid, inout sprite_acc acc) // the snow it takes, sooner in a heap float needs = mix(grid.snow.x, grid.snow.y, RandF(seed)) * mix(1.4, 0.6, snHeap(cell)); vec4 q = water_snow_at(uint(snSlot), snMap, (centre - grid.shift) / perUV); - if (q.x <= needs) + if ((q.x <= needs) || (RandF(seed) >= grid.share)) continue; float ang = RandF(seed) * 6.2831853; vec2 rot = vec2(cos(ang), sin(ang)); @@ -327,17 +328,18 @@ void main() ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); - // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: dots and crumbs, - // two of small puffs and icy clumps (the fleece), clumps, four of small lumps of packed snow (they close the glass by - // 2-3 mm) - snLumps(span, pixelUV, lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(0.6, 1.1), 0, 4), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(0.8, 1.4), 2, 4), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.25), 97u, vec2(0.2, 0.9), vec2(0.8, 1.4), 2, 4), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.1, 1.7), 10, 2), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.75, 0.25), 151u, vec2(0.8, 2.0), vec2(1.2, 1.6), 12, 2), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.2), vec2(1.2, 1.6), 12, 2), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.0, 0.5), 233u, vec2(1.2, 2.5), vec2(1.2, 1.6), 12, 2), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.75), 251u, vec2(1.4, 2.8), vec2(1.2, 1.6), 12, 2), layer); + // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: all of them icy + // fleece (small puffs and icy clumps, tiles 2-5), more and bigger, closing the glass by 2-3 mm + snLumps(span, pixelUV, lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(1.2, 2.0), 2, 4, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(1.4, 2.4), 2, 4, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.25), 97u, vec2(0.2, 0.9), vec2(1.4, 2.4), 2, 4, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.8, 2.8), 4, 2, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.75, 0.25), 151u, vec2(0.7, 1.6), vec2(1.8, 2.8), 4, 2, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.0), vec2(2.0, 3.0), 4, 2, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.0, 0.5), 233u, vec2(1.2, 2.4), vec2(2.0, 3.0), 4, 2, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.75), 251u, vec2(1.4, 2.8), vec2(2.0, 3.0), 4, 2, 1.0), layer); + // now and then a single lump of packed snow + snLumps(span, pixelUV, lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 12, 2, 0.03), layer); snFlakes(span, pixelUV, flakes); vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); From af4f01ec000a4fe1a22d9f3e58420a1d271e252a Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Thu, 12 Nov 2026 12:47:38 +0100 Subject: [PATCH 094/123] Snow windscreen: the tiles of the atlas from the top of its picture The shader counted the rows of the tiles from v = 0, the bottom of the picture of the atlas as the texture holds it, while snieg_atlas_maszyna.py numbers them from the top: every tile drawn was the one of the mirrored row (the fleece of tiles 2-5 came out as slush, drops and wet lumps, 6-7 as the clumps with stars...), so the glass showed other shapes than the atlas and its previews. The rows are counted from the top now, of the old 2 x 2 atlas too (its tiles at the places the old snow shader used). No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_snow_windscreen.frag | 6 ++++-- shaders/vk14/mat_snow_windscreen.frag | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index 55d531506..7c2f23949 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -110,10 +110,12 @@ struct sprite_acc }; // the corner of a tile in the atlas; an older 2 x 2 atlas stands its four tiles in for the sixteen +// the rows of the tiles counted from the top of the picture of the atlas (as snieg_atlas_maszyna.py makes it), the v of the +// texture from its bottom: the first row is at the top of the texture (the tiles of the old 2 x 2 atlas the same way) vec2 snTile(int tile) { if (snBig) - return vec2(float(tile % 4), float(tile / 4)) * 0.25; + return vec2(float(tile % 4), float(3 - tile / 4)) * 0.25; int old = 0; // a fluffy flake if ((tile == 6) || (tile == 7)) old = 2; // crumbs @@ -121,7 +123,7 @@ vec2 snTile(int tile) old = 1; // a wet lump else if (tile == TILE_DROP) old = 3; // a melted spot - return vec2(float(old % 2), float(old / 2)) * 0.5; + return vec2(float(old % 2), float(1 - old / 2)) * 0.5; } float snTileSize() diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index 1aed0a3e2..eee6dcbbd 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -115,10 +115,12 @@ struct sprite_acc }; // the corner of a tile in the atlas; an older 2 x 2 atlas stands its four tiles in for the sixteen +// the rows of the tiles counted from the top of the picture of the atlas (as snieg_atlas_maszyna.py makes it), the v of the +// texture from its bottom: the first row is at the top of the texture (the tiles of the old 2 x 2 atlas the same way) vec2 snTile(int tile) { if (snBig) - return vec2(float(tile % 4), float(tile / 4)) * 0.25; + return vec2(float(tile % 4), float(3 - tile / 4)) * 0.25; int old = 0; // a fluffy flake if ((tile == 6) || (tile == 7)) old = 2; // crumbs @@ -126,7 +128,7 @@ vec2 snTile(int tile) old = 1; // a wet lump else if (tile == TILE_DROP) old = 3; // a melted spot - return vec2(float(old % 2), float(old / 2)) * 0.5; + return vec2(float(old % 2), float(1 - old / 2)) * 0.5; } float snTileSize() From 15ed61f58715c711c8e41171d03bb9baedd691b2 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Thu, 12 Nov 2026 13:01:13 +0100 Subject: [PATCH 095/123] Windscreen snow: icier lumps, slower build-up Lumps stay 60% opaque until the snow is deep and take a faint blue ice tint. Only 1.5x (was 4x) of the snowfall share reaches the glass, and the facing gain from speed is capped at 6, so overcast 1.5 plasters the glass in about ten minutes standing instead of a few. No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_snow_windscreen.frag | 6 ++++-- shaders/ogl46/water_snow.comp | 9 ++++++--- shaders/vk14/mat_snow_windscreen.frag | 6 ++++-- shaders/vk14/water_snow.comp | 9 ++++++--- 4 files changed, 20 insertions(+), 10 deletions(-) diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index 7c2f23949..88f9f13a7 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -74,6 +74,8 @@ const float snow_cover = 0.25; // the lumps get opaque from three times th const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) +const float snow_ice = 0.6; // opacity of a lump until the snow gets thick (icy: the picture shows through, bent) +const vec3 snow_ice_tint = vec3(0.93, 0.97, 1.0); // the colour of the icy snow const float snow_thin = 0.45; // opacity of a single thin flake (ice crystals let most of the light through) const float snow_bump = 1.0; // strength of the relief from the normal map, 0 = flat const float snow_gloss = 0.8; // glints of the sun / headlights on the wet snow, 0 = matt @@ -181,7 +183,7 @@ float snWetness(vec4 q) // the tone of the snow: grey and darker when wet (slush), a little grey when packed vec3 snTone(vec4 q, float random) { - vec3 tone = vec3(mix(0.94, 1.04, random)); + vec3 tone = vec3(mix(0.94, 1.04, random)) * snow_ice_tint; tone *= mix(vec3(1.0), vec3(0.95, 0.96, 0.98), q.z); return tone * mix(vec3(1.0), vec3(0.88, 0.91, 0.94), smoothstep(0.3, 0.8, snWetness(q))); } @@ -288,7 +290,7 @@ void snLumps(vec2 span, float pixelUV, lump_grid grid, inout sprite_acc acc) continue; // fading in over the first snow (no flicker on the edge), opaque when thick; the thick snow bends nothing float deep = smoothstep(snow_cover * 3.0, snow_deep, q.x); - float alpha = smoothstep(needs, needs + 0.04, q.x) * mix(0.8, 1.0, deep); + float alpha = smoothstep(needs, needs + 0.04, q.x) * mix(snow_ice, 1.0, deep); snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0 - deep, acc); } } diff --git a/shaders/ogl46/water_snow.comp b/shaders/ogl46/water_snow.comp index 7680b570e..a1bb958c2 100644 --- a/shaders/ogl46/water_snow.comp +++ b/shaders/ogl46/water_snow.comp @@ -47,8 +47,11 @@ const float SNOW_WIPE_WET = 0.015; // ~70 W/m2 a degree, melts 0.0002 mm of water a second) const float SNOW_MELT = 0.0002; // the share of the snowfall the flakes of water_snow.x make (the renderer counts a quarter of them, as for the particles of the -// drop passes): the snow of the map gets all of it -const float SNOW_FALL_SHARE = 4.0; +// drop passes): the snow of the map gets a bit more of it (all of it built up too fast) +const float SNOW_FALL_SHARE = 1.5; +// the most of the speed of the snow against the glass counting for the snow landing, m/s: at speed most of the flakes go past or +// bounce off, so a front glass builds up its snow a few times as fast as a standing one, not a hundred +const float SNOW_FACING_MOST = 6.0; // how much warmer than the air the glass is, the share of the warmth given (water_snow.y, the cab heats it) const float SNOW_WARMTH = 1.0; // the share of a flake landing near zero already water (wet snow) @@ -253,7 +256,7 @@ void main() // the vehicle and its velocity) don't agree for every cab, and with them disagreeing a front glass at speed got the snow of // the eddies only, plastered no faster than a standing one. the glass the driver looks through leads, so the snow comes at // it from the outside - float facing = abs(dot(coming, frame.normal)) + SNOW_EDDIES; + float facing = min(abs(dot(coming, frame.normal)), SNOW_FACING_MOST) + SNOW_EDDIES; float density = mix(SNOW_FRESH, SNOW_PACKED, state.z); float wet = state.y / (state.y + state.x * density + 1e-4); // the dry flakes bounce off a moving glass (powder is blown away), the wet ones (near zero) and those landing on wet snow or diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index eee6dcbbd..d9dfc0933 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -79,6 +79,8 @@ const float snow_cover = 0.25; // the lumps get opaque from three times th const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) +const float snow_ice = 0.6; // opacity of a lump until the snow gets thick (icy: the picture shows through, bent) +const vec3 snow_ice_tint = vec3(0.93, 0.97, 1.0); // the colour of the icy snow const float snow_thin = 0.45; // opacity of a single thin flake (ice crystals let most of the light through) const float snow_bump = 1.0; // strength of the relief from the normal map, 0 = flat const float snow_gloss = 0.8; // glints of the sun / headlights on the wet snow, 0 = matt @@ -186,7 +188,7 @@ float snWetness(vec4 q) // the tone of the snow: grey and darker when wet (slush), a little grey when packed vec3 snTone(vec4 q, float random) { - vec3 tone = vec3(mix(0.94, 1.04, random)); + vec3 tone = vec3(mix(0.94, 1.04, random)) * snow_ice_tint; tone *= mix(vec3(1.0), vec3(0.95, 0.96, 0.98), q.z); return tone * mix(vec3(1.0), vec3(0.88, 0.91, 0.94), smoothstep(0.3, 0.8, snWetness(q))); } @@ -293,7 +295,7 @@ void snLumps(vec2 span, float pixelUV, lump_grid grid, inout sprite_acc acc) continue; // fading in over the first snow (no flicker on the edge), opaque when thick; the thick snow bends nothing float deep = smoothstep(snow_cover * 3.0, snow_deep, q.x); - float alpha = smoothstep(needs, needs + 0.04, q.x) * mix(0.8, 1.0, deep); + float alpha = smoothstep(needs, needs + 0.04, q.x) * mix(snow_ice, 1.0, deep); snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0 - deep, acc); } } diff --git a/shaders/vk14/water_snow.comp b/shaders/vk14/water_snow.comp index 4a8ee2dcb..a3129be3f 100644 --- a/shaders/vk14/water_snow.comp +++ b/shaders/vk14/water_snow.comp @@ -50,8 +50,11 @@ const float SNOW_WIPE_WET = 0.015; // ~70 W/m2 a degree, melts 0.0002 mm of water a second) const float SNOW_MELT = 0.0002; // the share of the snowfall the flakes of water_snow.x make (the renderer counts a quarter of them, as for the particles of the -// drop passes): the snow of the map gets all of it -const float SNOW_FALL_SHARE = 4.0; +// drop passes): the snow of the map gets a bit more of it (all of it built up too fast) +const float SNOW_FALL_SHARE = 1.5; +// the most of the speed of the snow against the glass counting for the snow landing, m/s: at speed most of the flakes go past or +// bounce off, so a front glass builds up its snow a few times as fast as a standing one, not a hundred +const float SNOW_FACING_MOST = 6.0; // how much warmer than the air the glass is, the share of the warmth given (water_snow.y, the cab heats it) const float SNOW_WARMTH = 1.0; // the share of a flake landing near zero already water (wet snow) @@ -256,7 +259,7 @@ void main() // the vehicle and its velocity) don't agree for every cab, and with them disagreeing a front glass at speed got the snow of // the eddies only, plastered no faster than a standing one. the glass the driver looks through leads, so the snow comes at // it from the outside - float facing = abs(dot(coming, frame.normal)) + SNOW_EDDIES; + float facing = min(abs(dot(coming, frame.normal)), SNOW_FACING_MOST) + SNOW_EDDIES; float density = mix(SNOW_FRESH, SNOW_PACKED, state.z); float wet = state.y / (state.y + state.x * density + 1e-4); // the dry flakes bounce off a moving glass (powder is blown away), the wet ones (near zero) and those landing on wet snow or From f66d825a046b58bce0c9d5acb8e683a5b50d68cc Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Fri, 13 Nov 2026 20:54:42 +0100 Subject: [PATCH 096/123] Windscreen snow: a wiped edge that stays, small gaps, blur, slabs sliding off [skip ci] - The snow no longer spreads onto its neighbours by itself: the snow piled outside the sweep slipped onto the wiped glass whenever the blade stopped, and a rim grew along the edge of the wipermask. - Lumps on thick snow are 12% smaller, so a plastered glass keeps a few small gaps. - The scene behind the snow is blurred as the rain mists the glass: from 0.05 mm of snow, fully from 0.6 mm, clear again behind a blade. - Now and then a slab of the snow lets go and slides off the glass, wiped or not: each slab from a random depth of snow in its middle (0.4 .. 2.5 mm), a slab every 3 s on a glass plastered over, fewer on a frozen glass. No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_snow_windscreen.frag | 8 ++- shaders/ogl46/water_snow.comp | 96 ++++++++++++++++++++------ shaders/vk14/mat_snow_windscreen.frag | 8 ++- shaders/vk14/water_snow.comp | 96 ++++++++++++++++++++------ 4 files changed, 158 insertions(+), 50 deletions(-) diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index 88f9f13a7..c4ceca540 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -14,7 +14,7 @@ // - the lumps, in nine grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, // size, the snow it takes); it comes when the snow around reaches that and stays as it is until the snow goes. The grids come // one after the other as the snow piles up (all of them icy fleece, more and bigger; a lump of packed snow very rarely), each on the ones before, -// so the snow accumulates rather than changes, and closes the glass by 2-3 mm. In a heap they come sooner +// so the snow accumulates rather than changes, and covers the glass by 2-3 mm, small gaps left (the scene behind them blurred). In a heap they come sooner // - dots and small puffs of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) // A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. // @@ -72,6 +72,7 @@ const float snow_drops = 0.05; // share of the texels with the water of a const float snow_deep = 2.5; // mm of snow from which the cover is opaque (no picture behind it) const float snow_cover = 0.25; // the lumps get opaque from three times this many mm of snow const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) +const vec2 snow_lump_grow = vec2(0.75, 0.88); // a lump's size as it comes .. on thick snow, of its size (small gaps stay open) const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) const float snow_ice = 0.6; // opacity of a lump until the snow gets thick (icy: the picture shows through, bent) @@ -84,6 +85,8 @@ const float snow_translucency = 0.8; // glow of thin snow when you look towards const float snow_haze = 1.0; // blur of the scene behind thin snow (frosted glass), 0 = off const float snow_drop_bend = 1.0; // how strongly the drops bend the picture behind them const float snow_wet_blur = 0.6; // blur of the scene behind a wet film +const vec2 snow_blur_mm = vec2(0.05, 0.6); // the scene behind the snow blurred from .. fully at this many mm of it (as the rain + // mists the glass up: the gaps between the lumps too, clear again behind a blade) const float WS_REFR_MAXPX = 96.0; // the largest picture shift the post-processing makes, screen pixels; as rain_windscreen_haze.glsl const float WS_BEND_ENC = 60.0; // the bend request in the velocity target; as rain_windscreen_haze.glsl @@ -284,7 +287,7 @@ void snLumps(vec2 span, float pixelUV, lump_grid grid, inout sprite_acc acc) int tile = grid.tiles + min(int(RandF(seed) * float(grid.count)), grid.count - 1); float random = RandF(seed); float aniso = mix(0.8, 1.0, RandF(seed)); - float size = mix(grid.size.x, grid.size.y, RandF(seed)) * mix(0.85, 1.15, smoothstep(needs, needs * 2.0 + 0.2, q.x)); + float size = mix(grid.size.x, grid.size.y, RandF(seed)) * mix(snow_lump_grow.x, snow_lump_grow.y, smoothstep(needs, needs * 2.0 + 0.2, q.x)); vec2 local; if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, aniso, local)) continue; @@ -344,6 +347,7 @@ void main() wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); // the picture behind thin flakes and a wet film is blurred snHaze = max(smoothstep(0.0, 0.3, flakes.a + layer.a) * (1.0 - smoothstep(0.5, 0.9, layer.a)) * 0.6, wet * snow_wet_blur); + snHaze = max(snHaze, smoothstep(snow_blur_mm.x, snow_blur_mm.y, q.x)); } // the flakes over the layer vec3 snowRGB = flakes.rgb + layer.rgb * (1.0 - flakes.a); diff --git a/shaders/ogl46/water_snow.comp b/shaders/ogl46/water_snow.comp index a1bb958c2..57e968437 100644 --- a/shaders/ogl46/water_snow.comp +++ b/shaders/ogl46/water_snow.comp @@ -8,10 +8,11 @@ // into the snow), how packed the snow is (0 fresh flakes .. 1 snow pressed by a blade) and a random number, the shape of its // flakes (mat_snow_windscreen.frag). in a step, in this order: // - the snow and the water move: wet heavy snow (slush) slides down the glass, dry powder is blown along it by the air at speed, -// the water runs down as a film and is pushed by the air; and snow piled higher than its neighbours by more than it holds slips -// onto them. what goes over the edge of the glass falls off +// the water runs down as a film and is pushed by the air. what goes over the edge of the glass falls off. snow doesn't spread +// onto its neighbours by itself: it sticks to the glass, so the edge of a wiped area stays where the blade left it // - the blades wipe, as they wipe the rain: a blade going over a texel in the step takes its snow (a little stays, and a wet // trace of the water); what it takes is gone +// - now and then the thick snow lets go of the glass in a slab and slides off it, the glass bare behind it // - the flakes land: as many as come to the glass facing the snow coming at it against the cab (and a few in the eddies of the // air where it doesn't face it), each bringing its snow to the texel; the faster the vehicle the more of the dry ones bounce off. // near zero the flakes are wet: they bring some water with them (wet snow, lumps of slush) @@ -31,11 +32,8 @@ const float SNOW_FLAKE_LEAST = 0.3; const float SNOW_FLAKE_MOST = 2.5; // the speed of the snow coming at the glass in the eddies of the air, m/s: a glass not facing the snow gets a little of it const float SNOW_EDDIES = 0.6; -// the most snow a texel holds, mm, and the step of the snow to a neighbour it holds without slipping onto it, mm +// the most snow a texel holds, mm const float SNOW_MOST = 40.0; -const float SNOW_REPOSE = 3.0; -// the share of the snow over the step slipping onto the neighbour in a second -const float SNOW_SLIP = 6.0; // the share of the snow a blade leaves (at most SNOW_WIPE_LEFT mm: the snow it pushes along goes with it), of the water, and // of the water of the snow it takes which it leaves as a wet trace (at most SNOW_WIPE_WET mm) const float SNOW_WIPE_MISS = 0.03; @@ -68,6 +66,26 @@ const float SNOW_BLOW = 0.001; const float SNOW_RUN = 0.02; const float SNOW_RUN_AIR = 0.002; +// the slabs: where the snow is thick, now and then a slab of it lets go and slides off the glass (on a glass plastered over a slab +// every SNOW_SLAB_EVERY seconds, on a frozen glass less often). its upper edge goes down the slab in SNOW_SLAB_SLIDE seconds and +// the glass behind it is bare, but for a little of the snow +// (the snow in the middle of the slab decides: the whole slab goes, a wiped glass as one never wiped, where the snow is as thick). +// every slab lets go from snow of its own, random: the more snow, the more of them go +const vec2 SNOW_SLAB_DEEP = vec2(0.4, 2.5); // mm of snow from which a slab lets go: from .. to (the glass is closed by 2-3 mm) +const float SNOW_SLAB_CELL = 24.0; // texels: at most a slab in a cell this big, about as big as the cell +const float SNOW_SLAB_EVERY = 3.0; // s +const float SNOW_SLAB_PERIOD = 10.0; // s: a cell draws for its slab once in this time +const float SNOW_SLAB_SLIDE = 1.2; // s +const float SNOW_SLAB_LEFT = 0.05; // the share of the snow a slab leaves + +struct snow_slab_s +{ + vec2 centre; // texels + float radius; // texels + float start; // s into the period + float deep; // mm of snow in its middle from which it lets go +}; + uint snow_slot; uint snow_from; uint snow_axes_base; @@ -104,16 +122,49 @@ bool snow_crossed(ivec2 texel, int blade) return (now > before) ? ((place > before) && (place <= now)) : ((place < before) && (place >= now)); } -// whether no blade goes over the texel now: the snow piled there may slip onto its neighbours (in a sweep of a working blade -// the snow it pushes would slip behind it, a stripe of snow left on the wiped glass for every step) -bool snow_unswept(ivec2 texel) +// the slab of a cell in a period, if the cell has one; the more often the warmer the glass (wet snow lets go sooner) +bool snow_slab_of(ivec2 cell, uint period, float glass, out snow_slab_s slab) { - for (int blade = 0; blade < 4; ++blade) + vec4 draw = water_random(uint(cell.x + 64), uint(cell.y + 64) + 977u * snow_slot, period, 0x51abu); + vec4 shape = water_random(uint(cell.x + 64), uint(cell.y + 64) + 977u * snow_slot, period, 0x51acu); + slab = snow_slab_s((vec2(cell) + 0.2 + 0.6 * shape.xy) * SNOW_SLAB_CELL, mix(0.5, 0.9, shape.z) * SNOW_SLAB_CELL, + shape.w * (SNOW_SLAB_PERIOD - SNOW_SLAB_SLIDE), mix(SNOW_SLAB_DEEP.x, SNOW_SLAB_DEEP.y, draw.y)); + float cells = float(WATER_MAP * WATER_MAP) / (SNOW_SLAB_CELL * SNOW_SLAB_CELL); + float chance = SNOW_SLAB_PERIOD / SNOW_SLAB_EVERY / cells * mix(0.4, 1.0, smoothstep(-6.0, 0.0, glass)); + return draw.x < chance; +} + +// whether the upper edge of the slab is past the place (texels) now, t seconds into the period: the place in the slab (its edge +// ragged) and above the edge going down it, faster and faster +bool snow_in_slab(vec2 p, vec2 down, float t, snow_slab_s slab) +{ + float progress = (t - slab.start) / SNOW_SLAB_SLIDE; + if ((progress < 0.0) || (progress > 1.0)) + return false; + vec2 off = p - slab.centre; + float ragged = slab.radius * mix(0.7, 1.15, water_noise(p / 5.0, 0x5a1bu + snow_slot)); + if (dot(off, off) > ragged * ragged) + return false; + return dot(off, down) < mix(-1.2, 1.2, progress * progress) * slab.radius; +} + +// whether a slab slides off the texel now; down: down the glass, texels (normalized) +bool snow_slid(ivec2 texel, vec2 down, float glass) +{ + float now = water_step.y; + uint period = uint(floor(now / SNOW_SLAB_PERIOD)); + float t = now - float(period) * SNOW_SLAB_PERIOD; + ivec2 here = ivec2(floor(vec2(texel) / SNOW_SLAB_CELL)); + vec2 p = vec2(texel) + 0.5; + for (int k = 0; k < 9; ++k) { - if ((water_blades_now[blade] >= 0.0) && (water_blades_now[blade] != water_blades_before[blade]) && (snow_blade(texel, blade) > 0.001)) - return false; + snow_slab_s slab; + if ((false == snow_slab_of(here + ivec2(k % 3 - 1, k / 3 - 1), period, glass, slab)) || (false == snow_in_slab(p, down, t, slab))) + continue; + if (snow_get(ivec2(floor(slab.centre))).x >= slab.deep) + return true; } - return true; + return false; } // the frame of the glass at a texel, unfiltered @@ -168,23 +219,16 @@ vec4 snow_move(ivec2 texel, vec4 state, float seconds) float snow = state.x * (1.0 - snowout.x - snowout.y); float water = state.y * (1.0 - waterout.x - waterout.y); float packed = state.z * snow; - bool unswept = snow_unswept(texel); - float slip = min(SNOW_SLIP * seconds, 0.2); const ivec2 sides[4] = ivec2[4](ivec2(1, 0), ivec2(-1, 0), ivec2(0, 1), ivec2(0, -1)); for (int k = 0; k < 4; ++k) { ivec2 side = sides[k]; ivec2 other = texel + side; bool glass = snow_on_glass(other); - vec4 neighbour = glass ? water_snow_texel(snow_slot, snow_from, other) : vec4(0.0); - // slipping onto the neighbour (off the glass: falling off) and from it, where no blade goes over either now - bool slips = unswept && snow_unswept(other); - float away = slips ? slip * max(state.x - neighbour.x - SNOW_REPOSE, 0.0) : 0.0; - snow -= away; - packed -= away * state.z; if (false == glass) continue; - float coming = slips ? slip * max(neighbour.x - state.x - SNOW_REPOSE, 0.0) : 0.0; + vec4 neighbour = water_snow_texel(snow_slot, snow_from, other); + float coming = 0.0; // what the motion of the neighbour brings: it goes this way along the axis of the side vec4 itsmotion = snow_motion(other, neighbour); vec2 itssnow = snow_out(itsmotion.xy, seconds); @@ -247,8 +291,14 @@ void main() state.y = state.y * SNOW_WIPE_WATER + trace; } - // the flakes landing + // a slab sliding off (not on a glass lying flat) water_frame_s frame = snow_frame(texel); + vec3 down = -water_up.xyz; + vec2 downmap = water_to_uv(frame, down - frame.normal * dot(down, frame.normal)) * float(WATER_MAP); + if ((state.x > 0.0) && (dot(downmap, downmap) > 0.25) && snow_slid(texel, normalize(downmap), glass)) + state.x *= SNOW_SLAB_LEFT; + + // the flakes landing float area = length(cross(frame.tu, frame.tv)) / float(WATER_MAP * WATER_MAP); // m2 vec3 coming = water_air.xyz - water_up.xyz * water_air.w; // the snow against the cab, m/s // the snow coming at the glass along its normal. the side of the glass the snow comes from isn't told: the outward side of diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index d9dfc0933..65688ab06 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -15,7 +15,7 @@ // - the lumps, in nine grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, // size, the snow it takes); it comes when the snow around reaches that and stays as it is until the snow goes. The grids come // one after the other as the snow piles up (all of them icy fleece, more and bigger; a lump of packed snow very rarely), each on the ones before, -// so the snow accumulates rather than changes, and closes the glass by 2-3 mm. In a heap they come sooner +// so the snow accumulates rather than changes, and covers the glass by 2-3 mm, small gaps left (the scene behind them blurred). In a heap they come sooner // - dots and small puffs of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) // A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. // @@ -77,6 +77,7 @@ const float snow_drops = 0.05; // share of the texels with the water of a const float snow_deep = 2.5; // mm of snow from which the cover is opaque (no picture behind it) const float snow_cover = 0.25; // the lumps get opaque from three times this many mm of snow const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) +const vec2 snow_lump_grow = vec2(0.75, 0.88); // a lump's size as it comes .. on thick snow, of its size (small gaps stay open) const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) const float snow_ice = 0.6; // opacity of a lump until the snow gets thick (icy: the picture shows through, bent) @@ -89,6 +90,8 @@ const float snow_translucency = 0.8; // glow of thin snow when you look towards const float snow_haze = 1.0; // blur of the scene behind thin snow (frosted glass), 0 = off const float snow_drop_bend = 1.0; // how strongly the drops bend the picture behind them const float snow_wet_blur = 0.6; // blur of the scene behind a wet film +const vec2 snow_blur_mm = vec2(0.05, 0.6); // the scene behind the snow blurred from .. fully at this many mm of it (as the rain + // mists the glass up: the gaps between the lumps too, clear again behind a blade) const float WS_REFR_MAXPX = 96.0; // the largest picture shift the post-processing makes, screen pixels; as rain_windscreen_haze.glsl const float WS_BEND_ENC = 60.0; // the bend request in the velocity target; as rain_windscreen_haze.glsl @@ -289,7 +292,7 @@ void snLumps(vec2 span, float pixelUV, lump_grid grid, inout sprite_acc acc) int tile = grid.tiles + min(int(RandF(seed) * float(grid.count)), grid.count - 1); float random = RandF(seed); float aniso = mix(0.8, 1.0, RandF(seed)); - float size = mix(grid.size.x, grid.size.y, RandF(seed)) * mix(0.85, 1.15, smoothstep(needs, needs * 2.0 + 0.2, q.x)); + float size = mix(grid.size.x, grid.size.y, RandF(seed)) * mix(snow_lump_grow.x, snow_lump_grow.y, smoothstep(needs, needs * 2.0 + 0.2, q.x)); vec2 local; if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, aniso, local)) continue; @@ -349,6 +352,7 @@ void main() wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); // the picture behind thin flakes and a wet film is blurred snHaze = max(smoothstep(0.0, 0.3, flakes.a + layer.a) * (1.0 - smoothstep(0.5, 0.9, layer.a)) * 0.6, wet * snow_wet_blur); + snHaze = max(snHaze, smoothstep(snow_blur_mm.x, snow_blur_mm.y, q.x)); } // the flakes over the layer vec3 snowRGB = flakes.rgb + layer.rgb * (1.0 - flakes.a); diff --git a/shaders/vk14/water_snow.comp b/shaders/vk14/water_snow.comp index a3129be3f..69fa1acad 100644 --- a/shaders/vk14/water_snow.comp +++ b/shaders/vk14/water_snow.comp @@ -8,10 +8,11 @@ // into the snow), how packed the snow is (0 fresh flakes .. 1 snow pressed by a blade) and a random number, the shape of its // flakes (mat_snow_windscreen.frag). in a step, in this order: // - the snow and the water move: wet heavy snow (slush) slides down the glass, dry powder is blown along it by the air at speed, -// the water runs down as a film and is pushed by the air; and snow piled higher than its neighbours by more than it holds slips -// onto them. what goes over the edge of the glass falls off +// the water runs down as a film and is pushed by the air. what goes over the edge of the glass falls off. snow doesn't spread +// onto its neighbours by itself: it sticks to the glass, so the edge of a wiped area stays where the blade left it // - the blades wipe, as they wipe the rain: a blade going over a texel in the step takes its snow (a little stays, and a wet // trace of the water); what it takes is gone +// - now and then the thick snow lets go of the glass in a slab and slides off it, the glass bare behind it // - the flakes land: as many as come to the glass facing the snow coming at it against the cab (and a few in the eddies of the // air where it doesn't face it), each bringing its snow to the texel; the faster the vehicle the more of the dry ones bounce off. // near zero the flakes are wet: they bring some water with them (wet snow, lumps of slush) @@ -34,11 +35,8 @@ const float SNOW_FLAKE_LEAST = 0.3; const float SNOW_FLAKE_MOST = 2.5; // the speed of the snow coming at the glass in the eddies of the air, m/s: a glass not facing the snow gets a little of it const float SNOW_EDDIES = 0.6; -// the most snow a texel holds, mm, and the step of the snow to a neighbour it holds without slipping onto it, mm +// the most snow a texel holds, mm const float SNOW_MOST = 40.0; -const float SNOW_REPOSE = 3.0; -// the share of the snow over the step slipping onto the neighbour in a second -const float SNOW_SLIP = 6.0; // the share of the snow a blade leaves (at most SNOW_WIPE_LEFT mm: the snow it pushes along goes with it), of the water, and // of the water of the snow it takes which it leaves as a wet trace (at most SNOW_WIPE_WET mm) const float SNOW_WIPE_MISS = 0.03; @@ -71,6 +69,26 @@ const float SNOW_BLOW = 0.001; const float SNOW_RUN = 0.02; const float SNOW_RUN_AIR = 0.002; +// the slabs: where the snow is thick, now and then a slab of it lets go and slides off the glass (on a glass plastered over a slab +// every SNOW_SLAB_EVERY seconds, on a frozen glass less often). its upper edge goes down the slab in SNOW_SLAB_SLIDE seconds and +// the glass behind it is bare, but for a little of the snow +// (the snow in the middle of the slab decides: the whole slab goes, a wiped glass as one never wiped, where the snow is as thick). +// every slab lets go from snow of its own, random: the more snow, the more of them go +const vec2 SNOW_SLAB_DEEP = vec2(0.4, 2.5); // mm of snow from which a slab lets go: from .. to (the glass is closed by 2-3 mm) +const float SNOW_SLAB_CELL = 24.0; // texels: at most a slab in a cell this big, about as big as the cell +const float SNOW_SLAB_EVERY = 3.0; // s +const float SNOW_SLAB_PERIOD = 10.0; // s: a cell draws for its slab once in this time +const float SNOW_SLAB_SLIDE = 1.2; // s +const float SNOW_SLAB_LEFT = 0.05; // the share of the snow a slab leaves + +struct snow_slab_s +{ + vec2 centre; // texels + float radius; // texels + float start; // s into the period + float deep; // mm of snow in its middle from which it lets go +}; + uint snow_slot; uint snow_from; uint snow_axes_base; @@ -107,16 +125,49 @@ bool snow_crossed(ivec2 texel, int blade) return (now > before) ? ((place > before) && (place <= now)) : ((place < before) && (place >= now)); } -// whether no blade goes over the texel now: the snow piled there may slip onto its neighbours (in a sweep of a working blade -// the snow it pushes would slip behind it, a stripe of snow left on the wiped glass for every step) -bool snow_unswept(ivec2 texel) +// the slab of a cell in a period, if the cell has one; the more often the warmer the glass (wet snow lets go sooner) +bool snow_slab_of(ivec2 cell, uint period, float glass, out snow_slab_s slab) { - for (int blade = 0; blade < 4; ++blade) + vec4 draw = water_random(uint(cell.x + 64), uint(cell.y + 64) + 977u * snow_slot, period, 0x51abu); + vec4 shape = water_random(uint(cell.x + 64), uint(cell.y + 64) + 977u * snow_slot, period, 0x51acu); + slab = snow_slab_s((vec2(cell) + 0.2 + 0.6 * shape.xy) * SNOW_SLAB_CELL, mix(0.5, 0.9, shape.z) * SNOW_SLAB_CELL, + shape.w * (SNOW_SLAB_PERIOD - SNOW_SLAB_SLIDE), mix(SNOW_SLAB_DEEP.x, SNOW_SLAB_DEEP.y, draw.y)); + float cells = float(WATER_MAP * WATER_MAP) / (SNOW_SLAB_CELL * SNOW_SLAB_CELL); + float chance = SNOW_SLAB_PERIOD / SNOW_SLAB_EVERY / cells * mix(0.4, 1.0, smoothstep(-6.0, 0.0, glass)); + return draw.x < chance; +} + +// whether the upper edge of the slab is past the place (texels) now, t seconds into the period: the place in the slab (its edge +// ragged) and above the edge going down it, faster and faster +bool snow_in_slab(vec2 p, vec2 down, float t, snow_slab_s slab) +{ + float progress = (t - slab.start) / SNOW_SLAB_SLIDE; + if ((progress < 0.0) || (progress > 1.0)) + return false; + vec2 off = p - slab.centre; + float ragged = slab.radius * mix(0.7, 1.15, water_noise(p / 5.0, 0x5a1bu + snow_slot)); + if (dot(off, off) > ragged * ragged) + return false; + return dot(off, down) < mix(-1.2, 1.2, progress * progress) * slab.radius; +} + +// whether a slab slides off the texel now; down: down the glass, texels (normalized) +bool snow_slid(ivec2 texel, vec2 down, float glass) +{ + float now = water_step.y; + uint period = uint(floor(now / SNOW_SLAB_PERIOD)); + float t = now - float(period) * SNOW_SLAB_PERIOD; + ivec2 here = ivec2(floor(vec2(texel) / SNOW_SLAB_CELL)); + vec2 p = vec2(texel) + 0.5; + for (int k = 0; k < 9; ++k) { - if ((water_blades_now[blade] >= 0.0) && (water_blades_now[blade] != water_blades_before[blade]) && (snow_blade(texel, blade) > 0.001)) - return false; + snow_slab_s slab; + if ((false == snow_slab_of(here + ivec2(k % 3 - 1, k / 3 - 1), period, glass, slab)) || (false == snow_in_slab(p, down, t, slab))) + continue; + if (snow_get(ivec2(floor(slab.centre))).x >= slab.deep) + return true; } - return true; + return false; } // the frame of the glass at a texel, unfiltered @@ -171,23 +222,16 @@ vec4 snow_move(ivec2 texel, vec4 state, float seconds) float snow = state.x * (1.0 - snowout.x - snowout.y); float water = state.y * (1.0 - waterout.x - waterout.y); float packed = state.z * snow; - bool unswept = snow_unswept(texel); - float slip = min(SNOW_SLIP * seconds, 0.2); const ivec2 sides[4] = ivec2[4](ivec2(1, 0), ivec2(-1, 0), ivec2(0, 1), ivec2(0, -1)); for (int k = 0; k < 4; ++k) { ivec2 side = sides[k]; ivec2 other = texel + side; bool glass = snow_on_glass(other); - vec4 neighbour = glass ? water_snow_texel(snow_slot, snow_from, other) : vec4(0.0); - // slipping onto the neighbour (off the glass: falling off) and from it, where no blade goes over either now - bool slips = unswept && snow_unswept(other); - float away = slips ? slip * max(state.x - neighbour.x - SNOW_REPOSE, 0.0) : 0.0; - snow -= away; - packed -= away * state.z; if (false == glass) continue; - float coming = slips ? slip * max(neighbour.x - state.x - SNOW_REPOSE, 0.0) : 0.0; + vec4 neighbour = water_snow_texel(snow_slot, snow_from, other); + float coming = 0.0; // what the motion of the neighbour brings: it goes this way along the axis of the side vec4 itsmotion = snow_motion(other, neighbour); vec2 itssnow = snow_out(itsmotion.xy, seconds); @@ -250,8 +294,14 @@ void main() state.y = state.y * SNOW_WIPE_WATER + trace; } - // the flakes landing + // a slab sliding off (not on a glass lying flat) water_frame_s frame = snow_frame(texel); + vec3 down = -water_up.xyz; + vec2 downmap = water_to_uv(frame, down - frame.normal * dot(down, frame.normal)) * float(WATER_MAP); + if ((state.x > 0.0) && (dot(downmap, downmap) > 0.25) && snow_slid(texel, normalize(downmap), glass)) + state.x *= SNOW_SLAB_LEFT; + + // the flakes landing float area = length(cross(frame.tu, frame.tv)) / float(WATER_MAP * WATER_MAP); // m2 vec3 coming = water_air.xyz - water_up.xyz * water_air.w; // the snow against the cab, m/s // the snow coming at the glass along its normal. the side of the glass the snow comes from isn't told: the outward side of From 02a0de85c205bde1353bc1647196df7a60ed1181 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Sat, 14 Nov 2026 20:41:21 +0100 Subject: [PATCH 097/123] Windscreen snow: lay the sprites into a layer of the glass, the glass only reads it The glass of the snow laid its nine grids of lumps (81 cells) and its flakes at every pixel in every frame, ~6-9 ms of the GPU at 1080p. Now a compute pass (water_snowlayer.comp, the sprites in snow_sprites.glsl) lays the snow of a glass into a layer of 1024 x 1024 texels over its uv after the step of the snow: a band of every 8th row in a step (the snow under a lump changes slowly) and at once wherever a blade went over the glass. The glass reads the layer filtered (mat_snow_windscreen.frag), as the glass of the rain reads its cells. Laid front to back: a texel stops once the snow over it covers it, and a cell reads the map only when its sprite reaches the texel. The storage of the water grows by the layers, 12 MiB for each of the four glasses. The look stays as it was. No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- gl/glsl_common.cpp | 4 + gl/ubo.h | 23 +- rendering/common/windscreenwater.cpp | 42 ++++ rendering/common/windscreenwater.h | 6 + rendering/opengl46/opengl46water.cpp | 25 +- rendering/opengl46/opengl46water.h | 2 + rendering/vulkan14/vulkan14shaders.cpp | 2 + rendering/vulkan14/vulkan14water.cpp | 33 ++- rendering/vulkan14/vulkan14water.h | 2 + shaders/ogl46/common.glsl | 4 + shaders/ogl46/mat_snow_windscreen.frag | 282 ++-------------------- shaders/ogl46/snow_sprites.glsl | 315 +++++++++++++++++++++++++ shaders/ogl46/water.glsl | 34 +++ shaders/ogl46/water_snowlayer.comp | 71 ++++++ shaders/vk14/common.glsl | 2 + shaders/vk14/mat_snow_windscreen.frag | 282 ++-------------------- shaders/vk14/snow_sprites.glsl | 315 +++++++++++++++++++++++++ shaders/vk14/water.glsl | 34 +++ shaders/vk14/water_snowlayer.comp | 73 ++++++ 19 files changed, 1018 insertions(+), 533 deletions(-) create mode 100644 shaders/ogl46/snow_sprites.glsl create mode 100644 shaders/ogl46/water_snowlayer.comp create mode 100644 shaders/vk14/snow_sprites.glsl create mode 100644 shaders/vk14/water_snowlayer.comp diff --git a/gl/glsl_common.cpp b/gl/glsl_common.cpp index 799698e3b..7c18fb9b8 100644 --- a/gl/glsl_common.cpp +++ b/gl/glsl_common.cpp @@ -56,6 +56,10 @@ void gl::glsl_common_setup() "#define RAIN_CELLS_SSBO_BINDING " + std::to_string(RAIN_CELLS_SSBO_BINDING) + "\n" + "#define WATER_UBO_BINDING " + std::to_string(WATER_UBO_BINDING) + "\n" + "#define WATER_MASK_TEX " + std::to_string(WATER_MASK_TEX) + "\n" + + "#define WATER_LAYER " + std::to_string(WATER_LAYER) + "\n" + + "#define WATER_LAYER_BANDS " + std::to_string(WATER_LAYER_BANDS) + "\n" + + "#define WATER_SNOW_ATLAS_TEX " + std::to_string(WATER_SNOW_ATLAS_TEX) + "\n" + + "#define WATER_SNOW_NORMAL_TEX " + std::to_string(WATER_SNOW_NORMAL_TEX) + "\n" + "#define INSTANCE_COUNTER_HEADER " + std::to_string(INSTANCE_COUNTER_HEADER) + "\n" + "#define INSTANCE_JOB_SLEEPERS " + std::to_string(INSTANCE_JOB_SLEEPERS) + "U\n" + "#define LIGHT_SSBO_BINDING " + std::to_string(LIGHT_SSBO_BINDING) + "\n" + diff --git a/gl/ubo.h b/gl/ubo.h index 66a10e2db..053fd2468 100644 --- a/gl/ubo.h +++ b/gl/ubo.h @@ -732,6 +732,10 @@ namespace gl const GLuint WATER_CELL_DROPS = 32; const GLuint WATER_TRAIL = 1024; const GLuint WATER_MAP = 256; + // the snow of a glass laid together (water_snowlayer.comp): WATER_LAYER x WATER_LAYER texels over its uv, a band of every + // WATER_LAYER_BANDS-th row laid anew in a step (and wherever a blade goes over it), read by mat_snow_windscreen.frag + const GLuint WATER_LAYER = 1024; + const GLuint WATER_LAYER_BANDS = 8; const GLuint WATER_GROUP_SIZE = 64; // the binding points of the opengl renderer: the storage of the water (read by the glasses, written by the passes), the block // of the step of the simulation (water_ubs) and the texture unit of the mask of the wipers the map is baked from. the storage @@ -749,6 +753,9 @@ namespace gl const size_t RAIN_CELLS_GROUP_SIZE = 64; const GLuint WATER_UBO_BINDING = 6; const size_t WATER_MASK_TEX = MAX_TEXTURES + HELPER_TEXTURES + 13; + // the atlas and the normal map of the snow of a glass, for the laying of its snow (water_snowlayer.comp) + const size_t WATER_SNOW_ATLAS_TEX = MAX_TEXTURES + HELPER_TEXTURES + 20; + const size_t WATER_SNOW_NORMAL_TEX = MAX_TEXTURES + HELPER_TEXTURES + 21; // the parts of the storage of the water (std430, GLSL water_ssbo), offsets in bytes: the header of every glass (vec4), the // counts of every glass (uvec4), the drops (two vec4 each), the axes of the map (two vec4 a texel), the blades of the map (vec4 // a texel), the state of the drops (uint), the drops they flow into (uint), what they gather (four int), what they keep @@ -772,10 +779,14 @@ namespace gl // flakes), a step reads one and writes the other (the header of the glass says which one is the latest) const size_t WATER_SNOW_OFFSET = WATER_TRAIL_OFFSET + 4 * static_cast(WATER_SLOTS) * WATER_TRAIL * WATER_TRAIL; const size_t WATER_SNOW_SIZE = 8 * static_cast(WATER_MAP) * WATER_MAP; - const size_t WATER_STORAGE_SIZE = WATER_SNOW_OFFSET + 2 * WATER_SNOW_SIZE * WATER_SLOTS; + // the snow of every glass laid together (water_snowlayer.comp): WATER_LAYER x WATER_LAYER texels of three uint each (the colour + // and the cover, the normal and the translucency, the bend and the haze, see water.glsl) + const size_t WATER_LAYER_OFFSET = WATER_SNOW_OFFSET + 2 * WATER_SNOW_SIZE * WATER_SLOTS; + const size_t WATER_LAYER_SIZE = 12 * static_cast(WATER_LAYER) * WATER_LAYER; + const size_t WATER_STORAGE_SIZE = WATER_LAYER_OFFSET + WATER_LAYER_SIZE * WATER_SLOTS; // the parts of a glass in the storage: its drops and what the passes keep of them, its map (the axes the second part), its - // cells and its paths, its header and its counts, its two maps of the snow, (offset, size) in bytes - inline std::array, 13> water_slot_parts(size_t const Slot) + // cells and its paths, its header and its counts, its two maps of the snow, its laid snow, (offset, size) in bytes + inline std::array, 14> water_slot_parts(size_t const Slot) { auto const drops{static_cast(WATER_DROPS)}; auto const texels{static_cast(WATER_MAP) * WATER_MAP}; @@ -793,7 +804,8 @@ namespace gl {WATER_HEADER_OFFSET + 16 * Slot, 16}, {WATER_COUNTS_OFFSET + 16 * Slot, 16}, {WATER_SNOW_OFFSET + WATER_SNOW_SIZE * Slot, WATER_SNOW_SIZE}, - {WATER_SNOW_OFFSET + WATER_SNOW_SIZE * (WATER_SLOTS + Slot), WATER_SNOW_SIZE}}}; + {WATER_SNOW_OFFSET + WATER_SNOW_SIZE * (WATER_SLOTS + Slot), WATER_SNOW_SIZE}, + {WATER_LAYER_OFFSET + WATER_LAYER_SIZE * Slot, WATER_LAYER_SIZE}}}; } // layout std140: the step of the simulation of the water on the windscreens (GLSL water_ubo), every vector in the space of the @@ -816,7 +828,8 @@ namespace gl // glass), y: 1 / the mean of the diameters above it, 1 / mm (they go as Marshall-Palmer), zw: unused glm::vec4 rain; // x: random seed of the step, y: the most landings tried on a glass in the step, z: the glass the passes for a single glass - // work on (the baking of the mask of the wipers) + // work on (the baking of the mask of the wipers, the laying of the snow), w: the step (the band of rows the laying of the + // snow lays anew) glm::uvec4 counts; // every glass: x the landings tried in the step, y 1 / the most metres squared of the glass a unit of its uv holds (the // landings tried at the densest place are all taken), z 1 when it's simulated, w the size of its drops (the param diff --git a/rendering/common/windscreenwater.cpp b/rendering/common/windscreenwater.cpp index 5a9dc9995..91a8ced0c 100644 --- a/rendering/common/windscreenwater.cpp +++ b/rendering/common/windscreenwater.cpp @@ -480,11 +480,53 @@ void windscreen_water::update(double const Seconds) gpu_step(block, most); if (anysnow) { + lay_snow(block); // the step wrote the other map of the snow m_snowmap = 1 - m_snowmap; } } +namespace +{ + +// a texture of the material by its name in the shader, none when the shader has no such texture +texture_handle material_texture(opengl_material const &Material, std::string const &Name) +{ + if ((Material.shader == nullptr) || (Material.shader->texture_conf.count(Name) == 0)) + { + return null_handle; + } + return Material.textures[Material.shader->texture_conf.at(Name).id]; +} + +} // namespace + +void windscreen_water::lay_snow(gl::water_ubs const &Block) +{ + for (std::size_t slot = 0; slot < m_glasscount; ++slot) + { + if (Block.snow_slots[static_cast(slot)] < 0.5f) + { + continue; + } + auto const *material{m_host.material(m_glasses[slot].material)}; + if (material == nullptr) + { + continue; + } + auto const atlas{material_texture(*material, "raindropsatlas")}; + auto const normal{material_texture(*material, "normalmap")}; + if ((atlas == null_handle) || (normal == null_handle)) + { + continue; + } + auto layer{Block}; + layer.counts.z = static_cast(slot); + layer.counts.w = m_step; + gpu_snow_layer(slot, atlas, normal, layer); + } +} + std::string windscreen_water::info() const { if ((m_state <= 0) || (m_glasscount == 0)) diff --git a/rendering/common/windscreenwater.h b/rendering/common/windscreenwater.h index 6a8ce7c17..53df232c0 100644 --- a/rendering/common/windscreenwater.h +++ b/rendering/common/windscreenwater.h @@ -80,6 +80,10 @@ class windscreen_water virtual bool gpu_bake(std::size_t Slot, texture_handle Mask, gl::water_ubs const &Block) = 0; // the step of the simulation of the glasses Block says are simulated; Tries: the most landings tried on a glass virtual void gpu_step(gl::water_ubs const &Block, std::uint32_t Tries) = 0; + // the snow of a glass of the snow laid together from the sprites of its atlas into its layer, after the step + // (water_snowlayer.comp; Block.counts: z the glass, w the step); Atlas, Normal: the atlas of the snow and its normal map (textures + // of the renderer); false when they aren't ready yet + virtual bool gpu_snow_layer(std::size_t Slot, texture_handle Atlas, texture_handle Normal, gl::water_ubs const &Block) = 0; private: struct glass @@ -99,6 +103,8 @@ class windscreen_water void rasterize(TSubModel *Submodel, material_handle Material, glm::vec3 const &Inside, std::vector &Axes) const; // the slots given to the materials of the glasses (every frame: a material made anew takes its default params) void assign(bool Assigned); + // the snow of the glasses of the snow Block says are simulated laid together, after the step + void lay_snow(gl::water_ubs const &Block); host m_host; int m_state{0}; // 0: not set up yet, 1: ready, -1: can't be used diff --git a/rendering/opengl46/opengl46water.cpp b/rendering/opengl46/opengl46water.cpp index d14fa0745..c0791d04d 100644 --- a/rendering/opengl46/opengl46water.cpp +++ b/rendering/opengl46/opengl46water.cpp @@ -58,7 +58,8 @@ bool opengl46_windscreen_water::gpu_init() try { std::array const names{"water_trail.comp", "water_spawn.comp", "water_move.comp", "water_clear.comp", "water_grid.comp", - "water_merge.comp", "water_gather.comp", "water_settle.comp", "water_bake.comp", "water_snow.comp"}; + "water_merge.comp", "water_gather.comp", "water_settle.comp", "water_bake.comp", "water_snow.comp", + "water_snowlayer.comp"}; for (std::size_t i = 0; i < names.size(); ++i) { if (m_programs[i]) @@ -155,6 +156,28 @@ bool opengl46_windscreen_water::gpu_bake(std::size_t const Slot, texture_handle return true; } +bool opengl46_windscreen_water::gpu_snow_layer(std::size_t const Slot, texture_handle const Atlas, texture_handle const Normal, gl::water_ubs const &Block) +{ + if ((!m_storage) || (Slot >= gl::WATER_SLOTS) || (Atlas == null_handle) || (Normal == null_handle)) + return false; + auto &atlas{GfxRenderer->Texture(Atlas)}; + auto &normal{GfxRenderer->Texture(Normal)}; + if ((false == atlas.create()) || (false == atlas.get_is_ready()) || (atlas.get_id() == 0) || (false == normal.create()) || (false == normal.get_is_ready()) || + (normal.get_id() == 0)) + return false; + m_storage->bind_base(); + m_block->update(Block); + m_block->bind_uniform(); + ::glBindTextureUnit(static_cast(gl::WATER_SNOW_ATLAS_TEX), static_cast(atlas.get_id())); + ::glBindTextureUnit(static_cast(gl::WATER_SNOW_NORMAL_TEX), static_cast(normal.get_id())); + m_programs[pass::snowlayer]->dispatch(groups(static_cast(gl::WATER_LAYER) * gl::WATER_LAYER)); + ::glBindTextureUnit(static_cast(gl::WATER_SNOW_ATLAS_TEX), 0); + ::glBindTextureUnit(static_cast(gl::WATER_SNOW_NORMAL_TEX), 0); + ::glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); + gl::program::unbind(); + return true; +} + void opengl46_windscreen_water::gpu_step(gl::water_ubs const &Block, std::uint32_t const Tries) { if (!m_storage) diff --git a/rendering/opengl46/opengl46water.h b/rendering/opengl46/opengl46water.h index ce3c92bae..d52737b9c 100644 --- a/rendering/opengl46/opengl46water.h +++ b/rendering/opengl46/opengl46water.h @@ -36,6 +36,7 @@ class opengl46_windscreen_water : public gfx::windscreen_water void gpu_setup(std::size_t Slot, std::vector const &Axes) override; bool gpu_bake(std::size_t Slot, texture_handle Mask, gl::water_ubs const &Block) override; void gpu_step(gl::water_ubs const &Block, std::uint32_t Tries) override; + bool gpu_snow_layer(std::size_t Slot, texture_handle Atlas, texture_handle Normal, gl::water_ubs const &Block) override; private: // the passes of the step, in their order @@ -51,6 +52,7 @@ class opengl46_windscreen_water : public gfx::windscreen_water settle, bake, snow, + snowlayer, count }; std::array, pass::count> m_programs; diff --git a/rendering/vulkan14/vulkan14shaders.cpp b/rendering/vulkan14/vulkan14shaders.cpp index 814ac29c3..e9d855667 100644 --- a/rendering/vulkan14/vulkan14shaders.cpp +++ b/rendering/vulkan14/vulkan14shaders.cpp @@ -971,6 +971,8 @@ std::string binding_preamble(bool const Raytracing) define("WATER_TRAIL", gl::WATER_TRAIL); define("WATER_MAP", gl::WATER_MAP); define("WATER_GROUP_SIZE", gl::WATER_GROUP_SIZE); + define("WATER_LAYER", gl::WATER_LAYER); + define("WATER_LAYER_BANDS", gl::WATER_LAYER_BANDS); define("CAB_PROBE_SH_SIZE", static_cast(gl::CAB_PROBE_SH_SIZE)); define("CAB_PROBE_SH_GROUP_SIZE", static_cast(gl::CAB_PROBE_SH_GROUP_SIZE)); return preamble; diff --git a/rendering/vulkan14/vulkan14water.cpp b/rendering/vulkan14/vulkan14water.cpp index 1ed3b45a2..ef37def6a 100644 --- a/rendering/vulkan14/vulkan14water.cpp +++ b/rendering/vulkan14/vulkan14water.cpp @@ -101,7 +101,8 @@ bool windscreen_water::gpu_init() try { std::array const names{"water_trail.comp", "water_spawn.comp", "water_move.comp", "water_clear.comp", "water_grid.comp", - "water_merge.comp", "water_gather.comp", "water_settle.comp", "water_bake.comp", "water_snow.comp"}; + "water_merge.comp", "water_gather.comp", "water_settle.comp", "water_bake.comp", "water_snow.comp", + "water_snowlayer.comp"}; for (std::size_t i = 0; i < names.size(); ++i) { if (false == m_kernels[i].create(m_device, *m_pipelines, m_shaders->get(names[i]), m_passlayout, {}, names[i])) @@ -261,6 +262,36 @@ bool windscreen_water::gpu_bake(std::size_t const Slot, texture_handle const Mas return true; } +bool windscreen_water::gpu_snow_layer(std::size_t const Slot, texture_handle const Atlas, texture_handle const Normal, gl::water_ubs const &Block) +{ + auto const commands{m_host.commands()}; + if ((commands == nullptr) || (false == m_full) || (Slot >= gl::WATER_SLOTS)) + { + return false; + } + VkImageView atlasview{VK_NULL_HANDLE}; + VkSampler atlassampler{VK_NULL_HANDLE}; + VkImageView normalview{VK_NULL_HANDLE}; + VkSampler normalsampler{VK_NULL_HANDLE}; + if ((false == m_host.texture(Atlas, atlasview, atlassampler)) || (atlasview == VK_NULL_HANDLE) || (false == m_host.texture(Normal, normalview, normalsampler)) || + (normalview == VK_NULL_HANDLE)) + { + return false; + } + auto const slice{block(Block)}; + if (false == bool(slice)) + { + return false; + } + begin(commands); + m_kernels[pass::snowlayer].run(commands, + {buffer_descriptor(m_storage->handle(), 0, VK_WHOLE_SIZE), buffer_descriptor(slice.buffer, slice.offset, sizeof(gl::water_ubs)), + image_descriptor(atlassampler, atlasview, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL), image_descriptor(normalsampler, normalview, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)}, + groups(static_cast(gl::WATER_LAYER) * gl::WATER_LAYER)); + compute_barrier(commands); + return true; +} + void windscreen_water::gpu_step(gl::water_ubs const &Block, std::uint32_t const Tries) { auto const commands{m_host.commands()}; diff --git a/rendering/vulkan14/vulkan14water.h b/rendering/vulkan14/vulkan14water.h index dd42cf72a..3c50ba915 100644 --- a/rendering/vulkan14/vulkan14water.h +++ b/rendering/vulkan14/vulkan14water.h @@ -64,6 +64,7 @@ class windscreen_water : public gfx::windscreen_water void gpu_setup(std::size_t Slot, std::vector const &Axes) override; bool gpu_bake(std::size_t Slot, texture_handle Mask, gl::water_ubs const &Block) override; void gpu_step(gl::water_ubs const &Block, std::uint32_t Tries) override; + bool gpu_snow_layer(std::size_t Slot, texture_handle Atlas, texture_handle Normal, gl::water_ubs const &Block) override; private: // the passes of the step, in their order @@ -79,6 +80,7 @@ class windscreen_water : public gfx::windscreen_water settle, bake, snow, + snowlayer, count }; // the block of the step in the ring of the frame; empty when the ring is full diff --git a/shaders/ogl46/common.glsl b/shaders/ogl46/common.glsl index f3ac47314..288c4b279 100644 --- a/shaders/ogl46/common.glsl +++ b/shaders/ogl46/common.glsl @@ -65,6 +65,10 @@ #define RAIN_CELLS_SSBO_BINDING 18 #define WATER_UBO_BINDING 6 #define WATER_MASK_TEX 25 +#define WATER_LAYER 1024 +#define WATER_LAYER_BANDS 8 +#define WATER_SNOW_ATLAS_TEX 32 +#define WATER_SNOW_NORMAL_TEX 33 #define INSTANCE_COUNTER_HEADER 8 #define INSTANCE_JOB_SLEEPERS 1U #define LIGHT_SSBO_BINDING 0 diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index c4ceca540..9776e309d 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -10,7 +10,8 @@ // the blades wipe it as they wipe the rain (a wet trace stays), it melts at the warm glass, slush slides down. The renderer gives // the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. // -// The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen: +// The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen, laid together into +// a layer of the glass by water_snowlayer.comp (snow_sprites.glsl) when the snow under them changes, so the glass only reads it: // - the lumps, in nine grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, // size, the snow it takes); it comes when the snow around reaches that and stays as it is until the snow goes. The grids come // one after the other as the snow piles up (all of them icy fleece, more and bigger; a lump of packed snow very rarely), each on the ones before, @@ -65,239 +66,7 @@ layout(binding = 1) uniform sampler2D raindropsatlas; layout(binding = 2) uniform sampler2D wipermask; layout(binding = 3) uniform sampler2D normalmap; -// --- tuning ------------------------------------------------------------------------------------------------------------------ -const float snow_flake_cell = 0.007; // a dot, a small puff or a drop at most every this many metres of the glass (its size) -const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff -const float snow_drops = 0.05; // share of the texels with the water of a melted flake showing a drop (more with more water) -const float snow_deep = 2.5; // mm of snow from which the cover is opaque (no picture behind it) -const float snow_cover = 0.25; // the lumps get opaque from three times this many mm of snow -const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) -const vec2 snow_lump_grow = vec2(0.75, 0.88); // a lump's size as it comes .. on thick snow, of its size (small gaps stay open) -const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) -const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) -const float snow_ice = 0.6; // opacity of a lump until the snow gets thick (icy: the picture shows through, bent) -const vec3 snow_ice_tint = vec3(0.93, 0.97, 1.0); // the colour of the icy snow -const float snow_thin = 0.45; // opacity of a single thin flake (ice crystals let most of the light through) -const float snow_bump = 1.0; // strength of the relief from the normal map, 0 = flat -const float snow_gloss = 0.8; // glints of the sun / headlights on the wet snow, 0 = matt -const float snow_ice_bend = 1.0; // how strongly the icy snow bends the picture behind it, of the bend of a drop -const float snow_translucency = 0.8; // glow of thin snow when you look towards the sun / a lamp, 0 = off -const float snow_haze = 1.0; // blur of the scene behind thin snow (frosted glass), 0 = off -const float snow_drop_bend = 1.0; // how strongly the drops bend the picture behind them -const float snow_wet_blur = 0.6; // blur of the scene behind a wet film -const vec2 snow_blur_mm = vec2(0.05, 0.6); // the scene behind the snow blurred from .. fully at this many mm of it (as the rain - // mists the glass up: the gaps between the lumps too, clear again behind a blade) - -const float WS_REFR_MAXPX = 96.0; // the largest picture shift the post-processing makes, screen pixels; as rain_windscreen_haze.glsl -const float WS_BEND_ENC = 60.0; // the bend request in the velocity target; as rain_windscreen_haze.glsl -const float WS_DROP_BIAS = 192.0; -const float WS_ENC = 64.0; // the haze request in the velocity target; as rain_windscreen_haze.glsl - -const float SNOW_FRESH = 0.1; // water in a mm of fresh snow, mm (as water_snow.comp) -const float SNOW_PACKED = 0.4; // and of packed snow - -// tiles of the atlas -const int TILE_DROP = 15; - -int snSlot = 0; -uint snMap = 0u; -bool snBig = true; // a 4 x 4 atlas (else the older 2 x 2) -float snHaze = 0.0; // the picture behind is blurred (thin snow, a wet film) -vec2 snBend = vec2(0.0); // the drops bend the picture behind (their normals, weighted) -float snBendA = 0.0; - -struct sprite_acc -{ - vec3 rgb; // premultiplied - float a; - vec3 n; // premultiplied, tangent space - float tr; // translucency, premultiplied -}; - -// the corner of a tile in the atlas; an older 2 x 2 atlas stands its four tiles in for the sixteen -// the rows of the tiles counted from the top of the picture of the atlas (as snieg_atlas_maszyna.py makes it), the v of the -// texture from its bottom: the first row is at the top of the texture (the tiles of the old 2 x 2 atlas the same way) -vec2 snTile(int tile) -{ - if (snBig) - return vec2(float(tile % 4), float(3 - tile / 4)) * 0.25; - int old = 0; // a fluffy flake - if ((tile == 6) || (tile == 7)) - old = 2; // crumbs - else if ((tile >= 8) && (tile != 10) && (tile != 11) && (tile != TILE_DROP)) - old = 1; // a wet lump - else if (tile == TILE_DROP) - old = 3; // a melted spot - return vec2(float(old % 2), float(1 - old / 2)) * 0.5; -} - -float snTileSize() -{ - return snBig ? 0.25 : 0.5; -} - -// a sprite over the accumulator: Local the place in it (0 .. 1), Rot its rotation (cos, sin), Tone its colour -void snSprite(vec2 local, int tile, float alpha, vec3 tone, vec2 rot, float flip, float lod, float bend, inout sprite_acc acc) -{ - vec2 uv = snTile(tile) + local * snTileSize(); - vec4 t = textureLod(raindropsatlas, uv, lod); - vec4 n = textureLod(normalmap, uv, lod); - float a = clamp(t.a * alpha, 0.0, 1.0); - if (a <= 0.002) - return; - vec2 nxy = (n.rg * 2.0 - 1.0) * snow_bump; - nxy.x *= flip; - vec2 nuv = vec2(rot.x * nxy.x - rot.y * nxy.y, rot.y * nxy.x + rot.x * nxy.y); - vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); - acc.rgb = t.rgb * tone * a + acc.rgb * (1.0 - a); - acc.n = nT * a + acc.n * (1.0 - a); - acc.tr = (1.0 - t.a * 0.55) * a + acc.tr * (1.0 - a); - acc.a = a + acc.a * (1.0 - a); - // all the snow bends the picture behind it (wet icy snow, slush, drops), as the drops of the rain; the drops and the slush - // the most - float bends = (((tile == TILE_DROP) || (tile == 8) || (tile == 9) || (tile == 14)) ? 1.0 : snow_ice_bend) * bend; - snBend = snBend * (1.0 - a) + nuv * bends * a; - snBendA = snBendA * (1.0 - a) + a; -} - -// where in a sprite the pixel is: P the pixel and C the centre of the sprite, in the units of its grid (the size of the sprite -// in them), Aspect the cells as they lie on the glass; false outside the sprite -bool snLocal(vec2 p, vec2 c, float size, vec2 aspect, vec2 rot, float flip, float aniso, out vec2 local) -{ - vec2 d = (p - c) * aspect; - vec2 r = vec2(rot.x * d.x + rot.y * d.y, -rot.y * d.x + rot.x * d.y); - r.x *= flip / aniso; - local = r / size + 0.5; - return all(greaterThanEqual(local, vec2(0.0))) && all(lessThanEqual(local, vec2(1.0))); -} - -float snLod(float pixelUV, float sizeUV) -{ - float tilePx = float(textureSize(raindropsatlas, 0).x) * snTileSize(); - return clamp(log2(max(pixelUV / sizeUV * tilePx, 1.0)), 0.0, 6.0); -} - -// how wet the snow of a state of the map is (0 dry .. 1 slush) -float snWetness(vec4 q) -{ - return q.y / (q.y + q.x * mix(SNOW_FRESH, SNOW_PACKED, q.z) + 1e-4); -} - -// the tone of the snow: grey and darker when wet (slush), a little grey when packed -vec3 snTone(vec4 q, float random) -{ - vec3 tone = vec3(mix(0.94, 1.04, random)) * snow_ice_tint; - tone *= mix(vec3(1.0), vec3(0.95, 0.96, 0.98), q.z); - return tone * mix(vec3(1.0), vec3(0.88, 0.91, 0.94), smoothstep(0.3, 0.8, snWetness(q))); -} - -// the dots and the drops, in cells of snow_flake_cell metres of the glass: in many of the cells holding a little dry snow a dot -// or a small puff sits between the lumps, in some of those holding only water a drop of a melted flake -void snFlakes(vec2 span, float pixelUV, inout sprite_acc acc) -{ - vec2 perUV = span / snow_flake_cell; // cells in a unit of the uv - vec2 p = f_coord * perUV; - ivec2 here = ivec2(floor(p)); - for (int oy = -1; oy <= 1; ++oy) - { - for (int ox = -1; ox <= 1; ++ox) - { - ivec2 cell = here + ivec2(ox, oy); - uint seed = Hash(uvec3(uvec2(cell + 8192), 17u + 7u * uint(snSlot))); - vec2 centre = vec2(cell) + 0.15 + 0.7 * vec2(RandF(seed), RandF(seed)); - vec4 q = water_snow_at(uint(snSlot), snMap, centre / perUV); - bool drop = (q.x < 0.05) && (q.y > 0.03); - bool crystal = (q.x >= 0.05); - if ((false == drop) && (false == crystal)) - continue; - if (RandF(seed) > (drop ? snow_drops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) - continue; - float ang = RandF(seed) * 6.2831853; - vec2 rot = vec2(cos(ang), sin(ang)); - float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; - float kind = RandF(seed); - float random = RandF(seed); - float size = mix(0.6, 1.0, RandF(seed)) * (drop ? mix(0.7, 1.4, smoothstep(0.03, 0.3, q.y)) : 1.0); - vec2 local; - if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, 1.0, local)) - continue; - int tile = TILE_DROP; - float alpha = smoothstep(0.03, 0.1, q.y); - if (crystal) - { - tile = 2 + min(int(kind * 2.0), 1); // small icy puffs - alpha = snow_thin; - } - snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0, acc); - } - } -} - -// how much a cell of the lumps lies in a heap: the snow landing side by side runs together, so the lumps come in heaps with -// barer glass between them; a random number for every few cells, blended between them (the same for every pixel of the cell) -float snHeap(ivec2 cell) -{ - vec2 c = (vec2(cell) + 0.5) / snow_heap_cells; - ivec2 i = ivec2(floor(c - 0.5)); - vec2 f = c - 0.5 - vec2(i); - f = f * f * (3.0 - 2.0 * f); - uint s00 = Hash(uvec3(uvec2(i + 8192), 53u)); - uint s10 = Hash(uvec3(uvec2(i + ivec2(1, 0) + 8192), 53u)); - uint s01 = Hash(uvec3(uvec2(i + ivec2(0, 1) + 8192), 53u)); - uint s11 = Hash(uvec3(uvec2(i + ivec2(1, 1) + 8192), 53u)); - return mix(mix(RandF(s00), RandF(s10), f.x), mix(RandF(s01), RandF(s11), f.x), f.y); -} - -// the lumps, in grids of cells of snow_lump_cell metres of the glass, shifted against each other. every cell of a grid has its -// lump fixed once (its tile, place, turn, size and the snow it takes to be there): the lump comes when the snow of the map around -// it reaches that, grows a little with more snow, and stays as it is until the snow goes (a blade, the melting); it never turns -// into another lump. the grids come one after the other as the snow piles up: dots and crumbs first, then puffs, clumps, and last -// the big lumps of packed snow which close the glass. in a heap (the snow landing side by side runs together) they come sooner -struct lump_grid -{ - vec2 shift; // the grid shifted, cells - uint salt; - vec2 snow; // the snow it takes for a lump of the grid to come, mm: from .. to (random per cell) - vec2 size; // the size of its lumps, cells: from .. to (random per cell) - int tiles; // its tiles: the first one and how many - int count; - float share; // the share of its cells having a lump at all (1: all of them) -}; - -void snLumps(vec2 span, float pixelUV, lump_grid grid, inout sprite_acc acc) -{ - vec2 perUV = span / snow_lump_cell; - vec2 p = f_coord * perUV + grid.shift; - ivec2 here = ivec2(floor(p)); - for (int oy = -1; oy <= 1; ++oy) - { - for (int ox = -1; ox <= 1; ++ox) - { - ivec2 cell = here + ivec2(ox, oy); - uint seed = Hash(uvec3(uvec2(cell + 4096), grid.salt + 7u * uint(snSlot))); - vec2 centre = vec2(cell) + 0.1 + 0.8 * vec2(RandF(seed), RandF(seed)); - // the snow it takes, sooner in a heap - float needs = mix(grid.snow.x, grid.snow.y, RandF(seed)) * mix(1.4, 0.6, snHeap(cell)); - vec4 q = water_snow_at(uint(snSlot), snMap, (centre - grid.shift) / perUV); - if ((q.x <= needs) || (RandF(seed) >= grid.share)) - continue; - float ang = RandF(seed) * 6.2831853; - vec2 rot = vec2(cos(ang), sin(ang)); - float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; - int tile = grid.tiles + min(int(RandF(seed) * float(grid.count)), grid.count - 1); - float random = RandF(seed); - float aniso = mix(0.8, 1.0, RandF(seed)); - float size = mix(grid.size.x, grid.size.y, RandF(seed)) * mix(snow_lump_grow.x, snow_lump_grow.y, smoothstep(needs, needs * 2.0 + 0.2, q.x)); - vec2 local; - if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, aniso, local)) - continue; - // fading in over the first snow (no flicker on the edge), opaque when thick; the thick snow bends nothing - float deep = smoothstep(snow_cover * 3.0, snow_deep, q.x); - float alpha = smoothstep(needs, needs + 0.04, q.x) * mix(snow_ice, 1.0, deep); - snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0 - deep, acc); - } - } -} +#include "snow_sprites.glsl" void main() { @@ -316,44 +85,31 @@ void main() Bgl *= invmax; vec4 tex_color = texture(diffuse, f_coord); // no discard: clean glass between faint dirt must still get snow and blur - float pixelUV = max(length(duv1), length(duv2)); - snBig = (textureSize(raindropsatlas, 0).x >= 2048); - - sprite_acc layer = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); - sprite_acc flakes = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + // the snow laid together from the sprites (water_snowlayer.comp, a band of its rows every step and wherever a blade goes) + vec3 snowRGB = vec3(0.0); + float snowA = 0.0; + vec3 snowN = vec3(0.0); + float snowTr = 0.0; float wet = 0.0; snSlot = int(param[2].z + 0.5) - 1; if ((snSlot >= 0) && (snSlot < WATER_SLOTS) && water_snow_map(uint(snSlot), snMap)) { - // the size of the glass, metres in a unit of its uv (the sizes of the snow are in metres: the glass may take a part of - // the uv only, or have it stretched) - ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); - uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; - vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); - // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: all of them icy - // fleece (small puffs and icy clumps, tiles 2-5), more and bigger, closing the glass by 2-3 mm - snLumps(span, pixelUV, lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(1.2, 2.0), 2, 4, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(1.4, 2.4), 2, 4, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.25), 97u, vec2(0.2, 0.9), vec2(1.4, 2.4), 2, 4, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.8, 2.8), 4, 2, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.75, 0.25), 151u, vec2(0.7, 1.6), vec2(1.8, 2.8), 4, 2, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.0), vec2(2.0, 3.0), 4, 2, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.0, 0.5), 233u, vec2(1.2, 2.4), vec2(2.0, 3.0), 4, 2, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.75), 251u, vec2(1.4, 2.8), vec2(2.0, 3.0), 4, 2, 1.0), layer); - // now and then a single lump of packed snow - snLumps(span, pixelUV, lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 12, 2, 0.03), layer); - snFlakes(span, pixelUV, flakes); + vec4 layerColour; + vec4 layerNormal; + vec4 layerBend; + water_layer_at(uint(snSlot), f_coord, layerColour, layerNormal, layerBend); + snowRGB = layerColour.rgb; + snowA = layerColour.a; + snowN = layerNormal.xyz; + snowTr = layerNormal.w; + snBend = layerBend.xy; + snBendA = layerBend.z; vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); // the picture behind thin flakes and a wet film is blurred - snHaze = max(smoothstep(0.0, 0.3, flakes.a + layer.a) * (1.0 - smoothstep(0.5, 0.9, layer.a)) * 0.6, wet * snow_wet_blur); + snHaze = max(layerBend.w, wet * snow_wet_blur); snHaze = max(snHaze, smoothstep(snow_blur_mm.x, snow_blur_mm.y, q.x)); } - // the flakes over the layer - vec3 snowRGB = flakes.rgb + layer.rgb * (1.0 - flakes.a); - float snowA = flakes.a + layer.a * (1.0 - flakes.a); - vec3 snowN = flakes.n + layer.n * (1.0 - flakes.a); - float snowTr = flakes.tr + layer.tr * (1.0 - flakes.a); float glassA = tex_color.a * alpha_mult; float finalA = snowA + glassA * (1.0 - snowA); diff --git a/shaders/ogl46/snow_sprites.glsl b/shaders/ogl46/snow_sprites.glsl new file mode 100644 index 000000000..a7291d671 --- /dev/null +++ b/shaders/ogl46/snow_sprites.glsl @@ -0,0 +1,315 @@ +// the snow on the windscreens laid together from the sprites of the atlas (mat_snow_windscreen.frag, water_snowlayer.comp): the +// tuning of the look of the snow and the laying of the lumps, the dots and the drops. the including file declares the samplers +// raindropsatlas and normalmap (the atlas of the snow and its normal map) and includes random.glsl and water.glsl before + +#ifndef SNOW_SPRITES_GLSL +#define SNOW_SPRITES_GLSL + +// --- tuning ------------------------------------------------------------------------------------------------------------------ +const float snow_flake_cell = 0.007; // a dot, a small puff or a drop at most every this many metres of the glass (its size) +const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff +const float snow_drops = 0.05; // share of the texels with the water of a melted flake showing a drop (more with more water) +const float snow_deep = 2.5; // mm of snow from which the cover is opaque (no picture behind it) +const float snow_cover = 0.25; // the lumps get opaque from three times this many mm of snow +const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) +const vec2 snow_lump_grow = vec2(0.75, 0.88); // a lump's size as it comes .. on thick snow, of its size (small gaps stay open) +const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) +const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) +const float snow_ice = 0.6; // opacity of a lump until the snow gets thick (icy: the picture shows through, bent) +const vec3 snow_ice_tint = vec3(0.93, 0.97, 1.0); // the colour of the icy snow +const float snow_thin = 0.45; // opacity of a single thin flake (ice crystals let most of the light through) +const float snow_bump = 1.0; // strength of the relief from the normal map, 0 = flat +const float snow_gloss = 0.8; // glints of the sun / headlights on the wet snow, 0 = matt +const float snow_ice_bend = 1.0; // how strongly the icy snow bends the picture behind it, of the bend of a drop +const float snow_translucency = 0.8; // glow of thin snow when you look towards the sun / a lamp, 0 = off +const float snow_haze = 1.0; // blur of the scene behind thin snow (frosted glass), 0 = off +const float snow_drop_bend = 1.0; // how strongly the drops bend the picture behind them +const float snow_wet_blur = 0.6; // blur of the scene behind a wet film +const vec2 snow_blur_mm = vec2(0.05, 0.6); // the scene behind the snow blurred from .. fully at this many mm of it (as the rain + // mists the glass up: the gaps between the lumps too, clear again behind a blade) + +const float WS_REFR_MAXPX = 96.0; // the largest picture shift the post-processing makes, screen pixels; as rain_windscreen_haze.glsl +const float WS_BEND_ENC = 60.0; // the bend request in the velocity target; as rain_windscreen_haze.glsl +const float WS_DROP_BIAS = 192.0; +const float WS_ENC = 64.0; // the haze request in the velocity target; as rain_windscreen_haze.glsl + +const float SNOW_FRESH = 0.1; // water in a mm of fresh snow, mm (as water_snow.comp) +const float SNOW_PACKED = 0.4; // and of packed snow + +// tiles of the atlas +const int TILE_DROP = 15; + +vec2 snUV = vec2(0.0); // the place on the glass laid, uv +int snSlot = 0; +uint snMap = 0u; +bool snBig = true; // a 4 x 4 atlas (else the older 2 x 2) +float snHaze = 0.0; // the picture behind is blurred (thin snow, a wet film) +vec2 snBend = vec2(0.0); // the drops bend the picture behind (their normals, weighted) +float snBendA = 0.0; + +struct sprite_acc +{ + vec3 rgb; // premultiplied + float a; + vec3 n; // premultiplied, tangent space + float tr; // translucency, premultiplied +}; + +// the corner of a tile in the atlas; an older 2 x 2 atlas stands its four tiles in for the sixteen +// the rows of the tiles counted from the top of the picture of the atlas (as snieg_atlas_maszyna.py makes it), the v of the +// texture from its bottom: the first row is at the top of the texture (the tiles of the old 2 x 2 atlas the same way) +vec2 snTile(int tile) +{ + if (snBig) + return vec2(float(tile % 4), float(3 - tile / 4)) * 0.25; + int old = 0; // a fluffy flake + if ((tile == 6) || (tile == 7)) + old = 2; // crumbs + else if ((tile >= 8) && (tile != 10) && (tile != 11) && (tile != TILE_DROP)) + old = 1; // a wet lump + else if (tile == TILE_DROP) + old = 3; // a melted spot + return vec2(float(old % 2), float(1 - old / 2)) * 0.5; +} + +float snTileSize() +{ + return snBig ? 0.25 : 0.5; +} + +// a sprite over the accumulator: Local the place in it (0 .. 1), Rot its rotation (cos, sin), Tone its colour +void snSprite(vec2 local, int tile, float alpha, vec3 tone, vec2 rot, float flip, float lod, float bend, inout sprite_acc acc) +{ + vec2 uv = snTile(tile) + local * snTileSize(); + vec4 t = textureLod(raindropsatlas, uv, lod); + vec4 n = textureLod(normalmap, uv, lod); + float a = clamp(t.a * alpha, 0.0, 1.0); + if (a <= 0.002) + return; + vec2 nxy = (n.rg * 2.0 - 1.0) * snow_bump; + nxy.x *= flip; + vec2 nuv = vec2(rot.x * nxy.x - rot.y * nxy.y, rot.y * nxy.x + rot.x * nxy.y); + vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); + // front to back: the sprites come from the top one down (the same picture as laying them back to front), so the pixel stops + // looking once the snow over it covers it + float w = a * (1.0 - acc.a); + acc.rgb += t.rgb * tone * w; + acc.n += nT * w; + acc.tr += (1.0 - t.a * 0.55) * w; + acc.a += w; + // all the snow bends the picture behind it (wet icy snow, slush, drops), as the drops of the rain; the drops and the slush + // the most + float bends = (((tile == TILE_DROP) || (tile == 8) || (tile == 9) || (tile == 14)) ? 1.0 : snow_ice_bend) * bend; + float wb = a * (1.0 - snBendA); + snBend += nuv * bends * wb; + snBendA += wb; +} + +// where in a sprite the pixel is: P the pixel and C the centre of the sprite, in the units of its grid (the size of the sprite +// in them), Aspect the cells as they lie on the glass; false outside the sprite +bool snLocal(vec2 p, vec2 c, float size, vec2 aspect, vec2 rot, float flip, float aniso, out vec2 local) +{ + vec2 d = (p - c) * aspect; + vec2 r = vec2(rot.x * d.x + rot.y * d.y, -rot.y * d.x + rot.x * d.y); + r.x *= flip / aniso; + local = r / size + 0.5; + return all(greaterThanEqual(local, vec2(0.0))) && all(lessThanEqual(local, vec2(1.0))); +} + +float snLod(float pixelUV, float sizeUV) +{ + float tilePx = float(textureSize(raindropsatlas, 0).x) * snTileSize(); + return clamp(log2(max(pixelUV / sizeUV * tilePx, 1.0)), 0.0, 6.0); +} + +// how wet the snow of a state of the map is (0 dry .. 1 slush) +float snWetness(vec4 q) +{ + return q.y / (q.y + q.x * mix(SNOW_FRESH, SNOW_PACKED, q.z) + 1e-4); +} + +// the tone of the snow: grey and darker when wet (slush), a little grey when packed +vec3 snTone(vec4 q, float random) +{ + vec3 tone = vec3(mix(0.94, 1.04, random)) * snow_ice_tint; + tone *= mix(vec3(1.0), vec3(0.95, 0.96, 0.98), q.z); + return tone * mix(vec3(1.0), vec3(0.88, 0.91, 0.94), smoothstep(0.3, 0.8, snWetness(q))); +} + +// the dots and the drops, in cells of snow_flake_cell metres of the glass: in many of the cells holding a little dry snow a dot +// or a small puff sits between the lumps, in some of those holding only water a drop of a melted flake +void snFlakes(vec2 span, float pixelUV, inout sprite_acc acc) +{ + vec2 perUV = span / snow_flake_cell; // cells in a unit of the uv + vec2 p = snUV * perUV; + ivec2 here = ivec2(floor(p)); + for (int oy = 1; oy >= -1; --oy) + { + for (int ox = 1; ox >= -1; --ox) + { + ivec2 cell = here + ivec2(ox, oy); + uint seed = Hash(uvec3(uvec2(cell + 8192), 17u + 7u * uint(snSlot))); + vec2 centre = vec2(cell) + 0.15 + 0.7 * vec2(RandF(seed), RandF(seed)); + // every draw of the cell first, in the order they always came, so the flake doesn't change: the map is the costly + // part, so it is read only for a flake which, as big as it gets, covers the pixel + float chance = RandF(seed); + float ang = RandF(seed) * 6.2831853; + vec2 rot = vec2(cos(ang), sin(ang)); + float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; + float kind = RandF(seed); + float random = RandF(seed); + float sizeDraw = mix(0.6, 1.0, RandF(seed)); + vec2 local; + if (false == snLocal(p, centre, sizeDraw * 1.4, vec2(1.0), rot, flip, 1.0, local)) + continue; + vec4 q = water_snow_at(uint(snSlot), snMap, centre / perUV); + bool drop = (q.x < 0.05) && (q.y > 0.03); + bool crystal = (q.x >= 0.05); + if ((false == drop) && (false == crystal)) + continue; + if (chance > (drop ? snow_drops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) + continue; + float size = sizeDraw * (drop ? mix(0.7, 1.4, smoothstep(0.03, 0.3, q.y)) : 1.0); + if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, 1.0, local)) + continue; + int tile = TILE_DROP; + float alpha = smoothstep(0.03, 0.1, q.y); + if (crystal) + { + tile = 2 + min(int(kind * 2.0), 1); // small icy puffs + alpha = snow_thin; + } + snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0, acc); + } + } +} + +// how much a cell of the lumps lies in a heap: the snow landing side by side runs together, so the lumps come in heaps with +// barer glass between them; a random number for every few cells, blended between them (the same for every pixel of the cell) +float snHeap(ivec2 cell) +{ + vec2 c = (vec2(cell) + 0.5) / snow_heap_cells; + ivec2 i = ivec2(floor(c - 0.5)); + vec2 f = c - 0.5 - vec2(i); + f = f * f * (3.0 - 2.0 * f); + uint s00 = Hash(uvec3(uvec2(i + 8192), 53u)); + uint s10 = Hash(uvec3(uvec2(i + ivec2(1, 0) + 8192), 53u)); + uint s01 = Hash(uvec3(uvec2(i + ivec2(0, 1) + 8192), 53u)); + uint s11 = Hash(uvec3(uvec2(i + ivec2(1, 1) + 8192), 53u)); + return mix(mix(RandF(s00), RandF(s10), f.x), mix(RandF(s01), RandF(s11), f.x), f.y); +} + +// the lumps, in grids of cells of snow_lump_cell metres of the glass, shifted against each other. every cell of a grid has its +// lump fixed once (its tile, place, turn, size and the snow it takes to be there): the lump comes when the snow of the map around +// it reaches that, grows a little with more snow, and stays as it is until the snow goes (a blade, the melting); it never turns +// into another lump. the grids come one after the other as the snow piles up: dots and crumbs first, then puffs, clumps, and last +// the big lumps of packed snow which close the glass. in a heap (the snow landing side by side runs together) they come sooner +struct lump_grid +{ + vec2 shift; // the grid shifted, cells + uint salt; + vec2 snow; // the snow it takes for a lump of the grid to come, mm: from .. to (random per cell) + vec2 size; // the size of its lumps, cells: from .. to (random per cell) + int tiles; // its tiles: the first one and how many + int count; + float share; // the share of its cells having a lump at all (1: all of them) +}; + +const float SN_COVERED = 0.998; // the snow over the pixel covering it: the sprites under it are not looked at + +void snLumps(vec2 span, float pixelUV, lump_grid grid, inout sprite_acc acc) +{ + if (acc.a >= SN_COVERED) + return; // the grids over this one cover the pixel + vec2 perUV = span / snow_lump_cell; + vec2 p = snUV * perUV + grid.shift; + ivec2 here = ivec2(floor(p)); + for (int oy = 1; oy >= -1; --oy) + { + for (int ox = 1; ox >= -1; --ox) + { + if (acc.a >= SN_COVERED) + return; + ivec2 cell = here + ivec2(ox, oy); + uint seed = Hash(uvec3(uvec2(cell + 4096), grid.salt + 7u * uint(snSlot))); + vec2 centre = vec2(cell) + 0.1 + 0.8 * vec2(RandF(seed), RandF(seed)); + // every draw of the cell first, in the order they always came, so the lump doesn't change: the map is the costly + // part, so it is read only for a lump which, as big as it grows, covers the pixel (most of the nine cells don't) + float needsDraw = RandF(seed); + if (RandF(seed) >= grid.share) + continue; + float ang = RandF(seed) * 6.2831853; + vec2 rot = vec2(cos(ang), sin(ang)); + float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; + int tile = grid.tiles + min(int(RandF(seed) * float(grid.count)), grid.count - 1); + float random = RandF(seed); + float aniso = mix(0.8, 1.0, RandF(seed)); + float sizeDraw = mix(grid.size.x, grid.size.y, RandF(seed)); + vec2 local; + if (false == snLocal(p, centre, sizeDraw * snow_lump_grow.y, vec2(1.0), rot, flip, aniso, local)) + continue; + // the snow it takes, sooner in a heap + float needs = mix(grid.snow.x, grid.snow.y, needsDraw) * mix(1.4, 0.6, snHeap(cell)); + vec4 q = water_snow_at(uint(snSlot), snMap, (centre - grid.shift) / perUV); + if (q.x <= needs) + continue; + float size = sizeDraw * mix(snow_lump_grow.x, snow_lump_grow.y, smoothstep(needs, needs * 2.0 + 0.2, q.x)); + if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, aniso, local)) + continue; + // fading in over the first snow (no flicker on the edge), opaque when thick; the thick snow bends nothing + float deep = smoothstep(snow_cover * 3.0, snow_deep, q.x); + float alpha = smoothstep(needs, needs + 0.04, q.x) * mix(snow_ice, 1.0, deep); + snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0 - deep, acc); + } + } +} + +// the snow of the glass laid together at UV: the flakes over the lumps (water_snowlayer.comp bakes it into the layer of the glass, +// mat_snow_windscreen.frag reads it). Span: metres of the glass in a unit of its uv; PixelUV: the uv a texel of the layer covers +// (the level of the atlas). snSlot, snMap and snBig set before +struct snow_layer_s +{ + vec3 rgb; // premultiplied + float a; + vec3 n; // premultiplied, tangent space + float tr; // translucency, premultiplied + vec2 bend; // the bend of the picture behind, weighted + float bendA; // its weight + float haze; // the blur of the picture behind the thin snow +}; + +snow_layer_s snCompose(vec2 uv, vec2 span, float pixelUV) +{ + snUV = uv; + snBend = vec2(0.0); + snBendA = 0.0; + sprite_acc layer = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + sprite_acc flakes = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: all of them icy + // fleece (small puffs and icy clumps, tiles 2-5), more and bigger, closing the glass by 2-3 mm; now and then a single + // lump of packed snow on top. laid front to back: the flakes, the single packed lumps, then the grids from the top one + // down, so a texel stops looking once the snow over it covers it + snFlakes(span, pixelUV, flakes); + snLumps(span, pixelUV, lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 12, 2, 0.03), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.75), 251u, vec2(1.4, 2.8), vec2(2.0, 3.0), 4, 2, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.0, 0.5), 233u, vec2(1.2, 2.4), vec2(2.0, 3.0), 4, 2, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.0), vec2(2.0, 3.0), 4, 2, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.75, 0.25), 151u, vec2(0.7, 1.6), vec2(1.8, 2.8), 4, 2, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.8, 2.8), 4, 2, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.25), 97u, vec2(0.2, 0.9), vec2(1.4, 2.4), 2, 4, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(1.4, 2.4), 2, 4, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(1.2, 2.0), 2, 4, 1.0), layer); + snow_layer_s s; + // the flakes over the layer + s.rgb = flakes.rgb + layer.rgb * (1.0 - flakes.a); + s.a = flakes.a + layer.a * (1.0 - flakes.a); + s.n = flakes.n + layer.n * (1.0 - flakes.a); + s.tr = flakes.tr + layer.tr * (1.0 - flakes.a); + s.bend = snBend; + s.bendA = snBendA; + // the picture behind thin flakes is blurred + s.haze = smoothstep(0.0, 0.3, flakes.a + layer.a) * (1.0 - smoothstep(0.5, 0.9, layer.a)) * 0.6; + return s; +} + +#endif diff --git a/shaders/ogl46/water.glsl b/shaders/ogl46/water.glsl index f35fbdf75..7bb7958f9 100644 --- a/shaders/ogl46/water.glsl +++ b/shaders/ogl46/water.glsl @@ -71,6 +71,40 @@ vec4 water_snow_texel(uint slot, uint map, ivec2 texel) return vec4(unpackHalf2x16(water_cells[index]), unpackHalf2x16(water_cells[index + 1u])); } +// the snow of a glass laid together (water_snowlayer.comp, read by mat_snow_windscreen.frag): WATER_LAYER x WATER_LAYER texels +// over its uv after the maps of the snow, three uint a texel: the colour (premultiplied, linear) and the cover; the normal of the +// sprites (tangent space, premultiplied) and their translucency; the bend of the picture behind (weighted), its weight, and the +// haze of the thin snow +uint water_layer_base(uint slot) +{ + return water_snow_base(0u, 2u) + slot * uint(WATER_LAYER * WATER_LAYER * 3); +} + +// the laid snow of a glass at UV, filtered between the texels: Colour (rgb, cover), Normal (xyz, translucency), Bend (xy, its +// weight, the haze) +void water_layer_at(uint slot, vec2 uv, out vec4 colour, out vec4 normal, out vec4 bend) +{ + vec2 p = uv * float(WATER_LAYER) - 0.5; + ivec2 i = ivec2(floor(p)); + vec2 f = p - vec2(i); + colour = vec4(0.0); + normal = vec4(0.0); + bend = vec4(0.0); + for (int k = 0; k < 4; ++k) + { + ivec2 t = i + ivec2(k & 1, k >> 1); + if (any(lessThan(t, ivec2(0))) || any(greaterThanEqual(t, ivec2(WATER_LAYER)))) + continue; + float w = ((k & 1) == 1 ? f.x : 1.0 - f.x) * ((k >> 1) == 1 ? f.y : 1.0 - f.y); + uint index = water_layer_base(slot) + 3u * uint(t.y * WATER_LAYER + t.x); + colour += unpackUnorm4x8(water_cells[index]) * w; + normal += unpackSnorm4x8(water_cells[index + 1u]) * w; + bend += unpackSnorm4x8(water_cells[index + 2u]) * w; + } + normal.w = normal.w * 0.5 + 0.5; + bend.zw = bend.zw * 0.5 + 0.5; +} + // the latest map of the snow of a glass; false when there's none yet bool water_snow_map(uint slot, out uint map) { diff --git a/shaders/ogl46/water_snowlayer.comp b/shaders/ogl46/water_snowlayer.comp new file mode 100644 index 000000000..6dbdd9dd2 --- /dev/null +++ b/shaders/ogl46/water_snowlayer.comp @@ -0,0 +1,71 @@ +#version 460 core +#define STAGE_COMPUTE 1 +// the snow on the windscreens (water_sim.glsl, water.glsl, snow_sprites.glsl): the snow of a glass of the snow laid together +// from the sprites of its atlas into its layer, which mat_snow_windscreen.frag reads (the glass only reads it: laying the nine +// grids of the lumps at every pixel of the glass in every frame cost as much as the rest of the frame). a thread per texel of +// the layer, the glass is water_counts.z. the snow under a lump changes slowly, so a band of every WATER_LAYER_BANDS-th row is +// laid anew in a step (water_counts.w the step), and at once wherever a blade went over the glass in the step + +#include "common.glsl" +#include "water_sim.glsl" +#include "random.glsl" + +// the atlas of the snow of the glass and its normal map (raindropsatlas, normalmap of its material) +layout(binding = WATER_SNOW_ATLAS_TEX) uniform sampler2D raindropsatlas; +layout(binding = WATER_SNOW_NORMAL_TEX) uniform sampler2D normalmap; + +#include "snow_sprites.glsl" + +layout(local_size_x = WATER_GROUP_SIZE) in; + +// the share of the sweep of a blade around where it went in the step whose snow is laid anew: a lump is laid by the snow at its +// middle, up to two of its cells (~3 cm) away from a texel it covers +const float SNOW_LAYER_BLADE_MARGIN = 0.06; + +// whether a blade went over the texel of the map, or near it, in the step +bool snow_layer_swept(uint mapTexel) +{ + vec4 place = water_blades[mapTexel]; + for (int blade = 0; blade < 4; ++blade) + { + float now = water_blades_now[blade]; + float before = water_blades_before[blade]; + if ((now < 0.0) || (now == before) || (place[blade] <= 0.001)) + continue; + if ((place[blade] >= min(now, before) - SNOW_LAYER_BLADE_MARGIN) && (place[blade] <= max(now, before) + SNOW_LAYER_BLADE_MARGIN)) + return true; + } + return false; +} + +void main() +{ + uint slot = water_counts.z; + uint texel = gl_GlobalInvocationID.x; + if ((slot >= uint(WATER_SLOTS)) || (texel >= uint(WATER_LAYER * WATER_LAYER)) || (water_snow_slots[slot] < 0.5)) + return; + uint map; + if (false == water_snow_map(slot, map)) + return; + ivec2 at = ivec2(int(texel % uint(WATER_LAYER)), int(texel / uint(WATER_LAYER))); + vec2 uv = (vec2(at) + 0.5) / float(WATER_LAYER); + ivec2 mapAt = clamp(ivec2(floor(uv * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); + uint mapTexel = slot * uint(WATER_MAP * WATER_MAP) + uint(mapAt.y * WATER_MAP + mapAt.x); + uint axis = mapTexel * 2u; + // nothing of the glass there (the glass reads its layer only where it is, filtered next to it) + if (water_axes[axis].w <= 0.0) + return; + // a band of the rows in a step (the snow builds up and melts slowly), and wherever a blade went + bool due = ((uint(at.y) % uint(WATER_LAYER_BANDS)) == (water_counts.w % uint(WATER_LAYER_BANDS))) || snow_layer_swept(mapTexel); + if (false == due) + return; + snSlot = int(slot); + snMap = map; + snBig = (textureSize(raindropsatlas, 0).x >= 2048); + vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); + snow_layer_s s = snCompose(uv, span, 1.0 / float(WATER_LAYER)); + uint index = water_layer_base(slot) + 3u * texel; + water_cells[index] = packUnorm4x8(vec4(s.rgb, s.a)); + water_cells[index + 1u] = packSnorm4x8(vec4(s.n, s.tr * 2.0 - 1.0)); + water_cells[index + 2u] = packSnorm4x8(vec4(s.bend, s.bendA * 2.0 - 1.0, s.haze * 2.0 - 1.0)); +} diff --git a/shaders/vk14/common.glsl b/shaders/vk14/common.glsl index dfc741624..f19df191f 100644 --- a/shaders/vk14/common.glsl +++ b/shaders/vk14/common.glsl @@ -138,6 +138,8 @@ #define WATER_TRAIL 1024 #define WATER_MAP 256 #define WATER_GROUP_SIZE 64 +#define WATER_LAYER 1024 +#define WATER_LAYER_BANDS 8 #define CAB_PROBE_SH_SIZE 16 #define CAB_PROBE_SH_GROUP_SIZE 64 #endif diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index 65688ab06..c3ae46e72 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -11,7 +11,8 @@ // the blades wipe it as they wipe the rain (a wet trace stays), it melts at the warm glass, slush slides down. The renderer gives // the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. // -// The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen: +// The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen, laid together into +// a layer of the glass by water_snowlayer.comp (snow_sprites.glsl) when the snow under them changes, so the glass only reads it: // - the lumps, in nine grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, // size, the snow it takes); it comes when the snow around reaches that and stays as it is until the snow goes. The grids come // one after the other as the snow piles up (all of them icy fleece, more and bigger; a lump of packed snow very rarely), each on the ones before, @@ -70,239 +71,7 @@ layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 1) uniform sampler layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 2) uniform sampler2D wipermask; layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 3) uniform sampler2D normalmap; -// --- tuning ------------------------------------------------------------------------------------------------------------------ -const float snow_flake_cell = 0.007; // a dot, a small puff or a drop at most every this many metres of the glass (its size) -const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff -const float snow_drops = 0.05; // share of the texels with the water of a melted flake showing a drop (more with more water) -const float snow_deep = 2.5; // mm of snow from which the cover is opaque (no picture behind it) -const float snow_cover = 0.25; // the lumps get opaque from three times this many mm of snow -const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) -const vec2 snow_lump_grow = vec2(0.75, 0.88); // a lump's size as it comes .. on thick snow, of its size (small gaps stay open) -const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) -const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) -const float snow_ice = 0.6; // opacity of a lump until the snow gets thick (icy: the picture shows through, bent) -const vec3 snow_ice_tint = vec3(0.93, 0.97, 1.0); // the colour of the icy snow -const float snow_thin = 0.45; // opacity of a single thin flake (ice crystals let most of the light through) -const float snow_bump = 1.0; // strength of the relief from the normal map, 0 = flat -const float snow_gloss = 0.8; // glints of the sun / headlights on the wet snow, 0 = matt -const float snow_ice_bend = 1.0; // how strongly the icy snow bends the picture behind it, of the bend of a drop -const float snow_translucency = 0.8; // glow of thin snow when you look towards the sun / a lamp, 0 = off -const float snow_haze = 1.0; // blur of the scene behind thin snow (frosted glass), 0 = off -const float snow_drop_bend = 1.0; // how strongly the drops bend the picture behind them -const float snow_wet_blur = 0.6; // blur of the scene behind a wet film -const vec2 snow_blur_mm = vec2(0.05, 0.6); // the scene behind the snow blurred from .. fully at this many mm of it (as the rain - // mists the glass up: the gaps between the lumps too, clear again behind a blade) - -const float WS_REFR_MAXPX = 96.0; // the largest picture shift the post-processing makes, screen pixels; as rain_windscreen_haze.glsl -const float WS_BEND_ENC = 60.0; // the bend request in the velocity target; as rain_windscreen_haze.glsl -const float WS_DROP_BIAS = 192.0; -const float WS_ENC = 64.0; // the haze request in the velocity target; as rain_windscreen_haze.glsl - -const float SNOW_FRESH = 0.1; // water in a mm of fresh snow, mm (as water_snow.comp) -const float SNOW_PACKED = 0.4; // and of packed snow - -// tiles of the atlas -const int TILE_DROP = 15; - -int snSlot = 0; -uint snMap = 0u; -bool snBig = true; // a 4 x 4 atlas (else the older 2 x 2) -float snHaze = 0.0; // the picture behind is blurred (thin snow, a wet film) -vec2 snBend = vec2(0.0); // the drops bend the picture behind (their normals, weighted) -float snBendA = 0.0; - -struct sprite_acc -{ - vec3 rgb; // premultiplied - float a; - vec3 n; // premultiplied, tangent space - float tr; // translucency, premultiplied -}; - -// the corner of a tile in the atlas; an older 2 x 2 atlas stands its four tiles in for the sixteen -// the rows of the tiles counted from the top of the picture of the atlas (as snieg_atlas_maszyna.py makes it), the v of the -// texture from its bottom: the first row is at the top of the texture (the tiles of the old 2 x 2 atlas the same way) -vec2 snTile(int tile) -{ - if (snBig) - return vec2(float(tile % 4), float(3 - tile / 4)) * 0.25; - int old = 0; // a fluffy flake - if ((tile == 6) || (tile == 7)) - old = 2; // crumbs - else if ((tile >= 8) && (tile != 10) && (tile != 11) && (tile != TILE_DROP)) - old = 1; // a wet lump - else if (tile == TILE_DROP) - old = 3; // a melted spot - return vec2(float(old % 2), float(1 - old / 2)) * 0.5; -} - -float snTileSize() -{ - return snBig ? 0.25 : 0.5; -} - -// a sprite over the accumulator: Local the place in it (0 .. 1), Rot its rotation (cos, sin), Tone its colour -void snSprite(vec2 local, int tile, float alpha, vec3 tone, vec2 rot, float flip, float lod, float bend, inout sprite_acc acc) -{ - vec2 uv = snTile(tile) + local * snTileSize(); - vec4 t = textureLod(raindropsatlas, uv, lod); - vec4 n = textureLod(normalmap, uv, lod); - float a = clamp(t.a * alpha, 0.0, 1.0); - if (a <= 0.002) - return; - vec2 nxy = (n.rg * 2.0 - 1.0) * snow_bump; - nxy.x *= flip; - vec2 nuv = vec2(rot.x * nxy.x - rot.y * nxy.y, rot.y * nxy.x + rot.x * nxy.y); - vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); - acc.rgb = t.rgb * tone * a + acc.rgb * (1.0 - a); - acc.n = nT * a + acc.n * (1.0 - a); - acc.tr = (1.0 - t.a * 0.55) * a + acc.tr * (1.0 - a); - acc.a = a + acc.a * (1.0 - a); - // all the snow bends the picture behind it (wet icy snow, slush, drops), as the drops of the rain; the drops and the slush - // the most - float bends = (((tile == TILE_DROP) || (tile == 8) || (tile == 9) || (tile == 14)) ? 1.0 : snow_ice_bend) * bend; - snBend = snBend * (1.0 - a) + nuv * bends * a; - snBendA = snBendA * (1.0 - a) + a; -} - -// where in a sprite the pixel is: P the pixel and C the centre of the sprite, in the units of its grid (the size of the sprite -// in them), Aspect the cells as they lie on the glass; false outside the sprite -bool snLocal(vec2 p, vec2 c, float size, vec2 aspect, vec2 rot, float flip, float aniso, out vec2 local) -{ - vec2 d = (p - c) * aspect; - vec2 r = vec2(rot.x * d.x + rot.y * d.y, -rot.y * d.x + rot.x * d.y); - r.x *= flip / aniso; - local = r / size + 0.5; - return all(greaterThanEqual(local, vec2(0.0))) && all(lessThanEqual(local, vec2(1.0))); -} - -float snLod(float pixelUV, float sizeUV) -{ - float tilePx = float(textureSize(raindropsatlas, 0).x) * snTileSize(); - return clamp(log2(max(pixelUV / sizeUV * tilePx, 1.0)), 0.0, 6.0); -} - -// how wet the snow of a state of the map is (0 dry .. 1 slush) -float snWetness(vec4 q) -{ - return q.y / (q.y + q.x * mix(SNOW_FRESH, SNOW_PACKED, q.z) + 1e-4); -} - -// the tone of the snow: grey and darker when wet (slush), a little grey when packed -vec3 snTone(vec4 q, float random) -{ - vec3 tone = vec3(mix(0.94, 1.04, random)) * snow_ice_tint; - tone *= mix(vec3(1.0), vec3(0.95, 0.96, 0.98), q.z); - return tone * mix(vec3(1.0), vec3(0.88, 0.91, 0.94), smoothstep(0.3, 0.8, snWetness(q))); -} - -// the dots and the drops, in cells of snow_flake_cell metres of the glass: in many of the cells holding a little dry snow a dot -// or a small puff sits between the lumps, in some of those holding only water a drop of a melted flake -void snFlakes(vec2 span, float pixelUV, inout sprite_acc acc) -{ - vec2 perUV = span / snow_flake_cell; // cells in a unit of the uv - vec2 p = f_coord * perUV; - ivec2 here = ivec2(floor(p)); - for (int oy = -1; oy <= 1; ++oy) - { - for (int ox = -1; ox <= 1; ++ox) - { - ivec2 cell = here + ivec2(ox, oy); - uint seed = Hash(uvec3(uvec2(cell + 8192), 17u + 7u * uint(snSlot))); - vec2 centre = vec2(cell) + 0.15 + 0.7 * vec2(RandF(seed), RandF(seed)); - vec4 q = water_snow_at(uint(snSlot), snMap, centre / perUV); - bool drop = (q.x < 0.05) && (q.y > 0.03); - bool crystal = (q.x >= 0.05); - if ((false == drop) && (false == crystal)) - continue; - if (RandF(seed) > (drop ? snow_drops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) - continue; - float ang = RandF(seed) * 6.2831853; - vec2 rot = vec2(cos(ang), sin(ang)); - float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; - float kind = RandF(seed); - float random = RandF(seed); - float size = mix(0.6, 1.0, RandF(seed)) * (drop ? mix(0.7, 1.4, smoothstep(0.03, 0.3, q.y)) : 1.0); - vec2 local; - if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, 1.0, local)) - continue; - int tile = TILE_DROP; - float alpha = smoothstep(0.03, 0.1, q.y); - if (crystal) - { - tile = 2 + min(int(kind * 2.0), 1); // small icy puffs - alpha = snow_thin; - } - snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0, acc); - } - } -} - -// how much a cell of the lumps lies in a heap: the snow landing side by side runs together, so the lumps come in heaps with -// barer glass between them; a random number for every few cells, blended between them (the same for every pixel of the cell) -float snHeap(ivec2 cell) -{ - vec2 c = (vec2(cell) + 0.5) / snow_heap_cells; - ivec2 i = ivec2(floor(c - 0.5)); - vec2 f = c - 0.5 - vec2(i); - f = f * f * (3.0 - 2.0 * f); - uint s00 = Hash(uvec3(uvec2(i + 8192), 53u)); - uint s10 = Hash(uvec3(uvec2(i + ivec2(1, 0) + 8192), 53u)); - uint s01 = Hash(uvec3(uvec2(i + ivec2(0, 1) + 8192), 53u)); - uint s11 = Hash(uvec3(uvec2(i + ivec2(1, 1) + 8192), 53u)); - return mix(mix(RandF(s00), RandF(s10), f.x), mix(RandF(s01), RandF(s11), f.x), f.y); -} - -// the lumps, in grids of cells of snow_lump_cell metres of the glass, shifted against each other. every cell of a grid has its -// lump fixed once (its tile, place, turn, size and the snow it takes to be there): the lump comes when the snow of the map around -// it reaches that, grows a little with more snow, and stays as it is until the snow goes (a blade, the melting); it never turns -// into another lump. the grids come one after the other as the snow piles up: dots and crumbs first, then puffs, clumps, and last -// the big lumps of packed snow which close the glass. in a heap (the snow landing side by side runs together) they come sooner -struct lump_grid -{ - vec2 shift; // the grid shifted, cells - uint salt; - vec2 snow; // the snow it takes for a lump of the grid to come, mm: from .. to (random per cell) - vec2 size; // the size of its lumps, cells: from .. to (random per cell) - int tiles; // its tiles: the first one and how many - int count; - float share; // the share of its cells having a lump at all (1: all of them) -}; - -void snLumps(vec2 span, float pixelUV, lump_grid grid, inout sprite_acc acc) -{ - vec2 perUV = span / snow_lump_cell; - vec2 p = f_coord * perUV + grid.shift; - ivec2 here = ivec2(floor(p)); - for (int oy = -1; oy <= 1; ++oy) - { - for (int ox = -1; ox <= 1; ++ox) - { - ivec2 cell = here + ivec2(ox, oy); - uint seed = Hash(uvec3(uvec2(cell + 4096), grid.salt + 7u * uint(snSlot))); - vec2 centre = vec2(cell) + 0.1 + 0.8 * vec2(RandF(seed), RandF(seed)); - // the snow it takes, sooner in a heap - float needs = mix(grid.snow.x, grid.snow.y, RandF(seed)) * mix(1.4, 0.6, snHeap(cell)); - vec4 q = water_snow_at(uint(snSlot), snMap, (centre - grid.shift) / perUV); - if ((q.x <= needs) || (RandF(seed) >= grid.share)) - continue; - float ang = RandF(seed) * 6.2831853; - vec2 rot = vec2(cos(ang), sin(ang)); - float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; - int tile = grid.tiles + min(int(RandF(seed) * float(grid.count)), grid.count - 1); - float random = RandF(seed); - float aniso = mix(0.8, 1.0, RandF(seed)); - float size = mix(grid.size.x, grid.size.y, RandF(seed)) * mix(snow_lump_grow.x, snow_lump_grow.y, smoothstep(needs, needs * 2.0 + 0.2, q.x)); - vec2 local; - if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, aniso, local)) - continue; - // fading in over the first snow (no flicker on the edge), opaque when thick; the thick snow bends nothing - float deep = smoothstep(snow_cover * 3.0, snow_deep, q.x); - float alpha = smoothstep(needs, needs + 0.04, q.x) * mix(snow_ice, 1.0, deep); - snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0 - deep, acc); - } - } -} +#include "snow_sprites.glsl" void main() { @@ -321,44 +90,31 @@ void main() Bgl *= invmax; vec4 tex_color = texture(diffuse, f_coord); // no discard: clean glass between faint dirt must still get snow and blur - float pixelUV = max(length(duv1), length(duv2)); - snBig = (textureSize(raindropsatlas, 0).x >= 2048); - - sprite_acc layer = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); - sprite_acc flakes = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + // the snow laid together from the sprites (water_snowlayer.comp, a band of its rows every step and wherever a blade goes) + vec3 snowRGB = vec3(0.0); + float snowA = 0.0; + vec3 snowN = vec3(0.0); + float snowTr = 0.0; float wet = 0.0; snSlot = int(param[2].z + 0.5) - 1; if ((snSlot >= 0) && (snSlot < WATER_SLOTS) && water_snow_map(uint(snSlot), snMap)) { - // the size of the glass, metres in a unit of its uv (the sizes of the snow are in metres: the glass may take a part of - // the uv only, or have it stretched) - ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); - uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; - vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); - // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: all of them icy - // fleece (small puffs and icy clumps, tiles 2-5), more and bigger, closing the glass by 2-3 mm - snLumps(span, pixelUV, lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(1.2, 2.0), 2, 4, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(1.4, 2.4), 2, 4, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.25), 97u, vec2(0.2, 0.9), vec2(1.4, 2.4), 2, 4, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.8, 2.8), 4, 2, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.75, 0.25), 151u, vec2(0.7, 1.6), vec2(1.8, 2.8), 4, 2, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.0), vec2(2.0, 3.0), 4, 2, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.0, 0.5), 233u, vec2(1.2, 2.4), vec2(2.0, 3.0), 4, 2, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.75), 251u, vec2(1.4, 2.8), vec2(2.0, 3.0), 4, 2, 1.0), layer); - // now and then a single lump of packed snow - snLumps(span, pixelUV, lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 12, 2, 0.03), layer); - snFlakes(span, pixelUV, flakes); + vec4 layerColour; + vec4 layerNormal; + vec4 layerBend; + water_layer_at(uint(snSlot), f_coord, layerColour, layerNormal, layerBend); + snowRGB = layerColour.rgb; + snowA = layerColour.a; + snowN = layerNormal.xyz; + snowTr = layerNormal.w; + snBend = layerBend.xy; + snBendA = layerBend.z; vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); // the picture behind thin flakes and a wet film is blurred - snHaze = max(smoothstep(0.0, 0.3, flakes.a + layer.a) * (1.0 - smoothstep(0.5, 0.9, layer.a)) * 0.6, wet * snow_wet_blur); + snHaze = max(layerBend.w, wet * snow_wet_blur); snHaze = max(snHaze, smoothstep(snow_blur_mm.x, snow_blur_mm.y, q.x)); } - // the flakes over the layer - vec3 snowRGB = flakes.rgb + layer.rgb * (1.0 - flakes.a); - float snowA = flakes.a + layer.a * (1.0 - flakes.a); - vec3 snowN = flakes.n + layer.n * (1.0 - flakes.a); - float snowTr = flakes.tr + layer.tr * (1.0 - flakes.a); float glassA = tex_color.a * alpha_mult; float finalA = snowA + glassA * (1.0 - snowA); diff --git a/shaders/vk14/snow_sprites.glsl b/shaders/vk14/snow_sprites.glsl new file mode 100644 index 000000000..a7291d671 --- /dev/null +++ b/shaders/vk14/snow_sprites.glsl @@ -0,0 +1,315 @@ +// the snow on the windscreens laid together from the sprites of the atlas (mat_snow_windscreen.frag, water_snowlayer.comp): the +// tuning of the look of the snow and the laying of the lumps, the dots and the drops. the including file declares the samplers +// raindropsatlas and normalmap (the atlas of the snow and its normal map) and includes random.glsl and water.glsl before + +#ifndef SNOW_SPRITES_GLSL +#define SNOW_SPRITES_GLSL + +// --- tuning ------------------------------------------------------------------------------------------------------------------ +const float snow_flake_cell = 0.007; // a dot, a small puff or a drop at most every this many metres of the glass (its size) +const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff +const float snow_drops = 0.05; // share of the texels with the water of a melted flake showing a drop (more with more water) +const float snow_deep = 2.5; // mm of snow from which the cover is opaque (no picture behind it) +const float snow_cover = 0.25; // the lumps get opaque from three times this many mm of snow +const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) +const vec2 snow_lump_grow = vec2(0.75, 0.88); // a lump's size as it comes .. on thick snow, of its size (small gaps stay open) +const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) +const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) +const float snow_ice = 0.6; // opacity of a lump until the snow gets thick (icy: the picture shows through, bent) +const vec3 snow_ice_tint = vec3(0.93, 0.97, 1.0); // the colour of the icy snow +const float snow_thin = 0.45; // opacity of a single thin flake (ice crystals let most of the light through) +const float snow_bump = 1.0; // strength of the relief from the normal map, 0 = flat +const float snow_gloss = 0.8; // glints of the sun / headlights on the wet snow, 0 = matt +const float snow_ice_bend = 1.0; // how strongly the icy snow bends the picture behind it, of the bend of a drop +const float snow_translucency = 0.8; // glow of thin snow when you look towards the sun / a lamp, 0 = off +const float snow_haze = 1.0; // blur of the scene behind thin snow (frosted glass), 0 = off +const float snow_drop_bend = 1.0; // how strongly the drops bend the picture behind them +const float snow_wet_blur = 0.6; // blur of the scene behind a wet film +const vec2 snow_blur_mm = vec2(0.05, 0.6); // the scene behind the snow blurred from .. fully at this many mm of it (as the rain + // mists the glass up: the gaps between the lumps too, clear again behind a blade) + +const float WS_REFR_MAXPX = 96.0; // the largest picture shift the post-processing makes, screen pixels; as rain_windscreen_haze.glsl +const float WS_BEND_ENC = 60.0; // the bend request in the velocity target; as rain_windscreen_haze.glsl +const float WS_DROP_BIAS = 192.0; +const float WS_ENC = 64.0; // the haze request in the velocity target; as rain_windscreen_haze.glsl + +const float SNOW_FRESH = 0.1; // water in a mm of fresh snow, mm (as water_snow.comp) +const float SNOW_PACKED = 0.4; // and of packed snow + +// tiles of the atlas +const int TILE_DROP = 15; + +vec2 snUV = vec2(0.0); // the place on the glass laid, uv +int snSlot = 0; +uint snMap = 0u; +bool snBig = true; // a 4 x 4 atlas (else the older 2 x 2) +float snHaze = 0.0; // the picture behind is blurred (thin snow, a wet film) +vec2 snBend = vec2(0.0); // the drops bend the picture behind (their normals, weighted) +float snBendA = 0.0; + +struct sprite_acc +{ + vec3 rgb; // premultiplied + float a; + vec3 n; // premultiplied, tangent space + float tr; // translucency, premultiplied +}; + +// the corner of a tile in the atlas; an older 2 x 2 atlas stands its four tiles in for the sixteen +// the rows of the tiles counted from the top of the picture of the atlas (as snieg_atlas_maszyna.py makes it), the v of the +// texture from its bottom: the first row is at the top of the texture (the tiles of the old 2 x 2 atlas the same way) +vec2 snTile(int tile) +{ + if (snBig) + return vec2(float(tile % 4), float(3 - tile / 4)) * 0.25; + int old = 0; // a fluffy flake + if ((tile == 6) || (tile == 7)) + old = 2; // crumbs + else if ((tile >= 8) && (tile != 10) && (tile != 11) && (tile != TILE_DROP)) + old = 1; // a wet lump + else if (tile == TILE_DROP) + old = 3; // a melted spot + return vec2(float(old % 2), float(1 - old / 2)) * 0.5; +} + +float snTileSize() +{ + return snBig ? 0.25 : 0.5; +} + +// a sprite over the accumulator: Local the place in it (0 .. 1), Rot its rotation (cos, sin), Tone its colour +void snSprite(vec2 local, int tile, float alpha, vec3 tone, vec2 rot, float flip, float lod, float bend, inout sprite_acc acc) +{ + vec2 uv = snTile(tile) + local * snTileSize(); + vec4 t = textureLod(raindropsatlas, uv, lod); + vec4 n = textureLod(normalmap, uv, lod); + float a = clamp(t.a * alpha, 0.0, 1.0); + if (a <= 0.002) + return; + vec2 nxy = (n.rg * 2.0 - 1.0) * snow_bump; + nxy.x *= flip; + vec2 nuv = vec2(rot.x * nxy.x - rot.y * nxy.y, rot.y * nxy.x + rot.x * nxy.y); + vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); + // front to back: the sprites come from the top one down (the same picture as laying them back to front), so the pixel stops + // looking once the snow over it covers it + float w = a * (1.0 - acc.a); + acc.rgb += t.rgb * tone * w; + acc.n += nT * w; + acc.tr += (1.0 - t.a * 0.55) * w; + acc.a += w; + // all the snow bends the picture behind it (wet icy snow, slush, drops), as the drops of the rain; the drops and the slush + // the most + float bends = (((tile == TILE_DROP) || (tile == 8) || (tile == 9) || (tile == 14)) ? 1.0 : snow_ice_bend) * bend; + float wb = a * (1.0 - snBendA); + snBend += nuv * bends * wb; + snBendA += wb; +} + +// where in a sprite the pixel is: P the pixel and C the centre of the sprite, in the units of its grid (the size of the sprite +// in them), Aspect the cells as they lie on the glass; false outside the sprite +bool snLocal(vec2 p, vec2 c, float size, vec2 aspect, vec2 rot, float flip, float aniso, out vec2 local) +{ + vec2 d = (p - c) * aspect; + vec2 r = vec2(rot.x * d.x + rot.y * d.y, -rot.y * d.x + rot.x * d.y); + r.x *= flip / aniso; + local = r / size + 0.5; + return all(greaterThanEqual(local, vec2(0.0))) && all(lessThanEqual(local, vec2(1.0))); +} + +float snLod(float pixelUV, float sizeUV) +{ + float tilePx = float(textureSize(raindropsatlas, 0).x) * snTileSize(); + return clamp(log2(max(pixelUV / sizeUV * tilePx, 1.0)), 0.0, 6.0); +} + +// how wet the snow of a state of the map is (0 dry .. 1 slush) +float snWetness(vec4 q) +{ + return q.y / (q.y + q.x * mix(SNOW_FRESH, SNOW_PACKED, q.z) + 1e-4); +} + +// the tone of the snow: grey and darker when wet (slush), a little grey when packed +vec3 snTone(vec4 q, float random) +{ + vec3 tone = vec3(mix(0.94, 1.04, random)) * snow_ice_tint; + tone *= mix(vec3(1.0), vec3(0.95, 0.96, 0.98), q.z); + return tone * mix(vec3(1.0), vec3(0.88, 0.91, 0.94), smoothstep(0.3, 0.8, snWetness(q))); +} + +// the dots and the drops, in cells of snow_flake_cell metres of the glass: in many of the cells holding a little dry snow a dot +// or a small puff sits between the lumps, in some of those holding only water a drop of a melted flake +void snFlakes(vec2 span, float pixelUV, inout sprite_acc acc) +{ + vec2 perUV = span / snow_flake_cell; // cells in a unit of the uv + vec2 p = snUV * perUV; + ivec2 here = ivec2(floor(p)); + for (int oy = 1; oy >= -1; --oy) + { + for (int ox = 1; ox >= -1; --ox) + { + ivec2 cell = here + ivec2(ox, oy); + uint seed = Hash(uvec3(uvec2(cell + 8192), 17u + 7u * uint(snSlot))); + vec2 centre = vec2(cell) + 0.15 + 0.7 * vec2(RandF(seed), RandF(seed)); + // every draw of the cell first, in the order they always came, so the flake doesn't change: the map is the costly + // part, so it is read only for a flake which, as big as it gets, covers the pixel + float chance = RandF(seed); + float ang = RandF(seed) * 6.2831853; + vec2 rot = vec2(cos(ang), sin(ang)); + float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; + float kind = RandF(seed); + float random = RandF(seed); + float sizeDraw = mix(0.6, 1.0, RandF(seed)); + vec2 local; + if (false == snLocal(p, centre, sizeDraw * 1.4, vec2(1.0), rot, flip, 1.0, local)) + continue; + vec4 q = water_snow_at(uint(snSlot), snMap, centre / perUV); + bool drop = (q.x < 0.05) && (q.y > 0.03); + bool crystal = (q.x >= 0.05); + if ((false == drop) && (false == crystal)) + continue; + if (chance > (drop ? snow_drops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) + continue; + float size = sizeDraw * (drop ? mix(0.7, 1.4, smoothstep(0.03, 0.3, q.y)) : 1.0); + if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, 1.0, local)) + continue; + int tile = TILE_DROP; + float alpha = smoothstep(0.03, 0.1, q.y); + if (crystal) + { + tile = 2 + min(int(kind * 2.0), 1); // small icy puffs + alpha = snow_thin; + } + snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0, acc); + } + } +} + +// how much a cell of the lumps lies in a heap: the snow landing side by side runs together, so the lumps come in heaps with +// barer glass between them; a random number for every few cells, blended between them (the same for every pixel of the cell) +float snHeap(ivec2 cell) +{ + vec2 c = (vec2(cell) + 0.5) / snow_heap_cells; + ivec2 i = ivec2(floor(c - 0.5)); + vec2 f = c - 0.5 - vec2(i); + f = f * f * (3.0 - 2.0 * f); + uint s00 = Hash(uvec3(uvec2(i + 8192), 53u)); + uint s10 = Hash(uvec3(uvec2(i + ivec2(1, 0) + 8192), 53u)); + uint s01 = Hash(uvec3(uvec2(i + ivec2(0, 1) + 8192), 53u)); + uint s11 = Hash(uvec3(uvec2(i + ivec2(1, 1) + 8192), 53u)); + return mix(mix(RandF(s00), RandF(s10), f.x), mix(RandF(s01), RandF(s11), f.x), f.y); +} + +// the lumps, in grids of cells of snow_lump_cell metres of the glass, shifted against each other. every cell of a grid has its +// lump fixed once (its tile, place, turn, size and the snow it takes to be there): the lump comes when the snow of the map around +// it reaches that, grows a little with more snow, and stays as it is until the snow goes (a blade, the melting); it never turns +// into another lump. the grids come one after the other as the snow piles up: dots and crumbs first, then puffs, clumps, and last +// the big lumps of packed snow which close the glass. in a heap (the snow landing side by side runs together) they come sooner +struct lump_grid +{ + vec2 shift; // the grid shifted, cells + uint salt; + vec2 snow; // the snow it takes for a lump of the grid to come, mm: from .. to (random per cell) + vec2 size; // the size of its lumps, cells: from .. to (random per cell) + int tiles; // its tiles: the first one and how many + int count; + float share; // the share of its cells having a lump at all (1: all of them) +}; + +const float SN_COVERED = 0.998; // the snow over the pixel covering it: the sprites under it are not looked at + +void snLumps(vec2 span, float pixelUV, lump_grid grid, inout sprite_acc acc) +{ + if (acc.a >= SN_COVERED) + return; // the grids over this one cover the pixel + vec2 perUV = span / snow_lump_cell; + vec2 p = snUV * perUV + grid.shift; + ivec2 here = ivec2(floor(p)); + for (int oy = 1; oy >= -1; --oy) + { + for (int ox = 1; ox >= -1; --ox) + { + if (acc.a >= SN_COVERED) + return; + ivec2 cell = here + ivec2(ox, oy); + uint seed = Hash(uvec3(uvec2(cell + 4096), grid.salt + 7u * uint(snSlot))); + vec2 centre = vec2(cell) + 0.1 + 0.8 * vec2(RandF(seed), RandF(seed)); + // every draw of the cell first, in the order they always came, so the lump doesn't change: the map is the costly + // part, so it is read only for a lump which, as big as it grows, covers the pixel (most of the nine cells don't) + float needsDraw = RandF(seed); + if (RandF(seed) >= grid.share) + continue; + float ang = RandF(seed) * 6.2831853; + vec2 rot = vec2(cos(ang), sin(ang)); + float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; + int tile = grid.tiles + min(int(RandF(seed) * float(grid.count)), grid.count - 1); + float random = RandF(seed); + float aniso = mix(0.8, 1.0, RandF(seed)); + float sizeDraw = mix(grid.size.x, grid.size.y, RandF(seed)); + vec2 local; + if (false == snLocal(p, centre, sizeDraw * snow_lump_grow.y, vec2(1.0), rot, flip, aniso, local)) + continue; + // the snow it takes, sooner in a heap + float needs = mix(grid.snow.x, grid.snow.y, needsDraw) * mix(1.4, 0.6, snHeap(cell)); + vec4 q = water_snow_at(uint(snSlot), snMap, (centre - grid.shift) / perUV); + if (q.x <= needs) + continue; + float size = sizeDraw * mix(snow_lump_grow.x, snow_lump_grow.y, smoothstep(needs, needs * 2.0 + 0.2, q.x)); + if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, aniso, local)) + continue; + // fading in over the first snow (no flicker on the edge), opaque when thick; the thick snow bends nothing + float deep = smoothstep(snow_cover * 3.0, snow_deep, q.x); + float alpha = smoothstep(needs, needs + 0.04, q.x) * mix(snow_ice, 1.0, deep); + snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0 - deep, acc); + } + } +} + +// the snow of the glass laid together at UV: the flakes over the lumps (water_snowlayer.comp bakes it into the layer of the glass, +// mat_snow_windscreen.frag reads it). Span: metres of the glass in a unit of its uv; PixelUV: the uv a texel of the layer covers +// (the level of the atlas). snSlot, snMap and snBig set before +struct snow_layer_s +{ + vec3 rgb; // premultiplied + float a; + vec3 n; // premultiplied, tangent space + float tr; // translucency, premultiplied + vec2 bend; // the bend of the picture behind, weighted + float bendA; // its weight + float haze; // the blur of the picture behind the thin snow +}; + +snow_layer_s snCompose(vec2 uv, vec2 span, float pixelUV) +{ + snUV = uv; + snBend = vec2(0.0); + snBendA = 0.0; + sprite_acc layer = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + sprite_acc flakes = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: all of them icy + // fleece (small puffs and icy clumps, tiles 2-5), more and bigger, closing the glass by 2-3 mm; now and then a single + // lump of packed snow on top. laid front to back: the flakes, the single packed lumps, then the grids from the top one + // down, so a texel stops looking once the snow over it covers it + snFlakes(span, pixelUV, flakes); + snLumps(span, pixelUV, lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 12, 2, 0.03), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.75), 251u, vec2(1.4, 2.8), vec2(2.0, 3.0), 4, 2, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.0, 0.5), 233u, vec2(1.2, 2.4), vec2(2.0, 3.0), 4, 2, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.0), vec2(2.0, 3.0), 4, 2, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.75, 0.25), 151u, vec2(0.7, 1.6), vec2(1.8, 2.8), 4, 2, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.8, 2.8), 4, 2, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.25), 97u, vec2(0.2, 0.9), vec2(1.4, 2.4), 2, 4, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(1.4, 2.4), 2, 4, 1.0), layer); + snLumps(span, pixelUV, lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(1.2, 2.0), 2, 4, 1.0), layer); + snow_layer_s s; + // the flakes over the layer + s.rgb = flakes.rgb + layer.rgb * (1.0 - flakes.a); + s.a = flakes.a + layer.a * (1.0 - flakes.a); + s.n = flakes.n + layer.n * (1.0 - flakes.a); + s.tr = flakes.tr + layer.tr * (1.0 - flakes.a); + s.bend = snBend; + s.bendA = snBendA; + // the picture behind thin flakes is blurred + s.haze = smoothstep(0.0, 0.3, flakes.a + layer.a) * (1.0 - smoothstep(0.5, 0.9, layer.a)) * 0.6; + return s; +} + +#endif diff --git a/shaders/vk14/water.glsl b/shaders/vk14/water.glsl index ed2b1094d..8befd9fcc 100644 --- a/shaders/vk14/water.glsl +++ b/shaders/vk14/water.glsl @@ -72,6 +72,40 @@ vec4 water_snow_texel(uint slot, uint map, ivec2 texel) return vec4(unpackHalf2x16(water_cells[index]), unpackHalf2x16(water_cells[index + 1u])); } +// the snow of a glass laid together (water_snowlayer.comp, read by mat_snow_windscreen.frag): WATER_LAYER x WATER_LAYER texels +// over its uv after the maps of the snow, three uint a texel: the colour (premultiplied, linear) and the cover; the normal of the +// sprites (tangent space, premultiplied) and their translucency; the bend of the picture behind (weighted), its weight, and the +// haze of the thin snow +uint water_layer_base(uint slot) +{ + return water_snow_base(0u, 2u) + slot * uint(WATER_LAYER * WATER_LAYER * 3); +} + +// the laid snow of a glass at UV, filtered between the texels: Colour (rgb, cover), Normal (xyz, translucency), Bend (xy, its +// weight, the haze) +void water_layer_at(uint slot, vec2 uv, out vec4 colour, out vec4 normal, out vec4 bend) +{ + vec2 p = uv * float(WATER_LAYER) - 0.5; + ivec2 i = ivec2(floor(p)); + vec2 f = p - vec2(i); + colour = vec4(0.0); + normal = vec4(0.0); + bend = vec4(0.0); + for (int k = 0; k < 4; ++k) + { + ivec2 t = i + ivec2(k & 1, k >> 1); + if (any(lessThan(t, ivec2(0))) || any(greaterThanEqual(t, ivec2(WATER_LAYER)))) + continue; + float w = ((k & 1) == 1 ? f.x : 1.0 - f.x) * ((k >> 1) == 1 ? f.y : 1.0 - f.y); + uint index = water_layer_base(slot) + 3u * uint(t.y * WATER_LAYER + t.x); + colour += unpackUnorm4x8(water_cells[index]) * w; + normal += unpackSnorm4x8(water_cells[index + 1u]) * w; + bend += unpackSnorm4x8(water_cells[index + 2u]) * w; + } + normal.w = normal.w * 0.5 + 0.5; + bend.zw = bend.zw * 0.5 + 0.5; +} + // the latest map of the snow of a glass; false when there's none yet bool water_snow_map(uint slot, out uint map) { diff --git a/shaders/vk14/water_snowlayer.comp b/shaders/vk14/water_snowlayer.comp new file mode 100644 index 000000000..1ec8a882a --- /dev/null +++ b/shaders/vk14/water_snowlayer.comp @@ -0,0 +1,73 @@ +#version 460 core +#define STAGE_COMPUTE 1 +// the snow on the windscreens (water_sim.glsl, water.glsl, snow_sprites.glsl): the snow of a glass of the snow laid together +// from the sprites of its atlas into its layer, which mat_snow_windscreen.frag reads (the glass only reads it: laying the nine +// grids of the lumps at every pixel of the glass in every frame cost as much as the rest of the frame). a thread per texel of +// the layer, the glass is water_counts.z. the snow under a lump changes slowly, so a band of every WATER_LAYER_BANDS-th row is +// laid anew in a step (water_counts.w the step), and at once wherever a blade went over the glass in the step + +// none of the pass set: everything the kernel reads is pushed with its dispatch (set COMPUTE_SET, water_sim.glsl) +#define LAYOUT_UI 1 +#include "common.glsl" +#include "water_sim.glsl" +#include "random.glsl" + +// the atlas of the snow of the glass and its normal map (raindropsatlas, normalmap of its material) +layout(set = COMPUTE_SET, binding = 2) uniform sampler2D raindropsatlas; +layout(set = COMPUTE_SET, binding = 3) uniform sampler2D normalmap; + +#include "snow_sprites.glsl" + +layout(local_size_x = WATER_GROUP_SIZE) in; + +// the share of the sweep of a blade around where it went in the step whose snow is laid anew: a lump is laid by the snow at its +// middle, up to two of its cells (~3 cm) away from a texel it covers +const float SNOW_LAYER_BLADE_MARGIN = 0.06; + +// whether a blade went over the texel of the map, or near it, in the step +bool snow_layer_swept(uint mapTexel) +{ + vec4 place = water_blades[mapTexel]; + for (int blade = 0; blade < 4; ++blade) + { + float now = water_blades_now[blade]; + float before = water_blades_before[blade]; + if ((now < 0.0) || (now == before) || (place[blade] <= 0.001)) + continue; + if ((place[blade] >= min(now, before) - SNOW_LAYER_BLADE_MARGIN) && (place[blade] <= max(now, before) + SNOW_LAYER_BLADE_MARGIN)) + return true; + } + return false; +} + +void main() +{ + uint slot = water_counts.z; + uint texel = gl_GlobalInvocationID.x; + if ((slot >= uint(WATER_SLOTS)) || (texel >= uint(WATER_LAYER * WATER_LAYER)) || (water_snow_slots[slot] < 0.5)) + return; + uint map; + if (false == water_snow_map(slot, map)) + return; + ivec2 at = ivec2(int(texel % uint(WATER_LAYER)), int(texel / uint(WATER_LAYER))); + vec2 uv = (vec2(at) + 0.5) / float(WATER_LAYER); + ivec2 mapAt = clamp(ivec2(floor(uv * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); + uint mapTexel = slot * uint(WATER_MAP * WATER_MAP) + uint(mapAt.y * WATER_MAP + mapAt.x); + uint axis = mapTexel * 2u; + // nothing of the glass there (the glass reads its layer only where it is, filtered next to it) + if (water_axes[axis].w <= 0.0) + return; + // a band of the rows in a step (the snow builds up and melts slowly), and wherever a blade went + bool due = ((uint(at.y) % uint(WATER_LAYER_BANDS)) == (water_counts.w % uint(WATER_LAYER_BANDS))) || snow_layer_swept(mapTexel); + if (false == due) + return; + snSlot = int(slot); + snMap = map; + snBig = (textureSize(raindropsatlas, 0).x >= 2048); + vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); + snow_layer_s s = snCompose(uv, span, 1.0 / float(WATER_LAYER)); + uint index = water_layer_base(slot) + 3u * texel; + water_cells[index] = packUnorm4x8(vec4(s.rgb, s.a)); + water_cells[index + 1u] = packSnorm4x8(vec4(s.n, s.tr * 2.0 - 1.0)); + water_cells[index + 2u] = packSnorm4x8(vec4(s.bend, s.bendA * 2.0 - 1.0, s.haze * 2.0 - 1.0)); +} From 3de73b0e850f2117e2da3681dbefd203325d0062 Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Sat, 14 Nov 2026 22:14:18 +0100 Subject: [PATCH 098/123] Windscreen snow: the layer over the rectangle of the glass, one for the cab The layer of 1024 x 1024 texels over the whole uv gave a glass taking a part of its texture too few of them (the EP09 104ec: ~470 across the glass, 1.8 pixels of the screen a texel at 1080p), so the lumps came out soft. Now the layer lies over the rectangle of the uv the glass takes, its 2M texels across and down as the glass is wide and high (~1 mm a texel); the renderer works it out from the map of the glass when it sets the glass up and puts it in the storage (water.glsl, water_layer_rect). One layer, for the first glass of the snow of the cab (a cab has one as a rule); a second one lays its snow at every pixel as before the layer, the same look, slower. The storage of the water: 58 MiB before the layers, 82 MiB now (106 MiB with the four layers of 1024 x 1024). No assets change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- gl/glsl_common.cpp | 2 +- gl/ubo.h | 27 +++++--- rendering/common/windscreenwater.cpp | 85 ++++++++++++++++++++------ rendering/common/windscreenwater.h | 11 ++++ rendering/opengl46/opengl46water.cpp | 5 +- rendering/vulkan14/vulkan14shaders.cpp | 2 +- rendering/vulkan14/vulkan14water.cpp | 8 ++- shaders/ogl46/common.glsl | 2 +- shaders/ogl46/mat_snow_windscreen.frag | 18 +++++- shaders/ogl46/water.glsl | 48 +++++++++++---- shaders/ogl46/water_snowlayer.comp | 19 ++++-- shaders/vk14/common.glsl | 2 +- shaders/vk14/mat_snow_windscreen.frag | 18 +++++- shaders/vk14/water.glsl | 48 +++++++++++---- shaders/vk14/water_snowlayer.comp | 19 ++++-- 15 files changed, 243 insertions(+), 71 deletions(-) diff --git a/gl/glsl_common.cpp b/gl/glsl_common.cpp index 7c18fb9b8..bfe1a4716 100644 --- a/gl/glsl_common.cpp +++ b/gl/glsl_common.cpp @@ -56,7 +56,7 @@ void gl::glsl_common_setup() "#define RAIN_CELLS_SSBO_BINDING " + std::to_string(RAIN_CELLS_SSBO_BINDING) + "\n" + "#define WATER_UBO_BINDING " + std::to_string(WATER_UBO_BINDING) + "\n" + "#define WATER_MASK_TEX " + std::to_string(WATER_MASK_TEX) + "\n" + - "#define WATER_LAYER " + std::to_string(WATER_LAYER) + "\n" + + "#define WATER_LAYER_TEXELS " + std::to_string(WATER_LAYER_TEXELS) + "\n" + "#define WATER_LAYER_BANDS " + std::to_string(WATER_LAYER_BANDS) + "\n" + "#define WATER_SNOW_ATLAS_TEX " + std::to_string(WATER_SNOW_ATLAS_TEX) + "\n" + "#define WATER_SNOW_NORMAL_TEX " + std::to_string(WATER_SNOW_NORMAL_TEX) + "\n" + diff --git a/gl/ubo.h b/gl/ubo.h index 053fd2468..fc33d9018 100644 --- a/gl/ubo.h +++ b/gl/ubo.h @@ -732,9 +732,11 @@ namespace gl const GLuint WATER_CELL_DROPS = 32; const GLuint WATER_TRAIL = 1024; const GLuint WATER_MAP = 256; - // the snow of a glass laid together (water_snowlayer.comp): WATER_LAYER x WATER_LAYER texels over its uv, a band of every - // WATER_LAYER_BANDS-th row laid anew in a step (and wherever a blade goes over it), read by mat_snow_windscreen.frag - const GLuint WATER_LAYER = 1024; + // the snow of a glass laid together (water_snowlayer.comp): WATER_LAYER_TEXELS texels over the rectangle of its uv the glass + // takes (across and down as the glass is wide and high, ~1 mm a texel), a band of every WATER_LAYER_BANDS-th row laid anew in + // a step (and wherever a blade goes over it), read by mat_snow_windscreen.frag. one layer: the first glass of the snow of the + // cab has it (a cab has one glass of the snow as a rule), the others lay their snow at every pixel as they're drawn + const GLuint WATER_LAYER_TEXELS = 2 * 1024 * 1024; const GLuint WATER_LAYER_BANDS = 8; const GLuint WATER_GROUP_SIZE = 64; // the binding points of the opengl renderer: the storage of the water (read by the glasses, written by the passes), the block @@ -779,13 +781,18 @@ namespace gl // flakes), a step reads one and writes the other (the header of the glass says which one is the latest) const size_t WATER_SNOW_OFFSET = WATER_TRAIL_OFFSET + 4 * static_cast(WATER_SLOTS) * WATER_TRAIL * WATER_TRAIL; const size_t WATER_SNOW_SIZE = 8 * static_cast(WATER_MAP) * WATER_MAP; - // the snow of every glass laid together (water_snowlayer.comp): WATER_LAYER x WATER_LAYER texels of three uint each (the colour - // and the cover, the normal and the translucency, the bend and the haze, see water.glsl) - const size_t WATER_LAYER_OFFSET = WATER_SNOW_OFFSET + 2 * WATER_SNOW_SIZE * WATER_SLOTS; - const size_t WATER_LAYER_SIZE = 12 * static_cast(WATER_LAYER) * WATER_LAYER; - const size_t WATER_STORAGE_SIZE = WATER_LAYER_OFFSET + WATER_LAYER_SIZE * WATER_SLOTS; + // the snow of the glass of the snow laid together (water_snowlayer.comp): first eight uint of every glass (the rectangle of its + // uv the layer takes, four floats; the texels of the layer across and down, 0 when the glass has no layer), then the layer, + // WATER_LAYER_TEXELS texels of three uint each (the colour and the cover, the normal and the translucency, the bend and the + // haze, see water.glsl) + const size_t WATER_LAYER_INFO_OFFSET = WATER_SNOW_OFFSET + 2 * WATER_SNOW_SIZE * WATER_SLOTS; + const size_t WATER_LAYER_INFO_SIZE = 32; + const size_t WATER_LAYER_OFFSET = WATER_LAYER_INFO_OFFSET + WATER_LAYER_INFO_SIZE * WATER_SLOTS; + const size_t WATER_LAYER_SIZE = 12 * static_cast(WATER_LAYER_TEXELS); + const size_t WATER_STORAGE_SIZE = WATER_LAYER_OFFSET + WATER_LAYER_SIZE; // the parts of a glass in the storage: its drops and what the passes keep of them, its map (the axes the second part), its - // cells and its paths, its header and its counts, its two maps of the snow, its laid snow, (offset, size) in bytes + // cells and its paths, its header and its counts, its two maps of the snow, the layer of the snow (the one of the cab, laid + // anew whichever glass it goes to), (offset, size) in bytes inline std::array, 14> water_slot_parts(size_t const Slot) { auto const drops{static_cast(WATER_DROPS)}; @@ -805,7 +812,7 @@ namespace gl {WATER_COUNTS_OFFSET + 16 * Slot, 16}, {WATER_SNOW_OFFSET + WATER_SNOW_SIZE * Slot, WATER_SNOW_SIZE}, {WATER_SNOW_OFFSET + WATER_SNOW_SIZE * (WATER_SLOTS + Slot), WATER_SNOW_SIZE}, - {WATER_LAYER_OFFSET + WATER_LAYER_SIZE * Slot, WATER_LAYER_SIZE}}}; + {WATER_LAYER_OFFSET, WATER_LAYER_SIZE}}}; } // layout std140: the step of the simulation of the water on the windscreens (GLSL water_ubo), every vector in the space of the diff --git a/rendering/common/windscreenwater.cpp b/rendering/common/windscreenwater.cpp index 91a8ced0c..f5d6e1e48 100644 --- a/rendering/common/windscreenwater.cpp +++ b/rendering/common/windscreenwater.cpp @@ -10,6 +10,10 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "rendering/common/windscreenwater.h" +#include +#include +#include + #include "model/Model3d.h" #include "model/material.h" #include "rendering/renderer.h" @@ -122,6 +126,7 @@ void windscreen_water::release() assign(false); m_glasses = {}; m_glasscount = 0; + m_layerslot = -1; m_kinds.clear(); m_vehicle = nullptr; m_cab = nullptr; @@ -501,29 +506,75 @@ texture_handle material_texture(opengl_material const &Material, std::string con } // namespace +std::array windscreen_water::layer_info(std::size_t const Slot, std::vector const &Axes) +{ + std::array info{}; + if ((Slot >= m_glasses.size()) || (false == m_glasses[Slot].snow) || ((m_layerslot >= 0) && (m_layerslot != static_cast(Slot)))) + { + return info; + } + auto const size{static_cast(gl::WATER_MAP)}; + glm::ivec2 least{size}; + glm::ivec2 most{-1}; + glm::dvec2 span{0.0}; + auto on{0}; + for (int y = 0; y < size; ++y) + { + for (int x = 0; x < size; ++x) + { + auto const texel{static_cast(y * size + x)}; + if ((texel * 2 + 1 >= Axes.size()) || (Axes[texel * 2].w <= 0.f)) + { + continue; + } + least = glm::min(least, glm::ivec2{x, y}); + most = glm::max(most, glm::ivec2{x, y}); + if (Axes[texel * 2].w >= 1.f) + { + // metres of the glass in a unit of its uv, across and down + span += glm::dvec2{glm::length(glm::vec3{Axes[texel * 2]}), glm::length(glm::vec3{Axes[texel * 2 + 1]})}; + ++on; + } + } + } + if ((on == 0) || (most.x < least.x) || (most.y < least.y)) + { + return info; + } + m_layerslot = static_cast(Slot); + span /= static_cast(on); + auto const corner{glm::vec2{least} / static_cast(size)}; + auto const extent{glm::vec2{most - least + 1} / static_cast(size)}; + // the texels across and down as the glass is wide and high (the same size in metres both ways) + auto const wide{std::max(static_cast(extent.x) * span.x, 1e-3)}; + auto const high{std::max(static_cast(extent.y) * span.y, 1e-3)}; + auto const texels{static_cast(gl::WATER_LAYER_TEXELS)}; + auto const across{static_cast(std::clamp(std::round(std::sqrt(texels * wide / high)), 16.0, texels / 16.0))}; + auto const down{static_cast(gl::WATER_LAYER_TEXELS / across)}; + info = {std::bit_cast(corner.x), std::bit_cast(corner.y), std::bit_cast(extent.x), std::bit_cast(extent.y), across, down, 0u, 0u}; + return info; +} + void windscreen_water::lay_snow(gl::water_ubs const &Block) { - for (std::size_t slot = 0; slot < m_glasscount; ++slot) + // the one glass with the layer + if ((m_layerslot < 0) || (static_cast(m_layerslot) >= m_glasscount)) + { + return; + } + auto const slot{static_cast(m_layerslot)}; + if (Block.snow_slots[static_cast(slot)] >= 0.5f) { - if (Block.snow_slots[static_cast(slot)] < 0.5f) - { - continue; - } auto const *material{m_host.material(m_glasses[slot].material)}; - if (material == nullptr) + auto const atlas{(material != nullptr) ? material_texture(*material, "raindropsatlas") : null_handle}; + auto const normal{(material != nullptr) ? material_texture(*material, "normalmap") : null_handle}; + if ((atlas != null_handle) && (normal != null_handle)) { - continue; + auto layer{Block}; + layer.counts.z = static_cast(slot); + layer.counts.w = m_step; + gpu_snow_layer(slot, atlas, normal, layer); } - auto const atlas{material_texture(*material, "raindropsatlas")}; - auto const normal{material_texture(*material, "normalmap")}; - if ((atlas == null_handle) || (normal == null_handle)) - { - continue; - } - auto layer{Block}; - layer.counts.z = static_cast(slot); - layer.counts.w = m_step; - gpu_snow_layer(slot, atlas, normal, layer); } } diff --git a/rendering/common/windscreenwater.h b/rendering/common/windscreenwater.h index 53df232c0..4acfe991e 100644 --- a/rendering/common/windscreenwater.h +++ b/rendering/common/windscreenwater.h @@ -106,6 +106,16 @@ class windscreen_water // the snow of the glasses of the snow Block says are simulated laid together, after the step void lay_snow(gl::water_ubs const &Block); + protected: + // where the layer of the snow of a glass lies (water.glsl): the rectangle of the uv its map holds the glass in (the corner and + // the size, the bits of floats) and the texels of the layer across and down, as the glass is wide and high in metres (0 when + // the map holds no glass or the glass has no layer) + // the eight uint the renderer puts at gl::WATER_LAYER_INFO_OFFSET for the glass of Slot (set up with its map Axes): the cab has + // one layer, for its first glass of the snow, the others get none (zeros) + std::array layer_info(std::size_t Slot, std::vector const &Axes); + + private: + host m_host; int m_state{0}; // 0: not set up yet, 1: ready, -1: can't be used TDynamicObject const *m_vehicle{nullptr}; @@ -113,6 +123,7 @@ class windscreen_water std::vector> m_kinds; // the materials of the cab with a mask of the wipers, what kind of glass they were std::array m_glasses{}; std::size_t m_glasscount{0}; + int m_layerslot{-1}; // the glass with the layer of the snow, -1 none glm::vec4 m_bladesbefore{-1.f}; double m_time{0.0}; // seconds the simulation runs std::uint32_t m_step{0}; diff --git a/rendering/opengl46/opengl46water.cpp b/rendering/opengl46/opengl46water.cpp index c0791d04d..4dbf77d18 100644 --- a/rendering/opengl46/opengl46water.cpp +++ b/rendering/opengl46/opengl46water.cpp @@ -135,6 +135,9 @@ void opengl46_windscreen_water::gpu_setup(std::size_t const Slot, std::vector(part.first), static_cast(part.second), GL_RED_INTEGER, GL_UNSIGNED_INT, nullptr); auto const axes{gl::water_slot_parts(Slot)[1]}; m_storage->update(Axes.data(), static_cast(axes.first), static_cast(std::min(axes.second, Axes.size() * sizeof(glm::vec4)))); + // where the layer of its snow lies + auto const info{layer_info(Slot, Axes)}; + m_storage->update(info.data(), static_cast(gl::WATER_LAYER_INFO_OFFSET + gl::WATER_LAYER_INFO_SIZE * Slot), static_cast(sizeof(info))); ::glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT | GL_BUFFER_UPDATE_BARRIER_BIT); } @@ -170,7 +173,7 @@ bool opengl46_windscreen_water::gpu_snow_layer(std::size_t const Slot, texture_h m_block->bind_uniform(); ::glBindTextureUnit(static_cast(gl::WATER_SNOW_ATLAS_TEX), static_cast(atlas.get_id())); ::glBindTextureUnit(static_cast(gl::WATER_SNOW_NORMAL_TEX), static_cast(normal.get_id())); - m_programs[pass::snowlayer]->dispatch(groups(static_cast(gl::WATER_LAYER) * gl::WATER_LAYER)); + m_programs[pass::snowlayer]->dispatch(groups(gl::WATER_LAYER_TEXELS)); ::glBindTextureUnit(static_cast(gl::WATER_SNOW_ATLAS_TEX), 0); ::glBindTextureUnit(static_cast(gl::WATER_SNOW_NORMAL_TEX), 0); ::glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); diff --git a/rendering/vulkan14/vulkan14shaders.cpp b/rendering/vulkan14/vulkan14shaders.cpp index e9d855667..7f6326901 100644 --- a/rendering/vulkan14/vulkan14shaders.cpp +++ b/rendering/vulkan14/vulkan14shaders.cpp @@ -971,7 +971,7 @@ std::string binding_preamble(bool const Raytracing) define("WATER_TRAIL", gl::WATER_TRAIL); define("WATER_MAP", gl::WATER_MAP); define("WATER_GROUP_SIZE", gl::WATER_GROUP_SIZE); - define("WATER_LAYER", gl::WATER_LAYER); + define("WATER_LAYER_TEXELS", gl::WATER_LAYER_TEXELS); define("WATER_LAYER_BANDS", gl::WATER_LAYER_BANDS); define("CAB_PROBE_SH_SIZE", static_cast(gl::CAB_PROBE_SH_SIZE)); define("CAB_PROBE_SH_GROUP_SIZE", static_cast(gl::CAB_PROBE_SH_GROUP_SIZE)); diff --git a/rendering/vulkan14/vulkan14water.cpp b/rendering/vulkan14/vulkan14water.cpp index ef37def6a..44ebc587e 100644 --- a/rendering/vulkan14/vulkan14water.cpp +++ b/rendering/vulkan14/vulkan14water.cpp @@ -150,6 +150,12 @@ void windscreen_water::gpu_setup(std::size_t const Slot, std::vector commands->fill_buffer(m_storage->handle(), static_cast(parts[part].first), static_cast(parts[part].second), 0); } } + // where the layer of its snow lies, a word at a time + auto const info{layer_info(Slot, Axes)}; + for (std::size_t word = 0; word < info.size(); ++word) + { + commands->fill_buffer(m_storage->handle(), static_cast(gl::WATER_LAYER_INFO_OFFSET + gl::WATER_LAYER_INFO_SIZE * Slot + 4 * word), 4, info[word]); + } // the axes of the map copied after that, from a staging buffer kept until the gpu is done with the frame auto const size{std::min(static_cast(parts[1].second), static_cast(Axes.size() * sizeof(glm::vec4)))}; auto staging{std::make_shared()}; @@ -287,7 +293,7 @@ bool windscreen_water::gpu_snow_layer(std::size_t const Slot, texture_handle con m_kernels[pass::snowlayer].run(commands, {buffer_descriptor(m_storage->handle(), 0, VK_WHOLE_SIZE), buffer_descriptor(slice.buffer, slice.offset, sizeof(gl::water_ubs)), image_descriptor(atlassampler, atlasview, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL), image_descriptor(normalsampler, normalview, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)}, - groups(static_cast(gl::WATER_LAYER) * gl::WATER_LAYER)); + groups(gl::WATER_LAYER_TEXELS)); compute_barrier(commands); return true; } diff --git a/shaders/ogl46/common.glsl b/shaders/ogl46/common.glsl index 288c4b279..f2193e498 100644 --- a/shaders/ogl46/common.glsl +++ b/shaders/ogl46/common.glsl @@ -65,7 +65,7 @@ #define RAIN_CELLS_SSBO_BINDING 18 #define WATER_UBO_BINDING 6 #define WATER_MASK_TEX 25 -#define WATER_LAYER 1024 +#define WATER_LAYER_TEXELS 2097152 #define WATER_LAYER_BANDS 8 #define WATER_SNOW_ATLAS_TEX 32 #define WATER_SNOW_NORMAL_TEX 33 diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index 9776e309d..58a81a870 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -97,7 +97,23 @@ void main() vec4 layerColour; vec4 layerNormal; vec4 layerBend; - water_layer_at(uint(snSlot), f_coord, layerColour, layerNormal, layerBend); + if (water_layer_of(uint(snSlot))) + { + water_layer_at(uint(snSlot), f_coord, layerColour, layerNormal, layerBend); + } + else + { + // a second glass of the snow in the cab (the layer goes to the first one): its snow laid at the pixel, as it was + // before the layer, slower but the same + snBig = (textureSize(raindropsatlas, 0).x >= 2048); + ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); + uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; + vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); + snow_layer_s laid = snCompose(f_coord, span, max(length(duv1), length(duv2))); + layerColour = vec4(laid.rgb, laid.a); + layerNormal = vec4(laid.n, laid.tr); + layerBend = vec4(laid.bend, laid.bendA, laid.haze); + } snowRGB = layerColour.rgb; snowA = layerColour.a; snowN = layerNormal.xyz; diff --git a/shaders/ogl46/water.glsl b/shaders/ogl46/water.glsl index 7bb7958f9..63dd7aab7 100644 --- a/shaders/ogl46/water.glsl +++ b/shaders/ogl46/water.glsl @@ -71,32 +71,56 @@ vec4 water_snow_texel(uint slot, uint map, ivec2 texel) return vec4(unpackHalf2x16(water_cells[index]), unpackHalf2x16(water_cells[index + 1u])); } -// the snow of a glass laid together (water_snowlayer.comp, read by mat_snow_windscreen.frag): WATER_LAYER x WATER_LAYER texels -// over its uv after the maps of the snow, three uint a texel: the colour (premultiplied, linear) and the cover; the normal of the -// sprites (tangent space, premultiplied) and their translucency; the bend of the picture behind (weighted), its weight, and the -// haze of the thin snow -uint water_layer_base(uint slot) +// the snow of a glass laid together (water_snowlayer.comp, read by mat_snow_windscreen.frag), after the maps of the snow: eight +// uint of every glass (the rectangle of its uv the layer takes: the corner and the size, floats; the texels of the layer across +// and down, 0 when the glass has no layer: the cab has one, for its first glass of the snow), then the layer, WATER_LAYER_TEXELS +// texels of three uint each: the colour +// (premultiplied, linear) and the cover; the normal of the sprites (tangent space, premultiplied) and their translucency; the bend +// of the picture behind (weighted), its weight, and the haze of the thin snow +void water_layer_rect(uint slot, out vec4 rect, out uvec2 size) { - return water_snow_base(0u, 2u) + slot * uint(WATER_LAYER * WATER_LAYER * 3); + uint info = water_snow_base(0u, 2u) + slot * 8u; + rect = uintBitsToFloat(uvec4(water_cells[info], water_cells[info + 1u], water_cells[info + 2u], water_cells[info + 3u])); + size = uvec2(water_cells[info + 4u], water_cells[info + 5u]); +} + +uint water_layer_base() +{ + return water_snow_base(0u, 2u) + uint(WATER_SLOTS) * 8u; +} + +// whether the glass has the layer of the snow +bool water_layer_of(uint slot) +{ + vec4 rect; + uvec2 size; + water_layer_rect(slot, rect, size); + return (size.x > 0u) && (size.y > 0u) && all(greaterThan(rect.zw, vec2(0.0))); } // the laid snow of a glass at UV, filtered between the texels: Colour (rgb, cover), Normal (xyz, translucency), Bend (xy, its -// weight, the haze) +// weight, the haze); nothing outside the layer void water_layer_at(uint slot, vec2 uv, out vec4 colour, out vec4 normal, out vec4 bend) { - vec2 p = uv * float(WATER_LAYER) - 0.5; - ivec2 i = ivec2(floor(p)); - vec2 f = p - vec2(i); colour = vec4(0.0); normal = vec4(0.0); bend = vec4(0.0); + vec4 rect; + uvec2 size; + water_layer_rect(slot, rect, size); + if ((size.x == 0u) || (size.y == 0u) || any(lessThanEqual(rect.zw, vec2(0.0)))) + return; + vec2 p = (uv - rect.xy) / rect.zw * vec2(size) - 0.5; + ivec2 i = ivec2(floor(p)); + vec2 f = p - vec2(i); + uint base = water_layer_base(); for (int k = 0; k < 4; ++k) { ivec2 t = i + ivec2(k & 1, k >> 1); - if (any(lessThan(t, ivec2(0))) || any(greaterThanEqual(t, ivec2(WATER_LAYER)))) + if (any(lessThan(t, ivec2(0))) || any(greaterThanEqual(t, ivec2(size)))) continue; float w = ((k & 1) == 1 ? f.x : 1.0 - f.x) * ((k >> 1) == 1 ? f.y : 1.0 - f.y); - uint index = water_layer_base(slot) + 3u * uint(t.y * WATER_LAYER + t.x); + uint index = base + 3u * (uint(t.y) * size.x + uint(t.x)); colour += unpackUnorm4x8(water_cells[index]) * w; normal += unpackSnorm4x8(water_cells[index + 1u]) * w; bend += unpackSnorm4x8(water_cells[index + 2u]) * w; diff --git a/shaders/ogl46/water_snowlayer.comp b/shaders/ogl46/water_snowlayer.comp index 6dbdd9dd2..524f83e95 100644 --- a/shaders/ogl46/water_snowlayer.comp +++ b/shaders/ogl46/water_snowlayer.comp @@ -3,7 +3,8 @@ // the snow on the windscreens (water_sim.glsl, water.glsl, snow_sprites.glsl): the snow of a glass of the snow laid together // from the sprites of its atlas into its layer, which mat_snow_windscreen.frag reads (the glass only reads it: laying the nine // grids of the lumps at every pixel of the glass in every frame cost as much as the rest of the frame). a thread per texel of -// the layer, the glass is water_counts.z. the snow under a lump changes slowly, so a band of every WATER_LAYER_BANDS-th row is +// the layer (over the rectangle of the uv the glass takes, ~1 mm a texel), the glass is water_counts.z. the snow under a lump +// changes slowly, so a band of every WATER_LAYER_BANDS-th row is // laid anew in a step (water_counts.w the step), and at once wherever a blade went over the glass in the step #include "common.glsl" @@ -42,13 +43,19 @@ void main() { uint slot = water_counts.z; uint texel = gl_GlobalInvocationID.x; - if ((slot >= uint(WATER_SLOTS)) || (texel >= uint(WATER_LAYER * WATER_LAYER)) || (water_snow_slots[slot] < 0.5)) + if ((slot >= uint(WATER_SLOTS)) || (texel >= uint(WATER_LAYER_TEXELS)) || (water_snow_slots[slot] < 0.5)) return; uint map; if (false == water_snow_map(slot, map)) return; - ivec2 at = ivec2(int(texel % uint(WATER_LAYER)), int(texel / uint(WATER_LAYER))); - vec2 uv = (vec2(at) + 0.5) / float(WATER_LAYER); + // the layer over the rectangle of the uv the glass takes + vec4 rect; + uvec2 size; + water_layer_rect(slot, rect, size); + if ((size.x == 0u) || (texel >= size.x * size.y)) + return; + ivec2 at = ivec2(int(texel % size.x), int(texel / size.x)); + vec2 uv = rect.xy + (vec2(at) + 0.5) / vec2(size) * rect.zw; ivec2 mapAt = clamp(ivec2(floor(uv * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); uint mapTexel = slot * uint(WATER_MAP * WATER_MAP) + uint(mapAt.y * WATER_MAP + mapAt.x); uint axis = mapTexel * 2u; @@ -63,8 +70,8 @@ void main() snMap = map; snBig = (textureSize(raindropsatlas, 0).x >= 2048); vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); - snow_layer_s s = snCompose(uv, span, 1.0 / float(WATER_LAYER)); - uint index = water_layer_base(slot) + 3u * texel; + snow_layer_s s = snCompose(uv, span, max(rect.z / float(size.x), rect.w / float(size.y))); + uint index = water_layer_base() + 3u * texel; water_cells[index] = packUnorm4x8(vec4(s.rgb, s.a)); water_cells[index + 1u] = packSnorm4x8(vec4(s.n, s.tr * 2.0 - 1.0)); water_cells[index + 2u] = packSnorm4x8(vec4(s.bend, s.bendA * 2.0 - 1.0, s.haze * 2.0 - 1.0)); diff --git a/shaders/vk14/common.glsl b/shaders/vk14/common.glsl index f19df191f..fd55c939e 100644 --- a/shaders/vk14/common.glsl +++ b/shaders/vk14/common.glsl @@ -138,7 +138,7 @@ #define WATER_TRAIL 1024 #define WATER_MAP 256 #define WATER_GROUP_SIZE 64 -#define WATER_LAYER 1024 +#define WATER_LAYER_TEXELS 2097152 #define WATER_LAYER_BANDS 8 #define CAB_PROBE_SH_SIZE 16 #define CAB_PROBE_SH_GROUP_SIZE 64 diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index c3ae46e72..e5e8d604a 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -102,7 +102,23 @@ void main() vec4 layerColour; vec4 layerNormal; vec4 layerBend; - water_layer_at(uint(snSlot), f_coord, layerColour, layerNormal, layerBend); + if (water_layer_of(uint(snSlot))) + { + water_layer_at(uint(snSlot), f_coord, layerColour, layerNormal, layerBend); + } + else + { + // a second glass of the snow in the cab (the layer goes to the first one): its snow laid at the pixel, as it was + // before the layer, slower but the same + snBig = (textureSize(raindropsatlas, 0).x >= 2048); + ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); + uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; + vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); + snow_layer_s laid = snCompose(f_coord, span, max(length(duv1), length(duv2))); + layerColour = vec4(laid.rgb, laid.a); + layerNormal = vec4(laid.n, laid.tr); + layerBend = vec4(laid.bend, laid.bendA, laid.haze); + } snowRGB = layerColour.rgb; snowA = layerColour.a; snowN = layerNormal.xyz; diff --git a/shaders/vk14/water.glsl b/shaders/vk14/water.glsl index 8befd9fcc..d2be3c053 100644 --- a/shaders/vk14/water.glsl +++ b/shaders/vk14/water.glsl @@ -72,32 +72,56 @@ vec4 water_snow_texel(uint slot, uint map, ivec2 texel) return vec4(unpackHalf2x16(water_cells[index]), unpackHalf2x16(water_cells[index + 1u])); } -// the snow of a glass laid together (water_snowlayer.comp, read by mat_snow_windscreen.frag): WATER_LAYER x WATER_LAYER texels -// over its uv after the maps of the snow, three uint a texel: the colour (premultiplied, linear) and the cover; the normal of the -// sprites (tangent space, premultiplied) and their translucency; the bend of the picture behind (weighted), its weight, and the -// haze of the thin snow -uint water_layer_base(uint slot) +// the snow of a glass laid together (water_snowlayer.comp, read by mat_snow_windscreen.frag), after the maps of the snow: eight +// uint of every glass (the rectangle of its uv the layer takes: the corner and the size, floats; the texels of the layer across +// and down, 0 when the glass has no layer: the cab has one, for its first glass of the snow), then the layer, WATER_LAYER_TEXELS +// texels of three uint each: the colour +// (premultiplied, linear) and the cover; the normal of the sprites (tangent space, premultiplied) and their translucency; the bend +// of the picture behind (weighted), its weight, and the haze of the thin snow +void water_layer_rect(uint slot, out vec4 rect, out uvec2 size) { - return water_snow_base(0u, 2u) + slot * uint(WATER_LAYER * WATER_LAYER * 3); + uint info = water_snow_base(0u, 2u) + slot * 8u; + rect = uintBitsToFloat(uvec4(water_cells[info], water_cells[info + 1u], water_cells[info + 2u], water_cells[info + 3u])); + size = uvec2(water_cells[info + 4u], water_cells[info + 5u]); +} + +uint water_layer_base() +{ + return water_snow_base(0u, 2u) + uint(WATER_SLOTS) * 8u; +} + +// whether the glass has the layer of the snow +bool water_layer_of(uint slot) +{ + vec4 rect; + uvec2 size; + water_layer_rect(slot, rect, size); + return (size.x > 0u) && (size.y > 0u) && all(greaterThan(rect.zw, vec2(0.0))); } // the laid snow of a glass at UV, filtered between the texels: Colour (rgb, cover), Normal (xyz, translucency), Bend (xy, its -// weight, the haze) +// weight, the haze); nothing outside the layer void water_layer_at(uint slot, vec2 uv, out vec4 colour, out vec4 normal, out vec4 bend) { - vec2 p = uv * float(WATER_LAYER) - 0.5; - ivec2 i = ivec2(floor(p)); - vec2 f = p - vec2(i); colour = vec4(0.0); normal = vec4(0.0); bend = vec4(0.0); + vec4 rect; + uvec2 size; + water_layer_rect(slot, rect, size); + if ((size.x == 0u) || (size.y == 0u) || any(lessThanEqual(rect.zw, vec2(0.0)))) + return; + vec2 p = (uv - rect.xy) / rect.zw * vec2(size) - 0.5; + ivec2 i = ivec2(floor(p)); + vec2 f = p - vec2(i); + uint base = water_layer_base(); for (int k = 0; k < 4; ++k) { ivec2 t = i + ivec2(k & 1, k >> 1); - if (any(lessThan(t, ivec2(0))) || any(greaterThanEqual(t, ivec2(WATER_LAYER)))) + if (any(lessThan(t, ivec2(0))) || any(greaterThanEqual(t, ivec2(size)))) continue; float w = ((k & 1) == 1 ? f.x : 1.0 - f.x) * ((k >> 1) == 1 ? f.y : 1.0 - f.y); - uint index = water_layer_base(slot) + 3u * uint(t.y * WATER_LAYER + t.x); + uint index = base + 3u * (uint(t.y) * size.x + uint(t.x)); colour += unpackUnorm4x8(water_cells[index]) * w; normal += unpackSnorm4x8(water_cells[index + 1u]) * w; bend += unpackSnorm4x8(water_cells[index + 2u]) * w; diff --git a/shaders/vk14/water_snowlayer.comp b/shaders/vk14/water_snowlayer.comp index 1ec8a882a..a69efdf1f 100644 --- a/shaders/vk14/water_snowlayer.comp +++ b/shaders/vk14/water_snowlayer.comp @@ -3,7 +3,8 @@ // the snow on the windscreens (water_sim.glsl, water.glsl, snow_sprites.glsl): the snow of a glass of the snow laid together // from the sprites of its atlas into its layer, which mat_snow_windscreen.frag reads (the glass only reads it: laying the nine // grids of the lumps at every pixel of the glass in every frame cost as much as the rest of the frame). a thread per texel of -// the layer, the glass is water_counts.z. the snow under a lump changes slowly, so a band of every WATER_LAYER_BANDS-th row is +// the layer (over the rectangle of the uv the glass takes, ~1 mm a texel), the glass is water_counts.z. the snow under a lump +// changes slowly, so a band of every WATER_LAYER_BANDS-th row is // laid anew in a step (water_counts.w the step), and at once wherever a blade went over the glass in the step // none of the pass set: everything the kernel reads is pushed with its dispatch (set COMPUTE_SET, water_sim.glsl) @@ -44,13 +45,19 @@ void main() { uint slot = water_counts.z; uint texel = gl_GlobalInvocationID.x; - if ((slot >= uint(WATER_SLOTS)) || (texel >= uint(WATER_LAYER * WATER_LAYER)) || (water_snow_slots[slot] < 0.5)) + if ((slot >= uint(WATER_SLOTS)) || (texel >= uint(WATER_LAYER_TEXELS)) || (water_snow_slots[slot] < 0.5)) return; uint map; if (false == water_snow_map(slot, map)) return; - ivec2 at = ivec2(int(texel % uint(WATER_LAYER)), int(texel / uint(WATER_LAYER))); - vec2 uv = (vec2(at) + 0.5) / float(WATER_LAYER); + // the layer over the rectangle of the uv the glass takes + vec4 rect; + uvec2 size; + water_layer_rect(slot, rect, size); + if ((size.x == 0u) || (texel >= size.x * size.y)) + return; + ivec2 at = ivec2(int(texel % size.x), int(texel / size.x)); + vec2 uv = rect.xy + (vec2(at) + 0.5) / vec2(size) * rect.zw; ivec2 mapAt = clamp(ivec2(floor(uv * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); uint mapTexel = slot * uint(WATER_MAP * WATER_MAP) + uint(mapAt.y * WATER_MAP + mapAt.x); uint axis = mapTexel * 2u; @@ -65,8 +72,8 @@ void main() snMap = map; snBig = (textureSize(raindropsatlas, 0).x >= 2048); vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); - snow_layer_s s = snCompose(uv, span, 1.0 / float(WATER_LAYER)); - uint index = water_layer_base(slot) + 3u * texel; + snow_layer_s s = snCompose(uv, span, max(rect.z / float(size.x), rect.w / float(size.y))); + uint index = water_layer_base() + 3u * texel; water_cells[index] = packUnorm4x8(vec4(s.rgb, s.a)); water_cells[index + 1u] = packSnorm4x8(vec4(s.n, s.tr * 2.0 - 1.0)); water_cells[index + 2u] = packSnorm4x8(vec4(s.bend, s.bendA * 2.0 - 1.0, s.haze * 2.0 - 1.0)); From 4d993908f515e33b41d34c6e2bb37ec4de6c8c39 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 23:14:37 +0100 Subject: [PATCH 099/123] Windscreen: rain keeps its last state and dries, snow stays and melts after snowfall [skip ci] - Rain drops, rivulets and micro droplets run on a rain clock (rain_state.w) that only advances while it rains, so they freeze when the rain stops and fade as the glass dries. - Glass wetness fills only during "rain:" weather. - Snow glasses keep their snow material after snowfall ends (until rain), so the snow stays, melts above 0 C into a wet film and drops, and dries. - The baked snow layer uses a larger drop share while melting. No new assets; no change to file formats. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- gl/ubo.h | 3 +- rendering/common/windscreenwater.cpp | 59 +++++++++++++++++++++++++ rendering/common/windscreenwater.h | 9 ++++ rendering/opengl46/opengl46renderer.cpp | 13 ++++-- rendering/opengl46/opengl46renderer.h | 1 + rendering/vulkan14/vulkan14frame.cpp | 13 ++++-- rendering/vulkan14/vulkan14renderer.h | 1 + shaders/ogl46/common.glsl | 2 +- shaders/ogl46/mat_rain_windscreen.frag | 6 +-- shaders/ogl46/rain_cells.comp | 2 +- shaders/ogl46/snow_sprites.glsl | 3 +- shaders/ogl46/water_snowlayer.comp | 4 ++ shaders/vk14/common.glsl | 2 +- shaders/vk14/mat_rain_windscreen.frag | 6 +-- shaders/vk14/rain_cells.comp | 2 +- shaders/vk14/snow_sprites.glsl | 3 +- shaders/vk14/water_snowlayer.comp | 4 ++ 17 files changed, 114 insertions(+), 19 deletions(-) diff --git a/gl/ubo.h b/gl/ubo.h index fc33d9018..4d6fb7513 100644 --- a/gl/ubo.h +++ b/gl/ubo.h @@ -212,7 +212,8 @@ namespace gl glm::vec4 camera_lo; // the rain the glass meets (mat_rain_windscreen): x the rain fallen so far, in seconds of the heaviest rain standing still (more // at speed: the glass runs into it); y how wet the glass is, 0 dry .. 1 as full of drops as it gets (it fills with the rain, - // dries when it stops); z how fast the glass fills: the share left to fill goes down as exp(-z x the rain fallen); w unused + // dries when it stops); z how fast the glass fills: the share left to fill goes down as exp(-z x the rain fallen); w the clock of + // the drops, s: it runs while it rains, so the glass keeps its last drops while it dries glm::vec4 rain_state; // the rain fallen (rain_state.x) when a blade last went over a place of its sweep: element b for the places b / 64 .. (b + 1) // / 64 of dWiperPos (the value of the wiper mask of a pixel), x .. w the blades (as wiper_pos); -1 not known. the drops and the diff --git a/rendering/common/windscreenwater.cpp b/rendering/common/windscreenwater.cpp index f5d6e1e48..949510867 100644 --- a/rendering/common/windscreenwater.cpp +++ b/rendering/common/windscreenwater.cpp @@ -30,6 +30,35 @@ http://mozilla.org/MPL/2.0/. namespace gfx { +// what the material of a glass of the snow draws with (the parts opengl_material copies for its variants, model/material.cpp) +struct snow_look +{ + opengl_material::texture_set textures{}; + std::vector texture_variants; + std::array params{}; + std::vector params_state; + std::shared_ptr shader; + std::optional opacity; + std::optional selfillum; + float glossiness{10.f}; + + static snow_look of(opengl_material const &Material) + { + return snow_look{Material.textures, Material.texture_variants, Material.params, Material.params_state, Material.shader, Material.opacity, Material.selfillum, Material.glossiness}; + } + void give(opengl_material &Material) const + { + Material.textures = textures; + Material.texture_variants = texture_variants; + Material.params = params; + Material.params_state = params_state; + Material.shader = shader; + Material.opacity = opacity; + Material.selfillum = selfillum; + Material.glossiness = glossiness; + } +}; + namespace { @@ -296,6 +325,10 @@ void windscreen_water::build(TModel3d &Cab) glass.material = material; auto const *opengl{m_host.material(material)}; glass.snow = is_snow_glass(opengl); + if (glass.snow) + { + glass.snowmaterial = std::make_shared(snow_look::of(*opengl)); + } glass.mask = opengl->textures[opengl->shader->texture_conf.at("wipermask").id]; for (std::size_t texel = 0; texel < texels; ++texel) { @@ -358,6 +391,10 @@ void windscreen_water::update(double const Seconds) } auto const *vehicle{simulation::Train != nullptr ? simulation::Train->Dynamic() : nullptr}; auto *cab{vehicle != nullptr ? vehicle->mdKabina : nullptr}; + if ((vehicle == m_vehicle) && (cab == m_cab)) + { + keep_snow(); + } // a material of the glasses of another kind: the weather changed, the materials have the shaders of the other weather (the // snow comes with the shader of the snow and goes with it) auto const changed{std::ranges::any_of(m_kinds, [this](auto const &Kind) { return glass_kind(m_host.material(Kind.first)) != Kind.second; })}; @@ -555,6 +592,28 @@ std::array windscreen_water::layer_info(std::size_t const Slot return info; } +void windscreen_water::keep_snow() +{ + if (Global.Weather == "rain:") + { + // the rain washes the snow off: the glass of the snow becomes a glass of the water again (built anew) + return; + } + for (std::size_t slot = 0; slot < m_glasscount; ++slot) + { + auto const &glass{m_glasses[slot]}; + if ((false == glass.snow) || (false == bool(glass.snowmaterial))) + { + continue; + } + if (auto *material{m_host.material(glass.material)}; (material != nullptr) && (false == is_snow_glass(material))) + { + // the weather took the shader of the snow away: it's given back (the slot param is set again by assign()) + glass.snowmaterial->give(*material); + } + } +} + void windscreen_water::lay_snow(gl::water_ubs const &Block) { // the one glass with the layer diff --git a/rendering/common/windscreenwater.h b/rendering/common/windscreenwater.h index 4acfe991e..bceebccf8 100644 --- a/rendering/common/windscreenwater.h +++ b/rendering/common/windscreenwater.h @@ -12,6 +12,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include #include @@ -29,6 +30,8 @@ class TDynamicObject; namespace gfx { +struct snow_look; // the look of the material of a glass of the snow (windscreenwater.cpp) + // the water on the windscreens of the cab of the train, simulated on the gpu, whichever api runs it. // // a glass is a material of mat_rain_windscreen (one with a mask of the wipers) in the model of the cab of the train, up to @@ -95,6 +98,9 @@ class windscreen_water double landings{0.0}; // the share of a landing left over from the steps before bool baked{false}; bool snow{false}; // a glass of the snow (mat_snow_windscreen), else of the water + // the material of a glass of the snow as it was set up: it stays on the glass when it stops snowing (until it rains), so + // the snow left on it melts into drops and dries + std::shared_ptr snowmaterial; }; // the glasses of the model of a cab found and set up @@ -105,6 +111,9 @@ class windscreen_water void assign(bool Assigned); // the snow of the glasses of the snow Block says are simulated laid together, after the step void lay_snow(gl::water_ubs const &Block); + // the glasses of the snow keep the material of the snow when it stops snowing, until it rains (the weather gave the material + // the shader of the rain back) + void keep_snow(); protected: // where the layer of the snow of a glass lies (water.glsl): the rectangle of the uv its map holds the glass in (the corner and diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index ba5b5ec46..f57a557da 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -1727,11 +1727,18 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) auto const speed{(owner != nullptr) ? std::min(std::abs(owner->MoverParameters->V) * 3.6 / 100.0, 1.0) : 0.0}; auto const meet{static_cast(percipitation_intensity) * (1.0 + fill_speed * speed)}; m_wiperrain += dt * meet; - if (percipitation_intensity > 0.f) + // the glass gets wet with the rain only (the snow lies on it, the glass of the snow melts it into its own water), and its + // drops live by the clock of the rain, which stands while it doesn't rain: the rain stopped, the glass keeps its last drops + // and rivulets where they are while it dries + auto const raining{(percipitation_intensity > 0.f) && (Global.Weather == "rain:")}; + if (raining) + { m_glasswet += (1.0 - m_glasswet) * (1.0 - std::exp(-fill_rate * dt * meet)); + m_raintime += dt; + } else m_glasswet *= std::exp(-dt * std::log(2.0) / dry_halflife * (1.0 + 2.0 * speed)); - scene_ubs.rain_state = glm::vec4{static_cast(m_wiperrain), static_cast(m_glasswet), static_cast(fill_rate), 0.f}; + scene_ubs.rain_state = glm::vec4{static_cast(m_wiperrain), static_cast(m_glasswet), static_cast(fill_rate), static_cast(m_raintime)}; } if (owner != nullptr) { @@ -1795,7 +1802,7 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) m_windscreenwater.update(Timer::GetDeltaTime()); // the drops and the rivulets of the glasses with rain, for the time of the block of the scene // (the drops a cell may hold: as many as the glass is wet) - m_windscreenwater.update_rain_cells(scene_ubs.time, (scene_ubs.rain_state.y > 0.001f) ? std::min(scene_ubs.rain_state.y + 0.01f, 1.f) : 0.f); + m_windscreenwater.update_rain_cells(static_cast(m_raintime), (scene_ubs.rain_state.y > 0.001f) ? std::min(scene_ubs.rain_state.y + 0.01f, 1.f) : 0.f); } m_windscreenwater.bind(); diff --git a/rendering/opengl46/opengl46renderer.h b/rendering/opengl46/opengl46renderer.h index 445b936c1..b74286e1a 100644 --- a/rendering/opengl46/opengl46renderer.h +++ b/rendering/opengl46/opengl46renderer.h @@ -862,6 +862,7 @@ class opengl46_renderer : public gfx_renderer, public gfx::scene_walk { // the rain the glass met so far and how wet it is (scene_ubs::rain_state) double m_wiperrain{0.0}; double m_glasswet{0.0}; + double m_raintime{0.0}; // the clock of the drops of the rain, s: it runs while it rains (scene_ubs.rain_state.w) gl::light_data light_data; std::unordered_map> m_shaders; diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index a4f31b27e..e0d6e769c 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -1137,7 +1137,7 @@ void vulkan14_renderer::render_scene() scene.water.update(Timer::GetDeltaTime()); // the drops and the rivulets of the glasses with rain, for the time the block of the scene gets (scene_ubs.time) // (the drops a cell may hold: as many as the glass is wet, a little more, since it's the wetness of the frame before) - scene.water.update_rain_cells(static_cast(Timer::GetTime()), (m_glasswet > 0.001) ? static_cast(std::min(m_glasswet + 0.01, 1.0)) : 0.f); + scene.water.update_rain_cells(static_cast(m_raintime), (m_glasswet > 0.001) ? static_cast(std::min(m_glasswet + 0.01, 1.0)) : 0.f); if (scene.targets.size() < m_viewports.size()) { scene.targets.resize(m_viewports.size()); @@ -1604,11 +1604,18 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) auto const speed{(owner != nullptr) ? std::min(std::abs(owner->MoverParameters->V) * 3.6 / 100.0, 1.0) : 0.0}; auto const meet{static_cast(percipitation_intensity) * (1.0 + fill_speed * speed)}; m_wiperrain += dt * meet; - if (percipitation_intensity > 0.f) + // the glass gets wet with the rain only (the snow lies on it, the glass of the snow melts it into its own water), and its + // drops live by the clock of the rain, which stands while it doesn't rain: the rain stopped, the glass keeps its last drops + // and rivulets where they are while it dries + auto const raining{(percipitation_intensity > 0.f) && (Global.Weather == "rain:")}; + if (raining) + { m_glasswet += (1.0 - m_glasswet) * (1.0 - std::exp(-fill_rate * dt * meet)); + m_raintime += dt; + } else m_glasswet *= std::exp(-dt * std::log(2.0) / dry_halflife * (1.0 + 2.0 * speed)); - scene_ubs.rain_state = glm::vec4{static_cast(m_wiperrain), static_cast(m_glasswet), static_cast(fill_rate), 0.f}; + scene_ubs.rain_state = glm::vec4{static_cast(m_wiperrain), static_cast(m_glasswet), static_cast(fill_rate), static_cast(m_raintime)}; } if (owner != nullptr) { diff --git a/rendering/vulkan14/vulkan14renderer.h b/rendering/vulkan14/vulkan14renderer.h index 477274efc..6f4d01a87 100644 --- a/rendering/vulkan14/vulkan14renderer.h +++ b/rendering/vulkan14/vulkan14renderer.h @@ -571,6 +571,7 @@ class vulkan14_renderer : public gfx_renderer, public gfx::scene_walk // the rain the glass met so far and how wet it is (scene_ubs::rain_state) double m_wiperrain{0.0}; double m_glasswet{0.0}; + double m_raintime{0.0}; // the clock of the drops of the rain, s: it runs while it rains (scene_ubs.rain_state.w) gl::light_data light_data{}; std::uint32_t m_lightcount{1}; // lights written to light_data // the copies of the light buffer in the ring of the frame since the lights were last written, by the header and the sun diff --git a/shaders/ogl46/common.glsl b/shaders/ogl46/common.glsl index f2193e498..6ac79e5d7 100644 --- a/shaders/ogl46/common.glsl +++ b/shaders/ogl46/common.glsl @@ -385,7 +385,7 @@ layout(std140, binding = SCENE_UBO_BINDING) uniform scene_ubo // the place of the camera of the pass in the world (whole 64 m, the rest), see gl::scene_ubs vec4 camera_hi; vec4 camera_lo; - // the rain the glass meets: x fallen so far, y how wet the glass is, z how fast it fills (mat_rain_windscreen), see gl::scene_ubs + // the rain the glass meets: x fallen so far, y how wet the glass is, z how fast it fills, w the clock of its drops (mat_rain_windscreen), see gl::scene_ubs vec4 rain_state; // the rain fallen when a blade last went over a place of its sweep (the wiper mask / 64), see gl::scene_ubs vec4 wiper_rain_pass[WIPER_PASS_BUCKETS]; diff --git a/shaders/ogl46/mat_rain_windscreen.frag b/shaders/ogl46/mat_rain_windscreen.frag index ca68ca98e..e3f012bc5 100644 --- a/shaders/ogl46/mat_rain_windscreen.frag +++ b/shaders/ogl46/mat_rain_windscreen.frag @@ -406,7 +406,7 @@ float rivWob(Riv r, float dW, out float ramp, out float wobD) ramp = rampT * rampT * (3.0 - 2.0 * rampT); float rampD = 3.0 * rampT * (1.0 - rampT) / 2.5; float a1 = dW * r.wavK + r.wavPh; - float a2 = dW * r.wavK * 1.7 - time * r.wavSp * 1.0472 + r.wavPh * 2.0; // the wave runs DOWN + float a2 = dW * r.wavK * 1.7 - rain_state.w * r.wavSp * 1.0472 + r.wavPh * 2.0; // the wave runs DOWN (the clock of the rain) float w1 = 0.7 * sin(a1) + 0.3 * sin(a2); float w1D = 0.7 * cos(a1) * r.wavK + 0.3 * cos(a2) * r.wavK * 1.7; wobD = -streak_wiggle * (rampD * w1 + ramp * w1D); @@ -535,7 +535,7 @@ void drawRivulet(inout Hit hit, Riv r, vec2 sUVr, vec2 rd1, vec2 rd2) vec2 slope = -nxy / max(nz, 0.08); if (!inHead) slope.y = slope.y * vtSign / STREAK_TAIL_SCALE - slope.x * wobD - + streak_flow * ramp * sin(dW * 4.8 - time * 4.0); + + streak_flow * ramp * sin(dW * 4.8 - rain_state.w * 4.0); // the slope of the layer to the one of the glass if (STREAK_FLIP_Y != 0) slope.y = -slope.y; slope = wsFromLayerDir(slope); @@ -787,7 +787,7 @@ void main() uvec2 mk = cellKey(mc); uint m0 = Hash(uvec3(mk, 51u)); float mLife = micro_life * mix(0.6, 1.6, RandF(m0)); - float mtt = time / mLife + RandF(m0); + float mtt = rain_state.w / mLife + RandF(m0); // the clock of the rain: still when it doesn't rain float mph = fract(mtt); uint mep = uint(mod(floor(mtt), 65521.0)); uint m1 = Hash(uvec3(mk, mep * 4u + 1u)); diff --git a/shaders/ogl46/rain_cells.comp b/shaders/ogl46/rain_cells.comp index 43ab26a60..1756b4009 100644 --- a/shaders/ogl46/rain_cells.comp +++ b/shaders/ogl46/rain_cells.comp @@ -6,7 +6,7 @@ #include "common.glsl" -layout(location = 0) uniform float rain_time; // the time of the block of the scene (scene_ubs.time) +layout(location = 0) uniform float rain_time; // the clock of the rain (scene_ubs.rain_state.w): it runs while it rains, the drops stay as they are when it stops layout(location = 1) uniform float rain_amount; // how wet the glass is (scene_ubs.rain_state.y, a little more) layout(location = 2) uniform int rain_pass; // 0 the cells, 1 the reach of the drops diff --git a/shaders/ogl46/snow_sprites.glsl b/shaders/ogl46/snow_sprites.glsl index a7291d671..015d0b2db 100644 --- a/shaders/ogl46/snow_sprites.glsl +++ b/shaders/ogl46/snow_sprites.glsl @@ -40,6 +40,7 @@ const float SNOW_PACKED = 0.4; // and of packed snow const int TILE_DROP = 15; vec2 snUV = vec2(0.0); // the place on the glass laid, uv +float snDrops = snow_drops; // share of the texels with water showing a drop (water_snowlayer.comp: more when it stopped snowing) int snSlot = 0; uint snMap = 0u; bool snBig = true; // a 4 x 4 atlas (else the older 2 x 2) @@ -167,7 +168,7 @@ void snFlakes(vec2 span, float pixelUV, inout sprite_acc acc) bool crystal = (q.x >= 0.05); if ((false == drop) && (false == crystal)) continue; - if (chance > (drop ? snow_drops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) + if (chance > (drop ? snDrops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) continue; float size = sizeDraw * (drop ? mix(0.7, 1.4, smoothstep(0.03, 0.3, q.y)) : 1.0); if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, 1.0, local)) diff --git a/shaders/ogl46/water_snowlayer.comp b/shaders/ogl46/water_snowlayer.comp index 524f83e95..4181b1615 100644 --- a/shaders/ogl46/water_snowlayer.comp +++ b/shaders/ogl46/water_snowlayer.comp @@ -22,6 +22,9 @@ layout(local_size_x = WATER_GROUP_SIZE) in; // the share of the sweep of a blade around where it went in the step whose snow is laid anew: a lump is laid by the snow at its // middle, up to two of its cells (~3 cm) away from a texel it covers const float SNOW_LAYER_BLADE_MARGIN = 0.06; +// the share of the texels with the water of the melted snow showing a drop when it doesn't snow (while it snows: snow_drops, rare): +// the snow left on the glass melts into drops, which dry +const float SNOW_LAYER_MELT_DROPS = 0.5; // whether a blade went over the texel of the map, or near it, in the step bool snow_layer_swept(uint mapTexel) @@ -67,6 +70,7 @@ void main() if (false == due) return; snSlot = int(slot); + snDrops = (water_step.w > 0.5) ? snow_drops : SNOW_LAYER_MELT_DROPS; snMap = map; snBig = (textureSize(raindropsatlas, 0).x >= 2048); vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); diff --git a/shaders/vk14/common.glsl b/shaders/vk14/common.glsl index fd55c939e..f673bf16d 100644 --- a/shaders/vk14/common.glsl +++ b/shaders/vk14/common.glsl @@ -345,7 +345,7 @@ layout(std140, set = PASS_SET, binding = SCENE_UBO) uniform scene_ubo // the place of the camera of the pass in the world (whole 64 m, the rest), see gl::scene_ubs vec4 camera_hi; vec4 camera_lo; - // the rain the glass meets: x fallen so far, y how wet the glass is, z how fast it fills (mat_rain_windscreen), see gl::scene_ubs + // the rain the glass meets: x fallen so far, y how wet the glass is, z how fast it fills, w the clock of its drops (mat_rain_windscreen), see gl::scene_ubs vec4 rain_state; // the rain fallen when a blade last went over a place of its sweep (the wiper mask / 64), see gl::scene_ubs vec4 wiper_rain_pass[WIPER_PASS_BUCKETS]; diff --git a/shaders/vk14/mat_rain_windscreen.frag b/shaders/vk14/mat_rain_windscreen.frag index 89f1c263f..2338a9341 100644 --- a/shaders/vk14/mat_rain_windscreen.frag +++ b/shaders/vk14/mat_rain_windscreen.frag @@ -411,7 +411,7 @@ float rivWob(Riv r, float dW, out float ramp, out float wobD) ramp = rampT * rampT * (3.0 - 2.0 * rampT); float rampD = 3.0 * rampT * (1.0 - rampT) / 2.5; float a1 = dW * r.wavK + r.wavPh; - float a2 = dW * r.wavK * 1.7 - time * r.wavSp * 1.0472 + r.wavPh * 2.0; // the wave runs DOWN + float a2 = dW * r.wavK * 1.7 - rain_state.w * r.wavSp * 1.0472 + r.wavPh * 2.0; // the wave runs DOWN (the clock of the rain) float w1 = 0.7 * sin(a1) + 0.3 * sin(a2); float w1D = 0.7 * cos(a1) * r.wavK + 0.3 * cos(a2) * r.wavK * 1.7; wobD = -streak_wiggle * (rampD * w1 + ramp * w1D); @@ -540,7 +540,7 @@ void drawRivulet(inout Hit hit, Riv r, vec2 sUVr, vec2 rd1, vec2 rd2) vec2 slope = -nxy / max(nz, 0.08); if (!inHead) slope.y = slope.y * vtSign / STREAK_TAIL_SCALE - slope.x * wobD - + streak_flow * ramp * sin(dW * 4.8 - time * 4.0); + + streak_flow * ramp * sin(dW * 4.8 - rain_state.w * 4.0); // the slope of the layer to the one of the glass if (STREAK_FLIP_Y != 0) slope.y = -slope.y; slope = wsFromLayerDir(slope); @@ -792,7 +792,7 @@ void main() uvec2 mk = cellKey(mc); uint m0 = Hash(uvec3(mk, 51u)); float mLife = micro_life * mix(0.6, 1.6, RandF(m0)); - float mtt = time / mLife + RandF(m0); + float mtt = rain_state.w / mLife + RandF(m0); // the clock of the rain: still when it doesn't rain float mph = fract(mtt); uint mep = uint(mod(floor(mtt), 65521.0)); uint m1 = Hash(uvec3(mk, mep * 4u + 1u)); diff --git a/shaders/vk14/rain_cells.comp b/shaders/vk14/rain_cells.comp index 9b6848a2b..9fb5414c6 100644 --- a/shaders/vk14/rain_cells.comp +++ b/shaders/vk14/rain_cells.comp @@ -10,7 +10,7 @@ layout(push_constant) uniform kernel_constants { - float rain_time; // the time of the block of the scene (scene_ubs.time) + float rain_time; // the clock of the rain (scene_ubs.rain_state.w): it runs while it rains, the drops stay as they are when it stops float rain_amount; // how wet the glass is (scene_ubs.rain_state.y, a little more) int rain_pass; // 0 the cells, 1 the reach of the drops }; diff --git a/shaders/vk14/snow_sprites.glsl b/shaders/vk14/snow_sprites.glsl index a7291d671..015d0b2db 100644 --- a/shaders/vk14/snow_sprites.glsl +++ b/shaders/vk14/snow_sprites.glsl @@ -40,6 +40,7 @@ const float SNOW_PACKED = 0.4; // and of packed snow const int TILE_DROP = 15; vec2 snUV = vec2(0.0); // the place on the glass laid, uv +float snDrops = snow_drops; // share of the texels with water showing a drop (water_snowlayer.comp: more when it stopped snowing) int snSlot = 0; uint snMap = 0u; bool snBig = true; // a 4 x 4 atlas (else the older 2 x 2) @@ -167,7 +168,7 @@ void snFlakes(vec2 span, float pixelUV, inout sprite_acc acc) bool crystal = (q.x >= 0.05); if ((false == drop) && (false == crystal)) continue; - if (chance > (drop ? snow_drops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) + if (chance > (drop ? snDrops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) continue; float size = sizeDraw * (drop ? mix(0.7, 1.4, smoothstep(0.03, 0.3, q.y)) : 1.0); if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, 1.0, local)) diff --git a/shaders/vk14/water_snowlayer.comp b/shaders/vk14/water_snowlayer.comp index a69efdf1f..fbae658a5 100644 --- a/shaders/vk14/water_snowlayer.comp +++ b/shaders/vk14/water_snowlayer.comp @@ -24,6 +24,9 @@ layout(local_size_x = WATER_GROUP_SIZE) in; // the share of the sweep of a blade around where it went in the step whose snow is laid anew: a lump is laid by the snow at its // middle, up to two of its cells (~3 cm) away from a texel it covers const float SNOW_LAYER_BLADE_MARGIN = 0.06; +// the share of the texels with the water of the melted snow showing a drop when it doesn't snow (while it snows: snow_drops, rare): +// the snow left on the glass melts into drops, which dry +const float SNOW_LAYER_MELT_DROPS = 0.5; // whether a blade went over the texel of the map, or near it, in the step bool snow_layer_swept(uint mapTexel) @@ -69,6 +72,7 @@ void main() if (false == due) return; snSlot = int(slot); + snDrops = (water_step.w > 0.5) ? snow_drops : SNOW_LAYER_MELT_DROPS; snMap = map; snBig = (textureSize(raindropsatlas, 0).x >= 2048); vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); From cc5bf11373484e332156109391b74aed7a7f632b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 12:07:54 +0100 Subject: [PATCH 100/123] Windscreen: no drying or melting after the precipitation; the glass clears at once [skip ci] Reverts e8a0e78 (kept on the branch stan/szyby-schniecie-2026-11-14). The glass fills with rain only while it rains ("rain:" with precipitation) and is clear at once when it doesn't: the rain stopped, or the glass holds snow, so a glass switched from snow to rain starts dry. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- gl/ubo.h | 3 +- rendering/common/windscreenwater.cpp | 59 ------------------------- rendering/common/windscreenwater.h | 9 ---- rendering/opengl46/opengl46renderer.cpp | 20 +++------ rendering/opengl46/opengl46renderer.h | 1 - rendering/vulkan14/vulkan14frame.cpp | 20 +++------ rendering/vulkan14/vulkan14renderer.h | 1 - shaders/ogl46/common.glsl | 2 +- shaders/ogl46/mat_rain_windscreen.frag | 6 +-- shaders/ogl46/rain_cells.comp | 2 +- shaders/ogl46/snow_sprites.glsl | 3 +- shaders/ogl46/water_snowlayer.comp | 4 -- shaders/vk14/common.glsl | 2 +- shaders/vk14/mat_rain_windscreen.frag | 6 +-- shaders/vk14/rain_cells.comp | 2 +- shaders/vk14/snow_sprites.glsl | 3 +- shaders/vk14/water_snowlayer.comp | 4 -- 17 files changed, 25 insertions(+), 122 deletions(-) diff --git a/gl/ubo.h b/gl/ubo.h index 4d6fb7513..fc33d9018 100644 --- a/gl/ubo.h +++ b/gl/ubo.h @@ -212,8 +212,7 @@ namespace gl glm::vec4 camera_lo; // the rain the glass meets (mat_rain_windscreen): x the rain fallen so far, in seconds of the heaviest rain standing still (more // at speed: the glass runs into it); y how wet the glass is, 0 dry .. 1 as full of drops as it gets (it fills with the rain, - // dries when it stops); z how fast the glass fills: the share left to fill goes down as exp(-z x the rain fallen); w the clock of - // the drops, s: it runs while it rains, so the glass keeps its last drops while it dries + // dries when it stops); z how fast the glass fills: the share left to fill goes down as exp(-z x the rain fallen); w unused glm::vec4 rain_state; // the rain fallen (rain_state.x) when a blade last went over a place of its sweep: element b for the places b / 64 .. (b + 1) // / 64 of dWiperPos (the value of the wiper mask of a pixel), x .. w the blades (as wiper_pos); -1 not known. the drops and the diff --git a/rendering/common/windscreenwater.cpp b/rendering/common/windscreenwater.cpp index 949510867..f5d6e1e48 100644 --- a/rendering/common/windscreenwater.cpp +++ b/rendering/common/windscreenwater.cpp @@ -30,35 +30,6 @@ http://mozilla.org/MPL/2.0/. namespace gfx { -// what the material of a glass of the snow draws with (the parts opengl_material copies for its variants, model/material.cpp) -struct snow_look -{ - opengl_material::texture_set textures{}; - std::vector texture_variants; - std::array params{}; - std::vector params_state; - std::shared_ptr shader; - std::optional opacity; - std::optional selfillum; - float glossiness{10.f}; - - static snow_look of(opengl_material const &Material) - { - return snow_look{Material.textures, Material.texture_variants, Material.params, Material.params_state, Material.shader, Material.opacity, Material.selfillum, Material.glossiness}; - } - void give(opengl_material &Material) const - { - Material.textures = textures; - Material.texture_variants = texture_variants; - Material.params = params; - Material.params_state = params_state; - Material.shader = shader; - Material.opacity = opacity; - Material.selfillum = selfillum; - Material.glossiness = glossiness; - } -}; - namespace { @@ -325,10 +296,6 @@ void windscreen_water::build(TModel3d &Cab) glass.material = material; auto const *opengl{m_host.material(material)}; glass.snow = is_snow_glass(opengl); - if (glass.snow) - { - glass.snowmaterial = std::make_shared(snow_look::of(*opengl)); - } glass.mask = opengl->textures[opengl->shader->texture_conf.at("wipermask").id]; for (std::size_t texel = 0; texel < texels; ++texel) { @@ -391,10 +358,6 @@ void windscreen_water::update(double const Seconds) } auto const *vehicle{simulation::Train != nullptr ? simulation::Train->Dynamic() : nullptr}; auto *cab{vehicle != nullptr ? vehicle->mdKabina : nullptr}; - if ((vehicle == m_vehicle) && (cab == m_cab)) - { - keep_snow(); - } // a material of the glasses of another kind: the weather changed, the materials have the shaders of the other weather (the // snow comes with the shader of the snow and goes with it) auto const changed{std::ranges::any_of(m_kinds, [this](auto const &Kind) { return glass_kind(m_host.material(Kind.first)) != Kind.second; })}; @@ -592,28 +555,6 @@ std::array windscreen_water::layer_info(std::size_t const Slot return info; } -void windscreen_water::keep_snow() -{ - if (Global.Weather == "rain:") - { - // the rain washes the snow off: the glass of the snow becomes a glass of the water again (built anew) - return; - } - for (std::size_t slot = 0; slot < m_glasscount; ++slot) - { - auto const &glass{m_glasses[slot]}; - if ((false == glass.snow) || (false == bool(glass.snowmaterial))) - { - continue; - } - if (auto *material{m_host.material(glass.material)}; (material != nullptr) && (false == is_snow_glass(material))) - { - // the weather took the shader of the snow away: it's given back (the slot param is set again by assign()) - glass.snowmaterial->give(*material); - } - } -} - void windscreen_water::lay_snow(gl::water_ubs const &Block) { // the one glass with the layer diff --git a/rendering/common/windscreenwater.h b/rendering/common/windscreenwater.h index bceebccf8..4acfe991e 100644 --- a/rendering/common/windscreenwater.h +++ b/rendering/common/windscreenwater.h @@ -12,7 +12,6 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include #include #include #include @@ -30,8 +29,6 @@ class TDynamicObject; namespace gfx { -struct snow_look; // the look of the material of a glass of the snow (windscreenwater.cpp) - // the water on the windscreens of the cab of the train, simulated on the gpu, whichever api runs it. // // a glass is a material of mat_rain_windscreen (one with a mask of the wipers) in the model of the cab of the train, up to @@ -98,9 +95,6 @@ class windscreen_water double landings{0.0}; // the share of a landing left over from the steps before bool baked{false}; bool snow{false}; // a glass of the snow (mat_snow_windscreen), else of the water - // the material of a glass of the snow as it was set up: it stays on the glass when it stops snowing (until it rains), so - // the snow left on it melts into drops and dries - std::shared_ptr snowmaterial; }; // the glasses of the model of a cab found and set up @@ -111,9 +105,6 @@ class windscreen_water void assign(bool Assigned); // the snow of the glasses of the snow Block says are simulated laid together, after the step void lay_snow(gl::water_ubs const &Block); - // the glasses of the snow keep the material of the snow when it stops snowing, until it rains (the weather gave the material - // the shader of the rain back) - void keep_snow(); protected: // where the layer of the snow of a glass lies (water.glsl): the rectangle of the uv its map holds the glass in (the corner and diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index f57a557da..a160b32ea 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -1717,28 +1717,20 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) m_wiperbugs += Timer::GetDeltaTime() * std::max(std::abs(owner->MoverParameters->V) * 3.6 - 20.0, 0.0) / 80.0; scene_ubs.rain_wind.w = static_cast(m_wiperbugs); // the rain the glass meets (mat_rain_windscreen): counted in seconds of the heaviest rain standing still, more at speed (the - // glass runs into it). the glass fills with it up to as many drops as it gets (a lighter rain only fills it more slowly), and - // dries when it stops (by half in dry_halflife standing still, faster at speed) + // glass runs into it). the glass fills with it up to as many drops as it gets (a lighter rain only fills it more slowly) while + // it rains, and is clear at once when it doesn't (the rain stopped, or the glass holds snow) { constexpr double fill_rate{0.3}; // per second of the heaviest rain: 95% full in 10 s (20 s at cloud cover 1.5) constexpr double fill_speed{1.5}; // at 100 km/h and more the glass meets x (1 + fill_speed) as much rain - constexpr double dry_halflife{180.0}; // seconds standing still auto const dt{Timer::GetDeltaTime()}; auto const speed{(owner != nullptr) ? std::min(std::abs(owner->MoverParameters->V) * 3.6 / 100.0, 1.0) : 0.0}; auto const meet{static_cast(percipitation_intensity) * (1.0 + fill_speed * speed)}; m_wiperrain += dt * meet; - // the glass gets wet with the rain only (the snow lies on it, the glass of the snow melts it into its own water), and its - // drops live by the clock of the rain, which stands while it doesn't rain: the rain stopped, the glass keeps its last drops - // and rivulets where they are while it dries - auto const raining{(percipitation_intensity > 0.f) && (Global.Weather == "rain:")}; - if (raining) - { + if ((percipitation_intensity > 0.f) && (Global.Weather == "rain:")) m_glasswet += (1.0 - m_glasswet) * (1.0 - std::exp(-fill_rate * dt * meet)); - m_raintime += dt; - } else - m_glasswet *= std::exp(-dt * std::log(2.0) / dry_halflife * (1.0 + 2.0 * speed)); - scene_ubs.rain_state = glm::vec4{static_cast(m_wiperrain), static_cast(m_glasswet), static_cast(fill_rate), static_cast(m_raintime)}; + m_glasswet = 0.0; + scene_ubs.rain_state = glm::vec4{static_cast(m_wiperrain), static_cast(m_glasswet), static_cast(fill_rate), 0.f}; } if (owner != nullptr) { @@ -1802,7 +1794,7 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) m_windscreenwater.update(Timer::GetDeltaTime()); // the drops and the rivulets of the glasses with rain, for the time of the block of the scene // (the drops a cell may hold: as many as the glass is wet) - m_windscreenwater.update_rain_cells(static_cast(m_raintime), (scene_ubs.rain_state.y > 0.001f) ? std::min(scene_ubs.rain_state.y + 0.01f, 1.f) : 0.f); + m_windscreenwater.update_rain_cells(scene_ubs.time, (scene_ubs.rain_state.y > 0.001f) ? std::min(scene_ubs.rain_state.y + 0.01f, 1.f) : 0.f); } m_windscreenwater.bind(); diff --git a/rendering/opengl46/opengl46renderer.h b/rendering/opengl46/opengl46renderer.h index b74286e1a..445b936c1 100644 --- a/rendering/opengl46/opengl46renderer.h +++ b/rendering/opengl46/opengl46renderer.h @@ -862,7 +862,6 @@ class opengl46_renderer : public gfx_renderer, public gfx::scene_walk { // the rain the glass met so far and how wet it is (scene_ubs::rain_state) double m_wiperrain{0.0}; double m_glasswet{0.0}; - double m_raintime{0.0}; // the clock of the drops of the rain, s: it runs while it rains (scene_ubs.rain_state.w) gl::light_data light_data; std::unordered_map> m_shaders; diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index e0d6e769c..f44c048b1 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -1137,7 +1137,7 @@ void vulkan14_renderer::render_scene() scene.water.update(Timer::GetDeltaTime()); // the drops and the rivulets of the glasses with rain, for the time the block of the scene gets (scene_ubs.time) // (the drops a cell may hold: as many as the glass is wet, a little more, since it's the wetness of the frame before) - scene.water.update_rain_cells(static_cast(m_raintime), (m_glasswet > 0.001) ? static_cast(std::min(m_glasswet + 0.01, 1.0)) : 0.f); + scene.water.update_rain_cells(static_cast(Timer::GetTime()), (m_glasswet > 0.001) ? static_cast(std::min(m_glasswet + 0.01, 1.0)) : 0.f); if (scene.targets.size() < m_viewports.size()) { scene.targets.resize(m_viewports.size()); @@ -1594,28 +1594,20 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) m_wiperbugs += Timer::GetDeltaTime() * std::max(std::abs(owner->MoverParameters->V) * 3.6 - 20.0, 0.0) / 80.0; scene_ubs.rain_wind.w = static_cast(m_wiperbugs); // the rain the glass meets (mat_rain_windscreen): counted in seconds of the heaviest rain standing still, more at speed (the - // glass runs into it). the glass fills with it up to as many drops as it gets (a lighter rain only fills it more slowly), and - // dries when it stops (by half in dry_halflife standing still, faster at speed) + // glass runs into it). the glass fills with it up to as many drops as it gets (a lighter rain only fills it more slowly) while + // it rains, and is clear at once when it doesn't (the rain stopped, or the glass holds snow) { constexpr double fill_rate{0.3}; // per second of the heaviest rain: 95% full in 10 s (20 s at cloud cover 1.5) constexpr double fill_speed{1.5}; // at 100 km/h and more the glass meets x (1 + fill_speed) as much rain - constexpr double dry_halflife{180.0}; // seconds standing still auto const dt{Timer::GetDeltaTime()}; auto const speed{(owner != nullptr) ? std::min(std::abs(owner->MoverParameters->V) * 3.6 / 100.0, 1.0) : 0.0}; auto const meet{static_cast(percipitation_intensity) * (1.0 + fill_speed * speed)}; m_wiperrain += dt * meet; - // the glass gets wet with the rain only (the snow lies on it, the glass of the snow melts it into its own water), and its - // drops live by the clock of the rain, which stands while it doesn't rain: the rain stopped, the glass keeps its last drops - // and rivulets where they are while it dries - auto const raining{(percipitation_intensity > 0.f) && (Global.Weather == "rain:")}; - if (raining) - { + if ((percipitation_intensity > 0.f) && (Global.Weather == "rain:")) m_glasswet += (1.0 - m_glasswet) * (1.0 - std::exp(-fill_rate * dt * meet)); - m_raintime += dt; - } else - m_glasswet *= std::exp(-dt * std::log(2.0) / dry_halflife * (1.0 + 2.0 * speed)); - scene_ubs.rain_state = glm::vec4{static_cast(m_wiperrain), static_cast(m_glasswet), static_cast(fill_rate), static_cast(m_raintime)}; + m_glasswet = 0.0; + scene_ubs.rain_state = glm::vec4{static_cast(m_wiperrain), static_cast(m_glasswet), static_cast(fill_rate), 0.f}; } if (owner != nullptr) { diff --git a/rendering/vulkan14/vulkan14renderer.h b/rendering/vulkan14/vulkan14renderer.h index 6f4d01a87..477274efc 100644 --- a/rendering/vulkan14/vulkan14renderer.h +++ b/rendering/vulkan14/vulkan14renderer.h @@ -571,7 +571,6 @@ class vulkan14_renderer : public gfx_renderer, public gfx::scene_walk // the rain the glass met so far and how wet it is (scene_ubs::rain_state) double m_wiperrain{0.0}; double m_glasswet{0.0}; - double m_raintime{0.0}; // the clock of the drops of the rain, s: it runs while it rains (scene_ubs.rain_state.w) gl::light_data light_data{}; std::uint32_t m_lightcount{1}; // lights written to light_data // the copies of the light buffer in the ring of the frame since the lights were last written, by the header and the sun diff --git a/shaders/ogl46/common.glsl b/shaders/ogl46/common.glsl index 6ac79e5d7..f2193e498 100644 --- a/shaders/ogl46/common.glsl +++ b/shaders/ogl46/common.glsl @@ -385,7 +385,7 @@ layout(std140, binding = SCENE_UBO_BINDING) uniform scene_ubo // the place of the camera of the pass in the world (whole 64 m, the rest), see gl::scene_ubs vec4 camera_hi; vec4 camera_lo; - // the rain the glass meets: x fallen so far, y how wet the glass is, z how fast it fills, w the clock of its drops (mat_rain_windscreen), see gl::scene_ubs + // the rain the glass meets: x fallen so far, y how wet the glass is, z how fast it fills (mat_rain_windscreen), see gl::scene_ubs vec4 rain_state; // the rain fallen when a blade last went over a place of its sweep (the wiper mask / 64), see gl::scene_ubs vec4 wiper_rain_pass[WIPER_PASS_BUCKETS]; diff --git a/shaders/ogl46/mat_rain_windscreen.frag b/shaders/ogl46/mat_rain_windscreen.frag index e3f012bc5..ca68ca98e 100644 --- a/shaders/ogl46/mat_rain_windscreen.frag +++ b/shaders/ogl46/mat_rain_windscreen.frag @@ -406,7 +406,7 @@ float rivWob(Riv r, float dW, out float ramp, out float wobD) ramp = rampT * rampT * (3.0 - 2.0 * rampT); float rampD = 3.0 * rampT * (1.0 - rampT) / 2.5; float a1 = dW * r.wavK + r.wavPh; - float a2 = dW * r.wavK * 1.7 - rain_state.w * r.wavSp * 1.0472 + r.wavPh * 2.0; // the wave runs DOWN (the clock of the rain) + float a2 = dW * r.wavK * 1.7 - time * r.wavSp * 1.0472 + r.wavPh * 2.0; // the wave runs DOWN float w1 = 0.7 * sin(a1) + 0.3 * sin(a2); float w1D = 0.7 * cos(a1) * r.wavK + 0.3 * cos(a2) * r.wavK * 1.7; wobD = -streak_wiggle * (rampD * w1 + ramp * w1D); @@ -535,7 +535,7 @@ void drawRivulet(inout Hit hit, Riv r, vec2 sUVr, vec2 rd1, vec2 rd2) vec2 slope = -nxy / max(nz, 0.08); if (!inHead) slope.y = slope.y * vtSign / STREAK_TAIL_SCALE - slope.x * wobD - + streak_flow * ramp * sin(dW * 4.8 - rain_state.w * 4.0); + + streak_flow * ramp * sin(dW * 4.8 - time * 4.0); // the slope of the layer to the one of the glass if (STREAK_FLIP_Y != 0) slope.y = -slope.y; slope = wsFromLayerDir(slope); @@ -787,7 +787,7 @@ void main() uvec2 mk = cellKey(mc); uint m0 = Hash(uvec3(mk, 51u)); float mLife = micro_life * mix(0.6, 1.6, RandF(m0)); - float mtt = rain_state.w / mLife + RandF(m0); // the clock of the rain: still when it doesn't rain + float mtt = time / mLife + RandF(m0); float mph = fract(mtt); uint mep = uint(mod(floor(mtt), 65521.0)); uint m1 = Hash(uvec3(mk, mep * 4u + 1u)); diff --git a/shaders/ogl46/rain_cells.comp b/shaders/ogl46/rain_cells.comp index 1756b4009..43ab26a60 100644 --- a/shaders/ogl46/rain_cells.comp +++ b/shaders/ogl46/rain_cells.comp @@ -6,7 +6,7 @@ #include "common.glsl" -layout(location = 0) uniform float rain_time; // the clock of the rain (scene_ubs.rain_state.w): it runs while it rains, the drops stay as they are when it stops +layout(location = 0) uniform float rain_time; // the time of the block of the scene (scene_ubs.time) layout(location = 1) uniform float rain_amount; // how wet the glass is (scene_ubs.rain_state.y, a little more) layout(location = 2) uniform int rain_pass; // 0 the cells, 1 the reach of the drops diff --git a/shaders/ogl46/snow_sprites.glsl b/shaders/ogl46/snow_sprites.glsl index 015d0b2db..a7291d671 100644 --- a/shaders/ogl46/snow_sprites.glsl +++ b/shaders/ogl46/snow_sprites.glsl @@ -40,7 +40,6 @@ const float SNOW_PACKED = 0.4; // and of packed snow const int TILE_DROP = 15; vec2 snUV = vec2(0.0); // the place on the glass laid, uv -float snDrops = snow_drops; // share of the texels with water showing a drop (water_snowlayer.comp: more when it stopped snowing) int snSlot = 0; uint snMap = 0u; bool snBig = true; // a 4 x 4 atlas (else the older 2 x 2) @@ -168,7 +167,7 @@ void snFlakes(vec2 span, float pixelUV, inout sprite_acc acc) bool crystal = (q.x >= 0.05); if ((false == drop) && (false == crystal)) continue; - if (chance > (drop ? snDrops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) + if (chance > (drop ? snow_drops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) continue; float size = sizeDraw * (drop ? mix(0.7, 1.4, smoothstep(0.03, 0.3, q.y)) : 1.0); if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, 1.0, local)) diff --git a/shaders/ogl46/water_snowlayer.comp b/shaders/ogl46/water_snowlayer.comp index 4181b1615..524f83e95 100644 --- a/shaders/ogl46/water_snowlayer.comp +++ b/shaders/ogl46/water_snowlayer.comp @@ -22,9 +22,6 @@ layout(local_size_x = WATER_GROUP_SIZE) in; // the share of the sweep of a blade around where it went in the step whose snow is laid anew: a lump is laid by the snow at its // middle, up to two of its cells (~3 cm) away from a texel it covers const float SNOW_LAYER_BLADE_MARGIN = 0.06; -// the share of the texels with the water of the melted snow showing a drop when it doesn't snow (while it snows: snow_drops, rare): -// the snow left on the glass melts into drops, which dry -const float SNOW_LAYER_MELT_DROPS = 0.5; // whether a blade went over the texel of the map, or near it, in the step bool snow_layer_swept(uint mapTexel) @@ -70,7 +67,6 @@ void main() if (false == due) return; snSlot = int(slot); - snDrops = (water_step.w > 0.5) ? snow_drops : SNOW_LAYER_MELT_DROPS; snMap = map; snBig = (textureSize(raindropsatlas, 0).x >= 2048); vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); diff --git a/shaders/vk14/common.glsl b/shaders/vk14/common.glsl index f673bf16d..fd55c939e 100644 --- a/shaders/vk14/common.glsl +++ b/shaders/vk14/common.glsl @@ -345,7 +345,7 @@ layout(std140, set = PASS_SET, binding = SCENE_UBO) uniform scene_ubo // the place of the camera of the pass in the world (whole 64 m, the rest), see gl::scene_ubs vec4 camera_hi; vec4 camera_lo; - // the rain the glass meets: x fallen so far, y how wet the glass is, z how fast it fills, w the clock of its drops (mat_rain_windscreen), see gl::scene_ubs + // the rain the glass meets: x fallen so far, y how wet the glass is, z how fast it fills (mat_rain_windscreen), see gl::scene_ubs vec4 rain_state; // the rain fallen when a blade last went over a place of its sweep (the wiper mask / 64), see gl::scene_ubs vec4 wiper_rain_pass[WIPER_PASS_BUCKETS]; diff --git a/shaders/vk14/mat_rain_windscreen.frag b/shaders/vk14/mat_rain_windscreen.frag index 2338a9341..89f1c263f 100644 --- a/shaders/vk14/mat_rain_windscreen.frag +++ b/shaders/vk14/mat_rain_windscreen.frag @@ -411,7 +411,7 @@ float rivWob(Riv r, float dW, out float ramp, out float wobD) ramp = rampT * rampT * (3.0 - 2.0 * rampT); float rampD = 3.0 * rampT * (1.0 - rampT) / 2.5; float a1 = dW * r.wavK + r.wavPh; - float a2 = dW * r.wavK * 1.7 - rain_state.w * r.wavSp * 1.0472 + r.wavPh * 2.0; // the wave runs DOWN (the clock of the rain) + float a2 = dW * r.wavK * 1.7 - time * r.wavSp * 1.0472 + r.wavPh * 2.0; // the wave runs DOWN float w1 = 0.7 * sin(a1) + 0.3 * sin(a2); float w1D = 0.7 * cos(a1) * r.wavK + 0.3 * cos(a2) * r.wavK * 1.7; wobD = -streak_wiggle * (rampD * w1 + ramp * w1D); @@ -540,7 +540,7 @@ void drawRivulet(inout Hit hit, Riv r, vec2 sUVr, vec2 rd1, vec2 rd2) vec2 slope = -nxy / max(nz, 0.08); if (!inHead) slope.y = slope.y * vtSign / STREAK_TAIL_SCALE - slope.x * wobD - + streak_flow * ramp * sin(dW * 4.8 - rain_state.w * 4.0); + + streak_flow * ramp * sin(dW * 4.8 - time * 4.0); // the slope of the layer to the one of the glass if (STREAK_FLIP_Y != 0) slope.y = -slope.y; slope = wsFromLayerDir(slope); @@ -792,7 +792,7 @@ void main() uvec2 mk = cellKey(mc); uint m0 = Hash(uvec3(mk, 51u)); float mLife = micro_life * mix(0.6, 1.6, RandF(m0)); - float mtt = rain_state.w / mLife + RandF(m0); // the clock of the rain: still when it doesn't rain + float mtt = time / mLife + RandF(m0); float mph = fract(mtt); uint mep = uint(mod(floor(mtt), 65521.0)); uint m1 = Hash(uvec3(mk, mep * 4u + 1u)); diff --git a/shaders/vk14/rain_cells.comp b/shaders/vk14/rain_cells.comp index 9fb5414c6..9b6848a2b 100644 --- a/shaders/vk14/rain_cells.comp +++ b/shaders/vk14/rain_cells.comp @@ -10,7 +10,7 @@ layout(push_constant) uniform kernel_constants { - float rain_time; // the clock of the rain (scene_ubs.rain_state.w): it runs while it rains, the drops stay as they are when it stops + float rain_time; // the time of the block of the scene (scene_ubs.time) float rain_amount; // how wet the glass is (scene_ubs.rain_state.y, a little more) int rain_pass; // 0 the cells, 1 the reach of the drops }; diff --git a/shaders/vk14/snow_sprites.glsl b/shaders/vk14/snow_sprites.glsl index 015d0b2db..a7291d671 100644 --- a/shaders/vk14/snow_sprites.glsl +++ b/shaders/vk14/snow_sprites.glsl @@ -40,7 +40,6 @@ const float SNOW_PACKED = 0.4; // and of packed snow const int TILE_DROP = 15; vec2 snUV = vec2(0.0); // the place on the glass laid, uv -float snDrops = snow_drops; // share of the texels with water showing a drop (water_snowlayer.comp: more when it stopped snowing) int snSlot = 0; uint snMap = 0u; bool snBig = true; // a 4 x 4 atlas (else the older 2 x 2) @@ -168,7 +167,7 @@ void snFlakes(vec2 span, float pixelUV, inout sprite_acc acc) bool crystal = (q.x >= 0.05); if ((false == drop) && (false == crystal)) continue; - if (chance > (drop ? snDrops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) + if (chance > (drop ? snow_drops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) continue; float size = sizeDraw * (drop ? mix(0.7, 1.4, smoothstep(0.03, 0.3, q.y)) : 1.0); if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, 1.0, local)) diff --git a/shaders/vk14/water_snowlayer.comp b/shaders/vk14/water_snowlayer.comp index fbae658a5..a69efdf1f 100644 --- a/shaders/vk14/water_snowlayer.comp +++ b/shaders/vk14/water_snowlayer.comp @@ -24,9 +24,6 @@ layout(local_size_x = WATER_GROUP_SIZE) in; // the share of the sweep of a blade around where it went in the step whose snow is laid anew: a lump is laid by the snow at its // middle, up to two of its cells (~3 cm) away from a texel it covers const float SNOW_LAYER_BLADE_MARGIN = 0.06; -// the share of the texels with the water of the melted snow showing a drop when it doesn't snow (while it snows: snow_drops, rare): -// the snow left on the glass melts into drops, which dry -const float SNOW_LAYER_MELT_DROPS = 0.5; // whether a blade went over the texel of the map, or near it, in the step bool snow_layer_swept(uint mapTexel) @@ -72,7 +69,6 @@ void main() if (false == due) return; snSlot = int(slot); - snDrops = (water_step.w > 0.5) ? snow_drops : SNOW_LAYER_MELT_DROPS; snMap = map; snBig = (textureSize(raindropsatlas, 0).x >= 2048); vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); From b5c3a87dc5c221cdde8d048b71b86dc3369e875c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 20:56:56 +0100 Subject: [PATCH 101/123] Windscreen snow: the layer lists the sprites of each texel, the glass lays them sharp [skip ci] The layer of the snow held the snow laid together at ~1 mm a texel, so the glass showed it filtered: softer lumps, flatter normals and refraction than when every pixel laid the sprites itself. Now water_snowlayer.comp lists, for each texel, the sprites coming within it (up to 16, in the order they are laid, the covered ones left out), and mat_snow_windscreen.frag lays only those at its pixels, sharp from the atlas, as the full look through every cell did. The layer grows from three to four uint a texel (+8 MiB). The snow also uses all the tiles of the atlas: mostly the icy fleece of the first two rows (0-7), now and then a lump of packed snow (10-13) or, more rarely, a wet one (8, 9); a drop now and then a wet lump with its film (14). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- gl/ubo.h | 6 +- shaders/ogl46/mat_snow_windscreen.frag | 45 ++-- shaders/ogl46/snow_sprites.glsl | 350 +++++++++++++++++-------- shaders/ogl46/water.glsl | 42 ++- shaders/ogl46/water_snowlayer.comp | 40 +-- shaders/vk14/mat_snow_windscreen.frag | 45 ++-- shaders/vk14/snow_sprites.glsl | 350 +++++++++++++++++-------- shaders/vk14/water.glsl | 42 ++- shaders/vk14/water_snowlayer.comp | 40 +-- 9 files changed, 599 insertions(+), 361 deletions(-) diff --git a/gl/ubo.h b/gl/ubo.h index fc33d9018..859485db4 100644 --- a/gl/ubo.h +++ b/gl/ubo.h @@ -783,12 +783,12 @@ namespace gl const size_t WATER_SNOW_SIZE = 8 * static_cast(WATER_MAP) * WATER_MAP; // the snow of the glass of the snow laid together (water_snowlayer.comp): first eight uint of every glass (the rectangle of its // uv the layer takes, four floats; the texels of the layer across and down, 0 when the glass has no layer), then the layer, - // WATER_LAYER_TEXELS texels of three uint each (the colour and the cover, the normal and the translucency, the bend and the - // haze, see water.glsl) + // WATER_LAYER_TEXELS texels of four uint each (the sprites of the snow coming within the texel, see water.glsl and + // snow_sprites.glsl) const size_t WATER_LAYER_INFO_OFFSET = WATER_SNOW_OFFSET + 2 * WATER_SNOW_SIZE * WATER_SLOTS; const size_t WATER_LAYER_INFO_SIZE = 32; const size_t WATER_LAYER_OFFSET = WATER_LAYER_INFO_OFFSET + WATER_LAYER_INFO_SIZE * WATER_SLOTS; - const size_t WATER_LAYER_SIZE = 12 * static_cast(WATER_LAYER_TEXELS); + const size_t WATER_LAYER_SIZE = 16 * static_cast(WATER_LAYER_TEXELS); const size_t WATER_STORAGE_SIZE = WATER_LAYER_OFFSET + WATER_LAYER_SIZE; // the parts of a glass in the storage: its drops and what the passes keep of them, its map (the axes the second part), its // cells and its paths, its header and its counts, its two maps of the snow, the layer of the snow (the one of the cab, laid diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index 58a81a870..e4772cb01 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -10,12 +10,14 @@ // the blades wipe it as they wipe the rain (a wet trace stays), it melts at the warm glass, slush slides down. The renderer gives // the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. // -// The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen, laid together into -// a layer of the glass by water_snowlayer.comp (snow_sprites.glsl) when the snow under them changes, so the glass only reads it: +// The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen, laid at each pixel +// sharp from the atlas (snow_sprites.glsl). water_snowlayer.comp lists, for each texel of a layer of the glass (~1 mm), the +// sprites coming within it when the snow under them changes, so the glass lays only those instead of looking through every cell: // - the lumps, in nine grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, // size, the snow it takes); it comes when the snow around reaches that and stays as it is until the snow goes. The grids come -// one after the other as the snow piles up (all of them icy fleece, more and bigger; a lump of packed snow very rarely), each on the ones before, -// so the snow accumulates rather than changes, and covers the glass by 2-3 mm, small gaps left (the scene behind them blurred). In a heap they come sooner +// one after the other as the snow piles up (mostly icy fleece, more and bigger; now and then a lump of packed or wet snow), +// each on the ones before, so the snow accumulates rather than changes, and covers the glass by 2-3 mm, small gaps left (the +// scene behind them blurred). In a heap they come sooner // - dots and small puffs of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) // A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. // @@ -85,7 +87,8 @@ void main() Bgl *= invmax; vec4 tex_color = texture(diffuse, f_coord); // no discard: clean glass between faint dirt must still get snow and blur - // the snow laid together from the sprites (water_snowlayer.comp, a band of its rows every step and wherever a blade goes) + // the snow laid together from the sprites (listed by water_snowlayer.comp, a band of its rows every step and wherever a blade + // goes) vec3 snowRGB = vec3(0.0); float snowA = 0.0; vec3 snowN = vec3(0.0); @@ -94,26 +97,28 @@ void main() snSlot = int(param[2].z + 0.5) - 1; if ((snSlot >= 0) && (snSlot < WATER_SLOTS) && water_snow_map(uint(snSlot), snMap)) { - vec4 layerColour; - vec4 layerNormal; - vec4 layerBend; - if (water_layer_of(uint(snSlot))) + // the sprites coming within the texel of the layer at the pixel (water_snowlayer.comp) laid at the pixel, sharp from the + // atlas; a second glass of the snow in the cab (the layer goes to the first one) looks through all the cells around the + // pixel, as it was before the layer, slower but the same + snBig = (textureSize(raindropsatlas, 0).x >= 2048); + float pixelUV = max(length(duv1), length(duv2)); + snow_layer_s laid; + uvec4 refs; + vec2 centreUV; + vec2 span; + if (water_layer_refs(uint(snSlot), f_coord, refs, centreUV)) { - water_layer_at(uint(snSlot), f_coord, layerColour, layerNormal, layerBend); + snSpan(uint(snSlot), centreUV, span); + laid = snComposeRefs(f_coord, centreUV, span, pixelUV, refs); } else { - // a second glass of the snow in the cab (the layer goes to the first one): its snow laid at the pixel, as it was - // before the layer, slower but the same - snBig = (textureSize(raindropsatlas, 0).x >= 2048); - ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); - uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; - vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); - snow_layer_s laid = snCompose(f_coord, span, max(length(duv1), length(duv2))); - layerColour = vec4(laid.rgb, laid.a); - layerNormal = vec4(laid.n, laid.tr); - layerBend = vec4(laid.bend, laid.bendA, laid.haze); + snSpan(uint(snSlot), f_coord, span); + laid = snCompose(f_coord, span, pixelUV); } + vec4 layerColour = vec4(laid.rgb, laid.a); + vec4 layerNormal = vec4(laid.n, laid.tr); + vec4 layerBend = vec4(laid.bend, laid.bendA, laid.haze); snowRGB = layerColour.rgb; snowA = layerColour.a; snowN = layerNormal.xyz; diff --git a/shaders/ogl46/snow_sprites.glsl b/shaders/ogl46/snow_sprites.glsl index a7291d671..9ab5e8066 100644 --- a/shaders/ogl46/snow_sprites.glsl +++ b/shaders/ogl46/snow_sprites.glsl @@ -136,54 +136,6 @@ vec3 snTone(vec4 q, float random) return tone * mix(vec3(1.0), vec3(0.88, 0.91, 0.94), smoothstep(0.3, 0.8, snWetness(q))); } -// the dots and the drops, in cells of snow_flake_cell metres of the glass: in many of the cells holding a little dry snow a dot -// or a small puff sits between the lumps, in some of those holding only water a drop of a melted flake -void snFlakes(vec2 span, float pixelUV, inout sprite_acc acc) -{ - vec2 perUV = span / snow_flake_cell; // cells in a unit of the uv - vec2 p = snUV * perUV; - ivec2 here = ivec2(floor(p)); - for (int oy = 1; oy >= -1; --oy) - { - for (int ox = 1; ox >= -1; --ox) - { - ivec2 cell = here + ivec2(ox, oy); - uint seed = Hash(uvec3(uvec2(cell + 8192), 17u + 7u * uint(snSlot))); - vec2 centre = vec2(cell) + 0.15 + 0.7 * vec2(RandF(seed), RandF(seed)); - // every draw of the cell first, in the order they always came, so the flake doesn't change: the map is the costly - // part, so it is read only for a flake which, as big as it gets, covers the pixel - float chance = RandF(seed); - float ang = RandF(seed) * 6.2831853; - vec2 rot = vec2(cos(ang), sin(ang)); - float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; - float kind = RandF(seed); - float random = RandF(seed); - float sizeDraw = mix(0.6, 1.0, RandF(seed)); - vec2 local; - if (false == snLocal(p, centre, sizeDraw * 1.4, vec2(1.0), rot, flip, 1.0, local)) - continue; - vec4 q = water_snow_at(uint(snSlot), snMap, centre / perUV); - bool drop = (q.x < 0.05) && (q.y > 0.03); - bool crystal = (q.x >= 0.05); - if ((false == drop) && (false == crystal)) - continue; - if (chance > (drop ? snow_drops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) - continue; - float size = sizeDraw * (drop ? mix(0.7, 1.4, smoothstep(0.03, 0.3, q.y)) : 1.0); - if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, 1.0, local)) - continue; - int tile = TILE_DROP; - float alpha = smoothstep(0.03, 0.1, q.y); - if (crystal) - { - tile = 2 + min(int(kind * 2.0), 1); // small icy puffs - alpha = snow_thin; - } - snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0, acc); - } - } -} - // how much a cell of the lumps lies in a heap: the snow landing side by side runs together, so the lumps come in heaps with // barer glass between them; a random number for every few cells, blended between them (the same for every pixel of the cell) float snHeap(ivec2 cell) @@ -215,58 +167,106 @@ struct lump_grid float share; // the share of its cells having a lump at all (1: all of them) }; +// the grids of the lumps, coming one after the other as the snow piles up, each on the ones before, in the order they are laid +// (front to back, the top one first): mostly icy fleece (the puffs and clumps of the first two rows of the atlas, tiles 0-7), +// more and bigger, closing the glass by 2-3 mm; now and then a single lump on top: packed snow (tiles 10-13) or, more rarely, a +// wet one with its film (tiles 8, 9) +const int SN_GRIDS = 9; +const lump_grid sn_grids[SN_GRIDS] = lump_grid[SN_GRIDS]( + lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 8, 6, 0.12), + lump_grid(vec2(0.75), 251u, vec2(1.4, 2.8), vec2(2.0, 3.0), 0, 8, 1.0), + lump_grid(vec2(0.0, 0.5), 233u, vec2(1.2, 2.4), vec2(2.0, 3.0), 0, 8, 1.0), + lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.0), vec2(2.0, 3.0), 0, 8, 1.0), + lump_grid(vec2(0.75, 0.25), 151u, vec2(0.7, 1.6), vec2(1.8, 2.8), 4, 4, 1.0), + lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.8, 2.8), 4, 4, 1.0), + lump_grid(vec2(0.25), 97u, vec2(0.2, 0.9), vec2(1.4, 2.4), 0, 4, 1.0), + lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(1.4, 2.4), 0, 4, 1.0), + lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(1.2, 2.0), 0, 4, 1.0)); + const float SN_COVERED = 0.998; // the snow over the pixel covering it: the sprites under it are not looked at -void snLumps(vec2 span, float pixelUV, lump_grid grid, inout sprite_acc acc) +// the dots and the drops, in cells of snow_flake_cell metres of the glass: in many of the cells holding a little dry snow a dot +// or a small puff sits between the lumps, in some of those holding only water a drop of a melted flake. the flake of a Cell at P +// (the place in cells): true when it is there and comes within Reach (cells) of P; laid over Acc where it covers P +bool snFlakeCell(vec2 p, ivec2 cell, vec2 perUV, float pixelUV, float reach, inout sprite_acc acc) { - if (acc.a >= SN_COVERED) - return; // the grids over this one cover the pixel - vec2 perUV = span / snow_lump_cell; - vec2 p = snUV * perUV + grid.shift; - ivec2 here = ivec2(floor(p)); - for (int oy = 1; oy >= -1; --oy) + uint seed = Hash(uvec3(uvec2(cell + 8192), 17u + 7u * uint(snSlot))); + vec2 centre = vec2(cell) + 0.15 + 0.7 * vec2(RandF(seed), RandF(seed)); + // every draw of the cell first, in the order they always came, so the flake doesn't change: the map is the costly part, so + // it is read only for a flake which, as big as it gets, covers the pixel + float chance = RandF(seed); + float ang = RandF(seed) * 6.2831853; + vec2 rot = vec2(cos(ang), sin(ang)); + float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; + float kind = RandF(seed); + float random = RandF(seed); + float sizeDraw = mix(0.6, 1.0, RandF(seed)); + vec2 local; + if (false == snLocal(p, centre, sizeDraw * 1.4 + 2.0 * reach, vec2(1.0), rot, flip, 1.0, local)) + return false; + vec4 q = water_snow_at(uint(snSlot), snMap, centre / perUV); + bool drop = (q.x < 0.05) && (q.y > 0.03); + bool crystal = (q.x >= 0.05); + if ((false == drop) && (false == crystal)) + return false; + if (chance > (drop ? snow_drops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) + return false; + float size = sizeDraw * (drop ? mix(0.7, 1.4, smoothstep(0.03, 0.3, q.y)) : 1.0); + if (false == snLocal(p, centre, size + 2.0 * reach, vec2(1.0), rot, flip, 1.0, local)) + return false; + if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, 1.0, local)) + return true; + int tile = (kind < 0.25) ? 14 : TILE_DROP; // a drop, now and then a wet lump with its film + float alpha = smoothstep(0.03, 0.1, q.y); + if (crystal) { - for (int ox = 1; ox >= -1; --ox) - { - if (acc.a >= SN_COVERED) - return; - ivec2 cell = here + ivec2(ox, oy); - uint seed = Hash(uvec3(uvec2(cell + 4096), grid.salt + 7u * uint(snSlot))); - vec2 centre = vec2(cell) + 0.1 + 0.8 * vec2(RandF(seed), RandF(seed)); - // every draw of the cell first, in the order they always came, so the lump doesn't change: the map is the costly - // part, so it is read only for a lump which, as big as it grows, covers the pixel (most of the nine cells don't) - float needsDraw = RandF(seed); - if (RandF(seed) >= grid.share) - continue; - float ang = RandF(seed) * 6.2831853; - vec2 rot = vec2(cos(ang), sin(ang)); - float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; - int tile = grid.tiles + min(int(RandF(seed) * float(grid.count)), grid.count - 1); - float random = RandF(seed); - float aniso = mix(0.8, 1.0, RandF(seed)); - float sizeDraw = mix(grid.size.x, grid.size.y, RandF(seed)); - vec2 local; - if (false == snLocal(p, centre, sizeDraw * snow_lump_grow.y, vec2(1.0), rot, flip, aniso, local)) - continue; - // the snow it takes, sooner in a heap - float needs = mix(grid.snow.x, grid.snow.y, needsDraw) * mix(1.4, 0.6, snHeap(cell)); - vec4 q = water_snow_at(uint(snSlot), snMap, (centre - grid.shift) / perUV); - if (q.x <= needs) - continue; - float size = sizeDraw * mix(snow_lump_grow.x, snow_lump_grow.y, smoothstep(needs, needs * 2.0 + 0.2, q.x)); - if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, aniso, local)) - continue; - // fading in over the first snow (no flicker on the edge), opaque when thick; the thick snow bends nothing - float deep = smoothstep(snow_cover * 3.0, snow_deep, q.x); - float alpha = smoothstep(needs, needs + 0.04, q.x) * mix(snow_ice, 1.0, deep); - snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0 - deep, acc); - } + tile = min(int(kind * 4.0), 3); // small icy puffs (the first row of the atlas) + alpha = snow_thin; } + snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0, acc); + return true; } -// the snow of the glass laid together at UV: the flakes over the lumps (water_snowlayer.comp bakes it into the layer of the glass, -// mat_snow_windscreen.frag reads it). Span: metres of the glass in a unit of its uv; PixelUV: the uv a texel of the layer covers -// (the level of the atlas). snSlot, snMap and snBig set before +// the lump of a Cell of a Grid at P (the place in the cells of the grid, shifted): true when it is there and comes within Reach +// (cells) of P; laid over Acc where it covers P +bool snLumpCell(vec2 p, ivec2 cell, vec2 perUV, lump_grid grid, float pixelUV, float reach, inout sprite_acc acc) +{ + uint seed = Hash(uvec3(uvec2(cell + 4096), grid.salt + 7u * uint(snSlot))); + vec2 centre = vec2(cell) + 0.1 + 0.8 * vec2(RandF(seed), RandF(seed)); + // every draw of the cell first, in the order they always came, so the lump doesn't change: the map is the costly part, so it + // is read only for a lump which, as big as it grows, covers the pixel (most of the nine cells don't) + float needsDraw = RandF(seed); + if (RandF(seed) >= grid.share) + return false; + float ang = RandF(seed) * 6.2831853; + vec2 rot = vec2(cos(ang), sin(ang)); + float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; + int tile = grid.tiles + min(int(RandF(seed) * float(grid.count)), grid.count - 1); + float random = RandF(seed); + float aniso = mix(0.8, 1.0, RandF(seed)); + float sizeDraw = mix(grid.size.x, grid.size.y, RandF(seed)); + vec2 local; + if (false == snLocal(p, centre, sizeDraw * snow_lump_grow.y + 2.0 * reach, vec2(1.0), rot, flip, aniso, local)) + return false; + // the snow it takes, sooner in a heap + float needs = mix(grid.snow.x, grid.snow.y, needsDraw) * mix(1.4, 0.6, snHeap(cell)); + vec4 q = water_snow_at(uint(snSlot), snMap, (centre - grid.shift) / perUV); + if (q.x <= needs) + return false; + float size = sizeDraw * mix(snow_lump_grow.x, snow_lump_grow.y, smoothstep(needs, needs * 2.0 + 0.2, q.x)); + if (false == snLocal(p, centre, size + 2.0 * reach, vec2(1.0), rot, flip, aniso, local)) + return false; + if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, aniso, local)) + return true; + // fading in over the first snow (no flicker on the edge), opaque when thick; the thick snow bends nothing + float deep = smoothstep(snow_cover * 3.0, snow_deep, q.x); + float alpha = smoothstep(needs, needs + 0.04, q.x) * mix(snow_ice, 1.0, deep); + snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0 - deep, acc); + return true; +} + +// the snow of the glass laid together: the flakes over the lumps, as water_snowlayer.comp lists them for the texels of the layer +// and mat_snow_windscreen.frag lays them at its pixels (or, for a glass without the layer, all of them at its pixels) struct snow_layer_s { vec3 rgb; // premultiplied @@ -278,27 +278,8 @@ struct snow_layer_s float haze; // the blur of the picture behind the thin snow }; -snow_layer_s snCompose(vec2 uv, vec2 span, float pixelUV) +snow_layer_s snFinish(sprite_acc flakes, sprite_acc layer) { - snUV = uv; - snBend = vec2(0.0); - snBendA = 0.0; - sprite_acc layer = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); - sprite_acc flakes = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); - // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: all of them icy - // fleece (small puffs and icy clumps, tiles 2-5), more and bigger, closing the glass by 2-3 mm; now and then a single - // lump of packed snow on top. laid front to back: the flakes, the single packed lumps, then the grids from the top one - // down, so a texel stops looking once the snow over it covers it - snFlakes(span, pixelUV, flakes); - snLumps(span, pixelUV, lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 12, 2, 0.03), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.75), 251u, vec2(1.4, 2.8), vec2(2.0, 3.0), 4, 2, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.0, 0.5), 233u, vec2(1.2, 2.4), vec2(2.0, 3.0), 4, 2, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.0), vec2(2.0, 3.0), 4, 2, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.75, 0.25), 151u, vec2(0.7, 1.6), vec2(1.8, 2.8), 4, 2, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.8, 2.8), 4, 2, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.25), 97u, vec2(0.2, 0.9), vec2(1.4, 2.4), 2, 4, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(1.4, 2.4), 2, 4, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(1.2, 2.0), 2, 4, 1.0), layer); snow_layer_s s; // the flakes over the layer s.rgb = flakes.rgb + layer.rgb * (1.0 - flakes.a); @@ -312,4 +293,147 @@ snow_layer_s snCompose(vec2 uv, vec2 span, float pixelUV) return s; } +// the snow of the glass laid together at UV from all the cells around it. Span: metres of the glass in a unit of its uv; +// PixelUV: the uv a pixel covers (the level of the atlas). snSlot, snMap and snBig set before +snow_layer_s snCompose(vec2 uv, vec2 span, float pixelUV) +{ + snUV = uv; + snBend = vec2(0.0); + snBendA = 0.0; + sprite_acc layer = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + sprite_acc flakes = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + // laid front to back: the flakes, then the grids from the top one down, so a pixel stops looking once the snow over it covers + // it + vec2 perF = span / snow_flake_cell; + vec2 pF = uv * perF; + ivec2 hereF = ivec2(floor(pF)); + for (int oy = 1; oy >= -1; --oy) + for (int ox = 1; ox >= -1; --ox) + snFlakeCell(pF, hereF + ivec2(ox, oy), perF, pixelUV, 0.0, flakes); + vec2 perL = span / snow_lump_cell; + for (int g = 0; g < SN_GRIDS; ++g) + { + vec2 pL = uv * perL + sn_grids[g].shift; + ivec2 hereL = ivec2(floor(pL)); + for (int k = 0; k < 9; ++k) + { + if (layer.a >= SN_COVERED) + return snFinish(flakes, layer); // the grids over this one cover the pixel + snLumpCell(pL, hereL + ivec2(1 - k % 3, 1 - k / 3), perL, sn_grids[g], pixelUV, 0.0, layer); + } + } + return snFinish(flakes, layer); +} + +// the layer of the snow of a glass (water_snowlayer.comp writes it, mat_snow_windscreen.frag reads it) holds for each of its +// texels (~1 mm of the glass) the sprites coming within it, in the order they are laid: up to SN_REFS bytes in four uint, each +// 1 + the list (0 the flakes, 1 .. SN_GRIDS the grids of the lumps) times 16 + the cell around the texel (0 .. 8: 1 - the column +// offset + 3 * (1 - the row offset)), 0 after the last one (a layer cleared to zeros lists nothing). the glass lays only those at +// its pixels, sharp from the atlas as when it laid all of the cells around itself, at a fraction of the cost +const int SN_REFS = 16; +// the sprites over a texel covering it on the whole (the level of the atlas the size of the texel): those under it are left out +const float SN_LIST_COVERED = 0.97; + +void snRef(uint ref, inout uvec4 refs, inout int count) +{ + if (count >= SN_REFS) + return; + uint shift = 8u * uint(count & 3); + refs[count >> 2] = (refs[count >> 2] & ~(255u << shift)) | ((ref + 1u) << shift); + ++count; +} + +// the sprites of the texel of the layer centred at UV (PixelUV its size in the uv), as the layer holds them +uvec4 snList(vec2 uv, vec2 span, float pixelUV) +{ + snUV = uv; + snBend = vec2(0.0); + snBendA = 0.0; + uvec4 refs = uvec4(0u); + int count = 0; + sprite_acc layer = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + sprite_acc flakes = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + // the sprites coming within the corners of the texel (cells of the list), as big as they grow before it is listed anew + float half_diagonal = 0.75 * pixelUV; + vec2 perF = span / snow_flake_cell; + vec2 pF = uv * perF; + ivec2 hereF = ivec2(floor(pF)); + float reachF = half_diagonal * max(perF.x, perF.y) * 1.25; + for (int k = 0; k < 9; ++k) + { + if (snFlakeCell(pF, hereF + ivec2(1 - k % 3, 1 - k / 3), perF, pixelUV, reachF, flakes)) + snRef(uint(k), refs, count); + } + vec2 perL = span / snow_lump_cell; + float reachL = half_diagonal * max(perL.x, perL.y) * 1.25 + 0.05; + for (int g = 0; g < SN_GRIDS; ++g) + { + if (layer.a >= SN_LIST_COVERED) + break; // the grids over this one cover the texel + vec2 pL = uv * perL + sn_grids[g].shift; + ivec2 hereL = ivec2(floor(pL)); + for (int k = 0; k < 9; ++k) + { + if (snLumpCell(pL, hereL + ivec2(1 - k % 3, 1 - k / 3), perL, sn_grids[g], pixelUV, reachL, layer)) + snRef(uint(16 * (g + 1) + k), refs, count); + } + } + return refs; +} + +// the snow of the glass laid together at UV from the sprites Refs of the texel of the layer centred at CentreUV (the cells +// counted around that). Span: metres of the glass in a unit of its uv at the texel; PixelUV: the uv a pixel covers +snow_layer_s snComposeRefs(vec2 uv, vec2 centreUV, vec2 span, float pixelUV, uvec4 refs) +{ + snUV = uv; + snBend = vec2(0.0); + snBendA = 0.0; + sprite_acc layer = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + sprite_acc flakes = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + vec2 perF = span / snow_flake_cell; + vec2 perL = span / snow_lump_cell; + for (int r = 0; r < SN_REFS; ++r) + { + uint ref = (refs[r >> 2] >> (8u * uint(r & 3))) & 255u; + if (ref == 0u) + break; + --ref; + int list = int(ref >> 4u); + int k = int(ref & 15u); + ivec2 offset = ivec2(1 - k % 3, 1 - k / 3); + if ((list == 0) && (k < 9)) + { + snFlakeCell(uv * perF, ivec2(floor(centreUV * perF)) + offset, perF, pixelUV, 0.0, flakes); + continue; + } + if ((list > SN_GRIDS) || (k >= 9) || (layer.a >= SN_COVERED)) + continue; // nothing laid, or the grids over this one cover the pixel + lump_grid grid = sn_grids[list - 1]; + ivec2 here = ivec2(floor(centreUV * perL + grid.shift)); + snLumpCell(uv * perL + grid.shift, here + offset, perL, grid, pixelUV, 0.0, layer); + } + return snFinish(flakes, layer); +} + +// the metres of the glass in a unit of its uv at UV, from the texel of its map there or, at the edge of the glass, the nearest +// one next to it the glass is on; false when there is none +bool snSpan(uint slot, vec2 uv, out vec2 span) +{ + span = vec2(0.05); + ivec2 at = clamp(ivec2(floor(uv * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); + // the texel itself first, then the ones beside it, then the corners + const ivec2 near[9] = ivec2[9](ivec2(0), ivec2(1, 0), ivec2(-1, 0), ivec2(0, 1), ivec2(0, -1), ivec2(1), ivec2(-1, 1), ivec2(1, -1), ivec2(-1)); + for (int k = 0; k < 9; ++k) + { + ivec2 t = clamp(at + near[k], ivec2(0), ivec2(WATER_MAP - 1)); + uint axis = (slot * uint(WATER_MAP * WATER_MAP) + uint(t.y * WATER_MAP + t.x)) * 2u; + if (water_axes[axis].w > 0.0) + { + span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); + return true; + } + } + return false; +} + #endif diff --git a/shaders/ogl46/water.glsl b/shaders/ogl46/water.glsl index 63dd7aab7..418f3455b 100644 --- a/shaders/ogl46/water.glsl +++ b/shaders/ogl46/water.glsl @@ -74,9 +74,8 @@ vec4 water_snow_texel(uint slot, uint map, ivec2 texel) // the snow of a glass laid together (water_snowlayer.comp, read by mat_snow_windscreen.frag), after the maps of the snow: eight // uint of every glass (the rectangle of its uv the layer takes: the corner and the size, floats; the texels of the layer across // and down, 0 when the glass has no layer: the cab has one, for its first glass of the snow), then the layer, WATER_LAYER_TEXELS -// texels of three uint each: the colour -// (premultiplied, linear) and the cover; the normal of the sprites (tangent space, premultiplied) and their translucency; the bend -// of the picture behind (weighted), its weight, and the haze of the thin snow +// texels of four uint each: the sprites of the snow coming within the texel, in the order they are laid (snow_sprites.glsl, +// snList) void water_layer_rect(uint slot, out vec4 rect, out uvec2 size) { uint info = water_snow_base(0u, 2u) + slot * 8u; @@ -98,35 +97,24 @@ bool water_layer_of(uint slot) return (size.x > 0u) && (size.y > 0u) && all(greaterThan(rect.zw, vec2(0.0))); } -// the laid snow of a glass at UV, filtered between the texels: Colour (rgb, cover), Normal (xyz, translucency), Bend (xy, its -// weight, the haze); nothing outside the layer -void water_layer_at(uint slot, vec2 uv, out vec4 colour, out vec4 normal, out vec4 bend) +// the sprites of the snow of a glass at UV, as its layer holds them for the texel there (Refs, see snow_sprites.glsl), and the +// centre of that texel (CentreUV); false outside the layer +bool water_layer_refs(uint slot, vec2 uv, out uvec4 refs, out vec2 centreUV) { - colour = vec4(0.0); - normal = vec4(0.0); - bend = vec4(0.0); + refs = uvec4(0u); + centreUV = uv; vec4 rect; uvec2 size; water_layer_rect(slot, rect, size); if ((size.x == 0u) || (size.y == 0u) || any(lessThanEqual(rect.zw, vec2(0.0)))) - return; - vec2 p = (uv - rect.xy) / rect.zw * vec2(size) - 0.5; - ivec2 i = ivec2(floor(p)); - vec2 f = p - vec2(i); - uint base = water_layer_base(); - for (int k = 0; k < 4; ++k) - { - ivec2 t = i + ivec2(k & 1, k >> 1); - if (any(lessThan(t, ivec2(0))) || any(greaterThanEqual(t, ivec2(size)))) - continue; - float w = ((k & 1) == 1 ? f.x : 1.0 - f.x) * ((k >> 1) == 1 ? f.y : 1.0 - f.y); - uint index = base + 3u * (uint(t.y) * size.x + uint(t.x)); - colour += unpackUnorm4x8(water_cells[index]) * w; - normal += unpackSnorm4x8(water_cells[index + 1u]) * w; - bend += unpackSnorm4x8(water_cells[index + 2u]) * w; - } - normal.w = normal.w * 0.5 + 0.5; - bend.zw = bend.zw * 0.5 + 0.5; + return false; + ivec2 t = ivec2(floor((uv - rect.xy) / rect.zw * vec2(size))); + if (any(lessThan(t, ivec2(0))) || any(greaterThanEqual(t, ivec2(size)))) + return false; + centreUV = rect.xy + (vec2(t) + 0.5) / vec2(size) * rect.zw; + uint index = water_layer_base() + 4u * (uint(t.y) * size.x + uint(t.x)); + refs = uvec4(water_cells[index], water_cells[index + 1u], water_cells[index + 2u], water_cells[index + 3u]); + return true; } // the latest map of the snow of a glass; false when there's none yet diff --git a/shaders/ogl46/water_snowlayer.comp b/shaders/ogl46/water_snowlayer.comp index 524f83e95..a27a884dc 100644 --- a/shaders/ogl46/water_snowlayer.comp +++ b/shaders/ogl46/water_snowlayer.comp @@ -1,11 +1,11 @@ #version 460 core #define STAGE_COMPUTE 1 -// the snow on the windscreens (water_sim.glsl, water.glsl, snow_sprites.glsl): the snow of a glass of the snow laid together -// from the sprites of its atlas into its layer, which mat_snow_windscreen.frag reads (the glass only reads it: laying the nine -// grids of the lumps at every pixel of the glass in every frame cost as much as the rest of the frame). a thread per texel of -// the layer (over the rectangle of the uv the glass takes, ~1 mm a texel), the glass is water_counts.z. the snow under a lump -// changes slowly, so a band of every WATER_LAYER_BANDS-th row is -// laid anew in a step (water_counts.w the step), and at once wherever a blade went over the glass in the step +// the snow on the windscreens (water_sim.glsl, water.glsl, snow_sprites.glsl): the sprites of the snow of a glass coming within +// each texel of its layer listed, which mat_snow_windscreen.frag lays at its pixels, sharp from the atlas (looking through the +// nine cells of the ten lists at every pixel of the glass in every frame cost as much as the rest of the frame). a thread per +// texel of the layer (over the rectangle of the uv the glass takes, ~1 mm a texel), the glass is water_counts.z. the snow under +// a lump changes slowly, so a band of every WATER_LAYER_BANDS-th row is listed anew in a step (water_counts.w the step), and at +// once wherever a blade went over the glass in the step #include "common.glsl" #include "water_sim.glsl" @@ -58,21 +58,23 @@ void main() vec2 uv = rect.xy + (vec2(at) + 0.5) / vec2(size) * rect.zw; ivec2 mapAt = clamp(ivec2(floor(uv * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); uint mapTexel = slot * uint(WATER_MAP * WATER_MAP) + uint(mapAt.y * WATER_MAP + mapAt.x); - uint axis = mapTexel * 2u; - // nothing of the glass there (the glass reads its layer only where it is, filtered next to it) - if (water_axes[axis].w <= 0.0) - return; // a band of the rows in a step (the snow builds up and melts slowly), and wherever a blade went bool due = ((uint(at.y) % uint(WATER_LAYER_BANDS)) == (water_counts.w % uint(WATER_LAYER_BANDS))) || snow_layer_swept(mapTexel); if (false == due) return; - snSlot = int(slot); - snMap = map; - snBig = (textureSize(raindropsatlas, 0).x >= 2048); - vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); - snow_layer_s s = snCompose(uv, span, max(rect.z / float(size.x), rect.w / float(size.y))); - uint index = water_layer_base() + 3u * texel; - water_cells[index] = packUnorm4x8(vec4(s.rgb, s.a)); - water_cells[index + 1u] = packSnorm4x8(vec4(s.n, s.tr * 2.0 - 1.0)); - water_cells[index + 2u] = packSnorm4x8(vec4(s.bend, s.bendA * 2.0 - 1.0, s.haze * 2.0 - 1.0)); + uint index = water_layer_base() + 4u * texel; + // nothing of the glass there or next to it (a texel on the edge of the glass takes the size of the glass beside it) + vec2 span; + uvec4 refs = uvec4(0u); + if (snSpan(slot, uv, span)) + { + snSlot = int(slot); + snMap = map; + snBig = (textureSize(raindropsatlas, 0).x >= 2048); + refs = snList(uv, span, max(rect.z / float(size.x), rect.w / float(size.y))); + } + water_cells[index] = refs.x; + water_cells[index + 1u] = refs.y; + water_cells[index + 2u] = refs.z; + water_cells[index + 3u] = refs.w; } diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index e5e8d604a..43f0c455f 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -11,12 +11,14 @@ // the blades wipe it as they wipe the rain (a wet trace stays), it melts at the warm glass, slush slides down. The renderer gives // the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. // -// The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen, laid together into -// a layer of the glass by water_snowlayer.comp (snow_sprites.glsl) when the snow under them changes, so the glass only reads it: +// The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen, laid at each pixel +// sharp from the atlas (snow_sprites.glsl). water_snowlayer.comp lists, for each texel of a layer of the glass (~1 mm), the +// sprites coming within it when the snow under them changes, so the glass lays only those instead of looking through every cell: // - the lumps, in nine grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, // size, the snow it takes); it comes when the snow around reaches that and stays as it is until the snow goes. The grids come -// one after the other as the snow piles up (all of them icy fleece, more and bigger; a lump of packed snow very rarely), each on the ones before, -// so the snow accumulates rather than changes, and covers the glass by 2-3 mm, small gaps left (the scene behind them blurred). In a heap they come sooner +// one after the other as the snow piles up (mostly icy fleece, more and bigger; now and then a lump of packed or wet snow), +// each on the ones before, so the snow accumulates rather than changes, and covers the glass by 2-3 mm, small gaps left (the +// scene behind them blurred). In a heap they come sooner // - dots and small puffs of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) // A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. // @@ -90,7 +92,8 @@ void main() Bgl *= invmax; vec4 tex_color = texture(diffuse, f_coord); // no discard: clean glass between faint dirt must still get snow and blur - // the snow laid together from the sprites (water_snowlayer.comp, a band of its rows every step and wherever a blade goes) + // the snow laid together from the sprites (listed by water_snowlayer.comp, a band of its rows every step and wherever a blade + // goes) vec3 snowRGB = vec3(0.0); float snowA = 0.0; vec3 snowN = vec3(0.0); @@ -99,26 +102,28 @@ void main() snSlot = int(param[2].z + 0.5) - 1; if ((snSlot >= 0) && (snSlot < WATER_SLOTS) && water_snow_map(uint(snSlot), snMap)) { - vec4 layerColour; - vec4 layerNormal; - vec4 layerBend; - if (water_layer_of(uint(snSlot))) + // the sprites coming within the texel of the layer at the pixel (water_snowlayer.comp) laid at the pixel, sharp from the + // atlas; a second glass of the snow in the cab (the layer goes to the first one) looks through all the cells around the + // pixel, as it was before the layer, slower but the same + snBig = (textureSize(raindropsatlas, 0).x >= 2048); + float pixelUV = max(length(duv1), length(duv2)); + snow_layer_s laid; + uvec4 refs; + vec2 centreUV; + vec2 span; + if (water_layer_refs(uint(snSlot), f_coord, refs, centreUV)) { - water_layer_at(uint(snSlot), f_coord, layerColour, layerNormal, layerBend); + snSpan(uint(snSlot), centreUV, span); + laid = snComposeRefs(f_coord, centreUV, span, pixelUV, refs); } else { - // a second glass of the snow in the cab (the layer goes to the first one): its snow laid at the pixel, as it was - // before the layer, slower but the same - snBig = (textureSize(raindropsatlas, 0).x >= 2048); - ivec2 texel = clamp(ivec2(floor(f_coord * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); - uint axis = (uint(snSlot) * uint(WATER_MAP * WATER_MAP) + uint(texel.y * WATER_MAP + texel.x)) * 2u; - vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); - snow_layer_s laid = snCompose(f_coord, span, max(length(duv1), length(duv2))); - layerColour = vec4(laid.rgb, laid.a); - layerNormal = vec4(laid.n, laid.tr); - layerBend = vec4(laid.bend, laid.bendA, laid.haze); + snSpan(uint(snSlot), f_coord, span); + laid = snCompose(f_coord, span, pixelUV); } + vec4 layerColour = vec4(laid.rgb, laid.a); + vec4 layerNormal = vec4(laid.n, laid.tr); + vec4 layerBend = vec4(laid.bend, laid.bendA, laid.haze); snowRGB = layerColour.rgb; snowA = layerColour.a; snowN = layerNormal.xyz; diff --git a/shaders/vk14/snow_sprites.glsl b/shaders/vk14/snow_sprites.glsl index a7291d671..9ab5e8066 100644 --- a/shaders/vk14/snow_sprites.glsl +++ b/shaders/vk14/snow_sprites.glsl @@ -136,54 +136,6 @@ vec3 snTone(vec4 q, float random) return tone * mix(vec3(1.0), vec3(0.88, 0.91, 0.94), smoothstep(0.3, 0.8, snWetness(q))); } -// the dots and the drops, in cells of snow_flake_cell metres of the glass: in many of the cells holding a little dry snow a dot -// or a small puff sits between the lumps, in some of those holding only water a drop of a melted flake -void snFlakes(vec2 span, float pixelUV, inout sprite_acc acc) -{ - vec2 perUV = span / snow_flake_cell; // cells in a unit of the uv - vec2 p = snUV * perUV; - ivec2 here = ivec2(floor(p)); - for (int oy = 1; oy >= -1; --oy) - { - for (int ox = 1; ox >= -1; --ox) - { - ivec2 cell = here + ivec2(ox, oy); - uint seed = Hash(uvec3(uvec2(cell + 8192), 17u + 7u * uint(snSlot))); - vec2 centre = vec2(cell) + 0.15 + 0.7 * vec2(RandF(seed), RandF(seed)); - // every draw of the cell first, in the order they always came, so the flake doesn't change: the map is the costly - // part, so it is read only for a flake which, as big as it gets, covers the pixel - float chance = RandF(seed); - float ang = RandF(seed) * 6.2831853; - vec2 rot = vec2(cos(ang), sin(ang)); - float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; - float kind = RandF(seed); - float random = RandF(seed); - float sizeDraw = mix(0.6, 1.0, RandF(seed)); - vec2 local; - if (false == snLocal(p, centre, sizeDraw * 1.4, vec2(1.0), rot, flip, 1.0, local)) - continue; - vec4 q = water_snow_at(uint(snSlot), snMap, centre / perUV); - bool drop = (q.x < 0.05) && (q.y > 0.03); - bool crystal = (q.x >= 0.05); - if ((false == drop) && (false == crystal)) - continue; - if (chance > (drop ? snow_drops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) - continue; - float size = sizeDraw * (drop ? mix(0.7, 1.4, smoothstep(0.03, 0.3, q.y)) : 1.0); - if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, 1.0, local)) - continue; - int tile = TILE_DROP; - float alpha = smoothstep(0.03, 0.1, q.y); - if (crystal) - { - tile = 2 + min(int(kind * 2.0), 1); // small icy puffs - alpha = snow_thin; - } - snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0, acc); - } - } -} - // how much a cell of the lumps lies in a heap: the snow landing side by side runs together, so the lumps come in heaps with // barer glass between them; a random number for every few cells, blended between them (the same for every pixel of the cell) float snHeap(ivec2 cell) @@ -215,58 +167,106 @@ struct lump_grid float share; // the share of its cells having a lump at all (1: all of them) }; +// the grids of the lumps, coming one after the other as the snow piles up, each on the ones before, in the order they are laid +// (front to back, the top one first): mostly icy fleece (the puffs and clumps of the first two rows of the atlas, tiles 0-7), +// more and bigger, closing the glass by 2-3 mm; now and then a single lump on top: packed snow (tiles 10-13) or, more rarely, a +// wet one with its film (tiles 8, 9) +const int SN_GRIDS = 9; +const lump_grid sn_grids[SN_GRIDS] = lump_grid[SN_GRIDS]( + lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 8, 6, 0.12), + lump_grid(vec2(0.75), 251u, vec2(1.4, 2.8), vec2(2.0, 3.0), 0, 8, 1.0), + lump_grid(vec2(0.0, 0.5), 233u, vec2(1.2, 2.4), vec2(2.0, 3.0), 0, 8, 1.0), + lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.0), vec2(2.0, 3.0), 0, 8, 1.0), + lump_grid(vec2(0.75, 0.25), 151u, vec2(0.7, 1.6), vec2(1.8, 2.8), 4, 4, 1.0), + lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.8, 2.8), 4, 4, 1.0), + lump_grid(vec2(0.25), 97u, vec2(0.2, 0.9), vec2(1.4, 2.4), 0, 4, 1.0), + lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(1.4, 2.4), 0, 4, 1.0), + lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(1.2, 2.0), 0, 4, 1.0)); + const float SN_COVERED = 0.998; // the snow over the pixel covering it: the sprites under it are not looked at -void snLumps(vec2 span, float pixelUV, lump_grid grid, inout sprite_acc acc) +// the dots and the drops, in cells of snow_flake_cell metres of the glass: in many of the cells holding a little dry snow a dot +// or a small puff sits between the lumps, in some of those holding only water a drop of a melted flake. the flake of a Cell at P +// (the place in cells): true when it is there and comes within Reach (cells) of P; laid over Acc where it covers P +bool snFlakeCell(vec2 p, ivec2 cell, vec2 perUV, float pixelUV, float reach, inout sprite_acc acc) { - if (acc.a >= SN_COVERED) - return; // the grids over this one cover the pixel - vec2 perUV = span / snow_lump_cell; - vec2 p = snUV * perUV + grid.shift; - ivec2 here = ivec2(floor(p)); - for (int oy = 1; oy >= -1; --oy) + uint seed = Hash(uvec3(uvec2(cell + 8192), 17u + 7u * uint(snSlot))); + vec2 centre = vec2(cell) + 0.15 + 0.7 * vec2(RandF(seed), RandF(seed)); + // every draw of the cell first, in the order they always came, so the flake doesn't change: the map is the costly part, so + // it is read only for a flake which, as big as it gets, covers the pixel + float chance = RandF(seed); + float ang = RandF(seed) * 6.2831853; + vec2 rot = vec2(cos(ang), sin(ang)); + float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; + float kind = RandF(seed); + float random = RandF(seed); + float sizeDraw = mix(0.6, 1.0, RandF(seed)); + vec2 local; + if (false == snLocal(p, centre, sizeDraw * 1.4 + 2.0 * reach, vec2(1.0), rot, flip, 1.0, local)) + return false; + vec4 q = water_snow_at(uint(snSlot), snMap, centre / perUV); + bool drop = (q.x < 0.05) && (q.y > 0.03); + bool crystal = (q.x >= 0.05); + if ((false == drop) && (false == crystal)) + return false; + if (chance > (drop ? snow_drops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) + return false; + float size = sizeDraw * (drop ? mix(0.7, 1.4, smoothstep(0.03, 0.3, q.y)) : 1.0); + if (false == snLocal(p, centre, size + 2.0 * reach, vec2(1.0), rot, flip, 1.0, local)) + return false; + if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, 1.0, local)) + return true; + int tile = (kind < 0.25) ? 14 : TILE_DROP; // a drop, now and then a wet lump with its film + float alpha = smoothstep(0.03, 0.1, q.y); + if (crystal) { - for (int ox = 1; ox >= -1; --ox) - { - if (acc.a >= SN_COVERED) - return; - ivec2 cell = here + ivec2(ox, oy); - uint seed = Hash(uvec3(uvec2(cell + 4096), grid.salt + 7u * uint(snSlot))); - vec2 centre = vec2(cell) + 0.1 + 0.8 * vec2(RandF(seed), RandF(seed)); - // every draw of the cell first, in the order they always came, so the lump doesn't change: the map is the costly - // part, so it is read only for a lump which, as big as it grows, covers the pixel (most of the nine cells don't) - float needsDraw = RandF(seed); - if (RandF(seed) >= grid.share) - continue; - float ang = RandF(seed) * 6.2831853; - vec2 rot = vec2(cos(ang), sin(ang)); - float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; - int tile = grid.tiles + min(int(RandF(seed) * float(grid.count)), grid.count - 1); - float random = RandF(seed); - float aniso = mix(0.8, 1.0, RandF(seed)); - float sizeDraw = mix(grid.size.x, grid.size.y, RandF(seed)); - vec2 local; - if (false == snLocal(p, centre, sizeDraw * snow_lump_grow.y, vec2(1.0), rot, flip, aniso, local)) - continue; - // the snow it takes, sooner in a heap - float needs = mix(grid.snow.x, grid.snow.y, needsDraw) * mix(1.4, 0.6, snHeap(cell)); - vec4 q = water_snow_at(uint(snSlot), snMap, (centre - grid.shift) / perUV); - if (q.x <= needs) - continue; - float size = sizeDraw * mix(snow_lump_grow.x, snow_lump_grow.y, smoothstep(needs, needs * 2.0 + 0.2, q.x)); - if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, aniso, local)) - continue; - // fading in over the first snow (no flicker on the edge), opaque when thick; the thick snow bends nothing - float deep = smoothstep(snow_cover * 3.0, snow_deep, q.x); - float alpha = smoothstep(needs, needs + 0.04, q.x) * mix(snow_ice, 1.0, deep); - snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0 - deep, acc); - } + tile = min(int(kind * 4.0), 3); // small icy puffs (the first row of the atlas) + alpha = snow_thin; } + snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0, acc); + return true; } -// the snow of the glass laid together at UV: the flakes over the lumps (water_snowlayer.comp bakes it into the layer of the glass, -// mat_snow_windscreen.frag reads it). Span: metres of the glass in a unit of its uv; PixelUV: the uv a texel of the layer covers -// (the level of the atlas). snSlot, snMap and snBig set before +// the lump of a Cell of a Grid at P (the place in the cells of the grid, shifted): true when it is there and comes within Reach +// (cells) of P; laid over Acc where it covers P +bool snLumpCell(vec2 p, ivec2 cell, vec2 perUV, lump_grid grid, float pixelUV, float reach, inout sprite_acc acc) +{ + uint seed = Hash(uvec3(uvec2(cell + 4096), grid.salt + 7u * uint(snSlot))); + vec2 centre = vec2(cell) + 0.1 + 0.8 * vec2(RandF(seed), RandF(seed)); + // every draw of the cell first, in the order they always came, so the lump doesn't change: the map is the costly part, so it + // is read only for a lump which, as big as it grows, covers the pixel (most of the nine cells don't) + float needsDraw = RandF(seed); + if (RandF(seed) >= grid.share) + return false; + float ang = RandF(seed) * 6.2831853; + vec2 rot = vec2(cos(ang), sin(ang)); + float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; + int tile = grid.tiles + min(int(RandF(seed) * float(grid.count)), grid.count - 1); + float random = RandF(seed); + float aniso = mix(0.8, 1.0, RandF(seed)); + float sizeDraw = mix(grid.size.x, grid.size.y, RandF(seed)); + vec2 local; + if (false == snLocal(p, centre, sizeDraw * snow_lump_grow.y + 2.0 * reach, vec2(1.0), rot, flip, aniso, local)) + return false; + // the snow it takes, sooner in a heap + float needs = mix(grid.snow.x, grid.snow.y, needsDraw) * mix(1.4, 0.6, snHeap(cell)); + vec4 q = water_snow_at(uint(snSlot), snMap, (centre - grid.shift) / perUV); + if (q.x <= needs) + return false; + float size = sizeDraw * mix(snow_lump_grow.x, snow_lump_grow.y, smoothstep(needs, needs * 2.0 + 0.2, q.x)); + if (false == snLocal(p, centre, size + 2.0 * reach, vec2(1.0), rot, flip, aniso, local)) + return false; + if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, aniso, local)) + return true; + // fading in over the first snow (no flicker on the edge), opaque when thick; the thick snow bends nothing + float deep = smoothstep(snow_cover * 3.0, snow_deep, q.x); + float alpha = smoothstep(needs, needs + 0.04, q.x) * mix(snow_ice, 1.0, deep); + snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0 - deep, acc); + return true; +} + +// the snow of the glass laid together: the flakes over the lumps, as water_snowlayer.comp lists them for the texels of the layer +// and mat_snow_windscreen.frag lays them at its pixels (or, for a glass without the layer, all of them at its pixels) struct snow_layer_s { vec3 rgb; // premultiplied @@ -278,27 +278,8 @@ struct snow_layer_s float haze; // the blur of the picture behind the thin snow }; -snow_layer_s snCompose(vec2 uv, vec2 span, float pixelUV) +snow_layer_s snFinish(sprite_acc flakes, sprite_acc layer) { - snUV = uv; - snBend = vec2(0.0); - snBendA = 0.0; - sprite_acc layer = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); - sprite_acc flakes = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); - // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before: all of them icy - // fleece (small puffs and icy clumps, tiles 2-5), more and bigger, closing the glass by 2-3 mm; now and then a single - // lump of packed snow on top. laid front to back: the flakes, the single packed lumps, then the grids from the top one - // down, so a texel stops looking once the snow over it covers it - snFlakes(span, pixelUV, flakes); - snLumps(span, pixelUV, lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 12, 2, 0.03), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.75), 251u, vec2(1.4, 2.8), vec2(2.0, 3.0), 4, 2, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.0, 0.5), 233u, vec2(1.2, 2.4), vec2(2.0, 3.0), 4, 2, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.0), vec2(2.0, 3.0), 4, 2, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.75, 0.25), 151u, vec2(0.7, 1.6), vec2(1.8, 2.8), 4, 2, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.8, 2.8), 4, 2, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.25), 97u, vec2(0.2, 0.9), vec2(1.4, 2.4), 2, 4, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(1.4, 2.4), 2, 4, 1.0), layer); - snLumps(span, pixelUV, lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(1.2, 2.0), 2, 4, 1.0), layer); snow_layer_s s; // the flakes over the layer s.rgb = flakes.rgb + layer.rgb * (1.0 - flakes.a); @@ -312,4 +293,147 @@ snow_layer_s snCompose(vec2 uv, vec2 span, float pixelUV) return s; } +// the snow of the glass laid together at UV from all the cells around it. Span: metres of the glass in a unit of its uv; +// PixelUV: the uv a pixel covers (the level of the atlas). snSlot, snMap and snBig set before +snow_layer_s snCompose(vec2 uv, vec2 span, float pixelUV) +{ + snUV = uv; + snBend = vec2(0.0); + snBendA = 0.0; + sprite_acc layer = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + sprite_acc flakes = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + // laid front to back: the flakes, then the grids from the top one down, so a pixel stops looking once the snow over it covers + // it + vec2 perF = span / snow_flake_cell; + vec2 pF = uv * perF; + ivec2 hereF = ivec2(floor(pF)); + for (int oy = 1; oy >= -1; --oy) + for (int ox = 1; ox >= -1; --ox) + snFlakeCell(pF, hereF + ivec2(ox, oy), perF, pixelUV, 0.0, flakes); + vec2 perL = span / snow_lump_cell; + for (int g = 0; g < SN_GRIDS; ++g) + { + vec2 pL = uv * perL + sn_grids[g].shift; + ivec2 hereL = ivec2(floor(pL)); + for (int k = 0; k < 9; ++k) + { + if (layer.a >= SN_COVERED) + return snFinish(flakes, layer); // the grids over this one cover the pixel + snLumpCell(pL, hereL + ivec2(1 - k % 3, 1 - k / 3), perL, sn_grids[g], pixelUV, 0.0, layer); + } + } + return snFinish(flakes, layer); +} + +// the layer of the snow of a glass (water_snowlayer.comp writes it, mat_snow_windscreen.frag reads it) holds for each of its +// texels (~1 mm of the glass) the sprites coming within it, in the order they are laid: up to SN_REFS bytes in four uint, each +// 1 + the list (0 the flakes, 1 .. SN_GRIDS the grids of the lumps) times 16 + the cell around the texel (0 .. 8: 1 - the column +// offset + 3 * (1 - the row offset)), 0 after the last one (a layer cleared to zeros lists nothing). the glass lays only those at +// its pixels, sharp from the atlas as when it laid all of the cells around itself, at a fraction of the cost +const int SN_REFS = 16; +// the sprites over a texel covering it on the whole (the level of the atlas the size of the texel): those under it are left out +const float SN_LIST_COVERED = 0.97; + +void snRef(uint ref, inout uvec4 refs, inout int count) +{ + if (count >= SN_REFS) + return; + uint shift = 8u * uint(count & 3); + refs[count >> 2] = (refs[count >> 2] & ~(255u << shift)) | ((ref + 1u) << shift); + ++count; +} + +// the sprites of the texel of the layer centred at UV (PixelUV its size in the uv), as the layer holds them +uvec4 snList(vec2 uv, vec2 span, float pixelUV) +{ + snUV = uv; + snBend = vec2(0.0); + snBendA = 0.0; + uvec4 refs = uvec4(0u); + int count = 0; + sprite_acc layer = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + sprite_acc flakes = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + // the sprites coming within the corners of the texel (cells of the list), as big as they grow before it is listed anew + float half_diagonal = 0.75 * pixelUV; + vec2 perF = span / snow_flake_cell; + vec2 pF = uv * perF; + ivec2 hereF = ivec2(floor(pF)); + float reachF = half_diagonal * max(perF.x, perF.y) * 1.25; + for (int k = 0; k < 9; ++k) + { + if (snFlakeCell(pF, hereF + ivec2(1 - k % 3, 1 - k / 3), perF, pixelUV, reachF, flakes)) + snRef(uint(k), refs, count); + } + vec2 perL = span / snow_lump_cell; + float reachL = half_diagonal * max(perL.x, perL.y) * 1.25 + 0.05; + for (int g = 0; g < SN_GRIDS; ++g) + { + if (layer.a >= SN_LIST_COVERED) + break; // the grids over this one cover the texel + vec2 pL = uv * perL + sn_grids[g].shift; + ivec2 hereL = ivec2(floor(pL)); + for (int k = 0; k < 9; ++k) + { + if (snLumpCell(pL, hereL + ivec2(1 - k % 3, 1 - k / 3), perL, sn_grids[g], pixelUV, reachL, layer)) + snRef(uint(16 * (g + 1) + k), refs, count); + } + } + return refs; +} + +// the snow of the glass laid together at UV from the sprites Refs of the texel of the layer centred at CentreUV (the cells +// counted around that). Span: metres of the glass in a unit of its uv at the texel; PixelUV: the uv a pixel covers +snow_layer_s snComposeRefs(vec2 uv, vec2 centreUV, vec2 span, float pixelUV, uvec4 refs) +{ + snUV = uv; + snBend = vec2(0.0); + snBendA = 0.0; + sprite_acc layer = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + sprite_acc flakes = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + vec2 perF = span / snow_flake_cell; + vec2 perL = span / snow_lump_cell; + for (int r = 0; r < SN_REFS; ++r) + { + uint ref = (refs[r >> 2] >> (8u * uint(r & 3))) & 255u; + if (ref == 0u) + break; + --ref; + int list = int(ref >> 4u); + int k = int(ref & 15u); + ivec2 offset = ivec2(1 - k % 3, 1 - k / 3); + if ((list == 0) && (k < 9)) + { + snFlakeCell(uv * perF, ivec2(floor(centreUV * perF)) + offset, perF, pixelUV, 0.0, flakes); + continue; + } + if ((list > SN_GRIDS) || (k >= 9) || (layer.a >= SN_COVERED)) + continue; // nothing laid, or the grids over this one cover the pixel + lump_grid grid = sn_grids[list - 1]; + ivec2 here = ivec2(floor(centreUV * perL + grid.shift)); + snLumpCell(uv * perL + grid.shift, here + offset, perL, grid, pixelUV, 0.0, layer); + } + return snFinish(flakes, layer); +} + +// the metres of the glass in a unit of its uv at UV, from the texel of its map there or, at the edge of the glass, the nearest +// one next to it the glass is on; false when there is none +bool snSpan(uint slot, vec2 uv, out vec2 span) +{ + span = vec2(0.05); + ivec2 at = clamp(ivec2(floor(uv * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); + // the texel itself first, then the ones beside it, then the corners + const ivec2 near[9] = ivec2[9](ivec2(0), ivec2(1, 0), ivec2(-1, 0), ivec2(0, 1), ivec2(0, -1), ivec2(1), ivec2(-1, 1), ivec2(1, -1), ivec2(-1)); + for (int k = 0; k < 9; ++k) + { + ivec2 t = clamp(at + near[k], ivec2(0), ivec2(WATER_MAP - 1)); + uint axis = (slot * uint(WATER_MAP * WATER_MAP) + uint(t.y * WATER_MAP + t.x)) * 2u; + if (water_axes[axis].w > 0.0) + { + span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); + return true; + } + } + return false; +} + #endif diff --git a/shaders/vk14/water.glsl b/shaders/vk14/water.glsl index d2be3c053..2bfe62a6a 100644 --- a/shaders/vk14/water.glsl +++ b/shaders/vk14/water.glsl @@ -75,9 +75,8 @@ vec4 water_snow_texel(uint slot, uint map, ivec2 texel) // the snow of a glass laid together (water_snowlayer.comp, read by mat_snow_windscreen.frag), after the maps of the snow: eight // uint of every glass (the rectangle of its uv the layer takes: the corner and the size, floats; the texels of the layer across // and down, 0 when the glass has no layer: the cab has one, for its first glass of the snow), then the layer, WATER_LAYER_TEXELS -// texels of three uint each: the colour -// (premultiplied, linear) and the cover; the normal of the sprites (tangent space, premultiplied) and their translucency; the bend -// of the picture behind (weighted), its weight, and the haze of the thin snow +// texels of four uint each: the sprites of the snow coming within the texel, in the order they are laid (snow_sprites.glsl, +// snList) void water_layer_rect(uint slot, out vec4 rect, out uvec2 size) { uint info = water_snow_base(0u, 2u) + slot * 8u; @@ -99,35 +98,24 @@ bool water_layer_of(uint slot) return (size.x > 0u) && (size.y > 0u) && all(greaterThan(rect.zw, vec2(0.0))); } -// the laid snow of a glass at UV, filtered between the texels: Colour (rgb, cover), Normal (xyz, translucency), Bend (xy, its -// weight, the haze); nothing outside the layer -void water_layer_at(uint slot, vec2 uv, out vec4 colour, out vec4 normal, out vec4 bend) +// the sprites of the snow of a glass at UV, as its layer holds them for the texel there (Refs, see snow_sprites.glsl), and the +// centre of that texel (CentreUV); false outside the layer +bool water_layer_refs(uint slot, vec2 uv, out uvec4 refs, out vec2 centreUV) { - colour = vec4(0.0); - normal = vec4(0.0); - bend = vec4(0.0); + refs = uvec4(0u); + centreUV = uv; vec4 rect; uvec2 size; water_layer_rect(slot, rect, size); if ((size.x == 0u) || (size.y == 0u) || any(lessThanEqual(rect.zw, vec2(0.0)))) - return; - vec2 p = (uv - rect.xy) / rect.zw * vec2(size) - 0.5; - ivec2 i = ivec2(floor(p)); - vec2 f = p - vec2(i); - uint base = water_layer_base(); - for (int k = 0; k < 4; ++k) - { - ivec2 t = i + ivec2(k & 1, k >> 1); - if (any(lessThan(t, ivec2(0))) || any(greaterThanEqual(t, ivec2(size)))) - continue; - float w = ((k & 1) == 1 ? f.x : 1.0 - f.x) * ((k >> 1) == 1 ? f.y : 1.0 - f.y); - uint index = base + 3u * (uint(t.y) * size.x + uint(t.x)); - colour += unpackUnorm4x8(water_cells[index]) * w; - normal += unpackSnorm4x8(water_cells[index + 1u]) * w; - bend += unpackSnorm4x8(water_cells[index + 2u]) * w; - } - normal.w = normal.w * 0.5 + 0.5; - bend.zw = bend.zw * 0.5 + 0.5; + return false; + ivec2 t = ivec2(floor((uv - rect.xy) / rect.zw * vec2(size))); + if (any(lessThan(t, ivec2(0))) || any(greaterThanEqual(t, ivec2(size)))) + return false; + centreUV = rect.xy + (vec2(t) + 0.5) / vec2(size) * rect.zw; + uint index = water_layer_base() + 4u * (uint(t.y) * size.x + uint(t.x)); + refs = uvec4(water_cells[index], water_cells[index + 1u], water_cells[index + 2u], water_cells[index + 3u]); + return true; } // the latest map of the snow of a glass; false when there's none yet diff --git a/shaders/vk14/water_snowlayer.comp b/shaders/vk14/water_snowlayer.comp index a69efdf1f..264e5881f 100644 --- a/shaders/vk14/water_snowlayer.comp +++ b/shaders/vk14/water_snowlayer.comp @@ -1,11 +1,11 @@ #version 460 core #define STAGE_COMPUTE 1 -// the snow on the windscreens (water_sim.glsl, water.glsl, snow_sprites.glsl): the snow of a glass of the snow laid together -// from the sprites of its atlas into its layer, which mat_snow_windscreen.frag reads (the glass only reads it: laying the nine -// grids of the lumps at every pixel of the glass in every frame cost as much as the rest of the frame). a thread per texel of -// the layer (over the rectangle of the uv the glass takes, ~1 mm a texel), the glass is water_counts.z. the snow under a lump -// changes slowly, so a band of every WATER_LAYER_BANDS-th row is -// laid anew in a step (water_counts.w the step), and at once wherever a blade went over the glass in the step +// the snow on the windscreens (water_sim.glsl, water.glsl, snow_sprites.glsl): the sprites of the snow of a glass coming within +// each texel of its layer listed, which mat_snow_windscreen.frag lays at its pixels, sharp from the atlas (looking through the +// nine cells of the ten lists at every pixel of the glass in every frame cost as much as the rest of the frame). a thread per +// texel of the layer (over the rectangle of the uv the glass takes, ~1 mm a texel), the glass is water_counts.z. the snow under +// a lump changes slowly, so a band of every WATER_LAYER_BANDS-th row is listed anew in a step (water_counts.w the step), and at +// once wherever a blade went over the glass in the step // none of the pass set: everything the kernel reads is pushed with its dispatch (set COMPUTE_SET, water_sim.glsl) #define LAYOUT_UI 1 @@ -60,21 +60,23 @@ void main() vec2 uv = rect.xy + (vec2(at) + 0.5) / vec2(size) * rect.zw; ivec2 mapAt = clamp(ivec2(floor(uv * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); uint mapTexel = slot * uint(WATER_MAP * WATER_MAP) + uint(mapAt.y * WATER_MAP + mapAt.x); - uint axis = mapTexel * 2u; - // nothing of the glass there (the glass reads its layer only where it is, filtered next to it) - if (water_axes[axis].w <= 0.0) - return; // a band of the rows in a step (the snow builds up and melts slowly), and wherever a blade went bool due = ((uint(at.y) % uint(WATER_LAYER_BANDS)) == (water_counts.w % uint(WATER_LAYER_BANDS))) || snow_layer_swept(mapTexel); if (false == due) return; - snSlot = int(slot); - snMap = map; - snBig = (textureSize(raindropsatlas, 0).x >= 2048); - vec2 span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); - snow_layer_s s = snCompose(uv, span, max(rect.z / float(size.x), rect.w / float(size.y))); - uint index = water_layer_base() + 3u * texel; - water_cells[index] = packUnorm4x8(vec4(s.rgb, s.a)); - water_cells[index + 1u] = packSnorm4x8(vec4(s.n, s.tr * 2.0 - 1.0)); - water_cells[index + 2u] = packSnorm4x8(vec4(s.bend, s.bendA * 2.0 - 1.0, s.haze * 2.0 - 1.0)); + uint index = water_layer_base() + 4u * texel; + // nothing of the glass there or next to it (a texel on the edge of the glass takes the size of the glass beside it) + vec2 span; + uvec4 refs = uvec4(0u); + if (snSpan(slot, uv, span)) + { + snSlot = int(slot); + snMap = map; + snBig = (textureSize(raindropsatlas, 0).x >= 2048); + refs = snList(uv, span, max(rect.z / float(size.x), rect.w / float(size.y))); + } + water_cells[index] = refs.x; + water_cells[index + 1u] = refs.y; + water_cells[index + 2u] = refs.z; + water_cells[index + 3u] = refs.w; } From c4d32ef85fe76cd2b0af9286769a12b6a21acc83 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 21:34:50 +0100 Subject: [PATCH 102/123] Windscreen bugs: counted from none once the rain or the snow stops, none in winter [skip ci] The insects were counted all the time the vehicle drove, so a glass turning to mat_bugs_windscreen after snow or rain (or after winter) showed at once all it had met meanwhile. Now the count stays at none in winter and while it rains or snows (the rain or the snow washes them off), and what the blades left of them before is forgotten. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- rendering/opengl46/opengl46renderer.cpp | 15 +++++++++++++-- rendering/vulkan14/vulkan14frame.cpp | 15 +++++++++++++-- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index a160b32ea..ba087821b 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -1712,8 +1712,19 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) m_wiperbugs = 0.0; } // the insects the vehicle meets (mat_bugs_windscreen): none below 20 km/h, above it the more the faster, counted in seconds of - // driving at 100 km/h - if (owner != nullptr) + // driving at 100 km/h. none in winter, and the rain or the snow washes them off: once it stops (and out of winter) the glass + // gets them anew from none, and what the blades left of them before is forgotten + auto const insects{(Global.Season != "winter:") && (Global.Weather != "rain:") && (Global.Weather != "snow:")}; + if (false == insects) + { + if (m_wiperbugs > 0.0) + { + scene_ubs.wiper_bugs_out = glm::vec4{-1.}; + scene_ubs.wiper_bugs_return = glm::vec4{-1.}; + } + m_wiperbugs = 0.0; + } + else if (owner != nullptr) m_wiperbugs += Timer::GetDeltaTime() * std::max(std::abs(owner->MoverParameters->V) * 3.6 - 20.0, 0.0) / 80.0; scene_ubs.rain_wind.w = static_cast(m_wiperbugs); // the rain the glass meets (mat_rain_windscreen): counted in seconds of the heaviest rain standing still, more at speed (the diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index f44c048b1..eb8527b37 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -1589,8 +1589,19 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) m_wiperbugs = 0.0; } // the insects the vehicle meets (mat_bugs_windscreen): none below 20 km/h, above it the more the faster, counted in seconds of - // driving at 100 km/h - if (owner != nullptr) + // driving at 100 km/h. none in winter, and the rain or the snow washes them off: once it stops (and out of winter) the glass + // gets them anew from none, and what the blades left of them before is forgotten + auto const insects{(Global.Season != "winter:") && (Global.Weather != "rain:") && (Global.Weather != "snow:")}; + if (false == insects) + { + if (m_wiperbugs > 0.0) + { + scene_ubs.wiper_bugs_out = glm::vec4{-1.}; + scene_ubs.wiper_bugs_return = glm::vec4{-1.}; + } + m_wiperbugs = 0.0; + } + else if (owner != nullptr) m_wiperbugs += Timer::GetDeltaTime() * std::max(std::abs(owner->MoverParameters->V) * 3.6 - 20.0, 0.0) / 80.0; scene_ubs.rain_wind.w = static_cast(m_wiperbugs); // the rain the glass meets (mat_rain_windscreen): counted in seconds of the heaviest rain standing still, more at speed (the From 26ed8650ff40b878cdebaf3e814fb074b356b7ee Mon Sep 17 00:00:00 2001 From: lcddisplay Date: Sun, 22 Nov 2026 10:08:37 +0100 Subject: [PATCH 103/123] Windscreen: rain rivulets run down the glass in the world, the snow as dense as before [skip ci] - The rivulets of the weight (mat_rain_windscreen.frag) run down the glass in the world whichever way its texture lies on it: their layer is turned by a quarter turn at a time to the gravity on the glass in its UV (no turn on a glass mapped upright, so it looks the same there). - The grids of the lumps of the snow use the dense tiles again (2-5) as before the change of the tiles, the packed and wet lumps on 3% of the cells; the small clump, the dots and the scattered crystals (0, 1, 6, 7) only among the flakes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_rain_windscreen.frag | 26 ++++++++++++++++++++------ shaders/ogl46/snow_sprites.glsl | 26 +++++++++++++------------- shaders/vk14/mat_rain_windscreen.frag | 26 ++++++++++++++++++++------ shaders/vk14/snow_sprites.glsl | 26 +++++++++++++------------- 4 files changed, 66 insertions(+), 38 deletions(-) diff --git a/shaders/ogl46/mat_rain_windscreen.frag b/shaders/ogl46/mat_rain_windscreen.frag index ca68ca98e..9846a6a0f 100644 --- a/shaders/ogl46/mat_rain_windscreen.frag +++ b/shaders/ogl46/mat_rain_windscreen.frag @@ -345,6 +345,10 @@ vec2 wsFromLayer(vec2 p) // the layers: 0 gravity, 1 air. WindShare: how much the air drives the water (0 standing still), WindCos / WindSin: the turn // of the layer of the air float wsWindShare = 0.0; +// the layer of the weight turned by a quarter turn at a time so that its rivulets run down the glass in the world, whichever +// way the texture lies on it (an island of the UV turned or upside down) +float wsGravCos = 1.0; +float wsGravSin = 0.0; float wsWindCos = 1.0; float wsWindSin = 0.0; void wsSetLayer(int layer) @@ -354,8 +358,8 @@ void wsSetLayer(int layer) wsLayerDensity = 1.0 - wsWindShare; wsLayerIndex = 0; wsLayerHead = 1.0; - wsLayerCos = 1.0; - wsLayerSin = 0.0; + wsLayerCos = wsGravCos; + wsLayerSin = wsGravSin; wsLayerVaried = false; } else @@ -554,8 +558,9 @@ void drawRivulet(inout Hit hit, Riv r, vec2 sUVr, vec2 rd1, vec2 rd2) float wsKept(vec2 cg, float rad, float sCW, float sCH, float gridSize) { wsSetLayer(0); - Riv rv = getRiv(floor(cg / vec2(sCW, sCH)), sCW, sCH, gridSize); - float kept = 1.0 - streak_sweep * rivSwept(rv, cg, rad); + vec2 cl = wsToLayer(cg); + Riv rv = getRiv(floor(cl / vec2(sCW, sCH)), sCW, sCH, gridSize); + float kept = 1.0 - streak_sweep * rivSwept(rv, cl, rad); if (wsWindShare > 0.001) { wsSetLayer(1); @@ -660,6 +665,14 @@ void main() // to the glass UV (v up) through the tangent frame of the texture vec2 gravG = vec2(dot(wsGrav, Tgl), dot(wsGrav, Bgl) * flipS); vec2 flowG = vec2(dot(wsFlowDir, Tgl), dot(wsFlowDir, Bgl) * flipS); + if (dot(gravG, gravG) > 1e-8) + { + // down the glass in its UV, to the nearest quarter turn (a finer turn would break the rivulets at the seams where a curved + // glass bends); none on a glass lying flat + float turn = round(atan(gravG.x, -gravG.y) / 1.5707963) * 1.5707963; + wsGravCos = round(cos(turn)); + wsGravSin = round(sin(turn)); + } wsSpeed = smoothstep(0.3, 1.2, wsDrag); // 0 standing still .. 1 at speed (haze, drops) wsWindShare = smoothstep(0.5, 1.3, wsDrag); // how much the air drives the rivulets if (wsWindShare > 0.0) @@ -694,7 +707,8 @@ void main() float sCW = streak_cell / gridSize; float sCH = streak_run / gridSize; vec2 sUVg = vec2(f_coord.x, (STREAK_FLIP_Y != 0) ? 1.0 - f_coord.y : f_coord.y); // glass UV, v up - vec2 sCell = floor(sUVg / vec2(sCW, sCH)); + vec2 sUVl = wsToLayer(sUVg); // the same in the layer of the weight (down: -v) + vec2 sCell = floor(sUVl / vec2(sCW, sCH)); bool sweepOn = streak_sweep > 0.0 && streak_density > 0.0 && (wind_streaks > 0.0 || wsWindShare < 1.0) && (WS_PROFILE != 2); if ((rain_state.y > 0.001) && (WS_PROFILE != 5)) @@ -835,7 +849,7 @@ void main() // =================================================================== #if WS_PROFILE != 2 wsSetLayer(0); - drawRivulet(hit, getRiv(sCell, sCW, sCH, gridSize), sUVg, wsRd1, wsRd2); + drawRivulet(hit, getRiv(sCell, sCW, sCH, gridSize), sUVl, wsToLayerDir(wsRd1), wsToLayerDir(wsRd2)); if (wsWindShare > 0.001) { for (int wl = 1; wl <= wind_layers; ++wl) diff --git a/shaders/ogl46/snow_sprites.glsl b/shaders/ogl46/snow_sprites.glsl index 9ab5e8066..b89bd2ebe 100644 --- a/shaders/ogl46/snow_sprites.glsl +++ b/shaders/ogl46/snow_sprites.glsl @@ -168,20 +168,19 @@ struct lump_grid }; // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before, in the order they are laid -// (front to back, the top one first): mostly icy fleece (the puffs and clumps of the first two rows of the atlas, tiles 0-7), -// more and bigger, closing the glass by 2-3 mm; now and then a single lump on top: packed snow (tiles 10-13) or, more rarely, a -// wet one with its film (tiles 8, 9) +// (front to back, the top one first): all of them icy fleece (the dense puffs and clumps, tiles 2-5), more and bigger, closing +// the glass by 2-3 mm; now and then a single lump on top: packed snow (tiles 10-13) or a wet one with its film (8, 9) const int SN_GRIDS = 9; const lump_grid sn_grids[SN_GRIDS] = lump_grid[SN_GRIDS]( - lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 8, 6, 0.12), - lump_grid(vec2(0.75), 251u, vec2(1.4, 2.8), vec2(2.0, 3.0), 0, 8, 1.0), - lump_grid(vec2(0.0, 0.5), 233u, vec2(1.2, 2.4), vec2(2.0, 3.0), 0, 8, 1.0), - lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.0), vec2(2.0, 3.0), 0, 8, 1.0), - lump_grid(vec2(0.75, 0.25), 151u, vec2(0.7, 1.6), vec2(1.8, 2.8), 4, 4, 1.0), - lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.8, 2.8), 4, 4, 1.0), - lump_grid(vec2(0.25), 97u, vec2(0.2, 0.9), vec2(1.4, 2.4), 0, 4, 1.0), - lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(1.4, 2.4), 0, 4, 1.0), - lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(1.2, 2.0), 0, 4, 1.0)); + lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 8, 6, 0.03), + lump_grid(vec2(0.75), 251u, vec2(1.4, 2.8), vec2(2.0, 3.0), 4, 2, 1.0), + lump_grid(vec2(0.0, 0.5), 233u, vec2(1.2, 2.4), vec2(2.0, 3.0), 4, 2, 1.0), + lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.0), vec2(2.0, 3.0), 4, 2, 1.0), + lump_grid(vec2(0.75, 0.25), 151u, vec2(0.7, 1.6), vec2(1.8, 2.8), 4, 2, 1.0), + lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.8, 2.8), 4, 2, 1.0), + lump_grid(vec2(0.25), 97u, vec2(0.2, 0.9), vec2(1.4, 2.4), 2, 4, 1.0), + lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(1.4, 2.4), 2, 4, 1.0), + lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(1.2, 2.0), 2, 4, 1.0)); const float SN_COVERED = 0.998; // the snow over the pixel covering it: the sprites under it are not looked at @@ -220,7 +219,8 @@ bool snFlakeCell(vec2 p, ivec2 cell, vec2 perUV, float pixelUV, float reach, ino float alpha = smoothstep(0.03, 0.1, q.y); if (crystal) { - tile = min(int(kind * 4.0), 3); // small icy puffs (the first row of the atlas) + tile = min(int(kind * 4.0), 3); // the small clump, the dots and the scattered crystals (tiles 0, 1, 6, 7) + tile += (tile < 2) ? 0 : 4; alpha = snow_thin; } snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0, acc); diff --git a/shaders/vk14/mat_rain_windscreen.frag b/shaders/vk14/mat_rain_windscreen.frag index 89f1c263f..85aba95e8 100644 --- a/shaders/vk14/mat_rain_windscreen.frag +++ b/shaders/vk14/mat_rain_windscreen.frag @@ -350,6 +350,10 @@ vec2 wsFromLayer(vec2 p) // the layers: 0 gravity, 1 air. WindShare: how much the air drives the water (0 standing still), WindCos / WindSin: the turn // of the layer of the air float wsWindShare = 0.0; +// the layer of the weight turned by a quarter turn at a time so that its rivulets run down the glass in the world, whichever +// way the texture lies on it (an island of the UV turned or upside down) +float wsGravCos = 1.0; +float wsGravSin = 0.0; float wsWindCos = 1.0; float wsWindSin = 0.0; void wsSetLayer(int layer) @@ -359,8 +363,8 @@ void wsSetLayer(int layer) wsLayerDensity = 1.0 - wsWindShare; wsLayerIndex = 0; wsLayerHead = 1.0; - wsLayerCos = 1.0; - wsLayerSin = 0.0; + wsLayerCos = wsGravCos; + wsLayerSin = wsGravSin; wsLayerVaried = false; } else @@ -559,8 +563,9 @@ void drawRivulet(inout Hit hit, Riv r, vec2 sUVr, vec2 rd1, vec2 rd2) float wsKept(vec2 cg, float rad, float sCW, float sCH, float gridSize) { wsSetLayer(0); - Riv rv = getRiv(floor(cg / vec2(sCW, sCH)), sCW, sCH, gridSize); - float kept = 1.0 - streak_sweep * rivSwept(rv, cg, rad); + vec2 cl = wsToLayer(cg); + Riv rv = getRiv(floor(cl / vec2(sCW, sCH)), sCW, sCH, gridSize); + float kept = 1.0 - streak_sweep * rivSwept(rv, cl, rad); if (wsWindShare > 0.001) { wsSetLayer(1); @@ -665,6 +670,14 @@ void main() // to the glass UV (v up) through the tangent frame of the texture vec2 gravG = vec2(dot(wsGrav, Tgl), dot(wsGrav, Bgl) * flipS); vec2 flowG = vec2(dot(wsFlowDir, Tgl), dot(wsFlowDir, Bgl) * flipS); + if (dot(gravG, gravG) > 1e-8) + { + // down the glass in its UV, to the nearest quarter turn (a finer turn would break the rivulets at the seams where a curved + // glass bends); none on a glass lying flat + float turn = round(atan(gravG.x, -gravG.y) / 1.5707963) * 1.5707963; + wsGravCos = round(cos(turn)); + wsGravSin = round(sin(turn)); + } wsSpeed = smoothstep(0.3, 1.2, wsDrag); // 0 standing still .. 1 at speed (haze, drops) wsWindShare = smoothstep(0.5, 1.3, wsDrag); // how much the air drives the rivulets if (wsWindShare > 0.0) @@ -699,7 +712,8 @@ void main() float sCW = streak_cell / gridSize; float sCH = streak_run / gridSize; vec2 sUVg = vec2(f_coord.x, (STREAK_FLIP_Y != 0) ? 1.0 - f_coord.y : f_coord.y); // glass UV, v up - vec2 sCell = floor(sUVg / vec2(sCW, sCH)); + vec2 sUVl = wsToLayer(sUVg); // the same in the layer of the weight (down: -v) + vec2 sCell = floor(sUVl / vec2(sCW, sCH)); bool sweepOn = streak_sweep > 0.0 && streak_density > 0.0 && (wind_streaks > 0.0 || wsWindShare < 1.0) && (WS_PROFILE != 2); if ((rain_state.y > 0.001) && (WS_PROFILE != 5)) @@ -840,7 +854,7 @@ void main() // =================================================================== #if WS_PROFILE != 2 wsSetLayer(0); - drawRivulet(hit, getRiv(sCell, sCW, sCH, gridSize), sUVg, wsRd1, wsRd2); + drawRivulet(hit, getRiv(sCell, sCW, sCH, gridSize), sUVl, wsToLayerDir(wsRd1), wsToLayerDir(wsRd2)); if (wsWindShare > 0.001) { for (int wl = 1; wl <= wind_layers; ++wl) diff --git a/shaders/vk14/snow_sprites.glsl b/shaders/vk14/snow_sprites.glsl index 9ab5e8066..b89bd2ebe 100644 --- a/shaders/vk14/snow_sprites.glsl +++ b/shaders/vk14/snow_sprites.glsl @@ -168,20 +168,19 @@ struct lump_grid }; // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before, in the order they are laid -// (front to back, the top one first): mostly icy fleece (the puffs and clumps of the first two rows of the atlas, tiles 0-7), -// more and bigger, closing the glass by 2-3 mm; now and then a single lump on top: packed snow (tiles 10-13) or, more rarely, a -// wet one with its film (tiles 8, 9) +// (front to back, the top one first): all of them icy fleece (the dense puffs and clumps, tiles 2-5), more and bigger, closing +// the glass by 2-3 mm; now and then a single lump on top: packed snow (tiles 10-13) or a wet one with its film (8, 9) const int SN_GRIDS = 9; const lump_grid sn_grids[SN_GRIDS] = lump_grid[SN_GRIDS]( - lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 8, 6, 0.12), - lump_grid(vec2(0.75), 251u, vec2(1.4, 2.8), vec2(2.0, 3.0), 0, 8, 1.0), - lump_grid(vec2(0.0, 0.5), 233u, vec2(1.2, 2.4), vec2(2.0, 3.0), 0, 8, 1.0), - lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.0), vec2(2.0, 3.0), 0, 8, 1.0), - lump_grid(vec2(0.75, 0.25), 151u, vec2(0.7, 1.6), vec2(1.8, 2.8), 4, 4, 1.0), - lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.8, 2.8), 4, 4, 1.0), - lump_grid(vec2(0.25), 97u, vec2(0.2, 0.9), vec2(1.4, 2.4), 0, 4, 1.0), - lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(1.4, 2.4), 0, 4, 1.0), - lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(1.2, 2.0), 0, 4, 1.0)); + lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 8, 6, 0.03), + lump_grid(vec2(0.75), 251u, vec2(1.4, 2.8), vec2(2.0, 3.0), 4, 2, 1.0), + lump_grid(vec2(0.0, 0.5), 233u, vec2(1.2, 2.4), vec2(2.0, 3.0), 4, 2, 1.0), + lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.0), vec2(2.0, 3.0), 4, 2, 1.0), + lump_grid(vec2(0.75, 0.25), 151u, vec2(0.7, 1.6), vec2(1.8, 2.8), 4, 2, 1.0), + lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.8, 2.8), 4, 2, 1.0), + lump_grid(vec2(0.25), 97u, vec2(0.2, 0.9), vec2(1.4, 2.4), 2, 4, 1.0), + lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(1.4, 2.4), 2, 4, 1.0), + lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(1.2, 2.0), 2, 4, 1.0)); const float SN_COVERED = 0.998; // the snow over the pixel covering it: the sprites under it are not looked at @@ -220,7 +219,8 @@ bool snFlakeCell(vec2 p, ivec2 cell, vec2 perUV, float pixelUV, float reach, ino float alpha = smoothstep(0.03, 0.1, q.y); if (crystal) { - tile = min(int(kind * 4.0), 3); // small icy puffs (the first row of the atlas) + tile = min(int(kind * 4.0), 3); // the small clump, the dots and the scattered crystals (tiles 0, 1, 6, 7) + tile += (tile < 2) ? 0 : 4; alpha = snow_thin; } snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0, acc); From 04e877ffa6c287595aa4de53ce345808aff16f55 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 20:12:36 +0100 Subject: [PATCH 104/123] Windscreen snow: compiles with the NVIDIA OpenGL driver, the state of the glasses in the log [skip ci] - water_snow.comp named a variable "packed", a reserved word of GLSL: the NVIDIA OpenGL compiler refused the program, so the whole simulation of the windscreens was off under OpenGL. Now "packing". - mat_snow_windscreen.frag: a material without its slot takes the first glass whose snow the simulation keeps. - The log says, once it changes, whether each glass is baked, what it was built as and what its material is now, whether its snow is simulated, and whether the layer of the snow is laid: to find why the snow stays off under OpenGL. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- rendering/common/windscreenwater.cpp | 17 ++++++++++++++++- rendering/common/windscreenwater.h | 2 ++ shaders/ogl46/mat_snow_windscreen.frag | 7 +++++++ shaders/ogl46/water_snow.comp | 6 +++--- shaders/vk14/mat_snow_windscreen.frag | 7 +++++++ shaders/vk14/water_snow.comp | 6 +++--- 6 files changed, 38 insertions(+), 7 deletions(-) diff --git a/rendering/common/windscreenwater.cpp b/rendering/common/windscreenwater.cpp index f5d6e1e48..7dc8d200d 100644 --- a/rendering/common/windscreenwater.cpp +++ b/rendering/common/windscreenwater.cpp @@ -127,6 +127,8 @@ void windscreen_water::release() m_glasses = {}; m_glasscount = 0; m_layerslot = -1; + m_logged.fill(-1); + m_layerlogged = -1; m_kinds.clear(); m_vehicle = nullptr; m_cab = nullptr; @@ -460,6 +462,14 @@ void windscreen_water::update(double const Seconds) auto const *material{m_host.material(glass.material)}; auto const snowed{glass.baked && glass.snow && is_snow_glass(material)}; block.snow_slots[static_cast(slot)] = (snowed ? 1.f : 0.f); + // the state of the glass in the log once it changes: why a glass stays without its water or snow + if (auto const state{(glass.baked ? 1 : 0) | (glass.snow ? 2 : 0) | (glass_kind(material) << 2) | (snowed ? 16 : 0)}; state != m_logged[slot]) + { + m_logged[slot] = state; + WriteLog("windscreen water: glass " + std::to_string(slot + 1) + (glass.baked ? " baked" : " not baked yet (the mask of the wipers not loaded)") + + (glass.snow ? ", built as a glass of the snow" : ", built as a glass of the water") + ", its material now " + + std::to_string(glass_kind(material)) + " (0 none, 1 water, 2 snow)" + (snowed ? ", its snow simulated" : "")); + } anysnow = anysnow || snowed; auto const simulated{glass.baked && (false == glass.snow) && is_water_glass(material)}; glass.landings += static_cast(perground / fall * coming * glass.densest) * seconds; @@ -573,7 +583,12 @@ void windscreen_water::lay_snow(gl::water_ubs const &Block) auto layer{Block}; layer.counts.z = static_cast(slot); layer.counts.w = m_step; - gpu_snow_layer(slot, atlas, normal, layer); + auto const laid{gpu_snow_layer(slot, atlas, normal, layer)}; + if (int const state{laid ? 1 : 0}; state != m_layerlogged) + { + m_layerlogged = state; + WriteLog("windscreen water: the layer of the snow of glass " + std::to_string(slot + 1) + (laid ? " laid" : " not laid (the atlas of the snow not loaded)")); + } } } } diff --git a/rendering/common/windscreenwater.h b/rendering/common/windscreenwater.h index 4acfe991e..29469b9fe 100644 --- a/rendering/common/windscreenwater.h +++ b/rendering/common/windscreenwater.h @@ -124,6 +124,8 @@ class windscreen_water std::array m_glasses{}; std::size_t m_glasscount{0}; int m_layerslot{-1}; // the glass with the layer of the snow, -1 none + std::array m_logged{-1, -1, -1, -1}; // what the log last said of each glass (baked, snow, the shader, simulated) + int m_layerlogged{-1}; // what the log last said of the layer of the snow glm::vec4 m_bladesbefore{-1.f}; double m_time{0.0}; // seconds the simulation runs std::uint32_t m_step{0}; diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index e4772cb01..56ca3a8a6 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -95,6 +95,13 @@ void main() float snowTr = 0.0; float wet = 0.0; snSlot = int(param[2].z + 0.5) - 1; + // the material without its slot (the opengl renderer may give the glass a fresh copy of the material after the weather + // changed, without it): the first glass whose snow the simulation keeps + for (int s = 0; (snSlot < 0) && (s < WATER_SLOTS); ++s) + { + if (water_header[s].z > 0.5) + snSlot = s; + } if ((snSlot >= 0) && (snSlot < WATER_SLOTS) && water_snow_map(uint(snSlot), snMap)) { // the sprites coming within the texel of the layer at the pixel (water_snowlayer.comp) laid at the pixel, sharp from the diff --git a/shaders/ogl46/water_snow.comp b/shaders/ogl46/water_snow.comp index 57e968437..1ca6a8c5a 100644 --- a/shaders/ogl46/water_snow.comp +++ b/shaders/ogl46/water_snow.comp @@ -218,7 +218,7 @@ vec4 snow_move(ivec2 texel, vec4 state, float seconds) vec2 waterout = snow_out(motion.zw, seconds); float snow = state.x * (1.0 - snowout.x - snowout.y); float water = state.y * (1.0 - waterout.x - waterout.y); - float packed = state.z * snow; + float packing = state.z * snow; // (not "packed": a reserved word of GLSL, the NVIDIA OpenGL compiler refuses it) const ivec2 sides[4] = ivec2[4](ivec2(1, 0), ivec2(-1, 0), ivec2(0, 1), ivec2(0, -1)); for (int k = 0; k < 4; ++k) { @@ -244,10 +244,10 @@ vec4 snow_move(ivec2 texel, vec4 state, float seconds) water += (itsmotion.w * float(side.y) < 0.0) ? neighbour.y * itswater.y : 0.0; } snow += coming; - packed += coming * neighbour.z; + packing += coming * neighbour.z; } snow = max(snow, 0.0); - return vec4(snow, max(water, 0.0), (snow > 1e-4) ? clamp(packed / snow, 0.0, 1.0) : 0.0, state.w); + return vec4(snow, max(water, 0.0), (snow > 1e-4) ? clamp(packing / snow, 0.0, 1.0) : 0.0, state.w); } void main() diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index 43f0c455f..5bdd3bdfa 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -100,6 +100,13 @@ void main() float snowTr = 0.0; float wet = 0.0; snSlot = int(param[2].z + 0.5) - 1; + // the material without its slot (the opengl renderer may give the glass a fresh copy of the material after the weather + // changed, without it): the first glass whose snow the simulation keeps + for (int s = 0; (snSlot < 0) && (s < WATER_SLOTS); ++s) + { + if (water_header[s].z > 0.5) + snSlot = s; + } if ((snSlot >= 0) && (snSlot < WATER_SLOTS) && water_snow_map(uint(snSlot), snMap)) { // the sprites coming within the texel of the layer at the pixel (water_snowlayer.comp) laid at the pixel, sharp from the diff --git a/shaders/vk14/water_snow.comp b/shaders/vk14/water_snow.comp index 69fa1acad..b7620c7ab 100644 --- a/shaders/vk14/water_snow.comp +++ b/shaders/vk14/water_snow.comp @@ -221,7 +221,7 @@ vec4 snow_move(ivec2 texel, vec4 state, float seconds) vec2 waterout = snow_out(motion.zw, seconds); float snow = state.x * (1.0 - snowout.x - snowout.y); float water = state.y * (1.0 - waterout.x - waterout.y); - float packed = state.z * snow; + float packing = state.z * snow; // (not "packed": a reserved word of GLSL, the NVIDIA OpenGL compiler refuses it) const ivec2 sides[4] = ivec2[4](ivec2(1, 0), ivec2(-1, 0), ivec2(0, 1), ivec2(0, -1)); for (int k = 0; k < 4; ++k) { @@ -247,10 +247,10 @@ vec4 snow_move(ivec2 texel, vec4 state, float seconds) water += (itsmotion.w * float(side.y) < 0.0) ? neighbour.y * itswater.y : 0.0; } snow += coming; - packed += coming * neighbour.z; + packing += coming * neighbour.z; } snow = max(snow, 0.0); - return vec4(snow, max(water, 0.0), (snow > 1e-4) ? clamp(packed / snow, 0.0, 1.0) : 0.0, state.w); + return vec4(snow, max(water, 0.0), (snow > 1e-4) ? clamp(packing / snow, 0.0, 1.0) : 0.0, state.w); } void main() From 48e4ef517fa372a420724d1568639240bcecc2f4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 20:38:07 +0100 Subject: [PATCH 105/123] Windscreen water (OpenGL): the mask of the wipers read for the kernels [skip ci] The OpenGL renderer reads a texture when a draw binds it. The glasses never draw the mask of their wipers, only the kernels read it, so under OpenGL the mask stayed unread, the glass was never baked and had no map: no snow (the log said "glass 1 not baked yet" for good). The kernels now have a texture they read loaded from its file when nothing read it yet. Vulkan reads its textures without a draw, so it had this right. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- rendering/opengl46/opengl46water.cpp | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/rendering/opengl46/opengl46water.cpp b/rendering/opengl46/opengl46water.cpp index 4dbf77d18..457544257 100644 --- a/rendering/opengl46/opengl46water.cpp +++ b/rendering/opengl46/opengl46water.cpp @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "rendering/opengl46/opengl46water.h" +#include "model/Texture.h" #include "rendering/renderer.h" #include "utilities/Logs.h" @@ -23,6 +24,16 @@ GLuint groups(std::size_t const Count) return static_cast((Count + gl::WATER_GROUP_SIZE - 1) / gl::WATER_GROUP_SIZE); } +// a texture a kernel reads, made ready: read from its file first when nothing read it yet. the opengl renderer reads a texture +// when a draw binds it, and the glasses never draw the mask of their wipers (only the kernels read it), so without this the mask +// stayed unread and the glass never got its map +bool kernel_texture(ITexture &Texture) +{ + if (auto *source{dynamic_cast(&Texture)}; (source != nullptr) && (source->data_state == resource_state::none) && (false == source->is_rendertarget)) + source->load(); + return Texture.create() && Texture.get_is_ready() && (Texture.get_id() != 0); +} + } // namespace namespace @@ -146,7 +157,7 @@ bool opengl46_windscreen_water::gpu_bake(std::size_t const Slot, texture_handle if ((!m_storage) || (Mask == null_handle)) return false; auto &texture{GfxRenderer->Texture(Mask)}; - if ((false == texture.create()) || (false == texture.get_is_ready()) || (texture.get_id() == 0)) + if (false == kernel_texture(texture)) return false; m_storage->bind_base(); m_block->update(Block); @@ -165,8 +176,7 @@ bool opengl46_windscreen_water::gpu_snow_layer(std::size_t const Slot, texture_h return false; auto &atlas{GfxRenderer->Texture(Atlas)}; auto &normal{GfxRenderer->Texture(Normal)}; - if ((false == atlas.create()) || (false == atlas.get_is_ready()) || (atlas.get_id() == 0) || (false == normal.create()) || (false == normal.get_is_ready()) || - (normal.get_id() == 0)) + if ((false == kernel_texture(atlas)) || (false == kernel_texture(normal))) return false; m_storage->bind_base(); m_block->update(Block); From 501784ab8663e00f0cbe5f8cefd4a72cb212e9e5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 12:03:17 +0100 Subject: [PATCH 106/123] Windscreen snow: bigger flakes and lumps, atlas of fleece only, glassy and white sprites [skip ci] - the flakes and the lumps bigger; the drops and the wet lumps gone (their atlas slots hold fleece now) - the lumps take the fleece tiles, most often the marked ones - each sprite at random from glassy (stuck, half melted, bends the picture) to fully white (dry powder), whiter where the snow is thicker Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/snow_sprites.glsl | 71 +++++++++++++++++++-------------- shaders/vk14/snow_sprites.glsl | 71 +++++++++++++++++++-------------- 2 files changed, 84 insertions(+), 58 deletions(-) diff --git a/shaders/ogl46/snow_sprites.glsl b/shaders/ogl46/snow_sprites.glsl index b89bd2ebe..0ba2a38e8 100644 --- a/shaders/ogl46/snow_sprites.glsl +++ b/shaders/ogl46/snow_sprites.glsl @@ -6,18 +6,19 @@ #define SNOW_SPRITES_GLSL // --- tuning ------------------------------------------------------------------------------------------------------------------ -const float snow_flake_cell = 0.007; // a dot, a small puff or a drop at most every this many metres of the glass (its size) +const float snow_flake_cell = 0.010; // a dot, a small puff or a drop at most every this many metres of the glass (its size) const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff const float snow_drops = 0.05; // share of the texels with the water of a melted flake showing a drop (more with more water) const float snow_deep = 2.5; // mm of snow from which the cover is opaque (no picture behind it) const float snow_cover = 0.25; // the lumps get opaque from three times this many mm of snow -const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) +const float snow_lump_cell = 0.0225; // a lump at most every this many metres of the glass (its size: up to two of them) const vec2 snow_lump_grow = vec2(0.75, 0.88); // a lump's size as it comes .. on thick snow, of its size (small gaps stay open) -const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) +const float snow_heap_cells = 2.85; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) -const float snow_ice = 0.6; // opacity of a lump until the snow gets thick (icy: the picture shows through, bent) +const float snow_ice = 0.75; // opacity of a lump until the snow gets thick (icy: the picture shows through, bent) const vec3 snow_ice_tint = vec3(0.93, 0.97, 1.0); // the colour of the icy snow -const float snow_thin = 0.45; // opacity of a single thin flake (ice crystals let most of the light through) +const float snow_thin = 0.35; // opacity of the most glassy flake; each flake is at random from it to fully white +const float snow_glassy = 0.45; // opacity of the most glassy lump until the snow gets thick; each lump from it to fully white const float snow_bump = 1.0; // strength of the relief from the normal map, 0 = flat const float snow_gloss = 0.8; // glints of the sun / headlights on the wet snow, 0 = matt const float snow_ice_bend = 1.0; // how strongly the icy snow bends the picture behind it, of the bend of a drop @@ -77,6 +78,14 @@ float snTileSize() return snBig ? 0.25 : 0.5; } +// how white a sprite is (0 glassy, stuck and half melted, 1 dry powder), at random from its Random, whiter where the snow is +// Thick (0 .. 1); another number than Random, so it goes its own way of the tone +float snWhite(float random, float thick) +{ + float r = fract(random * 13.731 + 0.377); + return smoothstep(0.0, 1.0, clamp(r + (thick - 0.5) * 0.7, 0.0, 1.0)); +} + // a sprite over the accumulator: Local the place in it (0 .. 1), Rot its rotation (cos, sin), Tone its colour void snSprite(vec2 local, int tile, float alpha, vec3 tone, vec2 rot, float flip, float lod, float bend, inout sprite_acc acc) { @@ -99,7 +108,7 @@ void snSprite(vec2 local, int tile, float alpha, vec3 tone, vec2 rot, float flip acc.a += w; // all the snow bends the picture behind it (wet icy snow, slush, drops), as the drops of the rain; the drops and the slush // the most - float bends = (((tile == TILE_DROP) || (tile == 8) || (tile == 9) || (tile == 14)) ? 1.0 : snow_ice_bend) * bend; + float bends = snow_ice_bend * bend; // the atlas holds icy snow only float wb = a * (1.0 - snBendA); snBend += nuv * bends * wb; snBendA += wb; @@ -162,22 +171,25 @@ struct lump_grid uint salt; vec2 snow; // the snow it takes for a lump of the grid to come, mm: from .. to (random per cell) vec2 size; // the size of its lumps, cells: from .. to (random per cell) - int tiles; // its tiles: the first one and how many + int tiles; // its tiles, in sn_lump_tiles: the first one and how many int count; float share; // the share of its cells having a lump at all (1: all of them) }; +// the tiles of the lumps, as the grids take them: the fleece (2-5, and the clumps made of it, 8, 9) and the packed snow (10-15) +const int sn_lump_tiles[12] = int[12](2, 3, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15); + // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before, in the order they are laid -// (front to back, the top one first): all of them icy fleece (the dense puffs and clumps, tiles 2-5), more and bigger, closing -// the glass by 2-3 mm; now and then a single lump on top: packed snow (tiles 10-13) or a wet one with its film (8, 9) +// (front to back, the top one first): all of them icy fleece (the dense puffs and clumps, tiles 2-5, 8, 9), more and bigger, closing +// the glass by 2-3 mm; now and then a single lump of packed snow on top (tiles 10-15) const int SN_GRIDS = 9; const lump_grid sn_grids[SN_GRIDS] = lump_grid[SN_GRIDS]( - lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 8, 6, 0.03), - lump_grid(vec2(0.75), 251u, vec2(1.4, 2.8), vec2(2.0, 3.0), 4, 2, 1.0), - lump_grid(vec2(0.0, 0.5), 233u, vec2(1.2, 2.4), vec2(2.0, 3.0), 4, 2, 1.0), - lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.0), vec2(2.0, 3.0), 4, 2, 1.0), - lump_grid(vec2(0.75, 0.25), 151u, vec2(0.7, 1.6), vec2(1.8, 2.8), 4, 2, 1.0), - lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.8, 2.8), 4, 2, 1.0), + lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 6, 6, 0.03), + lump_grid(vec2(0.75), 251u, vec2(1.4, 2.8), vec2(2.0, 3.0), 2, 4, 1.0), + lump_grid(vec2(0.0, 0.5), 233u, vec2(1.2, 2.4), vec2(2.0, 3.0), 0, 6, 1.0), + lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.0), vec2(2.0, 3.0), 0, 6, 1.0), + lump_grid(vec2(0.75, 0.25), 151u, vec2(0.7, 1.6), vec2(1.8, 2.8), 2, 4, 1.0), + lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.8, 2.8), 2, 4, 1.0), lump_grid(vec2(0.25), 97u, vec2(0.2, 0.9), vec2(1.4, 2.4), 2, 4, 1.0), lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(1.4, 2.4), 2, 4, 1.0), lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(1.2, 2.0), 2, 4, 1.0)); @@ -204,9 +216,11 @@ bool snFlakeCell(vec2 p, ivec2 cell, vec2 perUV, float pixelUV, float reach, ino if (false == snLocal(p, centre, sizeDraw * 1.4 + 2.0 * reach, vec2(1.0), rot, flip, 1.0, local)) return false; vec4 q = water_snow_at(uint(snSlot), snMap, centre / perUV); - bool drop = (q.x < 0.05) && (q.y > 0.03); + // only the dry snow has its flakes: no drops of the melted ones (the round drops and the wet lumps with their film, tiles 8, 9, + // 14, 15, aren't used) + bool drop = false; bool crystal = (q.x >= 0.05); - if ((false == drop) && (false == crystal)) + if (false == crystal) return false; if (chance > (drop ? snow_drops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) return false; @@ -215,15 +229,12 @@ bool snFlakeCell(vec2 p, ivec2 cell, vec2 perUV, float pixelUV, float reach, ino return false; if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, 1.0, local)) return true; - int tile = (kind < 0.25) ? 14 : TILE_DROP; // a drop, now and then a wet lump with its film - float alpha = smoothstep(0.03, 0.1, q.y); - if (crystal) - { - tile = min(int(kind * 4.0), 3); // the small clump, the dots and the scattered crystals (tiles 0, 1, 6, 7) - tile += (tile < 2) ? 0 : 4; - alpha = snow_thin; - } - snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0, acc); + int tile = min(int(kind * 4.0), 3); // the small clump, the dots and the scattered crystals (tiles 0, 1, 6, 7) + tile += (tile < 2) ? 0 : 4; + float white = snWhite(random, smoothstep(0.05, snow_cover * 3.0, q.x)); + float alpha = mix(snow_thin, 1.0, white); + vec3 tone = mix(snTone(q, random), vec3(1.0), white * 0.6); + snSprite(local, tile, alpha, tone, rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0 - white, acc); return true; } @@ -241,7 +252,7 @@ bool snLumpCell(vec2 p, ivec2 cell, vec2 perUV, lump_grid grid, float pixelUV, f float ang = RandF(seed) * 6.2831853; vec2 rot = vec2(cos(ang), sin(ang)); float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; - int tile = grid.tiles + min(int(RandF(seed) * float(grid.count)), grid.count - 1); + int tile = sn_lump_tiles[grid.tiles + min(int(RandF(seed) * float(grid.count)), grid.count - 1)]; float random = RandF(seed); float aniso = mix(0.8, 1.0, RandF(seed)); float sizeDraw = mix(grid.size.x, grid.size.y, RandF(seed)); @@ -260,8 +271,10 @@ bool snLumpCell(vec2 p, ivec2 cell, vec2 perUV, lump_grid grid, float pixelUV, f return true; // fading in over the first snow (no flicker on the edge), opaque when thick; the thick snow bends nothing float deep = smoothstep(snow_cover * 3.0, snow_deep, q.x); - float alpha = smoothstep(needs, needs + 0.04, q.x) * mix(snow_ice, 1.0, deep); - snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0 - deep, acc); + float white = snWhite(random, smoothstep(snow_cover, snow_deep, q.x)); + float alpha = smoothstep(needs, needs + 0.04, q.x) * mix(mix(snow_glassy, 1.0, white), 1.0, deep); + vec3 tone = mix(snTone(q, random), vec3(1.0), white * 0.6); + snSprite(local, tile, alpha, tone, rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), (1.0 - deep) * (1.0 - white), acc); return true; } diff --git a/shaders/vk14/snow_sprites.glsl b/shaders/vk14/snow_sprites.glsl index b89bd2ebe..0ba2a38e8 100644 --- a/shaders/vk14/snow_sprites.glsl +++ b/shaders/vk14/snow_sprites.glsl @@ -6,18 +6,19 @@ #define SNOW_SPRITES_GLSL // --- tuning ------------------------------------------------------------------------------------------------------------------ -const float snow_flake_cell = 0.007; // a dot, a small puff or a drop at most every this many metres of the glass (its size) +const float snow_flake_cell = 0.010; // a dot, a small puff or a drop at most every this many metres of the glass (its size) const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff const float snow_drops = 0.05; // share of the texels with the water of a melted flake showing a drop (more with more water) const float snow_deep = 2.5; // mm of snow from which the cover is opaque (no picture behind it) const float snow_cover = 0.25; // the lumps get opaque from three times this many mm of snow -const float snow_lump_cell = 0.016; // a lump at most every this many metres of the glass (its size: up to two of them) +const float snow_lump_cell = 0.0225; // a lump at most every this many metres of the glass (its size: up to two of them) const vec2 snow_lump_grow = vec2(0.75, 0.88); // a lump's size as it comes .. on thick snow, of its size (small gaps stay open) -const float snow_heap_cells = 4.0; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) +const float snow_heap_cells = 2.85; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) -const float snow_ice = 0.6; // opacity of a lump until the snow gets thick (icy: the picture shows through, bent) +const float snow_ice = 0.75; // opacity of a lump until the snow gets thick (icy: the picture shows through, bent) const vec3 snow_ice_tint = vec3(0.93, 0.97, 1.0); // the colour of the icy snow -const float snow_thin = 0.45; // opacity of a single thin flake (ice crystals let most of the light through) +const float snow_thin = 0.35; // opacity of the most glassy flake; each flake is at random from it to fully white +const float snow_glassy = 0.45; // opacity of the most glassy lump until the snow gets thick; each lump from it to fully white const float snow_bump = 1.0; // strength of the relief from the normal map, 0 = flat const float snow_gloss = 0.8; // glints of the sun / headlights on the wet snow, 0 = matt const float snow_ice_bend = 1.0; // how strongly the icy snow bends the picture behind it, of the bend of a drop @@ -77,6 +78,14 @@ float snTileSize() return snBig ? 0.25 : 0.5; } +// how white a sprite is (0 glassy, stuck and half melted, 1 dry powder), at random from its Random, whiter where the snow is +// Thick (0 .. 1); another number than Random, so it goes its own way of the tone +float snWhite(float random, float thick) +{ + float r = fract(random * 13.731 + 0.377); + return smoothstep(0.0, 1.0, clamp(r + (thick - 0.5) * 0.7, 0.0, 1.0)); +} + // a sprite over the accumulator: Local the place in it (0 .. 1), Rot its rotation (cos, sin), Tone its colour void snSprite(vec2 local, int tile, float alpha, vec3 tone, vec2 rot, float flip, float lod, float bend, inout sprite_acc acc) { @@ -99,7 +108,7 @@ void snSprite(vec2 local, int tile, float alpha, vec3 tone, vec2 rot, float flip acc.a += w; // all the snow bends the picture behind it (wet icy snow, slush, drops), as the drops of the rain; the drops and the slush // the most - float bends = (((tile == TILE_DROP) || (tile == 8) || (tile == 9) || (tile == 14)) ? 1.0 : snow_ice_bend) * bend; + float bends = snow_ice_bend * bend; // the atlas holds icy snow only float wb = a * (1.0 - snBendA); snBend += nuv * bends * wb; snBendA += wb; @@ -162,22 +171,25 @@ struct lump_grid uint salt; vec2 snow; // the snow it takes for a lump of the grid to come, mm: from .. to (random per cell) vec2 size; // the size of its lumps, cells: from .. to (random per cell) - int tiles; // its tiles: the first one and how many + int tiles; // its tiles, in sn_lump_tiles: the first one and how many int count; float share; // the share of its cells having a lump at all (1: all of them) }; +// the tiles of the lumps, as the grids take them: the fleece (2-5, and the clumps made of it, 8, 9) and the packed snow (10-15) +const int sn_lump_tiles[12] = int[12](2, 3, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15); + // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before, in the order they are laid -// (front to back, the top one first): all of them icy fleece (the dense puffs and clumps, tiles 2-5), more and bigger, closing -// the glass by 2-3 mm; now and then a single lump on top: packed snow (tiles 10-13) or a wet one with its film (8, 9) +// (front to back, the top one first): all of them icy fleece (the dense puffs and clumps, tiles 2-5, 8, 9), more and bigger, closing +// the glass by 2-3 mm; now and then a single lump of packed snow on top (tiles 10-15) const int SN_GRIDS = 9; const lump_grid sn_grids[SN_GRIDS] = lump_grid[SN_GRIDS]( - lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 8, 6, 0.03), - lump_grid(vec2(0.75), 251u, vec2(1.4, 2.8), vec2(2.0, 3.0), 4, 2, 1.0), - lump_grid(vec2(0.0, 0.5), 233u, vec2(1.2, 2.4), vec2(2.0, 3.0), 4, 2, 1.0), - lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.0), vec2(2.0, 3.0), 4, 2, 1.0), - lump_grid(vec2(0.75, 0.25), 151u, vec2(0.7, 1.6), vec2(1.8, 2.8), 4, 2, 1.0), - lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.8, 2.8), 4, 2, 1.0), + lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 6, 6, 0.03), + lump_grid(vec2(0.75), 251u, vec2(1.4, 2.8), vec2(2.0, 3.0), 2, 4, 1.0), + lump_grid(vec2(0.0, 0.5), 233u, vec2(1.2, 2.4), vec2(2.0, 3.0), 0, 6, 1.0), + lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.0), vec2(2.0, 3.0), 0, 6, 1.0), + lump_grid(vec2(0.75, 0.25), 151u, vec2(0.7, 1.6), vec2(1.8, 2.8), 2, 4, 1.0), + lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.8, 2.8), 2, 4, 1.0), lump_grid(vec2(0.25), 97u, vec2(0.2, 0.9), vec2(1.4, 2.4), 2, 4, 1.0), lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(1.4, 2.4), 2, 4, 1.0), lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(1.2, 2.0), 2, 4, 1.0)); @@ -204,9 +216,11 @@ bool snFlakeCell(vec2 p, ivec2 cell, vec2 perUV, float pixelUV, float reach, ino if (false == snLocal(p, centre, sizeDraw * 1.4 + 2.0 * reach, vec2(1.0), rot, flip, 1.0, local)) return false; vec4 q = water_snow_at(uint(snSlot), snMap, centre / perUV); - bool drop = (q.x < 0.05) && (q.y > 0.03); + // only the dry snow has its flakes: no drops of the melted ones (the round drops and the wet lumps with their film, tiles 8, 9, + // 14, 15, aren't used) + bool drop = false; bool crystal = (q.x >= 0.05); - if ((false == drop) && (false == crystal)) + if (false == crystal) return false; if (chance > (drop ? snow_drops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) return false; @@ -215,15 +229,12 @@ bool snFlakeCell(vec2 p, ivec2 cell, vec2 perUV, float pixelUV, float reach, ino return false; if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, 1.0, local)) return true; - int tile = (kind < 0.25) ? 14 : TILE_DROP; // a drop, now and then a wet lump with its film - float alpha = smoothstep(0.03, 0.1, q.y); - if (crystal) - { - tile = min(int(kind * 4.0), 3); // the small clump, the dots and the scattered crystals (tiles 0, 1, 6, 7) - tile += (tile < 2) ? 0 : 4; - alpha = snow_thin; - } - snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0, acc); + int tile = min(int(kind * 4.0), 3); // the small clump, the dots and the scattered crystals (tiles 0, 1, 6, 7) + tile += (tile < 2) ? 0 : 4; + float white = snWhite(random, smoothstep(0.05, snow_cover * 3.0, q.x)); + float alpha = mix(snow_thin, 1.0, white); + vec3 tone = mix(snTone(q, random), vec3(1.0), white * 0.6); + snSprite(local, tile, alpha, tone, rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0 - white, acc); return true; } @@ -241,7 +252,7 @@ bool snLumpCell(vec2 p, ivec2 cell, vec2 perUV, lump_grid grid, float pixelUV, f float ang = RandF(seed) * 6.2831853; vec2 rot = vec2(cos(ang), sin(ang)); float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; - int tile = grid.tiles + min(int(RandF(seed) * float(grid.count)), grid.count - 1); + int tile = sn_lump_tiles[grid.tiles + min(int(RandF(seed) * float(grid.count)), grid.count - 1)]; float random = RandF(seed); float aniso = mix(0.8, 1.0, RandF(seed)); float sizeDraw = mix(grid.size.x, grid.size.y, RandF(seed)); @@ -260,8 +271,10 @@ bool snLumpCell(vec2 p, ivec2 cell, vec2 perUV, lump_grid grid, float pixelUV, f return true; // fading in over the first snow (no flicker on the edge), opaque when thick; the thick snow bends nothing float deep = smoothstep(snow_cover * 3.0, snow_deep, q.x); - float alpha = smoothstep(needs, needs + 0.04, q.x) * mix(snow_ice, 1.0, deep); - snSprite(local, tile, alpha, snTone(q, random), rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0 - deep, acc); + float white = snWhite(random, smoothstep(snow_cover, snow_deep, q.x)); + float alpha = smoothstep(needs, needs + 0.04, q.x) * mix(mix(snow_glassy, 1.0, white), 1.0, deep); + vec3 tone = mix(snTone(q, random), vec3(1.0), white * 0.6); + snSprite(local, tile, alpha, tone, rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), (1.0 - deep) * (1.0 - white), acc); return true; } From da8f06dde1465ba3acdcbf9021315f8d3f9921f1 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 12:11:07 +0100 Subject: [PATCH 107/123] Rebase onto feat/gl46-migration: the code of the base the replayed hunks covered, back The rebase replayed the hunks of this branch over the ones of feat/gl46-migration where both touched the same lines; this brings back what of the base they covered: the null renderer, the black box of the camera, the opaque text displays, the motion blur of the free camera (OpenGL 4.6 and Vulkan), the scenario loader catching std::exception. The log keeps off the console in test mode. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- application/application.cpp | 7 +++++- application/drivermode.cpp | 11 ++++++++++ application/scenarioloadermode.cpp | 2 +- rendering/common/scenewalk.cpp | 29 +++++++++++++++++++++++-- rendering/common/scenewalk.h | 1 + rendering/opengl46/opengl46renderer.cpp | 15 ++++++++----- rendering/vulkan14/vulkan14frame.cpp | 5 +++++ 7 files changed, 61 insertions(+), 9 deletions(-) diff --git a/application/application.cpp b/application/application.cpp index 6b3cc4a8f..e8624b9e4 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -1538,7 +1538,12 @@ void eu07_application::select_gfx_backend() auto *factory{gfx_renderer_factory::get_instance()}; m_gfxbackend = nullptr; - if (Global.GfxRenderer == "vulkan") + if (Global.GfxRenderer == "null") + { + // draws nothing and loads no textures (test mode) + m_gfxbackend = factory->backend("null"); + } + else if (Global.GfxRenderer == "vulkan") { // a renderer which can't run here falls back to opengl, so a setting in eu07.ini doesn't leave the user with a black screen std::string reason; diff --git a/application/drivermode.cpp b/application/drivermode.cpp index f36656226..c4a2f063b 100644 --- a/application/drivermode.cpp +++ b/application/drivermode.cpp @@ -349,6 +349,17 @@ bool driver_mode::update() simulation::Lights.update(); Timer::subsystem.sim_lights.stop(); simulation::Deer.update(deltatime); + { + // where the user looks from, for the black box + auto const &camera{DebugCameraFlag ? DebugCamera : Camera}; + auto const mode{DebugCameraFlag ? blackbox::camera_modes::debug : + false == FreeFlyModeFlag ? blackbox::camera_modes::cab : + m_externalview ? blackbox::camera_modes::external : + blackbox::camera_modes::free}; + simulation::Blackbox.camera(blackbox_camera(camera, mode, mode == blackbox::camera_modes::external ? m_externalviewmode : 0), + DebugCameraFlag ? nullptr : camera.m_owner); + } + simulation::Blackbox.update(deltatime); if (Global.test.enabled && simulation::is_ready) { diff --git a/application/scenarioloadermode.cpp b/application/scenarioloadermode.cpp index 85f81a337..349ff691f 100644 --- a/application/scenarioloadermode.cpp +++ b/application/scenarioloadermode.cpp @@ -71,7 +71,7 @@ bool scenarioloader_mode::update() { } // the file it can't read, as the parser and the scenery opening report it; invalid_scenery_exception is one of these, and so is // what the file system throws - catch (std::runtime_error const &e) { + catch (std::exception const &e) { ErrorLog(std::format("Bad init: scenario \"{}\" couldn't be opened ({})", Global.SceneryFile, e.what())); state.reset(); if (Global.test.enabled) { diff --git a/rendering/common/scenewalk.cpp b/rendering/common/scenewalk.cpp index de01564f4..1b0cf12e3 100644 --- a/rendering/common/scenewalk.cpp +++ b/rendering/common/scenewalk.cpp @@ -2297,9 +2297,17 @@ void scene_walk::Render(TSubModel *Submodel) } } } - if (Submodel->Child != nullptr) - if (Submodel->iAlpha & Submodel->iFlags & 0x001F0000) + if (Submodel->Child != nullptr && (TSubModel::iAlpha & Submodel->iFlags & 0x001F0000)) + { + if (Submodel->eType == TP_TEXT) + { // the opaque characters of a text display, drawn with depth like the rest of the opaque geometry + Render_text(Submodel); + } + else + { Render(Submodel->Child); + } + } if (Submodel->iFlags & 0xC000) { @@ -3167,6 +3175,23 @@ bool scene_walk::Render_Alpha(TModel3d *Model, material_data const *Material, fl return result; } +// opaque characters of a text display, laid out in a row the same way as the translucent ones +void scene_walk::Render_text(TSubModel *Submodel) +{ + if (TSubModel::pasText == nullptr) + { + return; + } + ::glPushMatrix(); + for (auto *p : Submodel->text_letters(*TSubModel::pasText)) + { + Render(p); + if (p->fMatrix) + ::glMultMatrixf(p->fMatrix->readArray()); // move on to the place of the next character + } + ::glPopMatrix(); +} + // characters of a text display, laid out in a row. the text can be encoded in utf-8 or in windows-1250 void scene_walk::Render_Alpha_text(TSubModel *Submodel) { diff --git a/rendering/common/scenewalk.h b/rendering/common/scenewalk.h index 0db605644..111fa73fb 100644 --- a/rendering/common/scenewalk.h +++ b/rendering/common/scenewalk.h @@ -190,6 +190,7 @@ class scene_walk bool Render_Alpha(TModel3d *Model, material_data const *Material, float const Squaredistance, glm::dvec3 const &Position, glm::vec3 const &Angle); bool Render_Alpha(TModel3d *Model, material_data const *Material, float const Squaredistance); void Render_Alpha(TSubModel *Submodel); + void Render_text(TSubModel *Submodel); // opaque characters of a text display void Render_Alpha_text(TSubModel *Submodel); // characters of a text display // TDynamicObject::renderme as the walk sets and reads it: the walk keeps its own while the passes are walked by several threads at diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index ba087821b..9858863a3 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -1871,11 +1871,16 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) if (vp.main && !vp.custom_backbuffer) // TODO: update window sizes also for extra viewports target_size = Global.fb_size; - // the motion is blurred only when something in the view moves: the vehicle of the camera, or a vehicle drawn in the last - // frame (a vehicle setting off is blurred from its second frame, when its velocity is still far below a pixel). the pass - // itself runs in every frame: the windscreens (mat_rain_windscreen, mat_bugs_windscreen) ask it in the velocity target for - // the picture in their drops and the haze, also standing still, with the motion blur off and with any anti-aliasing (the - // motion is then blurred by 0) + // the camera with no vehicle of its own (freefly, the editor) blurs the world with its own movement, as a vehicle does with + // its (rendering/common/freecameramotion.h) + if (vp.main && (Global.pCamera.m_owner != nullptr)) + m_freecamera.reset(); + auto const freecameramovement{(vp.main && (Global.pCamera.m_owner == nullptr)) ? m_freecamera.next_frame(Global.pCamera.Pos) : glm::vec3{0.f}}; + // the motion is blurred only when something in the view moves: the vehicle of the camera, the camera with no vehicle of its + // own, or a vehicle drawn in the last frame (a vehicle setting off is blurred from its second frame, when its velocity is + // still far below a pixel). the pass itself runs in every frame: the windscreens (mat_rain_windscreen, mat_bugs_windscreen) + // ask it in the velocity target for the picture in their drops and the haze, also standing still, with the motion blur off + // and with any anti-aliasing (the motion is then blurred by 0) auto const moving{ Global.gfx_postfx_motionblur_enabled && (m_vehiclesmoved diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index eb8527b37..6e26f1315 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -1724,6 +1724,11 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) render_ray_scene(vp); } + // the camera with no vehicle of its own (freefly, the editor) blurs the world with its own movement, as a vehicle does with its + // (rendering/common/freecameramotion.h) + if (vp.main && (Global.pCamera.m_owner != nullptr)) + m_freecamera.reset(); + auto const freecameramovement{(vp.main && (Global.pCamera.m_owner == nullptr)) ? m_freecamera.next_frame(Global.pCamera.Pos) : glm::vec3{0.f}}; // the motion blurred only when something in the view moves (see opengl46_renderer::Render_pass()); the pass runs anyway auto const motionblur{Global.gfx_postfx_motionblur_enabled && targets.motion && (m_vehiclesmoved || (freecameramovement != glm::vec3{0.f}) || From 5fe115657fcde3eb8381e30557c13588b1211652 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 12:22:06 +0100 Subject: [PATCH 108/123] Windscreen snow: a glass takes its slot on the material the cab has now, no fallback to the first glass in the shader The renderer may give a glass a fresh copy of its material after the weather changed; the glass keeps its first submodel and re-resolves its material in assign(true). The fallback of mat_snow_windscreen (any material without a slot took the snow of the first simulated glass) is gone (OpenGL 4.6 and Vulkan). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- rendering/common/windscreenwater.cpp | 12 +++++++++++- rendering/common/windscreenwater.h | 1 + shaders/ogl46/mat_snow_windscreen.frag | 7 ------- shaders/vk14/mat_snow_windscreen.frag | 7 ------- 4 files changed, 12 insertions(+), 15 deletions(-) diff --git a/rendering/common/windscreenwater.cpp b/rendering/common/windscreenwater.cpp index 7dc8d200d..b28e065cc 100644 --- a/rendering/common/windscreenwater.cpp +++ b/rendering/common/windscreenwater.cpp @@ -148,7 +148,13 @@ void windscreen_water::assign(bool const Assigned) } for (std::size_t slot = 0; slot < m_glasscount; ++slot) { - auto const &glass{m_glasses[slot]}; + auto &glass{m_glasses[slot]}; + // the material of the glass as the cab has it now: the renderer may give the glass a fresh copy of its material (after the + // weather changed), which takes the slot then + if (Assigned && (glass.submodel != nullptr) && (glass.submodel->m_material != glass.material) && is_glass(m_host.material(glass.submodel->m_material))) + { + glass.material = glass.submodel->m_material; + } if (auto *material{m_host.material(glass.material)}; is_glass(material)) { material->params[SLOT_PARAM].z = (Assigned && glass.baked ? static_cast(slot + 1) : 0.f); @@ -296,6 +302,10 @@ void windscreen_water::build(TModel3d &Cab) auto &glass{m_glasses[m_glasscount]}; glass = windscreen_water::glass{}; glass.material = material; + visit_submodels(root, [&](TSubModel *Submodel) { + if ((glass.submodel == nullptr) && (Submodel->m_material == material) && (Submodel->eType == GL_TRIANGLES)) + glass.submodel = Submodel; + }); auto const *opengl{m_host.material(material)}; glass.snow = is_snow_glass(opengl); glass.mask = opengl->textures[opengl->shader->texture_conf.at("wipermask").id]; diff --git a/rendering/common/windscreenwater.h b/rendering/common/windscreenwater.h index 29469b9fe..d92d5e676 100644 --- a/rendering/common/windscreenwater.h +++ b/rendering/common/windscreenwater.h @@ -89,6 +89,7 @@ class windscreen_water struct glass { material_handle material{null_handle}; + TSubModel *submodel{nullptr}; // the first piece of the glass in the cab, for the material it has now texture_handle mask{null_handle}; float densest{0.f}; // the most metres squared a unit of the uv holds float area{0.f}; // metres squared of the glass diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag index 56ca3a8a6..e4772cb01 100644 --- a/shaders/ogl46/mat_snow_windscreen.frag +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -95,13 +95,6 @@ void main() float snowTr = 0.0; float wet = 0.0; snSlot = int(param[2].z + 0.5) - 1; - // the material without its slot (the opengl renderer may give the glass a fresh copy of the material after the weather - // changed, without it): the first glass whose snow the simulation keeps - for (int s = 0; (snSlot < 0) && (s < WATER_SLOTS); ++s) - { - if (water_header[s].z > 0.5) - snSlot = s; - } if ((snSlot >= 0) && (snSlot < WATER_SLOTS) && water_snow_map(uint(snSlot), snMap)) { // the sprites coming within the texel of the layer at the pixel (water_snowlayer.comp) laid at the pixel, sharp from the diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag index 5bdd3bdfa..43f0c455f 100644 --- a/shaders/vk14/mat_snow_windscreen.frag +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -100,13 +100,6 @@ void main() float snowTr = 0.0; float wet = 0.0; snSlot = int(param[2].z + 0.5) - 1; - // the material without its slot (the opengl renderer may give the glass a fresh copy of the material after the weather - // changed, without it): the first glass whose snow the simulation keeps - for (int s = 0; (snSlot < 0) && (s < WATER_SLOTS); ++s) - { - if (water_header[s].z > 0.5) - snSlot = s; - } if ((snSlot >= 0) && (snSlot < WATER_SLOTS) && water_snow_map(uint(snSlot), snMap)) { // the sprites coming within the texel of the layer at the pixel (water_snowlayer.comp) laid at the pixel, sharp from the From d9980b78f74e0f829a3ac5669f490617ad807996 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 12:22:07 +0100 Subject: [PATCH 109/123] Deer: LocalRandom(), not the seeded random engine of the simulation The spawning, the side, the angle and the first frame of a deer no longer draw from Random(), so they don't shift the simulation of a seeded run. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- world/deer.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/world/deer.cpp b/world/deer.cpp index 9b7949b3b..fae95efda 100644 --- a/world/deer.cpp +++ b/world/deer.cpp @@ -583,7 +583,7 @@ void simulation::deer_herd::update(double const Deltatime) if ((Global.deer_interval > 0.0) && (m_travelled >= Global.deer_interval)) { m_travelled = 0.0; - if ((Random(0.0, 1.0) < Global.deer_chance) && (false == spawn(*vehicle))) + if ((LocalRandom(0.0, 1.0) < Global.deer_chance) && (false == spawn(*vehicle))) { // no flat ground, a switch or a platform there: soon again m_travelled = std::max(0.0, Global.deer_interval - Retrydistance); @@ -669,8 +669,8 @@ bool simulation::deer_herd::spawn(TDynamicObject const &Vehicle) // across the path, a little askew, to the side with flat ground to run away over (one picked at random first) deer animal; animal.start = place.position; - auto const askew{Random(-25.0, 25.0) * std::numbers::pi / 180.0}; - auto const first{Random(0.0, 1.0) < 0.5 ? -1.0 : 1.0}; + auto const askew{LocalRandom(-25.0, 25.0) * std::numbers::pi / 180.0}; + auto const first{LocalRandom(0.0, 1.0) < 0.5 ? -1.0 : 1.0}; auto found{false}; std::string reasons; for (auto const side : {first, -first}) @@ -691,7 +691,7 @@ bool simulation::deer_herd::spawn(TDynamicObject const &Vehicle) return false; } // grazing from a moment of its own - animal.frame = Random(0.0, Grazing.frames); + animal.frame = LocalRandom(0.0, Grazing.frames); animal.time = Timer::GetTime(); animal.model = make_deer(Grazing, place.position, vat_turn(animal.heading, Grazing, 0, animal.frame, animal.time), false); if (animal.model == nullptr) From d896c7d81dd82e74ec554665e8c62624a612f15d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 12:22:07 +0100 Subject: [PATCH 110/123] Windscreens: the insects and the rain the glass meets advance once a frame, not once a view The step is taken in the first view of a frame (the views of a frame share its time); OpenGL 4.6 and Vulkan. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- rendering/opengl46/opengl46renderer.cpp | 7 +++++-- rendering/opengl46/opengl46renderer.h | 1 + rendering/vulkan14/vulkan14frame.cpp | 7 +++++-- rendering/vulkan14/vulkan14renderer.h | 1 + 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index 9858863a3..1c2eeb8b9 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -1714,6 +1714,9 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) // the insects the vehicle meets (mat_bugs_windscreen): none below 20 km/h, above it the more the faster, counted in seconds of // driving at 100 km/h. none in winter, and the rain or the snow washes them off: once it stops (and out of winter) the glass // gets them anew from none, and what the blades left of them before is forgotten + // the glass meets the insects and the rain once a frame, not once a view (the views of a frame have its time) + auto const glassstep{(scene_ubs.time != m_glasssteptime) ? Timer::GetDeltaTime() : 0.0}; + m_glasssteptime = scene_ubs.time; auto const insects{(Global.Season != "winter:") && (Global.Weather != "rain:") && (Global.Weather != "snow:")}; if (false == insects) { @@ -1725,7 +1728,7 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) m_wiperbugs = 0.0; } else if (owner != nullptr) - m_wiperbugs += Timer::GetDeltaTime() * std::max(std::abs(owner->MoverParameters->V) * 3.6 - 20.0, 0.0) / 80.0; + m_wiperbugs += glassstep * std::max(std::abs(owner->MoverParameters->V) * 3.6 - 20.0, 0.0) / 80.0; scene_ubs.rain_wind.w = static_cast(m_wiperbugs); // the rain the glass meets (mat_rain_windscreen): counted in seconds of the heaviest rain standing still, more at speed (the // glass runs into it). the glass fills with it up to as many drops as it gets (a lighter rain only fills it more slowly) while @@ -1733,7 +1736,7 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) { constexpr double fill_rate{0.3}; // per second of the heaviest rain: 95% full in 10 s (20 s at cloud cover 1.5) constexpr double fill_speed{1.5}; // at 100 km/h and more the glass meets x (1 + fill_speed) as much rain - auto const dt{Timer::GetDeltaTime()}; + auto const dt{glassstep}; auto const speed{(owner != nullptr) ? std::min(std::abs(owner->MoverParameters->V) * 3.6 / 100.0, 1.0) : 0.0}; auto const meet{static_cast(percipitation_intensity) * (1.0 + fill_speed * speed)}; m_wiperrain += dt * meet; diff --git a/rendering/opengl46/opengl46renderer.h b/rendering/opengl46/opengl46renderer.h index 445b936c1..11566b7b1 100644 --- a/rendering/opengl46/opengl46renderer.h +++ b/rendering/opengl46/opengl46renderer.h @@ -862,6 +862,7 @@ class opengl46_renderer : public gfx_renderer, public gfx::scene_walk { // the rain the glass met so far and how wet it is (scene_ubs::rain_state) double m_wiperrain{0.0}; double m_glasswet{0.0}; + double m_glasssteptime{-1.0}; // the time of the frame the glass last met the insects and the rain in gl::light_data light_data; std::unordered_map> m_shaders; diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index 6e26f1315..e46602ff5 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -1591,6 +1591,9 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) // the insects the vehicle meets (mat_bugs_windscreen): none below 20 km/h, above it the more the faster, counted in seconds of // driving at 100 km/h. none in winter, and the rain or the snow washes them off: once it stops (and out of winter) the glass // gets them anew from none, and what the blades left of them before is forgotten + // the glass meets the insects and the rain once a frame, not once a view (the views of a frame have its time) + auto const glassstep{(scene_ubs.time != m_glasssteptime) ? Timer::GetDeltaTime() : 0.0}; + m_glasssteptime = scene_ubs.time; auto const insects{(Global.Season != "winter:") && (Global.Weather != "rain:") && (Global.Weather != "snow:")}; if (false == insects) { @@ -1602,7 +1605,7 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) m_wiperbugs = 0.0; } else if (owner != nullptr) - m_wiperbugs += Timer::GetDeltaTime() * std::max(std::abs(owner->MoverParameters->V) * 3.6 - 20.0, 0.0) / 80.0; + m_wiperbugs += glassstep * std::max(std::abs(owner->MoverParameters->V) * 3.6 - 20.0, 0.0) / 80.0; scene_ubs.rain_wind.w = static_cast(m_wiperbugs); // the rain the glass meets (mat_rain_windscreen): counted in seconds of the heaviest rain standing still, more at speed (the // glass runs into it). the glass fills with it up to as many drops as it gets (a lighter rain only fills it more slowly) while @@ -1610,7 +1613,7 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) { constexpr double fill_rate{0.3}; // per second of the heaviest rain: 95% full in 10 s (20 s at cloud cover 1.5) constexpr double fill_speed{1.5}; // at 100 km/h and more the glass meets x (1 + fill_speed) as much rain - auto const dt{Timer::GetDeltaTime()}; + auto const dt{glassstep}; auto const speed{(owner != nullptr) ? std::min(std::abs(owner->MoverParameters->V) * 3.6 / 100.0, 1.0) : 0.0}; auto const meet{static_cast(percipitation_intensity) * (1.0 + fill_speed * speed)}; m_wiperrain += dt * meet; diff --git a/rendering/vulkan14/vulkan14renderer.h b/rendering/vulkan14/vulkan14renderer.h index 477274efc..0c2cf8e26 100644 --- a/rendering/vulkan14/vulkan14renderer.h +++ b/rendering/vulkan14/vulkan14renderer.h @@ -571,6 +571,7 @@ class vulkan14_renderer : public gfx_renderer, public gfx::scene_walk // the rain the glass met so far and how wet it is (scene_ubs::rain_state) double m_wiperrain{0.0}; double m_glasswet{0.0}; + double m_glasssteptime{-1.0}; // the time of the frame the glass last met the insects and the rain in gl::light_data light_data{}; std::uint32_t m_lightcount{1}; // lights written to light_data // the copies of the light buffer in the ring of the frame since the lights were last written, by the header and the sun From ab3b0e1565c6a203a3283efbd2300da14af4a6e6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 12:22:07 +0100 Subject: [PATCH 111/123] Moths: a swarm doesn't flip its visibility at the range of the lamp lights A swarm shown before stays shown while its lamp is out of the lights of the frame by its distance (the range of its node hides it there), so node_state_version changes only when a lamp goes out, not each time the camera passes the range. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- rendering/common/moths.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/rendering/common/moths.cpp b/rendering/common/moths.cpp index 16399b6c7..a4a58208d 100644 --- a/rendering/common/moths.cpp +++ b/rendering/common/moths.cpp @@ -116,7 +116,10 @@ void gfx::moths::update(std::vector const &Lights, glm::dve lookup->second.seen = Framestamp; } } - // the swarms of the lamps lit in this frame are shown + // the swarms of the lamps lit in this frame are shown. a swarm shown before stays so while its lamp is out of the lights of the + // frame by its distance (the range of the swarm, as of its node, hides it there): it changes, and the version of the state of + // the nodes with it, only when its lamp goes out, not each time the camera passes the range of the lights + auto const keepbeyond{static_cast(Global.moths_range) * 0.9}; m_shown = 0; for (auto &lamp : m_lamps) { @@ -125,7 +128,7 @@ void gfx::moths::update(std::vector const &Lights, glm::dve { continue; } - auto const shown{flying && (entry.seen == Framestamp)}; + auto const shown{flying && ((entry.seen == Framestamp) || (entry.model->visible() && (glm::length(entry.position - Camera) > keepbeyond)))}; entry.model->visible(shown); m_shown += (shown ? 1 : 0); } From 05be4bff2941b0174f659f5231e8a4c61bb2e11c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 12:22:07 +0100 Subject: [PATCH 112/123] Windscreen water: the passes of the snow are optional A snow kernel that doesn't compile (as water_snow.comp did on NVIDIA) leaves the glasses of the snow clear and the rain working, instead of disabling the whole simulation (OpenGL 4.6 and Vulkan). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- rendering/opengl46/opengl46water.cpp | 23 +++++++++++++++++------ rendering/vulkan14/vulkan14water.cpp | 23 +++++++++++++++++++---- rendering/vulkan14/vulkan14water.h | 1 + 3 files changed, 37 insertions(+), 10 deletions(-) diff --git a/rendering/opengl46/opengl46water.cpp b/rendering/opengl46/opengl46water.cpp index 457544257..51de7ddff 100644 --- a/rendering/opengl46/opengl46water.cpp +++ b/rendering/opengl46/opengl46water.cpp @@ -73,10 +73,21 @@ bool opengl46_windscreen_water::gpu_init() "water_snowlayer.comp"}; for (std::size_t i = 0; i < names.size(); ++i) { - if (m_programs[i]) - continue; - gl::shader shader(PROGRAM_NAMES[i]); - m_programs[i] = std::make_unique(std::vector>{shader}); + try + { + gl::shader shader(names[i]); + m_programs[i] = std::make_unique(std::vector>{shader}); + } + catch (gl::shader_exception const &e) + { + if (i < pass::snow) + throw; + // the passes of the snow are optional: without them the glasses of the snow stay clear, the rain works on + ErrorLog("windscreen water: can't use " + std::string(names[i]) + ", the glasses of the snow stay clear: " + std::string(e.what())); + m_programs[pass::snow].reset(); + m_programs[pass::snowlayer].reset(); + break; + } } } catch (gl::shader_exception const &e) @@ -172,7 +183,7 @@ bool opengl46_windscreen_water::gpu_bake(std::size_t const Slot, texture_handle bool opengl46_windscreen_water::gpu_snow_layer(std::size_t const Slot, texture_handle const Atlas, texture_handle const Normal, gl::water_ubs const &Block) { - if ((!m_storage) || (Slot >= gl::WATER_SLOTS) || (Atlas == null_handle) || (Normal == null_handle)) + if ((!m_storage) || (!m_programs[pass::snowlayer]) || (Slot >= gl::WATER_SLOTS) || (Atlas == null_handle) || (Normal == null_handle)) return false; auto &atlas{GfxRenderer->Texture(Atlas)}; auto &normal{GfxRenderer->Texture(Normal)}; @@ -224,7 +235,7 @@ void opengl46_windscreen_water::gpu_step(gl::water_ubs const &Block, std::uint32 run(pass::clear, cell_groups); run(pass::grid, drop_groups); // the snow of the glasses of the snow, a texel of their maps a thread - if (Block.snow_slots != glm::vec4{0.f}) + if ((Block.snow_slots != glm::vec4{0.f}) && m_programs[pass::snow]) run(pass::snow, groups(static_cast(gl::WATER_MAP) * gl::WATER_MAP)); gl::program::unbind(); } diff --git a/rendering/vulkan14/vulkan14water.cpp b/rendering/vulkan14/vulkan14water.cpp index 44ebc587e..c6b244bcc 100644 --- a/rendering/vulkan14/vulkan14water.cpp +++ b/rendering/vulkan14/vulkan14water.cpp @@ -89,6 +89,7 @@ void windscreen_water::destroy() m_storage.reset(); m_device = VK_NULL_HANDLE; m_cleared = false; + m_snowkernels = true; reset(); } @@ -105,9 +106,23 @@ bool windscreen_water::gpu_init() "water_snowlayer.comp"}; for (std::size_t i = 0; i < names.size(); ++i) { - if (false == m_kernels[i].create(m_device, *m_pipelines, m_shaders->get(names[i]), m_passlayout, {}, names[i])) + try { - throw gfx::shader_exception(std::string("no compute pipeline of ") + names[i]); + if (false == m_kernels[i].create(m_device, *m_pipelines, m_shaders->get(names[i]), m_passlayout, {}, names[i])) + { + throw gfx::shader_exception(std::string("no compute pipeline of ") + names[i]); + } + } + catch (gfx::shader_exception const &e) + { + if (i < pass::snow) + { + throw; + } + // the passes of the snow are optional: without them the glasses of the snow stay clear, the rain works on + ErrorLog("windscreen water: can't use " + std::string(names[i]) + ", the glasses of the snow stay clear: " + std::string(e.what())); + m_snowkernels = false; + break; } } } @@ -271,7 +286,7 @@ bool windscreen_water::gpu_bake(std::size_t const Slot, texture_handle const Mas bool windscreen_water::gpu_snow_layer(std::size_t const Slot, texture_handle const Atlas, texture_handle const Normal, gl::water_ubs const &Block) { auto const commands{m_host.commands()}; - if ((commands == nullptr) || (false == m_full) || (Slot >= gl::WATER_SLOTS)) + if ((commands == nullptr) || (false == m_full) || (false == m_snowkernels) || (Slot >= gl::WATER_SLOTS)) { return false; } @@ -341,7 +356,7 @@ void windscreen_water::gpu_step(gl::water_ubs const &Block, std::uint32_t const run(pass::clear, cell_groups); run(pass::grid, drop_groups); // the snow of the glasses of the snow, a texel of their maps a thread - if (Block.snow_slots != glm::vec4{0.f}) + if ((Block.snow_slots != glm::vec4{0.f}) && m_snowkernels) { run(pass::snow, groups(static_cast(gl::WATER_MAP) * gl::WATER_MAP)); } diff --git a/rendering/vulkan14/vulkan14water.h b/rendering/vulkan14/vulkan14water.h index 3c50ba915..a6ef05597 100644 --- a/rendering/vulkan14/vulkan14water.h +++ b/rendering/vulkan14/vulkan14water.h @@ -105,6 +105,7 @@ class windscreen_water : public gfx::windscreen_water bool m_raincelltried{false}; bool m_full{false}; // the storage is as large as the simulation needs (else a stand-in, the glasses make their water up) bool m_cleared{false}; + bool m_snowkernels{true}; // the passes of the snow made (they are optional: without them the glasses of the snow stay clear) }; } // namespace vk14 From 6db46bbc8337476c7c8fc94c30097ef5e836537d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 15:58:34 +0100 Subject: [PATCH 113/123] Windscreen snow: the air at speed blows off only thin dry snow, fewer flakes bounce off [skip ci] SNOW_BLOW halved, blown up to 0.25 mm (was 0.6 mm), 15% of the dry flakes bounce off at speed (was 40%): the glass gets covered at 100 km/h too, a little slower than slowly (OpenGL 4.6 and Vulkan). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/water_snow.comp | 6 +++--- shaders/vk14/water_snow.comp | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/shaders/ogl46/water_snow.comp b/shaders/ogl46/water_snow.comp index 1ca6a8c5a..96b6fbfc5 100644 --- a/shaders/ogl46/water_snow.comp +++ b/shaders/ogl46/water_snow.comp @@ -62,7 +62,7 @@ const float SNOW_FILM_DRY = 0.15; // how fast slush slides down a vertical glass, how fast dry powder goes with the air (a share of the speed of the air along the // glass), how fast the film of water runs down a vertical glass and goes with the air, m/s const float SNOW_SLIDE = 0.03; -const float SNOW_BLOW = 0.001; +const float SNOW_BLOW = 0.0005; const float SNOW_RUN = 0.02; const float SNOW_RUN_AIR = 0.002; @@ -195,7 +195,7 @@ vec4 snow_motion(ivec2 texel, vec4 state) float wet = state.y / (state.y + state.x * density + 1e-4); // slush: wet and heavy enough to go; dry powder: loose and thin enough to be blown float slide = SNOW_SLIDE * smoothstep(0.25, 0.7, wet) * smoothstep(2.0, 8.0, state.x); - float blow = SNOW_BLOW * smoothstep(10.0, 25.0, wind) * (1.0 - state.z) * (1.0 - smoothstep(0.1, 0.3, wet)) * (1.0 - smoothstep(0.2, 0.6, state.x)); + float blow = SNOW_BLOW * smoothstep(10.0, 25.0, wind) * (1.0 - state.z) * (1.0 - smoothstep(0.1, 0.3, wet)) * (1.0 - smoothstep(0.08, 0.25, state.x)); vec3 snow = slope * slide + air * blow; // the film of water runs where there's enough of it, not the water soaked into the snow float film = (1.0 - smoothstep(0.5, 3.0, state.x)); @@ -313,7 +313,7 @@ void main() // water stay // (only on a bare glass: a flake sticks to the snow already there) float dry = (1.0 - smoothstep(0.1, 0.4, wet)) * (1.0 - smoothstep(-3.0, 0.0, water_up.w)) * (1.0 - smoothstep(0.05, 0.3, state.x)); - float sticking = 1.0 - 0.4 * smoothstep(5.0, 25.0, speed) * dry; + float sticking = 1.0 - 0.15 * smoothstep(5.0, 25.0, speed) * dry; float landings = water_snow.x * SNOW_FALL_SHARE / max(water_air.w, 0.1) * facing * area * seconds * sticking; vec4 random = water_random(place, snow_slot, water_counts.x, 0x5e0du); float count = min(floor(landings) + ((random.x < fract(landings)) ? 1.0 : 0.0), 4.0); diff --git a/shaders/vk14/water_snow.comp b/shaders/vk14/water_snow.comp index b7620c7ab..e4497b2e6 100644 --- a/shaders/vk14/water_snow.comp +++ b/shaders/vk14/water_snow.comp @@ -65,7 +65,7 @@ const float SNOW_FILM_DRY = 0.15; // how fast slush slides down a vertical glass, how fast dry powder goes with the air (a share of the speed of the air along the // glass), how fast the film of water runs down a vertical glass and goes with the air, m/s const float SNOW_SLIDE = 0.03; -const float SNOW_BLOW = 0.001; +const float SNOW_BLOW = 0.0005; const float SNOW_RUN = 0.02; const float SNOW_RUN_AIR = 0.002; @@ -198,7 +198,7 @@ vec4 snow_motion(ivec2 texel, vec4 state) float wet = state.y / (state.y + state.x * density + 1e-4); // slush: wet and heavy enough to go; dry powder: loose and thin enough to be blown float slide = SNOW_SLIDE * smoothstep(0.25, 0.7, wet) * smoothstep(2.0, 8.0, state.x); - float blow = SNOW_BLOW * smoothstep(10.0, 25.0, wind) * (1.0 - state.z) * (1.0 - smoothstep(0.1, 0.3, wet)) * (1.0 - smoothstep(0.2, 0.6, state.x)); + float blow = SNOW_BLOW * smoothstep(10.0, 25.0, wind) * (1.0 - state.z) * (1.0 - smoothstep(0.1, 0.3, wet)) * (1.0 - smoothstep(0.08, 0.25, state.x)); vec3 snow = slope * slide + air * blow; // the film of water runs where there's enough of it, not the water soaked into the snow float film = (1.0 - smoothstep(0.5, 3.0, state.x)); @@ -316,7 +316,7 @@ void main() // water stay // (only on a bare glass: a flake sticks to the snow already there) float dry = (1.0 - smoothstep(0.1, 0.4, wet)) * (1.0 - smoothstep(-3.0, 0.0, water_up.w)) * (1.0 - smoothstep(0.05, 0.3, state.x)); - float sticking = 1.0 - 0.4 * smoothstep(5.0, 25.0, speed) * dry; + float sticking = 1.0 - 0.15 * smoothstep(5.0, 25.0, speed) * dry; float landings = water_snow.x * SNOW_FALL_SHARE / max(water_air.w, 0.1) * facing * area * seconds * sticking; vec4 random = water_random(place, snow_slot, water_counts.x, 0x5e0du); float count = min(floor(landings) + ((random.x < fract(landings)) ? 1.0 : 0.0), 4.0); From 44eedbbc97ae5695363e2bda77a232b29821d260 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 09:33:50 +0100 Subject: [PATCH 114/123] Windscreen snow: five grids of lumps, six sprites a texel at most, lighter to lay [skip ci] Laying the sprites took most of the snow on the glass (a covered glass ~1.0 ms at 2560x1440): nine grids, each covering the glass a few times over, put many sprites one on another at a pixel. Five grids (the same sizes and tiles, the snow they need from 0.02 to 2.6 mm) still close the glass; the layer lists at most six sprites a texel, two flakes and the top lumps (those under them are covered): ~0.6 ms. Also the flakes as glassy as 0.5 (were 0.35), the lumps of thin snow at most 0.88 opaque so the flakes under them show through, and a sprite reads the snow of the texel of the map under its centre (two reads, not eight). OpenGL 4.6 and Vulkan. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/snow_sprites.glsl | 38 +++++++++++++++++++-------------- shaders/vk14/snow_sprites.glsl | 38 +++++++++++++++++++-------------- 2 files changed, 44 insertions(+), 32 deletions(-) diff --git a/shaders/ogl46/snow_sprites.glsl b/shaders/ogl46/snow_sprites.glsl index 0ba2a38e8..1942ecb27 100644 --- a/shaders/ogl46/snow_sprites.glsl +++ b/shaders/ogl46/snow_sprites.glsl @@ -17,8 +17,9 @@ const float snow_heap_cells = 2.85; // the heaps the lumps come in, cells of th const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) const float snow_ice = 0.75; // opacity of a lump until the snow gets thick (icy: the picture shows through, bent) const vec3 snow_ice_tint = vec3(0.93, 0.97, 1.0); // the colour of the icy snow -const float snow_thin = 0.35; // opacity of the most glassy flake; each flake is at random from it to fully white +const float snow_thin = 0.5; // opacity of the most glassy flake; each flake is at random from it to fully white const float snow_glassy = 0.45; // opacity of the most glassy lump until the snow gets thick; each lump from it to fully white +const float snow_lump_white = 0.88; // opacity of the whitest lump until the snow gets thick (the flakes under it show through) const float snow_bump = 1.0; // strength of the relief from the normal map, 0 = flat const float snow_gloss = 0.8; // glints of the sun / headlights on the wet snow, 0 = matt const float snow_ice_bend = 1.0; // how strongly the icy snow bends the picture behind it, of the bend of a drop @@ -78,6 +79,13 @@ float snTileSize() return snBig ? 0.25 : 0.5; } +// the snow under the middle of a sprite: the texel of the map there, not filtered between four (a sprite reads it once for all +// of its pixels, so it changes nothing of its shape; two reads of the storage instead of eight, for each sprite of each pixel) +vec4 snSnowAt(vec2 uv) +{ + return water_snow_texel(uint(snSlot), snMap, ivec2(floor(uv * float(WATER_MAP)))); +} + // how white a sprite is (0 glassy, stuck and half melted, 1 dry powder), at random from its Random, whiter where the snow is // Thick (0 .. 1); another number than Random, so it goes its own way of the tone float snWhite(float random, float thick) @@ -182,17 +190,15 @@ const int sn_lump_tiles[12] = int[12](2, 3, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15); // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before, in the order they are laid // (front to back, the top one first): all of them icy fleece (the dense puffs and clumps, tiles 2-5, 8, 9), more and bigger, closing // the glass by 2-3 mm; now and then a single lump of packed snow on top (tiles 10-15) -const int SN_GRIDS = 9; +const int SN_GRIDS = 5; const lump_grid sn_grids[SN_GRIDS] = lump_grid[SN_GRIDS]( lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 6, 6, 0.03), - lump_grid(vec2(0.75), 251u, vec2(1.4, 2.8), vec2(2.0, 3.0), 2, 4, 1.0), - lump_grid(vec2(0.0, 0.5), 233u, vec2(1.2, 2.4), vec2(2.0, 3.0), 0, 6, 1.0), - lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.0), vec2(2.0, 3.0), 0, 6, 1.0), - lump_grid(vec2(0.75, 0.25), 151u, vec2(0.7, 1.6), vec2(1.8, 2.8), 2, 4, 1.0), - lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.8, 2.8), 2, 4, 1.0), - lump_grid(vec2(0.25), 97u, vec2(0.2, 0.9), vec2(1.4, 2.4), 2, 4, 1.0), - lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(1.4, 2.4), 2, 4, 1.0), - lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(1.2, 2.0), 2, 4, 1.0)); + lump_grid(vec2(0.75), 251u, vec2(1.0, 2.6), vec2(2.0, 3.0), 2, 4, 1.0), + lump_grid(vec2(0.0, 0.5), 233u, vec2(0.6, 1.8), vec2(2.0, 3.0), 0, 6, 1.0), + lump_grid(vec2(0.75, 0.25), 151u, vec2(0.2, 1.0), vec2(1.8, 2.8), 2, 4, 1.0), + lump_grid(vec2(0.0), 31u, vec2(0.02, 0.5), vec2(1.4, 2.4), 2, 4, 1.0)); +// (nine grids before: each grid alone covers the glass a few times over, so five close it as well, with fewer sprites one on +// another at a pixel) const float SN_COVERED = 0.998; // the snow over the pixel covering it: the sprites under it are not looked at @@ -215,7 +221,7 @@ bool snFlakeCell(vec2 p, ivec2 cell, vec2 perUV, float pixelUV, float reach, ino vec2 local; if (false == snLocal(p, centre, sizeDraw * 1.4 + 2.0 * reach, vec2(1.0), rot, flip, 1.0, local)) return false; - vec4 q = water_snow_at(uint(snSlot), snMap, centre / perUV); + vec4 q = snSnowAt(centre / perUV); // only the dry snow has its flakes: no drops of the melted ones (the round drops and the wet lumps with their film, tiles 8, 9, // 14, 15, aren't used) bool drop = false; @@ -261,7 +267,7 @@ bool snLumpCell(vec2 p, ivec2 cell, vec2 perUV, lump_grid grid, float pixelUV, f return false; // the snow it takes, sooner in a heap float needs = mix(grid.snow.x, grid.snow.y, needsDraw) * mix(1.4, 0.6, snHeap(cell)); - vec4 q = water_snow_at(uint(snSlot), snMap, (centre - grid.shift) / perUV); + vec4 q = snSnowAt((centre - grid.shift) / perUV); if (q.x <= needs) return false; float size = sizeDraw * mix(snow_lump_grow.x, snow_lump_grow.y, smoothstep(needs, needs * 2.0 + 0.2, q.x)); @@ -272,7 +278,7 @@ bool snLumpCell(vec2 p, ivec2 cell, vec2 perUV, lump_grid grid, float pixelUV, f // fading in over the first snow (no flicker on the edge), opaque when thick; the thick snow bends nothing float deep = smoothstep(snow_cover * 3.0, snow_deep, q.x); float white = snWhite(random, smoothstep(snow_cover, snow_deep, q.x)); - float alpha = smoothstep(needs, needs + 0.04, q.x) * mix(mix(snow_glassy, 1.0, white), 1.0, deep); + float alpha = smoothstep(needs, needs + 0.04, q.x) * mix(mix(snow_glassy, snow_lump_white, white), 1.0, deep); vec3 tone = mix(snTone(q, random), vec3(1.0), white * 0.6); snSprite(local, tile, alpha, tone, rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), (1.0 - deep) * (1.0 - white), acc); return true; @@ -343,7 +349,7 @@ snow_layer_s snCompose(vec2 uv, vec2 span, float pixelUV) // 1 + the list (0 the flakes, 1 .. SN_GRIDS the grids of the lumps) times 16 + the cell around the texel (0 .. 8: 1 - the column // offset + 3 * (1 - the row offset)), 0 after the last one (a layer cleared to zeros lists nothing). the glass lays only those at // its pixels, sharp from the atlas as when it laid all of the cells around itself, at a fraction of the cost -const int SN_REFS = 16; +const int SN_REFS = 6; // the top ones: those under them are covered (sixteen fit in the four uint) // the sprites over a texel covering it on the whole (the level of the atlas the size of the texel): those under it are left out const float SN_LIST_COVERED = 0.97; @@ -374,8 +380,8 @@ uvec4 snList(vec2 uv, vec2 span, float pixelUV) float reachF = half_diagonal * max(perF.x, perF.y) * 1.25; for (int k = 0; k < 9; ++k) { - if (snFlakeCell(pF, hereF + ivec2(1 - k % 3, 1 - k / 3), perF, pixelUV, reachF, flakes)) - snRef(uint(k), refs, count); + if ((count < 2) && snFlakeCell(pF, hereF + ivec2(1 - k % 3, 1 - k / 3), perF, pixelUV, reachF, flakes)) + snRef(uint(k), refs, count); // two flakes at most, the rest of the list for the lumps } vec2 perL = span / snow_lump_cell; float reachL = half_diagonal * max(perL.x, perL.y) * 1.25 + 0.05; diff --git a/shaders/vk14/snow_sprites.glsl b/shaders/vk14/snow_sprites.glsl index 0ba2a38e8..1942ecb27 100644 --- a/shaders/vk14/snow_sprites.glsl +++ b/shaders/vk14/snow_sprites.glsl @@ -17,8 +17,9 @@ const float snow_heap_cells = 2.85; // the heaps the lumps come in, cells of th const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) const float snow_ice = 0.75; // opacity of a lump until the snow gets thick (icy: the picture shows through, bent) const vec3 snow_ice_tint = vec3(0.93, 0.97, 1.0); // the colour of the icy snow -const float snow_thin = 0.35; // opacity of the most glassy flake; each flake is at random from it to fully white +const float snow_thin = 0.5; // opacity of the most glassy flake; each flake is at random from it to fully white const float snow_glassy = 0.45; // opacity of the most glassy lump until the snow gets thick; each lump from it to fully white +const float snow_lump_white = 0.88; // opacity of the whitest lump until the snow gets thick (the flakes under it show through) const float snow_bump = 1.0; // strength of the relief from the normal map, 0 = flat const float snow_gloss = 0.8; // glints of the sun / headlights on the wet snow, 0 = matt const float snow_ice_bend = 1.0; // how strongly the icy snow bends the picture behind it, of the bend of a drop @@ -78,6 +79,13 @@ float snTileSize() return snBig ? 0.25 : 0.5; } +// the snow under the middle of a sprite: the texel of the map there, not filtered between four (a sprite reads it once for all +// of its pixels, so it changes nothing of its shape; two reads of the storage instead of eight, for each sprite of each pixel) +vec4 snSnowAt(vec2 uv) +{ + return water_snow_texel(uint(snSlot), snMap, ivec2(floor(uv * float(WATER_MAP)))); +} + // how white a sprite is (0 glassy, stuck and half melted, 1 dry powder), at random from its Random, whiter where the snow is // Thick (0 .. 1); another number than Random, so it goes its own way of the tone float snWhite(float random, float thick) @@ -182,17 +190,15 @@ const int sn_lump_tiles[12] = int[12](2, 3, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15); // the grids of the lumps, coming one after the other as the snow piles up, each on the ones before, in the order they are laid // (front to back, the top one first): all of them icy fleece (the dense puffs and clumps, tiles 2-5, 8, 9), more and bigger, closing // the glass by 2-3 mm; now and then a single lump of packed snow on top (tiles 10-15) -const int SN_GRIDS = 9; +const int SN_GRIDS = 5; const lump_grid sn_grids[SN_GRIDS] = lump_grid[SN_GRIDS]( lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 6, 6, 0.03), - lump_grid(vec2(0.75), 251u, vec2(1.4, 2.8), vec2(2.0, 3.0), 2, 4, 1.0), - lump_grid(vec2(0.0, 0.5), 233u, vec2(1.2, 2.4), vec2(2.0, 3.0), 0, 6, 1.0), - lump_grid(vec2(0.5, 0.0), 199u, vec2(1.0, 2.0), vec2(2.0, 3.0), 0, 6, 1.0), - lump_grid(vec2(0.75, 0.25), 151u, vec2(0.7, 1.6), vec2(1.8, 2.8), 2, 4, 1.0), - lump_grid(vec2(0.25, 0.75), 113u, vec2(0.4, 1.2), vec2(1.8, 2.8), 2, 4, 1.0), - lump_grid(vec2(0.25), 97u, vec2(0.2, 0.9), vec2(1.4, 2.4), 2, 4, 1.0), - lump_grid(vec2(0.5), 77u, vec2(0.15, 0.7), vec2(1.4, 2.4), 2, 4, 1.0), - lump_grid(vec2(0.0), 31u, vec2(0.02, 0.35), vec2(1.2, 2.0), 2, 4, 1.0)); + lump_grid(vec2(0.75), 251u, vec2(1.0, 2.6), vec2(2.0, 3.0), 2, 4, 1.0), + lump_grid(vec2(0.0, 0.5), 233u, vec2(0.6, 1.8), vec2(2.0, 3.0), 0, 6, 1.0), + lump_grid(vec2(0.75, 0.25), 151u, vec2(0.2, 1.0), vec2(1.8, 2.8), 2, 4, 1.0), + lump_grid(vec2(0.0), 31u, vec2(0.02, 0.5), vec2(1.4, 2.4), 2, 4, 1.0)); +// (nine grids before: each grid alone covers the glass a few times over, so five close it as well, with fewer sprites one on +// another at a pixel) const float SN_COVERED = 0.998; // the snow over the pixel covering it: the sprites under it are not looked at @@ -215,7 +221,7 @@ bool snFlakeCell(vec2 p, ivec2 cell, vec2 perUV, float pixelUV, float reach, ino vec2 local; if (false == snLocal(p, centre, sizeDraw * 1.4 + 2.0 * reach, vec2(1.0), rot, flip, 1.0, local)) return false; - vec4 q = water_snow_at(uint(snSlot), snMap, centre / perUV); + vec4 q = snSnowAt(centre / perUV); // only the dry snow has its flakes: no drops of the melted ones (the round drops and the wet lumps with their film, tiles 8, 9, // 14, 15, aren't used) bool drop = false; @@ -261,7 +267,7 @@ bool snLumpCell(vec2 p, ivec2 cell, vec2 perUV, lump_grid grid, float pixelUV, f return false; // the snow it takes, sooner in a heap float needs = mix(grid.snow.x, grid.snow.y, needsDraw) * mix(1.4, 0.6, snHeap(cell)); - vec4 q = water_snow_at(uint(snSlot), snMap, (centre - grid.shift) / perUV); + vec4 q = snSnowAt((centre - grid.shift) / perUV); if (q.x <= needs) return false; float size = sizeDraw * mix(snow_lump_grow.x, snow_lump_grow.y, smoothstep(needs, needs * 2.0 + 0.2, q.x)); @@ -272,7 +278,7 @@ bool snLumpCell(vec2 p, ivec2 cell, vec2 perUV, lump_grid grid, float pixelUV, f // fading in over the first snow (no flicker on the edge), opaque when thick; the thick snow bends nothing float deep = smoothstep(snow_cover * 3.0, snow_deep, q.x); float white = snWhite(random, smoothstep(snow_cover, snow_deep, q.x)); - float alpha = smoothstep(needs, needs + 0.04, q.x) * mix(mix(snow_glassy, 1.0, white), 1.0, deep); + float alpha = smoothstep(needs, needs + 0.04, q.x) * mix(mix(snow_glassy, snow_lump_white, white), 1.0, deep); vec3 tone = mix(snTone(q, random), vec3(1.0), white * 0.6); snSprite(local, tile, alpha, tone, rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), (1.0 - deep) * (1.0 - white), acc); return true; @@ -343,7 +349,7 @@ snow_layer_s snCompose(vec2 uv, vec2 span, float pixelUV) // 1 + the list (0 the flakes, 1 .. SN_GRIDS the grids of the lumps) times 16 + the cell around the texel (0 .. 8: 1 - the column // offset + 3 * (1 - the row offset)), 0 after the last one (a layer cleared to zeros lists nothing). the glass lays only those at // its pixels, sharp from the atlas as when it laid all of the cells around itself, at a fraction of the cost -const int SN_REFS = 16; +const int SN_REFS = 6; // the top ones: those under them are covered (sixteen fit in the four uint) // the sprites over a texel covering it on the whole (the level of the atlas the size of the texel): those under it are left out const float SN_LIST_COVERED = 0.97; @@ -374,8 +380,8 @@ uvec4 snList(vec2 uv, vec2 span, float pixelUV) float reachF = half_diagonal * max(perF.x, perF.y) * 1.25; for (int k = 0; k < 9; ++k) { - if (snFlakeCell(pF, hereF + ivec2(1 - k % 3, 1 - k / 3), perF, pixelUV, reachF, flakes)) - snRef(uint(k), refs, count); + if ((count < 2) && snFlakeCell(pF, hereF + ivec2(1 - k % 3, 1 - k / 3), perF, pixelUV, reachF, flakes)) + snRef(uint(k), refs, count); // two flakes at most, the rest of the list for the lumps } vec2 perL = span / snow_lump_cell; float reachL = half_diagonal * max(perL.x, perL.y) * 1.25 + 0.05; From 29dcfd37696652ccce63e0376735fd28cd9b244e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 12:37:29 +0100 Subject: [PATCH 115/123] Drop what the rebase fix-up c0ebdd5 brought back that the base no longer has The second "null" renderer branch of select_gfx_backend(), the opaque text displays (Render_text) and the catch of std::exception in scenarioloader_mode::update(): the base's own code again (std::runtime_error, its own null branch). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- application/application.cpp | 7 +------ application/scenarioloadermode.cpp | 2 +- rendering/common/scenewalk.cpp | 29 ++--------------------------- rendering/common/scenewalk.h | 1 - 4 files changed, 4 insertions(+), 35 deletions(-) diff --git a/application/application.cpp b/application/application.cpp index e8624b9e4..6b3cc4a8f 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -1538,12 +1538,7 @@ void eu07_application::select_gfx_backend() auto *factory{gfx_renderer_factory::get_instance()}; m_gfxbackend = nullptr; - if (Global.GfxRenderer == "null") - { - // draws nothing and loads no textures (test mode) - m_gfxbackend = factory->backend("null"); - } - else if (Global.GfxRenderer == "vulkan") + if (Global.GfxRenderer == "vulkan") { // a renderer which can't run here falls back to opengl, so a setting in eu07.ini doesn't leave the user with a black screen std::string reason; diff --git a/application/scenarioloadermode.cpp b/application/scenarioloadermode.cpp index 349ff691f..85f81a337 100644 --- a/application/scenarioloadermode.cpp +++ b/application/scenarioloadermode.cpp @@ -71,7 +71,7 @@ bool scenarioloader_mode::update() { } // the file it can't read, as the parser and the scenery opening report it; invalid_scenery_exception is one of these, and so is // what the file system throws - catch (std::exception const &e) { + catch (std::runtime_error const &e) { ErrorLog(std::format("Bad init: scenario \"{}\" couldn't be opened ({})", Global.SceneryFile, e.what())); state.reset(); if (Global.test.enabled) { diff --git a/rendering/common/scenewalk.cpp b/rendering/common/scenewalk.cpp index 1b0cf12e3..de01564f4 100644 --- a/rendering/common/scenewalk.cpp +++ b/rendering/common/scenewalk.cpp @@ -2297,17 +2297,9 @@ void scene_walk::Render(TSubModel *Submodel) } } } - if (Submodel->Child != nullptr && (TSubModel::iAlpha & Submodel->iFlags & 0x001F0000)) - { - if (Submodel->eType == TP_TEXT) - { // the opaque characters of a text display, drawn with depth like the rest of the opaque geometry - Render_text(Submodel); - } - else - { + if (Submodel->Child != nullptr) + if (Submodel->iAlpha & Submodel->iFlags & 0x001F0000) Render(Submodel->Child); - } - } if (Submodel->iFlags & 0xC000) { @@ -3175,23 +3167,6 @@ bool scene_walk::Render_Alpha(TModel3d *Model, material_data const *Material, fl return result; } -// opaque characters of a text display, laid out in a row the same way as the translucent ones -void scene_walk::Render_text(TSubModel *Submodel) -{ - if (TSubModel::pasText == nullptr) - { - return; - } - ::glPushMatrix(); - for (auto *p : Submodel->text_letters(*TSubModel::pasText)) - { - Render(p); - if (p->fMatrix) - ::glMultMatrixf(p->fMatrix->readArray()); // move on to the place of the next character - } - ::glPopMatrix(); -} - // characters of a text display, laid out in a row. the text can be encoded in utf-8 or in windows-1250 void scene_walk::Render_Alpha_text(TSubModel *Submodel) { diff --git a/rendering/common/scenewalk.h b/rendering/common/scenewalk.h index 111fa73fb..0db605644 100644 --- a/rendering/common/scenewalk.h +++ b/rendering/common/scenewalk.h @@ -190,7 +190,6 @@ class scene_walk bool Render_Alpha(TModel3d *Model, material_data const *Material, float const Squaredistance, glm::dvec3 const &Position, glm::vec3 const &Angle); bool Render_Alpha(TModel3d *Model, material_data const *Material, float const Squaredistance); void Render_Alpha(TSubModel *Submodel); - void Render_text(TSubModel *Submodel); // opaque characters of a text display void Render_Alpha_text(TSubModel *Submodel); // characters of a text display // TDynamicObject::renderme as the walk sets and reads it: the walk keeps its own while the passes are walked by several threads at From a9579a9841d4274adca7286138c878efee5a612f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 12:39:00 +0100 Subject: [PATCH 116/123] Rebase onto staging (after #468): the water programs made ahead with the snow passes and the rain cells - opengl46water: the two passes of the snow join PROGRAM_NAMES and prepare_next() (#476), optional as before: one which doesn't compile leaves the snow out (both passes) and the rain working; rain_cells.comp is made ahead too (its storage still waits for the first rain), so the first rain doesn't compile it in the middle of a frame; program_count() counts it - vulkan14indirect: the path of the materials with their own shadow program passes the pending flag of multidraw_program() - opengl46renderer.h: staging's shader_prewarm kept with m_ownvertexprograms / m_materialshadowprograms Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- rendering/opengl46/opengl46renderer.h | 19 ++++ rendering/opengl46/opengl46water.cpp | 129 ++++++++++++++---------- rendering/opengl46/opengl46water.h | 8 ++ rendering/vulkan14/vulkan14indirect.cpp | 9 +- 4 files changed, 108 insertions(+), 57 deletions(-) diff --git a/rendering/opengl46/opengl46renderer.h b/rendering/opengl46/opengl46renderer.h index 11566b7b1..51cafb603 100644 --- a/rendering/opengl46/opengl46renderer.h +++ b/rendering/opengl46/opengl46renderer.h @@ -658,6 +658,25 @@ class opengl46_renderer : public gfx_renderer, public gfx::scene_walk { // the material programs with a vertex shader of their own (mat_.vert), and their programs of the sun shadows std::unordered_set m_ownvertexprograms; std::unordered_map> m_materialshadowprograms[ 2 ]; + // Prewarm_Shaders(): the programs to draw with, the next one, and a small target of the formats of the colour pass with a + // triangle of no area to draw + struct shader_prewarm + { + bool started{ false }; + std::vector programs; + std::size_t next{ 0 }; + std::size_t water{ 0 }; // programs of the windscreen water made ahead + bool water_done{ false }; + std::unique_ptr color; + std::unique_ptr depth; + std::unique_ptr motion; + std::unique_ptr target; + // one model block for the variants of the multi draws, which read theirs from a storage buffer (MODEL_DRAW_SSBO_BINDING) + std::unique_ptr draws; + gfx::geometrybank_handle bank{}; + gfx::geometry_handle triangle{}; + }; + shader_prewarm m_prewarm; std::unique_ptr m_prepass_multidraw_shader; std::unique_ptr m_prepass_alpha_multidraw_shader; std::unique_ptr m_shadow_multidraw_shader; // and of the sun shadows diff --git a/rendering/opengl46/opengl46water.cpp b/rendering/opengl46/opengl46water.cpp index 51de7ddff..50d692c08 100644 --- a/rendering/opengl46/opengl46water.cpp +++ b/rendering/opengl46/opengl46water.cpp @@ -15,6 +15,8 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include +#include +#include namespace { @@ -38,63 +40,89 @@ bool kernel_texture(ITexture &Texture) namespace { -// the programs of the passes, in their order (opengl46_windscreen_water::pass) -constexpr std::array PROGRAM_NAMES{"water_trail.comp", "water_spawn.comp", "water_move.comp", "water_clear.comp", "water_grid.comp", - "water_merge.comp", "water_gather.comp", "water_settle.comp", "water_bake.comp"}; +// the programs of the passes, in their order (opengl46_windscreen_water::pass). the passes of the snow (from pass::snow on) are +// optional: without them the glasses of the snow stay clear and the rain works on +constexpr std::array PROGRAM_NAMES{"water_trail.comp", "water_spawn.comp", "water_move.comp", "water_clear.comp", "water_grid.comp", + "water_merge.comp", "water_gather.comp", "water_settle.comp", "water_bake.comp", "water_snow.comp", + "water_snowlayer.comp"}; } // namespace +// the program of a pass made; false when it doesn't compile (a pass of the snow then leaves the snow out, both of its passes) +bool opengl46_windscreen_water::make_program(std::size_t const Index) +{ + try + { + gl::shader shader(PROGRAM_NAMES[Index]); + m_programs[Index] = std::make_unique(std::vector>{shader}); + return true; + } + catch (gl::shader_exception const &e) + { + if (Index >= pass::snow) + { + ErrorLog("windscreen water: can't use " + std::string(PROGRAM_NAMES[Index]) + ", the glasses of the snow stay clear: " + std::string(e.what())); + m_nosnow = true; + m_programs[pass::snow].reset(); + m_programs[pass::snowlayer].reset(); + } + else + { + ErrorLog("windscreen water: " + std::string(PROGRAM_NAMES[Index]) + " not made: " + std::string(e.what())); + } + return false; + } +} + +// the program of the cells of the rain (rain_cells.comp) made, once; its storage waits for the first rain (update_rain_cells()) +void opengl46_windscreen_water::make_rain_cells_program() +{ + if (m_raincelltried) + return; + m_raincelltried = true; + try + { + gl::shader shader("rain_cells.comp"); + m_raincellprogram = std::make_unique(std::vector>{shader}); + } + catch (gl::shader_exception const &e) + { + ErrorLog("rain cells: can't use rain_cells.comp, the glasses with rain stay dry: " + std::string(e.what())); + m_raincellprogram.reset(); + } +} + bool opengl46_windscreen_water::prepare_next() { static_assert(PROGRAM_NAMES.size() == pass::count, "a name for every pass of the water"); - auto const missing{std::ranges::find_if(m_programs, [](std::unique_ptr const &Program) { return Program == nullptr; })}; - if (missing == m_programs.end()) - return false; - auto const index{static_cast(std::distance(m_programs.begin(), missing))}; - try + for (std::size_t index = 0; index < PROGRAM_NAMES.size(); ++index) { - gl::shader shader(PROGRAM_NAMES[index]); - *missing = std::make_unique(std::vector>{shader}); + if (m_programs[index] || ((index >= pass::snow) && m_nosnow)) + continue; + // a pass of the water which doesn't compile is left to gpu_init(), which goes without the simulation + return (make_program(index) || (index >= pass::snow)); } - catch (gl::shader_exception const &e) + // the cells of the rain made ahead as well, so the first rain doesn't compile them in the middle of a frame + if (false == m_raincelltried) { - // left to gpu_init(), which tells of it and goes without the simulation - ErrorLog("windscreen water: " + std::string(PROGRAM_NAMES[index]) + " not made ahead: " + std::string(e.what())); - return false; + make_rain_cells_program(); + return true; } - return true; + return false; } bool opengl46_windscreen_water::gpu_init() { - try + // the ones made ahead (prepare_next()) are kept + for (std::size_t i = 0; i < PROGRAM_NAMES.size(); ++i) { - std::array const names{"water_trail.comp", "water_spawn.comp", "water_move.comp", "water_clear.comp", "water_grid.comp", - "water_merge.comp", "water_gather.comp", "water_settle.comp", "water_bake.comp", "water_snow.comp", - "water_snowlayer.comp"}; - for (std::size_t i = 0; i < names.size(); ++i) + if (m_programs[i] || ((i >= pass::snow) && m_nosnow)) + continue; + if ((false == make_program(i)) && (i < pass::snow)) { - try - { - gl::shader shader(names[i]); - m_programs[i] = std::make_unique(std::vector>{shader}); - } - catch (gl::shader_exception const &e) - { - if (i < pass::snow) - throw; - // the passes of the snow are optional: without them the glasses of the snow stay clear, the rain works on - ErrorLog("windscreen water: can't use " + std::string(names[i]) + ", the glasses of the snow stay clear: " + std::string(e.what())); - m_programs[pass::snow].reset(); - m_programs[pass::snowlayer].reset(); - break; - } + ErrorLog("windscreen water: can't use the programs of the simulation"); + return false; } } - catch (gl::shader_exception const &e) - { - ErrorLog("windscreen water: can't use the programs of the simulation: " + std::string(e.what())); - return false; - } m_storage = std::make_unique(static_cast(gl::WATER_STORAGE_SIZE), gl::WATER_SSBO_BINDING); ::glClearNamedBufferData(*m_storage, GL_R32UI, GL_RED_INTEGER, GL_UNSIGNED_INT, nullptr); m_block = std::make_unique(sizeof(gl::water_ubs), gl::WATER_UBO_BINDING); @@ -113,23 +141,12 @@ void opengl46_windscreen_water::update_rain_cells(float const Time, float const { if (Rain <= 0.f) return; - if (false == m_raincelltried) - { - m_raincelltried = true; - try - { - gl::shader shader("rain_cells.comp"); - m_raincellprogram = std::make_unique(std::vector>{shader}); - m_raincells = std::make_unique(static_cast(gl::RAIN_CELLS_COUNT * 16), gl::RAIN_CELLS_SSBO_BINDING); - } - catch (gl::shader_exception const &e) - { - ErrorLog("rain cells: can't use rain_cells.comp, the glasses with rain stay dry: " + std::string(e.what())); - m_raincellprogram.reset(); - } - } - if ((!m_raincellprogram) || (!m_raincells)) + make_rain_cells_program(); + if (!m_raincellprogram) return; + // the storage of the cells made at the first rain + if (!m_raincells) + m_raincells = std::make_unique(static_cast(gl::RAIN_CELLS_COUNT * 16), gl::RAIN_CELLS_SSBO_BINDING); // the glasses of the frame before read the cells, this one writes them ::glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); m_raincells->bind_base(); diff --git a/rendering/opengl46/opengl46water.h b/rendering/opengl46/opengl46water.h index d52737b9c..f0c33d08e 100644 --- a/rendering/opengl46/opengl46water.h +++ b/rendering/opengl46/opengl46water.h @@ -30,6 +30,10 @@ class opengl46_windscreen_water : public gfx::windscreen_water // the drops and the rivulets of the cells of the glasses with rain (mat_rain_windscreen, rain_cells.comp) worked out for the // time of the frame (scene_ubs.time), once a frame before the passes; nothing while it doesn't rain void update_rain_cells(float Time, float Rain); + // the next of the programs of the simulation compiled ahead of its first step (a few seconds each where the driver has none + // of them kept, at the first start of a new version), so the loading screen stays while they're made. false once all are + bool prepare_next(); + static constexpr std::size_t program_count() { return pass::count + 1; } // the passes and the cells of the rain protected: bool gpu_init() override; @@ -61,4 +65,8 @@ class opengl46_windscreen_water : public gfx::windscreen_water std::unique_ptr m_raincellprogram; std::unique_ptr m_raincells; bool m_raincelltried{false}; + bool m_nosnow{false}; // a pass of the snow didn't compile: the snow is left out + + bool make_program(std::size_t Index); + void make_rain_cells_program(); }; diff --git a/rendering/vulkan14/vulkan14indirect.cpp b/rendering/vulkan14/vulkan14indirect.cpp index c97eec716..d47428fe7 100644 --- a/rendering/vulkan14/vulkan14indirect.cpp +++ b/rendering/vulkan14/vulkan14indirect.cpp @@ -635,7 +635,14 @@ vulkan14_renderer::indirect_counts vulkan14_renderer::draw_indirect_shadow(vk14: auto &program{own != nullptr ? *own : m_cubeshadows ? (texture != null_handle ? *scene.cube_alpha_shadow : *scene.cube_shadow) : (texture != null_handle ? *scene.alpha_shadow : *scene.shadow)}; - auto *multidraw{m_indirectmultidraw ? multidraw_program(program) : nullptr}; + auto pending{false}; + auto *multidraw{m_indirectmultidraw ? multidraw_program(program, pending) : nullptr}; + if (pending) + { + // the shaders of its multi draws are being compiled: the draw is left out till they're there + ++index; + continue; + } auto last{index + 1}; if (multidraw != nullptr) { From 160e8b8a46579bc46dc1ec66e732e0b8b044e2d9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 12:42:31 +0100 Subject: [PATCH 117/123] Windscreen water: the review of 27.11 (the snow list stops when full, the cells of the rain only for a cab with a glass of the rain) - snList() stops listing when its SN_REFS are taken: no lumps worked out for nothing, and the cover of the texel counts only the sprites the glass lays (no gaps where it took the dropped ones for covering); OpenGL 4.6 and Vulkan - update_rain_cells() gets no rain for a cab without a material of the shader of the rain in this weather (windscreen_water::wants_rain_cells(); as before when the simulation isn't used) - Vulkan: a rain-cell buffer which can't be made leaves the glasses with rain dry (a small stand-in the pass sets hold) instead of failing the whole windscreen water; it is still made at the start, since the pass sets and those of the cullings hold it Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- rendering/common/windscreenwater.cpp | 15 +++++++++++++++ rendering/common/windscreenwater.h | 4 ++++ rendering/opengl46/opengl46renderer.cpp | 3 ++- rendering/vulkan14/vulkan14frame.cpp | 3 ++- rendering/vulkan14/vulkan14water.cpp | 18 ++++++++++++++---- rendering/vulkan14/vulkan14water.h | 1 + shaders/ogl46/snow_sprites.glsl | 14 +++++++++----- shaders/vk14/snow_sprites.glsl | 14 +++++++++----- 8 files changed, 56 insertions(+), 16 deletions(-) diff --git a/rendering/common/windscreenwater.cpp b/rendering/common/windscreenwater.cpp index b28e065cc..108bb78b0 100644 --- a/rendering/common/windscreenwater.cpp +++ b/rendering/common/windscreenwater.cpp @@ -130,6 +130,7 @@ void windscreen_water::release() m_logged.fill(-1); m_layerlogged = -1; m_kinds.clear(); + m_cabmaterials.clear(); m_vehicle = nullptr; m_cab = nullptr; } @@ -272,6 +273,8 @@ void windscreen_water::build(TModel3d &Cab) } } auto const material{Submodel->m_material}; + if ((material != null_handle) && (material > 0) && (Submodel->eType == GL_TRIANGLES) && (std::find(m_cabmaterials.begin(), m_cabmaterials.end(), material) == m_cabmaterials.end())) + m_cabmaterials.push_back(material); if ((material != null_handle) && (material > 0) && (Submodel->eType == GL_TRIANGLES) && std::ranges::none_of(m_kinds, [material](auto const &Kind) { return Kind.first == material; })) { // every material with a mask of the wipers, what it is kept: it's a glass of another kind when the weather changes @@ -362,6 +365,18 @@ void windscreen_water::build(TModel3d &Cab) } } +bool windscreen_water::wants_rain_cells() +{ + // without the simulation the cab isn't looked at: the cells as before, whenever it rains + if (m_state <= 0) + return true; + // a material of the cab of the shader of the rain, as it is in this weather (with a mask of the wipers or without) + return std::ranges::any_of(m_cabmaterials, [this](material_handle const Material) { + auto const *opengl{m_host.material(Material)}; + return (opengl != nullptr) && (opengl->shader != nullptr) && (opengl->shader->param_conf.count("water_slot") > 0); + }); +} + void windscreen_water::update(double const Seconds) { if (false == available()) diff --git a/rendering/common/windscreenwater.h b/rendering/common/windscreenwater.h index d92d5e676..e58b14f09 100644 --- a/rendering/common/windscreenwater.h +++ b/rendering/common/windscreenwater.h @@ -63,6 +63,9 @@ class windscreen_water // once a frame, before the colour passes: the cab of the train followed, the step of the simulation run. Seconds: of the // simulation since the frame before (0 when it's paused) void update(double Seconds); + // whether the glasses need the cells of the rain worked out: the cab of the train has a glass of the rain (or the simulation + // isn't used, the cab not looked at) + bool wants_rain_cells(); // the materials let go of their slots, the glasses forgotten (the storage stays as it is, unused) void release(); std::string info() const; @@ -121,6 +124,7 @@ class windscreen_water int m_state{0}; // 0: not set up yet, 1: ready, -1: can't be used TDynamicObject const *m_vehicle{nullptr}; TModel3d const *m_cab{nullptr}; + std::vector m_cabmaterials; // the materials of the cab (for the glasses with rain it has, wants_rain_cells()) std::vector> m_kinds; // the materials of the cab with a mask of the wipers, what kind of glass they were std::array m_glasses{}; std::size_t m_glasscount{0}; diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index 1c2eeb8b9..fb2e66d9b 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -1808,7 +1808,8 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) m_windscreenwater.update(Timer::GetDeltaTime()); // the drops and the rivulets of the glasses with rain, for the time of the block of the scene // (the drops a cell may hold: as many as the glass is wet) - m_windscreenwater.update_rain_cells(scene_ubs.time, (scene_ubs.rain_state.y > 0.001f) ? std::min(scene_ubs.rain_state.y + 0.01f, 1.f) : 0.f); + // (none for a cab without a glass of the rain) + m_windscreenwater.update_rain_cells(scene_ubs.time, ((scene_ubs.rain_state.y > 0.001f) && m_windscreenwater.wants_rain_cells()) ? std::min(scene_ubs.rain_state.y + 0.01f, 1.f) : 0.f); } m_windscreenwater.bind(); diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index e46602ff5..d3bb1cbf5 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -1137,7 +1137,8 @@ void vulkan14_renderer::render_scene() scene.water.update(Timer::GetDeltaTime()); // the drops and the rivulets of the glasses with rain, for the time the block of the scene gets (scene_ubs.time) // (the drops a cell may hold: as many as the glass is wet, a little more, since it's the wetness of the frame before) - scene.water.update_rain_cells(static_cast(Timer::GetTime()), (m_glasswet > 0.001) ? static_cast(std::min(m_glasswet + 0.01, 1.0)) : 0.f); + // (none for a cab without a glass of the rain) + scene.water.update_rain_cells(static_cast(Timer::GetTime()), ((m_glasswet > 0.001) && scene.water.wants_rain_cells()) ? static_cast(std::min(m_glasswet + 0.01, 1.0)) : 0.f); if (scene.targets.size() < m_viewports.size()) { scene.targets.resize(m_viewports.size()); diff --git a/rendering/vulkan14/vulkan14water.cpp b/rendering/vulkan14/vulkan14water.cpp index c6b244bcc..4ab057eb6 100644 --- a/rendering/vulkan14/vulkan14water.cpp +++ b/rendering/vulkan14/vulkan14water.cpp @@ -51,11 +51,20 @@ bool windscreen_water::init(VkDevice const Device, pipeline_library &Pipelines, m_ring = &Ring; m_alignment = std::max(Alignment, 16); m_host = std::move(Host); + // the cells of the rain: the pass sets hold their buffer from the start (made later, the sets of the passes and of the cullings + // would have to be written anew in the middle of a frame). without it a small stand-in, which no glass reads (the glasses with + // rain stay dry, the rest of the simulation works on) m_raincells = std::make_shared(); - if (false == m_raincells->create(Memory, static_cast(gl::RAIN_CELLS_COUNT * 16), storage_usage, memory_kind::device, "rain cells")) + m_raincellsfull = m_raincells->create(Memory, static_cast(gl::RAIN_CELLS_COUNT * 16), storage_usage, memory_kind::device, "rain cells"); + if (false == m_raincellsfull) { - m_raincells.reset(); - return false; + ErrorLog("rain cells: no storage of " + std::to_string(gl::RAIN_CELLS_COUNT * 16 / (1024 * 1024)) + " MiB, the glasses with rain stay dry"); + m_raincells = std::make_shared(); + if (false == m_raincells->create(Memory, 65536, storage_usage, memory_kind::device, "rain cells")) + { + m_raincells.reset(); + return false; + } } m_storage = std::make_shared(); m_full = m_storage->create(Memory, static_cast(gl::WATER_STORAGE_SIZE), storage_usage, memory_kind::device, "windscreen water"); @@ -85,6 +94,7 @@ void windscreen_water::destroy() } m_raincellkernel.destroy(m_device); m_raincelltried = false; + m_raincellsfull = false; m_raincells.reset(); m_storage.reset(); m_device = VK_NULL_HANDLE; @@ -199,7 +209,7 @@ void windscreen_water::gpu_setup(std::size_t const Slot, std::vector void windscreen_water::update_rain_cells(float const Time, float const Rain) { - if ((m_device == VK_NULL_HANDLE) || (false == bool(m_raincells)) || (Rain <= 0.f) || (false == bool(m_host.commands))) + if ((m_device == VK_NULL_HANDLE) || (false == bool(m_raincells)) || (false == m_raincellsfull) || (Rain <= 0.f) || (false == bool(m_host.commands))) { return; } diff --git a/rendering/vulkan14/vulkan14water.h b/rendering/vulkan14/vulkan14water.h index a6ef05597..cc9f7f7ef 100644 --- a/rendering/vulkan14/vulkan14water.h +++ b/rendering/vulkan14/vulkan14water.h @@ -103,6 +103,7 @@ class windscreen_water : public gfx::windscreen_water std::shared_ptr m_raincells; compute_kernel m_raincellkernel; bool m_raincelltried{false}; + bool m_raincellsfull{false}; // the cells of the rain have their storage (else a stand-in: the glasses with rain stay dry) bool m_full{false}; // the storage is as large as the simulation needs (else a stand-in, the glasses make their water up) bool m_cleared{false}; bool m_snowkernels{true}; // the passes of the snow made (they are optional: without them the glasses of the snow stay clear) diff --git a/shaders/ogl46/snow_sprites.glsl b/shaders/ogl46/snow_sprites.glsl index 1942ecb27..897ae70b9 100644 --- a/shaders/ogl46/snow_sprites.glsl +++ b/shaders/ogl46/snow_sprites.glsl @@ -349,7 +349,7 @@ snow_layer_s snCompose(vec2 uv, vec2 span, float pixelUV) // 1 + the list (0 the flakes, 1 .. SN_GRIDS the grids of the lumps) times 16 + the cell around the texel (0 .. 8: 1 - the column // offset + 3 * (1 - the row offset)), 0 after the last one (a layer cleared to zeros lists nothing). the glass lays only those at // its pixels, sharp from the atlas as when it laid all of the cells around itself, at a fraction of the cost -const int SN_REFS = 6; // the top ones: those under them are covered (sixteen fit in the four uint) +const int SN_REFS = 6; // the top ones, the listing stops when full (sixteen fit in the four uint; 8 if thick snow shows gaps) // the sprites over a texel covering it on the whole (the level of the atlas the size of the texel): those under it are left out const float SN_LIST_COVERED = 0.97; @@ -380,19 +380,23 @@ uvec4 snList(vec2 uv, vec2 span, float pixelUV) float reachF = half_diagonal * max(perF.x, perF.y) * 1.25; for (int k = 0; k < 9; ++k) { - if ((count < 2) && snFlakeCell(pF, hereF + ivec2(1 - k % 3, 1 - k / 3), perF, pixelUV, reachF, flakes)) - snRef(uint(k), refs, count); // two flakes at most, the rest of the list for the lumps + if (count >= 2) + break; // two flakes at most, the rest of the list for the lumps + if (snFlakeCell(pF, hereF + ivec2(1 - k % 3, 1 - k / 3), perF, pixelUV, reachF, flakes)) + snRef(uint(k), refs, count); } vec2 perL = span / snow_lump_cell; float reachL = half_diagonal * max(perL.x, perL.y) * 1.25 + 0.05; for (int g = 0; g < SN_GRIDS; ++g) { - if (layer.a >= SN_LIST_COVERED) - break; // the grids over this one cover the texel + if ((layer.a >= SN_LIST_COVERED) || (count >= SN_REFS)) + break; // the grids over this one cover the texel, or the list is full vec2 pL = uv * perL + sn_grids[g].shift; ivec2 hereL = ivec2(floor(pL)); for (int k = 0; k < 9; ++k) { + if (count >= SN_REFS) + break; // the list is full: nothing more worked out, and the cover counts only the sprites the glass lays if (snLumpCell(pL, hereL + ivec2(1 - k % 3, 1 - k / 3), perL, sn_grids[g], pixelUV, reachL, layer)) snRef(uint(16 * (g + 1) + k), refs, count); } diff --git a/shaders/vk14/snow_sprites.glsl b/shaders/vk14/snow_sprites.glsl index 1942ecb27..897ae70b9 100644 --- a/shaders/vk14/snow_sprites.glsl +++ b/shaders/vk14/snow_sprites.glsl @@ -349,7 +349,7 @@ snow_layer_s snCompose(vec2 uv, vec2 span, float pixelUV) // 1 + the list (0 the flakes, 1 .. SN_GRIDS the grids of the lumps) times 16 + the cell around the texel (0 .. 8: 1 - the column // offset + 3 * (1 - the row offset)), 0 after the last one (a layer cleared to zeros lists nothing). the glass lays only those at // its pixels, sharp from the atlas as when it laid all of the cells around itself, at a fraction of the cost -const int SN_REFS = 6; // the top ones: those under them are covered (sixteen fit in the four uint) +const int SN_REFS = 6; // the top ones, the listing stops when full (sixteen fit in the four uint; 8 if thick snow shows gaps) // the sprites over a texel covering it on the whole (the level of the atlas the size of the texel): those under it are left out const float SN_LIST_COVERED = 0.97; @@ -380,19 +380,23 @@ uvec4 snList(vec2 uv, vec2 span, float pixelUV) float reachF = half_diagonal * max(perF.x, perF.y) * 1.25; for (int k = 0; k < 9; ++k) { - if ((count < 2) && snFlakeCell(pF, hereF + ivec2(1 - k % 3, 1 - k / 3), perF, pixelUV, reachF, flakes)) - snRef(uint(k), refs, count); // two flakes at most, the rest of the list for the lumps + if (count >= 2) + break; // two flakes at most, the rest of the list for the lumps + if (snFlakeCell(pF, hereF + ivec2(1 - k % 3, 1 - k / 3), perF, pixelUV, reachF, flakes)) + snRef(uint(k), refs, count); } vec2 perL = span / snow_lump_cell; float reachL = half_diagonal * max(perL.x, perL.y) * 1.25 + 0.05; for (int g = 0; g < SN_GRIDS; ++g) { - if (layer.a >= SN_LIST_COVERED) - break; // the grids over this one cover the texel + if ((layer.a >= SN_LIST_COVERED) || (count >= SN_REFS)) + break; // the grids over this one cover the texel, or the list is full vec2 pL = uv * perL + sn_grids[g].shift; ivec2 hereL = ivec2(floor(pL)); for (int k = 0; k < 9; ++k) { + if (count >= SN_REFS) + break; // the list is full: nothing more worked out, and the cover counts only the sprites the glass lays if (snLumpCell(pL, hereL + ivec2(1 - k % 3, 1 - k / 3), perL, sn_grids[g], pixelUV, reachL, layer)) snRef(uint(16 * (g + 1) + k), refs, count); } From 5ce5a531b8e062ac0ab727ef098c8aea03f1c4f0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 13:15:59 +0100 Subject: [PATCH 118/123] Windscreen water: a glass with drops is one with an atlas of drops, not of the snow (wants_rain_cells()) mat_rain_windscreen has no param water_slot (only the glasses of the snow have a slot of their own), so wants_rain_cells() never found the glass of the rain and the cells weren't worked out: the glass showed only its fine droplets. A material of the cab with raindropsatlas and without snow_slot now (the insects too, which don't come with rain). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- rendering/common/windscreenwater.cpp | 6 ++++-- rendering/common/windscreenwater.h | 4 ++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/rendering/common/windscreenwater.cpp b/rendering/common/windscreenwater.cpp index 108bb78b0..e4d0dd3a5 100644 --- a/rendering/common/windscreenwater.cpp +++ b/rendering/common/windscreenwater.cpp @@ -370,10 +370,12 @@ bool windscreen_water::wants_rain_cells() // without the simulation the cab isn't looked at: the cells as before, whenever it rains if (m_state <= 0) return true; - // a material of the cab of the shader of the rain, as it is in this weather (with a mask of the wipers or without) + // a glass of the cab with drops, as it is in this weather: a material with an atlas of drops (raindropsatlas: the rain, or the + // insects, which don't come with rain), but not one of the snow (snow_slot) return std::ranges::any_of(m_cabmaterials, [this](material_handle const Material) { auto const *opengl{m_host.material(Material)}; - return (opengl != nullptr) && (opengl->shader != nullptr) && (opengl->shader->param_conf.count("water_slot") > 0); + return (opengl != nullptr) && (opengl->shader != nullptr) && (opengl->shader->texture_conf.count("raindropsatlas") > 0) && + (opengl->shader->param_conf.count("snow_slot") == 0); }); } diff --git a/rendering/common/windscreenwater.h b/rendering/common/windscreenwater.h index e58b14f09..d614392d6 100644 --- a/rendering/common/windscreenwater.h +++ b/rendering/common/windscreenwater.h @@ -63,8 +63,8 @@ class windscreen_water // once a frame, before the colour passes: the cab of the train followed, the step of the simulation run. Seconds: of the // simulation since the frame before (0 when it's paused) void update(double Seconds); - // whether the glasses need the cells of the rain worked out: the cab of the train has a glass of the rain (or the simulation - // isn't used, the cab not looked at) + // whether the glasses need the cells of the rain worked out: the cab of the train has a glass with drops, not of the snow (or + // the simulation isn't used, the cab not looked at) bool wants_rain_cells(); // the materials let go of their slots, the glasses forgotten (the storage stays as it is, unused) void release(); From 559d105aa480e6fa27f073365ad86ce8e3c66af7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 21:57:05 +0100 Subject: [PATCH 119/123] Deer: take fright by the speed of the train, run over slopes leaning with the ground A grazing deer takes fright when the train is deer.reactiontime seconds of its speed away (default 3.5 s: it needs 2.0-2.75 s from the alarm to be off the track), but no nearer than deer.reactiondistance (default 20 m) for a slow or a standing train. So the slower the train, the closer it gets before the deer runs. The horn (deer.hornrange) sends it off sooner, as before. deer.fleedistance, of the test builds of this feature only and never in a release, goes; an eu07.ini that still has it is read with its value passed over. The way a deer runs away may go down the slope of an embankment (to 6 m below the sleepers) or up the one of a cutting (to 4 m above them), no steeper than 35 degrees between the samples of the ground, now 17 of them, about 1.5 m apart. Water, walls and cliffs still keep a deer away. Running, the deer leans up and down the slope by the ground under its hooves (at most 30 degrees, smoothed, about its side axis, which keeps the turn the shader reads the clip and the moment from), and grazes leaning where it stopped, drawn on its own, out of the groups of the instances of its model. No change to the assets: the same models and textures of the deer (models/animals/jelen_*.t3d, textures/animals/jelen_*). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GXgG7F4L42c2F9sDSAJbT2 --- utilities/Globals.cpp | 9 +++- utilities/Globals.h | 3 +- world/deer.cpp | 105 +++++++++++++++++++++++++----------------- world/deer.h | 20 ++++---- 4 files changed, 83 insertions(+), 54 deletions(-) diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 10a7ae425..72758fd12 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -2284,7 +2284,11 @@ global_settings::ConfigParse_gfx_sky( cParser &Parser, std::string_view const To else if( Token == "deer.distance" ) { readvalue( deer_distance, 100.0f, 10000.0f ); } else if( Token == "deer.chance" ) { readvalue( deer_chance, 0.0f, 1.0f ); } else if( Token == "deer.hornrange" ) { readvalue( deer_hornrange, 0.0f, 5000.0f ); } - else if( Token == "deer.fleedistance" ) { readvalue( deer_fleedistance, 0.0f, 1000.0f ); } + else if( Token == "deer.reactiontime" ) { readvalue( deer_reactiontime, 0.0f, 60.0f ); } + else if( Token == "deer.reactiondistance" ) { readvalue( deer_reactiondistance, 0.0f, 1000.0f ); } + else if( Token == "deer.fleedistance" ) { + // of the test builds before deer.reactiontime, never in a release: its value is passed over + Parser.getTokens( 1 ); } else if( Token == "gfx.lights.shadows" ) { // no/low/medium/high, or the number of the level Parser.getTokens( 1 ); @@ -2867,7 +2871,8 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "deer.distance", deer_distance ); export_as_text( Output, "deer.chance", deer_chance ); export_as_text( Output, "deer.hornrange", deer_hornrange ); - export_as_text( Output, "deer.fleedistance", deer_fleedistance ); + export_as_text( Output, "deer.reactiontime", deer_reactiontime ); + export_as_text( Output, "deer.reactiondistance", deer_reactiondistance ); export_as_text( Output, "gfx.lights.shadows", std::string{ gfx_lights_shadows == 3 ? "high" : gfx_lights_shadows == 2 ? "medium" : gfx_lights_shadows == 1 ? "low" : "no" } ); export_as_text( Output, "gfx.lights.shadows.cab", gfx_lights_shadows_cab ); export_as_text( Output, "gfx.lights.shadows.lamps", gfx_lights_shadows_lamps ); diff --git a/utilities/Globals.h b/utilities/Globals.h index 5342e7079..699d4990c 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -660,7 +660,8 @@ struct global_settings { float deer_distance { 2000.0f }; // metres ahead of the train a deer is put at float deer_chance { 1.0f }; // of a deer at each interval, 0-1 float deer_hornrange { 600.0f }; // the horn sends away the deer within this many metres - float deer_fleedistance { 150.0f }; // a deer runs away from the train come this close, metres + float deer_reactiontime { 3.5f }; // a deer runs away from the train this many seconds of its speed away, seconds + float deer_reactiondistance { 20.0f }; // and from a slow or a standing train come this close, metres // shadows of the lamps (cube shadow maps), 0 none, 1 low, 2 medium, 3 high; see opengl46_local_shadows. for now the lamp of the // occupied cab, its shadows cast by the cab int gfx_lights_shadows { 2 }; diff --git a/world/deer.cpp b/world/deer.cpp index fae95efda..657b7c1dc 100644 --- a/world/deer.cpp +++ b/world/deer.cpp @@ -67,17 +67,24 @@ constexpr double Flight2{3.95}; constexpr double Flight3{4.85}; // the frame an instance starts from at the moment of the change, a little after the frame proper: never the end of the one before constexpr double Startframe{0.02}; -// the ground under the way of the deer, at equal steps from its start to its end (deer_herd::Groundsamples) -constexpr std::size_t Groundsamples{9}; -// the ground under the way of the deer is looked for up to this much above the place it starts from, metres +// the ground under the way of the deer, at equal steps from its start to its end (deer_herd::Groundsamples, about 1.5 m apart) +constexpr std::size_t Groundsamples{17}; +// the ground beside the track (a platform of the terrain) is looked for up to this much above the sleepers, metres constexpr double Groundceiling{3.0}; -// the way it runs: flat ground found all along it (no slope of an embankment or a cutting, no water). the ground beside the -// track no farther than this below or above the sleepers, metres -constexpr double Waybelow{1.2}; -constexpr double Wayabove{0.8}; -// rising or falling at most this much between the samples of the ground (3 m apart), and this much all along, metres -constexpr double Waystep{0.45}; -constexpr double Wayrange{1.2}; +// the way it runs: ground found all along it, no water. down the slope of an embankment or up the one of a cutting: the ground +// no farther than this below or above the sleepers, metres +constexpr double Waybelow{6.0}; +constexpr double Wayabove{4.0}; +// the ground of the way is looked for up to this much above the sleepers, metres (over the highest it may be) +constexpr double Wayceiling{Wayabove + 1.0}; +// no steeper than this between the samples of the ground (a wall, a cliff, a ditch with steep sides), rise to run +constexpr double Wayslope{0.7}; +// the body leans up and down the slope by the ground under its hooves, this far before and behind its middle, metres +constexpr double Halfbody{0.52}; +// at most this much, degrees +constexpr double Maxpitch{30.0}; +// and follows the slope this fast (a share of the difference a second), not jerking at the bends of the ground +constexpr double Pitchrate{8.0}; // where there's no such ground at the place, the next deer is looked for this much farther, metres constexpr double Retrydistance{200.0}; // the track at the place: plain (no switch) from the train to this much past the place, metres @@ -456,7 +463,7 @@ float vat_turn(glm::dvec3 const &Heading, vat_clip const &Animation, int const C } // a deer put in the scenery, not a part of it. Moving: the game moves it, so it's drawn on its own -TAnimModel *make_deer(vat_clip const &Animation, glm::dvec3 const &Position, float const Turn, bool const Moving) +TAnimModel *make_deer(vat_clip const &Animation, glm::dvec3 const &Position, float const Turn, float const Pitch, bool const Moving) { auto const range{static_cast(std::ceil(Global.deer_distance + 500.0))}; auto const definition{std::format("node {} 0 none model 0 0 0 0 {}.t3d none endmodel", range, Animation.model)}; @@ -471,10 +478,11 @@ TAnimModel *make_deer(vat_clip const &Animation, glm::dvec3 const &Position, flo model->m_dirty = false; model->m_generated = true; simulation::Region->erase(model); - model->Angles(glm::vec3{0.f, Turn, 0.f}); - if (Moving) + // leaning about its side, which keeps the turn the shader reads the clip from (the side axis stays level) + model->Angles(glm::vec3{Pitch, Turn, 0.f}); + if (Moving || (Pitch != 0.f)) { - // out of the groups of the instances of its model, which keep their places + // out of the groups of the instances of its model, which keep their places, level model->draw_alone(); } simulation::Region->insert(model); @@ -483,14 +491,17 @@ TAnimModel *make_deer(vat_clip const &Animation, glm::dvec3 const &Position, flo } // the deer moved to another place -void move_deer(TAnimModel &Model, glm::dvec3 const &Position) +void move_deer(TAnimModel &Model, glm::dvec3 const &Position, float const Pitch) { - if (glm::length(Model.location() - Position) < 1e-4) + auto angles{Model.Angles()}; + if ((glm::length(Model.location() - Position) < 1e-4) && (std::abs(angles.x - Pitch) < 1e-3f)) { return; } simulation::Region->erase(&Model); Model.location(Position); + angles.x = Pitch; + Model.Angles(angles); simulation::Region->insert(&Model); } @@ -506,7 +517,7 @@ void remove_deer(TAnimModel *Model) // the deer goes on with another animation, at frame Frame of clip Clip at the time Time; where the model can't be made, as it was void change_deer(TAnimModel *&Model, glm::dvec3 const &Heading, vat_clip const &Animation, int const Clip, double const Frame, double const Time, bool const Moving) { - auto *model{make_deer(Animation, Model->location(), vat_turn(Heading, Animation, Clip, Frame, Time), Moving)}; + auto *model{make_deer(Animation, Model->location(), vat_turn(Heading, Animation, Clip, Frame, Time), Model->Angles().x, Moving)}; if (model == nullptr) { return; @@ -515,18 +526,18 @@ void change_deer(TAnimModel *&Model, glm::dvec3 const &Heading, vat_clip const & Model = model; } -// the way a deer would run away from Start along Heading: true where it's all over flat ground, Ground then the heights of the ground -// at equal steps along it (the first one Start); Reason why not otherwise -bool flat_way(glm::dvec3 const &Start, glm::dvec3 const &Heading, std::array &Ground, std::string &Reason) +// the way a deer would run away from Start along Heading: true where it can run over all of it (no water, no wall or cliff, down an +// embankment or up a cutting no farther than Waybelow / Wayabove), Ground then the heights of the ground at equal steps along it +// (the first one Start); Reason why not otherwise +bool run_way(glm::dvec3 const &Start, glm::dvec3 const &Heading, std::array &Ground, std::string &Reason) { Ground.front() = Start.y; auto const length{flight_way(Flighttime)}; - auto low{Start.y}; - auto high{Start.y - 1e9}; + auto const spacing{length / static_cast(Groundsamples - 1)}; for (std::size_t sample = 1; sample < Groundsamples; ++sample) { - auto const point{Start + Heading * (length * static_cast(sample) / static_cast(Groundsamples - 1))}; - auto const here{ground_at(point, Start.y + Groundceiling)}; + auto const point{Start + Heading * (spacing * static_cast(sample))}; + auto const here{ground_at(point, Start.y + Wayceiling)}; if (false == here.found) { Reason = std::format("no ground at {:.1f} m", glm::length(point - Start)); @@ -537,23 +548,24 @@ bool flat_way(glm::dvec3 const &Start, glm::dvec3 const &Heading, std::array 1) && (std::abs(here.height - Ground[sample - 1]) > Waystep)) + if (std::abs(here.height - Ground[sample - 1]) > Wayslope * spacing) { Reason = std::format("a step of {:.2f} m at {:.1f} m", here.height - Ground[sample - 1], glm::length(point - Start)); return false; } Ground[sample] = here.height; - low = (sample == 1 ? here.height : std::min(low, here.height)); - high = std::max(high, here.height); - } - if (high - low > Wayrange) - { - Reason = std::format("the ground rises and falls {:.2f} m", high - low); - return false; } return true; } +// the height of the ground Way metres along the way of a deer (Ground, Length long), the ends held beyond it +double way_height(std::array const &Ground, double const Way, double const Length) +{ + auto const step{std::clamp(Way / Length, 0.0, 1.0) * static_cast(Groundsamples - 1)}; + auto const sample{std::min(static_cast(step), Groundsamples - 2)}; + return std::lerp(Ground[sample], Ground[sample + 1], step - static_cast(sample)); +} + } // namespace simulation::deer_herd simulation::Deer; @@ -585,17 +597,18 @@ void simulation::deer_herd::update(double const Deltatime) m_travelled = 0.0; if ((LocalRandom(0.0, 1.0) < Global.deer_chance) && (false == spawn(*vehicle))) { - // no flat ground, a switch or a platform there: soon again + // no ground to run over, a switch or a platform there: soon again m_travelled = std::max(0.0, Global.deer_interval - Retrydistance); } } auto const train{vehicle->GetPosition()}; + auto const speed{std::abs(mover->V)}; auto const horn{(mover->WarningSignal & 7) != 0}; auto const now{Timer::GetTime()}; - std::erase_if(m_deer, [this, &train, horn, now](deer &Animal) { return tend(Animal, train, horn, now); }); + std::erase_if(m_deer, [this, &train, speed, horn, now](deer &Animal) { return tend(Animal, train, speed, horn, now); }); } -bool simulation::deer_herd::tend(deer &Animal, glm::dvec3 const &Train, bool const Horn, double const Now) const +bool simulation::deer_herd::tend(deer &Animal, glm::dvec3 const &Train, double const Speed, bool const Horn, double const Now) const { auto const distance{glm::length(Animal.model->location() - Train)}; Animal.closest = std::min(Animal.closest, distance); @@ -608,7 +621,8 @@ bool simulation::deer_herd::tend(deer &Animal, glm::dvec3 const &Train, bool con switch (Animal.state) { case deer_state::grazing: - if ((Horn && (distance < Global.deer_hornrange)) || (distance < Global.deer_fleedistance)) + // the train the time to get away from it (deer.reactiontime) off, or the horn: the faster the train, the sooner + if ((Horn && (distance < Global.deer_hornrange)) || (distance < std::max(static_cast(Global.deer_reactiondistance), Speed * Global.deer_reactiontime))) { alarm(Animal, Train, Now); } @@ -666,7 +680,7 @@ bool simulation::deer_herd::spawn(TDynamicObject const &Vehicle) WriteLog(std::format("Deer not put at {:.1f} {:.1f} {:.1f}: {}", place.position.x, place.position.y, place.position.z, platform)); return false; } - // across the path, a little askew, to the side with flat ground to run away over (one picked at random first) + // across the path, a little askew, to the side with ground it can run away over (one picked at random first) deer animal; animal.start = place.position; auto const askew{LocalRandom(-25.0, 25.0) * std::numbers::pi / 180.0}; @@ -678,7 +692,7 @@ bool simulation::deer_herd::spawn(TDynamicObject const &Vehicle) glm::dvec3 const across{place.forward.z * side, 0.0, -place.forward.x * side}; animal.heading = glm::normalize(across * std::cos(askew) + place.forward * std::sin(askew)); std::string reason; - if (flat_way(animal.start, animal.heading, animal.ground, reason)) + if (run_way(animal.start, animal.heading, animal.ground, reason)) { found = true; break; @@ -693,7 +707,7 @@ bool simulation::deer_herd::spawn(TDynamicObject const &Vehicle) // grazing from a moment of its own animal.frame = LocalRandom(0.0, Grazing.frames); animal.time = Timer::GetTime(); - animal.model = make_deer(Grazing, place.position, vat_turn(animal.heading, Grazing, 0, animal.frame, animal.time), false); + animal.model = make_deer(Grazing, place.position, vat_turn(animal.heading, Grazing, 0, animal.frame, animal.time), 0.f, false); if (animal.model == nullptr) { return false; @@ -724,16 +738,21 @@ void simulation::deer_herd::flee(deer &Animal) const // the ground along its way was looked at when it was put there Animal.state = deer_state::fleeing; Animal.start = Animal.model->location(); + Animal.moved = Animal.time; } bool simulation::deer_herd::run(deer &Animal, double const Now) const { auto const elapsed{std::clamp(Now - Animal.time, 0.0, Flighttime)}; auto const way{flight_way(elapsed)}; - auto const step{way / flight_way(Flighttime) * static_cast(Groundsamples - 1)}; - auto const sample{std::min(static_cast(step), Groundsamples - 2)}; + auto const length{flight_way(Flighttime)}; auto position{Animal.start + Animal.heading * way}; - position.y = std::lerp(Animal.ground[sample], Animal.ground[sample + 1], step - static_cast(sample)); - move_deer(*Animal.model, position); + position.y = way_height(Animal.ground, way, length); + // leaning with the ground under its hooves, up the slope ahead (the body faces along the heading) + auto const rise{way_height(Animal.ground, way + Halfbody, length) - way_height(Animal.ground, way - Halfbody, length)}; + auto const slope{std::clamp(std::atan2(rise, 2.0 * Halfbody) * 180.0 / std::numbers::pi, -Maxpitch, Maxpitch)}; + Animal.pitch = std::lerp(Animal.pitch, slope, std::clamp((Now - Animal.moved) * Pitchrate, 0.0, 1.0)); + Animal.moved = Now; + move_deer(*Animal.model, position, static_cast(Animal.pitch)); return (Now - Animal.time >= Flighttime); } diff --git a/world/deer.h b/world/deer.h index 6f8b24cdc..95629702a 100644 --- a/world/deer.h +++ b/world/deer.h @@ -23,9 +23,9 @@ class basic_region; // deer at the tracks (Global.deer, off unless eu07.ini turns it on): every Global.deer_interval metres the train of the player // covers, a deer is put (with the chance Global.deer_chance) on the path the train goes along, Global.deer_distance metres ahead // of it, grazing (the model animals/jelen_je, animated by textures). the horn of the train within Global.deer_hornrange of it, or -// the train coming closer than Global.deer_fleedistance, frightens it: it raises its head (animals/jelen_zryw), looks at the train -// and runs away from the tracks in bounds (animals/jelen_skok, moved by the game along with the hooves), and grazes again where it -// stopped. the game picks the clip and the moment of each of the models (shader vat, vat_random -1), so one hands over to the next +// the train coming closer than Global.deer_reactiontime seconds of its speed (Global.deer_reactiondistance at least), frightens it: +// it raises its head (animals/jelen_zryw), looks at the train and runs away from the tracks in bounds (animals/jelen_skok, moved by +// the game along with the hooves, over the ground, leaning up and down its slopes), and grazes again where it stopped. the game picks the clip and the moment of each of the models (shader vat, vat_random -1), so one hands over to the next // in the very same pose. the deer go once the train is past them. they aren't parts of the scenery (not saved, not edited) namespace simulation { @@ -43,10 +43,10 @@ class deer_herd private: // the ground under the way the deer runs, at equal steps from its start to its end - static constexpr std::size_t Groundsamples{9}; + static constexpr std::size_t Groundsamples{17}; enum class deer_state { - grazing, // till it hears the horn or sees the train close + grazing, // till it hears the horn or the train comes close (deer.reactiontime of its speed away) alarmed, // grazing still, till the moment of the grazing its startle starts from (time) startled, // raises its head (since time) fleeing, // looks at the train and runs away (since time) @@ -64,10 +64,14 @@ class deer_herd int look{0}; // the clip of the flight which looks at the train double closest{1e9}; // the train came this close, metres std::array ground{}; // heights of the ground along the way it runs + double pitch{0.0}; // up the slope it runs on, degrees + double moved{0.0}; // the time of the simulation it was last moved at, seconds }; - // the train at Train, its horn sounding, at the time Now: the deer takes fright, runs, or goes (true) once the train is past it - bool tend(deer &Animal, glm::dvec3 const &Train, bool const Horn, double const Now) const; - // puts a deer on the path ahead of the train, where it's plain track (no switch) with flat ground beside it and no platform near; + // the train at Train going Speed (m/s), its horn sounding, at the time Now: the deer takes fright, runs, or goes (true) once the + // train is past it + bool tend(deer &Animal, glm::dvec3 const &Train, double const Speed, bool const Horn, double const Now) const; + // puts a deer on the path ahead of the train, where it's plain track (no switch) with ground beside it it can run over (slopes + // of embankments and cuttings too) and no platform near; // false where there's none bool spawn(TDynamicObject const &Vehicle); // the deer took fright: when it starts, where it looks From d8dc11aab2da8e5d4659f0bf2d2237f05165e49b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 11:39:53 +0100 Subject: [PATCH 120/123] Rebase onto staging (after #531) The vehicle's physics is TDynamicObject::physics now (physics::Vehicle): the wipers, the insects and the rain of the glasses, the snow of the windscreen water and the deer take it from there. The includes of staging kept in opengl46renderer.cpp; the texture check of staging first in Render_Instances_Indirect_Shadow(), then the materials with a vertex shader of their own. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- rendering/common/windscreenwater.cpp | 4 +--- rendering/opengl46/opengl46renderer.cpp | 18 ++++++++++++++---- rendering/vulkan14/vulkan14frame.cpp | 8 ++++---- world/deer.cpp | 6 +++--- 4 files changed, 22 insertions(+), 14 deletions(-) diff --git a/rendering/common/windscreenwater.cpp b/rendering/common/windscreenwater.cpp index e4d0dd3a5..610210ff0 100644 --- a/rendering/common/windscreenwater.cpp +++ b/rendering/common/windscreenwater.cpp @@ -25,8 +25,6 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Train.h" #include "physics/vehicle.h" -#include - namespace gfx { @@ -517,7 +515,7 @@ void windscreen_water::update(double const Seconds) m_bladesbefore.x < 0.f ? blades.x : m_bladesbefore.x, m_bladesbefore.y < 0.f ? blades.y : m_bladesbefore.y, m_bladesbefore.z < 0.f ? blades.z : m_bladesbefore.z, m_bladesbefore.w < 0.f ? blades.w : m_bladesbefore.w}; block.rain = glm::vec4{LEAST_DROP, lambda, 1.f, 0.f}; block.counts = glm::uvec4{m_step * 2654435761u, most, 0u, 0u}; - block.snow = glm::vec4{snow ? perground : 0.f, GLASS_WARMTH, static_cast(std::abs(vehicle->MoverParameters->V)), static_cast(m_snowmap)}; + block.snow = glm::vec4{snow ? perground : 0.f, GLASS_WARMTH, static_cast(std::abs(vehicle->physics->V)), static_cast(m_snowmap)}; m_bladesbefore = blades; gpu_step(block, most); if (anysnow) diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index fb2e66d9b..362def0bc 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -46,6 +46,11 @@ void scene_camera_place(gl::scene_ubs &Ubs, glm::dvec3 const &Place) } } // namespace +#include +#include +#include +#include + //#define EU07_DEBUG_OPENGL int constexpr EU07_PICKBUFFERSIZE{ 1024 }; // size of (square) textures bound with the pick framebuffer @@ -1697,7 +1702,7 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) // were at the ends of their sweep (the drops on the glass come back from then) are kept while the camera is away, so the glass // looks as the blades left it when it's back in the cab. they're forgotten only for another vehicle TDynamicObject const *owner = Global.pCamera.m_owner; - if ((owner == nullptr) || (owner->MoverParameters->CabActive == 0)) + if ((owner == nullptr) || (owner->physics->CabActive == 0)) owner = (simulation::Train != nullptr) ? simulation::Train->Dynamic() : nullptr; if (owner != m_wipervehicle) { @@ -1728,7 +1733,7 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) m_wiperbugs = 0.0; } else if (owner != nullptr) - m_wiperbugs += glassstep * std::max(std::abs(owner->MoverParameters->V) * 3.6 - 20.0, 0.0) / 80.0; + m_wiperbugs += glassstep * std::max(std::abs(owner->physics->V) * 3.6 - 20.0, 0.0) / 80.0; scene_ubs.rain_wind.w = static_cast(m_wiperbugs); // the rain the glass meets (mat_rain_windscreen): counted in seconds of the heaviest rain standing still, more at speed (the // glass runs into it). the glass fills with it up to as many drops as it gets (a lighter rain only fills it more slowly) while @@ -1737,7 +1742,7 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) constexpr double fill_rate{0.3}; // per second of the heaviest rain: 95% full in 10 s (20 s at cloud cover 1.5) constexpr double fill_speed{1.5}; // at 100 km/h and more the glass meets x (1 + fill_speed) as much rain auto const dt{glassstep}; - auto const speed{(owner != nullptr) ? std::min(std::abs(owner->MoverParameters->V) * 3.6 / 100.0, 1.0) : 0.0}; + auto const speed{(owner != nullptr) ? std::min(std::abs(owner->physics->V) * 3.6 / 100.0, 1.0) : 0.0}; auto const meet{static_cast(percipitation_intensity) * (1.0 + fill_speed * speed)}; m_wiperrain += dt * meet; if ((percipitation_intensity > 0.f) && (Global.Weather == "rain:")) @@ -1748,7 +1753,7 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) } if (owner != nullptr) { - auto const cabactive{owner->MoverParameters->CabActive != 0 ? owner->MoverParameters->CabActive : 1}; + auto const cabactive{owner->physics->CabActive != 0 ? owner->physics->CabActive : 1}; for (int i = 0; i < 4; ++i) { if (i < owner->dWiperPos.size()) @@ -4203,6 +4208,11 @@ opengl46_renderer::indirect_counts opengl46_renderer::Render_Instances_Indirect_ for( std::size_t index = 0; index < count; ) { auto const &draw { m_indirectdraws[ index ] }; auto const texture { Indirect_Shadow_Texture( draw.material ) }; + if( ( texture != null_handle ) && ( false == m_textures.mark_as_used( texture ).bind( 0 ) ) ) { + // a texture which isn't there (yet) would leave the one bound before to the alpha test; no shadow until it is + ++index; + continue; + } // the materials with a vertex shader of their own are drawn one by one, with it (Bind_Material_Shadow()) auto const ownvertex = [ this ]( material_handle const Material ) { return ( false == m_cubeshadows ) && ( Material_Shadow_Program( Material, Indirect_Shadow_Texture( Material ) != null_handle ) != nullptr ); }; diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index d3bb1cbf5..0806e94c6 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -1575,7 +1575,7 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) // were at the ends of their sweep (the drops on the glass come back from then) are kept while the camera is away, so the glass // looks as the blades left it when it's back in the cab. they're forgotten only for another vehicle TDynamicObject const *owner = Global.pCamera.m_owner; - if ((owner == nullptr) || (owner->MoverParameters->CabActive == 0)) + if ((owner == nullptr) || (owner->physics->CabActive == 0)) owner = (simulation::Train != nullptr) ? simulation::Train->Dynamic() : nullptr; if (owner != m_wipervehicle) { @@ -1606,7 +1606,7 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) m_wiperbugs = 0.0; } else if (owner != nullptr) - m_wiperbugs += glassstep * std::max(std::abs(owner->MoverParameters->V) * 3.6 - 20.0, 0.0) / 80.0; + m_wiperbugs += glassstep * std::max(std::abs(owner->physics->V) * 3.6 - 20.0, 0.0) / 80.0; scene_ubs.rain_wind.w = static_cast(m_wiperbugs); // the rain the glass meets (mat_rain_windscreen): counted in seconds of the heaviest rain standing still, more at speed (the // glass runs into it). the glass fills with it up to as many drops as it gets (a lighter rain only fills it more slowly) while @@ -1615,7 +1615,7 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) constexpr double fill_rate{0.3}; // per second of the heaviest rain: 95% full in 10 s (20 s at cloud cover 1.5) constexpr double fill_speed{1.5}; // at 100 km/h and more the glass meets x (1 + fill_speed) as much rain auto const dt{glassstep}; - auto const speed{(owner != nullptr) ? std::min(std::abs(owner->MoverParameters->V) * 3.6 / 100.0, 1.0) : 0.0}; + auto const speed{(owner != nullptr) ? std::min(std::abs(owner->physics->V) * 3.6 / 100.0, 1.0) : 0.0}; auto const meet{static_cast(percipitation_intensity) * (1.0 + fill_speed * speed)}; m_wiperrain += dt * meet; if ((percipitation_intensity > 0.f) && (Global.Weather == "rain:")) @@ -1626,7 +1626,7 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) } if (owner != nullptr) { - auto const cabactive{owner->MoverParameters->CabActive != 0 ? owner->MoverParameters->CabActive : 1}; + auto const cabactive{owner->physics->CabActive != 0 ? owner->physics->CabActive : 1}; for (int i = 0; i < 4; ++i) { if (i < owner->dWiperPos.size()) diff --git a/world/deer.cpp b/world/deer.cpp index 657b7c1dc..23f8ef4f0 100644 --- a/world/deer.cpp +++ b/world/deer.cpp @@ -27,7 +27,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulation.h" #include "rendering/renderer.h" #include "vehicle/DynObj.h" -#include "McZapkie/MOVER.h" +#include "physics/vehicle.h" #include "world/Track.h" #include "editor/editorTerrainStreamer.hpp" #include "scene/heightmapterrain.h" @@ -590,7 +590,7 @@ void simulation::deer_herd::update(double const Deltatime) m_travelled = 0.0; return; } - auto const *mover{vehicle->MoverParameters}; + auto const *mover{vehicle->physics}; m_travelled += std::abs(mover->V) * Deltatime; if ((Global.deer_interval > 0.0) && (m_travelled >= Global.deer_interval)) { @@ -661,7 +661,7 @@ bool simulation::deer_herd::tend(deer &Animal, glm::dvec3 const &Train, double c bool simulation::deer_herd::spawn(TDynamicObject const &Vehicle) { // the end of the train the way it goes, or the cab occupied when it stands - auto const *mover{Vehicle.MoverParameters}; + auto const *mover{Vehicle.physics}; auto front{mover->V > 0.1}; if (std::abs(mover->V) <= 0.1) { From 5d6f4434504571f7be340967d59fab7951510ae9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 12:53:29 +0100 Subject: [PATCH 121/123] Review 28.11: rain cells always bound, the velocity target and the blur pass only when needed - the cells of the rain: the opengl renderer makes their storage (cleared) with the first bind and keeps it bound, the glasses read the cells only when they were worked out in the frame (scene_ubs.rain_state.w, both renderers): never the storage before the first rain, nor the stand-in of the vulkan renderer - the pass of the motion blur and (opengl) the velocities drawn only in the frames which need them: the motion blur with something moving, the taa, or a glass of the rain, the insects or the snow in the view (windscreen_water::wants_glass_requests(): the cab seen from inside has one, or the view is not from the cab). the glasses keep their drops and haze with the motion blur off, the motion is blurred by 0 then Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- gl/ubo.h | 3 ++- rendering/common/windscreenwater.cpp | 12 ++++++++++++ rendering/common/windscreenwater.h | 4 ++++ rendering/opengl46/opengl46renderer.cpp | 19 ++++++++++++++----- rendering/opengl46/opengl46water.cpp | 23 ++++++++++++++++------- rendering/opengl46/opengl46water.h | 14 ++++++++++++-- rendering/vulkan14/vulkan14frame.cpp | 16 +++++++++------- rendering/vulkan14/vulkan14water.cpp | 3 +++ rendering/vulkan14/vulkan14water.h | 7 +++++++ shaders/ogl46/common.glsl | 3 ++- shaders/ogl46/mat_rain_windscreen.frag | 4 +++- shaders/vk14/common.glsl | 3 ++- shaders/vk14/mat_rain_windscreen.frag | 4 +++- utilities/Globals.h | 6 ++++-- 14 files changed, 93 insertions(+), 28 deletions(-) diff --git a/gl/ubo.h b/gl/ubo.h index 859485db4..6ee7d5d9a 100644 --- a/gl/ubo.h +++ b/gl/ubo.h @@ -212,7 +212,8 @@ namespace gl glm::vec4 camera_lo; // the rain the glass meets (mat_rain_windscreen): x the rain fallen so far, in seconds of the heaviest rain standing still (more // at speed: the glass runs into it); y how wet the glass is, 0 dry .. 1 as full of drops as it gets (it fills with the rain, - // dries when it stops); z how fast the glass fills: the share left to fill goes down as exp(-z x the rain fallen); w unused + // dries when it stops); z how fast the glass fills: the share left to fill goes down as exp(-z x the rain fallen); w 1 when the + // cells of the rain (RAIN_CELLS_SSBO_BINDING) were worked out in this frame, 0 else: the glasses read them only then glm::vec4 rain_state; // the rain fallen (rain_state.x) when a blade last went over a place of its sweep: element b for the places b / 64 .. (b + 1) // / 64 of dWiperPos (the value of the wiper mask of a pixel), x .. w the blades (as wiper_pos); -1 not known. the drops and the diff --git a/rendering/common/windscreenwater.cpp b/rendering/common/windscreenwater.cpp index 610210ff0..35b58426b 100644 --- a/rendering/common/windscreenwater.cpp +++ b/rendering/common/windscreenwater.cpp @@ -21,6 +21,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationenvironment.h" #include "utilities/Globals.h" #include "utilities/Logs.h" +#include "utilities/utilities.h" #include "vehicle/DynObj.h" #include "vehicle/Train.h" #include "physics/vehicle.h" @@ -377,6 +378,17 @@ bool windscreen_water::wants_rain_cells() }); } +bool windscreen_water::wants_glass_requests() +{ + if ((m_state <= 0) || (false == bool(m_host.material)) || FreeFlyModeFlag || (false == Global.render_cab) || (simulation::Train == nullptr)) + return true; + // the glasses of the rain, of the insects and of the snow all have the atlas of the drops + return std::ranges::any_of(m_cabmaterials, [this](material_handle const Material) { + auto const *opengl{m_host.material(Material)}; + return (opengl != nullptr) && (opengl->shader != nullptr) && (opengl->shader->texture_conf.count("raindropsatlas") > 0); + }); +} + void windscreen_water::update(double const Seconds) { if (false == available()) diff --git a/rendering/common/windscreenwater.h b/rendering/common/windscreenwater.h index d614392d6..3d3470fe7 100644 --- a/rendering/common/windscreenwater.h +++ b/rendering/common/windscreenwater.h @@ -66,6 +66,10 @@ class windscreen_water // whether the glasses need the cells of the rain worked out: the cab of the train has a glass with drops, not of the snow (or // the simulation isn't used, the cab not looked at) bool wants_rain_cells(); + // whether a glass in the view may ask the post-processing for its drops and haze in the velocity target (mat_rain_windscreen, + // mat_bugs_windscreen, mat_snow_windscreen): the cab seen from inside has such a glass, or the view is not from the cab + // (the glasses of any vehicle may be seen then), or the cab isn't looked at + bool wants_glass_requests(); // the materials let go of their slots, the glasses forgotten (the storage stays as it is, unused) void release(); std::string info() const; diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index 362def0bc..cbe7da7c9 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -1749,7 +1749,8 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) m_glasswet += (1.0 - m_glasswet) * (1.0 - std::exp(-fill_rate * dt * meet)); else m_glasswet = 0.0; - scene_ubs.rain_state = glm::vec4{static_cast(m_wiperrain), static_cast(m_glasswet), static_cast(fill_rate), 0.f}; + // w: the cells of the rain worked out in this frame (set again once they are, below), the glasses read them only then + scene_ubs.rain_state = glm::vec4{static_cast(m_wiperrain), static_cast(m_glasswet), static_cast(fill_rate), m_windscreenwater.rain_cells_valid() ? 1.f : 0.f}; } if (owner != nullptr) { @@ -1815,6 +1816,13 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) // (the drops a cell may hold: as many as the glass is wet) // (none for a cab without a glass of the rain) m_windscreenwater.update_rain_cells(scene_ubs.time, ((scene_ubs.rain_state.y > 0.001f) && m_windscreenwater.wants_rain_cells()) ? std::min(scene_ubs.rain_state.y + 0.01f, 1.f) : 0.f); + // whether the glasses read the cells: as they are now + auto const cellsvalid{m_windscreenwater.rain_cells_valid() ? 1.f : 0.f}; + if (scene_ubs.rain_state.w != cellsvalid) + { + scene_ubs.rain_state.w = cellsvalid; + scene_ubo->update(scene_ubs); + } } m_windscreenwater.bind(); @@ -1887,15 +1895,16 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) auto const freecameramovement{(vp.main && (Global.pCamera.m_owner == nullptr)) ? m_freecamera.next_frame(Global.pCamera.Pos) : glm::vec3{0.f}}; // the motion is blurred only when something in the view moves: the vehicle of the camera, the camera with no vehicle of its // own, or a vehicle drawn in the last frame (a vehicle setting off is blurred from its second frame, when its velocity is - // still far below a pixel). the pass itself runs in every frame: the windscreens (mat_rain_windscreen, mat_bugs_windscreen) - // ask it in the velocity target for the picture in their drops and the haze, also standing still, with the motion blur off - // and with any anti-aliasing (the motion is then blurred by 0) + // still far below a pixel). the pass itself runs also when a glass in the view may ask it in the velocity target for the + // picture in its drops and its haze (mat_rain_windscreen, mat_bugs_windscreen, mat_snow_windscreen), standing still, with the + // motion blur off and with any anti-aliasing: the motion is then blurred by 0. with neither the velocities aren't drawn + // (but for the taa), the pass is left out auto const moving{ Global.gfx_postfx_motionblur_enabled && (m_vehiclesmoved || (freecameramovement != glm::vec3{0.f}) || ((Global.pCamera.m_owner != nullptr) && (Global.pCamera.m_owner->get_future_movement() != glm::dvec3{0.0})))}; - auto const motionblur{Global.gfx_motion_vectors() && (vp.main_texv != nullptr)}; + auto const motionblur{Global.gfx_motion_vectors() && (vp.main_texv != nullptr) && (moving || m_windscreenwater.wants_glass_requests())}; if (!Global.gfx_skippipeline) { diff --git a/rendering/opengl46/opengl46water.cpp b/rendering/opengl46/opengl46water.cpp index 50d692c08..980e779df 100644 --- a/rendering/opengl46/opengl46water.cpp +++ b/rendering/opengl46/opengl46water.cpp @@ -73,7 +73,7 @@ bool opengl46_windscreen_water::make_program(std::size_t const Index) } } -// the program of the cells of the rain (rain_cells.comp) made, once; its storage waits for the first rain (update_rain_cells()) +// the program of the cells of the rain (rain_cells.comp) made, once; its storage is made with the first bind() void opengl46_windscreen_water::make_rain_cells_program() { if (m_raincelltried) @@ -129,24 +129,32 @@ bool opengl46_windscreen_water::gpu_init() return true; } -void opengl46_windscreen_water::bind() const +void opengl46_windscreen_water::make_rain_cells_storage() +{ + if (m_raincells) + return; + m_raincells = std::make_unique(static_cast(gl::RAIN_CELLS_COUNT * 16), gl::RAIN_CELLS_SSBO_BINDING); + ::glClearNamedBufferData(*m_raincells, GL_R32UI, GL_RED_INTEGER, GL_UNSIGNED_INT, nullptr); +} + +void opengl46_windscreen_water::bind() { if (m_storage) m_storage->bind_base(); - if (m_raincells) - m_raincells->bind_base(); + // the glasses of the rain always find the cells at their point (they read them only when worked out in the frame) + make_rain_cells_storage(); + m_raincells->bind_base(); } void opengl46_windscreen_water::update_rain_cells(float const Time, float const Rain) { + m_raincellsvalid = false; if (Rain <= 0.f) return; make_rain_cells_program(); if (!m_raincellprogram) return; - // the storage of the cells made at the first rain - if (!m_raincells) - m_raincells = std::make_unique(static_cast(gl::RAIN_CELLS_COUNT * 16), gl::RAIN_CELLS_SSBO_BINDING); + make_rain_cells_storage(); // the glasses of the frame before read the cells, this one writes them ::glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); m_raincells->bind_base(); @@ -161,6 +169,7 @@ void opengl46_windscreen_water::update_rain_cells(float const Time, float const m_raincellprogram->dispatch(groups(gl::RAIN_CELLS_COUNT - gl::RAIN_MASK_BASE)); ::glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); gl::program::unbind(); + m_raincellsvalid = true; } void opengl46_windscreen_water::gpu_setup(std::size_t const Slot, std::vector const &Axes) diff --git a/rendering/opengl46/opengl46water.h b/rendering/opengl46/opengl46water.h index f0c33d08e..db914fb93 100644 --- a/rendering/opengl46/opengl46water.h +++ b/rendering/opengl46/opengl46water.h @@ -25,11 +25,18 @@ class opengl46_windscreen_water : public gfx::windscreen_water opengl46_windscreen_water() = default; ~opengl46_windscreen_water() override = default; - // the storage bound to its point for the glasses drawn next (the bindings are kept by every context of its own) - void bind() const; + // the storage bound to its point for the glasses drawn next (the bindings are kept by every context of its own). the cells + // of the rain are always there and bound, made at the first call + void bind(); // the drops and the rivulets of the cells of the glasses with rain (mat_rain_windscreen, rain_cells.comp) worked out for the // time of the frame (scene_ubs.time), once a frame before the passes; nothing while it doesn't rain void update_rain_cells(float Time, float Rain); + // whether the cells were worked out in this frame (the last update_rain_cells()): only then the glasses read them + // (scene_ubs.rain_state.w) + bool rain_cells_valid() const + { + return m_raincellsvalid; + } // the next of the programs of the simulation compiled ahead of its first step (a few seconds each where the driver has none // of them kept, at the first start of a new version), so the loading screen stays while they're made. false once all are bool prepare_next(); @@ -65,8 +72,11 @@ class opengl46_windscreen_water : public gfx::windscreen_water std::unique_ptr m_raincellprogram; std::unique_ptr m_raincells; bool m_raincelltried{false}; + bool m_raincellsvalid{false}; // the cells worked out in this frame bool m_nosnow{false}; // a pass of the snow didn't compile: the snow is left out bool make_program(std::size_t Index); void make_rain_cells_program(); + // the storage of the cells made, once, cleared + void make_rain_cells_storage(); }; diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index 0806e94c6..1b66ce0be 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -393,7 +393,7 @@ bool make_targets(vk14::allocator &Memory, vk14::deletion_queue &Deletions, std: { ok = ok && make(Targets.motion_image, velocity, sampledcolour, VK_SAMPLE_COUNT_1_BIT, "scene velocity"); } - // the pass of the motion blur runs in every frame: the windscreens ask it for their drops and haze (see render_post()) + // the pass of the motion blur runs also without the motion blur: the windscreens ask it for their drops and haze (see render_post()) if (motion) { ok = ok && make(Targets.blurred, hdr, sampledcolour, VK_SAMPLE_COUNT_1_BIT, "motion blurred", outputextent); @@ -1622,7 +1622,8 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) m_glasswet += (1.0 - m_glasswet) * (1.0 - std::exp(-fill_rate * dt * meet)); else m_glasswet = 0.0; - scene_ubs.rain_state = glm::vec4{static_cast(m_wiperrain), static_cast(m_glasswet), static_cast(fill_rate), 0.f}; + // w: the cells of the rain worked out in this frame (render_scene(), before the viewports), the glasses read them only then + scene_ubs.rain_state = glm::vec4{static_cast(m_wiperrain), static_cast(m_glasswet), static_cast(fill_rate), scene.water.rain_cells_valid() ? 1.f : 0.f}; } if (owner != nullptr) { @@ -1733,7 +1734,8 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) if (vp.main && (Global.pCamera.m_owner != nullptr)) m_freecamera.reset(); auto const freecameramovement{(vp.main && (Global.pCamera.m_owner == nullptr)) ? m_freecamera.next_frame(Global.pCamera.Pos) : glm::vec3{0.f}}; - // the motion blurred only when something in the view moves (see opengl46_renderer::Render_pass()); the pass runs anyway + // the motion blurred only when something in the view moves (see opengl46_renderer::Render_pass()); the pass runs also for the + // glasses which ask it (render_post()) auto const motionblur{Global.gfx_postfx_motionblur_enabled && targets.motion && (m_vehiclesmoved || (freecameramovement != glm::vec3{0.f}) || ((Global.pCamera.m_owner != nullptr) && (Global.pCamera.m_owner->get_future_movement() != glm::dvec3{0.0})))}; @@ -3872,10 +3874,10 @@ void vulkan14_renderer::render_post(std::size_t const Index, bool const Motionbl store_ssr_history(Index, *hdr); } m_ssrframe = false; - // the pass of the motion blur in every frame: the windscreens (mat_rain_windscreen, mat_bugs_windscreen) ask it in the velocity - // target for the picture in their drops and the haze, also standing still, with the motion blur off and with any anti-aliasing. - // the motion is blurred only with Motionblur (by 0 otherwise) - if (targets.blurred && targets.motion_image) + // the pass of the motion blur: with Motionblur, and also when a glass in the view may ask it in the velocity target for the + // picture in its drops and its haze (mat_rain_windscreen, mat_bugs_windscreen, mat_snow_windscreen), standing still, with the + // motion blur off and with any anti-aliasing. the motion is blurred only with Motionblur (by 0 otherwise) + if (targets.blurred && targets.motion_image && (Motionblur || ctx.scene.water.wants_glass_requests())) { vk14::draw_constants constants; constants.data[0].x = Motionblur ? m_framerate / (1.0 / Global.gfx_postfx_motionblur_shutter) : 0.0; diff --git a/rendering/vulkan14/vulkan14water.cpp b/rendering/vulkan14/vulkan14water.cpp index 4ab057eb6..61910c0f7 100644 --- a/rendering/vulkan14/vulkan14water.cpp +++ b/rendering/vulkan14/vulkan14water.cpp @@ -95,6 +95,7 @@ void windscreen_water::destroy() m_raincellkernel.destroy(m_device); m_raincelltried = false; m_raincellsfull = false; + m_raincellsvalid = false; m_raincells.reset(); m_storage.reset(); m_device = VK_NULL_HANDLE; @@ -209,6 +210,7 @@ void windscreen_water::gpu_setup(std::size_t const Slot, std::vector void windscreen_water::update_rain_cells(float const Time, float const Rain) { + m_raincellsvalid = false; if ((m_device == VK_NULL_HANDLE) || (false == bool(m_raincells)) || (false == m_raincellsfull) || (Rain <= 0.f) || (false == bool(m_host.commands))) { return; @@ -254,6 +256,7 @@ void windscreen_water::update_rain_cells(float const Time, float const Rain) compute_barrier(commands); m_raincellkernel.dispatch(commands, descriptors, constants{Time, Rain, 1, 0.f}, groups(gl::RAIN_CELLS_COUNT - gl::RAIN_MASK_BASE)); compute_barrier(commands); + m_raincellsvalid = true; } ring_slice windscreen_water::block(gl::water_ubs const &Block) diff --git a/rendering/vulkan14/vulkan14water.h b/rendering/vulkan14/vulkan14water.h index cc9f7f7ef..1673419c0 100644 --- a/rendering/vulkan14/vulkan14water.h +++ b/rendering/vulkan14/vulkan14water.h @@ -58,6 +58,12 @@ class windscreen_water : public gfx::windscreen_water // the cells worked out for the time of the frame (the time of the block of the scene), with the commands of the frame before // its passes; nothing while it doesn't rain void update_rain_cells(float Time, float Rain); + // whether the cells were worked out in this frame (the last update_rain_cells()): only then the glasses read them + // (scene_ubs.rain_state.w). never with the stand-in of the storage, which is too small for them + bool rain_cells_valid() const + { + return m_raincellsvalid; + } protected: bool gpu_init() override; @@ -104,6 +110,7 @@ class windscreen_water : public gfx::windscreen_water compute_kernel m_raincellkernel; bool m_raincelltried{false}; bool m_raincellsfull{false}; // the cells of the rain have their storage (else a stand-in: the glasses with rain stay dry) + bool m_raincellsvalid{false}; // the cells worked out in this frame bool m_full{false}; // the storage is as large as the simulation needs (else a stand-in, the glasses make their water up) bool m_cleared{false}; bool m_snowkernels{true}; // the passes of the snow made (they are optional: without them the glasses of the snow stay clear) diff --git a/shaders/ogl46/common.glsl b/shaders/ogl46/common.glsl index f2193e498..0e727e3a1 100644 --- a/shaders/ogl46/common.glsl +++ b/shaders/ogl46/common.glsl @@ -385,7 +385,8 @@ layout(std140, binding = SCENE_UBO_BINDING) uniform scene_ubo // the place of the camera of the pass in the world (whole 64 m, the rest), see gl::scene_ubs vec4 camera_hi; vec4 camera_lo; - // the rain the glass meets: x fallen so far, y how wet the glass is, z how fast it fills (mat_rain_windscreen), see gl::scene_ubs + // the rain the glass meets: x fallen so far, y how wet the glass is, z how fast it fills, w 1 with the cells of the rain + // worked out in this frame (mat_rain_windscreen), see gl::scene_ubs vec4 rain_state; // the rain fallen when a blade last went over a place of its sweep (the wiper mask / 64), see gl::scene_ubs vec4 wiper_rain_pass[WIPER_PASS_BUCKETS]; diff --git a/shaders/ogl46/mat_rain_windscreen.frag b/shaders/ogl46/mat_rain_windscreen.frag index 9846a6a0f..903b81f23 100644 --- a/shaders/ogl46/mat_rain_windscreen.frag +++ b/shaders/ogl46/mat_rain_windscreen.frag @@ -711,7 +711,9 @@ void main() vec2 sCell = floor(sUVl / vec2(sCW, sCH)); bool sweepOn = streak_sweep > 0.0 && streak_density > 0.0 && (wind_streaks > 0.0 || wsWindShare < 1.0) && (WS_PROFILE != 2); - if ((rain_state.y > 0.001) && (WS_PROFILE != 5)) + // the cells (rain_cells) are read only when worked out in this frame (rain_state.w): before the first rain, or without their + // storage, there is nothing in them + if ((rain_state.y > 0.001) && (rain_state.w > 0.5) && (WS_PROFILE != 5)) { // =================================================================== // 1. drops from the atlas: this cell and its 8 neighbours diff --git a/shaders/vk14/common.glsl b/shaders/vk14/common.glsl index fd55c939e..6c0884dc1 100644 --- a/shaders/vk14/common.glsl +++ b/shaders/vk14/common.glsl @@ -345,7 +345,8 @@ layout(std140, set = PASS_SET, binding = SCENE_UBO) uniform scene_ubo // the place of the camera of the pass in the world (whole 64 m, the rest), see gl::scene_ubs vec4 camera_hi; vec4 camera_lo; - // the rain the glass meets: x fallen so far, y how wet the glass is, z how fast it fills (mat_rain_windscreen), see gl::scene_ubs + // the rain the glass meets: x fallen so far, y how wet the glass is, z how fast it fills, w 1 with the cells of the rain + // worked out in this frame (mat_rain_windscreen), see gl::scene_ubs vec4 rain_state; // the rain fallen when a blade last went over a place of its sweep (the wiper mask / 64), see gl::scene_ubs vec4 wiper_rain_pass[WIPER_PASS_BUCKETS]; diff --git a/shaders/vk14/mat_rain_windscreen.frag b/shaders/vk14/mat_rain_windscreen.frag index 85aba95e8..78e20679d 100644 --- a/shaders/vk14/mat_rain_windscreen.frag +++ b/shaders/vk14/mat_rain_windscreen.frag @@ -716,7 +716,9 @@ void main() vec2 sCell = floor(sUVl / vec2(sCW, sCH)); bool sweepOn = streak_sweep > 0.0 && streak_density > 0.0 && (wind_streaks > 0.0 || wsWindShare < 1.0) && (WS_PROFILE != 2); - if ((rain_state.y > 0.001) && (WS_PROFILE != 5)) + // the cells (rain_cells) are read only when worked out in this frame (rain_state.w): before the first rain, or without their + // storage, there is nothing in them + if ((rain_state.y > 0.001) && (rain_state.w > 0.5) && (WS_PROFILE != 5)) { // =================================================================== // 1. drops from the atlas: this cell and its 8 neighbours diff --git a/utilities/Globals.h b/utilities/Globals.h index 699d4990c..d8ed3e13e 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -488,8 +488,10 @@ struct global_settings { bool gfx_bufferstreaming = true; bool gfx_postfx_motionblur_enabled = true; // the colour pass writes the velocities of the pixels: for the motion blur, the temporal anti-aliasing or dlss - // the velocity target is always drawn: the windscreens (mat_rain_windscreen, mat_bugs_windscreen) send the post-processing their - // drops and haze through it, whatever the motion blur and the anti-aliasing (not without the pipeline: no post-processing there) + // the velocity target is there also without them: the windscreens (mat_rain_windscreen, mat_bugs_windscreen, mat_snow_windscreen) + // send the post-processing their drops and haze through it (not without the pipeline: no post-processing there). the renderers + // draw it and run the pass of the motion blur only in the frames which need it: with something moving and the motion blur on, + // with the anti-aliasing which takes it, or with a glass of the kind in the view (windscreen_water::wants_glass_requests()) bool gfx_motion_vectors() const { return ( false == gfx_skippipeline ) || gfx_postfx_motionblur_enabled; } float gfx_postfx_motionblur_shutter = 0.01f; GLenum gfx_postfx_motionblur_format = GL_RG16F; From 7cea551157a5d15016154ae0179f4aedffa6c1ca Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 12:52:56 +0100 Subject: [PATCH 122/123] Wipers and insects: the views from outside the cab follow the train driven The new views of the consist put the camera at any vehicle of the train, one with an active cab of its own too: taken for another vehicle, it wiped the insects met and the memory of the blades, so the insects were gone from the glass after a change of the view. Outside the cab (FreeFlyModeFlag) the glasses now follow the train driven, in both renderers. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- rendering/opengl46/opengl46renderer.cpp | 6 ++++-- rendering/vulkan14/vulkan14frame.cpp | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index cbe7da7c9..bd510fe36 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -1700,8 +1700,10 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) } // the wipers of the vehicle the camera is in, or of the train driven when the camera is outside it: the moments the blades // were at the ends of their sweep (the drops on the glass come back from then) are kept while the camera is away, so the glass - // looks as the blades left it when it's back in the cab. they're forgotten only for another vehicle - TDynamicObject const *owner = Global.pCamera.m_owner; + // looks as the blades left it when it's back in the cab. they're forgotten only for another vehicle. the views from outside + // (freefly, the views of the consist) put the camera at any vehicle of the train, one with an active cab of its own too: they + // follow the train driven, so going round them doesn't wipe the insects and the memory of the blades + TDynamicObject const *owner = FreeFlyModeFlag ? nullptr : Global.pCamera.m_owner; if ((owner == nullptr) || (owner->physics->CabActive == 0)) owner = (simulation::Train != nullptr) ? simulation::Train->Dynamic() : nullptr; if (owner != m_wipervehicle) diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index 1b66ce0be..7f91c41b7 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -1573,8 +1573,10 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) } // the wipers of the vehicle the camera is in, or of the train driven when the camera is outside it: the moments the blades // were at the ends of their sweep (the drops on the glass come back from then) are kept while the camera is away, so the glass - // looks as the blades left it when it's back in the cab. they're forgotten only for another vehicle - TDynamicObject const *owner = Global.pCamera.m_owner; + // looks as the blades left it when it's back in the cab. they're forgotten only for another vehicle. the views from outside + // (freefly, the views of the consist) put the camera at any vehicle of the train, one with an active cab of its own too: they + // follow the train driven, so going round them doesn't wipe the insects and the memory of the blades + TDynamicObject const *owner = FreeFlyModeFlag ? nullptr : Global.pCamera.m_owner; if ((owner == nullptr) || (owner->physics->CabActive == 0)) owner = (simulation::Train != nullptr) ? simulation::Train->Dynamic() : nullptr; if (owner != m_wipervehicle) From 231bd3eb845513c2cc2410a5c6f26390251c4071 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 12:52:56 +0100 Subject: [PATCH 123/123] Bugs: the big and the huge ones smaller (2.5x and 5x the normal ones, were 4x and 9x) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BqfRrTiBDaAyQ2gT6ZrnZD --- shaders/ogl46/mat_bugs_windscreen.frag | 4 ++-- shaders/vk14/mat_bugs_windscreen.frag | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/shaders/ogl46/mat_bugs_windscreen.frag b/shaders/ogl46/mat_bugs_windscreen.frag index 081d81c7d..caeaa2f09 100644 --- a/shaders/ogl46/mat_bugs_windscreen.frag +++ b/shaders/ogl46/mat_bugs_windscreen.frag @@ -108,9 +108,9 @@ const float bugs_halo_size = 1.15; // ring radius = bug half-size * this (1 = const float bugs_halo_px = 60.0; // a bug this many pixels wide on screen gets the full blur, smaller ones less (the blur radius is fixed in pixels) const float bugs_vertical = 0.0; // -1..1: more dirt at the bottom (<0) or at the top (>0) of the pane, 0 = even const float bugs_giant_density = 0.015; // share of the coarse cells that end up with a really big bug (0 = off) -const float bugs_giant_scale = 4.0; // how much bigger the big ones are (the coarse grid is this many times coarser) +const float bugs_giant_scale = 2.5; // how much bigger the big ones are (the coarse grid is this many times coarser) const float bugs_huge_density = 0.02; // share of the very coarse cells with a huge bug: about one per pane when fully dirty (0 = off) -const float bugs_huge_scale = 9.0; // how much bigger the huge ones are than the normal bugs +const float bugs_huge_scale = 5.0; // how much bigger the huge ones are than the normal bugs const float specks_size = 0.30; // size of the fine specks, in speck cells (0.1 .. 0.45) const float specks_opacity = 0.55; // how much a speck covers the glass diff --git a/shaders/vk14/mat_bugs_windscreen.frag b/shaders/vk14/mat_bugs_windscreen.frag index fc0396286..c3b7470de 100644 --- a/shaders/vk14/mat_bugs_windscreen.frag +++ b/shaders/vk14/mat_bugs_windscreen.frag @@ -113,9 +113,9 @@ const float bugs_halo_size = 1.15; // ring radius = bug half-size * this (1 = const float bugs_halo_px = 60.0; // a bug this many pixels wide on screen gets the full blur, smaller ones less (the blur radius is fixed in pixels) const float bugs_vertical = 0.0; // -1..1: more dirt at the bottom (<0) or at the top (>0) of the pane, 0 = even const float bugs_giant_density = 0.015; // share of the coarse cells that end up with a really big bug (0 = off) -const float bugs_giant_scale = 4.0; // how much bigger the big ones are (the coarse grid is this many times coarser) +const float bugs_giant_scale = 2.5; // how much bigger the big ones are (the coarse grid is this many times coarser) const float bugs_huge_density = 0.02; // share of the very coarse cells with a huge bug: about one per pane when fully dirty (0 = off) -const float bugs_huge_scale = 9.0; // how much bigger the huge ones are than the normal bugs +const float bugs_huge_scale = 5.0; // how much bigger the huge ones are than the normal bugs const float specks_size = 0.30; // size of the fine specks, in speck cells (0.1 .. 0.45) const float specks_opacity = 0.55; // how much a speck covers the glass